text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def disttar(target, source, env):
"""tar archive builder"""
import tarfile
env_dict = env.Dictionary()
if env_dict.get("DISTTAR_FORMAT") in ["gz", "bz2"]:
tar_format = env_dict["DISTTAR_FORMAT"]
else:
tar_format = ""
# split the target ... | [
"def",
"disttar",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"import",
"tarfile",
"env_dict",
"=",
"env",
".",
"Dictionary",
"(",
")",
"if",
"env_dict",
".",
"get",
"(",
"\"DISTTAR_FORMAT\"",
")",
"in",
"[",
"\"gz\"",
",",
"\"bz2\"",
"]",
":",... | 34.257143 | 0.008921 |
def discard_config(self):
"""Discard changes (rollback 0)."""
self.device.cu.rollback(rb_id=0)
if not self.config_lock:
self._unlock() | [
"def",
"discard_config",
"(",
"self",
")",
":",
"self",
".",
"device",
".",
"cu",
".",
"rollback",
"(",
"rb_id",
"=",
"0",
")",
"if",
"not",
"self",
".",
"config_lock",
":",
"self",
".",
"_unlock",
"(",
")"
] | 33.2 | 0.011765 |
def start(self, max_value=None, init=True):
'''Starts measuring time, and prints the bar at 0%.
It returns self so you can use it like this:
Args:
max_value (int): The maximum value of the progressbar
reinit (bool): Initialize the progressbar, this is useful if you
... | [
"def",
"start",
"(",
"self",
",",
"max_value",
"=",
"None",
",",
"init",
"=",
"True",
")",
":",
"if",
"init",
":",
"self",
".",
"init",
"(",
")",
"# Prevent multiple starts",
"if",
"self",
".",
"start_time",
"is",
"not",
"None",
":",
"# pragma: no cover"... | 32.753846 | 0.000912 |
def append(self, data):
"""Append data to a file."""
data_length = len(data)
if self._size + data_length > self._flush_size:
self.flush()
if not self._exclusive and data_length > _FILE_POOL_MAX_SIZE:
raise errors.Error(
"Too big input %s (%s)." % (data_length, _FILE_POOL_MAX_SIZE... | [
"def",
"append",
"(",
"self",
",",
"data",
")",
":",
"data_length",
"=",
"len",
"(",
"data",
")",
"if",
"self",
".",
"_size",
"+",
"data_length",
">",
"self",
".",
"_flush_size",
":",
"self",
".",
"flush",
"(",
")",
"if",
"not",
"self",
".",
"_excl... | 29.333333 | 0.015419 |
def time_average(rho, t):
r"""Return a time-averaged density matrix (using trapezium rule).
We test a basic two-level system.
>>> import numpy as np
>>> from scipy.constants import physical_constants
>>> from sympy import Matrix, symbols
>>> from fast.electric_field import electric_field_ampli... | [
"def",
"time_average",
"(",
"rho",
",",
"t",
")",
":",
"T",
"=",
"t",
"[",
"-",
"1",
"]",
"-",
"t",
"[",
"0",
"]",
"dt",
"=",
"t",
"[",
"1",
"]",
"-",
"t",
"[",
"0",
"]",
"rhoav",
"=",
"np",
".",
"sum",
"(",
"rho",
"[",
"1",
":",
"-",... | 33.54386 | 0.000508 |
def _recv_loop(self):
"""Sits in tight loop collecting data received from peer and
processing it.
"""
required_len = BGP_MIN_MSG_LEN
conn_lost_reason = "Connection lost as protocol is no longer active"
try:
while True:
next_bytes = self._socket... | [
"def",
"_recv_loop",
"(",
"self",
")",
":",
"required_len",
"=",
"BGP_MIN_MSG_LEN",
"conn_lost_reason",
"=",
"\"Connection lost as protocol is no longer active\"",
"try",
":",
"while",
"True",
":",
"next_bytes",
"=",
"self",
".",
"_socket",
".",
"recv",
"(",
"requir... | 40.5 | 0.002193 |
def list(self, **params):
"""
Retrieve all lead unqualified reasons
Returns all lead unqualified reasons available to the user according to the parameters provided
:calls: ``get /lead_unqualified_reasons``
:param dict params: (optional) Search options.
:return: List of ... | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"lead_unqualified_reasons",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/lead_unqualified_reasons\"",
",",
"params",
"=",
"params",
")",
"return",
"lead_unqualified_r... | 42.142857 | 0.008292 |
def set_local(self, key=None, value=None, data=None, **kwdata):
"""
Locally store some data associated with this conversation.
Data can be passed in either as a single dict, or as key-word args.
For example, if you need to store the previous value of a remote field
to determine... | [
"def",
"set_local",
"(",
"self",
",",
"key",
"=",
"None",
",",
"value",
"=",
"None",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwdata",
")",
":",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"{",
"}",
"if",
"key",
"is",
"not",
"None",
":",
"... | 39.870968 | 0.00158 |
def reset_params(self):
"""(Re)set all parameters."""
units = [self.input_units]
units += [self.hidden_units] * self.num_hidden
units += [self.output_units]
sequence = []
for u0, u1 in zip(units, units[1:]):
sequence.append(nn.Linear(u0, u1))
sequ... | [
"def",
"reset_params",
"(",
"self",
")",
":",
"units",
"=",
"[",
"self",
".",
"input_units",
"]",
"units",
"+=",
"[",
"self",
".",
"hidden_units",
"]",
"*",
"self",
".",
"num_hidden",
"units",
"+=",
"[",
"self",
".",
"output_units",
"]",
"sequence",
"=... | 32.176471 | 0.003552 |
def find_page_of_state_m(self, state_m):
"""Return the identifier and page of a given state model
:param state_m: The state model to be searched
:return: page containing the state and the state_identifier
"""
for state_identifier, page_info in list(self.tabs.items()):
... | [
"def",
"find_page_of_state_m",
"(",
"self",
",",
"state_m",
")",
":",
"for",
"state_identifier",
",",
"page_info",
"in",
"list",
"(",
"self",
".",
"tabs",
".",
"items",
"(",
")",
")",
":",
"if",
"page_info",
"[",
"'state_m'",
"]",
"is",
"state_m",
":",
... | 43.3 | 0.004525 |
def get_model(self, model_name):
"""
TODO: Need to validate model name has 2x '.' chars
"""
klass = None
try:
module_name, class_name = model_name.rsplit('.', 1)
mod = __import__(module_name, fromlist=[class_name])
klass = getattr(mod, class_na... | [
"def",
"get_model",
"(",
"self",
",",
"model_name",
")",
":",
"klass",
"=",
"None",
"try",
":",
"module_name",
",",
"class_name",
"=",
"model_name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"mod",
"=",
"__import__",
"(",
"module_name",
",",
"fromlist",
... | 33.076923 | 0.004525 |
def to_bytes(s):
"""
将字符串转换成字节数组
:param s: 要转换成字节数组的字符串
:return: 转换成字节数组的字符串
"""
if bytes != str:
if type(s) == str:
return s.encode('utf-8')
return s | [
"def",
"to_bytes",
"(",
"s",
")",
":",
"if",
"bytes",
"!=",
"str",
":",
"if",
"type",
"(",
"s",
")",
"==",
"str",
":",
"return",
"s",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"s"
] | 18.9 | 0.005051 |
def _init(self):
"""Read the line number."""
self._line_number = next_line(
self._communication.last_requested_line_number,
self._file.read(1)[0]) | [
"def",
"_init",
"(",
"self",
")",
":",
"self",
".",
"_line_number",
"=",
"next_line",
"(",
"self",
".",
"_communication",
".",
"last_requested_line_number",
",",
"self",
".",
"_file",
".",
"read",
"(",
"1",
")",
"[",
"0",
"]",
")"
] | 36.4 | 0.010753 |
def log_the_survey_settings(
log,
pathToYamlFile):
"""
*Create a MD log of the survey settings*
**Key Arguments:**
- ``log`` -- logger
- ``pathToYamlFile`` -- yaml results file
**Return:**
- None
"""
################ > IMPORTS ################
## STA... | [
"def",
"log_the_survey_settings",
"(",
"log",
",",
"pathToYamlFile",
")",
":",
"################ > IMPORTS ################",
"## STANDARD LIB ##",
"## THIRD PARTY ##",
"import",
"yaml",
"## LOCAL APPLICATION ##",
"from",
"datetime",
"import",
"datetime",
",",
"date",
",",
... | 42.777108 | 0.003441 |
def connection_exists(self, from_obj, to_obj):
"""
Returns ``True`` if a connection between the given objects exists,
else ``False``.
"""
self._validate_ctypes(from_obj, to_obj)
return self.connections.filter(from_pk=from_obj.pk, to_pk=to_obj.pk).exists() | [
"def",
"connection_exists",
"(",
"self",
",",
"from_obj",
",",
"to_obj",
")",
":",
"self",
".",
"_validate_ctypes",
"(",
"from_obj",
",",
"to_obj",
")",
"return",
"self",
".",
"connections",
".",
"filter",
"(",
"from_pk",
"=",
"from_obj",
".",
"pk",
",",
... | 42.428571 | 0.009901 |
def setTerms( self, terms ):
"""
Sets a simple rule list by accepting a list of strings for terms. \
This is a convenience method for the setRules method.
:param rules | [<str> term, ..]
"""
return self.setRules([XQueryRule(term = term) for term in terms]) | [
"def",
"setTerms",
"(",
"self",
",",
"terms",
")",
":",
"return",
"self",
".",
"setRules",
"(",
"[",
"XQueryRule",
"(",
"term",
"=",
"term",
")",
"for",
"term",
"in",
"terms",
"]",
")"
] | 39 | 0.021944 |
def response_hook(self, r, **kwargs):
"""The actual hook handler."""
if r.status_code == 401:
# Handle server auth.
www_authenticate = r.headers.get('www-authenticate', '').lower()
auth_type = _auth_type_from_header(www_authenticate)
if auth_type is not N... | [
"def",
"response_hook",
"(",
"self",
",",
"r",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"r",
".",
"status_code",
"==",
"401",
":",
"# Handle server auth.",
"www_authenticate",
"=",
"r",
".",
"headers",
".",
"get",
"(",
"'www-authenticate'",
",",
"''",
")... | 35.322581 | 0.001778 |
def _str_extract_noexpand(arr, pat, flags=0):
"""
Find groups in each string in the Series using passed regular
expression. This function is called from
str_extract(expand=False), and can return Series, DataFrame, or
Index.
"""
from pandas import DataFrame, Index
regex = re.compile(pat... | [
"def",
"_str_extract_noexpand",
"(",
"arr",
",",
"pat",
",",
"flags",
"=",
"0",
")",
":",
"from",
"pandas",
"import",
"DataFrame",
",",
"Index",
"regex",
"=",
"re",
".",
"compile",
"(",
"pat",
",",
"flags",
"=",
"flags",
")",
"groups_or_na",
"=",
"_gro... | 35.16129 | 0.000893 |
def summary(self):
"""
A succinct summary of the argument specifier. Unlike the repr,
a summary does not have to be complete but must supply the
most relevant information about the object to the user.
"""
print("Items: %s" % len(self))
varying_keys = ', '.join('%r... | [
"def",
"summary",
"(",
"self",
")",
":",
"print",
"(",
"\"Items: %s\"",
"%",
"len",
"(",
"self",
")",
")",
"varying_keys",
"=",
"', '",
".",
"join",
"(",
"'%r'",
"%",
"k",
"for",
"k",
"in",
"self",
".",
"varying_keys",
")",
"print",
"(",
"\"Varying K... | 44.230769 | 0.006814 |
def queue(self, blogname, **kwargs):
"""
Gets posts that are currently in the blog's queue
:param limit: an int, the number of posts you want returned
:param offset: an int, the post you want to start at, for pagination.
:param filter: the post format that you want returned: HTM... | [
"def",
"queue",
"(",
"self",
",",
"blogname",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"\"/v2/blog/{}/posts/queue\"",
".",
"format",
"(",
"blogname",
")",
"return",
"self",
".",
"send_api_request",
"(",
"\"get\"",
",",
"url",
",",
"kwargs",
",",
"[... | 44.666667 | 0.005484 |
def get_reports():
"""
Returns energy data from 1960 to 2014 across various factors.
"""
if False:
# If there was a Test version of this method, it would go here. But alas.
pass
else:
rows = _Constants._DATABASE.execute("SELECT data FROM energy".format(
hardw... | [
"def",
"get_reports",
"(",
")",
":",
"if",
"False",
":",
"# If there was a Test version of this method, it would go here. But alas.",
"pass",
"else",
":",
"rows",
"=",
"_Constants",
".",
"_DATABASE",
".",
"execute",
"(",
"\"SELECT data FROM energy\"",
".",
"format",
"("... | 32.333333 | 0.008016 |
def comments(self, update=True):
"""Fetch and return the comments for a single MoreComments object."""
if not self._comments:
if self.count == 0: # Handle 'continue this thread' type
return self._continue_comments(update)
# pylint: disable=W0212
child... | [
"def",
"comments",
"(",
"self",
",",
"update",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"_comments",
":",
"if",
"self",
".",
"count",
"==",
"0",
":",
"# Handle 'continue this thread' type",
"return",
"self",
".",
"_continue_comments",
"(",
"update",
... | 46 | 0.001521 |
def open_upload_stream(self, filename, chunk_size_bytes=None,
metadata=None):
"""Opens a Stream that the application can write the contents of the
file to.
The user must specify the filename, and can choose to add any
additional information in the metadata fie... | [
"def",
"open_upload_stream",
"(",
"self",
",",
"filename",
",",
"chunk_size_bytes",
"=",
"None",
",",
"metadata",
"=",
"None",
")",
":",
"validate_string",
"(",
"\"filename\"",
",",
"filename",
")",
"opts",
"=",
"{",
"\"filename\"",
":",
"filename",
",",
"\"... | 41.95122 | 0.001705 |
def ModuleHelp(self, module):
"""Describe the key flags of a module.
Args:
module: A module object or a module name (a string).
Returns:
string describing the key flags of a module.
"""
helplist = []
self.__RenderOurModuleKeyFlags(module, helplist)
return '\n'.join(helplist) | [
"def",
"ModuleHelp",
"(",
"self",
",",
"module",
")",
":",
"helplist",
"=",
"[",
"]",
"self",
".",
"__RenderOurModuleKeyFlags",
"(",
"module",
",",
"helplist",
")",
"return",
"'\\n'",
".",
"join",
"(",
"helplist",
")"
] | 25.5 | 0.003155 |
def perform_permissions_check(self, user, obj, perms):
""" Performs the permission check. """
return self.request.forum_permission_handler.can_edit_post(obj, user) | [
"def",
"perform_permissions_check",
"(",
"self",
",",
"user",
",",
"obj",
",",
"perms",
")",
":",
"return",
"self",
".",
"request",
".",
"forum_permission_handler",
".",
"can_edit_post",
"(",
"obj",
",",
"user",
")"
] | 59 | 0.011173 |
def get_poll_option_formset_kwargs(self):
""" Returns the keyword arguments for instantiating the poll option formset. """
kwargs = {
'prefix': 'poll',
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.request.POST,
... | [
"def",
"get_poll_option_formset_kwargs",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"'prefix'",
":",
"'poll'",
",",
"}",
"if",
"self",
".",
"request",
".",
"method",
"in",
"(",
"'POST'",
",",
"'PUT'",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'data... | 33.666667 | 0.006421 |
def cookie_attr_value_check(attr_name, attr_value):
""" Check cookie attribute value for validity. Return True if value is valid
:param attr_name: attribute name to check
:param attr_value: attribute value to check
:return: bool
"""
attr_value.encode('us-ascii')
return WHTTPCookie.cookie_attr_value_compl... | [
"def",
"cookie_attr_value_check",
"(",
"attr_name",
",",
"attr_value",
")",
":",
"attr_value",
".",
"encode",
"(",
"'us-ascii'",
")",
"return",
"WHTTPCookie",
".",
"cookie_attr_value_compliance",
"[",
"attr_name",
"]",
".",
"match",
"(",
"attr_value",
")",
"is",
... | 39.777778 | 0.027322 |
def __add_min_max_value(
parser,
basename,
default_min,
default_max,
initial,
help_template):
"""
Generates parser entries for options
with a min, max, and default value.
Args:
parser: the parser to use.
basename: the base option name. Gen... | [
"def",
"__add_min_max_value",
"(",
"parser",
",",
"basename",
",",
"default_min",
",",
"default_max",
",",
"initial",
",",
"help_template",
")",
":",
"help_template",
"=",
"Template",
"(",
"help_template",
")",
"parser",
".",
"add",
"(",
"'--{0}-min'",
".",
"f... | 29.159091 | 0.000754 |
def _AssertIsLocal(path):
'''
Checks if a given path is local, raise an exception if not.
This is used in filesystem functions that do not support remote operations yet.
:param unicode path:
:raises NotImplementedForRemotePathError:
If the given path is not local
'''
from six.move... | [
"def",
"_AssertIsLocal",
"(",
"path",
")",
":",
"from",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
"import",
"urlparse",
"if",
"not",
"_UrlIsLocal",
"(",
"urlparse",
"(",
"path",
")",
")",
":",
"from",
".",
"_exceptions",
"import",
"NotImplementedFo... | 32.6 | 0.003976 |
def sonify(annotation, sr=22050, duration=None, **kwargs):
'''Sonify a jams annotation through mir_eval
Parameters
----------
annotation : jams.Annotation
The annotation to sonify
sr = : positive number
The sampling rate of the output waveform
duration : float (optional)
... | [
"def",
"sonify",
"(",
"annotation",
",",
"sr",
"=",
"22050",
",",
"duration",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"length",
"=",
"None",
"if",
"duration",
"is",
"None",
":",
"duration",
"=",
"annotation",
".",
"duration",
"if",
"duration",
... | 29.320755 | 0.000623 |
def getPosNew(data):
"""
get Fixed position
"""
pos = data.geno['col_header']['pos'][:]
chrom= data.geno['col_header']['chrom'][:]
n_chroms = chrom.max()
pos_new = []
for chrom_i in range(1,n_chroms+1):
I = chrom==chrom_i
_pos = pos[I]
for i in range(1,_pos.shape[... | [
"def",
"getPosNew",
"(",
"data",
")",
":",
"pos",
"=",
"data",
".",
"geno",
"[",
"'col_header'",
"]",
"[",
"'pos'",
"]",
"[",
":",
"]",
"chrom",
"=",
"data",
".",
"geno",
"[",
"'col_header'",
"]",
"[",
"'chrom'",
"]",
"[",
":",
"]",
"n_chroms",
"... | 28 | 0.01626 |
def run(self):
"""Start the collector worker thread.
If running in standalone mode, the current thread will wait
until the collector thread ends.
"""
self.collector.start()
if self.standalone:
self.collector.join() | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"collector",
".",
"start",
"(",
")",
"if",
"self",
".",
"standalone",
":",
"self",
".",
"collector",
".",
"join",
"(",
")"
] | 29.666667 | 0.007273 |
def merge(profile, branch, merge_into):
"""Merge a branch into another branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
... | [
"def",
"merge",
"(",
"profile",
",",
"branch",
",",
"merge_into",
")",
":",
"data",
"=",
"merges",
".",
"merge",
"(",
"profile",
",",
"branch",
",",
"merge_into",
")",
"return",
"data"
] | 25.818182 | 0.001698 |
def handle(self,
t_input: inference.TranslatorInput,
t_output: inference.TranslatorOutput,
t_walltime: float = 0.):
"""
:param t_input: Translator input.
:param t_output: Translator output.
:param t_walltime: Total walltime for translation.
... | [
"def",
"handle",
"(",
"self",
",",
"t_input",
":",
"inference",
".",
"TranslatorInput",
",",
"t_output",
":",
"inference",
".",
"TranslatorOutput",
",",
"t_walltime",
":",
"float",
"=",
"0.",
")",
":",
"self",
".",
"stream",
".",
"write",
"(",
"\"%s\\n\"",... | 36.727273 | 0.012077 |
def _expand_libs_in_apps(specs):
"""
Expands specs.apps.depends.libs to include any indirectly required libs
"""
for app_name, app_spec in specs['apps'].iteritems():
if 'depends' in app_spec and 'libs' in app_spec['depends']:
app_spec['depends']['libs'] = _get_dependent('libs', app_n... | [
"def",
"_expand_libs_in_apps",
"(",
"specs",
")",
":",
"for",
"app_name",
",",
"app_spec",
"in",
"specs",
"[",
"'apps'",
"]",
".",
"iteritems",
"(",
")",
":",
"if",
"'depends'",
"in",
"app_spec",
"and",
"'libs'",
"in",
"app_spec",
"[",
"'depends'",
"]",
... | 47.571429 | 0.0059 |
def set_disk_timeout(timeout, power='ac', scheme=None):
'''
Set the disk timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the disk will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. V... | [
"def",
"set_disk_timeout",
"(",
"timeout",
",",
"power",
"=",
"'ac'",
",",
"scheme",
"=",
"None",
")",
":",
"return",
"_set_powercfg_value",
"(",
"scheme",
"=",
"scheme",
",",
"sub_group",
"=",
"'SUB_DISK'",
",",
"setting_guid",
"=",
"'DISKIDLE'",
",",
"powe... | 28.4 | 0.000851 |
def find_feasible_flow(self):
'''
API:
find_feasible_flow(self)
Description:
Solves feasible flow problem, stores solution in 'flow' attribute
or arcs. This method is used to get an initial feasible flow for
simplex and cycle canceling algorithms. ... | [
"def",
"find_feasible_flow",
"(",
"self",
")",
":",
"# establish a feasible flow in the network, to do this add nodes s and",
"# t and solve a max flow problem.",
"nl",
"=",
"self",
".",
"get_node_list",
"(",
")",
"for",
"i",
"in",
"nl",
":",
"b_i",
"=",
"self",
".",
... | 41.404255 | 0.001004 |
def month_interval(year, month, return_str=False):
"""
Usage Example::
>>> timewrapper.day_interval(2014, 12)
(datetime(2014, 12, 1, 0, 0, 0), datetime(2014, 12, 31, 23, 59, 59))
"""
if month == 12:
start, end = datetime(year, month, ... | [
"def",
"month_interval",
"(",
"year",
",",
"month",
",",
"return_str",
"=",
"False",
")",
":",
"if",
"month",
"==",
"12",
":",
"start",
",",
"end",
"=",
"datetime",
"(",
"year",
",",
"month",
",",
"1",
")",
",",
"datetime",
"(",
"year",
"+",
"1",
... | 34.823529 | 0.013158 |
def refresh(self):
"""
Fetches all current container names from the client, along with their id.
"""
if not self._client:
return
current_containers = self._client.containers(all=True)
self.clear()
for container in current_containers:
contai... | [
"def",
"refresh",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_client",
":",
"return",
"current_containers",
"=",
"self",
".",
"_client",
".",
"containers",
"(",
"all",
"=",
"True",
")",
"self",
".",
"clear",
"(",
")",
"for",
"container",
"in",
... | 36.714286 | 0.005693 |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._id_ is not None:
return False
if self._monetary_account_id is not None:
return False
if self._card_id is not None:
return False
if self._amount_local is not None:
... | [
"def",
"is_all_field_none",
"(",
"self",
")",
":",
"if",
"self",
".",
"_id_",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_monetary_account_id",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_card_id",
"is",
"not",... | 22.791667 | 0.000876 |
def maketrans(fromstr, tostr):
"""maketrans(frm, to) -> string
Return a translation table (a string of 256 bytes long)
suitable for use in string.translate. The strings frm and to
must be of the same length.
"""
if len(fromstr) != len(tostr):
raise ValueError, "maketrans arguments mus... | [
"def",
"maketrans",
"(",
"fromstr",
",",
"tostr",
")",
":",
"if",
"len",
"(",
"fromstr",
")",
"!=",
"len",
"(",
"tostr",
")",
":",
"raise",
"ValueError",
",",
"\"maketrans arguments must have same length\"",
"global",
"_idmapL",
"if",
"not",
"_idmapL",
":",
... | 29.555556 | 0.003643 |
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position] | [
"def",
"peek",
"(",
"self",
")",
":",
"if",
"self",
".",
"position",
">=",
"len",
"(",
"self",
".",
"tokens",
")",
":",
"return",
"None",
"return",
"self",
".",
"tokens",
"[",
"self",
".",
"position",
"]"
] | 23.8 | 0.008097 |
def _create_header(self):
"""
Function to create the GroupHeader (GrpHdr) in the
CstmrCdtTrfInitn Node
"""
# Retrieve the node to which we will append the group header.
CstmrCdtTrfInitn_node = self._xml.find('CstmrCdtTrfInitn')
# Create the header nodes.
... | [
"def",
"_create_header",
"(",
"self",
")",
":",
"# Retrieve the node to which we will append the group header.",
"CstmrCdtTrfInitn_node",
"=",
"self",
".",
"_xml",
".",
"find",
"(",
"'CstmrCdtTrfInitn'",
")",
"# Create the header nodes.",
"GrpHdr_node",
"=",
"ET",
".",
"E... | 35.9375 | 0.00254 |
def write_csv(self, path=None):
"""Write CSV file. Sorts the sections before calling the superclass write_csv"""
# Sort the Sections
self.sort_sections(['Root', 'Contacts', 'Documentation', 'References', 'Resources', 'Citations', 'Schema'])
# Sort Terms in the root section
# ... | [
"def",
"write_csv",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"# Sort the Sections",
"self",
".",
"sort_sections",
"(",
"[",
"'Root'",
",",
"'Contacts'",
",",
"'Documentation'",
",",
"'References'",
",",
"'Resources'",
",",
"'Citations'",
",",
"'Schema'... | 29.545455 | 0.005961 |
def _identify_heterogeneity_blocks_hmm(in_file, params, work_dir, somatic_info):
"""Use a HMM to identify blocks of heterogeneity to use for calculating allele frequencies.
The goal is to subset the genome to a more reasonable section that contains potential
loss of heterogeneity or other allele frequency ... | [
"def",
"_identify_heterogeneity_blocks_hmm",
"(",
"in_file",
",",
"params",
",",
"work_dir",
",",
"somatic_info",
")",
":",
"def",
"_segment_by_hmm",
"(",
"chrom",
",",
"freqs",
",",
"coords",
")",
":",
"cur_coords",
"=",
"[",
"]",
"for",
"j",
",",
"state",
... | 51.863636 | 0.005164 |
def update_record(self, dns_type, name, content, **kwargs):
"""
Update dns record
:param dns_type:
:param name:
:param content:
:param kwargs:
:return:
"""
record = self.get_record(dns_type, name)
data = {
'type': dns_type,
... | [
"def",
"update_record",
"(",
"self",
",",
"dns_type",
",",
"name",
",",
"content",
",",
"*",
"*",
"kwargs",
")",
":",
"record",
"=",
"self",
".",
"get_record",
"(",
"dns_type",
",",
"name",
")",
"data",
"=",
"{",
"'type'",
":",
"dns_type",
",",
"'nam... | 29.928571 | 0.003468 |
def _map_arguments(self, args):
"""Map from the top-level arguments to the arguments provided to
the indiviudal links """
data = args.get('data')
comp = args.get('comp')
library = args.get('library')
dry_run = args.get('dry_run', False)
self._set_link('sum-rings'... | [
"def",
"_map_arguments",
"(",
"self",
",",
"args",
")",
":",
"data",
"=",
"args",
".",
"get",
"(",
"'data'",
")",
"comp",
"=",
"args",
".",
"get",
"(",
"'comp'",
")",
"library",
"=",
"args",
".",
"get",
"(",
"'library'",
")",
"dry_run",
"=",
"args"... | 37.086957 | 0.002286 |
def print_attr_values( thing, all=False, heading=None, file=None ):
'''
Print the attributes of thing which have non-empty values,
as a vertical list of "name : value". When all=True, print
all attributes even those with empty values.
'''
if heading :
if isinstance( heading, int ) :
... | [
"def",
"print_attr_values",
"(",
"thing",
",",
"all",
"=",
"False",
",",
"heading",
"=",
"None",
",",
"file",
"=",
"None",
")",
":",
"if",
"heading",
":",
"if",
"isinstance",
"(",
"heading",
",",
"int",
")",
":",
"# request for default heading",
"heading",... | 38.428571 | 0.025393 |
def wait_while_reachable(self, servers, timeout=60):
"""wait while all servers be reachable
Args:
servers - list of servers
"""
t_start = time.time()
while True:
try:
for server in servers:
# TODO: use state code to chec... | [
"def",
"wait_while_reachable",
"(",
"self",
",",
"servers",
",",
"timeout",
"=",
"60",
")",
":",
"t_start",
"=",
"time",
".",
"time",
"(",
")",
"while",
"True",
":",
"try",
":",
"for",
"server",
"in",
"servers",
":",
"# TODO: use state code to check if serve... | 48.2 | 0.005086 |
def add_arguments(parser, default_level=logging.INFO):
"""
Add arguments to an ArgumentParser or OptionParser for purposes of
grabbing a logging level.
"""
adder = (
getattr(parser, 'add_argument', None)
or getattr(parser, 'add_option')
)
adder(
'-l', '--log-level', default=default_level, type=lo... | [
"def",
"add_arguments",
"(",
"parser",
",",
"default_level",
"=",
"logging",
".",
"INFO",
")",
":",
"adder",
"=",
"(",
"getattr",
"(",
"parser",
",",
"'add_argument'",
",",
"None",
")",
"or",
"getattr",
"(",
"parser",
",",
"'add_option'",
")",
")",
"adde... | 31 | 0.031332 |
def _conn_ready(self, conn):
"""
There is a nice state diagram at the top of httplib.py. It
indicates that once the response headers have been read (which
_mexe does before adding the connection to the pool), a
response is attached to the connection, and it stays there
u... | [
"def",
"_conn_ready",
"(",
"self",
",",
"conn",
")",
":",
"if",
"ON_APP_ENGINE",
":",
"# Google App Engine implementation of HTTPConnection doesn't contain",
"# _HTTPConnection__response attribute. Moreover, it's not possible",
"# to determine if given connection is ready. Reusing connecti... | 51.318182 | 0.002609 |
def from_(self, selectable):
"""
Adds a table to the query. This function can only be called once and will raise an AttributeError if called a
second time.
:param selectable:
Type: ``Table``, ``Query``, or ``str``
When a ``str`` is passed, a table with the name... | [
"def",
"from_",
"(",
"self",
",",
"selectable",
")",
":",
"self",
".",
"_from",
".",
"append",
"(",
"Table",
"(",
"selectable",
")",
"if",
"isinstance",
"(",
"selectable",
",",
"str",
")",
"else",
"selectable",
")",
"if",
"isinstance",
"(",
"selectable",... | 38.24 | 0.006122 |
def start_threads(self, n_threads):
"""
Terminate existing threads and create a
new set if the thread number doesn't match
the desired number.
Required:
n_threads: (int) number of threads to spawn
Returns: self
"""
if n_threads == len(self._threads):
return self
... | [
"def",
"start_threads",
"(",
"self",
",",
"n_threads",
")",
":",
"if",
"n_threads",
"==",
"len",
"(",
"self",
".",
"_threads",
")",
":",
"return",
"self",
"# Terminate all previous tasks with the existing",
"# event object, then create a new one for the next",
"# generati... | 25.4 | 0.010834 |
def _dist_version_url(self, dist):
"""
Get version and homepage for a pkg_resources.Distribution
:param dist: the pkg_resources.Distribution to get information for
:returns: 2-tuple of (version, homepage URL)
:rtype: tuple
"""
ver = str(dist.version)
url ... | [
"def",
"_dist_version_url",
"(",
"self",
",",
"dist",
")",
":",
"ver",
"=",
"str",
"(",
"dist",
".",
"version",
")",
"url",
"=",
"None",
"for",
"line",
"in",
"dist",
".",
"get_metadata_lines",
"(",
"dist",
".",
"PKG_INFO",
")",
":",
"line",
"=",
"lin... | 32.722222 | 0.0033 |
def main():
"""Executed on run"""
args = parse_args()
if args.version:
from .__init__ import __version__, __release_date__
print('elkme %s (release date %s)' % (__version__, __release_date__))
print('(c) 2015-2017 46elks AB <hello@46elks.com>')
print(small_elk)
exit(... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"if",
"args",
".",
"version",
":",
"from",
".",
"__init__",
"import",
"__version__",
",",
"__release_date__",
"print",
"(",
"'elkme %s (release date %s)'",
"%",
"(",
"__version__",
",",
"__re... | 28.434783 | 0.006652 |
def movie(self, cycles, plotstyle='',movname='',fps=12,**kwargs):
from matplotlib import animation
'''
Make an interactive movie in the matplotlib window for a number of
different plot types:
Plot types
----------
'iso_abund' : abundance distr... | [
"def",
"movie",
"(",
"self",
",",
"cycles",
",",
"plotstyle",
"=",
"''",
",",
"movname",
"=",
"''",
",",
"fps",
"=",
"12",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"matplotlib",
"import",
"animation",
"modelself",
"=",
"self",
"supported_styles",
"="... | 45.985577 | 0.013508 |
def schedule(identifier, **kwargs):
'''Schedule a harvest job to run periodically'''
source = actions.schedule(identifier, **kwargs)
msg = 'Scheduled {source.name} with the following crontab: {cron}'
log.info(msg.format(source=source, cron=source.periodic_task.crontab)) | [
"def",
"schedule",
"(",
"identifier",
",",
"*",
"*",
"kwargs",
")",
":",
"source",
"=",
"actions",
".",
"schedule",
"(",
"identifier",
",",
"*",
"*",
"kwargs",
")",
"msg",
"=",
"'Scheduled {source.name} with the following crontab: {cron}'",
"log",
".",
"info",
... | 56.4 | 0.003497 |
def decode_lazy(rlp, sedes=None, **sedes_kwargs):
"""Decode an RLP encoded object in a lazy fashion.
If the encoded object is a bytestring, this function acts similar to
:func:`rlp.decode`. If it is a list however, a :class:`LazyList` is
returned instead. This object will decode the string lazily, avoi... | [
"def",
"decode_lazy",
"(",
"rlp",
",",
"sedes",
"=",
"None",
",",
"*",
"*",
"sedes_kwargs",
")",
":",
"item",
",",
"end",
"=",
"consume_item_lazy",
"(",
"rlp",
",",
"0",
")",
"if",
"end",
"!=",
"len",
"(",
"rlp",
")",
":",
"raise",
"DecodingError",
... | 46.5 | 0.001859 |
def _build_tree_structure(cls):
"""
Build an in-memory representation of the item tree, trying to keep
database accesses down to a minimum. The returned dictionary looks like
this (as json dump):
{"6": [7, 8, 10]
"7": [12],
"8": [],
...
}
"""
all_node... | [
"def",
"_build_tree_structure",
"(",
"cls",
")",
":",
"all_nodes",
"=",
"{",
"}",
"for",
"p_id",
",",
"parent_id",
"in",
"cls",
".",
"objects",
".",
"order_by",
"(",
"cls",
".",
"_mptt_meta",
".",
"tree_id_attr",
",",
"cls",
".",
"_mptt_meta",
".",
"left... | 30.222222 | 0.003563 |
def GET_subdomain_ops(self, path_info, txid):
"""
Get all subdomain operations processed in a given transaction.
Returns the list of subdomains on success (can be empty)
Returns 502 on failure to get subdomains
"""
blockstackd_url = get_blockstackd_url()
subdomain... | [
"def",
"GET_subdomain_ops",
"(",
"self",
",",
"path_info",
",",
"txid",
")",
":",
"blockstackd_url",
"=",
"get_blockstackd_url",
"(",
")",
"subdomain_ops",
"=",
"None",
"try",
":",
"subdomain_ops",
"=",
"blockstackd_client",
".",
"get_subdomain_ops_at_txid",
"(",
... | 50 | 0.006543 |
def _bookToDF(b):
'''internal'''
quote = b.get('quote', [])
asks = b.get('asks', [])
bids = b.get('bids', [])
trades = b.get('trades', [])
df1 = pd.io.json.json_normalize(quote)
df1['type'] = 'quote'
df2 = pd.io.json.json_normalize(asks)
df2['symbol'] = quote['symbol']
df2['typ... | [
"def",
"_bookToDF",
"(",
"b",
")",
":",
"quote",
"=",
"b",
".",
"get",
"(",
"'quote'",
",",
"[",
"]",
")",
"asks",
"=",
"b",
".",
"get",
"(",
"'asks'",
",",
"[",
"]",
")",
"bids",
"=",
"b",
".",
"get",
"(",
"'bids'",
",",
"[",
"]",
")",
"... | 24.16 | 0.001592 |
def get_precision(self):
"""\
:returns: the ratio part of the dominant label for each unit.
:rtype: 2D :class:`numpy.ndarray`
"""
assert self.classifier is not None, 'not calibrated'
arr = np.zeros((self._som.nrows, self._som.ncols))
for ij, (lbl, p) in self.class... | [
"def",
"get_precision",
"(",
"self",
")",
":",
"assert",
"self",
".",
"classifier",
"is",
"not",
"None",
",",
"'not calibrated'",
"arr",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"_som",
".",
"nrows",
",",
"self",
".",
"_som",
".",
"ncols",
")"... | 36.8 | 0.005305 |
def clean(self):
"""
Clean fields that depend on each other.
In this case, the form can be used to link single user or bulk link multiple users. These are mutually
exclusive modes, so this method checks that only one field is passed.
"""
cleaned_data = super(ManageLearne... | [
"def",
"clean",
"(",
"self",
")",
":",
"cleaned_data",
"=",
"super",
"(",
"ManageLearnersForm",
",",
"self",
")",
".",
"clean",
"(",
")",
"# Here we take values from `data` (and not `cleaned_data`) as we need raw values - field clean methods",
"# might \"invalidate\" the value ... | 41.685714 | 0.004019 |
def setbridgeprio(self, prio):
""" Set bridge priority value. """
_runshell([brctlexe, 'setbridgeprio', self.name, str(prio)],
"Could not set bridge priority in %s." % self.name) | [
"def",
"setbridgeprio",
"(",
"self",
",",
"prio",
")",
":",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'setbridgeprio'",
",",
"self",
".",
"name",
",",
"str",
"(",
"prio",
")",
"]",
",",
"\"Could not set bridge priority in %s.\"",
"%",
"self",
".",
"name",
"... | 50.75 | 0.014563 |
def get_long_description():
"""
Strip the content index from the long description.
"""
import codecs
with codecs.open('README.rst', encoding='UTF-8') as f:
readme = [line for line in f if not line.startswith('.. contents::')]
return ''.join(readme) | [
"def",
"get_long_description",
"(",
")",
":",
"import",
"codecs",
"with",
"codecs",
".",
"open",
"(",
"'README.rst'",
",",
"encoding",
"=",
"'UTF-8'",
")",
"as",
"f",
":",
"readme",
"=",
"[",
"line",
"for",
"line",
"in",
"f",
"if",
"not",
"line",
".",
... | 34.75 | 0.007018 |
def get_query_tables(query):
"""
:type query str
:rtype: list[str]
"""
tables = []
last_keyword = None
last_token = None
table_syntax_keywords = [
# SELECT queries
'FROM', 'WHERE', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'ON',
# INSERT queries
'I... | [
"def",
"get_query_tables",
"(",
"query",
")",
":",
"tables",
"=",
"[",
"]",
"last_keyword",
"=",
"None",
"last_token",
"=",
"None",
"table_syntax_keywords",
"=",
"[",
"# SELECT queries",
"'FROM'",
",",
"'WHERE'",
",",
"'JOIN'",
",",
"'INNER JOIN'",
",",
"'LEFT... | 41.904762 | 0.002591 |
def CurrentNode(self):
"""Hacking interface allowing to get the xmlNodePtr
correponding to the current node being accessed by the
xmlTextReader. This is dangerous because the underlying
node may be destroyed on the next Reads. """
ret = libxml2mod.xmlTextReaderCurrentNode(... | [
"def",
"CurrentNode",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlTextReaderCurrentNode",
"(",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlTextReaderCurrentNode() failed'",
")",
"__tmp",
"=",
"xmlNode",... | 50.111111 | 0.008715 |
def _mouseDown(x, y, button):
"""Send the mouse down event to Windows by calling the mouse_event() win32
function.
Args:
x (int): The x position of the mouse event.
y (int): The y position of the mouse event.
button (str): The mouse button, either 'left', 'middle', or 'right'
Returns... | [
"def",
"_mouseDown",
"(",
"x",
",",
"y",
",",
"button",
")",
":",
"if",
"button",
"==",
"'left'",
":",
"try",
":",
"_sendMouseEvent",
"(",
"MOUSEEVENTF_LEFTDOWN",
",",
"x",
",",
"y",
")",
"except",
"(",
"PermissionError",
",",
"OSError",
")",
":",
"# T... | 41.551724 | 0.005677 |
def N(u,i,p,knots):
"""Compute Spline Basis
Evaluates the spline basis of order p defined by knots
at knot i and point u.
"""
if p == 0:
if knots[i] < u and u <=knots[i+1]:
return 1.0
else:
return 0.0
else:
try:
k = (( float((u-kn... | [
"def",
"N",
"(",
"u",
",",
"i",
",",
"p",
",",
"knots",
")",
":",
"if",
"p",
"==",
"0",
":",
"if",
"knots",
"[",
"i",
"]",
"<",
"u",
"and",
"u",
"<=",
"knots",
"[",
"i",
"+",
"1",
"]",
":",
"return",
"1.0",
"else",
":",
"return",
"0.0",
... | 28.434783 | 0.032544 |
def commit(self, force=False):
"""Commit data to couchdb
Compared to threshold (unless forced) then sends data to couch
"""
self.log.debug('Bulk commit requested')
size = sys.getsizeof(self.docs)
self.log.debug('Size of docs in KB: %d', size)
if size > self.comm... | [
"def",
"commit",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Bulk commit requested'",
")",
"size",
"=",
"sys",
".",
"getsizeof",
"(",
"self",
".",
"docs",
")",
"self",
".",
"log",
".",
"debug",
"(",
"... | 35.461538 | 0.004228 |
def locate(self, point):
r"""Find a point on the current curve.
Solves for :math:`s` in :math:`B(s) = p`.
This method acts as a (partial) inverse to :meth:`evaluate`.
.. note::
A unique solution is only guaranteed if the current curve has no
self-intersections. ... | [
"def",
"locate",
"(",
"self",
",",
"point",
")",
":",
"if",
"point",
".",
"shape",
"!=",
"(",
"self",
".",
"_dimension",
",",
"1",
")",
":",
"point_dimensions",
"=",
"\" x \"",
".",
"join",
"(",
"str",
"(",
"dimension",
")",
"for",
"dimension",
"in",... | 31.902778 | 0.000845 |
def getPoly(rCut, nMax):
"""Used to calculate discrete vectors for the polynomial basis functions.
Args:
rCut(float): Radial cutoff
nMax(int): Number of polynomial radial functions
"""
rCutVeryHard = rCut+5.0
rx = 0.5*rCutVeryHard*(x + 1)
basisFunctions = []
for i in range(... | [
"def",
"getPoly",
"(",
"rCut",
",",
"nMax",
")",
":",
"rCutVeryHard",
"=",
"rCut",
"+",
"5.0",
"rx",
"=",
"0.5",
"*",
"rCutVeryHard",
"*",
"(",
"x",
"+",
"1",
")",
"basisFunctions",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"nMax",... | 36.55 | 0.001999 |
def high_cli(repo_name, login, with_blog, as_list, role):
"""Extract mails from stargazers, collaborators and people involved with issues of given
repository.
"""
passw = getpass.getpass()
github = gh_login(login, passw)
repo = github.repository(login, repo_name)
role = [ROLES[k] for k in ro... | [
"def",
"high_cli",
"(",
"repo_name",
",",
"login",
",",
"with_blog",
",",
"as_list",
",",
"role",
")",
":",
"passw",
"=",
"getpass",
".",
"getpass",
"(",
")",
"github",
"=",
"gh_login",
"(",
"login",
",",
"passw",
")",
"repo",
"=",
"github",
".",
"re... | 31.526316 | 0.003241 |
def from_parameters3(cls, lengths, angles):
"""Construct a 3D unit cell with the given parameters
The a vector is always parallel with the x-axis and they point in the
same direction. The b vector is always in the xy plane and points
towards the positive y-direction. The c vect... | [
"def",
"from_parameters3",
"(",
"cls",
",",
"lengths",
",",
"angles",
")",
":",
"for",
"length",
"in",
"lengths",
":",
"if",
"length",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"The length parameters must be strictly positive.\"",
")",
"for",
"angle",
"in",
... | 41.880952 | 0.003333 |
def google(self):
"""Gets the tile in the Google format, converted from TMS"""
tms_x, tms_y = self.tms
return tms_x, (2 ** self.zoom - 1) - tms_y | [
"def",
"google",
"(",
"self",
")",
":",
"tms_x",
",",
"tms_y",
"=",
"self",
".",
"tms",
"return",
"tms_x",
",",
"(",
"2",
"**",
"self",
".",
"zoom",
"-",
"1",
")",
"-",
"tms_y"
] | 41.5 | 0.011834 |
def find_l50(contig_lengths_dict, genome_length_dict):
"""
Calculate the L50 for each strain. L50 is defined as the number of contigs required to achieve the N50
:param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths
:param genome_length_dict: dictionary of stra... | [
"def",
"find_l50",
"(",
"contig_lengths_dict",
",",
"genome_length_dict",
")",
":",
"# Initialise the dictionary",
"l50_dict",
"=",
"dict",
"(",
")",
"for",
"file_name",
",",
"contig_lengths",
"in",
"contig_lengths_dict",
".",
"items",
"(",
")",
":",
"currentlength"... | 52.045455 | 0.005146 |
def check_response_code(resp):
"""
check if query quota has been surpassed or other errors occured
:param resp: json response
:return:
"""
if resp["status"] == "OK" or resp["status"] == "ZERO_RESULTS":
return
if resp["status"] == "REQUEST_DENIED":
raise Exception("Google Pla... | [
"def",
"check_response_code",
"(",
"resp",
")",
":",
"if",
"resp",
"[",
"\"status\"",
"]",
"==",
"\"OK\"",
"or",
"resp",
"[",
"\"status\"",
"]",
"==",
"\"ZERO_RESULTS\"",
":",
"return",
"if",
"resp",
"[",
"\"status\"",
"]",
"==",
"\"REQUEST_DENIED\"",
":",
... | 43.192308 | 0.004355 |
def create_database(self, instance, body, project_id=None):
"""
Creates a new database inside a Cloud SQL instance.
:param instance: Database instance ID. This does not include the project ID.
:type instance: str
:param body: The request body, as described in
https:/... | [
"def",
"create_database",
"(",
"self",
",",
"instance",
",",
"body",
",",
"project_id",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"get_conn",
"(",
")",
".",
"databases",
"(",
")",
".",
"insert",
"(",
"project",
"=",
"project_id",
",",
"insta... | 46.318182 | 0.004808 |
def spdhg_generic(x, f, g, A, tau, sigma, niter, **kwargs):
r"""Computes a saddle point with a stochastic PDHG.
This means, a solution (x*, y*), y* = (y*_1, ..., y*_n) such that
(x*, y*) in arg min_x max_y sum_i=1^n <y_i, A_i> - f*[i](y_i) + g(x)
where g : X -> IR_infty and f[i] : Y[i] -> IR_infty ar... | [
"def",
"spdhg_generic",
"(",
"x",
",",
"f",
",",
"g",
",",
"A",
",",
"tau",
",",
"sigma",
",",
"niter",
",",
"*",
"*",
"kwargs",
")",
":",
"# Callback object",
"callback",
"=",
"kwargs",
".",
"pop",
"(",
"'callback'",
",",
"None",
")",
"if",
"callb... | 32.88024 | 0.000177 |
def get_abstract(doi):
"""Get the abstract text of an article from Elsevier given a doi."""
xml_string = download_article(doi)
if xml_string is None:
return None
assert isinstance(xml_string, str)
xml_tree = ET.XML(xml_string.encode('utf-8'), parser=UTB())
if xml_tree is None:
re... | [
"def",
"get_abstract",
"(",
"doi",
")",
":",
"xml_string",
"=",
"download_article",
"(",
"doi",
")",
"if",
"xml_string",
"is",
"None",
":",
"return",
"None",
"assert",
"isinstance",
"(",
"xml_string",
",",
"str",
")",
"xml_tree",
"=",
"ET",
".",
"XML",
"... | 37.538462 | 0.002 |
def generateSortedChildListString(self, stream, sectionTitle, lst):
'''
Helper method for :func:`~exhale.graph.ExhaleRoot.generateNamespaceChildrenString`.
Used to build up a continuous string with all of the children separated out into
titled sections.
This generates a new titl... | [
"def",
"generateSortedChildListString",
"(",
"self",
",",
"stream",
",",
"sectionTitle",
",",
"lst",
")",
":",
"if",
"lst",
":",
"lst",
".",
"sort",
"(",
")",
"stream",
".",
"write",
"(",
"textwrap",
".",
"dedent",
"(",
"'''\n\n {heading}\n ... | 36.102564 | 0.005533 |
def run(self, data, train_epochs=1000, test_epochs=1000, verbose=None,
idx=0, lr=0.01, **kwargs):
"""Run the CGNN on a given graph."""
verbose = SETTINGS.get_default(verbose=verbose)
optim = th.optim.Adam(self.parameters(), lr=lr)
self.score.zero_()
with trange(train_... | [
"def",
"run",
"(",
"self",
",",
"data",
",",
"train_epochs",
"=",
"1000",
",",
"test_epochs",
"=",
"1000",
",",
"verbose",
"=",
"None",
",",
"idx",
"=",
"0",
",",
"lr",
"=",
"0.01",
",",
"*",
"*",
"kwargs",
")",
":",
"verbose",
"=",
"SETTINGS",
"... | 43.684211 | 0.003538 |
def proj_list(args):
'''Retrieve the list of billing projects accessible to the caller/user, and
show the level of access granted for each (e.g. Owner, User, ...)'''
projects = fapi.list_billing_projects()
fapi._check_response_code(projects, 200)
projects = sorted(projects.json(), key=lambda d: d... | [
"def",
"proj_list",
"(",
"args",
")",
":",
"projects",
"=",
"fapi",
".",
"list_billing_projects",
"(",
")",
"fapi",
".",
"_check_response_code",
"(",
"projects",
",",
"200",
")",
"projects",
"=",
"sorted",
"(",
"projects",
".",
"json",
"(",
")",
",",
"ke... | 57.888889 | 0.003781 |
def run(self):
"""
Read lines while keep_reading is True. Calls process_dut for each received line.
:return: Nothing
"""
self.keep_reading = True
while self.keep_reading:
line = self._readline()
if line:
self.input_queue.appendleft... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"keep_reading",
"=",
"True",
"while",
"self",
".",
"keep_reading",
":",
"line",
"=",
"self",
".",
"_readline",
"(",
")",
"if",
"line",
":",
"self",
".",
"input_queue",
".",
"appendleft",
"(",
"line",
... | 29.416667 | 0.008242 |
def object_patch_add_link(self, root, name, ref, create=False, **kwargs):
"""Creates a new merkledag object based on an existing one.
The new object will have a link to the provided object.
.. code-block:: python
>>> c.object_patch_add_link(
... 'QmR79zQQj2aDfnrNgc... | [
"def",
"object_patch_add_link",
"(",
"self",
",",
"root",
",",
"name",
",",
"ref",
",",
"create",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",",
"{",
"\"create\"",
":",
"create",
"}",
")",
"args",
... | 32.441176 | 0.001761 |
def Norm2(self):
"""
Returns the L_2 (Euclidean) norm of self.
"""
sum = self.x * self.x + self.y * self.y + self.z * self.z
return math.sqrt(float(sum)) | [
"def",
"Norm2",
"(",
"self",
")",
":",
"sum",
"=",
"self",
".",
"x",
"*",
"self",
".",
"x",
"+",
"self",
".",
"y",
"*",
"self",
".",
"y",
"+",
"self",
".",
"z",
"*",
"self",
".",
"z",
"return",
"math",
".",
"sqrt",
"(",
"float",
"(",
"sum",... | 28 | 0.00578 |
def _resolve_image(ret, image, client_timeout):
'''
Resolve the image ID and pull the image if necessary
'''
image_id = __salt__['docker.resolve_image_id'](image)
if image_id is False:
if not __opts__['test']:
# Image not pulled locally, so try pulling it
try:
... | [
"def",
"_resolve_image",
"(",
"ret",
",",
"image",
",",
"client_timeout",
")",
":",
"image_id",
"=",
"__salt__",
"[",
"'docker.resolve_image_id'",
"]",
"(",
"image",
")",
"if",
"image_id",
"is",
"False",
":",
"if",
"not",
"__opts__",
"[",
"'test'",
"]",
":... | 38.862069 | 0.000866 |
def register_forward_pre_hook(self, hook):
r"""Registers a forward pre-hook on the block.
The hook function is called immediately before :func:`forward`.
It should not modify the input or output.
Parameters
----------
hook : callable
The forward hook functio... | [
"def",
"register_forward_pre_hook",
"(",
"self",
",",
"hook",
")",
":",
"handle",
"=",
"HookHandle",
"(",
")",
"handle",
".",
"attach",
"(",
"self",
".",
"_forward_pre_hooks",
",",
"hook",
")",
"return",
"handle"
] | 29.888889 | 0.003604 |
def calc_and_store_post_estimation_results(results_dict,
estimator):
"""
Calculates and stores post-estimation results that require the use of the
systematic utility transformation functions or the various derivative
functions. Note that this function is only v... | [
"def",
"calc_and_store_post_estimation_results",
"(",
"results_dict",
",",
"estimator",
")",
":",
"# Store the final log-likelihood",
"final_log_likelihood",
"=",
"-",
"1",
"*",
"results_dict",
"[",
"\"fun\"",
"]",
"results_dict",
"[",
"\"final_log_likelihood\"",
"]",
"="... | 37.326733 | 0.000258 |
def insertFile(self, businput, qInserts=False):
"""
This method supports bulk insert of files
performing other operations such as setting Block and Dataset parentages,
setting mapping between OutputConfigModules and File(s) etc.
:param qInserts: True means that inserts will be q... | [
"def",
"insertFile",
"(",
"self",
",",
"businput",
",",
"qInserts",
"=",
"False",
")",
":",
"# We do not want to go be beyond 10 files at a time",
"# If user wants to insert over 10 files in one shot, we run into risks of locking the database",
"# tables for longer time, and in case of e... | 56.518939 | 0.010406 |
def get_resource(self, resource_id):
"""Gets the ``Resource`` specified by its ``Id``.
In plenary mode, the exact ``Id`` is found or a ``NotFound``
results. Otherwise, the returned ``Resource`` may have a
different ``Id`` than requested, such as the case where a
duplicate ``Id``... | [
"def",
"get_resource",
"(",
"self",
",",
"resource_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resource",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
"JSONClientValidated",
"(",
"'resource'",
",",
... | 51 | 0.002654 |
def configure_retrieve(self, ns, definition):
"""
Register a retrieve endpoint.
The definition's func should be a retrieve function, which must:
- accept kwargs for path data
- return an item or falsey
:param ns: the namespace
:param definition: the endpoint def... | [
"def",
"configure_retrieve",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"request_schema",
"=",
"definition",
".",
"request_schema",
"or",
"Schema",
"(",
")",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"instance_path",
",",
"Operation",
".",
"... | 37.96875 | 0.00321 |
def eye(n, d=None):
""" Creates an identity TT-matrix"""
c = _matrix.matrix()
c.tt = _vector.vector()
if d is None:
n0 = _np.asanyarray(n, dtype=_np.int32)
c.tt.d = n0.size
else:
n0 = _np.asanyarray([n] * d, dtype=_np.int32)
c.tt.d = d
c.n = n0.copy()
c.m = n0... | [
"def",
"eye",
"(",
"n",
",",
"d",
"=",
"None",
")",
":",
"c",
"=",
"_matrix",
".",
"matrix",
"(",
")",
"c",
".",
"tt",
"=",
"_vector",
".",
"vector",
"(",
")",
"if",
"d",
"is",
"None",
":",
"n0",
"=",
"_np",
".",
"asanyarray",
"(",
"n",
","... | 24.64 | 0.004688 |
def _get_edge_date(self, date_field, sort):
'''
This method is used to get start and end dates for the collection.
'''
return self._source.query(self._source_coll, {
'q':'*:*',
'rows':1,
'fq':'+{}:*'.format(date_field),
... | [
"def",
"_get_edge_date",
"(",
"self",
",",
"date_field",
",",
"sort",
")",
":",
"return",
"self",
".",
"_source",
".",
"query",
"(",
"self",
".",
"_source_coll",
",",
"{",
"'q'",
":",
"'*:*'",
",",
"'rows'",
":",
"1",
",",
"'fq'",
":",
"'+{}:*'",
"."... | 41.888889 | 0.015584 |
def device(self):
"""returns the device which owns the given stream"""
splitted_path = self.path.split("/")
return Device(self.db,
splitted_path[0] + "/" + splitted_path[1]) | [
"def",
"device",
"(",
"self",
")",
":",
"splitted_path",
"=",
"self",
".",
"path",
".",
"split",
"(",
"\"/\"",
")",
"return",
"Device",
"(",
"self",
".",
"db",
",",
"splitted_path",
"[",
"0",
"]",
"+",
"\"/\"",
"+",
"splitted_path",
"[",
"1",
"]",
... | 35.833333 | 0.009091 |
def is_mod_class(mod, cls):
"""Checks if a class in a module was declared in that module.
Args:
mod: the module
cls: the class
"""
return inspect.isclass(cls) and inspect.getmodule(cls) == mod | [
"def",
"is_mod_class",
"(",
"mod",
",",
"cls",
")",
":",
"return",
"inspect",
".",
"isclass",
"(",
"cls",
")",
"and",
"inspect",
".",
"getmodule",
"(",
"cls",
")",
"==",
"mod"
] | 27.25 | 0.004444 |
def check_declared(self, node):
"""update the state of this Identifiers with the undeclared
and declared identifiers of the given node."""
for ident in node.undeclared_identifiers():
if ident != 'context' and\
ident not in self.declared.union(self.locally_dec... | [
"def",
"check_declared",
"(",
"self",
",",
"node",
")",
":",
"for",
"ident",
"in",
"node",
".",
"undeclared_identifiers",
"(",
")",
":",
"if",
"ident",
"!=",
"'context'",
"and",
"ident",
"not",
"in",
"self",
".",
"declared",
".",
"union",
"(",
"self",
... | 45.6 | 0.004301 |
def search_stack_for_var(varname, verbose=util_arg.NOT_QUIET):
"""
Finds a varable (local or global) somewhere in the stack and returns the value
Args:
varname (str): variable name
Returns:
None if varname is not found else its value
"""
curr_frame = inspect.currentframe()
... | [
"def",
"search_stack_for_var",
"(",
"varname",
",",
"verbose",
"=",
"util_arg",
".",
"NOT_QUIET",
")",
":",
"curr_frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"if",
"verbose",
":",
"print",
"(",
"' * Searching parent frames for: '",
"+",
"six",
".",
... | 36.178571 | 0.002885 |
def principals(geom, masses, on_tol=_DEF.ORTHONORM_TOL):
"""Principal axes and moments of inertia for the indicated geometry.
Calculated by :func:`scipy.linalg.eigh`, since the moment of inertia tensor
is symmetric (real-Hermitian) by construction. More convenient to
compute both the axes and moments ... | [
"def",
"principals",
"(",
"geom",
",",
"masses",
",",
"on_tol",
"=",
"_DEF",
".",
"ORTHONORM_TOL",
")",
":",
"# Imports",
"import",
"numpy",
"as",
"np",
"from",
"scipy",
"import",
"linalg",
"as",
"spla",
"from",
".",
".",
"const",
"import",
"PRM",
",",
... | 39.753036 | 0.009538 |
def _get_types(type_):
""" Gathers all types within the ``TYPE_MAPPINGS`` for a specific ``Types`` value.
:param Types type_: The type to retrieve
:return: All types within the ``TYPE_MAPPINGS``
:rtype: list
"""
return list(
itertools.chain.from_iterable(
map(lambda x: TYPE... | [
"def",
"_get_types",
"(",
"type_",
")",
":",
"return",
"list",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"map",
"(",
"lambda",
"x",
":",
"TYPE_MAPPINGS",
"[",
"x",
"]",
".",
"get",
"(",
"type_",
",",
"[",
"]",
")",
",",
"TYPE_MAPPING... | 28.230769 | 0.005277 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.