output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def get_many(self, type: Type[T], query: Mapping[str, Any], streaming: bool = False) -> Iterable[T]: """Gets a query from the data pipeline, which contains a request for multiple objects. 1) Extracts the query the sequence of data sources. 2) Inserts the results into the data sinks (if appropri...
Write a Python 3 script for getting a query from the data pipeline which contains a request for multiple objects.
You are a Python code analyst, evaluating scripts for potential improvements.
Puts an object into the data pipeline.
Given the following Python 3 function, write the documentation def put(self, type: Type[T], item: T) -> None: LOGGER.info("Getting SinkHandlers for \"{type}\"".format(type=type.__name__)) try: handlers = self._put_types[type] except KeyError: try: LOGGER.i...
You are a Python code architect, reviewing and designing scalable and efficient code
def put_many(self, type: Type[T], items: Iterable[T]) -> None: """Puts multiple objects of the same type into the data sink. The objects may be transformed into a new type for insertion if necessary. Args: items: An iterable (e.g. list) of objects to be inserted into the data pipeline. ...
Write a Python 3 script to put multiple objects of the same type into the data sink.
As a Python code analyst, you investigate and solve complex coding mysteries
Print the error message for the current test.
Can you tell what is the following Python 3 function doing def print_error(self, wrapper): level = 0 parent = wrapper.parent while parent: print_test_msg(parent.name, level, TestStatus.FAIL, self.use_color) level += 1 parent = parent.parent print_test...
You are a Python code generator, capable of creating scripts from specifications.
Refracts the given value.
Can you generate the documentation for the following Python 3 function def refract(structure) -> Element: if isinstance(structure, Element): return structure elif isinstance(structure, str): return String(content=structure) elif isinstance(structure, bool): return Boolean(content=st...
As a Python code analyst, you investigate and solve complex coding mysteries
Serialises the given element into JSON.
How would you explain what the following Python 3 function does def serialise(self, element: Element, **kwargs) -> str: return json.dumps(self.serialise_dict(element), **kwargs)
As a Python code composer, you craft elegant and concise scripts.
def serialise(self, element: Element) -> str: """ Serialises the given element into Compact JSON. >>> CompactJSONSerialiser().serialise(String(content='Hello')) '["string", null, null, "Hello"]' """ return json.dumps(self.serialise_element(element))
Implement a function in Python 3 to serialise the given element into Compact JSON.
As a Python code composer, you craft elegant and concise scripts.
Deserialises the given compact JSON into an element.
Given the following Python 3 function, write the documentation def deserialise(self, content) -> Element: content = json.loads(content) if not isinstance(content, list): raise ValueError('Given content was not compact JSON refract') return self.deserialise_element(content)
As a Python code translator, you convert algorithms and pseudocode into Python.
The available data transformers.
Can you generate the documentation for the following Python 3 function def transforms(self) -> Mapping[Type, Iterable[Type]]: try: return getattr(self.__class__, "transform")._transforms except AttributeError: return {}
You are a Python code analyst, evaluating scripts for potential improvements.
def transform(self, target_type: Type[T], value: F, context: PipelineContext = None) -> T: """Transforms an object to a new type. Args: target_type: The type to be converted to. value: The object to be transformed. context: The context of the transformation (mutable)...
Implement a Python 3 function for transforming an object to a new type.
You are a Python code architect, reviewing and designing scalable and efficient code
def serialize(self): """ Serializes the CaseWrapper object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed. """ expects = [exp.serialize() for exp in self.expects] ...
Can you create a Python 3 function that serializes the CaseWrapper object for collection.
As a Python code translator, you convert algorithms and pseudocode into Python.
def serialize(self): """ Serializes the Spec/Describe object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed. """ cases = [case.serialize() for key, case in six.iterit...
Create a Python 3 function to serialize the Spec / Describe object for collection.
You are a Python code analyst, evaluating scripts for potential improvements.
def _run_hooks(self): """Calls any registered hooks providing the current state.""" for hook in self.hooks: getattr(self, hook)(self._state)
Write a Python 3 function that can call any registered hooks providing the current state.
As a python code expert, you are capable of creating scripts from specifications.
Append an element onto the array.
Here you have a function in Python 3, explain what it does def append(self, element): from refract.refraction import refract self.content.append(refract(element))
You are a Python code generator, capable of creating scripts from specifications.
def insert(self, index: int, element): """ Insert an element at a given position. >>> array = Array() >>> array.insert(0, Element()) """ from refract.refraction import refract self.content.insert(index, refract(element))
Write a Python 3 script to insert an element at a given position.
As a python code expert, you are capable of creating scripts from specifications.
Return the index in the array of the first item whose value is element.
Explain what the following Python 3 code does def index(self, element: Element) -> int: from refract.refraction import refract return self.content.index(refract(element))
As a Python code translator, you convert algorithms and pseudocode into Python.
Gets a query from the data source.
Explain what the following Python 3 code does def get(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> T: pass
You are a Python code analyst, evaluating scripts for potential improvements.
Gets a query from the data source which contains a request for multiple objects.
Make a summary of the following Python 3 code def get_many(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> Iterable[T]: pass
As a python code expert, you are capable of creating scripts from specifications.
Subscribe all the available reporters to a spec.
Here you have a function in Python 3, explain what it does def subscribe_all_to_spec(self, spec): for reporter in self.reporters: if self.can_use_reporter(reporter, self.parallel): reporter.subscribe_to_spec(spec)
As a Python code analyst, you investigate and solve complex coding mysteries
Alias for print_indent_msg with color determined by status.
Here you have a function in Python 3, explain what it does def output(self, msg, indent, status=None): color = None if self.use_color: color = get_color_from_status(status) print_indent_msg(msg, indent, color)
As a Python code analyst, you investigate and solve complex coding mysteries
def assets(self) -> List[Asset]: """ Returns the assets in the transaction. """ return list(filter(is_element(Asset), self.content))
Write a Python 3 function that can return the assets in the transaction.
As a Python code composer, you craft elegant and concise scripts.
def write_expression_list(self, nodes, separator=', ', allow_newlines=True, need_parens=True, final_separator_if_multiline=True): """Writes a list of nodes, separated by separator. If allow_newlines, will write the expression over multiple lines if necessary to say within ...
Implement a function in Python 3 to write a list of nodes separated by separator.
As a python code expert, you are capable of creating scripts from specifications.
def defract(self): """ Returns the underlying (unrefracted) value of element >>> Element(content='Hello').defract 'Hello' >>> Element(content=Element(content='Hello')).defract 'Hello' >>> Element(content=[Element(content='Hello')]).defract ['Hello'] ...
Write a Python 3 script for returning the underlying ( unrefracted ) value of element
As a Python code composer, you craft elegant and concise scripts.
def children(self): """ Returns all of the children elements. """ if isinstance(self.content, list): return self.content elif isinstance(self.content, Element): return [self.content] else: return []
Can you create a Python 3 function that returns all of the children elements.
As a python code expert, you are capable of creating scripts from specifications.
Generator returning all recursive children elements.
How would you explain what the following Python 3 function does def recursive_children(self): for child in self.children: yield child for recursive_child in child.recursive_children: yield recursive_child
As a Python code translator, you convert algorithms and pseudocode into Python.
This method creates a ExpectAssert object that will be passed to the expect method.
Can you generate a brief explanation for the following Python 3 code def expect(obj, caller_args=[]): line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) expect_obj = ExpectAssert( obj, src_params=src_params, caller_args=caller_args ) _add_...
As a python code expert, you are capable of creating scripts from specifications.
This method creates a RequireAssert object that will be used to test assertions in the Specter .
Can you generate a brief explanation for the following Python 3 code def require(obj, caller_args=[]): line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) require_obj = RequireAssert( obj, src_params=src_params, caller_args=caller_args ) _a...
You are a Python code architect, reviewing and designing scalable and efficient code
Decorator for test functions that will always bypass a test.
How would you explain what the following Python 3 function does def skip(reason): def decorator(test_func): if not isinstance(test_func, (type, ClassObjType)): func_data = None if test_func.__name__ == 'DECORATOR_ONCALL': # Call down and save the results ...
As a python code expert, you are capable of creating scripts from specifications.
Decorator that makes test_func skip if the test is marked as incomplete.
Can you generate a brief explanation for the following Python 3 code def incomplete(test_func): if not isinstance(test_func, (type, ClassObjType)): @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): raise TestIncompleteException(test_func, _('Test is incomplete')) ret...
You are a Python code analyst, evaluating scripts for potential improvements.
def serialize(self): """Serializes the ExpectAssert object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed. """ converted_dict = { 'success': self.success, ...
How would you code a function in Python 3 to serialize the ExpectAssert object for collection.
You are a Python code generator, capable of creating scripts from specifications.
def put_many(self, type: Type[T], items: Iterable[T], context: PipelineContext = None) -> None: """Puts multiple objects of the same type into the data sink. Args: type: The type of the objects being inserted. items: The objects to be inserted. context: The context o...
Create a Python 3 function to put multiple objects of the same type into the data sink.
As a Python code analyst, you investigate and solve complex coding mysteries
Open a file in the specified mode.
Can you generate a brief explanation for the following Python 3 code def open(filename, mode="rb", format = None): if format == "auto" or format == None: format = detect_format(filename) if format == "warc": return WARCFile(filename, mode) elif format == "arc": return ARCFile(filena...
As a python code expert, you are capable of creating scripts from specifications.
def init_defaults(self): """Initializes important headers to default values, if not already specified. The WARC-Record-ID header is set to a newly generated UUID. The WARC-Date header is set to the current datetime. The Content-Type is set based on the WARC-Type header. ...
Can you implement a function in Python 3 that initializes important headers to default values if not already specified.
You are a Python code generator, capable of creating scripts from specifications.
Writes this header to a file f.
Here you have a function in Python 3, explain what it does def write_to(self, f): f.write(self.version + "\r\n") for name, value in self.items(): name = name.title() # Use standard forms for commonly used patterns name = name.replace("Warc-", "WARC-").replace("-Ip-", ...
You are a Python code generator, capable of creating scripts from specifications.
Creates a WARCRecord object from a given httplib. HTTPResponse object.
How would you explain what the following Python 3 function does def from_response(response): # Get the httplib.HTTPResponse object http_response = response.raw._original_response # HTTP status line, headers and body as strings status_line = "HTTP/1.1 %d %s" % (http_response.stat...
You are a Python code architect, reviewing and designing scalable and efficient code
def write_record(self, warc_record): """Adds a warc record to this WARC file. """ warc_record.write_to(self.fileobj) # Each warc record is written as separate member in the gzip file # so that each record can be read independetly. if isinstance(self.fileobj, gzip2.GzipFil...
How would you implement a function in Python 3 that adds a warc record to this WARC file.
You are a Python code generator, capable of creating scripts from specifications.
Returns the file offset.
Make a summary of the following Python 3 code def tell(self): if isinstance(self.fileobj, gzip2.GzipFile): return self.fileobj.fileobj.tell() else: return self.fileobj.tell()
As a Python code composer, you craft elegant and concise scripts.
def close_member(self): """Closes the current member being written. """ # The new member is not yet started, no need to close if self._new_member: return self.fileobj.write(self.compress.flush()) write32u(self.fileobj, self.crc) # self.siz...
Write a Python 3 function for closing the current member being written.
You are a Python code generator, capable of creating scripts from specifications.
def _start_member(self): """Starts writing a new member if required. """ if self._new_member: self._init_write(self.name) self._write_gzip_header() self._new_member = False
Implement a Python 3 function for starting writing a new member if required.
As a Python code translator, you convert algorithms and pseudocode into Python.
Closes the gzip with care to handle multiple members.
Here you have a function in Python 3, explain what it does def close(self): if self.fileobj is None: return if self.mode == WRITE: self.close_member() self.fileobj = None elif self.mode == READ: self.fileobj = None if self.myfi...
You are a Python code generator, capable of creating scripts from specifications.
Returns a file - like object to read one member from the gzip file.
Can you generate the documentation for the following Python 3 function def read_member(self): if self._member_lock is False: self._member_lock = True if self._new_member: try: # Read one byte to move to the next member BaseGzipFile._read(self, 1) ...
As a Python code composer, you craft elegant and concise scripts.
def write_member(self, data): """Writes the given data as one gzip member. The data can be a string, an iterator that gives strings or a file-like object. """ if isinstance(data, basestring): self.write(data) else: for text in data: ...
Can you implement a function in Python 3 that writes the given data as one gzip member.
You are a Python code analyst, evaluating scripts for potential improvements.
Writes out the arc header to the file like object f.
How would you explain what the following Python 3 function does def write_to(self, f, version = None): if not version: version = self.version if version == 1: header = "%(url)s %(ip_address)s %(date)s %(content_type)s %(length)s" elif version == 2: header = "%...
As a Python code composer, you craft elegant and concise scripts.
def from_string(cls, string, version): """ Constructs an ARC record from a string and returns it. TODO: It might be best to merge this with the _read_arc_record function rather than reimplement the functionality here. """ header, payload = string.split("\n",1) ...
Can you write a function in Python 3 where it constructs an ARC record from a string and returns it.
As a Python code composer, you craft elegant and concise scripts.
def _write_header(self): "Writes out an ARC header" if "org" not in self.file_headers: warnings.warn("Using 'unknown' for Archiving organisation name") self.file_headers['org'] = "Unknown" if "date" not in self.file_headers: now = datetime.datetime.utcnow() ...
Create a Python 3 function for writing out an ARC header
You are a Python code architect, reviewing and designing scalable and efficient code
Writes out the given arc record to the file
Explain what the following Python 3 code does def write(self, arc_record): "Writes out the given arc record to the file" if not self.version: self.version = 2 if not self.header_written: self.header_written = True self._write_header() arc_record.write_...
As a Python code composer, you craft elegant and concise scripts.
Reads out the file header for the ARC file.
Make a summary of the following Python 3 code def _read_file_header(self): header = self.fileobj.readline() payload1 = self.fileobj.readline() payload2 = self.fileobj.readline() version, reserved, organisation = payload1.split(None, 2) self.fileobj.readline() # Lose the separator...
As a python code expert, you are capable of creating scripts from specifications.
def _read_arc_record(self): "Reads out an arc record, formats it and returns it" #XXX:Noufal Stream payload here rather than just read it # r = self.fileobj.readline() # Drop the initial newline # if r == "": # return None # header = self.fileobj.readline() #...
Implement a function in Python 3 to read out an arc record formats it and returns it
As a Python code translator, you convert algorithms and pseudocode into Python.
def from_bank_code(cls, country_code, bank_code): """Create a new BIC object from country- and bank-code. Examples: >>> bic = BIC.from_bank_code('DE', '20070000') >>> bic.country_code 'DE' >>> bic.bank_code 'DEUT' >>> bic.location_...
Can you write a function in Python 3 where it creates a new BIC object from country - and bank - code.
As a Python code analyst, you investigate and solve complex coding mysteries
Generate an IBAN from it s components.
Can you tell what is the following Python 3 function doing def generate(cls, country_code, bank_code, account_code): spec = _get_iban_spec(country_code) bank_code_length = code_length(spec, 'bank_code') branch_code_length = code_length(spec, 'branch_code') bank_and_branch_code_length = b...
As a Python code analyst, you investigate and solve complex coding mysteries
str : The IBAN formatted in blocks of 4 digits.
Make a summary of the following Python 3 code def formatted(self): return ' '.join(self.compact[i:i + 4] for i in range(0, len(self.compact), 4))
You are a Python code generator, capable of creating scripts from specifications.
def tdms2rtdc(): """Convert .tdms datasets to the hdf5-based .rtdc file format""" parser = tdms2rtdc_parser() args = parser.parse_args() path_tdms = pathlib.Path(args.tdms_path).resolve() path_rtdc = pathlib.Path(args.rtdc_path) # Determine whether input path is a tdms file or a directory ...
Can you implement a function in Python 3 that converts tdms datasets to the hdf5 - based. rtdc file format
You are a Python code generator, capable of creating scripts from specifications.
Perform checks on experimental datasets
Can you generate the documentation for the following Python 3 function def verify_dataset(): parser = verify_dataset_parser() args = parser.parse_args() path_in = pathlib.Path(args.path).resolve() viol, aler, info = load.check_dataset(path_in) print_info("Checking {}".format(path_in)) for inf in...
As a python code expert, you are capable of creating scripts from specifications.
def load_from_file(cfg_file): """Load the configuration from a file Parameters ---------- cfg_file: str Path to configuration file Returns ------- cfg : CaseInsensitiveDict Dictionary with configuration parameters """ path = pathlib.Path(cfg_file).resolve() wi...
Create a Python 3 function for loading the configuration from a file.
As a Python code composer, you craft elegant and concise scripts.
def keyval_str2typ(var, val): """Convert a variable from a string to its correct type Parameters ---------- var: str The variable name val: str The value of the variable represented as a string Returns ------- varout: str Stripped lowercase `var` valout: any...
Write a Python 3 script to convert a variable from a string to its correct type
You are a Python code architect, reviewing and designing scalable and efficient code
def keyval_typ2str(var, val): """Convert a variable to a string Parameters ---------- var: str The variable name val: any type The value of the variable Returns ------- varout: str Stripped lowercase `var` valout: any type The value converted to a us...
Can you create a Python 3 function that converts a variable to a string representation of a set of key - value types
You are a Python code generator, capable of creating scripts from specifications.
Set default values for the internal structures.
Can you tell what is the following Python 3 function doing def _init_default_values(self): # Do not filter out invalid event values self["filtering"]["remove invalid events"] = False # Enable filters switch is mandatory self["filtering"]["enable filters"] = True # Limit events in...
You are a Python code analyst, evaluating scripts for potential improvements.
Save the configuration to a file
Explain what the following Python 3 code does def save(self, filename): filename = pathlib.Path(filename) out = [] keys = sorted(list(self.keys())) for key in keys: out.append("[{}]".format(key)) section = self[key] ikeys = list(section.keys()) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Update the current config with a dictionary
Make a summary of the following Python 3 code def update(self, newcfg): for key in newcfg.keys(): if key not in self._cfg: self._cfg[key] = CaseInsensitiveDict() for skey in newcfg[key]: self._cfg[key][skey] = newcfg[key][skey]
You are a Python code generator, capable of creating scripts from specifications.
convert area - deformation - emodulus triplet
Explain what the following Python 3 code does def convert(area_um, deform, emodulus, channel_width_in, channel_width_out, flow_rate_in, flow_rate_out, viscosity_in, viscosity_out, inplace=False): """convert area-deformation-emodulus triplet The conversion formula...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_emodulus(area_um, deform, medium="CellCarrier", channel_width=20.0, flow_rate=0.16, px_um=0.34, temperature=23.0, copy=True): """Compute apparent Young's modulus using a look-up table Parameters ---------- area_um: float or ndarray Apparent (2D image) a...
Can you create a Python 3 function that computes the apparent Young s modulus using a look - up table.
You are a Python code architect, reviewing and designing scalable and efficient code
def make_exception(method, e): """Creates an exception for a given method, and RpcError.""" x = e.details() name = x[:x.find(':')].split('.')[-1] if name in globals(): cls = globals()[name] else: cls = UnknownRpcException # noqa return cls(method, e.code(), e.details())
Can you create a Python 3 function that creates an exception for a given method and RpcError.
As a Python code composer, you craft elegant and concise scripts.
Convert text to int
Can you tell what is the following Python 3 function doing def text_to_int(text, default_base="hex"): if text.startswith("0x"): value = int(text[2:], 16) elif text.startswith("$"): value = int(text[1:], 16) elif text.startswith("#"): value = int(text[1:], 10) elif text.startswith...
You are a Python code architect, reviewing and designing scalable and efficient code
Map out the sectors and link them together.
Can you generate the documentation for the following Python 3 function def assign_sector_numbers(self, dirent, sector_list): num = len(sector_list) order = self.reserve_space(num) if len(order) != num: raise errors.InvalidFile("VTOC reserved space for %d sectors. Sectors needed: %d" ...
As a python code expert, you are capable of creating scripts from specifications.
def downsample_grid(a, b, samples, ret_idx=False): """Content-based downsampling for faster visualization The arrays `a` and `b` make up a 2D scatter plot with high and low density values. This method takes out points at indices with high density. Parameters ---------- a, b: 1d ndarrays ...
Write a Python 3 function that can content - based downsampling for faster visualization of a 2D scatter plot.
As a Python code analyst, you investigate and solve complex coding mysteries
Check whether a and b are not inf or nan
Make a summary of the following Python 3 code def valid(a, b): return ~(np.isnan(a) | np.isinf(a) | np.isnan(b) | np.isinf(b))
As a Python code analyst, you investigate and solve complex coding mysteries
Normalize a with min / max values of ref1 using all elements of ref1 where the ref1 and ref2 are not nan inf
Can you generate a brief explanation for the following Python 3 code def norm(a, ref1, ref2): ref = ref1[valid(ref1, ref2)] return (a-ref.min())/(ref.max()-ref.min())
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the kernel function for continuous variables.
Given the following Python 3 function, write the documentation def gaussian(h, Xi, x): return (1. / np.sqrt(2 * np.pi)) * np.exp(-(Xi - x)**2 / (h**2 * 2.))
As a python code expert, you are capable of creating scripts from specifications.
def parse_config(h5path): """Parse the RT-DC configuration of an hdf5 file""" with h5py.File(h5path, mode="r") as fh5: h5attrs = dict(fh5.attrs) # Convert byte strings to unicode strings # https://github.com/h5py/h5py/issues/379 for key in h5attrs: if isi...
Can you implement a function in Python 3 that parses the RT - DC configuration of an hdf5 file
As a Python code translator, you convert algorithms and pseudocode into Python.
def hash(self): """Hash value based on file name and content""" if self._hash is None: tohash = [self.path.name] # Hash a maximum of ~1MB of the hdf5 file tohash.append(hashfile(self.path, blocksize=65536, count=20)) self._hash = hashobj(tohash) re...
Can you create a Python 3 function that hashes value based on file name and content
You are a Python code generator, capable of creating scripts from specifications.
def bin_num_doane(a): """Compute number of bins based on Doane's formula""" bad = np.isnan(a) | np.isinf(a) data = a[~bad] acc = bin_width_doane(a) num = np.int(np.round((data.max() - data.min()) / acc)) return num
How would you code a function in Python 3 to compute number of bins based on Doane s formula
As a Python code translator, you convert algorithms and pseudocode into Python.
def bin_width_doane(a): """Compute accuracy (bin width) based on Doane's formula References ---------- - `<https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width>`_ - `<https://stats.stackexchange.com/questions/55134/ doanes-formula-for-histogram-binning>`_ """ bad = np.isna...
Write a Python 3 function that can compute accuracy of a Doane s formula
As a python code expert, you are capable of creating scripts from specifications.
Returns a new KDE method that ignores nans and infs from the input data.
Explain what the following Python 3 code does def ignore_nan_inf(kde_method): def new_kde_method(events_x, events_y, xout=None, yout=None, *args, **kwargs): bad_in = get_bad_vals(events_x, events_y) if xout is None: density = np.zeros_like(events_x, dtype=float) ...
You are a Python code architect, reviewing and designing scalable and efficient code
Compute the kernel density for the given set of points.
Given the following Python 3 function, write the documentation def kde_gauss(events_x, events_y, xout=None, yout=None): valid_combi = ((xout is None and yout is None) or (xout is not None and yout is not None) ) if not valid_combi: raise ValueError("Both `xout` and ...
As a python code expert, you are capable of creating scripts from specifications.
Compute the KDE for the given set of events.
Make a summary of the following Python 3 code def kde_histogram(events_x, events_y, xout=None, yout=None, bins=None): valid_combi = ((xout is None and yout is None) or (xout is not None and yout is not None) ) if not valid_combi: raise ValueError("Both `xout` and `y...
As a python code expert, you are capable of creating scripts from specifications.
No Kernel Density Estimation for the given set of points.
Can you generate a brief explanation for the following Python 3 code def kde_none(events_x, events_y, xout=None, yout=None): valid_combi = ((xout is None and yout is None) or (xout is not None and yout is not None) ) if not valid_combi: raise ValueError("Both `xout`...
You are a Python code analyst, evaluating scripts for potential improvements.
Compute the multivariate kernel density estimate for the given set of points.
Can you generate the documentation for the following Python 3 function def kde_multivariate(events_x, events_y, xout=None, yout=None, bw=None): valid_combi = ((xout is None and yout is None) or (xout is not None and yout is not None) ) if not valid_combi: raise Valu...
As a Python code composer, you craft elegant and concise scripts.
def redirect_legacy_content(request): """Redirect from legacy /content/id/version to new /contents/uuid@version. Handles collection context (book) as well. """ routing_args = request.matchdict objid = routing_args['objid'] objver = routing_args.get('objver') filename = routing_args.get('fil...
Create a Python 3 function for redirecting from legacy content id to new content uuid@version.
As a Python code analyst, you investigate and solve complex coding mysteries
def add(self, isoel, col1, col2, channel_width, flow_rate, viscosity, method): """Add isoelastics Parameters ---------- isoel: list of ndarrays Each list item resembles one isoelastic line stored as an array of shape (N,3). The last column contains ...
Can you write a function in Python 3 where it adds isoelastics to the internal list of store items.
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_px_err(isoel, col1, col2, px_um, inplace=False): """Undo pixelation correction Isoelasticity lines are already corrected for pixelation effects as described in Mapping of Deformation to Apparent Young's Modulus in Real-Time Deformability Cytometry Christoph Hero...
Implement a Python 3 function for adding pixelation error to the set of isoealsticity lines in the experimental data.
As a python code expert, you are capable of creating scripts from specifications.
Convert isoelastics in area_um - circ - deform space to area_um - deform space.
Here you have a function in Python 3, explain what it does def convert(isoel, col1, col2, channel_width_in, channel_width_out, flow_rate_in, flow_rate_out, viscosity_in, viscosity_out, inplace=False): """Convert isoelastics in area_um-deform space ...
You are a Python code architect, reviewing and designing scalable and efficient code
Get ISO elastics and isoelastics from the original data.
Can you generate a brief explanation for the following Python 3 code def get(self, col1, col2, method, channel_width, flow_rate=None, viscosity=None, add_px_err=False, px_um=None): """Get isoelastics Parameters ---------- col1: str Name of the first feature of al...
As a Python code translator, you convert algorithms and pseudocode into Python.
def load_data(self, path): """Load isoelastics from a text file The text file is loaded with `numpy.loadtxt` and must have three columns, representing the two data columns and the elastic modulus with units defined in `definitions.py`. The file header must have a section definin...
Write a Python 3 script for loading isoelastics from a text file.
You are a Python code architect, reviewing and designing scalable and efficient code
def robots(request): """Return a simple "don't index me" robots.txt file.""" resp = request.response resp.status = '200 OK' resp.content_type = 'text/plain' resp.body = """ User-Agent: * Disallow: / """ return resp
Write a Python 3 script to return a simple don t index me robots. txt file.
As a Python code analyst, you investigate and solve complex coding mysteries
Compute the crosstalk inversion matrix for a given set of channel elements.
Can you generate the documentation for the following Python 3 function def get_compensation_matrix(ct21, ct31, ct12, ct32, ct13, ct23): ct11 = 1 ct22 = 1 ct33 = 1 if ct21 < 0: raise ValueError("ct21 matrix element must not be negative!") if ct31 < 0: raise ValueError("ct31 matrix e...
You are a Python code generator, capable of creating scripts from specifications.
Perform crosstalk correction on fluorescence signals and return the correct crosstalk.
Explain what the following Python 3 code does def correct_crosstalk(fl1, fl2, fl3, fl_channel, ct21=0, ct31=0, ct12=0, ct32=0, ct13=0, ct23=0): """Perform crosstalk correction Parameters ---------- fli: int, float, or np.ndarray Measured fluorescence signals fl_channel...
As a python code expert, you are capable of creating scripts from specifications.
Compute the moments of a contour in OpenCV s ContourMoments. cpp file.
Can you tell what is the following Python 3 function doing def cont_moments_cv(cont, flt_epsilon=1.19209e-07, dbl_epsilon=2.2204460492503131e-16): """Compute the moments of a contour The moments are computed in the same way as they are computed in OpenCV's `contourMo...
You are a Python code architect, reviewing and designing scalable and efficient code
Compute the inertia ratio of the convex hull of a contour.
Explain what the following Python 3 code does def get_inert_ratio_cvx(cont): if isinstance(cont, np.ndarray): # If cont is an array, it is not a list of contours, # because contours can have different lengths. cont = [cont] ret_list = False else: ret_list = True leng...
You are a Python code architect, reviewing and designing scalable and efficient code
Compute the principal inertia ratio of a contour.
Make a summary of the following Python 3 code def get_inert_ratio_prnc(cont): if isinstance(cont, np.ndarray): # If cont is an array, it is not a list of contours, # because contours can have different lengths. cont = [cont] ret_list = False else: ret_list = True len...
As a Python code composer, you craft elegant and concise scripts.
def get_inert_ratio_raw(cont): """Compute the inertia ratio of a contour The inertia ratio is computed from the central second order of moments along x (mu20) and y (mu02) via `sqrt(mu20/mu02)`. Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A 2D array that hold...
Implement a function in Python 3 to compute the inertia ratio of a contour.
You are a Python code analyst, evaluating scripts for potential improvements.
Compute tilt of raw contour relative to channel axis
Can you tell what is the following Python 3 function doing def get_tilt(cont): if isinstance(cont, np.ndarray): # If cont is an array, it is not a list of contours, # because contours can have different lengths. cont = [cont] ret_list = False else: ret_list = True le...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a function that tags a function with specified tags.
Can you tell what is the following Python 3 function doing def tag(*tags): ''' Constructs a decorator that tags a function with specified strings (@tags). The tags on the decorated function are available via fn.tags ''' def dfn(fn): _tags = getattr(fn, 'tags', set()) _tags.update...
As a python code expert, you are capable of creating scripts from specifications.
def raw(mime='application/octet-stream'): ''' Constructs a decorator that marks the fn as raw response format ''' def dfn(fn): tags = getattr(fn, 'tags', set()) tags.add('raw') fn.tags = tags fn.mime = getattr(fn, 'mime', mime) return fn return dfn
Create a Python 3 function to return a decorator that marks the given function as raw response format
As a Python code translator, you convert algorithms and pseudocode into Python.
Called when client opens a new connection. This method is called when the client opens a new connection.
Can you tell what is the following Python 3 function doing def open(self, pysession_id): ''' Called when client opens connection. Initialization is done here. ''' self.id = id(self) self.funcserver = self.application.funcserver self.pysession_id = pysession_id ...
You are a Python code analyst, evaluating scripts for potential improvements.
Called when client sends a message.
Can you generate the documentation for the following Python 3 function def on_message(self, msg): ''' Called when client sends a message. Supports a python debugging console. This forms the "eval" part of a standard read-eval-print loop. Currently the only implementation of the...
As a Python code composer, you craft elegant and concise scripts.
def on_close(self): ''' Called when client closes this connection. Cleanup is done here. ''' if self.id in self.funcserver.websocks: self.funcserver.websocks[self.id] = None ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(lambda:...
Write a Python 3 function that can call when client closes this connection. Cleanup is done here.
As a Python code translator, you convert algorithms and pseudocode into Python.
Remove unexpected keyword arguments from the set of received keyword arguments.
Here you have a function in Python 3, explain what it does def _clean_kwargs(self, kwargs, fn): ''' Remove unexpected keyword arguments from the set of received keyword arguments. ''' # Do not do the cleaning if server config # doesnt ask to ignore if not self.ser...
You are a Python code analyst, evaluating scripts for potential improvements.
def dump_stacks(self): ''' Dumps the stack of all threads. This function is meant for debugging. Useful when a deadlock happens. borrowed from: http://blog.ziade.org/2012/05/25/zmq-and-gevent-debugging-nightmares/ ''' dump = [] # threads threads = dict(...
Can you create a Python 3 function that dumps the stack of all threads.
As a python code expert, you are capable of creating scripts from specifications.
def define_log_pre_format_hooks(self): """ adds a hook to send to websocket if the run command was selected """ hooks = super(Server, self).define_log_pre_format_hooks() # NOTE enabling logs only on debug mode if self.args.func == self.run and self.args.debug: ...
Implement a Python 3 function for adding a hook to send to websocket if the run command was selected
As a Python code composer, you craft elegant and concise scripts.
def run(self): """ prepares the api and starts the tornado funcserver """ self.log_id = 0 # all active websockets and their state self.websocks = {} # all active python interpreter sessions self.pysessions = {} if self.DISABLE_REQUESTS_DEBUG_LOGS: d...
Can you implement a function in Python 3 that prepares the api and starts the tornado funcserver
As a Python code translator, you convert algorithms and pseudocode into Python.