text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _set_rules(self, group, rules):
"""Implementation detail"""
group.clear()
for rule in rules:
self._add_rule(group, *rule)
self.invalidate() | [
"def",
"_set_rules",
"(",
"self",
",",
"group",
",",
"rules",
")",
":",
"group",
".",
"clear",
"(",
")",
"for",
"rule",
"in",
"rules",
":",
"self",
".",
"_add_rule",
"(",
"group",
",",
"*",
"rule",
")",
"self",
".",
"invalidate",
"(",
")"
] | 22.75 | 0.010582 |
def replace_unicode(cls, replacement_string):
"""This method will iterate over every character in
``replacement_string`` and see if it mathces any of the
unicode codepoints that we recognize. If it does then it will
replace that codepoint with an image just like ``replace``.
NOT... | [
"def",
"replace_unicode",
"(",
"cls",
",",
"replacement_string",
")",
":",
"e",
"=",
"cls",
"(",
")",
"output",
"=",
"[",
"]",
"surrogate_character",
"=",
"None",
"if",
"settings",
".",
"EMOJI_REPLACE_HTML_ENTITIES",
":",
"replacement_string",
"=",
"cls",
".",... | 37.22 | 0.001047 |
def xresnet50_2(pretrained=False, **kwargs):
"""Constructs a XResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = XResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['xresnet50']))
... | [
"def",
"xresnet50_2",
"(",
"pretrained",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"model",
"=",
"XResNet",
"(",
"Bottleneck",
",",
"[",
"3",
",",
"4",
",",
"6",
",",
"3",
"]",
",",
"*",
"*",
"kwargs",
")",
"if",
"pretrained",
":",
"model"... | 36.444444 | 0.008929 |
def init_group(self, group, chunk_size,
compression=None, compression_opts=None):
"""Initializes a HDF5 group compliant with the stored data.
This method creates the datasets 'items', 'labels', 'features'
and 'index' and leaves them empty.
:param h5py.Group group: Th... | [
"def",
"init_group",
"(",
"self",
",",
"group",
",",
"chunk_size",
",",
"compression",
"=",
"None",
",",
"compression_opts",
"=",
"None",
")",
":",
"create_index",
"(",
"group",
",",
"chunk_size",
")",
"self",
".",
"_entries",
"[",
"'items'",
"]",
".",
"... | 40.171429 | 0.002083 |
def myself(self):
"""
Return a :class:`Context` referring to the current process.
"""
return self.context_class(
router=self,
context_id=mitogen.context_id,
name='self',
) | [
"def",
"myself",
"(",
"self",
")",
":",
"return",
"self",
".",
"context_class",
"(",
"router",
"=",
"self",
",",
"context_id",
"=",
"mitogen",
".",
"context_id",
",",
"name",
"=",
"'self'",
",",
")"
] | 26.555556 | 0.008097 |
def open_file(filename, mode='r', encoding=None, errors='strict',
lazy=False, atomic=False):
"""This is similar to how the :class:`File` works but for manual
usage. Files are opened non lazy by default. This can open regular
files as well as stdin/stdout if ``'-'`` is passed.
If stdin/s... | [
"def",
"open_file",
"(",
"filename",
",",
"mode",
"=",
"'r'",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"lazy",
"=",
"False",
",",
"atomic",
"=",
"False",
")",
":",
"if",
"lazy",
":",
"return",
"LazyFile",
"(",
"filename",
",... | 41.967742 | 0.001503 |
def loadTex(self,name,category):
"""
Loads the texture of the given name and category.
All textures currently must be PNG files, although support for more formats may be added soon.
If the texture cannot be found, a missing texture will instead be returned. See :py:meth... | [
"def",
"loadTex",
"(",
"self",
",",
"name",
",",
"category",
")",
":",
"try",
":",
"img",
"=",
"pyglet",
".",
"image",
".",
"load",
"(",
"self",
".",
"resourceNameToPath",
"(",
"name",
",",
"\".png\"",
")",
")",
"except",
"FileNotFoundError",
":",
"img... | 54.735294 | 0.014784 |
def createEditor(self, delegate, parent, option):
""" Creates a ChoiceCtiEditor.
For the parameters see the AbstractCti constructor documentation.
"""
return FontChoiceCtiEditor(self, delegate, parent=parent) | [
"def",
"createEditor",
"(",
"self",
",",
"delegate",
",",
"parent",
",",
"option",
")",
":",
"return",
"FontChoiceCtiEditor",
"(",
"self",
",",
"delegate",
",",
"parent",
"=",
"parent",
")"
] | 48 | 0.008197 |
def load_commodities(self):
"""
Load the commodities for Amounts in this object.
"""
if isinstance(self.amount, Amount):
self.amount = Amount("{0:.8f} {1}".format(self.amount.to_double(), self.currency))
else:
self.amount = Amount("{0:.8f} {1}".format(self... | [
"def",
"load_commodities",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"amount",
",",
"Amount",
")",
":",
"self",
".",
"amount",
"=",
"Amount",
"(",
"\"{0:.8f} {1}\"",
".",
"format",
"(",
"self",
".",
"amount",
".",
"to_double",
"(",
"... | 42.125 | 0.011628 |
def find_dependencies(self, depslock_file_path, property_validate=True, deps_content=None):
"""
Find all dependencies by package
:param depslock_file_path:
:param property_validate: for `root` packages we need check property, bad if we find packages from `lock` file,
:param deps_... | [
"def",
"find_dependencies",
"(",
"self",
",",
"depslock_file_path",
",",
"property_validate",
"=",
"True",
",",
"deps_content",
"=",
"None",
")",
":",
"self",
".",
"_raw",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"_downloader",
".",
"common_parser",
"... | 61.076923 | 0.009926 |
def _tree_line(self, no_type: bool = False) -> str:
"""Return the receiver's contribution to tree diagram."""
return super()._tree_line() + ("!" if self.presence else "") | [
"def",
"_tree_line",
"(",
"self",
",",
"no_type",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"return",
"super",
"(",
")",
".",
"_tree_line",
"(",
")",
"+",
"(",
"\"!\"",
"if",
"self",
".",
"presence",
"else",
"\"\"",
")"
] | 61.333333 | 0.010753 |
def get_list(self, name, default=None):
"""Retrieves an environment variable as a list.
Note that while implicit access of environment variables
containing tuples will return tuples, using this method will
coerce tuples to lists.
Args:
name (str): The case-insensiti... | [
"def",
"get_list",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"if",
"name",
"not",
"in",
"self",
":",
"if",
"default",
"is",
"not",
"None",
":",
"return",
"default",
"raise",
"EnvironmentError",
".",
"not_found",
"(",
"self",
".",... | 36.333333 | 0.001986 |
def create(self, data):
"""Creates new entry in mongo database
"""
q = self.history.insert_one(data).inserted_id
logging.debug(self.history.find_one({"_id":q})) | [
"def",
"create",
"(",
"self",
",",
"data",
")",
":",
"q",
"=",
"self",
".",
"history",
".",
"insert_one",
"(",
"data",
")",
".",
"inserted_id",
"logging",
".",
"debug",
"(",
"self",
".",
"history",
".",
"find_one",
"(",
"{",
"\"_id\"",
":",
"q",
"}... | 33.2 | 0.047059 |
def SvcDoRun(self) -> None:
"""
Called when the service is started.
"""
# No need to self.ReportServiceStatus(win32service.SERVICE_RUNNING);
# that is done by the framework (see win32serviceutil.py).
# Similarly, no need to report a SERVICE_STOP_PENDING on exit.
#... | [
"def",
"SvcDoRun",
"(",
"self",
")",
"->",
"None",
":",
"# No need to self.ReportServiceStatus(win32service.SERVICE_RUNNING);",
"# that is done by the framework (see win32serviceutil.py).",
"# Similarly, no need to report a SERVICE_STOP_PENDING on exit.",
"# noinspection PyUnresolvedReferences... | 46.043478 | 0.00185 |
def ckcov(ck, idcode, needav, level, tol, timsys, cover=None):
"""
Find the coverage window for a specified object in a specified CK file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckcov_c.html
:param ck: Name of CK file.
:type ck: str
:param idcode: ID code of object.
:type ... | [
"def",
"ckcov",
"(",
"ck",
",",
"idcode",
",",
"needav",
",",
"level",
",",
"tol",
",",
"timsys",
",",
"cover",
"=",
"None",
")",
":",
"ck",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ck",
")",
"idcode",
"=",
"ctypes",
".",
"c_int",
"(",
"idcode",
... | 36.194444 | 0.000747 |
def thaw_args(subparsers):
"""Add command line options for the thaw operation"""
thaw_parser = subparsers.add_parser('thaw')
thaw_parser.add_argument('--gpg-password-path',
dest='gpg_pass_path',
help='Vault path of GPG passphrase location')
thaw_... | [
"def",
"thaw_args",
"(",
"subparsers",
")",
":",
"thaw_parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'thaw'",
")",
"thaw_parser",
".",
"add_argument",
"(",
"'--gpg-password-path'",
",",
"dest",
"=",
"'gpg_pass_path'",
",",
"help",
"=",
"'Vault path of GPG p... | 46.125 | 0.001328 |
def conn_aws(cred, crid):
"""Establish connection to AWS service."""
driver = get_driver(Provider.EC2)
try:
aws_obj = driver(cred['aws_access_key_id'],
cred['aws_secret_access_key'],
region=cred['aws_default_region'])
except SSLError as e:
... | [
"def",
"conn_aws",
"(",
"cred",
",",
"crid",
")",
":",
"driver",
"=",
"get_driver",
"(",
"Provider",
".",
"EC2",
")",
"try",
":",
"aws_obj",
"=",
"driver",
"(",
"cred",
"[",
"'aws_access_key_id'",
"]",
",",
"cred",
"[",
"'aws_secret_access_key'",
"]",
",... | 40.5 | 0.002012 |
def open_graph(self, **args):
"""open a vcg graph
"""
self._stream.write("%sgraph:{\n" % self._indent)
self._inc_indent()
self._write_attributes(GRAPH_ATTRS, **args) | [
"def",
"open_graph",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"self",
".",
"_stream",
".",
"write",
"(",
"\"%sgraph:{\\n\"",
"%",
"self",
".",
"_indent",
")",
"self",
".",
"_inc_indent",
"(",
")",
"self",
".",
"_write_attributes",
"(",
"GRAPH_ATTRS"... | 33.333333 | 0.009756 |
def detect_Concordia(dat_orig, s_freq, time, opts):
"""Spindle detection, experimental Concordia method. Similar to Moelle 2011
and Nir2011.
Parameters
----------
dat_orig : ndarray (dtype='float')
vector with the data for one channel
s_freq : float
sampling frequency
opts :... | [
"def",
"detect_Concordia",
"(",
"dat_orig",
",",
"s_freq",
",",
"time",
",",
"opts",
")",
":",
"dat_det",
"=",
"transform_signal",
"(",
"dat_orig",
",",
"s_freq",
",",
"'butter'",
",",
"opts",
".",
"det_butter",
")",
"dat_det",
"=",
"transform_signal",
"(",
... | 35.375 | 0.000382 |
def with_respect_to(self):
"""
Returns a dict to use as a filter for ordering operations
containing the original ``Meta.order_with_respect_to`` value
if provided. If the field is a Generic Relation, the dict
returned contains names and values for looking up the
relation's... | [
"def",
"with_respect_to",
"(",
"self",
")",
":",
"try",
":",
"name",
"=",
"self",
".",
"order_with_respect_to",
"value",
"=",
"getattr",
"(",
"self",
",",
"name",
")",
"except",
"AttributeError",
":",
"# No ``order_with_respect_to`` specified on the model.",
"return... | 42.8 | 0.002286 |
def normalized(beta, beta_list):
"""归一化函数
Keyword arguments:
beta -- 当前文本行的beta值,float类型
beta_list -- 标题候选队列的beta队列,list类型
Return:
result -- 归一化结果,区间【0,1】
"""
if len(beta_list) <= 2:
# beta_list元素小于等于2时,根据jiaccard相似度公式进行判定
... | [
"def",
"normalized",
"(",
"beta",
",",
"beta_list",
")",
":",
"if",
"len",
"(",
"beta_list",
")",
"<=",
"2",
":",
"# beta_list元素小于等于2时,根据jiaccard相似度公式进行判定",
"return",
"1",
"try",
":",
"result",
"=",
"(",
"beta",
"-",
"min",
"(",
"beta_list",
")",
")",
"/... | 27.647059 | 0.002058 |
def get_user_id(username):
"""
Returns the user id to a given user name. Returns ``None`` if the user does not exist.
:param username: User name.
:type username: unicode
:return: User id.
:rtype: int
"""
uid = single_line_stdout('id -u {0}'.format(username), expected_errors=(1,), shell=... | [
"def",
"get_user_id",
"(",
"username",
")",
":",
"uid",
"=",
"single_line_stdout",
"(",
"'id -u {0}'",
".",
"format",
"(",
"username",
")",
",",
"expected_errors",
"=",
"(",
"1",
",",
")",
",",
"shell",
"=",
"False",
")",
"return",
"check_int",
"(",
"uid... | 31.090909 | 0.008523 |
def _fill_sample_count(self, node):
"""Counts and fills sample counts inside call tree."""
node['sampleCount'] += sum(
self._fill_sample_count(child) for child in node['children'])
return node['sampleCount'] | [
"def",
"_fill_sample_count",
"(",
"self",
",",
"node",
")",
":",
"node",
"[",
"'sampleCount'",
"]",
"+=",
"sum",
"(",
"self",
".",
"_fill_sample_count",
"(",
"child",
")",
"for",
"child",
"in",
"node",
"[",
"'children'",
"]",
")",
"return",
"node",
"[",
... | 47.8 | 0.00823 |
def df_numeric_column(min_value=0, max_value=1, num_rows=100):
"""Generate a numeric column with random data
Args:
min_value (float): Minimum value (default = 0)
max_value (float): Maximum value (default = 1)
num_rows (int): The number of rows to generate (default = 100)... | [
"def",
"df_numeric_column",
"(",
"min_value",
"=",
"0",
",",
"max_value",
"=",
"1",
",",
"num_rows",
"=",
"100",
")",
":",
"# Generate numeric column",
"return",
"pd",
".",
"Series",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"min_value",
",",
"max_val... | 46.888889 | 0.002326 |
def draw_spectra(md, ds):
""" Generate best-fit spectra for all the test objects
Parameters
----------
md: model
The Cannon spectral model
ds: Dataset
Dataset object
Returns
-------
best_fluxes: ndarray
The best-fit test fluxes
best_ivars:
The ... | [
"def",
"draw_spectra",
"(",
"md",
",",
"ds",
")",
":",
"coeffs_all",
",",
"covs",
",",
"scatters",
",",
"red_chisqs",
",",
"pivots",
",",
"label_vector",
"=",
"model",
".",
"model",
"nstars",
"=",
"len",
"(",
"dataset",
".",
"test_SNR",
")",
"cannon_flux... | 28.133333 | 0.010309 |
def meryl(args):
"""
%prog meryl folder
Run meryl on Illumina reads.
"""
p = OptionParser(meryl.__doc__)
p.add_option("-k", default=19, type="int", help="Kmer size")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
folder, = ... | [
"def",
"meryl",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"meryl",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"-k\"",
",",
"default",
"=",
"19",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Kmer size\"",
")",
"p",
".",
"se... | 27.567568 | 0.001894 |
def save_file(self):
"""Saves the notebook to a file"""
with open(self.write_file, 'w') as out_nb:
json.dump(self.work_notebook, out_nb, indent=2) | [
"def",
"save_file",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"write_file",
",",
"'w'",
")",
"as",
"out_nb",
":",
"json",
".",
"dump",
"(",
"self",
".",
"work_notebook",
",",
"out_nb",
",",
"indent",
"=",
"2",
")"
] | 42.75 | 0.011494 |
def remove_specification(self, name):
""" Remove a specification that matches a query parameter. No checks for the specified or any parameter
are made regarding specification removing
:param name: parameter name to remove
:return: None
"""
if name in self.__specs:
self.__specs.pop(name) | [
"def",
"remove_specification",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"__specs",
":",
"self",
".",
"__specs",
".",
"pop",
"(",
"name",
")"
] | 32.777778 | 0.033003 |
def genty(target_cls):
"""
This decorator takes the information provided by @genty_dataset,
@genty_dataprovider, and @genty_repeat and generates the corresponding
test methods.
:param target_cls:
Test class whose test methods have been decorated.
:type target_cls:
`class`
""... | [
"def",
"genty",
"(",
"target_cls",
")",
":",
"tests",
"=",
"_expand_tests",
"(",
"target_cls",
")",
"tests_with_datasets",
"=",
"_expand_datasets",
"(",
"tests",
")",
"tests_with_datasets_and_repeats",
"=",
"_expand_repeats",
"(",
"tests_with_datasets",
")",
"_add_new... | 31.222222 | 0.001727 |
def _hm_form_message(
self,
thermostat_id,
protocol,
source,
function,
start,
payload
):
"""Forms a message payload, excluding CRC"""
if protocol == constants.HMV3_ID:
start_low = (start & cons... | [
"def",
"_hm_form_message",
"(",
"self",
",",
"thermostat_id",
",",
"protocol",
",",
"source",
",",
"function",
",",
"start",
",",
"payload",
")",
":",
"if",
"protocol",
"==",
"constants",
".",
"HMV3_ID",
":",
"start_low",
"=",
"(",
"start",
"&",
"constants... | 35.157895 | 0.002185 |
def _prepare_polib_files(files_dict, filename, languages,
locale_root, po_files_path, header):
"""
Prepare polib file object for writing/reading from them.
Create directories and write header if needed. For each language,
ensure there's a translation file named "filename" in the... | [
"def",
"_prepare_polib_files",
"(",
"files_dict",
",",
"filename",
",",
"languages",
",",
"locale_root",
",",
"po_files_path",
",",
"header",
")",
":",
"files_dict",
"[",
"filename",
"]",
"=",
"{",
"}",
"for",
"lang",
"in",
"languages",
":",
"file_path",
"="... | 42.55 | 0.001149 |
def create(cls, cli, sp, ip_port, ip_address, netmask=None,
v6_prefix_length=None, gateway=None, vlan_id=None):
"""
Creates a replication interface.
:param cls: this class.
:param cli: the rest cli.
:param sp: `UnityStorageProcessor` object. Storage processor on w... | [
"def",
"create",
"(",
"cls",
",",
"cli",
",",
"sp",
",",
"ip_port",
",",
"ip_address",
",",
"netmask",
"=",
"None",
",",
"v6_prefix_length",
"=",
"None",
",",
"gateway",
"=",
"None",
",",
"vlan_id",
"=",
"None",
")",
":",
"req_body",
"=",
"cli",
".",... | 48.344828 | 0.002098 |
def QA_fetch_get_globalfuture_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
14 3 伦敦金属 LM
15 3 伦敦石油 IP
16 3 纽约商... | [
"def",
"QA_fetch_get_globalfuture_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"global",
"extension_market_list",
"extension_market_list",
"=",
"QA_fetch_get_extensionmarket_list",
"(",
")",
"if",
"extension_market_list",
"is",
"None",
"else",
"e... | 36.04 | 0.002162 |
def itemByPath( self, path, includeRoot = False ):
"""
Loads the items for the given path.
:param path | <str>
includeRoot | <bool>
"""
sep = self.separator()
path = nativestring(path).strip(sep)
if ( not path ):
... | [
"def",
"itemByPath",
"(",
"self",
",",
"path",
",",
"includeRoot",
"=",
"False",
")",
":",
"sep",
"=",
"self",
".",
"separator",
"(",
")",
"path",
"=",
"nativestring",
"(",
"path",
")",
".",
"strip",
"(",
"sep",
")",
"if",
"(",
"not",
"path",
")",
... | 28.878788 | 0.02335 |
def get_parent_ps(self):
"""
Return a :class:`ParameterSet` of all Parameters in the same
:class:`phoebe.frontend.bundle.Bundle` which share the same
meta-tags (except qualifier, twig, uniquetwig)
:return: the parent :class:`ParameterSet`
"""
if self._bundle is N... | [
"def",
"get_parent_ps",
"(",
"self",
")",
":",
"if",
"self",
".",
"_bundle",
"is",
"None",
":",
"return",
"None",
"metawargs",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"meta",
".",
"items",
"(",
")",
"if",
"k",
"not",
"... | 34.857143 | 0.00998 |
def create_volume(self, name=None, driver=None, driver_opts=None,
labels=None):
"""
Create and register a named volume
Args:
name (str): Name of the volume
driver (str): Name of the driver used to create the volume
driver_opts (dict): Dr... | [
"def",
"create_volume",
"(",
"self",
",",
"name",
"=",
"None",
",",
"driver",
"=",
"None",
",",
"driver_opts",
"=",
"None",
",",
"labels",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"_url",
"(",
"'/volumes/create'",
")",
"if",
"driver_opts",
"is",... | 34.254902 | 0.001669 |
def send_signal_to_gdb(self, signal_input):
"""Send signal name (case insensitive) or number to gdb subprocess
gdbmi.send_signal_to_gdb(2) # valid
gdbmi.send_signal_to_gdb('sigint') # also valid
gdbmi.send_signal_to_gdb('SIGINT') # also valid
raises ValueError if signal_input... | [
"def",
"send_signal_to_gdb",
"(",
"self",
",",
"signal_input",
")",
":",
"try",
":",
"signal",
"=",
"int",
"(",
"signal_input",
")",
"except",
"Exception",
":",
"signal",
"=",
"SIGNAL_NAME_TO_NUM",
".",
"get",
"(",
"signal_input",
".",
"upper",
"(",
")",
"... | 36.44 | 0.002139 |
def explode(self):
"""
Try to resolve each timeperiod
:return: None
"""
for t_id in self.items:
timeperiod = self.items[t_id]
timeperiod.explode() | [
"def",
"explode",
"(",
"self",
")",
":",
"for",
"t_id",
"in",
"self",
".",
"items",
":",
"timeperiod",
"=",
"self",
".",
"items",
"[",
"t_id",
"]",
"timeperiod",
".",
"explode",
"(",
")"
] | 22.555556 | 0.009479 |
def json(func):
"Decorator to make JSON views simpler"
def wrapper(self, request, *args, **kwargs):
try:
response = {
"success": True,
"data": func(self, request, *args, **kwargs)
}
except GargoyleException, exc:
response = {
... | [
"def",
"json",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"response",
"=",
"{",
"\"success\"",
":",
"True",
",",
"\"data\"",
":",
"func",
"(",
"self",
","... | 30.5 | 0.000993 |
def check_env_cache(opts, env_cache):
'''
Returns cached env names, if present. Otherwise returns None.
'''
if not os.path.isfile(env_cache):
return None
try:
with salt.utils.files.fopen(env_cache, 'rb') as fp_:
log.trace('Returning env cache data from %s', env_cache)
... | [
"def",
"check_env_cache",
"(",
"opts",
",",
"env_cache",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"env_cache",
")",
":",
"return",
"None",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"env_cache",
",... | 33.571429 | 0.00207 |
def getImage(path, dockerfile, tag):
'''Check if an image with a given tag exists. If not, build an image from
using a given dockerfile in a given path, tagging it with a given tag.
No extra side effects. Handles and reraises BuildError, TypeError, and
APIError exceptions.
'''
image = getImageBy... | [
"def",
"getImage",
"(",
"path",
",",
"dockerfile",
",",
"tag",
")",
":",
"image",
"=",
"getImageByTag",
"(",
"tag",
")",
"if",
"not",
"image",
":",
"# Build an Image using the dockerfile in the path",
"try",
":",
"image",
"=",
"client",
".",
"images",
".",
"... | 33.259259 | 0.001082 |
def addGene(
self, gene_id, gene_label, gene_type=None, gene_description=None
):
''' genes are classes '''
if gene_type is None:
gene_type = self.globaltt['gene']
self.model.addClassToGraph(gene_id, gene_label, gene_type, gene_description)
return | [
"def",
"addGene",
"(",
"self",
",",
"gene_id",
",",
"gene_label",
",",
"gene_type",
"=",
"None",
",",
"gene_description",
"=",
"None",
")",
":",
"if",
"gene_type",
"is",
"None",
":",
"gene_type",
"=",
"self",
".",
"globaltt",
"[",
"'gene'",
"]",
"self",
... | 33.222222 | 0.013029 |
def listdir(self, folder_id='me/skydrive', limit=None, offset=None):
'Get OneDrive object representing list of objects in a folder.'
return self(self._api_url_join(folder_id, 'files'), dict(limit=limit, offset=offset)) | [
"def",
"listdir",
"(",
"self",
",",
"folder_id",
"=",
"'me/skydrive'",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"return",
"self",
"(",
"self",
".",
"_api_url_join",
"(",
"folder_id",
",",
"'files'",
")",
",",
"dict",
"(",
"limit... | 73.333333 | 0.022523 |
def to_frame(self, frame, current_frame=None, **kwargs):
"""
TODO:
Parameters
----------
frame : `gala.potential.CFrameBase`
The frame to transform to.
current_frame : `gala.potential.CFrameBase` (optional)
If the Orbit has no associated Hamiltoni... | [
"def",
"to_frame",
"(",
"self",
",",
"frame",
",",
"current_frame",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kw",
"=",
"kwargs",
".",
"copy",
"(",
")",
"# TODO: need a better way to do this!",
"from",
".",
".",
"potential",
".",
"frame",
".",
"bu... | 31.125 | 0.001947 |
def get(self, path, auth=None, **kwargs):
"""
Manually make a GET request.
:param str path: relative url of the request (e.g. `/users/username`)
:param auth.Authentication auth: authentication object
:param kwargs dict: Extra arguments for the request, as supported by the
... | [
"def",
"get",
"(",
"self",
",",
"path",
",",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_check_ok",
"(",
"self",
".",
"_get",
"(",
"path",
",",
"auth",
"=",
"auth",
",",
"*",
"*",
"kwargs",
")",
")"
] | 50.916667 | 0.008039 |
def chart(self, x=None, y=None, chart_type=None, opts=None,
style=None, label=None, options={}, **kwargs):
"""
Get a chart
"""
try:
self.chart_obj = self._chart(x, y, chart_type, opts, style, label,
options=options, **kwargs)
except Exception as e:
self.err(e, self.chart, "Can not create... | [
"def",
"chart",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"chart_type",
"=",
"None",
",",
"opts",
"=",
"None",
",",
"style",
"=",
"None",
",",
"label",
"=",
"None",
",",
"options",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
... | 31.9 | 0.045732 |
def find_executable(name, names=None, required=True):
"""Utility function to find an executable in PATH
name: program to find. Use given value if absolute path
names: list of additional names. For instance
>>> find_executable('sed', names=['gsed'])
required: If True, then the function raises a... | [
"def",
"find_executable",
"(",
"name",
",",
"names",
"=",
"None",
",",
"required",
"=",
"True",
")",
":",
"path_from_env",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
".",
"upper",
"(",
")",
")",
"if",
"path_from_env",
"is",
"not",
"None",
":... | 32.814815 | 0.001096 |
def add_info_to_exception(err: Exception, info: Dict) -> None:
"""
Adds an information dictionary to an exception.
See
http://stackoverflow.com/questions/9157210/how-do-i-raise-the-same-exception-with-a-custom-message-in-python
Args:
err: the exception to be modified
info: ... | [
"def",
"add_info_to_exception",
"(",
"err",
":",
"Exception",
",",
"info",
":",
"Dict",
")",
"->",
"None",
":",
"# noqa",
"if",
"not",
"err",
".",
"args",
":",
"err",
".",
"args",
"=",
"(",
"''",
",",
")",
"err",
".",
"args",
"+=",
"(",
"info",
"... | 29.785714 | 0.002326 |
def _init_proc(self):
"""Start processes if not already started"""
if not self.proc:
self.proc = [
mp.Process(target=self._proc_loop, args=(i, self.alive, self.queue, self.fn))
for i in range(self.num_proc)
]
self.alive.value = True
... | [
"def",
"_init_proc",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"proc",
":",
"self",
".",
"proc",
"=",
"[",
"mp",
".",
"Process",
"(",
"target",
"=",
"self",
".",
"_proc_loop",
",",
"args",
"=",
"(",
"i",
",",
"self",
".",
"alive",
",",
"... | 36.5 | 0.008021 |
def set_commission(self, us_equities=None, us_futures=None):
"""Sets the commission models for the simulation.
Parameters
----------
us_equities : EquityCommissionModel
The commission model to use for trading US equities.
us_futures : FutureCommissionModel
... | [
"def",
"set_commission",
"(",
"self",
",",
"us_equities",
"=",
"None",
",",
"us_futures",
"=",
"None",
")",
":",
"if",
"self",
".",
"initialized",
":",
"raise",
"SetCommissionPostInit",
"(",
")",
"if",
"us_equities",
"is",
"not",
"None",
":",
"if",
"Equity... | 38.944444 | 0.001392 |
def _check_cpd_inputs(X, rank):
"""Checks that inputs to optimization function are appropriate.
Parameters
----------
X : ndarray
Tensor used for fitting CP decomposition.
rank : int
Rank of low rank decomposition.
Raises
------
ValueError: If inputs are not suited for ... | [
"def",
"_check_cpd_inputs",
"(",
"X",
",",
"rank",
")",
":",
"if",
"X",
".",
"ndim",
"<",
"3",
":",
"raise",
"ValueError",
"(",
"\"Array with X.ndim > 2 expected.\"",
")",
"if",
"rank",
"<=",
"0",
"or",
"not",
"isinstance",
"(",
"rank",
",",
"int",
")",
... | 27.722222 | 0.001938 |
def plus(self, a):
""" Add. """
return Vector(self.x+a.x, self.y+a.y, self.z+a.z) | [
"def",
"plus",
"(",
"self",
",",
"a",
")",
":",
"return",
"Vector",
"(",
"self",
".",
"x",
"+",
"a",
".",
"x",
",",
"self",
".",
"y",
"+",
"a",
".",
"y",
",",
"self",
".",
"z",
"+",
"a",
".",
"z",
")"
] | 31.666667 | 0.020619 |
def resources(self, type_=None, title=None, **kwargs):
"""Query for resources limited by either type and/or title or query.
This will yield a Resources object for every returned resource.
:param type_: (Optional) The resource type. This can be any resource
type referenced in\
... | [
"def",
"resources",
"(",
"self",
",",
"type_",
"=",
"None",
",",
"title",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"None",
"if",
"type_",
"is",
"not",
"None",
":",
"type_",
"=",
"self",
".",
"_normalize_resource_type",
"(",
"type_... | 39.731707 | 0.002397 |
def curve_to(self, x, y, x2, y2, x3, y3):
"""draw a curve. (x2, y2) is the middle point of the curve"""
self._add_instruction("curve_to", x, y, x2, y2, x3, y3) | [
"def",
"curve_to",
"(",
"self",
",",
"x",
",",
"y",
",",
"x2",
",",
"y2",
",",
"x3",
",",
"y3",
")",
":",
"self",
".",
"_add_instruction",
"(",
"\"curve_to\"",
",",
"x",
",",
"y",
",",
"x2",
",",
"y2",
",",
"x3",
",",
"y3",
")"
] | 57.666667 | 0.011429 |
def _allocate_from_v6_subnet(self, context, net_id, subnet,
port_id, reuse_after, ip_address=None,
**kwargs):
"""This attempts to allocate v6 addresses as per RFC2462 and RFC3041.
To accomodate this, we effectively treat all v6 assignmen... | [
"def",
"_allocate_from_v6_subnet",
"(",
"self",
",",
"context",
",",
"net_id",
",",
"subnet",
",",
"port_id",
",",
"reuse_after",
",",
"ip_address",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"LOG",
".",
"info",
"(",
"\"Attempting to allocate a v6 address... | 48.561644 | 0.001106 |
def _get_def_class(self, class_obj, member_name):
"""
Return the class object in MRO order that defines a member.
class_obj: Class object that exposes (but not necessarily defines) the
member. I.e. starting point of the search.
member_name: Name of the member (method or attri... | [
"def",
"_get_def_class",
"(",
"self",
",",
"class_obj",
",",
"member_name",
")",
":",
"member_obj",
"=",
"getattr",
"(",
"class_obj",
",",
"member_name",
")",
"for",
"def_class_obj",
"in",
"inspect",
".",
"getmro",
"(",
"class_obj",
")",
":",
"if",
"member_n... | 40.291667 | 0.00202 |
def _update_secondary_channels(self, p):
"""Given a process, this method updates the
:attr:`~Process.secondary_channels` attribute with the corresponding
secondary inputs of that channel.
The rationale of the secondary channels is the following:
- Start storing any secondar... | [
"def",
"_update_secondary_channels",
"(",
"self",
",",
"p",
")",
":",
"# Check if the current process has a start of a secondary",
"# side channel",
"if",
"p",
".",
"link_start",
":",
"logger",
".",
"debug",
"(",
"\"[{}] Found secondary link start: {}\"",
".",
"format",
"... | 44.910448 | 0.001301 |
def get_current_span():
"""
Access current request context and extract current Span from it.
:return:
Return current span associated with the current request context.
If no request context is present in thread local, or the context
has no span, return None.
"""
# Check agains... | [
"def",
"get_current_span",
"(",
")",
":",
"# Check against the old, ScopeManager-less implementation,",
"# for backwards compatibility.",
"context",
"=",
"RequestContextManager",
".",
"current_context",
"(",
")",
"if",
"context",
"is",
"not",
"None",
":",
"return",
"context... | 36.9375 | 0.00165 |
def concat(variables, dim='concat_dim', positions=None, shortcut=False):
"""Concatenate variables along a new or existing dimension.
Parameters
----------
variables : iterable of Array
Arrays to stack together. Each variable is expected to have
matching dimensions and shape except for a... | [
"def",
"concat",
"(",
"variables",
",",
"dim",
"=",
"'concat_dim'",
",",
"positions",
"=",
"None",
",",
"shortcut",
"=",
"False",
")",
":",
"variables",
"=",
"list",
"(",
"variables",
")",
"if",
"all",
"(",
"isinstance",
"(",
"v",
",",
"IndexVariable",
... | 45.142857 | 0.00062 |
def _apply_callables(self, acl, obj=None):
""" Iterate over ACEs from :acl: and apply callable principals
if any.
Principals are passed 3 arguments on call:
:ace: Single ACE object that looks like (action, callable,
permission or [permission])
:request: C... | [
"def",
"_apply_callables",
"(",
"self",
",",
"acl",
",",
"obj",
"=",
"None",
")",
":",
"new_acl",
"=",
"[",
"]",
"for",
"i",
",",
"ace",
"in",
"enumerate",
"(",
"acl",
")",
":",
"principal",
"=",
"ace",
"[",
"1",
"]",
"if",
"six",
".",
"callable"... | 39.535714 | 0.001764 |
def get_mnl_point_est(orig_model_obj,
new_df,
boot_id_col,
num_params,
mnl_spec,
mnl_names,
mnl_init_vals,
mnl_fit_kwargs):
"""
Calculates the MLE for the des... | [
"def",
"get_mnl_point_est",
"(",
"orig_model_obj",
",",
"new_df",
",",
"boot_id_col",
",",
"num_params",
",",
"mnl_spec",
",",
"mnl_names",
",",
"mnl_init_vals",
",",
"mnl_fit_kwargs",
")",
":",
"# Get specification and name dictionaries for the mnl model, for the case",
"#... | 48.369048 | 0.000241 |
def table_is_subset_of(entries_a, entries_b):
"""Check that every key matched by every entry in one table results in the
same route when checked against the other table.
For example, the table::
>>> from rig.routing_table import Routes
>>> table = [
... RoutingTableEntry({Route... | [
"def",
"table_is_subset_of",
"(",
"entries_a",
",",
"entries_b",
")",
":",
"# Determine which bits we don't need to explicitly test for",
"common_xs",
"=",
"get_common_xs",
"(",
"entries_b",
")",
"# For every entry in the first table",
"for",
"entry",
"in",
"expand_entries",
... | 37.065934 | 0.000289 |
def __apply_mask(address_packed, mask_packed, nr_bytes):
"""
Perform a bitwise AND operation on all corresponding bytes between the
mask and the provided address. Mask parts set to 0 will become 0 in the
anonymized IP address as well
:param bytes address_packed: Binary representation of the IP addre... | [
"def",
"__apply_mask",
"(",
"address_packed",
",",
"mask_packed",
",",
"nr_bytes",
")",
":",
"anon_packed",
"=",
"bytearray",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"nr_bytes",
")",
":",
"anon_packed",
".",
"append",
"(",
"ord",
"(",
"mask_p... | 40.368421 | 0.001274 |
def reversals(series, left=False, right=False):
"""Iterate reversal points in the series.
A reversal point is a point in the series at which the first derivative
changes sign. Reversal is undefined at the first (last) point because the
derivative before (after) this point is undefined. The first and th... | [
"def",
"reversals",
"(",
"series",
",",
"left",
"=",
"False",
",",
"right",
"=",
"False",
")",
":",
"series",
"=",
"iter",
"(",
"series",
")",
"x_last",
",",
"x",
"=",
"next",
"(",
"series",
")",
",",
"next",
"(",
"series",
")",
"d_last",
"=",
"(... | 28.512821 | 0.00087 |
def native(self, value, context=None):
"""Convert the given string into a list of substrings."""
separator = self.separator.strip() if self.strip and hasattr(self.separator, 'strip') else self.separator
value = super().native(value, context)
if value is None:
return self.cast()
if hasattr(value, '... | [
"def",
"native",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"separator",
"=",
"self",
".",
"separator",
".",
"strip",
"(",
")",
"if",
"self",
".",
"strip",
"and",
"hasattr",
"(",
"self",
".",
"separator",
",",
"'strip'",
")",
... | 31.333333 | 0.04475 |
def autocorrelation(
data, name, maxlags=100, format='png', reflected=False, suffix='-acf', path='./',
fontmap=None, new=True, last=True, rows=1, columns=1, num=1, verbose=1):
"""
Generate bar plot of the autocorrelation function for a series (usually an MCMC trace).
:Arguments:
data: P... | [
"def",
"autocorrelation",
"(",
"data",
",",
"name",
",",
"maxlags",
"=",
"100",
",",
"format",
"=",
"'png'",
",",
"reflected",
"=",
"False",
",",
"suffix",
"=",
"'-acf'",
",",
"path",
"=",
"'./'",
",",
"fontmap",
"=",
"None",
",",
"new",
"=",
"True",... | 28.727273 | 0.002379 |
def create(self, data):
"""Create a new component
"""
response = self.http.post(str(self), json=data, auth=self.auth)
response.raise_for_status()
return response.json() | [
"def",
"create",
"(",
"self",
",",
"data",
")",
":",
"response",
"=",
"self",
".",
"http",
".",
"post",
"(",
"str",
"(",
"self",
")",
",",
"json",
"=",
"data",
",",
"auth",
"=",
"self",
".",
"auth",
")",
"response",
".",
"raise_for_status",
"(",
... | 33.833333 | 0.009615 |
def max_ver(ver1, ver2):
"""Returns the greater version of two versions
:param ver1: version string 1
:param ver2: version string 2
:return: the greater version of the two
:rtype: :class:`VersionInfo`
>>> import semver
>>> semver.max_ver("1.0.0", "2.0.0")
'2.0.0'
"""
cmp_res = ... | [
"def",
"max_ver",
"(",
"ver1",
",",
"ver2",
")",
":",
"cmp_res",
"=",
"compare",
"(",
"ver1",
",",
"ver2",
")",
"if",
"cmp_res",
"==",
"0",
"or",
"cmp_res",
"==",
"1",
":",
"return",
"ver1",
"else",
":",
"return",
"ver2"
] | 24.117647 | 0.002347 |
def numpy_formatter(_, vertices, codes=None):
"""`NumPy`_ style contour formatter.
Contours are returned as a list of Nx2 arrays containing the x and y
vertices of the contour line.
For filled contours the direction of vertices matters:
* CCW (ACW): The vertices give the exterior of a contour pol... | [
"def",
"numpy_formatter",
"(",
"_",
",",
"vertices",
",",
"codes",
"=",
"None",
")",
":",
"if",
"codes",
"is",
"None",
":",
"return",
"vertices",
"numpy_vertices",
"=",
"[",
"]",
"for",
"vertices_",
",",
"codes_",
"in",
"zip",
"(",
"vertices",
",",
"co... | 35 | 0.00107 |
def doc_includes_process(xmldoc, program):
"""
Return True if the process table in xmldoc includes entries for a
program named program.
"""
return program in lsctables.ProcessTable.get_table(xmldoc).getColumnByName(u"program") | [
"def",
"doc_includes_process",
"(",
"xmldoc",
",",
"program",
")",
":",
"return",
"program",
"in",
"lsctables",
".",
"ProcessTable",
".",
"get_table",
"(",
"xmldoc",
")",
".",
"getColumnByName",
"(",
"u\"program\"",
")"
] | 37.666667 | 0.030303 |
def read_octet(self):
"""Read one byte, return as an integer"""
self.bitcount = self.bits = 0
return unpack('B', self.input.read(1))[0] | [
"def",
"read_octet",
"(",
"self",
")",
":",
"self",
".",
"bitcount",
"=",
"self",
".",
"bits",
"=",
"0",
"return",
"unpack",
"(",
"'B'",
",",
"self",
".",
"input",
".",
"read",
"(",
"1",
")",
")",
"[",
"0",
"]"
] | 39 | 0.012579 |
def get_radius_normal(lat_radians: float, ell: Ellipsoid = None) -> float:
"""
Compute normal radius of planetary body
Parameters
----------
lat_radians : float
latitude in radians
ell : Ellipsoid, optional
reference ellipsoid
Returns
-------
radius : float
... | [
"def",
"get_radius_normal",
"(",
"lat_radians",
":",
"float",
",",
"ell",
":",
"Ellipsoid",
"=",
"None",
")",
"->",
"float",
":",
"if",
"ell",
"is",
"None",
":",
"ell",
"=",
"Ellipsoid",
"(",
")",
"a",
"=",
"ell",
".",
"a",
"b",
"=",
"ell",
".",
... | 19.36 | 0.001969 |
def stats_evaluation(stats):
"""Generate an evaluation for the given pylint ``stats``."""
statement = stats.get('statement')
error = stats.get('error', 0)
warning = stats.get('warning', 0)
refactor = stats.get('refactor', 0)
convention = stats.get('convention', 0)
if not statement or statem... | [
"def",
"stats_evaluation",
"(",
"stats",
")",
":",
"statement",
"=",
"stats",
".",
"get",
"(",
"'statement'",
")",
"error",
"=",
"stats",
".",
"get",
"(",
"'error'",
",",
"0",
")",
"warning",
"=",
"stats",
".",
"get",
"(",
"'warning'",
",",
"0",
")",... | 33.785714 | 0.002058 |
def _postback(self):
"""Perform PayPal Postback validation."""
return requests.post(self.get_endpoint(), data=b"cmd=_notify-validate&" + self.query.encode("ascii")).content | [
"def",
"_postback",
"(",
"self",
")",
":",
"return",
"requests",
".",
"post",
"(",
"self",
".",
"get_endpoint",
"(",
")",
",",
"data",
"=",
"b\"cmd=_notify-validate&\"",
"+",
"self",
".",
"query",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
".",
"content"... | 62 | 0.015957 |
def raftery_lewis(x, q, r, s=.95, epsilon=.001, verbose=1):
"""
Return the number of iterations needed to achieve a given
precision.
:Parameters:
x : sequence
Sampled series.
q : float
Quantile.
r : float
Accuracy requested for quantile.
... | [
"def",
"raftery_lewis",
"(",
"x",
",",
"q",
",",
"r",
",",
"s",
"=",
".95",
",",
"epsilon",
"=",
".001",
",",
"verbose",
"=",
"1",
")",
":",
"if",
"np",
".",
"ndim",
"(",
"x",
")",
">",
"1",
":",
"return",
"[",
"raftery_lewis",
"(",
"y",
",",... | 35.5875 | 0.002392 |
def execute(self, query, args, consistency):
"""
Execute a CQL query against the server.
:param query: The CQL query to execute
:type query: str.
:param args: The arguments to substitute
:type args: dict.
:param consistency: The consistency level
:type ... | [
"def",
"execute",
"(",
"self",
",",
"query",
",",
"args",
",",
"consistency",
")",
":",
"prep_query",
"=",
"prepare",
"(",
"query",
",",
"args",
")",
"def",
"_execute",
"(",
"client",
")",
":",
"exec_d",
"=",
"client",
".",
"execute_cql3_query",
"(",
"... | 36.360656 | 0.001317 |
def create_cluster(
self,
parent,
cluster_id,
cluster,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a cluster within an instance.
Example:
>>>... | [
"def",
"create_cluster",
"(",
"self",
",",
"parent",
",",
"cluster_id",
",",
"cluster",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"m... | 41.607843 | 0.002301 |
def revert_timefactor(cls, values):
"""The inverse version of method |Parameter.apply_timefactor|.
See the explanations on method Parameter.apply_timefactor| to
understand the following examples:
.. testsetup::
>>> from hydpy import pub
>>> del pub.timegrids
... | [
"def",
"revert_timefactor",
"(",
"cls",
",",
"values",
")",
":",
"if",
"cls",
".",
"TIME",
"is",
"True",
":",
"return",
"values",
"/",
"cls",
".",
"get_timefactor",
"(",
")",
"if",
"cls",
".",
"TIME",
"is",
"False",
":",
"return",
"values",
"*",
"cls... | 27.75 | 0.002176 |
def _send(data):
"""Send data to the Clowder API.
:param data: Dictionary of API data
:type data: dict
"""
url = data.get('url', CLOWDER_API_URL)
_validate_data(data)
if api_key is not None:
data['api_key'] = api_key
if 'value' not in data:
data['value'] = data.get('s... | [
"def",
"_send",
"(",
"data",
")",
":",
"url",
"=",
"data",
".",
"get",
"(",
"'url'",
",",
"CLOWDER_API_URL",
")",
"_validate_data",
"(",
"data",
")",
"if",
"api_key",
"is",
"not",
"None",
":",
"data",
"[",
"'api_key'",
"]",
"=",
"api_key",
"if",
"'va... | 28.875 | 0.001047 |
def write_bytes(self, addr, buf):
"""Write many bytes to the specified device. buf is a bytearray"""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
self._select_device(addr)
self._device.write(buf) | [
"def",
"write_bytes",
"(",
"self",
",",
"addr",
",",
"buf",
")",
":",
"assert",
"self",
".",
"_device",
"is",
"not",
"None",
",",
"'Bus must be opened before operations are made against it!'",
"self",
".",
"_select_device",
"(",
"addr",
")",
"self",
".",
"_devic... | 54.2 | 0.010909 |
def _get_scheduler(get=None, collection=None):
"""Determine the dask scheduler that is being used.
None is returned if no dask scheduler is active.
See also
--------
dask.base.get_scheduler
"""
try:
# dask 0.18.1 and later
from dask.base import get_scheduler
actual_... | [
"def",
"_get_scheduler",
"(",
"get",
"=",
"None",
",",
"collection",
"=",
"None",
")",
":",
"try",
":",
"# dask 0.18.1 and later",
"from",
"dask",
".",
"base",
"import",
"get_scheduler",
"actual_get",
"=",
"get_scheduler",
"(",
"get",
",",
"collection",
")",
... | 29.030303 | 0.00101 |
def calculate_frequencies(data, ndim: int, binnings, weights=None, dtype=None) -> Tuple[np.ndarray, np.ndarray, float]:
""""Get frequencies and bin errors from the data (n-dimensional variant).
Parameters
----------
data : array_like
2D array with ndim columns and row for each entry.
ndim :... | [
"def",
"calculate_frequencies",
"(",
"data",
",",
"ndim",
":",
"int",
",",
"binnings",
",",
"weights",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
"->",
"Tuple",
"[",
"np",
".",
"ndarray",
",",
"np",
".",
"ndarray",
",",
"float",
"]",
":",
"# TODO: ... | 35.184211 | 0.002183 |
def set_stream_logger(log_level=logging.DEBUG, format_string=None, logger_name='smc'):
"""
Stream logger convenience function to log to console
:param int log_level: A log level as specified in the `logging` module
:param str format_string: Optional format string as specified in the
`log... | [
"def",
"set_stream_logger",
"(",
"log_level",
"=",
"logging",
".",
"DEBUG",
",",
"format_string",
"=",
"None",
",",
"logger_name",
"=",
"'smc'",
")",
":",
"if",
"format_string",
"is",
"None",
":",
"format_string",
"=",
"LOG_FORMAT",
"logger",
"=",
"logging",
... | 33.136364 | 0.017333 |
def _pinyin(words, style, heteronym, errors, strict=True):
"""
:param words: 经过分词处理后的字符串,只包含中文字符或只包含非中文字符,
不存在混合的情况。
"""
pys = []
# 初步过滤没有拼音的字符
if RE_HANS.match(words):
pys = phrase_pinyin(words, style=style, heteronym=heteronym,
errors=error... | [
"def",
"_pinyin",
"(",
"words",
",",
"style",
",",
"heteronym",
",",
"errors",
",",
"strict",
"=",
"True",
")",
":",
"pys",
"=",
"[",
"]",
"# 初步过滤没有拼音的字符",
"if",
"RE_HANS",
".",
"match",
"(",
"words",
")",
":",
"pys",
"=",
"phrase_pinyin",
"(",
"word... | 28.6875 | 0.00211 |
def resample(self, indexer: Optional[Mapping[Hashable, str]] = None,
skipna=None, closed: Optional[str] = None,
label: Optional[str] = None,
base: int = 0, keep_attrs: Optional[bool] = None,
loffset=None,
**indexer_kwargs: str):
... | [
"def",
"resample",
"(",
"self",
",",
"indexer",
":",
"Optional",
"[",
"Mapping",
"[",
"Hashable",
",",
"str",
"]",
"]",
"=",
"None",
",",
"skipna",
"=",
"None",
",",
"closed",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"label",
":",
"Optio... | 43.129032 | 0.001279 |
def mass(self,R,z=None,t=0.,forceint=False):
"""
NAME:
mass
PURPOSE:
evaluate the mass enclosed
INPUT:
R - Cylindrical Galactocentric radius (can be Quantity)
z= (None) vertical height (can be Quantity)
t - time (optional; can... | [
"def",
"mass",
"(",
"self",
",",
"R",
",",
"z",
"=",
"None",
",",
"t",
"=",
"0.",
",",
"forceint",
"=",
"False",
")",
":",
"if",
"self",
".",
"isNonAxi",
":",
"raise",
"NotImplementedError",
"(",
"'mass for non-axisymmetric potentials is not currently supporte... | 34.960784 | 0.016912 |
def color(cls, value):
"""task value/score color"""
index = bisect(cls.breakpoints, value)
return colors.fg(cls.colors_[index]) | [
"def",
"color",
"(",
"cls",
",",
"value",
")",
":",
"index",
"=",
"bisect",
"(",
"cls",
".",
"breakpoints",
",",
"value",
")",
"return",
"colors",
".",
"fg",
"(",
"cls",
".",
"colors_",
"[",
"index",
"]",
")"
] | 37 | 0.013245 |
def _handleRenderResult(self, request, result):
"""
Handle the result from `IResource.render`.
If the result is a `Deferred` then return `NOT_DONE_YET` and add
a callback to write the result to the request when it arrives.
"""
def _requestFinished(result, cancel):
... | [
"def",
"_handleRenderResult",
"(",
"self",
",",
"request",
",",
"result",
")",
":",
"def",
"_requestFinished",
"(",
"result",
",",
"cancel",
")",
":",
"cancel",
"(",
")",
"return",
"result",
"if",
"not",
"isinstance",
"(",
"result",
",",
"Deferred",
")",
... | 36.615385 | 0.002047 |
def next(self):
'''
Return the next iteration by popping `chunk_size` from the left and
appending `chunk_size` to the right if there's info on the file left
to be read.
'''
if self.__buffered is None:
# Use floor division to force multiplier to an integer
... | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"__buffered",
"is",
"None",
":",
"# Use floor division to force multiplier to an integer",
"multiplier",
"=",
"self",
".",
"__max_in_mem",
"//",
"self",
".",
"__chunk_size",
"self",
".",
"__buffered",
"=",
... | 36.153846 | 0.002073 |
def segmentlistdict_fromsearchsummary_in(xmldoc, program = None):
"""
Convenience wrapper for a common case usage of the segmentlistdict
class: searches the process table in xmldoc for occurances of a
program named program, then scans the search summary table for
matching process IDs and constructs a segmentlistd... | [
"def",
"segmentlistdict_fromsearchsummary_in",
"(",
"xmldoc",
",",
"program",
"=",
"None",
")",
":",
"stbl",
"=",
"lsctables",
".",
"SearchSummaryTable",
".",
"get_table",
"(",
"xmldoc",
")",
"ptbl",
"=",
"lsctables",
".",
"ProcessTable",
".",
"get_table",
"(",
... | 46.4 | 0.023944 |
def connection_from_promised_list(data_promise, args=None, **kwargs):
'''
A version of `connectionFromArray` that takes a promised array, and returns a
promised connection.
'''
return data_promise.then(lambda data: connection_from_list(data, args, **kwargs)) | [
"def",
"connection_from_promised_list",
"(",
"data_promise",
",",
"args",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"data_promise",
".",
"then",
"(",
"lambda",
"data",
":",
"connection_from_list",
"(",
"data",
",",
"args",
",",
"*",
"*",
"k... | 45.5 | 0.010791 |
def run_scan():
"""
show all available partitions
"""
all_disks = walk_data(sess, oid_hrStorageDescr, helper)[0]
print "All available disks at: " + host
for disk in all_disks:
print "Disk: \t'" + disk + "'"
quit() | [
"def",
"run_scan",
"(",
")",
":",
"all_disks",
"=",
"walk_data",
"(",
"sess",
",",
"oid_hrStorageDescr",
",",
"helper",
")",
"[",
"0",
"]",
"print",
"\"All available disks at: \"",
"+",
"host",
"for",
"disk",
"in",
"all_disks",
":",
"print",
"\"Disk: \\t'\"",
... | 25.7 | 0.011278 |
def centroid_2dg(data, error=None, mask=None):
"""
Calculate the centroid of a 2D array by fitting a 2D Gaussian (plus
a constant) to the array.
Invalid values (e.g. NaNs or infs) in the ``data`` or ``error``
arrays are automatically masked. The mask for invalid values
represents the combinati... | [
"def",
"centroid_2dg",
"(",
"data",
",",
"error",
"=",
"None",
",",
"mask",
"=",
"None",
")",
":",
"gfit",
"=",
"fit_2dgaussian",
"(",
"data",
",",
"error",
"=",
"error",
",",
"mask",
"=",
"mask",
")",
"return",
"np",
".",
"array",
"(",
"[",
"gfit"... | 30.967742 | 0.00101 |
def _check_params(self):
"""Check validity of parameters and raise ValueError if not valid. """
self.n_estimators = int(self.n_estimators)
if self.n_estimators <= 0:
raise ValueError("n_estimators must be greater than 0 but "
"was %r" % self.n_estimators)... | [
"def",
"_check_params",
"(",
"self",
")",
":",
"self",
".",
"n_estimators",
"=",
"int",
"(",
"self",
".",
"n_estimators",
")",
"if",
"self",
".",
"n_estimators",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"n_estimators must be greater than 0 but \"",
"\"was %... | 42.416667 | 0.00128 |
def keras_tuples(stream, inputs=None, outputs=None):
"""Reformat data objects as keras-compatible tuples.
For more detail: https://keras.io/models/model/#fit
Parameters
----------
stream : iterable
Stream of data objects.
inputs : string or iterable of strings, None
Keys to us... | [
"def",
"keras_tuples",
"(",
"stream",
",",
"inputs",
"=",
"None",
",",
"outputs",
"=",
"None",
")",
":",
"flatten_inputs",
",",
"flatten_outputs",
"=",
"False",
",",
"False",
"if",
"inputs",
"and",
"isinstance",
"(",
"inputs",
",",
"six",
".",
"string_type... | 33.65 | 0.000481 |
def batch(self, num):
"""
Iterator returning results in batches. When making more general queries
that might have larger results, specify a batch result that should be
returned with each iteration.
:param int num: number of results per iteration
:return: iterator... | [
"def",
"batch",
"(",
"self",
",",
"num",
")",
":",
"self",
".",
"_params",
".",
"pop",
"(",
"'limit'",
",",
"None",
")",
"# Limit and batch are mutually exclusive",
"it",
"=",
"iter",
"(",
"self",
")",
"while",
"True",
":",
"chunk",
"=",
"list",
"(",
"... | 36.3125 | 0.008389 |
def _getEphemeralMembers(self):
"""
List of our member variables that we don't need to be saved
"""
e = BacktrackingTM._getEphemeralMembers(self)
if self.makeCells4Ephemeral:
e.extend(['cells4'])
return e | [
"def",
"_getEphemeralMembers",
"(",
"self",
")",
":",
"e",
"=",
"BacktrackingTM",
".",
"_getEphemeralMembers",
"(",
"self",
")",
"if",
"self",
".",
"makeCells4Ephemeral",
":",
"e",
".",
"extend",
"(",
"[",
"'cells4'",
"]",
")",
"return",
"e"
] | 28.375 | 0.008547 |
def __search_text_check_convert(cls, text):
"""Converts and keeps only words in text deemed to be valid"""
text = cls.check_convert_string(text, name='text', no_leading_trailing_whitespace=False)
if len(text) > VALIDATION_META_SEARCH_TEXT:
raise ValueError("Search text can contain at... | [
"def",
"__search_text_check_convert",
"(",
"cls",
",",
"text",
")",
":",
"text",
"=",
"cls",
".",
"check_convert_string",
"(",
"text",
",",
"name",
"=",
"'text'",
",",
"no_leading_trailing_whitespace",
"=",
"False",
")",
"if",
"len",
"(",
"text",
")",
">",
... | 61.666667 | 0.008881 |
def compactor(conf):
"""
The compactor daemon. This fuction watches the sorted set
containing bucket keys that need to be compacted, performing the
necessary compaction.
:param conf: A turnstile.config.Config instance containing the
configuration for the compactor daemon. Note th... | [
"def",
"compactor",
"(",
"conf",
")",
":",
"# Get the database handle",
"db",
"=",
"conf",
".",
"get_database",
"(",
"'compactor'",
")",
"# Get the limits container",
"limit_map",
"=",
"LimitContainer",
"(",
"conf",
",",
"db",
")",
"# Get the compactor configuration",... | 34.367647 | 0.000416 |
def get_dependencies(requirement, sources):
"""Get all dependencies for a given install requirement.
:param requirement: A requirement
:param sources: Pipfile-formatted sources
:type sources: list[dict]
"""
getters = [
_get_dependencies_from_cache,
_cached(_get_dependencies_from... | [
"def",
"get_dependencies",
"(",
"requirement",
",",
"sources",
")",
":",
"getters",
"=",
"[",
"_get_dependencies_from_cache",
",",
"_cached",
"(",
"_get_dependencies_from_json",
",",
"sources",
"=",
"sources",
")",
",",
"_cached",
"(",
"_get_dependencies_from_pip",
... | 31.896552 | 0.001049 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.