repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
Knoema/knoema-python-driver | knoema/api_client.py | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/api_client.py#L122-L131 | def get_data_raw(self, request):
"""The method is getting data by raw request"""
path = '/api/1.0/data/raw/'
res = self._api_post(definition.RawDataResponse, path, request)
token = res.continuation_token
while token is not None:
res2 = self.get_data_raw_with_toke... | [
"def",
"get_data_raw",
"(",
"self",
",",
"request",
")",
":",
"path",
"=",
"'/api/1.0/data/raw/'",
"res",
"=",
"self",
".",
"_api_post",
"(",
"definition",
".",
"RawDataResponse",
",",
"path",
",",
"request",
")",
"token",
"=",
"res",
".",
"continuation_toke... | The method is getting data by raw request | [
"The",
"method",
"is",
"getting",
"data",
"by",
"raw",
"request"
] | python | train | 42.2 |
pypa/pipenv | pipenv/vendor/pipdeptree.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L340-L356 | def render_json(tree, indent):
"""Converts the tree into a flat json representation.
The json repr will be a list of hashes, each hash having 2 fields:
- package
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int indent: no. of spaces to indent json
:retu... | [
"def",
"render_json",
"(",
"tree",
",",
"indent",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"[",
"{",
"'package'",
":",
"k",
".",
"as_dict",
"(",
")",
",",
"'dependencies'",
":",
"[",
"v",
".",
"as_dict",
"(",
")",
"for",
"v",
"in",
"vs",
"]... | Converts the tree into a flat json representation.
The json repr will be a list of hashes, each hash having 2 fields:
- package
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int indent: no. of spaces to indent json
:returns: json representation of the tree
... | [
"Converts",
"the",
"tree",
"into",
"a",
"flat",
"json",
"representation",
"."
] | python | train | 33.411765 |
mitsei/dlkit | dlkit/records/assessment/qti/inline_choice_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/qti/inline_choice_records.py#L350-L366 | def set_choice_order(self, choice_ids, inline_region):
""" reorder choices per the passed in list
:param choice_ids:
:return:
"""
reordered_choices = []
current_choice_ids = [c['id'] for c in self.my_osid_object_form._my_map['choices'][inline_region]]
if set(choic... | [
"def",
"set_choice_order",
"(",
"self",
",",
"choice_ids",
",",
"inline_region",
")",
":",
"reordered_choices",
"=",
"[",
"]",
"current_choice_ids",
"=",
"[",
"c",
"[",
"'id'",
"]",
"for",
"c",
"in",
"self",
".",
"my_osid_object_form",
".",
"_my_map",
"[",
... | reorder choices per the passed in list
:param choice_ids:
:return: | [
"reorder",
"choices",
"per",
"the",
"passed",
"in",
"list",
":",
"param",
"choice_ids",
":",
":",
"return",
":"
] | python | train | 45.058824 |
twilio/twilio-python | twilio/rest/api/v2010/account/queue/member.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/queue/member.py#L118-L132 | def get(self, call_sid):
"""
Constructs a MemberContext
:param call_sid: The Call SID of the resource(s) to fetch
:returns: twilio.rest.api.v2010.account.queue.member.MemberContext
:rtype: twilio.rest.api.v2010.account.queue.member.MemberContext
"""
return Membe... | [
"def",
"get",
"(",
"self",
",",
"call_sid",
")",
":",
"return",
"MemberContext",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
"queue_sid",
"=",
"self",
".",
"_solution",
"[",
"'queue_sid'"... | Constructs a MemberContext
:param call_sid: The Call SID of the resource(s) to fetch
:returns: twilio.rest.api.v2010.account.queue.member.MemberContext
:rtype: twilio.rest.api.v2010.account.queue.member.MemberContext | [
"Constructs",
"a",
"MemberContext"
] | python | train | 32.6 |
materialsproject/pymatgen | pymatgen/analysis/local_env.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/local_env.py#L1512-L1550 | def get_nn_info(self, structure, n):
"""
Get all near-neighbor sites as well as the associated image locations
and weights of the site with index n using the closest relative
neighbor distance-based method with VIRE atomic/ionic radii.
Args:
structure (Structure): in... | [
"def",
"get_nn_info",
"(",
"self",
",",
"structure",
",",
"n",
")",
":",
"vire",
"=",
"ValenceIonicRadiusEvaluator",
"(",
"structure",
")",
"site",
"=",
"vire",
".",
"structure",
"[",
"n",
"]",
"neighs_dists",
"=",
"vire",
".",
"structure",
".",
"get_neigh... | Get all near-neighbor sites as well as the associated image locations
and weights of the site with index n using the closest relative
neighbor distance-based method with VIRE atomic/ionic radii.
Args:
structure (Structure): input structure.
n (integer): index of site for... | [
"Get",
"all",
"near",
"-",
"neighbor",
"sites",
"as",
"well",
"as",
"the",
"associated",
"image",
"locations",
"and",
"weights",
"of",
"the",
"site",
"with",
"index",
"n",
"using",
"the",
"closest",
"relative",
"neighbor",
"distance",
"-",
"based",
"method",... | python | train | 39.128205 |
lucastheis/django-publications | publications/views/unapi.py | https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/views/unapi.py#L9-L75 | def unapi(request):
"""
This view implements unAPI 1.0 (see http://unapi.info).
"""
id = request.GET.get('id')
format = request.GET.get('format')
if format is not None:
try:
publications = Publication.objects.filter(pk=int(id))
if not publications:
raise ValueError
except ValueError:
# inv... | [
"def",
"unapi",
"(",
"request",
")",
":",
"id",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'id'",
")",
"format",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'format'",
")",
"if",
"format",
"is",
"not",
"None",
":",
"try",
":",
"publications",
... | This view implements unAPI 1.0 (see http://unapi.info). | [
"This",
"view",
"implements",
"unAPI",
"1",
".",
"0",
"(",
"see",
"http",
":",
"//",
"unapi",
".",
"info",
")",
"."
] | python | valid | 29.253731 |
opendatateam/udata | udata/search/commands.py | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/commands.py#L64-L80 | def index_model(index_name, adapter):
''' Indel all objects given a model'''
model = adapter.model
log.info('Indexing {0} objects'.format(model.__name__))
qs = model.objects
if hasattr(model.objects, 'visible'):
qs = qs.visible()
if adapter.exclude_fields:
qs = qs.exclude(*adapte... | [
"def",
"index_model",
"(",
"index_name",
",",
"adapter",
")",
":",
"model",
"=",
"adapter",
".",
"model",
"log",
".",
"info",
"(",
"'Indexing {0} objects'",
".",
"format",
"(",
"model",
".",
"__name__",
")",
")",
"qs",
"=",
"model",
".",
"objects",
"if",... | Indel all objects given a model | [
"Indel",
"all",
"objects",
"given",
"a",
"model"
] | python | train | 37.058824 |
annoviko/pyclustering | pyclustering/nnet/sync.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/nnet/sync.py#L381-L410 | def calculate_local_order_parameter(self, oscillatory_network, start_iteration = None, stop_iteration = None):
"""!
@brief Calculates local order parameter.
@details Local order parameter or so-called level of local or partial synchronization is calculated by following expression:
... | [
"def",
"calculate_local_order_parameter",
"(",
"self",
",",
"oscillatory_network",
",",
"start_iteration",
"=",
"None",
",",
"stop_iteration",
"=",
"None",
")",
":",
"(",
"start_iteration",
",",
"stop_iteration",
")",
"=",
"self",
".",
"__get_start_stop_iterations",
... | !
@brief Calculates local order parameter.
@details Local order parameter or so-called level of local or partial synchronization is calculated by following expression:
\f[
r_{c}=\left | \sum_{i=0}^{N} \frac{1}{N_{i}} \sum_{j=0}e^{ \theta_{j} - \theta_{i} } \right |;
... | [
"!"
] | python | valid | 60.433333 |
Mollom/mollom_python | mollom/mollom.py | https://github.com/Mollom/mollom_python/blob/dfacb63fd79f82c0eabde76b511116df5b51d6f1/mollom/mollom.py#L338-L347 | def delete_blacklist_entry(self, blacklist_entry_id):
"""Delete an existing blacklist entry.
Keyword arguments:
blacklist_entry_id -- The unique identifier of the blacklist entry to delete.
"""
delete_blacklist_endpoint = Template("${rest_root}/blacklist/${public_key}/${... | [
"def",
"delete_blacklist_entry",
"(",
"self",
",",
"blacklist_entry_id",
")",
":",
"delete_blacklist_endpoint",
"=",
"Template",
"(",
"\"${rest_root}/blacklist/${public_key}/${blacklist_entry_id}/delete\"",
")",
"url",
"=",
"delete_blacklist_endpoint",
".",
"substitute",
"(",
... | Delete an existing blacklist entry.
Keyword arguments:
blacklist_entry_id -- The unique identifier of the blacklist entry to delete. | [
"Delete",
"an",
"existing",
"blacklist",
"entry",
".",
"Keyword",
"arguments",
":",
"blacklist_entry_id",
"--",
"The",
"unique",
"identifier",
"of",
"the",
"blacklist",
"entry",
"to",
"delete",
"."
] | python | train | 53.1 |
abw333/dominoes | dominoes/players.py | https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/players.py#L89-L96 | def bota_gorda(game):
'''
Prefers to play dominoes with higher point values.
:param Game game: game to play
:return: None
'''
game.valid_moves = tuple(sorted(game.valid_moves, key=lambda m: -(m[0].first + m[0].second))) | [
"def",
"bota_gorda",
"(",
"game",
")",
":",
"game",
".",
"valid_moves",
"=",
"tuple",
"(",
"sorted",
"(",
"game",
".",
"valid_moves",
",",
"key",
"=",
"lambda",
"m",
":",
"-",
"(",
"m",
"[",
"0",
"]",
".",
"first",
"+",
"m",
"[",
"0",
"]",
".",... | Prefers to play dominoes with higher point values.
:param Game game: game to play
:return: None | [
"Prefers",
"to",
"play",
"dominoes",
"with",
"higher",
"point",
"values",
"."
] | python | train | 29.625 |
libtcod/python-tcod | tdl/__init__.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L101-L115 | def _format_char(char):
"""Prepares a single character for passing to ctypes calls, needs to return
an integer but can also pass None which will keep the current character
instead of overwriting it.
This is called often and needs to be optimized whenever possible.
"""
if char is None:
r... | [
"def",
"_format_char",
"(",
"char",
")",
":",
"if",
"char",
"is",
"None",
":",
"return",
"-",
"1",
"if",
"isinstance",
"(",
"char",
",",
"_STRTYPES",
")",
"and",
"len",
"(",
"char",
")",
"==",
"1",
":",
"return",
"ord",
"(",
"char",
")",
"try",
"... | Prepares a single character for passing to ctypes calls, needs to return
an integer but can also pass None which will keep the current character
instead of overwriting it.
This is called often and needs to be optimized whenever possible. | [
"Prepares",
"a",
"single",
"character",
"for",
"passing",
"to",
"ctypes",
"calls",
"needs",
"to",
"return",
"an",
"integer",
"but",
"can",
"also",
"pass",
"None",
"which",
"will",
"keep",
"the",
"current",
"character",
"instead",
"of",
"overwriting",
"it",
"... | python | train | 37.866667 |
kylejusticemagnuson/pyti | pyti/double_exponential_moving_average.py | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/double_exponential_moving_average.py#L8-L18 | def double_exponential_moving_average(data, period):
"""
Double Exponential Moving Average.
Formula:
DEMA = 2*EMA - EMA(EMA)
"""
catch_errors.check_for_period_error(data, period)
dema = (2 * ema(data, period)) - ema(ema(data, period), period)
return dema | [
"def",
"double_exponential_moving_average",
"(",
"data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"dema",
"=",
"(",
"2",
"*",
"ema",
"(",
"data",
",",
"period",
")",
")",
"-",
"ema",
"(",
"e... | Double Exponential Moving Average.
Formula:
DEMA = 2*EMA - EMA(EMA) | [
"Double",
"Exponential",
"Moving",
"Average",
"."
] | python | train | 25.272727 |
quantopian/zipline | zipline/finance/ledger.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L479-L523 | def process_transaction(self, transaction):
"""Add a transaction to ledger, updating the current state as needed.
Parameters
----------
transaction : zp.Transaction
The transaction to execute.
"""
asset = transaction.asset
if isinstance(asset, Future)... | [
"def",
"process_transaction",
"(",
"self",
",",
"transaction",
")",
":",
"asset",
"=",
"transaction",
".",
"asset",
"if",
"isinstance",
"(",
"asset",
",",
"Future",
")",
":",
"try",
":",
"old_price",
"=",
"self",
".",
"_payout_last_sale_prices",
"[",
"asset"... | Add a transaction to ledger, updating the current state as needed.
Parameters
----------
transaction : zp.Transaction
The transaction to execute. | [
"Add",
"a",
"transaction",
"to",
"ledger",
"updating",
"the",
"current",
"state",
"as",
"needed",
"."
] | python | train | 35.044444 |
scikit-learn-contrib/categorical-encoding | examples/encoding_examples.py | https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/examples/encoding_examples.py#L52-L89 | def main(loader, name):
"""
Here we iterate through the datasets and score them with a classifier using different encodings.
"""
scores = []
raw_scores_ds = {}
# first get the dataset
X, y, mapping = loader()
clf = linear_model.LogisticRegression(solver='lbfgs', multi_class='auto', m... | [
"def",
"main",
"(",
"loader",
",",
"name",
")",
":",
"scores",
"=",
"[",
"]",
"raw_scores_ds",
"=",
"{",
"}",
"# first get the dataset",
"X",
",",
"y",
",",
"mapping",
"=",
"loader",
"(",
")",
"clf",
"=",
"linear_model",
".",
"LogisticRegression",
"(",
... | Here we iterate through the datasets and score them with a classifier using different encodings. | [
"Here",
"we",
"iterate",
"through",
"the",
"datasets",
"and",
"score",
"them",
"with",
"a",
"classifier",
"using",
"different",
"encodings",
"."
] | python | valid | 35.184211 |
hyperledger/indy-node | indy_node/server/node_maintainer.py | https://github.com/hyperledger/indy-node/blob/8fabd364eaf7d940a56df2911d9215b1e512a2de/indy_node/server/node_maintainer.py#L75-L86 | def _unscheduleAction(self):
"""
Unschedule current action
Note that it does not add record to action log and does not do
required steps to resume previous action. If you need this - use
_cancelScheduledAction
"""
logger.trace("{} unscheduling actions".format(se... | [
"def",
"_unscheduleAction",
"(",
"self",
")",
":",
"logger",
".",
"trace",
"(",
"\"{} unscheduling actions\"",
".",
"format",
"(",
"self",
")",
")",
"self",
".",
"aqStash",
"=",
"deque",
"(",
")",
"self",
".",
"scheduledAction",
"=",
"None"
] | Unschedule current action
Note that it does not add record to action log and does not do
required steps to resume previous action. If you need this - use
_cancelScheduledAction | [
"Unschedule",
"current",
"action"
] | python | train | 31.666667 |
gwastro/pycbc | pycbc/conversions.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L604-L609 | def spin2y_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s):
"""Returns y-component spin for secondary mass.
"""
chi_perp = chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2)
phi2 = phi2_from_phi_a_phi_s(phi_a, phi_s)
return chi_perp * numpy.sin(phi2) | [
"def",
"spin2y_from_mass1_mass2_xi2_phi_a_phi_s",
"(",
"mass1",
",",
"mass2",
",",
"xi2",
",",
"phi_a",
",",
"phi_s",
")",
":",
"chi_perp",
"=",
"chi_perp_from_mass1_mass2_xi2",
"(",
"mass1",
",",
"mass2",
",",
"xi2",
")",
"phi2",
"=",
"phi2_from_phi_a_phi_s",
"... | Returns y-component spin for secondary mass. | [
"Returns",
"y",
"-",
"component",
"spin",
"for",
"secondary",
"mass",
"."
] | python | train | 46.833333 |
aiidateam/aiida-cp2k | aiida_cp2k/calculations/__init__.py | https://github.com/aiidateam/aiida-cp2k/blob/27f5e075ddf2f1badaa5523a487339f8ed7711b1/aiida_cp2k/calculations/__init__.py#L174-L222 | def _render_section(self, output, params, indent=0):
"""
It takes a dictionary and recurses through.
For key-value pair it checks whether the value is a dictionary
and prepends the key with &
It passes the valued to the same function, increasing the indentation
If the va... | [
"def",
"_render_section",
"(",
"self",
",",
"output",
",",
"params",
",",
"indent",
"=",
"0",
")",
":",
"for",
"key",
",",
"val",
"in",
"sorted",
"(",
"params",
".",
"items",
"(",
")",
")",
":",
"if",
"key",
".",
"upper",
"(",
")",
"!=",
"key",
... | It takes a dictionary and recurses through.
For key-value pair it checks whether the value is a dictionary
and prepends the key with &
It passes the valued to the same function, increasing the indentation
If the value is a list, I assume that this is something the user
wants to ... | [
"It",
"takes",
"a",
"dictionary",
"and",
"recurses",
"through",
"."
] | python | train | 39 |
rbuffat/pyepw | pyepw/epw.py | https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L3894-L3915 | def depth_soil_conductivity(self, value=None):
"""Corresponds to IDD Field `depth_soil_conductivity`
Args:
value (float): value for IDD Field `depth_soil_conductivity`
Unit: W/m-K,
if `value` is None it will not be checked against the
specific... | [
"def",
"depth_soil_conductivity",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to b... | Corresponds to IDD Field `depth_soil_conductivity`
Args:
value (float): value for IDD Field `depth_soil_conductivity`
Unit: W/m-K,
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises... | [
"Corresponds",
"to",
"IDD",
"Field",
"depth_soil_conductivity"
] | python | train | 34.227273 |
daskol/nls | nls/animation.py | https://github.com/daskol/nls/blob/00bb4555e4f56e222dc6f54faf2e286567519626/nls/animation.py#L30-L41 | def render(self, filename):
"""Perform initialization of render, set quality and size video attributes and then call template method that
is defined in child class.
"""
self.elapsed_time = -time()
dpi = 100
fig = figure(figsize=(16, 9), dpi=dpi)
with self.writer.s... | [
"def",
"render",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"elapsed_time",
"=",
"-",
"time",
"(",
")",
"dpi",
"=",
"100",
"fig",
"=",
"figure",
"(",
"figsize",
"=",
"(",
"16",
",",
"9",
")",
",",
"dpi",
"=",
"dpi",
")",
"with",
"self... | Perform initialization of render, set quality and size video attributes and then call template method that
is defined in child class. | [
"Perform",
"initialization",
"of",
"render",
"set",
"quality",
"and",
"size",
"video",
"attributes",
"and",
"then",
"call",
"template",
"method",
"that",
"is",
"defined",
"in",
"child",
"class",
"."
] | python | train | 42.333333 |
jeremylow/pyshk | pyshk/models.py | https://github.com/jeremylow/pyshk/blob/3ab92f6706397cde7a18367266eba9e0f1ada868/pyshk/models.py#L193-L207 | def NewFromJSON(data):
"""
Create a new Comment instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a Comment.
Returns:
A Comment instance.
"""
return Comment(
body=data.get('body', None),
posted_at=... | [
"def",
"NewFromJSON",
"(",
"data",
")",
":",
"return",
"Comment",
"(",
"body",
"=",
"data",
".",
"get",
"(",
"'body'",
",",
"None",
")",
",",
"posted_at",
"=",
"data",
".",
"get",
"(",
"'posted_at'",
",",
"None",
")",
",",
"user",
"=",
"User",
".",... | Create a new Comment instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a Comment.
Returns:
A Comment instance. | [
"Create",
"a",
"new",
"Comment",
"instance",
"from",
"a",
"JSON",
"dict",
"."
] | python | train | 26.8 |
sloria/doitlive | doitlive/keyboard.py | https://github.com/sloria/doitlive/blob/baf43f8ad3f2e4593fe21f6af42aedd34ef1efee/doitlive/keyboard.py#L36-L75 | def magictype(text, prompt_template="default", speed=1):
"""Echo each character in ``text`` as keyboard characters are pressed.
Characters are echo'd ``speed`` characters at a time.
"""
echo_prompt(prompt_template)
cursor_position = 0
return_to_regular_type = False
with raw_mode():
w... | [
"def",
"magictype",
"(",
"text",
",",
"prompt_template",
"=",
"\"default\"",
",",
"speed",
"=",
"1",
")",
":",
"echo_prompt",
"(",
"prompt_template",
")",
"cursor_position",
"=",
"0",
"return_to_regular_type",
"=",
"False",
"with",
"raw_mode",
"(",
")",
":",
... | Echo each character in ``text`` as keyboard characters are pressed.
Characters are echo'd ``speed`` characters at a time. | [
"Echo",
"each",
"character",
"in",
"text",
"as",
"keyboard",
"characters",
"are",
"pressed",
".",
"Characters",
"are",
"echo",
"d",
"speed",
"characters",
"at",
"a",
"time",
"."
] | python | train | 40.875 |
saltstack/salt | salt/states/loop.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/loop.py#L47-L118 | def until(name,
m_args=None,
m_kwargs=None,
condition=None,
period=0,
timeout=604800):
'''
Loop over an execution module until a condition is met.
name
The name of the execution module
m_args
The execution module's positional arguments
... | [
"def",
"until",
"(",
"name",
",",
"m_args",
"=",
"None",
",",
"m_kwargs",
"=",
"None",
",",
"condition",
"=",
"None",
",",
"period",
"=",
"0",
",",
"timeout",
"=",
"604800",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
... | Loop over an execution module until a condition is met.
name
The name of the execution module
m_args
The execution module's positional arguments
m_kwargs
The execution module's keyword arguments
condition
The condition which must be met for the loop to break. This
... | [
"Loop",
"over",
"an",
"execution",
"module",
"until",
"a",
"condition",
"is",
"met",
"."
] | python | train | 27.097222 |
echonest/pyechonest | pyechonest/artist.py | https://github.com/echonest/pyechonest/blob/d8c7af6c1da699b50b2f4b1bd3c0febe72e7f1ee/pyechonest/artist.py#L308-L341 | def get_images(self, results=15, start=0, license=None, cache=True):
"""Get a list of artist images
Args:
cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.
results (int): An integer number of ... | [
"def",
"get_images",
"(",
"self",
",",
"results",
"=",
"15",
",",
"start",
"=",
"0",
",",
"license",
"=",
"None",
",",
"cache",
"=",
"True",
")",
":",
"if",
"cache",
"and",
"(",
"'images'",
"in",
"self",
".",
"cache",
")",
"and",
"results",
"==",
... | Get a list of artist images
Args:
cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.
results (int): An integer number of results to return
start (int): An integer starting valu... | [
"Get",
"a",
"list",
"of",
"artist",
"images",
"Args",
":",
"cache",
"(",
"bool",
")",
":",
"A",
"boolean",
"indicating",
"whether",
"or",
"not",
"the",
"cached",
"value",
"should",
"be",
"used",
"(",
"if",
"available",
")",
".",
"Defaults",
"to",
"True... | python | train | 41.794118 |
influxdata/influxdb-python | influxdb/influxdb08/dataframe_client.py | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/dataframe_client.py#L37-L71 | def write_points(self, data, *args, **kwargs):
"""Write to multiple time series names.
:param data: A dictionary mapping series names to pandas DataFrames
:param time_precision: [Optional, default 's'] Either 's', 'm', 'ms'
or 'u'.
:param batch_size: [Optional] Value to writ... | [
"def",
"write_points",
"(",
"self",
",",
"data",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"batch_size",
"=",
"kwargs",
".",
"get",
"(",
"'batch_size'",
")",
"time_precision",
"=",
"kwargs",
".",
"get",
"(",
"'time_precision'",
",",
"'s'",
"... | Write to multiple time series names.
:param data: A dictionary mapping series names to pandas DataFrames
:param time_precision: [Optional, default 's'] Either 's', 'm', 'ms'
or 'u'.
:param batch_size: [Optional] Value to write the points in batches
instead of all at one ... | [
"Write",
"to",
"multiple",
"time",
"series",
"names",
"."
] | python | train | 49.228571 |
pantsbuild/pants | src/python/pants/base/exception_sink.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/exception_sink.py#L305-L311 | def trapped_signals(cls, new_signal_handler):
"""A contextmanager which temporarily overrides signal handling."""
try:
previous_signal_handler = cls.reset_signal_handler(new_signal_handler)
yield
finally:
cls.reset_signal_handler(previous_signal_handler) | [
"def",
"trapped_signals",
"(",
"cls",
",",
"new_signal_handler",
")",
":",
"try",
":",
"previous_signal_handler",
"=",
"cls",
".",
"reset_signal_handler",
"(",
"new_signal_handler",
")",
"yield",
"finally",
":",
"cls",
".",
"reset_signal_handler",
"(",
"previous_sig... | A contextmanager which temporarily overrides signal handling. | [
"A",
"contextmanager",
"which",
"temporarily",
"overrides",
"signal",
"handling",
"."
] | python | train | 39.714286 |
saltstack/salt | salt/utils/schedule.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schedule.py#L505-L519 | def list(self, where):
'''
List the current schedule items
'''
if where == 'pillar':
schedule = self._get_schedule(include_opts=False)
elif where == 'opts':
schedule = self._get_schedule(include_pillar=False)
else:
schedule = self._get_... | [
"def",
"list",
"(",
"self",
",",
"where",
")",
":",
"if",
"where",
"==",
"'pillar'",
":",
"schedule",
"=",
"self",
".",
"_get_schedule",
"(",
"include_opts",
"=",
"False",
")",
"elif",
"where",
"==",
"'opts'",
":",
"schedule",
"=",
"self",
".",
"_get_s... | List the current schedule items | [
"List",
"the",
"current",
"schedule",
"items"
] | python | train | 40.466667 |
johnbywater/eventsourcing | eventsourcing/infrastructure/eventstore.py | https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/infrastructure/eventstore.py#L160-L175 | def get_most_recent_event(self, originator_id, lt=None, lte=None):
"""
Gets a domain event from the sequence identified by `originator_id`
at the highest position.
:param originator_id: ID of a sequence of events
:param lt: get highest before this position
:param lte: ge... | [
"def",
"get_most_recent_event",
"(",
"self",
",",
"originator_id",
",",
"lt",
"=",
"None",
",",
"lte",
"=",
"None",
")",
":",
"events",
"=",
"self",
".",
"get_domain_events",
"(",
"originator_id",
"=",
"originator_id",
",",
"lt",
"=",
"lt",
",",
"lte",
"... | Gets a domain event from the sequence identified by `originator_id`
at the highest position.
:param originator_id: ID of a sequence of events
:param lt: get highest before this position
:param lte: get highest at or before this position
:return: domain event | [
"Gets",
"a",
"domain",
"event",
"from",
"the",
"sequence",
"identified",
"by",
"originator_id",
"at",
"the",
"highest",
"position",
"."
] | python | train | 38.3125 |
danicarrion/pyrestcli | pyrestcli/resources.py | https://github.com/danicarrion/pyrestcli/blob/cde9a2ed856b81cac86386e8d87d901fa03d7b11/pyrestcli/resources.py#L277-L302 | def filter(self, **search_args):
"""
Get a filtered list of resources
:param search_args: To be translated into ?arg1=value1&arg2=value2...
:return: A list of resources
"""
search_args = search_args or {}
raw_resources = []
for url, paginator_params in se... | [
"def",
"filter",
"(",
"self",
",",
"*",
"*",
"search_args",
")",
":",
"search_args",
"=",
"search_args",
"or",
"{",
"}",
"raw_resources",
"=",
"[",
"]",
"for",
"url",
",",
"paginator_params",
"in",
"self",
".",
"paginator",
".",
"get_urls",
"(",
"self",
... | Get a filtered list of resources
:param search_args: To be translated into ?arg1=value1&arg2=value2...
:return: A list of resources | [
"Get",
"a",
"filtered",
"list",
"of",
"resources",
":",
"param",
"search_args",
":",
"To",
"be",
"translated",
"into",
"?arg1",
"=",
"value1&arg2",
"=",
"value2",
"...",
":",
"return",
":",
"A",
"list",
"of",
"resources"
] | python | valid | 41.884615 |
aarongarrett/inspyred | inspyred/ec/utilities.py | https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/utilities.py#L252-L301 | def memoize(func=None, maxlen=None):
"""Cache a function's return value each time it is called.
This function serves as a function decorator to provide a caching of
evaluated fitness values. If called later with the same arguments,
the cached value is returned instead of being re-evaluated.
... | [
"def",
"memoize",
"(",
"func",
"=",
"None",
",",
"maxlen",
"=",
"None",
")",
":",
"if",
"func",
"is",
"not",
"None",
":",
"cache",
"=",
"BoundedOrderedDict",
"(",
"maxlen",
"=",
"maxlen",
")",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
... | Cache a function's return value each time it is called.
This function serves as a function decorator to provide a caching of
evaluated fitness values. If called later with the same arguments,
the cached value is returned instead of being re-evaluated.
This decorator assumes that candidates ar... | [
"Cache",
"a",
"function",
"s",
"return",
"value",
"each",
"time",
"it",
"is",
"called",
".",
"This",
"function",
"serves",
"as",
"a",
"function",
"decorator",
"to",
"provide",
"a",
"caching",
"of",
"evaluated",
"fitness",
"values",
".",
"If",
"called",
"la... | python | train | 42.44 |
OpenTreeOfLife/peyotl | peyotl/git_storage/git_action.py | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/git_storage/git_action.py#L17-L27 | def get_HEAD_SHA1(git_dir):
"""Not locked!
"""
head_file = os.path.join(git_dir, 'HEAD')
with open(head_file, 'r') as hf:
head_contents = hf.read().strip()
assert head_contents.startswith('ref: ')
ref_filename = head_contents[5:] # strip off "ref: "
real_ref = os.path.join(git_dir, ... | [
"def",
"get_HEAD_SHA1",
"(",
"git_dir",
")",
":",
"head_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"git_dir",
",",
"'HEAD'",
")",
"with",
"open",
"(",
"head_file",
",",
"'r'",
")",
"as",
"hf",
":",
"head_contents",
"=",
"hf",
".",
"read",
"(",
... | Not locked! | [
"Not",
"locked!"
] | python | train | 35.636364 |
olitheolix/qtmacs | qtmacs/auxiliary.py | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L1339-L1365 | def qteInsertMode(self, pos: int, mode: str, value):
"""
Insert ``mode`` at position ``pos``.
If ``pos`` is negative then this is equivalent to ``pos=0``. If it
is larger than the number of modes in the list then it is appended
as the last element.
|Args|
* ``p... | [
"def",
"qteInsertMode",
"(",
"self",
",",
"pos",
":",
"int",
",",
"mode",
":",
"str",
",",
"value",
")",
":",
"# Add the label to the list.",
"label",
"=",
"self",
".",
"_qteGetLabelInstance",
"(",
")",
"label",
".",
"setText",
"(",
"value",
")",
"self",
... | Insert ``mode`` at position ``pos``.
If ``pos`` is negative then this is equivalent to ``pos=0``. If it
is larger than the number of modes in the list then it is appended
as the last element.
|Args|
* ``pos`` (**int**): insertion point.
* ``mode`` (**str**): name of mo... | [
"Insert",
"mode",
"at",
"position",
"pos",
"."
] | python | train | 29.333333 |
nchopin/particles | particles/smc_samplers.py | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smc_samplers.py#L251-L270 | def copyto(self, src, where=None):
"""Emulates function `copyto` in NumPy.
Parameters
----------
where: (N,) bool ndarray
True if particle n in src must be copied.
src: (N,) `ThetaParticles` object
source
for each n such that where[n] is True, cop... | [
"def",
"copyto",
"(",
"self",
",",
"src",
",",
"where",
"=",
"None",
")",
":",
"for",
"k",
"in",
"self",
".",
"containers",
":",
"v",
"=",
"self",
".",
"__dict__",
"[",
"k",
"]",
"if",
"isinstance",
"(",
"v",
",",
"np",
".",
"ndarray",
")",
":"... | Emulates function `copyto` in NumPy.
Parameters
----------
where: (N,) bool ndarray
True if particle n in src must be copied.
src: (N,) `ThetaParticles` object
source
for each n such that where[n] is True, copy particle n in src
into self (at locat... | [
"Emulates",
"function",
"copyto",
"in",
"NumPy",
"."
] | python | train | 30.3 |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_1/task_agent/task_agent_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_1/task_agent/task_agent_client.py#L937-L945 | def get_yaml_schema(self):
"""GetYamlSchema.
[Preview API]
:rtype: object
"""
response = self._send(http_method='GET',
location_id='1f9990b9-1dba-441f-9c2e-6485888c42b6',
version='5.1-preview.1')
return self._des... | [
"def",
"get_yaml_schema",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_send",
"(",
"http_method",
"=",
"'GET'",
",",
"location_id",
"=",
"'1f9990b9-1dba-441f-9c2e-6485888c42b6'",
",",
"version",
"=",
"'5.1-preview.1'",
")",
"return",
"self",
".",
"_des... | GetYamlSchema.
[Preview API]
:rtype: object | [
"GetYamlSchema",
".",
"[",
"Preview",
"API",
"]",
":",
"rtype",
":",
"object"
] | python | train | 37.777778 |
pyblish/pyblish-qml | pyblish_qml/host.py | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/host.py#L393-L428 | def install(self, host):
"""Setup common to all Qt-based hosts"""
print("Installing..")
if self._state["installed"]:
return
if self.is_headless():
log.info("Headless host")
return
print("aboutToQuit..")
self.app.aboutToQuit.connect(se... | [
"def",
"install",
"(",
"self",
",",
"host",
")",
":",
"print",
"(",
"\"Installing..\"",
")",
"if",
"self",
".",
"_state",
"[",
"\"installed\"",
"]",
":",
"return",
"if",
"self",
".",
"is_headless",
"(",
")",
":",
"log",
".",
"info",
"(",
"\"Headless ho... | Setup common to all Qt-based hosts | [
"Setup",
"common",
"to",
"all",
"Qt",
"-",
"based",
"hosts"
] | python | train | 28.388889 |
zetaops/pyoko | pyoko/db/adapter/db_riak.py | https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/db/adapter/db_riak.py#L129-L159 | def riak_http_search_query(self, solr_core, solr_params, count_deleted=False):
"""
This method is for advanced SOLR queries. Riak HTTP search query endpoint,
sends solr_params and query string as a proxy and returns solr reponse.
Args:
solr_core (str): solr core on w... | [
"def",
"riak_http_search_query",
"(",
"self",
",",
"solr_core",
",",
"solr_params",
",",
"count_deleted",
"=",
"False",
")",
":",
"# append current _solr_query params",
"sq",
"=",
"[",
"\"%s%%3A%s\"",
"%",
"(",
"q",
"[",
"0",
"]",
",",
"q",
"[",
"1",
"]",
... | This method is for advanced SOLR queries. Riak HTTP search query endpoint,
sends solr_params and query string as a proxy and returns solr reponse.
Args:
solr_core (str): solr core on which query will be executed
solr_params (str): solr specific query params,... | [
"This",
"method",
"is",
"for",
"advanced",
"SOLR",
"queries",
".",
"Riak",
"HTTP",
"search",
"query",
"endpoint",
"sends",
"solr_params",
"and",
"query",
"string",
"as",
"a",
"proxy",
"and",
"returns",
"solr",
"reponse",
".",
"Args",
":",
"solr_core",
"(",
... | python | train | 34.806452 |
aaugustin/websockets | src/websockets/headers.py | https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L339-L348 | def build_extension(extensions: Sequence[ExtensionHeader]) -> str:
"""
Unparse a ``Sec-WebSocket-Extensions`` header.
This is the reverse of :func:`parse_extension`.
"""
return ", ".join(
build_extension_item(name, parameters) for name, parameters in extensions
) | [
"def",
"build_extension",
"(",
"extensions",
":",
"Sequence",
"[",
"ExtensionHeader",
"]",
")",
"->",
"str",
":",
"return",
"\", \"",
".",
"join",
"(",
"build_extension_item",
"(",
"name",
",",
"parameters",
")",
"for",
"name",
",",
"parameters",
"in",
"exte... | Unparse a ``Sec-WebSocket-Extensions`` header.
This is the reverse of :func:`parse_extension`. | [
"Unparse",
"a",
"Sec",
"-",
"WebSocket",
"-",
"Extensions",
"header",
"."
] | python | train | 28.8 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L2864-L2888 | def get_found_includes(self, env, scanner, path):
"""Return the included implicit dependencies in this file.
Cache results so we only scan the file once per path
regardless of how many times this information is requested.
"""
memo_key = (id(env), id(scanner), path)
try:
... | [
"def",
"get_found_includes",
"(",
"self",
",",
"env",
",",
"scanner",
",",
"path",
")",
":",
"memo_key",
"=",
"(",
"id",
"(",
"env",
")",
",",
"id",
"(",
"scanner",
")",
",",
"path",
")",
"try",
":",
"memo_dict",
"=",
"self",
".",
"_memo",
"[",
"... | Return the included implicit dependencies in this file.
Cache results so we only scan the file once per path
regardless of how many times this information is requested. | [
"Return",
"the",
"included",
"implicit",
"dependencies",
"in",
"this",
"file",
".",
"Cache",
"results",
"so",
"we",
"only",
"scan",
"the",
"file",
"once",
"per",
"path",
"regardless",
"of",
"how",
"many",
"times",
"this",
"information",
"is",
"requested",
".... | python | train | 31.12 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L341-L348 | def iget_batches(task_ids, batch_size=10):
"""Yield out a map of the keys and futures in batches of the batch size
passed in.
"""
make_key = lambda _id: ndb.Key(FuriousAsyncMarker, _id)
for keys in i_batch(imap(make_key, task_ids), batch_size):
yield izip(keys, ndb.get_multi_async(keys)) | [
"def",
"iget_batches",
"(",
"task_ids",
",",
"batch_size",
"=",
"10",
")",
":",
"make_key",
"=",
"lambda",
"_id",
":",
"ndb",
".",
"Key",
"(",
"FuriousAsyncMarker",
",",
"_id",
")",
"for",
"keys",
"in",
"i_batch",
"(",
"imap",
"(",
"make_key",
",",
"ta... | Yield out a map of the keys and futures in batches of the batch size
passed in. | [
"Yield",
"out",
"a",
"map",
"of",
"the",
"keys",
"and",
"futures",
"in",
"batches",
"of",
"the",
"batch",
"size",
"passed",
"in",
"."
] | python | train | 38.75 |
merll/docker-map | dockermap/build/buffer.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/build/buffer.py#L102-L114 | def save(self, name):
"""
Save the string buffer to a file. Finalizes prior to saving.
:param name: File path.
:type name: unicode | str
"""
self.finalize()
with open(name, 'wb+') as f:
if six.PY3:
f.write(self.fileobj.getbuffer())
... | [
"def",
"save",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"finalize",
"(",
")",
"with",
"open",
"(",
"name",
",",
"'wb+'",
")",
"as",
"f",
":",
"if",
"six",
".",
"PY3",
":",
"f",
".",
"write",
"(",
"self",
".",
"fileobj",
".",
"getbuffer"... | Save the string buffer to a file. Finalizes prior to saving.
:param name: File path.
:type name: unicode | str | [
"Save",
"the",
"string",
"buffer",
"to",
"a",
"file",
".",
"Finalizes",
"prior",
"to",
"saving",
"."
] | python | train | 29.769231 |
neurodata/ndio | ndio/remote/metadata.py | https://github.com/neurodata/ndio/blob/792dd5816bc770b05a3db2f4327da42ff6253531/ndio/remote/metadata.py#L136-L158 | def get_image_size(self, token, resolution=0):
"""
Return the size of the volume (3D). Convenient for when you want
to download the entirety of a dataset.
Arguments:
token (str): The token for which to find the dataset image bounds
resolution (int : 0): The resol... | [
"def",
"get_image_size",
"(",
"self",
",",
"token",
",",
"resolution",
"=",
"0",
")",
":",
"info",
"=",
"self",
".",
"get_proj_info",
"(",
"token",
")",
"res",
"=",
"str",
"(",
"resolution",
")",
"if",
"res",
"not",
"in",
"info",
"[",
"'dataset'",
"]... | Return the size of the volume (3D). Convenient for when you want
to download the entirety of a dataset.
Arguments:
token (str): The token for which to find the dataset image bounds
resolution (int : 0): The resolution at which to get image bounds.
Defaults to 0, ... | [
"Return",
"the",
"size",
"of",
"the",
"volume",
"(",
"3D",
")",
".",
"Convenient",
"for",
"when",
"you",
"want",
"to",
"download",
"the",
"entirety",
"of",
"a",
"dataset",
"."
] | python | test | 42.304348 |
wbond/oscrypto | oscrypto/_osx/symmetric.py | https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L449-L490 | def des_cbc_pkcs5_encrypt(key, data, iv):
"""
Encrypts plaintext using DES with a 56 bit key
:param key:
The encryption key - a byte string 8 bytes long (includes error correction bits)
:param data:
The plaintext - a byte string
:param iv:
The 8-byte initialization vector ... | [
"def",
"des_cbc_pkcs5_encrypt",
"(",
"key",
",",
"data",
",",
"iv",
")",
":",
"if",
"len",
"(",
"key",
")",
"!=",
"8",
":",
"raise",
"ValueError",
"(",
"pretty_message",
"(",
"'''\n key must be 8 bytes (56 bits + 8 parity bits) long - is %s\n '''",... | Encrypts plaintext using DES with a 56 bit key
:param key:
The encryption key - a byte string 8 bytes long (includes error correction bits)
:param data:
The plaintext - a byte string
:param iv:
The 8-byte initialization vector to use - a byte string - set as None
to genera... | [
"Encrypts",
"plaintext",
"using",
"DES",
"with",
"a",
"56",
"bit",
"key"
] | python | valid | 27.857143 |
reingart/pyafipws | wsctg.py | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsctg.py#L640-L654 | def ConsultarConstanciaCTGPDF(self, numero_ctg=None,
archivo="constancia.pdf"):
"Operación Consultar Constancia de CTG en PDF"
ret = self.client.consultarConstanciaCTGPDF(request=dict(
auth={
'token': self.Token... | [
"def",
"ConsultarConstanciaCTGPDF",
"(",
"self",
",",
"numero_ctg",
"=",
"None",
",",
"archivo",
"=",
"\"constancia.pdf\"",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"consultarConstanciaCTGPDF",
"(",
"request",
"=",
"dict",
"(",
"auth",
"=",
"{",
"'t... | Operación Consultar Constancia de CTG en PDF | [
"Operación",
"Consultar",
"Constancia",
"de",
"CTG",
"en",
"PDF"
] | python | train | 43.666667 |
sunlightlabs/django-mediasync | mediasync/views.py | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/views.py#L14-L32 | def combo_serve(request, path, client):
"""
Handles generating a 'combo' file for the given path. This is similar to
what happens when we upload to S3. Processors are applied, and we get
the value that we would if we were serving from S3. This is a good way
to make sure combo files work as intended ... | [
"def",
"combo_serve",
"(",
"request",
",",
"path",
",",
"client",
")",
":",
"joinfile",
"=",
"path",
"sourcefiles",
"=",
"msettings",
"[",
"'JOINED'",
"]",
"[",
"path",
"]",
"# Generate the combo file as a string.",
"combo_data",
",",
"dirname",
"=",
"combine_fi... | Handles generating a 'combo' file for the given path. This is similar to
what happens when we upload to S3. Processors are applied, and we get
the value that we would if we were serving from S3. This is a good way
to make sure combo files work as intended before rolling out
to production. | [
"Handles",
"generating",
"a",
"combo",
"file",
"for",
"the",
"given",
"path",
".",
"This",
"is",
"similar",
"to",
"what",
"happens",
"when",
"we",
"upload",
"to",
"S3",
".",
"Processors",
"are",
"applied",
"and",
"we",
"get",
"the",
"value",
"that",
"we"... | python | train | 38.315789 |
flo-compbio/genometools | genometools/basic/gene_set_collection.py | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/basic/gene_set_collection.py#L232-L250 | def write_tsv(self, path):
"""Write the database to a tab-delimited text file.
Parameters
----------
path: str
The path name of the file.
Returns
-------
None
"""
with open(path, 'wb') as ofh:
writer = csv.writer(
... | [
"def",
"write_tsv",
"(",
"self",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"ofh",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"ofh",
",",
"dialect",
"=",
"'excel-tab'",
",",
"quoting",
"=",
"csv",
".",
"QUOTE_NO... | Write the database to a tab-delimited text file.
Parameters
----------
path: str
The path name of the file.
Returns
-------
None | [
"Write",
"the",
"database",
"to",
"a",
"tab",
"-",
"delimited",
"text",
"file",
"."
] | python | train | 26.789474 |
click-contrib/sphinx-click | sphinx_click/ext.py | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L31-L64 | def _get_help_record(opt):
"""Re-implementation of click.Opt.get_help_record.
The variant of 'get_help_record' found in Click makes uses of slashes to
separate multiple opts, and formats option arguments using upper case. This
is not compatible with Sphinx's 'option' directive, which expects
comma-... | [
"def",
"_get_help_record",
"(",
"opt",
")",
":",
"def",
"_write_opts",
"(",
"opts",
")",
":",
"rv",
",",
"_",
"=",
"click",
".",
"formatting",
".",
"join_options",
"(",
"opts",
")",
"if",
"not",
"opt",
".",
"is_flag",
"and",
"not",
"opt",
".",
"count... | Re-implementation of click.Opt.get_help_record.
The variant of 'get_help_record' found in Click makes uses of slashes to
separate multiple opts, and formats option arguments using upper case. This
is not compatible with Sphinx's 'option' directive, which expects
comma-separated opts and option argument... | [
"Re",
"-",
"implementation",
"of",
"click",
".",
"Opt",
".",
"get_help_record",
"."
] | python | train | 36.264706 |
SALib/SALib | src/SALib/plotting/morris.py | https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/plotting/morris.py#L105-L138 | def sample_histograms(fig, input_sample, problem, param_dict):
'''Plots a set of subplots of histograms of the input sample
'''
num_vars = problem['num_vars']
names = problem['names']
framing = 101 + (num_vars * 10)
# Find number of levels
num_levels = len(set(input_sample[:, 1]))
ou... | [
"def",
"sample_histograms",
"(",
"fig",
",",
"input_sample",
",",
"problem",
",",
"param_dict",
")",
":",
"num_vars",
"=",
"problem",
"[",
"'num_vars'",
"]",
"names",
"=",
"problem",
"[",
"'names'",
"]",
"framing",
"=",
"101",
"+",
"(",
"num_vars",
"*",
... | Plots a set of subplots of histograms of the input sample | [
"Plots",
"a",
"set",
"of",
"subplots",
"of",
"histograms",
"of",
"the",
"input",
"sample"
] | python | train | 37.794118 |
yyuu/botornado | boto/dynamodb/table.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/dynamodb/table.py#L224-L229 | def new_item(self, hash_key, range_key=None, attrs=None):
"""
Return an new, unsaved Item which can later be PUT to
Amazon DynamoDB.
"""
return Item(self, hash_key, range_key, attrs) | [
"def",
"new_item",
"(",
"self",
",",
"hash_key",
",",
"range_key",
"=",
"None",
",",
"attrs",
"=",
"None",
")",
":",
"return",
"Item",
"(",
"self",
",",
"hash_key",
",",
"range_key",
",",
"attrs",
")"
] | Return an new, unsaved Item which can later be PUT to
Amazon DynamoDB. | [
"Return",
"an",
"new",
"unsaved",
"Item",
"which",
"can",
"later",
"be",
"PUT",
"to",
"Amazon",
"DynamoDB",
"."
] | python | train | 36.166667 |
idlesign/django-sitemessage | sitemessage/messages/base.py | https://github.com/idlesign/django-sitemessage/blob/25b179b798370354c5988042ec209e255d23793f/sitemessage/messages/base.py#L240-L259 | def handle_mark_read_request(cls, request, message, dispatch, hash_is_valid, redirect_to):
"""Handles a request to mark a message as read.
:param Request request: Request instance
:param Message message: Message model instance
:param Dispatch dispatch: Dispatch model instance
:p... | [
"def",
"handle_mark_read_request",
"(",
"cls",
",",
"request",
",",
"message",
",",
"dispatch",
",",
"hash_is_valid",
",",
"redirect_to",
")",
":",
"if",
"hash_is_valid",
":",
"dispatch",
".",
"mark_read",
"(",
")",
"dispatch",
".",
"save",
"(",
")",
"signal... | Handles a request to mark a message as read.
:param Request request: Request instance
:param Message message: Message model instance
:param Dispatch dispatch: Dispatch model instance
:param bool hash_is_valid: Flag indicating that user supplied request signature is correct
:para... | [
"Handles",
"a",
"request",
"to",
"mark",
"a",
"message",
"as",
"read",
"."
] | python | train | 38.65 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_init.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_init.py#L123-L138 | def update_install_json():
"""Update the install.json configuration file if exists."""
if not os.path.isfile('install.json'):
return
with open('install.json', 'r') as f:
install_json = json.load(f)
if install_json.get('programMain'):
install_json['pr... | [
"def",
"update_install_json",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"'install.json'",
")",
":",
"return",
"with",
"open",
"(",
"'install.json'",
",",
"'r'",
")",
"as",
"f",
":",
"install_json",
"=",
"json",
".",
"load",
"("... | Update the install.json configuration file if exists. | [
"Update",
"the",
"install",
".",
"json",
"configuration",
"file",
"if",
"exists",
"."
] | python | train | 35 |
numenta/nupic | src/nupic/encoders/adaptive_scalar.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/adaptive_scalar.py#L196-L204 | def topDownCompute(self, encoded):
"""
[overrides nupic.encoders.scalar.ScalarEncoder.topDownCompute]
"""
if self.minval is None or self.maxval is None:
return [EncoderResult(value=0, scalar=0,
encoding=numpy.zeros(self.n))]
return super(AdaptiveScalarEncoder, self)... | [
"def",
"topDownCompute",
"(",
"self",
",",
"encoded",
")",
":",
"if",
"self",
".",
"minval",
"is",
"None",
"or",
"self",
".",
"maxval",
"is",
"None",
":",
"return",
"[",
"EncoderResult",
"(",
"value",
"=",
"0",
",",
"scalar",
"=",
"0",
",",
"encoding... | [overrides nupic.encoders.scalar.ScalarEncoder.topDownCompute] | [
"[",
"overrides",
"nupic",
".",
"encoders",
".",
"scalar",
".",
"ScalarEncoder",
".",
"topDownCompute",
"]"
] | python | valid | 37.333333 |
uw-it-cte/uw-restclients-wheniwork | uw_wheniwork/shifts.py | https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/shifts.py#L52-L64 | def create_shift(self, params={}):
"""
Creates a shift
http://dev.wheniwork.com/#create/update-shift
"""
url = "/2/shifts/"
body = params
data = self._post_resource(url, body)
shift = self.shift_from_json(data["shift"])
return shift | [
"def",
"create_shift",
"(",
"self",
",",
"params",
"=",
"{",
"}",
")",
":",
"url",
"=",
"\"/2/shifts/\"",
"body",
"=",
"params",
"data",
"=",
"self",
".",
"_post_resource",
"(",
"url",
",",
"body",
")",
"shift",
"=",
"self",
".",
"shift_from_json",
"("... | Creates a shift
http://dev.wheniwork.com/#create/update-shift | [
"Creates",
"a",
"shift"
] | python | valid | 22.692308 |
manns/pyspread | pyspread/src/gui/_widgets.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_widgets.py#L490-L507 | def get_label(self, code):
"""Returns string label for given code string
Inverse of get_code
Parameters
----------
code: String
\tCode string, field 1 of style tuple
"""
for style in self.styles:
if style[1] == code:
return ... | [
"def",
"get_label",
"(",
"self",
",",
"code",
")",
":",
"for",
"style",
"in",
"self",
".",
"styles",
":",
"if",
"style",
"[",
"1",
"]",
"==",
"code",
":",
"return",
"style",
"[",
"0",
"]",
"msg",
"=",
"_",
"(",
"\"Code {code} is invalid.\"",
")",
"... | Returns string label for given code string
Inverse of get_code
Parameters
----------
code: String
\tCode string, field 1 of style tuple | [
"Returns",
"string",
"label",
"for",
"given",
"code",
"string"
] | python | train | 22.388889 |
ValvePython/steam | steam/guard.py | https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/guard.py#L421-L444 | def generate_twofactor_code_for_time(shared_secret, timestamp):
"""Generate Steam 2FA code for timestamp
:param shared_secret: authenticator shared secret
:type shared_secret: bytes
:param timestamp: timestamp to use, if left out uses current time
:type timestamp: int
:return: steam two factor ... | [
"def",
"generate_twofactor_code_for_time",
"(",
"shared_secret",
",",
"timestamp",
")",
":",
"hmac",
"=",
"hmac_sha1",
"(",
"bytes",
"(",
"shared_secret",
")",
",",
"struct",
".",
"pack",
"(",
"'>Q'",
",",
"int",
"(",
"timestamp",
")",
"//",
"30",
")",
")"... | Generate Steam 2FA code for timestamp
:param shared_secret: authenticator shared secret
:type shared_secret: bytes
:param timestamp: timestamp to use, if left out uses current time
:type timestamp: int
:return: steam two factor code
:rtype: str | [
"Generate",
"Steam",
"2FA",
"code",
"for",
"timestamp"
] | python | train | 31.25 |
edeposit/edeposit.amqp.aleph | src/edeposit/amqp/aleph/aleph.py | https://github.com/edeposit/edeposit.amqp.aleph/blob/360342c0504d5daa2344e864762cdf938d4149c7/src/edeposit/amqp/aleph/aleph.py#L569-L615 | def downloadMARCOAI(doc_id, base):
"""
Download MARC OAI document with given `doc_id` from given (logical) `base`.
Funny part is, that some documents can be obtained only with this function
in their full text.
Args:
doc_id (str): You will get this from :func:`getDocumentIDs`.
... | [
"def",
"downloadMARCOAI",
"(",
"doc_id",
",",
"base",
")",
":",
"downer",
"=",
"Downloader",
"(",
")",
"data",
"=",
"downer",
".",
"download",
"(",
"ALEPH_URL",
"+",
"Template",
"(",
"OAI_DOC_URL_TEMPLATE",
")",
".",
"substitute",
"(",
"DOC_ID",
"=",
"doc_... | Download MARC OAI document with given `doc_id` from given (logical) `base`.
Funny part is, that some documents can be obtained only with this function
in their full text.
Args:
doc_id (str): You will get this from :func:`getDocumentIDs`.
base (str, optional): Base from which you wa... | [
"Download",
"MARC",
"OAI",
"document",
"with",
"given",
"doc_id",
"from",
"given",
"(",
"logical",
")",
"base",
"."
] | python | train | 29.659574 |
google/grr | grr/server/grr_response_server/flows/general/transfer.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/flows/general/transfer.py#L270-L313 | def Start(self,
file_size=0,
maximum_pending_files=1000,
use_external_stores=False):
"""Initialize our state."""
super(MultiGetFileLogic, self).Start()
self.state.files_hashed = 0
self.state.use_external_stores = use_external_stores
self.state.file_size = file_si... | [
"def",
"Start",
"(",
"self",
",",
"file_size",
"=",
"0",
",",
"maximum_pending_files",
"=",
"1000",
",",
"use_external_stores",
"=",
"False",
")",
":",
"super",
"(",
"MultiGetFileLogic",
",",
"self",
")",
".",
"Start",
"(",
")",
"self",
".",
"state",
"."... | Initialize our state. | [
"Initialize",
"our",
"state",
"."
] | python | train | 41.431818 |
BD2KGenomics/protect | src/protect/common.py | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/common.py#L337-L373 | def get_file_from_url(job, any_url, encryption_key=None, per_file_encryption=True,
write_to_jobstore=True):
"""
Download a supplied URL that points to a file on an http, https or ftp server. If the file is
found to be an https s3 link then the file is downloaded using `get_file_from_s... | [
"def",
"get_file_from_url",
"(",
"job",
",",
"any_url",
",",
"encryption_key",
"=",
"None",
",",
"per_file_encryption",
"=",
"True",
",",
"write_to_jobstore",
"=",
"True",
")",
":",
"work_dir",
"=",
"job",
".",
"fileStore",
".",
"getLocalTempDir",
"(",
")",
... | Download a supplied URL that points to a file on an http, https or ftp server. If the file is
found to be an https s3 link then the file is downloaded using `get_file_from_s3`. The file is
downloaded and written to the jobstore if requested.
Encryption arguments are for passing to `get_file_from_s3` if req... | [
"Download",
"a",
"supplied",
"URL",
"that",
"points",
"to",
"a",
"file",
"on",
"an",
"http",
"https",
"or",
"ftp",
"server",
".",
"If",
"the",
"file",
"is",
"found",
"to",
"be",
"an",
"https",
"s3",
"link",
"then",
"the",
"file",
"is",
"downloaded",
... | python | train | 45.162162 |
sdss/sdss_access | python/sdss_access/sync/http.py | https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/sync/http.py#L34-L56 | def remote(self, remote_base=None, username=None, password=None):
"""
Configures remote access
Parameters
----------
remote_base : str
base URL path for remote repository
username : str
user name for remote repository
password : str
... | [
"def",
"remote",
"(",
"self",
",",
"remote_base",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"remote_base",
"is",
"not",
"None",
":",
"self",
".",
"remote_base",
"=",
"remote_base",
"self",
".",
"_remote",
... | Configures remote access
Parameters
----------
remote_base : str
base URL path for remote repository
username : str
user name for remote repository
password : str
password for local repository | [
"Configures",
"remote",
"access"
] | python | train | 36.217391 |
UCL-INGI/INGInious | inginious/common/course_factory.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/course_factory.py#L150-L176 | def _cache_update_needed(self, courseid):
"""
:param courseid: the (valid) course id of the course
:raise InvalidNameException, CourseNotFoundException
:return: True if an update of the cache is needed, False else
"""
if courseid not in self._cache:
return Tru... | [
"def",
"_cache_update_needed",
"(",
"self",
",",
"courseid",
")",
":",
"if",
"courseid",
"not",
"in",
"self",
".",
"_cache",
":",
"return",
"True",
"try",
":",
"descriptor_name",
"=",
"self",
".",
"_get_course_descriptor_path",
"(",
"courseid",
")",
"last_upda... | :param courseid: the (valid) course id of the course
:raise InvalidNameException, CourseNotFoundException
:return: True if an update of the cache is needed, False else | [
":",
"param",
"courseid",
":",
"the",
"(",
"valid",
")",
"course",
"id",
"of",
"the",
"course",
":",
"raise",
"InvalidNameException",
"CourseNotFoundException",
":",
"return",
":",
"True",
"if",
"an",
"update",
"of",
"the",
"cache",
"is",
"needed",
"False",
... | python | train | 44.481481 |
f3at/feat | src/feat/extern/log/log.py | https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/extern/log/log.py#L1047-L1068 | def adaptStandardLogging(loggerName, logCategory, targetModule):
"""
Make a logger from the standard library log through the Flumotion logging
system.
@param loggerName: The standard logger to adapt, e.g. 'library.module'
@type loggerName: str
@param logCategory: The Flumotion log category to u... | [
"def",
"adaptStandardLogging",
"(",
"loggerName",
",",
"logCategory",
",",
"targetModule",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"loggerName",
")",
"# if there is already a FluHandler, exit",
"if",
"map",
"(",
"lambda",
"h",
":",
"isinstance",
... | Make a logger from the standard library log through the Flumotion logging
system.
@param loggerName: The standard logger to adapt, e.g. 'library.module'
@type loggerName: str
@param logCategory: The Flumotion log category to use when reporting output
from the standard logger, e.... | [
"Make",
"a",
"logger",
"from",
"the",
"standard",
"library",
"log",
"through",
"the",
"Flumotion",
"logging",
"system",
"."
] | python | train | 47.863636 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py#L1900-L1919 | def get_media_detail_output_interface_interface_identifier_gbic_gbc_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "... | [
"def",
"get_media_detail_output_interface_interface_identifier_gbic_gbc_vendor_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_media_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_media_detail\"... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 50.7 |
StackStorm/pybind | pybind/slxos/v17r_2_00/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_2_00/__init__.py#L5270-L5291 | def _set_port_profile_domain(self, v, load=False):
"""
Setter method for port_profile_domain, mapped from YANG variable /port_profile_domain (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_profile_domain is considered as a private
method. Backends looking... | [
"def",
"_set_port_profile_domain",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",... | Setter method for port_profile_domain, mapped from YANG variable /port_profile_domain (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_profile_domain is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj... | [
"Setter",
"method",
"for",
"port_profile_domain",
"mapped",
"from",
"YANG",
"variable",
"/",
"port_profile_domain",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file"... | python | train | 137.727273 |
BD2KOnFHIR/fhirtordf | fhirtordf/rdfsupport/rdfcompare.py | https://github.com/BD2KOnFHIR/fhirtordf/blob/f97b3df683fa4caacf5cf4f29699ab060bcc0fbf/fhirtordf/rdfsupport/rdfcompare.py#L108-L114 | def dump_nt_sorted(g: Graph) -> List[str]:
"""
Dump graph g in a sorted n3 format
:param g: graph to dump
:return: stringified representation of g
"""
return [l.decode('ascii') for l in sorted(g.serialize(format='nt').splitlines()) if l] | [
"def",
"dump_nt_sorted",
"(",
"g",
":",
"Graph",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"l",
".",
"decode",
"(",
"'ascii'",
")",
"for",
"l",
"in",
"sorted",
"(",
"g",
".",
"serialize",
"(",
"format",
"=",
"'nt'",
")",
".",
"split... | Dump graph g in a sorted n3 format
:param g: graph to dump
:return: stringified representation of g | [
"Dump",
"graph",
"g",
"in",
"a",
"sorted",
"n3",
"format",
":",
"param",
"g",
":",
"graph",
"to",
"dump",
":",
"return",
":",
"stringified",
"representation",
"of",
"g"
] | python | train | 36.428571 |
click-contrib/click-configfile | tasks/_vendor/pathlib.py | https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/pathlib.py#L773-L778 | def with_name(self, name):
"""Return a new path with the file name changed."""
if not self.name:
raise ValueError("%r has an empty name" % (self,))
return self._from_parsed_parts(self._drv, self._root,
self._parts[:-1] + [name]) | [
"def",
"with_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"self",
".",
"name",
":",
"raise",
"ValueError",
"(",
"\"%r has an empty name\"",
"%",
"(",
"self",
",",
")",
")",
"return",
"self",
".",
"_from_parsed_parts",
"(",
"self",
".",
"_drv",... | Return a new path with the file name changed. | [
"Return",
"a",
"new",
"path",
"with",
"the",
"file",
"name",
"changed",
"."
] | python | train | 49.666667 |
simse/pymitv | pymitv/control.py | https://github.com/simse/pymitv/blob/03213f591d70fbf90ba2b6af372e474c9bfb99f6/pymitv/control.py#L46-L58 | def mute(ip):
"""Polyfill for muting the TV."""
tv_url = 'http://{}:6095/controller?action=keyevent&keycode='.format(ip)
count = 0
while count > 30:
count = count + 1
request = requests.get(tv_url + 'volumedown')
if request.status_code != 20... | [
"def",
"mute",
"(",
"ip",
")",
":",
"tv_url",
"=",
"'http://{}:6095/controller?action=keyevent&keycode='",
".",
"format",
"(",
"ip",
")",
"count",
"=",
"0",
"while",
"count",
">",
"30",
":",
"count",
"=",
"count",
"+",
"1",
"request",
"=",
"requests",
".",... | Polyfill for muting the TV. | [
"Polyfill",
"for",
"muting",
"the",
"TV",
"."
] | python | train | 27.923077 |
locationlabs/mockredis | mockredis/client.py | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1529-L1544 | def _list_or_args(self, keys, args):
"""
Shamelessly copied from redis-py.
"""
# returns a single list combining keys and args
try:
iter(keys)
# a string can be iterated, but indicates
# keys wasn't passed as a list
if isinstance(ke... | [
"def",
"_list_or_args",
"(",
"self",
",",
"keys",
",",
"args",
")",
":",
"# returns a single list combining keys and args",
"try",
":",
"iter",
"(",
"keys",
")",
"# a string can be iterated, but indicates",
"# keys wasn't passed as a list",
"if",
"isinstance",
"(",
"keys"... | Shamelessly copied from redis-py. | [
"Shamelessly",
"copied",
"from",
"redis",
"-",
"py",
"."
] | python | train | 29.375 |
xsleonard/pystmark | pystmark.py | https://github.com/xsleonard/pystmark/blob/329ccae1a7c8d57f28fa72cd8dbbee3e39413ed6/pystmark.py#L123-L138 | def send_batch(messages, api_key=None, secure=None, test=None, **request_args):
'''Send a batch of messages.
:param messages: Messages to send.
:type message: A list of `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https ... | [
"def",
"send_batch",
"(",
"messages",
",",
"api_key",
"=",
"None",
",",
"secure",
"=",
"None",
",",
"test",
"=",
"None",
",",
"*",
"*",
"request_args",
")",
":",
"return",
"_default_pyst_batch_sender",
".",
"send",
"(",
"messages",
"=",
"messages",
",",
... | Send a batch of messages.
:param messages: Messages to send.
:type message: A list of `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postma... | [
"Send",
"a",
"batch",
"of",
"messages",
"."
] | python | train | 48.1875 |
GoogleCloudPlatform/datastore-ndb-python | ndb/blobstore.py | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/blobstore.py#L301-L328 | def create_upload_url(success_path,
max_bytes_per_blob=None,
max_bytes_total=None,
**options):
"""Create upload URL for POST form.
Args:
success_path: Path within application to call when POST is successful
and upload is complete.
max_... | [
"def",
"create_upload_url",
"(",
"success_path",
",",
"max_bytes_per_blob",
"=",
"None",
",",
"max_bytes_total",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"fut",
"=",
"create_upload_url_async",
"(",
"success_path",
",",
"max_bytes_per_blob",
"=",
"max_bytes... | Create upload URL for POST form.
Args:
success_path: Path within application to call when POST is successful
and upload is complete.
max_bytes_per_blob: The maximum size in bytes that any one blob in the
upload can be or None for no maximum size.
max_bytes_total: The maximum size in bytes tha... | [
"Create",
"upload",
"URL",
"for",
"POST",
"form",
"."
] | python | train | 38.035714 |
CalebBell/fluids | fluids/two_phase.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/two_phase.py#L2569-L2657 | def two_phase_dP_gravitational(angle, z, alpha_i, rho_li, rho_gi,
alpha_o=None, rho_lo=None, rho_go=None, g=g):
r'''This function handles calculation of two-phase liquid-gas pressure drop
due to gravitation for flow inside channels. This is a discrete
calculation for a segm... | [
"def",
"two_phase_dP_gravitational",
"(",
"angle",
",",
"z",
",",
"alpha_i",
",",
"rho_li",
",",
"rho_gi",
",",
"alpha_o",
"=",
"None",
",",
"rho_lo",
"=",
"None",
",",
"rho_go",
"=",
"None",
",",
"g",
"=",
"g",
")",
":",
"if",
"rho_lo",
"is",
"None"... | r'''This function handles calculation of two-phase liquid-gas pressure drop
due to gravitation for flow inside channels. This is a discrete
calculation for a segment with a known difference in elevation (and ideally
known inlet and outlet pressures so density dependence can be included).
.. math:... | [
"r",
"This",
"function",
"handles",
"calculation",
"of",
"two",
"-",
"phase",
"liquid",
"-",
"gas",
"pressure",
"drop",
"due",
"to",
"gravitation",
"for",
"flow",
"inside",
"channels",
".",
"This",
"is",
"a",
"discrete",
"calculation",
"for",
"a",
"segment",... | python | train | 38.393258 |
basho/riak-python-client | riak/transports/pool.py | https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/transports/pool.py#L162-L174 | def release(self, resource):
"""release(resource)
Returns a resource to the pool. Most of the time you will want
to use :meth:`transaction`, but if you use :meth:`acquire`,
you must release the acquired resource back to the pool when
finished. Failure to do so could result in de... | [
"def",
"release",
"(",
"self",
",",
"resource",
")",
":",
"with",
"self",
".",
"releaser",
":",
"resource",
".",
"claimed",
"=",
"False",
"self",
".",
"releaser",
".",
"notify_all",
"(",
")"
] | release(resource)
Returns a resource to the pool. Most of the time you will want
to use :meth:`transaction`, but if you use :meth:`acquire`,
you must release the acquired resource back to the pool when
finished. Failure to do so could result in deadlock.
:param resource: Resour... | [
"release",
"(",
"resource",
")"
] | python | train | 35.846154 |
pandas-dev/pandas | pandas/core/frame.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L832-L910 | def itertuples(self, index=True, name="Pandas"):
"""
Iterate over DataFrame rows as namedtuples.
Parameters
----------
index : bool, default True
If True, return the index as the first element of the tuple.
name : str or None, default "Pandas"
The... | [
"def",
"itertuples",
"(",
"self",
",",
"index",
"=",
"True",
",",
"name",
"=",
"\"Pandas\"",
")",
":",
"arrays",
"=",
"[",
"]",
"fields",
"=",
"list",
"(",
"self",
".",
"columns",
")",
"if",
"index",
":",
"arrays",
".",
"append",
"(",
"self",
".",
... | Iterate over DataFrame rows as namedtuples.
Parameters
----------
index : bool, default True
If True, return the index as the first element of the tuple.
name : str or None, default "Pandas"
The name of the returned namedtuples or None to return regular
... | [
"Iterate",
"over",
"DataFrame",
"rows",
"as",
"namedtuples",
"."
] | python | train | 34.202532 |
horazont/aioopenssl | aioopenssl/__init__.py | https://github.com/horazont/aioopenssl/blob/95cb39b5904d6a9702afcef6704181c850371081/aioopenssl/__init__.py#L576-L585 | def abort(self):
"""
Immediately close the stream, without sending remaining buffers or
performing a proper shutdown.
"""
if self._state == _State.CLOSED:
self._invalid_state("abort() called")
return
self._force_close(None) | [
"def",
"abort",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"_State",
".",
"CLOSED",
":",
"self",
".",
"_invalid_state",
"(",
"\"abort() called\"",
")",
"return",
"self",
".",
"_force_close",
"(",
"None",
")"
] | Immediately close the stream, without sending remaining buffers or
performing a proper shutdown. | [
"Immediately",
"close",
"the",
"stream",
"without",
"sending",
"remaining",
"buffers",
"or",
"performing",
"a",
"proper",
"shutdown",
"."
] | python | train | 28.7 |
androguard/androguard | androguard/core/bytecodes/dvm.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/dvm.py#L7987-L7998 | def get_fields(self):
"""
Return all field objects
:rtype: a list of :class:`EncodedField` objects
"""
if self.__cache_all_fields is None:
self.__cache_all_fields = []
for i in self.get_classes():
for j in i.get_fields():
... | [
"def",
"get_fields",
"(",
"self",
")",
":",
"if",
"self",
".",
"__cache_all_fields",
"is",
"None",
":",
"self",
".",
"__cache_all_fields",
"=",
"[",
"]",
"for",
"i",
"in",
"self",
".",
"get_classes",
"(",
")",
":",
"for",
"j",
"in",
"i",
".",
"get_fi... | Return all field objects
:rtype: a list of :class:`EncodedField` objects | [
"Return",
"all",
"field",
"objects"
] | python | train | 32 |
nivardus/kclboot | kclboot/command.py | https://github.com/nivardus/kclboot/blob/aee054d9186938bec51f19e9ed8deed6ac6fe492/kclboot/command.py#L20-L59 | def main():
'''
Bootstrapper CLI
'''
parser = argparse.ArgumentParser(prog='kclboot',
description='kclboot - Kinesis Client Library Bootstrapper')
subparsers = parser.add_subparsers(title='Subcommands', help='Additional help', dest='subparser')
# Common arguments
jar_path_parser =... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"'kclboot'",
",",
"description",
"=",
"'kclboot - Kinesis Client Library Bootstrapper'",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"title",
"=",
... | Bootstrapper CLI | [
"Bootstrapper",
"CLI"
] | python | train | 44.025 |
onicagroup/runway | runway/module/serverless.py | https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/serverless.py#L46-L56 | def run_sls_remove(sls_cmd, env_vars):
"""Run sls remove command."""
sls_process = subprocess.Popen(sls_cmd,
stdout=subprocess.PIPE,
env=env_vars)
stdoutdata, _stderrdata = sls_process.communicate()
sls_return = sls_process.wait()
... | [
"def",
"run_sls_remove",
"(",
"sls_cmd",
",",
"env_vars",
")",
":",
"sls_process",
"=",
"subprocess",
".",
"Popen",
"(",
"sls_cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"env",
"=",
"env_vars",
")",
"stdoutdata",
",",
"_stderrdata",
"=",
"sls... | Run sls remove command. | [
"Run",
"sls",
"remove",
"command",
"."
] | python | train | 43.454545 |
juju/theblues | theblues/identity_manager.py | https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L44-L50 | def debug(self):
"""Retrieve the debug information from the identity manager."""
url = '{}debug/status'.format(self.url)
try:
return make_request(url, timeout=self.timeout)
except ServerError as err:
return {"error": str(err)} | [
"def",
"debug",
"(",
"self",
")",
":",
"url",
"=",
"'{}debug/status'",
".",
"format",
"(",
"self",
".",
"url",
")",
"try",
":",
"return",
"make_request",
"(",
"url",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"except",
"ServerError",
"as",
"err"... | Retrieve the debug information from the identity manager. | [
"Retrieve",
"the",
"debug",
"information",
"from",
"the",
"identity",
"manager",
"."
] | python | train | 39.428571 |
google/grr | grr/core/grr_response_core/lib/util/compatibility.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/util/compatibility.py#L80-L104 | def GetName(obj):
"""A compatibility wrapper for getting object's name.
In Python 2 class names are returned as `bytes` (since class names can contain
only ASCII characters) whereas in Python 3 they are `unicode` (since class
names can contain arbitrary unicode characters).
This function makes this behaviou... | [
"def",
"GetName",
"(",
"obj",
")",
":",
"precondition",
".",
"AssertType",
"(",
"obj",
",",
"(",
"type",
",",
"types",
".",
"FunctionType",
")",
")",
"if",
"PY2",
":",
"return",
"obj",
".",
"__name__",
".",
"decode",
"(",
"\"ascii\"",
")",
"else",
":... | A compatibility wrapper for getting object's name.
In Python 2 class names are returned as `bytes` (since class names can contain
only ASCII characters) whereas in Python 3 they are `unicode` (since class
names can contain arbitrary unicode characters).
This function makes this behaviour consistent and always... | [
"A",
"compatibility",
"wrapper",
"for",
"getting",
"object",
"s",
"name",
"."
] | python | train | 30.32 |
acutesoftware/AIKIF | aikif/programs.py | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/programs.py#L88-L112 | def save(self, fname=''):
"""
Save the list of items to AIKIF core and optionally to local file fname
"""
if fname != '':
with open(fname, 'w') as f:
for i in self.lstPrograms:
f.write(self.get_file_info_line(i, ','))
# sa... | [
"def",
"save",
"(",
"self",
",",
"fname",
"=",
"''",
")",
":",
"if",
"fname",
"!=",
"''",
":",
"with",
"open",
"(",
"fname",
",",
"'w'",
")",
"as",
"f",
":",
"for",
"i",
"in",
"self",
".",
"lstPrograms",
":",
"f",
".",
"write",
"(",
"self",
"... | Save the list of items to AIKIF core and optionally to local file fname | [
"Save",
"the",
"list",
"of",
"items",
"to",
"AIKIF",
"core",
"and",
"optionally",
"to",
"local",
"file",
"fname"
] | python | train | 42.84 |
mlperf/training | data_generation/fractal_graph_expansions/util.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/util.py#L62-L67 | def serialize_to_file(obj, file_name, append=False):
"""Pickle obj to file_name."""
logging.info("Serializing to file %s.", file_name)
with tf.gfile.Open(file_name, "a+" if append else "wb") as output_file:
pickle.dump(obj, output_file)
logging.info("Done serializing to file %s.", file_name) | [
"def",
"serialize_to_file",
"(",
"obj",
",",
"file_name",
",",
"append",
"=",
"False",
")",
":",
"logging",
".",
"info",
"(",
"\"Serializing to file %s.\"",
",",
"file_name",
")",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"file_name",
",",
"\"a+\"",
"i... | Pickle obj to file_name. | [
"Pickle",
"obj",
"to",
"file_name",
"."
] | python | train | 49.833333 |
baliame/http-hmac-python | httphmac/v2.py | https://github.com/baliame/http-hmac-python/blob/9884c0cbfdb712f9f37080a8efbfdce82850785f/httphmac/v2.py#L128-L163 | def check(self, request, secret):
"""Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature.
This verifies every element of the signature, including the timestamp's value.
Does not alter the request.
Keyword arguments:
... | [
"def",
"check",
"(",
"self",
",",
"request",
",",
"secret",
")",
":",
"if",
"request",
".",
"get_header",
"(",
"\"Authorization\"",
")",
"==",
"\"\"",
":",
"return",
"False",
"ah",
"=",
"self",
".",
"parse_auth_headers",
"(",
"request",
".",
"get_header",
... | Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature.
This verifies every element of the signature, including the timestamp's value.
Does not alter the request.
Keyword arguments:
request -- A request object which can be cons... | [
"Verifies",
"whether",
"or",
"not",
"the",
"request",
"bears",
"an",
"authorization",
"appropriate",
"and",
"valid",
"for",
"this",
"version",
"of",
"the",
"signature",
".",
"This",
"verifies",
"every",
"element",
"of",
"the",
"signature",
"including",
"the",
... | python | train | 55.166667 |
manahl/arctic | arctic/arctic.py | https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/arctic.py#L303-L326 | def delete_library(self, library):
"""
Delete an Arctic Library, and all associated collections in the MongoDB.
Parameters
----------
library : `str`
The name of the library. e.g. 'library' or 'user.library'
"""
lib = ArcticLibraryBinding(self, librar... | [
"def",
"delete_library",
"(",
"self",
",",
"library",
")",
":",
"lib",
"=",
"ArcticLibraryBinding",
"(",
"self",
",",
"library",
")",
"colname",
"=",
"lib",
".",
"get_top_level_collection",
"(",
")",
".",
"name",
"if",
"not",
"[",
"c",
"for",
"c",
"in",
... | Delete an Arctic Library, and all associated collections in the MongoDB.
Parameters
----------
library : `str`
The name of the library. e.g. 'library' or 'user.library' | [
"Delete",
"an",
"Arctic",
"Library",
"and",
"all",
"associated",
"collections",
"in",
"the",
"MongoDB",
"."
] | python | train | 45.75 |
saltstack/salt | salt/daemons/masterapi.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/daemons/masterapi.py#L1151-L1213 | def wheel(self, load):
'''
Send a master control function back to the wheel system
'''
# All wheel ops pass through eauth
auth_type, err_name, key = self._prep_auth_info(load)
# Authenticate
auth_check = self.loadauth.check_authentication(
load,
... | [
"def",
"wheel",
"(",
"self",
",",
"load",
")",
":",
"# All wheel ops pass through eauth",
"auth_type",
",",
"err_name",
",",
"key",
"=",
"self",
".",
"_prep_auth_info",
"(",
"load",
")",
"# Authenticate",
"auth_check",
"=",
"self",
".",
"loadauth",
".",
"check... | Send a master control function back to the wheel system | [
"Send",
"a",
"master",
"control",
"function",
"back",
"to",
"the",
"wheel",
"system"
] | python | train | 39.809524 |
twilio/twilio-python | twilio/rest/sync/v1/service/sync_list/sync_list_permission.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py#L261-L286 | def update(self, read, write, manage):
"""
Update the SyncListPermissionInstance
:param bool read: Read access.
:param bool write: Write access.
:param bool manage: Manage access.
:returns: Updated SyncListPermissionInstance
:rtype: twilio.rest.sync.v1.service.s... | [
"def",
"update",
"(",
"self",
",",
"read",
",",
"write",
",",
"manage",
")",
":",
"data",
"=",
"values",
".",
"of",
"(",
"{",
"'Read'",
":",
"read",
",",
"'Write'",
":",
"write",
",",
"'Manage'",
":",
"manage",
",",
"}",
")",
"payload",
"=",
"sel... | Update the SyncListPermissionInstance
:param bool read: Read access.
:param bool write: Write access.
:param bool manage: Manage access.
:returns: Updated SyncListPermissionInstance
:rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance | [
"Update",
"the",
"SyncListPermissionInstance"
] | python | train | 31.230769 |
dropbox/stone | stone/backends/python_types.py | https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/backends/python_types.py#L715-L747 | def _generate_struct_class_custom_annotations(self, ns, data_type):
"""
The _process_custom_annotations function allows client code to access
custom annotations defined in the spec.
"""
self.emit('def _process_custom_annotations(self, annotation_type, field_path, processor):')
... | [
"def",
"_generate_struct_class_custom_annotations",
"(",
"self",
",",
"ns",
",",
"data_type",
")",
":",
"self",
".",
"emit",
"(",
"'def _process_custom_annotations(self, annotation_type, field_path, processor):'",
")",
"with",
"self",
".",
"indent",
"(",
")",
",",
"emit... | The _process_custom_annotations function allows client code to access
custom annotations defined in the spec. | [
"The",
"_process_custom_annotations",
"function",
"allows",
"client",
"code",
"to",
"access",
"custom",
"annotations",
"defined",
"in",
"the",
"spec",
"."
] | python | train | 48.181818 |
elkiwy/paynter | paynter/paynter.py | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L186-L200 | def drawRect(self, x1, y1, x2, y2, angle=0):
"""
Draws a rectangle on the current :py:class:`Layer` with the current :py:class:`Brush`.
Coordinates are relative to the original layer size WITHOUT downsampling applied.
:param x1: The X of the top-left corner of the rectangle.
:param y1: The Y of the top-lef... | [
"def",
"drawRect",
"(",
"self",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"angle",
"=",
"0",
")",
":",
"vertices",
"=",
"[",
"[",
"x1",
",",
"y1",
"]",
",",
"[",
"x2",
",",
"y1",
"]",
",",
"[",
"x2",
",",
"y2",
"]",
",",
"[",
"x1... | Draws a rectangle on the current :py:class:`Layer` with the current :py:class:`Brush`.
Coordinates are relative to the original layer size WITHOUT downsampling applied.
:param x1: The X of the top-left corner of the rectangle.
:param y1: The Y of the top-left corner of the rectangle.
:param x2: The X of the ... | [
"Draws",
"a",
"rectangle",
"on",
"the",
"current",
":",
"py",
":",
"class",
":",
"Layer",
"with",
"the",
"current",
":",
"py",
":",
"class",
":",
"Brush",
".",
"Coordinates",
"are",
"relative",
"to",
"the",
"original",
"layer",
"size",
"WITHOUT",
"downsa... | python | train | 48.933333 |
grahambell/pymoc | lib/pymoc/util/tool.py | https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L307-L322 | def normalize(self):
"""Normalize the MOC to a given order.
This command takes a MOC order (0-29) and normalizes the MOC so that
its maximum order is the given order.
::
pymoctool a.fits --normalize 10 --output a_10.fits
"""
if self.moc is None:
... | [
"def",
"normalize",
"(",
"self",
")",
":",
"if",
"self",
".",
"moc",
"is",
"None",
":",
"raise",
"CommandError",
"(",
"'No MOC information present for normalization'",
")",
"order",
"=",
"int",
"(",
"self",
".",
"params",
".",
"pop",
"(",
")",
")",
"self",... | Normalize the MOC to a given order.
This command takes a MOC order (0-29) and normalizes the MOC so that
its maximum order is the given order.
::
pymoctool a.fits --normalize 10 --output a_10.fits | [
"Normalize",
"the",
"MOC",
"to",
"a",
"given",
"order",
"."
] | python | train | 27.9375 |
nugget/python-insteonplm | insteonplm/messages/__init__.py | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/messages/__init__.py#L193-L203 | def _trim_buffer_garbage(rawmessage, debug=True):
"""Remove leading bytes from a byte stream.
A proper message byte stream begins with 0x02.
"""
while rawmessage and rawmessage[0] != MESSAGE_START_CODE_0X02:
if debug:
_LOGGER.debug('Buffer content: %s', binascii.hexlify(rawmessage))... | [
"def",
"_trim_buffer_garbage",
"(",
"rawmessage",
",",
"debug",
"=",
"True",
")",
":",
"while",
"rawmessage",
"and",
"rawmessage",
"[",
"0",
"]",
"!=",
"MESSAGE_START_CODE_0X02",
":",
"if",
"debug",
":",
"_LOGGER",
".",
"debug",
"(",
"'Buffer content: %s'",
",... | Remove leading bytes from a byte stream.
A proper message byte stream begins with 0x02. | [
"Remove",
"leading",
"bytes",
"from",
"a",
"byte",
"stream",
"."
] | python | train | 39 |
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 | 38.96 |
readbeyond/aeneas | aeneas/tree.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L270-L280 | def remove_children(self, reset_parent=True):
"""
Remove all the children of this node.
:param bool reset_parent: if ``True``, set to ``None`` the parent attribute
of the children
"""
if reset_parent:
for child in self.children:
... | [
"def",
"remove_children",
"(",
"self",
",",
"reset_parent",
"=",
"True",
")",
":",
"if",
"reset_parent",
":",
"for",
"child",
"in",
"self",
".",
"children",
":",
"child",
".",
"parent",
"=",
"None",
"self",
".",
"__children",
"=",
"[",
"]"
] | Remove all the children of this node.
:param bool reset_parent: if ``True``, set to ``None`` the parent attribute
of the children | [
"Remove",
"all",
"the",
"children",
"of",
"this",
"node",
"."
] | python | train | 33.636364 |
BD2KGenomics/toil-scripts | src/toil_scripts/bwa_alignment/old_alignment_script/batch_align.py | https://github.com/BD2KGenomics/toil-scripts/blob/f878d863defcdccaabb7fe06f991451b7a198fb7/src/toil_scripts/bwa_alignment/old_alignment_script/batch_align.py#L49-L62 | def generate_unique_key(master_key_path, url):
"""
Input1: Path to the BD2K Master Key (for S3 Encryption)
Input2: S3 URL (e.g. https://s3-us-west-2.amazonaws.com/cgl-driver-projects-encrypted/wcdt/exome_bams/DTB-111-N.bam)
Returns: 32-byte unique key generated for that URL
"""
with open(master... | [
"def",
"generate_unique_key",
"(",
"master_key_path",
",",
"url",
")",
":",
"with",
"open",
"(",
"master_key_path",
",",
"'r'",
")",
"as",
"f",
":",
"master_key",
"=",
"f",
".",
"read",
"(",
")",
"assert",
"len",
"(",
"master_key",
")",
"==",
"32",
","... | Input1: Path to the BD2K Master Key (for S3 Encryption)
Input2: S3 URL (e.g. https://s3-us-west-2.amazonaws.com/cgl-driver-projects-encrypted/wcdt/exome_bams/DTB-111-N.bam)
Returns: 32-byte unique key generated for that URL | [
"Input1",
":",
"Path",
"to",
"the",
"BD2K",
"Master",
"Key",
"(",
"for",
"S3",
"Encryption",
")",
"Input2",
":",
"S3",
"URL",
"(",
"e",
".",
"g",
".",
"https",
":",
"//",
"s3",
"-",
"us",
"-",
"west",
"-",
"2",
".",
"amazonaws",
".",
"com",
"/"... | python | train | 49.785714 |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/_backends/connector_bootstrap/models/pre_shared_key.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/connector_bootstrap/models/pre_shared_key.py#L64-L77 | def endpoint_name(self, endpoint_name):
"""
Sets the endpoint_name of this PreSharedKey.
The unique endpoint identifier that this pre-shared key applies to. 16-64 [printable](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (non-control) ASCII characters.
:param endpoint_name: ... | [
"def",
"endpoint_name",
"(",
"self",
",",
"endpoint_name",
")",
":",
"if",
"endpoint_name",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `endpoint_name`, must not be `None`\"",
")",
"if",
"endpoint_name",
"is",
"not",
"None",
"and",
"not",
"re... | Sets the endpoint_name of this PreSharedKey.
The unique endpoint identifier that this pre-shared key applies to. 16-64 [printable](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (non-control) ASCII characters.
:param endpoint_name: The endpoint_name of this PreSharedKey.
:type: str | [
"Sets",
"the",
"endpoint_name",
"of",
"this",
"PreSharedKey",
".",
"The",
"unique",
"endpoint",
"identifier",
"that",
"this",
"pre",
"-",
"shared",
"key",
"applies",
"to",
".",
"16",
"-",
"64",
"[",
"printable",
"]",
"(",
"https",
":",
"//",
"en",
".",
... | python | train | 53.857143 |
sdispater/poetry | poetry/installation/installer.py | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/installation/installer.py#L300-L306 | def _execute(self, operation): # type: (Operation) -> None
"""
Execute a given operation.
"""
method = operation.job_type
getattr(self, "_execute_{}".format(method))(operation) | [
"def",
"_execute",
"(",
"self",
",",
"operation",
")",
":",
"# type: (Operation) -> None",
"method",
"=",
"operation",
".",
"job_type",
"getattr",
"(",
"self",
",",
"\"_execute_{}\"",
".",
"format",
"(",
"method",
")",
")",
"(",
"operation",
")"
] | Execute a given operation. | [
"Execute",
"a",
"given",
"operation",
"."
] | python | train | 30.285714 |
videntity/django-djmongo | djmongo/mongoutils.py | https://github.com/videntity/django-djmongo/blob/7534e0981a2bc12634cf3f1ed03353623dc57565/djmongo/mongoutils.py#L138-L193 | def query_mongo_sort_decend(
database_name,
collection_name,
query={},
skip=0,
limit=getattr(
settings,
'MONGO_LIMIT',
200),
return_keys=(),
sortkey=None):
"""return a response_dict with a list of search results in decending
... | [
"def",
"query_mongo_sort_decend",
"(",
"database_name",
",",
"collection_name",
",",
"query",
"=",
"{",
"}",
",",
"skip",
"=",
"0",
",",
"limit",
"=",
"getattr",
"(",
"settings",
",",
"'MONGO_LIMIT'",
",",
"200",
")",
",",
"return_keys",
"=",
"(",
")",
"... | return a response_dict with a list of search results in decending
order based on a sort key | [
"return",
"a",
"response_dict",
"with",
"a",
"list",
"of",
"search",
"results",
"in",
"decending",
"order",
"based",
"on",
"a",
"sort",
"key"
] | python | train | 31.178571 |
moonso/vcftoolbox | vcftoolbox/get_header.py | https://github.com/moonso/vcftoolbox/blob/438fb1d85a83812c389774b94802eb5921c89e3a/vcftoolbox/get_header.py#L8-L31 | def get_vcf_header(source):
"""Get the header lines of a vcf file
Args:
source(iterable): A vcf file
Returns:
head (HeaderParser): A headerparser object
"""
head = HeaderParser()
#Parse the header lines
for line in source:
line = line.rst... | [
"def",
"get_vcf_header",
"(",
"source",
")",
":",
"head",
"=",
"HeaderParser",
"(",
")",
"#Parse the header lines",
"for",
"line",
"in",
"source",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
... | Get the header lines of a vcf file
Args:
source(iterable): A vcf file
Returns:
head (HeaderParser): A headerparser object | [
"Get",
"the",
"header",
"lines",
"of",
"a",
"vcf",
"file",
"Args",
":",
"source",
"(",
"iterable",
")",
":",
"A",
"vcf",
"file",
"Returns",
":",
"head",
"(",
"HeaderParser",
")",
":",
"A",
"headerparser",
"object"
] | python | train | 27.833333 |
dnarvaez/gwebsockets | gwebsockets/protocol.py | https://github.com/dnarvaez/gwebsockets/blob/777954a3a97de2e62817f3180d5b3bc530caff65/gwebsockets/protocol.py#L206-L214 | def make_message(message, binary=False):
"""Make text message."""
if isinstance(message, str):
message = message.encode('utf-8')
if binary:
return _make_frame(message, OPCODE_BINARY)
else:
return _make_frame(message, OPCODE_TEXT) | [
"def",
"make_message",
"(",
"message",
",",
"binary",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"message",
",",
"str",
")",
":",
"message",
"=",
"message",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"binary",
":",
"return",
"_make_frame",
"(",
"m... | Make text message. | [
"Make",
"text",
"message",
"."
] | python | train | 29.111111 |
jciskey/pygraph | pygraph/functions/planarity/kocay_algorithm.py | https://github.com/jciskey/pygraph/blob/037bb2f32503fecb60d62921f9766d54109f15e2/pygraph/functions/planarity/kocay_algorithm.py#L955-L960 | def S_star(u, dfs_data):
"""The set of all descendants of u, with u added."""
s_u = S(u, dfs_data)
if u not in s_u:
s_u.append(u)
return s_u | [
"def",
"S_star",
"(",
"u",
",",
"dfs_data",
")",
":",
"s_u",
"=",
"S",
"(",
"u",
",",
"dfs_data",
")",
"if",
"u",
"not",
"in",
"s_u",
":",
"s_u",
".",
"append",
"(",
"u",
")",
"return",
"s_u"
] | The set of all descendants of u, with u added. | [
"The",
"set",
"of",
"all",
"descendants",
"of",
"u",
"with",
"u",
"added",
"."
] | python | train | 26.5 |
skojaku/core-periphery-detection | cpalgorithm/Cucuringu.py | https://github.com/skojaku/core-periphery-detection/blob/d724e6441066622506ddb54d81ee9a1cfd15f766/cpalgorithm/Cucuringu.py#L54-L74 | def detect(self, G):
"""Detect a single core-periphery pair.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> lrc = cp.LowRankCore()
>>> lrc.detect(G)
... | [
"def",
"detect",
"(",
"self",
",",
"G",
")",
":",
"self",
".",
"c_",
",",
"self",
".",
"x_",
"=",
"self",
".",
"_low_rank_core",
"(",
"G",
")",
"self",
".",
"Q_",
"=",
"self",
".",
"_score",
"(",
"G",
",",
"self",
".",
"c_",
",",
"self",
".",... | Detect a single core-periphery pair.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> lrc = cp.LowRankCore()
>>> lrc.detect(G) | [
"Detect",
"a",
"single",
"core",
"-",
"periphery",
"pair",
".",
"Parameters",
"----------",
"G",
":",
"NetworkX",
"graph",
"object",
"Examples",
"--------",
">>>",
"import",
"networkx",
"as",
"nx",
">>>",
"import",
"cpalgorithm",
"as",
"cpa",
">>>",
"G",
"="... | python | train | 20.142857 |
CivicSpleen/ambry | ambry/bundle/bundle.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1459-L1470 | def sync_in_records(self, force=False):
"""Synchronize from files to records"""
self.log('---- Sync Files ----')
for f in self.build_source_files:
f.record_to_objects()
# Only the metadata needs to be driven to the objects, since the other files are used as code,
# ... | [
"def",
"sync_in_records",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"self",
".",
"log",
"(",
"'---- Sync Files ----'",
")",
"for",
"f",
"in",
"self",
".",
"build_source_files",
":",
"f",
".",
"record_to_objects",
"(",
")",
"# Only the metadata needs t... | Synchronize from files to records | [
"Synchronize",
"from",
"files",
"to",
"records"
] | python | train | 36.416667 |
neurosynth/neurosynth | neurosynth/analysis/classify.py | https://github.com/neurosynth/neurosynth/blob/948ce7edce15d7df693446e76834e0c23bfe8f11/neurosynth/analysis/classify.py#L308-L331 | def set_class_weight(self, class_weight='auto', y=None):
""" Sets the class_weight of the classifier to match y """
if class_weight is None:
cw = None
try:
self.clf.set_params(class_weight=cw)
except ValueError:
pass
elif cla... | [
"def",
"set_class_weight",
"(",
"self",
",",
"class_weight",
"=",
"'auto'",
",",
"y",
"=",
"None",
")",
":",
"if",
"class_weight",
"is",
"None",
":",
"cw",
"=",
"None",
"try",
":",
"self",
".",
"clf",
".",
"set_params",
"(",
"class_weight",
"=",
"cw",
... | Sets the class_weight of the classifier to match y | [
"Sets",
"the",
"class_weight",
"of",
"the",
"classifier",
"to",
"match",
"y"
] | python | test | 31.416667 |
trailofbits/manticore | manticore/core/state.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/state.py#L317-L329 | def solve_max(self, expr):
"""
Solves a symbolic :class:`~manticore.core.smtlib.expression.Expression` into
its maximum solution
:param manticore.core.smtlib.Expression expr: Symbolic value to solve
:return: Concrete value
:rtype: list[int]
"""
if isinsta... | [
"def",
"solve_max",
"(",
"self",
",",
"expr",
")",
":",
"if",
"isinstance",
"(",
"expr",
",",
"int",
")",
":",
"return",
"expr",
"expr",
"=",
"self",
".",
"migrate_expression",
"(",
"expr",
")",
"return",
"self",
".",
"_solver",
".",
"max",
"(",
"sel... | Solves a symbolic :class:`~manticore.core.smtlib.expression.Expression` into
its maximum solution
:param manticore.core.smtlib.Expression expr: Symbolic value to solve
:return: Concrete value
:rtype: list[int] | [
"Solves",
"a",
"symbolic",
":",
"class",
":",
"~manticore",
".",
"core",
".",
"smtlib",
".",
"expression",
".",
"Expression",
"into",
"its",
"maximum",
"solution"
] | python | valid | 34.538462 |
swift-nav/libsbp | python/sbp/msg.py | https://github.com/swift-nav/libsbp/blob/5a950608506b23e31b73ef7065da905b646055c1/python/sbp/msg.py#L234-L239 | def to_json(self, sort_keys=False):
"""Produce a JSON-encoded SBP message.
"""
d = self.to_json_dict()
return json.dumps(d, sort_keys=sort_keys) | [
"def",
"to_json",
"(",
"self",
",",
"sort_keys",
"=",
"False",
")",
":",
"d",
"=",
"self",
".",
"to_json_dict",
"(",
")",
"return",
"json",
".",
"dumps",
"(",
"d",
",",
"sort_keys",
"=",
"sort_keys",
")"
] | Produce a JSON-encoded SBP message. | [
"Produce",
"a",
"JSON",
"-",
"encoded",
"SBP",
"message",
"."
] | python | train | 26 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.