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 |
|---|---|---|---|---|---|---|---|---|---|
msmbuilder/msmbuilder | msmbuilder/msm/core.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/core.py#L266-L308 | def draw_samples(self, sequences, n_samples, random_state=None):
"""Sample conformations for a sequences of states.
Parameters
----------
sequences : list or list of lists
A sequence or list of sequences, in which each element corresponds
to a state label.
... | [
"def",
"draw_samples",
"(",
"self",
",",
"sequences",
",",
"n_samples",
",",
"random_state",
"=",
"None",
")",
":",
"if",
"not",
"any",
"(",
"[",
"isinstance",
"(",
"seq",
",",
"collections",
".",
"Iterable",
")",
"for",
"seq",
"in",
"sequences",
"]",
... | Sample conformations for a sequences of states.
Parameters
----------
sequences : list or list of lists
A sequence or list of sequences, in which each element corresponds
to a state label.
n_samples : int
How many samples to return for any given state... | [
"Sample",
"conformations",
"for",
"a",
"sequences",
"of",
"states",
"."
] | python | train | 35.465116 |
rgmining/ria | ria/bipartite_sum.py | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite_sum.py#L85-L120 | def update(self):
""" Update reviewers' anomalous scores and products' summaries.
The update consists of 2 steps;
Step1 (updating summaries):
Update summaries of products with anomalous scores of reviewers
and weight function. The weight is calculated by the manner in
... | [
"def",
"update",
"(",
"self",
")",
":",
"res",
"=",
"super",
"(",
"BipartiteGraph",
",",
"self",
")",
".",
"update",
"(",
")",
"max_v",
"=",
"None",
"min_v",
"=",
"float",
"(",
"\"inf\"",
")",
"for",
"r",
"in",
"self",
".",
"reviewers",
":",
"max_v... | Update reviewers' anomalous scores and products' summaries.
The update consists of 2 steps;
Step1 (updating summaries):
Update summaries of products with anomalous scores of reviewers
and weight function. The weight is calculated by the manner in
:class:`ria.biparti... | [
"Update",
"reviewers",
"anomalous",
"scores",
"and",
"products",
"summaries",
"."
] | python | train | 37.972222 |
angr/angr | angr/sim_manager.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/sim_manager.py#L610-L648 | def merge(self, merge_func=None, merge_key=None, stash='active'):
"""
Merge the states in a given stash.
:param stash: The stash (default: 'active')
:param merge_func: If provided, instead of using state.merge, call this function with
the states as the... | [
"def",
"merge",
"(",
"self",
",",
"merge_func",
"=",
"None",
",",
"merge_key",
"=",
"None",
",",
"stash",
"=",
"'active'",
")",
":",
"self",
".",
"prune",
"(",
"from_stash",
"=",
"stash",
")",
"to_merge",
"=",
"self",
".",
"_fetch_states",
"(",
"stash"... | Merge the states in a given stash.
:param stash: The stash (default: 'active')
:param merge_func: If provided, instead of using state.merge, call this function with
the states as the argument. Should return the merged state.
:param merge_key: If provided, sh... | [
"Merge",
"the",
"states",
"in",
"a",
"given",
"stash",
"."
] | python | train | 43.358974 |
ninuxorg/nodeshot | nodeshot/community/notifications/models/notification.py | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/models/notification.py#L67-L75 | def send_email(self):
""" send email notification according to user settings """
# send only if user notification setting is set to true
if self.check_user_settings():
send_mail(_(self.type), self.email_message, settings.DEFAULT_FROM_EMAIL, [self.to_user.email])
return Tr... | [
"def",
"send_email",
"(",
"self",
")",
":",
"# send only if user notification setting is set to true",
"if",
"self",
".",
"check_user_settings",
"(",
")",
":",
"send_mail",
"(",
"_",
"(",
"self",
".",
"type",
")",
",",
"self",
".",
"email_message",
",",
"setting... | send email notification according to user settings | [
"send",
"email",
"notification",
"according",
"to",
"user",
"settings"
] | python | train | 43.333333 |
adamrothman/ftl | ftl/connection.py | https://github.com/adamrothman/ftl/blob/a88f3df1ecbdfba45035b65f833b8ffffc49b399/ftl/connection.py#L456-L477 | async def get_pushed_stream_ids(self, parent_stream_id: int) -> List[int]:
"""Return a list of all streams pushed by the remote peer that are
children of the specified stream. If no streams have been pushed when
this method is called, waits until at least one stream has been pushed.
"""
... | [
"async",
"def",
"get_pushed_stream_ids",
"(",
"self",
",",
"parent_stream_id",
":",
"int",
")",
"->",
"List",
"[",
"int",
"]",
":",
"if",
"parent_stream_id",
"not",
"in",
"self",
".",
"_streams",
":",
"logger",
".",
"error",
"(",
"f'Parent stream {parent_strea... | Return a list of all streams pushed by the remote peer that are
children of the specified stream. If no streams have been pushed when
this method is called, waits until at least one stream has been pushed. | [
"Return",
"a",
"list",
"of",
"all",
"streams",
"pushed",
"by",
"the",
"remote",
"peer",
"that",
"are",
"children",
"of",
"the",
"specified",
"stream",
".",
"If",
"no",
"streams",
"have",
"been",
"pushed",
"when",
"this",
"method",
"is",
"called",
"waits",
... | python | train | 42.5 |
iterative/dvc | dvc/logger.py | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/logger.py#L134-L140 | def _progress_aware(self):
"""Add a new line if progress bar hasn't finished"""
from dvc.progress import progress
if not progress.is_finished:
progress._print()
progress.clearln() | [
"def",
"_progress_aware",
"(",
"self",
")",
":",
"from",
"dvc",
".",
"progress",
"import",
"progress",
"if",
"not",
"progress",
".",
"is_finished",
":",
"progress",
".",
"_print",
"(",
")",
"progress",
".",
"clearln",
"(",
")"
] | Add a new line if progress bar hasn't finished | [
"Add",
"a",
"new",
"line",
"if",
"progress",
"bar",
"hasn",
"t",
"finished"
] | python | train | 31.142857 |
pantsbuild/pants | src/python/pants/scm/git.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/scm/git.py#L478-L488 | def _realpath(self, relpath):
"""Follow symlinks to find the real path to a file or directory in the repo.
:returns: if the expanded path points to a file, the relative path
to that file; if a directory, the relative path + '/'; if
a symlink outside the repo, a path starting with / ... | [
"def",
"_realpath",
"(",
"self",
",",
"relpath",
")",
":",
"obj",
",",
"path_so_far",
"=",
"self",
".",
"_read_object",
"(",
"relpath",
",",
"MAX_SYMLINKS_IN_REALPATH",
")",
"if",
"isinstance",
"(",
"obj",
",",
"self",
".",
"Symlink",
")",
":",
"raise",
... | Follow symlinks to find the real path to a file or directory in the repo.
:returns: if the expanded path points to a file, the relative path
to that file; if a directory, the relative path + '/'; if
a symlink outside the repo, a path starting with / or ../. | [
"Follow",
"symlinks",
"to",
"find",
"the",
"real",
"path",
"to",
"a",
"file",
"or",
"directory",
"in",
"the",
"repo",
"."
] | python | train | 47.181818 |
aewallin/allantools | allantools/allantools.py | https://github.com/aewallin/allantools/blob/b5c695a5af4379fcea4d4ce93a066cb902e7ee0a/allantools/allantools.py#L157-L245 | def mdev(data, rate=1.0, data_type="phase", taus=None):
""" Modified Allan deviation.
Used to distinguish between White and Flicker Phase Modulation.
.. math::
\\sigma^2_{MDEV}(m\\tau_0) = { 1 \\over 2 (m \\tau_0 )^2 (N-3m+1) }
\\sum_{j=1}^{N-3m+1} \\lbrace
\\sum_{i=j}^{j+m-1... | [
"def",
"mdev",
"(",
"data",
",",
"rate",
"=",
"1.0",
",",
"data_type",
"=",
"\"phase\"",
",",
"taus",
"=",
"None",
")",
":",
"phase",
"=",
"input_to_phase",
"(",
"data",
",",
"rate",
",",
"data_type",
")",
"(",
"phase",
",",
"ms",
",",
"taus_used",
... | Modified Allan deviation.
Used to distinguish between White and Flicker Phase Modulation.
.. math::
\\sigma^2_{MDEV}(m\\tau_0) = { 1 \\over 2 (m \\tau_0 )^2 (N-3m+1) }
\\sum_{j=1}^{N-3m+1} \\lbrace
\\sum_{i=j}^{j+m-1} {x}_{i+2m} - 2x_{i+m} + x_{i} \\rbrace^2
Parameters
--... | [
"Modified",
"Allan",
"deviation",
".",
"Used",
"to",
"distinguish",
"between",
"White",
"and",
"Flicker",
"Phase",
"Modulation",
"."
] | python | train | 28.595506 |
apache/incubator-mxnet | python/mxnet/contrib/svrg_optimization/svrg_module.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/svrg_optimization/svrg_module.py#L554-L579 | def prepare(self, data_batch, sparse_row_id_fn=None):
"""Prepares two modules for processing a data batch.
Usually involves switching bucket and reshaping.
For modules that contain `row_sparse` parameters in KVStore,
it prepares the `row_sparse` parameters based on the sparse_row_id_fn.... | [
"def",
"prepare",
"(",
"self",
",",
"data_batch",
",",
"sparse_row_id_fn",
"=",
"None",
")",
":",
"super",
"(",
"SVRGModule",
",",
"self",
")",
".",
"prepare",
"(",
"data_batch",
",",
"sparse_row_id_fn",
"=",
"sparse_row_id_fn",
")",
"self",
".",
"_mod_aux",... | Prepares two modules for processing a data batch.
Usually involves switching bucket and reshaping.
For modules that contain `row_sparse` parameters in KVStore,
it prepares the `row_sparse` parameters based on the sparse_row_id_fn.
When KVStore is used to update parameters for multi-dev... | [
"Prepares",
"two",
"modules",
"for",
"processing",
"a",
"data",
"batch",
"."
] | python | train | 53.730769 |
jobovy/galpy | galpy/actionAngle/actionAngleIsochrone.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngleIsochrone.py#L191-L300 | def _actionsFreqsAngles(self,*args,**kwargs):
"""
NAME:
actionsFreqsAngles (_actionsFreqsAngles)
PURPOSE:
evaluate the actions, frequencies, and angles (jr,lz,jz,Omegar,Omegaphi,Omegaz,angler,anglephi,anglez)
INPUT:
Either:
a) R,vR,vT,z,vz[,... | [
"def",
"_actionsFreqsAngles",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"5",
":",
"#R,vR.vT, z, vz pragma: no cover",
"raise",
"IOError",
"(",
"\"You need to provide phi when calculating angles\"",
")",
... | NAME:
actionsFreqsAngles (_actionsFreqsAngles)
PURPOSE:
evaluate the actions, frequencies, and angles (jr,lz,jz,Omegar,Omegaphi,Omegaz,angler,anglephi,anglez)
INPUT:
Either:
a) R,vR,vT,z,vz[,phi]:
1) floats: phase-space value for single obj... | [
"NAME",
":",
"actionsFreqsAngles",
"(",
"_actionsFreqsAngles",
")",
"PURPOSE",
":",
"evaluate",
"the",
"actions",
"frequencies",
"and",
"angles",
"(",
"jr",
"lz",
"jz",
"Omegar",
"Omegaphi",
"Omegaz",
"angler",
"anglephi",
"anglez",
")",
"INPUT",
":",
"Either",
... | python | train | 40.309091 |
Clinical-Genomics/scout | scout/parse/variant/rank_score.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/parse/variant/rank_score.py#L3-L19 | def parse_rank_score(rank_score_entry, case_id):
"""Parse the rank score
Args:
rank_score_entry(str): The raw rank score entry
case_id(str)
Returns:
rank_score(float)
"""
rank_score = None
if rank_score_entry:
for family_info in rank_score_en... | [
"def",
"parse_rank_score",
"(",
"rank_score_entry",
",",
"case_id",
")",
":",
"rank_score",
"=",
"None",
"if",
"rank_score_entry",
":",
"for",
"family_info",
"in",
"rank_score_entry",
".",
"split",
"(",
"','",
")",
":",
"splitted_info",
"=",
"family_info",
".",
... | Parse the rank score
Args:
rank_score_entry(str): The raw rank score entry
case_id(str)
Returns:
rank_score(float) | [
"Parse",
"the",
"rank",
"score"
] | python | test | 28.764706 |
pyviz/holoviews | holoviews/core/util.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/util.py#L1960-L1981 | def cftime_to_timestamp(date, time_unit='us'):
"""Converts cftime to timestamp since epoch in milliseconds
Non-standard calendars (e.g. Julian or no leap calendars)
are converted to standard Gregorian calendar. This can cause
extra space to be added for dates that don't exist in the original
calend... | [
"def",
"cftime_to_timestamp",
"(",
"date",
",",
"time_unit",
"=",
"'us'",
")",
":",
"import",
"cftime",
"utime",
"=",
"cftime",
".",
"utime",
"(",
"'microseconds since 1970-01-01 00:00:00'",
")",
"if",
"time_unit",
"==",
"'us'",
":",
"tscale",
"=",
"1",
"else"... | Converts cftime to timestamp since epoch in milliseconds
Non-standard calendars (e.g. Julian or no leap calendars)
are converted to standard Gregorian calendar. This can cause
extra space to be added for dates that don't exist in the original
calendar. In order to handle these dates correctly a custom ... | [
"Converts",
"cftime",
"to",
"timestamp",
"since",
"epoch",
"in",
"milliseconds"
] | python | train | 36.5 |
liip/taxi | taxi/commands/commit.py | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/commit.py#L24-L84 | def commit(ctx, f, force_yes, date):
"""
Commits your work to the server. The [date] option can be used either as a
single date (eg. 20.01.2014), as a range (eg. 20.01.2014-22.01.2014), or as
a range with one of the dates omitted (eg. -22.01.2014).
"""
timesheet_collection = get_timesheet_collec... | [
"def",
"commit",
"(",
"ctx",
",",
"f",
",",
"force_yes",
",",
"date",
")",
":",
"timesheet_collection",
"=",
"get_timesheet_collection_for_context",
"(",
"ctx",
",",
"f",
")",
"if",
"not",
"date",
"and",
"not",
"force_yes",
":",
"non_workday_entries",
"=",
"... | Commits your work to the server. The [date] option can be used either as a
single date (eg. 20.01.2014), as a range (eg. 20.01.2014-22.01.2014), or as
a range with one of the dates omitted (eg. -22.01.2014). | [
"Commits",
"your",
"work",
"to",
"the",
"server",
".",
"The",
"[",
"date",
"]",
"option",
"can",
"be",
"used",
"either",
"as",
"a",
"single",
"date",
"(",
"eg",
".",
"20",
".",
"01",
".",
"2014",
")",
"as",
"a",
"range",
"(",
"eg",
".",
"20",
"... | python | train | 41.704918 |
uw-it-aca/uw-restclients-canvas | uw_canvas/sis_import.py | https://github.com/uw-it-aca/uw-restclients-canvas/blob/9845faf33d49a8f06908efc22640c001116d6ea2/uw_canvas/sis_import.py#L18-L32 | def import_str(self, csv, params={}):
"""
Imports a CSV string.
https://canvas.instructure.com/doc/api/sis_imports.html#method.sis_imports_api.create
"""
if not self._canvas_account_id:
raise MissingAccountID()
params["import_type"] = SISImportModel.CSV_IMPO... | [
"def",
"import_str",
"(",
"self",
",",
"csv",
",",
"params",
"=",
"{",
"}",
")",
":",
"if",
"not",
"self",
".",
"_canvas_account_id",
":",
"raise",
"MissingAccountID",
"(",
")",
"params",
"[",
"\"import_type\"",
"]",
"=",
"SISImportModel",
".",
"CSV_IMPORT... | Imports a CSV string.
https://canvas.instructure.com/doc/api/sis_imports.html#method.sis_imports_api.create | [
"Imports",
"a",
"CSV",
"string",
"."
] | python | test | 36.8 |
arne-cl/discoursegraphs | src/discoursegraphs/readwrite/mmax2.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/mmax2.py#L416-L444 | def sort_sentences_by_token_order(sentence_root_nodes, token_nodes):
"""
Given a list of sentence markables (i.e. sentence root nodes) and a list of
lists of token markables (one list per sentence), returns a list of
(sentence root node, token nodes) tuples. The result is sorted by the
order in whic... | [
"def",
"sort_sentences_by_token_order",
"(",
"sentence_root_nodes",
",",
"token_nodes",
")",
":",
"def",
"sentence_sort_key",
"(",
"sentence_token_tuple",
")",
":",
"\"\"\"\n extracts a sortable key from the first token node ID of a sentence\n \"\"\"",
"return",
"natura... | Given a list of sentence markables (i.e. sentence root nodes) and a list of
lists of token markables (one list per sentence), returns a list of
(sentence root node, token nodes) tuples. The result is sorted by the
order in which the tokens occur in the text.
Parameters
----------
sentence_root_... | [
"Given",
"a",
"list",
"of",
"sentence",
"markables",
"(",
"i",
".",
"e",
".",
"sentence",
"root",
"nodes",
")",
"and",
"a",
"list",
"of",
"lists",
"of",
"token",
"markables",
"(",
"one",
"list",
"per",
"sentence",
")",
"returns",
"a",
"list",
"of",
"... | python | train | 40.827586 |
F-Secure/see | see/observer.py | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/observer.py#L93-L108 | def trigger(self, event, **kwargs):
"""
Triggers an event.
All subscribed handlers will be executed, asynchronous ones
won't block this call.
@param event: (str|see.Event) event intended to be raised.
"""
with self._handlers.trigger_mutex:
event = pr... | [
"def",
"trigger",
"(",
"self",
",",
"event",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"_handlers",
".",
"trigger_mutex",
":",
"event",
"=",
"prime_event",
"(",
"event",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"*",
"*",
"kw... | Triggers an event.
All subscribed handlers will be executed, asynchronous ones
won't block this call.
@param event: (str|see.Event) event intended to be raised. | [
"Triggers",
"an",
"event",
"."
] | python | train | 35.9375 |
bitesofcode/projexui | projexui/widgets/xchart/xchartaxis.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchart/xchartaxis.py#L485-L508 | def valueAt(self, percent):
"""
Returns the value at the inputed percent.
:param percent | <float>
:return <variant>
"""
values = self.values()
if percent < 0:
index = 0
elif percent > 1:
index ... | [
"def",
"valueAt",
"(",
"self",
",",
"percent",
")",
":",
"values",
"=",
"self",
".",
"values",
"(",
")",
"if",
"percent",
"<",
"0",
":",
"index",
"=",
"0",
"elif",
"percent",
">",
"1",
":",
"index",
"=",
"-",
"1",
"else",
":",
"index",
"=",
"pe... | Returns the value at the inputed percent.
:param percent | <float>
:return <variant> | [
"Returns",
"the",
"value",
"at",
"the",
"inputed",
"percent",
".",
":",
"param",
"percent",
"|",
"<float",
">",
":",
"return",
"<variant",
">"
] | python | train | 28.041667 |
duniter/duniter-python-api | duniterpy/key/signing_key.py | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/signing_key.py#L175-L193 | def from_wif_or_ewif_file(path: str, password: Optional[str] = None) -> SigningKeyType:
"""
Return SigningKey instance from Duniter WIF or EWIF file
:param path: Path to WIF of EWIF file
:param password: Password needed for EWIF file
"""
with open(path, 'r') as fh:
... | [
"def",
"from_wif_or_ewif_file",
"(",
"path",
":",
"str",
",",
"password",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"SigningKeyType",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"fh",
":",
"wif_content",
"=",
"fh",
".",
"... | Return SigningKey instance from Duniter WIF or EWIF file
:param path: Path to WIF of EWIF file
:param password: Password needed for EWIF file | [
"Return",
"SigningKey",
"instance",
"from",
"Duniter",
"WIF",
"or",
"EWIF",
"file"
] | python | train | 36.631579 |
adrn/gala | gala/dynamics/nonlinear.py | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/nonlinear.py#L12-L95 | def fast_lyapunov_max(w0, hamiltonian, dt, n_steps, d0=1e-5,
n_steps_per_pullback=10, noffset_orbits=2, t1=0.,
atol=1E-10, rtol=1E-10, nmax=0, return_orbit=True):
"""
Compute the maximum Lyapunov exponent using a C-implemented estimator
that uses the DOPRI853 inte... | [
"def",
"fast_lyapunov_max",
"(",
"w0",
",",
"hamiltonian",
",",
"dt",
",",
"n_steps",
",",
"d0",
"=",
"1e-5",
",",
"n_steps_per_pullback",
"=",
"10",
",",
"noffset_orbits",
"=",
"2",
",",
"t1",
"=",
"0.",
",",
"atol",
"=",
"1E-10",
",",
"rtol",
"=",
... | Compute the maximum Lyapunov exponent using a C-implemented estimator
that uses the DOPRI853 integrator.
Parameters
----------
w0 : `~gala.dynamics.PhaseSpacePosition`, array_like
Initial conditions.
hamiltonian : `~gala.potential.Hamiltonian`
dt : numeric
Timestep.
n_steps ... | [
"Compute",
"the",
"maximum",
"Lyapunov",
"exponent",
"using",
"a",
"C",
"-",
"implemented",
"estimator",
"that",
"uses",
"the",
"DOPRI853",
"integrator",
"."
] | python | train | 34.928571 |
larryng/narwal | narwal/reddit.py | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L512-L527 | def submit_text(self, sr, title, text, follow=True):
"""Login required. POSTs a text submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise.
Argument ``follow`` exists because reddit only returns the permalink afte... | [
"def",
"submit_text",
"(",
"self",
",",
"sr",
",",
"title",
",",
"text",
",",
"follow",
"=",
"True",
")",
":",
"return",
"self",
".",
"_submit",
"(",
"sr",
",",
"title",
",",
"'self'",
",",
"text",
"=",
"text",
",",
"follow",
"=",
"follow",
")"
] | Login required. POSTs a text submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise.
Argument ``follow`` exists because reddit only returns the permalink after POSTing a submission. In order to get detailed info on the ne... | [
"Login",
"required",
".",
"POSTs",
"a",
"text",
"submission",
".",
"Returns",
":",
"class",
":",
"things",
".",
"Link",
"object",
"if",
"follow",
"=",
"True",
"(",
"default",
")",
"or",
"the",
"string",
"permalink",
"of",
"the",
"new",
"submission",
"oth... | python | train | 64.5 |
emencia/dr-dump | drdump/dependancies.py | https://github.com/emencia/dr-dump/blob/f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b/drdump/dependancies.py#L71-L76 | def get_dump_order(self, names):
"""
Return ordered dump names required for a given dump names list
"""
finded_names = self.get_dump_names(names)
return [item for item in self if item in finded_names] | [
"def",
"get_dump_order",
"(",
"self",
",",
"names",
")",
":",
"finded_names",
"=",
"self",
".",
"get_dump_names",
"(",
"names",
")",
"return",
"[",
"item",
"for",
"item",
"in",
"self",
"if",
"item",
"in",
"finded_names",
"]"
] | Return ordered dump names required for a given dump names list | [
"Return",
"ordered",
"dump",
"names",
"required",
"for",
"a",
"given",
"dump",
"names",
"list"
] | python | train | 39.166667 |
jantman/awslimitchecker | dev/release_utils.py | https://github.com/jantman/awslimitchecker/blob/e50197f70f3d0abcc5cfc7fde6336f548b790e34/dev/release_utils.py#L117-L128 | def _find_travis_job(self, build, toxenv):
"""Given a build object, find the acceptance36 job"""
for jobid in build.job_ids:
j = self._travis.job(jobid)
if 'TOXENV=%s' % toxenv in j.config['env']:
logger.debug('Found %s job: %s', toxenv, j.number)
... | [
"def",
"_find_travis_job",
"(",
"self",
",",
"build",
",",
"toxenv",
")",
":",
"for",
"jobid",
"in",
"build",
".",
"job_ids",
":",
"j",
"=",
"self",
".",
"_travis",
".",
"job",
"(",
"jobid",
")",
"if",
"'TOXENV=%s'",
"%",
"toxenv",
"in",
"j",
".",
... | Given a build object, find the acceptance36 job | [
"Given",
"a",
"build",
"object",
"find",
"the",
"acceptance36",
"job"
] | python | train | 39.916667 |
pawamoy/python-getdoc | src/getdoc/__init__.py | https://github.com/pawamoy/python-getdoc/blob/7589605be746ecde54f3fb68a46c88242d9b6405/src/getdoc/__init__.py#L144-L151 | def get_function_doc(function, config=default_config):
"""Return doc for a function."""
if config.exclude_function:
for ex in config.exclude_function:
if ex.match(function.__name__):
return None
return _doc_object(function, 'function', config=config) | [
"def",
"get_function_doc",
"(",
"function",
",",
"config",
"=",
"default_config",
")",
":",
"if",
"config",
".",
"exclude_function",
":",
"for",
"ex",
"in",
"config",
".",
"exclude_function",
":",
"if",
"ex",
".",
"match",
"(",
"function",
".",
"__name__",
... | Return doc for a function. | [
"Return",
"doc",
"for",
"a",
"function",
"."
] | python | train | 36.5 |
briwilcox/Concurrent-Pandas | concurrentpandas.py | https://github.com/briwilcox/Concurrent-Pandas/blob/22cb392dacb712e1bdb5b60c6ba7015c38445c99/concurrentpandas.py#L241-L248 | def set_source_quandl(self, quandl_token):
"""
Set data source to Quandl
"""
self.data_worker = data_worker
self.worker_args = {"function": Quandl.get, "input": self.input_queue, "output": self.output_map,
"token": quandl_token}
self.source_nam... | [
"def",
"set_source_quandl",
"(",
"self",
",",
"quandl_token",
")",
":",
"self",
".",
"data_worker",
"=",
"data_worker",
"self",
".",
"worker_args",
"=",
"{",
"\"function\"",
":",
"Quandl",
".",
"get",
",",
"\"input\"",
":",
"self",
".",
"input_queue",
",",
... | Set data source to Quandl | [
"Set",
"data",
"source",
"to",
"Quandl"
] | python | train | 40.625 |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L3033-L3037 | def sharing_agreement_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/sharing_agreements#show-a-sharing-agreement"
api_path = "/api/v2/sharing_agreements/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | [
"def",
"sharing_agreement_show",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/sharing_agreements/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"call",
"("... | https://developer.zendesk.com/rest_api/docs/core/sharing_agreements#show-a-sharing-agreement | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"core",
"/",
"sharing_agreements#show",
"-",
"a",
"-",
"sharing",
"-",
"agreement"
] | python | train | 58.2 |
spyder-ide/spyder | spyder/plugins/help/plugin.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/plugin.py#L373-L402 | def set_plain_text(self, text, is_code):
"""Set plain text docs"""
# text is coming from utils.dochelpers.getdoc
if type(text) is dict:
name = text['name']
if name:
rst_title = ''.join(['='*len(name), '\n', name, '\n',
... | [
"def",
"set_plain_text",
"(",
"self",
",",
"text",
",",
"is_code",
")",
":",
"# text is coming from utils.dochelpers.getdoc\r",
"if",
"type",
"(",
"text",
")",
"is",
"dict",
":",
"name",
"=",
"text",
"[",
"'name'",
"]",
"if",
"name",
":",
"rst_title",
"=",
... | Set plain text docs | [
"Set",
"plain",
"text",
"docs"
] | python | train | 34.266667 |
ToFuProject/tofu | tofu/utils.py | https://github.com/ToFuProject/tofu/blob/39d6b2e7ced9e13666572dfd37e19403f1d6ff8d/tofu/utils.py#L793-L823 | def strip(self, strip=0, **kwdargs):
""" Remove non-essential attributes to save memory / disk usage
Useful to save a very compressed version of the object
The higher strip => the more stripped the object
Use strip=0 to recover all atributes
See the difference by doing:
... | [
"def",
"strip",
"(",
"self",
",",
"strip",
"=",
"0",
",",
"*",
"*",
"kwdargs",
")",
":",
"msg",
"=",
"\"Only allowed strip values are:\\n\"",
"msg",
"+=",
"\" \"",
"+",
"\", \"",
".",
"join",
"(",
"[",
"\"{0}\"",
".",
"format",
"(",
"ii",
")",
"for"... | Remove non-essential attributes to save memory / disk usage
Useful to save a very compressed version of the object
The higher strip => the more stripped the object
Use strip=0 to recover all atributes
See the difference by doing:
> self.get_nbytes()
> self.strip... | [
"Remove",
"non",
"-",
"essential",
"attributes",
"to",
"save",
"memory",
"/",
"disk",
"usage"
] | python | train | 35.516129 |
cloudtools/stacker | stacker/dag/__init__.py | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/dag/__init__.py#L118-L134 | def delete_edge(self, ind_node, dep_node):
""" Delete an edge from the graph.
Args:
ind_node (str): The independent node to delete an edge from.
dep_node (str): The dependent node that has a dependency on the
ind_node.
Raises:
Key... | [
"def",
"delete_edge",
"(",
"self",
",",
"ind_node",
",",
"dep_node",
")",
":",
"graph",
"=",
"self",
".",
"graph",
"if",
"dep_node",
"not",
"in",
"graph",
".",
"get",
"(",
"ind_node",
",",
"[",
"]",
")",
":",
"raise",
"KeyError",
"(",
"\"No edge exists... | Delete an edge from the graph.
Args:
ind_node (str): The independent node to delete an edge from.
dep_node (str): The dependent node that has a dependency on the
ind_node.
Raises:
KeyError: Raised when the edge doesn't already exist. | [
"Delete",
"an",
"edge",
"from",
"the",
"graph",
"."
] | python | train | 35.470588 |
materialsproject/pymatgen | pymatgen/analysis/ewald.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/ewald.py#L473-L481 | def minimize_matrix(self):
"""
This method finds and returns the permutations that produce the lowest
ewald sum calls recursive function to iterate through permutations
"""
if self._algo == EwaldMinimizer.ALGO_FAST or \
self._algo == EwaldMinimizer.ALGO_BE... | [
"def",
"minimize_matrix",
"(",
"self",
")",
":",
"if",
"self",
".",
"_algo",
"==",
"EwaldMinimizer",
".",
"ALGO_FAST",
"or",
"self",
".",
"_algo",
"==",
"EwaldMinimizer",
".",
"ALGO_BEST_FIRST",
":",
"return",
"self",
".",
"_recurse",
"(",
"self",
".",
"_m... | This method finds and returns the permutations that produce the lowest
ewald sum calls recursive function to iterate through permutations | [
"This",
"method",
"finds",
"and",
"returns",
"the",
"permutations",
"that",
"produce",
"the",
"lowest",
"ewald",
"sum",
"calls",
"recursive",
"function",
"to",
"iterate",
"through",
"permutations"
] | python | train | 49.555556 |
python/performance | performance/benchmarks/bm_regex_effbot.py | https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/benchmarks/bm_regex_effbot.py#L97-L126 | def init_benchmarks(n_values=None):
"""Initialize the strings we'll run the regexes against.
The strings used in the benchmark are prefixed and suffixed by
strings that are repeated n times.
The sequence n_values contains the values for n.
If n_values is None the values of n from the original benc... | [
"def",
"init_benchmarks",
"(",
"n_values",
"=",
"None",
")",
":",
"if",
"n_values",
"is",
"None",
":",
"n_values",
"=",
"(",
"0",
",",
"5",
",",
"50",
",",
"250",
",",
"1000",
",",
"5000",
",",
"10000",
")",
"string_tables",
"=",
"{",
"n",
":",
"... | Initialize the strings we'll run the regexes against.
The strings used in the benchmark are prefixed and suffixed by
strings that are repeated n times.
The sequence n_values contains the values for n.
If n_values is None the values of n from the original benchmark
are used.
The generated list... | [
"Initialize",
"the",
"strings",
"we",
"ll",
"run",
"the",
"regexes",
"against",
"."
] | python | test | 28.7 |
tariqdaouda/pyGeno | pyGeno/tools/ProgressBar.py | https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/ProgressBar.py#L60-L66 | def log(self) :
"""logs stats about the progression, without printing anything on screen"""
self.logs['epochDuration'].append(self.lastEpochDuration)
self.logs['avg'].append(self.avg)
self.logs['runtime'].append(self.runtime)
self.logs['remtime'].append(self.remtime) | [
"def",
"log",
"(",
"self",
")",
":",
"self",
".",
"logs",
"[",
"'epochDuration'",
"]",
".",
"append",
"(",
"self",
".",
"lastEpochDuration",
")",
"self",
".",
"logs",
"[",
"'avg'",
"]",
".",
"append",
"(",
"self",
".",
"avg",
")",
"self",
".",
"log... | logs stats about the progression, without printing anything on screen | [
"logs",
"stats",
"about",
"the",
"progression",
"without",
"printing",
"anything",
"on",
"screen"
] | python | train | 39.142857 |
brutasse/graphite-api | graphite_api/functions.py | https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L3158-L3243 | def timeShift(requestContext, seriesList, timeShift, resetEnd=True,
alignDST=False):
"""
Takes one metric or a wildcard seriesList, followed by a quoted string
with the length of time (See ``from / until`` in the render\_api_ for
examples of time formats).
Draws the selected metrics s... | [
"def",
"timeShift",
"(",
"requestContext",
",",
"seriesList",
",",
"timeShift",
",",
"resetEnd",
"=",
"True",
",",
"alignDST",
"=",
"False",
")",
":",
"# Default to negative. parseTimeOffset defaults to +",
"if",
"timeShift",
"[",
"0",
"]",
".",
"isdigit",
"(",
... | Takes one metric or a wildcard seriesList, followed by a quoted string
with the length of time (See ``from / until`` in the render\_api_ for
examples of time formats).
Draws the selected metrics shifted in time. If no sign is given, a minus
sign ( - ) is implied which will shift the metric back in time... | [
"Takes",
"one",
"metric",
"or",
"a",
"wildcard",
"seriesList",
"followed",
"by",
"a",
"quoted",
"string",
"with",
"the",
"length",
"of",
"time",
"(",
"See",
"from",
"/",
"until",
"in",
"the",
"render",
"\\",
"_api_",
"for",
"examples",
"of",
"time",
"for... | python | train | 39.255814 |
edx/edx-enterprise | enterprise/views.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/views.py#L1778-L1808 | def post(self, request, *args, **kwargs):
"""
Run some custom POST logic for Enterprise workflows before routing the user through existing views.
"""
# pylint: disable=unused-variable
enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variable... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-variable",
"enterprise_customer_uuid",
",",
"course_run_id",
",",
"course_key",
",",
"program_uuid",
"=",
"RouterView",
".",
"get_path_variab... | Run some custom POST logic for Enterprise workflows before routing the user through existing views. | [
"Run",
"some",
"custom",
"POST",
"logic",
"for",
"Enterprise",
"workflows",
"before",
"routing",
"the",
"user",
"through",
"existing",
"views",
"."
] | python | valid | 51 |
siznax/wptools | scripts/wptool.py | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/scripts/wptool.py#L19-L30 | def _html_image(page):
"""
returns HTML img tag
"""
source = _image(page)
if not source:
return
alt = page.data.get('label') or page.data.get('title')
img = "<img src=\"%s\"" % source
img += " alt=\"%s\" title=\"%s\" " % (alt, alt)
img += "align=\"right\" width=\"240\">"
... | [
"def",
"_html_image",
"(",
"page",
")",
":",
"source",
"=",
"_image",
"(",
"page",
")",
"if",
"not",
"source",
":",
"return",
"alt",
"=",
"page",
".",
"data",
".",
"get",
"(",
"'label'",
")",
"or",
"page",
".",
"data",
".",
"get",
"(",
"'title'",
... | returns HTML img tag | [
"returns",
"HTML",
"img",
"tag"
] | python | train | 26.583333 |
intel-analytics/BigDL | pyspark/bigdl/nn/layer.py | https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L134-L142 | def set_running_mean(self, running_mean):
"""
Set the running mean of the layer.
Only use this method for a BatchNormalization layer.
:param running_mean: a Numpy array.
"""
callBigDlFunc(self.bigdl_type, "setRunningMean",
self.value, JTensor.from_nd... | [
"def",
"set_running_mean",
"(",
"self",
",",
"running_mean",
")",
":",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"setRunningMean\"",
",",
"self",
".",
"value",
",",
"JTensor",
".",
"from_ndarray",
"(",
"running_mean",
")",
")",
"return",
"self"
] | Set the running mean of the layer.
Only use this method for a BatchNormalization layer.
:param running_mean: a Numpy array. | [
"Set",
"the",
"running",
"mean",
"of",
"the",
"layer",
".",
"Only",
"use",
"this",
"method",
"for",
"a",
"BatchNormalization",
"layer",
".",
":",
"param",
"running_mean",
":",
"a",
"Numpy",
"array",
"."
] | python | test | 39.111111 |
vfilimonov/pydatastream | pydatastream/pydatastream.py | https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L119-L122 | def version(self):
"""Return version of the TR DWE."""
res = self.client.service.Version()
return '.'.join([ustr(x) for x in res[0]]) | [
"def",
"version",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"client",
".",
"service",
".",
"Version",
"(",
")",
"return",
"'.'",
".",
"join",
"(",
"[",
"ustr",
"(",
"x",
")",
"for",
"x",
"in",
"res",
"[",
"0",
"]",
"]",
")"
] | Return version of the TR DWE. | [
"Return",
"version",
"of",
"the",
"TR",
"DWE",
"."
] | python | train | 38.5 |
edx/edx-enterprise | integrated_channels/xapi/serializers.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/xapi/serializers.py#L76-L89 | def get_course_duration(self, obj):
"""
Get course's duration as a timedelta.
Arguments:
obj (CourseOverview): CourseOverview object
Returns:
(timedelta): Duration of a course.
"""
duration = obj.end - obj.start if obj.start and obj.end else None... | [
"def",
"get_course_duration",
"(",
"self",
",",
"obj",
")",
":",
"duration",
"=",
"obj",
".",
"end",
"-",
"obj",
".",
"start",
"if",
"obj",
".",
"start",
"and",
"obj",
".",
"end",
"else",
"None",
"if",
"duration",
":",
"return",
"strfdelta",
"(",
"du... | Get course's duration as a timedelta.
Arguments:
obj (CourseOverview): CourseOverview object
Returns:
(timedelta): Duration of a course. | [
"Get",
"course",
"s",
"duration",
"as",
"a",
"timedelta",
"."
] | python | valid | 29.142857 |
erikrose/conway | bin/conway.py | https://github.com/erikrose/conway/blob/4c185d5f2d4b942a0710d7593926e7b749b16015/bin/conway.py#L98-L102 | def draw(board, term, cells):
"""Draw a board to the terminal."""
for (x, y), state in board.iteritems():
with term.location(x, y):
print cells[state], | [
"def",
"draw",
"(",
"board",
",",
"term",
",",
"cells",
")",
":",
"for",
"(",
"x",
",",
"y",
")",
",",
"state",
"in",
"board",
".",
"iteritems",
"(",
")",
":",
"with",
"term",
".",
"location",
"(",
"x",
",",
"y",
")",
":",
"print",
"cells",
"... | Draw a board to the terminal. | [
"Draw",
"a",
"board",
"to",
"the",
"terminal",
"."
] | python | train | 35 |
devassistant/devassistant | devassistant/yaml_assistant.py | https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_assistant.py#L141-L158 | def proper_kwargs(self, section, kwargs):
"""Returns kwargs updated with proper meta variables (like __assistant__).
If this method is run repeatedly with the same section and the same kwargs,
it always modifies kwargs in the same way.
"""
kwargs['__section__'] = section
... | [
"def",
"proper_kwargs",
"(",
"self",
",",
"section",
",",
"kwargs",
")",
":",
"kwargs",
"[",
"'__section__'",
"]",
"=",
"section",
"kwargs",
"[",
"'__assistant__'",
"]",
"=",
"self",
"kwargs",
"[",
"'__env__'",
"]",
"=",
"copy",
".",
"deepcopy",
"(",
"os... | Returns kwargs updated with proper meta variables (like __assistant__).
If this method is run repeatedly with the same section and the same kwargs,
it always modifies kwargs in the same way. | [
"Returns",
"kwargs",
"updated",
"with",
"proper",
"meta",
"variables",
"(",
"like",
"__assistant__",
")",
".",
"If",
"this",
"method",
"is",
"run",
"repeatedly",
"with",
"the",
"same",
"section",
"and",
"the",
"same",
"kwargs",
"it",
"always",
"modifies",
"k... | python | train | 46.333333 |
watson-developer-cloud/python-sdk | ibm_watson/assistant_v2.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/assistant_v2.py#L948-L957 | def _from_dict(cls, _dict):
"""Initialize a MessageContext object from a json dictionary."""
args = {}
if 'global' in _dict:
args['global_'] = MessageContextGlobal._from_dict(
_dict.get('global'))
if 'skills' in _dict:
args['skills'] = MessageConte... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'global'",
"in",
"_dict",
":",
"args",
"[",
"'global_'",
"]",
"=",
"MessageContextGlobal",
".",
"_from_dict",
"(",
"_dict",
".",
"get",
"(",
"'global'",
")",
")",
... | Initialize a MessageContext object from a json dictionary. | [
"Initialize",
"a",
"MessageContext",
"object",
"from",
"a",
"json",
"dictionary",
"."
] | python | train | 39.5 |
lbenitez000/trparse | trparse.py | https://github.com/lbenitez000/trparse/blob/1f932d882a98b062b540b6f4bc2ecb0f35b92e97/trparse.py#L88-L158 | def loads(data):
"""Parser entry point. Parses the output of a traceroute execution"""
data += "\n_EOS_" # Append EOS token. Helps to match last RE_HOP
# Get headers
match_dest = RE_HEADER.search(data)
dest_name = match_dest.group(1)
dest_ip = match_dest.group(2)
# The Traceroute is the ro... | [
"def",
"loads",
"(",
"data",
")",
":",
"data",
"+=",
"\"\\n_EOS_\"",
"# Append EOS token. Helps to match last RE_HOP",
"# Get headers",
"match_dest",
"=",
"RE_HEADER",
".",
"search",
"(",
"data",
")",
"dest_name",
"=",
"match_dest",
".",
"group",
"(",
"1",
")",
... | Parser entry point. Parses the output of a traceroute execution | [
"Parser",
"entry",
"point",
".",
"Parses",
"the",
"output",
"of",
"a",
"traceroute",
"execution"
] | python | train | 34.422535 |
thespacedoctor/fundamentals | fundamentals/mysql/insert_list_of_dictionaries_into_database_tables.py | https://github.com/thespacedoctor/fundamentals/blob/1d2c007ac74442ec2eabde771cfcacdb9c1ab382/fundamentals/mysql/insert_list_of_dictionaries_into_database_tables.py#L33-L158 | def insert_list_of_dictionaries_into_database_tables(
dbConn,
log,
dictList,
dbTableName,
uniqueKeyList=[],
dateModified=False,
dateCreated=True,
batchSize=2500,
replace=False,
dbSettings=False):
"""insert list of dictionaries into data... | [
"def",
"insert_list_of_dictionaries_into_database_tables",
"(",
"dbConn",
",",
"log",
",",
"dictList",
",",
"dbTableName",
",",
"uniqueKeyList",
"=",
"[",
"]",
",",
"dateModified",
"=",
"False",
",",
"dateCreated",
"=",
"True",
",",
"batchSize",
"=",
"2500",
","... | insert list of dictionaries into database tables
**Key Arguments:**
- ``dbConn`` -- mysql database connection
- ``log`` -- logger
- ``dictList`` -- list of python dictionaries to add to the database table
- ``dbTableName`` -- name of the database table
- ``uniqueKeyList`` --... | [
"insert",
"list",
"of",
"dictionaries",
"into",
"database",
"tables"
] | python | train | 31.412698 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/rest.py | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/rest.py#L134-L215 | def request(
self,
method,
url,
query_params=None,
headers=None,
body=None,
post_params=None,
_preload_content=True,
_request_timeout=None,
):
"""
:param method: http request method
:param url: http request url
:... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"query_params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"body",
"=",
"None",
",",
"post_params",
"=",
"None",
",",
"_preload_content",
"=",
"True",
",",
"_request_timeout",
"=",
"None"... | :param method: http request method
:param url: http request url
:param query_params: query parameters in the url
:param headers: http request headers
:param body: request json body, for `application/json`
:param post_params: request post parameters,
`a... | [
":",
"param",
"method",
":",
"http",
"request",
"method",
":",
"param",
"url",
":",
"http",
"request",
"url",
":",
"param",
"query_params",
":",
"query",
"parameters",
"in",
"the",
"url",
":",
"param",
"headers",
":",
"http",
"request",
"headers",
":",
"... | python | train | 39.02439 |
fedora-python/pyp2rpm | pyp2rpm/utils.py | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/utils.py#L59-L101 | def build_srpm(specfile, save_dir):
"""Builds a srpm from given specfile using rpmbuild.
Generated srpm is stored in directory specified by save_dir.
Args:
specfile: path to a specfile
save_dir: path to source and build tree
"""
logger.info('Starting rpmbuild to build: {0} SRPM.'.fo... | [
"def",
"build_srpm",
"(",
"specfile",
",",
"save_dir",
")",
":",
"logger",
".",
"info",
"(",
"'Starting rpmbuild to build: {0} SRPM.'",
".",
"format",
"(",
"specfile",
")",
")",
"if",
"save_dir",
"!=",
"get_default_save_path",
"(",
")",
":",
"try",
":",
"msg",... | Builds a srpm from given specfile using rpmbuild.
Generated srpm is stored in directory specified by save_dir.
Args:
specfile: path to a specfile
save_dir: path to source and build tree | [
"Builds",
"a",
"srpm",
"from",
"given",
"specfile",
"using",
"rpmbuild",
".",
"Generated",
"srpm",
"is",
"stored",
"in",
"directory",
"specified",
"by",
"save_dir",
"."
] | python | train | 45.023256 |
opencobra/cobrapy | cobra/flux_analysis/variability.py | https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/variability.py#L304-L335 | def find_essential_reactions(model, threshold=None, processes=None):
"""Return a set of essential reactions.
A reaction is considered essential if restricting its flux to zero
causes the objective, e.g., the growth rate, to also be zero, below the
threshold, or infeasible.
Parameters
--------... | [
"def",
"find_essential_reactions",
"(",
"model",
",",
"threshold",
"=",
"None",
",",
"processes",
"=",
"None",
")",
":",
"if",
"threshold",
"is",
"None",
":",
"threshold",
"=",
"model",
".",
"slim_optimize",
"(",
"error_value",
"=",
"None",
")",
"*",
"1E-0... | Return a set of essential reactions.
A reaction is considered essential if restricting its flux to zero
causes the objective, e.g., the growth rate, to also be zero, below the
threshold, or infeasible.
Parameters
----------
model : cobra.Model
The model to find the essential reactions... | [
"Return",
"a",
"set",
"of",
"essential",
"reactions",
"."
] | python | valid | 38.6875 |
cons3rt/pycons3rt | pycons3rt/slack.py | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/slack.py#L114-L129 | def add_attachment(self, attachment):
"""Adds an attachment to the SlackMessage payload
This public method adds a slack message to the attachment
list.
:param attachment: SlackAttachment object
:return: None
"""
log = logging.getLogger(self.cls_logger + '.add_at... | [
"def",
"add_attachment",
"(",
"self",
",",
"attachment",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.add_attachment'",
")",
"if",
"not",
"isinstance",
"(",
"attachment",
",",
"SlackAttachment",
")",
":",
"msg",
... | Adds an attachment to the SlackMessage payload
This public method adds a slack message to the attachment
list.
:param attachment: SlackAttachment object
:return: None | [
"Adds",
"an",
"attachment",
"to",
"the",
"SlackMessage",
"payload"
] | python | train | 38.4375 |
Capitains/MyCapytain | MyCapytain/resources/texts/remote/cts.py | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L63-L88 | def getValidReff(self, level=1, reference=None):
""" Given a resource, CtsText will compute valid reffs
:param level: Depth required. If not set, should retrieve first encountered level (1 based)
:type level: Int
:param reference: CapitainsCtsPassage reference
:type reference: C... | [
"def",
"getValidReff",
"(",
"self",
",",
"level",
"=",
"1",
",",
"reference",
"=",
"None",
")",
":",
"if",
"reference",
":",
"urn",
"=",
"\"{0}:{1}\"",
".",
"format",
"(",
"self",
".",
"urn",
",",
"reference",
")",
"else",
":",
"urn",
"=",
"str",
"... | Given a resource, CtsText will compute valid reffs
:param level: Depth required. If not set, should retrieve first encountered level (1 based)
:type level: Int
:param reference: CapitainsCtsPassage reference
:type reference: CtsReference
:rtype: list(str)
:returns: List ... | [
"Given",
"a",
"resource",
"CtsText",
"will",
"compute",
"valid",
"reffs"
] | python | train | 34.461538 |
swimlane/swimlane-python | swimlane/core/fields/list.py | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/list.py#L207-L219 | def set_swimlane(self, value):
"""Convert from list of dicts with values to list of values
Cache list items with their ID pairs to restore existing IDs to unmodified values to prevent workflow
evaluating on each save for any already existing values
"""
value = value or []
... | [
"def",
"set_swimlane",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"value",
"or",
"[",
"]",
"self",
".",
"_initial_value_to_ids_map",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"item",
"in",
"value",
":",
"self",
".",
"_initial_value_to_ids_map",
... | Convert from list of dicts with values to list of values
Cache list items with their ID pairs to restore existing IDs to unmodified values to prevent workflow
evaluating on each save for any already existing values | [
"Convert",
"from",
"list",
"of",
"dicts",
"with",
"values",
"to",
"list",
"of",
"values"
] | python | train | 42 |
utek/pyseaweed | pyseaweed/weed.py | https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/weed.py#L140-L147 | def delete_file(self, fid):
"""
Delete file from WeedFS
:param string fid: File ID
"""
url = self.get_file_url(fid)
return self.conn.delete_data(url) | [
"def",
"delete_file",
"(",
"self",
",",
"fid",
")",
":",
"url",
"=",
"self",
".",
"get_file_url",
"(",
"fid",
")",
"return",
"self",
".",
"conn",
".",
"delete_data",
"(",
"url",
")"
] | Delete file from WeedFS
:param string fid: File ID | [
"Delete",
"file",
"from",
"WeedFS"
] | python | train | 23.875 |
hyperledger/sawtooth-core | validator/sawtooth_validator/journal/consensus/dev_mode/dev_mode_consensus.py | https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/validator/sawtooth_validator/journal/consensus/dev_mode/dev_mode_consensus.py#L70-L101 | def initialize_block(self, block_header):
"""Do initialization necessary for the consensus to claim a block,
this may include initiating voting activates, starting proof of work
hash generation, or create a PoET wait timer.
Args:
block_header (BlockHeader): the BlockHeader t... | [
"def",
"initialize_block",
"(",
"self",
",",
"block_header",
")",
":",
"# Using the current chain head, we need to create a state view so we",
"# can get our config values.",
"state_view",
"=",
"BlockWrapper",
".",
"state_view_for_block",
"(",
"self",
".",
"_block_cache",
".",
... | Do initialization necessary for the consensus to claim a block,
this may include initiating voting activates, starting proof of work
hash generation, or create a PoET wait timer.
Args:
block_header (BlockHeader): the BlockHeader to initialize.
Returns:
True | [
"Do",
"initialization",
"necessary",
"for",
"the",
"consensus",
"to",
"claim",
"a",
"block",
"this",
"may",
"include",
"initiating",
"voting",
"activates",
"starting",
"proof",
"of",
"work",
"hash",
"generation",
"or",
"create",
"a",
"PoET",
"wait",
"timer",
"... | python | train | 41.46875 |
redcap-tools/PyCap | redcap/project.py | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L591-L625 | def delete_file(self, record, field, return_format='json', event=None):
"""
Delete a file from REDCap
Notes
-----
There is no undo button to this.
Parameters
----------
record : str
record ID
field : str
field name
... | [
"def",
"delete_file",
"(",
"self",
",",
"record",
",",
"field",
",",
"return_format",
"=",
"'json'",
",",
"event",
"=",
"None",
")",
":",
"self",
".",
"_check_file_field",
"(",
"field",
")",
"# Load up payload",
"pl",
"=",
"self",
".",
"__basepl",
"(",
"... | Delete a file from REDCap
Notes
-----
There is no undo button to this.
Parameters
----------
record : str
record ID
field : str
field name
return_format : (``'json'``), ``'csv'``, ``'xml'``
return format for error mess... | [
"Delete",
"a",
"file",
"from",
"REDCap"
] | python | train | 27.914286 |
hickeroar/simplebayes | simplebayes/categories.py | https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/categories.py#L33-L44 | def add_category(self, name):
"""
Adds a bayes category that we can later train
:param name: name of the category
:type name: str
:return: the requested category
:rtype: BayesCategory
"""
category = BayesCategory(name)
self.categories[name] = cate... | [
"def",
"add_category",
"(",
"self",
",",
"name",
")",
":",
"category",
"=",
"BayesCategory",
"(",
"name",
")",
"self",
".",
"categories",
"[",
"name",
"]",
"=",
"category",
"return",
"category"
] | Adds a bayes category that we can later train
:param name: name of the category
:type name: str
:return: the requested category
:rtype: BayesCategory | [
"Adds",
"a",
"bayes",
"category",
"that",
"we",
"can",
"later",
"train"
] | python | train | 28.083333 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L8278-L8289 | def serial_udb_extra_f6_send(self, sue_PITCHGAIN, sue_PITCHKD, sue_RUDDER_ELEV_MIX, sue_ROLL_ELEV_MIX, sue_ELEVATOR_BOOST, force_mavlink1=False):
'''
Backwards compatible version of SERIAL_UDB_EXTRA F6: format
sue_PITCHGAIN : Serial UDB Extra PITCHGAIN Propor... | [
"def",
"serial_udb_extra_f6_send",
"(",
"self",
",",
"sue_PITCHGAIN",
",",
"sue_PITCHKD",
",",
"sue_RUDDER_ELEV_MIX",
",",
"sue_ROLL_ELEV_MIX",
",",
"sue_ELEVATOR_BOOST",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".... | Backwards compatible version of SERIAL_UDB_EXTRA F6: format
sue_PITCHGAIN : Serial UDB Extra PITCHGAIN Proportional Control (float)
sue_PITCHKD : Serial UDB Extra Pitch Rate Control (float)
sue_RUDDER_ELEV_MIX : Serial UDB Extra Rudder to... | [
"Backwards",
"compatible",
"version",
"of",
"SERIAL_UDB_EXTRA",
"F6",
":",
"format"
] | python | train | 77 |
pyusb/pyusb | usb/control.py | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/control.py#L188-L206 | def get_configuration(dev):
r"""Get the current active configuration of the device.
dev is the Device object to which the request will be
sent to.
This function differs from the Device.get_active_configuration
method because the later may use cached data, while this
function always does a devi... | [
"def",
"get_configuration",
"(",
"dev",
")",
":",
"bmRequestType",
"=",
"util",
".",
"build_request_type",
"(",
"util",
".",
"CTRL_IN",
",",
"util",
".",
"CTRL_TYPE_STANDARD",
",",
"util",
".",
"CTRL_RECIPIENT_DEVICE",
")",
"return",
"dev",
".",
"ctrl_transfer",... | r"""Get the current active configuration of the device.
dev is the Device object to which the request will be
sent to.
This function differs from the Device.get_active_configuration
method because the later may use cached data, while this
function always does a device request. | [
"r",
"Get",
"the",
"current",
"active",
"configuration",
"of",
"the",
"device",
"."
] | python | train | 34.315789 |
mbakker7/timml | timml/aquifer.py | https://github.com/mbakker7/timml/blob/91e99ad573cb8a9ad8ac1fa041c3ca44520c2390/timml/aquifer.py#L85-L98 | def findlayer(self, z):
'''
Returns layer-number, layer-type and model-layer-number'''
if z > self.z[0]:
modellayer, ltype = -1, 'above'
layernumber = None
elif z < self.z[-1]:
modellayer, ltype = len(self.layernumber), 'below'
layernumber ... | [
"def",
"findlayer",
"(",
"self",
",",
"z",
")",
":",
"if",
"z",
">",
"self",
".",
"z",
"[",
"0",
"]",
":",
"modellayer",
",",
"ltype",
"=",
"-",
"1",
",",
"'above'",
"layernumber",
"=",
"None",
"elif",
"z",
"<",
"self",
".",
"z",
"[",
"-",
"1... | Returns layer-number, layer-type and model-layer-number | [
"Returns",
"layer",
"-",
"number",
"layer",
"-",
"type",
"and",
"model",
"-",
"layer",
"-",
"number"
] | python | train | 39.642857 |
juju/charm-helpers | charmhelpers/contrib/openstack/amulet/utils.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L478-L503 | def authenticate_keystone(self, keystone_ip, username, password,
api_version=False, admin_port=False,
user_domain_name=None, domain_name=None,
project_domain_name=None, project_name=None):
"""Authenticate with Keystone"""
... | [
"def",
"authenticate_keystone",
"(",
"self",
",",
"keystone_ip",
",",
"username",
",",
"password",
",",
"api_version",
"=",
"False",
",",
"admin_port",
"=",
"False",
",",
"user_domain_name",
"=",
"None",
",",
"domain_name",
"=",
"None",
",",
"project_domain_name... | Authenticate with Keystone | [
"Authenticate",
"with",
"Keystone"
] | python | train | 42.153846 |
upsight/doctor | doctor/routing.py | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/routing.py#L88-L112 | def create_http_method(logic: Callable, http_method: str,
handle_http: Callable, before: Callable = None,
after: Callable = None) -> Callable:
"""Create a handler method to be used in a handler class.
:param callable logic: The underlying function to execute with t... | [
"def",
"create_http_method",
"(",
"logic",
":",
"Callable",
",",
"http_method",
":",
"str",
",",
"handle_http",
":",
"Callable",
",",
"before",
":",
"Callable",
"=",
"None",
",",
"after",
":",
"Callable",
"=",
"None",
")",
"->",
"Callable",
":",
"@",
"fu... | Create a handler method to be used in a handler class.
:param callable logic: The underlying function to execute with the
parsed and validated parameters.
:param str http_method: HTTP method this will handle.
:param handle_http: The HTTP handler function that should be
used to wrap the logi... | [
"Create",
"a",
"handler",
"method",
"to",
"be",
"used",
"in",
"a",
"handler",
"class",
"."
] | python | train | 42.48 |
tomprince/nomenclature | nomenclature/syscalls.py | https://github.com/tomprince/nomenclature/blob/81af4a590034f75211f028d485c0d83fceda5af2/nomenclature/syscalls.py#L15-L24 | def unshare(flags):
"""
Disassociate parts of the process execution context.
:param flags int: A bitmask that specifies which parts of the execution
context should be unshared.
"""
res = lib.unshare(flags)
if res != 0:
_check_error(ffi.errno) | [
"def",
"unshare",
"(",
"flags",
")",
":",
"res",
"=",
"lib",
".",
"unshare",
"(",
"flags",
")",
"if",
"res",
"!=",
"0",
":",
"_check_error",
"(",
"ffi",
".",
"errno",
")"
] | Disassociate parts of the process execution context.
:param flags int: A bitmask that specifies which parts of the execution
context should be unshared. | [
"Disassociate",
"parts",
"of",
"the",
"process",
"execution",
"context",
"."
] | python | train | 27.4 |
MSchnei/pyprf_feature | pyprf_feature/analysis/model_creation_utils.py | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/model_creation_utils.py#L594-L662 | def crt_prf_ftr_tc(aryMdlRsp, aryTmpExpInf, varNumVol, varTr, varTmpOvsmpl,
switchHrfSet, tplPngSize, varPar, dctPrm=None,
lgcPrint=True):
"""Create all spatial x feature prf time courses.
Parameters
----------
aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos *... | [
"def",
"crt_prf_ftr_tc",
"(",
"aryMdlRsp",
",",
"aryTmpExpInf",
",",
"varNumVol",
",",
"varTr",
",",
"varTmpOvsmpl",
",",
"switchHrfSet",
",",
"tplPngSize",
",",
"varPar",
",",
"dctPrm",
"=",
"None",
",",
"lgcPrint",
"=",
"True",
")",
":",
"# Identify number o... | Create all spatial x feature prf time courses.
Parameters
----------
aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond]
Responses of 2D Gauss models to spatial conditions
aryTmpExpInf: 2d numpy array, shape [unknown, 4]
Temporal information about conditions
varNumV... | [
"Create",
"all",
"spatial",
"x",
"feature",
"prf",
"time",
"courses",
"."
] | python | train | 40.130435 |
CivicSpleen/ambry | ambry/identity.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L881-L886 | def increment(cls, v):
"""Increment the version number of an object number of object number string"""
if not isinstance(v, ObjectNumber):
v = ObjectNumber.parse(v)
return v.rev(v.revision+1) | [
"def",
"increment",
"(",
"cls",
",",
"v",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"ObjectNumber",
")",
":",
"v",
"=",
"ObjectNumber",
".",
"parse",
"(",
"v",
")",
"return",
"v",
".",
"rev",
"(",
"v",
".",
"revision",
"+",
"1",
")"
] | Increment the version number of an object number of object number string | [
"Increment",
"the",
"version",
"number",
"of",
"an",
"object",
"number",
"of",
"object",
"number",
"string"
] | python | train | 37 |
aliyun/aliyun-odps-python-sdk | odps/df/expr/collections.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/collections.py#L1206-L1234 | def min_max_scale(expr, columns=None, feature_range=(0, 1), preserve=False, suffix='_scaled', group=None):
"""
Resize a data frame by max / min values, i.e., (X - min(X)) / (max(X) - min(X))
:param DataFrame expr: input DataFrame
:param feature_range: the target range to resize the value into, i.e., v ... | [
"def",
"min_max_scale",
"(",
"expr",
",",
"columns",
"=",
"None",
",",
"feature_range",
"=",
"(",
"0",
",",
"1",
")",
",",
"preserve",
"=",
"False",
",",
"suffix",
"=",
"'_scaled'",
",",
"group",
"=",
"None",
")",
":",
"time_suffix",
"=",
"str",
"(",... | Resize a data frame by max / min values, i.e., (X - min(X)) / (max(X) - min(X))
:param DataFrame expr: input DataFrame
:param feature_range: the target range to resize the value into, i.e., v * (b - a) + a
:param bool preserve: determine whether input data should be kept. If True, scaled input data will be... | [
"Resize",
"a",
"data",
"frame",
"by",
"max",
"/",
"min",
"values",
"i",
".",
"e",
".",
"(",
"X",
"-",
"min",
"(",
"X",
"))",
"/",
"(",
"max",
"(",
"X",
")",
"-",
"min",
"(",
"X",
"))"
] | python | train | 52.37931 |
aegirhall/console-menu | consolemenu/validators/regex.py | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/validators/regex.py#L16-L30 | def validate(self, input_string):
"""
Validate input_string against a regex pattern
:return: True if match / False otherwise
"""
validation_result = False
try:
validation_result = bool(match(pattern=self.pattern, string=input_string))
except TypeError... | [
"def",
"validate",
"(",
"self",
",",
"input_string",
")",
":",
"validation_result",
"=",
"False",
"try",
":",
"validation_result",
"=",
"bool",
"(",
"match",
"(",
"pattern",
"=",
"self",
".",
"pattern",
",",
"string",
"=",
"input_string",
")",
")",
"except... | Validate input_string against a regex pattern
:return: True if match / False otherwise | [
"Validate",
"input_string",
"against",
"a",
"regex",
"pattern"
] | python | train | 47.6 |
CalebBell/fluids | fluids/friction.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/friction.py#L2913-L3038 | def friction_factor_curved(Re, Di, Dc, roughness=0.0, Method=None,
Rec_method='Schmidt',
laminar_method='Schmidt laminar',
turbulent_method='Schmidt turbulent', Darcy=True,
AvailableMethods=False):
r'''Cal... | [
"def",
"friction_factor_curved",
"(",
"Re",
",",
"Di",
",",
"Dc",
",",
"roughness",
"=",
"0.0",
",",
"Method",
"=",
"None",
",",
"Rec_method",
"=",
"'Schmidt'",
",",
"laminar_method",
"=",
"'Schmidt laminar'",
",",
"turbulent_method",
"=",
"'Schmidt turbulent'",... | r'''Calculates friction factor fluid flowing in a curved pipe or helical
coil, supporting both laminar and turbulent regimes. Selects the
appropriate regime by default, and has default correlation choices.
Optionally, a specific correlation can be specified with the `Method`
keyword.
The defa... | [
"r",
"Calculates",
"friction",
"factor",
"fluid",
"flowing",
"in",
"a",
"curved",
"pipe",
"or",
"helical",
"coil",
"supporting",
"both",
"laminar",
"and",
"turbulent",
"regimes",
".",
"Selects",
"the",
"appropriate",
"regime",
"by",
"default",
"and",
"has",
"d... | python | train | 36.65873 |
google/grr | grr/client/grr_response_client/client_actions/windows/windows.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/client_actions/windows/windows.py#L177-L186 | def WmiQueryFromClient(args):
"""Run the WMI query and return the data."""
query = args.query
base_object = args.base_object or r"winmgmts:\root\cimv2"
if not query.upper().startswith("SELECT "):
raise RuntimeError("Only SELECT WMI queries allowed.")
for response_dict in RunWMIQuery(query, baseobj=base_... | [
"def",
"WmiQueryFromClient",
"(",
"args",
")",
":",
"query",
"=",
"args",
".",
"query",
"base_object",
"=",
"args",
".",
"base_object",
"or",
"r\"winmgmts:\\root\\cimv2\"",
"if",
"not",
"query",
".",
"upper",
"(",
")",
".",
"startswith",
"(",
"\"SELECT \"",
... | Run the WMI query and return the data. | [
"Run",
"the",
"WMI",
"query",
"and",
"return",
"the",
"data",
"."
] | python | train | 34.3 |
rsmuc/health_monitoring_plugins | health_monitoring_plugins/idrac.py | https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/idrac.py#L260-L279 | def process_temperature_sensors(helper, session):
"""process the temperature sensors"""
snmp_result_temp_sensor_names = helper.walk_snmp_values(
session, helper,
DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_location'], "temperature sensors")
snmp_result_temp_sensor_stat... | [
"def",
"process_temperature_sensors",
"(",
"helper",
",",
"session",
")",
":",
"snmp_result_temp_sensor_names",
"=",
"helper",
".",
"walk_snmp_values",
"(",
"session",
",",
"helper",
",",
"DEVICE_TEMPERATURE_OIDS",
"[",
"'oid_temperature_probe_location'",
"]",
",",
"\"t... | process the temperature sensors | [
"process",
"the",
"temperature",
"sensors"
] | python | train | 57 |
apple/turicreate | src/unity/python/turicreate/meta/decompiler/simple_instructions.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/decompiler/simple_instructions.py#L829-L849 | def STORE_SLICE_3(self, instr):
'obj[lower:upper] = expr'
upper = self.ast_stack.pop()
lower = self.ast_stack.pop()
value = self.ast_stack.pop()
expr = self.ast_stack.pop()
kw = dict(lineno=instr.lineno, col_offset=0)
slice = _ast.Slice(lower=lower, step... | [
"def",
"STORE_SLICE_3",
"(",
"self",
",",
"instr",
")",
":",
"upper",
"=",
"self",
".",
"ast_stack",
".",
"pop",
"(",
")",
"lower",
"=",
"self",
".",
"ast_stack",
".",
"pop",
"(",
")",
"value",
"=",
"self",
".",
"ast_stack",
".",
"pop",
"(",
")",
... | obj[lower:upper] = expr | [
"obj",
"[",
"lower",
":",
"upper",
"]",
"=",
"expr"
] | python | train | 33.809524 |
mitsei/dlkit | dlkit/json_/relationship/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/relationship/sessions.py#L205-L229 | def get_relationship(self, relationship_id):
"""Gets the ``Relationship`` specified by its ``Id``.
arg: relationship_id (osid.id.Id): the ``Id`` of the
``Relationship`` to retrieve
return: (osid.relationship.Relationship) - the returned
``Relationship``
... | [
"def",
"get_relationship",
"(",
"self",
",",
"relationship_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resource",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
"JSONClientValidated",
"(",
"'relationship... | Gets the ``Relationship`` specified by its ``Id``.
arg: relationship_id (osid.id.Id): the ``Id`` of the
``Relationship`` to retrieve
return: (osid.relationship.Relationship) - the returned
``Relationship``
raise: NotFound - no ``Relationship`` found with the ... | [
"Gets",
"the",
"Relationship",
"specified",
"by",
"its",
"Id",
"."
] | python | train | 51.12 |
MillionIntegrals/vel | vel/rl/algo/policy_gradient/a2c.py | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/a2c.py#L41-L71 | def calculate_gradient(self, batch_info, device, model, rollout):
""" Calculate loss of the supplied rollout """
evaluator = model.evaluate(rollout)
# Use evaluator interface to get the what we are interested in from the model
advantages = evaluator.get('rollout:advantages')
ret... | [
"def",
"calculate_gradient",
"(",
"self",
",",
"batch_info",
",",
"device",
",",
"model",
",",
"rollout",
")",
":",
"evaluator",
"=",
"model",
".",
"evaluate",
"(",
"rollout",
")",
"# Use evaluator interface to get the what we are interested in from the model",
"advanta... | Calculate loss of the supplied rollout | [
"Calculate",
"loss",
"of",
"the",
"supplied",
"rollout"
] | python | train | 39.612903 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_group.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_group.py#L239-L257 | def tag(self, name, formatter=None):
"""Return instance of Tag.
Args:
name (str): The value for this tag.
formatter (method, optional): A method that take a tag value and returns a
formatted tag.
Returns:
obj: An instance of Tag.
"""
... | [
"def",
"tag",
"(",
"self",
",",
"name",
",",
"formatter",
"=",
"None",
")",
":",
"tag",
"=",
"Tag",
"(",
"name",
",",
"formatter",
")",
"for",
"tag_data",
"in",
"self",
".",
"_tags",
":",
"if",
"tag_data",
".",
"name",
"==",
"name",
":",
"tag",
"... | Return instance of Tag.
Args:
name (str): The value for this tag.
formatter (method, optional): A method that take a tag value and returns a
formatted tag.
Returns:
obj: An instance of Tag. | [
"Return",
"instance",
"of",
"Tag",
"."
] | python | train | 27.947368 |
edx/xblock-utils | xblockutils/resources.py | https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/resources.py#L100-L107 | def render_template(self, template_path, context=None):
"""
This function has been deprecated. It calls render_django_template to support backwards compatibility.
"""
warnings.warn(
"ResourceLoader.render_template has been deprecated in favor of ResourceLoader.render_django_t... | [
"def",
"render_template",
"(",
"self",
",",
"template_path",
",",
"context",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"ResourceLoader.render_template has been deprecated in favor of ResourceLoader.render_django_template\"",
")",
"return",
"self",
".",
"render_... | This function has been deprecated. It calls render_django_template to support backwards compatibility. | [
"This",
"function",
"has",
"been",
"deprecated",
".",
"It",
"calls",
"render_django_template",
"to",
"support",
"backwards",
"compatibility",
"."
] | python | train | 49.75 |
lappis-unb/salic-ml | src/salicml/metrics/finance/total_receipts.py | https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/total_receipts.py#L9-L36 | def total_receipts(pronac, dt):
"""
This metric calculates the project total of receipts
and compare it to projects in the same segment
output:
is_outlier: True if projects receipts is not compatible
to others projects in the same segment
total_receipts: a... | [
"def",
"total_receipts",
"(",
"pronac",
",",
"dt",
")",
":",
"dataframe",
"=",
"data",
".",
"planilha_comprovacao",
"project",
"=",
"dataframe",
".",
"loc",
"[",
"dataframe",
"[",
"'PRONAC'",
"]",
"==",
"pronac",
"]",
"segment_id",
"=",
"project",
".",
"il... | This metric calculates the project total of receipts
and compare it to projects in the same segment
output:
is_outlier: True if projects receipts is not compatible
to others projects in the same segment
total_receipts: absolute number of receipts
maxim... | [
"This",
"metric",
"calculates",
"the",
"project",
"total",
"of",
"receipts",
"and",
"compare",
"it",
"to",
"projects",
"in",
"the",
"same",
"segment",
"output",
":",
"is_outlier",
":",
"True",
"if",
"projects",
"receipts",
"is",
"not",
"compatible",
"to",
"o... | python | train | 40.071429 |
has2k1/plotnine | plotnine/stats/density.py | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/density.py#L96-L120 | def kde_sklearn(data, grid, **kwargs):
"""
Kernel Density Estimation with Scikit-learn
Parameters
----------
data : numpy.array
Data points used to compute a density estimator. It
has `n x p` dimensions, representing n points and p
variables.
grid : numpy.array
D... | [
"def",
"kde_sklearn",
"(",
"data",
",",
"grid",
",",
"*",
"*",
"kwargs",
")",
":",
"kde_skl",
"=",
"KernelDensity",
"(",
"*",
"*",
"kwargs",
")",
"kde_skl",
".",
"fit",
"(",
"data",
")",
"# score_samples() returns the log-likelihood of the samples",
"log_pdf",
... | Kernel Density Estimation with Scikit-learn
Parameters
----------
data : numpy.array
Data points used to compute a density estimator. It
has `n x p` dimensions, representing n points and p
variables.
grid : numpy.array
Data points at which the desity will be estimated. I... | [
"Kernel",
"Density",
"Estimation",
"with",
"Scikit",
"-",
"learn"
] | python | train | 28.96 |
hsolbrig/PyShEx | pyshex/utils/value_set_utils.py | https://github.com/hsolbrig/PyShEx/blob/9d659cc36e808afd66d4a6d60e8ea21cb12eb744/pyshex/utils/value_set_utils.py#L32-L35 | def literal_matches_objectliteral(v1: Literal, v2: ShExJ.ObjectLiteral) -> bool:
""" Compare :py:class:`rdflib.Literal` with :py:class:`ShExJ.objectLiteral` """
v2_lit = Literal(str(v2.value), datatype=iriref_to_uriref(v2.type), lang=str(v2.language) if v2.language else None)
return v1 == v2_lit | [
"def",
"literal_matches_objectliteral",
"(",
"v1",
":",
"Literal",
",",
"v2",
":",
"ShExJ",
".",
"ObjectLiteral",
")",
"->",
"bool",
":",
"v2_lit",
"=",
"Literal",
"(",
"str",
"(",
"v2",
".",
"value",
")",
",",
"datatype",
"=",
"iriref_to_uriref",
"(",
"... | Compare :py:class:`rdflib.Literal` with :py:class:`ShExJ.objectLiteral` | [
"Compare",
":",
"py",
":",
"class",
":",
"rdflib",
".",
"Literal",
"with",
":",
"py",
":",
"class",
":",
"ShExJ",
".",
"objectLiteral"
] | python | train | 76.25 |
jhermann/rituals | src/rituals/acts/basic.py | https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/basic.py#L105-L120 | def build(ctx, docs=False):
"""Build the project."""
cfg = config.load()
ctx.run("python setup.py build")
if docs:
for doc_path in ('docs', 'doc'):
if os.path.exists(cfg.rootjoin(doc_path, 'conf.py')):
break
else:
doc_path = None
if doc_p... | [
"def",
"build",
"(",
"ctx",
",",
"docs",
"=",
"False",
")",
":",
"cfg",
"=",
"config",
".",
"load",
"(",
")",
"ctx",
".",
"run",
"(",
"\"python setup.py build\"",
")",
"if",
"docs",
":",
"for",
"doc_path",
"in",
"(",
"'docs'",
",",
"'doc'",
")",
":... | Build the project. | [
"Build",
"the",
"project",
"."
] | python | valid | 27.6875 |
bxlab/bx-python | lib/bx_extras/stats.py | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1140-L1162 | def ltiecorrect(rankvals):
"""
Corrects for ties in Mann Whitney U and Kruskal Wallis H tests. See
Siegel, S. (1956) Nonparametric Statistics for the Behavioral Sciences.
New York: McGraw-Hill. Code adapted from |Stat rankind.c code.
Usage: ltiecorrect(rankvals)
Returns: T correction factor for U or H
"""
... | [
"def",
"ltiecorrect",
"(",
"rankvals",
")",
":",
"sorted",
",",
"posn",
"=",
"shellsort",
"(",
"rankvals",
")",
"n",
"=",
"len",
"(",
"sorted",
")",
"T",
"=",
"0.0",
"i",
"=",
"0",
"while",
"(",
"i",
"<",
"n",
"-",
"1",
")",
":",
"if",
"sorted"... | Corrects for ties in Mann Whitney U and Kruskal Wallis H tests. See
Siegel, S. (1956) Nonparametric Statistics for the Behavioral Sciences.
New York: McGraw-Hill. Code adapted from |Stat rankind.c code.
Usage: ltiecorrect(rankvals)
Returns: T correction factor for U or H | [
"Corrects",
"for",
"ties",
"in",
"Mann",
"Whitney",
"U",
"and",
"Kruskal",
"Wallis",
"H",
"tests",
".",
"See",
"Siegel",
"S",
".",
"(",
"1956",
")",
"Nonparametric",
"Statistics",
"for",
"the",
"Behavioral",
"Sciences",
".",
"New",
"York",
":",
"McGraw",
... | python | train | 28.913043 |
orbingol/NURBS-Python | geomdl/helpers.py | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/helpers.py#L307-L326 | def basis_functions_ders(degree, knot_vector, spans, knots, order):
""" Computes derivatives of the basis functions for a list of parameters.
:param degree: degree, :math:`p`
:type degree: int
:param knot_vector: knot vector, :math:`U`
:type knot_vector: list, tuple
:param spans: list of knot s... | [
"def",
"basis_functions_ders",
"(",
"degree",
",",
"knot_vector",
",",
"spans",
",",
"knots",
",",
"order",
")",
":",
"basis_ders",
"=",
"[",
"]",
"for",
"span",
",",
"knot",
"in",
"zip",
"(",
"spans",
",",
"knots",
")",
":",
"basis_ders",
".",
"append... | Computes derivatives of the basis functions for a list of parameters.
:param degree: degree, :math:`p`
:type degree: int
:param knot_vector: knot vector, :math:`U`
:type knot_vector: list, tuple
:param spans: list of knot spans
:type spans: list, tuple
:param knots: list of knots or parame... | [
"Computes",
"derivatives",
"of",
"the",
"basis",
"functions",
"for",
"a",
"list",
"of",
"parameters",
"."
] | python | train | 35.8 |
agile-geoscience/striplog | striplog/legend.py | https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/legend.py#L637-L682 | def to_csv(self):
"""
Renders a legend as a CSV string.
No arguments.
Returns:
str: The legend as a CSV.
"""
# We can't delegate this to Decor because we need to know the superset
# of all Decor properties. There may be lots of blanks.
header... | [
"def",
"to_csv",
"(",
"self",
")",
":",
"# We can't delegate this to Decor because we need to know the superset",
"# of all Decor properties. There may be lots of blanks.",
"header",
"=",
"[",
"]",
"component_header",
"=",
"[",
"]",
"for",
"row",
"in",
"self",
":",
"for",
... | Renders a legend as a CSV string.
No arguments.
Returns:
str: The legend as a CSV. | [
"Renders",
"a",
"legend",
"as",
"a",
"CSV",
"string",
"."
] | python | test | 33.347826 |
ralphje/imagemounter | imagemounter/volume.py | https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/volume.py#L597-L632 | def mount(self, fstype=None):
"""Based on the file system type as determined by :func:`determine_fs_type`, the proper mount command is executed
for this volume. The volume is mounted in a temporary path (or a pretty path if :attr:`pretty` is enabled) in
the mountpoint as specified by :attr:`moun... | [
"def",
"mount",
"(",
"self",
",",
"fstype",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"parent",
".",
"is_mounted",
":",
"raise",
"NotMountedError",
"(",
"self",
".",
"parent",
")",
"if",
"fstype",
"is",
"None",
":",
"fstype",
"=",
"self",
".",... | Based on the file system type as determined by :func:`determine_fs_type`, the proper mount command is executed
for this volume. The volume is mounted in a temporary path (or a pretty path if :attr:`pretty` is enabled) in
the mountpoint as specified by :attr:`mountpoint`.
If the file system type... | [
"Based",
"on",
"the",
"file",
"system",
"type",
"as",
"determined",
"by",
":",
"func",
":",
"determine_fs_type",
"the",
"proper",
"mount",
"command",
"is",
"executed",
"for",
"this",
"volume",
".",
"The",
"volume",
"is",
"mounted",
"in",
"a",
"temporary",
... | python | train | 40.638889 |
hyperledger/sawtooth-core | cli/sawtooth_cli/admin_command/keygen.py | https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/cli/sawtooth_cli/admin_command/keygen.py#L65-L133 | def do_keygen(args):
"""Executes the key generation operation, given the parsed arguments.
Args:
args (:obj:`Namespace`): The parsed args.
"""
if args.key_name is not None:
key_name = args.key_name
else:
key_name = 'validator'
key_dir = get_key_dir()
if not os.path... | [
"def",
"do_keygen",
"(",
"args",
")",
":",
"if",
"args",
".",
"key_name",
"is",
"not",
"None",
":",
"key_name",
"=",
"args",
".",
"key_name",
"else",
":",
"key_name",
"=",
"'validator'",
"key_dir",
"=",
"get_key_dir",
"(",
")",
"if",
"not",
"os",
".",
... | Executes the key generation operation, given the parsed arguments.
Args:
args (:obj:`Namespace`): The parsed args. | [
"Executes",
"the",
"key",
"generation",
"operation",
"given",
"the",
"parsed",
"arguments",
"."
] | python | train | 37 |
openstax/cnx-archive | cnxarchive/database.py | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L126-L138 | def get_tree(ident_hash, cursor, as_collated=False):
"""Return a JSON representation of the binder tree for ``ident_hash``."""
uuid, version = split_ident_hash(ident_hash)
cursor.execute(SQL['get-tree-by-uuid-n-version'],
(uuid, version, as_collated,))
try:
tree = cursor.fetch... | [
"def",
"get_tree",
"(",
"ident_hash",
",",
"cursor",
",",
"as_collated",
"=",
"False",
")",
":",
"uuid",
",",
"version",
"=",
"split_ident_hash",
"(",
"ident_hash",
")",
"cursor",
".",
"execute",
"(",
"SQL",
"[",
"'get-tree-by-uuid-n-version'",
"]",
",",
"("... | Return a JSON representation of the binder tree for ``ident_hash``. | [
"Return",
"a",
"JSON",
"representation",
"of",
"the",
"binder",
"tree",
"for",
"ident_hash",
"."
] | python | train | 37.538462 |
moonso/loqusdb | loqusdb/utils/profiling.py | https://github.com/moonso/loqusdb/blob/792dcd0d461aff5adc703c49eebf58964913a513/loqusdb/utils/profiling.py#L128-L151 | def compare_profiles(profile1, profile2):
"""
Given two profiles, determine the ratio of similarity, i.e.
the hamming distance between the strings.
Args:
profile1/2 (str): profile string
Returns:
similarity_ratio (float): the ratio of similiarity (0-1)
"... | [
"def",
"compare_profiles",
"(",
"profile1",
",",
"profile2",
")",
":",
"length",
"=",
"len",
"(",
"profile1",
")",
"profile1",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"profile1",
")",
")",
"profile2",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"pr... | Given two profiles, determine the ratio of similarity, i.e.
the hamming distance between the strings.
Args:
profile1/2 (str): profile string
Returns:
similarity_ratio (float): the ratio of similiarity (0-1) | [
"Given",
"two",
"profiles",
"determine",
"the",
"ratio",
"of",
"similarity",
"i",
".",
"e",
".",
"the",
"hamming",
"distance",
"between",
"the",
"strings",
"."
] | python | train | 23.375 |
kajala/django-jutil | jutil/urls.py | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/urls.py#L1-L14 | def url_equals(a: str, b: str) -> bool:
"""
Compares two URLs/paths and returns True if they point to same URI.
For example, querystring parameters can be different order but URLs are still equal.
:param a: URL/path
:param b: URL/path
:return: True if URLs/paths are equal
"""
from urllib... | [
"def",
"url_equals",
"(",
"a",
":",
"str",
",",
"b",
":",
"str",
")",
"->",
"bool",
":",
"from",
"urllib",
".",
"parse",
"import",
"urlparse",
",",
"parse_qsl",
"a2",
"=",
"list",
"(",
"urlparse",
"(",
"a",
")",
")",
"b2",
"=",
"list",
"(",
"urlp... | Compares two URLs/paths and returns True if they point to same URI.
For example, querystring parameters can be different order but URLs are still equal.
:param a: URL/path
:param b: URL/path
:return: True if URLs/paths are equal | [
"Compares",
"two",
"URLs",
"/",
"paths",
"and",
"returns",
"True",
"if",
"they",
"point",
"to",
"same",
"URI",
".",
"For",
"example",
"querystring",
"parameters",
"can",
"be",
"different",
"order",
"but",
"URLs",
"are",
"still",
"equal",
".",
":",
"param",... | python | train | 34.571429 |
xoolive/traffic | traffic/data/adsb/opensky.py | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/data/adsb/opensky.py#L32-L44 | def plot(
self, ax: GeoAxesSubplot, cmap: str = "inferno", s: int = 5, **kwargs
) -> Artist:
"""Plotting function. All arguments are passed to ax.scatter"""
return ax.scatter(
self.df.longitude,
self.df.latitude,
s=s,
transform=PlateCarree(),
... | [
"def",
"plot",
"(",
"self",
",",
"ax",
":",
"GeoAxesSubplot",
",",
"cmap",
":",
"str",
"=",
"\"inferno\"",
",",
"s",
":",
"int",
"=",
"5",
",",
"*",
"*",
"kwargs",
")",
"->",
"Artist",
":",
"return",
"ax",
".",
"scatter",
"(",
"self",
".",
"df",
... | Plotting function. All arguments are passed to ax.scatter | [
"Plotting",
"function",
".",
"All",
"arguments",
"are",
"passed",
"to",
"ax",
".",
"scatter"
] | python | train | 30.307692 |
poppy-project/pypot | pypot/vrep/remoteApiBindings/vrep.py | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/remoteApiBindings/vrep.py#L1025-L1046 | def simxSetStringSignal(clientID, signalName, signalValue, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
sigV=signalValue
if sys.version_info[0] == 3:
if type(signalName) is str:
signalName=signalName.encode('utf-8'... | [
"def",
"simxSetStringSignal",
"(",
"clientID",
",",
"signalName",
",",
"signalValue",
",",
"operationMode",
")",
":",
"sigV",
"=",
"signalValue",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
":",
"if",
"type",
"(",
"signalName",
")",
"is",
... | Please have a look at the function description/documentation in the V-REP user manual | [
"Please",
"have",
"a",
"look",
"at",
"the",
"function",
"description",
"/",
"documentation",
"in",
"the",
"V",
"-",
"REP",
"user",
"manual"
] | python | train | 44.681818 |
googlefonts/glyphsLib | Lib/glyphsLib/glyphdata.py | https://github.com/googlefonts/glyphsLib/blob/9c12dc70c8d13f08d92b824e6710f6e3bb5037bb/Lib/glyphsLib/glyphdata.py#L89-L139 | def get_glyph(glyph_name, data=None):
"""Return a named tuple (Glyph) containing information derived from a glyph
name akin to GSGlyphInfo.
The information is derived from an included copy of GlyphData.xml
and GlyphData_Ideographs.xml, going purely by the glyph name.
"""
# Read data on first u... | [
"def",
"get_glyph",
"(",
"glyph_name",
",",
"data",
"=",
"None",
")",
":",
"# Read data on first use.",
"if",
"data",
"is",
"None",
":",
"global",
"GLYPHDATA",
"if",
"GLYPHDATA",
"is",
"None",
":",
"GLYPHDATA",
"=",
"GlyphData",
".",
"from_files",
"(",
"os",... | Return a named tuple (Glyph) containing information derived from a glyph
name akin to GSGlyphInfo.
The information is derived from an included copy of GlyphData.xml
and GlyphData_Ideographs.xml, going purely by the glyph name. | [
"Return",
"a",
"named",
"tuple",
"(",
"Glyph",
")",
"containing",
"information",
"derived",
"from",
"a",
"glyph",
"name",
"akin",
"to",
"GSGlyphInfo",
"."
] | python | train | 30.215686 |
allenai/allennlp | allennlp/modules/sampled_softmax_loss.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/sampled_softmax_loss.py#L11-L42 | def _choice(num_words: int, num_samples: int) -> Tuple[np.ndarray, int]:
"""
Chooses ``num_samples`` samples without replacement from [0, ..., num_words).
Returns a tuple (samples, num_tries).
"""
num_tries = 0
num_chosen = 0
def get_buffer() -> np.ndarray:
log_samples = np.random.r... | [
"def",
"_choice",
"(",
"num_words",
":",
"int",
",",
"num_samples",
":",
"int",
")",
"->",
"Tuple",
"[",
"np",
".",
"ndarray",
",",
"int",
"]",
":",
"num_tries",
"=",
"0",
"num_chosen",
"=",
"0",
"def",
"get_buffer",
"(",
")",
"->",
"np",
".",
"nda... | Chooses ``num_samples`` samples without replacement from [0, ..., num_words).
Returns a tuple (samples, num_tries). | [
"Chooses",
"num_samples",
"samples",
"without",
"replacement",
"from",
"[",
"0",
"...",
"num_words",
")",
".",
"Returns",
"a",
"tuple",
"(",
"samples",
"num_tries",
")",
"."
] | python | train | 30.65625 |
learningequality/ricecooker | ricecooker/commands.py | https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/commands.py#L230-L245 | def create_initial_tree(channel):
""" create_initial_tree: Create initial tree structure
Args:
channel (Channel): channel to construct
Returns: tree manager to run rest of steps
"""
# Create channel manager with channel data
config.LOGGER.info(" Setting up initial channel s... | [
"def",
"create_initial_tree",
"(",
"channel",
")",
":",
"# Create channel manager with channel data",
"config",
".",
"LOGGER",
".",
"info",
"(",
"\" Setting up initial channel structure... \"",
")",
"tree",
"=",
"ChannelManager",
"(",
"channel",
")",
"# Make sure channel ... | create_initial_tree: Create initial tree structure
Args:
channel (Channel): channel to construct
Returns: tree manager to run rest of steps | [
"create_initial_tree",
":",
"Create",
"initial",
"tree",
"structure",
"Args",
":",
"channel",
"(",
"Channel",
")",
":",
"channel",
"to",
"construct",
"Returns",
":",
"tree",
"manager",
"to",
"run",
"rest",
"of",
"steps"
] | python | train | 35.3125 |
djgagne/hagelslag | hagelslag/evaluation/NeighborEvaluator.py | https://github.com/djgagne/hagelslag/blob/6fb6c3df90bf4867e13a97d3460b14471d107df1/hagelslag/evaluation/NeighborEvaluator.py#L95-L114 | def load_obs(self, mask_threshold=0.5):
"""
Loads observations and masking grid (if needed).
Args:
mask_threshold: Values greater than the threshold are kept, others are masked.
"""
print("Loading obs ", self.run_date, self.model_name, self.forecast_variable)
... | [
"def",
"load_obs",
"(",
"self",
",",
"mask_threshold",
"=",
"0.5",
")",
":",
"print",
"(",
"\"Loading obs \"",
",",
"self",
".",
"run_date",
",",
"self",
".",
"model_name",
",",
"self",
".",
"forecast_variable",
")",
"start_date",
"=",
"self",
".",
"run_da... | Loads observations and masking grid (if needed).
Args:
mask_threshold: Values greater than the threshold are kept, others are masked. | [
"Loads",
"observations",
"and",
"masking",
"grid",
"(",
"if",
"needed",
")",
"."
] | python | train | 56.95 |
watson-developer-cloud/python-sdk | ibm_watson/compare_comply_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/compare_comply_v1.py#L3399-L3408 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'cell_id') and self.cell_id is not None:
_dict['cell_id'] = self.cell_id
if hasattr(self, 'location') and self.location is not None:
_dict['location'] = self.lo... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'cell_id'",
")",
"and",
"self",
".",
"cell_id",
"is",
"not",
"None",
":",
"_dict",
"[",
"'cell_id'",
"]",
"=",
"self",
".",
"cell_id",
"if",
"hasa... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train | 44.7 |
senaite/senaite.core | bika/lims/browser/idserver/view.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/idserver/view.py#L93-L108 | def get_next_id_for(self, key):
"""Get a preview of the next number
"""
portal_type = key.split("-")[0]
config = get_config(None, portal_type=portal_type)
id_template = config.get("form", "")
number = self.storage.get(key) + 1
spec = {
"seq": number,
... | [
"def",
"get_next_id_for",
"(",
"self",
",",
"key",
")",
":",
"portal_type",
"=",
"key",
".",
"split",
"(",
"\"-\"",
")",
"[",
"0",
"]",
"config",
"=",
"get_config",
"(",
"None",
",",
"portal_type",
"=",
"portal_type",
")",
"id_template",
"=",
"config",
... | Get a preview of the next number | [
"Get",
"a",
"preview",
"of",
"the",
"next",
"number"
] | python | train | 37.25 |
Esri/ArcREST | src/arcrest/enrichment/_geoenrichment.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/enrichment/_geoenrichment.py#L445-L546 | def getVariables(self,
sourceCountry,
optionalCountryDataset=None,
searchText=None):
r"""
The GeoEnrichment GetVariables helper method allows you to search
the data collections for variables that contain specific keywords.
T... | [
"def",
"getVariables",
"(",
"self",
",",
"sourceCountry",
",",
"optionalCountryDataset",
"=",
"None",
",",
"searchText",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"_base_url",
"+",
"self",
".",
"_url_getVariables",
"params",
"=",
"{",
"\"f\"",
":",
"... | r"""
The GeoEnrichment GetVariables helper method allows you to search
the data collections for variables that contain specific keywords.
To see the comprehensive set of global Esri Demographics data that
are available, use the interactive data browser:
http://resources.arcgis.c... | [
"r",
"The",
"GeoEnrichment",
"GetVariables",
"helper",
"method",
"allows",
"you",
"to",
"search",
"the",
"data",
"collections",
"for",
"variables",
"that",
"contain",
"specific",
"keywords",
"."
] | python | train | 69.77451 |
infobloxopen/infoblox-netmri | infoblox_netmri/client.py | https://github.com/infobloxopen/infoblox-netmri/blob/e633bef1584101228b6d403df1de0d3d8e88d5c0/infoblox_netmri/client.py#L233-L245 | def show(self, objtype, objid):
"""Query for a specific resource by ID
Args:
objtype (str): object type, e.g. 'device', 'interface'
objid (int): object ID (DeviceID, etc.)
Returns:
A dict with that object
Raises:
requests.exceptions.HTTPEr... | [
"def",
"show",
"(",
"self",
",",
"objtype",
",",
"objid",
")",
":",
"url",
"=",
"self",
".",
"_object_url",
"(",
"objtype",
",",
"int",
"(",
"objid",
")",
")",
"return",
"self",
".",
"_make_request",
"(",
"url",
",",
"method",
"=",
"\"get\"",
")"
] | Query for a specific resource by ID
Args:
objtype (str): object type, e.g. 'device', 'interface'
objid (int): object ID (DeviceID, etc.)
Returns:
A dict with that object
Raises:
requests.exceptions.HTTPError | [
"Query",
"for",
"a",
"specific",
"resource",
"by",
"ID"
] | python | train | 32.923077 |
duguyue100/minesweeper | minesweeper/gui.py | https://github.com/duguyue100/minesweeper/blob/38b1910f4c34d0275ac10a300285aba6f1d91d61/minesweeper/gui.py#L185-L222 | def info_label(self, indicator):
"""Set info label by given settings.
Parameters
----------
indicator : int
A number where
0-8 is number of mines in srrounding.
12 is a mine field.
"""
if indicator in xrange(1, 9):
self.id ... | [
"def",
"info_label",
"(",
"self",
",",
"indicator",
")",
":",
"if",
"indicator",
"in",
"xrange",
"(",
"1",
",",
"9",
")",
":",
"self",
".",
"id",
"=",
"indicator",
"self",
".",
"setPixmap",
"(",
"QtGui",
".",
"QPixmap",
"(",
"NUMBER_PATHS",
"[",
"ind... | Set info label by given settings.
Parameters
----------
indicator : int
A number where
0-8 is number of mines in srrounding.
12 is a mine field. | [
"Set",
"info",
"label",
"by",
"given",
"settings",
"."
] | python | train | 43.5 |
mapnik/Cascadenik | cascadenik/parse.py | https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/parse.py#L498-L709 | def parse_rule(tokens, variables, neighbors, parents, is_merc):
""" Parse a rule set, return a list of declarations.
Requires a dictionary of declared variables. Selectors in the neighbors
list are simply grouped, and are generated from comma-delimited lists
of selectors in the styl... | [
"def",
"parse_rule",
"(",
"tokens",
",",
"variables",
",",
"neighbors",
",",
"parents",
",",
"is_merc",
")",
":",
"#",
"# Local helper function",
"#",
"def",
"validate_selector_elements",
"(",
"elements",
",",
"line",
",",
"col",
")",
":",
"if",
"len",
"(",
... | Parse a rule set, return a list of declarations.
Requires a dictionary of declared variables. Selectors in the neighbors
list are simply grouped, and are generated from comma-delimited lists
of selectors in the stylesheet. Selectors in the parents list should
be combined with th... | [
"Parse",
"a",
"rule",
"set",
"return",
"a",
"list",
"of",
"declarations",
".",
"Requires",
"a",
"dictionary",
"of",
"declared",
"variables",
".",
"Selectors",
"in",
"the",
"neighbors",
"list",
"are",
"simply",
"grouped",
"and",
"are",
"generated",
"from",
"c... | python | train | 38.59434 |
fananimi/pyzk | zk/base.py | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L753-L766 | def poweroff(self):
"""
shutdown the machine
"""
command = const.CMD_POWEROFF
command_string = b''
response_size = 1032
cmd_response = self.__send_command(command, command_string, response_size)
if cmd_response.get('status'):
self.is_connect = ... | [
"def",
"poweroff",
"(",
"self",
")",
":",
"command",
"=",
"const",
".",
"CMD_POWEROFF",
"command_string",
"=",
"b''",
"response_size",
"=",
"1032",
"cmd_response",
"=",
"self",
".",
"__send_command",
"(",
"command",
",",
"command_string",
",",
"response_size",
... | shutdown the machine | [
"shutdown",
"the",
"machine"
] | python | train | 30.857143 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/query_builder.py | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/query_builder.py#L123-L137 | def startswith(text, ignore_case=True):
"""
Test if a string-field start with ``text``.
Example::
filters = {"path": Text.startswith(r"C:\\")}
"""
if ignore_case:
compiled = re.compile(
"^%s" % text.replace("\\", "\\\\"), re.IGNORECASE)
... | [
"def",
"startswith",
"(",
"text",
",",
"ignore_case",
"=",
"True",
")",
":",
"if",
"ignore_case",
":",
"compiled",
"=",
"re",
".",
"compile",
"(",
"\"^%s\"",
"%",
"text",
".",
"replace",
"(",
"\"\\\\\"",
",",
"\"\\\\\\\\\"",
")",
",",
"re",
".",
"IGNOR... | Test if a string-field start with ``text``.
Example::
filters = {"path": Text.startswith(r"C:\\")} | [
"Test",
"if",
"a",
"string",
"-",
"field",
"start",
"with",
"text",
"."
] | python | train | 29.666667 |
sosy-lab/benchexec | benchexec/container.py | https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/container.py#L324-L339 | def forward_all_signals_async(target_pid, process_name):
"""Install all signal handler that forwards all signals to the given process."""
def forwarding_signal_handler(signum):
_forward_signal(signum, process_name, forwarding_signal_handler.target_pid)
# Somehow we get a Python SystemError sometime... | [
"def",
"forward_all_signals_async",
"(",
"target_pid",
",",
"process_name",
")",
":",
"def",
"forwarding_signal_handler",
"(",
"signum",
")",
":",
"_forward_signal",
"(",
"signum",
",",
"process_name",
",",
"forwarding_signal_handler",
".",
"target_pid",
")",
"# Someh... | Install all signal handler that forwards all signals to the given process. | [
"Install",
"all",
"signal",
"handler",
"that",
"forwards",
"all",
"signals",
"to",
"the",
"given",
"process",
"."
] | python | train | 50.625 |
MisterWil/abodepy | abodepy/devices/lock.py | https://github.com/MisterWil/abodepy/blob/6f84bb428fd1da98855f55083cd427bebbcc57ae/abodepy/devices/lock.py#L10-L17 | def lock(self):
"""Lock the device."""
success = self.set_status(CONST.STATUS_LOCKCLOSED_INT)
if success:
self._json_state['status'] = CONST.STATUS_LOCKCLOSED
return success | [
"def",
"lock",
"(",
"self",
")",
":",
"success",
"=",
"self",
".",
"set_status",
"(",
"CONST",
".",
"STATUS_LOCKCLOSED_INT",
")",
"if",
"success",
":",
"self",
".",
"_json_state",
"[",
"'status'",
"]",
"=",
"CONST",
".",
"STATUS_LOCKCLOSED",
"return",
"suc... | Lock the device. | [
"Lock",
"the",
"device",
"."
] | python | train | 26.5 |
inveniosoftware-attic/invenio-utils | invenio_utils/text.py | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/text.py#L435-L462 | def nice_number(number, thousands_separator=',', max_ndigits_after_dot=None):
"""Return nicely printed number NUMBER in language LN.
Return nicely printed number NUMBER in language LN using
given THOUSANDS_SEPARATOR character.
If max_ndigits_after_dot is specified and the number is float, the
numbe... | [
"def",
"nice_number",
"(",
"number",
",",
"thousands_separator",
"=",
"','",
",",
"max_ndigits_after_dot",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"number",
",",
"float",
")",
":",
"if",
"max_ndigits_after_dot",
"is",
"not",
"None",
":",
"number",
"=... | Return nicely printed number NUMBER in language LN.
Return nicely printed number NUMBER in language LN using
given THOUSANDS_SEPARATOR character.
If max_ndigits_after_dot is specified and the number is float, the
number is rounded by taking in consideration up to max_ndigits_after_dot
digit after t... | [
"Return",
"nicely",
"printed",
"number",
"NUMBER",
"in",
"language",
"LN",
"."
] | python | train | 40.464286 |
rigetti/grove | grove/alpha/jordan_gradient/gradient_utils.py | https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/jordan_gradient/gradient_utils.py#L6-L27 | def binary_float_to_decimal_float(number: Union[float, str]) -> float:
"""
Convert binary floating point to decimal floating point.
:param number: Binary floating point.
:return: Decimal floating point representation of binary floating point.
"""
if isinstance(number, str):
if number[0]... | [
"def",
"binary_float_to_decimal_float",
"(",
"number",
":",
"Union",
"[",
"float",
",",
"str",
"]",
")",
"->",
"float",
":",
"if",
"isinstance",
"(",
"number",
",",
"str",
")",
":",
"if",
"number",
"[",
"0",
"]",
"==",
"'-'",
":",
"n_sign",
"=",
"-",... | Convert binary floating point to decimal floating point.
:param number: Binary floating point.
:return: Decimal floating point representation of binary floating point. | [
"Convert",
"binary",
"floating",
"point",
"to",
"decimal",
"floating",
"point",
"."
] | python | train | 27.727273 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.