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
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
NoviceLive/intellicoder | intellicoder/msbuild/builders.py | Builder.make_objs | def make_objs(names, out_dir=''):
"""
Make object file names for cl.exe and link.exe.
"""
objs = [replace_ext(name, '.obj') for name in names]
if out_dir:
objs = [os.path.join(out_dir, obj) for obj in objs]
return objs | python | def make_objs(names, out_dir=''):
"""
Make object file names for cl.exe and link.exe.
"""
objs = [replace_ext(name, '.obj') for name in names]
if out_dir:
objs = [os.path.join(out_dir, obj) for obj in objs]
return objs | [
"def",
"make_objs",
"(",
"names",
",",
"out_dir",
"=",
"''",
")",
":",
"objs",
"=",
"[",
"replace_ext",
"(",
"name",
",",
"'.obj'",
")",
"for",
"name",
"in",
"names",
"]",
"if",
"out_dir",
":",
"objs",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"obj",
")",
"for",
"obj",
"in",
"objs",
"]",
"return",
"objs"
]
| Make object file names for cl.exe and link.exe. | [
"Make",
"object",
"file",
"names",
"for",
"cl",
".",
"exe",
"and",
"link",
".",
"exe",
"."
]
| 6cac5ebfce65c370dbebe47756a1789b120ef982 | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/msbuild/builders.py#L129-L136 | train |
tgbugs/ontquery | ontquery/plugins/interlex_client.py | examples | def examples():
''' Examples of how to use. Default are that some functions are commented out in order
to not cause harm to existing metadata within the database.
'''
sci = InterLexClient(
api_key = os.environ.get('INTERLEX_API_KEY'),
base_url = 'https://beta.scicrunch.org/api/1/', # NEVER CHANGE
)
entity = {
'label': 'brain115',
'type': 'fde', # broken at the moment NEEDS PDE HARDCODED
'definition': 'Part of the central nervous system',
'comment': 'Cannot live without it',
'superclass': {
'ilx_id': 'ilx_0108124', # ILX ID for Organ
},
'synonyms': [
{
'literal': 'Encephalon'
},
{
'literal': 'Cerebro'
},
],
'existing_ids': [
{
'iri': 'http://uri.neuinfo.org/nif/nifstd/birnlex_796',
'curie': 'BIRNLEX:796',
},
],
}
simple_entity = {
'label': entity['label'],
'type': entity['type'], # broken at the moment NEEDS PDE HARDCODED
'definition': entity['definition'],
'comment': entity['comment'],
'superclass': entity['superclass']['ilx_id'],
'synonyms': [syn['literal'] for syn in entity['synonyms']],
'predicates': {'tmp_0381624': 'http://example_dbxref'}
}
annotation = {
'term_ilx_id': 'ilx_0101431', # brain ILX ID
'annotation_type_ilx_id': 'tmp_0381624', # hasDbXref ILX ID
'annotation_value': 'PMID:12345',
}
relationship = {
'entity1_ilx': 'ilx_0101431', # brain
'relationship_ilx': 'ilx_0115023', # Related to
'entity2_ilx': 'ilx_0108124', #organ
}
update_entity_data = {
'ilx_id': 'ilx_0101431',
'label': 'Brain',
'definition': 'update_test!!',
'type': 'fde',
'comment': 'test comment',
'superclass': 'ilx_0108124',
'synonyms': ['test', 'test2', 'test2'],
}
# resp = sci.delete_annotation(**{
# 'term_ilx_id': 'ilx_0101431', # brain ILX ID
# 'annotation_type_ilx_id': 'ilx_0115071', # hasConstraint ILX ID
# 'annotation_value': 'test_12345',
# })
relationship = {
'entity1_ilx': 'http://uri.interlex.org/base/ilx_0100001', # (R)N6 chemical ILX ID
'relationship_ilx': 'http://uri.interlex.org/base/ilx_0112772', # Afferent projection ILX ID
'entity2_ilx': 'http://uri.interlex.org/base/ilx_0100000', #1,2-Dibromo chemical ILX ID
} | python | def examples():
''' Examples of how to use. Default are that some functions are commented out in order
to not cause harm to existing metadata within the database.
'''
sci = InterLexClient(
api_key = os.environ.get('INTERLEX_API_KEY'),
base_url = 'https://beta.scicrunch.org/api/1/', # NEVER CHANGE
)
entity = {
'label': 'brain115',
'type': 'fde', # broken at the moment NEEDS PDE HARDCODED
'definition': 'Part of the central nervous system',
'comment': 'Cannot live without it',
'superclass': {
'ilx_id': 'ilx_0108124', # ILX ID for Organ
},
'synonyms': [
{
'literal': 'Encephalon'
},
{
'literal': 'Cerebro'
},
],
'existing_ids': [
{
'iri': 'http://uri.neuinfo.org/nif/nifstd/birnlex_796',
'curie': 'BIRNLEX:796',
},
],
}
simple_entity = {
'label': entity['label'],
'type': entity['type'], # broken at the moment NEEDS PDE HARDCODED
'definition': entity['definition'],
'comment': entity['comment'],
'superclass': entity['superclass']['ilx_id'],
'synonyms': [syn['literal'] for syn in entity['synonyms']],
'predicates': {'tmp_0381624': 'http://example_dbxref'}
}
annotation = {
'term_ilx_id': 'ilx_0101431', # brain ILX ID
'annotation_type_ilx_id': 'tmp_0381624', # hasDbXref ILX ID
'annotation_value': 'PMID:12345',
}
relationship = {
'entity1_ilx': 'ilx_0101431', # brain
'relationship_ilx': 'ilx_0115023', # Related to
'entity2_ilx': 'ilx_0108124', #organ
}
update_entity_data = {
'ilx_id': 'ilx_0101431',
'label': 'Brain',
'definition': 'update_test!!',
'type': 'fde',
'comment': 'test comment',
'superclass': 'ilx_0108124',
'synonyms': ['test', 'test2', 'test2'],
}
# resp = sci.delete_annotation(**{
# 'term_ilx_id': 'ilx_0101431', # brain ILX ID
# 'annotation_type_ilx_id': 'ilx_0115071', # hasConstraint ILX ID
# 'annotation_value': 'test_12345',
# })
relationship = {
'entity1_ilx': 'http://uri.interlex.org/base/ilx_0100001', # (R)N6 chemical ILX ID
'relationship_ilx': 'http://uri.interlex.org/base/ilx_0112772', # Afferent projection ILX ID
'entity2_ilx': 'http://uri.interlex.org/base/ilx_0100000', #1,2-Dibromo chemical ILX ID
} | [
"def",
"examples",
"(",
")",
":",
"sci",
"=",
"InterLexClient",
"(",
"api_key",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'INTERLEX_API_KEY'",
")",
",",
"base_url",
"=",
"'https://beta.scicrunch.org/api/1/'",
",",
"# NEVER CHANGE",
")",
"entity",
"=",
"{",
"'label'",
":",
"'brain115'",
",",
"'type'",
":",
"'fde'",
",",
"# broken at the moment NEEDS PDE HARDCODED",
"'definition'",
":",
"'Part of the central nervous system'",
",",
"'comment'",
":",
"'Cannot live without it'",
",",
"'superclass'",
":",
"{",
"'ilx_id'",
":",
"'ilx_0108124'",
",",
"# ILX ID for Organ",
"}",
",",
"'synonyms'",
":",
"[",
"{",
"'literal'",
":",
"'Encephalon'",
"}",
",",
"{",
"'literal'",
":",
"'Cerebro'",
"}",
",",
"]",
",",
"'existing_ids'",
":",
"[",
"{",
"'iri'",
":",
"'http://uri.neuinfo.org/nif/nifstd/birnlex_796'",
",",
"'curie'",
":",
"'BIRNLEX:796'",
",",
"}",
",",
"]",
",",
"}",
"simple_entity",
"=",
"{",
"'label'",
":",
"entity",
"[",
"'label'",
"]",
",",
"'type'",
":",
"entity",
"[",
"'type'",
"]",
",",
"# broken at the moment NEEDS PDE HARDCODED",
"'definition'",
":",
"entity",
"[",
"'definition'",
"]",
",",
"'comment'",
":",
"entity",
"[",
"'comment'",
"]",
",",
"'superclass'",
":",
"entity",
"[",
"'superclass'",
"]",
"[",
"'ilx_id'",
"]",
",",
"'synonyms'",
":",
"[",
"syn",
"[",
"'literal'",
"]",
"for",
"syn",
"in",
"entity",
"[",
"'synonyms'",
"]",
"]",
",",
"'predicates'",
":",
"{",
"'tmp_0381624'",
":",
"'http://example_dbxref'",
"}",
"}",
"annotation",
"=",
"{",
"'term_ilx_id'",
":",
"'ilx_0101431'",
",",
"# brain ILX ID",
"'annotation_type_ilx_id'",
":",
"'tmp_0381624'",
",",
"# hasDbXref ILX ID",
"'annotation_value'",
":",
"'PMID:12345'",
",",
"}",
"relationship",
"=",
"{",
"'entity1_ilx'",
":",
"'ilx_0101431'",
",",
"# brain",
"'relationship_ilx'",
":",
"'ilx_0115023'",
",",
"# Related to",
"'entity2_ilx'",
":",
"'ilx_0108124'",
",",
"#organ",
"}",
"update_entity_data",
"=",
"{",
"'ilx_id'",
":",
"'ilx_0101431'",
",",
"'label'",
":",
"'Brain'",
",",
"'definition'",
":",
"'update_test!!'",
",",
"'type'",
":",
"'fde'",
",",
"'comment'",
":",
"'test comment'",
",",
"'superclass'",
":",
"'ilx_0108124'",
",",
"'synonyms'",
":",
"[",
"'test'",
",",
"'test2'",
",",
"'test2'",
"]",
",",
"}",
"# resp = sci.delete_annotation(**{",
"# 'term_ilx_id': 'ilx_0101431', # brain ILX ID",
"# 'annotation_type_ilx_id': 'ilx_0115071', # hasConstraint ILX ID",
"# 'annotation_value': 'test_12345',",
"# })",
"relationship",
"=",
"{",
"'entity1_ilx'",
":",
"'http://uri.interlex.org/base/ilx_0100001'",
",",
"# (R)N6 chemical ILX ID",
"'relationship_ilx'",
":",
"'http://uri.interlex.org/base/ilx_0112772'",
",",
"# Afferent projection ILX ID",
"'entity2_ilx'",
":",
"'http://uri.interlex.org/base/ilx_0100000'",
",",
"#1,2-Dibromo chemical ILX ID",
"}"
]
| Examples of how to use. Default are that some functions are commented out in order
to not cause harm to existing metadata within the database. | [
"Examples",
"of",
"how",
"to",
"use",
".",
"Default",
"are",
"that",
"some",
"functions",
"are",
"commented",
"out",
"in",
"order",
"to",
"not",
"cause",
"harm",
"to",
"existing",
"metadata",
"within",
"the",
"database",
"."
]
| bcf4863cb2bf221afe2b093c5dc7da1377300041 | https://github.com/tgbugs/ontquery/blob/bcf4863cb2bf221afe2b093c5dc7da1377300041/ontquery/plugins/interlex_client.py#L778-L846 | train |
tgbugs/ontquery | ontquery/plugins/interlex_client.py | InterLexClient.process_response | def process_response(self, response: requests.models.Response) -> dict:
""" Checks for correct data response and status codes """
try:
output = response.json()
except json.JSONDecodeError: # Server is having a bad day and crashed.
raise self.BadResponseError(
'Json not returned with status code [' + str(response.status_code) + ']')
if response.status_code == 400:
return output
if response.status_code not in [200, 201]: # Safety catch.
raise self.BadResponseError(
str(output) + ': with status code [' + str(response.status_code) +
'] and params:' + str(output))
return output['data'] | python | def process_response(self, response: requests.models.Response) -> dict:
""" Checks for correct data response and status codes """
try:
output = response.json()
except json.JSONDecodeError: # Server is having a bad day and crashed.
raise self.BadResponseError(
'Json not returned with status code [' + str(response.status_code) + ']')
if response.status_code == 400:
return output
if response.status_code not in [200, 201]: # Safety catch.
raise self.BadResponseError(
str(output) + ': with status code [' + str(response.status_code) +
'] and params:' + str(output))
return output['data'] | [
"def",
"process_response",
"(",
"self",
",",
"response",
":",
"requests",
".",
"models",
".",
"Response",
")",
"->",
"dict",
":",
"try",
":",
"output",
"=",
"response",
".",
"json",
"(",
")",
"except",
"json",
".",
"JSONDecodeError",
":",
"# Server is having a bad day and crashed.",
"raise",
"self",
".",
"BadResponseError",
"(",
"'Json not returned with status code ['",
"+",
"str",
"(",
"response",
".",
"status_code",
")",
"+",
"']'",
")",
"if",
"response",
".",
"status_code",
"==",
"400",
":",
"return",
"output",
"if",
"response",
".",
"status_code",
"not",
"in",
"[",
"200",
",",
"201",
"]",
":",
"# Safety catch.",
"raise",
"self",
".",
"BadResponseError",
"(",
"str",
"(",
"output",
")",
"+",
"': with status code ['",
"+",
"str",
"(",
"response",
".",
"status_code",
")",
"+",
"'] and params:'",
"+",
"str",
"(",
"output",
")",
")",
"return",
"output",
"[",
"'data'",
"]"
]
| Checks for correct data response and status codes | [
"Checks",
"for",
"correct",
"data",
"response",
"and",
"status",
"codes"
]
| bcf4863cb2bf221afe2b093c5dc7da1377300041 | https://github.com/tgbugs/ontquery/blob/bcf4863cb2bf221afe2b093c5dc7da1377300041/ontquery/plugins/interlex_client.py#L63-L79 | train |
tgbugs/ontquery | ontquery/plugins/interlex_client.py | InterLexClient.process_superclass | def process_superclass(self, entity: List[dict]) -> List[dict]:
""" Replaces ILX ID with superclass ID """
superclass = entity.pop('superclass')
label = entity['label']
if not superclass.get('ilx_id'):
raise self.SuperClassDoesNotExistError(
f'Superclass not given an interlex ID for label: {label}')
superclass_data = self.get_entity(superclass['ilx_id'])
if not superclass_data['id']:
raise self.SuperClassDoesNotExistError(
'Superclass ILX ID: ' + superclass['ilx_id'] + ' does not exist in SciCrunch')
# BUG: only excepts superclass_tid
entity['superclasses'] = [{'superclass_tid': superclass_data['id']}]
return entity | python | def process_superclass(self, entity: List[dict]) -> List[dict]:
""" Replaces ILX ID with superclass ID """
superclass = entity.pop('superclass')
label = entity['label']
if not superclass.get('ilx_id'):
raise self.SuperClassDoesNotExistError(
f'Superclass not given an interlex ID for label: {label}')
superclass_data = self.get_entity(superclass['ilx_id'])
if not superclass_data['id']:
raise self.SuperClassDoesNotExistError(
'Superclass ILX ID: ' + superclass['ilx_id'] + ' does not exist in SciCrunch')
# BUG: only excepts superclass_tid
entity['superclasses'] = [{'superclass_tid': superclass_data['id']}]
return entity | [
"def",
"process_superclass",
"(",
"self",
",",
"entity",
":",
"List",
"[",
"dict",
"]",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"superclass",
"=",
"entity",
".",
"pop",
"(",
"'superclass'",
")",
"label",
"=",
"entity",
"[",
"'label'",
"]",
"if",
"not",
"superclass",
".",
"get",
"(",
"'ilx_id'",
")",
":",
"raise",
"self",
".",
"SuperClassDoesNotExistError",
"(",
"f'Superclass not given an interlex ID for label: {label}'",
")",
"superclass_data",
"=",
"self",
".",
"get_entity",
"(",
"superclass",
"[",
"'ilx_id'",
"]",
")",
"if",
"not",
"superclass_data",
"[",
"'id'",
"]",
":",
"raise",
"self",
".",
"SuperClassDoesNotExistError",
"(",
"'Superclass ILX ID: '",
"+",
"superclass",
"[",
"'ilx_id'",
"]",
"+",
"' does not exist in SciCrunch'",
")",
"# BUG: only excepts superclass_tid",
"entity",
"[",
"'superclasses'",
"]",
"=",
"[",
"{",
"'superclass_tid'",
":",
"superclass_data",
"[",
"'id'",
"]",
"}",
"]",
"return",
"entity"
]
| Replaces ILX ID with superclass ID | [
"Replaces",
"ILX",
"ID",
"with",
"superclass",
"ID"
]
| bcf4863cb2bf221afe2b093c5dc7da1377300041 | https://github.com/tgbugs/ontquery/blob/bcf4863cb2bf221afe2b093c5dc7da1377300041/ontquery/plugins/interlex_client.py#L115-L128 | train |
tgbugs/ontquery | ontquery/plugins/interlex_client.py | InterLexClient.check_scicrunch_for_label | def check_scicrunch_for_label(self, label: str) -> dict:
""" Sees if label with your user ID already exists
There are can be multiples of the same label in interlex, but there should only be one
label with your user id. Therefore you can create labels if there already techniqually
exist, but not if you are the one to create it.
"""
list_of_crude_matches = self.crude_search_scicrunch_via_label(label)
for crude_match in list_of_crude_matches:
# If labels match
if crude_match['label'].lower().strip() == label.lower().strip():
complete_data_of_crude_match = self.get_entity(crude_match['ilx'])
crude_match_label = crude_match['label']
crude_match_user_id = complete_data_of_crude_match['uid']
# If label was created by you
if str(self.user_id) == str(crude_match_user_id):
return complete_data_of_crude_match # You created the entity already
# No label AND user id match
return {} | python | def check_scicrunch_for_label(self, label: str) -> dict:
""" Sees if label with your user ID already exists
There are can be multiples of the same label in interlex, but there should only be one
label with your user id. Therefore you can create labels if there already techniqually
exist, but not if you are the one to create it.
"""
list_of_crude_matches = self.crude_search_scicrunch_via_label(label)
for crude_match in list_of_crude_matches:
# If labels match
if crude_match['label'].lower().strip() == label.lower().strip():
complete_data_of_crude_match = self.get_entity(crude_match['ilx'])
crude_match_label = crude_match['label']
crude_match_user_id = complete_data_of_crude_match['uid']
# If label was created by you
if str(self.user_id) == str(crude_match_user_id):
return complete_data_of_crude_match # You created the entity already
# No label AND user id match
return {} | [
"def",
"check_scicrunch_for_label",
"(",
"self",
",",
"label",
":",
"str",
")",
"->",
"dict",
":",
"list_of_crude_matches",
"=",
"self",
".",
"crude_search_scicrunch_via_label",
"(",
"label",
")",
"for",
"crude_match",
"in",
"list_of_crude_matches",
":",
"# If labels match",
"if",
"crude_match",
"[",
"'label'",
"]",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"==",
"label",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
":",
"complete_data_of_crude_match",
"=",
"self",
".",
"get_entity",
"(",
"crude_match",
"[",
"'ilx'",
"]",
")",
"crude_match_label",
"=",
"crude_match",
"[",
"'label'",
"]",
"crude_match_user_id",
"=",
"complete_data_of_crude_match",
"[",
"'uid'",
"]",
"# If label was created by you",
"if",
"str",
"(",
"self",
".",
"user_id",
")",
"==",
"str",
"(",
"crude_match_user_id",
")",
":",
"return",
"complete_data_of_crude_match",
"# You created the entity already",
"# No label AND user id match",
"return",
"{",
"}"
]
| Sees if label with your user ID already exists
There are can be multiples of the same label in interlex, but there should only be one
label with your user id. Therefore you can create labels if there already techniqually
exist, but not if you are the one to create it. | [
"Sees",
"if",
"label",
"with",
"your",
"user",
"ID",
"already",
"exists"
]
| bcf4863cb2bf221afe2b093c5dc7da1377300041 | https://github.com/tgbugs/ontquery/blob/bcf4863cb2bf221afe2b093c5dc7da1377300041/ontquery/plugins/interlex_client.py#L162-L180 | train |
tgbugs/ontquery | ontquery/plugins/interlex_client.py | InterLexClient.add_raw_entity | def add_raw_entity(self, entity: dict) -> dict:
""" Adds entity if it does not already exist under your user ID.
Need to provide a list of dictionaries that have at least the key/values
for label and type. If given a key, the values provided must be in the
format shown in order for the server to except them. You can input
multiple synonyms, or existing_ids.
Entity type can be any of the following: term, pde, fde, cde, annotation, or relationship
Options Template:
entity = {
'label': '',
'type': '',
'definition': '',
'comment': '',
'superclass': {
'ilx_id': ''
},
'synonyms': [
{
'literal': ''
},
],
'existing_ids': [
{
'iri': '',
'curie': '',
},
],
}
Minimum Needed:
entity = {
'label': '',
'type': '',
}
Example:
entity = {
'label': 'brain',
'type': 'pde',
'definition': 'Part of the central nervous system',
'comment': 'Cannot live without it',
'superclass': {
'ilx_id': 'ilx_0108124', # ILX ID for Organ
},
'synonyms': [
{
'literal': 'Encephalon'
},
{
'literal': 'Cerebro'
},
],
'existing_ids': [
{
'iri': 'http://uri.neuinfo.org/nif/nifstd/birnlex_796',
'curie': 'BIRNLEX:796',
},
],
}
"""
needed_in_entity = set([
'label',
'type',
])
options_in_entity = set([
'label',
'type',
'definition',
'comment',
'superclass',
'synonyms',
'existing_ids'
])
prime_entity_url = self.base_url + 'ilx/add'
add_entity_url = self.base_url + 'term/add'
### Checking if key/value format is correct ###
# Seeing if you are missing a needed key
if (set(entity) & needed_in_entity) != needed_in_entity:
raise self.MissingKeyError(
'You need key(s): '+ str(needed_in_entity - set(entity)))
# Seeing if you have other options not included in the description
elif (set(entity) | options_in_entity) != options_in_entity:
raise self.IncorrectKeyError(
'Unexpected key(s): ' + str(set(entity) - options_in_entity))
entity['type'] = entity['type'].lower() # BUG: server only takes lowercase
if entity['type'] not in ['term', 'relationship', 'annotation', 'cde', 'fde', 'pde']:
raise TypeError(
'Entity should be one of the following: ' +
'term, relationship, annotation, cde, fde, pde')
if entity.get('superclass'):
entity = self.process_superclass(entity)
if entity.get('synonyms'):
entity = self.process_synonyms(entity)
if entity.get('existing_ids'):
entity = self.process_existing_ids(entity)
entity['uid'] = self.user_id # BUG: php lacks uid update
### Adding entity to SciCrunch ###
entity['term'] = entity.pop('label') # ilx/add nuance
ilx_data = self.post(
url = prime_entity_url,
data = entity.copy(),
) # requesting spot in server for entity
if ilx_data.get('ilx'):
ilx_id = ilx_data['ilx']
else:
ilx_id = ilx_data['fragment'] # beta.scicrunch.org
entity['label'] = entity.pop('term') # term/add nuance
entity['ilx'] = ilx_id # need entity ilx_id to place entity in db
output = self.post(
url = add_entity_url,
data = entity.copy(),
) # data represented in SciCrunch interface
### Checking if label already exisits ###
if output.get('errormsg'):
if 'already exists' in output['errormsg'].lower():
prexisting_data = self.check_scicrunch_for_label(entity['label'])
if prexisting_data:
print(
'You already added entity', entity['label'],
'with ILX ID:', prexisting_data['ilx'])
return prexisting_data
self.Error(output) # FIXME what is the correct error here?
self.Error(output) # FIXME what is the correct error here?
# BUG: server output incomplete compared to search via ilx ids
output = self.get_entity(output['ilx'])
return output | python | def add_raw_entity(self, entity: dict) -> dict:
""" Adds entity if it does not already exist under your user ID.
Need to provide a list of dictionaries that have at least the key/values
for label and type. If given a key, the values provided must be in the
format shown in order for the server to except them. You can input
multiple synonyms, or existing_ids.
Entity type can be any of the following: term, pde, fde, cde, annotation, or relationship
Options Template:
entity = {
'label': '',
'type': '',
'definition': '',
'comment': '',
'superclass': {
'ilx_id': ''
},
'synonyms': [
{
'literal': ''
},
],
'existing_ids': [
{
'iri': '',
'curie': '',
},
],
}
Minimum Needed:
entity = {
'label': '',
'type': '',
}
Example:
entity = {
'label': 'brain',
'type': 'pde',
'definition': 'Part of the central nervous system',
'comment': 'Cannot live without it',
'superclass': {
'ilx_id': 'ilx_0108124', # ILX ID for Organ
},
'synonyms': [
{
'literal': 'Encephalon'
},
{
'literal': 'Cerebro'
},
],
'existing_ids': [
{
'iri': 'http://uri.neuinfo.org/nif/nifstd/birnlex_796',
'curie': 'BIRNLEX:796',
},
],
}
"""
needed_in_entity = set([
'label',
'type',
])
options_in_entity = set([
'label',
'type',
'definition',
'comment',
'superclass',
'synonyms',
'existing_ids'
])
prime_entity_url = self.base_url + 'ilx/add'
add_entity_url = self.base_url + 'term/add'
### Checking if key/value format is correct ###
# Seeing if you are missing a needed key
if (set(entity) & needed_in_entity) != needed_in_entity:
raise self.MissingKeyError(
'You need key(s): '+ str(needed_in_entity - set(entity)))
# Seeing if you have other options not included in the description
elif (set(entity) | options_in_entity) != options_in_entity:
raise self.IncorrectKeyError(
'Unexpected key(s): ' + str(set(entity) - options_in_entity))
entity['type'] = entity['type'].lower() # BUG: server only takes lowercase
if entity['type'] not in ['term', 'relationship', 'annotation', 'cde', 'fde', 'pde']:
raise TypeError(
'Entity should be one of the following: ' +
'term, relationship, annotation, cde, fde, pde')
if entity.get('superclass'):
entity = self.process_superclass(entity)
if entity.get('synonyms'):
entity = self.process_synonyms(entity)
if entity.get('existing_ids'):
entity = self.process_existing_ids(entity)
entity['uid'] = self.user_id # BUG: php lacks uid update
### Adding entity to SciCrunch ###
entity['term'] = entity.pop('label') # ilx/add nuance
ilx_data = self.post(
url = prime_entity_url,
data = entity.copy(),
) # requesting spot in server for entity
if ilx_data.get('ilx'):
ilx_id = ilx_data['ilx']
else:
ilx_id = ilx_data['fragment'] # beta.scicrunch.org
entity['label'] = entity.pop('term') # term/add nuance
entity['ilx'] = ilx_id # need entity ilx_id to place entity in db
output = self.post(
url = add_entity_url,
data = entity.copy(),
) # data represented in SciCrunch interface
### Checking if label already exisits ###
if output.get('errormsg'):
if 'already exists' in output['errormsg'].lower():
prexisting_data = self.check_scicrunch_for_label(entity['label'])
if prexisting_data:
print(
'You already added entity', entity['label'],
'with ILX ID:', prexisting_data['ilx'])
return prexisting_data
self.Error(output) # FIXME what is the correct error here?
self.Error(output) # FIXME what is the correct error here?
# BUG: server output incomplete compared to search via ilx ids
output = self.get_entity(output['ilx'])
return output | [
"def",
"add_raw_entity",
"(",
"self",
",",
"entity",
":",
"dict",
")",
"->",
"dict",
":",
"needed_in_entity",
"=",
"set",
"(",
"[",
"'label'",
",",
"'type'",
",",
"]",
")",
"options_in_entity",
"=",
"set",
"(",
"[",
"'label'",
",",
"'type'",
",",
"'definition'",
",",
"'comment'",
",",
"'superclass'",
",",
"'synonyms'",
",",
"'existing_ids'",
"]",
")",
"prime_entity_url",
"=",
"self",
".",
"base_url",
"+",
"'ilx/add'",
"add_entity_url",
"=",
"self",
".",
"base_url",
"+",
"'term/add'",
"### Checking if key/value format is correct ###",
"# Seeing if you are missing a needed key",
"if",
"(",
"set",
"(",
"entity",
")",
"&",
"needed_in_entity",
")",
"!=",
"needed_in_entity",
":",
"raise",
"self",
".",
"MissingKeyError",
"(",
"'You need key(s): '",
"+",
"str",
"(",
"needed_in_entity",
"-",
"set",
"(",
"entity",
")",
")",
")",
"# Seeing if you have other options not included in the description",
"elif",
"(",
"set",
"(",
"entity",
")",
"|",
"options_in_entity",
")",
"!=",
"options_in_entity",
":",
"raise",
"self",
".",
"IncorrectKeyError",
"(",
"'Unexpected key(s): '",
"+",
"str",
"(",
"set",
"(",
"entity",
")",
"-",
"options_in_entity",
")",
")",
"entity",
"[",
"'type'",
"]",
"=",
"entity",
"[",
"'type'",
"]",
".",
"lower",
"(",
")",
"# BUG: server only takes lowercase",
"if",
"entity",
"[",
"'type'",
"]",
"not",
"in",
"[",
"'term'",
",",
"'relationship'",
",",
"'annotation'",
",",
"'cde'",
",",
"'fde'",
",",
"'pde'",
"]",
":",
"raise",
"TypeError",
"(",
"'Entity should be one of the following: '",
"+",
"'term, relationship, annotation, cde, fde, pde'",
")",
"if",
"entity",
".",
"get",
"(",
"'superclass'",
")",
":",
"entity",
"=",
"self",
".",
"process_superclass",
"(",
"entity",
")",
"if",
"entity",
".",
"get",
"(",
"'synonyms'",
")",
":",
"entity",
"=",
"self",
".",
"process_synonyms",
"(",
"entity",
")",
"if",
"entity",
".",
"get",
"(",
"'existing_ids'",
")",
":",
"entity",
"=",
"self",
".",
"process_existing_ids",
"(",
"entity",
")",
"entity",
"[",
"'uid'",
"]",
"=",
"self",
".",
"user_id",
"# BUG: php lacks uid update",
"### Adding entity to SciCrunch ###",
"entity",
"[",
"'term'",
"]",
"=",
"entity",
".",
"pop",
"(",
"'label'",
")",
"# ilx/add nuance",
"ilx_data",
"=",
"self",
".",
"post",
"(",
"url",
"=",
"prime_entity_url",
",",
"data",
"=",
"entity",
".",
"copy",
"(",
")",
",",
")",
"# requesting spot in server for entity",
"if",
"ilx_data",
".",
"get",
"(",
"'ilx'",
")",
":",
"ilx_id",
"=",
"ilx_data",
"[",
"'ilx'",
"]",
"else",
":",
"ilx_id",
"=",
"ilx_data",
"[",
"'fragment'",
"]",
"# beta.scicrunch.org",
"entity",
"[",
"'label'",
"]",
"=",
"entity",
".",
"pop",
"(",
"'term'",
")",
"# term/add nuance",
"entity",
"[",
"'ilx'",
"]",
"=",
"ilx_id",
"# need entity ilx_id to place entity in db",
"output",
"=",
"self",
".",
"post",
"(",
"url",
"=",
"add_entity_url",
",",
"data",
"=",
"entity",
".",
"copy",
"(",
")",
",",
")",
"# data represented in SciCrunch interface",
"### Checking if label already exisits ###",
"if",
"output",
".",
"get",
"(",
"'errormsg'",
")",
":",
"if",
"'already exists'",
"in",
"output",
"[",
"'errormsg'",
"]",
".",
"lower",
"(",
")",
":",
"prexisting_data",
"=",
"self",
".",
"check_scicrunch_for_label",
"(",
"entity",
"[",
"'label'",
"]",
")",
"if",
"prexisting_data",
":",
"print",
"(",
"'You already added entity'",
",",
"entity",
"[",
"'label'",
"]",
",",
"'with ILX ID:'",
",",
"prexisting_data",
"[",
"'ilx'",
"]",
")",
"return",
"prexisting_data",
"self",
".",
"Error",
"(",
"output",
")",
"# FIXME what is the correct error here?",
"self",
".",
"Error",
"(",
"output",
")",
"# FIXME what is the correct error here?",
"# BUG: server output incomplete compared to search via ilx ids",
"output",
"=",
"self",
".",
"get_entity",
"(",
"output",
"[",
"'ilx'",
"]",
")",
"return",
"output"
]
| Adds entity if it does not already exist under your user ID.
Need to provide a list of dictionaries that have at least the key/values
for label and type. If given a key, the values provided must be in the
format shown in order for the server to except them. You can input
multiple synonyms, or existing_ids.
Entity type can be any of the following: term, pde, fde, cde, annotation, or relationship
Options Template:
entity = {
'label': '',
'type': '',
'definition': '',
'comment': '',
'superclass': {
'ilx_id': ''
},
'synonyms': [
{
'literal': ''
},
],
'existing_ids': [
{
'iri': '',
'curie': '',
},
],
}
Minimum Needed:
entity = {
'label': '',
'type': '',
}
Example:
entity = {
'label': 'brain',
'type': 'pde',
'definition': 'Part of the central nervous system',
'comment': 'Cannot live without it',
'superclass': {
'ilx_id': 'ilx_0108124', # ILX ID for Organ
},
'synonyms': [
{
'literal': 'Encephalon'
},
{
'literal': 'Cerebro'
},
],
'existing_ids': [
{
'iri': 'http://uri.neuinfo.org/nif/nifstd/birnlex_796',
'curie': 'BIRNLEX:796',
},
],
} | [
"Adds",
"entity",
"if",
"it",
"does",
"not",
"already",
"exist",
"under",
"your",
"user",
"ID",
"."
]
| bcf4863cb2bf221afe2b093c5dc7da1377300041 | https://github.com/tgbugs/ontquery/blob/bcf4863cb2bf221afe2b093c5dc7da1377300041/ontquery/plugins/interlex_client.py#L266-L401 | train |
tgbugs/ontquery | ontquery/plugins/interlex_client.py | InterLexClient.add_annotation | def add_annotation(
self,
term_ilx_id: str,
annotation_type_ilx_id: str,
annotation_value: str) -> dict:
""" Adding an annotation value to a prexisting entity
An annotation exists as 3 different parts:
1. entity with type term, cde, fde, or pde
2. entity with type annotation
3. string value of the annotation
Example:
annotation = {
'term_ilx_id': 'ilx_0101431', # brain ILX ID
'annotation_type_ilx_id': 'ilx_0381360', # hasDbXref ILX ID
'annotation_value': 'http://neurolex.org/wiki/birnlex_796',
}
"""
url = self.base_url + 'term/add-annotation'
term_data = self.get_entity(term_ilx_id)
if not term_data['id']:
exit(
'term_ilx_id: ' + term_ilx_id + ' does not exist'
)
anno_data = self.get_entity(annotation_type_ilx_id)
if not anno_data['id']:
exit(
'annotation_type_ilx_id: ' + annotation_type_ilx_id +
' does not exist'
)
data = {
'tid': term_data['id'],
'annotation_tid': anno_data['id'],
'value': annotation_value,
'term_version': term_data['version'],
'annotation_term_version': anno_data['version'],
'orig_uid': self.user_id, # BUG: php lacks orig_uid update
}
output = self.post(
url = url,
data = data,
)
### If already exists, we return the actual annotation properly ###
if output.get('errormsg'):
if 'already exists' in output['errormsg'].lower():
term_annotations = self.get_annotation_via_tid(term_data['id'])
for term_annotation in term_annotations:
if str(term_annotation['annotation_tid']) == str(anno_data['id']):
if term_annotation['value'] == data['value']:
print(
'Annotation: [' + term_data['label'] + ' -> ' + anno_data['label'] +
' -> ' + data['value'] + '], already exists.'
)
return term_annotation
exit(output)
exit(output)
return output | python | def add_annotation(
self,
term_ilx_id: str,
annotation_type_ilx_id: str,
annotation_value: str) -> dict:
""" Adding an annotation value to a prexisting entity
An annotation exists as 3 different parts:
1. entity with type term, cde, fde, or pde
2. entity with type annotation
3. string value of the annotation
Example:
annotation = {
'term_ilx_id': 'ilx_0101431', # brain ILX ID
'annotation_type_ilx_id': 'ilx_0381360', # hasDbXref ILX ID
'annotation_value': 'http://neurolex.org/wiki/birnlex_796',
}
"""
url = self.base_url + 'term/add-annotation'
term_data = self.get_entity(term_ilx_id)
if not term_data['id']:
exit(
'term_ilx_id: ' + term_ilx_id + ' does not exist'
)
anno_data = self.get_entity(annotation_type_ilx_id)
if not anno_data['id']:
exit(
'annotation_type_ilx_id: ' + annotation_type_ilx_id +
' does not exist'
)
data = {
'tid': term_data['id'],
'annotation_tid': anno_data['id'],
'value': annotation_value,
'term_version': term_data['version'],
'annotation_term_version': anno_data['version'],
'orig_uid': self.user_id, # BUG: php lacks orig_uid update
}
output = self.post(
url = url,
data = data,
)
### If already exists, we return the actual annotation properly ###
if output.get('errormsg'):
if 'already exists' in output['errormsg'].lower():
term_annotations = self.get_annotation_via_tid(term_data['id'])
for term_annotation in term_annotations:
if str(term_annotation['annotation_tid']) == str(anno_data['id']):
if term_annotation['value'] == data['value']:
print(
'Annotation: [' + term_data['label'] + ' -> ' + anno_data['label'] +
' -> ' + data['value'] + '], already exists.'
)
return term_annotation
exit(output)
exit(output)
return output | [
"def",
"add_annotation",
"(",
"self",
",",
"term_ilx_id",
":",
"str",
",",
"annotation_type_ilx_id",
":",
"str",
",",
"annotation_value",
":",
"str",
")",
"->",
"dict",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"'term/add-annotation'",
"term_data",
"=",
"self",
".",
"get_entity",
"(",
"term_ilx_id",
")",
"if",
"not",
"term_data",
"[",
"'id'",
"]",
":",
"exit",
"(",
"'term_ilx_id: '",
"+",
"term_ilx_id",
"+",
"' does not exist'",
")",
"anno_data",
"=",
"self",
".",
"get_entity",
"(",
"annotation_type_ilx_id",
")",
"if",
"not",
"anno_data",
"[",
"'id'",
"]",
":",
"exit",
"(",
"'annotation_type_ilx_id: '",
"+",
"annotation_type_ilx_id",
"+",
"' does not exist'",
")",
"data",
"=",
"{",
"'tid'",
":",
"term_data",
"[",
"'id'",
"]",
",",
"'annotation_tid'",
":",
"anno_data",
"[",
"'id'",
"]",
",",
"'value'",
":",
"annotation_value",
",",
"'term_version'",
":",
"term_data",
"[",
"'version'",
"]",
",",
"'annotation_term_version'",
":",
"anno_data",
"[",
"'version'",
"]",
",",
"'orig_uid'",
":",
"self",
".",
"user_id",
",",
"# BUG: php lacks orig_uid update",
"}",
"output",
"=",
"self",
".",
"post",
"(",
"url",
"=",
"url",
",",
"data",
"=",
"data",
",",
")",
"### If already exists, we return the actual annotation properly ###",
"if",
"output",
".",
"get",
"(",
"'errormsg'",
")",
":",
"if",
"'already exists'",
"in",
"output",
"[",
"'errormsg'",
"]",
".",
"lower",
"(",
")",
":",
"term_annotations",
"=",
"self",
".",
"get_annotation_via_tid",
"(",
"term_data",
"[",
"'id'",
"]",
")",
"for",
"term_annotation",
"in",
"term_annotations",
":",
"if",
"str",
"(",
"term_annotation",
"[",
"'annotation_tid'",
"]",
")",
"==",
"str",
"(",
"anno_data",
"[",
"'id'",
"]",
")",
":",
"if",
"term_annotation",
"[",
"'value'",
"]",
"==",
"data",
"[",
"'value'",
"]",
":",
"print",
"(",
"'Annotation: ['",
"+",
"term_data",
"[",
"'label'",
"]",
"+",
"' -> '",
"+",
"anno_data",
"[",
"'label'",
"]",
"+",
"' -> '",
"+",
"data",
"[",
"'value'",
"]",
"+",
"'], already exists.'",
")",
"return",
"term_annotation",
"exit",
"(",
"output",
")",
"exit",
"(",
"output",
")",
"return",
"output"
]
| Adding an annotation value to a prexisting entity
An annotation exists as 3 different parts:
1. entity with type term, cde, fde, or pde
2. entity with type annotation
3. string value of the annotation
Example:
annotation = {
'term_ilx_id': 'ilx_0101431', # brain ILX ID
'annotation_type_ilx_id': 'ilx_0381360', # hasDbXref ILX ID
'annotation_value': 'http://neurolex.org/wiki/birnlex_796',
} | [
"Adding",
"an",
"annotation",
"value",
"to",
"a",
"prexisting",
"entity"
]
| bcf4863cb2bf221afe2b093c5dc7da1377300041 | https://github.com/tgbugs/ontquery/blob/bcf4863cb2bf221afe2b093c5dc7da1377300041/ontquery/plugins/interlex_client.py#L527-L589 | train |
tgbugs/ontquery | ontquery/plugins/interlex_client.py | InterLexClient.delete_annotation | def delete_annotation(
self,
term_ilx_id: str,
annotation_type_ilx_id: str,
annotation_value: str) -> dict:
""" If annotation doesnt exist, add it
"""
term_data = self.get_entity(term_ilx_id)
if not term_data['id']:
exit(
'term_ilx_id: ' + term_ilx_id + ' does not exist'
)
anno_data = self.get_entity(annotation_type_ilx_id)
if not anno_data['id']:
exit(
'annotation_type_ilx_id: ' + annotation_type_ilx_id +
' does not exist'
)
entity_annotations = self.get_annotation_via_tid(term_data['id'])
annotation_id = ''
for annotation in entity_annotations:
if str(annotation['tid']) == str(term_data['id']):
if str(annotation['annotation_tid']) == str(anno_data['id']):
if str(annotation['value']) == str(annotation_value):
annotation_id = annotation['id']
break
if not annotation_id:
print('''WARNING: Annotation you wanted to delete does not exist ''')
return None
url = self.base_url + 'term/edit-annotation/{annotation_id}'.format(
annotation_id = annotation_id
)
data = {
'tid': ' ', # for delete
'annotation_tid': ' ', # for delete
'value': ' ', # for delete
'term_version': ' ',
'annotation_term_version': ' ',
}
output = self.post(
url = url,
data = data,
)
# check output
return output | python | def delete_annotation(
self,
term_ilx_id: str,
annotation_type_ilx_id: str,
annotation_value: str) -> dict:
""" If annotation doesnt exist, add it
"""
term_data = self.get_entity(term_ilx_id)
if not term_data['id']:
exit(
'term_ilx_id: ' + term_ilx_id + ' does not exist'
)
anno_data = self.get_entity(annotation_type_ilx_id)
if not anno_data['id']:
exit(
'annotation_type_ilx_id: ' + annotation_type_ilx_id +
' does not exist'
)
entity_annotations = self.get_annotation_via_tid(term_data['id'])
annotation_id = ''
for annotation in entity_annotations:
if str(annotation['tid']) == str(term_data['id']):
if str(annotation['annotation_tid']) == str(anno_data['id']):
if str(annotation['value']) == str(annotation_value):
annotation_id = annotation['id']
break
if not annotation_id:
print('''WARNING: Annotation you wanted to delete does not exist ''')
return None
url = self.base_url + 'term/edit-annotation/{annotation_id}'.format(
annotation_id = annotation_id
)
data = {
'tid': ' ', # for delete
'annotation_tid': ' ', # for delete
'value': ' ', # for delete
'term_version': ' ',
'annotation_term_version': ' ',
}
output = self.post(
url = url,
data = data,
)
# check output
return output | [
"def",
"delete_annotation",
"(",
"self",
",",
"term_ilx_id",
":",
"str",
",",
"annotation_type_ilx_id",
":",
"str",
",",
"annotation_value",
":",
"str",
")",
"->",
"dict",
":",
"term_data",
"=",
"self",
".",
"get_entity",
"(",
"term_ilx_id",
")",
"if",
"not",
"term_data",
"[",
"'id'",
"]",
":",
"exit",
"(",
"'term_ilx_id: '",
"+",
"term_ilx_id",
"+",
"' does not exist'",
")",
"anno_data",
"=",
"self",
".",
"get_entity",
"(",
"annotation_type_ilx_id",
")",
"if",
"not",
"anno_data",
"[",
"'id'",
"]",
":",
"exit",
"(",
"'annotation_type_ilx_id: '",
"+",
"annotation_type_ilx_id",
"+",
"' does not exist'",
")",
"entity_annotations",
"=",
"self",
".",
"get_annotation_via_tid",
"(",
"term_data",
"[",
"'id'",
"]",
")",
"annotation_id",
"=",
"''",
"for",
"annotation",
"in",
"entity_annotations",
":",
"if",
"str",
"(",
"annotation",
"[",
"'tid'",
"]",
")",
"==",
"str",
"(",
"term_data",
"[",
"'id'",
"]",
")",
":",
"if",
"str",
"(",
"annotation",
"[",
"'annotation_tid'",
"]",
")",
"==",
"str",
"(",
"anno_data",
"[",
"'id'",
"]",
")",
":",
"if",
"str",
"(",
"annotation",
"[",
"'value'",
"]",
")",
"==",
"str",
"(",
"annotation_value",
")",
":",
"annotation_id",
"=",
"annotation",
"[",
"'id'",
"]",
"break",
"if",
"not",
"annotation_id",
":",
"print",
"(",
"'''WARNING: Annotation you wanted to delete does not exist '''",
")",
"return",
"None",
"url",
"=",
"self",
".",
"base_url",
"+",
"'term/edit-annotation/{annotation_id}'",
".",
"format",
"(",
"annotation_id",
"=",
"annotation_id",
")",
"data",
"=",
"{",
"'tid'",
":",
"' '",
",",
"# for delete",
"'annotation_tid'",
":",
"' '",
",",
"# for delete",
"'value'",
":",
"' '",
",",
"# for delete",
"'term_version'",
":",
"' '",
",",
"'annotation_term_version'",
":",
"' '",
",",
"}",
"output",
"=",
"self",
".",
"post",
"(",
"url",
"=",
"url",
",",
"data",
"=",
"data",
",",
")",
"# check output",
"return",
"output"
]
| If annotation doesnt exist, add it | [
"If",
"annotation",
"doesnt",
"exist",
"add",
"it"
]
| bcf4863cb2bf221afe2b093c5dc7da1377300041 | https://github.com/tgbugs/ontquery/blob/bcf4863cb2bf221afe2b093c5dc7da1377300041/ontquery/plugins/interlex_client.py#L591-L642 | train |
lowandrew/OLCTools | databasesetup/rest_auth_class.py | REST.main | def main(self):
"""
Run the appropriate methods in the correct order
"""
self.secret_finder()
self.parse_access_token()
self.get_session_token()
self.parse_session_token()
self.get_route()
self.download_profile()
self.find_loci()
self.download_loci() | python | def main(self):
"""
Run the appropriate methods in the correct order
"""
self.secret_finder()
self.parse_access_token()
self.get_session_token()
self.parse_session_token()
self.get_route()
self.download_profile()
self.find_loci()
self.download_loci() | [
"def",
"main",
"(",
"self",
")",
":",
"self",
".",
"secret_finder",
"(",
")",
"self",
".",
"parse_access_token",
"(",
")",
"self",
".",
"get_session_token",
"(",
")",
"self",
".",
"parse_session_token",
"(",
")",
"self",
".",
"get_route",
"(",
")",
"self",
".",
"download_profile",
"(",
")",
"self",
".",
"find_loci",
"(",
")",
"self",
".",
"download_loci",
"(",
")"
]
| Run the appropriate methods in the correct order | [
"Run",
"the",
"appropriate",
"methods",
"in",
"the",
"correct",
"order"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/databasesetup/rest_auth_class.py#L37-L48 | train |
lowandrew/OLCTools | databasesetup/rest_auth_class.py | REST.secret_finder | def secret_finder(self):
"""
Parses the supplied secret.txt file for the consumer key and secrets
"""
secretlist = list()
if os.path.isfile(self.secret_file):
# Open the file, and put the contents into a list
with open(self.secret_file, 'r') as secret:
for line in secret:
secretlist.append(line.rstrip())
# Extract the key and secret from the list
self.consumer_key = secretlist[0]
self.consumer_secret = secretlist[1]
else:
print('"Cannot find the secret.txt file required for authorization. '
'Please ensure that this file exists, and that the supplied consumer key is on the '
'first line, and the consumer secret is on he second line. '
'Contact [email protected] for an account, and the necessary keys')
quit() | python | def secret_finder(self):
"""
Parses the supplied secret.txt file for the consumer key and secrets
"""
secretlist = list()
if os.path.isfile(self.secret_file):
# Open the file, and put the contents into a list
with open(self.secret_file, 'r') as secret:
for line in secret:
secretlist.append(line.rstrip())
# Extract the key and secret from the list
self.consumer_key = secretlist[0]
self.consumer_secret = secretlist[1]
else:
print('"Cannot find the secret.txt file required for authorization. '
'Please ensure that this file exists, and that the supplied consumer key is on the '
'first line, and the consumer secret is on he second line. '
'Contact [email protected] for an account, and the necessary keys')
quit() | [
"def",
"secret_finder",
"(",
"self",
")",
":",
"secretlist",
"=",
"list",
"(",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"secret_file",
")",
":",
"# Open the file, and put the contents into a list",
"with",
"open",
"(",
"self",
".",
"secret_file",
",",
"'r'",
")",
"as",
"secret",
":",
"for",
"line",
"in",
"secret",
":",
"secretlist",
".",
"append",
"(",
"line",
".",
"rstrip",
"(",
")",
")",
"# Extract the key and secret from the list",
"self",
".",
"consumer_key",
"=",
"secretlist",
"[",
"0",
"]",
"self",
".",
"consumer_secret",
"=",
"secretlist",
"[",
"1",
"]",
"else",
":",
"print",
"(",
"'\"Cannot find the secret.txt file required for authorization. '",
"'Please ensure that this file exists, and that the supplied consumer key is on the '",
"'first line, and the consumer secret is on he second line. '",
"'Contact [email protected] for an account, and the necessary keys'",
")",
"quit",
"(",
")"
]
| Parses the supplied secret.txt file for the consumer key and secrets | [
"Parses",
"the",
"supplied",
"secret",
".",
"txt",
"file",
"for",
"the",
"consumer",
"key",
"and",
"secrets"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/databasesetup/rest_auth_class.py#L50-L68 | train |
lowandrew/OLCTools | databasesetup/rest_auth_class.py | REST.parse_access_token | def parse_access_token(self):
"""
Extract the secret and token values from the access_token file
"""
access_file = os.path.join(self.file_path, 'access_token')
# Ensure that the access_token file exists
if os.path.isfile(access_file):
# Initialise a list to store the secret and token
access_list = list()
with open(access_file, 'r') as access_token:
for line in access_token:
value, data = line.split('=')
access_list.append(data.rstrip())
# Set the variables appropriately
self.access_secret = access_list[0]
self.access_token = access_list[1]
else:
print('Missing access_token')
self.get_request_token()
self.get_access_token() | python | def parse_access_token(self):
"""
Extract the secret and token values from the access_token file
"""
access_file = os.path.join(self.file_path, 'access_token')
# Ensure that the access_token file exists
if os.path.isfile(access_file):
# Initialise a list to store the secret and token
access_list = list()
with open(access_file, 'r') as access_token:
for line in access_token:
value, data = line.split('=')
access_list.append(data.rstrip())
# Set the variables appropriately
self.access_secret = access_list[0]
self.access_token = access_list[1]
else:
print('Missing access_token')
self.get_request_token()
self.get_access_token() | [
"def",
"parse_access_token",
"(",
"self",
")",
":",
"access_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"file_path",
",",
"'access_token'",
")",
"# Ensure that the access_token file exists",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"access_file",
")",
":",
"# Initialise a list to store the secret and token",
"access_list",
"=",
"list",
"(",
")",
"with",
"open",
"(",
"access_file",
",",
"'r'",
")",
"as",
"access_token",
":",
"for",
"line",
"in",
"access_token",
":",
"value",
",",
"data",
"=",
"line",
".",
"split",
"(",
"'='",
")",
"access_list",
".",
"append",
"(",
"data",
".",
"rstrip",
"(",
")",
")",
"# Set the variables appropriately",
"self",
".",
"access_secret",
"=",
"access_list",
"[",
"0",
"]",
"self",
".",
"access_token",
"=",
"access_list",
"[",
"1",
"]",
"else",
":",
"print",
"(",
"'Missing access_token'",
")",
"self",
".",
"get_request_token",
"(",
")",
"self",
".",
"get_access_token",
"(",
")"
]
| Extract the secret and token values from the access_token file | [
"Extract",
"the",
"secret",
"and",
"token",
"values",
"from",
"the",
"access_token",
"file"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/databasesetup/rest_auth_class.py#L70-L89 | train |
lowandrew/OLCTools | databasesetup/rest_auth_class.py | REST.get_request_token | def get_request_token(self):
"""
Obtain a request token
"""
print('Obtaining request token')
try:
os.remove(os.path.join(self.file_path, 'request_token'))
except FileNotFoundError:
pass
# Create a new session
session = OAuth1Session(consumer_key=self.consumer_key,
consumer_secret=self.consumer_secret)
# Use the test URL in the GET request
r = session.request(method='GET',
url=self.request_token_url,
params={'oauth_callback': 'oob'})
# If the status code is '200' (OK), proceed
if r.status_code == 200:
# Save the JSON-decoded token secret and token
self.request_token = r.json()['oauth_token']
self.request_secret = r.json()['oauth_token_secret']
# Write the token and secret to file
self.write_token('request_token', self.request_token, self.request_secret) | python | def get_request_token(self):
"""
Obtain a request token
"""
print('Obtaining request token')
try:
os.remove(os.path.join(self.file_path, 'request_token'))
except FileNotFoundError:
pass
# Create a new session
session = OAuth1Session(consumer_key=self.consumer_key,
consumer_secret=self.consumer_secret)
# Use the test URL in the GET request
r = session.request(method='GET',
url=self.request_token_url,
params={'oauth_callback': 'oob'})
# If the status code is '200' (OK), proceed
if r.status_code == 200:
# Save the JSON-decoded token secret and token
self.request_token = r.json()['oauth_token']
self.request_secret = r.json()['oauth_token_secret']
# Write the token and secret to file
self.write_token('request_token', self.request_token, self.request_secret) | [
"def",
"get_request_token",
"(",
"self",
")",
":",
"print",
"(",
"'Obtaining request token'",
")",
"try",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"file_path",
",",
"'request_token'",
")",
")",
"except",
"FileNotFoundError",
":",
"pass",
"# Create a new session",
"session",
"=",
"OAuth1Session",
"(",
"consumer_key",
"=",
"self",
".",
"consumer_key",
",",
"consumer_secret",
"=",
"self",
".",
"consumer_secret",
")",
"# Use the test URL in the GET request",
"r",
"=",
"session",
".",
"request",
"(",
"method",
"=",
"'GET'",
",",
"url",
"=",
"self",
".",
"request_token_url",
",",
"params",
"=",
"{",
"'oauth_callback'",
":",
"'oob'",
"}",
")",
"# If the status code is '200' (OK), proceed",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"# Save the JSON-decoded token secret and token",
"self",
".",
"request_token",
"=",
"r",
".",
"json",
"(",
")",
"[",
"'oauth_token'",
"]",
"self",
".",
"request_secret",
"=",
"r",
".",
"json",
"(",
")",
"[",
"'oauth_token_secret'",
"]",
"# Write the token and secret to file",
"self",
".",
"write_token",
"(",
"'request_token'",
",",
"self",
".",
"request_token",
",",
"self",
".",
"request_secret",
")"
]
| Obtain a request token | [
"Obtain",
"a",
"request",
"token"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/databasesetup/rest_auth_class.py#L119-L141 | train |
lowandrew/OLCTools | databasesetup/rest_auth_class.py | REST.get_session_token | def get_session_token(self):
"""
Use the accession token to request a new session token
"""
# self.logging.info('Getting session token')
# Rather than testing any previous session tokens to see if they are still valid, simply delete old tokens in
# preparation of the creation of new ones
try:
os.remove(os.path.join(self.file_path, 'session_token'))
except FileNotFoundError:
pass
# Create a new session
session_request = OAuth1Session(self.consumer_key,
self.consumer_secret,
access_token=self.access_token,
access_token_secret=self.access_secret)
# Perform a GET request with the appropriate keys and tokens
r = session_request.get(self.session_token_url)
# If the status code is '200' (OK), proceed
if r.status_code == 200:
# Save the JSON-decoded token secret and token
self.session_token = r.json()['oauth_token']
self.session_secret = r.json()['oauth_token_secret']
# Write the token and secret to file
self.write_token('session_token', self.session_token, self.session_secret)
# Any other status than 200 is considered a failure
else:
print('Failed:')
print(r.json()['message']) | python | def get_session_token(self):
"""
Use the accession token to request a new session token
"""
# self.logging.info('Getting session token')
# Rather than testing any previous session tokens to see if they are still valid, simply delete old tokens in
# preparation of the creation of new ones
try:
os.remove(os.path.join(self.file_path, 'session_token'))
except FileNotFoundError:
pass
# Create a new session
session_request = OAuth1Session(self.consumer_key,
self.consumer_secret,
access_token=self.access_token,
access_token_secret=self.access_secret)
# Perform a GET request with the appropriate keys and tokens
r = session_request.get(self.session_token_url)
# If the status code is '200' (OK), proceed
if r.status_code == 200:
# Save the JSON-decoded token secret and token
self.session_token = r.json()['oauth_token']
self.session_secret = r.json()['oauth_token_secret']
# Write the token and secret to file
self.write_token('session_token', self.session_token, self.session_secret)
# Any other status than 200 is considered a failure
else:
print('Failed:')
print(r.json()['message']) | [
"def",
"get_session_token",
"(",
"self",
")",
":",
"# self.logging.info('Getting session token')",
"# Rather than testing any previous session tokens to see if they are still valid, simply delete old tokens in",
"# preparation of the creation of new ones",
"try",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"file_path",
",",
"'session_token'",
")",
")",
"except",
"FileNotFoundError",
":",
"pass",
"# Create a new session",
"session_request",
"=",
"OAuth1Session",
"(",
"self",
".",
"consumer_key",
",",
"self",
".",
"consumer_secret",
",",
"access_token",
"=",
"self",
".",
"access_token",
",",
"access_token_secret",
"=",
"self",
".",
"access_secret",
")",
"# Perform a GET request with the appropriate keys and tokens",
"r",
"=",
"session_request",
".",
"get",
"(",
"self",
".",
"session_token_url",
")",
"# If the status code is '200' (OK), proceed",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"# Save the JSON-decoded token secret and token",
"self",
".",
"session_token",
"=",
"r",
".",
"json",
"(",
")",
"[",
"'oauth_token'",
"]",
"self",
".",
"session_secret",
"=",
"r",
".",
"json",
"(",
")",
"[",
"'oauth_token_secret'",
"]",
"# Write the token and secret to file",
"self",
".",
"write_token",
"(",
"'session_token'",
",",
"self",
".",
"session_token",
",",
"self",
".",
"session_secret",
")",
"# Any other status than 200 is considered a failure",
"else",
":",
"print",
"(",
"'Failed:'",
")",
"print",
"(",
"r",
".",
"json",
"(",
")",
"[",
"'message'",
"]",
")"
]
| Use the accession token to request a new session token | [
"Use",
"the",
"accession",
"token",
"to",
"request",
"a",
"new",
"session",
"token"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/databasesetup/rest_auth_class.py#L143-L171 | train |
lowandrew/OLCTools | databasesetup/rest_auth_class.py | REST.parse_session_token | def parse_session_token(self):
"""
Extract the session secret and token strings from the session token file
"""
session_file = os.path.join(self.file_path, 'session_token')
# Only try to extract the strings if the file exists
if os.path.isfile(session_file):
# Create a list to store the data from the file
session_list = list()
with open(session_file, 'r') as session_token:
for line in session_token:
# Split the description e.g. secret= from the line
value, data = line.split('=')
# Add each string to the list
session_list.append(data.rstrip())
# Extract the appropriate variable from the list
self.session_secret = session_list[0]
self.session_token = session_list[1] | python | def parse_session_token(self):
"""
Extract the session secret and token strings from the session token file
"""
session_file = os.path.join(self.file_path, 'session_token')
# Only try to extract the strings if the file exists
if os.path.isfile(session_file):
# Create a list to store the data from the file
session_list = list()
with open(session_file, 'r') as session_token:
for line in session_token:
# Split the description e.g. secret= from the line
value, data = line.split('=')
# Add each string to the list
session_list.append(data.rstrip())
# Extract the appropriate variable from the list
self.session_secret = session_list[0]
self.session_token = session_list[1] | [
"def",
"parse_session_token",
"(",
"self",
")",
":",
"session_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"file_path",
",",
"'session_token'",
")",
"# Only try to extract the strings if the file exists",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"session_file",
")",
":",
"# Create a list to store the data from the file",
"session_list",
"=",
"list",
"(",
")",
"with",
"open",
"(",
"session_file",
",",
"'r'",
")",
"as",
"session_token",
":",
"for",
"line",
"in",
"session_token",
":",
"# Split the description e.g. secret= from the line",
"value",
",",
"data",
"=",
"line",
".",
"split",
"(",
"'='",
")",
"# Add each string to the list",
"session_list",
".",
"append",
"(",
"data",
".",
"rstrip",
"(",
")",
")",
"# Extract the appropriate variable from the list",
"self",
".",
"session_secret",
"=",
"session_list",
"[",
"0",
"]",
"self",
".",
"session_token",
"=",
"session_list",
"[",
"1",
"]"
]
| Extract the session secret and token strings from the session token file | [
"Extract",
"the",
"session",
"secret",
"and",
"token",
"strings",
"from",
"the",
"session",
"token",
"file"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/databasesetup/rest_auth_class.py#L185-L202 | train |
lowandrew/OLCTools | databasesetup/rest_auth_class.py | REST.get_route | def get_route(self):
"""
Creates a session to find the URL for the loci and schemes
"""
# Create a new session
session = OAuth1Session(self.consumer_key,
self.consumer_secret,
access_token=self.session_token,
access_token_secret=self.session_secret)
# Use the test URL in the GET request
r = session.get(self.test_rest_url)
if r.status_code == 200 or r.status_code == 201:
if re.search('json', r.headers['content-type'], flags=0):
decoded = r.json()
else:
decoded = r.text
# Extract the URLs from the returned data
self.loci = decoded['loci']
self.profile = decoded['schemes'] | python | def get_route(self):
"""
Creates a session to find the URL for the loci and schemes
"""
# Create a new session
session = OAuth1Session(self.consumer_key,
self.consumer_secret,
access_token=self.session_token,
access_token_secret=self.session_secret)
# Use the test URL in the GET request
r = session.get(self.test_rest_url)
if r.status_code == 200 or r.status_code == 201:
if re.search('json', r.headers['content-type'], flags=0):
decoded = r.json()
else:
decoded = r.text
# Extract the URLs from the returned data
self.loci = decoded['loci']
self.profile = decoded['schemes'] | [
"def",
"get_route",
"(",
"self",
")",
":",
"# Create a new session",
"session",
"=",
"OAuth1Session",
"(",
"self",
".",
"consumer_key",
",",
"self",
".",
"consumer_secret",
",",
"access_token",
"=",
"self",
".",
"session_token",
",",
"access_token_secret",
"=",
"self",
".",
"session_secret",
")",
"# Use the test URL in the GET request",
"r",
"=",
"session",
".",
"get",
"(",
"self",
".",
"test_rest_url",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
"or",
"r",
".",
"status_code",
"==",
"201",
":",
"if",
"re",
".",
"search",
"(",
"'json'",
",",
"r",
".",
"headers",
"[",
"'content-type'",
"]",
",",
"flags",
"=",
"0",
")",
":",
"decoded",
"=",
"r",
".",
"json",
"(",
")",
"else",
":",
"decoded",
"=",
"r",
".",
"text",
"# Extract the URLs from the returned data",
"self",
".",
"loci",
"=",
"decoded",
"[",
"'loci'",
"]",
"self",
".",
"profile",
"=",
"decoded",
"[",
"'schemes'",
"]"
]
| Creates a session to find the URL for the loci and schemes | [
"Creates",
"a",
"session",
"to",
"find",
"the",
"URL",
"for",
"the",
"loci",
"and",
"schemes"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/databasesetup/rest_auth_class.py#L204-L222 | train |
lowandrew/OLCTools | databasesetup/rest_auth_class.py | REST.download_profile | def download_profile(self):
"""
Download the profile from the database
"""
# Set the name of the profile file
profile_file = os.path.join(self.output_path, 'profile.txt')
size = 0
# Ensure that the file exists, and that it is not too small; likely indicating a failed download
try:
stats = os.stat(profile_file)
size = stats.st_size
except FileNotFoundError:
pass
# Only download the profile if the file doesn't exist, or is likely truncated
if not os.path.isfile(profile_file) or size <= 100:
# Create a new session
session = OAuth1Session(self.consumer_key,
self.consumer_secret,
access_token=self.session_token,
access_token_secret=self.session_secret)
# The profile file is called profiles_csv on the server. Updated the URL appropriately
r = session.get(self.profile + '/1/profiles_csv')
# On a successful GET request, parse the returned data appropriately
if r.status_code == 200 or r.status_code == 201:
if re.search('json', r.headers['content-type'], flags=0):
decoded = r.json()
else:
decoded = r.text
# Write the profile file to disk
with open(profile_file, 'w') as profile:
profile.write(decoded) | python | def download_profile(self):
"""
Download the profile from the database
"""
# Set the name of the profile file
profile_file = os.path.join(self.output_path, 'profile.txt')
size = 0
# Ensure that the file exists, and that it is not too small; likely indicating a failed download
try:
stats = os.stat(profile_file)
size = stats.st_size
except FileNotFoundError:
pass
# Only download the profile if the file doesn't exist, or is likely truncated
if not os.path.isfile(profile_file) or size <= 100:
# Create a new session
session = OAuth1Session(self.consumer_key,
self.consumer_secret,
access_token=self.session_token,
access_token_secret=self.session_secret)
# The profile file is called profiles_csv on the server. Updated the URL appropriately
r = session.get(self.profile + '/1/profiles_csv')
# On a successful GET request, parse the returned data appropriately
if r.status_code == 200 or r.status_code == 201:
if re.search('json', r.headers['content-type'], flags=0):
decoded = r.json()
else:
decoded = r.text
# Write the profile file to disk
with open(profile_file, 'w') as profile:
profile.write(decoded) | [
"def",
"download_profile",
"(",
"self",
")",
":",
"# Set the name of the profile file",
"profile_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"output_path",
",",
"'profile.txt'",
")",
"size",
"=",
"0",
"# Ensure that the file exists, and that it is not too small; likely indicating a failed download",
"try",
":",
"stats",
"=",
"os",
".",
"stat",
"(",
"profile_file",
")",
"size",
"=",
"stats",
".",
"st_size",
"except",
"FileNotFoundError",
":",
"pass",
"# Only download the profile if the file doesn't exist, or is likely truncated",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"profile_file",
")",
"or",
"size",
"<=",
"100",
":",
"# Create a new session",
"session",
"=",
"OAuth1Session",
"(",
"self",
".",
"consumer_key",
",",
"self",
".",
"consumer_secret",
",",
"access_token",
"=",
"self",
".",
"session_token",
",",
"access_token_secret",
"=",
"self",
".",
"session_secret",
")",
"# The profile file is called profiles_csv on the server. Updated the URL appropriately",
"r",
"=",
"session",
".",
"get",
"(",
"self",
".",
"profile",
"+",
"'/1/profiles_csv'",
")",
"# On a successful GET request, parse the returned data appropriately",
"if",
"r",
".",
"status_code",
"==",
"200",
"or",
"r",
".",
"status_code",
"==",
"201",
":",
"if",
"re",
".",
"search",
"(",
"'json'",
",",
"r",
".",
"headers",
"[",
"'content-type'",
"]",
",",
"flags",
"=",
"0",
")",
":",
"decoded",
"=",
"r",
".",
"json",
"(",
")",
"else",
":",
"decoded",
"=",
"r",
".",
"text",
"# Write the profile file to disk",
"with",
"open",
"(",
"profile_file",
",",
"'w'",
")",
"as",
"profile",
":",
"profile",
".",
"write",
"(",
"decoded",
")"
]
| Download the profile from the database | [
"Download",
"the",
"profile",
"from",
"the",
"database"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/databasesetup/rest_auth_class.py#L224-L254 | train |
lowandrew/OLCTools | databasesetup/rest_auth_class.py | REST.find_loci | def find_loci(self):
"""
Finds the URLs for all allele files
"""
session = OAuth1Session(self.consumer_key,
self.consumer_secret,
access_token=self.session_token,
access_token_secret=self.session_secret)
# Use the URL for all loci determined above
r = session.get(self.loci)
if r.status_code == 200 or r.status_code == 201:
if re.search('json', r.headers['content-type'], flags=0):
decoded = r.json()
else:
decoded = r.text
# Extract all the URLs in the decoded dictionary under the key 'loci'
for locus in decoded['loci']:
# Add each URL to the list
self.loci_url.append(locus) | python | def find_loci(self):
"""
Finds the URLs for all allele files
"""
session = OAuth1Session(self.consumer_key,
self.consumer_secret,
access_token=self.session_token,
access_token_secret=self.session_secret)
# Use the URL for all loci determined above
r = session.get(self.loci)
if r.status_code == 200 or r.status_code == 201:
if re.search('json', r.headers['content-type'], flags=0):
decoded = r.json()
else:
decoded = r.text
# Extract all the URLs in the decoded dictionary under the key 'loci'
for locus in decoded['loci']:
# Add each URL to the list
self.loci_url.append(locus) | [
"def",
"find_loci",
"(",
"self",
")",
":",
"session",
"=",
"OAuth1Session",
"(",
"self",
".",
"consumer_key",
",",
"self",
".",
"consumer_secret",
",",
"access_token",
"=",
"self",
".",
"session_token",
",",
"access_token_secret",
"=",
"self",
".",
"session_secret",
")",
"# Use the URL for all loci determined above",
"r",
"=",
"session",
".",
"get",
"(",
"self",
".",
"loci",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
"or",
"r",
".",
"status_code",
"==",
"201",
":",
"if",
"re",
".",
"search",
"(",
"'json'",
",",
"r",
".",
"headers",
"[",
"'content-type'",
"]",
",",
"flags",
"=",
"0",
")",
":",
"decoded",
"=",
"r",
".",
"json",
"(",
")",
"else",
":",
"decoded",
"=",
"r",
".",
"text",
"# Extract all the URLs in the decoded dictionary under the key 'loci'",
"for",
"locus",
"in",
"decoded",
"[",
"'loci'",
"]",
":",
"# Add each URL to the list",
"self",
".",
"loci_url",
".",
"append",
"(",
"locus",
")"
]
| Finds the URLs for all allele files | [
"Finds",
"the",
"URLs",
"for",
"all",
"allele",
"files"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/databasesetup/rest_auth_class.py#L256-L274 | train |
lowandrew/OLCTools | databasesetup/rest_auth_class.py | REST.download_loci | def download_loci(self):
"""
Uses a multi-threaded approach to download allele files
"""
# Setup the multiprocessing pool.
pool = multiprocessing.Pool(processes=self.threads)
# Map the list of loci URLs to the download method
pool.map(self.download_threads, self.loci_url)
pool.close()
pool.join() | python | def download_loci(self):
"""
Uses a multi-threaded approach to download allele files
"""
# Setup the multiprocessing pool.
pool = multiprocessing.Pool(processes=self.threads)
# Map the list of loci URLs to the download method
pool.map(self.download_threads, self.loci_url)
pool.close()
pool.join() | [
"def",
"download_loci",
"(",
"self",
")",
":",
"# Setup the multiprocessing pool.",
"pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"processes",
"=",
"self",
".",
"threads",
")",
"# Map the list of loci URLs to the download method",
"pool",
".",
"map",
"(",
"self",
".",
"download_threads",
",",
"self",
".",
"loci_url",
")",
"pool",
".",
"close",
"(",
")",
"pool",
".",
"join",
"(",
")"
]
| Uses a multi-threaded approach to download allele files | [
"Uses",
"a",
"multi",
"-",
"threaded",
"approach",
"to",
"download",
"allele",
"files"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/databasesetup/rest_auth_class.py#L276-L285 | train |
lowandrew/OLCTools | databasesetup/rest_auth_class.py | REST.download_threads | def download_threads(self, url):
"""
Download the allele files
"""
# Set the name of the allele file - split the gene name from the URL
output_file = os.path.join(self.output_path, '{}.tfa'.format(os.path.split(url)[-1]))
# Check to see whether the file already exists, and if it is unusually small
size = 0
try:
stats = os.stat(output_file)
size = stats.st_size
except FileNotFoundError:
pass
# If the file doesn't exist, or is truncated, proceed with the download
if not os.path.isfile(output_file) or size <= 100:
# Create a new session
session = OAuth1Session(self.consumer_key,
self.consumer_secret,
access_token=self.session_token,
access_token_secret=self.session_secret)
# The allele file on the server is called alleles_fasta. Update the URL appropriately
r = session.get(url + '/alleles_fasta')
if r.status_code == 200 or r.status_code == 201:
if re.search('json', r.headers['content-type'], flags=0):
decoded = r.json()
else:
decoded = r.text
# Write the allele to disk
with open(output_file, 'w') as allele:
allele.write(decoded) | python | def download_threads(self, url):
"""
Download the allele files
"""
# Set the name of the allele file - split the gene name from the URL
output_file = os.path.join(self.output_path, '{}.tfa'.format(os.path.split(url)[-1]))
# Check to see whether the file already exists, and if it is unusually small
size = 0
try:
stats = os.stat(output_file)
size = stats.st_size
except FileNotFoundError:
pass
# If the file doesn't exist, or is truncated, proceed with the download
if not os.path.isfile(output_file) or size <= 100:
# Create a new session
session = OAuth1Session(self.consumer_key,
self.consumer_secret,
access_token=self.session_token,
access_token_secret=self.session_secret)
# The allele file on the server is called alleles_fasta. Update the URL appropriately
r = session.get(url + '/alleles_fasta')
if r.status_code == 200 or r.status_code == 201:
if re.search('json', r.headers['content-type'], flags=0):
decoded = r.json()
else:
decoded = r.text
# Write the allele to disk
with open(output_file, 'w') as allele:
allele.write(decoded) | [
"def",
"download_threads",
"(",
"self",
",",
"url",
")",
":",
"# Set the name of the allele file - split the gene name from the URL",
"output_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"output_path",
",",
"'{}.tfa'",
".",
"format",
"(",
"os",
".",
"path",
".",
"split",
"(",
"url",
")",
"[",
"-",
"1",
"]",
")",
")",
"# Check to see whether the file already exists, and if it is unusually small",
"size",
"=",
"0",
"try",
":",
"stats",
"=",
"os",
".",
"stat",
"(",
"output_file",
")",
"size",
"=",
"stats",
".",
"st_size",
"except",
"FileNotFoundError",
":",
"pass",
"# If the file doesn't exist, or is truncated, proceed with the download",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"output_file",
")",
"or",
"size",
"<=",
"100",
":",
"# Create a new session",
"session",
"=",
"OAuth1Session",
"(",
"self",
".",
"consumer_key",
",",
"self",
".",
"consumer_secret",
",",
"access_token",
"=",
"self",
".",
"session_token",
",",
"access_token_secret",
"=",
"self",
".",
"session_secret",
")",
"# The allele file on the server is called alleles_fasta. Update the URL appropriately",
"r",
"=",
"session",
".",
"get",
"(",
"url",
"+",
"'/alleles_fasta'",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
"or",
"r",
".",
"status_code",
"==",
"201",
":",
"if",
"re",
".",
"search",
"(",
"'json'",
",",
"r",
".",
"headers",
"[",
"'content-type'",
"]",
",",
"flags",
"=",
"0",
")",
":",
"decoded",
"=",
"r",
".",
"json",
"(",
")",
"else",
":",
"decoded",
"=",
"r",
".",
"text",
"# Write the allele to disk",
"with",
"open",
"(",
"output_file",
",",
"'w'",
")",
"as",
"allele",
":",
"allele",
".",
"write",
"(",
"decoded",
")"
]
| Download the allele files | [
"Download",
"the",
"allele",
"files"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/databasesetup/rest_auth_class.py#L287-L316 | train |
by46/simplekit | simplekit/objson/dolphin2.py | dumps | def dumps(obj, *args, **kwargs):
"""Serialize a object to string
Basic Usage:
>>> import simplekit.objson
>>> obj = {'name':'wendy'}
>>> print simplekit.objson.dumps(obj)
:param obj: a object which need to dump
:param args: Optional arguments that :func:`json.dumps` takes.
:param kwargs: Keys arguments that :py:func:`json.dumps` takes.
:return: string
"""
kwargs['default'] = object2dict
return json.dumps(obj, *args, **kwargs) | python | def dumps(obj, *args, **kwargs):
"""Serialize a object to string
Basic Usage:
>>> import simplekit.objson
>>> obj = {'name':'wendy'}
>>> print simplekit.objson.dumps(obj)
:param obj: a object which need to dump
:param args: Optional arguments that :func:`json.dumps` takes.
:param kwargs: Keys arguments that :py:func:`json.dumps` takes.
:return: string
"""
kwargs['default'] = object2dict
return json.dumps(obj, *args, **kwargs) | [
"def",
"dumps",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'default'",
"]",
"=",
"object2dict",
"return",
"json",
".",
"dumps",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
]
| Serialize a object to string
Basic Usage:
>>> import simplekit.objson
>>> obj = {'name':'wendy'}
>>> print simplekit.objson.dumps(obj)
:param obj: a object which need to dump
:param args: Optional arguments that :func:`json.dumps` takes.
:param kwargs: Keys arguments that :py:func:`json.dumps` takes.
:return: string | [
"Serialize",
"a",
"object",
"to",
"string"
]
| 33f3ce6de33accc185e1057f096af41859db5976 | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/objson/dolphin2.py#L78-L95 | train |
by46/simplekit | simplekit/objson/dolphin2.py | dump | def dump(obj, fp, *args, **kwargs):
"""Serialize a object to a file object.
Basic Usage:
>>> import simplekit.objson
>>> from cStringIO import StringIO
>>> obj = {'name': 'wendy'}
>>> io = StringIO()
>>> simplekit.objson.dump(obj, io)
>>> print io.getvalue()
:param obj: a object which need to dump
:param fp: a instance of file object
:param args: Optional arguments that :func:`json.dump` takes.
:param kwargs: Keys arguments that :func:`json.dump` takes.
:return: None
"""
kwargs['default'] = object2dict
json.dump(obj, fp, *args, **kwargs) | python | def dump(obj, fp, *args, **kwargs):
"""Serialize a object to a file object.
Basic Usage:
>>> import simplekit.objson
>>> from cStringIO import StringIO
>>> obj = {'name': 'wendy'}
>>> io = StringIO()
>>> simplekit.objson.dump(obj, io)
>>> print io.getvalue()
:param obj: a object which need to dump
:param fp: a instance of file object
:param args: Optional arguments that :func:`json.dump` takes.
:param kwargs: Keys arguments that :func:`json.dump` takes.
:return: None
"""
kwargs['default'] = object2dict
json.dump(obj, fp, *args, **kwargs) | [
"def",
"dump",
"(",
"obj",
",",
"fp",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'default'",
"]",
"=",
"object2dict",
"json",
".",
"dump",
"(",
"obj",
",",
"fp",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
]
| Serialize a object to a file object.
Basic Usage:
>>> import simplekit.objson
>>> from cStringIO import StringIO
>>> obj = {'name': 'wendy'}
>>> io = StringIO()
>>> simplekit.objson.dump(obj, io)
>>> print io.getvalue()
:param obj: a object which need to dump
:param fp: a instance of file object
:param args: Optional arguments that :func:`json.dump` takes.
:param kwargs: Keys arguments that :func:`json.dump` takes.
:return: None | [
"Serialize",
"a",
"object",
"to",
"a",
"file",
"object",
"."
]
| 33f3ce6de33accc185e1057f096af41859db5976 | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/objson/dolphin2.py#L98-L118 | train |
jayme-github/steam_idle | steam_idle/idle.py | calc_delay | def calc_delay(remainingDrops):
''' Calculate the idle delay
Minimum play time for cards to drop is ~20min again. Except for accounts
that requested a refund?
Re-check every 15 mintes if there are more than 1 card drops remaining.
If only one drop remains, check every 5 minutes
'''
global sameDelay, lastDelay
# Reset lastDelay for new appids
if remainingDrops > 1:
lastDelay = 5
sameDelay = 0
if remainingDrops > 2:
return 15 * 60 # Check every 15 minutes
elif remainingDrops == 2:
return 10 * 60 # Check every 10 minutes
else:
# decrease delay by one minute every two calls
if lastDelay > 1:
if sameDelay == 2:
sameDelay = 0
lastDelay -= 1
sameDelay += 1
return lastDelay * 60 | python | def calc_delay(remainingDrops):
''' Calculate the idle delay
Minimum play time for cards to drop is ~20min again. Except for accounts
that requested a refund?
Re-check every 15 mintes if there are more than 1 card drops remaining.
If only one drop remains, check every 5 minutes
'''
global sameDelay, lastDelay
# Reset lastDelay for new appids
if remainingDrops > 1:
lastDelay = 5
sameDelay = 0
if remainingDrops > 2:
return 15 * 60 # Check every 15 minutes
elif remainingDrops == 2:
return 10 * 60 # Check every 10 minutes
else:
# decrease delay by one minute every two calls
if lastDelay > 1:
if sameDelay == 2:
sameDelay = 0
lastDelay -= 1
sameDelay += 1
return lastDelay * 60 | [
"def",
"calc_delay",
"(",
"remainingDrops",
")",
":",
"global",
"sameDelay",
",",
"lastDelay",
"# Reset lastDelay for new appids",
"if",
"remainingDrops",
">",
"1",
":",
"lastDelay",
"=",
"5",
"sameDelay",
"=",
"0",
"if",
"remainingDrops",
">",
"2",
":",
"return",
"15",
"*",
"60",
"# Check every 15 minutes",
"elif",
"remainingDrops",
"==",
"2",
":",
"return",
"10",
"*",
"60",
"# Check every 10 minutes",
"else",
":",
"# decrease delay by one minute every two calls",
"if",
"lastDelay",
">",
"1",
":",
"if",
"sameDelay",
"==",
"2",
":",
"sameDelay",
"=",
"0",
"lastDelay",
"-=",
"1",
"sameDelay",
"+=",
"1",
"return",
"lastDelay",
"*",
"60"
]
| Calculate the idle delay
Minimum play time for cards to drop is ~20min again. Except for accounts
that requested a refund?
Re-check every 15 mintes if there are more than 1 card drops remaining.
If only one drop remains, check every 5 minutes | [
"Calculate",
"the",
"idle",
"delay",
"Minimum",
"play",
"time",
"for",
"cards",
"to",
"drop",
"is",
"~20min",
"again",
".",
"Except",
"for",
"accounts",
"that",
"requested",
"a",
"refund?"
]
| 4f9b887fd6c3aea3baa9087f88ee739efcc150cc | https://github.com/jayme-github/steam_idle/blob/4f9b887fd6c3aea3baa9087f88ee739efcc150cc/steam_idle/idle.py#L53-L79 | train |
lowandrew/OLCTools | spadespipeline/fastqCreator.py | CreateFastq.configfilepopulator | def configfilepopulator(self):
"""Populates an unpopulated config.xml file with run-specific values and creates
the file in the appropriate location"""
# Set the number of cycles for each read and index using the number of reads specified in the sample sheet
self.forwardlength = self.metadata.header.forwardlength
self.reverselength = self.metadata.header.reverselength
# Create a list of lists containing [cycle start, cycle end, and :runid] for each of forward reads, index 1
# index 2, and reverse reads
cycles = [[1, self.forwardlength, self.runid],
[self.forwardlength + 1, self.forwardlength + 8, self.runid],
[self.forwardlength + 9, self.forwardlength + 16, self.runid],
[self.forwardlength + 17, self.forwardlength + 16 + self.reverselength, self.runid]]
# A dictionary of parameters (keys) and the values to use when repopulating the config file
parameters = {'RunFolder': self.runid, 'RunFolderDate': self.metadata.date.replace("-", ""),
'RunFolderId': self.metadata.runnumber, 'RunFlowcellId': self.metadata.flowcell}
# Load the xml file using element tree
config = ElementTree.parse("{}/config.xml".format(self.homepath))
# Get the root of the tree
configroot = config.getroot()
# The run node is the only child node of the root
for run in configroot:
# Iterate through the child nodes. There are three nodes sections that must be populated
for child in run:
# Find the cycles tag
if child.tag == 'Cycles':
# Set the attributes with a dictionary containing the total reads
child.attrib = {'Last': '{}'.format(self.forwardlength + 16 + self.reverselength),
'Number': '{}'.format(self.totalreads), 'First': '1'}
elif child.tag == 'RunParameters':
# Name the child as runparameter for easier coding
runparameters = child
for runparameter in runparameters:
# This replaces data in both 'ImagingReads' and 'Reads' nodes
if 'Reads' in runparameter.tag:
# Enumerate through the run parameters
for indexcount, reads in enumerate(runparameter):
# The values for the index are 1, 2, 3, 4. Subtract one to get the index of the first
# list in cycles
index = int(runparameter.attrib['Index']) - 1
# Set the text value as the appropriate value from cycles
reads.text = str(cycles[index][indexcount])
# Populate the instrument value
if runparameter.tag == 'Instrument':
runparameter.text = self.instrument
# Iterate through the parameters in the parameter dictionary
for parameter in parameters:
# If the key is encountered
if runparameter.tag == parameter:
# Replace the text with the value
runparameter.text = parameters[parameter]
if 'Barcode' in runparameter.tag:
for cycle, barcode in enumerate(runparameter):
# Add the barcode cycles. These are the number of forward reads (+ 1 as the barcode
# starts 1 cycle after the first run) plus the current iterator
barcode.text = str(self.forwardlength + 1 + cycle)
# Write the modified config file to the desired location
config.write('{}Data/Intensities/BaseCalls/config.xml'.format(self.miseqfolder)) | python | def configfilepopulator(self):
"""Populates an unpopulated config.xml file with run-specific values and creates
the file in the appropriate location"""
# Set the number of cycles for each read and index using the number of reads specified in the sample sheet
self.forwardlength = self.metadata.header.forwardlength
self.reverselength = self.metadata.header.reverselength
# Create a list of lists containing [cycle start, cycle end, and :runid] for each of forward reads, index 1
# index 2, and reverse reads
cycles = [[1, self.forwardlength, self.runid],
[self.forwardlength + 1, self.forwardlength + 8, self.runid],
[self.forwardlength + 9, self.forwardlength + 16, self.runid],
[self.forwardlength + 17, self.forwardlength + 16 + self.reverselength, self.runid]]
# A dictionary of parameters (keys) and the values to use when repopulating the config file
parameters = {'RunFolder': self.runid, 'RunFolderDate': self.metadata.date.replace("-", ""),
'RunFolderId': self.metadata.runnumber, 'RunFlowcellId': self.metadata.flowcell}
# Load the xml file using element tree
config = ElementTree.parse("{}/config.xml".format(self.homepath))
# Get the root of the tree
configroot = config.getroot()
# The run node is the only child node of the root
for run in configroot:
# Iterate through the child nodes. There are three nodes sections that must be populated
for child in run:
# Find the cycles tag
if child.tag == 'Cycles':
# Set the attributes with a dictionary containing the total reads
child.attrib = {'Last': '{}'.format(self.forwardlength + 16 + self.reverselength),
'Number': '{}'.format(self.totalreads), 'First': '1'}
elif child.tag == 'RunParameters':
# Name the child as runparameter for easier coding
runparameters = child
for runparameter in runparameters:
# This replaces data in both 'ImagingReads' and 'Reads' nodes
if 'Reads' in runparameter.tag:
# Enumerate through the run parameters
for indexcount, reads in enumerate(runparameter):
# The values for the index are 1, 2, 3, 4. Subtract one to get the index of the first
# list in cycles
index = int(runparameter.attrib['Index']) - 1
# Set the text value as the appropriate value from cycles
reads.text = str(cycles[index][indexcount])
# Populate the instrument value
if runparameter.tag == 'Instrument':
runparameter.text = self.instrument
# Iterate through the parameters in the parameter dictionary
for parameter in parameters:
# If the key is encountered
if runparameter.tag == parameter:
# Replace the text with the value
runparameter.text = parameters[parameter]
if 'Barcode' in runparameter.tag:
for cycle, barcode in enumerate(runparameter):
# Add the barcode cycles. These are the number of forward reads (+ 1 as the barcode
# starts 1 cycle after the first run) plus the current iterator
barcode.text = str(self.forwardlength + 1 + cycle)
# Write the modified config file to the desired location
config.write('{}Data/Intensities/BaseCalls/config.xml'.format(self.miseqfolder)) | [
"def",
"configfilepopulator",
"(",
"self",
")",
":",
"# Set the number of cycles for each read and index using the number of reads specified in the sample sheet",
"self",
".",
"forwardlength",
"=",
"self",
".",
"metadata",
".",
"header",
".",
"forwardlength",
"self",
".",
"reverselength",
"=",
"self",
".",
"metadata",
".",
"header",
".",
"reverselength",
"# Create a list of lists containing [cycle start, cycle end, and :runid] for each of forward reads, index 1",
"# index 2, and reverse reads",
"cycles",
"=",
"[",
"[",
"1",
",",
"self",
".",
"forwardlength",
",",
"self",
".",
"runid",
"]",
",",
"[",
"self",
".",
"forwardlength",
"+",
"1",
",",
"self",
".",
"forwardlength",
"+",
"8",
",",
"self",
".",
"runid",
"]",
",",
"[",
"self",
".",
"forwardlength",
"+",
"9",
",",
"self",
".",
"forwardlength",
"+",
"16",
",",
"self",
".",
"runid",
"]",
",",
"[",
"self",
".",
"forwardlength",
"+",
"17",
",",
"self",
".",
"forwardlength",
"+",
"16",
"+",
"self",
".",
"reverselength",
",",
"self",
".",
"runid",
"]",
"]",
"# A dictionary of parameters (keys) and the values to use when repopulating the config file",
"parameters",
"=",
"{",
"'RunFolder'",
":",
"self",
".",
"runid",
",",
"'RunFolderDate'",
":",
"self",
".",
"metadata",
".",
"date",
".",
"replace",
"(",
"\"-\"",
",",
"\"\"",
")",
",",
"'RunFolderId'",
":",
"self",
".",
"metadata",
".",
"runnumber",
",",
"'RunFlowcellId'",
":",
"self",
".",
"metadata",
".",
"flowcell",
"}",
"# Load the xml file using element tree",
"config",
"=",
"ElementTree",
".",
"parse",
"(",
"\"{}/config.xml\"",
".",
"format",
"(",
"self",
".",
"homepath",
")",
")",
"# Get the root of the tree",
"configroot",
"=",
"config",
".",
"getroot",
"(",
")",
"# The run node is the only child node of the root",
"for",
"run",
"in",
"configroot",
":",
"# Iterate through the child nodes. There are three nodes sections that must be populated",
"for",
"child",
"in",
"run",
":",
"# Find the cycles tag",
"if",
"child",
".",
"tag",
"==",
"'Cycles'",
":",
"# Set the attributes with a dictionary containing the total reads",
"child",
".",
"attrib",
"=",
"{",
"'Last'",
":",
"'{}'",
".",
"format",
"(",
"self",
".",
"forwardlength",
"+",
"16",
"+",
"self",
".",
"reverselength",
")",
",",
"'Number'",
":",
"'{}'",
".",
"format",
"(",
"self",
".",
"totalreads",
")",
",",
"'First'",
":",
"'1'",
"}",
"elif",
"child",
".",
"tag",
"==",
"'RunParameters'",
":",
"# Name the child as runparameter for easier coding",
"runparameters",
"=",
"child",
"for",
"runparameter",
"in",
"runparameters",
":",
"# This replaces data in both 'ImagingReads' and 'Reads' nodes",
"if",
"'Reads'",
"in",
"runparameter",
".",
"tag",
":",
"# Enumerate through the run parameters",
"for",
"indexcount",
",",
"reads",
"in",
"enumerate",
"(",
"runparameter",
")",
":",
"# The values for the index are 1, 2, 3, 4. Subtract one to get the index of the first",
"# list in cycles",
"index",
"=",
"int",
"(",
"runparameter",
".",
"attrib",
"[",
"'Index'",
"]",
")",
"-",
"1",
"# Set the text value as the appropriate value from cycles",
"reads",
".",
"text",
"=",
"str",
"(",
"cycles",
"[",
"index",
"]",
"[",
"indexcount",
"]",
")",
"# Populate the instrument value",
"if",
"runparameter",
".",
"tag",
"==",
"'Instrument'",
":",
"runparameter",
".",
"text",
"=",
"self",
".",
"instrument",
"# Iterate through the parameters in the parameter dictionary",
"for",
"parameter",
"in",
"parameters",
":",
"# If the key is encountered",
"if",
"runparameter",
".",
"tag",
"==",
"parameter",
":",
"# Replace the text with the value",
"runparameter",
".",
"text",
"=",
"parameters",
"[",
"parameter",
"]",
"if",
"'Barcode'",
"in",
"runparameter",
".",
"tag",
":",
"for",
"cycle",
",",
"barcode",
"in",
"enumerate",
"(",
"runparameter",
")",
":",
"# Add the barcode cycles. These are the number of forward reads (+ 1 as the barcode",
"# starts 1 cycle after the first run) plus the current iterator",
"barcode",
".",
"text",
"=",
"str",
"(",
"self",
".",
"forwardlength",
"+",
"1",
"+",
"cycle",
")",
"# Write the modified config file to the desired location",
"config",
".",
"write",
"(",
"'{}Data/Intensities/BaseCalls/config.xml'",
".",
"format",
"(",
"self",
".",
"miseqfolder",
")",
")"
]
| Populates an unpopulated config.xml file with run-specific values and creates
the file in the appropriate location | [
"Populates",
"an",
"unpopulated",
"config",
".",
"xml",
"file",
"with",
"run",
"-",
"specific",
"values",
"and",
"creates",
"the",
"file",
"in",
"the",
"appropriate",
"location"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/fastqCreator.py#L138-L194 | train |
yamcs/yamcs-python | yamcs-client/examples/change_alarms.py | subscribe_param | def subscribe_param():
"""Print value of parameter"""
def print_data(data):
for parameter in data.parameters:
print(parameter)
processor.create_parameter_subscription('/YSS/SIMULATOR/BatteryVoltage2',
on_data=print_data) | python | def subscribe_param():
"""Print value of parameter"""
def print_data(data):
for parameter in data.parameters:
print(parameter)
processor.create_parameter_subscription('/YSS/SIMULATOR/BatteryVoltage2',
on_data=print_data) | [
"def",
"subscribe_param",
"(",
")",
":",
"def",
"print_data",
"(",
"data",
")",
":",
"for",
"parameter",
"in",
"data",
".",
"parameters",
":",
"print",
"(",
"parameter",
")",
"processor",
".",
"create_parameter_subscription",
"(",
"'/YSS/SIMULATOR/BatteryVoltage2'",
",",
"on_data",
"=",
"print_data",
")"
]
| Print value of parameter | [
"Print",
"value",
"of",
"parameter"
]
| 1082fee8a299010cc44416bbb7518fac0ef08b48 | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/examples/change_alarms.py#L7-L14 | train |
wanshot/holiday | holiday/core.py | Holiday._check_holiday_structure | def _check_holiday_structure(self, times):
""" To check the structure of the HolidayClass
:param list times: years or months or days or number week
:rtype: None or Exception
:return: in the case of exception returns the exception
"""
if not isinstance(times, list):
raise TypeError("an list is required")
for time in times:
if not isinstance(time, tuple):
raise TypeError("a tuple is required")
if len(time) > 5:
raise TypeError("Target time takes at most 5 arguments"
" ('%d' given)" % len(time))
if len(time) < 5:
raise TypeError("Required argument '%s' (pos '%d')"
" not found" % (TIME_LABEL[len(time)], len(time)))
self._check_time_format(TIME_LABEL, time) | python | def _check_holiday_structure(self, times):
""" To check the structure of the HolidayClass
:param list times: years or months or days or number week
:rtype: None or Exception
:return: in the case of exception returns the exception
"""
if not isinstance(times, list):
raise TypeError("an list is required")
for time in times:
if not isinstance(time, tuple):
raise TypeError("a tuple is required")
if len(time) > 5:
raise TypeError("Target time takes at most 5 arguments"
" ('%d' given)" % len(time))
if len(time) < 5:
raise TypeError("Required argument '%s' (pos '%d')"
" not found" % (TIME_LABEL[len(time)], len(time)))
self._check_time_format(TIME_LABEL, time) | [
"def",
"_check_holiday_structure",
"(",
"self",
",",
"times",
")",
":",
"if",
"not",
"isinstance",
"(",
"times",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"an list is required\"",
")",
"for",
"time",
"in",
"times",
":",
"if",
"not",
"isinstance",
"(",
"time",
",",
"tuple",
")",
":",
"raise",
"TypeError",
"(",
"\"a tuple is required\"",
")",
"if",
"len",
"(",
"time",
")",
">",
"5",
":",
"raise",
"TypeError",
"(",
"\"Target time takes at most 5 arguments\"",
"\" ('%d' given)\"",
"%",
"len",
"(",
"time",
")",
")",
"if",
"len",
"(",
"time",
")",
"<",
"5",
":",
"raise",
"TypeError",
"(",
"\"Required argument '%s' (pos '%d')\"",
"\" not found\"",
"%",
"(",
"TIME_LABEL",
"[",
"len",
"(",
"time",
")",
"]",
",",
"len",
"(",
"time",
")",
")",
")",
"self",
".",
"_check_time_format",
"(",
"TIME_LABEL",
",",
"time",
")"
]
| To check the structure of the HolidayClass
:param list times: years or months or days or number week
:rtype: None or Exception
:return: in the case of exception returns the exception | [
"To",
"check",
"the",
"structure",
"of",
"the",
"HolidayClass"
]
| e08681c237d684aa05ba2f98b3baa388dab9eea6 | https://github.com/wanshot/holiday/blob/e08681c237d684aa05ba2f98b3baa388dab9eea6/holiday/core.py#L75-L96 | train |
wanshot/holiday | holiday/core.py | Holiday._check_time_format | def _check_time_format(self, labels, values):
""" To check the format of the times
:param list labels: years or months or days or number week
:param list values: number or the asterisk in the list
:rtype: None or Exception
:raises PeriodRangeError: outside the scope of the period
:raises ParseError: not parse the day of the week
:return: in the case of exception returns the exception
"""
for label, value in zip(labels, values):
if value == "*":
continue
if label == "day_of_week":
if isinstance(value, string_types):
if value not in ORDER_WEEK:
raise ParseError("'%s' is not day of the week. "
"character is the only '%s'" % (
value, ', '.join(ORDER_WEEK)))
elif not isinstance(value, int):
raise TypeError("'%s' is not an int" % value)
if label in ["year", "month", "day", "num_of_week"]:
if not isinstance(value, int):
raise TypeError("'%s' is not an int" % value)
if isinstance(value, int):
start, end = TIME_INFO[label]
if not start <= value <= end:
raise PeriodRangeError("'%d' is outside the scope of the period "
"'%s' range: '%d' to '%d'" % (
value, label, start, end)) | python | def _check_time_format(self, labels, values):
""" To check the format of the times
:param list labels: years or months or days or number week
:param list values: number or the asterisk in the list
:rtype: None or Exception
:raises PeriodRangeError: outside the scope of the period
:raises ParseError: not parse the day of the week
:return: in the case of exception returns the exception
"""
for label, value in zip(labels, values):
if value == "*":
continue
if label == "day_of_week":
if isinstance(value, string_types):
if value not in ORDER_WEEK:
raise ParseError("'%s' is not day of the week. "
"character is the only '%s'" % (
value, ', '.join(ORDER_WEEK)))
elif not isinstance(value, int):
raise TypeError("'%s' is not an int" % value)
if label in ["year", "month", "day", "num_of_week"]:
if not isinstance(value, int):
raise TypeError("'%s' is not an int" % value)
if isinstance(value, int):
start, end = TIME_INFO[label]
if not start <= value <= end:
raise PeriodRangeError("'%d' is outside the scope of the period "
"'%s' range: '%d' to '%d'" % (
value, label, start, end)) | [
"def",
"_check_time_format",
"(",
"self",
",",
"labels",
",",
"values",
")",
":",
"for",
"label",
",",
"value",
"in",
"zip",
"(",
"labels",
",",
"values",
")",
":",
"if",
"value",
"==",
"\"*\"",
":",
"continue",
"if",
"label",
"==",
"\"day_of_week\"",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"if",
"value",
"not",
"in",
"ORDER_WEEK",
":",
"raise",
"ParseError",
"(",
"\"'%s' is not day of the week. \"",
"\"character is the only '%s'\"",
"%",
"(",
"value",
",",
"', '",
".",
"join",
"(",
"ORDER_WEEK",
")",
")",
")",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"'%s' is not an int\"",
"%",
"value",
")",
"if",
"label",
"in",
"[",
"\"year\"",
",",
"\"month\"",
",",
"\"day\"",
",",
"\"num_of_week\"",
"]",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"'%s' is not an int\"",
"%",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"start",
",",
"end",
"=",
"TIME_INFO",
"[",
"label",
"]",
"if",
"not",
"start",
"<=",
"value",
"<=",
"end",
":",
"raise",
"PeriodRangeError",
"(",
"\"'%d' is outside the scope of the period \"",
"\"'%s' range: '%d' to '%d'\"",
"%",
"(",
"value",
",",
"label",
",",
"start",
",",
"end",
")",
")"
]
| To check the format of the times
:param list labels: years or months or days or number week
:param list values: number or the asterisk in the list
:rtype: None or Exception
:raises PeriodRangeError: outside the scope of the period
:raises ParseError: not parse the day of the week
:return: in the case of exception returns the exception | [
"To",
"check",
"the",
"format",
"of",
"the",
"times"
]
| e08681c237d684aa05ba2f98b3baa388dab9eea6 | https://github.com/wanshot/holiday/blob/e08681c237d684aa05ba2f98b3baa388dab9eea6/holiday/core.py#L98-L130 | train |
wanshot/holiday | holiday/core.py | Holiday.is_holiday | def is_holiday(self, date):
""" Whether holiday judges
:param datetime date: datetime.date object
:rtype: bool
"""
time = [
date.year,
date.month,
date.day,
date.isoweekday(),
_extract_week_number(date)
]
target = []
for key, data in list(zip(TIME_LABEL, time)):
d = getattr(self, key)
asterisk = d.get("*", set())
s = asterisk.union(d.get(data, set()))
target.append(list(s))
for result in map(set, product(*target)):
if len(result) == 1:
return True
return False | python | def is_holiday(self, date):
""" Whether holiday judges
:param datetime date: datetime.date object
:rtype: bool
"""
time = [
date.year,
date.month,
date.day,
date.isoweekday(),
_extract_week_number(date)
]
target = []
for key, data in list(zip(TIME_LABEL, time)):
d = getattr(self, key)
asterisk = d.get("*", set())
s = asterisk.union(d.get(data, set()))
target.append(list(s))
for result in map(set, product(*target)):
if len(result) == 1:
return True
return False | [
"def",
"is_holiday",
"(",
"self",
",",
"date",
")",
":",
"time",
"=",
"[",
"date",
".",
"year",
",",
"date",
".",
"month",
",",
"date",
".",
"day",
",",
"date",
".",
"isoweekday",
"(",
")",
",",
"_extract_week_number",
"(",
"date",
")",
"]",
"target",
"=",
"[",
"]",
"for",
"key",
",",
"data",
"in",
"list",
"(",
"zip",
"(",
"TIME_LABEL",
",",
"time",
")",
")",
":",
"d",
"=",
"getattr",
"(",
"self",
",",
"key",
")",
"asterisk",
"=",
"d",
".",
"get",
"(",
"\"*\"",
",",
"set",
"(",
")",
")",
"s",
"=",
"asterisk",
".",
"union",
"(",
"d",
".",
"get",
"(",
"data",
",",
"set",
"(",
")",
")",
")",
"target",
".",
"append",
"(",
"list",
"(",
"s",
")",
")",
"for",
"result",
"in",
"map",
"(",
"set",
",",
"product",
"(",
"*",
"target",
")",
")",
":",
"if",
"len",
"(",
"result",
")",
"==",
"1",
":",
"return",
"True",
"return",
"False"
]
| Whether holiday judges
:param datetime date: datetime.date object
:rtype: bool | [
"Whether",
"holiday",
"judges"
]
| e08681c237d684aa05ba2f98b3baa388dab9eea6 | https://github.com/wanshot/holiday/blob/e08681c237d684aa05ba2f98b3baa388dab9eea6/holiday/core.py#L132-L156 | train |
kevinconway/venvctrl | venvctrl/venv/create.py | CreateMixin.create | def create(self, python=None, system_site=False, always_copy=False):
"""Create a new virtual environment.
Args:
python (str): The name or path of a python interpreter to use while
creating the virtual environment.
system_site (bool): Whether or not use use the system site packages
within the virtual environment. Default is False.
always_copy (bool): Whether or not to force copying instead of
symlinking in the virtual environment. Default is False.
"""
command = 'virtualenv'
if python:
command = '{0} --python={1}'.format(command, python)
if system_site:
command = '{0} --system-site-packages'.format(command)
if always_copy:
command = '{0} --always-copy'.format(command)
command = '{0} {1}'.format(command, self.path)
self._execute(command) | python | def create(self, python=None, system_site=False, always_copy=False):
"""Create a new virtual environment.
Args:
python (str): The name or path of a python interpreter to use while
creating the virtual environment.
system_site (bool): Whether or not use use the system site packages
within the virtual environment. Default is False.
always_copy (bool): Whether or not to force copying instead of
symlinking in the virtual environment. Default is False.
"""
command = 'virtualenv'
if python:
command = '{0} --python={1}'.format(command, python)
if system_site:
command = '{0} --system-site-packages'.format(command)
if always_copy:
command = '{0} --always-copy'.format(command)
command = '{0} {1}'.format(command, self.path)
self._execute(command) | [
"def",
"create",
"(",
"self",
",",
"python",
"=",
"None",
",",
"system_site",
"=",
"False",
",",
"always_copy",
"=",
"False",
")",
":",
"command",
"=",
"'virtualenv'",
"if",
"python",
":",
"command",
"=",
"'{0} --python={1}'",
".",
"format",
"(",
"command",
",",
"python",
")",
"if",
"system_site",
":",
"command",
"=",
"'{0} --system-site-packages'",
".",
"format",
"(",
"command",
")",
"if",
"always_copy",
":",
"command",
"=",
"'{0} --always-copy'",
".",
"format",
"(",
"command",
")",
"command",
"=",
"'{0} {1}'",
".",
"format",
"(",
"command",
",",
"self",
".",
"path",
")",
"self",
".",
"_execute",
"(",
"command",
")"
]
| Create a new virtual environment.
Args:
python (str): The name or path of a python interpreter to use while
creating the virtual environment.
system_site (bool): Whether or not use use the system site packages
within the virtual environment. Default is False.
always_copy (bool): Whether or not to force copying instead of
symlinking in the virtual environment. Default is False. | [
"Create",
"a",
"new",
"virtual",
"environment",
"."
]
| 36d4e0e4d5ebced6385a6ade1198f4769ff2df41 | https://github.com/kevinconway/venvctrl/blob/36d4e0e4d5ebced6385a6ade1198f4769ff2df41/venvctrl/venv/create.py#L16-L41 | train |
lowandrew/OLCTools | spadespipeline/vtyper.py | Vtyper.epcrparse | def epcrparse(self):
"""
Parse the ePCR text file outputs
"""
logging.info('Parsing ePCR results')
for sample in self.metadata:
if sample.general.bestassemblyfile != 'NA':
if 'stx' in sample.general.datastore:
# Initialise count - this allows for the population of vtyperresults with unique values
uniquecount = 0
# This populates vtyperresults with the verotoxin subtypes
toxinlist = []
if os.path.isfile(sample[self.analysistype].resultsfile):
epcrresults = open(sample[self.analysistype].resultsfile, 'r')
for result in epcrresults:
# Only the lines without a # contain results
if "#" not in result:
uniquecount += 1
# Split on \t
data = result.split('\t')
# The subtyping primer pair is the first entry on lines with results
vttype = data[0].split('_')[0]
# Push the name of the primer pair - stripped of anything after a _ to the dictionary
if vttype not in toxinlist:
toxinlist.append(vttype)
# Create a string of the entries in list1 joined with ";"
toxinstring = ";".join(sorted(toxinlist))
# Save the string to the metadata
sample[self.analysistype].toxinprofile = toxinstring
else:
setattr(sample, self.analysistype, GenObject())
sample[self.analysistype].toxinprofile = 'NA'
else:
setattr(sample, self.analysistype, GenObject())
sample[self.analysistype].toxinprofile = 'NA' | python | def epcrparse(self):
"""
Parse the ePCR text file outputs
"""
logging.info('Parsing ePCR results')
for sample in self.metadata:
if sample.general.bestassemblyfile != 'NA':
if 'stx' in sample.general.datastore:
# Initialise count - this allows for the population of vtyperresults with unique values
uniquecount = 0
# This populates vtyperresults with the verotoxin subtypes
toxinlist = []
if os.path.isfile(sample[self.analysistype].resultsfile):
epcrresults = open(sample[self.analysistype].resultsfile, 'r')
for result in epcrresults:
# Only the lines without a # contain results
if "#" not in result:
uniquecount += 1
# Split on \t
data = result.split('\t')
# The subtyping primer pair is the first entry on lines with results
vttype = data[0].split('_')[0]
# Push the name of the primer pair - stripped of anything after a _ to the dictionary
if vttype not in toxinlist:
toxinlist.append(vttype)
# Create a string of the entries in list1 joined with ";"
toxinstring = ";".join(sorted(toxinlist))
# Save the string to the metadata
sample[self.analysistype].toxinprofile = toxinstring
else:
setattr(sample, self.analysistype, GenObject())
sample[self.analysistype].toxinprofile = 'NA'
else:
setattr(sample, self.analysistype, GenObject())
sample[self.analysistype].toxinprofile = 'NA' | [
"def",
"epcrparse",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Parsing ePCR results'",
")",
"for",
"sample",
"in",
"self",
".",
"metadata",
":",
"if",
"sample",
".",
"general",
".",
"bestassemblyfile",
"!=",
"'NA'",
":",
"if",
"'stx'",
"in",
"sample",
".",
"general",
".",
"datastore",
":",
"# Initialise count - this allows for the population of vtyperresults with unique values",
"uniquecount",
"=",
"0",
"# This populates vtyperresults with the verotoxin subtypes",
"toxinlist",
"=",
"[",
"]",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"sample",
"[",
"self",
".",
"analysistype",
"]",
".",
"resultsfile",
")",
":",
"epcrresults",
"=",
"open",
"(",
"sample",
"[",
"self",
".",
"analysistype",
"]",
".",
"resultsfile",
",",
"'r'",
")",
"for",
"result",
"in",
"epcrresults",
":",
"# Only the lines without a # contain results",
"if",
"\"#\"",
"not",
"in",
"result",
":",
"uniquecount",
"+=",
"1",
"# Split on \\t",
"data",
"=",
"result",
".",
"split",
"(",
"'\\t'",
")",
"# The subtyping primer pair is the first entry on lines with results",
"vttype",
"=",
"data",
"[",
"0",
"]",
".",
"split",
"(",
"'_'",
")",
"[",
"0",
"]",
"# Push the name of the primer pair - stripped of anything after a _ to the dictionary",
"if",
"vttype",
"not",
"in",
"toxinlist",
":",
"toxinlist",
".",
"append",
"(",
"vttype",
")",
"# Create a string of the entries in list1 joined with \";\"",
"toxinstring",
"=",
"\";\"",
".",
"join",
"(",
"sorted",
"(",
"toxinlist",
")",
")",
"# Save the string to the metadata",
"sample",
"[",
"self",
".",
"analysistype",
"]",
".",
"toxinprofile",
"=",
"toxinstring",
"else",
":",
"setattr",
"(",
"sample",
",",
"self",
".",
"analysistype",
",",
"GenObject",
"(",
")",
")",
"sample",
"[",
"self",
".",
"analysistype",
"]",
".",
"toxinprofile",
"=",
"'NA'",
"else",
":",
"setattr",
"(",
"sample",
",",
"self",
".",
"analysistype",
",",
"GenObject",
"(",
")",
")",
"sample",
"[",
"self",
".",
"analysistype",
"]",
".",
"toxinprofile",
"=",
"'NA'"
]
| Parse the ePCR text file outputs | [
"Parse",
"the",
"ePCR",
"text",
"file",
"outputs"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/vtyper.py#L96-L131 | train |
tgbugs/ontquery | ontquery/terms.py | OntCuries.populate | def populate(cls, graph):
""" populate an rdflib graph with these curies """
[graph.bind(k, v) for k, v in cls._dict.items()] | python | def populate(cls, graph):
""" populate an rdflib graph with these curies """
[graph.bind(k, v) for k, v in cls._dict.items()] | [
"def",
"populate",
"(",
"cls",
",",
"graph",
")",
":",
"[",
"graph",
".",
"bind",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"cls",
".",
"_dict",
".",
"items",
"(",
")",
"]"
]
| populate an rdflib graph with these curies | [
"populate",
"an",
"rdflib",
"graph",
"with",
"these",
"curies"
]
| bcf4863cb2bf221afe2b093c5dc7da1377300041 | https://github.com/tgbugs/ontquery/blob/bcf4863cb2bf221afe2b093c5dc7da1377300041/ontquery/terms.py#L51-L53 | train |
mediawiki-utilities/python-mwoauth | mwoauth/flask.py | authorized | def authorized(route):
"""
Wrap a flask route. Ensure that the user has authorized via OAuth or
redirect the user to the authorization endpoint with a delayed redirect
back to the originating endpoint.
"""
@wraps(route)
def authorized_route(*args, **kwargs):
if 'mwoauth_access_token' in flask.session:
return route(*args, **kwargs)
else:
return flask.redirect(
flask.url_for('mwoauth.mwoauth_initiate') +
"?next=" + flask.request.endpoint)
return authorized_route | python | def authorized(route):
"""
Wrap a flask route. Ensure that the user has authorized via OAuth or
redirect the user to the authorization endpoint with a delayed redirect
back to the originating endpoint.
"""
@wraps(route)
def authorized_route(*args, **kwargs):
if 'mwoauth_access_token' in flask.session:
return route(*args, **kwargs)
else:
return flask.redirect(
flask.url_for('mwoauth.mwoauth_initiate') +
"?next=" + flask.request.endpoint)
return authorized_route | [
"def",
"authorized",
"(",
"route",
")",
":",
"@",
"wraps",
"(",
"route",
")",
"def",
"authorized_route",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mwoauth_access_token'",
"in",
"flask",
".",
"session",
":",
"return",
"route",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"flask",
".",
"redirect",
"(",
"flask",
".",
"url_for",
"(",
"'mwoauth.mwoauth_initiate'",
")",
"+",
"\"?next=\"",
"+",
"flask",
".",
"request",
".",
"endpoint",
")",
"return",
"authorized_route"
]
| Wrap a flask route. Ensure that the user has authorized via OAuth or
redirect the user to the authorization endpoint with a delayed redirect
back to the originating endpoint. | [
"Wrap",
"a",
"flask",
"route",
".",
"Ensure",
"that",
"the",
"user",
"has",
"authorized",
"via",
"OAuth",
"or",
"redirect",
"the",
"user",
"to",
"the",
"authorization",
"endpoint",
"with",
"a",
"delayed",
"redirect",
"back",
"to",
"the",
"originating",
"endpoint",
"."
]
| cd6990753ec3d59b7cfd96a76459f71ef4790cd3 | https://github.com/mediawiki-utilities/python-mwoauth/blob/cd6990753ec3d59b7cfd96a76459f71ef4790cd3/mwoauth/flask.py#L237-L252 | train |
sirfoga/pyhal | hal/maths/primes.py | blum_blum_shub | def blum_blum_shub(seed, amount, prime0, prime1):
"""Creates pseudo-number generator
:param seed: seeder
:param amount: amount of number to generate
:param prime0: one prime number
:param prime1: the second prime number
:return: pseudo-number generator
"""
if amount == 0:
return []
assert (prime0 % 4 == 3 and
prime1 % 4 == 3) # primes must be congruent 3 mod 4
mod = prime0 * prime1
rand = [seed]
for _ in range(amount - 1):
last_num = rand[len(rand) - 1]
next_num = (last_num * last_num) % mod
rand.append(next_num)
return rand | python | def blum_blum_shub(seed, amount, prime0, prime1):
"""Creates pseudo-number generator
:param seed: seeder
:param amount: amount of number to generate
:param prime0: one prime number
:param prime1: the second prime number
:return: pseudo-number generator
"""
if amount == 0:
return []
assert (prime0 % 4 == 3 and
prime1 % 4 == 3) # primes must be congruent 3 mod 4
mod = prime0 * prime1
rand = [seed]
for _ in range(amount - 1):
last_num = rand[len(rand) - 1]
next_num = (last_num * last_num) % mod
rand.append(next_num)
return rand | [
"def",
"blum_blum_shub",
"(",
"seed",
",",
"amount",
",",
"prime0",
",",
"prime1",
")",
":",
"if",
"amount",
"==",
"0",
":",
"return",
"[",
"]",
"assert",
"(",
"prime0",
"%",
"4",
"==",
"3",
"and",
"prime1",
"%",
"4",
"==",
"3",
")",
"# primes must be congruent 3 mod 4",
"mod",
"=",
"prime0",
"*",
"prime1",
"rand",
"=",
"[",
"seed",
"]",
"for",
"_",
"in",
"range",
"(",
"amount",
"-",
"1",
")",
":",
"last_num",
"=",
"rand",
"[",
"len",
"(",
"rand",
")",
"-",
"1",
"]",
"next_num",
"=",
"(",
"last_num",
"*",
"last_num",
")",
"%",
"mod",
"rand",
".",
"append",
"(",
"next_num",
")",
"return",
"rand"
]
| Creates pseudo-number generator
:param seed: seeder
:param amount: amount of number to generate
:param prime0: one prime number
:param prime1: the second prime number
:return: pseudo-number generator | [
"Creates",
"pseudo",
"-",
"number",
"generator"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/maths/primes.py#L112-L135 | train |
lowandrew/OLCTools | spadespipeline/basicAssembly.py | Basic.readlength | def readlength(self):
"""Calculates the read length of the fastq files. Short reads will not be able to be assembled properly with the
default parameters used for spades."""
logging.info('Estimating read lengths of FASTQ files')
# Iterate through the samples
for sample in self.samples:
sample.run.Date = 'NA'
sample.run.InvestigatorName = 'NA'
sample.run.TotalClustersinRun = 'NA'
sample.run.NumberofClustersPF = 'NA'
sample.run.PercentOfClusters = 'NA'
sample.run.SampleProject = 'NA'
# Only perform this step if the forward and reverse lengths have not been loaded into the metadata
if not GenObject.isattr(sample.run, 'forwardlength') and not GenObject.isattr(sample.run, 'reverselength'):
# Initialise the .header attribute for each sample
sample.header = GenObject()
sample.commands = GenObject()
# Set /dev/null
devnull = open(os.devnull, 'wb')
# Only process the samples if the file type is a list
if type(sample.general.fastqfiles) is list:
# Set the forward fastq to be the first entry in the list
forwardfastq = sorted(sample.general.fastqfiles)[0]
# If the files are gzipped, then zcat must be used instead of cat
if '.gz' in forwardfastq:
command = 'zcat'
else:
command = 'cat'
# Read in the output of the (z)cat of the fastq file piped through head to read only the first 1000
# lines. Will make a string of the first 1000 lines in the file
forwardreads = subprocess.Popen("{} {} | head -n 1000".format(command, forwardfastq),
shell=True,
stdout=subprocess.PIPE,
stderr=devnull).communicate()[0].rstrip()
# Set the length of the reads as follows: the highest value (max) of the length of the sequence. The
# sequence was extracted from the rest of the lines in the fastq file. Example of first four lines:
"""
@M02466:126:000000000-AKF4P:1:1101:11875:1838 1:N:0:1
TCATAACGCAGTGAAACGCTTTAACAAAAGCGGAGACACGCCACTATTTGTCAATATTTCGTATGATACATTTTTAGAAAATCAAGAAGAGTTGCACGA
+
AA,B89C,@++B,,,,C,:BFF9,C,,,,,6+++++:,C,8C+BE,EFF9FC,6E,EFGF@F<F@9F9E<FFGGGC8,,,,CC<,,,,,,6CE,C<C,,
"""
# The line with the sequence information occurs every four lines (1, 5, 9, etc). This can be
# represented by linenumber % 4 == 1
try:
# Added due to weird 2to3 conversion issues, was coming
forwardreads = forwardreads.decode('utf-8')
except UnicodeDecodeError:
sample.run.forwardlength = 0
# up as a bytes object when we need it as a string.
try:
forwardlength = max([len(sequence) for iterator, sequence in enumerate(forwardreads.split('\n'))
if iterator % 4 == 1])
sample.run.forwardlength = forwardlength
except (ValueError, TypeError):
sample.run.forwardlength = 0
# For paired end analyses, also calculate the length of the reverse reads
if len(sample.general.fastqfiles) == 2:
reversefastq = sorted(sample.general.fastqfiles)[1]
reversereads = subprocess.Popen("{} {} | head -n 1000".format(command, reversefastq),
shell=True,
stdout=subprocess.PIPE,
stderr=devnull).communicate()[0].rstrip()
try:
reversereads = reversereads.decode('utf-8')
except UnicodeDecodeError:
sample.run.reverselength = 0
try:
sample.run.reverselength = max([len(sequence) for iterator, sequence in
enumerate(reversereads.split('\n')) if iterator % 4 == 1])
except (ValueError, TypeError):
sample.run.reverselength = 0
# Populate metadata of single end reads with 'NA'
else:
sample.run.reverselength = 0 | python | def readlength(self):
"""Calculates the read length of the fastq files. Short reads will not be able to be assembled properly with the
default parameters used for spades."""
logging.info('Estimating read lengths of FASTQ files')
# Iterate through the samples
for sample in self.samples:
sample.run.Date = 'NA'
sample.run.InvestigatorName = 'NA'
sample.run.TotalClustersinRun = 'NA'
sample.run.NumberofClustersPF = 'NA'
sample.run.PercentOfClusters = 'NA'
sample.run.SampleProject = 'NA'
# Only perform this step if the forward and reverse lengths have not been loaded into the metadata
if not GenObject.isattr(sample.run, 'forwardlength') and not GenObject.isattr(sample.run, 'reverselength'):
# Initialise the .header attribute for each sample
sample.header = GenObject()
sample.commands = GenObject()
# Set /dev/null
devnull = open(os.devnull, 'wb')
# Only process the samples if the file type is a list
if type(sample.general.fastqfiles) is list:
# Set the forward fastq to be the first entry in the list
forwardfastq = sorted(sample.general.fastqfiles)[0]
# If the files are gzipped, then zcat must be used instead of cat
if '.gz' in forwardfastq:
command = 'zcat'
else:
command = 'cat'
# Read in the output of the (z)cat of the fastq file piped through head to read only the first 1000
# lines. Will make a string of the first 1000 lines in the file
forwardreads = subprocess.Popen("{} {} | head -n 1000".format(command, forwardfastq),
shell=True,
stdout=subprocess.PIPE,
stderr=devnull).communicate()[0].rstrip()
# Set the length of the reads as follows: the highest value (max) of the length of the sequence. The
# sequence was extracted from the rest of the lines in the fastq file. Example of first four lines:
"""
@M02466:126:000000000-AKF4P:1:1101:11875:1838 1:N:0:1
TCATAACGCAGTGAAACGCTTTAACAAAAGCGGAGACACGCCACTATTTGTCAATATTTCGTATGATACATTTTTAGAAAATCAAGAAGAGTTGCACGA
+
AA,B89C,@++B,,,,C,:BFF9,C,,,,,6+++++:,C,8C+BE,EFF9FC,6E,EFGF@F<F@9F9E<FFGGGC8,,,,CC<,,,,,,6CE,C<C,,
"""
# The line with the sequence information occurs every four lines (1, 5, 9, etc). This can be
# represented by linenumber % 4 == 1
try:
# Added due to weird 2to3 conversion issues, was coming
forwardreads = forwardreads.decode('utf-8')
except UnicodeDecodeError:
sample.run.forwardlength = 0
# up as a bytes object when we need it as a string.
try:
forwardlength = max([len(sequence) for iterator, sequence in enumerate(forwardreads.split('\n'))
if iterator % 4 == 1])
sample.run.forwardlength = forwardlength
except (ValueError, TypeError):
sample.run.forwardlength = 0
# For paired end analyses, also calculate the length of the reverse reads
if len(sample.general.fastqfiles) == 2:
reversefastq = sorted(sample.general.fastqfiles)[1]
reversereads = subprocess.Popen("{} {} | head -n 1000".format(command, reversefastq),
shell=True,
stdout=subprocess.PIPE,
stderr=devnull).communicate()[0].rstrip()
try:
reversereads = reversereads.decode('utf-8')
except UnicodeDecodeError:
sample.run.reverselength = 0
try:
sample.run.reverselength = max([len(sequence) for iterator, sequence in
enumerate(reversereads.split('\n')) if iterator % 4 == 1])
except (ValueError, TypeError):
sample.run.reverselength = 0
# Populate metadata of single end reads with 'NA'
else:
sample.run.reverselength = 0 | [
"def",
"readlength",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Estimating read lengths of FASTQ files'",
")",
"# Iterate through the samples",
"for",
"sample",
"in",
"self",
".",
"samples",
":",
"sample",
".",
"run",
".",
"Date",
"=",
"'NA'",
"sample",
".",
"run",
".",
"InvestigatorName",
"=",
"'NA'",
"sample",
".",
"run",
".",
"TotalClustersinRun",
"=",
"'NA'",
"sample",
".",
"run",
".",
"NumberofClustersPF",
"=",
"'NA'",
"sample",
".",
"run",
".",
"PercentOfClusters",
"=",
"'NA'",
"sample",
".",
"run",
".",
"SampleProject",
"=",
"'NA'",
"# Only perform this step if the forward and reverse lengths have not been loaded into the metadata",
"if",
"not",
"GenObject",
".",
"isattr",
"(",
"sample",
".",
"run",
",",
"'forwardlength'",
")",
"and",
"not",
"GenObject",
".",
"isattr",
"(",
"sample",
".",
"run",
",",
"'reverselength'",
")",
":",
"# Initialise the .header attribute for each sample",
"sample",
".",
"header",
"=",
"GenObject",
"(",
")",
"sample",
".",
"commands",
"=",
"GenObject",
"(",
")",
"# Set /dev/null",
"devnull",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"'wb'",
")",
"# Only process the samples if the file type is a list",
"if",
"type",
"(",
"sample",
".",
"general",
".",
"fastqfiles",
")",
"is",
"list",
":",
"# Set the forward fastq to be the first entry in the list",
"forwardfastq",
"=",
"sorted",
"(",
"sample",
".",
"general",
".",
"fastqfiles",
")",
"[",
"0",
"]",
"# If the files are gzipped, then zcat must be used instead of cat",
"if",
"'.gz'",
"in",
"forwardfastq",
":",
"command",
"=",
"'zcat'",
"else",
":",
"command",
"=",
"'cat'",
"# Read in the output of the (z)cat of the fastq file piped through head to read only the first 1000",
"# lines. Will make a string of the first 1000 lines in the file",
"forwardreads",
"=",
"subprocess",
".",
"Popen",
"(",
"\"{} {} | head -n 1000\"",
".",
"format",
"(",
"command",
",",
"forwardfastq",
")",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"devnull",
")",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
".",
"rstrip",
"(",
")",
"# Set the length of the reads as follows: the highest value (max) of the length of the sequence. The",
"# sequence was extracted from the rest of the lines in the fastq file. Example of first four lines:",
"\"\"\"\n @M02466:126:000000000-AKF4P:1:1101:11875:1838 1:N:0:1\n TCATAACGCAGTGAAACGCTTTAACAAAAGCGGAGACACGCCACTATTTGTCAATATTTCGTATGATACATTTTTAGAAAATCAAGAAGAGTTGCACGA\n +\n AA,B89C,@++B,,,,C,:BFF9,C,,,,,6+++++:,C,8C+BE,EFF9FC,6E,EFGF@F<F@9F9E<FFGGGC8,,,,CC<,,,,,,6CE,C<C,,\n \"\"\"",
"# The line with the sequence information occurs every four lines (1, 5, 9, etc). This can be",
"# represented by linenumber % 4 == 1",
"try",
":",
"# Added due to weird 2to3 conversion issues, was coming",
"forwardreads",
"=",
"forwardreads",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"UnicodeDecodeError",
":",
"sample",
".",
"run",
".",
"forwardlength",
"=",
"0",
"# up as a bytes object when we need it as a string.",
"try",
":",
"forwardlength",
"=",
"max",
"(",
"[",
"len",
"(",
"sequence",
")",
"for",
"iterator",
",",
"sequence",
"in",
"enumerate",
"(",
"forwardreads",
".",
"split",
"(",
"'\\n'",
")",
")",
"if",
"iterator",
"%",
"4",
"==",
"1",
"]",
")",
"sample",
".",
"run",
".",
"forwardlength",
"=",
"forwardlength",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"sample",
".",
"run",
".",
"forwardlength",
"=",
"0",
"# For paired end analyses, also calculate the length of the reverse reads",
"if",
"len",
"(",
"sample",
".",
"general",
".",
"fastqfiles",
")",
"==",
"2",
":",
"reversefastq",
"=",
"sorted",
"(",
"sample",
".",
"general",
".",
"fastqfiles",
")",
"[",
"1",
"]",
"reversereads",
"=",
"subprocess",
".",
"Popen",
"(",
"\"{} {} | head -n 1000\"",
".",
"format",
"(",
"command",
",",
"reversefastq",
")",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"devnull",
")",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
".",
"rstrip",
"(",
")",
"try",
":",
"reversereads",
"=",
"reversereads",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"UnicodeDecodeError",
":",
"sample",
".",
"run",
".",
"reverselength",
"=",
"0",
"try",
":",
"sample",
".",
"run",
".",
"reverselength",
"=",
"max",
"(",
"[",
"len",
"(",
"sequence",
")",
"for",
"iterator",
",",
"sequence",
"in",
"enumerate",
"(",
"reversereads",
".",
"split",
"(",
"'\\n'",
")",
")",
"if",
"iterator",
"%",
"4",
"==",
"1",
"]",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"sample",
".",
"run",
".",
"reverselength",
"=",
"0",
"# Populate metadata of single end reads with 'NA'",
"else",
":",
"sample",
".",
"run",
".",
"reverselength",
"=",
"0"
]
| Calculates the read length of the fastq files. Short reads will not be able to be assembled properly with the
default parameters used for spades. | [
"Calculates",
"the",
"read",
"length",
"of",
"the",
"fastq",
"files",
".",
"Short",
"reads",
"will",
"not",
"be",
"able",
"to",
"be",
"assembled",
"properly",
"with",
"the",
"default",
"parameters",
"used",
"for",
"spades",
"."
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/basicAssembly.py#L54-L128 | train |
dpa-newslab/livebridge | livebridge/storages/sql.py | SQLStorage.setup | async def setup(self):
"""Setting up SQL table, if it not exists."""
try:
engine = await self.db
created = False
if not await engine.has_table(self.table_name):
# create table
logger.info("Creating SQL table [{}]".format(self.table_name))
items = self._get_table()
await engine.execute(CreateTable(items))
# create indeces
conn = await engine.connect()
await conn.execute(
"CREATE INDEX `lb_last_updated` ON `{}` (`source_id` DESC,`updated` DESC);".format(self.table_name))
await conn.execute(
"CREATE INDEX `lb_post` ON `{}` (`target_id` DESC,`post_id` DESC);".format(self.table_name))
await conn.close()
created = True
# create control table if not already created.
if self.control_table_name and not await engine.has_table(self.control_table_name):
# create table
logger.info("Creating SQL control table [{}]".format(self.control_table_name))
items = self._get_control_table()
await engine.execute(CreateTable(items))
created = True
return created
except Exception as exc:
logger.error("[DB] Error when setting up SQL table: {}".format(exc))
return False | python | async def setup(self):
"""Setting up SQL table, if it not exists."""
try:
engine = await self.db
created = False
if not await engine.has_table(self.table_name):
# create table
logger.info("Creating SQL table [{}]".format(self.table_name))
items = self._get_table()
await engine.execute(CreateTable(items))
# create indeces
conn = await engine.connect()
await conn.execute(
"CREATE INDEX `lb_last_updated` ON `{}` (`source_id` DESC,`updated` DESC);".format(self.table_name))
await conn.execute(
"CREATE INDEX `lb_post` ON `{}` (`target_id` DESC,`post_id` DESC);".format(self.table_name))
await conn.close()
created = True
# create control table if not already created.
if self.control_table_name and not await engine.has_table(self.control_table_name):
# create table
logger.info("Creating SQL control table [{}]".format(self.control_table_name))
items = self._get_control_table()
await engine.execute(CreateTable(items))
created = True
return created
except Exception as exc:
logger.error("[DB] Error when setting up SQL table: {}".format(exc))
return False | [
"async",
"def",
"setup",
"(",
"self",
")",
":",
"try",
":",
"engine",
"=",
"await",
"self",
".",
"db",
"created",
"=",
"False",
"if",
"not",
"await",
"engine",
".",
"has_table",
"(",
"self",
".",
"table_name",
")",
":",
"# create table",
"logger",
".",
"info",
"(",
"\"Creating SQL table [{}]\"",
".",
"format",
"(",
"self",
".",
"table_name",
")",
")",
"items",
"=",
"self",
".",
"_get_table",
"(",
")",
"await",
"engine",
".",
"execute",
"(",
"CreateTable",
"(",
"items",
")",
")",
"# create indeces",
"conn",
"=",
"await",
"engine",
".",
"connect",
"(",
")",
"await",
"conn",
".",
"execute",
"(",
"\"CREATE INDEX `lb_last_updated` ON `{}` (`source_id` DESC,`updated` DESC);\"",
".",
"format",
"(",
"self",
".",
"table_name",
")",
")",
"await",
"conn",
".",
"execute",
"(",
"\"CREATE INDEX `lb_post` ON `{}` (`target_id` DESC,`post_id` DESC);\"",
".",
"format",
"(",
"self",
".",
"table_name",
")",
")",
"await",
"conn",
".",
"close",
"(",
")",
"created",
"=",
"True",
"# create control table if not already created.",
"if",
"self",
".",
"control_table_name",
"and",
"not",
"await",
"engine",
".",
"has_table",
"(",
"self",
".",
"control_table_name",
")",
":",
"# create table",
"logger",
".",
"info",
"(",
"\"Creating SQL control table [{}]\"",
".",
"format",
"(",
"self",
".",
"control_table_name",
")",
")",
"items",
"=",
"self",
".",
"_get_control_table",
"(",
")",
"await",
"engine",
".",
"execute",
"(",
"CreateTable",
"(",
"items",
")",
")",
"created",
"=",
"True",
"return",
"created",
"except",
"Exception",
"as",
"exc",
":",
"logger",
".",
"error",
"(",
"\"[DB] Error when setting up SQL table: {}\"",
".",
"format",
"(",
"exc",
")",
")",
"return",
"False"
]
| Setting up SQL table, if it not exists. | [
"Setting",
"up",
"SQL",
"table",
"if",
"it",
"not",
"exists",
"."
]
| d930e887faa2f882d15b574f0f1fe4a580d7c5fa | https://github.com/dpa-newslab/livebridge/blob/d930e887faa2f882d15b574f0f1fe4a580d7c5fa/livebridge/storages/sql.py#L75-L103 | train |
aquatix/ns-api | ns_api.py | is_dst | def is_dst(zonename):
"""
Find out whether it's Daylight Saving Time in this timezone
"""
tz = pytz.timezone(zonename)
now = pytz.utc.localize(datetime.utcnow())
return now.astimezone(tz).dst() != timedelta(0) | python | def is_dst(zonename):
"""
Find out whether it's Daylight Saving Time in this timezone
"""
tz = pytz.timezone(zonename)
now = pytz.utc.localize(datetime.utcnow())
return now.astimezone(tz).dst() != timedelta(0) | [
"def",
"is_dst",
"(",
"zonename",
")",
":",
"tz",
"=",
"pytz",
".",
"timezone",
"(",
"zonename",
")",
"now",
"=",
"pytz",
".",
"utc",
".",
"localize",
"(",
"datetime",
".",
"utcnow",
"(",
")",
")",
"return",
"now",
".",
"astimezone",
"(",
"tz",
")",
".",
"dst",
"(",
")",
"!=",
"timedelta",
"(",
"0",
")"
]
| Find out whether it's Daylight Saving Time in this timezone | [
"Find",
"out",
"whether",
"it",
"s",
"Daylight",
"Saving",
"Time",
"in",
"this",
"timezone"
]
| 9b3379f8df6217132f457c4363457c16321c2448 | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L43-L49 | train |
aquatix/ns-api | ns_api.py | load_datetime | def load_datetime(value, dt_format):
"""
Create timezone-aware datetime object
"""
if dt_format.endswith('%z'):
dt_format = dt_format[:-2]
offset = value[-5:]
value = value[:-5]
if offset != offset.replace(':', ''):
# strip : from HHMM if needed (isoformat() adds it between HH and MM)
offset = '+' + offset.replace(':', '')
value = value[:-1]
return OffsetTime(offset).localize(datetime.strptime(value, dt_format))
return datetime.strptime(value, dt_format) | python | def load_datetime(value, dt_format):
"""
Create timezone-aware datetime object
"""
if dt_format.endswith('%z'):
dt_format = dt_format[:-2]
offset = value[-5:]
value = value[:-5]
if offset != offset.replace(':', ''):
# strip : from HHMM if needed (isoformat() adds it between HH and MM)
offset = '+' + offset.replace(':', '')
value = value[:-1]
return OffsetTime(offset).localize(datetime.strptime(value, dt_format))
return datetime.strptime(value, dt_format) | [
"def",
"load_datetime",
"(",
"value",
",",
"dt_format",
")",
":",
"if",
"dt_format",
".",
"endswith",
"(",
"'%z'",
")",
":",
"dt_format",
"=",
"dt_format",
"[",
":",
"-",
"2",
"]",
"offset",
"=",
"value",
"[",
"-",
"5",
":",
"]",
"value",
"=",
"value",
"[",
":",
"-",
"5",
"]",
"if",
"offset",
"!=",
"offset",
".",
"replace",
"(",
"':'",
",",
"''",
")",
":",
"# strip : from HHMM if needed (isoformat() adds it between HH and MM)",
"offset",
"=",
"'+'",
"+",
"offset",
".",
"replace",
"(",
"':'",
",",
"''",
")",
"value",
"=",
"value",
"[",
":",
"-",
"1",
"]",
"return",
"OffsetTime",
"(",
"offset",
")",
".",
"localize",
"(",
"datetime",
".",
"strptime",
"(",
"value",
",",
"dt_format",
")",
")",
"return",
"datetime",
".",
"strptime",
"(",
"value",
",",
"dt_format",
")"
]
| Create timezone-aware datetime object | [
"Create",
"timezone",
"-",
"aware",
"datetime",
"object"
]
| 9b3379f8df6217132f457c4363457c16321c2448 | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L62-L76 | train |
aquatix/ns-api | ns_api.py | list_to_json | def list_to_json(source_list):
"""
Serialise all the items in source_list to json
"""
result = []
for item in source_list:
result.append(item.to_json())
return result | python | def list_to_json(source_list):
"""
Serialise all the items in source_list to json
"""
result = []
for item in source_list:
result.append(item.to_json())
return result | [
"def",
"list_to_json",
"(",
"source_list",
")",
":",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"source_list",
":",
"result",
".",
"append",
"(",
"item",
".",
"to_json",
"(",
")",
")",
"return",
"result"
]
| Serialise all the items in source_list to json | [
"Serialise",
"all",
"the",
"items",
"in",
"source_list",
"to",
"json"
]
| 9b3379f8df6217132f457c4363457c16321c2448 | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L81-L88 | train |
aquatix/ns-api | ns_api.py | list_from_json | def list_from_json(source_list_json):
"""
Deserialise all the items in source_list from json
"""
result = []
if source_list_json == [] or source_list_json == None:
return result
for list_item in source_list_json:
item = json.loads(list_item)
try:
if item['class_name'] == 'Departure':
temp = Departure()
elif item['class_name'] == 'Disruption':
temp = Disruption()
elif item['class_name'] == 'Station':
temp = Station()
elif item['class_name'] == 'Trip':
temp = Trip()
elif item['class_name'] == 'TripRemark':
temp = TripRemark()
elif item['class_name'] == 'TripStop':
temp = TripStop()
elif item['class_name'] == 'TripSubpart':
temp = TripSubpart()
else:
print('Unrecognised Class ' + item['class_name'] + ', skipping')
continue
temp.from_json(list_item)
result.append(temp)
except KeyError:
print('Unrecognised item with no class_name, skipping')
continue
return result | python | def list_from_json(source_list_json):
"""
Deserialise all the items in source_list from json
"""
result = []
if source_list_json == [] or source_list_json == None:
return result
for list_item in source_list_json:
item = json.loads(list_item)
try:
if item['class_name'] == 'Departure':
temp = Departure()
elif item['class_name'] == 'Disruption':
temp = Disruption()
elif item['class_name'] == 'Station':
temp = Station()
elif item['class_name'] == 'Trip':
temp = Trip()
elif item['class_name'] == 'TripRemark':
temp = TripRemark()
elif item['class_name'] == 'TripStop':
temp = TripStop()
elif item['class_name'] == 'TripSubpart':
temp = TripSubpart()
else:
print('Unrecognised Class ' + item['class_name'] + ', skipping')
continue
temp.from_json(list_item)
result.append(temp)
except KeyError:
print('Unrecognised item with no class_name, skipping')
continue
return result | [
"def",
"list_from_json",
"(",
"source_list_json",
")",
":",
"result",
"=",
"[",
"]",
"if",
"source_list_json",
"==",
"[",
"]",
"or",
"source_list_json",
"==",
"None",
":",
"return",
"result",
"for",
"list_item",
"in",
"source_list_json",
":",
"item",
"=",
"json",
".",
"loads",
"(",
"list_item",
")",
"try",
":",
"if",
"item",
"[",
"'class_name'",
"]",
"==",
"'Departure'",
":",
"temp",
"=",
"Departure",
"(",
")",
"elif",
"item",
"[",
"'class_name'",
"]",
"==",
"'Disruption'",
":",
"temp",
"=",
"Disruption",
"(",
")",
"elif",
"item",
"[",
"'class_name'",
"]",
"==",
"'Station'",
":",
"temp",
"=",
"Station",
"(",
")",
"elif",
"item",
"[",
"'class_name'",
"]",
"==",
"'Trip'",
":",
"temp",
"=",
"Trip",
"(",
")",
"elif",
"item",
"[",
"'class_name'",
"]",
"==",
"'TripRemark'",
":",
"temp",
"=",
"TripRemark",
"(",
")",
"elif",
"item",
"[",
"'class_name'",
"]",
"==",
"'TripStop'",
":",
"temp",
"=",
"TripStop",
"(",
")",
"elif",
"item",
"[",
"'class_name'",
"]",
"==",
"'TripSubpart'",
":",
"temp",
"=",
"TripSubpart",
"(",
")",
"else",
":",
"print",
"(",
"'Unrecognised Class '",
"+",
"item",
"[",
"'class_name'",
"]",
"+",
"', skipping'",
")",
"continue",
"temp",
".",
"from_json",
"(",
"list_item",
")",
"result",
".",
"append",
"(",
"temp",
")",
"except",
"KeyError",
":",
"print",
"(",
"'Unrecognised item with no class_name, skipping'",
")",
"continue",
"return",
"result"
]
| Deserialise all the items in source_list from json | [
"Deserialise",
"all",
"the",
"items",
"in",
"source_list",
"from",
"json"
]
| 9b3379f8df6217132f457c4363457c16321c2448 | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L91-L123 | train |
aquatix/ns-api | ns_api.py | list_diff | def list_diff(list_a, list_b):
"""
Return the items from list_b that differ from list_a
"""
result = []
for item in list_b:
if not item in list_a:
result.append(item)
return result | python | def list_diff(list_a, list_b):
"""
Return the items from list_b that differ from list_a
"""
result = []
for item in list_b:
if not item in list_a:
result.append(item)
return result | [
"def",
"list_diff",
"(",
"list_a",
",",
"list_b",
")",
":",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"list_b",
":",
"if",
"not",
"item",
"in",
"list_a",
":",
"result",
".",
"append",
"(",
"item",
")",
"return",
"result"
]
| Return the items from list_b that differ from list_a | [
"Return",
"the",
"items",
"from",
"list_b",
"that",
"differ",
"from",
"list_a"
]
| 9b3379f8df6217132f457c4363457c16321c2448 | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L126-L134 | train |
aquatix/ns-api | ns_api.py | list_same | def list_same(list_a, list_b):
"""
Return the items from list_b that are also on list_a
"""
result = []
for item in list_b:
if item in list_a:
result.append(item)
return result | python | def list_same(list_a, list_b):
"""
Return the items from list_b that are also on list_a
"""
result = []
for item in list_b:
if item in list_a:
result.append(item)
return result | [
"def",
"list_same",
"(",
"list_a",
",",
"list_b",
")",
":",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"list_b",
":",
"if",
"item",
"in",
"list_a",
":",
"result",
".",
"append",
"(",
"item",
")",
"return",
"result"
]
| Return the items from list_b that are also on list_a | [
"Return",
"the",
"items",
"from",
"list_b",
"that",
"are",
"also",
"on",
"list_a"
]
| 9b3379f8df6217132f457c4363457c16321c2448 | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L137-L145 | train |
aquatix/ns-api | ns_api.py | list_merge | def list_merge(list_a, list_b):
"""
Merge two lists without duplicating items
Args:
list_a: list
list_b: list
Returns:
New list with deduplicated items from list_a and list_b
"""
#return list(collections.OrderedDict.fromkeys(list_a + list_b))
#result = list(list_b)
result = []
for item in list_a:
if not item in result:
result.append(item)
for item in list_b:
if not item in result:
result.append(item)
return result | python | def list_merge(list_a, list_b):
"""
Merge two lists without duplicating items
Args:
list_a: list
list_b: list
Returns:
New list with deduplicated items from list_a and list_b
"""
#return list(collections.OrderedDict.fromkeys(list_a + list_b))
#result = list(list_b)
result = []
for item in list_a:
if not item in result:
result.append(item)
for item in list_b:
if not item in result:
result.append(item)
return result | [
"def",
"list_merge",
"(",
"list_a",
",",
"list_b",
")",
":",
"#return list(collections.OrderedDict.fromkeys(list_a + list_b))",
"#result = list(list_b)",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"list_a",
":",
"if",
"not",
"item",
"in",
"result",
":",
"result",
".",
"append",
"(",
"item",
")",
"for",
"item",
"in",
"list_b",
":",
"if",
"not",
"item",
"in",
"result",
":",
"result",
".",
"append",
"(",
"item",
")",
"return",
"result"
]
| Merge two lists without duplicating items
Args:
list_a: list
list_b: list
Returns:
New list with deduplicated items from list_a and list_b | [
"Merge",
"two",
"lists",
"without",
"duplicating",
"items"
]
| 9b3379f8df6217132f457c4363457c16321c2448 | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L148-L167 | train |
aquatix/ns-api | ns_api.py | Trip.delay | def delay(self):
"""
Return the delay of the train for this instance
"""
delay = {'departure_time': None, 'departure_delay': None, 'requested_differs': None,
'remarks': self.trip_remarks, 'parts': []}
if self.departure_time_actual > self.departure_time_planned:
delay['departure_delay'] = self.departure_time_actual - self.departure_time_planned
delay['departure_time'] = self.departure_time_actual
if self.requested_time != self.departure_time_actual:
delay['requested_differs'] = self.departure_time_actual
for part in self.trip_parts:
if part.has_delay:
delay['parts'].append(part)
return delay | python | def delay(self):
"""
Return the delay of the train for this instance
"""
delay = {'departure_time': None, 'departure_delay': None, 'requested_differs': None,
'remarks': self.trip_remarks, 'parts': []}
if self.departure_time_actual > self.departure_time_planned:
delay['departure_delay'] = self.departure_time_actual - self.departure_time_planned
delay['departure_time'] = self.departure_time_actual
if self.requested_time != self.departure_time_actual:
delay['requested_differs'] = self.departure_time_actual
for part in self.trip_parts:
if part.has_delay:
delay['parts'].append(part)
return delay | [
"def",
"delay",
"(",
"self",
")",
":",
"delay",
"=",
"{",
"'departure_time'",
":",
"None",
",",
"'departure_delay'",
":",
"None",
",",
"'requested_differs'",
":",
"None",
",",
"'remarks'",
":",
"self",
".",
"trip_remarks",
",",
"'parts'",
":",
"[",
"]",
"}",
"if",
"self",
".",
"departure_time_actual",
">",
"self",
".",
"departure_time_planned",
":",
"delay",
"[",
"'departure_delay'",
"]",
"=",
"self",
".",
"departure_time_actual",
"-",
"self",
".",
"departure_time_planned",
"delay",
"[",
"'departure_time'",
"]",
"=",
"self",
".",
"departure_time_actual",
"if",
"self",
".",
"requested_time",
"!=",
"self",
".",
"departure_time_actual",
":",
"delay",
"[",
"'requested_differs'",
"]",
"=",
"self",
".",
"departure_time_actual",
"for",
"part",
"in",
"self",
".",
"trip_parts",
":",
"if",
"part",
".",
"has_delay",
":",
"delay",
"[",
"'parts'",
"]",
".",
"append",
"(",
"part",
")",
"return",
"delay"
]
| Return the delay of the train for this instance | [
"Return",
"the",
"delay",
"of",
"the",
"train",
"for",
"this",
"instance"
]
| 9b3379f8df6217132f457c4363457c16321c2448 | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L580-L594 | train |
aquatix/ns-api | ns_api.py | Trip.get_actual | def get_actual(cls, trip_list, time):
"""
Look for the train actually leaving at time
"""
for trip in trip_list:
if simple_time(trip.departure_time_planned) == time:
return trip
return None | python | def get_actual(cls, trip_list, time):
"""
Look for the train actually leaving at time
"""
for trip in trip_list:
if simple_time(trip.departure_time_planned) == time:
return trip
return None | [
"def",
"get_actual",
"(",
"cls",
",",
"trip_list",
",",
"time",
")",
":",
"for",
"trip",
"in",
"trip_list",
":",
"if",
"simple_time",
"(",
"trip",
".",
"departure_time_planned",
")",
"==",
"time",
":",
"return",
"trip",
"return",
"None"
]
| Look for the train actually leaving at time | [
"Look",
"for",
"the",
"train",
"actually",
"leaving",
"at",
"time"
]
| 9b3379f8df6217132f457c4363457c16321c2448 | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L674-L681 | train |
aquatix/ns-api | ns_api.py | NSAPI.parse_disruptions | def parse_disruptions(self, xml):
"""
Parse the NS API xml result into Disruption objects
@param xml: raw XML result from the NS API
"""
obj = xmltodict.parse(xml)
disruptions = {}
disruptions['unplanned'] = []
disruptions['planned'] = []
if obj['Storingen']['Ongepland']:
raw_disruptions = obj['Storingen']['Ongepland']['Storing']
if isinstance(raw_disruptions, collections.OrderedDict):
raw_disruptions = [raw_disruptions]
for disruption in raw_disruptions:
newdis = Disruption(disruption)
#print(newdis.__dict__)
disruptions['unplanned'].append(newdis)
if obj['Storingen']['Gepland']:
raw_disruptions = obj['Storingen']['Gepland']['Storing']
if isinstance(raw_disruptions, collections.OrderedDict):
raw_disruptions = [raw_disruptions]
for disruption in raw_disruptions:
newdis = Disruption(disruption)
#print(newdis.__dict__)
disruptions['planned'].append(newdis)
return disruptions | python | def parse_disruptions(self, xml):
"""
Parse the NS API xml result into Disruption objects
@param xml: raw XML result from the NS API
"""
obj = xmltodict.parse(xml)
disruptions = {}
disruptions['unplanned'] = []
disruptions['planned'] = []
if obj['Storingen']['Ongepland']:
raw_disruptions = obj['Storingen']['Ongepland']['Storing']
if isinstance(raw_disruptions, collections.OrderedDict):
raw_disruptions = [raw_disruptions]
for disruption in raw_disruptions:
newdis = Disruption(disruption)
#print(newdis.__dict__)
disruptions['unplanned'].append(newdis)
if obj['Storingen']['Gepland']:
raw_disruptions = obj['Storingen']['Gepland']['Storing']
if isinstance(raw_disruptions, collections.OrderedDict):
raw_disruptions = [raw_disruptions]
for disruption in raw_disruptions:
newdis = Disruption(disruption)
#print(newdis.__dict__)
disruptions['planned'].append(newdis)
return disruptions | [
"def",
"parse_disruptions",
"(",
"self",
",",
"xml",
")",
":",
"obj",
"=",
"xmltodict",
".",
"parse",
"(",
"xml",
")",
"disruptions",
"=",
"{",
"}",
"disruptions",
"[",
"'unplanned'",
"]",
"=",
"[",
"]",
"disruptions",
"[",
"'planned'",
"]",
"=",
"[",
"]",
"if",
"obj",
"[",
"'Storingen'",
"]",
"[",
"'Ongepland'",
"]",
":",
"raw_disruptions",
"=",
"obj",
"[",
"'Storingen'",
"]",
"[",
"'Ongepland'",
"]",
"[",
"'Storing'",
"]",
"if",
"isinstance",
"(",
"raw_disruptions",
",",
"collections",
".",
"OrderedDict",
")",
":",
"raw_disruptions",
"=",
"[",
"raw_disruptions",
"]",
"for",
"disruption",
"in",
"raw_disruptions",
":",
"newdis",
"=",
"Disruption",
"(",
"disruption",
")",
"#print(newdis.__dict__)",
"disruptions",
"[",
"'unplanned'",
"]",
".",
"append",
"(",
"newdis",
")",
"if",
"obj",
"[",
"'Storingen'",
"]",
"[",
"'Gepland'",
"]",
":",
"raw_disruptions",
"=",
"obj",
"[",
"'Storingen'",
"]",
"[",
"'Gepland'",
"]",
"[",
"'Storing'",
"]",
"if",
"isinstance",
"(",
"raw_disruptions",
",",
"collections",
".",
"OrderedDict",
")",
":",
"raw_disruptions",
"=",
"[",
"raw_disruptions",
"]",
"for",
"disruption",
"in",
"raw_disruptions",
":",
"newdis",
"=",
"Disruption",
"(",
"disruption",
")",
"#print(newdis.__dict__)",
"disruptions",
"[",
"'planned'",
"]",
".",
"append",
"(",
"newdis",
")",
"return",
"disruptions"
]
| Parse the NS API xml result into Disruption objects
@param xml: raw XML result from the NS API | [
"Parse",
"the",
"NS",
"API",
"xml",
"result",
"into",
"Disruption",
"objects"
]
| 9b3379f8df6217132f457c4363457c16321c2448 | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L729-L756 | train |
aquatix/ns-api | ns_api.py | NSAPI.parse_departures | def parse_departures(self, xml):
"""
Parse the NS API xml result into Departure objects
@param xml: raw XML result from the NS API
"""
obj = xmltodict.parse(xml)
departures = []
for departure in obj['ActueleVertrekTijden']['VertrekkendeTrein']:
newdep = Departure(departure)
departures.append(newdep)
#print('-- dep --')
#print(newdep.__dict__)
#print(newdep.to_json())
print(newdep.delay)
return departures | python | def parse_departures(self, xml):
"""
Parse the NS API xml result into Departure objects
@param xml: raw XML result from the NS API
"""
obj = xmltodict.parse(xml)
departures = []
for departure in obj['ActueleVertrekTijden']['VertrekkendeTrein']:
newdep = Departure(departure)
departures.append(newdep)
#print('-- dep --')
#print(newdep.__dict__)
#print(newdep.to_json())
print(newdep.delay)
return departures | [
"def",
"parse_departures",
"(",
"self",
",",
"xml",
")",
":",
"obj",
"=",
"xmltodict",
".",
"parse",
"(",
"xml",
")",
"departures",
"=",
"[",
"]",
"for",
"departure",
"in",
"obj",
"[",
"'ActueleVertrekTijden'",
"]",
"[",
"'VertrekkendeTrein'",
"]",
":",
"newdep",
"=",
"Departure",
"(",
"departure",
")",
"departures",
".",
"append",
"(",
"newdep",
")",
"#print('-- dep --')",
"#print(newdep.__dict__)",
"#print(newdep.to_json())",
"print",
"(",
"newdep",
".",
"delay",
")",
"return",
"departures"
]
| Parse the NS API xml result into Departure objects
@param xml: raw XML result from the NS API | [
"Parse",
"the",
"NS",
"API",
"xml",
"result",
"into",
"Departure",
"objects"
]
| 9b3379f8df6217132f457c4363457c16321c2448 | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L776-L792 | train |
aquatix/ns-api | ns_api.py | NSAPI.parse_trips | def parse_trips(self, xml, requested_time):
"""
Parse the NS API xml result into Trip objects
"""
obj = xmltodict.parse(xml)
trips = []
if 'error' in obj:
print('Error in trips: ' + obj['error']['message'])
return None
try:
for trip in obj['ReisMogelijkheden']['ReisMogelijkheid']:
newtrip = Trip(trip, requested_time)
trips.append(newtrip)
except TypeError:
# If no options are found, obj['ReisMogelijkheden'] is None
return None
return trips | python | def parse_trips(self, xml, requested_time):
"""
Parse the NS API xml result into Trip objects
"""
obj = xmltodict.parse(xml)
trips = []
if 'error' in obj:
print('Error in trips: ' + obj['error']['message'])
return None
try:
for trip in obj['ReisMogelijkheden']['ReisMogelijkheid']:
newtrip = Trip(trip, requested_time)
trips.append(newtrip)
except TypeError:
# If no options are found, obj['ReisMogelijkheden'] is None
return None
return trips | [
"def",
"parse_trips",
"(",
"self",
",",
"xml",
",",
"requested_time",
")",
":",
"obj",
"=",
"xmltodict",
".",
"parse",
"(",
"xml",
")",
"trips",
"=",
"[",
"]",
"if",
"'error'",
"in",
"obj",
":",
"print",
"(",
"'Error in trips: '",
"+",
"obj",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
")",
"return",
"None",
"try",
":",
"for",
"trip",
"in",
"obj",
"[",
"'ReisMogelijkheden'",
"]",
"[",
"'ReisMogelijkheid'",
"]",
":",
"newtrip",
"=",
"Trip",
"(",
"trip",
",",
"requested_time",
")",
"trips",
".",
"append",
"(",
"newtrip",
")",
"except",
"TypeError",
":",
"# If no options are found, obj['ReisMogelijkheden'] is None",
"return",
"None",
"return",
"trips"
]
| Parse the NS API xml result into Trip objects | [
"Parse",
"the",
"NS",
"API",
"xml",
"result",
"into",
"Trip",
"objects"
]
| 9b3379f8df6217132f457c4363457c16321c2448 | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L807-L826 | train |
aquatix/ns-api | ns_api.py | NSAPI.get_stations | def get_stations(self):
"""
Fetch the list of stations
"""
url = 'http://webservices.ns.nl/ns-api-stations-v2'
raw_stations = self._request('GET', url)
return self.parse_stations(raw_stations) | python | def get_stations(self):
"""
Fetch the list of stations
"""
url = 'http://webservices.ns.nl/ns-api-stations-v2'
raw_stations = self._request('GET', url)
return self.parse_stations(raw_stations) | [
"def",
"get_stations",
"(",
"self",
")",
":",
"url",
"=",
"'http://webservices.ns.nl/ns-api-stations-v2'",
"raw_stations",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",",
"url",
")",
"return",
"self",
".",
"parse_stations",
"(",
"raw_stations",
")"
]
| Fetch the list of stations | [
"Fetch",
"the",
"list",
"of",
"stations"
]
| 9b3379f8df6217132f457c4363457c16321c2448 | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L877-L883 | train |
steven-lang/bottr | bottr/bot.py | AbstractBot.stop | def stop(self):
"""
Stops this bot.
Returns as soon as all running threads have finished processing.
"""
self.log.debug('Stopping bot {}'.format(self._name))
self._stop = True
for t in self._threads:
t.join()
self.log.debug('Stopping bot {} finished. All threads joined.'.format(self._name)) | python | def stop(self):
"""
Stops this bot.
Returns as soon as all running threads have finished processing.
"""
self.log.debug('Stopping bot {}'.format(self._name))
self._stop = True
for t in self._threads:
t.join()
self.log.debug('Stopping bot {} finished. All threads joined.'.format(self._name)) | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Stopping bot {}'",
".",
"format",
"(",
"self",
".",
"_name",
")",
")",
"self",
".",
"_stop",
"=",
"True",
"for",
"t",
"in",
"self",
".",
"_threads",
":",
"t",
".",
"join",
"(",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Stopping bot {} finished. All threads joined.'",
".",
"format",
"(",
"self",
".",
"_name",
")",
")"
]
| Stops this bot.
Returns as soon as all running threads have finished processing. | [
"Stops",
"this",
"bot",
"."
]
| c1b92becc31adfbd5a7b77179b852a51da70b193 | https://github.com/steven-lang/bottr/blob/c1b92becc31adfbd5a7b77179b852a51da70b193/bottr/bot.py#L50-L61 | train |
steven-lang/bottr | bottr/bot.py | AbstractCommentBot._listen_comments | def _listen_comments(self):
"""Start listening to comments, using a separate thread."""
# Collect comments in a queue
comments_queue = Queue(maxsize=self._n_jobs * 4)
threads = [] # type: List[BotQueueWorker]
try:
# Create n_jobs CommentsThreads
for i in range(self._n_jobs):
t = BotQueueWorker(name='CommentThread-t-{}'.format(i),
jobs=comments_queue,
target=self._process_comment)
t.start()
threads.append(t)
# Iterate over all comments in the comment stream
for comment in self._reddit.subreddit('+'.join(self._subs)).stream.comments():
# Check for stopping
if self._stop:
self._do_stop(comments_queue, threads)
break
comments_queue.put(comment)
self.log.debug('Listen comments stopped')
except Exception as e:
self._do_stop(comments_queue, threads)
self.log.error('Exception while listening to comments:')
self.log.error(str(e))
self.log.error('Waiting for 10 minutes and trying again.')
time.sleep(10 * 60)
# Retry
self._listen_comments() | python | def _listen_comments(self):
"""Start listening to comments, using a separate thread."""
# Collect comments in a queue
comments_queue = Queue(maxsize=self._n_jobs * 4)
threads = [] # type: List[BotQueueWorker]
try:
# Create n_jobs CommentsThreads
for i in range(self._n_jobs):
t = BotQueueWorker(name='CommentThread-t-{}'.format(i),
jobs=comments_queue,
target=self._process_comment)
t.start()
threads.append(t)
# Iterate over all comments in the comment stream
for comment in self._reddit.subreddit('+'.join(self._subs)).stream.comments():
# Check for stopping
if self._stop:
self._do_stop(comments_queue, threads)
break
comments_queue.put(comment)
self.log.debug('Listen comments stopped')
except Exception as e:
self._do_stop(comments_queue, threads)
self.log.error('Exception while listening to comments:')
self.log.error(str(e))
self.log.error('Waiting for 10 minutes and trying again.')
time.sleep(10 * 60)
# Retry
self._listen_comments() | [
"def",
"_listen_comments",
"(",
"self",
")",
":",
"# Collect comments in a queue",
"comments_queue",
"=",
"Queue",
"(",
"maxsize",
"=",
"self",
".",
"_n_jobs",
"*",
"4",
")",
"threads",
"=",
"[",
"]",
"# type: List[BotQueueWorker]",
"try",
":",
"# Create n_jobs CommentsThreads",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_n_jobs",
")",
":",
"t",
"=",
"BotQueueWorker",
"(",
"name",
"=",
"'CommentThread-t-{}'",
".",
"format",
"(",
"i",
")",
",",
"jobs",
"=",
"comments_queue",
",",
"target",
"=",
"self",
".",
"_process_comment",
")",
"t",
".",
"start",
"(",
")",
"threads",
".",
"append",
"(",
"t",
")",
"# Iterate over all comments in the comment stream",
"for",
"comment",
"in",
"self",
".",
"_reddit",
".",
"subreddit",
"(",
"'+'",
".",
"join",
"(",
"self",
".",
"_subs",
")",
")",
".",
"stream",
".",
"comments",
"(",
")",
":",
"# Check for stopping",
"if",
"self",
".",
"_stop",
":",
"self",
".",
"_do_stop",
"(",
"comments_queue",
",",
"threads",
")",
"break",
"comments_queue",
".",
"put",
"(",
"comment",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Listen comments stopped'",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"_do_stop",
"(",
"comments_queue",
",",
"threads",
")",
"self",
".",
"log",
".",
"error",
"(",
"'Exception while listening to comments:'",
")",
"self",
".",
"log",
".",
"error",
"(",
"str",
"(",
"e",
")",
")",
"self",
".",
"log",
".",
"error",
"(",
"'Waiting for 10 minutes and trying again.'",
")",
"time",
".",
"sleep",
"(",
"10",
"*",
"60",
")",
"# Retry",
"self",
".",
"_listen_comments",
"(",
")"
]
| Start listening to comments, using a separate thread. | [
"Start",
"listening",
"to",
"comments",
"using",
"a",
"separate",
"thread",
"."
]
| c1b92becc31adfbd5a7b77179b852a51da70b193 | https://github.com/steven-lang/bottr/blob/c1b92becc31adfbd5a7b77179b852a51da70b193/bottr/bot.py#L79-L115 | train |
steven-lang/bottr | bottr/bot.py | AbstractSubmissionBot._listen_submissions | def _listen_submissions(self):
"""Start listening to submissions, using a separate thread."""
# Collect submissions in a queue
subs_queue = Queue(maxsize=self._n_jobs * 4)
threads = [] # type: List[BotQueueWorker]
try:
# Create n_jobs SubmissionThreads
for i in range(self._n_jobs):
t = BotQueueWorker(name='SubmissionThread-t-{}'.format(i),
jobs=subs_queue,
target=self._process_submission)
t.start()
self._threads.append(t)
# Iterate over all comments in the comment stream
for submission in self._reddit.subreddit('+'.join(self._subs)).stream.submissions():
# Check for stopping
if self._stop:
self._do_stop(subs_queue, threads)
break
subs_queue.put(submission)
self.log.debug('Listen submissions stopped')
except Exception as e:
self._do_stop(subs_queue, threads)
self.log.error('Exception while listening to submissions:')
self.log.error(str(e))
self.log.error('Waiting for 10 minutes and trying again.')
time.sleep(10 * 60)
# Retry:
self._listen_submissions() | python | def _listen_submissions(self):
"""Start listening to submissions, using a separate thread."""
# Collect submissions in a queue
subs_queue = Queue(maxsize=self._n_jobs * 4)
threads = [] # type: List[BotQueueWorker]
try:
# Create n_jobs SubmissionThreads
for i in range(self._n_jobs):
t = BotQueueWorker(name='SubmissionThread-t-{}'.format(i),
jobs=subs_queue,
target=self._process_submission)
t.start()
self._threads.append(t)
# Iterate over all comments in the comment stream
for submission in self._reddit.subreddit('+'.join(self._subs)).stream.submissions():
# Check for stopping
if self._stop:
self._do_stop(subs_queue, threads)
break
subs_queue.put(submission)
self.log.debug('Listen submissions stopped')
except Exception as e:
self._do_stop(subs_queue, threads)
self.log.error('Exception while listening to submissions:')
self.log.error(str(e))
self.log.error('Waiting for 10 minutes and trying again.')
time.sleep(10 * 60)
# Retry:
self._listen_submissions() | [
"def",
"_listen_submissions",
"(",
"self",
")",
":",
"# Collect submissions in a queue",
"subs_queue",
"=",
"Queue",
"(",
"maxsize",
"=",
"self",
".",
"_n_jobs",
"*",
"4",
")",
"threads",
"=",
"[",
"]",
"# type: List[BotQueueWorker]",
"try",
":",
"# Create n_jobs SubmissionThreads",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_n_jobs",
")",
":",
"t",
"=",
"BotQueueWorker",
"(",
"name",
"=",
"'SubmissionThread-t-{}'",
".",
"format",
"(",
"i",
")",
",",
"jobs",
"=",
"subs_queue",
",",
"target",
"=",
"self",
".",
"_process_submission",
")",
"t",
".",
"start",
"(",
")",
"self",
".",
"_threads",
".",
"append",
"(",
"t",
")",
"# Iterate over all comments in the comment stream",
"for",
"submission",
"in",
"self",
".",
"_reddit",
".",
"subreddit",
"(",
"'+'",
".",
"join",
"(",
"self",
".",
"_subs",
")",
")",
".",
"stream",
".",
"submissions",
"(",
")",
":",
"# Check for stopping",
"if",
"self",
".",
"_stop",
":",
"self",
".",
"_do_stop",
"(",
"subs_queue",
",",
"threads",
")",
"break",
"subs_queue",
".",
"put",
"(",
"submission",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Listen submissions stopped'",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"_do_stop",
"(",
"subs_queue",
",",
"threads",
")",
"self",
".",
"log",
".",
"error",
"(",
"'Exception while listening to submissions:'",
")",
"self",
".",
"log",
".",
"error",
"(",
"str",
"(",
"e",
")",
")",
"self",
".",
"log",
".",
"error",
"(",
"'Waiting for 10 minutes and trying again.'",
")",
"time",
".",
"sleep",
"(",
"10",
"*",
"60",
")",
"# Retry:",
"self",
".",
"_listen_submissions",
"(",
")"
]
| Start listening to submissions, using a separate thread. | [
"Start",
"listening",
"to",
"submissions",
"using",
"a",
"separate",
"thread",
"."
]
| c1b92becc31adfbd5a7b77179b852a51da70b193 | https://github.com/steven-lang/bottr/blob/c1b92becc31adfbd5a7b77179b852a51da70b193/bottr/bot.py#L137-L172 | train |
steven-lang/bottr | bottr/bot.py | AbstractMessageBot._listen_inbox_messages | def _listen_inbox_messages(self):
"""Start listening to messages, using a separate thread."""
# Collect messages in a queue
inbox_queue = Queue(maxsize=self._n_jobs * 4)
threads = [] # type: List[BotQueueWorker]
try:
# Create n_jobs inbox threads
for i in range(self._n_jobs):
t = BotQueueWorker(name='InboxThread-t-{}'.format(i),
jobs=inbox_queue,
target=self._process_inbox_message)
t.start()
self._threads.append(t)
# Iterate over all messages in the messages stream
for message in self._reddit.inbox.stream():
# Check for stopping
if self._stop:
self._do_stop(inbox_queue, threads)
break
inbox_queue.put(message)
self.log.debug('Listen inbox stopped')
except Exception as e:
self._do_stop(inbox_queue, threads)
self.log.error('Exception while listening to inbox:')
self.log.error(str(e))
self.log.error('Waiting for 10 minutes and trying again.')
time.sleep(10 * 60)
# Retry:
self._listen_inbox_messages() | python | def _listen_inbox_messages(self):
"""Start listening to messages, using a separate thread."""
# Collect messages in a queue
inbox_queue = Queue(maxsize=self._n_jobs * 4)
threads = [] # type: List[BotQueueWorker]
try:
# Create n_jobs inbox threads
for i in range(self._n_jobs):
t = BotQueueWorker(name='InboxThread-t-{}'.format(i),
jobs=inbox_queue,
target=self._process_inbox_message)
t.start()
self._threads.append(t)
# Iterate over all messages in the messages stream
for message in self._reddit.inbox.stream():
# Check for stopping
if self._stop:
self._do_stop(inbox_queue, threads)
break
inbox_queue.put(message)
self.log.debug('Listen inbox stopped')
except Exception as e:
self._do_stop(inbox_queue, threads)
self.log.error('Exception while listening to inbox:')
self.log.error(str(e))
self.log.error('Waiting for 10 minutes and trying again.')
time.sleep(10 * 60)
# Retry:
self._listen_inbox_messages() | [
"def",
"_listen_inbox_messages",
"(",
"self",
")",
":",
"# Collect messages in a queue",
"inbox_queue",
"=",
"Queue",
"(",
"maxsize",
"=",
"self",
".",
"_n_jobs",
"*",
"4",
")",
"threads",
"=",
"[",
"]",
"# type: List[BotQueueWorker]",
"try",
":",
"# Create n_jobs inbox threads",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_n_jobs",
")",
":",
"t",
"=",
"BotQueueWorker",
"(",
"name",
"=",
"'InboxThread-t-{}'",
".",
"format",
"(",
"i",
")",
",",
"jobs",
"=",
"inbox_queue",
",",
"target",
"=",
"self",
".",
"_process_inbox_message",
")",
"t",
".",
"start",
"(",
")",
"self",
".",
"_threads",
".",
"append",
"(",
"t",
")",
"# Iterate over all messages in the messages stream",
"for",
"message",
"in",
"self",
".",
"_reddit",
".",
"inbox",
".",
"stream",
"(",
")",
":",
"# Check for stopping",
"if",
"self",
".",
"_stop",
":",
"self",
".",
"_do_stop",
"(",
"inbox_queue",
",",
"threads",
")",
"break",
"inbox_queue",
".",
"put",
"(",
"message",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Listen inbox stopped'",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"_do_stop",
"(",
"inbox_queue",
",",
"threads",
")",
"self",
".",
"log",
".",
"error",
"(",
"'Exception while listening to inbox:'",
")",
"self",
".",
"log",
".",
"error",
"(",
"str",
"(",
"e",
")",
")",
"self",
".",
"log",
".",
"error",
"(",
"'Waiting for 10 minutes and trying again.'",
")",
"time",
".",
"sleep",
"(",
"10",
"*",
"60",
")",
"# Retry:",
"self",
".",
"_listen_inbox_messages",
"(",
")"
]
| Start listening to messages, using a separate thread. | [
"Start",
"listening",
"to",
"messages",
"using",
"a",
"separate",
"thread",
"."
]
| c1b92becc31adfbd5a7b77179b852a51da70b193 | https://github.com/steven-lang/bottr/blob/c1b92becc31adfbd5a7b77179b852a51da70b193/bottr/bot.py#L205-L239 | train |
hozn/keepassdb | keepassdb/model.py | BaseModel.to_struct | def to_struct(self):
"""
Initialize properties of the appropriate struct class from this model class.
"""
structobj = self.struct_type()
for k in structobj.attributes():
self.log.info("Setting attribute %s to %r" % (k, getattr(self, k)))
setattr(structobj, k, getattr(self, k))
return structobj | python | def to_struct(self):
"""
Initialize properties of the appropriate struct class from this model class.
"""
structobj = self.struct_type()
for k in structobj.attributes():
self.log.info("Setting attribute %s to %r" % (k, getattr(self, k)))
setattr(structobj, k, getattr(self, k))
return structobj | [
"def",
"to_struct",
"(",
"self",
")",
":",
"structobj",
"=",
"self",
".",
"struct_type",
"(",
")",
"for",
"k",
"in",
"structobj",
".",
"attributes",
"(",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Setting attribute %s to %r\"",
"%",
"(",
"k",
",",
"getattr",
"(",
"self",
",",
"k",
")",
")",
")",
"setattr",
"(",
"structobj",
",",
"k",
",",
"getattr",
"(",
"self",
",",
"k",
")",
")",
"return",
"structobj"
]
| Initialize properties of the appropriate struct class from this model class. | [
"Initialize",
"properties",
"of",
"the",
"appropriate",
"struct",
"class",
"from",
"this",
"model",
"class",
"."
]
| cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b | https://github.com/hozn/keepassdb/blob/cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b/keepassdb/model.py#L65-L73 | train |
hozn/keepassdb | keepassdb/model.py | Entry.move | def move(self, group, index=None):
"""
This method moves the entry to another group.
"""
return self.group.db.move_entry(self, group, index=index) | python | def move(self, group, index=None):
"""
This method moves the entry to another group.
"""
return self.group.db.move_entry(self, group, index=index) | [
"def",
"move",
"(",
"self",
",",
"group",
",",
"index",
"=",
"None",
")",
":",
"return",
"self",
".",
"group",
".",
"db",
".",
"move_entry",
"(",
"self",
",",
"group",
",",
"index",
"=",
"index",
")"
]
| This method moves the entry to another group. | [
"This",
"method",
"moves",
"the",
"entry",
"to",
"another",
"group",
"."
]
| cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b | https://github.com/hozn/keepassdb/blob/cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b/keepassdb/model.py#L447-L451 | train |
loganasherjones/yapconf | yapconf/__init__.py | dump_data | def dump_data(data,
filename=None,
file_type='json',
klazz=YapconfError,
open_kwargs=None,
dump_kwargs=None):
"""Dump data given to file or stdout in file_type.
Args:
data (dict): The dictionary to dump.
filename (str, optional): Defaults to None. The filename to write
the data to. If none is provided, it will be written to STDOUT.
file_type (str, optional): Defaults to 'json'. Can be any of
yapconf.FILE_TYPES
klazz (optional): Defaults to YapconfError a special error to throw
when something goes wrong.
open_kwargs (dict, optional): Keyword arguments to open.
dump_kwargs (dict, optional): Keyword arguments to dump.
"""
_check_file_type(file_type, klazz)
open_kwargs = open_kwargs or {'encoding': 'utf-8'}
dump_kwargs = dump_kwargs or {}
if filename:
with open(filename, 'w', **open_kwargs) as conf_file:
_dump(data, conf_file, file_type, **dump_kwargs)
else:
_dump(data, sys.stdout, file_type, **dump_kwargs) | python | def dump_data(data,
filename=None,
file_type='json',
klazz=YapconfError,
open_kwargs=None,
dump_kwargs=None):
"""Dump data given to file or stdout in file_type.
Args:
data (dict): The dictionary to dump.
filename (str, optional): Defaults to None. The filename to write
the data to. If none is provided, it will be written to STDOUT.
file_type (str, optional): Defaults to 'json'. Can be any of
yapconf.FILE_TYPES
klazz (optional): Defaults to YapconfError a special error to throw
when something goes wrong.
open_kwargs (dict, optional): Keyword arguments to open.
dump_kwargs (dict, optional): Keyword arguments to dump.
"""
_check_file_type(file_type, klazz)
open_kwargs = open_kwargs or {'encoding': 'utf-8'}
dump_kwargs = dump_kwargs or {}
if filename:
with open(filename, 'w', **open_kwargs) as conf_file:
_dump(data, conf_file, file_type, **dump_kwargs)
else:
_dump(data, sys.stdout, file_type, **dump_kwargs) | [
"def",
"dump_data",
"(",
"data",
",",
"filename",
"=",
"None",
",",
"file_type",
"=",
"'json'",
",",
"klazz",
"=",
"YapconfError",
",",
"open_kwargs",
"=",
"None",
",",
"dump_kwargs",
"=",
"None",
")",
":",
"_check_file_type",
"(",
"file_type",
",",
"klazz",
")",
"open_kwargs",
"=",
"open_kwargs",
"or",
"{",
"'encoding'",
":",
"'utf-8'",
"}",
"dump_kwargs",
"=",
"dump_kwargs",
"or",
"{",
"}",
"if",
"filename",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
",",
"*",
"*",
"open_kwargs",
")",
"as",
"conf_file",
":",
"_dump",
"(",
"data",
",",
"conf_file",
",",
"file_type",
",",
"*",
"*",
"dump_kwargs",
")",
"else",
":",
"_dump",
"(",
"data",
",",
"sys",
".",
"stdout",
",",
"file_type",
",",
"*",
"*",
"dump_kwargs",
")"
]
| Dump data given to file or stdout in file_type.
Args:
data (dict): The dictionary to dump.
filename (str, optional): Defaults to None. The filename to write
the data to. If none is provided, it will be written to STDOUT.
file_type (str, optional): Defaults to 'json'. Can be any of
yapconf.FILE_TYPES
klazz (optional): Defaults to YapconfError a special error to throw
when something goes wrong.
open_kwargs (dict, optional): Keyword arguments to open.
dump_kwargs (dict, optional): Keyword arguments to dump. | [
"Dump",
"data",
"given",
"to",
"file",
"or",
"stdout",
"in",
"file_type",
"."
]
| d2970e6e7e3334615d4d978d8b0ca33006d79d16 | https://github.com/loganasherjones/yapconf/blob/d2970e6e7e3334615d4d978d8b0ca33006d79d16/yapconf/__init__.py#L111-L140 | train |
loganasherjones/yapconf | yapconf/__init__.py | load_file | def load_file(filename,
file_type='json',
klazz=YapconfError,
open_kwargs=None,
load_kwargs=None):
"""Load a file with the given file type.
Args:
filename (str): The filename to load.
file_type (str, optional): Defaults to 'json'. The file type for the
given filename. Supported types are ``yapconf.FILE_TYPES```
klazz (optional): The custom exception to raise if something goes
wrong.
open_kwargs (dict, optional): Keyword arguments for the open call.
load_kwargs (dict, optional): Keyword arguments for the load call.
Raises:
klazz: If no klazz was passed in, this will be the ``YapconfError``
Returns:
dict: The dictionary from the file.
"""
_check_file_type(file_type, klazz)
open_kwargs = open_kwargs or {'encoding': 'utf-8'}
load_kwargs = load_kwargs or {}
data = None
with open(filename, **open_kwargs) as conf_file:
if str(file_type).lower() == 'json':
data = json.load(conf_file, **load_kwargs)
elif str(file_type).lower() == 'yaml':
data = yaml.safe_load(conf_file.read())
else:
raise NotImplementedError('Someone forgot to implement how to '
'load a %s file_type.' % file_type)
if not isinstance(data, dict):
raise klazz('Successfully loaded %s, but the result was '
'not a dictionary.' % filename)
return data | python | def load_file(filename,
file_type='json',
klazz=YapconfError,
open_kwargs=None,
load_kwargs=None):
"""Load a file with the given file type.
Args:
filename (str): The filename to load.
file_type (str, optional): Defaults to 'json'. The file type for the
given filename. Supported types are ``yapconf.FILE_TYPES```
klazz (optional): The custom exception to raise if something goes
wrong.
open_kwargs (dict, optional): Keyword arguments for the open call.
load_kwargs (dict, optional): Keyword arguments for the load call.
Raises:
klazz: If no klazz was passed in, this will be the ``YapconfError``
Returns:
dict: The dictionary from the file.
"""
_check_file_type(file_type, klazz)
open_kwargs = open_kwargs or {'encoding': 'utf-8'}
load_kwargs = load_kwargs or {}
data = None
with open(filename, **open_kwargs) as conf_file:
if str(file_type).lower() == 'json':
data = json.load(conf_file, **load_kwargs)
elif str(file_type).lower() == 'yaml':
data = yaml.safe_load(conf_file.read())
else:
raise NotImplementedError('Someone forgot to implement how to '
'load a %s file_type.' % file_type)
if not isinstance(data, dict):
raise klazz('Successfully loaded %s, but the result was '
'not a dictionary.' % filename)
return data | [
"def",
"load_file",
"(",
"filename",
",",
"file_type",
"=",
"'json'",
",",
"klazz",
"=",
"YapconfError",
",",
"open_kwargs",
"=",
"None",
",",
"load_kwargs",
"=",
"None",
")",
":",
"_check_file_type",
"(",
"file_type",
",",
"klazz",
")",
"open_kwargs",
"=",
"open_kwargs",
"or",
"{",
"'encoding'",
":",
"'utf-8'",
"}",
"load_kwargs",
"=",
"load_kwargs",
"or",
"{",
"}",
"data",
"=",
"None",
"with",
"open",
"(",
"filename",
",",
"*",
"*",
"open_kwargs",
")",
"as",
"conf_file",
":",
"if",
"str",
"(",
"file_type",
")",
".",
"lower",
"(",
")",
"==",
"'json'",
":",
"data",
"=",
"json",
".",
"load",
"(",
"conf_file",
",",
"*",
"*",
"load_kwargs",
")",
"elif",
"str",
"(",
"file_type",
")",
".",
"lower",
"(",
")",
"==",
"'yaml'",
":",
"data",
"=",
"yaml",
".",
"safe_load",
"(",
"conf_file",
".",
"read",
"(",
")",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'Someone forgot to implement how to '",
"'load a %s file_type.'",
"%",
"file_type",
")",
"if",
"not",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"raise",
"klazz",
"(",
"'Successfully loaded %s, but the result was '",
"'not a dictionary.'",
"%",
"filename",
")",
"return",
"data"
]
| Load a file with the given file type.
Args:
filename (str): The filename to load.
file_type (str, optional): Defaults to 'json'. The file type for the
given filename. Supported types are ``yapconf.FILE_TYPES```
klazz (optional): The custom exception to raise if something goes
wrong.
open_kwargs (dict, optional): Keyword arguments for the open call.
load_kwargs (dict, optional): Keyword arguments for the load call.
Raises:
klazz: If no klazz was passed in, this will be the ``YapconfError``
Returns:
dict: The dictionary from the file. | [
"Load",
"a",
"file",
"with",
"the",
"given",
"file",
"type",
"."
]
| d2970e6e7e3334615d4d978d8b0ca33006d79d16 | https://github.com/loganasherjones/yapconf/blob/d2970e6e7e3334615d4d978d8b0ca33006d79d16/yapconf/__init__.py#L172-L214 | train |
loganasherjones/yapconf | yapconf/__init__.py | flatten | def flatten(dictionary, separator='.', prefix=''):
"""Flatten the dictionary keys are separated by separator
Arguments:
dictionary {dict} -- The dictionary to be flattened.
Keyword Arguments:
separator {str} -- The separator to use (default is '.'). It will
crush items with key conflicts.
prefix {str} -- Used for recursive calls.
Returns:
dict -- The flattened dictionary.
"""
new_dict = {}
for key, value in dictionary.items():
new_key = prefix + separator + key if prefix else key
if isinstance(value, collections.MutableMapping):
new_dict.update(flatten(value, separator, new_key))
elif isinstance(value, list):
new_value = []
for item in value:
if isinstance(item, collections.MutableMapping):
new_value.append(flatten(item, separator, new_key))
else:
new_value.append(item)
new_dict[new_key] = new_value
else:
new_dict[new_key] = value
return new_dict | python | def flatten(dictionary, separator='.', prefix=''):
"""Flatten the dictionary keys are separated by separator
Arguments:
dictionary {dict} -- The dictionary to be flattened.
Keyword Arguments:
separator {str} -- The separator to use (default is '.'). It will
crush items with key conflicts.
prefix {str} -- Used for recursive calls.
Returns:
dict -- The flattened dictionary.
"""
new_dict = {}
for key, value in dictionary.items():
new_key = prefix + separator + key if prefix else key
if isinstance(value, collections.MutableMapping):
new_dict.update(flatten(value, separator, new_key))
elif isinstance(value, list):
new_value = []
for item in value:
if isinstance(item, collections.MutableMapping):
new_value.append(flatten(item, separator, new_key))
else:
new_value.append(item)
new_dict[new_key] = new_value
else:
new_dict[new_key] = value
return new_dict | [
"def",
"flatten",
"(",
"dictionary",
",",
"separator",
"=",
"'.'",
",",
"prefix",
"=",
"''",
")",
":",
"new_dict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"new_key",
"=",
"prefix",
"+",
"separator",
"+",
"key",
"if",
"prefix",
"else",
"key",
"if",
"isinstance",
"(",
"value",
",",
"collections",
".",
"MutableMapping",
")",
":",
"new_dict",
".",
"update",
"(",
"flatten",
"(",
"value",
",",
"separator",
",",
"new_key",
")",
")",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"new_value",
"=",
"[",
"]",
"for",
"item",
"in",
"value",
":",
"if",
"isinstance",
"(",
"item",
",",
"collections",
".",
"MutableMapping",
")",
":",
"new_value",
".",
"append",
"(",
"flatten",
"(",
"item",
",",
"separator",
",",
"new_key",
")",
")",
"else",
":",
"new_value",
".",
"append",
"(",
"item",
")",
"new_dict",
"[",
"new_key",
"]",
"=",
"new_value",
"else",
":",
"new_dict",
"[",
"new_key",
"]",
"=",
"value",
"return",
"new_dict"
]
| Flatten the dictionary keys are separated by separator
Arguments:
dictionary {dict} -- The dictionary to be flattened.
Keyword Arguments:
separator {str} -- The separator to use (default is '.'). It will
crush items with key conflicts.
prefix {str} -- Used for recursive calls.
Returns:
dict -- The flattened dictionary. | [
"Flatten",
"the",
"dictionary",
"keys",
"are",
"separated",
"by",
"separator"
]
| d2970e6e7e3334615d4d978d8b0ca33006d79d16 | https://github.com/loganasherjones/yapconf/blob/d2970e6e7e3334615d4d978d8b0ca33006d79d16/yapconf/__init__.py#L228-L260 | train |
kevinconway/venvctrl | venvctrl/cli/relocate.py | relocate | def relocate(source, destination, move=False):
"""Adjust the virtual environment settings and optional move it.
Args:
source (str): Path to the existing virtual environment.
destination (str): Desired path of the virtual environment.
move (bool): Whether or not to actually move the files. Default False.
"""
venv = api.VirtualEnvironment(source)
if not move:
venv.relocate(destination)
return None
venv.move(destination)
return None | python | def relocate(source, destination, move=False):
"""Adjust the virtual environment settings and optional move it.
Args:
source (str): Path to the existing virtual environment.
destination (str): Desired path of the virtual environment.
move (bool): Whether or not to actually move the files. Default False.
"""
venv = api.VirtualEnvironment(source)
if not move:
venv.relocate(destination)
return None
venv.move(destination)
return None | [
"def",
"relocate",
"(",
"source",
",",
"destination",
",",
"move",
"=",
"False",
")",
":",
"venv",
"=",
"api",
".",
"VirtualEnvironment",
"(",
"source",
")",
"if",
"not",
"move",
":",
"venv",
".",
"relocate",
"(",
"destination",
")",
"return",
"None",
"venv",
".",
"move",
"(",
"destination",
")",
"return",
"None"
]
| Adjust the virtual environment settings and optional move it.
Args:
source (str): Path to the existing virtual environment.
destination (str): Desired path of the virtual environment.
move (bool): Whether or not to actually move the files. Default False. | [
"Adjust",
"the",
"virtual",
"environment",
"settings",
"and",
"optional",
"move",
"it",
"."
]
| 36d4e0e4d5ebced6385a6ade1198f4769ff2df41 | https://github.com/kevinconway/venvctrl/blob/36d4e0e4d5ebced6385a6ade1198f4769ff2df41/venvctrl/cli/relocate.py#L13-L28 | train |
kevinconway/venvctrl | venvctrl/cli/relocate.py | main | def main():
"""Relocate a virtual environment."""
parser = argparse.ArgumentParser(
description='Relocate a virtual environment.'
)
parser.add_argument(
'--source',
help='The existing virtual environment.',
required=True,
)
parser.add_argument(
'--destination',
help='The location for which to configure the virtual environment.',
required=True,
)
parser.add_argument(
'--move',
help='Move the virtual environment to the destination.',
default=False,
action='store_true',
)
args = parser.parse_args()
relocate(args.source, args.destination, args.move) | python | def main():
"""Relocate a virtual environment."""
parser = argparse.ArgumentParser(
description='Relocate a virtual environment.'
)
parser.add_argument(
'--source',
help='The existing virtual environment.',
required=True,
)
parser.add_argument(
'--destination',
help='The location for which to configure the virtual environment.',
required=True,
)
parser.add_argument(
'--move',
help='Move the virtual environment to the destination.',
default=False,
action='store_true',
)
args = parser.parse_args()
relocate(args.source, args.destination, args.move) | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Relocate a virtual environment.'",
")",
"parser",
".",
"add_argument",
"(",
"'--source'",
",",
"help",
"=",
"'The existing virtual environment.'",
",",
"required",
"=",
"True",
",",
")",
"parser",
".",
"add_argument",
"(",
"'--destination'",
",",
"help",
"=",
"'The location for which to configure the virtual environment.'",
",",
"required",
"=",
"True",
",",
")",
"parser",
".",
"add_argument",
"(",
"'--move'",
",",
"help",
"=",
"'Move the virtual environment to the destination.'",
",",
"default",
"=",
"False",
",",
"action",
"=",
"'store_true'",
",",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"relocate",
"(",
"args",
".",
"source",
",",
"args",
".",
"destination",
",",
"args",
".",
"move",
")"
]
| Relocate a virtual environment. | [
"Relocate",
"a",
"virtual",
"environment",
"."
]
| 36d4e0e4d5ebced6385a6ade1198f4769ff2df41 | https://github.com/kevinconway/venvctrl/blob/36d4e0e4d5ebced6385a6ade1198f4769ff2df41/venvctrl/cli/relocate.py#L31-L54 | train |
wylee/runcommands | runcommands/util/prompt.py | confirm | def confirm(prompt='Really?', color='warning', yes_values=('y', 'yes'),
abort_on_unconfirmed=False, abort_options=None):
"""Prompt for confirmation.
Confirmation can be aborted by typing in a no value instead of one
of the yes values or with Ctrl-C.
Args:
prompt (str): Prompt to present user ["Really?"]
color (string|Color|bool) Color to print prompt string; can be
``False`` or ``None`` to print without color ["yellow"]
yes_values (list[str]): Values user must type in to confirm
[("y", "yes")]
abort_on_unconfirmed (bool|int|str): When user does *not*
confirm:
- If this is an integer, print "Aborted" to stdout if
it's 0 or to stderr if it's not 0 and then exit with
this code
- If this is a string, print it to stdout and exit with
code 0
- If this is ``True`` (or any other truthy value), print
"Aborted" to stdout and exit with code 0
abort_options (dict): Options to pass to :func:`abort` when not
confirmed (these options will override any options set via
``abort_on_unconfirmed``)
"""
if isinstance(yes_values, str):
yes_values = (yes_values,)
prompt = '{prompt} [{yes_value}/N] '.format(prompt=prompt, yes_value=yes_values[0])
if color:
prompt = printer.colorize(prompt, color=color)
try:
answer = input(prompt)
except KeyboardInterrupt:
print()
confirmed = False
else:
answer = answer.strip().lower()
confirmed = answer in yes_values
# NOTE: The abort-on-unconfirmed logic is somewhat convoluted
# because of the special case for return code 0.
do_abort_on_unconfirmed = not confirmed and (
# True, non-zero return code, non-empty string, or any other
# truthy value (in the manner of typical Python duck-typing)
bool(abort_on_unconfirmed) or
# Zero return code (special case)
(abort_on_unconfirmed == 0 and abort_on_unconfirmed is not False)
)
if do_abort_on_unconfirmed:
if abort_options is None:
abort_options = {}
if abort_on_unconfirmed is True:
abort_options.setdefault('return_code', 0)
elif isinstance(abort_on_unconfirmed, int):
abort_options.setdefault('return_code', abort_on_unconfirmed)
elif isinstance(abort_on_unconfirmed, str):
abort_options.setdefault('message', abort_on_unconfirmed)
else:
abort_options.setdefault('return_code', 0)
abort(**abort_options)
return confirmed | python | def confirm(prompt='Really?', color='warning', yes_values=('y', 'yes'),
abort_on_unconfirmed=False, abort_options=None):
"""Prompt for confirmation.
Confirmation can be aborted by typing in a no value instead of one
of the yes values or with Ctrl-C.
Args:
prompt (str): Prompt to present user ["Really?"]
color (string|Color|bool) Color to print prompt string; can be
``False`` or ``None`` to print without color ["yellow"]
yes_values (list[str]): Values user must type in to confirm
[("y", "yes")]
abort_on_unconfirmed (bool|int|str): When user does *not*
confirm:
- If this is an integer, print "Aborted" to stdout if
it's 0 or to stderr if it's not 0 and then exit with
this code
- If this is a string, print it to stdout and exit with
code 0
- If this is ``True`` (or any other truthy value), print
"Aborted" to stdout and exit with code 0
abort_options (dict): Options to pass to :func:`abort` when not
confirmed (these options will override any options set via
``abort_on_unconfirmed``)
"""
if isinstance(yes_values, str):
yes_values = (yes_values,)
prompt = '{prompt} [{yes_value}/N] '.format(prompt=prompt, yes_value=yes_values[0])
if color:
prompt = printer.colorize(prompt, color=color)
try:
answer = input(prompt)
except KeyboardInterrupt:
print()
confirmed = False
else:
answer = answer.strip().lower()
confirmed = answer in yes_values
# NOTE: The abort-on-unconfirmed logic is somewhat convoluted
# because of the special case for return code 0.
do_abort_on_unconfirmed = not confirmed and (
# True, non-zero return code, non-empty string, or any other
# truthy value (in the manner of typical Python duck-typing)
bool(abort_on_unconfirmed) or
# Zero return code (special case)
(abort_on_unconfirmed == 0 and abort_on_unconfirmed is not False)
)
if do_abort_on_unconfirmed:
if abort_options is None:
abort_options = {}
if abort_on_unconfirmed is True:
abort_options.setdefault('return_code', 0)
elif isinstance(abort_on_unconfirmed, int):
abort_options.setdefault('return_code', abort_on_unconfirmed)
elif isinstance(abort_on_unconfirmed, str):
abort_options.setdefault('message', abort_on_unconfirmed)
else:
abort_options.setdefault('return_code', 0)
abort(**abort_options)
return confirmed | [
"def",
"confirm",
"(",
"prompt",
"=",
"'Really?'",
",",
"color",
"=",
"'warning'",
",",
"yes_values",
"=",
"(",
"'y'",
",",
"'yes'",
")",
",",
"abort_on_unconfirmed",
"=",
"False",
",",
"abort_options",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"yes_values",
",",
"str",
")",
":",
"yes_values",
"=",
"(",
"yes_values",
",",
")",
"prompt",
"=",
"'{prompt} [{yes_value}/N] '",
".",
"format",
"(",
"prompt",
"=",
"prompt",
",",
"yes_value",
"=",
"yes_values",
"[",
"0",
"]",
")",
"if",
"color",
":",
"prompt",
"=",
"printer",
".",
"colorize",
"(",
"prompt",
",",
"color",
"=",
"color",
")",
"try",
":",
"answer",
"=",
"input",
"(",
"prompt",
")",
"except",
"KeyboardInterrupt",
":",
"print",
"(",
")",
"confirmed",
"=",
"False",
"else",
":",
"answer",
"=",
"answer",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"confirmed",
"=",
"answer",
"in",
"yes_values",
"# NOTE: The abort-on-unconfirmed logic is somewhat convoluted",
"# because of the special case for return code 0.",
"do_abort_on_unconfirmed",
"=",
"not",
"confirmed",
"and",
"(",
"# True, non-zero return code, non-empty string, or any other",
"# truthy value (in the manner of typical Python duck-typing)",
"bool",
"(",
"abort_on_unconfirmed",
")",
"or",
"# Zero return code (special case)",
"(",
"abort_on_unconfirmed",
"==",
"0",
"and",
"abort_on_unconfirmed",
"is",
"not",
"False",
")",
")",
"if",
"do_abort_on_unconfirmed",
":",
"if",
"abort_options",
"is",
"None",
":",
"abort_options",
"=",
"{",
"}",
"if",
"abort_on_unconfirmed",
"is",
"True",
":",
"abort_options",
".",
"setdefault",
"(",
"'return_code'",
",",
"0",
")",
"elif",
"isinstance",
"(",
"abort_on_unconfirmed",
",",
"int",
")",
":",
"abort_options",
".",
"setdefault",
"(",
"'return_code'",
",",
"abort_on_unconfirmed",
")",
"elif",
"isinstance",
"(",
"abort_on_unconfirmed",
",",
"str",
")",
":",
"abort_options",
".",
"setdefault",
"(",
"'message'",
",",
"abort_on_unconfirmed",
")",
"else",
":",
"abort_options",
".",
"setdefault",
"(",
"'return_code'",
",",
"0",
")",
"abort",
"(",
"*",
"*",
"abort_options",
")",
"return",
"confirmed"
]
| Prompt for confirmation.
Confirmation can be aborted by typing in a no value instead of one
of the yes values or with Ctrl-C.
Args:
prompt (str): Prompt to present user ["Really?"]
color (string|Color|bool) Color to print prompt string; can be
``False`` or ``None`` to print without color ["yellow"]
yes_values (list[str]): Values user must type in to confirm
[("y", "yes")]
abort_on_unconfirmed (bool|int|str): When user does *not*
confirm:
- If this is an integer, print "Aborted" to stdout if
it's 0 or to stderr if it's not 0 and then exit with
this code
- If this is a string, print it to stdout and exit with
code 0
- If this is ``True`` (or any other truthy value), print
"Aborted" to stdout and exit with code 0
abort_options (dict): Options to pass to :func:`abort` when not
confirmed (these options will override any options set via
``abort_on_unconfirmed``) | [
"Prompt",
"for",
"confirmation",
"."
]
| b1d7c262885b9ced7ab89b63562f5464ca9970fe | https://github.com/wylee/runcommands/blob/b1d7c262885b9ced7ab89b63562f5464ca9970fe/runcommands/util/prompt.py#L5-L78 | train |
sirfoga/pyhal | hal/internet/email/templates.py | EmailTemplate.get_mime_message | def get_mime_message(self):
"""Gets email MIME message
:return: Email formatted as HTML ready to be sent
"""
message = MIMEText(
"<html>" +
self.get_email_header() +
get_email_content(self.content_file) +
self.get_email_footer() +
"</html>", "html"
)
message["subject"] = self.email_subject
return message | python | def get_mime_message(self):
"""Gets email MIME message
:return: Email formatted as HTML ready to be sent
"""
message = MIMEText(
"<html>" +
self.get_email_header() +
get_email_content(self.content_file) +
self.get_email_footer() +
"</html>", "html"
)
message["subject"] = self.email_subject
return message | [
"def",
"get_mime_message",
"(",
"self",
")",
":",
"message",
"=",
"MIMEText",
"(",
"\"<html>\"",
"+",
"self",
".",
"get_email_header",
"(",
")",
"+",
"get_email_content",
"(",
"self",
".",
"content_file",
")",
"+",
"self",
".",
"get_email_footer",
"(",
")",
"+",
"\"</html>\"",
",",
"\"html\"",
")",
"message",
"[",
"\"subject\"",
"]",
"=",
"self",
".",
"email_subject",
"return",
"message"
]
| Gets email MIME message
:return: Email formatted as HTML ready to be sent | [
"Gets",
"email",
"MIME",
"message"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/internet/email/templates.py#L45-L58 | train |
freshbooks/statsdecor | statsdecor/decorators.py | increment | def increment(name, tags=None):
"""Function decorator for incrementing a statsd stat whenever
a function is invoked.
>>> from statsdecor.decorators import increment
>>> @increment('my.metric')
>>> def my_func():
>>> pass
"""
def wrap(f):
@wraps(f)
def decorator(*args, **kwargs):
stats = client()
ret = f(*args, **kwargs)
stats.incr(name, tags=tags)
return ret
return decorator
return wrap | python | def increment(name, tags=None):
"""Function decorator for incrementing a statsd stat whenever
a function is invoked.
>>> from statsdecor.decorators import increment
>>> @increment('my.metric')
>>> def my_func():
>>> pass
"""
def wrap(f):
@wraps(f)
def decorator(*args, **kwargs):
stats = client()
ret = f(*args, **kwargs)
stats.incr(name, tags=tags)
return ret
return decorator
return wrap | [
"def",
"increment",
"(",
"name",
",",
"tags",
"=",
"None",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"stats",
"=",
"client",
"(",
")",
"ret",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"stats",
".",
"incr",
"(",
"name",
",",
"tags",
"=",
"tags",
")",
"return",
"ret",
"return",
"decorator",
"return",
"wrap"
]
| Function decorator for incrementing a statsd stat whenever
a function is invoked.
>>> from statsdecor.decorators import increment
>>> @increment('my.metric')
>>> def my_func():
>>> pass | [
"Function",
"decorator",
"for",
"incrementing",
"a",
"statsd",
"stat",
"whenever",
"a",
"function",
"is",
"invoked",
"."
]
| 1c4a98e120799b430fd40c8fede9020a91162d31 | https://github.com/freshbooks/statsdecor/blob/1c4a98e120799b430fd40c8fede9020a91162d31/statsdecor/decorators.py#L5-L22 | train |
freshbooks/statsdecor | statsdecor/decorators.py | decrement | def decrement(name, tags=None):
"""Function decorator for decrementing a statsd stat whenever
a function is invoked.
>>> from statsdecor.decorators import decrement
>>> @decrement('my.metric')
>>> def my_func():
>>> pass
"""
def wrap(f):
@wraps(f)
def decorator(*args, **kwargs):
stats = client()
ret = f(*args, **kwargs)
stats.decr(name, tags=tags)
return ret
return decorator
return wrap | python | def decrement(name, tags=None):
"""Function decorator for decrementing a statsd stat whenever
a function is invoked.
>>> from statsdecor.decorators import decrement
>>> @decrement('my.metric')
>>> def my_func():
>>> pass
"""
def wrap(f):
@wraps(f)
def decorator(*args, **kwargs):
stats = client()
ret = f(*args, **kwargs)
stats.decr(name, tags=tags)
return ret
return decorator
return wrap | [
"def",
"decrement",
"(",
"name",
",",
"tags",
"=",
"None",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"stats",
"=",
"client",
"(",
")",
"ret",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"stats",
".",
"decr",
"(",
"name",
",",
"tags",
"=",
"tags",
")",
"return",
"ret",
"return",
"decorator",
"return",
"wrap"
]
| Function decorator for decrementing a statsd stat whenever
a function is invoked.
>>> from statsdecor.decorators import decrement
>>> @decrement('my.metric')
>>> def my_func():
>>> pass | [
"Function",
"decorator",
"for",
"decrementing",
"a",
"statsd",
"stat",
"whenever",
"a",
"function",
"is",
"invoked",
"."
]
| 1c4a98e120799b430fd40c8fede9020a91162d31 | https://github.com/freshbooks/statsdecor/blob/1c4a98e120799b430fd40c8fede9020a91162d31/statsdecor/decorators.py#L25-L42 | train |
freshbooks/statsdecor | statsdecor/decorators.py | timed | def timed(name, tags=None):
"""Function decorator for tracking timing information
on a function's invocation.
>>> from statsdecor.decorators import timed
>>> @timed('my.metric')
>>> def my_func():
>>> pass
"""
def wrap(f):
@wraps(f)
def decorator(*args, **kwargs):
stats = client()
with stats.timer(name, tags=tags):
return f(*args, **kwargs)
return decorator
return wrap | python | def timed(name, tags=None):
"""Function decorator for tracking timing information
on a function's invocation.
>>> from statsdecor.decorators import timed
>>> @timed('my.metric')
>>> def my_func():
>>> pass
"""
def wrap(f):
@wraps(f)
def decorator(*args, **kwargs):
stats = client()
with stats.timer(name, tags=tags):
return f(*args, **kwargs)
return decorator
return wrap | [
"def",
"timed",
"(",
"name",
",",
"tags",
"=",
"None",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"stats",
"=",
"client",
"(",
")",
"with",
"stats",
".",
"timer",
"(",
"name",
",",
"tags",
"=",
"tags",
")",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"decorator",
"return",
"wrap"
]
| Function decorator for tracking timing information
on a function's invocation.
>>> from statsdecor.decorators import timed
>>> @timed('my.metric')
>>> def my_func():
>>> pass | [
"Function",
"decorator",
"for",
"tracking",
"timing",
"information",
"on",
"a",
"function",
"s",
"invocation",
"."
]
| 1c4a98e120799b430fd40c8fede9020a91162d31 | https://github.com/freshbooks/statsdecor/blob/1c4a98e120799b430fd40c8fede9020a91162d31/statsdecor/decorators.py#L45-L61 | train |
sirfoga/pyhal | hal/files/models/files.py | Document.move_file_to_directory | def move_file_to_directory(file_path, directory_path):
"""Moves file to given directory
:param file_path: path to file to move
:param directory_path: path to target directory where to move file
"""
file_name = os.path.basename(file_path) # get name of file
if not os.path.exists(directory_path):
os.makedirs(directory_path) # create directory if necessary
os.rename(file_path, os.path.join(directory_path,
file_name)) | python | def move_file_to_directory(file_path, directory_path):
"""Moves file to given directory
:param file_path: path to file to move
:param directory_path: path to target directory where to move file
"""
file_name = os.path.basename(file_path) # get name of file
if not os.path.exists(directory_path):
os.makedirs(directory_path) # create directory if necessary
os.rename(file_path, os.path.join(directory_path,
file_name)) | [
"def",
"move_file_to_directory",
"(",
"file_path",
",",
"directory_path",
")",
":",
"file_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"file_path",
")",
"# get name of file",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory_path",
")",
":",
"os",
".",
"makedirs",
"(",
"directory_path",
")",
"# create directory if necessary",
"os",
".",
"rename",
"(",
"file_path",
",",
"os",
".",
"path",
".",
"join",
"(",
"directory_path",
",",
"file_name",
")",
")"
]
| Moves file to given directory
:param file_path: path to file to move
:param directory_path: path to target directory where to move file | [
"Moves",
"file",
"to",
"given",
"directory"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/files.py#L25-L35 | train |
sirfoga/pyhal | hal/files/models/files.py | Document.move_file_to_file | def move_file_to_file(old_path, new_path):
"""Moves file from old location to new one
:param old_path: path of file to move
:param new_path: new path
"""
try:
os.rename(old_path, new_path)
except:
old_file = os.path.basename(old_path)
target_directory, target_file = os.path.dirname(
os.path.abspath(new_path)), os.path.basename(new_path)
Document.move_file_to_directory(
old_path,
target_directory
) # move old file to new directory, change name to new name
os.rename(os.path.join(target_directory, old_file),
os.path.join(target_directory, target_file)) | python | def move_file_to_file(old_path, new_path):
"""Moves file from old location to new one
:param old_path: path of file to move
:param new_path: new path
"""
try:
os.rename(old_path, new_path)
except:
old_file = os.path.basename(old_path)
target_directory, target_file = os.path.dirname(
os.path.abspath(new_path)), os.path.basename(new_path)
Document.move_file_to_directory(
old_path,
target_directory
) # move old file to new directory, change name to new name
os.rename(os.path.join(target_directory, old_file),
os.path.join(target_directory, target_file)) | [
"def",
"move_file_to_file",
"(",
"old_path",
",",
"new_path",
")",
":",
"try",
":",
"os",
".",
"rename",
"(",
"old_path",
",",
"new_path",
")",
"except",
":",
"old_file",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"old_path",
")",
"target_directory",
",",
"target_file",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"new_path",
")",
")",
",",
"os",
".",
"path",
".",
"basename",
"(",
"new_path",
")",
"Document",
".",
"move_file_to_directory",
"(",
"old_path",
",",
"target_directory",
")",
"# move old file to new directory, change name to new name",
"os",
".",
"rename",
"(",
"os",
".",
"path",
".",
"join",
"(",
"target_directory",
",",
"old_file",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"target_directory",
",",
"target_file",
")",
")"
]
| Moves file from old location to new one
:param old_path: path of file to move
:param new_path: new path | [
"Moves",
"file",
"from",
"old",
"location",
"to",
"new",
"one"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/files.py#L38-L55 | train |
sirfoga/pyhal | hal/files/models/files.py | Document.write_data | def write_data(self, data):
"""Writes given data to given path file
:param data: data to write to file
"""
with open(self.path, "w") as writer:
writer.write(data) | python | def write_data(self, data):
"""Writes given data to given path file
:param data: data to write to file
"""
with open(self.path, "w") as writer:
writer.write(data) | [
"def",
"write_data",
"(",
"self",
",",
"data",
")",
":",
"with",
"open",
"(",
"self",
".",
"path",
",",
"\"w\"",
")",
"as",
"writer",
":",
"writer",
".",
"write",
"(",
"data",
")"
]
| Writes given data to given path file
:param data: data to write to file | [
"Writes",
"given",
"data",
"to",
"given",
"path",
"file"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/files.py#L57-L63 | train |
sirfoga/pyhal | hal/files/models/files.py | Document.get_path_name | def get_path_name(self):
"""Gets path and name of song
:return: Name of path, name of file (or folder)
"""
path = fix_raw_path(os.path.dirname(os.path.abspath(self.path)))
name = os.path.basename(self.path)
return path, name | python | def get_path_name(self):
"""Gets path and name of song
:return: Name of path, name of file (or folder)
"""
path = fix_raw_path(os.path.dirname(os.path.abspath(self.path)))
name = os.path.basename(self.path)
return path, name | [
"def",
"get_path_name",
"(",
"self",
")",
":",
"path",
"=",
"fix_raw_path",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"path",
")",
")",
")",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"path",
")",
"return",
"path",
",",
"name"
]
| Gets path and name of song
:return: Name of path, name of file (or folder) | [
"Gets",
"path",
"and",
"name",
"of",
"song"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/files.py#L84-L91 | train |
sirfoga/pyhal | hal/files/models/files.py | Directory.get_path_name | def get_path_name(self):
"""Gets path and name of file
:return: Name of path, name of file (or folder)
"""
complete_path = os.path.dirname(os.path.abspath(self.path))
name = self.path.replace(complete_path + PATH_SEPARATOR, "")
if name.endswith("/"):
name = name[: -1]
return complete_path, name | python | def get_path_name(self):
"""Gets path and name of file
:return: Name of path, name of file (or folder)
"""
complete_path = os.path.dirname(os.path.abspath(self.path))
name = self.path.replace(complete_path + PATH_SEPARATOR, "")
if name.endswith("/"):
name = name[: -1]
return complete_path, name | [
"def",
"get_path_name",
"(",
"self",
")",
":",
"complete_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"path",
")",
")",
"name",
"=",
"self",
".",
"path",
".",
"replace",
"(",
"complete_path",
"+",
"PATH_SEPARATOR",
",",
"\"\"",
")",
"if",
"name",
".",
"endswith",
"(",
"\"/\"",
")",
":",
"name",
"=",
"name",
"[",
":",
"-",
"1",
"]",
"return",
"complete_path",
",",
"name"
]
| Gets path and name of file
:return: Name of path, name of file (or folder) | [
"Gets",
"path",
"and",
"name",
"of",
"file"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/files.py#L152-L162 | train |
ArabellaTech/django-basic-cms | basic_cms/placeholders.py | PlaceholderNode.save | def save(self, page, language, data, change, extra_data=None):
"""Actually save the placeholder data into the Content object."""
# if this placeholder is untranslated, we save everything
# in the default language
if self.untranslated:
language = settings.PAGE_DEFAULT_LANGUAGE
# the page is being changed
if change:
# we need create a new content if revision is enabled
if(settings.PAGE_CONTENT_REVISION and self.name
not in settings.PAGE_CONTENT_REVISION_EXCLUDE_LIST):
Content.objects.create_content_if_changed(
page,
language,
self.name,
data
)
else:
Content.objects.set_or_create_content(
page,
language,
self.name,
data
)
# the page is being added
else:
Content.objects.set_or_create_content(
page,
language,
self.name,
data
) | python | def save(self, page, language, data, change, extra_data=None):
"""Actually save the placeholder data into the Content object."""
# if this placeholder is untranslated, we save everything
# in the default language
if self.untranslated:
language = settings.PAGE_DEFAULT_LANGUAGE
# the page is being changed
if change:
# we need create a new content if revision is enabled
if(settings.PAGE_CONTENT_REVISION and self.name
not in settings.PAGE_CONTENT_REVISION_EXCLUDE_LIST):
Content.objects.create_content_if_changed(
page,
language,
self.name,
data
)
else:
Content.objects.set_or_create_content(
page,
language,
self.name,
data
)
# the page is being added
else:
Content.objects.set_or_create_content(
page,
language,
self.name,
data
) | [
"def",
"save",
"(",
"self",
",",
"page",
",",
"language",
",",
"data",
",",
"change",
",",
"extra_data",
"=",
"None",
")",
":",
"# if this placeholder is untranslated, we save everything",
"# in the default language",
"if",
"self",
".",
"untranslated",
":",
"language",
"=",
"settings",
".",
"PAGE_DEFAULT_LANGUAGE",
"# the page is being changed",
"if",
"change",
":",
"# we need create a new content if revision is enabled",
"if",
"(",
"settings",
".",
"PAGE_CONTENT_REVISION",
"and",
"self",
".",
"name",
"not",
"in",
"settings",
".",
"PAGE_CONTENT_REVISION_EXCLUDE_LIST",
")",
":",
"Content",
".",
"objects",
".",
"create_content_if_changed",
"(",
"page",
",",
"language",
",",
"self",
".",
"name",
",",
"data",
")",
"else",
":",
"Content",
".",
"objects",
".",
"set_or_create_content",
"(",
"page",
",",
"language",
",",
"self",
".",
"name",
",",
"data",
")",
"# the page is being added",
"else",
":",
"Content",
".",
"objects",
".",
"set_or_create_content",
"(",
"page",
",",
"language",
",",
"self",
".",
"name",
",",
"data",
")"
]
| Actually save the placeholder data into the Content object. | [
"Actually",
"save",
"the",
"placeholder",
"data",
"into",
"the",
"Content",
"object",
"."
]
| 863f3c6098606f663994930cd8e7723ad0c07caf | https://github.com/ArabellaTech/django-basic-cms/blob/863f3c6098606f663994930cd8e7723ad0c07caf/basic_cms/placeholders.py#L156-L188 | train |
ArabellaTech/django-basic-cms | basic_cms/placeholders.py | PlaceholderNode.render | def render(self, context):
"""Output the content of the `PlaceholdeNode` in the template."""
content = mark_safe(self.get_content_from_context(context))
if not content:
return ''
if self.parsed:
try:
t = template.Template(content, name=self.name)
content = mark_safe(t.render(context))
except TemplateSyntaxError as error:
if global_settings.DEBUG:
content = PLACEHOLDER_ERROR % {
'name': self.name,
'error': error,
}
else:
content = ''
if self.as_varname is None:
return content
context[self.as_varname] = content
return '' | python | def render(self, context):
"""Output the content of the `PlaceholdeNode` in the template."""
content = mark_safe(self.get_content_from_context(context))
if not content:
return ''
if self.parsed:
try:
t = template.Template(content, name=self.name)
content = mark_safe(t.render(context))
except TemplateSyntaxError as error:
if global_settings.DEBUG:
content = PLACEHOLDER_ERROR % {
'name': self.name,
'error': error,
}
else:
content = ''
if self.as_varname is None:
return content
context[self.as_varname] = content
return '' | [
"def",
"render",
"(",
"self",
",",
"context",
")",
":",
"content",
"=",
"mark_safe",
"(",
"self",
".",
"get_content_from_context",
"(",
"context",
")",
")",
"if",
"not",
"content",
":",
"return",
"''",
"if",
"self",
".",
"parsed",
":",
"try",
":",
"t",
"=",
"template",
".",
"Template",
"(",
"content",
",",
"name",
"=",
"self",
".",
"name",
")",
"content",
"=",
"mark_safe",
"(",
"t",
".",
"render",
"(",
"context",
")",
")",
"except",
"TemplateSyntaxError",
"as",
"error",
":",
"if",
"global_settings",
".",
"DEBUG",
":",
"content",
"=",
"PLACEHOLDER_ERROR",
"%",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'error'",
":",
"error",
",",
"}",
"else",
":",
"content",
"=",
"''",
"if",
"self",
".",
"as_varname",
"is",
"None",
":",
"return",
"content",
"context",
"[",
"self",
".",
"as_varname",
"]",
"=",
"content",
"return",
"''"
]
| Output the content of the `PlaceholdeNode` in the template. | [
"Output",
"the",
"content",
"of",
"the",
"PlaceholdeNode",
"in",
"the",
"template",
"."
]
| 863f3c6098606f663994930cd8e7723ad0c07caf | https://github.com/ArabellaTech/django-basic-cms/blob/863f3c6098606f663994930cd8e7723ad0c07caf/basic_cms/placeholders.py#L219-L240 | train |
Frzk/Ellis | ellis/action.py | Action.from_string | def from_string(cls, action_str):
"""
Creates a new Action instance from the given string.
The given string **must** match one of those patterns:
* module.function
* module.function()
* module.function(arg1=value1, arg2=value2)
Any other form will trigger an Exception.
The function parses the given string and tries to load the function
from the given module.
Raises :class:`exceptions.SyntaxError` if the compiled source code is
invalid.
Raises :class:`exceptions.ValueError` if the given source code contains
null bytes.
Raises :class:`exceptions.UnsupportedActionError` if the given source
code can not be parsed (doesn't match one of the supported patterns).
Raises :class:`exceptions.UnsupportedActionArgumentError` if one the
given argument has an unsupported type (we only support
:class:`ast.Num` and :class:`ast.Str`).
Returns a new :class:`Action` instance.
"""
args = {}
try:
mod_obj = ast.parse(action_str)
except (SyntaxError, ValueError) as e:
raise e
else:
call_obj = mod_obj.body[0].value
if isinstance(call_obj, ast.Attribute):
# Seems like we have a simple function name
# (for example `module.function`)
module = call_obj.value.id
func = call_obj.attr
elif isinstance(call_obj, ast.Call):
# Seems like we have a function call, maybe with
# a few parameters.
# Note that we only support `module.function()` format.
# You can't use `function()`.
try:
module = call_obj.func.value.id
func = call_obj.func.attr
except AttributeError:
raise UnsupportedActionError(action_str)
else:
# If we have arguments, they MUST be named:
for kwarg in call_obj.keywords:
# We only support Strings and Numerics:
if isinstance(kwarg.value, ast.Num):
args.update({kwarg.arg: kwarg.value.n})
elif isinstance(kwarg.value, ast.Str):
args.update({kwarg.arg: kwarg.value.s})
else:
raise UnsupportedActionArgumentError(action_str,
kwarg)
else:
raise UnsupportedActionError(action_str)
return cls(module, func, args) | python | def from_string(cls, action_str):
"""
Creates a new Action instance from the given string.
The given string **must** match one of those patterns:
* module.function
* module.function()
* module.function(arg1=value1, arg2=value2)
Any other form will trigger an Exception.
The function parses the given string and tries to load the function
from the given module.
Raises :class:`exceptions.SyntaxError` if the compiled source code is
invalid.
Raises :class:`exceptions.ValueError` if the given source code contains
null bytes.
Raises :class:`exceptions.UnsupportedActionError` if the given source
code can not be parsed (doesn't match one of the supported patterns).
Raises :class:`exceptions.UnsupportedActionArgumentError` if one the
given argument has an unsupported type (we only support
:class:`ast.Num` and :class:`ast.Str`).
Returns a new :class:`Action` instance.
"""
args = {}
try:
mod_obj = ast.parse(action_str)
except (SyntaxError, ValueError) as e:
raise e
else:
call_obj = mod_obj.body[0].value
if isinstance(call_obj, ast.Attribute):
# Seems like we have a simple function name
# (for example `module.function`)
module = call_obj.value.id
func = call_obj.attr
elif isinstance(call_obj, ast.Call):
# Seems like we have a function call, maybe with
# a few parameters.
# Note that we only support `module.function()` format.
# You can't use `function()`.
try:
module = call_obj.func.value.id
func = call_obj.func.attr
except AttributeError:
raise UnsupportedActionError(action_str)
else:
# If we have arguments, they MUST be named:
for kwarg in call_obj.keywords:
# We only support Strings and Numerics:
if isinstance(kwarg.value, ast.Num):
args.update({kwarg.arg: kwarg.value.n})
elif isinstance(kwarg.value, ast.Str):
args.update({kwarg.arg: kwarg.value.s})
else:
raise UnsupportedActionArgumentError(action_str,
kwarg)
else:
raise UnsupportedActionError(action_str)
return cls(module, func, args) | [
"def",
"from_string",
"(",
"cls",
",",
"action_str",
")",
":",
"args",
"=",
"{",
"}",
"try",
":",
"mod_obj",
"=",
"ast",
".",
"parse",
"(",
"action_str",
")",
"except",
"(",
"SyntaxError",
",",
"ValueError",
")",
"as",
"e",
":",
"raise",
"e",
"else",
":",
"call_obj",
"=",
"mod_obj",
".",
"body",
"[",
"0",
"]",
".",
"value",
"if",
"isinstance",
"(",
"call_obj",
",",
"ast",
".",
"Attribute",
")",
":",
"# Seems like we have a simple function name",
"# (for example `module.function`)",
"module",
"=",
"call_obj",
".",
"value",
".",
"id",
"func",
"=",
"call_obj",
".",
"attr",
"elif",
"isinstance",
"(",
"call_obj",
",",
"ast",
".",
"Call",
")",
":",
"# Seems like we have a function call, maybe with",
"# a few parameters.",
"# Note that we only support `module.function()` format.",
"# You can't use `function()`.",
"try",
":",
"module",
"=",
"call_obj",
".",
"func",
".",
"value",
".",
"id",
"func",
"=",
"call_obj",
".",
"func",
".",
"attr",
"except",
"AttributeError",
":",
"raise",
"UnsupportedActionError",
"(",
"action_str",
")",
"else",
":",
"# If we have arguments, they MUST be named:",
"for",
"kwarg",
"in",
"call_obj",
".",
"keywords",
":",
"# We only support Strings and Numerics:",
"if",
"isinstance",
"(",
"kwarg",
".",
"value",
",",
"ast",
".",
"Num",
")",
":",
"args",
".",
"update",
"(",
"{",
"kwarg",
".",
"arg",
":",
"kwarg",
".",
"value",
".",
"n",
"}",
")",
"elif",
"isinstance",
"(",
"kwarg",
".",
"value",
",",
"ast",
".",
"Str",
")",
":",
"args",
".",
"update",
"(",
"{",
"kwarg",
".",
"arg",
":",
"kwarg",
".",
"value",
".",
"s",
"}",
")",
"else",
":",
"raise",
"UnsupportedActionArgumentError",
"(",
"action_str",
",",
"kwarg",
")",
"else",
":",
"raise",
"UnsupportedActionError",
"(",
"action_str",
")",
"return",
"cls",
"(",
"module",
",",
"func",
",",
"args",
")"
]
| Creates a new Action instance from the given string.
The given string **must** match one of those patterns:
* module.function
* module.function()
* module.function(arg1=value1, arg2=value2)
Any other form will trigger an Exception.
The function parses the given string and tries to load the function
from the given module.
Raises :class:`exceptions.SyntaxError` if the compiled source code is
invalid.
Raises :class:`exceptions.ValueError` if the given source code contains
null bytes.
Raises :class:`exceptions.UnsupportedActionError` if the given source
code can not be parsed (doesn't match one of the supported patterns).
Raises :class:`exceptions.UnsupportedActionArgumentError` if one the
given argument has an unsupported type (we only support
:class:`ast.Num` and :class:`ast.Str`).
Returns a new :class:`Action` instance. | [
"Creates",
"a",
"new",
"Action",
"instance",
"from",
"the",
"given",
"string",
"."
]
| 39ce8987cbc503354cf1f45927344186a8b18363 | https://github.com/Frzk/Ellis/blob/39ce8987cbc503354cf1f45927344186a8b18363/ellis/action.py#L143-L213 | train |
ArabellaTech/django-basic-cms | basic_cms/managers.py | ContentManager.sanitize | def sanitize(self, content):
"""Sanitize a string in order to avoid possible XSS using
``html5lib``."""
import html5lib
from html5lib import sanitizer
p = html5lib.HTMLParser(tokenizer=sanitizer.HTMLSanitizer)
dom_tree = p.parseFragment(content)
return dom_tree.text | python | def sanitize(self, content):
"""Sanitize a string in order to avoid possible XSS using
``html5lib``."""
import html5lib
from html5lib import sanitizer
p = html5lib.HTMLParser(tokenizer=sanitizer.HTMLSanitizer)
dom_tree = p.parseFragment(content)
return dom_tree.text | [
"def",
"sanitize",
"(",
"self",
",",
"content",
")",
":",
"import",
"html5lib",
"from",
"html5lib",
"import",
"sanitizer",
"p",
"=",
"html5lib",
".",
"HTMLParser",
"(",
"tokenizer",
"=",
"sanitizer",
".",
"HTMLSanitizer",
")",
"dom_tree",
"=",
"p",
".",
"parseFragment",
"(",
"content",
")",
"return",
"dom_tree",
".",
"text"
]
| Sanitize a string in order to avoid possible XSS using
``html5lib``. | [
"Sanitize",
"a",
"string",
"in",
"order",
"to",
"avoid",
"possible",
"XSS",
"using",
"html5lib",
"."
]
| 863f3c6098606f663994930cd8e7723ad0c07caf | https://github.com/ArabellaTech/django-basic-cms/blob/863f3c6098606f663994930cd8e7723ad0c07caf/basic_cms/managers.py#L273-L280 | train |
TorkamaniLab/metapipe | metapipe/parser.py | Parser.consume | def consume(self, cwd=None):
""" Converts the lexer tokens into valid statements. This process
also checks command syntax.
"""
first_pass = Grammar.overall.parseString(self.string)
lowered = { key.lower(): val for key, val in first_pass.iteritems() }
self.commands = ['\n'.join(self._get('commands', lowered))]
self.job_options = self._get('job_options', lowered)
self.global_options = self._get('options', lowered)
self.files = self._get('files', lowered)
self.paths = self._get('paths', lowered)
self.files = self._parse(self.files, Grammar.file, True)
self.paths = self._parse(self.paths, Grammar.path, True)
self.job_options = self._parse(self.job_options, Grammar.line)
try:
command_lines = self._parse(self.commands, Grammar.command_lines)[0]
except IndexError:
raise ValueError('Did you write any commands?')
self.commands = []
for command_line in command_lines:
comments, command = command_line
self.commands.append([comments.asList(),
self._parse([''.join(command)], Grammar.command)])
self.job_options = [opt.asList() for opt in self.job_options]
self.paths = ctf.get_paths(self.paths)
self.files = ctf.get_files(self.files)
self.paths.reverse()
self.files.reverse()
self.commands.reverse()
return ctf.get_command_templates(self.commands, self.files[:],
self.paths[:], self.job_options) | python | def consume(self, cwd=None):
""" Converts the lexer tokens into valid statements. This process
also checks command syntax.
"""
first_pass = Grammar.overall.parseString(self.string)
lowered = { key.lower(): val for key, val in first_pass.iteritems() }
self.commands = ['\n'.join(self._get('commands', lowered))]
self.job_options = self._get('job_options', lowered)
self.global_options = self._get('options', lowered)
self.files = self._get('files', lowered)
self.paths = self._get('paths', lowered)
self.files = self._parse(self.files, Grammar.file, True)
self.paths = self._parse(self.paths, Grammar.path, True)
self.job_options = self._parse(self.job_options, Grammar.line)
try:
command_lines = self._parse(self.commands, Grammar.command_lines)[0]
except IndexError:
raise ValueError('Did you write any commands?')
self.commands = []
for command_line in command_lines:
comments, command = command_line
self.commands.append([comments.asList(),
self._parse([''.join(command)], Grammar.command)])
self.job_options = [opt.asList() for opt in self.job_options]
self.paths = ctf.get_paths(self.paths)
self.files = ctf.get_files(self.files)
self.paths.reverse()
self.files.reverse()
self.commands.reverse()
return ctf.get_command_templates(self.commands, self.files[:],
self.paths[:], self.job_options) | [
"def",
"consume",
"(",
"self",
",",
"cwd",
"=",
"None",
")",
":",
"first_pass",
"=",
"Grammar",
".",
"overall",
".",
"parseString",
"(",
"self",
".",
"string",
")",
"lowered",
"=",
"{",
"key",
".",
"lower",
"(",
")",
":",
"val",
"for",
"key",
",",
"val",
"in",
"first_pass",
".",
"iteritems",
"(",
")",
"}",
"self",
".",
"commands",
"=",
"[",
"'\\n'",
".",
"join",
"(",
"self",
".",
"_get",
"(",
"'commands'",
",",
"lowered",
")",
")",
"]",
"self",
".",
"job_options",
"=",
"self",
".",
"_get",
"(",
"'job_options'",
",",
"lowered",
")",
"self",
".",
"global_options",
"=",
"self",
".",
"_get",
"(",
"'options'",
",",
"lowered",
")",
"self",
".",
"files",
"=",
"self",
".",
"_get",
"(",
"'files'",
",",
"lowered",
")",
"self",
".",
"paths",
"=",
"self",
".",
"_get",
"(",
"'paths'",
",",
"lowered",
")",
"self",
".",
"files",
"=",
"self",
".",
"_parse",
"(",
"self",
".",
"files",
",",
"Grammar",
".",
"file",
",",
"True",
")",
"self",
".",
"paths",
"=",
"self",
".",
"_parse",
"(",
"self",
".",
"paths",
",",
"Grammar",
".",
"path",
",",
"True",
")",
"self",
".",
"job_options",
"=",
"self",
".",
"_parse",
"(",
"self",
".",
"job_options",
",",
"Grammar",
".",
"line",
")",
"try",
":",
"command_lines",
"=",
"self",
".",
"_parse",
"(",
"self",
".",
"commands",
",",
"Grammar",
".",
"command_lines",
")",
"[",
"0",
"]",
"except",
"IndexError",
":",
"raise",
"ValueError",
"(",
"'Did you write any commands?'",
")",
"self",
".",
"commands",
"=",
"[",
"]",
"for",
"command_line",
"in",
"command_lines",
":",
"comments",
",",
"command",
"=",
"command_line",
"self",
".",
"commands",
".",
"append",
"(",
"[",
"comments",
".",
"asList",
"(",
")",
",",
"self",
".",
"_parse",
"(",
"[",
"''",
".",
"join",
"(",
"command",
")",
"]",
",",
"Grammar",
".",
"command",
")",
"]",
")",
"self",
".",
"job_options",
"=",
"[",
"opt",
".",
"asList",
"(",
")",
"for",
"opt",
"in",
"self",
".",
"job_options",
"]",
"self",
".",
"paths",
"=",
"ctf",
".",
"get_paths",
"(",
"self",
".",
"paths",
")",
"self",
".",
"files",
"=",
"ctf",
".",
"get_files",
"(",
"self",
".",
"files",
")",
"self",
".",
"paths",
".",
"reverse",
"(",
")",
"self",
".",
"files",
".",
"reverse",
"(",
")",
"self",
".",
"commands",
".",
"reverse",
"(",
")",
"return",
"ctf",
".",
"get_command_templates",
"(",
"self",
".",
"commands",
",",
"self",
".",
"files",
"[",
":",
"]",
",",
"self",
".",
"paths",
"[",
":",
"]",
",",
"self",
".",
"job_options",
")"
]
| Converts the lexer tokens into valid statements. This process
also checks command syntax. | [
"Converts",
"the",
"lexer",
"tokens",
"into",
"valid",
"statements",
".",
"This",
"process",
"also",
"checks",
"command",
"syntax",
"."
]
| 15592e5b0c217afb00ac03503f8d0d7453d4baf4 | https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/parser.py#L17-L56 | train |
TorkamaniLab/metapipe | metapipe/parser.py | Parser._get | def _get(self, key, parser_result):
""" Given a type and a dict of parser results, return
the items as a list.
"""
try:
list_data = parser_result[key].asList()
if any(isinstance(obj, str) for obj in list_data):
txt_lines = [''.join(list_data)]
else:
txt_lines = [''.join(f) for f in list_data]
except KeyError:
txt_lines = []
return txt_lines | python | def _get(self, key, parser_result):
""" Given a type and a dict of parser results, return
the items as a list.
"""
try:
list_data = parser_result[key].asList()
if any(isinstance(obj, str) for obj in list_data):
txt_lines = [''.join(list_data)]
else:
txt_lines = [''.join(f) for f in list_data]
except KeyError:
txt_lines = []
return txt_lines | [
"def",
"_get",
"(",
"self",
",",
"key",
",",
"parser_result",
")",
":",
"try",
":",
"list_data",
"=",
"parser_result",
"[",
"key",
"]",
".",
"asList",
"(",
")",
"if",
"any",
"(",
"isinstance",
"(",
"obj",
",",
"str",
")",
"for",
"obj",
"in",
"list_data",
")",
":",
"txt_lines",
"=",
"[",
"''",
".",
"join",
"(",
"list_data",
")",
"]",
"else",
":",
"txt_lines",
"=",
"[",
"''",
".",
"join",
"(",
"f",
")",
"for",
"f",
"in",
"list_data",
"]",
"except",
"KeyError",
":",
"txt_lines",
"=",
"[",
"]",
"return",
"txt_lines"
]
| Given a type and a dict of parser results, return
the items as a list. | [
"Given",
"a",
"type",
"and",
"a",
"dict",
"of",
"parser",
"results",
"return",
"the",
"items",
"as",
"a",
"list",
"."
]
| 15592e5b0c217afb00ac03503f8d0d7453d4baf4 | https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/parser.py#L58-L70 | train |
TorkamaniLab/metapipe | metapipe/parser.py | Parser._parse | def _parse(self, lines, grammar, ignore_comments=False):
""" Given a type and a list, parse it using the more detailed
parse grammar.
"""
results = []
for c in lines:
if c != '' and not (ignore_comments and c[0] == '#'):
try:
results.append(grammar.parseString(c))
except pyparsing.ParseException as e:
raise ValueError('Invalid syntax. Verify line {} is '
'correct.\n{}\n\n{}'.format(e.lineno, c, e))
return results | python | def _parse(self, lines, grammar, ignore_comments=False):
""" Given a type and a list, parse it using the more detailed
parse grammar.
"""
results = []
for c in lines:
if c != '' and not (ignore_comments and c[0] == '#'):
try:
results.append(grammar.parseString(c))
except pyparsing.ParseException as e:
raise ValueError('Invalid syntax. Verify line {} is '
'correct.\n{}\n\n{}'.format(e.lineno, c, e))
return results | [
"def",
"_parse",
"(",
"self",
",",
"lines",
",",
"grammar",
",",
"ignore_comments",
"=",
"False",
")",
":",
"results",
"=",
"[",
"]",
"for",
"c",
"in",
"lines",
":",
"if",
"c",
"!=",
"''",
"and",
"not",
"(",
"ignore_comments",
"and",
"c",
"[",
"0",
"]",
"==",
"'#'",
")",
":",
"try",
":",
"results",
".",
"append",
"(",
"grammar",
".",
"parseString",
"(",
"c",
")",
")",
"except",
"pyparsing",
".",
"ParseException",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"'Invalid syntax. Verify line {} is '",
"'correct.\\n{}\\n\\n{}'",
".",
"format",
"(",
"e",
".",
"lineno",
",",
"c",
",",
"e",
")",
")",
"return",
"results"
]
| Given a type and a list, parse it using the more detailed
parse grammar. | [
"Given",
"a",
"type",
"and",
"a",
"list",
"parse",
"it",
"using",
"the",
"more",
"detailed",
"parse",
"grammar",
"."
]
| 15592e5b0c217afb00ac03503f8d0d7453d4baf4 | https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/parser.py#L72-L84 | train |
lowandrew/OLCTools | metagenomefilter/automateCLARK.py | CLARK.objectprep | def objectprep(self):
"""Create objects to store data and metadata for each sample. Also, perform necessary file manipulations"""
# Move the files to subfolders and create objects
self.runmetadata = createobject.ObjectCreation(self)
if self.extension == 'fastq':
# To streamline the CLARK process, decompress and combine .gz and paired end files as required
logging.info('Decompressing and combining .fastq files for CLARK analysis')
fileprep.Fileprep(self)
else:
logging.info('Using .fasta files for CLARK analysis')
for sample in self.runmetadata.samples:
sample.general.combined = sample.general.fastqfiles[0] | python | def objectprep(self):
"""Create objects to store data and metadata for each sample. Also, perform necessary file manipulations"""
# Move the files to subfolders and create objects
self.runmetadata = createobject.ObjectCreation(self)
if self.extension == 'fastq':
# To streamline the CLARK process, decompress and combine .gz and paired end files as required
logging.info('Decompressing and combining .fastq files for CLARK analysis')
fileprep.Fileprep(self)
else:
logging.info('Using .fasta files for CLARK analysis')
for sample in self.runmetadata.samples:
sample.general.combined = sample.general.fastqfiles[0] | [
"def",
"objectprep",
"(",
"self",
")",
":",
"# Move the files to subfolders and create objects",
"self",
".",
"runmetadata",
"=",
"createobject",
".",
"ObjectCreation",
"(",
"self",
")",
"if",
"self",
".",
"extension",
"==",
"'fastq'",
":",
"# To streamline the CLARK process, decompress and combine .gz and paired end files as required",
"logging",
".",
"info",
"(",
"'Decompressing and combining .fastq files for CLARK analysis'",
")",
"fileprep",
".",
"Fileprep",
"(",
"self",
")",
"else",
":",
"logging",
".",
"info",
"(",
"'Using .fasta files for CLARK analysis'",
")",
"for",
"sample",
"in",
"self",
".",
"runmetadata",
".",
"samples",
":",
"sample",
".",
"general",
".",
"combined",
"=",
"sample",
".",
"general",
".",
"fastqfiles",
"[",
"0",
"]"
]
| Create objects to store data and metadata for each sample. Also, perform necessary file manipulations | [
"Create",
"objects",
"to",
"store",
"data",
"and",
"metadata",
"for",
"each",
"sample",
".",
"Also",
"perform",
"necessary",
"file",
"manipulations"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/metagenomefilter/automateCLARK.py#L38-L49 | train |
lowandrew/OLCTools | metagenomefilter/automateCLARK.py | CLARK.settargets | def settargets(self):
"""Set the targets to be used in the analyses. Involves the path of the database files, the database files to
use, and the level of classification for the analysis"""
# Define the set targets call. Include the path to the script, the database path and files, as well
# as the taxonomic rank to use
logging.info('Setting up database')
self.targetcall = 'cd {} && ./set_targets.sh {} {} --{}'.format(self.clarkpath, self.databasepath,
self.database, self.rank)
#
subprocess.call(self.targetcall, shell=True, stdout=self.devnull, stderr=self.devnull) | python | def settargets(self):
"""Set the targets to be used in the analyses. Involves the path of the database files, the database files to
use, and the level of classification for the analysis"""
# Define the set targets call. Include the path to the script, the database path and files, as well
# as the taxonomic rank to use
logging.info('Setting up database')
self.targetcall = 'cd {} && ./set_targets.sh {} {} --{}'.format(self.clarkpath, self.databasepath,
self.database, self.rank)
#
subprocess.call(self.targetcall, shell=True, stdout=self.devnull, stderr=self.devnull) | [
"def",
"settargets",
"(",
"self",
")",
":",
"# Define the set targets call. Include the path to the script, the database path and files, as well",
"# as the taxonomic rank to use",
"logging",
".",
"info",
"(",
"'Setting up database'",
")",
"self",
".",
"targetcall",
"=",
"'cd {} && ./set_targets.sh {} {} --{}'",
".",
"format",
"(",
"self",
".",
"clarkpath",
",",
"self",
".",
"databasepath",
",",
"self",
".",
"database",
",",
"self",
".",
"rank",
")",
"#",
"subprocess",
".",
"call",
"(",
"self",
".",
"targetcall",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"self",
".",
"devnull",
",",
"stderr",
"=",
"self",
".",
"devnull",
")"
]
| Set the targets to be used in the analyses. Involves the path of the database files, the database files to
use, and the level of classification for the analysis | [
"Set",
"the",
"targets",
"to",
"be",
"used",
"in",
"the",
"analyses",
".",
"Involves",
"the",
"path",
"of",
"the",
"database",
"files",
"the",
"database",
"files",
"to",
"use",
"and",
"the",
"level",
"of",
"classification",
"for",
"the",
"analysis"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/metagenomefilter/automateCLARK.py#L51-L60 | train |
lowandrew/OLCTools | metagenomefilter/automateCLARK.py | CLARK.classifymetagenome | def classifymetagenome(self):
"""Run the classify metagenome of the CLARK package on the samples"""
logging.info('Classifying metagenomes')
# Define the system call
self.classifycall = 'cd {} && ./classify_metagenome.sh -O {} -R {} -n {} --light'\
.format(self.clarkpath,
self.filelist,
self.reportlist,
self.cpus)
# Variable to store classification state
classify = True
for sample in self.runmetadata.samples:
try:
# Define the name of the .csv classification file
sample.general.classification = sample.general.combined.split('.')[0] + '.csv'
# If the file exists, then set classify to False
if os.path.isfile(sample.general.classification):
classify = False
except KeyError:
pass
# Run the system call if the samples have not been classified
if classify:
# Run the call
subprocess.call(self.classifycall, shell=True, stdout=self.devnull, stderr=self.devnull) | python | def classifymetagenome(self):
"""Run the classify metagenome of the CLARK package on the samples"""
logging.info('Classifying metagenomes')
# Define the system call
self.classifycall = 'cd {} && ./classify_metagenome.sh -O {} -R {} -n {} --light'\
.format(self.clarkpath,
self.filelist,
self.reportlist,
self.cpus)
# Variable to store classification state
classify = True
for sample in self.runmetadata.samples:
try:
# Define the name of the .csv classification file
sample.general.classification = sample.general.combined.split('.')[0] + '.csv'
# If the file exists, then set classify to False
if os.path.isfile(sample.general.classification):
classify = False
except KeyError:
pass
# Run the system call if the samples have not been classified
if classify:
# Run the call
subprocess.call(self.classifycall, shell=True, stdout=self.devnull, stderr=self.devnull) | [
"def",
"classifymetagenome",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Classifying metagenomes'",
")",
"# Define the system call",
"self",
".",
"classifycall",
"=",
"'cd {} && ./classify_metagenome.sh -O {} -R {} -n {} --light'",
".",
"format",
"(",
"self",
".",
"clarkpath",
",",
"self",
".",
"filelist",
",",
"self",
".",
"reportlist",
",",
"self",
".",
"cpus",
")",
"# Variable to store classification state",
"classify",
"=",
"True",
"for",
"sample",
"in",
"self",
".",
"runmetadata",
".",
"samples",
":",
"try",
":",
"# Define the name of the .csv classification file",
"sample",
".",
"general",
".",
"classification",
"=",
"sample",
".",
"general",
".",
"combined",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"+",
"'.csv'",
"# If the file exists, then set classify to False",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"sample",
".",
"general",
".",
"classification",
")",
":",
"classify",
"=",
"False",
"except",
"KeyError",
":",
"pass",
"# Run the system call if the samples have not been classified",
"if",
"classify",
":",
"# Run the call",
"subprocess",
".",
"call",
"(",
"self",
".",
"classifycall",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"self",
".",
"devnull",
",",
"stderr",
"=",
"self",
".",
"devnull",
")"
]
| Run the classify metagenome of the CLARK package on the samples | [
"Run",
"the",
"classify",
"metagenome",
"of",
"the",
"CLARK",
"package",
"on",
"the",
"samples"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/metagenomefilter/automateCLARK.py#L80-L103 | train |
lowandrew/OLCTools | metagenomefilter/automateCLARK.py | CLARK.lists | def lists(self):
"""
Prepare the list of files to be processed
"""
# Prepare the lists to be used to classify the metagenomes
with open(self.filelist, 'w') as filelist:
with open(self.reportlist, 'w') as reportlist:
for sample in self.runmetadata.samples:
if self.extension == 'fastq':
try:
status = sample.run.Description
if status == 'metagenome':
filelist.write(sample.general.combined + '\n')
reportlist.write(sample.general.combined.split('.')[0] + '\n')
except AttributeError:
pass
else:
if sample.general.combined != 'NA':
filelist.write(sample.general.combined + '\n')
reportlist.write(sample.general.combined.split('.')[0] + '\n') | python | def lists(self):
"""
Prepare the list of files to be processed
"""
# Prepare the lists to be used to classify the metagenomes
with open(self.filelist, 'w') as filelist:
with open(self.reportlist, 'w') as reportlist:
for sample in self.runmetadata.samples:
if self.extension == 'fastq':
try:
status = sample.run.Description
if status == 'metagenome':
filelist.write(sample.general.combined + '\n')
reportlist.write(sample.general.combined.split('.')[0] + '\n')
except AttributeError:
pass
else:
if sample.general.combined != 'NA':
filelist.write(sample.general.combined + '\n')
reportlist.write(sample.general.combined.split('.')[0] + '\n') | [
"def",
"lists",
"(",
"self",
")",
":",
"# Prepare the lists to be used to classify the metagenomes",
"with",
"open",
"(",
"self",
".",
"filelist",
",",
"'w'",
")",
"as",
"filelist",
":",
"with",
"open",
"(",
"self",
".",
"reportlist",
",",
"'w'",
")",
"as",
"reportlist",
":",
"for",
"sample",
"in",
"self",
".",
"runmetadata",
".",
"samples",
":",
"if",
"self",
".",
"extension",
"==",
"'fastq'",
":",
"try",
":",
"status",
"=",
"sample",
".",
"run",
".",
"Description",
"if",
"status",
"==",
"'metagenome'",
":",
"filelist",
".",
"write",
"(",
"sample",
".",
"general",
".",
"combined",
"+",
"'\\n'",
")",
"reportlist",
".",
"write",
"(",
"sample",
".",
"general",
".",
"combined",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"+",
"'\\n'",
")",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"if",
"sample",
".",
"general",
".",
"combined",
"!=",
"'NA'",
":",
"filelist",
".",
"write",
"(",
"sample",
".",
"general",
".",
"combined",
"+",
"'\\n'",
")",
"reportlist",
".",
"write",
"(",
"sample",
".",
"general",
".",
"combined",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"+",
"'\\n'",
")"
]
| Prepare the list of files to be processed | [
"Prepare",
"the",
"list",
"of",
"files",
"to",
"be",
"processed"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/metagenomefilter/automateCLARK.py#L105-L124 | train |
lowandrew/OLCTools | metagenomefilter/automateCLARK.py | CLARK.estimateabundance | def estimateabundance(self):
"""
Estimate the abundance of taxonomic groups
"""
logging.info('Estimating abundance of taxonomic groups')
# Create and start threads
for i in range(self.cpus):
# Send the threads to the appropriate destination function
threads = Thread(target=self.estimate, args=())
# Set the daemon to true - something to do with thread management
threads.setDaemon(True)
# Start the threading
threads.start()
with progressbar(self.runmetadata.samples) as bar:
for sample in bar:
try:
if sample.general.combined != 'NA':
# Set the name of the abundance report
sample.general.abundance = sample.general.combined.split('.')[0] + '_abundance.csv'
# if not hasattr(sample, 'commands'):
if not sample.commands.datastore:
sample.commands = GenObject()
# Define system calls
sample.commands.target = self.targetcall
sample.commands.classify = self.classifycall
sample.commands.abundancecall = \
'cd {} && ./estimate_abundance.sh -D {} -F {} > {}'.format(self.clarkpath,
self.databasepath,
sample.general.classification,
sample.general.abundance)
self.abundancequeue.put(sample)
except KeyError:
pass
self.abundancequeue.join() | python | def estimateabundance(self):
"""
Estimate the abundance of taxonomic groups
"""
logging.info('Estimating abundance of taxonomic groups')
# Create and start threads
for i in range(self.cpus):
# Send the threads to the appropriate destination function
threads = Thread(target=self.estimate, args=())
# Set the daemon to true - something to do with thread management
threads.setDaemon(True)
# Start the threading
threads.start()
with progressbar(self.runmetadata.samples) as bar:
for sample in bar:
try:
if sample.general.combined != 'NA':
# Set the name of the abundance report
sample.general.abundance = sample.general.combined.split('.')[0] + '_abundance.csv'
# if not hasattr(sample, 'commands'):
if not sample.commands.datastore:
sample.commands = GenObject()
# Define system calls
sample.commands.target = self.targetcall
sample.commands.classify = self.classifycall
sample.commands.abundancecall = \
'cd {} && ./estimate_abundance.sh -D {} -F {} > {}'.format(self.clarkpath,
self.databasepath,
sample.general.classification,
sample.general.abundance)
self.abundancequeue.put(sample)
except KeyError:
pass
self.abundancequeue.join() | [
"def",
"estimateabundance",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Estimating abundance of taxonomic groups'",
")",
"# Create and start threads",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"cpus",
")",
":",
"# Send the threads to the appropriate destination function",
"threads",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"estimate",
",",
"args",
"=",
"(",
")",
")",
"# Set the daemon to true - something to do with thread management",
"threads",
".",
"setDaemon",
"(",
"True",
")",
"# Start the threading",
"threads",
".",
"start",
"(",
")",
"with",
"progressbar",
"(",
"self",
".",
"runmetadata",
".",
"samples",
")",
"as",
"bar",
":",
"for",
"sample",
"in",
"bar",
":",
"try",
":",
"if",
"sample",
".",
"general",
".",
"combined",
"!=",
"'NA'",
":",
"# Set the name of the abundance report",
"sample",
".",
"general",
".",
"abundance",
"=",
"sample",
".",
"general",
".",
"combined",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"+",
"'_abundance.csv'",
"# if not hasattr(sample, 'commands'):",
"if",
"not",
"sample",
".",
"commands",
".",
"datastore",
":",
"sample",
".",
"commands",
"=",
"GenObject",
"(",
")",
"# Define system calls",
"sample",
".",
"commands",
".",
"target",
"=",
"self",
".",
"targetcall",
"sample",
".",
"commands",
".",
"classify",
"=",
"self",
".",
"classifycall",
"sample",
".",
"commands",
".",
"abundancecall",
"=",
"'cd {} && ./estimate_abundance.sh -D {} -F {} > {}'",
".",
"format",
"(",
"self",
".",
"clarkpath",
",",
"self",
".",
"databasepath",
",",
"sample",
".",
"general",
".",
"classification",
",",
"sample",
".",
"general",
".",
"abundance",
")",
"self",
".",
"abundancequeue",
".",
"put",
"(",
"sample",
")",
"except",
"KeyError",
":",
"pass",
"self",
".",
"abundancequeue",
".",
"join",
"(",
")"
]
| Estimate the abundance of taxonomic groups | [
"Estimate",
"the",
"abundance",
"of",
"taxonomic",
"groups"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/metagenomefilter/automateCLARK.py#L126-L160 | train |
TorkamaniLab/metapipe | metapipe/models/command_template_factory.py | get_command_templates | def get_command_templates(command_tokens, file_tokens=[], path_tokens=[],
job_options=[]):
""" Given a list of tokens from the grammar, return a
list of commands.
"""
files = get_files(file_tokens)
paths = get_paths(path_tokens)
job_options = get_options(job_options)
templates = _get_command_templates(command_tokens, files, paths,
job_options)
for command_template in templates:
command_template._dependencies = _get_prelim_dependencies(
command_template, templates)
return templates | python | def get_command_templates(command_tokens, file_tokens=[], path_tokens=[],
job_options=[]):
""" Given a list of tokens from the grammar, return a
list of commands.
"""
files = get_files(file_tokens)
paths = get_paths(path_tokens)
job_options = get_options(job_options)
templates = _get_command_templates(command_tokens, files, paths,
job_options)
for command_template in templates:
command_template._dependencies = _get_prelim_dependencies(
command_template, templates)
return templates | [
"def",
"get_command_templates",
"(",
"command_tokens",
",",
"file_tokens",
"=",
"[",
"]",
",",
"path_tokens",
"=",
"[",
"]",
",",
"job_options",
"=",
"[",
"]",
")",
":",
"files",
"=",
"get_files",
"(",
"file_tokens",
")",
"paths",
"=",
"get_paths",
"(",
"path_tokens",
")",
"job_options",
"=",
"get_options",
"(",
"job_options",
")",
"templates",
"=",
"_get_command_templates",
"(",
"command_tokens",
",",
"files",
",",
"paths",
",",
"job_options",
")",
"for",
"command_template",
"in",
"templates",
":",
"command_template",
".",
"_dependencies",
"=",
"_get_prelim_dependencies",
"(",
"command_template",
",",
"templates",
")",
"return",
"templates"
]
| Given a list of tokens from the grammar, return a
list of commands. | [
"Given",
"a",
"list",
"of",
"tokens",
"from",
"the",
"grammar",
"return",
"a",
"list",
"of",
"commands",
"."
]
| 15592e5b0c217afb00ac03503f8d0d7453d4baf4 | https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/command_template_factory.py#L15-L30 | train |
TorkamaniLab/metapipe | metapipe/models/command_template_factory.py | get_files | def get_files(file_tokens, cwd=None):
""" Given a list of parser file tokens, return a list of input objects
for them.
"""
if not file_tokens:
return []
token = file_tokens.pop()
try:
filename = token.filename
except AttributeError:
filename = ''
if cwd:
input = Input(token.alias, filename, cwd=cwd)
else:
input = Input(token.alias, filename)
return [input] + get_files(file_tokens) | python | def get_files(file_tokens, cwd=None):
""" Given a list of parser file tokens, return a list of input objects
for them.
"""
if not file_tokens:
return []
token = file_tokens.pop()
try:
filename = token.filename
except AttributeError:
filename = ''
if cwd:
input = Input(token.alias, filename, cwd=cwd)
else:
input = Input(token.alias, filename)
return [input] + get_files(file_tokens) | [
"def",
"get_files",
"(",
"file_tokens",
",",
"cwd",
"=",
"None",
")",
":",
"if",
"not",
"file_tokens",
":",
"return",
"[",
"]",
"token",
"=",
"file_tokens",
".",
"pop",
"(",
")",
"try",
":",
"filename",
"=",
"token",
".",
"filename",
"except",
"AttributeError",
":",
"filename",
"=",
"''",
"if",
"cwd",
":",
"input",
"=",
"Input",
"(",
"token",
".",
"alias",
",",
"filename",
",",
"cwd",
"=",
"cwd",
")",
"else",
":",
"input",
"=",
"Input",
"(",
"token",
".",
"alias",
",",
"filename",
")",
"return",
"[",
"input",
"]",
"+",
"get_files",
"(",
"file_tokens",
")"
]
| Given a list of parser file tokens, return a list of input objects
for them. | [
"Given",
"a",
"list",
"of",
"parser",
"file",
"tokens",
"return",
"a",
"list",
"of",
"input",
"objects",
"for",
"them",
"."
]
| 15592e5b0c217afb00ac03503f8d0d7453d4baf4 | https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/command_template_factory.py#L33-L51 | train |
TorkamaniLab/metapipe | metapipe/models/command_template_factory.py | get_paths | def get_paths(path_tokens):
""" Given a list of parser path tokens, return a list of path objects
for them.
"""
if len(path_tokens) == 0:
return []
token = path_tokens.pop()
path = PathToken(token.alias, token.path)
return [path] + get_paths(path_tokens) | python | def get_paths(path_tokens):
""" Given a list of parser path tokens, return a list of path objects
for them.
"""
if len(path_tokens) == 0:
return []
token = path_tokens.pop()
path = PathToken(token.alias, token.path)
return [path] + get_paths(path_tokens) | [
"def",
"get_paths",
"(",
"path_tokens",
")",
":",
"if",
"len",
"(",
"path_tokens",
")",
"==",
"0",
":",
"return",
"[",
"]",
"token",
"=",
"path_tokens",
".",
"pop",
"(",
")",
"path",
"=",
"PathToken",
"(",
"token",
".",
"alias",
",",
"token",
".",
"path",
")",
"return",
"[",
"path",
"]",
"+",
"get_paths",
"(",
"path_tokens",
")"
]
| Given a list of parser path tokens, return a list of path objects
for them. | [
"Given",
"a",
"list",
"of",
"parser",
"path",
"tokens",
"return",
"a",
"list",
"of",
"path",
"objects",
"for",
"them",
"."
]
| 15592e5b0c217afb00ac03503f8d0d7453d4baf4 | https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/command_template_factory.py#L54-L63 | train |
TorkamaniLab/metapipe | metapipe/models/command_template_factory.py | _get_command_templates | def _get_command_templates(command_tokens, files=[], paths=[], job_options=[],
count=1):
""" Reversivly create command templates. """
if not command_tokens:
return []
comment_tokens, command_token = command_tokens.pop()
parts = []
parts += job_options + _get_comments(comment_tokens)
for part in command_token[0]:
# Check for file
try:
parts.append(_get_file_by_alias(part, files))
continue
except (AttributeError, ValueError):
pass
# Check for path/string
for cut in part.split():
try:
parts.append(_get_path_by_name(cut, paths))
continue
except ValueError:
pass
parts.append(cut)
command_template = CommandTemplate(alias=str(count), parts=parts)
[setattr(p, 'alias', command_template.alias)
for p in command_template.output_parts]
return [command_template] + _get_command_templates(command_tokens,
files, paths, job_options, count+1) | python | def _get_command_templates(command_tokens, files=[], paths=[], job_options=[],
count=1):
""" Reversivly create command templates. """
if not command_tokens:
return []
comment_tokens, command_token = command_tokens.pop()
parts = []
parts += job_options + _get_comments(comment_tokens)
for part in command_token[0]:
# Check for file
try:
parts.append(_get_file_by_alias(part, files))
continue
except (AttributeError, ValueError):
pass
# Check for path/string
for cut in part.split():
try:
parts.append(_get_path_by_name(cut, paths))
continue
except ValueError:
pass
parts.append(cut)
command_template = CommandTemplate(alias=str(count), parts=parts)
[setattr(p, 'alias', command_template.alias)
for p in command_template.output_parts]
return [command_template] + _get_command_templates(command_tokens,
files, paths, job_options, count+1) | [
"def",
"_get_command_templates",
"(",
"command_tokens",
",",
"files",
"=",
"[",
"]",
",",
"paths",
"=",
"[",
"]",
",",
"job_options",
"=",
"[",
"]",
",",
"count",
"=",
"1",
")",
":",
"if",
"not",
"command_tokens",
":",
"return",
"[",
"]",
"comment_tokens",
",",
"command_token",
"=",
"command_tokens",
".",
"pop",
"(",
")",
"parts",
"=",
"[",
"]",
"parts",
"+=",
"job_options",
"+",
"_get_comments",
"(",
"comment_tokens",
")",
"for",
"part",
"in",
"command_token",
"[",
"0",
"]",
":",
"# Check for file",
"try",
":",
"parts",
".",
"append",
"(",
"_get_file_by_alias",
"(",
"part",
",",
"files",
")",
")",
"continue",
"except",
"(",
"AttributeError",
",",
"ValueError",
")",
":",
"pass",
"# Check for path/string",
"for",
"cut",
"in",
"part",
".",
"split",
"(",
")",
":",
"try",
":",
"parts",
".",
"append",
"(",
"_get_path_by_name",
"(",
"cut",
",",
"paths",
")",
")",
"continue",
"except",
"ValueError",
":",
"pass",
"parts",
".",
"append",
"(",
"cut",
")",
"command_template",
"=",
"CommandTemplate",
"(",
"alias",
"=",
"str",
"(",
"count",
")",
",",
"parts",
"=",
"parts",
")",
"[",
"setattr",
"(",
"p",
",",
"'alias'",
",",
"command_template",
".",
"alias",
")",
"for",
"p",
"in",
"command_template",
".",
"output_parts",
"]",
"return",
"[",
"command_template",
"]",
"+",
"_get_command_templates",
"(",
"command_tokens",
",",
"files",
",",
"paths",
",",
"job_options",
",",
"count",
"+",
"1",
")"
]
| Reversivly create command templates. | [
"Reversivly",
"create",
"command",
"templates",
"."
]
| 15592e5b0c217afb00ac03503f8d0d7453d4baf4 | https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/command_template_factory.py#L74-L106 | train |
TorkamaniLab/metapipe | metapipe/models/command_template_factory.py | _get_prelim_dependencies | def _get_prelim_dependencies(command_template, all_templates):
""" Given a command_template determine which other templates it
depends on. This should not be used as the be-all end-all of
dependencies and before calling each command, ensure that it's
requirements are met.
"""
deps = []
for input in command_template.input_parts:
if '.' not in input.alias:
continue
for template in all_templates:
for output in template.output_parts:
if input.fuzzy_match(output):
deps.append(template)
break
return list(set(deps)) | python | def _get_prelim_dependencies(command_template, all_templates):
""" Given a command_template determine which other templates it
depends on. This should not be used as the be-all end-all of
dependencies and before calling each command, ensure that it's
requirements are met.
"""
deps = []
for input in command_template.input_parts:
if '.' not in input.alias:
continue
for template in all_templates:
for output in template.output_parts:
if input.fuzzy_match(output):
deps.append(template)
break
return list(set(deps)) | [
"def",
"_get_prelim_dependencies",
"(",
"command_template",
",",
"all_templates",
")",
":",
"deps",
"=",
"[",
"]",
"for",
"input",
"in",
"command_template",
".",
"input_parts",
":",
"if",
"'.'",
"not",
"in",
"input",
".",
"alias",
":",
"continue",
"for",
"template",
"in",
"all_templates",
":",
"for",
"output",
"in",
"template",
".",
"output_parts",
":",
"if",
"input",
".",
"fuzzy_match",
"(",
"output",
")",
":",
"deps",
".",
"append",
"(",
"template",
")",
"break",
"return",
"list",
"(",
"set",
"(",
"deps",
")",
")"
]
| Given a command_template determine which other templates it
depends on. This should not be used as the be-all end-all of
dependencies and before calling each command, ensure that it's
requirements are met. | [
"Given",
"a",
"command_template",
"determine",
"which",
"other",
"templates",
"it",
"depends",
"on",
".",
"This",
"should",
"not",
"be",
"used",
"as",
"the",
"be",
"-",
"all",
"end",
"-",
"all",
"of",
"dependencies",
"and",
"before",
"calling",
"each",
"command",
"ensure",
"that",
"it",
"s",
"requirements",
"are",
"met",
"."
]
| 15592e5b0c217afb00ac03503f8d0d7453d4baf4 | https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/command_template_factory.py#L109-L124 | train |
TorkamaniLab/metapipe | metapipe/models/command_template_factory.py | _is_output | def _is_output(part):
""" Returns whether the given part represents an output variable. """
if part[0].lower() == 'o':
return True
elif part[0][:2].lower() == 'o:':
return True
elif part[0][:2].lower() == 'o.':
return True
else:
return False | python | def _is_output(part):
""" Returns whether the given part represents an output variable. """
if part[0].lower() == 'o':
return True
elif part[0][:2].lower() == 'o:':
return True
elif part[0][:2].lower() == 'o.':
return True
else:
return False | [
"def",
"_is_output",
"(",
"part",
")",
":",
"if",
"part",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"==",
"'o'",
":",
"return",
"True",
"elif",
"part",
"[",
"0",
"]",
"[",
":",
"2",
"]",
".",
"lower",
"(",
")",
"==",
"'o:'",
":",
"return",
"True",
"elif",
"part",
"[",
"0",
"]",
"[",
":",
"2",
"]",
".",
"lower",
"(",
")",
"==",
"'o.'",
":",
"return",
"True",
"else",
":",
"return",
"False"
]
| Returns whether the given part represents an output variable. | [
"Returns",
"whether",
"the",
"given",
"part",
"represents",
"an",
"output",
"variable",
"."
]
| 15592e5b0c217afb00ac03503f8d0d7453d4baf4 | https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/command_template_factory.py#L182-L191 | train |
RedHatQE/Sentaku | examples/mini_example.py | search_browser | def search_browser(self, text):
"""do a slow search via the website and return the first match"""
self.impl.get(self.base_url)
search_div = self.impl.find_element_by_id("search")
search_term = search_div.find_element_by_id("term")
search_term.send_keys(text)
search_div.find_element_by_id("submit").click()
e = self.impl.find_element_by_css_selector("table.list tr td a")
return e.get_attribute("href") | python | def search_browser(self, text):
"""do a slow search via the website and return the first match"""
self.impl.get(self.base_url)
search_div = self.impl.find_element_by_id("search")
search_term = search_div.find_element_by_id("term")
search_term.send_keys(text)
search_div.find_element_by_id("submit").click()
e = self.impl.find_element_by_css_selector("table.list tr td a")
return e.get_attribute("href") | [
"def",
"search_browser",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"impl",
".",
"get",
"(",
"self",
".",
"base_url",
")",
"search_div",
"=",
"self",
".",
"impl",
".",
"find_element_by_id",
"(",
"\"search\"",
")",
"search_term",
"=",
"search_div",
".",
"find_element_by_id",
"(",
"\"term\"",
")",
"search_term",
".",
"send_keys",
"(",
"text",
")",
"search_div",
".",
"find_element_by_id",
"(",
"\"submit\"",
")",
".",
"click",
"(",
")",
"e",
"=",
"self",
".",
"impl",
".",
"find_element_by_css_selector",
"(",
"\"table.list tr td a\"",
")",
"return",
"e",
".",
"get_attribute",
"(",
"\"href\"",
")"
]
| do a slow search via the website and return the first match | [
"do",
"a",
"slow",
"search",
"via",
"the",
"website",
"and",
"return",
"the",
"first",
"match"
]
| b336cef5b6ee2db4e8dff28dcdb2be35a1f3d01c | https://github.com/RedHatQE/Sentaku/blob/b336cef5b6ee2db4e8dff28dcdb2be35a1f3d01c/examples/mini_example.py#L51-L60 | train |
RedHatQE/Sentaku | examples/mini_example.py | search_fast | def search_fast(self, text):
"""do a sloppy quick "search" via the json index"""
resp = self.impl.get(
"{base_url}/{text}/json".format(base_url=self.base_url, text=text)
)
return resp.json()["info"]["package_url"] | python | def search_fast(self, text):
"""do a sloppy quick "search" via the json index"""
resp = self.impl.get(
"{base_url}/{text}/json".format(base_url=self.base_url, text=text)
)
return resp.json()["info"]["package_url"] | [
"def",
"search_fast",
"(",
"self",
",",
"text",
")",
":",
"resp",
"=",
"self",
".",
"impl",
".",
"get",
"(",
"\"{base_url}/{text}/json\"",
".",
"format",
"(",
"base_url",
"=",
"self",
".",
"base_url",
",",
"text",
"=",
"text",
")",
")",
"return",
"resp",
".",
"json",
"(",
")",
"[",
"\"info\"",
"]",
"[",
"\"package_url\"",
"]"
]
| do a sloppy quick "search" via the json index | [
"do",
"a",
"sloppy",
"quick",
"search",
"via",
"the",
"json",
"index"
]
| b336cef5b6ee2db4e8dff28dcdb2be35a1f3d01c | https://github.com/RedHatQE/Sentaku/blob/b336cef5b6ee2db4e8dff28dcdb2be35a1f3d01c/examples/mini_example.py#L64-L70 | train |
RedHatQE/Sentaku | examples/mini_example.py | main | def main(search, query):
"""main function that does the search"""
url = search.search(query)
print(url)
search.open_page(url) | python | def main(search, query):
"""main function that does the search"""
url = search.search(query)
print(url)
search.open_page(url) | [
"def",
"main",
"(",
"search",
",",
"query",
")",
":",
"url",
"=",
"search",
".",
"search",
"(",
"query",
")",
"print",
"(",
"url",
")",
"search",
".",
"open_page",
"(",
"url",
")"
]
| main function that does the search | [
"main",
"function",
"that",
"does",
"the",
"search"
]
| b336cef5b6ee2db4e8dff28dcdb2be35a1f3d01c | https://github.com/RedHatQE/Sentaku/blob/b336cef5b6ee2db4e8dff28dcdb2be35a1f3d01c/examples/mini_example.py#L78-L82 | train |
RedHatQE/Sentaku | examples/mini_example.py | cli_main | def cli_main():
"""cli entrypoitns, sets up everything needed"""
SearchContext.commit()
args = parser.parse_args()
# open up a browser
firefox_remote = Remote("http://127.0.0.1:4444/wd/hub", DesiredCapabilities.FIREFOX)
with contextlib.closing(firefox_remote):
context = SearchContext.from_instances([FastSearch(), Browser(firefox_remote)])
search = Search(parent=context)
if args.fast:
with context.use(FastSearch, Browser):
main(search, args.query)
else:
with context.use(Browser):
main(search, args.query) | python | def cli_main():
"""cli entrypoitns, sets up everything needed"""
SearchContext.commit()
args = parser.parse_args()
# open up a browser
firefox_remote = Remote("http://127.0.0.1:4444/wd/hub", DesiredCapabilities.FIREFOX)
with contextlib.closing(firefox_remote):
context = SearchContext.from_instances([FastSearch(), Browser(firefox_remote)])
search = Search(parent=context)
if args.fast:
with context.use(FastSearch, Browser):
main(search, args.query)
else:
with context.use(Browser):
main(search, args.query) | [
"def",
"cli_main",
"(",
")",
":",
"SearchContext",
".",
"commit",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"# open up a browser",
"firefox_remote",
"=",
"Remote",
"(",
"\"http://127.0.0.1:4444/wd/hub\"",
",",
"DesiredCapabilities",
".",
"FIREFOX",
")",
"with",
"contextlib",
".",
"closing",
"(",
"firefox_remote",
")",
":",
"context",
"=",
"SearchContext",
".",
"from_instances",
"(",
"[",
"FastSearch",
"(",
")",
",",
"Browser",
"(",
"firefox_remote",
")",
"]",
")",
"search",
"=",
"Search",
"(",
"parent",
"=",
"context",
")",
"if",
"args",
".",
"fast",
":",
"with",
"context",
".",
"use",
"(",
"FastSearch",
",",
"Browser",
")",
":",
"main",
"(",
"search",
",",
"args",
".",
"query",
")",
"else",
":",
"with",
"context",
".",
"use",
"(",
"Browser",
")",
":",
"main",
"(",
"search",
",",
"args",
".",
"query",
")"
]
| cli entrypoitns, sets up everything needed | [
"cli",
"entrypoitns",
"sets",
"up",
"everything",
"needed"
]
| b336cef5b6ee2db4e8dff28dcdb2be35a1f3d01c | https://github.com/RedHatQE/Sentaku/blob/b336cef5b6ee2db4e8dff28dcdb2be35a1f3d01c/examples/mini_example.py#L85-L100 | train |
wylee/runcommands | runcommands/util/string.py | camel_to_underscore | def camel_to_underscore(name):
"""Convert camel case name to underscore name.
Examples::
>>> camel_to_underscore('HttpRequest')
'http_request'
>>> camel_to_underscore('httpRequest')
'http_request'
>>> camel_to_underscore('HTTPRequest')
'http_request'
>>> camel_to_underscore('myHTTPRequest')
'my_http_request'
>>> camel_to_underscore('MyHTTPRequest')
'my_http_request'
>>> camel_to_underscore('my_http_request')
'my_http_request'
>>> camel_to_underscore('MyHTTPRequestXYZ')
'my_http_request_xyz'
>>> camel_to_underscore('_HTTPRequest')
'_http_request'
>>> camel_to_underscore('Request')
'request'
>>> camel_to_underscore('REQUEST')
'request'
>>> camel_to_underscore('_Request')
'_request'
>>> camel_to_underscore('__Request')
'__request'
>>> camel_to_underscore('_request')
'_request'
>>> camel_to_underscore('Request_')
'request_'
"""
name = re.sub(r'(?<!\b)(?<!_)([A-Z][a-z])', r'_\1', name)
name = re.sub(r'(?<!\b)(?<!_)([a-z])([A-Z])', r'\1_\2', name)
name = name.lower()
return name | python | def camel_to_underscore(name):
"""Convert camel case name to underscore name.
Examples::
>>> camel_to_underscore('HttpRequest')
'http_request'
>>> camel_to_underscore('httpRequest')
'http_request'
>>> camel_to_underscore('HTTPRequest')
'http_request'
>>> camel_to_underscore('myHTTPRequest')
'my_http_request'
>>> camel_to_underscore('MyHTTPRequest')
'my_http_request'
>>> camel_to_underscore('my_http_request')
'my_http_request'
>>> camel_to_underscore('MyHTTPRequestXYZ')
'my_http_request_xyz'
>>> camel_to_underscore('_HTTPRequest')
'_http_request'
>>> camel_to_underscore('Request')
'request'
>>> camel_to_underscore('REQUEST')
'request'
>>> camel_to_underscore('_Request')
'_request'
>>> camel_to_underscore('__Request')
'__request'
>>> camel_to_underscore('_request')
'_request'
>>> camel_to_underscore('Request_')
'request_'
"""
name = re.sub(r'(?<!\b)(?<!_)([A-Z][a-z])', r'_\1', name)
name = re.sub(r'(?<!\b)(?<!_)([a-z])([A-Z])', r'\1_\2', name)
name = name.lower()
return name | [
"def",
"camel_to_underscore",
"(",
"name",
")",
":",
"name",
"=",
"re",
".",
"sub",
"(",
"r'(?<!\\b)(?<!_)([A-Z][a-z])'",
",",
"r'_\\1'",
",",
"name",
")",
"name",
"=",
"re",
".",
"sub",
"(",
"r'(?<!\\b)(?<!_)([a-z])([A-Z])'",
",",
"r'\\1_\\2'",
",",
"name",
")",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"return",
"name"
]
| Convert camel case name to underscore name.
Examples::
>>> camel_to_underscore('HttpRequest')
'http_request'
>>> camel_to_underscore('httpRequest')
'http_request'
>>> camel_to_underscore('HTTPRequest')
'http_request'
>>> camel_to_underscore('myHTTPRequest')
'my_http_request'
>>> camel_to_underscore('MyHTTPRequest')
'my_http_request'
>>> camel_to_underscore('my_http_request')
'my_http_request'
>>> camel_to_underscore('MyHTTPRequestXYZ')
'my_http_request_xyz'
>>> camel_to_underscore('_HTTPRequest')
'_http_request'
>>> camel_to_underscore('Request')
'request'
>>> camel_to_underscore('REQUEST')
'request'
>>> camel_to_underscore('_Request')
'_request'
>>> camel_to_underscore('__Request')
'__request'
>>> camel_to_underscore('_request')
'_request'
>>> camel_to_underscore('Request_')
'request_' | [
"Convert",
"camel",
"case",
"name",
"to",
"underscore",
"name",
"."
]
| b1d7c262885b9ced7ab89b63562f5464ca9970fe | https://github.com/wylee/runcommands/blob/b1d7c262885b9ced7ab89b63562f5464ca9970fe/runcommands/util/string.py#L4-L42 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/launcher.py | main_func | def main_func(args=None):
"""Main funcion when executing this module as script
:param args: commandline arguments
:type args: list
:returns: None
:rtype: None
:raises: None
"""
# we have to initialize a gui even if we dont need one right now.
# as soon as you call maya.standalone.initialize(), a QApplication
# with type Tty is created. This is the type for conosle apps.
# Because i have not found a way to replace that, we just init the gui.
guimain.init_gui()
main.init()
launcher = Launcher()
parsed, unknown = launcher.parse_args(args)
parsed.func(parsed, unknown) | python | def main_func(args=None):
"""Main funcion when executing this module as script
:param args: commandline arguments
:type args: list
:returns: None
:rtype: None
:raises: None
"""
# we have to initialize a gui even if we dont need one right now.
# as soon as you call maya.standalone.initialize(), a QApplication
# with type Tty is created. This is the type for conosle apps.
# Because i have not found a way to replace that, we just init the gui.
guimain.init_gui()
main.init()
launcher = Launcher()
parsed, unknown = launcher.parse_args(args)
parsed.func(parsed, unknown) | [
"def",
"main_func",
"(",
"args",
"=",
"None",
")",
":",
"# we have to initialize a gui even if we dont need one right now.",
"# as soon as you call maya.standalone.initialize(), a QApplication",
"# with type Tty is created. This is the type for conosle apps.",
"# Because i have not found a way to replace that, we just init the gui.",
"guimain",
".",
"init_gui",
"(",
")",
"main",
".",
"init",
"(",
")",
"launcher",
"=",
"Launcher",
"(",
")",
"parsed",
",",
"unknown",
"=",
"launcher",
".",
"parse_args",
"(",
"args",
")",
"parsed",
".",
"func",
"(",
"parsed",
",",
"unknown",
")"
]
| Main funcion when executing this module as script
:param args: commandline arguments
:type args: list
:returns: None
:rtype: None
:raises: None | [
"Main",
"funcion",
"when",
"executing",
"this",
"module",
"as",
"script"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/launcher.py#L143-L161 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/launcher.py | Launcher.setup_launch_parser | def setup_launch_parser(self, parser):
"""Setup the given parser for the launch command
:param parser: the argument parser to setup
:type parser: :class:`argparse.ArgumentParser`
:returns: None
:rtype: None
:raises: None
"""
parser.set_defaults(func=self.launch)
parser.add_argument("addon", help="The jukebox addon to launch. The addon should be a standalone plugin.") | python | def setup_launch_parser(self, parser):
"""Setup the given parser for the launch command
:param parser: the argument parser to setup
:type parser: :class:`argparse.ArgumentParser`
:returns: None
:rtype: None
:raises: None
"""
parser.set_defaults(func=self.launch)
parser.add_argument("addon", help="The jukebox addon to launch. The addon should be a standalone plugin.") | [
"def",
"setup_launch_parser",
"(",
"self",
",",
"parser",
")",
":",
"parser",
".",
"set_defaults",
"(",
"func",
"=",
"self",
".",
"launch",
")",
"parser",
".",
"add_argument",
"(",
"\"addon\"",
",",
"help",
"=",
"\"The jukebox addon to launch. The addon should be a standalone plugin.\"",
")"
]
| Setup the given parser for the launch command
:param parser: the argument parser to setup
:type parser: :class:`argparse.ArgumentParser`
:returns: None
:rtype: None
:raises: None | [
"Setup",
"the",
"given",
"parser",
"for",
"the",
"launch",
"command"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/launcher.py#L58-L68 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/launcher.py | Launcher.parse_args | def parse_args(self, args=None):
"""Parse the given arguments
All commands should support executing a function,
so you can use the arg Namespace like this::
launcher = Launcher()
args, unknown = launcher.parse_args()
args.func(args, unknown) # execute the command
:param args: arguments to pass
:type args:
:returns: the parsed arguments and all unknown arguments
:rtype: (Namespace, list)
:raises: None
"""
if args is None:
args = sys.argv[1:]
return self.parser.parse_known_args(args) | python | def parse_args(self, args=None):
"""Parse the given arguments
All commands should support executing a function,
so you can use the arg Namespace like this::
launcher = Launcher()
args, unknown = launcher.parse_args()
args.func(args, unknown) # execute the command
:param args: arguments to pass
:type args:
:returns: the parsed arguments and all unknown arguments
:rtype: (Namespace, list)
:raises: None
"""
if args is None:
args = sys.argv[1:]
return self.parser.parse_known_args(args) | [
"def",
"parse_args",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"return",
"self",
".",
"parser",
".",
"parse_known_args",
"(",
"args",
")"
]
| Parse the given arguments
All commands should support executing a function,
so you can use the arg Namespace like this::
launcher = Launcher()
args, unknown = launcher.parse_args()
args.func(args, unknown) # execute the command
:param args: arguments to pass
:type args:
:returns: the parsed arguments and all unknown arguments
:rtype: (Namespace, list)
:raises: None | [
"Parse",
"the",
"given",
"arguments"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/launcher.py#L122-L140 | train |
yamcs/yamcs-python | yamcs-client/yamcs/storage/model.py | Bucket.list_objects | def list_objects(self, prefix=None, delimiter=None):
"""
List the objects for this bucket.
:param str prefix: If specified, only objects that start with this
prefix are listed.
:param str delimiter: If specified, return only objects whose name
do not contain the delimiter after the prefix.
For the other objects, the response contains
(in the prefix response parameter) the name
truncated after the delimiter. Duplicates are
omitted.
"""
return self._client.list_objects(
instance=self._instance, bucket_name=self.name, prefix=prefix,
delimiter=delimiter) | python | def list_objects(self, prefix=None, delimiter=None):
"""
List the objects for this bucket.
:param str prefix: If specified, only objects that start with this
prefix are listed.
:param str delimiter: If specified, return only objects whose name
do not contain the delimiter after the prefix.
For the other objects, the response contains
(in the prefix response parameter) the name
truncated after the delimiter. Duplicates are
omitted.
"""
return self._client.list_objects(
instance=self._instance, bucket_name=self.name, prefix=prefix,
delimiter=delimiter) | [
"def",
"list_objects",
"(",
"self",
",",
"prefix",
"=",
"None",
",",
"delimiter",
"=",
"None",
")",
":",
"return",
"self",
".",
"_client",
".",
"list_objects",
"(",
"instance",
"=",
"self",
".",
"_instance",
",",
"bucket_name",
"=",
"self",
".",
"name",
",",
"prefix",
"=",
"prefix",
",",
"delimiter",
"=",
"delimiter",
")"
]
| List the objects for this bucket.
:param str prefix: If specified, only objects that start with this
prefix are listed.
:param str delimiter: If specified, return only objects whose name
do not contain the delimiter after the prefix.
For the other objects, the response contains
(in the prefix response parameter) the name
truncated after the delimiter. Duplicates are
omitted. | [
"List",
"the",
"objects",
"for",
"this",
"bucket",
"."
]
| 1082fee8a299010cc44416bbb7518fac0ef08b48 | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/storage/model.py#L26-L41 | train |
yamcs/yamcs-python | yamcs-client/yamcs/storage/model.py | Bucket.upload_object | def upload_object(self, object_name, file_obj):
"""
Upload an object to this bucket.
:param str object_name: The target name of the object.
:param file file_obj: The file (or file-like object) to upload.
:param str content_type: The content type associated to this object.
This is mainly useful when accessing an object
directly via a web browser. If unspecified, a
content type *may* be automatically derived
from the specified ``file_obj``.
"""
return self._client.upload_object(
self._instance, self.name, object_name, file_obj) | python | def upload_object(self, object_name, file_obj):
"""
Upload an object to this bucket.
:param str object_name: The target name of the object.
:param file file_obj: The file (or file-like object) to upload.
:param str content_type: The content type associated to this object.
This is mainly useful when accessing an object
directly via a web browser. If unspecified, a
content type *may* be automatically derived
from the specified ``file_obj``.
"""
return self._client.upload_object(
self._instance, self.name, object_name, file_obj) | [
"def",
"upload_object",
"(",
"self",
",",
"object_name",
",",
"file_obj",
")",
":",
"return",
"self",
".",
"_client",
".",
"upload_object",
"(",
"self",
".",
"_instance",
",",
"self",
".",
"name",
",",
"object_name",
",",
"file_obj",
")"
]
| Upload an object to this bucket.
:param str object_name: The target name of the object.
:param file file_obj: The file (or file-like object) to upload.
:param str content_type: The content type associated to this object.
This is mainly useful when accessing an object
directly via a web browser. If unspecified, a
content type *may* be automatically derived
from the specified ``file_obj``. | [
"Upload",
"an",
"object",
"to",
"this",
"bucket",
"."
]
| 1082fee8a299010cc44416bbb7518fac0ef08b48 | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/storage/model.py#L52-L65 | train |
yamcs/yamcs-python | yamcs-client/yamcs/storage/model.py | Bucket.delete_object | def delete_object(self, object_name):
"""
Remove an object from this bucket.
:param str object_name: The object to remove.
"""
self._client.remove_object(self._instance, self.name, object_name) | python | def delete_object(self, object_name):
"""
Remove an object from this bucket.
:param str object_name: The object to remove.
"""
self._client.remove_object(self._instance, self.name, object_name) | [
"def",
"delete_object",
"(",
"self",
",",
"object_name",
")",
":",
"self",
".",
"_client",
".",
"remove_object",
"(",
"self",
".",
"_instance",
",",
"self",
".",
"name",
",",
"object_name",
")"
]
| Remove an object from this bucket.
:param str object_name: The object to remove. | [
"Remove",
"an",
"object",
"from",
"this",
"bucket",
"."
]
| 1082fee8a299010cc44416bbb7518fac0ef08b48 | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/storage/model.py#L67-L73 | train |
yamcs/yamcs-python | yamcs-client/yamcs/storage/model.py | ObjectListing.objects | def objects(self):
"""
The objects in this listing.
:type: List[:class:`.ObjectInfo`]
"""
return [ObjectInfo(o, self._instance, self._bucket, self._client)
for o in self._proto.object] | python | def objects(self):
"""
The objects in this listing.
:type: List[:class:`.ObjectInfo`]
"""
return [ObjectInfo(o, self._instance, self._bucket, self._client)
for o in self._proto.object] | [
"def",
"objects",
"(",
"self",
")",
":",
"return",
"[",
"ObjectInfo",
"(",
"o",
",",
"self",
".",
"_instance",
",",
"self",
".",
"_bucket",
",",
"self",
".",
"_client",
")",
"for",
"o",
"in",
"self",
".",
"_proto",
".",
"object",
"]"
]
| The objects in this listing.
:type: List[:class:`.ObjectInfo`] | [
"The",
"objects",
"in",
"this",
"listing",
"."
]
| 1082fee8a299010cc44416bbb7518fac0ef08b48 | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/storage/model.py#L103-L110 | train |
yamcs/yamcs-python | yamcs-client/yamcs/storage/model.py | ObjectInfo.delete | def delete(self):
"""Remove this object."""
self._client.remove_object(self._instance, self._bucket, self.name) | python | def delete(self):
"""Remove this object."""
self._client.remove_object(self._instance, self._bucket, self.name) | [
"def",
"delete",
"(",
"self",
")",
":",
"self",
".",
"_client",
".",
"remove_object",
"(",
"self",
".",
"_instance",
",",
"self",
".",
"_bucket",
",",
"self",
".",
"name",
")"
]
| Remove this object. | [
"Remove",
"this",
"object",
"."
]
| 1082fee8a299010cc44416bbb7518fac0ef08b48 | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/storage/model.py#L142-L144 | train |
yamcs/yamcs-python | yamcs-client/yamcs/storage/model.py | ObjectInfo.download | def download(self):
"""Download this object."""
return self._client.download_object(
self._instance, self._bucket, self.name) | python | def download(self):
"""Download this object."""
return self._client.download_object(
self._instance, self._bucket, self.name) | [
"def",
"download",
"(",
"self",
")",
":",
"return",
"self",
".",
"_client",
".",
"download_object",
"(",
"self",
".",
"_instance",
",",
"self",
".",
"_bucket",
",",
"self",
".",
"name",
")"
]
| Download this object. | [
"Download",
"this",
"object",
"."
]
| 1082fee8a299010cc44416bbb7518fac0ef08b48 | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/storage/model.py#L146-L149 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.