repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
sveetch/boussole | boussole/conf/post_processor.py | https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/post_processor.py#L103-L126 | def _validate_path(self, settings, name, value):
"""
Validate path exists
Args:
settings (dict): Current settings.
name (str): Setting name.
value (str): Path to validate.
Raises:
boussole.exceptions.SettingsInvalidError: If path does not... | [
"def",
"_validate_path",
"(",
"self",
",",
"settings",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"value",
")",
":",
"raise",
"SettingsInvalidError",
"(",
"\"Path from setting '{name}' does not \"",
"\"exists: {value... | Validate path exists
Args:
settings (dict): Current settings.
name (str): Setting name.
value (str): Path to validate.
Raises:
boussole.exceptions.SettingsInvalidError: If path does not exists.
Returns:
str: Validated path. | [
"Validate",
"path",
"exists"
] | python | train |
wonambi-python/wonambi | wonambi/ioeeg/ktlx.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/ktlx.py#L626-L665 | def _read_snc(snc_file):
"""Read Synchronization File and return sample stamp and time
Returns
-------
sampleStamp : list of int
Sample number from start of study
sampleTime : list of datetime.datetime
File time representation of sampleStamp
Notes
-----
The synchronizat... | [
"def",
"_read_snc",
"(",
"snc_file",
")",
":",
"snc_raw_dtype",
"=",
"dtype",
"(",
"[",
"(",
"'sampleStamp'",
",",
"'<i'",
")",
",",
"(",
"'sampleTime'",
",",
"'<q'",
")",
"]",
")",
"with",
"snc_file",
".",
"open",
"(",
"'rb'",
")",
"as",
"f",
":",
... | Read Synchronization File and return sample stamp and time
Returns
-------
sampleStamp : list of int
Sample number from start of study
sampleTime : list of datetime.datetime
File time representation of sampleStamp
Notes
-----
The synchronization file is used to calculate a ... | [
"Read",
"Synchronization",
"File",
"and",
"return",
"sample",
"stamp",
"and",
"time"
] | python | train |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/random/RandomText.py | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/random/RandomText.py#L148-L165 | def name():
"""
Generates a random person's name which has the following structure
<optional prefix> <first name> <second name> <optional suffix>
:return: a random name.
"""
result = ""
if RandomBoolean.chance(3, 5):
result += random.choice(_name_pre... | [
"def",
"name",
"(",
")",
":",
"result",
"=",
"\"\"",
"if",
"RandomBoolean",
".",
"chance",
"(",
"3",
",",
"5",
")",
":",
"result",
"+=",
"random",
".",
"choice",
"(",
"_name_prefixes",
")",
"+",
"\" \"",
"result",
"+=",
"random",
".",
"choice",
"(",
... | Generates a random person's name which has the following structure
<optional prefix> <first name> <second name> <optional suffix>
:return: a random name. | [
"Generates",
"a",
"random",
"person",
"s",
"name",
"which",
"has",
"the",
"following",
"structure",
"<optional",
"prefix",
">",
"<first",
"name",
">",
"<second",
"name",
">",
"<optional",
"suffix",
">"
] | python | train |
allenai/allennlp | allennlp/state_machines/states/lambda_grammar_statelet.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/states/lambda_grammar_statelet.py#L102-L158 | def take_action(self, production_rule: str) -> 'LambdaGrammarStatelet':
"""
Takes an action in the current grammar state, returning a new grammar state with whatever
updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS".
This will update the non-terminal... | [
"def",
"take_action",
"(",
"self",
",",
"production_rule",
":",
"str",
")",
"->",
"'LambdaGrammarStatelet'",
":",
"left_side",
",",
"right_side",
"=",
"production_rule",
".",
"split",
"(",
"' -> '",
")",
"assert",
"self",
".",
"_nonterminal_stack",
"[",
"-",
"... | Takes an action in the current grammar state, returning a new grammar state with whatever
updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS".
This will update the non-terminal stack and the context-dependent actions. Updating the
non-terminal stack involves ... | [
"Takes",
"an",
"action",
"in",
"the",
"current",
"grammar",
"state",
"returning",
"a",
"new",
"grammar",
"state",
"with",
"whatever",
"updates",
"are",
"necessary",
".",
"The",
"production",
"rule",
"is",
"assumed",
"to",
"be",
"formatted",
"as",
"LHS",
"-",... | python | train |
serkanyersen/underscore.py | src/underscore.py | https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L718-L732 | def lastIndexOf(self, item):
"""
Return the position of the last occurrence of an
item in an array, or -1 if the item is not included in the array.
"""
array = self.obj
i = len(array) - 1
if not (self._clean.isList() or self._clean.isTuple()):
return s... | [
"def",
"lastIndexOf",
"(",
"self",
",",
"item",
")",
":",
"array",
"=",
"self",
".",
"obj",
"i",
"=",
"len",
"(",
"array",
")",
"-",
"1",
"if",
"not",
"(",
"self",
".",
"_clean",
".",
"isList",
"(",
")",
"or",
"self",
".",
"_clean",
".",
"isTup... | Return the position of the last occurrence of an
item in an array, or -1 if the item is not included in the array. | [
"Return",
"the",
"position",
"of",
"the",
"last",
"occurrence",
"of",
"an",
"item",
"in",
"an",
"array",
"or",
"-",
"1",
"if",
"the",
"item",
"is",
"not",
"included",
"in",
"the",
"array",
"."
] | python | train |
IdentityPython/pysaml2 | src/saml2/client.py | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client.py#L287-L293 | def is_logged_in(self, name_id):
""" Check if user is in the cache
:param name_id: The identifier of the subject
"""
identity = self.users.get_identity(name_id)[0]
return bool(identity) | [
"def",
"is_logged_in",
"(",
"self",
",",
"name_id",
")",
":",
"identity",
"=",
"self",
".",
"users",
".",
"get_identity",
"(",
"name_id",
")",
"[",
"0",
"]",
"return",
"bool",
"(",
"identity",
")"
] | Check if user is in the cache
:param name_id: The identifier of the subject | [
"Check",
"if",
"user",
"is",
"in",
"the",
"cache"
] | python | train |
kcallin/mqtt-codec | mqtt_codec/io.py | https://github.com/kcallin/mqtt-codec/blob/0f754250cc3f44f4376777e7e8b3676c5a4d413a/mqtt_codec/io.py#L439-L463 | def read(self, max_bytes=1):
"""Read at most `max_bytes` from internal buffer.
Parameters
-----------
max_bytes: int
Maximum number of bytes to read.
Returns
--------
bytes
Bytes extracted from internal buffer. Length may be less
... | [
"def",
"read",
"(",
"self",
",",
"max_bytes",
"=",
"1",
")",
":",
"if",
"self",
".",
"limit",
"is",
"None",
":",
"b",
"=",
"self",
".",
"__f",
".",
"read",
"(",
"max_bytes",
")",
"else",
":",
"if",
"self",
".",
"__num_bytes_consumed",
"+",
"max_byt... | Read at most `max_bytes` from internal buffer.
Parameters
-----------
max_bytes: int
Maximum number of bytes to read.
Returns
--------
bytes
Bytes extracted from internal buffer. Length may be less
than ``max_bytes``. On end-of file... | [
"Read",
"at",
"most",
"max_bytes",
"from",
"internal",
"buffer",
"."
] | python | train |
openai/baselines | baselines/her/her_sampler.py | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/her/her_sampler.py#L4-L63 | def make_sample_her_transitions(replay_strategy, replay_k, reward_fun):
"""Creates a sample function that can be used for HER experience replay.
Args:
replay_strategy (in ['future', 'none']): the HER replay strategy; if set to 'none',
regular DDPG experience replay is used
replay_k ... | [
"def",
"make_sample_her_transitions",
"(",
"replay_strategy",
",",
"replay_k",
",",
"reward_fun",
")",
":",
"if",
"replay_strategy",
"==",
"'future'",
":",
"future_p",
"=",
"1",
"-",
"(",
"1.",
"/",
"(",
"1",
"+",
"replay_k",
")",
")",
"else",
":",
"# 'rep... | Creates a sample function that can be used for HER experience replay.
Args:
replay_strategy (in ['future', 'none']): the HER replay strategy; if set to 'none',
regular DDPG experience replay is used
replay_k (int): the ratio between HER replays and regular replays (e.g. k = 4 -> 4 times... | [
"Creates",
"a",
"sample",
"function",
"that",
"can",
"be",
"used",
"for",
"HER",
"experience",
"replay",
"."
] | python | valid |
linkhub-sdk/popbill.py | popbill/closedownService.py | https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/closedownService.py#L39-L51 | def getUnitCost(self, CorpNum):
""" 휴폐업조회 단가 확인.
args
CorpNum : 팝빌회원 사업자번호
return
발행단가 by float
raise
PopbillException
"""
result = self._httpget('/CloseDown/UnitCost', CorpNum)
return float(result.unit... | [
"def",
"getUnitCost",
"(",
"self",
",",
"CorpNum",
")",
":",
"result",
"=",
"self",
".",
"_httpget",
"(",
"'/CloseDown/UnitCost'",
",",
"CorpNum",
")",
"return",
"float",
"(",
"result",
".",
"unitCost",
")"
] | 휴폐업조회 단가 확인.
args
CorpNum : 팝빌회원 사업자번호
return
발행단가 by float
raise
PopbillException | [
"휴폐업조회",
"단가",
"확인",
".",
"args",
"CorpNum",
":",
"팝빌회원",
"사업자번호",
"return",
"발행단가",
"by",
"float",
"raise",
"PopbillException"
] | python | train |
horazont/aioxmpp | aioxmpp/stream.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1894-L1909 | def stop(self):
"""
Send a signal to the main broker task to terminate. You have to check
:attr:`running` and possibly wait for it to become :data:`False` ---
the task takes at least one loop through the event loop to terminate.
It is guarenteed that the task will not attempt to... | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"running",
":",
"return",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"sending stop signal to task\"",
")",
"self",
".",
"_task",
".",
"cancel",
"(",
")"
] | Send a signal to the main broker task to terminate. You have to check
:attr:`running` and possibly wait for it to become :data:`False` ---
the task takes at least one loop through the event loop to terminate.
It is guarenteed that the task will not attempt to send stanzas over
the exist... | [
"Send",
"a",
"signal",
"to",
"the",
"main",
"broker",
"task",
"to",
"terminate",
".",
"You",
"have",
"to",
"check",
":",
"attr",
":",
"running",
"and",
"possibly",
"wait",
"for",
"it",
"to",
"become",
":",
"data",
":",
"False",
"---",
"the",
"task",
... | python | train |
PredixDev/predixpy | predix/admin/cf/services.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/cf/services.py#L50-L55 | def delete_service_bindings(self, service_name):
"""
Remove service bindings to applications.
"""
instance = self.get_instance(service_name)
return self.api.delete(instance['service_bindings_url']) | [
"def",
"delete_service_bindings",
"(",
"self",
",",
"service_name",
")",
":",
"instance",
"=",
"self",
".",
"get_instance",
"(",
"service_name",
")",
"return",
"self",
".",
"api",
".",
"delete",
"(",
"instance",
"[",
"'service_bindings_url'",
"]",
")"
] | Remove service bindings to applications. | [
"Remove",
"service",
"bindings",
"to",
"applications",
"."
] | python | train |
thecynic/pylutron | pylutron/__init__.py | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L192-L227 | def _parse_area(self, area_xml):
"""Parses an Area tag, which is effectively a room, depending on how the
Lutron controller programming was done."""
area = Area(self._lutron,
name=area_xml.get('Name'),
integration_id=int(area_xml.get('IntegrationID')),
occupan... | [
"def",
"_parse_area",
"(",
"self",
",",
"area_xml",
")",
":",
"area",
"=",
"Area",
"(",
"self",
".",
"_lutron",
",",
"name",
"=",
"area_xml",
".",
"get",
"(",
"'Name'",
")",
",",
"integration_id",
"=",
"int",
"(",
"area_xml",
".",
"get",
"(",
"'Integ... | Parses an Area tag, which is effectively a room, depending on how the
Lutron controller programming was done. | [
"Parses",
"an",
"Area",
"tag",
"which",
"is",
"effectively",
"a",
"room",
"depending",
"on",
"how",
"the",
"Lutron",
"controller",
"programming",
"was",
"done",
"."
] | python | train |
OnroerendErfgoed/crabpy_pyramid | crabpy_pyramid/renderers/crab.py | https://github.com/OnroerendErfgoed/crabpy_pyramid/blob/b727ea55838d71575db96e987b536a0bac9f6a7a/crabpy_pyramid/renderers/crab.py#L252-L264 | def item_deelgemeente_adapter(obj, request):
"""
Adapter for rendering a object of
:class:`crabpy.gateway.crab.Deelgemeente` to json.
"""
return {
'id': obj.id,
'naam': obj.naam,
'gemeente': {
'id': obj.gemeente.id,
'naam': obj.gemeente.naam
}
... | [
"def",
"item_deelgemeente_adapter",
"(",
"obj",
",",
"request",
")",
":",
"return",
"{",
"'id'",
":",
"obj",
".",
"id",
",",
"'naam'",
":",
"obj",
".",
"naam",
",",
"'gemeente'",
":",
"{",
"'id'",
":",
"obj",
".",
"gemeente",
".",
"id",
",",
"'naam'"... | Adapter for rendering a object of
:class:`crabpy.gateway.crab.Deelgemeente` to json. | [
"Adapter",
"for",
"rendering",
"a",
"object",
"of",
":",
"class",
":",
"crabpy",
".",
"gateway",
".",
"crab",
".",
"Deelgemeente",
"to",
"json",
"."
] | python | train |
jtpaasch/simplygithub | simplygithub/internals/api.py | https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/internals/api.py#L46-L71 | def post_merge_request(profile, payload):
"""Do a POST request to Github's API to merge.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect ... | [
"def",
"post_merge_request",
"(",
"profile",
",",
"payload",
")",
":",
"repo",
"=",
"profile",
"[",
"\"repo\"",
"]",
"url",
"=",
"GITHUB_API_BASE_URL",
"+",
"\"repos/\"",
"+",
"repo",
"+",
"\"/merges\"",
"headers",
"=",
"get_headers",
"(",
"profile",
")",
"r... | Do a POST request to Github's API to merge.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
payload
A dict of info... | [
"Do",
"a",
"POST",
"request",
"to",
"Github",
"s",
"API",
"to",
"merge",
"."
] | python | train |
saltstack/salt | salt/states/file.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/file.py#L6945-L7046 | def accumulated(name, filename, text, **kwargs):
'''
Prepare accumulator which can be used in template in file.managed state.
Accumulator dictionary becomes available in template. It can also be used
in file.blockreplace.
name
Accumulator name
filename
Filename which would rece... | [
"def",
"accumulated",
"(",
"name",
",",
"filename",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"if",
"no... | Prepare accumulator which can be used in template in file.managed state.
Accumulator dictionary becomes available in template. It can also be used
in file.blockreplace.
name
Accumulator name
filename
Filename which would receive this accumulator (see file.managed state
document... | [
"Prepare",
"accumulator",
"which",
"can",
"be",
"used",
"in",
"template",
"in",
"file",
".",
"managed",
"state",
".",
"Accumulator",
"dictionary",
"becomes",
"available",
"in",
"template",
".",
"It",
"can",
"also",
"be",
"used",
"in",
"file",
".",
"blockrepl... | python | train |
HumanCellAtlas/cloud-blobstore | cloud_blobstore/s3.py | https://github.com/HumanCellAtlas/cloud-blobstore/blob/b8a60e8e8c0da0e39dda084cb467a34cd2d1ef0a/cloud_blobstore/s3.py#L226-L246 | def get_all_metadata(
self,
bucket: str,
key: str
) -> dict:
"""
Retrieves all the metadata for a given object in a given bucket.
:param bucket: the bucket the object resides in.
:param key: the key of the object for which metadata is being retriev... | [
"def",
"get_all_metadata",
"(",
"self",
",",
"bucket",
":",
"str",
",",
"key",
":",
"str",
")",
"->",
"dict",
":",
"try",
":",
"return",
"self",
".",
"s3_client",
".",
"head_object",
"(",
"Bucket",
"=",
"bucket",
",",
"Key",
"=",
"key",
")",
"except"... | Retrieves all the metadata for a given object in a given bucket.
:param bucket: the bucket the object resides in.
:param key: the key of the object for which metadata is being retrieved.
:return: the metadata | [
"Retrieves",
"all",
"the",
"metadata",
"for",
"a",
"given",
"object",
"in",
"a",
"given",
"bucket",
".",
":",
"param",
"bucket",
":",
"the",
"bucket",
"the",
"object",
"resides",
"in",
".",
":",
"param",
"key",
":",
"the",
"key",
"of",
"the",
"object",... | python | train |
briandilley/ebs-deploy | ebs_deploy/__init__.py | https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L43-L55 | def get(vals, key, default_val=None):
"""
Returns a dictionary value
"""
val = vals
for part in key.split('.'):
if isinstance(val, dict):
val = val.get(part, None)
if val is None:
return default_val
else:
return default_val
retu... | [
"def",
"get",
"(",
"vals",
",",
"key",
",",
"default_val",
"=",
"None",
")",
":",
"val",
"=",
"vals",
"for",
"part",
"in",
"key",
".",
"split",
"(",
"'.'",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"val",
"=",
"val",
".",... | Returns a dictionary value | [
"Returns",
"a",
"dictionary",
"value"
] | python | valid |
geophysics-ubonn/reda | lib/reda/importers/sip04.py | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/importers/sip04.py#L30-L91 | def import_sip04_data(data_filename):
"""Import RELEVANT data from the result files. Refer to the function
:func:`reda.importers.sip04.import_sip04_data_all` for an importer that
imports ALL data.
Exported parameters:
================== ========================================================
... | [
"def",
"import_sip04_data",
"(",
"data_filename",
")",
":",
"df_all",
"=",
"import_sip04_data_all",
"(",
"data_filename",
")",
"columns_to_keep",
"=",
"[",
"'a'",
",",
"'b'",
",",
"'m'",
",",
"'n'",
",",
"'frequency'",
",",
"'Temp_1'",
",",
"'Temp_2'",
",",
... | Import RELEVANT data from the result files. Refer to the function
:func:`reda.importers.sip04.import_sip04_data_all` for an importer that
imports ALL data.
Exported parameters:
================== ========================================================
key description
==========... | [
"Import",
"RELEVANT",
"data",
"from",
"the",
"result",
"files",
".",
"Refer",
"to",
"the",
"function",
":",
"func",
":",
"reda",
".",
"importers",
".",
"sip04",
".",
"import_sip04_data_all",
"for",
"an",
"importer",
"that",
"imports",
"ALL",
"data",
"."
] | python | train |
mbedmicro/pyOCD | pyocd/probe/stlink/detect/linux.py | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/probe/stlink/detect/linux.py#L87-L98 | def _fat_mounts(self):
"""! Lists mounted devices with vfat file system (potential mbeds)
@result Returns list of all mounted vfat devices
@details Uses Linux shell command: 'mount'
"""
_stdout, _, retval = self._run_cli_process("mount")
if not retval:
for lin... | [
"def",
"_fat_mounts",
"(",
"self",
")",
":",
"_stdout",
",",
"_",
",",
"retval",
"=",
"self",
".",
"_run_cli_process",
"(",
"\"mount\"",
")",
"if",
"not",
"retval",
":",
"for",
"line",
"in",
"_stdout",
".",
"splitlines",
"(",
")",
":",
"if",
"b\"vfat\"... | ! Lists mounted devices with vfat file system (potential mbeds)
@result Returns list of all mounted vfat devices
@details Uses Linux shell command: 'mount' | [
"!",
"Lists",
"mounted",
"devices",
"with",
"vfat",
"file",
"system",
"(",
"potential",
"mbeds",
")"
] | python | train |
addisonlynch/iexfinance | iexfinance/__init__.py | https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L136-L142 | def get_market_last(symbols=None, **kwargs):
"""
MOVED to iexfinance.iexdata.get_last
"""
import warnings
warnings.warn(WNG_MSG % ("get_market_last", "iexdata.get_last"))
return Last(symbols, **kwargs).fetch() | [
"def",
"get_market_last",
"(",
"symbols",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"WNG_MSG",
"%",
"(",
"\"get_market_last\"",
",",
"\"iexdata.get_last\"",
")",
")",
"return",
"Last",
"(",
"symbols",... | MOVED to iexfinance.iexdata.get_last | [
"MOVED",
"to",
"iexfinance",
".",
"iexdata",
".",
"get_last"
] | python | train |
ravenac95/lxc4u | lxc4u/lxc.py | https://github.com/ravenac95/lxc4u/blob/4b5a9c8e25af97e5637db2f4c0c67d319ab0ed32/lxc4u/lxc.py#L56-L60 | def start(self):
"""Start this LXC"""
if self.status == 'RUNNING':
raise LXCAlreadyStarted(self.name)
self._service.start(self.name) | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"==",
"'RUNNING'",
":",
"raise",
"LXCAlreadyStarted",
"(",
"self",
".",
"name",
")",
"self",
".",
"_service",
".",
"start",
"(",
"self",
".",
"name",
")"
] | Start this LXC | [
"Start",
"this",
"LXC"
] | python | train |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L93-L124 | def oauth_manager(self, oauth_manager):
"""Use the oauth manager to enable oauth for API
:param oauth_manager: the oauth manager
"""
@self.app.before_request
def before_request():
endpoint = request.endpoint
resource = self.app.view_functions[endpoint].vi... | [
"def",
"oauth_manager",
"(",
"self",
",",
"oauth_manager",
")",
":",
"@",
"self",
".",
"app",
".",
"before_request",
"def",
"before_request",
"(",
")",
":",
"endpoint",
"=",
"request",
".",
"endpoint",
"resource",
"=",
"self",
".",
"app",
".",
"view_functi... | Use the oauth manager to enable oauth for API
:param oauth_manager: the oauth manager | [
"Use",
"the",
"oauth",
"manager",
"to",
"enable",
"oauth",
"for",
"API"
] | python | train |
oceanprotocol/squid-py | squid_py/keeper/diagnostics.py | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/diagnostics.py#L19-L66 | def verify_contracts():
"""
Verify that the contracts are deployed correctly in the network.
:raise Exception: raise exception if the contracts are not deployed correctly.
"""
artifacts_path = ConfigProvider.get_config().keeper_path
logger.info(f'Keeper contract artifact... | [
"def",
"verify_contracts",
"(",
")",
":",
"artifacts_path",
"=",
"ConfigProvider",
".",
"get_config",
"(",
")",
".",
"keeper_path",
"logger",
".",
"info",
"(",
"f'Keeper contract artifacts (JSON abi files) at: {artifacts_path}'",
")",
"if",
"os",
".",
"environ",
".",
... | Verify that the contracts are deployed correctly in the network.
:raise Exception: raise exception if the contracts are not deployed correctly. | [
"Verify",
"that",
"the",
"contracts",
"are",
"deployed",
"correctly",
"in",
"the",
"network",
"."
] | python | train |
samjabrahams/anchorhub | anchorhub/util/hasattrs.py | https://github.com/samjabrahams/anchorhub/blob/5ade359b08297d4003a5f477389c01de9e634b54/anchorhub/util/hasattrs.py#L8-L21 | def hasattrs(object, *names):
"""
Takes in an object and a variable length amount of named attributes,
and checks to see if the object has each property. If any of the
attributes are missing, this returns false.
:param object: an object that may or may not contain the listed attributes
:param n... | [
"def",
"hasattrs",
"(",
"object",
",",
"*",
"names",
")",
":",
"for",
"name",
"in",
"names",
":",
"if",
"not",
"hasattr",
"(",
"object",
",",
"name",
")",
":",
"return",
"False",
"return",
"True"
] | Takes in an object and a variable length amount of named attributes,
and checks to see if the object has each property. If any of the
attributes are missing, this returns false.
:param object: an object that may or may not contain the listed attributes
:param names: a variable amount of attribute names... | [
"Takes",
"in",
"an",
"object",
"and",
"a",
"variable",
"length",
"amount",
"of",
"named",
"attributes",
"and",
"checks",
"to",
"see",
"if",
"the",
"object",
"has",
"each",
"property",
".",
"If",
"any",
"of",
"the",
"attributes",
"are",
"missing",
"this",
... | python | train |
msmbuilder/msmbuilder | msmbuilder/tpt/path.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/tpt/path.py#L195-L318 | def paths(sources, sinks, net_flux, remove_path='subtract',
num_paths=np.inf, flux_cutoff=(1-1E-10)):
"""
Get the top N paths by iteratively performing Dijkstra's
algorithm.
Parameters
----------
sources : array_like, int
One-dimensional list of nodes to define the source stat... | [
"def",
"paths",
"(",
"sources",
",",
"sinks",
",",
"net_flux",
",",
"remove_path",
"=",
"'subtract'",
",",
"num_paths",
"=",
"np",
".",
"inf",
",",
"flux_cutoff",
"=",
"(",
"1",
"-",
"1E-10",
")",
")",
":",
"if",
"not",
"callable",
"(",
"remove_path",
... | Get the top N paths by iteratively performing Dijkstra's
algorithm.
Parameters
----------
sources : array_like, int
One-dimensional list of nodes to define the source states.
sinks : array_like, int
One-dimensional list of nodes to define the sink states.
net_flux : np.ndarray
... | [
"Get",
"the",
"top",
"N",
"paths",
"by",
"iteratively",
"performing",
"Dijkstra",
"s",
"algorithm",
"."
] | python | train |
avalente/appmetrics | appmetrics/statistics.py | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L458-L484 | def get_histogram(data):
"""Return the histogram relative to the given data
Assume that the data are already sorted
"""
count = len(data)
if count < 2:
raise StatisticsError('Too few data points ({}) for get_histogram'.format(count))
min_ = data[0]
max_ = data[-1]
std = stde... | [
"def",
"get_histogram",
"(",
"data",
")",
":",
"count",
"=",
"len",
"(",
"data",
")",
"if",
"count",
"<",
"2",
":",
"raise",
"StatisticsError",
"(",
"'Too few data points ({}) for get_histogram'",
".",
"format",
"(",
"count",
")",
")",
"min_",
"=",
"data",
... | Return the histogram relative to the given data
Assume that the data are already sorted | [
"Return",
"the",
"histogram",
"relative",
"to",
"the",
"given",
"data"
] | python | train |
log2timeline/plaso | plaso/parsers/esedb.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/esedb.py#L63-L104 | def ParseFileObject(self, parser_mediator, file_object):
"""Parses an ESE database file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object.
"""
ese... | [
"def",
"ParseFileObject",
"(",
"self",
",",
"parser_mediator",
",",
"file_object",
")",
":",
"esedb_file",
"=",
"pyesedb",
".",
"file",
"(",
")",
"try",
":",
"esedb_file",
".",
"open_file_object",
"(",
"file_object",
")",
"except",
"IOError",
"as",
"exception"... | Parses an ESE database file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object. | [
"Parses",
"an",
"ESE",
"database",
"file",
"-",
"like",
"object",
"."
] | python | train |
spotify/luigi | luigi/setup_logging.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/setup_logging.py#L157-L168 | def _conf(cls, opts):
"""Setup logging via ini-file from logging_conf_file option."""
if not opts.logging_conf_file:
return False
if not os.path.exists(opts.logging_conf_file):
# FileNotFoundError added only in Python 3.3
# https://docs.python.org/3/whatsnew/... | [
"def",
"_conf",
"(",
"cls",
",",
"opts",
")",
":",
"if",
"not",
"opts",
".",
"logging_conf_file",
":",
"return",
"False",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"opts",
".",
"logging_conf_file",
")",
":",
"# FileNotFoundError added only in Pytho... | Setup logging via ini-file from logging_conf_file option. | [
"Setup",
"logging",
"via",
"ini",
"-",
"file",
"from",
"logging_conf_file",
"option",
"."
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/aux_funcs.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/aux_funcs.py#L331-L336 | def group_files_by_size_simple(fileslist, nbgroups): # pragma: no cover
""" Simple and fast files grouping strategy: just order by size, and group files n-by-n, so that files with the closest sizes are grouped together.
In this strategy, there is only one file per subgroup, and thus there will often be remaini... | [
"def",
"group_files_by_size_simple",
"(",
"fileslist",
",",
"nbgroups",
")",
":",
"# pragma: no cover",
"ford",
"=",
"sorted",
"(",
"fileslist",
".",
"iteritems",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
",",
"reverse",
"=",
"Tr... | Simple and fast files grouping strategy: just order by size, and group files n-by-n, so that files with the closest sizes are grouped together.
In this strategy, there is only one file per subgroup, and thus there will often be remaining space left because there is no filling strategy here, but it's very fast. | [
"Simple",
"and",
"fast",
"files",
"grouping",
"strategy",
":",
"just",
"order",
"by",
"size",
"and",
"group",
"files",
"n",
"-",
"by",
"-",
"n",
"so",
"that",
"files",
"with",
"the",
"closest",
"sizes",
"are",
"grouped",
"together",
".",
"In",
"this",
... | python | train |
elliterate/capybara.py | capybara/server.py | https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/server.py#L68-L98 | def boot(self):
"""
Boots a server for the app, if it isn't already booted.
Returns:
Server: This server.
"""
if not self.responsive:
# Remember the port so we can reuse it if we try to serve this same app again.
type(self)._ports[self.port_k... | [
"def",
"boot",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"responsive",
":",
"# Remember the port so we can reuse it if we try to serve this same app again.",
"type",
"(",
"self",
")",
".",
"_ports",
"[",
"self",
".",
"port_key",
"]",
"=",
"self",
".",
"po... | Boots a server for the app, if it isn't already booted.
Returns:
Server: This server. | [
"Boots",
"a",
"server",
"for",
"the",
"app",
"if",
"it",
"isn",
"t",
"already",
"booted",
"."
] | python | test |
6809/MC6809 | MC6809/components/mc6809_ops_logic.py | https://github.com/6809/MC6809/blob/6ba2f5106df46689017b5d0b6d84d43b7ee6a240/MC6809/components/mc6809_ops_logic.py#L172-L182 | def instruction_LSL_memory(self, opcode, ea, m):
"""
Logical shift left memory location / Arithmetic shift of memory left
"""
r = self.LSL(m)
# log.debug("$%x LSL memory value $%x << 1 = $%x and write it to $%x \t| %s" % (
# self.program_counter,
# m, r, ea,
... | [
"def",
"instruction_LSL_memory",
"(",
"self",
",",
"opcode",
",",
"ea",
",",
"m",
")",
":",
"r",
"=",
"self",
".",
"LSL",
"(",
"m",
")",
"# log.debug(\"$%x LSL memory value $%x << 1 = $%x and write it to $%x \\t| %s\" % (",
"# self.program_counter,",
"# ... | Logical shift left memory location / Arithmetic shift of memory left | [
"Logical",
"shift",
"left",
"memory",
"location",
"/",
"Arithmetic",
"shift",
"of",
"memory",
"left"
] | python | train |
ska-sa/katversion | katversion/build.py | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/build.py#L32-L58 | def patch_init_py(base_dir, name, version):
"""Patch __init__.py to remove version check and append hard-coded version."""
# Ensure main package dir is there (may be absent in script-only packages)
package_dir = os.path.join(base_dir, name)
if not os.path.isdir(package_dir):
os.makedirs(package_... | [
"def",
"patch_init_py",
"(",
"base_dir",
",",
"name",
",",
"version",
")",
":",
"# Ensure main package dir is there (may be absent in script-only packages)",
"package_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base_dir",
",",
"name",
")",
"if",
"not",
"os",
... | Patch __init__.py to remove version check and append hard-coded version. | [
"Patch",
"__init__",
".",
"py",
"to",
"remove",
"version",
"check",
"and",
"append",
"hard",
"-",
"coded",
"version",
"."
] | python | train |
spacetelescope/synphot_refactor | synphot/utils.py | https://github.com/spacetelescope/synphot_refactor/blob/9c064f3cff0c41dd8acadc0f67c6350931275b9f/synphot/utils.py#L54-L73 | def validate_totalflux(totalflux):
"""Check integrated flux for invalid values.
Parameters
----------
totalflux : float
Integrated flux.
Raises
------
synphot.exceptions.SynphotError
Input is zero, negative, or not a number.
"""
if totalflux <= 0.0:
raise e... | [
"def",
"validate_totalflux",
"(",
"totalflux",
")",
":",
"if",
"totalflux",
"<=",
"0.0",
":",
"raise",
"exceptions",
".",
"SynphotError",
"(",
"'Integrated flux is <= 0'",
")",
"elif",
"np",
".",
"isnan",
"(",
"totalflux",
")",
":",
"raise",
"exceptions",
".",... | Check integrated flux for invalid values.
Parameters
----------
totalflux : float
Integrated flux.
Raises
------
synphot.exceptions.SynphotError
Input is zero, negative, or not a number. | [
"Check",
"integrated",
"flux",
"for",
"invalid",
"values",
"."
] | python | train |
etingof/pysnmp | pysnmp/entity/rfc3413/cmdrsp.py | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/entity/rfc3413/cmdrsp.py#L339-L375 | def _getManagedObjectsInstances(self, varBinds, **context):
"""Iterate over Managed Objects fulfilling SNMP query.
Returns
-------
:py:class:`list` - List of Managed Objects Instances to respond with or
`None` to indicate that not all objects have been gathered
s... | [
"def",
"_getManagedObjectsInstances",
"(",
"self",
",",
"varBinds",
",",
"*",
"*",
"context",
")",
":",
"rspVarBinds",
"=",
"context",
"[",
"'rspVarBinds'",
"]",
"varBindsMap",
"=",
"context",
"[",
"'varBindsMap'",
"]",
"rtrVarBinds",
"=",
"[",
"]",
"for",
"... | Iterate over Managed Objects fulfilling SNMP query.
Returns
-------
:py:class:`list` - List of Managed Objects Instances to respond with or
`None` to indicate that not all objects have been gathered
so far. | [
"Iterate",
"over",
"Managed",
"Objects",
"fulfilling",
"SNMP",
"query",
"."
] | python | train |
twilio/twilio-python | twilio/rest/api/v2010/account/signing_key.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/signing_key.py#L168-L177 | def get_instance(self, payload):
"""
Build an instance of SigningKeyInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance
:rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance
""... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"SigningKeyInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")"
] | Build an instance of SigningKeyInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance
:rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance | [
"Build",
"an",
"instance",
"of",
"SigningKeyInstance"
] | python | train |
INM-6/hybridLFPy | examples/Hagen_et_al_2016_cercor/plot_methods.py | https://github.com/INM-6/hybridLFPy/blob/c38bdf38982c4624c2f70caeb50c40f1d5980abd/examples/Hagen_et_al_2016_cercor/plot_methods.py#L738-L853 | def plot_signal_sum(ax, params, fname='LFPsum.h5', unit='mV', scaling_factor=1.,
ylabels=True, scalebar=True, vlimround=None,
T=[800, 1000], ylim=[-1500, 0], color='k', fancy=False,
label='', transient=200, clip_on=False, rasterized=True,
*... | [
"def",
"plot_signal_sum",
"(",
"ax",
",",
"params",
",",
"fname",
"=",
"'LFPsum.h5'",
",",
"unit",
"=",
"'mV'",
",",
"scaling_factor",
"=",
"1.",
",",
"ylabels",
"=",
"True",
",",
"scalebar",
"=",
"True",
",",
"vlimround",
"=",
"None",
",",
"T",
"=",
... | on axes plot the summed LFP contributions
args:
::
ax : matplotlib.axes.AxesSubplot object
fname : str/np.ndarray, path to h5 file or ndim=2 numpy.ndarray
unit : str, scalebar unit
scaling_factor : float, scaling factor (e.g. to scale 10% data set up)
ylabe... | [
"on",
"axes",
"plot",
"the",
"summed",
"LFP",
"contributions",
"args",
":",
"::",
"ax",
":",
"matplotlib",
".",
"axes",
".",
"AxesSubplot",
"object",
"fname",
":",
"str",
"/",
"np",
".",
"ndarray",
"path",
"to",
"h5",
"file",
"or",
"ndim",
"=",
"2",
... | python | train |
ajyoon/blur | examples/softlife/softlife.py | https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/examples/softlife/softlife.py#L89-L97 | def draw_canvas():
"""Render the tkinter canvas based on the state of ``world``"""
for x in range(len(world)):
for y in range(len(world[x])):
if world[x][y].value:
color = world[x][y].color_alive.get_as_hex()
else:
color = world[x][y].color_dead.ge... | [
"def",
"draw_canvas",
"(",
")",
":",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"world",
")",
")",
":",
"for",
"y",
"in",
"range",
"(",
"len",
"(",
"world",
"[",
"x",
"]",
")",
")",
":",
"if",
"world",
"[",
"x",
"]",
"[",
"y",
"]",
".",
... | Render the tkinter canvas based on the state of ``world`` | [
"Render",
"the",
"tkinter",
"canvas",
"based",
"on",
"the",
"state",
"of",
"world"
] | python | train |
secdev/scapy | scapy/layers/tls/record_tls13.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/tls/record_tls13.py#L172-L179 | def _tls_auth_encrypt(self, s):
"""
Return the TLSCiphertext.encrypted_record for AEAD ciphers.
"""
wcs = self.tls_session.wcs
write_seq_num = struct.pack("!Q", wcs.seq_num)
wcs.seq_num += 1
return wcs.cipher.auth_encrypt(s, b"", write_seq_num) | [
"def",
"_tls_auth_encrypt",
"(",
"self",
",",
"s",
")",
":",
"wcs",
"=",
"self",
".",
"tls_session",
".",
"wcs",
"write_seq_num",
"=",
"struct",
".",
"pack",
"(",
"\"!Q\"",
",",
"wcs",
".",
"seq_num",
")",
"wcs",
".",
"seq_num",
"+=",
"1",
"return",
... | Return the TLSCiphertext.encrypted_record for AEAD ciphers. | [
"Return",
"the",
"TLSCiphertext",
".",
"encrypted_record",
"for",
"AEAD",
"ciphers",
"."
] | python | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L903-L913 | def _parse_tag(self):
"""Parse an HTML tag at the head of the wikicode string."""
reset = self._head
self._head += 1
try:
tag = self._really_parse_tag()
except BadRoute:
self._head = reset
self._emit_text("<")
else:
self._em... | [
"def",
"_parse_tag",
"(",
"self",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"self",
".",
"_head",
"+=",
"1",
"try",
":",
"tag",
"=",
"self",
".",
"_really_parse_tag",
"(",
")",
"except",
"BadRoute",
":",
"self",
".",
"_head",
"=",
"reset",
"self"... | Parse an HTML tag at the head of the wikicode string. | [
"Parse",
"an",
"HTML",
"tag",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
] | python | train |
SALib/SALib | src/SALib/analyze/rbd_fast.py | https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/analyze/rbd_fast.py#L85-L99 | def permute_outputs(Y, X):
"""
Permute the output according to one of the inputs as in [_2]
References
----------
.. [2] Elmar Plischke (2010) "An effective algorithm for computing global
sensitivity indices (EASI) Reliability Engineering & System Safety",
95:4, 354-360.... | [
"def",
"permute_outputs",
"(",
"Y",
",",
"X",
")",
":",
"permutation_index",
"=",
"np",
".",
"argsort",
"(",
"X",
")",
"permutation_index",
"=",
"np",
".",
"concatenate",
"(",
"[",
"permutation_index",
"[",
":",
":",
"2",
"]",
",",
"permutation_index",
"... | Permute the output according to one of the inputs as in [_2]
References
----------
.. [2] Elmar Plischke (2010) "An effective algorithm for computing global
sensitivity indices (EASI) Reliability Engineering & System Safety",
95:4, 354-360. doi:10.1016/j.ress.2009.11.005 | [
"Permute",
"the",
"output",
"according",
"to",
"one",
"of",
"the",
"inputs",
"as",
"in",
"[",
"_2",
"]",
"References",
"----------",
"..",
"[",
"2",
"]",
"Elmar",
"Plischke",
"(",
"2010",
")",
"An",
"effective",
"algorithm",
"for",
"computing",
"global",
... | python | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/algorithmic_math.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L439-L477 | def algebra_inverse(alphabet_size=26, min_depth=0, max_depth=2,
nbr_cases=10000):
"""Generate the algebra inverse dataset.
Each sample is a symbolic math equation involving unknown variables. The
task is to solve for the given variable. The target is the resulting
expression.
Args:
a... | [
"def",
"algebra_inverse",
"(",
"alphabet_size",
"=",
"26",
",",
"min_depth",
"=",
"0",
",",
"max_depth",
"=",
"2",
",",
"nbr_cases",
"=",
"10000",
")",
":",
"if",
"max_depth",
"<",
"min_depth",
":",
"raise",
"ValueError",
"(",
"\"max_depth must be greater than... | Generate the algebra inverse dataset.
Each sample is a symbolic math equation involving unknown variables. The
task is to solve for the given variable. The target is the resulting
expression.
Args:
alphabet_size: How many possible variables there are. Max 52.
min_depth: Minimum depth of the expression... | [
"Generate",
"the",
"algebra",
"inverse",
"dataset",
"."
] | python | train |
scot-dev/scot | scot/plainica.py | https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/plainica.py#L29-L77 | def plainica(x, reducedim=0.99, backend=None, random_state=None):
""" Source decomposition with ICA.
Apply ICA to the data x, with optional PCA dimensionality reduction.
Parameters
----------
x : array, shape (n_trials, n_channels, n_samples) or (n_channels, n_samples)
data set
reduced... | [
"def",
"plainica",
"(",
"x",
",",
"reducedim",
"=",
"0.99",
",",
"backend",
"=",
"None",
",",
"random_state",
"=",
"None",
")",
":",
"x",
"=",
"atleast_3d",
"(",
"x",
")",
"t",
",",
"m",
",",
"l",
"=",
"np",
".",
"shape",
"(",
"x",
")",
"if",
... | Source decomposition with ICA.
Apply ICA to the data x, with optional PCA dimensionality reduction.
Parameters
----------
x : array, shape (n_trials, n_channels, n_samples) or (n_channels, n_samples)
data set
reducedim : {int, float, 'no_pca'}, optional
A number of less than 1 in i... | [
"Source",
"decomposition",
"with",
"ICA",
"."
] | python | train |
rackerlabs/simpl | simpl/config.py | https://github.com/rackerlabs/simpl/blob/60ed3336a931cd6a7a7246e60f26165d9dc7c99c/simpl/config.py#L378-L382 | def init(cls, *args, **kwargs):
"""Initialize the config like as you would a regular dict."""
instance = cls()
instance._values.update(dict(*args, **kwargs))
return instance | [
"def",
"init",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"cls",
"(",
")",
"instance",
".",
"_values",
".",
"update",
"(",
"dict",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"instance"
] | Initialize the config like as you would a regular dict. | [
"Initialize",
"the",
"config",
"like",
"as",
"you",
"would",
"a",
"regular",
"dict",
"."
] | python | train |
sony/nnabla | python/src/nnabla/functions.py | https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/functions.py#L62-L109 | def max(x, axis=None, keepdims=False, with_index=False, only_index=False):
"""Reduce the input N-D array `x` along the given `axis` using the max
operation. The `axis` argument may be a single integer to reduce
over one axis, a tuple of integers to reduce over multiple axes,
or ``None`` to reduce over a... | [
"def",
"max",
"(",
"x",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"False",
",",
"with_index",
"=",
"False",
",",
"only_index",
"=",
"False",
")",
":",
"from",
".",
"function_bases",
"import",
"max",
"as",
"max_base",
"if",
"axis",
"is",
"None",
... | Reduce the input N-D array `x` along the given `axis` using the max
operation. The `axis` argument may be a single integer to reduce
over one axis, a tuple of integers to reduce over multiple axes,
or ``None`` to reduce over all axes. If `keepdims` is ``True``,
the output will keep all reduced dimension... | [
"Reduce",
"the",
"input",
"N",
"-",
"D",
"array",
"x",
"along",
"the",
"given",
"axis",
"using",
"the",
"max",
"operation",
".",
"The",
"axis",
"argument",
"may",
"be",
"a",
"single",
"integer",
"to",
"reduce",
"over",
"one",
"axis",
"a",
"tuple",
"of"... | python | train |
classam/silly | silly/main.py | https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L691-L730 | def datetime(past=True, random=random):
"""
Returns a random datetime from the past... or the future!
>>> mock_random.seed(0)
>>> datetime(random=mock_random).isoformat()
'1950-02-03T03:04:05'
"""
def year():
if past:
return random.choice(range(1950,2005))
else... | [
"def",
"datetime",
"(",
"past",
"=",
"True",
",",
"random",
"=",
"random",
")",
":",
"def",
"year",
"(",
")",
":",
"if",
"past",
":",
"return",
"random",
".",
"choice",
"(",
"range",
"(",
"1950",
",",
"2005",
")",
")",
"else",
":",
"return",
"_da... | Returns a random datetime from the past... or the future!
>>> mock_random.seed(0)
>>> datetime(random=mock_random).isoformat()
'1950-02-03T03:04:05' | [
"Returns",
"a",
"random",
"datetime",
"from",
"the",
"past",
"...",
"or",
"the",
"future!"
] | python | train |
PierreRust/apigpio | apigpio/apigpio.py | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L767-L782 | def set_bank_1(self, bits):
"""
Sets gpios 0-31 if the corresponding bit in bits is set.
bits:= a 32 bit mask with 1 set if the corresponding gpio is
to be set.
A returned status of PI_SOME_PERMITTED indicates that the user
is not allowed to write to one or more of... | [
"def",
"set_bank_1",
"(",
"self",
",",
"bits",
")",
":",
"res",
"=",
"yield",
"from",
"self",
".",
"_pigpio_aio_command",
"(",
"_PI_CMD_BS1",
",",
"bits",
",",
"0",
")",
"return",
"_u2i",
"(",
"res",
")"
] | Sets gpios 0-31 if the corresponding bit in bits is set.
bits:= a 32 bit mask with 1 set if the corresponding gpio is
to be set.
A returned status of PI_SOME_PERMITTED indicates that the user
is not allowed to write to one or more of the gpios.
...
pi.set_bank_1(i... | [
"Sets",
"gpios",
"0",
"-",
"31",
"if",
"the",
"corresponding",
"bit",
"in",
"bits",
"is",
"set",
"."
] | python | train |
Ezhil-Language-Foundation/open-tamil | tamil/utf8.py | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/utf8.py#L33-L37 | def to_unicode_repr( _letter ):
""" helpful in situations where browser/app may recognize Unicode encoding
in the \u0b8e type syntax but not actual unicode glyph/code-point"""
# Python 2-3 compatible
return u"u'"+ u"".join( [ u"\\u%04x"%ord(l) for l in _letter ] ) + u"'" | [
"def",
"to_unicode_repr",
"(",
"_letter",
")",
":",
"# Python 2-3 compatible",
"return",
"u\"u'\"",
"+",
"u\"\"",
".",
"join",
"(",
"[",
"u\"\\\\u%04x\"",
"%",
"ord",
"(",
"l",
")",
"for",
"l",
"in",
"_letter",
"]",
")",
"+",
"u\"'\""
] | helpful in situations where browser/app may recognize Unicode encoding
in the \u0b8e type syntax but not actual unicode glyph/code-point | [
"helpful",
"in",
"situations",
"where",
"browser",
"/",
"app",
"may",
"recognize",
"Unicode",
"encoding",
"in",
"the",
"\\",
"u0b8e",
"type",
"syntax",
"but",
"not",
"actual",
"unicode",
"glyph",
"/",
"code",
"-",
"point"
] | python | train |
necaris/python3-openid | openid/consumer/consumer.py | https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/consumer/consumer.py#L1187-L1223 | def _negotiateAssociation(self, endpoint):
"""Make association requests to the server, attempting to
create a new association.
@returns: a new association object
@rtype: L{openid.association.Association}
"""
# Get our preferred session/association type from the negotiat... | [
"def",
"_negotiateAssociation",
"(",
"self",
",",
"endpoint",
")",
":",
"# Get our preferred session/association type from the negotiatior.",
"assoc_type",
",",
"session_type",
"=",
"self",
".",
"negotiator",
".",
"getAllowedType",
"(",
")",
"try",
":",
"assoc",
"=",
... | Make association requests to the server, attempting to
create a new association.
@returns: a new association object
@rtype: L{openid.association.Association} | [
"Make",
"association",
"requests",
"to",
"the",
"server",
"attempting",
"to",
"create",
"a",
"new",
"association",
"."
] | python | train |
JnyJny/Geometry | Geometry/ellipse.py | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L118-L122 | def xAxisIsMinor(self):
'''
Returns True if the minor axis is parallel to the X axis, boolean.
'''
return min(self.radius.x, self.radius.y) == self.radius.x | [
"def",
"xAxisIsMinor",
"(",
"self",
")",
":",
"return",
"min",
"(",
"self",
".",
"radius",
".",
"x",
",",
"self",
".",
"radius",
".",
"y",
")",
"==",
"self",
".",
"radius",
".",
"x"
] | Returns True if the minor axis is parallel to the X axis, boolean. | [
"Returns",
"True",
"if",
"the",
"minor",
"axis",
"is",
"parallel",
"to",
"the",
"X",
"axis",
"boolean",
"."
] | python | train |
ly0/baidupcsapi | baidupcsapi/api.py | https://github.com/ly0/baidupcsapi/blob/6f6feeef0767a75b3b968924727460eb09242d76/baidupcsapi/api.py#L1348-L1393 | def share(self, file_ids, pwd=None, **kwargs):
"""
创建一个文件的分享链接
:param file_ids: 要分享的文件fid列表
:type file_ids: list
:param pwd: 分享密码,没有则没有密码
:type pwd: str
:return: requests.Response 对象
.. note::
返回正确
{
... | [
"def",
"share",
"(",
"self",
",",
"file_ids",
",",
"pwd",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"pwd",
":",
"data",
"=",
"{",
"'fid_list'",
":",
"json",
".",
"dumps",
"(",
"[",
"int",
"(",
"fid",
")",
"for",
"fid",
"in",
"file_i... | 创建一个文件的分享链接
:param file_ids: 要分享的文件fid列表
:type file_ids: list
:param pwd: 分享密码,没有则没有密码
:type pwd: str
:return: requests.Response 对象
.. note::
返回正确
{
"errno": 0,
"request_id": 请求识别... | [
"创建一个文件的分享链接"
] | python | train |
ereOn/azmq | azmq/socket.py | https://github.com/ereOn/azmq/blob/9f40d6d721eea7f7659ec6cc668811976db59854/azmq/socket.py#L445-L456 | async def _fair_recv(self):
"""
Receive from all the existing peers, rotating the list of peers every
time.
:returns: The frames.
"""
with await self._read_lock:
peer = await self._fair_get_in_peer()
result = peer.inbox.read_nowait()
retu... | [
"async",
"def",
"_fair_recv",
"(",
"self",
")",
":",
"with",
"await",
"self",
".",
"_read_lock",
":",
"peer",
"=",
"await",
"self",
".",
"_fair_get_in_peer",
"(",
")",
"result",
"=",
"peer",
".",
"inbox",
".",
"read_nowait",
"(",
")",
"return",
"result"
... | Receive from all the existing peers, rotating the list of peers every
time.
:returns: The frames. | [
"Receive",
"from",
"all",
"the",
"existing",
"peers",
"rotating",
"the",
"list",
"of",
"peers",
"every",
"time",
"."
] | python | train |
icgood/pymap | pymap/parsing/primitives.py | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/primitives.py#L188-L227 | def build(cls, value: object, binary: bool = False,
fallback: object = None) -> Union[Nil, 'String']:
"""Produce either a :class:`QuotedString` or :class:`LiteralString`
based on the contents of ``data``. This is useful to improve
readability of response data.
Args:
... | [
"def",
"build",
"(",
"cls",
",",
"value",
":",
"object",
",",
"binary",
":",
"bool",
"=",
"False",
",",
"fallback",
":",
"object",
"=",
"None",
")",
"->",
"Union",
"[",
"Nil",
",",
"'String'",
"]",
":",
"if",
"value",
"is",
"None",
":",
"if",
"fa... | Produce either a :class:`QuotedString` or :class:`LiteralString`
based on the contents of ``data``. This is useful to improve
readability of response data.
Args:
value: The string to serialize.
binary: True if the string should be transmitted as binary.
fallb... | [
"Produce",
"either",
"a",
":",
"class",
":",
"QuotedString",
"or",
":",
"class",
":",
"LiteralString",
"based",
"on",
"the",
"contents",
"of",
"data",
".",
"This",
"is",
"useful",
"to",
"improve",
"readability",
"of",
"response",
"data",
"."
] | python | train |
apache/incubator-mxnet | example/gluon/lipnet/utils/align.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/align.py#L36-L52 | def build(self, align_path):
"""
Build the align array
"""
file = open(align_path, 'r')
lines = file.readlines()
file.close()
# words: list([op, ed, word])
words = []
for line in lines:
_op, _ed, word = line.strip().split(' ')
... | [
"def",
"build",
"(",
"self",
",",
"align_path",
")",
":",
"file",
"=",
"open",
"(",
"align_path",
",",
"'r'",
")",
"lines",
"=",
"file",
".",
"readlines",
"(",
")",
"file",
".",
"close",
"(",
")",
"# words: list([op, ed, word])",
"words",
"=",
"[",
"]"... | Build the align array | [
"Build",
"the",
"align",
"array"
] | python | train |
HewlettPackard/python-hpOneView | hpOneView/resources/uncategorized/os_deployment_servers.py | https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/uncategorized/os_deployment_servers.py#L134-L151 | def update(self, resource, force=False, timeout=-1):
"""
Updates the Deployment Server resource. The properties that are omitted (not included as part
of the request body) are ignored.
Args:
resource (dict): Object to update.
force:
If set to true... | [
"def",
"update",
"(",
"self",
",",
"resource",
",",
"force",
"=",
"False",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"return",
"self",
".",
"_client",
".",
"update",
"(",
"resource",
",",
"timeout",
"=",
"timeout",
",",
"force",
"=",
"force",
")"
] | Updates the Deployment Server resource. The properties that are omitted (not included as part
of the request body) are ignored.
Args:
resource (dict): Object to update.
force:
If set to true, the operation completes despite any problems with network connectivity ... | [
"Updates",
"the",
"Deployment",
"Server",
"resource",
".",
"The",
"properties",
"that",
"are",
"omitted",
"(",
"not",
"included",
"as",
"part",
"of",
"the",
"request",
"body",
")",
"are",
"ignored",
"."
] | python | train |
saltstack/salt | salt/renderers/stateconf.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/stateconf.py#L310-L331 | def nvlist(thelist, names=None):
'''
Given a list of items::
- whatever
- name1: value1
- name2:
- key: value
- key: value
return a generator that yields each (item, key, value) tuple, skipping
items that are not name-value's(dictionaries) or those not in th... | [
"def",
"nvlist",
"(",
"thelist",
",",
"names",
"=",
"None",
")",
":",
"# iterate over the list under the state dict.",
"for",
"nvitem",
"in",
"thelist",
":",
"if",
"isinstance",
"(",
"nvitem",
",",
"dict",
")",
":",
"# then nvitem is a name-value item(a dict) of the l... | Given a list of items::
- whatever
- name1: value1
- name2:
- key: value
- key: value
return a generator that yields each (item, key, value) tuple, skipping
items that are not name-value's(dictionaries) or those not in the
list of matching names. The item in the... | [
"Given",
"a",
"list",
"of",
"items",
"::"
] | python | train |
nerdvegas/rez | src/build_utils/virtualenv/virtualenv.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/virtualenv/virtualenv.py#L913-L937 | def find_wheels(projects, search_dirs):
"""Find wheels from which we can import PROJECTS.
Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return
a list of the first wheel found for each PROJECT
"""
wheels = []
# Look through SEARCH_DIRS for the first suitable wheel. Don't bothe... | [
"def",
"find_wheels",
"(",
"projects",
",",
"search_dirs",
")",
":",
"wheels",
"=",
"[",
"]",
"# Look through SEARCH_DIRS for the first suitable wheel. Don't bother",
"# about version checking here, as this is simply to get something we can",
"# then use to install the correct version.",... | Find wheels from which we can import PROJECTS.
Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return
a list of the first wheel found for each PROJECT | [
"Find",
"wheels",
"from",
"which",
"we",
"can",
"import",
"PROJECTS",
"."
] | python | train |
cloud-custodian/cloud-custodian | c7n/utils.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L242-L251 | def query_instances(session, client=None, **query):
"""Return a list of ec2 instances for the query.
"""
if client is None:
client = session.client('ec2')
p = client.get_paginator('describe_instances')
results = p.paginate(**query)
return list(itertools.chain(
*[r["Instances"] fo... | [
"def",
"query_instances",
"(",
"session",
",",
"client",
"=",
"None",
",",
"*",
"*",
"query",
")",
":",
"if",
"client",
"is",
"None",
":",
"client",
"=",
"session",
".",
"client",
"(",
"'ec2'",
")",
"p",
"=",
"client",
".",
"get_paginator",
"(",
"'de... | Return a list of ec2 instances for the query. | [
"Return",
"a",
"list",
"of",
"ec2",
"instances",
"for",
"the",
"query",
"."
] | python | train |
acristoffers/ahio | ahio/abstract_driver.py | https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/abstract_driver.py#L418-L444 | def set_pwm_frequency(self, frequency, pin=None):
"""Sets PWM frequency, if supported by hardware
If the driver supports per pin frequency setting, set pin to the
desired frequency. If not, passing None means set to all. If only per
pin frequency is supported and pin is None, raise Runt... | [
"def",
"set_pwm_frequency",
"(",
"self",
",",
"frequency",
",",
"pin",
"=",
"None",
")",
":",
"if",
"pin",
"is",
"None",
":",
"self",
".",
"_set_pwm_frequency",
"(",
"frequency",
",",
"None",
")",
"else",
":",
"pin_id",
"=",
"self",
".",
"_pin_mapping",
... | Sets PWM frequency, if supported by hardware
If the driver supports per pin frequency setting, set pin to the
desired frequency. If not, passing None means set to all. If only per
pin frequency is supported and pin is None, raise RuntimeError.
If you're developing a driver, implement
... | [
"Sets",
"PWM",
"frequency",
"if",
"supported",
"by",
"hardware"
] | python | valid |
CLARIAH/grlc | src/pagination.py | https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/pagination.py#L12-L35 | def buildPaginationHeader(resultCount, resultsPerPage, pageArg, url):
'''Build link header for result pagination'''
lastPage = resultCount / resultsPerPage
if pageArg:
page = int(pageArg)
next_url = re.sub("page=[0-9]+", "page={}".format(page + 1), url)
prev_url = re.sub("page=[0-9]... | [
"def",
"buildPaginationHeader",
"(",
"resultCount",
",",
"resultsPerPage",
",",
"pageArg",
",",
"url",
")",
":",
"lastPage",
"=",
"resultCount",
"/",
"resultsPerPage",
"if",
"pageArg",
":",
"page",
"=",
"int",
"(",
"pageArg",
")",
"next_url",
"=",
"re",
".",... | Build link header for result pagination | [
"Build",
"link",
"header",
"for",
"result",
"pagination"
] | python | train |
mongodb/mongo-python-driver | gridfs/__init__.py | https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/gridfs/__init__.py#L578-L619 | def upload_from_stream(self, filename, source, chunk_size_bytes=None,
metadata=None, session=None):
"""Uploads a user file to a GridFS bucket.
Reads the contents of the user file from `source` and uploads
it to the file `filename`. Source can be a string or file-like ... | [
"def",
"upload_from_stream",
"(",
"self",
",",
"filename",
",",
"source",
",",
"chunk_size_bytes",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"with",
"self",
".",
"open_upload_stream",
"(",
"filename",
",",
"chunk_size_... | Uploads a user file to a GridFS bucket.
Reads the contents of the user file from `source` and uploads
it to the file `filename`. Source can be a string or file-like object.
For example::
my_db = MongoClient().test
fs = GridFSBucket(my_db)
file_id = fs.upload_from_... | [
"Uploads",
"a",
"user",
"file",
"to",
"a",
"GridFS",
"bucket",
"."
] | python | train |
SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L1016-L1045 | def find_elements(self, by=By.ID, value=None):
"""
Find elements given a By strategy and locator. Prefer the find_elements_by_* methods when
possible.
:Usage:
::
elements = driver.find_elements(By.CLASS_NAME, 'foo')
:rtype: list of WebElement
... | [
"def",
"find_elements",
"(",
"self",
",",
"by",
"=",
"By",
".",
"ID",
",",
"value",
"=",
"None",
")",
":",
"if",
"self",
".",
"w3c",
":",
"if",
"by",
"==",
"By",
".",
"ID",
":",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
"value",
"=",
"'[id=\"%s\"]'",... | Find elements given a By strategy and locator. Prefer the find_elements_by_* methods when
possible.
:Usage:
::
elements = driver.find_elements(By.CLASS_NAME, 'foo')
:rtype: list of WebElement | [
"Find",
"elements",
"given",
"a",
"By",
"strategy",
"and",
"locator",
".",
"Prefer",
"the",
"find_elements_by_",
"*",
"methods",
"when",
"possible",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_query.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_query.py#L202-L208 | def count_star(self) -> int:
"""
Implements the ``COUNT(*)`` specialization.
"""
count_query = (self.statement.with_only_columns([func.count()])
.order_by(None))
return self.session.execute(count_query).scalar() | [
"def",
"count_star",
"(",
"self",
")",
"->",
"int",
":",
"count_query",
"=",
"(",
"self",
".",
"statement",
".",
"with_only_columns",
"(",
"[",
"func",
".",
"count",
"(",
")",
"]",
")",
".",
"order_by",
"(",
"None",
")",
")",
"return",
"self",
".",
... | Implements the ``COUNT(*)`` specialization. | [
"Implements",
"the",
"COUNT",
"(",
"*",
")",
"specialization",
"."
] | python | train |
openxc/openxc-python | openxc/sinks/notifier.py | https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/sinks/notifier.py#L33-L40 | def unregister(self, measurement_class, callback):
"""Stop notifying ``callback`` of new values of ``measurement_class``.
If the callback wasn't previously registered, this method will have no
effect.
"""
self.callbacks[Measurement.name_from_class(measurement_class)
... | [
"def",
"unregister",
"(",
"self",
",",
"measurement_class",
",",
"callback",
")",
":",
"self",
".",
"callbacks",
"[",
"Measurement",
".",
"name_from_class",
"(",
"measurement_class",
")",
"]",
".",
"remove",
"(",
"callback",
")"
] | Stop notifying ``callback`` of new values of ``measurement_class``.
If the callback wasn't previously registered, this method will have no
effect. | [
"Stop",
"notifying",
"callback",
"of",
"new",
"values",
"of",
"measurement_class",
"."
] | python | train |
moonso/vcftoolbox | vcftoolbox/header_parser.py | https://github.com/moonso/vcftoolbox/blob/438fb1d85a83812c389774b94802eb5921c89e3a/vcftoolbox/header_parser.py#L138-L240 | def parse_meta_data(self, line):
"""Parse a vcf metadataline"""
line = line.rstrip()
logger.debug("Parsing metadata line:{0}".format(line))
line_info = line[2:].split('=')
match = False
if line_info[0] == 'fileformat':
logger.debug("Parsing fileformat")
... | [
"def",
"parse_meta_data",
"(",
"self",
",",
"line",
")",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
"logger",
".",
"debug",
"(",
"\"Parsing metadata line:{0}\"",
".",
"format",
"(",
"line",
")",
")",
"line_info",
"=",
"line",
"[",
"2",
":",
"]"... | Parse a vcf metadataline | [
"Parse",
"a",
"vcf",
"metadataline"
] | python | train |
xlorepdarkhelm/config | xdh/_config.py | https://github.com/xlorepdarkhelm/config/blob/c973d02f6500c7719441e016bc9c3df84104e392/xdh/_config.py#L288-L302 | def _attr_data_(self):
"Special property containing the memoized data."
try:
return self.__attr_data
except AttributeError:
self.__attr_data = type(
''.join([type(self).__name__, 'EmptyData']),
(),
{
'__... | [
"def",
"_attr_data_",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"__attr_data",
"except",
"AttributeError",
":",
"self",
".",
"__attr_data",
"=",
"type",
"(",
"''",
".",
"join",
"(",
"[",
"type",
"(",
"self",
")",
".",
"__name__",
",",
... | Special property containing the memoized data. | [
"Special",
"property",
"containing",
"the",
"memoized",
"data",
"."
] | python | train |
ml4ai/delphi | delphi/translators/for2py/arrays.py | https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/arrays.py#L152-L162 | def all_subs(bounds):
"""given a list of tuples specifying the bounds of an array, all_subs()
returns a list of all the tuples of subscripts for that array."""
idx_list = []
for i in range(len(bounds)):
this_dim = bounds[i]
lo,hi = this_dim[0],this_dim[1] # bounds for this dimension... | [
"def",
"all_subs",
"(",
"bounds",
")",
":",
"idx_list",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"bounds",
")",
")",
":",
"this_dim",
"=",
"bounds",
"[",
"i",
"]",
"lo",
",",
"hi",
"=",
"this_dim",
"[",
"0",
"]",
",",
"this_di... | given a list of tuples specifying the bounds of an array, all_subs()
returns a list of all the tuples of subscripts for that array. | [
"given",
"a",
"list",
"of",
"tuples",
"specifying",
"the",
"bounds",
"of",
"an",
"array",
"all_subs",
"()",
"returns",
"a",
"list",
"of",
"all",
"the",
"tuples",
"of",
"subscripts",
"for",
"that",
"array",
"."
] | python | train |
EventRegistry/event-registry-python | eventregistry/examples/TopicPagesExamples.py | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/examples/TopicPagesExamples.py#L30-L63 | def createTopicPage2():
"""
create a topic page directly, set the article threshold, restrict results to set concepts and keywords
"""
topic = TopicPage(er)
topic.addCategory(er.getCategoryUri("renewable"), 50)
topic.addKeyword("renewable energy", 30)
topic.addConcept(er.getConceptUri("bio... | [
"def",
"createTopicPage2",
"(",
")",
":",
"topic",
"=",
"TopicPage",
"(",
"er",
")",
"topic",
".",
"addCategory",
"(",
"er",
".",
"getCategoryUri",
"(",
"\"renewable\"",
")",
",",
"50",
")",
"topic",
".",
"addKeyword",
"(",
"\"renewable energy\"",
",",
"30... | create a topic page directly, set the article threshold, restrict results to set concepts and keywords | [
"create",
"a",
"topic",
"page",
"directly",
"set",
"the",
"article",
"threshold",
"restrict",
"results",
"to",
"set",
"concepts",
"and",
"keywords"
] | python | train |
lepture/terminal | terminal/log.py | https://github.com/lepture/terminal/blob/5226d1cac53077f12624aa51f64de7b5b05d9cb8/terminal/log.py#L100-L113 | def verbose(self):
"""
Make it the verbose log.
A verbose log can be only shown when user want to see more logs.
It works as::
log.verbose.warn('this is a verbose warn')
log.verbose.info('this is a verbose info')
"""
log = copy.copy(self)
... | [
"def",
"verbose",
"(",
"self",
")",
":",
"log",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"log",
".",
"_is_verbose",
"=",
"True",
"return",
"log"
] | Make it the verbose log.
A verbose log can be only shown when user want to see more logs.
It works as::
log.verbose.warn('this is a verbose warn')
log.verbose.info('this is a verbose info') | [
"Make",
"it",
"the",
"verbose",
"log",
"."
] | python | train |
evansde77/dockerstache | src/dockerstache/templates.py | https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/templates.py#L59-L81 | def find_templates(input_dir):
"""
_find_templates_
traverse the input_dir structure and return a list
of template files ending with .mustache
:param input_dir: Path to start recursive search for
mustache templates
:returns: List of file paths corresponding to templates
"""
temp... | [
"def",
"find_templates",
"(",
"input_dir",
")",
":",
"templates",
"=",
"[",
"]",
"def",
"template_finder",
"(",
"result",
",",
"dirname",
")",
":",
"for",
"obj",
"in",
"os",
".",
"listdir",
"(",
"dirname",
")",
":",
"if",
"obj",
".",
"endswith",
"(",
... | _find_templates_
traverse the input_dir structure and return a list
of template files ending with .mustache
:param input_dir: Path to start recursive search for
mustache templates
:returns: List of file paths corresponding to templates | [
"_find_templates_"
] | python | train |
SuperCowPowers/workbench | workbench/workers/view_customer.py | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/view_customer.py#L7-L13 | def execute(self, input_data):
''' Execute Method '''
# View on all the meta data files in the sample
fields = ['filename', 'md5', 'length', 'customer', 'import_time', 'type_tag']
view = {key:input_data['meta'][key] for key in fields}
return view | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"# View on all the meta data files in the sample",
"fields",
"=",
"[",
"'filename'",
",",
"'md5'",
",",
"'length'",
",",
"'customer'",
",",
"'import_time'",
",",
"'type_tag'",
"]",
"view",
"=",
"{",
"ke... | Execute Method | [
"Execute",
"Method"
] | python | train |
ambitioninc/django-manager-utils | manager_utils/manager_utils.py | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/manager_utils.py#L375-L398 | def sync(queryset, model_objs, unique_fields, update_fields=None, **kwargs):
"""
Performs a sync operation on a queryset, making the contents of the
queryset match the contents of model_objs.
This function calls bulk_upsert underneath the hood with sync=True.
:type model_objs: list of :class:`Mode... | [
"def",
"sync",
"(",
"queryset",
",",
"model_objs",
",",
"unique_fields",
",",
"update_fields",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"bulk_upsert",
"(",
"queryset",
",",
"model_objs",
",",
"unique_fields",
",",
"update_fields",
"=",
"upda... | Performs a sync operation on a queryset, making the contents of the
queryset match the contents of model_objs.
This function calls bulk_upsert underneath the hood with sync=True.
:type model_objs: list of :class:`Models<django:django.db.models.Model>`
:param model_objs: The models to sync
:type u... | [
"Performs",
"a",
"sync",
"operation",
"on",
"a",
"queryset",
"making",
"the",
"contents",
"of",
"the",
"queryset",
"match",
"the",
"contents",
"of",
"model_objs",
"."
] | python | train |
biocore/burrito-fillings | bfillings/mothur.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L252-L275 | def _derive_log_path(self):
"""Guess logfile path produced by Mothur
This method checks the working directory for log files
generated by Mothur. It will raise an ApplicationError if no
log file can be found.
Mothur generates log files named in a nondeterministic way,
u... | [
"def",
"_derive_log_path",
"(",
"self",
")",
":",
"filenames",
"=",
"listdir",
"(",
"self",
".",
"WorkingDir",
")",
"lognames",
"=",
"[",
"x",
"for",
"x",
"in",
"filenames",
"if",
"re",
".",
"match",
"(",
"\"^mothur\\.\\d+\\.logfile$\"",
",",
"x",
")",
"... | Guess logfile path produced by Mothur
This method checks the working directory for log files
generated by Mothur. It will raise an ApplicationError if no
log file can be found.
Mothur generates log files named in a nondeterministic way,
using the current time. We return the l... | [
"Guess",
"logfile",
"path",
"produced",
"by",
"Mothur"
] | python | train |
dnanexus/dx-toolkit | src/python/dxpy/workflow_builder.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/workflow_builder.py#L140-L163 | def _version_exists(json_spec, name=None, version=None):
"""
Returns True if a global workflow with the given name and version
already exists in the platform and the user has developer rights
to the workflow. "name" and "version" can be passed if we already
made a "describe" API call on the global w... | [
"def",
"_version_exists",
"(",
"json_spec",
",",
"name",
"=",
"None",
",",
"version",
"=",
"None",
")",
":",
"requested_name",
"=",
"json_spec",
"[",
"'name'",
"]",
"requested_version",
"=",
"json_spec",
"[",
"'version'",
"]",
"if",
"requested_name",
"==",
"... | Returns True if a global workflow with the given name and version
already exists in the platform and the user has developer rights
to the workflow. "name" and "version" can be passed if we already
made a "describe" API call on the global workflow and so know the
requested name and version already exists... | [
"Returns",
"True",
"if",
"a",
"global",
"workflow",
"with",
"the",
"given",
"name",
"and",
"version",
"already",
"exists",
"in",
"the",
"platform",
"and",
"the",
"user",
"has",
"developer",
"rights",
"to",
"the",
"workflow",
".",
"name",
"and",
"version",
... | python | train |
chaoss/grimoirelab-cereslib | cereslib/events/events.py | https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/events/events.py#L464-L600 | def eventize(self, granularity):
""" This splits the JSON information found at self.events into the
several events. For this there are three different levels of time
consuming actions: 1-soft, 2-medium and 3-hard.
Level 1 provides events about commits
Level 2 provides events abo... | [
"def",
"eventize",
"(",
"self",
",",
"granularity",
")",
":",
"df_columns",
"=",
"{",
"}",
"# Init common columns",
"self",
".",
"_init_common_fields",
"(",
"df_columns",
")",
"# First level granularity",
"df_columns",
"[",
"Git",
".",
"COMMIT_ID",
"]",
"=",
"["... | This splits the JSON information found at self.events into the
several events. For this there are three different levels of time
consuming actions: 1-soft, 2-medium and 3-hard.
Level 1 provides events about commits
Level 2 provides events about files
Level 3 provides other event... | [
"This",
"splits",
"the",
"JSON",
"information",
"found",
"at",
"self",
".",
"events",
"into",
"the",
"several",
"events",
".",
"For",
"this",
"there",
"are",
"three",
"different",
"levels",
"of",
"time",
"consuming",
"actions",
":",
"1",
"-",
"soft",
"2",
... | python | train |
aio-libs/aiomysql | aiomysql/sa/result.py | https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/sa/result.py#L379-L388 | async def fetchall(self):
"""Fetch all rows, just like DB-API cursor.fetchall()."""
try:
rows = await self._cursor.fetchall()
except AttributeError:
self._non_result()
else:
ret = self._process_rows(rows)
await self.close()
retu... | [
"async",
"def",
"fetchall",
"(",
"self",
")",
":",
"try",
":",
"rows",
"=",
"await",
"self",
".",
"_cursor",
".",
"fetchall",
"(",
")",
"except",
"AttributeError",
":",
"self",
".",
"_non_result",
"(",
")",
"else",
":",
"ret",
"=",
"self",
".",
"_pro... | Fetch all rows, just like DB-API cursor.fetchall(). | [
"Fetch",
"all",
"rows",
"just",
"like",
"DB",
"-",
"API",
"cursor",
".",
"fetchall",
"()",
"."
] | python | train |
kkroening/ffmpeg-python | ffmpeg/_filters.py | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L216-L354 | def drawtext(stream, text=None, x=0, y=0, escape_text=True, **kwargs):
"""Draw a text string or text from a specified file on top of a video, using the libfreetype library.
To enable compilation of this filter, you need to configure FFmpeg with ``--enable-libfreetype``. To enable default
font fallback and ... | [
"def",
"drawtext",
"(",
"stream",
",",
"text",
"=",
"None",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"escape_text",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"text",
"is",
"not",
"None",
":",
"if",
"escape_text",
":",
"text",
"=... | Draw a text string or text from a specified file on top of a video, using the libfreetype library.
To enable compilation of this filter, you need to configure FFmpeg with ``--enable-libfreetype``. To enable default
font fallback and the font option you need to configure FFmpeg with ``--enable-libfontconfig``. ... | [
"Draw",
"a",
"text",
"string",
"or",
"text",
"from",
"a",
"specified",
"file",
"on",
"top",
"of",
"a",
"video",
"using",
"the",
"libfreetype",
"library",
"."
] | python | train |
xtream1101/web-wrapper | web_wrapper/driver_selenium_phantomjs.py | https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_phantomjs.py#L92-L100 | def _create_session(self):
"""
Creates a fresh session with no/default headers and proxies
"""
logger.debug("Create new phantomjs web driver")
self.driver = webdriver.PhantomJS(desired_capabilities=self.dcap,
**self.driver_args)
s... | [
"def",
"_create_session",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Create new phantomjs web driver\"",
")",
"self",
".",
"driver",
"=",
"webdriver",
".",
"PhantomJS",
"(",
"desired_capabilities",
"=",
"self",
".",
"dcap",
",",
"*",
"*",
"self",
... | Creates a fresh session with no/default headers and proxies | [
"Creates",
"a",
"fresh",
"session",
"with",
"no",
"/",
"default",
"headers",
"and",
"proxies"
] | python | train |
Valassis-Digital-Media/spylon | spylon/spark/launcher.py | https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/launcher.py#L497-L522 | def spark_context(self, application_name):
"""Create a spark context given the parameters configured in this class.
The caller is responsible for calling ``.close`` on the resulting spark context
Parameters
----------
application_name : string
Returns
-------
... | [
"def",
"spark_context",
"(",
"self",
",",
"application_name",
")",
":",
"# initialize the spark configuration",
"self",
".",
"_init_spark",
"(",
")",
"import",
"pyspark",
"import",
"pyspark",
".",
"sql",
"# initialize conf",
"spark_conf",
"=",
"pyspark",
".",
"Spark... | Create a spark context given the parameters configured in this class.
The caller is responsible for calling ``.close`` on the resulting spark context
Parameters
----------
application_name : string
Returns
-------
sc : SparkContext | [
"Create",
"a",
"spark",
"context",
"given",
"the",
"parameters",
"configured",
"in",
"this",
"class",
"."
] | python | train |
aio-libs/aioredis | aioredis/commands/hash.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/commands/hash.py#L124-L135 | def ihscan(self, key, *, match=None, count=None):
"""Incrementally iterate sorted set items using async for.
Usage example:
>>> async for name, val in redis.ihscan(key, match='something*'):
... print('Matched:', name, '->', val)
"""
return _ScanIter(lambda cur: sel... | [
"def",
"ihscan",
"(",
"self",
",",
"key",
",",
"*",
",",
"match",
"=",
"None",
",",
"count",
"=",
"None",
")",
":",
"return",
"_ScanIter",
"(",
"lambda",
"cur",
":",
"self",
".",
"hscan",
"(",
"key",
",",
"cur",
",",
"match",
"=",
"match",
",",
... | Incrementally iterate sorted set items using async for.
Usage example:
>>> async for name, val in redis.ihscan(key, match='something*'):
... print('Matched:', name, '->', val) | [
"Incrementally",
"iterate",
"sorted",
"set",
"items",
"using",
"async",
"for",
"."
] | python | train |
saltstack/salt | salt/states/boto_apigateway.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L953-L965 | def deployment_label(self):
'''
this property returns the deployment label dictionary (mainly used by
stage description)
'''
label = dict()
label['swagger_info_object'] = self.info
label['api_name'] = self.rest_api_name
label['swagger_file'] = os.path.bas... | [
"def",
"deployment_label",
"(",
"self",
")",
":",
"label",
"=",
"dict",
"(",
")",
"label",
"[",
"'swagger_info_object'",
"]",
"=",
"self",
".",
"info",
"label",
"[",
"'api_name'",
"]",
"=",
"self",
".",
"rest_api_name",
"label",
"[",
"'swagger_file'",
"]",... | this property returns the deployment label dictionary (mainly used by
stage description) | [
"this",
"property",
"returns",
"the",
"deployment",
"label",
"dictionary",
"(",
"mainly",
"used",
"by",
"stage",
"description",
")"
] | python | train |
pypa/pipenv | pipenv/vendor/jinja2/utils.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/utils.py#L287-L303 | def unicode_urlencode(obj, charset='utf-8', for_qs=False):
"""URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to thei... | [
"def",
"unicode_urlencode",
"(",
"obj",
",",
"charset",
"=",
"'utf-8'",
",",
"for_qs",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"string_types",
")",
":",
"obj",
"=",
"text_type",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"obj... | URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to their unicode
representation first. | [
"URL",
"escapes",
"a",
"single",
"bytestring",
"or",
"unicode",
"string",
"with",
"the",
"given",
"charset",
"if",
"applicable",
"to",
"URL",
"safe",
"quoting",
"under",
"all",
"rules",
"that",
"need",
"to",
"be",
"considered",
"under",
"all",
"supported",
"... | python | train |
dwavesystems/dimod | dimod/reference/composites/roofduality.py | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/composites/roofduality.py#L54-L79 | def sample(self, bqm, sampling_mode=True, **parameters):
"""Sample from the provided binary quadratic model.
Uses the :func:`~dimod.roof_duality.fix_variables` function to determine
which variables to fix.
Args:
bqm (:obj:`dimod.BinaryQuadraticModel`):
Binar... | [
"def",
"sample",
"(",
"self",
",",
"bqm",
",",
"sampling_mode",
"=",
"True",
",",
"*",
"*",
"parameters",
")",
":",
"# use roof-duality to decide which variables to fix",
"parameters",
"[",
"'fixed_variables'",
"]",
"=",
"fix_variables",
"(",
"bqm",
",",
"sampling... | Sample from the provided binary quadratic model.
Uses the :func:`~dimod.roof_duality.fix_variables` function to determine
which variables to fix.
Args:
bqm (:obj:`dimod.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
sampling_mode (bo... | [
"Sample",
"from",
"the",
"provided",
"binary",
"quadratic",
"model",
"."
] | python | train |
LonamiWebs/Telethon | telethon/extensions/binaryreader.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/extensions/binaryreader.py#L60-L73 | def read(self, length=None):
"""Read the given amount of bytes."""
if length is None:
return self.reader.read()
result = self.reader.read(length)
if len(result) != length:
raise BufferError(
'No more data left to read (need {}, got {}: {}); last r... | [
"def",
"read",
"(",
"self",
",",
"length",
"=",
"None",
")",
":",
"if",
"length",
"is",
"None",
":",
"return",
"self",
".",
"reader",
".",
"read",
"(",
")",
"result",
"=",
"self",
".",
"reader",
".",
"read",
"(",
"length",
")",
"if",
"len",
"(",
... | Read the given amount of bytes. | [
"Read",
"the",
"given",
"amount",
"of",
"bytes",
"."
] | python | train |
vertexproject/synapse | synapse/lib/migrate.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/migrate.py#L97-L112 | async def setFormName(self, oldn, newn):
'''
Rename a form within all the layers.
'''
logger.info(f'Migrating [{oldn}] to [{newn}]')
async with self.getTempSlab():
i = 0
async for buid, valu in self.getFormTodo(oldn):
await self.editNode... | [
"async",
"def",
"setFormName",
"(",
"self",
",",
"oldn",
",",
"newn",
")",
":",
"logger",
".",
"info",
"(",
"f'Migrating [{oldn}] to [{newn}]'",
")",
"async",
"with",
"self",
".",
"getTempSlab",
"(",
")",
":",
"i",
"=",
"0",
"async",
"for",
"buid",
",",
... | Rename a form within all the layers. | [
"Rename",
"a",
"form",
"within",
"all",
"the",
"layers",
"."
] | python | train |
fboender/ansible-cmdb | lib/mako/_ast_util.py | https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/lib/mako/_ast_util.py#L87-L104 | def to_source(node, indent_with=' ' * 4):
"""
This function can convert a node tree back into python sourcecode. This
is useful for debugging purposes, especially if you're dealing with custom
asts not generated by python itself.
It could be that the sourcecode is evaluable when the AST itself is ... | [
"def",
"to_source",
"(",
"node",
",",
"indent_with",
"=",
"' '",
"*",
"4",
")",
":",
"generator",
"=",
"SourceGenerator",
"(",
"indent_with",
")",
"generator",
".",
"visit",
"(",
"node",
")",
"return",
"''",
".",
"join",
"(",
"generator",
".",
"result",
... | This function can convert a node tree back into python sourcecode. This
is useful for debugging purposes, especially if you're dealing with custom
asts not generated by python itself.
It could be that the sourcecode is evaluable when the AST itself is not
compilable / evaluable. The reason for this i... | [
"This",
"function",
"can",
"convert",
"a",
"node",
"tree",
"back",
"into",
"python",
"sourcecode",
".",
"This",
"is",
"useful",
"for",
"debugging",
"purposes",
"especially",
"if",
"you",
"re",
"dealing",
"with",
"custom",
"asts",
"not",
"generated",
"by",
"p... | python | train |
SoCo/SoCo | soco/music_services/music_service.py | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L488-L505 | def get_data_for_name(cls, service_name):
"""Get the data relating to a named music service.
Args:
service_name (str): The name of the music service for which data
is required.
Returns:
dict: Data relating to the music service.
Raises:
... | [
"def",
"get_data_for_name",
"(",
"cls",
",",
"service_name",
")",
":",
"for",
"service",
"in",
"cls",
".",
"_get_music_services_data",
"(",
")",
".",
"values",
"(",
")",
":",
"if",
"service_name",
"==",
"service",
"[",
"\"Name\"",
"]",
":",
"return",
"serv... | Get the data relating to a named music service.
Args:
service_name (str): The name of the music service for which data
is required.
Returns:
dict: Data relating to the music service.
Raises:
`MusicServiceException`: if the music service cann... | [
"Get",
"the",
"data",
"relating",
"to",
"a",
"named",
"music",
"service",
"."
] | python | train |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L26366-L26383 | def dump_guest_core(self, filename, compression):
"""Takes a core dump of the guest.
See include/VBox/dbgfcorefmt.h for details on the file format.
in filename of type str
The name of the output file. The file must not exist.
in compression of type str
... | [
"def",
"dump_guest_core",
"(",
"self",
",",
"filename",
",",
"compression",
")",
":",
"if",
"not",
"isinstance",
"(",
"filename",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"filename can only be an instance of type basestring\"",
")",
"if",
"not",
"... | Takes a core dump of the guest.
See include/VBox/dbgfcorefmt.h for details on the file format.
in filename of type str
The name of the output file. The file must not exist.
in compression of type str
Reserved for future compression method indicator. | [
"Takes",
"a",
"core",
"dump",
"of",
"the",
"guest",
".",
"See",
"include",
"/",
"VBox",
"/",
"dbgfcorefmt",
".",
"h",
"for",
"details",
"on",
"the",
"file",
"format",
"."
] | python | train |
pywbem/pywbem | pywbem/mof_compiler.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L490-L614 | def p_mp_createClass(p):
"""mp_createClass : classDeclaration
"""
# pylint: disable=too-many-branches,too-many-statements,too-many-locals
ns = p.parser.handle.default_namespace
cc = p[1]
try:
fixedNS = fixedRefs = fixedSuper = False
while not fixedNS or not fix... | [
"def",
"p_mp_createClass",
"(",
"p",
")",
":",
"# pylint: disable=too-many-branches,too-many-statements,too-many-locals",
"ns",
"=",
"p",
".",
"parser",
".",
"handle",
".",
"default_namespace",
"cc",
"=",
"p",
"[",
"1",
"]",
"try",
":",
"fixedNS",
"=",
"fixedRefs"... | mp_createClass : classDeclaration | [
"mp_createClass",
":",
"classDeclaration"
] | python | train |
plaid/plaid-python | plaid/api/institutions.py | https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/api/institutions.py#L26-L37 | def get_by_id(self, institution_id, _options=None):
'''
Fetch a single institution by id.
:param str institution_id:
'''
options = _options or {}
return self.client.post_public_key('/institutions/get_by_id', {
'institution_id': institution_id,
... | [
"def",
"get_by_id",
"(",
"self",
",",
"institution_id",
",",
"_options",
"=",
"None",
")",
":",
"options",
"=",
"_options",
"or",
"{",
"}",
"return",
"self",
".",
"client",
".",
"post_public_key",
"(",
"'/institutions/get_by_id'",
",",
"{",
"'institution_id'",... | Fetch a single institution by id.
:param str institution_id: | [
"Fetch",
"a",
"single",
"institution",
"by",
"id",
"."
] | python | train |
pycontribs/pyrax | pyrax/utils.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/utils.py#L277-L287 | def random_unicode(length=20):
"""
Generates a random name; useful for testing.
Returns an encoded string of the specified length containing unicode values
up to code point 1000.
"""
def get_char():
return six.unichr(random.randint(32, 1000))
chars = u"".join([get_char() for ii in s... | [
"def",
"random_unicode",
"(",
"length",
"=",
"20",
")",
":",
"def",
"get_char",
"(",
")",
":",
"return",
"six",
".",
"unichr",
"(",
"random",
".",
"randint",
"(",
"32",
",",
"1000",
")",
")",
"chars",
"=",
"u\"\"",
".",
"join",
"(",
"[",
"get_char"... | Generates a random name; useful for testing.
Returns an encoded string of the specified length containing unicode values
up to code point 1000. | [
"Generates",
"a",
"random",
"name",
";",
"useful",
"for",
"testing",
"."
] | python | train |
hollenstein/maspy | maspy_resources/pparse.py | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy_resources/pparse.py#L167-L205 | def cleanUpPparse(outputpath, rawfilename, mgf=False):
"""Delete temporary files generated by pparse, including the filetypes
".csv", ".ms1", ".ms2", ".xtract", the files "pParsePlusLog.txt" and
"pParse.para" and optionally also the ".mgf" file generated by pParse.
.. warning:
When the paramet... | [
"def",
"cleanUpPparse",
"(",
"outputpath",
",",
"rawfilename",
",",
"mgf",
"=",
"False",
")",
":",
"extensions",
"=",
"[",
"'csv'",
",",
"'ms1'",
",",
"'ms2'",
",",
"'xtract'",
"]",
"filename",
",",
"fileext",
"=",
"os",
".",
"path",
".",
"splitext",
"... | Delete temporary files generated by pparse, including the filetypes
".csv", ".ms1", ".ms2", ".xtract", the files "pParsePlusLog.txt" and
"pParse.para" and optionally also the ".mgf" file generated by pParse.
.. warning:
When the parameter "mgf" is set to "True" all files ending with ".mgf"
... | [
"Delete",
"temporary",
"files",
"generated",
"by",
"pparse",
"including",
"the",
"filetypes",
".",
"csv",
".",
"ms1",
".",
"ms2",
".",
"xtract",
"the",
"files",
"pParsePlusLog",
".",
"txt",
"and",
"pParse",
".",
"para",
"and",
"optionally",
"also",
"the",
... | python | train |
diamondman/proteusisc | proteusisc/drivers/digilentdriver.py | https://github.com/diamondman/proteusisc/blob/7622b7b04e63f9dc0f5a04429ff78d9a490c9c5c/proteusisc/drivers/digilentdriver.py#L170-L188 | def _get_adv_trans_stats(self, cmd, return_tdo=False):
"""Utility function to fetch the transfer statistics for the last
advanced transfer. Checking the stats appears to sync the
controller. For details on the advanced transfer please refer
to the documentation at
http://diamondm... | [
"def",
"_get_adv_trans_stats",
"(",
"self",
",",
"cmd",
",",
"return_tdo",
"=",
"False",
")",
":",
"t",
"=",
"time",
"(",
")",
"code",
",",
"res",
"=",
"self",
".",
"bulkCommand",
"(",
"b'\\x03\\x02%c\\x00'",
"%",
"(",
"0x80",
"|",
"cmd",
")",
",",
"... | Utility function to fetch the transfer statistics for the last
advanced transfer. Checking the stats appears to sync the
controller. For details on the advanced transfer please refer
to the documentation at
http://diamondman.github.io/Adapt/cable_digilent_adept.html#bulk-requests | [
"Utility",
"function",
"to",
"fetch",
"the",
"transfer",
"statistics",
"for",
"the",
"last",
"advanced",
"transfer",
".",
"Checking",
"the",
"stats",
"appears",
"to",
"sync",
"the",
"controller",
".",
"For",
"details",
"on",
"the",
"advanced",
"transfer",
"ple... | python | train |
spencerahill/aospy | aospy/automate.py | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L302-L339 | def _exec_calcs(calcs, parallelize=False, client=None, **compute_kwargs):
"""Execute the given calculations.
Parameters
----------
calcs : Sequence of ``aospy.Calc`` objects
parallelize : bool, default False
Whether to submit the calculations in parallel or not
client : distributed.Clie... | [
"def",
"_exec_calcs",
"(",
"calcs",
",",
"parallelize",
"=",
"False",
",",
"client",
"=",
"None",
",",
"*",
"*",
"compute_kwargs",
")",
":",
"if",
"parallelize",
":",
"def",
"func",
"(",
"calc",
")",
":",
"\"\"\"Wrap _compute_or_skip_on_error to require only the... | Execute the given calculations.
Parameters
----------
calcs : Sequence of ``aospy.Calc`` objects
parallelize : bool, default False
Whether to submit the calculations in parallel or not
client : distributed.Client or None
The distributed Client used if parallelize is set to True; if ... | [
"Execute",
"the",
"given",
"calculations",
"."
] | python | train |
victorlei/smop | smop/parse.py | https://github.com/victorlei/smop/blob/bdad96b715d1dd75ce8ab4724f76b9b1bb1f61cd/smop/parse.py#L119-L140 | def p_case_list(p):
"""
case_list :
| CASE expr sep stmt_list_opt case_list
| CASE expr error stmt_list_opt case_list
| OTHERWISE stmt_list
"""
if len(p) == 1:
p[0] = node.stmt_list()
elif len(p) == 3:
assert isinstance(p[2], node.stmt_list)
... | [
"def",
"p_case_list",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"1",
":",
"p",
"[",
"0",
"]",
"=",
"node",
".",
"stmt_list",
"(",
")",
"elif",
"len",
"(",
"p",
")",
"==",
"3",
":",
"assert",
"isinstance",
"(",
"p",
"[",
"2",
"]"... | case_list :
| CASE expr sep stmt_list_opt case_list
| CASE expr error stmt_list_opt case_list
| OTHERWISE stmt_list | [
"case_list",
":",
"|",
"CASE",
"expr",
"sep",
"stmt_list_opt",
"case_list",
"|",
"CASE",
"expr",
"error",
"stmt_list_opt",
"case_list",
"|",
"OTHERWISE",
"stmt_list"
] | python | train |
knipknap/exscript | Exscript/util/mail.py | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/mail.py#L417-L430 | def from_template(filename, **kwargs):
"""
Like from_template_string(), but reads the template from the file with
the given name instead.
:type filename: string
:param filename: The name of the template file.
:type kwargs: str
:param kwargs: Variables to replace in the template.
:rtyp... | [
"def",
"from_template",
"(",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"fp",
":",
"return",
"from_template_string",
"(",
"fp",
".",
"read",
"(",
")",
",",
"*",
"*",
"kwargs",
")"
] | Like from_template_string(), but reads the template from the file with
the given name instead.
:type filename: string
:param filename: The name of the template file.
:type kwargs: str
:param kwargs: Variables to replace in the template.
:rtype: Mail
:return: The resulting mail. | [
"Like",
"from_template_string",
"()",
"but",
"reads",
"the",
"template",
"from",
"the",
"file",
"with",
"the",
"given",
"name",
"instead",
"."
] | python | train |
eyeseast/python-metalsmyth | metalsmyth/plugins/template.py | https://github.com/eyeseast/python-metalsmyth/blob/8c99746d4987ab8ec88d6ba84b6092c51dfbbe3e/metalsmyth/plugins/template.py#L33-L54 | def run(self, files, stack):
"Render templates"
# make stack available to all templates
self.env.globals['stack'] = stack
for filename, post in files.items():
# render content first
post.content = self.env.from_string(post.content).render(post.metadata)
... | [
"def",
"run",
"(",
"self",
",",
"files",
",",
"stack",
")",
":",
"# make stack available to all templates",
"self",
".",
"env",
".",
"globals",
"[",
"'stack'",
"]",
"=",
"stack",
"for",
"filename",
",",
"post",
"in",
"files",
".",
"items",
"(",
")",
":",... | Render templates | [
"Render",
"templates"
] | python | train |
jobovy/galpy | galpy/potential/BurkertPotential.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/BurkertPotential.py#L178-L210 | def _surfdens(self,R,z,phi=0.,t=0.):
"""
NAME:
_surfdens
PURPOSE:
evaluate the surface density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | [
"def",
"_surfdens",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"r",
"=",
"numpy",
".",
"sqrt",
"(",
"R",
"**",
"2.",
"+",
"z",
"**",
"2.",
")",
"x",
"=",
"r",
"/",
"self",
".",
"a",
"Rpa",
"="... | NAME:
_surfdens
PURPOSE:
evaluate the surface density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the surface density
HISTORY:
20... | [
"NAME",
":",
"_surfdens",
"PURPOSE",
":",
"evaluate",
"the",
"surface",
"density",
"for",
"this",
"potential",
"INPUT",
":",
"R",
"-",
"Galactocentric",
"cylindrical",
"radius",
"z",
"-",
"vertical",
"height",
"phi",
"-",
"azimuth",
"t",
"-",
"time",
"OUTPUT... | python | train |
kervi/kervi-core | kervi/values/__init__.py | https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/values/__init__.py#L401-L409 | def value(self, new_value):
"""
Updates the value.
If the change exceeds the change delta observers and linked values are notified.
"""
datetime_value = None
if new_value:
datetime_value = new_value.strftime("%Y-%M-%dT%H:%M:%SZ")
self._set_value(date... | [
"def",
"value",
"(",
"self",
",",
"new_value",
")",
":",
"datetime_value",
"=",
"None",
"if",
"new_value",
":",
"datetime_value",
"=",
"new_value",
".",
"strftime",
"(",
"\"%Y-%M-%dT%H:%M:%SZ\"",
")",
"self",
".",
"_set_value",
"(",
"datetime_value",
")"
] | Updates the value.
If the change exceeds the change delta observers and linked values are notified. | [
"Updates",
"the",
"value",
".",
"If",
"the",
"change",
"exceeds",
"the",
"change",
"delta",
"observers",
"and",
"linked",
"values",
"are",
"notified",
"."
] | python | train |
apache/incubator-mxnet | python/mxnet/symbol/symbol.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/symbol.py#L817-L839 | def list_inputs(self):
"""Lists all arguments and auxiliary states of this Symbol.
Returns
-------
inputs : list of str
List of all inputs.
Examples
--------
>>> bn = mx.sym.BatchNorm(name='bn')
>>> bn.list_arguments()
['bn_data', 'bn... | [
"def",
"list_inputs",
"(",
"self",
")",
":",
"size",
"=",
"ctypes",
".",
"c_uint",
"(",
")",
"sarr",
"=",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_char_p",
")",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"NNSymbolListInputNames",
"(",
"self",
".... | Lists all arguments and auxiliary states of this Symbol.
Returns
-------
inputs : list of str
List of all inputs.
Examples
--------
>>> bn = mx.sym.BatchNorm(name='bn')
>>> bn.list_arguments()
['bn_data', 'bn_gamma', 'bn_beta']
>>> bn... | [
"Lists",
"all",
"arguments",
"and",
"auxiliary",
"states",
"of",
"this",
"Symbol",
"."
] | python | train |
mardix/Mocha | mocha/extras/md.py | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/extras/md.py#L25-L29 | def run(self, root):
"Find all images and append to markdown.images. "
self.markdown.images = []
for image in root.getiterator("img"):
self.markdown.images.append(image.attrib["src"]) | [
"def",
"run",
"(",
"self",
",",
"root",
")",
":",
"self",
".",
"markdown",
".",
"images",
"=",
"[",
"]",
"for",
"image",
"in",
"root",
".",
"getiterator",
"(",
"\"img\"",
")",
":",
"self",
".",
"markdown",
".",
"images",
".",
"append",
"(",
"image"... | Find all images and append to markdown.images. | [
"Find",
"all",
"images",
"and",
"append",
"to",
"markdown",
".",
"images",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.