text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def target_from_compact(bits):
"""\
Extract a full target from its compact representation, undoing the
transformation x=compact_from_target(t). See compact_from_target() for
more information on this 32-bit floating point format."""
size = bits >> 24
word = bits & 0x007fffff
if size < 3:
... | [
"def",
"target_from_compact",
"(",
"bits",
")",
":",
"size",
"=",
"bits",
">>",
"24",
"word",
"=",
"bits",
"&",
"0x007fffff",
"if",
"size",
"<",
"3",
":",
"word",
">>=",
"8",
"*",
"(",
"3",
"-",
"size",
")",
"else",
":",
"word",
"<<=",
"8",
"*",
... | 31.357143 | 0.002212 |
def is_integer(value,
coerce_value = False,
minimum = None,
maximum = None,
base = 10,
**kwargs):
"""Indicate whether ``value`` contains a whole number.
:param value: The value to evaluate.
:param coerce_value: If ``True``, will re... | [
"def",
"is_integer",
"(",
"value",
",",
"coerce_value",
"=",
"False",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
",",
"base",
"=",
"10",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"integer",
"(",
... | 38.078431 | 0.011546 |
def _create_model(self, X, Y):
"""
Creates the model given some input data X and Y.
"""
from sklearn.ensemble import RandomForestRegressor
self.X = X
self.Y = Y
self.model = RandomForestRegressor(bootstrap = self.bootstrap,
... | [
"def",
"_create_model",
"(",
"self",
",",
"X",
",",
"Y",
")",
":",
"from",
"sklearn",
".",
"ensemble",
"import",
"RandomForestRegressor",
"self",
".",
"X",
"=",
"X",
"self",
".",
"Y",
"=",
"Y",
"self",
".",
"model",
"=",
"RandomForestRegressor",
"(",
"... | 56 | 0.026335 |
def calculate_current_allocation(self):
""" Calculates the current allocation % based on the value """
for ac in self.asset_classes:
ac.curr_alloc = ac.curr_value * 100 / self.total_amount | [
"def",
"calculate_current_allocation",
"(",
"self",
")",
":",
"for",
"ac",
"in",
"self",
".",
"asset_classes",
":",
"ac",
".",
"curr_alloc",
"=",
"ac",
".",
"curr_value",
"*",
"100",
"/",
"self",
".",
"total_amount"
] | 53.25 | 0.009259 |
def _run_apps(self, paths):
""" Runs apps for the provided paths.
"""
for path in paths:
common.shell_process(path, background=True)
time.sleep(0.2) | [
"def",
"_run_apps",
"(",
"self",
",",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"common",
".",
"shell_process",
"(",
"path",
",",
"background",
"=",
"True",
")",
"time",
".",
"sleep",
"(",
"0.2",
")"
] | 27.857143 | 0.00995 |
def transmissions(self, direction="outgoing", status="all", failed=False):
"""Get transmissions sent to or from this node.
Direction can be "all", "incoming" or "outgoing" (default).
Status can be "all" (default), "pending", or "received".
failed can be True, False or "all"
"""
... | [
"def",
"transmissions",
"(",
"self",
",",
"direction",
"=",
"\"outgoing\"",
",",
"status",
"=",
"\"all\"",
",",
"failed",
"=",
"False",
")",
":",
"# check parameters",
"if",
"direction",
"not",
"in",
"[",
"\"incoming\"",
",",
"\"outgoing\"",
",",
"\"all\"",
... | 45.40678 | 0.002192 |
def additional_files(self):
"""Get a list of absolute paths to the additional config files."""
return [os.path.join(f, self.filename) for f in self.additional_dirs] | [
"def",
"additional_files",
"(",
"self",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"f",
",",
"self",
".",
"filename",
")",
"for",
"f",
"in",
"self",
".",
"additional_dirs",
"]"
] | 59.333333 | 0.011111 |
def channels_create(self, name, **kwargs):
"""Creates a new public channel, optionally including users."""
return self.__call_api_post('channels.create', name=name, kwargs=kwargs) | [
"def",
"channels_create",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'channels.create'",
",",
"name",
"=",
"name",
",",
"kwargs",
"=",
"kwargs",
")"
] | 64.333333 | 0.015385 |
def bootstrap(v):
"""
Constructs Monte Carlo simulated data set using the
Bootstrap algorithm.
Usage:
>>> bootstrap(x)
where x is either an array or a list of arrays. If it is a
list, the code returns the corresponding list of bootst... | [
"def",
"bootstrap",
"(",
"v",
")",
":",
"if",
"type",
"(",
"v",
")",
"==",
"list",
":",
"vboot",
"=",
"[",
"]",
"# list of boostrapped arrays",
"n",
"=",
"v",
"[",
"0",
"]",
".",
"size",
"iran",
"=",
"scipy",
".",
"random",
".",
"randint",
"(",
"... | 27.888889 | 0.043646 |
def prune(self, dir):
"""Filter out files from 'dir/'."""
match = translate_pattern(os.path.join(dir, '**'))
return self._remove_files(match.match) | [
"def",
"prune",
"(",
"self",
",",
"dir",
")",
":",
"match",
"=",
"translate_pattern",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"'**'",
")",
")",
"return",
"self",
".",
"_remove_files",
"(",
"match",
".",
"match",
")"
] | 42 | 0.011696 |
def _evaluate_selection_mask(self, name="default", i1=None, i2=None, selection=None, cache=False):
"""Internal use, ignores the filter"""
i1 = i1 or 0
i2 = i2 or len(self)
scope = scopes._BlockScopeSelection(self, i1, i2, selection, cache=cache)
return scope.evaluate(name) | [
"def",
"_evaluate_selection_mask",
"(",
"self",
",",
"name",
"=",
"\"default\"",
",",
"i1",
"=",
"None",
",",
"i2",
"=",
"None",
",",
"selection",
"=",
"None",
",",
"cache",
"=",
"False",
")",
":",
"i1",
"=",
"i1",
"or",
"0",
"i2",
"=",
"i2",
"or",... | 51.333333 | 0.01278 |
def _get_channels(self):
"""
获取channel列表
"""
self._channel_list = [
# {'name': '红心兆赫', 'channel_id': -3},
{'name': '我的私人兆赫', 'channel_id': 0},
{'name': '每日私人歌单', 'channel_id': -2},
{'name': '豆瓣精选兆赫', 'channel_id': -10},
# 心情 / 场... | [
"def",
"_get_channels",
"(",
"self",
")",
":",
"self",
".",
"_channel_list",
"=",
"[",
"# {'name': '红心兆赫', 'channel_id': -3},",
"{",
"'name'",
":",
"'我的私人兆赫', 'channel_i",
"d",
": 0},",
"",
"",
"",
"",
"{",
"'name'",
":",
"'每日私人歌单', 'channel_i",
"d",
": -2},",
... | 40.553191 | 0.001025 |
def btc_make_p2sh_address( script_hex ):
"""
Make a P2SH address from a hex script
"""
h = hashing.bin_hash160(binascii.unhexlify(script_hex))
addr = bin_hash160_to_address(h, version_byte=multisig_version_byte)
return addr | [
"def",
"btc_make_p2sh_address",
"(",
"script_hex",
")",
":",
"h",
"=",
"hashing",
".",
"bin_hash160",
"(",
"binascii",
".",
"unhexlify",
"(",
"script_hex",
")",
")",
"addr",
"=",
"bin_hash160_to_address",
"(",
"h",
",",
"version_byte",
"=",
"multisig_version_byt... | 34.428571 | 0.012146 |
def extend_node_list(acc, new):
"""Extend accumulator with Node(s) from new"""
if new is None:
new = []
elif not isinstance(new, list):
new = [new]
return acc + new | [
"def",
"extend_node_list",
"(",
"acc",
",",
"new",
")",
":",
"if",
"new",
"is",
"None",
":",
"new",
"=",
"[",
"]",
"elif",
"not",
"isinstance",
"(",
"new",
",",
"list",
")",
":",
"new",
"=",
"[",
"new",
"]",
"return",
"acc",
"+",
"new"
] | 30.571429 | 0.009091 |
def update(self, virtual_interfaces):
"""
Method to update Virtual Interfaces
:param Virtual Interfaces: List containing Virtual Interfaces desired to updated
:return: None
"""
data = {'virtual_interfaces': virtual_interfaces}
virtual_interfaces_ids = [str(env.g... | [
"def",
"update",
"(",
"self",
",",
"virtual_interfaces",
")",
":",
"data",
"=",
"{",
"'virtual_interfaces'",
":",
"virtual_interfaces",
"}",
"virtual_interfaces_ids",
"=",
"[",
"str",
"(",
"env",
".",
"get",
"(",
"'id'",
")",
")",
"for",
"env",
"in",
"virt... | 37.692308 | 0.011952 |
def _compute(self):
"""
The main method of the class, which computes an MCS given its
over-approximation. The over-approximation is defined by a model
for the hard part of the formula obtained in :func:`compute`.
The method is essentially a simple loop going over... | [
"def",
"_compute",
"(",
"self",
")",
":",
"# unless clause D checks are used, test one literal at a time",
"# and add it either to satisfied of backbone assumptions",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"self",
".",
"setd",
")",
":",
"if",
"self",
".",
"ucld... | 44.891892 | 0.001768 |
def next_update(self):
"""Compute the next expected update date,
given the frequency and last_update.
Return None if the frequency is not handled.
"""
delta = None
if self.frequency == 'daily':
delta = timedelta(days=1)
elif self.frequency == 'weekly'... | [
"def",
"next_update",
"(",
"self",
")",
":",
"delta",
"=",
"None",
"if",
"self",
".",
"frequency",
"==",
"'daily'",
":",
"delta",
"=",
"timedelta",
"(",
"days",
"=",
"1",
")",
"elif",
"self",
".",
"frequency",
"==",
"'weekly'",
":",
"delta",
"=",
"ti... | 36.515152 | 0.001617 |
def _check_pwm_list(pwm_list):
"""Check the input validity
"""
for pwm in pwm_list:
if not isinstance(pwm, PWM):
raise TypeError("element {0} of pwm_list is not of type PWM".format(pwm))
return True | [
"def",
"_check_pwm_list",
"(",
"pwm_list",
")",
":",
"for",
"pwm",
"in",
"pwm_list",
":",
"if",
"not",
"isinstance",
"(",
"pwm",
",",
"PWM",
")",
":",
"raise",
"TypeError",
"(",
"\"element {0} of pwm_list is not of type PWM\"",
".",
"format",
"(",
"pwm",
")",
... | 32.571429 | 0.008547 |
def mark_locations(h,section,locs,markspec='or',**kwargs):
"""
Marks one or more locations on along a section. Could be used to
mark the location of a recording or electrical stimulation.
Args:
h = hocObject to interface with neuron
section = reference to section
locs = float be... | [
"def",
"mark_locations",
"(",
"h",
",",
"section",
",",
"locs",
",",
"markspec",
"=",
"'or'",
",",
"*",
"*",
"kwargs",
")",
":",
"# get list of cartesian coordinates specifying section path",
"xyz",
"=",
"get_section_path",
"(",
"h",
",",
"section",
")",
"(",
... | 32.675676 | 0.013655 |
def find_command(cmd, path=None, pathext=None):
"""
Taken `from Django http://bit.ly/1njB3Y9>`_.
"""
if path is None:
path = os.environ.get('PATH', '').split(os.pathsep)
if isinstance(path, string_types):
path = [path]
# check if there are path extensions for Windows executables... | [
"def",
"find_command",
"(",
"cmd",
",",
"path",
"=",
"None",
",",
"pathext",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
",",
"''",
")",
".",
"split",
"(",
"os",
".",
"pa... | 29.1 | 0.001109 |
def get_max_drawdown_underwater(underwater):
"""
Determines peak, valley, and recovery dates given an 'underwater'
DataFrame.
An underwater DataFrame is a DataFrame that has precomputed
rolling drawdown.
Parameters
----------
underwater : pd.Series
Underwater returns (rolling dr... | [
"def",
"get_max_drawdown_underwater",
"(",
"underwater",
")",
":",
"valley",
"=",
"np",
".",
"argmin",
"(",
"underwater",
")",
"# end of the period",
"# Find first 0",
"peak",
"=",
"underwater",
"[",
":",
"valley",
"]",
"[",
"underwater",
"[",
":",
"valley",
"... | 27.5 | 0.001098 |
def insert_column(self, name, data, colnum=None):
"""
Insert a new column.
parameters
----------
name: string
The column name
data:
The data to write into the new column.
colnum: int, optional
The column number for the new colu... | [
"def",
"insert_column",
"(",
"self",
",",
"name",
",",
"data",
",",
"colnum",
"=",
"None",
")",
":",
"if",
"name",
"in",
"self",
".",
"_colnames",
":",
"raise",
"ValueError",
"(",
"\"column '%s' already exists\"",
"%",
"name",
")",
"if",
"IS_PY3",
"and",
... | 32.196429 | 0.001076 |
def with_column(self, label, values, *rest):
"""Return a new table with an additional or replaced column.
Args:
``label`` (str): The column label. If an existing label is used,
the existing column will be replaced in the new table.
``values`` (single value or se... | [
"def",
"with_column",
"(",
"self",
",",
"label",
",",
"values",
",",
"*",
"rest",
")",
":",
"# Ensure that if with_column is called instead of with_columns;",
"# no error is raised.",
"if",
"rest",
":",
"return",
"self",
".",
"with_columns",
"(",
"label",
",",
"valu... | 37.79661 | 0.001311 |
def get_tokenizer(fhp # type: Optional[field_formats.FieldHashingProperties]
):
# type: (...) -> Callable[[Text, Optional[Text]], Iterable[Text]]
""" Get tokeniser function from the hash settings.
This function takes a FieldHashingProperties object. It returns a
function that... | [
"def",
"get_tokenizer",
"(",
"fhp",
"# type: Optional[field_formats.FieldHashingProperties]",
")",
":",
"# type: (...) -> Callable[[Text, Optional[Text]], Iterable[Text]]",
"def",
"dummy",
"(",
"word",
",",
"ignore",
"=",
"None",
")",
":",
"# type: (Text, Optional[Text]) -> Itera... | 32.309091 | 0.000546 |
async def get_codec(self):
"""Get codec settings."""
act = self.service.action("X_GetCodec")
res = await act.async_call()
return res | [
"async",
"def",
"get_codec",
"(",
"self",
")",
":",
"act",
"=",
"self",
".",
"service",
".",
"action",
"(",
"\"X_GetCodec\"",
")",
"res",
"=",
"await",
"act",
".",
"async_call",
"(",
")",
"return",
"res"
] | 32 | 0.012195 |
def _pastorestr(ins):
''' Stores a string value into a memory address.
It copies content of 2nd operand (string), into 1st, reallocating
dynamic memory for the 1st str. These instruction DOES ALLOW
inmediate strings for the 2nd parameter, starting with '#'.
'''
output = _paddr(ins.quad[1])
t... | [
"def",
"_pastorestr",
"(",
"ins",
")",
":",
"output",
"=",
"_paddr",
"(",
"ins",
".",
"quad",
"[",
"1",
"]",
")",
"temporal",
"=",
"False",
"value",
"=",
"ins",
".",
"quad",
"[",
"2",
"]",
"indirect",
"=",
"value",
"[",
"0",
"]",
"==",
"'*'",
"... | 28.340426 | 0.000726 |
def process_raw_data(cls, raw_data):
"""Create a new model using raw API response."""
properties = raw_data["properties"]
raw_content = properties.get("addressSpace", None)
if raw_content is not None:
address_space = AddressSpace.from_raw_data(raw_content)
proper... | [
"def",
"process_raw_data",
"(",
"cls",
",",
"raw_data",
")",
":",
"properties",
"=",
"raw_data",
"[",
"\"properties\"",
"]",
"raw_content",
"=",
"properties",
".",
"get",
"(",
"\"addressSpace\"",
",",
"None",
")",
"if",
"raw_content",
"is",
"not",
"None",
":... | 42.12 | 0.001857 |
def invoke(stage, async, dry_run, config_file, args):
"""Invoke the lambda function."""
config = _load_config(config_file)
if stage is None:
stage = config['devstage']
cfn = boto3.client('cloudformation')
lmb = boto3.client('lambda')
try:
stack = cfn.describe_stacks(StackName=c... | [
"def",
"invoke",
"(",
"stage",
",",
"async",
",",
"dry_run",
",",
"config_file",
",",
"args",
")",
":",
"config",
"=",
"_load_config",
"(",
"config_file",
")",
"if",
"stage",
"is",
"None",
":",
"stage",
"=",
"config",
"[",
"'devstage'",
"]",
"cfn",
"="... | 36.232143 | 0.00144 |
def iter_open(cls, name=None, interface_class=None, interface_subclass=None,
interface_protocol=None, serial_number=None, port_path=None,
default_timeout_ms=None):
"""Find and yield locally connected devices that match.
Note that devices are opened (and interfaces claimd) as the... | [
"def",
"iter_open",
"(",
"cls",
",",
"name",
"=",
"None",
",",
"interface_class",
"=",
"None",
",",
"interface_subclass",
"=",
"None",
",",
"interface_protocol",
"=",
"None",
",",
"serial_number",
"=",
"None",
",",
"port_path",
"=",
"None",
",",
"default_tim... | 38.5 | 0.008442 |
def camel2snake(name:str)->str:
"Change `name` from camel to snake style."
s1 = re.sub(_camel_re1, r'\1_\2', name)
return re.sub(_camel_re2, r'\1_\2', s1).lower() | [
"def",
"camel2snake",
"(",
"name",
":",
"str",
")",
"->",
"str",
":",
"s1",
"=",
"re",
".",
"sub",
"(",
"_camel_re1",
",",
"r'\\1_\\2'",
",",
"name",
")",
"return",
"re",
".",
"sub",
"(",
"_camel_re2",
",",
"r'\\1_\\2'",
",",
"s1",
")",
".",
"lower... | 42.75 | 0.017241 |
def get_ratings(self):
"""get_ratings()
Returns a Vote QuerySet for this rating field."""
return Vote.objects.filter(content_type=self.get_content_type(), object_id=self.instance.pk, key=self.field.key) | [
"def",
"get_ratings",
"(",
"self",
")",
":",
"return",
"Vote",
".",
"objects",
".",
"filter",
"(",
"content_type",
"=",
"self",
".",
"get_content_type",
"(",
")",
",",
"object_id",
"=",
"self",
".",
"instance",
".",
"pk",
",",
"key",
"=",
"self",
".",
... | 46.2 | 0.017021 |
def get_default_recipients(self):
''' Overrides EmailRecipientMixin '''
if self.email:
return [self.email,]
if self.finalRegistration:
return [self.finalRegistration.customer.email,]
elif self.temporaryRegistration:
return [self.temporaryRegistration.e... | [
"def",
"get_default_recipients",
"(",
"self",
")",
":",
"if",
"self",
".",
"email",
":",
"return",
"[",
"self",
".",
"email",
",",
"]",
"if",
"self",
".",
"finalRegistration",
":",
"return",
"[",
"self",
".",
"finalRegistration",
".",
"customer",
".",
"e... | 37.333333 | 0.014535 |
def _get_valid_formats():
''' Calls SoX help for a lists of audio formats available with the current
install of SoX.
Returns:
--------
formats : list
List of audio file extensions that SoX can process.
'''
if NO_SOX:
return []
so = subprocess.check_output(['sox', '-h']... | [
"def",
"_get_valid_formats",
"(",
")",
":",
"if",
"NO_SOX",
":",
"return",
"[",
"]",
"so",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'sox'",
",",
"'-h'",
"]",
")",
"if",
"type",
"(",
"so",
")",
"is",
"not",
"str",
":",
"so",
"=",
"str",
... | 24.952381 | 0.001838 |
def func_info(task, n_runs, metadata, img, config):
"""
Generate a paragraph describing T2*-weighted functional scans.
Parameters
----------
task : :obj:`str`
The name of the task.
n_runs : :obj:`int`
The number of runs acquired for this task.
metadata : :obj:`dict`
... | [
"def",
"func_info",
"(",
"task",
",",
"n_runs",
",",
"metadata",
",",
"img",
",",
"config",
")",
":",
"if",
"metadata",
".",
"get",
"(",
"'MultibandAccelerationFactor'",
",",
"1",
")",
">",
"1",
":",
"mb_str",
"=",
"'; MB factor={}'",
".",
"format",
"(",... | 34.676768 | 0.001133 |
def call_actions(self, event, *args, **kwargs):
"""Call each function in self._actions after setting self._event."""
self._event = event
for func in self._actions:
func(event, *args, **kwargs) | [
"def",
"call_actions",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_event",
"=",
"event",
"for",
"func",
"in",
"self",
".",
"_actions",
":",
"func",
"(",
"event",
",",
"*",
"args",
",",
"*",
"*",
... | 37.333333 | 0.008734 |
def _get_uncertainties(self, star_group_size):
"""
Retrieve uncertainties on fitted parameters from the fitter
object.
Parameters
----------
star_group_size : int
Number of stars in the given group.
Returns
-------
unc_tab : `~astropy... | [
"def",
"_get_uncertainties",
"(",
"self",
",",
"star_group_size",
")",
":",
"unc_tab",
"=",
"Table",
"(",
")",
"for",
"param_name",
"in",
"self",
".",
"psf_model",
".",
"param_names",
":",
"if",
"not",
"self",
".",
"psf_model",
".",
"fixed",
"[",
"param_na... | 37.272727 | 0.001585 |
def disconnect(self):
"""
disconnect a client.
"""
logger.info("disconnecting snap7 client")
result = self.library.Cli_Disconnect(self.pointer)
check_error(result, context="client")
return result | [
"def",
"disconnect",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"disconnecting snap7 client\"",
")",
"result",
"=",
"self",
".",
"library",
".",
"Cli_Disconnect",
"(",
"self",
".",
"pointer",
")",
"check_error",
"(",
"result",
",",
"context",
"=",
... | 30.625 | 0.011905 |
def fit(self, X, y, num_training_samples=None):
"""Use correlation data to train a model.
First compute the correlation of the input data,
and then normalize within subject
if more than one sample in one subject,
and then fit to a model defined by self.clf.
Parameters
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"num_training_samples",
"=",
"None",
")",
":",
"time1",
"=",
"time",
".",
"time",
"(",
")",
"assert",
"len",
"(",
"X",
")",
"==",
"len",
"(",
"y",
")",
",",
"'the number of samples must be equal to th... | 39.962025 | 0.000618 |
def execute_command(command):
"""Execute a command and return its output"""
command = shlex.split(command)
try:
process = subprocess.Popen(
command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except FileNotFou... | [
"def",
"execute_command",
"(",
"command",
")",
":",
"command",
"=",
"shlex",
".",
"split",
"(",
"command",
")",
"try",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"s... | 34.684211 | 0.001477 |
def _extract_phot_from_exposure(
expIdIndex,
log,
cachePath,
settings):
"""* extract phot from exposure*
**Key Arguments:**
- ``expIdIndex`` -- index of the exposure to extract the dophot photometry from. A tuple of expId and integer MJD
- ``cachePath`` -- path t... | [
"def",
"_extract_phot_from_exposure",
"(",
"expIdIndex",
",",
"log",
",",
"cachePath",
",",
"settings",
")",
":",
"log",
".",
"info",
"(",
"'starting the ``_extract_phot_from_exposure`` method'",
")",
"global",
"exposureIds",
"expId",
"=",
"exposureIds",
"[",
"expIdIn... | 27.076503 | 0.001168 |
async def github_request(session, api_token,
query=None, mutation=None, variables=None):
"""Send a request to the GitHub v4 (GraphQL) API.
The request is asynchronous, with asyncio.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp ... | [
"async",
"def",
"github_request",
"(",
"session",
",",
"api_token",
",",
"query",
"=",
"None",
",",
"mutation",
"=",
"None",
",",
"variables",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"}",
"if",
"query",
"is",
"not",
"None",
":",
"payload",
"[",
"... | 36.520833 | 0.000556 |
def ProcessNewBlock(self, block):
"""
Processes a block on the blockchain. This should be done in a sequential order, ie block 4 should be
only processed after block 3.
Args:
block: (neo.Core.Block) a block on the blockchain.
"""
added = set()
change... | [
"def",
"ProcessNewBlock",
"(",
"self",
",",
"block",
")",
":",
"added",
"=",
"set",
"(",
")",
"changed",
"=",
"set",
"(",
")",
"deleted",
"=",
"set",
"(",
")",
"try",
":",
"# go through the list of transactions in the block and enumerate",
"# over their outputs",
... | 41.320988 | 0.002334 |
def open_file(default_dir='~', extensions=None,
title='Choose a file', multiple_files=False, directory=False):
'''Start the native file dialog for opening file(s).
Starts the system native file dialog in order to open a file (or multiple files).
The toolkit used for each platform:
+-------------------------... | [
"def",
"open_file",
"(",
"default_dir",
"=",
"'~'",
",",
"extensions",
"=",
"None",
",",
"title",
"=",
"'Choose a file'",
",",
"multiple_files",
"=",
"False",
",",
"directory",
"=",
"False",
")",
":",
"default_dir",
"=",
"os",
".",
"path",
".",
"expanduser... | 24.803493 | 0.030636 |
def add(self, num_iid, properties, quantity, price, session, outer_id=None, item_price=None, lang=None):
'''taobao.item.sku.add 添加SKU
新增一个sku到num_iid指定的商品中 传入的iid所对应的商品必须属于当前会话的用户'''
request = TOPRequest('taobao.item.sku.add')
request['num_iid'] = num_iid
request['proper... | [
"def",
"add",
"(",
"self",
",",
"num_iid",
",",
"properties",
",",
"quantity",
",",
"price",
",",
"session",
",",
"outer_id",
"=",
"None",
",",
"item_price",
"=",
"None",
",",
"lang",
"=",
"None",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.i... | 39.882353 | 0.014409 |
def maximum_hline_bundle(self, y0, x0, x1):
"""Compute a maximum set of horizontal lines in the unit cells ``(x,y0)``
for :math:`x0 \leq x \leq x1`.
INPUTS:
y0,x0,x1: int
OUTPUT:
list of lists of qubits
"""
x_range = range(x0, x1 + 1) if x0 < x1 ... | [
"def",
"maximum_hline_bundle",
"(",
"self",
",",
"y0",
",",
"x0",
",",
"x1",
")",
":",
"x_range",
"=",
"range",
"(",
"x0",
",",
"x1",
"+",
"1",
")",
"if",
"x0",
"<",
"x1",
"else",
"range",
"(",
"x0",
",",
"x1",
"-",
"1",
",",
"-",
"1",
")",
... | 35.846154 | 0.01046 |
def type_list(signature, doc, header):
"""
Construct a list of types, preferring type annotations to
docstrings if they are available.
Parameters
----------
signature : Signature
Signature of thing
doc : list of tuple
Numpydoc's type list section
Returns
-------
... | [
"def",
"type_list",
"(",
"signature",
",",
"doc",
",",
"header",
")",
":",
"lines",
"=",
"[",
"]",
"docced",
"=",
"set",
"(",
")",
"lines",
".",
"append",
"(",
"header",
")",
"try",
":",
"for",
"names",
",",
"types",
",",
"description",
"in",
"doc"... | 36.295082 | 0.00044 |
def transpose(self, *args, **kwargs):
"""
Transpose index and columns.
Reflect the DataFrame over its main diagonal by writing rows as columns
and vice-versa. The property :attr:`.T` is an accessor to the method
:meth:`transpose`.
Parameters
----------
c... | [
"def",
"transpose",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nv",
".",
"validate_transpose",
"(",
"args",
",",
"dict",
"(",
")",
")",
"return",
"super",
"(",
")",
".",
"transpose",
"(",
"1",
",",
"0",
",",
"*",
"*",
"k... | 27.835052 | 0.000715 |
def get_as_map(self, key):
"""
Converts map element into an AnyValueMap or returns empty AnyValueMap if conversion is not possible.
:param key: a key of element to get.
:return: AnyValueMap value of the element or empty AnyValueMap if conversion is not supported.
"""
if... | [
"def",
"get_as_map",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"==",
"None",
":",
"map",
"=",
"{",
"}",
"for",
"(",
"k",
",",
"v",
")",
"in",
"self",
".",
"items",
"(",
")",
":",
"map",
"[",
"k",
"]",
"=",
"v",
"return",
"map",
"else"... | 32.6875 | 0.009294 |
def get_link_or_none(pattern_name, request, view_kwargs=None):
"""
Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL.
If not None is returned.
Args:
pattern_name (str): slug which is used for view registratin to pattern
req... | [
"def",
"get_link_or_none",
"(",
"pattern_name",
",",
"request",
",",
"view_kwargs",
"=",
"None",
")",
":",
"from",
"is_core",
".",
"patterns",
"import",
"reverse_pattern",
"pattern",
"=",
"reverse_pattern",
"(",
"pattern_name",
")",
"assert",
"pattern",
"is",
"n... | 36.454545 | 0.00243 |
def stream(self, handler, whenDone=None):
"""
Fetches data from river streams and feeds them into the given function.
:param handler: (function) passed headers [list] and row [list] of the data
for one time step, for every row of data
"""
self._createConfluence()
headers = ["... | [
"def",
"stream",
"(",
"self",
",",
"handler",
",",
"whenDone",
"=",
"None",
")",
":",
"self",
".",
"_createConfluence",
"(",
")",
"headers",
"=",
"[",
"\"timestamp\"",
"]",
"+",
"self",
".",
"getStreamIds",
"(",
")",
"for",
"row",
"in",
"self",
".",
... | 35.384615 | 0.008475 |
def blum_blum_shub(seed, amount, prime0, prime1):
"""Creates pseudo-number generator
:param seed: seeder
:param amount: amount of number to generate
:param prime0: one prime number
:param prime1: the second prime number
:return: pseudo-number generator
"""
if amount == 0:
return... | [
"def",
"blum_blum_shub",
"(",
"seed",
",",
"amount",
",",
"prime0",
",",
"prime1",
")",
":",
"if",
"amount",
"==",
"0",
":",
"return",
"[",
"]",
"assert",
"(",
"prime0",
"%",
"4",
"==",
"3",
"and",
"prime1",
"%",
"4",
"==",
"3",
")",
"# primes must... | 25.375 | 0.001582 |
def unregisterView(viewType, location='Central'):
"""
Unregisteres the given view type from the inputed location.
:param viewType | <subclass of XView>
"""
XView._registry.get(location, {}).pop(viewType.viewName(), None)
XView.dispatch(location).emit('unregi... | [
"def",
"unregisterView",
"(",
"viewType",
",",
"location",
"=",
"'Central'",
")",
":",
"XView",
".",
"_registry",
".",
"get",
"(",
"location",
",",
"{",
"}",
")",
".",
"pop",
"(",
"viewType",
".",
"viewName",
"(",
")",
",",
"None",
")",
"XView",
".",... | 43.125 | 0.008523 |
def eagle(args):
"""
%prog eagle fastafile
"""
p = OptionParser(eagle.__doc__)
p.add_option("--share", default="/usr/local/share/EAGLE/",
help="Default EAGLE share path")
add_sim_options(p)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print... | [
"def",
"eagle",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"eagle",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--share\"",
",",
"default",
"=",
"\"/usr/local/share/EAGLE/\"",
",",
"help",
"=",
"\"Default EAGLE share path\"",
")",
"add_sim_... | 37.103093 | 0.002436 |
def _get_tns_search_results(
self):
"""
*query the tns and result the response*
"""
self.log.info('starting the ``_get_tns_search_results`` method')
try:
response = requests.get(
url="http://wis-tns.weizmann.ac.il/search",
... | [
"def",
"_get_tns_search_results",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_get_tns_search_results`` method'",
")",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"\"http://wis-tns.weizmann.ac.il/search\"",
... | 38.875 | 0.001255 |
def main(args,parser,subparser):
'''the list command corresponds with listing images for an external
resource. This is different from listing images that are local to the
database, which should be done with "images"
'''
from sregistry.main import get_client
cli = get_client(quiet=args.quie... | [
"def",
"main",
"(",
"args",
",",
"parser",
",",
"subparser",
")",
":",
"from",
"sregistry",
".",
"main",
"import",
"get_client",
"cli",
"=",
"get_client",
"(",
"quiet",
"=",
"args",
".",
"quiet",
")",
"for",
"query",
"in",
"args",
".",
"query",
":",
... | 32.923077 | 0.011364 |
def get_proxies():
"""Get available proxies to use with requests library."""
proxies = getproxies()
filtered_proxies = {}
for key, value in proxies.items():
if key.startswith('http://'):
if not value.startswith('http://'):
filtered_proxies[key] = 'http://{0}'.format(v... | [
"def",
"get_proxies",
"(",
")",
":",
"proxies",
"=",
"getproxies",
"(",
")",
"filtered_proxies",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"proxies",
".",
"items",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"'http://'",
")",
":",
"if"... | 37 | 0.002398 |
def update_indel(self, nucmer_snp):
'''Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False'''
new_v... | [
"def",
"update_indel",
"(",
"self",
",",
"nucmer_snp",
")",
":",
"new_variant",
"=",
"Variant",
"(",
"nucmer_snp",
")",
"if",
"self",
".",
"var_type",
"not",
"in",
"[",
"INS",
",",
"DEL",
"]",
"or",
"self",
".",
"var_type",
"!=",
"new_variant",
".",
"v... | 49.086957 | 0.009557 |
def update(self, list_id, segment_id, data):
"""
updates an existing list segment.
"""
return self._mc_client._patch(url=self._build_path(list_id, 'segments', segment_id), data=data) | [
"def",
"update",
"(",
"self",
",",
"list_id",
",",
"segment_id",
",",
"data",
")",
":",
"return",
"self",
".",
"_mc_client",
".",
"_patch",
"(",
"url",
"=",
"self",
".",
"_build_path",
"(",
"list_id",
",",
"'segments'",
",",
"segment_id",
")",
",",
"da... | 42 | 0.014019 |
def run_interrupted(self):
"""
Runs custodian in a interuppted mode, which sets up and
validates jobs but doesn't run the executable
Returns:
number of remaining jobs
Raises:
ValidationError: if a job fails validation
ReturnCodeError: if the ... | [
"def",
"run_interrupted",
"(",
"self",
")",
":",
"start",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"try",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"v",
"=",
"sys",
".",
"version",
".",
"replace",
"(",
"\"\\n\"",
",",
"\" \"",
... | 43.5 | 0.000624 |
def reverb(self,
reverberance=50,
hf_damping=50,
room_scale=100,
stereo_depth=100,
pre_delay=20,
wet_gain=0,
wet_only=False):
"""reverb takes 7 parameters: reverberance, high-freqnency damping,
room ... | [
"def",
"reverb",
"(",
"self",
",",
"reverberance",
"=",
"50",
",",
"hf_damping",
"=",
"50",
",",
"room_scale",
"=",
"100",
",",
"stereo_depth",
"=",
"100",
",",
"pre_delay",
"=",
"20",
",",
"wet_gain",
"=",
"0",
",",
"wet_only",
"=",
"False",
")",
":... | 35.190476 | 0.011858 |
def _init_idxs_float(self, usr_hdrs):
"""List of indexes whose values will be floats."""
self.idxs_float = [
Idx for Hdr, Idx in self.hdr2idx.items() if Hdr in usr_hdrs and Hdr in self.float_hdrs] | [
"def",
"_init_idxs_float",
"(",
"self",
",",
"usr_hdrs",
")",
":",
"self",
".",
"idxs_float",
"=",
"[",
"Idx",
"for",
"Hdr",
",",
"Idx",
"in",
"self",
".",
"hdr2idx",
".",
"items",
"(",
")",
"if",
"Hdr",
"in",
"usr_hdrs",
"and",
"Hdr",
"in",
"self",
... | 55.25 | 0.013393 |
def is_opposite(self, ns1, id1, ns2, id2):
"""Return True if two entities are in an "is_opposite" relationship
Parameters
----------
ns1 : str
Namespace code for an entity.
id1 : str
URI for an entity.
ns2 : str
Namespace code for an e... | [
"def",
"is_opposite",
"(",
"self",
",",
"ns1",
",",
"id1",
",",
"ns2",
",",
"id2",
")",
":",
"u1",
"=",
"self",
".",
"get_uri",
"(",
"ns1",
",",
"id1",
")",
"u2",
"=",
"self",
".",
"get_uri",
"(",
"ns2",
",",
"id2",
")",
"t1",
"=",
"rdflib",
... | 27.413793 | 0.00243 |
def update(cls, id, name, size, quantity, password, sshkey, upgrade,
console, snapshot_profile, reset_mysql_password, background):
"""Update a PaaS instance."""
if not background and not cls.intty():
background = True
paas_params = {}
if name:
paa... | [
"def",
"update",
"(",
"cls",
",",
"id",
",",
"name",
",",
"size",
",",
"quantity",
",",
"password",
",",
"sshkey",
",",
"upgrade",
",",
"console",
",",
"snapshot_profile",
",",
"reset_mysql_password",
",",
"background",
")",
":",
"if",
"not",
"background",... | 29.309524 | 0.002358 |
def bufsize_validator(kwargs):
""" a validator to prevent a user from saying that they want custom
buffering when they're using an in/out object that will be os.dup'd to the
process, and has its own buffering. an example is a pipe or a tty. it
doesn't make sense to tell them to have a custom buffering... | [
"def",
"bufsize_validator",
"(",
"kwargs",
")",
":",
"invalid",
"=",
"[",
"]",
"in_ob",
"=",
"kwargs",
".",
"get",
"(",
"\"in\"",
",",
"None",
")",
"out_ob",
"=",
"kwargs",
".",
"get",
"(",
"\"out\"",
",",
"None",
")",
"in_buf",
"=",
"kwargs",
".",
... | 37.115385 | 0.00202 |
def resource_filename_mod_entry_point(module_name, entry_point):
"""
If a given package declares a namespace and also provide submodules
nested at that namespace level, and for whatever reason that module
is needed, Python's import mechanism will not have a path associated
with that module. However... | [
"def",
"resource_filename_mod_entry_point",
"(",
"module_name",
",",
"entry_point",
")",
":",
"if",
"entry_point",
".",
"dist",
"is",
"None",
":",
"# distribution missing is typically caused by mocked entry",
"# points from tests; silently falling back to basic lookup",
"result",
... | 41.612903 | 0.000758 |
def view_entries(search_query=None):
"""View previous entries"""
if search_query:
expr = Entry.content.search(search_query)
else:
expr = None
query = Entry.query(expr, order_by=Entry.timestamp.desc())
for entry in query:
timestamp = entry.timestamp.strftime('%A %B %d, %Y %I:... | [
"def",
"view_entries",
"(",
"search_query",
"=",
"None",
")",
":",
"if",
"search_query",
":",
"expr",
"=",
"Entry",
".",
"content",
".",
"search",
"(",
"search_query",
")",
"else",
":",
"expr",
"=",
"None",
"query",
"=",
"Entry",
".",
"query",
"(",
"ex... | 31.521739 | 0.001339 |
def supports_spatial_unit_record_type(self, spatial_unit_record_type=None):
"""Tests if the given spatial unit record type is supported.
arg: spatial_unit_record_type (osid.type.Type): a spatial
unit record Type
return: (boolean) - ``true`` if the type is supported, ``false``... | [
"def",
"supports_spatial_unit_record_type",
"(",
"self",
",",
"spatial_unit_record_type",
"=",
"None",
")",
":",
"# Implemented from template for osid.Metadata.supports_coordinate_type",
"from",
".",
"osid_errors",
"import",
"IllegalState",
",",
"NullArgument",
"if",
"not",
"... | 52 | 0.001988 |
def to_nodename(string, invalid=None, raise_exc=False):
"""Makes a Quilt Node name (perhaps an ugly one) out of any string.
This should match whatever the current definition of a node name is, as
defined in is_nodename().
This isn't an isomorphic change, the original name can't be recovered
from t... | [
"def",
"to_nodename",
"(",
"string",
",",
"invalid",
"=",
"None",
",",
"raise_exc",
"=",
"False",
")",
":",
"string",
"=",
"to_identifier",
"(",
"string",
")",
"#TODO: Remove this stanza once keywords are permissible in nodenames",
"if",
"keyword",
".",
"iskeyword",
... | 36.886792 | 0.001495 |
def submit(self, fn, *args, **kwargs):
""" Internal """
if not self.is_shutdown:
return self.cluster.executor.submit(fn, *args, **kwargs) | [
"def",
"submit",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"is_shutdown",
":",
"return",
"self",
".",
"cluster",
".",
"executor",
".",
"submit",
"(",
"fn",
",",
"*",
"args",
",",
"*",
... | 40.5 | 0.012121 |
def http_quote(string):
"""
Given a unicode string, will do its dandiest to give you back a
valid ascii charset string you can use in, say, http headers and the
like.
"""
if isinstance(string, six.text_type):
try:
import unidecode
except ImportError:
pass
... | [
"def",
"http_quote",
"(",
"string",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"text_type",
")",
":",
"try",
":",
"import",
"unidecode",
"except",
"ImportError",
":",
"pass",
"else",
":",
"string",
"=",
"unidecode",
".",
"unidecode",
"... | 33.941176 | 0.001686 |
def mk_token(opts, tdata):
'''
Mint a new token using the config option hash_type and store tdata with 'token' attribute set
to the token.
This module uses the hash of random 512 bytes as a token.
:param opts: Salt master config options
:param tdata: Token data to be stored with 'token' attirbu... | [
"def",
"mk_token",
"(",
"opts",
",",
"tdata",
")",
":",
"redis_client",
"=",
"_redis_client",
"(",
"opts",
")",
"if",
"not",
"redis_client",
":",
"return",
"{",
"}",
"hash_type",
"=",
"getattr",
"(",
"hashlib",
",",
"opts",
".",
"get",
"(",
"'hash_type'"... | 34.857143 | 0.002392 |
def _urlopen_as_json(self, url, headers=None):
"""Shorcut for return contents as json"""
req = Request(url, headers=headers)
return json.loads(urlopen(req).read()) | [
"def",
"_urlopen_as_json",
"(",
"self",
",",
"url",
",",
"headers",
"=",
"None",
")",
":",
"req",
"=",
"Request",
"(",
"url",
",",
"headers",
"=",
"headers",
")",
"return",
"json",
".",
"loads",
"(",
"urlopen",
"(",
"req",
")",
".",
"read",
"(",
")... | 46 | 0.010695 |
def _read_mode_qsopt(self, size, kind):
"""Read Quick-Start Response option.
Positional arguments:
* size - int, length of option
* kind - int, 27 (Quick-Start Response)
Returns:
* dict -- extracted Quick-Start Response (QS) option
Structure of TCP ... | [
"def",
"_read_mode_qsopt",
"(",
"self",
",",
"size",
",",
"kind",
")",
":",
"rvrr",
"=",
"self",
".",
"_read_binary",
"(",
"1",
")",
"ttld",
"=",
"self",
".",
"_read_unpack",
"(",
"1",
")",
"noun",
"=",
"self",
".",
"_read_fileng",
"(",
"4",
")",
"... | 42.093023 | 0.00108 |
def msetnx(self, mapping):
"""Sets the given keys to their respective values.
:meth:`~tredis.RedisClient.msetnx` will not perform any operation at
all even if just a single key already exists.
Because of this semantic :meth:`~tredis.RedisClient.msetnx` can be used
in order to se... | [
"def",
"msetnx",
"(",
"self",
",",
"mapping",
")",
":",
"command",
"=",
"[",
"b'MSETNX'",
"]",
"for",
"key",
",",
"value",
"in",
"mapping",
".",
"items",
"(",
")",
":",
"command",
"+=",
"[",
"key",
",",
"value",
"]",
"return",
"self",
".",
"_execut... | 39.285714 | 0.001775 |
def tail_ratio(returns):
"""Determines the ratio between the right (95%) and left tail (5%).
For example, a ratio of 0.25 means that losses are four times
as bad as profits.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
-... | [
"def",
"tail_ratio",
"(",
"returns",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"1",
":",
"return",
"np",
".",
"nan",
"returns",
"=",
"np",
".",
"asanyarray",
"(",
"returns",
")",
"# Be tolerant of nan's",
"returns",
"=",
"returns",
"[",
"~",
"np... | 25.214286 | 0.001364 |
def add(self, rule: 'functions.ReplacementRule') -> None:
"""Add a new rule to the replacer.
Args:
rule:
The rule to add.
"""
self.matcher.add(rule.pattern, rule.replacement) | [
"def",
"add",
"(",
"self",
",",
"rule",
":",
"'functions.ReplacementRule'",
")",
"->",
"None",
":",
"self",
".",
"matcher",
".",
"add",
"(",
"rule",
".",
"pattern",
",",
"rule",
".",
"replacement",
")"
] | 28.5 | 0.008511 |
def print_markdown(data, title=None):
"""Print data in GitHub-flavoured Markdown format for issues etc.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be rendered as headline 2.
"""
markdown = []
for key, value in data.items():
if isinstance(value... | [
"def",
"print_markdown",
"(",
"data",
",",
"title",
"=",
"None",
")",
":",
"markdown",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"basestring_",
")",
"and",
"Path",
"... | 38.428571 | 0.001815 |
def get_img(self, url, headers=None, cookies=None, timeout=60, verify=False, proxies=None, allow_redirects=True,
params=None):
"""
get方式获取 img 二进制信息
:param url: 访问Url
:param headers: 请求头
:param cookies: 请求cookies
:param timeout: 超时时间
:param verify:... | [
"def",
"get_img",
"(",
"self",
",",
"url",
",",
"headers",
"=",
"None",
",",
"cookies",
"=",
"None",
",",
"timeout",
"=",
"60",
",",
"verify",
"=",
"False",
",",
"proxies",
"=",
"None",
",",
"allow_redirects",
"=",
"True",
",",
"params",
"=",
"None",... | 42.478261 | 0.008008 |
def _other_wrapper(self, name, writing):
"""Wrap a stream attribute in an other_wrapper.
Args:
name: the name of the stream attribute to wrap.
Returns:
other_wrapper which is described below.
"""
io_attr = getattr(self._io, name)
def other_wrapper(*... | [
"def",
"_other_wrapper",
"(",
"self",
",",
"name",
",",
"writing",
")",
":",
"io_attr",
"=",
"getattr",
"(",
"self",
".",
"_io",
",",
"name",
")",
"def",
"other_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrap all other calls to... | 31.617647 | 0.001805 |
def register_signals(self):
"""Register signals."""
from .models import Collection
from .receivers import CollectionUpdater
if self.app.config['COLLECTIONS_USE_PERCOLATOR']:
from .percolator import collection_inserted_percolator, \
collection_removed_percolat... | [
"def",
"register_signals",
"(",
"self",
")",
":",
"from",
".",
"models",
"import",
"Collection",
"from",
".",
"receivers",
"import",
"CollectionUpdater",
"if",
"self",
".",
"app",
".",
"config",
"[",
"'COLLECTIONS_USE_PERCOLATOR'",
"]",
":",
"from",
".",
"perc... | 49.272727 | 0.00181 |
def Lab_to_XYZ(cobj, *args, **kwargs):
"""
Convert from Lab to XYZ
"""
illum = cobj.get_illuminant_xyz()
xyz_y = (cobj.lab_l + 16.0) / 116.0
xyz_x = cobj.lab_a / 500.0 + xyz_y
xyz_z = xyz_y - cobj.lab_b / 200.0
if math.pow(xyz_y, 3) > color_constants.CIE_E:
xyz_y = math.pow(xyz_... | [
"def",
"Lab_to_XYZ",
"(",
"cobj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"illum",
"=",
"cobj",
".",
"get_illuminant_xyz",
"(",
")",
"xyz_y",
"=",
"(",
"cobj",
".",
"lab_l",
"+",
"16.0",
")",
"/",
"116.0",
"xyz_x",
"=",
"cobj",
".",
... | 28.133333 | 0.002291 |
def decode(encoded_histogram, b64_wrap=True):
'''Decode an encoded histogram and return a new histogram instance that
has been initialized with the decoded content
Return:
a new histogram instance representing the decoded content
Exception:
TypeError in case of ba... | [
"def",
"decode",
"(",
"encoded_histogram",
",",
"b64_wrap",
"=",
"True",
")",
":",
"hdr_payload",
"=",
"HdrHistogramEncoder",
".",
"decode",
"(",
"encoded_histogram",
",",
"b64_wrap",
")",
"payload",
"=",
"hdr_payload",
".",
"payload",
"histogram",
"=",
"HdrHist... | 49.565217 | 0.001721 |
def generate_supplied_intersect_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to run an intersect query
using the supplied results sets."""
parser = subparsers.add_parser(
'sintersect', description=constants.SUPPLIED_INTERSECT_DESCRIPTION,
epilog=constants.SUPPLIED_INTE... | [
"def",
"generate_supplied_intersect_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'sintersect'",
",",
"description",
"=",
"constants",
".",
"SUPPLIED_INTERSECT_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"SUPPLI... | 49.166667 | 0.001664 |
def import_experience(self, experiences):
"""
Imports experiences.
Args:
experiences:
"""
if isinstance(experiences, dict):
if self.unique_state:
experiences['states'] = dict(state=experiences['states'])
if self.unique_action:... | [
"def",
"import_experience",
"(",
"self",
",",
"experiences",
")",
":",
"if",
"isinstance",
"(",
"experiences",
",",
"dict",
")",
":",
"if",
"self",
".",
"unique_state",
":",
"experiences",
"[",
"'states'",
"]",
"=",
"dict",
"(",
"state",
"=",
"experiences"... | 37.078431 | 0.001546 |
def str_arg(d):
"""formats a function argument prettily not as code
dicts are expressed in {key=value} syntax
strings are formatted using str in quotes not repr"""
if not d:
return None
if isinstance(d, dict):
if len(d) == 2 and d.get('type') == 'text' and 'value' in d:
... | [
"def",
"str_arg",
"(",
"d",
")",
":",
"if",
"not",
"d",
":",
"return",
"None",
"if",
"isinstance",
"(",
"d",
",",
"dict",
")",
":",
"if",
"len",
"(",
"d",
")",
"==",
"2",
"and",
"d",
".",
"get",
"(",
"'type'",
")",
"==",
"'text'",
"and",
"'va... | 33.217391 | 0.001272 |
def relation_get(attribute=None, unit=None, rid=None):
"""Get relation information"""
_args = ['relation-get', '--format=json']
if rid:
_args.append('-r')
_args.append(rid)
_args.append(attribute or '-')
if unit:
_args.append(unit)
try:
return json.loads(subproces... | [
"def",
"relation_get",
"(",
"attribute",
"=",
"None",
",",
"unit",
"=",
"None",
",",
"rid",
"=",
"None",
")",
":",
"_args",
"=",
"[",
"'relation-get'",
",",
"'--format=json'",
"]",
"if",
"rid",
":",
"_args",
".",
"append",
"(",
"'-r'",
")",
"_args",
... | 28.764706 | 0.00198 |
def crontab(
state, host, command, present=True, user=None,
minute='*', hour='*', month='*', day_of_week='*', day_of_month='*',
):
'''
Add/remove/update crontab entries.
+ command: the command for the cron
+ present: whether this cron command should exist
+ user: the user whose crontab to m... | [
"def",
"crontab",
"(",
"state",
",",
"host",
",",
"command",
",",
"present",
"=",
"True",
",",
"user",
"=",
"None",
",",
"minute",
"=",
"'*'",
",",
"hour",
"=",
"'*'",
",",
"month",
"=",
"'*'",
",",
"day_of_week",
"=",
"'*'",
",",
"day_of_month",
"... | 34.325 | 0.001062 |
def _phi2deriv(self,R,z,phi=0.,t=0.):
"""
NAME:
_phi2deriv
PURPOSE:
evaluate the second azimuthal derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
... | [
"def",
"_phi2deriv",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"if",
"not",
"self",
".",
"isNonAxi",
":",
"phi",
"=",
"0.",
"x",
",",
"y",
",",
"z",
"=",
"self",
".",
"_compute_xyz",
"(",
"R",
",... | 37.59375 | 0.036467 |
def update_where(self, col, value, where_col_list, where_value_list):
"""
updates the array to set cell = value where col_list == val_list
"""
if type(col) is str:
col_ndx = self.get_col_by_name(col)
else:
col_ndx = col
#print('col_ndx = ', col_nd... | [
"def",
"update_where",
"(",
"self",
",",
"col",
",",
"value",
",",
"where_col_list",
",",
"where_value_list",
")",
":",
"if",
"type",
"(",
"col",
")",
"is",
"str",
":",
"col_ndx",
"=",
"self",
".",
"get_col_by_name",
"(",
"col",
")",
"else",
":",
"col_... | 42.428571 | 0.011532 |
def reset(self):
""" Reset/remove all layers, keeping only the initial volume. """
self.layers = {}
self.stack = []
self.set_mask()
self.n_vox_in_vol = len(np.where(self.current_mask)[0]) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"layers",
"=",
"{",
"}",
"self",
".",
"stack",
"=",
"[",
"]",
"self",
".",
"set_mask",
"(",
")",
"self",
".",
"n_vox_in_vol",
"=",
"len",
"(",
"np",
".",
"where",
"(",
"self",
".",
"current_mask... | 37 | 0.008811 |
def setEnv(self, name, value=None):
"""
Set an environment variable for the worker process before it is launched. The worker
process will typically inherit the environment of the machine it is running on but this
method makes it possible to override specific variables in that inherited e... | [
"def",
"setEnv",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"try",
":",
"value",
"=",
"os",
".",
"environ",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"RuntimeError",
"(",
"\"%s does no... | 54.551724 | 0.008696 |
def QA_SU_save_option_commodity_min(
client=DATABASE,
ui_log=None,
ui_progress=None
):
'''
:param client:
:return:
'''
# 测试中发现, 一起回去,容易出现错误,每次获取一个品种后 ,更换服务ip继续获取 ?
_save_option_commodity_cu_min(
client=client,
ui_log=ui_log,
ui_progress=ui... | [
"def",
"QA_SU_save_option_commodity_min",
"(",
"client",
"=",
"DATABASE",
",",
"ui_log",
"=",
"None",
",",
"ui_progress",
"=",
"None",
")",
":",
"# 测试中发现, 一起回去,容易出现错误,每次获取一个品种后 ,更换服务ip继续获取 ?",
"_save_option_commodity_cu_min",
"(",
"client",
"=",
"client",
",",
"ui_log",... | 20.181818 | 0.001074 |
def get_full_md5(self, partial_md5, collection):
"""Support partial/short md5s, return the full md5 with this method"""
print 'Notice: Performing slow md5 search...'
starts_with = '%s.*' % partial_md5
sample_info = self.database[collection].find_one({'md5': {'$regex' : starts_with}},{'md... | [
"def",
"get_full_md5",
"(",
"self",
",",
"partial_md5",
",",
"collection",
")",
":",
"print",
"'Notice: Performing slow md5 search...'",
"starts_with",
"=",
"'%s.*'",
"%",
"partial_md5",
"sample_info",
"=",
"self",
".",
"database",
"[",
"collection",
"]",
".",
"fi... | 63.333333 | 0.015584 |
def cmd_connect(node, cmd_name, node_info):
"""Connect to node."""
# FUTURE: call function to check for custom connection-info
conn_info = "Defaults"
conf_mess = ("\r{0}{1} TO{2} {3} using {5}{4}{2} - Confirm [y/N]: ".
format(C_STAT[cmd_name.upper()], cmd_name.upper(), C_NORM,
... | [
"def",
"cmd_connect",
"(",
"node",
",",
"cmd_name",
",",
"node_info",
")",
":",
"# FUTURE: call function to check for custom connection-info",
"conn_info",
"=",
"\"Defaults\"",
"conf_mess",
"=",
"(",
"\"\\r{0}{1} TO{2} {3} using {5}{4}{2} - Confirm [y/N]: \"",
".",
"format",
... | 39.866667 | 0.000816 |
def lucas_gas(T, Tc, Pc, Zc, MW, dipole=0, CASRN=None):
r'''Estimate the viscosity of a gas using an emperical
formula developed in several sources, but as discussed in [1]_ as the
original sources are in German or merely personal communications with the
authors of [1]_.
.. math::
\eta = \... | [
"def",
"lucas_gas",
"(",
"T",
",",
"Tc",
",",
"Pc",
",",
"Zc",
",",
"MW",
",",
"dipole",
"=",
"0",
",",
"CASRN",
"=",
"None",
")",
":",
"Tr",
"=",
"T",
"/",
"Tc",
"xi",
"=",
"0.176",
"*",
"(",
"Tc",
"/",
"MW",
"**",
"3",
"/",
"(",
"Pc",
... | 30.765432 | 0.002333 |
def items(self):
""" Return all merged items as iterator """
if not self.pdata and not self.spills:
return iter(self.data.items())
return self._external_items() | [
"def",
"items",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"pdata",
"and",
"not",
"self",
".",
"spills",
":",
"return",
"iter",
"(",
"self",
".",
"data",
".",
"items",
"(",
")",
")",
"return",
"self",
".",
"_external_items",
"(",
")"
] | 38.4 | 0.010204 |
def _parse_hostvar_dir(self, inventory_path):
"""
Parse host_vars dir, if it exists.
"""
# inventory_path could point to a `hosts` file, or to a dir. So we
# construct the location to the `host_vars` differently.
if os.path.isdir(inventory_path):
path = os.pat... | [
"def",
"_parse_hostvar_dir",
"(",
"self",
",",
"inventory_path",
")",
":",
"# inventory_path could point to a `hosts` file, or to a dir. So we",
"# construct the location to the `host_vars` differently.",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"inventory_path",
")",
":",
... | 40.914286 | 0.001364 |
def calculate_tetra_zscore(filename):
"""Returns TETRA Z-score for the sequence in the passed file.
- filename - path to sequence file
Calculates mono-, di-, tri- and tetranucleotide frequencies
for each sequence, on each strand, and follows Teeling et al. (2004)
in calculating a corresponding Z-s... | [
"def",
"calculate_tetra_zscore",
"(",
"filename",
")",
":",
"# For the Teeling et al. method, the Z-scores require us to count",
"# mono, di, tri and tetranucleotide sequences - these are stored",
"# (in order) in the counts tuple",
"counts",
"=",
"(",
"collections",
".",
"defaultdict",
... | 49.192982 | 0.00035 |
def coordinatesFromIndex(index, dimensions):
"""
Translate an index into coordinates, using the given coordinate system.
Similar to ``numpy.unravel_index``.
:param index: (int) The index of the point. The coordinates are expressed as a
single index by using the dimensions as a mixed radix definition... | [
"def",
"coordinatesFromIndex",
"(",
"index",
",",
"dimensions",
")",
":",
"coordinates",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"dimensions",
")",
"shifted",
"=",
"index",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"dimensions",
")",
"-",
"1",
",",
"... | 30.6 | 0.013942 |
def check_sla(self, sla, diff_metric):
"""
Check whether the SLA has passed or failed
"""
try:
if sla.display is '%':
diff_val = float(diff_metric['percent_diff'])
else:
diff_val = float(diff_metric['absolute_diff'])
except ValueError:
return False
if not (sla.c... | [
"def",
"check_sla",
"(",
"self",
",",
"sla",
",",
"diff_metric",
")",
":",
"try",
":",
"if",
"sla",
".",
"display",
"is",
"'%'",
":",
"diff_val",
"=",
"float",
"(",
"diff_metric",
"[",
"'percent_diff'",
"]",
")",
"else",
":",
"diff_val",
"=",
"float",
... | 29.8 | 0.013015 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.