text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def symbol(name: str=None, symbol_type: Type[Symbol]=Symbol) -> 'SymbolWildcard':
"""Create a `SymbolWildcard` that matches a single `Symbol` argument.
Args:
name:
Optional variable name for the wildcard.
symbol_type:
An optional subclass of `Symb... | [
"def",
"symbol",
"(",
"name",
":",
"str",
"=",
"None",
",",
"symbol_type",
":",
"Type",
"[",
"Symbol",
"]",
"=",
"Symbol",
")",
"->",
"'SymbolWildcard'",
":",
"if",
"isinstance",
"(",
"name",
",",
"type",
")",
"and",
"issubclass",
"(",
"name",
",",
"... | 42.375 | 0.012987 |
def _export_to2marc(self, key, value):
"""Populate the ``595`` MARC field."""
def _is_for_cds(value):
return 'CDS' in value
def _is_for_hal(value):
return 'HAL' in value and value['HAL']
def _is_not_for_hal(value):
return 'HAL' in value and not value['HAL']
result = []
... | [
"def",
"_export_to2marc",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"def",
"_is_for_cds",
"(",
"value",
")",
":",
"return",
"'CDS'",
"in",
"value",
"def",
"_is_for_hal",
"(",
"value",
")",
":",
"return",
"'HAL'",
"in",
"value",
"and",
"value",
"... | 23.409091 | 0.001866 |
def Run(self, args):
"""Run."""
# Open the file.
fd = vfs.VFSOpen(args.pathspec, progress_callback=self.Progress)
if args.address_family == rdf_client_network.NetworkAddress.Family.INET:
family = socket.AF_INET
elif args.address_family == rdf_client_network.NetworkAddress.Family.INET6:
... | [
"def",
"Run",
"(",
"self",
",",
"args",
")",
":",
"# Open the file.",
"fd",
"=",
"vfs",
".",
"VFSOpen",
"(",
"args",
".",
"pathspec",
",",
"progress_callback",
"=",
"self",
".",
"Progress",
")",
"if",
"args",
".",
"address_family",
"==",
"rdf_client_networ... | 27.083333 | 0.010891 |
def loss_batch(model:nn.Module, xb:Tensor, yb:Tensor, loss_func:OptLossFunc=None, opt:OptOptimizer=None,
cb_handler:Optional[CallbackHandler]=None)->Tuple[Union[Tensor,int,float,str]]:
"Calculate loss and metrics for a batch, call out to callbacks as necessary."
cb_handler = ifnone(cb_handler, Ca... | [
"def",
"loss_batch",
"(",
"model",
":",
"nn",
".",
"Module",
",",
"xb",
":",
"Tensor",
",",
"yb",
":",
"Tensor",
",",
"loss_func",
":",
"OptLossFunc",
"=",
"None",
",",
"opt",
":",
"OptOptimizer",
"=",
"None",
",",
"cb_handler",
":",
"Optional",
"[",
... | 43.947368 | 0.031653 |
def make_slider_range(self, cursor_pos):
"""Make slider range QRect"""
# The slider range indicator position follows the mouse vertical
# position while its height corresponds to the part of the file that
# is currently visible on screen.
vsb = self.editor.verticalScrollBar()
... | [
"def",
"make_slider_range",
"(",
"self",
",",
"cursor_pos",
")",
":",
"# The slider range indicator position follows the mouse vertical",
"# position while its height corresponds to the part of the file that",
"# is currently visible on screen.",
"vsb",
"=",
"self",
".",
"editor",
".... | 46.2 | 0.002121 |
def vectorize_range(values):
"""
This function is for url encoding.
Takes a value or a tuple or list of tuples and returns a single result,
tuples are joined by "," if necessary, elements in tuple are joined by '_'
"""
if isinstance(values, tuple):
return '_'.join(str(i) for i in values)... | [
"def",
"vectorize_range",
"(",
"values",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"tuple",
")",
":",
"return",
"'_'",
".",
"join",
"(",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"values",
")",
"if",
"isinstance",
"(",
"values",
",",
"list",
... | 43.307692 | 0.001739 |
def f(x, depth1, depth2, dim='2d', first_batch_norm=True, stride=1,
training=True, bottleneck=True, padding='SAME'):
"""Applies residual function for RevNet.
Args:
x: input tensor
depth1: Number of output channels for the first and second conv layers.
depth2: Number of output channels for the thi... | [
"def",
"f",
"(",
"x",
",",
"depth1",
",",
"depth2",
",",
"dim",
"=",
"'2d'",
",",
"first_batch_norm",
"=",
"True",
",",
"stride",
"=",
"1",
",",
"training",
"=",
"True",
",",
"bottleneck",
"=",
"True",
",",
"padding",
"=",
"'SAME'",
")",
":",
"conv... | 38.372549 | 0.008969 |
def tick_clients(self):
"""Trigger the periodic tick function in the client."""
if not self._ticker:
self._create_ticker()
for client in self.clients.values():
self._ticker.tick(client) | [
"def",
"tick_clients",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ticker",
":",
"self",
".",
"_create_ticker",
"(",
")",
"for",
"client",
"in",
"self",
".",
"clients",
".",
"values",
"(",
")",
":",
"self",
".",
"_ticker",
".",
"tick",
"(",
... | 32.571429 | 0.008547 |
def initialize(self):
"""
Initialize the environment. Done with a method call outside of the constructor for 2 reasons:
1. Unit tests probably won't want/need to do this
2. We don't initialize the logger (also something unit tests don't want) until after the
constructor
"""
create_folders = ... | [
"def",
"initialize",
"(",
"self",
")",
":",
"create_folders",
"=",
"Command",
"(",
"'mkdir -p %s'",
"%",
"self",
".",
"log_dir",
",",
"self",
".",
"shell_env",
")",
"self",
".",
"run_command_or_exit",
"(",
"create_folders",
")",
"chmod_logs_dir",
"=",
"Command... | 42.347826 | 0.008032 |
def unlock(self):
"""
Releases the lock.
"""
return self._encode_invoke(lock_unlock_codec, thread_id=thread_id(),
reference_id=self.reference_id_generator.get_and_increment()) | [
"def",
"unlock",
"(",
"self",
")",
":",
"return",
"self",
".",
"_encode_invoke",
"(",
"lock_unlock_codec",
",",
"thread_id",
"=",
"thread_id",
"(",
")",
",",
"reference_id",
"=",
"self",
".",
"reference_id_generator",
".",
"get_and_increment",
"(",
")",
")"
] | 39.5 | 0.012397 |
def fit_meanshift(self, data, bandwidth=None, bin_seeding=False, **kwargs):
"""
Fit MeanShift clustering algorithm to data.
Parameters
----------
data : array-like
A dataset formatted by `classifier.fitting_data`.
bandwidth : float
The bandwidth v... | [
"def",
"fit_meanshift",
"(",
"self",
",",
"data",
",",
"bandwidth",
"=",
"None",
",",
"bin_seeding",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"bandwidth",
"is",
"None",
":",
"bandwidth",
"=",
"cl",
".",
"estimate_bandwidth",
"(",
"data",
... | 34.928571 | 0.00199 |
def fix_missing_locations(node):
"""
Some nodes require a line number and the column offset. Without that
information the compiler will abort the compilation. Because it can be
a dull task to add appropriate line numbers and column offsets when
adding new nodes this function can help. It copies t... | [
"def",
"fix_missing_locations",
"(",
"node",
")",
":",
"def",
"_fix",
"(",
"node",
",",
"lineno",
",",
"col_offset",
")",
":",
"if",
"'lineno'",
"in",
"node",
".",
"_attributes",
":",
"if",
"not",
"hasattr",
"(",
"node",
",",
"'lineno'",
")",
":",
"nod... | 39.518519 | 0.000915 |
def set_display_sleep(minutes):
'''
Set the amount of idle time until the display sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example:
... | [
"def",
"set_display_sleep",
"(",
"minutes",
")",
":",
"value",
"=",
"_validate_sleep",
"(",
"minutes",
")",
"cmd",
"=",
"'systemsetup -setdisplaysleep {0}'",
".",
"format",
"(",
"value",
")",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
... | 25.807692 | 0.001437 |
def get_block_type(values, dtype=None):
"""
Find the appropriate Block subclass to use for the given values and dtype.
Parameters
----------
values : ndarray-like
dtype : numpy or pandas dtype
Returns
-------
cls : class, subclass of Block
"""
dtype = dtype or values.dtype
... | [
"def",
"get_block_type",
"(",
"values",
",",
"dtype",
"=",
"None",
")",
":",
"dtype",
"=",
"dtype",
"or",
"values",
".",
"dtype",
"vtype",
"=",
"dtype",
".",
"type",
"if",
"is_sparse",
"(",
"dtype",
")",
":",
"# Need this first(ish) so that Sparse[datetime] is... | 28.931818 | 0.00076 |
def parse_return_annotation(callback):
'''Parses the annotation return tuples. Ruturn a dictinary {code: info}.'''
# This has been implemented as a function as the parsing need to be
# accessible from a decorator used on the function's class method
responses = {}
for data in callback.__annotations__... | [
"def",
"parse_return_annotation",
"(",
"callback",
")",
":",
"# This has been implemented as a function as the parsing need to be",
"# accessible from a decorator used on the function's class method",
"responses",
"=",
"{",
"}",
"for",
"data",
"in",
"callback",
".",
"__annotations_... | 52.181818 | 0.001712 |
def new_character(self, name, data=None, **kwargs):
"""Create and return a new :class:`Character`."""
self.add_character(name, data, **kwargs)
return self.character[name] | [
"def",
"new_character",
"(",
"self",
",",
"name",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"add_character",
"(",
"name",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"character",
"[",
"name",
"]... | 47.75 | 0.010309 |
def close(self):
"""\
Closes the writer.
This method MUST be called once all vectors are added.
"""
self._mmw.fake_headers(self._num_docs+1, self._num_terms, self._num_nnz)
self._mmw.close() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_mmw",
".",
"fake_headers",
"(",
"self",
".",
"_num_docs",
"+",
"1",
",",
"self",
".",
"_num_terms",
",",
"self",
".",
"_num_nnz",
")",
"self",
".",
"_mmw",
".",
"close",
"(",
")"
] | 29 | 0.012552 |
def comp_sma(b, component, solve_for=None, **kwargs):
"""
Create a constraint for the star's semi-major axes WITHIN its
parent orbit. This is NOT the same as the semi-major axes OF
the parent orbit
If 'sma' does not exist in the component, it will be created
:parameter b: the :class:`phoebe.f... | [
"def",
"comp_sma",
"(",
"b",
",",
"component",
",",
"solve_for",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"hier",
"=",
"b",
".",
"get_hierarchy",
"(",
")",
"if",
"not",
"len",
"(",
"hier",
".",
"get_value",
"(",
")",
")",
":",
"# TODO: chang... | 36.416667 | 0.002228 |
def set_outgroup(self, outgroup):
"""
Sets a descendant node as the outgroup of a tree. This function
can be used to root a tree or even an internal node.
Parameters:
-----------
outgroup:
a node instance within the same tree structure that will be
... | [
"def",
"set_outgroup",
"(",
"self",
",",
"outgroup",
")",
":",
"outgroup",
"=",
"_translate_nodes",
"(",
"self",
",",
"outgroup",
")",
"if",
"self",
"==",
"outgroup",
":",
"##return",
"## why raise an error for this?",
"raise",
"TreeError",
"(",
"\"Cannot set myse... | 36.356322 | 0.002155 |
def _create_container_args(kwargs):
"""
Convert arguments to create() to arguments to create_container().
"""
# Copy over kwargs which can be copied directly
create_kwargs = {}
for key in copy.copy(kwargs):
if key in RUN_CREATE_KWARGS:
create_kwargs[key] = kwargs.pop(key)
... | [
"def",
"_create_container_args",
"(",
"kwargs",
")",
":",
"# Copy over kwargs which can be copied directly",
"create_kwargs",
"=",
"{",
"}",
"for",
"key",
"in",
"copy",
".",
"copy",
"(",
"kwargs",
")",
":",
"if",
"key",
"in",
"RUN_CREATE_KWARGS",
":",
"create_kwar... | 34.745098 | 0.000549 |
def remove_declarated(type_):
"""removes type-declaration class-binder :class:`declarated_t` from
the `type_`
If `type_` is not :class:`declarated_t`, it will be returned as is
"""
type_ = remove_alias(type_)
if isinstance(type_, cpptypes.elaborated_t):
type_ = type_.base
if isinsta... | [
"def",
"remove_declarated",
"(",
"type_",
")",
":",
"type_",
"=",
"remove_alias",
"(",
"type_",
")",
"if",
"isinstance",
"(",
"type_",
",",
"cpptypes",
".",
"elaborated_t",
")",
":",
"type_",
"=",
"type_",
".",
"base",
"if",
"isinstance",
"(",
"type_",
"... | 32.833333 | 0.002469 |
def task_failure_message(task_report):
"""Task failure message."""
trace_list = traceback.format_tb(task_report['traceback'])
body = 'Error: task failure\n\n'
body += 'Task ID: {}\n\n'.format(task_report['task_id'])
body += 'Archive: {}\n\n'.format(task_report['archive'])
body += 'Docker image: ... | [
"def",
"task_failure_message",
"(",
"task_report",
")",
":",
"trace_list",
"=",
"traceback",
".",
"format_tb",
"(",
"task_report",
"[",
"'traceback'",
"]",
")",
"body",
"=",
"'Error: task failure\\n\\n'",
"body",
"+=",
"'Task ID: {}\\n\\n'",
".",
"format",
"(",
"t... | 47.818182 | 0.001866 |
def Hf(CASRN, AvailableMethods=False, Method=None):
r'''This function handles the retrieval of a chemical's standard-phase
heat of formation. The lookup is based on CASRNs. Selects the only
data source available ('API TDB') if the chemical is in it.
Returns None if the data is not available.
Functi... | [
"def",
"Hf",
"(",
"CASRN",
",",
"AvailableMethods",
"=",
"False",
",",
"Method",
"=",
"None",
")",
":",
"def",
"list_methods",
"(",
")",
":",
"methods",
"=",
"[",
"]",
"if",
"CASRN",
"in",
"API_TDB_data",
".",
"index",
":",
"methods",
".",
"append",
... | 31.283582 | 0.000463 |
def publish(self, events):
"""Publish events."""
assert len(events) > 0
with self.create_producer() as producer:
for event in events:
producer.publish(event) | [
"def",
"publish",
"(",
"self",
",",
"events",
")",
":",
"assert",
"len",
"(",
"events",
")",
">",
"0",
"with",
"self",
".",
"create_producer",
"(",
")",
"as",
"producer",
":",
"for",
"event",
"in",
"events",
":",
"producer",
".",
"publish",
"(",
"eve... | 34 | 0.009569 |
def analytic(input_type, output_type):
"""Define an *analytic* user-defined function that takes N
pandas Series or scalar values as inputs and produces N rows of output.
Parameters
----------
input_type : List[ibis.expr.datatypes.DataType]
A list of the types found i... | [
"def",
"analytic",
"(",
"input_type",
",",
"output_type",
")",
":",
"return",
"udf",
".",
"_grouped",
"(",
"input_type",
",",
"output_type",
",",
"base_class",
"=",
"ops",
".",
"AnalyticOp",
",",
"output_type_method",
"=",
"operator",
".",
"attrgetter",
"(",
... | 40.071429 | 0.001741 |
def uint8_3(self, val1, val2, val3):
"""append a frame containing 3 uint8"""
try:
self.msg += [pack("BBB", val1, val2, val3)]
except struct.error:
raise ValueError("Expected uint8")
return self | [
"def",
"uint8_3",
"(",
"self",
",",
"val1",
",",
"val2",
",",
"val3",
")",
":",
"try",
":",
"self",
".",
"msg",
"+=",
"[",
"pack",
"(",
"\"BBB\"",
",",
"val1",
",",
"val2",
",",
"val3",
")",
"]",
"except",
"struct",
".",
"error",
":",
"raise",
... | 34.714286 | 0.008032 |
def evaluate_model_single_recording_multisymbol(model_file, recording):
"""
Evaluate a model for a single recording where possibly multiple symbols
are.
Parameters
----------
model_file : string
Model file (.tar)
recording :
The handwritten recording.
"""
(preprocess... | [
"def",
"evaluate_model_single_recording_multisymbol",
"(",
"model_file",
",",
"recording",
")",
":",
"(",
"preprocessing_queue",
",",
"feature_list",
",",
"model",
",",
"output_semantics",
")",
"=",
"load_model",
"(",
"model_file",
")",
"logging",
".",
"info",
"(",
... | 37.136364 | 0.001193 |
def uplink_bond_intf_process(self):
"""Process the case when uplink interface becomes part of a bond.
This is called to check if the phy interface became a part of the
bond. If the below condition is True, this means, a physical
interface that was not a part of a bond was earlier discov... | [
"def",
"uplink_bond_intf_process",
"(",
"self",
")",
":",
"bond_intf",
"=",
"sys_utils",
".",
"get_bond_intf",
"(",
"self",
".",
"phy_uplink",
")",
"if",
"bond_intf",
"is",
"None",
":",
"return",
"False",
"self",
".",
"save_uplink",
"(",
"fail_reason",
"=",
... | 49.6 | 0.000879 |
def _set_attributes(self, kwds):
"""Internal helper to set attributes from keyword arguments.
Expando overrides this.
"""
cls = self.__class__
for name, value in kwds.iteritems():
prop = getattr(cls, name) # Raises AttributeError for unknown properties.
if not isinstance(prop, Property... | [
"def",
"_set_attributes",
"(",
"self",
",",
"kwds",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"for",
"name",
",",
"value",
"in",
"kwds",
".",
"iteritems",
"(",
")",
":",
"prop",
"=",
"getattr",
"(",
"cls",
",",
"name",
")",
"# Raises AttributeErr... | 37.090909 | 0.011962 |
def encrypt(plaintext_str, keys):
"""Encrypt data and return the encrypted form.
:param bytes plaintext_str: the mail to encrypt
:param key: optionally, a list of keys to encrypt with
:type key: list[gpg.gpgme.gpgme_key_t] or None
:returns: encrypted mail
:rtype: str
"""
assert keys, 'M... | [
"def",
"encrypt",
"(",
"plaintext_str",
",",
"keys",
")",
":",
"assert",
"keys",
",",
"'Must provide at least one key to encrypt with'",
"ctx",
"=",
"gpg",
".",
"core",
".",
"Context",
"(",
"armor",
"=",
"True",
")",
"out",
"=",
"ctx",
".",
"encrypt",
"(",
... | 36.857143 | 0.00189 |
def _http(method, url, headers=None, **kw):
'''
Send http request and return response text.
'''
params = None
boundary = None
if method == 'UPLOAD':
params, boundary = _encode_multipart(**kw)
else:
params = _encode_params(**kw)
http_url = '%s?%s' % (url, params) if method... | [
"def",
"_http",
"(",
"method",
",",
"url",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"params",
"=",
"None",
"boundary",
"=",
"None",
"if",
"method",
"==",
"'UPLOAD'",
":",
"params",
",",
"boundary",
"=",
"_encode_multipart",
"(",
"*... | 33.16 | 0.002345 |
def _mix(color1, color2, weight=None):
"""
Mixes together two colors. Specifically, takes the average of each of the
RGB components, optionally weighted by the given percentage.
The opacity of the colors is also considered when weighting the components.
Specifically, takes the average of each of th... | [
"def",
"_mix",
"(",
"color1",
",",
"color2",
",",
"weight",
"=",
"None",
")",
":",
"# This algorithm factors in both the user-provided weight",
"# and the difference between the alpha values of the two colors",
"# to decide how to perform the weighted average of the two RGB values.",
"... | 38.169231 | 0.000393 |
def _fields_sort_by_indicators(fields):
"""Sort a set of fields by their indicators.
Return a sorted list with correct global field positions.
"""
field_dict = {}
field_positions_global = []
for field in fields:
field_dict.setdefault(field[1:3], []).append(field)
field_positions... | [
"def",
"_fields_sort_by_indicators",
"(",
"fields",
")",
":",
"field_dict",
"=",
"{",
"}",
"field_positions_global",
"=",
"[",
"]",
"for",
"field",
"in",
"fields",
":",
"field_dict",
".",
"setdefault",
"(",
"field",
"[",
"1",
":",
"3",
"]",
",",
"[",
"]"... | 29 | 0.001669 |
def is_list(self, key):
"""Return True if variable is a list or a tuple"""
data = self.model.get_data()
return isinstance(data[key], (tuple, list)) | [
"def",
"is_list",
"(",
"self",
",",
"key",
")",
":",
"data",
"=",
"self",
".",
"model",
".",
"get_data",
"(",
")",
"return",
"isinstance",
"(",
"data",
"[",
"key",
"]",
",",
"(",
"tuple",
",",
"list",
")",
")"
] | 42.75 | 0.011494 |
def is_unary_operator(oper):
"""returns True, if operator is unary operator, otherwise False"""
# definition:
# member in class
# ret-type operator symbol()
# ret-type operator [++ --](int)
# globally
# ret-type operator symbol( arg )
# ret-type operator [++ --](X&, int)
symbols = ['... | [
"def",
"is_unary_operator",
"(",
"oper",
")",
":",
"# definition:",
"# member in class",
"# ret-type operator symbol()",
"# ret-type operator [++ --](int)",
"# globally",
"# ret-type operator symbol( arg )",
"# ret-type operator [++ --](X&, int)",
"symbols",
"=",
"[",
"'!'",
",",
... | 35.419355 | 0.000887 |
def window_blackman_harris(N):
r"""Blackman Harris window
:param N: window length
.. math:: w(n) = a_0 - a_1 \cos\left(\frac{2\pi n}{N-1}\right)+ a_2 \cos\left(\frac{4\pi n}{N-1}\right)- a_3 \cos\left(\frac{6\pi n}{N-1}\right)
=============== =========
coeff value
=============== =... | [
"def",
"window_blackman_harris",
"(",
"N",
")",
":",
"a0",
"=",
"0.35875",
"a1",
"=",
"0.48829",
"a2",
"=",
"0.14128",
"a3",
"=",
"0.01168",
"return",
"_coeff4",
"(",
"N",
",",
"a0",
",",
"a1",
",",
"a2",
",",
"a3",
")"
] | 26.516129 | 0.002347 |
def wrap_apply_async(apply_async_func):
"""Wrap the apply_async function of multiprocessing.pools. Get the function
that will be called and wrap it then add the opencensus context."""
def call(self, func, args=(), kwds={}, **kwargs):
wrapped_func = wrap_task_func(func)
_tracer = execution_c... | [
"def",
"wrap_apply_async",
"(",
"apply_async_func",
")",
":",
"def",
"call",
"(",
"self",
",",
"func",
",",
"args",
"=",
"(",
")",
",",
"kwds",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"wrapped_func",
"=",
"wrap_task_func",
"(",
"func",
")",... | 37.652174 | 0.001126 |
def runGetOutput(cmd, raiseOnFailure=False, encoding=sys.getdefaultencoding()):
'''
runGetOutput - Simply runs a command and returns the output as a string. Use #runGetResults if you need something more complex.
@param cmd <str/list> - String of command and arguments, or list of command... | [
"def",
"runGetOutput",
"(",
"cmd",
",",
"raiseOnFailure",
"=",
"False",
",",
"encoding",
"=",
"sys",
".",
"getdefaultencoding",
"(",
")",
")",
":",
"results",
"=",
"Simple",
".",
"runGetResults",
"(",
"cmd",
",",
"stdout",
"=",
"True",
",",
"stderr",
"="... | 49.446809 | 0.010127 |
def all_cities():
"""
Get a list of all Backpage city names.
Returns:
list of city names as Strings
"""
cities = []
fname = pkg_resources.resource_filename(__name__, 'resources/CityPops.csv')
with open(fname, 'rU') as csvfile:
reader = csv.reader(csvfile, delimiter = ',')
for row in reader:
... | [
"def",
"all_cities",
"(",
")",
":",
"cities",
"=",
"[",
"]",
"fname",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"__name__",
",",
"'resources/CityPops.csv'",
")",
"with",
"open",
"(",
"fname",
",",
"'rU'",
")",
"as",
"csvfile",
":",
"reader",
"="... | 24.266667 | 0.026455 |
def load_model_from_path(model_path, meta=False, **overrides):
"""Load a model from a data directory path. Creates Language class with
pipeline from meta.json and then calls from_disk() with path."""
if not meta:
meta = get_model_meta(model_path)
cls = get_lang_class(meta["lang"])
nlp = cls(... | [
"def",
"load_model_from_path",
"(",
"model_path",
",",
"meta",
"=",
"False",
",",
"*",
"*",
"overrides",
")",
":",
"if",
"not",
"meta",
":",
"meta",
"=",
"get_model_meta",
"(",
"model_path",
")",
"cls",
"=",
"get_lang_class",
"(",
"meta",
"[",
"\"lang\"",
... | 42.210526 | 0.00122 |
def get_history_item_for_tree_iter(self, child_tree_iter):
"""Hands history item for tree iter and compensate if tree item is a dummy item
:param Gtk.TreeIter child_tree_iter: Tree iter of row
:rtype rafcon.core.execution.execution_history.HistoryItem:
:return history tree item:
... | [
"def",
"get_history_item_for_tree_iter",
"(",
"self",
",",
"child_tree_iter",
")",
":",
"history_item",
"=",
"self",
".",
"history_tree_store",
"[",
"child_tree_iter",
"]",
"[",
"self",
".",
"HISTORY_ITEM_STORAGE_ID",
"]",
"if",
"history_item",
"is",
"None",
":",
... | 56.866667 | 0.008074 |
def check_insert_size(data, sample):
"""
check mean insert size for this sample and update
hackersonly.max_inner_mate_distance if need be. This value controls how
far apart mate pairs can be to still be considered for bedtools merging
downstream.
"""
## pipe stats output to grep
cmd1... | [
"def",
"check_insert_size",
"(",
"data",
",",
"sample",
")",
":",
"## pipe stats output to grep",
"cmd1",
"=",
"[",
"ipyrad",
".",
"bins",
".",
"samtools",
",",
"\"stats\"",
",",
"sample",
".",
"files",
".",
"mapped_reads",
"]",
"cmd2",
"=",
"[",
"\"grep\"",... | 40.458333 | 0.011394 |
def top_n_list(lang, n, wordlist='best', ascii_only=False):
"""
Return a frequency list of length `n` in descending order of frequency.
This list contains words from `wordlist`, of the given language.
If `ascii_only`, then only ascii words are considered.
"""
results = []
for word in iter_wo... | [
"def",
"top_n_list",
"(",
"lang",
",",
"n",
",",
"wordlist",
"=",
"'best'",
",",
"ascii_only",
"=",
"False",
")",
":",
"results",
"=",
"[",
"]",
"for",
"word",
"in",
"iter_wordlist",
"(",
"lang",
",",
"wordlist",
")",
":",
"if",
"(",
"not",
"ascii_on... | 37.538462 | 0.002 |
def add_name(self, tax_id, tax_name, source_name=None, source_id=None,
name_class='synonym', is_primary=False, is_classified=None,
execute=True, **ignored):
"""Add a record to the names table corresponding to
``tax_id``. Arguments are as follows:
- tax_id (str... | [
"def",
"add_name",
"(",
"self",
",",
"tax_id",
",",
"tax_name",
",",
"source_name",
"=",
"None",
",",
"source_id",
"=",
"None",
",",
"name_class",
"=",
"'synonym'",
",",
"is_primary",
"=",
"False",
",",
"is_classified",
"=",
"None",
",",
"execute",
"=",
... | 31.339286 | 0.00221 |
def run_xenon_simple(workflow, machine, worker_config):
"""Run a workflow using a single Xenon remote worker.
:param workflow: |Workflow| or |PromisedObject| to evaluate.
:param machine: |Machine| instance.
:param worker_config: Configuration for the pilot job."""
scheduler = Scheduler()
retur... | [
"def",
"run_xenon_simple",
"(",
"workflow",
",",
"machine",
",",
"worker_config",
")",
":",
"scheduler",
"=",
"Scheduler",
"(",
")",
"return",
"scheduler",
".",
"run",
"(",
"xenon_interactive_worker",
"(",
"machine",
",",
"worker_config",
")",
",",
"get_workflow... | 35 | 0.00232 |
def generate(env):
"""Add Builders and construction variables for sun f90 compiler to an
Environment."""
add_all_to_env(env)
fcomp = env.Detect(compilers) or 'f90'
env['FORTRAN'] = fcomp
env['F90'] = fcomp
env['SHFORTRAN'] = '$FORTRAN'
env['SHF90'] = '$F90'
env['SHFORT... | [
"def",
"generate",
"(",
"env",
")",
":",
"add_all_to_env",
"(",
"env",
")",
"fcomp",
"=",
"env",
".",
"Detect",
"(",
"compilers",
")",
"or",
"'f90'",
"env",
"[",
"'FORTRAN'",
"]",
"=",
"fcomp",
"env",
"[",
"'F90'",
"]",
"=",
"fcomp",
"env",
"[",
"'... | 29.928571 | 0.011574 |
def has_authors(edge_data: EdgeData) -> bool:
"""Check if the edge contains author information for its citation."""
return CITATION in edge_data and CITATION_AUTHORS in edge_data[CITATION] and edge_data[CITATION][CITATION_AUTHORS] | [
"def",
"has_authors",
"(",
"edge_data",
":",
"EdgeData",
")",
"->",
"bool",
":",
"return",
"CITATION",
"in",
"edge_data",
"and",
"CITATION_AUTHORS",
"in",
"edge_data",
"[",
"CITATION",
"]",
"and",
"edge_data",
"[",
"CITATION",
"]",
"[",
"CITATION_AUTHORS",
"]"... | 78.666667 | 0.008403 |
def count_snps(mat):
"""
get dstats from the count array and return as a float tuple
"""
## get [aabb, baba, abba, aaab]
snps = np.zeros(4, dtype=np.uint32)
## get concordant (aabb) pis sites
snps[0] = np.uint32(\
mat[0, 5] + mat[0, 10] + mat[0, 15] + \
mat[5, 0] +... | [
"def",
"count_snps",
"(",
"mat",
")",
":",
"## get [aabb, baba, abba, aaab] ",
"snps",
"=",
"np",
".",
"zeros",
"(",
"4",
",",
"dtype",
"=",
"np",
".",
"uint32",
")",
"## get concordant (aabb) pis sites",
"snps",
"[",
"0",
"]",
"=",
"np",
".",
"uint32",
"(... | 29.566667 | 0.018559 |
def get_voronoi_nodes(structure, rad_dict=None, probe_rad=0.1):
"""
Analyze the void space in the input structure using voronoi decomposition
Calls Zeo++ for Voronoi decomposition.
Args:
structure: pymatgen.core.structure.Structure
rad_dict (optional): Dictionary of radii of elements in... | [
"def",
"get_voronoi_nodes",
"(",
"structure",
",",
"rad_dict",
"=",
"None",
",",
"probe_rad",
"=",
"0.1",
")",
":",
"with",
"ScratchDir",
"(",
"'.'",
")",
":",
"name",
"=",
"\"temp_zeo1\"",
"zeo_inp_filename",
"=",
"name",
"+",
"\".cssr\"",
"ZeoCssr",
"(",
... | 41.453333 | 0.000314 |
def format_option(self, option):
"""
No documentation
"""
# The help for each option consists of two parts:
# * the opt strings and metavars
# eg. ("-x", or "-fFILENAME, --file=FILENAME")
# * the user-supplied help string
# eg. ("turn on expert mod... | [
"def",
"format_option",
"(",
"self",
",",
"option",
")",
":",
"# The help for each option consists of two parts:",
"# * the opt strings and metavars",
"# eg. (\"-x\", or \"-fFILENAME, --file=FILENAME\")",
"# * the user-supplied help string",
"# eg. (\"turn on expert mode\", \"read da... | 42.190476 | 0.002206 |
def heartbeat(self):
"""Check The API Is Up.
https://starfighter.readme.io/docs/heartbeat
"""
url = urljoin(self.base_url, 'heartbeat')
return self.session.get(url).json()['ok'] | [
"def",
"heartbeat",
"(",
"self",
")",
":",
"url",
"=",
"urljoin",
"(",
"self",
".",
"base_url",
",",
"'heartbeat'",
")",
"return",
"self",
".",
"session",
".",
"get",
"(",
"url",
")",
".",
"json",
"(",
")",
"[",
"'ok'",
"]"
] | 30.285714 | 0.009174 |
def run(self):
"""
build image inside current environment;
it's expected this may run within (privileged) docker container
Input:
df_dir
image
Output:
BuildResult
built_image_info
image_id
"""
builder ... | [
"def",
"run",
"(",
"self",
")",
":",
"builder",
"=",
"self",
".",
"workflow",
".",
"builder",
"allow_repo_dir_in_dockerignore",
"(",
"builder",
".",
"df_dir",
")",
"logs_gen",
"=",
"self",
".",
"tasker",
".",
"build_image_from_path",
"(",
"builder",
".",
"df... | 33.297297 | 0.001577 |
def decode_html(html):
"""
Converts bytes stream containing an HTML page into Unicode.
Tries to guess character encoding from meta tag of by "chardet" library.
"""
if isinstance(html, unicode):
return html
match = CHARSET_META_TAG_PATTERN.search(html)
if match:
declared_enco... | [
"def",
"decode_html",
"(",
"html",
")",
":",
"if",
"isinstance",
"(",
"html",
",",
"unicode",
")",
":",
"return",
"html",
"match",
"=",
"CHARSET_META_TAG_PATTERN",
".",
"search",
"(",
"html",
")",
"if",
"match",
":",
"declared_encoding",
"=",
"match",
".",... | 32 | 0.000892 |
def surge_handler(response, **kwargs):
"""Error Handler to surface 409 Surge Conflict errors.
Attached as a callback hook on the Request object.
Parameters
response (requests.Response)
The HTTP response from an API request.
**kwargs
Arbitrary keyword arguments.
... | [
"def",
"surge_handler",
"(",
"response",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"response",
".",
"status_code",
"==",
"codes",
".",
"conflict",
":",
"json",
"=",
"response",
".",
"json",
"(",
")",
"errors",
"=",
"json",
".",
"get",
"(",
"'errors'",
... | 29.65 | 0.001634 |
def _vertex_one_color_qubo(x_vars):
"""For each vertex, it should have exactly one color. Generates
the QUBO to enforce this constraint.
Notes
-----
Does not enforce neighboring vertices having different colors.
Ground energy is -1 * |G|, infeasible gap is 1.
"""
Q = {}
for v in x_... | [
"def",
"_vertex_one_color_qubo",
"(",
"x_vars",
")",
":",
"Q",
"=",
"{",
"}",
"for",
"v",
"in",
"x_vars",
":",
"for",
"color",
"in",
"x_vars",
"[",
"v",
"]",
":",
"idx",
"=",
"x_vars",
"[",
"v",
"]",
"[",
"color",
"]",
"Q",
"[",
"(",
"idx",
","... | 25.695652 | 0.001631 |
def stationary_values(self, method='doubling'):
"""
Computes the matrix :math:`P` and scalar :math:`d` that represent
the value function
.. math::
V(x) = x' P x + d
in the infinite horizon case. Also computes the control matrix
:math:`F` from :math:`u = -... | [
"def",
"stationary_values",
"(",
"self",
",",
"method",
"=",
"'doubling'",
")",
":",
"# === simplify notation === #",
"Q",
",",
"R",
",",
"A",
",",
"B",
",",
"N",
",",
"C",
"=",
"self",
".",
"Q",
",",
"self",
".",
"R",
",",
"self",
".",
"A",
",",
... | 33.528302 | 0.001093 |
def override(self, obj):
"""Overrides the plain fields of the dashboard."""
for field in obj.__class__.export_fields:
setattr(self, field, getattr(obj, field)) | [
"def",
"override",
"(",
"self",
",",
"obj",
")",
":",
"for",
"field",
"in",
"obj",
".",
"__class__",
".",
"export_fields",
":",
"setattr",
"(",
"self",
",",
"field",
",",
"getattr",
"(",
"obj",
",",
"field",
")",
")"
] | 46 | 0.010695 |
def terms(order, dim):
"""
Count the number of polynomials in an expansion.
Parameters
----------
order : int
The upper order for the expansion.
dim : int
The number of dimensions of the expansion.
Returns
-------
N : int
The number of terms in an expansion ... | [
"def",
"terms",
"(",
"order",
",",
"dim",
")",
":",
"return",
"int",
"(",
"scipy",
".",
"special",
".",
"comb",
"(",
"order",
"+",
"dim",
",",
"dim",
",",
"1",
")",
")"
] | 23.5 | 0.002273 |
def create_injector(param_name, fun_param_value):
'''Dependency injection with Bottle.
This creates a simple dependency injector that will map
``param_name`` in routes to the value ``fun_param_value()``
each time the route is invoked.
``fun_param_value`` is a closure so that it is lazily evaluated... | [
"def",
"create_injector",
"(",
"param_name",
",",
"fun_param_value",
")",
":",
"class",
"_",
"(",
"object",
")",
":",
"api",
"=",
"2",
"def",
"apply",
"(",
"self",
",",
"callback",
",",
"route",
")",
":",
"if",
"param_name",
"not",
"in",
"inspect",
"."... | 36.515152 | 0.000808 |
def rm_subtitles(path):
""" delete all subtitles in path recursively
"""
sub_exts = ['ass', 'srt', 'sub']
count = 0
for root, dirs, files in os.walk(path):
for f in files:
_, ext = os.path.splitext(f)
ext = ext[1:]
if ext in sub_exts:
p = o... | [
"def",
"rm_subtitles",
"(",
"path",
")",
":",
"sub_exts",
"=",
"[",
"'ass'",
",",
"'srt'",
",",
"'sub'",
"]",
"count",
"=",
"0",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"f",
"in",
"files",
... | 29.6 | 0.002183 |
def add_scm_info(self):
"""Adds SCM-related info."""
scm = get_scm()
if scm:
revision = scm.commit_id
branch = scm.branch_name or revision
else:
revision, branch = 'none', 'none'
self.add_infos(('revision', revision), ('branch', branch)) | [
"def",
"add_scm_info",
"(",
"self",
")",
":",
"scm",
"=",
"get_scm",
"(",
")",
"if",
"scm",
":",
"revision",
"=",
"scm",
".",
"commit_id",
"branch",
"=",
"scm",
".",
"branch_name",
"or",
"revision",
"else",
":",
"revision",
",",
"branch",
"=",
"'none'"... | 29.666667 | 0.014545 |
def _get_asset(file_path):
""" Get the database record for an asset file """
record = model.Image.get(file_path=file_path)
fingerprint = ','.join((utils.file_fingerprint(file_path),
str(RENDITION_VERSION)))
if not record or record.fingerprint != fingerprint:
# Reindex... | [
"def",
"_get_asset",
"(",
"file_path",
")",
":",
"record",
"=",
"model",
".",
"Image",
".",
"get",
"(",
"file_path",
"=",
"file_path",
")",
"fingerprint",
"=",
"','",
".",
"join",
"(",
"(",
"utils",
".",
"file_fingerprint",
"(",
"file_path",
")",
",",
... | 35.276596 | 0.000587 |
def serialize_value_map(self, map_elem, thedict):
"""
Serializes a dictionary of key/value pairs, where the values are
either strings, or Attrib, or PathAttrib objects.
Example::
<variable>
<name>foo</name>
<value>text</value>
</v... | [
"def",
"serialize_value_map",
"(",
"self",
",",
"map_elem",
",",
"thedict",
")",
":",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"(",
"str",
"(",
"k",
")",
",",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"thedict",
".",
"items",
"(",
... | 35.545455 | 0.002491 |
def retrieve_matching_jwk(self, token):
"""Get the signing key by exploring the JWKS endpoint of the OP."""
response_jwks = requests.get(
self.OIDC_OP_JWKS_ENDPOINT,
verify=self.get_settings('OIDC_VERIFY_SSL', True)
)
response_jwks.raise_for_status()
jwks ... | [
"def",
"retrieve_matching_jwk",
"(",
"self",
",",
"token",
")",
":",
"response_jwks",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"OIDC_OP_JWKS_ENDPOINT",
",",
"verify",
"=",
"self",
".",
"get_settings",
"(",
"'OIDC_VERIFY_SSL'",
",",
"True",
")",
")",
"r... | 38.833333 | 0.002094 |
def change_score_for(self, member, delta, member_data=None):
'''
Change the score for a member in the leaderboard by a score delta which can be positive or negative.
@param member [String] Member name.
@param delta [float] Score change.
@param member_data [String] Optional membe... | [
"def",
"change_score_for",
"(",
"self",
",",
"member",
",",
"delta",
",",
"member_data",
"=",
"None",
")",
":",
"self",
".",
"change_score_for_member_in",
"(",
"self",
".",
"leaderboard_name",
",",
"member",
",",
"delta",
",",
"member_data",
")"
] | 46.888889 | 0.009302 |
async def get_oauth_verifier(oauth_token):
"""
Open authorize page in a browser,
print the url if it didn't work
Arguments
---------
oauth_token : str
The oauth token received in :func:`get_oauth_token`
Returns
-------
str
The PIN entered by the user
"""
url... | [
"async",
"def",
"get_oauth_verifier",
"(",
"oauth_token",
")",
":",
"url",
"=",
"\"https://api.twitter.com/oauth/authorize?oauth_token=\"",
"+",
"oauth_token",
"try",
":",
"browser",
"=",
"webbrowser",
".",
"open",
"(",
"url",
")",
"await",
"asyncio",
".",
"sleep",
... | 23.785714 | 0.001443 |
async def clear_state(self, turn_context: TurnContext):
"""
Clears any state currently stored in this state scope.
NOTE: that save_changes must be called in order for the cleared state to be persisted to the underlying store.
:param turn_context: The context object for this turn... | [
"async",
"def",
"clear_state",
"(",
"self",
",",
"turn_context",
":",
"TurnContext",
")",
":",
"if",
"turn_context",
"==",
"None",
":",
"raise",
"TypeError",
"(",
"'BotState.clear_state(): turn_context cannot be None.'",
")",
"# Explicitly setting the hash will mean IsChan... | 47.466667 | 0.011019 |
def plane_lines(plane_origin,
plane_normal,
endpoints,
line_segments=True):
"""
Calculate plane-line intersections
Parameters
---------
plane_origin : (3,) float
Point on plane
plane_normal : (3,) float
Plane normal vector
endp... | [
"def",
"plane_lines",
"(",
"plane_origin",
",",
"plane_normal",
",",
"endpoints",
",",
"line_segments",
"=",
"True",
")",
":",
"endpoints",
"=",
"np",
".",
"asanyarray",
"(",
"endpoints",
")",
"plane_origin",
"=",
"np",
".",
"asanyarray",
"(",
"plane_origin",
... | 34.666667 | 0.000519 |
def ensure_secret():
"""Check if secret key to encryot sessions exists,
generate it otherwise."""
home_dir = os.environ['HOME']
file_name = home_dir + "/.ipcamweb"
if os.path.exists(file_name):
with open(file_name, "r") as s_file:
secret = s_file.readline()
else:
secr... | [
"def",
"ensure_secret",
"(",
")",
":",
"home_dir",
"=",
"os",
".",
"environ",
"[",
"'HOME'",
"]",
"file_name",
"=",
"home_dir",
"+",
"\"/.ipcamweb\"",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"file_name",
")",
":",
"with",
"open",
"(",
"file_name",
... | 33.615385 | 0.002227 |
def remove_container(self, container, v=False, link=False, force=False):
"""
Remove a container. Similar to the ``docker rm`` command.
Args:
container (str): The container to remove
v (bool): Remove the volumes associated with the container
link (bool): Remov... | [
"def",
"remove_container",
"(",
"self",
",",
"container",
",",
"v",
"=",
"False",
",",
"link",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'v'",
":",
"v",
",",
"'link'",
":",
"link",
",",
"'force'",
":",
"force",
"}",
... | 37.714286 | 0.002463 |
def import_mapping(connection_id, mapping):
"""
Import Heroku Connection mapping for given connection.
Args:
connection_id (str): Heroku Connection connection ID.
mapping (dict): Heroku Connect mapping.
Raises:
requests.HTTPError: If an error occurs uploading the mapping.
... | [
"def",
"import_mapping",
"(",
"connection_id",
",",
"mapping",
")",
":",
"url",
"=",
"os",
".",
"path",
".",
"join",
"(",
"settings",
".",
"HEROKU_CONNECT_API_ENDPOINT",
",",
"'connections'",
",",
"connection_id",
",",
"'actions'",
",",
"'import'",
")",
"respo... | 29.590909 | 0.001488 |
def udf(input_type, output_type, strict=True, libraries=None):
'''Define a UDF for BigQuery
Parameters
----------
input_type : List[DataType]
output_type : DataType
strict : bool
Whether or not to put a ``'use strict';`` string at the beginning of
the UDF. Setting to ``False`` i... | [
"def",
"udf",
"(",
"input_type",
",",
"output_type",
",",
"strict",
"=",
"True",
",",
"libraries",
"=",
"None",
")",
":",
"if",
"libraries",
"is",
"None",
":",
"libraries",
"=",
"[",
"]",
"def",
"wrapper",
"(",
"f",
")",
":",
"if",
"not",
"callable",... | 30.40201 | 0.00016 |
def dict_to_table(header, contents):
"""
Convert dict to table
Parameters
----------
header : tuple
Table header. Should have a length of 2.
contents : dict
The key becomes column 1 of table and the
value becomes column 2 of table.
"""
def to_text(row):
n... | [
"def",
"dict_to_table",
"(",
"header",
",",
"contents",
")",
":",
"def",
"to_text",
"(",
"row",
")",
":",
"name",
",",
"value",
"=",
"row",
"m",
"=",
"max_col1_size",
"+",
"1",
"-",
"len",
"(",
"name",
")",
"spacing",
"=",
"' '",
"*",
"m",
"return"... | 29.166667 | 0.000922 |
def delete(self):
""" Removes current SyncItem """
url = SyncList.key.format(clientId=self.clientIdentifier)
url += '/' + str(self.id)
self._server.query(url, self._server._session.delete) | [
"def",
"delete",
"(",
"self",
")",
":",
"url",
"=",
"SyncList",
".",
"key",
".",
"format",
"(",
"clientId",
"=",
"self",
".",
"clientIdentifier",
")",
"url",
"+=",
"'/'",
"+",
"str",
"(",
"self",
".",
"id",
")",
"self",
".",
"_server",
".",
"query"... | 43.2 | 0.009091 |
def find_suggestions(filelist):
"""Suggest MANIFEST.in patterns for missing files."""
suggestions = set()
unknowns = []
for filename in filelist:
if os.path.isdir(filename):
# it's impossible to add empty directories via MANIFEST.in anyway,
# and non-empty directories wil... | [
"def",
"find_suggestions",
"(",
"filelist",
")",
":",
"suggestions",
"=",
"set",
"(",
")",
"unknowns",
"=",
"[",
"]",
"for",
"filename",
"in",
"filelist",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"filename",
")",
":",
"# it's impossible to add empt... | 39.388889 | 0.001377 |
def pattern_match(data, values, level=None, regexp=False, has_nan=True):
"""
matching of model/scenario names, variables, regions, and meta columns to
pseudo-regex (if `regexp == False`) for filtering (str, int, bool)
"""
matches = np.array([False] * len(data))
if not isinstance(values, collecti... | [
"def",
"pattern_match",
"(",
"data",
",",
"values",
",",
"level",
"=",
"None",
",",
"regexp",
"=",
"False",
",",
"has_nan",
"=",
"True",
")",
":",
"matches",
"=",
"np",
".",
"array",
"(",
"[",
"False",
"]",
"*",
"len",
"(",
"data",
")",
")",
"if"... | 39.913043 | 0.001064 |
def fbcorr(imgs, filters):
n_imgs, n_rows, n_cols, n_channels = imgs.shape
n_filters, height, width, n_ch2 = filters.shape
output = numpy.zeros((n_imgs, n_filters, (n_rows - height + 1),(n_cols - width + 1)))
"omp parallel for private(rr,cc,hh,ww,jj,ff,imgval, filterval)"
for ii in xrange(n_imgs):
... | [
"def",
"fbcorr",
"(",
"imgs",
",",
"filters",
")",
":",
"n_imgs",
",",
"n_rows",
",",
"n_cols",
",",
"n_channels",
"=",
"imgs",
".",
"shape",
"n_filters",
",",
"height",
",",
"width",
",",
"n_ch2",
"=",
"filters",
".",
"shape",
"output",
"=",
"numpy",
... | 51.5 | 0.014303 |
def furtherArgsProcessing(args):
"""
Converts args, and deals with incongruities that argparse couldn't handle
"""
if isinstance(args, str):
unprocessed = args.strip().split(' ')
if unprocessed[0] == 'cyther':
del unprocessed[0]
args = parser.parse_args(unprocessed)._... | [
"def",
"furtherArgsProcessing",
"(",
"args",
")",
":",
"if",
"isinstance",
"(",
"args",
",",
"str",
")",
":",
"unprocessed",
"=",
"args",
".",
"strip",
"(",
")",
".",
"split",
"(",
"' '",
")",
"if",
"unprocessed",
"[",
"0",
"]",
"==",
"'cyther'",
":"... | 30.461538 | 0.002448 |
def idfdiffs(idf1, idf2):
"""return the diffs between the two idfs"""
thediffs = {}
keys = idf1.model.dtls # undocumented variable
for akey in keys:
idfobjs1 = idf1.idfobjects[akey]
idfobjs2 = idf2.idfobjects[akey]
names = set([getobjname(i) for i in idfobjs1] +
... | [
"def",
"idfdiffs",
"(",
"idf1",
",",
"idf2",
")",
":",
"thediffs",
"=",
"{",
"}",
"keys",
"=",
"idf1",
".",
"model",
".",
"dtls",
"# undocumented variable",
"for",
"akey",
"in",
"keys",
":",
"idfobjs1",
"=",
"idf1",
".",
"idfobjects",
"[",
"akey",
"]",... | 47.472222 | 0.010894 |
def dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False,
unsafe_hash=False, frozen=False):
"""Returns the same class as was passed in, with dunder methods
added based on the fields defined in the class.
Examines PEP 526 __annotations__ to determine fields.
If init is true,... | [
"def",
"dataclass",
"(",
"_cls",
"=",
"None",
",",
"*",
",",
"init",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"eq",
"=",
"True",
",",
"order",
"=",
"False",
",",
"unsafe_hash",
"=",
"False",
",",
"frozen",
"=",
"False",
")",
":",
"def",
"wrap"... | 38.375 | 0.001059 |
def process_calibration(self, save=False):
"""processes the data gathered in a calibration run (does not work if multiple
calibrations), returns resultant dB"""
if not self.save_data:
raise Exception("Runner must be set to save when run, to be able to process")
... | [
"def",
"process_calibration",
"(",
"self",
",",
"save",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"save_data",
":",
"raise",
"Exception",
"(",
"\"Runner must be set to save when run, to be able to process\"",
")",
"vfunc",
"=",
"np",
".",
"vectorize",
"(",... | 43.233333 | 0.008296 |
def set_name(self, name):
"""Set a client name."""
if not name:
name = ''
self._client['config']['name'] = name
yield from self._server.client_name(self.identifier, name) | [
"def",
"set_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"name",
":",
"name",
"=",
"''",
"self",
".",
"_client",
"[",
"'config'",
"]",
"[",
"'name'",
"]",
"=",
"name",
"yield",
"from",
"self",
".",
"_server",
".",
"client_name",
"(",
"se... | 34.833333 | 0.009346 |
def on_train_begin(self, **kwargs:Any)->None:
"Initializes the best value."
self.best = float('inf') if self.operator == np.less else -float('inf') | [
"def",
"on_train_begin",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"best",
"=",
"float",
"(",
"'inf'",
")",
"if",
"self",
".",
"operator",
"==",
"np",
".",
"less",
"else",
"-",
"float",
"(",
"'inf'",
"... | 53.666667 | 0.02454 |
def list_pkgs(versions_as_list=False, **kwargs):
'''
.. versionchanged: 2016.3.0
List the packages currently installed as a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(vers... | [
"def",
"list_pkgs",
"(",
"versions_as_list",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"versions_as_list",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"versions_as_list",
")",
"# not yet implemented or not applicable",
"if",
"any",
"(",
... | 28.959184 | 0.000682 |
def maybe_append_oov_vectors(embeddings, num_oov_buckets):
"""Adds zero vectors for oov buckets if num_oov_buckets > 0.
Since we are assigning zero vectors, adding more that one oov bucket is only
meaningful if we perform fine-tuning.
Args:
embeddings: Embeddings to extend.
num_oov_buckets: Number of ... | [
"def",
"maybe_append_oov_vectors",
"(",
"embeddings",
",",
"num_oov_buckets",
")",
":",
"num_embeddings",
"=",
"np",
".",
"shape",
"(",
"embeddings",
")",
"[",
"0",
"]",
"embedding_dim",
"=",
"np",
".",
"shape",
"(",
"embeddings",
")",
"[",
"1",
"]",
"embe... | 37.857143 | 0.009208 |
def next_permutation(tab):
"""find the next permutation of tab in the lexicographical order
:param tab: table with n elements from an ordered set
:modifies: table to next permutation
:returns: False if permutation is already lexicographical maximal
:complexity: O(n)
"""
n = len(tab)
piv... | [
"def",
"next_permutation",
"(",
"tab",
")",
":",
"n",
"=",
"len",
"(",
"tab",
")",
"pivot",
"=",
"None",
"# find pivot",
"for",
"i",
"in",
"range",
"(",
"n",
"-",
"1",
")",
":",
"if",
"tab",
"[",
"i",
"]",
"<",
"tab",
"[",
"i",
"+",
"1",
"]",... | 33.269231 | 0.001124 |
def make_trans_matrix(y, n_classes, dtype=np.float64):
"""Make a sparse transition matrix for y.
Takes a label sequence y and returns an indicator matrix with n_classes²
columns of the label transitions in y: M[i, j, k] means y[i-1] == j and
y[i] == k. The first row will be empty.
"""
indices =... | [
"def",
"make_trans_matrix",
"(",
"y",
",",
"n_classes",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
":",
"indices",
"=",
"np",
".",
"empty",
"(",
"len",
"(",
"y",
")",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"for",
"i",
"in",
"six",
".",
... | 36 | 0.001592 |
def GetInstance(self, InstanceName, LocalOnly=None, IncludeQualifiers=None,
IncludeClassOrigin=None, PropertyList=None, **extra):
# pylint: disable=invalid-name,line-too-long
"""
Retrieve an instance.
This method performs the GetInstance operation
(see :term:... | [
"def",
"GetInstance",
"(",
"self",
",",
"InstanceName",
",",
"LocalOnly",
"=",
"None",
",",
"IncludeQualifiers",
"=",
"None",
",",
"IncludeClassOrigin",
"=",
"None",
",",
"PropertyList",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"# pylint: disable=invalid... | 42.517442 | 0.000534 |
def _parse_template_or_argument(self):
"""Parse a template or argument at the head of the wikicode string."""
self._head += 2
braces = 2
while self._read() == "{":
self._head += 1
braces += 1
has_content = False
self._push()
while braces:
... | [
"def",
"_parse_template_or_argument",
"(",
"self",
")",
":",
"self",
".",
"_head",
"+=",
"2",
"braces",
"=",
"2",
"while",
"self",
".",
"_read",
"(",
")",
"==",
"\"{\"",
":",
"self",
".",
"_head",
"+=",
"1",
"braces",
"+=",
"1",
"has_content",
"=",
"... | 32.257143 | 0.00172 |
def db_create(name, user=None, password=None, host=None, port=None):
'''
Create a database
name
Database name to create
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI ... | [
"def",
"db_create",
"(",
"name",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"if",
"db_exists",
"(",
"name",
",",
"user",
",",
"password",
",",
"host",
",",
"port",
")",
":... | 21.875 | 0.001368 |
def append(args):
"""
%prog append csvfile [tag]
Append a column with fixed value. If tag is missing then just append the
filename.
"""
p = OptionParser(append.__doc__)
p.set_sep()
p.set_outfile()
opts, args = p.parse_args(args)
nargs = len(args)
if nargs not in (1, 2):
... | [
"def",
"append",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"append",
".",
"__doc__",
")",
"p",
".",
"set_sep",
"(",
")",
"p",
".",
"set_outfile",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"nargs",
"... | 24.333333 | 0.001647 |
async def edit(self, *, reason=None, **fields):
"""|coro|
Edits the role.
You must have the :attr:`~Permissions.manage_roles` permission to
use this.
All fields are optional.
Parameters
-----------
name: :class:`str`
The new role name to ch... | [
"async",
"def",
"edit",
"(",
"self",
",",
"*",
",",
"reason",
"=",
"None",
",",
"*",
"*",
"fields",
")",
":",
"position",
"=",
"fields",
".",
"get",
"(",
"'position'",
")",
"if",
"position",
"is",
"not",
"None",
":",
"await",
"self",
".",
"_move",
... | 33.372881 | 0.001973 |
def est_res(signals):
"""
Estimate the resolution of each signal in a multi-channel signal in
bits. Maximum of 32 bits.
Parameters
----------
signals : numpy array, or list
A 2d numpy array representing a uniform multichannel signal, or
a list of 1d numpy arrays representing mul... | [
"def",
"est_res",
"(",
"signals",
")",
":",
"res_levels",
"=",
"np",
".",
"power",
"(",
"2",
",",
"np",
".",
"arange",
"(",
"0",
",",
"33",
")",
")",
"# Expanded sample signals. List of numpy arrays",
"if",
"isinstance",
"(",
"signals",
",",
"list",
")",
... | 29.407407 | 0.002438 |
def clone_rtcpath_update_rt_as(path, new_rt_as):
"""Clones given RT NLRI `path`, and updates it with new RT_NLRI AS.
Parameters:
- `path`: (Path) RT_NLRI path
- `new_rt_as`: AS value of cloned paths' RT_NLRI
"""
assert path and new_rt_as
if not path or path.route_family ... | [
"def",
"clone_rtcpath_update_rt_as",
"(",
"path",
",",
"new_rt_as",
")",
":",
"assert",
"path",
"and",
"new_rt_as",
"if",
"not",
"path",
"or",
"path",
".",
"route_family",
"!=",
"RF_RTC_UC",
":",
"raise",
"ValueError",
"(",
"'Expected RT_NLRI path'",
")",
"old_n... | 43.866667 | 0.001488 |
def status_codes_chart():
"""Chart for status codes."""
stats = status_codes_stats()
chart_options = {
'chart': {
'type': 'pie'
},
'title': {
'text': ''
},
'subtitle': {
'text': ''
},
'tooltip': {
'formatt... | [
"def",
"status_codes_chart",
"(",
")",
":",
"stats",
"=",
"status_codes_stats",
"(",
")",
"chart_options",
"=",
"{",
"'chart'",
":",
"{",
"'type'",
":",
"'pie'",
"}",
",",
"'title'",
":",
"{",
"'text'",
":",
"''",
"}",
",",
"'subtitle'",
":",
"{",
"'te... | 27.577778 | 0.000778 |
def database_remove_tags(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /database-xxxx/removeTags API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Tags#API-method%3A-%2Fclass-xxxx%2FremoveTags
"""
return DXHTTPRequest('/%s/removeTags' % o... | [
"def",
"database_remove_tags",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/removeTags'",
"%",
"object_id",
",",
"input_params",
",",
"always_re... | 53.428571 | 0.010526 |
def update(self, obj, size):
'''Update this profile.
'''
self.number += 1
self.total += size
if self.high < size: # largest
self.high = size
try: # prefer using weak ref
self.objref, self.weak = Weakref.ref(obj), True
except Type... | [
"def",
"update",
"(",
"self",
",",
"obj",
",",
"size",
")",
":",
"self",
".",
"number",
"+=",
"1",
"self",
".",
"total",
"+=",
"size",
"if",
"self",
".",
"high",
"<",
"size",
":",
"# largest",
"self",
".",
"high",
"=",
"size",
"try",
":",
"# pref... | 33.363636 | 0.02122 |
def _encode_resp(self, value):
"""Dynamically build the RESP payload based upon the list provided.
:param mixed value: The list of command parts to encode
:rtype: bytes
"""
if isinstance(value, bytes):
return b''.join(
[b'$',
ascii(l... | [
"def",
"_encode_resp",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"return",
"b''",
".",
"join",
"(",
"[",
"b'$'",
",",
"ascii",
"(",
"len",
"(",
"value",
")",
")",
".",
"encode",
"(",
"'ascii'",
... | 41.125 | 0.00198 |
def set_ssh_port(port=22):
'''
Enable SSH on a user defined port
CLI Example:
.. code-block:: bash
salt '*' ilo.set_ssh_port 2222
'''
_current = global_settings()
if _current['Global Settings']['SSH_PORT']['VALUE'] == port:
return True
_xml = """<RIBCL VERSION="2.0">... | [
"def",
"set_ssh_port",
"(",
"port",
"=",
"22",
")",
":",
"_current",
"=",
"global_settings",
"(",
")",
"if",
"_current",
"[",
"'Global Settings'",
"]",
"[",
"'SSH_PORT'",
"]",
"[",
"'VALUE'",
"]",
"==",
"port",
":",
"return",
"True",
"_xml",
"=",
"\"\"\"... | 26.307692 | 0.00141 |
def fuzz_string(seed_str, runs=100, fuzz_factor=50):
"""A random fuzzer for a simulated text viewer application.
It takes a string as seed and generates <runs> variant of it.
:param seed_str: the string to use as seed for fuzzing.
:param runs: number of fuzzed variants to supply.
:param fuzz_facto... | [
"def",
"fuzz_string",
"(",
"seed_str",
",",
"runs",
"=",
"100",
",",
"fuzz_factor",
"=",
"50",
")",
":",
"buf",
"=",
"bytearray",
"(",
"seed_str",
",",
"encoding",
"=",
"\"utf8\"",
")",
"variants",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"runs... | 38.166667 | 0.00142 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.