text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def populate(self, compound_dict=None, x=1, y=1, z=1):
"""Expand lattice and create compound from lattice.
populate will expand lattice based on user input. The user must also
pass in a dictionary that contains the keys that exist in the
basis_dict. The corresponding Compound will be th... | [
"def",
"populate",
"(",
"self",
",",
"compound_dict",
"=",
"None",
",",
"x",
"=",
"1",
",",
"y",
"=",
"1",
",",
"z",
"=",
"1",
")",
":",
"error_dict",
"=",
"{",
"0",
":",
"'X'",
",",
"1",
":",
"'Y'",
",",
"2",
":",
"'Z'",
"}",
"try",
":",
... | 42.440945 | 0.001088 |
def rename(self, file_id, new_filename, session=None):
"""Renames the stored file with the specified file_id.
For example::
my_db = MongoClient().test
fs = GridFSBucket(my_db)
# Get _id of file to rename
file_id = fs.upload_from_stream("test_file", "data I want ... | [
"def",
"rename",
"(",
"self",
",",
"file_id",
",",
"new_filename",
",",
"session",
"=",
"None",
")",
":",
"result",
"=",
"self",
".",
"_files",
".",
"update_one",
"(",
"{",
"\"_id\"",
":",
"file_id",
"}",
",",
"{",
"\"$set\"",
":",
"{",
"\"filename\"",... | 39.785714 | 0.001753 |
def Alt_Fn(self, n, dl = 0):
"""Alt + Fn1~12 组合键
"""
self.Delay(dl)
self.keyboard.press_key(self.keyboard.alt_key)
self.keyboard.tap_key(self.keyboard.function_keys[n])
self.keyboard.release_key(self.keyboard.alt_key) | [
"def",
"Alt_Fn",
"(",
"self",
",",
"n",
",",
"dl",
"=",
"0",
")",
":",
"self",
".",
"Delay",
"(",
"dl",
")",
"self",
".",
"keyboard",
".",
"press_key",
"(",
"self",
".",
"keyboard",
".",
"alt_key",
")",
"self",
".",
"keyboard",
".",
"tap_key",
"(... | 37 | 0.015094 |
def get_values(self, idx):
"""
Return the variable values at the given indices
"""
if isinstance(idx, list):
idx = np.array(idx, dtype=int)
return self._data[:, idx] | [
"def",
"get_values",
"(",
"self",
",",
"idx",
")",
":",
"if",
"isinstance",
"(",
"idx",
",",
"list",
")",
":",
"idx",
"=",
"np",
".",
"array",
"(",
"idx",
",",
"dtype",
"=",
"int",
")",
"return",
"self",
".",
"_data",
"[",
":",
",",
"idx",
"]"
... | 26.375 | 0.009174 |
def trim(self):
"""
Trims data based on propensity score to create a subsample with
better covariate balance.
The default cutoff value is set to 0.1. To set a custom cutoff
value, modify the object attribute named cutoff directly.
This method should only be executed after the propensity score
has bee... | [
"def",
"trim",
"(",
"self",
")",
":",
"if",
"0",
"<",
"self",
".",
"cutoff",
"<=",
"0.5",
":",
"pscore",
"=",
"self",
".",
"raw_data",
"[",
"'pscore'",
"]",
"keep",
"=",
"(",
"pscore",
">=",
"self",
".",
"cutoff",
")",
"&",
"(",
"pscore",
"<=",
... | 30.214286 | 0.030928 |
def set(self, uri, content):
"""
Cache node content for uri.
No return.
"""
key, value = self._prepare_node(uri, content)
self._set(key, value) | [
"def",
"set",
"(",
"self",
",",
"uri",
",",
"content",
")",
":",
"key",
",",
"value",
"=",
"self",
".",
"_prepare_node",
"(",
"uri",
",",
"content",
")",
"self",
".",
"_set",
"(",
"key",
",",
"value",
")"
] | 26.428571 | 0.010471 |
def locus(args):
"""
%prog locus bamfile
Extract selected locus from a list of TREDs for validation, and run lobSTR.
"""
from jcvi.formats.sam import get_minibam
# See `Format-lobSTR-database.ipynb` for a list of TREDs for validation
INCLUDE = ["HD", "SBMA", "SCA1", "SCA2", "SCA8", "SCA17",... | [
"def",
"locus",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"sam",
"import",
"get_minibam",
"# See `Format-lobSTR-database.ipynb` for a list of TREDs for validation",
"INCLUDE",
"=",
"[",
"\"HD\"",
",",
"\"SBMA\"",
",",
"\"SCA1\"",
",",
"\"SCA2\"",
"... | 28.824561 | 0.000589 |
def job_delete(job_id):
'''Deletes the job together with its logs and metadata.
:param job_id: An identifier for the job
:type job_id: string
:statuscode 200: no error
:statuscode 403: not authorized to delete the job
:statuscode 404: the job could not be found
:statuscode 409: an error oc... | [
"def",
"job_delete",
"(",
"job_id",
")",
":",
"conn",
"=",
"db",
".",
"ENGINE",
".",
"connect",
"(",
")",
"job",
"=",
"db",
".",
"get_job",
"(",
"job_id",
")",
"if",
"not",
"job",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"'error'",
":",
"'j... | 32.857143 | 0.001056 |
def infer_call_result(self, caller, context=None):
"""infer what a class is returning when called"""
if (
self.is_subtype_of("%s.type" % (BUILTINS,), context)
and len(caller.args) == 3
):
result = self._infer_type_call(caller, context)
yield result... | [
"def",
"infer_call_result",
"(",
"self",
",",
"caller",
",",
"context",
"=",
"None",
")",
":",
"if",
"(",
"self",
".",
"is_subtype_of",
"(",
"\"%s.type\"",
"%",
"(",
"BUILTINS",
",",
")",
",",
"context",
")",
"and",
"len",
"(",
"caller",
".",
"args",
... | 40.375 | 0.002016 |
def to_df(self, variables=None, format='wide', fillna=np.nan, **kwargs):
''' Merge variables into a single pandas DataFrame.
Args:
variables (list): Optional list of column names to retain; if None,
all variables are returned.
format (str): Whether to return a Da... | [
"def",
"to_df",
"(",
"self",
",",
"variables",
"=",
"None",
",",
"format",
"=",
"'wide'",
",",
"fillna",
"=",
"np",
".",
"nan",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"variables",
"is",
"None",
":",
"variables",
"=",
"list",
"(",
"self",
".",
"... | 43.317073 | 0.001101 |
def _validate(self, data, owner=None):
"""Validate input data in returning an empty list if true.
:param data: data to validate with this schema.
:param Schema owner: schema owner.
:raises: Exception if the data is not validated.
"""
if isinstance(data, DynamicValue):
... | [
"def",
"_validate",
"(",
"self",
",",
"data",
",",
"owner",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"DynamicValue",
")",
":",
"data",
"=",
"data",
"(",
")",
"if",
"data",
"is",
"None",
"and",
"not",
"self",
".",
"nullable",
":"... | 35.075 | 0.001387 |
def to_int(d, key, default_to_zero=False, default=None, required=True):
"""Pull a value from the dict and convert to int
:param default_to_zero: If the value is None or empty, treat it as zero
:param default: If the value is missing in the dict use this default
"""
value = d.get(key) or default
... | [
"def",
"to_int",
"(",
"d",
",",
"key",
",",
"default_to_zero",
"=",
"False",
",",
"default",
"=",
"None",
",",
"required",
"=",
"True",
")",
":",
"value",
"=",
"d",
".",
"get",
"(",
"key",
")",
"or",
"default",
"if",
"(",
"value",
"in",
"[",
"\"\... | 34.533333 | 0.00188 |
def is_reversible(T, mu=None, tol=1e-15):
r"""
checks whether T is reversible in terms of given stationary distribution.
If no distribution is given, it will be calculated out of T.
performs follwing check:
:math:`\pi_i P_{ij} = \pi_j P_{ji}
Parameters
----------
T : scipy.sparse matrix... | [
"def",
"is_reversible",
"(",
"T",
",",
"mu",
"=",
"None",
",",
"tol",
"=",
"1e-15",
")",
":",
"if",
"not",
"is_transition_matrix",
"(",
"T",
",",
"tol",
")",
":",
"raise",
"ValueError",
"(",
"\"given matrix is not a valid transition matrix.\"",
")",
"T",
"="... | 25.771429 | 0.001068 |
def _getbins():
""" gets the right version of vsearch, muscle, and smalt
depending on linux vs osx """
# Return error if system is 32-bit arch.
# This is straight from the python docs:
# https://docs.python.org/2/library/platform.html#cross-platform
if not _sys.maxsize > 2**32:
_sys.exi... | [
"def",
"_getbins",
"(",
")",
":",
"# Return error if system is 32-bit arch.",
"# This is straight from the python docs:",
"# https://docs.python.org/2/library/platform.html#cross-platform",
"if",
"not",
"_sys",
".",
"maxsize",
">",
"2",
"**",
"32",
":",
"_sys",
".",
"exit",
... | 39.5375 | 0.002159 |
def run_process_with_timeout(
args,
filename_in=None,
filename_out=None,
filename_err=None,
cwd=None,
timeout=None,
sudo=None):
"""Execute the specified process but within a certain timeout.
@param args: the actuall process. This should be a list of strin... | [
"def",
"run_process_with_timeout",
"(",
"args",
",",
"filename_in",
"=",
"None",
",",
"filename_out",
"=",
"None",
",",
"filename_err",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"sudo",
"=",
"None",
")",
":",
"if",
"timeout"... | 37.950355 | 0.000182 |
def updatecache(filename, module_globals=None):
"""Update a cache entry and return its list of lines.
If something's wrong, print a message, discard the cache entry,
and return an empty list."""
if filename in cache:
del cache[filename]
if not filename or (filename.startswith('<') and filen... | [
"def",
"updatecache",
"(",
"filename",
",",
"module_globals",
"=",
"None",
")",
":",
"if",
"filename",
"in",
"cache",
":",
"del",
"cache",
"[",
"filename",
"]",
"if",
"not",
"filename",
"or",
"(",
"filename",
".",
"startswith",
"(",
"'<'",
")",
"and",
... | 34.161765 | 0.000418 |
def user_can_edit_news(user):
"""
Check if the user has permission to edit any of the registered NewsItem
types.
"""
newsitem_models = [model.get_newsitem_model()
for model in NEWSINDEX_MODEL_CLASSES]
if user.is_active and user.is_superuser:
# admin can edit news ... | [
"def",
"user_can_edit_news",
"(",
"user",
")",
":",
"newsitem_models",
"=",
"[",
"model",
".",
"get_newsitem_model",
"(",
")",
"for",
"model",
"in",
"NEWSINDEX_MODEL_CLASSES",
"]",
"if",
"user",
".",
"is_active",
"and",
"user",
".",
"is_superuser",
":",
"# adm... | 30.944444 | 0.001742 |
def get_markdown_levels(lines, levels=set((0, 1, 2, 3, 4, 5, 6))):
r""" Return a list of 2-tuples with a level integer for the heading levels
>>> get_markdown_levels('paragraph \n##bad\n# hello\n ### world\n')
[(0, 'paragraph '), (2, 'bad'), (0, '# hello'), (3, 'world')]
>>> get_markdown_levels('- bul... | [
"def",
"get_markdown_levels",
"(",
"lines",
",",
"levels",
"=",
"set",
"(",
"(",
"0",
",",
"1",
",",
"2",
",",
"3",
",",
"4",
",",
"5",
",",
"6",
")",
")",
")",
":",
"if",
"isinstance",
"(",
"levels",
",",
"(",
"int",
",",
"float",
",",
"base... | 39.612903 | 0.000795 |
def group_by_interpolate(df, x=None, y=None, group_by=None,
number_of_points=100, tidy=False,
individual_x_cols=False, header_name="Unit",
dx=10.0, generate_new_x=True):
"""Use this for generating wide format from long (tidy) data"""
ti... | [
"def",
"group_by_interpolate",
"(",
"df",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"group_by",
"=",
"None",
",",
"number_of_points",
"=",
"100",
",",
"tidy",
"=",
"False",
",",
"individual_x_cols",
"=",
"False",
",",
"header_name",
"=",
"\"Unit... | 30.515625 | 0.000496 |
def syncItems(self, client=None, clientId=None):
""" Returns an instance of :class:`plexapi.sync.SyncList` for specified client.
Parameters:
client (:class:`~plexapi.myplex.MyPlexDevice`): a client to query SyncItems for.
clientId (str): an identifier of a client to ... | [
"def",
"syncItems",
"(",
"self",
",",
"client",
"=",
"None",
",",
"clientId",
"=",
"None",
")",
":",
"if",
"client",
":",
"clientId",
"=",
"client",
".",
"clientIdentifier",
"elif",
"clientId",
"is",
"None",
":",
"clientId",
"=",
"X_PLEX_IDENTIFIER",
"data... | 43.166667 | 0.008816 |
def norm_squared(x, Mx=None, inner_product=ip_euclid):
'''Compute the norm^2 w.r.t. to a given scalar product.'''
assert(len(x.shape) == 2)
if Mx is None:
rho = inner_product(x, x)
else:
assert(len(Mx.shape) == 2)
rho = inner_product(x, Mx)
if rho.shape == (1, 1):
if... | [
"def",
"norm_squared",
"(",
"x",
",",
"Mx",
"=",
"None",
",",
"inner_product",
"=",
"ip_euclid",
")",
":",
"assert",
"(",
"len",
"(",
"x",
".",
"shape",
")",
"==",
"2",
")",
"if",
"Mx",
"is",
"None",
":",
"rho",
"=",
"inner_product",
"(",
"x",
",... | 36.733333 | 0.00177 |
def remote_is_append_blob(self):
# type: (Descriptor) -> bool
"""Remote destination is an Azure Append Blob
:param Descriptor self: this
:rtype: bool
:return: remote is an Azure Append Blob
"""
return self.entity.mode == blobxfer.models.azure.StorageModes.Append | [
"def",
"remote_is_append_blob",
"(",
"self",
")",
":",
"# type: (Descriptor) -> bool",
"return",
"self",
".",
"entity",
".",
"mode",
"==",
"blobxfer",
".",
"models",
".",
"azure",
".",
"StorageModes",
".",
"Append"
] | 38.875 | 0.009434 |
def _with_loc(f: W) -> W:
"""Wrap a reader function in a decorator to supply line and column
information along with relevant forms."""
@functools.wraps(f)
def with_lineno_and_col(ctx):
meta = lmap.map(
{READER_LINE_KW: ctx.reader.line, READER_COL_KW: ctx.reader.col}
)
... | [
"def",
"_with_loc",
"(",
"f",
":",
"W",
")",
"->",
"W",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"with_lineno_and_col",
"(",
"ctx",
")",
":",
"meta",
"=",
"lmap",
".",
"map",
"(",
"{",
"READER_LINE_KW",
":",
"ctx",
".",
"reader",
... | 29.75 | 0.002037 |
def cleave_sequence(input_layer, unroll=None):
"""Cleaves a tensor into a sequence, this is the inverse of squash.
Recurrent methods unroll across an array of Tensors with each one being a
timestep. This cleaves the first dim so that each it is an array of Tensors.
It is the inverse of squash_sequence.
Arg... | [
"def",
"cleave_sequence",
"(",
"input_layer",
",",
"unroll",
"=",
"None",
")",
":",
"if",
"unroll",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'You must set unroll either here or in the defaults.'",
")",
"shape",
"=",
"input_layer",
".",
"shape",
"if",
"shape... | 34 | 0.010534 |
def items(self, raw = False):
"""Like `items` for dicts but with a `raw` option
# Parameters
_raw_ : `optional [bool]`
> Default `False`, if `True` the `KeysView` contains the raw values as the values
# Returns
`KeysView`
> The key-value pairs of the record
... | [
"def",
"items",
"(",
"self",
",",
"raw",
"=",
"False",
")",
":",
"if",
"raw",
":",
"return",
"self",
".",
"_fieldDict",
".",
"items",
"(",
")",
"else",
":",
"return",
"collections",
".",
"abc",
".",
"Mapping",
".",
"items",
"(",
"self",
")"
] | 23.210526 | 0.010893 |
def make_series(x, *args, **kwargs):
"""Coerce a provided array/sequence/generator into a pandas.Series object
FIXME: Deal with CSR, COO, DOK and other sparse matrices like this:
pd.Series(csr.toarray()[:,0])
or, if csr.shape[1] == 2
pd.Series(csr.toarray()[:,1], index=csr.toarray()[:,0])... | [
"def",
"make_series",
"(",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"pd",
".",
"Series",
")",
":",
"return",
"x",
"try",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"'pk'",
"not",
... | 35.576923 | 0.002104 |
def from_web_element(self, web_element):
"""
Store reference to a WebElement instance representing the element on the DOM.
Use it when an instance of WebElement has already been created (e.g. as the result of find_element) and
you want to create a UIComponent out of it withou... | [
"def",
"from_web_element",
"(",
"self",
",",
"web_element",
")",
":",
"if",
"isinstance",
"(",
"web_element",
",",
"WebElement",
")",
"is",
"not",
"True",
":",
"raise",
"TypeError",
"(",
"\"web_element parameter is not of type WebElement.\"",
")",
"self",
".",
"_w... | 55.181818 | 0.008104 |
def merge_paths(paths, weights=None):
"""
Zip together sorted lists.
>>> paths = [[1, 2, 3], [1, 3, 4], [2, 4, 5]]
>>> G = merge_paths(paths)
>>> nx.topological_sort(G)
[1, 2, 3, 4, 5]
>>> paths = [[1, 2, 3, 4], [1, 2, 3, 2, 4]]
>>> G = merge_paths(paths, weights=(1, 2))
>>> nx.topo... | [
"def",
"merge_paths",
"(",
"paths",
",",
"weights",
"=",
"None",
")",
":",
"G",
"=",
"make_paths",
"(",
"paths",
",",
"weights",
"=",
"weights",
")",
"G",
"=",
"reduce_paths",
"(",
"G",
")",
"return",
"G"
] | 26.5625 | 0.002273 |
def Tethering_unbind(self, port):
"""
Function path: Tethering.unbind
Domain: Tethering
Method name: unbind
Parameters:
Required arguments:
'port' (type: integer) -> Port number to unbind.
No return value.
Description: Request browser port unbinding.
"""
assert isinstance(port, (in... | [
"def",
"Tethering_unbind",
"(",
"self",
",",
"port",
")",
":",
"assert",
"isinstance",
"(",
"port",
",",
"(",
"int",
",",
")",
")",
",",
"\"Argument 'port' must be of type '['int']'. Received type: '%s'\"",
"%",
"type",
"(",
"port",
")",
"subdom_funcs",
"=",
"se... | 27.5 | 0.048828 |
def lint(fix_imports):
"""
Run flake8.
"""
from glob import glob
from subprocess import call
# FIXME: should support passing these in an option
skip = [
'ansible',
'db',
'flask_sessions',
'node_modules',
'requirements',
]
root_files = glob('*.... | [
"def",
"lint",
"(",
"fix_imports",
")",
":",
"from",
"glob",
"import",
"glob",
"from",
"subprocess",
"import",
"call",
"# FIXME: should support passing these in an option",
"skip",
"=",
"[",
"'ansible'",
",",
"'db'",
",",
"'flask_sessions'",
",",
"'node_modules'",
"... | 26.866667 | 0.001198 |
def eaSimpleConverge(population, toolbox, cxpb, mutpb, ngen, stats=None,
halloffame=None, callback=None, verbose=True):
"""This algorithm reproduce the simplest evolutionary algorithm as
presented in chapter 7 of [Back2000]_.
Modified to allow checking if there is no change for ngen, a... | [
"def",
"eaSimpleConverge",
"(",
"population",
",",
"toolbox",
",",
"cxpb",
",",
"mutpb",
",",
"ngen",
",",
"stats",
"=",
"None",
",",
"halloffame",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"# Evaluate the individual... | 36.253968 | 0.000426 |
def get_node(self, key):
"""Delegate to our current "value provider" for the node belonging to this key."""
if key in self.names:
return self.values.get_member_node(key) if hasattr(self.values, 'get_member_node') else None
return self.parent.get_node(key) | [
"def",
"get_node",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"names",
":",
"return",
"self",
".",
"values",
".",
"get_member_node",
"(",
"key",
")",
"if",
"hasattr",
"(",
"self",
".",
"values",
",",
"'get_member_node'",
")",
... | 53.8 | 0.014652 |
def _build_template_map(cookbook, cookbook_name, stencil):
"""Build a map of variables for this generated cookbook and stencil.
Get template variables from stencil option values, adding the default ones
like cookbook and cookbook year.
"""
template_map = {
'cookbook': {"name": cookbook_name... | [
"def",
"_build_template_map",
"(",
"cookbook",
",",
"cookbook_name",
",",
"stencil",
")",
":",
"template_map",
"=",
"{",
"'cookbook'",
":",
"{",
"\"name\"",
":",
"cookbook_name",
"}",
",",
"'options'",
":",
"stencil",
"[",
"'options'",
"]",
"}",
"# Cookbooks m... | 39.608696 | 0.001072 |
def _cassists_any(self,dc,dt,dt2,name,nodiag=False,memlimit=-1):
"""Calculates probability of gene i regulating gene j with continuous anchor data assisted method,
with multiple tests, by converting log likelihoods into probabilities per A for all B.
dc: numpy.ndarray(nt,ns,dtype=ftype(='f4' by default)) Continuous ... | [
"def",
"_cassists_any",
"(",
"self",
",",
"dc",
",",
"dt",
",",
"dt2",
",",
"name",
",",
"nodiag",
"=",
"False",
",",
"memlimit",
"=",
"-",
"1",
")",
":",
"if",
"self",
".",
"lib",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Not initialized.\""... | 58.152778 | 0.046501 |
def serve(content):
"""Write content to a temp file and serve it in browser"""
temp_folder = tempfile.gettempdir()
temp_file_name = tempfile.gettempprefix() + str(uuid.uuid4()) + ".html"
# Generate a file path with a random name in temporary dir
temp_file_path = os.path.join(temp_folder, temp_file_n... | [
"def",
"serve",
"(",
"content",
")",
":",
"temp_folder",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
"temp_file_name",
"=",
"tempfile",
".",
"gettempprefix",
"(",
")",
"+",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"+",
"\".html\"",
"# Generate ... | 33.1 | 0.001468 |
def getNetworkSummary(self, suid, verbose=None):
"""
Returns summary of collection containing the specified network.
:param suid: Cytoscape Collection/Subnetwork SUID
:param verbose: print more
:returns: 200: successful operation
"""
surl=self.___url
sv... | [
"def",
"getNetworkSummary",
"(",
"self",
",",
"suid",
",",
"verbose",
"=",
"None",
")",
":",
"surl",
"=",
"self",
".",
"___url",
"sv",
"=",
"surl",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"surl",
"=",
"surl",
".",
"rstrip",
"(",
"sv",
... | 33.733333 | 0.013462 |
def _derive_distinct_intervals(self, rows):
"""
Returns the set of distinct intervals in a row set.
:param list[dict[str,T]] rows: The rows set.
:rtype: set[(int,int)]
"""
ret = set()
for row in rows:
self._add_interval(ret, (row[self._key_start_date... | [
"def",
"_derive_distinct_intervals",
"(",
"self",
",",
"rows",
")",
":",
"ret",
"=",
"set",
"(",
")",
"for",
"row",
"in",
"rows",
":",
"self",
".",
"_add_interval",
"(",
"ret",
",",
"(",
"row",
"[",
"self",
".",
"_key_start_date",
"]",
",",
"row",
"[... | 27.384615 | 0.008152 |
def dataCollector( self ):
"""
Returns a method or function that will be used to collect mime data \
for a list of tablewidgetitems. If set, the method should accept a \
single argument for a list of items and then return a QMimeData \
instance.
:usage |fro... | [
"def",
"dataCollector",
"(",
"self",
")",
":",
"func",
"=",
"None",
"if",
"(",
"self",
".",
"_dataCollectorRef",
")",
":",
"func",
"=",
"self",
".",
"_dataCollectorRef",
"(",
")",
"if",
"(",
"not",
"func",
")",
":",
"self",
".",
"_dataCollectorRef",
"=... | 39.181818 | 0.010566 |
def _parse_contract(self, player_info):
"""
Parse the player's contract.
Depending on the player's contract status, a contract table is located
at the bottom of the stats page and includes player wages by season. If
found, create a dictionary housing the wages by season.
... | [
"def",
"_parse_contract",
"(",
"self",
",",
"player_info",
")",
":",
"contract",
"=",
"{",
"}",
"salary_table",
"=",
"player_info",
"(",
"'table#br-salaries'",
")",
"for",
"row",
"in",
"salary_table",
"(",
"'tbody tr'",
")",
".",
"items",
"(",
")",
":",
"i... | 37.193548 | 0.001691 |
def popitem(self):
"""Pop an item from the dict."""
try:
item = dict.popitem(self)
return (item[0], item[1][0])
except KeyError, e:
raise BadRequestKeyError(str(e)) | [
"def",
"popitem",
"(",
"self",
")",
":",
"try",
":",
"item",
"=",
"dict",
".",
"popitem",
"(",
"self",
")",
"return",
"(",
"item",
"[",
"0",
"]",
",",
"item",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"except",
"KeyError",
",",
"e",
":",
"raise",
"B... | 31.142857 | 0.008929 |
def min_interval(self,name, alpha=_alpha, **kwargs):
"""
Calculate minimum interval for parameter.
"""
data = self.get(name, **kwargs)
return min_interval(data,alpha) | [
"def",
"min_interval",
"(",
"self",
",",
"name",
",",
"alpha",
"=",
"_alpha",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"self",
".",
"get",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
"return",
"min_interval",
"(",
"data",
",",
"alpha",
")"
] | 33.666667 | 0.024155 |
def get_section_key_line(self, data, key, opt_extension=':'):
"""Get the next section line for a given key.
:param data: the data to proceed
:param key: the key
:param opt_extension: an optional extension to delimit the opt value
"""
return super(GoogledocTools, self).g... | [
"def",
"get_section_key_line",
"(",
"self",
",",
"data",
",",
"key",
",",
"opt_extension",
"=",
"':'",
")",
":",
"return",
"super",
"(",
"GoogledocTools",
",",
"self",
")",
".",
"get_section_key_line",
"(",
"data",
",",
"key",
",",
"opt_extension",
")"
] | 39.666667 | 0.008219 |
def get_directory_modules(directory):
"""Return a list containing tuples of
e.g. ('__init__', 'example/import_test_project/__init__.py')
"""
if _local_modules and os.path.dirname(_local_modules[0][1]) == directory:
return _local_modules
if not os.path.isdir(directory):
# example/imp... | [
"def",
"get_directory_modules",
"(",
"directory",
")",
":",
"if",
"_local_modules",
"and",
"os",
".",
"path",
".",
"dirname",
"(",
"_local_modules",
"[",
"0",
"]",
"[",
"1",
"]",
")",
"==",
"directory",
":",
"return",
"_local_modules",
"if",
"not",
"os",
... | 33.857143 | 0.001368 |
def record(self, localStreamName, pathToFile, **kwargs):
"""
Records any inbound stream. The record command allows users to record
a stream that may not yet exist. When a new stream is brought into
the server, it is checked against a list of streams to be recorded.
Streams can b... | [
"def",
"record",
"(",
"self",
",",
"localStreamName",
",",
"pathToFile",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"protocol",
".",
"execute",
"(",
"'record'",
",",
"localStreamName",
"=",
"localStreamName",
",",
"pathToFile",
"=",
"pathToFil... | 42.1 | 0.000929 |
def copy_from_server_to_local(dataset_remote_dir, dataset_local_dir,
remote_fname, local_fname):
"""Copies a remote file locally.
Parameters
----------
remote_fname : str
Remote file to copy
local_fname : str
Path and name of the local copy to be made o... | [
"def",
"copy_from_server_to_local",
"(",
"dataset_remote_dir",
",",
"dataset_local_dir",
",",
"remote_fname",
",",
"local_fname",
")",
":",
"log",
".",
"debug",
"(",
"\"Copying file `{}` to a local directory `{}`.\"",
".",
"format",
"(",
"remote_fname",
",",
"dataset_loca... | 34.622642 | 0.00053 |
def _auto_adjust_panel_spans(dashboard):
'''Adjust panel spans to take up the available width.
For each group of panels that would be laid out on the same level, scale up
the unspecified panel spans to fill up the level.
'''
for row in dashboard.get('rows', []):
levels = []
current_... | [
"def",
"_auto_adjust_panel_spans",
"(",
"dashboard",
")",
":",
"for",
"row",
"in",
"dashboard",
".",
"get",
"(",
"'rows'",
",",
"[",
"]",
")",
":",
"levels",
"=",
"[",
"]",
"current_level",
"=",
"[",
"]",
"levels",
".",
"append",
"(",
"current_level",
... | 43 | 0.000711 |
def status(self, obj):
"""Get the wifi interface status."""
reply = self._send_cmd_to_wpas(obj['name'], 'STATUS', True)
result = reply.split('\n')
status = ''
for l in result:
if l.startswith('wpa_state='):
status = l[10:]
return stat... | [
"def",
"status",
"(",
"self",
",",
"obj",
")",
":",
"reply",
"=",
"self",
".",
"_send_cmd_to_wpas",
"(",
"obj",
"[",
"'name'",
"]",
",",
"'STATUS'",
",",
"True",
")",
"result",
"=",
"reply",
".",
"split",
"(",
"'\\n'",
")",
"status",
"=",
"''",
"fo... | 30.272727 | 0.008746 |
def evergreen_video(self, **kwargs):
"""Filter evergreen content to exclusively video content."""
eqs = self.evergreen(**kwargs)
eqs = eqs.filter(VideohubVideo())
return eqs | [
"def",
"evergreen_video",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"eqs",
"=",
"self",
".",
"evergreen",
"(",
"*",
"*",
"kwargs",
")",
"eqs",
"=",
"eqs",
".",
"filter",
"(",
"VideohubVideo",
"(",
")",
")",
"return",
"eqs"
] | 40.2 | 0.009756 |
def _get_resolved_alias_name(self, property_name, original_alias_value, intrinsics_resolver):
"""
Alias names can be supplied as an intrinsic function. This method tries to extract alias name from a reference
to a parameter. If it cannot completely resolve (ie. if a complex intrinsic function wa... | [
"def",
"_get_resolved_alias_name",
"(",
"self",
",",
"property_name",
",",
"original_alias_value",
",",
"intrinsics_resolver",
")",
":",
"# Try to resolve.",
"resolved_alias_name",
"=",
"intrinsics_resolver",
".",
"resolve_parameter_refs",
"(",
"original_alias_value",
")",
... | 60.73913 | 0.008457 |
def read(path, attribute, **kwargs):
'''
Read the given attributes on the given file/directory
:param str path: The file to get attributes from
:param str attribute: The attribute to read
:param bool hex: Return the values with forced hexadecimal values
:return: A string containing the value... | [
"def",
"read",
"(",
"path",
",",
"attribute",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"hex_",
"=",
"kwargs",
".",
"pop",
"(",
"'hex'",
",",
"False",
"... | 30.44186 | 0.00148 |
def get_network_by_id(self, network_id: int) -> Network:
"""Get a network from the database by its identifier."""
return self.session.query(Network).get(network_id) | [
"def",
"get_network_by_id",
"(",
"self",
",",
"network_id",
":",
"int",
")",
"->",
"Network",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Network",
")",
".",
"get",
"(",
"network_id",
")"
] | 59.333333 | 0.011111 |
def _create_regexp_filter(regex):
"""Returns a boolean function that filters strings based on a regular exp.
Args:
regex: A string describing the regexp to use.
Returns:
A function taking a string and returns True if any of its substrings
matches regex.
"""
# Warning: Note that python's regex lib... | [
"def",
"_create_regexp_filter",
"(",
"regex",
")",
":",
"# Warning: Note that python's regex library allows inputs that take",
"# exponential time. Time-limiting it is difficult. When we move to",
"# a true multi-tenant tensorboard server, the regexp implementation here",
"# would need to be repla... | 38.681818 | 0.012615 |
def _get_timestamp_tuple(ts):
"""
Internal method to get a timestamp tuple from a value.
Handles input being a datetime or a Timestamp.
"""
if isinstance(ts, datetime.datetime):
return Timestamp.from_datetime(ts).tuple()
elif isinstance(ts, Timestamp):
return ts
raise... | [
"def",
"_get_timestamp_tuple",
"(",
"ts",
")",
":",
"if",
"isinstance",
"(",
"ts",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"Timestamp",
".",
"from_datetime",
"(",
"ts",
")",
".",
"tuple",
"(",
")",
"elif",
"isinstance",
"(",
"ts",
",",
"T... | 36.4 | 0.008043 |
def send(self, diffTo, diffFrom):
""" Do a btrfs send. """
diff = self.toObj.diff(diffTo, diffFrom)
self._open(self.butterStore.send(diff)) | [
"def",
"send",
"(",
"self",
",",
"diffTo",
",",
"diffFrom",
")",
":",
"diff",
"=",
"self",
".",
"toObj",
".",
"diff",
"(",
"diffTo",
",",
"diffFrom",
")",
"self",
".",
"_open",
"(",
"self",
".",
"butterStore",
".",
"send",
"(",
"diff",
")",
")"
] | 40 | 0.01227 |
def write_tlv(data):
"""Convert a dict to TLV8 bytes."""
tlv = b''
for key, value in data.items():
tag = bytes([int(key)])
length = len(value)
pos = 0
# A tag with length > 255 is added multiple times and concatenated into
# one buffer when reading the TLV again.
... | [
"def",
"write_tlv",
"(",
"data",
")",
":",
"tlv",
"=",
"b''",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"tag",
"=",
"bytes",
"(",
"[",
"int",
"(",
"key",
")",
"]",
")",
"length",
"=",
"len",
"(",
"value",
")",
"po... | 29.333333 | 0.001835 |
def parse(url):
"""Parses a search URL."""
config = {}
url = urlparse.urlparse(url)
# Remove query strings.
path = url.path[1:]
path = path.split('?', 2)[0]
if url.scheme in SCHEMES:
config["ENGINE"] = SCHEMES[url.scheme]
if url.scheme in USES_URL:
config["URL"] = ur... | [
"def",
"parse",
"(",
"url",
")",
":",
"config",
"=",
"{",
"}",
"url",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"# Remove query strings.",
"path",
"=",
"url",
".",
"path",
"[",
"1",
":",
"]",
"path",
"=",
"path",
".",
"split",
"(",
"'?'",
... | 21.121951 | 0.002208 |
def get_urls(self):
"""
Add the entries view to urls.
"""
urls = super(FormAdmin, self).get_urls()
extra_urls = [
re_path("^(?P<form_id>\d+)/entries/$",
self.admin_site.admin_view(self.entries_view),
name="form_entries"),
re... | [
"def",
"get_urls",
"(",
"self",
")",
":",
"urls",
"=",
"super",
"(",
"FormAdmin",
",",
"self",
")",
".",
"get_urls",
"(",
")",
"extra_urls",
"=",
"[",
"re_path",
"(",
"\"^(?P<form_id>\\d+)/entries/$\"",
",",
"self",
".",
"admin_site",
".",
"admin_view",
"(... | 42.05 | 0.016279 |
async def unlock(self, device):
"""
Unlock the device if not already unlocked.
:param device: device object, block device path or mount path
:returns: whether the device is unlocked
"""
device = self._find_device(device)
if not self.is_handleable(device) or not d... | [
"async",
"def",
"unlock",
"(",
"self",
",",
"device",
")",
":",
"device",
"=",
"self",
".",
"_find_device",
"(",
"device",
")",
"if",
"not",
"self",
".",
"is_handleable",
"(",
"device",
")",
"or",
"not",
"device",
".",
"is_crypto",
":",
"self",
".",
... | 43.690476 | 0.001066 |
def value(self, name):
"""get value of a track at the current time"""
return self.tracks.get(name).row_value(self.controller.row) | [
"def",
"value",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"tracks",
".",
"get",
"(",
"name",
")",
".",
"row_value",
"(",
"self",
".",
"controller",
".",
"row",
")"
] | 47.666667 | 0.013793 |
def get_class(classname):
"""
Returns the class object associated with the dot-notation classname.
Taken from here: http://stackoverflow.com/a/452981
:param classname: the classname
:type classname: str
:return: the class object
:rtype: object
"""
parts = classname.split('.')
m... | [
"def",
"get_class",
"(",
"classname",
")",
":",
"parts",
"=",
"classname",
".",
"split",
"(",
"'.'",
")",
"module",
"=",
"\".\"",
".",
"join",
"(",
"parts",
"[",
":",
"-",
"1",
"]",
")",
"m",
"=",
"__import__",
"(",
"module",
")",
"for",
"comp",
... | 25.176471 | 0.002252 |
def remove_ip(self, IPAddress):
"""
Release the specified IP-address from the server.
"""
self.cloud_manager.release_ip(IPAddress.address)
self.ip_addresses.remove(IPAddress) | [
"def",
"remove_ip",
"(",
"self",
",",
"IPAddress",
")",
":",
"self",
".",
"cloud_manager",
".",
"release_ip",
"(",
"IPAddress",
".",
"address",
")",
"self",
".",
"ip_addresses",
".",
"remove",
"(",
"IPAddress",
")"
] | 34.833333 | 0.009346 |
def add_process(self, name, cmd, quiet=False, env=None, cwd=None):
"""
Add a process to this manager instance. The process will not be started
until :func:`~honcho.manager.Manager.loop` is called.
"""
assert name not in self._processes, "process names must be unique"
proc... | [
"def",
"add_process",
"(",
"self",
",",
"name",
",",
"cmd",
",",
"quiet",
"=",
"False",
",",
"env",
"=",
"None",
",",
"cwd",
"=",
"None",
")",
":",
"assert",
"name",
"not",
"in",
"self",
".",
"_processes",
",",
"\"process names must be unique\"",
"proc",... | 42.052632 | 0.002448 |
def clean_conditionally(node):
"""Remove the clean_el if it looks like bad content based on rules."""
if node.tag not in ('form', 'table', 'ul', 'div', 'p'):
return # this is not the tag we are looking for
weight = get_class_weight(node)
# content_score = LOOK up the content score for this nod... | [
"def",
"clean_conditionally",
"(",
"node",
")",
":",
"if",
"node",
".",
"tag",
"not",
"in",
"(",
"'form'",
",",
"'table'",
",",
"'ul'",
",",
"'div'",
",",
"'p'",
")",
":",
"return",
"# this is not the tag we are looking for",
"weight",
"=",
"get_class_weight",... | 37.921875 | 0.001205 |
def split_first(s, delims):
"""
Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input string.
Example::
>>> split_first('foo/bar?baz', '?/=')
('foo', '... | [
"def",
"split_first",
"(",
"s",
",",
"delims",
")",
":",
"min_idx",
"=",
"None",
"min_delim",
"=",
"None",
"for",
"d",
"in",
"delims",
":",
"idx",
"=",
"s",
".",
"find",
"(",
"d",
")",
"if",
"idx",
"<",
"0",
":",
"continue",
"if",
"min_idx",
"is"... | 26.354839 | 0.002361 |
def make_virtual_offset(block_start_offset, within_block_offset):
"""Compute a BGZF virtual offset from block start and within block offsets.
The BAM indexing scheme records read positions using a 64 bit
'virtual offset', comprising in C terms:
block_start_offset << 16 | within_block_offset
Here blo... | [
"def",
"make_virtual_offset",
"(",
"block_start_offset",
",",
"within_block_offset",
")",
":",
"if",
"within_block_offset",
"<",
"0",
"or",
"within_block_offset",
">=",
"65536",
":",
"raise",
"ValueError",
"(",
"\"Require 0 <= within_block_offset < 2**16, got %i\"",
"%",
... | 40.97561 | 0.001744 |
def apply_filters(query, args):
"""
Apply all QueryFilters, validating the querystring in the process.
"""
pre_joins = []
for querystring_key, filter_value in args.items(multi=True):
if querystring_key in filter_registry:
cls_inst = filter_registry[querystring_key]
qu... | [
"def",
"apply_filters",
"(",
"query",
",",
"args",
")",
":",
"pre_joins",
"=",
"[",
"]",
"for",
"querystring_key",
",",
"filter_value",
"in",
"args",
".",
"items",
"(",
"multi",
"=",
"True",
")",
":",
"if",
"querystring_key",
"in",
"filter_registry",
":",
... | 38.142857 | 0.001828 |
def wheregreater(self, fieldname, value):
"""
Returns a new DataTable with rows only where the value at
`fieldname` > `value`.
"""
return self.mask([elem > value for elem in self[fieldname]]) | [
"def",
"wheregreater",
"(",
"self",
",",
"fieldname",
",",
"value",
")",
":",
"return",
"self",
".",
"mask",
"(",
"[",
"elem",
">",
"value",
"for",
"elem",
"in",
"self",
"[",
"fieldname",
"]",
"]",
")"
] | 37.666667 | 0.008658 |
def update( self, jump ):
"""
Update the lattice state by accepting a specific jump
Args:
jump (Jump): The jump that has been accepted.
Returns:
None.
"""
atom = jump.initial_site.atom
dr = jump.dr( self.cell_lengths )
#print( "at... | [
"def",
"update",
"(",
"self",
",",
"jump",
")",
":",
"atom",
"=",
"jump",
".",
"initial_site",
".",
"atom",
"dr",
"=",
"jump",
".",
"dr",
"(",
"self",
".",
"cell_lengths",
")",
"#print( \"atom {} jumped from site {} to site {}\".format( atom.number, jump.initial_sit... | 37 | 0.012075 |
def acquire(self, username, password, frontend='headless'):
"""Acquire a Machine resource."""
with self._lock() as root_session:
for clone in self._clones:
# Search for a free clone
session = Session()
try:
clone.lock_machin... | [
"def",
"acquire",
"(",
"self",
",",
"username",
",",
"password",
",",
"frontend",
"=",
"'headless'",
")",
":",
"with",
"self",
".",
"_lock",
"(",
")",
"as",
"root_session",
":",
"for",
"clone",
"in",
"self",
".",
"_clones",
":",
"# Search for a free clone"... | 44.018519 | 0.001235 |
def aggregate(self, val1, val2):
"""Aggregate two event values."""
assert val1 is not None
assert val2 is not None
return self._aggregator(val1, val2) | [
"def",
"aggregate",
"(",
"self",
",",
"val1",
",",
"val2",
")",
":",
"assert",
"val1",
"is",
"not",
"None",
"assert",
"val2",
"is",
"not",
"None",
"return",
"self",
".",
"_aggregator",
"(",
"val1",
",",
"val2",
")"
] | 35.6 | 0.010989 |
def list_all_orders(cls, **kwargs):
"""List Orders
Return a list of Orders
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_orders(async=True)
>>> result = thread.get()
... | [
"def",
"list_all_orders",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_list_all_orders_with_http_info",
"(",
"*",
"... | 35.565217 | 0.002381 |
def get_checks(
target_type=None,
tags=None,
ruleset_name=None,
ruleset_file=None,
ruleset=None,
logging_level=logging.WARNING,
checks_paths=None,
skips=None,
):
"""
Get the sanity checks for the target.
:param skips: name of checks to skip
:param target_type: TargetType... | [
"def",
"get_checks",
"(",
"target_type",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"ruleset_name",
"=",
"None",
",",
"ruleset_file",
"=",
"None",
",",
"ruleset",
"=",
"None",
",",
"logging_level",
"=",
"logging",
".",
"WARNING",
",",
"checks_paths",
"=",... | 31.676471 | 0.001802 |
def freq_filt(bma):
"""
This is a framework for 2D FFT filtering. It has not be tested or finished - might be a dead end
See separate utility freq_analysis.py
"""
"""
Want to fit linear function to artifact line in freq space,
Then mask everything near that line at distances of ~5-200 pixel... | [
"def",
"freq_filt",
"(",
"bma",
")",
":",
"\"\"\"\n Want to fit linear function to artifact line in freq space,\n Then mask everything near that line at distances of ~5-200 pixels, \n Or whatever the maximum CCD artifact dimension happens to be, \n This will depend on scaling - consult CCD m... | 29.362069 | 0.015341 |
def setProxy(self, protocol="http"):
"""
Public method to set a proxy for the browser.
"""
# Setting proxy
try:
new = { protocol: self.proxies[protocol]}
self.br.set_proxies( new )
except:
# No proxy defined for that protocol
... | [
"def",
"setProxy",
"(",
"self",
",",
"protocol",
"=",
"\"http\"",
")",
":",
"# Setting proxy",
"try",
":",
"new",
"=",
"{",
"protocol",
":",
"self",
".",
"proxies",
"[",
"protocol",
"]",
"}",
"self",
".",
"br",
".",
"set_proxies",
"(",
"new",
")",
"e... | 29.090909 | 0.018182 |
def trim_display_field(self, value, max_length):
"""Return a value for display; if longer than max length, use ellipsis."""
if not value:
return ''
if len(value) > max_length:
return value[:max_length - 3] + '...'
return value | [
"def",
"trim_display_field",
"(",
"self",
",",
"value",
",",
"max_length",
")",
":",
"if",
"not",
"value",
":",
"return",
"''",
"if",
"len",
"(",
"value",
")",
">",
"max_length",
":",
"return",
"value",
"[",
":",
"max_length",
"-",
"3",
"]",
"+",
"'.... | 35.428571 | 0.011811 |
def _det_tc(detector_name, ra, dec, tc, ref_frame='geocentric'):
"""Returns the coalescence time of a signal in the given detector.
Parameters
----------
detector_name : string
The name of the detector, e.g., 'H1'.
ra : float
The right ascension of the signal, in radians.
dec : ... | [
"def",
"_det_tc",
"(",
"detector_name",
",",
"ra",
",",
"dec",
",",
"tc",
",",
"ref_frame",
"=",
"'geocentric'",
")",
":",
"if",
"ref_frame",
"==",
"detector_name",
":",
"return",
"tc",
"detector",
"=",
"Detector",
"(",
"detector_name",
")",
"if",
"ref_fra... | 35.333333 | 0.000918 |
def filter_label(label, replace_by_similar=True):
"""Some labels currently don't work together because of LaTeX naming
clashes. Those will be replaced by simple strings. """
bad_names = ['celsius', 'degree', 'ohm', 'venus', 'mars', 'astrosun',
'fullmoon', 'leftmoon', 'female', 'male', 'c... | [
"def",
"filter_label",
"(",
"label",
",",
"replace_by_similar",
"=",
"True",
")",
":",
"bad_names",
"=",
"[",
"'celsius'",
",",
"'degree'",
",",
"'ohm'",
",",
"'venus'",
",",
"'mars'",
",",
"'astrosun'",
",",
"'fullmoon'",
",",
"'leftmoon'",
",",
"'female'",... | 47.4375 | 0.001292 |
def array(shape, dtype=_np.float64, autolock=False):
"""Factory method for shared memory arrays supporting all numpy dtypes."""
assert _NP_AVAILABLE, "To use the shared array object, numpy must be available!"
if not isinstance(dtype, _np.dtype):
dtype = _np.dtype(dtype)
# Not bothering to transl... | [
"def",
"array",
"(",
"shape",
",",
"dtype",
"=",
"_np",
".",
"float64",
",",
"autolock",
"=",
"False",
")",
":",
"assert",
"_NP_AVAILABLE",
",",
"\"To use the shared array object, numpy must be available!\"",
"if",
"not",
"isinstance",
"(",
"dtype",
",",
"_np",
... | 55.823529 | 0.002073 |
def reordi(iorder, ndim, array):
"""
Re-order the elements of an integer array according to
a given order vector.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reordi_c.html
:param iorder: Order vector to be used to re-order array.
:type iorder: Array of ints
:param ndim: Dimensi... | [
"def",
"reordi",
"(",
"iorder",
",",
"ndim",
",",
"array",
")",
":",
"iorder",
"=",
"stypes",
".",
"toIntVector",
"(",
"iorder",
")",
"ndim",
"=",
"ctypes",
".",
"c_int",
"(",
"ndim",
")",
"array",
"=",
"stypes",
".",
"toIntVector",
"(",
"array",
")"... | 31.52381 | 0.001466 |
def delete_post(self, post_id):
"""
Delete the post defined by ``post_id``
:param post_id: The identifier corresponding to a post
:type post_id: int
:return: Returns True if the post was successfully deleted and False
otherwise.
"""
status = False
... | [
"def",
"delete_post",
"(",
"self",
",",
"post_id",
")",
":",
"status",
"=",
"False",
"success",
"=",
"0",
"post_id",
"=",
"_as_int",
"(",
"post_id",
")",
"with",
"self",
".",
"_engine",
".",
"begin",
"(",
")",
"as",
"conn",
":",
"try",
":",
"post_del... | 38.583333 | 0.001404 |
def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id):
"""Create a Campaign with a Shared Bidding Strategy.
Args:
client: AdWordsClient the client to run the example with.
bidding_strategy_id: string the bidding strategy ID to use.
budget_id: string the shared budget ID to use.
... | [
"def",
"CreateCampaignWithBiddingStrategy",
"(",
"client",
",",
"bidding_strategy_id",
",",
"budget_id",
")",
":",
"# Initialize appropriate service.",
"campaign_service",
"=",
"client",
".",
"GetService",
"(",
"'CampaignService'",
",",
"version",
"=",
"'v201809'",
")",
... | 29.130435 | 0.009386 |
def lessThan(self, leftIndex, rightIndex):
""" Returns true if the value of the item referred to by the given index left is less than
the value of the item referred to by the given index right, otherwise returns false.
"""
leftData = self.sourceModel().data(leftIndex, RegistryTable... | [
"def",
"lessThan",
"(",
"self",
",",
"leftIndex",
",",
"rightIndex",
")",
":",
"leftData",
"=",
"self",
".",
"sourceModel",
"(",
")",
".",
"data",
"(",
"leftIndex",
",",
"RegistryTableModel",
".",
"SORT_ROLE",
")",
"rightData",
"=",
"self",
".",
"sourceMod... | 56.5 | 0.015251 |
def pack_header_for_user(
self, user,
override_access_lifespan=None, override_refresh_lifespan=None,
**custom_claims
):
"""
Encodes a jwt token and packages it into a header dict for a given user
:param: user: The user to package the ... | [
"def",
"pack_header_for_user",
"(",
"self",
",",
"user",
",",
"override_access_lifespan",
"=",
"None",
",",
"override_refresh_lifespan",
"=",
"None",
",",
"*",
"*",
"custom_claims",
")",
":",
"token",
"=",
"self",
".",
"encode_jwt_token",
"(",
"user",
",",
"ov... | 52.133333 | 0.001883 |
def analyze_pages(file_name, char_margin=1.0):
"""
Input: the file path to the PDF file
Output: yields the layout object for each page in the PDF
"""
log = logging.getLogger(__name__)
# Open a PDF file.
with open(os.path.realpath(file_name), "rb") as fp:
# Create a PDF parser object ... | [
"def",
"analyze_pages",
"(",
"file_name",
",",
"char_margin",
"=",
"1.0",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"# Open a PDF file.",
"with",
"open",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"file_name",
")",
",",
... | 43.117647 | 0.001334 |
def add_subtask(self, task, params={}, **options):
"""Creates a new subtask and adds it to the parent task. Returns the full record
for the newly created subtask.
Parameters
----------
task : {Id} The task to add a subtask to.
[data] : {Object} Data for the request
... | [
"def",
"add_subtask",
"(",
"self",
",",
"task",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/tasks/%s/subtasks\"",
"%",
"(",
"task",
")",
"return",
"self",
".",
"client",
".",
"post",
"(",
"path",
",",
"params",
... | 38.090909 | 0.009324 |
def setQuery( self, query ):
"""
Assigns the query for this widget, loading the query builder tree with
the pertinent information.
:param query | <Query> || <QueryCompound> || None
"""
tree = self.uiQueryTREE
tree.blockSignals(True)
... | [
"def",
"setQuery",
"(",
"self",
",",
"query",
")",
":",
"tree",
"=",
"self",
".",
"uiQueryTREE",
"tree",
".",
"blockSignals",
"(",
"True",
")",
"tree",
".",
"setUpdatesEnabled",
"(",
"False",
")",
"tree",
".",
"clear",
"(",
")",
"# assign a top level query... | 34.133333 | 0.016144 |
def get_movies(self):
"""
Retrieves all the movies published by the artist
:return: List. Movies published by the artist
"""
return itunespy.lookup(id=self.artist_id, entity=itunespy.entities['movie'])[1:] | [
"def",
"get_movies",
"(",
"self",
")",
":",
"return",
"itunespy",
".",
"lookup",
"(",
"id",
"=",
"self",
".",
"artist_id",
",",
"entity",
"=",
"itunespy",
".",
"entities",
"[",
"'movie'",
"]",
")",
"[",
"1",
":",
"]"
] | 40 | 0.012245 |
def read_file(fname, *args, **kwargs):
"""Read data from a file saved in the standard IAMC format
or a table with year/value columns
"""
if not isstr(fname):
raise ValueError('reading multiple files not supported, '
'please use `pyam.IamDataFrame.append()`')
logger()... | [
"def",
"read_file",
"(",
"fname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isstr",
"(",
"fname",
")",
":",
"raise",
"ValueError",
"(",
"'reading multiple files not supported, '",
"'please use `pyam.IamDataFrame.append()`'",
")",
"logger",... | 47.692308 | 0.001582 |
def get(self):
"""
*get the conesearch object*
**Return:**
- ``conesearch``
.. todo::
- @review: when complete, clean get method
- @review: when complete add logging
"""
self.log.info('starting the ``get`` method')
# SEARCH ... | [
"def",
"get",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``get`` method'",
")",
"# SEARCH NED WITH SINGLE CONESEARCHES TO RETURN LIST OF MATCHED NAMES",
"names",
",",
"searchParams",
"=",
"self",
".",
"get_crossmatch_names",
"(",
"listOf... | 27.787879 | 0.002107 |
def _submit_request(self, url, params=None, data=None, headers=None,
method="GET"):
"""Submits the given request, and handles the errors appropriately.
Args:
url (str): the request to send.
params (dict): params to be passed along to get/post
... | [
"def",
"_submit_request",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"method",
"=",
"\"GET\"",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"{",
"}",
"if",
"self... | 40.363636 | 0.001649 |
def to_bytes(s, encoding=None, errors='strict'):
'''
Given bytes, bytearray, str, or unicode (python 2), return bytes (str for
python 2)
'''
if encoding is None:
# Try utf-8 first, and fall back to detected encoding
encoding = ('utf-8', __salt_system_encoding__)
if not isinstance... | [
"def",
"to_bytes",
"(",
"s",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"# Try utf-8 first, and fall back to detected encoding",
"encoding",
"=",
"(",
"'utf-8'",
",",
"__salt_system_encoding__",
")"... | 34.794118 | 0.000822 |
def mavloss(logfile):
'''work out signal loss times for a log file'''
print("Processing log %s" % filename)
mlog = mavutil.mavlink_connection(filename,
planner_format=args.planner,
notimestamps=args.notimestamps,
... | [
"def",
"mavloss",
"(",
"logfile",
")",
":",
"print",
"(",
"\"Processing log %s\"",
"%",
"filename",
")",
"mlog",
"=",
"mavutil",
".",
"mavlink_connection",
"(",
"filename",
",",
"planner_format",
"=",
"args",
".",
"planner",
",",
"notimestamps",
"=",
"args",
... | 37.694444 | 0.001437 |
def auto_model(layout, scan_length=None, one_vs_rest=False):
'''Create a simple default model for each of the tasks in a BIDSLayout.
Contrasts each trial type against all other trial types and trial types
at the run level and then uses t-tests at each other level present to
aggregate these results up.
... | [
"def",
"auto_model",
"(",
"layout",
",",
"scan_length",
"=",
"None",
",",
"one_vs_rest",
"=",
"False",
")",
":",
"base_name",
"=",
"split",
"(",
"layout",
".",
"root",
")",
"[",
"-",
"1",
"]",
"tasks",
"=",
"layout",
".",
"entities",
"[",
"'task'",
"... | 39.057692 | 0.00096 |
def load_world(filename):
"""
Load a world from the given HDF5 filename.
The return type is determined by ``ecell4_base.core.load_version_information``.
Parameters
----------
filename : str
A HDF5 filename.
Returns
-------
w : World
Return one from ``BDWorld``, ``EG... | [
"def",
"load_world",
"(",
"filename",
")",
":",
"import",
"ecell4_base",
"vinfo",
"=",
"ecell4_base",
".",
"core",
".",
"load_version_information",
"(",
"filename",
")",
"if",
"vinfo",
".",
"startswith",
"(",
"\"ecell4-bd\"",
")",
":",
"return",
"ecell4_base",
... | 34.885714 | 0.00239 |
def convert_examples_to_features(examples, tokenizer, max_seq_length,
doc_stride, max_query_length, is_training):
"""Loads a data file into a list of `InputBatch`s."""
unique_id = 1000000000
features = []
for (example_index, example) in enumerate(examples):
que... | [
"def",
"convert_examples_to_features",
"(",
"examples",
",",
"tokenizer",
",",
"max_seq_length",
",",
"doc_stride",
",",
"max_query_length",
",",
"is_training",
")",
":",
"unique_id",
"=",
"1000000000",
"features",
"=",
"[",
"]",
"for",
"(",
"example_index",
",",
... | 44.621118 | 0.00177 |
def save(d, output_file, indent=4, spacer=" ", quote='"', newlinechar="\n", end_comment=False, **kwargs):
"""
Write a dictionary to an output Mapfile on disk
Parameters
----------
d: dict
A Python dictionary based on the the mappyfile schema
output_file: string
The output filen... | [
"def",
"save",
"(",
"d",
",",
"output_file",
",",
"indent",
"=",
"4",
",",
"spacer",
"=",
"\" \"",
",",
"quote",
"=",
"'\"'",
",",
"newlinechar",
"=",
"\"\\n\"",
",",
"end_comment",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"map_string",
"=",
... | 28.886364 | 0.001522 |
def get_definition(self):
'''Returns the definition of the complex item'''
serialized = super(ComplexSchemaItem, self).serialize()
# Adjust entries in the serialization
del serialized['definition_name']
serialized['title'] = self.definition_name
properties = {}
... | [
"def",
"get_definition",
"(",
"self",
")",
":",
"serialized",
"=",
"super",
"(",
"ComplexSchemaItem",
",",
"self",
")",
".",
"serialize",
"(",
")",
"# Adjust entries in the serialization",
"del",
"serialized",
"[",
"'definition_name'",
"]",
"serialized",
"[",
"'ti... | 38.857143 | 0.001794 |
def ChiSquared(k, tag=None):
"""
A Chi-Squared random variate
Parameters
----------
k : int
The degrees of freedom of the distribution (must be greater than one)
"""
assert int(k) == k and k >= 1, 'Chi-Squared "k" must be an integer greater than 0'
return uv(ss.chi2(k), tag=... | [
"def",
"ChiSquared",
"(",
"k",
",",
"tag",
"=",
"None",
")",
":",
"assert",
"int",
"(",
"k",
")",
"==",
"k",
"and",
"k",
">=",
"1",
",",
"'Chi-Squared \"k\" must be an integer greater than 0'",
"return",
"uv",
"(",
"ss",
".",
"chi2",
"(",
"k",
")",
","... | 28.545455 | 0.009259 |
def random_pure_actions(nums_actions, random_state=None):
"""
Return a tuple of random pure actions (integers).
Parameters
----------
nums_actions : tuple(int)
Tuple of the numbers of actions, one for each player.
random_state : int or np.random.RandomState, optional
Random see... | [
"def",
"random_pure_actions",
"(",
"nums_actions",
",",
"random_state",
"=",
"None",
")",
":",
"random_state",
"=",
"check_random_state",
"(",
"random_state",
")",
"action_profile",
"=",
"tuple",
"(",
"[",
"random_state",
".",
"randint",
"(",
"num_actions",
")",
... | 30.576923 | 0.00122 |
def p_array(self,t):
"""expression : '{' commalist '}'
| kw_array '[' commalist ']'
"""
if len(t)==4: t[0] = ArrayLit(t[2].children)
elif len(t)==5: t[0] = ArrayLit(t[3].children)
else: raise NotImplementedError('unk_len',len(t)) # pragma: no cover | [
"def",
"p_array",
"(",
"self",
",",
"t",
")",
":",
"if",
"len",
"(",
"t",
")",
"==",
"4",
":",
"t",
"[",
"0",
"]",
"=",
"ArrayLit",
"(",
"t",
"[",
"2",
"]",
".",
"children",
")",
"elif",
"len",
"(",
"t",
")",
"==",
"5",
":",
"t",
"[",
"... | 40 | 0.031469 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.