repo
stringlengths 7
54
| path
stringlengths 4
192
| url
stringlengths 87
284
| code
stringlengths 78
104k
| code_tokens
sequence | docstring
stringlengths 1
46.9k
| docstring_tokens
sequence | language
stringclasses 1
value | partition
stringclasses 3
values |
---|---|---|---|---|---|---|---|---|
jjangsangy/py-translate | translate/translator.py | https://github.com/jjangsangy/py-translate/blob/fe6279b2ee353f42ce73333ffae104e646311956/translate/translator.py#L22-L57 | def push_url(interface):
'''
Decorates a function returning the url of translation API.
Creates and maintains HTTP connection state
Returns a dict response object from the server containing the translated
text and metadata of the request body
:param interface: Callable Request Interface
:type interface: Function
'''
@functools.wraps(interface)
def connection(*args, **kwargs):
"""
Extends and wraps a HTTP interface.
:return: Response Content
:rtype: Dictionary
"""
session = Session()
session.mount('http://', HTTPAdapter(max_retries=2))
session.mount('https://', HTTPAdapter(max_retries=2))
request = Request(**interface(*args, **kwargs))
prepare = session.prepare_request(request)
response = session.send(prepare, verify=True)
if response.status_code != requests.codes.ok:
response.raise_for_status()
cleanup = re.subn(r',(?=,)', '', response.content.decode('utf-8'))[0]
return json.loads(cleanup.replace(r'\xA0', r' ').replace('[,', '[1,'), encoding='UTF-8')
return connection | [
"def",
"push_url",
"(",
"interface",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"interface",
")",
"def",
"connection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Extends and wraps a HTTP interface.\n\n :return: Response Content\n :rtype: Dictionary\n \"\"\"",
"session",
"=",
"Session",
"(",
")",
"session",
".",
"mount",
"(",
"'http://'",
",",
"HTTPAdapter",
"(",
"max_retries",
"=",
"2",
")",
")",
"session",
".",
"mount",
"(",
"'https://'",
",",
"HTTPAdapter",
"(",
"max_retries",
"=",
"2",
")",
")",
"request",
"=",
"Request",
"(",
"*",
"*",
"interface",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"prepare",
"=",
"session",
".",
"prepare_request",
"(",
"request",
")",
"response",
"=",
"session",
".",
"send",
"(",
"prepare",
",",
"verify",
"=",
"True",
")",
"if",
"response",
".",
"status_code",
"!=",
"requests",
".",
"codes",
".",
"ok",
":",
"response",
".",
"raise_for_status",
"(",
")",
"cleanup",
"=",
"re",
".",
"subn",
"(",
"r',(?=,)'",
",",
"''",
",",
"response",
".",
"content",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"[",
"0",
"]",
"return",
"json",
".",
"loads",
"(",
"cleanup",
".",
"replace",
"(",
"r'\\xA0'",
",",
"r' '",
")",
".",
"replace",
"(",
"'[,'",
",",
"'[1,'",
")",
",",
"encoding",
"=",
"'UTF-8'",
")",
"return",
"connection"
] | Decorates a function returning the url of translation API.
Creates and maintains HTTP connection state
Returns a dict response object from the server containing the translated
text and metadata of the request body
:param interface: Callable Request Interface
:type interface: Function | [
"Decorates",
"a",
"function",
"returning",
"the",
"url",
"of",
"translation",
"API",
".",
"Creates",
"and",
"maintains",
"HTTP",
"connection",
"state"
] | python | test |
bkjones/pyrabbit | pyrabbit/api.py | https://github.com/bkjones/pyrabbit/blob/e8a9f74ed5c6bba958994fb9a72c396e6a99ea0f/pyrabbit/api.py#L794-L801 | def delete_user(self, username):
"""
Deletes a user from the server.
:param string username: Name of the user to delete from the server.
"""
path = Client.urls['users_by_name'] % username
return self._call(path, 'DELETE') | [
"def",
"delete_user",
"(",
"self",
",",
"username",
")",
":",
"path",
"=",
"Client",
".",
"urls",
"[",
"'users_by_name'",
"]",
"%",
"username",
"return",
"self",
".",
"_call",
"(",
"path",
",",
"'DELETE'",
")"
] | Deletes a user from the server.
:param string username: Name of the user to delete from the server. | [
"Deletes",
"a",
"user",
"from",
"the",
"server",
"."
] | python | train |
genialis/resolwe | resolwe/permissions/utils.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/utils.py#L100-L112 | def check_owner_permission(payload, allow_user_owner):
"""Raise ``PermissionDenied``if ``owner`` found in ``data``."""
for entity_type in ['users', 'groups']:
for perm_type in ['add', 'remove']:
for perms in payload.get(entity_type, {}).get(perm_type, {}).values():
if 'owner' in perms:
if entity_type == 'users' and allow_user_owner:
continue
if entity_type == 'groups':
raise exceptions.ParseError("Owner permission cannot be assigned to a group")
raise exceptions.PermissionDenied("Only owners can grant/revoke owner permission") | [
"def",
"check_owner_permission",
"(",
"payload",
",",
"allow_user_owner",
")",
":",
"for",
"entity_type",
"in",
"[",
"'users'",
",",
"'groups'",
"]",
":",
"for",
"perm_type",
"in",
"[",
"'add'",
",",
"'remove'",
"]",
":",
"for",
"perms",
"in",
"payload",
".",
"get",
"(",
"entity_type",
",",
"{",
"}",
")",
".",
"get",
"(",
"perm_type",
",",
"{",
"}",
")",
".",
"values",
"(",
")",
":",
"if",
"'owner'",
"in",
"perms",
":",
"if",
"entity_type",
"==",
"'users'",
"and",
"allow_user_owner",
":",
"continue",
"if",
"entity_type",
"==",
"'groups'",
":",
"raise",
"exceptions",
".",
"ParseError",
"(",
"\"Owner permission cannot be assigned to a group\"",
")",
"raise",
"exceptions",
".",
"PermissionDenied",
"(",
"\"Only owners can grant/revoke owner permission\"",
")"
] | Raise ``PermissionDenied``if ``owner`` found in ``data``. | [
"Raise",
"PermissionDenied",
"if",
"owner",
"found",
"in",
"data",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py#L146-L166 | def hide_routemap_holder_route_map_content_match_ipv6_route_source_ipv6_prefix_list_rmrs(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map = ET.SubElement(hide_routemap_holder, "route-map")
name_key = ET.SubElement(route_map, "name")
name_key.text = kwargs.pop('name')
action_rm_key = ET.SubElement(route_map, "action-rm")
action_rm_key.text = kwargs.pop('action_rm')
instance_key = ET.SubElement(route_map, "instance")
instance_key.text = kwargs.pop('instance')
content = ET.SubElement(route_map, "content")
match = ET.SubElement(content, "match")
ipv6 = ET.SubElement(match, "ipv6")
route_source = ET.SubElement(ipv6, "route-source")
ipv6_prefix_list_rmrs = ET.SubElement(route_source, "ipv6-prefix-list-rmrs")
ipv6_prefix_list_rmrs.text = kwargs.pop('ipv6_prefix_list_rmrs')
callback = kwargs.pop('callback', self._callback)
return callback(config) | [
"def",
"hide_routemap_holder_route_map_content_match_ipv6_route_source_ipv6_prefix_list_rmrs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_routemap_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"hide-routemap-holder\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:mgmt:brocade-ip-policy\"",
")",
"route_map",
"=",
"ET",
".",
"SubElement",
"(",
"hide_routemap_holder",
",",
"\"route-map\"",
")",
"name_key",
"=",
"ET",
".",
"SubElement",
"(",
"route_map",
",",
"\"name\"",
")",
"name_key",
".",
"text",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
")",
"action_rm_key",
"=",
"ET",
".",
"SubElement",
"(",
"route_map",
",",
"\"action-rm\"",
")",
"action_rm_key",
".",
"text",
"=",
"kwargs",
".",
"pop",
"(",
"'action_rm'",
")",
"instance_key",
"=",
"ET",
".",
"SubElement",
"(",
"route_map",
",",
"\"instance\"",
")",
"instance_key",
".",
"text",
"=",
"kwargs",
".",
"pop",
"(",
"'instance'",
")",
"content",
"=",
"ET",
".",
"SubElement",
"(",
"route_map",
",",
"\"content\"",
")",
"match",
"=",
"ET",
".",
"SubElement",
"(",
"content",
",",
"\"match\"",
")",
"ipv6",
"=",
"ET",
".",
"SubElement",
"(",
"match",
",",
"\"ipv6\"",
")",
"route_source",
"=",
"ET",
".",
"SubElement",
"(",
"ipv6",
",",
"\"route-source\"",
")",
"ipv6_prefix_list_rmrs",
"=",
"ET",
".",
"SubElement",
"(",
"route_source",
",",
"\"ipv6-prefix-list-rmrs\"",
")",
"ipv6_prefix_list_rmrs",
".",
"text",
"=",
"kwargs",
".",
"pop",
"(",
"'ipv6_prefix_list_rmrs'",
")",
"callback",
"=",
"kwargs",
".",
"pop",
"(",
"'callback'",
",",
"self",
".",
"_callback",
")",
"return",
"callback",
"(",
"config",
")"
] | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
stain/forgetSQL | lib/forgetSQL.py | https://github.com/stain/forgetSQL/blob/2e13f983020b121fd75a95fcafce3ea75573fb6b/lib/forgetSQL.py#L1001-L1122 | def generateFromTables(tables, cursor, getLinks=1, code=0):
"""Generates python code (or class objects if code is false)
based on SQL queries on the table names given in the list
tables.
code -- if given -- should be an dictionary containing these
keys to be inserted into generated code:
'database': database name
'module': database module name
'connect': string to be inserted into module.connect()
"""
curs = cursor()
forgetters = {}
class _Wrapper(forgetSQL.Forgetter):
_autosave = False
pass
_Wrapper.cursor = cursor
for table in tables:
# capitalize the table name to make it look like a class
name = table.capitalize()
# Define the class by instanciating the meta class to
# the given name (requires Forgetter to be new style)
forgetter = _Wrapper.__class__(name, (_Wrapper,), {})
# Register it
forgetters[name] = forgetter
forgetter._sqlTable = table
forgetter._sqlLinks = {}
forgetter._sqlFields = {}
forgetter._shortView = ()
forgetter._descriptions = {}
forgetter._userClasses = {}
# Get columns
curs.execute("SELECT * FROM %s LIMIT 1" % table)
columns = [column[0] for column in curs.description]
# convert to dictionary and register in forgetter
for column in columns:
forgetter._sqlFields[column] = column
if getLinks:
# Try to find links between tables (!)
# Note the big O factor with this ...
for (tableName, forgetter) in forgetters.items():
for (key, column) in forgetter._sqlFields.items():
# A column refering to another table would most likely
# be called otherColumnID or just otherColumn. We'll
# lowercase below when performing the test.
possTable = re.sub(r'_?id$', '', column)
# all tables (ie. one of the forgetters) are candidates
foundLink = False
for candidate in forgetters.keys():
if candidate.lower() == possTable.lower():
if possTable.lower() == tableName.lower():
# It's our own primary key!
forgetter._sqlPrimary = (column,)
break
# Woooh! First - let's replace 'blapp_id' with 'blapp'
# as the attribute name to indicate that it would
# contain the Blapp instance, not just
# some ID.
del forgetter._sqlFields[key]
forgetter._sqlFields[possTable] = column
# And.. we'll need to know which class we refer to
forgetter._userClasses[possTable] = candidate
break # we've found our candidate
if code:
if code['module'] == "MySQLdb":
code['class'] = 'forgetSQL.MysqlForgetter'
else:
code['class'] = 'forgetSQL.Forgetter'
code['date'] = time.strftime('%Y-%m-%d')
print '''
"""Database wrappers %(database)s
Autogenerated by forgetsql-generate %(date)s.
"""
import forgetSQL
#import %(module)s
class _Wrapper(%(class)s):
"""Just a simple wrapper class so that you may
easily change stuff for all forgetters. Typically
this involves subclassing MysqlForgetter instead."""
# Only save changes on .save()
_autosave = False
# Example database connection (might lack password)
#_dbModule = %(module)s
#_dbConnection = %(module)s.connect(%(connect)s)
#def cursor(cls):
# return cls._dbConnection.cursor()
#cursor = classmethod(cursor)
''' % code
items = forgetters.items()
items.sort()
for (name, forgetter) in items:
print "class %s(_Wrapper):" % name
for (key, value) in forgetter.__dict__.items():
if key.find('__') == 0:
continue
nice = pprint.pformat(value)
# Get some indention
nice = nice.replace('\n', '\n ' + ' '*len(key))
print ' %s = ' % key, nice
print ""
print '''
# Prepare them all. We need to send in our local
# namespace.
forgetSQL.prepareClasses(locals())
'''
else:
prepareClasses(forgetters)
return forgetters | [
"def",
"generateFromTables",
"(",
"tables",
",",
"cursor",
",",
"getLinks",
"=",
"1",
",",
"code",
"=",
"0",
")",
":",
"curs",
"=",
"cursor",
"(",
")",
"forgetters",
"=",
"{",
"}",
"class",
"_Wrapper",
"(",
"forgetSQL",
".",
"Forgetter",
")",
":",
"_autosave",
"=",
"False",
"pass",
"_Wrapper",
".",
"cursor",
"=",
"cursor",
"for",
"table",
"in",
"tables",
":",
"# capitalize the table name to make it look like a class",
"name",
"=",
"table",
".",
"capitalize",
"(",
")",
"# Define the class by instanciating the meta class to",
"# the given name (requires Forgetter to be new style)",
"forgetter",
"=",
"_Wrapper",
".",
"__class__",
"(",
"name",
",",
"(",
"_Wrapper",
",",
")",
",",
"{",
"}",
")",
"# Register it",
"forgetters",
"[",
"name",
"]",
"=",
"forgetter",
"forgetter",
".",
"_sqlTable",
"=",
"table",
"forgetter",
".",
"_sqlLinks",
"=",
"{",
"}",
"forgetter",
".",
"_sqlFields",
"=",
"{",
"}",
"forgetter",
".",
"_shortView",
"=",
"(",
")",
"forgetter",
".",
"_descriptions",
"=",
"{",
"}",
"forgetter",
".",
"_userClasses",
"=",
"{",
"}",
"# Get columns",
"curs",
".",
"execute",
"(",
"\"SELECT * FROM %s LIMIT 1\"",
"%",
"table",
")",
"columns",
"=",
"[",
"column",
"[",
"0",
"]",
"for",
"column",
"in",
"curs",
".",
"description",
"]",
"# convert to dictionary and register in forgetter",
"for",
"column",
"in",
"columns",
":",
"forgetter",
".",
"_sqlFields",
"[",
"column",
"]",
"=",
"column",
"if",
"getLinks",
":",
"# Try to find links between tables (!)",
"# Note the big O factor with this ...",
"for",
"(",
"tableName",
",",
"forgetter",
")",
"in",
"forgetters",
".",
"items",
"(",
")",
":",
"for",
"(",
"key",
",",
"column",
")",
"in",
"forgetter",
".",
"_sqlFields",
".",
"items",
"(",
")",
":",
"# A column refering to another table would most likely",
"# be called otherColumnID or just otherColumn. We'll",
"# lowercase below when performing the test.",
"possTable",
"=",
"re",
".",
"sub",
"(",
"r'_?id$'",
",",
"''",
",",
"column",
")",
"# all tables (ie. one of the forgetters) are candidates",
"foundLink",
"=",
"False",
"for",
"candidate",
"in",
"forgetters",
".",
"keys",
"(",
")",
":",
"if",
"candidate",
".",
"lower",
"(",
")",
"==",
"possTable",
".",
"lower",
"(",
")",
":",
"if",
"possTable",
".",
"lower",
"(",
")",
"==",
"tableName",
".",
"lower",
"(",
")",
":",
"# It's our own primary key!",
"forgetter",
".",
"_sqlPrimary",
"=",
"(",
"column",
",",
")",
"break",
"# Woooh! First - let's replace 'blapp_id' with 'blapp'",
"# as the attribute name to indicate that it would",
"# contain the Blapp instance, not just",
"# some ID.",
"del",
"forgetter",
".",
"_sqlFields",
"[",
"key",
"]",
"forgetter",
".",
"_sqlFields",
"[",
"possTable",
"]",
"=",
"column",
"# And.. we'll need to know which class we refer to",
"forgetter",
".",
"_userClasses",
"[",
"possTable",
"]",
"=",
"candidate",
"break",
"# we've found our candidate",
"if",
"code",
":",
"if",
"code",
"[",
"'module'",
"]",
"==",
"\"MySQLdb\"",
":",
"code",
"[",
"'class'",
"]",
"=",
"'forgetSQL.MysqlForgetter'",
"else",
":",
"code",
"[",
"'class'",
"]",
"=",
"'forgetSQL.Forgetter'",
"code",
"[",
"'date'",
"]",
"=",
"time",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"print",
"'''\n\"\"\"Database wrappers %(database)s\nAutogenerated by forgetsql-generate %(date)s.\n\"\"\"\n\nimport forgetSQL\n\n#import %(module)s\n\nclass _Wrapper(%(class)s):\n \"\"\"Just a simple wrapper class so that you may\n easily change stuff for all forgetters. Typically\n this involves subclassing MysqlForgetter instead.\"\"\"\n\n # Only save changes on .save()\n _autosave = False\n\n # Example database connection (might lack password)\n #_dbModule = %(module)s\n #_dbConnection = %(module)s.connect(%(connect)s)\n #def cursor(cls):\n # return cls._dbConnection.cursor()\n #cursor = classmethod(cursor)\n\n'''",
"%",
"code",
"items",
"=",
"forgetters",
".",
"items",
"(",
")",
"items",
".",
"sort",
"(",
")",
"for",
"(",
"name",
",",
"forgetter",
")",
"in",
"items",
":",
"print",
"\"class %s(_Wrapper):\"",
"%",
"name",
"for",
"(",
"key",
",",
"value",
")",
"in",
"forgetter",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"key",
".",
"find",
"(",
"'__'",
")",
"==",
"0",
":",
"continue",
"nice",
"=",
"pprint",
".",
"pformat",
"(",
"value",
")",
"# Get some indention",
"nice",
"=",
"nice",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n '",
"+",
"' '",
"*",
"len",
"(",
"key",
")",
")",
"print",
"' %s = '",
"%",
"key",
",",
"nice",
"print",
"\"\"",
"print",
"'''\n\n# Prepare them all. We need to send in our local\n# namespace.\nforgetSQL.prepareClasses(locals())\n'''",
"else",
":",
"prepareClasses",
"(",
"forgetters",
")",
"return",
"forgetters"
] | Generates python code (or class objects if code is false)
based on SQL queries on the table names given in the list
tables.
code -- if given -- should be an dictionary containing these
keys to be inserted into generated code:
'database': database name
'module': database module name
'connect': string to be inserted into module.connect() | [
"Generates",
"python",
"code",
"(",
"or",
"class",
"objects",
"if",
"code",
"is",
"false",
")",
"based",
"on",
"SQL",
"queries",
"on",
"the",
"table",
"names",
"given",
"in",
"the",
"list",
"tables",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L76-L93 | def _build_credentials(self, nexus_switches):
"""Build credential table for Rest API Client.
:param nexus_switches: switch config
:returns credentials: switch credentials list
"""
credentials = {}
for switch_ip, attrs in nexus_switches.items():
credentials[switch_ip] = (
attrs[const.USERNAME], attrs[const.PASSWORD],
attrs[const.HTTPS_VERIFY], attrs[const.HTTPS_CERT],
None)
if not attrs[const.HTTPS_VERIFY]:
LOG.warning("HTTPS Certificate verification is "
"disabled. Your connection to Nexus "
"Switch %(ip)s is insecure.",
{'ip': switch_ip})
return credentials | [
"def",
"_build_credentials",
"(",
"self",
",",
"nexus_switches",
")",
":",
"credentials",
"=",
"{",
"}",
"for",
"switch_ip",
",",
"attrs",
"in",
"nexus_switches",
".",
"items",
"(",
")",
":",
"credentials",
"[",
"switch_ip",
"]",
"=",
"(",
"attrs",
"[",
"const",
".",
"USERNAME",
"]",
",",
"attrs",
"[",
"const",
".",
"PASSWORD",
"]",
",",
"attrs",
"[",
"const",
".",
"HTTPS_VERIFY",
"]",
",",
"attrs",
"[",
"const",
".",
"HTTPS_CERT",
"]",
",",
"None",
")",
"if",
"not",
"attrs",
"[",
"const",
".",
"HTTPS_VERIFY",
"]",
":",
"LOG",
".",
"warning",
"(",
"\"HTTPS Certificate verification is \"",
"\"disabled. Your connection to Nexus \"",
"\"Switch %(ip)s is insecure.\"",
",",
"{",
"'ip'",
":",
"switch_ip",
"}",
")",
"return",
"credentials"
] | Build credential table for Rest API Client.
:param nexus_switches: switch config
:returns credentials: switch credentials list | [
"Build",
"credential",
"table",
"for",
"Rest",
"API",
"Client",
"."
] | python | train |
ccxt/ccxt | python/ccxt/base/exchange.py | https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L1000-L1006 | def check_address(self, address):
"""Checks an address is not the same character repeated or an empty sequence"""
if address is None:
self.raise_error(InvalidAddress, details='address is None')
if all(letter == address[0] for letter in address) or len(address) < self.minFundingAddressLength or ' ' in address:
self.raise_error(InvalidAddress, details='address is invalid or has less than ' + str(self.minFundingAddressLength) + ' characters: "' + str(address) + '"')
return address | [
"def",
"check_address",
"(",
"self",
",",
"address",
")",
":",
"if",
"address",
"is",
"None",
":",
"self",
".",
"raise_error",
"(",
"InvalidAddress",
",",
"details",
"=",
"'address is None'",
")",
"if",
"all",
"(",
"letter",
"==",
"address",
"[",
"0",
"]",
"for",
"letter",
"in",
"address",
")",
"or",
"len",
"(",
"address",
")",
"<",
"self",
".",
"minFundingAddressLength",
"or",
"' '",
"in",
"address",
":",
"self",
".",
"raise_error",
"(",
"InvalidAddress",
",",
"details",
"=",
"'address is invalid or has less than '",
"+",
"str",
"(",
"self",
".",
"minFundingAddressLength",
")",
"+",
"' characters: \"'",
"+",
"str",
"(",
"address",
")",
"+",
"'\"'",
")",
"return",
"address"
] | Checks an address is not the same character repeated or an empty sequence | [
"Checks",
"an",
"address",
"is",
"not",
"the",
"same",
"character",
"repeated",
"or",
"an",
"empty",
"sequence"
] | python | train |
cltrudeau/django-flowr | flowr/models.py | https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L585-L594 | def connect_child(self, child_node):
"""Adds a connection to an existing rule in the :class`Flow` graph.
The given :class`Rule` subclass must be allowed to be connected at
this stage of the flow according to the hierarchy of rules.
:param child_node:
``FlowNodeData`` to attach as a child
"""
self._child_allowed(child_node.rule)
self.node.connect_child(child_node.node) | [
"def",
"connect_child",
"(",
"self",
",",
"child_node",
")",
":",
"self",
".",
"_child_allowed",
"(",
"child_node",
".",
"rule",
")",
"self",
".",
"node",
".",
"connect_child",
"(",
"child_node",
".",
"node",
")"
] | Adds a connection to an existing rule in the :class`Flow` graph.
The given :class`Rule` subclass must be allowed to be connected at
this stage of the flow according to the hierarchy of rules.
:param child_node:
``FlowNodeData`` to attach as a child | [
"Adds",
"a",
"connection",
"to",
"an",
"existing",
"rule",
"in",
"the",
":",
"class",
"Flow",
"graph",
".",
"The",
"given",
":",
"class",
"Rule",
"subclass",
"must",
"be",
"allowed",
"to",
"be",
"connected",
"at",
"this",
"stage",
"of",
"the",
"flow",
"according",
"to",
"the",
"hierarchy",
"of",
"rules",
"."
] | python | valid |
xhtml2pdf/xhtml2pdf | xhtml2pdf/paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/paragraph.py#L458-L481 | def wrap(self, availWidth, availHeight):
"""
Determine the rectangle this paragraph really needs.
"""
# memorize available space
self.avWidth = availWidth
self.avHeight = availHeight
logger.debug("*** wrap (%f, %f)", availWidth, availHeight)
if not self.text:
logger.debug("*** wrap (%f, %f) needed", 0, 0)
return 0, 0
# Split lines
width = availWidth
self.splitIndex = self.text.splitIntoLines(width, availHeight)
self.width, self.height = availWidth, self.text.height
logger.debug("*** wrap (%f, %f) needed, splitIndex %r", self.width, self.height, self.splitIndex)
return self.width, self.height | [
"def",
"wrap",
"(",
"self",
",",
"availWidth",
",",
"availHeight",
")",
":",
"# memorize available space",
"self",
".",
"avWidth",
"=",
"availWidth",
"self",
".",
"avHeight",
"=",
"availHeight",
"logger",
".",
"debug",
"(",
"\"*** wrap (%f, %f)\"",
",",
"availWidth",
",",
"availHeight",
")",
"if",
"not",
"self",
".",
"text",
":",
"logger",
".",
"debug",
"(",
"\"*** wrap (%f, %f) needed\"",
",",
"0",
",",
"0",
")",
"return",
"0",
",",
"0",
"# Split lines",
"width",
"=",
"availWidth",
"self",
".",
"splitIndex",
"=",
"self",
".",
"text",
".",
"splitIntoLines",
"(",
"width",
",",
"availHeight",
")",
"self",
".",
"width",
",",
"self",
".",
"height",
"=",
"availWidth",
",",
"self",
".",
"text",
".",
"height",
"logger",
".",
"debug",
"(",
"\"*** wrap (%f, %f) needed, splitIndex %r\"",
",",
"self",
".",
"width",
",",
"self",
".",
"height",
",",
"self",
".",
"splitIndex",
")",
"return",
"self",
".",
"width",
",",
"self",
".",
"height"
] | Determine the rectangle this paragraph really needs. | [
"Determine",
"the",
"rectangle",
"this",
"paragraph",
"really",
"needs",
"."
] | python | train |
ShenggaoZhu/midict | midict/__init__.py | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L1275-L1280 | def iteritems(self, indices=None):
'Iterate through items in the ``indices`` (defaults to all indices)'
if indices is None:
indices = force_list(self.indices.keys())
for x in self.itervalues(indices):
yield x | [
"def",
"iteritems",
"(",
"self",
",",
"indices",
"=",
"None",
")",
":",
"if",
"indices",
"is",
"None",
":",
"indices",
"=",
"force_list",
"(",
"self",
".",
"indices",
".",
"keys",
"(",
")",
")",
"for",
"x",
"in",
"self",
".",
"itervalues",
"(",
"indices",
")",
":",
"yield",
"x"
] | Iterate through items in the ``indices`` (defaults to all indices) | [
"Iterate",
"through",
"items",
"in",
"the",
"indices",
"(",
"defaults",
"to",
"all",
"indices",
")"
] | python | train |
pixelogik/NearPy | nearpy/hashes/randombinaryprojectiontree.py | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/hashes/randombinaryprojectiontree.py#L191-L203 | def get_config(self):
"""
Returns pickle-serializable configuration struct for storage.
"""
# Fill this dict with config data
return {
'hash_name': self.hash_name,
'dim': self.dim,
'projection_count': self.projection_count,
'normals': self.normals,
'tree_root': self.tree_root,
'minimum_result_size': self.minimum_result_size
} | [
"def",
"get_config",
"(",
"self",
")",
":",
"# Fill this dict with config data",
"return",
"{",
"'hash_name'",
":",
"self",
".",
"hash_name",
",",
"'dim'",
":",
"self",
".",
"dim",
",",
"'projection_count'",
":",
"self",
".",
"projection_count",
",",
"'normals'",
":",
"self",
".",
"normals",
",",
"'tree_root'",
":",
"self",
".",
"tree_root",
",",
"'minimum_result_size'",
":",
"self",
".",
"minimum_result_size",
"}"
] | Returns pickle-serializable configuration struct for storage. | [
"Returns",
"pickle",
"-",
"serializable",
"configuration",
"struct",
"for",
"storage",
"."
] | python | train |
williballenthin/python-evtx | Evtx/Views.py | https://github.com/williballenthin/python-evtx/blob/4e9e29544adde64c79ff9b743269ecb18c677eb4/Evtx/Views.py#L98-L177 | def render_root_node_with_subs(root_node, subs):
"""
render the given root node using the given substitutions into XML.
Args:
root_node (e_nodes.RootNode): the node to render.
subs (list[str]): the substitutions that maybe included in the XML.
Returns:
str: the rendered XML document.
"""
def rec(node, acc):
if isinstance(node, e_nodes.EndOfStreamNode):
pass # intended
elif isinstance(node, e_nodes.OpenStartElementNode):
acc.append("<")
acc.append(node.tag_name())
for child in node.children():
if isinstance(child, e_nodes.AttributeNode):
acc.append(" ")
acc.append(validate_name(child.attribute_name().string()))
acc.append("=\"")
# TODO: should use xml.sax.saxutils.quoteattr here
# but to do so, we'd need to ensure we're not double-quoting this value.
rec(child.attribute_value(), acc)
acc.append("\"")
acc.append(">")
for child in node.children():
rec(child, acc)
acc.append("</")
acc.append(validate_name(node.tag_name()))
acc.append(">\n")
elif isinstance(node, e_nodes.CloseStartElementNode):
pass # intended
elif isinstance(node, e_nodes.CloseEmptyElementNode):
pass # intended
elif isinstance(node, e_nodes.CloseElementNode):
pass # intended
elif isinstance(node, e_nodes.ValueNode):
acc.append(escape_value(node.children()[0].string()))
elif isinstance(node, e_nodes.AttributeNode):
pass # intended
elif isinstance(node, e_nodes.CDataSectionNode):
acc.append("<![CDATA[")
# TODO: is this correct escaping???
acc.append(escape_value(node.cdata()))
acc.append("]]>")
elif isinstance(node, e_nodes.EntityReferenceNode):
acc.append(escape_value(node.entity_reference()))
elif isinstance(node, e_nodes.ProcessingInstructionTargetNode):
acc.append(escape_value(node.processing_instruction_target()))
elif isinstance(node, e_nodes.ProcessingInstructionDataNode):
acc.append(escape_value(node.string()))
elif isinstance(node, e_nodes.TemplateInstanceNode):
raise UnexpectedElementException("TemplateInstanceNode")
elif isinstance(node, e_nodes.NormalSubstitutionNode):
sub = subs[node.index()]
if isinstance(sub, e_nodes.BXmlTypeNode):
sub = render_root_node(sub.root())
else:
sub = escape_value(sub.string())
acc.append(sub)
elif isinstance(node, e_nodes.ConditionalSubstitutionNode):
sub = subs[node.index()]
if isinstance(sub, e_nodes.BXmlTypeNode):
sub = render_root_node(sub.root())
else:
sub = escape_value(sub.string())
acc.append(sub)
elif isinstance(node, e_nodes.StreamStartNode):
pass # intended
acc = []
for c in root_node.template().children():
rec(c, acc)
return "".join(acc) | [
"def",
"render_root_node_with_subs",
"(",
"root_node",
",",
"subs",
")",
":",
"def",
"rec",
"(",
"node",
",",
"acc",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"EndOfStreamNode",
")",
":",
"pass",
"# intended",
"elif",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"OpenStartElementNode",
")",
":",
"acc",
".",
"append",
"(",
"\"<\"",
")",
"acc",
".",
"append",
"(",
"node",
".",
"tag_name",
"(",
")",
")",
"for",
"child",
"in",
"node",
".",
"children",
"(",
")",
":",
"if",
"isinstance",
"(",
"child",
",",
"e_nodes",
".",
"AttributeNode",
")",
":",
"acc",
".",
"append",
"(",
"\" \"",
")",
"acc",
".",
"append",
"(",
"validate_name",
"(",
"child",
".",
"attribute_name",
"(",
")",
".",
"string",
"(",
")",
")",
")",
"acc",
".",
"append",
"(",
"\"=\\\"\"",
")",
"# TODO: should use xml.sax.saxutils.quoteattr here",
"# but to do so, we'd need to ensure we're not double-quoting this value.",
"rec",
"(",
"child",
".",
"attribute_value",
"(",
")",
",",
"acc",
")",
"acc",
".",
"append",
"(",
"\"\\\"\"",
")",
"acc",
".",
"append",
"(",
"\">\"",
")",
"for",
"child",
"in",
"node",
".",
"children",
"(",
")",
":",
"rec",
"(",
"child",
",",
"acc",
")",
"acc",
".",
"append",
"(",
"\"</\"",
")",
"acc",
".",
"append",
"(",
"validate_name",
"(",
"node",
".",
"tag_name",
"(",
")",
")",
")",
"acc",
".",
"append",
"(",
"\">\\n\"",
")",
"elif",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"CloseStartElementNode",
")",
":",
"pass",
"# intended",
"elif",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"CloseEmptyElementNode",
")",
":",
"pass",
"# intended",
"elif",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"CloseElementNode",
")",
":",
"pass",
"# intended",
"elif",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"ValueNode",
")",
":",
"acc",
".",
"append",
"(",
"escape_value",
"(",
"node",
".",
"children",
"(",
")",
"[",
"0",
"]",
".",
"string",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"AttributeNode",
")",
":",
"pass",
"# intended",
"elif",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"CDataSectionNode",
")",
":",
"acc",
".",
"append",
"(",
"\"<![CDATA[\"",
")",
"# TODO: is this correct escaping???",
"acc",
".",
"append",
"(",
"escape_value",
"(",
"node",
".",
"cdata",
"(",
")",
")",
")",
"acc",
".",
"append",
"(",
"\"]]>\"",
")",
"elif",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"EntityReferenceNode",
")",
":",
"acc",
".",
"append",
"(",
"escape_value",
"(",
"node",
".",
"entity_reference",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"ProcessingInstructionTargetNode",
")",
":",
"acc",
".",
"append",
"(",
"escape_value",
"(",
"node",
".",
"processing_instruction_target",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"ProcessingInstructionDataNode",
")",
":",
"acc",
".",
"append",
"(",
"escape_value",
"(",
"node",
".",
"string",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"TemplateInstanceNode",
")",
":",
"raise",
"UnexpectedElementException",
"(",
"\"TemplateInstanceNode\"",
")",
"elif",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"NormalSubstitutionNode",
")",
":",
"sub",
"=",
"subs",
"[",
"node",
".",
"index",
"(",
")",
"]",
"if",
"isinstance",
"(",
"sub",
",",
"e_nodes",
".",
"BXmlTypeNode",
")",
":",
"sub",
"=",
"render_root_node",
"(",
"sub",
".",
"root",
"(",
")",
")",
"else",
":",
"sub",
"=",
"escape_value",
"(",
"sub",
".",
"string",
"(",
")",
")",
"acc",
".",
"append",
"(",
"sub",
")",
"elif",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"ConditionalSubstitutionNode",
")",
":",
"sub",
"=",
"subs",
"[",
"node",
".",
"index",
"(",
")",
"]",
"if",
"isinstance",
"(",
"sub",
",",
"e_nodes",
".",
"BXmlTypeNode",
")",
":",
"sub",
"=",
"render_root_node",
"(",
"sub",
".",
"root",
"(",
")",
")",
"else",
":",
"sub",
"=",
"escape_value",
"(",
"sub",
".",
"string",
"(",
")",
")",
"acc",
".",
"append",
"(",
"sub",
")",
"elif",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"StreamStartNode",
")",
":",
"pass",
"# intended",
"acc",
"=",
"[",
"]",
"for",
"c",
"in",
"root_node",
".",
"template",
"(",
")",
".",
"children",
"(",
")",
":",
"rec",
"(",
"c",
",",
"acc",
")",
"return",
"\"\"",
".",
"join",
"(",
"acc",
")"
] | render the given root node using the given substitutions into XML.
Args:
root_node (e_nodes.RootNode): the node to render.
subs (list[str]): the substitutions that maybe included in the XML.
Returns:
str: the rendered XML document. | [
"render",
"the",
"given",
"root",
"node",
"using",
"the",
"given",
"substitutions",
"into",
"XML",
"."
] | python | train |
mozilla/treeherder | treeherder/webapp/api/note.py | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/webapp/api/note.py#L64-L74 | def destroy(self, request, project, pk=None):
"""
Delete a note entry
"""
try:
note = JobNote.objects.get(id=pk)
note.delete()
return Response({"message": "Note deleted"})
except JobNote.DoesNotExist:
return Response("No note with id: {0}".format(pk),
status=HTTP_404_NOT_FOUND) | [
"def",
"destroy",
"(",
"self",
",",
"request",
",",
"project",
",",
"pk",
"=",
"None",
")",
":",
"try",
":",
"note",
"=",
"JobNote",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"pk",
")",
"note",
".",
"delete",
"(",
")",
"return",
"Response",
"(",
"{",
"\"message\"",
":",
"\"Note deleted\"",
"}",
")",
"except",
"JobNote",
".",
"DoesNotExist",
":",
"return",
"Response",
"(",
"\"No note with id: {0}\"",
".",
"format",
"(",
"pk",
")",
",",
"status",
"=",
"HTTP_404_NOT_FOUND",
")"
] | Delete a note entry | [
"Delete",
"a",
"note",
"entry"
] | python | train |
SmartTeleMax/iktomi | iktomi/cli/base.py | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/cli/base.py#L14-L114 | def manage(commands, argv=None, delim=':'):
'''
Parses argv and runs neccessary command. Is to be used in manage.py file.
Accept a dict with digest name as keys and instances of
:class:`Cli<iktomi.management.commands.Cli>`
objects as values.
The format of command is the following::
./manage.py digest_name:command_name[ arg1[ arg2[...]]][ --key1=kwarg1[...]]
where command_name is a part of digest instance method name, args and kwargs
are passed to the method. For details, see
:class:`Cli<iktomi.management.commands.Cli>` docs.
'''
commands = {(k.decode('utf-8') if isinstance(k, six.binary_type) else k): v
for k, v in commands.items()}
# Default django autocompletion script is registered to manage.py
# We use the same name for this script and it seems to be ok
# to implement the same interface
def perform_auto_complete(commands):
from .lazy import LazyCli
cwords = os.environ['COMP_WORDS'].split()[1:]
cword = int(os.environ['COMP_CWORD'])
try:
curr = cwords[cword - 1]
except IndexError:
curr = ''
suggest = []
if len(cwords) > 1 and cwords[0] in commands.keys():
value = commands[cwords[0]]
if isinstance(value, LazyCli):
value = value.get_digest()
for cmd_name, _ in value.get_funcs():
cmd_name = cmd_name[8:]
suggest.append(cmd_name)
if curr == ":":
curr = ''
else:
suggest += list(commands.keys()) + [x+":" for x in commands.keys()]
suggest.sort()
output = u" ".join(filter(lambda x: x.startswith(curr), suggest))
sys.stdout.write(output)
auto_complete = 'IKTOMI_AUTO_COMPLETE' in os.environ or \
'DJANGO_AUTO_COMPLETE' in os.environ
if auto_complete:
perform_auto_complete(commands)
sys.exit(0)
argv = sys.argv if argv is None else argv
if len(argv) > 1:
cmd_name = argv[1]
raw_args = argv[2:]
args, kwargs = [], {}
# parsing params
for item in raw_args:
if item.startswith('--'):
splited = item[2:].split('=', 1)
if len(splited) == 2:
k,v = splited
elif len(splited) == 1:
k,v = splited[0], True
kwargs[k] = v
else:
args.append(item)
# trying to get command instance
if delim in cmd_name:
digest_name, command = cmd_name.split(delim)
else:
digest_name = cmd_name
command = None
try:
digest = commands[digest_name]
except KeyError:
_command_list(commands)
sys.exit('ERROR: Command "{}" not found'.format(digest_name))
try:
if command is None:
if isinstance(digest, Cli):
help_ = digest.description(argv[0], digest_name)
sys.stdout.write(help_)
sys.exit('ERROR: "{}" command digest requires command name'\
.format(digest_name))
digest(*args, **kwargs)
else:
digest(command, *args, **kwargs)
except CommandNotFound:
help_ = digest.description(argv[0], digest_name)
sys.stdout.write(help_)
sys.exit('ERROR: Command "{}:{}" not found'.format(digest_name, command))
else:
_command_list(commands)
sys.exit('Please provide any command') | [
"def",
"manage",
"(",
"commands",
",",
"argv",
"=",
"None",
",",
"delim",
"=",
"':'",
")",
":",
"commands",
"=",
"{",
"(",
"k",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"k",
",",
"six",
".",
"binary_type",
")",
"else",
"k",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"commands",
".",
"items",
"(",
")",
"}",
"# Default django autocompletion script is registered to manage.py",
"# We use the same name for this script and it seems to be ok",
"# to implement the same interface",
"def",
"perform_auto_complete",
"(",
"commands",
")",
":",
"from",
".",
"lazy",
"import",
"LazyCli",
"cwords",
"=",
"os",
".",
"environ",
"[",
"'COMP_WORDS'",
"]",
".",
"split",
"(",
")",
"[",
"1",
":",
"]",
"cword",
"=",
"int",
"(",
"os",
".",
"environ",
"[",
"'COMP_CWORD'",
"]",
")",
"try",
":",
"curr",
"=",
"cwords",
"[",
"cword",
"-",
"1",
"]",
"except",
"IndexError",
":",
"curr",
"=",
"''",
"suggest",
"=",
"[",
"]",
"if",
"len",
"(",
"cwords",
")",
">",
"1",
"and",
"cwords",
"[",
"0",
"]",
"in",
"commands",
".",
"keys",
"(",
")",
":",
"value",
"=",
"commands",
"[",
"cwords",
"[",
"0",
"]",
"]",
"if",
"isinstance",
"(",
"value",
",",
"LazyCli",
")",
":",
"value",
"=",
"value",
".",
"get_digest",
"(",
")",
"for",
"cmd_name",
",",
"_",
"in",
"value",
".",
"get_funcs",
"(",
")",
":",
"cmd_name",
"=",
"cmd_name",
"[",
"8",
":",
"]",
"suggest",
".",
"append",
"(",
"cmd_name",
")",
"if",
"curr",
"==",
"\":\"",
":",
"curr",
"=",
"''",
"else",
":",
"suggest",
"+=",
"list",
"(",
"commands",
".",
"keys",
"(",
")",
")",
"+",
"[",
"x",
"+",
"\":\"",
"for",
"x",
"in",
"commands",
".",
"keys",
"(",
")",
"]",
"suggest",
".",
"sort",
"(",
")",
"output",
"=",
"u\" \"",
".",
"join",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"startswith",
"(",
"curr",
")",
",",
"suggest",
")",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"output",
")",
"auto_complete",
"=",
"'IKTOMI_AUTO_COMPLETE'",
"in",
"os",
".",
"environ",
"or",
"'DJANGO_AUTO_COMPLETE'",
"in",
"os",
".",
"environ",
"if",
"auto_complete",
":",
"perform_auto_complete",
"(",
"commands",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"argv",
"=",
"sys",
".",
"argv",
"if",
"argv",
"is",
"None",
"else",
"argv",
"if",
"len",
"(",
"argv",
")",
">",
"1",
":",
"cmd_name",
"=",
"argv",
"[",
"1",
"]",
"raw_args",
"=",
"argv",
"[",
"2",
":",
"]",
"args",
",",
"kwargs",
"=",
"[",
"]",
",",
"{",
"}",
"# parsing params",
"for",
"item",
"in",
"raw_args",
":",
"if",
"item",
".",
"startswith",
"(",
"'--'",
")",
":",
"splited",
"=",
"item",
"[",
"2",
":",
"]",
".",
"split",
"(",
"'='",
",",
"1",
")",
"if",
"len",
"(",
"splited",
")",
"==",
"2",
":",
"k",
",",
"v",
"=",
"splited",
"elif",
"len",
"(",
"splited",
")",
"==",
"1",
":",
"k",
",",
"v",
"=",
"splited",
"[",
"0",
"]",
",",
"True",
"kwargs",
"[",
"k",
"]",
"=",
"v",
"else",
":",
"args",
".",
"append",
"(",
"item",
")",
"# trying to get command instance",
"if",
"delim",
"in",
"cmd_name",
":",
"digest_name",
",",
"command",
"=",
"cmd_name",
".",
"split",
"(",
"delim",
")",
"else",
":",
"digest_name",
"=",
"cmd_name",
"command",
"=",
"None",
"try",
":",
"digest",
"=",
"commands",
"[",
"digest_name",
"]",
"except",
"KeyError",
":",
"_command_list",
"(",
"commands",
")",
"sys",
".",
"exit",
"(",
"'ERROR: Command \"{}\" not found'",
".",
"format",
"(",
"digest_name",
")",
")",
"try",
":",
"if",
"command",
"is",
"None",
":",
"if",
"isinstance",
"(",
"digest",
",",
"Cli",
")",
":",
"help_",
"=",
"digest",
".",
"description",
"(",
"argv",
"[",
"0",
"]",
",",
"digest_name",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"help_",
")",
"sys",
".",
"exit",
"(",
"'ERROR: \"{}\" command digest requires command name'",
".",
"format",
"(",
"digest_name",
")",
")",
"digest",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"digest",
"(",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"CommandNotFound",
":",
"help_",
"=",
"digest",
".",
"description",
"(",
"argv",
"[",
"0",
"]",
",",
"digest_name",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"help_",
")",
"sys",
".",
"exit",
"(",
"'ERROR: Command \"{}:{}\" not found'",
".",
"format",
"(",
"digest_name",
",",
"command",
")",
")",
"else",
":",
"_command_list",
"(",
"commands",
")",
"sys",
".",
"exit",
"(",
"'Please provide any command'",
")"
] | Parses argv and runs neccessary command. Is to be used in manage.py file.
Accept a dict with digest name as keys and instances of
:class:`Cli<iktomi.management.commands.Cli>`
objects as values.
The format of command is the following::
./manage.py digest_name:command_name[ arg1[ arg2[...]]][ --key1=kwarg1[...]]
where command_name is a part of digest instance method name, args and kwargs
are passed to the method. For details, see
:class:`Cli<iktomi.management.commands.Cli>` docs. | [
"Parses",
"argv",
"and",
"runs",
"neccessary",
"command",
".",
"Is",
"to",
"be",
"used",
"in",
"manage",
".",
"py",
"file",
"."
] | python | train |
dswah/pyGAM | pygam/distributions.py | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/distributions.py#L535-L554 | def sample(self, mu):
"""
Return random samples from this Gamma distribution.
Parameters
----------
mu : array-like of shape n_samples or shape (n_simulations, n_samples)
expected values
Returns
-------
random_samples : np.array of same shape as mu
"""
# in numpy.random.gamma, `shape` is the parameter sometimes denoted by
# `k` that corresponds to `nu` in S. Wood (2006) Table 2.1
shape = 1. / self.scale
# in numpy.random.gamma, `scale` is the parameter sometimes denoted by
# `theta` that corresponds to mu / nu in S. Wood (2006) Table 2.1
scale = mu / shape
return np.random.gamma(shape=shape, scale=scale, size=None) | [
"def",
"sample",
"(",
"self",
",",
"mu",
")",
":",
"# in numpy.random.gamma, `shape` is the parameter sometimes denoted by",
"# `k` that corresponds to `nu` in S. Wood (2006) Table 2.1",
"shape",
"=",
"1.",
"/",
"self",
".",
"scale",
"# in numpy.random.gamma, `scale` is the parameter sometimes denoted by",
"# `theta` that corresponds to mu / nu in S. Wood (2006) Table 2.1",
"scale",
"=",
"mu",
"/",
"shape",
"return",
"np",
".",
"random",
".",
"gamma",
"(",
"shape",
"=",
"shape",
",",
"scale",
"=",
"scale",
",",
"size",
"=",
"None",
")"
] | Return random samples from this Gamma distribution.
Parameters
----------
mu : array-like of shape n_samples or shape (n_simulations, n_samples)
expected values
Returns
-------
random_samples : np.array of same shape as mu | [
"Return",
"random",
"samples",
"from",
"this",
"Gamma",
"distribution",
"."
] | python | train |
WoLpH/python-statsd | statsd/client.py | https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L88-L94 | def get_gauge(self, name=None):
'''Shortcut for getting a :class:`~statsd.gauge.Gauge` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str
'''
return self.get_client(name=name, class_=statsd.Gauge) | [
"def",
"get_gauge",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_client",
"(",
"name",
"=",
"name",
",",
"class_",
"=",
"statsd",
".",
"Gauge",
")"
] | Shortcut for getting a :class:`~statsd.gauge.Gauge` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str | [
"Shortcut",
"for",
"getting",
"a",
":",
"class",
":",
"~statsd",
".",
"gauge",
".",
"Gauge",
"instance"
] | python | train |
jim-easterbrook/pywws | src/pywws/conversions.py | https://github.com/jim-easterbrook/pywws/blob/4e4d74cee5a3ac5bf42286feaa251cd2ffcaf02c/src/pywws/conversions.py#L202-L210 | def cadhumidex(temp, humidity):
"Calculate Humidity Index as per Canadian Weather Standards"
if temp is None or humidity is None:
return None
# Formulas are adapted to not use e^(...) with no appreciable
# change in accuracy (0.0227%)
saturation_pressure = (6.112 * (10.0**(7.5 * temp / (237.7 + temp))) *
float(humidity) / 100.0)
return temp + (0.555 * (saturation_pressure - 10.0)) | [
"def",
"cadhumidex",
"(",
"temp",
",",
"humidity",
")",
":",
"if",
"temp",
"is",
"None",
"or",
"humidity",
"is",
"None",
":",
"return",
"None",
"# Formulas are adapted to not use e^(...) with no appreciable",
"# change in accuracy (0.0227%)",
"saturation_pressure",
"=",
"(",
"6.112",
"*",
"(",
"10.0",
"**",
"(",
"7.5",
"*",
"temp",
"/",
"(",
"237.7",
"+",
"temp",
")",
")",
")",
"*",
"float",
"(",
"humidity",
")",
"/",
"100.0",
")",
"return",
"temp",
"+",
"(",
"0.555",
"*",
"(",
"saturation_pressure",
"-",
"10.0",
")",
")"
] | Calculate Humidity Index as per Canadian Weather Standards | [
"Calculate",
"Humidity",
"Index",
"as",
"per",
"Canadian",
"Weather",
"Standards"
] | python | train |
allenai/allennlp | allennlp/data/vocabulary.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L270-L294 | def save_to_files(self, directory: str) -> None:
"""
Persist this Vocabulary to files so it can be reloaded later.
Each namespace corresponds to one file.
Parameters
----------
directory : ``str``
The directory where we save the serialized vocabulary.
"""
os.makedirs(directory, exist_ok=True)
if os.listdir(directory):
logging.warning("vocabulary serialization directory %s is not empty", directory)
with codecs.open(os.path.join(directory, NAMESPACE_PADDING_FILE), 'w', 'utf-8') as namespace_file:
for namespace_str in self._non_padded_namespaces:
print(namespace_str, file=namespace_file)
for namespace, mapping in self._index_to_token.items():
# Each namespace gets written to its own file, in index order.
with codecs.open(os.path.join(directory, namespace + '.txt'), 'w', 'utf-8') as token_file:
num_tokens = len(mapping)
start_index = 1 if mapping[0] == self._padding_token else 0
for i in range(start_index, num_tokens):
print(mapping[i].replace('\n', '@@NEWLINE@@'), file=token_file) | [
"def",
"save_to_files",
"(",
"self",
",",
"directory",
":",
"str",
")",
"->",
"None",
":",
"os",
".",
"makedirs",
"(",
"directory",
",",
"exist_ok",
"=",
"True",
")",
"if",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"logging",
".",
"warning",
"(",
"\"vocabulary serialization directory %s is not empty\"",
",",
"directory",
")",
"with",
"codecs",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"NAMESPACE_PADDING_FILE",
")",
",",
"'w'",
",",
"'utf-8'",
")",
"as",
"namespace_file",
":",
"for",
"namespace_str",
"in",
"self",
".",
"_non_padded_namespaces",
":",
"print",
"(",
"namespace_str",
",",
"file",
"=",
"namespace_file",
")",
"for",
"namespace",
",",
"mapping",
"in",
"self",
".",
"_index_to_token",
".",
"items",
"(",
")",
":",
"# Each namespace gets written to its own file, in index order.",
"with",
"codecs",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"namespace",
"+",
"'.txt'",
")",
",",
"'w'",
",",
"'utf-8'",
")",
"as",
"token_file",
":",
"num_tokens",
"=",
"len",
"(",
"mapping",
")",
"start_index",
"=",
"1",
"if",
"mapping",
"[",
"0",
"]",
"==",
"self",
".",
"_padding_token",
"else",
"0",
"for",
"i",
"in",
"range",
"(",
"start_index",
",",
"num_tokens",
")",
":",
"print",
"(",
"mapping",
"[",
"i",
"]",
".",
"replace",
"(",
"'\\n'",
",",
"'@@NEWLINE@@'",
")",
",",
"file",
"=",
"token_file",
")"
] | Persist this Vocabulary to files so it can be reloaded later.
Each namespace corresponds to one file.
Parameters
----------
directory : ``str``
The directory where we save the serialized vocabulary. | [
"Persist",
"this",
"Vocabulary",
"to",
"files",
"so",
"it",
"can",
"be",
"reloaded",
"later",
".",
"Each",
"namespace",
"corresponds",
"to",
"one",
"file",
"."
] | python | train |
Alignak-monitoring/alignak | alignak/objects/item.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1580-L1629 | def explode_host_groups_into_hosts(self, item, hosts, hostgroups):
"""
Get all hosts of hostgroups and add all in host_name container
:param item: the item object
:type item: alignak.objects.item.Item
:param hosts: hosts object
:type hosts: alignak.objects.host.Hosts
:param hostgroups: hostgroups object
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:return: None
"""
hnames_list = []
# Gets item's hostgroup_name
hgnames = getattr(item, "hostgroup_name", '') or ''
# Defines if hostgroup is a complex expression
# Expands hostgroups
if is_complex_expr(hgnames):
hnames_list.extend(self.evaluate_hostgroup_expression(
item.hostgroup_name, hosts, hostgroups))
elif hgnames:
try:
hnames_list.extend(
self.get_hosts_from_hostgroups(hgnames, hostgroups))
except ValueError as err: # pragma: no cover, simple protection
item.add_error(str(err))
# Expands host names
hname = getattr(item, "host_name", '')
hnames_list.extend([n.strip() for n in hname.split(',') if n.strip()])
hnames = set()
for host in hnames_list:
# If the host start with a !, it's to be removed from
# the hostgroup get list
if host.startswith('!'):
hst_to_remove = host[1:].strip()
try:
hnames.remove(hst_to_remove)
except KeyError:
pass
elif host == '*':
hnames.update([host.host_name for host
in hosts.items.values() if getattr(host, 'host_name', '')])
# Else it's a host to add, but maybe it's ALL
else:
hnames.add(host)
item.host_name = ','.join(hnames) | [
"def",
"explode_host_groups_into_hosts",
"(",
"self",
",",
"item",
",",
"hosts",
",",
"hostgroups",
")",
":",
"hnames_list",
"=",
"[",
"]",
"# Gets item's hostgroup_name",
"hgnames",
"=",
"getattr",
"(",
"item",
",",
"\"hostgroup_name\"",
",",
"''",
")",
"or",
"''",
"# Defines if hostgroup is a complex expression",
"# Expands hostgroups",
"if",
"is_complex_expr",
"(",
"hgnames",
")",
":",
"hnames_list",
".",
"extend",
"(",
"self",
".",
"evaluate_hostgroup_expression",
"(",
"item",
".",
"hostgroup_name",
",",
"hosts",
",",
"hostgroups",
")",
")",
"elif",
"hgnames",
":",
"try",
":",
"hnames_list",
".",
"extend",
"(",
"self",
".",
"get_hosts_from_hostgroups",
"(",
"hgnames",
",",
"hostgroups",
")",
")",
"except",
"ValueError",
"as",
"err",
":",
"# pragma: no cover, simple protection",
"item",
".",
"add_error",
"(",
"str",
"(",
"err",
")",
")",
"# Expands host names",
"hname",
"=",
"getattr",
"(",
"item",
",",
"\"host_name\"",
",",
"''",
")",
"hnames_list",
".",
"extend",
"(",
"[",
"n",
".",
"strip",
"(",
")",
"for",
"n",
"in",
"hname",
".",
"split",
"(",
"','",
")",
"if",
"n",
".",
"strip",
"(",
")",
"]",
")",
"hnames",
"=",
"set",
"(",
")",
"for",
"host",
"in",
"hnames_list",
":",
"# If the host start with a !, it's to be removed from",
"# the hostgroup get list",
"if",
"host",
".",
"startswith",
"(",
"'!'",
")",
":",
"hst_to_remove",
"=",
"host",
"[",
"1",
":",
"]",
".",
"strip",
"(",
")",
"try",
":",
"hnames",
".",
"remove",
"(",
"hst_to_remove",
")",
"except",
"KeyError",
":",
"pass",
"elif",
"host",
"==",
"'*'",
":",
"hnames",
".",
"update",
"(",
"[",
"host",
".",
"host_name",
"for",
"host",
"in",
"hosts",
".",
"items",
".",
"values",
"(",
")",
"if",
"getattr",
"(",
"host",
",",
"'host_name'",
",",
"''",
")",
"]",
")",
"# Else it's a host to add, but maybe it's ALL",
"else",
":",
"hnames",
".",
"add",
"(",
"host",
")",
"item",
".",
"host_name",
"=",
"','",
".",
"join",
"(",
"hnames",
")"
] | Get all hosts of hostgroups and add all in host_name container
:param item: the item object
:type item: alignak.objects.item.Item
:param hosts: hosts object
:type hosts: alignak.objects.host.Hosts
:param hostgroups: hostgroups object
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:return: None | [
"Get",
"all",
"hosts",
"of",
"hostgroups",
"and",
"add",
"all",
"in",
"host_name",
"container"
] | python | train |
PolyJIT/benchbuild | benchbuild/utils/user_interface.py | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/user_interface.py#L46-L84 | def ask(question, default_answer=False, default_answer_str="no"):
"""
Ask for user input.
This asks a yes/no question with a preset default.
You can bypass the user-input and fetch the default answer, if
you set
Args:
question: The question to ask on stdout.
default_answer: The default value to return.
default_answer_str:
The default answer string that we present to the user.
Tests:
>>> os.putenv("TEST", "yes"); ask("Test?", default_answer=True)
True
>>> os.putenv("TEST", "yes"); ask("Test?", default_answer=False)
False
"""
response = default_answer
def should_ignore_tty():
"""
Check, if we want to ignore an opened tty result.
"""
ret_to_bool = {"yes": True, "no": False, "true": True, "false": False}
envs = [os.getenv("CI", default="no"), os.getenv("TEST", default="no")]
vals = [ret_to_bool[val] for val in envs if val in ret_to_bool]
return any(vals)
ignore_stdin_istty = should_ignore_tty()
has_tty = sys.stdin.isatty() and not ignore_stdin_istty
if has_tty:
response = query_yes_no(question, default_answer_str)
else:
LOG.debug("NoTTY: %s -> %s", question, response)
return response | [
"def",
"ask",
"(",
"question",
",",
"default_answer",
"=",
"False",
",",
"default_answer_str",
"=",
"\"no\"",
")",
":",
"response",
"=",
"default_answer",
"def",
"should_ignore_tty",
"(",
")",
":",
"\"\"\"\n Check, if we want to ignore an opened tty result.\n \"\"\"",
"ret_to_bool",
"=",
"{",
"\"yes\"",
":",
"True",
",",
"\"no\"",
":",
"False",
",",
"\"true\"",
":",
"True",
",",
"\"false\"",
":",
"False",
"}",
"envs",
"=",
"[",
"os",
".",
"getenv",
"(",
"\"CI\"",
",",
"default",
"=",
"\"no\"",
")",
",",
"os",
".",
"getenv",
"(",
"\"TEST\"",
",",
"default",
"=",
"\"no\"",
")",
"]",
"vals",
"=",
"[",
"ret_to_bool",
"[",
"val",
"]",
"for",
"val",
"in",
"envs",
"if",
"val",
"in",
"ret_to_bool",
"]",
"return",
"any",
"(",
"vals",
")",
"ignore_stdin_istty",
"=",
"should_ignore_tty",
"(",
")",
"has_tty",
"=",
"sys",
".",
"stdin",
".",
"isatty",
"(",
")",
"and",
"not",
"ignore_stdin_istty",
"if",
"has_tty",
":",
"response",
"=",
"query_yes_no",
"(",
"question",
",",
"default_answer_str",
")",
"else",
":",
"LOG",
".",
"debug",
"(",
"\"NoTTY: %s -> %s\"",
",",
"question",
",",
"response",
")",
"return",
"response"
] | Ask for user input.
This asks a yes/no question with a preset default.
You can bypass the user-input and fetch the default answer, if
you set
Args:
question: The question to ask on stdout.
default_answer: The default value to return.
default_answer_str:
The default answer string that we present to the user.
Tests:
>>> os.putenv("TEST", "yes"); ask("Test?", default_answer=True)
True
>>> os.putenv("TEST", "yes"); ask("Test?", default_answer=False)
False | [
"Ask",
"for",
"user",
"input",
"."
] | python | train |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L485-L506 | def Normalize(self, fraction=1.0):
"""Normalizes this PMF so the sum of all probs is fraction.
Args:
fraction: what the total should be after normalization
Returns: the total probability before normalizing
"""
if self.log:
raise ValueError("Pmf is under a log transform")
total = self.Total()
if total == 0.0:
raise ValueError('total probability is zero.')
logging.warning('Normalize: total probability is zero.')
return total
factor = float(fraction) / total
for x in self.d:
self.d[x] *= factor
return total | [
"def",
"Normalize",
"(",
"self",
",",
"fraction",
"=",
"1.0",
")",
":",
"if",
"self",
".",
"log",
":",
"raise",
"ValueError",
"(",
"\"Pmf is under a log transform\"",
")",
"total",
"=",
"self",
".",
"Total",
"(",
")",
"if",
"total",
"==",
"0.0",
":",
"raise",
"ValueError",
"(",
"'total probability is zero.'",
")",
"logging",
".",
"warning",
"(",
"'Normalize: total probability is zero.'",
")",
"return",
"total",
"factor",
"=",
"float",
"(",
"fraction",
")",
"/",
"total",
"for",
"x",
"in",
"self",
".",
"d",
":",
"self",
".",
"d",
"[",
"x",
"]",
"*=",
"factor",
"return",
"total"
] | Normalizes this PMF so the sum of all probs is fraction.
Args:
fraction: what the total should be after normalization
Returns: the total probability before normalizing | [
"Normalizes",
"this",
"PMF",
"so",
"the",
"sum",
"of",
"all",
"probs",
"is",
"fraction",
"."
] | python | train |
saltstack/salt | salt/returners/multi_returner.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/multi_returner.py#L101-L109 | def get_jids():
'''
Return all job data from all returners
'''
ret = {}
for returner_ in __opts__[CONFIG_KEY]:
ret.update(_mminion().returners['{0}.get_jids'.format(returner_)]())
return ret | [
"def",
"get_jids",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"returner_",
"in",
"__opts__",
"[",
"CONFIG_KEY",
"]",
":",
"ret",
".",
"update",
"(",
"_mminion",
"(",
")",
".",
"returners",
"[",
"'{0}.get_jids'",
".",
"format",
"(",
"returner_",
")",
"]",
"(",
")",
")",
"return",
"ret"
] | Return all job data from all returners | [
"Return",
"all",
"job",
"data",
"from",
"all",
"returners"
] | python | train |
ghukill/pyfc4 | pyfc4/models.py | https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/models.py#L357-L387 | def keep_alive(self):
'''
Keep current transaction alive, updates self.expires
Args:
None
Return:
None: sets new self.expires
'''
# keep transaction alive
txn_response = self.api.http_request('POST','%sfcr:tx' % self.root, data=None, headers=None)
# if 204, transaction kept alive
if txn_response.status_code == 204:
logger.debug("continuing transaction: %s" % self.root)
# update status and timer
self.active = True
self.expires = txn_response.headers['Expires']
return True
# if 410, transaction does not exist
elif txn_response.status_code == 410:
logger.debug("transaction does not exist: %s" % self.root)
self.active = False
return False
else:
raise Exception('HTTP %s, could not continue transaction' % txn_response.status_code) | [
"def",
"keep_alive",
"(",
"self",
")",
":",
"# keep transaction alive",
"txn_response",
"=",
"self",
".",
"api",
".",
"http_request",
"(",
"'POST'",
",",
"'%sfcr:tx'",
"%",
"self",
".",
"root",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
")",
"# if 204, transaction kept alive",
"if",
"txn_response",
".",
"status_code",
"==",
"204",
":",
"logger",
".",
"debug",
"(",
"\"continuing transaction: %s\"",
"%",
"self",
".",
"root",
")",
"# update status and timer",
"self",
".",
"active",
"=",
"True",
"self",
".",
"expires",
"=",
"txn_response",
".",
"headers",
"[",
"'Expires'",
"]",
"return",
"True",
"# if 410, transaction does not exist",
"elif",
"txn_response",
".",
"status_code",
"==",
"410",
":",
"logger",
".",
"debug",
"(",
"\"transaction does not exist: %s\"",
"%",
"self",
".",
"root",
")",
"self",
".",
"active",
"=",
"False",
"return",
"False",
"else",
":",
"raise",
"Exception",
"(",
"'HTTP %s, could not continue transaction'",
"%",
"txn_response",
".",
"status_code",
")"
] | Keep current transaction alive, updates self.expires
Args:
None
Return:
None: sets new self.expires | [
"Keep",
"current",
"transaction",
"alive",
"updates",
"self",
".",
"expires"
] | python | train |
senaite/senaite.core | bika/lims/content/worksheet.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/worksheet.py#L1277-L1298 | def setMethod(self, method, override_analyses=False):
""" Sets the specified method to the Analyses from the
Worksheet. Only sets the method if the Analysis
allows to keep the integrity.
If an analysis has already been assigned to a method, it won't
be overriden.
Returns the number of analyses affected.
"""
analyses = [an for an in self.getAnalyses()
if (not an.getMethod() or
not an.getInstrument() or
override_analyses) and an.isMethodAllowed(method)]
total = 0
for an in analyses:
success = False
if an.isMethodAllowed(method):
success = an.setMethod(method)
if success is True:
total += 1
self.getField('Method').set(self, method)
return total | [
"def",
"setMethod",
"(",
"self",
",",
"method",
",",
"override_analyses",
"=",
"False",
")",
":",
"analyses",
"=",
"[",
"an",
"for",
"an",
"in",
"self",
".",
"getAnalyses",
"(",
")",
"if",
"(",
"not",
"an",
".",
"getMethod",
"(",
")",
"or",
"not",
"an",
".",
"getInstrument",
"(",
")",
"or",
"override_analyses",
")",
"and",
"an",
".",
"isMethodAllowed",
"(",
"method",
")",
"]",
"total",
"=",
"0",
"for",
"an",
"in",
"analyses",
":",
"success",
"=",
"False",
"if",
"an",
".",
"isMethodAllowed",
"(",
"method",
")",
":",
"success",
"=",
"an",
".",
"setMethod",
"(",
"method",
")",
"if",
"success",
"is",
"True",
":",
"total",
"+=",
"1",
"self",
".",
"getField",
"(",
"'Method'",
")",
".",
"set",
"(",
"self",
",",
"method",
")",
"return",
"total"
] | Sets the specified method to the Analyses from the
Worksheet. Only sets the method if the Analysis
allows to keep the integrity.
If an analysis has already been assigned to a method, it won't
be overriden.
Returns the number of analyses affected. | [
"Sets",
"the",
"specified",
"method",
"to",
"the",
"Analyses",
"from",
"the",
"Worksheet",
".",
"Only",
"sets",
"the",
"method",
"if",
"the",
"Analysis",
"allows",
"to",
"keep",
"the",
"integrity",
".",
"If",
"an",
"analysis",
"has",
"already",
"been",
"assigned",
"to",
"a",
"method",
"it",
"won",
"t",
"be",
"overriden",
".",
"Returns",
"the",
"number",
"of",
"analyses",
"affected",
"."
] | python | train |
whyscream/dspam-milter | dspam/client.py | https://github.com/whyscream/dspam-milter/blob/f9939b718eed02cb7e56f8c5b921db4cfe1cd85a/dspam/client.py#L295-L319 | def rcptto(self, recipients):
"""
Send LMTP RCPT TO command, and process the server response.
The DSPAM server expects to find one or more valid DSPAM users as
envelope recipients. The set recipient will be the user DSPAM
processes mail for.
When you need want DSPAM to deliver the message itself, and need to
pass the server an envelope recipient for this that differs from the
DSPAM user account name, use the --rcpt-to parameter in client_args
at mailfrom().
args:
recipients -- A list of recipients
"""
for rcpt in recipients:
self._send('RCPT TO:<{}>\r\n'.format(rcpt))
resp = self._read()
if not resp.startswith('250'):
raise DspamClientError(
'Unexpected server response at RCPT TO for '
'recipient {}: {}'.format(rcpt, resp))
self._recipients.append(rcpt) | [
"def",
"rcptto",
"(",
"self",
",",
"recipients",
")",
":",
"for",
"rcpt",
"in",
"recipients",
":",
"self",
".",
"_send",
"(",
"'RCPT TO:<{}>\\r\\n'",
".",
"format",
"(",
"rcpt",
")",
")",
"resp",
"=",
"self",
".",
"_read",
"(",
")",
"if",
"not",
"resp",
".",
"startswith",
"(",
"'250'",
")",
":",
"raise",
"DspamClientError",
"(",
"'Unexpected server response at RCPT TO for '",
"'recipient {}: {}'",
".",
"format",
"(",
"rcpt",
",",
"resp",
")",
")",
"self",
".",
"_recipients",
".",
"append",
"(",
"rcpt",
")"
] | Send LMTP RCPT TO command, and process the server response.
The DSPAM server expects to find one or more valid DSPAM users as
envelope recipients. The set recipient will be the user DSPAM
processes mail for.
When you need want DSPAM to deliver the message itself, and need to
pass the server an envelope recipient for this that differs from the
DSPAM user account name, use the --rcpt-to parameter in client_args
at mailfrom().
args:
recipients -- A list of recipients | [
"Send",
"LMTP",
"RCPT",
"TO",
"command",
"and",
"process",
"the",
"server",
"response",
"."
] | python | train |
agoragames/haigha | haigha/classes/basic_class.py | https://github.com/agoragames/haigha/blob/7b004e1c0316ec14b94fec1c54554654c38b1a25/haigha/classes/basic_class.py#L96-L106 | def qos(self, prefetch_size=0, prefetch_count=0, is_global=False):
'''
Set QoS on this channel.
'''
args = Writer()
args.write_long(prefetch_size).\
write_short(prefetch_count).\
write_bit(is_global)
self.send_frame(MethodFrame(self.channel_id, 60, 10, args))
self.channel.add_synchronous_cb(self._recv_qos_ok) | [
"def",
"qos",
"(",
"self",
",",
"prefetch_size",
"=",
"0",
",",
"prefetch_count",
"=",
"0",
",",
"is_global",
"=",
"False",
")",
":",
"args",
"=",
"Writer",
"(",
")",
"args",
".",
"write_long",
"(",
"prefetch_size",
")",
".",
"write_short",
"(",
"prefetch_count",
")",
".",
"write_bit",
"(",
"is_global",
")",
"self",
".",
"send_frame",
"(",
"MethodFrame",
"(",
"self",
".",
"channel_id",
",",
"60",
",",
"10",
",",
"args",
")",
")",
"self",
".",
"channel",
".",
"add_synchronous_cb",
"(",
"self",
".",
"_recv_qos_ok",
")"
] | Set QoS on this channel. | [
"Set",
"QoS",
"on",
"this",
"channel",
"."
] | python | train |
wuher/devil | devil/fields/fields.py | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/fields.py#L102-L128 | def clean(self, value):
""" Clean the data and validate the nested spec.
Implementation is the same as for other fields but in addition,
this will propagate the validation to the nested spec.
"""
obj = self.factory.create(value)
# todo: what if the field defines properties that have any of
# these names:
if obj:
del obj.fields
del obj.alias
del obj.validators
del obj.required
del obj.factory
# do own cleaning first...
self._validate_existence(obj)
self._run_validators(obj)
# ret = {}
# for name in self.fields.keys():
# ret[name] = getattr(obj, name)
# return ret
return obj | [
"def",
"clean",
"(",
"self",
",",
"value",
")",
":",
"obj",
"=",
"self",
".",
"factory",
".",
"create",
"(",
"value",
")",
"# todo: what if the field defines properties that have any of",
"# these names:",
"if",
"obj",
":",
"del",
"obj",
".",
"fields",
"del",
"obj",
".",
"alias",
"del",
"obj",
".",
"validators",
"del",
"obj",
".",
"required",
"del",
"obj",
".",
"factory",
"# do own cleaning first...",
"self",
".",
"_validate_existence",
"(",
"obj",
")",
"self",
".",
"_run_validators",
"(",
"obj",
")",
"# ret = {}",
"# for name in self.fields.keys():",
"# ret[name] = getattr(obj, name)",
"# return ret",
"return",
"obj"
] | Clean the data and validate the nested spec.
Implementation is the same as for other fields but in addition,
this will propagate the validation to the nested spec. | [
"Clean",
"the",
"data",
"and",
"validate",
"the",
"nested",
"spec",
"."
] | python | train |
benmack/eo-box | eobox/raster/rasterprocessing.py | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L252-L256 | def _process_window(self, ji_win, func, **kwargs):
"""Load (resampled) array of window ji_win and apply custom function on it. """
arr = self.get_arrays(ji_win)
result = func(arr, **kwargs)
return result | [
"def",
"_process_window",
"(",
"self",
",",
"ji_win",
",",
"func",
",",
"*",
"*",
"kwargs",
")",
":",
"arr",
"=",
"self",
".",
"get_arrays",
"(",
"ji_win",
")",
"result",
"=",
"func",
"(",
"arr",
",",
"*",
"*",
"kwargs",
")",
"return",
"result"
] | Load (resampled) array of window ji_win and apply custom function on it. | [
"Load",
"(",
"resampled",
")",
"array",
"of",
"window",
"ji_win",
"and",
"apply",
"custom",
"function",
"on",
"it",
"."
] | python | train |
sosy-lab/benchexec | benchexec/runexecutor.py | https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/runexecutor.py#L1186-L1192 | def _try_join_cancelled_thread(thread):
"""Join a thread, but if the thread doesn't terminate for some time, ignore it
instead of waiting infinitely."""
thread.join(10)
if thread.is_alive():
logging.warning("Thread %s did not terminate within grace period after cancellation",
thread.name) | [
"def",
"_try_join_cancelled_thread",
"(",
"thread",
")",
":",
"thread",
".",
"join",
"(",
"10",
")",
"if",
"thread",
".",
"is_alive",
"(",
")",
":",
"logging",
".",
"warning",
"(",
"\"Thread %s did not terminate within grace period after cancellation\"",
",",
"thread",
".",
"name",
")"
] | Join a thread, but if the thread doesn't terminate for some time, ignore it
instead of waiting infinitely. | [
"Join",
"a",
"thread",
"but",
"if",
"the",
"thread",
"doesn",
"t",
"terminate",
"for",
"some",
"time",
"ignore",
"it",
"instead",
"of",
"waiting",
"infinitely",
"."
] | python | train |
limpyd/redis-limpyd-jobs | limpyd_jobs/models.py | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/models.py#L125-L137 | def get_all_by_priority(cls, names):
"""
Return all the queues with the given names, sorted by priorities (higher
priority first), then by name
"""
names = cls._get_iterable_for_names(names)
queues = cls.get_all(names)
# sort all queues by priority
queues.sort(key=lambda q: int(q.priority.hget() or 0), reverse=True)
return queues | [
"def",
"get_all_by_priority",
"(",
"cls",
",",
"names",
")",
":",
"names",
"=",
"cls",
".",
"_get_iterable_for_names",
"(",
"names",
")",
"queues",
"=",
"cls",
".",
"get_all",
"(",
"names",
")",
"# sort all queues by priority",
"queues",
".",
"sort",
"(",
"key",
"=",
"lambda",
"q",
":",
"int",
"(",
"q",
".",
"priority",
".",
"hget",
"(",
")",
"or",
"0",
")",
",",
"reverse",
"=",
"True",
")",
"return",
"queues"
] | Return all the queues with the given names, sorted by priorities (higher
priority first), then by name | [
"Return",
"all",
"the",
"queues",
"with",
"the",
"given",
"names",
"sorted",
"by",
"priorities",
"(",
"higher",
"priority",
"first",
")",
"then",
"by",
"name"
] | python | train |
dev-pipeline/dev-pipeline-git | lib/devpipeline_git/git.py | https://github.com/dev-pipeline/dev-pipeline-git/blob/b604f1f89402502b8ad858f4f834baa9467ef380/lib/devpipeline_git/git.py#L118-L124 | def checkout(self, repo_dir, shared_dir, **kwargs):
"""This function checks out code from a Git SCM server."""
del kwargs
args = []
for checkout_fn in _CHECKOUT_ARG_BUILDERS:
args.extend(checkout_fn(shared_dir, repo_dir, self._args))
return args | [
"def",
"checkout",
"(",
"self",
",",
"repo_dir",
",",
"shared_dir",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"kwargs",
"args",
"=",
"[",
"]",
"for",
"checkout_fn",
"in",
"_CHECKOUT_ARG_BUILDERS",
":",
"args",
".",
"extend",
"(",
"checkout_fn",
"(",
"shared_dir",
",",
"repo_dir",
",",
"self",
".",
"_args",
")",
")",
"return",
"args"
] | This function checks out code from a Git SCM server. | [
"This",
"function",
"checks",
"out",
"code",
"from",
"a",
"Git",
"SCM",
"server",
"."
] | python | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L7146-L7163 | def insrtc(item, inset):
"""
Insert an item into a character set.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/insrtc_c.html
:param item: Item to be inserted.
:type item: str or list of str
:param inset: Insertion set.
:type inset: spiceypy.utils.support_types.SpiceCell
"""
assert isinstance(inset, stypes.SpiceCell)
if isinstance(item, list):
for c in item:
libspice.insrtc_c(stypes.stringToCharP(c), ctypes.byref(inset))
else:
item = stypes.stringToCharP(item)
libspice.insrtc_c(item, ctypes.byref(inset)) | [
"def",
"insrtc",
"(",
"item",
",",
"inset",
")",
":",
"assert",
"isinstance",
"(",
"inset",
",",
"stypes",
".",
"SpiceCell",
")",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"for",
"c",
"in",
"item",
":",
"libspice",
".",
"insrtc_c",
"(",
"stypes",
".",
"stringToCharP",
"(",
"c",
")",
",",
"ctypes",
".",
"byref",
"(",
"inset",
")",
")",
"else",
":",
"item",
"=",
"stypes",
".",
"stringToCharP",
"(",
"item",
")",
"libspice",
".",
"insrtc_c",
"(",
"item",
",",
"ctypes",
".",
"byref",
"(",
"inset",
")",
")"
] | Insert an item into a character set.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/insrtc_c.html
:param item: Item to be inserted.
:type item: str or list of str
:param inset: Insertion set.
:type inset: spiceypy.utils.support_types.SpiceCell | [
"Insert",
"an",
"item",
"into",
"a",
"character",
"set",
"."
] | python | train |
refenv/cijoe | modules/cij/reporter.py | https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/reporter.py#L138-L150 | def aux_listing(aux_root):
"""Listing"""
listing = []
for root, _, fnames in os.walk(aux_root):
count = len(aux_root.split(os.sep))
prefix = root.split(os.sep)[count:]
for fname in fnames:
listing.append(os.sep.join(prefix + [fname]))
return listing | [
"def",
"aux_listing",
"(",
"aux_root",
")",
":",
"listing",
"=",
"[",
"]",
"for",
"root",
",",
"_",
",",
"fnames",
"in",
"os",
".",
"walk",
"(",
"aux_root",
")",
":",
"count",
"=",
"len",
"(",
"aux_root",
".",
"split",
"(",
"os",
".",
"sep",
")",
")",
"prefix",
"=",
"root",
".",
"split",
"(",
"os",
".",
"sep",
")",
"[",
"count",
":",
"]",
"for",
"fname",
"in",
"fnames",
":",
"listing",
".",
"append",
"(",
"os",
".",
"sep",
".",
"join",
"(",
"prefix",
"+",
"[",
"fname",
"]",
")",
")",
"return",
"listing"
] | Listing | [
"Listing"
] | python | valid |
open-mmlab/mmcv | mmcv/runner/checkpoint.py | https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/runner/checkpoint.py#L157-L187 | def save_checkpoint(model, filename, optimizer=None, meta=None):
"""Save checkpoint to file.
The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
``optimizer``. By default ``meta`` will contain version and time info.
Args:
model (Module): Module whose params are to be saved.
filename (str): Checkpoint filename.
optimizer (:obj:`Optimizer`, optional): Optimizer to be saved.
meta (dict, optional): Metadata to be saved in checkpoint.
"""
if meta is None:
meta = {}
elif not isinstance(meta, dict):
raise TypeError('meta must be a dict or None, but got {}'.format(
type(meta)))
meta.update(mmcv_version=mmcv.__version__, time=time.asctime())
mmcv.mkdir_or_exist(osp.dirname(filename))
if hasattr(model, 'module'):
model = model.module
checkpoint = {
'meta': meta,
'state_dict': weights_to_cpu(model.state_dict())
}
if optimizer is not None:
checkpoint['optimizer'] = optimizer.state_dict()
torch.save(checkpoint, filename) | [
"def",
"save_checkpoint",
"(",
"model",
",",
"filename",
",",
"optimizer",
"=",
"None",
",",
"meta",
"=",
"None",
")",
":",
"if",
"meta",
"is",
"None",
":",
"meta",
"=",
"{",
"}",
"elif",
"not",
"isinstance",
"(",
"meta",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'meta must be a dict or None, but got {}'",
".",
"format",
"(",
"type",
"(",
"meta",
")",
")",
")",
"meta",
".",
"update",
"(",
"mmcv_version",
"=",
"mmcv",
".",
"__version__",
",",
"time",
"=",
"time",
".",
"asctime",
"(",
")",
")",
"mmcv",
".",
"mkdir_or_exist",
"(",
"osp",
".",
"dirname",
"(",
"filename",
")",
")",
"if",
"hasattr",
"(",
"model",
",",
"'module'",
")",
":",
"model",
"=",
"model",
".",
"module",
"checkpoint",
"=",
"{",
"'meta'",
":",
"meta",
",",
"'state_dict'",
":",
"weights_to_cpu",
"(",
"model",
".",
"state_dict",
"(",
")",
")",
"}",
"if",
"optimizer",
"is",
"not",
"None",
":",
"checkpoint",
"[",
"'optimizer'",
"]",
"=",
"optimizer",
".",
"state_dict",
"(",
")",
"torch",
".",
"save",
"(",
"checkpoint",
",",
"filename",
")"
] | Save checkpoint to file.
The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
``optimizer``. By default ``meta`` will contain version and time info.
Args:
model (Module): Module whose params are to be saved.
filename (str): Checkpoint filename.
optimizer (:obj:`Optimizer`, optional): Optimizer to be saved.
meta (dict, optional): Metadata to be saved in checkpoint. | [
"Save",
"checkpoint",
"to",
"file",
"."
] | python | test |
limodou/uliweb | uliweb/contrib/csrf/__init__.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/csrf/__init__.py#L31-L44 | def check_csrf_token():
"""
Check token
"""
from uliweb import request, settings
token = (request.params.get(settings.CSRF.form_token_name, None) or
request.headers.get("X-Xsrftoken") or
request.headers.get("X-Csrftoken"))
if not token:
raise Forbidden("CSRF token missing.")
if csrf_token() != token:
raise Forbidden("CSRF token dismatched.") | [
"def",
"check_csrf_token",
"(",
")",
":",
"from",
"uliweb",
"import",
"request",
",",
"settings",
"token",
"=",
"(",
"request",
".",
"params",
".",
"get",
"(",
"settings",
".",
"CSRF",
".",
"form_token_name",
",",
"None",
")",
"or",
"request",
".",
"headers",
".",
"get",
"(",
"\"X-Xsrftoken\"",
")",
"or",
"request",
".",
"headers",
".",
"get",
"(",
"\"X-Csrftoken\"",
")",
")",
"if",
"not",
"token",
":",
"raise",
"Forbidden",
"(",
"\"CSRF token missing.\"",
")",
"if",
"csrf_token",
"(",
")",
"!=",
"token",
":",
"raise",
"Forbidden",
"(",
"\"CSRF token dismatched.\"",
")"
] | Check token | [
"Check",
"token"
] | python | train |
nyergler/hieroglyph | src/hieroglyph/quickstart.py | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/quickstart.py#L16-L76 | def ask_user(d):
"""Wrap sphinx.quickstart.ask_user, and add additional questions."""
# Print welcome message
msg = bold('Welcome to the Hieroglyph %s quickstart utility.') % (
version(),
)
print(msg)
msg = """
This will ask questions for creating a Hieroglyph project, and then ask
some basic Sphinx questions.
"""
print(msg)
# set a few defaults that we don't usually care about for Hieroglyph
d.update({
'version': datetime.date.today().strftime('%Y.%m.%d'),
'release': datetime.date.today().strftime('%Y.%m.%d'),
'make_mode': True,
})
if 'project' not in d:
print('''
The presentation title will be included on the title slide.''')
sphinx.quickstart.do_prompt(d, 'project', 'Presentation title')
if 'author' not in d:
sphinx.quickstart.do_prompt(d, 'author', 'Author name(s)')
# slide_theme
theme_entrypoints = pkg_resources.iter_entry_points('hieroglyph.theme')
themes = [
t.load()
for t in theme_entrypoints
]
msg = """
Available themes:
"""
for theme in themes:
msg += '\n'.join([
bold(theme['name']),
theme['desc'],
'', '',
])
msg += """Which theme would you like to use?"""
print(msg)
sphinx.quickstart.do_prompt(
d, 'slide_theme', 'Slide Theme', themes[0]['name'],
sphinx.quickstart.choice(
*[t['name'] for t in themes]
),
)
# Ask original questions
print("")
sphinx.quickstart.ask_user(d) | [
"def",
"ask_user",
"(",
"d",
")",
":",
"# Print welcome message",
"msg",
"=",
"bold",
"(",
"'Welcome to the Hieroglyph %s quickstart utility.'",
")",
"%",
"(",
"version",
"(",
")",
",",
")",
"print",
"(",
"msg",
")",
"msg",
"=",
"\"\"\"\nThis will ask questions for creating a Hieroglyph project, and then ask\nsome basic Sphinx questions.\n\"\"\"",
"print",
"(",
"msg",
")",
"# set a few defaults that we don't usually care about for Hieroglyph",
"d",
".",
"update",
"(",
"{",
"'version'",
":",
"datetime",
".",
"date",
".",
"today",
"(",
")",
".",
"strftime",
"(",
"'%Y.%m.%d'",
")",
",",
"'release'",
":",
"datetime",
".",
"date",
".",
"today",
"(",
")",
".",
"strftime",
"(",
"'%Y.%m.%d'",
")",
",",
"'make_mode'",
":",
"True",
",",
"}",
")",
"if",
"'project'",
"not",
"in",
"d",
":",
"print",
"(",
"'''\nThe presentation title will be included on the title slide.'''",
")",
"sphinx",
".",
"quickstart",
".",
"do_prompt",
"(",
"d",
",",
"'project'",
",",
"'Presentation title'",
")",
"if",
"'author'",
"not",
"in",
"d",
":",
"sphinx",
".",
"quickstart",
".",
"do_prompt",
"(",
"d",
",",
"'author'",
",",
"'Author name(s)'",
")",
"# slide_theme",
"theme_entrypoints",
"=",
"pkg_resources",
".",
"iter_entry_points",
"(",
"'hieroglyph.theme'",
")",
"themes",
"=",
"[",
"t",
".",
"load",
"(",
")",
"for",
"t",
"in",
"theme_entrypoints",
"]",
"msg",
"=",
"\"\"\"\nAvailable themes:\n\n\"\"\"",
"for",
"theme",
"in",
"themes",
":",
"msg",
"+=",
"'\\n'",
".",
"join",
"(",
"[",
"bold",
"(",
"theme",
"[",
"'name'",
"]",
")",
",",
"theme",
"[",
"'desc'",
"]",
",",
"''",
",",
"''",
",",
"]",
")",
"msg",
"+=",
"\"\"\"Which theme would you like to use?\"\"\"",
"print",
"(",
"msg",
")",
"sphinx",
".",
"quickstart",
".",
"do_prompt",
"(",
"d",
",",
"'slide_theme'",
",",
"'Slide Theme'",
",",
"themes",
"[",
"0",
"]",
"[",
"'name'",
"]",
",",
"sphinx",
".",
"quickstart",
".",
"choice",
"(",
"*",
"[",
"t",
"[",
"'name'",
"]",
"for",
"t",
"in",
"themes",
"]",
")",
",",
")",
"# Ask original questions",
"print",
"(",
"\"\"",
")",
"sphinx",
".",
"quickstart",
".",
"ask_user",
"(",
"d",
")"
] | Wrap sphinx.quickstart.ask_user, and add additional questions. | [
"Wrap",
"sphinx",
".",
"quickstart",
".",
"ask_user",
"and",
"add",
"additional",
"questions",
"."
] | python | train |
pgxcentre/geneparse | geneparse/readers/vcf.py | https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/vcf.py#L102-L105 | def iter_variants(self):
"""Iterate over marker information."""
for v in self.get_vcf():
yield Variant(v.ID, v.CHROM, v.POS, {v.REF} | set(v.ALT)) | [
"def",
"iter_variants",
"(",
"self",
")",
":",
"for",
"v",
"in",
"self",
".",
"get_vcf",
"(",
")",
":",
"yield",
"Variant",
"(",
"v",
".",
"ID",
",",
"v",
".",
"CHROM",
",",
"v",
".",
"POS",
",",
"{",
"v",
".",
"REF",
"}",
"|",
"set",
"(",
"v",
".",
"ALT",
")",
")"
] | Iterate over marker information. | [
"Iterate",
"over",
"marker",
"information",
"."
] | python | train |
google/prettytensor | prettytensor/layers.py | https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/layers.py#L119-L144 | def xavier_init(n_inputs, n_outputs, uniform=True):
"""Set the parameter initialization using the method described.
This method is designed to keep the scale of the gradients roughly the same
in all layers.
Xavier Glorot and Yoshua Bengio (2010):
Understanding the difficulty of training deep feedforward neural
networks. International conference on artificial intelligence and
statistics.
Args:
n_inputs: The number of input nodes into each output.
n_outputs: The number of output nodes for each input.
uniform: If true use a uniform distribution, otherwise use a normal.
Returns:
An initializer.
"""
if uniform:
# 6 was used in the paper.
init_range = math.sqrt(6.0 / (n_inputs + n_outputs))
return tf.random_uniform_initializer(-init_range, init_range)
else:
# 3 gives us approximately the same limits as above since this repicks
# values greater than 2 standard deviations from the mean.
stddev = math.sqrt(3.0 / (n_inputs + n_outputs))
return tf.truncated_normal_initializer(stddev=stddev) | [
"def",
"xavier_init",
"(",
"n_inputs",
",",
"n_outputs",
",",
"uniform",
"=",
"True",
")",
":",
"if",
"uniform",
":",
"# 6 was used in the paper.",
"init_range",
"=",
"math",
".",
"sqrt",
"(",
"6.0",
"/",
"(",
"n_inputs",
"+",
"n_outputs",
")",
")",
"return",
"tf",
".",
"random_uniform_initializer",
"(",
"-",
"init_range",
",",
"init_range",
")",
"else",
":",
"# 3 gives us approximately the same limits as above since this repicks",
"# values greater than 2 standard deviations from the mean.",
"stddev",
"=",
"math",
".",
"sqrt",
"(",
"3.0",
"/",
"(",
"n_inputs",
"+",
"n_outputs",
")",
")",
"return",
"tf",
".",
"truncated_normal_initializer",
"(",
"stddev",
"=",
"stddev",
")"
] | Set the parameter initialization using the method described.
This method is designed to keep the scale of the gradients roughly the same
in all layers.
Xavier Glorot and Yoshua Bengio (2010):
Understanding the difficulty of training deep feedforward neural
networks. International conference on artificial intelligence and
statistics.
Args:
n_inputs: The number of input nodes into each output.
n_outputs: The number of output nodes for each input.
uniform: If true use a uniform distribution, otherwise use a normal.
Returns:
An initializer. | [
"Set",
"the",
"parameter",
"initialization",
"using",
"the",
"method",
"described",
"."
] | python | train |
pythongssapi/python-gssapi | gssapi/_utils.py | https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/_utils.py#L10-L30 | def import_gssapi_extension(name):
"""Import a GSSAPI extension module
This method imports a GSSAPI extension module based
on the name of the extension (not including the
'ext_' prefix). If the extension is not available,
the method retuns None.
Args:
name (str): the name of the extension
Returns:
module: Either the extension module or None
"""
try:
path = 'gssapi.raw.ext_{0}'.format(name)
__import__(path)
return sys.modules[path]
except ImportError:
return None | [
"def",
"import_gssapi_extension",
"(",
"name",
")",
":",
"try",
":",
"path",
"=",
"'gssapi.raw.ext_{0}'",
".",
"format",
"(",
"name",
")",
"__import__",
"(",
"path",
")",
"return",
"sys",
".",
"modules",
"[",
"path",
"]",
"except",
"ImportError",
":",
"return",
"None"
] | Import a GSSAPI extension module
This method imports a GSSAPI extension module based
on the name of the extension (not including the
'ext_' prefix). If the extension is not available,
the method retuns None.
Args:
name (str): the name of the extension
Returns:
module: Either the extension module or None | [
"Import",
"a",
"GSSAPI",
"extension",
"module"
] | python | train |
bitesofcode/projexui | projexui/widgets/xscintillaedit/xscintillaedit.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xscintillaedit/xscintillaedit.py#L448-L478 | def removeComments( self, comment = None ):
"""
Inserts comments into the editor based on the current selection.\
If no comment string is supplied, then the comment from the language \
will be used.
:param comment | <str> || None
:return <bool> | success
"""
if ( not comment ):
lang = self.language()
if ( lang ):
comment = lang.lineComment()
if ( not comment ):
return False
startline, startcol, endline, endcol = self.getSelection()
len_comment = len(comment)
line, col = self.getCursorPosition()
for lineno in range(startline, endline+1 ):
self.setSelection(lineno, 0, lineno, len_comment)
if ( self.selectedText() == comment ):
self.removeSelectedText()
self.setSelection(startline, startcol, endline, endcol)
self.setCursorPosition(line, col)
return True | [
"def",
"removeComments",
"(",
"self",
",",
"comment",
"=",
"None",
")",
":",
"if",
"(",
"not",
"comment",
")",
":",
"lang",
"=",
"self",
".",
"language",
"(",
")",
"if",
"(",
"lang",
")",
":",
"comment",
"=",
"lang",
".",
"lineComment",
"(",
")",
"if",
"(",
"not",
"comment",
")",
":",
"return",
"False",
"startline",
",",
"startcol",
",",
"endline",
",",
"endcol",
"=",
"self",
".",
"getSelection",
"(",
")",
"len_comment",
"=",
"len",
"(",
"comment",
")",
"line",
",",
"col",
"=",
"self",
".",
"getCursorPosition",
"(",
")",
"for",
"lineno",
"in",
"range",
"(",
"startline",
",",
"endline",
"+",
"1",
")",
":",
"self",
".",
"setSelection",
"(",
"lineno",
",",
"0",
",",
"lineno",
",",
"len_comment",
")",
"if",
"(",
"self",
".",
"selectedText",
"(",
")",
"==",
"comment",
")",
":",
"self",
".",
"removeSelectedText",
"(",
")",
"self",
".",
"setSelection",
"(",
"startline",
",",
"startcol",
",",
"endline",
",",
"endcol",
")",
"self",
".",
"setCursorPosition",
"(",
"line",
",",
"col",
")",
"return",
"True"
] | Inserts comments into the editor based on the current selection.\
If no comment string is supplied, then the comment from the language \
will be used.
:param comment | <str> || None
:return <bool> | success | [
"Inserts",
"comments",
"into",
"the",
"editor",
"based",
"on",
"the",
"current",
"selection",
".",
"\\",
"If",
"no",
"comment",
"string",
"is",
"supplied",
"then",
"the",
"comment",
"from",
"the",
"language",
"\\",
"will",
"be",
"used",
".",
":",
"param",
"comment",
"|",
"<str",
">",
"||",
"None",
":",
"return",
"<bool",
">",
"|",
"success"
] | python | train |
misli/django-cms-articles | cms_articles/models/managers.py | https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/models/managers.py#L95-L124 | def set_or_create(self, request, article, form, language):
"""
set or create a title for a particular article and language
"""
base_fields = [
'slug',
'title',
'description',
'meta_description',
'page_title',
'menu_title',
'image',
]
cleaned_data = form.cleaned_data
try:
obj = self.get(article=article, language=language)
except self.model.DoesNotExist:
data = {}
for name in base_fields:
if name in cleaned_data:
data[name] = cleaned_data[name]
data['article'] = article
data['language'] = language
return self.create(**data)
for name in base_fields:
if name in form.base_fields:
value = cleaned_data.get(name, None)
setattr(obj, name, value)
obj.save()
return obj | [
"def",
"set_or_create",
"(",
"self",
",",
"request",
",",
"article",
",",
"form",
",",
"language",
")",
":",
"base_fields",
"=",
"[",
"'slug'",
",",
"'title'",
",",
"'description'",
",",
"'meta_description'",
",",
"'page_title'",
",",
"'menu_title'",
",",
"'image'",
",",
"]",
"cleaned_data",
"=",
"form",
".",
"cleaned_data",
"try",
":",
"obj",
"=",
"self",
".",
"get",
"(",
"article",
"=",
"article",
",",
"language",
"=",
"language",
")",
"except",
"self",
".",
"model",
".",
"DoesNotExist",
":",
"data",
"=",
"{",
"}",
"for",
"name",
"in",
"base_fields",
":",
"if",
"name",
"in",
"cleaned_data",
":",
"data",
"[",
"name",
"]",
"=",
"cleaned_data",
"[",
"name",
"]",
"data",
"[",
"'article'",
"]",
"=",
"article",
"data",
"[",
"'language'",
"]",
"=",
"language",
"return",
"self",
".",
"create",
"(",
"*",
"*",
"data",
")",
"for",
"name",
"in",
"base_fields",
":",
"if",
"name",
"in",
"form",
".",
"base_fields",
":",
"value",
"=",
"cleaned_data",
".",
"get",
"(",
"name",
",",
"None",
")",
"setattr",
"(",
"obj",
",",
"name",
",",
"value",
")",
"obj",
".",
"save",
"(",
")",
"return",
"obj"
] | set or create a title for a particular article and language | [
"set",
"or",
"create",
"a",
"title",
"for",
"a",
"particular",
"article",
"and",
"language"
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/utils/optimize.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L281-L298 | def weight_decay(decay_rate, var_list, skip_biases=True):
"""Apply weight decay to vars in var_list."""
if not decay_rate:
return 0.
tf.logging.info("Applying weight decay, decay_rate: %0.5f", decay_rate)
weight_decays = []
for v in var_list:
# Weight decay.
# This is a heuristic way to detect biases that works for main tf.layers.
is_bias = len(v.shape.as_list()) == 1 and v.name.endswith("bias:0")
if not (skip_biases and is_bias):
with tf.device(v.device):
v_loss = tf.nn.l2_loss(v)
weight_decays.append(v_loss)
return tf.add_n(weight_decays) * decay_rate | [
"def",
"weight_decay",
"(",
"decay_rate",
",",
"var_list",
",",
"skip_biases",
"=",
"True",
")",
":",
"if",
"not",
"decay_rate",
":",
"return",
"0.",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Applying weight decay, decay_rate: %0.5f\"",
",",
"decay_rate",
")",
"weight_decays",
"=",
"[",
"]",
"for",
"v",
"in",
"var_list",
":",
"# Weight decay.",
"# This is a heuristic way to detect biases that works for main tf.layers.",
"is_bias",
"=",
"len",
"(",
"v",
".",
"shape",
".",
"as_list",
"(",
")",
")",
"==",
"1",
"and",
"v",
".",
"name",
".",
"endswith",
"(",
"\"bias:0\"",
")",
"if",
"not",
"(",
"skip_biases",
"and",
"is_bias",
")",
":",
"with",
"tf",
".",
"device",
"(",
"v",
".",
"device",
")",
":",
"v_loss",
"=",
"tf",
".",
"nn",
".",
"l2_loss",
"(",
"v",
")",
"weight_decays",
".",
"append",
"(",
"v_loss",
")",
"return",
"tf",
".",
"add_n",
"(",
"weight_decays",
")",
"*",
"decay_rate"
] | Apply weight decay to vars in var_list. | [
"Apply",
"weight",
"decay",
"to",
"vars",
"in",
"var_list",
"."
] | python | train |
T-002/pycast | pycast/common/matrix.py | https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/matrix.py#L530-L590 | def gauss_jordan(self):
"""Reduce :py:obj:`self` to row echelon form.
:return: Returns :py:obj:`self` in row echelon form for convenience.
:rtype: Matrix
:raise: Raises an :py:exc:`ValueError` if:
- the matrix rows < columns
- the matrix is not invertible
In this case :py:obj:`self` is not changed.
"""
mArray = self.get_array(rowBased=False)
width = self.get_width()
height = self.get_height()
if not height < width:
raise ValueError("""Not enough rows""")
# Start with complete matrix and remove in each iteration
# the first row and the first column
for offset in xrange(height):
# Switch lines, if current first value is 0
if mArray[offset][offset] == 0:
for i in xrange(offset + 1, height):
if mArray[offset][i] != 0:
tmp = []
for j in xrange(offset, width):
tmp.append(mArray[j][offset])
# tmp = mArray[offset][offset:]
for j in xrange(offset, width):
mArray[j][offset] = mArray[j][i]
mArray[j][i] = tmp[j]
# mArray[offset][offset:] = mArray[i][offset:]
# mArray[i] = tmp
break
currentRow = [mArray[j][offset] for j in xrange(offset, width)]
devider = float(currentRow[0])
# If no line is found with an value != 0
# the matrix is not invertible
if devider == 0:
raise ValueError("Matrix is not invertible")
transformedRow = []
# Devide current row by first element of current row
for value in currentRow:
transformedRow.append(value / devider)
# put transformed row back into matrix
for j in xrange(offset, width):
mArray[j][offset] = transformedRow[j - offset]
# subtract multiples of the current row, from all remaining rows
# in order to become a 0 at the current first column
for i in xrange(offset + 1, height):
multi = mArray[offset][i]
for j in xrange(offset, width):
mArray[j][i] = mArray[j][i] - mArray[j][offset] * multi
for i in xrange(1, height):
# subtract multiples of the i-the row from all above rows
for j in xrange(0, i):
multi = mArray[i][j]
for col in xrange(i, width):
mArray[col][j] = mArray[col][j] - mArray[col][i] * multi
self.matrix = mArray
return self | [
"def",
"gauss_jordan",
"(",
"self",
")",
":",
"mArray",
"=",
"self",
".",
"get_array",
"(",
"rowBased",
"=",
"False",
")",
"width",
"=",
"self",
".",
"get_width",
"(",
")",
"height",
"=",
"self",
".",
"get_height",
"(",
")",
"if",
"not",
"height",
"<",
"width",
":",
"raise",
"ValueError",
"(",
"\"\"\"Not enough rows\"\"\"",
")",
"# Start with complete matrix and remove in each iteration",
"# the first row and the first column",
"for",
"offset",
"in",
"xrange",
"(",
"height",
")",
":",
"# Switch lines, if current first value is 0",
"if",
"mArray",
"[",
"offset",
"]",
"[",
"offset",
"]",
"==",
"0",
":",
"for",
"i",
"in",
"xrange",
"(",
"offset",
"+",
"1",
",",
"height",
")",
":",
"if",
"mArray",
"[",
"offset",
"]",
"[",
"i",
"]",
"!=",
"0",
":",
"tmp",
"=",
"[",
"]",
"for",
"j",
"in",
"xrange",
"(",
"offset",
",",
"width",
")",
":",
"tmp",
".",
"append",
"(",
"mArray",
"[",
"j",
"]",
"[",
"offset",
"]",
")",
"# tmp = mArray[offset][offset:]",
"for",
"j",
"in",
"xrange",
"(",
"offset",
",",
"width",
")",
":",
"mArray",
"[",
"j",
"]",
"[",
"offset",
"]",
"=",
"mArray",
"[",
"j",
"]",
"[",
"i",
"]",
"mArray",
"[",
"j",
"]",
"[",
"i",
"]",
"=",
"tmp",
"[",
"j",
"]",
"# mArray[offset][offset:] = mArray[i][offset:]",
"# mArray[i] = tmp",
"break",
"currentRow",
"=",
"[",
"mArray",
"[",
"j",
"]",
"[",
"offset",
"]",
"for",
"j",
"in",
"xrange",
"(",
"offset",
",",
"width",
")",
"]",
"devider",
"=",
"float",
"(",
"currentRow",
"[",
"0",
"]",
")",
"# If no line is found with an value != 0",
"# the matrix is not invertible",
"if",
"devider",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Matrix is not invertible\"",
")",
"transformedRow",
"=",
"[",
"]",
"# Devide current row by first element of current row",
"for",
"value",
"in",
"currentRow",
":",
"transformedRow",
".",
"append",
"(",
"value",
"/",
"devider",
")",
"# put transformed row back into matrix",
"for",
"j",
"in",
"xrange",
"(",
"offset",
",",
"width",
")",
":",
"mArray",
"[",
"j",
"]",
"[",
"offset",
"]",
"=",
"transformedRow",
"[",
"j",
"-",
"offset",
"]",
"# subtract multiples of the current row, from all remaining rows",
"# in order to become a 0 at the current first column",
"for",
"i",
"in",
"xrange",
"(",
"offset",
"+",
"1",
",",
"height",
")",
":",
"multi",
"=",
"mArray",
"[",
"offset",
"]",
"[",
"i",
"]",
"for",
"j",
"in",
"xrange",
"(",
"offset",
",",
"width",
")",
":",
"mArray",
"[",
"j",
"]",
"[",
"i",
"]",
"=",
"mArray",
"[",
"j",
"]",
"[",
"i",
"]",
"-",
"mArray",
"[",
"j",
"]",
"[",
"offset",
"]",
"*",
"multi",
"for",
"i",
"in",
"xrange",
"(",
"1",
",",
"height",
")",
":",
"# subtract multiples of the i-the row from all above rows",
"for",
"j",
"in",
"xrange",
"(",
"0",
",",
"i",
")",
":",
"multi",
"=",
"mArray",
"[",
"i",
"]",
"[",
"j",
"]",
"for",
"col",
"in",
"xrange",
"(",
"i",
",",
"width",
")",
":",
"mArray",
"[",
"col",
"]",
"[",
"j",
"]",
"=",
"mArray",
"[",
"col",
"]",
"[",
"j",
"]",
"-",
"mArray",
"[",
"col",
"]",
"[",
"i",
"]",
"*",
"multi",
"self",
".",
"matrix",
"=",
"mArray",
"return",
"self"
] | Reduce :py:obj:`self` to row echelon form.
:return: Returns :py:obj:`self` in row echelon form for convenience.
:rtype: Matrix
:raise: Raises an :py:exc:`ValueError` if:
- the matrix rows < columns
- the matrix is not invertible
In this case :py:obj:`self` is not changed. | [
"Reduce",
":",
"py",
":",
"obj",
":",
"self",
"to",
"row",
"echelon",
"form",
"."
] | python | train |
shoebot/shoebot | shoebot/data/geometry.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L39-L45 | def rotate(x, y, x0, y0, angle):
""" Returns the coordinates of (x,y) rotated around origin (x0,y0).
"""
x, y = x - x0, y - y0
a, b = cos(radians(angle)), sin(radians(angle))
return (x * a - y * b + x0,
y * a + x * b + y0) | [
"def",
"rotate",
"(",
"x",
",",
"y",
",",
"x0",
",",
"y0",
",",
"angle",
")",
":",
"x",
",",
"y",
"=",
"x",
"-",
"x0",
",",
"y",
"-",
"y0",
"a",
",",
"b",
"=",
"cos",
"(",
"radians",
"(",
"angle",
")",
")",
",",
"sin",
"(",
"radians",
"(",
"angle",
")",
")",
"return",
"(",
"x",
"*",
"a",
"-",
"y",
"*",
"b",
"+",
"x0",
",",
"y",
"*",
"a",
"+",
"x",
"*",
"b",
"+",
"y0",
")"
] | Returns the coordinates of (x,y) rotated around origin (x0,y0). | [
"Returns",
"the",
"coordinates",
"of",
"(",
"x",
"y",
")",
"rotated",
"around",
"origin",
"(",
"x0",
"y0",
")",
"."
] | python | valid |
nickmckay/LiPD-utilities | Python/lipd/directory.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L434-L449 | def rm_files_in_dir(path):
"""
Removes all files within a directory, but does not delete the directory
:param str path: Target directory
:return none:
"""
for f in os.listdir(path):
try:
os.remove(f)
except PermissionError:
os.chmod(f, 0o777)
try:
os.remove(f)
except Exception:
pass
return | [
"def",
"rm_files_in_dir",
"(",
"path",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"f",
")",
"except",
"PermissionError",
":",
"os",
".",
"chmod",
"(",
"f",
",",
"0o777",
")",
"try",
":",
"os",
".",
"remove",
"(",
"f",
")",
"except",
"Exception",
":",
"pass",
"return"
] | Removes all files within a directory, but does not delete the directory
:param str path: Target directory
:return none: | [
"Removes",
"all",
"files",
"within",
"a",
"directory",
"but",
"does",
"not",
"delete",
"the",
"directory",
":",
"param",
"str",
"path",
":",
"Target",
"directory",
":",
"return",
"none",
":"
] | python | train |
tanghaibao/jcvi | jcvi/algorithms/formula.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/formula.py#L198-L219 | def velvet(readsize, genomesize, numreads, K):
"""
Calculate velvet memory requirement.
<http://seqanswers.com/forums/showthread.php?t=2101>
Ram required for velvetg = -109635 + 18977*ReadSize + 86326*GenomeSize +
233353*NumReads - 51092*K
Read size is in bases.
Genome size is in millions of bases (Mb)
Number of reads is in millions
K is the kmer hash value used in velveth
"""
ram = -109635 + 18977 * readsize + 86326 * genomesize + \
233353 * numreads - 51092 * K
print("ReadSize: {0}".format(readsize), file=sys.stderr)
print("GenomeSize: {0}Mb".format(genomesize), file=sys.stderr)
print("NumReads: {0}M".format(numreads), file=sys.stderr)
print("K: {0}".format(K), file=sys.stderr)
ram = human_size(ram * 1000, a_kilobyte_is_1024_bytes=True)
print("RAM usage: {0} (MAXKMERLENGTH=31)".format(ram), file=sys.stderr) | [
"def",
"velvet",
"(",
"readsize",
",",
"genomesize",
",",
"numreads",
",",
"K",
")",
":",
"ram",
"=",
"-",
"109635",
"+",
"18977",
"*",
"readsize",
"+",
"86326",
"*",
"genomesize",
"+",
"233353",
"*",
"numreads",
"-",
"51092",
"*",
"K",
"print",
"(",
"\"ReadSize: {0}\"",
".",
"format",
"(",
"readsize",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"\"GenomeSize: {0}Mb\"",
".",
"format",
"(",
"genomesize",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"\"NumReads: {0}M\"",
".",
"format",
"(",
"numreads",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"\"K: {0}\"",
".",
"format",
"(",
"K",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"ram",
"=",
"human_size",
"(",
"ram",
"*",
"1000",
",",
"a_kilobyte_is_1024_bytes",
"=",
"True",
")",
"print",
"(",
"\"RAM usage: {0} (MAXKMERLENGTH=31)\"",
".",
"format",
"(",
"ram",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | Calculate velvet memory requirement.
<http://seqanswers.com/forums/showthread.php?t=2101>
Ram required for velvetg = -109635 + 18977*ReadSize + 86326*GenomeSize +
233353*NumReads - 51092*K
Read size is in bases.
Genome size is in millions of bases (Mb)
Number of reads is in millions
K is the kmer hash value used in velveth | [
"Calculate",
"velvet",
"memory",
"requirement",
".",
"<http",
":",
"//",
"seqanswers",
".",
"com",
"/",
"forums",
"/",
"showthread",
".",
"php?t",
"=",
"2101",
">"
] | python | train |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L4756-L4764 | def set_property(self, **kwargs):
"""
set any property of the underlying nparray object
"""
if not isinstance(self._value, nparray.ndarray):
raise ValueError("value is not a nparray object")
for property, value in kwargs.items():
setattr(self._value, property, value) | [
"def",
"set_property",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_value",
",",
"nparray",
".",
"ndarray",
")",
":",
"raise",
"ValueError",
"(",
"\"value is not a nparray object\"",
")",
"for",
"property",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
".",
"_value",
",",
"property",
",",
"value",
")"
] | set any property of the underlying nparray object | [
"set",
"any",
"property",
"of",
"the",
"underlying",
"nparray",
"object"
] | python | train |
mitsei/dlkit | dlkit/json_/logging_/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/logging_/managers.py#L749-L772 | def get_log_entry_query_session_for_log(self, log_id, proxy):
"""Gets the ``OsidSession`` associated with the log entry query service for the given log.
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.logging.LogEntryQuerySession) - a
``LogEntryQuerySession``
raise: NotFound - no ``Log`` found by the given ``Id``
raise: NullArgument - ``log_id`` or ``proxy`` is ``null``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_log_entry_query()`` or
``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_log_entry_query()`` and
``supports_visible_federation()`` are ``true``*
"""
if not self.supports_log_entry_query():
raise errors.Unimplemented()
##
# Also include check to see if the catalog Id is found otherwise raise errors.NotFound
##
# pylint: disable=no-member
return sessions.LogEntryQuerySession(log_id, proxy, self._runtime) | [
"def",
"get_log_entry_query_session_for_log",
"(",
"self",
",",
"log_id",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_log_entry_query",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"##",
"# Also include check to see if the catalog Id is found otherwise raise errors.NotFound",
"##",
"# pylint: disable=no-member",
"return",
"sessions",
".",
"LogEntryQuerySession",
"(",
"log_id",
",",
"proxy",
",",
"self",
".",
"_runtime",
")"
] | Gets the ``OsidSession`` associated with the log entry query service for the given log.
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.logging.LogEntryQuerySession) - a
``LogEntryQuerySession``
raise: NotFound - no ``Log`` found by the given ``Id``
raise: NullArgument - ``log_id`` or ``proxy`` is ``null``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_log_entry_query()`` or
``supports_visible_federation()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_log_entry_query()`` and
``supports_visible_federation()`` are ``true``* | [
"Gets",
"the",
"OsidSession",
"associated",
"with",
"the",
"log",
"entry",
"query",
"service",
"for",
"the",
"given",
"log",
"."
] | python | train |
quantumlib/Cirq | cirq/contrib/acquaintance/mutation_utils.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/contrib/acquaintance/mutation_utils.py#L36-L67 | def rectify_acquaintance_strategy(
circuit: circuits.Circuit,
acquaint_first: bool=True
) -> None:
"""Splits moments so that they contain either only acquaintance gates
or only permutation gates. Orders resulting moments so that the first one
is of the same type as the previous one.
Args:
circuit: The acquaintance strategy to rectify.
acquaint_first: Whether to make acquaintance moment first in when
splitting the first mixed moment.
"""
if not is_acquaintance_strategy(circuit):
raise TypeError('not is_acquaintance_strategy(circuit)')
rectified_moments = []
for moment in circuit:
gate_type_to_ops = collections.defaultdict(list
) # type: Dict[bool, List[ops.GateOperation]]
for op in moment.operations:
gate_type_to_ops[isinstance(op.gate, AcquaintanceOpportunityGate)
].append(op)
if len(gate_type_to_ops) == 1:
rectified_moments.append(moment)
continue
for acquaint_first in sorted(gate_type_to_ops.keys(),
reverse=acquaint_first):
rectified_moments.append(
ops.Moment(gate_type_to_ops[acquaint_first]))
circuit._moments = rectified_moments | [
"def",
"rectify_acquaintance_strategy",
"(",
"circuit",
":",
"circuits",
".",
"Circuit",
",",
"acquaint_first",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"if",
"not",
"is_acquaintance_strategy",
"(",
"circuit",
")",
":",
"raise",
"TypeError",
"(",
"'not is_acquaintance_strategy(circuit)'",
")",
"rectified_moments",
"=",
"[",
"]",
"for",
"moment",
"in",
"circuit",
":",
"gate_type_to_ops",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"# type: Dict[bool, List[ops.GateOperation]]",
"for",
"op",
"in",
"moment",
".",
"operations",
":",
"gate_type_to_ops",
"[",
"isinstance",
"(",
"op",
".",
"gate",
",",
"AcquaintanceOpportunityGate",
")",
"]",
".",
"append",
"(",
"op",
")",
"if",
"len",
"(",
"gate_type_to_ops",
")",
"==",
"1",
":",
"rectified_moments",
".",
"append",
"(",
"moment",
")",
"continue",
"for",
"acquaint_first",
"in",
"sorted",
"(",
"gate_type_to_ops",
".",
"keys",
"(",
")",
",",
"reverse",
"=",
"acquaint_first",
")",
":",
"rectified_moments",
".",
"append",
"(",
"ops",
".",
"Moment",
"(",
"gate_type_to_ops",
"[",
"acquaint_first",
"]",
")",
")",
"circuit",
".",
"_moments",
"=",
"rectified_moments"
] | Splits moments so that they contain either only acquaintance gates
or only permutation gates. Orders resulting moments so that the first one
is of the same type as the previous one.
Args:
circuit: The acquaintance strategy to rectify.
acquaint_first: Whether to make acquaintance moment first in when
splitting the first mixed moment. | [
"Splits",
"moments",
"so",
"that",
"they",
"contain",
"either",
"only",
"acquaintance",
"gates",
"or",
"only",
"permutation",
"gates",
".",
"Orders",
"resulting",
"moments",
"so",
"that",
"the",
"first",
"one",
"is",
"of",
"the",
"same",
"type",
"as",
"the",
"previous",
"one",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/debugging.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/debugging.py#L158-L264 | def get_caller_stack_info(start_back: int = 1) -> List[str]:
r"""
Retrieves a textual representation of the call stack.
Args:
start_back: number of calls back in the frame stack (starting
from the frame stack as seen by :func:`get_caller_stack_info`)
to begin with
Returns:
list of descriptions
Example:
.. code-block:: python
from cardinal_pythonlib.debugging import get_caller_stack_info
def who_am_i():
return get_caller_name()
class MyClass(object):
def classfunc(self):
print("Stack info:\n" + "\n".join(get_caller_stack_info()))
def f2():
x = MyClass()
x.classfunc()
def f1():
f2()
f1()
if called from the Python prompt will produce:
.. code-block:: none
Stack info:
<module>()
... defined at <stdin>:1
... line 1 calls next in stack; code is:
f1()
... defined at <stdin>:1
... line 2 calls next in stack; code is:
f2()
... defined at <stdin>:1
... line 3 calls next in stack; code is:
classfunc(self=<__main__.MyClass object at 0x7f86a009c6d8>)
... defined at <stdin>:2
... line 3 calls next in stack; code is:
and if called from a Python file will produce:
.. code-block:: none
Stack info:
<module>()
... defined at /home/rudolf/tmp/stack.py:1
... line 17 calls next in stack; code is:
f1()
f1()
... defined at /home/rudolf/tmp/stack.py:14
... line 15 calls next in stack; code is:
f2()
f2()
... defined at /home/rudolf/tmp/stack.py:10
... line 12 calls next in stack; code is:
x.classfunc()
classfunc(self=<__main__.MyClass object at 0x7fd7a731f358>)
... defined at /home/rudolf/tmp/stack.py:7
... line 8 calls next in stack; code is:
print("Stack info:\n" + "\n".join(get_caller_stack_info()))
"""
# "0 back" is debug_callers, so "1 back" its caller
# https://docs.python.org/3/library/inspect.html
callers = [] # type: List[str]
frameinfolist = inspect.stack() # type: List[FrameInfo] # noqa
frameinfolist = frameinfolist[start_back:]
for frameinfo in frameinfolist:
frame = frameinfo.frame
function_defined_at = "... defined at {filename}:{line}".format(
filename=frame.f_code.co_filename,
line=frame.f_code.co_firstlineno,
)
argvalues = inspect.getargvalues(frame)
formatted_argvalues = inspect.formatargvalues(*argvalues)
function_call = "{funcname}{argvals}".format(
funcname=frame.f_code.co_name,
argvals=formatted_argvalues,
)
code_context = frameinfo.code_context
code = "".join(code_context) if code_context else ""
onwards = "... line {line} calls next in stack; code is:\n{c}".format(
line=frame.f_lineno,
c=code,
)
description = "\n".join([function_call, function_defined_at, onwards])
callers.append(description)
return list(reversed(callers)) | [
"def",
"get_caller_stack_info",
"(",
"start_back",
":",
"int",
"=",
"1",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# \"0 back\" is debug_callers, so \"1 back\" its caller",
"# https://docs.python.org/3/library/inspect.html",
"callers",
"=",
"[",
"]",
"# type: List[str]",
"frameinfolist",
"=",
"inspect",
".",
"stack",
"(",
")",
"# type: List[FrameInfo] # noqa",
"frameinfolist",
"=",
"frameinfolist",
"[",
"start_back",
":",
"]",
"for",
"frameinfo",
"in",
"frameinfolist",
":",
"frame",
"=",
"frameinfo",
".",
"frame",
"function_defined_at",
"=",
"\"... defined at {filename}:{line}\"",
".",
"format",
"(",
"filename",
"=",
"frame",
".",
"f_code",
".",
"co_filename",
",",
"line",
"=",
"frame",
".",
"f_code",
".",
"co_firstlineno",
",",
")",
"argvalues",
"=",
"inspect",
".",
"getargvalues",
"(",
"frame",
")",
"formatted_argvalues",
"=",
"inspect",
".",
"formatargvalues",
"(",
"*",
"argvalues",
")",
"function_call",
"=",
"\"{funcname}{argvals}\"",
".",
"format",
"(",
"funcname",
"=",
"frame",
".",
"f_code",
".",
"co_name",
",",
"argvals",
"=",
"formatted_argvalues",
",",
")",
"code_context",
"=",
"frameinfo",
".",
"code_context",
"code",
"=",
"\"\"",
".",
"join",
"(",
"code_context",
")",
"if",
"code_context",
"else",
"\"\"",
"onwards",
"=",
"\"... line {line} calls next in stack; code is:\\n{c}\"",
".",
"format",
"(",
"line",
"=",
"frame",
".",
"f_lineno",
",",
"c",
"=",
"code",
",",
")",
"description",
"=",
"\"\\n\"",
".",
"join",
"(",
"[",
"function_call",
",",
"function_defined_at",
",",
"onwards",
"]",
")",
"callers",
".",
"append",
"(",
"description",
")",
"return",
"list",
"(",
"reversed",
"(",
"callers",
")",
")"
] | r"""
Retrieves a textual representation of the call stack.
Args:
start_back: number of calls back in the frame stack (starting
from the frame stack as seen by :func:`get_caller_stack_info`)
to begin with
Returns:
list of descriptions
Example:
.. code-block:: python
from cardinal_pythonlib.debugging import get_caller_stack_info
def who_am_i():
return get_caller_name()
class MyClass(object):
def classfunc(self):
print("Stack info:\n" + "\n".join(get_caller_stack_info()))
def f2():
x = MyClass()
x.classfunc()
def f1():
f2()
f1()
if called from the Python prompt will produce:
.. code-block:: none
Stack info:
<module>()
... defined at <stdin>:1
... line 1 calls next in stack; code is:
f1()
... defined at <stdin>:1
... line 2 calls next in stack; code is:
f2()
... defined at <stdin>:1
... line 3 calls next in stack; code is:
classfunc(self=<__main__.MyClass object at 0x7f86a009c6d8>)
... defined at <stdin>:2
... line 3 calls next in stack; code is:
and if called from a Python file will produce:
.. code-block:: none
Stack info:
<module>()
... defined at /home/rudolf/tmp/stack.py:1
... line 17 calls next in stack; code is:
f1()
f1()
... defined at /home/rudolf/tmp/stack.py:14
... line 15 calls next in stack; code is:
f2()
f2()
... defined at /home/rudolf/tmp/stack.py:10
... line 12 calls next in stack; code is:
x.classfunc()
classfunc(self=<__main__.MyClass object at 0x7fd7a731f358>)
... defined at /home/rudolf/tmp/stack.py:7
... line 8 calls next in stack; code is:
print("Stack info:\n" + "\n".join(get_caller_stack_info())) | [
"r",
"Retrieves",
"a",
"textual",
"representation",
"of",
"the",
"call",
"stack",
"."
] | python | train |
yandex/yandex-tank | yandextank/plugins/Telegraf/client.py | https://github.com/yandex/yandex-tank/blob/d71d63b6ab5de8b8a5ea2b728b6ab9ac0b1ba71b/yandextank/plugins/Telegraf/client.py#L141-L162 | def uninstall(self):
"""
Remove agent's files from remote host
"""
if self.session:
logger.info('Waiting monitoring data...')
self.session.terminate()
self.session.wait()
self.session = None
log_filename = "agent_{host}.log".format(host="localhost")
data_filename = "agent_{host}.rawdata".format(host="localhost")
try:
logger.info('Saving monitoring artefacts from localhost')
copyfile(self.workdir + "/_agent.log", log_filename)
copyfile(self.workdir + "/monitoring.rawdata", data_filename)
logger.info('Deleting temp directory: %s', self.workdir)
rmtree(self.workdir)
except Exception:
logger.error("Exception while uninstalling agent", exc_info=True)
logger.info("Removing agent from: localhost")
return log_filename, data_filename | [
"def",
"uninstall",
"(",
"self",
")",
":",
"if",
"self",
".",
"session",
":",
"logger",
".",
"info",
"(",
"'Waiting monitoring data...'",
")",
"self",
".",
"session",
".",
"terminate",
"(",
")",
"self",
".",
"session",
".",
"wait",
"(",
")",
"self",
".",
"session",
"=",
"None",
"log_filename",
"=",
"\"agent_{host}.log\"",
".",
"format",
"(",
"host",
"=",
"\"localhost\"",
")",
"data_filename",
"=",
"\"agent_{host}.rawdata\"",
".",
"format",
"(",
"host",
"=",
"\"localhost\"",
")",
"try",
":",
"logger",
".",
"info",
"(",
"'Saving monitoring artefacts from localhost'",
")",
"copyfile",
"(",
"self",
".",
"workdir",
"+",
"\"/_agent.log\"",
",",
"log_filename",
")",
"copyfile",
"(",
"self",
".",
"workdir",
"+",
"\"/monitoring.rawdata\"",
",",
"data_filename",
")",
"logger",
".",
"info",
"(",
"'Deleting temp directory: %s'",
",",
"self",
".",
"workdir",
")",
"rmtree",
"(",
"self",
".",
"workdir",
")",
"except",
"Exception",
":",
"logger",
".",
"error",
"(",
"\"Exception while uninstalling agent\"",
",",
"exc_info",
"=",
"True",
")",
"logger",
".",
"info",
"(",
"\"Removing agent from: localhost\"",
")",
"return",
"log_filename",
",",
"data_filename"
] | Remove agent's files from remote host | [
"Remove",
"agent",
"s",
"files",
"from",
"remote",
"host"
] | python | test |
hapylestat/apputils | apputils/settings/ast/cmd.py | https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/settings/ast/cmd.py#L142-L160 | def parse(self, argv, tokenizer=DefaultTokenizer):
"""
Parse command line to out tree
:type argv object
:type tokenizer AbstractTokenizer
"""
args = tokenizer.tokenize(argv)
_lang = tokenizer.language_definition()
#
# for param in self.__args:
# if self._is_default_arg(param):
# self.__out_tree[self.__default_arg_tag].append(param.strip())
# else:
# param = param.lstrip("-").partition('=')
# if len(param) == 3:
# self.__parse_one_param(param)
pass | [
"def",
"parse",
"(",
"self",
",",
"argv",
",",
"tokenizer",
"=",
"DefaultTokenizer",
")",
":",
"args",
"=",
"tokenizer",
".",
"tokenize",
"(",
"argv",
")",
"_lang",
"=",
"tokenizer",
".",
"language_definition",
"(",
")",
"#",
"# for param in self.__args:",
"# if self._is_default_arg(param):",
"# self.__out_tree[self.__default_arg_tag].append(param.strip())",
"# else:",
"# param = param.lstrip(\"-\").partition('=')",
"# if len(param) == 3:",
"# self.__parse_one_param(param)",
"pass"
] | Parse command line to out tree
:type argv object
:type tokenizer AbstractTokenizer | [
"Parse",
"command",
"line",
"to",
"out",
"tree"
] | python | train |
rosenbrockc/ci | pyci/scripts/ci.py | https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/scripts/ci.py#L115-L122 | def _load_db():
"""Deserializes the script database from JSON."""
from os import path
from pyci.utility import get_json
global datapath, db
datapath = path.abspath(path.expanduser(settings.datafile))
vms("Deserializing DB from {}".format(datapath))
db = get_json(datapath, {"installed": [], "enabled": True, "cron": False}) | [
"def",
"_load_db",
"(",
")",
":",
"from",
"os",
"import",
"path",
"from",
"pyci",
".",
"utility",
"import",
"get_json",
"global",
"datapath",
",",
"db",
"datapath",
"=",
"path",
".",
"abspath",
"(",
"path",
".",
"expanduser",
"(",
"settings",
".",
"datafile",
")",
")",
"vms",
"(",
"\"Deserializing DB from {}\"",
".",
"format",
"(",
"datapath",
")",
")",
"db",
"=",
"get_json",
"(",
"datapath",
",",
"{",
"\"installed\"",
":",
"[",
"]",
",",
"\"enabled\"",
":",
"True",
",",
"\"cron\"",
":",
"False",
"}",
")"
] | Deserializes the script database from JSON. | [
"Deserializes",
"the",
"script",
"database",
"from",
"JSON",
"."
] | python | train |
cni/MRS | MRS/leastsqbound/leastsqbound.py | https://github.com/cni/MRS/blob/16098b3cf4830780efd787fee9efa46513850283/MRS/leastsqbound/leastsqbound.py#L89-L327 | def leastsqbound(func, x0, args=(), bounds=None, Dfun=None, full_output=0,
col_deriv=0, ftol=1.49012e-8, xtol=1.49012e-8,
gtol=0.0, maxfev=0, epsfcn=0.0, factor=100, diag=None):
"""
Bounded minimization of the sum of squares of a set of equations.
::
x = arg min(sum(func(y)**2,axis=0))
y
Parameters
----------
func : callable
should take at least one (possibly length N vector) argument and
returns M floating point numbers.
x0 : ndarray
The starting estimate for the minimization.
args : tuple
Any extra arguments to func are placed in this tuple.
bounds : list
``(min, max)`` pairs for each element in ``x``, defining
the bounds on that parameter. Use None for one of ``min`` or
``max`` when there is no bound in that direction.
Dfun : callable
A function or method to compute the Jacobian of func with derivatives
across the rows. If this is None, the Jacobian will be estimated.
full_output : bool
non-zero to return all optional outputs.
col_deriv : bool
non-zero to specify that the Jacobian function computes derivatives
down the columns (faster, because there is no transpose operation).
ftol : float
Relative error desired in the sum of squares.
xtol : float
Relative error desired in the approximate solution.
gtol : float
Orthogonality desired between the function vector and the columns of
the Jacobian.
maxfev : int
The maximum number of calls to the function. If zero, then 100*(N+1) is
the maximum where N is the number of elements in x0.
epsfcn : float
A suitable step length for the forward-difference approximation of the
Jacobian (for Dfun=None). If epsfcn is less than the machine precision,
it is assumed that the relative errors in the functions are of the
order of the machine precision.
factor : float
A parameter determining the initial step bound
(``factor * || diag * x||``). Should be in interval ``(0.1, 100)``.
diag : sequence
N positive entries that serve as a scale factors for the variables.
Returns
-------
x : ndarray
The solution (or the result of the last iteration for an unsuccessful
call).
cov_x : ndarray
Uses the fjac and ipvt optional outputs to construct an
estimate of the jacobian around the solution. ``None`` if a
singular matrix encountered (indicates very flat curvature in
some direction). This matrix must be multiplied by the
residual standard deviation to get the covariance of the
parameter estimates -- see curve_fit.
infodict : dict
a dictionary of optional outputs with the key s::
- 'nfev' : the number of function calls
- 'fvec' : the function evaluated at the output
- 'fjac' : A permutation of the R matrix of a QR
factorization of the final approximate
Jacobian matrix, stored column wise.
Together with ipvt, the covariance of the
estimate can be approximated.
- 'ipvt' : an integer array of length N which defines
a permutation matrix, p, such that
fjac*p = q*r, where r is upper triangular
with diagonal elements of nonincreasing
magnitude. Column j of p is column ipvt(j)
of the identity matrix.
- 'qtf' : the vector (transpose(q) * fvec).
mesg : str
A string message giving information about the cause of failure.
ier : int
An integer flag. If it is equal to 1, 2, 3 or 4, the solution was
found. Otherwise, the solution was not found. In either case, the
optional output variable 'mesg' gives more information.
Notes
-----
"leastsq" is a wrapper around MINPACK's lmdif and lmder algorithms.
cov_x is a Jacobian approximation to the Hessian of the least squares
objective function.
This approximation assumes that the objective function is based on the
difference between some observed target data (ydata) and a (non-linear)
function of the parameters `f(xdata, params)` ::
func(params) = ydata - f(xdata, params)
so that the objective function is ::
min sum((ydata - f(xdata, params))**2, axis=0)
params
Contraints on the parameters are enforced using an internal parameter list
with appropiate transformations such that these internal parameters can be
optimized without constraints. The transfomation between a given internal
parameter, p_i, and a external parameter, p_e, are as follows:
With ``min`` and ``max`` bounds defined ::
p_i = arcsin((2 * (p_e - min) / (max - min)) - 1.)
p_e = min + ((max - min) / 2.) * (sin(p_i) + 1.)
With only ``max`` defined ::
p_i = sqrt((p_e - max + 1.)**2 - 1.)
p_e = max + 1. - sqrt(p_i**2 + 1.)
With only ``min`` defined ::
p_i = sqrt((p_e - min + 1.)**2 - 1.)
p_e = min - 1. + sqrt(p_i**2 + 1.)
These transfomations are used in the MINUIT package, and described in
detail in the section 1.3.1 of the MINUIT User's Guide.
To Do
-----
Currently the ``factor`` and ``diag`` parameters scale the
internal parameter list, but should scale the external parameter list.
The `qtf` vector in the infodic dictionary reflects internal parameter
list, it should be correct to reflect the external parameter list.
References
----------
* F. James and M. Winkler. MINUIT User's Guide, July 16, 2004.
"""
# use leastsq if no bounds are present
if bounds is None:
return leastsq(func, x0, args, Dfun, full_output, col_deriv,
ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
# create function which convert between internal and external parameters
i2e = _internal2external_func(bounds)
e2i = _external2internal_func(bounds)
x0 = array(x0, ndmin=1)
i0 = e2i(x0)
n = len(x0)
if len(bounds) != n:
raise ValueError('length of x0 != length of bounds')
if type(args) != type(()):
args = (args,)
m = _check_func('leastsq', 'func', func, x0, args, n)[0]
if n > m:
raise TypeError('Improper input: N=%s must not exceed M=%s' % (n,m))
# define a wrapped func which accept internal parameters, converts them
# to external parameters and calls func
def wfunc(x, *args): return func(i2e(x), *args)
if Dfun is None:
if (maxfev == 0):
maxfev = 200*(n + 1)
retval = _minpack._lmdif(wfunc, i0, args, full_output, ftol, xtol,
gtol, maxfev, epsfcn, factor, diag)
else:
if col_deriv:
_check_func('leastsq', 'Dfun', Dfun, x0, args, n, (n,m))
else:
_check_func('leastsq', 'Dfun', Dfun, x0, args, n, (m,n))
if (maxfev == 0):
maxfev = 100*(n + 1)
def wDfun(x, *args): return Dfun(i2e(x), *args) # wrapped Dfun
retval = _minpack._lmder(func, wDfun, i0, args, full_output,
col_deriv, ftol, xtol, gtol, maxfev, factor, diag)
errors = {0:["Improper input parameters.", TypeError],
1:["Both actual and predicted relative reductions "
"in the sum of squares\n are at most %f" % ftol, None],
2:["The relative error between two consecutive "
"iterates is at most %f" % xtol, None],
3:["Both actual and predicted relative reductions in "
"the sum of squares\n are at most %f and the "
"relative error between two consecutive "
"iterates is at \n most %f" % (ftol,xtol), None],
4:["The cosine of the angle between func(x) and any "
"column of the\n Jacobian is at most %f in "
"absolute value" % gtol, None],
5:["Number of calls to function has reached "
"maxfev = %d." % maxfev, ValueError],
6:["ftol=%f is too small, no further reduction "
"in the sum of squares\n is possible.""" % ftol, ValueError],
7:["xtol=%f is too small, no further improvement in "
"the approximate\n solution is possible." % xtol, ValueError],
8:["gtol=%f is too small, func(x) is orthogonal to the "
"columns of\n the Jacobian to machine "
"precision." % gtol, ValueError],
'unknown':["Unknown error.", TypeError]}
info = retval[-1] # The FORTRAN return value
if (info not in [1,2,3,4] and not full_output):
if info in [5,6,7,8]:
warnings.warn(errors[info][0], RuntimeWarning)
else:
try:
raise errors[info][1](errors[info][0])
except KeyError:
raise errors['unknown'][1](errors['unknown'][0])
mesg = errors[info][0]
x = i2e(retval[0]) # internal params to external params
if full_output:
# convert fjac from internal params to external
grad = _internal2external_grad(retval[0], bounds)
retval[1]['fjac'] = (retval[1]['fjac'].T / take(grad,
retval[1]['ipvt'] - 1)).T
cov_x = None
if info in [1,2,3,4]:
from numpy.dual import inv
from numpy.linalg import LinAlgError
perm = take(eye(n),retval[1]['ipvt']-1,0)
r = triu(transpose(retval[1]['fjac'])[:n,:])
R = dot(r, perm)
try:
cov_x = inv(dot(transpose(R),R))
except LinAlgError:
pass
return (x, cov_x) + retval[1:-1] + (mesg, info)
else:
return (x, info) | [
"def",
"leastsqbound",
"(",
"func",
",",
"x0",
",",
"args",
"=",
"(",
")",
",",
"bounds",
"=",
"None",
",",
"Dfun",
"=",
"None",
",",
"full_output",
"=",
"0",
",",
"col_deriv",
"=",
"0",
",",
"ftol",
"=",
"1.49012e-8",
",",
"xtol",
"=",
"1.49012e-8",
",",
"gtol",
"=",
"0.0",
",",
"maxfev",
"=",
"0",
",",
"epsfcn",
"=",
"0.0",
",",
"factor",
"=",
"100",
",",
"diag",
"=",
"None",
")",
":",
"# use leastsq if no bounds are present",
"if",
"bounds",
"is",
"None",
":",
"return",
"leastsq",
"(",
"func",
",",
"x0",
",",
"args",
",",
"Dfun",
",",
"full_output",
",",
"col_deriv",
",",
"ftol",
",",
"xtol",
",",
"gtol",
",",
"maxfev",
",",
"epsfcn",
",",
"factor",
",",
"diag",
")",
"# create function which convert between internal and external parameters",
"i2e",
"=",
"_internal2external_func",
"(",
"bounds",
")",
"e2i",
"=",
"_external2internal_func",
"(",
"bounds",
")",
"x0",
"=",
"array",
"(",
"x0",
",",
"ndmin",
"=",
"1",
")",
"i0",
"=",
"e2i",
"(",
"x0",
")",
"n",
"=",
"len",
"(",
"x0",
")",
"if",
"len",
"(",
"bounds",
")",
"!=",
"n",
":",
"raise",
"ValueError",
"(",
"'length of x0 != length of bounds'",
")",
"if",
"type",
"(",
"args",
")",
"!=",
"type",
"(",
"(",
")",
")",
":",
"args",
"=",
"(",
"args",
",",
")",
"m",
"=",
"_check_func",
"(",
"'leastsq'",
",",
"'func'",
",",
"func",
",",
"x0",
",",
"args",
",",
"n",
")",
"[",
"0",
"]",
"if",
"n",
">",
"m",
":",
"raise",
"TypeError",
"(",
"'Improper input: N=%s must not exceed M=%s'",
"%",
"(",
"n",
",",
"m",
")",
")",
"# define a wrapped func which accept internal parameters, converts them",
"# to external parameters and calls func",
"def",
"wfunc",
"(",
"x",
",",
"*",
"args",
")",
":",
"return",
"func",
"(",
"i2e",
"(",
"x",
")",
",",
"*",
"args",
")",
"if",
"Dfun",
"is",
"None",
":",
"if",
"(",
"maxfev",
"==",
"0",
")",
":",
"maxfev",
"=",
"200",
"*",
"(",
"n",
"+",
"1",
")",
"retval",
"=",
"_minpack",
".",
"_lmdif",
"(",
"wfunc",
",",
"i0",
",",
"args",
",",
"full_output",
",",
"ftol",
",",
"xtol",
",",
"gtol",
",",
"maxfev",
",",
"epsfcn",
",",
"factor",
",",
"diag",
")",
"else",
":",
"if",
"col_deriv",
":",
"_check_func",
"(",
"'leastsq'",
",",
"'Dfun'",
",",
"Dfun",
",",
"x0",
",",
"args",
",",
"n",
",",
"(",
"n",
",",
"m",
")",
")",
"else",
":",
"_check_func",
"(",
"'leastsq'",
",",
"'Dfun'",
",",
"Dfun",
",",
"x0",
",",
"args",
",",
"n",
",",
"(",
"m",
",",
"n",
")",
")",
"if",
"(",
"maxfev",
"==",
"0",
")",
":",
"maxfev",
"=",
"100",
"*",
"(",
"n",
"+",
"1",
")",
"def",
"wDfun",
"(",
"x",
",",
"*",
"args",
")",
":",
"return",
"Dfun",
"(",
"i2e",
"(",
"x",
")",
",",
"*",
"args",
")",
"# wrapped Dfun",
"retval",
"=",
"_minpack",
".",
"_lmder",
"(",
"func",
",",
"wDfun",
",",
"i0",
",",
"args",
",",
"full_output",
",",
"col_deriv",
",",
"ftol",
",",
"xtol",
",",
"gtol",
",",
"maxfev",
",",
"factor",
",",
"diag",
")",
"errors",
"=",
"{",
"0",
":",
"[",
"\"Improper input parameters.\"",
",",
"TypeError",
"]",
",",
"1",
":",
"[",
"\"Both actual and predicted relative reductions \"",
"\"in the sum of squares\\n are at most %f\"",
"%",
"ftol",
",",
"None",
"]",
",",
"2",
":",
"[",
"\"The relative error between two consecutive \"",
"\"iterates is at most %f\"",
"%",
"xtol",
",",
"None",
"]",
",",
"3",
":",
"[",
"\"Both actual and predicted relative reductions in \"",
"\"the sum of squares\\n are at most %f and the \"",
"\"relative error between two consecutive \"",
"\"iterates is at \\n most %f\"",
"%",
"(",
"ftol",
",",
"xtol",
")",
",",
"None",
"]",
",",
"4",
":",
"[",
"\"The cosine of the angle between func(x) and any \"",
"\"column of the\\n Jacobian is at most %f in \"",
"\"absolute value\"",
"%",
"gtol",
",",
"None",
"]",
",",
"5",
":",
"[",
"\"Number of calls to function has reached \"",
"\"maxfev = %d.\"",
"%",
"maxfev",
",",
"ValueError",
"]",
",",
"6",
":",
"[",
"\"ftol=%f is too small, no further reduction \"",
"\"in the sum of squares\\n is possible.\"",
"\"\"",
"%",
"ftol",
",",
"ValueError",
"]",
",",
"7",
":",
"[",
"\"xtol=%f is too small, no further improvement in \"",
"\"the approximate\\n solution is possible.\"",
"%",
"xtol",
",",
"ValueError",
"]",
",",
"8",
":",
"[",
"\"gtol=%f is too small, func(x) is orthogonal to the \"",
"\"columns of\\n the Jacobian to machine \"",
"\"precision.\"",
"%",
"gtol",
",",
"ValueError",
"]",
",",
"'unknown'",
":",
"[",
"\"Unknown error.\"",
",",
"TypeError",
"]",
"}",
"info",
"=",
"retval",
"[",
"-",
"1",
"]",
"# The FORTRAN return value",
"if",
"(",
"info",
"not",
"in",
"[",
"1",
",",
"2",
",",
"3",
",",
"4",
"]",
"and",
"not",
"full_output",
")",
":",
"if",
"info",
"in",
"[",
"5",
",",
"6",
",",
"7",
",",
"8",
"]",
":",
"warnings",
".",
"warn",
"(",
"errors",
"[",
"info",
"]",
"[",
"0",
"]",
",",
"RuntimeWarning",
")",
"else",
":",
"try",
":",
"raise",
"errors",
"[",
"info",
"]",
"[",
"1",
"]",
"(",
"errors",
"[",
"info",
"]",
"[",
"0",
"]",
")",
"except",
"KeyError",
":",
"raise",
"errors",
"[",
"'unknown'",
"]",
"[",
"1",
"]",
"(",
"errors",
"[",
"'unknown'",
"]",
"[",
"0",
"]",
")",
"mesg",
"=",
"errors",
"[",
"info",
"]",
"[",
"0",
"]",
"x",
"=",
"i2e",
"(",
"retval",
"[",
"0",
"]",
")",
"# internal params to external params",
"if",
"full_output",
":",
"# convert fjac from internal params to external",
"grad",
"=",
"_internal2external_grad",
"(",
"retval",
"[",
"0",
"]",
",",
"bounds",
")",
"retval",
"[",
"1",
"]",
"[",
"'fjac'",
"]",
"=",
"(",
"retval",
"[",
"1",
"]",
"[",
"'fjac'",
"]",
".",
"T",
"/",
"take",
"(",
"grad",
",",
"retval",
"[",
"1",
"]",
"[",
"'ipvt'",
"]",
"-",
"1",
")",
")",
".",
"T",
"cov_x",
"=",
"None",
"if",
"info",
"in",
"[",
"1",
",",
"2",
",",
"3",
",",
"4",
"]",
":",
"from",
"numpy",
".",
"dual",
"import",
"inv",
"from",
"numpy",
".",
"linalg",
"import",
"LinAlgError",
"perm",
"=",
"take",
"(",
"eye",
"(",
"n",
")",
",",
"retval",
"[",
"1",
"]",
"[",
"'ipvt'",
"]",
"-",
"1",
",",
"0",
")",
"r",
"=",
"triu",
"(",
"transpose",
"(",
"retval",
"[",
"1",
"]",
"[",
"'fjac'",
"]",
")",
"[",
":",
"n",
",",
":",
"]",
")",
"R",
"=",
"dot",
"(",
"r",
",",
"perm",
")",
"try",
":",
"cov_x",
"=",
"inv",
"(",
"dot",
"(",
"transpose",
"(",
"R",
")",
",",
"R",
")",
")",
"except",
"LinAlgError",
":",
"pass",
"return",
"(",
"x",
",",
"cov_x",
")",
"+",
"retval",
"[",
"1",
":",
"-",
"1",
"]",
"+",
"(",
"mesg",
",",
"info",
")",
"else",
":",
"return",
"(",
"x",
",",
"info",
")"
] | Bounded minimization of the sum of squares of a set of equations.
::
x = arg min(sum(func(y)**2,axis=0))
y
Parameters
----------
func : callable
should take at least one (possibly length N vector) argument and
returns M floating point numbers.
x0 : ndarray
The starting estimate for the minimization.
args : tuple
Any extra arguments to func are placed in this tuple.
bounds : list
``(min, max)`` pairs for each element in ``x``, defining
the bounds on that parameter. Use None for one of ``min`` or
``max`` when there is no bound in that direction.
Dfun : callable
A function or method to compute the Jacobian of func with derivatives
across the rows. If this is None, the Jacobian will be estimated.
full_output : bool
non-zero to return all optional outputs.
col_deriv : bool
non-zero to specify that the Jacobian function computes derivatives
down the columns (faster, because there is no transpose operation).
ftol : float
Relative error desired in the sum of squares.
xtol : float
Relative error desired in the approximate solution.
gtol : float
Orthogonality desired between the function vector and the columns of
the Jacobian.
maxfev : int
The maximum number of calls to the function. If zero, then 100*(N+1) is
the maximum where N is the number of elements in x0.
epsfcn : float
A suitable step length for the forward-difference approximation of the
Jacobian (for Dfun=None). If epsfcn is less than the machine precision,
it is assumed that the relative errors in the functions are of the
order of the machine precision.
factor : float
A parameter determining the initial step bound
(``factor * || diag * x||``). Should be in interval ``(0.1, 100)``.
diag : sequence
N positive entries that serve as a scale factors for the variables.
Returns
-------
x : ndarray
The solution (or the result of the last iteration for an unsuccessful
call).
cov_x : ndarray
Uses the fjac and ipvt optional outputs to construct an
estimate of the jacobian around the solution. ``None`` if a
singular matrix encountered (indicates very flat curvature in
some direction). This matrix must be multiplied by the
residual standard deviation to get the covariance of the
parameter estimates -- see curve_fit.
infodict : dict
a dictionary of optional outputs with the key s::
- 'nfev' : the number of function calls
- 'fvec' : the function evaluated at the output
- 'fjac' : A permutation of the R matrix of a QR
factorization of the final approximate
Jacobian matrix, stored column wise.
Together with ipvt, the covariance of the
estimate can be approximated.
- 'ipvt' : an integer array of length N which defines
a permutation matrix, p, such that
fjac*p = q*r, where r is upper triangular
with diagonal elements of nonincreasing
magnitude. Column j of p is column ipvt(j)
of the identity matrix.
- 'qtf' : the vector (transpose(q) * fvec).
mesg : str
A string message giving information about the cause of failure.
ier : int
An integer flag. If it is equal to 1, 2, 3 or 4, the solution was
found. Otherwise, the solution was not found. In either case, the
optional output variable 'mesg' gives more information.
Notes
-----
"leastsq" is a wrapper around MINPACK's lmdif and lmder algorithms.
cov_x is a Jacobian approximation to the Hessian of the least squares
objective function.
This approximation assumes that the objective function is based on the
difference between some observed target data (ydata) and a (non-linear)
function of the parameters `f(xdata, params)` ::
func(params) = ydata - f(xdata, params)
so that the objective function is ::
min sum((ydata - f(xdata, params))**2, axis=0)
params
Contraints on the parameters are enforced using an internal parameter list
with appropiate transformations such that these internal parameters can be
optimized without constraints. The transfomation between a given internal
parameter, p_i, and a external parameter, p_e, are as follows:
With ``min`` and ``max`` bounds defined ::
p_i = arcsin((2 * (p_e - min) / (max - min)) - 1.)
p_e = min + ((max - min) / 2.) * (sin(p_i) + 1.)
With only ``max`` defined ::
p_i = sqrt((p_e - max + 1.)**2 - 1.)
p_e = max + 1. - sqrt(p_i**2 + 1.)
With only ``min`` defined ::
p_i = sqrt((p_e - min + 1.)**2 - 1.)
p_e = min - 1. + sqrt(p_i**2 + 1.)
These transfomations are used in the MINUIT package, and described in
detail in the section 1.3.1 of the MINUIT User's Guide.
To Do
-----
Currently the ``factor`` and ``diag`` parameters scale the
internal parameter list, but should scale the external parameter list.
The `qtf` vector in the infodic dictionary reflects internal parameter
list, it should be correct to reflect the external parameter list.
References
----------
* F. James and M. Winkler. MINUIT User's Guide, July 16, 2004. | [
"Bounded",
"minimization",
"of",
"the",
"sum",
"of",
"squares",
"of",
"a",
"set",
"of",
"equations",
"."
] | python | train |
tjcsl/cslbot | cslbot/commands/msg.py | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/msg.py#L23-L37 | def cmd(send, msg, args):
"""Sends a message to a channel
Syntax: {command} <channel> <message>
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('channel', action=arguments.ChanParser)
parser.add_argument('message', nargs='+')
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
cmdargs.message = ' '.join(cmdargs.message)
send(cmdargs.message, target=cmdargs.channels[0])
send("%s sent message %s to %s" % (args['nick'], cmdargs.message, cmdargs.channels[0]), target=args['config']['core']['ctrlchan']) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'channel'",
",",
"action",
"=",
"arguments",
".",
"ChanParser",
")",
"parser",
".",
"add_argument",
"(",
"'message'",
",",
"nargs",
"=",
"'+'",
")",
"try",
":",
"cmdargs",
"=",
"parser",
".",
"parse_args",
"(",
"msg",
")",
"except",
"arguments",
".",
"ArgumentException",
"as",
"e",
":",
"send",
"(",
"str",
"(",
"e",
")",
")",
"return",
"cmdargs",
".",
"message",
"=",
"' '",
".",
"join",
"(",
"cmdargs",
".",
"message",
")",
"send",
"(",
"cmdargs",
".",
"message",
",",
"target",
"=",
"cmdargs",
".",
"channels",
"[",
"0",
"]",
")",
"send",
"(",
"\"%s sent message %s to %s\"",
"%",
"(",
"args",
"[",
"'nick'",
"]",
",",
"cmdargs",
".",
"message",
",",
"cmdargs",
".",
"channels",
"[",
"0",
"]",
")",
",",
"target",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
"[",
"'ctrlchan'",
"]",
")"
] | Sends a message to a channel
Syntax: {command} <channel> <message> | [
"Sends",
"a",
"message",
"to",
"a",
"channel",
"Syntax",
":",
"{",
"command",
"}",
"<channel",
">",
"<message",
">"
] | python | train |
DataKitchen/DKCloudCommand | DKCloudCommand/modules/DKCloudAPI.py | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudAPI.py#L1021-L1057 | def orderrun_detail(self, kitchen, pdict, return_all_data=False):
"""
api.add_resource(OrderDetailsV2, '/v2/order/details/<string:kitchenname>', methods=['POST'])
:param self: DKCloudAPI
:param kitchen: string
:param pdict: dict
:param return_all_data: boolean
:rtype: DKReturnCode
"""
rc = DKReturnCode()
if kitchen is None or isinstance(kitchen, basestring) is False:
rc.set(rc.DK_FAIL, 'issue with kitchen')
return rc
url = '%s/v2/order/details/%s' % (self.get_url_for_direct_rest_call(),
kitchen)
try:
response = requests.post(url, data=json.dumps(pdict), headers=self._get_common_headers())
rdict = self._get_json(response)
if False:
import pickle
pickle.dump(rdict, open("files/orderrun_detail.p", "wb"))
pass
except (RequestException, ValueError), c:
s = "orderrun_detail: exception: %s" % str(c)
rc.set(rc.DK_FAIL, s)
return rc
if DKCloudAPI._valid_response(response):
if return_all_data is False:
rc.set(rc.DK_SUCCESS, None, rdict['servings'])
else:
rc.set(rc.DK_SUCCESS, None, rdict)
return rc
else:
arc = DKAPIReturnCode(rdict, response)
rc.set(rc.DK_FAIL, arc.get_message())
return rc | [
"def",
"orderrun_detail",
"(",
"self",
",",
"kitchen",
",",
"pdict",
",",
"return_all_data",
"=",
"False",
")",
":",
"rc",
"=",
"DKReturnCode",
"(",
")",
"if",
"kitchen",
"is",
"None",
"or",
"isinstance",
"(",
"kitchen",
",",
"basestring",
")",
"is",
"False",
":",
"rc",
".",
"set",
"(",
"rc",
".",
"DK_FAIL",
",",
"'issue with kitchen'",
")",
"return",
"rc",
"url",
"=",
"'%s/v2/order/details/%s'",
"%",
"(",
"self",
".",
"get_url_for_direct_rest_call",
"(",
")",
",",
"kitchen",
")",
"try",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"pdict",
")",
",",
"headers",
"=",
"self",
".",
"_get_common_headers",
"(",
")",
")",
"rdict",
"=",
"self",
".",
"_get_json",
"(",
"response",
")",
"if",
"False",
":",
"import",
"pickle",
"pickle",
".",
"dump",
"(",
"rdict",
",",
"open",
"(",
"\"files/orderrun_detail.p\"",
",",
"\"wb\"",
")",
")",
"pass",
"except",
"(",
"RequestException",
",",
"ValueError",
")",
",",
"c",
":",
"s",
"=",
"\"orderrun_detail: exception: %s\"",
"%",
"str",
"(",
"c",
")",
"rc",
".",
"set",
"(",
"rc",
".",
"DK_FAIL",
",",
"s",
")",
"return",
"rc",
"if",
"DKCloudAPI",
".",
"_valid_response",
"(",
"response",
")",
":",
"if",
"return_all_data",
"is",
"False",
":",
"rc",
".",
"set",
"(",
"rc",
".",
"DK_SUCCESS",
",",
"None",
",",
"rdict",
"[",
"'servings'",
"]",
")",
"else",
":",
"rc",
".",
"set",
"(",
"rc",
".",
"DK_SUCCESS",
",",
"None",
",",
"rdict",
")",
"return",
"rc",
"else",
":",
"arc",
"=",
"DKAPIReturnCode",
"(",
"rdict",
",",
"response",
")",
"rc",
".",
"set",
"(",
"rc",
".",
"DK_FAIL",
",",
"arc",
".",
"get_message",
"(",
")",
")",
"return",
"rc"
] | api.add_resource(OrderDetailsV2, '/v2/order/details/<string:kitchenname>', methods=['POST'])
:param self: DKCloudAPI
:param kitchen: string
:param pdict: dict
:param return_all_data: boolean
:rtype: DKReturnCode | [
"api",
".",
"add_resource",
"(",
"OrderDetailsV2",
"/",
"v2",
"/",
"order",
"/",
"details",
"/",
"<string",
":",
"kitchenname",
">",
"methods",
"=",
"[",
"POST",
"]",
")",
":",
"param",
"self",
":",
"DKCloudAPI",
":",
"param",
"kitchen",
":",
"string",
":",
"param",
"pdict",
":",
"dict",
":",
"param",
"return_all_data",
":",
"boolean",
":",
"rtype",
":",
"DKReturnCode"
] | python | train |
SmokinCaterpillar/pypet | pypet/utils/decorators.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/decorators.py#L105-L125 | def kwargs_mutual_exclusive(param1_name, param2_name, map2to1=None):
""" If there exist mutually exclusive parameters checks for them and maps param2 to 1."""
def wrapper(func):
@functools.wraps(func)
def new_func(*args, **kwargs):
if param2_name in kwargs:
if param1_name in kwargs:
raise ValueError('You cannot specify `%s` and `%s` at the same time, '
'they are mutually exclusive.' % (param1_name, param2_name))
param2 = kwargs.pop(param2_name)
if map2to1 is not None:
param1 = map2to1(param2)
else:
param1 = param2
kwargs[param1_name] = param1
return func(*args, **kwargs)
return new_func
return wrapper | [
"def",
"kwargs_mutual_exclusive",
"(",
"param1_name",
",",
"param2_name",
",",
"map2to1",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"param2_name",
"in",
"kwargs",
":",
"if",
"param1_name",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"'You cannot specify `%s` and `%s` at the same time, '",
"'they are mutually exclusive.'",
"%",
"(",
"param1_name",
",",
"param2_name",
")",
")",
"param2",
"=",
"kwargs",
".",
"pop",
"(",
"param2_name",
")",
"if",
"map2to1",
"is",
"not",
"None",
":",
"param1",
"=",
"map2to1",
"(",
"param2",
")",
"else",
":",
"param1",
"=",
"param2",
"kwargs",
"[",
"param1_name",
"]",
"=",
"param1",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"new_func",
"return",
"wrapper"
] | If there exist mutually exclusive parameters checks for them and maps param2 to 1. | [
"If",
"there",
"exist",
"mutually",
"exclusive",
"parameters",
"checks",
"for",
"them",
"and",
"maps",
"param2",
"to",
"1",
"."
] | python | test |
GeorgeArgyros/symautomata | symautomata/flex2fst.py | https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/flex2fst.py#L219-L230 | def _add_sink_state(self, states):
"""
This function adds a sing state in the total states
Args:
states (list): The current states
Returns:
None
"""
cleared = []
for i in range(0, 128):
cleared.append(-1)
states.append(cleared) | [
"def",
"_add_sink_state",
"(",
"self",
",",
"states",
")",
":",
"cleared",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"128",
")",
":",
"cleared",
".",
"append",
"(",
"-",
"1",
")",
"states",
".",
"append",
"(",
"cleared",
")"
] | This function adds a sing state in the total states
Args:
states (list): The current states
Returns:
None | [
"This",
"function",
"adds",
"a",
"sing",
"state",
"in",
"the",
"total",
"states",
"Args",
":",
"states",
"(",
"list",
")",
":",
"The",
"current",
"states",
"Returns",
":",
"None"
] | python | train |
googleapis/google-cloud-python | bigquery/google/cloud/bigquery/job.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/job.py#L2518-L2528 | def to_api_repr(self):
"""Generate a resource for :meth:`_begin`."""
configuration = self._configuration.to_api_repr()
resource = {
"jobReference": self._properties["jobReference"],
"configuration": configuration,
}
configuration["query"]["query"] = self.query
return resource | [
"def",
"to_api_repr",
"(",
"self",
")",
":",
"configuration",
"=",
"self",
".",
"_configuration",
".",
"to_api_repr",
"(",
")",
"resource",
"=",
"{",
"\"jobReference\"",
":",
"self",
".",
"_properties",
"[",
"\"jobReference\"",
"]",
",",
"\"configuration\"",
":",
"configuration",
",",
"}",
"configuration",
"[",
"\"query\"",
"]",
"[",
"\"query\"",
"]",
"=",
"self",
".",
"query",
"return",
"resource"
] | Generate a resource for :meth:`_begin`. | [
"Generate",
"a",
"resource",
"for",
":",
"meth",
":",
"_begin",
"."
] | python | train |
dhermes/bezier | src/bezier/_geometric_intersection.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L1180-L1199 | def make_same_degree(nodes1, nodes2):
"""Degree-elevate a curve so two curves have matching degree.
Args:
nodes1 (numpy.ndarray): Set of control points for a
B |eacute| zier curve.
nodes2 (numpy.ndarray): Set of control points for a
B |eacute| zier curve.
Returns:
Tuple[numpy.ndarray, numpy.ndarray]: The potentially degree-elevated
nodes passed in.
"""
_, num_nodes1 = nodes1.shape
_, num_nodes2 = nodes2.shape
for _ in six.moves.xrange(num_nodes2 - num_nodes1):
nodes1 = _curve_helpers.elevate_nodes(nodes1)
for _ in six.moves.xrange(num_nodes1 - num_nodes2):
nodes2 = _curve_helpers.elevate_nodes(nodes2)
return nodes1, nodes2 | [
"def",
"make_same_degree",
"(",
"nodes1",
",",
"nodes2",
")",
":",
"_",
",",
"num_nodes1",
"=",
"nodes1",
".",
"shape",
"_",
",",
"num_nodes2",
"=",
"nodes2",
".",
"shape",
"for",
"_",
"in",
"six",
".",
"moves",
".",
"xrange",
"(",
"num_nodes2",
"-",
"num_nodes1",
")",
":",
"nodes1",
"=",
"_curve_helpers",
".",
"elevate_nodes",
"(",
"nodes1",
")",
"for",
"_",
"in",
"six",
".",
"moves",
".",
"xrange",
"(",
"num_nodes1",
"-",
"num_nodes2",
")",
":",
"nodes2",
"=",
"_curve_helpers",
".",
"elevate_nodes",
"(",
"nodes2",
")",
"return",
"nodes1",
",",
"nodes2"
] | Degree-elevate a curve so two curves have matching degree.
Args:
nodes1 (numpy.ndarray): Set of control points for a
B |eacute| zier curve.
nodes2 (numpy.ndarray): Set of control points for a
B |eacute| zier curve.
Returns:
Tuple[numpy.ndarray, numpy.ndarray]: The potentially degree-elevated
nodes passed in. | [
"Degree",
"-",
"elevate",
"a",
"curve",
"so",
"two",
"curves",
"have",
"matching",
"degree",
"."
] | python | train |
Neurita/boyle | boyle/utils/strings.py | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/strings.py#L209-L238 | def where_is(strings, pattern, n=1, lookup_func=re.match):
"""Return index of the nth match found of pattern in strings
Parameters
----------
strings: list of str
List of strings
pattern: str
Pattern to be matched
nth: int
Number of times the match must happen to return the item index.
lookup_func: callable
Function to match each item in strings to the pattern, e.g., re.match or re.search.
Returns
-------
index: int
Index of the nth item that matches the pattern.
If there are no n matches will return -1
"""
count = 0
for idx, item in enumerate(strings):
if lookup_func(pattern, item):
count += 1
if count == n:
return idx
return -1 | [
"def",
"where_is",
"(",
"strings",
",",
"pattern",
",",
"n",
"=",
"1",
",",
"lookup_func",
"=",
"re",
".",
"match",
")",
":",
"count",
"=",
"0",
"for",
"idx",
",",
"item",
"in",
"enumerate",
"(",
"strings",
")",
":",
"if",
"lookup_func",
"(",
"pattern",
",",
"item",
")",
":",
"count",
"+=",
"1",
"if",
"count",
"==",
"n",
":",
"return",
"idx",
"return",
"-",
"1"
] | Return index of the nth match found of pattern in strings
Parameters
----------
strings: list of str
List of strings
pattern: str
Pattern to be matched
nth: int
Number of times the match must happen to return the item index.
lookup_func: callable
Function to match each item in strings to the pattern, e.g., re.match or re.search.
Returns
-------
index: int
Index of the nth item that matches the pattern.
If there are no n matches will return -1 | [
"Return",
"index",
"of",
"the",
"nth",
"match",
"found",
"of",
"pattern",
"in",
"strings"
] | python | valid |
dw/mitogen | ansible_mitogen/mixins.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/mixins.py#L404-L432 | def _low_level_execute_command(self, cmd, sudoable=True, in_data=None,
executable=None,
encoding_errors='surrogate_then_replace',
chdir=None):
"""
Override the base implementation by simply calling
target.exec_command() in the target context.
"""
LOG.debug('_low_level_execute_command(%r, in_data=%r, exe=%r, dir=%r)',
cmd, type(in_data), executable, chdir)
if executable is None: # executable defaults to False
executable = self._play_context.executable
if executable:
cmd = executable + ' -c ' + shlex_quote(cmd)
rc, stdout, stderr = self._connection.exec_command(
cmd=cmd,
in_data=in_data,
sudoable=sudoable,
mitogen_chdir=chdir,
)
stdout_text = to_text(stdout, errors=encoding_errors)
return {
'rc': rc,
'stdout': stdout_text,
'stdout_lines': stdout_text.splitlines(),
'stderr': stderr,
} | [
"def",
"_low_level_execute_command",
"(",
"self",
",",
"cmd",
",",
"sudoable",
"=",
"True",
",",
"in_data",
"=",
"None",
",",
"executable",
"=",
"None",
",",
"encoding_errors",
"=",
"'surrogate_then_replace'",
",",
"chdir",
"=",
"None",
")",
":",
"LOG",
".",
"debug",
"(",
"'_low_level_execute_command(%r, in_data=%r, exe=%r, dir=%r)'",
",",
"cmd",
",",
"type",
"(",
"in_data",
")",
",",
"executable",
",",
"chdir",
")",
"if",
"executable",
"is",
"None",
":",
"# executable defaults to False",
"executable",
"=",
"self",
".",
"_play_context",
".",
"executable",
"if",
"executable",
":",
"cmd",
"=",
"executable",
"+",
"' -c '",
"+",
"shlex_quote",
"(",
"cmd",
")",
"rc",
",",
"stdout",
",",
"stderr",
"=",
"self",
".",
"_connection",
".",
"exec_command",
"(",
"cmd",
"=",
"cmd",
",",
"in_data",
"=",
"in_data",
",",
"sudoable",
"=",
"sudoable",
",",
"mitogen_chdir",
"=",
"chdir",
",",
")",
"stdout_text",
"=",
"to_text",
"(",
"stdout",
",",
"errors",
"=",
"encoding_errors",
")",
"return",
"{",
"'rc'",
":",
"rc",
",",
"'stdout'",
":",
"stdout_text",
",",
"'stdout_lines'",
":",
"stdout_text",
".",
"splitlines",
"(",
")",
",",
"'stderr'",
":",
"stderr",
",",
"}"
] | Override the base implementation by simply calling
target.exec_command() in the target context. | [
"Override",
"the",
"base",
"implementation",
"by",
"simply",
"calling",
"target",
".",
"exec_command",
"()",
"in",
"the",
"target",
"context",
"."
] | python | train |
saltstack/salt | salt/modules/glanceng.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glanceng.py#L188-L201 | def update_image_properties(auth=None, **kwargs):
'''
Update properties for an image
CLI Example:
.. code-block:: bash
salt '*' glanceng.update_image_properties name=image1 hw_scsi_model=virtio-scsi hw_disk_bus=scsi
salt '*' glanceng.update_image_properties name=0e4febc2a5ab4f2c8f374b054162506d min_ram=1024
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.update_image_properties(**kwargs) | [
"def",
"update_image_properties",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"update_image_properties",
"(",
"*",
"*",
"kwargs",
")"
] | Update properties for an image
CLI Example:
.. code-block:: bash
salt '*' glanceng.update_image_properties name=image1 hw_scsi_model=virtio-scsi hw_disk_bus=scsi
salt '*' glanceng.update_image_properties name=0e4febc2a5ab4f2c8f374b054162506d min_ram=1024 | [
"Update",
"properties",
"for",
"an",
"image"
] | python | train |
zetaops/zengine | zengine/views/channel_management.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/views/channel_management.py#L113-L123 | def save_new_channel(self):
"""
It saves new channel according to specified channel features.
"""
form_info = self.input['form']
channel = Channel(typ=15, name=form_info['name'],
description=form_info['description'],
owner_id=form_info['owner_id'])
channel.blocking_save()
self.current.task_data['target_channel_key'] = channel.key | [
"def",
"save_new_channel",
"(",
"self",
")",
":",
"form_info",
"=",
"self",
".",
"input",
"[",
"'form'",
"]",
"channel",
"=",
"Channel",
"(",
"typ",
"=",
"15",
",",
"name",
"=",
"form_info",
"[",
"'name'",
"]",
",",
"description",
"=",
"form_info",
"[",
"'description'",
"]",
",",
"owner_id",
"=",
"form_info",
"[",
"'owner_id'",
"]",
")",
"channel",
".",
"blocking_save",
"(",
")",
"self",
".",
"current",
".",
"task_data",
"[",
"'target_channel_key'",
"]",
"=",
"channel",
".",
"key"
] | It saves new channel according to specified channel features. | [
"It",
"saves",
"new",
"channel",
"according",
"to",
"specified",
"channel",
"features",
"."
] | python | train |
briancappello/flask-unchained | flask_unchained/bundles/security/services/security_service.py | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L229-L247 | def send_reset_password_instructions(self, user):
"""
Sends the reset password instructions email for the specified user.
Sends signal `reset_password_instructions_sent`.
:param user: The user to send the instructions to.
"""
token = self.security_utils_service.generate_reset_password_token(user)
reset_link = url_for('security_controller.reset_password',
token=token, _external=True)
self.send_mail(
_('flask_unchained.bundles.security:email_subject.reset_password_instructions'),
to=user.email,
template='security/email/reset_password_instructions.html',
user=user,
reset_link=reset_link)
reset_password_instructions_sent.send(app._get_current_object(),
user=user, token=token) | [
"def",
"send_reset_password_instructions",
"(",
"self",
",",
"user",
")",
":",
"token",
"=",
"self",
".",
"security_utils_service",
".",
"generate_reset_password_token",
"(",
"user",
")",
"reset_link",
"=",
"url_for",
"(",
"'security_controller.reset_password'",
",",
"token",
"=",
"token",
",",
"_external",
"=",
"True",
")",
"self",
".",
"send_mail",
"(",
"_",
"(",
"'flask_unchained.bundles.security:email_subject.reset_password_instructions'",
")",
",",
"to",
"=",
"user",
".",
"email",
",",
"template",
"=",
"'security/email/reset_password_instructions.html'",
",",
"user",
"=",
"user",
",",
"reset_link",
"=",
"reset_link",
")",
"reset_password_instructions_sent",
".",
"send",
"(",
"app",
".",
"_get_current_object",
"(",
")",
",",
"user",
"=",
"user",
",",
"token",
"=",
"token",
")"
] | Sends the reset password instructions email for the specified user.
Sends signal `reset_password_instructions_sent`.
:param user: The user to send the instructions to. | [
"Sends",
"the",
"reset",
"password",
"instructions",
"email",
"for",
"the",
"specified",
"user",
"."
] | python | train |
openfisca/openfisca-core | openfisca_core/simulation_builder.py | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulation_builder.py#L59-L126 | def build_from_entities(self, tax_benefit_system, input_dict):
"""
Build a simulation from a Python dict ``input_dict`` fully specifying entities.
Examples:
>>> simulation_builder.build_from_entities({
'persons': {'Javier': { 'salary': {'2018-11': 2000}}},
'households': {'household': {'parents': ['Javier']}}
})
"""
input_dict = deepcopy(input_dict)
simulation = Simulation(tax_benefit_system, tax_benefit_system.instantiate_entities())
# Register variables so get_variable_entity can find them
for (variable_name, _variable) in tax_benefit_system.variables.items():
self.register_variable(variable_name, simulation.get_variable_population(variable_name).entity)
check_type(input_dict, dict, ['error'])
axes = input_dict.pop('axes', None)
unexpected_entities = [entity for entity in input_dict if entity not in tax_benefit_system.entities_plural()]
if unexpected_entities:
unexpected_entity = unexpected_entities[0]
raise SituationParsingError([unexpected_entity],
''.join([
"Some entities in the situation are not defined in the loaded tax and benefit system.",
"These entities are not found: {0}.",
"The defined entities are: {1}."]
)
.format(
', '.join(unexpected_entities),
', '.join(tax_benefit_system.entities_plural())
)
)
persons_json = input_dict.get(tax_benefit_system.person_entity.plural, None)
if not persons_json:
raise SituationParsingError([tax_benefit_system.person_entity.plural],
'No {0} found. At least one {0} must be defined to run a simulation.'.format(tax_benefit_system.person_entity.key))
persons_ids = self.add_person_entity(simulation.persons.entity, persons_json)
for entity_class in tax_benefit_system.group_entities:
instances_json = input_dict.get(entity_class.plural)
if instances_json is not None:
self.add_group_entity(self.persons_plural, persons_ids, entity_class, instances_json)
else:
self.add_default_group_entity(persons_ids, entity_class)
if axes:
self.axes = axes
self.expand_axes()
try:
self.finalize_variables_init(simulation.persons)
except PeriodMismatchError as e:
self.raise_period_mismatch(simulation.persons.entity, persons_json, e)
for entity_class in tax_benefit_system.group_entities:
try:
population = simulation.populations[entity_class.key]
self.finalize_variables_init(population)
except PeriodMismatchError as e:
self.raise_period_mismatch(population.entity, instances_json, e)
return simulation | [
"def",
"build_from_entities",
"(",
"self",
",",
"tax_benefit_system",
",",
"input_dict",
")",
":",
"input_dict",
"=",
"deepcopy",
"(",
"input_dict",
")",
"simulation",
"=",
"Simulation",
"(",
"tax_benefit_system",
",",
"tax_benefit_system",
".",
"instantiate_entities",
"(",
")",
")",
"# Register variables so get_variable_entity can find them",
"for",
"(",
"variable_name",
",",
"_variable",
")",
"in",
"tax_benefit_system",
".",
"variables",
".",
"items",
"(",
")",
":",
"self",
".",
"register_variable",
"(",
"variable_name",
",",
"simulation",
".",
"get_variable_population",
"(",
"variable_name",
")",
".",
"entity",
")",
"check_type",
"(",
"input_dict",
",",
"dict",
",",
"[",
"'error'",
"]",
")",
"axes",
"=",
"input_dict",
".",
"pop",
"(",
"'axes'",
",",
"None",
")",
"unexpected_entities",
"=",
"[",
"entity",
"for",
"entity",
"in",
"input_dict",
"if",
"entity",
"not",
"in",
"tax_benefit_system",
".",
"entities_plural",
"(",
")",
"]",
"if",
"unexpected_entities",
":",
"unexpected_entity",
"=",
"unexpected_entities",
"[",
"0",
"]",
"raise",
"SituationParsingError",
"(",
"[",
"unexpected_entity",
"]",
",",
"''",
".",
"join",
"(",
"[",
"\"Some entities in the situation are not defined in the loaded tax and benefit system.\"",
",",
"\"These entities are not found: {0}.\"",
",",
"\"The defined entities are: {1}.\"",
"]",
")",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"unexpected_entities",
")",
",",
"', '",
".",
"join",
"(",
"tax_benefit_system",
".",
"entities_plural",
"(",
")",
")",
")",
")",
"persons_json",
"=",
"input_dict",
".",
"get",
"(",
"tax_benefit_system",
".",
"person_entity",
".",
"plural",
",",
"None",
")",
"if",
"not",
"persons_json",
":",
"raise",
"SituationParsingError",
"(",
"[",
"tax_benefit_system",
".",
"person_entity",
".",
"plural",
"]",
",",
"'No {0} found. At least one {0} must be defined to run a simulation.'",
".",
"format",
"(",
"tax_benefit_system",
".",
"person_entity",
".",
"key",
")",
")",
"persons_ids",
"=",
"self",
".",
"add_person_entity",
"(",
"simulation",
".",
"persons",
".",
"entity",
",",
"persons_json",
")",
"for",
"entity_class",
"in",
"tax_benefit_system",
".",
"group_entities",
":",
"instances_json",
"=",
"input_dict",
".",
"get",
"(",
"entity_class",
".",
"plural",
")",
"if",
"instances_json",
"is",
"not",
"None",
":",
"self",
".",
"add_group_entity",
"(",
"self",
".",
"persons_plural",
",",
"persons_ids",
",",
"entity_class",
",",
"instances_json",
")",
"else",
":",
"self",
".",
"add_default_group_entity",
"(",
"persons_ids",
",",
"entity_class",
")",
"if",
"axes",
":",
"self",
".",
"axes",
"=",
"axes",
"self",
".",
"expand_axes",
"(",
")",
"try",
":",
"self",
".",
"finalize_variables_init",
"(",
"simulation",
".",
"persons",
")",
"except",
"PeriodMismatchError",
"as",
"e",
":",
"self",
".",
"raise_period_mismatch",
"(",
"simulation",
".",
"persons",
".",
"entity",
",",
"persons_json",
",",
"e",
")",
"for",
"entity_class",
"in",
"tax_benefit_system",
".",
"group_entities",
":",
"try",
":",
"population",
"=",
"simulation",
".",
"populations",
"[",
"entity_class",
".",
"key",
"]",
"self",
".",
"finalize_variables_init",
"(",
"population",
")",
"except",
"PeriodMismatchError",
"as",
"e",
":",
"self",
".",
"raise_period_mismatch",
"(",
"population",
".",
"entity",
",",
"instances_json",
",",
"e",
")",
"return",
"simulation"
] | Build a simulation from a Python dict ``input_dict`` fully specifying entities.
Examples:
>>> simulation_builder.build_from_entities({
'persons': {'Javier': { 'salary': {'2018-11': 2000}}},
'households': {'household': {'parents': ['Javier']}}
}) | [
"Build",
"a",
"simulation",
"from",
"a",
"Python",
"dict",
"input_dict",
"fully",
"specifying",
"entities",
"."
] | python | train |
ewels/MultiQC | multiqc/modules/picard/VariantCallingMetrics.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/VariantCallingMetrics.py#L184-L230 | def compare_variant_type_plot(data):
""" Return HTML for the Variant Counts barplot """
keys = OrderedDict()
keys['snps'] = {'name': 'SNPs', 'color': '#7cb5ec'}
keys['indels'] = {'name': 'InDels', 'color': '#90ed7d'}
keys['multiallelic_snps'] = {'name': 'multi-allelic SNP', 'color': 'orange'}
keys['complex_indels'] = {'name': 'Complex InDels', 'color': '#8085e9'}
total_variants = dict()
known_variants = dict()
novel_variants = dict()
for s_name, values in data.items():
total_variants[s_name] = {
'snps': values['TOTAL_SNPS'],
'indels': values['TOTAL_INDELS'],
'multiallelic_snps': values['TOTAL_MULTIALLELIC_SNPS'],
'complex_indels': values['TOTAL_COMPLEX_INDELS'],
}
known_variants[s_name] = {
'snps': values['NUM_IN_DB_SNP'],
'indels': int(values['TOTAL_INDELS'])-int(values['NOVEL_INDELS']),
'multiallelic_snps': values['NUM_IN_DB_SNP_MULTIALLELIC'],
'complex_indels': values['NUM_IN_DB_SNP_COMPLEX_INDELS'],
}
novel_variants[s_name] = {
'snps': values['NOVEL_SNPS'],
'indels': values['NOVEL_INDELS'],
'multiallelic_snps': int(values['TOTAL_MULTIALLELIC_SNPS'])-int(values['NUM_IN_DB_SNP_MULTIALLELIC']),
'complex_indels': int(values['TOTAL_COMPLEX_INDELS'])-int(values['NUM_IN_DB_SNP_COMPLEX_INDELS']),
}
plot_conf = {
'id': 'picard_variantCallingMetrics_variant_type',
'title': 'Picard: Variants Called',
'ylab': 'Counts of Variants',
'hide_zero_cats': False,
'data_labels': [
{'name': 'Total'},
{'name': 'Known'},
{'name': 'Novel'}
],
}
return bargraph.plot(data=[total_variants, known_variants, novel_variants],
cats=[keys, keys, keys],
pconfig=plot_conf) | [
"def",
"compare_variant_type_plot",
"(",
"data",
")",
":",
"keys",
"=",
"OrderedDict",
"(",
")",
"keys",
"[",
"'snps'",
"]",
"=",
"{",
"'name'",
":",
"'SNPs'",
",",
"'color'",
":",
"'#7cb5ec'",
"}",
"keys",
"[",
"'indels'",
"]",
"=",
"{",
"'name'",
":",
"'InDels'",
",",
"'color'",
":",
"'#90ed7d'",
"}",
"keys",
"[",
"'multiallelic_snps'",
"]",
"=",
"{",
"'name'",
":",
"'multi-allelic SNP'",
",",
"'color'",
":",
"'orange'",
"}",
"keys",
"[",
"'complex_indels'",
"]",
"=",
"{",
"'name'",
":",
"'Complex InDels'",
",",
"'color'",
":",
"'#8085e9'",
"}",
"total_variants",
"=",
"dict",
"(",
")",
"known_variants",
"=",
"dict",
"(",
")",
"novel_variants",
"=",
"dict",
"(",
")",
"for",
"s_name",
",",
"values",
"in",
"data",
".",
"items",
"(",
")",
":",
"total_variants",
"[",
"s_name",
"]",
"=",
"{",
"'snps'",
":",
"values",
"[",
"'TOTAL_SNPS'",
"]",
",",
"'indels'",
":",
"values",
"[",
"'TOTAL_INDELS'",
"]",
",",
"'multiallelic_snps'",
":",
"values",
"[",
"'TOTAL_MULTIALLELIC_SNPS'",
"]",
",",
"'complex_indels'",
":",
"values",
"[",
"'TOTAL_COMPLEX_INDELS'",
"]",
",",
"}",
"known_variants",
"[",
"s_name",
"]",
"=",
"{",
"'snps'",
":",
"values",
"[",
"'NUM_IN_DB_SNP'",
"]",
",",
"'indels'",
":",
"int",
"(",
"values",
"[",
"'TOTAL_INDELS'",
"]",
")",
"-",
"int",
"(",
"values",
"[",
"'NOVEL_INDELS'",
"]",
")",
",",
"'multiallelic_snps'",
":",
"values",
"[",
"'NUM_IN_DB_SNP_MULTIALLELIC'",
"]",
",",
"'complex_indels'",
":",
"values",
"[",
"'NUM_IN_DB_SNP_COMPLEX_INDELS'",
"]",
",",
"}",
"novel_variants",
"[",
"s_name",
"]",
"=",
"{",
"'snps'",
":",
"values",
"[",
"'NOVEL_SNPS'",
"]",
",",
"'indels'",
":",
"values",
"[",
"'NOVEL_INDELS'",
"]",
",",
"'multiallelic_snps'",
":",
"int",
"(",
"values",
"[",
"'TOTAL_MULTIALLELIC_SNPS'",
"]",
")",
"-",
"int",
"(",
"values",
"[",
"'NUM_IN_DB_SNP_MULTIALLELIC'",
"]",
")",
",",
"'complex_indels'",
":",
"int",
"(",
"values",
"[",
"'TOTAL_COMPLEX_INDELS'",
"]",
")",
"-",
"int",
"(",
"values",
"[",
"'NUM_IN_DB_SNP_COMPLEX_INDELS'",
"]",
")",
",",
"}",
"plot_conf",
"=",
"{",
"'id'",
":",
"'picard_variantCallingMetrics_variant_type'",
",",
"'title'",
":",
"'Picard: Variants Called'",
",",
"'ylab'",
":",
"'Counts of Variants'",
",",
"'hide_zero_cats'",
":",
"False",
",",
"'data_labels'",
":",
"[",
"{",
"'name'",
":",
"'Total'",
"}",
",",
"{",
"'name'",
":",
"'Known'",
"}",
",",
"{",
"'name'",
":",
"'Novel'",
"}",
"]",
",",
"}",
"return",
"bargraph",
".",
"plot",
"(",
"data",
"=",
"[",
"total_variants",
",",
"known_variants",
",",
"novel_variants",
"]",
",",
"cats",
"=",
"[",
"keys",
",",
"keys",
",",
"keys",
"]",
",",
"pconfig",
"=",
"plot_conf",
")"
] | Return HTML for the Variant Counts barplot | [
"Return",
"HTML",
"for",
"the",
"Variant",
"Counts",
"barplot"
] | python | train |
hubo1016/vlcp | vlcp/utils/flowupdater.py | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/utils/flowupdater.py#L114-L127 | async def _dataobject_update_detect(self, _initialkeys, _savedresult):
"""
Coroutine that wait for retrieved value update notification
"""
def expr(newvalues, updatedvalues):
if any(v.getkey() in _initialkeys for v in updatedvalues if v is not None):
return True
else:
return self.shouldupdate(newvalues, updatedvalues)
while True:
updatedvalues, _ = await multiwaitif(_savedresult, self, expr, True)
if not self._updatedset:
self.scheduler.emergesend(FlowUpdaterNotification(self, FlowUpdaterNotification.DATAUPDATED))
self._updatedset.update(updatedvalues) | [
"async",
"def",
"_dataobject_update_detect",
"(",
"self",
",",
"_initialkeys",
",",
"_savedresult",
")",
":",
"def",
"expr",
"(",
"newvalues",
",",
"updatedvalues",
")",
":",
"if",
"any",
"(",
"v",
".",
"getkey",
"(",
")",
"in",
"_initialkeys",
"for",
"v",
"in",
"updatedvalues",
"if",
"v",
"is",
"not",
"None",
")",
":",
"return",
"True",
"else",
":",
"return",
"self",
".",
"shouldupdate",
"(",
"newvalues",
",",
"updatedvalues",
")",
"while",
"True",
":",
"updatedvalues",
",",
"_",
"=",
"await",
"multiwaitif",
"(",
"_savedresult",
",",
"self",
",",
"expr",
",",
"True",
")",
"if",
"not",
"self",
".",
"_updatedset",
":",
"self",
".",
"scheduler",
".",
"emergesend",
"(",
"FlowUpdaterNotification",
"(",
"self",
",",
"FlowUpdaterNotification",
".",
"DATAUPDATED",
")",
")",
"self",
".",
"_updatedset",
".",
"update",
"(",
"updatedvalues",
")"
] | Coroutine that wait for retrieved value update notification | [
"Coroutine",
"that",
"wait",
"for",
"retrieved",
"value",
"update",
"notification"
] | python | train |
LogicalDash/LiSE | ELiDE/ELiDE/charmenu.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/charmenu.py#L140-L158 | def toggle_reciprocal(self):
"""Flip my ``reciprocal_portal`` boolean, and draw (or stop drawing)
an extra arrow on the appropriate button to indicate the
fact.
"""
self.screen.boardview.reciprocal_portal = not self.screen.boardview.reciprocal_portal
if self.screen.boardview.reciprocal_portal:
assert(self.revarrow is None)
self.revarrow = ArrowWidget(
board=self.screen.boardview.board,
origin=self.ids.emptyright,
destination=self.ids.emptyleft
)
self.ids.portaladdbut.add_widget(self.revarrow)
else:
if hasattr(self, 'revarrow'):
self.ids.portaladdbut.remove_widget(self.revarrow)
self.revarrow = None | [
"def",
"toggle_reciprocal",
"(",
"self",
")",
":",
"self",
".",
"screen",
".",
"boardview",
".",
"reciprocal_portal",
"=",
"not",
"self",
".",
"screen",
".",
"boardview",
".",
"reciprocal_portal",
"if",
"self",
".",
"screen",
".",
"boardview",
".",
"reciprocal_portal",
":",
"assert",
"(",
"self",
".",
"revarrow",
"is",
"None",
")",
"self",
".",
"revarrow",
"=",
"ArrowWidget",
"(",
"board",
"=",
"self",
".",
"screen",
".",
"boardview",
".",
"board",
",",
"origin",
"=",
"self",
".",
"ids",
".",
"emptyright",
",",
"destination",
"=",
"self",
".",
"ids",
".",
"emptyleft",
")",
"self",
".",
"ids",
".",
"portaladdbut",
".",
"add_widget",
"(",
"self",
".",
"revarrow",
")",
"else",
":",
"if",
"hasattr",
"(",
"self",
",",
"'revarrow'",
")",
":",
"self",
".",
"ids",
".",
"portaladdbut",
".",
"remove_widget",
"(",
"self",
".",
"revarrow",
")",
"self",
".",
"revarrow",
"=",
"None"
] | Flip my ``reciprocal_portal`` boolean, and draw (or stop drawing)
an extra arrow on the appropriate button to indicate the
fact. | [
"Flip",
"my",
"reciprocal_portal",
"boolean",
"and",
"draw",
"(",
"or",
"stop",
"drawing",
")",
"an",
"extra",
"arrow",
"on",
"the",
"appropriate",
"button",
"to",
"indicate",
"the",
"fact",
"."
] | python | train |
h2oai/h2o-3 | h2o-py/h2o/utils/debugging.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/utils/debugging.py#L268-L304 | def _find_function_from_code(frame, code):
"""
Given a frame and a compiled function code, find the corresponding function object within the frame.
This function addresses the following problem: when handling a stacktrace, we receive information about
which piece of code was being executed in the form of a CodeType object. That objects contains function name,
file name, line number, and the compiled bytecode. What it *doesn't* contain is the function object itself.
So this utility function aims at locating this function object, and it does so by searching through objects
in the preceding local frame (i.e. the frame where the function was called from). We expect that the function
should usually exist there -- either by itself, or as a method on one of the objects.
:param types.FrameType frame: local frame where the function ought to be found somewhere.
:param types.CodeType code: the compiled code of the function to look for.
:returns: the function object, or None if not found.
"""
def find_code(iterable, depth=0):
if depth > 3: return # Avoid potential infinite loops, or generally objects that are too deep.
for item in iterable:
if item is None: continue
found = None
if hasattr(item, "__code__") and item.__code__ == code:
found = item
elif isinstance(item, type) or isinstance(item, ModuleType): # class / module
try:
found = find_code((getattr(item, n, None) for n in dir(item)), depth + 1)
except Exception:
# Sometimes merely getting module's attributes may cause an exception. For example :mod:`six.moves`
# is such an offender...
continue
elif isinstance(item, (list, tuple, set)):
found = find_code(item, depth + 1)
elif isinstance(item, dict):
found = find_code(item.values(), depth + 1)
if found: return found
return find_code(frame.f_locals.values()) or find_code(frame.f_globals.values()) | [
"def",
"_find_function_from_code",
"(",
"frame",
",",
"code",
")",
":",
"def",
"find_code",
"(",
"iterable",
",",
"depth",
"=",
"0",
")",
":",
"if",
"depth",
">",
"3",
":",
"return",
"# Avoid potential infinite loops, or generally objects that are too deep.",
"for",
"item",
"in",
"iterable",
":",
"if",
"item",
"is",
"None",
":",
"continue",
"found",
"=",
"None",
"if",
"hasattr",
"(",
"item",
",",
"\"__code__\"",
")",
"and",
"item",
".",
"__code__",
"==",
"code",
":",
"found",
"=",
"item",
"elif",
"isinstance",
"(",
"item",
",",
"type",
")",
"or",
"isinstance",
"(",
"item",
",",
"ModuleType",
")",
":",
"# class / module",
"try",
":",
"found",
"=",
"find_code",
"(",
"(",
"getattr",
"(",
"item",
",",
"n",
",",
"None",
")",
"for",
"n",
"in",
"dir",
"(",
"item",
")",
")",
",",
"depth",
"+",
"1",
")",
"except",
"Exception",
":",
"# Sometimes merely getting module's attributes may cause an exception. For example :mod:`six.moves`",
"# is such an offender...",
"continue",
"elif",
"isinstance",
"(",
"item",
",",
"(",
"list",
",",
"tuple",
",",
"set",
")",
")",
":",
"found",
"=",
"find_code",
"(",
"item",
",",
"depth",
"+",
"1",
")",
"elif",
"isinstance",
"(",
"item",
",",
"dict",
")",
":",
"found",
"=",
"find_code",
"(",
"item",
".",
"values",
"(",
")",
",",
"depth",
"+",
"1",
")",
"if",
"found",
":",
"return",
"found",
"return",
"find_code",
"(",
"frame",
".",
"f_locals",
".",
"values",
"(",
")",
")",
"or",
"find_code",
"(",
"frame",
".",
"f_globals",
".",
"values",
"(",
")",
")"
] | Given a frame and a compiled function code, find the corresponding function object within the frame.
This function addresses the following problem: when handling a stacktrace, we receive information about
which piece of code was being executed in the form of a CodeType object. That objects contains function name,
file name, line number, and the compiled bytecode. What it *doesn't* contain is the function object itself.
So this utility function aims at locating this function object, and it does so by searching through objects
in the preceding local frame (i.e. the frame where the function was called from). We expect that the function
should usually exist there -- either by itself, or as a method on one of the objects.
:param types.FrameType frame: local frame where the function ought to be found somewhere.
:param types.CodeType code: the compiled code of the function to look for.
:returns: the function object, or None if not found. | [
"Given",
"a",
"frame",
"and",
"a",
"compiled",
"function",
"code",
"find",
"the",
"corresponding",
"function",
"object",
"within",
"the",
"frame",
"."
] | python | test |
sixty-north/cosmic-ray | src/cosmic_ray/plugins.py | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/plugins.py#L78-L87 | def get_execution_engine(name):
"""Get the execution engine by name."""
manager = driver.DriverManager(
namespace='cosmic_ray.execution_engines',
name=name,
invoke_on_load=True,
on_load_failure_callback=_log_extension_loading_failure,
)
return manager.driver | [
"def",
"get_execution_engine",
"(",
"name",
")",
":",
"manager",
"=",
"driver",
".",
"DriverManager",
"(",
"namespace",
"=",
"'cosmic_ray.execution_engines'",
",",
"name",
"=",
"name",
",",
"invoke_on_load",
"=",
"True",
",",
"on_load_failure_callback",
"=",
"_log_extension_loading_failure",
",",
")",
"return",
"manager",
".",
"driver"
] | Get the execution engine by name. | [
"Get",
"the",
"execution",
"engine",
"by",
"name",
"."
] | python | train |
HumanCellAtlas/dcp-cli | hca/util/__init__.py | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/util/__init__.py#L335-L344 | def refresh_swagger(self):
"""
Manually refresh the swagger document. This can help resolve errors communicate with the API.
"""
try:
os.remove(self._get_swagger_filename(self.swagger_url))
except EnvironmentError as e:
logger.warn(os.strerror(e.errno))
else:
self.__init__() | [
"def",
"refresh_swagger",
"(",
"self",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"self",
".",
"_get_swagger_filename",
"(",
"self",
".",
"swagger_url",
")",
")",
"except",
"EnvironmentError",
"as",
"e",
":",
"logger",
".",
"warn",
"(",
"os",
".",
"strerror",
"(",
"e",
".",
"errno",
")",
")",
"else",
":",
"self",
".",
"__init__",
"(",
")"
] | Manually refresh the swagger document. This can help resolve errors communicate with the API. | [
"Manually",
"refresh",
"the",
"swagger",
"document",
".",
"This",
"can",
"help",
"resolve",
"errors",
"communicate",
"with",
"the",
"API",
"."
] | python | train |
senaite/senaite.core | bika/lims/browser/partition_magic.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/partition_magic.py#L169-L174 | def get_preservation_data(self):
"""Returns a list of Preservation data
"""
for obj in self.get_preservations():
info = self.get_base_info(obj)
yield info | [
"def",
"get_preservation_data",
"(",
"self",
")",
":",
"for",
"obj",
"in",
"self",
".",
"get_preservations",
"(",
")",
":",
"info",
"=",
"self",
".",
"get_base_info",
"(",
"obj",
")",
"yield",
"info"
] | Returns a list of Preservation data | [
"Returns",
"a",
"list",
"of",
"Preservation",
"data"
] | python | train |
markchil/gptools | gptools/gaussian_process.py | https://github.com/markchil/gptools/blob/225db52bfe6baef1516529ad22177aa2cf7b71e4/gptools/gaussian_process.py#L247-L253 | def hyperprior(self):
"""Combined hyperprior for the kernel, noise kernel and (if present) mean function.
"""
hp = self.k.hyperprior * self.noise_k.hyperprior
if self.mu is not None:
hp *= self.mu.hyperprior
return hp | [
"def",
"hyperprior",
"(",
"self",
")",
":",
"hp",
"=",
"self",
".",
"k",
".",
"hyperprior",
"*",
"self",
".",
"noise_k",
".",
"hyperprior",
"if",
"self",
".",
"mu",
"is",
"not",
"None",
":",
"hp",
"*=",
"self",
".",
"mu",
".",
"hyperprior",
"return",
"hp"
] | Combined hyperprior for the kernel, noise kernel and (if present) mean function. | [
"Combined",
"hyperprior",
"for",
"the",
"kernel",
"noise",
"kernel",
"and",
"(",
"if",
"present",
")",
"mean",
"function",
"."
] | python | train |
openstack/networking-arista | networking_arista/ml2/security_groups/arista_security_groups.py | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/security_groups/arista_security_groups.py#L87-L100 | def _valid_baremetal_port(port):
"""Check if port is a baremetal port with exactly one security group"""
if port.get(portbindings.VNIC_TYPE) != portbindings.VNIC_BAREMETAL:
return False
sgs = port.get('security_groups', [])
if len(sgs) == 0:
# Nothing to do
return False
if len(port.get('security_groups', [])) > 1:
LOG.warning('SG provisioning failed for %(port)s. Only one '
'SG may be applied per port.',
{'port': port['id']})
return False
return True | [
"def",
"_valid_baremetal_port",
"(",
"port",
")",
":",
"if",
"port",
".",
"get",
"(",
"portbindings",
".",
"VNIC_TYPE",
")",
"!=",
"portbindings",
".",
"VNIC_BAREMETAL",
":",
"return",
"False",
"sgs",
"=",
"port",
".",
"get",
"(",
"'security_groups'",
",",
"[",
"]",
")",
"if",
"len",
"(",
"sgs",
")",
"==",
"0",
":",
"# Nothing to do",
"return",
"False",
"if",
"len",
"(",
"port",
".",
"get",
"(",
"'security_groups'",
",",
"[",
"]",
")",
")",
">",
"1",
":",
"LOG",
".",
"warning",
"(",
"'SG provisioning failed for %(port)s. Only one '",
"'SG may be applied per port.'",
",",
"{",
"'port'",
":",
"port",
"[",
"'id'",
"]",
"}",
")",
"return",
"False",
"return",
"True"
] | Check if port is a baremetal port with exactly one security group | [
"Check",
"if",
"port",
"is",
"a",
"baremetal",
"port",
"with",
"exactly",
"one",
"security",
"group"
] | python | train |
liftoff/pyminifier | pyminifier/minification.py | https://github.com/liftoff/pyminifier/blob/087ea7b0c8c964f1f907c3f350f5ce281798db86/pyminifier/minification.py#L281-L333 | def dedent(source, use_tabs=False):
"""
Minimizes indentation to save precious bytes. Optionally, *use_tabs*
may be specified if you want to use tabulators (\t) instead of spaces.
Example::
def foo(bar):
test = "This is a test"
Will become::
def foo(bar):
test = "This is a test"
"""
if use_tabs:
indent_char = '\t'
else:
indent_char = ' '
io_obj = io.StringIO(source)
out = ""
last_lineno = -1
last_col = 0
prev_start_line = 0
indentation = ""
indentation_level = 0
for i, tok in enumerate(tokenize.generate_tokens(io_obj.readline)):
token_type = tok[0]
token_string = tok[1]
start_line, start_col = tok[2]
end_line, end_col = tok[3]
if start_line > last_lineno:
last_col = 0
if token_type == tokenize.INDENT:
indentation_level += 1
continue
if token_type == tokenize.DEDENT:
indentation_level -= 1
continue
indentation = indent_char * indentation_level
if start_line > prev_start_line:
if token_string in (',', '.'):
out += str(token_string)
else:
out += indentation + str(token_string)
elif start_col > last_col:
out += indent_char + str(token_string)
else:
out += token_string
prev_start_line = start_line
last_col = end_col
last_lineno = end_line
return out | [
"def",
"dedent",
"(",
"source",
",",
"use_tabs",
"=",
"False",
")",
":",
"if",
"use_tabs",
":",
"indent_char",
"=",
"'\\t'",
"else",
":",
"indent_char",
"=",
"' '",
"io_obj",
"=",
"io",
".",
"StringIO",
"(",
"source",
")",
"out",
"=",
"\"\"",
"last_lineno",
"=",
"-",
"1",
"last_col",
"=",
"0",
"prev_start_line",
"=",
"0",
"indentation",
"=",
"\"\"",
"indentation_level",
"=",
"0",
"for",
"i",
",",
"tok",
"in",
"enumerate",
"(",
"tokenize",
".",
"generate_tokens",
"(",
"io_obj",
".",
"readline",
")",
")",
":",
"token_type",
"=",
"tok",
"[",
"0",
"]",
"token_string",
"=",
"tok",
"[",
"1",
"]",
"start_line",
",",
"start_col",
"=",
"tok",
"[",
"2",
"]",
"end_line",
",",
"end_col",
"=",
"tok",
"[",
"3",
"]",
"if",
"start_line",
">",
"last_lineno",
":",
"last_col",
"=",
"0",
"if",
"token_type",
"==",
"tokenize",
".",
"INDENT",
":",
"indentation_level",
"+=",
"1",
"continue",
"if",
"token_type",
"==",
"tokenize",
".",
"DEDENT",
":",
"indentation_level",
"-=",
"1",
"continue",
"indentation",
"=",
"indent_char",
"*",
"indentation_level",
"if",
"start_line",
">",
"prev_start_line",
":",
"if",
"token_string",
"in",
"(",
"','",
",",
"'.'",
")",
":",
"out",
"+=",
"str",
"(",
"token_string",
")",
"else",
":",
"out",
"+=",
"indentation",
"+",
"str",
"(",
"token_string",
")",
"elif",
"start_col",
">",
"last_col",
":",
"out",
"+=",
"indent_char",
"+",
"str",
"(",
"token_string",
")",
"else",
":",
"out",
"+=",
"token_string",
"prev_start_line",
"=",
"start_line",
"last_col",
"=",
"end_col",
"last_lineno",
"=",
"end_line",
"return",
"out"
] | Minimizes indentation to save precious bytes. Optionally, *use_tabs*
may be specified if you want to use tabulators (\t) instead of spaces.
Example::
def foo(bar):
test = "This is a test"
Will become::
def foo(bar):
test = "This is a test" | [
"Minimizes",
"indentation",
"to",
"save",
"precious",
"bytes",
".",
"Optionally",
"*",
"use_tabs",
"*",
"may",
"be",
"specified",
"if",
"you",
"want",
"to",
"use",
"tabulators",
"(",
"\\",
"t",
")",
"instead",
"of",
"spaces",
"."
] | python | train |
sorgerlab/indra | indra/assemblers/pysb/assembler.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/assembler.py#L792-L812 | def save_rst(self, file_name='pysb_model.rst', module_name='pysb_module'):
"""Save the assembled model as an RST file for literate modeling.
Parameters
----------
file_name : Optional[str]
The name of the file to save the RST in.
Default: pysb_model.rst
module_name : Optional[str]
The name of the python function defining the module.
Default: pysb_module
"""
if self.model is not None:
with open(file_name, 'wt') as fh:
fh.write('.. _%s:\n\n' % module_name)
fh.write('Module\n======\n\n')
fh.write('INDRA-assembled model\n---------------------\n\n')
fh.write('::\n\n')
model_str = pysb.export.export(self.model, 'pysb_flat')
model_str = '\t' + model_str.replace('\n', '\n\t')
fh.write(model_str) | [
"def",
"save_rst",
"(",
"self",
",",
"file_name",
"=",
"'pysb_model.rst'",
",",
"module_name",
"=",
"'pysb_module'",
")",
":",
"if",
"self",
".",
"model",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"file_name",
",",
"'wt'",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"'.. _%s:\\n\\n'",
"%",
"module_name",
")",
"fh",
".",
"write",
"(",
"'Module\\n======\\n\\n'",
")",
"fh",
".",
"write",
"(",
"'INDRA-assembled model\\n---------------------\\n\\n'",
")",
"fh",
".",
"write",
"(",
"'::\\n\\n'",
")",
"model_str",
"=",
"pysb",
".",
"export",
".",
"export",
"(",
"self",
".",
"model",
",",
"'pysb_flat'",
")",
"model_str",
"=",
"'\\t'",
"+",
"model_str",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n\\t'",
")",
"fh",
".",
"write",
"(",
"model_str",
")"
] | Save the assembled model as an RST file for literate modeling.
Parameters
----------
file_name : Optional[str]
The name of the file to save the RST in.
Default: pysb_model.rst
module_name : Optional[str]
The name of the python function defining the module.
Default: pysb_module | [
"Save",
"the",
"assembled",
"model",
"as",
"an",
"RST",
"file",
"for",
"literate",
"modeling",
"."
] | python | train |
eandersson/amqpstorm | amqpstorm/io.py | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L152-L166 | def _get_socket_addresses(self):
"""Get Socket address information.
:rtype: list
"""
family = socket.AF_UNSPEC
if not socket.has_ipv6:
family = socket.AF_INET
try:
addresses = socket.getaddrinfo(self._parameters['hostname'],
self._parameters['port'], family,
socket.SOCK_STREAM)
except socket.gaierror as why:
raise AMQPConnectionError(why)
return addresses | [
"def",
"_get_socket_addresses",
"(",
"self",
")",
":",
"family",
"=",
"socket",
".",
"AF_UNSPEC",
"if",
"not",
"socket",
".",
"has_ipv6",
":",
"family",
"=",
"socket",
".",
"AF_INET",
"try",
":",
"addresses",
"=",
"socket",
".",
"getaddrinfo",
"(",
"self",
".",
"_parameters",
"[",
"'hostname'",
"]",
",",
"self",
".",
"_parameters",
"[",
"'port'",
"]",
",",
"family",
",",
"socket",
".",
"SOCK_STREAM",
")",
"except",
"socket",
".",
"gaierror",
"as",
"why",
":",
"raise",
"AMQPConnectionError",
"(",
"why",
")",
"return",
"addresses"
] | Get Socket address information.
:rtype: list | [
"Get",
"Socket",
"address",
"information",
"."
] | python | train |
shaypal5/utilitime | utilitime/timestamp/timestamp.py | https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/timestamp/timestamp.py#L12-L32 | def timestamp_to_local_time(timestamp, timezone_name):
"""Convert epoch timestamp to a localized Delorean datetime object.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
Returns
-------
delorean.Delorean
A localized Delorean datetime object.
"""
# first convert timestamp to UTC
utc_time = datetime.utcfromtimestamp(float(timestamp))
delo = Delorean(utc_time, timezone='UTC')
# shift d according to input timezone
localized_d = delo.shift(timezone_name)
return localized_d | [
"def",
"timestamp_to_local_time",
"(",
"timestamp",
",",
"timezone_name",
")",
":",
"# first convert timestamp to UTC",
"utc_time",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"float",
"(",
"timestamp",
")",
")",
"delo",
"=",
"Delorean",
"(",
"utc_time",
",",
"timezone",
"=",
"'UTC'",
")",
"# shift d according to input timezone",
"localized_d",
"=",
"delo",
".",
"shift",
"(",
"timezone_name",
")",
"return",
"localized_d"
] | Convert epoch timestamp to a localized Delorean datetime object.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
Returns
-------
delorean.Delorean
A localized Delorean datetime object. | [
"Convert",
"epoch",
"timestamp",
"to",
"a",
"localized",
"Delorean",
"datetime",
"object",
"."
] | python | train |
mozilla-b2g/fxos-certsuite | mcts/utils/handlers/adb_b2g.py | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/utils/handlers/adb_b2g.py#L131-L189 | def wait_for_device_ready(self, timeout=None, wait_polling_interval=None, after_first=None):
"""Wait for the device to become ready for reliable interaction via adb.
NOTE: if the device is *already* ready this method will timeout.
:param timeout: Maximum time to wait for the device to become ready
:param wait_polling_interval: Interval at which to poll for device readiness.
:param after_first: A function to run after first polling for device
readiness. This allows use cases such as stopping b2g
setting the unready state, and then restarting b2g.
"""
if timeout is None:
timeout = self._timeout
if wait_polling_interval is None:
wait_polling_interval = self._wait_polling_interval
self._logger.info("Waiting for device to become ready")
profiles = self.get_profiles()
assert len(profiles) == 1
profile_dir = profiles.itervalues().next()
prefs_file = posixpath.normpath(profile_dir + "/prefs.js")
current_date = int(self.shell_output('date +\"%s\"'))
set_date = current_date - (365 * 24 * 3600 + 24 * 3600 + 3600 + 60 + 1)
try:
self.shell_output("touch -t %i %s" % (set_date, prefs_file))
except adb.ADBError:
# See Bug 1092383, the format for the touch command
# has changed for flame-kk builds.
set_date = datetime.datetime.fromtimestamp(set_date)
self.shell_output("touch -t %s %s" %
(set_date.strftime('%Y%m%d.%H%M%S'),
prefs_file))
def prefs_modified():
times = [None, None]
def inner():
try:
listing = self.shell_output("ls -l %s" % (prefs_file))
mode, user, group, size, date, time, name = listing.split(None, 6)
mtime = "%s %s" % (date, time)
except:
return False
if times[0] is None:
times[0] = mtime
else:
times[1] = mtime
if times[1] != times[0]:
return True
return False
return inner
poll_wait(prefs_modified(), timeout=timeout,
polling_interval=wait_polling_interval, after_first=after_first) | [
"def",
"wait_for_device_ready",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"wait_polling_interval",
"=",
"None",
",",
"after_first",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"self",
".",
"_timeout",
"if",
"wait_polling_interval",
"is",
"None",
":",
"wait_polling_interval",
"=",
"self",
".",
"_wait_polling_interval",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Waiting for device to become ready\"",
")",
"profiles",
"=",
"self",
".",
"get_profiles",
"(",
")",
"assert",
"len",
"(",
"profiles",
")",
"==",
"1",
"profile_dir",
"=",
"profiles",
".",
"itervalues",
"(",
")",
".",
"next",
"(",
")",
"prefs_file",
"=",
"posixpath",
".",
"normpath",
"(",
"profile_dir",
"+",
"\"/prefs.js\"",
")",
"current_date",
"=",
"int",
"(",
"self",
".",
"shell_output",
"(",
"'date +\\\"%s\\\"'",
")",
")",
"set_date",
"=",
"current_date",
"-",
"(",
"365",
"*",
"24",
"*",
"3600",
"+",
"24",
"*",
"3600",
"+",
"3600",
"+",
"60",
"+",
"1",
")",
"try",
":",
"self",
".",
"shell_output",
"(",
"\"touch -t %i %s\"",
"%",
"(",
"set_date",
",",
"prefs_file",
")",
")",
"except",
"adb",
".",
"ADBError",
":",
"# See Bug 1092383, the format for the touch command",
"# has changed for flame-kk builds.",
"set_date",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"set_date",
")",
"self",
".",
"shell_output",
"(",
"\"touch -t %s %s\"",
"%",
"(",
"set_date",
".",
"strftime",
"(",
"'%Y%m%d.%H%M%S'",
")",
",",
"prefs_file",
")",
")",
"def",
"prefs_modified",
"(",
")",
":",
"times",
"=",
"[",
"None",
",",
"None",
"]",
"def",
"inner",
"(",
")",
":",
"try",
":",
"listing",
"=",
"self",
".",
"shell_output",
"(",
"\"ls -l %s\"",
"%",
"(",
"prefs_file",
")",
")",
"mode",
",",
"user",
",",
"group",
",",
"size",
",",
"date",
",",
"time",
",",
"name",
"=",
"listing",
".",
"split",
"(",
"None",
",",
"6",
")",
"mtime",
"=",
"\"%s %s\"",
"%",
"(",
"date",
",",
"time",
")",
"except",
":",
"return",
"False",
"if",
"times",
"[",
"0",
"]",
"is",
"None",
":",
"times",
"[",
"0",
"]",
"=",
"mtime",
"else",
":",
"times",
"[",
"1",
"]",
"=",
"mtime",
"if",
"times",
"[",
"1",
"]",
"!=",
"times",
"[",
"0",
"]",
":",
"return",
"True",
"return",
"False",
"return",
"inner",
"poll_wait",
"(",
"prefs_modified",
"(",
")",
",",
"timeout",
"=",
"timeout",
",",
"polling_interval",
"=",
"wait_polling_interval",
",",
"after_first",
"=",
"after_first",
")"
] | Wait for the device to become ready for reliable interaction via adb.
NOTE: if the device is *already* ready this method will timeout.
:param timeout: Maximum time to wait for the device to become ready
:param wait_polling_interval: Interval at which to poll for device readiness.
:param after_first: A function to run after first polling for device
readiness. This allows use cases such as stopping b2g
setting the unready state, and then restarting b2g. | [
"Wait",
"for",
"the",
"device",
"to",
"become",
"ready",
"for",
"reliable",
"interaction",
"via",
"adb",
".",
"NOTE",
":",
"if",
"the",
"device",
"is",
"*",
"already",
"*",
"ready",
"this",
"method",
"will",
"timeout",
"."
] | python | train |
niemasd/TreeSwift | treeswift/Node.py | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Node.py#L336-L349 | def traverse_preorder(self, leaves=True, internal=True):
'''Perform a preorder traversal starting at this ``Node`` object
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
'''
s = deque(); s.append(self)
while len(s) != 0:
n = s.pop()
if (leaves and n.is_leaf()) or (internal and not n.is_leaf()):
yield n
s.extend(n.children) | [
"def",
"traverse_preorder",
"(",
"self",
",",
"leaves",
"=",
"True",
",",
"internal",
"=",
"True",
")",
":",
"s",
"=",
"deque",
"(",
")",
"s",
".",
"append",
"(",
"self",
")",
"while",
"len",
"(",
"s",
")",
"!=",
"0",
":",
"n",
"=",
"s",
".",
"pop",
"(",
")",
"if",
"(",
"leaves",
"and",
"n",
".",
"is_leaf",
"(",
")",
")",
"or",
"(",
"internal",
"and",
"not",
"n",
".",
"is_leaf",
"(",
")",
")",
":",
"yield",
"n",
"s",
".",
"extend",
"(",
"n",
".",
"children",
")"
] | Perform a preorder traversal starting at this ``Node`` object
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False`` | [
"Perform",
"a",
"preorder",
"traversal",
"starting",
"at",
"this",
"Node",
"object"
] | python | train |
pantsbuild/pants | contrib/python/src/python/pants/contrib/python/checks/checker/common.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/python/src/python/pants/contrib/python/checks/checker/common.py#L148-L159 | def from_statement(cls, statement, filename='<expr>'):
"""A helper to construct a PythonFile from a triple-quoted string, for testing.
:param statement: Python file contents
:return: Instance of PythonFile
"""
lines = textwrap.dedent(statement).split('\n')
if lines and not lines[0]: # Remove the initial empty line, which is an artifact of dedent.
lines = lines[1:]
blob = '\n'.join(lines).encode('utf-8')
tree = cls._parse(blob, filename)
return cls(blob=blob, tree=tree, root=None, filename=filename) | [
"def",
"from_statement",
"(",
"cls",
",",
"statement",
",",
"filename",
"=",
"'<expr>'",
")",
":",
"lines",
"=",
"textwrap",
".",
"dedent",
"(",
"statement",
")",
".",
"split",
"(",
"'\\n'",
")",
"if",
"lines",
"and",
"not",
"lines",
"[",
"0",
"]",
":",
"# Remove the initial empty line, which is an artifact of dedent.",
"lines",
"=",
"lines",
"[",
"1",
":",
"]",
"blob",
"=",
"'\\n'",
".",
"join",
"(",
"lines",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"tree",
"=",
"cls",
".",
"_parse",
"(",
"blob",
",",
"filename",
")",
"return",
"cls",
"(",
"blob",
"=",
"blob",
",",
"tree",
"=",
"tree",
",",
"root",
"=",
"None",
",",
"filename",
"=",
"filename",
")"
] | A helper to construct a PythonFile from a triple-quoted string, for testing.
:param statement: Python file contents
:return: Instance of PythonFile | [
"A",
"helper",
"to",
"construct",
"a",
"PythonFile",
"from",
"a",
"triple",
"-",
"quoted",
"string",
"for",
"testing",
".",
":",
"param",
"statement",
":",
"Python",
"file",
"contents",
":",
"return",
":",
"Instance",
"of",
"PythonFile"
] | python | train |
theiviaxx/python-perforce | perforce/models.py | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L320-L345 | def findChangelist(self, description=None):
"""Gets or creates a Changelist object with a description
:param description: The description to set or lookup
:type description: str
:returns: :class:`.Changelist`
"""
if description is None:
change = Default(self)
else:
if isinstance(description, six.integer_types):
change = Changelist(description, self)
else:
pending = self.run(['changes', '-l', '-s', 'pending', '-c', str(self._client), '-u', self._user])
for cl in pending:
if cl['desc'].strip() == description.strip():
LOGGER.debug('Changelist found: {}'.format(cl['change']))
change = Changelist(int(cl['change']), self)
break
else:
LOGGER.debug('No changelist found, creating one')
change = Changelist.create(description, self)
change.client = self._client
change.save()
return change | [
"def",
"findChangelist",
"(",
"self",
",",
"description",
"=",
"None",
")",
":",
"if",
"description",
"is",
"None",
":",
"change",
"=",
"Default",
"(",
"self",
")",
"else",
":",
"if",
"isinstance",
"(",
"description",
",",
"six",
".",
"integer_types",
")",
":",
"change",
"=",
"Changelist",
"(",
"description",
",",
"self",
")",
"else",
":",
"pending",
"=",
"self",
".",
"run",
"(",
"[",
"'changes'",
",",
"'-l'",
",",
"'-s'",
",",
"'pending'",
",",
"'-c'",
",",
"str",
"(",
"self",
".",
"_client",
")",
",",
"'-u'",
",",
"self",
".",
"_user",
"]",
")",
"for",
"cl",
"in",
"pending",
":",
"if",
"cl",
"[",
"'desc'",
"]",
".",
"strip",
"(",
")",
"==",
"description",
".",
"strip",
"(",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Changelist found: {}'",
".",
"format",
"(",
"cl",
"[",
"'change'",
"]",
")",
")",
"change",
"=",
"Changelist",
"(",
"int",
"(",
"cl",
"[",
"'change'",
"]",
")",
",",
"self",
")",
"break",
"else",
":",
"LOGGER",
".",
"debug",
"(",
"'No changelist found, creating one'",
")",
"change",
"=",
"Changelist",
".",
"create",
"(",
"description",
",",
"self",
")",
"change",
".",
"client",
"=",
"self",
".",
"_client",
"change",
".",
"save",
"(",
")",
"return",
"change"
] | Gets or creates a Changelist object with a description
:param description: The description to set or lookup
:type description: str
:returns: :class:`.Changelist` | [
"Gets",
"or",
"creates",
"a",
"Changelist",
"object",
"with",
"a",
"description"
] | python | train |
tbreitenfeldt/invisible_ui | invisible_ui/events/eventManager.py | https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/events/eventManager.py#L149-L163 | def change_event_actions(self, handler, actions):
"""
This allows the client to change the actions for an event, in the case that there is a desire for slightly different behavior, such as reasigning keys.
handler - the handler object that the desired changes are made to.
actions - The methods that are called when this handler is varified against the current event.
"""
if not isinstance(handler, Handler):
raise TypeError("given object must be of type Handler.")
if not self.remove_handler(handler):
raise ValueError("You must pass in a valid handler that already exists.")
self.add_handler(handler.type, actions, handler.params)
self.event = handler.event | [
"def",
"change_event_actions",
"(",
"self",
",",
"handler",
",",
"actions",
")",
":",
"if",
"not",
"isinstance",
"(",
"handler",
",",
"Handler",
")",
":",
"raise",
"TypeError",
"(",
"\"given object must be of type Handler.\"",
")",
"if",
"not",
"self",
".",
"remove_handler",
"(",
"handler",
")",
":",
"raise",
"ValueError",
"(",
"\"You must pass in a valid handler that already exists.\"",
")",
"self",
".",
"add_handler",
"(",
"handler",
".",
"type",
",",
"actions",
",",
"handler",
".",
"params",
")",
"self",
".",
"event",
"=",
"handler",
".",
"event"
] | This allows the client to change the actions for an event, in the case that there is a desire for slightly different behavior, such as reasigning keys.
handler - the handler object that the desired changes are made to.
actions - The methods that are called when this handler is varified against the current event. | [
"This",
"allows",
"the",
"client",
"to",
"change",
"the",
"actions",
"for",
"an",
"event",
"in",
"the",
"case",
"that",
"there",
"is",
"a",
"desire",
"for",
"slightly",
"different",
"behavior",
"such",
"as",
"reasigning",
"keys",
"."
] | python | train |
emirozer/bowshock | bowshock/maas.py | https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/maas.py#L45-L67 | def maas_archive(begin, end):
'''
This returns a collection of JSON objects for every weather report available for October 2012:
{
"count": 29,
"next": "http://marsweather.ingenology.com/v1/archive/?terrestrial_date_end=2012-10-31&terrestrial_date_start=2012-10-01&page=2",
"previous": null,
"results": [
...
]
}
'''
base_url = 'http://marsweather.ingenology.com/v1/archive/?'
try:
vali_date(begin)
vali_date(end)
base_url += 'terrestrial_date_start=' + begin + "&" + 'terrestrial_date_end=' + end
except:
raise ValueError("Incorrect date format, should be YYYY-MM-DD")
return dispatch_http_get(base_url) | [
"def",
"maas_archive",
"(",
"begin",
",",
"end",
")",
":",
"base_url",
"=",
"'http://marsweather.ingenology.com/v1/archive/?'",
"try",
":",
"vali_date",
"(",
"begin",
")",
"vali_date",
"(",
"end",
")",
"base_url",
"+=",
"'terrestrial_date_start='",
"+",
"begin",
"+",
"\"&\"",
"+",
"'terrestrial_date_end='",
"+",
"end",
"except",
":",
"raise",
"ValueError",
"(",
"\"Incorrect date format, should be YYYY-MM-DD\"",
")",
"return",
"dispatch_http_get",
"(",
"base_url",
")"
] | This returns a collection of JSON objects for every weather report available for October 2012:
{
"count": 29,
"next": "http://marsweather.ingenology.com/v1/archive/?terrestrial_date_end=2012-10-31&terrestrial_date_start=2012-10-01&page=2",
"previous": null,
"results": [
...
]
} | [
"This",
"returns",
"a",
"collection",
"of",
"JSON",
"objects",
"for",
"every",
"weather",
"report",
"available",
"for",
"October",
"2012",
":"
] | python | train |
evhub/coconut | coconut/requirements.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/requirements.py#L157-L176 | def print_new_versions(strict=False):
"""Prints new requirement versions."""
new_updates = []
same_updates = []
for req in everything_in(all_reqs):
new_versions = []
same_versions = []
for ver_str in all_versions(req):
if newer(ver_str_to_tuple(ver_str), min_versions[req], strict=True):
new_versions.append(ver_str)
elif not strict and newer(ver_str_to_tuple(ver_str), min_versions[req]):
same_versions.append(ver_str)
update_str = req + ": " + ver_tuple_to_str(min_versions[req]) + " -> " + ", ".join(
new_versions + ["(" + v + ")" for v in same_versions],
)
if new_versions:
new_updates.append(update_str)
elif same_versions:
same_updates.append(update_str)
print("\n".join(new_updates + same_updates)) | [
"def",
"print_new_versions",
"(",
"strict",
"=",
"False",
")",
":",
"new_updates",
"=",
"[",
"]",
"same_updates",
"=",
"[",
"]",
"for",
"req",
"in",
"everything_in",
"(",
"all_reqs",
")",
":",
"new_versions",
"=",
"[",
"]",
"same_versions",
"=",
"[",
"]",
"for",
"ver_str",
"in",
"all_versions",
"(",
"req",
")",
":",
"if",
"newer",
"(",
"ver_str_to_tuple",
"(",
"ver_str",
")",
",",
"min_versions",
"[",
"req",
"]",
",",
"strict",
"=",
"True",
")",
":",
"new_versions",
".",
"append",
"(",
"ver_str",
")",
"elif",
"not",
"strict",
"and",
"newer",
"(",
"ver_str_to_tuple",
"(",
"ver_str",
")",
",",
"min_versions",
"[",
"req",
"]",
")",
":",
"same_versions",
".",
"append",
"(",
"ver_str",
")",
"update_str",
"=",
"req",
"+",
"\": \"",
"+",
"ver_tuple_to_str",
"(",
"min_versions",
"[",
"req",
"]",
")",
"+",
"\" -> \"",
"+",
"\", \"",
".",
"join",
"(",
"new_versions",
"+",
"[",
"\"(\"",
"+",
"v",
"+",
"\")\"",
"for",
"v",
"in",
"same_versions",
"]",
",",
")",
"if",
"new_versions",
":",
"new_updates",
".",
"append",
"(",
"update_str",
")",
"elif",
"same_versions",
":",
"same_updates",
".",
"append",
"(",
"update_str",
")",
"print",
"(",
"\"\\n\"",
".",
"join",
"(",
"new_updates",
"+",
"same_updates",
")",
")"
] | Prints new requirement versions. | [
"Prints",
"new",
"requirement",
"versions",
"."
] | python | train |
quantopian/zipline | zipline/utils/api_support.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/api_support.py#L86-L105 | def require_initialized(exception):
"""
Decorator for API methods that should only be called after
TradingAlgorithm.initialize. `exception` will be raised if the method is
called before initialize has completed.
Examples
--------
@require_initialized(SomeException("Don't do that!"))
def method(self):
# Do stuff that should only be allowed after initialize.
"""
def decorator(method):
@wraps(method)
def wrapped_method(self, *args, **kwargs):
if not self.initialized:
raise exception
return method(self, *args, **kwargs)
return wrapped_method
return decorator | [
"def",
"require_initialized",
"(",
"exception",
")",
":",
"def",
"decorator",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"wrapped_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"initialized",
":",
"raise",
"exception",
"return",
"method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapped_method",
"return",
"decorator"
] | Decorator for API methods that should only be called after
TradingAlgorithm.initialize. `exception` will be raised if the method is
called before initialize has completed.
Examples
--------
@require_initialized(SomeException("Don't do that!"))
def method(self):
# Do stuff that should only be allowed after initialize. | [
"Decorator",
"for",
"API",
"methods",
"that",
"should",
"only",
"be",
"called",
"after",
"TradingAlgorithm",
".",
"initialize",
".",
"exception",
"will",
"be",
"raised",
"if",
"the",
"method",
"is",
"called",
"before",
"initialize",
"has",
"completed",
"."
] | python | train |
bgyori/pykqml | kqml/kqml_list.py | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L113-L124 | def push(self, obj):
"""Prepend an element to the beginnging of the list.
Parameters
----------
obj : KQMLObject or str
If a string is passed, it is instantiated as a
KQMLToken before being added to the list.
"""
if isinstance(obj, str):
obj = KQMLToken(obj)
self.data.insert(0, obj) | [
"def",
"push",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"obj",
"=",
"KQMLToken",
"(",
"obj",
")",
"self",
".",
"data",
".",
"insert",
"(",
"0",
",",
"obj",
")"
] | Prepend an element to the beginnging of the list.
Parameters
----------
obj : KQMLObject or str
If a string is passed, it is instantiated as a
KQMLToken before being added to the list. | [
"Prepend",
"an",
"element",
"to",
"the",
"beginnging",
"of",
"the",
"list",
"."
] | python | train |
HumanBrainProject/hbp-service-client | hbp_service_client/storage_service/api.py | https://github.com/HumanBrainProject/hbp-service-client/blob/b338fb41a7f0e7b9d654ff28fcf13a56d03bff4d/hbp_service_client/storage_service/api.py#L527-L557 | def create_project(self, collab_id):
'''Create a new project.
Args:
collab_id (int): The id of the collab the project should be created in.
Returns:
A dictionary of details of the created project::
{
u'collab_id': 12998,
u'created_by': u'303447',
u'created_on': u'2017-03-21T14:06:32.293902Z',
u'description': u'',
u'entity_type': u'project',
u'modified_by': u'303447',
u'modified_on': u'2017-03-21T14:06:32.293967Z',
u'name': u'12998',
u'uuid': u'2516442e-1e26-4de1-8ed8-94523224cc40'
}
Raises:
StorageForbiddenException: Server response code 403
StorageNotFoundException: Server response code 404
StorageException: other 400-600 error codes
'''
return self._authenticated_request \
.to_endpoint('project/') \
.with_json_body(self._prep_params(locals())) \
.return_body() \
.post() | [
"def",
"create_project",
"(",
"self",
",",
"collab_id",
")",
":",
"return",
"self",
".",
"_authenticated_request",
".",
"to_endpoint",
"(",
"'project/'",
")",
".",
"with_json_body",
"(",
"self",
".",
"_prep_params",
"(",
"locals",
"(",
")",
")",
")",
".",
"return_body",
"(",
")",
".",
"post",
"(",
")"
] | Create a new project.
Args:
collab_id (int): The id of the collab the project should be created in.
Returns:
A dictionary of details of the created project::
{
u'collab_id': 12998,
u'created_by': u'303447',
u'created_on': u'2017-03-21T14:06:32.293902Z',
u'description': u'',
u'entity_type': u'project',
u'modified_by': u'303447',
u'modified_on': u'2017-03-21T14:06:32.293967Z',
u'name': u'12998',
u'uuid': u'2516442e-1e26-4de1-8ed8-94523224cc40'
}
Raises:
StorageForbiddenException: Server response code 403
StorageNotFoundException: Server response code 404
StorageException: other 400-600 error codes | [
"Create",
"a",
"new",
"project",
"."
] | python | test |
SeattleTestbed/seash | pyreadline/unicode_helper.py | https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/unicode_helper.py#L29-L36 | def ensure_str(text):
u"""Convert unicode to str using pyreadline_codepage"""
if isinstance(text, unicode):
try:
return text.encode(pyreadline_codepage, u"replace")
except (LookupError, TypeError):
return text.encode(u"ascii", u"replace")
return text | [
"def",
"ensure_str",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"unicode",
")",
":",
"try",
":",
"return",
"text",
".",
"encode",
"(",
"pyreadline_codepage",
",",
"u\"replace\"",
")",
"except",
"(",
"LookupError",
",",
"TypeError",
")",
":",
"return",
"text",
".",
"encode",
"(",
"u\"ascii\"",
",",
"u\"replace\"",
")",
"return",
"text"
] | u"""Convert unicode to str using pyreadline_codepage | [
"u",
"Convert",
"unicode",
"to",
"str",
"using",
"pyreadline_codepage"
] | python | train |
swimlane/swimlane-python | swimlane/core/fields/base/field.py | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/base/field.py#L101-L111 | def validate_value(self, value):
"""Validate value is an acceptable type during set_python operation"""
if self.readonly:
raise ValidationError(self.record, "Cannot set readonly field '{}'".format(self.name))
if value not in (None, self._unset):
if self.supported_types and not isinstance(value, tuple(self.supported_types)):
raise ValidationError(self.record, "Field '{}' expects one of {}, got '{}' instead".format(
self.name,
', '.join([repr(t.__name__) for t in self.supported_types]),
type(value).__name__)
) | [
"def",
"validate_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"readonly",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"record",
",",
"\"Cannot set readonly field '{}'\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"if",
"value",
"not",
"in",
"(",
"None",
",",
"self",
".",
"_unset",
")",
":",
"if",
"self",
".",
"supported_types",
"and",
"not",
"isinstance",
"(",
"value",
",",
"tuple",
"(",
"self",
".",
"supported_types",
")",
")",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"record",
",",
"\"Field '{}' expects one of {}, got '{}' instead\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"', '",
".",
"join",
"(",
"[",
"repr",
"(",
"t",
".",
"__name__",
")",
"for",
"t",
"in",
"self",
".",
"supported_types",
"]",
")",
",",
"type",
"(",
"value",
")",
".",
"__name__",
")",
")"
] | Validate value is an acceptable type during set_python operation | [
"Validate",
"value",
"is",
"an",
"acceptable",
"type",
"during",
"set_python",
"operation"
] | python | train |
niklasf/python-chess | chess/gaviota.py | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/gaviota.py#L1544-L1554 | def add_directory(self, directory: PathLike) -> None:
"""
Adds *.gtb.cp4* tables from a directory. The relevant files are lazily
opened when the tablebase is actually probed.
"""
directory = os.path.abspath(directory)
if not os.path.isdir(directory):
raise IOError("not a directory: {!r}".format(directory))
for tbfile in fnmatch.filter(os.listdir(directory), "*.gtb.cp4"):
self.available_tables[os.path.basename(tbfile).replace(".gtb.cp4", "")] = os.path.join(directory, tbfile) | [
"def",
"add_directory",
"(",
"self",
",",
"directory",
":",
"PathLike",
")",
"->",
"None",
":",
"directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"raise",
"IOError",
"(",
"\"not a directory: {!r}\"",
".",
"format",
"(",
"directory",
")",
")",
"for",
"tbfile",
"in",
"fnmatch",
".",
"filter",
"(",
"os",
".",
"listdir",
"(",
"directory",
")",
",",
"\"*.gtb.cp4\"",
")",
":",
"self",
".",
"available_tables",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"tbfile",
")",
".",
"replace",
"(",
"\".gtb.cp4\"",
",",
"\"\"",
")",
"]",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"tbfile",
")"
] | Adds *.gtb.cp4* tables from a directory. The relevant files are lazily
opened when the tablebase is actually probed. | [
"Adds",
"*",
".",
"gtb",
".",
"cp4",
"*",
"tables",
"from",
"a",
"directory",
".",
"The",
"relevant",
"files",
"are",
"lazily",
"opened",
"when",
"the",
"tablebase",
"is",
"actually",
"probed",
"."
] | python | train |
quodlibet/mutagen | mutagen/mp4/_as_entry.py | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/_as_entry.py#L228-L245 | def parse(cls, fileobj):
"""Returns a parsed instance of the called type.
The file position is right after the descriptor after this returns.
Raises DescriptorError
"""
try:
length = cls._parse_desc_length_file(fileobj)
except ValueError as e:
raise DescriptorError(e)
pos = fileobj.tell()
instance = cls(fileobj, length)
left = length - (fileobj.tell() - pos)
if left < 0:
raise DescriptorError("descriptor parsing read too much data")
fileobj.seek(left, 1)
return instance | [
"def",
"parse",
"(",
"cls",
",",
"fileobj",
")",
":",
"try",
":",
"length",
"=",
"cls",
".",
"_parse_desc_length_file",
"(",
"fileobj",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"DescriptorError",
"(",
"e",
")",
"pos",
"=",
"fileobj",
".",
"tell",
"(",
")",
"instance",
"=",
"cls",
"(",
"fileobj",
",",
"length",
")",
"left",
"=",
"length",
"-",
"(",
"fileobj",
".",
"tell",
"(",
")",
"-",
"pos",
")",
"if",
"left",
"<",
"0",
":",
"raise",
"DescriptorError",
"(",
"\"descriptor parsing read too much data\"",
")",
"fileobj",
".",
"seek",
"(",
"left",
",",
"1",
")",
"return",
"instance"
] | Returns a parsed instance of the called type.
The file position is right after the descriptor after this returns.
Raises DescriptorError | [
"Returns",
"a",
"parsed",
"instance",
"of",
"the",
"called",
"type",
".",
"The",
"file",
"position",
"is",
"right",
"after",
"the",
"descriptor",
"after",
"this",
"returns",
"."
] | python | train |
pythongssapi/python-gssapi | gssapi/mechs.py | https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/mechs.py#L167-L200 | def from_attrs(cls, desired_attrs=None, except_attrs=None,
critical_attrs=None):
"""
Get a generator of mechanisms supporting the specified attributes. See
RFC 5587's :func:`indicate_mechs_by_attrs` for more information.
Args:
desired_attrs ([OID]): Desired attributes
except_attrs ([OID]): Except attributes
critical_attrs ([OID]): Critical attributes
Returns:
[Mechanism]: A set of mechanisms having the desired features.
Raises:
GSSError
:requires-ext:`rfc5587`
"""
if isinstance(desired_attrs, roids.OID):
desired_attrs = set([desired_attrs])
if isinstance(except_attrs, roids.OID):
except_attrs = set([except_attrs])
if isinstance(critical_attrs, roids.OID):
critical_attrs = set([critical_attrs])
if rfc5587 is None:
raise NotImplementedError("Your GSSAPI implementation does not "
"have support for RFC 5587")
mechs = rfc5587.indicate_mechs_by_attrs(desired_attrs,
except_attrs,
critical_attrs)
return (cls(mech) for mech in mechs) | [
"def",
"from_attrs",
"(",
"cls",
",",
"desired_attrs",
"=",
"None",
",",
"except_attrs",
"=",
"None",
",",
"critical_attrs",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"desired_attrs",
",",
"roids",
".",
"OID",
")",
":",
"desired_attrs",
"=",
"set",
"(",
"[",
"desired_attrs",
"]",
")",
"if",
"isinstance",
"(",
"except_attrs",
",",
"roids",
".",
"OID",
")",
":",
"except_attrs",
"=",
"set",
"(",
"[",
"except_attrs",
"]",
")",
"if",
"isinstance",
"(",
"critical_attrs",
",",
"roids",
".",
"OID",
")",
":",
"critical_attrs",
"=",
"set",
"(",
"[",
"critical_attrs",
"]",
")",
"if",
"rfc5587",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"Your GSSAPI implementation does not \"",
"\"have support for RFC 5587\"",
")",
"mechs",
"=",
"rfc5587",
".",
"indicate_mechs_by_attrs",
"(",
"desired_attrs",
",",
"except_attrs",
",",
"critical_attrs",
")",
"return",
"(",
"cls",
"(",
"mech",
")",
"for",
"mech",
"in",
"mechs",
")"
] | Get a generator of mechanisms supporting the specified attributes. See
RFC 5587's :func:`indicate_mechs_by_attrs` for more information.
Args:
desired_attrs ([OID]): Desired attributes
except_attrs ([OID]): Except attributes
critical_attrs ([OID]): Critical attributes
Returns:
[Mechanism]: A set of mechanisms having the desired features.
Raises:
GSSError
:requires-ext:`rfc5587` | [
"Get",
"a",
"generator",
"of",
"mechanisms",
"supporting",
"the",
"specified",
"attributes",
".",
"See",
"RFC",
"5587",
"s",
":",
"func",
":",
"indicate_mechs_by_attrs",
"for",
"more",
"information",
"."
] | python | train |
cyrus-/cypy | cypy/cg.py | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/cg.py#L598-L619 | def trigger_staged_cg_hook(self, name, g, *args, **kwargs):
"""Calls a three-staged hook:
1. ``"pre_"+name``
2. ``"in_"+name``
3. ``"post_"+name``
"""
print_hooks = self._print_hooks
# TODO: document name lookup business
# TODO: refactor this context stuff, its confusing
hook_name = "pre_" + name
printed_name = hook_name if print_hooks else None
self.trigger_cg_hook(hook_name, g, printed_name, *args, **kwargs) # TODO: avoid copies
hook_name = "in_" + name
printed_name = hook_name if print_hooks else None
self.trigger_cg_hook(hook_name, g, printed_name, *args, **kwargs)
hook_name = "post_" + name
printed_name = hook_name if print_hooks else None
self.trigger_cg_hook(hook_name, g, printed_name, *args, **kwargs) | [
"def",
"trigger_staged_cg_hook",
"(",
"self",
",",
"name",
",",
"g",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print_hooks",
"=",
"self",
".",
"_print_hooks",
"# TODO: document name lookup business",
"# TODO: refactor this context stuff, its confusing",
"hook_name",
"=",
"\"pre_\"",
"+",
"name",
"printed_name",
"=",
"hook_name",
"if",
"print_hooks",
"else",
"None",
"self",
".",
"trigger_cg_hook",
"(",
"hook_name",
",",
"g",
",",
"printed_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# TODO: avoid copies",
"hook_name",
"=",
"\"in_\"",
"+",
"name",
"printed_name",
"=",
"hook_name",
"if",
"print_hooks",
"else",
"None",
"self",
".",
"trigger_cg_hook",
"(",
"hook_name",
",",
"g",
",",
"printed_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"hook_name",
"=",
"\"post_\"",
"+",
"name",
"printed_name",
"=",
"hook_name",
"if",
"print_hooks",
"else",
"None",
"self",
".",
"trigger_cg_hook",
"(",
"hook_name",
",",
"g",
",",
"printed_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Calls a three-staged hook:
1. ``"pre_"+name``
2. ``"in_"+name``
3. ``"post_"+name`` | [
"Calls",
"a",
"three",
"-",
"staged",
"hook",
":",
"1",
".",
"pre_",
"+",
"name",
"2",
".",
"in_",
"+",
"name",
"3",
".",
"post_",
"+",
"name"
] | python | train |
gmr/flatdict | flatdict.py | https://github.com/gmr/flatdict/blob/40bfa64972b2dc148643116db786aa106e7d7d56/flatdict.py#L322-L338 | def set_delimiter(self, delimiter):
"""Override the default or passed in delimiter with a new value. If
the requested delimiter already exists in a key, a :exc:`ValueError`
will be raised.
:param str delimiter: The delimiter to use
:raises: ValueError
"""
for key in self.keys():
if delimiter in key:
raise ValueError('Key {!r} collides with delimiter {!r}', key,
delimiter)
self._delimiter = delimiter
for key in self._values.keys():
if isinstance(self._values[key], FlatDict):
self._values[key].set_delimiter(delimiter) | [
"def",
"set_delimiter",
"(",
"self",
",",
"delimiter",
")",
":",
"for",
"key",
"in",
"self",
".",
"keys",
"(",
")",
":",
"if",
"delimiter",
"in",
"key",
":",
"raise",
"ValueError",
"(",
"'Key {!r} collides with delimiter {!r}'",
",",
"key",
",",
"delimiter",
")",
"self",
".",
"_delimiter",
"=",
"delimiter",
"for",
"key",
"in",
"self",
".",
"_values",
".",
"keys",
"(",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_values",
"[",
"key",
"]",
",",
"FlatDict",
")",
":",
"self",
".",
"_values",
"[",
"key",
"]",
".",
"set_delimiter",
"(",
"delimiter",
")"
] | Override the default or passed in delimiter with a new value. If
the requested delimiter already exists in a key, a :exc:`ValueError`
will be raised.
:param str delimiter: The delimiter to use
:raises: ValueError | [
"Override",
"the",
"default",
"or",
"passed",
"in",
"delimiter",
"with",
"a",
"new",
"value",
".",
"If",
"the",
"requested",
"delimiter",
"already",
"exists",
"in",
"a",
"key",
"a",
":",
"exc",
":",
"ValueError",
"will",
"be",
"raised",
"."
] | python | train |
inveniosoftware/invenio-oaiserver | invenio_oaiserver/response.py | https://github.com/inveniosoftware/invenio-oaiserver/blob/eae765e32bd816ddc5612d4b281caf205518b512/invenio_oaiserver/response.py#L296-L317 | def listrecords(**kwargs):
"""Create OAI-PMH response for verb ListRecords."""
record_dumper = serializer(kwargs['metadataPrefix'])
e_tree, e_listrecords = verb(**kwargs)
result = get_records(**kwargs)
for record in result.items:
pid = oaiid_fetcher(record['id'], record['json']['_source'])
e_record = SubElement(e_listrecords,
etree.QName(NS_OAIPMH, 'record'))
header(
e_record,
identifier=pid.pid_value,
datestamp=record['updated'],
sets=record['json']['_source'].get('_oai', {}).get('sets', []),
)
e_metadata = SubElement(e_record, etree.QName(NS_OAIPMH, 'metadata'))
e_metadata.append(record_dumper(pid, record['json']))
resumption_token(e_listrecords, result, **kwargs)
return e_tree | [
"def",
"listrecords",
"(",
"*",
"*",
"kwargs",
")",
":",
"record_dumper",
"=",
"serializer",
"(",
"kwargs",
"[",
"'metadataPrefix'",
"]",
")",
"e_tree",
",",
"e_listrecords",
"=",
"verb",
"(",
"*",
"*",
"kwargs",
")",
"result",
"=",
"get_records",
"(",
"*",
"*",
"kwargs",
")",
"for",
"record",
"in",
"result",
".",
"items",
":",
"pid",
"=",
"oaiid_fetcher",
"(",
"record",
"[",
"'id'",
"]",
",",
"record",
"[",
"'json'",
"]",
"[",
"'_source'",
"]",
")",
"e_record",
"=",
"SubElement",
"(",
"e_listrecords",
",",
"etree",
".",
"QName",
"(",
"NS_OAIPMH",
",",
"'record'",
")",
")",
"header",
"(",
"e_record",
",",
"identifier",
"=",
"pid",
".",
"pid_value",
",",
"datestamp",
"=",
"record",
"[",
"'updated'",
"]",
",",
"sets",
"=",
"record",
"[",
"'json'",
"]",
"[",
"'_source'",
"]",
".",
"get",
"(",
"'_oai'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'sets'",
",",
"[",
"]",
")",
",",
")",
"e_metadata",
"=",
"SubElement",
"(",
"e_record",
",",
"etree",
".",
"QName",
"(",
"NS_OAIPMH",
",",
"'metadata'",
")",
")",
"e_metadata",
".",
"append",
"(",
"record_dumper",
"(",
"pid",
",",
"record",
"[",
"'json'",
"]",
")",
")",
"resumption_token",
"(",
"e_listrecords",
",",
"result",
",",
"*",
"*",
"kwargs",
")",
"return",
"e_tree"
] | Create OAI-PMH response for verb ListRecords. | [
"Create",
"OAI",
"-",
"PMH",
"response",
"for",
"verb",
"ListRecords",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/distlib/locators.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/locators.py#L1107-L1121 | def get_matcher(self, reqt):
"""
Get a version matcher for a requirement.
:param reqt: The requirement
:type reqt: str
:return: A version matcher (an instance of
:class:`distlib.version.Matcher`).
"""
try:
matcher = self.scheme.matcher(reqt)
except UnsupportedVersionError: # pragma: no cover
# XXX compat-mode if cannot read the version
name = reqt.split()[0]
matcher = self.scheme.matcher(name)
return matcher | [
"def",
"get_matcher",
"(",
"self",
",",
"reqt",
")",
":",
"try",
":",
"matcher",
"=",
"self",
".",
"scheme",
".",
"matcher",
"(",
"reqt",
")",
"except",
"UnsupportedVersionError",
":",
"# pragma: no cover",
"# XXX compat-mode if cannot read the version",
"name",
"=",
"reqt",
".",
"split",
"(",
")",
"[",
"0",
"]",
"matcher",
"=",
"self",
".",
"scheme",
".",
"matcher",
"(",
"name",
")",
"return",
"matcher"
] | Get a version matcher for a requirement.
:param reqt: The requirement
:type reqt: str
:return: A version matcher (an instance of
:class:`distlib.version.Matcher`). | [
"Get",
"a",
"version",
"matcher",
"for",
"a",
"requirement",
".",
":",
"param",
"reqt",
":",
"The",
"requirement",
":",
"type",
"reqt",
":",
"str",
":",
"return",
":",
"A",
"version",
"matcher",
"(",
"an",
"instance",
"of",
":",
"class",
":",
"distlib",
".",
"version",
".",
"Matcher",
")",
"."
] | python | train |
raamana/mrivis | mrivis/base.py | https://github.com/raamana/mrivis/blob/199ad096b8a1d825f69109e7218a81b2f1cec756/mrivis/base.py#L997-L1015 | def save(self, output_path=None, title=None):
"""Saves the current figure with carpet visualization to disk.
Parameters
----------
output_path : str
Path to where the figure needs to be saved to.
title : str
text to overlay and annotate the visualization (done via plt.suptitle())
"""
try:
save_figure(self.fig, output_path=output_path, annot=title)
except:
print('Unable to save the figure to disk! \nException: ')
traceback.print_exc() | [
"def",
"save",
"(",
"self",
",",
"output_path",
"=",
"None",
",",
"title",
"=",
"None",
")",
":",
"try",
":",
"save_figure",
"(",
"self",
".",
"fig",
",",
"output_path",
"=",
"output_path",
",",
"annot",
"=",
"title",
")",
"except",
":",
"print",
"(",
"'Unable to save the figure to disk! \\nException: '",
")",
"traceback",
".",
"print_exc",
"(",
")"
] | Saves the current figure with carpet visualization to disk.
Parameters
----------
output_path : str
Path to where the figure needs to be saved to.
title : str
text to overlay and annotate the visualization (done via plt.suptitle()) | [
"Saves",
"the",
"current",
"figure",
"with",
"carpet",
"visualization",
"to",
"disk",
"."
] | python | train |
ceph/ceph-deploy | ceph_deploy/util/system.py | https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/system.py#L167-L180 | def is_systemd_service_enabled(conn, service='ceph'):
"""
Detects if a systemd service is enabled or not.
"""
_, _, returncode = remoto.process.check(
conn,
[
'systemctl',
'is-enabled',
'--quiet',
'{service}'.format(service=service),
]
)
return returncode == 0 | [
"def",
"is_systemd_service_enabled",
"(",
"conn",
",",
"service",
"=",
"'ceph'",
")",
":",
"_",
",",
"_",
",",
"returncode",
"=",
"remoto",
".",
"process",
".",
"check",
"(",
"conn",
",",
"[",
"'systemctl'",
",",
"'is-enabled'",
",",
"'--quiet'",
",",
"'{service}'",
".",
"format",
"(",
"service",
"=",
"service",
")",
",",
"]",
")",
"return",
"returncode",
"==",
"0"
] | Detects if a systemd service is enabled or not. | [
"Detects",
"if",
"a",
"systemd",
"service",
"is",
"enabled",
"or",
"not",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.