output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Add CORS headers needed for web app implementation.
Can you tell what is the following Python 3 function doing def add_cors_headers(request, response): response.headerlist.append(('Access-Control-Allow-Origin', '*')) response.headerlist.append( ('Access-Control-Allow-Methods', 'GET, OPTIONS')) response.headerlist.append( ('Access-Control-Allo...
You are a Python code architect, reviewing and designing scalable and efficient code
def trace(self): """Initializes the trace data""" if self._trace is None: self._trace = self.load_trace(self.mname) return self._trace
Write a Python 3 script for initializing the trace data
As a python code expert, you are capable of creating scripts from specifications.
Loads the traces and returns them as a dictionary which contains the keys of the actual data.
Can you generate a brief explanation for the following Python 3 code def load_trace(mname): tname = TraceColumn.find_trace_file(mname) # Initialize empty trace dictionary trace = {} if tname is None: pass elif tname.suffix == ".tdms": # Again load the me...
As a Python code translator, you convert algorithms and pseudocode into Python.
def find_trace_file(mname): """Tries to find the traces tdms file name Returns None if no trace file is found. """ mname = pathlib.Path(mname) tname = None if mname.exists(): cand = mname.with_name(mname.name[:-5] + "_traces.tdms") if cand.exists...
How would you code a function in Python 3 to try to find the traces tdms file name Returns None if no trace file is found.
As a python code expert, you are capable of creating scripts from specifications.
This function fetches a docker secret from the secrets directory.
Explain what the following Python 3 code does def get_docker_secret(name, default=None, cast_to=str, autocast_name=True, getenv=True, safe=True, secrets_dir=os.path.join(root, 'var', 'run', 'secrets')): """This function fetches a docker secret :param name: the name of the docker secret ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Takes an argument and updates the hash.
Make a summary of the following Python 3 code def _update_hash(self, arg): if isinstance(arg, np.ndarray): self.ahash.update(arg.view(np.uint8)) elif isinstance(arg, list): [self._update_hash(a) for a in arg] else: self.ahash.update(str(arg).encode('utf-8'))
As a python code expert, you are capable of creating scripts from specifications.
Remove all cached objects
How would you explain what the following Python 3 function does def clear_cache(): del Cache._keys for k in list(Cache._cache.keys()): it = Cache._cache.pop(k) del it del Cache._cache Cache._keys = [] Cache._cache = {} gc.collect()
You are a Python code analyst, evaluating scripts for potential improvements.
Get the offset and size of the entry in the raw data of the disk image.
Here you have a function in Python 3, explain what it does def get_pos(self, sector): if not self.sector_is_valid(sector): raise ByteNotInFile166("Sector %d out of range" % sector) pos = sector * self.sector_size + self.header_offset size = self.sector_size return pos, size
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_sector_slice(self, start, end=None): """ Get contiguous sectors :param start: first sector number to read (note: numbering starts from 1) :param end: last sector number to read :returns: bytes """ pos, size = self.header.get_pos(start) if end is N...
Write a Python 3 function that can get a slice of the data from the specified sector.
As a Python code composer, you craft elegant and concise scripts.
def get_sectors(self, start, end=None): """ Get contiguous sectors :param start: first sector number to read (note: numbering starts from 1) :param end: last sector number to read :returns: bytes """ s = self.get_sector_slice(start, end) return self.bytes...
Can you create a Python 3 function that gets contiguous sectors in the cache.
You are a Python code generator, capable of creating scripts from specifications.
def write_file(self, filename, filetype, data): """Write data to a file on disk This throws various exceptions on failures, for instance if there is not enough space on disk or a free entry is not available in the catalog. """ state = self.begin_transaction() try...
Can you implement a function in Python 3 that writes data to a file on disk.
As a Python code translator, you convert algorithms and pseudocode into Python.
Helper function for transforming an array a ray to log - scale.
Can you tell what is the following Python 3 function doing def _apply_scale(self, a, scale, feat): if scale == "linear": b = a elif scale == "log": with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") b = np.log(a) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Return a list of all available features
Can you tell what is the following Python 3 function doing def features(self): mycols = [] for col in dfn.feature_names: if col in self: mycols.append(col) mycols.sort() return mycols
As a Python code analyst, you investigate and solve complex coding mysteries
Downsampling of the data for a specific set of locations.
How would you explain what the following Python 3 function does def get_downsampled_scatter(self, xax="area_um", yax="deform", downsample=0, xscale="linear", yscale="linear"): """Downsampling by removing points at dense locations Parameter...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_kde_contour(self, xax="area_um", yax="deform", xacc=None, yacc=None, kde_type="histogram", kde_kwargs={}, xscale="linear", yscale="linear"): """Evaluate the kernel density estimate for contour plots Parameters ---------- xax: str ...
Can you write a function in Python 3 where it evaluates the kernel density estimate for contour plots.
As a Python code translator, you convert algorithms and pseudocode into Python.
Evaluate the kernel density estimate for scatter plots.
Can you tell what is the following Python 3 function doing def get_kde_scatter(self, xax="area_um", yax="deform", positions=None, kde_type="histogram", kde_kwargs={}, xscale="linear", yscale="linear"): """Evaluate the kernel density estimate for scatter plots ...
You are a Python code generator, capable of creating scripts from specifications.
def polygon_filter_add(self, filt): """Associate a Polygon Filter with this instance Parameters ---------- filt: int or instance of `PolygonFilter` The polygon filter to add """ if not isinstance(filt, (PolygonFilter, int, float)): msg = "`filt` m...
How would you code a function in Python 3 to associate a Polygon Filter with this instance
As a Python code analyst, you investigate and solve complex coding mysteries
Removes a polygon filter from this instance.
Can you generate the documentation for the following Python 3 function def polygon_filter_rm(self, filt): if not isinstance(filt, (PolygonFilter, int, float)): msg = "`filt` must be a number or instance of PolygonFilter!" raise ValueError(msg) if isinstance(filt, PolygonFilter):...
You are a Python code analyst, evaluating scripts for potential improvements.
Checks whether a dataset is complete and returns a list of str or list of str
Make a summary of the following Python 3 code def check_dataset(path_or_ds): aler = [] info = [] viol = [] if isinstance(path_or_ds, RTDCBase): ds = path_or_ds else: ds = load_file(path_or_ds) # check for meta data types for sec in ds.config: for key in ds.config[sec]...
As a Python code translator, you convert algorithms and pseudocode into Python.
Initialize a new RT - DC dataset.
Explain what the following Python 3 code does def new_dataset(data, identifier=None): if isinstance(data, dict): return fmt_dict.RTDC_Dict(data, identifier=identifier) elif isinstance(data, (str_types)) or isinstance(data, pathlib.Path): return load_file(data, identifier=identifier) elif isi...
You are a Python code analyst, evaluating scripts for potential improvements.
Parse a log buffer based on url_pattern.
Explain what the following Python 3 code does def parse_log(log, url_pattern): hits = {} initial_timestamp = None def clean_timestamp(v): return ' '.join(v).strip('[]') for line in log: data = line.split() if not initial_timestamp: initial_timestamp = clean_timestamp...
As a Python code analyst, you investigate and solve complex coding mysteries
def main(argv=None): """Count the hits from logfile.""" parser = create_parser('hits_counter', description=__doc__) parser.add_argument('--hostname', default='cnx.org', help="hostname of the site (default: cnx.org)") parser.add_argument('--log-format', def...
Can you create a Python 3 function that counts the hits from a logfile.
As a python code expert, you are capable of creating scripts from specifications.
def fbool(value): """boolean""" if isinstance(value, str_types): value = value.lower() if value == "false": value = False elif value == "true": value = True elif value: value = bool(float(value)) else: raise ValueError("empt...
Can you implement a function in Python 3 that converts a string to a boolean
As a python code expert, you are capable of creating scripts from specifications.
converts a string to an integer
Here you have a function in Python 3, explain what it does def fint(value): if isinstance(value, str_types): # strings might have been saved wrongly as booleans value = value.lower() if value == "false": value = 0 elif value == "true": value = 1 elif v...
You are a Python code architect, reviewing and designing scalable and efficient code
A list of integers
Here you have a function in Python 3, explain what it does def fintlist(alist): outlist = [] if not isinstance(alist, (list, tuple)): # we have a string (comma-separated integers) alist = alist.strip().strip("[] ").split(",") for it in alist: if it: outlist.append(fint(it...
As a Python code translator, you convert algorithms and pseudocode into Python.
def avi(self, path, filtered=True, override=False): """Exports filtered event images to an avi file Parameters ---------- path: str Path to a .tsv file. The ending .tsv is added automatically. filtered: bool If set to `True`, only the filtered data (index...
Can you write a function in Python 3 where it exports filtered event images to an avi file.
You are a Python code analyst, evaluating scripts for potential improvements.
def fcs(self, path, features, filtered=True, override=False): """Export the data of an RT-DC dataset to an .fcs file Parameters ---------- mm: instance of dclab.RTDCBase The dataset that will be exported. path: str Path to a .tsv file. The ending .tsv is ...
Can you create a Python 3 function that exports the data of an RT - DC dataset to a. fcs file.
As a Python code composer, you craft elegant and concise scripts.
Export the current instance data to an HDF5 file.
Can you tell what is the following Python 3 function doing def hdf5(self, path, features, filtered=True, override=False, compression="gzip"): """Export the data of the current instance to an HDF5 file Parameters ---------- path: str Path to an .rtdc file. The en...
As a python code expert, you are capable of creating scripts from specifications.
Export the data of the current instance to a. tsv file.
Given the following Python 3 function, write the documentation def tsv(self, path, features, filtered=True, override=False): features = [c.lower() for c in features] path = pathlib.Path(path) ds = self.rtdc_ds # Make sure that path ends with .tsv if path.suffix != ".tsv": ...
As a Python code analyst, you investigate and solve complex coding mysteries
def hashfile(fname, blocksize=65536, count=0): """Compute md5 hex-hash of a file Parameters ---------- fname: str path to the file blocksize: int block size in bytes read from the file (set to `0` to hash the entire file) count: int number of blocks read from the...
Create a Python 3 function for computing md5 hex - hash of a file
You are a Python code analyst, evaluating scripts for potential improvements.
def obj2str(obj): """String representation of an object for hashing""" if isinstance(obj, str_types): return obj.encode("utf-8") elif isinstance(obj, pathlib.Path): return obj2str(str(obj)) elif isinstance(obj, (bool, int, float)): return str(obj).encode("utf-8") elif obj is ...
Can you implement a function in Python 3 that converts an object to a string representation for hashing.
You are a Python code generator, capable of creating scripts from specifications.
def create_self_signed_cert(): """Creates a self-signed certificate key pair.""" config_dir = Path(BaseDirectory.xdg_config_home) / 'xenon-grpc' config_dir.mkdir(parents=True, exist_ok=True) key_prefix = gethostname() crt_file = config_dir / ('%s.crt' % key_prefix) key_file = config_dir / ('%s....
Create a Python 3 function for creating a self - signed certificate key pair.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_project_name_from_path(path, append_mx=False): """Get the project name from a path. For a path "/home/peter/hans/HLC12398/online/M1_13.tdms" or For a path "/home/peter/hans/HLC12398/online/data/M1_13.tdms" or without the ".tdms" file, this will return always "HLC12398". Parameters ----...
Create a Python 3 function to get the project name from a path.
As a python code expert, you are capable of creating scripts from specifications.
Recursively find projects based on. tdms file endings Searches the directory and returns a sorted list of all found. tdms project files except fluorescence data trace files which end with _traces. tdms.
Make a summary of the following Python 3 code def get_tdms_files(directory): path = pathlib.Path(directory).resolve() # get all tdms files tdmslist = [r for r in path.rglob("*.tdms") if r.is_file()] # exclude traces files tdmslist = [r for r in tdmslist if not r.name.endswith("_traces.tdms")] re...
As a Python code composer, you craft elegant and concise scripts.
Initializes the current RT - DC dataset with a tdms file.
Make a summary of the following Python 3 code def _init_data_with_tdms(self, tdms_filename): tdms_file = TdmsFile(str(tdms_filename)) # time is always there table = "Cell Track" # Edit naming.dclab2tdms to add features for arg in naming.tdms2dclab: try: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Hash value based on file name and. ini file content
Here you have a function in Python 3, explain what it does def hash(self): if self._hash is None: # Only hash _camera.ini and _para.ini fsh = [self.path.with_name(self._mid + "_camera.ini"), self.path.with_name(self._mid + "_para.ini")] tohash = [hashfile(f...
As a Python code translator, you convert algorithms and pseudocode into Python.
Determines the offset of the contours w. r. t. other data columns.
Given the following Python 3 function, write the documentation def determine_offset(self): # In case of regular RTDC, the first contour is # missing. In case of fRTDC, it is there, so we # might have an offset. We find out if the first # contour frame is missing by comparing it to ...
You are a Python code generator, capable of creating scripts from specifications.
def find_contour_file(rtdc_dataset): """Tries to find a contour file that belongs to an RTDC dataset Returns None if no contour file is found. """ cont_id = rtdc_dataset.path.stem cands = [c.name for c in rtdc_dataset._fdir.rglob("*_contours.txt")] cands = sorted(cands) ...
Write a Python 3 function for trying to find a contour file that belongs to an RTDC dataset. Returns None if no contour file is found.
As a Python code composer, you craft elegant and concise scripts.
Open and index the contour file and populate internal list of contours with the names of the contour entries.
Can you generate a brief explanation for the following Python 3 code def _index_file(self): with self.filename.open() as fd: data = fd.read() ident = "Contour in frame" self._data = data.split(ident)[1:] self._initialized = True
As a Python code composer, you craft elegant and concise scripts.
def get_frame(self, idx): """Return the frame number of a contour""" cont = self.data[idx] frame = int(cont.strip().split(" ", 1)[0]) return frame
Can you create a Python 3 function that returns the frame number of a contour
You are a Python code architect, reviewing and designing scalable and efficient code
def get_viscosity(medium="CellCarrier", channel_width=20.0, flow_rate=0.16, temperature=23.0): """Returns the viscosity for RT-DC-specific media Parameters ---------- medium: str The medium to compute the viscosity for. One of ["CellCarrier", "CellCarrier B", "water"]....
Implement a function in Python 3 to return the viscosity for the given medium and channel width.
As a python code expert, you are capable of creating scripts from specifications.
def get_statistics(ds, methods=None, features=None): """Compute statistics for an RT-DC dataset Parameters ---------- ds: dclab.rtdc_dataset.RTDCBase The dataset for which to compute the statistics. methods: list of str or None The methods wih which to compute the statistics. ...
Write a Python 3 script for computing statistics for an RT - DC dataset.
As a Python code composer, you craft elegant and concise scripts.
def mode(data): """Compute an intelligent value for the mode The most common value in experimental is not very useful if there are a lot of digits after the comma. This method approaches this issue by rounding to bin size that is determined by the Freedman–Diaconis rule. Parameters -------...
Write a Python 3 function for computing an intelligent value for the mode of the current node in the experimental.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_feature(self, ds, feat): """Return filtered feature data The features are filtered according to the user-defined filters, using the information in `ds._filter`. In addition, all `nan` and `inf` values are purged. Parameters ---------- ds: dclab.rtdc_data...
Create a Python 3 function to return the feature data for the specified feature
You are a Python code analyst, evaluating scripts for potential improvements.
def check_global_valid(self): """ Makes sure there aren't any SAM resources in a template that will be used in a CloudFormation StackSet :return: bool """ serverless_cnt = len(list(filter(lambda x: x._serverless_type, self._data['resources']))) if serverless_cnt > 0: ...
Write a Python 3 function for checking if the global resource set is valid.
As a Python code analyst, you investigate and solve complex coding mysteries
def has_stack(self, stack_name): """ Checks if a CloudFormation stack with given name exists :param stack_name: Name or ID of the stack :return: True if stack exists. False otherwise """ cf = self.cf_client try: resp = cf.describe_stacks(StackName=stac...
Can you implement a function in Python 3 that checks if a CloudFormation stack with given name exists.
You are a Python code architect, reviewing and designing scalable and efficient code
Check whether a flyweight object with the specified key has already been created.
How would you explain what the following Python 3 function does def has_key(cls, *args): key = args if len(args) > 1 else args[0] return key in cls._instances
As a python code expert, you are capable of creating scripts from specifications.
Returns a new object with the given key if it has already been created.
Explain what the following Python 3 code does def from_key(cls, *args): key = args if len(args) > 1 else args[0] return cls._instances.get(key, None)
As a Python code composer, you craft elegant and concise scripts.
Writes the metric to elasticsearch
Given the following Python 3 function, write the documentation def write(self, name, **data): data["name"] = name if not ("timestamp" in data): data["timestamp"] = datetime.utcnow() try: self.client.index( index=self.get_index(), doc_type...
As a python code expert, you are capable of creating scripts from specifications.
Write multiple metrics to elasticsearch in one request
How would you explain what the following Python 3 function does def bulk_write(self, metrics): actions = [] index = self.get_index() for metric in metrics: actions.append({'index': {'_index': index, '_type': self.doc_type}}) actions.append(metric) try: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_bright(mask, image, ret_data="avg,sd"): """Compute avg and/or std of the event brightness The event brightness is defined by the gray-scale values of the image data within the event mask area. Parameters ---------- mask: ndarray or list of ndarrays of shape (M,N) and dtype bool ...
Create a Python 3 function for computing average and standard deviation of the event brightness of the contour.
You are a Python code architect, reviewing and designing scalable and efficient code
def search(query, query_type, nocache=False): """Search archive contents. Look up search results in cache, if not in cache, do a database search and cache the result """ settings = get_current_registry().settings memcache_servers = settings['memcache-servers'].split() if not memcache_server...
How would you code a function in Python 3 to search archive contents. Look up search results in cache, if not in cache, do a database search and cache the result
You are a Python code architect, reviewing and designing scalable and efficient code
def available_features(rtdc_ds): """Determine available features for an RT-DC dataset Parameters ---------- rtdc_ds: instance of RTDCBase The dataset to check availability for Returns ------- features: dict Dictionary with feature names a...
Write a Python 3 script for determining available features for an RT - DC dataset.
You are a Python code analyst, evaluating scripts for potential improvements.
Compute the feature with self. method
Given the following Python 3 function, write the documentation def compute(self, rtdc_ds): data = self.method(rtdc_ds) dsize = len(rtdc_ds) - len(data) if dsize > 0: msg = "Growing feature {} in {} by {} to match event number!" warnings.warn(msg.format(self.feature_name,...
You are a Python code generator, capable of creating scripts from specifications.
def get_instances(feature_name): """Return all all instances that compute `feature_name`""" feats = [] for ft in AncillaryFeature.features: if ft.feature_name == feature_name: feats.append(ft) return feats
Create a Python 3 function for returning all instances that compute feature_name
As a python code expert, you are capable of creating scripts from specifications.
def hash(self, rtdc_ds): """Used for identifying an ancillary computation The data columns and the used configuration keys/values are hashed. """ hasher = hashlib.md5() # data columns for col in self.req_features: hasher.update(obj2str(rtdc_ds[col])) ...
Implement a Python 3 function for using for identifying an ancillary computation
As a Python code translator, you convert algorithms and pseudocode into Python.
Checks whether the feature is available for the current instance of AncillaryFeature.
Given the following Python 3 function, write the documentation def is_available(self, rtdc_ds, verbose=False): # Check config keys for item in self.req_config: section, keys = item if section not in rtdc_ds.config: if verbose: print("{} not in ...
You are a Python code architect, reviewing and designing scalable and efficient code
def producer(self): """ :raises: kafka.errors.NoBrokersAvailable if the connection is broken """ if self._producer: return self._producer self._producer = KafkaProducer( bootstrap_servers=self.hosts, value_serializer=lambda v: self._serializer...
Write a Python 3 script to return a KafkaProducer instance for this connection.
You are a Python code generator, capable of creating scripts from specifications.
Write the metric to kafka
Make a summary of the following Python 3 code def write(self, name, **data): data["name"] = name if not ("timestamp" in data): data["timestamp"] = datetime.utcnow() try: self.producer.send(topic=self.topic, value=data) self.producer.flush() except (K...
As a Python code translator, you convert algorithms and pseudocode into Python.
def bulk_write(self, metrics): """ Write multiple metrics to kafka in one request Args: metrics (list): """ try: for metric in metrics: self.producer.send(self.topic, metric) self.producer.flush() except (KafkaTimeoutEr...
Create a Python 3 function to write multiple metrics to kafka in one request
As a Python code composer, you craft elegant and concise scripts.
Build the text of the file and write the file.
How would you explain what the following Python 3 function does def create_module_file(package, module, opts): if not opts.noheadings: text = format_heading(1, '%s module' % module) else: text = '' # text += format_heading(2, ':mod:`%s` Module' % module) text += format_directive(module, ...
As a python code expert, you are capable of creating scripts from specifications.
Create the text of the file and write it.
Explain what the following Python 3 code does def create_package_file(root, master_package, subroot, py_files, opts, subs): text = format_heading(1, '%s' % makename(master_package, subroot)) if opts.modulefirst: text += format_directive(subroot, master_package) text += '\n' # build a list ...
As a Python code composer, you craft elegant and concise scripts.
Check if we want to skip this module.
Given the following Python 3 function, write the documentation def shall_skip(module, opts): # skip it if there is nothing (or just \n or \r\n) in the file if path.getsize(module) <= 2: return True # skip if it has a "private" name and this is selected filename = path.basename(module) if fil...
As a python code expert, you are capable of creating scripts from specifications.
Use threads and a subproc to bodge a timeout on top of filesystem access
How would you explain what the following Python 3 function does def safe_stat(path, timeout=1, cmd=None): "Use threads and a subproc to bodge a timeout on top of filesystem access" global safe_stat_process if cmd is None: cmd = ['/usr/bin/stat'] cmd.append(path) def target(): glob...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_polygon_filter_names(): """Get the names of all polygon filters in the order of creation""" names = [] for p in PolygonFilter.instances: names.append(p.name) return names
Implement a function in Python 3 to get the names of all polygon filters in the order of creation
As a python code expert, you are capable of creating scripts from specifications.
def _check_data(self): """Check if the data given is valid""" if self.axes is None: raise PolygonFilterError("`axes` parm not set.") if self.points is None: raise PolygonFilterError("`points` parm not set.") self.points = np.array(self.points) if self.poin...
How would you code a function in Python 3 to check if the data given is valid
You are a Python code generator, capable of creating scripts from specifications.
def _load(self, filename): """Import all filters from a text file""" filename = pathlib.Path(filename) with filename.open() as fd: data = fd.readlines() # Get the strings that correspond to self.fileid bool_head = [l.strip().startswith("[") for l in data] in...
Implement a Python 3 function for loading all filters from a text file
You are a Python code generator, capable of creating scripts from specifications.
Define a unique id for this filter
Can you tell what is the following Python 3 function doing def _set_unique_id(self, unique_id): assert isinstance(unique_id, int), "unique_id must be an integer" if PolygonFilter.instace_exists(unique_id): newid = max(PolygonFilter._instance_counter, unique_id+1) msg = "PolygonF...
As a Python code translator, you convert algorithms and pseudocode into Python.
Return a copy of the current instance.
Here you have a function in Python 3, explain what it does def copy(self, invert=False): if invert: inverted = not self.inverted else: inverted = self.inverted return PolygonFilter(axes=self.axes, points=self.points, ...
As a python code expert, you are capable of creating scripts from specifications.
Filter a set of datax and datay according to self. points
Make a summary of the following Python 3 code def filter(self, datax, datay): f = np.ones(datax.shape, dtype=bool) for i, p in enumerate(zip(datax, datay)): f[i] = PolygonFilter.point_in_poly(p, self.points) if self.inverted: np.invert(f, f) return f
As a Python code analyst, you investigate and solve complex coding mysteries
def get_instance_from_id(unique_id): """Get an instance of the `PolygonFilter` using a unique id""" for instance in PolygonFilter.instances: if instance.unique_id == unique_id: return instance # if this does not work: raise KeyError("PolygonFilter with unique_...
Can you implement a function in Python 3 that gets an instance of the PolygonFilter using a unique id
You are a Python code generator, capable of creating scripts from specifications.
Import all polygons from a. poly file.
Given the following Python 3 function, write the documentation def import_all(path): plist = [] fid = 0 while True: try: p = PolygonFilter(filename=path, fileid=fid) plist.append(p) fid += 1 except IndexError: ...
You are a Python code architect, reviewing and designing scalable and efficient code
def point_in_poly(p, poly): """Determine whether a point is within a polygon area Uses the ray casting algorithm. Parameters ---------- p: float Coordinates of the point poly: array_like of shape (N, 2) Polygon (`PolygonFilter.points`) R...
Can you create a Python 3 function that determines whether a point is inside a polygon area.
You are a Python code generator, capable of creating scripts from specifications.
def remove(unique_id): """Remove a polygon filter from `PolygonFilter.instances`""" for p in PolygonFilter.instances: if p.unique_id == unique_id: PolygonFilter.instances.remove(p)
Write a Python 3 script for removing a polygon filter from PolygonFilter. instances
You are a Python code generator, capable of creating scripts from specifications.
Save all data to a text file.
Given the following Python 3 function, write the documentation def save(self, polyfile, ret_fobj=False): if is_file_obj(polyfile): fobj = polyfile else: fobj = pathlib.Path(polyfile).open("a") # Who the hell would use more then 10 million polygons or # polygon po...
You are a Python code generator, capable of creating scripts from specifications.
Save all polygon filters to a file.
How would you explain what the following Python 3 function does def save_all(polyfile): nump = len(PolygonFilter.instances) if nump == 0: raise PolygonFilterError("There are not polygon filters to save.") for p in PolygonFilter.instances: # we return the ret_obj, so we do...
As a Python code analyst, you investigate and solve complex coding mysteries
Retrieve a file s data.
Make a summary of the following Python 3 code def get_resource(request): hash = request.matchdict['hash'] # Do the file lookup with db_connect() as db_connection: with db_connection.cursor() as cursor: args = dict(hash=hash) cursor.execute(SQL['get-resource'], args) ...
As a python code expert, you are capable of creating scripts from specifications.
def get_style_bits(match=False, comment=False, selected=False, data=False, diff=False, user=0): """ Return an int value that contains the specified style bits set. Available styles for each byte are: match: part of the currently matched search comment: user commented area selected: selected region...
How would you implement a function in Python 3 that returns an int value that contains the specified style bits set.
You are a Python code generator, capable of creating scripts from specifications.
Get the bit mask that will turn off the selected bits
Can you generate the documentation for the following Python 3 function def get_style_mask(**kwargs): bits = get_style_bits(**kwargs) if 'user' in kwargs and kwargs['user']: bits |= user_bit_mask else: bits &= (0xff ^ user_bit_mask) return 0xff ^ bits
As a Python code analyst, you investigate and solve complex coding mysteries
Return start and end offsets of this segment s data into the base array s data.
Explain what the following Python 3 code does def byte_bounds_offset(self): if self.data.base is None: if self.is_indexed: basearray = self.data.np_data else: basearray = self.data return 0, len(basearray) return int(self.data_start - s...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_raw_index(self, i): """Get index into base array's raw data, given the index into this segment """ if self.is_indexed: return int(self.order[i]) if self.data.base is None: return int(i) return int(self.data_start - self.base_start + i)
Create a Python 3 function for getting index into base array s raw data given the index into this object s base array s base array
You are a Python code generator, capable of creating scripts from specifications.
Get array of indexes from the base array as if this raw data were were indexed.
Can you generate a brief explanation for the following Python 3 code def get_indexes_from_base(self): if self.is_indexed: return np.copy(self.order[i]) if self.data.base is None: i = 0 else: i = self.get_raw_index(0) return np.arange(i, i + len(self), ...
You are a Python code architect, reviewing and designing scalable and efficient code
Get mapping from this segment s indexes to the indexes of the base array.
Here you have a function in Python 3, explain what it does def reverse_index_mapping(self): if self._reverse_index_mapping is None: if self.is_indexed: # Initialize array to out of range r = np.zeros(self.base_length, dtype=np.int32) - 1 r[self.order] ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_reverse_index(self, base_index): """Get index into this segment's data given the index into the base data Raises IndexError if the base index doesn't map to anything in this segment's data """ r = self.reverse_index_mapping[base_index] if r < 0: raise...
How would you implement a function in Python 3 that gets the index into this segment s data given the index into the base data
As a Python code translator, you convert algorithms and pseudocode into Python.
Resize the data arrays of the child segments to the new size.
Can you tell what is the following Python 3 function doing def resize(self, newsize, zeros=True): if not self.can_resize: raise ValueError("Segment %s can't be resized" % str(self)) # only makes sense for the container (outermost) object if not self.rawdata.is_base: raise...
You are a Python code analyst, evaluating scripts for potential improvements.
Hook for the future if attributes have been renamed.
Can you tell what is the following Python 3 function doing def restore_renamed_serializable_attributes(self): if hasattr(self, 'start_addr'): self.origin = self.start_addr log.debug(f"moving start_addr to origin: {self.start_addr}") delattr(self, 'start_addr')
As a Python code translator, you convert algorithms and pseudocode into Python.
Reconstruct the pointers to the parent data arrays
Can you tell what is the following Python 3 function doing def reconstruct_raw(self, rawdata): start, end = self._rawdata_bounds r = rawdata[start:end] delattr(self, '_rawdata_bounds') try: if self._order_list: order = to_numpy_list(self._order_list) ...
You are a Python code generator, capable of creating scripts from specifications.
def get_parallel_raw_data(self, other): """ Get the raw data that is similar to the specified other segment """ start, end = other.byte_bounds_offset() r = self.rawdata[start:end] if other.rawdata.is_indexed: r = r.get_indexed[other.order] return r
Can you implement a function in Python 3 that gets the raw data that is similar to the specified other segment.
You are a Python code architect, reviewing and designing scalable and efficient code
Save extra metadata to a dict so that it can be serialized.
Given the following Python 3 function, write the documentation def serialize_session(self, mdict): mdict["comment ranges"] = [list(a) for a in self.get_style_ranges(comment=True)] mdict["data ranges"] = [list(a) for a in self.get_style_ranges(data=True)] for i in range(1, user_bit_mask): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_index_from_base_index(self, base_index): """Get index into this array's data given the index into the base array """ r = self.rawdata try: index = r.get_reverse_index(base_index) except IndexError: raise IndexError("index %d not in this segment" % ...
Write a Python 3 function for getting index into this array s data given the index into the base array
You are a Python code generator, capable of creating scripts from specifications.
def get_style_ranges(self, **kwargs): """Return a list of start, end pairs that match the specified style """ style_bits = self.get_style_bits(**kwargs) matches = (self.style & style_bits) == style_bits return self.bool_to_ranges(matches)
Write a Python 3 function for returning a list of start end pairs that match the specified style
You are a Python code analyst, evaluating scripts for potential improvements.
Fixup any style bytes that are marked as commented but have no comments.
Here you have a function in Python 3, explain what it does def fixup_comments(self): style_base = self.rawdata.style_base comment_text_indexes = np.asarray(list(self.rawdata.extra.comments.keys()), dtype=np.uint32) comment_mask = self.get_style_mask(comment=True) has_comments = np.where(...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_entire_style_ranges(self, split_comments=None, **kwargs): """Find sections of the segment that have the same style value. The arguments to this function are used as a mask for the style to determine where to split the styles. Style bits that aren't included in the list will be i...
Write a Python 3 function for finding sections of the segment that have the same style value. The arguments to this function are used as a mask for the style to determine where to split the styles. Style bits that aren't included in the list will be ignored when splitting. The returned list covers the entire length of ...
As a Python code analyst, you investigate and solve complex coding mysteries
Get a list of comments at specified indexes
How would you explain what the following Python 3 function does def get_comments_at_indexes(self, indexes): s = self.style[indexes] has_comments = np.where(s & comment_bit_mask > 0)[0] comments = [] for where_index in has_comments: raw = self.get_raw_index(indexes[where_index...
As a Python code composer, you craft elegant and concise scripts.
Get a chunk of data that can be used to recreate the comments on an undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS undo ArcGIS
Explain what the following Python 3 code does def get_comment_restore_data(self, ranges): restore_data = [] for start, end in ranges: log.debug("range: %d-%d" % (start, end)) styles = self.style[start:end].copy() items = {} for i in range(start, end): ...
You are a Python code analyst, evaluating scripts for potential improvements.
def restore_comments(self, restore_data): """Restore comment styles and data """ for start, end, styles, items in restore_data: log.debug("range: %d-%d" % (start, end)) self.style[start:end] = styles for i in range(start, end): rawindex, commen...
How would you code a function in Python 3 to restore comment styles and data structures
You are a Python code analyst, evaluating scripts for potential improvements.
def get_comments_in_range(self, start, end): """Get a list of comments at specified indexes""" comments = {} # Naive way, but maybe it's fast enough: loop over all comments # gathering those within the bounds for rawindex, comment in self.rawdata.extra.comments.items(): ...
Implement a function in Python 3 to get a list of comments at specified indexes
You are a Python code analyst, evaluating scripts for potential improvements.
def copy_user_data(self, source, index_offset=0): """Copy comments and other user data from the source segment to this segment. The index offset is the offset into self based on the index of source. """ for index, comment in source.iter_comments_in_segment(): self.se...
Create a Python 3 function for copying comments and other user data from the source segment to this segment.
As a Python code translator, you convert algorithms and pseudocode into Python.
def xpath_book(request, uuid, version, return_json=True): """ Given a request, book UUID and version: returns a JSON object or HTML list of results, each result containing: module_name, module_uuid, xpath_results, an array of strings, each an individual xpath result. """ xpath_string =...
How would you implement a function in Python 3 that gives a request book UUID and version returns a JSON object or HTML list of results.
You are a Python code architect, reviewing and designing scalable and efficient code
def xpath_page(request, uuid, version): """Given a page UUID (and optional version), returns a JSON object of results, as in xpath_book()""" xpath_string = request.params.get('q') return execute_xpath(xpath_string, 'xpath-module', uuid, version)
Create a Python 3 function for giving a page UUID and optional version returns a JSON object of results as in xpath_book
You are a Python code analyst, evaluating scripts for potential improvements.