repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
sassoftware/saspy | saspy/sasproccommons.py | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasproccommons.py#L206-L304 | def _makeProcCallMacro(self, objtype: str, objname: str, data: ['SASdata', str] = None, args: dict = None) -> str:
"""
This method generates the SAS code from the python objects and included data and arguments.
The list of args in this method is largely alphabetical but there are exceptions in o... | [
"def",
"_makeProcCallMacro",
"(",
"self",
",",
"objtype",
":",
"str",
",",
"objname",
":",
"str",
",",
"data",
":",
"[",
"'SASdata'",
",",
"str",
"]",
"=",
"None",
",",
"args",
":",
"dict",
"=",
"None",
")",
"->",
"str",
":",
"plot",
"=",
"''",
"... | This method generates the SAS code from the python objects and included data and arguments.
The list of args in this method is largely alphabetical but there are exceptions in order to
satisfy the order needs of the statements for the procedure. as an example...
http://support.sas.com/documentat... | [
"This",
"method",
"generates",
"the",
"SAS",
"code",
"from",
"the",
"python",
"objects",
"and",
"included",
"data",
"and",
"arguments",
".",
"The",
"list",
"of",
"args",
"in",
"this",
"method",
"is",
"largely",
"alphabetical",
"but",
"there",
"are",
"excepti... | python | train |
evhub/coconut | coconut/compiler/compiler.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/compiler.py#L1123-L1134 | def endline_handle(self, original, loc, tokens):
"""Add line number information to end of line."""
internal_assert(len(tokens) == 1, "invalid endline tokens", tokens)
lines = tokens[0].splitlines(True)
if self.minify:
lines = lines[0]
out = []
ln = lineno(loc,... | [
"def",
"endline_handle",
"(",
"self",
",",
"original",
",",
"loc",
",",
"tokens",
")",
":",
"internal_assert",
"(",
"len",
"(",
"tokens",
")",
"==",
"1",
",",
"\"invalid endline tokens\"",
",",
"tokens",
")",
"lines",
"=",
"tokens",
"[",
"0",
"]",
".",
... | Add line number information to end of line. | [
"Add",
"line",
"number",
"information",
"to",
"end",
"of",
"line",
"."
] | python | train |
odlgroup/odl | odl/contrib/tomo/elekta.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/tomo/elekta.py#L23-L114 | def elekta_icon_geometry(sad=780.0, sdd=1000.0,
piercing_point=(390.0, 0.0),
angles=None, num_angles=None,
detector_shape=(780, 720)):
"""Tomographic geometry of the Elekta Icon CBCT system.
See the [whitepaper]_ for specific descriptio... | [
"def",
"elekta_icon_geometry",
"(",
"sad",
"=",
"780.0",
",",
"sdd",
"=",
"1000.0",
",",
"piercing_point",
"=",
"(",
"390.0",
",",
"0.0",
")",
",",
"angles",
"=",
"None",
",",
"num_angles",
"=",
"None",
",",
"detector_shape",
"=",
"(",
"780",
",",
"720... | Tomographic geometry of the Elekta Icon CBCT system.
See the [whitepaper]_ for specific descriptions of each parameter.
All measurments are given in millimeters unless otherwise stated.
Parameters
----------
sad : float, optional
Source to Axis distance.
sdd : float, optional
... | [
"Tomographic",
"geometry",
"of",
"the",
"Elekta",
"Icon",
"CBCT",
"system",
"."
] | python | train |
cltk/cltk | cltk/stem/french/stem.py | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/stem/french/stem.py#L53-L74 | def matchremove_verb_endings(word):
"""Remove the verb endings"""
"""verb endings sorted by charlen then alph"""
verb_endings =['issiiens', 'isseient', 'issiiez', 'issons', 'issent', 'issant', 'isseie', 'isseit', 'issons',
'isseiz', 'assent', 'issons', 'isseiz', 'issent', 'iiens', 'eient'... | [
"def",
"matchremove_verb_endings",
"(",
"word",
")",
":",
"\"\"\"verb endings sorted by charlen then alph\"\"\"",
"verb_endings",
"=",
"[",
"'issiiens'",
",",
"'isseient'",
",",
"'issiiez'",
",",
"'issons'",
",",
"'issent'",
",",
"'issant'",
",",
"'isseie'",
",",
"'is... | Remove the verb endings | [
"Remove",
"the",
"verb",
"endings"
] | python | train |
whtsky/parguments | parguments/cli.py | https://github.com/whtsky/parguments/blob/96aa23af411a67c2f70d856e81fa186bb187daab/parguments/cli.py#L78-L97 | def prompt_bool(name, default=False, yes_choices=None, no_choices=None):
"""
Grabs user input from command line and converts to boolean
value.
:param name: prompt text
:param default: default value if no input provided.
:param yes_choices: default 'y', 'yes', '1', 'on', 'true', 't'
:param n... | [
"def",
"prompt_bool",
"(",
"name",
",",
"default",
"=",
"False",
",",
"yes_choices",
"=",
"None",
",",
"no_choices",
"=",
"None",
")",
":",
"yes_choices",
"=",
"yes_choices",
"or",
"(",
"'y'",
",",
"'yes'",
",",
"'1'",
",",
"'on'",
",",
"'true'",
",",
... | Grabs user input from command line and converts to boolean
value.
:param name: prompt text
:param default: default value if no input provided.
:param yes_choices: default 'y', 'yes', '1', 'on', 'true', 't'
:param no_choices: default 'n', 'no', '0', 'off', 'false', 'f' | [
"Grabs",
"user",
"input",
"from",
"command",
"line",
"and",
"converts",
"to",
"boolean",
"value",
"."
] | python | train |
sdispater/poetry | poetry/mixology/partial_solution.py | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/partial_solution.py#L171-L202 | def satisfier(self, term): # type: (Term) -> Assignment
"""
Returns the first Assignment in this solution such that the sublist of
assignments up to and including that entry collectively satisfies term.
"""
assigned_term = None # type: Term
for assignment in self._assi... | [
"def",
"satisfier",
"(",
"self",
",",
"term",
")",
":",
"# type: (Term) -> Assignment",
"assigned_term",
"=",
"None",
"# type: Term",
"for",
"assignment",
"in",
"self",
".",
"_assignments",
":",
"if",
"assignment",
".",
"dependency",
".",
"name",
"!=",
"term",
... | Returns the first Assignment in this solution such that the sublist of
assignments up to and including that entry collectively satisfies term. | [
"Returns",
"the",
"first",
"Assignment",
"in",
"this",
"solution",
"such",
"that",
"the",
"sublist",
"of",
"assignments",
"up",
"to",
"and",
"including",
"that",
"entry",
"collectively",
"satisfies",
"term",
"."
] | python | train |
Parsl/parsl | parsl/app/bash.py | https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/app/bash.py#L12-L111 | def remote_side_bash_executor(func, *args, **kwargs):
"""Execute the bash app type function and return the command line string.
This string is reformatted with the *args, and **kwargs
from call time.
"""
import os
import time
import subprocess
import logging
import parsl.app.errors ... | [
"def",
"remote_side_bash_executor",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"os",
"import",
"time",
"import",
"subprocess",
"import",
"logging",
"import",
"parsl",
".",
"app",
".",
"errors",
"as",
"pe",
"logging",
".",
... | Execute the bash app type function and return the command line string.
This string is reformatted with the *args, and **kwargs
from call time. | [
"Execute",
"the",
"bash",
"app",
"type",
"function",
"and",
"return",
"the",
"command",
"line",
"string",
"."
] | python | valid |
juju/python-libjuju | juju/client/_client3.py | https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/_client3.py#L1673-L1688 | async def UpdateCredentialsCheckModels(self, credentials, force):
'''
credentials : typing.Sequence[~TaggedCredential]
force : bool
Returns -> typing.Sequence[~UpdateCredentialResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Cloud... | [
"async",
"def",
"UpdateCredentialsCheckModels",
"(",
"self",
",",
"credentials",
",",
"force",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'Cloud'",
",",
"request",
"=",
"'UpdateCredentialsCh... | credentials : typing.Sequence[~TaggedCredential]
force : bool
Returns -> typing.Sequence[~UpdateCredentialResult] | [
"credentials",
":",
"typing",
".",
"Sequence",
"[",
"~TaggedCredential",
"]",
"force",
":",
"bool",
"Returns",
"-",
">",
"typing",
".",
"Sequence",
"[",
"~UpdateCredentialResult",
"]"
] | python | train |
ojarva/python-sshpubkeys | sshpubkeys/keys.py | https://github.com/ojarva/python-sshpubkeys/blob/86dc1ab27ce82dcc091ce127416cc3ee219e9bec/sshpubkeys/keys.py#L251-L295 | def parse_options(self, options):
"""Parses ssh options string."""
quote_open = False
parsed_options = {}
def parse_add_single_option(opt):
"""Parses and validates a single option, and adds it to parsed_options field."""
if "=" in opt:
opt_name, o... | [
"def",
"parse_options",
"(",
"self",
",",
"options",
")",
":",
"quote_open",
"=",
"False",
"parsed_options",
"=",
"{",
"}",
"def",
"parse_add_single_option",
"(",
"opt",
")",
":",
"\"\"\"Parses and validates a single option, and adds it to parsed_options field.\"\"\"",
"i... | Parses ssh options string. | [
"Parses",
"ssh",
"options",
"string",
"."
] | python | test |
gem/oq-engine | openquake/risklib/scientific.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1184-L1196 | def broadcast(func, composite_array, *args):
"""
Broadcast an array function over a composite array
"""
dic = {}
dtypes = []
for name in composite_array.dtype.names:
dic[name] = func(composite_array[name], *args)
dtypes.append((name, dic[name].dtype))
res = numpy.zeros(dic[na... | [
"def",
"broadcast",
"(",
"func",
",",
"composite_array",
",",
"*",
"args",
")",
":",
"dic",
"=",
"{",
"}",
"dtypes",
"=",
"[",
"]",
"for",
"name",
"in",
"composite_array",
".",
"dtype",
".",
"names",
":",
"dic",
"[",
"name",
"]",
"=",
"func",
"(",
... | Broadcast an array function over a composite array | [
"Broadcast",
"an",
"array",
"function",
"over",
"a",
"composite",
"array"
] | python | train |
fozzle/python-brotherprint | brotherprint/brotherprint.py | https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L813-L874 | def barcode(self, data, format, characters='off', height=48, width='small', parentheses='on', ratio='3:1', equalize='off', rss_symbol='rss14std', horiz_char_rss=2):
'''Print a standard barcode in the specified format
Args:
data: the barcode data
format: the barcode type ... | [
"def",
"barcode",
"(",
"self",
",",
"data",
",",
"format",
",",
"characters",
"=",
"'off'",
",",
"height",
"=",
"48",
",",
"width",
"=",
"'small'",
",",
"parentheses",
"=",
"'on'",
",",
"ratio",
"=",
"'3:1'",
",",
"equalize",
"=",
"'off'",
",",
"rss_... | Print a standard barcode in the specified format
Args:
data: the barcode data
format: the barcode type you want. Choose between code39, itf, ean8/upca, upce, codabar, code128, gs1-128, rss
characters: Whether you want characters below the bar code. 'off' or 'on'
... | [
"Print",
"a",
"standard",
"barcode",
"in",
"the",
"specified",
"format",
"Args",
":",
"data",
":",
"the",
"barcode",
"data",
"format",
":",
"the",
"barcode",
"type",
"you",
"want",
".",
"Choose",
"between",
"code39",
"itf",
"ean8",
"/",
"upca",
"upce",
"... | python | train |
google/grr | grr/core/grr_response_core/lib/rdfvalues/structs.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/rdfvalues/structs.py#L820-L839 | def Validate(self, value, **_):
"""Check that value is a valid enum."""
# None is a valid value - it means the field is not set.
if value is None:
return
# If the value is a string we need to try to convert it to an integer.
checked_value = value
if isinstance(value, string_types):
... | [
"def",
"Validate",
"(",
"self",
",",
"value",
",",
"*",
"*",
"_",
")",
":",
"# None is a valid value - it means the field is not set.",
"if",
"value",
"is",
"None",
":",
"return",
"# If the value is a string we need to try to convert it to an integer.",
"checked_value",
"="... | Check that value is a valid enum. | [
"Check",
"that",
"value",
"is",
"a",
"valid",
"enum",
"."
] | python | train |
saltstack/salt | salt/netapi/rest_tornado/saltnado.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L522-L534 | def _form_loader(self, _):
'''
function to get the data from the urlencoded forms
ignore the data passed in and just get the args from wherever they are
'''
data = {}
for key in self.request.arguments:
val = self.get_arguments(key)
if len(val) == 1... | [
"def",
"_form_loader",
"(",
"self",
",",
"_",
")",
":",
"data",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"request",
".",
"arguments",
":",
"val",
"=",
"self",
".",
"get_arguments",
"(",
"key",
")",
"if",
"len",
"(",
"val",
")",
"==",
"1",
... | function to get the data from the urlencoded forms
ignore the data passed in and just get the args from wherever they are | [
"function",
"to",
"get",
"the",
"data",
"from",
"the",
"urlencoded",
"forms",
"ignore",
"the",
"data",
"passed",
"in",
"and",
"just",
"get",
"the",
"args",
"from",
"wherever",
"they",
"are"
] | python | train |
anrosent/LT-code | lt/encode/__init__.py | https://github.com/anrosent/LT-code/blob/e13a4c927effc90f9d41ab3884f9fcbd95b9450d/lt/encode/__init__.py#L17-L43 | def encoder(f, blocksize, seed=None, c=sampler.DEFAULT_C, delta=sampler.DEFAULT_DELTA):
"""Generates an infinite sequence of blocks to transmit
to the receiver
"""
# Generate seed if not provided
if seed is None:
seed = randint(0, 1 << 31 - 1)
# get file blocks
filesize, blocks = _... | [
"def",
"encoder",
"(",
"f",
",",
"blocksize",
",",
"seed",
"=",
"None",
",",
"c",
"=",
"sampler",
".",
"DEFAULT_C",
",",
"delta",
"=",
"sampler",
".",
"DEFAULT_DELTA",
")",
":",
"# Generate seed if not provided",
"if",
"seed",
"is",
"None",
":",
"seed",
... | Generates an infinite sequence of blocks to transmit
to the receiver | [
"Generates",
"an",
"infinite",
"sequence",
"of",
"blocks",
"to",
"transmit",
"to",
"the",
"receiver"
] | python | train |
Alignak-monitoring/alignak | alignak/external_command.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/external_command.py#L3966-L3978 | def stop_accepting_passive_svc_checks(self):
"""Disable passive service check submission (globally)
Format of the line that triggers function call::
STOP_ACCEPTING_PASSIVE_SVC_CHECKS
:return: None
"""
if self.my_conf.accept_passive_service_checks:
self.my_co... | [
"def",
"stop_accepting_passive_svc_checks",
"(",
"self",
")",
":",
"if",
"self",
".",
"my_conf",
".",
"accept_passive_service_checks",
":",
"self",
".",
"my_conf",
".",
"modified_attributes",
"|=",
"DICT_MODATTR",
"[",
"\"MODATTR_PASSIVE_CHECKS_ENABLED\"",
"]",
".",
"... | Disable passive service check submission (globally)
Format of the line that triggers function call::
STOP_ACCEPTING_PASSIVE_SVC_CHECKS
:return: None | [
"Disable",
"passive",
"service",
"check",
"submission",
"(",
"globally",
")",
"Format",
"of",
"the",
"line",
"that",
"triggers",
"function",
"call",
"::"
] | python | train |
nugget/python-insteonplm | insteonplm/messages/x10received.py | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/messages/x10received.py#L56-L65 | def command_msg(housecode, command):
"""Create an X10 message to send the house code and a command code."""
house_byte = 0
if isinstance(housecode, str):
house_byte = insteonplm.utils.housecode_to_byte(housecode) << 4
elif isinstance(housecode, int) and housecode < 16:
... | [
"def",
"command_msg",
"(",
"housecode",
",",
"command",
")",
":",
"house_byte",
"=",
"0",
"if",
"isinstance",
"(",
"housecode",
",",
"str",
")",
":",
"house_byte",
"=",
"insteonplm",
".",
"utils",
".",
"housecode_to_byte",
"(",
"housecode",
")",
"<<",
"4",... | Create an X10 message to send the house code and a command code. | [
"Create",
"an",
"X10",
"message",
"to",
"send",
"the",
"house",
"code",
"and",
"a",
"command",
"code",
"."
] | python | train |
DasIch/argvard | argvard/__init__.py | https://github.com/DasIch/argvard/blob/2603e323a995e0915ce41fcf49e2a82519556195/argvard/__init__.py#L151-L179 | def main(self, signature=''):
"""
A decorator that is used to register the main function with the given
`signature`::
@app.main()
def main(context):
# do something
pass
The main function is called, after any options and if no comm... | [
"def",
"main",
"(",
"self",
",",
"signature",
"=",
"''",
")",
":",
"signature",
"=",
"Signature",
".",
"from_string",
"(",
"signature",
",",
"option",
"=",
"False",
")",
"def",
"decorator",
"(",
"function",
")",
":",
"if",
"self",
".",
"main_func",
"is... | A decorator that is used to register the main function with the given
`signature`::
@app.main()
def main(context):
# do something
pass
The main function is called, after any options and if no command has
been called. | [
"A",
"decorator",
"that",
"is",
"used",
"to",
"register",
"the",
"main",
"function",
"with",
"the",
"given",
"signature",
"::"
] | python | train |
scott-griffiths/bitstring | bitstring.py | https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2411-L2447 | def find(self, bs, start=None, end=None, bytealigned=None):
"""Find first occurrence of substring bs.
Returns a single item tuple with the bit position if found, or an
empty tuple if not found. The bit position (pos property) will
also be set to the start of the substring if it is found... | [
"def",
"find",
"(",
"self",
",",
"bs",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"bytealigned",
"=",
"None",
")",
":",
"bs",
"=",
"Bits",
"(",
"bs",
")",
"if",
"not",
"bs",
".",
"len",
":",
"raise",
"ValueError",
"(",
"\"Cannot fin... | Find first occurrence of substring bs.
Returns a single item tuple with the bit position if found, or an
empty tuple if not found. The bit position (pos property) will
also be set to the start of the substring if it is found.
bs -- The bitstring to find.
start -- The bit positi... | [
"Find",
"first",
"occurrence",
"of",
"substring",
"bs",
"."
] | python | train |
craffel/mir_eval | mir_eval/chord.py | https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/chord.py#L594-L615 | def rotate_bitmaps_to_roots(bitmaps, roots):
"""Circularly shift a relative bitmaps to asbolute pitch classes.
See :func:`rotate_bitmap_to_root` for more information.
Parameters
----------
bitmap : np.ndarray, shape=(N, 12)
Bitmap of active notes, relative to the given root.
root : np.... | [
"def",
"rotate_bitmaps_to_roots",
"(",
"bitmaps",
",",
"roots",
")",
":",
"abs_bitmaps",
"=",
"[",
"]",
"for",
"bitmap",
",",
"chord_root",
"in",
"zip",
"(",
"bitmaps",
",",
"roots",
")",
":",
"abs_bitmaps",
".",
"append",
"(",
"rotate_bitmap_to_root",
"(",
... | Circularly shift a relative bitmaps to asbolute pitch classes.
See :func:`rotate_bitmap_to_root` for more information.
Parameters
----------
bitmap : np.ndarray, shape=(N, 12)
Bitmap of active notes, relative to the given root.
root : np.ndarray, shape=(N,)
Absolute pitch class num... | [
"Circularly",
"shift",
"a",
"relative",
"bitmaps",
"to",
"asbolute",
"pitch",
"classes",
"."
] | python | train |
saltstack/salt | salt/modules/boto_apigateway.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L539-L545 | def _api_key_patch_add(conn, apiKey, pvlist):
'''
the add patch operation for a list of (path, value) tuples on an ApiKey resource list path
'''
response = conn.update_api_key(apiKey=apiKey,
patchOperations=_api_key_patchops('add', pvlist))
return response | [
"def",
"_api_key_patch_add",
"(",
"conn",
",",
"apiKey",
",",
"pvlist",
")",
":",
"response",
"=",
"conn",
".",
"update_api_key",
"(",
"apiKey",
"=",
"apiKey",
",",
"patchOperations",
"=",
"_api_key_patchops",
"(",
"'add'",
",",
"pvlist",
")",
")",
"return",... | the add patch operation for a list of (path, value) tuples on an ApiKey resource list path | [
"the",
"add",
"patch",
"operation",
"for",
"a",
"list",
"of",
"(",
"path",
"value",
")",
"tuples",
"on",
"an",
"ApiKey",
"resource",
"list",
"path"
] | python | train |
lmjohns3/theanets | theanets/graph.py | https://github.com/lmjohns3/theanets/blob/79db9f878ef2071f2f576a1cf5d43a752a55894a/theanets/graph.py#L700-L710 | def updates(self, **kwargs):
'''Return expressions to run as updates during network training.
Returns
-------
updates : list of (parameter, expression) pairs
A list of named parameter update expressions for this network.
'''
regs = regularizers.from_kwargs(se... | [
"def",
"updates",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"regs",
"=",
"regularizers",
".",
"from_kwargs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"_",
",",
"updates",
"=",
"self",
".",
"build_graph",
"(",
"regs",
")",
"return",
"updates"
... | Return expressions to run as updates during network training.
Returns
-------
updates : list of (parameter, expression) pairs
A list of named parameter update expressions for this network. | [
"Return",
"expressions",
"to",
"run",
"as",
"updates",
"during",
"network",
"training",
"."
] | python | test |
lago-project/lago | lago/templates.py | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/templates.py#L494-L503 | def get_hash(self):
"""
Returns the associated hash for this template version
Returns:
str: Hash for this version
"""
if self._hash is None:
self._hash = self._source.get_hash(self._handle).strip()
return self._hash | [
"def",
"get_hash",
"(",
"self",
")",
":",
"if",
"self",
".",
"_hash",
"is",
"None",
":",
"self",
".",
"_hash",
"=",
"self",
".",
"_source",
".",
"get_hash",
"(",
"self",
".",
"_handle",
")",
".",
"strip",
"(",
")",
"return",
"self",
".",
"_hash"
] | Returns the associated hash for this template version
Returns:
str: Hash for this version | [
"Returns",
"the",
"associated",
"hash",
"for",
"this",
"template",
"version"
] | python | train |
ianmiell/shutit | shutit_patterns/shutitfile.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_patterns/shutitfile.py#L856-L869 | def scan_text(text):
"""Scan text, and replace items that match shutit's pattern format, ie:
{{ shutit.THING }}
"""
while True:
match = re.match("(.*){{ shutit.(.*) }}(.*)$", text)
if match:
before = match.group(1)
name = match.group(2)
after = match.group(3)
text = before + """''' + shutit.cfg[self... | [
"def",
"scan_text",
"(",
"text",
")",
":",
"while",
"True",
":",
"match",
"=",
"re",
".",
"match",
"(",
"\"(.*){{ shutit.(.*) }}(.*)$\"",
",",
"text",
")",
"if",
"match",
":",
"before",
"=",
"match",
".",
"group",
"(",
"1",
")",
"name",
"=",
"match",
... | Scan text, and replace items that match shutit's pattern format, ie:
{{ shutit.THING }} | [
"Scan",
"text",
"and",
"replace",
"items",
"that",
"match",
"shutit",
"s",
"pattern",
"format",
"ie",
":",
"{{",
"shutit",
".",
"THING",
"}}"
] | python | train |
wummel/linkchecker | linkcheck/checker/urlbase.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/checker/urlbase.py#L633-L642 | def read_content(self):
"""Return data for this URL. Can be overridden in subclasses."""
buf = StringIO()
data = self.read_content_chunk()
while data:
if buf.tell() + len(data) > self.aggregate.config["maxfilesizedownload"]:
raise LinkCheckerError(_("File size... | [
"def",
"read_content",
"(",
"self",
")",
":",
"buf",
"=",
"StringIO",
"(",
")",
"data",
"=",
"self",
".",
"read_content_chunk",
"(",
")",
"while",
"data",
":",
"if",
"buf",
".",
"tell",
"(",
")",
"+",
"len",
"(",
"data",
")",
">",
"self",
".",
"a... | Return data for this URL. Can be overridden in subclasses. | [
"Return",
"data",
"for",
"this",
"URL",
".",
"Can",
"be",
"overridden",
"in",
"subclasses",
"."
] | python | train |
fabioz/PyDev.Debugger | third_party/pep8/autopep8.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/autopep8.py#L3757-L3796 | def main(argv=None, apply_config=True):
"""Command-line entry."""
if argv is None:
argv = sys.argv
try:
# Exit on broken pipe.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except AttributeError: # pragma: no cover
# SIGPIPE is not available on Windows.
pass
... | [
"def",
"main",
"(",
"argv",
"=",
"None",
",",
"apply_config",
"=",
"True",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"try",
":",
"# Exit on broken pipe.",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGPIPE",
",",
... | Command-line entry. | [
"Command",
"-",
"line",
"entry",
"."
] | python | train |
cs50/lib50 | lib50/_api.py | https://github.com/cs50/lib50/blob/941767f6c0a3b81af0cdea48c25c8d5a761086eb/lib50/_api.py#L58-L97 | def local(tool, slug, config_loader, offline=False):
"""
Create/update local copy of github.com/org/repo/branch.
Returns path to local copy
"""
# Parse slug
slug = Slug(slug, offline=offline)
local_path = Path(LOCAL_PATH).expanduser() / slug.org / slug.repo
git = Git(f"-C {shlex.quote(... | [
"def",
"local",
"(",
"tool",
",",
"slug",
",",
"config_loader",
",",
"offline",
"=",
"False",
")",
":",
"# Parse slug",
"slug",
"=",
"Slug",
"(",
"slug",
",",
"offline",
"=",
"offline",
")",
"local_path",
"=",
"Path",
"(",
"LOCAL_PATH",
")",
".",
"expa... | Create/update local copy of github.com/org/repo/branch.
Returns path to local copy | [
"Create",
"/",
"update",
"local",
"copy",
"of",
"github",
".",
"com",
"/",
"org",
"/",
"repo",
"/",
"branch",
".",
"Returns",
"path",
"to",
"local",
"copy"
] | python | train |
TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/ipaddr.py | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/ipaddr.py#L1609-L1631 | def is_reserved(self):
"""Test if the address is otherwise IETF reserved.
Returns:
A boolean, True if the address is within one of the
reserved IPv6 Network ranges.
"""
return (self in IPv6Network('::/8') or
self in IPv6Network('100::/8') or
... | [
"def",
"is_reserved",
"(",
"self",
")",
":",
"return",
"(",
"self",
"in",
"IPv6Network",
"(",
"'::/8'",
")",
"or",
"self",
"in",
"IPv6Network",
"(",
"'100::/8'",
")",
"or",
"self",
"in",
"IPv6Network",
"(",
"'200::/7'",
")",
"or",
"self",
"in",
"IPv6Netw... | Test if the address is otherwise IETF reserved.
Returns:
A boolean, True if the address is within one of the
reserved IPv6 Network ranges. | [
"Test",
"if",
"the",
"address",
"is",
"otherwise",
"IETF",
"reserved",
"."
] | python | train |
terrycain/aioboto3 | aioboto3/s3/cse.py | https://github.com/terrycain/aioboto3/blob/0fd192175461f7bb192f3ed9a872591caf8474ac/aioboto3/s3/cse.py#L178-L194 | async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes:
"""
Get decryption key for a given S3 object
:param key: Base64 decoded version of x-amz-key
:param material_description: JSON decoded x-amz-matdesc
:return: Raw AES key bytes
... | [
"async",
"def",
"get_decryption_aes_key",
"(",
"self",
",",
"key",
":",
"bytes",
",",
"material_description",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"bytes",
":",
"# So it seems when java just calls Cipher.getInstance('AES') it'll default to AES/ECB/PKCS5Pad... | Get decryption key for a given S3 object
:param key: Base64 decoded version of x-amz-key
:param material_description: JSON decoded x-amz-matdesc
:return: Raw AES key bytes | [
"Get",
"decryption",
"key",
"for",
"a",
"given",
"S3",
"object"
] | python | train |
welbornprod/colr | colr/colr.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/colr.py#L1065-L1108 | def _iter_text_wave(
self, text, numbers, step=1,
fore=None, back=None, style=None, rgb_mode=False):
""" Yield colorized characters from `text`, using a wave of `numbers`.
Arguments:
text : String to be colorized.
numbers : A list/tuple ... | [
"def",
"_iter_text_wave",
"(",
"self",
",",
"text",
",",
"numbers",
",",
"step",
"=",
"1",
",",
"fore",
"=",
"None",
",",
"back",
"=",
"None",
",",
"style",
"=",
"None",
",",
"rgb_mode",
"=",
"False",
")",
":",
"if",
"fore",
"and",
"back",
":",
"... | Yield colorized characters from `text`, using a wave of `numbers`.
Arguments:
text : String to be colorized.
numbers : A list/tuple of numbers (256 colors).
step : Number of characters to colorize per color.
fore : Fore color t... | [
"Yield",
"colorized",
"characters",
"from",
"text",
"using",
"a",
"wave",
"of",
"numbers",
".",
"Arguments",
":",
"text",
":",
"String",
"to",
"be",
"colorized",
".",
"numbers",
":",
"A",
"list",
"/",
"tuple",
"of",
"numbers",
"(",
"256",
"colors",
")",
... | python | train |
BerkeleyAutomation/perception | perception/realsense_sensor.py | https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/realsense_sensor.py#L179-L189 | def stop(self):
"""Stop the sensor.
"""
# check that everything is running
if not self._running:
logging.warning('Realsense not running. Aborting stop.')
return False
self._pipe.stop()
self._running = False
return True | [
"def",
"stop",
"(",
"self",
")",
":",
"# check that everything is running",
"if",
"not",
"self",
".",
"_running",
":",
"logging",
".",
"warning",
"(",
"'Realsense not running. Aborting stop.'",
")",
"return",
"False",
"self",
".",
"_pipe",
".",
"stop",
"(",
")",... | Stop the sensor. | [
"Stop",
"the",
"sensor",
"."
] | python | train |
seequent/properties | properties/basic.py | https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L34-L53 | def accept_kwargs(func):
"""Wrap a function that may not accept kwargs so they are accepted
The output function will always have call signature of
:code:`func(val, **kwargs)`, whereas the original function may have
call signatures of :code:`func(val)` or :code:`func(val, **kwargs)`.
In the case of ... | [
"def",
"accept_kwargs",
"(",
"func",
")",
":",
"def",
"wrapped",
"(",
"val",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Perform a function on a value, ignoring kwargs if necessary\"\"\"",
"try",
":",
"return",
"func",
"(",
"val",
",",
"*",
"*",
"kwargs",
")",
"... | Wrap a function that may not accept kwargs so they are accepted
The output function will always have call signature of
:code:`func(val, **kwargs)`, whereas the original function may have
call signatures of :code:`func(val)` or :code:`func(val, **kwargs)`.
In the case of the former, rather than erroring... | [
"Wrap",
"a",
"function",
"that",
"may",
"not",
"accept",
"kwargs",
"so",
"they",
"are",
"accepted"
] | python | train |
twisted/txaws | txaws/server/call.py | https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/server/call.py#L40-L52 | def parse(self, schema, strict=True):
"""Update C{args} and C{rest}, parsing the raw request arguments.
@param schema: The L{Schema} the parameters must be extracted with.
@param strict: If C{True} an error is raised if parameters not included
in the schema are found, otherwise the ... | [
"def",
"parse",
"(",
"self",
",",
"schema",
",",
"strict",
"=",
"True",
")",
":",
"self",
".",
"args",
",",
"self",
".",
"rest",
"=",
"schema",
".",
"extract",
"(",
"self",
".",
"_raw_params",
")",
"if",
"strict",
"and",
"self",
".",
"rest",
":",
... | Update C{args} and C{rest}, parsing the raw request arguments.
@param schema: The L{Schema} the parameters must be extracted with.
@param strict: If C{True} an error is raised if parameters not included
in the schema are found, otherwise the extra parameters will be
saved in the... | [
"Update",
"C",
"{",
"args",
"}",
"and",
"C",
"{",
"rest",
"}",
"parsing",
"the",
"raw",
"request",
"arguments",
"."
] | python | train |
Esri/ArcREST | src/arcresthelper/portalautomation.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/portalautomation.py#L301-L440 | def createGroups(self, configFiles, dateTimeFormat=None):
"""Parses a JSON configuration file to create groups.
Args:
configFiles (list): A list of JSON files on disk containing
configuration data for creating groups.
dateTimeFormat (str): A valid date formatting... | [
"def",
"createGroups",
"(",
"self",
",",
"configFiles",
",",
"dateTimeFormat",
"=",
"None",
")",
":",
"groupInfo",
"=",
"None",
"groupFile",
"=",
"None",
"iconPath",
"=",
"None",
"startTime",
"=",
"None",
"thumbnail",
"=",
"None",
"result",
"=",
"None",
"c... | Parses a JSON configuration file to create groups.
Args:
configFiles (list): A list of JSON files on disk containing
configuration data for creating groups.
dateTimeFormat (str): A valid date formatting directive, as understood
by :py:meth:`datetime.datet... | [
"Parses",
"a",
"JSON",
"configuration",
"file",
"to",
"create",
"groups",
"."
] | python | train |
LogicalDash/LiSE | allegedb/allegedb/query.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/query.py#L282-L293 | def graph_val_dump(self):
"""Yield the entire contents of the graph_val table."""
self._flush_graph_val()
for (graph, key, branch, turn, tick, value) in self.sql('graph_val_dump'):
yield (
self.unpack(graph),
self.unpack(key),
branch,
... | [
"def",
"graph_val_dump",
"(",
"self",
")",
":",
"self",
".",
"_flush_graph_val",
"(",
")",
"for",
"(",
"graph",
",",
"key",
",",
"branch",
",",
"turn",
",",
"tick",
",",
"value",
")",
"in",
"self",
".",
"sql",
"(",
"'graph_val_dump'",
")",
":",
"yiel... | Yield the entire contents of the graph_val table. | [
"Yield",
"the",
"entire",
"contents",
"of",
"the",
"graph_val",
"table",
"."
] | python | train |
tanghaibao/jcvi | jcvi/formats/gff.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/gff.py#L2669-L2850 | def load(args):
'''
%prog load gff_file fasta_file [--options]
Parses the selected features out of GFF, with subfeatures concatenated.
For example, to get the CDS sequences, do this:
$ %prog load athaliana.gff athaliana.fa --parents mRNA --children CDS
To get 500bp upstream of a genes Transcri... | [
"def",
"load",
"(",
"args",
")",
":",
"from",
"datetime",
"import",
"datetime",
"as",
"dt",
"from",
"jcvi",
".",
"formats",
".",
"fasta",
"import",
"Seq",
",",
"SeqRecord",
"# can request output fasta sequence id to be picked from following attributes",
"valid_id_attrib... | %prog load gff_file fasta_file [--options]
Parses the selected features out of GFF, with subfeatures concatenated.
For example, to get the CDS sequences, do this:
$ %prog load athaliana.gff athaliana.fa --parents mRNA --children CDS
To get 500bp upstream of a genes Transcription Start Site (TSS), do t... | [
"%prog",
"load",
"gff_file",
"fasta_file",
"[",
"--",
"options",
"]"
] | python | train |
hugapi/hug | hug/middleware.py | https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/middleware.py#L99-L101 | def process_request(self, request, response):
"""Logs the basic endpoint requested"""
self.logger.info('Requested: {0} {1} {2}'.format(request.method, request.relative_uri, request.content_type)) | [
"def",
"process_request",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Requested: {0} {1} {2}'",
".",
"format",
"(",
"request",
".",
"method",
",",
"request",
".",
"relative_uri",
",",
"request",
".",
"... | Logs the basic endpoint requested | [
"Logs",
"the",
"basic",
"endpoint",
"requested"
] | python | train |
ToucanToco/toucan-data-sdk | toucan_data_sdk/utils/postprocess/filter_by_date.py | https://github.com/ToucanToco/toucan-data-sdk/blob/c3ca874e1b64f4bdcc2edda750a72d45d1561d8a/toucan_data_sdk/utils/postprocess/filter_by_date.py#L95-L112 | def add_years(dateobj, nb_years):
"""return `dateobj` + `nb_years`
If landing date doesn't exist (e.g. february, 30th), return the last
day of the landing month.
>>> add_years(date(2018, 1, 1), 1)
datetime.date(2019, 1, 1)
>>> add_years(date(2018, 1, 1), -1)
datetime.date(2017, 1, 1)
>... | [
"def",
"add_years",
"(",
"dateobj",
",",
"nb_years",
")",
":",
"year",
"=",
"dateobj",
".",
"year",
"+",
"nb_years",
"lastday",
"=",
"monthrange",
"(",
"year",
",",
"dateobj",
".",
"month",
")",
"[",
"1",
"]",
"return",
"dateobj",
".",
"replace",
"(",
... | return `dateobj` + `nb_years`
If landing date doesn't exist (e.g. february, 30th), return the last
day of the landing month.
>>> add_years(date(2018, 1, 1), 1)
datetime.date(2019, 1, 1)
>>> add_years(date(2018, 1, 1), -1)
datetime.date(2017, 1, 1)
>>> add_years(date(2020, 2, 29), 1)
da... | [
"return",
"dateobj",
"+",
"nb_years"
] | python | test |
saltstack/salt | salt/cloud/clouds/saltify.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/saltify.py#L203-L210 | def show_instance(name, call=None):
'''
List the a single node, return dict of grains.
'''
local = salt.client.LocalClient()
ret = local.cmd(name, 'grains.items')
ret.update(_build_required_items(ret))
return ret | [
"def",
"show_instance",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"local",
"=",
"salt",
".",
"client",
".",
"LocalClient",
"(",
")",
"ret",
"=",
"local",
".",
"cmd",
"(",
"name",
",",
"'grains.items'",
")",
"ret",
".",
"update",
"(",
"_build_r... | List the a single node, return dict of grains. | [
"List",
"the",
"a",
"single",
"node",
"return",
"dict",
"of",
"grains",
"."
] | python | train |
lsst-sqre/lsst-projectmeta-kit | lsstprojectmeta/tex/lsstdoc.py | https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L282-L315 | def format_title(self, format='html5', deparagraph=True, mathjax=False,
smart=True, extra_args=None):
"""Get the document title in the specified markup format.
Parameters
----------
format : `str`, optional
Output format (such as ``'html5'`` or ``'plain'... | [
"def",
"format_title",
"(",
"self",
",",
"format",
"=",
"'html5'",
",",
"deparagraph",
"=",
"True",
",",
"mathjax",
"=",
"False",
",",
"smart",
"=",
"True",
",",
"extra_args",
"=",
"None",
")",
":",
"if",
"self",
".",
"title",
"is",
"None",
":",
"ret... | Get the document title in the specified markup format.
Parameters
----------
format : `str`, optional
Output format (such as ``'html5'`` or ``'plain'``).
deparagraph : `bool`, optional
Remove the paragraph tags from single paragraph content.
mathjax : `bo... | [
"Get",
"the",
"document",
"title",
"in",
"the",
"specified",
"markup",
"format",
"."
] | python | valid |
SecurityInnovation/PGPy | pgpy/pgp.py | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L1539-L1568 | def protect(self, passphrase, enc_alg, hash_alg):
"""
Add a passphrase to a private key. If the key is already passphrase protected, it should be unlocked before
a new passphrase can be specified.
Has no effect on public keys.
:param passphrase: A passphrase to protect the key ... | [
"def",
"protect",
"(",
"self",
",",
"passphrase",
",",
"enc_alg",
",",
"hash_alg",
")",
":",
"##TODO: specify strong defaults for enc_alg and hash_alg",
"if",
"self",
".",
"is_public",
":",
"# we can't protect public keys because only private key material is ever protected",
"w... | Add a passphrase to a private key. If the key is already passphrase protected, it should be unlocked before
a new passphrase can be specified.
Has no effect on public keys.
:param passphrase: A passphrase to protect the key with
:type passphrase: ``str``, ``unicode``
:param enc... | [
"Add",
"a",
"passphrase",
"to",
"a",
"private",
"key",
".",
"If",
"the",
"key",
"is",
"already",
"passphrase",
"protected",
"it",
"should",
"be",
"unlocked",
"before",
"a",
"new",
"passphrase",
"can",
"be",
"specified",
"."
] | python | train |
FutunnOpen/futuquant | futuquant/examples/TinyQuant/TinyQuantBase.py | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/examples/TinyQuant/TinyQuantBase.py#L138-L143 | def cci(self, n, array=False):
"""CCI指标"""
result = talib.CCI(self.high, self.low, self.close, n)
if array:
return result
return result[-1] | [
"def",
"cci",
"(",
"self",
",",
"n",
",",
"array",
"=",
"False",
")",
":",
"result",
"=",
"talib",
".",
"CCI",
"(",
"self",
".",
"high",
",",
"self",
".",
"low",
",",
"self",
".",
"close",
",",
"n",
")",
"if",
"array",
":",
"return",
"result",
... | CCI指标 | [
"CCI指标"
] | python | train |
CityOfZion/neo-python | neo/Wallets/Wallet.py | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L1184-L1215 | def Sign(self, context):
"""
Sign the verifiable items ( Transaction, Block, etc ) in the context with the Keypairs in this wallet.
Args:
context (ContractParameterContext): the context to sign.
Returns:
bool: if signing is successful for all contracts in this w... | [
"def",
"Sign",
"(",
"self",
",",
"context",
")",
":",
"success",
"=",
"False",
"for",
"hash",
"in",
"context",
".",
"ScriptHashes",
":",
"contract",
"=",
"self",
".",
"GetContract",
"(",
"hash",
")",
"if",
"contract",
"is",
"None",
":",
"logger",
".",
... | Sign the verifiable items ( Transaction, Block, etc ) in the context with the Keypairs in this wallet.
Args:
context (ContractParameterContext): the context to sign.
Returns:
bool: if signing is successful for all contracts in this wallet. | [
"Sign",
"the",
"verifiable",
"items",
"(",
"Transaction",
"Block",
"etc",
")",
"in",
"the",
"context",
"with",
"the",
"Keypairs",
"in",
"this",
"wallet",
"."
] | python | train |
MaT1g3R/option | option/option_.py | https://github.com/MaT1g3R/option/blob/37c954e6e74273d48649b3236bc881a1286107d6/option/option_.py#L240-L258 | def map(self, callback: Callable[[T], U]) -> 'Option[U]':
"""
Applies the ``callback`` with the contained value as its argument or
returns :py:data:`NONE`.
Args:
callback: The callback to apply to the contained value.
Returns:
The ``callback`` result wra... | [
"def",
"map",
"(",
"self",
",",
"callback",
":",
"Callable",
"[",
"[",
"T",
"]",
",",
"U",
"]",
")",
"->",
"'Option[U]'",
":",
"return",
"self",
".",
"_type",
".",
"Some",
"(",
"callback",
"(",
"self",
".",
"_val",
")",
")",
"if",
"self",
".",
... | Applies the ``callback`` with the contained value as its argument or
returns :py:data:`NONE`.
Args:
callback: The callback to apply to the contained value.
Returns:
The ``callback`` result wrapped in an :class:`Option` if the
contained value is ``Some``, oth... | [
"Applies",
"the",
"callback",
"with",
"the",
"contained",
"value",
"as",
"its",
"argument",
"or",
"returns",
":",
"py",
":",
"data",
":",
"NONE",
"."
] | python | train |
cuihantao/andes | andes/variables/dae.py | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/dae.py#L624-L644 | def set_jac(self, m, val, row, col):
"""
Set the values at (row, col) to val in Jacobian m
:param m: Jacobian name
:param val: values to set
:param row: row indices
:param col: col indices
:return: None
"""
assert m in ('Fx', 'Fy', 'Gx', 'Gy', 'Fx... | [
"def",
"set_jac",
"(",
"self",
",",
"m",
",",
"val",
",",
"row",
",",
"col",
")",
":",
"assert",
"m",
"in",
"(",
"'Fx'",
",",
"'Fy'",
",",
"'Gx'",
",",
"'Gy'",
",",
"'Fx0'",
",",
"'Fy0'",
",",
"'Gx0'",
",",
"'Gy0'",
")",
",",
"'Wrong Jacobian mat... | Set the values at (row, col) to val in Jacobian m
:param m: Jacobian name
:param val: values to set
:param row: row indices
:param col: col indices
:return: None | [
"Set",
"the",
"values",
"at",
"(",
"row",
"col",
")",
"to",
"val",
"in",
"Jacobian",
"m"
] | python | train |
bukun/TorCMS | torcms/core/privilege.py | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/core/privilege.py#L23-L54 | def auth_view(method):
'''
role for view.
'''
def wrapper(self, *args, **kwargs):
'''
wrapper.
'''
if ROLE_CFG['view'] == '':
return method(self, *args, **kwargs)
elif self.current_user:
if is_prived(self.userinfo.role, ROLE_CFG['view']):... | [
"def",
"auth_view",
"(",
"method",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"'''\n wrapper.\n '''",
"if",
"ROLE_CFG",
"[",
"'view'",
"]",
"==",
"''",
":",
"return",
"method",
"(",
"self",... | role for view. | [
"role",
"for",
"view",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/provenance/system.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/system.py#L101-L119 | def _torque_queue_nodes(queue):
"""Retrieve the nodes available for a queue.
Parses out nodes from `acl_hosts` in qstat -Qf and extracts the
initial names of nodes used in pbsnodes.
"""
qstat_out = subprocess.check_output(["qstat", "-Qf", queue]).decode()
hosts = []
in_hosts = False
for... | [
"def",
"_torque_queue_nodes",
"(",
"queue",
")",
":",
"qstat_out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"qstat\"",
",",
"\"-Qf\"",
",",
"queue",
"]",
")",
".",
"decode",
"(",
")",
"hosts",
"=",
"[",
"]",
"in_hosts",
"=",
"False",
"for",
... | Retrieve the nodes available for a queue.
Parses out nodes from `acl_hosts` in qstat -Qf and extracts the
initial names of nodes used in pbsnodes. | [
"Retrieve",
"the",
"nodes",
"available",
"for",
"a",
"queue",
"."
] | python | train |
gofed/gofedlib | gofedlib/snapshot/capturer.py | https://github.com/gofed/gofedlib/blob/0674c248fe3d8706f98f912996b65af469f96b10/gofedlib/snapshot/capturer.py#L25-L51 | def capture(self, commit = ""):
"""Capture the current state of a project based on its provider
Commit is relevant only for upstream providers.
If empty, the latest commit from provider repository is taken.
It is ignored for distribution providers.
:param provider: project provider, e.g. upstream repository... | [
"def",
"capture",
"(",
"self",
",",
"commit",
"=",
"\"\"",
")",
":",
"self",
".",
"_validateProvider",
"(",
"self",
".",
"_provider",
")",
"# get client for repository",
"# TODO(jchaloup): read config file to switch between local and remove clients",
"# TODO(jchaloup): remote... | Capture the current state of a project based on its provider
Commit is relevant only for upstream providers.
If empty, the latest commit from provider repository is taken.
It is ignored for distribution providers.
:param provider: project provider, e.g. upstream repository, distribution builder
:type provi... | [
"Capture",
"the",
"current",
"state",
"of",
"a",
"project",
"based",
"on",
"its",
"provider"
] | python | train |
FNNDSC/pfurl | pfurl/pfurl.py | https://github.com/FNNDSC/pfurl/blob/572f634ab582b7b7b7a3fbfd5bf12aadc1ba7958/pfurl/pfurl.py#L266-L330 | def man(self, **kwargs):
"""
Print some man for each understood command
"""
str_man = 'commands'
str_amount = 'full'
for k, v in kwargs.items():
if k == 'on': str_man = v
if k == 'amount': str_amount = v
if str_man == '... | [
"def",
"man",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"str_man",
"=",
"'commands'",
"str_amount",
"=",
"'full'",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'on'",
":",
"str_man",
"=",
"v",
"if",
... | Print some man for each understood command | [
"Print",
"some",
"man",
"for",
"each",
"understood",
"command"
] | python | train |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L154-L178 | def css_tag(parser, token):
"""
Renders a tag to include the stylesheet. It takes an optional second
parameter for the media attribute; the default media is "screen, projector".
Usage::
{% css "<somefile>.css" ["<projection type(s)>"] %}
Examples::
{% css "myfile.css" %}
... | [
"def",
"css_tag",
"(",
"parser",
",",
"token",
")",
":",
"path",
"=",
"get_path_from_tokens",
"(",
"token",
")",
"tokens",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"tokens",
")",
">",
"2",
":",
"# Get the media types from the tag call... | Renders a tag to include the stylesheet. It takes an optional second
parameter for the media attribute; the default media is "screen, projector".
Usage::
{% css "<somefile>.css" ["<projection type(s)>"] %}
Examples::
{% css "myfile.css" %}
{% css "myfile.css" "screen, projec... | [
"Renders",
"a",
"tag",
"to",
"include",
"the",
"stylesheet",
".",
"It",
"takes",
"an",
"optional",
"second",
"parameter",
"for",
"the",
"media",
"attribute",
";",
"the",
"default",
"media",
"is",
"screen",
"projector",
".",
"Usage",
"::"
] | python | train |
hazelcast/hazelcast-python-client | hazelcast/proxy/multi_map.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/multi_map.py#L19-L53 | def add_entry_listener(self, include_value=False, key=None, added_func=None, removed_func=None, clear_all_func=None):
"""
Adds an entry listener for this multimap. The listener will be notified for all multimap add/remove/clear-all
events.
:param include_value: (bool), whether received ... | [
"def",
"add_entry_listener",
"(",
"self",
",",
"include_value",
"=",
"False",
",",
"key",
"=",
"None",
",",
"added_func",
"=",
"None",
",",
"removed_func",
"=",
"None",
",",
"clear_all_func",
"=",
"None",
")",
":",
"if",
"key",
":",
"key_data",
"=",
"sel... | Adds an entry listener for this multimap. The listener will be notified for all multimap add/remove/clear-all
events.
:param include_value: (bool), whether received event should include the value or not (optional).
:param key: (object), key for filtering the events (optional).
:param ad... | [
"Adds",
"an",
"entry",
"listener",
"for",
"this",
"multimap",
".",
"The",
"listener",
"will",
"be",
"notified",
"for",
"all",
"multimap",
"add",
"/",
"remove",
"/",
"clear",
"-",
"all",
"events",
"."
] | python | train |
amperser/proselint | proselint/checks/dates_times/dates.py | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/dates_times/dates.py#L21-L29 | def check_decade_apostrophes_short(text):
"""Check the text for dates of the form X0's."""
err = "dates_times.dates"
msg = u"Apostrophes aren't needed for decades."
regex = "\d0\'s"
return existence_check(
text, [regex], err, msg, excluded_topics=["50 Cent"]) | [
"def",
"check_decade_apostrophes_short",
"(",
"text",
")",
":",
"err",
"=",
"\"dates_times.dates\"",
"msg",
"=",
"u\"Apostrophes aren't needed for decades.\"",
"regex",
"=",
"\"\\d0\\'s\"",
"return",
"existence_check",
"(",
"text",
",",
"[",
"regex",
"]",
",",
"err",
... | Check the text for dates of the form X0's. | [
"Check",
"the",
"text",
"for",
"dates",
"of",
"the",
"form",
"X0",
"s",
"."
] | python | train |
timofurrer/colorful | colorful/colors.py | https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/colors.py#L18-L30 | def parse_colors(path):
"""Parse the given color files.
Supported are:
* .txt for X11 colors
* .json for colornames
"""
if path.endswith(".txt"):
return parse_rgb_txt_file(path)
elif path.endswith(".json"):
return parse_json_color_file(path)
raise TypeError("col... | [
"def",
"parse_colors",
"(",
"path",
")",
":",
"if",
"path",
".",
"endswith",
"(",
"\".txt\"",
")",
":",
"return",
"parse_rgb_txt_file",
"(",
"path",
")",
"elif",
"path",
".",
"endswith",
"(",
"\".json\"",
")",
":",
"return",
"parse_json_color_file",
"(",
"... | Parse the given color files.
Supported are:
* .txt for X11 colors
* .json for colornames | [
"Parse",
"the",
"given",
"color",
"files",
"."
] | python | valid |
rvswift/EB | EB/builder/utilities/classification.py | https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/utilities/classification.py#L383-L412 | def make_score_structure(molecules, ensemble):
"""
puts data in the score_structure format for subsequent processing
:param molecules: list [mol_object_1, mol_object_2, .... ] mol_objects are instances of common_tools.molecules
:return score_structure: list [(id, best_score, best_query, status, net deco... | [
"def",
"make_score_structure",
"(",
"molecules",
",",
"ensemble",
")",
":",
"# sort molecules by their ensemble score",
"#sort_order = get_sort_order(molecules)",
"sort_order",
"=",
"'asc'",
"sorted_molecules",
"=",
"screener",
".",
"screener",
"(",
"molecules",
",",
"ensem... | puts data in the score_structure format for subsequent processing
:param molecules: list [mol_object_1, mol_object_2, .... ] mol_objects are instances of common_tools.molecules
:return score_structure: list [(id, best_score, best_query, status, net decoy count, net active count), ..., ] | [
"puts",
"data",
"in",
"the",
"score_structure",
"format",
"for",
"subsequent",
"processing",
":",
"param",
"molecules",
":",
"list",
"[",
"mol_object_1",
"mol_object_2",
"....",
"]",
"mol_objects",
"are",
"instances",
"of",
"common_tools",
".",
"molecules",
":",
... | python | train |
open-mmlab/mmcv | mmcv/video/optflow.py | https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/video/optflow.py#L90-L115 | def quantize_flow(flow, max_val=0.02, norm=True):
"""Quantize flow to [0, 255].
After this step, the size of flow will be much smaller, and can be
dumped as jpeg images.
Args:
flow (ndarray): (h, w, 2) array of optical flow.
max_val (float): Maximum value of flow, values beyond
... | [
"def",
"quantize_flow",
"(",
"flow",
",",
"max_val",
"=",
"0.02",
",",
"norm",
"=",
"True",
")",
":",
"h",
",",
"w",
",",
"_",
"=",
"flow",
".",
"shape",
"dx",
"=",
"flow",
"[",
"...",
",",
"0",
"]",
"dy",
"=",
"flow",
"[",
"...",
",",
"1",
... | Quantize flow to [0, 255].
After this step, the size of flow will be much smaller, and can be
dumped as jpeg images.
Args:
flow (ndarray): (h, w, 2) array of optical flow.
max_val (float): Maximum value of flow, values beyond
[-max_val, max_val] will be truncated.
... | [
"Quantize",
"flow",
"to",
"[",
"0",
"255",
"]",
"."
] | python | test |
watson-developer-cloud/python-sdk | ibm_watson/language_translator_v3.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/language_translator_v3.py#L626-L633 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'language') and self.language is not None:
_dict['language'] = self.language
if hasattr(self, 'confidence') and self.confidence is not None:
_dict['confidence']... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'language'",
")",
"and",
"self",
".",
"language",
"is",
"not",
"None",
":",
"_dict",
"[",
"'language'",
"]",
"=",
"self",
".",
"language",
"if",
"... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
ansible/tower-cli | tower_cli/cli/base.py | https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/base.py#L60-L69 | def format_commands(self, ctx, formatter):
"""Extra format methods for multi methods that adds all the commands
after the options.
"""
self.format_command_subsection(
ctx, formatter, self.list_misc_commands(), 'Commands'
)
self.format_command_subsection(
... | [
"def",
"format_commands",
"(",
"self",
",",
"ctx",
",",
"formatter",
")",
":",
"self",
".",
"format_command_subsection",
"(",
"ctx",
",",
"formatter",
",",
"self",
".",
"list_misc_commands",
"(",
")",
",",
"'Commands'",
")",
"self",
".",
"format_command_subsec... | Extra format methods for multi methods that adds all the commands
after the options. | [
"Extra",
"format",
"methods",
"for",
"multi",
"methods",
"that",
"adds",
"all",
"the",
"commands",
"after",
"the",
"options",
"."
] | python | valid |
balloob/pychromecast | pychromecast/controllers/media.py | https://github.com/balloob/pychromecast/blob/831b09c4fed185a7bffe0ea330b7849d5f4e36b6/pychromecast/controllers/media.py#L459-L471 | def _process_media_status(self, data):
""" Processes a STATUS message. """
self.status.update(data)
self.logger.debug("Media:Received status %s", data)
# Update session active threading event
if self.status.media_session_id is None:
self.session_active_event.clear()... | [
"def",
"_process_media_status",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"status",
".",
"update",
"(",
"data",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Media:Received status %s\"",
",",
"data",
")",
"# Update session active threading event",
"if... | Processes a STATUS message. | [
"Processes",
"a",
"STATUS",
"message",
"."
] | python | train |
AnalogJ/lexicon | lexicon/providers/hetzner.py | https://github.com/AnalogJ/lexicon/blob/9330b871988753cad44fe2876a217b4c67b1fa0e/lexicon/providers/hetzner.py#L677-L696 | def _get_zone(self, domain, domain_id):
"""
Pulls the zone for the current domain from authenticated Hetzner account and
returns it as an zone object.
"""
api = self.api[self.account]
for request in api['zone']['GET']:
url = (request.copy()).get('url', '/').re... | [
"def",
"_get_zone",
"(",
"self",
",",
"domain",
",",
"domain_id",
")",
":",
"api",
"=",
"self",
".",
"api",
"[",
"self",
".",
"account",
"]",
"for",
"request",
"in",
"api",
"[",
"'zone'",
"]",
"[",
"'GET'",
"]",
":",
"url",
"=",
"(",
"request",
"... | Pulls the zone for the current domain from authenticated Hetzner account and
returns it as an zone object. | [
"Pulls",
"the",
"zone",
"for",
"the",
"current",
"domain",
"from",
"authenticated",
"Hetzner",
"account",
"and",
"returns",
"it",
"as",
"an",
"zone",
"object",
"."
] | python | train |
tensorlayer/tensorlayer | tensorlayer/rein.py | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/rein.py#L65-L98 | def cross_entropy_reward_loss(logits, actions, rewards, name=None):
"""Calculate the loss for Policy Gradient Network.
Parameters
----------
logits : tensor
The network outputs without softmax. This function implements softmax inside.
actions : tensor or placeholder
The agent action... | [
"def",
"cross_entropy_reward_loss",
"(",
"logits",
",",
"actions",
",",
"rewards",
",",
"name",
"=",
"None",
")",
":",
"cross_entropy",
"=",
"tf",
".",
"nn",
".",
"sparse_softmax_cross_entropy_with_logits",
"(",
"labels",
"=",
"actions",
",",
"logits",
"=",
"l... | Calculate the loss for Policy Gradient Network.
Parameters
----------
logits : tensor
The network outputs without softmax. This function implements softmax inside.
actions : tensor or placeholder
The agent actions.
rewards : tensor or placeholder
The rewards.
Returns
... | [
"Calculate",
"the",
"loss",
"for",
"Policy",
"Gradient",
"Network",
"."
] | python | valid |
lpantano/seqcluster | seqcluster/install.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/install.py#L115-L141 | def _install_data(data_dir, path_flavor, args):
"""Upgrade required genome data files in place.
"""
try:
from bcbio import install as bcb
except:
raise ImportError("It needs bcbio to do the quick installation.")
bio_data = op.join(path_flavor, "../biodata.yaml")
s = {"flavor": pa... | [
"def",
"_install_data",
"(",
"data_dir",
",",
"path_flavor",
",",
"args",
")",
":",
"try",
":",
"from",
"bcbio",
"import",
"install",
"as",
"bcb",
"except",
":",
"raise",
"ImportError",
"(",
"\"It needs bcbio to do the quick installation.\"",
")",
"bio_data",
"=",... | Upgrade required genome data files in place. | [
"Upgrade",
"required",
"genome",
"data",
"files",
"in",
"place",
"."
] | python | train |
IRC-SPHERE/HyperStream | hyperstream/tool/base_tool.py | https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/tool/base_tool.py#L98-L128 | def parameters(self):
"""
Get the tool parameters
:return: The tool parameters along with additional information (whether they are functions or sets)
"""
parameters = []
for k, v in self.__dict__.items():
if k.startswith("_"):
continue
... | [
"def",
"parameters",
"(",
"self",
")",
":",
"parameters",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"k",
".",
"startswith",
"(",
"\"_\"",
")",
":",
"continue",
"is_function",
"=",
"False"... | Get the tool parameters
:return: The tool parameters along with additional information (whether they are functions or sets) | [
"Get",
"the",
"tool",
"parameters"
] | python | train |
IBMStreams/pypi.streamsx | streamsx/topology/context.py | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/context.py#L409-L414 | def _get_java_env(self):
"Pass the VCAP through the environment to the java submission"
env = super(_StreamingAnalyticsSubmitter, self)._get_java_env()
vcap = streamsx.rest._get_vcap_services(self._vcap_services)
env['VCAP_SERVICES'] = json.dumps(vcap)
return env | [
"def",
"_get_java_env",
"(",
"self",
")",
":",
"env",
"=",
"super",
"(",
"_StreamingAnalyticsSubmitter",
",",
"self",
")",
".",
"_get_java_env",
"(",
")",
"vcap",
"=",
"streamsx",
".",
"rest",
".",
"_get_vcap_services",
"(",
"self",
".",
"_vcap_services",
")... | Pass the VCAP through the environment to the java submission | [
"Pass",
"the",
"VCAP",
"through",
"the",
"environment",
"to",
"the",
"java",
"submission"
] | python | train |
ontio/ontology-python-sdk | ontology/io/binary_writer.py | https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_writer.py#L370-L382 | def write_hashes(self, arr):
"""
Write an array of hashes to the stream.
Args:
arr (list): a list of 32 byte hashes.
"""
length = len(arr)
self.write_var_int(length)
for item in arr:
ba = bytearray(binascii.unhexlify(item))
ba.... | [
"def",
"write_hashes",
"(",
"self",
",",
"arr",
")",
":",
"length",
"=",
"len",
"(",
"arr",
")",
"self",
".",
"write_var_int",
"(",
"length",
")",
"for",
"item",
"in",
"arr",
":",
"ba",
"=",
"bytearray",
"(",
"binascii",
".",
"unhexlify",
"(",
"item"... | Write an array of hashes to the stream.
Args:
arr (list): a list of 32 byte hashes. | [
"Write",
"an",
"array",
"of",
"hashes",
"to",
"the",
"stream",
"."
] | python | train |
ARMmbed/icetea | icetea_lib/CliResponse.py | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/CliResponse.py#L90-L110 | def verify_trace(self, expected_traces, break_in_fail=True):
"""
Verifies that expectedResponse is found in self.traces
:param expected_traces: response or responses to look for. Must be list or str.
:param break_in_fail: If set to True, re-raises exceptions caught or if message was
... | [
"def",
"verify_trace",
"(",
"self",
",",
"expected_traces",
",",
"break_in_fail",
"=",
"True",
")",
":",
"ok",
"=",
"True",
"try",
":",
"ok",
"=",
"verify_message",
"(",
"self",
".",
"traces",
",",
"expected_traces",
")",
"except",
"(",
"TypeError",
",",
... | Verifies that expectedResponse is found in self.traces
:param expected_traces: response or responses to look for. Must be list or str.
:param break_in_fail: If set to True, re-raises exceptions caught or if message was
not found
:return: True or False
:raises: LookupError if mes... | [
"Verifies",
"that",
"expectedResponse",
"is",
"found",
"in",
"self",
".",
"traces"
] | python | train |
iotile/coretools | iotile_ext_cloud/iotile/cloud/apps/ota_updater.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotile_ext_cloud/iotile/cloud/apps/ota_updater.py#L27-L36 | def _download_ota_script(script_url):
"""Download the script from the cloud service and store to temporary file location"""
try:
blob = requests.get(script_url, stream=True)
return blob.content
except Exception as e:
iprint("Failed to download OTA script")
iprint(e)
... | [
"def",
"_download_ota_script",
"(",
"script_url",
")",
":",
"try",
":",
"blob",
"=",
"requests",
".",
"get",
"(",
"script_url",
",",
"stream",
"=",
"True",
")",
"return",
"blob",
".",
"content",
"except",
"Exception",
"as",
"e",
":",
"iprint",
"(",
"\"Fa... | Download the script from the cloud service and store to temporary file location | [
"Download",
"the",
"script",
"from",
"the",
"cloud",
"service",
"and",
"store",
"to",
"temporary",
"file",
"location"
] | python | train |
openmicroanalysis/pyxray | pyxray/composition.py | https://github.com/openmicroanalysis/pyxray/blob/cae89677f00ebcc0952f94d1ab70e6b35e1a51e9/pyxray/composition.py#L92-L120 | def convert_formula_to_atomic_fractions(formula):
"""
Converts a chemical formula to an atomic fraction :class:`dict`.
Args:
formula (str): chemical formula, like Al2O3. No wildcard are accepted.
"""
mole_fractions = {}
total_mole_fraction = 0.0
for match in CHEMICAL_FORMULA_PATTER... | [
"def",
"convert_formula_to_atomic_fractions",
"(",
"formula",
")",
":",
"mole_fractions",
"=",
"{",
"}",
"total_mole_fraction",
"=",
"0.0",
"for",
"match",
"in",
"CHEMICAL_FORMULA_PATTERN",
".",
"finditer",
"(",
"formula",
")",
":",
"symbol",
",",
"mole_fraction",
... | Converts a chemical formula to an atomic fraction :class:`dict`.
Args:
formula (str): chemical formula, like Al2O3. No wildcard are accepted. | [
"Converts",
"a",
"chemical",
"formula",
"to",
"an",
"atomic",
"fraction",
":",
"class",
":",
"dict",
"."
] | python | train |
mwickert/scikit-dsp-comm | sk_dsp_comm/multirate_helper.py | https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/multirate_helper.py#L120-L126 | def dn(self,x,M_change = 12):
"""
Downsample and filter the signal
"""
y = signal.lfilter(self.b,[1],x)
y = ssd.downsample(y,M_change)
return y | [
"def",
"dn",
"(",
"self",
",",
"x",
",",
"M_change",
"=",
"12",
")",
":",
"y",
"=",
"signal",
".",
"lfilter",
"(",
"self",
".",
"b",
",",
"[",
"1",
"]",
",",
"x",
")",
"y",
"=",
"ssd",
".",
"downsample",
"(",
"y",
",",
"M_change",
")",
"ret... | Downsample and filter the signal | [
"Downsample",
"and",
"filter",
"the",
"signal"
] | python | valid |
ronhanson/python-tbx | tbx/text.py | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L48-L57 | def slugify(text, delim='-'):
"""Generates an slightly worse ASCII-only slug."""
punctuation_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+')
result = []
for word in punctuation_re.split(text.lower()):
word = normalize_text(word)
if word:
result.append(word)
... | [
"def",
"slugify",
"(",
"text",
",",
"delim",
"=",
"'-'",
")",
":",
"punctuation_re",
"=",
"re",
".",
"compile",
"(",
"r'[\\t !\"#$%&\\'()*\\-/<=>?@\\[\\\\\\]^_`{|},.:]+'",
")",
"result",
"=",
"[",
"]",
"for",
"word",
"in",
"punctuation_re",
".",
"split",
"(",
... | Generates an slightly worse ASCII-only slug. | [
"Generates",
"an",
"slightly",
"worse",
"ASCII",
"-",
"only",
"slug",
"."
] | python | train |
gwastro/pycbc | pycbc/frame/frame.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/frame/frame.py#L566-L581 | def advance(self, blocksize):
"""Add blocksize seconds more to the buffer, push blocksize seconds
from the beginning.
Parameters
----------
blocksize: int
The number of seconds to attempt to read from the channel
"""
ts = self._read_frame(blocksize)
... | [
"def",
"advance",
"(",
"self",
",",
"blocksize",
")",
":",
"ts",
"=",
"self",
".",
"_read_frame",
"(",
"blocksize",
")",
"self",
".",
"raw_buffer",
".",
"roll",
"(",
"-",
"len",
"(",
"ts",
")",
")",
"self",
".",
"raw_buffer",
"[",
"-",
"len",
"(",
... | Add blocksize seconds more to the buffer, push blocksize seconds
from the beginning.
Parameters
----------
blocksize: int
The number of seconds to attempt to read from the channel | [
"Add",
"blocksize",
"seconds",
"more",
"to",
"the",
"buffer",
"push",
"blocksize",
"seconds",
"from",
"the",
"beginning",
"."
] | python | train |
iwanbk/nyamuk | nyamuk/mqtt_pkt.py | https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/mqtt_pkt.py#L218-L236 | def read_string(self):
"""Read string."""
rc, length = self.read_uint16()
if rc != NC.ERR_SUCCESS:
return rc, None
if self.pos + length > self.remaining_length:
return NC.ERR_PROTOCOL, None
ba = bytearray(length)
if ba is... | [
"def",
"read_string",
"(",
"self",
")",
":",
"rc",
",",
"length",
"=",
"self",
".",
"read_uint16",
"(",
")",
"if",
"rc",
"!=",
"NC",
".",
"ERR_SUCCESS",
":",
"return",
"rc",
",",
"None",
"if",
"self",
".",
"pos",
"+",
"length",
">",
"self",
".",
... | Read string. | [
"Read",
"string",
"."
] | python | train |
rraadd88/rohan | rohan/dandage/io_strs.py | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_strs.py#L120-L127 | def make_pathable_string(s,replacewith='_'):
"""
Removes symbols from a string to be compatible with directory structure.
:param s: string
"""
import re
return re.sub(r'[^\w+/.]',replacewith, s.lower()) | [
"def",
"make_pathable_string",
"(",
"s",
",",
"replacewith",
"=",
"'_'",
")",
":",
"import",
"re",
"return",
"re",
".",
"sub",
"(",
"r'[^\\w+/.]'",
",",
"replacewith",
",",
"s",
".",
"lower",
"(",
")",
")"
] | Removes symbols from a string to be compatible with directory structure.
:param s: string | [
"Removes",
"symbols",
"from",
"a",
"string",
"to",
"be",
"compatible",
"with",
"directory",
"structure",
"."
] | python | train |
lemieuxl/pyGenClean | pyGenClean/RelatedSamples/merge_related_samples.py | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/RelatedSamples/merge_related_samples.py#L175-L193 | def checkArgs(args):
"""Checks the arguments and options.
:param args: a an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` cl... | [
"def",
"checkArgs",
"(",
"args",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"args",
".",
"ibs_related",
")",
":",
"msg",
"=",
"\"{}: no such file\"",
".",
"format",
"(",
"args",
".",
"ibs_related",
")",
"raise",
"ProgramError",
"(",
... | Checks the arguments and options.
:param args: a an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` class, a message is printed to... | [
"Checks",
"the",
"arguments",
"and",
"options",
"."
] | python | train |
blockstack/blockstack-core | blockstack/blockstackd.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L271-L356 | def do_POST(self):
"""
Based on the original, available at https://github.com/python/cpython/blob/2.7/Lib/SimpleXMLRPCServer.py
Only difference is that it denies requests bigger than a certain size.
Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as ... | [
"def",
"do_POST",
"(",
"self",
")",
":",
"# Check that the path is legal",
"if",
"not",
"self",
".",
"is_rpc_path_valid",
"(",
")",
":",
"self",
".",
"report_404",
"(",
")",
"return",
"# reject gzip, so size-caps will work",
"encoding",
"=",
"self",
".",
"headers"... | Based on the original, available at https://github.com/python/cpython/blob/2.7/Lib/SimpleXMLRPCServer.py
Only difference is that it denies requests bigger than a certain size.
Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwar... | [
"Based",
"on",
"the",
"original",
"available",
"at",
"https",
":",
"//",
"github",
".",
"com",
"/",
"python",
"/",
"cpython",
"/",
"blob",
"/",
"2",
".",
"7",
"/",
"Lib",
"/",
"SimpleXMLRPCServer",
".",
"py"
] | python | train |
MacHu-GWU/angora-project | angora/gadget/backup.py | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/backup.py#L75-L117 | def run_backup(filename, root_dir, ignore=[], ignore_ext=[], ignore_pattern=[]):
"""The backup utility method.
:param root_dir: the directory you want to backup
:param ignore: file or directory defined in this list will be ignored.
:param ignore_ext: file with extensions defined in this list will be ig... | [
"def",
"run_backup",
"(",
"filename",
",",
"root_dir",
",",
"ignore",
"=",
"[",
"]",
",",
"ignore_ext",
"=",
"[",
"]",
",",
"ignore_pattern",
"=",
"[",
"]",
")",
":",
"tab",
"=",
"\" \"",
"# Step 1, calculate files to backup",
"print",
"(",
"\"Perform backu... | The backup utility method.
:param root_dir: the directory you want to backup
:param ignore: file or directory defined in this list will be ignored.
:param ignore_ext: file with extensions defined in this list will be ignored.
:param ignore_pattern: any file or directory that contains this pattern
... | [
"The",
"backup",
"utility",
"method",
"."
] | python | train |
gmr/rejected | rejected/process.py | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L368-L433 | def on_processed(self, message, result, start_time):
"""Invoked after a message is processed by the consumer and
implements the logic for how to deal with a message based upon
the result.
:param rejected.data.Message message: The message that was processed
:param int result: The... | [
"def",
"on_processed",
"(",
"self",
",",
"message",
",",
"result",
",",
"start_time",
")",
":",
"duration",
"=",
"max",
"(",
"start_time",
",",
"time",
".",
"time",
"(",
")",
")",
"-",
"start_time",
"self",
".",
"counters",
"[",
"self",
".",
"TIME_SPEN... | Invoked after a message is processed by the consumer and
implements the logic for how to deal with a message based upon
the result.
:param rejected.data.Message message: The message that was processed
:param int result: The result of the processing of the message
:param float st... | [
"Invoked",
"after",
"a",
"message",
"is",
"processed",
"by",
"the",
"consumer",
"and",
"implements",
"the",
"logic",
"for",
"how",
"to",
"deal",
"with",
"a",
"message",
"based",
"upon",
"the",
"result",
"."
] | python | train |
laplacesdemon/django-youtube | django_youtube/views.py | https://github.com/laplacesdemon/django-youtube/blob/8051ef372473eccb053f773c68e2e5e1b2cfb538/django_youtube/views.py#L51-L90 | def video(request, video_id):
"""
Displays a video in an embed player
"""
# Check video availability
# Available states are: processing
api = Api()
api.authenticate()
availability = api.check_upload_status(video_id)
if availability is not True:
# Video is not available
... | [
"def",
"video",
"(",
"request",
",",
"video_id",
")",
":",
"# Check video availability",
"# Available states are: processing",
"api",
"=",
"Api",
"(",
")",
"api",
".",
"authenticate",
"(",
")",
"availability",
"=",
"api",
".",
"check_upload_status",
"(",
"video_id... | Displays a video in an embed player | [
"Displays",
"a",
"video",
"in",
"an",
"embed",
"player"
] | python | test |
jhermann/rudiments | src/rudiments/security.py | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/security.py#L56-L60 | def auth_pair(self, force_console=False):
"""Return username/password tuple, possibly prompting the user for them."""
if not self.auth_valid():
self._get_auth(force_console)
return (self.user, self.password) | [
"def",
"auth_pair",
"(",
"self",
",",
"force_console",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"auth_valid",
"(",
")",
":",
"self",
".",
"_get_auth",
"(",
"force_console",
")",
"return",
"(",
"self",
".",
"user",
",",
"self",
".",
"password",... | Return username/password tuple, possibly prompting the user for them. | [
"Return",
"username",
"/",
"password",
"tuple",
"possibly",
"prompting",
"the",
"user",
"for",
"them",
"."
] | python | train |
hayalasalah/adhan.py | adhan/calculations.py | https://github.com/hayalasalah/adhan.py/blob/a7c080ba48f70be9801f048451d2c91a7d579602/adhan/calculations.py#L170-L195 | def compute_time_at_sun_angle(day, latitude, angle):
"""Compute the floating point time difference between mid-day and an angle.
All the prayers are defined as certain angles from mid-day (Zuhr).
This formula is taken from praytimes.org/calculation
:param day: The day to which to compute for
:para... | [
"def",
"compute_time_at_sun_angle",
"(",
"day",
",",
"latitude",
",",
"angle",
")",
":",
"positive_angle_rad",
"=",
"radians",
"(",
"abs",
"(",
"angle",
")",
")",
"angle_sign",
"=",
"abs",
"(",
"angle",
")",
"/",
"angle",
"latitude_rad",
"=",
"radians",
"(... | Compute the floating point time difference between mid-day and an angle.
All the prayers are defined as certain angles from mid-day (Zuhr).
This formula is taken from praytimes.org/calculation
:param day: The day to which to compute for
:param longitude: Longitude of the place of interest
:angle: ... | [
"Compute",
"the",
"floating",
"point",
"time",
"difference",
"between",
"mid",
"-",
"day",
"and",
"an",
"angle",
"."
] | python | train |
bwohlberg/sporco | sporco/admm/bpdn.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/bpdn.py#L1092-L1098 | def setdict(self, D):
"""Set dictionary array."""
self.D = np.asarray(D, dtype=self.dtype)
# Factorise dictionary for efficient solves
self.lu, self.piv = sl.cho_factor(self.D, 1.0)
self.lu = np.asarray(self.lu, dtype=self.dtype) | [
"def",
"setdict",
"(",
"self",
",",
"D",
")",
":",
"self",
".",
"D",
"=",
"np",
".",
"asarray",
"(",
"D",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"# Factorise dictionary for efficient solves",
"self",
".",
"lu",
",",
"self",
".",
"piv",
"=",
"s... | Set dictionary array. | [
"Set",
"dictionary",
"array",
"."
] | python | train |
DataBiosphere/toil | src/toil/provisioners/aws/awsProvisioner.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/provisioners/aws/awsProvisioner.py#L394-L406 | def _waitForIP(cls, instance):
"""
Wait until the instances has a public IP address assigned to it.
:type instance: boto.ec2.instance.Instance
"""
logger.debug('Waiting for ip...')
while True:
time.sleep(a_short_time)
instance.update()
... | [
"def",
"_waitForIP",
"(",
"cls",
",",
"instance",
")",
":",
"logger",
".",
"debug",
"(",
"'Waiting for ip...'",
")",
"while",
"True",
":",
"time",
".",
"sleep",
"(",
"a_short_time",
")",
"instance",
".",
"update",
"(",
")",
"if",
"instance",
".",
"ip_add... | Wait until the instances has a public IP address assigned to it.
:type instance: boto.ec2.instance.Instance | [
"Wait",
"until",
"the",
"instances",
"has",
"a",
"public",
"IP",
"address",
"assigned",
"to",
"it",
"."
] | python | train |
tensorflow/cleverhans | scripts/plot_success_fail_curve.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/plot_success_fail_curve.py#L25-L38 | def main(argv=None):
"""Takes the path to a directory with reports and renders success fail plots."""
report_paths = argv[1:]
fail_names = FLAGS.fail_names.split(',')
for report_path in report_paths:
plot_report_from_path(report_path, label=report_path, fail_names=fail_names)
pyplot.legend()
pyplot.x... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"report_paths",
"=",
"argv",
"[",
"1",
":",
"]",
"fail_names",
"=",
"FLAGS",
".",
"fail_names",
".",
"split",
"(",
"','",
")",
"for",
"report_path",
"in",
"report_paths",
":",
"plot_report_from_path",
"(... | Takes the path to a directory with reports and renders success fail plots. | [
"Takes",
"the",
"path",
"to",
"a",
"directory",
"with",
"reports",
"and",
"renders",
"success",
"fail",
"plots",
"."
] | python | train |
saltstack/salt | salt/modules/saltutil.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L859-L880 | def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
... | [
"def",
"list_extmods",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"ext_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'extmods'",
")",
"mod_types",
"=",
"os",
".",
"listdir",
"(",
"ext_dir",
")",
"for",
"mod_type"... | .. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | python | train |
PaulHancock/Aegean | AegeanTools/fits_image.py | https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/fits_image.py#L235-L254 | def set_pixels(self, pixels):
"""
Set the image data.
Will not work if the new image has a different shape than the current image.
Parameters
----------
pixels : numpy.ndarray
New image data
Returns
-------
None
"""
if... | [
"def",
"set_pixels",
"(",
"self",
",",
"pixels",
")",
":",
"if",
"not",
"(",
"pixels",
".",
"shape",
"==",
"self",
".",
"_pixels",
".",
"shape",
")",
":",
"raise",
"AssertionError",
"(",
"\"Shape mismatch between pixels supplied {0} and existing image pixels {1}\"",... | Set the image data.
Will not work if the new image has a different shape than the current image.
Parameters
----------
pixels : numpy.ndarray
New image data
Returns
-------
None | [
"Set",
"the",
"image",
"data",
".",
"Will",
"not",
"work",
"if",
"the",
"new",
"image",
"has",
"a",
"different",
"shape",
"than",
"the",
"current",
"image",
"."
] | python | train |
pricingassistant/mrq | mrq/job.py | https://github.com/pricingassistant/mrq/blob/d0a5a34de9cba38afa94fb7c9e17f9b570b79a50/mrq/job.py#L585-L602 | def trace_memory_clean_caches(self):
""" Avoid polluting results with some builtin python caches """
urllib.parse.clear_cache()
re.purge()
linecache.clearcache()
copyreg.clear_extension_cache()
if hasattr(fnmatch, "purge"):
fnmatch.purge() # pylint: disable... | [
"def",
"trace_memory_clean_caches",
"(",
"self",
")",
":",
"urllib",
".",
"parse",
".",
"clear_cache",
"(",
")",
"re",
".",
"purge",
"(",
")",
"linecache",
".",
"clearcache",
"(",
")",
"copyreg",
".",
"clear_extension_cache",
"(",
")",
"if",
"hasattr",
"("... | Avoid polluting results with some builtin python caches | [
"Avoid",
"polluting",
"results",
"with",
"some",
"builtin",
"python",
"caches"
] | python | train |
DLR-RM/RAFCON | source/rafcon/gui/controllers/main_window.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/main_window.py#L408-L432 | def focus_notebook_page_of_controller(self, controller):
"""Puts the focus on the given child controller
The method implements focus request of the notebooks in left side-bar of the main window. Thereby it is the
master-function of focus pattern of the notebooks in left side-bar.
Actua... | [
"def",
"focus_notebook_page_of_controller",
"(",
"self",
",",
"controller",
")",
":",
"# TODO think about to may substitute Controller- by View-objects it is may the better design",
"if",
"controller",
"not",
"in",
"self",
".",
"get_child_controllers",
"(",
")",
":",
"return",
... | Puts the focus on the given child controller
The method implements focus request of the notebooks in left side-bar of the main window. Thereby it is the
master-function of focus pattern of the notebooks in left side-bar.
Actual pattern is:
* Execution-History is put to focus any time r... | [
"Puts",
"the",
"focus",
"on",
"the",
"given",
"child",
"controller"
] | python | train |
apache/airflow | scripts/perf/scheduler_ops_metrics.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/scripts/perf/scheduler_ops_metrics.py#L65-L101 | def print_stats(self):
"""
Print operational metrics for the scheduler test.
"""
session = settings.Session()
TI = TaskInstance
tis = (
session
.query(TI)
.filter(TI.dag_id.in_(DAG_IDS))
.all()
)
successful_t... | [
"def",
"print_stats",
"(",
"self",
")",
":",
"session",
"=",
"settings",
".",
"Session",
"(",
")",
"TI",
"=",
"TaskInstance",
"tis",
"=",
"(",
"session",
".",
"query",
"(",
"TI",
")",
".",
"filter",
"(",
"TI",
".",
"dag_id",
".",
"in_",
"(",
"DAG_I... | Print operational metrics for the scheduler test. | [
"Print",
"operational",
"metrics",
"for",
"the",
"scheduler",
"test",
"."
] | python | test |
qba73/circleclient | circleclient/circleclient.py | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L46-L55 | def client_post(self, url, **kwargs):
"""Send POST request with given url and keyword args."""
response = requests.post(self.make_url(url),
data=json.dumps(kwargs),
headers=self.headers)
if not response.ok:
raise Excep... | [
"def",
"client_post",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"make_url",
"(",
"url",
")",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"kwargs",
")",
",",
"headers",
... | Send POST request with given url and keyword args. | [
"Send",
"POST",
"request",
"with",
"given",
"url",
"and",
"keyword",
"args",
"."
] | python | train |
romanz/trezor-agent | libagent/ssh/__init__.py | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L206-L211 | def public_keys(self):
"""Return a list of SSH public keys (in textual format)."""
if not self.public_keys_cache:
conn = self.conn_factory()
self.public_keys_cache = conn.export_public_keys(self.identities)
return self.public_keys_cache | [
"def",
"public_keys",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"public_keys_cache",
":",
"conn",
"=",
"self",
".",
"conn_factory",
"(",
")",
"self",
".",
"public_keys_cache",
"=",
"conn",
".",
"export_public_keys",
"(",
"self",
".",
"identities",
"... | Return a list of SSH public keys (in textual format). | [
"Return",
"a",
"list",
"of",
"SSH",
"public",
"keys",
"(",
"in",
"textual",
"format",
")",
"."
] | python | train |
globocom/globomap-loader-api-client | globomap_loader_api_client/update.py | https://github.com/globocom/globomap-loader-api-client/blob/b12347ca77d245de1abd604d1b694162156570e6/globomap_loader_api_client/update.py#L40-L54 | def get(self, key):
"""Return the status from a job.
:param key: id of job
:type document: dict or list
:return: message with location of job
:rtype: dict
:raises Unauthorized: if API returns status 401
:raises Forbidden: if API returns status 403
:raises... | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"uri",
"=",
"'updates/job/{}'",
".",
"format",
"(",
"key",
")",
"return",
"self",
".",
"make_request",
"(",
"method",
"=",
"'GET'",
",",
"uri",
"=",
"uri",
")"
] | Return the status from a job.
:param key: id of job
:type document: dict or list
:return: message with location of job
:rtype: dict
:raises Unauthorized: if API returns status 401
:raises Forbidden: if API returns status 403
:raises NotFound: if API returns statu... | [
"Return",
"the",
"status",
"from",
"a",
"job",
"."
] | python | train |
caffeinehit/django-oauth2-provider | provider/oauth2/models.py | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/oauth2/models.py#L149-L166 | def get_expire_delta(self, reference=None):
"""
Return the number of seconds until this token expires.
"""
if reference is None:
reference = now()
expiration = self.expires
if timezone:
if timezone.is_aware(reference) and timezone.is_naive(expirat... | [
"def",
"get_expire_delta",
"(",
"self",
",",
"reference",
"=",
"None",
")",
":",
"if",
"reference",
"is",
"None",
":",
"reference",
"=",
"now",
"(",
")",
"expiration",
"=",
"self",
".",
"expires",
"if",
"timezone",
":",
"if",
"timezone",
".",
"is_aware",... | Return the number of seconds until this token expires. | [
"Return",
"the",
"number",
"of",
"seconds",
"until",
"this",
"token",
"expires",
"."
] | python | train |
blockstack/blockstack-core | blockstack/lib/subdomains.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L224-L232 | def serialize_to_txt(self):
"""
Serialize this subdomain record to a TXT record. The trailing newline will be omitted
"""
txtrec = {
'name': self.fqn if self.independent else self.subdomain,
'txt': self.pack_subdomain()[1:]
}
return blockstack_zon... | [
"def",
"serialize_to_txt",
"(",
"self",
")",
":",
"txtrec",
"=",
"{",
"'name'",
":",
"self",
".",
"fqn",
"if",
"self",
".",
"independent",
"else",
"self",
".",
"subdomain",
",",
"'txt'",
":",
"self",
".",
"pack_subdomain",
"(",
")",
"[",
"1",
":",
"]... | Serialize this subdomain record to a TXT record. The trailing newline will be omitted | [
"Serialize",
"this",
"subdomain",
"record",
"to",
"a",
"TXT",
"record",
".",
"The",
"trailing",
"newline",
"will",
"be",
"omitted"
] | python | train |
Cog-Creators/Red-Lavalink | lavalink/node.py | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/node.py#L335-L368 | def get_node(guild_id: int, ignore_ready_status: bool = False) -> Node:
"""
Gets a node based on a guild ID, useful for noding separation. If the
guild ID does not already have a node association, the least used
node is returned. Skips over nodes that are not yet ready.
Parameters
----------
... | [
"def",
"get_node",
"(",
"guild_id",
":",
"int",
",",
"ignore_ready_status",
":",
"bool",
"=",
"False",
")",
"->",
"Node",
":",
"guild_count",
"=",
"1e10",
"least_used",
"=",
"None",
"for",
"node",
"in",
"_nodes",
":",
"guild_ids",
"=",
"node",
".",
"play... | Gets a node based on a guild ID, useful for noding separation. If the
guild ID does not already have a node association, the least used
node is returned. Skips over nodes that are not yet ready.
Parameters
----------
guild_id : int
ignore_ready_status : bool
Returns
-------
Node | [
"Gets",
"a",
"node",
"based",
"on",
"a",
"guild",
"ID",
"useful",
"for",
"noding",
"separation",
".",
"If",
"the",
"guild",
"ID",
"does",
"not",
"already",
"have",
"a",
"node",
"association",
"the",
"least",
"used",
"node",
"is",
"returned",
".",
"Skips"... | python | train |
llazzaro/analyzerstrategies | analyzerstrategies/sma_portfolio_strategy.py | https://github.com/llazzaro/analyzerstrategies/blob/3c647802f582bf2f06c6793f282bee0d26514cd6/analyzerstrategies/sma_portfolio_strategy.py#L131-L150 | def __placeSellShortOrder(self, tick):
''' place short sell order'''
share=math.floor(self.__strategy.getAccountCopy().getCash() / float(tick.close))
sellShortOrder=Order(accountId=self.__strategy.accountId,
action=Action.SELL_SHORT,
... | [
"def",
"__placeSellShortOrder",
"(",
"self",
",",
"tick",
")",
":",
"share",
"=",
"math",
".",
"floor",
"(",
"self",
".",
"__strategy",
".",
"getAccountCopy",
"(",
")",
".",
"getCash",
"(",
")",
"/",
"float",
"(",
"tick",
".",
"close",
")",
")",
"sel... | place short sell order | [
"place",
"short",
"sell",
"order"
] | python | train |
dsoprea/NsqSpinner | nsq/connection.py | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/connection.py#L78-L84 | def flush(self):
"""Return all buffered data, and clear the stack."""
(slice_, self.__buffer) = (self.__buffer, '')
self.__size = 0
return slice_ | [
"def",
"flush",
"(",
"self",
")",
":",
"(",
"slice_",
",",
"self",
".",
"__buffer",
")",
"=",
"(",
"self",
".",
"__buffer",
",",
"''",
")",
"self",
".",
"__size",
"=",
"0",
"return",
"slice_"
] | Return all buffered data, and clear the stack. | [
"Return",
"all",
"buffered",
"data",
"and",
"clear",
"the",
"stack",
"."
] | python | train |
soravux/scoop | scoop/backports/runpy.py | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/backports/runpy.py#L165-L181 | def run_module(mod_name, init_globals=None,
run_name=None, alter_sys=False):
"""Execute a module's code without importing it
Returns the resulting top level namespace dictionary
"""
mod_name, loader, code, fname = _get_module_details(mod_name)
if run_name is None:
run_name... | [
"def",
"run_module",
"(",
"mod_name",
",",
"init_globals",
"=",
"None",
",",
"run_name",
"=",
"None",
",",
"alter_sys",
"=",
"False",
")",
":",
"mod_name",
",",
"loader",
",",
"code",
",",
"fname",
"=",
"_get_module_details",
"(",
"mod_name",
")",
"if",
... | Execute a module's code without importing it
Returns the resulting top level namespace dictionary | [
"Execute",
"a",
"module",
"s",
"code",
"without",
"importing",
"it"
] | python | train |
cirruscluster/cirruscluster | cirruscluster/cluster/mapr.py | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/mapr.py#L1033-L1043 | def __CleanUpRootPartition(self):
"""
Mapr signals an alarm in the web ui when there are files in a nodes
/opt/cores dir. This is anoying because we can't see if there is a real
problem with the node because of this pointless error message.
This removes those files so the alarm goes away.
... | [
"def",
"__CleanUpRootPartition",
"(",
"self",
")",
":",
"instances",
"=",
"self",
".",
"__GetAllInstances",
"(",
")",
"clean_cores_cmd",
"=",
"\"\"\"sudo sh -c 'rm -rf /opt/mapr/cache/tmp/*'\"\"\"",
"self",
".",
"__RunCommandOnInstances",
"(",
"clean_cores_cmd",
",",
"ins... | Mapr signals an alarm in the web ui when there are files in a nodes
/opt/cores dir. This is anoying because we can't see if there is a real
problem with the node because of this pointless error message.
This removes those files so the alarm goes away. | [
"Mapr",
"signals",
"an",
"alarm",
"in",
"the",
"web",
"ui",
"when",
"there",
"are",
"files",
"in",
"a",
"nodes",
"/",
"opt",
"/",
"cores",
"dir",
".",
"This",
"is",
"anoying",
"because",
"we",
"can",
"t",
"see",
"if",
"there",
"is",
"a",
"real",
"p... | python | train |
pytroll/satpy | satpy/readers/fci_l1c_fdhsi.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/readers/fci_l1c_fdhsi.py#L223-L234 | def _vis_calibrate(self, data, key):
"""VIS channel calibration."""
# radiance to reflectance taken as in mipp/xrit/MSG.py
# again FCI User Guide is not clear on how to do this
sirr = self.nc[
'/data/{}/measured/channel_effective_solar_irradiance'
.format(key.nam... | [
"def",
"_vis_calibrate",
"(",
"self",
",",
"data",
",",
"key",
")",
":",
"# radiance to reflectance taken as in mipp/xrit/MSG.py",
"# again FCI User Guide is not clear on how to do this",
"sirr",
"=",
"self",
".",
"nc",
"[",
"'/data/{}/measured/channel_effective_solar_irradiance'... | VIS channel calibration. | [
"VIS",
"channel",
"calibration",
"."
] | python | train |
Gorialis/jishaku | jishaku/repl/compilation.py | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/repl/compilation.py#L49-L106 | def wrap_code(code: str, args: str = '') -> ast.Module:
"""
Compiles Python code into an async function or generator,
and automatically adds return if the function body is a single evaluation.
Also adds inline import expression support.
"""
if sys.version_info >= (3, 7):
user_code = imp... | [
"def",
"wrap_code",
"(",
"code",
":",
"str",
",",
"args",
":",
"str",
"=",
"''",
")",
"->",
"ast",
".",
"Module",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"7",
")",
":",
"user_code",
"=",
"import_expression",
".",
"parse",
"(",
... | Compiles Python code into an async function or generator,
and automatically adds return if the function body is a single evaluation.
Also adds inline import expression support. | [
"Compiles",
"Python",
"code",
"into",
"an",
"async",
"function",
"or",
"generator",
"and",
"automatically",
"adds",
"return",
"if",
"the",
"function",
"body",
"is",
"a",
"single",
"evaluation",
".",
"Also",
"adds",
"inline",
"import",
"expression",
"support",
... | python | train |
Richienb/quilt | src/quilt_lang/__init__.py | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L584-L603 | def reversetext(contenttoreverse, reconvert=True):
"""
Reverse any content
:type contenttoreverse: string
:param contenttoreverse: The content to be reversed
:type reeval: boolean
:param reeval: Wether or not to reconvert the object back into it's initial state. Default is "True".
"""
... | [
"def",
"reversetext",
"(",
"contenttoreverse",
",",
"reconvert",
"=",
"True",
")",
":",
"# If reconvert is specified",
"if",
"reconvert",
"is",
"True",
":",
"# Return the evalated form",
"return",
"eval",
"(",
"str",
"(",
"type",
"(",
"contenttoreverse",
")",
")",... | Reverse any content
:type contenttoreverse: string
:param contenttoreverse: The content to be reversed
:type reeval: boolean
:param reeval: Wether or not to reconvert the object back into it's initial state. Default is "True". | [
"Reverse",
"any",
"content"
] | python | train |
datascopeanalytics/traces | traces/timeseries.py | https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L244-L250 | def exists(self):
"""returns False when the timeseries has a None value,
True otherwise"""
result = TimeSeries(default=False if self.default is None else True)
for t, v in self:
result[t] = False if v is None else True
return result | [
"def",
"exists",
"(",
"self",
")",
":",
"result",
"=",
"TimeSeries",
"(",
"default",
"=",
"False",
"if",
"self",
".",
"default",
"is",
"None",
"else",
"True",
")",
"for",
"t",
",",
"v",
"in",
"self",
":",
"result",
"[",
"t",
"]",
"=",
"False",
"i... | returns False when the timeseries has a None value,
True otherwise | [
"returns",
"False",
"when",
"the",
"timeseries",
"has",
"a",
"None",
"value",
"True",
"otherwise"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.