text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _image_to_data(img):
"""
Does the work of encoding an image into Base64
"""
# If the image is already encoded in Base64, we have nothing to do here
if "src" not in img.attrs or img["src"].startswith("data:"):
return
elif re.match("https?://", img["src"]):
img_data = _load_url... | [
"def",
"_image_to_data",
"(",
"img",
")",
":",
"# If the image is already encoded in Base64, we have nothing to do here",
"if",
"\"src\"",
"not",
"in",
"img",
".",
"attrs",
"or",
"img",
"[",
"\"src\"",
"]",
".",
"startswith",
"(",
"\"data:\"",
")",
":",
"return",
... | 36.411765 | 0.001575 |
def gtom(adj, nr_steps):
'''
The m-th step generalized topological overlap measure (GTOM) quantifies
the extent to which a pair of nodes have similar m-th step neighbors.
Mth-step neighbors are nodes that are reachable by a path of at most
length m.
This function computes the the M x M generali... | [
"def",
"gtom",
"(",
"adj",
",",
"nr_steps",
")",
":",
"bm",
"=",
"binarize",
"(",
"adj",
",",
"copy",
"=",
"True",
")",
"bm_aux",
"=",
"bm",
".",
"copy",
"(",
")",
"nr_nodes",
"=",
"len",
"(",
"adj",
")",
"if",
"nr_steps",
">",
"nr_nodes",
":",
... | 34.741935 | 0.000451 |
def sync(self, vault_client):
"""Update remove Vault resource contents if needed"""
if self.present and not self.existing:
LOG.info("Writing new %s to %s",
self.secret_format, self)
self.write(vault_client)
elif self.present and self.existing:
... | [
"def",
"sync",
"(",
"self",
",",
"vault_client",
")",
":",
"if",
"self",
".",
"present",
"and",
"not",
"self",
".",
"existing",
":",
"LOG",
".",
"info",
"(",
"\"Writing new %s to %s\"",
",",
"self",
".",
"secret_format",
",",
"self",
")",
"self",
".",
... | 45.888889 | 0.002372 |
def _get_envs_from_ref_paths(self, refs):
'''
Return the names of remote refs (stripped of the remote name) and tags
which are map to the branches and tags.
'''
def _check_ref(env_set, rname):
'''
Add the appropriate saltenv(s) to the set
'''
... | [
"def",
"_get_envs_from_ref_paths",
"(",
"self",
",",
"refs",
")",
":",
"def",
"_check_ref",
"(",
"env_set",
",",
"rname",
")",
":",
"'''\n Add the appropriate saltenv(s) to the set\n '''",
"if",
"rname",
"in",
"self",
".",
"saltenv_revmap",
":",
... | 37.594595 | 0.001402 |
def fetch_track_items(upstream_file_url, data_source):
""" The file format is:
# Upstream contributions, bitergia will crawl this and extract the relevant information
# system is one of Gerrit, Bugzilla, Launchpad (insert more)
---
-
url: https://review.openstack.org/169836
system: Gerr... | [
"def",
"fetch_track_items",
"(",
"upstream_file_url",
",",
"data_source",
")",
":",
"track_uris",
"=",
"[",
"]",
"req",
"=",
"requests_ses",
".",
"get",
"(",
"upstream_file_url",
")",
"try",
":",
"req",
".",
"raise_for_status",
"(",
")",
"except",
"requests",
... | 32.517241 | 0.00206 |
def handle_block(
mediator_state: MediatorTransferState,
state_change: Block,
channelidentifiers_to_channels: ChannelMap,
pseudo_random_generator: random.Random,
) -> TransitionResult[MediatorTransferState]:
""" After Raiden learns about a new block this function must be called to
... | [
"def",
"handle_block",
"(",
"mediator_state",
":",
"MediatorTransferState",
",",
"state_change",
":",
"Block",
",",
"channelidentifiers_to_channels",
":",
"ChannelMap",
",",
"pseudo_random_generator",
":",
"random",
".",
"Random",
",",
")",
"->",
"TransitionResult",
"... | 34.341463 | 0.000691 |
def save_data(self, trigger_id, **data):
"""
let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the sa... | [
"def",
"save_data",
"(",
"self",
",",
"trigger_id",
",",
"*",
"*",
"data",
")",
":",
"if",
"data",
".",
"get",
"(",
"'link'",
")",
":",
"if",
"len",
"(",
"data",
".",
"get",
"(",
"'link'",
")",
")",
">",
"0",
":",
"# get the pocket data of this trigg... | 40.628571 | 0.00206 |
def map_weights(self):
"""
Reshaped weights for visualization.
The weights are reshaped as
(W.shape[0], prod(W.shape[1:-1]), W.shape[2]).
This allows one to easily see patterns, even for hyper-dimensional
soms.
For one-dimensional SOMs, the returned array is of ... | [
"def",
"map_weights",
"(",
"self",
")",
":",
"first_dim",
"=",
"self",
".",
"map_dimensions",
"[",
"0",
"]",
"if",
"len",
"(",
"self",
".",
"map_dimensions",
")",
"!=",
"1",
":",
"second_dim",
"=",
"np",
".",
"prod",
"(",
"self",
".",
"map_dimensions",... | 31.172414 | 0.002146 |
def is_domain_valid(
self, domain=None, subdomain_check=False
): # pylint:disable=too-many-return-statements, too-many-branches
"""
Check if the given domain is a valid.
:param domain: The domain to validate.
:type domain: str
:param subdomain_check:
Ac... | [
"def",
"is_domain_valid",
"(",
"self",
",",
"domain",
"=",
"None",
",",
"subdomain_check",
"=",
"False",
")",
":",
"# pylint:disable=too-many-return-statements, too-many-branches",
"# We initate our regex which will match for valid domains.",
"regex_valid_domains",
"=",
"r\"^(?=.... | 38.722581 | 0.002112 |
def scale_pixels(color, layer):
"""Scales the pixel to the virtual pixelmap."""
pixelmap = []
# Scaling the pixel offsets.
for pix_x in range(MAX_X + 1):
for pix_y in range(MAX_Y + 1):
# Horizontal pixels
y1 = pix_y * dotsize[0]
x1 = pix_x * dotsize[1]
... | [
"def",
"scale_pixels",
"(",
"color",
",",
"layer",
")",
":",
"pixelmap",
"=",
"[",
"]",
"# Scaling the pixel offsets.",
"for",
"pix_x",
"in",
"range",
"(",
"MAX_X",
"+",
"1",
")",
":",
"for",
"pix_y",
"in",
"range",
"(",
"MAX_Y",
"+",
"1",
")",
":",
... | 32.047619 | 0.001443 |
def cd(cd_path, create=False):
"""cd to target dir when running in this block
:param cd_path: dir to cd into
:param create: create new dir if destination not there
Usage::
>>> with cd("/tmp"):
... print("we are in /tmp now")
"""
oricwd = os.getcwd()
if create:
... | [
"def",
"cd",
"(",
"cd_path",
",",
"create",
"=",
"False",
")",
":",
"oricwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"if",
"create",
":",
"mkdir",
"(",
"cd_path",
")",
"try",
":",
"os",
".",
"chdir",
"(",
"cd_path",
")",
"yield",
"finally",
":",
"os... | 21.210526 | 0.002375 |
def valid_index(index, shape) -> tuple:
"""Get a valid index for a broadcastable shape.
Parameters
----------
index : tuple
Given index.
shape : tuple of int
Shape.
Returns
-------
tuple
Valid index.
"""
# append slices to index
index = list(index)
... | [
"def",
"valid_index",
"(",
"index",
",",
"shape",
")",
"->",
"tuple",
":",
"# append slices to index",
"index",
"=",
"list",
"(",
"index",
")",
"while",
"len",
"(",
"index",
")",
"<",
"len",
"(",
"shape",
")",
":",
"index",
".",
"append",
"(",
"slice",... | 21.9 | 0.001458 |
def bin_kb_sparse(M, positions, length=10):
"""Perform the exact kb-binning procedure on a sparse matrix.
"""
try:
from scipy.sparse import coo_matrix
except ImportError as e:
print(str(e))
print("I am peforming dense normalization by default.")
return bin_kb_dense(M.tod... | [
"def",
"bin_kb_sparse",
"(",
"M",
",",
"positions",
",",
"length",
"=",
"10",
")",
":",
"try",
":",
"from",
"scipy",
".",
"sparse",
"import",
"coo_matrix",
"except",
"ImportError",
"as",
"e",
":",
"print",
"(",
"str",
"(",
"e",
")",
")",
"print",
"("... | 35.428571 | 0.001309 |
def friend_addRow(self, rowNum, row):
"""used only by parser: adds a row of columns"""
self[rowNum] = row
if (rowNum > self.maxRow):
self.maxRow = rowNum
for cellNum in row.keys():
if cellNum > self.m... | [
"def",
"friend_addRow",
"(",
"self",
",",
"rowNum",
",",
"row",
")",
":",
"self",
"[",
"rowNum",
"]",
"=",
"row",
"if",
"(",
"rowNum",
">",
"self",
".",
"maxRow",
")",
":",
"self",
".",
"maxRow",
"=",
"rowNum",
"for",
"cellNum",
"in",
"row",
".",
... | 38.636364 | 0.011494 |
def message(self):
"""Return default message for this element
"""
if self.code != 200:
for code in self.response_codes:
if code.code == self.code:
return code.message
raise ValueError("Unknown response code \"%s\" in \"%s\"." % (self.c... | [
"def",
"message",
"(",
"self",
")",
":",
"if",
"self",
".",
"code",
"!=",
"200",
":",
"for",
"code",
"in",
"self",
".",
"response_codes",
":",
"if",
"code",
".",
"code",
"==",
"self",
".",
"code",
":",
"return",
"code",
".",
"message",
"raise",
"Va... | 31.545455 | 0.008403 |
def _get_module_filename(module):
"""
Return the filename of `module` if it can be imported.
If `module` is a package, its directory will be returned.
If it cannot be imported ``None`` is returned.
If the ``__file__`` attribute is missing, or the module or package is a
compiled egg, then an :... | [
"def",
"_get_module_filename",
"(",
"module",
")",
":",
"# Split up the module and its containing package, if it has one",
"module",
"=",
"module",
".",
"split",
"(",
"'.'",
")",
"package",
"=",
"'.'",
".",
"join",
"(",
"module",
"[",
":",
"-",
"1",
"]",
")",
... | 36.150943 | 0.000508 |
def expand(self, basedir, config, sourcedir, targetdir, cwd):
"""
Validate that given paths are not the same.
Args:
basedir (string): Project base directory used to prepend relative
paths. If empty or equal to '.', it will be filled with current
direc... | [
"def",
"expand",
"(",
"self",
",",
"basedir",
",",
"config",
",",
"sourcedir",
",",
"targetdir",
",",
"cwd",
")",
":",
"# Expand home directory if any",
"expanded_basedir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"basedir",
")",
"expanded_config",
"=",... | 45.955556 | 0.000947 |
def down_the_wabbit_hole(session, class_name):
"""
Authenticate on class.coursera.org
"""
auth_redirector_url = AUTH_REDIRECT_URL.format(class_name=class_name)
r = session.get(auth_redirector_url)
logging.debug('Following %s to authenticate on class.coursera.org.',
auth_redir... | [
"def",
"down_the_wabbit_hole",
"(",
"session",
",",
"class_name",
")",
":",
"auth_redirector_url",
"=",
"AUTH_REDIRECT_URL",
".",
"format",
"(",
"class_name",
"=",
"class_name",
")",
"r",
"=",
"session",
".",
"get",
"(",
"auth_redirector_url",
")",
"logging",
".... | 30.333333 | 0.001776 |
def whence_file(py_script, dirnames=None):
"""Do a shell-like path lookup for py_script and return the results.
If we can't find anything return py_script"""
if py_script.find(os.sep) != -1:
# Don't search since this name has path separator components
return py_script
if dirnames is None... | [
"def",
"whence_file",
"(",
"py_script",
",",
"dirnames",
"=",
"None",
")",
":",
"if",
"py_script",
".",
"find",
"(",
"os",
".",
"sep",
")",
"!=",
"-",
"1",
":",
"# Don't search since this name has path separator components",
"return",
"py_script",
"if",
"dirname... | 39.428571 | 0.00177 |
def main(argv=None):
'''Command line options.'''
program_name = os.path.basename(sys.argv[0])
program_version = "v0.1"
program_build_date = "%s" % __updated__
program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
#program_usage = '''usage: spam two eggs''' # op... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"program_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"program_version",
"=",
"\"v0.1\"",
"program_build_date",
"=",
"\"%s\"",
"%",
"__updated__",
"program... | 38.584416 | 0.022645 |
def compile_protos():
"""Builds necessary assets from sources."""
# If there's no makefile, we're likely installing from an sdist,
# so there's no need to compile the protos (they should be already
# compiled).
if not os.path.exists(os.path.join(THIS_DIRECTORY, "makefile.py")):
return
# Only compile pr... | [
"def",
"compile_protos",
"(",
")",
":",
"# If there's no makefile, we're likely installing from an sdist,",
"# so there's no need to compile the protos (they should be already",
"# compiled).",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join"... | 39.909091 | 0.017817 |
def gf_poly_eval(poly, x):
'''Evaluates a polynomial in GF(2^p) given the value for x. This is based on Horner's scheme for maximum efficiency.'''
y = poly[0]
for i in xrange(1, len(poly)):
y = gf_mul(y, x) ^ poly[i]
return y | [
"def",
"gf_poly_eval",
"(",
"poly",
",",
"x",
")",
":",
"y",
"=",
"poly",
"[",
"0",
"]",
"for",
"i",
"in",
"xrange",
"(",
"1",
",",
"len",
"(",
"poly",
")",
")",
":",
"y",
"=",
"gf_mul",
"(",
"y",
",",
"x",
")",
"^",
"poly",
"[",
"i",
"]"... | 40.666667 | 0.008032 |
def _findProteinClusters(protToPeps, pepToProts):
"""Find protein clusters in the specified protein to peptide mappings.
A protein cluster is a group of proteins that are somehow directly or
indirectly connected by shared peptides.
:param protToPeps: dict, for each protein (=key) contains a set of
... | [
"def",
"_findProteinClusters",
"(",
"protToPeps",
",",
"pepToProts",
")",
":",
"clusters",
"=",
"list",
"(",
")",
"resolvingProteins",
"=",
"set",
"(",
"protToPeps",
")",
"while",
"resolvingProteins",
":",
"protein",
"=",
"resolvingProteins",
".",
"pop",
"(",
... | 41 | 0.001537 |
def isFile(self):
""" Check if the given object is a file
"""
try:
filetype = file
except NameError:
filetype = io.IOBase
return self._wrap(type(self.obj) is filetype) | [
"def",
"isFile",
"(",
"self",
")",
":",
"try",
":",
"filetype",
"=",
"file",
"except",
"NameError",
":",
"filetype",
"=",
"io",
".",
"IOBase",
"return",
"self",
".",
"_wrap",
"(",
"type",
"(",
"self",
".",
"obj",
")",
"is",
"filetype",
")"
] | 24.888889 | 0.008621 |
def mkCompoundFilter(parts):
"""Create a filter out of a list of filter-like things
Used by mkFilter
@param parts: list of filter, endpoint, callable or list of any of these
"""
# Separate into a list of callables and a list of filter objects
transformers = []
filters = []
for subfilte... | [
"def",
"mkCompoundFilter",
"(",
"parts",
")",
":",
"# Separate into a list of callables and a list of filter objects",
"transformers",
"=",
"[",
"]",
"filters",
"=",
"[",
"]",
"for",
"subfilter",
"in",
"parts",
":",
"try",
":",
"subfilter",
"=",
"list",
"(",
"subf... | 35.128205 | 0.00071 |
def start(self):
""" Starts the agent. Among other things, this means connecting
to the master agent, if configured that way. """
if self._status != netsnmpAgentStatus.CONNECTED \
and self._status != netsnmpAgentStatus.RECONNECTING:
self._status = netsnmpAgentStatus.FIRSTCONNECT
libnsa.init_snmp(b(se... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_status",
"!=",
"netsnmpAgentStatus",
".",
"CONNECTED",
"and",
"self",
".",
"_status",
"!=",
"netsnmpAgentStatus",
".",
"RECONNECTING",
":",
"self",
".",
"_status",
"=",
"netsnmpAgentStatus",
".",
"F... | 48.416667 | 0.028716 |
def push_intent(self, intent):
"""Registers or updates an intent and returns the intent_json with an ID"""
if intent.id:
print('Updating {} intent'.format(intent.name))
self.update(intent)
else:
print('Registering {} intent'.format(intent.name))
in... | [
"def",
"push_intent",
"(",
"self",
",",
"intent",
")",
":",
"if",
"intent",
".",
"id",
":",
"print",
"(",
"'Updating {} intent'",
".",
"format",
"(",
"intent",
".",
"name",
")",
")",
"self",
".",
"update",
"(",
"intent",
")",
"else",
":",
"print",
"(... | 40.222222 | 0.008108 |
def get_option(self, key, subkey, in_path_none=False):
"""Get the current value of the option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:param bool in_path_none: Allows for ``in_path`` values of
:data:`None` to be re... | [
"def",
"get_option",
"(",
"self",
",",
"key",
",",
"subkey",
",",
"in_path_none",
"=",
"False",
")",
":",
"key",
",",
"subkey",
"=",
"_lower_keys",
"(",
"key",
",",
"subkey",
")",
"_entry_must_exist",
"(",
"self",
".",
"gc",
",",
"key",
",",
"subkey",
... | 42.096774 | 0.001498 |
def exportCustomers(self, outPath):
"""exports customer list to a csv file
Input:
outPath - save location of the customer list
"""
url = "%s/customers/export" % self.root
params = {"f":"csv"}
dirPath = None
fileName = None
if outPath is not None:
... | [
"def",
"exportCustomers",
"(",
"self",
",",
"outPath",
")",
":",
"url",
"=",
"\"%s/customers/export\"",
"%",
"self",
".",
"root",
"params",
"=",
"{",
"\"f\"",
":",
"\"csv\"",
"}",
"dirPath",
"=",
"None",
"fileName",
"=",
"None",
"if",
"outPath",
"is",
"n... | 39.333333 | 0.009655 |
def getkeys(table):
"""
customize by commenting out unwanted keys
"""
keys = []
if table == "ER_expedition":
pass
if table == "ER_citations":
keys.append("er_citation_name")
keys.append("long_authors")
keys.append("year")
keys.append("title")
keys.... | [
"def",
"getkeys",
"(",
"table",
")",
":",
"keys",
"=",
"[",
"]",
"if",
"table",
"==",
"\"ER_expedition\"",
":",
"pass",
"if",
"table",
"==",
"\"ER_citations\"",
":",
"keys",
".",
"append",
"(",
"\"er_citation_name\"",
")",
"keys",
".",
"append",
"(",
"\"... | 37.759494 | 0.000163 |
def XYZ_to_galcencyl(X,Y,Z,Xsun=1.,Zsun=0.,_extra_rot=True):
"""
NAME:
XYZ_to_galcencyl
PURPOSE:
transform XYZ coordinates (wrt Sun) to cylindrical Galactocentric coordinates
INPUT:
X - X
Y - Y
Z - Z
Xsun - cylindrical distance to the GC
Z... | [
"def",
"XYZ_to_galcencyl",
"(",
"X",
",",
"Y",
",",
"Z",
",",
"Xsun",
"=",
"1.",
",",
"Zsun",
"=",
"0.",
",",
"_extra_rot",
"=",
"True",
")",
":",
"XYZ",
"=",
"nu",
".",
"atleast_2d",
"(",
"XYZ_to_galcenrect",
"(",
"X",
",",
"Y",
",",
"Z",
",",
... | 20.833333 | 0.024204 |
def Rforce(self,R,z,phi=0.,t=0.,v=None):
"""
NAME:
Rforce
PURPOSE:
evaluate cylindrical radial force F_R (R,z)
INPUT:
R - Cylindrical Galactocentric radius (can be Quantity)
z - vertical height (can be Quantity)
phi - azimuth... | [
"def",
"Rforce",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
",",
"v",
"=",
"None",
")",
":",
"return",
"self",
".",
"_Rforce_nodecorator",
"(",
"R",
",",
"z",
",",
"phi",
"=",
"phi",
",",
"t",
"=",
"t",
","... | 19 | 0.017214 |
def unstage_signature(vcs, signature):
"""Remove `signature` from the list of staged signatures
Args:
vcs (easyci.vcs.base.Vcs)
signature (basestring)
Raises:
NotStagedError
"""
evidence_path = _get_staged_history_path(vcs)
staged = get_staged_signatures(vcs)
if sig... | [
"def",
"unstage_signature",
"(",
"vcs",
",",
"signature",
")",
":",
"evidence_path",
"=",
"_get_staged_history_path",
"(",
"vcs",
")",
"staged",
"=",
"get_staged_signatures",
"(",
"vcs",
")",
"if",
"signature",
"not",
"in",
"staged",
":",
"raise",
"NotStagedErro... | 26.5 | 0.002024 |
def plot_heterozygosity(heterozygosity, options):
"""Plots the heterozygosity rate distribution.
:param heterozygosity: the heterozygosity data.
:param options: the options.
:type heterozygosity: numpy.array
:type options: argparse.Namespace
Plots a histogram or a boxplot of the heterozygosit... | [
"def",
"plot_heterozygosity",
"(",
"heterozygosity",
",",
"options",
")",
":",
"# importing important stuff",
"import",
"matplotlib",
"as",
"mpl",
"if",
"options",
".",
"format",
"!=",
"\"X11\"",
"and",
"mpl",
".",
"get_backend",
"(",
")",
"!=",
"\"agg\"",
":",
... | 32.484848 | 0.000302 |
def probabilities(self) -> bk.BKTensor:
"""
Returns:
The state probabilities
"""
value = bk.absolute(self.tensor)
return value * value | [
"def",
"probabilities",
"(",
"self",
")",
"->",
"bk",
".",
"BKTensor",
":",
"value",
"=",
"bk",
".",
"absolute",
"(",
"self",
".",
"tensor",
")",
"return",
"value",
"*",
"value"
] | 25.714286 | 0.010753 |
def transactions(self, dt=None):
"""Retrieve the dict-form of all of the transactions in a given bar or
for the whole simulation.
Parameters
----------
dt : pd.Timestamp or None, optional
The particular datetime to look up transactions for. If not passed,
... | [
"def",
"transactions",
"(",
"self",
",",
"dt",
"=",
"None",
")",
":",
"if",
"dt",
"is",
"None",
":",
"# flatten the by-day transactions",
"return",
"[",
"txn",
"for",
"by_day",
"in",
"itervalues",
"(",
"self",
".",
"_processed_transactions",
")",
"for",
"txn... | 31.44 | 0.002469 |
def check_autosign_grains(self, autosign_grains):
'''
Check for matching grains in the autosign_grains_dir.
'''
if not autosign_grains or 'autosign_grains_dir' not in self.opts:
return False
autosign_grains_dir = self.opts['autosign_grains_dir']
for root, dir... | [
"def",
"check_autosign_grains",
"(",
"self",
",",
"autosign_grains",
")",
":",
"if",
"not",
"autosign_grains",
"or",
"'autosign_grains_dir'",
"not",
"in",
"self",
".",
"opts",
":",
"return",
"False",
"autosign_grains_dir",
"=",
"self",
".",
"opts",
"[",
"'autosi... | 42.214286 | 0.002481 |
def get_definition_with_regex(source, token, start_line=-1):
"""
Find the definition of an object within a source closest to a given line
"""
if not token:
return None
if DEBUG_EDITOR:
t0 = time.time()
patterns = [ # python / cython keyword definitions
r... | [
"def",
"get_definition_with_regex",
"(",
"source",
",",
"token",
",",
"start_line",
"=",
"-",
"1",
")",
":",
"if",
"not",
"token",
":",
"return",
"None",
"if",
"DEBUG_EDITOR",
":",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"patterns",
"=",
"[",
"# pyth... | 36.702128 | 0.000565 |
def subnetpool_create(request, name, prefixes, **kwargs):
"""Create a subnetpool.
ip_version is auto-detected in back-end.
Parameters:
request -- Request context
name -- Name for subnetpool
prefixes -- List of prefixes for pool
Keyword Arguments (optional):... | [
"def",
"subnetpool_create",
"(",
"request",
",",
"name",
",",
"prefixes",
",",
"*",
"*",
"kwargs",
")",
":",
"LOG",
".",
"debug",
"(",
"\"subnetpool_create(): name=%(name)s, prefixes=%(prefixes)s, \"",
"\"kwargs=%(kwargs)s\"",
",",
"{",
"'name'",
":",
"name",
",",
... | 37.2 | 0.000749 |
def _make_expand_x_fn_for_non_batch_interpolation(y_ref, axis):
"""Make func to expand left/right (of axis) dims of tensors shaped like x."""
# This expansion is to help x broadcast with `y`, the output.
# In the non-batch case, the output shape is going to be
# y_ref.shape[:axis] + x.shape + y_ref.shape[axis... | [
"def",
"_make_expand_x_fn_for_non_batch_interpolation",
"(",
"y_ref",
",",
"axis",
")",
":",
"# This expansion is to help x broadcast with `y`, the output.",
"# In the non-batch case, the output shape is going to be",
"# y_ref.shape[:axis] + x.shape + y_ref.shape[axis+1:]",
"# Recall we made... | 35.942857 | 0.010836 |
def plot_vyy(self, colorbar=True, cb_orientation='vertical',
cb_label=None, ax=None, show=True, fname=None, **kwargs):
"""
Plot the Vyy component of the tensor.
Usage
-----
x.plot_vyy([tick_interval, xlabel, ylabel, ax, colorbar,
cb_orientati... | [
"def",
"plot_vyy",
"(",
"self",
",",
"colorbar",
"=",
"True",
",",
"cb_orientation",
"=",
"'vertical'",
",",
"cb_label",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"show",
"=",
"True",
",",
"fname",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"i... | 40.641509 | 0.00136 |
def convert_timedelta(obj):
"""Returns a TIME column as a timedelta object:
>>> timedelta_or_None('25:06:17')
datetime.timedelta(1, 3977)
>>> timedelta_or_None('-25:06:17')
datetime.timedelta(-2, 83177)
Illegal values are returned as None:
>>> timedelta_or_None('random crap') is... | [
"def",
"convert_timedelta",
"(",
"obj",
")",
":",
"try",
":",
"microseconds",
"=",
"0",
"if",
"\".\"",
"in",
"obj",
":",
"(",
"obj",
",",
"tail",
")",
"=",
"obj",
".",
"split",
"(",
"'.'",
")",
"microseconds",
"=",
"float",
"(",
"'0.'",
"+",
"tail"... | 29.777778 | 0.00813 |
def close(args):
"""
%prog close scaffolds.fasta PE*.fastq
Run GapFiller to fill gaps.
"""
p = OptionParser(close.__doc__)
p.set_home("gapfiller")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(not p.print_help())
scaffolds = args[0]
libtxt... | [
"def",
"close",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"close",
".",
"__doc__",
")",
"p",
".",
"set_home",
"(",
"\"gapfiller\"",
")",
"p",
".",
"set_cpus",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",... | 25.190476 | 0.001821 |
def get(self, page_size, current_page, session):
'''taobao.crm.groups.get 查询卖家的分组
查询卖家的分组,返回查询到的分组列表,分页返回分组'''
request = TOPRequest('taobao.crm.groups.get')
request['page_size'] = page_size
request['current_page'] = current_page
self.create(self.execute(request, ... | [
"def",
"get",
"(",
"self",
",",
"page_size",
",",
"current_page",
",",
"session",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.crm.groups.get'",
")",
"request",
"[",
"'page_size'",
"]",
"=",
"page_size",
"request",
"[",
"'current_page'",
"]",
"=",
"... | 38.666667 | 0.008427 |
def write(self, pin, value, pwm=False):
"""Sets the output to the given value.
Sets `pin` output to given value. If the pin is in INPUT mode, do
nothing. If it's an analog pin, value should be in write_range.
If it's not in the allowed range, it will be clamped. If pin is in
dig... | [
"def",
"write",
"(",
"self",
",",
"pin",
",",
"value",
",",
"pwm",
"=",
"False",
")",
":",
"if",
"type",
"(",
"pin",
")",
"is",
"list",
":",
"for",
"p",
"in",
"pin",
":",
"self",
".",
"write",
"(",
"p",
",",
"value",
",",
"pwm",
")",
"return"... | 45.404762 | 0.001027 |
def Run(self):
"""Initialize the data_store."""
global DB # pylint: disable=global-statement
global REL_DB # pylint: disable=global-statement
global BLOBS # pylint: disable=global-statement
if flags.FLAGS.list_storage:
self._ListStorageOptions()
sys.exit(0)
try:
cls = Data... | [
"def",
"Run",
"(",
"self",
")",
":",
"global",
"DB",
"# pylint: disable=global-statement",
"global",
"REL_DB",
"# pylint: disable=global-statement",
"global",
"BLOBS",
"# pylint: disable=global-statement",
"if",
"flags",
".",
"FLAGS",
".",
"list_storage",
":",
"self",
"... | 33.6875 | 0.009615 |
def read(fname, URL, URLImage):
"""Read the content of a file."""
readme = open(path.join(path.dirname(__file__), fname)).read()
if hasattr(readme, 'decode'):
# In Python 3, turn bytes into str.
readme = readme.decode('utf8')
# turn relative links into absolute ones
readme = re.sub(r... | [
"def",
"read",
"(",
"fname",
",",
"URL",
",",
"URLImage",
")",
":",
"readme",
"=",
"open",
"(",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"fname",
")",
")",
".",
"read",
"(",
")",
"if",
"hasattr",
"(",
"readme",... | 39.307692 | 0.001912 |
def get_item(self, item_id):
""" see if this is a magic item id (i.e. questionId).
If so, grab the item and set the params.
If not, just pass through to the original Mongo ItemLookupSession
:param item_id:
:return:
"""
authority = item_id.authority
mgr = s... | [
"def",
"get_item",
"(",
"self",
",",
"item_id",
")",
":",
"authority",
"=",
"item_id",
".",
"authority",
"mgr",
"=",
"self",
".",
"_get_provider_manager",
"(",
"'ASSESSMENT'",
",",
"local",
"=",
"True",
")",
"if",
"self",
".",
"_proxy",
"is",
"not",
"Non... | 40.892857 | 0.001706 |
def run(self):
"""Run flux variability command"""
# Load compound information
def compound_name(id):
if id not in self._model.compounds:
return id
return self._model.compounds[id].properties.get('name', id)
reaction = self._get_objective()
... | [
"def",
"run",
"(",
"self",
")",
":",
"# Load compound information",
"def",
"compound_name",
"(",
"id",
")",
":",
"if",
"id",
"not",
"in",
"self",
".",
"_model",
".",
"compounds",
":",
"return",
"id",
"return",
"self",
".",
"_model",
".",
"compounds",
"["... | 34.567164 | 0.00084 |
def soupify(self):
"""Get proper torrent/magnet information.
If search_mode is rated then get torrent/magnet.
If not, get all the elements to build the table.
There are different ways for each page.
"""
soup = BeautifulSoup(self.content_page.content, 'lxml')
if s... | [
"def",
"soupify",
"(",
"self",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"self",
".",
"content_page",
".",
"content",
",",
"'lxml'",
")",
"if",
"self",
".",
"page",
"==",
"'torrent_project'",
":",
"main",
"=",
"soup",
".",
"find",
"(",
"'div'",
",",... | 43.898734 | 0.000564 |
def find_group(self, star, starlist):
"""
Find the ids of those stars in ``starlist`` which are at a
distance less than ``crit_separation`` from ``star``.
Parameters
----------
star : `~astropy.table.Row`
Star which will be either the head of a cluster or an
... | [
"def",
"find_group",
"(",
"self",
",",
"star",
",",
"starlist",
")",
":",
"star_distance",
"=",
"np",
".",
"hypot",
"(",
"star",
"[",
"'x_0'",
"]",
"-",
"starlist",
"[",
"'x_0'",
"]",
",",
"star",
"[",
"'y_0'",
"]",
"-",
"starlist",
"[",
"'y_0'",
"... | 38.64 | 0.00202 |
def processTPED(uniqueSamples, duplicatedSamples, fileName, prefix):
"""Process the TPED file.
:param uniqueSamples: the position of unique samples.
:param duplicatedSamples: the position of duplicated samples.
:param fileName: the name of the file.
:param prefix: the prefix of all the files.
... | [
"def",
"processTPED",
"(",
"uniqueSamples",
",",
"duplicatedSamples",
",",
"fileName",
",",
"prefix",
")",
":",
"# Getting the indexes",
"uI",
"=",
"sorted",
"(",
"uniqueSamples",
".",
"values",
"(",
")",
")",
"dI",
"=",
"[",
"]",
"for",
"item",
"in",
"dup... | 32.920635 | 0.000468 |
def check_lazy_load_perceel(f):
'''
Decorator function to lazy load a :class:`Perceel`.
'''
def wrapper(*args):
perceel = args[0]
if perceel._centroid is None or perceel._metadata is None:
log.debug('Lazy loading Perceel %s', perceel.id)
perceel.check_gateway()
... | [
"def",
"check_lazy_load_perceel",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
")",
":",
"perceel",
"=",
"args",
"[",
"0",
"]",
"if",
"perceel",
".",
"_centroid",
"is",
"None",
"or",
"perceel",
".",
"_metadata",
"is",
"None",
":",
"log",
"... | 35.5 | 0.001961 |
def find_perf_space_price(package, size):
"""Find the price in the given package with the specified size
:param package: The Performance product package
:param size: The storage space size for which a price is desired
:return: Returns the price for the given size, or an error if not found
"""
f... | [
"def",
"find_perf_space_price",
"(",
"package",
",",
"size",
")",
":",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"int",
"(",
"item",
"[",
"'capacity'",
"]",
")",
"!=",
"size",
":",
"continue",
"price_id",
"=",
"_find_price_id",
"(",... | 37.8125 | 0.001613 |
def trim(self, name):
"""When the name is too long, use the LHS or a random string instead."""
if len(name) > self.MAX_LENGTH and self.target:
name = self.TEMP_VAR.format(self._name(self.target))
if len(name) > self.MAX_LENGTH:
while True:
name = '_{:04x}'.format(random.randint(0, 16 ** ... | [
"def",
"trim",
"(",
"self",
",",
"name",
")",
":",
"if",
"len",
"(",
"name",
")",
">",
"self",
".",
"MAX_LENGTH",
"and",
"self",
".",
"target",
":",
"name",
"=",
"self",
".",
"TEMP_VAR",
".",
"format",
"(",
"self",
".",
"_name",
"(",
"self",
".",... | 38.5 | 0.010152 |
def people(self):
"""
The people list stored in payload (decoded upon every call())
:return: The people
:rtype: list[paps.people.People]
:raises ProtocolViolation:
Failed to find marker
Wrong number of bits in payload -> cannot decode into people
... | [
"def",
"people",
"(",
"self",
")",
":",
"people",
"=",
"[",
"]",
"bits",
"=",
"bytearray",
"(",
")",
"byts",
"=",
"struct",
".",
"unpack",
"(",
"APPUpdateMessage",
".",
"fmt",
".",
"format",
"(",
"len",
"(",
"self",
".",
"payload",
")",
")",
",",
... | 32.942308 | 0.001134 |
def get_args():
'''
Parse CLI args
'''
parser = argparse.ArgumentParser(description='Process args')
parser.Add_argument(
'-H', '--host',
required=True,
action='store',
help='Remote host to connect to'
)
parser.add_argument(
'-P', '--port',
type... | [
"def",
"get_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Process args'",
")",
"parser",
".",
"Add_argument",
"(",
"'-H'",
",",
"'--host'",
",",
"required",
"=",
"True",
",",
"action",
"=",
"'store'",
",... | 23.684211 | 0.000711 |
def open(self, database, user, password, host):
'''This opens a new database connection.
Parameters
----------
database : str
Name of the database to connect to.
user : str
User name of the database server user.
password : str
Passw... | [
"def",
"open",
"(",
"self",
",",
"database",
",",
"user",
",",
"password",
",",
"host",
")",
":",
"try",
":",
"self",
".",
"connection",
"=",
"pg",
".",
"connect",
"(",
"user",
"=",
"user",
",",
"password",
"=",
"password",
",",
"database",
"=",
"d... | 27.738095 | 0.001658 |
def load_library(filename, match, folder, token, host):
"""
upload an egg to the Databricks filesystem.
Parameters
----------
filename: string
local location of file to upload
match: FilenameMatch object
match object with library_type, library_name, and version
folder: strin... | [
"def",
"load_library",
"(",
"filename",
",",
"match",
",",
"folder",
",",
"token",
",",
"host",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"file_obj",
":",
"res",
"=",
"requests",
".",
"post",
"(",
"host",
"+",
"'/api/1.2/librar... | 28.75 | 0.000935 |
def do_check(vext_files):
"""
Attempt to import everything in the 'test-imports' section of specified
vext_files
:param: list of vext filenames (without paths), '*' matches all.
:return: True if test_imports was successful from all files
"""
import vext
# not efficient ... but then ther... | [
"def",
"do_check",
"(",
"vext_files",
")",
":",
"import",
"vext",
"# not efficient ... but then there shouldn't be many of these",
"all_specs",
"=",
"set",
"(",
"vext",
".",
"gatekeeper",
".",
"spec_files_flat",
"(",
")",
")",
"if",
"vext_files",
"==",
"[",
"'*'",
... | 32.969697 | 0.001786 |
def volume_create(name, size=100, snapshot=None, voltype=None, **kwargs):
'''
Create block storage device
'''
conn = get_conn()
create_kwargs = {'name': name,
'size': size,
'snapshot': snapshot,
'voltype': voltype}
create_kwargs['ava... | [
"def",
"volume_create",
"(",
"name",
",",
"size",
"=",
"100",
",",
"snapshot",
"=",
"None",
",",
"voltype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"get_conn",
"(",
")",
"create_kwargs",
"=",
"{",
"'name'",
":",
"name",
",",
"'... | 37.545455 | 0.002364 |
def process(self):
"""!
@brief Performs cluster analysis in line with rules of DBSCAN algorithm.
@see get_clusters()
@see get_noise()
"""
if self.__ccore is True:
(self.__clusters, self.__noise) = wrapper.dbscan(self.__poin... | [
"def",
"process",
"(",
"self",
")",
":",
"if",
"self",
".",
"__ccore",
"is",
"True",
":",
"(",
"self",
".",
"__clusters",
",",
"self",
".",
"__noise",
")",
"=",
"wrapper",
".",
"dbscan",
"(",
"self",
".",
"__pointer_data",
",",
"self",
".",
"__eps",
... | 37.56 | 0.009346 |
def response_schema(schema, code=200, required=False, description=None):
"""
Add response info into the swagger spec
Usage:
.. code-block:: python
from aiohttp import web
from marshmallow import Schema, fields
class ResponseSchema(Schema):
msg = fields.Str()
... | [
"def",
"response_schema",
"(",
"schema",
",",
"code",
"=",
"200",
",",
"required",
"=",
"False",
",",
"description",
"=",
"None",
")",
":",
"if",
"callable",
"(",
"schema",
")",
":",
"schema",
"=",
"schema",
"(",
")",
"def",
"wrapper",
"(",
"func",
"... | 27 | 0.000917 |
def find_imports_and_track_names(filename, warn_about_duplicates=False,
verbose=False):
"""Find all imported names in a given file.
Returns ``(imports, unused)``. Both are lists of ImportInfo objects.
"""
with open(filename) as f:
root = ast.parse(f.read(), fil... | [
"def",
"find_imports_and_track_names",
"(",
"filename",
",",
"warn_about_duplicates",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"root",
"=",
"ast",
".",
"parse",
"(",
"f",
".",
"read",
"("... | 39.571429 | 0.001764 |
def write_segment(self, objects):
""" Write a segment of data to a TDMS file
:param objects: A list of TdmsObject instances to write
"""
segment = TdmsSegment(objects)
segment.write(self._file) | [
"def",
"write_segment",
"(",
"self",
",",
"objects",
")",
":",
"segment",
"=",
"TdmsSegment",
"(",
"objects",
")",
"segment",
".",
"write",
"(",
"self",
".",
"_file",
")"
] | 32.571429 | 0.008547 |
def cancel(self, session):
'''taobao.crm.shopvip.cancel 卖家取消店铺vip的优惠
此接口用于取消VIP优惠'''
request = TOPRequest('taobao.crm.shopvip.cancel')
self.create(self.execute(request, session))
return self.is_success | [
"def",
"cancel",
"(",
"self",
",",
"session",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.crm.shopvip.cancel'",
")",
"self",
".",
"create",
"(",
"self",
".",
"execute",
"(",
"request",
",",
"session",
")",
")",
"return",
"self",
".",
"is_success"... | 34.857143 | 0.012 |
def restore(self, remotepath):
''' Usage: restore <remotepath> - \
restore a file from the recycle bin
remotepath - the remote path to restore
'''
rpath = get_pcs_path(remotepath)
# by default, only 1000 items, more than that sounds a bit crazy
pars = {
'method' : 'listrecycle' }
self.pd("Searching fo... | [
"def",
"restore",
"(",
"self",
",",
"remotepath",
")",
":",
"rpath",
"=",
"get_pcs_path",
"(",
"remotepath",
")",
"# by default, only 1000 items, more than that sounds a bit crazy",
"pars",
"=",
"{",
"'method'",
":",
"'listrecycle'",
"}",
"self",
".",
"pd",
"(",
"... | 33.833333 | 0.033573 |
def set_final_value(self, description_type, value):
"""Set the value for the given description type.
in description_type type :class:`VirtualSystemDescriptionType`
in value type str
"""
types, _, _, vbox_values, extra_config = self.get_description()
# find offset to de... | [
"def",
"set_final_value",
"(",
"self",
",",
"description_type",
",",
"value",
")",
":",
"types",
",",
"_",
",",
"_",
",",
"vbox_values",
",",
"extra_config",
"=",
"self",
".",
"get_description",
"(",
")",
"# find offset to description type",
"for",
"offset",
"... | 33.129032 | 0.001892 |
def trace_debug_dispatch(self, frame, event, arg):
"""Utility function to add debug to tracing"""
trace_log.info(
'Frame:%s. Event: %s. Arg: %r' % (pretty_frame(frame), event, arg)
)
trace_log.debug(
'state %r breaks ? %s stops ? %s' % (
self.state... | [
"def",
"trace_debug_dispatch",
"(",
"self",
",",
"frame",
",",
"event",
",",
"arg",
")",
":",
"trace_log",
".",
"info",
"(",
"'Frame:%s. Event: %s. Arg: %r'",
"%",
"(",
"pretty_frame",
"(",
"frame",
")",
",",
"event",
",",
"arg",
")",
")",
"trace_log",
"."... | 40.761905 | 0.002283 |
def __check_file_status(self, index):
"""Check if file has been changed in any way outside Spyder:
1. removed, moved or renamed outside Spyder
2. modified outside Spyder"""
if self.__file_status_flag:
# Avoid infinite loop: when the QMessageBox.question pops, it
... | [
"def",
"__check_file_status",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
".",
"__file_status_flag",
":",
"# Avoid infinite loop: when the QMessageBox.question pops, it\r",
"# gets focus and then give it back to the CodeEditor instance,\r",
"# triggering a refresh cycle which ca... | 43.354839 | 0.000728 |
def api(func, container = None, criteria = None):
'''
Return an API def for a generic function
:param func: a function or bounded method
:param container: if None, this is used as a synchronous method, the return value of the method
is used for the return value. If not No... | [
"def",
"api",
"(",
"func",
",",
"container",
"=",
"None",
",",
"criteria",
"=",
"None",
")",
":",
"return",
"(",
"func",
".",
"__name__",
".",
"lower",
"(",
")",
",",
"functools",
".",
"update_wrapper",
"(",
"lambda",
"n",
",",
"p",
":",
"func",
"(... | 55.5625 | 0.015487 |
def mutate(self, p_mutate):
"""
Check all genes in this chromosome for mutation.
p_mutate: probability for mutation to occur
"""
assert 0 <= p_mutate <= 1
for gene in self.genes:
gene.mutate(p_mutate) | [
"def",
"mutate",
"(",
"self",
",",
"p_mutate",
")",
":",
"assert",
"0",
"<=",
"p_mutate",
"<=",
"1",
"for",
"gene",
"in",
"self",
".",
"genes",
":",
"gene",
".",
"mutate",
"(",
"p_mutate",
")"
] | 27.2 | 0.021352 |
def _WriteSerializedAttributeContainerList(self, container_type):
"""Writes a serialized attribute container list.
Args:
container_type (str): attribute container type.
"""
if container_type == self._CONTAINER_TYPE_EVENT:
if not self._serialized_event_heap.data_size:
return
n... | [
"def",
"_WriteSerializedAttributeContainerList",
"(",
"self",
",",
"container_type",
")",
":",
"if",
"container_type",
"==",
"self",
".",
"_CONTAINER_TYPE_EVENT",
":",
"if",
"not",
"self",
".",
"_serialized_event_heap",
".",
"data_size",
":",
"return",
"number_of_attr... | 34.409836 | 0.009727 |
def cve_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""Sphinx role for linking to a CVE on https://cve.mitre.org.
Examples: ::
:cve:`CVE-2018-17175`
"""
options = options or {}
content = content or []
has_explicit_title, title, target = split_explicit_title... | [
"def",
"cve_role",
"(",
"name",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"None",
",",
"content",
"=",
"None",
")",
":",
"options",
"=",
"options",
"or",
"{",
"}",
"content",
"=",
"content",
"or",
"[",
"]",
"h... | 33.777778 | 0.0016 |
def evaluate(self, flux, xo, yo, a, b, c):
"""
Evaluate the Gaussian model
Parameters
----------
flux : tf.Variable
xo, yo : tf.Variable, tf.Variable
Center coordiantes of the Gaussian.
a, b, c : tf.Variable, tf.Variable
Parameters that co... | [
"def",
"evaluate",
"(",
"self",
",",
"flux",
",",
"xo",
",",
"yo",
",",
"a",
",",
"b",
",",
"c",
")",
":",
"dx",
"=",
"self",
".",
"x",
"-",
"xo",
"dy",
"=",
"self",
".",
"y",
"-",
"yo",
"psf",
"=",
"tf",
".",
"exp",
"(",
"-",
"(",
"a",... | 34.434783 | 0.002457 |
def try_value_to_bool(value, strict_mode=True):
"""Tries to convert value into boolean.
strict_mode is True:
- Only string representation of str(True) and str(False)
are converted into booleans;
- Otherwise unchanged incoming value is returned;
strict_mode is False:
- Anything that looks... | [
"def",
"try_value_to_bool",
"(",
"value",
",",
"strict_mode",
"=",
"True",
")",
":",
"if",
"strict_mode",
":",
"true_list",
"=",
"(",
"'True'",
",",
")",
"false_list",
"=",
"(",
"'False'",
",",
")",
"val",
"=",
"value",
"else",
":",
"true_list",
"=",
"... | 29.5 | 0.001094 |
def _get_credentials(self):
# type: () -> Optional[Tuple[str, str]]
"""
Return HDX site username and password
Returns:
Optional[Tuple[str, str]]: HDX site username and password or None
"""
site = self.data[self.hdx_site]
username = site.get('username... | [
"def",
"_get_credentials",
"(",
"self",
")",
":",
"# type: () -> Optional[Tuple[str, str]]",
"site",
"=",
"self",
".",
"data",
"[",
"self",
".",
"hdx_site",
"]",
"username",
"=",
"site",
".",
"get",
"(",
"'username'",
")",
"if",
"username",
":",
"return",
"b... | 31.133333 | 0.008316 |
def simxGetIntegerSignal(clientID, signalName, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
signalValue = ct.c_int()
if (sys.version_info[0] == 3) and (type(signalName) is str):
signalName=signalName.encode('utf-8')
return... | [
"def",
"simxGetIntegerSignal",
"(",
"clientID",
",",
"signalName",
",",
"operationMode",
")",
":",
"signalValue",
"=",
"ct",
".",
"c_int",
"(",
")",
"if",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
")",
"and",
"(",
"type",
"(",
"signalN... | 45.555556 | 0.009569 |
def get_primary_group(obj_name, obj_type='file'):
r'''
Gets the primary group of the passed object
Args:
obj_name (str):
The path for which to obtain primary group information
obj_type (str):
The type of object to query. This value changes the format of the
... | [
"def",
"get_primary_group",
"(",
"obj_name",
",",
"obj_type",
"=",
"'file'",
")",
":",
"# Not all filesystems mountable within windows have SecurityDescriptors.",
"# For instance, some mounted SAMBA shares, or VirtualBox shared folders. If",
"# we can't load a file descriptor for the file, w... | 37.27381 | 0.000311 |
def list_modules(*args):
'''
List the modules loaded on the minion
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' sys.list_modules
Module names can be specified as globs.
.. code-block:: bash
salt '*' sys.list_modules 's*'
'''
modules = ... | [
"def",
"list_modules",
"(",
"*",
"args",
")",
":",
"modules",
"=",
"set",
"(",
")",
"if",
"not",
"args",
":",
"for",
"func",
"in",
"__salt__",
":",
"modules",
".",
"add",
"(",
"func",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"return",
... | 22.057143 | 0.001241 |
def delete(self):
"""
Delete this VM, and remove all its disks
"""
disks = self.get_disks()
self.domain.undefine()
for disk in disks:
disk.wipe()
disk.delete() | [
"def",
"delete",
"(",
"self",
")",
":",
"disks",
"=",
"self",
".",
"get_disks",
"(",
")",
"self",
".",
"domain",
".",
"undefine",
"(",
")",
"for",
"disk",
"in",
"disks",
":",
"disk",
".",
"wipe",
"(",
")",
"disk",
".",
"delete",
"(",
")"
] | 24.777778 | 0.008658 |
def contains_key(self, *keys):
"""Asserts the val is a dict and contains the given key or keys. Alias for contains()."""
self._check_dict_like(self.val, check_values=False, check_getitem=False)
return self.contains(*keys) | [
"def",
"contains_key",
"(",
"self",
",",
"*",
"keys",
")",
":",
"self",
".",
"_check_dict_like",
"(",
"self",
".",
"val",
",",
"check_values",
"=",
"False",
",",
"check_getitem",
"=",
"False",
")",
"return",
"self",
".",
"contains",
"(",
"*",
"keys",
"... | 60.75 | 0.01626 |
def _find_metric_value(session_or_group, metric_name):
"""Returns the metric_value for a given metric in a session or session group.
Args:
session_or_group: A Session protobuffer or SessionGroup protobuffer.
metric_name: A MetricName protobuffer. The metric to search for.
Returns:
A MetricValue proto... | [
"def",
"_find_metric_value",
"(",
"session_or_group",
",",
"metric_name",
")",
":",
"# Note: We can speed this up by converting the metric_values field",
"# to a dictionary on initialization, to avoid a linear search here. We'll",
"# need to wrap the SessionGroup and Session protos in a python o... | 46.555556 | 0.010526 |
def input_selector_schema(config_cls):
'''
A decorator for annotating a function that can take the selected properties
from a ``config_value`` in to an instance of a custom type.
Args:
config_cls (Selector)
'''
config_type = resolve_config_cls_arg(config_cls)
check.param_invariant(c... | [
"def",
"input_selector_schema",
"(",
"config_cls",
")",
":",
"config_type",
"=",
"resolve_config_cls_arg",
"(",
"config_cls",
")",
"check",
".",
"param_invariant",
"(",
"config_type",
".",
"is_selector",
",",
"'config_cls'",
")",
"def",
"_wrap",
"(",
"func",
")",
... | 32.526316 | 0.001572 |
def get_node(self,obj,cls=type(None),hist={}):
"""
Returns the node corresponding to obj. If does not already exist
then it will create it.
"""
#~ ident = getattr(obj,'ident',obj)
if obj in self.modules and is_module(obj,cls):
return self.modules[obj]
... | [
"def",
"get_node",
"(",
"self",
",",
"obj",
",",
"cls",
"=",
"type",
"(",
"None",
")",
",",
"hist",
"=",
"{",
"}",
")",
":",
"#~ ident = getattr(obj,'ident',obj)",
"if",
"obj",
"in",
"self",
".",
"modules",
"and",
"is_module",
"(",
"obj",
",",
"cls",
... | 42.73913 | 0.016915 |
def get_file_info(obj, fieldname, default=None):
"""Extract file data from a file field
:param obj: Content object
:type obj: ATContentType/DexterityContentType
:param fieldname: Schema name of the field
:type fieldname: str/unicode
:returns: File data mapping
:rtype: dict
"""
# ex... | [
"def",
"get_file_info",
"(",
"obj",
",",
"fieldname",
",",
"default",
"=",
"None",
")",
":",
"# extract the file field from the object if omitted",
"field",
"=",
"get_field",
"(",
"obj",
",",
"fieldname",
")",
"# get the value with the fieldmanager",
"fm",
"=",
"IFiel... | 26.757576 | 0.001093 |
def push(self, filename):
"""Push a PLY lexer on the stack to parse filename."""
self.lexer.qasm_file = self.filename
self.lexer.qasm_line = self.lineno
self.stack.append(self.lexer)
self.__mklexer__(filename) | [
"def",
"push",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"lexer",
".",
"qasm_file",
"=",
"self",
".",
"filename",
"self",
".",
"lexer",
".",
"qasm_line",
"=",
"self",
".",
"lineno",
"self",
".",
"stack",
".",
"append",
"(",
"self",
".",
... | 40.666667 | 0.008032 |
def organization_field_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organization_fields#show-organization-field"
api_path = "/api/v2/organization_fields/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | [
"def",
"organization_field_show",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/organization_fields/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"call",
"... | 58.6 | 0.010101 |
def merge_and_fit(self, segment):
""" Merges another segment with this one, ordering the points based on a
distance heuristic
Args:
segment (:obj:`Segment`): Segment to merge with
Returns:
:obj:`Segment`: self
"""
self.points = sort_segment_po... | [
"def",
"merge_and_fit",
"(",
"self",
",",
"segment",
")",
":",
"self",
".",
"points",
"=",
"sort_segment_points",
"(",
"self",
".",
"points",
",",
"segment",
".",
"points",
")",
"return",
"self"
] | 33 | 0.008043 |
def _parse_info(self, data):
"""Parse the first line of a GNTP message to get security and other info values
:param string data: GNTP Message
:return dict: Parsed GNTP Info line
"""
match = GNTP_INFO_LINE.match(data)
if not match:
raise errors.ParseError('ERROR_PARSING_INFO_LINE')
info = match.grou... | [
"def",
"_parse_info",
"(",
"self",
",",
"data",
")",
":",
"match",
"=",
"GNTP_INFO_LINE",
".",
"match",
"(",
"data",
")",
"if",
"not",
"match",
":",
"raise",
"errors",
".",
"ParseError",
"(",
"'ERROR_PARSING_INFO_LINE'",
")",
"info",
"=",
"match",
".",
"... | 24.235294 | 0.03271 |
def _get_http_crl_distribution_points(self, crl_distribution_points):
"""
Fetches the DistributionPoint object for non-relative, HTTP CRLs
referenced by the certificate
:param crl_distribution_points:
A CRLDistributionPoints object to grab the DistributionPoints from
... | [
"def",
"_get_http_crl_distribution_points",
"(",
"self",
",",
"crl_distribution_points",
")",
":",
"output",
"=",
"[",
"]",
"if",
"crl_distribution_points",
"is",
"None",
":",
"return",
"[",
"]",
"for",
"distribution_point",
"in",
"crl_distribution_points",
":",
"di... | 38.166667 | 0.001704 |
def error_handler(response, **kwargs):
"""Error Handler to surface 4XX and 5XX errors.
Attached as a callback hook on the Request object.
Parameters
response (requests.Response)
The HTTP response from an API request.
**kwargs
Arbitrary keyword arguments.
Raises
... | [
"def",
"error_handler",
"(",
"response",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"400",
"<=",
"response",
".",
"status_code",
"<=",
"499",
":",
"message",
"=",
"response",
".",
"json",
"(",
")",
"[",
"'error_description'",
"]",
"if",
"'error_description'"... | 34.888889 | 0.001033 |
def cli(obj, role, scopes, delete):
"""Add or delete role-to-permission lookup entry."""
client = obj['client']
if delete:
client.delete_perm(delete)
else:
if not role:
raise click.UsageError('Missing option "--role".')
if not scopes:
raise click.UsageErro... | [
"def",
"cli",
"(",
"obj",
",",
"role",
",",
"scopes",
",",
"delete",
")",
":",
"client",
"=",
"obj",
"[",
"'client'",
"]",
"if",
"delete",
":",
"client",
".",
"delete_perm",
"(",
"delete",
")",
"else",
":",
"if",
"not",
"role",
":",
"raise",
"click... | 33.0625 | 0.001838 |
def compile_sources(files, CompilerRunner_=None,
destdir=None, cwd=None,
keep_dir_struct=False,
per_file_kwargs=None,
**kwargs):
"""
Compile source code files to object files.
Parameters
----------
files: iterable of pa... | [
"def",
"compile_sources",
"(",
"files",
",",
"CompilerRunner_",
"=",
"None",
",",
"destdir",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"keep_dir_struct",
"=",
"False",
",",
"per_file_kwargs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_per_file_kwar... | 35.257576 | 0.000418 |
def get_base_naive(cls, name, ignore=''):
""" Checks a string for a possible base name of an object (no prefix, no suffix).
We need to do a full parse to make sure we've ruled out all the possible other parse queries
:param name: str, string that represents a possible name of an object
... | [
"def",
"get_base_naive",
"(",
"cls",
",",
"name",
",",
"ignore",
"=",
"''",
")",
":",
"return",
"cls",
".",
"_get_regex_search",
"(",
"name",
",",
"cls",
".",
"REGEX_BASENAME",
",",
"match_index",
"=",
"0",
",",
"ignore",
"=",
"ignore",
")"
] | 57.125 | 0.010776 |
def parse_swf (url_data):
"""Parse a SWF file for URLs."""
linkfinder = linkparse.swf_url_re.finditer
for mo in linkfinder(url_data.get_content()):
url = mo.group()
url_data.add_url(url) | [
"def",
"parse_swf",
"(",
"url_data",
")",
":",
"linkfinder",
"=",
"linkparse",
".",
"swf_url_re",
".",
"finditer",
"for",
"mo",
"in",
"linkfinder",
"(",
"url_data",
".",
"get_content",
"(",
")",
")",
":",
"url",
"=",
"mo",
".",
"group",
"(",
")",
"url_... | 34.833333 | 0.009346 |
def getFilesForName(name):
"""Get a list of module files for a filename, a module or package name,
or a directory.
"""
if not os.path.exists(name):
# check for glob chars
if containsAny(name, "*?[]"):
files = glob.glob(name)
list = []
for file in files... | [
"def",
"getFilesForName",
"(",
"name",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"name",
")",
":",
"# check for glob chars",
"if",
"containsAny",
"(",
"name",
",",
"\"*?[]\"",
")",
":",
"files",
"=",
"glob",
".",
"glob",
"(",
"name"... | 26.571429 | 0.001297 |
def smooth_image(image, sigma, sigma_in_physical_coordinates=True, FWHM=False, max_kernel_width=32):
"""
Smooth an image
ANTsR function: `smoothImage`
Arguments
---------
image
Image to smooth
sigma
Smoothing factor. Can be scalar, in which case the same sigma is... | [
"def",
"smooth_image",
"(",
"image",
",",
"sigma",
",",
"sigma_in_physical_coordinates",
"=",
"True",
",",
"FWHM",
"=",
"False",
",",
"max_kernel_width",
"=",
"32",
")",
":",
"if",
"image",
".",
"components",
"==",
"1",
":",
"return",
"_smooth_image_helper",
... | 33.47619 | 0.01244 |
def filtered(f):
'''
Decorator function that wraps functions returning pandas
dataframes, such that the dataframe is filtered
according to left and right bounds set.
'''
def _filter(f, self, *args, **kwargs):
frame = f(self, *args, **kwargs)
ret = type(self)(frame)
ret._... | [
"def",
"filtered",
"(",
"f",
")",
":",
"def",
"_filter",
"(",
"f",
",",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"frame",
"=",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"ret",
"=",
"type",
"(",
"s... | 28.8 | 0.001681 |
def automation_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/automations#delete-automation"
api_path = "/api/v2/automations/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, method="DELETE", **kwargs) | [
"def",
"automation_delete",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/automations/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"call",
"(",
"api_pat... | 56.4 | 0.01049 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.