text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_java_path():
"""Get the path of java executable"""
java_home = os.environ.get("JAVA_HOME")
return os.path.join(java_home, BIN_DIR, "java") | [
"def",
"get_java_path",
"(",
")",
":",
"java_home",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"JAVA_HOME\"",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"java_home",
",",
"BIN_DIR",
",",
"\"java\"",
")"
] | 37.25 | 0.026316 |
def get_info(self, wiki=None, show=True, proxy=None, timeout=0):
"""
GET site info (general, statistics, siteviews, mostviewed) via
https://www.mediawiki.org/wiki/API:Siteinfo, and
https://www.mediawiki.org/wiki/Extension:PageViewInfo
Optional arguments:
- [wiki]: <str> ... | [
"def",
"get_info",
"(",
"self",
",",
"wiki",
"=",
"None",
",",
"show",
"=",
"True",
",",
"proxy",
"=",
"None",
",",
"timeout",
"=",
"0",
")",
":",
"if",
"wiki",
":",
"self",
".",
"params",
".",
"update",
"(",
"{",
"'wiki'",
":",
"wiki",
"}",
")... | 42.035714 | 0.001661 |
def apply(self, event = None):
"""Before self.onOk closes the window, it calls this function to sync the config changes from the GUI back to self.config."""
for section in self.config.sections():
# Run through the sections to check all the option values:
for option, o in self.config.config[section].items(... | [
"def",
"apply",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"for",
"section",
"in",
"self",
".",
"config",
".",
"sections",
"(",
")",
":",
"# Run through the sections to check all the option values:\r",
"for",
"option",
",",
"o",
"in",
"self",
".",
"co... | 51.875 | 0.022871 |
def geo_mesh(element):
"""
Get mesh data from a 2D Element ensuring that if the data is
on a cylindrical coordinate system and wraps globally that data
actually wraps around.
"""
if len(element.vdims) > 1:
xs, ys = (element.dimension_values(i, False, False)
for i in ran... | [
"def",
"geo_mesh",
"(",
"element",
")",
":",
"if",
"len",
"(",
"element",
".",
"vdims",
")",
">",
"1",
":",
"xs",
",",
"ys",
"=",
"(",
"element",
".",
"dimension_values",
"(",
"i",
",",
"False",
",",
"False",
")",
"for",
"i",
"in",
"range",
"(",
... | 42.315789 | 0.002433 |
def additions_mount():
'''
Mount VirtualBox Guest Additions CD to the temp directory.
To connect VirtualBox Guest Additions via VirtualBox graphical interface
press 'Host+D' ('Host' is usually 'Right Ctrl').
CLI Example:
.. code-block:: bash
salt '*' vbox_guest.additions_mount
:... | [
"def",
"additions_mount",
"(",
")",
":",
"mount_point",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"ret",
"=",
"__salt__",
"[",
"'mount.mount'",
"]",
"(",
"mount_point",
",",
"'/dev/cdrom'",
")",
"if",
"ret",
"is",
"True",
":",
"return",
"mount_point",
"el... | 24.904762 | 0.001842 |
def parseReaderConfig(self, confdict):
"""Parse a reader configuration dictionary.
Examples:
{
Type: 23,
Data: b'\x00'
}
{
Type: 1023,
Vendor: 25882,
Subtype: 21,
Data: b'\x00'
}
"""
... | [
"def",
"parseReaderConfig",
"(",
"self",
",",
"confdict",
")",
":",
"logger",
".",
"debug",
"(",
"'parseReaderConfig input: %s'",
",",
"confdict",
")",
"conf",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"confdict",
".",
"items",
"(",
")",
":",
"if",
"n... | 26.694444 | 0.002008 |
def load_connection_settings(self):
"""Load the user's previously-saved kernel connection settings."""
existing_kernel = CONF.get("existing-kernel", "settings", {})
connection_file_path = existing_kernel.get("json_file_path", "")
is_remote = existing_kernel.get("is_remote", False)
... | [
"def",
"load_connection_settings",
"(",
"self",
")",
":",
"existing_kernel",
"=",
"CONF",
".",
"get",
"(",
"\"existing-kernel\"",
",",
"\"settings\"",
",",
"{",
"}",
")",
"connection_file_path",
"=",
"existing_kernel",
".",
"get",
"(",
"\"json_file_path\"",
",",
... | 41.486486 | 0.001273 |
def merge_modified_section_data(self):
"""Update the PE image content with any individual section data that has been modified."""
for section in self.sections:
section_data_start = adjust_FileAlignment( section.PointerToRawData,
self.OPTIONAL_HEADER.FileAlignment )
... | [
"def",
"merge_modified_section_data",
"(",
"self",
")",
":",
"for",
"section",
"in",
"self",
".",
"sections",
":",
"section_data_start",
"=",
"adjust_FileAlignment",
"(",
"section",
".",
"PointerToRawData",
",",
"self",
".",
"OPTIONAL_HEADER",
".",
"FileAlignment",
... | 67 | 0.016367 |
def add_group_coordinator(self, group, response):
"""Update with metadata for a group coordinator
Arguments:
group (str): name of group from GroupCoordinatorRequest
response (GroupCoordinatorResponse): broker response
Returns:
bool: True if metadata is updat... | [
"def",
"add_group_coordinator",
"(",
"self",
",",
"group",
",",
"response",
")",
":",
"log",
".",
"debug",
"(",
"\"Updating coordinator for %s: %s\"",
",",
"group",
",",
"response",
")",
"error_type",
"=",
"Errors",
".",
"for_code",
"(",
"response",
".",
"erro... | 38.813953 | 0.001169 |
def send_mail(subject, message, recipient_list, from_email=None,
fail_silently=False, auth_user=None, auth_password=None,
connection=None, **kwargs):
"""
Easy wrapper for sending a single message to a recipient list. All members
of the recipient list will see the other recipients... | [
"def",
"send_mail",
"(",
"subject",
",",
"message",
",",
"recipient_list",
",",
"from_email",
"=",
"None",
",",
"fail_silently",
"=",
"False",
",",
"auth_user",
"=",
"None",
",",
"auth_password",
"=",
"None",
",",
"connection",
"=",
"None",
",",
"*",
"*",
... | 38.529412 | 0.00149 |
def namedb_select_count_rows( cur, query, args, count_column='COUNT(*)' ):
"""
Execute a SELECT COUNT(*) ... query
and return the number of rows.
"""
count_rows = namedb_query_execute( cur, query, args )
count = 0
for r in count_rows:
count = r[count_column]
break
return... | [
"def",
"namedb_select_count_rows",
"(",
"cur",
",",
"query",
",",
"args",
",",
"count_column",
"=",
"'COUNT(*)'",
")",
":",
"count_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"args",
")",
"count",
"=",
"0",
"for",
"r",
"in",
"count_r... | 26.25 | 0.015337 |
def default_configfile(base_filename):
'''Return fully expanded configuration filename location for
base_filename. python2 and python3 debuggers share the smae
directory: ~/.config/trepan.py
'''
file_dir = os.path.join(os.environ.get('HOME', '~'), '.config', 'trepanpy')
file_dir = Mclifns.path_... | [
"def",
"default_configfile",
"(",
"base_filename",
")",
":",
"file_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'HOME'",
",",
"'~'",
")",
",",
"'.config'",
",",
"'trepanpy'",
")",
"file_dir",
"=",
"Mclifns",
"... | 42 | 0.002119 |
def initialize_wind_farms(my_turbine, e126):
r"""
Initializes two :class:`~.wind_farm.WindFarm` objects.
This function shows how to initialize a WindFarm object. You need to
provide at least a name and a the wind farm's wind turbine fleet as done
below for 'example_farm'. Optionally you can provide... | [
"def",
"initialize_wind_farms",
"(",
"my_turbine",
",",
"e126",
")",
":",
"# specification of wind farm data",
"example_farm_data",
"=",
"{",
"'name'",
":",
"'example_farm'",
",",
"'wind_turbine_fleet'",
":",
"[",
"{",
"'wind_turbine'",
":",
"my_turbine",
",",
"'numbe... | 35.576923 | 0.000526 |
def get_pipe_series_output(commands: Sequence[str],
stdinput: BinaryIO = None) -> bytes:
"""
Get the output from a piped series of commands.
Args:
commands: sequence of command strings
stdinput: optional ``stdin`` data to feed into the start of the pipe
Retur... | [
"def",
"get_pipe_series_output",
"(",
"commands",
":",
"Sequence",
"[",
"str",
"]",
",",
"stdinput",
":",
"BinaryIO",
"=",
"None",
")",
"->",
"bytes",
":",
"# Python arrays indexes are zero-based, i.e. an array is indexed from",
"# 0 to len(array)-1.",
"# The range/xrange c... | 33.052632 | 0.000773 |
def _determine_redirect(self, url, verb, timeout=15, headers={}):
"""
Internal redirect function, focuses on HTTP and worries less about
application-y stuff.
@param url: the url to check
@param verb: the verb, e.g. head, or get.
@param timeout: the time, in seconds, that ... | [
"def",
"_determine_redirect",
"(",
"self",
",",
"url",
",",
"verb",
",",
"timeout",
"=",
"15",
",",
"headers",
"=",
"{",
"}",
")",
":",
"requests_verb",
"=",
"getattr",
"(",
"self",
".",
"session",
",",
"verb",
")",
"r",
"=",
"requests_verb",
"(",
"u... | 37.121212 | 0.002387 |
def dirint(ghi, altitudes, doys, pressures, use_delta_kt_prime=True,
temp_dew=None, min_sin_altitude=0.065, min_altitude=3):
"""
Determine DNI from GHI using the DIRINT modification of the DISC
model.
Implements the modified DISC model known as "DIRINT" introduced in
[1]. DIRINT predicts... | [
"def",
"dirint",
"(",
"ghi",
",",
"altitudes",
",",
"doys",
",",
"pressures",
",",
"use_delta_kt_prime",
"=",
"True",
",",
"temp_dew",
"=",
"None",
",",
"min_sin_altitude",
"=",
"0.065",
",",
"min_altitude",
"=",
"3",
")",
":",
"# calculate kt_prime values",
... | 43.278846 | 0.000869 |
def index(self, elem):
"""Find the index of elem in the count."""
if elem not in self:
raise _coconut.ValueError(_coconut.repr(elem) + " is not in count")
return (elem - self._start) // self._step | [
"def",
"index",
"(",
"self",
",",
"elem",
")",
":",
"if",
"elem",
"not",
"in",
"self",
":",
"raise",
"_coconut",
".",
"ValueError",
"(",
"_coconut",
".",
"repr",
"(",
"elem",
")",
"+",
"\" is not in count\"",
")",
"return",
"(",
"elem",
"-",
"self",
... | 45.6 | 0.008621 |
def add_linguistic_processor(self, layer ,my_lp):
"""
Adds a linguistic processor to a certain layer
@type layer: string
@param layer: the name of the layer
@type my_lp: L{Clp}
@param my_lp: the linguistic processor
"""
## Locate the linguisticProcessor el... | [
"def",
"add_linguistic_processor",
"(",
"self",
",",
"layer",
",",
"my_lp",
")",
":",
"## Locate the linguisticProcessor element for taht layer",
"found_lp_obj",
"=",
"None",
"for",
"this_lp",
"in",
"self",
".",
"node",
".",
"findall",
"(",
"'linguisticProcessors'",
"... | 38.227273 | 0.009281 |
def get_language_info(language):
"""
Looks up the things we need to know about how to handle text in a given
language. This will return a dictionary with the following fields:
'script': a BCP 47 script code such as 'Latn', 'Cyrl', 'Hans'...
Indicates the script that tokens in this language sho... | [
"def",
"get_language_info",
"(",
"language",
")",
":",
"# The input is probably a string, so parse it into a Language. If it's",
"# already a Language, it will pass through.",
"language",
"=",
"Language",
".",
"get",
"(",
"language",
")",
"# Assume additional things about the languag... | 38.267857 | 0.000455 |
def get_1D_overlap(eclusters, depth=1):
"""
Find blocks that are 1D overlapping,
returns cliques of block ids that are in conflict
"""
overlap_set = set()
active = set()
ends = []
for i, (chr, left, right) in enumerate(eclusters):
ends.append((chr, left, 0, i)) # 0/1 for left/r... | [
"def",
"get_1D_overlap",
"(",
"eclusters",
",",
"depth",
"=",
"1",
")",
":",
"overlap_set",
"=",
"set",
"(",
")",
"active",
"=",
"set",
"(",
")",
"ends",
"=",
"[",
"]",
"for",
"i",
",",
"(",
"chr",
",",
"left",
",",
"right",
")",
"in",
"enumerate... | 24.172414 | 0.001372 |
def get_particles_featuring(feature_rad, state_name=None, im_name=None,
use_full_path=False, actual_rad=None, invert=True, featuring_params={},
**kwargs):
"""
Combines centroid featuring with the globals from a previous state.
Runs trackpy.locate on an image, sets the globals from a previou... | [
"def",
"get_particles_featuring",
"(",
"feature_rad",
",",
"state_name",
"=",
"None",
",",
"im_name",
"=",
"None",
",",
"use_full_path",
"=",
"False",
",",
"actual_rad",
"=",
"None",
",",
"invert",
"=",
"True",
",",
"featuring_params",
"=",
"{",
"}",
",",
... | 43.425926 | 0.000625 |
def create_tcp_rpc_system(hostname=None, port_range=(0,), ping_interval=1, ping_timeout=0.5):
"""
Creates a TCP based :class:`RPCSystem`.
:param port_range: List of ports to try. If `[0]`, an arbitrary free
port will be used.
"""
def ownid_factory(listeningport):
port = lis... | [
"def",
"create_tcp_rpc_system",
"(",
"hostname",
"=",
"None",
",",
"port_range",
"=",
"(",
"0",
",",
")",
",",
"ping_interval",
"=",
"1",
",",
"ping_timeout",
"=",
"0.5",
")",
":",
"def",
"ownid_factory",
"(",
"listeningport",
")",
":",
"port",
"=",
"lis... | 37.5 | 0.009751 |
def score_xrefs_by_semsim(self, xg, ont=None):
"""
Given an xref graph (see ref:`get_xref_graph`), this will adjust scores based on
the semantic similarity of matches.
"""
logging.info("scoring xrefs by semantic similarity for {} nodes in {}".format(len(xg.nodes()), ont))
... | [
"def",
"score_xrefs_by_semsim",
"(",
"self",
",",
"xg",
",",
"ont",
"=",
"None",
")",
":",
"logging",
".",
"info",
"(",
"\"scoring xrefs by semantic similarity for {} nodes in {}\"",
".",
"format",
"(",
"len",
"(",
"xg",
".",
"nodes",
"(",
")",
")",
",",
"on... | 48.941176 | 0.018868 |
def list_teams(profile="github", ignore_cache=False):
'''
Lists all teams with the organization.
profile
The name of the profile configuration to use. Defaults to ``github``.
ignore_cache
Bypasses the use of cached teams.
CLI Example:
.. code-block:: bash
salt mymini... | [
"def",
"list_teams",
"(",
"profile",
"=",
"\"github\"",
",",
"ignore_cache",
"=",
"False",
")",
":",
"key",
"=",
"'github.{0}:teams'",
".",
"format",
"(",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
")",
"if",
"key",
"not",
"in",
"__context_... | 30.818182 | 0.002144 |
def query(self, asql, logger=None):
"""
Execute an ASQL file and return the result of the first SELECT statement.
:param asql:
:param logger:
:return:
"""
import sqlparse
from ambry.mprlib.exceptions import BadSQLError
from ambry.bundle.asql_parse... | [
"def",
"query",
"(",
"self",
",",
"asql",
",",
"logger",
"=",
"None",
")",
":",
"import",
"sqlparse",
"from",
"ambry",
".",
"mprlib",
".",
"exceptions",
"import",
"BadSQLError",
"from",
"ambry",
".",
"bundle",
".",
"asql_parser",
"import",
"process_sql",
"... | 31.506667 | 0.002462 |
def is_cell_empty(self, cell):
"""Checks if the cell is empty."""
if cell is None:
return True
elif self._is_cell_empty:
return self._is_cell_empty(cell)
else:
return cell is None | [
"def",
"is_cell_empty",
"(",
"self",
",",
"cell",
")",
":",
"if",
"cell",
"is",
"None",
":",
"return",
"True",
"elif",
"self",
".",
"_is_cell_empty",
":",
"return",
"self",
".",
"_is_cell_empty",
"(",
"cell",
")",
"else",
":",
"return",
"cell",
"is",
"... | 25.75 | 0.018779 |
def pairwise(fun, v):
"""
>>> pairwise(operator.sub, [4,3,2,1,-10])
[1, 1, 1, 11]
>>> import numpy
>>> pairwise(numpy.subtract, numpy.array([4,3,2,1,-10]))
array([ 1, 1, 1, 11])
"""
if not hasattr(v, 'shape'):
return list(ipairwise(fun,v))
else:
return fun(v[:-1],v[... | [
"def",
"pairwise",
"(",
"fun",
",",
"v",
")",
":",
"if",
"not",
"hasattr",
"(",
"v",
",",
"'shape'",
")",
":",
"return",
"list",
"(",
"ipairwise",
"(",
"fun",
",",
"v",
")",
")",
"else",
":",
"return",
"fun",
"(",
"v",
"[",
":",
"-",
"1",
"]"... | 26.083333 | 0.009259 |
def stack(files, version="4.10", sync=True, **kwargs):
""" stack several files and return the stacked *MDF* object
Parameters
----------
files : list | tuple
list of *MDF* file names or *MDF* instances
version : str
merged file version
sync : bool... | [
"def",
"stack",
"(",
"files",
",",
"version",
"=",
"\"4.10\"",
",",
"sync",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"files",
":",
"raise",
"MdfException",
"(",
"\"No files given for stack\"",
")",
"version",
"=",
"validate_version_argume... | 40.330472 | 0.001454 |
def splitdrive(path):
"""
Split the path into a pair (drive, tail) where drive is either a
mount point or the empty string. On systems which do not use drive
specifications, drive will always be the empty string.
In all cases, drive + tail will be the same as path.
Equivalent to "os.path.split... | [
"def",
"splitdrive",
"(",
"path",
")",
":",
"relative",
"=",
"get_instance",
"(",
"path",
")",
".",
"relpath",
"(",
"path",
")",
"drive",
"=",
"path",
".",
"rsplit",
"(",
"relative",
",",
"1",
")",
"[",
"0",
"]",
"if",
"drive",
"and",
"not",
"drive... | 29.217391 | 0.001441 |
def validate_email(email, check_mx=False, verify=False, debug=False, smtp_timeout=10):
"""Indicate whether the given string is a valid email address
according to the 'addr-spec' portion of RFC 2822 (see section
3.4.1). Parts of the spec that are marked obsolete are *not*
included in this test, and cert... | [
"def",
"validate_email",
"(",
"email",
",",
"check_mx",
"=",
"False",
",",
"verify",
"=",
"False",
",",
"debug",
"=",
"False",
",",
"smtp_timeout",
"=",
"10",
")",
":",
"if",
"debug",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'validate_email... | 42.515152 | 0.00209 |
def get_sphinx_ref(self, url, label=None):
"""
Get an internal sphinx cross reference corresponding to `url`
into the online docs, associated with a link with label `label`
(if not None).
"""
# Raise an exception if the initial part of url does not match
# the ba... | [
"def",
"get_sphinx_ref",
"(",
"self",
",",
"url",
",",
"label",
"=",
"None",
")",
":",
"# Raise an exception if the initial part of url does not match",
"# the base url for this object",
"n",
"=",
"len",
"(",
"self",
".",
"baseurl",
")",
"if",
"url",
"[",
"0",
":"... | 38.382353 | 0.001495 |
def community_post_comment_delete(self, post_id, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/post_comments#delete-comment"
api_path = "/api/v2/community/posts/{post_id}/comments/{id}.json"
api_path = api_path.format(post_id=post_id, id=id)
return self.call(api... | [
"def",
"community_post_comment_delete",
"(",
"self",
",",
"post_id",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/community/posts/{post_id}/comments/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"post_id",
"=",
"post_id"... | 69.8 | 0.008499 |
def _verify_pair(prev, curr):
"""Verify a pair of sides share an endpoint.
.. note::
This currently checks that edge endpoints match **exactly**
but allowing some roundoff may be desired.
Args:
prev (.Curve): "Previous" curve at piecewise junction.
... | [
"def",
"_verify_pair",
"(",
"prev",
",",
"curr",
")",
":",
"if",
"prev",
".",
"_dimension",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"Curve not in R^2\"",
",",
"prev",
")",
"end",
"=",
"prev",
".",
"_nodes",
"[",
":",
",",
"-",
"1",
"]",
"start"... | 32.285714 | 0.002148 |
def wait(timeout=300):
"""Wait util target connected"""
if env():
cij.err("cij.ssh.wait: Invalid SSH environment")
return 1
timeout_backup = cij.ENV.get("SSH_CMD_TIMEOUT")
try:
time_start = time.time()
cij.ENV["SSH_CMD_TIMEOUT"] = "3"
while True:
... | [
"def",
"wait",
"(",
"timeout",
"=",
"300",
")",
":",
"if",
"env",
"(",
")",
":",
"cij",
".",
"err",
"(",
"\"cij.ssh.wait: Invalid SSH environment\"",
")",
"return",
"1",
"timeout_backup",
"=",
"cij",
".",
"ENV",
".",
"get",
"(",
"\"SSH_CMD_TIMEOUT\"",
")",... | 25.060606 | 0.002328 |
def _advapi32_generate_pair(algorithm, bit_size=None):
"""
Generates a public/private key pair using CryptoAPI
:param algorithm:
The key algorithm - "rsa" or "dsa"
:param bit_size:
An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024,
2048, 3072 or 4096. For ... | [
"def",
"_advapi32_generate_pair",
"(",
"algorithm",
",",
"bit_size",
"=",
"None",
")",
":",
"if",
"algorithm",
"==",
"'rsa'",
":",
"provider",
"=",
"Advapi32Const",
".",
"MS_ENH_RSA_AES_PROV",
"algorithm_id",
"=",
"Advapi32Const",
".",
"CALG_RSA_SIGN",
"struct_type"... | 32.553571 | 0.001863 |
def resp_json(resp):
"""
Get JSON from response if success, raise requests.HTTPError otherwise.
Args:
resp: requests.Response or flask.Response
Retuens:
JSON value
"""
if isinstance(resp, flask.Response):
if 400 <= resp.status_code < 600:
msg = resp.status
... | [
"def",
"resp_json",
"(",
"resp",
")",
":",
"if",
"isinstance",
"(",
"resp",
",",
"flask",
".",
"Response",
")",
":",
"if",
"400",
"<=",
"resp",
".",
"status_code",
"<",
"600",
":",
"msg",
"=",
"resp",
".",
"status",
"try",
":",
"result",
"=",
"load... | 33.378378 | 0.000787 |
def rsdl_s(self, Yprev, Y):
"""Compute dual residual vector."""
return self.rho * self.cnst_AT(self.U) | [
"def",
"rsdl_s",
"(",
"self",
",",
"Yprev",
",",
"Y",
")",
":",
"return",
"self",
".",
"rho",
"*",
"self",
".",
"cnst_AT",
"(",
"self",
".",
"U",
")"
] | 29 | 0.016807 |
def refresh(self):
"""Re-pulls the data from redis"""
redis_key = EXPERIMENT_REDIS_KEY_TEMPLATE % self.experiment.name
self.plays = int(self.experiment.redis.hget(redis_key, "%s:plays" % self.name) or 0)
self.rewards = int(self.experiment.redis.hget(redis_key, "%s:rewards" % self.name) ... | [
"def",
"refresh",
"(",
"self",
")",
":",
"redis_key",
"=",
"EXPERIMENT_REDIS_KEY_TEMPLATE",
"%",
"self",
".",
"experiment",
".",
"name",
"self",
".",
"plays",
"=",
"int",
"(",
"self",
".",
"experiment",
".",
"redis",
".",
"hget",
"(",
"redis_key",
",",
"... | 55.285714 | 0.010178 |
def start(self):
"""Run PostgresGreenlet and web/debug servers."""
self.logger.debug('PostgresGreenlet start')
self._stop_event.clear()
self.print('=> Discovering DDP endpoints...')
if self.verbosity > 1:
for api_path in sorted(self.api.api_path_map()):
... | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'PostgresGreenlet start'",
")",
"self",
".",
"_stop_event",
".",
"clear",
"(",
")",
"self",
".",
"print",
"(",
"'=> Discovering DDP endpoints...'",
")",
"if",
"self",
".",
"v... | 41.472222 | 0.001309 |
def minimumLineInArray(arr, relative=False, f=0,
refinePosition=True,
max_pos=100,
return_pos_arr=False,
# order=2
):
'''
find closest minimum position next to middle line
relative: ret... | [
"def",
"minimumLineInArray",
"(",
"arr",
",",
"relative",
"=",
"False",
",",
"f",
"=",
"0",
",",
"refinePosition",
"=",
"True",
",",
"max_pos",
"=",
"100",
",",
"return_pos_arr",
"=",
"False",
",",
"# order=2\r",
")",
":",
"s0",
",",
"s1",
"=",
"arr",
... | 28.652174 | 0.001467 |
def verify(self, key, data, signature, mecha=MechanismRSAPKCS1):
"""
C_VerifyInit/C_Verify
:param key: a key handle, obtained calling :func:`findObjects`.
:type key: integer
:param data: the data that was signed
:type data: (binary) string or list/tuple of bytes
... | [
"def",
"verify",
"(",
"self",
",",
"key",
",",
"data",
",",
"signature",
",",
"mecha",
"=",
"MechanismRSAPKCS1",
")",
":",
"m",
"=",
"mecha",
".",
"to_native",
"(",
")",
"data1",
"=",
"ckbytelist",
"(",
"data",
")",
"rv",
"=",
"self",
".",
"lib",
"... | 36.448276 | 0.001843 |
def _create_slots_class(self):
"""
Build and return a new class with a `__slots__` attribute.
"""
base_names = self._base_names
cd = {
k: v
for k, v in iteritems(self._cls_dict)
if k not in tuple(self._attr_names) + ("__dict__", "__weakref__")
... | [
"def",
"_create_slots_class",
"(",
"self",
")",
":",
"base_names",
"=",
"self",
".",
"_base_names",
"cd",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"self",
".",
"_cls_dict",
")",
"if",
"k",
"not",
"in",
"tuple",
"(",
"s... | 39.368421 | 0.000522 |
def split_qs(string, delimiter='&'):
"""Split a string by the specified unquoted, not enclosed delimiter"""
open_list = '[<{('
close_list = ']>})'
quote_chars = '"\''
level = index = last_index = 0
quoted = False
result = []
for index, letter in enumerate(string):
if letter in... | [
"def",
"split_qs",
"(",
"string",
",",
"delimiter",
"=",
"'&'",
")",
":",
"open_list",
"=",
"'[<{('",
"close_list",
"=",
"']>})'",
"quote_chars",
"=",
"'\"\\''",
"level",
"=",
"index",
"=",
"last_index",
"=",
"0",
"quoted",
"=",
"False",
"result",
"=",
"... | 25.944444 | 0.002064 |
def RGB(self, val):
"""Set the color using an Nx3 array of RGB uint8 values"""
# need to convert to normalized float
val = np.atleast_1d(val).astype(np.float32) / 255.
self.rgba = val | [
"def",
"RGB",
"(",
"self",
",",
"val",
")",
":",
"# need to convert to normalized float",
"val",
"=",
"np",
".",
"atleast_1d",
"(",
"val",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"/",
"255.",
"self",
".",
"rgba",
"=",
"val"
] | 42.2 | 0.009302 |
def join(self):
"""Wait until grid finishes computing."""
self._future = False
self._job.poll()
self._job = None | [
"def",
"join",
"(",
"self",
")",
":",
"self",
".",
"_future",
"=",
"False",
"self",
".",
"_job",
".",
"poll",
"(",
")",
"self",
".",
"_job",
"=",
"None"
] | 28 | 0.013889 |
def _sig_key(key, date_stamp, regionName, serviceName):
'''
Get a signature key. See:
http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
'''
kDate = _sign(('AWS4' + key).encode('utf-8'), date_stamp)
if regionName:
kRegion = _sign(kDate, ... | [
"def",
"_sig_key",
"(",
"key",
",",
"date_stamp",
",",
"regionName",
",",
"serviceName",
")",
":",
"kDate",
"=",
"_sign",
"(",
"(",
"'AWS4'",
"+",
"key",
")",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"date_stamp",
")",
"if",
"regionName",
":",
"kRegion... | 34.785714 | 0.002 |
def asZip(self):
"""
Return a serialised zip archive containing:
- callgrind profiling statistics (cachegrind.out.pprofile)
- any SQL query issued via ZMySQLDA (query_*.sql)
- any persistent object load via ZODB.Connection (ZODB_setstate.txt)
- any path argument given to ... | [
"def",
"asZip",
"(",
"self",
")",
":",
"out",
"=",
"BytesIO",
"(",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"out",
",",
"mode",
"=",
"'w'",
",",
"compression",
"=",
"zipfile",
".",
"ZIP_DEFLATED",
",",
")",
"as",
"outfile",
":",
"for",
"path",
... | 39.45 | 0.002475 |
def add_links(network_id, links,**kwargs):
'''
add links to network
'''
start_time = datetime.datetime.now()
user_id = kwargs.get('user_id')
names=[] # used to check uniqueness of link name before saving links to database
for l_i in links:
if l_i.name in names:
rai... | [
"def",
"add_links",
"(",
"network_id",
",",
"links",
",",
"*",
"*",
"kwargs",
")",
":",
"start_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"names",
"=",
"[",
"]",
"# used... | 36.451613 | 0.012069 |
def read_header(fd, endian):
"""Read and return the matrix header."""
flag_class, nzmax = read_elements(fd, endian, ['miUINT32'])
header = {
'mclass': flag_class & 0x0FF,
'is_logical': (flag_class >> 9 & 1) == 1,
'is_global': (flag_class >> 10 & 1) == 1,
'is_complex': (flag_c... | [
"def",
"read_header",
"(",
"fd",
",",
"endian",
")",
":",
"flag_class",
",",
"nzmax",
"=",
"read_elements",
"(",
"fd",
",",
"endian",
",",
"[",
"'miUINT32'",
"]",
")",
"header",
"=",
"{",
"'mclass'",
":",
"flag_class",
"&",
"0x0FF",
",",
"'is_logical'",
... | 40.8125 | 0.001497 |
def find_magic(self, magic_name, magic_kind='line'):
"""Find and return a magic of the given type by name.
Returns None if the magic isn't found."""
return self.magics_manager.magics[magic_kind].get(magic_name) | [
"def",
"find_magic",
"(",
"self",
",",
"magic_name",
",",
"magic_kind",
"=",
"'line'",
")",
":",
"return",
"self",
".",
"magics_manager",
".",
"magics",
"[",
"magic_kind",
"]",
".",
"get",
"(",
"magic_name",
")"
] | 46.2 | 0.008511 |
def stSpectogram(signal, fs, win, step, PLOT=False):
"""
Short-term FFT mag for spectogram estimation:
Returns:
a numpy array (nFFT x numOfShortTermWindows)
ARGUMENTS:
signal: the input signal samples
fs: the sampling freq (in Hz)
win: the short-term... | [
"def",
"stSpectogram",
"(",
"signal",
",",
"fs",
",",
"win",
",",
"step",
",",
"PLOT",
"=",
"False",
")",
":",
"win",
"=",
"int",
"(",
"win",
")",
"step",
"=",
"int",
"(",
"step",
")",
"signal",
"=",
"numpy",
".",
"double",
"(",
"signal",
")",
... | 32.428571 | 0.001425 |
def proxy(host='localhost', port=4304, flags=0, persistent=False,
verbose=False, ):
"""factory function that returns a proxy object for an owserver at
host, port.
"""
# resolve host name/port
try:
gai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM,
... | [
"def",
"proxy",
"(",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"4304",
",",
"flags",
"=",
"0",
",",
"persistent",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
")",
":",
"# resolve host name/port",
"try",
":",
"gai",
"=",
"socket",
".",
"getaddr... | 31.976744 | 0.000706 |
def _logsum(a_n):
"""Compute the log of a sum of exponentiated terms exp(a_n) in a numerically-stable manner.
NOTE: this function has been deprecated in favor of logsumexp.
Parameters
----------
a_n : np.ndarray, shape=(n_samples)
a_n[n] is the nth exponential argument
Returns
----... | [
"def",
"_logsum",
"(",
"a_n",
")",
":",
"# Compute the maximum argument.",
"max_log_term",
"=",
"np",
".",
"max",
"(",
"a_n",
")",
"# Compute the reduced terms.",
"terms",
"=",
"np",
".",
"exp",
"(",
"a_n",
"-",
"max_log_term",
")",
"# Compute the log sum.",
"lo... | 23.756098 | 0.008876 |
def apply(self, resource):
"""
Apply filter to resource
:param resource: Image
:return: Image
"""
if not isinstance(resource, Image.Image):
raise ValueError('Unknown resource format')
original_width, original_height = resource.size
if self.st... | [
"def",
"apply",
"(",
"self",
",",
"resource",
")",
":",
"if",
"not",
"isinstance",
"(",
"resource",
",",
"Image",
".",
"Image",
")",
":",
"raise",
"ValueError",
"(",
"'Unknown resource format'",
")",
"original_width",
",",
"original_height",
"=",
"resource",
... | 28.121212 | 0.002083 |
def pep8_check(files):
# type: (List[str]) -> int
""" Run code checks using pep8.
Args:
files (list[str]):
A list of files to check
Returns:
bool: **True** if all files passed the checks, **False** otherwise.
pep8 tool is **very** fast. Especially compared to pylint an... | [
"def",
"pep8_check",
"(",
"files",
")",
":",
"# type: (List[str]) -> int",
"files",
"=",
"fs",
".",
"wrap_paths",
"(",
"files",
")",
"cfg_path",
"=",
"conf",
".",
"get_path",
"(",
"'lint.pep8_cfg'",
",",
"'ops/tools/pep8.ini'",
")",
"pep8_cmd",
"=",
"'pep8 --con... | 38.772727 | 0.002288 |
def chunk_sequence(sequence, chunk_length, allow_incomplete=True):
"""Given a sequence, divide it into sequences of length `chunk_length`.
:param allow_incomplete: If True, allow final chunk to be shorter if the
given sequence is not an exact multiple of `chunk_length`.
If False, the incomplete... | [
"def",
"chunk_sequence",
"(",
"sequence",
",",
"chunk_length",
",",
"allow_incomplete",
"=",
"True",
")",
":",
"(",
"complete",
",",
"leftover",
")",
"=",
"divmod",
"(",
"len",
"(",
"sequence",
")",
",",
"chunk_length",
")",
"if",
"not",
"allow_incomplete",
... | 33.75 | 0.001441 |
def getWorkDirs():
"""get input/output dirs (same input/output layout as for package)"""
# get caller module
caller_fullurl = inspect.stack()[1][1]
caller_relurl = os.path.relpath(caller_fullurl)
caller_modurl = os.path.splitext(caller_relurl)[0]
# split caller_url & append 'Dir' to package name
dirs = ca... | [
"def",
"getWorkDirs",
"(",
")",
":",
"# get caller module",
"caller_fullurl",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"1",
"]",
"[",
"1",
"]",
"caller_relurl",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"caller_fullurl",
")",
"caller_modurl",
"=",
... | 37.421053 | 0.026063 |
def _get_genesplicer(data):
"""
This is a plugin for the Ensembl Variant Effect Predictor (VEP) that
runs GeneSplicer (https://ccb.jhu.edu/software/genesplicer/) to get splice site predictions.
https://github.com/Ensembl/VEP_plugins/blob/master/GeneSplicer.pm
"""
genesplicer_exec = os.path.real... | [
"def",
"_get_genesplicer",
"(",
"data",
")",
":",
"genesplicer_exec",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"config_utils",
".",
"get_program",
"(",
"\"genesplicer\"",
",",
"data",
"[",
"\"config\"",
"]",
")",
")",
"genesplicer_training",
"=",
"tz",
... | 54.615385 | 0.01108 |
def simple_signatures(ambiguous_word: str, pos: str = None, lemma=True, stem=False,
hyperhypo=True, stop=True, from_cache=True) -> dict:
"""
Returns a synsets_signatures dictionary that includes signature words of a
sense from its:
(i) definition
(ii) example sentences
(i... | [
"def",
"simple_signatures",
"(",
"ambiguous_word",
":",
"str",
",",
"pos",
":",
"str",
"=",
"None",
",",
"lemma",
"=",
"True",
",",
"stem",
"=",
"False",
",",
"hyperhypo",
"=",
"True",
",",
"stop",
"=",
"True",
",",
"from_cache",
"=",
"True",
")",
"-... | 44.722222 | 0.008516 |
def connect_build(self, nyamuk, keepalive, clean_session, retain = 0, dup = 0, version = 3):
"""Build packet for CONNECT command."""
will = 0; will_topic = None
byte = 0
client_id = utf8encode(nyamuk.client_id)
username = utf8encode(nyamuk.username) if nyamuk.username is not No... | [
"def",
"connect_build",
"(",
"self",
",",
"nyamuk",
",",
"keepalive",
",",
"clean_session",
",",
"retain",
"=",
"0",
",",
"dup",
"=",
"0",
",",
"version",
"=",
"3",
")",
":",
"will",
"=",
"0",
"will_topic",
"=",
"None",
"byte",
"=",
"0",
"client_id",... | 34.033333 | 0.015231 |
def post_ext_init(state):
"""Setup blueprint."""
app = state.app
app.config.setdefault(
'OAUTHCLIENT_SITENAME',
app.config.get('THEME_SITENAME', 'Invenio'))
app.config.setdefault(
'OAUTHCLIENT_BASE_TEMPLATE',
app.config.get('BASE_TEMPLATE',
'inveni... | [
"def",
"post_ext_init",
"(",
"state",
")",
":",
"app",
"=",
"state",
".",
"app",
"app",
".",
"config",
".",
"setdefault",
"(",
"'OAUTHCLIENT_SITENAME'",
",",
"app",
".",
"config",
".",
"get",
"(",
"'THEME_SITENAME'",
",",
"'Invenio'",
")",
")",
"app",
".... | 35.526316 | 0.001443 |
async def open_async(self):
"""
Starts the host.
"""
if not self.loop:
self.loop = asyncio.get_event_loop()
await self.partition_manager.start_async() | [
"async",
"def",
"open_async",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"loop",
":",
"self",
".",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"await",
"self",
".",
"partition_manager",
".",
"start_async",
"(",
")"
] | 28 | 0.009901 |
def get_time_data(self, timeStart=None, timeEnd=None):
"""
Gets the time and voltage data.
Parameters
----------
timeStart : float, optional
The time get data from.
By default it uses the first time point
timeEnd : float, optional
The ... | [
"def",
"get_time_data",
"(",
"self",
",",
"timeStart",
"=",
"None",
",",
"timeEnd",
"=",
"None",
")",
":",
"if",
"timeStart",
"==",
"None",
":",
"timeStart",
"=",
"self",
".",
"timeStart",
"if",
"timeEnd",
"==",
"None",
":",
"timeEnd",
"=",
"self",
"."... | 33.416667 | 0.008078 |
def _locate_day(year, cutoff):
"""
Takes a SYSTEMTIME object, such as retrieved from a TIME_ZONE_INFORMATION
structure or call to GetTimeZoneInformation and interprets
it based on the given
year to identify the actual day.
This method is necessary because the SYSTEMTIME structure
refers to a day by its
... | [
"def",
"_locate_day",
"(",
"year",
",",
"cutoff",
")",
":",
"# MS stores Sunday as 0, Python datetime stores Monday as zero",
"target_weekday",
"=",
"(",
"cutoff",
".",
"day_of_week",
"+",
"6",
")",
"%",
"7",
"# For SYSTEMTIMEs relating to time zone inforamtion, cutoff.day",
... | 39.571429 | 0.023488 |
def _add_additional_properties(position, properties_dict):
"""
Sets AdditionalProperties of the ProbModelXML.
"""
add_prop = etree.SubElement(position, 'AdditionalProperties')
for key, value in properties_dict.items():
etree.SubElement(add_prop, 'Property', attrib={'n... | [
"def",
"_add_additional_properties",
"(",
"position",
",",
"properties_dict",
")",
":",
"add_prop",
"=",
"etree",
".",
"SubElement",
"(",
"position",
",",
"'AdditionalProperties'",
")",
"for",
"key",
",",
"value",
"in",
"properties_dict",
".",
"items",
"(",
")",... | 48.714286 | 0.008646 |
def subpnt(method, target, et, fixref, abcorr, obsrvr):
"""
Compute the rectangular coordinates of the sub-observer point on
a target body at a specified epoch, optionally corrected for
light time and stellar aberration.
This routine supersedes :func:`subpt`.
http://naif.jpl.nasa.gov/pub/naif/... | [
"def",
"subpnt",
"(",
"method",
",",
"target",
",",
"et",
",",
"fixref",
",",
"abcorr",
",",
"obsrvr",
")",
":",
"method",
"=",
"stypes",
".",
"stringToCharP",
"(",
"method",
")",
"target",
"=",
"stypes",
".",
"stringToCharP",
"(",
"target",
")",
"et",... | 36.487805 | 0.001302 |
def get_topic(self):
""" Returns the topic to consider. """
if not hasattr(self, 'topic'):
self.topic = get_object_or_404(
Topic.objects.select_related('forum').all(), pk=self.kwargs['pk'],
)
return self.topic | [
"def",
"get_topic",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'topic'",
")",
":",
"self",
".",
"topic",
"=",
"get_object_or_404",
"(",
"Topic",
".",
"objects",
".",
"select_related",
"(",
"'forum'",
")",
".",
"all",
"(",
")",
... | 38.142857 | 0.010989 |
def qnm_freq_decay(f_0, tau, decay):
"""Return the frequency at which the amplitude of the
ringdown falls to decay of the peak amplitude.
Parameters
----------
f_0 : float
The ringdown-frequency, which gives the peak amplitude.
tau : float
The damping time of the sinusoid.
d... | [
"def",
"qnm_freq_decay",
"(",
"f_0",
",",
"tau",
",",
"decay",
")",
":",
"q_0",
"=",
"pi",
"*",
"f_0",
"*",
"tau",
"alpha",
"=",
"1.",
"/",
"decay",
"alpha_sq",
"=",
"1.",
"/",
"decay",
"/",
"decay",
"# Expression obtained analytically under the assumption",... | 29.392857 | 0.002353 |
def dafgs(n=125):
# The 125 may be a hard set,
# I got strange errors that occasionally happened without it
"""
Return (get) the summary for the current array in the current DAF.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafgs_c.html
:param n: Optional length N for result Array.
... | [
"def",
"dafgs",
"(",
"n",
"=",
"125",
")",
":",
"# The 125 may be a hard set,",
"# I got strange errors that occasionally happened without it",
"retarray",
"=",
"stypes",
".",
"emptyDoubleVector",
"(",
"125",
")",
"# libspice.dafgs_c(ctypes.cast(retarray, ctypes.POINTER(ctypes.c_... | 36.5 | 0.001669 |
def estimate(self,param,burn=None,clip=10.0,alpha=0.32):
""" Estimate parameter value and uncertainties """
# FIXME: Need to add age and metallicity to composite isochrone params (currently properties)
if param not in list(self.samples.names) + list(self.source.params) + ['age','metallicity']:
... | [
"def",
"estimate",
"(",
"self",
",",
"param",
",",
"burn",
"=",
"None",
",",
"clip",
"=",
"10.0",
",",
"alpha",
"=",
"0.32",
")",
":",
"# FIXME: Need to add age and metallicity to composite isochrone params (currently properties)",
"if",
"param",
"not",
"in",
"list"... | 43.8 | 0.018767 |
def validate_status_code_to_response_definition(response, operation_definition):
"""
Given a response, validate that the response status code is in the accepted
status codes defined by this endpoint.
If so, return the response definition that corresponds to the status code.
"""
status_code = re... | [
"def",
"validate_status_code_to_response_definition",
"(",
"response",
",",
"operation_definition",
")",
":",
"status_code",
"=",
"response",
".",
"status_code",
"operation_responses",
"=",
"{",
"str",
"(",
"code",
")",
":",
"val",
"for",
"code",
",",
"val",
"in",... | 34.791667 | 0.002331 |
def clear_caches(self, hard=False):
"""Clear all caches in Rez.
Rez caches package contents and iteration during a python session. Thus
newly released packages, and changes to existing packages, may not be
picked up. You need to clear the cache for these changes to become
visibl... | [
"def",
"clear_caches",
"(",
"self",
",",
"hard",
"=",
"False",
")",
":",
"from",
"rez",
".",
"package_repository",
"import",
"package_repository_manager",
"from",
"rez",
".",
"utils",
".",
"memcached",
"import",
"memcached_client",
"package_repository_manager",
".",... | 40.9 | 0.002389 |
def batch_norm(attrs, inputs, proto_obj):
"""Batch normalization."""
new_attrs = translation_utils._fix_attribute_names(attrs, {'epsilon': 'eps',
'is_test': 'fix_gamma'})
new_attrs = translation_utils._remove_attributes(new_attrs,
... | [
"def",
"batch_norm",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"new_attrs",
"=",
"translation_utils",
".",
"_fix_attribute_names",
"(",
"attrs",
",",
"{",
"'epsilon'",
":",
"'eps'",
",",
"'is_test'",
":",
"'fix_gamma'",
"}",
")",
"new_attrs",
... | 57.785714 | 0.008516 |
def list_to_serialized(ref, the_list):
"""Serialize the list of elements
Used for the retention store
:param ref: Not used
:type ref:
:param the_list: dictionary to convert
:type the_list: dict
:return: dict of serialized
:rtype: dict
"""
result = []
for elt in the_list:
... | [
"def",
"list_to_serialized",
"(",
"ref",
",",
"the_list",
")",
":",
"result",
"=",
"[",
"]",
"for",
"elt",
"in",
"the_list",
":",
"if",
"not",
"getattr",
"(",
"elt",
",",
"'serialize'",
",",
"None",
")",
":",
"continue",
"result",
".",
"append",
"(",
... | 23.666667 | 0.002257 |
def basic_lstm(inputs, state, num_units, name=None):
"""Basic LSTM."""
input_shape = common_layers.shape_list(inputs)
# reuse parameters across time-steps.
cell = tf.nn.rnn_cell.BasicLSTMCell(
num_units, name=name, reuse=tf.AUTO_REUSE)
if state is None:
state = cell.zero_state(input_shape[0], tf.flo... | [
"def",
"basic_lstm",
"(",
"inputs",
",",
"state",
",",
"num_units",
",",
"name",
"=",
"None",
")",
":",
"input_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"inputs",
")",
"# reuse parameters across time-steps.",
"cell",
"=",
"tf",
".",
"nn",
".",
"r... | 38.7 | 0.020202 |
def filter_concept_names(stmts_in, name_list, policy, **kwargs):
"""Return Statements that refer to concepts/agents given as a list of names.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of Statements to filter.
name_list : list[str]
A list of concept/age... | [
"def",
"filter_concept_names",
"(",
"stmts_in",
",",
"name_list",
",",
"policy",
",",
"*",
"*",
"kwargs",
")",
":",
"invert",
"=",
"kwargs",
".",
"get",
"(",
"'invert'",
",",
"False",
")",
"if",
"policy",
"not",
"in",
"(",
"'one'",
",",
"'all'",
")",
... | 35.626866 | 0.000815 |
def flush(self, frame):
'''
Passes the drawqueue to the sink for rendering
'''
self.sink.render(self.size_or_default(), frame, self._drawqueue)
self.reset_drawqueue() | [
"def",
"flush",
"(",
"self",
",",
"frame",
")",
":",
"self",
".",
"sink",
".",
"render",
"(",
"self",
".",
"size_or_default",
"(",
")",
",",
"frame",
",",
"self",
".",
"_drawqueue",
")",
"self",
".",
"reset_drawqueue",
"(",
")"
] | 33.5 | 0.009709 |
def dset_info(dset):
'''returns a :class:`DsetInfo` object containing the meta-data from ``dset``'''
if nl.pkg_available('afni'):
return _dset_info_afni(dset)
nl.notify('Error: no packages available to get dset info',level=nl.level.error)
return None | [
"def",
"dset_info",
"(",
"dset",
")",
":",
"if",
"nl",
".",
"pkg_available",
"(",
"'afni'",
")",
":",
"return",
"_dset_info_afni",
"(",
"dset",
")",
"nl",
".",
"notify",
"(",
"'Error: no packages available to get dset info'",
",",
"level",
"=",
"nl",
".",
"l... | 44.833333 | 0.014599 |
def migrate_keys(self, host, port, keys, dest_db, timeout, *,
copy=False, replace=False):
"""Atomically transfer keys from one Redis instance to another one.
Keys argument must be list/tuple of keys to migrate.
"""
if not isinstance(host, str):
raise Typ... | [
"def",
"migrate_keys",
"(",
"self",
",",
"host",
",",
"port",
",",
"keys",
",",
"dest_db",
",",
"timeout",
",",
"*",
",",
"copy",
"=",
"False",
",",
"replace",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"host",
",",
"str",
")",
":",
... | 38.818182 | 0.002285 |
def wrap(cls, meth):
'''
Wraps a connection opening method in this class.
'''
async def inner(*args, **kwargs):
sock = await meth(*args, **kwargs)
return cls(sock)
return inner | [
"def",
"wrap",
"(",
"cls",
",",
"meth",
")",
":",
"async",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"sock",
"=",
"await",
"meth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"cls",
"(",
"sock",
")",
"... | 23.3 | 0.008264 |
def set_target(module, target, module_parameter=None, action_parameter=None):
'''
Set the target for the given module.
Target can be specified by index or name.
module
name of the module for which a target should be set
target
name of the target to be set for this module
modul... | [
"def",
"set_target",
"(",
"module",
",",
"target",
",",
"module_parameter",
"=",
"None",
",",
"action_parameter",
"=",
"None",
")",
":",
"if",
"action_parameter",
":",
"action_parameter",
"=",
"'{0} {1}'",
".",
"format",
"(",
"action_parameter",
",",
"target",
... | 28.651163 | 0.002355 |
def plot_coordinates(network, pores=None, fig=None, **kwargs):
r"""
Produces a 3D plot showing specified pore coordinates as markers
Parameters
----------
network : OpenPNM Network Object
The network whose topological connections to plot
pores : array_like (optional)
The list o... | [
"def",
"plot_coordinates",
"(",
"network",
",",
"pores",
"=",
"None",
",",
"fig",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"from",
"mpl_toolkits",
".",
"mplot3d",
"import",
"Axes3D",
"if",
"pores... | 30.081395 | 0.000374 |
def get_wrapped_stream(stream, encoding=None, errors="replace"):
"""
Given a stream, wrap it in a `StreamWrapper` instance and return the wrapped stream.
:param stream: A stream instance to wrap
:param str encoding: The encoding to use for the stream
:param str errors: The error handler to use, def... | [
"def",
"get_wrapped_stream",
"(",
"stream",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"\"replace\"",
")",
":",
"if",
"stream",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"must provide a stream to wrap\"",
")",
"stream",
"=",
"_get_binary_buffer",
"(... | 37.904762 | 0.002451 |
def query(params):
"""`params` is a city name or a city name + hospital name.
CLI:
1. query all putian hospitals in a city:
$ iquery -p 南京
+------+
| 南京 |
+------+
|... |
+------+
|... |
+------+
...
2. query if the... | [
"def",
"query",
"(",
"params",
")",
":",
"r",
"=",
"requests_get",
"(",
"QUERY_URL",
",",
"verify",
"=",
"True",
")",
"return",
"HospitalCollection",
"(",
"r",
".",
"json",
"(",
")",
",",
"params",
")"
] | 18.787879 | 0.001534 |
def alignmentPanel(titlesAlignments, sortOn='maxScore', idList=False,
equalizeXAxes=False, xRange='subject', logLinearXAxis=False,
rankScores=False, showFeatures=True,
logBase=DEFAULT_LOG_LINEAR_X_AXIS_BASE):
"""
Produces a rectangular panel of graphs tha... | [
"def",
"alignmentPanel",
"(",
"titlesAlignments",
",",
"sortOn",
"=",
"'maxScore'",
",",
"idList",
"=",
"False",
",",
"equalizeXAxes",
"=",
"False",
",",
"xRange",
"=",
"'subject'",
",",
"logLinearXAxis",
"=",
"False",
",",
"rankScores",
"=",
"False",
",",
"... | 42.977273 | 0.000172 |
def checktypes(func):
"""Decorator to verify arguments and return types."""
sig = inspect.signature(func)
types = {}
for param in sig.parameters.values():
# Iterate through function's parameters and build the list of
# arguments types
param_type = param.annotation
if par... | [
"def",
"checktypes",
"(",
"func",
")",
":",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
"types",
"=",
"{",
"}",
"for",
"param",
"in",
"sig",
".",
"parameters",
".",
"values",
"(",
")",
":",
"# Iterate through function's parameters and build th... | 42.051948 | 0.000302 |
def hexdump(data, cols=8, folded=False, stream=False, offset=0, header=False):
"""
yields the rows of the hex dump
Arguments:
data -- data to dump
cols -- number of octets per row
folded -- fold long ranges of equal bytes
stream -- dont use len on data
>>> from string i... | [
"def",
"hexdump",
"(",
"data",
",",
"cols",
"=",
"8",
",",
"folded",
"=",
"False",
",",
"stream",
"=",
"False",
",",
"offset",
"=",
"0",
",",
"header",
"=",
"False",
")",
":",
"last_byte",
"=",
"None",
"fold",
"=",
"False",
"# determine index width",
... | 33.768293 | 0.000526 |
def gcd2(a, b):
"""Greatest common divisor using Euclid's algorithm."""
while a:
a, b = b%a, a
return b | [
"def",
"gcd2",
"(",
"a",
",",
"b",
")",
":",
"while",
"a",
":",
"a",
",",
"b",
"=",
"b",
"%",
"a",
",",
"a",
"return",
"b"
] | 21.8 | 0.044248 |
def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space via pairwise
atom-atom distances
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.n... | [
"def",
"partial_transform",
"(",
"self",
",",
"traj",
")",
":",
"d",
"=",
"md",
".",
"geometry",
".",
"compute_distances",
"(",
"traj",
",",
"self",
".",
"pair_indices",
",",
"periodic",
"=",
"self",
".",
"periodic",
")",
"return",
"d",
"**",
"self",
"... | 37.541667 | 0.002165 |
def get_all_events_with_time_range(self, **kwargs): # noqa: E501
"""List all the events for a customer within a time range # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> ... | [
"def",
"get_all_events_with_time_range",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"get_all_even... | 43.708333 | 0.001866 |
def mac_to_ipv6_linklocal(mac,prefix="fe80::"):
""" Translate a MAC address into an IPv6 address in the prefixed network.
This function calculates the EUI (Extended Unique Identifier) from the given
MAC address and prepend the needed prefix to come up with a valid IPv6 address.
The default prefix is th... | [
"def",
"mac_to_ipv6_linklocal",
"(",
"mac",
",",
"prefix",
"=",
"\"fe80::\"",
")",
":",
"# Remove the most common delimiters; dots, dashes, etc.",
"mac_value",
"=",
"int",
"(",
"mac",
".",
"translate",
"(",
"str",
".",
"maketrans",
"(",
"dict",
"(",
"[",
"(",
"x... | 40.296296 | 0.008977 |
def _control_vm(self, command, expected=None):
"""
Executes a command with QEMU monitor when this VM is running.
:param command: QEMU monitor command (e.g. info status, stop etc.)
:param expected: An array of expected strings
:returns: result of the command (matched object or N... | [
"def",
"_control_vm",
"(",
"self",
",",
"command",
",",
"expected",
"=",
"None",
")",
":",
"result",
"=",
"None",
"if",
"self",
".",
"is_running",
"(",
")",
"and",
"self",
".",
"_monitor",
":",
"log",
".",
"debug",
"(",
"\"Execute QEMU monitor command: {}\... | 42.128205 | 0.00238 |
def is_datetime(property_name, *, format=None, present_optional=False, message=None):
"""Returns a Validation that checks a value as a datetime."""
# NOTE: Not currently using format param
def check(val):
"""Checks that a value can be parsed as a datetime."""
if val is None:
return prese... | [
"def",
"is_datetime",
"(",
"property_name",
",",
"*",
",",
"format",
"=",
"None",
",",
"present_optional",
"=",
"False",
",",
"message",
"=",
"None",
")",
":",
"# NOTE: Not currently using format param",
"def",
"check",
"(",
"val",
")",
":",
"\"\"\"Checks that a... | 38.25 | 0.010638 |
def last_modified(self, last_modified):
"""Set Indicator lastModified."""
self._indicator_data['lastModified'] = self._utils.format_datetime(
last_modified, date_format='%Y-%m-%dT%H:%M:%SZ'
) | [
"def",
"last_modified",
"(",
"self",
",",
"last_modified",
")",
":",
"self",
".",
"_indicator_data",
"[",
"'lastModified'",
"]",
"=",
"self",
".",
"_utils",
".",
"format_datetime",
"(",
"last_modified",
",",
"date_format",
"=",
"'%Y-%m-%dT%H:%M:%SZ'",
")"
] | 44.6 | 0.008811 |
def _items(self):
"""
Parse url and yield namedtuple Torrent for every torrent on page
"""
torrents = map(self._get_torrent, self._get_rows())
for t in torrents:
yield t | [
"def",
"_items",
"(",
"self",
")",
":",
"torrents",
"=",
"map",
"(",
"self",
".",
"_get_torrent",
",",
"self",
".",
"_get_rows",
"(",
")",
")",
"for",
"t",
"in",
"torrents",
":",
"yield",
"t"
] | 26.875 | 0.009009 |
def fit(self, fixed=None, random=None, priors=None, family='gaussian',
link=None, run=True, categorical=None, backend=None, **kwargs):
'''Fit the model using the specified BackEnd.
Args:
fixed (str): Optional formula specification of fixed effects.
random (list): Opt... | [
"def",
"fit",
"(",
"self",
",",
"fixed",
"=",
"None",
",",
"random",
"=",
"None",
",",
"priors",
"=",
"None",
",",
"family",
"=",
"'gaussian'",
",",
"link",
"=",
"None",
",",
"run",
"=",
"True",
",",
"categorical",
"=",
"None",
",",
"backend",
"=",... | 57.27451 | 0.001346 |
def is_offsetlike(arr_or_obj):
"""
Check if obj or all elements of list-like is DateOffset
Parameters
----------
arr_or_obj : object
Returns
-------
boolean
Whether the object is a DateOffset or listlike of DatetOffsets
Examples
--------
>>> is_offsetlike(pd.DateOf... | [
"def",
"is_offsetlike",
"(",
"arr_or_obj",
")",
":",
"if",
"isinstance",
"(",
"arr_or_obj",
",",
"ABCDateOffset",
")",
":",
"return",
"True",
"elif",
"(",
"is_list_like",
"(",
"arr_or_obj",
")",
"and",
"len",
"(",
"arr_or_obj",
")",
"and",
"is_object_dtype",
... | 26.033333 | 0.001235 |
def zext(self, num):
"""Zero-extend this farray by *num* bits.
Returns a new farray.
"""
zero = self.ftype.box(0)
return self.__class__(self._items + [zero] * num, ftype=self.ftype) | [
"def",
"zext",
"(",
"self",
",",
"num",
")",
":",
"zero",
"=",
"self",
".",
"ftype",
".",
"box",
"(",
"0",
")",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"_items",
"+",
"[",
"zero",
"]",
"*",
"num",
",",
"ftype",
"=",
"self",
".",
... | 30.857143 | 0.009009 |
def _infer_xy_labels(darray, x, y, imshow=False, rgb=None):
"""
Determine x and y labels. For use in _plot2d
darray must be a 2 dimensional data array, or 3d for imshow only.
"""
assert x is None or x != y
if imshow and darray.ndim == 3:
return _infer_xy_labels_3d(darray, x, y, rgb)
... | [
"def",
"_infer_xy_labels",
"(",
"darray",
",",
"x",
",",
"y",
",",
"imshow",
"=",
"False",
",",
"rgb",
"=",
"None",
")",
":",
"assert",
"x",
"is",
"None",
"or",
"x",
"!=",
"y",
"if",
"imshow",
"and",
"darray",
".",
"ndim",
"==",
"3",
":",
"return... | 42.16 | 0.000928 |
def register_actions(self, shortcut_manager):
"""Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions.
"""
self.add_callback_to_shortcut_man... | [
"def",
"register_actions",
"(",
"self",
",",
"shortcut_manager",
")",
":",
"self",
".",
"add_callback_to_shortcut_manager",
"(",
"'save'",
",",
"partial",
"(",
"self",
".",
"call_action_callback",
",",
"\"on_save_activate\"",
")",
")",
"self",
".",
"add_callback_to_... | 86.285714 | 0.009413 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.