output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Create a IndicatorItem node for FileItem / PEInfo / VersionInfoList / VersionInfoItem
Given the following Python 3 function, write the documentation def make_fileitem_peinfo_versioninfoitem(key, value, condition='is', negate=False, preserve_case=False): document = 'FileItem' search = 'FileItem/PEInfo/VersionInfoList/VersionInfoItem/' + key # XXX: No validation of key done. content_type = 's...
You are a Python code architect, reviewing and designing scalable and efficient code
def fix_schema_node_ordering(parent): """ Fix the ordering of children under the criteria node to ensure that IndicatorItem/Indicator order is preserved, as per XML Schema. :return: """ children = parent.getchildren() i_nodes = [node for node in children if node....
Can you write a function in Python 3 where it fixes the ordering of children under the criteria node to ensure that IndicatorItem or Indicator order is preserved as per XML Schema.
You are a Python code analyst, evaluating scripts for potential improvements.
This function makes a Indicator node element.
Here you have a function in Python 3, explain what it does def make_indicator_node(operator, nid=None): if operator.upper() not in VALID_INDICATOR_OPERATORS: raise ValueError('Indicator operator must be in [{}].'.format(VALID_INDICATOR_OPERATORS)) i_node = et.Element('Indicator') if nid: i_n...
You are a Python code architect, reviewing and designing scalable and efficient code
This function creates an IndicatorItem element.
Make a summary of the following Python 3 code def make_indicatoritem_node(condition, document, search, content_type, content, preserve_case=False, negat...
As a python code expert, you are capable of creating scripts from specifications.
This returns the first top level Indicator node under the criteria node.
Here you have a function in Python 3, explain what it does def get_top_level_indicator_node(root_node): if root_node.tag != 'OpenIOC': raise IOCParseError('Root tag is not "OpenIOC" [{}].'.format(root_node.tag)) elems = root_node.xpath('criteria/Indicator') if len(elems) == 0: log.warning('N...
As a Python code analyst, you investigate and solve complex coding mysteries
def write_ioc(root, output_dir=None, force=False): """ Serialize an IOC, as defined by a set of etree Elements, to a .IOC file. :param root: etree Element to write out. Should have the tag 'OpenIOC' :param output_dir: Directory to write the ioc out to. default is current working directory. :param...
How would you implement a function in Python 3 that serializes an IOC as defined by a set of etree Elements to a. IOC file.
You are a Python code architect, reviewing and designing scalable and efficient code
Serialize an IOC to a string.
Can you tell what is the following Python 3 function doing def write_ioc_string(root, force=False): root_tag = 'OpenIOC' if not force and root.tag != root_tag: raise ValueError('Root tag is not "{}".'.format(root_tag)) default_encoding = 'utf-8' tree = root.getroottree() # noinspection PyBro...
As a Python code translator, you convert algorithms and pseudocode into Python.
def open_ioc(fn): """ Opens an IOC file, or XML string. Returns the root element, top level indicator element, and parameters element. If the IOC or string fails to parse, an IOCParseError is raised. This is a helper function used by __init__. :param fn: This is a pat...
Write a Python 3 function for opening an IOC file or XML string and returns the root element top level Indicator element and Parameters element.
You are a Python code analyst, evaluating scripts for potential improvements.
This function generates all parts of an IOC.
Can you generate the documentation for the following Python 3 function def make_ioc(name=None, description='Automatically generated IOC', author='IOC_api', links=None, keywords=None, iocid=None): """ This generates all ...
As a Python code analyst, you investigate and solve complex coding mysteries
Set the last modified date of a IOC to the current date.
Can you generate the documentation for the following Python 3 function def set_lastmodified_date(self, date=None): if date: match = re.match(DATE_REGEX, date) if not match: raise IOCParseError('last-modified date is not valid. Must be in the form YYYY-MM-DDTHH:MM:SS') ...
As a python code expert, you are capable of creating scripts from specifications.
def set_published_date(self, date=None): """ Set the published date of a IOC to the current date. User may specify the date they want to set as well. :param date: Date value to set the published date to. This should be in the xsdDate form. This defaults to the current date if ...
Write a Python 3 script for setting the published date of a IOC to the current date.
You are a Python code generator, capable of creating scripts from specifications.
def set_created_date(self, date=None): """ Set the created date of a IOC to the current date. User may specify the date they want to set as well. :param date: Date value to set the created date to. This should be in the xsdDate form. This defaults to the current date if it is ...
Can you implement a function in Python 3 that sets the created date of a IOC to the current date.
You are a Python code architect, reviewing and designing scalable and efficient code
def add_parameter(self, indicator_id, content, name='comment', ptype='string'): """ Add a a parameter to the IOC. :param indicator_id: The unique Indicator/IndicatorItem id the parameter is associated with. :param content: The value of the parameter. :param name: The name of the...
Can you create a Python 3 function that adds a parameter to the IOC.
You are a Python code architect, reviewing and designing scalable and efficient code
Add a Link metadata element to the IOC.
How would you explain what the following Python 3 function does def add_link(self, rel, value, href=None): links_node = self.metadata.find('links') if links_node is None: links_node = ioc_et.make_links_node() self.metadata.append(links_node) link_node = ioc_et.make_link_n...
As a Python code composer, you craft elegant and concise scripts.
Update the name of an IOC.
Given the following Python 3 function, write the documentation def update_name(self, name): short_desc_node = self.metadata.find('short_description') if short_desc_node is None: log.debug('Could not find short description node for [{}].'.format(str(self.iocid))) log.debug('Creati...
You are a Python code analyst, evaluating scripts for potential improvements.
def update_description(self, description): """ Update the description) of an IOC This creates the description node if it is not present. :param description: Value to set the description too :return: True """ desc_node = self.metadata.find('description') i...
Create a Python 3 function to update the description node of an IOC.
As a python code expert, you are capable of creating scripts from specifications.
Update link nodes based on the existing link / @rel value.
Can you generate a brief explanation for the following Python 3 code def update_link_rel_based(self, old_rel, new_rel=None, new_text=None, single_link=False): links = self.metadata.xpath('./links/link[@rel="{}"]'.format(old_rel)) if len(links) < 1: log.warning('No links with link/[@rel="{}"]...
As a Python code composer, you craft elegant and concise scripts.
def update_link_rewrite(self, old_rel, old_text, new_text, single_link=False): """ Rewrite the text() value of a link based on the link/@rel and link/text() value. This is similar to update_link_rel_based but users link/@rel AND link/text() values to determine which links have their lin...
Implement a function in Python 3 to rewrite the text() value of a link based on the link/@rel and link/text() value. This is similar to update_link_rel_based but users link/@rel AND link/text() values to determine which links have their link/@text() values updated. :param old_rel: The link/@rel value used to select lin...
You are a Python code architect, reviewing and designing scalable and efficient code
Updates the value of a single parameter in an Indicator or IndicatorItem node.
Given the following Python 3 function, write the documentation def update_parameter(self, parameter_id, content=None, name=None, param_type=None): if not (content or name or param_type): log.warning('Must specify at least the value/text(), param/@name or the value/@type values to update.') ...
You are a Python code generator, capable of creating scripts from specifications.
def remove_link(self, rel, value=None, href=None): """ Removes link nodes based on the function arguments. This can remove link nodes based on the following combinations of arguments: link/@rel link/@rel & link/text() link/@rel & link/@href link/@...
Can you implement a function in Python 3 that removes a link node based on the function arguments.
As a Python code composer, you craft elegant and concise scripts.
def remove_indicator(self, nid, prune=False): """ Removes a Indicator or IndicatorItem node from the IOC. By default, if nodes are removed, any children nodes are inherited by the removed node. It has the ability to delete all children Indicator and IndicatorItem nodes undernea...
How would you implement a function in Python 3 that removes a Indicator or IndicatorItem node from the IOC.
You are a Python code generator, capable of creating scripts from specifications.
def remove_parameter(self, param_id=None, name=None, ref_id=None, ): """ Removes parameters based on function arguments. This can remove parameters based on the following param values: param/@id param/@name param/@ref_id Each input is mutually exclus...
Write a Python 3 function for removing parameters based on function arguments. This can remove parameters based on the following param values: param/@id param/@name param/@ref_id Each input is mutually exclusive. Calling this function with multiple values set will cause an IOCParseError exception. Calling this function...
As a Python code analyst, you investigate and solve complex coding mysteries
def remove_name(self): """ Removes the name (short_description node) from the metadata node, if present. :return: True if the node is removed. False is the node is node is not present. """ short_description_node = self.metadata.find('short_description') if short_descrip...
Create a Python 3 function for removing the name from the metadata node.
As a Python code analyst, you investigate and solve complex coding mysteries
Removes the description node from the metadata node. Returns True if the description node is removed. Returns False if the description node is not present.
Can you generate a brief explanation for the following Python 3 code def remove_description(self): description_node = self.metadata.find('description') if description_node is not None: self.metadata.remove(description_node) return True return False
As a Python code analyst, you investigate and solve complex coding mysteries
Serialize the IOC to a. ioc file.
Can you generate a brief explanation for the following Python 3 code def write_ioc_to_file(self, output_dir=None, force=False): return write_ioc(self.root, output_dir, force=force)
You are a Python code analyst, evaluating scripts for potential improvements.
def display_ioc(self, width=120, sep=' ', params=False): """ Get a string representation of an IOC. :param width: Width to print the description too. :param sep: Separator used for displaying the contents of the criteria nodes. :param params: Boolean, set to True in order to di...
Write a Python 3 function that can get a string representation of an IOC.
You are a Python code generator, capable of creating scripts from specifications.
Get a text represention of the links node.
Can you tell what is the following Python 3 function doing def link_text(self): s = '' links_node = self.metadata.find('links') if links_node is None: return s links = links_node.getchildren() if links is None: return s s += 'IOC Links\n' f...
As a Python code translator, you convert algorithms and pseudocode into Python.
def criteria_text(self, sep=' ', params=False): """ Get a text representation of the criteria node. :param sep: Separator used to indent the contents of the node. :param params: Boolean, set to True in order to display node parameters. :return: """ s = '' ...
Can you create a Python 3 function that gets a text representation of the criteria node.
You are a Python code analyst, evaluating scripts for potential improvements.
Get the text for a given Indicator or IndicatorItem node.
Here you have a function in Python 3, explain what it does def get_node_text(self, node, depth, sep, params=False,): indent = sep * depth s = '' tag = node.tag if tag == 'Indicator': node_text = self.get_i_text(node) elif tag == 'IndicatorItem': node_text ...
As a Python code composer, you craft elegant and concise scripts.
def get_i_text(node): """ Get the text for an Indicator node. :param node: Indicator node. :return: """ if node.tag != 'Indicator': raise IOCParseError('Invalid tag: {}'.format(node.tag)) s = node.get('operator').upper() return s
Create a Python 3 function for getting the text for an Indicator node.
As a Python code composer, you craft elegant and concise scripts.
def get_ii_text(node): """ Get the text for IndicatorItem node. :param node: IndicatorItem node. :return: """ if node.tag != 'IndicatorItem': raise IOCParseError('Invalid tag: {}'.format(node.tag)) condition = node.attrib.get('condition') pres...
Can you write a function in Python 3 where it gets the text for IndicatorItem node.
You are a Python code generator, capable of creating scripts from specifications.
Get a list of parameters as text values for a given node id.
Can you tell what is the following Python 3 function doing def get_param_text(self, nid): r = [] params = self.parameters.xpath('.//param[@ref-id="{}"]'.format(nid)) if not params: return r for param in params: vnode = param.find('value') s = 'Paramete...
As a Python code translator, you convert algorithms and pseudocode into Python.
def read_xml(filename): """ Use et to read in a xml file, or string, into a Element object. :param filename: File to parse. :return: lxml._elementTree object or None """ parser = et.XMLParser(remove_blank_text=True) isfile=False try: isfile = os.path.exists(filename) except ...
Write a Python 3 script for reading in an XML file or string into a lxml. _elementTree object.
You are a Python code analyst, evaluating scripts for potential improvements.
def remove_namespace(doc, namespace): """ Takes in a ElementTree object and namespace value. The length of that namespace value is removed from all Element nodes within the document. This effectively removes the namespace from that document. :param doc: lxml.etree :param namespace: Namespace t...
Can you create a Python 3 function that removes the specified namespace from all Element nodes within a document.
As a Python code composer, you craft elegant and concise scripts.
Removes the namespace associated with the root node of a XML document and returns the original XML document.
Can you generate the documentation for the following Python 3 function def delete_namespace(parsed_xml): if parsed_xml.getroot().tag.startswith('{'): root = parsed_xml.getroot().tag end_ns = root.find('}') remove_namespace(parsed_xml, root[1:end_ns]) return parsed_xml
As a Python code composer, you craft elegant and concise scripts.
def insert(self, filename): """ Parses files to load them into memory and insert them into the class. :param filename: File or directory pointing to .ioc files. :return: A list of .ioc files which could not be parsed. """ errors = [] if os.path.isfile(filename): ...
Implement a function in Python 3 to parse the specified file into memory and inserts them into the class.
As a python code expert, you are capable of creating scripts from specifications.
Parses a file into a lxml. etree structure with namespaces removed.
Make a summary of the following Python 3 code def parse(self, fn): ioc_xml = xmlutils.read_xml_no_ns(fn) if not ioc_xml: return False root = ioc_xml.getroot() iocid = root.get('id', None) if not iocid: return False self.iocs[iocid] = ioc_xml ...
You are a Python code generator, capable of creating scripts from specifications.
Convert the iocs in self. iocs from OpenIOC 1. 0 to OpenIOC 1. 1 format.
Can you generate the documentation for the following Python 3 function def convert_to_11(self): if len(self) < 1: log.error('No iocs available to modify.') return False log.info('Converting IOCs from 1.0 to 1.1') errors = [] for iocid in self.iocs: ioc...
You are a Python code analyst, evaluating scripts for potential improvements.
This function recursively walks a branch of the Indicator node and converts it to a new node.
Can you generate the documentation for the following Python 3 function def convert_branch(self, old_node, new_node, comment_dict=None): expected_tag = 'Indicator' if old_node.tag != expected_tag: raise UpgradeError('old_node expected tag is [%s]' % expected_tag) if not comment_dict: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def insert(self, filename): """ Parses files to load them into memory and insert them into the class. :param filename: File or directory pointing to .ioc files. :return: A list of .ioc files which could not be parsed. """ errors = [] if os.path.isfile(filename): ...
Create a Python 3 function for parsing a file or directory containing IOCs and inserts them into the class.
You are a Python code analyst, evaluating scripts for potential improvements.
def parse(self, ioc_obj): """ parses an ioc to populate self.iocs and self.ioc_name :param ioc_obj: :return: """ if ioc_obj is None: return iocid = ioc_obj.iocid try: sd = ioc_obj.metadata.xpath('.//short_description/text()')[0] ...
Implement a function in Python 3 to parse an ioc to populate self. iocs and self. ioc_name .
You are a Python code analyst, evaluating scripts for potential improvements.
Register a callback function that is called after self. ioc_name is populated.
How would you explain what the following Python 3 function does def register_parser_callback(self, func): if hasattr(func, '__call__'): self.parser_callback = func log.debug('Set callback to {}'.format(func)) else: raise TypeError('Provided function is not callable: {...
You are a Python code architect, reviewing and designing scalable and efficient code
def create(self, permission): """ Create single permission for the given object. :param Permission permission: A single Permission object to be set. """ parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', 'single', {'id': self.parent_object.id}) ...
How would you implement a function in Python 3 that creates single permission for the given object.
You are a Python code analyst, evaluating scripts for potential improvements.
Sets the permissions for the object.
Can you tell what is the following Python 3 function doing def set(self, permissions): parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', 'single', {'id': self.parent_object.id}) target_url = parent_url + self.client.get_url_path(self._URL_KEY, 'PUT', 'multi') r = self...
You are a Python code analyst, evaluating scripts for potential improvements.
List permissions for the given object.
Can you generate a brief explanation for the following Python 3 code def list(self): parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', 'single', {'id': self.parent_object.id}) target_url = parent_url + self.client.get_url_path(self._URL_KEY, 'GET', 'multi') return bas...
You are a Python code architect, reviewing and designing scalable and efficient code
Get a specific permisison for the given object.
Can you generate a brief explanation for the following Python 3 code def get(self, permission_id, expand=[]): parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', 'single', {'id': self.parent_object.id}) target_url = parent_url + self.client.get_url_path( self._URL_K...
As a Python code composer, you craft elegant and concise scripts.
Read the configfile and return a dictionary with the content of the configpath file.
How would you explain what the following Python 3 function does def get_config(): configpath = get_configpath() if not configpath.exists(): raise IOError("Config file {} not found.".format(str(configpath))) else: config = configparser.ConfigParser() config.read(str(configpath)) ...
As a Python code composer, you craft elegant and concise scripts.
def set_database_path(dbfolder): """Use to write the database path into the config. Parameters ---------- dbfolder : str or pathlib.Path Path to where pyciss will store the ISS images it downloads and receives. """ configpath = get_configpath() try: d = get_config() exce...
Implement a function in Python 3 to use to write the database path into the config.
As a Python code analyst, you investigate and solve complex coding mysteries
Read dbroot folder from config and mkdir if required.
Can you tell what is the following Python 3 function doing def get_db_root(): "Read dbroot folder from config and mkdir if required." d = get_config() dbroot = Path(d['pyciss_db']['path']) dbroot.mkdir(exist_ok=True) return dbroot
You are a Python code architect, reviewing and designing scalable and efficient code
def print_db_stats(): """Print database stats. Returns ------- pd.DataFrame Table with the found data items per type. """ dbroot = get_db_root() n_ids = len(list(dbroot.glob("[N,W]*"))) print("Number of WACs and NACs in database: {}".format(n_ids)) print("These kind of data ...
Can you create a Python 3 function that prints database stats. Returns ------- pd. DataFrame pd. DataFrame
You are a Python code generator, capable of creating scripts from specifications.
def is_lossy(label): """Check Label file for the compression type. """ val = getkey(from_=label, keyword='INST_CMPRS_TYPE').decode().strip() if val == 'LOSSY': return True else: return False
Write a Python 3 function for checking if the label file is LOSSY.
You are a Python code architect, reviewing and designing scalable and efficient code
Download and calibrate in parallel.
Here you have a function in Python 3, explain what it does def download_and_calibrate_parallel(list_of_ids, n=None): setup_cluster(n_cores=n) c = Client() lbview = c.load_balanced_view() lbview.map_async(download_and_calibrate, list_of_ids) subprocess.Popen(["ipcluster", "stop", "--quiet"])
As a python code expert, you are capable of creating scripts from specifications.
def download_and_calibrate(img_id=None, overwrite=False, recalibrate=False, **kwargs): """Download and calibrate one or more image ids, in parallel. Parameters ---------- img_id : str or io.PathManager, optional If more than one item is in img_id, a parallel process is started overwrite: bo...
Create a Python 3 function for downloading and calibrate one or more image ids in parallel.
You are a Python code analyst, evaluating scripts for potential improvements.
def spiceinit(self): """Perform either normal spiceinit or one for ringdata. Note how Python name-spacing can distinguish between the method and the function with the same name. `spiceinit` from the outer namespace is the one imported from pysis. """ shape = "ringplane" ...
How would you implement a function in Python 3 that performs either normal spiceinit or outer spiceinit.
As a Python code composer, you craft elegant and concise scripts.
Check label for target name and fix if necessary.
Explain what the following Python 3 code does def check_label(self): if not self.is_ring_data: return targetname = getkey( from_=self.pm.raw_cub, grp="instrument", keyword="targetname" ) if targetname.lower() != "saturn": editlab( from...
As a python code expert, you are capable of creating scripts from specifications.
def _set_supported_content_type(self, content_types_supported): """ Checks and sets the supported content types configuration value. """ if not isinstance(content_types_supported, list): raise TypeError(("Settings 'READTIME_CONTENT_SUPPORT' must be" "a li...
Create a Python 3 function for checking and sets the supported content types configuration value.
You are a Python code generator, capable of creating scripts from specifications.
def _set_lang_settings(self, lang_settings): """ Checks and sets the per language WPM, singular and plural values. """ is_int = isinstance(lang_settings, int) is_dict = isinstance(lang_settings, dict) if not is_int and not is_dict: raise TypeError(("Settings 'READTIME...
How would you implement a function in Python 3 that checks and sets the per language WPM singular and plural values.
As a python code expert, you are capable of creating scripts from specifications.
def initialize_settings(self, sender): """ Initializes ReadTimeParser with configuration values set by the site author. """ try: self.initialized = True settings_content_types = sender.settings.get( 'READTIME_CONTENT_SUPPORT', self.content_type_su...
Write a Python 3 function for initializing the ReadTimeParser with the configuration values set by the readtime plugin.
You are a Python code generator, capable of creating scripts from specifications.
This function generates the read time for the content.
Explain what the following Python 3 code does def read_time(self, content): if get_class_name(content) in self.content_type_supported: # Exit if readtime is already set if hasattr(content, 'readtime'): return None default_lang_conf = self.lang_settings['defau...
You are a Python code generator, capable of creating scripts from specifications.
def pluralize(self, measure, singular, plural): """ Returns a string that contains the measure (amount) and its plural or singular form depending on the amount. Parameters: :param measure: Amount, value, always a numerical value :param singular: The singular form of the ...
Can you implement a function in Python 3 that returns a string that contains the measure and its plural form depending on the amount.
You are a Python code architect, reviewing and designing scalable and efficient code
Filterable list of Datasources for a Source.
Can you tell what is the following Python 3 function doing def list_datasources(self, source_id): target_url = self.client.get_url('DATASOURCE', 'GET', 'multi', {'source_id': source_id}) return base.Query(self.client.get_manager(Datasource), target_url)
As a python code expert, you are capable of creating scripts from specifications.
Get a Datasource object
Can you generate the documentation for the following Python 3 function def get_datasource(self, source_id, datasource_id): target_url = self.client.get_url('DATASOURCE', 'GET', 'single', {'source_id': source_id, 'datasource_id': datasource_id}) return self.client.get_manager(Datasource)._get(target_url)
You are a Python code analyst, evaluating scripts for potential improvements.
def list_scans(self, source_id=None): """ Filterable list of Scans for a Source. Ordered newest to oldest by default """ if source_id: target_url = self.client.get_url('SCAN', 'GET', 'multi', {'source_id': source_id}) else: target_url = self.client...
Implement a function in Python 3 to list all Scans for a Source.
As a Python code composer, you craft elegant and concise scripts.
def get_scan(self, source_id, scan_id): """ Get a Scan object :rtype: Scan """ target_url = self.client.get_url('SCAN', 'GET', 'single', {'source_id': source_id, 'scan_id': scan_id}) return self.client.get_manager(Scan)._get(target_url)
How would you code a function in Python 3 to get a Scan object from the given source and scan ID.
As a Python code composer, you craft elegant and concise scripts.
Get the log lines for a Scan
Explain what the following Python 3 code does def get_scan_log_lines(self, source_id, scan_id): return self.client.get_manager(Scan).get_log_lines(source_id=source_id, scan_id=scan_id)
As a Python code analyst, you investigate and solve complex coding mysteries
def start_scan(self, source_id): """ Start a new scan of a Source. :rtype: Scan """ target_url = self.client.get_url('SCAN', 'POST', 'create', {'source_id': source_id}) r = self.client.request('POST', target_url, json={}) return self.client.get_manager(Scan).crea...
How would you implement a function in Python 3 that starts a new scan of a Source.
As a Python code composer, you craft elegant and concise scripts.
Saves this Source into the server.
Can you generate the documentation for the following Python 3 function def save(self, with_data=False): r = self._client.request('PUT', self.url, json=self._serialize(with_data=with_data)) return self._deserialize(r.json(), self._manager)
As a python code expert, you are capable of creating scripts from specifications.
def add_file(self, fp, upload_path=None, content_type=None): """ Add a single file or archive to upload. To add metadata records with a file, add a .xml file with the same upload path basename eg. ``points-with-metadata.geojson`` & ``points-with-metadata.xml`` Datasource XML mus...
Create a Python 3 function for adding a single file or archive to the upload list.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_log_lines(self, source_id, scan_id): """ Get the log text for a scan object :rtype: Iterator over log lines. """ target_url = self.client.get_url('SCAN', 'GET', 'log', {'source_id': source_id, 'scan_id': scan_id}) r = self.client.request('GET', target_url, headers...
Write a Python 3 function for getting the log lines for a given source and scan.
As a Python code composer, you craft elegant and concise scripts.
Get the log lines for a scan object.
Can you generate a brief explanation for the following Python 3 code def get_log_lines(self): rel = self._client.reverse_url('SCAN', self.url) return self._manager.get_log_lines(**rel)
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the Creative Commons license for the given attributes.
Explain what the following Python 3 code does def get_creative_commons(self, slug, jurisdiction=None): if not slug.startswith('cc-by'): raise exceptions.ClientValidationError("slug needs to start with 'cc-by'") if jurisdiction is None: jurisdiction = '' target_url = sel...
As a Python code composer, you craft elegant and concise scripts.
Median Absolute Deviation of a sample.
How would you explain what the following Python 3 function does def mad(arr, relative=True): with warnings.catch_warnings(): warnings.simplefilter("ignore") med = np.nanmedian(arr, axis=1) mad = np.nanmedian(np.abs(arr - med[:, np.newaxis]), axis=1) if relative: return ma...
As a Python code analyst, you investigate and solve complex coding mysteries
Calculate an offset from the side of data so that at least 200 image pixels are in the MAD stats.
How would you explain what the following Python 3 function does def calc_offset(cube): i = 0 while pd.Series(cube.img[:, i]).count() < 200: i += 1 return max(i, 20)
You are a Python code generator, capable of creating scripts from specifications.
def imshow( self, data=None, save=False, ax=None, interpolation="none", extra_title=None, show_resonances="some", set_extent=True, equalized=False, rmin=None, rmax=None, savepath=".", **kwargs, ): """Powe...
Create a Python 3 function for plotting the image of the current object.
As a Python code composer, you craft elegant and concise scripts.
def _update_range(self, response): """ Update the query count property from the `X-Resource-Range` response header """ header_value = response.headers.get('x-resource-range', '') m = re.match(r'\d+-\d+/(\d+)$', header_value) if m: self._count = int(m.group(1)) else: ...
Can you create a Python 3 function that updates the query count property from the X - Resource - Range response header.
You are a Python code architect, reviewing and designing scalable and efficient code
def _to_url(self): """ Serialises this query into a request-able URL including parameters """ url = self._target_url params = collections.defaultdict(list, copy.deepcopy(self._filters)) if self._order_by is not None: params['sort'] = self._order_by for k, vl in self....
Write a Python 3 script for serialising this query into a request - able URL including parameters
As a Python code translator, you convert algorithms and pseudocode into Python.
def extra(self, **params): """ Set extra query parameters (eg. filter expressions/attributes that don't validate). Appends to any previous extras set. :rtype: Query """ q = self._clone() for key, value in params.items(): q._extra[key].append(value) ...
How would you implement a function in Python 3 that returns a new Query object with extra query parameters added.
As a Python code analyst, you investigate and solve complex coding mysteries
Add a filter to this query.
Can you generate the documentation for the following Python 3 function def filter(self, **filters): q = self._clone() for key, value in filters.items(): filter_key = re.split('__', key) filter_attr = filter_key[0] if filter_attr not in self._valid_filter_attrs: ...
You are a Python code generator, capable of creating scripts from specifications.
Sets the ordering for this query.
How would you explain what the following Python 3 function does def order_by(self, sort_key=None): if sort_key is not None: sort_attr = re.match(r'(-)?(.*)$', sort_key).group(2) if sort_attr not in self._valid_sort_attrs: raise ClientValidationError("Invalid ordering attr...
You are a Python code analyst, evaluating scripts for potential improvements.
Serialise this instance into JSON - style request data.
Can you tell what is the following Python 3 function doing def _serialize(self, skip_empty=True): skip = set(getattr(self._meta, 'serialize_skip', [])) r = {} for k, v in self.__dict__.items(): if k.startswith('_'): continue elif k in skip: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Serialize a single value.
Explain what the following Python 3 code does def _serialize_value(self, value): if isinstance(value, (list, tuple, set)): return [self._serialize_value(v) for v in value] elif isinstance(value, dict): return dict([(k, self._serialize_value(v)) for k, v in value.items()]) ...
As a python code expert, you are capable of creating scripts from specifications.
def refresh(self): """ Refresh this model from the server. Updates attributes with the server-defined values. This is useful where the Model instance came from a partial response (eg. a list query) and additional details are required. Existing attribute values will be o...
Implement a function in Python 3 to refresh the current model s attributes with the server - defined values.
As a Python code composer, you craft elegant and concise scripts.
Gets a crop feature
Given the following Python 3 function, write the documentation def get_feature(self, croplayer_id, cropfeature_id): target_url = self.client.get_url('CROPFEATURE', 'GET', 'single', {'croplayer_id': croplayer_id, 'cropfeature_id': cropfeature_id}) return self.client.get_manager(CropFeature)._get(target_u...
As a Python code translator, you convert algorithms and pseudocode into Python.
def create(self, export): """ Create and start processing a new Export. :param Export export: The Export to create. :rtype: Export """ target_url = self.client.get_url(self._URL_KEY, 'POST', 'create') r = self.client.request('POST', target_url, json=export._seria...
Create a Python 3 function for creating and start processing a new Export.
As a python code expert, you are capable of creating scripts from specifications.
Validates an Export. :param Export export: :rtype: ExportValidationResponse
Can you generate a brief explanation for the following Python 3 code def validate(self, export): target_url = self.client.get_url(self._URL_KEY, 'POST', 'validate') response_object = ExportValidationResponse() r = self.client.request('POST', target_url, json=export._serialize()) return r...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a raw options object
Can you generate the documentation for the following Python 3 function def _options(self): if self._options_cache is None: target_url = self.client.get_url(self._URL_KEY, 'OPTIONS', 'options') r = self.client.request('OPTIONS', target_url) self._options_cache = r.json() ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_formats(self): """ Returns a dictionary of format options keyed by data kind. .. code-block:: python { "vector": { "application/x-ogc-gpkg": "GeoPackage", "application/x-zipped-shp": "Shapefile", #....
How would you implement a function in Python 3 that returns a dictionary of format options keyed by data kind.
You are a Python code generator, capable of creating scripts from specifications.
def add_item(self, item, **options): """ Add a layer or table item to the export. :param Layer|Table item: The Layer or Table to add :rtype: self """ export_item = { "item": item.url, } export_item.update(options) self.items.append(exp...
Create a Python 3 function for adding a new item to the export.
As a Python code translator, you convert algorithms and pseudocode into Python.
Download the export archive.
How would you explain what the following Python 3 function does def download(self, path, progress_callback=None, chunk_size=1024**2): if not self.download_url or self.state != 'complete': raise DownloadError("Download not available") # ignore parsing the Content-Disposition header, since we...
You are a Python code analyst, evaluating scripts for potential improvements.
def from_requests_error(cls, err): """ Raises a subclass of ServerError based on the HTTP response code. """ import requests if isinstance(err, requests.HTTPError): status_code = err.response.status_code return HTTP_ERRORS.get(status_code, cls)(error=err, ...
Write a Python 3 function for creating an instance of the class from a requests. ServerError.
As a Python code composer, you craft elegant and concise scripts.
def console_create(): """ Command line tool (``koordinates-create-token``) used to create an API token. """ import argparse import getpass import re import sys import requests from six.moves import input from koordinates.client import Client parser = argparse.ArgumentParser(...
Implement a Python 3 function for commanding line tool (``koordinates-create-token``) used to create an API token.
You are a Python code architect, reviewing and designing scalable and efficient code
def create(self, token, email, password): """ Create a new token :param Token token: Token instance to create. :param str email: Email address of the Koordinates user account. :param str password: Koordinates user account password. """ target_url = self.client.ge...
Can you implement a function in Python 3 that creates a new token in Koordinates user account.
As a Python code analyst, you investigate and solve complex coding mysteries
Read in the whole cumulative index and return dataframe.
Explain what the following Python 3 code does def read_cumulative_iss_index(): "Read in the whole cumulative index and return dataframe." indexdir = get_index_dir() path = indexdir / "COISS_2999_index.hdf" try: df = pd.read_hdf(path, "df") except FileNotFoundError: path = indexdir /...
You are a Python code architect, reviewing and designing scalable and efficient code
def read_ring_images_index(): """Filter cumulative index for ring images. This is done by matching the column TARGET_DESC to contain the string 'ring' Returns ------- pandas.DataFrame data table containing only meta-data for ring images """ meta = read_cumulative_iss_index() ri...
Implement a function in Python 3 to filter cumulative index for ring images.
As a python code expert, you are capable of creating scripts from specifications.
filter for covered ringspan giver in km.
Make a summary of the following Python 3 code def filter_for_ringspan(clearnacs, spanlimit): "filter for covered ringspan, giver in km." delta = clearnacs.MAXIMUM_RING_RADIUS - clearnacs.MINIMUM_RING_RADIUS f = delta < spanlimit ringspan = clearnacs[f].copy() return ringspan
As a Python code analyst, you investigate and solve complex coding mysteries
Creates a new publish group.
Can you tell what is the following Python 3 function doing def create(self, publish): target_url = self.client.get_url('PUBLISH', 'POST', 'create') r = self.client.request('POST', target_url, json=publish._serialize()) return self.create_from_result(r.json())
You are a Python code generator, capable of creating scripts from specifications.
def cancel(self): """ Cancel a pending publish task """ target_url = self._client.get_url('PUBLISH', 'DELETE', 'single', {'id': self.id}) r = self._client.request('DELETE', target_url) logger.info("cancel(): %s", r.status_code)
Can you write a function in Python 3 where it cancels a pending publish task
You are a Python code generator, capable of creating scripts from specifications.
Returns the item models associated with this Publish group.
Here you have a function in Python 3, explain what it does def get_items(self): from .layers import Layer # no expansion support, just URLs results = [] for url in self.items: if '/layers/' in url: r = self._client.request('GET', url) results....
As a python code expert, you are capable of creating scripts from specifications.
def add_layer_item(self, layer): """ Adds a Layer to the publish group. """ if not layer.is_draft_version: raise ValueError("Layer isn't a draft version") self.items.append(layer.latest_version)
Implement a Python 3 function for adding a Layer to the publish group.
As a Python code analyst, you investigate and solve complex coding mysteries
Adds a Table to the publish group.
Given the following Python 3 function, write the documentation def add_table_item(self, table): if not table.is_draft_version: raise ValueError("Table isn't a draft version") self.items.append(table.latest_version)
You are a Python code generator, capable of creating scripts from specifications.