text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def multifile_dataframe(paths=['urbanslang{}of4.csv'.format(i) for i in range(1, 5)], header=0, index_col=None):
"""Like pandas.read_csv, but loads and concatenates (df.append(df)s) DataFrames together"""
df = pd.DataFrame()
for p in paths:
df = df.append(read_csv(p, header=header, index_col=index_c... | [
"def",
"multifile_dataframe",
"(",
"paths",
"=",
"[",
"'urbanslang{}of4.csv'",
".",
"format",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"5",
")",
"]",
",",
"header",
"=",
"0",
",",
"index_col",
"=",
"None",
")",
":",
"df",
"=",
"pd",... | 56.625 | 29.75 |
def read_fwf(self, *args, **kwargs):
"""Fetch the target and pass through to pandas.read_fwf.
Don't provide the first argument of read_fwf(); it is supplied internally. """
import pandas
t = self.resolved_url.get_resource().get_target()
return pandas.read_fwf(t.fspath, *args, ... | [
"def",
"read_fwf",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"pandas",
"t",
"=",
"self",
".",
"resolved_url",
".",
"get_resource",
"(",
")",
".",
"get_target",
"(",
")",
"return",
"pandas",
".",
"read_fwf",
"(",
"t",... | 35.666667 | 19.666667 |
def make_char_data_file(do_it_anyway=False):
"""
Build the compressed data file 'char_classes.dat' and write it to the
current directory.
If you run this, run it in Python 3.7.0 or later. It will run in earlier
versions, but you won't get the Unicode 11 standard, leading to inconsistent
behavio... | [
"def",
"make_char_data_file",
"(",
"do_it_anyway",
"=",
"False",
")",
":",
"if",
"sys",
".",
"hexversion",
"<",
"0x030700f0",
"and",
"not",
"do_it_anyway",
":",
"raise",
"RuntimeError",
"(",
"\"This function should be run in Python 3.7.0 or later.\"",
")",
"cclasses",
... | 40.544444 | 15.877778 |
def attr_func(*attrs, **kwargs):
"""Creates an "attribute function" for given attribute name(s).
Resulting function will retrieve attributes with given names, in order,
from the object that has been passed to it.
For example, ``attr_func('a', 'b')(foo)`` yields the same as ``foo.a.b``
:param attrs... | [
"def",
"attr_func",
"(",
"*",
"attrs",
",",
"*",
"*",
"kwargs",
")",
":",
"ensure_argcount",
"(",
"attrs",
",",
"min_",
"=",
"1",
")",
"ensure_keyword_args",
"(",
"kwargs",
",",
"optional",
"=",
"(",
"'default'",
",",
")",
")",
"# preprocess argument list:... | 36.102041 | 17.816327 |
def cleanup_html(html):
""" This 'cleans' the HTML, meaning that any page structure is removed
(only the contents of <body> are used, if there is any <body).
Also <ins> and <del> tags are removed. """
match = _body_re.search(html)
if match:
html = html[match.end():]
match = _end_body_re... | [
"def",
"cleanup_html",
"(",
"html",
")",
":",
"match",
"=",
"_body_re",
".",
"search",
"(",
"html",
")",
"if",
"match",
":",
"html",
"=",
"html",
"[",
"match",
".",
"end",
"(",
")",
":",
"]",
"match",
"=",
"_end_body_re",
".",
"search",
"(",
"html"... | 35.416667 | 12.333333 |
def pypi_module_version_is_available(module, version):
"Check whether module==version is available on pypi"
# returns True/False (or None if failed to execute the check)
# using a hack that when passing "module==" w/ no version number to pip
# it "fails" and returns all the available versions in stderr... | [
"def",
"pypi_module_version_is_available",
"(",
"module",
",",
"version",
")",
":",
"# returns True/False (or None if failed to execute the check)",
"# using a hack that when passing \"module==\" w/ no version number to pip",
"# it \"fails\" and returns all the available versions in stderr",
"... | 41.35 | 20.85 |
def z_axis_rotation(theta):
"""Generates a 3x3 rotation matrix for a rotation of angle
theta about the z axis.
Parameters
----------
theta : float
amount to rotate, in radians
Returns
-------
:obj:`numpy.ndarray` of float
A random... | [
"def",
"z_axis_rotation",
"(",
"theta",
")",
":",
"R",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"-",
"np",
".",
"sin",
"(",
"theta",
")",
",",
"0",
"]",
",",
"[",
"np",
".",
"sin",
"(",
"theta",
")",... | 27.888889 | 15.722222 |
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 | 15.5 |
def read_docs(self, payloadType, els_client = None):
"""Fetches the list of documents associated with this entity from
api.elsevier.com. If need be, splits the requests in batches to
retrieve them all. Returns True if successful; else, False.
NOTE: this method requires elevated API pe... | [
"def",
"read_docs",
"(",
"self",
",",
"payloadType",
",",
"els_client",
"=",
"None",
")",
":",
"if",
"els_client",
":",
"self",
".",
"_client",
"=",
"els_client",
"elif",
"not",
"self",
".",
"client",
":",
"raise",
"ValueError",
"(",
"'''Entity object not cu... | 57.085714 | 25.628571 |
def get_build_info(api_instance, build_id=None,
keys=DEFAULT_BUILD_KEYS, wait=False):
""" print build info about a job """
build = (api_instance.get_build(build_id) if build_id
else api_instance.get_last_build())
output = ""
if wait:
build.block_until_complete()
... | [
"def",
"get_build_info",
"(",
"api_instance",
",",
"build_id",
"=",
"None",
",",
"keys",
"=",
"DEFAULT_BUILD_KEYS",
",",
"wait",
"=",
"False",
")",
":",
"build",
"=",
"(",
"api_instance",
".",
"get_build",
"(",
"build_id",
")",
"if",
"build_id",
"else",
"a... | 28.36 | 19.8 |
def RandomNormalInitializer(stddev=1e-2):
"""An initializer function for random normal coefficients."""
def init(shape, rng):
return (stddev * backend.random.normal(rng, shape)).astype('float32')
return init | [
"def",
"RandomNormalInitializer",
"(",
"stddev",
"=",
"1e-2",
")",
":",
"def",
"init",
"(",
"shape",
",",
"rng",
")",
":",
"return",
"(",
"stddev",
"*",
"backend",
".",
"random",
".",
"normal",
"(",
"rng",
",",
"shape",
")",
")",
".",
"astype",
"(",
... | 42.6 | 15.6 |
def auto_connect(handler, timeout=5, not_found=None, event_loop=None):
"""Short method for connecting to a device.
This is a convenience method that create an event loop, auto discovers
devices, picks the first device found, connects to it and passes it to a
user provided handler. An optional error han... | [
"def",
"auto_connect",
"(",
"handler",
",",
"timeout",
"=",
"5",
",",
"not_found",
"=",
"None",
",",
"event_loop",
"=",
"None",
")",
":",
"# A coroutine is used so we can connect to the device while being inside",
"# the event loop",
"async",
"def",
"_handle",
"(",
"l... | 39.612903 | 20.580645 |
def sort_args(args):
"""Put flags at the end"""
args = args.copy()
flags = [i for i in args if FLAGS_RE.match(i[1])]
for i in flags:
args.remove(i)
return args + flags | [
"def",
"sort_args",
"(",
"args",
")",
":",
"args",
"=",
"args",
".",
"copy",
"(",
")",
"flags",
"=",
"[",
"i",
"for",
"i",
"in",
"args",
"if",
"FLAGS_RE",
".",
"match",
"(",
"i",
"[",
"1",
"]",
")",
"]",
"for",
"i",
"in",
"flags",
":",
"args"... | 21 | 20.777778 |
def save_intraday(data: pd.DataFrame, ticker: str, dt, typ='TRADE'):
"""
Check whether data is done for the day and save
Args:
data: data
ticker: ticker
dt: date
typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]
Examples:
>>> os.environ['BBG_ROOT'] ... | [
"def",
"save_intraday",
"(",
"data",
":",
"pd",
".",
"DataFrame",
",",
"ticker",
":",
"str",
",",
"dt",
",",
"typ",
"=",
"'TRADE'",
")",
":",
"cur_dt",
"=",
"pd",
".",
"Timestamp",
"(",
"dt",
")",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"logger",
... | 34.553191 | 20.638298 |
def fit(self, X, y, cost_mat, sample_weight=None):
"""Build a Bagging ensemble of estimators from the training set (X, y).
Parameters
----------
X : {array-like, sparse matrix} of shape = [n_samples, n_features]
The training input samples. Sparse matrices are accepted only i... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"cost_mat",
",",
"sample_weight",
"=",
"None",
")",
":",
"random_state",
"=",
"check_random_state",
"(",
"self",
".",
"random_state",
")",
"# Convert data",
"# X, y = check_X_y(X, y, ['csr', 'csc', 'coo']) # Not i... | 37.23913 | 23.826087 |
def ip_addrs6(interface=None, include_loopback=False, cidr=None):
'''
Returns a list of IPv6 addresses assigned to the host.
interface
Only IP addresses from that interface will be returned.
include_loopback : False
Include loopback ::1 IPv6 address.
cidr
Describes subnet ... | [
"def",
"ip_addrs6",
"(",
"interface",
"=",
"None",
",",
"include_loopback",
"=",
"False",
",",
"cidr",
"=",
"None",
")",
":",
"addrs",
"=",
"salt",
".",
"utils",
".",
"network",
".",
"ip_addrs6",
"(",
"interface",
"=",
"interface",
",",
"include_loopback",... | 28.310345 | 25.965517 |
def run(self):
"""
Perform the actual QChem run.
Returns:
(subprocess.Popen) Used for monitoring.
"""
qclog = open(self.qclog_file, 'w')
p = subprocess.Popen(self.current_command, stdout=qclog)
return p | [
"def",
"run",
"(",
"self",
")",
":",
"qclog",
"=",
"open",
"(",
"self",
".",
"qclog_file",
",",
"'w'",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"self",
".",
"current_command",
",",
"stdout",
"=",
"qclog",
")",
"return",
"p"
] | 26.2 | 15.4 |
def get_by_number(self, number: int) -> Optional[DataObjectReplica]:
"""
Gets the data object replica in this collection with the given number. Will return `None` if such replica does
not exist.
:param number: the number of the data object replica to get
:return: the data object ... | [
"def",
"get_by_number",
"(",
"self",
",",
"number",
":",
"int",
")",
"->",
"Optional",
"[",
"DataObjectReplica",
"]",
":",
"return",
"self",
".",
"_data",
".",
"get",
"(",
"number",
",",
"None",
")"
] | 52.125 | 24.875 |
def ph_basename(self, ph_type):
"""
Return the base name for a placeholder of *ph_type* in this shape
collection. There is some variance between slide types, for example
a notes slide uses a different name for the body placeholder, so this
method can be overriden by subclasses.
... | [
"def",
"ph_basename",
"(",
"self",
",",
"ph_type",
")",
":",
"return",
"{",
"PP_PLACEHOLDER",
".",
"BITMAP",
":",
"'ClipArt Placeholder'",
",",
"PP_PLACEHOLDER",
".",
"BODY",
":",
"'Text Placeholder'",
",",
"PP_PLACEHOLDER",
".",
"CENTER_TITLE",
":",
"'Title'",
... | 52.333333 | 19.333333 |
def extract_traits(self, entity):
"""
Extract data required to classify entity.
:param object entity:
:return: namedtuple consisting of characteristic traits and match flag
:rtype: matchbox.box.Trait
"""
traits = getattr(entity, self._characteristic)
if t... | [
"def",
"extract_traits",
"(",
"self",
",",
"entity",
")",
":",
"traits",
"=",
"getattr",
"(",
"entity",
",",
"self",
".",
"_characteristic",
")",
"if",
"traits",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"traits",
",",
"Hashable",
")",
":",
"traits"... | 33.733333 | 17.066667 |
def set(self, *args, **kwargs):
'''
d.set(...) yields a copy of the IMap object d; the ... may be replaced with either
nothing (in which case d is returned) or a list of 0 or more dictionaries followed by a lsit
of zero or more keyword arguments. These dictionaries and keywords arguments... | [
"def",
"set",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"merge",
"(",
"args",
",",
"kwargs",
")",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"return",
"self",
"affs",
"=",
"self",
".",
"afferents",
"pln"... | 54.416667 | 25.083333 |
def _bisect_kmeans(X, n_clusters, n_trials, max_iter, tol):
""" Apply Bisecting Kmeans clustering
to reach n_clusters number of clusters
"""
membs = np.empty(shape=X.shape[0], dtype=int)
centers = dict() #np.empty(shape=(n_clusters,X.shape[1]), dtype=float)
sse_arr = dict() #-1.0*np.ones(sha... | [
"def",
"_bisect_kmeans",
"(",
"X",
",",
"n_clusters",
",",
"n_trials",
",",
"max_iter",
",",
"tol",
")",
":",
"membs",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
"int",
")",
"centers",
"=",
"d... | 41.6875 | 20.520833 |
def encrypt_file(file, keys=secretKeys()):
'''Encrypt file data with the same method as the Send browser/js client'''
key = keys.encryptKey
iv = keys.encryptIV
encData = tempfile.SpooledTemporaryFile(max_size=SPOOL_SIZE, mode='w+b')
cipher = Cryptodome.Cipher.AES.new(key, Cryptodome.Cipher.AES.MODE_... | [
"def",
"encrypt_file",
"(",
"file",
",",
"keys",
"=",
"secretKeys",
"(",
")",
")",
":",
"key",
"=",
"keys",
".",
"encryptKey",
"iv",
"=",
"keys",
".",
"encryptIV",
"encData",
"=",
"tempfile",
".",
"SpooledTemporaryFile",
"(",
"max_size",
"=",
"SPOOL_SIZE",... | 31.210526 | 23.210526 |
def convert_to_array(pmap, nsites, imtls, inner_idx=0):
"""
Convert the probability map into a composite array with header
of the form PGA-0.1, PGA-0.2 ...
:param pmap: probability map
:param nsites: total number of sites
:param imtls: a DictArray with IMT and levels
:returns: a composite a... | [
"def",
"convert_to_array",
"(",
"pmap",
",",
"nsites",
",",
"imtls",
",",
"inner_idx",
"=",
"0",
")",
":",
"lst",
"=",
"[",
"]",
"# build the export dtype, of the form PGA-0.1, PGA-0.2 ...",
"for",
"imt",
",",
"imls",
"in",
"imtls",
".",
"items",
"(",
")",
"... | 34.75 | 13.75 |
def create_request_url(self, interface, method, version, parameters):
"""Create the URL to submit to the Steam Web API
interface: Steam Web API interface containing methods.
method: The method to call.
version: The version of the method.
paramters: Parameters to supply to the me... | [
"def",
"create_request_url",
"(",
"self",
",",
"interface",
",",
"method",
",",
"version",
",",
"parameters",
")",
":",
"if",
"'format'",
"in",
"parameters",
":",
"parameters",
"[",
"'key'",
"]",
"=",
"self",
".",
"apikey",
"else",
":",
"parameters",
".",
... | 39.529412 | 17.117647 |
def codestr2rst(codestr, lang='python'):
"""Return reStructuredText code block from code string"""
code_directive = "\n.. code-block:: {0}\n\n".format(lang)
indented_block = indent(codestr, ' ' * 4)
return code_directive + indented_block | [
"def",
"codestr2rst",
"(",
"codestr",
",",
"lang",
"=",
"'python'",
")",
":",
"code_directive",
"=",
"\"\\n.. code-block:: {0}\\n\\n\"",
".",
"format",
"(",
"lang",
")",
"indented_block",
"=",
"indent",
"(",
"codestr",
",",
"' '",
"*",
"4",
")",
"return",
"c... | 49.8 | 5.6 |
def get_env_path(cls):
"""Returns PATH environment variable updated to run uwsgiconf in
(e.g. for virtualenv).
:rtype: str|unicode
"""
return os.path.dirname(Finder.python()) + os.pathsep + os.environ['PATH'] | [
"def",
"get_env_path",
"(",
"cls",
")",
":",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"Finder",
".",
"python",
"(",
")",
")",
"+",
"os",
".",
"pathsep",
"+",
"os",
".",
"environ",
"[",
"'PATH'",
"]"
] | 34.714286 | 17.428571 |
def _update_assessment_parts_map(self, part_list):
"""Updates the part map.
Called before question list gets updated if it is determined that the
sections assessmentPart map is out of date with the current part list.
"""
for part in part_list:
# perhaps look for a "... | [
"def",
"_update_assessment_parts_map",
"(",
"self",
",",
"part_list",
")",
":",
"for",
"part",
"in",
"part_list",
":",
"# perhaps look for a \"level offset\"?",
"level",
"=",
"part",
".",
"_level_in_section",
"# plus or minus \"level offset\"?",
"if",
"str",
"(",
"part"... | 45.5 | 21 |
def _set_zfcp_multipath(self):
"""sles"""
# modprobe DM multipath kernel module
modprobe = 'modprobe dm_multipath'
conf_file = '#blacklist {\n'
conf_file += '#\tdevnode \\"*\\"\n'
conf_file += '#}\n'
conf_cmd = 'echo -e "%s" > /etc/multipath.conf' % conf_file
... | [
"def",
"_set_zfcp_multipath",
"(",
"self",
")",
":",
"# modprobe DM multipath kernel module",
"modprobe",
"=",
"'modprobe dm_multipath'",
"conf_file",
"=",
"'#blacklist {\\n'",
"conf_file",
"+=",
"'#\\tdevnode \\\\\"*\\\\\"\\n'",
"conf_file",
"+=",
"'#}\\n'",
"conf_cmd",
"=",... | 38 | 6.833333 |
def split(cls, entry):
"""Split a declaration name into a (declaration, subpath) tuple.
Examples:
>>> DeclarationSet.split('foo__bar')
('foo', 'bar')
>>> DeclarationSet.split('foo')
('foo', None)
>>> DeclarationSet.split('foo__bar__baz')
('foo', 'bar__baz... | [
"def",
"split",
"(",
"cls",
",",
"entry",
")",
":",
"if",
"enums",
".",
"SPLITTER",
"in",
"entry",
":",
"return",
"entry",
".",
"split",
"(",
"enums",
".",
"SPLITTER",
",",
"1",
")",
"else",
":",
"return",
"(",
"entry",
",",
"None",
")"
] | 30.2 | 12.933333 |
def _run_xmlsec(self, com_list, extra_args):
"""
Common code to invoke xmlsec and parse the output.
:param com_list: Key-value parameter list for xmlsec
:param extra_args: Positional parameters to be appended after all
key-value parameters
:result: Whatever xmlsec wro... | [
"def",
"_run_xmlsec",
"(",
"self",
",",
"com_list",
",",
"extra_args",
")",
":",
"with",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.xml'",
",",
"delete",
"=",
"self",
".",
"_xmlsec_delete_tmpfiles",
")",
"as",
"ntf",
":",
"com_list",
".",
"extend",
"(",
... | 39.464286 | 18.321429 |
def visit_module(self, node):
"""
A interface will be called when visiting a module.
@param node: node of current module
"""
if not node.file_stream:
# Failed to open the module
return
isFirstLineOfComment = True
isDocString = False
... | [
"def",
"visit_module",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"node",
".",
"file_stream",
":",
"# Failed to open the module",
"return",
"isFirstLineOfComment",
"=",
"True",
"isDocString",
"=",
"False",
"lines",
"=",
"node",
".",
"stream",
"(",
")",
... | 40.707317 | 14.097561 |
def jobSetFields(self, jobID, fields, useConnectionID=True,
ignoreUnchanged=False):
""" Change the values of 1 or more fields in a job. Here, 'fields' is a
dict with the name/value pairs to change. The names are the public names of
the fields (camelBack, not the lower_case_only form as st... | [
"def",
"jobSetFields",
"(",
"self",
",",
"jobID",
",",
"fields",
",",
"useConnectionID",
"=",
"True",
",",
"ignoreUnchanged",
"=",
"False",
")",
":",
"# Form the sequecce of key=value strings that will go into the",
"# request",
"assignmentExpressions",
"=",
"','",
"."... | 38.843137 | 20.254902 |
def get_gfe(self, annotation, locus):
"""
creates GFE from a sequence annotation
:param locus: The gene locus
:type locus: ``str``
:param annotation: An sequence annotation object
:type annotation: ``List``
:rtype: ``List``
Returns:
The GFE ... | [
"def",
"get_gfe",
"(",
"self",
",",
"annotation",
",",
"locus",
")",
":",
"features",
"=",
"[",
"]",
"accessions",
"=",
"{",
"}",
"for",
"feat",
"in",
"annotation",
".",
"annotation",
":",
"if",
"isinstance",
"(",
"annotation",
".",
"annotation",
"[",
... | 44.792857 | 23.992857 |
def findCaller(self):
"""
Find the stack frame of the caller so that we can note the source
file name, line number and function name.
"""
f = currentframe()
#On some versions of IronPython, currentframe() returns None if
#IronPython isn't run with -X:Frames.
... | [
"def",
"findCaller",
"(",
"self",
")",
":",
"f",
"=",
"currentframe",
"(",
")",
"#On some versions of IronPython, currentframe() returns None if",
"#IronPython isn't run with -X:Frames.",
"if",
"f",
"is",
"not",
"None",
":",
"f",
"=",
"f",
".",
"f_back",
"rv",
"=",
... | 35.5 | 14.6 |
def register_hit_type(
self, title, description, reward, duration_hours, keywords, qualifications
):
"""Register HIT Type for this HIT and return the type's ID, which
is required for creating a HIT.
"""
reward = str(reward)
duration_secs = int(datetime.timedelta(hours... | [
"def",
"register_hit_type",
"(",
"self",
",",
"title",
",",
"description",
",",
"reward",
",",
"duration_hours",
",",
"keywords",
",",
"qualifications",
")",
":",
"reward",
"=",
"str",
"(",
"reward",
")",
"duration_secs",
"=",
"int",
"(",
"datetime",
".",
... | 37.421053 | 15.526316 |
def load(self, ds, verbose=False):
"""
Load a CLDF dataset into the database.
:param dataset:
:return:
"""
try:
self.fetchone('select ID from dataset')
except sqlite3.OperationalError:
self.create(force=True)
self.unload(ds)
... | [
"def",
"load",
"(",
"self",
",",
"ds",
",",
"verbose",
"=",
"False",
")",
":",
"try",
":",
"self",
".",
"fetchone",
"(",
"'select ID from dataset'",
")",
"except",
"sqlite3",
".",
"OperationalError",
":",
"self",
".",
"create",
"(",
"force",
"=",
"True",... | 41.580357 | 19.098214 |
def initialize(self, argv=None):
"""initialize the app"""
super(BaseParallelApplication, self).initialize(argv)
self.to_work_dir()
self.reinit_logging() | [
"def",
"initialize",
"(",
"self",
",",
"argv",
"=",
"None",
")",
":",
"super",
"(",
"BaseParallelApplication",
",",
"self",
")",
".",
"initialize",
"(",
"argv",
")",
"self",
".",
"to_work_dir",
"(",
")",
"self",
".",
"reinit_logging",
"(",
")"
] | 36 | 10.8 |
def recent_update_frequencies(self):
""" Returns the 10 most recent update frequencies.
The given frequencies are computed as short-term frequencies!
The 0th element of the list corresponds to the most recent frequency.
"""
return list(reversed([(1.0 / p) for p in numpy.diff(sel... | [
"def",
"recent_update_frequencies",
"(",
"self",
")",
":",
"return",
"list",
"(",
"reversed",
"(",
"[",
"(",
"1.0",
"/",
"p",
")",
"for",
"p",
"in",
"numpy",
".",
"diff",
"(",
"self",
".",
"_recent_updates",
")",
"]",
")",
")"
] | 47.857143 | 22 |
def process_document(self, doc):
"""
Add your code for processing the document
"""
descriptions = doc.select_segments("projects[*].description")
projects = doc.select_segments("projects[*]")
for d, p in zip(descriptions, projects):
# First phase of extracti... | [
"def",
"process_document",
"(",
"self",
",",
"doc",
")",
":",
"descriptions",
"=",
"doc",
".",
"select_segments",
"(",
"\"projects[*].description\"",
")",
"projects",
"=",
"doc",
".",
"select_segments",
"(",
"\"projects[*]\"",
")",
"for",
"d",
",",
"p",
"in",
... | 36.136364 | 17.5 |
def invert(self):
""" Invert the price (e.g. go from ``USD/BTS`` into ``BTS/USD``)
"""
tmp = self["quote"]
self["quote"] = self["base"]
self["base"] = tmp
if "for_sale" in self and self["for_sale"]:
self["for_sale"] = self.amount_class(
self["f... | [
"def",
"invert",
"(",
"self",
")",
":",
"tmp",
"=",
"self",
"[",
"\"quote\"",
"]",
"self",
"[",
"\"quote\"",
"]",
"=",
"self",
"[",
"\"base\"",
"]",
"self",
"[",
"\"base\"",
"]",
"=",
"tmp",
"if",
"\"for_sale\"",
"in",
"self",
"and",
"self",
"[",
"... | 36.636364 | 14.909091 |
def predict(self,param_dict):
""" predict new waveforms using multivar fit """
encoder_dict = self._designmatrix_object.encoder
X, col_names = self._designmatrix_object.run_encoder(param_dict, encoder_dict)
# compute predictions
Y_pred = self._compute_prediction(X)
return... | [
"def",
"predict",
"(",
"self",
",",
"param_dict",
")",
":",
"encoder_dict",
"=",
"self",
".",
"_designmatrix_object",
".",
"encoder",
"X",
",",
"col_names",
"=",
"self",
".",
"_designmatrix_object",
".",
"run_encoder",
"(",
"param_dict",
",",
"encoder_dict",
"... | 45.857143 | 15.285714 |
def element_screen_center(self, element):
"""
:returns: The center point of the element.
:rtype: class:`dict` with the field "left" set to the X
coordinate and the field "top" set to the Y
coordinate.
"""
pos = self.element_screen_position(element... | [
"def",
"element_screen_center",
"(",
"self",
",",
"element",
")",
":",
"pos",
"=",
"self",
".",
"element_screen_position",
"(",
"element",
")",
"size",
"=",
"element",
".",
"size",
"pos",
"[",
"\"top\"",
"]",
"+=",
"int",
"(",
"size",
"[",
"\"height\"",
... | 34.461538 | 12.461538 |
def malloc(func):
""" Decorator
Execute tracemalloc
"""
def _f(*args, **kwargs):
print("\n<<<---")
tracemalloc.start()
res = func(*args, **kwargs)
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
print("[ Top 10 ]")
... | [
"def",
"malloc",
"(",
"func",
")",
":",
"def",
"_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"\"\\n<<<---\"",
")",
"tracemalloc",
".",
"start",
"(",
")",
"res",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
... | 34.142857 | 13.952381 |
def create_user(self, claims):
"""
Create the user if it doesn't exist yet
Args:
claims (dict): claims from the access token
Returns:
django.contrib.auth.models.User: A Django user
"""
# Create the user
username_claim = settings.USERNAME_... | [
"def",
"create_user",
"(",
"self",
",",
"claims",
")",
":",
"# Create the user",
"username_claim",
"=",
"settings",
".",
"USERNAME_CLAIM",
"usermodel",
"=",
"get_user_model",
"(",
")",
"user",
",",
"created",
"=",
"usermodel",
".",
"objects",
".",
"get_or_create... | 31.619048 | 18.285714 |
def InverseGamma(alpha: vertex_constructor_param_types, beta: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
One to one constructor for mapping some shape of alpha and beta to
alpha matching shaped Inverse Gamma.
:param alpha: the alpha of the Inverse Gamma with either th... | [
"def",
"InverseGamma",
"(",
"alpha",
":",
"vertex_constructor_param_types",
",",
"beta",
":",
"vertex_constructor_param_types",
",",
"label",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Vertex",
":",
"return",
"Double",
"(",
"context",
".",
"jvm... | 68.777778 | 44.111111 |
def invoke(self, args, initial_invocation_data=None, out_file=None):
""" Invoke a command.
:param args: The arguments that represent the command
:type args: list, tuple
:param initial_invocation_data: Prime the in memory collection of key-value data for this invocation.
:type in... | [
"def",
"invoke",
"(",
"self",
",",
"args",
",",
"initial_invocation_data",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"from",
".",
"util",
"import",
"CommandResultItem",
"if",
"not",
"isinstance",
"(",
"args",
",",
"(",
"list",
",",
"tuple",
")... | 47.076923 | 21.115385 |
def main():
"""main program body"""
if len( sys.argv ) != 2:
print __doc__ % sys.argv[0]
sys.exit( 1 )
file = open( sys.argv[1], "w\n" )
write = file.write
count_sid = len( sid_standard_names )
# `mac_extras' contains the list of glyph names in the Macintosh standard
# encoding which are not ... | [
"def",
"main",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"!=",
"2",
":",
"print",
"__doc__",
"%",
"sys",
".",
"argv",
"[",
"0",
"]",
"sys",
".",
"exit",
"(",
"1",
")",
"file",
"=",
"open",
"(",
"sys",
".",
"argv",
"[",
"1",
... | 26.239669 | 26.082645 |
def fmod(x, y, context=None):
"""
Return ``x`` reduced modulo ``y``.
Returns the value of x - n * y, where n is the integer quotient of x
divided by y, rounded toward zero.
Special values are handled as described in Section F.9.7.1 of the ISO C99
standard: If x is infinite or y is zero, the re... | [
"def",
"fmod",
"(",
"x",
",",
"y",
",",
"context",
"=",
"None",
")",
":",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr",
".",
"mpfr_fmod",
",",
"(",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
",",
"BigFloat",
".",
... | 30.636364 | 20.454545 |
def alignment_chart(data):
"""Make the HighCharts HTML to plot the alignment rates """
keys = OrderedDict()
keys['reads_mapped'] = {'color': '#437bb1', 'name': 'Mapped'}
keys['reads_unmapped'] = {'color': '#b1084c', 'name': 'Unmapped'}
# Config for the plot
plot_conf = {
'id': 'samtools... | [
"def",
"alignment_chart",
"(",
"data",
")",
":",
"keys",
"=",
"OrderedDict",
"(",
")",
"keys",
"[",
"'reads_mapped'",
"]",
"=",
"{",
"'color'",
":",
"'#437bb1'",
",",
"'name'",
":",
"'Mapped'",
"}",
"keys",
"[",
"'reads_unmapped'",
"]",
"=",
"{",
"'color... | 36.357143 | 17.142857 |
def get_content_string(self):
""" Ge thet Clusterpoint response's content as a string. """
return ''.join([ET.tostring(element, encoding="utf-8", method="xml")
for element in list(self._content)]) | [
"def",
"get_content_string",
"(",
"self",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"ET",
".",
"tostring",
"(",
"element",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"method",
"=",
"\"xml\"",
")",
"for",
"element",
"in",
"list",
"(",
"self",
".",
... | 58.25 | 16.75 |
def keys(self):
"""
:returns: a list of usable keys
:rtype: list
"""
keys = list()
for attribute_name, type_instance in inspect.getmembers(self):
# ignore parameters with __ and if they are methods
if attribute_name.startswith('__') or inspect.... | [
"def",
"keys",
"(",
"self",
")",
":",
"keys",
"=",
"list",
"(",
")",
"for",
"attribute_name",
",",
"type_instance",
"in",
"inspect",
".",
"getmembers",
"(",
"self",
")",
":",
"# ignore parameters with __ and if they are methods",
"if",
"attribute_name",
".",
"st... | 21.789474 | 25.157895 |
def index_list(self):
'''
List all cube indexes
:param collection: cube name
:param owner: username of cube owner
'''
logger.info('Listing indexes')
_ix = {}
_i = self.inspector
for tbl in _i.get_table_names():
_ix.setdefault(tbl, [])
... | [
"def",
"index_list",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Listing indexes'",
")",
"_ix",
"=",
"{",
"}",
"_i",
"=",
"self",
".",
"inspector",
"for",
"tbl",
"in",
"_i",
".",
"get_table_names",
"(",
")",
":",
"_ix",
".",
"setdefault",
"(... | 26.866667 | 13.933333 |
def add_filepath(self, filepath, fullpath, copy=False):
"""
Bespoke function to add filepath & fullpath to manifest
object without hashing. Can defer hashing until all files are
added. Hashing all at once is much faster as overhead for
threading is spread over all files
"... | [
"def",
"add_filepath",
"(",
"self",
",",
"filepath",
",",
"fullpath",
",",
"copy",
"=",
"False",
")",
":",
"# Ignore directories",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"fullpath",
")",
":",
"return",
"False",
"# Ignore anything matching the ignore pattern... | 33.5 | 19.1875 |
def _packto(self, stream):
'''
Pack current struct into stream. For parser internal use.
:param stream: a buffered stream (File or BytesIO)
:return: packed bytes length
'''
#self._logger.log(logging.DEBUG, 'packing %r', self)
total_size = 0
... | [
"def",
"_packto",
"(",
"self",
",",
"stream",
")",
":",
"#self._logger.log(logging.DEBUG, 'packing %r', self)",
"total_size",
"=",
"0",
"current",
"=",
"self",
"while",
"current",
"is",
"not",
"None",
":",
"total_size",
"+=",
"current",
".",
"_parser",
".",
"pac... | 33.789474 | 17.368421 |
def _einsum_helper(input_shapes, output_shape, mesh_impl):
"""Returns slicewise function and reduced mesh dimensions.
Assumes the output shape contains no new dimensions.
Args:
input_shapes: a list of Shapes
output_shape: a Shape
mesh_impl: a MeshImpl
Returns:
einsum_slice_fn: a function from ... | [
"def",
"_einsum_helper",
"(",
"input_shapes",
",",
"output_shape",
",",
"mesh_impl",
")",
":",
"input_shape_union",
"=",
"_shape_union",
"(",
"input_shapes",
")",
"total_num_dims",
"=",
"input_shape_union",
".",
"ndims",
"# list of input shapes that contain all dimensions."... | 40.65 | 17.025 |
def store_nulldata(self, hexdata, wifs, change_address=None, txouts=None,
fee=10000, lock_time=0):
"""Store <hexdata> in blockchain and return new txid.
Utxos taken from <wifs> and change sent to <change_address>.
<wifs>: '["privatekey_in_wif_format", ...]'
"""
... | [
"def",
"store_nulldata",
"(",
"self",
",",
"hexdata",
",",
"wifs",
",",
"change_address",
"=",
"None",
",",
"txouts",
"=",
"None",
",",
"fee",
"=",
"10000",
",",
"lock_time",
"=",
"0",
")",
":",
"rawtx",
"=",
"self",
".",
"create_tx",
"(",
"txouts",
... | 52.272727 | 14.090909 |
def _set_axis_ticks(self, axis, ticks, log=False, rotation=0):
"""
Allows setting the ticks for a particular axis either with
a tuple of ticks, a tick locator object, an integer number
of ticks, a list of tuples containing positions and labels
or a list of positions. Also support... | [
"def",
"_set_axis_ticks",
"(",
"self",
",",
"axis",
",",
"ticks",
",",
"log",
"=",
"False",
",",
"rotation",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"ticks",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and",
"all",
"(",
"isinstance",
"(",
"l",
... | 43.90625 | 12.71875 |
def median(timeseries, segmentlength, **kwargs):
"""Calculate a PSD using Welch's method with a median average
"""
if scipy_version <= '1.1.9999':
raise ValueError(
"median average PSD estimation requires scipy >= 1.2.0",
)
kwargs.setdefault('average', 'median')
return we... | [
"def",
"median",
"(",
"timeseries",
",",
"segmentlength",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"scipy_version",
"<=",
"'1.1.9999'",
":",
"raise",
"ValueError",
"(",
"\"median average PSD estimation requires scipy >= 1.2.0\"",
",",
")",
"kwargs",
".",
"setdefault... | 39.111111 | 11.333333 |
def parse(self, stream):
"""Parses the keys + values from a config file."""
items = OrderedDict()
for i, line in enumerate(stream):
line = line.strip()
if not line or line[0] in ["#", ";", "["] or line.startswith("---"):
continue
white_space =... | [
"def",
"parse",
"(",
"self",
",",
"stream",
")",
":",
"items",
"=",
"OrderedDict",
"(",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"stream",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"not",
"line",
"or",
"line",
"[",... | 38.470588 | 20.411765 |
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_co... | [
"def",
"list_nodes_full",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_full function must be called with -f or --function.'",
")",
"if",
"not",
"conn",
":",
... | 30.434783 | 24.521739 |
def logsumexp(arr,axis=0):
"""Faster logsumexp?"""
minarr= numpy.amax(arr,axis=axis)
if axis == 1:
minarr= numpy.reshape(minarr,(arr.shape[0],1))
if axis == 0:
minminarr= numpy.tile(minarr,(arr.shape[0],1))
elif axis == 1:
minminarr= numpy.tile(minarr,(1,arr.shape[1]))
el... | [
"def",
"logsumexp",
"(",
"arr",
",",
"axis",
"=",
"0",
")",
":",
"minarr",
"=",
"numpy",
".",
"amax",
"(",
"arr",
",",
"axis",
"=",
"axis",
")",
"if",
"axis",
"==",
"1",
":",
"minarr",
"=",
"numpy",
".",
"reshape",
"(",
"minarr",
",",
"(",
"arr... | 38.375 | 18.6875 |
def calculate_gamma_matrix(magnetic_states, Omega=1, einsteinA=None,
numeric=True):
ur"""Calculate the matrix of decay between states.
This function calculates the matrix :math:`\gamma_{ij}` of decay rates
between states :math:`|i\rangle` and :math:`|j\rangle` (in the units
s... | [
"def",
"calculate_gamma_matrix",
"(",
"magnetic_states",
",",
"Omega",
"=",
"1",
",",
"einsteinA",
"=",
"None",
",",
"numeric",
"=",
"True",
")",
":",
"Ne",
"=",
"len",
"(",
"magnetic_states",
")",
"fine_states",
"=",
"[",
"]",
"fine_map",
"=",
"{",
"}",... | 31.488688 | 18.461538 |
def signif(self, digits=6):
"""
Round doubles/floats to the given number of significant digits.
:param int digits: Number of significant digits to retain.
:returns: new H2OFrame with rounded values from the original frame.
"""
return H2OFrame._expr(expr=ExprNode("signif"... | [
"def",
"signif",
"(",
"self",
",",
"digits",
"=",
"6",
")",
":",
"return",
"H2OFrame",
".",
"_expr",
"(",
"expr",
"=",
"ExprNode",
"(",
"\"signif\"",
",",
"self",
",",
"digits",
")",
",",
"cache",
"=",
"self",
".",
"_ex",
".",
"_cache",
")"
] | 44 | 24.5 |
def _get_mount_methods(self, disk_type):
"""Finds which mount methods are suitable for the specified disk type. Returns a list of all suitable mount
methods.
"""
if self.disk_mounter == 'auto':
methods = []
def add_method_if_exists(method):
if (me... | [
"def",
"_get_mount_methods",
"(",
"self",
",",
"disk_type",
")",
":",
"if",
"self",
".",
"disk_mounter",
"==",
"'auto'",
":",
"methods",
"=",
"[",
"]",
"def",
"add_method_if_exists",
"(",
"method",
")",
":",
"if",
"(",
"method",
"==",
"'avfs'",
"and",
"_... | 40.21875 | 11.21875 |
def to_dict(self):
"""Transform the date-range to a dict."""
d = {}
d['start'] = date_to_str(self.start)
d['end'] = date_to_str(self.end)
return d | [
"def",
"to_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"d",
"[",
"'start'",
"]",
"=",
"date_to_str",
"(",
"self",
".",
"start",
")",
"d",
"[",
"'end'",
"]",
"=",
"date_to_str",
"(",
"self",
".",
"end",
")",
"return",
"d"
] | 31 | 12.666667 |
def pack_apply_message(f, args, kwargs, buffer_threshold=MAX_BYTES, item_threshold=MAX_ITEMS):
"""Pack up a function, args, and kwargs to be sent over the wire.
Each element of args/kwargs will be canned for special treatment,
but inspection will not go any deeper than that.
Any object whose data is l... | [
"def",
"pack_apply_message",
"(",
"f",
",",
"args",
",",
"kwargs",
",",
"buffer_threshold",
"=",
"MAX_BYTES",
",",
"item_threshold",
"=",
"MAX_ITEMS",
")",
":",
"arg_bufs",
"=",
"list",
"(",
"chain",
".",
"from_iterable",
"(",
"serialize_object",
"(",
"arg",
... | 37.266667 | 25.466667 |
def coloured_network(network, setup, filename):
"""
Plots a coloured (hyper-)graph to a dot file
Parameters
----------
network : object
An object implementing a method `__plot__` which must return the `networkx.MultiDiGraph`_ instance to be coloured.
Typically, it will be an instanc... | [
"def",
"coloured_network",
"(",
"network",
",",
"setup",
",",
"filename",
")",
":",
"NODES_ATTR",
"=",
"{",
"'DEFAULT'",
":",
"{",
"'color'",
":",
"'black'",
",",
"'fillcolor'",
":",
"'white'",
",",
"'style'",
":",
"'filled, bold'",
",",
"'fontname'",
":",
... | 40.848485 | 27.030303 |
def get_keyvault(access_token, subscription_id, rgname, vault_name):
'''Gets details about the named key vault.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
vault_name (str): ... | [
"def",
"get_keyvault",
"(",
"access_token",
",",
"subscription_id",
",",
"rgname",
",",
"vault_name",
")",
":",
"endpoint",
"=",
"''",
".",
"join",
"(",
"[",
"get_rm_endpoint",
"(",
")",
",",
"'/subscriptions/'",
",",
"subscription_id",
",",
"'/resourcegroups/'"... | 40.833333 | 19.944444 |
def calc_signal_sum(self, measure='LFP'):
"""
Superimpose each cell's contribution to the compound population signal,
i.e., the population CSD or LFP
Parameters
----------
measure : str
{'LFP', 'CSD'}: Either 'LFP' or 'CSD'.
Returns
-------... | [
"def",
"calc_signal_sum",
"(",
"self",
",",
"measure",
"=",
"'LFP'",
")",
":",
"#compute the total LFP of cells on this RANK",
"if",
"self",
".",
"RANK_CELLINDICES",
".",
"size",
">",
"0",
":",
"for",
"i",
",",
"cellindex",
"in",
"enumerate",
"(",
"self",
".",... | 29.575 | 21.225 |
def _check_path(self, src, path_type, dest=None, force=False):
"""Check a new destination path in the archive.
Since it is possible for multiple plugins to collect the same
paths, and since plugins can now run concurrently, it is possible
for two threads to race in archive m... | [
"def",
"_check_path",
"(",
"self",
",",
"src",
",",
"path_type",
",",
"dest",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"dest",
"=",
"dest",
"or",
"self",
".",
"dest_path",
"(",
"src",
")",
"if",
"path_type",
"==",
"P_DIR",
":",
"dest_dir",
... | 45.216216 | 22.432432 |
def expand(sconf, cwd=None, parent=None):
"""Return config with shorthand and inline properties expanded.
This is necessary to keep the code in the :class:`WorkspaceBuilder` clean
and also allow for neat, short-hand configurations.
As a simple example, internally, tmuxp expects that config options
... | [
"def",
"expand",
"(",
"sconf",
",",
"cwd",
"=",
"None",
",",
"parent",
"=",
"None",
")",
":",
"# Note: cli.py will expand configs relative to project's config directory",
"# for the first cwd argument.",
"if",
"not",
"cwd",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",... | 36.15493 | 20.647887 |
def update_variogram_model(self, variogram_model, variogram_parameters=None,
variogram_function=None, nlags=6, weight=False,
anisotropy_scaling_y=1., anisotropy_scaling_z=1.,
anisotropy_angle_x=0., anisotropy_angle_y=0.,
... | [
"def",
"update_variogram_model",
"(",
"self",
",",
"variogram_model",
",",
"variogram_parameters",
"=",
"None",
",",
"variogram_function",
"=",
"None",
",",
"nlags",
"=",
"6",
",",
"weight",
"=",
"False",
",",
"anisotropy_scaling_y",
"=",
"1.",
",",
"anisotropy_... | 55.083969 | 22.793893 |
def configure_logging(verbosity):
'''configure logging via verbosity level of between 0 and 2 corresponding
to log levels warning, info and debug respectfully.'''
log_level = max(logging.DEBUG, logging.WARNING - logging.DEBUG*verbosity)
logging.basicConfig(
stream=sys.stderr, level=log_level,
... | [
"def",
"configure_logging",
"(",
"verbosity",
")",
":",
"log_level",
"=",
"max",
"(",
"logging",
".",
"DEBUG",
",",
"logging",
".",
"WARNING",
"-",
"logging",
".",
"DEBUG",
"*",
"verbosity",
")",
"logging",
".",
"basicConfig",
"(",
"stream",
"=",
"sys",
... | 38.142857 | 18.142857 |
def _get_or_add_image(self, image_file):
"""
Return an (rId, description, image_size) 3-tuple identifying the
related image part containing *image_file* and describing the image.
"""
image_part, rId = self.part.get_or_add_image_part(image_file)
desc, image_size = image_pa... | [
"def",
"_get_or_add_image",
"(",
"self",
",",
"image_file",
")",
":",
"image_part",
",",
"rId",
"=",
"self",
".",
"part",
".",
"get_or_add_image_part",
"(",
"image_file",
")",
"desc",
",",
"image_size",
"=",
"image_part",
".",
"desc",
",",
"image_part",
".",... | 47.25 | 15.5 |
def compute_avg_adj_deg(G):
r"""
Compute the average adjacency degree for each node.
The average adjacency degree is the average of the degrees of a node and
its neighbors.
Parameters
----------
G: Graph
Graph on which the statistic is extracted
"""
return np.sum(np.dot(G.A... | [
"def",
"compute_avg_adj_deg",
"(",
"G",
")",
":",
"return",
"np",
".",
"sum",
"(",
"np",
".",
"dot",
"(",
"G",
".",
"A",
",",
"G",
".",
"A",
")",
",",
"axis",
"=",
"1",
")",
"/",
"(",
"np",
".",
"sum",
"(",
"G",
".",
"A",
",",
"axis",
"="... | 27.076923 | 22.076923 |
def escape_ampersand(string):
"""
Quick convert unicode ampersand characters not associated with
a numbered entity or not starting with allowed characters to a plain &
"""
if not string:
return string
start_with_match = r"(\#x(....);|lt;|gt;|amp;)"
# The pattern below is match & ... | [
"def",
"escape_ampersand",
"(",
"string",
")",
":",
"if",
"not",
"string",
":",
"return",
"string",
"start_with_match",
"=",
"r\"(\\#x(....);|lt;|gt;|amp;)\"",
"# The pattern below is match & that is not immediately followed by #",
"string",
"=",
"re",
".",
"sub",
"(",
"r... | 39.636364 | 19.272727 |
def shutdown(self, channel=Channel.CHANNEL_ALL, shutdown_hardware=True):
"""
Shuts down all CAN interfaces and/or the hardware interface.
:param int channel:
CAN channel, to be used (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1` or
:data:`Channel.CHANNEL_ALL`)... | [
"def",
"shutdown",
"(",
"self",
",",
"channel",
"=",
"Channel",
".",
"CHANNEL_ALL",
",",
"shutdown_hardware",
"=",
"True",
")",
":",
"# shutdown each channel if it's initialized",
"for",
"_channel",
",",
"is_initialized",
"in",
"self",
".",
"_ch_is_initialized",
"."... | 49.25 | 22.75 |
def oh_my_zsh_auto_title():
"""Give warning and offer to fix ``DISABLE_AUTO_TITLE``.
see: https://github.com/robbyrussell/oh-my-zsh/pull/257
"""
if 'SHELL' in os.environ and 'zsh' in os.environ.get('SHELL'):
if os.path.exists(os.path.expanduser('~/.oh-my-zsh')):
# oh-my-zsh exists... | [
"def",
"oh_my_zsh_auto_title",
"(",
")",
":",
"if",
"'SHELL'",
"in",
"os",
".",
"environ",
"and",
"'zsh'",
"in",
"os",
".",
"environ",
".",
"get",
"(",
"'SHELL'",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"expan... | 37.954545 | 20.090909 |
def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=DEFAULT_SAVE_DIR, download_delay=15):
"""
Ensure that a setuptools version is installed.
Return None. Raise SystemExit if the requested version
or later cannot be installed.
"""
to_dir = os.path.abspa... | [
"def",
"use_setuptools",
"(",
"version",
"=",
"DEFAULT_VERSION",
",",
"download_base",
"=",
"DEFAULT_URL",
",",
"to_dir",
"=",
"DEFAULT_SAVE_DIR",
",",
"download_delay",
"=",
"15",
")",
":",
"to_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"to_dir",
")... | 33.378378 | 19.108108 |
def parse_range_header(self, header, resource_size):
"""
Parses a range header into a list of two-tuples (start, stop) where
`start` is the starting byte of the range (inclusive) and
`stop` is the ending byte position of the range (exclusive).
Args:
header (str): The... | [
"def",
"parse_range_header",
"(",
"self",
",",
"header",
",",
"resource_size",
")",
":",
"if",
"not",
"header",
"or",
"'='",
"not",
"in",
"header",
":",
"return",
"None",
"ranges",
"=",
"[",
"]",
"units",
",",
"range_",
"=",
"header",
".",
"split",
"("... | 33.897959 | 19 |
def change_class(self):
""" "on changing the classification label, update the "draw" text """
self.toolbarcenterframe.config(text="Draw: {}".format(self.config.solar_class_name[self.solar_class_var.get()])) | [
"def",
"change_class",
"(",
"self",
")",
":",
"self",
".",
"toolbarcenterframe",
".",
"config",
"(",
"text",
"=",
"\"Draw: {}\"",
".",
"format",
"(",
"self",
".",
"config",
".",
"solar_class_name",
"[",
"self",
".",
"solar_class_var",
".",
"get",
"(",
")",... | 73.333333 | 32.333333 |
def SInt(value, width):
"""
Convert a bitstring `value` of `width` bits to a signed integer
representation.
:param value: The value to convert.
:type value: int or long or BitVec
:param int width: The width of the bitstring to consider
:return: The converted value
:rtype int or long or ... | [
"def",
"SInt",
"(",
"value",
",",
"width",
")",
":",
"return",
"Operators",
".",
"ITEBV",
"(",
"width",
",",
"Bit",
"(",
"value",
",",
"width",
"-",
"1",
")",
"==",
"1",
",",
"GetNBits",
"(",
"value",
",",
"width",
")",
"-",
"2",
"**",
"width",
... | 35.428571 | 14 |
def _get_attribute_dimension(trait_name, mark_type=None):
"""Returns the dimension for the name of the trait for the specified mark.
If `mark_type` is `None`, then the `trait_name` is returned
as is.
Returns `None` if the `trait_name` is not valid for `mark_type`.
"""
if(mark_type is None):
... | [
"def",
"_get_attribute_dimension",
"(",
"trait_name",
",",
"mark_type",
"=",
"None",
")",
":",
"if",
"(",
"mark_type",
"is",
"None",
")",
":",
"return",
"trait_name",
"scale_metadata",
"=",
"mark_type",
".",
"class_traits",
"(",
")",
"[",
"'scales_metadata'",
... | 40.916667 | 19.666667 |
def update_or_create_all(cls, list_of_kwargs, keys=[]):
"""Batch method for updating a list of instances and
creating them if required
Args:
list_of_kwargs(list of dicts): A list of dicts where
each dict denotes the keyword args that you would pass
to... | [
"def",
"update_or_create_all",
"(",
"cls",
",",
"list_of_kwargs",
",",
"keys",
"=",
"[",
"]",
")",
":",
"objs",
"=",
"[",
"]",
"for",
"kwargs",
"in",
"list_of_kwargs",
":",
"filter_kwargs",
"=",
"subdict",
"(",
"kwargs",
",",
"keys",
")",
"if",
"filter_k... | 35.75 | 17.425 |
def clear_jobs(self, recursive=True):
"""Clear the self.jobs dictionary that contains information
about jobs associated with this `ScatterGather`
If recursive is True this will include jobs from all internal `Link`
"""
if recursive:
self._scatter_link.clear_jobs(recu... | [
"def",
"clear_jobs",
"(",
"self",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"recursive",
":",
"self",
".",
"_scatter_link",
".",
"clear_jobs",
"(",
"recursive",
")",
"self",
".",
"jobs",
".",
"clear",
"(",
")"
] | 38.222222 | 15.555556 |
def make_dir_structure(base_dir):
"""Make the build directory structure. """
def maybe_makedir(*args):
p = join(base_dir, *args)
if exists(p) and not isdir(p):
raise IOError("File '{}' exists but is not a directory ".format(p))
if not exists(p):
makedirs(p)
... | [
"def",
"make_dir_structure",
"(",
"base_dir",
")",
":",
"def",
"maybe_makedir",
"(",
"*",
"args",
")",
":",
"p",
"=",
"join",
"(",
"base_dir",
",",
"*",
"args",
")",
"if",
"exists",
"(",
"p",
")",
"and",
"not",
"isdir",
"(",
"p",
")",
":",
"raise",... | 24.5625 | 20.6875 |
def by_location(self, location, cc=None):
"""
Perform a Yelp Neighborhood API Search based on a location specifier.
Args:
location - textual location specifier of form: "address, city, state or zip, optional country"
cc - ISO 3166-1 alpha-2 country code. (Optional)
... | [
"def",
"by_location",
"(",
"self",
",",
"location",
",",
"cc",
"=",
"None",
")",
":",
"header",
",",
"content",
"=",
"self",
".",
"_http_request",
"(",
"self",
".",
"BASE_URL",
",",
"location",
"=",
"location",
",",
"cc",
"=",
"cc",
")",
"return",
"j... | 40.181818 | 26 |
def write(self, byte):
"""
Writes a byte buffer to the underlying output file.
Raise exception when file is already closed.
"""
if self.is_closed_flag:
raise Exception("Unable to write - already closed!")
self.written += len(byte)
self.file.write(byte) | [
"def",
"write",
"(",
"self",
",",
"byte",
")",
":",
"if",
"self",
".",
"is_closed_flag",
":",
"raise",
"Exception",
"(",
"\"Unable to write - already closed!\"",
")",
"self",
".",
"written",
"+=",
"len",
"(",
"byte",
")",
"self",
".",
"file",
".",
"write",... | 34.666667 | 11.111111 |
def rApply(d, f):
"""Recursively applies f to the values in dict d.
Args:
d: The dict to recurse over.
f: A function to apply to values in d that takes the value and a list of
keys from the root of the dict to the value.
"""
remainingDicts = [(d, ())]
while len(remainingDicts) > 0:
curren... | [
"def",
"rApply",
"(",
"d",
",",
"f",
")",
":",
"remainingDicts",
"=",
"[",
"(",
"d",
",",
"(",
")",
")",
"]",
"while",
"len",
"(",
"remainingDicts",
")",
">",
"0",
":",
"current",
",",
"prevKeys",
"=",
"remainingDicts",
".",
"pop",
"(",
")",
"for... | 29.941176 | 15.117647 |
def _get_source(self):
"""
Get the lambda function source template. Strip the leading docstring.
Note that it's a real module in this project so we can test it.
:return: function source code, with leading docstring stripped.
:rtype: str
"""
logger.debug('Getting ... | [
"def",
"_get_source",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Getting module source for webhook2lambda2sqs.lambda_func'",
")",
"orig",
"=",
"getsourcelines",
"(",
"lambda_func",
")",
"src",
"=",
"''",
"in_docstr",
"=",
"False",
"have_docstr",
"=",
"F... | 35.291667 | 15.958333 |
def _performAction(self, action):
"""Perform the specified action."""
try:
_a11y.AXUIElement._performAction(self, 'AX%s' % action)
except _a11y.ErrorUnsupported as e:
sierra_ver = '10.12'
if mac_ver()[0] < sierra_ver:
raise e
else:
... | [
"def",
"_performAction",
"(",
"self",
",",
"action",
")",
":",
"try",
":",
"_a11y",
".",
"AXUIElement",
".",
"_performAction",
"(",
"self",
",",
"'AX%s'",
"%",
"action",
")",
"except",
"_a11y",
".",
"ErrorUnsupported",
"as",
"e",
":",
"sierra_ver",
"=",
... | 33.1 | 13.4 |
def _collect_valid_settings(meta, clsdict):
"""
Return a sequence containing the enumeration values that are valid
assignment values. Return-only values are excluded.
"""
enum_members = clsdict['__members__']
valid_settings = []
for member in enum_members:
... | [
"def",
"_collect_valid_settings",
"(",
"meta",
",",
"clsdict",
")",
":",
"enum_members",
"=",
"clsdict",
"[",
"'__members__'",
"]",
"valid_settings",
"=",
"[",
"]",
"for",
"member",
"in",
"enum_members",
":",
"valid_settings",
".",
"extend",
"(",
"member",
"."... | 41.2 | 10.6 |
def _best_version(fields):
"""Detect the best version depending on the fields used."""
def _has_marker(keys, markers):
for marker in markers:
if marker in keys:
return True
return False
keys = []
for key, value in fields.items():
if value in ([], 'UNK... | [
"def",
"_best_version",
"(",
"fields",
")",
":",
"def",
"_has_marker",
"(",
"keys",
",",
"markers",
")",
":",
"for",
"marker",
"in",
"markers",
":",
"if",
"marker",
"in",
"keys",
":",
"return",
"True",
"return",
"False",
"keys",
"=",
"[",
"]",
"for",
... | 42.085714 | 19.557143 |
def time_bins(header):
'''
Returns the time-axis lower bin edge values for the spectrogram.
'''
return np.arange(header['number_of_half_frames'], dtype=np.float64)*constants.bins_per_half_frame\
*(1.0 - header['over_sampling']) / header['subband_spacing_hz'] | [
"def",
"time_bins",
"(",
"header",
")",
":",
"return",
"np",
".",
"arange",
"(",
"header",
"[",
"'number_of_half_frames'",
"]",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"*",
"constants",
".",
"bins_per_half_frame",
"*",
"(",
"1.0",
"-",
"header",
"[... | 43.833333 | 33.166667 |
def construct_datapipeline(env='',
generated=None,
previous_env=None,
region='us-east-1',
settings=None,
pipeline_data=None):
"""Create the Pipeline JSON from template.
This ha... | [
"def",
"construct_datapipeline",
"(",
"env",
"=",
"''",
",",
"generated",
"=",
"None",
",",
"previous_env",
"=",
"None",
",",
"region",
"=",
"'us-east-1'",
",",
"settings",
"=",
"None",
",",
"pipeline_data",
"=",
"None",
")",
":",
"LOG",
".",
"info",
"("... | 34.28 | 20.5 |
def find_package_data(
where='.', package='',
exclude=standard_exclude,
exclude_directories=standard_exclude_directories,
only_in_packages=True,
show_ignored=False,
):
"""
Return a dictionary suitable for use in ``package_data``
in a distutils ``setup.py`` file.
The dictionary l... | [
"def",
"find_package_data",
"(",
"where",
"=",
"'.'",
",",
"package",
"=",
"''",
",",
"exclude",
"=",
"standard_exclude",
",",
"exclude_directories",
"=",
"standard_exclude_directories",
",",
"only_in_packages",
"=",
"True",
",",
"show_ignored",
"=",
"False",
",",... | 36.890244 | 16.914634 |
def set_time_index_from_datetime(self, value, best_fit=True):
"""
Sets the time_index parameter from a datetime using start/end/interval/units information from the service
configuration. If best_fit is True, the method will match the closest time index for the given value, otherwise
it w... | [
"def",
"set_time_index_from_datetime",
"(",
"self",
",",
"value",
",",
"best_fit",
"=",
"True",
")",
":",
"steps",
"=",
"self",
".",
"variable",
".",
"time_stops",
"if",
"value",
"in",
"steps",
":",
"self",
".",
"time_index",
"=",
"steps",
".",
"index",
... | 46.857143 | 25.142857 |
def community_louvain(W, gamma=1, ci=None, B='modularity', seed=None):
'''
The optimal community structure is a subdivision of the network into
nonoverlapping groups of nodes which maximizes the number of within-group
edges and minimizes the number of between-group edges.
This function is a fast an... | [
"def",
"community_louvain",
"(",
"W",
",",
"gamma",
"=",
"1",
",",
"ci",
"=",
"None",
",",
"B",
"=",
"'modularity'",
",",
"seed",
"=",
"None",
")",
":",
"rng",
"=",
"get_rng",
"(",
"seed",
")",
"n",
"=",
"len",
"(",
"W",
")",
"s",
"=",
"np",
... | 33.583815 | 22.49711 |
def _process_ed25516(self, data):
"""Parses ed25516 keys.
There is no (apparent) way to validate ed25519 keys. This only
checks data length (256 bits), but does not try to validate
the key in any way."""
current_position, verifying_key = self._unpack_by_int(data, 0)
ver... | [
"def",
"_process_ed25516",
"(",
"self",
",",
"data",
")",
":",
"current_position",
",",
"verifying_key",
"=",
"self",
".",
"_unpack_by_int",
"(",
"data",
",",
"0",
")",
"verifying_key_length",
"=",
"len",
"(",
"verifying_key",
")",
"*",
"8",
"verifying_key",
... | 39.166667 | 22.333333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.