repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
diffeo/rejester | rejester/_task_master.py | TaskMaster.get_child_work_units | def get_child_work_units(self, worker_id):
'''Get work units assigned to a worker's children.
Returns a dictionary mapping worker ID to :class:`WorkUnit`.
If a child exists but is idle, that worker ID will map to
:const:`None`. The work unit may already be expired or
assigned t... | python | def get_child_work_units(self, worker_id):
'''Get work units assigned to a worker's children.
Returns a dictionary mapping worker ID to :class:`WorkUnit`.
If a child exists but is idle, that worker ID will map to
:const:`None`. The work unit may already be expired or
assigned t... | [
"def",
"get_child_work_units",
"(",
"self",
",",
"worker_id",
")",
":",
"result",
"=",
"{",
"}",
"with",
"self",
".",
"registry",
".",
"lock",
"(",
"identifier",
"=",
"worker_id",
")",
"as",
"session",
":",
"all_children",
"=",
"session",
".",
"pull",
"(... | Get work units assigned to a worker's children.
Returns a dictionary mapping worker ID to :class:`WorkUnit`.
If a child exists but is idle, that worker ID will map to
:const:`None`. The work unit may already be expired or
assigned to a different worker; this will be reflected in
... | [
"Get",
"work",
"units",
"assigned",
"to",
"a",
"worker",
"s",
"children",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_task_master.py#L1720-L1773 |
scivision/histutils | histutils/plotsimul.py | plotPlainImg | def plotPlainImg(sim, cam, rawdata, t, odir):
"""
No subplots, just a plan
http://stackoverflow.com/questions/22408237/named-colors-in-matplotlib
"""
for R, C in zip(rawdata, cam):
fg = figure()
ax = fg.gca()
ax.set_axis_off() # no ticks
ax.imshow(R[t, :, :],
... | python | def plotPlainImg(sim, cam, rawdata, t, odir):
"""
No subplots, just a plan
http://stackoverflow.com/questions/22408237/named-colors-in-matplotlib
"""
for R, C in zip(rawdata, cam):
fg = figure()
ax = fg.gca()
ax.set_axis_off() # no ticks
ax.imshow(R[t, :, :],
... | [
"def",
"plotPlainImg",
"(",
"sim",
",",
"cam",
",",
"rawdata",
",",
"t",
",",
"odir",
")",
":",
"for",
"R",
",",
"C",
"in",
"zip",
"(",
"rawdata",
",",
"cam",
")",
":",
"fg",
"=",
"figure",
"(",
")",
"ax",
"=",
"fg",
".",
"gca",
"(",
")",
"... | No subplots, just a plan
http://stackoverflow.com/questions/22408237/named-colors-in-matplotlib | [
"No",
"subplots",
"just",
"a",
"plan"
] | train | https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/plotsimul.py#L23-L46 |
scivision/histutils | histutils/plotsimul.py | plotRealImg | def plotRealImg(sim, cam, rawdata, t: int, odir: Path=None, fg=None):
"""
sim: histfeas/simclass.py
cam: camclass.py
rawdata: nframe x ny x nx ndarray
t: integer index to read
odir: output directory (where to write results)
plots both cameras together,
and magnetic zenith 1-D cut line
... | python | def plotRealImg(sim, cam, rawdata, t: int, odir: Path=None, fg=None):
"""
sim: histfeas/simclass.py
cam: camclass.py
rawdata: nframe x ny x nx ndarray
t: integer index to read
odir: output directory (where to write results)
plots both cameras together,
and magnetic zenith 1-D cut line
... | [
"def",
"plotRealImg",
"(",
"sim",
",",
"cam",
",",
"rawdata",
",",
"t",
":",
"int",
",",
"odir",
":",
"Path",
"=",
"None",
",",
"fg",
"=",
"None",
")",
":",
"ncols",
"=",
"len",
"(",
"cam",
")",
"# print('using {} cameras'.format(ncols))",
"T",
"=",
... | sim: histfeas/simclass.py
cam: camclass.py
rawdata: nframe x ny x nx ndarray
t: integer index to read
odir: output directory (where to write results)
plots both cameras together,
and magnetic zenith 1-D cut line
and 1 degree radar beam red circle centered on magnetic zenith | [
"sim",
":",
"histfeas",
"/",
"simclass",
".",
"py",
"cam",
":",
"camclass",
".",
"py",
"rawdata",
":",
"nframe",
"x",
"ny",
"x",
"nx",
"ndarray",
"t",
":",
"integer",
"index",
"to",
"read",
"odir",
":",
"output",
"directory",
"(",
"where",
"to",
"wri... | train | https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/plotsimul.py#L50-L115 |
scivision/histutils | histutils/plotsimul.py | updateframe | def updateframe(t, raw, wavelen, cam, ax, fg):
showcb = False
ttxt = f'Cam {cam.name}: '
if raw.ndim == 3:
frame = raw[t, ...]
elif raw.ndim == 2:
frame = raw
elif raw.ndim == 1: # GeoData
frame = raw.reshape((sqrt(raw.size), -1))
else:
raise ValueError('ndim==... | python | def updateframe(t, raw, wavelen, cam, ax, fg):
showcb = False
ttxt = f'Cam {cam.name}: '
if raw.ndim == 3:
frame = raw[t, ...]
elif raw.ndim == 2:
frame = raw
elif raw.ndim == 1: # GeoData
frame = raw.reshape((sqrt(raw.size), -1))
else:
raise ValueError('ndim==... | [
"def",
"updateframe",
"(",
"t",
",",
"raw",
",",
"wavelen",
",",
"cam",
",",
"ax",
",",
"fg",
")",
":",
"showcb",
"=",
"False",
"ttxt",
"=",
"f'Cam {cam.name}: '",
"if",
"raw",
".",
"ndim",
"==",
"3",
":",
"frame",
"=",
"raw",
"[",
"t",
",",
"...... | http://scikit-image.org/docs/dev/api/skimage.restoration.html?highlight=denoise | [
"http",
":",
"//",
"scikit",
"-",
"image",
".",
"org",
"/",
"docs",
"/",
"dev",
"/",
"api",
"/",
"skimage",
".",
"restoration",
".",
"html?highlight",
"=",
"denoise"
] | train | https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/plotsimul.py#L118-L210 |
arcus-io/puppetdb-python | puppetdb/v2/nodes.py | get_nodes | def get_nodes(api_url=None, verify=False, cert=list()):
"""
Returns info for all Nodes
:param api_url: Base PuppetDB API url
"""
return utils._make_api_request(api_url, '/nodes', verify, cert) | python | def get_nodes(api_url=None, verify=False, cert=list()):
"""
Returns info for all Nodes
:param api_url: Base PuppetDB API url
"""
return utils._make_api_request(api_url, '/nodes', verify, cert) | [
"def",
"get_nodes",
"(",
"api_url",
"=",
"None",
",",
"verify",
"=",
"False",
",",
"cert",
"=",
"list",
"(",
")",
")",
":",
"return",
"utils",
".",
"_make_api_request",
"(",
"api_url",
",",
"'/nodes'",
",",
"verify",
",",
"cert",
")"
] | Returns info for all Nodes
:param api_url: Base PuppetDB API url | [
"Returns",
"info",
"for",
"all",
"Nodes"
] | train | https://github.com/arcus-io/puppetdb-python/blob/d772eb80a1dfb1154a1f421c7ecdc1ac951b5ea2/puppetdb/v2/nodes.py#L25-L32 |
arcus-io/puppetdb-python | puppetdb/v2/nodes.py | get_node | def get_node(api_url=None, node_name=None, verify=False, cert=list()):
"""
Returns info for a Node
:param api_url: Base PuppetDB API url
:param node_name: Name of node
"""
return utils._make_api_request(api_url, '/nodes/{0}'.format(node_name), verify, cert) | python | def get_node(api_url=None, node_name=None, verify=False, cert=list()):
"""
Returns info for a Node
:param api_url: Base PuppetDB API url
:param node_name: Name of node
"""
return utils._make_api_request(api_url, '/nodes/{0}'.format(node_name), verify, cert) | [
"def",
"get_node",
"(",
"api_url",
"=",
"None",
",",
"node_name",
"=",
"None",
",",
"verify",
"=",
"False",
",",
"cert",
"=",
"list",
"(",
")",
")",
":",
"return",
"utils",
".",
"_make_api_request",
"(",
"api_url",
",",
"'/nodes/{0}'",
".",
"format",
"... | Returns info for a Node
:param api_url: Base PuppetDB API url
:param node_name: Name of node | [
"Returns",
"info",
"for",
"a",
"Node"
] | train | https://github.com/arcus-io/puppetdb-python/blob/d772eb80a1dfb1154a1f421c7ecdc1ac951b5ea2/puppetdb/v2/nodes.py#L34-L42 |
arcus-io/puppetdb-python | puppetdb/v2/nodes.py | get_node_fact_by_name | def get_node_fact_by_name(api_url=None, node_name=None, fact_name=None, verify=False, cert=list()):
"""
Returns specified fact for a Node
:param api_url: Base PuppetDB API url
:param node_name: Name of node
:param fact_name: Name of fact
"""
return utils._make_api_request(api_url, '/nodes/... | python | def get_node_fact_by_name(api_url=None, node_name=None, fact_name=None, verify=False, cert=list()):
"""
Returns specified fact for a Node
:param api_url: Base PuppetDB API url
:param node_name: Name of node
:param fact_name: Name of fact
"""
return utils._make_api_request(api_url, '/nodes/... | [
"def",
"get_node_fact_by_name",
"(",
"api_url",
"=",
"None",
",",
"node_name",
"=",
"None",
",",
"fact_name",
"=",
"None",
",",
"verify",
"=",
"False",
",",
"cert",
"=",
"list",
"(",
")",
")",
":",
"return",
"utils",
".",
"_make_api_request",
"(",
"api_u... | Returns specified fact for a Node
:param api_url: Base PuppetDB API url
:param node_name: Name of node
:param fact_name: Name of fact | [
"Returns",
"specified",
"fact",
"for",
"a",
"Node"
] | train | https://github.com/arcus-io/puppetdb-python/blob/d772eb80a1dfb1154a1f421c7ecdc1ac951b5ea2/puppetdb/v2/nodes.py#L54-L64 |
arcus-io/puppetdb-python | puppetdb/v2/nodes.py | get_node_resource_by_type | def get_node_resource_by_type(api_url=None, node_name=None,
type_name=None, verify=False, cert=list()):
"""
Returns specified resource for a Node
:param api_url: Base PuppetDB API url
:param node_name: Name of node
:param type_name: Type of resource
"""
return utils._make_api_request(a... | python | def get_node_resource_by_type(api_url=None, node_name=None,
type_name=None, verify=False, cert=list()):
"""
Returns specified resource for a Node
:param api_url: Base PuppetDB API url
:param node_name: Name of node
:param type_name: Type of resource
"""
return utils._make_api_request(a... | [
"def",
"get_node_resource_by_type",
"(",
"api_url",
"=",
"None",
",",
"node_name",
"=",
"None",
",",
"type_name",
"=",
"None",
",",
"verify",
"=",
"False",
",",
"cert",
"=",
"list",
"(",
")",
")",
":",
"return",
"utils",
".",
"_make_api_request",
"(",
"a... | Returns specified resource for a Node
:param api_url: Base PuppetDB API url
:param node_name: Name of node
:param type_name: Type of resource | [
"Returns",
"specified",
"resource",
"for",
"a",
"Node"
] | train | https://github.com/arcus-io/puppetdb-python/blob/d772eb80a1dfb1154a1f421c7ecdc1ac951b5ea2/puppetdb/v2/nodes.py#L76-L87 |
EnigmaBridge/client.py | ebclient/eb_request.py | RequestCall.call | def call(self, request=None, *args, **kwargs):
"""
Calls multiple time - with retry.
:param request:
:return: response
"""
if request is not None:
self.request = request
retry = self.request.configuration.retry
if not isinstance(retry, Simple... | python | def call(self, request=None, *args, **kwargs):
"""
Calls multiple time - with retry.
:param request:
:return: response
"""
if request is not None:
self.request = request
retry = self.request.configuration.retry
if not isinstance(retry, Simple... | [
"def",
"call",
"(",
"self",
",",
"request",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"request",
"is",
"not",
"None",
":",
"self",
".",
"request",
"=",
"request",
"retry",
"=",
"self",
".",
"request",
".",
"configurati... | Calls multiple time - with retry.
:param request:
:return: response | [
"Calls",
"multiple",
"time",
"-",
"with",
"retry",
"."
] | train | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_request.py#L68-L99 |
EnigmaBridge/client.py | ebclient/eb_request.py | RequestCall.field_to_long | def field_to_long(value):
"""
Converts given value to long if possible, otherwise None is returned.
:param value:
:return:
"""
if isinstance(value, (int, long)):
return long(value)
elif isinstance(value, basestring):
return bytes_to_long(f... | python | def field_to_long(value):
"""
Converts given value to long if possible, otherwise None is returned.
:param value:
:return:
"""
if isinstance(value, (int, long)):
return long(value)
elif isinstance(value, basestring):
return bytes_to_long(f... | [
"def",
"field_to_long",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"return",
"long",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"return",
"bytes_to_lon... | Converts given value to long if possible, otherwise None is returned.
:param value:
:return: | [
"Converts",
"given",
"value",
"to",
"long",
"if",
"possible",
"otherwise",
"None",
"is",
"returned",
"."
] | train | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_request.py#L102-L114 |
EnigmaBridge/client.py | ebclient/eb_request.py | RequestCall.build_url | def build_url(self):
"""
Construct URL
e.g.,: http://site2.enigmabridge.com:12000/1.0/testAPI/GetAllAPIKeys/abcdef012345
:return:
"""
url = "%s/1.0/%s/%s/%s" % (
self.request.endpoint.get_url(),
self.request.api_object,
self.request.ap... | python | def build_url(self):
"""
Construct URL
e.g.,: http://site2.enigmabridge.com:12000/1.0/testAPI/GetAllAPIKeys/abcdef012345
:return:
"""
url = "%s/1.0/%s/%s/%s" % (
self.request.endpoint.get_url(),
self.request.api_object,
self.request.ap... | [
"def",
"build_url",
"(",
"self",
")",
":",
"url",
"=",
"\"%s/1.0/%s/%s/%s\"",
"%",
"(",
"self",
".",
"request",
".",
"endpoint",
".",
"get_url",
"(",
")",
",",
"self",
".",
"request",
".",
"api_object",
",",
"self",
".",
"request",
".",
"api_method",
"... | Construct URL
e.g.,: http://site2.enigmabridge.com:12000/1.0/testAPI/GetAllAPIKeys/abcdef012345
:return: | [
"Construct",
"URL",
"e",
".",
"g",
".",
":",
"http",
":",
"//",
"site2",
".",
"enigmabridge",
".",
"com",
":",
"12000",
"/",
"1",
".",
"0",
"/",
"testAPI",
"/",
"GetAllAPIKeys",
"/",
"abcdef012345"
] | train | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_request.py#L116-L129 |
EnigmaBridge/client.py | ebclient/eb_request.py | RequestCall.call_once | def call_once(self, request=None, *args, **kwargs):
"""
Performs one API request.
Raises exception on failure.
:param request:
:param args:
:param kwargs:
:return: response
"""
if request is not None:
self.request = request
co... | python | def call_once(self, request=None, *args, **kwargs):
"""
Performs one API request.
Raises exception on failure.
:param request:
:param args:
:param kwargs:
:return: response
"""
if request is not None:
self.request = request
co... | [
"def",
"call_once",
"(",
"self",
",",
"request",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"request",
"is",
"not",
"None",
":",
"self",
".",
"request",
"=",
"request",
"config",
"=",
"self",
".",
"request",
".",
"confi... | Performs one API request.
Raises exception on failure.
:param request:
:param args:
:param kwargs:
:return: response | [
"Performs",
"one",
"API",
"request",
".",
"Raises",
"exception",
"on",
"failure",
"."
] | train | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_request.py#L149-L172 |
EnigmaBridge/client.py | ebclient/eb_request.py | RequestCall.check_response | def check_response(self, resp):
"""
Checks response after request was made.
Checks status of the response, mainly
:param resp:
:return:
"""
# For successful API call, response code will be 200 (OK)
if resp.ok:
json = resp.json()
s... | python | def check_response(self, resp):
"""
Checks response after request was made.
Checks status of the response, mainly
:param resp:
:return:
"""
# For successful API call, response code will be 200 (OK)
if resp.ok:
json = resp.json()
s... | [
"def",
"check_response",
"(",
"self",
",",
"resp",
")",
":",
"# For successful API call, response code will be 200 (OK)",
"if",
"resp",
".",
"ok",
":",
"json",
"=",
"resp",
".",
"json",
"(",
")",
"self",
".",
"response",
"=",
"ResponseHolder",
"(",
")",
"self"... | Checks response after request was made.
Checks status of the response, mainly
:param resp:
:return: | [
"Checks",
"response",
"after",
"request",
"was",
"made",
".",
"Checks",
"status",
"of",
"the",
"response",
"mainly"
] | train | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_request.py#L174-L207 |
rjw57/throw | throw/minus_renderer.py | create_email | def create_email(filepaths, collection_name):
"""Create an email message object which implements the
email.message.Message interface and which has the files to be shared
uploaded to min.us and links placed in the message body.
"""
gallery = minus.CreateGallery()
if collection_name is not None:... | python | def create_email(filepaths, collection_name):
"""Create an email message object which implements the
email.message.Message interface and which has the files to be shared
uploaded to min.us and links placed in the message body.
"""
gallery = minus.CreateGallery()
if collection_name is not None:... | [
"def",
"create_email",
"(",
"filepaths",
",",
"collection_name",
")",
":",
"gallery",
"=",
"minus",
".",
"CreateGallery",
"(",
")",
"if",
"collection_name",
"is",
"not",
"None",
":",
"gallery",
".",
"SaveGallery",
"(",
"collection_name",
")",
"interface",
"=",... | Create an email message object which implements the
email.message.Message interface and which has the files to be shared
uploaded to min.us and links placed in the message body. | [
"Create",
"an",
"email",
"message",
"object",
"which",
"implements",
"the",
"email",
".",
"message",
".",
"Message",
"interface",
"and",
"which",
"has",
"the",
"files",
"to",
"be",
"shared",
"uploaded",
"to",
"min",
".",
"us",
"and",
"links",
"placed",
"in... | train | https://github.com/rjw57/throw/blob/74a7116362ba5b45635ab247472b25cfbdece4ee/throw/minus_renderer.py#L7-L46 |
krukas/Trionyx | trionyx/trionyx/layouts.py | account_overview | def account_overview(object):
"""Create layout for user profile"""
return Layout(
Container(
Row(
Column2(
Panel(
'Avatar',
Img(src="{}{}".format(settings.MEDIA_URL, object.avatar)),
c... | python | def account_overview(object):
"""Create layout for user profile"""
return Layout(
Container(
Row(
Column2(
Panel(
'Avatar',
Img(src="{}{}".format(settings.MEDIA_URL, object.avatar)),
c... | [
"def",
"account_overview",
"(",
"object",
")",
":",
"return",
"Layout",
"(",
"Container",
"(",
"Row",
"(",
"Column2",
"(",
"Panel",
"(",
"'Avatar'",
",",
"Img",
"(",
"src",
"=",
"\"{}{}\"",
".",
"format",
"(",
"settings",
".",
"MEDIA_URL",
",",
"object",... | Create layout for user profile | [
"Create",
"layout",
"for",
"user",
"profile"
] | train | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/layouts.py#L15-L39 |
Basic-Components/msgpack-rpc-protocol | python/pymprpc/server/utils.py | list_public_methods | def list_public_methods(obj: Any):
"""找出对象中的函数.
Parameters:
obj (Any): - 要执行的对象
Returns:
(List[str]): - 所有对象中的公开的方法名
"""
return [member for member in dir(obj)
if not member.startswith('_') and
callable(getattr(obj, member))] | python | def list_public_methods(obj: Any):
"""找出对象中的函数.
Parameters:
obj (Any): - 要执行的对象
Returns:
(List[str]): - 所有对象中的公开的方法名
"""
return [member for member in dir(obj)
if not member.startswith('_') and
callable(getattr(obj, member))] | [
"def",
"list_public_methods",
"(",
"obj",
":",
"Any",
")",
":",
"return",
"[",
"member",
"for",
"member",
"in",
"dir",
"(",
"obj",
")",
"if",
"not",
"member",
".",
"startswith",
"(",
"'_'",
")",
"and",
"callable",
"(",
"getattr",
"(",
"obj",
",",
"me... | 找出对象中的函数.
Parameters:
obj (Any): - 要执行的对象
Returns:
(List[str]): - 所有对象中的公开的方法名 | [
"找出对象中的函数",
"."
] | train | https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/server/utils.py#L38-L52 |
zagfai/webtul | webtul/cache.py | Cache.add_exp_key | def add_exp_key(self, key, value, ex):
"Expired in seconds"
return self.c.set(key, value, ex) | python | def add_exp_key(self, key, value, ex):
"Expired in seconds"
return self.c.set(key, value, ex) | [
"def",
"add_exp_key",
"(",
"self",
",",
"key",
",",
"value",
",",
"ex",
")",
":",
"return",
"self",
".",
"c",
".",
"set",
"(",
"key",
",",
"value",
",",
"ex",
")"
] | Expired in seconds | [
"Expired",
"in",
"seconds"
] | train | https://github.com/zagfai/webtul/blob/58c49928070b56ef54a45b4af20d800b269ad8ce/webtul/cache.py#L50-L52 |
Vito2015/pyextend | pyextend/core/itertools.py | unpack | def unpack(iterable, count, fill=None):
"""
The iter data unpack function.
Example 1:
In[1]: source = 'abc'
In[2]: a, b = safe_unpack(source, 2)
In[3]: print(a, b)
a b
Example 2:
In[1]: source = 'abc'
In[2]: a, b, c, d = safe_unpack(source, 4)
In... | python | def unpack(iterable, count, fill=None):
"""
The iter data unpack function.
Example 1:
In[1]: source = 'abc'
In[2]: a, b = safe_unpack(source, 2)
In[3]: print(a, b)
a b
Example 2:
In[1]: source = 'abc'
In[2]: a, b, c, d = safe_unpack(source, 4)
In... | [
"def",
"unpack",
"(",
"iterable",
",",
"count",
",",
"fill",
"=",
"None",
")",
":",
"iterable",
"=",
"list",
"(",
"enumerate",
"(",
"iterable",
")",
")",
"cnt",
"=",
"count",
"if",
"count",
"<=",
"len",
"(",
"iterable",
")",
"else",
"len",
"(",
"it... | The iter data unpack function.
Example 1:
In[1]: source = 'abc'
In[2]: a, b = safe_unpack(source, 2)
In[3]: print(a, b)
a b
Example 2:
In[1]: source = 'abc'
In[2]: a, b, c, d = safe_unpack(source, 4)
In[3]: print(a, b, c, d)
a b None None | [
"The",
"iter",
"data",
"unpack",
"function",
"."
] | train | https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/itertools.py#L19-L41 |
Vito2015/pyextend | pyextend/core/itertools.py | merge | def merge(iterable1, *args):
"""
Returns an type of iterable1 value, which merged after iterable1 used *args
:exception TypeError: if any parameter type of args not equals type(iterable1)
Example 1:
source = ['a', 'b', 'c']
result = merge(source, [1, 2, 3])
self.assertEqual(res... | python | def merge(iterable1, *args):
"""
Returns an type of iterable1 value, which merged after iterable1 used *args
:exception TypeError: if any parameter type of args not equals type(iterable1)
Example 1:
source = ['a', 'b', 'c']
result = merge(source, [1, 2, 3])
self.assertEqual(res... | [
"def",
"merge",
"(",
"iterable1",
",",
"*",
"args",
")",
":",
"result_list",
"=",
"list",
"(",
"iterable1",
")",
"if",
"not",
"isinstance",
"(",
"iterable1",
",",
"dict",
")",
"else",
"eval",
"(",
"'list(iterable1.items())'",
")",
"for",
"i",
",",
"other... | Returns an type of iterable1 value, which merged after iterable1 used *args
:exception TypeError: if any parameter type of args not equals type(iterable1)
Example 1:
source = ['a', 'b', 'c']
result = merge(source, [1, 2, 3])
self.assertEqual(result, ['a', 'b', 'c', 1, 2, 3])
r... | [
"Returns",
"an",
"type",
"of",
"iterable1",
"value",
"which",
"merged",
"after",
"iterable1",
"used",
"*",
"args"
] | train | https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/itertools.py#L45-L99 |
CitrineInformatics/dftparse | dftparse/util.py | transpose_list | def transpose_list(list_of_dicts):
"""Transpose a list of dicts to a dict of lists
:param list_of_dicts: to transpose, as in the output from a parse call
:return: Dict of lists
"""
res = {}
for d in list_of_dicts:
for k, v in d.items():
if k in res:
res[k].ap... | python | def transpose_list(list_of_dicts):
"""Transpose a list of dicts to a dict of lists
:param list_of_dicts: to transpose, as in the output from a parse call
:return: Dict of lists
"""
res = {}
for d in list_of_dicts:
for k, v in d.items():
if k in res:
res[k].ap... | [
"def",
"transpose_list",
"(",
"list_of_dicts",
")",
":",
"res",
"=",
"{",
"}",
"for",
"d",
"in",
"list_of_dicts",
":",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"res",
":",
"res",
"[",
"k",
"]",
".",
"append... | Transpose a list of dicts to a dict of lists
:param list_of_dicts: to transpose, as in the output from a parse call
:return: Dict of lists | [
"Transpose",
"a",
"list",
"of",
"dicts",
"to",
"a",
"dict",
"of",
"lists"
] | train | https://github.com/CitrineInformatics/dftparse/blob/53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d/dftparse/util.py#L10-L23 |
JNRowe/jnrbase | jnrbase/debug.py | noisy_wrap | def noisy_wrap(__func: Callable) -> Callable:
"""Decorator to enable DebugPrint for a given function.
Args:
__func: Function to wrap
Returns:
Wrapped function
"""
# pylint: disable=missing-docstring
def wrapper(*args, **kwargs):
DebugPrint.enable()
try:
... | python | def noisy_wrap(__func: Callable) -> Callable:
"""Decorator to enable DebugPrint for a given function.
Args:
__func: Function to wrap
Returns:
Wrapped function
"""
# pylint: disable=missing-docstring
def wrapper(*args, **kwargs):
DebugPrint.enable()
try:
... | [
"def",
"noisy_wrap",
"(",
"__func",
":",
"Callable",
")",
"->",
"Callable",
":",
"# pylint: disable=missing-docstring",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"DebugPrint",
".",
"enable",
"(",
")",
"try",
":",
"__func",
"(",... | Decorator to enable DebugPrint for a given function.
Args:
__func: Function to wrap
Returns:
Wrapped function | [
"Decorator",
"to",
"enable",
"DebugPrint",
"for",
"a",
"given",
"function",
"."
] | train | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/debug.py#L74-L90 |
JNRowe/jnrbase | jnrbase/debug.py | on_enter | def on_enter(__msg: Optional[Union[Callable, str]] = None) -> Callable:
"""Decorator to display a message when entering a function.
Args:
__msg: Message to display
Returns:
Wrapped function
"""
# pylint: disable=missing-docstring
def decorator(__func):
@wraps(__func)
... | python | def on_enter(__msg: Optional[Union[Callable, str]] = None) -> Callable:
"""Decorator to display a message when entering a function.
Args:
__msg: Message to display
Returns:
Wrapped function
"""
# pylint: disable=missing-docstring
def decorator(__func):
@wraps(__func)
... | [
"def",
"on_enter",
"(",
"__msg",
":",
"Optional",
"[",
"Union",
"[",
"Callable",
",",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"Callable",
":",
"# pylint: disable=missing-docstring",
"def",
"decorator",
"(",
"__func",
")",
":",
"@",
"wraps",
"(",
"__func",... | Decorator to display a message when entering a function.
Args:
__msg: Message to display
Returns:
Wrapped function | [
"Decorator",
"to",
"display",
"a",
"message",
"when",
"entering",
"a",
"function",
"."
] | train | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/debug.py#L93-L114 |
JNRowe/jnrbase | jnrbase/debug.py | DebugPrint.write | def write(self, __text: str) -> None:
"""Write text to the debug stream.
Args:
__text: Text to write
"""
if __text == os.linesep:
self.handle.write(__text)
else:
frame = inspect.currentframe()
if frame is None:
file... | python | def write(self, __text: str) -> None:
"""Write text to the debug stream.
Args:
__text: Text to write
"""
if __text == os.linesep:
self.handle.write(__text)
else:
frame = inspect.currentframe()
if frame is None:
file... | [
"def",
"write",
"(",
"self",
",",
"__text",
":",
"str",
")",
"->",
"None",
":",
"if",
"__text",
"==",
"os",
".",
"linesep",
":",
"self",
".",
"handle",
".",
"write",
"(",
"__text",
")",
"else",
":",
"frame",
"=",
"inspect",
".",
"currentframe",
"("... | Write text to the debug stream.
Args:
__text: Text to write | [
"Write",
"text",
"to",
"the",
"debug",
"stream",
"."
] | train | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/debug.py#L42-L60 |
JNRowe/jnrbase | jnrbase/debug.py | DebugPrint.enable | def enable() -> None:
"""Patch ``sys.stdout`` to use ``DebugPrint``."""
if not isinstance(sys.stdout, DebugPrint):
sys.stdout = DebugPrint(sys.stdout) | python | def enable() -> None:
"""Patch ``sys.stdout`` to use ``DebugPrint``."""
if not isinstance(sys.stdout, DebugPrint):
sys.stdout = DebugPrint(sys.stdout) | [
"def",
"enable",
"(",
")",
"->",
"None",
":",
"if",
"not",
"isinstance",
"(",
"sys",
".",
"stdout",
",",
"DebugPrint",
")",
":",
"sys",
".",
"stdout",
"=",
"DebugPrint",
"(",
"sys",
".",
"stdout",
")"
] | Patch ``sys.stdout`` to use ``DebugPrint``. | [
"Patch",
"sys",
".",
"stdout",
"to",
"use",
"DebugPrint",
"."
] | train | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/debug.py#L63-L66 |
toastdriven/alligator | alligator/workers.py | Worker.starting | def starting(self):
"""
Prints a startup message to stdout.
"""
ident = self.ident()
print('{} starting & consuming "{}".'.format(ident, self.to_consume))
if self.max_tasks:
print('{} will die after {} tasks.'.format(ident, self.max_tasks))
else:
... | python | def starting(self):
"""
Prints a startup message to stdout.
"""
ident = self.ident()
print('{} starting & consuming "{}".'.format(ident, self.to_consume))
if self.max_tasks:
print('{} will die after {} tasks.'.format(ident, self.max_tasks))
else:
... | [
"def",
"starting",
"(",
"self",
")",
":",
"ident",
"=",
"self",
".",
"ident",
"(",
")",
"print",
"(",
"'{} starting & consuming \"{}\".'",
".",
"format",
"(",
"ident",
",",
"self",
".",
"to_consume",
")",
")",
"if",
"self",
".",
"max_tasks",
":",
"print"... | Prints a startup message to stdout. | [
"Prints",
"a",
"startup",
"message",
"to",
"stdout",
"."
] | train | https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/workers.py#L55-L65 |
toastdriven/alligator | alligator/workers.py | Worker.interrupt | def interrupt(self):
"""
Prints an interrupt message to stdout.
"""
ident = self.ident()
print('{} for "{}" saw interrupt. Finishing in-progress task.'.format(
ident,
self.to_consume
)) | python | def interrupt(self):
"""
Prints an interrupt message to stdout.
"""
ident = self.ident()
print('{} for "{}" saw interrupt. Finishing in-progress task.'.format(
ident,
self.to_consume
)) | [
"def",
"interrupt",
"(",
"self",
")",
":",
"ident",
"=",
"self",
".",
"ident",
"(",
")",
"print",
"(",
"'{} for \"{}\" saw interrupt. Finishing in-progress task.'",
".",
"format",
"(",
"ident",
",",
"self",
".",
"to_consume",
")",
")"
] | Prints an interrupt message to stdout. | [
"Prints",
"an",
"interrupt",
"message",
"to",
"stdout",
"."
] | train | https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/workers.py#L67-L75 |
toastdriven/alligator | alligator/workers.py | Worker.stopping | def stopping(self):
"""
Prints a shutdown message to stdout.
"""
ident = self.ident()
print('{} for "{}" shutting down. Consumed {} tasks.'.format(
ident,
self.to_consume,
self.tasks_complete
)) | python | def stopping(self):
"""
Prints a shutdown message to stdout.
"""
ident = self.ident()
print('{} for "{}" shutting down. Consumed {} tasks.'.format(
ident,
self.to_consume,
self.tasks_complete
)) | [
"def",
"stopping",
"(",
"self",
")",
":",
"ident",
"=",
"self",
".",
"ident",
"(",
")",
"print",
"(",
"'{} for \"{}\" shutting down. Consumed {} tasks.'",
".",
"format",
"(",
"ident",
",",
"self",
".",
"to_consume",
",",
"self",
".",
"tasks_complete",
")",
"... | Prints a shutdown message to stdout. | [
"Prints",
"a",
"shutdown",
"message",
"to",
"stdout",
"."
] | train | https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/workers.py#L77-L86 |
toastdriven/alligator | alligator/workers.py | Worker.run_forever | def run_forever(self):
"""
Causes the worker to run either forever or until the
``Worker.max_tasks`` are reached.
"""
self.starting()
self.keep_running = True
def handle(signum, frame):
self.interrupt()
self.keep_running = False
s... | python | def run_forever(self):
"""
Causes the worker to run either forever or until the
``Worker.max_tasks`` are reached.
"""
self.starting()
self.keep_running = True
def handle(signum, frame):
self.interrupt()
self.keep_running = False
s... | [
"def",
"run_forever",
"(",
"self",
")",
":",
"self",
".",
"starting",
"(",
")",
"self",
".",
"keep_running",
"=",
"True",
"def",
"handle",
"(",
"signum",
",",
"frame",
")",
":",
"self",
".",
"interrupt",
"(",
")",
"self",
".",
"keep_running",
"=",
"F... | Causes the worker to run either forever or until the
``Worker.max_tasks`` are reached. | [
"Causes",
"the",
"worker",
"to",
"run",
"either",
"forever",
"or",
"until",
"the",
"Worker",
".",
"max_tasks",
"are",
"reached",
"."
] | train | https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/workers.py#L96-L122 |
naphatkrit/temp-utils | temp_utils/contextmanagers.py | chdir | def chdir(path):
"""Change the working directory to `path` for the duration of this context
manager.
:param str path: The path to change to
"""
cur_cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(cur_cwd) | python | def chdir(path):
"""Change the working directory to `path` for the duration of this context
manager.
:param str path: The path to change to
"""
cur_cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(cur_cwd) | [
"def",
"chdir",
"(",
"path",
")",
":",
"cur_cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"path",
")",
"try",
":",
"yield",
"finally",
":",
"os",
".",
"chdir",
"(",
"cur_cwd",
")"
] | Change the working directory to `path` for the duration of this context
manager.
:param str path: The path to change to | [
"Change",
"the",
"working",
"directory",
"to",
"path",
"for",
"the",
"duration",
"of",
"this",
"context",
"manager",
"."
] | train | https://github.com/naphatkrit/temp-utils/blob/4b0cb5a76fcaa9f3b5db05ed1f5f7a1979a86d2c/temp_utils/contextmanagers.py#L9-L20 |
naphatkrit/temp-utils | temp_utils/contextmanagers.py | temp_file | def temp_file():
"""Create a temporary file for the duration of this context manager,
deleting it afterwards.
Yields:
str - path to the file
"""
fd, path = tempfile.mkstemp()
os.close(fd)
try:
yield path
finally:
os.remove(path) | python | def temp_file():
"""Create a temporary file for the duration of this context manager,
deleting it afterwards.
Yields:
str - path to the file
"""
fd, path = tempfile.mkstemp()
os.close(fd)
try:
yield path
finally:
os.remove(path) | [
"def",
"temp_file",
"(",
")",
":",
"fd",
",",
"path",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"os",
".",
"close",
"(",
"fd",
")",
"try",
":",
"yield",
"path",
"finally",
":",
"os",
".",
"remove",
"(",
"path",
")"
] | Create a temporary file for the duration of this context manager,
deleting it afterwards.
Yields:
str - path to the file | [
"Create",
"a",
"temporary",
"file",
"for",
"the",
"duration",
"of",
"this",
"context",
"manager",
"deleting",
"it",
"afterwards",
"."
] | train | https://github.com/naphatkrit/temp-utils/blob/4b0cb5a76fcaa9f3b5db05ed1f5f7a1979a86d2c/temp_utils/contextmanagers.py#L39-L51 |
maxfischer2781/chainlet | docs/conf.py | skip_pickle_inject | def skip_pickle_inject(app, what, name, obj, skip, options):
"""skip global wrapper._raw_slave names used only for pickle support"""
if name.endswith('._raw_slave'):
return True
return None | python | def skip_pickle_inject(app, what, name, obj, skip, options):
"""skip global wrapper._raw_slave names used only for pickle support"""
if name.endswith('._raw_slave'):
return True
return None | [
"def",
"skip_pickle_inject",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"skip",
",",
"options",
")",
":",
"if",
"name",
".",
"endswith",
"(",
"'._raw_slave'",
")",
":",
"return",
"True",
"return",
"None"
] | skip global wrapper._raw_slave names used only for pickle support | [
"skip",
"global",
"wrapper",
".",
"_raw_slave",
"names",
"used",
"only",
"for",
"pickle",
"support"
] | train | https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/docs/conf.py#L170-L174 |
maxfischer2781/chainlet | docs/conf.py | wraplet_signature | def wraplet_signature(app, what, name, obj, options, signature, return_annotation):
"""have wrapplets use the signature of the slave"""
try:
wrapped = obj._raw_slave
except AttributeError:
return None
else:
slave_argspec = autodoc.getargspec(wrapped)
slave_signature = aut... | python | def wraplet_signature(app, what, name, obj, options, signature, return_annotation):
"""have wrapplets use the signature of the slave"""
try:
wrapped = obj._raw_slave
except AttributeError:
return None
else:
slave_argspec = autodoc.getargspec(wrapped)
slave_signature = aut... | [
"def",
"wraplet_signature",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"options",
",",
"signature",
",",
"return_annotation",
")",
":",
"try",
":",
"wrapped",
"=",
"obj",
".",
"_raw_slave",
"except",
"AttributeError",
":",
"return",
"None",
"el... | have wrapplets use the signature of the slave | [
"have",
"wrapplets",
"use",
"the",
"signature",
"of",
"the",
"slave"
] | train | https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/docs/conf.py#L177-L186 |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/passwd_reader.py | load_users | def load_users(path=settings.LOGIN_FILE):
"""
Read passwd file and return dict with users and all their settings.
Args:
path (str, default settings.LOGIN_FILE): path of the file,
which will be loaded (default :attr:`ftp.settings.LOGIN_FILE`).
Returns:
(dict): username: {pas... | python | def load_users(path=settings.LOGIN_FILE):
"""
Read passwd file and return dict with users and all their settings.
Args:
path (str, default settings.LOGIN_FILE): path of the file,
which will be loaded (default :attr:`ftp.settings.LOGIN_FILE`).
Returns:
(dict): username: {pas... | [
"def",
"load_users",
"(",
"path",
"=",
"settings",
".",
"LOGIN_FILE",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"{",
"}",
"data",
"=",
"\"\"",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"data... | Read passwd file and return dict with users and all their settings.
Args:
path (str, default settings.LOGIN_FILE): path of the file,
which will be loaded (default :attr:`ftp.settings.LOGIN_FILE`).
Returns:
(dict): username: {pass_hash, uid, gid, full_name, home, shell}
Example... | [
"Read",
"passwd",
"file",
"and",
"return",
"dict",
"with",
"users",
"and",
"all",
"their",
"settings",
"."
] | train | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/passwd_reader.py#L21-L73 |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/passwd_reader.py | save_users | def save_users(users, path=settings.LOGIN_FILE):
"""
Save dictionary with user data to passwd file (default
:attr:`ftp.settings.LOGIN_FILE`).
Args:
users (dict): dictionary with user data. For details look at dict
returned from :func:`load_users`.
path (str, defaul... | python | def save_users(users, path=settings.LOGIN_FILE):
"""
Save dictionary with user data to passwd file (default
:attr:`ftp.settings.LOGIN_FILE`).
Args:
users (dict): dictionary with user data. For details look at dict
returned from :func:`load_users`.
path (str, defaul... | [
"def",
"save_users",
"(",
"users",
",",
"path",
"=",
"settings",
".",
"LOGIN_FILE",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"w\"",
")",
"as",
"fh",
":",
"for",
"username",
",",
"data",
"in",
"users",
".",
"items",
"(",
")",
":",
"pass_line",
... | Save dictionary with user data to passwd file (default
:attr:`ftp.settings.LOGIN_FILE`).
Args:
users (dict): dictionary with user data. For details look at dict
returned from :func:`load_users`.
path (str, default settings.LOGIN_FILE): path of the file, where the
... | [
"Save",
"dictionary",
"with",
"user",
"data",
"to",
"passwd",
"file",
"(",
"default",
":",
"attr",
":",
"ftp",
".",
"settings",
".",
"LOGIN_FILE",
")",
"."
] | train | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/passwd_reader.py#L76-L98 |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/passwd_reader.py | set_permissions | def set_permissions(filename, uid=None, gid=None, mode=0775):
"""
Set pemissions for given `filename`.
Args:
filename (str): name of the file/directory
uid (int, default proftpd): user ID - if not set, user ID of `proftpd`
is used
gid (int): group... | python | def set_permissions(filename, uid=None, gid=None, mode=0775):
"""
Set pemissions for given `filename`.
Args:
filename (str): name of the file/directory
uid (int, default proftpd): user ID - if not set, user ID of `proftpd`
is used
gid (int): group... | [
"def",
"set_permissions",
"(",
"filename",
",",
"uid",
"=",
"None",
",",
"gid",
"=",
"None",
",",
"mode",
"=",
"0775",
")",
":",
"if",
"uid",
"is",
"None",
":",
"uid",
"=",
"get_ftp_uid",
"(",
")",
"if",
"gid",
"is",
"None",
":",
"gid",
"=",
"-",... | Set pemissions for given `filename`.
Args:
filename (str): name of the file/directory
uid (int, default proftpd): user ID - if not set, user ID of `proftpd`
is used
gid (int): group ID, if not set, it is not changed
mode (int, default 0775): unix ... | [
"Set",
"pemissions",
"for",
"given",
"filename",
"."
] | train | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/passwd_reader.py#L115-L133 |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/passwd_reader.py | _decode_config | def _decode_config(conf_str):
"""
Decode string to configuration dict.
Only values defined in settings._ALLOWED_MERGES can be redefined.
"""
conf_str = conf_str.strip()
# convert "tttff" -> [True, True, True, False, False]
conf = map(
lambda x: True if x.upper() == "T" else False,
... | python | def _decode_config(conf_str):
"""
Decode string to configuration dict.
Only values defined in settings._ALLOWED_MERGES can be redefined.
"""
conf_str = conf_str.strip()
# convert "tttff" -> [True, True, True, False, False]
conf = map(
lambda x: True if x.upper() == "T" else False,
... | [
"def",
"_decode_config",
"(",
"conf_str",
")",
":",
"conf_str",
"=",
"conf_str",
".",
"strip",
"(",
")",
"# convert \"tttff\" -> [True, True, True, False, False]",
"conf",
"=",
"map",
"(",
"lambda",
"x",
":",
"True",
"if",
"x",
".",
"upper",
"(",
")",
"==",
... | Decode string to configuration dict.
Only values defined in settings._ALLOWED_MERGES can be redefined. | [
"Decode",
"string",
"to",
"configuration",
"dict",
"."
] | train | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/passwd_reader.py#L136-L150 |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/passwd_reader.py | _encode_config | def _encode_config(conf_dict):
"""Encode `conf_dict` to string."""
out = []
# get variables in order defined in settings._ALLOWED_MERGES
for var in settings._ALLOWED_MERGES:
out.append(conf_dict[var])
# convert bools to chars
out = map(
lambda x: "t" if x else "f",
out
... | python | def _encode_config(conf_dict):
"""Encode `conf_dict` to string."""
out = []
# get variables in order defined in settings._ALLOWED_MERGES
for var in settings._ALLOWED_MERGES:
out.append(conf_dict[var])
# convert bools to chars
out = map(
lambda x: "t" if x else "f",
out
... | [
"def",
"_encode_config",
"(",
"conf_dict",
")",
":",
"out",
"=",
"[",
"]",
"# get variables in order defined in settings._ALLOWED_MERGES",
"for",
"var",
"in",
"settings",
".",
"_ALLOWED_MERGES",
":",
"out",
".",
"append",
"(",
"conf_dict",
"[",
"var",
"]",
")",
... | Encode `conf_dict` to string. | [
"Encode",
"conf_dict",
"to",
"string",
"."
] | train | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/passwd_reader.py#L153-L167 |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/passwd_reader.py | read_user_config | def read_user_config(username, path=settings.LOGIN_FILE):
"""
Read user's configuration from otherwise unused field ``full_name`` in
passwd file.
Configuration is stored in string as list of t/f characters.
"""
return _decode_config(load_users(path=path)[username]["full_name"]) | python | def read_user_config(username, path=settings.LOGIN_FILE):
"""
Read user's configuration from otherwise unused field ``full_name`` in
passwd file.
Configuration is stored in string as list of t/f characters.
"""
return _decode_config(load_users(path=path)[username]["full_name"]) | [
"def",
"read_user_config",
"(",
"username",
",",
"path",
"=",
"settings",
".",
"LOGIN_FILE",
")",
":",
"return",
"_decode_config",
"(",
"load_users",
"(",
"path",
"=",
"path",
")",
"[",
"username",
"]",
"[",
"\"full_name\"",
"]",
")"
] | Read user's configuration from otherwise unused field ``full_name`` in
passwd file.
Configuration is stored in string as list of t/f characters. | [
"Read",
"user",
"s",
"configuration",
"from",
"otherwise",
"unused",
"field",
"full_name",
"in",
"passwd",
"file",
"."
] | train | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/passwd_reader.py#L170-L177 |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/passwd_reader.py | save_user_config | def save_user_config(username, conf_dict, path=settings.LOGIN_FILE):
"""
Save user's configuration to otherwise unused field ``full_name`` in passwd
file.
"""
users = load_users(path=path)
users[username]["full_name"] = _encode_config(conf_dict)
save_users(users, path=path) | python | def save_user_config(username, conf_dict, path=settings.LOGIN_FILE):
"""
Save user's configuration to otherwise unused field ``full_name`` in passwd
file.
"""
users = load_users(path=path)
users[username]["full_name"] = _encode_config(conf_dict)
save_users(users, path=path) | [
"def",
"save_user_config",
"(",
"username",
",",
"conf_dict",
",",
"path",
"=",
"settings",
".",
"LOGIN_FILE",
")",
":",
"users",
"=",
"load_users",
"(",
"path",
"=",
"path",
")",
"users",
"[",
"username",
"]",
"[",
"\"full_name\"",
"]",
"=",
"_encode_conf... | Save user's configuration to otherwise unused field ``full_name`` in passwd
file. | [
"Save",
"user",
"s",
"configuration",
"to",
"otherwise",
"unused",
"field",
"full_name",
"in",
"passwd",
"file",
"."
] | train | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/passwd_reader.py#L180-L187 |
xaptum/xtt-python | xtt/crypto/ecdsap256.py | create_ecdsap256_key_pair | def create_ecdsap256_key_pair():
"""
Create a new ECDSAP256 key pair.
:returns: a tuple of the public and private keys
"""
pub = ECDSAP256PublicKey()
priv = ECDSAP256PrivateKey()
rc = _lib.xtt_crypto_create_ecdsap256_key_pair(pub.native, priv.native)
if rc == RC.SUCCESS:
return... | python | def create_ecdsap256_key_pair():
"""
Create a new ECDSAP256 key pair.
:returns: a tuple of the public and private keys
"""
pub = ECDSAP256PublicKey()
priv = ECDSAP256PrivateKey()
rc = _lib.xtt_crypto_create_ecdsap256_key_pair(pub.native, priv.native)
if rc == RC.SUCCESS:
return... | [
"def",
"create_ecdsap256_key_pair",
"(",
")",
":",
"pub",
"=",
"ECDSAP256PublicKey",
"(",
")",
"priv",
"=",
"ECDSAP256PrivateKey",
"(",
")",
"rc",
"=",
"_lib",
".",
"xtt_crypto_create_ecdsap256_key_pair",
"(",
"pub",
".",
"native",
",",
"priv",
".",
"native",
... | Create a new ECDSAP256 key pair.
:returns: a tuple of the public and private keys | [
"Create",
"a",
"new",
"ECDSAP256",
"key",
"pair",
"."
] | train | https://github.com/xaptum/xtt-python/blob/23ee469488d710d730314bec1136c4dd7ac2cd5c/xtt/crypto/ecdsap256.py#L35-L47 |
skibblenybbles/django-commando | commando/management/base.py | get_option_default | def get_option_default(option):
"""
Given an optparse.Option, returns a two-tuple of the option's variable name
and default value.
"""
return (
option.dest,
None if option.default is optparse.NO_DEFAULT else option.default,
) | python | def get_option_default(option):
"""
Given an optparse.Option, returns a two-tuple of the option's variable name
and default value.
"""
return (
option.dest,
None if option.default is optparse.NO_DEFAULT else option.default,
) | [
"def",
"get_option_default",
"(",
"option",
")",
":",
"return",
"(",
"option",
".",
"dest",
",",
"None",
"if",
"option",
".",
"default",
"is",
"optparse",
".",
"NO_DEFAULT",
"else",
"option",
".",
"default",
",",
")"
] | Given an optparse.Option, returns a two-tuple of the option's variable name
and default value. | [
"Given",
"an",
"optparse",
".",
"Option",
"returns",
"a",
"two",
"-",
"tuple",
"of",
"the",
"option",
"s",
"variable",
"name",
"and",
"default",
"value",
"."
] | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L12-L21 |
skibblenybbles/django-commando | commando/management/base.py | get_command_class_from_apps | def get_command_class_from_apps(name, apps, exclude_packages=None, exclude_command_class=None):
"""
Searches through the given apps to find the named command class. Skips
over any packages specified by exclude_packages and any command class
specified by exclude_command_class. Returns the last command cl... | python | def get_command_class_from_apps(name, apps, exclude_packages=None, exclude_command_class=None):
"""
Searches through the given apps to find the named command class. Skips
over any packages specified by exclude_packages and any command class
specified by exclude_command_class. Returns the last command cl... | [
"def",
"get_command_class_from_apps",
"(",
"name",
",",
"apps",
",",
"exclude_packages",
"=",
"None",
",",
"exclude_command_class",
"=",
"None",
")",
":",
"if",
"exclude_packages",
"is",
"None",
":",
"exclude_packages",
"=",
"[",
"]",
"for",
"app",
"in",
"reve... | Searches through the given apps to find the named command class. Skips
over any packages specified by exclude_packages and any command class
specified by exclude_command_class. Returns the last command class found
or None if the command class could not be found.
Django's command searching behavior ... | [
"Searches",
"through",
"the",
"given",
"apps",
"to",
"find",
"the",
"named",
"command",
"class",
".",
"Skips",
"over",
"any",
"packages",
"specified",
"by",
"exclude_packages",
"and",
"any",
"command",
"class",
"specified",
"by",
"exclude_command_class",
".",
"R... | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L45-L71 |
skibblenybbles/django-commando | commando/management/base.py | get_command_class | def get_command_class(name, exclude_packages=None, exclude_command_class=None):
"""
Searches "django.core" and the apps in settings.INSTALLED_APPS to find the
named command class, optionally skipping packages or a particular
command class.
"""
from django.conf import settings
return get... | python | def get_command_class(name, exclude_packages=None, exclude_command_class=None):
"""
Searches "django.core" and the apps in settings.INSTALLED_APPS to find the
named command class, optionally skipping packages or a particular
command class.
"""
from django.conf import settings
return get... | [
"def",
"get_command_class",
"(",
"name",
",",
"exclude_packages",
"=",
"None",
",",
"exclude_command_class",
"=",
"None",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"return",
"get_command_class_from_apps",
"(",
"name",
",",
"settings",
".",
"... | Searches "django.core" and the apps in settings.INSTALLED_APPS to find the
named command class, optionally skipping packages or a particular
command class. | [
"Searches",
"django",
".",
"core",
"and",
"the",
"apps",
"in",
"settings",
".",
"INSTALLED_APPS",
"to",
"find",
"the",
"named",
"command",
"class",
"optionally",
"skipping",
"packages",
"or",
"a",
"particular",
"command",
"class",
"."
] | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L74-L88 |
skibblenybbles/django-commando | commando/management/base.py | get_command_and_defaults | def get_command_and_defaults(name, exclude_packages=None, exclude_command_class=None):
"""
Searches "django.core" and the apps in settings.INSTALLED_APPS to find the
named command class, optionally skipping packages or a particular command
class. Gathers the command's default options and returns the com... | python | def get_command_and_defaults(name, exclude_packages=None, exclude_command_class=None):
"""
Searches "django.core" and the apps in settings.INSTALLED_APPS to find the
named command class, optionally skipping packages or a particular command
class. Gathers the command's default options and returns the com... | [
"def",
"get_command_and_defaults",
"(",
"name",
",",
"exclude_packages",
"=",
"None",
",",
"exclude_command_class",
"=",
"None",
")",
":",
"command",
"=",
"get_command_class",
"(",
"name",
",",
"exclude_packages",
"=",
"exclude_packages",
",",
"exclude_command_class",... | Searches "django.core" and the apps in settings.INSTALLED_APPS to find the
named command class, optionally skipping packages or a particular command
class. Gathers the command's default options and returns the command and
options dictionary as a two-tuple: (command, options). Returns (None, {})
if the c... | [
"Searches",
"django",
".",
"core",
"and",
"the",
"apps",
"in",
"settings",
".",
"INSTALLED_APPS",
"to",
"find",
"the",
"named",
"command",
"class",
"optionally",
"skipping",
"packages",
"or",
"a",
"particular",
"command",
"class",
".",
"Gathers",
"the",
"comma... | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L91-L109 |
skibblenybbles/django-commando | commando/management/base.py | check_command | def check_command(self, name, exclude_packages=None, exclude_command_class=None):
"""
Uses get_command_class() to check for the presence of a command.
"""
return get_command_class(
name,
exclude_packages=exclude_packages,
exclude_command_class=exclude_command_class) is not ... | python | def check_command(self, name, exclude_packages=None, exclude_command_class=None):
"""
Uses get_command_class() to check for the presence of a command.
"""
return get_command_class(
name,
exclude_packages=exclude_packages,
exclude_command_class=exclude_command_class) is not ... | [
"def",
"check_command",
"(",
"self",
",",
"name",
",",
"exclude_packages",
"=",
"None",
",",
"exclude_command_class",
"=",
"None",
")",
":",
"return",
"get_command_class",
"(",
"name",
",",
"exclude_packages",
"=",
"exclude_packages",
",",
"exclude_command_class",
... | Uses get_command_class() to check for the presence of a command. | [
"Uses",
"get_command_class",
"()",
"to",
"check",
"for",
"the",
"presence",
"of",
"a",
"command",
"."
] | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L112-L120 |
skibblenybbles/django-commando | commando/management/base.py | check_program | def check_program(name):
"""
Uses the shell program "which" to determine whether the named program
is available on the shell PATH.
"""
with open(os.devnull, "w") as null:
try:
subprocess.check_call(("which", name), stdout=null, stderr=null)
except subprocess.CalledPr... | python | def check_program(name):
"""
Uses the shell program "which" to determine whether the named program
is available on the shell PATH.
"""
with open(os.devnull, "w") as null:
try:
subprocess.check_call(("which", name), stdout=null, stderr=null)
except subprocess.CalledPr... | [
"def",
"check_program",
"(",
"name",
")",
":",
"with",
"open",
"(",
"os",
".",
"devnull",
",",
"\"w\"",
")",
"as",
"null",
":",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"(",
"\"which\"",
",",
"name",
")",
",",
"stdout",
"=",
"null",
",",
"... | Uses the shell program "which" to determine whether the named program
is available on the shell PATH. | [
"Uses",
"the",
"shell",
"program",
"which",
"to",
"determine",
"whether",
"the",
"named",
"program",
"is",
"available",
"on",
"the",
"shell",
"PATH",
"."
] | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L123-L134 |
skibblenybbles/django-commando | commando/management/base.py | CommandOptions.get_option_lists | def get_option_lists(self):
"""
A hook to override the option lists used to generate option names
and defaults.
"""
return [self.get_option_list()] + \
[option_list
for name, description, option_list
in self.get_option_groups()... | python | def get_option_lists(self):
"""
A hook to override the option lists used to generate option names
and defaults.
"""
return [self.get_option_list()] + \
[option_list
for name, description, option_list
in self.get_option_groups()... | [
"def",
"get_option_lists",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"get_option_list",
"(",
")",
"]",
"+",
"[",
"option_list",
"for",
"name",
",",
"description",
",",
"option_list",
"in",
"self",
".",
"get_option_groups",
"(",
")",
"]"
] | A hook to override the option lists used to generate option names
and defaults. | [
"A",
"hook",
"to",
"override",
"the",
"option",
"lists",
"used",
"to",
"generate",
"option",
"names",
"and",
"defaults",
"."
] | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L194-L203 |
skibblenybbles/django-commando | commando/management/base.py | CommandOptions.get_options | def get_options(self):
"""
A hook to override the flattened list of all options used to generate
option names and defaults.
"""
return reduce(
list.__add__,
[list(option_list) for option_list in self.get_option_lists()],
[]) | python | def get_options(self):
"""
A hook to override the flattened list of all options used to generate
option names and defaults.
"""
return reduce(
list.__add__,
[list(option_list) for option_list in self.get_option_lists()],
[]) | [
"def",
"get_options",
"(",
"self",
")",
":",
"return",
"reduce",
"(",
"list",
".",
"__add__",
",",
"[",
"list",
"(",
"option_list",
")",
"for",
"option_list",
"in",
"self",
".",
"get_option_lists",
"(",
")",
"]",
",",
"[",
"]",
")"
] | A hook to override the flattened list of all options used to generate
option names and defaults. | [
"A",
"hook",
"to",
"override",
"the",
"flattened",
"list",
"of",
"all",
"options",
"used",
"to",
"generate",
"option",
"names",
"and",
"defaults",
"."
] | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L205-L214 |
skibblenybbles/django-commando | commando/management/base.py | Command.create_parser | def create_parser(self, prog_name, subcommand):
"""
Customize the parser to include option groups.
"""
parser = optparse.OptionParser(
prog=prog_name,
usage=self.usage(subcommand),
version=self.get_version(),
option_list=self.get_o... | python | def create_parser(self, prog_name, subcommand):
"""
Customize the parser to include option groups.
"""
parser = optparse.OptionParser(
prog=prog_name,
usage=self.usage(subcommand),
version=self.get_version(),
option_list=self.get_o... | [
"def",
"create_parser",
"(",
"self",
",",
"prog_name",
",",
"subcommand",
")",
":",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"prog",
"=",
"prog_name",
",",
"usage",
"=",
"self",
".",
"usage",
"(",
"subcommand",
")",
",",
"version",
"=",
"self... | Customize the parser to include option groups. | [
"Customize",
"the",
"parser",
"to",
"include",
"option",
"groups",
"."
] | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L249-L263 |
skibblenybbles/django-commando | commando/management/base.py | Command.parse_options | def parse_options(self, options):
"""
Perform any required parsing on the option values from optparse.
Attempts to call a parse_option_<name> method for each option name
returned by self.get_option_names().
"""
for name in self.get_option_names():
par... | python | def parse_options(self, options):
"""
Perform any required parsing on the option values from optparse.
Attempts to call a parse_option_<name> method for each option name
returned by self.get_option_names().
"""
for name in self.get_option_names():
par... | [
"def",
"parse_options",
"(",
"self",
",",
"options",
")",
":",
"for",
"name",
"in",
"self",
".",
"get_option_names",
"(",
")",
":",
"parse",
"=",
"getattr",
"(",
"self",
",",
"\"parse_option_{name:s}\"",
".",
"format",
"(",
"name",
"=",
"name",
")",
",",... | Perform any required parsing on the option values from optparse.
Attempts to call a parse_option_<name> method for each option name
returned by self.get_option_names(). | [
"Perform",
"any",
"required",
"parsing",
"on",
"the",
"option",
"values",
"from",
"optparse",
".",
"Attempts",
"to",
"call",
"a",
"parse_option_<name",
">",
"method",
"for",
"each",
"option",
"name",
"returned",
"by",
"self",
".",
"get_option_names",
"()",
"."... | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L272-L284 |
skibblenybbles/django-commando | commando/management/base.py | Command.handle | def handle(self, *arguments, **options):
"""
Parses arguments and options, runs validate_<action> for each action
named by self.get_actions(), then runs handle_<action> for each action
named by self.get_actions().
"""
self.arguments = arguments
self.optio... | python | def handle(self, *arguments, **options):
"""
Parses arguments and options, runs validate_<action> for each action
named by self.get_actions(), then runs handle_<action> for each action
named by self.get_actions().
"""
self.arguments = arguments
self.optio... | [
"def",
"handle",
"(",
"self",
",",
"*",
"arguments",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"arguments",
"=",
"arguments",
"self",
".",
"options",
"=",
"options",
"self",
".",
"arguments",
"=",
"self",
".",
"parse_arguments",
"(",
"arguments",
... | Parses arguments and options, runs validate_<action> for each action
named by self.get_actions(), then runs handle_<action> for each action
named by self.get_actions(). | [
"Parses",
"arguments",
"and",
"options",
"runs",
"validate_<action",
">",
"for",
"each",
"action",
"named",
"by",
"self",
".",
"get_actions",
"()",
"then",
"runs",
"handle_<action",
">",
"for",
"each",
"action",
"named",
"by",
"self",
".",
"get_actions",
"()",... | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L286-L307 |
skibblenybbles/django-commando | commando/management/base.py | BaseCommandOptions.check_command | def check_command(self, name):
"""
Checks whether the given Django management command exists, excluding
this command from the search.
"""
if not check_command(
name,
exclude_packages=self.get_exclude_packages(),
exclude_command_class=... | python | def check_command(self, name):
"""
Checks whether the given Django management command exists, excluding
this command from the search.
"""
if not check_command(
name,
exclude_packages=self.get_exclude_packages(),
exclude_command_class=... | [
"def",
"check_command",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"check_command",
"(",
"name",
",",
"exclude_packages",
"=",
"self",
".",
"get_exclude_packages",
"(",
")",
",",
"exclude_command_class",
"=",
"self",
".",
"__class__",
")",
":",
"raise"... | Checks whether the given Django management command exists, excluding
this command from the search. | [
"Checks",
"whether",
"the",
"given",
"Django",
"management",
"command",
"exists",
"excluding",
"this",
"command",
"from",
"the",
"search",
"."
] | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L340-L355 |
skibblenybbles/django-commando | commando/management/base.py | BaseCommandOptions.check_program | def check_program(self, name):
"""
Checks whether a program is available on the shell PATH.
"""
if not check_program(name):
raise management.CommandError(
"The program \"{name:s}\" is not available in the shell. "
"Please ensure that \... | python | def check_program(self, name):
"""
Checks whether a program is available on the shell PATH.
"""
if not check_program(name):
raise management.CommandError(
"The program \"{name:s}\" is not available in the shell. "
"Please ensure that \... | [
"def",
"check_program",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"check_program",
"(",
"name",
")",
":",
"raise",
"management",
".",
"CommandError",
"(",
"\"The program \\\"{name:s}\\\" is not available in the shell. \"",
"\"Please ensure that \\\"{name:s}\\\" is in... | Checks whether a program is available on the shell PATH. | [
"Checks",
"whether",
"a",
"program",
"is",
"available",
"on",
"the",
"shell",
"PATH",
"."
] | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L357-L367 |
skibblenybbles/django-commando | commando/management/base.py | BaseCommandOptions.call_command | def call_command(self, name, *arguments, **options):
"""
Finds the given Django management command and default options,
excluding this command, and calls it with the given arguments
and override options.
"""
command, defaults = get_command_and_defaults(
... | python | def call_command(self, name, *arguments, **options):
"""
Finds the given Django management command and default options,
excluding this command, and calls it with the given arguments
and override options.
"""
command, defaults = get_command_and_defaults(
... | [
"def",
"call_command",
"(",
"self",
",",
"name",
",",
"*",
"arguments",
",",
"*",
"*",
"options",
")",
":",
"command",
",",
"defaults",
"=",
"get_command_and_defaults",
"(",
"name",
",",
"exclude_packages",
"=",
"self",
".",
"get_exclude_packages",
"(",
")",... | Finds the given Django management command and default options,
excluding this command, and calls it with the given arguments
and override options. | [
"Finds",
"the",
"given",
"Django",
"management",
"command",
"and",
"default",
"options",
"excluding",
"this",
"command",
"and",
"calls",
"it",
"with",
"the",
"given",
"arguments",
"and",
"override",
"options",
"."
] | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L369-L385 |
skibblenybbles/django-commando | commando/management/base.py | BaseCommandOptions.call_program | def call_program(self, name, *arguments):
"""
Calls the shell program on the PATH with the given arguments.
"""
verbosity = self.options.get("verbosity", 1)
with self.devnull as null:
try:
subprocess.check_call((name,) + tuple(arguments),
... | python | def call_program(self, name, *arguments):
"""
Calls the shell program on the PATH with the given arguments.
"""
verbosity = self.options.get("verbosity", 1)
with self.devnull as null:
try:
subprocess.check_call((name,) + tuple(arguments),
... | [
"def",
"call_program",
"(",
"self",
",",
"name",
",",
"*",
"arguments",
")",
":",
"verbosity",
"=",
"self",
".",
"options",
".",
"get",
"(",
"\"verbosity\"",
",",
"1",
")",
"with",
"self",
".",
"devnull",
"as",
"null",
":",
"try",
":",
"subprocess",
... | Calls the shell program on the PATH with the given arguments. | [
"Calls",
"the",
"shell",
"program",
"on",
"the",
"PATH",
"with",
"the",
"given",
"arguments",
"."
] | train | https://github.com/skibblenybbles/django-commando/blob/dd1dd6969fc0dd8231fc115fee3eeb690809585b/commando/management/base.py#L387-L402 |
todddeluca/temps | setup.py | version | def version(modfile):
'''
Parse version from module without importing or evaluating the code.
The module should define a __version__ variable like __version__ = '2.0.1'.
'''
import re
with open(modfile) as fh:
for line in fh:
m = re.search(r"^__version__ = '([^']+)'$", line)
... | python | def version(modfile):
'''
Parse version from module without importing or evaluating the code.
The module should define a __version__ variable like __version__ = '2.0.1'.
'''
import re
with open(modfile) as fh:
for line in fh:
m = re.search(r"^__version__ = '([^']+)'$", line)
... | [
"def",
"version",
"(",
"modfile",
")",
":",
"import",
"re",
"with",
"open",
"(",
"modfile",
")",
"as",
"fh",
":",
"for",
"line",
"in",
"fh",
":",
"m",
"=",
"re",
".",
"search",
"(",
"r\"^__version__ = '([^']+)'$\"",
",",
"line",
")",
"if",
"m",
":",
... | Parse version from module without importing or evaluating the code.
The module should define a __version__ variable like __version__ = '2.0.1'. | [
"Parse",
"version",
"from",
"module",
"without",
"importing",
"or",
"evaluating",
"the",
"code",
".",
"The",
"module",
"should",
"define",
"a",
"__version__",
"variable",
"like",
"__version__",
"=",
"2",
".",
"0",
".",
"1",
"."
] | train | https://github.com/todddeluca/temps/blob/10bf4e71a6b2e8ad10fa8a272145968b6c84f61b/setup.py#L5-L16 |
colab/colab-superarchives-plugin | src/colab_superarchives/models.py | Thread.update_score | def update_score(self):
"""Update the relevance score for this thread.
The score is calculated with the following variables:
* vote_weight: 100 - (minus) 1 for each 3 days since
voted with minimum of 5.
* replies_weight: 300 - (minus) 1 for each 3 days since
replied... | python | def update_score(self):
"""Update the relevance score for this thread.
The score is calculated with the following variables:
* vote_weight: 100 - (minus) 1 for each 3 days since
voted with minimum of 5.
* replies_weight: 300 - (minus) 1 for each 3 days since
replied... | [
"def",
"update_score",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"subject_token",
":",
"return",
"vote_score",
"=",
"0",
"replies_score",
"=",
"0",
"for",
"msg",
"in",
"self",
".",
"message_set",
".",
"all",
"(",
")",
":",
"# Calculate replies_score... | Update the relevance score for this thread.
The score is calculated with the following variables:
* vote_weight: 100 - (minus) 1 for each 3 days since
voted with minimum of 5.
* replies_weight: 300 - (minus) 1 for each 3 days since
replied with minimum of 5.
* page_... | [
"Update",
"the",
"relevance",
"score",
"for",
"this",
"thread",
"."
] | train | https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/models.py#L173-L210 |
colab/colab-superarchives-plugin | src/colab_superarchives/models.py | Message.url | def url(self):
"""Shortcut to get thread url"""
return reverse('archives:thread_view',
args=[self.mailinglist.name,
self.thread.subject_token]) | python | def url(self):
"""Shortcut to get thread url"""
return reverse('archives:thread_view',
args=[self.mailinglist.name,
self.thread.subject_token]) | [
"def",
"url",
"(",
"self",
")",
":",
"return",
"reverse",
"(",
"'archives:thread_view'",
",",
"args",
"=",
"[",
"self",
".",
"mailinglist",
".",
"name",
",",
"self",
".",
"thread",
".",
"subject_token",
"]",
")"
] | Shortcut to get thread url | [
"Shortcut",
"to",
"get",
"thread",
"url"
] | train | https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/models.py#L373-L377 |
fizyk/pyramid_yml | tzf/pyramid_yml/scripts.py | print_config | def print_config(): # pragma: no cover
"""Print config entry function."""
description = """\
Print the deployment settings for a Pyramid application. Example:
'psettings deployment.ini'
"""
parser = argparse.ArgumentParser(
description=textwrap.dedent(description)
)
par... | python | def print_config(): # pragma: no cover
"""Print config entry function."""
description = """\
Print the deployment settings for a Pyramid application. Example:
'psettings deployment.ini'
"""
parser = argparse.ArgumentParser(
description=textwrap.dedent(description)
)
par... | [
"def",
"print_config",
"(",
")",
":",
"# pragma: no cover",
"description",
"=",
"\"\"\"\\\n Print the deployment settings for a Pyramid application. Example:\n 'psettings deployment.ini'\n \"\"\"",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
... | Print config entry function. | [
"Print",
"config",
"entry",
"function",
"."
] | train | https://github.com/fizyk/pyramid_yml/blob/1b36c4e74194c04d7d69b4d7f86801757e78f0a6/tzf/pyramid_yml/scripts.py#L17-L54 |
fizyk/pyramid_yml | tzf/pyramid_yml/scripts.py | printer | def printer(data, depth=0):
"""
Prepare data for printing.
:param data: a data value that will be processed by method
:param int depth: recurrency indicator, to maintain proper indent
:returns: string with formatted config
:rtype: str
"""
indent = _INDENT * depth
config_string = ''... | python | def printer(data, depth=0):
"""
Prepare data for printing.
:param data: a data value that will be processed by method
:param int depth: recurrency indicator, to maintain proper indent
:returns: string with formatted config
:rtype: str
"""
indent = _INDENT * depth
config_string = ''... | [
"def",
"printer",
"(",
"data",
",",
"depth",
"=",
"0",
")",
":",
"indent",
"=",
"_INDENT",
"*",
"depth",
"config_string",
"=",
"''",
"if",
"not",
"depth",
"else",
"':\\n'",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"for",
"key",
",",
... | Prepare data for printing.
:param data: a data value that will be processed by method
:param int depth: recurrency indicator, to maintain proper indent
:returns: string with formatted config
:rtype: str | [
"Prepare",
"data",
"for",
"printing",
"."
] | train | https://github.com/fizyk/pyramid_yml/blob/1b36c4e74194c04d7d69b4d7f86801757e78f0a6/tzf/pyramid_yml/scripts.py#L57-L87 |
fizyk/pyramid_yml | tzf/pyramid_yml/scripts.py | slice_config | def slice_config(config, key):
"""
Slice config for printing as defined in key.
:param ConfigManager config: configuration dictionary
:param str key: dotted key, by which config should be sliced for printing
:returns: sliced config
:rtype: dict
"""
if key:
keys = key.split('.')... | python | def slice_config(config, key):
"""
Slice config for printing as defined in key.
:param ConfigManager config: configuration dictionary
:param str key: dotted key, by which config should be sliced for printing
:returns: sliced config
:rtype: dict
"""
if key:
keys = key.split('.')... | [
"def",
"slice_config",
"(",
"config",
",",
"key",
")",
":",
"if",
"key",
":",
"keys",
"=",
"key",
".",
"split",
"(",
"'.'",
")",
"for",
"k",
"in",
"keys",
":",
"config",
"=",
"config",
"[",
"k",
"]",
"return",
"config"
] | Slice config for printing as defined in key.
:param ConfigManager config: configuration dictionary
:param str key: dotted key, by which config should be sliced for printing
:returns: sliced config
:rtype: dict | [
"Slice",
"config",
"for",
"printing",
"as",
"defined",
"in",
"key",
"."
] | train | https://github.com/fizyk/pyramid_yml/blob/1b36c4e74194c04d7d69b4d7f86801757e78f0a6/tzf/pyramid_yml/scripts.py#L90-L105 |
physacco/reverse | reverse.py | split_size | def split_size(size):
'''Split the file size into several chunks.'''
rem = size % CHUNK_SIZE
if rem == 0:
cnt = size // CHUNK_SIZE
else:
cnt = size // CHUNK_SIZE + 1
chunks = []
for i in range(cnt):
pos = i * CHUNK_SIZE
if i == cnt - 1:
disp = size - ... | python | def split_size(size):
'''Split the file size into several chunks.'''
rem = size % CHUNK_SIZE
if rem == 0:
cnt = size // CHUNK_SIZE
else:
cnt = size // CHUNK_SIZE + 1
chunks = []
for i in range(cnt):
pos = i * CHUNK_SIZE
if i == cnt - 1:
disp = size - ... | [
"def",
"split_size",
"(",
"size",
")",
":",
"rem",
"=",
"size",
"%",
"CHUNK_SIZE",
"if",
"rem",
"==",
"0",
":",
"cnt",
"=",
"size",
"//",
"CHUNK_SIZE",
"else",
":",
"cnt",
"=",
"size",
"//",
"CHUNK_SIZE",
"+",
"1",
"chunks",
"=",
"[",
"]",
"for",
... | Split the file size into several chunks. | [
"Split",
"the",
"file",
"size",
"into",
"several",
"chunks",
"."
] | train | https://github.com/physacco/reverse/blob/bb900e4831a3e33745d15265fbbbb2502397ebfd/reverse.py#L38-L54 |
physacco/reverse | reverse.py | reverse_fd | def reverse_fd(inf, outf):
'''Reverse the content of inf, write to outf.
Both inf and outf are file objects.
inf must be seekable.
'''
inf.seek(0, 2)
size = inf.tell()
if not size:
return
chunks = split_size(size)
for chunk in reversed(chunks):
inf.seek(chunk[0], 0)
... | python | def reverse_fd(inf, outf):
'''Reverse the content of inf, write to outf.
Both inf and outf are file objects.
inf must be seekable.
'''
inf.seek(0, 2)
size = inf.tell()
if not size:
return
chunks = split_size(size)
for chunk in reversed(chunks):
inf.seek(chunk[0], 0)
... | [
"def",
"reverse_fd",
"(",
"inf",
",",
"outf",
")",
":",
"inf",
".",
"seek",
"(",
"0",
",",
"2",
")",
"size",
"=",
"inf",
".",
"tell",
"(",
")",
"if",
"not",
"size",
":",
"return",
"chunks",
"=",
"split_size",
"(",
"size",
")",
"for",
"chunk",
"... | Reverse the content of inf, write to outf.
Both inf and outf are file objects.
inf must be seekable. | [
"Reverse",
"the",
"content",
"of",
"inf",
"write",
"to",
"outf",
".",
"Both",
"inf",
"and",
"outf",
"are",
"file",
"objects",
".",
"inf",
"must",
"be",
"seekable",
"."
] | train | https://github.com/physacco/reverse/blob/bb900e4831a3e33745d15265fbbbb2502397ebfd/reverse.py#L56-L72 |
physacco/reverse | reverse.py | reverse_file | def reverse_file(infile, outfile):
'''Reverse the content of infile, write to outfile.
Both infile and outfile are filenames or filepaths.
'''
with open(infile, 'rb') as inf:
with open(outfile, 'wb') as outf:
reverse_fd(inf, outf) | python | def reverse_file(infile, outfile):
'''Reverse the content of infile, write to outfile.
Both infile and outfile are filenames or filepaths.
'''
with open(infile, 'rb') as inf:
with open(outfile, 'wb') as outf:
reverse_fd(inf, outf) | [
"def",
"reverse_file",
"(",
"infile",
",",
"outfile",
")",
":",
"with",
"open",
"(",
"infile",
",",
"'rb'",
")",
"as",
"inf",
":",
"with",
"open",
"(",
"outfile",
",",
"'wb'",
")",
"as",
"outf",
":",
"reverse_fd",
"(",
"inf",
",",
"outf",
")"
] | Reverse the content of infile, write to outfile.
Both infile and outfile are filenames or filepaths. | [
"Reverse",
"the",
"content",
"of",
"infile",
"write",
"to",
"outfile",
".",
"Both",
"infile",
"and",
"outfile",
"are",
"filenames",
"or",
"filepaths",
"."
] | train | https://github.com/physacco/reverse/blob/bb900e4831a3e33745d15265fbbbb2502397ebfd/reverse.py#L74-L80 |
physacco/reverse | reverse.py | main | def main():
'''Script entry point.'''
import getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'hv', ['help', 'version'])
except getopt.GetoptError as err:
sys.stderr.write('Error: %s\n' % err)
exit(2)
for opt, _ in opts:
if opt in ['-h', '--help']:
s... | python | def main():
'''Script entry point.'''
import getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'hv', ['help', 'version'])
except getopt.GetoptError as err:
sys.stderr.write('Error: %s\n' % err)
exit(2)
for opt, _ in opts:
if opt in ['-h', '--help']:
s... | [
"def",
"main",
"(",
")",
":",
"import",
"getopt",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"'hv'",
",",
"[",
"'help'",
",",
"'version'",
"]",
")",
"except",
"getopt",
".",
... | Script entry point. | [
"Script",
"entry",
"point",
"."
] | train | https://github.com/physacco/reverse/blob/bb900e4831a3e33745d15265fbbbb2502397ebfd/reverse.py#L95-L123 |
eight04/safeprint | safeprint/__init__.py | BasePrinter.print | def print(self, *objects, **kwargs):
"""Micmic print interface"""
file = kwargs.get("file")
if file is not None and file is not sys.stdout:
PRINT(*objects, **kwargs)
else:
sep = STR(kwargs.get("sep", " "))
end = STR(kwargs.get("end", "\n"))
text = sep.join(STR(o) for o in objects)
self.imp_pr... | python | def print(self, *objects, **kwargs):
"""Micmic print interface"""
file = kwargs.get("file")
if file is not None and file is not sys.stdout:
PRINT(*objects, **kwargs)
else:
sep = STR(kwargs.get("sep", " "))
end = STR(kwargs.get("end", "\n"))
text = sep.join(STR(o) for o in objects)
self.imp_pr... | [
"def",
"print",
"(",
"self",
",",
"*",
"objects",
",",
"*",
"*",
"kwargs",
")",
":",
"file",
"=",
"kwargs",
".",
"get",
"(",
"\"file\"",
")",
"if",
"file",
"is",
"not",
"None",
"and",
"file",
"is",
"not",
"sys",
".",
"stdout",
":",
"PRINT",
"(",
... | Micmic print interface | [
"Micmic",
"print",
"interface"
] | train | https://github.com/eight04/safeprint/blob/e27a1653fb8d29e83952ec474931105b7911651a/safeprint/__init__.py#L61-L77 |
eight04/safeprint | safeprint/__init__.py | TryPrinter.imp_print | def imp_print(self, text, end):
"""Catch UnicodeEncodeError"""
try:
PRINT(text, end=end)
except UnicodeEncodeError:
for i in text:
try:
PRINT(i, end="")
except UnicodeEncodeError:
PRINT("?", end="")
PRINT("", end=end) | python | def imp_print(self, text, end):
"""Catch UnicodeEncodeError"""
try:
PRINT(text, end=end)
except UnicodeEncodeError:
for i in text:
try:
PRINT(i, end="")
except UnicodeEncodeError:
PRINT("?", end="")
PRINT("", end=end) | [
"def",
"imp_print",
"(",
"self",
",",
"text",
",",
"end",
")",
":",
"try",
":",
"PRINT",
"(",
"text",
",",
"end",
"=",
"end",
")",
"except",
"UnicodeEncodeError",
":",
"for",
"i",
"in",
"text",
":",
"try",
":",
"PRINT",
"(",
"i",
",",
"end",
"=",... | Catch UnicodeEncodeError | [
"Catch",
"UnicodeEncodeError"
] | train | https://github.com/eight04/safeprint/blob/e27a1653fb8d29e83952ec474931105b7911651a/safeprint/__init__.py#L92-L102 |
eight04/safeprint | safeprint/__init__.py | WinUnicodePrinter.imp_print | def imp_print(self, text, end):
"""Use win_unicode_console"""
PRINT(text, end=end, file=win_unicode_console.streams.stdout_text_transcoded) | python | def imp_print(self, text, end):
"""Use win_unicode_console"""
PRINT(text, end=end, file=win_unicode_console.streams.stdout_text_transcoded) | [
"def",
"imp_print",
"(",
"self",
",",
"text",
",",
"end",
")",
":",
"PRINT",
"(",
"text",
",",
"end",
"=",
"end",
",",
"file",
"=",
"win_unicode_console",
".",
"streams",
".",
"stdout_text_transcoded",
")"
] | Use win_unicode_console | [
"Use",
"win_unicode_console"
] | train | https://github.com/eight04/safeprint/blob/e27a1653fb8d29e83952ec474931105b7911651a/safeprint/__init__.py#L105-L107 |
eight04/safeprint | safeprint/__init__.py | EncodePrinter.imp_print | def imp_print(self, text, end):
"""Directly send utf8 bytes to stdout"""
sys.stdout.write((text + end).encode("utf-8")) | python | def imp_print(self, text, end):
"""Directly send utf8 bytes to stdout"""
sys.stdout.write((text + end).encode("utf-8")) | [
"def",
"imp_print",
"(",
"self",
",",
"text",
",",
"end",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"(",
"text",
"+",
"end",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")"
] | Directly send utf8 bytes to stdout | [
"Directly",
"send",
"utf8",
"bytes",
"to",
"stdout"
] | train | https://github.com/eight04/safeprint/blob/e27a1653fb8d29e83952ec474931105b7911651a/safeprint/__init__.py#L110-L112 |
rosenbrockc/acorn | acorn/logging/diff.py | cascade | def cascade(sequence, full=False):
"""Restores a sequence of string definitions using the first entry as the
original and then applying a series of :func:`~acorn.logging.diff.restore`
calls.
Args:
sequence (list): of results returned by
:func:`~acorn.logging.diff.compress`, except tha... | python | def cascade(sequence, full=False):
"""Restores a sequence of string definitions using the first entry as the
original and then applying a series of :func:`~acorn.logging.diff.restore`
calls.
Args:
sequence (list): of results returned by
:func:`~acorn.logging.diff.compress`, except tha... | [
"def",
"cascade",
"(",
"sequence",
",",
"full",
"=",
"False",
")",
":",
"if",
"len",
"(",
"sequence",
")",
"==",
"1",
":",
"return",
"sequence",
"[",
"0",
"]",
"left",
"=",
"sequence",
"[",
"0",
"]",
"if",
"full",
":",
"intermed",
"=",
"[",
"]",
... | Restores a sequence of string definitions using the first entry as the
original and then applying a series of :func:`~acorn.logging.diff.restore`
calls.
Args:
sequence (list): of results returned by
:func:`~acorn.logging.diff.compress`, except that the first entry should
be a li... | [
"Restores",
"a",
"sequence",
"of",
"string",
"definitions",
"using",
"the",
"first",
"entry",
"as",
"the",
"original",
"and",
"then",
"applying",
"a",
"series",
"of",
":",
"func",
":",
"~acorn",
".",
"logging",
".",
"diff",
".",
"restore",
"calls",
"."
] | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/diff.py#L5-L30 |
rosenbrockc/acorn | acorn/logging/diff.py | restore | def restore(cdiff, a):
"""Restores the full text of either the edited text using the
compressed diff.
Args:
cdiff (dict): compressed diff returned by
:func:`~acorn.logging.diff.compress`.
a (str or list): *original* string or list of strings to use as a
reference to res... | python | def restore(cdiff, a):
"""Restores the full text of either the edited text using the
compressed diff.
Args:
cdiff (dict): compressed diff returned by
:func:`~acorn.logging.diff.compress`.
a (str or list): *original* string or list of strings to use as a
reference to res... | [
"def",
"restore",
"(",
"cdiff",
",",
"a",
")",
":",
"left",
"=",
"a",
".",
"splitlines",
"(",
"1",
")",
"if",
"isinstance",
"(",
"a",
",",
"string_types",
")",
"else",
"a",
"lrest",
"=",
"[",
"]",
"iline",
"=",
"0",
"for",
"i",
",",
"line",
"in... | Restores the full text of either the edited text using the
compressed diff.
Args:
cdiff (dict): compressed diff returned by
:func:`~acorn.logging.diff.compress`.
a (str or list): *original* string or list of strings to use as a
reference to restore the edited version. | [
"Restores",
"the",
"full",
"text",
"of",
"either",
"the",
"edited",
"text",
"using",
"the",
"compressed",
"diff",
"."
] | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/diff.py#L32-L61 |
rosenbrockc/acorn | acorn/logging/diff.py | compress | def compress(a, b):
"""Performs the *compressed* diff of `a` and `b` such that the original
contents of the :func:`difflib.ndiff` call can be reconstructed using
:func:`~acorn.logging.diff.restore`.
Args:
a (str or list): *original* string or list of strings to diff.
b (str or list): *e... | python | def compress(a, b):
"""Performs the *compressed* diff of `a` and `b` such that the original
contents of the :func:`difflib.ndiff` call can be reconstructed using
:func:`~acorn.logging.diff.restore`.
Args:
a (str or list): *original* string or list of strings to diff.
b (str or list): *e... | [
"def",
"compress",
"(",
"a",
",",
"b",
")",
":",
"from",
"difflib",
"import",
"ndiff",
"left",
"=",
"a",
".",
"splitlines",
"(",
"1",
")",
"if",
"isinstance",
"(",
"a",
",",
"string_types",
")",
"else",
"a",
"right",
"=",
"b",
".",
"splitlines",
"(... | Performs the *compressed* diff of `a` and `b` such that the original
contents of the :func:`difflib.ndiff` call can be reconstructed using
:func:`~acorn.logging.diff.restore`.
Args:
a (str or list): *original* string or list of strings to diff.
b (str or list): *edited* string or list of st... | [
"Performs",
"the",
"*",
"compressed",
"*",
"diff",
"of",
"a",
"and",
"b",
"such",
"that",
"the",
"original",
"contents",
"of",
"the",
":",
"func",
":",
"difflib",
".",
"ndiff",
"call",
"can",
"be",
"reconstructed",
"using",
":",
"func",
":",
"~acorn",
... | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/diff.py#L63-L124 |
datadesk/django-greeking | greeking/fillmurray.py | get_url | def get_url(width, height, color=True):
"""
Craft the URL for a placekitten image.
By default they are in color. To retrieve a grayscale image, set
the color kwarg to False.
"""
d = dict(width=width, height=height)
return URL % d | python | def get_url(width, height, color=True):
"""
Craft the URL for a placekitten image.
By default they are in color. To retrieve a grayscale image, set
the color kwarg to False.
"""
d = dict(width=width, height=height)
return URL % d | [
"def",
"get_url",
"(",
"width",
",",
"height",
",",
"color",
"=",
"True",
")",
":",
"d",
"=",
"dict",
"(",
"width",
"=",
"width",
",",
"height",
"=",
"height",
")",
"return",
"URL",
"%",
"d"
] | Craft the URL for a placekitten image.
By default they are in color. To retrieve a grayscale image, set
the color kwarg to False. | [
"Craft",
"the",
"URL",
"for",
"a",
"placekitten",
"image",
"."
] | train | https://github.com/datadesk/django-greeking/blob/72509c94952279503bbe8d5a710c1fd344da0670/greeking/fillmurray.py#L8-L16 |
mengzhuo/ioloop | ioloop/__init__.py | IOLoop.instance | def instance():
"""Returns a global `IOLoop` instance.
Most applications have a single, global `IOLoop` running on the
main thread. Use this method to get this instance from
another thread. To get the current thread's `IOLoop`, use `current()`.
"""
if not hasattr(IOLoo... | python | def instance():
"""Returns a global `IOLoop` instance.
Most applications have a single, global `IOLoop` running on the
main thread. Use this method to get this instance from
another thread. To get the current thread's `IOLoop`, use `current()`.
"""
if not hasattr(IOLoo... | [
"def",
"instance",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"IOLoop",
",",
"\"_instance\"",
")",
":",
"with",
"IOLoop",
".",
"_instance_lock",
":",
"if",
"not",
"hasattr",
"(",
"IOLoop",
",",
"\"_instance\"",
")",
":",
"# New instance after double check",
... | Returns a global `IOLoop` instance.
Most applications have a single, global `IOLoop` running on the
main thread. Use this method to get this instance from
another thread. To get the current thread's `IOLoop`, use `current()`. | [
"Returns",
"a",
"global",
"IOLoop",
"instance",
"."
] | train | https://github.com/mengzhuo/ioloop/blob/9a3602ab5f1435753253f63906fd4364135b07b5/ioloop/__init__.py#L26-L38 |
dolph/pasteraw-client | pasteraw.py | Client.create_paste | def create_paste(self, content):
"""Create a raw paste of the given content.
Returns a URL to the paste, or raises a ``pasteraw.Error`` if something
tragic happens instead.
"""
r = requests.post(
self.endpoint + '/pastes',
data={'content': content},
... | python | def create_paste(self, content):
"""Create a raw paste of the given content.
Returns a URL to the paste, or raises a ``pasteraw.Error`` if something
tragic happens instead.
"""
r = requests.post(
self.endpoint + '/pastes',
data={'content': content},
... | [
"def",
"create_paste",
"(",
"self",
",",
"content",
")",
":",
"r",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"endpoint",
"+",
"'/pastes'",
",",
"data",
"=",
"{",
"'content'",
":",
"content",
"}",
",",
"allow_redirects",
"=",
"False",
")",
"if",
... | Create a raw paste of the given content.
Returns a URL to the paste, or raises a ``pasteraw.Error`` if something
tragic happens instead. | [
"Create",
"a",
"raw",
"paste",
"of",
"the",
"given",
"content",
"."
] | train | https://github.com/dolph/pasteraw-client/blob/f1d5ec0bc0fb02584ad12f50266ac8f1fd2a3297/pasteraw.py#L63-L86 |
blha303/DO-runin | runin/runin.py | match_keys | def match_keys(inp, p=False):
"""Takes a comma-separated string of key ids or fingerprints and returns a list of key ids"""
_keys = []
ssh_keys = DO.get_ssh_keys()
for k in inp.split(","):
done = False
if k.isdigit():
for _ in [s for s in ssh_keys if s["id"] == int(k)]:
... | python | def match_keys(inp, p=False):
"""Takes a comma-separated string of key ids or fingerprints and returns a list of key ids"""
_keys = []
ssh_keys = DO.get_ssh_keys()
for k in inp.split(","):
done = False
if k.isdigit():
for _ in [s for s in ssh_keys if s["id"] == int(k)]:
... | [
"def",
"match_keys",
"(",
"inp",
",",
"p",
"=",
"False",
")",
":",
"_keys",
"=",
"[",
"]",
"ssh_keys",
"=",
"DO",
".",
"get_ssh_keys",
"(",
")",
"for",
"k",
"in",
"inp",
".",
"split",
"(",
"\",\"",
")",
":",
"done",
"=",
"False",
"if",
"k",
"."... | Takes a comma-separated string of key ids or fingerprints and returns a list of key ids | [
"Takes",
"a",
"comma",
"-",
"separated",
"string",
"of",
"key",
"ids",
"or",
"fingerprints",
"and",
"returns",
"a",
"list",
"of",
"key",
"ids"
] | train | https://github.com/blha303/DO-runin/blob/4e725165e79f8bc0a2e1cb07a83f414686570e90/runin/runin.py#L13-L29 |
SkyLothar/shcmd | shcmd/cmd.py | cd | def cd(cd_path, create=False):
"""cd to target dir when running in this block
:param cd_path: dir to cd into
:param create: create new dir if destination not there
Usage::
>>> with cd("/tmp"):
... print("we are in /tmp now")
"""
oricwd = os.getcwd()
if create:
... | python | def cd(cd_path, create=False):
"""cd to target dir when running in this block
:param cd_path: dir to cd into
:param create: create new dir if destination not there
Usage::
>>> with cd("/tmp"):
... print("we are in /tmp now")
"""
oricwd = os.getcwd()
if create:
... | [
"def",
"cd",
"(",
"cd_path",
",",
"create",
"=",
"False",
")",
":",
"oricwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"if",
"create",
":",
"mkdir",
"(",
"cd_path",
")",
"try",
":",
"os",
".",
"chdir",
"(",
"cd_path",
")",
"yield",
"finally",
":",
"os... | cd to target dir when running in this block
:param cd_path: dir to cd into
:param create: create new dir if destination not there
Usage::
>>> with cd("/tmp"):
... print("we are in /tmp now") | [
"cd",
"to",
"target",
"dir",
"when",
"running",
"in",
"this",
"block"
] | train | https://github.com/SkyLothar/shcmd/blob/d8cad6311a4da7ef09f3419c86b58e30388b7ee3/shcmd/cmd.py#L10-L28 |
SkyLothar/shcmd | shcmd/cmd.py | cd_to | def cd_to(path, mkdir=False):
"""make a generator like cd, but use it for function
Usage::
>>> @cd_to("/")
... def say_where():
... print(os.getcwd())
...
>>> say_where()
/
"""
def cd_to_decorator(func):
@functools.wraps(func)
def _c... | python | def cd_to(path, mkdir=False):
"""make a generator like cd, but use it for function
Usage::
>>> @cd_to("/")
... def say_where():
... print(os.getcwd())
...
>>> say_where()
/
"""
def cd_to_decorator(func):
@functools.wraps(func)
def _c... | [
"def",
"cd_to",
"(",
"path",
",",
"mkdir",
"=",
"False",
")",
":",
"def",
"cd_to_decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"_cd_and_exec",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with"... | make a generator like cd, but use it for function
Usage::
>>> @cd_to("/")
... def say_where():
... print(os.getcwd())
...
>>> say_where()
/ | [
"make",
"a",
"generator",
"like",
"cd",
"but",
"use",
"it",
"for",
"function"
] | train | https://github.com/SkyLothar/shcmd/blob/d8cad6311a4da7ef09f3419c86b58e30388b7ee3/shcmd/cmd.py#L31-L50 |
SkyLothar/shcmd | shcmd/cmd.py | rm | def rm(path, isdir=False):
"""delete file or dir
returns True if deleted, if file/dir not exists, return False
:param path: path to delete
:param isdir: set True if you want to delete dir
"""
if isdir:
deleted = os.path.isdir(path)
shutil.rmtree(path, ignore_errors=True)
eli... | python | def rm(path, isdir=False):
"""delete file or dir
returns True if deleted, if file/dir not exists, return False
:param path: path to delete
:param isdir: set True if you want to delete dir
"""
if isdir:
deleted = os.path.isdir(path)
shutil.rmtree(path, ignore_errors=True)
eli... | [
"def",
"rm",
"(",
"path",
",",
"isdir",
"=",
"False",
")",
":",
"if",
"isdir",
":",
"deleted",
"=",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
"shutil",
".",
"rmtree",
"(",
"path",
",",
"ignore_errors",
"=",
"True",
")",
"elif",
"os",
"."... | delete file or dir
returns True if deleted, if file/dir not exists, return False
:param path: path to delete
:param isdir: set True if you want to delete dir | [
"delete",
"file",
"or",
"dir",
"returns",
"True",
"if",
"deleted",
"if",
"file",
"/",
"dir",
"not",
"exists",
"return",
"False"
] | train | https://github.com/SkyLothar/shcmd/blob/d8cad6311a4da7ef09f3419c86b58e30388b7ee3/shcmd/cmd.py#L61-L76 |
matthewdeanmartin/jiggle_version | sample_projects/ver_in_weird_file/setup_helpers.py | require_python | def require_python(minimum):
"""Require at least a minimum Python version.
The version number is expressed in terms of `sys.hexversion`. E.g. to
require a minimum of Python 2.6, use::
>>> require_python(0x206000f0)
:param minimum: Minimum Python version supported.
:type minimum: integer
... | python | def require_python(minimum):
"""Require at least a minimum Python version.
The version number is expressed in terms of `sys.hexversion`. E.g. to
require a minimum of Python 2.6, use::
>>> require_python(0x206000f0)
:param minimum: Minimum Python version supported.
:type minimum: integer
... | [
"def",
"require_python",
"(",
"minimum",
")",
":",
"if",
"sys",
".",
"hexversion",
"<",
"minimum",
":",
"hversion",
"=",
"hex",
"(",
"minimum",
")",
"[",
"2",
":",
"]",
"if",
"len",
"(",
"hversion",
")",
"%",
"2",
"!=",
"0",
":",
"hversion",
"=",
... | Require at least a minimum Python version.
The version number is expressed in terms of `sys.hexversion`. E.g. to
require a minimum of Python 2.6, use::
>>> require_python(0x206000f0)
:param minimum: Minimum Python version supported.
:type minimum: integer | [
"Require",
"at",
"least",
"a",
"minimum",
"Python",
"version",
"."
] | train | https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/sample_projects/ver_in_weird_file/setup_helpers.py#L41-L67 |
matthewdeanmartin/jiggle_version | sample_projects/ver_in_weird_file/setup_helpers.py | get_version | def get_version(filename, pattern=None):
"""Extract the __version__ from a file without importing it.
While you could get the __version__ by importing the module, the very act
of importing can cause unintended consequences. For example, Distribute's
automatic 2to3 support will break. Instead, this se... | python | def get_version(filename, pattern=None):
"""Extract the __version__ from a file without importing it.
While you could get the __version__ by importing the module, the very act
of importing can cause unintended consequences. For example, Distribute's
automatic 2to3 support will break. Instead, this se... | [
"def",
"get_version",
"(",
"filename",
",",
"pattern",
"=",
"None",
")",
":",
"if",
"pattern",
"is",
"None",
":",
"cre",
"=",
"DEFAULT_VERSION_RE",
"else",
":",
"cre",
"=",
"re",
".",
"compile",
"(",
"pattern",
")",
"with",
"open",
"(",
"filename",
")"... | Extract the __version__ from a file without importing it.
While you could get the __version__ by importing the module, the very act
of importing can cause unintended consequences. For example, Distribute's
automatic 2to3 support will break. Instead, this searches the file for a
line that starts with ... | [
"Extract",
"the",
"__version__",
"from",
"a",
"file",
"without",
"importing",
"it",
"."
] | train | https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/sample_projects/ver_in_weird_file/setup_helpers.py#L70-L100 |
matthewdeanmartin/jiggle_version | sample_projects/ver_in_weird_file/setup_helpers.py | long_description | def long_description(*filenames):
"""Provide a long description."""
res = ['']
for filename in filenames:
with open(filename) as fp:
for line in fp:
res.append(' ' + line)
res.append('')
res.append('\n')
return EMPTYSTRING.join(res) | python | def long_description(*filenames):
"""Provide a long description."""
res = ['']
for filename in filenames:
with open(filename) as fp:
for line in fp:
res.append(' ' + line)
res.append('')
res.append('\n')
return EMPTYSTRING.join(res) | [
"def",
"long_description",
"(",
"*",
"filenames",
")",
":",
"res",
"=",
"[",
"''",
"]",
"for",
"filename",
"in",
"filenames",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"fp",
":",
"for",
"line",
"in",
"fp",
":",
"res",
".",
"append",
"(",
"' ... | Provide a long description. | [
"Provide",
"a",
"long",
"description",
"."
] | train | https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/sample_projects/ver_in_weird_file/setup_helpers.py#L125-L134 |
matthewdeanmartin/jiggle_version | sample_projects/ver_in_weird_file/setup_helpers.py | description | def description(filename):
"""Provide a short description."""
# This ends up in the Summary header for PKG-INFO and it should be a
# one-liner. It will get rendered on the package page just below the
# package version header but above the long_description, which ironically
# gets stuff into the Des... | python | def description(filename):
"""Provide a short description."""
# This ends up in the Summary header for PKG-INFO and it should be a
# one-liner. It will get rendered on the package page just below the
# package version header but above the long_description, which ironically
# gets stuff into the Des... | [
"def",
"description",
"(",
"filename",
")",
":",
"# This ends up in the Summary header for PKG-INFO and it should be a",
"# one-liner. It will get rendered on the package page just below the",
"# package version header but above the long_description, which ironically",
"# gets stuff into the Desc... | Provide a short description. | [
"Provide",
"a",
"short",
"description",
"."
] | train | https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/sample_projects/ver_in_weird_file/setup_helpers.py#L137-L150 |
noirbizarre/minibench | tasks.py | clean | def clean(docs=False, bytecode=False, extra=''):
'''Cleanup all build artifacts'''
patterns = ['build', 'dist', 'cover', 'docs/_build', '**/*.pyc', '*.egg-info', '.tox', '**/__pycache__']
for pattern in patterns:
print('Removing {0}'.format(pattern))
lrun('rm -rf {0}'.format(pattern)) | python | def clean(docs=False, bytecode=False, extra=''):
'''Cleanup all build artifacts'''
patterns = ['build', 'dist', 'cover', 'docs/_build', '**/*.pyc', '*.egg-info', '.tox', '**/__pycache__']
for pattern in patterns:
print('Removing {0}'.format(pattern))
lrun('rm -rf {0}'.format(pattern)) | [
"def",
"clean",
"(",
"docs",
"=",
"False",
",",
"bytecode",
"=",
"False",
",",
"extra",
"=",
"''",
")",
":",
"patterns",
"=",
"[",
"'build'",
",",
"'dist'",
",",
"'cover'",
",",
"'docs/_build'",
",",
"'**/*.pyc'",
",",
"'*.egg-info'",
",",
"'.tox'",
",... | Cleanup all build artifacts | [
"Cleanup",
"all",
"build",
"artifacts"
] | train | https://github.com/noirbizarre/minibench/blob/a1ac66dc075181c62bb3c0d3a26beb5c46d5f4ab/tasks.py#L17-L22 |
heathbar/plum-lightpad-python | plumlightpad/plumcloud.py | PlumCloud.fetch_houses | async def fetch_houses(self):
"""Lookup details for devices on the plum servers"""
try:
async with self._websession.get("https://production.plum.technology/v2/getHouses", headers=self.headers) as response:
return await response.json()
except IOError:
prin... | python | async def fetch_houses(self):
"""Lookup details for devices on the plum servers"""
try:
async with self._websession.get("https://production.plum.technology/v2/getHouses", headers=self.headers) as response:
return await response.json()
except IOError:
prin... | [
"async",
"def",
"fetch_houses",
"(",
"self",
")",
":",
"try",
":",
"async",
"with",
"self",
".",
"_websession",
".",
"get",
"(",
"\"https://production.plum.technology/v2/getHouses\"",
",",
"headers",
"=",
"self",
".",
"headers",
")",
"as",
"response",
":",
"re... | Lookup details for devices on the plum servers | [
"Lookup",
"details",
"for",
"devices",
"on",
"the",
"plum",
"servers"
] | train | https://github.com/heathbar/plum-lightpad-python/blob/181b3dc26cfe77830565f6f844af5ed0728dccd5/plumlightpad/plumcloud.py#L38-L46 |
heathbar/plum-lightpad-python | plumlightpad/plumcloud.py | PlumCloud.fetch_house | async def fetch_house(self, house_id):
"""Lookup details for a given house id"""
url = "https://production.plum.technology/v2/getHouse"
data = {"hid": house_id}
return await self.__post(url, data) | python | async def fetch_house(self, house_id):
"""Lookup details for a given house id"""
url = "https://production.plum.technology/v2/getHouse"
data = {"hid": house_id}
return await self.__post(url, data) | [
"async",
"def",
"fetch_house",
"(",
"self",
",",
"house_id",
")",
":",
"url",
"=",
"\"https://production.plum.technology/v2/getHouse\"",
"data",
"=",
"{",
"\"hid\"",
":",
"house_id",
"}",
"return",
"await",
"self",
".",
"__post",
"(",
"url",
",",
"data",
")"
] | Lookup details for a given house id | [
"Lookup",
"details",
"for",
"a",
"given",
"house",
"id"
] | train | https://github.com/heathbar/plum-lightpad-python/blob/181b3dc26cfe77830565f6f844af5ed0728dccd5/plumlightpad/plumcloud.py#L48-L52 |
heathbar/plum-lightpad-python | plumlightpad/plumcloud.py | PlumCloud.fetch_room | async def fetch_room(self, room_id):
"""Lookup details for a given room id"""
url = "https://production.plum.technology/v2/getRoom"
data = {"rid": room_id}
return await self.__post(url, data) | python | async def fetch_room(self, room_id):
"""Lookup details for a given room id"""
url = "https://production.plum.technology/v2/getRoom"
data = {"rid": room_id}
return await self.__post(url, data) | [
"async",
"def",
"fetch_room",
"(",
"self",
",",
"room_id",
")",
":",
"url",
"=",
"\"https://production.plum.technology/v2/getRoom\"",
"data",
"=",
"{",
"\"rid\"",
":",
"room_id",
"}",
"return",
"await",
"self",
".",
"__post",
"(",
"url",
",",
"data",
")"
] | Lookup details for a given room id | [
"Lookup",
"details",
"for",
"a",
"given",
"room",
"id"
] | train | https://github.com/heathbar/plum-lightpad-python/blob/181b3dc26cfe77830565f6f844af5ed0728dccd5/plumlightpad/plumcloud.py#L54-L58 |
heathbar/plum-lightpad-python | plumlightpad/plumcloud.py | PlumCloud.fetch_logical_load | async def fetch_logical_load(self, llid):
"""Lookup details for a given logical load"""
url = "https://production.plum.technology/v2/getLogicalLoad"
data = {"llid": llid}
return await self.__post(url, data) | python | async def fetch_logical_load(self, llid):
"""Lookup details for a given logical load"""
url = "https://production.plum.technology/v2/getLogicalLoad"
data = {"llid": llid}
return await self.__post(url, data) | [
"async",
"def",
"fetch_logical_load",
"(",
"self",
",",
"llid",
")",
":",
"url",
"=",
"\"https://production.plum.technology/v2/getLogicalLoad\"",
"data",
"=",
"{",
"\"llid\"",
":",
"llid",
"}",
"return",
"await",
"self",
".",
"__post",
"(",
"url",
",",
"data",
... | Lookup details for a given logical load | [
"Lookup",
"details",
"for",
"a",
"given",
"logical",
"load"
] | train | https://github.com/heathbar/plum-lightpad-python/blob/181b3dc26cfe77830565f6f844af5ed0728dccd5/plumlightpad/plumcloud.py#L60-L64 |
heathbar/plum-lightpad-python | plumlightpad/plumcloud.py | PlumCloud.fetch_lightpad | async def fetch_lightpad(self, lpid):
"""Lookup details for a given lightpad"""
url = "https://production.plum.technology/v2/getLightpad"
data = {"lpid": lpid}
return await self.__post(url, data) | python | async def fetch_lightpad(self, lpid):
"""Lookup details for a given lightpad"""
url = "https://production.plum.technology/v2/getLightpad"
data = {"lpid": lpid}
return await self.__post(url, data) | [
"async",
"def",
"fetch_lightpad",
"(",
"self",
",",
"lpid",
")",
":",
"url",
"=",
"\"https://production.plum.technology/v2/getLightpad\"",
"data",
"=",
"{",
"\"lpid\"",
":",
"lpid",
"}",
"return",
"await",
"self",
".",
"__post",
"(",
"url",
",",
"data",
")"
] | Lookup details for a given lightpad | [
"Lookup",
"details",
"for",
"a",
"given",
"lightpad"
] | train | https://github.com/heathbar/plum-lightpad-python/blob/181b3dc26cfe77830565f6f844af5ed0728dccd5/plumlightpad/plumcloud.py#L66-L70 |
heathbar/plum-lightpad-python | plumlightpad/plumcloud.py | PlumCloud.update_houses | async def update_houses(self):
"""Lookup details for devices on the plum servers"""
houses = await self.fetch_houses()
for house_id in houses:
asyncio.Task(self.update_house(house_id)) | python | async def update_houses(self):
"""Lookup details for devices on the plum servers"""
houses = await self.fetch_houses()
for house_id in houses:
asyncio.Task(self.update_house(house_id)) | [
"async",
"def",
"update_houses",
"(",
"self",
")",
":",
"houses",
"=",
"await",
"self",
".",
"fetch_houses",
"(",
")",
"for",
"house_id",
"in",
"houses",
":",
"asyncio",
".",
"Task",
"(",
"self",
".",
"update_house",
"(",
"house_id",
")",
")"
] | Lookup details for devices on the plum servers | [
"Lookup",
"details",
"for",
"devices",
"on",
"the",
"plum",
"servers"
] | train | https://github.com/heathbar/plum-lightpad-python/blob/181b3dc26cfe77830565f6f844af5ed0728dccd5/plumlightpad/plumcloud.py#L76-L80 |
xaptum/xtt-python | xtt/_utils.py | to_bytes | def to_bytes(s, encoding="utf-8"):
"""
Converts the string to a bytes type, if not already.
:s: the string to convert to bytes
:returns: `str` on Python2 and `bytes` on Python3.
"""
if isinstance(s, six.binary_type):
return s
else:
return six.text_type(s).encode(encoding) | python | def to_bytes(s, encoding="utf-8"):
"""
Converts the string to a bytes type, if not already.
:s: the string to convert to bytes
:returns: `str` on Python2 and `bytes` on Python3.
"""
if isinstance(s, six.binary_type):
return s
else:
return six.text_type(s).encode(encoding) | [
"def",
"to_bytes",
"(",
"s",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"binary_type",
")",
":",
"return",
"s",
"else",
":",
"return",
"six",
".",
"text_type",
"(",
"s",
")",
".",
"encode",
"(",
"enc... | Converts the string to a bytes type, if not already.
:s: the string to convert to bytes
:returns: `str` on Python2 and `bytes` on Python3. | [
"Converts",
"the",
"string",
"to",
"a",
"bytes",
"type",
"if",
"not",
"already",
"."
] | train | https://github.com/xaptum/xtt-python/blob/23ee469488d710d730314bec1136c4dd7ac2cd5c/xtt/_utils.py#L21-L31 |
xaptum/xtt-python | xtt/_utils.py | to_text | def to_text(s, encoding="utf-8"):
"""
Converts the bytes to a text type, if not already.
:s: the bytes to convert to text
:returns: `unicode` on Python2 and `str` on Python3.
"""
if isinstance(s, six.text_type):
return s
else:
return six.binary_type(s).decode(encoding) | python | def to_text(s, encoding="utf-8"):
"""
Converts the bytes to a text type, if not already.
:s: the bytes to convert to text
:returns: `unicode` on Python2 and `str` on Python3.
"""
if isinstance(s, six.text_type):
return s
else:
return six.binary_type(s).decode(encoding) | [
"def",
"to_text",
"(",
"s",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"text_type",
")",
":",
"return",
"s",
"else",
":",
"return",
"six",
".",
"binary_type",
"(",
"s",
")",
".",
"decode",
"(",
"enco... | Converts the bytes to a text type, if not already.
:s: the bytes to convert to text
:returns: `unicode` on Python2 and `str` on Python3. | [
"Converts",
"the",
"bytes",
"to",
"a",
"text",
"type",
"if",
"not",
"already",
"."
] | train | https://github.com/xaptum/xtt-python/blob/23ee469488d710d730314bec1136c4dd7ac2cd5c/xtt/_utils.py#L33-L43 |
xaptum/xtt-python | xtt/_utils.py | _check_len | def _check_len(a, b):
"""
Raises an exception if the two values do not have the same
length. This is useful for validating preconditions.
:a: the first value
:b: the second value
:raises ValueError: if the sizes do not match
"""
if len(a) != len(b):
msg = "Length must be {}. Got... | python | def _check_len(a, b):
"""
Raises an exception if the two values do not have the same
length. This is useful for validating preconditions.
:a: the first value
:b: the second value
:raises ValueError: if the sizes do not match
"""
if len(a) != len(b):
msg = "Length must be {}. Got... | [
"def",
"_check_len",
"(",
"a",
",",
"b",
")",
":",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
":",
"msg",
"=",
"\"Length must be {}. Got {}\"",
".",
"format",
"(",
"len",
"(",
"a",
")",
",",
"len",
"(",
"b",
")",
")",
"raise",
"Val... | Raises an exception if the two values do not have the same
length. This is useful for validating preconditions.
:a: the first value
:b: the second value
:raises ValueError: if the sizes do not match | [
"Raises",
"an",
"exception",
"if",
"the",
"two",
"values",
"do",
"not",
"have",
"the",
"same",
"length",
".",
"This",
"is",
"useful",
"for",
"validating",
"preconditions",
"."
] | train | https://github.com/xaptum/xtt-python/blob/23ee469488d710d730314bec1136c4dd7ac2cd5c/xtt/_utils.py#L45-L56 |
radjkarl/fancyTools | fancytools/math/similarity1DdiffShapedArrays.py | similarity1DdiffShapedArrays | def similarity1DdiffShapedArrays(arr1, arr2, normalize=False):
"""
compare two strictly monotonous increasing 1d arrays
of same or different size
return a similarity index-> 0=identical
"""
# assign longer and shorter here, because jit cannot do it
if len(arr1) < len(arr2):
arr1, arr... | python | def similarity1DdiffShapedArrays(arr1, arr2, normalize=False):
"""
compare two strictly monotonous increasing 1d arrays
of same or different size
return a similarity index-> 0=identical
"""
# assign longer and shorter here, because jit cannot do it
if len(arr1) < len(arr2):
arr1, arr... | [
"def",
"similarity1DdiffShapedArrays",
"(",
"arr1",
",",
"arr2",
",",
"normalize",
"=",
"False",
")",
":",
"# assign longer and shorter here, because jit cannot do it",
"if",
"len",
"(",
"arr1",
")",
"<",
"len",
"(",
"arr2",
")",
":",
"arr1",
",",
"arr2",
"=",
... | compare two strictly monotonous increasing 1d arrays
of same or different size
return a similarity index-> 0=identical | [
"compare",
"two",
"strictly",
"monotonous",
"increasing",
"1d",
"arrays",
"of",
"same",
"or",
"different",
"size",
"return",
"a",
"similarity",
"index",
"-",
">",
"0",
"=",
"identical"
] | train | https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/math/similarity1DdiffShapedArrays.py#L7-L30 |
nefarioustim/parker | parker/consumestore.py | get_instance | def get_instance(
model, method="file",
img_dir=None, data_dir=None,
bucket=None
):
"""Return an instance of ConsumeStore."""
global _instances
if not isinstance(model, ConsumeModel):
raise TypeError(
"get_instance() expects a parker.ConsumeModel derivative."
)
i... | python | def get_instance(
model, method="file",
img_dir=None, data_dir=None,
bucket=None
):
"""Return an instance of ConsumeStore."""
global _instances
if not isinstance(model, ConsumeModel):
raise TypeError(
"get_instance() expects a parker.ConsumeModel derivative."
)
i... | [
"def",
"get_instance",
"(",
"model",
",",
"method",
"=",
"\"file\"",
",",
"img_dir",
"=",
"None",
",",
"data_dir",
"=",
"None",
",",
"bucket",
"=",
"None",
")",
":",
"global",
"_instances",
"if",
"not",
"isinstance",
"(",
"model",
",",
"ConsumeModel",
")... | Return an instance of ConsumeStore. | [
"Return",
"an",
"instance",
"of",
"ConsumeStore",
"."
] | train | https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/consumestore.py#L13-L45 |
nefarioustim/parker | parker/consumestore.py | ConsumeStore.save_media | def save_media(self):
"""Store any media within model.media_list."""
chunk_path = fileops.get_chunk_path_from_string(
self.model.unique_field
)
for i, mediafile in enumerate(self.model.media_list):
filename = os.path.join(
self._get_prefix(),
... | python | def save_media(self):
"""Store any media within model.media_list."""
chunk_path = fileops.get_chunk_path_from_string(
self.model.unique_field
)
for i, mediafile in enumerate(self.model.media_list):
filename = os.path.join(
self._get_prefix(),
... | [
"def",
"save_media",
"(",
"self",
")",
":",
"chunk_path",
"=",
"fileops",
".",
"get_chunk_path_from_string",
"(",
"self",
".",
"model",
".",
"unique_field",
")",
"for",
"i",
",",
"mediafile",
"in",
"enumerate",
"(",
"self",
".",
"model",
".",
"media_list",
... | Store any media within model.media_list. | [
"Store",
"any",
"media",
"within",
"model",
".",
"media_list",
"."
] | train | https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/consumestore.py#L57-L69 |
nefarioustim/parker | parker/consumestore.py | ConsumeStore.save_data | def save_data(self):
"""Store data as a JSON dump."""
filename = os.path.join(
self._get_prefix(),
self.model.site
)
self.store.store_json(
filename,
self.model.get_dict()
) | python | def save_data(self):
"""Store data as a JSON dump."""
filename = os.path.join(
self._get_prefix(),
self.model.site
)
self.store.store_json(
filename,
self.model.get_dict()
) | [
"def",
"save_data",
"(",
"self",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_get_prefix",
"(",
")",
",",
"self",
".",
"model",
".",
"site",
")",
"self",
".",
"store",
".",
"store_json",
"(",
"filename",
",",
"self... | Store data as a JSON dump. | [
"Store",
"data",
"as",
"a",
"JSON",
"dump",
"."
] | train | https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/consumestore.py#L71-L80 |
rosenbrockc/acorn | acorn/ipython.py | findloop | def findloop(m):
"""Determines if the specified member of `_ast` contains any for or while loops
in its body definition.
"""
from _ast import For, While, FunctionDef, ClassDef, ListComp
from _ast import DictComp
if isinstance(m, (FunctionDef, ClassDef)):
return False
elif isinsta... | python | def findloop(m):
"""Determines if the specified member of `_ast` contains any for or while loops
in its body definition.
"""
from _ast import For, While, FunctionDef, ClassDef, ListComp
from _ast import DictComp
if isinstance(m, (FunctionDef, ClassDef)):
return False
elif isinsta... | [
"def",
"findloop",
"(",
"m",
")",
":",
"from",
"_ast",
"import",
"For",
",",
"While",
",",
"FunctionDef",
",",
"ClassDef",
",",
"ListComp",
"from",
"_ast",
"import",
"DictComp",
"if",
"isinstance",
"(",
"m",
",",
"(",
"FunctionDef",
",",
"ClassDef",
")",... | Determines if the specified member of `_ast` contains any for or while loops
in its body definition. | [
"Determines",
"if",
"the",
"specified",
"member",
"of",
"_ast",
"contains",
"any",
"for",
"or",
"while",
"loops",
"in",
"its",
"body",
"definition",
"."
] | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/ipython.py#L453-L478 |
rosenbrockc/acorn | acorn/ipython.py | record_markdown | def record_markdown(text, cellid):
"""Records the specified markdown text to the acorn database.
Args:
text (str): the *raw* markdown text entered into the cell in the ipython
notebook.
"""
from acorn.logging.database import record
from time import time
ekey = "nb-{}".format(c... | python | def record_markdown(text, cellid):
"""Records the specified markdown text to the acorn database.
Args:
text (str): the *raw* markdown text entered into the cell in the ipython
notebook.
"""
from acorn.logging.database import record
from time import time
ekey = "nb-{}".format(c... | [
"def",
"record_markdown",
"(",
"text",
",",
"cellid",
")",
":",
"from",
"acorn",
".",
"logging",
".",
"database",
"import",
"record",
"from",
"time",
"import",
"time",
"ekey",
"=",
"\"nb-{}\"",
".",
"format",
"(",
"cellid",
")",
"global",
"_cellid_map",
"i... | Records the specified markdown text to the acorn database.
Args:
text (str): the *raw* markdown text entered into the cell in the ipython
notebook. | [
"Records",
"the",
"specified",
"markdown",
"text",
"to",
"the",
"acorn",
"database",
"."
] | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/ipython.py#L488-L534 |
rosenbrockc/acorn | acorn/ipython.py | load_ipython_extension | def load_ipython_extension(ip):
"""Loads the interacting decorator that ships with `acorn` into the ipython
interactive shell.
Args:
ip (IPython.core.interactiveshell.InteractiveShell): ipython shell instance
for interacting with the shell variables.
"""
decor = InteractiveDecorat... | python | def load_ipython_extension(ip):
"""Loads the interacting decorator that ships with `acorn` into the ipython
interactive shell.
Args:
ip (IPython.core.interactiveshell.InteractiveShell): ipython shell instance
for interacting with the shell variables.
"""
decor = InteractiveDecorat... | [
"def",
"load_ipython_extension",
"(",
"ip",
")",
":",
"decor",
"=",
"InteractiveDecorator",
"(",
"ip",
")",
"ip",
".",
"events",
".",
"register",
"(",
"'post_run_cell'",
",",
"decor",
".",
"post_run_cell",
")",
"#Unfortunately, the built-in \"pre-execute\" and \"pre-r... | Loads the interacting decorator that ships with `acorn` into the ipython
interactive shell.
Args:
ip (IPython.core.interactiveshell.InteractiveShell): ipython shell instance
for interacting with the shell variables. | [
"Loads",
"the",
"interacting",
"decorator",
"that",
"ships",
"with",
"acorn",
"into",
"the",
"ipython",
"interactive",
"shell",
"."
] | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/ipython.py#L536-L553 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.