text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def save(self, expected_value=None, return_values=None):
"""
Commits pending updates to Amazon DynamoDB.
:type expected_value: dict
:param expected_value: A dictionary of name/value pairs that
you expect. This dictionary should have name/value pairs
where the na... | [
"def",
"save",
"(",
"self",
",",
"expected_value",
"=",
"None",
",",
"return_values",
"=",
"None",
")",
":",
"return",
"self",
".",
"table",
".",
"layer2",
".",
"update_item",
"(",
"self",
",",
"expected_value",
",",
"return_values",
")"
] | 51.521739 | 0.001657 |
def increment(version, major=False, minor=False, patch=True):
"""
Increment a semantic version
:param version: str of the version to increment
:param major: bool specifying major level version increment
:param minor: bool specifying minor level version increment
:param patch: bool specifying pa... | [
"def",
"increment",
"(",
"version",
",",
"major",
"=",
"False",
",",
"minor",
"=",
"False",
",",
"patch",
"=",
"True",
")",
":",
"version",
"=",
"semantic_version",
".",
"Version",
"(",
"version",
")",
"if",
"major",
":",
"version",
".",
"major",
"+=",... | 29.818182 | 0.001477 |
def load_friend_chains(chain, friend_chains, txt, nfiles=None):
"""Load a list of trees from a file and add them as friends to the
chain."""
if re.search('.root?', txt) is not None:
c = ROOT.TChain(chain.GetName())
c.SetDirectory(0)
c.Add(txt)
friend_chains.append(c)
... | [
"def",
"load_friend_chains",
"(",
"chain",
",",
"friend_chains",
",",
"txt",
",",
"nfiles",
"=",
"None",
")",
":",
"if",
"re",
".",
"search",
"(",
"'.root?'",
",",
"txt",
")",
"is",
"not",
"None",
":",
"c",
"=",
"ROOT",
".",
"TChain",
"(",
"chain",
... | 27 | 0.001325 |
def _verify_and_add_jwt():
"""
This helper method just checks and adds jwt data to the app context. Will
not add jwt data if it is already present. Only use in this module
"""
if not app_context_has_jwt_data():
guard = current_guard()
token = guard.read_token_from_header()
jw... | [
"def",
"_verify_and_add_jwt",
"(",
")",
":",
"if",
"not",
"app_context_has_jwt_data",
"(",
")",
":",
"guard",
"=",
"current_guard",
"(",
")",
"token",
"=",
"guard",
".",
"read_token_from_header",
"(",
")",
"jwt_data",
"=",
"guard",
".",
"extract_jwt_token",
"(... | 39.6 | 0.002469 |
def validate(file_paths, opts):
"""
Client facing validate function. Runs _validate() and returns True if the
the file_paths pass all of the validations. Handles exceptions
automatically if _validate() throws any and exits the program.
:param file_paths: List of string file paths to test
:param... | [
"def",
"validate",
"(",
"file_paths",
",",
"opts",
")",
":",
"try",
":",
"return",
"_validate",
"(",
"file_paths",
")",
"except",
"ValidationException",
"as",
"e",
":",
"if",
"str",
"(",
"e",
")",
"==",
"\"No files found\"",
":",
"messages",
".",
"print_no... | 37.263158 | 0.001377 |
def authenticate_direct_bind(self, username, password):
"""
Performs a direct bind. We can do this since the RDN is the same
as the login attribute. Hence we just string together a dn to find
this user with.
Args:
username (str): Username of the user to bind (the fie... | [
"def",
"authenticate_direct_bind",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"bind_user",
"=",
"'{rdn}={username},{user_search_dn}'",
".",
"format",
"(",
"rdn",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'LDAP_USER_RDN_ATTR'",
")",
",",
"userna... | 35.222222 | 0.002046 |
def get_android_version(self) -> str:
'''Show Android version.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'getprop', 'ro.build.version.release')
return output.strip() | [
"def",
"get_android_version",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'getprop'",
",",
"'ro.build.version.release'",
")",
"return",
"output",
".... | 43.2 | 0.013636 |
def update():
# type: () -> None
""" Update the feature with updates committed to develop.
This will merge current develop into the current branch.
"""
branch = git.current_branch(refresh=True)
base_branch = common.get_base_branch()
common.assert_branch_type('task')
common.git_checkout... | [
"def",
"update",
"(",
")",
":",
"# type: () -> None",
"branch",
"=",
"git",
".",
"current_branch",
"(",
"refresh",
"=",
"True",
")",
"base_branch",
"=",
"common",
".",
"get_base_branch",
"(",
")",
"common",
".",
"assert_branch_type",
"(",
"'task'",
")",
"com... | 31.214286 | 0.002222 |
def forward_word_extend_selection(self, e): #
u"""Move forward to the end of the next word. Words are composed of
letters and digits."""
self.l_buffer.forward_word_extend_selection(self.argument_reset)
self.finalize() | [
"def",
"forward_word_extend_selection",
"(",
"self",
",",
"e",
")",
":",
"# \r",
"self",
".",
"l_buffer",
".",
"forward_word_extend_selection",
"(",
"self",
".",
"argument_reset",
")",
"self",
".",
"finalize",
"(",
")"
] | 50 | 0.015748 |
def _async_poll(self, poller, async_seconds, async_poll_interval):
''' launch an async job, if poll_interval is set, wait for completion '''
results = poller.wait(async_seconds, async_poll_interval)
# mark any hosts that are still listed as started as failed
# since these likely got ki... | [
"def",
"_async_poll",
"(",
"self",
",",
"poller",
",",
"async_seconds",
",",
"async_poll_interval",
")",
":",
"results",
"=",
"poller",
".",
"wait",
"(",
"async_seconds",
",",
"async_poll_interval",
")",
"# mark any hosts that are still listed as started as failed",
"# ... | 44.076923 | 0.013675 |
def get_ecmwf_macc(filename, params, startdate, stopdate, lookup_params=True,
server=None, target=_ecmwf):
"""
Download data from ECMWF MACC Reanalysis API.
Parameters
----------
filename : str
full path of file where to save data, ``.nc`` appended if not given
params... | [
"def",
"get_ecmwf_macc",
"(",
"filename",
",",
"params",
",",
"startdate",
",",
"stopdate",
",",
"lookup_params",
"=",
"True",
",",
"server",
"=",
"None",
",",
"target",
"=",
"_ecmwf",
")",
":",
"if",
"not",
"filename",
".",
"endswith",
"(",
"'nc'",
")",... | 40.431034 | 0.000416 |
def login(self, user: str, passwd: str) -> None:
"""Log in to instagram with given username and password and internally store session object.
:raises InvalidArgumentException: If the provided username does not exist.
:raises BadCredentialsException: If the provided password is wrong.
:r... | [
"def",
"login",
"(",
"self",
",",
"user",
":",
"str",
",",
"passwd",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"context",
".",
"login",
"(",
"user",
",",
"passwd",
")"
] | 67.875 | 0.009091 |
def sync_handler(self, args):
'''Handler for sync command.
XXX Here we emulate sync command with get/put -r -f --sync-check. So
it doesn't provide delete operation.
'''
self.opt.recursive = True
self.opt.sync_check = True
self.opt.force = True
self.validate('cmd|s3,local|s3,lo... | [
"def",
"sync_handler",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"opt",
".",
"recursive",
"=",
"True",
"self",
".",
"opt",
".",
"sync_check",
"=",
"True",
"self",
".",
"opt",
".",
"force",
"=",
"True",
"self",
".",
"validate",
"(",
"'cmd|s3,lo... | 29.214286 | 0.00237 |
def pretty_plot(width=None, height=None, plt=None, dpi=None):
"""Get a :obj:`matplotlib.pyplot` object with publication ready defaults.
Args:
width (:obj:`float`, optional): The width of the plot.
height (:obj:`float`, optional): The height of the plot.
plt (:obj:`matplotlib.pyplot`, op... | [
"def",
"pretty_plot",
"(",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"plt",
"=",
"None",
",",
"dpi",
"=",
"None",
")",
":",
"if",
"plt",
"is",
"None",
":",
"plt",
"=",
"matplotlib",
".",
"pyplot",
"if",
"width",
"is",
"None",
":",
"w... | 33.566667 | 0.000965 |
def install_vendored(cls, prefix, root=None, expose=None):
"""Install an importer for all vendored code with the given import prefix.
All distributions listed in ``expose`` will also be made available for import in direct,
un-prefixed form.
:param str prefix: The import prefix the installed importer w... | [
"def",
"install_vendored",
"(",
"cls",
",",
"prefix",
",",
"root",
"=",
"None",
",",
"expose",
"=",
"None",
")",
":",
"from",
"pex",
"import",
"vendor",
"root",
"=",
"cls",
".",
"_abs_root",
"(",
"root",
")",
"vendored_path_items",
"=",
"[",
"spec",
".... | 44.146341 | 0.008649 |
def start(self):
"""
Given the pipeline topology starts ``Pipers`` in the order input ->
output. See ``Piper.start``. ``Pipers`` instances are started in two
stages, which allows them to share ``NuMaps``.
"""
# top - > bottom of pipeline
pipers = self.p... | [
"def",
"start",
"(",
"self",
")",
":",
"# top - > bottom of pipeline",
"pipers",
"=",
"self",
".",
"postorder",
"(",
")",
"# ",
"for",
"piper",
"in",
"pipers",
":",
"piper",
".",
"start",
"(",
"stages",
"=",
"(",
"0",
",",
"1",
")",
")",
"for",
"pipe... | 33 | 0.012632 |
def crps_climo(self):
"""
Calculate the climatological CRPS.
"""
o_bar = self.errors["O"].values / float(self.num_forecasts)
crps_c = np.sum(self.num_forecasts * (o_bar ** 2) - o_bar * self.errors["O"].values * 2.0 +
self.errors["O_2"].values) / float(self... | [
"def",
"crps_climo",
"(",
"self",
")",
":",
"o_bar",
"=",
"self",
".",
"errors",
"[",
"\"O\"",
"]",
".",
"values",
"/",
"float",
"(",
"self",
".",
"num_forecasts",
")",
"crps_c",
"=",
"np",
".",
"sum",
"(",
"self",
".",
"num_forecasts",
"*",
"(",
"... | 46.625 | 0.010526 |
def refresh(self):
"""Update the Server information and list of API Roots"""
response = self.__raw = self._conn.get(self.url)
self._populate_fields(**response)
self._loaded = True | [
"def",
"refresh",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"__raw",
"=",
"self",
".",
"_conn",
".",
"get",
"(",
"self",
".",
"url",
")",
"self",
".",
"_populate_fields",
"(",
"*",
"*",
"response",
")",
"self",
".",
"_loaded",
"=",
"True... | 41.4 | 0.009479 |
def _default_logfile(exe_name):
'''
Retrieve the logfile name
'''
if salt.utils.platform.is_windows():
tmp_dir = os.path.join(__opts__['cachedir'], 'tmp')
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir)
logfile_tmp = tempfile.NamedTemporaryFile(dir=tmp_dir,
... | [
"def",
"_default_logfile",
"(",
"exe_name",
")",
":",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"tmp_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'tmp'",
")",
"if",
"no... | 32.952381 | 0.001404 |
def gpg_fetch_key( key_url, key_id=None, config_dir=None ):
"""
Fetch a GPG public key from the given URL.
Supports anything urllib2 supports.
If the URL has no scheme, then assume it's a PGP key server, and use GPG to go get it.
The key is not accepted into any keyrings.
Return the key data on ... | [
"def",
"gpg_fetch_key",
"(",
"key_url",
",",
"key_id",
"=",
"None",
",",
"config_dir",
"=",
"None",
")",
":",
"dat",
"=",
"None",
"from_blockstack",
"=",
"False",
"# make sure it's valid ",
"try",
":",
"urlparse",
".",
"urlparse",
"(",
"key_url",
")",
"excep... | 35.022222 | 0.008331 |
def auto_change_docstring(app, what, name, obj, options, lines):
r"""Make some automatic changes to docstrings.
Things this function does are:
- Add a title to module docstrings
- Merge lines that end with a '\' with the next line.
"""
if what == 'module' and name.startswith('pylatex')... | [
"def",
"auto_change_docstring",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"options",
",",
"lines",
")",
":",
"if",
"what",
"==",
"'module'",
"and",
"name",
".",
"startswith",
"(",
"'pylatex'",
")",
":",
"lines",
".",
"insert",
"(",
"0",
... | 31.941176 | 0.001789 |
def cleanup(self):
"""
Executes `ansible-playbook` against the cleanup playbook and returns
None.
:return: None
"""
pb = self._get_ansible_playbook(self.playbooks.cleanup)
pb.execute() | [
"def",
"cleanup",
"(",
"self",
")",
":",
"pb",
"=",
"self",
".",
"_get_ansible_playbook",
"(",
"self",
".",
"playbooks",
".",
"cleanup",
")",
"pb",
".",
"execute",
"(",
")"
] | 25.888889 | 0.008299 |
def add(self,dist):
"""Add `dist` if we ``can_add()`` it and it isn't already added"""
if self.can_add(dist) and dist.has_version():
dists = self._distmap.setdefault(dist.key,[])
if dist not in dists:
dists.append(dist)
if dist.key in self._cache:
... | [
"def",
"add",
"(",
"self",
",",
"dist",
")",
":",
"if",
"self",
".",
"can_add",
"(",
"dist",
")",
"and",
"dist",
".",
"has_version",
"(",
")",
":",
"dists",
"=",
"self",
".",
"_distmap",
".",
"setdefault",
"(",
"dist",
".",
"key",
",",
"[",
"]",
... | 45.875 | 0.010695 |
def activate():
"""
Activates the version specified in ``env.project_version`` if it is different
from the current active version.
An active version is just the version that is symlinked.
"""
env_path = '/'.join([deployment_root(),'env',env.project_fullname])
if not exists(env_path):
... | [
"def",
"activate",
"(",
")",
":",
"env_path",
"=",
"'/'",
".",
"join",
"(",
"[",
"deployment_root",
"(",
")",
",",
"'env'",
",",
"env",
".",
"project_fullname",
"]",
")",
"if",
"not",
"exists",
"(",
"env_path",
")",
":",
"print",
"env",
".",
"host",
... | 34 | 0.02162 |
def decompress_amount(x):
"""\
Undo the value compression performed by x=compress_amount(n). The input
x matches one of the following patterns:
x = n = 0
x = 1+10*(9*n + d - 1) + e
x = 1+10*(n - 1) + 9"""
if not x: return 0;
x = x - 1;
# x = 10*(9*n + d - 1) + e
x, e... | [
"def",
"decompress_amount",
"(",
"x",
")",
":",
"if",
"not",
"x",
":",
"return",
"0",
"x",
"=",
"x",
"-",
"1",
"# x = 10*(9*n + d - 1) + e",
"x",
",",
"e",
"=",
"divmod",
"(",
"x",
",",
"10",
")",
"n",
"=",
"0",
"if",
"e",
"<",
"9",
":",
"# x =... | 22.681818 | 0.011538 |
def serial_starfeatures(lclist,
outdir,
lc_catalog_pickle,
neighbor_radius_arcsec,
maxobjects=None,
deredden=True,
custom_bandpasses=None,
lcformat='hat... | [
"def",
"serial_starfeatures",
"(",
"lclist",
",",
"outdir",
",",
"lc_catalog_pickle",
",",
"neighbor_radius_arcsec",
",",
"maxobjects",
"=",
"None",
",",
"deredden",
"=",
"True",
",",
"custom_bandpasses",
"=",
"None",
",",
"lcformat",
"=",
"'hat-sql'",
",",
"lcf... | 38.710526 | 0.001326 |
def section_branch_orders(neurites, neurite_type=NeuriteType.all):
'''section branch orders in a collection of neurites'''
return map_sections(sectionfunc.branch_order, neurites, neurite_type=neurite_type) | [
"def",
"section_branch_orders",
"(",
"neurites",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"all",
")",
":",
"return",
"map_sections",
"(",
"sectionfunc",
".",
"branch_order",
",",
"neurites",
",",
"neurite_type",
"=",
"neurite_type",
")"
] | 70.333333 | 0.00939 |
def sync_local_order(self):
"""!
@brief Calculates current level of local (partial) synchronization in the network.
@return (double) Level of local (partial) synchronization.
@see sync_order()
"""
if (self._ccore_network_point... | [
"def",
"sync_local_order",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_ccore_network_pointer",
"is",
"not",
"None",
")",
":",
"return",
"wrapper",
".",
"sync_local_order",
"(",
"self",
".",
"_ccore_network_pointer",
")",
"return",
"order_estimator",
".",
... | 34.857143 | 0.01996 |
def obsolete_client(func):
"""This is a decorator which can be used to mark Client classes as
obsolete. It will result in an error being emitted when the class is
instantiated."""
@functools.wraps(func)
def new_func(*args, **kwargs):
raise ObsoleteException(
"{} has been removed... | [
"def",
"obsolete_client",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"ObsoleteException",
"(",
"\"{} has been removed from this version of the library.... | 33.928571 | 0.002049 |
def set_keywords(self, keywords):
"""Changes the <meta> keywords tag."""
self.head.keywords.attr(content=", ".join(keywords))
return self | [
"def",
"set_keywords",
"(",
"self",
",",
"keywords",
")",
":",
"self",
".",
"head",
".",
"keywords",
".",
"attr",
"(",
"content",
"=",
"\", \"",
".",
"join",
"(",
"keywords",
")",
")",
"return",
"self"
] | 39.5 | 0.012422 |
def count(self, event_str, inc_int=1):
"""Count an event.
Args:
event_str:
The name of an event to count. Used as a key in the event dict. The same
name will also be used in the summary.
inc_int: int
Optional argument to increase the count for th... | [
"def",
"count",
"(",
"self",
",",
"event_str",
",",
"inc_int",
"=",
"1",
")",
":",
"self",
".",
"_event_dict",
".",
"setdefault",
"(",
"event_str",
",",
"0",
")",
"self",
".",
"_event_dict",
"[",
"event_str",
"]",
"+=",
"inc_int"
] | 31.428571 | 0.00883 |
def add_search_engine(self, name, engine):
'''Adds a search engine with the given name.
``engine`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.SearchEngine`, which should provide a means
of obtaining recommendations... | [
"def",
"add_search_engine",
"(",
"self",
",",
"name",
",",
"engine",
")",
":",
"if",
"engine",
"is",
"None",
":",
"self",
".",
"search_engines",
".",
"pop",
"(",
"name",
",",
"None",
")",
"self",
".",
"search_engines",
"[",
"name",
"]",
"=",
"engine",
... | 41.269231 | 0.001821 |
def tar_and_copy_usr_dir(usr_dir, train_dir):
"""Package, tar, and copy usr_dir to GCS train_dir."""
tf.logging.info("Tarring and pushing t2t_usr_dir.")
usr_dir = os.path.abspath(os.path.expanduser(usr_dir))
# Copy usr dir to a temp location
top_dir = os.path.join(tempfile.gettempdir(), "t2t_usr_container")
... | [
"def",
"tar_and_copy_usr_dir",
"(",
"usr_dir",
",",
"train_dir",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Tarring and pushing t2t_usr_dir.\"",
")",
"usr_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",... | 42.631579 | 0.018116 |
def hash(self):
'''
:rtype: int
:return: hash of the field
'''
hashed = super(RandomBits, self).hash()
return khash(hashed, self._min_length, self._max_length, self._num_mutations, self._step, self._seed) | [
"def",
"hash",
"(",
"self",
")",
":",
"hashed",
"=",
"super",
"(",
"RandomBits",
",",
"self",
")",
".",
"hash",
"(",
")",
"return",
"khash",
"(",
"hashed",
",",
"self",
".",
"_min_length",
",",
"self",
".",
"_max_length",
",",
"self",
".",
"_num_muta... | 35.142857 | 0.011905 |
def get_container_data(self):
"""Returns a list of Container data
"""
for obj in self.get_containers():
info = self.get_base_info(obj)
yield info | [
"def",
"get_container_data",
"(",
"self",
")",
":",
"for",
"obj",
"in",
"self",
".",
"get_containers",
"(",
")",
":",
"info",
"=",
"self",
".",
"get_base_info",
"(",
"obj",
")",
"yield",
"info"
] | 31.333333 | 0.010363 |
def get_polygon_rules(declarations):
""" Given a Map element, a Layer element, and a list of declarations,
create a new Style element with a PolygonSymbolizer, add it to Map
and refer to it in Layer.
"""
property_map = {'polygon-fill': 'fill', 'polygon-opacity': 'fill-opacity',
... | [
"def",
"get_polygon_rules",
"(",
"declarations",
")",
":",
"property_map",
"=",
"{",
"'polygon-fill'",
":",
"'fill'",
",",
"'polygon-opacity'",
":",
"'fill-opacity'",
",",
"'polygon-gamma'",
":",
"'gamma'",
",",
"'polygon-meta-output'",
":",
"'meta-output'",
",",
"'... | 44.333333 | 0.01104 |
def shorter_name(key):
"""Return a shorter name for an id.
Does this by only taking the last part of the URI,
after the last / and the last #. Also replaces - and . with _.
Parameters
----------
key: str
Some URI
Returns
-------
key_short: str
A shortened, but more... | [
"def",
"shorter_name",
"(",
"key",
")",
":",
"key_short",
"=",
"key",
"for",
"sep",
"in",
"[",
"'#'",
",",
"'/'",
"]",
":",
"ind",
"=",
"key_short",
".",
"rfind",
"(",
"sep",
")",
"if",
"ind",
"is",
"not",
"None",
":",
"key_short",
"=",
"key_short"... | 24.333333 | 0.001647 |
async def install_agent(self, connection, nonce, machine_id):
"""
:param object connection: Connection to Juju API
:param str nonce: The nonce machine specification
:param str machine_id: The id assigned to the machine
:return: bool: If the initialization was successful
... | [
"async",
"def",
"install_agent",
"(",
"self",
",",
"connection",
",",
"nonce",
",",
"machine_id",
")",
":",
"# The path where the Juju agent should be installed.",
"data_dir",
"=",
"\"/var/lib/juju\"",
"# Disabling this prevents `apt-get update` from running initially, so",
"# ch... | 33.96 | 0.002291 |
def set_maxlen(self, length):
"""Sets maxlen"""
with self.lock:
self._maxlen = length
while len(self.data) > length:
self._poplast() | [
"def",
"set_maxlen",
"(",
"self",
",",
"length",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"_maxlen",
"=",
"length",
"while",
"len",
"(",
"self",
".",
"data",
")",
">",
"length",
":",
"self",
".",
"_poplast",
"(",
")"
] | 30.5 | 0.010638 |
def allreduce(data, op, prepare_fun=None):
"""Perform allreduce, return the result.
Parameters
----------
data: numpy array
Input data.
op: int
Reduction operators, can be MIN, MAX, SUM, BITOR
prepare_fun: function
Lazy preprocessing function, if it is not None, prepare_... | [
"def",
"allreduce",
"(",
"data",
",",
"op",
",",
"prepare_fun",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"Exception",
"(",
"'allreduce only takes in numpy.ndarray'",
")",
"buf",
"=",
"data... | 34.227273 | 0.001937 |
def concatenate_by_line(first, second):
"""Zip two strings together, line wise"""
return '\n'.join(x+y for x,y in zip(first.split('\n'), second.split('\n'))) | [
"def",
"concatenate_by_line",
"(",
"first",
",",
"second",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"x",
"+",
"y",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"first",
".",
"split",
"(",
"'\\n'",
")",
",",
"second",
".",
"split",
"(",
"'\\n'",
... | 54.333333 | 0.012121 |
def dataframe2sasdata(self, df: '<Pandas Data Frame object>', table: str ='a',
libref: str ="", keep_outer_quotes: bool=False):
"""
This method imports a Pandas Data Frame to a SAS Data Set, returning the SASdata object for the new Data Set.
df - Pandas Data Frame to imp... | [
"def",
"dataframe2sasdata",
"(",
"self",
",",
"df",
":",
"'<Pandas Data Frame object>'",
",",
"table",
":",
"str",
"=",
"'a'",
",",
"libref",
":",
"str",
"=",
"\"\"",
",",
"keep_outer_quotes",
":",
"bool",
"=",
"False",
")",
":",
"input",
"=",
"\"\"",
"c... | 36.809524 | 0.024567 |
def can_cast_to(v: Literal, dt: str) -> bool:
""" 5.4.3 Datatype Constraints
Determine whether "a value of the lexical form of n can be cast to the target type v per
XPath Functions 3.1 section 19 Casting[xpath-functions]."
"""
# TODO: rdflib doesn't appear to pay any attention to lengths (e.g. 257... | [
"def",
"can_cast_to",
"(",
"v",
":",
"Literal",
",",
"dt",
":",
"str",
")",
"->",
"bool",
":",
"# TODO: rdflib doesn't appear to pay any attention to lengths (e.g. 257 is a valid XSD.byte)",
"return",
"v",
".",
"value",
"is",
"not",
"None",
"and",
"Literal",
"(",
"s... | 52 | 0.009456 |
def data_to_bytes(data, encoding):
"""\
Converts the provided data into bytes. If the data is already a byte
sequence, it will be left unchanged.
This function tries to use the provided `encoding` (if not ``None``)
or the default encoding (ISO/IEC 8859-1). It uses UTF-8 as fallback.
Returns th... | [
"def",
"data_to_bytes",
"(",
"data",
",",
"encoding",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"return",
"data",
",",
"len",
"(",
"data",
")",
",",
"encoding",
"or",
"consts",
".",
"DEFAULT_BYTE_ENCODING",
"data",
"=",
"str",
... | 35.972222 | 0.000752 |
def escape(html):
"""
Escapes HTML according to the rules defined by the settings
``RICHTEXT_FILTER_LEVEL``, ``RICHTEXT_ALLOWED_TAGS``,
``RICHTEXT_ALLOWED_ATTRIBUTES``, ``RICHTEXT_ALLOWED_STYLES``.
"""
from yacms.conf import settings
from yacms.core import defaults
if settings.RICHTEXT_F... | [
"def",
"escape",
"(",
"html",
")",
":",
"from",
"yacms",
".",
"conf",
"import",
"settings",
"from",
"yacms",
".",
"core",
"import",
"defaults",
"if",
"settings",
".",
"RICHTEXT_FILTER_LEVEL",
"==",
"defaults",
".",
"RICHTEXT_FILTER_LEVEL_NONE",
":",
"return",
... | 42.888889 | 0.001267 |
def _build_pipeline(self, task):
"""Build up the pipeline."""
self.pipeline_steps = []
kwargs = {}
if self.default_encoding:
kwargs["default_encoding"] = self.default_encoding
steps = task.get('pipeline', [])
if steps is None:
self.pipeline_steps... | [
"def",
"_build_pipeline",
"(",
"self",
",",
"task",
")",
":",
"self",
".",
"pipeline_steps",
"=",
"[",
"]",
"kwargs",
"=",
"{",
"}",
"if",
"self",
".",
"default_encoding",
":",
"kwargs",
"[",
"\"default_encoding\"",
"]",
"=",
"self",
".",
"default_encoding... | 37.404762 | 0.002481 |
def syntax_err(self):
"""Creates a SyntaxError."""
args = self.args[:2] + (None, None) + self.args[4:]
err = SyntaxError(self.message(*args))
err.offset = args[2]
err.lineno = args[3]
return err | [
"def",
"syntax_err",
"(",
"self",
")",
":",
"args",
"=",
"self",
".",
"args",
"[",
":",
"2",
"]",
"+",
"(",
"None",
",",
"None",
")",
"+",
"self",
".",
"args",
"[",
"4",
":",
"]",
"err",
"=",
"SyntaxError",
"(",
"self",
".",
"message",
"(",
"... | 33.714286 | 0.008264 |
def __pack_message(operation, data):
"""Takes message data and adds a message header based on the operation.
Returns the resultant message string.
"""
request_id = _randint()
message = struct.pack("<i", 16 + len(data))
message += struct.pack("<i", request_id)
message += _ZERO_32 # response... | [
"def",
"__pack_message",
"(",
"operation",
",",
"data",
")",
":",
"request_id",
"=",
"_randint",
"(",
")",
"message",
"=",
"struct",
".",
"pack",
"(",
"\"<i\"",
",",
"16",
"+",
"len",
"(",
"data",
")",
")",
"message",
"+=",
"struct",
".",
"pack",
"("... | 36 | 0.002463 |
def in_miso_and_inner(self):
"""
Test if a node is miso: multiple input and single output
"""
return len(self.successor) == 1 and self.successor[0] is not None and not self.successor[0].in_or_out and \
len(self.precedence) > 1 and self.precedence[0] is not None and not sel... | [
"def",
"in_miso_and_inner",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"successor",
")",
"==",
"1",
"and",
"self",
".",
"successor",
"[",
"0",
"]",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"successor",
"[",
"0",
"]",
".",
"in_... | 56.5 | 0.014535 |
def choose_key(gpg_private_keys):
"""Displays gpg key choice and returns key"""
uid_strings_fp = []
uid_string_fp2key = {}
current_key_index = None
for i, key in enumerate(gpg_private_keys):
fingerprint = key['fingerprint']
if fingerprint == config["gpg_key_fingerprint"]:
... | [
"def",
"choose_key",
"(",
"gpg_private_keys",
")",
":",
"uid_strings_fp",
"=",
"[",
"]",
"uid_string_fp2key",
"=",
"{",
"}",
"current_key_index",
"=",
"None",
"for",
"i",
",",
"key",
"in",
"enumerate",
"(",
"gpg_private_keys",
")",
":",
"fingerprint",
"=",
"... | 28.488372 | 0.000789 |
def _finalize(self, fill_value=None, dtype=np.uint8, keep_palette=False, cmap=None):
"""Wrapper around 'finalize' method for backwards compatibility."""
import warnings
warnings.warn("'_finalize' is deprecated, use 'finalize' instead.",
DeprecationWarning)
return se... | [
"def",
"_finalize",
"(",
"self",
",",
"fill_value",
"=",
"None",
",",
"dtype",
"=",
"np",
".",
"uint8",
",",
"keep_palette",
"=",
"False",
",",
"cmap",
"=",
"None",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"'_finalize' is deprecated,... | 60.833333 | 0.008108 |
def create_hireme_project(session, title, description,
currency, budget, jobs, hireme_initial_bid):
"""
Create a fixed project
"""
jobs.append(create_job_object(id=417)) # Hire Me job, required
project_data = {'title': title,
'description': description... | [
"def",
"create_hireme_project",
"(",
"session",
",",
"title",
",",
"description",
",",
"currency",
",",
"budget",
",",
"jobs",
",",
"hireme_initial_bid",
")",
":",
"jobs",
".",
"append",
"(",
"create_job_object",
"(",
"id",
"=",
"417",
")",
")",
"# Hire Me j... | 39.586207 | 0.00085 |
def show_cluster_role(cl_args, cluster, role):
''' print topologies information to stdout '''
try:
result = tracker_access.get_cluster_role_topologies(cluster, role)
if not result:
Log.error('Unknown cluster/role \'%s\'' % '/'.join([cluster, role]))
return False
result = result[cluster]
ex... | [
"def",
"show_cluster_role",
"(",
"cl_args",
",",
"cluster",
",",
"role",
")",
":",
"try",
":",
"result",
"=",
"tracker_access",
".",
"get_cluster_role_topologies",
"(",
"cluster",
",",
"role",
")",
"if",
"not",
"result",
":",
"Log",
".",
"error",
"(",
"'Un... | 38.941176 | 0.017699 |
def _decode_doubles(message):
"""Helper for decode_qp, decodes a double array.
The double array is stored as little endian 64 bit doubles.
The array has then been base64 encoded. Since we are decoding we do these
steps in reverse.
Args:
message: the double array
Returns:
decod... | [
"def",
"_decode_doubles",
"(",
"message",
")",
":",
"binary",
"=",
"base64",
".",
"b64decode",
"(",
"message",
")",
"return",
"struct",
".",
"unpack",
"(",
"'<'",
"+",
"(",
"'d'",
"*",
"(",
"len",
"(",
"binary",
")",
"//",
"8",
")",
")",
",",
"bina... | 29 | 0.002227 |
def help(self):
'''Return the help string of the task'''
# This returns a help string for a given task of the form:
#
# ==================================================
# <name>
# ============================== (If supplied)
# <docstring>
# =============... | [
"def",
"help",
"(",
"self",
")",
":",
"# This returns a help string for a given task of the form:",
"#",
"# ==================================================",
"# <name>",
"# ============================== (If supplied)",
"# <docstring>",
"# ============================== (If overrides othe... | 30.642857 | 0.001506 |
def _read_meta(ctx: ReaderContext) -> IMeta:
"""Read metadata and apply that to the next object in the
input stream."""
start = ctx.reader.advance()
assert start == "^"
meta = _read_next_consuming_comment(ctx)
meta_map: Optional[lmap.Map[LispForm, LispForm]] = None
if isinstance(meta, symbo... | [
"def",
"_read_meta",
"(",
"ctx",
":",
"ReaderContext",
")",
"->",
"IMeta",
":",
"start",
"=",
"ctx",
".",
"reader",
".",
"advance",
"(",
")",
"assert",
"start",
"==",
"\"^\"",
"meta",
"=",
"_read_next_consuming_comment",
"(",
"ctx",
")",
"meta_map",
":",
... | 35 | 0.00107 |
def _validate_classpath_tuples(self, classpath, target):
"""Validates that all files are located within the working directory, to simplify relativization.
:param classpath: The list of classpath tuples. Each tuple is a 2-tuple of ivy_conf and
ClasspathEntry.
:param target: The target ... | [
"def",
"_validate_classpath_tuples",
"(",
"self",
",",
"classpath",
",",
"target",
")",
":",
"for",
"classpath_tuple",
"in",
"classpath",
":",
"conf",
",",
"classpath_entry",
"=",
"classpath_tuple",
"path",
"=",
"classpath_entry",
".",
"path",
"if",
"os",
".",
... | 53.933333 | 0.008505 |
def skip(stackframe=1):
"""
Must be called from within `__enter__()`. Performs some magic to have a
#ContextSkipped exception be raised the moment the with context is entered.
The #ContextSkipped must then be handled in `__exit__()` to suppress the
propagation of the exception.
> Important: This function d... | [
"def",
"skip",
"(",
"stackframe",
"=",
"1",
")",
":",
"def",
"trace",
"(",
"frame",
",",
"event",
",",
"args",
")",
":",
"raise",
"ContextSkipped",
"sys",
".",
"settrace",
"(",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"None",
")",
"fram... | 35.411765 | 0.011327 |
def get_logger(level=None, name=None, filename=None):
"""
Create a logger or return the current one if already instantiated.
Parameters
----------
level : int
one of the logger.level constants
name : string
name of the logger
filename : string
name of the log file
... | [
"def",
"get_logger",
"(",
"level",
"=",
"None",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"if",
"level",
"is",
"None",
":",
"level",
"=",
"settings",
".",
"log_level",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"settings",
... | 29.659574 | 0.002083 |
def calculate_integral_over_T(self, T1, T2):
r'''Method to compute the entropy integral of heat capacity from
`T1` to `T2`.
Parameters
----------
T1 : float
Initial temperature, [K]
T2 : float
Final temperature, [K]
... | [
"def",
"calculate_integral_over_T",
"(",
"self",
",",
"T1",
",",
"T2",
")",
":",
"return",
"(",
"Zabransky_quasi_polynomial_integral_over_T",
"(",
"T2",
",",
"self",
".",
"Tc",
",",
"*",
"self",
".",
"coeffs",
")",
"-",
"Zabransky_quasi_polynomial_integral_over_T"... | 33.722222 | 0.014423 |
def build_scoring_scheme( s, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ):
"""
Initialize scoring scheme from a blastz style text blob, first line
specifies the bases for each row/col, subsequent lines contain the
corresponding scores. Slaw extensions allow for unusual and/or
asymmetric al... | [
"def",
"build_scoring_scheme",
"(",
"s",
",",
"gap_open",
",",
"gap_extend",
",",
"gap1",
"=",
"\"-\"",
",",
"gap2",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# perform initial parse to determine alphabets and locate scores",
"bad_matrix",
"=",
"\"invalid sco... | 43.217391 | 0.027785 |
def upload(cls, path, document_type, is_protocol, description=""):
"""
Args:
path: `str`. The path to the document to upload.
document_type: `str`. DocumentType identified by the value of its name attribute.
is_protocol: `bool`.
description: `str`.
... | [
"def",
"upload",
"(",
"cls",
",",
"path",
",",
"document_type",
",",
"is_protocol",
",",
"description",
"=",
"\"\"",
")",
":",
"file_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"mime_type",
"=",
"mimetypes",
".",
"guess_type",
"(",
... | 44.047619 | 0.012698 |
def get_dependencies(ireq, sources=None, parent=None):
# type: (Union[InstallRequirement, InstallationCandidate], Optional[List[Dict[S, Union[S, bool]]]], Optional[AbstractDependency]) -> Set[S, ...]
"""Get all dependencies for a given install requirement.
:param ireq: A single InstallRequirement
:type... | [
"def",
"get_dependencies",
"(",
"ireq",
",",
"sources",
"=",
"None",
",",
"parent",
"=",
"None",
")",
":",
"# type: (Union[InstallRequirement, InstallationCandidate], Optional[List[Dict[S, Union[S, bool]]]], Optional[AbstractDependency]) -> Set[S, ...]",
"if",
"not",
"isinstance",
... | 46.228571 | 0.002421 |
def describe_topic_rule(ruleName,
region=None, key=None, keyid=None, profile=None):
'''
Given a topic rule name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_topic_rule myrule
'... | [
"def",
"describe_topic_rule",
"(",
"ruleName",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",... | 30.037037 | 0.002389 |
def FromData(cls, stream, json_data, http, auto_transfer=None,
gzip_encoded=False, **kwds):
"""Create a new Upload of stream from serialized json_data and http."""
info = json.loads(json_data)
missing_keys = cls._REQUIRED_SERIALIZATION_KEYS - set(info.keys())
if missing_... | [
"def",
"FromData",
"(",
"cls",
",",
"stream",
",",
"json_data",
",",
"http",
",",
"auto_transfer",
"=",
"None",
",",
"gzip_encoded",
"=",
"False",
",",
"*",
"*",
"kwds",
")",
":",
"info",
"=",
"json",
".",
"loads",
"(",
"json_data",
")",
"missing_keys"... | 48.733333 | 0.002012 |
def verify_file_private(filename):
"""
Raises ValueError the file permissions allow group/other
On windows this never raises due to the implementation of stat.
"""
if platform.system().upper() != 'WINDOWS':
filename = os.path.expanduser(filename)
if os.path.exists(filename):
... | [
"def",
"verify_file_private",
"(",
"filename",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
".",
"upper",
"(",
")",
"!=",
"'WINDOWS'",
":",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"if",
"os",
".",
"path",
... | 42.636364 | 0.002088 |
def expand_env_variables(lines_enum):
# type: (ReqFileLines) -> ReqFileLines
"""Replace all environment variables that can be retrieved via `os.getenv`.
The only allowed format for environment variables defined in the
requirement file is `${MY_VARIABLE_1}` to ensure two things:
1. Strings that con... | [
"def",
"expand_env_variables",
"(",
"lines_enum",
")",
":",
"# type: (ReqFileLines) -> ReqFileLines",
"for",
"line_number",
",",
"line",
"in",
"lines_enum",
":",
"for",
"env_var",
",",
"var_name",
"in",
"ENV_VAR_RE",
".",
"findall",
"(",
"line",
")",
":",
"value",... | 39.346154 | 0.000954 |
def is_enable_action_dependent(self, hosts, services):
"""
Check if dependencies states match dependencies statuses
This basically means that a dependency is in a bad state and
it can explain this object state.
:param hosts: hosts objects, used to get object in act_depend_of
... | [
"def",
"is_enable_action_dependent",
"(",
"self",
",",
"hosts",
",",
"services",
")",
":",
"# Use to know if notification is raise or not",
"enable_action",
"=",
"False",
"for",
"(",
"dep_id",
",",
"status",
",",
"_",
",",
"_",
")",
"in",
"self",
".",
"act_depen... | 41.83871 | 0.001507 |
def finish(self, message: Optional[Message_T] = None, **kwargs) -> None:
"""Finish the session."""
if message:
asyncio.ensure_future(self.send(message, **kwargs))
raise _FinishException | [
"def",
"finish",
"(",
"self",
",",
"message",
":",
"Optional",
"[",
"Message_T",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"if",
"message",
":",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"send",
"(",
"message",
",",
... | 43.4 | 0.00905 |
def wait_export(
self,
export_type,
timeout=None,
):
"""
Blocks until an in-progress export is ready.
- **export_type** is a string specifying which type of export to wait
for.
- **timeout** is the maximum number of seconds to wait.
If ``ti... | [
"def",
"wait_export",
"(",
"self",
",",
"export_type",
",",
"timeout",
"=",
"None",
",",
")",
":",
"success",
"=",
"False",
"if",
"timeout",
":",
"end_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"("... | 28.93617 | 0.002134 |
def bg_compensate(img, sigma, splinepoints, scale):
'''Reads file, subtracts background. Returns [compensated image, background].'''
from PIL import Image
import pylab
from matplotlib.image import pil_to_array
from centrosome.filter import canny
import matplotlib
img = Image.open(img)
... | [
"def",
"bg_compensate",
"(",
"img",
",",
"sigma",
",",
"splinepoints",
",",
"scale",
")",
":",
"from",
"PIL",
"import",
"Image",
"import",
"pylab",
"from",
"matplotlib",
".",
"image",
"import",
"pil_to_array",
"from",
"centrosome",
".",
"filter",
"import",
"... | 35.982456 | 0.015662 |
def discover(glob_pattern):
"""
Find all files matching given glob_pattern,
parse them, and return list of environments:
>>> envs = discover("requirements/*.in")
>>> # print(envs)
>>> envs == [
... {'name': 'base', 'refs': set()},
... {'name': 'py27', 'refs': set()},
... ... | [
"def",
"discover",
"(",
"glob_pattern",
")",
":",
"in_paths",
"=",
"glob",
".",
"glob",
"(",
"glob_pattern",
")",
"names",
"=",
"{",
"extract_env_name",
"(",
"path",
")",
":",
"path",
"for",
"path",
"in",
"in_paths",
"}",
"return",
"order_by_refs",
"(",
... | 30.346154 | 0.001229 |
def call_json(self, req_json, props=None):
"""
Deserializes req_json as JSON, invokes self.call(), and serializes result to JSON.
Returns JSON encoded string.
:Parameters:
req_json
JSON-RPC request serialized as JSON string
props
Application d... | [
"def",
"call_json",
"(",
"self",
",",
"req_json",
",",
"props",
"=",
"None",
")",
":",
"try",
":",
"req",
"=",
"json",
".",
"loads",
"(",
"req_json",
")",
"except",
":",
"msg",
"=",
"\"Unable to parse JSON: %s\"",
"%",
"req_json",
"return",
"json",
".",
... | 37.888889 | 0.008584 |
def subseparable_conv(inputs, filters, kernel_size, **kwargs):
"""Sub-separable convolution. If separability == 0 it's a separable_conv."""
def conv_fn(inputs, filters, kernel_size, **kwargs):
"""Sub-separable convolution, splits into separability-many blocks."""
separability = None
if "separability" i... | [
"def",
"subseparable_conv",
"(",
"inputs",
",",
"filters",
",",
"kernel_size",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"conv_fn",
"(",
"inputs",
",",
"filters",
",",
"kernel_size",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Sub-separable convolution, splits i... | 42.027778 | 0.00969 |
def find_jamfile (self, dir, parent_root=0, no_errors=0):
"""Find the Jamfile at the given location. This returns the
exact names of all the Jamfiles in the given directory. The optional
parent-root argument causes this to search not the given directory
but the ones above it up to the di... | [
"def",
"find_jamfile",
"(",
"self",
",",
"dir",
",",
"parent_root",
"=",
"0",
",",
"no_errors",
"=",
"0",
")",
":",
"assert",
"isinstance",
"(",
"dir",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"parent_root",
",",
"(",
"int",
",",
"bool",
")... | 43.377358 | 0.001701 |
def subplots(scale_x=None, scale_y=None, scale=None, **kwargs):
r'''
Run ``matplotlib.pyplot.subplots`` with ``figsize`` set to the correct multiple of the default.
:additional options:
**scale, scale_x, scale_y** (``<float>``)
Scale the figure-size (along one of the dimensions).
'''
if 'figsize' in kwar... | [
"def",
"subplots",
"(",
"scale_x",
"=",
"None",
",",
"scale_y",
"=",
"None",
",",
"scale",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'figsize'",
"in",
"kwargs",
":",
"return",
"plt",
".",
"subplots",
"(",
"*",
"*",
"kwargs",
")",
"widt... | 23.774194 | 0.023468 |
def make_work_parcels(upload_workers, num_chunks):
"""
Make groups so we can split up num_chunks into similar sizes.
Rounds up trying to keep work evenly split so sometimes it will not use all workers.
For very small numbers it can result in (upload_workers-1) total workers.
For ... | [
"def",
"make_work_parcels",
"(",
"upload_workers",
",",
"num_chunks",
")",
":",
"chunks_per_worker",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"float",
"(",
"num_chunks",
")",
"/",
"float",
"(",
"upload_workers",
")",
")",
")",
"return",
"ParallelChunkProcess... | 65.25 | 0.008816 |
def check_image_duplicates(file_list):
""" Checking Images for duplicates (despite resizing, colours, etc) """
master_hash = ''
ham_dist = 0
results = []
print("Checking Images for duplicates (despite resizing, colours, etc) " )
for ndx, fname in enumerate(file_list):
#img = Image.open(f... | [
"def",
"check_image_duplicates",
"(",
"file_list",
")",
":",
"master_hash",
"=",
"''",
"ham_dist",
"=",
"0",
"results",
"=",
"[",
"]",
"print",
"(",
"\"Checking Images for duplicates (despite resizing, colours, etc) \"",
")",
"for",
"ndx",
",",
"fname",
"in",
"enume... | 46.5 | 0.013699 |
def write_to_file(data, path):
"""Export extracted fields to csv
Appends .csv to path if missing and generates csv file in specified directory, if not then in root
Parameters
----------
data : dict
Dictionary of extracted fields
path : str
directory to save generated csv file
... | [
"def",
"write_to_file",
"(",
"data",
",",
"path",
")",
":",
"if",
"path",
".",
"endswith",
"(",
"'.csv'",
")",
":",
"filename",
"=",
"path",
"else",
":",
"filename",
"=",
"path",
"+",
"'.csv'",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
... | 26.3 | 0.001466 |
def _prop(self, T, rho, fav):
"""Thermodynamic properties of humid air
Parameters
----------
T : float
Temperature, [K]
rho : float
Density, [kg/m³]
fav : dict
dictionary with helmholtz energy and derivatives
Returns
-... | [
"def",
"_prop",
"(",
"self",
",",
"T",
",",
"rho",
",",
"fav",
")",
":",
"prop",
"=",
"{",
"}",
"prop",
"[",
"\"P\"",
"]",
"=",
"rho",
"**",
"2",
"*",
"fav",
"[",
"\"fird\"",
"]",
"/",
"1000",
"# Eq T1",
"prop",
"[",
"\"s\"",
"]",
"=",
"-",
... | 45.686275 | 0.00084 |
def LoadChecksFromDirs(dir_paths, overwrite_if_exists=True):
"""Load checks from all yaml files in the specified directories."""
loaded = []
for dir_path in dir_paths:
cfg_files = glob.glob(os.path.join(dir_path, "*.yaml"))
loaded.extend(LoadChecksFromFiles(cfg_files, overwrite_if_exists))
return loaded | [
"def",
"LoadChecksFromDirs",
"(",
"dir_paths",
",",
"overwrite_if_exists",
"=",
"True",
")",
":",
"loaded",
"=",
"[",
"]",
"for",
"dir_path",
"in",
"dir_paths",
":",
"cfg_files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir_pa... | 44.857143 | 0.015625 |
def select_enclosed_points(dataset, surface, tolerance=0.001,
inside_out=False, check_surface=True):
"""Mark points as to whether they are inside a closed surface.
This evaluates all the input points to determine whether they are in an
enclosed surface. The filter produces a (0,1... | [
"def",
"select_enclosed_points",
"(",
"dataset",
",",
"surface",
",",
"tolerance",
"=",
"0.001",
",",
"inside_out",
"=",
"False",
",",
"check_surface",
"=",
"True",
")",
":",
"alg",
"=",
"vtk",
".",
"vtkSelectEnclosedPoints",
"(",
")",
"alg",
".",
"SetInputD... | 45.826087 | 0.001393 |
def update_node(self, job_record):
""" Updates job record property for a tree node associated with the given Job """
if job_record.process_name not in self.process_hierarchy:
raise ValueError('unable to update the node due to unknown process: {0}'.format(job_record.process_name))
ti... | [
"def",
"update_node",
"(",
"self",
",",
"job_record",
")",
":",
"if",
"job_record",
".",
"process_name",
"not",
"in",
"self",
".",
"process_hierarchy",
":",
"raise",
"ValueError",
"(",
"'unable to update the node due to unknown process: {0}'",
".",
"format",
"(",
"j... | 63.75 | 0.009671 |
def import_data(self, data):
"""Import additional data for tuning
Parameters
----------
data:
a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'
"""
_completed_num = 0
for trial_info in data:
logger.info("I... | [
"def",
"import_data",
"(",
"self",
",",
"data",
")",
":",
"_completed_num",
"=",
"0",
"for",
"trial_info",
"in",
"data",
":",
"logger",
".",
"info",
"(",
"\"Importing data, current processing progress %s / %s\"",
"%",
"(",
"_completed_num",
",",
"len",
"(",
"dat... | 45.807692 | 0.008224 |
def unregister_checker(self, checker):
"""Unregister a checker instance."""
if checker in self._checkers:
self._checkers.remove(checker) | [
"def",
"unregister_checker",
"(",
"self",
",",
"checker",
")",
":",
"if",
"checker",
"in",
"self",
".",
"_checkers",
":",
"self",
".",
"_checkers",
".",
"remove",
"(",
"checker",
")"
] | 40.25 | 0.012195 |
def call_sacrebleu(input_fname: str, ref_fname: str, output_fname: str, log_fname: str, tokenized: bool = False):
"""
Call pip-installed sacrebleu on tokenized or detokenized inputs.
:param input_fname: Input translation file.
:param ref_fname: Reference translation file.
:param output_fname: Outpu... | [
"def",
"call_sacrebleu",
"(",
"input_fname",
":",
"str",
",",
"ref_fname",
":",
"str",
",",
"output_fname",
":",
"str",
",",
"log_fname",
":",
"str",
",",
"tokenized",
":",
"bool",
"=",
"False",
")",
":",
"# Assemble command",
"command",
"=",
"[",
"\"sacre... | 39.038462 | 0.001923 |
def save_examples(noise = 0.0, maxVal = 1.0, dataDir="data"):
"""
Generate sample noise files for listening and debugging.
:param noise: noise value for the addNoise transform
:param maxVal: maxVal for the addNoise transform
:param dataDir: root dir containing speech_commands directory
"""
testDataDir = o... | [
"def",
"save_examples",
"(",
"noise",
"=",
"0.0",
",",
"maxVal",
"=",
"1.0",
",",
"dataDir",
"=",
"\"data\"",
")",
":",
"testDataDir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dataDir",
",",
"\"speech_commands\"",
",",
"\"test\"",
")",
"outDir",
"=",
... | 34.484848 | 0.011111 |
def write(self,
fout=None,
fmt=SPARSE,
schema_only=False,
data_only=False):
"""
Write an arff structure to a string.
"""
assert not (schema_only and data_only), 'Make up your mind.'
assert fmt in FORMATS, 'Invalid format "%s". Should be one of: %s'... | [
"def",
"write",
"(",
"self",
",",
"fout",
"=",
"None",
",",
"fmt",
"=",
"SPARSE",
",",
"schema_only",
"=",
"False",
",",
"data_only",
"=",
"False",
")",
":",
"assert",
"not",
"(",
"schema_only",
"and",
"data_only",
")",
",",
"'Make up your mind.'",
"asse... | 36.576923 | 0.008197 |
def set_state(self, state, enable):
"""Set the state."""
is_enabled = self.get_state(state)
if is_enabled == enable:
return True
key = None
desired_states = [{'state': state, 'enabled': not is_enabled}]
if state == States.FILTER_LOW_SPEED:
if no... | [
"def",
"set_state",
"(",
"self",
",",
"state",
",",
"enable",
")",
":",
"is_enabled",
"=",
"self",
".",
"get_state",
"(",
"state",
")",
"if",
"is_enabled",
"==",
"enable",
":",
"return",
"True",
"key",
"=",
"None",
"desired_states",
"=",
"[",
"{",
"'st... | 38.102564 | 0.001312 |
def _find_best_in_population(population, values):
"""Finds the population member with the lowest value."""
best_value = tf.math.reduce_min(input_tensor=values)
best_index = tf.where(tf.math.equal(values, best_value))[0, 0]
return ([population_part[best_index] for population_part in population],
best_... | [
"def",
"_find_best_in_population",
"(",
"population",
",",
"values",
")",
":",
"best_value",
"=",
"tf",
".",
"math",
".",
"reduce_min",
"(",
"input_tensor",
"=",
"values",
")",
"best_index",
"=",
"tf",
".",
"where",
"(",
"tf",
".",
"math",
".",
"equal",
... | 45.714286 | 0.015337 |
def open( self, **kwargs ):
"""Append an opening tag."""
if self.tag in self.parent.twotags or self.tag in self.parent.onetags:
self.render( self.tag, False, None, kwargs )
elif self.mode == 'strict_html' and self.tag in self.parent.deptags:
raise DeprecationError( self.... | [
"def",
"open",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"tag",
"in",
"self",
".",
"parent",
".",
"twotags",
"or",
"self",
".",
"tag",
"in",
"self",
".",
"parent",
".",
"onetags",
":",
"self",
".",
"render",
"(",
"self",
... | 45.571429 | 0.024615 |
def spa_distance(psd, mass1, mass2, lower_frequency_cutoff, snr=8):
""" Return the distance at a given snr (default=8) of the SPA TaylorF2
template.
"""
kend = int(spa_tmplt_end(mass1=mass1, mass2=mass2) / psd.delta_f)
norm1 = spa_tmplt_norm(psd, len(psd), psd.delta_f, lower_frequency_cutoff)
no... | [
"def",
"spa_distance",
"(",
"psd",
",",
"mass1",
",",
"mass2",
",",
"lower_frequency_cutoff",
",",
"snr",
"=",
"8",
")",
":",
"kend",
"=",
"int",
"(",
"spa_tmplt_end",
"(",
"mass1",
"=",
"mass1",
",",
"mass2",
"=",
"mass2",
")",
"/",
"psd",
".",
"del... | 42.545455 | 0.002092 |
def _special_value_size(em):
'''
handle "size" property, which has different behaviour for input vs everything else
'''
if em.tagName == 'input':
# TODO: "size" on an input is implemented very weirdly. Negative values are treated as invalid,
# A value of "0" raises an except... | [
"def",
"_special_value_size",
"(",
"em",
")",
":",
"if",
"em",
".",
"tagName",
"==",
"'input'",
":",
"# TODO: \"size\" on an input is implemented very weirdly. Negative values are treated as invalid,",
"# A value of \"0\" raises an exception (and does not set HTML attribute)",
... | 50.6 | 0.009709 |
def _PreParse(self, key, value):
"""Executed against each field of each row read from index table."""
if key == 'Command':
return re.sub(r'(\[\[.+?\]\])', self._Completion, value)
else:
return value | [
"def",
"_PreParse",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"==",
"'Command'",
":",
"return",
"re",
".",
"sub",
"(",
"r'(\\[\\[.+?\\]\\])'",
",",
"self",
".",
"_Completion",
",",
"value",
")",
"else",
":",
"return",
"value"
] | 36.166667 | 0.013514 |
def load_target_from_cache(target: Target, build_context) -> (bool, bool):
"""Load `target` from build cache, restoring cached artifacts & summary.
Return (build_cached, test_cached) tuple.
`build_cached` is True if target restored successfully.
`test_cached` is True if build is cached and test_time... | [
"def",
"load_target_from_cache",
"(",
"target",
":",
"Target",
",",
"build_context",
")",
"->",
"(",
"bool",
",",
"bool",
")",
":",
"cache_dir",
"=",
"build_context",
".",
"conf",
".",
"get_cache_dir",
"(",
"target",
",",
"build_context",
")",
"if",
"not",
... | 48.929825 | 0.000703 |
def _import_status(data, item, repo_name, repo_tag):
'''
Process a status update from docker import, updating the data structure
'''
status = item['status']
try:
if 'Downloading from' in status:
return
elif all(x in string.hexdigits for x in status):
# Status ... | [
"def",
"_import_status",
"(",
"data",
",",
"item",
",",
"repo_name",
",",
"repo_tag",
")",
":",
"status",
"=",
"item",
"[",
"'status'",
"]",
"try",
":",
"if",
"'Downloading from'",
"in",
"status",
":",
"return",
"elif",
"all",
"(",
"x",
"in",
"string",
... | 33.714286 | 0.002062 |
def getMeanInpCurrents(params, numunits=100,
filepattern=os.path.join('simulation_output_default',
'population_input_spikes*')):
'''return a dict with the per population mean and std synaptic current,
averaging over numcells recorded units f... | [
"def",
"getMeanInpCurrents",
"(",
"params",
",",
"numunits",
"=",
"100",
",",
"filepattern",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'simulation_output_default'",
",",
"'population_input_spikes*'",
")",
")",
":",
"#convolution kernels",
"x",
"=",
"np",
".",
... | 35.015152 | 0.012626 |
def dataset_create_new(self,
folder,
public=False,
quiet=False,
convert_to_csv=True,
dir_mode='skip'):
""" create a new dataset, meaning the same as creating a version but
... | [
"def",
"dataset_create_new",
"(",
"self",
",",
"folder",
",",
"public",
"=",
"False",
",",
"quiet",
"=",
"False",
",",
"convert_to_csv",
"=",
"True",
",",
"dir_mode",
"=",
"'skip'",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"folder",... | 40.683544 | 0.00243 |
def smallest_url(flickr, pid, min_width, min_height):
"""Return the url of the smallest photo above the dimensions.
If no such photo exists, return None.
"""
sizes = flickr.photos_getSizes(photo_id=pid, format='parsed-json')
smallest_url = None
smallest_area = None
for size in sizes['sizes'... | [
"def",
"smallest_url",
"(",
"flickr",
",",
"pid",
",",
"min_width",
",",
"min_height",
")",
":",
"sizes",
"=",
"flickr",
".",
"photos_getSizes",
"(",
"photo_id",
"=",
"pid",
",",
"format",
"=",
"'parsed-json'",
")",
"smallest_url",
"=",
"None",
"smallest_are... | 39.470588 | 0.001456 |
def p_operation_definition7(self, p):
"""
operation_definition : operation_type directives selection_set
"""
p[0] = self.operation_cls(p[1])(
selections=p[3],
directives=p[2],
) | [
"def",
"p_operation_definition7",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"operation_cls",
"(",
"p",
"[",
"1",
"]",
")",
"(",
"selections",
"=",
"p",
"[",
"3",
"]",
",",
"directives",
"=",
"p",
"[",
"2",
"]",
",",... | 29.25 | 0.008299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.