repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
SuperCowPowers/workbench | workbench/workers/pe_indicators.py | PEIndicators.check_section_unaligned | def check_section_unaligned(self):
''' Checking if any of the sections are unaligned '''
file_alignment = self.pefile_handle.OPTIONAL_HEADER.FileAlignment
unaligned_sections = []
for section in self.pefile_handle.sections:
if section.PointerToRawData % file_alignment:
unaligned_sections.append(section.Name)
# If we had any unaligned sections, return them
if unaligned_sections:
return {'description': 'Unaligned section, tamper indication',
'severity': 3, 'category': 'MALFORMED', 'attributes': unaligned_sections}
return None | python | def check_section_unaligned(self):
''' Checking if any of the sections are unaligned '''
file_alignment = self.pefile_handle.OPTIONAL_HEADER.FileAlignment
unaligned_sections = []
for section in self.pefile_handle.sections:
if section.PointerToRawData % file_alignment:
unaligned_sections.append(section.Name)
# If we had any unaligned sections, return them
if unaligned_sections:
return {'description': 'Unaligned section, tamper indication',
'severity': 3, 'category': 'MALFORMED', 'attributes': unaligned_sections}
return None | [
"def",
"check_section_unaligned",
"(",
"self",
")",
":",
"file_alignment",
"=",
"self",
".",
"pefile_handle",
".",
"OPTIONAL_HEADER",
".",
"FileAlignment",
"unaligned_sections",
"=",
"[",
"]",
"for",
"section",
"in",
"self",
".",
"pefile_handle",
".",
"sections",
... | Checking if any of the sections are unaligned | [
"Checking",
"if",
"any",
"of",
"the",
"sections",
"are",
"unaligned"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pe_indicators.py#L158-L170 | train | 43,300 |
SuperCowPowers/workbench | workbench/workers/pe_indicators.py | PEIndicators.check_section_oversized | def check_section_oversized(self):
''' Checking if any of the sections go past the total size of the image '''
total_image_size = self.pefile_handle.OPTIONAL_HEADER.SizeOfImage
for section in self.pefile_handle.sections:
if section.PointerToRawData + section.SizeOfRawData > total_image_size:
return {'description': 'Oversized section, storing addition data within the PE',
'severity': 3, 'category': 'MALFORMED', 'attributes': section.Name}
return None | python | def check_section_oversized(self):
''' Checking if any of the sections go past the total size of the image '''
total_image_size = self.pefile_handle.OPTIONAL_HEADER.SizeOfImage
for section in self.pefile_handle.sections:
if section.PointerToRawData + section.SizeOfRawData > total_image_size:
return {'description': 'Oversized section, storing addition data within the PE',
'severity': 3, 'category': 'MALFORMED', 'attributes': section.Name}
return None | [
"def",
"check_section_oversized",
"(",
"self",
")",
":",
"total_image_size",
"=",
"self",
".",
"pefile_handle",
".",
"OPTIONAL_HEADER",
".",
"SizeOfImage",
"for",
"section",
"in",
"self",
".",
"pefile_handle",
".",
"sections",
":",
"if",
"section",
".",
"Pointer... | Checking if any of the sections go past the total size of the image | [
"Checking",
"if",
"any",
"of",
"the",
"sections",
"go",
"past",
"the",
"total",
"size",
"of",
"the",
"image"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pe_indicators.py#L172-L181 | train | 43,301 |
yfpeng/bioc | bioc/biocxml/encoder.py | encode_location | def encode_location(location: BioCLocation):
"""Encode a single location."""
return etree.Element('location',
{'offset': str(location.offset), 'length': str(location.length)}) | python | def encode_location(location: BioCLocation):
"""Encode a single location."""
return etree.Element('location',
{'offset': str(location.offset), 'length': str(location.length)}) | [
"def",
"encode_location",
"(",
"location",
":",
"BioCLocation",
")",
":",
"return",
"etree",
".",
"Element",
"(",
"'location'",
",",
"{",
"'offset'",
":",
"str",
"(",
"location",
".",
"offset",
")",
",",
"'length'",
":",
"str",
"(",
"location",
".",
"len... | Encode a single location. | [
"Encode",
"a",
"single",
"location",
"."
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocxml/encoder.py#L39-L42 | train | 43,302 |
yfpeng/bioc | bioc/biocxml/encoder.py | encode_collection | def encode_collection(collection):
"""Encode a single collection."""
tree = etree.Element('collection')
etree.SubElement(tree, 'source').text = collection.source
etree.SubElement(tree, 'date').text = collection.date
etree.SubElement(tree, 'key').text = collection.key
encode_infons(tree, collection.infons)
for doc in collection.documents:
tree.append(encode_document(doc))
return tree | python | def encode_collection(collection):
"""Encode a single collection."""
tree = etree.Element('collection')
etree.SubElement(tree, 'source').text = collection.source
etree.SubElement(tree, 'date').text = collection.date
etree.SubElement(tree, 'key').text = collection.key
encode_infons(tree, collection.infons)
for doc in collection.documents:
tree.append(encode_document(doc))
return tree | [
"def",
"encode_collection",
"(",
"collection",
")",
":",
"tree",
"=",
"etree",
".",
"Element",
"(",
"'collection'",
")",
"etree",
".",
"SubElement",
"(",
"tree",
",",
"'source'",
")",
".",
"text",
"=",
"collection",
".",
"source",
"etree",
".",
"SubElement... | Encode a single collection. | [
"Encode",
"a",
"single",
"collection",
"."
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocxml/encoder.py#L125-L134 | train | 43,303 |
yfpeng/bioc | bioc/biocxml/encoder.py | BioCXMLEncoder.default | def default(self, obj):
"""Implement this method in a subclass such that it returns a tree for ``o``."""
if isinstance(obj, BioCDocument):
return encode_document(obj)
if isinstance(obj, BioCCollection):
return encode_collection(obj)
raise TypeError(f'Object of type {obj.__class__.__name__} is not BioC XML serializable') | python | def default(self, obj):
"""Implement this method in a subclass such that it returns a tree for ``o``."""
if isinstance(obj, BioCDocument):
return encode_document(obj)
if isinstance(obj, BioCCollection):
return encode_collection(obj)
raise TypeError(f'Object of type {obj.__class__.__name__} is not BioC XML serializable') | [
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"BioCDocument",
")",
":",
"return",
"encode_document",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"obj",
",",
"BioCCollection",
")",
":",
"return",
"encode_collection"... | Implement this method in a subclass such that it returns a tree for ``o``. | [
"Implement",
"this",
"method",
"in",
"a",
"subclass",
"such",
"that",
"it",
"returns",
"a",
"tree",
"for",
"o",
"."
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocxml/encoder.py#L146-L152 | train | 43,304 |
yfpeng/bioc | bioc/biocxml/encoder.py | BioCXMLDocumentWriter.write_document | def write_document(self, document: BioCDocument):
"""Encode and write a single document."""
tree = self.encoder.encode(document)
self.__writer.send(tree) | python | def write_document(self, document: BioCDocument):
"""Encode and write a single document."""
tree = self.encoder.encode(document)
self.__writer.send(tree) | [
"def",
"write_document",
"(",
"self",
",",
"document",
":",
"BioCDocument",
")",
":",
"tree",
"=",
"self",
".",
"encoder",
".",
"encode",
"(",
"document",
")",
"self",
".",
"__writer",
".",
"send",
"(",
"tree",
")"
] | Encode and write a single document. | [
"Encode",
"and",
"write",
"a",
"single",
"document",
"."
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocxml/encoder.py#L210-L213 | train | 43,305 |
SuperCowPowers/workbench | workbench/clients/customer_report.py | run | def run():
"""This client generates customer reports on all the samples in workbench."""
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
workbench = zerorpc.Client(timeout=300, heartbeat=60)
workbench.connect('tcp://'+args['server']+':'+args['port'])
all_set = workbench.generate_sample_set()
results = workbench.set_work_request('view_customer', all_set)
for customer in results:
print customer['customer'] | python | def run():
"""This client generates customer reports on all the samples in workbench."""
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
workbench = zerorpc.Client(timeout=300, heartbeat=60)
workbench.connect('tcp://'+args['server']+':'+args['port'])
all_set = workbench.generate_sample_set()
results = workbench.set_work_request('view_customer', all_set)
for customer in results:
print customer['customer'] | [
"def",
"run",
"(",
")",
":",
"# Grab server args",
"args",
"=",
"client_helper",
".",
"grab_server_args",
"(",
")",
"# Start up workbench connection",
"workbench",
"=",
"zerorpc",
".",
"Client",
"(",
"timeout",
"=",
"300",
",",
"heartbeat",
"=",
"60",
")",
"wo... | This client generates customer reports on all the samples in workbench. | [
"This",
"client",
"generates",
"customer",
"reports",
"on",
"all",
"the",
"samples",
"in",
"workbench",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/customer_report.py#L7-L20 | train | 43,306 |
yfpeng/bioc | bioc/validator.py | validate | def validate(collection, onerror: Callable[[str, List], None] = None):
"""Validate BioC data structure."""
BioCValidator(onerror).validate(collection) | python | def validate(collection, onerror: Callable[[str, List], None] = None):
"""Validate BioC data structure."""
BioCValidator(onerror).validate(collection) | [
"def",
"validate",
"(",
"collection",
",",
"onerror",
":",
"Callable",
"[",
"[",
"str",
",",
"List",
"]",
",",
"None",
"]",
"=",
"None",
")",
":",
"BioCValidator",
"(",
"onerror",
")",
".",
"validate",
"(",
"collection",
")"
] | Validate BioC data structure. | [
"Validate",
"BioC",
"data",
"structure",
"."
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/validator.py#L131-L133 | train | 43,307 |
yfpeng/bioc | bioc/validator.py | BioCValidator.validate_doc | def validate_doc(self, document: BioCDocument):
"""Validate a single document."""
annotations = []
annotations.extend(document.annotations)
annotations.extend(document.relations)
for passage in document.passages:
annotations.extend(passage.annotations)
annotations.extend(passage.relations)
for sentence in passage.sentences:
annotations.extend(sentence.annotations)
annotations.extend(sentence.relations)
self.current_docid = document.id
self.traceback.append(document)
text = self.__get_doc_text(document)
self.__validate_ann(document.annotations, text, 0)
self.__validate_rel(annotations, document.relations, f'document {document.id}')
for passage in document.passages:
self.traceback.append(passage)
text = self.__get_passage_text(passage)
self.__validate_ann(passage.annotations, text, passage.offset)
self.__validate_rel(annotations, passage.relations,
f'document {document.id} --> passage {passage.offset}')
for sentence in passage.sentences:
self.traceback.append(sentence)
self.__validate_ann(sentence.annotations, sentence.text, sentence.offset)
self.__validate_rel(annotations, sentence.relations,
f'document {document.id} --> sentence {sentence.offset}')
self.traceback.pop()
self.traceback.pop()
self.traceback.pop() | python | def validate_doc(self, document: BioCDocument):
"""Validate a single document."""
annotations = []
annotations.extend(document.annotations)
annotations.extend(document.relations)
for passage in document.passages:
annotations.extend(passage.annotations)
annotations.extend(passage.relations)
for sentence in passage.sentences:
annotations.extend(sentence.annotations)
annotations.extend(sentence.relations)
self.current_docid = document.id
self.traceback.append(document)
text = self.__get_doc_text(document)
self.__validate_ann(document.annotations, text, 0)
self.__validate_rel(annotations, document.relations, f'document {document.id}')
for passage in document.passages:
self.traceback.append(passage)
text = self.__get_passage_text(passage)
self.__validate_ann(passage.annotations, text, passage.offset)
self.__validate_rel(annotations, passage.relations,
f'document {document.id} --> passage {passage.offset}')
for sentence in passage.sentences:
self.traceback.append(sentence)
self.__validate_ann(sentence.annotations, sentence.text, sentence.offset)
self.__validate_rel(annotations, sentence.relations,
f'document {document.id} --> sentence {sentence.offset}')
self.traceback.pop()
self.traceback.pop()
self.traceback.pop() | [
"def",
"validate_doc",
"(",
"self",
",",
"document",
":",
"BioCDocument",
")",
":",
"annotations",
"=",
"[",
"]",
"annotations",
".",
"extend",
"(",
"document",
".",
"annotations",
")",
"annotations",
".",
"extend",
"(",
"document",
".",
"relations",
")",
... | Validate a single document. | [
"Validate",
"a",
"single",
"document",
"."
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/validator.py#L28-L62 | train | 43,308 |
yfpeng/bioc | bioc/validator.py | BioCValidator.validate | def validate(self, collection: BioCCollection):
"""Validate a single collection."""
for document in collection.documents:
self.validate_doc(document) | python | def validate(self, collection: BioCCollection):
"""Validate a single collection."""
for document in collection.documents:
self.validate_doc(document) | [
"def",
"validate",
"(",
"self",
",",
"collection",
":",
"BioCCollection",
")",
":",
"for",
"document",
"in",
"collection",
".",
"documents",
":",
"self",
".",
"validate_doc",
"(",
"document",
")"
] | Validate a single collection. | [
"Validate",
"a",
"single",
"collection",
"."
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/validator.py#L64-L67 | train | 43,309 |
SuperCowPowers/workbench | workbench/clients/pe_indexer.py | run | def run():
"""This client pushes PE Files -> ELS Indexer."""
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
workbench = zerorpc.Client(timeout=300, heartbeat=60)
workbench.connect('tcp://'+args['server']+':'+args['port'])
# Test out PEFile -> strings -> indexer -> search
data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),'../data/pe/bad')
file_list = [os.path.join(data_path, child) for child in os.listdir(data_path)][:20]
for filename in file_list:
# Skip OS generated files
if '.DS_Store' in filename:
continue
with open(filename, 'rb') as f:
base_name = os.path.basename(filename)
md5 = workbench.store_sample(f.read(), base_name, 'exe')
# Index the strings and features output (notice we can ask for any worker output)
# Also (super important) it all happens on the server side.
workbench.index_worker_output('strings', md5, 'strings', None)
print '\n<<< Strings for PE: %s Indexed>>>' % (base_name)
workbench.index_worker_output('pe_features', md5, 'pe_features', None)
print '<<< Features for PE: %s Indexed>>>' % (base_name)
# Well we should execute some queries against ElasticSearch at this point but as of
# version 1.2+ the dynamic scripting disabled by default, see
# 'http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-scripting.html#_enabling_dynamic_scripting
# Now actually do something interesing with our ELS index
# ES Facets are kewl (http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets.html)
facet_query = '{"facets" : {"tag" : {"terms" : {"field" : "string_list"}}}}'
results = workbench.search_index('strings', facet_query)
try:
print '\nQuery: %s' % facet_query
print 'Number of hits: %d' % results['hits']['total']
print 'Max Score: %f' % results['hits']['max_score']
pprint.pprint(results['facets'])
except TypeError:
print 'Probably using a Stub Indexer, if you want an ELS Indexer see the readme'
# Fuzzy is kewl (http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-fuzzy-query.html)
fuzzy_query = '{"fields":["md5","sparse_features.imported_symbols"],' \
'"query": {"fuzzy" : {"sparse_features.imported_symbols" : "loadlibrary"}}}'
results = workbench.search_index('pe_features', fuzzy_query)
try:
print '\nQuery: %s' % fuzzy_query
print 'Number of hits: %d' % results['hits']['total']
print 'Max Score: %f' % results['hits']['max_score']
pprint.pprint([(hit['fields']['md5'], hit['fields']['sparse_features.imported_symbols'])
for hit in results['hits']['hits']])
except TypeError:
print 'Probably using a Stub Indexer, if you want an ELS Indexer see the readme' | python | def run():
"""This client pushes PE Files -> ELS Indexer."""
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
workbench = zerorpc.Client(timeout=300, heartbeat=60)
workbench.connect('tcp://'+args['server']+':'+args['port'])
# Test out PEFile -> strings -> indexer -> search
data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),'../data/pe/bad')
file_list = [os.path.join(data_path, child) for child in os.listdir(data_path)][:20]
for filename in file_list:
# Skip OS generated files
if '.DS_Store' in filename:
continue
with open(filename, 'rb') as f:
base_name = os.path.basename(filename)
md5 = workbench.store_sample(f.read(), base_name, 'exe')
# Index the strings and features output (notice we can ask for any worker output)
# Also (super important) it all happens on the server side.
workbench.index_worker_output('strings', md5, 'strings', None)
print '\n<<< Strings for PE: %s Indexed>>>' % (base_name)
workbench.index_worker_output('pe_features', md5, 'pe_features', None)
print '<<< Features for PE: %s Indexed>>>' % (base_name)
# Well we should execute some queries against ElasticSearch at this point but as of
# version 1.2+ the dynamic scripting disabled by default, see
# 'http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-scripting.html#_enabling_dynamic_scripting
# Now actually do something interesing with our ELS index
# ES Facets are kewl (http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets.html)
facet_query = '{"facets" : {"tag" : {"terms" : {"field" : "string_list"}}}}'
results = workbench.search_index('strings', facet_query)
try:
print '\nQuery: %s' % facet_query
print 'Number of hits: %d' % results['hits']['total']
print 'Max Score: %f' % results['hits']['max_score']
pprint.pprint(results['facets'])
except TypeError:
print 'Probably using a Stub Indexer, if you want an ELS Indexer see the readme'
# Fuzzy is kewl (http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-fuzzy-query.html)
fuzzy_query = '{"fields":["md5","sparse_features.imported_symbols"],' \
'"query": {"fuzzy" : {"sparse_features.imported_symbols" : "loadlibrary"}}}'
results = workbench.search_index('pe_features', fuzzy_query)
try:
print '\nQuery: %s' % fuzzy_query
print 'Number of hits: %d' % results['hits']['total']
print 'Max Score: %f' % results['hits']['max_score']
pprint.pprint([(hit['fields']['md5'], hit['fields']['sparse_features.imported_symbols'])
for hit in results['hits']['hits']])
except TypeError:
print 'Probably using a Stub Indexer, if you want an ELS Indexer see the readme' | [
"def",
"run",
"(",
")",
":",
"# Grab server args",
"args",
"=",
"client_helper",
".",
"grab_server_args",
"(",
")",
"# Start up workbench connection",
"workbench",
"=",
"zerorpc",
".",
"Client",
"(",
"timeout",
"=",
"300",
",",
"heartbeat",
"=",
"60",
")",
"wo... | This client pushes PE Files -> ELS Indexer. | [
"This",
"client",
"pushes",
"PE",
"Files",
"-",
">",
"ELS",
"Indexer",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/pe_indexer.py#L7-L64 | train | 43,310 |
SuperCowPowers/workbench | workbench/workers/pe_features.py | convert_to_utf8 | def convert_to_utf8(string):
''' Convert string to UTF8 '''
if (isinstance(string, unicode)):
return string.encode('utf-8')
try:
u = unicode(string, 'utf-8')
except TypeError:
return str(string)
utf8 = u.encode('utf-8')
return utf8 | python | def convert_to_utf8(string):
''' Convert string to UTF8 '''
if (isinstance(string, unicode)):
return string.encode('utf-8')
try:
u = unicode(string, 'utf-8')
except TypeError:
return str(string)
utf8 = u.encode('utf-8')
return utf8 | [
"def",
"convert_to_utf8",
"(",
"string",
")",
":",
"if",
"(",
"isinstance",
"(",
"string",
",",
"unicode",
")",
")",
":",
"return",
"string",
".",
"encode",
"(",
"'utf-8'",
")",
"try",
":",
"u",
"=",
"unicode",
"(",
"string",
",",
"'utf-8'",
")",
"ex... | Convert string to UTF8 | [
"Convert",
"string",
"to",
"UTF8"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pe_features.py#L309-L318 | train | 43,311 |
SuperCowPowers/workbench | workbench/workers/pe_features.py | PEFileWorker.execute | def execute(self, input_data):
''' Process the input bytes with pefile '''
raw_bytes = input_data['sample']['raw_bytes']
# Have the PE File module process the file
pefile_handle, error_str = self.open_using_pefile('unknown', raw_bytes)
if not pefile_handle:
return {'error': error_str, 'dense_features': [], 'sparse_features': []}
# Now extract the various features using pefile
dense_features, sparse_features = self.extract_features_using_pefile(pefile_handle)
# Okay set my response
return {'dense_features': dense_features, 'sparse_features': sparse_features, 'tags': input_data['tags']['tags']} | python | def execute(self, input_data):
''' Process the input bytes with pefile '''
raw_bytes = input_data['sample']['raw_bytes']
# Have the PE File module process the file
pefile_handle, error_str = self.open_using_pefile('unknown', raw_bytes)
if not pefile_handle:
return {'error': error_str, 'dense_features': [], 'sparse_features': []}
# Now extract the various features using pefile
dense_features, sparse_features = self.extract_features_using_pefile(pefile_handle)
# Okay set my response
return {'dense_features': dense_features, 'sparse_features': sparse_features, 'tags': input_data['tags']['tags']} | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"raw_bytes",
"=",
"input_data",
"[",
"'sample'",
"]",
"[",
"'raw_bytes'",
"]",
"# Have the PE File module process the file",
"pefile_handle",
",",
"error_str",
"=",
"self",
".",
"open_using_pefile",
"(",
... | Process the input bytes with pefile | [
"Process",
"the",
"input",
"bytes",
"with",
"pefile"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pe_features.py#L53-L67 | train | 43,312 |
SuperCowPowers/workbench | workbench/workers/pe_features.py | PEFileWorker.open_using_pefile | def open_using_pefile(input_name, input_bytes):
''' Open the PE File using the Python pefile module. '''
try:
pef = pefile.PE(data=input_bytes, fast_load=False)
except (AttributeError, pefile.PEFormatError), error:
print 'warning: pe_fail (with exception from pefile module) on file: %s' % input_name
error_str = '(Exception):, %s' % (str(error))
return None, error_str
# Now test to see if the features are there/extractable if not return FAIL flag
if pef.PE_TYPE is None or pef.OPTIONAL_HEADER is None or len(pef.OPTIONAL_HEADER.DATA_DIRECTORY) < 7:
print 'warning: pe_fail on file: %s' % input_name
error_str = 'warning: pe_fail on file: %s' % input_name
return None, error_str
# Success
return pef, None | python | def open_using_pefile(input_name, input_bytes):
''' Open the PE File using the Python pefile module. '''
try:
pef = pefile.PE(data=input_bytes, fast_load=False)
except (AttributeError, pefile.PEFormatError), error:
print 'warning: pe_fail (with exception from pefile module) on file: %s' % input_name
error_str = '(Exception):, %s' % (str(error))
return None, error_str
# Now test to see if the features are there/extractable if not return FAIL flag
if pef.PE_TYPE is None or pef.OPTIONAL_HEADER is None or len(pef.OPTIONAL_HEADER.DATA_DIRECTORY) < 7:
print 'warning: pe_fail on file: %s' % input_name
error_str = 'warning: pe_fail on file: %s' % input_name
return None, error_str
# Success
return pef, None | [
"def",
"open_using_pefile",
"(",
"input_name",
",",
"input_bytes",
")",
":",
"try",
":",
"pef",
"=",
"pefile",
".",
"PE",
"(",
"data",
"=",
"input_bytes",
",",
"fast_load",
"=",
"False",
")",
"except",
"(",
"AttributeError",
",",
"pefile",
".",
"PEFormatEr... | Open the PE File using the Python pefile module. | [
"Open",
"the",
"PE",
"File",
"using",
"the",
"Python",
"pefile",
"module",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pe_features.py#L93-L109 | train | 43,313 |
SuperCowPowers/workbench | workbench/server/bro/bro_log_reader.py | BroLogReader.read_log | def read_log(self, logfile):
"""The read_log method returns a memory efficient generator for rows in a Bro log.
Usage:
rows = my_bro_reader.read_log(logfile)
for row in rows:
do something with row
Args:
logfile: The Bro Log file.
"""
# Make sure we're at the beginning
logfile.seek(0)
# First parse the header of the bro log
field_names, _ = self._parse_bro_header(logfile)
# Note: SO stupid to write a csv reader, but csv.DictReader on Bro
# files was doing something weird with generator output that
# affected zeroRPC and gave 'could not route _zpc_more' error.
# So wrote my own, put a sleep at the end, seems to fix it.
while 1:
_line = next(logfile).strip()
if not _line.startswith('#close'):
yield self._cast_dict(dict(zip(field_names, _line.split(self.delimiter))))
else:
time.sleep(.1) # Give time for zeroRPC to finish messages
break | python | def read_log(self, logfile):
"""The read_log method returns a memory efficient generator for rows in a Bro log.
Usage:
rows = my_bro_reader.read_log(logfile)
for row in rows:
do something with row
Args:
logfile: The Bro Log file.
"""
# Make sure we're at the beginning
logfile.seek(0)
# First parse the header of the bro log
field_names, _ = self._parse_bro_header(logfile)
# Note: SO stupid to write a csv reader, but csv.DictReader on Bro
# files was doing something weird with generator output that
# affected zeroRPC and gave 'could not route _zpc_more' error.
# So wrote my own, put a sleep at the end, seems to fix it.
while 1:
_line = next(logfile).strip()
if not _line.startswith('#close'):
yield self._cast_dict(dict(zip(field_names, _line.split(self.delimiter))))
else:
time.sleep(.1) # Give time for zeroRPC to finish messages
break | [
"def",
"read_log",
"(",
"self",
",",
"logfile",
")",
":",
"# Make sure we're at the beginning",
"logfile",
".",
"seek",
"(",
"0",
")",
"# First parse the header of the bro log",
"field_names",
",",
"_",
"=",
"self",
".",
"_parse_bro_header",
"(",
"logfile",
")",
"... | The read_log method returns a memory efficient generator for rows in a Bro log.
Usage:
rows = my_bro_reader.read_log(logfile)
for row in rows:
do something with row
Args:
logfile: The Bro Log file. | [
"The",
"read_log",
"method",
"returns",
"a",
"memory",
"efficient",
"generator",
"for",
"rows",
"in",
"a",
"Bro",
"log",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/bro/bro_log_reader.py#L20-L48 | train | 43,314 |
SuperCowPowers/workbench | workbench/server/bro/bro_log_reader.py | BroLogReader._parse_bro_header | def _parse_bro_header(self, logfile):
"""This method tries to parse the Bro log header section.
Note: My googling is failing me on the documentation on the format,
so just making a lot of assumptions and skipping some shit.
Assumption 1: The delimeter is a tab.
Assumption 2: Types are either time, string, int or float
Assumption 3: The header always ends with #fields and #types as
the last two lines.
Format example:
#separator \x09
#set_separator ,
#empty_field (empty)
#unset_field -
#path httpheader_recon
#fields ts origin useragent header_events_json
#types time string string string
Args:
logfile: The Bro log file.
Returns:
A tuple of 2 lists. One for field names and other for field types.
"""
# Skip until you find the #fields line
_line = next(logfile)
while (not _line.startswith('#fields')):
_line = next(logfile)
# Read in the field names
_field_names = _line.strip().split(self.delimiter)[1:]
# Read in the types
_line = next(logfile)
_field_types = _line.strip().split(self.delimiter)[1:]
# Return the header info
return _field_names, _field_types | python | def _parse_bro_header(self, logfile):
"""This method tries to parse the Bro log header section.
Note: My googling is failing me on the documentation on the format,
so just making a lot of assumptions and skipping some shit.
Assumption 1: The delimeter is a tab.
Assumption 2: Types are either time, string, int or float
Assumption 3: The header always ends with #fields and #types as
the last two lines.
Format example:
#separator \x09
#set_separator ,
#empty_field (empty)
#unset_field -
#path httpheader_recon
#fields ts origin useragent header_events_json
#types time string string string
Args:
logfile: The Bro log file.
Returns:
A tuple of 2 lists. One for field names and other for field types.
"""
# Skip until you find the #fields line
_line = next(logfile)
while (not _line.startswith('#fields')):
_line = next(logfile)
# Read in the field names
_field_names = _line.strip().split(self.delimiter)[1:]
# Read in the types
_line = next(logfile)
_field_types = _line.strip().split(self.delimiter)[1:]
# Return the header info
return _field_names, _field_types | [
"def",
"_parse_bro_header",
"(",
"self",
",",
"logfile",
")",
":",
"# Skip until you find the #fields line",
"_line",
"=",
"next",
"(",
"logfile",
")",
"while",
"(",
"not",
"_line",
".",
"startswith",
"(",
"'#fields'",
")",
")",
":",
"_line",
"=",
"next",
"(... | This method tries to parse the Bro log header section.
Note: My googling is failing me on the documentation on the format,
so just making a lot of assumptions and skipping some shit.
Assumption 1: The delimeter is a tab.
Assumption 2: Types are either time, string, int or float
Assumption 3: The header always ends with #fields and #types as
the last two lines.
Format example:
#separator \x09
#set_separator ,
#empty_field (empty)
#unset_field -
#path httpheader_recon
#fields ts origin useragent header_events_json
#types time string string string
Args:
logfile: The Bro log file.
Returns:
A tuple of 2 lists. One for field names and other for field types. | [
"This",
"method",
"tries",
"to",
"parse",
"the",
"Bro",
"log",
"header",
"section",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/bro/bro_log_reader.py#L51-L90 | train | 43,315 |
SuperCowPowers/workbench | workbench/server/bro/bro_log_reader.py | BroLogReader._cast_dict | def _cast_dict(self, data_dict):
"""Internal method that makes sure any dictionary elements
are properly cast into the correct types, instead of
just treating everything like a string from the csv file.
Args:
data_dict: dictionary containing bro log data.
Returns:
Cleaned Data dict.
"""
for key, value in data_dict.iteritems():
data_dict[key] = self._cast_value(value)
# Fixme: resp_body_data can be very large so removing it for now
if 'resp_body_data' in data_dict:
del data_dict['resp_body_data']
return data_dict | python | def _cast_dict(self, data_dict):
"""Internal method that makes sure any dictionary elements
are properly cast into the correct types, instead of
just treating everything like a string from the csv file.
Args:
data_dict: dictionary containing bro log data.
Returns:
Cleaned Data dict.
"""
for key, value in data_dict.iteritems():
data_dict[key] = self._cast_value(value)
# Fixme: resp_body_data can be very large so removing it for now
if 'resp_body_data' in data_dict:
del data_dict['resp_body_data']
return data_dict | [
"def",
"_cast_dict",
"(",
"self",
",",
"data_dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"data_dict",
".",
"iteritems",
"(",
")",
":",
"data_dict",
"[",
"key",
"]",
"=",
"self",
".",
"_cast_value",
"(",
"value",
")",
"# Fixme: resp_body_data can be ... | Internal method that makes sure any dictionary elements
are properly cast into the correct types, instead of
just treating everything like a string from the csv file.
Args:
data_dict: dictionary containing bro log data.
Returns:
Cleaned Data dict. | [
"Internal",
"method",
"that",
"makes",
"sure",
"any",
"dictionary",
"elements",
"are",
"properly",
"cast",
"into",
"the",
"correct",
"types",
"instead",
"of",
"just",
"treating",
"everything",
"like",
"a",
"string",
"from",
"the",
"csv",
"file",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/bro/bro_log_reader.py#L92-L110 | train | 43,316 |
SuperCowPowers/workbench | workbench/server/bro/bro_log_reader.py | BroLogReader._cast_value | def _cast_value(self, value):
"""Internal method that makes sure every value in dictionary
is properly cast into the correct types, instead of
just treating everything like a string from the csv file.
Args:
value : The value to be casted
Returns:
A casted Value.
"""
# Try to convert to a datetime (if requested)
if (self.convert_datetimes):
try:
date_time = datetime.datetime.fromtimestamp(float(value))
if datetime.datetime(1970, 1, 1) > date_time:
raise ValueError
else:
return date_time
# Next try a set of primitive types
except ValueError:
pass
# Try conversion to basic types
tests = (int, float, str)
for test in tests:
try:
return test(value)
except ValueError:
continue
return value | python | def _cast_value(self, value):
"""Internal method that makes sure every value in dictionary
is properly cast into the correct types, instead of
just treating everything like a string from the csv file.
Args:
value : The value to be casted
Returns:
A casted Value.
"""
# Try to convert to a datetime (if requested)
if (self.convert_datetimes):
try:
date_time = datetime.datetime.fromtimestamp(float(value))
if datetime.datetime(1970, 1, 1) > date_time:
raise ValueError
else:
return date_time
# Next try a set of primitive types
except ValueError:
pass
# Try conversion to basic types
tests = (int, float, str)
for test in tests:
try:
return test(value)
except ValueError:
continue
return value | [
"def",
"_cast_value",
"(",
"self",
",",
"value",
")",
":",
"# Try to convert to a datetime (if requested)",
"if",
"(",
"self",
".",
"convert_datetimes",
")",
":",
"try",
":",
"date_time",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"float",
"(",... | Internal method that makes sure every value in dictionary
is properly cast into the correct types, instead of
just treating everything like a string from the csv file.
Args:
value : The value to be casted
Returns:
A casted Value. | [
"Internal",
"method",
"that",
"makes",
"sure",
"every",
"value",
"in",
"dictionary",
"is",
"properly",
"cast",
"into",
"the",
"correct",
"types",
"instead",
"of",
"just",
"treating",
"everything",
"like",
"a",
"string",
"from",
"the",
"csv",
"file",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/bro/bro_log_reader.py#L112-L143 | train | 43,317 |
SuperCowPowers/workbench | workbench/clients/zip_file_extraction.py | run | def run():
"""This client shows workbench extacting files from a zip file."""
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
workbench = zerorpc.Client(timeout=300, heartbeat=60)
workbench.connect('tcp://'+args['server']+':'+args['port'])
# Test out zip data
data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),'../data/zip')
file_list = [os.path.join(data_path, child) for child in os.listdir(data_path)]
for filename in file_list:
with open(filename,'rb') as f:
base_name = os.path.basename(filename)
md5 = workbench.store_sample(f.read(), base_name, 'zip')
results = workbench.work_request('view', md5)
print 'Filename: %s ' % (base_name)
pprint.pprint(results)
# The unzip worker gives you a list of md5s back
# Run meta on all the unzipped files.
results = workbench.work_request('unzip', md5)
print '\n*** Filename: %s ***' % (base_name)
for child_md5 in results['unzip']['payload_md5s']:
pprint.pprint(workbench.work_request('meta', child_md5)) | python | def run():
"""This client shows workbench extacting files from a zip file."""
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
workbench = zerorpc.Client(timeout=300, heartbeat=60)
workbench.connect('tcp://'+args['server']+':'+args['port'])
# Test out zip data
data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),'../data/zip')
file_list = [os.path.join(data_path, child) for child in os.listdir(data_path)]
for filename in file_list:
with open(filename,'rb') as f:
base_name = os.path.basename(filename)
md5 = workbench.store_sample(f.read(), base_name, 'zip')
results = workbench.work_request('view', md5)
print 'Filename: %s ' % (base_name)
pprint.pprint(results)
# The unzip worker gives you a list of md5s back
# Run meta on all the unzipped files.
results = workbench.work_request('unzip', md5)
print '\n*** Filename: %s ***' % (base_name)
for child_md5 in results['unzip']['payload_md5s']:
pprint.pprint(workbench.work_request('meta', child_md5)) | [
"def",
"run",
"(",
")",
":",
"# Grab server args",
"args",
"=",
"client_helper",
".",
"grab_server_args",
"(",
")",
"# Start up workbench connection",
"workbench",
"=",
"zerorpc",
".",
"Client",
"(",
"timeout",
"=",
"300",
",",
"heartbeat",
"=",
"60",
")",
"wo... | This client shows workbench extacting files from a zip file. | [
"This",
"client",
"shows",
"workbench",
"extacting",
"files",
"from",
"a",
"zip",
"file",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/zip_file_extraction.py#L8-L34 | train | 43,318 |
SuperCowPowers/workbench | workbench/workers/vt_query.py | VTQuery.execute | def execute(self, input_data):
''' Execute the VTQuery worker '''
md5 = input_data['meta']['md5']
response = requests.get('http://www.virustotal.com/vtapi/v2/file/report',
params={'apikey':self.apikey,'resource':md5, 'allinfo':1})
# Make sure we got a json blob back
try:
vt_output = response.json()
except ValueError:
return {'vt_error': 'VirusTotal Query Error, no valid response... past per min quota?'}
# Just pull some of the fields
output = {field:vt_output[field] for field in vt_output.keys() if field not in self.exclude}
# Check for not-found
not_found = False if output else True
# Add in file_type
output['file_type'] = input_data['meta']['file_type']
# Toss back a not found
if not_found:
output['not_found'] = True
return output
# Organize the scans fields
scan_results = collections.Counter()
for scan in vt_output['scans'].values():
if 'result' in scan:
if scan['result']:
scan_results[scan['result']] += 1
output['scan_results'] = scan_results.most_common(5)
return output | python | def execute(self, input_data):
''' Execute the VTQuery worker '''
md5 = input_data['meta']['md5']
response = requests.get('http://www.virustotal.com/vtapi/v2/file/report',
params={'apikey':self.apikey,'resource':md5, 'allinfo':1})
# Make sure we got a json blob back
try:
vt_output = response.json()
except ValueError:
return {'vt_error': 'VirusTotal Query Error, no valid response... past per min quota?'}
# Just pull some of the fields
output = {field:vt_output[field] for field in vt_output.keys() if field not in self.exclude}
# Check for not-found
not_found = False if output else True
# Add in file_type
output['file_type'] = input_data['meta']['file_type']
# Toss back a not found
if not_found:
output['not_found'] = True
return output
# Organize the scans fields
scan_results = collections.Counter()
for scan in vt_output['scans'].values():
if 'result' in scan:
if scan['result']:
scan_results[scan['result']] += 1
output['scan_results'] = scan_results.most_common(5)
return output | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"md5",
"=",
"input_data",
"[",
"'meta'",
"]",
"[",
"'md5'",
"]",
"response",
"=",
"requests",
".",
"get",
"(",
"'http://www.virustotal.com/vtapi/v2/file/report'",
",",
"params",
"=",
"{",
"'apikey'",
... | Execute the VTQuery worker | [
"Execute",
"the",
"VTQuery",
"worker"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/vt_query.py#L30-L63 | train | 43,319 |
SuperCowPowers/workbench | workbench/workers/pe_peid.py | get_peid_db | def get_peid_db():
''' Grab the peid_userdb.txt file from local disk '''
# Try to find the yara rules directory relative to the worker
my_dir = os.path.dirname(os.path.realpath(__file__))
db_path = os.path.join(my_dir, 'peid_userdb.txt')
if not os.path.exists(db_path):
raise RuntimeError('peid could not find peid_userdb.txt under: %s' % db_path)
# Okay load up signature
signatures = peutils.SignatureDatabase(data = open(db_path, 'rb').read())
return signatures | python | def get_peid_db():
''' Grab the peid_userdb.txt file from local disk '''
# Try to find the yara rules directory relative to the worker
my_dir = os.path.dirname(os.path.realpath(__file__))
db_path = os.path.join(my_dir, 'peid_userdb.txt')
if not os.path.exists(db_path):
raise RuntimeError('peid could not find peid_userdb.txt under: %s' % db_path)
# Okay load up signature
signatures = peutils.SignatureDatabase(data = open(db_path, 'rb').read())
return signatures | [
"def",
"get_peid_db",
"(",
")",
":",
"# Try to find the yara rules directory relative to the worker",
"my_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"db_path",
"=",
"os",
".",
"path",
".",
... | Grab the peid_userdb.txt file from local disk | [
"Grab",
"the",
"peid_userdb",
".",
"txt",
"file",
"from",
"local",
"disk"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pe_peid.py#L9-L20 | train | 43,320 |
SuperCowPowers/workbench | workbench/workers/pe_peid.py | PEIDWorker.execute | def execute(self, input_data):
''' Execute the PEIDWorker '''
raw_bytes = input_data['sample']['raw_bytes']
# Have the PE File module process the file
try:
pefile_handle = pefile.PE(data=raw_bytes, fast_load=False)
except (AttributeError, pefile.PEFormatError), error:
return {'error': str(error), 'match_list': []}
# Now get information from PEID module
peid_match = self.peid_features(pefile_handle)
return {'match_list': peid_match} | python | def execute(self, input_data):
''' Execute the PEIDWorker '''
raw_bytes = input_data['sample']['raw_bytes']
# Have the PE File module process the file
try:
pefile_handle = pefile.PE(data=raw_bytes, fast_load=False)
except (AttributeError, pefile.PEFormatError), error:
return {'error': str(error), 'match_list': []}
# Now get information from PEID module
peid_match = self.peid_features(pefile_handle)
return {'match_list': peid_match} | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"raw_bytes",
"=",
"input_data",
"[",
"'sample'",
"]",
"[",
"'raw_bytes'",
"]",
"# Have the PE File module process the file",
"try",
":",
"pefile_handle",
"=",
"pefile",
".",
"PE",
"(",
"data",
"=",
"r... | Execute the PEIDWorker | [
"Execute",
"the",
"PEIDWorker"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pe_peid.py#L31-L43 | train | 43,321 |
SuperCowPowers/workbench | workbench/workers/pe_peid.py | PEIDWorker.peid_features | def peid_features(self, pefile_handle):
''' Get features from PEid signature database'''
peid_match = self.peid_sigs.match(pefile_handle)
return peid_match if peid_match else [] | python | def peid_features(self, pefile_handle):
''' Get features from PEid signature database'''
peid_match = self.peid_sigs.match(pefile_handle)
return peid_match if peid_match else [] | [
"def",
"peid_features",
"(",
"self",
",",
"pefile_handle",
")",
":",
"peid_match",
"=",
"self",
".",
"peid_sigs",
".",
"match",
"(",
"pefile_handle",
")",
"return",
"peid_match",
"if",
"peid_match",
"else",
"[",
"]"
] | Get features from PEid signature database | [
"Get",
"features",
"from",
"PEid",
"signature",
"database"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pe_peid.py#L45-L48 | train | 43,322 |
SuperCowPowers/workbench | workbench/clients/pcap_report.py | run | def run():
"""This client pulls PCAP files for building report.
Returns:
A list with `view_pcap` , `meta` and `filename` objects.
"""
global WORKBENCH
# Grab grab_server_argsrver args
args = client_helper.grab_server_args()
# Start up workbench connection
WORKBENCH = zerorpc.Client(timeout=300, heartbeat=60)
WORKBENCH.connect('tcp://'+args['server']+':'+args['port'])
data_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)), '../data/pcap')
file_list = [os.path.join(data_path, child) for child in \
os.listdir(data_path)]
results = []
for filename in file_list:
# Skip OS generated files
if '.DS_Store' in filename: continue
# Process the pcap file
with open(filename,'rb') as f:
md5 = WORKBENCH.store_sample(f.read(), filename, 'pcap')
result = WORKBENCH.work_request('view_pcap', md5)
result.update(WORKBENCH.work_request('meta', result['view_pcap']['md5']))
result['filename'] = result['meta']['filename'].split('/')[-1]
results.append(result)
return results | python | def run():
"""This client pulls PCAP files for building report.
Returns:
A list with `view_pcap` , `meta` and `filename` objects.
"""
global WORKBENCH
# Grab grab_server_argsrver args
args = client_helper.grab_server_args()
# Start up workbench connection
WORKBENCH = zerorpc.Client(timeout=300, heartbeat=60)
WORKBENCH.connect('tcp://'+args['server']+':'+args['port'])
data_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)), '../data/pcap')
file_list = [os.path.join(data_path, child) for child in \
os.listdir(data_path)]
results = []
for filename in file_list:
# Skip OS generated files
if '.DS_Store' in filename: continue
# Process the pcap file
with open(filename,'rb') as f:
md5 = WORKBENCH.store_sample(f.read(), filename, 'pcap')
result = WORKBENCH.work_request('view_pcap', md5)
result.update(WORKBENCH.work_request('meta', result['view_pcap']['md5']))
result['filename'] = result['meta']['filename'].split('/')[-1]
results.append(result)
return results | [
"def",
"run",
"(",
")",
":",
"global",
"WORKBENCH",
"# Grab grab_server_argsrver args",
"args",
"=",
"client_helper",
".",
"grab_server_args",
"(",
")",
"# Start up workbench connection",
"WORKBENCH",
"=",
"zerorpc",
".",
"Client",
"(",
"timeout",
"=",
"300",
",",
... | This client pulls PCAP files for building report.
Returns:
A list with `view_pcap` , `meta` and `filename` objects. | [
"This",
"client",
"pulls",
"PCAP",
"files",
"for",
"building",
"report",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/pcap_report.py#L17-L51 | train | 43,323 |
SuperCowPowers/workbench | workbench/clients/pcap_report.py | show_files | def show_files(md5):
'''Renders template with `view` of the md5.'''
if not WORKBENCH:
return flask.redirect('/')
md5_view = WORKBENCH.work_request('view', md5)
return flask.render_template('templates/md5_view.html', md5_view=md5_view['view'], md5=md5) | python | def show_files(md5):
'''Renders template with `view` of the md5.'''
if not WORKBENCH:
return flask.redirect('/')
md5_view = WORKBENCH.work_request('view', md5)
return flask.render_template('templates/md5_view.html', md5_view=md5_view['view'], md5=md5) | [
"def",
"show_files",
"(",
"md5",
")",
":",
"if",
"not",
"WORKBENCH",
":",
"return",
"flask",
".",
"redirect",
"(",
"'/'",
")",
"md5_view",
"=",
"WORKBENCH",
".",
"work_request",
"(",
"'view'",
",",
"md5",
")",
"return",
"flask",
".",
"render_template",
"... | Renders template with `view` of the md5. | [
"Renders",
"template",
"with",
"view",
"of",
"the",
"md5",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/pcap_report.py#L60-L66 | train | 43,324 |
SuperCowPowers/workbench | workbench/clients/pcap_report.py | show_md5_view | def show_md5_view(md5):
'''Renders template with `stream_sample` of the md5.'''
if not WORKBENCH:
return flask.redirect('/')
md5_view = WORKBENCH.stream_sample(md5)
return flask.render_template('templates/md5_view.html', md5_view=list(md5_view), md5=md5) | python | def show_md5_view(md5):
'''Renders template with `stream_sample` of the md5.'''
if not WORKBENCH:
return flask.redirect('/')
md5_view = WORKBENCH.stream_sample(md5)
return flask.render_template('templates/md5_view.html', md5_view=list(md5_view), md5=md5) | [
"def",
"show_md5_view",
"(",
"md5",
")",
":",
"if",
"not",
"WORKBENCH",
":",
"return",
"flask",
".",
"redirect",
"(",
"'/'",
")",
"md5_view",
"=",
"WORKBENCH",
".",
"stream_sample",
"(",
"md5",
")",
"return",
"flask",
".",
"render_template",
"(",
"'templat... | Renders template with `stream_sample` of the md5. | [
"Renders",
"template",
"with",
"stream_sample",
"of",
"the",
"md5",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/pcap_report.py#L71-L78 | train | 43,325 |
SuperCowPowers/workbench | workbench/workers/timeout_corner/pe_features_df.py | PEFeaturesDF.execute | def execute(self, input_data):
"""This worker puts the output of pe_features into a dictionary of dataframes"""
if 'sample' in input_data:
print 'Warning: PEFeaturesDF is supposed to be called on a sample_set'
self.samples.append(input_data['sample']['md5'])
else:
self.samples = input_data['sample_set']['md5_list']
# Make a sample set
sample_set = self.workbench.store_sample_set(self.samples)
# Dense Features
dense_features = self.workbench.set_work_request('pe_features', sample_set, ['md5', 'tags', 'dense_features'])
# Fixme: There's probably a nicer/better way to do this
flat_features = []
for feat in dense_features:
feat['dense_features'].update({'md5': feat['md5'], 'tags': feat['tags']})
flat_features.append(feat['dense_features'])
dense_df = pd.DataFrame(flat_features)
df_packed = dense_df.to_msgpack()
dense_df_md5 = self.workbench.store_sample(df_packed, 'pe_features_dense_df', 'dataframe')
# Sparse Features
sparse_features = self.workbench.set_work_request('pe_features', sample_set, ['md5', 'tags', 'sparse_features'])
# Fixme: There's probably a nicer/better way to do this
flat_features = []
for feat in sparse_features:
feat['sparse_features'].update({'md5': feat['md5'], 'tags': feat['tags']})
flat_features.append(feat['sparse_features'])
sparse_df = pd.DataFrame(flat_features)
df_packed = sparse_df.to_msgpack()
sparse_df_md5 = self.workbench.store_sample(df_packed, 'pe_features_sparse_df', 'dataframe')
# Return the dataframes
return {'dense_features': dense_df_md5, 'sparse_features': sparse_df_md5} | python | def execute(self, input_data):
"""This worker puts the output of pe_features into a dictionary of dataframes"""
if 'sample' in input_data:
print 'Warning: PEFeaturesDF is supposed to be called on a sample_set'
self.samples.append(input_data['sample']['md5'])
else:
self.samples = input_data['sample_set']['md5_list']
# Make a sample set
sample_set = self.workbench.store_sample_set(self.samples)
# Dense Features
dense_features = self.workbench.set_work_request('pe_features', sample_set, ['md5', 'tags', 'dense_features'])
# Fixme: There's probably a nicer/better way to do this
flat_features = []
for feat in dense_features:
feat['dense_features'].update({'md5': feat['md5'], 'tags': feat['tags']})
flat_features.append(feat['dense_features'])
dense_df = pd.DataFrame(flat_features)
df_packed = dense_df.to_msgpack()
dense_df_md5 = self.workbench.store_sample(df_packed, 'pe_features_dense_df', 'dataframe')
# Sparse Features
sparse_features = self.workbench.set_work_request('pe_features', sample_set, ['md5', 'tags', 'sparse_features'])
# Fixme: There's probably a nicer/better way to do this
flat_features = []
for feat in sparse_features:
feat['sparse_features'].update({'md5': feat['md5'], 'tags': feat['tags']})
flat_features.append(feat['sparse_features'])
sparse_df = pd.DataFrame(flat_features)
df_packed = sparse_df.to_msgpack()
sparse_df_md5 = self.workbench.store_sample(df_packed, 'pe_features_sparse_df', 'dataframe')
# Return the dataframes
return {'dense_features': dense_df_md5, 'sparse_features': sparse_df_md5} | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"if",
"'sample'",
"in",
"input_data",
":",
"print",
"'Warning: PEFeaturesDF is supposed to be called on a sample_set'",
"self",
".",
"samples",
".",
"append",
"(",
"input_data",
"[",
"'sample'",
"]",
"[",
... | This worker puts the output of pe_features into a dictionary of dataframes | [
"This",
"worker",
"puts",
"the",
"output",
"of",
"pe_features",
"into",
"a",
"dictionary",
"of",
"dataframes"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/timeout_corner/pe_features_df.py#L19-L55 | train | 43,326 |
SuperCowPowers/workbench | workbench/server/neo_db.py | NeoDB.add_node | def add_node(self, node_id, name, labels):
"""Add the node with name and labels.
Args:
node_id: Id for the node.
name: Name for the node.
labels: Label for the node.
Raises:
NotImplementedError: When adding labels is not supported.
"""
node = self.graph_db.get_or_create_indexed_node('Node', 'node_id', node_id, {'node_id': node_id, 'name': name})
try:
node.add_labels(*labels)
except NotImplementedError:
pass | python | def add_node(self, node_id, name, labels):
"""Add the node with name and labels.
Args:
node_id: Id for the node.
name: Name for the node.
labels: Label for the node.
Raises:
NotImplementedError: When adding labels is not supported.
"""
node = self.graph_db.get_or_create_indexed_node('Node', 'node_id', node_id, {'node_id': node_id, 'name': name})
try:
node.add_labels(*labels)
except NotImplementedError:
pass | [
"def",
"add_node",
"(",
"self",
",",
"node_id",
",",
"name",
",",
"labels",
")",
":",
"node",
"=",
"self",
".",
"graph_db",
".",
"get_or_create_indexed_node",
"(",
"'Node'",
",",
"'node_id'",
",",
"node_id",
",",
"{",
"'node_id'",
":",
"node_id",
",",
"'... | Add the node with name and labels.
Args:
node_id: Id for the node.
name: Name for the node.
labels: Label for the node.
Raises:
NotImplementedError: When adding labels is not supported. | [
"Add",
"the",
"node",
"with",
"name",
"and",
"labels",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/neo_db.py#L26-L41 | train | 43,327 |
SuperCowPowers/workbench | workbench/server/neo_db.py | NeoDB.add_rel | def add_rel(self, source_node_id, target_node_id, rel):
"""Add a relationship between nodes.
Args:
source_node_id: Node Id for the source node.
target_node_id: Node Id for the target node.
rel: Name of the relationship 'contains'
"""
# Add the relationship
n1_ref = self.graph_db.get_indexed_node('Node', 'node_id', source_node_id)
n2_ref = self.graph_db.get_indexed_node('Node', 'node_id', target_node_id)
# Sanity check
if not n1_ref or not n2_ref:
print 'Cannot add relationship between unfound nodes: %s --> %s' % (source_node_id, target_node_id)
return
path = neo4j.Path(n1_ref, rel, n2_ref)
path.get_or_create(self.graph_db) | python | def add_rel(self, source_node_id, target_node_id, rel):
"""Add a relationship between nodes.
Args:
source_node_id: Node Id for the source node.
target_node_id: Node Id for the target node.
rel: Name of the relationship 'contains'
"""
# Add the relationship
n1_ref = self.graph_db.get_indexed_node('Node', 'node_id', source_node_id)
n2_ref = self.graph_db.get_indexed_node('Node', 'node_id', target_node_id)
# Sanity check
if not n1_ref or not n2_ref:
print 'Cannot add relationship between unfound nodes: %s --> %s' % (source_node_id, target_node_id)
return
path = neo4j.Path(n1_ref, rel, n2_ref)
path.get_or_create(self.graph_db) | [
"def",
"add_rel",
"(",
"self",
",",
"source_node_id",
",",
"target_node_id",
",",
"rel",
")",
":",
"# Add the relationship",
"n1_ref",
"=",
"self",
".",
"graph_db",
".",
"get_indexed_node",
"(",
"'Node'",
",",
"'node_id'",
",",
"source_node_id",
")",
"n2_ref",
... | Add a relationship between nodes.
Args:
source_node_id: Node Id for the source node.
target_node_id: Node Id for the target node.
rel: Name of the relationship 'contains' | [
"Add",
"a",
"relationship",
"between",
"nodes",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/neo_db.py#L55-L73 | train | 43,328 |
SuperCowPowers/workbench | workbench/workers/view_pe.py | ViewPE.execute | def execute(self, input_data):
''' Execute the ViewPE worker '''
# Just a small check to make sure we haven't been called on the wrong file type
if (input_data['meta']['type_tag'] != 'exe'):
return {'error': self.__class__.__name__+': called on '+input_data['meta']['type_tag']}
view = {}
view['indicators'] = list(set([item['category'] for item in input_data['pe_indicators']['indicator_list']]))
view['peid_matches'] = input_data['pe_peid']['match_list']
view['yara_sigs'] = input_data['yara_sigs']['matches'].keys()
view['classification'] = input_data['pe_classifier']['classification']
view['disass'] = self.safe_get(input_data, ['pe_disass', 'decode'])[:15]
view.update(input_data['meta'])
return view | python | def execute(self, input_data):
''' Execute the ViewPE worker '''
# Just a small check to make sure we haven't been called on the wrong file type
if (input_data['meta']['type_tag'] != 'exe'):
return {'error': self.__class__.__name__+': called on '+input_data['meta']['type_tag']}
view = {}
view['indicators'] = list(set([item['category'] for item in input_data['pe_indicators']['indicator_list']]))
view['peid_matches'] = input_data['pe_peid']['match_list']
view['yara_sigs'] = input_data['yara_sigs']['matches'].keys()
view['classification'] = input_data['pe_classifier']['classification']
view['disass'] = self.safe_get(input_data, ['pe_disass', 'decode'])[:15]
view.update(input_data['meta'])
return view | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"# Just a small check to make sure we haven't been called on the wrong file type",
"if",
"(",
"input_data",
"[",
"'meta'",
"]",
"[",
"'type_tag'",
"]",
"!=",
"'exe'",
")",
":",
"return",
"{",
"'error'",
":"... | Execute the ViewPE worker | [
"Execute",
"the",
"ViewPE",
"worker"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/view_pe.py#L9-L24 | train | 43,329 |
SuperCowPowers/workbench | workbench/workers/view_pe.py | ViewPE.safe_get | def safe_get(data, key_list):
''' Safely access dictionary keys when plugin may have failed '''
for key in key_list:
data = data.get(key, {})
return data if data else 'plugin_failed' | python | def safe_get(data, key_list):
''' Safely access dictionary keys when plugin may have failed '''
for key in key_list:
data = data.get(key, {})
return data if data else 'plugin_failed' | [
"def",
"safe_get",
"(",
"data",
",",
"key_list",
")",
":",
"for",
"key",
"in",
"key_list",
":",
"data",
"=",
"data",
".",
"get",
"(",
"key",
",",
"{",
"}",
")",
"return",
"data",
"if",
"data",
"else",
"'plugin_failed'"
] | Safely access dictionary keys when plugin may have failed | [
"Safely",
"access",
"dictionary",
"keys",
"when",
"plugin",
"may",
"have",
"failed"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/view_pe.py#L28-L32 | train | 43,330 |
SuperCowPowers/workbench | workbench/utils/pcap_streamer.py | TCPDumpToWorkbench.execute | def execute(self):
''' Begin capturing PCAPs and sending them to workbench '''
# Create a temporary directory
self.temp_dir = tempfile.mkdtemp()
os.chdir(self.temp_dir)
# Spin up the directory watcher
DirWatcher(self.temp_dir, self.file_created)
# Spin up tcpdump
self.subprocess_manager(self.tcpdump_cmd) | python | def execute(self):
''' Begin capturing PCAPs and sending them to workbench '''
# Create a temporary directory
self.temp_dir = tempfile.mkdtemp()
os.chdir(self.temp_dir)
# Spin up the directory watcher
DirWatcher(self.temp_dir, self.file_created)
# Spin up tcpdump
self.subprocess_manager(self.tcpdump_cmd) | [
"def",
"execute",
"(",
"self",
")",
":",
"# Create a temporary directory",
"self",
".",
"temp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"os",
".",
"chdir",
"(",
"self",
".",
"temp_dir",
")",
"# Spin up the directory watcher",
"DirWatcher",
"(",
"self",
... | Begin capturing PCAPs and sending them to workbench | [
"Begin",
"capturing",
"PCAPs",
"and",
"sending",
"them",
"to",
"workbench"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/utils/pcap_streamer.py#L59-L70 | train | 43,331 |
SuperCowPowers/workbench | workbench/utils/pcap_streamer.py | TCPDumpToWorkbench.file_created | def file_created(self, filepath):
''' File created callback '''
# Send the on-deck pcap to workbench
if self.on_deck:
self.store_file(self.on_deck)
os.remove(self.on_deck)
# Now put the newly created file on-deck
self.on_deck = filepath | python | def file_created(self, filepath):
''' File created callback '''
# Send the on-deck pcap to workbench
if self.on_deck:
self.store_file(self.on_deck)
os.remove(self.on_deck)
# Now put the newly created file on-deck
self.on_deck = filepath | [
"def",
"file_created",
"(",
"self",
",",
"filepath",
")",
":",
"# Send the on-deck pcap to workbench",
"if",
"self",
".",
"on_deck",
":",
"self",
".",
"store_file",
"(",
"self",
".",
"on_deck",
")",
"os",
".",
"remove",
"(",
"self",
".",
"on_deck",
")",
"#... | File created callback | [
"File",
"created",
"callback"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/utils/pcap_streamer.py#L72-L81 | train | 43,332 |
SuperCowPowers/workbench | workbench/utils/pcap_streamer.py | TCPDumpToWorkbench.store_file | def store_file(self, filename):
''' Store a file into workbench '''
# Spin up workbench
self.workbench = zerorpc.Client(timeout=300, heartbeat=60)
self.workbench.connect("tcp://127.0.0.1:4242")
# Open the file and send it to workbench
storage_name = "streaming_pcap" + str(self.pcap_index)
print filename, storage_name
with open(filename,'rb') as f:
self.workbench.store_sample(f.read(), storage_name, 'pcap')
self.pcap_index += 1
# Close workbench client
self.workbench.close() | python | def store_file(self, filename):
''' Store a file into workbench '''
# Spin up workbench
self.workbench = zerorpc.Client(timeout=300, heartbeat=60)
self.workbench.connect("tcp://127.0.0.1:4242")
# Open the file and send it to workbench
storage_name = "streaming_pcap" + str(self.pcap_index)
print filename, storage_name
with open(filename,'rb') as f:
self.workbench.store_sample(f.read(), storage_name, 'pcap')
self.pcap_index += 1
# Close workbench client
self.workbench.close() | [
"def",
"store_file",
"(",
"self",
",",
"filename",
")",
":",
"# Spin up workbench",
"self",
".",
"workbench",
"=",
"zerorpc",
".",
"Client",
"(",
"timeout",
"=",
"300",
",",
"heartbeat",
"=",
"60",
")",
"self",
".",
"workbench",
".",
"connect",
"(",
"\"t... | Store a file into workbench | [
"Store",
"a",
"file",
"into",
"workbench"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/utils/pcap_streamer.py#L83-L98 | train | 43,333 |
SuperCowPowers/workbench | workbench/workers/mem_pslist.py | MemoryImagePSList.parse_eprocess | def parse_eprocess(self, eprocess_data):
"""Parse the EProcess object we get from some rekall output"""
Name = eprocess_data['_EPROCESS']['Cybox']['Name']
PID = eprocess_data['_EPROCESS']['Cybox']['PID']
PPID = eprocess_data['_EPROCESS']['Cybox']['Parent_PID']
return {'Name': Name, 'PID': PID, 'PPID': PPID} | python | def parse_eprocess(self, eprocess_data):
"""Parse the EProcess object we get from some rekall output"""
Name = eprocess_data['_EPROCESS']['Cybox']['Name']
PID = eprocess_data['_EPROCESS']['Cybox']['PID']
PPID = eprocess_data['_EPROCESS']['Cybox']['Parent_PID']
return {'Name': Name, 'PID': PID, 'PPID': PPID} | [
"def",
"parse_eprocess",
"(",
"self",
",",
"eprocess_data",
")",
":",
"Name",
"=",
"eprocess_data",
"[",
"'_EPROCESS'",
"]",
"[",
"'Cybox'",
"]",
"[",
"'Name'",
"]",
"PID",
"=",
"eprocess_data",
"[",
"'_EPROCESS'",
"]",
"[",
"'Cybox'",
"]",
"[",
"'PID'",
... | Parse the EProcess object we get from some rekall output | [
"Parse",
"the",
"EProcess",
"object",
"we",
"get",
"from",
"some",
"rekall",
"output"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/mem_pslist.py#L24-L29 | train | 43,334 |
SuperCowPowers/workbench | workbench/workers/unzip.py | Unzip.execute | def execute(self, input_data):
''' Execute the Unzip worker '''
raw_bytes = input_data['sample']['raw_bytes']
zipfile_output = zipfile.ZipFile(StringIO(raw_bytes))
payload_md5s = []
for name in zipfile_output.namelist():
filename = os.path.basename(name)
payload_md5s.append(self.workbench.store_sample(zipfile_output.read(name), name, 'unknown'))
return {'payload_md5s': payload_md5s} | python | def execute(self, input_data):
''' Execute the Unzip worker '''
raw_bytes = input_data['sample']['raw_bytes']
zipfile_output = zipfile.ZipFile(StringIO(raw_bytes))
payload_md5s = []
for name in zipfile_output.namelist():
filename = os.path.basename(name)
payload_md5s.append(self.workbench.store_sample(zipfile_output.read(name), name, 'unknown'))
return {'payload_md5s': payload_md5s} | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"raw_bytes",
"=",
"input_data",
"[",
"'sample'",
"]",
"[",
"'raw_bytes'",
"]",
"zipfile_output",
"=",
"zipfile",
".",
"ZipFile",
"(",
"StringIO",
"(",
"raw_bytes",
")",
")",
"payload_md5s",
"=",
"... | Execute the Unzip worker | [
"Execute",
"the",
"Unzip",
"worker"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/unzip.py#L20-L28 | train | 43,335 |
SuperCowPowers/workbench | workbench_apps/workbench_cli/help_content.py | WorkbenchShellHelp.help_cli | def help_cli(self):
""" Help on Workbench CLI """
help = '%sWelcome to Workbench CLI Help:%s' % (color.Yellow, color.Normal)
help += '\n\t%s> help cli_basic %s for getting started help' % (color.Green, color.LightBlue)
help += '\n\t%s> help workers %s for help on available workers' % (color.Green, color.LightBlue)
help += '\n\t%s> help search %s for help on searching samples' % (color.Green, color.LightBlue)
help += '\n\t%s> help dataframe %s for help on making dataframes' % (color.Green, color.LightBlue)
help += '\n\t%s> help commands %s for help on workbench commands' % (color.Green, color.LightBlue)
help += '\n\t%s> help topic %s where topic can be a help, command or worker' % (color.Green, color.LightBlue)
help += '\n\n%sNote: cli commands are transformed into python calls' % (color.Yellow)
help += '\n\t%s> help cli_basic --> help("cli_basic")%s' % (color.Green, color.Normal)
return help | python | def help_cli(self):
""" Help on Workbench CLI """
help = '%sWelcome to Workbench CLI Help:%s' % (color.Yellow, color.Normal)
help += '\n\t%s> help cli_basic %s for getting started help' % (color.Green, color.LightBlue)
help += '\n\t%s> help workers %s for help on available workers' % (color.Green, color.LightBlue)
help += '\n\t%s> help search %s for help on searching samples' % (color.Green, color.LightBlue)
help += '\n\t%s> help dataframe %s for help on making dataframes' % (color.Green, color.LightBlue)
help += '\n\t%s> help commands %s for help on workbench commands' % (color.Green, color.LightBlue)
help += '\n\t%s> help topic %s where topic can be a help, command or worker' % (color.Green, color.LightBlue)
help += '\n\n%sNote: cli commands are transformed into python calls' % (color.Yellow)
help += '\n\t%s> help cli_basic --> help("cli_basic")%s' % (color.Green, color.Normal)
return help | [
"def",
"help_cli",
"(",
"self",
")",
":",
"help",
"=",
"'%sWelcome to Workbench CLI Help:%s'",
"%",
"(",
"color",
".",
"Yellow",
",",
"color",
".",
"Normal",
")",
"help",
"+=",
"'\\n\\t%s> help cli_basic %s for getting started help'",
"%",
"(",
"color",
".",
"Gree... | Help on Workbench CLI | [
"Help",
"on",
"Workbench",
"CLI"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/help_content.py#L13-L24 | train | 43,336 |
SuperCowPowers/workbench | workbench_apps/workbench_cli/help_content.py | WorkbenchShellHelp.help_cli_basic | def help_cli_basic(self):
""" Help for Workbench CLI Basics """
help = '%sWorkbench: Getting started...' % (color.Yellow)
help += '\n%sLoad in a sample:' % (color.Green)
help += '\n\t%s> load_sample /path/to/file' % (color.LightBlue)
help += '\n\n%sNotice the prompt now shows the md5 of the sample...'% (color.Yellow)
help += '\n%sRun workers on the sample:' % (color.Green)
help += '\n\t%s> view' % (color.LightBlue)
help += '\n%sType the \'help workers\' or the first part of the worker <tab>...' % (color.Green)
help += '\n\t%s> help workers (lists all possible workers)' % (color.LightBlue)
help += '\n\t%s> pe_<tab> (will give you pe_classifier, pe_deep_sim, pe_features, pe_indicators, pe_peid)%s' % (color.LightBlue, color.Normal)
return help | python | def help_cli_basic(self):
""" Help for Workbench CLI Basics """
help = '%sWorkbench: Getting started...' % (color.Yellow)
help += '\n%sLoad in a sample:' % (color.Green)
help += '\n\t%s> load_sample /path/to/file' % (color.LightBlue)
help += '\n\n%sNotice the prompt now shows the md5 of the sample...'% (color.Yellow)
help += '\n%sRun workers on the sample:' % (color.Green)
help += '\n\t%s> view' % (color.LightBlue)
help += '\n%sType the \'help workers\' or the first part of the worker <tab>...' % (color.Green)
help += '\n\t%s> help workers (lists all possible workers)' % (color.LightBlue)
help += '\n\t%s> pe_<tab> (will give you pe_classifier, pe_deep_sim, pe_features, pe_indicators, pe_peid)%s' % (color.LightBlue, color.Normal)
return help | [
"def",
"help_cli_basic",
"(",
"self",
")",
":",
"help",
"=",
"'%sWorkbench: Getting started...'",
"%",
"(",
"color",
".",
"Yellow",
")",
"help",
"+=",
"'\\n%sLoad in a sample:'",
"%",
"(",
"color",
".",
"Green",
")",
"help",
"+=",
"'\\n\\t%s> load_sample /path/to/... | Help for Workbench CLI Basics | [
"Help",
"for",
"Workbench",
"CLI",
"Basics"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/help_content.py#L26-L37 | train | 43,337 |
SuperCowPowers/workbench | workbench_apps/workbench_cli/help_content.py | WorkbenchShellHelp.help_cli_search | def help_cli_search(self):
""" Help for Workbench CLI Search """
help = '%sSearch: %s returns sample_sets, a sample_set is a set/list of md5s.' % (color.Yellow, color.Green)
help += '\n\n\t%sSearch for all samples in the database that are known bad pe files,' % (color.Green)
help += '\n\t%sthis command returns the sample_set containing the matching items'% (color.Green)
help += '\n\t%s> my_bad_exes = search([\'bad\', \'exe\'])' % (color.LightBlue)
help += '\n\n\t%sRun workers on this sample_set:' % (color.Green)
help += '\n\t%s> pe_outputs = pe_features(my_bad_exes) %s' % (color.LightBlue, color.Normal)
help += '\n\n\t%sLoop on the generator (or make a DataFrame see >help dataframe)' % (color.Green)
help += '\n\t%s> for output in pe_outputs: %s' % (color.LightBlue, color.Normal)
help += '\n\t\t%s print output %s' % (color.LightBlue, color.Normal)
return help | python | def help_cli_search(self):
""" Help for Workbench CLI Search """
help = '%sSearch: %s returns sample_sets, a sample_set is a set/list of md5s.' % (color.Yellow, color.Green)
help += '\n\n\t%sSearch for all samples in the database that are known bad pe files,' % (color.Green)
help += '\n\t%sthis command returns the sample_set containing the matching items'% (color.Green)
help += '\n\t%s> my_bad_exes = search([\'bad\', \'exe\'])' % (color.LightBlue)
help += '\n\n\t%sRun workers on this sample_set:' % (color.Green)
help += '\n\t%s> pe_outputs = pe_features(my_bad_exes) %s' % (color.LightBlue, color.Normal)
help += '\n\n\t%sLoop on the generator (or make a DataFrame see >help dataframe)' % (color.Green)
help += '\n\t%s> for output in pe_outputs: %s' % (color.LightBlue, color.Normal)
help += '\n\t\t%s print output %s' % (color.LightBlue, color.Normal)
return help | [
"def",
"help_cli_search",
"(",
"self",
")",
":",
"help",
"=",
"'%sSearch: %s returns sample_sets, a sample_set is a set/list of md5s.'",
"%",
"(",
"color",
".",
"Yellow",
",",
"color",
".",
"Green",
")",
"help",
"+=",
"'\\n\\n\\t%sSearch for all samples in the database that... | Help for Workbench CLI Search | [
"Help",
"for",
"Workbench",
"CLI",
"Search"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/help_content.py#L39-L50 | train | 43,338 |
SuperCowPowers/workbench | workbench/workers/view_pcap_deep.py | ViewPcapDeep.execute | def execute(self, input_data):
''' ViewPcapDeep execute method '''
# Copy info from input
view = input_data['view_pcap']
# Grab a couple of handles
extracted_files = input_data['view_pcap']['extracted_files']
# Dump a couple of fields
del view['extracted_files']
# Grab additional info about the extracted files
view['extracted_files'] = [self.workbench.work_request('meta_deep', md5,
['md5', 'sha256', 'entropy', 'ssdeep', 'file_size', 'file_type']) for md5 in extracted_files]
return view | python | def execute(self, input_data):
''' ViewPcapDeep execute method '''
# Copy info from input
view = input_data['view_pcap']
# Grab a couple of handles
extracted_files = input_data['view_pcap']['extracted_files']
# Dump a couple of fields
del view['extracted_files']
# Grab additional info about the extracted files
view['extracted_files'] = [self.workbench.work_request('meta_deep', md5,
['md5', 'sha256', 'entropy', 'ssdeep', 'file_size', 'file_type']) for md5 in extracted_files]
return view | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"# Copy info from input",
"view",
"=",
"input_data",
"[",
"'view_pcap'",
"]",
"# Grab a couple of handles",
"extracted_files",
"=",
"input_data",
"[",
"'view_pcap'",
"]",
"[",
"'extracted_files'",
"]",
"# D... | ViewPcapDeep execute method | [
"ViewPcapDeep",
"execute",
"method"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/view_pcap_deep.py#L16-L32 | train | 43,339 |
yfpeng/bioc | bioc/biocjson/decoder.py | parse_collection | def parse_collection(obj: dict) -> BioCCollection:
"""Deserialize a dict obj to a BioCCollection object"""
collection = BioCCollection()
collection.source = obj['source']
collection.date = obj['date']
collection.key = obj['key']
collection.infons = obj['infons']
for doc in obj['documents']:
collection.add_document(parse_doc(doc))
return collection | python | def parse_collection(obj: dict) -> BioCCollection:
"""Deserialize a dict obj to a BioCCollection object"""
collection = BioCCollection()
collection.source = obj['source']
collection.date = obj['date']
collection.key = obj['key']
collection.infons = obj['infons']
for doc in obj['documents']:
collection.add_document(parse_doc(doc))
return collection | [
"def",
"parse_collection",
"(",
"obj",
":",
"dict",
")",
"->",
"BioCCollection",
":",
"collection",
"=",
"BioCCollection",
"(",
")",
"collection",
".",
"source",
"=",
"obj",
"[",
"'source'",
"]",
"collection",
".",
"date",
"=",
"obj",
"[",
"'date'",
"]",
... | Deserialize a dict obj to a BioCCollection object | [
"Deserialize",
"a",
"dict",
"obj",
"to",
"a",
"BioCCollection",
"object"
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocjson/decoder.py#L14-L23 | train | 43,340 |
yfpeng/bioc | bioc/biocjson/decoder.py | parse_annotation | def parse_annotation(obj: dict) -> BioCAnnotation:
"""Deserialize a dict obj to a BioCAnnotation object"""
ann = BioCAnnotation()
ann.id = obj['id']
ann.infons = obj['infons']
ann.text = obj['text']
for loc in obj['locations']:
ann.add_location(BioCLocation(loc['offset'], loc['length']))
return ann | python | def parse_annotation(obj: dict) -> BioCAnnotation:
"""Deserialize a dict obj to a BioCAnnotation object"""
ann = BioCAnnotation()
ann.id = obj['id']
ann.infons = obj['infons']
ann.text = obj['text']
for loc in obj['locations']:
ann.add_location(BioCLocation(loc['offset'], loc['length']))
return ann | [
"def",
"parse_annotation",
"(",
"obj",
":",
"dict",
")",
"->",
"BioCAnnotation",
":",
"ann",
"=",
"BioCAnnotation",
"(",
")",
"ann",
".",
"id",
"=",
"obj",
"[",
"'id'",
"]",
"ann",
".",
"infons",
"=",
"obj",
"[",
"'infons'",
"]",
"ann",
".",
"text",
... | Deserialize a dict obj to a BioCAnnotation object | [
"Deserialize",
"a",
"dict",
"obj",
"to",
"a",
"BioCAnnotation",
"object"
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocjson/decoder.py#L26-L34 | train | 43,341 |
yfpeng/bioc | bioc/biocjson/decoder.py | parse_relation | def parse_relation(obj: dict) -> BioCRelation:
"""Deserialize a dict obj to a BioCRelation object"""
rel = BioCRelation()
rel.id = obj['id']
rel.infons = obj['infons']
for node in obj['nodes']:
rel.add_node(BioCNode(node['refid'], node['role']))
return rel | python | def parse_relation(obj: dict) -> BioCRelation:
"""Deserialize a dict obj to a BioCRelation object"""
rel = BioCRelation()
rel.id = obj['id']
rel.infons = obj['infons']
for node in obj['nodes']:
rel.add_node(BioCNode(node['refid'], node['role']))
return rel | [
"def",
"parse_relation",
"(",
"obj",
":",
"dict",
")",
"->",
"BioCRelation",
":",
"rel",
"=",
"BioCRelation",
"(",
")",
"rel",
".",
"id",
"=",
"obj",
"[",
"'id'",
"]",
"rel",
".",
"infons",
"=",
"obj",
"[",
"'infons'",
"]",
"for",
"node",
"in",
"ob... | Deserialize a dict obj to a BioCRelation object | [
"Deserialize",
"a",
"dict",
"obj",
"to",
"a",
"BioCRelation",
"object"
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocjson/decoder.py#L37-L44 | train | 43,342 |
yfpeng/bioc | bioc/biocjson/decoder.py | parse_sentence | def parse_sentence(obj: dict) -> BioCSentence:
"""Deserialize a dict obj to a BioCSentence object"""
sentence = BioCSentence()
sentence.offset = obj['offset']
sentence.infons = obj['infons']
sentence.text = obj['text']
for annotation in obj['annotations']:
sentence.add_annotation(parse_annotation(annotation))
for relation in obj['relations']:
sentence.add_relation(parse_relation(relation))
return sentence | python | def parse_sentence(obj: dict) -> BioCSentence:
"""Deserialize a dict obj to a BioCSentence object"""
sentence = BioCSentence()
sentence.offset = obj['offset']
sentence.infons = obj['infons']
sentence.text = obj['text']
for annotation in obj['annotations']:
sentence.add_annotation(parse_annotation(annotation))
for relation in obj['relations']:
sentence.add_relation(parse_relation(relation))
return sentence | [
"def",
"parse_sentence",
"(",
"obj",
":",
"dict",
")",
"->",
"BioCSentence",
":",
"sentence",
"=",
"BioCSentence",
"(",
")",
"sentence",
".",
"offset",
"=",
"obj",
"[",
"'offset'",
"]",
"sentence",
".",
"infons",
"=",
"obj",
"[",
"'infons'",
"]",
"senten... | Deserialize a dict obj to a BioCSentence object | [
"Deserialize",
"a",
"dict",
"obj",
"to",
"a",
"BioCSentence",
"object"
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocjson/decoder.py#L47-L57 | train | 43,343 |
yfpeng/bioc | bioc/biocjson/decoder.py | parse_passage | def parse_passage(obj: dict) -> BioCPassage:
"""Deserialize a dict obj to a BioCPassage object"""
passage = BioCPassage()
passage.offset = obj['offset']
passage.infons = obj['infons']
if 'text' in obj:
passage.text = obj['text']
for sentence in obj['sentences']:
passage.add_sentence(parse_sentence(sentence))
for annotation in obj['annotations']:
passage.add_annotation(parse_annotation(annotation))
for relation in obj['relations']:
passage.add_relation(parse_relation(relation))
return passage | python | def parse_passage(obj: dict) -> BioCPassage:
"""Deserialize a dict obj to a BioCPassage object"""
passage = BioCPassage()
passage.offset = obj['offset']
passage.infons = obj['infons']
if 'text' in obj:
passage.text = obj['text']
for sentence in obj['sentences']:
passage.add_sentence(parse_sentence(sentence))
for annotation in obj['annotations']:
passage.add_annotation(parse_annotation(annotation))
for relation in obj['relations']:
passage.add_relation(parse_relation(relation))
return passage | [
"def",
"parse_passage",
"(",
"obj",
":",
"dict",
")",
"->",
"BioCPassage",
":",
"passage",
"=",
"BioCPassage",
"(",
")",
"passage",
".",
"offset",
"=",
"obj",
"[",
"'offset'",
"]",
"passage",
".",
"infons",
"=",
"obj",
"[",
"'infons'",
"]",
"if",
"'tex... | Deserialize a dict obj to a BioCPassage object | [
"Deserialize",
"a",
"dict",
"obj",
"to",
"a",
"BioCPassage",
"object"
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocjson/decoder.py#L60-L73 | train | 43,344 |
yfpeng/bioc | bioc/biocjson/decoder.py | parse_doc | def parse_doc(obj: dict) -> BioCDocument:
"""Deserialize a dict obj to a BioCDocument object"""
doc = BioCDocument()
doc.id = obj['id']
doc.infons = obj['infons']
for passage in obj['passages']:
doc.add_passage(parse_passage(passage))
for annotation in obj['annotations']:
doc.add_annotation(parse_annotation(annotation))
for relation in obj['relations']:
doc.add_relation(parse_relation(relation))
return doc | python | def parse_doc(obj: dict) -> BioCDocument:
"""Deserialize a dict obj to a BioCDocument object"""
doc = BioCDocument()
doc.id = obj['id']
doc.infons = obj['infons']
for passage in obj['passages']:
doc.add_passage(parse_passage(passage))
for annotation in obj['annotations']:
doc.add_annotation(parse_annotation(annotation))
for relation in obj['relations']:
doc.add_relation(parse_relation(relation))
return doc | [
"def",
"parse_doc",
"(",
"obj",
":",
"dict",
")",
"->",
"BioCDocument",
":",
"doc",
"=",
"BioCDocument",
"(",
")",
"doc",
".",
"id",
"=",
"obj",
"[",
"'id'",
"]",
"doc",
".",
"infons",
"=",
"obj",
"[",
"'infons'",
"]",
"for",
"passage",
"in",
"obj"... | Deserialize a dict obj to a BioCDocument object | [
"Deserialize",
"a",
"dict",
"obj",
"to",
"a",
"BioCDocument",
"object"
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocjson/decoder.py#L76-L87 | train | 43,345 |
SuperCowPowers/workbench | workbench/workers/pcap_http_graph.py | PcapHTTPGraph.execute | def execute(self, input_data):
''' Okay this worker is going build graphs from PCAP Bro output logs '''
# Grab the Bro log handles from the input
bro_logs = input_data['pcap_bro']
# Weird log
if 'weird_log' in bro_logs:
stream = self.workbench.stream_sample(bro_logs['weird_log'])
self.weird_log_graph(stream)
# HTTP log
gsleep()
stream = self.workbench.stream_sample(bro_logs['http_log'])
self.http_log_graph(stream)
# Files log
gsleep()
stream = self.workbench.stream_sample(bro_logs['files_log'])
self.files_log_graph(stream)
return {'output':'go to http://localhost:7474/browser and execute this query "match (s:origin), (t:file), p=allShortestPaths((s)--(t)) return p"'} | python | def execute(self, input_data):
''' Okay this worker is going build graphs from PCAP Bro output logs '''
# Grab the Bro log handles from the input
bro_logs = input_data['pcap_bro']
# Weird log
if 'weird_log' in bro_logs:
stream = self.workbench.stream_sample(bro_logs['weird_log'])
self.weird_log_graph(stream)
# HTTP log
gsleep()
stream = self.workbench.stream_sample(bro_logs['http_log'])
self.http_log_graph(stream)
# Files log
gsleep()
stream = self.workbench.stream_sample(bro_logs['files_log'])
self.files_log_graph(stream)
return {'output':'go to http://localhost:7474/browser and execute this query "match (s:origin), (t:file), p=allShortestPaths((s)--(t)) return p"'} | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"# Grab the Bro log handles from the input",
"bro_logs",
"=",
"input_data",
"[",
"'pcap_bro'",
"]",
"# Weird log",
"if",
"'weird_log'",
"in",
"bro_logs",
":",
"stream",
"=",
"self",
".",
"workbench",
".",... | Okay this worker is going build graphs from PCAP Bro output logs | [
"Okay",
"this",
"worker",
"is",
"going",
"build",
"graphs",
"from",
"PCAP",
"Bro",
"output",
"logs"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pcap_http_graph.py#L45-L66 | train | 43,346 |
SuperCowPowers/workbench | workbench/server/dir_watcher.py | DirWatcher.register_callbacks | def register_callbacks(self, on_create, on_modify, on_delete):
""" Register callbacks for file creation, modification, and deletion """
self.on_create = on_create
self.on_modify = on_modify
self.on_delete = on_delete | python | def register_callbacks(self, on_create, on_modify, on_delete):
""" Register callbacks for file creation, modification, and deletion """
self.on_create = on_create
self.on_modify = on_modify
self.on_delete = on_delete | [
"def",
"register_callbacks",
"(",
"self",
",",
"on_create",
",",
"on_modify",
",",
"on_delete",
")",
":",
"self",
".",
"on_create",
"=",
"on_create",
"self",
".",
"on_modify",
"=",
"on_modify",
"self",
".",
"on_delete",
"=",
"on_delete"
] | Register callbacks for file creation, modification, and deletion | [
"Register",
"callbacks",
"for",
"file",
"creation",
"modification",
"and",
"deletion"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/dir_watcher.py#L21-L25 | train | 43,347 |
SuperCowPowers/workbench | workbench/server/dir_watcher.py | DirWatcher._start_monitoring | def _start_monitoring(self):
""" Internal method that monitors the directory for changes """
# Grab all the timestamp info
before = self._file_timestamp_info(self.path)
while True:
gevent.sleep(1)
after = self._file_timestamp_info(self.path)
added = [fname for fname in after.keys() if fname not in before.keys()]
removed = [fname for fname in before.keys() if fname not in after.keys()]
modified = []
for fname in before.keys():
if fname not in removed:
if os.path.getmtime(fname) != before.get(fname):
modified.append(fname)
if added:
self.on_create(added)
if removed:
self.on_delete(removed)
if modified:
self.on_modify(modified)
before = after | python | def _start_monitoring(self):
""" Internal method that monitors the directory for changes """
# Grab all the timestamp info
before = self._file_timestamp_info(self.path)
while True:
gevent.sleep(1)
after = self._file_timestamp_info(self.path)
added = [fname for fname in after.keys() if fname not in before.keys()]
removed = [fname for fname in before.keys() if fname not in after.keys()]
modified = []
for fname in before.keys():
if fname not in removed:
if os.path.getmtime(fname) != before.get(fname):
modified.append(fname)
if added:
self.on_create(added)
if removed:
self.on_delete(removed)
if modified:
self.on_modify(modified)
before = after | [
"def",
"_start_monitoring",
"(",
"self",
")",
":",
"# Grab all the timestamp info",
"before",
"=",
"self",
".",
"_file_timestamp_info",
"(",
"self",
".",
"path",
")",
"while",
"True",
":",
"gevent",
".",
"sleep",
"(",
"1",
")",
"after",
"=",
"self",
".",
"... | Internal method that monitors the directory for changes | [
"Internal",
"method",
"that",
"monitors",
"the",
"directory",
"for",
"changes"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/dir_watcher.py#L31-L57 | train | 43,348 |
SuperCowPowers/workbench | workbench/server/dir_watcher.py | DirWatcher._file_timestamp_info | def _file_timestamp_info(self, path):
""" Grab all the timestamps for the files in the directory """
files = [os.path.join(path, fname) for fname in os.listdir(path) if '.py' in fname]
return dict ([(fname, os.path.getmtime(fname)) for fname in files]) | python | def _file_timestamp_info(self, path):
""" Grab all the timestamps for the files in the directory """
files = [os.path.join(path, fname) for fname in os.listdir(path) if '.py' in fname]
return dict ([(fname, os.path.getmtime(fname)) for fname in files]) | [
"def",
"_file_timestamp_info",
"(",
"self",
",",
"path",
")",
":",
"files",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"fname",
")",
"for",
"fname",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
"if",
"'.py'",
"in",
"fname",
"]",
... | Grab all the timestamps for the files in the directory | [
"Grab",
"all",
"the",
"timestamps",
"for",
"the",
"files",
"in",
"the",
"directory"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/dir_watcher.py#L59-L62 | train | 43,349 |
SuperCowPowers/workbench | workbench/workers/timeout_corner/yara_sigs.py | YaraSigs.execute | def execute(self, input_data):
''' yara worker execute method '''
raw_bytes = input_data['sample']['raw_bytes']
matches = self.rules.match_data(raw_bytes)
# The matches data is organized in the following way
# {'filename1': [match_list], 'filename2': [match_list]}
# match_list = list of match
# match = {'meta':{'description':'blah}, tags=[], matches:True,
# strings:[string_list]}
# string = {'flags':blah, 'identifier':'$', 'data': FindWindow, 'offset'}
#
# So we're going to flatten a bit (shrug)
# {filename_match_meta_description: string_list}
flat_data = collections.defaultdict(list)
for filename, match_list in matches.iteritems():
for match in match_list:
if 'description' in match['meta']:
new_tag = filename+'_'+match['meta']['description']
else:
new_tag = filename+'_'+match['rule']
for match in match['strings']:
flat_data[new_tag].append(match['data'])
# Remove duplicates
flat_data[new_tag] = list(set(flat_data[new_tag]))
return {'matches': flat_data} | python | def execute(self, input_data):
''' yara worker execute method '''
raw_bytes = input_data['sample']['raw_bytes']
matches = self.rules.match_data(raw_bytes)
# The matches data is organized in the following way
# {'filename1': [match_list], 'filename2': [match_list]}
# match_list = list of match
# match = {'meta':{'description':'blah}, tags=[], matches:True,
# strings:[string_list]}
# string = {'flags':blah, 'identifier':'$', 'data': FindWindow, 'offset'}
#
# So we're going to flatten a bit (shrug)
# {filename_match_meta_description: string_list}
flat_data = collections.defaultdict(list)
for filename, match_list in matches.iteritems():
for match in match_list:
if 'description' in match['meta']:
new_tag = filename+'_'+match['meta']['description']
else:
new_tag = filename+'_'+match['rule']
for match in match['strings']:
flat_data[new_tag].append(match['data'])
# Remove duplicates
flat_data[new_tag] = list(set(flat_data[new_tag]))
return {'matches': flat_data} | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"raw_bytes",
"=",
"input_data",
"[",
"'sample'",
"]",
"[",
"'raw_bytes'",
"]",
"matches",
"=",
"self",
".",
"rules",
".",
"match_data",
"(",
"raw_bytes",
")",
"# The matches data is organized in the fol... | yara worker execute method | [
"yara",
"worker",
"execute",
"method"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/timeout_corner/yara_sigs.py#L69-L95 | train | 43,350 |
SuperCowPowers/workbench | workbench/clients/upload_file_chunks.py | chunks | def chunks(data, chunk_size):
""" Yield chunk_size chunks from data."""
for i in xrange(0, len(data), chunk_size):
yield data[i:i+chunk_size] | python | def chunks(data, chunk_size):
""" Yield chunk_size chunks from data."""
for i in xrange(0, len(data), chunk_size):
yield data[i:i+chunk_size] | [
"def",
"chunks",
"(",
"data",
",",
"chunk_size",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"data",
")",
",",
"chunk_size",
")",
":",
"yield",
"data",
"[",
"i",
":",
"i",
"+",
"chunk_size",
"]"
] | Yield chunk_size chunks from data. | [
"Yield",
"chunk_size",
"chunks",
"from",
"data",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/upload_file_chunks.py#L9-L12 | train | 43,351 |
SuperCowPowers/workbench | workbench/workers/pcap_bro.py | PcapBro.setup_pcap_inputs | def setup_pcap_inputs(self, input_data):
''' Write the PCAPs to disk for Bro to process and return the pcap filenames '''
# Setup the pcap in the input data for processing by Bro. The input
# may be either an individual sample or a sample set.
file_list = []
if 'sample' in input_data:
raw_bytes = input_data['sample']['raw_bytes']
filename = os.path.basename(input_data['sample']['filename'])
file_list.append({'filename': filename, 'bytes': raw_bytes})
else:
for md5 in input_data['sample_set']['md5_list']:
sample = self.workbench.get_sample(md5)['sample']
raw_bytes = sample['raw_bytes']
filename = os.path.basename(sample['filename'])
file_list.append({'filename': filename, 'bytes': raw_bytes})
# Write the pcaps to disk and keep the filenames for Bro to process
for file_info in file_list:
with open(file_info['filename'], 'wb') as pcap_file:
pcap_file.write(file_info['bytes'])
# Return filenames
return [file_info['filename'] for file_info in file_list] | python | def setup_pcap_inputs(self, input_data):
''' Write the PCAPs to disk for Bro to process and return the pcap filenames '''
# Setup the pcap in the input data for processing by Bro. The input
# may be either an individual sample or a sample set.
file_list = []
if 'sample' in input_data:
raw_bytes = input_data['sample']['raw_bytes']
filename = os.path.basename(input_data['sample']['filename'])
file_list.append({'filename': filename, 'bytes': raw_bytes})
else:
for md5 in input_data['sample_set']['md5_list']:
sample = self.workbench.get_sample(md5)['sample']
raw_bytes = sample['raw_bytes']
filename = os.path.basename(sample['filename'])
file_list.append({'filename': filename, 'bytes': raw_bytes})
# Write the pcaps to disk and keep the filenames for Bro to process
for file_info in file_list:
with open(file_info['filename'], 'wb') as pcap_file:
pcap_file.write(file_info['bytes'])
# Return filenames
return [file_info['filename'] for file_info in file_list] | [
"def",
"setup_pcap_inputs",
"(",
"self",
",",
"input_data",
")",
":",
"# Setup the pcap in the input data for processing by Bro. The input",
"# may be either an individual sample or a sample set.",
"file_list",
"=",
"[",
"]",
"if",
"'sample'",
"in",
"input_data",
":",
"raw_byte... | Write the PCAPs to disk for Bro to process and return the pcap filenames | [
"Write",
"the",
"PCAPs",
"to",
"disk",
"for",
"Bro",
"to",
"process",
"and",
"return",
"the",
"pcap",
"filenames"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pcap_bro.py#L29-L52 | train | 43,352 |
SuperCowPowers/workbench | workbench/workers/pcap_bro.py | PcapBro.subprocess_manager | def subprocess_manager(self, exec_args):
''' Bro subprocess manager '''
try:
sp = gevent.subprocess.Popen(exec_args, stdout=gevent.subprocess.PIPE, stderr=gevent.subprocess.PIPE)
except OSError:
raise RuntimeError('Could not run bro executable (either not installed or not in path): %s' % (exec_args))
out, err = sp.communicate()
if out:
print 'standard output of subprocess: %s' % out
if err:
raise RuntimeError('%s\npcap_bro had output on stderr: %s' % (exec_args, err))
if sp.returncode:
raise RuntimeError('%s\npcap_bro had returncode: %d' % (exec_args, sp.returncode)) | python | def subprocess_manager(self, exec_args):
''' Bro subprocess manager '''
try:
sp = gevent.subprocess.Popen(exec_args, stdout=gevent.subprocess.PIPE, stderr=gevent.subprocess.PIPE)
except OSError:
raise RuntimeError('Could not run bro executable (either not installed or not in path): %s' % (exec_args))
out, err = sp.communicate()
if out:
print 'standard output of subprocess: %s' % out
if err:
raise RuntimeError('%s\npcap_bro had output on stderr: %s' % (exec_args, err))
if sp.returncode:
raise RuntimeError('%s\npcap_bro had returncode: %d' % (exec_args, sp.returncode)) | [
"def",
"subprocess_manager",
"(",
"self",
",",
"exec_args",
")",
":",
"try",
":",
"sp",
"=",
"gevent",
".",
"subprocess",
".",
"Popen",
"(",
"exec_args",
",",
"stdout",
"=",
"gevent",
".",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"gevent",
".",
"... | Bro subprocess manager | [
"Bro",
"subprocess",
"manager"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pcap_bro.py#L113-L125 | train | 43,353 |
mfcloud/python-zvm-sdk | smtLayer/getVM.py | getDirectory | def getDirectory(rh):
"""
Get the virtual machine's directory statements.
Input:
Request Handle with the following properties:
function - 'CMDVM'
subfunction - 'CMD'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter getVM.getDirectory")
parms = ["-T", rh.userid]
results = invokeSMCLI(rh, "Image_Query_DM", parms)
if results['overallRC'] == 0:
results['response'] = re.sub('\*DVHOPT.*', '', results['response'])
rh.printLn("N", results['response'])
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit getVM.getDirectory, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def getDirectory(rh):
"""
Get the virtual machine's directory statements.
Input:
Request Handle with the following properties:
function - 'CMDVM'
subfunction - 'CMD'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter getVM.getDirectory")
parms = ["-T", rh.userid]
results = invokeSMCLI(rh, "Image_Query_DM", parms)
if results['overallRC'] == 0:
results['response'] = re.sub('\*DVHOPT.*', '', results['response'])
rh.printLn("N", results['response'])
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit getVM.getDirectory, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"getDirectory",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter getVM.getDirectory\"",
")",
"parms",
"=",
"[",
"\"-T\"",
",",
"rh",
".",
"userid",
"]",
"results",
"=",
"invokeSMCLI",
"(",
"rh",
",",
"\"Image_Query_DM\"",
",",
"parms",
"... | Get the virtual machine's directory statements.
Input:
Request Handle with the following properties:
function - 'CMDVM'
subfunction - 'CMD'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Get",
"the",
"virtual",
"machine",
"s",
"directory",
"statements",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/getVM.py#L286-L314 | train | 43,354 |
mfcloud/python-zvm-sdk | smtLayer/getVM.py | getStatus | def getStatus(rh):
"""
Get the basic status of a virtual machine.
Input:
Request Handle with the following properties:
function - 'CMDVM'
subfunction - 'CMD'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter getVM.getStatus, userid: " + rh.userid)
results = isLoggedOn(rh, rh.userid)
if results['rc'] != 0:
# Uhoh, can't determine if guest is logged on or not
rh.updateResults(results)
rh.printSysLog("Exit getVM.getStatus, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC']
if results['rs'] == 1:
# Guest is logged off, everything is 0
powerStr = "Power state: off"
memStr = "Total Memory: 0M"
usedMemStr = "Used Memory: 0M"
procStr = "Processors: 0"
timeStr = "CPU Used Time: 0 sec"
else:
powerStr = "Power state: on"
if 'power' in rh.parms:
# Test here to see if we only need power state
# Then we can return early
rh.printLn("N", powerStr)
rh.updateResults(results)
rh.printSysLog("Exit getVM.getStatus, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC']
if results['rs'] != 1:
# Guest is logged on, go get more info
results = getPerfInfo(rh, rh.userid)
if results['overallRC'] != 0:
# Something went wrong in subroutine, exit
rh.updateResults(results)
rh.printSysLog("Exit getVM.getStatus, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC']
else:
# Everything went well, response should be good
memStr = results['response'].split("\n")[0]
usedMemStr = results['response'].split("\n")[1]
procStr = results['response'].split("\n")[2]
timeStr = results['response'].split("\n")[3]
# Build our output string according
# to what information was asked for
if 'memory' in rh.parms:
outStr = memStr + "\n" + usedMemStr
elif 'cpu' in rh.parms:
outStr = procStr + "\n" + timeStr
else:
# Default to all
outStr = powerStr + "\n" + memStr + "\n" + usedMemStr
outStr += "\n" + procStr + "\n" + timeStr
rh.printLn("N", outStr)
rh.printSysLog("Exit getVM.getStatus, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def getStatus(rh):
"""
Get the basic status of a virtual machine.
Input:
Request Handle with the following properties:
function - 'CMDVM'
subfunction - 'CMD'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter getVM.getStatus, userid: " + rh.userid)
results = isLoggedOn(rh, rh.userid)
if results['rc'] != 0:
# Uhoh, can't determine if guest is logged on or not
rh.updateResults(results)
rh.printSysLog("Exit getVM.getStatus, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC']
if results['rs'] == 1:
# Guest is logged off, everything is 0
powerStr = "Power state: off"
memStr = "Total Memory: 0M"
usedMemStr = "Used Memory: 0M"
procStr = "Processors: 0"
timeStr = "CPU Used Time: 0 sec"
else:
powerStr = "Power state: on"
if 'power' in rh.parms:
# Test here to see if we only need power state
# Then we can return early
rh.printLn("N", powerStr)
rh.updateResults(results)
rh.printSysLog("Exit getVM.getStatus, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC']
if results['rs'] != 1:
# Guest is logged on, go get more info
results = getPerfInfo(rh, rh.userid)
if results['overallRC'] != 0:
# Something went wrong in subroutine, exit
rh.updateResults(results)
rh.printSysLog("Exit getVM.getStatus, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC']
else:
# Everything went well, response should be good
memStr = results['response'].split("\n")[0]
usedMemStr = results['response'].split("\n")[1]
procStr = results['response'].split("\n")[2]
timeStr = results['response'].split("\n")[3]
# Build our output string according
# to what information was asked for
if 'memory' in rh.parms:
outStr = memStr + "\n" + usedMemStr
elif 'cpu' in rh.parms:
outStr = procStr + "\n" + timeStr
else:
# Default to all
outStr = powerStr + "\n" + memStr + "\n" + usedMemStr
outStr += "\n" + procStr + "\n" + timeStr
rh.printLn("N", outStr)
rh.printSysLog("Exit getVM.getStatus, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"getStatus",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter getVM.getStatus, userid: \"",
"+",
"rh",
".",
"userid",
")",
"results",
"=",
"isLoggedOn",
"(",
"rh",
",",
"rh",
".",
"userid",
")",
"if",
"results",
"[",
"'rc'",
"]",
"!=",... | Get the basic status of a virtual machine.
Input:
Request Handle with the following properties:
function - 'CMDVM'
subfunction - 'CMD'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Get",
"the",
"basic",
"status",
"of",
"a",
"virtual",
"machine",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/getVM.py#L317-L392 | train | 43,355 |
mfcloud/python-zvm-sdk | smtLayer/getVM.py | fcpinfo | def fcpinfo(rh):
"""
Get fcp info and filter by the status.
Input:
Request Handle with the following properties:
function - 'GETVM'
subfunction - 'FCPINFO'
userid - userid of the virtual machine
parms['status'] - The status for filter results.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.dedicate")
parms = ["-T", rh.userid]
hideList = []
results = invokeSMCLI(rh,
"System_WWPN_Query",
parms,
hideInLog=hideList)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if results['overallRC'] == 0:
# extract data from smcli return
ret = extract_fcp_data(results['response'], rh.parms['status'])
# write the ret into results['response']
rh.printLn("N", ret)
else:
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
return rh.results['overallRC'] | python | def fcpinfo(rh):
"""
Get fcp info and filter by the status.
Input:
Request Handle with the following properties:
function - 'GETVM'
subfunction - 'FCPINFO'
userid - userid of the virtual machine
parms['status'] - The status for filter results.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.dedicate")
parms = ["-T", rh.userid]
hideList = []
results = invokeSMCLI(rh,
"System_WWPN_Query",
parms,
hideInLog=hideList)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if results['overallRC'] == 0:
# extract data from smcli return
ret = extract_fcp_data(results['response'], rh.parms['status'])
# write the ret into results['response']
rh.printLn("N", ret)
else:
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
return rh.results['overallRC'] | [
"def",
"fcpinfo",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter changeVM.dedicate\"",
")",
"parms",
"=",
"[",
"\"-T\"",
",",
"rh",
".",
"userid",
"]",
"hideList",
"=",
"[",
"]",
"results",
"=",
"invokeSMCLI",
"(",
"rh",
",",
"\"System_WWPN... | Get fcp info and filter by the status.
Input:
Request Handle with the following properties:
function - 'GETVM'
subfunction - 'FCPINFO'
userid - userid of the virtual machine
parms['status'] - The status for filter results.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Get",
"fcp",
"info",
"and",
"filter",
"by",
"the",
"status",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/getVM.py#L579-L618 | train | 43,356 |
Chilipp/psyplot | psyplot/data.py | _get_variable_names | def _get_variable_names(arr):
"""Return the variable names of an array"""
if VARIABLELABEL in arr.dims:
return arr.coords[VARIABLELABEL].tolist()
else:
return arr.name | python | def _get_variable_names(arr):
"""Return the variable names of an array"""
if VARIABLELABEL in arr.dims:
return arr.coords[VARIABLELABEL].tolist()
else:
return arr.name | [
"def",
"_get_variable_names",
"(",
"arr",
")",
":",
"if",
"VARIABLELABEL",
"in",
"arr",
".",
"dims",
":",
"return",
"arr",
".",
"coords",
"[",
"VARIABLELABEL",
"]",
".",
"tolist",
"(",
")",
"else",
":",
"return",
"arr",
".",
"name"
] | Return the variable names of an array | [
"Return",
"the",
"variable",
"names",
"of",
"an",
"array"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L91-L96 | train | 43,357 |
Chilipp/psyplot | psyplot/data.py | setup_coords | def setup_coords(arr_names=None, sort=[], dims={}, **kwargs):
"""
Sets up the arr_names dictionary for the plot
Parameters
----------
arr_names: string, list of strings or dictionary
Set the unique array names of the resulting arrays and (optionally)
dimensions.
- if string: same as list of strings (see below). Strings may
include {0} which will be replaced by a counter.
- list of strings: those will be used for the array names. The final
number of dictionaries in the return depend in this case on the
`dims` and ``**furtherdims``
- dictionary:
Then nothing happens and an :class:`OrderedDict` version of
`arr_names` is returned.
sort: list of strings
This parameter defines how the dictionaries are ordered. It has no
effect if `arr_names` is a dictionary (use a
:class:`~collections.OrderedDict` for that). It can be a list of
dimension strings matching to the dimensions in `dims` for the
variable.
dims: dict
Keys must be variable names of dimensions (e.g. time, level, lat or
lon) or 'name' for the variable name you want to choose.
Values must be values of that dimension or iterables of the values
(e.g. lists). Note that strings will be put into a list.
For example dims = {'name': 't2m', 'time': 0} will result in one plot
for the first time step, whereas dims = {'name': 't2m', 'time': [0, 1]}
will result in two plots, one for the first (time == 0) and one for the
second (time == 1) time step.
``**kwargs``
The same as `dims` (those will update what is specified in `dims`)
Returns
-------
~collections.OrderedDict
A mapping from the keys in `arr_names` and to dictionaries. Each
dictionary corresponds defines the coordinates of one data array to
load"""
try:
return OrderedDict(arr_names)
except (ValueError, TypeError):
# ValueError for cyordereddict, TypeError for collections.OrderedDict
pass
if arr_names is None:
arr_names = repeat('arr{0}')
elif isstring(arr_names):
arr_names = repeat(arr_names)
dims = OrderedDict(dims)
for key, val in six.iteritems(kwargs):
dims.setdefault(key, val)
sorted_dims = OrderedDict()
if sort:
for key in sort:
sorted_dims[key] = dims.pop(key)
for key, val in six.iteritems(dims):
sorted_dims[key] = val
else:
# make sure, it is first sorted for the variable names
if 'name' in dims:
sorted_dims['name'] = None
for key, val in sorted(dims.items()):
sorted_dims[key] = val
for key, val in six.iteritems(kwargs):
sorted_dims.setdefault(key, val)
for key, val in six.iteritems(sorted_dims):
sorted_dims[key] = iter(safe_list(val))
return OrderedDict([
(arr_name.format(i), dict(zip(sorted_dims.keys(), dim_tuple)))
for i, (arr_name, dim_tuple) in enumerate(zip(
arr_names, product(
*map(list, sorted_dims.values()))))]) | python | def setup_coords(arr_names=None, sort=[], dims={}, **kwargs):
"""
Sets up the arr_names dictionary for the plot
Parameters
----------
arr_names: string, list of strings or dictionary
Set the unique array names of the resulting arrays and (optionally)
dimensions.
- if string: same as list of strings (see below). Strings may
include {0} which will be replaced by a counter.
- list of strings: those will be used for the array names. The final
number of dictionaries in the return depend in this case on the
`dims` and ``**furtherdims``
- dictionary:
Then nothing happens and an :class:`OrderedDict` version of
`arr_names` is returned.
sort: list of strings
This parameter defines how the dictionaries are ordered. It has no
effect if `arr_names` is a dictionary (use a
:class:`~collections.OrderedDict` for that). It can be a list of
dimension strings matching to the dimensions in `dims` for the
variable.
dims: dict
Keys must be variable names of dimensions (e.g. time, level, lat or
lon) or 'name' for the variable name you want to choose.
Values must be values of that dimension or iterables of the values
(e.g. lists). Note that strings will be put into a list.
For example dims = {'name': 't2m', 'time': 0} will result in one plot
for the first time step, whereas dims = {'name': 't2m', 'time': [0, 1]}
will result in two plots, one for the first (time == 0) and one for the
second (time == 1) time step.
``**kwargs``
The same as `dims` (those will update what is specified in `dims`)
Returns
-------
~collections.OrderedDict
A mapping from the keys in `arr_names` and to dictionaries. Each
dictionary corresponds defines the coordinates of one data array to
load"""
try:
return OrderedDict(arr_names)
except (ValueError, TypeError):
# ValueError for cyordereddict, TypeError for collections.OrderedDict
pass
if arr_names is None:
arr_names = repeat('arr{0}')
elif isstring(arr_names):
arr_names = repeat(arr_names)
dims = OrderedDict(dims)
for key, val in six.iteritems(kwargs):
dims.setdefault(key, val)
sorted_dims = OrderedDict()
if sort:
for key in sort:
sorted_dims[key] = dims.pop(key)
for key, val in six.iteritems(dims):
sorted_dims[key] = val
else:
# make sure, it is first sorted for the variable names
if 'name' in dims:
sorted_dims['name'] = None
for key, val in sorted(dims.items()):
sorted_dims[key] = val
for key, val in six.iteritems(kwargs):
sorted_dims.setdefault(key, val)
for key, val in six.iteritems(sorted_dims):
sorted_dims[key] = iter(safe_list(val))
return OrderedDict([
(arr_name.format(i), dict(zip(sorted_dims.keys(), dim_tuple)))
for i, (arr_name, dim_tuple) in enumerate(zip(
arr_names, product(
*map(list, sorted_dims.values()))))]) | [
"def",
"setup_coords",
"(",
"arr_names",
"=",
"None",
",",
"sort",
"=",
"[",
"]",
",",
"dims",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"OrderedDict",
"(",
"arr_names",
")",
"except",
"(",
"ValueError",
",",
"TypeError"... | Sets up the arr_names dictionary for the plot
Parameters
----------
arr_names: string, list of strings or dictionary
Set the unique array names of the resulting arrays and (optionally)
dimensions.
- if string: same as list of strings (see below). Strings may
include {0} which will be replaced by a counter.
- list of strings: those will be used for the array names. The final
number of dictionaries in the return depend in this case on the
`dims` and ``**furtherdims``
- dictionary:
Then nothing happens and an :class:`OrderedDict` version of
`arr_names` is returned.
sort: list of strings
This parameter defines how the dictionaries are ordered. It has no
effect if `arr_names` is a dictionary (use a
:class:`~collections.OrderedDict` for that). It can be a list of
dimension strings matching to the dimensions in `dims` for the
variable.
dims: dict
Keys must be variable names of dimensions (e.g. time, level, lat or
lon) or 'name' for the variable name you want to choose.
Values must be values of that dimension or iterables of the values
(e.g. lists). Note that strings will be put into a list.
For example dims = {'name': 't2m', 'time': 0} will result in one plot
for the first time step, whereas dims = {'name': 't2m', 'time': [0, 1]}
will result in two plots, one for the first (time == 0) and one for the
second (time == 1) time step.
``**kwargs``
The same as `dims` (those will update what is specified in `dims`)
Returns
-------
~collections.OrderedDict
A mapping from the keys in `arr_names` and to dictionaries. Each
dictionary corresponds defines the coordinates of one data array to
load | [
"Sets",
"up",
"the",
"arr_names",
"dictionary",
"for",
"the",
"plot"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L113-L187 | train | 43,358 |
Chilipp/psyplot | psyplot/data.py | to_slice | def to_slice(arr):
"""Test whether `arr` is an integer array that can be replaced by a slice
Parameters
----------
arr: numpy.array
Numpy integer array
Returns
-------
slice or None
If `arr` could be converted to an array, this is returned, otherwise
`None` is returned
See Also
--------
get_index_from_coord"""
if isinstance(arr, slice):
return arr
if len(arr) == 1:
return slice(arr[0], arr[0] + 1)
step = np.unique(arr[1:] - arr[:-1])
if len(step) == 1:
return slice(arr[0], arr[-1] + step[0], step[0]) | python | def to_slice(arr):
"""Test whether `arr` is an integer array that can be replaced by a slice
Parameters
----------
arr: numpy.array
Numpy integer array
Returns
-------
slice or None
If `arr` could be converted to an array, this is returned, otherwise
`None` is returned
See Also
--------
get_index_from_coord"""
if isinstance(arr, slice):
return arr
if len(arr) == 1:
return slice(arr[0], arr[0] + 1)
step = np.unique(arr[1:] - arr[:-1])
if len(step) == 1:
return slice(arr[0], arr[-1] + step[0], step[0]) | [
"def",
"to_slice",
"(",
"arr",
")",
":",
"if",
"isinstance",
"(",
"arr",
",",
"slice",
")",
":",
"return",
"arr",
"if",
"len",
"(",
"arr",
")",
"==",
"1",
":",
"return",
"slice",
"(",
"arr",
"[",
"0",
"]",
",",
"arr",
"[",
"0",
"]",
"+",
"1",... | Test whether `arr` is an integer array that can be replaced by a slice
Parameters
----------
arr: numpy.array
Numpy integer array
Returns
-------
slice or None
If `arr` could be converted to an array, this is returned, otherwise
`None` is returned
See Also
--------
get_index_from_coord | [
"Test",
"whether",
"arr",
"is",
"an",
"integer",
"array",
"that",
"can",
"be",
"replaced",
"by",
"a",
"slice"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L190-L213 | train | 43,359 |
Chilipp/psyplot | psyplot/data.py | get_index_from_coord | def get_index_from_coord(coord, base_index):
"""Function to return the coordinate as integer, integer array or slice
If `coord` is zero-dimensional, the corresponding integer in `base_index`
will be supplied. Otherwise it is first tried to return a slice, if that
does not work an integer array with the corresponding indices is returned.
Parameters
----------
coord: xarray.Coordinate or xarray.Variable
Coordinate to convert
base_index: pandas.Index
The base index from which the `coord` was extracted
Returns
-------
int, array of ints or slice
The indexer that can be used to access the `coord` in the
`base_index`
"""
try:
values = coord.values
except AttributeError:
values = coord
if values.ndim == 0:
return base_index.get_loc(values[()])
if len(values) == len(base_index) and (values == base_index).all():
return slice(None)
values = np.array(list(map(lambda i: base_index.get_loc(i), values)))
return to_slice(values) or values | python | def get_index_from_coord(coord, base_index):
"""Function to return the coordinate as integer, integer array or slice
If `coord` is zero-dimensional, the corresponding integer in `base_index`
will be supplied. Otherwise it is first tried to return a slice, if that
does not work an integer array with the corresponding indices is returned.
Parameters
----------
coord: xarray.Coordinate or xarray.Variable
Coordinate to convert
base_index: pandas.Index
The base index from which the `coord` was extracted
Returns
-------
int, array of ints or slice
The indexer that can be used to access the `coord` in the
`base_index`
"""
try:
values = coord.values
except AttributeError:
values = coord
if values.ndim == 0:
return base_index.get_loc(values[()])
if len(values) == len(base_index) and (values == base_index).all():
return slice(None)
values = np.array(list(map(lambda i: base_index.get_loc(i), values)))
return to_slice(values) or values | [
"def",
"get_index_from_coord",
"(",
"coord",
",",
"base_index",
")",
":",
"try",
":",
"values",
"=",
"coord",
".",
"values",
"except",
"AttributeError",
":",
"values",
"=",
"coord",
"if",
"values",
".",
"ndim",
"==",
"0",
":",
"return",
"base_index",
".",
... | Function to return the coordinate as integer, integer array or slice
If `coord` is zero-dimensional, the corresponding integer in `base_index`
will be supplied. Otherwise it is first tried to return a slice, if that
does not work an integer array with the corresponding indices is returned.
Parameters
----------
coord: xarray.Coordinate or xarray.Variable
Coordinate to convert
base_index: pandas.Index
The base index from which the `coord` was extracted
Returns
-------
int, array of ints or slice
The indexer that can be used to access the `coord` in the
`base_index` | [
"Function",
"to",
"return",
"the",
"coordinate",
"as",
"integer",
"integer",
"array",
"or",
"slice"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L216-L245 | train | 43,360 |
Chilipp/psyplot | psyplot/data.py | get_tdata | def get_tdata(t_format, files):
"""
Get the time information from file names
Parameters
----------
t_format: str
The string that can be used to get the time information in the files.
Any numeric datetime format string (e.g. %Y, %m, %H) can be used, but
not non-numeric strings like %b, etc. See [1]_ for the datetime format
strings
files: list of str
The that contain the time informations
Returns
-------
pandas.Index
The time coordinate
list of str
The file names as they are sorten in the returned index
References
----------
.. [1] https://docs.python.org/2/library/datetime.html"""
def median(arr):
return arr.min() + (arr.max() - arr.min())/2
import re
from pandas import Index
t_pattern = t_format
for fmt, patt in t_patterns.items():
t_pattern = t_pattern.replace(fmt, patt)
t_pattern = re.compile(t_pattern)
time = list(range(len(files)))
for i, f in enumerate(files):
time[i] = median(np.array(list(map(
lambda s: np.datetime64(dt.datetime.strptime(s, t_format)),
t_pattern.findall(f)))))
ind = np.argsort(time) # sort according to time
files = np.array(files)[ind]
time = np.array(time)[ind]
return to_datetime(Index(time, name='time')), files | python | def get_tdata(t_format, files):
"""
Get the time information from file names
Parameters
----------
t_format: str
The string that can be used to get the time information in the files.
Any numeric datetime format string (e.g. %Y, %m, %H) can be used, but
not non-numeric strings like %b, etc. See [1]_ for the datetime format
strings
files: list of str
The that contain the time informations
Returns
-------
pandas.Index
The time coordinate
list of str
The file names as they are sorten in the returned index
References
----------
.. [1] https://docs.python.org/2/library/datetime.html"""
def median(arr):
return arr.min() + (arr.max() - arr.min())/2
import re
from pandas import Index
t_pattern = t_format
for fmt, patt in t_patterns.items():
t_pattern = t_pattern.replace(fmt, patt)
t_pattern = re.compile(t_pattern)
time = list(range(len(files)))
for i, f in enumerate(files):
time[i] = median(np.array(list(map(
lambda s: np.datetime64(dt.datetime.strptime(s, t_format)),
t_pattern.findall(f)))))
ind = np.argsort(time) # sort according to time
files = np.array(files)[ind]
time = np.array(time)[ind]
return to_datetime(Index(time, name='time')), files | [
"def",
"get_tdata",
"(",
"t_format",
",",
"files",
")",
":",
"def",
"median",
"(",
"arr",
")",
":",
"return",
"arr",
".",
"min",
"(",
")",
"+",
"(",
"arr",
".",
"max",
"(",
")",
"-",
"arr",
".",
"min",
"(",
")",
")",
"/",
"2",
"import",
"re",... | Get the time information from file names
Parameters
----------
t_format: str
The string that can be used to get the time information in the files.
Any numeric datetime format string (e.g. %Y, %m, %H) can be used, but
not non-numeric strings like %b, etc. See [1]_ for the datetime format
strings
files: list of str
The that contain the time informations
Returns
-------
pandas.Index
The time coordinate
list of str
The file names as they are sorten in the returned index
References
----------
.. [1] https://docs.python.org/2/library/datetime.html | [
"Get",
"the",
"time",
"information",
"from",
"file",
"names"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L261-L301 | train | 43,361 |
Chilipp/psyplot | psyplot/data.py | to_netcdf | def to_netcdf(ds, *args, **kwargs):
"""
Store the given dataset as a netCDF file
This functions works essentially the same as the usual
:meth:`xarray.Dataset.to_netcdf` method but can also encode absolute time
units
Parameters
----------
ds: xarray.Dataset
The dataset to store
%(xarray.Dataset.to_netcdf.parameters)s
"""
to_update = {}
for v, obj in six.iteritems(ds.variables):
units = obj.attrs.get('units', obj.encoding.get('units', None))
if units == 'day as %Y%m%d.%f' and np.issubdtype(
obj.dtype, np.datetime64):
to_update[v] = xr.Variable(
obj.dims, AbsoluteTimeEncoder(obj), attrs=obj.attrs.copy(),
encoding=obj.encoding)
to_update[v].attrs['units'] = units
if to_update:
ds = ds.copy()
ds.update(to_update)
return xarray_api.to_netcdf(ds, *args, **kwargs) | python | def to_netcdf(ds, *args, **kwargs):
"""
Store the given dataset as a netCDF file
This functions works essentially the same as the usual
:meth:`xarray.Dataset.to_netcdf` method but can also encode absolute time
units
Parameters
----------
ds: xarray.Dataset
The dataset to store
%(xarray.Dataset.to_netcdf.parameters)s
"""
to_update = {}
for v, obj in six.iteritems(ds.variables):
units = obj.attrs.get('units', obj.encoding.get('units', None))
if units == 'day as %Y%m%d.%f' and np.issubdtype(
obj.dtype, np.datetime64):
to_update[v] = xr.Variable(
obj.dims, AbsoluteTimeEncoder(obj), attrs=obj.attrs.copy(),
encoding=obj.encoding)
to_update[v].attrs['units'] = units
if to_update:
ds = ds.copy()
ds.update(to_update)
return xarray_api.to_netcdf(ds, *args, **kwargs) | [
"def",
"to_netcdf",
"(",
"ds",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"to_update",
"=",
"{",
"}",
"for",
"v",
",",
"obj",
"in",
"six",
".",
"iteritems",
"(",
"ds",
".",
"variables",
")",
":",
"units",
"=",
"obj",
".",
"attrs",
"."... | Store the given dataset as a netCDF file
This functions works essentially the same as the usual
:meth:`xarray.Dataset.to_netcdf` method but can also encode absolute time
units
Parameters
----------
ds: xarray.Dataset
The dataset to store
%(xarray.Dataset.to_netcdf.parameters)s | [
"Store",
"the",
"given",
"dataset",
"as",
"a",
"netCDF",
"file"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L309-L335 | train | 43,362 |
Chilipp/psyplot | psyplot/data.py | _get_fname_nio | def _get_fname_nio(store):
"""Try to get the file name from the NioDataStore store"""
try:
f = store.ds.file
except AttributeError:
return None
try:
return f.path
except AttributeError:
return None | python | def _get_fname_nio(store):
"""Try to get the file name from the NioDataStore store"""
try:
f = store.ds.file
except AttributeError:
return None
try:
return f.path
except AttributeError:
return None | [
"def",
"_get_fname_nio",
"(",
"store",
")",
":",
"try",
":",
"f",
"=",
"store",
".",
"ds",
".",
"file",
"except",
"AttributeError",
":",
"return",
"None",
"try",
":",
"return",
"f",
".",
"path",
"except",
"AttributeError",
":",
"return",
"None"
] | Try to get the file name from the NioDataStore store | [
"Try",
"to",
"get",
"the",
"file",
"name",
"from",
"the",
"NioDataStore",
"store"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L351-L360 | train | 43,363 |
Chilipp/psyplot | psyplot/data.py | get_filename_ds | def get_filename_ds(ds, dump=True, paths=None, **kwargs):
"""
Return the filename of the corresponding to a dataset
This method returns the path to the `ds` or saves the dataset
if there exists no filename
Parameters
----------
ds: xarray.Dataset
The dataset you want the path information for
dump: bool
If True and the dataset has not been dumped so far, it is dumped to a
temporary file or the one generated by `paths` is used
paths: iterable or True
An iterator over filenames to use if a dataset has no filename.
If paths is ``True``, an iterator over temporary files will be
created without raising a warning
Other Parameters
----------------
``**kwargs``
Any other keyword for the :func:`to_netcdf` function
%(xarray.Dataset.to_netcdf.parameters)s
Returns
-------
str or None
None, if the dataset has not yet been dumped to the harddisk and
`dump` is False, otherwise the complete the path to the input
file
str
The module of the :class:`xarray.backends.common.AbstractDataStore`
instance that is used to hold the data
str
The class name of the
:class:`xarray.backends.common.AbstractDataStore` instance that is
used to open the data
"""
from tempfile import NamedTemporaryFile
# if already specified, return that filename
if ds.psy._filename is not None:
return tuple([ds.psy._filename] + list(ds.psy.data_store))
def dump_nc():
# make sure that the data store is not closed by providing a
# write argument
if xr_version < (0, 11):
kwargs.setdefault('writer', xarray_api.ArrayWriter())
store = to_netcdf(ds, fname, **kwargs)
else:
# `writer` parameter was removed by
# https://github.com/pydata/xarray/pull/2261
kwargs.setdefault('multifile', True)
store = to_netcdf(ds, fname, **kwargs)[1]
store_mod = store.__module__
store_cls = store.__class__.__name__
ds._file_obj = store
return store_mod, store_cls
def tmp_it():
while True:
yield NamedTemporaryFile(suffix='.nc').name
fname = None
if paths is True or (dump and paths is None):
paths = tmp_it()
elif paths is not None:
if isstring(paths):
paths = iter([paths])
else:
paths = iter(paths)
# try to get the filename from the data store of the obj
store_mod, store_cls = ds.psy.data_store
if store_mod is not None:
store = ds._file_obj
# try several engines
if hasattr(store, 'file_objs'):
fname = []
store_mod = []
store_cls = []
for obj in store.file_objs: # mfdataset
_fname = None
for func in get_fname_funcs:
if _fname is None:
_fname = func(obj)
if _fname is not None:
fname.append(_fname)
store_mod.append(obj.__module__)
store_cls.append(obj.__class__.__name__)
fname = tuple(fname)
store_mod = tuple(store_mod)
store_cls = tuple(store_cls)
else:
for func in get_fname_funcs:
fname = func(store)
if fname is not None:
break
# check if paths is provided and if yes, save the file
if fname is None and paths is not None:
fname = next(paths, None)
if dump and fname is not None:
store_mod, store_cls = dump_nc()
ds.psy.filename = fname
ds.psy.data_store = (store_mod, store_cls)
return fname, store_mod, store_cls | python | def get_filename_ds(ds, dump=True, paths=None, **kwargs):
"""
Return the filename of the corresponding to a dataset
This method returns the path to the `ds` or saves the dataset
if there exists no filename
Parameters
----------
ds: xarray.Dataset
The dataset you want the path information for
dump: bool
If True and the dataset has not been dumped so far, it is dumped to a
temporary file or the one generated by `paths` is used
paths: iterable or True
An iterator over filenames to use if a dataset has no filename.
If paths is ``True``, an iterator over temporary files will be
created without raising a warning
Other Parameters
----------------
``**kwargs``
Any other keyword for the :func:`to_netcdf` function
%(xarray.Dataset.to_netcdf.parameters)s
Returns
-------
str or None
None, if the dataset has not yet been dumped to the harddisk and
`dump` is False, otherwise the complete the path to the input
file
str
The module of the :class:`xarray.backends.common.AbstractDataStore`
instance that is used to hold the data
str
The class name of the
:class:`xarray.backends.common.AbstractDataStore` instance that is
used to open the data
"""
from tempfile import NamedTemporaryFile
# if already specified, return that filename
if ds.psy._filename is not None:
return tuple([ds.psy._filename] + list(ds.psy.data_store))
def dump_nc():
# make sure that the data store is not closed by providing a
# write argument
if xr_version < (0, 11):
kwargs.setdefault('writer', xarray_api.ArrayWriter())
store = to_netcdf(ds, fname, **kwargs)
else:
# `writer` parameter was removed by
# https://github.com/pydata/xarray/pull/2261
kwargs.setdefault('multifile', True)
store = to_netcdf(ds, fname, **kwargs)[1]
store_mod = store.__module__
store_cls = store.__class__.__name__
ds._file_obj = store
return store_mod, store_cls
def tmp_it():
while True:
yield NamedTemporaryFile(suffix='.nc').name
fname = None
if paths is True or (dump and paths is None):
paths = tmp_it()
elif paths is not None:
if isstring(paths):
paths = iter([paths])
else:
paths = iter(paths)
# try to get the filename from the data store of the obj
store_mod, store_cls = ds.psy.data_store
if store_mod is not None:
store = ds._file_obj
# try several engines
if hasattr(store, 'file_objs'):
fname = []
store_mod = []
store_cls = []
for obj in store.file_objs: # mfdataset
_fname = None
for func in get_fname_funcs:
if _fname is None:
_fname = func(obj)
if _fname is not None:
fname.append(_fname)
store_mod.append(obj.__module__)
store_cls.append(obj.__class__.__name__)
fname = tuple(fname)
store_mod = tuple(store_mod)
store_cls = tuple(store_cls)
else:
for func in get_fname_funcs:
fname = func(store)
if fname is not None:
break
# check if paths is provided and if yes, save the file
if fname is None and paths is not None:
fname = next(paths, None)
if dump and fname is not None:
store_mod, store_cls = dump_nc()
ds.psy.filename = fname
ds.psy.data_store = (store_mod, store_cls)
return fname, store_mod, store_cls | [
"def",
"get_filename_ds",
"(",
"ds",
",",
"dump",
"=",
"True",
",",
"paths",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"tempfile",
"import",
"NamedTemporaryFile",
"# if already specified, return that filename",
"if",
"ds",
".",
"psy",
".",
"_file... | Return the filename of the corresponding to a dataset
This method returns the path to the `ds` or saves the dataset
if there exists no filename
Parameters
----------
ds: xarray.Dataset
The dataset you want the path information for
dump: bool
If True and the dataset has not been dumped so far, it is dumped to a
temporary file or the one generated by `paths` is used
paths: iterable or True
An iterator over filenames to use if a dataset has no filename.
If paths is ``True``, an iterator over temporary files will be
created without raising a warning
Other Parameters
----------------
``**kwargs``
Any other keyword for the :func:`to_netcdf` function
%(xarray.Dataset.to_netcdf.parameters)s
Returns
-------
str or None
None, if the dataset has not yet been dumped to the harddisk and
`dump` is False, otherwise the complete the path to the input
file
str
The module of the :class:`xarray.backends.common.AbstractDataStore`
instance that is used to hold the data
str
The class name of the
:class:`xarray.backends.common.AbstractDataStore` instance that is
used to open the data | [
"Return",
"the",
"filename",
"of",
"the",
"corresponding",
"to",
"a",
"dataset"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L416-L524 | train | 43,364 |
Chilipp/psyplot | psyplot/data.py | _open_ds_from_store | def _open_ds_from_store(fname, store_mod=None, store_cls=None, **kwargs):
"""Open a dataset and return it"""
if isinstance(fname, xr.Dataset):
return fname
if not isstring(fname):
try: # test iterable
fname[0]
except TypeError:
pass
else:
if store_mod is not None and store_cls is not None:
if isstring(store_mod):
store_mod = repeat(store_mod)
if isstring(store_cls):
store_cls = repeat(store_cls)
fname = [_open_store(sm, sc, f)
for sm, sc, f in zip(store_mod, store_cls, fname)]
kwargs['engine'] = None
kwargs['lock'] = False
return open_mfdataset(fname, **kwargs)
if store_mod is not None and store_cls is not None:
fname = _open_store(store_mod, store_cls, fname)
return open_dataset(fname, **kwargs) | python | def _open_ds_from_store(fname, store_mod=None, store_cls=None, **kwargs):
"""Open a dataset and return it"""
if isinstance(fname, xr.Dataset):
return fname
if not isstring(fname):
try: # test iterable
fname[0]
except TypeError:
pass
else:
if store_mod is not None and store_cls is not None:
if isstring(store_mod):
store_mod = repeat(store_mod)
if isstring(store_cls):
store_cls = repeat(store_cls)
fname = [_open_store(sm, sc, f)
for sm, sc, f in zip(store_mod, store_cls, fname)]
kwargs['engine'] = None
kwargs['lock'] = False
return open_mfdataset(fname, **kwargs)
if store_mod is not None and store_cls is not None:
fname = _open_store(store_mod, store_cls, fname)
return open_dataset(fname, **kwargs) | [
"def",
"_open_ds_from_store",
"(",
"fname",
",",
"store_mod",
"=",
"None",
",",
"store_cls",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"fname",
",",
"xr",
".",
"Dataset",
")",
":",
"return",
"fname",
"if",
"not",
"isstrin... | Open a dataset and return it | [
"Open",
"a",
"dataset",
"and",
"return",
"it"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L4738-L4760 | train | 43,365 |
Chilipp/psyplot | psyplot/data.py | Signal.disconnect | def disconnect(self, func=None):
"""Disconnect a function call to the signal. If None, all connections
are disconnected"""
if func is None:
self._connections = []
else:
self._connections.remove(func) | python | def disconnect(self, func=None):
"""Disconnect a function call to the signal. If None, all connections
are disconnected"""
if func is None:
self._connections = []
else:
self._connections.remove(func) | [
"def",
"disconnect",
"(",
"self",
",",
"func",
"=",
"None",
")",
":",
"if",
"func",
"is",
"None",
":",
"self",
".",
"_connections",
"=",
"[",
"]",
"else",
":",
"self",
".",
"_connections",
".",
"remove",
"(",
"func",
")"
] | Disconnect a function call to the signal. If None, all connections
are disconnected | [
"Disconnect",
"a",
"function",
"call",
"to",
"the",
"signal",
".",
"If",
"None",
"all",
"connections",
"are",
"disconnected"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L390-L396 | train | 43,366 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.get_decoder | def get_decoder(cls, ds, var):
"""
Class method to get the right decoder class that can decode the
given dataset and variable
Parameters
----------
%(CFDecoder.can_decode.parameters)s
Returns
-------
CFDecoder
The decoder for the given dataset that can decode the variable
`var`"""
for decoder_cls in cls._registry:
if decoder_cls.can_decode(ds, var):
return decoder_cls(ds)
return CFDecoder(ds) | python | def get_decoder(cls, ds, var):
"""
Class method to get the right decoder class that can decode the
given dataset and variable
Parameters
----------
%(CFDecoder.can_decode.parameters)s
Returns
-------
CFDecoder
The decoder for the given dataset that can decode the variable
`var`"""
for decoder_cls in cls._registry:
if decoder_cls.can_decode(ds, var):
return decoder_cls(ds)
return CFDecoder(ds) | [
"def",
"get_decoder",
"(",
"cls",
",",
"ds",
",",
"var",
")",
":",
"for",
"decoder_cls",
"in",
"cls",
".",
"_registry",
":",
"if",
"decoder_cls",
".",
"can_decode",
"(",
"ds",
",",
"var",
")",
":",
"return",
"decoder_cls",
"(",
"ds",
")",
"return",
"... | Class method to get the right decoder class that can decode the
given dataset and variable
Parameters
----------
%(CFDecoder.can_decode.parameters)s
Returns
-------
CFDecoder
The decoder for the given dataset that can decode the variable
`var` | [
"Class",
"method",
"to",
"get",
"the",
"right",
"decoder",
"class",
"that",
"can",
"decode",
"the",
"given",
"dataset",
"and",
"variable"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L601-L618 | train | 43,367 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.decode_coords | def decode_coords(ds, gridfile=None):
"""
Sets the coordinates and bounds in a dataset
This static method sets those coordinates and bounds that are marked
marked in the netCDF attributes as coordinates in :attr:`ds` (without
deleting them from the variable attributes because this information is
necessary for visualizing the data correctly)
Parameters
----------
ds: xarray.Dataset
The dataset to decode
gridfile: str
The path to a separate grid file or a xarray.Dataset instance which
may store the coordinates used in `ds`
Returns
-------
xarray.Dataset
`ds` with additional coordinates"""
def add_attrs(obj):
if 'coordinates' in obj.attrs:
extra_coords.update(obj.attrs['coordinates'].split())
obj.encoding['coordinates'] = obj.attrs.pop('coordinates')
if 'bounds' in obj.attrs:
extra_coords.add(obj.attrs['bounds'])
if gridfile is not None and not isinstance(gridfile, xr.Dataset):
gridfile = open_dataset(gridfile)
extra_coords = set(ds.coords)
for k, v in six.iteritems(ds.variables):
add_attrs(v)
add_attrs(ds)
if gridfile is not None:
ds.update({k: v for k, v in six.iteritems(gridfile.variables)
if k in extra_coords})
if xr_version < (0, 11):
ds.set_coords(extra_coords.intersection(ds.variables),
inplace=True)
else:
ds._coord_names.update(extra_coords.intersection(ds.variables))
return ds | python | def decode_coords(ds, gridfile=None):
"""
Sets the coordinates and bounds in a dataset
This static method sets those coordinates and bounds that are marked
marked in the netCDF attributes as coordinates in :attr:`ds` (without
deleting them from the variable attributes because this information is
necessary for visualizing the data correctly)
Parameters
----------
ds: xarray.Dataset
The dataset to decode
gridfile: str
The path to a separate grid file or a xarray.Dataset instance which
may store the coordinates used in `ds`
Returns
-------
xarray.Dataset
`ds` with additional coordinates"""
def add_attrs(obj):
if 'coordinates' in obj.attrs:
extra_coords.update(obj.attrs['coordinates'].split())
obj.encoding['coordinates'] = obj.attrs.pop('coordinates')
if 'bounds' in obj.attrs:
extra_coords.add(obj.attrs['bounds'])
if gridfile is not None and not isinstance(gridfile, xr.Dataset):
gridfile = open_dataset(gridfile)
extra_coords = set(ds.coords)
for k, v in six.iteritems(ds.variables):
add_attrs(v)
add_attrs(ds)
if gridfile is not None:
ds.update({k: v for k, v in six.iteritems(gridfile.variables)
if k in extra_coords})
if xr_version < (0, 11):
ds.set_coords(extra_coords.intersection(ds.variables),
inplace=True)
else:
ds._coord_names.update(extra_coords.intersection(ds.variables))
return ds | [
"def",
"decode_coords",
"(",
"ds",
",",
"gridfile",
"=",
"None",
")",
":",
"def",
"add_attrs",
"(",
"obj",
")",
":",
"if",
"'coordinates'",
"in",
"obj",
".",
"attrs",
":",
"extra_coords",
".",
"update",
"(",
"obj",
".",
"attrs",
"[",
"'coordinates'",
"... | Sets the coordinates and bounds in a dataset
This static method sets those coordinates and bounds that are marked
marked in the netCDF attributes as coordinates in :attr:`ds` (without
deleting them from the variable attributes because this information is
necessary for visualizing the data correctly)
Parameters
----------
ds: xarray.Dataset
The dataset to decode
gridfile: str
The path to a separate grid file or a xarray.Dataset instance which
may store the coordinates used in `ds`
Returns
-------
xarray.Dataset
`ds` with additional coordinates | [
"Sets",
"the",
"coordinates",
"and",
"bounds",
"in",
"a",
"dataset"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L623-L664 | train | 43,368 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.is_triangular | def is_triangular(self, var):
"""
Test if a variable is on a triangular grid
This method first checks the `grid_type` attribute of the variable (if
existent) whether it is equal to ``"unstructered"``, then it checks
whether the bounds are not two-dimensional.
Parameters
----------
var: xarray.Variable or xarray.DataArray
The variable to check
Returns
-------
bool
True, if the grid is triangular, else False"""
warn("The 'is_triangular' method is depreceated and will be removed "
"soon! Use the 'is_unstructured' method!", DeprecationWarning,
stacklevel=1)
return str(var.attrs.get('grid_type')) == 'unstructured' or \
self._check_triangular_bounds(var)[0] | python | def is_triangular(self, var):
"""
Test if a variable is on a triangular grid
This method first checks the `grid_type` attribute of the variable (if
existent) whether it is equal to ``"unstructered"``, then it checks
whether the bounds are not two-dimensional.
Parameters
----------
var: xarray.Variable or xarray.DataArray
The variable to check
Returns
-------
bool
True, if the grid is triangular, else False"""
warn("The 'is_triangular' method is depreceated and will be removed "
"soon! Use the 'is_unstructured' method!", DeprecationWarning,
stacklevel=1)
return str(var.attrs.get('grid_type')) == 'unstructured' or \
self._check_triangular_bounds(var)[0] | [
"def",
"is_triangular",
"(",
"self",
",",
"var",
")",
":",
"warn",
"(",
"\"The 'is_triangular' method is depreceated and will be removed \"",
"\"soon! Use the 'is_unstructured' method!\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"1",
")",
"return",
"str",
"(",
... | Test if a variable is on a triangular grid
This method first checks the `grid_type` attribute of the variable (if
existent) whether it is equal to ``"unstructered"``, then it checks
whether the bounds are not two-dimensional.
Parameters
----------
var: xarray.Variable or xarray.DataArray
The variable to check
Returns
-------
bool
True, if the grid is triangular, else False | [
"Test",
"if",
"a",
"variable",
"is",
"on",
"a",
"triangular",
"grid"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L669-L690 | train | 43,369 |
Chilipp/psyplot | psyplot/data.py | CFDecoder._get_coord_cell_node_coord | def _get_coord_cell_node_coord(self, coord, coords=None, nans=None,
var=None):
"""
Get the boundaries of an unstructed coordinate
Parameters
----------
coord: xr.Variable
The coordinate whose bounds should be returned
%(CFDecoder.get_cell_node_coord.parameters.no_var|axis)s
Returns
-------
%(CFDecoder.get_cell_node_coord.returns)s
"""
bounds = coord.attrs.get('bounds')
if bounds is not None:
bounds = self.ds.coords.get(bounds)
if bounds is not None:
if coords is not None:
bounds = bounds.sel(**{
key: coords[key]
for key in set(coords).intersection(bounds.dims)})
if nans is not None and var is None:
raise ValueError("Need the variable to deal with NaN!")
elif nans is None:
pass
elif nans == 'skip':
bounds = bounds[~np.isnan(var.values)]
elif nans == 'only':
bounds = bounds[np.isnan(var.values)]
else:
raise ValueError(
"`nans` must be either None, 'skip', or 'only'! "
"Not {0}!".format(str(nans)))
return bounds | python | def _get_coord_cell_node_coord(self, coord, coords=None, nans=None,
var=None):
"""
Get the boundaries of an unstructed coordinate
Parameters
----------
coord: xr.Variable
The coordinate whose bounds should be returned
%(CFDecoder.get_cell_node_coord.parameters.no_var|axis)s
Returns
-------
%(CFDecoder.get_cell_node_coord.returns)s
"""
bounds = coord.attrs.get('bounds')
if bounds is not None:
bounds = self.ds.coords.get(bounds)
if bounds is not None:
if coords is not None:
bounds = bounds.sel(**{
key: coords[key]
for key in set(coords).intersection(bounds.dims)})
if nans is not None and var is None:
raise ValueError("Need the variable to deal with NaN!")
elif nans is None:
pass
elif nans == 'skip':
bounds = bounds[~np.isnan(var.values)]
elif nans == 'only':
bounds = bounds[np.isnan(var.values)]
else:
raise ValueError(
"`nans` must be either None, 'skip', or 'only'! "
"Not {0}!".format(str(nans)))
return bounds | [
"def",
"_get_coord_cell_node_coord",
"(",
"self",
",",
"coord",
",",
"coords",
"=",
"None",
",",
"nans",
"=",
"None",
",",
"var",
"=",
"None",
")",
":",
"bounds",
"=",
"coord",
".",
"attrs",
".",
"get",
"(",
"'bounds'",
")",
"if",
"bounds",
"is",
"no... | Get the boundaries of an unstructed coordinate
Parameters
----------
coord: xr.Variable
The coordinate whose bounds should be returned
%(CFDecoder.get_cell_node_coord.parameters.no_var|axis)s
Returns
-------
%(CFDecoder.get_cell_node_coord.returns)s | [
"Get",
"the",
"boundaries",
"of",
"an",
"unstructed",
"coordinate"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L755-L790 | train | 43,370 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.is_unstructured | def is_unstructured(self, var):
"""
Test if a variable is on an unstructered grid
Parameters
----------
%(CFDecoder.is_triangular.parameters)s
Returns
-------
%(CFDecoder.is_triangular.returns)s
Notes
-----
Currently this is the same as :meth:`is_triangular` method, but may
change in the future to support hexagonal grids"""
if str(var.attrs.get('grid_type')) == 'unstructured':
return True
xcoord = self.get_x(var)
if xcoord is not None:
bounds = self._get_coord_cell_node_coord(xcoord)
if bounds is not None and bounds.shape[-1] > 2:
return True | python | def is_unstructured(self, var):
"""
Test if a variable is on an unstructered grid
Parameters
----------
%(CFDecoder.is_triangular.parameters)s
Returns
-------
%(CFDecoder.is_triangular.returns)s
Notes
-----
Currently this is the same as :meth:`is_triangular` method, but may
change in the future to support hexagonal grids"""
if str(var.attrs.get('grid_type')) == 'unstructured':
return True
xcoord = self.get_x(var)
if xcoord is not None:
bounds = self._get_coord_cell_node_coord(xcoord)
if bounds is not None and bounds.shape[-1] > 2:
return True | [
"def",
"is_unstructured",
"(",
"self",
",",
"var",
")",
":",
"if",
"str",
"(",
"var",
".",
"attrs",
".",
"get",
"(",
"'grid_type'",
")",
")",
"==",
"'unstructured'",
":",
"return",
"True",
"xcoord",
"=",
"self",
".",
"get_x",
"(",
"var",
")",
"if",
... | Test if a variable is on an unstructered grid
Parameters
----------
%(CFDecoder.is_triangular.parameters)s
Returns
-------
%(CFDecoder.is_triangular.returns)s
Notes
-----
Currently this is the same as :meth:`is_triangular` method, but may
change in the future to support hexagonal grids | [
"Test",
"if",
"a",
"variable",
"is",
"on",
"an",
"unstructered",
"grid"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L818-L840 | train | 43,371 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.is_circumpolar | def is_circumpolar(self, var):
"""
Test if a variable is on a circumpolar grid
Parameters
----------
%(CFDecoder.is_triangular.parameters)s
Returns
-------
%(CFDecoder.is_triangular.returns)s"""
xcoord = self.get_x(var)
return xcoord is not None and xcoord.ndim == 2 | python | def is_circumpolar(self, var):
"""
Test if a variable is on a circumpolar grid
Parameters
----------
%(CFDecoder.is_triangular.parameters)s
Returns
-------
%(CFDecoder.is_triangular.returns)s"""
xcoord = self.get_x(var)
return xcoord is not None and xcoord.ndim == 2 | [
"def",
"is_circumpolar",
"(",
"self",
",",
"var",
")",
":",
"xcoord",
"=",
"self",
".",
"get_x",
"(",
"var",
")",
"return",
"xcoord",
"is",
"not",
"None",
"and",
"xcoord",
".",
"ndim",
"==",
"2"
] | Test if a variable is on a circumpolar grid
Parameters
----------
%(CFDecoder.is_triangular.parameters)s
Returns
-------
%(CFDecoder.is_triangular.returns)s | [
"Test",
"if",
"a",
"variable",
"is",
"on",
"a",
"circumpolar",
"grid"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L843-L855 | train | 43,372 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.get_variable_by_axis | def get_variable_by_axis(self, var, axis, coords=None):
"""Return the coordinate matching the specified axis
This method uses to ``'axis'`` attribute in coordinates to return the
corresponding coordinate of the given variable
Possible types
--------------
var: xarray.Variable
The variable to get the dimension for
axis: {'x', 'y', 'z', 't'}
The axis string that identifies the dimension
coords: dict
Coordinates to use. If None, the coordinates of the dataset in the
:attr:`ds` attribute are used.
Returns
-------
xarray.Coordinate or None
The coordinate for `var` that matches the given `axis` or None if
no coordinate with the right `axis` could be found.
Notes
-----
This is a rather low-level function that only interpretes the
CFConvention. It is used by the :meth:`get_x`,
:meth:`get_y`, :meth:`get_z` and :meth:`get_t` methods
Warning
-------
If None of the coordinates have an ``'axis'`` attribute, we use the
``'coordinate'`` attribute of `var` (if existent).
Since however the CF Conventions do not determine the order on how
the coordinates shall be saved, we try to use a pattern matching
for latitude (``'lat'``) and longitude (``lon'``). If this patterns
do not match, we interpret the coordinates such that x: -1, y: -2,
z: -3. This is all not very safe for awkward dimension names,
but works for most cases. If you want to be a hundred percent sure,
use the :attr:`x`, :attr:`y`, :attr:`z` and :attr:`t` attribute.
See Also
--------
get_x, get_y, get_z, get_t"""
axis = axis.lower()
if axis not in list('xyzt'):
raise ValueError("Axis must be one of X, Y, Z, T, not {0}".format(
axis))
# we first check for the dimensions and then for the coordinates
# attribute
coords = coords or self.ds.coords
coord_names = var.attrs.get('coordinates', var.encoding.get(
'coordinates', '')).split()
if not coord_names:
return
ret = []
for coord in map(lambda dim: coords[dim], filter(
lambda dim: dim in coords, chain(
coord_names, var.dims))):
# check for the axis attribute or whether the coordinate is in the
# list of possible coordinate names
if (coord.name not in (c.name for c in ret) and
(coord.attrs.get('axis', '').lower() == axis or
coord.name in getattr(self, axis))):
ret.append(coord)
if ret:
return None if len(ret) > 1 else ret[0]
# If the coordinates attribute is specified but the coordinate
# variables themselves have no 'axis' attribute, we interpret the
# coordinates such that x: -1, y: -2, z: -3
# Since however the CF Conventions do not determine the order on how
# the coordinates shall be saved, we try to use a pattern matching
# for latitude and longitude. This is not very nice, hence it is
# better to specify the :attr:`x` and :attr:`y` attribute
tnames = self.t.intersection(coord_names)
if axis == 'x':
for cname in filter(lambda cname: re.search('lon', cname),
coord_names):
return coords[cname]
return coords.get(coord_names[-1])
elif axis == 'y' and len(coord_names) >= 2:
for cname in filter(lambda cname: re.search('lat', cname),
coord_names):
return coords[cname]
return coords.get(coord_names[-2])
elif (axis == 'z' and len(coord_names) >= 3 and
coord_names[-3] not in tnames):
return coords.get(coord_names[-3])
elif axis == 't' and tnames:
tname = next(iter(tnames))
if len(tnames) > 1:
warn("Found multiple matches for time coordinate in the "
"coordinates: %s. I use %s" % (', '.join(tnames), tname),
PsyPlotRuntimeWarning)
return coords.get(tname) | python | def get_variable_by_axis(self, var, axis, coords=None):
"""Return the coordinate matching the specified axis
This method uses to ``'axis'`` attribute in coordinates to return the
corresponding coordinate of the given variable
Possible types
--------------
var: xarray.Variable
The variable to get the dimension for
axis: {'x', 'y', 'z', 't'}
The axis string that identifies the dimension
coords: dict
Coordinates to use. If None, the coordinates of the dataset in the
:attr:`ds` attribute are used.
Returns
-------
xarray.Coordinate or None
The coordinate for `var` that matches the given `axis` or None if
no coordinate with the right `axis` could be found.
Notes
-----
This is a rather low-level function that only interpretes the
CFConvention. It is used by the :meth:`get_x`,
:meth:`get_y`, :meth:`get_z` and :meth:`get_t` methods
Warning
-------
If None of the coordinates have an ``'axis'`` attribute, we use the
``'coordinate'`` attribute of `var` (if existent).
Since however the CF Conventions do not determine the order on how
the coordinates shall be saved, we try to use a pattern matching
for latitude (``'lat'``) and longitude (``lon'``). If this patterns
do not match, we interpret the coordinates such that x: -1, y: -2,
z: -3. This is all not very safe for awkward dimension names,
but works for most cases. If you want to be a hundred percent sure,
use the :attr:`x`, :attr:`y`, :attr:`z` and :attr:`t` attribute.
See Also
--------
get_x, get_y, get_z, get_t"""
axis = axis.lower()
if axis not in list('xyzt'):
raise ValueError("Axis must be one of X, Y, Z, T, not {0}".format(
axis))
# we first check for the dimensions and then for the coordinates
# attribute
coords = coords or self.ds.coords
coord_names = var.attrs.get('coordinates', var.encoding.get(
'coordinates', '')).split()
if not coord_names:
return
ret = []
for coord in map(lambda dim: coords[dim], filter(
lambda dim: dim in coords, chain(
coord_names, var.dims))):
# check for the axis attribute or whether the coordinate is in the
# list of possible coordinate names
if (coord.name not in (c.name for c in ret) and
(coord.attrs.get('axis', '').lower() == axis or
coord.name in getattr(self, axis))):
ret.append(coord)
if ret:
return None if len(ret) > 1 else ret[0]
# If the coordinates attribute is specified but the coordinate
# variables themselves have no 'axis' attribute, we interpret the
# coordinates such that x: -1, y: -2, z: -3
# Since however the CF Conventions do not determine the order on how
# the coordinates shall be saved, we try to use a pattern matching
# for latitude and longitude. This is not very nice, hence it is
# better to specify the :attr:`x` and :attr:`y` attribute
tnames = self.t.intersection(coord_names)
if axis == 'x':
for cname in filter(lambda cname: re.search('lon', cname),
coord_names):
return coords[cname]
return coords.get(coord_names[-1])
elif axis == 'y' and len(coord_names) >= 2:
for cname in filter(lambda cname: re.search('lat', cname),
coord_names):
return coords[cname]
return coords.get(coord_names[-2])
elif (axis == 'z' and len(coord_names) >= 3 and
coord_names[-3] not in tnames):
return coords.get(coord_names[-3])
elif axis == 't' and tnames:
tname = next(iter(tnames))
if len(tnames) > 1:
warn("Found multiple matches for time coordinate in the "
"coordinates: %s. I use %s" % (', '.join(tnames), tname),
PsyPlotRuntimeWarning)
return coords.get(tname) | [
"def",
"get_variable_by_axis",
"(",
"self",
",",
"var",
",",
"axis",
",",
"coords",
"=",
"None",
")",
":",
"axis",
"=",
"axis",
".",
"lower",
"(",
")",
"if",
"axis",
"not",
"in",
"list",
"(",
"'xyzt'",
")",
":",
"raise",
"ValueError",
"(",
"\"Axis mu... | Return the coordinate matching the specified axis
This method uses to ``'axis'`` attribute in coordinates to return the
corresponding coordinate of the given variable
Possible types
--------------
var: xarray.Variable
The variable to get the dimension for
axis: {'x', 'y', 'z', 't'}
The axis string that identifies the dimension
coords: dict
Coordinates to use. If None, the coordinates of the dataset in the
:attr:`ds` attribute are used.
Returns
-------
xarray.Coordinate or None
The coordinate for `var` that matches the given `axis` or None if
no coordinate with the right `axis` could be found.
Notes
-----
This is a rather low-level function that only interpretes the
CFConvention. It is used by the :meth:`get_x`,
:meth:`get_y`, :meth:`get_z` and :meth:`get_t` methods
Warning
-------
If None of the coordinates have an ``'axis'`` attribute, we use the
``'coordinate'`` attribute of `var` (if existent).
Since however the CF Conventions do not determine the order on how
the coordinates shall be saved, we try to use a pattern matching
for latitude (``'lat'``) and longitude (``lon'``). If this patterns
do not match, we interpret the coordinates such that x: -1, y: -2,
z: -3. This is all not very safe for awkward dimension names,
but works for most cases. If you want to be a hundred percent sure,
use the :attr:`x`, :attr:`y`, :attr:`z` and :attr:`t` attribute.
See Also
--------
get_x, get_y, get_z, get_t | [
"Return",
"the",
"coordinate",
"matching",
"the",
"specified",
"axis"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L857-L950 | train | 43,373 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.get_x | def get_x(self, var, coords=None):
"""
Get the x-coordinate of a variable
This method searches for the x-coordinate in the :attr:`ds`. It first
checks whether there is one dimension that holds an ``'axis'``
attribute with 'X', otherwise it looks whether there is an intersection
between the :attr:`x` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the last dimension of `var`
Possible types
--------------
var: xarray.Variable
The variable to get the x-coordinate for
coords: dict
Coordinates to use. If None, the coordinates of the dataset in the
:attr:`ds` attribute are used.
Returns
-------
xarray.Coordinate or None
The y-coordinate or None if it could be found"""
coords = coords or self.ds.coords
coord = self.get_variable_by_axis(var, 'x', coords)
if coord is not None:
return coord
return coords.get(self.get_xname(var)) | python | def get_x(self, var, coords=None):
"""
Get the x-coordinate of a variable
This method searches for the x-coordinate in the :attr:`ds`. It first
checks whether there is one dimension that holds an ``'axis'``
attribute with 'X', otherwise it looks whether there is an intersection
between the :attr:`x` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the last dimension of `var`
Possible types
--------------
var: xarray.Variable
The variable to get the x-coordinate for
coords: dict
Coordinates to use. If None, the coordinates of the dataset in the
:attr:`ds` attribute are used.
Returns
-------
xarray.Coordinate or None
The y-coordinate or None if it could be found"""
coords = coords or self.ds.coords
coord = self.get_variable_by_axis(var, 'x', coords)
if coord is not None:
return coord
return coords.get(self.get_xname(var)) | [
"def",
"get_x",
"(",
"self",
",",
"var",
",",
"coords",
"=",
"None",
")",
":",
"coords",
"=",
"coords",
"or",
"self",
".",
"ds",
".",
"coords",
"coord",
"=",
"self",
".",
"get_variable_by_axis",
"(",
"var",
",",
"'x'",
",",
"coords",
")",
"if",
"co... | Get the x-coordinate of a variable
This method searches for the x-coordinate in the :attr:`ds`. It first
checks whether there is one dimension that holds an ``'axis'``
attribute with 'X', otherwise it looks whether there is an intersection
between the :attr:`x` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the last dimension of `var`
Possible types
--------------
var: xarray.Variable
The variable to get the x-coordinate for
coords: dict
Coordinates to use. If None, the coordinates of the dataset in the
:attr:`ds` attribute are used.
Returns
-------
xarray.Coordinate or None
The y-coordinate or None if it could be found | [
"Get",
"the",
"x",
"-",
"coordinate",
"of",
"a",
"variable"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L955-L981 | train | 43,374 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.get_xname | def get_xname(self, var, coords=None):
"""Get the name of the x-dimension
This method gives the name of the x-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str
The coordinate name
See Also
--------
get_x"""
if coords is not None:
coord = self.get_variable_by_axis(var, 'x', coords)
if coord is not None and coord.name in var.dims:
return coord.name
dimlist = list(self.x.intersection(var.dims))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for x coordinate in the variable:"
"%s. I use %s" % (', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return dimlist[0]
# otherwise we return the coordinate in the last position
return var.dims[-1] | python | def get_xname(self, var, coords=None):
"""Get the name of the x-dimension
This method gives the name of the x-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str
The coordinate name
See Also
--------
get_x"""
if coords is not None:
coord = self.get_variable_by_axis(var, 'x', coords)
if coord is not None and coord.name in var.dims:
return coord.name
dimlist = list(self.x.intersection(var.dims))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for x coordinate in the variable:"
"%s. I use %s" % (', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return dimlist[0]
# otherwise we return the coordinate in the last position
return var.dims[-1] | [
"def",
"get_xname",
"(",
"self",
",",
"var",
",",
"coords",
"=",
"None",
")",
":",
"if",
"coords",
"is",
"not",
"None",
":",
"coord",
"=",
"self",
".",
"get_variable_by_axis",
"(",
"var",
",",
"'x'",
",",
"coords",
")",
"if",
"coord",
"is",
"not",
... | Get the name of the x-dimension
This method gives the name of the x-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str
The coordinate name
See Also
--------
get_x | [
"Get",
"the",
"name",
"of",
"the",
"x",
"-",
"dimension"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L983-L1017 | train | 43,375 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.get_y | def get_y(self, var, coords=None):
"""
Get the y-coordinate of a variable
This method searches for the y-coordinate in the :attr:`ds`. It first
checks whether there is one dimension that holds an ``'axis'``
attribute with 'Y', otherwise it looks whether there is an intersection
between the :attr:`y` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the second last dimension of
`var` (or the last if the dimension of var is one-dimensional)
Possible types
--------------
var: xarray.Variable
The variable to get the y-coordinate for
coords: dict
Coordinates to use. If None, the coordinates of the dataset in the
:attr:`ds` attribute are used.
Returns
-------
xarray.Coordinate or None
The y-coordinate or None if it could be found"""
coords = coords or self.ds.coords
coord = self.get_variable_by_axis(var, 'y', coords)
if coord is not None:
return coord
return coords.get(self.get_yname(var)) | python | def get_y(self, var, coords=None):
"""
Get the y-coordinate of a variable
This method searches for the y-coordinate in the :attr:`ds`. It first
checks whether there is one dimension that holds an ``'axis'``
attribute with 'Y', otherwise it looks whether there is an intersection
between the :attr:`y` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the second last dimension of
`var` (or the last if the dimension of var is one-dimensional)
Possible types
--------------
var: xarray.Variable
The variable to get the y-coordinate for
coords: dict
Coordinates to use. If None, the coordinates of the dataset in the
:attr:`ds` attribute are used.
Returns
-------
xarray.Coordinate or None
The y-coordinate or None if it could be found"""
coords = coords or self.ds.coords
coord = self.get_variable_by_axis(var, 'y', coords)
if coord is not None:
return coord
return coords.get(self.get_yname(var)) | [
"def",
"get_y",
"(",
"self",
",",
"var",
",",
"coords",
"=",
"None",
")",
":",
"coords",
"=",
"coords",
"or",
"self",
".",
"ds",
".",
"coords",
"coord",
"=",
"self",
".",
"get_variable_by_axis",
"(",
"var",
",",
"'y'",
",",
"coords",
")",
"if",
"co... | Get the y-coordinate of a variable
This method searches for the y-coordinate in the :attr:`ds`. It first
checks whether there is one dimension that holds an ``'axis'``
attribute with 'Y', otherwise it looks whether there is an intersection
between the :attr:`y` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the second last dimension of
`var` (or the last if the dimension of var is one-dimensional)
Possible types
--------------
var: xarray.Variable
The variable to get the y-coordinate for
coords: dict
Coordinates to use. If None, the coordinates of the dataset in the
:attr:`ds` attribute are used.
Returns
-------
xarray.Coordinate or None
The y-coordinate or None if it could be found | [
"Get",
"the",
"y",
"-",
"coordinate",
"of",
"a",
"variable"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1022-L1049 | train | 43,376 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.get_yname | def get_yname(self, var, coords=None):
"""Get the name of the y-dimension
This method gives the name of the y-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str
The coordinate name
See Also
--------
get_y"""
if coords is not None:
coord = self.get_variable_by_axis(var, 'y', coords)
if coord is not None and coord.name in var.dims:
return coord.name
dimlist = list(self.y.intersection(var.dims))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for y coordinate in the variable:"
"%s. I use %s" % (', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return dimlist[0]
# otherwise we return the coordinate in the last or second last
# position
if self.is_unstructured(var):
return var.dims[-1]
return var.dims[-2 if var.ndim > 1 else -1] | python | def get_yname(self, var, coords=None):
"""Get the name of the y-dimension
This method gives the name of the y-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str
The coordinate name
See Also
--------
get_y"""
if coords is not None:
coord = self.get_variable_by_axis(var, 'y', coords)
if coord is not None and coord.name in var.dims:
return coord.name
dimlist = list(self.y.intersection(var.dims))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for y coordinate in the variable:"
"%s. I use %s" % (', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return dimlist[0]
# otherwise we return the coordinate in the last or second last
# position
if self.is_unstructured(var):
return var.dims[-1]
return var.dims[-2 if var.ndim > 1 else -1] | [
"def",
"get_yname",
"(",
"self",
",",
"var",
",",
"coords",
"=",
"None",
")",
":",
"if",
"coords",
"is",
"not",
"None",
":",
"coord",
"=",
"self",
".",
"get_variable_by_axis",
"(",
"var",
",",
"'y'",
",",
"coords",
")",
"if",
"coord",
"is",
"not",
... | Get the name of the y-dimension
This method gives the name of the y-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str
The coordinate name
See Also
--------
get_y | [
"Get",
"the",
"name",
"of",
"the",
"y",
"-",
"dimension"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1051-L1088 | train | 43,377 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.get_zname | def get_zname(self, var, coords=None):
"""Get the name of the z-dimension
This method gives the name of the z-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str or None
The coordinate name or None if no vertical coordinate could be
found
See Also
--------
get_z"""
if coords is not None:
coord = self.get_variable_by_axis(var, 'z', coords)
if coord is not None and coord.name in var.dims:
return coord.name
dimlist = list(self.z.intersection(var.dims))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for z coordinate in the variable:"
"%s. I use %s" % (', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return dimlist[0]
# otherwise we return the coordinate in the third last position
is_unstructured = self.is_unstructured(var)
icheck = -2 if is_unstructured else -3
min_dim = abs(icheck) if 'variable' not in var.dims else abs(icheck-1)
if var.ndim >= min_dim and var.dims[icheck] != self.get_tname(
var, coords):
return var.dims[icheck]
return None | python | def get_zname(self, var, coords=None):
"""Get the name of the z-dimension
This method gives the name of the z-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str or None
The coordinate name or None if no vertical coordinate could be
found
See Also
--------
get_z"""
if coords is not None:
coord = self.get_variable_by_axis(var, 'z', coords)
if coord is not None and coord.name in var.dims:
return coord.name
dimlist = list(self.z.intersection(var.dims))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for z coordinate in the variable:"
"%s. I use %s" % (', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return dimlist[0]
# otherwise we return the coordinate in the third last position
is_unstructured = self.is_unstructured(var)
icheck = -2 if is_unstructured else -3
min_dim = abs(icheck) if 'variable' not in var.dims else abs(icheck-1)
if var.ndim >= min_dim and var.dims[icheck] != self.get_tname(
var, coords):
return var.dims[icheck]
return None | [
"def",
"get_zname",
"(",
"self",
",",
"var",
",",
"coords",
"=",
"None",
")",
":",
"if",
"coords",
"is",
"not",
"None",
":",
"coord",
"=",
"self",
".",
"get_variable_by_axis",
"(",
"var",
",",
"'z'",
",",
"coords",
")",
"if",
"coord",
"is",
"not",
... | Get the name of the z-dimension
This method gives the name of the z-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str or None
The coordinate name or None if no vertical coordinate could be
found
See Also
--------
get_z | [
"Get",
"the",
"name",
"of",
"the",
"z",
"-",
"dimension"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1125-L1166 | train | 43,378 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.get_t | def get_t(self, var, coords=None):
"""
Get the time coordinate of a variable
This method searches for the time coordinate in the :attr:`ds`. It
first checks whether there is one dimension that holds an ``'axis'``
attribute with 'T', otherwise it looks whether there is an intersection
between the :attr:`t` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the first dimension of `var`
Possible types
--------------
var: xarray.Variable
The variable to get the time coordinate for
coords: dict
Coordinates to use. If None, the coordinates of the dataset in the
:attr:`ds` attribute are used.
Returns
-------
xarray.Coordinate or None
The time coordinate or None if no time coordinate could be found"""
coords = coords or self.ds.coords
coord = self.get_variable_by_axis(var, 't', coords)
if coord is not None:
return coord
dimlist = list(self.t.intersection(var.dims).intersection(coords))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for time coordinate in the "
"variable: %s. I use %s" % (
', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return coords[dimlist[0]]
tname = self.get_tname(var)
if tname is not None:
return coords.get(tname)
return None | python | def get_t(self, var, coords=None):
"""
Get the time coordinate of a variable
This method searches for the time coordinate in the :attr:`ds`. It
first checks whether there is one dimension that holds an ``'axis'``
attribute with 'T', otherwise it looks whether there is an intersection
between the :attr:`t` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the first dimension of `var`
Possible types
--------------
var: xarray.Variable
The variable to get the time coordinate for
coords: dict
Coordinates to use. If None, the coordinates of the dataset in the
:attr:`ds` attribute are used.
Returns
-------
xarray.Coordinate or None
The time coordinate or None if no time coordinate could be found"""
coords = coords or self.ds.coords
coord = self.get_variable_by_axis(var, 't', coords)
if coord is not None:
return coord
dimlist = list(self.t.intersection(var.dims).intersection(coords))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for time coordinate in the "
"variable: %s. I use %s" % (
', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return coords[dimlist[0]]
tname = self.get_tname(var)
if tname is not None:
return coords.get(tname)
return None | [
"def",
"get_t",
"(",
"self",
",",
"var",
",",
"coords",
"=",
"None",
")",
":",
"coords",
"=",
"coords",
"or",
"self",
".",
"ds",
".",
"coords",
"coord",
"=",
"self",
".",
"get_variable_by_axis",
"(",
"var",
",",
"'t'",
",",
"coords",
")",
"if",
"co... | Get the time coordinate of a variable
This method searches for the time coordinate in the :attr:`ds`. It
first checks whether there is one dimension that holds an ``'axis'``
attribute with 'T', otherwise it looks whether there is an intersection
between the :attr:`t` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the first dimension of `var`
Possible types
--------------
var: xarray.Variable
The variable to get the time coordinate for
coords: dict
Coordinates to use. If None, the coordinates of the dataset in the
:attr:`ds` attribute are used.
Returns
-------
xarray.Coordinate or None
The time coordinate or None if no time coordinate could be found | [
"Get",
"the",
"time",
"coordinate",
"of",
"a",
"variable"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1171-L1208 | train | 43,379 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.get_tname | def get_tname(self, var, coords=None):
"""Get the name of the t-dimension
This method gives the name of the time dimension
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str or None
The coordinate name or None if no time coordinate could be found
See Also
--------
get_t"""
if coords is not None:
coord = self.get_variable_by_axis(var, 't', coords)
if coord is not None and coord.name in var.dims:
return coord.name
dimlist = list(self.t.intersection(var.dims))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for t coordinate in the variable:"
"%s. I use %s" % (', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return dimlist[0]
# otherwise we return None
return None | python | def get_tname(self, var, coords=None):
"""Get the name of the t-dimension
This method gives the name of the time dimension
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str or None
The coordinate name or None if no time coordinate could be found
See Also
--------
get_t"""
if coords is not None:
coord = self.get_variable_by_axis(var, 't', coords)
if coord is not None and coord.name in var.dims:
return coord.name
dimlist = list(self.t.intersection(var.dims))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for t coordinate in the variable:"
"%s. I use %s" % (', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return dimlist[0]
# otherwise we return None
return None | [
"def",
"get_tname",
"(",
"self",
",",
"var",
",",
"coords",
"=",
"None",
")",
":",
"if",
"coords",
"is",
"not",
"None",
":",
"coord",
"=",
"self",
".",
"get_variable_by_axis",
"(",
"var",
",",
"'t'",
",",
"coords",
")",
"if",
"coord",
"is",
"not",
... | Get the name of the t-dimension
This method gives the name of the time dimension
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str or None
The coordinate name or None if no time coordinate could be found
See Also
--------
get_t | [
"Get",
"the",
"name",
"of",
"the",
"t",
"-",
"dimension"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1210-L1243 | train | 43,380 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.get_coord_idims | def get_coord_idims(self, coords):
"""Get the slicers for the given coordinates from the base dataset
This method converts `coords` to slicers (list of
integers or ``slice`` objects)
Parameters
----------
coords: dict
A subset of the ``ds.coords`` attribute of the base dataset
:attr:`ds`
Returns
-------
dict
Mapping from coordinate name to integer, list of integer or slice
"""
ret = dict(
(label, get_index_from_coord(coord, self.ds.indexes[label]))
for label, coord in six.iteritems(coords)
if label in self.ds.indexes)
return ret | python | def get_coord_idims(self, coords):
"""Get the slicers for the given coordinates from the base dataset
This method converts `coords` to slicers (list of
integers or ``slice`` objects)
Parameters
----------
coords: dict
A subset of the ``ds.coords`` attribute of the base dataset
:attr:`ds`
Returns
-------
dict
Mapping from coordinate name to integer, list of integer or slice
"""
ret = dict(
(label, get_index_from_coord(coord, self.ds.indexes[label]))
for label, coord in six.iteritems(coords)
if label in self.ds.indexes)
return ret | [
"def",
"get_coord_idims",
"(",
"self",
",",
"coords",
")",
":",
"ret",
"=",
"dict",
"(",
"(",
"label",
",",
"get_index_from_coord",
"(",
"coord",
",",
"self",
".",
"ds",
".",
"indexes",
"[",
"label",
"]",
")",
")",
"for",
"label",
",",
"coord",
"in",... | Get the slicers for the given coordinates from the base dataset
This method converts `coords` to slicers (list of
integers or ``slice`` objects)
Parameters
----------
coords: dict
A subset of the ``ds.coords`` attribute of the base dataset
:attr:`ds`
Returns
-------
dict
Mapping from coordinate name to integer, list of integer or slice | [
"Get",
"the",
"slicers",
"for",
"the",
"given",
"coordinates",
"from",
"the",
"base",
"dataset"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1284-L1305 | train | 43,381 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.get_plotbounds | def get_plotbounds(self, coord, kind=None, ignore_shape=False):
"""
Get the bounds of a coordinate
This method first checks the ``'bounds'`` attribute of the given
`coord` and if it fails, it calculates them.
Parameters
----------
coord: xarray.Coordinate
The coordinate to get the bounds for
kind: str
The interpolation method (see :func:`scipy.interpolate.interp1d`)
that is used in case of a 2-dimensional coordinate
ignore_shape: bool
If True and the `coord` has a ``'bounds'`` attribute, this
attribute is returned without further check. Otherwise it is tried
to bring the ``'bounds'`` into a format suitable for (e.g.) the
:func:`matplotlib.pyplot.pcolormesh` function.
Returns
-------
bounds: np.ndarray
The bounds with the same number of dimensions as `coord` but one
additional array (i.e. if `coord` has shape (4, ), `bounds` will
have shape (5, ) and if `coord` has shape (4, 5), `bounds` will
have shape (5, 6)"""
if 'bounds' in coord.attrs:
bounds = self.ds.coords[coord.attrs['bounds']]
if ignore_shape:
return bounds.values.ravel()
if not bounds.shape[:-1] == coord.shape:
bounds = self.ds.isel(**self.get_idims(coord))
try:
return self._get_plotbounds_from_cf(coord, bounds)
except ValueError as e:
warn((e.message if six.PY2 else str(e)) +
" Bounds are calculated automatically!")
return self._infer_interval_breaks(coord, kind=kind) | python | def get_plotbounds(self, coord, kind=None, ignore_shape=False):
"""
Get the bounds of a coordinate
This method first checks the ``'bounds'`` attribute of the given
`coord` and if it fails, it calculates them.
Parameters
----------
coord: xarray.Coordinate
The coordinate to get the bounds for
kind: str
The interpolation method (see :func:`scipy.interpolate.interp1d`)
that is used in case of a 2-dimensional coordinate
ignore_shape: bool
If True and the `coord` has a ``'bounds'`` attribute, this
attribute is returned without further check. Otherwise it is tried
to bring the ``'bounds'`` into a format suitable for (e.g.) the
:func:`matplotlib.pyplot.pcolormesh` function.
Returns
-------
bounds: np.ndarray
The bounds with the same number of dimensions as `coord` but one
additional array (i.e. if `coord` has shape (4, ), `bounds` will
have shape (5, ) and if `coord` has shape (4, 5), `bounds` will
have shape (5, 6)"""
if 'bounds' in coord.attrs:
bounds = self.ds.coords[coord.attrs['bounds']]
if ignore_shape:
return bounds.values.ravel()
if not bounds.shape[:-1] == coord.shape:
bounds = self.ds.isel(**self.get_idims(coord))
try:
return self._get_plotbounds_from_cf(coord, bounds)
except ValueError as e:
warn((e.message if six.PY2 else str(e)) +
" Bounds are calculated automatically!")
return self._infer_interval_breaks(coord, kind=kind) | [
"def",
"get_plotbounds",
"(",
"self",
",",
"coord",
",",
"kind",
"=",
"None",
",",
"ignore_shape",
"=",
"False",
")",
":",
"if",
"'bounds'",
"in",
"coord",
".",
"attrs",
":",
"bounds",
"=",
"self",
".",
"ds",
".",
"coords",
"[",
"coord",
".",
"attrs"... | Get the bounds of a coordinate
This method first checks the ``'bounds'`` attribute of the given
`coord` and if it fails, it calculates them.
Parameters
----------
coord: xarray.Coordinate
The coordinate to get the bounds for
kind: str
The interpolation method (see :func:`scipy.interpolate.interp1d`)
that is used in case of a 2-dimensional coordinate
ignore_shape: bool
If True and the `coord` has a ``'bounds'`` attribute, this
attribute is returned without further check. Otherwise it is tried
to bring the ``'bounds'`` into a format suitable for (e.g.) the
:func:`matplotlib.pyplot.pcolormesh` function.
Returns
-------
bounds: np.ndarray
The bounds with the same number of dimensions as `coord` but one
additional array (i.e. if `coord` has shape (4, ), `bounds` will
have shape (5, ) and if `coord` has shape (4, 5), `bounds` will
have shape (5, 6) | [
"Get",
"the",
"bounds",
"of",
"a",
"coordinate"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1310-L1348 | train | 43,382 |
Chilipp/psyplot | psyplot/data.py | CFDecoder._get_plotbounds_from_cf | def _get_plotbounds_from_cf(coord, bounds):
"""
Get plot bounds from the bounds stored as defined by CFConventions
Parameters
----------
coord: xarray.Coordinate
The coordinate to get the bounds for
bounds: xarray.DataArray
The bounds as inferred from the attributes of the given `coord`
Returns
-------
%(CFDecoder.get_plotbounds.returns)s
Notes
-----
this currently only works for rectilinear grids"""
if bounds.shape[:-1] != coord.shape or bounds.shape[-1] != 2:
raise ValueError(
"Cannot interprete bounds with shape {0} for {1} "
"coordinate with shape {2}.".format(
bounds.shape, coord.name, coord.shape))
ret = np.zeros(tuple(map(lambda i: i+1, coord.shape)))
ret[tuple(map(slice, coord.shape))] = bounds[..., 0]
last_slices = tuple(slice(-1, None) for _ in coord.shape)
ret[last_slices] = bounds[tuple(chain(last_slices, [1]))]
return ret | python | def _get_plotbounds_from_cf(coord, bounds):
"""
Get plot bounds from the bounds stored as defined by CFConventions
Parameters
----------
coord: xarray.Coordinate
The coordinate to get the bounds for
bounds: xarray.DataArray
The bounds as inferred from the attributes of the given `coord`
Returns
-------
%(CFDecoder.get_plotbounds.returns)s
Notes
-----
this currently only works for rectilinear grids"""
if bounds.shape[:-1] != coord.shape or bounds.shape[-1] != 2:
raise ValueError(
"Cannot interprete bounds with shape {0} for {1} "
"coordinate with shape {2}.".format(
bounds.shape, coord.name, coord.shape))
ret = np.zeros(tuple(map(lambda i: i+1, coord.shape)))
ret[tuple(map(slice, coord.shape))] = bounds[..., 0]
last_slices = tuple(slice(-1, None) for _ in coord.shape)
ret[last_slices] = bounds[tuple(chain(last_slices, [1]))]
return ret | [
"def",
"_get_plotbounds_from_cf",
"(",
"coord",
",",
"bounds",
")",
":",
"if",
"bounds",
".",
"shape",
"[",
":",
"-",
"1",
"]",
"!=",
"coord",
".",
"shape",
"or",
"bounds",
".",
"shape",
"[",
"-",
"1",
"]",
"!=",
"2",
":",
"raise",
"ValueError",
"(... | Get plot bounds from the bounds stored as defined by CFConventions
Parameters
----------
coord: xarray.Coordinate
The coordinate to get the bounds for
bounds: xarray.DataArray
The bounds as inferred from the attributes of the given `coord`
Returns
-------
%(CFDecoder.get_plotbounds.returns)s
Notes
-----
this currently only works for rectilinear grids | [
"Get",
"plot",
"bounds",
"from",
"the",
"bounds",
"stored",
"as",
"defined",
"by",
"CFConventions"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1352-L1380 | train | 43,383 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.get_triangles | def get_triangles(self, var, coords=None, convert_radian=True,
copy=False, src_crs=None, target_crs=None,
nans=None, stacklevel=1):
"""
Get the triangles for the variable
Parameters
----------
var: xarray.Variable or xarray.DataArray
The variable to use
coords: dict
Alternative coordinates to use. If None, the coordinates of the
:attr:`ds` dataset are used
convert_radian: bool
If True and the coordinate has units in 'radian', those are
converted to degrees
copy: bool
If True, vertice arrays are copied
src_crs: cartopy.crs.Crs
The source projection of the data. If not None, a transformation
to the given `target_crs` will be done
target_crs: cartopy.crs.Crs
The target projection for which the triangles shall be transformed.
Must only be provided if the `src_crs` is not None.
%(CFDecoder._check_triangular_bounds.parameters.nans)s
Returns
-------
matplotlib.tri.Triangulation
The spatial triangles of the variable
Raises
------
ValueError
If `src_crs` is not None and `target_crs` is None"""
warn("The 'get_triangles' method is depreceated and will be removed "
"soon! Use the 'get_cell_node_coord' method!",
DeprecationWarning, stacklevel=stacklevel)
from matplotlib.tri import Triangulation
def get_vertices(axis):
bounds = self._check_triangular_bounds(var, coords=coords,
axis=axis, nans=nans)[1]
if coords is not None:
bounds = coords.get(bounds.name, bounds)
vertices = bounds.values.ravel()
if convert_radian:
coord = getattr(self, 'get_' + axis)(var)
if coord.attrs.get('units') == 'radian':
vertices = vertices * 180. / np.pi
return vertices if not copy else vertices.copy()
if coords is None:
coords = self.ds.coords
xvert = get_vertices('x')
yvert = get_vertices('y')
if src_crs is not None and src_crs != target_crs:
if target_crs is None:
raise ValueError(
"Found %s for the source crs but got None for the "
"target_crs!" % (src_crs, ))
arr = target_crs.transform_points(src_crs, xvert, yvert)
xvert = arr[:, 0]
yvert = arr[:, 1]
triangles = np.reshape(range(len(xvert)), (len(xvert) // 3, 3))
return Triangulation(xvert, yvert, triangles) | python | def get_triangles(self, var, coords=None, convert_radian=True,
copy=False, src_crs=None, target_crs=None,
nans=None, stacklevel=1):
"""
Get the triangles for the variable
Parameters
----------
var: xarray.Variable or xarray.DataArray
The variable to use
coords: dict
Alternative coordinates to use. If None, the coordinates of the
:attr:`ds` dataset are used
convert_radian: bool
If True and the coordinate has units in 'radian', those are
converted to degrees
copy: bool
If True, vertice arrays are copied
src_crs: cartopy.crs.Crs
The source projection of the data. If not None, a transformation
to the given `target_crs` will be done
target_crs: cartopy.crs.Crs
The target projection for which the triangles shall be transformed.
Must only be provided if the `src_crs` is not None.
%(CFDecoder._check_triangular_bounds.parameters.nans)s
Returns
-------
matplotlib.tri.Triangulation
The spatial triangles of the variable
Raises
------
ValueError
If `src_crs` is not None and `target_crs` is None"""
warn("The 'get_triangles' method is depreceated and will be removed "
"soon! Use the 'get_cell_node_coord' method!",
DeprecationWarning, stacklevel=stacklevel)
from matplotlib.tri import Triangulation
def get_vertices(axis):
bounds = self._check_triangular_bounds(var, coords=coords,
axis=axis, nans=nans)[1]
if coords is not None:
bounds = coords.get(bounds.name, bounds)
vertices = bounds.values.ravel()
if convert_radian:
coord = getattr(self, 'get_' + axis)(var)
if coord.attrs.get('units') == 'radian':
vertices = vertices * 180. / np.pi
return vertices if not copy else vertices.copy()
if coords is None:
coords = self.ds.coords
xvert = get_vertices('x')
yvert = get_vertices('y')
if src_crs is not None and src_crs != target_crs:
if target_crs is None:
raise ValueError(
"Found %s for the source crs but got None for the "
"target_crs!" % (src_crs, ))
arr = target_crs.transform_points(src_crs, xvert, yvert)
xvert = arr[:, 0]
yvert = arr[:, 1]
triangles = np.reshape(range(len(xvert)), (len(xvert) // 3, 3))
return Triangulation(xvert, yvert, triangles) | [
"def",
"get_triangles",
"(",
"self",
",",
"var",
",",
"coords",
"=",
"None",
",",
"convert_radian",
"=",
"True",
",",
"copy",
"=",
"False",
",",
"src_crs",
"=",
"None",
",",
"target_crs",
"=",
"None",
",",
"nans",
"=",
"None",
",",
"stacklevel",
"=",
... | Get the triangles for the variable
Parameters
----------
var: xarray.Variable or xarray.DataArray
The variable to use
coords: dict
Alternative coordinates to use. If None, the coordinates of the
:attr:`ds` dataset are used
convert_radian: bool
If True and the coordinate has units in 'radian', those are
converted to degrees
copy: bool
If True, vertice arrays are copied
src_crs: cartopy.crs.Crs
The source projection of the data. If not None, a transformation
to the given `target_crs` will be done
target_crs: cartopy.crs.Crs
The target projection for which the triangles shall be transformed.
Must only be provided if the `src_crs` is not None.
%(CFDecoder._check_triangular_bounds.parameters.nans)s
Returns
-------
matplotlib.tri.Triangulation
The spatial triangles of the variable
Raises
------
ValueError
If `src_crs` is not None and `target_crs` is None | [
"Get",
"the",
"triangles",
"for",
"the",
"variable"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1388-L1454 | train | 43,384 |
Chilipp/psyplot | psyplot/data.py | CFDecoder._infer_interval_breaks | def _infer_interval_breaks(coord, kind=None):
"""
Interpolate the bounds from the data in coord
Parameters
----------
%(CFDecoder.get_plotbounds.parameters.no_ignore_shape)s
Returns
-------
%(CFDecoder.get_plotbounds.returns)s
Notes
-----
this currently only works for rectilinear grids"""
if coord.ndim == 1:
return _infer_interval_breaks(coord)
elif coord.ndim == 2:
from scipy.interpolate import interp2d
kind = kind or rcParams['decoder.interp_kind']
y, x = map(np.arange, coord.shape)
new_x, new_y = map(_infer_interval_breaks, [x, y])
coord = np.asarray(coord)
return interp2d(x, y, coord, kind=kind, copy=False)(new_x, new_y) | python | def _infer_interval_breaks(coord, kind=None):
"""
Interpolate the bounds from the data in coord
Parameters
----------
%(CFDecoder.get_plotbounds.parameters.no_ignore_shape)s
Returns
-------
%(CFDecoder.get_plotbounds.returns)s
Notes
-----
this currently only works for rectilinear grids"""
if coord.ndim == 1:
return _infer_interval_breaks(coord)
elif coord.ndim == 2:
from scipy.interpolate import interp2d
kind = kind or rcParams['decoder.interp_kind']
y, x = map(np.arange, coord.shape)
new_x, new_y = map(_infer_interval_breaks, [x, y])
coord = np.asarray(coord)
return interp2d(x, y, coord, kind=kind, copy=False)(new_x, new_y) | [
"def",
"_infer_interval_breaks",
"(",
"coord",
",",
"kind",
"=",
"None",
")",
":",
"if",
"coord",
".",
"ndim",
"==",
"1",
":",
"return",
"_infer_interval_breaks",
"(",
"coord",
")",
"elif",
"coord",
".",
"ndim",
"==",
"2",
":",
"from",
"scipy",
".",
"i... | Interpolate the bounds from the data in coord
Parameters
----------
%(CFDecoder.get_plotbounds.parameters.no_ignore_shape)s
Returns
-------
%(CFDecoder.get_plotbounds.returns)s
Notes
-----
this currently only works for rectilinear grids | [
"Interpolate",
"the",
"bounds",
"from",
"the",
"data",
"in",
"coord"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1460-L1483 | train | 43,385 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.correct_dims | def correct_dims(self, var, dims={}, remove=True):
"""Expands the dimensions to match the dims in the variable
Parameters
----------
var: xarray.Variable
The variable to get the data for
dims: dict
a mapping from dimension to the slices
remove: bool
If True, dimensions in `dims` that are not in the dimensions of
`var` are removed"""
method_mapping = {'x': self.get_xname,
'z': self.get_zname, 't': self.get_tname}
dims = dict(dims)
if self.is_unstructured(var): # we assume a one-dimensional grid
method_mapping['y'] = self.get_xname
else:
method_mapping['y'] = self.get_yname
for key in six.iterkeys(dims.copy()):
if key in method_mapping and key not in var.dims:
dim_name = method_mapping[key](var, self.ds.coords)
if dim_name in dims:
dims.pop(key)
else:
new_name = method_mapping[key](var)
if new_name is not None:
dims[new_name] = dims.pop(key)
# now remove the unnecessary dimensions
if remove:
for key in set(dims).difference(var.dims):
dims.pop(key)
self.logger.debug(
"Could not find a dimensions matching %s in variable %s!",
key, var)
return dims | python | def correct_dims(self, var, dims={}, remove=True):
"""Expands the dimensions to match the dims in the variable
Parameters
----------
var: xarray.Variable
The variable to get the data for
dims: dict
a mapping from dimension to the slices
remove: bool
If True, dimensions in `dims` that are not in the dimensions of
`var` are removed"""
method_mapping = {'x': self.get_xname,
'z': self.get_zname, 't': self.get_tname}
dims = dict(dims)
if self.is_unstructured(var): # we assume a one-dimensional grid
method_mapping['y'] = self.get_xname
else:
method_mapping['y'] = self.get_yname
for key in six.iterkeys(dims.copy()):
if key in method_mapping and key not in var.dims:
dim_name = method_mapping[key](var, self.ds.coords)
if dim_name in dims:
dims.pop(key)
else:
new_name = method_mapping[key](var)
if new_name is not None:
dims[new_name] = dims.pop(key)
# now remove the unnecessary dimensions
if remove:
for key in set(dims).difference(var.dims):
dims.pop(key)
self.logger.debug(
"Could not find a dimensions matching %s in variable %s!",
key, var)
return dims | [
"def",
"correct_dims",
"(",
"self",
",",
"var",
",",
"dims",
"=",
"{",
"}",
",",
"remove",
"=",
"True",
")",
":",
"method_mapping",
"=",
"{",
"'x'",
":",
"self",
".",
"get_xname",
",",
"'z'",
":",
"self",
".",
"get_zname",
",",
"'t'",
":",
"self",
... | Expands the dimensions to match the dims in the variable
Parameters
----------
var: xarray.Variable
The variable to get the data for
dims: dict
a mapping from dimension to the slices
remove: bool
If True, dimensions in `dims` that are not in the dimensions of
`var` are removed | [
"Expands",
"the",
"dimensions",
"to",
"match",
"the",
"dims",
"in",
"the",
"variable"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1541-L1576 | train | 43,386 |
Chilipp/psyplot | psyplot/data.py | CFDecoder.standardize_dims | def standardize_dims(self, var, dims={}):
"""Replace the coordinate names through x, y, z and t
Parameters
----------
var: xarray.Variable
The variable to use the dimensions of
dims: dict
The dictionary to use for replacing the original dimensions
Returns
-------
dict
The dictionary with replaced dimensions"""
dims = dict(dims)
name_map = {self.get_xname(var, self.ds.coords): 'x',
self.get_yname(var, self.ds.coords): 'y',
self.get_zname(var, self.ds.coords): 'z',
self.get_tname(var, self.ds.coords): 't'}
dims = dict(dims)
for dim in set(dims).intersection(name_map):
dims[name_map[dim]] = dims.pop(dim)
return dims | python | def standardize_dims(self, var, dims={}):
"""Replace the coordinate names through x, y, z and t
Parameters
----------
var: xarray.Variable
The variable to use the dimensions of
dims: dict
The dictionary to use for replacing the original dimensions
Returns
-------
dict
The dictionary with replaced dimensions"""
dims = dict(dims)
name_map = {self.get_xname(var, self.ds.coords): 'x',
self.get_yname(var, self.ds.coords): 'y',
self.get_zname(var, self.ds.coords): 'z',
self.get_tname(var, self.ds.coords): 't'}
dims = dict(dims)
for dim in set(dims).intersection(name_map):
dims[name_map[dim]] = dims.pop(dim)
return dims | [
"def",
"standardize_dims",
"(",
"self",
",",
"var",
",",
"dims",
"=",
"{",
"}",
")",
":",
"dims",
"=",
"dict",
"(",
"dims",
")",
"name_map",
"=",
"{",
"self",
".",
"get_xname",
"(",
"var",
",",
"self",
".",
"ds",
".",
"coords",
")",
":",
"'x'",
... | Replace the coordinate names through x, y, z and t
Parameters
----------
var: xarray.Variable
The variable to use the dimensions of
dims: dict
The dictionary to use for replacing the original dimensions
Returns
-------
dict
The dictionary with replaced dimensions | [
"Replace",
"the",
"coordinate",
"names",
"through",
"x",
"y",
"z",
"and",
"t"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1578-L1600 | train | 43,387 |
Chilipp/psyplot | psyplot/data.py | UGridDecoder.get_mesh | def get_mesh(self, var, coords=None):
"""Get the mesh variable for the given `var`
Parameters
----------
var: xarray.Variable
The data source whith the ``'mesh'`` attribute
coords: dict
The coordinates to use. If None, the coordinates of the dataset of
this decoder is used
Returns
-------
xarray.Coordinate
The mesh coordinate"""
mesh = var.attrs.get('mesh')
if mesh is None:
return None
if coords is None:
coords = self.ds.coords
return coords.get(mesh, self.ds.coords.get(mesh)) | python | def get_mesh(self, var, coords=None):
"""Get the mesh variable for the given `var`
Parameters
----------
var: xarray.Variable
The data source whith the ``'mesh'`` attribute
coords: dict
The coordinates to use. If None, the coordinates of the dataset of
this decoder is used
Returns
-------
xarray.Coordinate
The mesh coordinate"""
mesh = var.attrs.get('mesh')
if mesh is None:
return None
if coords is None:
coords = self.ds.coords
return coords.get(mesh, self.ds.coords.get(mesh)) | [
"def",
"get_mesh",
"(",
"self",
",",
"var",
",",
"coords",
"=",
"None",
")",
":",
"mesh",
"=",
"var",
".",
"attrs",
".",
"get",
"(",
"'mesh'",
")",
"if",
"mesh",
"is",
"None",
":",
"return",
"None",
"if",
"coords",
"is",
"None",
":",
"coords",
"=... | Get the mesh variable for the given `var`
Parameters
----------
var: xarray.Variable
The data source whith the ``'mesh'`` attribute
coords: dict
The coordinates to use. If None, the coordinates of the dataset of
this decoder is used
Returns
-------
xarray.Coordinate
The mesh coordinate | [
"Get",
"the",
"mesh",
"variable",
"for",
"the",
"given",
"var"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1621-L1641 | train | 43,388 |
Chilipp/psyplot | psyplot/data.py | UGridDecoder.get_triangles | def get_triangles(self, var, coords=None, convert_radian=True, copy=False,
src_crs=None, target_crs=None, nans=None, stacklevel=1):
"""
Get the of the given coordinate.
Parameters
----------
%(CFDecoder.get_triangles.parameters)s
Returns
-------
%(CFDecoder.get_triangles.returns)s
Notes
-----
If the ``'location'`` attribute is set to ``'node'``, a delaunay
triangulation is performed using the
:class:`matplotlib.tri.Triangulation` class.
.. todo::
Implement the visualization for UGrid data shown on the edge of the
triangles"""
warn("The 'get_triangles' method is depreceated and will be removed "
"soon! Use the 'get_cell_node_coord' method!",
DeprecationWarning, stacklevel=stacklevel)
from matplotlib.tri import Triangulation
if coords is None:
coords = self.ds.coords
def get_coord(coord):
return coords.get(coord, self.ds.coords.get(coord))
mesh = self.get_mesh(var, coords)
nodes = self.get_nodes(mesh, coords)
if any(n is None for n in nodes):
raise ValueError("Could not find the nodes variables!")
xvert, yvert = nodes
xvert = xvert.values
yvert = yvert.values
loc = var.attrs.get('location', 'face')
if loc == 'face':
triangles = get_coord(
mesh.attrs.get('face_node_connectivity', '')).values
if triangles is None:
raise ValueError(
"Could not find the connectivity information!")
elif loc == 'node':
triangles = None
else:
raise ValueError(
"Could not interprete location attribute (%s) of mesh "
"variable %s!" % (loc, mesh.name))
if convert_radian:
for coord in nodes:
if coord.attrs.get('units') == 'radian':
coord = coord * 180. / np.pi
if src_crs is not None and src_crs != target_crs:
if target_crs is None:
raise ValueError(
"Found %s for the source crs but got None for the "
"target_crs!" % (src_crs, ))
xvert = xvert[triangles].ravel()
yvert = yvert[triangles].ravel()
arr = target_crs.transform_points(src_crs, xvert, yvert)
xvert = arr[:, 0]
yvert = arr[:, 1]
if loc == 'face':
triangles = np.reshape(range(len(xvert)), (len(xvert) // 3,
3))
return Triangulation(xvert, yvert, triangles) | python | def get_triangles(self, var, coords=None, convert_radian=True, copy=False,
src_crs=None, target_crs=None, nans=None, stacklevel=1):
"""
Get the of the given coordinate.
Parameters
----------
%(CFDecoder.get_triangles.parameters)s
Returns
-------
%(CFDecoder.get_triangles.returns)s
Notes
-----
If the ``'location'`` attribute is set to ``'node'``, a delaunay
triangulation is performed using the
:class:`matplotlib.tri.Triangulation` class.
.. todo::
Implement the visualization for UGrid data shown on the edge of the
triangles"""
warn("The 'get_triangles' method is depreceated and will be removed "
"soon! Use the 'get_cell_node_coord' method!",
DeprecationWarning, stacklevel=stacklevel)
from matplotlib.tri import Triangulation
if coords is None:
coords = self.ds.coords
def get_coord(coord):
return coords.get(coord, self.ds.coords.get(coord))
mesh = self.get_mesh(var, coords)
nodes = self.get_nodes(mesh, coords)
if any(n is None for n in nodes):
raise ValueError("Could not find the nodes variables!")
xvert, yvert = nodes
xvert = xvert.values
yvert = yvert.values
loc = var.attrs.get('location', 'face')
if loc == 'face':
triangles = get_coord(
mesh.attrs.get('face_node_connectivity', '')).values
if triangles is None:
raise ValueError(
"Could not find the connectivity information!")
elif loc == 'node':
triangles = None
else:
raise ValueError(
"Could not interprete location attribute (%s) of mesh "
"variable %s!" % (loc, mesh.name))
if convert_radian:
for coord in nodes:
if coord.attrs.get('units') == 'radian':
coord = coord * 180. / np.pi
if src_crs is not None and src_crs != target_crs:
if target_crs is None:
raise ValueError(
"Found %s for the source crs but got None for the "
"target_crs!" % (src_crs, ))
xvert = xvert[triangles].ravel()
yvert = yvert[triangles].ravel()
arr = target_crs.transform_points(src_crs, xvert, yvert)
xvert = arr[:, 0]
yvert = arr[:, 1]
if loc == 'face':
triangles = np.reshape(range(len(xvert)), (len(xvert) // 3,
3))
return Triangulation(xvert, yvert, triangles) | [
"def",
"get_triangles",
"(",
"self",
",",
"var",
",",
"coords",
"=",
"None",
",",
"convert_radian",
"=",
"True",
",",
"copy",
"=",
"False",
",",
"src_crs",
"=",
"None",
",",
"target_crs",
"=",
"None",
",",
"nans",
"=",
"None",
",",
"stacklevel",
"=",
... | Get the of the given coordinate.
Parameters
----------
%(CFDecoder.get_triangles.parameters)s
Returns
-------
%(CFDecoder.get_triangles.returns)s
Notes
-----
If the ``'location'`` attribute is set to ``'node'``, a delaunay
triangulation is performed using the
:class:`matplotlib.tri.Triangulation` class.
.. todo::
Implement the visualization for UGrid data shown on the edge of the
triangles | [
"Get",
"the",
"of",
"the",
"given",
"coordinate",
"."
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1662-L1734 | train | 43,389 |
Chilipp/psyplot | psyplot/data.py | UGridDecoder.decode_coords | def decode_coords(ds, gridfile=None):
"""
Reimplemented to set the mesh variables as coordinates
Parameters
----------
%(CFDecoder.decode_coords.parameters)s
Returns
-------
%(CFDecoder.decode_coords.returns)s"""
extra_coords = set(ds.coords)
for var in six.itervalues(ds.variables):
if 'mesh' in var.attrs:
mesh = var.attrs['mesh']
if mesh not in extra_coords:
extra_coords.add(mesh)
try:
mesh_var = ds.variables[mesh]
except KeyError:
warn('Could not find mesh variable %s' % mesh)
continue
if 'node_coordinates' in mesh_var.attrs:
extra_coords.update(
mesh_var.attrs['node_coordinates'].split())
if 'face_node_connectivity' in mesh_var.attrs:
extra_coords.add(
mesh_var.attrs['face_node_connectivity'])
if gridfile is not None and not isinstance(gridfile, xr.Dataset):
gridfile = open_dataset(gridfile)
ds.update({k: v for k, v in six.iteritems(gridfile.variables)
if k in extra_coords})
if xr_version < (0, 11):
ds.set_coords(extra_coords.intersection(ds.variables),
inplace=True)
else:
ds._coord_names.update(extra_coords.intersection(ds.variables))
return ds | python | def decode_coords(ds, gridfile=None):
"""
Reimplemented to set the mesh variables as coordinates
Parameters
----------
%(CFDecoder.decode_coords.parameters)s
Returns
-------
%(CFDecoder.decode_coords.returns)s"""
extra_coords = set(ds.coords)
for var in six.itervalues(ds.variables):
if 'mesh' in var.attrs:
mesh = var.attrs['mesh']
if mesh not in extra_coords:
extra_coords.add(mesh)
try:
mesh_var = ds.variables[mesh]
except KeyError:
warn('Could not find mesh variable %s' % mesh)
continue
if 'node_coordinates' in mesh_var.attrs:
extra_coords.update(
mesh_var.attrs['node_coordinates'].split())
if 'face_node_connectivity' in mesh_var.attrs:
extra_coords.add(
mesh_var.attrs['face_node_connectivity'])
if gridfile is not None and not isinstance(gridfile, xr.Dataset):
gridfile = open_dataset(gridfile)
ds.update({k: v for k, v in six.iteritems(gridfile.variables)
if k in extra_coords})
if xr_version < (0, 11):
ds.set_coords(extra_coords.intersection(ds.variables),
inplace=True)
else:
ds._coord_names.update(extra_coords.intersection(ds.variables))
return ds | [
"def",
"decode_coords",
"(",
"ds",
",",
"gridfile",
"=",
"None",
")",
":",
"extra_coords",
"=",
"set",
"(",
"ds",
".",
"coords",
")",
"for",
"var",
"in",
"six",
".",
"itervalues",
"(",
"ds",
".",
"variables",
")",
":",
"if",
"'mesh'",
"in",
"var",
... | Reimplemented to set the mesh variables as coordinates
Parameters
----------
%(CFDecoder.decode_coords.parameters)s
Returns
-------
%(CFDecoder.decode_coords.returns)s | [
"Reimplemented",
"to",
"set",
"the",
"mesh",
"variables",
"as",
"coordinates"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1803-L1840 | train | 43,390 |
Chilipp/psyplot | psyplot/data.py | UGridDecoder.get_nodes | def get_nodes(self, coord, coords):
"""Get the variables containing the definition of the nodes
Parameters
----------
coord: xarray.Coordinate
The mesh variable
coords: dict
The coordinates to use to get node coordinates"""
def get_coord(coord):
return coords.get(coord, self.ds.coords.get(coord))
return list(map(get_coord,
coord.attrs.get('node_coordinates', '').split()[:2])) | python | def get_nodes(self, coord, coords):
"""Get the variables containing the definition of the nodes
Parameters
----------
coord: xarray.Coordinate
The mesh variable
coords: dict
The coordinates to use to get node coordinates"""
def get_coord(coord):
return coords.get(coord, self.ds.coords.get(coord))
return list(map(get_coord,
coord.attrs.get('node_coordinates', '').split()[:2])) | [
"def",
"get_nodes",
"(",
"self",
",",
"coord",
",",
"coords",
")",
":",
"def",
"get_coord",
"(",
"coord",
")",
":",
"return",
"coords",
".",
"get",
"(",
"coord",
",",
"self",
".",
"ds",
".",
"coords",
".",
"get",
"(",
"coord",
")",
")",
"return",
... | Get the variables containing the definition of the nodes
Parameters
----------
coord: xarray.Coordinate
The mesh variable
coords: dict
The coordinates to use to get node coordinates | [
"Get",
"the",
"variables",
"containing",
"the",
"definition",
"of",
"the",
"nodes"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1842-L1854 | train | 43,391 |
Chilipp/psyplot | psyplot/data.py | UGridDecoder.get_x | def get_x(self, var, coords=None):
"""
Get the centers of the triangles in the x-dimension
Parameters
----------
%(CFDecoder.get_y.parameters)s
Returns
-------
%(CFDecoder.get_y.returns)s"""
if coords is None:
coords = self.ds.coords
# first we try the super class
ret = super(UGridDecoder, self).get_x(var, coords)
# but if that doesn't work because we get the variable name in the
# dimension of `var`, we use the means of the triangles
if ret is None or ret.name in var.dims:
bounds = self.get_cell_node_coord(var, axis='x', coords=coords)
if bounds is not None:
centers = bounds.mean(axis=-1)
x = self.get_nodes(self.get_mesh(var, coords), coords)[0]
try:
cls = xr.IndexVariable
except AttributeError: # xarray < 0.9
cls = xr.Coordinate
return cls(x.name, centers, attrs=x.attrs.copy()) | python | def get_x(self, var, coords=None):
"""
Get the centers of the triangles in the x-dimension
Parameters
----------
%(CFDecoder.get_y.parameters)s
Returns
-------
%(CFDecoder.get_y.returns)s"""
if coords is None:
coords = self.ds.coords
# first we try the super class
ret = super(UGridDecoder, self).get_x(var, coords)
# but if that doesn't work because we get the variable name in the
# dimension of `var`, we use the means of the triangles
if ret is None or ret.name in var.dims:
bounds = self.get_cell_node_coord(var, axis='x', coords=coords)
if bounds is not None:
centers = bounds.mean(axis=-1)
x = self.get_nodes(self.get_mesh(var, coords), coords)[0]
try:
cls = xr.IndexVariable
except AttributeError: # xarray < 0.9
cls = xr.Coordinate
return cls(x.name, centers, attrs=x.attrs.copy()) | [
"def",
"get_x",
"(",
"self",
",",
"var",
",",
"coords",
"=",
"None",
")",
":",
"if",
"coords",
"is",
"None",
":",
"coords",
"=",
"self",
".",
"ds",
".",
"coords",
"# first we try the super class",
"ret",
"=",
"super",
"(",
"UGridDecoder",
",",
"self",
... | Get the centers of the triangles in the x-dimension
Parameters
----------
%(CFDecoder.get_y.parameters)s
Returns
-------
%(CFDecoder.get_y.returns)s | [
"Get",
"the",
"centers",
"of",
"the",
"triangles",
"in",
"the",
"x",
"-",
"dimension"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1857-L1883 | train | 43,392 |
Chilipp/psyplot | psyplot/data.py | InteractiveBase.plot | def plot(self):
"""An object to visualize this data object
To make a 2D-plot with the :mod:`psy-simple <psy_simple.plugin>`
plugin, you can just type
.. code-block:: python
plotter = da.psy.plot.plot2d()
It will create a new :class:`psyplot.plotter.Plotter` instance with the
extracted and visualized data.
See Also
--------
psyplot.project.DataArrayPlotter: for the different plot methods"""
if self._plot is None:
import psyplot.project as psy
self._plot = psy.DataArrayPlotter(self)
return self._plot | python | def plot(self):
"""An object to visualize this data object
To make a 2D-plot with the :mod:`psy-simple <psy_simple.plugin>`
plugin, you can just type
.. code-block:: python
plotter = da.psy.plot.plot2d()
It will create a new :class:`psyplot.plotter.Plotter` instance with the
extracted and visualized data.
See Also
--------
psyplot.project.DataArrayPlotter: for the different plot methods"""
if self._plot is None:
import psyplot.project as psy
self._plot = psy.DataArrayPlotter(self)
return self._plot | [
"def",
"plot",
"(",
"self",
")",
":",
"if",
"self",
".",
"_plot",
"is",
"None",
":",
"import",
"psyplot",
".",
"project",
"as",
"psy",
"self",
".",
"_plot",
"=",
"psy",
".",
"DataArrayPlotter",
"(",
"self",
")",
"return",
"self",
".",
"_plot"
] | An object to visualize this data object
To make a 2D-plot with the :mod:`psy-simple <psy_simple.plugin>`
plugin, you can just type
.. code-block:: python
plotter = da.psy.plot.plot2d()
It will create a new :class:`psyplot.plotter.Plotter` instance with the
extracted and visualized data.
See Also
--------
psyplot.project.DataArrayPlotter: for the different plot methods | [
"An",
"object",
"to",
"visualize",
"this",
"data",
"object"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L2059-L2078 | train | 43,393 |
Chilipp/psyplot | psyplot/data.py | InteractiveBase._register_update | def _register_update(self, replot=False, fmt={}, force=False,
todefault=False):
"""
Register new formatoptions for updating
Parameters
----------
replot: bool
Boolean that determines whether the data specific formatoptions
shall be updated in any case or not. Note, if `dims` is not empty
or any coordinate keyword is in ``**kwargs``, this will be set to
True automatically
fmt: dict
Keys may be any valid formatoption of the formatoptions in the
:attr:`plotter`
force: str, list of str or bool
If formatoption key (i.e. string) or list of formatoption keys,
thery are definitely updated whether they changed or not.
If True, all the given formatoptions in this call of the are
:meth:`update` method are updated
todefault: bool
If True, all changed formatoptions (except the registered ones)
are updated to their default value as stored in the
:attr:`~psyplot.plotter.Plotter.rc` attribute
See Also
--------
start_update"""
self.replot = self.replot or replot
if self.plotter is not None:
self.plotter._register_update(replot=self.replot, fmt=fmt,
force=force, todefault=todefault) | python | def _register_update(self, replot=False, fmt={}, force=False,
todefault=False):
"""
Register new formatoptions for updating
Parameters
----------
replot: bool
Boolean that determines whether the data specific formatoptions
shall be updated in any case or not. Note, if `dims` is not empty
or any coordinate keyword is in ``**kwargs``, this will be set to
True automatically
fmt: dict
Keys may be any valid formatoption of the formatoptions in the
:attr:`plotter`
force: str, list of str or bool
If formatoption key (i.e. string) or list of formatoption keys,
thery are definitely updated whether they changed or not.
If True, all the given formatoptions in this call of the are
:meth:`update` method are updated
todefault: bool
If True, all changed formatoptions (except the registered ones)
are updated to their default value as stored in the
:attr:`~psyplot.plotter.Plotter.rc` attribute
See Also
--------
start_update"""
self.replot = self.replot or replot
if self.plotter is not None:
self.plotter._register_update(replot=self.replot, fmt=fmt,
force=force, todefault=todefault) | [
"def",
"_register_update",
"(",
"self",
",",
"replot",
"=",
"False",
",",
"fmt",
"=",
"{",
"}",
",",
"force",
"=",
"False",
",",
"todefault",
"=",
"False",
")",
":",
"self",
".",
"replot",
"=",
"self",
".",
"replot",
"or",
"replot",
"if",
"self",
"... | Register new formatoptions for updating
Parameters
----------
replot: bool
Boolean that determines whether the data specific formatoptions
shall be updated in any case or not. Note, if `dims` is not empty
or any coordinate keyword is in ``**kwargs``, this will be set to
True automatically
fmt: dict
Keys may be any valid formatoption of the formatoptions in the
:attr:`plotter`
force: str, list of str or bool
If formatoption key (i.e. string) or list of formatoption keys,
thery are definitely updated whether they changed or not.
If True, all the given formatoptions in this call of the are
:meth:`update` method are updated
todefault: bool
If True, all changed formatoptions (except the registered ones)
are updated to their default value as stored in the
:attr:`~psyplot.plotter.Plotter.rc` attribute
See Also
--------
start_update | [
"Register",
"new",
"formatoptions",
"for",
"updating"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L2192-L2223 | train | 43,394 |
Chilipp/psyplot | psyplot/data.py | ArrayList.dims_intersect | def dims_intersect(self):
"""Dimensions of the arrays in this list that are used in all arrays
"""
return set.intersection(*map(
set, (getattr(arr, 'dims_intersect', arr.dims) for arr in self))) | python | def dims_intersect(self):
"""Dimensions of the arrays in this list that are used in all arrays
"""
return set.intersection(*map(
set, (getattr(arr, 'dims_intersect', arr.dims) for arr in self))) | [
"def",
"dims_intersect",
"(",
"self",
")",
":",
"return",
"set",
".",
"intersection",
"(",
"*",
"map",
"(",
"set",
",",
"(",
"getattr",
"(",
"arr",
",",
"'dims_intersect'",
",",
"arr",
".",
"dims",
")",
"for",
"arr",
"in",
"self",
")",
")",
")"
] | Dimensions of the arrays in this list that are used in all arrays | [
"Dimensions",
"of",
"the",
"arrays",
"in",
"this",
"list",
"that",
"are",
"used",
"in",
"all",
"arrays"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L3197-L3201 | train | 43,395 |
Chilipp/psyplot | psyplot/data.py | ArrayList.names | def names(self):
"""Set of the variable in this list"""
ret = set()
for arr in self:
if isinstance(arr, InteractiveList):
ret.update(arr.names)
else:
ret.add(arr.name)
return ret | python | def names(self):
"""Set of the variable in this list"""
ret = set()
for arr in self:
if isinstance(arr, InteractiveList):
ret.update(arr.names)
else:
ret.add(arr.name)
return ret | [
"def",
"names",
"(",
"self",
")",
":",
"ret",
"=",
"set",
"(",
")",
"for",
"arr",
"in",
"self",
":",
"if",
"isinstance",
"(",
"arr",
",",
"InteractiveList",
")",
":",
"ret",
".",
"update",
"(",
"arr",
".",
"names",
")",
"else",
":",
"ret",
".",
... | Set of the variable in this list | [
"Set",
"of",
"the",
"variable",
"in",
"this",
"list"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L3222-L3230 | train | 43,396 |
Chilipp/psyplot | psyplot/data.py | ArrayList.all_names | def all_names(self):
"""The variable names for each of the arrays in this list"""
return [
_get_variable_names(arr) if not isinstance(arr, ArrayList) else
arr.all_names
for arr in self] | python | def all_names(self):
"""The variable names for each of the arrays in this list"""
return [
_get_variable_names(arr) if not isinstance(arr, ArrayList) else
arr.all_names
for arr in self] | [
"def",
"all_names",
"(",
"self",
")",
":",
"return",
"[",
"_get_variable_names",
"(",
"arr",
")",
"if",
"not",
"isinstance",
"(",
"arr",
",",
"ArrayList",
")",
"else",
"arr",
".",
"all_names",
"for",
"arr",
"in",
"self",
"]"
] | The variable names for each of the arrays in this list | [
"The",
"variable",
"names",
"for",
"each",
"of",
"the",
"arrays",
"in",
"this",
"list"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L3233-L3238 | train | 43,397 |
Chilipp/psyplot | psyplot/data.py | ArrayList.all_dims | def all_dims(self):
"""The dimensions for each of the arrays in this list"""
return [
_get_dims(arr) if not isinstance(arr, ArrayList) else
arr.all_dims
for arr in self] | python | def all_dims(self):
"""The dimensions for each of the arrays in this list"""
return [
_get_dims(arr) if not isinstance(arr, ArrayList) else
arr.all_dims
for arr in self] | [
"def",
"all_dims",
"(",
"self",
")",
":",
"return",
"[",
"_get_dims",
"(",
"arr",
")",
"if",
"not",
"isinstance",
"(",
"arr",
",",
"ArrayList",
")",
"else",
"arr",
".",
"all_dims",
"for",
"arr",
"in",
"self",
"]"
] | The dimensions for each of the arrays in this list | [
"The",
"dimensions",
"for",
"each",
"of",
"the",
"arrays",
"in",
"this",
"list"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L3241-L3246 | train | 43,398 |
Chilipp/psyplot | psyplot/data.py | ArrayList.is_unstructured | def is_unstructured(self):
"""A boolean for each array whether it is unstructured or not"""
return [
arr.psy.decoder.is_unstructured(arr)
if not isinstance(arr, ArrayList) else
arr.is_unstructured
for arr in self] | python | def is_unstructured(self):
"""A boolean for each array whether it is unstructured or not"""
return [
arr.psy.decoder.is_unstructured(arr)
if not isinstance(arr, ArrayList) else
arr.is_unstructured
for arr in self] | [
"def",
"is_unstructured",
"(",
"self",
")",
":",
"return",
"[",
"arr",
".",
"psy",
".",
"decoder",
".",
"is_unstructured",
"(",
"arr",
")",
"if",
"not",
"isinstance",
"(",
"arr",
",",
"ArrayList",
")",
"else",
"arr",
".",
"is_unstructured",
"for",
"arr",... | A boolean for each array whether it is unstructured or not | [
"A",
"boolean",
"for",
"each",
"array",
"whether",
"it",
"is",
"unstructured",
"or",
"not"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L3249-L3255 | train | 43,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.