text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
List all contributors visible in the git history.
<END_TASK>
<USER_TASK:>
Description:
def contributors(lancet, output):
"""
List all contributors visible in the git history.
""" |
sorting = pygit2.GIT_SORT_TIME | pygit2.GIT_SORT_REVERSE
commits = lancet.repo.walk(lancet.repo.head.target, sorting)
contributors = ((c.author.name, c.author.email) for c in commits)
contributors = OrderedDict(contributors)
template_content = content_from_path(
lancet.config.get('packaging', 'contributors_template'))
template = Template(template_content)
output.write(template.render(contributors=contributors).encode('utf-8')) |
<SYSTEM_TASK:>
Converts given text to a pydub AudioSegment using a specified speech
<END_TASK>
<USER_TASK:>
Description:
def text_to_speech(text, synthesizer, synth_args, sentence_break):
"""
Converts given text to a pydub AudioSegment using a specified speech
synthesizer. At the moment, IBM Watson's text-to-speech API is the only
available synthesizer.
:param text:
The text that will be synthesized to audio.
:param synthesizer:
The text-to-speech synthesizer to use. At the moment, 'watson' is the
only available input.
:param synth_args:
A dictionary of arguments to pass to the synthesizer. Parameters for
authorization (username/password) should be passed here.
:param sentence_break:
A string that identifies a sentence break or another logical break in
the text. Necessary for text longer than 50 words. Defaults to '. '.
""" |
if len(text.split()) < 50:
if synthesizer == 'watson':
with open('.temp.wav', 'wb') as temp:
temp.write(watson_request(text=text, synth_args=synth_args).content)
response = AudioSegment.from_wav('.temp.wav')
os.remove('.temp.wav')
return response
else:
raise ValueError('"' + synthesizer + '" synthesizer not found.')
else:
segments = []
for i, sentence in enumerate(text.split(sentence_break)):
if synthesizer == 'watson':
with open('.temp' + str(i) + '.wav', 'wb') as temp:
temp.write(watson_request(text=sentence, synth_args=synth_args).content)
segments.append(AudioSegment.from_wav('.temp' + str(i) + '.wav'))
os.remove('.temp' + str(i) + '.wav')
else:
raise ValueError('"' + synthesizer + '" synthesizer not found.')
response = segments[0]
for segment in segments[1:]:
response = response + segment
return response |
<SYSTEM_TASK:>
Makes a single request to the IBM Watson text-to-speech API.
<END_TASK>
<USER_TASK:>
Description:
def watson_request(text, synth_args):
"""
Makes a single request to the IBM Watson text-to-speech API.
:param text:
The text that will be synthesized to audio.
:param synth_args:
A dictionary of arguments to add to the request. These should include
username and password for authentication.
""" |
params = {
'text': text,
'accept': 'audio/wav'
}
if synth_args is not None:
params.update(synth_args)
if 'username' in params:
username = params.pop('username')
else:
raise Warning('The IBM Watson API requires credentials that should be passed as "username" and "password" in "synth_args"')
if 'password' in params:
password = params.pop('password')
else:
raise Warning('The IBM Watson API requires credentials that should be passed as "username" and "password" in "synth_args"')
return requests.get(watson_url, auth=(username, password), params=params) |
<SYSTEM_TASK:>
Builds a podcast RSS feed and returns an xml file.
<END_TASK>
<USER_TASK:>
Description:
def build_rss_feed(podcast):
"""
Builds a podcast RSS feed and returns an xml file.
:param podcast:
A Podcast model to build the RSS feed from.
""" |
if not os.path.exists(podcast.output_path):
os.makedirs(podcast.output_path)
rss = ET.Element('rss', attrib={'xmlns:itunes': 'http://www.itunes.com/dtds/podcast-1.0.dtd', 'version': '2.0'})
channel = ET.SubElement(rss, 'channel')
ET.SubElement(channel, 'title').text = podcast.title
ET.SubElement(channel, 'link').text = podcast.link
ET.SubElement(channel, 'copyright').text = podcast.copyright
ET.SubElement(channel, 'itunes:subtitle').text = podcast.subtitle
ET.SubElement(channel, 'itunes:author').text = podcast.author
ET.SubElement(channel, 'itunes:summary').text = podcast.description
ET.SubElement(channel, 'description').text = podcast.description
owner = ET.SubElement(channel, 'itunes:owner')
ET.SubElement(owner, 'itunes:name').text = podcast.owner_name
ET.SubElement(owner, 'itunes:email').text = podcast.owner_email
ET.SubElement(channel, 'itunes:image').text = podcast.image
for category in podcast.categories:
ET.SubElement(channel, 'itunes:category').text = category
for episode in sorted(podcast.episodes.values(), key=lambda x: x.publish_date):
if episode.published is True:
item = ET.SubElement(channel, 'item')
ET.SubElement(item, 'title').text = episode.title
ET.SubElement(item, 'author').text = episode.author
ET.SubElement(item, 'summary').text = episode.summary
ET.SubElement(item, 'enclosure', attrib={'url': podcast.link + '/' + episode.link, 'length': str(episode.length), 'type': 'audio/x-mp3'})
ET.SubElement(item, 'guid').text = podcast.link + '/' + episode.link
ET.SubElement(item, 'pubDate').text = episode.publish_date.strftime('%a, %d %b %Y %H:%M:%S UTC')
ET.SubElement(item, 'itunes:duration').text = episode.duration
tree = ET.ElementTree(rss)
with open(podcast.output_path + '/feed.xml', 'wb') as feed:
tree.write(feed) |
<SYSTEM_TASK:>
Example POST method.
<END_TASK>
<USER_TASK:>
Description:
def post(self):
"""Example POST method.
""" |
resource_data = self.request.json
record = {'id': str(len(resource_db) + 1),
'name': resource_data.get('name')}
resource_db.append(record)
return self.response_factory.ok(data=record) |
<SYSTEM_TASK:>
Return the 'pages' from the starting url
<END_TASK>
<USER_TASK:>
Description:
def get_pages(url):
"""
Return the 'pages' from the starting url
Technically, look for the 'next 50' link, yield and download it, repeat
""" |
while True:
yield url
doc = html.parse(url).find("body")
links = [a for a in doc.findall(".//a") if a.text and a.text.startswith("next ")]
if not links:
break
url = urljoin(url, links[0].get('href')) |
<SYSTEM_TASK:>
Return the articles from a page
<END_TASK>
<USER_TASK:>
Description:
def get_article_urls(url):
"""
Return the articles from a page
Technically, look for a div with class mw-search-result-heading
and get the first link from this div
""" |
doc = html.parse(url).getroot()
for div in doc.cssselect("div.mw-search-result-heading"):
href = div.cssselect("a")[0].get('href')
if ":" in href:
continue # skip Category: links
href = urljoin(url, href)
yield href |
<SYSTEM_TASK:>
Return a single article as a 'amcat-ready' dict
<END_TASK>
<USER_TASK:>
Description:
def get_article(url):
"""
Return a single article as a 'amcat-ready' dict
Uses the 'export' function of wikinews to get an xml article
""" |
a = html.parse(url).getroot()
title = a.cssselect(".firstHeading")[0].text_content()
date = a.cssselect(".published")[0].text_content()
date = datetime.datetime.strptime(date, "%A, %B %d, %Y").isoformat()
paras = a.cssselect("#mw-content-text p")
paras = paras[1:] # skip first paragraph, which contains date
text = "\n\n".join(p.text_content().strip() for p in paras)
return dict(headline=title,
date=date,
url=url,
text=text,
medium="Wikinews") |
<SYSTEM_TASK:>
Scrape wikinews articles from the given query
<END_TASK>
<USER_TASK:>
Description:
def scrape_wikinews(conn, project, articleset, query):
"""
Scrape wikinews articles from the given query
@param conn: The AmcatAPI object
@param articleset: The target articleset ID
@param category: The wikinews category name
""" |
url = "http://en.wikinews.org/w/index.php?search={}&limit=50".format(query)
logging.info(url)
for page in get_pages(url):
urls = get_article_urls(page)
arts = list(get_articles(urls))
logging.info("Adding {} articles to set {}:{}"
.format(len(arts), project, articleset))
conn.create_articles(project=project, articleset=articleset,
json_data=arts) |
<SYSTEM_TASK:>
Returns a callable that can be used to transmit a message, with a given
<END_TASK>
<USER_TASK:>
Description:
def pub(self, topic=b'', embed_topic=False):
"""
Returns a callable that can be used to transmit a message, with a given
``topic``, in a publisher-subscriber fashion. Note that the sender
function has a ``print`` like signature, with an infinite number of
arguments. Each one being a part of the complete message.
By default, no topic will be included into published messages. Being up
to developers to include the topic, at the beginning of the first part
(i.e. frame) of every published message, so that subscribers are able
to receive them. For a different behaviour, check the embed_topic
argument.
:param topic: the topic that will be published to (default=b'')
:type topic: bytes
:param embed_topic: set for the topic to be automatically sent as the
first part (i.e. frame) of every published message
(default=False)
:type embed_topic bool
:rtype: function
""" |
if not isinstance(topic, bytes):
error = 'Topic must be bytes'
log.error(error)
raise TypeError(error)
sock = self.__sock(zmq.PUB)
return self.__send_function(sock, topic, embed_topic) |
<SYSTEM_TASK:>
Returns an iterable that can be used to iterate over incoming messages,
<END_TASK>
<USER_TASK:>
Description:
def sub(self, topics=(b'',)):
"""
Returns an iterable that can be used to iterate over incoming messages,
that were published with one of the topics specified in ``topics``. Note
that the iterable returns as many parts as sent by subscribed publishers.
:param topics: a list of topics to subscribe to (default=b'')
:type topics: list of bytes
:rtype: generator
""" |
sock = self.__sock(zmq.SUB)
for topic in topics:
if not isinstance(topic, bytes):
error = 'Topics must be a list of bytes'
log.error(error)
raise TypeError(error)
sock.setsockopt(zmq.SUBSCRIBE, topic)
return self.__recv_generator(sock) |
<SYSTEM_TASK:>
Returns a callable that can be used to transmit a message in a push-pull
<END_TASK>
<USER_TASK:>
Description:
def push(self):
"""
Returns a callable that can be used to transmit a message in a push-pull
fashion. Note that the sender function has a ``print`` like signature,
with an infinite number of arguments. Each one being a part of the
complete message.
:rtype: function
""" |
sock = self.__sock(zmq.PUSH)
return self.__send_function(sock) |
<SYSTEM_TASK:>
Returns an iterable that can be used to iterate over incoming messages,
<END_TASK>
<USER_TASK:>
Description:
def pull(self):
"""
Returns an iterable that can be used to iterate over incoming messages,
that were pushed by a push socket. Note that the iterable returns as
many parts as sent by pushers.
:rtype: generator
""" |
sock = self.__sock(zmq.PULL)
return self.__recv_generator(sock) |
<SYSTEM_TASK:>
Connects to a server at the specified ip and port.
<END_TASK>
<USER_TASK:>
Description:
def connect(self, ip, port):
"""
Connects to a server at the specified ip and port.
:param ip: an IP address
:type ip: str or unicode
:param port: port number from 1024 up to 65535
:type port: int
:rtype: self
""" |
_check_valid_port_range(port)
address = (ip, port)
if address in self._addresses:
error = 'Already connected to {0} on port {1}'.format(ip, port)
log.exception(error)
raise ValueError(error)
self._addresses.append(address)
if self._is_ready:
_check_valid_num_connections(self._sock.socket_type,
len(self._addresses))
_connect_zmq_sock(self._sock, ip, port)
return self |
<SYSTEM_TASK:>
Disconnects from a server at the specified ip and port.
<END_TASK>
<USER_TASK:>
Description:
def disconnect(self, ip, port):
"""
Disconnects from a server at the specified ip and port.
:param ip: an IP address
:type ip: str or unicode
:param port: port number from 1024 up to 65535
:type port: int
:rtype: self
""" |
_check_valid_port_range(port)
address = (ip, port)
try:
self._addresses.remove(address)
except ValueError:
error = 'There was no connection to {0} on port {1}'.format(ip, port)
log.exception(error)
raise ValueError(error)
if self._is_ready:
_disconnect_zmq_sock(self._sock, ip, port)
return self |
<SYSTEM_TASK:>
Separate with predefined separator.
<END_TASK>
<USER_TASK:>
Description:
def prettify(amount, separator=','):
"""Separate with predefined separator.""" |
orig = str(amount)
new = re.sub("^(-?\d+)(\d{3})", "\g<1>{0}\g<2>".format(separator), str(amount))
if orig == new:
return new
else:
return prettify(new) |
<SYSTEM_TASK:>
Save data to json string
<END_TASK>
<USER_TASK:>
Description:
def save_json(val, pretty=False, sort=True, encoder=None):
"""
Save data to json string
:param val: Value or struct to save
:type val: None | int | float | str | list | dict
:param pretty: Format data to be readable (default: False)
otherwise going to be compact
:type pretty: bool
:param sort: Sort keys (default: True)
:type sort: bool
:param encoder: Use custom json encoder
:type encoder: T <= DateTimeEncoder
:return: The jsonified string
:rtype: str | unicode
""" |
if encoder is None:
encoder = DateTimeEncoder
if pretty:
data = json.dumps(
val,
indent=4,
separators=(',', ': '),
sort_keys=sort,
cls=encoder
)
else:
data = json.dumps(
val,
separators=(',', ':'),
sort_keys=sort,
cls=encoder
)
if not sys.version_info > (3, 0) and isinstance(data, str):
data = data.decode("utf-8")
return data |
<SYSTEM_TASK:>
Load settings dict
<END_TASK>
<USER_TASK:>
Description:
def load_settings(self, path):
"""
Load settings dict
:param path: Path to settings file
:type path: str | unicode
:return: Loaded settings
:rtype: dict
:raises IOError: If file not found or error accessing file
:raises TypeError: Settings file does not contain dict
""" |
res = self.load_file(path)
if not isinstance(res, dict):
raise TypeError("Expected settings to be dict")
return res |
<SYSTEM_TASK:>
Save settings to file
<END_TASK>
<USER_TASK:>
Description:
def save_settings(self, path, settings, readable=False):
"""
Save settings to file
:param path: File path to save
:type path: str | unicode
:param settings: Settings to save
:type settings: dict
:param readable: Format file to be human readable (default: False)
:type readable: bool
:rtype: None
:raises IOError: If empty path or error writing file
:raises TypeError: Settings is not a dict
""" |
if not isinstance(settings, dict):
raise TypeError("Expected settings to be dict")
return self.save_file(path, settings, readable) |
<SYSTEM_TASK:>
Get function name of calling method
<END_TASK>
<USER_TASK:>
Description:
def _get_function_name(self):
"""
Get function name of calling method
:return: The name of the calling function
(expected to be called in self.error/debug/..)
:rtype: str | unicode
""" |
fname = inspect.getframeinfo(inspect.stack()[2][0]).function
if fname == "<module>":
return ""
else:
return fname |
<SYSTEM_TASK:>
Write out yara signatures to a file.
<END_TASK>
<USER_TASK:>
Description:
def write_yara(self, output_file):
"""
Write out yara signatures to a file.
""" |
fout = open(output_file, 'wb')
fout.write('\n')
for iocid in self.yara_signatures:
signature = self.yara_signatures[iocid]
fout.write(signature)
fout.write('\n')
fout.close()
return True |
<SYSTEM_TASK:>
Make an arbitrary directory. This is safe to call for Python 2 users.
<END_TASK>
<USER_TASK:>
Description:
def safe_makedirs(fdir):
"""
Make an arbitrary directory. This is safe to call for Python 2 users.
:param fdir: Directory path to make.
:return:
""" |
if os.path.isdir(fdir):
pass
# print 'dir already exists: %s' % str(dir)
else:
try:
os.makedirs(fdir)
except WindowsError as e:
if 'Cannot create a file when that file already exists' in e:
log.debug('relevant dir already exists')
else:
raise WindowsError(e)
return True |
<SYSTEM_TASK:>
Serializes IOCs to a directory.
<END_TASK>
<USER_TASK:>
Description:
def write_iocs(self, directory=None, source=None):
"""
Serializes IOCs to a directory.
:param directory: Directory to write IOCs to. If not provided, the current working directory is used.
:param source: Dictionary contianing iocid -> IOC mapping. Defaults to self.iocs_10. This is not normally modifed by a user for this class.
:return:
""" |
"""
if directory is None, write the iocs to the current working directory
source: allows specifying a different dictionry of elmentTree ioc objects
"""
if not source:
source = self.iocs_10
if len(source) < 1:
log.error('no iocs available to write out')
return False
if not directory:
directory = os.getcwd()
if os.path.isfile(directory):
log.error('cannot writes iocs to a directory')
return False
source_iocs = set(source.keys())
source_iocs = source_iocs.difference(self.pruned_11_iocs)
source_iocs = source_iocs.difference(self.null_pruned_iocs)
if not source_iocs:
log.error('no iocs available to write out after removing pruned/null iocs')
return False
utils.safe_makedirs(directory)
output_dir = os.path.abspath(directory)
log.info('Writing IOCs to %s' % (str(output_dir)))
# serialize the iocs
for iocid in source_iocs:
ioc_obj = source[iocid]
ioc_obj.write_ioc_to_file(output_dir=output_dir, force=True)
return True |
<SYSTEM_TASK:>
Writes IOCs to a directory that have been pruned of some or all IOCs.
<END_TASK>
<USER_TASK:>
Description:
def write_pruned_iocs(self, directory=None, pruned_source=None):
"""
Writes IOCs to a directory that have been pruned of some or all IOCs.
:param directory: Directory to write IOCs to. If not provided, the current working directory is used.
:param pruned_source: Iterable containing a set of iocids. Defaults to self.iocs_10.
:return:
""" |
"""
write_pruned_iocs to a directory
if directory is None, write the iocs to the current working directory
"""
if pruned_source is None:
pruned_source = self.pruned_11_iocs
if len(pruned_source) < 1:
log.error('no iocs available to write out')
return False
if not directory:
directory = os.getcwd()
if os.path.isfile(directory):
log.error('cannot writes iocs to a directory')
return False
utils.safe_makedirs(directory)
output_dir = os.path.abspath(directory)
# serialize the iocs
for iocid in pruned_source:
ioc_obj = self.iocs_10[iocid]
ioc_obj.write_ioc_to_file(output_dir=output_dir, force=True)
return True |
<SYSTEM_TASK:>
This makes a Indicator node element. These allow the construction of a logic tree within the IOC.
<END_TASK>
<USER_TASK:>
Description:
def make_indicator_node(operator, nid=None):
"""
This makes a Indicator node element. These allow the construction of a logic tree within the IOC.
:param operator: String 'AND' or 'OR'. The constants ioc_api.OR and ioc_api.AND may be used as well.
:param nid: This is used to provide a GUID for the Indicator. The ID should NOT be specified under normal circumstances.
:return: elementTree element
""" |
if operator.upper() not in VALID_INDICATOR_OPERATORS:
raise ValueError('Indicator operator must be in [{}].'.format(VALID_INDICATOR_OPERATORS))
i_node = et.Element('Indicator')
if nid:
i_node.attrib['id'] = nid
else:
i_node.attrib['id'] = ioc_et.get_guid()
i_node.attrib['operator'] = operator.upper()
return i_node |
<SYSTEM_TASK:>
This makes a IndicatorItem element. This contains the actual threat intelligence in the IOC.
<END_TASK>
<USER_TASK:>
Description:
def make_indicatoritem_node(condition,
document,
search,
content_type,
content,
preserve_case=False,
negate=False,
context_type='mir',
nid=None):
"""
This makes a IndicatorItem element. This contains the actual threat intelligence in the IOC.
:param condition: This is the condition of the item ('is', 'contains', 'matches', etc). The following contants in ioc_api may be used:
==================== =====================================================
Constant Meaning
==================== =====================================================
ioc_api.IS Exact String match.
ioc_api.CONTAINS Substring match.
ioc_api.MATCHES Regex match.
ioc_api.STARTS_WITH String match at the beginning of a string.
ioc_api.ENDS_WITH String match at the end of a string.
ioc_api.GREATER_THAN Integer match indicating a greater than (>) operation.
ioc_api.LESS_THAN Integer match indicator a less than (<) operation.
==================== =====================================================
:param document: Denotes the type of document to look for the encoded artifact in.
:param search: Specifies what attribute of the document type the encoded value is.
:param content_type: This is the display type of the item. This is normally derived from the iocterm for the search value.
:param content: The threat intelligence that is being encoded.
:param preserve_case: Specifiy that the content should be treated in a case sensitive manner.
:param negate: Specifify that the condition is negated. An example of this is:
@condition = 'is' & @negate = 'true' would be equal to the
@condition = 'isnot' in OpenIOC 1.0.
:param context_type: Gives context to the document/search information.
:param nid: This is used to provide a GUID for the IndicatorItem. The ID should NOT be specified under normal
circumstances.
:return: an elementTree Element item
""" |
# validate condition
if condition not in VALID_INDICATORITEM_CONDITIONS:
raise ValueError('Invalid IndicatorItem condition [{}]'.format(condition))
ii_node = et.Element('IndicatorItem')
if nid:
ii_node.attrib['id'] = nid
else:
ii_node.attrib['id'] = ioc_et.get_guid()
ii_node.attrib['condition'] = condition
if preserve_case:
ii_node.attrib['preserve-case'] = 'true'
else:
ii_node.attrib['preserve-case'] = 'false'
if negate:
ii_node.attrib['negate'] = 'true'
else:
ii_node.attrib['negate'] = 'false'
context_node = ioc_et.make_context_node(document, search, context_type)
content_node = ioc_et.make_content_node(content_type, content)
ii_node.append(context_node)
ii_node.append(content_node)
return ii_node |
<SYSTEM_TASK:>
This returns the first top level Indicator node under the criteria node.
<END_TASK>
<USER_TASK:>
Description:
def get_top_level_indicator_node(root_node):
"""
This returns the first top level Indicator node under the criteria node.
:param root_node: Root node of an etree.
:return: an elementTree Element item, or None if no item is found.
""" |
if root_node.tag != 'OpenIOC':
raise IOCParseError('Root tag is not "OpenIOC" [{}].'.format(root_node.tag))
elems = root_node.xpath('criteria/Indicator')
if len(elems) == 0:
log.warning('No top level Indicator node found.')
return None
elif len(elems) > 1:
log.warning('Multiple top level Indicator nodes found. This is not a valid MIR IOC.')
return None
else:
top_level_indicator_node = elems[0]
if top_level_indicator_node.get('operator').lower() != 'or':
log.warning('Top level Indicator/@operator attribute is not "OR". This is not a valid MIR IOC.')
return top_level_indicator_node |
<SYSTEM_TASK:>
Serialize an IOC, as defined by a set of etree Elements, to a .IOC file.
<END_TASK>
<USER_TASK:>
Description:
def write_ioc(root, output_dir=None, force=False):
"""
Serialize an IOC, as defined by a set of etree Elements, to a .IOC file.
:param root: etree Element to 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 |
<SYSTEM_TASK:>
Opens an IOC file, or XML string. Returns the root element, top level
<END_TASK>
<USER_TASK:>
Description:
def open_ioc(fn):
"""
Opens an IOC file, or XML string. Returns the root element, top level
indicator element, and parameters element. If the IOC or string fails
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 |
<SYSTEM_TASK:>
This generates all parts of an IOC, but without any definition.
<END_TASK>
<USER_TASK:>
Description:
def make_ioc(name=None,
description='Automatically generated IOC',
author='IOC_api',
links=None,
keywords=None,
iocid=None):
"""
This generates all parts of an 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 |
<SYSTEM_TASK:>
Set the last modified date of a IOC to the current date.
<END_TASK>
<USER_TASK:>
Description:
def set_lastmodified_date(self, date=None):
"""
Set the last modified date of a IOC to the current date.
User may specify the date they want to set as well.
: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 |
<SYSTEM_TASK:>
Set the published date of a IOC to the current date.
<END_TASK>
<USER_TASK:>
Description:
def set_published_date(self, date=None):
"""
Set the published date of a IOC to the current date.
User may specify the date they want to set as well.
:param date: 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 |
<SYSTEM_TASK:>
Set the created date of a IOC to the current date.
<END_TASK>
<USER_TASK:>
Description:
def set_created_date(self, date=None):
"""
Set the created date of a IOC to the current date.
User may specify the date they want to set as well.
:param date: 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 |
<SYSTEM_TASK:>
Add a a parameter to the IOC.
<END_TASK>
<USER_TASK:>
Description:
def add_parameter(self, indicator_id, content, name='comment', ptype='string'):
"""
Add a a parameter to the IOC.
:param indicator_id: The unique Indicator/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 |
<SYSTEM_TASK:>
Add a Link metadata element to the IOC.
<END_TASK>
<USER_TASK:>
Description:
def add_link(self, rel, value, href=None):
"""
Add a Link metadata element to the IOC.
:param rel: Type of the link.
:param value: Value of the link text.
:param 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 |
<SYSTEM_TASK:>
Update the description) of an IOC
<END_TASK>
<USER_TASK:>
Description:
def update_description(self, description):
"""
Update the description) of an IOC
This creates the description node if it is not present.
:param description: 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 |
<SYSTEM_TASK:>
Updates the parameter attached to an Indicator or IndicatorItem node.
<END_TASK>
<USER_TASK:>
Description:
def update_parameter(self, parameter_id, content=None, name=None, param_type=None):
"""
Updates the parameter attached to an Indicator or IndicatorItem node.
All 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 |
<SYSTEM_TASK:>
Removes link nodes based on the function arguments.
<END_TASK>
<USER_TASK:>
Description:
def remove_link(self, rel, value=None, href=None):
"""
Removes link nodes based on the function arguments.
This can remove link nodes based on the following 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 |
<SYSTEM_TASK:>
Removes a Indicator or IndicatorItem node from the IOC. By default,
<END_TASK>
<USER_TASK:>
Description:
def remove_indicator(self, nid, prune=False):
"""
Removes a Indicator or IndicatorItem node from the IOC. By default,
if nodes are removed, any children nodes 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)) |
<SYSTEM_TASK:>
Removes parameters based on function arguments.
<END_TASK>
<USER_TASK:>
Description:
def remove_parameter(self, param_id=None, name=None, ref_id=None, ):
"""
Removes parameters based on function arguments.
This can remove parameters based on the 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 |
<SYSTEM_TASK:>
Removes the description node from the metadata node, if present.
<END_TASK>
<USER_TASK:>
Description:
def remove_description(self):
"""
Removes the description node from the metadata node, if present.
:return: Returns True if the description node is removed. 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 |
<SYSTEM_TASK:>
Serialize the IOC to a .ioc file.
<END_TASK>
<USER_TASK:>
Description:
def write_ioc_to_file(self, output_dir=None, force=False):
"""
Serialize the IOC to a .ioc file.
:param output_dir: Directory to write the ioc out to. default is 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) |
<SYSTEM_TASK:>
Get a string representation of an IOC.
<END_TASK>
<USER_TASK:>
Description:
def display_ioc(self, width=120, sep=' ', params=False):
"""
Get a string representation of an IOC.
:param width: Width to print the description too.
:param sep: 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 |
<SYSTEM_TASK:>
Get a text represention of the links node.
<END_TASK>
<USER_TASK:>
Description:
def link_text(self):
"""
Get a text represention of the links node.
:return:
""" |
s = ''
links_node = self.metadata.find('links')
if links_node is None:
return s
links = links_node.getchildren()
if links is None:
return s
s += 'IOC Links\n'
for link in links:
rel = link.attrib.get('rel', 'No Rel')
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 |
<SYSTEM_TASK:>
Get a text representation of the criteria node.
<END_TASK>
<USER_TASK:>
Description:
def criteria_text(self, sep=' ', params=False):
"""
Get a text representation of the criteria node.
:param sep: Separator used to indent the contents of the node.
: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 |
<SYSTEM_TASK:>
Get the text for a given Indicator or IndicatorItem node.
<END_TASK>
<USER_TASK:>
Description:
def get_node_text(self, node, depth, sep, params=False,):
"""
Get the text for a given Indicator or IndicatorItem node.
This does walk an IndicatorItem node to 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 |
<SYSTEM_TASK:>
Get the text for an Indicator node.
<END_TASK>
<USER_TASK:>
Description:
def get_i_text(node):
"""
Get the text for an Indicator node.
:param node: Indicator node.
:return:
""" |
if node.tag != 'Indicator':
raise IOCParseError('Invalid tag: {}'.format(node.tag))
s = node.get('operator').upper()
return s |
<SYSTEM_TASK:>
Get a list of parameters as text values for a given node id.
<END_TASK>
<USER_TASK:>
Description:
def get_param_text(self, nid):
"""
Get a list of parameters as text values for a given node id.
:param nid: id to look for.
:return:
""" |
r = []
params = self.parameters.xpath('.//param[@ref-id="{}"]'.format(nid))
if not params:
return r
for param in params:
vnode = param.find('value')
s = 'Parameter: {}, type:{}, value: {}'.format(param.attrib.get('name'),
vnode.attrib.get('type'),
param.findtext('value', default='No Value'))
r.append(s)
return r |
<SYSTEM_TASK:>
Use et to read in a xml file, or string, into a Element object.
<END_TASK>
<USER_TASK:>
Description:
def read_xml(filename):
"""
Use et to read in a xml file, or string, into a Element object.
:param filename: File to parse.
:return: lxml._elementTree object or 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 |
<SYSTEM_TASK:>
Takes in a ElementTree object and namespace value. The length of that
<END_TASK>
<USER_TASK:>
Description:
def remove_namespace(doc, namespace):
"""
Takes in a ElementTree object and namespace value. The length of that
namespace value is removed from all Element nodes 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 |
<SYSTEM_TASK:>
Identifies the namespace associated with the root node of a XML document
<END_TASK>
<USER_TASK:>
Description:
def delete_namespace(parsed_xml):
"""
Identifies the namespace associated with the root node of a XML document
and removes that names from the document.
:param 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 |
<SYSTEM_TASK:>
Parses a file into a lxml.etree structure with namespaces remove. This tree is added to self.iocs.
<END_TASK>
<USER_TASK:>
Description:
def parse(self, fn):
"""
Parses a file into a lxml.etree structure with namespaces remove. This tree is added to self.iocs.
:param fn: File to parse.
:return:
""" |
ioc_xml = xmlutils.read_xml_no_ns(fn)
if not ioc_xml:
return False
root = ioc_xml.getroot()
iocid = root.get('id', None)
if not iocid:
return False
self.iocs[iocid] = ioc_xml
return True |
<SYSTEM_TASK:>
converts the iocs in self.iocs from openioc 1.0 to openioc 1.1 format.
<END_TASK>
<USER_TASK:>
Description:
def convert_to_11(self):
"""
converts the iocs in self.iocs from openioc 1.0 to openioc 1.1 format.
the converted iocs are stored in the dictionary self.iocs_11
""" |
if len(self) < 1:
log.error('No iocs available to modify.')
return False
log.info('Converting IOCs from 1.0 to 1.1')
errors = []
for iocid in self.iocs:
ioc_xml = self.iocs[iocid]
root = ioc_xml.getroot()
if root.tag != 'ioc':
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 |
<SYSTEM_TASK:>
parses an ioc to populate self.iocs and self.ioc_name
<END_TASK>
<USER_TASK:>
Description:
def parse(self, ioc_obj):
"""
parses an ioc to populate self.iocs and self.ioc_name
:param ioc_obj:
:return:
""" |
if ioc_obj is None:
return
iocid = ioc_obj.iocid
try:
sd = ioc_obj.metadata.xpath('.//short_description/text()')[0]
except IndexError:
sd = 'NoName'
if iocid in self.iocs:
msg = 'duplicate IOC UUID [{}] [orig_shortName: {}][new_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 |
<SYSTEM_TASK:>
Register a callback function that is called after self.iocs and self.ioc_name is populated.
<END_TASK>
<USER_TASK:>
Description:
def register_parser_callback(self, func):
"""
Register a callback function that is called after self.iocs and self.ioc_name is populated.
This is intended for 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)) |
<SYSTEM_TASK:>
Create single permission for the given object.
<END_TASK>
<USER_TASK:>
Description:
def create(self, permission):
"""
Create single permission for the given object.
:param Permission permission: A single Permission object to be set.
""" |
parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', 'single', {'id': self.parent_object.id})
target_url = parent_url + self.client.get_url_path(self._URL_KEY, 'POST', 'single')
r = self.client.request('POST', target_url, json=permission._serialize())
return permission._deserialize(r.json(), self) |
<SYSTEM_TASK:>
Set the object permissions. If the parent object already has permissions, they will be overwritten.
<END_TASK>
<USER_TASK:>
Description:
def set(self, permissions):
"""
Set the object permissions. If the parent object already has permissions, they will be overwritten.
:param [] permissions: A 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() |
<SYSTEM_TASK:>
List permissions for the given object.
<END_TASK>
<USER_TASK:>
Description:
def list(self):
"""
List permissions for the given object.
""" |
parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', 'single', {'id': self.parent_object.id})
target_url = parent_url + self.client.get_url_path(self._URL_KEY, 'GET', 'multi')
return base.Query(self, target_url) |
<SYSTEM_TASK:>
List a specific permisison for the given object.
<END_TASK>
<USER_TASK:>
Description:
def get(self, permission_id, expand=[]):
"""
List a specific permisison for the given object.
:param str permission_id: the id of the Permission to be listed.
""" |
parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', 'single', {'id': self.parent_object.id})
target_url = parent_url + self.client.get_url_path(
self._URL_KEY, 'GET', 'single', {'permission_id': permission_id})
return self._get(target_url, expand=expand) |
<SYSTEM_TASK:>
Read the configfile and return config dict.
<END_TASK>
<USER_TASK:>
Description:
def get_config():
"""Read the configfile and return config dict.
Returns
-------
dict
Dictionary with the content of the configpath file.
""" |
configpath = get_configpath()
if not configpath.exists():
raise IOError("Config file {} not found.".format(str(configpath)))
else:
config = configparser.ConfigParser()
config.read(str(configpath))
return config |
<SYSTEM_TASK:>
Use to write the database path into the config.
<END_TASK>
<USER_TASK:>
Description:
def set_database_path(dbfolder):
"""Use to write the database path into the config.
Parameters
----------
dbfolder : str or pathlib.Path
Path to where pyciss will store the 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)) |
<SYSTEM_TASK:>
Check Label file for the compression type.
<END_TASK>
<USER_TASK:>
Description:
def is_lossy(label):
"""Check Label file for the compression type. """ |
val = getkey(from_=label, keyword='INST_CMPRS_TYPE').decode().strip()
if val == 'LOSSY':
return True
else:
return False |
<SYSTEM_TASK:>
Download and calibrate in parallel.
<END_TASK>
<USER_TASK:>
Description:
def download_and_calibrate_parallel(list_of_ids, n=None):
"""Download and calibrate in parallel.
Parameters
----------
list_of_ids : list, optional
container with img_ids 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"]) |
<SYSTEM_TASK:>
Download and calibrate one or more image ids, in parallel.
<END_TASK>
<USER_TASK:>
Description:
def download_and_calibrate(img_id=None, overwrite=False, recalibrate=False, **kwargs):
"""Download and calibrate one or more image ids, in parallel.
Parameters
----------
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.") |
<SYSTEM_TASK:>
Perform either normal spiceinit or one for ringdata.
<END_TASK>
<USER_TASK:>
Description:
def spiceinit(self):
"""Perform either normal spiceinit or one for ringdata.
Note how Python name-spacing can distinguish between the method
and the function 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.") |
<SYSTEM_TASK:>
Check label for target and fix if necessary.
<END_TASK>
<USER_TASK:>
Description:
def check_label(self):
""" Check label for target and fix if necessary.
Forcing the target name to Saturn here, because some observations of
the rings have moons 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",
) |
<SYSTEM_TASK:>
Checks and sets the supported content types configuration value.
<END_TASK>
<USER_TASK:>
Description:
def _set_supported_content_type(self, content_types_supported):
""" Checks and sets the supported content types configuration value.
""" |
if not isinstance(content_types_supported, list):
raise TypeError(("Settings 'READTIME_CONTENT_SUPPORT' must be"
"a list of content types."))
self.content_type_supported = content_types_supported |
<SYSTEM_TASK:>
Checks and sets the per language WPM, singular and plural values.
<END_TASK>
<USER_TASK:>
Description:
def _set_lang_settings(self, lang_settings):
""" Checks and sets the per language WPM, singular and plural values.
""" |
is_int = isinstance(lang_settings, int)
is_dict = isinstance(lang_settings, dict)
if not is_int and not is_dict:
raise TypeError(("Settings 'READTIME_WPM' must be either an int,"
"or a dict with settings per language."))
# For backwards 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 |
<SYSTEM_TASK:>
Initializes ReadTimeParser with configuration values set by the
<END_TASK>
<USER_TASK:>
Description:
def initialize_settings(self, sender):
""" Initializes ReadTimeParser with configuration values set by the
site author.
""" |
try:
self.initialized = True
settings_content_types = sender.settings.get(
'READTIME_CONTENT_SUPPORT', self.content_type_supported)
self._set_supported_content_type(settings_content_types)
lang_settings = sender.settings.get(
'READTIME_WPM', self.lang_settings)
self._set_lang_settings(lang_settings)
except Exception as e:
raise Exception("ReadTime Plugin: %s" % str(e)) |
<SYSTEM_TASK:>
Core function used to generate the read_time for content.
<END_TASK>
<USER_TASK:>
Description:
def read_time(self, content):
""" Core function used to generate the read_time for content.
Parameters:
:param content: Instance of pelican.content.Content
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) |
<SYSTEM_TASK:>
Filterable list of Scans for a Source.
<END_TASK>
<USER_TASK:>
Description:
def list_scans(self, source_id=None):
"""
Filterable list of Scans for a Source.
Ordered newest to oldest by default
""" |
if source_id:
target_url = self.client.get_url('SCAN', 'GET', 'multi', {'source_id': source_id})
else:
target_url = self.client.get_ulr('SCAN', 'GET', 'all')
return base.Query(self.client.get_manager(Scan), target_url) |
<SYSTEM_TASK:>
Get the log text for a Scan
<END_TASK>
<USER_TASK:>
Description:
def get_scan_log_lines(self, source_id, scan_id):
"""
Get the log text for a Scan
:rtype: Iterator over log lines.
""" |
return self.client.get_manager(Scan).get_log_lines(source_id=source_id, scan_id=scan_id) |
<SYSTEM_TASK:>
Add a single file or archive to upload.
<END_TASK>
<USER_TASK:>
Description:
def add_file(self, fp, upload_path=None, content_type=None):
"""
Add a single file or archive to upload.
To add metadata records with a file, add a .xml file 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) |
<SYSTEM_TASK:>
Get the log text for a scan object
<END_TASK>
<USER_TASK:>
Description:
def get_log_lines(self):
"""
Get the log text for a scan object
:rtype: Iterator over log lines.
""" |
rel = self._client.reverse_url('SCAN', self.url)
return self._manager.get_log_lines(**rel) |
<SYSTEM_TASK:>
Returns the Creative Commons license for the given attributes.
<END_TASK>
<USER_TASK:>
Description:
def get_creative_commons(self, slug, jurisdiction=None):
"""Returns the Creative Commons license for the given attributes.
:param str slug: the type of Creative 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) |
<SYSTEM_TASK:>
Calculate an offset.
<END_TASK>
<USER_TASK:>
Description:
def calc_offset(cube):
"""Calculate an offset.
Calculate offset from the side of data so that at least 200 image pixels are in the MAD stats.
Parameters
==========
cube : pyciss.ringcube.RingCube
Cubefile with ring image
""" |
i = 0
while pd.Series(cube.img[:, i]).count() < 200:
i += 1
return max(i, 20) |
<SYSTEM_TASK:>
Powerful default display.
<END_TASK>
<USER_TASK:>
Description:
def imshow(
self,
data=None,
save=False,
ax=None,
interpolation="none",
extra_title=None,
show_resonances="some",
set_extent=True,
equalized=False,
rmin=None,
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 |
<SYSTEM_TASK:>
Update the query count property from the `X-Resource-Range` response header
<END_TASK>
<USER_TASK:>
Description:
def _update_range(self, response):
""" Update the query count property from the `X-Resource-Range` response header """ |
header_value = response.headers.get('x-resource-range', '')
m = re.match(r'\d+-\d+/(\d+)$', header_value)
if m:
self._count = int(m.group(1))
else:
self._count = None |
<SYSTEM_TASK:>
Serialises this query into a request-able URL including parameters
<END_TASK>
<USER_TASK:>
Description:
def _to_url(self):
""" Serialises this query into a request-able URL including parameters """ |
url = self._target_url
params = collections.defaultdict(list, copy.deepcopy(self._filters))
if self._order_by is not None:
params['sort'] = self._order_by
for k, vl in self._extra.items():
params[k] += vl
if params:
url += "?" + urllib.parse.urlencode(params, doseq=True)
return url |
<SYSTEM_TASK:>
Add a filter to this query.
<END_TASK>
<USER_TASK:>
Description:
def filter(self, **filters):
"""
Add a filter to this query.
Appends to any previous filters set.
:rtype: Query
""" |
q = self._clone()
for key, value in filters.items():
filter_key = re.split('__', key)
filter_attr = filter_key[0]
if filter_attr not in self._valid_filter_attrs:
raise ClientValidationError("Invalid filter attribute: %s" % key)
# we use __ as a separator in the Python library, the APIs use '.'
q._filters['.'.join(filter_key)].append(value)
return q |
<SYSTEM_TASK:>
Deserialise from JSON response data.
<END_TASK>
<USER_TASK:>
Description:
def _deserialize(self, data):
"""
Deserialise from JSON response data.
String items named ``*_at`` are turned into dates.
Filters out:
* attribute names in ``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 |
<SYSTEM_TASK:>
Serialise this instance into JSON-style request data.
<END_TASK>
<USER_TASK:>
Description:
def _serialize(self, skip_empty=True):
"""
Serialise this instance into JSON-style request data.
Filters out:
* attribute names starting with ``_``
* attribute 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 |
<SYSTEM_TASK:>
Refresh this model from the server.
<END_TASK>
<USER_TASK:>
Description:
def refresh(self):
"""
Refresh this model from the server.
Updates attributes with the server-defined values. This is useful where the Model
instance came from a 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) |
<SYSTEM_TASK:>
Gets a crop feature
<END_TASK>
<USER_TASK:>
Description:
def get_feature(self, croplayer_id, cropfeature_id):
"""
Gets a crop feature
:param int croplayer_id: ID of a cropping layer
:param int cropfeature_id: ID of a 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) |
<SYSTEM_TASK:>
Add a layer or table item to the export.
<END_TASK>
<USER_TASK:>
Description:
def add_item(self, item, **options):
"""
Add a layer or table item to the export.
:param Layer|Table item: The Layer or Table to add
:rtype: self
""" |
export_item = {
"item": item.url,
}
export_item.update(options)
self.items.append(export_item)
return self |
<SYSTEM_TASK:>
Download the export archive.
<END_TASK>
<USER_TASK:>
Description:
def download(self, path, progress_callback=None, chunk_size=1024**2):
"""
Download the export archive.
.. warning::
If you pass this function an open file-like 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 |
<SYSTEM_TASK:>
Raises a subclass of ServerError based on the HTTP response code.
<END_TASK>
<USER_TASK:>
Description:
def from_requests_error(cls, err):
"""
Raises a subclass of ServerError based on the HTTP response code.
""" |
import requests
if isinstance(err, requests.HTTPError):
status_code = err.response.status_code
return HTTP_ERRORS.get(status_code, cls)(error=err, response=err.response)
else:
return cls(error=err) |
<SYSTEM_TASK:>
Create a new token
<END_TASK>
<USER_TASK:>
Description:
def create(self, token, email, password):
"""
Create a new token
:param Token token: Token instance to create.
:param str email: Email address of the Koordinates 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()) |
<SYSTEM_TASK:>
Filter cumulative index for ring images.
<END_TASK>
<USER_TASK:>
Description:
def read_ring_images_index():
"""Filter cumulative index for ring images.
This is done by matching the column TARGET_DESC to contain the string 'ring'
Returns
-------
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] |
<SYSTEM_TASK:>
Creates a new publish group.
<END_TASK>
<USER_TASK:>
Description:
def create(self, publish):
"""
Creates a new publish group.
""" |
target_url = self.client.get_url('PUBLISH', 'POST', 'create')
r = self.client.request('POST', target_url, json=publish._serialize())
return self.create_from_result(r.json()) |
<SYSTEM_TASK:>
Cancel a pending publish task
<END_TASK>
<USER_TASK:>
Description:
def cancel(self):
""" Cancel a pending publish task """ |
target_url = self._client.get_url('PUBLISH', 'DELETE', 'single', {'id': self.id})
r = self._client.request('DELETE', target_url)
logger.info("cancel(): %s", r.status_code) |
<SYSTEM_TASK:>
Return the item models associated with this Publish group.
<END_TASK>
<USER_TASK:>
Description:
def get_items(self):
"""
Return the item models associated with this Publish group.
""" |
from .layers import Layer
# no expansion support, just URLs
results = []
for url in self.items:
if '/layers/' in url:
r = self._client.request('GET', url)
results.append(self._client.get_manager(Layer).create_from_result(r.json()))
else:
raise NotImplementedError("No support for %s" % url)
return results |
<SYSTEM_TASK:>
Adds a Layer to the publish group.
<END_TASK>
<USER_TASK:>
Description:
def add_layer_item(self, layer):
"""
Adds a Layer to the publish group.
""" |
if not layer.is_draft_version:
raise ValueError("Layer isn't a draft version")
self.items.append(layer.latest_version) |
<SYSTEM_TASK:>
Adds a Table to the publish group.
<END_TASK>
<USER_TASK:>
Description:
def add_table_item(self, table):
"""
Adds a Table to the publish group.
""" |
if not table.is_draft_version:
raise ValueError("Table isn't a draft version")
self.items.append(table.latest_version) |
<SYSTEM_TASK:>
Add new ticks to an axis.
<END_TASK>
<USER_TASK:>
Description:
def add_ticks_to_x(ax, newticks, newnames):
"""Add new ticks to an axis.
I use this for the right-hand plotting of resonance names in my plots.
""" |
ticks = list(ax.get_xticks())
ticks.extend(newticks)
ax.set_xticks(ticks)
names = list(ax.get_xticklabels())
names.extend(newnames)
ax.set_xticklabels(names) |
<SYSTEM_TASK:>
If the parent object already has XML metadata, it will be overwritten.
<END_TASK>
<USER_TASK:>
Description:
def set(self, parent_url, fp):
"""
If the parent object already has XML metadata, it will be overwritten.
Accepts XML metadata in any of the three supported formats.
The format will be detected from the XML content.
The Metadata object becomes invalid after setting
:param file fp: A reference to an open file-like object which the content will be read from.
""" |
url = parent_url + self.client.get_url_path('METADATA', 'POST', 'set', {})
r = self.client.request('POST', url, data=fp, headers={'Content-Type': 'text/xml'})
if r.status_code not in [200, 201]:
raise exceptions.ServerError("Expected success response, got %s: %s" % (r.status_code, url)) |
<SYSTEM_TASK:>
Returns the XML metadata for this source, converted to the requested format.
<END_TASK>
<USER_TASK:>
Description:
def get_xml(self, fp, format=FORMAT_NATIVE):
"""
Returns the XML metadata for this source, converted to the requested format.
Converted metadata may not contain all the same information as the native format.
:param file fp: A path, or an open file-like object which the content should be written to.
:param str format: desired format for the output. This should be one of the available
formats from :py:meth:`.get_formats`, or :py:attr:`.FORMAT_NATIVE` for the native format.
If you pass this function an open file-like object as the fp parameter, the function will
not close that file for you.
""" |
r = self._client.request('GET', getattr(self, format), stream=True)
filename = stream.stream_response_to_file(r, path=fp)
return filename |
<SYSTEM_TASK:>
Return the available format names for this metadata
<END_TASK>
<USER_TASK:>
Description:
def get_formats(self):
""" Return the available format names for this metadata """ |
formats = []
for key in (self.FORMAT_DC, self.FORMAT_FGDC, self.FORMAT_ISO):
if hasattr(self, key):
formats.append(key)
return formats |
<SYSTEM_TASK:>
Decorator that asserts the model instance is bound.
<END_TASK>
<USER_TASK:>
Description:
def is_bound(method):
"""
Decorator that asserts the model instance is bound.
Requires:
1. an ``id`` attribute
2. a ``url`` attribute
2. a manager set
""" |
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if not self._is_bound:
raise ValueError("%r must be bound to call %s()" % (self, method.__name__))
return method(self, *args, **kwargs)
return wrapper |
<SYSTEM_TASK:>
Query OPUS via the image_id.
<END_TASK>
<USER_TASK:>
Description:
def query_image_id(self, image_id):
"""Query OPUS via the image_id.
This is a query using the 'primaryfilespec' field of the OPUS database.
It returns a list of URLS into the `obsids` attribute.
This example queries for an image of Titan:
>>> opus = opusapi.OPUS()
>>> opus.query_image_id('N1695760475_1')
After this, one can call `download_results()` to retrieve the found
data into the standard locations into the database_path as defined in
`.pyciss.yaml` (the config file),
""" |
myquery = {"primaryfilespec": image_id}
self.create_files_request(myquery, fmt="json")
self.unpack_json_response()
return self.obsids |
Subsets and Splits