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 |
|---|---|---|---|---|---|---|---|---|---|
buildbot/buildbot | master/buildbot/worker_transition.py | https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/worker_transition.py#L131-L150 | def setupWorkerTransition():
"""Hook Twisted deprecation machinery to use custom warning class
for Worker API deprecation warnings."""
default_warn_method = getWarningMethod()
def custom_warn_method(message, category, stacklevel):
if stacklevel is not None:
stacklevel += 1
... | [
"def",
"setupWorkerTransition",
"(",
")",
":",
"default_warn_method",
"=",
"getWarningMethod",
"(",
")",
"def",
"custom_warn_method",
"(",
"message",
",",
"category",
",",
"stacklevel",
")",
":",
"if",
"stacklevel",
"is",
"not",
"None",
":",
"stacklevel",
"+=",
... | Hook Twisted deprecation machinery to use custom warning class
for Worker API deprecation warnings. | [
"Hook",
"Twisted",
"deprecation",
"machinery",
"to",
"use",
"custom",
"warning",
"class",
"for",
"Worker",
"API",
"deprecation",
"warnings",
"."
] | python | train | 38.65 |
ff0000/scarlet | scarlet/cms/bundles.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/bundles.py#L342-L392 | def get_string_from_view(self, request, view_name, url_kwargs,
render_type='string'):
"""
Returns a string that is a rendering of the view given a
request, view_name, and the original url_kwargs. Makes the
following changes the view before... | [
"def",
"get_string_from_view",
"(",
"self",
",",
"request",
",",
"view_name",
",",
"url_kwargs",
",",
"render_type",
"=",
"'string'",
")",
":",
"response",
"=",
"\"\"",
"try",
":",
"view",
",",
"name",
"=",
"self",
".",
"get_initialized_view_and_name",
"(",
... | Returns a string that is a rendering of the view given a
request, view_name, and the original url_kwargs. Makes the
following changes the view before rendering:
* Sets can_submit to False.
* Adds action_url to the context. This is the url where \
this view actually lives.
... | [
"Returns",
"a",
"string",
"that",
"is",
"a",
"rendering",
"of",
"the",
"view",
"given",
"a",
"request",
"view_name",
"and",
"the",
"original",
"url_kwargs",
".",
"Makes",
"the",
"following",
"changes",
"the",
"view",
"before",
"rendering",
":"
] | python | train | 44.254902 |
lsst-epo/vela | astropixie-widgets/astropixie_widgets/science.py | https://github.com/lsst-epo/vela/blob/8e17ebec509be5c3cc2063f4645dfe9e26b49c18/astropixie-widgets/astropixie_widgets/science.py#L24-L41 | def teff(cluster):
"""
Calculate Teff for main sequence stars ranging from Teff 3500K - 8000K. Use
[Fe/H] of the cluster, if available.
Returns a list of Teff values.
"""
b_vs, _ = cluster.stars()
teffs = []
for b_v in b_vs:
b_v -= cluster.eb_v
if b_v > -0.04:
... | [
"def",
"teff",
"(",
"cluster",
")",
":",
"b_vs",
",",
"_",
"=",
"cluster",
".",
"stars",
"(",
")",
"teffs",
"=",
"[",
"]",
"for",
"b_v",
"in",
"b_vs",
":",
"b_v",
"-=",
"cluster",
".",
"eb_v",
"if",
"b_v",
">",
"-",
"0.04",
":",
"x",
"=",
"("... | Calculate Teff for main sequence stars ranging from Teff 3500K - 8000K. Use
[Fe/H] of the cluster, if available.
Returns a list of Teff values. | [
"Calculate",
"Teff",
"for",
"main",
"sequence",
"stars",
"ranging",
"from",
"Teff",
"3500K",
"-",
"8000K",
".",
"Use",
"[",
"Fe",
"/",
"H",
"]",
"of",
"the",
"cluster",
"if",
"available",
"."
] | python | valid | 25.888889 |
3ll3d00d/vibe | backend/src/analyser/common/uploadcontroller.py | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/analyser/common/uploadcontroller.py#L41-L54 | def loadSignal(self, name, start=None, end=None):
"""
Loads the named entry from the upload cache as a signal.
:param name: the name.
:param start: the time to start from in HH:mm:ss.SSS format
:param end: the time to end at in HH:mm:ss.SSS format.
:return: the signal if ... | [
"def",
"loadSignal",
"(",
"self",
",",
"name",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"entry",
"=",
"self",
".",
"_getCacheEntry",
"(",
"name",
")",
"if",
"entry",
"is",
"not",
"None",
":",
"from",
"analyser",
".",
"common",
... | Loads the named entry from the upload cache as a signal.
:param name: the name.
:param start: the time to start from in HH:mm:ss.SSS format
:param end: the time to end at in HH:mm:ss.SSS format.
:return: the signal if the named upload exists. | [
"Loads",
"the",
"named",
"entry",
"from",
"the",
"upload",
"cache",
"as",
"a",
"signal",
".",
":",
"param",
"name",
":",
"the",
"name",
".",
":",
"param",
"start",
":",
"the",
"time",
"to",
"start",
"from",
"in",
"HH",
":",
"mm",
":",
"ss",
".",
... | python | train | 42.285714 |
eamigo86/graphene-django-extras | graphene_django_extras/utils.py | https://github.com/eamigo86/graphene-django-extras/blob/b27fd6b5128f6b6a500a8b7a497d76be72d6a232/graphene_django_extras/utils.py#L104-L130 | def get_obj(app_label, model_name, object_id):
"""
Function used to get a object
:param app_label: A valid Django Model or a string with format: <app_label>.<model_name>
:param model_name: Key into kwargs that contains de data: new_person
:param object_id:
:return: instance
"""
try:
... | [
"def",
"get_obj",
"(",
"app_label",
",",
"model_name",
",",
"object_id",
")",
":",
"try",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"\"{}.{}\"",
".",
"format",
"(",
"app_label",
",",
"model_name",
")",
")",
"assert",
"is_valid_django_model",
"(",
"... | Function used to get a object
:param app_label: A valid Django Model or a string with format: <app_label>.<model_name>
:param model_name: Key into kwargs that contains de data: new_person
:param object_id:
:return: instance | [
"Function",
"used",
"to",
"get",
"a",
"object",
":",
"param",
"app_label",
":",
"A",
"valid",
"Django",
"Model",
"or",
"a",
"string",
"with",
"format",
":",
"<app_label",
">",
".",
"<model_name",
">",
":",
"param",
"model_name",
":",
"Key",
"into",
"kwar... | python | train | 31.592593 |
fastai/fastai | fastai/callback.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L364-L367 | def annealing_cos(start:Number, end:Number, pct:float)->Number:
"Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0."
cos_out = np.cos(np.pi * pct) + 1
return end + (start-end)/2 * cos_out | [
"def",
"annealing_cos",
"(",
"start",
":",
"Number",
",",
"end",
":",
"Number",
",",
"pct",
":",
"float",
")",
"->",
"Number",
":",
"cos_out",
"=",
"np",
".",
"cos",
"(",
"np",
".",
"pi",
"*",
"pct",
")",
"+",
"1",
"return",
"end",
"+",
"(",
"s... | Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0. | [
"Cosine",
"anneal",
"from",
"start",
"to",
"end",
"as",
"pct",
"goes",
"from",
"0",
".",
"0",
"to",
"1",
".",
"0",
"."
] | python | train | 52.5 |
dnanexus/dx-toolkit | src/python/dxpy/bindings/dxapplet.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/bindings/dxapplet.py#L158-L227 | def run(self, executable_input, project=None, folder=None, name=None, tags=None, properties=None, details=None,
instance_type=None, stage_instance_types=None, stage_folders=None, rerun_stages=None, cluster_spec=None,
depends_on=None, allow_ssh=None, debug=None, delay_workspace_destruction=None, ... | [
"def",
"run",
"(",
"self",
",",
"executable_input",
",",
"project",
"=",
"None",
",",
"folder",
"=",
"None",
",",
"name",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"properties",
"=",
"None",
",",
"details",
"=",
"None",
",",
"instance_type",
"=",
"... | :param executable_input: Hash of the executable's input arguments
:type executable_input: dict
:param project: Project ID of the project context
:type project: string
:param folder: Folder in which executable's outputs will be placed in *project*
:type folder: string
:par... | [
":",
"param",
"executable_input",
":",
"Hash",
"of",
"the",
"executable",
"s",
"input",
"arguments",
":",
"type",
"executable_input",
":",
"dict",
":",
"param",
"project",
":",
"Project",
"ID",
"of",
"the",
"project",
"context",
":",
"type",
"project",
":",
... | python | train | 62.342857 |
openstax/cnx-easybake | cnxeasybake/oven.py | https://github.com/openstax/cnx-easybake/blob/f8edf018fb7499f6f18af0145c326b93a737a782/cnxeasybake/oven.py#L1390-L1404 | def append_string(t, string):
"""Append a string to a node, as text or tail of last child."""
node = t.tree
if string:
if len(node) == 0:
if node.text is not None:
node.text += string
else:
node.text = string
else: # Get last child
... | [
"def",
"append_string",
"(",
"t",
",",
"string",
")",
":",
"node",
"=",
"t",
".",
"tree",
"if",
"string",
":",
"if",
"len",
"(",
"node",
")",
"==",
"0",
":",
"if",
"node",
".",
"text",
"is",
"not",
"None",
":",
"node",
".",
"text",
"+=",
"strin... | Append a string to a node, as text or tail of last child. | [
"Append",
"a",
"string",
"to",
"a",
"node",
"as",
"text",
"or",
"tail",
"of",
"last",
"child",
"."
] | python | train | 31.133333 |
tanghaibao/jcvi | jcvi/formats/agp.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L269-L275 | def getNorthSouthClone(self, i):
"""
Returns the adjacent clone name from both sides.
"""
north = self.getAdjacentClone(i, south=False)
south = self.getAdjacentClone(i)
return north, south | [
"def",
"getNorthSouthClone",
"(",
"self",
",",
"i",
")",
":",
"north",
"=",
"self",
".",
"getAdjacentClone",
"(",
"i",
",",
"south",
"=",
"False",
")",
"south",
"=",
"self",
".",
"getAdjacentClone",
"(",
"i",
")",
"return",
"north",
",",
"south"
] | Returns the adjacent clone name from both sides. | [
"Returns",
"the",
"adjacent",
"clone",
"name",
"from",
"both",
"sides",
"."
] | python | train | 32.857143 |
Erotemic/utool | utool/util_sysreq.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_sysreq.py#L11-L44 | def in_virtual_env():
"""
returns True if you are running inside a python virtual environment.
(DOES NOT WORK IF IN IPYTHON AND USING A VIRTUALENV)
sys.prefix gives the location of the virtualenv
Notes:
It seems IPython does not respect virtual environments properly.
TODO: find a s... | [
"def",
"in_virtual_env",
"(",
")",
":",
"import",
"sys",
"has_venv",
"=",
"False",
"if",
"hasattr",
"(",
"sys",
",",
"'real_prefix'",
")",
":",
"# For virtualenv module",
"has_venv",
"=",
"True",
"elif",
"hasattr",
"(",
"sys",
",",
"'base_prefix'",
")",
":",... | returns True if you are running inside a python virtual environment.
(DOES NOT WORK IF IN IPYTHON AND USING A VIRTUALENV)
sys.prefix gives the location of the virtualenv
Notes:
It seems IPython does not respect virtual environments properly.
TODO: find a solution
http://stackoverfl... | [
"returns",
"True",
"if",
"you",
"are",
"running",
"inside",
"a",
"python",
"virtual",
"environment",
".",
"(",
"DOES",
"NOT",
"WORK",
"IF",
"IN",
"IPYTHON",
"AND",
"USING",
"A",
"VIRTUALENV",
")"
] | python | train | 30.411765 |
jalanb/pysyte | pysyte/getch.py | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/getch.py#L282-L292 | def get_string():
"""A better str(_get_keycodes()) method"""
keycodes = _get_keycodes()
initial_code, codes = keycodes[0], keycodes[1:]
initial_char = chr(initial_code)
if initial_code == 27:
initial_char = '\\e'
elif not ascii.isgraph(initial_char):
initial_char = '\\x%x' % init... | [
"def",
"get_string",
"(",
")",
":",
"keycodes",
"=",
"_get_keycodes",
"(",
")",
"initial_code",
",",
"codes",
"=",
"keycodes",
"[",
"0",
"]",
",",
"keycodes",
"[",
"1",
":",
"]",
"initial_char",
"=",
"chr",
"(",
"initial_code",
")",
"if",
"initial_code",... | A better str(_get_keycodes()) method | [
"A",
"better",
"str",
"(",
"_get_keycodes",
"()",
")",
"method"
] | python | train | 36.818182 |
google/grr | grr/core/grr_response_core/lib/fingerprint.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/fingerprint.py#L65-L98 | def ConsumeRange(self, start, end):
"""Consumes an entire range, or part thereof.
If the finger has no ranges left, or the curent range start is higher
than the end of the consumed block, nothing happens. Otherwise,
the current range is adjusted for the consumed block, or removed,
if the entire blo... | [
"def",
"ConsumeRange",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"old",
"=",
"self",
".",
"CurrentRange",
"(",
")",
"if",
"old",
"is",
"None",
":",
"return",
"if",
"old",
".",
"start",
">",
"start",
":",
"if",
"old",
".",
"start",
"<",
"en... | Consumes an entire range, or part thereof.
If the finger has no ranges left, or the curent range start is higher
than the end of the consumed block, nothing happens. Otherwise,
the current range is adjusted for the consumed block, or removed,
if the entire block is consumed. For things to work, the con... | [
"Consumes",
"an",
"entire",
"range",
"or",
"part",
"thereof",
"."
] | python | train | 36.911765 |
siznax/wptools | wptools/page.py | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L607-L643 | def get_query(self, show=True, proxy=None, timeout=0):
"""
GET MediaWiki:API action=query selected data
https://en.wikipedia.org/w/api.php?action=help&modules=query
Required {params}: title OR pageid
- title: <str> article title
- pageid: <int> Wikipedia database ID
... | [
"def",
"get_query",
"(",
"self",
",",
"show",
"=",
"True",
",",
"proxy",
"=",
"None",
",",
"timeout",
"=",
"0",
")",
":",
"if",
"not",
"self",
".",
"params",
".",
"get",
"(",
"'title'",
")",
"and",
"not",
"self",
".",
"params",
".",
"get",
"(",
... | GET MediaWiki:API action=query selected data
https://en.wikipedia.org/w/api.php?action=help&modules=query
Required {params}: title OR pageid
- title: <str> article title
- pageid: <int> Wikipedia database ID
Optional arguments:
- [show]: <bool> echo page data if true
... | [
"GET",
"MediaWiki",
":",
"API",
"action",
"=",
"query",
"selected",
"data",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"w",
"/",
"api",
".",
"php?action",
"=",
"help&modules",
"=",
"query"
] | python | train | 39.972973 |
incuna/django-orderable | orderable/models.py | https://github.com/incuna/django-orderable/blob/88da9c762ef0500725f95988c8f18d9b304e6951/orderable/models.py#L73-L84 | def _update(qs):
"""
Increment the sort_order in a queryset.
Handle IntegrityErrors caused by unique constraints.
"""
try:
with transaction.atomic():
qs.update(sort_order=models.F('sort_order') + 1)
except IntegrityError:
for obj i... | [
"def",
"_update",
"(",
"qs",
")",
":",
"try",
":",
"with",
"transaction",
".",
"atomic",
"(",
")",
":",
"qs",
".",
"update",
"(",
"sort_order",
"=",
"models",
".",
"F",
"(",
"'sort_order'",
")",
"+",
"1",
")",
"except",
"IntegrityError",
":",
"for",
... | Increment the sort_order in a queryset.
Handle IntegrityErrors caused by unique constraints. | [
"Increment",
"the",
"sort_order",
"in",
"a",
"queryset",
"."
] | python | train | 35.083333 |
DreamLab/VmShepherd | src/vmshepherd/iaas/openstack_driver.py | https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/iaas/openstack_driver.py#L30-L52 | def initialize_openstack(func):
'''
Initialize and refresh openstack connection
'''
async def wrap(self, *args, **kwargs):
if not hasattr(self, 'auth') or not self.auth.is_token_valid():
self.auth = AuthPassword(auth_url=self.config['auth_url'],
... | [
"def",
"initialize_openstack",
"(",
"func",
")",
":",
"async",
"def",
"wrap",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'auth'",
")",
"or",
"not",
"self",
".",
"auth",
".",
"is_toke... | Initialize and refresh openstack connection | [
"Initialize",
"and",
"refresh",
"openstack",
"connection"
] | python | train | 54.26087 |
ranaroussi/qtpylib | qtpylib/asynctools.py | https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/asynctools.py#L179-L189 | def run(self):
"""Start the recurring task."""
if self.init_sec:
sleep(self.init_sec)
self._functime = time()
while self._running:
start = time()
self._func()
self._functime += self.interval_sec
if self._functime - start > 0:
... | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"init_sec",
":",
"sleep",
"(",
"self",
".",
"init_sec",
")",
"self",
".",
"_functime",
"=",
"time",
"(",
")",
"while",
"self",
".",
"_running",
":",
"start",
"=",
"time",
"(",
")",
"self",
"... | Start the recurring task. | [
"Start",
"the",
"recurring",
"task",
"."
] | python | train | 32.090909 |
serkanyersen/underscore.py | src/underscore.py | https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L1367-L1377 | def uniqueId(self, prefix=""):
"""
Generate a unique integer id (unique within the entire client session).
Useful for temporary DOM ids.
"""
_IdCounter.count += 1
id = _IdCounter.count
if prefix:
return self._wrap(prefix + str(id))
else:
... | [
"def",
"uniqueId",
"(",
"self",
",",
"prefix",
"=",
"\"\"",
")",
":",
"_IdCounter",
".",
"count",
"+=",
"1",
"id",
"=",
"_IdCounter",
".",
"count",
"if",
"prefix",
":",
"return",
"self",
".",
"_wrap",
"(",
"prefix",
"+",
"str",
"(",
"id",
")",
")",... | Generate a unique integer id (unique within the entire client session).
Useful for temporary DOM ids. | [
"Generate",
"a",
"unique",
"integer",
"id",
"(",
"unique",
"within",
"the",
"entire",
"client",
"session",
")",
".",
"Useful",
"for",
"temporary",
"DOM",
"ids",
"."
] | python | train | 30.636364 |
LonamiWebs/Telethon | telethon_generator/generators/tlobject.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/tlobject.py#L410-L527 | def _write_arg_to_bytes(builder, arg, args, name=None):
"""
Writes the .__bytes__() code for the given argument
:param builder: The source code builder
:param arg: The argument to write
:param args: All the other arguments in TLObject same __bytes__.
This is required to determine th... | [
"def",
"_write_arg_to_bytes",
"(",
"builder",
",",
"arg",
",",
"args",
",",
"name",
"=",
"None",
")",
":",
"if",
"arg",
".",
"generic_definition",
":",
"return",
"# Do nothing, this only specifies a later type",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"'... | Writes the .__bytes__() code for the given argument
:param builder: The source code builder
:param arg: The argument to write
:param args: All the other arguments in TLObject same __bytes__.
This is required to determine the flags value
:param name: The name of the argument. Defaults to... | [
"Writes",
"the",
".",
"__bytes__",
"()",
"code",
"for",
"the",
"given",
"argument",
":",
"param",
"builder",
":",
"The",
"source",
"code",
"builder",
":",
"param",
"arg",
":",
"The",
"argument",
"to",
"write",
":",
"param",
"args",
":",
"All",
"the",
"... | python | train | 36.211864 |
anchore/anchore | anchore/cli/common.py | https://github.com/anchore/anchore/blob/8a4d5b9708e27856312d303aae3f04f3c72039d6/anchore/cli/common.py#L14-L49 | def extended_help_option(extended_help=None, *param_decls, **attrs):
"""
Based on the click.help_option code.
Adds a ``--extended-help`` option which immediately ends the program
printing out the extended extended-help page. Defaults to using the
callback's doc string, but can be given an explicit ... | [
"def",
"extended_help_option",
"(",
"extended_help",
"=",
"None",
",",
"*",
"param_decls",
",",
"*",
"*",
"attrs",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"def",
"callback",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"value",
"... | Based on the click.help_option code.
Adds a ``--extended-help`` option which immediately ends the program
printing out the extended extended-help page. Defaults to using the
callback's doc string, but can be given an explicit value as well.
This is intended for use as a decorator on a command to provi... | [
"Based",
"on",
"the",
"click",
".",
"help_option",
"code",
"."
] | python | train | 40.75 |
nerdvegas/rez | src/rez/vendor/pygraph/algorithms/cycles.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/cycles.py#L38-L108 | def find_cycle(graph):
"""
Find a cycle in the given graph.
This function will return a list of nodes which form a cycle in the graph or an empty list if
no cycle exists.
@type graph: graph, digraph
@param graph: Graph.
@rtype: list
@return: List of nodes.
"""
... | [
"def",
"find_cycle",
"(",
"graph",
")",
":",
"if",
"(",
"isinstance",
"(",
"graph",
",",
"graph_class",
")",
")",
":",
"directed",
"=",
"False",
"elif",
"(",
"isinstance",
"(",
"graph",
",",
"digraph_class",
")",
")",
":",
"directed",
"=",
"True",
"els... | Find a cycle in the given graph.
This function will return a list of nodes which form a cycle in the graph or an empty list if
no cycle exists.
@type graph: graph, digraph
@param graph: Graph.
@rtype: list
@return: List of nodes. | [
"Find",
"a",
"cycle",
"in",
"the",
"given",
"graph",
".",
"This",
"function",
"will",
"return",
"a",
"list",
"of",
"nodes",
"which",
"form",
"a",
"cycle",
"in",
"the",
"graph",
"or",
"an",
"empty",
"list",
"if",
"no",
"cycle",
"exists",
"."
] | python | train | 27.28169 |
markuskiller/textblob-de | textblob_de/ext/_pattern/text/tree.py | https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/tree.py#L1440-L1487 | def parse_string(xml):
""" Returns a slash-formatted string from the given XML representation.
The return value is a TokenString (for MBSP) or TaggedString (for Pattern).
"""
string = ""
# Traverse all the <sentence> elements in the XML.
dom = XML(xml)
for sentence in dom(XML_SENTENCE):
... | [
"def",
"parse_string",
"(",
"xml",
")",
":",
"string",
"=",
"\"\"",
"# Traverse all the <sentence> elements in the XML.",
"dom",
"=",
"XML",
"(",
"xml",
")",
"for",
"sentence",
"in",
"dom",
"(",
"XML_SENTENCE",
")",
":",
"_anchors",
".",
"clear",
"(",
")",
"... | Returns a slash-formatted string from the given XML representation.
The return value is a TokenString (for MBSP) or TaggedString (for Pattern). | [
"Returns",
"a",
"slash",
"-",
"formatted",
"string",
"from",
"the",
"given",
"XML",
"representation",
".",
"The",
"return",
"value",
"is",
"a",
"TokenString",
"(",
"for",
"MBSP",
")",
"or",
"TaggedString",
"(",
"for",
"Pattern",
")",
"."
] | python | train | 52.375 |
tensorlayer/tensorlayer | tensorlayer/logging/tl_logging.py | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/logging/tl_logging.py#L148-L160 | def _GetNextLogCountPerToken(token):
"""Wrapper for _log_counter_per_token.
Args:
token: The token for which to look up the count.
Returns:
The number of times this function has been called with
*token* as an argument (starting at 0)
"""
global _log_counter_per_token # pylint: disable... | [
"def",
"_GetNextLogCountPerToken",
"(",
"token",
")",
":",
"global",
"_log_counter_per_token",
"# pylint: disable=global-variable-not-assigned",
"_log_counter_per_token",
"[",
"token",
"]",
"=",
"1",
"+",
"_log_counter_per_token",
".",
"get",
"(",
"token",
",",
"-",
"1"... | Wrapper for _log_counter_per_token.
Args:
token: The token for which to look up the count.
Returns:
The number of times this function has been called with
*token* as an argument (starting at 0) | [
"Wrapper",
"for",
"_log_counter_per_token",
"."
] | python | valid | 35.076923 |
pavlin-policar/openTSNE | openTSNE/affinity.py | https://github.com/pavlin-policar/openTSNE/blob/28513a0d669f2f20e7b971c0c6373dc375f72771/openTSNE/affinity.py#L139-L178 | def set_perplexity(self, new_perplexity):
"""Change the perplexity of the affinity matrix.
Note that we only allow lowering the perplexity or restoring it to its
original value. This restriction exists because setting a higher
perplexity value requires recomputing all the nearest neighb... | [
"def",
"set_perplexity",
"(",
"self",
",",
"new_perplexity",
")",
":",
"# If the value hasn't changed, there's nothing to do",
"if",
"new_perplexity",
"==",
"self",
".",
"perplexity",
":",
"return",
"# Verify that the perplexity isn't too large",
"new_perplexity",
"=",
"self"... | Change the perplexity of the affinity matrix.
Note that we only allow lowering the perplexity or restoring it to its
original value. This restriction exists because setting a higher
perplexity value requires recomputing all the nearest neighbors, which
can take a long time. To avoid pot... | [
"Change",
"the",
"perplexity",
"of",
"the",
"affinity",
"matrix",
"."
] | python | train | 42.7 |
danielperna84/pyhomematic | pyhomematic/devicetypes/generic.py | https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/generic.py#L199-L211 | def getValue(self, key):
"""
Some devices allow to directly get values for specific parameters.
"""
LOG.debug("HMGeneric.getValue: address = '%s', key = '%s'" % (self._ADDRESS, key))
try:
returnvalue = self._proxy.getValue(self._ADDRESS, key)
self._VALUES[... | [
"def",
"getValue",
"(",
"self",
",",
"key",
")",
":",
"LOG",
".",
"debug",
"(",
"\"HMGeneric.getValue: address = '%s', key = '%s'\"",
"%",
"(",
"self",
".",
"_ADDRESS",
",",
"key",
")",
")",
"try",
":",
"returnvalue",
"=",
"self",
".",
"_proxy",
".",
"getV... | Some devices allow to directly get values for specific parameters. | [
"Some",
"devices",
"allow",
"to",
"directly",
"get",
"values",
"for",
"specific",
"parameters",
"."
] | python | train | 41.076923 |
liminspace/dju-common | dju_common/validators.py | https://github.com/liminspace/dju-common/blob/c68860bb84d454a35e66275841c20f38375c2135/dju_common/validators.py#L6-L14 | def validate_email_domain(email):
""" Validates email domain by blacklist. """
try:
domain = email.split('@', 1)[1].lower().strip()
except IndexError:
return
if domain in dju_settings.DJU_EMAIL_DOMAIN_BLACK_LIST:
raise ValidationError(_(u'Email with domain "%(domain)s" is disallo... | [
"def",
"validate_email_domain",
"(",
"email",
")",
":",
"try",
":",
"domain",
"=",
"email",
".",
"split",
"(",
"'@'",
",",
"1",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"except",
"IndexError",
":",
"return",
"if",
"domain... | Validates email domain by blacklist. | [
"Validates",
"email",
"domain",
"by",
"blacklist",
"."
] | python | train | 44.222222 |
orb-framework/orb | orb/core/schema.py | https://github.com/orb-framework/orb/blob/575be2689cb269e65a0a2678232ff940acc19e5a/orb/core/schema.py#L478-L487 | def setCollectors(self, collectors):
"""
Sets the collector methods that will be used for this schema.
:param collectors | [<orb.Collectors>, ..]
"""
self.__collectors = {}
for name, collector in collectors.items():
self.__collectors[name] = coll... | [
"def",
"setCollectors",
"(",
"self",
",",
"collectors",
")",
":",
"self",
".",
"__collectors",
"=",
"{",
"}",
"for",
"name",
",",
"collector",
"in",
"collectors",
".",
"items",
"(",
")",
":",
"self",
".",
"__collectors",
"[",
"name",
"]",
"=",
"collect... | Sets the collector methods that will be used for this schema.
:param collectors | [<orb.Collectors>, ..] | [
"Sets",
"the",
"collector",
"methods",
"that",
"will",
"be",
"used",
"for",
"this",
"schema",
".",
":",
"param",
"collectors",
"|",
"[",
"<orb",
".",
"Collectors",
">",
"..",
"]"
] | python | train | 35.4 |
JoseAntFer/pyny3d | pyny3d/geoms.py | https://github.com/JoseAntFer/pyny3d/blob/fb81684935a24f7e50c975cb4383c81a63ab56df/pyny3d/geoms.py#L804-L816 | def get_domain(self):
"""
:returns: opposite vertices of the bounding prism for this
object in the form of ndarray([min], [max])
.. note:: This method automatically stores the solution in order
to do not repeat calculations if the user needs to call it
... | [
"def",
"get_domain",
"(",
"self",
")",
":",
"points",
"=",
"(",
"[",
"poly",
".",
"points",
"for",
"poly",
"in",
"self",
"]",
"+",
"[",
"holes",
".",
"points",
"for",
"holes",
"in",
"self",
".",
"holes",
"]",
")",
"points",
"=",
"np",
".",
"conca... | :returns: opposite vertices of the bounding prism for this
object in the form of ndarray([min], [max])
.. note:: This method automatically stores the solution in order
to do not repeat calculations if the user needs to call it
more than once. | [
":",
"returns",
":",
"opposite",
"vertices",
"of",
"the",
"bounding",
"prism",
"for",
"this",
"object",
"in",
"the",
"form",
"of",
"ndarray",
"(",
"[",
"min",
"]",
"[",
"max",
"]",
")",
"..",
"note",
"::",
"This",
"method",
"automatically",
"stores",
"... | python | train | 44.076923 |
tensorflow/cleverhans | cleverhans/attacks/bapp.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L358-L364 | def compute_distance(x_ori, x_pert, constraint='l2'):
""" Compute the distance between two images. """
if constraint == 'l2':
dist = np.linalg.norm(x_ori - x_pert)
elif constraint == 'linf':
dist = np.max(abs(x_ori - x_pert))
return dist | [
"def",
"compute_distance",
"(",
"x_ori",
",",
"x_pert",
",",
"constraint",
"=",
"'l2'",
")",
":",
"if",
"constraint",
"==",
"'l2'",
":",
"dist",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"x_ori",
"-",
"x_pert",
")",
"elif",
"constraint",
"==",
"'linf... | Compute the distance between two images. | [
"Compute",
"the",
"distance",
"between",
"two",
"images",
"."
] | python | train | 35.285714 |
brutasse/graphite-api | graphite_api/functions.py | https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L2544-L2551 | def sortByTotal(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Sorts the list of metrics by the sum of values across the time period
specified.
"""
return list(sorted(seriesList, key=safeSum, reverse=True)) | [
"def",
"sortByTotal",
"(",
"requestContext",
",",
"seriesList",
")",
":",
"return",
"list",
"(",
"sorted",
"(",
"seriesList",
",",
"key",
"=",
"safeSum",
",",
"reverse",
"=",
"True",
")",
")"
] | Takes one metric or a wildcard seriesList.
Sorts the list of metrics by the sum of values across the time period
specified. | [
"Takes",
"one",
"metric",
"or",
"a",
"wildcard",
"seriesList",
"."
] | python | train | 31.625 |
quodlibet/mutagen | mutagen/_util.py | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L661-L683 | def seek_end(fileobj, offset):
"""Like fileobj.seek(-offset, 2), but will not try to go beyond the start
Needed since file objects from BytesIO will not raise IOError and
file objects from open() will raise IOError if going to a negative offset.
To make things easier for custom implementations, instead... | [
"def",
"seek_end",
"(",
"fileobj",
",",
"offset",
")",
":",
"if",
"offset",
"<",
"0",
":",
"raise",
"ValueError",
"if",
"get_size",
"(",
"fileobj",
")",
"<",
"offset",
":",
"fileobj",
".",
"seek",
"(",
"0",
",",
"0",
")",
"else",
":",
"fileobj",
".... | Like fileobj.seek(-offset, 2), but will not try to go beyond the start
Needed since file objects from BytesIO will not raise IOError and
file objects from open() will raise IOError if going to a negative offset.
To make things easier for custom implementations, instead of allowing
both behaviors, we ju... | [
"Like",
"fileobj",
".",
"seek",
"(",
"-",
"offset",
"2",
")",
"but",
"will",
"not",
"try",
"to",
"go",
"beyond",
"the",
"start"
] | python | train | 28.347826 |
lpantano/seqcluster | seqcluster/function/coral.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/function/coral.py#L18-L29 | def prepare_bam(bam_in, precursors):
"""
Clean BAM file to keep only position inside the bigger cluster
"""
# use pybedtools to keep valid positions
# intersect option with -b bigger_cluster_loci
a = pybedtools.BedTool(bam_in)
b = pybedtools.BedTool(precursors)
c = a.intersect(b, u=True)... | [
"def",
"prepare_bam",
"(",
"bam_in",
",",
"precursors",
")",
":",
"# use pybedtools to keep valid positions",
"# intersect option with -b bigger_cluster_loci",
"a",
"=",
"pybedtools",
".",
"BedTool",
"(",
"bam_in",
")",
"b",
"=",
"pybedtools",
".",
"BedTool",
"(",
"pr... | Clean BAM file to keep only position inside the bigger cluster | [
"Clean",
"BAM",
"file",
"to",
"keep",
"only",
"position",
"inside",
"the",
"bigger",
"cluster"
] | python | train | 36.5 |
hubo1016/vlcp | vlcp/utils/flowupdater.py | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/utils/flowupdater.py#L167-L248 | async def main(self):
"""
Main coroutine
"""
try:
lastkeys = set()
dataupdate = FlowUpdaterNotification.createMatcher(self, FlowUpdaterNotification.DATAUPDATED)
startwalk = FlowUpdaterNotification.createMatcher(self, FlowUpdaterNotification.STARTWALK)
... | [
"async",
"def",
"main",
"(",
"self",
")",
":",
"try",
":",
"lastkeys",
"=",
"set",
"(",
")",
"dataupdate",
"=",
"FlowUpdaterNotification",
".",
"createMatcher",
"(",
"self",
",",
"FlowUpdaterNotification",
".",
"DATAUPDATED",
")",
"startwalk",
"=",
"FlowUpdate... | Main coroutine | [
"Main",
"coroutine"
] | python | train | 57.134146 |
constverum/ProxyBroker | proxybroker/providers.py | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/providers.py#L70-L86 | async def get_proxies(self):
"""Receive proxies from the provider and return them.
:return: :attr:`.proxies`
"""
log.debug('Try to get proxies from %s' % self.domain)
async with aiohttp.ClientSession(
headers=get_headers(), cookies=self._cookies, loop=self._loop
... | [
"async",
"def",
"get_proxies",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"'Try to get proxies from %s'",
"%",
"self",
".",
"domain",
")",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
"headers",
"=",
"get_headers",
"(",
")",
",",
"cookies",
... | Receive proxies from the provider and return them.
:return: :attr:`.proxies` | [
"Receive",
"proxies",
"from",
"the",
"provider",
"and",
"return",
"them",
"."
] | python | train | 30.823529 |
GochoMugo/firecall | firecall/sync.py | https://github.com/GochoMugo/firecall/blob/6b99ff72b3c056f51a5901f2be32030c7e68961a/firecall/sync.py#L119-L130 | def catch_error(response):
'''
Checks for Errors in a Response.
401 or 403 - Security Rules Violation.
404 or 417 - Firebase NOT Found.
response - (Request.Response) - response from a request.
'''
status = response.status_code
if status == 401 or status ==... | [
"def",
"catch_error",
"(",
"response",
")",
":",
"status",
"=",
"response",
".",
"status_code",
"if",
"status",
"==",
"401",
"or",
"status",
"==",
"403",
":",
"raise",
"EnvironmentError",
"(",
"\"Forbidden\"",
")",
"elif",
"status",
"==",
"417",
"or",
"sta... | Checks for Errors in a Response.
401 or 403 - Security Rules Violation.
404 or 417 - Firebase NOT Found.
response - (Request.Response) - response from a request. | [
"Checks",
"for",
"Errors",
"in",
"a",
"Response",
".",
"401",
"or",
"403",
"-",
"Security",
"Rules",
"Violation",
".",
"404",
"or",
"417",
"-",
"Firebase",
"NOT",
"Found",
".",
"response",
"-",
"(",
"Request",
".",
"Response",
")",
"-",
"response",
"fr... | python | valid | 37.833333 |
phaethon/kamene | kamene/contrib/gsm_um.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L1283-L1290 | def extendedMeasurementOrder():
"""EXTENDED MEASUREMENT ORDER Section 9.1.51"""
a = L2PseudoLength(l2pLength=0x12)
b = TpPd(pd=0x6)
c = MessageType(mesType=0x37) # 00110111
d = ExtendedMeasurementFrequencyList()
packet = a / b / c / d
return packet | [
"def",
"extendedMeasurementOrder",
"(",
")",
":",
"a",
"=",
"L2PseudoLength",
"(",
"l2pLength",
"=",
"0x12",
")",
"b",
"=",
"TpPd",
"(",
"pd",
"=",
"0x6",
")",
"c",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x37",
")",
"# 00110111",
"d",
"=",
"Extended... | EXTENDED MEASUREMENT ORDER Section 9.1.51 | [
"EXTENDED",
"MEASUREMENT",
"ORDER",
"Section",
"9",
".",
"1",
".",
"51"
] | python | train | 33.75 |
invisibleroads/socketIO-client | socketIO_client/namespaces.py | https://github.com/invisibleroads/socketIO-client/blob/1e58adda9397500d89b4521c90aa06e6a511cef6/socketIO_client/namespaces.py#L27-L33 | def off(self, event):
'Remove an event handler'
try:
self._once_events.remove(event)
except KeyError:
pass
self._callback_by_event.pop(event, None) | [
"def",
"off",
"(",
"self",
",",
"event",
")",
":",
"try",
":",
"self",
".",
"_once_events",
".",
"remove",
"(",
"event",
")",
"except",
"KeyError",
":",
"pass",
"self",
".",
"_callback_by_event",
".",
"pop",
"(",
"event",
",",
"None",
")"
] | Remove an event handler | [
"Remove",
"an",
"event",
"handler"
] | python | train | 28.142857 |
kkroening/ffmpeg-python | ffmpeg/_run.py | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_run.py#L158-L173 | def compile(stream_spec, cmd='ffmpeg', overwrite_output=False):
"""Build command-line for invoking ffmpeg.
The :meth:`run` function uses this to build the commnad line
arguments and should work in most cases, but calling this function
directly is useful for debugging or if you need to invoke ffmpeg
... | [
"def",
"compile",
"(",
"stream_spec",
",",
"cmd",
"=",
"'ffmpeg'",
",",
"overwrite_output",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"cmd",
",",
"basestring",
")",
":",
"cmd",
"=",
"[",
"cmd",
"]",
"elif",
"type",
"(",
"cmd",
")",
"!=",
"list... | Build command-line for invoking ffmpeg.
The :meth:`run` function uses this to build the commnad line
arguments and should work in most cases, but calling this function
directly is useful for debugging or if you need to invoke ffmpeg
manually for whatever reason.
This is the same as calling :meth:`... | [
"Build",
"command",
"-",
"line",
"for",
"invoking",
"ffmpeg",
"."
] | python | train | 40.875 |
Fizzadar/pyinfra | pyinfra/modules/server.py | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/server.py#L99-L121 | def modprobe(state, host, name, present=True, force=False):
'''
Load/unload kernel modules.
+ name: name of the module to manage
+ present: whether the module should be loaded or not
+ force: whether to force any add/remove modules
'''
modules = host.fact.kernel_modules
is_present = na... | [
"def",
"modprobe",
"(",
"state",
",",
"host",
",",
"name",
",",
"present",
"=",
"True",
",",
"force",
"=",
"False",
")",
":",
"modules",
"=",
"host",
".",
"fact",
".",
"kernel_modules",
"is_present",
"=",
"name",
"in",
"modules",
"args",
"=",
"''",
"... | Load/unload kernel modules.
+ name: name of the module to manage
+ present: whether the module should be loaded or not
+ force: whether to force any add/remove modules | [
"Load",
"/",
"unload",
"kernel",
"modules",
"."
] | python | train | 27.26087 |
hotdoc/hotdoc | hotdoc/parsers/sitemap.py | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/sitemap.py#L77-L87 | def walk(self, action, user_data=None):
"""
Walk the hierarchy, applying action to each filename.
Args:
action: callable, the callable to invoke for each filename,
will be invoked with the filename, the subfiles, and
the level in the sitemap.
... | [
"def",
"walk",
"(",
"self",
",",
"action",
",",
"user_data",
"=",
"None",
")",
":",
"action",
"(",
"self",
".",
"index_file",
",",
"self",
".",
"__root",
",",
"0",
",",
"user_data",
")",
"self",
".",
"__do_walk",
"(",
"self",
".",
"__root",
",",
"1... | Walk the hierarchy, applying action to each filename.
Args:
action: callable, the callable to invoke for each filename,
will be invoked with the filename, the subfiles, and
the level in the sitemap. | [
"Walk",
"the",
"hierarchy",
"applying",
"action",
"to",
"each",
"filename",
"."
] | python | train | 39.090909 |
romanz/trezor-agent | libagent/gpg/keyring.py | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L191-L197 | def get_gnupg_components(sp=subprocess):
"""Parse GnuPG components' paths."""
args = [util.which('gpgconf'), '--list-components']
output = check_output(args=args, sp=sp)
components = dict(re.findall('(.*):.*:(.*)', output.decode('utf-8')))
log.debug('gpgconf --list-components: %s', components)
r... | [
"def",
"get_gnupg_components",
"(",
"sp",
"=",
"subprocess",
")",
":",
"args",
"=",
"[",
"util",
".",
"which",
"(",
"'gpgconf'",
")",
",",
"'--list-components'",
"]",
"output",
"=",
"check_output",
"(",
"args",
"=",
"args",
",",
"sp",
"=",
"sp",
")",
"... | Parse GnuPG components' paths. | [
"Parse",
"GnuPG",
"components",
"paths",
"."
] | python | train | 47.142857 |
erget/StereoVision | stereovision/blockmatchers.py | https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L82-L87 | def load_settings(self, settings):
"""Load settings from file"""
with open(settings) as settings_file:
settings_dict = simplejson.load(settings_file)
for key, value in settings_dict.items():
self.__setattr__(key, value) | [
"def",
"load_settings",
"(",
"self",
",",
"settings",
")",
":",
"with",
"open",
"(",
"settings",
")",
"as",
"settings_file",
":",
"settings_dict",
"=",
"simplejson",
".",
"load",
"(",
"settings_file",
")",
"for",
"key",
",",
"value",
"in",
"settings_dict",
... | Load settings from file | [
"Load",
"settings",
"from",
"file"
] | python | train | 43.666667 |
Netflix-Skunkworks/historical | historical/common/dynamodb.py | https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/dynamodb.py#L146-L165 | def get_full_durable_object(arn, event_time, durable_model):
"""
Utility method to fetch items from the Durable table if they are too big for SNS/SQS.
:param record:
:param durable_model:
:return:
"""
LOG.debug(f'[-->] Item with ARN: {arn} was too big for SNS -- fetching it from the Durable... | [
"def",
"get_full_durable_object",
"(",
"arn",
",",
"event_time",
",",
"durable_model",
")",
":",
"LOG",
".",
"debug",
"(",
"f'[-->] Item with ARN: {arn} was too big for SNS -- fetching it from the Durable table...'",
")",
"item",
"=",
"list",
"(",
"durable_model",
".",
"q... | Utility method to fetch items from the Durable table if they are too big for SNS/SQS.
:param record:
:param durable_model:
:return: | [
"Utility",
"method",
"to",
"fetch",
"items",
"from",
"the",
"Durable",
"table",
"if",
"they",
"are",
"too",
"big",
"for",
"SNS",
"/",
"SQS",
"."
] | python | train | 45.15 |
proycon/pynlpl | pynlpl/textprocessors.py | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/textprocessors.py#L444-L455 | def find_keyword_in_context(tokens, keyword, contextsize=1):
"""Find a keyword in a particular sequence of tokens, and return the local context. Contextsize is the number of words to the left and right. The keyword may have multiple word, in which case it should to passed as a tuple or list"""
if isinstance(key... | [
"def",
"find_keyword_in_context",
"(",
"tokens",
",",
"keyword",
",",
"contextsize",
"=",
"1",
")",
":",
"if",
"isinstance",
"(",
"keyword",
",",
"tuple",
")",
"and",
"isinstance",
"(",
"keyword",
",",
"list",
")",
":",
"l",
"=",
"len",
"(",
"keyword",
... | Find a keyword in a particular sequence of tokens, and return the local context. Contextsize is the number of words to the left and right. The keyword may have multiple word, in which case it should to passed as a tuple or list | [
"Find",
"a",
"keyword",
"in",
"a",
"particular",
"sequence",
"of",
"tokens",
"and",
"return",
"the",
"local",
"context",
".",
"Contextsize",
"is",
"the",
"number",
"of",
"words",
"to",
"the",
"left",
"and",
"right",
".",
"The",
"keyword",
"may",
"have",
... | python | train | 55.5 |
HPCC-Cloud-Computing/CAL | calplus/v1/compute/drivers/openstack.py | https://github.com/HPCC-Cloud-Computing/CAL/blob/7134b3dfe9ee3a383506a592765c7a12fa4ca1e9/calplus/v1/compute/drivers/openstack.py#L119-L122 | def delete_nic(self, instance_id, port_id):
"""Delete a Network Interface Controller"""
self.client.servers.interface_detach(instance_id, port_id)
return True | [
"def",
"delete_nic",
"(",
"self",
",",
"instance_id",
",",
"port_id",
")",
":",
"self",
".",
"client",
".",
"servers",
".",
"interface_detach",
"(",
"instance_id",
",",
"port_id",
")",
"return",
"True"
] | Delete a Network Interface Controller | [
"Delete",
"a",
"Network",
"Interface",
"Controller"
] | python | train | 44.75 |
ndrlslz/ternya | ternya/ternya.py | https://github.com/ndrlslz/ternya/blob/c05aec10029e645d63ff04313dbcf2644743481f/ternya/ternya.py#L165-L183 | def init_glance_consumer(self, mq):
"""
Init openstack glance mq
1. Check if enable listening glance notification
2. Create consumer
:param mq: class ternya.mq.MQ
"""
if not self.enable_component_notification(Openstack.Glance):
log.debug("disable lis... | [
"def",
"init_glance_consumer",
"(",
"self",
",",
"mq",
")",
":",
"if",
"not",
"self",
".",
"enable_component_notification",
"(",
"Openstack",
".",
"Glance",
")",
":",
"log",
".",
"debug",
"(",
"\"disable listening glance notification\"",
")",
"return",
"for",
"i... | Init openstack glance mq
1. Check if enable listening glance notification
2. Create consumer
:param mq: class ternya.mq.MQ | [
"Init",
"openstack",
"glance",
"mq"
] | python | test | 35.684211 |
pandas-dev/pandas | pandas/core/indexes/datetimes.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimes.py#L35-L51 | def _new_DatetimeIndex(cls, d):
""" This is called upon unpickling, rather than the default which doesn't
have arguments and breaks __new__ """
if "data" in d and not isinstance(d["data"], DatetimeIndex):
# Avoid need to verify integrity by calling simple_new directly
data = d.pop("data")
... | [
"def",
"_new_DatetimeIndex",
"(",
"cls",
",",
"d",
")",
":",
"if",
"\"data\"",
"in",
"d",
"and",
"not",
"isinstance",
"(",
"d",
"[",
"\"data\"",
"]",
",",
"DatetimeIndex",
")",
":",
"# Avoid need to verify integrity by calling simple_new directly",
"data",
"=",
... | This is called upon unpickling, rather than the default which doesn't
have arguments and breaks __new__ | [
"This",
"is",
"called",
"upon",
"unpickling",
"rather",
"than",
"the",
"default",
"which",
"doesn",
"t",
"have",
"arguments",
"and",
"breaks",
"__new__"
] | python | train | 42.235294 |
crdoconnor/pathquery | hitch/key.py | https://github.com/crdoconnor/pathquery/blob/4905fef27fc666ea4511eb0eee5098f754bb52ed/hitch/key.py#L291-L302 | def regression():
"""
Run regression testing - lint and then run all tests.
"""
# HACK: Start using hitchbuildpy to get around this.
Command("touch", DIR.project.joinpath("pathquery", "__init__.py").abspath()).run()
storybook = _storybook({}).only_uninherited()
#storybook.with_params(**{"pyt... | [
"def",
"regression",
"(",
")",
":",
"# HACK: Start using hitchbuildpy to get around this.",
"Command",
"(",
"\"touch\"",
",",
"DIR",
".",
"project",
".",
"joinpath",
"(",
"\"pathquery\"",
",",
"\"__init__.py\"",
")",
".",
"abspath",
"(",
")",
")",
".",
"run",
"(... | Run regression testing - lint and then run all tests. | [
"Run",
"regression",
"testing",
"-",
"lint",
"and",
"then",
"run",
"all",
"tests",
"."
] | python | train | 46.166667 |
moonso/vcf_parser | vcf_parser/header_parser.py | https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/header_parser.py#L178-L183 | def parse_header_line(self, line):
"""docstring for parse_header_line"""
self.header = line[1:].rstrip().split('\t')
if len(self.header) < 9:
self.header = line[1:].rstrip().split()
self.individuals = self.header[9:] | [
"def",
"parse_header_line",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"header",
"=",
"line",
"[",
"1",
":",
"]",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
"if",
"len",
"(",
"self",
".",
"header",
")",
"<",
"9",
":",
"self... | docstring for parse_header_line | [
"docstring",
"for",
"parse_header_line"
] | python | train | 42.5 |
jmbhughes/suvi-trainer | suvitrainer/fileio.py | https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/fileio.py#L249-L313 | def fetch_suvi_l1b(self, product, correct=True, median_kernel=5):
"""
Given a product keyword, downloads the SUVI l1b image into the current directory.
NOTE: the suvi_l1b_url must be properly set for the Fetcher object
:param product: the keyword for the product, e.g. suvi-l1b-fe094
... | [
"def",
"fetch_suvi_l1b",
"(",
"self",
",",
"product",
",",
"correct",
"=",
"True",
",",
"median_kernel",
"=",
"5",
")",
":",
"if",
"self",
".",
"date",
"<",
"datetime",
"(",
"2018",
",",
"5",
",",
"23",
")",
"and",
"not",
"(",
"self",
".",
"date",
... | Given a product keyword, downloads the SUVI l1b image into the current directory.
NOTE: the suvi_l1b_url must be properly set for the Fetcher object
:param product: the keyword for the product, e.g. suvi-l1b-fe094
:param correct: remove nans and negatives
:return: tuple of product name, ... | [
"Given",
"a",
"product",
"keyword",
"downloads",
"the",
"SUVI",
"l1b",
"image",
"into",
"the",
"current",
"directory",
".",
"NOTE",
":",
"the",
"suvi_l1b_url",
"must",
"be",
"properly",
"set",
"for",
"the",
"Fetcher",
"object",
":",
"param",
"product",
":",
... | python | train | 43.092308 |
saltstack/salt | salt/modules/win_useradd.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L1025-L1063 | def current(sam=False):
'''
Get the username that salt-minion is running under. If salt-minion is
running as a service it should return the Local System account. If salt is
running from a command prompt it should return the username that started the
command prompt.
.. versionadded:: 2015.5.6
... | [
"def",
"current",
"(",
"sam",
"=",
"False",
")",
":",
"try",
":",
"if",
"sam",
":",
"user_name",
"=",
"win32api",
".",
"GetUserNameEx",
"(",
"win32con",
".",
"NameSamCompatible",
")",
"else",
":",
"user_name",
"=",
"win32api",
".",
"GetUserName",
"(",
")... | Get the username that salt-minion is running under. If salt-minion is
running as a service it should return the Local System account. If salt is
running from a command prompt it should return the username that started the
command prompt.
.. versionadded:: 2015.5.6
Args:
sam (bool, optional... | [
"Get",
"the",
"username",
"that",
"salt",
"-",
"minion",
"is",
"running",
"under",
".",
"If",
"salt",
"-",
"minion",
"is",
"running",
"as",
"a",
"service",
"it",
"should",
"return",
"the",
"Local",
"System",
"account",
".",
"If",
"salt",
"is",
"running",... | python | train | 30.230769 |
bprinty/gems | gems/datatypes.py | https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/datatypes.py#L648-L658 | def json(self):
"""
Return JSON representation of object.
"""
data = {}
for item in self._data:
if isinstance(self._data[item], filetree):
data[item] = self._data[item].json()
else:
data[item] = self._data[item]
retu... | [
"def",
"json",
"(",
"self",
")",
":",
"data",
"=",
"{",
"}",
"for",
"item",
"in",
"self",
".",
"_data",
":",
"if",
"isinstance",
"(",
"self",
".",
"_data",
"[",
"item",
"]",
",",
"filetree",
")",
":",
"data",
"[",
"item",
"]",
"=",
"self",
".",... | Return JSON representation of object. | [
"Return",
"JSON",
"representation",
"of",
"object",
"."
] | python | valid | 28.818182 |
sbg/sevenbridges-python | sevenbridges/transfer/upload.py | https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/transfer/upload.py#L142-L170 | def submit(self):
"""
Partitions the file into chunks and submits them into group of 4
for upload on the api upload pool.
:return: Futures
"""
futures = []
while self.submitted < 4 and not self.done():
part = self.parts.pop(0)
part_number ... | [
"def",
"submit",
"(",
"self",
")",
":",
"futures",
"=",
"[",
"]",
"while",
"self",
".",
"submitted",
"<",
"4",
"and",
"not",
"self",
".",
"done",
"(",
")",
":",
"part",
"=",
"self",
".",
"parts",
".",
"pop",
"(",
"0",
")",
"part_number",
"=",
"... | Partitions the file into chunks and submits them into group of 4
for upload on the api upload pool.
:return: Futures | [
"Partitions",
"the",
"file",
"into",
"chunks",
"and",
"submits",
"them",
"into",
"group",
"of",
"4",
"for",
"upload",
"on",
"the",
"api",
"upload",
"pool",
".",
":",
"return",
":",
"Futures"
] | python | train | 30.758621 |
idlesign/steampak | steampak/libsteam/resources/apps.py | https://github.com/idlesign/steampak/blob/cb3f2c737e272b0360802d947e388df7e34f50f3/steampak/libsteam/resources/apps.py#L73-L90 | def install_dir(self):
"""Returns application installation path.
.. note::
If fails this falls back to a restricted interface, which can only be used by approved apps.
:rtype: str
"""
max_len = 500
directory = self._get_str(self._iface.get_install_dir, [se... | [
"def",
"install_dir",
"(",
"self",
")",
":",
"max_len",
"=",
"500",
"directory",
"=",
"self",
".",
"_get_str",
"(",
"self",
".",
"_iface",
".",
"get_install_dir",
",",
"[",
"self",
".",
"app_id",
"]",
",",
"max_len",
"=",
"max_len",
")",
"if",
"not",
... | Returns application installation path.
.. note::
If fails this falls back to a restricted interface, which can only be used by approved apps.
:rtype: str | [
"Returns",
"application",
"installation",
"path",
"."
] | python | train | 31.777778 |
ejeschke/ginga | ginga/misc/Task.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Task.py#L999-L1048 | def startall(self, wait=False, **kwdargs):
"""Start all of the threads in the thread pool. If _wait_ is True
then don't return until all threads are up and running. Any extra
keyword arguments are passed to the worker thread constructor.
"""
self.logger.debug("startall called")... | [
"def",
"startall",
"(",
"self",
",",
"wait",
"=",
"False",
",",
"*",
"*",
"kwdargs",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"startall called\"",
")",
"with",
"self",
".",
"regcond",
":",
"while",
"self",
".",
"status",
"!=",
"'down'",
... | Start all of the threads in the thread pool. If _wait_ is True
then don't return until all threads are up and running. Any extra
keyword arguments are passed to the worker thread constructor. | [
"Start",
"all",
"of",
"the",
"threads",
"in",
"the",
"thread",
"pool",
".",
"If",
"_wait_",
"is",
"True",
"then",
"don",
"t",
"return",
"until",
"all",
"threads",
"are",
"up",
"and",
"running",
".",
"Any",
"extra",
"keyword",
"arguments",
"are",
"passed"... | python | train | 42.06 |
Yubico/python-pyhsm | pyhsm/util.py | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/util.py#L103-L110 | def input_validate_aead(aead, name='aead', expected_len=None, max_aead_len = pyhsm.defines.YSM_AEAD_MAX_SIZE):
""" Input validation for YHSM_GeneratedAEAD or string. """
if isinstance(aead, pyhsm.aead_cmd.YHSM_GeneratedAEAD):
aead = aead.data
if expected_len != None:
return input_validate_st... | [
"def",
"input_validate_aead",
"(",
"aead",
",",
"name",
"=",
"'aead'",
",",
"expected_len",
"=",
"None",
",",
"max_aead_len",
"=",
"pyhsm",
".",
"defines",
".",
"YSM_AEAD_MAX_SIZE",
")",
":",
"if",
"isinstance",
"(",
"aead",
",",
"pyhsm",
".",
"aead_cmd",
... | Input validation for YHSM_GeneratedAEAD or string. | [
"Input",
"validation",
"for",
"YHSM_GeneratedAEAD",
"or",
"string",
"."
] | python | train | 53.75 |
zengbin93/zb | zb/algorithms/nn_one_hidden.py | https://github.com/zengbin93/zb/blob/ccdb384a0b5801b459933220efcb71972c2b89a7/zb/algorithms/nn_one_hidden.py#L107-L131 | def compute_cost(A2, Y):
"""
Computes the cross-entropy cost given in equation (13)
Arguments:
A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
Y -- "true" labels vector of shape (1, number of examples)
parameters -- python dictionary containing your parameter... | [
"def",
"compute_cost",
"(",
"A2",
",",
"Y",
")",
":",
"m",
"=",
"Y",
".",
"shape",
"[",
"1",
"]",
"# number of example",
"# Compute the cross-entropy cost",
"logprobs",
"=",
"np",
".",
"multiply",
"(",
"np",
".",
"log",
"(",
"A2",
")",
",",
"Y",
")",
... | Computes the cross-entropy cost given in equation (13)
Arguments:
A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
Y -- "true" labels vector of shape (1, number of examples)
parameters -- python dictionary containing your parameters W1, b1, W2 and b2
Returns:
... | [
"Computes",
"the",
"cross",
"-",
"entropy",
"cost",
"given",
"in",
"equation",
"(",
"13",
")"
] | python | train | 29.8 |
RedisJSON/rejson-py | rejson/client.py | https://github.com/RedisJSON/rejson-py/blob/55f0adf3adc40f5a769e28e541dbbf5377b90ec6/rejson/client.py#L215-L220 | def jsonarrlen(self, name, path=Path.rootPath()):
"""
Returns the length of the array JSON value under ``path`` at key
``name``
"""
return self.execute_command('JSON.ARRLEN', name, str_path(path)) | [
"def",
"jsonarrlen",
"(",
"self",
",",
"name",
",",
"path",
"=",
"Path",
".",
"rootPath",
"(",
")",
")",
":",
"return",
"self",
".",
"execute_command",
"(",
"'JSON.ARRLEN'",
",",
"name",
",",
"str_path",
"(",
"path",
")",
")"
] | Returns the length of the array JSON value under ``path`` at key
``name`` | [
"Returns",
"the",
"length",
"of",
"the",
"array",
"JSON",
"value",
"under",
"path",
"at",
"key",
"name"
] | python | train | 38.5 |
opencobra/cobrapy | cobra/io/sbml.py | https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L843-L1103 | def _model_to_sbml(cobra_model, f_replace=None, units=True):
"""Convert Cobra model to SBMLDocument.
Parameters
----------
cobra_model : cobra.core.Model
Cobra model instance
f_replace : dict of replacement functions
Replacement to apply on identifiers.
units : boolean
S... | [
"def",
"_model_to_sbml",
"(",
"cobra_model",
",",
"f_replace",
"=",
"None",
",",
"units",
"=",
"True",
")",
":",
"if",
"f_replace",
"is",
"None",
":",
"f_replace",
"=",
"{",
"}",
"sbml_ns",
"=",
"libsbml",
".",
"SBMLNamespaces",
"(",
"3",
",",
"1",
")"... | Convert Cobra model to SBMLDocument.
Parameters
----------
cobra_model : cobra.core.Model
Cobra model instance
f_replace : dict of replacement functions
Replacement to apply on identifiers.
units : boolean
Should the FLUX_UNITS be written in the SBMLDocument.
Returns
... | [
"Convert",
"Cobra",
"model",
"to",
"SBMLDocument",
"."
] | python | valid | 40.781609 |
spdx/tools-python | spdx/parsers/rdf.py | https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L606-L612 | def p_file_comments_on_lics(self, f_term, predicate):
"""Sets file license comment."""
try:
for _, _, comment in self.graph.triples((f_term, predicate, None)):
self.builder.set_file_license_comment(self.doc, six.text_type(comment))
except CardinalityError:
... | [
"def",
"p_file_comments_on_lics",
"(",
"self",
",",
"f_term",
",",
"predicate",
")",
":",
"try",
":",
"for",
"_",
",",
"_",
",",
"comment",
"in",
"self",
".",
"graph",
".",
"triples",
"(",
"(",
"f_term",
",",
"predicate",
",",
"None",
")",
")",
":",
... | Sets file license comment. | [
"Sets",
"file",
"license",
"comment",
"."
] | python | valid | 52.428571 |
yjzhang/uncurl_python | uncurl/lineage.py | https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/lineage.py#L195-L213 | def pseudotime(starting_node, edges, fitted_vals):
"""
Args:
starting_node (int): index of the starting node
edges (list): list of tuples (node1, node2)
fitted_vals (array): output of lineage (2 x cells)
Returns:
A 1d array containing the pseudotime value of each cell.
"... | [
"def",
"pseudotime",
"(",
"starting_node",
",",
"edges",
",",
"fitted_vals",
")",
":",
"# TODO",
"# 1. calculate a distance matrix...",
"distances",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"sum",
"(",
"(",
"x",
"-",
"y",
")",
"**",
"2",
")",
"for",
"x",
... | Args:
starting_node (int): index of the starting node
edges (list): list of tuples (node1, node2)
fitted_vals (array): output of lineage (2 x cells)
Returns:
A 1d array containing the pseudotime value of each cell. | [
"Args",
":",
"starting_node",
"(",
"int",
")",
":",
"index",
"of",
"the",
"starting",
"node",
"edges",
"(",
"list",
")",
":",
"list",
"of",
"tuples",
"(",
"node1",
"node2",
")",
"fitted_vals",
"(",
"array",
")",
":",
"output",
"of",
"lineage",
"(",
"... | python | train | 37.526316 |
googledatalab/pydatalab | google/datalab/contrib/mlworkbench/_local_predict.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L242-L297 | def get_probs_for_labels(labels, prediction_results):
""" Given ML Workbench prediction results, get probs of each label for each instance.
The prediction results are like:
[
{'predicted': 'daisy', 'probability': 0.8, 'predicted_2': 'rose', 'probability_2': 0.1},
{'predicted': 'sunflower', 'probability':... | [
"def",
"get_probs_for_labels",
"(",
"labels",
",",
"prediction_results",
")",
":",
"probs",
"=",
"[",
"]",
"if",
"'probability'",
"in",
"prediction_results",
":",
"# 'probability' exists so top-n is set to none zero, and results are like",
"# \"predicted, predicted_2,...,probabil... | Given ML Workbench prediction results, get probs of each label for each instance.
The prediction results are like:
[
{'predicted': 'daisy', 'probability': 0.8, 'predicted_2': 'rose', 'probability_2': 0.1},
{'predicted': 'sunflower', 'probability': 0.9, 'predicted_2': 'daisy', 'probability_2': 0.01},
..... | [
"Given",
"ML",
"Workbench",
"prediction",
"results",
"get",
"probs",
"of",
"each",
"label",
"for",
"each",
"instance",
"."
] | python | train | 36.160714 |
cyrus-/cypy | cypy/cg.py | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/cg.py#L198-L205 | def last_string(self):
"""The last entry in code_builder, or ``None`` if none so far."""
cb = self.code_builder
len_cb = len(cb)
if len_cb > 0:
return cb[len_cb - 1]
else:
return None | [
"def",
"last_string",
"(",
"self",
")",
":",
"cb",
"=",
"self",
".",
"code_builder",
"len_cb",
"=",
"len",
"(",
"cb",
")",
"if",
"len_cb",
">",
"0",
":",
"return",
"cb",
"[",
"len_cb",
"-",
"1",
"]",
"else",
":",
"return",
"None"
] | The last entry in code_builder, or ``None`` if none so far. | [
"The",
"last",
"entry",
"in",
"code_builder",
"or",
"None",
"if",
"none",
"so",
"far",
"."
] | python | train | 30 |
raff/dynash | dynash2/dynash2.py | https://github.com/raff/dynash/blob/a2b4fab67dd85ceaa9c1bb7604ebc1768a7fc28e/dynash2/dynash2.py#L574-L617 | def _todo_do_update(self, line):
"update [:tablename] {hashkey[,rangekey]} [!fieldname:expectedvalue] [-add|-delete] [+ALL_OLD|ALL_NEW|UPDATED_OLD|UPDATED_NEW] {attributes}"
table, line = self.get_table_params(line)
hkey, line = line.split(" ", 1)
expected, attr = self.get_expected(line)... | [
"def",
"_todo_do_update",
"(",
"self",
",",
"line",
")",
":",
"table",
",",
"line",
"=",
"self",
".",
"get_table_params",
"(",
"line",
")",
"hkey",
",",
"line",
"=",
"line",
".",
"split",
"(",
"\" \"",
",",
"1",
")",
"expected",
",",
"attr",
"=",
"... | update [:tablename] {hashkey[,rangekey]} [!fieldname:expectedvalue] [-add|-delete] [+ALL_OLD|ALL_NEW|UPDATED_OLD|UPDATED_NEW] {attributes} | [
"update",
"[",
":",
"tablename",
"]",
"{",
"hashkey",
"[",
"rangekey",
"]",
"}",
"[",
"!fieldname",
":",
"expectedvalue",
"]",
"[",
"-",
"add|",
"-",
"delete",
"]",
"[",
"+",
"ALL_OLD|ALL_NEW|UPDATED_OLD|UPDATED_NEW",
"]",
"{",
"attributes",
"}"
] | python | train | 31.954545 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/core_v1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/core_v1_api.py#L22763-L22787 | def replace_namespaced_service_account(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_service_account # noqa: E501
replace the specified ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP reque... | [
"def",
"replace_namespaced_service_account",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'"... | replace_namespaced_service_account # noqa: E501
replace the specified ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_service_account(name, namespa... | [
"replace_namespaced_service_account",
"#",
"noqa",
":",
"E501"
] | python | train | 62.64 |
saltstack/salt | salt/modules/rdp.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rdp.py#L104-L151 | def list_sessions(logged_in_users_only=False):
'''
List information about the sessions.
.. versionadded:: 2016.11.0
:param logged_in_users_only: If True, only return sessions with users logged in.
:return: A list containing dictionaries of session information.
CLI Example:
.. code-block:... | [
"def",
"list_sessions",
"(",
"logged_in_users_only",
"=",
"False",
")",
":",
"ret",
"=",
"list",
"(",
")",
"server",
"=",
"win32ts",
".",
"WTS_CURRENT_SERVER_HANDLE",
"protocols",
"=",
"{",
"win32ts",
".",
"WTS_PROTOCOL_TYPE_CONSOLE",
":",
"'console'",
",",
"win... | List information about the sessions.
.. versionadded:: 2016.11.0
:param logged_in_users_only: If True, only return sessions with users logged in.
:return: A list containing dictionaries of session information.
CLI Example:
.. code-block:: bash
salt '*' rdp.list_sessions | [
"List",
"information",
"about",
"the",
"sessions",
"."
] | python | train | 45.166667 |
pyusb/pyusb | usb/legacy.py | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L131-L141 | def bulkWrite(self, endpoint, buffer, timeout = 100):
r"""Perform a bulk write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
... | [
"def",
"bulkWrite",
"(",
"self",
",",
"endpoint",
",",
"buffer",
",",
"timeout",
"=",
"100",
")",
":",
"return",
"self",
".",
"dev",
".",
"write",
"(",
"endpoint",
",",
"buffer",
",",
"timeout",
")"
] | r"""Perform a bulk write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
timeout: operation timeout in milliseconds. (default: 100... | [
"r",
"Perform",
"a",
"bulk",
"write",
"request",
"to",
"the",
"endpoint",
"specified",
"."
] | python | train | 44.636364 |
mastro35/flows | flows/FlowsManager.py | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/FlowsManager.py#L229-L237 | def _deliver_message(self, msg):
"""
Deliver the message to the subscripted actions
"""
my_subscribed_actions = self.subscriptions.get(msg.sender, [])
for action in my_subscribed_actions:
if Global.CONFIG_MANAGER.tracing_mode:
Global.LOGGER.debug(f"del... | [
"def",
"_deliver_message",
"(",
"self",
",",
"msg",
")",
":",
"my_subscribed_actions",
"=",
"self",
".",
"subscriptions",
".",
"get",
"(",
"msg",
".",
"sender",
",",
"[",
"]",
")",
"for",
"action",
"in",
"my_subscribed_actions",
":",
"if",
"Global",
".",
... | Deliver the message to the subscripted actions | [
"Deliver",
"the",
"message",
"to",
"the",
"subscripted",
"actions"
] | python | train | 43.111111 |
idlesign/django-sitetree | sitetree/admin.py | https://github.com/idlesign/django-sitetree/blob/61de4608e6e415247c75fe8691027d7c4ed0d1e7/sitetree/admin.py#L264-L276 | def save_model(self, request, obj, form, change):
"""Saves TreeItem model under certain Tree.
Handles item's parent assignment exception.
"""
if change:
# No, you're not allowed to make item parent of itself
if obj.parent is not None and obj.parent.id == obj.id:
... | [
"def",
"save_model",
"(",
"self",
",",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
":",
"if",
"change",
":",
"# No, you're not allowed to make item parent of itself",
"if",
"obj",
".",
"parent",
"is",
"not",
"None",
"and",
"obj",
".",
"parent",
"... | Saves TreeItem model under certain Tree.
Handles item's parent assignment exception. | [
"Saves",
"TreeItem",
"model",
"under",
"certain",
"Tree",
".",
"Handles",
"item",
"s",
"parent",
"assignment",
"exception",
"."
] | python | test | 42.230769 |
pkgw/pwkit | pwkit/msmt.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/msmt.py#L401-L478 | def text_pieces(self, method, uplaces=2, use_exponent=True):
"""Return (main, dhigh, dlow, sharedexponent), all as strings. The
delta terms do not have sign indicators. Any item except the first
may be None.
`method` is passed to Uval.repvals() to compute representative
statisti... | [
"def",
"text_pieces",
"(",
"self",
",",
"method",
",",
"uplaces",
"=",
"2",
",",
"use_exponent",
"=",
"True",
")",
":",
"md",
",",
"hi",
",",
"lo",
"=",
"self",
".",
"repvals",
"(",
"method",
")",
"if",
"hi",
"==",
"lo",
":",
"return",
"'%g'",
"%... | Return (main, dhigh, dlow, sharedexponent), all as strings. The
delta terms do not have sign indicators. Any item except the first
may be None.
`method` is passed to Uval.repvals() to compute representative
statistical limits. | [
"Return",
"(",
"main",
"dhigh",
"dlow",
"sharedexponent",
")",
"all",
"as",
"strings",
".",
"The",
"delta",
"terms",
"do",
"not",
"have",
"sign",
"indicators",
".",
"Any",
"item",
"except",
"the",
"first",
"may",
"be",
"None",
"."
] | python | train | 34.679487 |
timofurrer/w1thermsensor | w1thermsensor/core.py | https://github.com/timofurrer/w1thermsensor/blob/8ac4fbb85e0c247dbb39e8b178cca0a975adc332/w1thermsensor/core.py#L329-L338 | def get_precision(self):
"""
Get the current precision from the sensor.
:returns: sensor resolution from 9-12 bits
:rtype: int
"""
config_str = self.raw_sensor_strings[1].split()[4] # Byte 5 is the config register
bit_base = int(config_str, 16) >> 5 ... | [
"def",
"get_precision",
"(",
"self",
")",
":",
"config_str",
"=",
"self",
".",
"raw_sensor_strings",
"[",
"1",
"]",
".",
"split",
"(",
")",
"[",
"4",
"]",
"# Byte 5 is the config register",
"bit_base",
"=",
"int",
"(",
"config_str",
",",
"16",
")",
">>",
... | Get the current precision from the sensor.
:returns: sensor resolution from 9-12 bits
:rtype: int | [
"Get",
"the",
"current",
"precision",
"from",
"the",
"sensor",
"."
] | python | train | 39.1 |
allenai/allennlp | allennlp/nn/initializers.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/initializers.py#L58-L95 | def uniform_unit_scaling(tensor: torch.Tensor, nonlinearity: str = "linear"):
"""
An initaliser which preserves output variance for approximately gaussian
distributed inputs. This boils down to initialising layers using a uniform
distribution in the range ``(-sqrt(3/dim[0]) * scale, sqrt(3 / dim[0]) * s... | [
"def",
"uniform_unit_scaling",
"(",
"tensor",
":",
"torch",
".",
"Tensor",
",",
"nonlinearity",
":",
"str",
"=",
"\"linear\"",
")",
":",
"size",
"=",
"1.",
"# Estimate the input size. This won't work perfectly,",
"# but it covers almost all use cases where this initialiser",
... | An initaliser which preserves output variance for approximately gaussian
distributed inputs. This boils down to initialising layers using a uniform
distribution in the range ``(-sqrt(3/dim[0]) * scale, sqrt(3 / dim[0]) * scale)``, where
``dim[0]`` is equal to the input dimension of the parameter and the ``s... | [
"An",
"initaliser",
"which",
"preserves",
"output",
"variance",
"for",
"approximately",
"gaussian",
"distributed",
"inputs",
".",
"This",
"boils",
"down",
"to",
"initialising",
"layers",
"using",
"a",
"uniform",
"distribution",
"in",
"the",
"range",
"(",
"-",
"s... | python | train | 44.605263 |
DataBiosphere/dsub | dsub/lib/job_model.py | https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/job_model.py#L927-L942 | def task_view_generator(job_descriptor):
"""Generator that yields a task-specific view of the job.
This generator exists to make it easy for callers to iterate over the tasks
in a JobDescriptor. Each pass yields a new JobDescriptor with a single task.
Args:
job_descriptor: A JobDescriptor with 1 or more t... | [
"def",
"task_view_generator",
"(",
"job_descriptor",
")",
":",
"for",
"task_descriptor",
"in",
"job_descriptor",
".",
"task_descriptors",
":",
"jd",
"=",
"JobDescriptor",
"(",
"job_descriptor",
".",
"job_metadata",
",",
"job_descriptor",
".",
"job_params",
",",
"job... | Generator that yields a task-specific view of the job.
This generator exists to make it easy for callers to iterate over the tasks
in a JobDescriptor. Each pass yields a new JobDescriptor with a single task.
Args:
job_descriptor: A JobDescriptor with 1 or more tasks.
Yields:
A JobDescriptor with a si... | [
"Generator",
"that",
"yields",
"a",
"task",
"-",
"specific",
"view",
"of",
"the",
"job",
"."
] | python | valid | 36.8125 |
dossier/dossier.models | dossier/models/openquery/fetcher.py | https://github.com/dossier/dossier.models/blob/c9e282f690eab72963926329efe1600709e48b13/dossier/models/openquery/fetcher.py#L108-L121 | def add(self, si):
'''puts `si` into the currently open chunk, which it creates if
necessary. If this item causes the chunk to cross chunk_max,
then the chunk closed after adding.
'''
if self.o_chunk is None:
if os.path.exists(self.t_path):
os.remove... | [
"def",
"add",
"(",
"self",
",",
"si",
")",
":",
"if",
"self",
".",
"o_chunk",
"is",
"None",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"t_path",
")",
":",
"os",
".",
"remove",
"(",
"self",
".",
"t_path",
")",
"self",
".",
... | puts `si` into the currently open chunk, which it creates if
necessary. If this item causes the chunk to cross chunk_max,
then the chunk closed after adding. | [
"puts",
"si",
"into",
"the",
"currently",
"open",
"chunk",
"which",
"it",
"creates",
"if",
"necessary",
".",
"If",
"this",
"item",
"causes",
"the",
"chunk",
"to",
"cross",
"chunk_max",
"then",
"the",
"chunk",
"closed",
"after",
"adding",
"."
] | python | train | 40.071429 |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QASU/save_tdx.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/save_tdx.py#L4016-L4146 | def QA_SU_save_future_min(client=DATABASE, ui_log=None, ui_progress=None):
"""save future_min
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
future_list = [
item for item in QA_fetch_get_future_list().code.unique().tolist()
if str(item)[-2:] in ['... | [
"def",
"QA_SU_save_future_min",
"(",
"client",
"=",
"DATABASE",
",",
"ui_log",
"=",
"None",
",",
"ui_progress",
"=",
"None",
")",
":",
"future_list",
"=",
"[",
"item",
"for",
"item",
"in",
"QA_fetch_get_future_list",
"(",
")",
".",
"code",
".",
"unique",
"... | save future_min
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | [
"save",
"future_min"
] | python | train | 32.755725 |
JarryShaw/PyPCAPKit | src/protocols/transport/tcp.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/transport/tcp.py#L464-L494 | def _read_mode_tsopt(self, size, kind):
"""Read Timestamps option.
Positional arguments:
* size - int, length of option
* kind - int, 8 (Timestamps)
Returns:
* dict -- extracted Timestamps (TS) option
Structure of TCP TSopt [RFC 7323]:
+... | [
"def",
"_read_mode_tsopt",
"(",
"self",
",",
"size",
",",
"kind",
")",
":",
"temp",
"=",
"struct",
".",
"unpack",
"(",
"'>II'",
",",
"self",
".",
"_read_fileng",
"(",
"size",
")",
")",
"data",
"=",
"dict",
"(",
"kind",
"=",
"kind",
",",
"length",
"... | Read Timestamps option.
Positional arguments:
* size - int, length of option
* kind - int, 8 (Timestamps)
Returns:
* dict -- extracted Timestamps (TS) option
Structure of TCP TSopt [RFC 7323]:
+-------+-------+---------------------+-------------... | [
"Read",
"Timestamps",
"option",
"."
] | python | train | 36.774194 |
Crypto-toolbox/btfxwss | btfxwss/connection.py | https://github.com/Crypto-toolbox/btfxwss/blob/16827fa6aacb2c0e289aa852bf61a18df6905835/btfxwss/connection.py#L291-L314 | def send(self, api_key=None, secret=None, list_data=None, auth=False, **kwargs):
"""Sends the given Payload to the API via the websocket connection.
:param kwargs: payload paarameters as key=value pairs
:return:
"""
if auth:
nonce = str(int(time.time() * 10000000))
... | [
"def",
"send",
"(",
"self",
",",
"api_key",
"=",
"None",
",",
"secret",
"=",
"None",
",",
"list_data",
"=",
"None",
",",
"auth",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"auth",
":",
"nonce",
"=",
"str",
"(",
"int",
"(",
"time",
"... | Sends the given Payload to the API via the websocket connection.
:param kwargs: payload paarameters as key=value pairs
:return: | [
"Sends",
"the",
"given",
"Payload",
"to",
"the",
"API",
"via",
"the",
"websocket",
"connection",
"."
] | python | test | 44.375 |
sbg/sevenbridges-python | sevenbridges/transfer/download.py | https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/transfer/download.py#L305-L318 | def start(self):
"""
Starts the download.
:raises SbgError: If download is not in PREPARING state.
"""
if self._status == TransferState.PREPARING:
self._running.set()
super(Download, self).start()
self._status = TransferState.RUNNING
... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_status",
"==",
"TransferState",
".",
"PREPARING",
":",
"self",
".",
"_running",
".",
"set",
"(",
")",
"super",
"(",
"Download",
",",
"self",
")",
".",
"start",
"(",
")",
"self",
".",
"_sta... | Starts the download.
:raises SbgError: If download is not in PREPARING state. | [
"Starts",
"the",
"download",
".",
":",
"raises",
"SbgError",
":",
"If",
"download",
"is",
"not",
"in",
"PREPARING",
"state",
"."
] | python | train | 33.214286 |
PredixDev/predixpy | predix/admin/service.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/service.py#L30-L34 | def _generate_name(self, space, service_name, plan_name):
"""
Can generate a name based on the space, service name and plan.
"""
return str.join('-', [space, service_name, plan_name]).lower() | [
"def",
"_generate_name",
"(",
"self",
",",
"space",
",",
"service_name",
",",
"plan_name",
")",
":",
"return",
"str",
".",
"join",
"(",
"'-'",
",",
"[",
"space",
",",
"service_name",
",",
"plan_name",
"]",
")",
".",
"lower",
"(",
")"
] | Can generate a name based on the space, service name and plan. | [
"Can",
"generate",
"a",
"name",
"based",
"on",
"the",
"space",
"service",
"name",
"and",
"plan",
"."
] | python | train | 43.8 |
JustinLovinger/optimal | optimal/optimize.py | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L138-L141 | def decode_solution(self, encoded_solution):
"""Return solution from an encoded representation."""
return self._decode_function(encoded_solution, *self._decode_args,
**self._decode_kwargs) | [
"def",
"decode_solution",
"(",
"self",
",",
"encoded_solution",
")",
":",
"return",
"self",
".",
"_decode_function",
"(",
"encoded_solution",
",",
"*",
"self",
".",
"_decode_args",
",",
"*",
"*",
"self",
".",
"_decode_kwargs",
")"
] | Return solution from an encoded representation. | [
"Return",
"solution",
"from",
"an",
"encoded",
"representation",
"."
] | python | train | 59.5 |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdpa_utils.py | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L148-L191 | def solve_with_sdpa(sdp, solverparameters=None):
"""Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:ty... | [
"def",
"solve_with_sdpa",
"(",
"sdp",
",",
"solverparameters",
"=",
"None",
")",
":",
"solverexecutable",
"=",
"detect_sdpa",
"(",
"solverparameters",
")",
"if",
"solverexecutable",
"is",
"None",
":",
"raise",
"OSError",
"(",
"\"SDPA is not in the path or the executab... | Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:type solverparameters: dict of str.
:returns: tuple of... | [
"Helper",
"function",
"to",
"write",
"out",
"the",
"SDP",
"problem",
"to",
"a",
"temporary",
"file",
"call",
"the",
"solver",
"and",
"parse",
"the",
"output",
"."
] | python | train | 42.045455 |
NASA-AMMOS/AIT-Core | ait/core/dtype.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/dtype.py#L240-L250 | def decode(self, bytes, raw=False):
"""decode(bytearray, raw=False) -> value
Decodes the given bytearray according to this PrimitiveType
definition.
NOTE: The parameter ``raw`` is present to adhere to the
``decode()`` inteface, but has no effect for PrimitiveType
defini... | [
"def",
"decode",
"(",
"self",
",",
"bytes",
",",
"raw",
"=",
"False",
")",
":",
"return",
"struct",
".",
"unpack",
"(",
"self",
".",
"format",
",",
"buffer",
"(",
"bytes",
")",
")",
"[",
"0",
"]"
] | decode(bytearray, raw=False) -> value
Decodes the given bytearray according to this PrimitiveType
definition.
NOTE: The parameter ``raw`` is present to adhere to the
``decode()`` inteface, but has no effect for PrimitiveType
definitions. | [
"decode",
"(",
"bytearray",
"raw",
"=",
"False",
")",
"-",
">",
"value"
] | python | train | 35.272727 |
todddeluca/dones | dones.py | https://github.com/todddeluca/dones/blob/6ef56565556987e701fed797a405f0825fe2e15a/dones.py#L265-L283 | def open_conn(host, db, user, password, retries=0, sleep=0.5):
'''
Return an open mysql db connection using the given credentials. Use
`retries` and `sleep` to be robust to the occassional transient connection
failure.
retries: if an exception when getting the connection, try again at most this ma... | [
"def",
"open_conn",
"(",
"host",
",",
"db",
",",
"user",
",",
"password",
",",
"retries",
"=",
"0",
",",
"sleep",
"=",
"0.5",
")",
":",
"assert",
"retries",
">=",
"0",
"try",
":",
"return",
"MySQLdb",
".",
"connect",
"(",
"host",
"=",
"host",
",",
... | Return an open mysql db connection using the given credentials. Use
`retries` and `sleep` to be robust to the occassional transient connection
failure.
retries: if an exception when getting the connection, try again at most this many times.
sleep: pause between retries for this many seconds. a float ... | [
"Return",
"an",
"open",
"mysql",
"db",
"connection",
"using",
"the",
"given",
"credentials",
".",
"Use",
"retries",
"and",
"sleep",
"to",
"be",
"robust",
"to",
"the",
"occassional",
"transient",
"connection",
"failure",
"."
] | python | train | 36 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py#L234-L254 | def hide_routemap_holder_route_map_content_match_ip_route_source_prefix_list_rmrs(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_m... | [
"def",
"hide_routemap_holder_route_map_content_match_ip_route_source_prefix_list_rmrs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_routemap_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 52.47619 |
fake-name/ChromeController | ChromeController/transport.py | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/transport.py#L474-L509 | def send(self, command, tab_key, params=None):
'''
Send command `command` with optional parameters `params` to the
remote chrome instance.
The command `id` is automatically added to the outgoing message.
return value is the command id, which can be used to match a command
to it's associated response.
''... | [
"def",
"send",
"(",
"self",
",",
"command",
",",
"tab_key",
",",
"params",
"=",
"None",
")",
":",
"self",
".",
"__check_open_socket",
"(",
"tab_key",
")",
"sent_id",
"=",
"self",
".",
"msg_id",
"command",
"=",
"{",
"\"id\"",
":",
"self",
".",
"msg_id",... | Send command `command` with optional parameters `params` to the
remote chrome instance.
The command `id` is automatically added to the outgoing message.
return value is the command id, which can be used to match a command
to it's associated response. | [
"Send",
"command",
"command",
"with",
"optional",
"parameters",
"params",
"to",
"the",
"remote",
"chrome",
"instance",
"."
] | python | train | 26.75 |
pybel/pybel | src/pybel/manager/cache_manager.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/cache_manager.py#L825-L881 | def get_or_create_node(self, graph: BELGraph, node: BaseEntity) -> Optional[Node]:
"""Create an entry and object for given node if it does not exist."""
sha512 = node.as_sha512()
if sha512 in self.object_cache_node:
return self.object_cache_node[sha512]
node_model = self.get... | [
"def",
"get_or_create_node",
"(",
"self",
",",
"graph",
":",
"BELGraph",
",",
"node",
":",
"BaseEntity",
")",
"->",
"Optional",
"[",
"Node",
"]",
":",
"sha512",
"=",
"node",
".",
"as_sha512",
"(",
")",
"if",
"sha512",
"in",
"self",
".",
"object_cache_nod... | Create an entry and object for given node if it does not exist. | [
"Create",
"an",
"entry",
"and",
"object",
"for",
"given",
"node",
"if",
"it",
"does",
"not",
"exist",
"."
] | python | train | 34.017544 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/ext/_bundled/mplexporter.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/mplexporter.py#L455-L467 | def draw_marked_line(self, data, coordinates, linestyle, markerstyle,
label, mplobj=None):
"""Draw a line that also has markers.
If this isn't reimplemented by a renderer object, by default, it will
make a call to BOTH draw_line and draw_markers when both markerstyle
... | [
"def",
"draw_marked_line",
"(",
"self",
",",
"data",
",",
"coordinates",
",",
"linestyle",
",",
"markerstyle",
",",
"label",
",",
"mplobj",
"=",
"None",
")",
":",
"if",
"linestyle",
"is",
"not",
"None",
":",
"self",
".",
"draw_line",
"(",
"data",
",",
... | Draw a line that also has markers.
If this isn't reimplemented by a renderer object, by default, it will
make a call to BOTH draw_line and draw_markers when both markerstyle
and linestyle are not None in the same Line2D object. | [
"Draw",
"a",
"line",
"that",
"also",
"has",
"markers",
"."
] | python | train | 46.076923 |
couchbase/couchbase-python-client | couchbase/bucket.py | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1235-L1246 | def lock_multi(self, keys, ttl=0):
"""Lock multiple keys. Multi variant of :meth:`lock`
:param keys: the keys to lock
:type keys: :ref:`iterable<argtypes>`
:param int ttl: The lock timeout for all keys
:return: a :class:`~.MultiResult` object
.. seealso:: :meth:`lock`
... | [
"def",
"lock_multi",
"(",
"self",
",",
"keys",
",",
"ttl",
"=",
"0",
")",
":",
"return",
"_Base",
".",
"lock_multi",
"(",
"self",
",",
"keys",
",",
"ttl",
"=",
"ttl",
")"
] | Lock multiple keys. Multi variant of :meth:`lock`
:param keys: the keys to lock
:type keys: :ref:`iterable<argtypes>`
:param int ttl: The lock timeout for all keys
:return: a :class:`~.MultiResult` object
.. seealso:: :meth:`lock` | [
"Lock",
"multiple",
"keys",
".",
"Multi",
"variant",
"of",
":",
"meth",
":",
"lock"
] | python | train | 31.083333 |
samfoo/vt102 | vt102/__init__.py | https://github.com/samfoo/vt102/blob/ff5be883bc9a880a422b09bb87b210d7c408cf2c/vt102/__init__.py#L513-L550 | def _print(self, char):
"""
Print a character at the current cursor position and advance the
cursor.
"""
# Don't make bugs where we try to print a screen.
assert len(char) == 1
try:
try:
# Python 3
char = self.decoder... | [
"def",
"_print",
"(",
"self",
",",
"char",
")",
":",
"# Don't make bugs where we try to print a screen. ",
"assert",
"len",
"(",
"char",
")",
"==",
"1",
"try",
":",
"try",
":",
"# Python 3",
"char",
"=",
"self",
".",
"decoder",
"(",
"bytes",
"(",
"char",
"... | Print a character at the current cursor position and advance the
cursor. | [
"Print",
"a",
"character",
"at",
"the",
"current",
"cursor",
"position",
"and",
"advance",
"the",
"cursor",
"."
] | python | train | 29.973684 |
tradenity/python-sdk | tradenity/resources/braintree_gateway.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/braintree_gateway.py#L709-L731 | def list_all_braintree_gateways(cls, **kwargs):
"""List BraintreeGateways
Return a list of BraintreeGateways
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_braintree_gateways(async=T... | [
"def",
"list_all_braintree_gateways",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_list_all_braintree_gateways_with_http_... | List BraintreeGateways
Return a list of BraintreeGateways
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_braintree_gateways(async=True)
>>> result = thread.get()
:param asyn... | [
"List",
"BraintreeGateways"
] | python | train | 39.086957 |
mlperf/training | reinforcement/tensorflow/minigo/dual_net.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/dual_net.py#L219-L376 | def model_fn(features, labels, mode, params):
"""
Create the model for estimator api
Args:
features: tensor with shape
[BATCH_SIZE, go.N, go.N, features_lib.NEW_FEATURES_PLANES]
labels: dict from string to tensor with shape
'pi_tensor': [BATCH_SIZE, go.N * go.N + 1]
... | [
"def",
"model_fn",
"(",
"features",
",",
"labels",
",",
"mode",
",",
"params",
")",
":",
"policy_output",
",",
"value_output",
",",
"logits",
"=",
"model_inference_fn",
"(",
"features",
",",
"mode",
"==",
"tf",
".",
"estimator",
".",
"ModeKeys",
".",
"TRAI... | Create the model for estimator api
Args:
features: tensor with shape
[BATCH_SIZE, go.N, go.N, features_lib.NEW_FEATURES_PLANES]
labels: dict from string to tensor with shape
'pi_tensor': [BATCH_SIZE, go.N * go.N + 1]
'value_tensor': [BATCH_SIZE]
mode: a t... | [
"Create",
"the",
"model",
"for",
"estimator",
"api"
] | python | train | 40.892405 |
swharden/SWHLab | swhlab/common.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/common.py#L36-L47 | def lowpass(data,filterSize=None):
"""
minimal complexity low-pass filtering.
Filter size is how "wide" the filter will be.
Sigma will be 1/10 of this filter width.
If filter size isn't given, it will be 1/10 of the data size.
"""
if filterSize is None:
filterSize=len(data)/10
ke... | [
"def",
"lowpass",
"(",
"data",
",",
"filterSize",
"=",
"None",
")",
":",
"if",
"filterSize",
"is",
"None",
":",
"filterSize",
"=",
"len",
"(",
"data",
")",
"/",
"10",
"kernel",
"=",
"kernel_gaussian",
"(",
"size",
"=",
"filterSize",
")",
"data",
"=",
... | minimal complexity low-pass filtering.
Filter size is how "wide" the filter will be.
Sigma will be 1/10 of this filter width.
If filter size isn't given, it will be 1/10 of the data size. | [
"minimal",
"complexity",
"low",
"-",
"pass",
"filtering",
".",
"Filter",
"size",
"is",
"how",
"wide",
"the",
"filter",
"will",
"be",
".",
"Sigma",
"will",
"be",
"1",
"/",
"10",
"of",
"this",
"filter",
"width",
".",
"If",
"filter",
"size",
"isn",
"t",
... | python | valid | 36 |
amelchio/eternalegypt | examples/sms.py | https://github.com/amelchio/eternalegypt/blob/895e0b235ceaf7f61458c620237c3ad397780e98/examples/sms.py#L15-L26 | async def send_message():
"""Example of sending a message."""
jar = aiohttp.CookieJar(unsafe=True)
websession = aiohttp.ClientSession(cookie_jar=jar)
modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession)
await modem.login(password=sys.argv[2])
await modem.sms(phone=sys.argv[3... | [
"async",
"def",
"send_message",
"(",
")",
":",
"jar",
"=",
"aiohttp",
".",
"CookieJar",
"(",
"unsafe",
"=",
"True",
")",
"websession",
"=",
"aiohttp",
".",
"ClientSession",
"(",
"cookie_jar",
"=",
"jar",
")",
"modem",
"=",
"eternalegypt",
".",
"Modem",
"... | Example of sending a message. | [
"Example",
"of",
"sending",
"a",
"message",
"."
] | python | test | 32.25 |
gtaylor/python-route53 | route53/connection.py | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/connection.py#L113-L139 | def list_hosted_zones(self, page_chunks=100):
"""
List all hosted zones associated with this connection's account. Since
this method returns a generator, you can pull as many or as few
entries as you'd like, without having to query and receive every
hosted zone you may have.
... | [
"def",
"list_hosted_zones",
"(",
"self",
",",
"page_chunks",
"=",
"100",
")",
":",
"return",
"self",
".",
"_do_autopaginating_api_call",
"(",
"path",
"=",
"'hostedzone'",
",",
"params",
"=",
"{",
"'maxitems'",
":",
"page_chunks",
"}",
",",
"method",
"=",
"'G... | List all hosted zones associated with this connection's account. Since
this method returns a generator, you can pull as many or as few
entries as you'd like, without having to query and receive every
hosted zone you may have.
:keyword int page_chunks: This API call is "paginated" behind... | [
"List",
"all",
"hosted",
"zones",
"associated",
"with",
"this",
"connection",
"s",
"account",
".",
"Since",
"this",
"method",
"returns",
"a",
"generator",
"you",
"can",
"pull",
"as",
"many",
"or",
"as",
"few",
"entries",
"as",
"you",
"d",
"like",
"without"... | python | test | 41.444444 |
xmikos/reparser | reparser.py | https://github.com/xmikos/reparser/blob/0668112a15b9e8e9355a1261040c36b4a6034020/reparser.py#L103-L109 | def get_matched_token(self, match):
"""Find which token has been matched by compound regex"""
match_groupdict = match.groupdict()
for group in self.groups:
if match_groupdict[group] is not None:
token, match_type = self.groups[group]
return (token, mat... | [
"def",
"get_matched_token",
"(",
"self",
",",
"match",
")",
":",
"match_groupdict",
"=",
"match",
".",
"groupdict",
"(",
")",
"for",
"group",
"in",
"self",
".",
"groups",
":",
"if",
"match_groupdict",
"[",
"group",
"]",
"is",
"not",
"None",
":",
"token",... | Find which token has been matched by compound regex | [
"Find",
"which",
"token",
"has",
"been",
"matched",
"by",
"compound",
"regex"
] | python | train | 47 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L302-L341 | def send_packet(self, pk, expected_reply=(), resend=False, timeout=0.2):
"""
Send a packet through the link interface.
pk -- Packet to send
expect_answer -- True if a packet from the Crazyflie is expected to
be sent back, otherwise false
"""
sel... | [
"def",
"send_packet",
"(",
"self",
",",
"pk",
",",
"expected_reply",
"=",
"(",
")",
",",
"resend",
"=",
"False",
",",
"timeout",
"=",
"0.2",
")",
":",
"self",
".",
"_send_lock",
".",
"acquire",
"(",
")",
"if",
"self",
".",
"link",
"is",
"not",
"Non... | Send a packet through the link interface.
pk -- Packet to send
expect_answer -- True if a packet from the Crazyflie is expected to
be sent back, otherwise false | [
"Send",
"a",
"packet",
"through",
"the",
"link",
"interface",
"."
] | python | train | 46.075 |
bitesofcode/projexui | projexui/widgets/xnodewidget/xnode.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnode.py#L1831-L1839 | def setIsolateHidden(self, state):
"""
Sets whether or not this item is hidden due to isolation.
:param state | <bool>
"""
self._isolatedHidden = state
super(XNode, self).setVisible(self.isVisible()) | [
"def",
"setIsolateHidden",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"_isolatedHidden",
"=",
"state",
"super",
"(",
"XNode",
",",
"self",
")",
".",
"setVisible",
"(",
"self",
".",
"isVisible",
"(",
")",
")"
] | Sets whether or not this item is hidden due to isolation.
:param state | <bool> | [
"Sets",
"whether",
"or",
"not",
"this",
"item",
"is",
"hidden",
"due",
"to",
"isolation",
".",
":",
"param",
"state",
"|",
"<bool",
">"
] | python | train | 29.111111 |
pallets/werkzeug | src/werkzeug/serving.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/serving.py#L611-L630 | def select_address_family(host, port):
"""Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
the host and port."""
# disabled due to problems with current ipv6 implementations
# and various operating systems. Probably this code also is
# not supposed to work, but I can't come up with an... | [
"def",
"select_address_family",
"(",
"host",
",",
"port",
")",
":",
"# disabled due to problems with current ipv6 implementations",
"# and various operating systems. Probably this code also is",
"# not supposed to work, but I can't come up with any other",
"# ways to implement this.",
"# tr... | Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
the host and port. | [
"Return",
"AF_INET4",
"AF_INET6",
"or",
"AF_UNIX",
"depending",
"on",
"the",
"host",
"and",
"port",
"."
] | python | train | 40.05 |
etcher-be/epab | epab/utils/_repo.py | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L33-L52 | def tag(self, tag: str, overwrite: bool = False) -> None:
"""
Tags the current commit
:param tag: tag
:type tag: str
:param overwrite: overwrite existing tag
:type overwrite: bool
"""
LOGGER.info('tagging repo: %s', tag)
try:
self.repo... | [
"def",
"tag",
"(",
"self",
",",
"tag",
":",
"str",
",",
"overwrite",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"LOGGER",
".",
"info",
"(",
"'tagging repo: %s'",
",",
"tag",
")",
"try",
":",
"self",
".",
"repo",
".",
"create_tag",
"(",
"tag... | Tags the current commit
:param tag: tag
:type tag: str
:param overwrite: overwrite existing tag
:type overwrite: bool | [
"Tags",
"the",
"current",
"commit"
] | python | train | 32.65 |
ninuxorg/nodeshot | nodeshot/core/nodes/models/node.py | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/nodes/models/node.py#L88-L116 | def save(self, *args, **kwargs):
"""
Custom save method does the following things:
* converts geometry collections of just 1 item to that item (eg: a collection of 1 Point becomes a Point)
* intercepts changes to status and fires node_status_changed signal
* set defau... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# geometry collection check",
"if",
"isinstance",
"(",
"self",
".",
"geometry",
",",
"GeometryCollection",
")",
"and",
"0",
"<",
"len",
"(",
"self",
".",
"geometry",
")",
... | Custom save method does the following things:
* converts geometry collections of just 1 item to that item (eg: a collection of 1 Point becomes a Point)
* intercepts changes to status and fires node_status_changed signal
* set default status | [
"Custom",
"save",
"method",
"does",
"the",
"following",
"things",
":",
"*",
"converts",
"geometry",
"collections",
"of",
"just",
"1",
"item",
"to",
"that",
"item",
"(",
"eg",
":",
"a",
"collection",
"of",
"1",
"Point",
"becomes",
"a",
"Point",
")",
"*",
... | python | train | 45.965517 |
Robpol86/Flask-Celery-Helper | flask_celery.py | https://github.com/Robpol86/Flask-Celery-Helper/blob/92bd3b02954422665260116adda8eb899546c365/flask_celery.py#L82-L85 | def is_already_running(self):
"""Return True if lock exists and has not timed out."""
redis_key = self.CELERY_LOCK.format(task_id=self.task_identifier)
return self.celery_self.backend.client.exists(redis_key) | [
"def",
"is_already_running",
"(",
"self",
")",
":",
"redis_key",
"=",
"self",
".",
"CELERY_LOCK",
".",
"format",
"(",
"task_id",
"=",
"self",
".",
"task_identifier",
")",
"return",
"self",
".",
"celery_self",
".",
"backend",
".",
"client",
".",
"exists",
"... | Return True if lock exists and has not timed out. | [
"Return",
"True",
"if",
"lock",
"exists",
"and",
"has",
"not",
"timed",
"out",
"."
] | python | valid | 57.25 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.