repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
sequencelengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
sequencelengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
mandiant/ioc_writer
ioc_writer/ioc_api.py
write_ioc
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 force: If set, skip the root node tag check. :return: True, unless an error occurs while writing the IOC. """ 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 to get encoding from docinfo') encoding = default_encoding ioc_id = root.attrib['id'] fn = ioc_id + '.ioc' if output_dir: fn = os.path.join(output_dir, fn) else: fn = os.path.join(os.getcwd(), fn) try: with open(fn, 'wb') as fout: fout.write(et.tostring(tree, encoding=encoding, xml_declaration=True, pretty_print=True)) except (IOError, OSError): log.exception('Failed to write out IOC') return False except: raise return True
python
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 force: If set, skip the root node tag check. :return: True, unless an error occurs while writing the IOC. """ 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 to get encoding from docinfo') encoding = default_encoding ioc_id = root.attrib['id'] fn = ioc_id + '.ioc' if output_dir: fn = os.path.join(output_dir, fn) else: fn = os.path.join(os.getcwd(), fn) try: with open(fn, 'wb') as fout: fout.write(et.tostring(tree, encoding=encoding, xml_declaration=True, pretty_print=True)) except (IOError, OSError): log.exception('Failed to write out IOC') return False except: raise return True
[ "def", "write_ioc", "(", "root", ",", "output_dir", "=", "None", ",", "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 PyBroadException", "try", ":", "encoding", "=", "tree", ".", "docinfo", ".", "encoding", "except", ":", "log", ".", "debug", "(", "'Failed to get encoding from docinfo'", ")", "encoding", "=", "default_encoding", "ioc_id", "=", "root", ".", "attrib", "[", "'id'", "]", "fn", "=", "ioc_id", "+", "'.ioc'", "if", "output_dir", ":", "fn", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "fn", ")", "else", ":", "fn", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "fn", ")", "try", ":", "with", "open", "(", "fn", ",", "'wb'", ")", "as", "fout", ":", "fout", ".", "write", "(", "et", ".", "tostring", "(", "tree", ",", "encoding", "=", "encoding", ",", "xml_declaration", "=", "True", ",", "pretty_print", "=", "True", ")", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "log", ".", "exception", "(", "'Failed to write out IOC'", ")", "return", "False", "except", ":", "raise", "return", "True" ]
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 force: If set, skip the root node tag check. :return: True, unless an error occurs while writing the IOC.
[ "Serialize", "an", "IOC", "as", "defined", "by", "a", "set", "of", "etree", "Elements", "to", "a", ".", "IOC", "file", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L885-L919
mandiant/ioc_writer
ioc_writer/ioc_api.py
write_ioc_string
def write_ioc_string(root, force=False): """ Serialize an IOC, as defined by a set of etree Elements, to a String. :param root: etree Element to serialize. Should have the tag 'OpenIOC' :param force: Skip the root node tag check. :return: """ 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 to get encoding from docinfo') encoding = default_encoding return et.tostring(tree, encoding=encoding, xml_declaration=True, pretty_print=True)
python
def write_ioc_string(root, force=False): """ Serialize an IOC, as defined by a set of etree Elements, to a String. :param root: etree Element to serialize. Should have the tag 'OpenIOC' :param force: Skip the root node tag check. :return: """ 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 to get encoding from docinfo') encoding = default_encoding return et.tostring(tree, encoding=encoding, xml_declaration=True, pretty_print=True)
[ "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 PyBroadException", "try", ":", "encoding", "=", "tree", ".", "docinfo", ".", "encoding", "except", ":", "log", ".", "debug", "(", "'Failed to get encoding from docinfo'", ")", "encoding", "=", "default_encoding", "return", "et", ".", "tostring", "(", "tree", ",", "encoding", "=", "encoding", ",", "xml_declaration", "=", "True", ",", "pretty_print", "=", "True", ")" ]
Serialize an IOC, as defined by a set of etree Elements, to a String. :param root: etree Element to serialize. Should have the tag 'OpenIOC' :param force: Skip the root node tag check. :return:
[ "Serialize", "an", "IOC", "as", "defined", "by", "a", "set", "of", "etree", "Elements", "to", "a", "String", ".", ":", "param", "root", ":", "etree", "Element", "to", "serialize", ".", "Should", "have", "the", "tag", "OpenIOC", ":", "param", "force", ":", "Skip", "the", "root", "node", "tag", "check", ".", ":", "return", ":" ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L922-L940
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.open_ioc
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 path to a file to open, or a string containing XML representing an IOC. :return: a tuple containing three elementTree Element objects The first element, the root, contains the entire IOC itself. The second element, the top level OR indicator, allows the user to add additional IndicatorItem or Indicator nodes to the IOC easily. The third element, the parameters node, allows the user to quickly parse the parameters. """ 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('parameters') if parameters_node is None: # parameters node is not required by schema; but we add it if it is not present parameters_node = ioc_et.make_parameters_node() root.append(parameters_node) return root, metadata_node, top_level_indicator, parameters_node
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 path to a file to open, or a string containing XML representing an IOC. :return: a tuple containing three elementTree Element objects The first element, the root, contains the entire IOC itself. The second element, the top level OR indicator, allows the user to add additional IndicatorItem or Indicator nodes to the IOC easily. The third element, the parameters node, allows the user to quickly parse the parameters. """ 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('parameters') if parameters_node is None: # parameters node is not required by schema; but we add it if it is not present parameters_node = ioc_et.make_parameters_node() root.append(parameters_node) return root, metadata_node, top_level_indicator, parameters_node
[ "def", "open_ioc", "(", "fn", ")", ":", "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", "(", "'parameters'", ")", "if", "parameters_node", "is", "None", ":", "# parameters node is not required by schema; but we add it if it is not present", "parameters_node", "=", "ioc_et", ".", "make_parameters_node", "(", ")", "root", ".", "append", "(", "parameters_node", ")", "return", "root", ",", "metadata_node", ",", "top_level_indicator", ",", "parameters_node" ]
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 path to a file to open, or a string containing XML representing an IOC. :return: a tuple containing three elementTree Element objects The first element, the root, contains the entire IOC itself. The second element, the top level OR indicator, allows the user to add additional IndicatorItem or Indicator nodes to the IOC easily. The third element, the parameters node, allows the user to quickly parse the parameters.
[ "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", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L108-L135
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.make_ioc
def make_ioc(name=None, description='Automatically generated IOC', author='IOC_api', links=None, keywords=None, iocid=None): """ This generates all parts of an IOC, but without any definition. This is a helper function used by __init__. :param name: string, Name of the ioc :param description: string, description of the ioc :param author: string, author name/email address :param links: ist of tuples. Each tuple should be in the form (rel, href, value). :param keywords: string. This is normally a space delimited string of values that may be used as keywords :param iocid: GUID for the IOC. This should not be specified under normal circumstances. :return: a tuple containing three elementTree Element objects The first element, the root, contains the entire IOC itself. The second element, the top level OR indicator, allows the user to add additional IndicatorItem or Indicator nodes to the IOC easily. The third element, the parameters node, allows the user to quickly parse the parameters. """ 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_et.make_criteria_node(top_level_indicator)) root.append(parameters_node) ioc_et.set_root_lastmodified(root) return root, metadata_node, top_level_indicator, parameters_node
python
def make_ioc(name=None, description='Automatically generated IOC', author='IOC_api', links=None, keywords=None, iocid=None): """ This generates all parts of an IOC, but without any definition. This is a helper function used by __init__. :param name: string, Name of the ioc :param description: string, description of the ioc :param author: string, author name/email address :param links: ist of tuples. Each tuple should be in the form (rel, href, value). :param keywords: string. This is normally a space delimited string of values that may be used as keywords :param iocid: GUID for the IOC. This should not be specified under normal circumstances. :return: a tuple containing three elementTree Element objects The first element, the root, contains the entire IOC itself. The second element, the top level OR indicator, allows the user to add additional IndicatorItem or Indicator nodes to the IOC easily. The third element, the parameters node, allows the user to quickly parse the parameters. """ 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_et.make_criteria_node(top_level_indicator)) root.append(parameters_node) ioc_et.set_root_lastmodified(root) return root, metadata_node, top_level_indicator, parameters_node
[ "def", "make_ioc", "(", "name", "=", "None", ",", "description", "=", "'Automatically generated IOC'", ",", "author", "=", "'IOC_api'", ",", "links", "=", "None", ",", "keywords", "=", "None", ",", "iocid", "=", "None", ")", ":", "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_et", ".", "make_criteria_node", "(", "top_level_indicator", ")", ")", "root", ".", "append", "(", "parameters_node", ")", "ioc_et", ".", "set_root_lastmodified", "(", "root", ")", "return", "root", ",", "metadata_node", ",", "top_level_indicator", ",", "parameters_node" ]
This generates all parts of an IOC, but without any definition. This is a helper function used by __init__. :param name: string, Name of the ioc :param description: string, description of the ioc :param author: string, author name/email address :param links: ist of tuples. Each tuple should be in the form (rel, href, value). :param keywords: string. This is normally a space delimited string of values that may be used as keywords :param iocid: GUID for the IOC. This should not be specified under normal circumstances. :return: a tuple containing three elementTree Element objects The first element, the root, contains the entire IOC itself. The second element, the top level OR indicator, allows the user to add additional IndicatorItem or Indicator nodes to the IOC easily. The third element, the parameters node, allows the user to quickly parse the parameters.
[ "This", "generates", "all", "parts", "of", "an", "IOC", "but", "without", "any", "definition", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L138-L170
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.set_lastmodified_date
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. :param date: Date value to set the last modified date to. This should be in the xsdDate form. This defaults to the current date if it is not provided. xsdDate Form: YYYY-MM-DDTHH:MM:SS :return: True :raises: IOCParseError if date format is not valid. """ 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
python
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. :param date: Date value to set the last modified date to. This should be in the xsdDate form. This defaults to the current date if it is not provided. xsdDate Form: YYYY-MM-DDTHH:MM:SS :return: True :raises: IOCParseError if date format is not valid. """ 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
[ "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'", ")", "ioc_et", ".", "set_root_lastmodified", "(", "self", ".", "root", ",", "date", ")", "return", "True" ]
Set the last modified 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 last modified date to. This should be in the xsdDate form. This defaults to the current date if it is not provided. xsdDate Form: YYYY-MM-DDTHH:MM:SS :return: True :raises: IOCParseError if date format is not valid.
[ "Set", "the", "last", "modified", "date", "of", "a", "IOC", "to", "the", "current", "date", ".", "User", "may", "specify", "the", "date", "they", "want", "to", "set", "as", "well", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L172-L188
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.set_published_date
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 it is not provided. xsdDate Form: YYYY-MM-DDTHH:MM:SS :return: True :raises: IOCParseError if date format is not valid. """ 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
python
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 it is not provided. xsdDate Form: YYYY-MM-DDTHH:MM:SS :return: True :raises: IOCParseError if date format is not valid. """ 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
[ "def", "set_published_date", "(", "self", ",", "date", "=", "None", ")", ":", "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" ]
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 it is not provided. xsdDate Form: YYYY-MM-DDTHH:MM:SS :return: True :raises: IOCParseError if date format is not valid.
[ "Set", "the", "published", "date", "of", "a", "IOC", "to", "the", "current", "date", ".", "User", "may", "specify", "the", "date", "they", "want", "to", "set", "as", "well", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L190-L206
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.set_created_date
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 not provided. xsdDate form: YYYY-MM-DDTHH:MM:SS :return: True :raises: IOCParseError if date format is not valid. """ 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
python
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 not provided. xsdDate form: YYYY-MM-DDTHH:MM:SS :return: True :raises: IOCParseError if date format is not valid. """ 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
[ "def", "set_created_date", "(", "self", ",", "date", "=", "None", ")", ":", "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" ]
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 not provided. xsdDate form: YYYY-MM-DDTHH:MM:SS :return: True :raises: IOCParseError if date format is not valid.
[ "Set", "the", "created", "date", "of", "a", "IOC", "to", "the", "current", "date", ".", "User", "may", "specify", "the", "date", "they", "want", "to", "set", "as", "well", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L208-L225
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.add_parameter
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 parameter. :param ptype: The type of the parameter content. :return: True :raises: IOCParseError if the indicator_id is not associated with a Indicator or IndicatorItem in the IOC. """ 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 actual restriction on duplicate parameters log.info('Duplicate (id,name) parameter pair will be inserted [{}][{}].'.format(indicator_id, name)) # now check to make sure the id is present in the IOC logic elems = criteria_node.xpath( './/IndicatorItem[@id="{}"]|.//Indicator[@id="{}"]'.format(indicator_id, indicator_id)) if len(elems) == 0: raise IOCParseError('ID does not exist in the IOC [{}][{}].'.format(str(indicator_id), str(content))) parameters_node.append(ioc_et.make_param_node(indicator_id, content, name, ptype)) return True
python
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 parameter. :param ptype: The type of the parameter content. :return: True :raises: IOCParseError if the indicator_id is not associated with a Indicator or IndicatorItem in the IOC. """ 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 actual restriction on duplicate parameters log.info('Duplicate (id,name) parameter pair will be inserted [{}][{}].'.format(indicator_id, name)) # now check to make sure the id is present in the IOC logic elems = criteria_node.xpath( './/IndicatorItem[@id="{}"]|.//Indicator[@id="{}"]'.format(indicator_id, indicator_id)) if len(elems) == 0: raise IOCParseError('ID does not exist in the IOC [{}][{}].'.format(str(indicator_id), str(content))) parameters_node.append(ioc_et.make_param_node(indicator_id, content, name, ptype)) return True
[ "def", "add_parameter", "(", "self", ",", "indicator_id", ",", "content", ",", "name", "=", "'comment'", ",", "ptype", "=", "'string'", ")", ":", "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 actual restriction on duplicate parameters", "log", ".", "info", "(", "'Duplicate (id,name) parameter pair will be inserted [{}][{}].'", ".", "format", "(", "indicator_id", ",", "name", ")", ")", "# now check to make sure the id is present in the IOC logic", "elems", "=", "criteria_node", ".", "xpath", "(", "'.//IndicatorItem[@id=\"{}\"]|.//Indicator[@id=\"{}\"]'", ".", "format", "(", "indicator_id", ",", "indicator_id", ")", ")", "if", "len", "(", "elems", ")", "==", "0", ":", "raise", "IOCParseError", "(", "'ID does not exist in the IOC [{}][{}].'", ".", "format", "(", "str", "(", "indicator_id", ")", ",", "str", "(", "content", ")", ")", ")", "parameters_node", ".", "append", "(", "ioc_et", ".", "make_param_node", "(", "indicator_id", ",", "content", ",", "name", ",", "ptype", ")", ")", "return", "True" ]
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 parameter. :param ptype: The type of the parameter content. :return: True :raises: IOCParseError if the indicator_id is not associated with a Indicator or IndicatorItem in the IOC.
[ "Add", "a", "a", "parameter", "to", "the", "IOC", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L227-L251
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.add_link
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 href: A href value assigned to the link. :return: True """ 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
python
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 href: A href value assigned to the link. :return: True """ 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
[ "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_node", "(", "rel", ",", "value", ",", "href", ")", "links_node", ".", "append", "(", "link_node", ")", "return", "True" ]
Add a Link metadata element to the IOC. :param rel: Type of the link. :param value: Value of the link text. :param href: A href value assigned to the link. :return: True
[ "Add", "a", "Link", "metadata", "element", "to", "the", "IOC", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L253-L268
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.update_name
def update_name(self, name): """ Update the name (short description) of an IOC This creates the short description node if it is not present. :param name: Value to set the short description too :return: """ 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('Creating & inserting the short description node') short_desc_node = ioc_et.make_short_description_node(name) self.metadata.insert(0, short_desc_node) else: short_desc_node.text = name return True
python
def update_name(self, name): """ Update the name (short description) of an IOC This creates the short description node if it is not present. :param name: Value to set the short description too :return: """ 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('Creating & inserting the short description node') short_desc_node = ioc_et.make_short_description_node(name) self.metadata.insert(0, short_desc_node) else: short_desc_node.text = name return True
[ "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", "(", "'Creating & inserting the short description node'", ")", "short_desc_node", "=", "ioc_et", ".", "make_short_description_node", "(", "name", ")", "self", ".", "metadata", ".", "insert", "(", "0", ",", "short_desc_node", ")", "else", ":", "short_desc_node", ".", "text", "=", "name", "return", "True" ]
Update the name (short description) of an IOC This creates the short description node if it is not present. :param name: Value to set the short description too :return:
[ "Update", "the", "name", "(", "short", "description", ")", "of", "an", "IOC" ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L270-L287
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.update_description
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') 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) insert_index = 0 for child in self.metadata.getchildren(): if child.tag == 'short_description': index = self.metadata.index(child) insert_index = index + 1 break self.metadata.insert(insert_index, desc_node) else: desc_node.text = description return True
python
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') 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) insert_index = 0 for child in self.metadata.getchildren(): if child.tag == 'short_description': index = self.metadata.index(child) insert_index = index + 1 break self.metadata.insert(insert_index, desc_node) else: desc_node.text = description return True
[ "def", "update_description", "(", "self", ",", "description", ")", ":", "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", ")", "insert_index", "=", "0", "for", "child", "in", "self", ".", "metadata", ".", "getchildren", "(", ")", ":", "if", "child", ".", "tag", "==", "'short_description'", ":", "index", "=", "self", ".", "metadata", ".", "index", "(", "child", ")", "insert_index", "=", "index", "+", "1", "break", "self", ".", "metadata", ".", "insert", "(", "insert_index", ",", "desc_node", ")", "else", ":", "desc_node", ".", "text", "=", "description", "return", "True" ]
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
[ "Update", "the", "description", ")", "of", "an", "IOC" ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L289-L311
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.update_link_rel_based
def update_link_rel_based(self, old_rel, new_rel=None, new_text=None, single_link=False): """ Update link nodes, based on the existing link/@rel values. This requires specifying a link/@rel value to update, and either a new link/@rel value, or a new link/text() value for all links which match the link/@rel value. Optionally, only the first link which matches the link/@rel value will be modified. :param old_rel: The link/@rel value used to select link nodes to update :param new_rel: The new link/@rel value :param new_text: The new link/text() value :param single_link: Determine if only the first, or multiple, linkes are modified. :return: True, unless there are no links with link[@rel='old_rel'] """ links = self.metadata.xpath('./links/link[@rel="{}"]'.format(old_rel)) if len(links) < 1: log.warning('No links with link/[@rel="{}"]'.format(str(old_rel))) return False if new_rel and not new_text: # update link/@rel value for link in links: link.attrib['rel'] = new_rel if single_link: break elif not new_rel and new_text: # update link/@text() value for link in links: link.text = new_text if single_link: break elif new_rel and new_text: log.warning('Cannot update rel and text at the same time') return False else: log.warning('Must specify either new_rel or new_text arguments') return False return True
python
def update_link_rel_based(self, old_rel, new_rel=None, new_text=None, single_link=False): """ Update link nodes, based on the existing link/@rel values. This requires specifying a link/@rel value to update, and either a new link/@rel value, or a new link/text() value for all links which match the link/@rel value. Optionally, only the first link which matches the link/@rel value will be modified. :param old_rel: The link/@rel value used to select link nodes to update :param new_rel: The new link/@rel value :param new_text: The new link/text() value :param single_link: Determine if only the first, or multiple, linkes are modified. :return: True, unless there are no links with link[@rel='old_rel'] """ links = self.metadata.xpath('./links/link[@rel="{}"]'.format(old_rel)) if len(links) < 1: log.warning('No links with link/[@rel="{}"]'.format(str(old_rel))) return False if new_rel and not new_text: # update link/@rel value for link in links: link.attrib['rel'] = new_rel if single_link: break elif not new_rel and new_text: # update link/@text() value for link in links: link.text = new_text if single_link: break elif new_rel and new_text: log.warning('Cannot update rel and text at the same time') return False else: log.warning('Must specify either new_rel or new_text arguments') return False return True
[ "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=\"{}\"]'", ".", "format", "(", "str", "(", "old_rel", ")", ")", ")", "return", "False", "if", "new_rel", "and", "not", "new_text", ":", "# update link/@rel value", "for", "link", "in", "links", ":", "link", ".", "attrib", "[", "'rel'", "]", "=", "new_rel", "if", "single_link", ":", "break", "elif", "not", "new_rel", "and", "new_text", ":", "# update link/@text() value", "for", "link", "in", "links", ":", "link", ".", "text", "=", "new_text", "if", "single_link", ":", "break", "elif", "new_rel", "and", "new_text", ":", "log", ".", "warning", "(", "'Cannot update rel and text at the same time'", ")", "return", "False", "else", ":", "log", ".", "warning", "(", "'Must specify either new_rel or new_text arguments'", ")", "return", "False", "return", "True" ]
Update link nodes, based on the existing link/@rel values. This requires specifying a link/@rel value to update, and either a new link/@rel value, or a new link/text() value for all links which match the link/@rel value. Optionally, only the first link which matches the link/@rel value will be modified. :param old_rel: The link/@rel value used to select link nodes to update :param new_rel: The new link/@rel value :param new_text: The new link/text() value :param single_link: Determine if only the first, or multiple, linkes are modified. :return: True, unless there are no links with link[@rel='old_rel']
[ "Update", "link", "nodes", "based", "on", "the", "existing", "link", "/", "@rel", "values", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L313-L350
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.update_link_rewrite
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 link/@text() values updated. :param old_rel: The link/@rel value used to select link nodes to update. :param old_text: The link/text() value used to select link nodes to update. :param new_text: The new link/text() value to set on link nodes. :param single_link: Determine if only the first, or multiple, linkes are modified. :return: True, unless there are no links with link/[@rel='old_rel' and text()='old_text'] """ links = self.metadata.xpath('./links/link[@rel="{}" and text()="{}"]'.format(old_rel, old_text)) if len(links) < 1: log.warning('No links with link/[@rel="{}"and text()="{}"]'.format(str(old_rel), str(old_text))) return False for link in links: link.text = new_text if single_link: break return True
python
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 link/@text() values updated. :param old_rel: The link/@rel value used to select link nodes to update. :param old_text: The link/text() value used to select link nodes to update. :param new_text: The new link/text() value to set on link nodes. :param single_link: Determine if only the first, or multiple, linkes are modified. :return: True, unless there are no links with link/[@rel='old_rel' and text()='old_text'] """ links = self.metadata.xpath('./links/link[@rel="{}" and text()="{}"]'.format(old_rel, old_text)) if len(links) < 1: log.warning('No links with link/[@rel="{}"and text()="{}"]'.format(str(old_rel), str(old_text))) return False for link in links: link.text = new_text if single_link: break return True
[ "def", "update_link_rewrite", "(", "self", ",", "old_rel", ",", "old_text", ",", "new_text", ",", "single_link", "=", "False", ")", ":", "links", "=", "self", ".", "metadata", ".", "xpath", "(", "'./links/link[@rel=\"{}\" and text()=\"{}\"]'", ".", "format", "(", "old_rel", ",", "old_text", ")", ")", "if", "len", "(", "links", ")", "<", "1", ":", "log", ".", "warning", "(", "'No links with link/[@rel=\"{}\"and text()=\"{}\"]'", ".", "format", "(", "str", "(", "old_rel", ")", ",", "str", "(", "old_text", ")", ")", ")", "return", "False", "for", "link", "in", "links", ":", "link", ".", "text", "=", "new_text", "if", "single_link", ":", "break", "return", "True" ]
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 link nodes to update. :param old_text: The link/text() value used to select link nodes to update. :param new_text: The new link/text() value to set on link nodes. :param single_link: Determine if only the first, or multiple, linkes are modified. :return: True, unless there are no links with link/[@rel='old_rel' and text()='old_text']
[ "Rewrite", "the", "text", "()", "value", "of", "a", "link", "based", "on", "the", "link", "/", "@rel", "and", "link", "/", "text", "()", "value", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L352-L373
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.update_parameter
def update_parameter(self, parameter_id, content=None, name=None, param_type=None): """ Updates the parameter attached to an Indicator or IndicatorItem node. All inputs must be strings or unicode objects. :param parameter_id: The unique id of the parameter to modify :param content: The value of the parameter. :param name: The name of the parameter. :param param_type: The type of the parameter content. :return: True, unless none of the optional arguments are supplied :raises: IOCParseError if the parameter id is not present in the IOC. """ 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)) if len(elems) != 1: msg = 'Did not find a single parameter with the supplied ID[{}]. Found [{}] parameters'.format(parameter_id, len(elems)) raise IOCParseError(msg) param_node = elems[0] value_node = param_node.find('value') if name: param_node.attrib['name'] = name if value_node is None: msg = 'No value node is associated with param [{}]. Not updating value node with content or tuple.' \ .format(parameter_id) log.warning(msg) else: if content: value_node.text = content if param_type: value_node.attrib['type'] = param_type return True
python
def update_parameter(self, parameter_id, content=None, name=None, param_type=None): """ Updates the parameter attached to an Indicator or IndicatorItem node. All inputs must be strings or unicode objects. :param parameter_id: The unique id of the parameter to modify :param content: The value of the parameter. :param name: The name of the parameter. :param param_type: The type of the parameter content. :return: True, unless none of the optional arguments are supplied :raises: IOCParseError if the parameter id is not present in the IOC. """ 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)) if len(elems) != 1: msg = 'Did not find a single parameter with the supplied ID[{}]. Found [{}] parameters'.format(parameter_id, len(elems)) raise IOCParseError(msg) param_node = elems[0] value_node = param_node.find('value') if name: param_node.attrib['name'] = name if value_node is None: msg = 'No value node is associated with param [{}]. Not updating value node with content or tuple.' \ .format(parameter_id) log.warning(msg) else: if content: value_node.text = content if param_type: value_node.attrib['type'] = param_type return True
[ "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.'", ")", "return", "False", "parameters_node", "=", "self", ".", "parameters", "elems", "=", "parameters_node", ".", "xpath", "(", "'.//param[@id=\"{}\"]'", ".", "format", "(", "parameter_id", ")", ")", "if", "len", "(", "elems", ")", "!=", "1", ":", "msg", "=", "'Did not find a single parameter with the supplied ID[{}]. Found [{}] parameters'", ".", "format", "(", "parameter_id", ",", "len", "(", "elems", ")", ")", "raise", "IOCParseError", "(", "msg", ")", "param_node", "=", "elems", "[", "0", "]", "value_node", "=", "param_node", ".", "find", "(", "'value'", ")", "if", "name", ":", "param_node", ".", "attrib", "[", "'name'", "]", "=", "name", "if", "value_node", "is", "None", ":", "msg", "=", "'No value node is associated with param [{}]. Not updating value node with content or tuple.'", ".", "format", "(", "parameter_id", ")", "log", ".", "warning", "(", "msg", ")", "else", ":", "if", "content", ":", "value_node", ".", "text", "=", "content", "if", "param_type", ":", "value_node", ".", "attrib", "[", "'type'", "]", "=", "param_type", "return", "True" ]
Updates the parameter attached to an Indicator or IndicatorItem node. All inputs must be strings or unicode objects. :param parameter_id: The unique id of the parameter to modify :param content: The value of the parameter. :param name: The name of the parameter. :param param_type: The type of the parameter content. :return: True, unless none of the optional arguments are supplied :raises: IOCParseError if the parameter id is not present in the IOC.
[ "Updates", "the", "parameter", "attached", "to", "an", "Indicator", "or", "IndicatorItem", "node", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L375-L413
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.remove_link
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/@rel & link/text() & link/@href :param rel: link/@rel value to remove. Required. :param value: link/text() value to remove. This is used in conjunction with link/@rel. :param href: link/@href value to remove. This is used in conjunction with link/@rel. :return: Return the number of link nodes removed, or False if no nodes are removed. """ 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 link.text == value and link.attrib['href'] == href: links_node.remove(link) counter += 1 elif value and not href: if link.text == value: links_node.remove(link) counter += 1 elif not value and href: if link.attrib['href'] == href: links_node.remove(link) counter += 1 else: links_node.remove(link) counter += 1 return counter
python
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/@rel & link/text() & link/@href :param rel: link/@rel value to remove. Required. :param value: link/text() value to remove. This is used in conjunction with link/@rel. :param href: link/@href value to remove. This is used in conjunction with link/@rel. :return: Return the number of link nodes removed, or False if no nodes are removed. """ 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 link.text == value and link.attrib['href'] == href: links_node.remove(link) counter += 1 elif value and not href: if link.text == value: links_node.remove(link) counter += 1 elif not value and href: if link.attrib['href'] == href: links_node.remove(link) counter += 1 else: links_node.remove(link) counter += 1 return counter
[ "def", "remove_link", "(", "self", ",", "rel", ",", "value", "=", "None", ",", "href", "=", "None", ")", ":", "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", "link", ".", "text", "==", "value", "and", "link", ".", "attrib", "[", "'href'", "]", "==", "href", ":", "links_node", ".", "remove", "(", "link", ")", "counter", "+=", "1", "elif", "value", "and", "not", "href", ":", "if", "link", ".", "text", "==", "value", ":", "links_node", ".", "remove", "(", "link", ")", "counter", "+=", "1", "elif", "not", "value", "and", "href", ":", "if", "link", ".", "attrib", "[", "'href'", "]", "==", "href", ":", "links_node", ".", "remove", "(", "link", ")", "counter", "+=", "1", "else", ":", "links_node", ".", "remove", "(", "link", ")", "counter", "+=", "1", "return", "counter" ]
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/@rel & link/text() & link/@href :param rel: link/@rel value to remove. Required. :param value: link/text() value to remove. This is used in conjunction with link/@rel. :param href: link/@href value to remove. This is used in conjunction with link/@rel. :return: Return the number of link nodes removed, or False if no nodes are removed.
[ "Removes", "link", "nodes", "based", "on", "the", "function", "arguments", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L415-L452
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.remove_indicator
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 underneath an Indicator node if the 'prune' argument is set. This will not remove the top level Indicator node from an IOC. If the id value has been reused within the IOC, this will remove the first node which contains the id value. This also removes any parameters associated with any nodes that are removed. :param nid: The Indicator/@id or IndicatorItem/@id value indicating a specific node to remove. :param prune: Remove all children of the deleted node. If a Indicator node is removed and prune is set to False, the children nodes will be promoted to be children of the removed nodes' parent. :return: True if nodes are removed, False otherwise. """ 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 == 'IndicatorItem': node_to_remove.getparent().remove(node_to_remove) self.remove_parameter(ref_id=nid) return True elif node_to_remove.tag == 'Indicator': if node_to_remove == self.top_level_indicator: raise IOCParseError('Cannot remove the top level indicator') if prune: pruned_ids = node_to_remove.xpath('.//@id') node_to_remove.getparent().remove(node_to_remove) for pruned_id in pruned_ids: self.remove_parameter(ref_id=pruned_id) else: for child_node in node_to_remove.getchildren(): node_to_remove.getparent().append(child_node) node_to_remove.getparent().remove(node_to_remove) self.remove_parameter(ref_id=nid) return True else: raise IOCParseError( 'Bad tag found. Expected "IndicatorItem" or "Indicator", got [[}]'.format(node_to_remove.tag))
python
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 underneath an Indicator node if the 'prune' argument is set. This will not remove the top level Indicator node from an IOC. If the id value has been reused within the IOC, this will remove the first node which contains the id value. This also removes any parameters associated with any nodes that are removed. :param nid: The Indicator/@id or IndicatorItem/@id value indicating a specific node to remove. :param prune: Remove all children of the deleted node. If a Indicator node is removed and prune is set to False, the children nodes will be promoted to be children of the removed nodes' parent. :return: True if nodes are removed, False otherwise. """ 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 == 'IndicatorItem': node_to_remove.getparent().remove(node_to_remove) self.remove_parameter(ref_id=nid) return True elif node_to_remove.tag == 'Indicator': if node_to_remove == self.top_level_indicator: raise IOCParseError('Cannot remove the top level indicator') if prune: pruned_ids = node_to_remove.xpath('.//@id') node_to_remove.getparent().remove(node_to_remove) for pruned_id in pruned_ids: self.remove_parameter(ref_id=pruned_id) else: for child_node in node_to_remove.getchildren(): node_to_remove.getparent().append(child_node) node_to_remove.getparent().remove(node_to_remove) self.remove_parameter(ref_id=nid) return True else: raise IOCParseError( 'Bad tag found. Expected "IndicatorItem" or "Indicator", got [[}]'.format(node_to_remove.tag))
[ "def", "remove_indicator", "(", "self", ",", "nid", ",", "prune", "=", "False", ")", ":", "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", "==", "'IndicatorItem'", ":", "node_to_remove", ".", "getparent", "(", ")", ".", "remove", "(", "node_to_remove", ")", "self", ".", "remove_parameter", "(", "ref_id", "=", "nid", ")", "return", "True", "elif", "node_to_remove", ".", "tag", "==", "'Indicator'", ":", "if", "node_to_remove", "==", "self", ".", "top_level_indicator", ":", "raise", "IOCParseError", "(", "'Cannot remove the top level indicator'", ")", "if", "prune", ":", "pruned_ids", "=", "node_to_remove", ".", "xpath", "(", "'.//@id'", ")", "node_to_remove", ".", "getparent", "(", ")", ".", "remove", "(", "node_to_remove", ")", "for", "pruned_id", "in", "pruned_ids", ":", "self", ".", "remove_parameter", "(", "ref_id", "=", "pruned_id", ")", "else", ":", "for", "child_node", "in", "node_to_remove", ".", "getchildren", "(", ")", ":", "node_to_remove", ".", "getparent", "(", ")", ".", "append", "(", "child_node", ")", "node_to_remove", ".", "getparent", "(", ")", ".", "remove", "(", "node_to_remove", ")", "self", ".", "remove_parameter", "(", "ref_id", "=", "nid", ")", "return", "True", "else", ":", "raise", "IOCParseError", "(", "'Bad tag found. Expected \"IndicatorItem\" or \"Indicator\", got [[}]'", ".", "format", "(", "node_to_remove", ".", "tag", ")", ")" ]
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 underneath an Indicator node if the 'prune' argument is set. This will not remove the top level Indicator node from an IOC. If the id value has been reused within the IOC, this will remove the first node which contains the id value. This also removes any parameters associated with any nodes that are removed. :param nid: The Indicator/@id or IndicatorItem/@id value indicating a specific node to remove. :param prune: Remove all children of the deleted node. If a Indicator node is removed and prune is set to False, the children nodes will be promoted to be children of the removed nodes' parent. :return: True if nodes are removed, False otherwise.
[ "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", "underneath", "an", "Indicator", "node", "if", "the", "prune", "argument", "is", "set", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L454-L500
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.remove_parameter
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 exclusive. Calling this function with multiple values set will cause an IOCParseError exception. Calling this function without setting one value will raise an exception. :param param_id: The id of the parameter to remove. :param name: The name of the parameter to remove. :param ref_id: The IndicatorItem/Indicator id of the parameter to remove. :return: Number of parameters removed. """ 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: raise IOCParseError('Must specifiy an param_id, name or ref_id to remove a paramater') counter = 0 parameters_node = self.parameters if param_id: params = parameters_node.xpath('//param[@id="{}"]'.format(param_id)) for param in params: parameters_node.remove(param) counter += 1 elif name: params = parameters_node.xpath('//param[@name="{}"]'.format(name)) for param in params: parameters_node.remove(param) counter += 1 elif ref_id: params = parameters_node.xpath('//param[@ref-id="{}"]'.format(ref_id)) for param in params: parameters_node.remove(param) counter += 1 return counter
python
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 exclusive. Calling this function with multiple values set will cause an IOCParseError exception. Calling this function without setting one value will raise an exception. :param param_id: The id of the parameter to remove. :param name: The name of the parameter to remove. :param ref_id: The IndicatorItem/Indicator id of the parameter to remove. :return: Number of parameters removed. """ 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: raise IOCParseError('Must specifiy an param_id, name or ref_id to remove a paramater') counter = 0 parameters_node = self.parameters if param_id: params = parameters_node.xpath('//param[@id="{}"]'.format(param_id)) for param in params: parameters_node.remove(param) counter += 1 elif name: params = parameters_node.xpath('//param[@name="{}"]'.format(name)) for param in params: parameters_node.remove(param) counter += 1 elif ref_id: params = parameters_node.xpath('//param[@ref-id="{}"]'.format(ref_id)) for param in params: parameters_node.remove(param) counter += 1 return counter
[ "def", "remove_parameter", "(", "self", ",", "param_id", "=", "None", ",", "name", "=", "None", ",", "ref_id", "=", "None", ",", ")", ":", "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", ":", "raise", "IOCParseError", "(", "'Must specifiy an param_id, name or ref_id to remove a paramater'", ")", "counter", "=", "0", "parameters_node", "=", "self", ".", "parameters", "if", "param_id", ":", "params", "=", "parameters_node", ".", "xpath", "(", "'//param[@id=\"{}\"]'", ".", "format", "(", "param_id", ")", ")", "for", "param", "in", "params", ":", "parameters_node", ".", "remove", "(", "param", ")", "counter", "+=", "1", "elif", "name", ":", "params", "=", "parameters_node", ".", "xpath", "(", "'//param[@name=\"{}\"]'", ".", "format", "(", "name", ")", ")", "for", "param", "in", "params", ":", "parameters_node", ".", "remove", "(", "param", ")", "counter", "+=", "1", "elif", "ref_id", ":", "params", "=", "parameters_node", ".", "xpath", "(", "'//param[@ref-id=\"{}\"]'", ".", "format", "(", "ref_id", ")", ")", "for", "param", "in", "params", ":", "parameters_node", ".", "remove", "(", "param", ")", "counter", "+=", "1", "return", "counter" ]
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 exclusive. Calling this function with multiple values set will cause an IOCParseError exception. Calling this function without setting one value will raise an exception. :param param_id: The id of the parameter to remove. :param name: The name of the parameter to remove. :param ref_id: The IndicatorItem/Indicator id of the parameter to remove. :return: Number of parameters removed.
[ "Removes", "parameters", "based", "on", "function", "arguments", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L502-L549
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.remove_name
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_description_node is not None: self.metadata.remove(short_description_node) return True return False
python
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_description_node is not None: self.metadata.remove(short_description_node) return True return False
[ "def", "remove_name", "(", "self", ")", ":", "short_description_node", "=", "self", ".", "metadata", ".", "find", "(", "'short_description'", ")", "if", "short_description_node", "is", "not", "None", ":", "self", ".", "metadata", ".", "remove", "(", "short_description_node", ")", "return", "True", "return", "False" ]
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.
[ "Removes", "the", "name", "(", "short_description", "node", ")", "from", "the", "metadata", "node", "if", "present", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L551-L561
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.remove_description
def remove_description(self): """ Removes the description node from the metadata node, if present. :return: Returns True if the description node is removed. Returns False if the node is not present. """ description_node = self.metadata.find('description') if description_node is not None: self.metadata.remove(description_node) return True return False
python
def remove_description(self): """ Removes the description node from the metadata node, if present. :return: Returns True if the description node is removed. Returns False if the node is not present. """ description_node = self.metadata.find('description') if description_node is not None: self.metadata.remove(description_node) return True return False
[ "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" ]
Removes the description node from the metadata node, if present. :return: Returns True if the description node is removed. Returns False if the node is not present.
[ "Removes", "the", "description", "node", "from", "the", "metadata", "node", "if", "present", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L563-L573
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.write_ioc_to_file
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 the current working directory. :param force: If specified, will not validate the root node of the IOC is 'OpenIOC'. :return: """ return write_ioc(self.root, output_dir, force=force)
python
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 the current working directory. :param force: If specified, will not validate the root node of the IOC is 'OpenIOC'. :return: """ return write_ioc(self.root, output_dir, force=force)
[ "def", "write_ioc_to_file", "(", "self", ",", "output_dir", "=", "None", ",", "force", "=", "False", ")", ":", "return", "write_ioc", "(", "self", ".", "root", ",", "output_dir", ",", "force", "=", "force", ")" ]
Serialize the IOC to a .ioc file. :param output_dir: Directory to write the ioc out to. default is the current working directory. :param force: If specified, will not validate the root node of the IOC is 'OpenIOC'. :return:
[ "Serialize", "the", "IOC", "to", "a", ".", "ioc", "file", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L575-L583
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.display_ioc
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 display node parameters. :return: """ 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('last-modified', default='No last-modified attrib')) s += 'Author: {}\n'.format(self.metadata.findtext('authored_by', default='No authored_by')) desc = self.metadata.findtext('description', default='No Description') desc = textwrap.wrap(desc, width=width) desc = '\n'.join(desc) s += 'Description:\n{}\n\n'.format(desc) links = self.link_text() if links: s += '{}'.format(links) content_text = self.criteria_text(sep=sep, params=params) s += '\nCriteria:\n{}'.format(content_text) return s
python
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 display node parameters. :return: """ 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('last-modified', default='No last-modified attrib')) s += 'Author: {}\n'.format(self.metadata.findtext('authored_by', default='No authored_by')) desc = self.metadata.findtext('description', default='No Description') desc = textwrap.wrap(desc, width=width) desc = '\n'.join(desc) s += 'Description:\n{}\n\n'.format(desc) links = self.link_text() if links: s += '{}'.format(links) content_text = self.criteria_text(sep=sep, params=params) s += '\nCriteria:\n{}'.format(content_text) return s
[ "def", "display_ioc", "(", "self", ",", "width", "=", "120", ",", "sep", "=", "' '", ",", "params", "=", "False", ")", ":", "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", "(", "'last-modified'", ",", "default", "=", "'No last-modified attrib'", ")", ")", "s", "+=", "'Author: {}\\n'", ".", "format", "(", "self", ".", "metadata", ".", "findtext", "(", "'authored_by'", ",", "default", "=", "'No authored_by'", ")", ")", "desc", "=", "self", ".", "metadata", ".", "findtext", "(", "'description'", ",", "default", "=", "'No Description'", ")", "desc", "=", "textwrap", ".", "wrap", "(", "desc", ",", "width", "=", "width", ")", "desc", "=", "'\\n'", ".", "join", "(", "desc", ")", "s", "+=", "'Description:\\n{}\\n\\n'", ".", "format", "(", "desc", ")", "links", "=", "self", ".", "link_text", "(", ")", "if", "links", ":", "s", "+=", "'{}'", ".", "format", "(", "links", ")", "content_text", "=", "self", ".", "criteria_text", "(", "sep", "=", "sep", ",", "params", "=", "params", ")", "s", "+=", "'\\nCriteria:\\n{}'", ".", "format", "(", "content_text", ")", "return", "s" ]
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 display node parameters. :return:
[ "Get", "a", "string", "representation", "of", "an", "IOC", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L594-L617
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.link_text
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') href = link.attrib.get('href') text = link.text lt = '{rel}{href}: {text}\n'.format(rel=rel, href=' @ {}'.format(href) if href else '', text=text) s += lt return s
python
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') href = link.attrib.get('href') text = link.text lt = '{rel}{href}: {text}\n'.format(rel=rel, href=' @ {}'.format(href) if href else '', text=text) s += lt return s
[ "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'", "for", "link", "in", "links", ":", "rel", "=", "link", ".", "attrib", ".", "get", "(", "'rel'", ",", "'No Rel'", ")", "href", "=", "link", ".", "attrib", ".", "get", "(", "'href'", ")", "text", "=", "link", ".", "text", "lt", "=", "'{rel}{href}: {text}\\n'", ".", "format", "(", "rel", "=", "rel", ",", "href", "=", "' @ {}'", ".", "format", "(", "href", ")", "if", "href", "else", "''", ",", "text", "=", "text", ")", "s", "+=", "lt", "return", "s" ]
Get a text represention of the links node. :return:
[ "Get", "a", "text", "represention", "of", "the", "links", "node", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L619-L641
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.criteria_text
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 = '' 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'.join(node_texts) return s
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 = '' 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'.join(node_texts) return s
[ "def", "criteria_text", "(", "self", ",", "sep", "=", "' '", ",", "params", "=", "False", ")", ":", "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'", ".", "join", "(", "node_texts", ")", "return", "s" ]
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:
[ "Get", "a", "text", "representation", "of", "the", "criteria", "node", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L643-L661
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.get_node_text
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 get its children text as well. :param node: Node to get the text for. :param depth: Track the number of recursions that have occured, modifies the indentation. :param sep: Seperator used for formatting the text. Multiplied by the depth to get the indentation. :param params: Boolean, set to True in order to display node parameters. :return: """ 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)) s += '{}{}\n'.format(indent, node_text) if params: param_text = self.get_param_text(node.attrib.get('id')) for pt in param_text: s += '{}{}\n'.format(indent+sep, pt) if node.tag == 'Indicator': for child in node.getchildren(): s += self.get_node_text(node=child, depth=depth+1, sep=sep, params=params) return s
python
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 get its children text as well. :param node: Node to get the text for. :param depth: Track the number of recursions that have occured, modifies the indentation. :param sep: Seperator used for formatting the text. Multiplied by the depth to get the indentation. :param params: Boolean, set to True in order to display node parameters. :return: """ 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)) s += '{}{}\n'.format(indent, node_text) if params: param_text = self.get_param_text(node.attrib.get('id')) for pt in param_text: s += '{}{}\n'.format(indent+sep, pt) if node.tag == 'Indicator': for child in node.getchildren(): s += self.get_node_text(node=child, depth=depth+1, sep=sep, params=params) return s
[ "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", "=", "self", ".", "get_ii_text", "(", "node", ")", "else", ":", "raise", "IOCParseError", "(", "'Invalid node encountered: {}'", ".", "format", "(", "tag", ")", ")", "s", "+=", "'{}{}\\n'", ".", "format", "(", "indent", ",", "node_text", ")", "if", "params", ":", "param_text", "=", "self", ".", "get_param_text", "(", "node", ".", "attrib", ".", "get", "(", "'id'", ")", ")", "for", "pt", "in", "param_text", ":", "s", "+=", "'{}{}\\n'", ".", "format", "(", "indent", "+", "sep", ",", "pt", ")", "if", "node", ".", "tag", "==", "'Indicator'", ":", "for", "child", "in", "node", ".", "getchildren", "(", ")", ":", "s", "+=", "self", ".", "get_node_text", "(", "node", "=", "child", ",", "depth", "=", "depth", "+", "1", ",", "sep", "=", "sep", ",", "params", "=", "params", ")", "return", "s" ]
Get the text for a given Indicator or IndicatorItem node. This does walk an IndicatorItem node to get its children text as well. :param node: Node to get the text for. :param depth: Track the number of recursions that have occured, modifies the indentation. :param sep: Seperator used for formatting the text. Multiplied by the depth to get the indentation. :param params: Boolean, set to True in order to display node parameters. :return:
[ "Get", "the", "text", "for", "a", "given", "Indicator", "or", "IndicatorItem", "node", ".", "This", "does", "walk", "an", "IndicatorItem", "node", "to", "get", "its", "children", "text", "as", "well", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L663-L691
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.get_i_text
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
python
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
[ "def", "get_i_text", "(", "node", ")", ":", "if", "node", ".", "tag", "!=", "'Indicator'", ":", "raise", "IOCParseError", "(", "'Invalid tag: {}'", ".", "format", "(", "node", ".", "tag", ")", ")", "s", "=", "node", ".", "get", "(", "'operator'", ")", ".", "upper", "(", ")", "return", "s" ]
Get the text for an Indicator node. :param node: Indicator node. :return:
[ "Get", "the", "text", "for", "an", "Indicator", "node", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L694-L704
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.get_ii_text
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') search = node.find('Context').get('search') if preserve_case.lower() == 'true': preserve_case = ' (Preserve Case)' else: preserve_case = '' if negate.lower() == 'true': negate = 'NOT ' else: negate = '' s = '{negate}{search} {condition} "{content}"{preserve_case}'.format(negate=negate, search=search, condition=condition, content=content, preserve_case=preserve_case) return s
python
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') search = node.find('Context').get('search') if preserve_case.lower() == 'true': preserve_case = ' (Preserve Case)' else: preserve_case = '' if negate.lower() == 'true': negate = 'NOT ' else: negate = '' s = '{negate}{search} {condition} "{content}"{preserve_case}'.format(negate=negate, search=search, condition=condition, content=content, preserve_case=preserve_case) return s
[ "def", "get_ii_text", "(", "node", ")", ":", "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'", ")", "search", "=", "node", ".", "find", "(", "'Context'", ")", ".", "get", "(", "'search'", ")", "if", "preserve_case", ".", "lower", "(", ")", "==", "'true'", ":", "preserve_case", "=", "' (Preserve Case)'", "else", ":", "preserve_case", "=", "''", "if", "negate", ".", "lower", "(", ")", "==", "'true'", ":", "negate", "=", "'NOT '", "else", ":", "negate", "=", "''", "s", "=", "'{negate}{search} {condition} \"{content}\"{preserve_case}'", ".", "format", "(", "negate", "=", "negate", ",", "search", "=", "search", ",", "condition", "=", "condition", ",", "content", "=", "content", ",", "preserve_case", "=", "preserve_case", ")", "return", "s" ]
Get the text for IndicatorItem node. :param node: IndicatorItem node. :return:
[ "Get", "the", "text", "for", "IndicatorItem", "node", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L707-L734
mandiant/ioc_writer
ioc_writer/ioc_api.py
IOC.get_param_text
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'), vnode.attrib.get('type'), param.findtext('value', default='No Value')) r.append(s) return r
python
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'), vnode.attrib.get('type'), param.findtext('value', default='No Value')) r.append(s) return r
[ "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", "=", "'Parameter: {}, type:{}, value: {}'", ".", "format", "(", "param", ".", "attrib", ".", "get", "(", "'name'", ")", ",", "vnode", ".", "attrib", ".", "get", "(", "'type'", ")", ",", "param", ".", "findtext", "(", "'value'", ",", "default", "=", "'No Value'", ")", ")", "r", ".", "append", "(", "s", ")", "return", "r" ]
Get a list of parameters as text values for a given node id. :param nid: id to look for. :return:
[ "Get", "a", "list", "of", "parameters", "as", "text", "values", "for", "a", "given", "node", "id", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L736-L753
mandiant/ioc_writer
ioc_writer/utils/xmlutils.py
read_xml
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 ValueError as e: if 'path too long for Windows' in str(e): pass else: raise try: if isfile: return et.parse(filename, parser) else: r = et.fromstring(filename, parser) return r.getroottree() except IOError: log.exception('unable to open file [[}]'.format(filename)) except et.XMLSyntaxError: log.exception('unable to parse XML [{}]'.format(filename)) return None return None
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 ValueError as e: if 'path too long for Windows' in str(e): pass else: raise try: if isfile: return et.parse(filename, parser) else: r = et.fromstring(filename, parser) return r.getroottree() except IOError: log.exception('unable to open file [[}]'.format(filename)) except et.XMLSyntaxError: log.exception('unable to parse XML [{}]'.format(filename)) return None return None
[ "def", "read_xml", "(", "filename", ")", ":", "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", ")", "else", ":", "r", "=", "et", ".", "fromstring", "(", "filename", ",", "parser", ")", "return", "r", ".", "getroottree", "(", ")", "except", "IOError", ":", "log", ".", "exception", "(", "'unable to open file [[}]'", ".", "format", "(", "filename", ")", ")", "except", "et", ".", "XMLSyntaxError", ":", "log", ".", "exception", "(", "'unable to parse XML [{}]'", ".", "format", "(", "filename", ")", ")", "return", "None", "return", "None" ]
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
[ "Use", "et", "to", "read", "in", "a", "xml", "file", "or", "string", "into", "a", "Element", "object", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/utils/xmlutils.py#L30-L57
mandiant/ioc_writer
ioc_writer/utils/xmlutils.py
remove_namespace
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 that needs to be removed. :return: Returns the source document with namespaces removed. """ # 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, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ns = '{{{}}}'.format(namespace) nsl = len(ns) # print 'DEBUG: removing',ns for elem in doc.getiterator(): if elem.tag.startswith(ns): elem.tag = elem.tag[nsl:] return doc
python
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 that needs to be removed. :return: Returns the source document with namespaces removed. """ # 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, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ns = '{{{}}}'.format(namespace) nsl = len(ns) # print 'DEBUG: removing',ns for elem in doc.getiterator(): if elem.tag.startswith(ns): elem.tag = elem.tag[nsl:] return doc
[ "def", "remove_namespace", "(", "doc", ",", "namespace", ")", ":", "# 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, including", "# without limitation the rights to use, copy, modify, merge, publish,", "# distribute, sublicense, and/or sell copies of the Software, and to", "# permit persons to whom the Software is furnished to do so, subject to", "# the following conditions:", "#", "# The above copyright notice and this permission notice shall be", "# included in all copies or substantial portions of the Software.", "#", "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND", "# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE", "# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION", "# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION", "# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", "ns", "=", "'{{{}}}'", ".", "format", "(", "namespace", ")", "nsl", "=", "len", "(", "ns", ")", "# print 'DEBUG: removing',ns", "for", "elem", "in", "doc", ".", "getiterator", "(", ")", ":", "if", "elem", ".", "tag", ".", "startswith", "(", "ns", ")", ":", "elem", ".", "tag", "=", "elem", ".", "tag", "[", "nsl", ":", "]", "return", "doc" ]
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 that needs to be removed. :return: Returns the source document with namespaces removed.
[ "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", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/utils/xmlutils.py#L60-L96
mandiant/ioc_writer
ioc_writer/utils/xmlutils.py
delete_namespace
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 parsed_xml: lxml.Etree object. :return: Returns the sources document with the namespace removed. """ 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
python
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 parsed_xml: lxml.Etree object. :return: Returns the sources document with the namespace removed. """ 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
[ "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" ]
Identifies the namespace associated with the root node of a XML document and removes that names from the document. :param parsed_xml: lxml.Etree object. :return: Returns the sources document with the namespace removed.
[ "Identifies", "the", "namespace", "associated", "with", "the", "root", "node", "of", "a", "XML", "document", "and", "removes", "that", "names", "from", "the", "document", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/utils/xmlutils.py#L99-L111
mandiant/ioc_writer
ioc_writer/managers/upgrade_10.py
UpgradeManager.insert
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): log.info('loading IOC from: {}'.format(filename)) if not self.parse(filename): log.warning('Failed to prase [{}]'.format(filename)) errors.append(filename) elif os.path.isdir(filename): log.info('loading IOCs from: {}'.format(filename)) for fn in glob.glob(filename + os.path.sep + '*.ioc'): if not os.path.isfile(fn): continue else: if not self.parse(fn): log.warning('Failed to parse [{}]'.format(filename)) errors.append(fn) else: pass log.info('Parsed [%s] IOCs' % str(len(self))) return errors
python
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): log.info('loading IOC from: {}'.format(filename)) if not self.parse(filename): log.warning('Failed to prase [{}]'.format(filename)) errors.append(filename) elif os.path.isdir(filename): log.info('loading IOCs from: {}'.format(filename)) for fn in glob.glob(filename + os.path.sep + '*.ioc'): if not os.path.isfile(fn): continue else: if not self.parse(fn): log.warning('Failed to parse [{}]'.format(filename)) errors.append(fn) else: pass log.info('Parsed [%s] IOCs' % str(len(self))) return errors
[ "def", "insert", "(", "self", ",", "filename", ")", ":", "errors", "=", "[", "]", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "log", ".", "info", "(", "'loading IOC from: {}'", ".", "format", "(", "filename", ")", ")", "if", "not", "self", ".", "parse", "(", "filename", ")", ":", "log", ".", "warning", "(", "'Failed to prase [{}]'", ".", "format", "(", "filename", ")", ")", "errors", ".", "append", "(", "filename", ")", "elif", "os", ".", "path", ".", "isdir", "(", "filename", ")", ":", "log", ".", "info", "(", "'loading IOCs from: {}'", ".", "format", "(", "filename", ")", ")", "for", "fn", "in", "glob", ".", "glob", "(", "filename", "+", "os", ".", "path", ".", "sep", "+", "'*.ioc'", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "fn", ")", ":", "continue", "else", ":", "if", "not", "self", ".", "parse", "(", "fn", ")", ":", "log", ".", "warning", "(", "'Failed to parse [{}]'", ".", "format", "(", "filename", ")", ")", "errors", ".", "append", "(", "fn", ")", "else", ":", "pass", "log", ".", "info", "(", "'Parsed [%s] IOCs'", "%", "str", "(", "len", "(", "self", ")", ")", ")", "return", "errors" ]
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.
[ "Parses", "files", "to", "load", "them", "into", "memory", "and", "insert", "them", "into", "the", "class", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/managers/upgrade_10.py#L52-L77
mandiant/ioc_writer
ioc_writer/managers/upgrade_10.py
UpgradeManager.parse
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
python
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
[ "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", "return", "True" ]
Parses a file into a lxml.etree structure with namespaces remove. This tree is added to self.iocs. :param fn: File to parse. :return:
[ "Parses", "a", "file", "into", "a", "lxml", ".", "etree", "structure", "with", "namespaces", "remove", ".", "This", "tree", "is", "added", "to", "self", ".", "iocs", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/managers/upgrade_10.py#L79-L94
mandiant/ioc_writer
ioc_writer/managers/upgrade_10.py
UpgradeManager.convert_to_11
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': log.error('IOC root is not "ioc" [%s].' % str(iocid)) errors.append(iocid) continue name_10 = root.findtext('.//short_description') keywords_10 = root.findtext('.//keywords') description_10 = root.findtext('.//description') author_10 = root.findtext('.//authored_by') created_date_10 = root.findtext('.//authored_date') last_modified_date_10 = root.get('last-modified', None) if last_modified_date_10: last_modified_date_10 = last_modified_date_10.rstrip('Z') created_date_10 = created_date_10.rstrip('Z') links_10 = [] for link in root.xpath('//link'): link_rel = link.get('rel', None) link_text = link.text links_10.append((link_rel, link_text, None)) # get ioc_logic try: ioc_logic = root.xpath('.//definition')[0] except IndexError: log.exception( 'Could not find definition nodes for IOC [%s]. Did you attempt to convert OpenIOC 1.1 iocs?' % str( iocid)) errors.append(iocid) continue # create 1.1 ioc obj ioc_obj = ioc_api.IOC(name=name_10, description=description_10, author=author_10, links=links_10, keywords=keywords_10, iocid=iocid) ioc_obj.set_lastmodified_date(last_modified_date_10) ioc_obj.set_created_date(created_date_10) comment_dict = {} tlo_10 = ioc_logic.getchildren()[0] try: self.convert_branch(tlo_10, ioc_obj.top_level_indicator, comment_dict) except UpgradeError: log.exception('Problem converting IOC [{}]'.format(iocid)) errors.append(iocid) continue for node_id in comment_dict: ioc_obj.add_parameter(node_id, comment_dict[node_id]) self.iocs_11[iocid] = ioc_obj return errors
python
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': log.error('IOC root is not "ioc" [%s].' % str(iocid)) errors.append(iocid) continue name_10 = root.findtext('.//short_description') keywords_10 = root.findtext('.//keywords') description_10 = root.findtext('.//description') author_10 = root.findtext('.//authored_by') created_date_10 = root.findtext('.//authored_date') last_modified_date_10 = root.get('last-modified', None) if last_modified_date_10: last_modified_date_10 = last_modified_date_10.rstrip('Z') created_date_10 = created_date_10.rstrip('Z') links_10 = [] for link in root.xpath('//link'): link_rel = link.get('rel', None) link_text = link.text links_10.append((link_rel, link_text, None)) # get ioc_logic try: ioc_logic = root.xpath('.//definition')[0] except IndexError: log.exception( 'Could not find definition nodes for IOC [%s]. Did you attempt to convert OpenIOC 1.1 iocs?' % str( iocid)) errors.append(iocid) continue # create 1.1 ioc obj ioc_obj = ioc_api.IOC(name=name_10, description=description_10, author=author_10, links=links_10, keywords=keywords_10, iocid=iocid) ioc_obj.set_lastmodified_date(last_modified_date_10) ioc_obj.set_created_date(created_date_10) comment_dict = {} tlo_10 = ioc_logic.getchildren()[0] try: self.convert_branch(tlo_10, ioc_obj.top_level_indicator, comment_dict) except UpgradeError: log.exception('Problem converting IOC [{}]'.format(iocid)) errors.append(iocid) continue for node_id in comment_dict: ioc_obj.add_parameter(node_id, comment_dict[node_id]) self.iocs_11[iocid] = ioc_obj return errors
[ "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_xml", "=", "self", ".", "iocs", "[", "iocid", "]", "root", "=", "ioc_xml", ".", "getroot", "(", ")", "if", "root", ".", "tag", "!=", "'ioc'", ":", "log", ".", "error", "(", "'IOC root is not \"ioc\" [%s].'", "%", "str", "(", "iocid", ")", ")", "errors", ".", "append", "(", "iocid", ")", "continue", "name_10", "=", "root", ".", "findtext", "(", "'.//short_description'", ")", "keywords_10", "=", "root", ".", "findtext", "(", "'.//keywords'", ")", "description_10", "=", "root", ".", "findtext", "(", "'.//description'", ")", "author_10", "=", "root", ".", "findtext", "(", "'.//authored_by'", ")", "created_date_10", "=", "root", ".", "findtext", "(", "'.//authored_date'", ")", "last_modified_date_10", "=", "root", ".", "get", "(", "'last-modified'", ",", "None", ")", "if", "last_modified_date_10", ":", "last_modified_date_10", "=", "last_modified_date_10", ".", "rstrip", "(", "'Z'", ")", "created_date_10", "=", "created_date_10", ".", "rstrip", "(", "'Z'", ")", "links_10", "=", "[", "]", "for", "link", "in", "root", ".", "xpath", "(", "'//link'", ")", ":", "link_rel", "=", "link", ".", "get", "(", "'rel'", ",", "None", ")", "link_text", "=", "link", ".", "text", "links_10", ".", "append", "(", "(", "link_rel", ",", "link_text", ",", "None", ")", ")", "# get ioc_logic", "try", ":", "ioc_logic", "=", "root", ".", "xpath", "(", "'.//definition'", ")", "[", "0", "]", "except", "IndexError", ":", "log", ".", "exception", "(", "'Could not find definition nodes for IOC [%s]. Did you attempt to convert OpenIOC 1.1 iocs?'", "%", "str", "(", "iocid", ")", ")", "errors", ".", "append", "(", "iocid", ")", "continue", "# create 1.1 ioc obj", "ioc_obj", "=", "ioc_api", ".", "IOC", "(", "name", "=", "name_10", ",", "description", "=", "description_10", ",", "author", "=", "author_10", ",", "links", "=", "links_10", ",", "keywords", "=", "keywords_10", ",", "iocid", "=", "iocid", ")", "ioc_obj", ".", "set_lastmodified_date", "(", "last_modified_date_10", ")", "ioc_obj", ".", "set_created_date", "(", "created_date_10", ")", "comment_dict", "=", "{", "}", "tlo_10", "=", "ioc_logic", ".", "getchildren", "(", ")", "[", "0", "]", "try", ":", "self", ".", "convert_branch", "(", "tlo_10", ",", "ioc_obj", ".", "top_level_indicator", ",", "comment_dict", ")", "except", "UpgradeError", ":", "log", ".", "exception", "(", "'Problem converting IOC [{}]'", ".", "format", "(", "iocid", ")", ")", "errors", ".", "append", "(", "iocid", ")", "continue", "for", "node_id", "in", "comment_dict", ":", "ioc_obj", ".", "add_parameter", "(", "node_id", ",", "comment_dict", "[", "node_id", "]", ")", "self", ".", "iocs_11", "[", "iocid", "]", "=", "ioc_obj", "return", "errors" ]
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
[ "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" ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/managers/upgrade_10.py#L96-L153
mandiant/ioc_writer
ioc_writer/managers/upgrade_10.py
UpgradeManager.convert_branch
def convert_branch(self, old_node, new_node, comment_dict=None): """ recursively walk a indicator logic tree, starting from a Indicator node. converts OpenIOC 1.0 Indicator/IndicatorItems to Openioc 1.1 and preserves order. :param old_node: Indicator node, which we walk down to convert :param new_node: Indicator node, which we add new IndicatorItem and Indicator nodes too :param comment_dict: maps ids to comment values. only applied to IndicatorItem nodes :return: True upon completion :raises: UpgradeError if there is a problem during the conversion. """ expected_tag = 'Indicator' if old_node.tag != expected_tag: raise UpgradeError('old_node expected tag is [%s]' % expected_tag) if not comment_dict: comment_dict = {} for node in old_node.getchildren(): node_id = node.get('id') if node.tag == 'IndicatorItem': condition = node.get('condition') negation = False if condition.endswith('not'): negation = True condition = condition[:-3] document = node.xpath('Context/@document')[0] search = node.xpath('Context/@search')[0] content_type = node.xpath('Content/@type')[0] content = node.findtext('Content') context_type = node.xpath('Context/@type')[0] new_ii_node = ioc_api.make_indicatoritem_node(condition=condition, document=document, search=search, content_type=content_type, content=content, context_type=context_type, negate=negation, nid=node_id) # set comment comment = node.find('Comment') if comment is not None: comment_dict[node_id] = comment.text new_node.append(new_ii_node) elif node.tag == 'Indicator': operator = node.get('operator') if operator.upper() not in ['OR', 'AND']: raise UpgradeError('Indicator@operator is not AND/OR. [%s] has [%s]' % (node_id, operator)) new_i_node = ioc_api.make_indicator_node(operator, node_id) new_node.append(new_i_node) self.convert_branch(node, new_i_node, comment_dict) else: # should never get here raise UpgradeError('node is not a Indicator/IndicatorItem') return True
python
def convert_branch(self, old_node, new_node, comment_dict=None): """ recursively walk a indicator logic tree, starting from a Indicator node. converts OpenIOC 1.0 Indicator/IndicatorItems to Openioc 1.1 and preserves order. :param old_node: Indicator node, which we walk down to convert :param new_node: Indicator node, which we add new IndicatorItem and Indicator nodes too :param comment_dict: maps ids to comment values. only applied to IndicatorItem nodes :return: True upon completion :raises: UpgradeError if there is a problem during the conversion. """ expected_tag = 'Indicator' if old_node.tag != expected_tag: raise UpgradeError('old_node expected tag is [%s]' % expected_tag) if not comment_dict: comment_dict = {} for node in old_node.getchildren(): node_id = node.get('id') if node.tag == 'IndicatorItem': condition = node.get('condition') negation = False if condition.endswith('not'): negation = True condition = condition[:-3] document = node.xpath('Context/@document')[0] search = node.xpath('Context/@search')[0] content_type = node.xpath('Content/@type')[0] content = node.findtext('Content') context_type = node.xpath('Context/@type')[0] new_ii_node = ioc_api.make_indicatoritem_node(condition=condition, document=document, search=search, content_type=content_type, content=content, context_type=context_type, negate=negation, nid=node_id) # set comment comment = node.find('Comment') if comment is not None: comment_dict[node_id] = comment.text new_node.append(new_ii_node) elif node.tag == 'Indicator': operator = node.get('operator') if operator.upper() not in ['OR', 'AND']: raise UpgradeError('Indicator@operator is not AND/OR. [%s] has [%s]' % (node_id, operator)) new_i_node = ioc_api.make_indicator_node(operator, node_id) new_node.append(new_i_node) self.convert_branch(node, new_i_node, comment_dict) else: # should never get here raise UpgradeError('node is not a Indicator/IndicatorItem') return True
[ "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", ":", "comment_dict", "=", "{", "}", "for", "node", "in", "old_node", ".", "getchildren", "(", ")", ":", "node_id", "=", "node", ".", "get", "(", "'id'", ")", "if", "node", ".", "tag", "==", "'IndicatorItem'", ":", "condition", "=", "node", ".", "get", "(", "'condition'", ")", "negation", "=", "False", "if", "condition", ".", "endswith", "(", "'not'", ")", ":", "negation", "=", "True", "condition", "=", "condition", "[", ":", "-", "3", "]", "document", "=", "node", ".", "xpath", "(", "'Context/@document'", ")", "[", "0", "]", "search", "=", "node", ".", "xpath", "(", "'Context/@search'", ")", "[", "0", "]", "content_type", "=", "node", ".", "xpath", "(", "'Content/@type'", ")", "[", "0", "]", "content", "=", "node", ".", "findtext", "(", "'Content'", ")", "context_type", "=", "node", ".", "xpath", "(", "'Context/@type'", ")", "[", "0", "]", "new_ii_node", "=", "ioc_api", ".", "make_indicatoritem_node", "(", "condition", "=", "condition", ",", "document", "=", "document", ",", "search", "=", "search", ",", "content_type", "=", "content_type", ",", "content", "=", "content", ",", "context_type", "=", "context_type", ",", "negate", "=", "negation", ",", "nid", "=", "node_id", ")", "# set comment", "comment", "=", "node", ".", "find", "(", "'Comment'", ")", "if", "comment", "is", "not", "None", ":", "comment_dict", "[", "node_id", "]", "=", "comment", ".", "text", "new_node", ".", "append", "(", "new_ii_node", ")", "elif", "node", ".", "tag", "==", "'Indicator'", ":", "operator", "=", "node", ".", "get", "(", "'operator'", ")", "if", "operator", ".", "upper", "(", ")", "not", "in", "[", "'OR'", ",", "'AND'", "]", ":", "raise", "UpgradeError", "(", "'Indicator@operator is not AND/OR. [%s] has [%s]'", "%", "(", "node_id", ",", "operator", ")", ")", "new_i_node", "=", "ioc_api", ".", "make_indicator_node", "(", "operator", ",", "node_id", ")", "new_node", ".", "append", "(", "new_i_node", ")", "self", ".", "convert_branch", "(", "node", ",", "new_i_node", ",", "comment_dict", ")", "else", ":", "# should never get here", "raise", "UpgradeError", "(", "'node is not a Indicator/IndicatorItem'", ")", "return", "True" ]
recursively walk a indicator logic tree, starting from a Indicator node. converts OpenIOC 1.0 Indicator/IndicatorItems to Openioc 1.1 and preserves order. :param old_node: Indicator node, which we walk down to convert :param new_node: Indicator node, which we add new IndicatorItem and Indicator nodes too :param comment_dict: maps ids to comment values. only applied to IndicatorItem nodes :return: True upon completion :raises: UpgradeError if there is a problem during the conversion.
[ "recursively", "walk", "a", "indicator", "logic", "tree", "starting", "from", "a", "Indicator", "node", ".", "converts", "OpenIOC", "1", ".", "0", "Indicator", "/", "IndicatorItems", "to", "Openioc", "1", ".", "1", "and", "preserves", "order", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/managers/upgrade_10.py#L155-L207
mandiant/ioc_writer
ioc_writer/managers/__init__.py
IOCManager.insert
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): log.info('loading IOC from: {}'.format(filename)) try: self.parse(ioc_api.IOC(filename)) except ioc_api.IOCParseError: log.exception('Parse Error') errors.append(filename) elif os.path.isdir(filename): log.info('loading IOCs from: {}'.format(filename)) for fn in glob.glob(filename + os.path.sep + '*.ioc'): if not os.path.isfile(fn): continue else: try: self.parse(ioc_api.IOC(fn)) except ioc_api.IOCParseError: log.exception('Parse Error') errors.append(fn) else: pass log.info('Parsed [{}] IOCs'.format(len(self))) return errors
python
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): log.info('loading IOC from: {}'.format(filename)) try: self.parse(ioc_api.IOC(filename)) except ioc_api.IOCParseError: log.exception('Parse Error') errors.append(filename) elif os.path.isdir(filename): log.info('loading IOCs from: {}'.format(filename)) for fn in glob.glob(filename + os.path.sep + '*.ioc'): if not os.path.isfile(fn): continue else: try: self.parse(ioc_api.IOC(fn)) except ioc_api.IOCParseError: log.exception('Parse Error') errors.append(fn) else: pass log.info('Parsed [{}] IOCs'.format(len(self))) return errors
[ "def", "insert", "(", "self", ",", "filename", ")", ":", "errors", "=", "[", "]", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "log", ".", "info", "(", "'loading IOC from: {}'", ".", "format", "(", "filename", ")", ")", "try", ":", "self", ".", "parse", "(", "ioc_api", ".", "IOC", "(", "filename", ")", ")", "except", "ioc_api", ".", "IOCParseError", ":", "log", ".", "exception", "(", "'Parse Error'", ")", "errors", ".", "append", "(", "filename", ")", "elif", "os", ".", "path", ".", "isdir", "(", "filename", ")", ":", "log", ".", "info", "(", "'loading IOCs from: {}'", ".", "format", "(", "filename", ")", ")", "for", "fn", "in", "glob", ".", "glob", "(", "filename", "+", "os", ".", "path", ".", "sep", "+", "'*.ioc'", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "fn", ")", ":", "continue", "else", ":", "try", ":", "self", ".", "parse", "(", "ioc_api", ".", "IOC", "(", "fn", ")", ")", "except", "ioc_api", ".", "IOCParseError", ":", "log", ".", "exception", "(", "'Parse Error'", ")", "errors", ".", "append", "(", "fn", ")", "else", ":", "pass", "log", ".", "info", "(", "'Parsed [{}] IOCs'", ".", "format", "(", "len", "(", "self", ")", ")", ")", "return", "errors" ]
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.
[ "Parses", "files", "to", "load", "them", "into", "memory", "and", "insert", "them", "into", "the", "class", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/managers/__init__.py#L51-L80
mandiant/ioc_writer
ioc_writer/managers/__init__.py
IOCManager.parse
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_shortName: {}]'.format(iocid, self.ioc_name[iocid], sd) log.warning(msg) self.iocs[iocid] = ioc_obj self.ioc_name[iocid] = sd if self.parser_callback: self.parser_callback(ioc_obj) return True
python
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_shortName: {}]'.format(iocid, self.ioc_name[iocid], sd) log.warning(msg) self.iocs[iocid] = ioc_obj self.ioc_name[iocid] = sd if self.parser_callback: self.parser_callback(ioc_obj) return True
[ "def", "parse", "(", "self", ",", "ioc_obj", ")", ":", "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_shortName: {}]'", ".", "format", "(", "iocid", ",", "self", ".", "ioc_name", "[", "iocid", "]", ",", "sd", ")", "log", ".", "warning", "(", "msg", ")", "self", ".", "iocs", "[", "iocid", "]", "=", "ioc_obj", "self", ".", "ioc_name", "[", "iocid", "]", "=", "sd", "if", "self", ".", "parser_callback", ":", "self", ".", "parser_callback", "(", "ioc_obj", ")", "return", "True" ]
parses an ioc to populate self.iocs and self.ioc_name :param ioc_obj: :return:
[ "parses", "an", "ioc", "to", "populate", "self", ".", "iocs", "and", "self", ".", "ioc_name" ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/managers/__init__.py#L82-L105
mandiant/ioc_writer
ioc_writer/managers/__init__.py
IOCManager.register_parser_callback
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 use by subclasses that may have additional parsing requirements. :param func: A callable function. This should accept a single input, which will be an IOC class. :return: """ 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))
python
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 use by subclasses that may have additional parsing requirements. :param func: A callable function. This should accept a single input, which will be an IOC class. :return: """ 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))
[ "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: {}'", ".", "format", "(", "func", ")", ")" ]
Register a callback function that is called after self.iocs and self.ioc_name is populated. This is intended for use by subclasses that may have additional parsing requirements. :param func: A callable function. This should accept a single input, which will be an IOC class. :return:
[ "Register", "a", "callback", "function", "that", "is", "called", "after", "self", ".", "iocs", "and", "self", ".", "ioc_name", "is", "populated", "." ]
train
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/managers/__init__.py#L107-L120
koordinates/python-client
koordinates/permissions.py
PermissionManager.create
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 permission._deserialize(r.json(), self)
python
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 permission._deserialize(r.json(), self)
[ "def", "create", "(", "self", ",", "permission", ")", ":", "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", "permission", ".", "_deserialize", "(", "r", ".", "json", "(", ")", ",", "self", ")" ]
Create single permission for the given object. :param Permission permission: A single Permission object to be set.
[ "Create", "single", "permission", "for", "the", "given", "object", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/permissions.py#L35-L44
koordinates/python-client
koordinates/permissions.py
PermissionManager.set
def set(self, permissions): """ Set the object permissions. If the parent object already has permissions, they will be overwritten. :param [] permissions: A group of Permission objects 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, 'PUT', 'multi') r = self.client.request('PUT', target_url, json=permissions) if r.status_code != 201: raise exceptions.ServerError("Expected 201 response, got %s: %s" % (r.status_code, target_url)) return self.list()
python
def set(self, permissions): """ Set the object permissions. If the parent object already has permissions, they will be overwritten. :param [] permissions: A group of Permission objects 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, 'PUT', 'multi') r = self.client.request('PUT', target_url, json=permissions) if r.status_code != 201: raise exceptions.ServerError("Expected 201 response, got %s: %s" % (r.status_code, target_url)) return self.list()
[ "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", ".", "client", ".", "request", "(", "'PUT'", ",", "target_url", ",", "json", "=", "permissions", ")", "if", "r", ".", "status_code", "!=", "201", ":", "raise", "exceptions", ".", "ServerError", "(", "\"Expected 201 response, got %s: %s\"", "%", "(", "r", ".", "status_code", ",", "target_url", ")", ")", "return", "self", ".", "list", "(", ")" ]
Set the object permissions. If the parent object already has permissions, they will be overwritten. :param [] permissions: A group of Permission objects to be set.
[ "Set", "the", "object", "permissions", ".", "If", "the", "parent", "object", "already", "has", "permissions", "they", "will", "be", "overwritten", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/permissions.py#L46-L57
koordinates/python-client
koordinates/permissions.py
PermissionManager.list
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)
python
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)
[ "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", "base", ".", "Query", "(", "self", ",", "target_url", ")" ]
List permissions for the given object.
[ "List", "permissions", "for", "the", "given", "object", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/permissions.py#L59-L65
koordinates/python-client
koordinates/permissions.py
PermissionManager.get
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)
python
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)
[ "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_KEY", ",", "'GET'", ",", "'single'", ",", "{", "'permission_id'", ":", "permission_id", "}", ")", "return", "self", ".", "_get", "(", "target_url", ",", "expand", "=", "expand", ")" ]
List a specific permisison for the given object. :param str permission_id: the id of the Permission to be listed.
[ "List", "a", "specific", "permisison", "for", "the", "given", "object", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/permissions.py#L67-L76
michaelaye/pyciss
pyciss/io.py
get_config
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
python
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
[ "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", ")", ")", "return", "config" ]
Read the configfile and return config dict. Returns ------- dict Dictionary with the content of the configpath file.
[ "Read", "the", "configfile", "and", "return", "config", "dict", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/io.py#L23-L37
michaelaye/pyciss
pyciss/io.py
set_database_path
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() 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))
python
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() 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))
[ "def", "set_database_path", "(", "dbfolder", ")", ":", "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", ")", ")" ]
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.
[ "Use", "to", "write", "the", "database", "path", "into", "the", "config", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/io.py#L53-L70
michaelaye/pyciss
pyciss/io.py
get_db_root
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
python
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
[ "def", "get_db_root", "(", ")", ":", "d", "=", "get_config", "(", ")", "dbroot", "=", "Path", "(", "d", "[", "'pyciss_db'", "]", "[", "'path'", "]", ")", "dbroot", ".", "mkdir", "(", "exist_ok", "=", "True", ")", "return", "dbroot" ]
Read dbroot folder from config and mkdir if required.
[ "Read", "dbroot", "folder", "from", "config", "and", "mkdir", "if", "required", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/io.py#L81-L86
michaelaye/pyciss
pyciss/io.py
print_db_stats
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("**/*" + val)))] return pd.DataFrame(d)
python
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("**/*" + val)))] return pd.DataFrame(d)
[ "def", "print_db_stats", "(", ")", ":", "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", "(", "\"**/*\"", "+", "val", ")", ")", ")", "]", "return", "pd", ".", "DataFrame", "(", "d", ")" ]
Print database stats. Returns ------- pd.DataFrame Table with the found data items per type.
[ "Print", "database", "stats", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/io.py#L89-L104
michaelaye/pyciss
pyciss/io.py
is_lossy
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
python
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
[ "def", "is_lossy", "(", "label", ")", ":", "val", "=", "getkey", "(", "from_", "=", "label", ",", "keyword", "=", "'INST_CMPRS_TYPE'", ")", ".", "decode", "(", ")", ".", "strip", "(", ")", "if", "val", "==", "'LOSSY'", ":", "return", "True", "else", ":", "return", "False" ]
Check Label file for the compression type.
[ "Check", "Label", "file", "for", "the", "compression", "type", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/io.py#L237-L243
michaelaye/pyciss
pyciss/downloader.py
download_and_calibrate_parallel
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 to process n : int Number of cores for the parallel processing. Default: n_cores_system//2 """ 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"])
python
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 to process n : int Number of cores for the parallel processing. Default: n_cores_system//2 """ 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"])
[ "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\"", "]", ")" ]
Download and calibrate in parallel. Parameters ---------- list_of_ids : list, optional container with img_ids to process n : int Number of cores for the parallel processing. Default: n_cores_system//2
[ "Download", "and", "calibrate", "in", "parallel", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/downloader.py#L37-L51
michaelaye/pyciss
pyciss/downloader.py
download_and_calibrate
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: bool, optional If the pm.cubepath exists, this switch controls if it is being overwritten. Default: False """ 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("Downloading file %s" % pm.img_id) download_file_id(pm.img_id) pm = io.PathManager(img_id) # refresh, to get proper PDS version id. else: logger.info("Found ") if not (pm.cubepath.exists() and pm.undestriped.exists()) or overwrite is True: calib = pipeline.Calibrator(img_id, **kwargs) calib.standard_calib() else: print("All files exist. Use overwrite=True to redownload and calibrate.")
python
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: bool, optional If the pm.cubepath exists, this switch controls if it is being overwritten. Default: False """ 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("Downloading file %s" % pm.img_id) download_file_id(pm.img_id) pm = io.PathManager(img_id) # refresh, to get proper PDS version id. else: logger.info("Found ") if not (pm.cubepath.exists() and pm.undestriped.exists()) or overwrite is True: calib = pipeline.Calibrator(img_id, **kwargs) calib.standard_calib() else: print("All files exist. Use overwrite=True to redownload and calibrate.")
[ "def", "download_and_calibrate", "(", "img_id", "=", "None", ",", "overwrite", "=", "False", ",", "recalibrate", "=", "False", ",", "*", "*", "kwargs", ")", ":", "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", "(", "\"Downloading file %s\"", "%", "pm", ".", "img_id", ")", "download_file_id", "(", "pm", ".", "img_id", ")", "pm", "=", "io", ".", "PathManager", "(", "img_id", ")", "# refresh, to get proper PDS version id.", "else", ":", "logger", ".", "info", "(", "\"Found \"", ")", "if", "not", "(", "pm", ".", "cubepath", ".", "exists", "(", ")", "and", "pm", ".", "undestriped", ".", "exists", "(", ")", ")", "or", "overwrite", "is", "True", ":", "calib", "=", "pipeline", ".", "Calibrator", "(", "img_id", ",", "*", "*", "kwargs", ")", "calib", ".", "standard_calib", "(", ")", "else", ":", "print", "(", "\"All files exist. Use overwrite=True to redownload and calibrate.\"", ")" ]
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: bool, optional If the pm.cubepath exists, this switch controls if it is being overwritten. Default: False
[ "Download", "and", "calibrate", "one", "or", "more", "image", "ids", "in", "parallel", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/downloader.py#L54-L83
michaelaye/pyciss
pyciss/pipeline.py
Calibrator.spiceinit
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" if self.is_ring_data else None spiceinit(from_=self.pm.raw_cub, cksmithed="yes", spksmithed="yes", shape=shape) logger.info("spiceinit done.")
python
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" if self.is_ring_data else None spiceinit(from_=self.pm.raw_cub, cksmithed="yes", spksmithed="yes", shape=shape) logger.info("spiceinit done.")
[ "def", "spiceinit", "(", "self", ")", ":", "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.\"", ")" ]
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.
[ "Perform", "either", "normal", "spiceinit", "or", "one", "for", "ringdata", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/pipeline.py#L142-L151
michaelaye/pyciss
pyciss/pipeline.py
Calibrator.check_label
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 as a target, but then the standard map projection onto the Saturn ring plane fails. See also -------- https://isis.astrogeology.usgs.gov/IsisSupport/index.php/topic,3922.0.html """ 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", keyword="TargetName", value="Saturn", grpname="Instrument", )
python
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 as a target, but then the standard map projection onto the Saturn ring plane fails. See also -------- https://isis.astrogeology.usgs.gov/IsisSupport/index.php/topic,3922.0.html """ 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", keyword="TargetName", value="Saturn", grpname="Instrument", )
[ "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_", "=", "self", ".", "pm", ".", "raw_cub", ",", "options", "=", "\"modkey\"", ",", "keyword", "=", "\"TargetName\"", ",", "value", "=", "\"Saturn\"", ",", "grpname", "=", "\"Instrument\"", ",", ")" ]
Check label for target and fix if necessary. Forcing the target name to Saturn here, because some observations of the rings have moons as a target, but then the standard map projection onto the Saturn ring plane fails. See also -------- https://isis.astrogeology.usgs.gov/IsisSupport/index.php/topic,3922.0.html
[ "Check", "label", "for", "target", "and", "fix", "if", "necessary", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/pipeline.py#L153-L177
JenkinsDev/pelican-readtime
readtime.py
ReadTimeParser._set_supported_content_type
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
python
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
[ "def", "_set_supported_content_type", "(", "self", ",", "content_types_supported", ")", ":", "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" ]
Checks and sets the supported content types configuration value.
[ "Checks", "and", "sets", "the", "supported", "content", "types", "configuration", "value", "." ]
train
https://github.com/JenkinsDev/pelican-readtime/blob/9440eb062950cb34111170e057f1e73c82bdce9a/readtime.py#L20-L27
JenkinsDev/pelican-readtime
readtime.py
ReadTimeParser._set_lang_settings
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 compatability reasons we'll allow the # READTIME_WPM setting to be set as an to override just the default # set WPM. if is_int: self.lang_settings['default']['wpm'] = lang_settings elif is_dict: for lang, conf in lang_settings.items(): if 'wpm' not in conf: raise KeyError(('Missing wpm value for the' 'language: {}'.format(lang))) if not isinstance(conf['wpm'], int): raise TypeError(('WPM is not an integer for' ' the language: {}'.format(lang))) if "min_singular" not in conf: raise KeyError(('Missing singular form for "minute" for' ' the language: {}'.format(lang))) if "min_plural" not in conf: raise KeyError(('Missing plural form for "minutes" for' ' the language: {}'.format(lang))) if "sec_singular" not in conf: raise KeyError(('Missing singular form for "second" for' ' the language: {}'.format(lang))) if "sec_plural" not in conf: raise KeyError(('Missing plural form for "seconds" for' ' the language: {}'.format(lang))) self.lang_settings = lang_settings
python
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 compatability reasons we'll allow the # READTIME_WPM setting to be set as an to override just the default # set WPM. if is_int: self.lang_settings['default']['wpm'] = lang_settings elif is_dict: for lang, conf in lang_settings.items(): if 'wpm' not in conf: raise KeyError(('Missing wpm value for the' 'language: {}'.format(lang))) if not isinstance(conf['wpm'], int): raise TypeError(('WPM is not an integer for' ' the language: {}'.format(lang))) if "min_singular" not in conf: raise KeyError(('Missing singular form for "minute" for' ' the language: {}'.format(lang))) if "min_plural" not in conf: raise KeyError(('Missing plural form for "minutes" for' ' the language: {}'.format(lang))) if "sec_singular" not in conf: raise KeyError(('Missing singular form for "second" for' ' the language: {}'.format(lang))) if "sec_plural" not in conf: raise KeyError(('Missing plural form for "seconds" for' ' the language: {}'.format(lang))) self.lang_settings = lang_settings
[ "def", "_set_lang_settings", "(", "self", ",", "lang_settings", ")", ":", "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 compatability reasons we'll allow the", "# READTIME_WPM setting to be set as an to override just the default", "# set WPM.", "if", "is_int", ":", "self", ".", "lang_settings", "[", "'default'", "]", "[", "'wpm'", "]", "=", "lang_settings", "elif", "is_dict", ":", "for", "lang", ",", "conf", "in", "lang_settings", ".", "items", "(", ")", ":", "if", "'wpm'", "not", "in", "conf", ":", "raise", "KeyError", "(", "(", "'Missing wpm value for the'", "'language: {}'", ".", "format", "(", "lang", ")", ")", ")", "if", "not", "isinstance", "(", "conf", "[", "'wpm'", "]", ",", "int", ")", ":", "raise", "TypeError", "(", "(", "'WPM is not an integer for'", "' the language: {}'", ".", "format", "(", "lang", ")", ")", ")", "if", "\"min_singular\"", "not", "in", "conf", ":", "raise", "KeyError", "(", "(", "'Missing singular form for \"minute\" for'", "' the language: {}'", ".", "format", "(", "lang", ")", ")", ")", "if", "\"min_plural\"", "not", "in", "conf", ":", "raise", "KeyError", "(", "(", "'Missing plural form for \"minutes\" for'", "' the language: {}'", ".", "format", "(", "lang", ")", ")", ")", "if", "\"sec_singular\"", "not", "in", "conf", ":", "raise", "KeyError", "(", "(", "'Missing singular form for \"second\" for'", "' the language: {}'", ".", "format", "(", "lang", ")", ")", ")", "if", "\"sec_plural\"", "not", "in", "conf", ":", "raise", "KeyError", "(", "(", "'Missing plural form for \"seconds\" for'", "' the language: {}'", ".", "format", "(", "lang", ")", ")", ")", "self", ".", "lang_settings", "=", "lang_settings" ]
Checks and sets the per language WPM, singular and plural values.
[ "Checks", "and", "sets", "the", "per", "language", "WPM", "singular", "and", "plural", "values", "." ]
train
https://github.com/JenkinsDev/pelican-readtime/blob/9440eb062950cb34111170e057f1e73c82bdce9a/readtime.py#L29-L69
JenkinsDev/pelican-readtime
readtime.py
ReadTimeParser.initialize_settings
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( 'READTIME_WPM', self.lang_settings) self._set_lang_settings(lang_settings) except Exception as e: raise Exception("ReadTime Plugin: %s" % str(e))
python
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( 'READTIME_WPM', self.lang_settings) self._set_lang_settings(lang_settings) except Exception as e: raise Exception("ReadTime Plugin: %s" % str(e))
[ "def", "initialize_settings", "(", "self", ",", "sender", ")", ":", "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", "(", "'READTIME_WPM'", ",", "self", ".", "lang_settings", ")", "self", ".", "_set_lang_settings", "(", "lang_settings", ")", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "\"ReadTime Plugin: %s\"", "%", "str", "(", "e", ")", ")" ]
Initializes ReadTimeParser with configuration values set by the site author.
[ "Initializes", "ReadTimeParser", "with", "configuration", "values", "set", "by", "the", "site", "author", "." ]
train
https://github.com/JenkinsDev/pelican-readtime/blob/9440eb062950cb34111170e057f1e73c82bdce9a/readtime.py#L71-L86
JenkinsDev/pelican-readtime
readtime.py
ReadTimeParser.read_time
def read_time(self, content): """ Core function used to generate the read_time for content. Parameters: :param content: Instance of pelican.content.Content Returns: None """ 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_lang_conf) avg_reading_wpm = lang_conf['wpm'] num_words = len(content._content.split()) # Floor division so we don't have to convert float -> int minutes = num_words // avg_reading_wpm # Get seconds to read, then subtract our minutes as seconds from # the time to get remainder seconds seconds = int((num_words / avg_reading_wpm * 60) - (minutes * 60)) minutes_str = self.pluralize( minutes, lang_conf['min_singular'], lang_conf['min_plural'] ) seconds_str = self.pluralize( seconds, lang_conf['sec_singular'], lang_conf['sec_plural'] ) content.readtime = minutes content.readtime_string = minutes_str content.readtime_with_seconds = (minutes, seconds,) content.readtime_string_with_seconds = "{}, {}".format( minutes_str, seconds_str)
python
def read_time(self, content): """ Core function used to generate the read_time for content. Parameters: :param content: Instance of pelican.content.Content Returns: None """ 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_lang_conf) avg_reading_wpm = lang_conf['wpm'] num_words = len(content._content.split()) # Floor division so we don't have to convert float -> int minutes = num_words // avg_reading_wpm # Get seconds to read, then subtract our minutes as seconds from # the time to get remainder seconds seconds = int((num_words / avg_reading_wpm * 60) - (minutes * 60)) minutes_str = self.pluralize( minutes, lang_conf['min_singular'], lang_conf['min_plural'] ) seconds_str = self.pluralize( seconds, lang_conf['sec_singular'], lang_conf['sec_plural'] ) content.readtime = minutes content.readtime_string = minutes_str content.readtime_with_seconds = (minutes, seconds,) content.readtime_string_with_seconds = "{}, {}".format( minutes_str, seconds_str)
[ "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", "[", "'default'", "]", "lang_conf", "=", "self", ".", "lang_settings", ".", "get", "(", "content", ".", "lang", ",", "default_lang_conf", ")", "avg_reading_wpm", "=", "lang_conf", "[", "'wpm'", "]", "num_words", "=", "len", "(", "content", ".", "_content", ".", "split", "(", ")", ")", "# Floor division so we don't have to convert float -> int", "minutes", "=", "num_words", "//", "avg_reading_wpm", "# Get seconds to read, then subtract our minutes as seconds from", "# the time to get remainder seconds", "seconds", "=", "int", "(", "(", "num_words", "/", "avg_reading_wpm", "*", "60", ")", "-", "(", "minutes", "*", "60", ")", ")", "minutes_str", "=", "self", ".", "pluralize", "(", "minutes", ",", "lang_conf", "[", "'min_singular'", "]", ",", "lang_conf", "[", "'min_plural'", "]", ")", "seconds_str", "=", "self", ".", "pluralize", "(", "seconds", ",", "lang_conf", "[", "'sec_singular'", "]", ",", "lang_conf", "[", "'sec_plural'", "]", ")", "content", ".", "readtime", "=", "minutes", "content", ".", "readtime_string", "=", "minutes_str", "content", ".", "readtime_with_seconds", "=", "(", "minutes", ",", "seconds", ",", ")", "content", ".", "readtime_string_with_seconds", "=", "\"{}, {}\"", ".", "format", "(", "minutes_str", ",", "seconds_str", ")" ]
Core function used to generate the read_time for content. Parameters: :param content: Instance of pelican.content.Content Returns: None
[ "Core", "function", "used", "to", "generate", "the", "read_time", "for", "content", "." ]
train
https://github.com/JenkinsDev/pelican-readtime/blob/9440eb062950cb34111170e057f1e73c82bdce9a/readtime.py#L88-L129
JenkinsDev/pelican-readtime
readtime.py
ReadTimeParser.pluralize
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 chosen word :param plural: The plural form of the chosen word Returns: String """ if measure == 1: return "{} {}".format(measure, singular) else: return "{} {}".format(measure, plural)
python
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 chosen word :param plural: The plural form of the chosen word Returns: String """ if measure == 1: return "{} {}".format(measure, singular) else: return "{} {}".format(measure, plural)
[ "def", "pluralize", "(", "self", ",", "measure", ",", "singular", ",", "plural", ")", ":", "if", "measure", "==", "1", ":", "return", "\"{} {}\"", ".", "format", "(", "measure", ",", "singular", ")", "else", ":", "return", "\"{} {}\"", ".", "format", "(", "measure", ",", "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 chosen word :param plural: The plural form of the chosen word Returns: String
[ "Returns", "a", "string", "that", "contains", "the", "measure", "(", "amount", ")", "and", "its", "plural", "or", "singular", "form", "depending", "on", "the", "amount", "." ]
train
https://github.com/JenkinsDev/pelican-readtime/blob/9440eb062950cb34111170e057f1e73c82bdce9a/readtime.py#L131-L146
koordinates/python-client
koordinates/sources.py
SourceManager.list_datasources
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)
python
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)
[ "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", ")" ]
Filterable list of Datasources for a Source.
[ "Filterable", "list", "of", "Datasources", "for", "a", "Source", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/sources.py#L65-L70
koordinates/python-client
koordinates/sources.py
SourceManager.get_datasource
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)
python
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)
[ "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", ")" ]
Get a Datasource object :rtype: Datasource
[ "Get", "a", "Datasource", "object" ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/sources.py#L72-L79
koordinates/python-client
koordinates/sources.py
SourceManager.list_scans
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)
python
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)
[ "def", "list_scans", "(", "self", ",", "source_id", "=", "None", ")", ":", "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", ")" ]
Filterable list of Scans for a Source. Ordered newest to oldest by default
[ "Filterable", "list", "of", "Scans", "for", "a", "Source", ".", "Ordered", "newest", "to", "oldest", "by", "default" ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/sources.py#L81-L90
koordinates/python-client
koordinates/sources.py
SourceManager.get_scan
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)
python
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)
[ "def", "get_scan", "(", "self", ",", "source_id", ",", "scan_id", ")", ":", "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", ")" ]
Get a Scan object :rtype: Scan
[ "Get", "a", "Scan", "object" ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/sources.py#L92-L99
koordinates/python-client
koordinates/sources.py
SourceManager.get_scan_log_lines
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)
python
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)
[ "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", ")" ]
Get the log text for a Scan :rtype: Iterator over log lines.
[ "Get", "the", "log", "text", "for", "a", "Scan" ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/sources.py#L101-L107
koordinates/python-client
koordinates/sources.py
SourceManager.start_scan
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())
python
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())
[ "def", "start_scan", "(", "self", ",", "source_id", ")", ":", "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", "(", ")", ")" ]
Start a new scan of a Source. :rtype: Scan
[ "Start", "a", "new", "scan", "of", "a", "Source", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/sources.py#L109-L117
koordinates/python-client
koordinates/sources.py
Source.save
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)
python
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)
[ "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", ")" ]
Edits this Source
[ "Edits", "this", "Source" ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/sources.py#L158-L163
koordinates/python-client
koordinates/sources.py
Source.delete
def delete(self): """ Delete this source """ r = self._client.request('DELETE', self.url) logger.info("delete(): %s", r.status_code)
python
def delete(self): """ Delete this source """ r = self._client.request('DELETE', self.url) logger.info("delete(): %s", r.status_code)
[ "def", "delete", "(", "self", ")", ":", "r", "=", "self", ".", "_client", ".", "request", "(", "'DELETE'", ",", "self", ".", "url", ")", "logger", ".", "info", "(", "\"delete(): %s\"", ",", "r", ".", "status_code", ")" ]
Delete this source
[ "Delete", "this", "source" ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/sources.py#L166-L169
koordinates/python-client
koordinates/sources.py
UploadSource.add_file
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 must be in one of these three formats: - ISO 19115/19139 - FGDC CSDGM - Dublin Core (OAI-PMH) :param fp: File to upload into this source, can be a path or a file-like object. :type fp: str or file :param str upload_path: relative path to store the file as within the source (eg. ``folder/0001.tif``). \ By default it will use ``fp``, either the filename from a path or the ``.name`` \ attribute of a file-like object. :param str content_type: Content-Type of the file. By default it will attempt to auto-detect from the \ file/upload_path. """ 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 upload_path: upload_path = os.path.split(fp.name)[1] content_type = content_type or mimetypes.guess_type(upload_path, strict=False)[0] if upload_path in self._files: raise ClientValidationError("Duplicate upload path: %s" % upload_path) self._files[upload_path] = (fp, content_type) logger.debug("UploadSource.add_file: %s -> %s (%s)", repr(fp), upload_path, content_type)
python
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 must be in one of these three formats: - ISO 19115/19139 - FGDC CSDGM - Dublin Core (OAI-PMH) :param fp: File to upload into this source, can be a path or a file-like object. :type fp: str or file :param str upload_path: relative path to store the file as within the source (eg. ``folder/0001.tif``). \ By default it will use ``fp``, either the filename from a path or the ``.name`` \ attribute of a file-like object. :param str content_type: Content-Type of the file. By default it will attempt to auto-detect from the \ file/upload_path. """ 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 upload_path: upload_path = os.path.split(fp.name)[1] content_type = content_type or mimetypes.guess_type(upload_path, strict=False)[0] if upload_path in self._files: raise ClientValidationError("Duplicate upload path: %s" % upload_path) self._files[upload_path] = (fp, content_type) logger.debug("UploadSource.add_file: %s -> %s (%s)", repr(fp), upload_path, content_type)
[ "def", "add_file", "(", "self", ",", "fp", ",", "upload_path", "=", "None", ",", "content_type", "=", "None", ")", ":", "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", "upload_path", ":", "upload_path", "=", "os", ".", "path", ".", "split", "(", "fp", ".", "name", ")", "[", "1", "]", "content_type", "=", "content_type", "or", "mimetypes", ".", "guess_type", "(", "upload_path", ",", "strict", "=", "False", ")", "[", "0", "]", "if", "upload_path", "in", "self", ".", "_files", ":", "raise", "ClientValidationError", "(", "\"Duplicate upload path: %s\"", "%", "upload_path", ")", "self", ".", "_files", "[", "upload_path", "]", "=", "(", "fp", ",", "content_type", ")", "logger", ".", "debug", "(", "\"UploadSource.add_file: %s -> %s (%s)\"", ",", "repr", "(", "fp", ")", ",", "upload_path", ",", "content_type", ")" ]
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 must be in one of these three formats: - ISO 19115/19139 - FGDC CSDGM - Dublin Core (OAI-PMH) :param fp: File to upload into this source, can be a path or a file-like object. :type fp: str or file :param str upload_path: relative path to store the file as within the source (eg. ``folder/0001.tif``). \ By default it will use ``fp``, either the filename from a path or the ``.name`` \ attribute of a file-like object. :param str content_type: Content-Type of the file. By default it will attempt to auto-detect from the \ file/upload_path.
[ "Add", "a", "single", "file", "or", "archive", "to", "upload", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/sources.py#L258-L294
koordinates/python-client
koordinates/sources.py
ScanManager.get_log_lines
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={'Accept': 'text/plain'}, stream=True) return r.iter_lines(decode_unicode=True)
python
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={'Accept': 'text/plain'}, stream=True) return r.iter_lines(decode_unicode=True)
[ "def", "get_log_lines", "(", "self", ",", "source_id", ",", "scan_id", ")", ":", "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", "=", "{", "'Accept'", ":", "'text/plain'", "}", ",", "stream", "=", "True", ")", "return", "r", ".", "iter_lines", "(", "decode_unicode", "=", "True", ")" ]
Get the log text for a scan object :rtype: Iterator over log lines.
[ "Get", "the", "log", "text", "for", "a", "scan", "object", ":", "rtype", ":", "Iterator", "over", "log", "lines", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/sources.py#L300-L307
koordinates/python-client
koordinates/sources.py
Scan.get_log_lines
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)
python
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)
[ "def", "get_log_lines", "(", "self", ")", ":", "rel", "=", "self", ".", "_client", ".", "reverse_url", "(", "'SCAN'", ",", "self", ".", "url", ")", "return", "self", ".", "_manager", ".", "get_log_lines", "(", "*", "*", "rel", ")" ]
Get the log text for a scan object :rtype: Iterator over log lines.
[ "Get", "the", "log", "text", "for", "a", "scan", "object" ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/sources.py#L336-L343
koordinates/python-client
koordinates/licenses.py
LicenseManager.get_creative_commons
def get_creative_commons(self, slug, jurisdiction=None): """Returns the Creative Commons license for the given attributes. :param str slug: the type of Creative Commons license. It must start with ``cc-by`` and can optionally contain ``nc`` (non-commercial), ``sa`` (share-alike), ``nd`` (no derivatives) terms, seperated by hyphens. Note that a CC license cannot be both ``sa`` and ``nd`` :param str jurisdiction: The jurisdiction for a ported Creative Commons license (eg. ``nz``), or ``None`` for unported/international licenses. :rtype: License """ 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}) return self._get(target_url)
python
def get_creative_commons(self, slug, jurisdiction=None): """Returns the Creative Commons license for the given attributes. :param str slug: the type of Creative Commons license. It must start with ``cc-by`` and can optionally contain ``nc`` (non-commercial), ``sa`` (share-alike), ``nd`` (no derivatives) terms, seperated by hyphens. Note that a CC license cannot be both ``sa`` and ``nd`` :param str jurisdiction: The jurisdiction for a ported Creative Commons license (eg. ``nz``), or ``None`` for unported/international licenses. :rtype: License """ 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}) return self._get(target_url)
[ "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", "=", "self", ".", "client", ".", "get_url", "(", "self", ".", "_URL_KEY", ",", "'GET'", ",", "'cc'", ",", "{", "'slug'", ":", "slug", ",", "'jurisdiction'", ":", "jurisdiction", "}", ")", "return", "self", ".", "_get", "(", "target_url", ")" ]
Returns the Creative Commons license for the given attributes. :param str slug: the type of Creative Commons license. It must start with ``cc-by`` and can optionally contain ``nc`` (non-commercial), ``sa`` (share-alike), ``nd`` (no derivatives) terms, seperated by hyphens. Note that a CC license cannot be both ``sa`` and ``nd`` :param str jurisdiction: The jurisdiction for a ported Creative Commons license (eg. ``nz``), or ``None`` for unported/international licenses. :rtype: License
[ "Returns", "the", "Creative", "Commons", "license", "for", "the", "given", "attributes", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/licenses.py#L26-L44
michaelaye/pyciss
pyciss/ringcube.py
mad
def mad(arr, relative=True): """ Median Absolute Deviation: a "Robust" version of standard deviation. Indices variabililty of the sample. https://en.wikipedia.org/wiki/Median_absolute_deviation """ 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 mad / med else: return mad
python
def mad(arr, relative=True): """ Median Absolute Deviation: a "Robust" version of standard deviation. Indices variabililty of the sample. https://en.wikipedia.org/wiki/Median_absolute_deviation """ 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 mad / med else: return mad
[ "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", "mad", "/", "med", "else", ":", "return", "mad" ]
Median Absolute Deviation: a "Robust" version of standard deviation. Indices variabililty of the sample. https://en.wikipedia.org/wiki/Median_absolute_deviation
[ "Median", "Absolute", "Deviation", ":", "a", "Robust", "version", "of", "standard", "deviation", ".", "Indices", "variabililty", "of", "the", "sample", ".", "https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Median_absolute_deviation" ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/ringcube.py#L59-L71
michaelaye/pyciss
pyciss/ringcube.py
calc_offset
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 ========== cube : pyciss.ringcube.RingCube Cubefile with ring image """ i = 0 while pd.Series(cube.img[:, i]).count() < 200: i += 1 return max(i, 20)
python
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 ========== cube : pyciss.ringcube.RingCube Cubefile with ring image """ i = 0 while pd.Series(cube.img[:, i]).count() < 200: i += 1 return max(i, 20)
[ "def", "calc_offset", "(", "cube", ")", ":", "i", "=", "0", "while", "pd", ".", "Series", "(", "cube", ".", "img", "[", ":", ",", "i", "]", ")", ".", "count", "(", ")", "<", "200", ":", "i", "+=", "1", "return", "max", "(", "i", ",", "20", ")" ]
Calculate an offset. Calculate offset from the side of data so that at least 200 image pixels are in the MAD stats. Parameters ========== cube : pyciss.ringcube.RingCube Cubefile with ring image
[ "Calculate", "an", "offset", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/ringcube.py#L74-L87
michaelaye/pyciss
pyciss/ringcube.py
RingCube.imshow
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, ): """Powerful default display. show_resonances can be True, a list, 'all', or 'some' """ 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_hist(data) self.plotted_data = data extent_val = self.extent if set_extent else None min_, max_ = self.plot_limits self.min_ = min_ self.max_ = max_ if ax is None: if not _SEABORN_INSTALLED: fig, ax = plt.subplots(figsize=calc_4_3(8)) else: fig, ax = plt.subplots() else: fig = ax.get_figure() with quantity_support(): im = ax.imshow( data, extent=extent_val, cmap="gray", vmin=min_, vmax=max_, interpolation=interpolation, origin="lower", aspect="auto", **kwargs, ) if any([rmin is not None, rmax is not None]): ax.set_ylim(rmin, rmax) self.mpl_im = im ax.set_xlabel("Longitude [deg]") ax.set_ylabel("Radius [Mm]") ax.ticklabel_format(useOffset=False) # ax.grid('on') title = self.plot_title if extra_title: title += ", " + extra_title ax.set_title(title, fontsize=12) if show_resonances: self.set_resonance_axis(ax, show_resonances, rmin, rmax) if save: savename = self.plotfname if extra_title: savename = savename[:-4] + "_" + extra_title + ".png" p = Path(savename) fullpath = Path(savepath) / p.name fig.savefig(fullpath, dpi=150) logging.info("Created %s", fullpath) self.im = im return im
python
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, ): """Powerful default display. show_resonances can be True, a list, 'all', or 'some' """ 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_hist(data) self.plotted_data = data extent_val = self.extent if set_extent else None min_, max_ = self.plot_limits self.min_ = min_ self.max_ = max_ if ax is None: if not _SEABORN_INSTALLED: fig, ax = plt.subplots(figsize=calc_4_3(8)) else: fig, ax = plt.subplots() else: fig = ax.get_figure() with quantity_support(): im = ax.imshow( data, extent=extent_val, cmap="gray", vmin=min_, vmax=max_, interpolation=interpolation, origin="lower", aspect="auto", **kwargs, ) if any([rmin is not None, rmax is not None]): ax.set_ylim(rmin, rmax) self.mpl_im = im ax.set_xlabel("Longitude [deg]") ax.set_ylabel("Radius [Mm]") ax.ticklabel_format(useOffset=False) # ax.grid('on') title = self.plot_title if extra_title: title += ", " + extra_title ax.set_title(title, fontsize=12) if show_resonances: self.set_resonance_axis(ax, show_resonances, rmin, rmax) if save: savename = self.plotfname if extra_title: savename = savename[:-4] + "_" + extra_title + ".png" p = Path(savename) fullpath = Path(savepath) / p.name fig.savefig(fullpath, dpi=150) logging.info("Created %s", fullpath) self.im = im return im
[ "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", ",", ")", ":", "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_hist", "(", "data", ")", "self", ".", "plotted_data", "=", "data", "extent_val", "=", "self", ".", "extent", "if", "set_extent", "else", "None", "min_", ",", "max_", "=", "self", ".", "plot_limits", "self", ".", "min_", "=", "min_", "self", ".", "max_", "=", "max_", "if", "ax", "is", "None", ":", "if", "not", "_SEABORN_INSTALLED", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "calc_4_3", "(", "8", ")", ")", "else", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", ")", "else", ":", "fig", "=", "ax", ".", "get_figure", "(", ")", "with", "quantity_support", "(", ")", ":", "im", "=", "ax", ".", "imshow", "(", "data", ",", "extent", "=", "extent_val", ",", "cmap", "=", "\"gray\"", ",", "vmin", "=", "min_", ",", "vmax", "=", "max_", ",", "interpolation", "=", "interpolation", ",", "origin", "=", "\"lower\"", ",", "aspect", "=", "\"auto\"", ",", "*", "*", "kwargs", ",", ")", "if", "any", "(", "[", "rmin", "is", "not", "None", ",", "rmax", "is", "not", "None", "]", ")", ":", "ax", ".", "set_ylim", "(", "rmin", ",", "rmax", ")", "self", ".", "mpl_im", "=", "im", "ax", ".", "set_xlabel", "(", "\"Longitude [deg]\"", ")", "ax", ".", "set_ylabel", "(", "\"Radius [Mm]\"", ")", "ax", ".", "ticklabel_format", "(", "useOffset", "=", "False", ")", "# ax.grid('on')", "title", "=", "self", ".", "plot_title", "if", "extra_title", ":", "title", "+=", "\", \"", "+", "extra_title", "ax", ".", "set_title", "(", "title", ",", "fontsize", "=", "12", ")", "if", "show_resonances", ":", "self", ".", "set_resonance_axis", "(", "ax", ",", "show_resonances", ",", "rmin", ",", "rmax", ")", "if", "save", ":", "savename", "=", "self", ".", "plotfname", "if", "extra_title", ":", "savename", "=", "savename", "[", ":", "-", "4", "]", "+", "\"_\"", "+", "extra_title", "+", "\".png\"", "p", "=", "Path", "(", "savename", ")", "fullpath", "=", "Path", "(", "savepath", ")", "/", "p", ".", "name", "fig", ".", "savefig", "(", "fullpath", ",", "dpi", "=", "150", ")", "logging", ".", "info", "(", "\"Created %s\"", ",", "fullpath", ")", "self", ".", "im", "=", "im", "return", "im" ]
Powerful default display. show_resonances can be True, a list, 'all', or 'some'
[ "Powerful", "default", "display", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/ringcube.py#L259-L335
koordinates/python-client
koordinates/base.py
Query._update_range
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
python
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
[ "def", "_update_range", "(", "self", ",", "response", ")", ":", "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" ]
Update the query count property from the `X-Resource-Range` response header
[ "Update", "the", "query", "count", "property", "from", "the", "X", "-", "Resource", "-", "Range", "response", "header" ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/base.py#L146-L153
koordinates/python-client
koordinates/base.py
Query._to_url
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.urlencode(params, doseq=True) return url
python
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.urlencode(params, doseq=True) return url
[ "def", "_to_url", "(", "self", ")", ":", "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", ".", "urlencode", "(", "params", ",", "doseq", "=", "True", ")", "return", "url" ]
Serialises this query into a request-able URL including parameters
[ "Serialises", "this", "query", "into", "a", "request", "-", "able", "URL", "including", "parameters" ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/base.py#L155-L168
koordinates/python-client
koordinates/base.py
Query.extra
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) return q
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) return q
[ "def", "extra", "(", "self", ",", "*", "*", "params", ")", ":", "q", "=", "self", ".", "_clone", "(", ")", "for", "key", ",", "value", "in", "params", ".", "items", "(", ")", ":", "q", ".", "_extra", "[", "key", "]", ".", "append", "(", "value", ")", "return", "q" ]
Set extra query parameters (eg. filter expressions/attributes that don't validate). Appends to any previous extras set. :rtype: Query
[ "Set", "extra", "query", "parameters", "(", "eg", ".", "filter", "expressions", "/", "attributes", "that", "don", "t", "validate", ")", ".", "Appends", "to", "any", "previous", "extras", "set", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/base.py#L267-L277
koordinates/python-client
koordinates/base.py
Query.filter
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 __ as a separator in the Python library, the APIs use '.' q._filters['.'.join(filter_key)].append(value) return q
python
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 __ as a separator in the Python library, the APIs use '.' q._filters['.'.join(filter_key)].append(value) return q
[ "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", ":", "raise", "ClientValidationError", "(", "\"Invalid filter attribute: %s\"", "%", "key", ")", "# we use __ as a separator in the Python library, the APIs use '.'", "q", ".", "_filters", "[", "'.'", ".", "join", "(", "filter_key", ")", "]", ".", "append", "(", "value", ")", "return", "q" ]
Add a filter to this query. Appends to any previous filters set. :rtype: Query
[ "Add", "a", "filter", "to", "this", "query", ".", "Appends", "to", "any", "previous", "filters", "set", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/base.py#L279-L296
koordinates/python-client
koordinates/base.py
Query.order_by
def order_by(self, sort_key=None): """ Set the sort for this query. Not all attributes are sorting candidates. To sort in descending order, call ``Query.order_by('-attribute')``. Calling ``Query.order_by()`` replaces any previous ordering. :rtype: Query """ 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 attribute: %s" % sort_key) q = self._clone() q._order_by = sort_key return q
python
def order_by(self, sort_key=None): """ Set the sort for this query. Not all attributes are sorting candidates. To sort in descending order, call ``Query.order_by('-attribute')``. Calling ``Query.order_by()`` replaces any previous ordering. :rtype: Query """ 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 attribute: %s" % sort_key) q = self._clone() q._order_by = sort_key return q
[ "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 attribute: %s\"", "%", "sort_key", ")", "q", "=", "self", ".", "_clone", "(", ")", "q", ".", "_order_by", "=", "sort_key", "return", "q" ]
Set the sort for this query. Not all attributes are sorting candidates. To sort in descending order, call ``Query.order_by('-attribute')``. Calling ``Query.order_by()`` replaces any previous ordering. :rtype: Query
[ "Set", "the", "sort", "for", "this", "query", ".", "Not", "all", "attributes", "are", "sorting", "candidates", ".", "To", "sort", "in", "descending", "order", "call", "Query", ".", "order_by", "(", "-", "attribute", ")", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/base.py#L298-L314
koordinates/python-client
koordinates/base.py
SerializableBase._deserialize
def _deserialize(self, data): """ Deserialise from JSON response data. String items named ``*_at`` are turned into dates. Filters out: * attribute names in ``Meta.deserialize_skip`` :param data dict: JSON-style object with instance data. :return: this instance """ 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 key not in skip: value = self._deserialize_value(key, value) setattr(self, key, value) return self
python
def _deserialize(self, data): """ Deserialise from JSON response data. String items named ``*_at`` are turned into dates. Filters out: * attribute names in ``Meta.deserialize_skip`` :param data dict: JSON-style object with instance data. :return: this instance """ 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 key not in skip: value = self._deserialize_value(key, value) setattr(self, key, value) return self
[ "def", "_deserialize", "(", "self", ",", "data", ")", ":", "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", "key", "not", "in", "skip", ":", "value", "=", "self", ".", "_deserialize_value", "(", "key", ",", "value", ")", "setattr", "(", "self", ",", "key", ",", "value", ")", "return", "self" ]
Deserialise from JSON response data. String items named ``*_at`` are turned into dates. Filters out: * attribute names in ``Meta.deserialize_skip`` :param data dict: JSON-style object with instance data. :return: this instance
[ "Deserialise", "from", "JSON", "response", "data", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/base.py#L428-L452
koordinates/python-client
koordinates/base.py
SerializableBase._serialize
def _serialize(self, skip_empty=True): """ Serialise this instance into JSON-style request data. Filters out: * attribute names starting with ``_`` * attribute values that are ``None`` (unless ``skip_empty`` is ``False``) * attribute values that are empty lists/tuples/dicts (unless ``skip_empty`` is ``False``) * attribute names in ``Meta.serialize_skip`` * constants set on the model class Inner :py:class:`Model` instances get :py:meth:`._serialize` called on them. Date and datetime objects are converted into ISO 8601 strings. :param bool skip_empty: whether to skip attributes where the value is ``None`` :rtype: dict """ 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 isinstance(v, (dict, list, tuple, set)) and len(v) == 0 and skip_empty: continue else: r[k] = self._serialize_value(v) return r
python
def _serialize(self, skip_empty=True): """ Serialise this instance into JSON-style request data. Filters out: * attribute names starting with ``_`` * attribute values that are ``None`` (unless ``skip_empty`` is ``False``) * attribute values that are empty lists/tuples/dicts (unless ``skip_empty`` is ``False``) * attribute names in ``Meta.serialize_skip`` * constants set on the model class Inner :py:class:`Model` instances get :py:meth:`._serialize` called on them. Date and datetime objects are converted into ISO 8601 strings. :param bool skip_empty: whether to skip attributes where the value is ``None`` :rtype: dict """ 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 isinstance(v, (dict, list, tuple, set)) and len(v) == 0 and skip_empty: continue else: r[k] = self._serialize_value(v) return r
[ "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", ":", "continue", "elif", "v", "is", "None", "and", "skip_empty", ":", "continue", "elif", "isinstance", "(", "v", ",", "(", "dict", ",", "list", ",", "tuple", ",", "set", ")", ")", "and", "len", "(", "v", ")", "==", "0", "and", "skip_empty", ":", "continue", "else", ":", "r", "[", "k", "]", "=", "self", ".", "_serialize_value", "(", "v", ")", "return", "r" ]
Serialise this instance into JSON-style request data. Filters out: * attribute names starting with ``_`` * attribute values that are ``None`` (unless ``skip_empty`` is ``False``) * attribute values that are empty lists/tuples/dicts (unless ``skip_empty`` is ``False``) * attribute names in ``Meta.serialize_skip`` * constants set on the model class Inner :py:class:`Model` instances get :py:meth:`._serialize` called on them. Date and datetime objects are converted into ISO 8601 strings. :param bool skip_empty: whether to skip attributes where the value is ``None`` :rtype: dict
[ "Serialise", "this", "instance", "into", "JSON", "-", "style", "request", "data", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/base.py#L459-L490
koordinates/python-client
koordinates/base.py
SerializableBase._serialize_value
def _serialize_value(self, value): """ Called by :py:meth:`._serialize` to serialise an individual 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()]) elif isinstance(value, ModelBase): return value._serialize() elif isinstance(value, datetime.date): # includes datetime.datetime return value.isoformat() else: return value
python
def _serialize_value(self, value): """ Called by :py:meth:`._serialize` to serialise an individual 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()]) elif isinstance(value, ModelBase): return value._serialize() elif isinstance(value, datetime.date): # includes datetime.datetime return value.isoformat() else: return value
[ "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", "(", ")", "]", ")", "elif", "isinstance", "(", "value", ",", "ModelBase", ")", ":", "return", "value", ".", "_serialize", "(", ")", "elif", "isinstance", "(", "value", ",", "datetime", ".", "date", ")", ":", "# includes datetime.datetime", "return", "value", ".", "isoformat", "(", ")", "else", ":", "return", "value" ]
Called by :py:meth:`._serialize` to serialise an individual value.
[ "Called", "by", ":", "py", ":", "meth", ":", ".", "_serialize", "to", "serialise", "an", "individual", "value", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/base.py#L492-L505
koordinates/python-client
koordinates/base.py
Model.refresh
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 overwritten. """ r = self._client.request('GET', self.url) return self._deserialize(r.json(), self._manager)
python
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 overwritten. """ r = self._client.request('GET', self.url) return self._deserialize(r.json(), self._manager)
[ "def", "refresh", "(", "self", ")", ":", "r", "=", "self", ".", "_client", ".", "request", "(", "'GET'", ",", "self", ".", "url", ")", "return", "self", ".", "_deserialize", "(", "r", ".", "json", "(", ")", ",", "self", ".", "_manager", ")" ]
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 overwritten.
[ "Refresh", "this", "model", "from", "the", "server", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/base.py#L610-L621
koordinates/python-client
koordinates/exports.py
CropLayerManager.get_feature
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 cropping feature :rtype: CropFeature """ 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)
python
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 cropping feature :rtype: CropFeature """ 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)
[ "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_url", ")" ]
Gets a crop feature :param int croplayer_id: ID of a cropping layer :param int cropfeature_id: ID of a cropping feature :rtype: CropFeature
[ "Gets", "a", "crop", "feature" ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/exports.py#L37-L46
koordinates/python-client
koordinates/exports.py
ExportManager.create
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)
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._serialize()) return export._deserialize(r.json(), self)
[ "def", "create", "(", "self", ",", "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", ")" ]
Create and start processing a new Export. :param Export export: The Export to create. :rtype: Export
[ "Create", "and", "start", "processing", "a", "new", "Export", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/exports.py#L112-L121
koordinates/python-client
koordinates/exports.py
ExportManager.validate
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())
python
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())
[ "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", "response_object", ".", "_deserialize", "(", "r", ".", "json", "(", ")", ")" ]
Validates an Export. :param Export export: :rtype: ExportValidationResponse
[ "Validates", "an", "Export", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/exports.py#L123-L134
koordinates/python-client
koordinates/exports.py
ExportManager._options
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
python
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
[ "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", "(", ")", "return", "self", ".", "_options_cache" ]
Returns a raw options object :rtype: dict
[ "Returns", "a", "raw", "options", "object" ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/exports.py#L141-L151
koordinates/python-client
koordinates/exports.py
ExportManager.get_formats
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", #... }, "table": { "text/csv": "CSV (text/csv)", "application/x-ogc-gpkg": "GeoPackage", #... }, "raster": { "image/jpeg": "JPEG", "image/jp2": "JPEG2000", #... }, "grid": { "application/x-ogc-aaigrid": "ASCII Grid", "image/tiff;subtype=geotiff": "GeoTIFF", #... }, "rat": { "application/x-erdas-hfa": "ERDAS Imagine", #... } } :rtype: dict """ 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
python
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", #... }, "table": { "text/csv": "CSV (text/csv)", "application/x-ogc-gpkg": "GeoPackage", #... }, "raster": { "image/jpeg": "JPEG", "image/jp2": "JPEG2000", #... }, "grid": { "application/x-ogc-aaigrid": "ASCII Grid", "image/tiff;subtype=geotiff": "GeoTIFF", #... }, "rat": { "application/x-erdas-hfa": "ERDAS Imagine", #... } } :rtype: dict """ 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
[ "def", "get_formats", "(", "self", ")", ":", "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" ]
Returns a dictionary of format options keyed by data kind. .. code-block:: python { "vector": { "application/x-ogc-gpkg": "GeoPackage", "application/x-zipped-shp": "Shapefile", #... }, "table": { "text/csv": "CSV (text/csv)", "application/x-ogc-gpkg": "GeoPackage", #... }, "raster": { "image/jpeg": "JPEG", "image/jp2": "JPEG2000", #... }, "grid": { "application/x-ogc-aaigrid": "ASCII Grid", "image/tiff;subtype=geotiff": "GeoTIFF", #... }, "rat": { "application/x-erdas-hfa": "ERDAS Imagine", #... } } :rtype: dict
[ "Returns", "a", "dictionary", "of", "format", "options", "keyed", "by", "data", "kind", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/exports.py#L153-L192
koordinates/python-client
koordinates/exports.py
Export.add_item
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
python
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
[ "def", "add_item", "(", "self", ",", "item", ",", "*", "*", "options", ")", ":", "export_item", "=", "{", "\"item\"", ":", "item", ".", "url", ",", "}", "export_item", ".", "update", "(", "options", ")", "self", ".", "items", ".", "append", "(", "export_item", ")", "return", "self" ]
Add a layer or table item to the export. :param Layer|Table item: The Layer or Table to add :rtype: self
[ "Add", "a", "layer", "or", "table", "item", "to", "the", "export", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/exports.py#L239-L251
koordinates/python-client
koordinates/exports.py
Export.download
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 object as the ``path`` parameter, the function will not close that file for you. If a ``path`` parameter is a directory, this function will use the Export name to determine the name of the file (returned). If the calculated download file path already exists, this function will raise a DownloadError. You can also specify the filename as a string. This will be passed to the built-in :func:`open` and we will read the content into the file. Instead, if you want to manage the file object yourself, you need to provide either a :class:`io.BytesIO` object or a file opened with the `'b'` flag. See the two examples below for more details. :param path: Either a string with the path to the location to save the response content, or a file-like object expecting bytes. :param function progress_callback: An optional callback function which receives upload progress notifications. The function should take two arguments: the number of bytes recieved, and the total number of bytes to recieve. :param int chunk_size: Chunk size in bytes for streaming large downloads and progress reporting. 1MB by default :returns The name of the automatic filename that would be used. :rtype: str """ 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', None), collections.Callable): # already open file-like object fd = path elif os.path.isdir(path): # directory to download to, using the export name path = os.path.join(path, download_filename) # do not allow overwriting if os.path.exists(path): raise DownloadError("Download file already exists: %s" % path) elif path: # fully qualified file path # allow overwriting pass elif not path: raise DownloadError("Empty download file path") with contextlib.ExitStack() as stack: if not fd: fd = open(path, 'wb') # only close a file we open stack.callback(fd.close) r = self._manager.client.request('GET', self.download_url, stream=True) stack.callback(r.close) bytes_written = 0 try: bytes_total = int(r.headers.get('content-length', None)) except TypeError: bytes_total = None if progress_callback: # initial callback (0%) progress_callback(bytes_written, bytes_total) for chunk in r.iter_content(chunk_size=chunk_size): fd.write(chunk) bytes_written += len(chunk) if progress_callback: progress_callback(bytes_written, bytes_total) return download_filename
python
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 object as the ``path`` parameter, the function will not close that file for you. If a ``path`` parameter is a directory, this function will use the Export name to determine the name of the file (returned). If the calculated download file path already exists, this function will raise a DownloadError. You can also specify the filename as a string. This will be passed to the built-in :func:`open` and we will read the content into the file. Instead, if you want to manage the file object yourself, you need to provide either a :class:`io.BytesIO` object or a file opened with the `'b'` flag. See the two examples below for more details. :param path: Either a string with the path to the location to save the response content, or a file-like object expecting bytes. :param function progress_callback: An optional callback function which receives upload progress notifications. The function should take two arguments: the number of bytes recieved, and the total number of bytes to recieve. :param int chunk_size: Chunk size in bytes for streaming large downloads and progress reporting. 1MB by default :returns The name of the automatic filename that would be used. :rtype: str """ 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', None), collections.Callable): # already open file-like object fd = path elif os.path.isdir(path): # directory to download to, using the export name path = os.path.join(path, download_filename) # do not allow overwriting if os.path.exists(path): raise DownloadError("Download file already exists: %s" % path) elif path: # fully qualified file path # allow overwriting pass elif not path: raise DownloadError("Empty download file path") with contextlib.ExitStack() as stack: if not fd: fd = open(path, 'wb') # only close a file we open stack.callback(fd.close) r = self._manager.client.request('GET', self.download_url, stream=True) stack.callback(r.close) bytes_written = 0 try: bytes_total = int(r.headers.get('content-length', None)) except TypeError: bytes_total = None if progress_callback: # initial callback (0%) progress_callback(bytes_written, bytes_total) for chunk in r.iter_content(chunk_size=chunk_size): fd.write(chunk) bytes_written += len(chunk) if progress_callback: progress_callback(bytes_written, bytes_total) return download_filename
[ "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 know the name", "download_filename", "=", "\"{}.zip\"", ".", "format", "(", "self", ".", "name", ")", "fd", "=", "None", "if", "isinstance", "(", "getattr", "(", "path", ",", "'write'", ",", "None", ")", ",", "collections", ".", "Callable", ")", ":", "# already open file-like object", "fd", "=", "path", "elif", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "# directory to download to, using the export name", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "download_filename", ")", "# do not allow overwriting", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "DownloadError", "(", "\"Download file already exists: %s\"", "%", "path", ")", "elif", "path", ":", "# fully qualified file path", "# allow overwriting", "pass", "elif", "not", "path", ":", "raise", "DownloadError", "(", "\"Empty download file path\"", ")", "with", "contextlib", ".", "ExitStack", "(", ")", "as", "stack", ":", "if", "not", "fd", ":", "fd", "=", "open", "(", "path", ",", "'wb'", ")", "# only close a file we open", "stack", ".", "callback", "(", "fd", ".", "close", ")", "r", "=", "self", ".", "_manager", ".", "client", ".", "request", "(", "'GET'", ",", "self", ".", "download_url", ",", "stream", "=", "True", ")", "stack", ".", "callback", "(", "r", ".", "close", ")", "bytes_written", "=", "0", "try", ":", "bytes_total", "=", "int", "(", "r", ".", "headers", ".", "get", "(", "'content-length'", ",", "None", ")", ")", "except", "TypeError", ":", "bytes_total", "=", "None", "if", "progress_callback", ":", "# initial callback (0%)", "progress_callback", "(", "bytes_written", ",", "bytes_total", ")", "for", "chunk", "in", "r", ".", "iter_content", "(", "chunk_size", "=", "chunk_size", ")", ":", "fd", ".", "write", "(", "chunk", ")", "bytes_written", "+=", "len", "(", "chunk", ")", "if", "progress_callback", ":", "progress_callback", "(", "bytes_written", ",", "bytes_total", ")", "return", "download_filename" ]
Download the export archive. .. warning:: If you pass this function an open file-like object as the ``path`` parameter, the function will not close that file for you. If a ``path`` parameter is a directory, this function will use the Export name to determine the name of the file (returned). If the calculated download file path already exists, this function will raise a DownloadError. You can also specify the filename as a string. This will be passed to the built-in :func:`open` and we will read the content into the file. Instead, if you want to manage the file object yourself, you need to provide either a :class:`io.BytesIO` object or a file opened with the `'b'` flag. See the two examples below for more details. :param path: Either a string with the path to the location to save the response content, or a file-like object expecting bytes. :param function progress_callback: An optional callback function which receives upload progress notifications. The function should take two arguments: the number of bytes recieved, and the total number of bytes to recieve. :param int chunk_size: Chunk size in bytes for streaming large downloads and progress reporting. 1MB by default :returns The name of the automatic filename that would be used. :rtype: str
[ "Download", "the", "export", "archive", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/exports.py#L273-L351
koordinates/python-client
koordinates/exceptions.py
ServerError.from_requests_error
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)
python
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)
[ "def", "from_requests_error", "(", "cls", ",", "err", ")", ":", "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", ")" ]
Raises a subclass of ServerError based on the HTTP response code.
[ "Raises", "a", "subclass", "of", "ServerError", "based", "on", "the", "HTTP", "response", "code", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/exceptions.py#L28-L37
koordinates/python-client
koordinates/tokens.py
console_create
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(description="Command line tool to create a Koordinates API Token.") parser.add_argument('site', help="Domain (eg. labs.koordinates.com) for the Koordinates site.", metavar='SITE') parser.add_argument('email', help="User account email address", metavar='EMAIL') parser.add_argument('name', help="Description for the key", metavar='NAME') parser.add_argument('--scopes', help="Scopes for the new API token", nargs='+', metavar="SCOPE") parser.add_argument('--referrers', help="Restrict the request referrers for the token. You can use * as a wildcard, eg. *.example.com", nargs='+', metavar='HOST') parser.add_argument('--expires', help="Expiry time in ISO 8601 (YYYY-MM-DD) format", metavar="DATE") args = parser.parse_args() # check we have a valid-ish looking domain name if not re.match(r'(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}$)', args.site): parser.error("'%s' doesn't look like a valid domain name." % args.site) # check we have a valid-ish looking email address if not re.match(r'[^@]+@[^@]+\.[^@]+$', args.email): parser.error("'%s' doesn't look like a valid email address." % args.email) password = getpass.getpass('Account password for %s: ' % args.email) if not password: parser.error("Empty password.") expires_at = make_date(args.expires) print("\nNew API Token Parameters:") print(" Koordinates Site: %s" % args.site) print(" User email address: %s" % args.email) print(" Name: %s" % args.name) print(" Scopes: %s" % ' '.join(args.scopes or ['(default)'])) print(" Referrer restrictions: %s" % ' '.join(args.referrers or ['(none)'])) print(" Expires: %s" % (expires_at or '(never)')) if input("Continue? [Yn] ").lower() == 'n': sys.exit(1) token = Token(name=args.name) if args.scopes: token.scopes = args.scopes if args.referrers: token.referrers = args.referrers if expires_at: token.expires_at = expires_at print("\nRequesting token...") # need a dummy token here for initialisation client = Client(host=args.site, token='-dummy-') try: token = client.tokens.create(token, args.email, password) except requests.HTTPError as e: print("%s: %s" % (e, e.response.text)) # Helpful tips for specific errors if e.response.status_code == 401: print(" => Check your email address, password, and site domain carefully.") sys.exit(1) print("Token created successfully.\n Key: %s\n Scopes: %s" % (token.key, token.scope))
python
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(description="Command line tool to create a Koordinates API Token.") parser.add_argument('site', help="Domain (eg. labs.koordinates.com) for the Koordinates site.", metavar='SITE') parser.add_argument('email', help="User account email address", metavar='EMAIL') parser.add_argument('name', help="Description for the key", metavar='NAME') parser.add_argument('--scopes', help="Scopes for the new API token", nargs='+', metavar="SCOPE") parser.add_argument('--referrers', help="Restrict the request referrers for the token. You can use * as a wildcard, eg. *.example.com", nargs='+', metavar='HOST') parser.add_argument('--expires', help="Expiry time in ISO 8601 (YYYY-MM-DD) format", metavar="DATE") args = parser.parse_args() # check we have a valid-ish looking domain name if not re.match(r'(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}$)', args.site): parser.error("'%s' doesn't look like a valid domain name." % args.site) # check we have a valid-ish looking email address if not re.match(r'[^@]+@[^@]+\.[^@]+$', args.email): parser.error("'%s' doesn't look like a valid email address." % args.email) password = getpass.getpass('Account password for %s: ' % args.email) if not password: parser.error("Empty password.") expires_at = make_date(args.expires) print("\nNew API Token Parameters:") print(" Koordinates Site: %s" % args.site) print(" User email address: %s" % args.email) print(" Name: %s" % args.name) print(" Scopes: %s" % ' '.join(args.scopes or ['(default)'])) print(" Referrer restrictions: %s" % ' '.join(args.referrers or ['(none)'])) print(" Expires: %s" % (expires_at or '(never)')) if input("Continue? [Yn] ").lower() == 'n': sys.exit(1) token = Token(name=args.name) if args.scopes: token.scopes = args.scopes if args.referrers: token.referrers = args.referrers if expires_at: token.expires_at = expires_at print("\nRequesting token...") # need a dummy token here for initialisation client = Client(host=args.site, token='-dummy-') try: token = client.tokens.create(token, args.email, password) except requests.HTTPError as e: print("%s: %s" % (e, e.response.text)) # Helpful tips for specific errors if e.response.status_code == 401: print(" => Check your email address, password, and site domain carefully.") sys.exit(1) print("Token created successfully.\n Key: %s\n Scopes: %s" % (token.key, token.scope))
[ "def", "console_create", "(", ")", ":", "import", "argparse", "import", "getpass", "import", "re", "import", "sys", "import", "requests", "from", "six", ".", "moves", "import", "input", "from", "koordinates", ".", "client", "import", "Client", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Command line tool to create a Koordinates API Token.\"", ")", "parser", ".", "add_argument", "(", "'site'", ",", "help", "=", "\"Domain (eg. labs.koordinates.com) for the Koordinates site.\"", ",", "metavar", "=", "'SITE'", ")", "parser", ".", "add_argument", "(", "'email'", ",", "help", "=", "\"User account email address\"", ",", "metavar", "=", "'EMAIL'", ")", "parser", ".", "add_argument", "(", "'name'", ",", "help", "=", "\"Description for the key\"", ",", "metavar", "=", "'NAME'", ")", "parser", ".", "add_argument", "(", "'--scopes'", ",", "help", "=", "\"Scopes for the new API token\"", ",", "nargs", "=", "'+'", ",", "metavar", "=", "\"SCOPE\"", ")", "parser", ".", "add_argument", "(", "'--referrers'", ",", "help", "=", "\"Restrict the request referrers for the token. You can use * as a wildcard, eg. *.example.com\"", ",", "nargs", "=", "'+'", ",", "metavar", "=", "'HOST'", ")", "parser", ".", "add_argument", "(", "'--expires'", ",", "help", "=", "\"Expiry time in ISO 8601 (YYYY-MM-DD) format\"", ",", "metavar", "=", "\"DATE\"", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "# check we have a valid-ish looking domain name", "if", "not", "re", ".", "match", "(", "r'(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\\.)+[a-zA-Z]{2,63}$)'", ",", "args", ".", "site", ")", ":", "parser", ".", "error", "(", "\"'%s' doesn't look like a valid domain name.\"", "%", "args", ".", "site", ")", "# check we have a valid-ish looking email address", "if", "not", "re", ".", "match", "(", "r'[^@]+@[^@]+\\.[^@]+$'", ",", "args", ".", "email", ")", ":", "parser", ".", "error", "(", "\"'%s' doesn't look like a valid email address.\"", "%", "args", ".", "email", ")", "password", "=", "getpass", ".", "getpass", "(", "'Account password for %s: '", "%", "args", ".", "email", ")", "if", "not", "password", ":", "parser", ".", "error", "(", "\"Empty password.\"", ")", "expires_at", "=", "make_date", "(", "args", ".", "expires", ")", "print", "(", "\"\\nNew API Token Parameters:\"", ")", "print", "(", "\" Koordinates Site: %s\"", "%", "args", ".", "site", ")", "print", "(", "\" User email address: %s\"", "%", "args", ".", "email", ")", "print", "(", "\" Name: %s\"", "%", "args", ".", "name", ")", "print", "(", "\" Scopes: %s\"", "%", "' '", ".", "join", "(", "args", ".", "scopes", "or", "[", "'(default)'", "]", ")", ")", "print", "(", "\" Referrer restrictions: %s\"", "%", "' '", ".", "join", "(", "args", ".", "referrers", "or", "[", "'(none)'", "]", ")", ")", "print", "(", "\" Expires: %s\"", "%", "(", "expires_at", "or", "'(never)'", ")", ")", "if", "input", "(", "\"Continue? [Yn] \"", ")", ".", "lower", "(", ")", "==", "'n'", ":", "sys", ".", "exit", "(", "1", ")", "token", "=", "Token", "(", "name", "=", "args", ".", "name", ")", "if", "args", ".", "scopes", ":", "token", ".", "scopes", "=", "args", ".", "scopes", "if", "args", ".", "referrers", ":", "token", ".", "referrers", "=", "args", ".", "referrers", "if", "expires_at", ":", "token", ".", "expires_at", "=", "expires_at", "print", "(", "\"\\nRequesting token...\"", ")", "# need a dummy token here for initialisation", "client", "=", "Client", "(", "host", "=", "args", ".", "site", ",", "token", "=", "'-dummy-'", ")", "try", ":", "token", "=", "client", ".", "tokens", ".", "create", "(", "token", ",", "args", ".", "email", ",", "password", ")", "except", "requests", ".", "HTTPError", "as", "e", ":", "print", "(", "\"%s: %s\"", "%", "(", "e", ",", "e", ".", "response", ".", "text", ")", ")", "# Helpful tips for specific errors", "if", "e", ".", "response", ".", "status_code", "==", "401", ":", "print", "(", "\" => Check your email address, password, and site domain carefully.\"", ")", "sys", ".", "exit", "(", "1", ")", "print", "(", "\"Token created successfully.\\n Key: %s\\n Scopes: %s\"", "%", "(", "token", ".", "key", ",", "token", ".", "scope", ")", ")" ]
Command line tool (``koordinates-create-token``) used to create an API token.
[ "Command", "line", "tool", "(", "koordinates", "-", "create", "-", "token", ")", "used", "to", "create", "an", "API", "token", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/tokens.py#L96-L163
koordinates/python-client
koordinates/tokens.py
TokenManager.delete
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()
python
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()
[ "def", "delete", "(", "self", ",", "id", ")", ":", "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", "(", ")" ]
Delete a token
[ "Delete", "a", "token" ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/tokens.py#L33-L38
koordinates/python-client
koordinates/tokens.py
TokenManager.create
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.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.scope if getattr(token, 'expires_at', None): post_data['expires_at'] = token.expires_at if getattr(token, 'referrers', None): post_data['referrers'] = token.referrers r = self.client._raw_request('POST', target_url, json=post_data, headers={'Content-type': 'application/json'}) return self.create_from_result(r.json())
python
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.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.scope if getattr(token, 'expires_at', None): post_data['expires_at'] = token.expires_at if getattr(token, 'referrers', None): post_data['referrers'] = token.referrers r = self.client._raw_request('POST', target_url, json=post_data, headers={'Content-type': 'application/json'}) return self.create_from_result(r.json())
[ "def", "create", "(", "self", ",", "token", ",", "email", ",", "password", ")", ":", "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", ".", "scope", "if", "getattr", "(", "token", ",", "'expires_at'", ",", "None", ")", ":", "post_data", "[", "'expires_at'", "]", "=", "token", ".", "expires_at", "if", "getattr", "(", "token", ",", "'referrers'", ",", "None", ")", ":", "post_data", "[", "'referrers'", "]", "=", "token", ".", "referrers", "r", "=", "self", ".", "client", ".", "_raw_request", "(", "'POST'", ",", "target_url", ",", "json", "=", "post_data", ",", "headers", "=", "{", "'Content-type'", ":", "'application/json'", "}", ")", "return", "self", ".", "create_from_result", "(", "r", ".", "json", "(", ")", ")" ]
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.
[ "Create", "a", "new", "token" ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/tokens.py#L41-L64
michaelaye/pyciss
pyciss/index.py
read_cumulative_iss_index
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, "df") # replace PDS Nan values (-1e32) with real NaNs df = df.replace(-1.000000e32, np.nan) return df.replace(-999.0, np.nan)
python
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, "df") # replace PDS Nan values (-1e32) with real NaNs df = df.replace(-1.000000e32, np.nan) return df.replace(-999.0, np.nan)
[ "def", "read_cumulative_iss_index", "(", ")", ":", "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", ",", "\"df\"", ")", "# replace PDS Nan values (-1e32) with real NaNs", "df", "=", "df", ".", "replace", "(", "-", "1.000000e32", ",", "np", ".", "nan", ")", "return", "df", ".", "replace", "(", "-", "999.0", ",", "np", ".", "nan", ")" ]
Read in the whole cumulative index and return dataframe.
[ "Read", "in", "the", "whole", "cumulative", "index", "and", "return", "dataframe", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/index.py#L33-L45
michaelaye/pyciss
pyciss/index.py
read_ring_images_index
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() ringfilter = meta.TARGET_DESC.str.contains("ring", case=False) return meta[ringfilter]
python
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() ringfilter = meta.TARGET_DESC.str.contains("ring", case=False) return meta[ringfilter]
[ "def", "read_ring_images_index", "(", ")", ":", "meta", "=", "read_cumulative_iss_index", "(", ")", "ringfilter", "=", "meta", ".", "TARGET_DESC", ".", "str", ".", "contains", "(", "\"ring\"", ",", "case", "=", "False", ")", "return", "meta", "[", "ringfilter", "]" ]
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
[ "Filter", "cumulative", "index", "for", "ring", "images", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/index.py#L62-L74
michaelaye/pyciss
pyciss/index.py
filter_for_ringspan
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
python
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
[ "def", "filter_for_ringspan", "(", "clearnacs", ",", "spanlimit", ")", ":", "delta", "=", "clearnacs", ".", "MAXIMUM_RING_RADIUS", "-", "clearnacs", ".", "MINIMUM_RING_RADIUS", "f", "=", "delta", "<", "spanlimit", "ringspan", "=", "clearnacs", "[", "f", "]", ".", "copy", "(", ")", "return", "ringspan" ]
filter for covered ringspan, giver in km.
[ "filter", "for", "covered", "ringspan", "giver", "in", "km", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/index.py#L95-L100
koordinates/python-client
koordinates/publishing.py
PublishManager.create
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())
python
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())
[ "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", "(", ")", ")" ]
Creates a new publish group.
[ "Creates", "a", "new", "publish", "group", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/publishing.py#L29-L35
koordinates/python-client
koordinates/publishing.py
Publish.cancel
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)
python
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)
[ "def", "cancel", "(", "self", ")", ":", "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", ")" ]
Cancel a pending publish task
[ "Cancel", "a", "pending", "publish", "task" ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/publishing.py#L56-L60
koordinates/python-client
koordinates/publishing.py
Publish.get_items
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())) else: raise NotImplementedError("No support for %s" % url) return results
python
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())) else: raise NotImplementedError("No support for %s" % url) return results
[ "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", ".", "append", "(", "self", ".", "_client", ".", "get_manager", "(", "Layer", ")", ".", "create_from_result", "(", "r", ".", "json", "(", ")", ")", ")", "else", ":", "raise", "NotImplementedError", "(", "\"No support for %s\"", "%", "url", ")", "return", "results" ]
Return the item models associated with this Publish group.
[ "Return", "the", "item", "models", "associated", "with", "this", "Publish", "group", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/publishing.py#L62-L76
koordinates/python-client
koordinates/publishing.py
Publish.add_layer_item
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)
python
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)
[ "def", "add_layer_item", "(", "self", ",", "layer", ")", ":", "if", "not", "layer", ".", "is_draft_version", ":", "raise", "ValueError", "(", "\"Layer isn't a draft version\"", ")", "self", ".", "items", ".", "append", "(", "layer", ".", "latest_version", ")" ]
Adds a Layer to the publish group.
[ "Adds", "a", "Layer", "to", "the", "publish", "group", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/publishing.py#L78-L85
koordinates/python-client
koordinates/publishing.py
Publish.add_table_item
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)
python
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)
[ "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", ")" ]
Adds a Table to the publish group.
[ "Adds", "a", "Table", "to", "the", "publish", "group", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/publishing.py#L87-L94
michaelaye/pyciss
pyciss/plotting.py
add_ticks_to_x
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)
python
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)
[ "def", "add_ticks_to_x", "(", "ax", ",", "newticks", ",", "newnames", ")", ":", "ticks", "=", "list", "(", "ax", ".", "get_xticks", "(", ")", ")", "ticks", ".", "extend", "(", "newticks", ")", "ax", ".", "set_xticks", "(", "ticks", ")", "names", "=", "list", "(", "ax", ".", "get_xticklabels", "(", ")", ")", "names", ".", "extend", "(", "newnames", ")", "ax", ".", "set_xticklabels", "(", "names", ")" ]
Add new ticks to an axis. I use this for the right-hand plotting of resonance names in my plots.
[ "Add", "new", "ticks", "to", "an", "axis", "." ]
train
https://github.com/michaelaye/pyciss/blob/019256424466060babead7edab86736c881b0831/pyciss/plotting.py#L90-L101
koordinates/python-client
koordinates/sets.py
SetManager.create
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)
python
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)
[ "def", "create", "(", "self", ",", "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", ")" ]
Creates a new Set.
[ "Creates", "a", "new", "Set", "." ]
train
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/sets.py#L37-L43