text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_settings(self, path): """ Load settings dict :param path: Path to settings file :type path: str | unicode :return: Loaded settings :rtype: dict :raises ...
res = self.load_file(path) if not isinstance(res, dict): raise TypeError("Expected settings to be dict") return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_settings(self, path, settings, readable=False): """ Save settings to file :param path: File path to save :type path: str | unicode :param settings: Sett...
if not isinstance(settings, dict): raise TypeError("Expected settings to be dict") return self.save_file(path, settings, readable)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name(self): """ Get the module name :return: Module name :rtype: str | unicode """
res = type(self).__name__ if self._id: res += ".{}".format(self._id) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_function_name(self): """ Get function name of calling method :return: The name of the calling function (expected to be called in self.error/debug/..) :r...
fname = inspect.getframeinfo(inspect.stack()[2][0]).function if fname == "<module>": return "" else: return fname
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_yara(self, output_file): """ Write out yara signatures to a file. """
fout = open(output_file, 'wb') fout.write('\n') for iocid in self.yara_signatures: signature = self.yara_signatures[iocid] fout.write(signature) fout.write('\n') fout.close() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_makedirs(fdir): """ Make an arbitrary directory. This is safe to call for Python 2 users. :param fdir: Directory path to make. :return: """
if os.path.isdir(fdir): pass # print 'dir already exists: %s' % str(dir) else: try: os.makedirs(fdir) except WindowsError as e: if 'Cannot create a file when that file already exists' in e: log.debug('relevant dir already exists') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_iocs(self, directory=None, source=None): """ Serializes IOCs to a directory. :param directory: Directory to write IOCs to. If not provided, the current...
""" if directory is None, write the iocs to the current working directory source: allows specifying a different dictionry of elmentTree ioc objects """ if not source: source = self.iocs_10 if len(source) < 1: log.error('no iocs available to writ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_pruned_iocs(self, directory=None, pruned_source=None): """ Writes IOCs to a directory that have been pruned of some or all IOCs. :param directory: Dire...
""" write_pruned_iocs to a directory if directory is None, write the iocs to the current working directory """ if pruned_source is None: pruned_source = self.pruned_11_iocs if len(pruned_source) < 1: log.error('no iocs available to write out') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_indicator_node(operator, nid=None): """ This makes a Indicator node element. These allow the construction of a logic tree within the IOC. :param operato...
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_node.attrib['id'] = nid else: i_node.attrib['id'] = ioc_et.get_guid() i_node.attrib['ope...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_indicatoritem_node(condition, document, search, content_type, content, preserve_case=False, negate=False, context_type='mir', nid=None): """ This makes ...
# validate condition if condition not in VALID_INDICATORITEM_CONDITIONS: raise ValueError('Invalid IndicatorItem condition [{}]'.format(condition)) ii_node = et.Element('IndicatorItem') if nid: ii_node.attrib['id'] = nid else: ii_node.attrib['id'] = ioc_et.get_guid() ii_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_top_level_indicator_node(root_node): """ This returns the first top level Indicator node under the criteria node. :param root_node: Root node of an etree...
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('No top level Indicator node found.') return None elif len(elems) > 1: log.warning('M...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 wri...
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 PyBroadException try: encoding = tree.docinfo.encoding except: log.debug('Failed...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
parsed_xml = xmlutils.read_xml_no_ns(fn) if not parsed_xml: raise IOCParseError('Error occured parsing XML') root = parsed_xml.getroot() metadata_node = root.find('metadata') top_level_indicator = get_top_level_indicator_node(root) parameters_node = root.find...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_ioc(name=None, description='Automatically generated IOC', author='IOC_api', links=None, keywords=None, iocid=None): """ This generates all parts of an I...
root = ioc_et.make_ioc_root(iocid) root.append(ioc_et.make_metadata_node(name, description, author, links, keywords)) metadata_node = root.find('metadata') top_level_indicator = make_indicator_node('OR') parameters_node = (ioc_et.make_parameters_node()) root.append(ioc_e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_lastmodified_date(self, date=None): """ Set the last modified date of a IOC to the current date. User may specify the date they want to set as well. :par...
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') ioc_et.set_root_lastmodified(self.root, date) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if date: match = re.match(DATE_REGEX, date) if not match: raise IOCParseError('Published date is not valid. Must be in the form YYYY-MM-DDTHH:MM:SS') ioc_et.set_root_published_date(self.root, date) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: Da...
if date: match = re.match(DATE_REGEX, date) if not match: raise IOCParseError('Created date is not valid. Must be in the form YYYY-MM-DDTHH:MM:SS') # XXX can this use self.metadata? ioc_et.set_root_created_date(self.root, date) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_parameter(self, indicator_id, content, name='comment', ptype='string'): """ Add a a parameter to the IOC. :param indicator_id: The unique Indicator/Indic...
parameters_node = self.parameters criteria_node = self.top_level_indicator.getparent() # first check for duplicate id,name pairs elems = parameters_node.xpath('.//param[@ref-id="{}" and @name="{}"]'.format(indicator_id, name)) if len(elems) > 0: # there is no act...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_link(self, rel, value, href=None): """ Add a Link metadata element to the IOC. :param rel: Type of the link. :param value: Value of the link text. :param...
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_node(rel, value, href) links_node.append(link_node) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_description(self, description): """ Update the description) of an IOC This creates the description node if it is not present. :param description: Valu...
desc_node = self.metadata.find('description') if desc_node is None: log.debug('Could not find short description node for [{}].'.format(str(self.iocid))) log.debug('Creating & inserting the short description node') desc_node = ioc_et.make_description_node(description)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_parameter(self, parameter_id, content=None, name=None, param_type=None): """ Updates the parameter attached to an Indicator or IndicatorItem node. All...
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.') return False parameters_node = self.parameters elems = parameters_node.xpath('.//param[@id="{}"]'.format(parameter_id)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 comb...
links_node = self.metadata.find('links') if links_node is None: log.warning('No links node present') return False counter = 0 links = links_node.xpath('.//link[@rel="{}"]'.format(rel)) for link in links: if value and href: if l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ar...
try: node_to_remove = self.top_level_indicator.xpath( '//IndicatorItem[@id="{}"]|//Indicator[@id="{}"]'.format(str(nid), str(nid)))[0] except IndexError: log.exception('Node [{}] not present'.format(nid)) return False if node_to_remove.tag == ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
l = [] if param_id: l.append('param_id') if name: l.append('name') if ref_id: l.append('ref_id') if len(l) > 1: raise IOCParseError('Must specify only param_id, name or ref_id. Specified {}'.format(str(l))) elif len(l) < 1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_description(self): """ Removes the description node from the metadata node, if present. :return: Returns True if the description node is removed. Retu...
description_node = self.metadata.find('description') if description_node is not None: self.metadata.remove(description_node) return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_ioc_to_file(self, output_dir=None, force=False): """ Serialize the IOC to a .ioc file. :param output_dir: Directory to write the ioc out to. default is...
return write_ioc(self.root, output_dir, force=force)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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:...
s = 'Name: {}\n'.format(self.metadata.findtext('short_description', default='No Name')) s += 'ID: {}\n'.format(self.root.attrib.get('id')) s += 'Created: {}\n'.format(self.metadata.findtext('authored_date', default='No authored_date')) s += 'Updated: {}\n\n'.format(self.root.attrib.get(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def link_text(self): """ Get a text represention of the links node. :return: """
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' for link in links: rel = link.attrib.get('rel', 'No Rel') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
s = '' criteria_node = self.root.find('criteria') if criteria_node is None: return s node_texts = [] for node in criteria_node.getchildren(): nt = self.get_node_text(node, depth=0, sep=sep, params=params) node_texts.append(nt) s = '\n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_node_text(self, node, depth, sep, params=False,): """ Get the text for a given Indicator or IndicatorItem node. This does walk an IndicatorItem node to g...
indent = sep * depth s = '' tag = node.tag if tag == 'Indicator': node_text = self.get_i_text(node) elif tag == 'IndicatorItem': node_text = self.get_ii_text(node) else: raise IOCParseError('Invalid node encountered: {}'.format(tag)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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') preserve_case = node.attrib.get('preserve-case', '') negate = node.attrib.get('negate', '') content = node.findtext('Content') sea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_param_text(self, nid): """ Get a list of parameters as text values for a given node id. :param nid: id to look for. :return: """
r = [] params = self.parameters.xpath('.//param[@ref-id="{}"]'.format(nid)) if not params: return r for param in params: vnode = param.find('value') s = 'Parameter: {}, type:{}, value: {}'.format(param.attrib.get('name'), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
parser = et.XMLParser(remove_blank_text=True) isfile=False try: isfile = os.path.exists(filename) except ValueError as e: if 'path too long for Windows' in str(e): pass else: raise try: if isfile: return et.parse(filename, parser) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
# http://homework.nwsnet.de/products/45be_remove-namespace-in-an-xml-document-using-elementtree # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, inc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_namespace(parsed_xml): """ Identifies the namespace associated with the root node of a XML document and removes that names from the document. :param p...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, fn): """ Parses a file into a lxml.etree structure with namespaces remove. This tree is added to self.iocs. :param fn: File to parse. :return: ""...
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 return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_to_11(self): """ converts the iocs in self.iocs from openioc 1.0 to openioc 1.1 format. the converted iocs are stored in the dictionary self.iocs_11 ...
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_xml = self.iocs[iocid] root = ioc_xml.getroot() if root.tag != 'ioc': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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] except IndexError: sd = 'NoName' if iocid in self.iocs: msg = 'duplicate IOC UUID [{}] [orig_shortName: {}][new_sho...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_parser_callback(self, func): """ Register a callback function that is called after self.iocs and self.ioc_name is populated. This is intended for us...
if hasattr(func, '__call__'): self.parser_callback = func log.debug('Set callback to {}'.format(func)) else: raise TypeError('Provided function is not callable: {}'.format(func))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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}) target_url = parent_url + self.client.get_url_path(self._URL_KEY, 'POST', 'single') r = self.client.request('POST', target_url, json=permission._serialize()) return per...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, permissions): """ Set the object permissions. If the parent object already has permissions, they will be overwritten. :param [] permissions: A grou...
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.client.request('PUT', target_url, json=permissions) if r.status_code != 201: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(self): """ List permissions for the given object. """
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 base.Query(self, target_url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, permission_id, expand=[]): """ List a specific permisison for the given object. :param str permission_id: the id of the Permission to be listed. ""...
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', 'single', {'permission_id': permission_id}) return self._get(target_url, expand=expand)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config(): """Read the configfile and return config dict. Returns ------- dict Dictionary with the content of the configpath file. """
configpath = get_configpath() if not configpath.exists(): raise IOError("Config file {} not found.".format(str(configpath))) else: config = configparser.ConfigParser() config.read(str(configpath)) return config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
configpath = get_configpath() try: d = get_config() except IOError: d = configparser.ConfigParser() d['pyciss_db'] = {} d['pyciss_db']['path'] = dbfolder with configpath.open('w') as f: d.write(f) print("Saved database path into {}.".format(configpath))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 are in the database: (returning pd.DataFrame)") d = {} for key, val in PathManager.extensions.items(): d[key] = [len(list(dbroot.glob(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_and_calibrate_parallel(list_of_ids, n=None): """Download and calibrate in parallel. Parameters list_of_ids : list, optional container with img_ids t...
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"])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_and_calibrate(img_id=None, overwrite=False, recalibrate=False, **kwargs): """Download and calibrate one or more image ids, in parallel. Parameters i...
if isinstance(img_id, io.PathManager): pm = img_id else: # get a PathManager object that knows where your data is or should be logger.debug("Creating Pathmanager object") pm = io.PathManager(img_id) if not pm.raw_image.exists() or overwrite is True: logger.debug("Do...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spiceinit(self): """Perform either normal spiceinit or one for ringdata. Note how Python name-spacing can distinguish between the method and the function wit...
shape = "ringplane" if self.is_ring_data else None spiceinit(from_=self.pm.raw_cub, cksmithed="yes", spksmithed="yes", shape=shape) logger.info("spiceinit done.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_label(self): """ Check label for target and fix if necessary. Forcing the target name to Saturn here, because some observations of the rings have moons...
if not self.is_ring_data: return targetname = getkey( from_=self.pm.raw_cub, grp="instrument", keyword="targetname" ) if targetname.lower() != "saturn": editlab( from_=self.pm.raw_cub, options="modkey", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 list of content types.")) self.content_type_supported = content_types_supported
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_WPM' must be either an int," "or a dict with settings per language.")) # For backwards compatab...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_supported) self._set_supported_content_type(settings_content_types) lang_settings = sender.settings.get( 'RE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_time(self, content): """ Core function used to generate the read_time for content. Parameters: :param content: Instance of pelican.content.Content Retur...
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['default'] lang_conf = self.lang_settings.get(content.lang, default_l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_datasources(self, source_id): """ Filterable list of Datasources for a Source. """
target_url = self.client.get_url('DATASOURCE', 'GET', 'multi', {'source_id': source_id}) return base.Query(self.client.get_manager(Datasource), target_url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_datasource(self, source_id, datasource_id): """ Get a Datasource object :rtype: Datasource """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.get_ulr('SCAN', 'GET', 'all') return base.Query(self.client.get_manager(Scan), target_url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_scan_log_lines(self, source_id, scan_id): """ Get the log text for a Scan :rtype: Iterator over log lines. """
return self.client.get_manager(Scan).get_log_lines(source_id=source_id, scan_id=scan_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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).create_from_result(r.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, with_data=False): """ Edits this Source """
r = self._client.request('PUT', self.url, json=self._serialize(with_data=with_data)) return self._deserialize(r.json(), self._manager)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self): """ Delete this source """
r = self._client.request('DELETE', self.url) logger.info("delete(): %s", r.status_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 wit...
if isinstance(fp, six.string_types): # path if not os.path.isfile(fp): raise ClientValidationError("Invalid file: %s", fp) if not upload_path: upload_path = os.path.split(fp)[1] else: # file-like object if not u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_log_lines(self): """ Get the log text for a scan object :rtype: Iterator over log lines. """
rel = self._client.reverse_url('SCAN', self.url) return self._manager.get_log_lines(**rel)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_creative_commons(self, slug, jurisdiction=None): """Returns the Creative Commons license for the given attributes. :param str slug: the type of Creative ...
if not slug.startswith('cc-by'): raise exceptions.ClientValidationError("slug needs to start with 'cc-by'") if jurisdiction is None: jurisdiction = '' target_url = self.client.get_url(self._URL_KEY, 'GET', 'cc', {'slug': slug, 'jurisdiction': jurisdiction}) ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_offset(cube): """Calculate an offset. Calculate offset from the side of data so that at least 200 image pixels are in the MAD stats. Parameters ========...
i = 0 while pd.Series(cube.img[:, i]).count() < 200: i += 1 return max(i, 20)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def imshow( self, data=None, save=False, ax=None, interpolation="none", extra_title=None, show_resonances="some", set_extent=True, equalized=False, rmin=None, rma...
if data is None: data = self.img if self.resonance_axis is not None: logger.debug("removing resonance_axis") self.resonance_axis.remove() if equalized: data = np.nan_to_num(data) data[data < 0] = 0 data = exposure.equalize_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: self._count = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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._extra.items(): params[k] += vl if params: url += "?" + urllib.parse...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, **filters): """ Add a filter to this query. Appends to any previous filters set. :rtype: Query """
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: raise ClientValidationError("Invalid filter attribute: %s" % key) # we use ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _deserialize(self, data): """ Deserialise from JSON response data. String items named ``*_at`` are turned into dates. Filters out: * attribute names in ``Met...
if not isinstance(data, dict): raise ValueError("Need to deserialize from a dict") try: skip = set(getattr(self._meta, 'deserialize_skip', [])) except AttributeError: # _meta not available skip = [] for key, value in data.items(): if ke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _serialize(self, skip_empty=True): """ Serialise this instance into JSON-style request data. Filters out: * attribute names starting with ``_`` * attribute v...
skip = set(getattr(self._meta, 'serialize_skip', [])) r = {} for k, v in self.__dict__.items(): if k.startswith('_'): continue elif k in skip: continue elif v is None and skip_empty: continue elif i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
r = self._client.request('GET', self.url) return self._deserialize(r.json(), self._manager)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_feature(self, croplayer_id, cropfeature_id): """ Gets a crop feature :param int croplayer_id: ID of a cropping layer :param int cropfeature_id: ID of a c...
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_url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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._serialize()) return export._deserialize(r.json(), self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, export): """ Validates an Export. :param Export export: :rtype: ExportValidationResponse """
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 response_object._deserialize(r.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _options(self): """ Returns a raw options object :rtype: dict """
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() return self._options_cache
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_formats(self): """ Returns a dictionary of format options keyed by data kind. .. code-block:: python { "vector": { "application/x-ogc-gpkg": "GeoPackage"...
format_opts = self._options()['actions']['POST']['formats']['children'] r = {} for kind, kind_opts in format_opts.items(): r[kind] = {c['value']: c['display_name'] for c in kind_opts['choices']} return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(export_item) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(self, path, progress_callback=None, chunk_size=1024**2): """ Download the export archive. .. warning:: If you pass this function an open file-like o...
if not self.download_url or self.state != 'complete': raise DownloadError("Download not available") # ignore parsing the Content-Disposition header, since we know the name download_filename = "{}.zip".format(self.name) fd = None if isinstance(getattr(path, 'write',...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, response=err.response) else: return cls(error=err)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, id ): """ Delete a token """
target_url = self.client.get_url('TOKEN', 'DELETE', 'single', {'id':id}) r = self.client.request('DELETE', target_url, headers={'Content-type': 'application/json'}) r.raise_for_status()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
target_url = self.client.get_url('TOKEN', 'POST', 'create') post_data = { 'grant_type': 'password', 'username': email, 'password': password, 'name': token.name, } if getattr(token, 'scope', None): post_data['scope'] = token.sco...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 / "cumindex.hdf" df = pd.read_hdf(path,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 --...
meta = read_cumulative_iss_index() ringfilter = meta.TARGET_DESC.str.contains("ring", case=False) return meta[ringfilter]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, publish): """ Creates a new publish group. """
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())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_items(self): """ Return the item models associated with this Publish group. """
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.append(self._client.get_manager(Layer).create_from_result(r.json())) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_table_item(self, table): """ Adds a Table to the publish group. """
if not table.is_draft_version: raise ValueError("Table isn't a draft version") self.items.append(table.latest_version)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_ticks_to_x(ax, newticks, newnames): """Add new ticks to an axis. I use this for the right-hand plotting of resonance names in my plots. """
ticks = list(ax.get_xticks()) ticks.extend(newticks) ax.set_xticks(ticks) names = list(ax.get_xticklabels()) names.extend(newnames) ax.set_xticklabels(names)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, set): """ Creates a new Set. """
target_url = self.client.get_url('SET', 'POST', 'create') r = self.client.request('POST', target_url, json=set._serialize()) return set._deserialize(r.json(), self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, parent_url, fp): """ If the parent object already has XML metadata, it will be overwritten. Accepts XML metadata in any of the three supported form...
url = parent_url + self.client.get_url_path('METADATA', 'POST', 'set', {}) r = self.client.request('POST', url, data=fp, headers={'Content-Type': 'text/xml'}) if r.status_code not in [200, 201]: raise exceptions.ServerError("Expected success response, got %s: %s" % (r.status_code, u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_xml(self, fp, format=FORMAT_NATIVE): """ Returns the XML metadata for this source, converted to the requested format. Converted metadata may not contain ...
r = self._client.request('GET', getattr(self, format), stream=True) filename = stream.stream_response_to_file(r, path=fp) return filename
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_formats(self): """ Return the available format names for this metadata """
formats = [] for key in (self.FORMAT_DC, self.FORMAT_FGDC, self.FORMAT_ISO): if hasattr(self, key): formats.append(key) return formats
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_bound(method): """ Decorator that asserts the model instance is bound. Requires: 1. an ``id`` attribute 2. a ``url`` attribute 2. a manager set """
@functools.wraps(method) def wrapper(self, *args, **kwargs): if not self._is_bound: raise ValueError("%r must be bound to call %s()" % (self, method.__name__)) return method(self, *args, **kwargs) return wrapper