repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
gwww/elkm1 | elkm1_lib/message.py | https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/message.py#L212-L215 | def _zp_decode(self, msg):
"""ZP: Zone partitions."""
zone_partitions = [ord(x)-0x31 for x in msg[4:4+Max.ZONES.value]]
return {'zone_partitions': zone_partitions} | [
"def",
"_zp_decode",
"(",
"self",
",",
"msg",
")",
":",
"zone_partitions",
"=",
"[",
"ord",
"(",
"x",
")",
"-",
"0x31",
"for",
"x",
"in",
"msg",
"[",
"4",
":",
"4",
"+",
"Max",
".",
"ZONES",
".",
"value",
"]",
"]",
"return",
"{",
"'zone_partition... | ZP: Zone partitions. | [
"ZP",
":",
"Zone",
"partitions",
"."
] | python | train | 46 |
pypa/pipenv | pipenv/vendor/yaspin/core.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yaspin/core.py#L251-L264 | def hide(self):
"""Hide the spinner to allow for custom writing to the terminal."""
thr_is_alive = self._spin_thread and self._spin_thread.is_alive()
if thr_is_alive and not self._hide_spin.is_set():
# set the hidden spinner flag
self._hide_spin.set()
# clea... | [
"def",
"hide",
"(",
"self",
")",
":",
"thr_is_alive",
"=",
"self",
".",
"_spin_thread",
"and",
"self",
".",
"_spin_thread",
".",
"is_alive",
"(",
")",
"if",
"thr_is_alive",
"and",
"not",
"self",
".",
"_hide_spin",
".",
"is_set",
"(",
")",
":",
"# set the... | Hide the spinner to allow for custom writing to the terminal. | [
"Hide",
"the",
"spinner",
"to",
"allow",
"for",
"custom",
"writing",
"to",
"the",
"terminal",
"."
] | python | train | 35.785714 |
confluentinc/confluent-kafka-python | examples/adminapi.py | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/examples/adminapi.py#L120-L140 | def example_alter_configs(a, args):
""" Alter configs atomically, replacing non-specified
configuration properties with their default values.
"""
resources = []
for restype, resname, configs in zip(args[0::3], args[1::3], args[2::3]):
resource = ConfigResource(restype, resname)
reso... | [
"def",
"example_alter_configs",
"(",
"a",
",",
"args",
")",
":",
"resources",
"=",
"[",
"]",
"for",
"restype",
",",
"resname",
",",
"configs",
"in",
"zip",
"(",
"args",
"[",
"0",
":",
":",
"3",
"]",
",",
"args",
"[",
"1",
":",
":",
"3",
"]",
",... | Alter configs atomically, replacing non-specified
configuration properties with their default values. | [
"Alter",
"configs",
"atomically",
"replacing",
"non",
"-",
"specified",
"configuration",
"properties",
"with",
"their",
"default",
"values",
"."
] | python | train | 34.619048 |
push-things/django-th | django_th/views_userservices.py | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/views_userservices.py#L22-L35 | def renew_service(request, pk):
"""
renew an existing service
:param request object
:param pk: the primary key of the service to renew
:type pk: int
"""
default_provider.load_services()
service = get_object_or_404(ServicesActivated, pk=pk)
service_name = str(service.n... | [
"def",
"renew_service",
"(",
"request",
",",
"pk",
")",
":",
"default_provider",
".",
"load_services",
"(",
")",
"service",
"=",
"get_object_or_404",
"(",
"ServicesActivated",
",",
"pk",
"=",
"pk",
")",
"service_name",
"=",
"str",
"(",
"service",
".",
"name"... | renew an existing service
:param request object
:param pk: the primary key of the service to renew
:type pk: int | [
"renew",
"an",
"existing",
"service",
":",
"param",
"request",
"object",
":",
"param",
"pk",
":",
"the",
"primary",
"key",
"of",
"the",
"service",
"to",
"renew",
":",
"type",
"pk",
":",
"int"
] | python | train | 36.714286 |
KrzyHonk/bpmn-python | bpmn_python/bpmn_diagram_export.py | https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L400-L414 | def export_flow_di_data(params, plane):
"""
Creates a new BPMNEdge XML element for given edge parameters and adds it to 'plane' element.
:param params: dictionary with edge parameters,
:param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for edge DI dat... | [
"def",
"export_flow_di_data",
"(",
"params",
",",
"plane",
")",
":",
"output_flow",
"=",
"eTree",
".",
"SubElement",
"(",
"plane",
",",
"BpmnDiagramGraphExport",
".",
"bpmndi_namespace",
"+",
"consts",
".",
"Consts",
".",
"bpmn_edge",
")",
"output_flow",
".",
... | Creates a new BPMNEdge XML element for given edge parameters and adds it to 'plane' element.
:param params: dictionary with edge parameters,
:param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for edge DI data). | [
"Creates",
"a",
"new",
"BPMNEdge",
"XML",
"element",
"for",
"given",
"edge",
"parameters",
"and",
"adds",
"it",
"to",
"plane",
"element",
"."
] | python | train | 58.733333 |
agoragames/leaderboard-python | leaderboard/leaderboard.py | https://github.com/agoragames/leaderboard-python/blob/ec309859b197a751ac0322374b36d134d8c5522f/leaderboard/leaderboard.py#L462-L481 | def rank_for_in(self, leaderboard_name, member):
'''
Retrieve the rank for a member in the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param member [String] Member name.
@return the rank for a member in the leaderboard.
'''
if se... | [
"def",
"rank_for_in",
"(",
"self",
",",
"leaderboard_name",
",",
"member",
")",
":",
"if",
"self",
".",
"order",
"==",
"self",
".",
"ASC",
":",
"try",
":",
"return",
"self",
".",
"redis_connection",
".",
"zrank",
"(",
"leaderboard_name",
",",
"member",
"... | Retrieve the rank for a member in the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param member [String] Member name.
@return the rank for a member in the leaderboard. | [
"Retrieve",
"the",
"rank",
"for",
"a",
"member",
"in",
"the",
"named",
"leaderboard",
"."
] | python | train | 33.65 |
bskinn/opan | opan/utils/symm.py | https://github.com/bskinn/opan/blob/0b1b21662df6abc971407a9386db21a8796fbfe5/opan/utils/symm.py#L223-L300 | def geom_symm_match(g, atwts, ax, theta, do_refl):
""" [Revised match factor calculation]
.. todo:: Complete geom_symm_match docstring
"""
# Imports
import numpy as np
from scipy import linalg as spla
# Convert g and atwts to n-D vectors
g = make_nd_vec(g, nd=None, t=np.float64, norm... | [
"def",
"geom_symm_match",
"(",
"g",
",",
"atwts",
",",
"ax",
",",
"theta",
",",
"do_refl",
")",
":",
"# Imports",
"import",
"numpy",
"as",
"np",
"from",
"scipy",
"import",
"linalg",
"as",
"spla",
"# Convert g and atwts to n-D vectors",
"g",
"=",
"make_nd_vec",... | [Revised match factor calculation]
.. todo:: Complete geom_symm_match docstring | [
"[",
"Revised",
"match",
"factor",
"calculation",
"]"
] | python | train | 35.192308 |
PythonCharmers/python-future | src/future/types/newdict.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/types/newdict.py#L41-L53 | def items(self):
"""
On Python 2.7+:
D.items() -> a set-like object providing a view on D's items
On Python 2.6:
D.items() -> an iterator over D's items
"""
if ver == (2, 7):
return self.viewitems()
elif ver == (2, 6):
retur... | [
"def",
"items",
"(",
"self",
")",
":",
"if",
"ver",
"==",
"(",
"2",
",",
"7",
")",
":",
"return",
"self",
".",
"viewitems",
"(",
")",
"elif",
"ver",
"==",
"(",
"2",
",",
"6",
")",
":",
"return",
"self",
".",
"iteritems",
"(",
")",
"elif",
"ve... | On Python 2.7+:
D.items() -> a set-like object providing a view on D's items
On Python 2.6:
D.items() -> an iterator over D's items | [
"On",
"Python",
"2",
".",
"7",
"+",
":",
"D",
".",
"items",
"()",
"-",
">",
"a",
"set",
"-",
"like",
"object",
"providing",
"a",
"view",
"on",
"D",
"s",
"items",
"On",
"Python",
"2",
".",
"6",
":",
"D",
".",
"items",
"()",
"-",
">",
"an",
"... | python | train | 29.692308 |
mozilla/Marketplace.Python | marketplace/client.py | https://github.com/mozilla/Marketplace.Python/blob/88176b12201f766b6b96bccc1e4c3e82f0676283/marketplace/client.py#L183-L204 | def create_screenshot(self, app_id, filename, position=1):
"""Add a screenshot to the web app identified by by ``app_id``.
Screenshots are ordered by ``position``.
:returns: HttpResponse:
* status_code (int) 201 is successful
* content (dict) containing screenshot data
... | [
"def",
"create_screenshot",
"(",
"self",
",",
"app_id",
",",
"filename",
",",
"position",
"=",
"1",
")",
":",
"# prepare file for upload",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"s_file",
":",
"s_content",
"=",
"s_file",
".",
"read",
"(",... | Add a screenshot to the web app identified by by ``app_id``.
Screenshots are ordered by ``position``.
:returns: HttpResponse:
* status_code (int) 201 is successful
* content (dict) containing screenshot data | [
"Add",
"a",
"screenshot",
"to",
"the",
"web",
"app",
"identified",
"by",
"by",
"app_id",
".",
"Screenshots",
"are",
"ordered",
"by",
"position",
"."
] | python | train | 36.863636 |
mfitzp/padua | padua/normalization.py | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/normalization.py#L4-L22 | def subtract_column_median(df, prefix='Intensity '):
"""
Apply column-wise normalisation to expression columns.
Default is median transform to expression columns beginning with Intensity
:param df:
:param prefix: The column prefix for expression columns
:return:
"""
df = df.copy()
... | [
"def",
"subtract_column_median",
"(",
"df",
",",
"prefix",
"=",
"'Intensity '",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"df",
".",
"replace",
"(",
"[",
"np",
".",
"inf",
",",
"-",
"np",
".",
"inf",
"]",
",",
"np",
".",
"nan",
",",
"in... | Apply column-wise normalisation to expression columns.
Default is median transform to expression columns beginning with Intensity
:param df:
:param prefix: The column prefix for expression columns
:return: | [
"Apply",
"column",
"-",
"wise",
"normalisation",
"to",
"expression",
"columns",
"."
] | python | train | 26.631579 |
restran/mountains | mountains/http/__init__.py | https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/http/__init__.py#L75-L119 | def read_request_from_str(data, **params):
"""
从字符串中读取请求头,并根据格式化字符串模板,进行字符串格式化
:param data:
:param params:
:return:
"""
method, uri = None, None
headers = {}
host = ''
try:
split_list = data.split('\n\n')
headers_text = split_list[0]
body = '\n\n'.join(sp... | [
"def",
"read_request_from_str",
"(",
"data",
",",
"*",
"*",
"params",
")",
":",
"method",
",",
"uri",
"=",
"None",
",",
"None",
"headers",
"=",
"{",
"}",
"host",
"=",
"''",
"try",
":",
"split_list",
"=",
"data",
".",
"split",
"(",
"'\\n\\n'",
")",
... | 从字符串中读取请求头,并根据格式化字符串模板,进行字符串格式化
:param data:
:param params:
:return: | [
"从字符串中读取请求头,并根据格式化字符串模板,进行字符串格式化",
":",
"param",
"data",
":",
":",
"param",
"params",
":",
":",
"return",
":"
] | python | train | 25.777778 |
ethan92429/onshapepy | onshapepy/core/client.py | https://github.com/ethan92429/onshapepy/blob/61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df/onshapepy/core/client.py#L298-L325 | def create_assembly_instance(self, assembly_uri, part_uri, configuration):
'''
Insert a configurable part into an assembly.
Args:
- assembly (dict): eid, wid, and did of the assembly into which will be inserted
- part (dict): eid and did of the configurable part
... | [
"def",
"create_assembly_instance",
"(",
"self",
",",
"assembly_uri",
",",
"part_uri",
",",
"configuration",
")",
":",
"payload",
"=",
"{",
"\"documentId\"",
":",
"part_uri",
"[",
"\"did\"",
"]",
",",
"\"elementId\"",
":",
"part_uri",
"[",
"\"eid\"",
"]",
",",
... | Insert a configurable part into an assembly.
Args:
- assembly (dict): eid, wid, and did of the assembly into which will be inserted
- part (dict): eid and did of the configurable part
- configuration (dict): the configuration
Returns:
- requests.Response... | [
"Insert",
"a",
"configurable",
"part",
"into",
"an",
"assembly",
"."
] | python | train | 41.714286 |
mardix/Juice | juice/utils.py | https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/utils.py#L67-L75 | def md5_string(s):
"""
Shortcut to create md5 hash
:param s:
:return:
"""
m = hashlib.md5()
m.update(s)
return str(m.hexdigest()) | [
"def",
"md5_string",
"(",
"s",
")",
":",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"m",
".",
"update",
"(",
"s",
")",
"return",
"str",
"(",
"m",
".",
"hexdigest",
"(",
")",
")"
] | Shortcut to create md5 hash
:param s:
:return: | [
"Shortcut",
"to",
"create",
"md5",
"hash",
":",
"param",
"s",
":",
":",
"return",
":"
] | python | train | 17 |
Esri/ArcREST | src/arcrest/opendata/_web.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/opendata/_web.py#L238-L279 | def _process_response(self, resp, out_folder=None):
""" processes the response object"""
CHUNK = 4056
maintype = self._mainType(resp)
contentDisposition = resp.headers.get('content-disposition')
contentEncoding = resp.headers.get('content-encoding')
contentType = resp.hea... | [
"def",
"_process_response",
"(",
"self",
",",
"resp",
",",
"out_folder",
"=",
"None",
")",
":",
"CHUNK",
"=",
"4056",
"maintype",
"=",
"self",
".",
"_mainType",
"(",
"resp",
")",
"contentDisposition",
"=",
"resp",
".",
"headers",
".",
"get",
"(",
"'conte... | processes the response object | [
"processes",
"the",
"response",
"object"
] | python | train | 40.904762 |
StellarCN/py-stellar-base | stellar_base/builder.py | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/builder.py#L746-L758 | def sign(self, secret=None):
"""Sign the generated :class:`TransactionEnvelope
<stellar_base.transaction_envelope.TransactionEnvelope>` from the list
of this builder's operations.
:param str secret: The secret seed to use if a key pair or secret was
not provided when this cl... | [
"def",
"sign",
"(",
"self",
",",
"secret",
"=",
"None",
")",
":",
"keypair",
"=",
"self",
".",
"keypair",
"if",
"not",
"secret",
"else",
"Keypair",
".",
"from_seed",
"(",
"secret",
")",
"self",
".",
"gen_te",
"(",
")",
"self",
".",
"te",
".",
"sign... | Sign the generated :class:`TransactionEnvelope
<stellar_base.transaction_envelope.TransactionEnvelope>` from the list
of this builder's operations.
:param str secret: The secret seed to use if a key pair or secret was
not provided when this class was originaly instantiated, or if
... | [
"Sign",
"the",
"generated",
":",
"class",
":",
"TransactionEnvelope",
"<stellar_base",
".",
"transaction_envelope",
".",
"TransactionEnvelope",
">",
"from",
"the",
"list",
"of",
"this",
"builder",
"s",
"operations",
"."
] | python | train | 43.230769 |
JensAstrup/pyOutlook | pyOutlook/core/contact.py | https://github.com/JensAstrup/pyOutlook/blob/f4ca9d4a8629c0a41f78102ce84fab702a841167/pyOutlook/core/contact.py#L82-L84 | def api_representation(self):
""" Returns the JSON formatting required by Outlook's API for contacts """
return dict(EmailAddress=dict(Name=self.name, Address=self.email)) | [
"def",
"api_representation",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"EmailAddress",
"=",
"dict",
"(",
"Name",
"=",
"self",
".",
"name",
",",
"Address",
"=",
"self",
".",
"email",
")",
")"
] | Returns the JSON formatting required by Outlook's API for contacts | [
"Returns",
"the",
"JSON",
"formatting",
"required",
"by",
"Outlook",
"s",
"API",
"for",
"contacts"
] | python | train | 61.666667 |
deepmind/pysc2 | pysc2/lib/renderer_human.py | https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1287-L1334 | def draw_mini_map(self, surf):
"""Draw the minimap."""
if (self._render_rgb and self._obs.observation.HasField("render_data") and
self._obs.observation.render_data.HasField("minimap")):
# Draw the rendered version.
surf.blit_np_array(features.Feature.unpack_rgb_image(
self._obs.obs... | [
"def",
"draw_mini_map",
"(",
"self",
",",
"surf",
")",
":",
"if",
"(",
"self",
".",
"_render_rgb",
"and",
"self",
".",
"_obs",
".",
"observation",
".",
"HasField",
"(",
"\"render_data\"",
")",
"and",
"self",
".",
"_obs",
".",
"observation",
".",
"render_... | Draw the minimap. | [
"Draw",
"the",
"minimap",
"."
] | python | train | 45.5625 |
bkg/django-spillway | spillway/query.py | https://github.com/bkg/django-spillway/blob/c488a62642430b005f1e0d4a19e160d8d5964b67/spillway/query.py#L248-L263 | def warp(self, srid=None, format=None, geom=None):
"""Returns a new RasterQuerySet with possibly warped/converted rasters.
Keyword args:
format -- raster file extension format as str
geom -- geometry for masking or spatial subsetting
srid -- spatial reference identifier as int f... | [
"def",
"warp",
"(",
"self",
",",
"srid",
"=",
"None",
",",
"format",
"=",
"None",
",",
"geom",
"=",
"None",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"for",
"obj",
"in",
"clone",
":",
"obj",
".",
"convert",
"(",
"format",
",",
"g... | Returns a new RasterQuerySet with possibly warped/converted rasters.
Keyword args:
format -- raster file extension format as str
geom -- geometry for masking or spatial subsetting
srid -- spatial reference identifier as int for warping to | [
"Returns",
"a",
"new",
"RasterQuerySet",
"with",
"possibly",
"warped",
"/",
"converted",
"rasters",
"."
] | python | train | 40.75 |
saltstack/salt | salt/modules/boto_iam.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L331-L352 | def get_user(user_name=None, region=None, key=None, keyid=None, profile=None):
'''
Get user information.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_user myuser
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
... | [
"def",
"get_user",
"(",
"user_name",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",... | Get user information.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_user myuser | [
"Get",
"user",
"information",
"."
] | python | train | 25.772727 |
Tivix/django-common | django_common/management/commands/generate_secret_key.py | https://github.com/Tivix/django-common/blob/407d208121011a8425139e541629554114d96c18/django_common/management/commands/generate_secret_key.py#L19-L27 | def add_arguments(self, parser):
"""
Define optional arguments with default values
"""
parser.add_argument('--length', default=self.length,
type=int, help=_('SECRET_KEY length default=%d' % self.length))
parser.add_argument('--alphabet', default=self.... | [
"def",
"add_arguments",
"(",
"self",
",",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'--length'",
",",
"default",
"=",
"self",
".",
"length",
",",
"type",
"=",
"int",
",",
"help",
"=",
"_",
"(",
"'SECRET_KEY length default=%d'",
"%",
"self",
... | Define optional arguments with default values | [
"Define",
"optional",
"arguments",
"with",
"default",
"values"
] | python | train | 47 |
yymao/generic-catalog-reader | GCR/base.py | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L151-L160 | def first_available(self, *quantities):
"""
Return the first available quantity in the input arguments.
Return `None` if none of them is available.
"""
for i, q in enumerate(quantities):
if self.has_quantity(q):
if i:
warnings.warn(... | [
"def",
"first_available",
"(",
"self",
",",
"*",
"quantities",
")",
":",
"for",
"i",
",",
"q",
"in",
"enumerate",
"(",
"quantities",
")",
":",
"if",
"self",
".",
"has_quantity",
"(",
"q",
")",
":",
"if",
"i",
":",
"warnings",
".",
"warn",
"(",
"'{}... | Return the first available quantity in the input arguments.
Return `None` if none of them is available. | [
"Return",
"the",
"first",
"available",
"quantity",
"in",
"the",
"input",
"arguments",
".",
"Return",
"None",
"if",
"none",
"of",
"them",
"is",
"available",
"."
] | python | train | 39.8 |
jmbeach/KEP.py | src/keppy/device.py | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/device.py#L15-L22 | def set_driver_simulated(self):
"""Sets the device driver type to simulated"""
self._device_dict["servermain.MULTIPLE_TYPES_DEVICE_DRIVER"] = "Simulator"
if self._is_sixteen_bit:
self._device_dict["servermain.DEVICE_MODEL"] = 0
else:
self._device_dict["servermain.... | [
"def",
"set_driver_simulated",
"(",
"self",
")",
":",
"self",
".",
"_device_dict",
"[",
"\"servermain.MULTIPLE_TYPES_DEVICE_DRIVER\"",
"]",
"=",
"\"Simulator\"",
"if",
"self",
".",
"_is_sixteen_bit",
":",
"self",
".",
"_device_dict",
"[",
"\"servermain.DEVICE_MODEL\"",
... | Sets the device driver type to simulated | [
"Sets",
"the",
"device",
"driver",
"type",
"to",
"simulated"
] | python | train | 48.875 |
theislab/scvelo | scvelo/tools/rank_velocity_genes.py | https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/tools/rank_velocity_genes.py#L39-L52 | def select_groups(adata, groups='all', key='louvain'):
"""Get subset of groups in adata.obs[key].
"""
strings_to_categoricals(adata)
if isinstance(groups, list) and isinstance(groups[0], int): groups = [str(n) for n in groups]
categories = adata.obs[key].cat.categories
groups_masks = np.array([c... | [
"def",
"select_groups",
"(",
"adata",
",",
"groups",
"=",
"'all'",
",",
"key",
"=",
"'louvain'",
")",
":",
"strings_to_categoricals",
"(",
"adata",
")",
"if",
"isinstance",
"(",
"groups",
",",
"list",
")",
"and",
"isinstance",
"(",
"groups",
"[",
"0",
"]... | Get subset of groups in adata.obs[key]. | [
"Get",
"subset",
"of",
"groups",
"in",
"adata",
".",
"obs",
"[",
"key",
"]",
"."
] | python | train | 47.357143 |
inveniosoftware/invenio-logging | invenio_logging/sentry6.py | https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/sentry6.py#L21-L35 | def get_user_info(self, request):
"""Implement custom getter."""
if not current_user.is_authenticated:
return {}
user_info = {
'id': current_user.get_id(),
}
if 'SENTRY_USER_ATTRS' in current_app.config:
for attr in current_app.config['SENTRY... | [
"def",
"get_user_info",
"(",
"self",
",",
"request",
")",
":",
"if",
"not",
"current_user",
".",
"is_authenticated",
":",
"return",
"{",
"}",
"user_info",
"=",
"{",
"'id'",
":",
"current_user",
".",
"get_id",
"(",
")",
",",
"}",
"if",
"'SENTRY_USER_ATTRS'"... | Implement custom getter. | [
"Implement",
"custom",
"getter",
"."
] | python | train | 30.666667 |
psd-tools/psd-tools | src/psd_tools/utils.py | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L69-L81 | def read_length_block(fp, fmt='I', padding=1):
"""
Read a block of data with a length marker at the beginning.
:param fp: file-like
:param fmt: format of the length marker
:return: bytes object
"""
length = read_fmt(fmt, fp)[0]
data = fp.read(length)
assert len(data) == length, (len... | [
"def",
"read_length_block",
"(",
"fp",
",",
"fmt",
"=",
"'I'",
",",
"padding",
"=",
"1",
")",
":",
"length",
"=",
"read_fmt",
"(",
"fmt",
",",
"fp",
")",
"[",
"0",
"]",
"data",
"=",
"fp",
".",
"read",
"(",
"length",
")",
"assert",
"len",
"(",
"... | Read a block of data with a length marker at the beginning.
:param fp: file-like
:param fmt: format of the length marker
:return: bytes object | [
"Read",
"a",
"block",
"of",
"data",
"with",
"a",
"length",
"marker",
"at",
"the",
"beginning",
"."
] | python | train | 29 |
archman/beamline | beamline/lattice.py | https://github.com/archman/beamline/blob/417bc5dc13e754bc89d246427984590fced64d07/beamline/lattice.py#L382-L388 | def scanStoVars(self, strline):
""" scan input string line, replace sto parameters with calculated results.
"""
for wd in strline.split():
if wd in self.stodict:
strline = strline.replace(wd, str(self.stodict[wd]))
return strline | [
"def",
"scanStoVars",
"(",
"self",
",",
"strline",
")",
":",
"for",
"wd",
"in",
"strline",
".",
"split",
"(",
")",
":",
"if",
"wd",
"in",
"self",
".",
"stodict",
":",
"strline",
"=",
"strline",
".",
"replace",
"(",
"wd",
",",
"str",
"(",
"self",
... | scan input string line, replace sto parameters with calculated results. | [
"scan",
"input",
"string",
"line",
"replace",
"sto",
"parameters",
"with",
"calculated",
"results",
"."
] | python | train | 40.428571 |
google/grr | grr/client/grr_response_client/client_utils_osx_linux.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/client_utils_osx_linux.py#L233-L249 | def Write(self, grr_message):
"""Write the message into the transaction log."""
grr_message = grr_message.SerializeToString()
try:
with io.open(self.logfile, "wb") as fd:
fd.write(grr_message)
except (IOError, OSError):
# Check if we're missing directories and try to create them.
... | [
"def",
"Write",
"(",
"self",
",",
"grr_message",
")",
":",
"grr_message",
"=",
"grr_message",
".",
"SerializeToString",
"(",
")",
"try",
":",
"with",
"io",
".",
"open",
"(",
"self",
".",
"logfile",
",",
"\"wb\"",
")",
"as",
"fd",
":",
"fd",
".",
"wri... | Write the message into the transaction log. | [
"Write",
"the",
"message",
"into",
"the",
"transaction",
"log",
"."
] | python | train | 38.882353 |
cloudnull/turbolift | turbolift/authentication/utils.py | https://github.com/cloudnull/turbolift/blob/da33034e88959226529ce762e2895e6f6356c448/turbolift/authentication/utils.py#L155-L224 | def parse_reqtype(self):
"""Return the authentication body."""
if self.job_args['os_auth_version'] == 'v1.0':
return dict()
else:
setup = {
'username': self.job_args.get('os_user')
}
# Check if any prefix items are set. A prefix s... | [
"def",
"parse_reqtype",
"(",
"self",
")",
":",
"if",
"self",
".",
"job_args",
"[",
"'os_auth_version'",
"]",
"==",
"'v1.0'",
":",
"return",
"dict",
"(",
")",
"else",
":",
"setup",
"=",
"{",
"'username'",
":",
"self",
".",
"job_args",
".",
"get",
"(",
... | Return the authentication body. | [
"Return",
"the",
"authentication",
"body",
"."
] | python | train | 38.114286 |
pandas-dev/pandas | pandas/core/frame.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L2723-L2747 | def set_value(self, index, col, value, takeable=False):
"""
Put single value at passed column and index.
.. deprecated:: 0.21.0
Use .at[] or .iat[] accessors instead.
Parameters
----------
index : row label
col : column label
value : scalar
... | [
"def",
"set_value",
"(",
"self",
",",
"index",
",",
"col",
",",
"value",
",",
"takeable",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"\"set_value is deprecated and will be removed \"",
"\"in a future release. Please use \"",
"\".at[] or .iat[] accessors instead... | Put single value at passed column and index.
.. deprecated:: 0.21.0
Use .at[] or .iat[] accessors instead.
Parameters
----------
index : row label
col : column label
value : scalar
takeable : interpret the index/col as indexers, default False
... | [
"Put",
"single",
"value",
"at",
"passed",
"column",
"and",
"index",
"."
] | python | train | 33.92 |
SwissDataScienceCenter/renku-python | renku/cli/env.py | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/env.py#L29-L41 | def env(config, endpoint):
"""Print RENKU environment variables.
Run this command to configure your Renku client:
$ eval "$(renku env)"
"""
access_token = config['endpoints'][endpoint]['token']['access_token']
click.echo('export {0}={1}'.format('RENKU_ENDPOINT', endpoint))
click.echo(... | [
"def",
"env",
"(",
"config",
",",
"endpoint",
")",
":",
"access_token",
"=",
"config",
"[",
"'endpoints'",
"]",
"[",
"endpoint",
"]",
"[",
"'token'",
"]",
"[",
"'access_token'",
"]",
"click",
".",
"echo",
"(",
"'export {0}={1}'",
".",
"format",
"(",
"'RE... | Print RENKU environment variables.
Run this command to configure your Renku client:
$ eval "$(renku env)" | [
"Print",
"RENKU",
"environment",
"variables",
"."
] | python | train | 36.692308 |
tanghaibao/goatools | goatools/grouper/hdrgos.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/hdrgos.py#L69-L88 | def _init_hdrgos(self, hdrgos_dflt, hdrgos_usr=None, add_dflt=True):
"""Initialize GO high"""
# Use default GO group header values
if (hdrgos_usr is None or hdrgos_usr is False) and not self.sections:
return set(hdrgos_dflt)
# Get GO group headers provided by user
hdr... | [
"def",
"_init_hdrgos",
"(",
"self",
",",
"hdrgos_dflt",
",",
"hdrgos_usr",
"=",
"None",
",",
"add_dflt",
"=",
"True",
")",
":",
"# Use default GO group header values",
"if",
"(",
"hdrgos_usr",
"is",
"None",
"or",
"hdrgos_usr",
"is",
"False",
")",
"and",
"not",... | Initialize GO high | [
"Initialize",
"GO",
"high"
] | python | train | 46.8 |
pgmpy/pgmpy | pgmpy/readwrite/XMLBIF.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/XMLBIF.py#L430-L444 | def write_xmlbif(self, filename):
"""
Write the xml data into the file.
Parameters
----------
filename: Name of the file.
Examples
-------
>>> writer = XMLBIFWriter(model)
>>> writer.write_xmlbif(test_file)
"""
with open(filename,... | [
"def",
"write_xmlbif",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fout",
":",
"fout",
".",
"write",
"(",
"self",
".",
"__str__",
"(",
")",
")"
] | Write the xml data into the file.
Parameters
----------
filename: Name of the file.
Examples
-------
>>> writer = XMLBIFWriter(model)
>>> writer.write_xmlbif(test_file) | [
"Write",
"the",
"xml",
"data",
"into",
"the",
"file",
"."
] | python | train | 23.933333 |
python-constraint/python-constraint | constraint/__init__.py | https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L373-L386 | def getSolution(self, domains, constraints, vconstraints):
"""
Return one solution for the given problem
@param domains: Dictionary mapping variables to their domains
@type domains: dict
@param constraints: List of pairs of (constraint, variables)
@type constraints: li... | [
"def",
"getSolution",
"(",
"self",
",",
"domains",
",",
"constraints",
",",
"vconstraints",
")",
":",
"msg",
"=",
"\"%s is an abstract class\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
"raise",
"NotImplementedError",
"(",
"msg",
")"
] | Return one solution for the given problem
@param domains: Dictionary mapping variables to their domains
@type domains: dict
@param constraints: List of pairs of (constraint, variables)
@type constraints: list
@param vconstraints: Dictionary mapping variables to a list of
... | [
"Return",
"one",
"solution",
"for",
"the",
"given",
"problem"
] | python | train | 43.071429 |
limpyd/redis-limpyd | limpyd/indexes.py | https://github.com/limpyd/redis-limpyd/blob/3c745dde1390a0bd09690b77a089dcc08c6c7e43/limpyd/indexes.py#L1112-L1128 | def _extract_value_from_storage(self, string):
"""Taking a string that was a member of the zset, extract the value and pk
Parameters
----------
string: str
The member extracted from the sorted set
Returns
-------
tuple
Tuple with the valu... | [
"def",
"_extract_value_from_storage",
"(",
"self",
",",
"string",
")",
":",
"parts",
"=",
"string",
".",
"split",
"(",
"self",
".",
"separator",
")",
"pk",
"=",
"parts",
".",
"pop",
"(",
")",
"return",
"self",
".",
"separator",
".",
"join",
"(",
"parts... | Taking a string that was a member of the zset, extract the value and pk
Parameters
----------
string: str
The member extracted from the sorted set
Returns
-------
tuple
Tuple with the value and the pk, extracted from the string | [
"Taking",
"a",
"string",
"that",
"was",
"a",
"member",
"of",
"the",
"zset",
"extract",
"the",
"value",
"and",
"pk"
] | python | train | 27.764706 |
catherinedevlin/ddl-generator | ddlgenerator/reshape.py | https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/reshape.py#L18-L34 | def clean_key_name(key):
"""
Makes ``key`` a valid and appropriate SQL column name:
1. Replaces illegal characters in column names with ``_``
2. Prevents name from beginning with a digit (prepends ``_``)
3. Lowercases name. If you want case-sensitive table
or column names, you are a bad pers... | [
"def",
"clean_key_name",
"(",
"key",
")",
":",
"result",
"=",
"_illegal_in_column_name",
".",
"sub",
"(",
"\"_\"",
",",
"key",
".",
"strip",
"(",
")",
")",
"if",
"result",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
":",
"result",
"=",
"'_%s'",
"%",
"... | Makes ``key`` a valid and appropriate SQL column name:
1. Replaces illegal characters in column names with ``_``
2. Prevents name from beginning with a digit (prepends ``_``)
3. Lowercases name. If you want case-sensitive table
or column names, you are a bad person and you should feel bad. | [
"Makes",
"key",
"a",
"valid",
"and",
"appropriate",
"SQL",
"column",
"name",
":"
] | python | train | 32.823529 |
NoviceLive/intellicoder | intellicoder/synthesizers.py | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/synthesizers.py#L162-L171 | def c_struct(self):
"""Get the struct of the module."""
member = '\n'.join(self.c_member_funcs(True))
if self.opts.windll:
return 'struct {{\n{}{} }} {};\n'.format(
self._c_dll_base(), member, self.name
)
return 'typedef\nstruct {2} {{\n{0}\n{1}}}\... | [
"def",
"c_struct",
"(",
"self",
")",
":",
"member",
"=",
"'\\n'",
".",
"join",
"(",
"self",
".",
"c_member_funcs",
"(",
"True",
")",
")",
"if",
"self",
".",
"opts",
".",
"windll",
":",
"return",
"'struct {{\\n{}{} }} {};\\n'",
".",
"format",
"(",
"self",... | Get the struct of the module. | [
"Get",
"the",
"struct",
"of",
"the",
"module",
"."
] | python | train | 40.1 |
eaton-lab/toytree | toytree/MultiDrawing.py | https://github.com/eaton-lab/toytree/blob/0347ed2098acc5f707fadf52a0ecd411a6d1859c/toytree/MultiDrawing.py#L170-L206 | def add_tip_labels_to_axes(self):
"""
Add text offset from tips of tree with correction for orientation,
and fixed_order which is usually used in multitree plotting.
"""
# get tip-coords and replace if using fixed_order
if self.style.orient in ("up", "down"):
... | [
"def",
"add_tip_labels_to_axes",
"(",
"self",
")",
":",
"# get tip-coords and replace if using fixed_order",
"if",
"self",
".",
"style",
".",
"orient",
"in",
"(",
"\"up\"",
",",
"\"down\"",
")",
":",
"ypos",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"ntips",
... | Add text offset from tips of tree with correction for orientation,
and fixed_order which is usually used in multitree plotting. | [
"Add",
"text",
"offset",
"from",
"tips",
"of",
"tree",
"with",
"correction",
"for",
"orientation",
"and",
"fixed_order",
"which",
"is",
"usually",
"used",
"in",
"multitree",
"plotting",
"."
] | python | train | 41.27027 |
tijme/not-your-average-web-crawler | nyawc/Queue.py | https://github.com/tijme/not-your-average-web-crawler/blob/d77c14e1616c541bb3980f649a7e6f8ed02761fb/nyawc/Queue.py#L181-L192 | def get_progress(self):
"""Get the progress of the queue in percentage (float).
Returns:
float: The 'finished' progress in percentage.
"""
count_remaining = len(self.items_queued) + len(self.items_in_progress)
percentage_remaining = 100 / self.count_total * count_r... | [
"def",
"get_progress",
"(",
"self",
")",
":",
"count_remaining",
"=",
"len",
"(",
"self",
".",
"items_queued",
")",
"+",
"len",
"(",
"self",
".",
"items_in_progress",
")",
"percentage_remaining",
"=",
"100",
"/",
"self",
".",
"count_total",
"*",
"count_remai... | Get the progress of the queue in percentage (float).
Returns:
float: The 'finished' progress in percentage. | [
"Get",
"the",
"progress",
"of",
"the",
"queue",
"in",
"percentage",
"(",
"float",
")",
"."
] | python | train | 30 |
google/grr | grr/core/grr_response_core/lib/utils.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/utils.py#L572-L626 | def NormalizePath(path, sep="/"):
"""A sane implementation of os.path.normpath.
The standard implementation treats leading / and // as different leading to
incorrect normal forms.
NOTE: Its ok to use a relative path here (without leading /) but any /../ will
still be removed anchoring the path at the top le... | [
"def",
"NormalizePath",
"(",
"path",
",",
"sep",
"=",
"\"/\"",
")",
":",
"if",
"not",
"path",
":",
"return",
"sep",
"path",
"=",
"SmartUnicode",
"(",
"path",
")",
"path_list",
"=",
"path",
".",
"split",
"(",
"sep",
")",
"# This is a relative path and the f... | A sane implementation of os.path.normpath.
The standard implementation treats leading / and // as different leading to
incorrect normal forms.
NOTE: Its ok to use a relative path here (without leading /) but any /../ will
still be removed anchoring the path at the top level (e.g. foo/../../../../bar
=> bar)... | [
"A",
"sane",
"implementation",
"of",
"os",
".",
"path",
".",
"normpath",
"."
] | python | train | 27.890909 |
opencivicdata/pupa | pupa/utils/topsort.py | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/utils/topsort.py#L105-L145 | def cycles(self):
"""
Fairly expensive cycle detection algorithm. This method
will return the shortest unique cycles that were detected.
Debug usage may look something like:
print("The following cycles were found:")
for cycle in network.cycles():
print(" ... | [
"def",
"cycles",
"(",
"self",
")",
":",
"def",
"walk_node",
"(",
"node",
",",
"seen",
")",
":",
"\"\"\"\n Walk each top-level node we know about, and recurse\n along the graph.\n \"\"\"",
"if",
"node",
"in",
"seen",
":",
"yield",
"(",
"nod... | Fairly expensive cycle detection algorithm. This method
will return the shortest unique cycles that were detected.
Debug usage may look something like:
print("The following cycles were found:")
for cycle in network.cycles():
print(" ", " -> ".join(cycle)) | [
"Fairly",
"expensive",
"cycle",
"detection",
"algorithm",
".",
"This",
"method",
"will",
"return",
"the",
"shortest",
"unique",
"cycles",
"that",
"were",
"detected",
"."
] | python | train | 33.02439 |
singularityhub/sregistry-cli | sregistry/main/workers/tasks.py | https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/main/workers/tasks.py#L28-L59 | def download_task(url, headers, destination, download_type='layer'):
'''download an image layer (.tar.gz) to a specified download folder.
This task is done by using local versions of the same download functions
that are used for the client.
core stream/download functions of the parent client.
... | [
"def",
"download_task",
"(",
"url",
",",
"headers",
",",
"destination",
",",
"download_type",
"=",
"'layer'",
")",
":",
"# Update the user what we are doing",
"bot",
".",
"verbose",
"(",
"\"Downloading %s from %s\"",
"%",
"(",
"download_type",
",",
"url",
")",
")"... | download an image layer (.tar.gz) to a specified download folder.
This task is done by using local versions of the same download functions
that are used for the client.
core stream/download functions of the parent client.
Parameters
==========
image_id: the shasum id of the la... | [
"download",
"an",
"image",
"layer",
"(",
".",
"tar",
".",
"gz",
")",
"to",
"a",
"specified",
"download",
"folder",
".",
"This",
"task",
"is",
"done",
"by",
"using",
"local",
"versions",
"of",
"the",
"same",
"download",
"functions",
"that",
"are",
"used",... | python | test | 34.90625 |
michael-lazar/rtv | rtv/packages/praw/objects.py | https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/objects.py#L781-L790 | def mute_modmail_author(self, _unmute=False):
"""Mute the sender of this modmail message.
:param _unmute: Unmute the user instead. Please use
:meth:`unmute_modmail_author` instead of setting this directly.
"""
path = 'unmute_sender' if _unmute else 'mute_sender'
ret... | [
"def",
"mute_modmail_author",
"(",
"self",
",",
"_unmute",
"=",
"False",
")",
":",
"path",
"=",
"'unmute_sender'",
"if",
"_unmute",
"else",
"'mute_sender'",
"return",
"self",
".",
"reddit_session",
".",
"request_json",
"(",
"self",
".",
"reddit_session",
".",
... | Mute the sender of this modmail message.
:param _unmute: Unmute the user instead. Please use
:meth:`unmute_modmail_author` instead of setting this directly. | [
"Mute",
"the",
"sender",
"of",
"this",
"modmail",
"message",
"."
] | python | train | 42.2 |
mozilla/treeherder | treeherder/intermittents_commenter/commenter.py | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/intermittents_commenter/commenter.py#L252-L300 | def get_bug_stats(self, startday, endday):
"""Get all intermittent failures per specified date range and repository,
returning a dict of bug_id's with total, repository and platform totals
if totals are greater than or equal to the threshold.
eg:
{
"1206327": {
... | [
"def",
"get_bug_stats",
"(",
"self",
",",
"startday",
",",
"endday",
")",
":",
"# Min required failures per bug in order to post a comment",
"threshold",
"=",
"1",
"if",
"self",
".",
"weekly_mode",
"else",
"15",
"bug_ids",
"=",
"(",
"BugJobMap",
".",
"failures",
"... | Get all intermittent failures per specified date range and repository,
returning a dict of bug_id's with total, repository and platform totals
if totals are greater than or equal to the threshold.
eg:
{
"1206327": {
"total": 5,
"per_repos... | [
"Get",
"all",
"intermittent",
"failures",
"per",
"specified",
"date",
"range",
"and",
"repository",
"returning",
"a",
"dict",
"of",
"bug_id",
"s",
"with",
"total",
"repository",
"and",
"platform",
"totals",
"if",
"totals",
"are",
"greater",
"than",
"or",
"equa... | python | train | 40.857143 |
sawcordwell/pymdptoolbox | src/experimental/mdpsql.py | https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/experimental/mdpsql.py#L50-L88 | def exampleRand(S, A):
"""WARNING: This will delete a database with the same name as 'db'."""
db = "MDP-%sx%s.db" % (S, A)
if os.path.exists(db):
os.remove(db)
conn = sqlite3.connect(db)
with conn:
c = conn.cursor()
cmd = '''
CREATE TABLE info (name TEXT, value IN... | [
"def",
"exampleRand",
"(",
"S",
",",
"A",
")",
":",
"db",
"=",
"\"MDP-%sx%s.db\"",
"%",
"(",
"S",
",",
"A",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"db",
")",
":",
"os",
".",
"remove",
"(",
"db",
")",
"conn",
"=",
"sqlite3",
".",
"c... | WARNING: This will delete a database with the same name as 'db'. | [
"WARNING",
":",
"This",
"will",
"delete",
"a",
"database",
"with",
"the",
"same",
"name",
"as",
"db",
"."
] | python | train | 45.102564 |
poldracklab/niworkflows | niworkflows/interfaces/freesurfer.py | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/freesurfer.py#L402-L441 | def grow_mask(anat, aseg, ants_segs=None, ww=7, zval=2.0, bw=4):
"""
Grow mask including pixels that have a high likelihood.
GM tissue parameters are sampled in image patches of ``ww`` size.
This is inspired on mindboggle's solution to the problem:
https://github.com/nipy/mindboggle/blob/master/min... | [
"def",
"grow_mask",
"(",
"anat",
",",
"aseg",
",",
"ants_segs",
"=",
"None",
",",
"ww",
"=",
"7",
",",
"zval",
"=",
"2.0",
",",
"bw",
"=",
"4",
")",
":",
"selem",
"=",
"sim",
".",
"ball",
"(",
"bw",
")",
"if",
"ants_segs",
"is",
"None",
":",
... | Grow mask including pixels that have a high likelihood.
GM tissue parameters are sampled in image patches of ``ww`` size.
This is inspired on mindboggle's solution to the problem:
https://github.com/nipy/mindboggle/blob/master/mindboggle/guts/segment.py#L1660 | [
"Grow",
"mask",
"including",
"pixels",
"that",
"have",
"a",
"high",
"likelihood",
".",
"GM",
"tissue",
"parameters",
"are",
"sampled",
"in",
"image",
"patches",
"of",
"ww",
"size",
"."
] | python | train | 33.05 |
HumanCellAtlas/dcp-cli | hca/cli.py | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/cli.py#L61-L81 | def check_if_release_is_current(log):
"""Warns the user if their release is behind the latest PyPi __version__."""
if __version__ == '0.0.0':
return
client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
latest_pypi_version = client.package_releases('hca')
latest_version_nums = [int... | [
"def",
"check_if_release_is_current",
"(",
"log",
")",
":",
"if",
"__version__",
"==",
"'0.0.0'",
":",
"return",
"client",
"=",
"xmlrpclib",
".",
"ServerProxy",
"(",
"'https://pypi.python.org/pypi'",
")",
"latest_pypi_version",
"=",
"client",
".",
"package_releases",
... | Warns the user if their release is behind the latest PyPi __version__. | [
"Warns",
"the",
"user",
"if",
"their",
"release",
"is",
"behind",
"the",
"latest",
"PyPi",
"__version__",
"."
] | python | train | 53.857143 |
saltstack/salt | salt/modules/nix.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nix.py#L143-L183 | def install(*pkgs, **kwargs):
'''
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed ... | [
"def",
"install",
"(",
"*",
"pkgs",
",",
"*",
"*",
"kwargs",
")",
":",
"attributes",
"=",
"kwargs",
".",
"get",
"(",
"'attributes'",
",",
"False",
")",
"if",
"not",
"pkgs",
":",
"return",
"\"Plese specify a package or packages to upgrade\"",
"cmd",
"=",
"_qu... | Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
... | [
"Installs",
"a",
"single",
"or",
"multiple",
"packages",
"via",
"nix"
] | python | train | 25.390244 |
Qiskit/qiskit-terra | qiskit/tools/qi/qi.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L337-L344 | def random_unitary_matrix(dim, seed=None):
"""Deprecated in 0.8+
"""
warnings.warn('The random_unitary_matrix() function in qiskit.tools.qi has been '
'deprecated and will be removed in the future. Instead use '
'the function in qiskit.quantum_info.random',
... | [
"def",
"random_unitary_matrix",
"(",
"dim",
",",
"seed",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"'The random_unitary_matrix() function in qiskit.tools.qi has been '",
"'deprecated and will be removed in the future. Instead use '",
"'the function in qiskit.quantum_info.r... | Deprecated in 0.8+ | [
"Deprecated",
"in",
"0",
".",
"8",
"+"
] | python | test | 48.125 |
data61/clkhash | clkhash/randomnames.py | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/randomnames.py#L32-L43 | def load_csv_data(resource_name):
# type: (str) -> List[str]
""" Loads first column of specified CSV file from package data.
"""
data_bytes = pkgutil.get_data('clkhash', 'data/{}'.format(resource_name))
if data_bytes is None:
raise ValueError("No data resource found with name {}".format(reso... | [
"def",
"load_csv_data",
"(",
"resource_name",
")",
":",
"# type: (str) -> List[str]",
"data_bytes",
"=",
"pkgutil",
".",
"get_data",
"(",
"'clkhash'",
",",
"'data/{}'",
".",
"format",
"(",
"resource_name",
")",
")",
"if",
"data_bytes",
"is",
"None",
":",
"raise"... | Loads first column of specified CSV file from package data. | [
"Loads",
"first",
"column",
"of",
"specified",
"CSV",
"file",
"from",
"package",
"data",
"."
] | python | train | 42.25 |
Riffstation/flask-philo | flask_philo/db/postgresql/types.py | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/db/postgresql/types.py#L76-L90 | def _convert(self, value):
"""Returns a PasswordHash from the given string.
PasswordHash instances or None values will return unchanged.
Strings will be hashed and the resulting PasswordHash returned.
Any other input will result in a TypeError.
"""
if isinstance(value, P... | [
"def",
"_convert",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"PasswordHash",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"value",
".",
"encode",
"(",
"'utf-8'",
... | Returns a PasswordHash from the given string.
PasswordHash instances or None values will return unchanged.
Strings will be hashed and the resulting PasswordHash returned.
Any other input will result in a TypeError. | [
"Returns",
"a",
"PasswordHash",
"from",
"the",
"given",
"string",
"."
] | python | train | 41 |
titusz/epubcheck | src/epubcheck/utils.py | https://github.com/titusz/epubcheck/blob/7adde81543d3ae7385ab7062adb76e1414d49c2e/src/epubcheck/utils.py#L52-L61 | def generate_sample_json():
"""Generate sample json data for testing"""
check = EpubCheck(samples.EPUB3_VALID)
with open(samples.RESULT_VALID, 'wb') as jsonfile:
jsonfile.write(check._stdout)
check = EpubCheck(samples.EPUB3_INVALID)
with open(samples.RESULT_INVALID, 'wb') as jsonfile:
... | [
"def",
"generate_sample_json",
"(",
")",
":",
"check",
"=",
"EpubCheck",
"(",
"samples",
".",
"EPUB3_VALID",
")",
"with",
"open",
"(",
"samples",
".",
"RESULT_VALID",
",",
"'wb'",
")",
"as",
"jsonfile",
":",
"jsonfile",
".",
"write",
"(",
"check",
".",
"... | Generate sample json data for testing | [
"Generate",
"sample",
"json",
"data",
"for",
"testing"
] | python | train | 34.4 |
facebook/codemod | codemod/query.py | https://github.com/facebook/codemod/blob/78bb627792fc8a5253baa9cd9d8160533b16fd85/codemod/query.py#L126-L167 | def generate_patches(self):
"""
Generates a list of patches for each file underneath
self.root_directory
that satisfy the given conditions given
query conditions, where patches for
each file are suggested by self.suggestor.
"""
start_pos = self.start_posit... | [
"def",
"generate_patches",
"(",
"self",
")",
":",
"start_pos",
"=",
"self",
".",
"start_position",
"or",
"Position",
"(",
"None",
",",
"None",
")",
"end_pos",
"=",
"self",
".",
"end_position",
"or",
"Position",
"(",
"None",
",",
"None",
")",
"path_list",
... | Generates a list of patches for each file underneath
self.root_directory
that satisfy the given conditions given
query conditions, where patches for
each file are suggested by self.suggestor. | [
"Generates",
"a",
"list",
"of",
"patches",
"for",
"each",
"file",
"underneath",
"self",
".",
"root_directory",
"that",
"satisfy",
"the",
"given",
"conditions",
"given",
"query",
"conditions",
"where",
"patches",
"for",
"each",
"file",
"are",
"suggested",
"by",
... | python | train | 42.928571 |
gmr/tornado-elasticsearch | tornado_elasticsearch.py | https://github.com/gmr/tornado-elasticsearch/blob/fafe0de680277ce6faceb7449ded0b33822438d0/tornado_elasticsearch.py#L349-L372 | def exists(self, index, id, doc_type='_all', params=None):
"""
Returns a boolean indicating whether or not given document exists in
Elasticsearch. `<http://elasticsearch.org/guide/reference/api/get/>`_
:arg index: The name of the index
:arg id: The document ID
:arg doc_t... | [
"def",
"exists",
"(",
"self",
",",
"index",
",",
"id",
",",
"doc_type",
"=",
"'_all'",
",",
"params",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"transport",
".",
"perform_request",
"(",
"'HEAD'",
",",
"_make_path",
"(",
"index",
",",
"doc_type",
... | Returns a boolean indicating whether or not given document exists in
Elasticsearch. `<http://elasticsearch.org/guide/reference/api/get/>`_
:arg index: The name of the index
:arg id: The document ID
:arg doc_type: The type of the document (uses `_all` by default to
fetch the ... | [
"Returns",
"a",
"boolean",
"indicating",
"whether",
"or",
"not",
"given",
"document",
"exists",
"in",
"Elasticsearch",
".",
"<http",
":",
"//",
"elasticsearch",
".",
"org",
"/",
"guide",
"/",
"reference",
"/",
"api",
"/",
"get",
"/",
">",
"_"
] | python | test | 45.791667 |
pschmitt/pykeepass | pykeepass/kdbx_parsing/kdbx4.py | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/kdbx4.py#L64-L79 | def compute_header_hmac_hash(context):
"""Compute HMAC-SHA256 hash of header.
Used to prevent header tampering."""
return hmac.new(
hashlib.sha512(
b'\xff' * 8 +
hashlib.sha512(
context._.header.value.dynamic_header.master_seed.data +
context.... | [
"def",
"compute_header_hmac_hash",
"(",
"context",
")",
":",
"return",
"hmac",
".",
"new",
"(",
"hashlib",
".",
"sha512",
"(",
"b'\\xff'",
"*",
"8",
"+",
"hashlib",
".",
"sha512",
"(",
"context",
".",
"_",
".",
"header",
".",
"value",
".",
"dynamic_heade... | Compute HMAC-SHA256 hash of header.
Used to prevent header tampering. | [
"Compute",
"HMAC",
"-",
"SHA256",
"hash",
"of",
"header",
".",
"Used",
"to",
"prevent",
"header",
"tampering",
"."
] | python | train | 28.625 |
axel-events/axel | axel/axel.py | https://github.com/axel-events/axel/blob/08a663347ef21614b96f92f60f4de57a502db73c/axel/axel.py#L254-L259 | def clear(self):
""" Discards all registered handlers and cached results """
with self._hlock:
self.handlers.clear()
with self._mlock:
self.memoize.clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"with",
"self",
".",
"_hlock",
":",
"self",
".",
"handlers",
".",
"clear",
"(",
")",
"with",
"self",
".",
"_mlock",
":",
"self",
".",
"memoize",
".",
"clear",
"(",
")"
] | Discards all registered handlers and cached results | [
"Discards",
"all",
"registered",
"handlers",
"and",
"cached",
"results"
] | python | train | 33.833333 |
Esri/ArcREST | src/arcrest/manageportal/administration.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L459-L488 | def generateCertificate(self, alias,
commonName, organizationalUnit,
city, state, country,
keyalg="RSA", keysize=1024,
sigalg="SHA256withRSA",
validity=90
... | [
"def",
"generateCertificate",
"(",
"self",
",",
"alias",
",",
"commonName",
",",
"organizationalUnit",
",",
"city",
",",
"state",
",",
"country",
",",
"keyalg",
"=",
"\"RSA\"",
",",
"keysize",
"=",
"1024",
",",
"sigalg",
"=",
"\"SHA256withRSA\"",
",",
"valid... | Use this operation to create a self-signed certificate or as a
starting point for getting a production-ready CA-signed
certificate. The portal will generate a certificate for you and
store it in its keystore. | [
"Use",
"this",
"operation",
"to",
"create",
"a",
"self",
"-",
"signed",
"certificate",
"or",
"as",
"a",
"starting",
"point",
"for",
"getting",
"a",
"production",
"-",
"ready",
"CA",
"-",
"signed",
"certificate",
".",
"The",
"portal",
"will",
"generate",
"a... | python | train | 42.233333 |
tanghaibao/jcvi | jcvi/formats/fasta.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L1934-L1958 | def uniq(args):
"""
%prog uniq fasta uniq.fasta
remove fasta records that are the same
"""
p = OptionParser(uniq.__doc__)
p.add_option("--seq", default=False, action="store_true",
help="Uniqify the sequences [default: %default]")
p.add_option("-t", "--trimname", dest="trimname",... | [
"def",
"uniq",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"uniq",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--seq\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Uniqify the sequences [defa... | %prog uniq fasta uniq.fasta
remove fasta records that are the same | [
"%prog",
"uniq",
"fasta",
"uniq",
".",
"fasta"
] | python | train | 30.32 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/tcex_ti.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L356-L371 | def signature(self, name, file_name, file_type, file_content, owner=None, **kwargs):
"""
Create the Signature TI object.
Args:
owner:
file_content:
file_name:
file_type:
name:
**kwargs:
Return:
"""
... | [
"def",
"signature",
"(",
"self",
",",
"name",
",",
"file_name",
",",
"file_type",
",",
"file_content",
",",
"owner",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Signature",
"(",
"self",
".",
"tcex",
",",
"name",
",",
"file_name",
",",
... | Create the Signature TI object.
Args:
owner:
file_content:
file_name:
file_type:
name:
**kwargs:
Return: | [
"Create",
"the",
"Signature",
"TI",
"object",
"."
] | python | train | 24.875 |
fastai/fastai | old/fastai/structured.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/structured.py#L178-L235 | def fix_missing(df, col, name, na_dict):
""" Fill missing data in a column of df with the median, and add a {name}_na column
which specifies if the data was missing.
Parameters:
-----------
df: The data frame that will be changed.
col: The column of data to fix by filling in missing data.
na... | [
"def",
"fix_missing",
"(",
"df",
",",
"col",
",",
"name",
",",
"na_dict",
")",
":",
"if",
"is_numeric_dtype",
"(",
"col",
")",
":",
"if",
"pd",
".",
"isnull",
"(",
"col",
")",
".",
"sum",
"(",
")",
"or",
"(",
"name",
"in",
"na_dict",
")",
":",
... | Fill missing data in a column of df with the median, and add a {name}_na column
which specifies if the data was missing.
Parameters:
-----------
df: The data frame that will be changed.
col: The column of data to fix by filling in missing data.
name: The name of the new filled column in df.
... | [
"Fill",
"missing",
"data",
"in",
"a",
"column",
"of",
"df",
"with",
"the",
"median",
"and",
"add",
"a",
"{",
"name",
"}",
"_na",
"column",
"which",
"specifies",
"if",
"the",
"data",
"was",
"missing",
".",
"Parameters",
":",
"-----------",
"df",
":",
"T... | python | train | 31.741379 |
uw-it-aca/uw-restclients | restclients/uwnetid/subscription.py | https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/uwnetid/subscription.py#L16-L31 | def get_email_forwarding(netid):
"""
Return a restclients.models.uwnetid.UwEmailForwarding object
on the given uwnetid
"""
subscriptions = get_netid_subscriptions(netid, Subscription.SUBS_CODE_U_FORWARDING)
for subscription in subscriptions:
if subscription.subscription_code == Subscript... | [
"def",
"get_email_forwarding",
"(",
"netid",
")",
":",
"subscriptions",
"=",
"get_netid_subscriptions",
"(",
"netid",
",",
"Subscription",
".",
"SUBS_CODE_U_FORWARDING",
")",
"for",
"subscription",
"in",
"subscriptions",
":",
"if",
"subscription",
".",
"subscription_c... | Return a restclients.models.uwnetid.UwEmailForwarding object
on the given uwnetid | [
"Return",
"a",
"restclients",
".",
"models",
".",
"uwnetid",
".",
"UwEmailForwarding",
"object",
"on",
"the",
"given",
"uwnetid"
] | python | train | 39.75 |
chaoss/grimoirelab-perceval | perceval/backends/core/mbox.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/mbox.py#L238-L247 | def _copy_mbox(self, mbox):
"""Copy the contents of a mbox to a temporary file"""
tmp_path = tempfile.mktemp(prefix='perceval_')
with mbox.container as f_in:
with open(tmp_path, mode='wb') as f_out:
for l in f_in:
f_out.write(l)
return tm... | [
"def",
"_copy_mbox",
"(",
"self",
",",
"mbox",
")",
":",
"tmp_path",
"=",
"tempfile",
".",
"mktemp",
"(",
"prefix",
"=",
"'perceval_'",
")",
"with",
"mbox",
".",
"container",
"as",
"f_in",
":",
"with",
"open",
"(",
"tmp_path",
",",
"mode",
"=",
"'wb'",... | Copy the contents of a mbox to a temporary file | [
"Copy",
"the",
"contents",
"of",
"a",
"mbox",
"to",
"a",
"temporary",
"file"
] | python | test | 31.7 |
daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumberutil.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1709-L1769 | def invalid_example_number(region_code):
"""Gets an invalid number for the specified region.
This is useful for unit-testing purposes, where you want to test what
will happen with an invalid number. Note that the number that is
returned will always be able to be parsed and will have the correct
cou... | [
"def",
"invalid_example_number",
"(",
"region_code",
")",
":",
"if",
"not",
"_is_valid_region_code",
"(",
"region_code",
")",
":",
"return",
"None",
"# We start off with a valid fixed-line number since every country",
"# supports this. Alternatively we could start with a different nu... | Gets an invalid number for the specified region.
This is useful for unit-testing purposes, where you want to test what
will happen with an invalid number. Note that the number that is
returned will always be able to be parsed and will have the correct
country code. It may also be a valid *short* number... | [
"Gets",
"an",
"invalid",
"number",
"for",
"the",
"specified",
"region",
"."
] | python | train | 52.245902 |
pavoni/pyvera | pyvera/__init__.py | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L137-L154 | def get_device_by_name(self, device_name):
"""Search the list of connected devices by name.
device_name param is the string name of the device
"""
# Find the device for the vera device name we are interested in
found_device = None
for device in self.get_devices():
... | [
"def",
"get_device_by_name",
"(",
"self",
",",
"device_name",
")",
":",
"# Find the device for the vera device name we are interested in",
"found_device",
"=",
"None",
"for",
"device",
"in",
"self",
".",
"get_devices",
"(",
")",
":",
"if",
"device",
".",
"name",
"==... | Search the list of connected devices by name.
device_name param is the string name of the device | [
"Search",
"the",
"list",
"of",
"connected",
"devices",
"by",
"name",
"."
] | python | train | 33.888889 |
RedisJSON/rejson-py | rejson/client.py | https://github.com/RedisJSON/rejson-py/blob/55f0adf3adc40f5a769e28e541dbbf5377b90ec6/rejson/client.py#L229-L234 | def jsonarrtrim(self, name, path, start, stop):
"""
Trim the array JSON value under ``path`` at key ``name`` to the
inclusive range given by ``start`` and ``stop``
"""
return self.execute_command('JSON.ARRTRIM', name, str_path(path), start, stop) | [
"def",
"jsonarrtrim",
"(",
"self",
",",
"name",
",",
"path",
",",
"start",
",",
"stop",
")",
":",
"return",
"self",
".",
"execute_command",
"(",
"'JSON.ARRTRIM'",
",",
"name",
",",
"str_path",
"(",
"path",
")",
",",
"start",
",",
"stop",
")"
] | Trim the array JSON value under ``path`` at key ``name`` to the
inclusive range given by ``start`` and ``stop`` | [
"Trim",
"the",
"array",
"JSON",
"value",
"under",
"path",
"at",
"key",
"name",
"to",
"the",
"inclusive",
"range",
"given",
"by",
"start",
"and",
"stop"
] | python | train | 47 |
nugget/python-insteonplm | insteonplm/tools.py | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/tools.py#L346-L350 | def kpl_set_on_mask(self, address, group, mask):
"""Get the status of a KPL button."""
addr = Address(address)
device = self.plm.devices[addr.id]
device.states[group].set_on_mask(mask) | [
"def",
"kpl_set_on_mask",
"(",
"self",
",",
"address",
",",
"group",
",",
"mask",
")",
":",
"addr",
"=",
"Address",
"(",
"address",
")",
"device",
"=",
"self",
".",
"plm",
".",
"devices",
"[",
"addr",
".",
"id",
"]",
"device",
".",
"states",
"[",
"... | Get the status of a KPL button. | [
"Get",
"the",
"status",
"of",
"a",
"KPL",
"button",
"."
] | python | train | 42.4 |
pyviz/holoviews | holoviews/plotting/bokeh/path.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/bokeh/path.py#L250-L267 | def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
plot_method = properties.pop('plot_method', None)
properties = mpl_to_bokeh(properties)
data = dict(properties, **mapping)
if self._has_holes:
plot_method = 'multi_... | [
"def",
"_init_glyph",
"(",
"self",
",",
"plot",
",",
"mapping",
",",
"properties",
")",
":",
"plot_method",
"=",
"properties",
".",
"pop",
"(",
"'plot_method'",
",",
"None",
")",
"properties",
"=",
"mpl_to_bokeh",
"(",
"properties",
")",
"data",
"=",
"dict... | Returns a Bokeh glyph object. | [
"Returns",
"a",
"Bokeh",
"glyph",
"object",
"."
] | python | train | 39.5 |
tipsi/aiozk | aiozk/protocol/primitives.py | https://github.com/tipsi/aiozk/blob/96d2f543de248c6d993b5bfe6621167dd1eb8223/aiozk/protocol/primitives.py#L91-L108 | def parse(cls, buff, offset):
"""
Given a buffer and offset, returns the parsed value and new offset.
Parses the ``size_primitive`` first to determine how many more bytes to
consume to extract the value.
"""
size, offset = cls.size_primitive.parse(buff, offset)
i... | [
"def",
"parse",
"(",
"cls",
",",
"buff",
",",
"offset",
")",
":",
"size",
",",
"offset",
"=",
"cls",
".",
"size_primitive",
".",
"parse",
"(",
"buff",
",",
"offset",
")",
"if",
"size",
"==",
"-",
"1",
":",
"return",
"None",
",",
"offset",
"var_stru... | Given a buffer and offset, returns the parsed value and new offset.
Parses the ``size_primitive`` first to determine how many more bytes to
consume to extract the value. | [
"Given",
"a",
"buffer",
"and",
"offset",
"returns",
"the",
"parsed",
"value",
"and",
"new",
"offset",
"."
] | python | train | 31.055556 |
crackinglandia/pype32 | pype32/pype32.py | https://github.com/crackinglandia/pype32/blob/192fd14dfc0dd36d953739a81c17fbaf5e3d6076/pype32/pype32.py#L838-L847 | def isPe32(self):
"""
Determines if the current L{PE} instance is a PE32 file.
@rtype: bool
@return: C{True} if the current L{PE} instance is a PE32 file. Otherwise, returns C{False}.
"""
if self.ntHeaders.optionalHeader.magic.value == consts.PE32:
re... | [
"def",
"isPe32",
"(",
"self",
")",
":",
"if",
"self",
".",
"ntHeaders",
".",
"optionalHeader",
".",
"magic",
".",
"value",
"==",
"consts",
".",
"PE32",
":",
"return",
"True",
"return",
"False"
] | Determines if the current L{PE} instance is a PE32 file.
@rtype: bool
@return: C{True} if the current L{PE} instance is a PE32 file. Otherwise, returns C{False}. | [
"Determines",
"if",
"the",
"current",
"L",
"{",
"PE",
"}",
"instance",
"is",
"a",
"PE32",
"file",
"."
] | python | train | 34.1 |
dmort27/panphon | panphon/permissive.py | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/permissive.py#L125-L142 | def fts_match(self, fts_mask, segment):
"""Evaluates whether a set of features 'match' a segment (are a subset
of that segment's features)
Args:
fts_mask (list): list of (value, feature) tuples
segment (unicode): IPA string corresponding to segment (consonant or
... | [
"def",
"fts_match",
"(",
"self",
",",
"fts_mask",
",",
"segment",
")",
":",
"fts_mask",
"=",
"set",
"(",
"fts_mask",
")",
"fts_seg",
"=",
"self",
".",
"fts",
"(",
"segment",
")",
"if",
"fts_seg",
":",
"return",
"fts_seg",
"<=",
"fts_mask",
"else",
":",... | Evaluates whether a set of features 'match' a segment (are a subset
of that segment's features)
Args:
fts_mask (list): list of (value, feature) tuples
segment (unicode): IPA string corresponding to segment (consonant or
vowel)
Returns:
... | [
"Evaluates",
"whether",
"a",
"set",
"of",
"features",
"match",
"a",
"segment",
"(",
"are",
"a",
"subset",
"of",
"that",
"segment",
"s",
"features",
")"
] | python | train | 37.555556 |
pantsbuild/pants | src/python/pants/build_graph/build_graph.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/build_graph/build_graph.py#L658-L680 | def sort_targets(targets):
"""
:API: public
:return: the targets that `targets` depend on sorted from most dependent to least.
"""
roots, inverted_deps = invert_dependencies(targets)
ordered = []
visited = set()
def topological_sort(target):
if target not in visited:
visited.add(target)
... | [
"def",
"sort_targets",
"(",
"targets",
")",
":",
"roots",
",",
"inverted_deps",
"=",
"invert_dependencies",
"(",
"targets",
")",
"ordered",
"=",
"[",
"]",
"visited",
"=",
"set",
"(",
")",
"def",
"topological_sort",
"(",
"target",
")",
":",
"if",
"target",
... | :API: public
:return: the targets that `targets` depend on sorted from most dependent to least. | [
":",
"API",
":",
"public"
] | python | train | 21.652174 |
SiLab-Bonn/pyBAR | pybar/run_manager.py | https://github.com/SiLab-Bonn/pyBAR/blob/5ad95bbcd41cd358825823fb78f396cfce23593e/pybar/run_manager.py#L580-L602 | def run_primlist(self, primlist, skip_remaining=False):
'''Runs runs from a primlist.
Parameters
----------
primlist : string
Filename of primlist.
skip_remaining : bool
If True, skip remaining runs, if a run does not exit with status FINISHED.
N... | [
"def",
"run_primlist",
"(",
"self",
",",
"primlist",
",",
"skip_remaining",
"=",
"False",
")",
":",
"runlist",
"=",
"self",
".",
"open_primlist",
"(",
"primlist",
")",
"for",
"index",
",",
"run",
"in",
"enumerate",
"(",
"runlist",
")",
":",
"logging",
".... | Runs runs from a primlist.
Parameters
----------
primlist : string
Filename of primlist.
skip_remaining : bool
If True, skip remaining runs, if a run does not exit with status FINISHED.
Note
----
Primlist is a text file of the following f... | [
"Runs",
"runs",
"from",
"a",
"primlist",
"."
] | python | train | 45.043478 |
johnnoone/json-spec | src/jsonspec/operations/bases.py | https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/operations/bases.py#L28-L45 | def check(self, pointer, expected, raise_onerror=False):
"""Check if value exists into object.
:param pointer: the path to search in
:param expected: the expected value
:param raise_onerror: should raise on error?
:return: boolean
"""
obj = self.document
... | [
"def",
"check",
"(",
"self",
",",
"pointer",
",",
"expected",
",",
"raise_onerror",
"=",
"False",
")",
":",
"obj",
"=",
"self",
".",
"document",
"for",
"token",
"in",
"Pointer",
"(",
"pointer",
")",
":",
"try",
":",
"obj",
"=",
"token",
".",
"extract... | Check if value exists into object.
:param pointer: the path to search in
:param expected: the expected value
:param raise_onerror: should raise on error?
:return: boolean | [
"Check",
"if",
"value",
"exists",
"into",
"object",
"."
] | python | train | 34.944444 |
Capitains/MyCapytain | MyCapytain/resources/texts/remote/cts.py | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L262-L271 | def lastId(self):
""" Children passage
:rtype: str
:returns: First children of the graph. Shortcut to self.graph.children[0]
"""
if self._last is False:
# Request the next urn
self._last = self.childIds[-1]
return self._last | [
"def",
"lastId",
"(",
"self",
")",
":",
"if",
"self",
".",
"_last",
"is",
"False",
":",
"# Request the next urn",
"self",
".",
"_last",
"=",
"self",
".",
"childIds",
"[",
"-",
"1",
"]",
"return",
"self",
".",
"_last"
] | Children passage
:rtype: str
:returns: First children of the graph. Shortcut to self.graph.children[0] | [
"Children",
"passage"
] | python | train | 28.8 |
GoogleCloudPlatform/datastore-ndb-python | ndb/context.py | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/context.py#L908-L928 | def call_on_commit(self, callback):
"""Call a callback upon successful commit of a transaction.
If not in a transaction, the callback is called immediately.
In a transaction, multiple callbacks may be registered and will be
called once the transaction commits, in the order in which they
were regis... | [
"def",
"call_on_commit",
"(",
"self",
",",
"callback",
")",
":",
"if",
"not",
"self",
".",
"in_transaction",
"(",
")",
":",
"callback",
"(",
")",
"else",
":",
"self",
".",
"_on_commit_queue",
".",
"append",
"(",
"callback",
")"
] | Call a callback upon successful commit of a transaction.
If not in a transaction, the callback is called immediately.
In a transaction, multiple callbacks may be registered and will be
called once the transaction commits, in the order in which they
were registered. If the transaction fails, the callb... | [
"Call",
"a",
"callback",
"upon",
"successful",
"commit",
"of",
"a",
"transaction",
"."
] | python | train | 41.904762 |
pycampers/zproc | zproc/exceptions.py | https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/exceptions.py#L63-L83 | def signal_to_exception(sig: signal.Signals) -> SignalException:
"""
Convert a ``signal.Signals`` to a ``SignalException``.
This allows for natural, pythonic signal handing with the use of try-except blocks.
.. code-block:: python
import signal
import zproc
zproc.signal_to_ex... | [
"def",
"signal_to_exception",
"(",
"sig",
":",
"signal",
".",
"Signals",
")",
"->",
"SignalException",
":",
"signal",
".",
"signal",
"(",
"sig",
",",
"_sig_exc_handler",
")",
"return",
"SignalException",
"(",
"sig",
")"
] | Convert a ``signal.Signals`` to a ``SignalException``.
This allows for natural, pythonic signal handing with the use of try-except blocks.
.. code-block:: python
import signal
import zproc
zproc.signal_to_exception(signals.SIGTERM)
try:
...
except zproc.Si... | [
"Convert",
"a",
"signal",
".",
"Signals",
"to",
"a",
"SignalException",
"."
] | python | train | 27.904762 |
jgorset/facepy | facepy/graph_api.py | https://github.com/jgorset/facepy/blob/1be3ee21389fb2db543927a2f4ffa949faec4242/facepy/graph_api.py#L209-L341 | def _query(self, method, path, data=None, page=False, retry=0):
"""
Fetch an object from the Graph API and parse the output, returning a tuple where the first item
is the object yielded by the Graph API and the second is the URL for the next page of results, or
``None`` if results have b... | [
"def",
"_query",
"(",
"self",
",",
"method",
",",
"path",
",",
"data",
"=",
"None",
",",
"page",
"=",
"False",
",",
"retry",
"=",
"0",
")",
":",
"if",
"(",
"data",
")",
":",
"data",
"=",
"dict",
"(",
"(",
"k",
".",
"replace",
"(",
"'_sqbro_'",
... | Fetch an object from the Graph API and parse the output, returning a tuple where the first item
is the object yielded by the Graph API and the second is the URL for the next page of results, or
``None`` if results have been exhausted.
:param method: A string describing the HTTP method.
... | [
"Fetch",
"an",
"object",
"from",
"the",
"Graph",
"API",
"and",
"parse",
"the",
"output",
"returning",
"a",
"tuple",
"where",
"the",
"first",
"item",
"is",
"the",
"object",
"yielded",
"by",
"the",
"Graph",
"API",
"and",
"the",
"second",
"is",
"the",
"URL"... | python | train | 38.969925 |
gc3-uzh-ch/elasticluster | elasticluster/providers/ec2_boto.py | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/ec2_boto.py#L144-L154 | def to_vars_dict(self):
"""
Return local state which is relevant for the cluster setup process.
"""
return {
'aws_access_key_id': self._access_key,
'aws_secret_access_key': self._secret_key,
'aws_region': self._region_name,
... | [
"def",
"to_vars_dict",
"(",
"self",
")",
":",
"return",
"{",
"'aws_access_key_id'",
":",
"self",
".",
"_access_key",
",",
"'aws_secret_access_key'",
":",
"self",
".",
"_secret_key",
",",
"'aws_region'",
":",
"self",
".",
"_region_name",
",",
"'aws_vpc_name'",
":... | Return local state which is relevant for the cluster setup process. | [
"Return",
"local",
"state",
"which",
"is",
"relevant",
"for",
"the",
"cluster",
"setup",
"process",
"."
] | python | train | 38.727273 |
ibis-project/ibis | ibis/clickhouse/operations.py | https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/clickhouse/operations.py#L214-L219 | def _sign(translator, expr):
"""Workaround for missing sign function"""
op = expr.op()
arg, = op.args
arg_ = translator.translate(arg)
return 'intDivOrZero({0}, abs({0}))'.format(arg_) | [
"def",
"_sign",
"(",
"translator",
",",
"expr",
")",
":",
"op",
"=",
"expr",
".",
"op",
"(",
")",
"arg",
",",
"=",
"op",
".",
"args",
"arg_",
"=",
"translator",
".",
"translate",
"(",
"arg",
")",
"return",
"'intDivOrZero({0}, abs({0}))'",
".",
"format"... | Workaround for missing sign function | [
"Workaround",
"for",
"missing",
"sign",
"function"
] | python | train | 33.166667 |
swistakm/graceful | src/graceful/authentication.py | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L77-L81 | def get_user(
self, identified_with, identifier, req, resp, resource, uri_kwargs
):
"""Return default user object."""
return self.user | [
"def",
"get_user",
"(",
"self",
",",
"identified_with",
",",
"identifier",
",",
"req",
",",
"resp",
",",
"resource",
",",
"uri_kwargs",
")",
":",
"return",
"self",
".",
"user"
] | Return default user object. | [
"Return",
"default",
"user",
"object",
"."
] | python | train | 31.6 |
twilio/twilio-python | twilio/base/page.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/base/page.py#L51-L61 | def process_response(self, response):
"""
Load a JSON response.
:param Response response: The HTTP response.
:return dict: The JSON-loaded content.
"""
if response.status_code != 200:
raise TwilioException('Unable to fetch page', response)
return jso... | [
"def",
"process_response",
"(",
"self",
",",
"response",
")",
":",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"raise",
"TwilioException",
"(",
"'Unable to fetch page'",
",",
"response",
")",
"return",
"json",
".",
"loads",
"(",
"response",
".",
... | Load a JSON response.
:param Response response: The HTTP response.
:return dict: The JSON-loaded content. | [
"Load",
"a",
"JSON",
"response",
"."
] | python | train | 30.181818 |
senaite/senaite.core | bika/lims/browser/dashboard/dashboard.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/dashboard/dashboard.py#L129-L157 | def get_dashboard_panels_visibility_by_section(section_name):
"""
Return a list of pairs as values that represents the role-permission
view relation for the panel section passed in.
:param section_name: the panels section id.
:return: a list of tuples.
"""
registry_info = get_dashboard_regis... | [
"def",
"get_dashboard_panels_visibility_by_section",
"(",
"section_name",
")",
":",
"registry_info",
"=",
"get_dashboard_registry_record",
"(",
")",
"if",
"section_name",
"not",
"in",
"registry_info",
":",
"# Registry hasn't been set, do it at least for this section",
"registry_i... | Return a list of pairs as values that represents the role-permission
view relation for the panel section passed in.
:param section_name: the panels section id.
:return: a list of tuples. | [
"Return",
"a",
"list",
"of",
"pairs",
"as",
"values",
"that",
"represents",
"the",
"role",
"-",
"permission",
"view",
"relation",
"for",
"the",
"panel",
"section",
"passed",
"in",
".",
":",
"param",
"section_name",
":",
"the",
"panels",
"section",
"id",
".... | python | train | 39.793103 |
googleapis/google-cloud-python | datastore/google/cloud/datastore/key.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/key.py#L629-L656 | def _to_legacy_path(dict_path):
"""Convert a tuple of ints and strings in a legacy "Path".
.. note:
This assumes, but does not verify, that each entry in
``dict_path`` is valid (i.e. doesn't have more than one
key out of "name" / "id").
:type dict_path: lsit
:param dict_path: ... | [
"def",
"_to_legacy_path",
"(",
"dict_path",
")",
":",
"elements",
"=",
"[",
"]",
"for",
"part",
"in",
"dict_path",
":",
"element_kwargs",
"=",
"{",
"\"type\"",
":",
"part",
"[",
"\"kind\"",
"]",
"}",
"if",
"\"id\"",
"in",
"part",
":",
"element_kwargs",
"... | Convert a tuple of ints and strings in a legacy "Path".
.. note:
This assumes, but does not verify, that each entry in
``dict_path`` is valid (i.e. doesn't have more than one
key out of "name" / "id").
:type dict_path: lsit
:param dict_path: The "structured" path for a key, i.e. i... | [
"Convert",
"a",
"tuple",
"of",
"ints",
"and",
"strings",
"in",
"a",
"legacy",
"Path",
"."
] | python | train | 35.035714 |
jleclanche/fireplace | fireplace/game.py | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/game.py#L153-L158 | def trigger(self, source, actions, event_args):
"""
Perform actions as a result of an event listener (TRIGGER)
"""
type = BlockType.TRIGGER
return self.action_block(source, actions, type, event_args=event_args) | [
"def",
"trigger",
"(",
"self",
",",
"source",
",",
"actions",
",",
"event_args",
")",
":",
"type",
"=",
"BlockType",
".",
"TRIGGER",
"return",
"self",
".",
"action_block",
"(",
"source",
",",
"actions",
",",
"type",
",",
"event_args",
"=",
"event_args",
... | Perform actions as a result of an event listener (TRIGGER) | [
"Perform",
"actions",
"as",
"a",
"result",
"of",
"an",
"event",
"listener",
"(",
"TRIGGER",
")"
] | python | train | 35.833333 |
sander76/aio-powerview-api | aiopvapi/helpers/powerview_util.py | https://github.com/sander76/aio-powerview-api/blob/08b6ac747aba9de19842359a981a7ff1292f5a6c/aiopvapi/helpers/powerview_util.py#L32-L40 | async def create_scene(self, scene_name, room_id) -> Scene:
"""Create a scene and returns the scene object.
:raises PvApiError when something is wrong with the hub.
"""
_raw = await self._scenes_entry_point.create_scene(room_id, scene_name)
result = Scene(_raw, self.request)
... | [
"async",
"def",
"create_scene",
"(",
"self",
",",
"scene_name",
",",
"room_id",
")",
"->",
"Scene",
":",
"_raw",
"=",
"await",
"self",
".",
"_scenes_entry_point",
".",
"create_scene",
"(",
"room_id",
",",
"scene_name",
")",
"result",
"=",
"Scene",
"(",
"_r... | Create a scene and returns the scene object.
:raises PvApiError when something is wrong with the hub. | [
"Create",
"a",
"scene",
"and",
"returns",
"the",
"scene",
"object",
"."
] | python | train | 40.555556 |
umich-brcf-bioinf/Jacquard | jacquard/utils/vcf.py | https://github.com/umich-brcf-bioinf/Jacquard/blob/83dd61dd2b5e4110468493beec7bc121e6cb3cd1/jacquard/utils/vcf.py#L313-L326 | def _join_info_fields(self):
"""Updates info attribute from info dict."""
if self.info_dict:
info_fields = []
if len(self.info_dict) > 1:
self.info_dict.pop(".", None)
for field, value in self.info_dict.items():
if field == value:
... | [
"def",
"_join_info_fields",
"(",
"self",
")",
":",
"if",
"self",
".",
"info_dict",
":",
"info_fields",
"=",
"[",
"]",
"if",
"len",
"(",
"self",
".",
"info_dict",
")",
">",
"1",
":",
"self",
".",
"info_dict",
".",
"pop",
"(",
"\".\"",
",",
"None",
"... | Updates info attribute from info dict. | [
"Updates",
"info",
"attribute",
"from",
"info",
"dict",
"."
] | python | test | 37.285714 |
oauthlib/oauthlib | oauthlib/oauth2/rfc6749/tokens.py | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/tokens.py#L300-L340 | def create_token(self, request, refresh_token=False, **kwargs):
"""
Create a BearerToken, by default without refresh token.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param refresh_token:
"""
if "save_token" in kwargs:
w... | [
"def",
"create_token",
"(",
"self",
",",
"request",
",",
"refresh_token",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"\"save_token\"",
"in",
"kwargs",
":",
"warnings",
".",
"warn",
"(",
"\"`save_token` has been deprecated, it was not called internally.\"... | Create a BearerToken, by default without refresh token.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param refresh_token: | [
"Create",
"a",
"BearerToken",
"by",
"default",
"without",
"refresh",
"token",
"."
] | python | train | 39.853659 |
pantsbuild/pants | src/python/pants/build_graph/bundle_mixin.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/build_graph/bundle_mixin.py#L58-L80 | def symlink_bundles(self, app, bundle_dir):
"""For each bundle in the given app, symlinks relevant matched paths.
Validates that at least one path was matched by a bundle.
"""
for bundle_counter, bundle in enumerate(app.bundles):
count = 0
for path, relpath in bundle.filemap.items():
... | [
"def",
"symlink_bundles",
"(",
"self",
",",
"app",
",",
"bundle_dir",
")",
":",
"for",
"bundle_counter",
",",
"bundle",
"in",
"enumerate",
"(",
"app",
".",
"bundles",
")",
":",
"count",
"=",
"0",
"for",
"path",
",",
"relpath",
"in",
"bundle",
".",
"fil... | For each bundle in the given app, symlinks relevant matched paths.
Validates that at least one path was matched by a bundle. | [
"For",
"each",
"bundle",
"in",
"the",
"given",
"app",
"symlinks",
"relevant",
"matched",
"paths",
"."
] | python | train | 37.478261 |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L1220-L1230 | def highlightBlock(self, text):
""" Actually highlight the block"""
# Note that an undefined blockstate is equal to -1, so the first block
# will have the correct behaviour of starting at 0.
if self._allow_highlight:
start = self.previousBlockState() + 1
end... | [
"def",
"highlightBlock",
"(",
"self",
",",
"text",
")",
":",
"# Note that an undefined blockstate is equal to -1, so the first block\r",
"# will have the correct behaviour of starting at 0.\r",
"if",
"self",
".",
"_allow_highlight",
":",
"start",
"=",
"self",
".",
"previousBloc... | Actually highlight the block | [
"Actually",
"highlight",
"the",
"block"
] | python | train | 48.454545 |
brandonxiang/geojson-python-utils | geojson_utils/geojson_utils.py | https://github.com/brandonxiang/geojson-python-utils/blob/33d0dcd5f16e0567b48c0d49fd292a4f1db16b41/geojson_utils/geojson_utils.py#L216-L236 | def point_distance(point1, point2):
"""
calculate the distance between two points on the sphere like google map
reference http://www.movable-type.co.uk/scripts/latlong.html
Keyword arguments:
point1 -- point one geojson object
point2 -- point two geojson object
return distance
"""
... | [
"def",
"point_distance",
"(",
"point1",
",",
"point2",
")",
":",
"lon1",
"=",
"point1",
"[",
"'coordinates'",
"]",
"[",
"0",
"]",
"lat1",
"=",
"point1",
"[",
"'coordinates'",
"]",
"[",
"1",
"]",
"lon2",
"=",
"point2",
"[",
"'coordinates'",
"]",
"[",
... | calculate the distance between two points on the sphere like google map
reference http://www.movable-type.co.uk/scripts/latlong.html
Keyword arguments:
point1 -- point one geojson object
point2 -- point two geojson object
return distance | [
"calculate",
"the",
"distance",
"between",
"two",
"points",
"on",
"the",
"sphere",
"like",
"google",
"map",
"reference",
"http",
":",
"//",
"www",
".",
"movable",
"-",
"type",
".",
"co",
".",
"uk",
"/",
"scripts",
"/",
"latlong",
".",
"html"
] | python | train | 36.238095 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L1431-L1459 | def get_dependencies(self, id, **kwargs):
"""
Get the direct dependencies of the specified configuration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the re... | [
"def",
"get_dependencies",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_dependencies_with_http_inf... | Get the direct dependencies of the specified configuration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>... | [
"Get",
"the",
"direct",
"dependencies",
"of",
"the",
"specified",
"configuration",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",... | python | train | 41.448276 |
carpedm20/fbchat | fbchat/_client.py | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L680-L693 | def searchForUsers(self, name, limit=10):
"""
Find and get user by his/her name
:param name: Name of the user
:param limit: The max. amount of users to fetch
:return: :class:`models.User` objects, ordered by relevance
:rtype: list
:raises: FBchatException if requ... | [
"def",
"searchForUsers",
"(",
"self",
",",
"name",
",",
"limit",
"=",
"10",
")",
":",
"params",
"=",
"{",
"\"search\"",
":",
"name",
",",
"\"limit\"",
":",
"limit",
"}",
"j",
"=",
"self",
".",
"graphql_request",
"(",
"GraphQL",
"(",
"query",
"=",
"Gr... | Find and get user by his/her name
:param name: Name of the user
:param limit: The max. amount of users to fetch
:return: :class:`models.User` objects, ordered by relevance
:rtype: list
:raises: FBchatException if request failed | [
"Find",
"and",
"get",
"user",
"by",
"his",
"/",
"her",
"name"
] | python | train | 38.857143 |
zetaops/zengine | zengine/engine.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/engine.py#L608-L643 | def _load_activity(self, activity):
"""
Iterates trough the all enabled `~zengine.settings.ACTIVITY_MODULES_IMPORT_PATHS` to find the given path.
"""
fpths = []
full_path = ''
errors = []
paths = settings.ACTIVITY_MODULES_IMPORT_PATHS
number_of_paths = len... | [
"def",
"_load_activity",
"(",
"self",
",",
"activity",
")",
":",
"fpths",
"=",
"[",
"]",
"full_path",
"=",
"''",
"errors",
"=",
"[",
"]",
"paths",
"=",
"settings",
".",
"ACTIVITY_MODULES_IMPORT_PATHS",
"number_of_paths",
"=",
"len",
"(",
"paths",
")",
"for... | Iterates trough the all enabled `~zengine.settings.ACTIVITY_MODULES_IMPORT_PATHS` to find the given path. | [
"Iterates",
"trough",
"the",
"all",
"enabled",
"~zengine",
".",
"settings",
".",
"ACTIVITY_MODULES_IMPORT_PATHS",
"to",
"find",
"the",
"given",
"path",
"."
] | python | train | 58.888889 |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L734-L769 | def get_job(self, id_job, hub=None, group=None, project=None,
access_token=None, user_id=None):
"""
Get the information about a job, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.... | [
"def",
"get_job",
"(",
"self",
",",
"id_job",
",",
"hub",
"=",
"None",
",",
"group",
"=",
"None",
",",
"project",
"=",
"None",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
"... | Get the information about a job, by its id | [
"Get",
"the",
"information",
"about",
"a",
"job",
"by",
"its",
"id"
] | python | train | 33.25 |
dag/flask-zodb | flask_zodb.py | https://github.com/dag/flask-zodb/blob/c5451aba28cd5b303c71654b7ef2b62edb08afe8/flask_zodb.py#L48-L57 | def close_db(self, exception):
"""Added as a `~flask.Flask.teardown_request` to applications to
commit the transaction and disconnect ZODB if it was used during
the request."""
if self.is_connected:
if exception is None and not transaction.isDoomed():
transact... | [
"def",
"close_db",
"(",
"self",
",",
"exception",
")",
":",
"if",
"self",
".",
"is_connected",
":",
"if",
"exception",
"is",
"None",
"and",
"not",
"transaction",
".",
"isDoomed",
"(",
")",
":",
"transaction",
".",
"commit",
"(",
")",
"else",
":",
"tran... | Added as a `~flask.Flask.teardown_request` to applications to
commit the transaction and disconnect ZODB if it was used during
the request. | [
"Added",
"as",
"a",
"~flask",
".",
"Flask",
".",
"teardown_request",
"to",
"applications",
"to",
"commit",
"the",
"transaction",
"and",
"disconnect",
"ZODB",
"if",
"it",
"was",
"used",
"during",
"the",
"request",
"."
] | python | train | 41.3 |
stanfordnlp/stanza | stanza/research/learner.py | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/learner.py#L153-L164 | def load(self, infile):
'''
Deserialize a model from a stored file.
By default, unpickle an entire object. If `dump` is overridden to
use a different storage format, `load` should be as well.
:param file outfile: A file-like object from which to retrieve the
seriali... | [
"def",
"load",
"(",
"self",
",",
"infile",
")",
":",
"model",
"=",
"pickle",
".",
"load",
"(",
"infile",
")",
"self",
".",
"__dict__",
".",
"update",
"(",
"model",
".",
"__dict__",
")"
] | Deserialize a model from a stored file.
By default, unpickle an entire object. If `dump` is overridden to
use a different storage format, `load` should be as well.
:param file outfile: A file-like object from which to retrieve the
serialized model. | [
"Deserialize",
"a",
"model",
"from",
"a",
"stored",
"file",
"."
] | python | train | 34.333333 |
mila/pyoo | pyoo.py | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1776-L1786 | def date_to_number(self, date):
"""
Converts a date or datetime instance to a corresponding float value.
"""
if isinstance(date, datetime.datetime):
delta = date - self._null_date
elif isinstance(date, datetime.date):
delta = date - self._null_date.date()
... | [
"def",
"date_to_number",
"(",
"self",
",",
"date",
")",
":",
"if",
"isinstance",
"(",
"date",
",",
"datetime",
".",
"datetime",
")",
":",
"delta",
"=",
"date",
"-",
"self",
".",
"_null_date",
"elif",
"isinstance",
"(",
"date",
",",
"datetime",
".",
"da... | Converts a date or datetime instance to a corresponding float value. | [
"Converts",
"a",
"date",
"or",
"datetime",
"instance",
"to",
"a",
"corresponding",
"float",
"value",
"."
] | python | train | 38 |
jam31118/vis | vis/layout.py | https://github.com/jam31118/vis/blob/965ebec102c539b323d5756fef04153ac71e50d9/vis/layout.py#L59-L71 | def get_text_position_and_inner_alignment(ax, pos, scale=default_text_relative_padding, with_transAxes_kwargs=True):
"""Return text position and its alignment in its bounding box.
The returned position is given in Axes coordinate,
as defined in matplotlib documentation on transformation.
The retur... | [
"def",
"get_text_position_and_inner_alignment",
"(",
"ax",
",",
"pos",
",",
"scale",
"=",
"default_text_relative_padding",
",",
"with_transAxes_kwargs",
"=",
"True",
")",
":",
"xy",
"=",
"get_text_position_in_ax_coord",
"(",
"ax",
",",
"pos",
",",
"scale",
"=",
"s... | Return text position and its alignment in its bounding box.
The returned position is given in Axes coordinate,
as defined in matplotlib documentation on transformation.
The returned alignment is given in dictionary,
which can be put as a fontdict to text-relavent method. | [
"Return",
"text",
"position",
"and",
"its",
"alignment",
"in",
"its",
"bounding",
"box",
".",
"The",
"returned",
"position",
"is",
"given",
"in",
"Axes",
"coordinate",
"as",
"defined",
"in",
"matplotlib",
"documentation",
"on",
"transformation",
"."
] | python | train | 50.692308 |
Telefonica/toolium | toolium/config_parser.py | https://github.com/Telefonica/toolium/blob/56847c243b3a98876df74c184b75e43f8810e475/toolium/config_parser.py#L75-L82 | def update_properties(self, new_properties):
""" Update config properties values
Property name must be equal to 'Section_option' of config property
:param new_properties: dict with new properties values
"""
[self._update_property_from_dict(section, option, new_properties)
... | [
"def",
"update_properties",
"(",
"self",
",",
"new_properties",
")",
":",
"[",
"self",
".",
"_update_property_from_dict",
"(",
"section",
",",
"option",
",",
"new_properties",
")",
"for",
"section",
"in",
"self",
".",
"sections",
"(",
")",
"for",
"option",
"... | Update config properties values
Property name must be equal to 'Section_option' of config property
:param new_properties: dict with new properties values | [
"Update",
"config",
"properties",
"values",
"Property",
"name",
"must",
"be",
"equal",
"to",
"Section_option",
"of",
"config",
"property"
] | python | train | 47.875 |
Azure/blobxfer | blobxfer/operations/upload.py | https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/operations/upload.py#L369-L397 | def _process_transfer(self, ud, ase, offsets, data):
# type: (Uploader, blobxfer.models.upload.Descriptor,
# blobxfer.models.azure.StorageEntity,
# blobxfer.models.upload.Offsets, bytes) -> None
"""Process transfer instructions
:param Uploader self: this
:pa... | [
"def",
"_process_transfer",
"(",
"self",
",",
"ud",
",",
"ase",
",",
"offsets",
",",
"data",
")",
":",
"# type: (Uploader, blobxfer.models.upload.Descriptor,",
"# blobxfer.models.azure.StorageEntity,",
"# blobxfer.models.upload.Offsets, bytes) -> None",
"# issue put r... | Process transfer instructions
:param Uploader self: this
:param blobxfer.models.upload.Descriptor ud: upload descriptor
:param blobxfer.models.azure.StorageEntity ase: Storage entity
:param blobxfer.models.upload.Offsets offsets: offsets
:param bytes data: data to upload | [
"Process",
"transfer",
"instructions",
":",
"param",
"Uploader",
"self",
":",
"this",
":",
"param",
"blobxfer",
".",
"models",
".",
"upload",
".",
"Descriptor",
"ud",
":",
"upload",
"descriptor",
":",
"param",
"blobxfer",
".",
"models",
".",
"azure",
".",
... | python | train | 48.827586 |
mayfield/shellish | shellish/layout/table.py | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L207-L238 | def attach_arguments(cls, parser, prefix='--', skip_formats=False,
format_excludes=None, format_title=None,
format_desc=None, skip_render=False,
render_excludes=None, render_title=None,
render_desc=None, skip_filters=Fal... | [
"def",
"attach_arguments",
"(",
"cls",
",",
"parser",
",",
"prefix",
"=",
"'--'",
",",
"skip_formats",
"=",
"False",
",",
"format_excludes",
"=",
"None",
",",
"format_title",
"=",
"None",
",",
"format_desc",
"=",
"None",
",",
"skip_render",
"=",
"False",
"... | Attach argparse arguments to an argparse parser/group with table
options. These are renderer options and filtering options with the
ability to turn off headers and footers. The return value is function
that parses an argparse.Namespace object into keyword arguments for a
layout.Table c... | [
"Attach",
"argparse",
"arguments",
"to",
"an",
"argparse",
"parser",
"/",
"group",
"with",
"table",
"options",
".",
"These",
"are",
"renderer",
"options",
"and",
"filtering",
"options",
"with",
"the",
"ability",
"to",
"turn",
"off",
"headers",
"and",
"footers"... | python | train | 49.5625 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.