text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _payload_to_dict(self):
"""When an error status the payload is holding an AsyncException that
is converted to a serializable dict.
"""
if self.status != self.ERROR or not self.payload:
return self.payload
import traceback
return {
"error": se... | [
"def",
"_payload_to_dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"!=",
"self",
".",
"ERROR",
"or",
"not",
"self",
".",
"payload",
":",
"return",
"self",
".",
"payload",
"import",
"traceback",
"return",
"{",
"\"error\"",
":",
"self",
".",
... | 32.142857 | 16.571429 |
def update(self,
stats,
duration=3):
"""Display stats to stdout.
Refresh every duration second.
"""
for plugin, attribute in self.plugins_list:
# Check if the plugin exist and is enable
if plugin in stats.getPluginsList() and \
... | [
"def",
"update",
"(",
"self",
",",
"stats",
",",
"duration",
"=",
"3",
")",
":",
"for",
"plugin",
",",
"attribute",
"in",
"self",
".",
"plugins_list",
":",
"# Check if the plugin exist and is enable",
"if",
"plugin",
"in",
"stats",
".",
"getPluginsList",
"(",
... | 37.607143 | 16.035714 |
def subspaces(self, expressions_list=None, dimensions=None, exclude=None, **kwargs):
"""Generate a Subspaces object, based on a custom list of expressions or all possible combinations based on
dimension
:param expressions_list: list of list of expressions, where the inner list defines the subsp... | [
"def",
"subspaces",
"(",
"self",
",",
"expressions_list",
"=",
"None",
",",
"dimensions",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"dimensions",
"is",
"not",
"None",
":",
"expressions_list",
"=",
"list",
"(",
"... | 57.297297 | 25.837838 |
def nn_allocmsg(size, type):
"allocate a message"
pointer = _nn_allocmsg(size, type)
if pointer is None:
return None
return _create_message(pointer, size) | [
"def",
"nn_allocmsg",
"(",
"size",
",",
"type",
")",
":",
"pointer",
"=",
"_nn_allocmsg",
"(",
"size",
",",
"type",
")",
"if",
"pointer",
"is",
"None",
":",
"return",
"None",
"return",
"_create_message",
"(",
"pointer",
",",
"size",
")"
] | 28.833333 | 11.5 |
def orcid_uri_to_orcid(value):
"Strip the uri schema from the start of ORCID URL strings"
if value is None:
return value
replace_values = ['http://orcid.org/', 'https://orcid.org/']
for replace_value in replace_values:
value = value.replace(replace_value, '')
return value | [
"def",
"orcid_uri_to_orcid",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"value",
"replace_values",
"=",
"[",
"'http://orcid.org/'",
",",
"'https://orcid.org/'",
"]",
"for",
"replace_value",
"in",
"replace_values",
":",
"value",
"=",
"val... | 37.625 | 15.875 |
def run(engine, parameters, components_paths=None, requisite_components=None, visible_components=None):
"""
Starts the Application.
:param engine: Engine.
:type engine: QObject
:param parameters: Command line parameters.
:type parameters: tuple
:param components_paths: Components components... | [
"def",
"run",
"(",
"engine",
",",
"parameters",
",",
"components_paths",
"=",
"None",
",",
"requisite_components",
"=",
"None",
",",
"visible_components",
"=",
"None",
")",
":",
"# Command line parameters handling.",
"RuntimeGlobals",
".",
"parameters",
",",
"Runtim... | 59.018405 | 35.165644 |
def reduce_vertex(self, name1, *names):
"""treat name1, name2, ... as same point.
name2.alias, name3.alias, ... are merged with name1.alias
the key name2, name3, ... in self.vertices are kept and mapped to
same Vertex instance as name1
"""
v = self.vertices[name1]
... | [
"def",
"reduce_vertex",
"(",
"self",
",",
"name1",
",",
"*",
"names",
")",
":",
"v",
"=",
"self",
".",
"vertices",
"[",
"name1",
"]",
"for",
"n",
"in",
"names",
":",
"w",
"=",
"self",
".",
"vertices",
"[",
"n",
"]",
"v",
".",
"alias",
".",
"upd... | 36.461538 | 11.846154 |
def create_prefetch(self, addresses):
"""Create futures needed before starting the process of reading the
address's value from the merkle tree.
Args:
addresses (list of str): addresses in the txn's inputs that
aren't in any base context (or any in the chain).
... | [
"def",
"create_prefetch",
"(",
"self",
",",
"addresses",
")",
":",
"with",
"self",
".",
"_lock",
":",
"for",
"add",
"in",
"addresses",
":",
"self",
".",
"_state",
"[",
"add",
"]",
"=",
"_ContextFuture",
"(",
"address",
"=",
"add",
",",
"wait_for_tree",
... | 38.846154 | 18.846154 |
def link_curves(*args, **kwargs):
""" Links the input curves together.
The end control point of the curve k has to be the same with the start control point of the curve k + 1.
Keyword Arguments:
* ``tol``: tolerance value for checking equality. *Default: 10e-8*
* ``validate``: flag to enab... | [
"def",
"link_curves",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get keyword arguments",
"tol",
"=",
"kwargs",
".",
"get",
"(",
"'tol'",
",",
"10e-8",
")",
"validate",
"=",
"kwargs",
".",
"get",
"(",
"'validate'",
",",
"False",
")",
"# Val... | 36.830508 | 21.59322 |
def execute(cls, cmd, stdin_payload=None, **kwargs):
"""Execute a command via subprocess.Popen and returns the stdio.
:param string|list cmd: A list or string representing the command to run.
:param string stdin_payload: A string representing the stdin payload, if any, to send.
:param **kwargs: Additio... | [
"def",
"execute",
"(",
"cls",
",",
"cmd",
",",
"stdin_payload",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"process",
"=",
"cls",
".",
"open_process",
"(",
"cmd",
"=",
"cmd",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"s... | 55.041667 | 27.333333 |
def current_position(self):
"""Return a tuple of (start, end)."""
token = self.tokenizer.peek(0)
if token:
return token.start, token.end
return self.tokenizer.position, self.tokenizer.position + 1 | [
"def",
"current_position",
"(",
"self",
")",
":",
"token",
"=",
"self",
".",
"tokenizer",
".",
"peek",
"(",
"0",
")",
"if",
"token",
":",
"return",
"token",
".",
"start",
",",
"token",
".",
"end",
"return",
"self",
".",
"tokenizer",
".",
"position",
... | 33.571429 | 15.142857 |
def count_consonants(text):
"""Count number of occurrences of consonants in a given string"""
count = 0
for i in text:
if i.lower() in config.AVRO_CONSONANTS:
count += 1
return count | [
"def",
"count_consonants",
"(",
"text",
")",
":",
"count",
"=",
"0",
"for",
"i",
"in",
"text",
":",
"if",
"i",
".",
"lower",
"(",
")",
"in",
"config",
".",
"AVRO_CONSONANTS",
":",
"count",
"+=",
"1",
"return",
"count"
] | 30.285714 | 15.857143 |
def load_template_help(builtin):
"""Loads the help for a given template"""
help_file = "templates/%s-help.yml" % builtin
help_file = resource_filename(__name__, help_file)
help_obj = {}
if os.path.exists(help_file):
help_data = yaml.safe_load(open(help_file))
if 'name' in help_data:... | [
"def",
"load_template_help",
"(",
"builtin",
")",
":",
"help_file",
"=",
"\"templates/%s-help.yml\"",
"%",
"builtin",
"help_file",
"=",
"resource_filename",
"(",
"__name__",
",",
"help_file",
")",
"help_obj",
"=",
"{",
"}",
"if",
"os",
".",
"path",
".",
"exist... | 29.833333 | 16.888889 |
def _default_interface(self, route_output=None):
"""
:param route_output: For mocking actual output
"""
if not route_output:
out, __, __ = exec_cmd('/sbin/ip route')
lines = out.splitlines()
else:
lines = route_output.split("\n")
for l... | [
"def",
"_default_interface",
"(",
"self",
",",
"route_output",
"=",
"None",
")",
":",
"if",
"not",
"route_output",
":",
"out",
",",
"__",
",",
"__",
"=",
"exec_cmd",
"(",
"'/sbin/ip route'",
")",
"lines",
"=",
"out",
".",
"splitlines",
"(",
")",
"else",
... | 31.533333 | 11.666667 |
def expanding_stdize(obj, **kwargs):
"""Standardize a pandas object column-wise on expanding window.
**kwargs -> passed to `obj.expanding`
Example
-------
df = pd.DataFrame(np.random.randn(10, 3))
print(expanding_stdize(df, min_periods=5))
0 1 2
0 ... | [
"def",
"expanding_stdize",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"(",
"obj",
"-",
"obj",
".",
"expanding",
"(",
"*",
"*",
"kwargs",
")",
".",
"mean",
"(",
")",
")",
"/",
"(",
"obj",
".",
"expanding",
"(",
"*",
"*",
"kwargs",
... | 29.4 | 12.76 |
def parse_arguments(kwargs):
"""Function that parses PrettyPrinter arguments.
Detects which aesthetics are mapped to which layers
and collects user-provided values.
Parameters
----------
kwargs: dict
The keyword arguments to PrettyPrinter.
Returns
-------
dict, dict
... | [
"def",
"parse_arguments",
"(",
"kwargs",
")",
":",
"aesthetics",
"=",
"{",
"}",
"values",
"=",
"{",
"}",
"for",
"aes",
"in",
"AESTHETICS",
":",
"if",
"aes",
"in",
"kwargs",
":",
"aesthetics",
"[",
"aes",
"]",
"=",
"kwargs",
"[",
"aes",
"]",
"val_name... | 30.12 | 18.16 |
def create(cls, *args, **kwargs) -> 'Entity':
"""Create a new record in the repository.
Also performs unique validations before creating the entity
:param args: positional arguments for the entity
:param kwargs: keyword arguments for the entity
"""
logger.debug(
... | [
"def",
"create",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"'Entity'",
":",
"logger",
".",
"debug",
"(",
"f'Creating new `{cls.__name__}` object using data {kwargs}'",
")",
"model_cls",
"=",
"repo_factory",
".",
"get_model",
"(",
"cls",
... | 34.468085 | 19.787234 |
def merge(self, df: pd.DataFrame, on: str, how: str="outer", **kwargs):
"""
Set the main dataframe from the current dataframe and the passed
dataframe
:param df: the pandas dataframe to merge
:type df: pd.DataFrame
:param on: param for ``pd.merge``
:type on: str
... | [
"def",
"merge",
"(",
"self",
",",
"df",
":",
"pd",
".",
"DataFrame",
",",
"on",
":",
"str",
",",
"how",
":",
"str",
"=",
"\"outer\"",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"df",
"=",
"pd",
".",
"merge",
"(",
"self",
".",
"df",
",",
... | 37.055556 | 17.388889 |
def receive_trial_result(self, parameter_id, parameters, value):
""" Record an observation of the objective function.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
"""... | [
"def",
"receive_trial_result",
"(",
"self",
",",
"parameter_id",
",",
"parameters",
",",
"value",
")",
":",
"reward",
"=",
"extract_scalar_reward",
"(",
"value",
")",
"if",
"parameter_id",
"not",
"in",
"self",
".",
"total_data",
":",
"raise",
"RuntimeError",
"... | 33.227273 | 19.727273 |
def _get_stack_info_for_trace(
self,
frames,
library_frame_context_lines=None,
in_app_frame_context_lines=None,
with_locals=True,
locals_processor_func=None,
):
"""If the stacktrace originates within the elasticapm module, it will skip
frames until som... | [
"def",
"_get_stack_info_for_trace",
"(",
"self",
",",
"frames",
",",
"library_frame_context_lines",
"=",
"None",
",",
"in_app_frame_context_lines",
"=",
"None",
",",
"with_locals",
"=",
"True",
",",
"locals_processor_func",
"=",
"None",
",",
")",
":",
"return",
"l... | 37.952381 | 15.52381 |
def _base_signup_form_class():
"""
Currently, we inherit from the custom form, if any. This is all
not very elegant, though it serves a purpose:
- There are two signup forms: one for local accounts, and one for
social accounts
- Both share a common base (BaseSignupForm)
- Given the above... | [
"def",
"_base_signup_form_class",
"(",
")",
":",
"if",
"not",
"app_settings",
".",
"SIGNUP_FORM_CLASS",
":",
"return",
"_DummyCustomSignupForm",
"try",
":",
"fc_module",
",",
"fc_classname",
"=",
"app_settings",
".",
"SIGNUP_FORM_CLASS",
".",
"rsplit",
"(",
"'.'",
... | 44.275 | 21.225 |
def list(self):
"""
Run the FTP LIST command, and update the state.
"""
logger.debug('Sending FTP list command.')
self.state['file_list'] = []
self.state['dir_list'] = []
self.client.retrlines('LIST', self._process_list) | [
"def",
"list",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Sending FTP list command.'",
")",
"self",
".",
"state",
"[",
"'file_list'",
"]",
"=",
"[",
"]",
"self",
".",
"state",
"[",
"'dir_list'",
"]",
"=",
"[",
"]",
"self",
".",
"client",
"... | 34.125 | 9.875 |
def attribute(element, attribute, default=None):
"""
Returns the value of an attribute, or a default if it's not defined
:param element: The XML Element object
:type element: etree._Element
:param attribute: The name of the attribute to evaluate
:type attribute: basestring
:param default... | [
"def",
"attribute",
"(",
"element",
",",
"attribute",
",",
"default",
"=",
"None",
")",
":",
"attribute_value",
"=",
"element",
".",
"get",
"(",
"attribute",
")",
"return",
"attribute_value",
"if",
"attribute_value",
"is",
"not",
"None",
"else",
"default"
] | 35.214286 | 19.071429 |
def libvlc_vlm_set_enabled(p_instance, psz_name, b_enabled):
'''Enable or disable a media (VOD or broadcast).
@param p_instance: the instance.
@param psz_name: the media to work on.
@param b_enabled: the new status.
@return: 0 on success, -1 on error.
'''
f = _Cfunctions.get('libvlc_vlm_set_... | [
"def",
"libvlc_vlm_set_enabled",
"(",
"p_instance",
",",
"psz_name",
",",
"b_enabled",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_vlm_set_enabled'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_vlm_set_enabled'",
",",
"(",
"(",
"1",
",... | 47.545455 | 15 |
def get_element_mass_dictionary(self):
"""
Determine the masses of elements in the package and return as a
dictionary.
:returns: Dictionary of element symbols and masses. [kg]
"""
element_symbols = self.material.elements
element_masses = self.get_element_masses(... | [
"def",
"get_element_mass_dictionary",
"(",
"self",
")",
":",
"element_symbols",
"=",
"self",
".",
"material",
".",
"elements",
"element_masses",
"=",
"self",
".",
"get_element_masses",
"(",
")",
"return",
"{",
"s",
":",
"m",
"for",
"s",
",",
"m",
"in",
"zi... | 31.833333 | 20.5 |
def apply_tag_sets(tag_sets, selection):
"""All servers match a list of tag sets.
tag_sets is a list of dicts. The empty tag set {} matches any server,
and may be provided at the end of the list as a fallback. So
[{'a': 'value'}, {}] expresses a preference for servers tagged
{'a': 'value'}, but acc... | [
"def",
"apply_tag_sets",
"(",
"tag_sets",
",",
"selection",
")",
":",
"for",
"tag_set",
"in",
"tag_sets",
":",
"with_tag_set",
"=",
"apply_single_tag_set",
"(",
"tag_set",
",",
"selection",
")",
"if",
"with_tag_set",
":",
"return",
"with_tag_set",
"return",
"sel... | 38.133333 | 19 |
def get_destinations(cls, domain, source):
"""Retrieve forward information."""
forwards = cls.list(domain, {'items_per_page': 500})
for fwd in forwards:
if fwd['source'] == source:
return fwd['destinations']
return [] | [
"def",
"get_destinations",
"(",
"cls",
",",
"domain",
",",
"source",
")",
":",
"forwards",
"=",
"cls",
".",
"list",
"(",
"domain",
",",
"{",
"'items_per_page'",
":",
"500",
"}",
")",
"for",
"fwd",
"in",
"forwards",
":",
"if",
"fwd",
"[",
"'source'",
... | 33.875 | 12.5 |
def savePattern(self):
"""Save internal RAM pattern to flash
"""
if ( self.dev == None ): return ''
buf = [REPORT_ID, ord('W'), 0xBE, 0xEF, 0xCA, 0xFE, 0, 0, 0]
return self.write(buf); | [
"def",
"savePattern",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"dev",
"==",
"None",
")",
":",
"return",
"''",
"buf",
"=",
"[",
"REPORT_ID",
",",
"ord",
"(",
"'W'",
")",
",",
"0xBE",
",",
"0xEF",
",",
"0xCA",
",",
"0xFE",
",",
"0",
",",
... | 36.666667 | 9.5 |
def duplicate(self):
'''
Returns a copy of the current Line, including its taxes and discounts
@returns: Line.
'''
instance = self.__class__(name=self.name, description=self.description,
unit=self.unit, quantity=self.quantity,
... | [
"def",
"duplicate",
"(",
"self",
")",
":",
"instance",
"=",
"self",
".",
"__class__",
"(",
"name",
"=",
"self",
".",
"name",
",",
"description",
"=",
"self",
".",
"description",
",",
"unit",
"=",
"self",
".",
"unit",
",",
"quantity",
"=",
"self",
"."... | 46.5 | 24.071429 |
def setInitialCenters(self, centers, weights):
"""
Set initial centers. Should be set before calling trainOn.
"""
self._model = StreamingKMeansModel(centers, weights)
return self | [
"def",
"setInitialCenters",
"(",
"self",
",",
"centers",
",",
"weights",
")",
":",
"self",
".",
"_model",
"=",
"StreamingKMeansModel",
"(",
"centers",
",",
"weights",
")",
"return",
"self"
] | 35.5 | 12.166667 |
def subproductPath(self, ext):
"""Makes a subproduct filename by appending 'ext' to the subproduct directory.
Returns a (filename,fullpath) tuple."""
ext = ext.lstrip("-")
basename = os.path.join(os.path.basename(self.dp.subproduct_dir()), ext)
fullpath = os.path.join(self.dp.sub... | [
"def",
"subproductPath",
"(",
"self",
",",
"ext",
")",
":",
"ext",
"=",
"ext",
".",
"lstrip",
"(",
"\"-\"",
")",
"basename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"dp",
".",
"subproduct_dir"... | 52.428571 | 12.857143 |
def doc_to_html(doc, doc_format="ROBOT"):
"""Convert documentation to HTML"""
from robot.libdocpkg.htmlwriter import DocToHtml
return DocToHtml(doc_format)(doc) | [
"def",
"doc_to_html",
"(",
"doc",
",",
"doc_format",
"=",
"\"ROBOT\"",
")",
":",
"from",
"robot",
".",
"libdocpkg",
".",
"htmlwriter",
"import",
"DocToHtml",
"return",
"DocToHtml",
"(",
"doc_format",
")",
"(",
"doc",
")"
] | 42.25 | 4 |
def interruptible_sleep(t, event=None):
"""
Sleeps for a specified duration, optionally stopping early for event.
Returns True if interrupted
"""
log.info("sleeping %s", t)
if event is None:
time.sleep(t)
return False
else:
return not event.wait(t) | [
"def",
"interruptible_sleep",
"(",
"t",
",",
"event",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"sleeping %s\"",
",",
"t",
")",
"if",
"event",
"is",
"None",
":",
"time",
".",
"sleep",
"(",
"t",
")",
"return",
"False",
"else",
":",
"return",
... | 22.307692 | 17.692308 |
def getTaskHelp(_Task):
r"""Gets help on the given task member.
"""
Ret = []
for k in ['name', 'desc']:
v = _Task.Config.get(k)
if v is not None:
Ret.append('%s: %s' % (k, v))
Args = _Task.Args
if Args:
Ret.append('\nArgs:')
for argName, Arg in Args.items():
Ret.append(' %s... | [
"def",
"getTaskHelp",
"(",
"_Task",
")",
":",
"Ret",
"=",
"[",
"]",
"for",
"k",
"in",
"[",
"'name'",
",",
"'desc'",
"]",
":",
"v",
"=",
"_Task",
".",
"Config",
".",
"get",
"(",
"k",
")",
"if",
"v",
"is",
"not",
"None",
":",
"Ret",
".",
"appen... | 18.409091 | 23.136364 |
def write(self, filename=None, io=None,
coors=None, igs=None, out=None, float_format=None, **kwargs):
"""
Write mesh + optional results in `out` to a file.
Parameters
----------
filename : str, optional
The file name. If None, the mesh name is used inst... | [
"def",
"write",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"io",
"=",
"None",
",",
"coors",
"=",
"None",
",",
"igs",
"=",
"None",
",",
"out",
"=",
"None",
",",
"float_format",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"filename",... | 36.454545 | 19.727273 |
def alert_policy_path(cls, project, alert_policy):
"""Return a fully-qualified alert_policy string."""
return google.api_core.path_template.expand(
"projects/{project}/alertPolicies/{alert_policy}",
project=project,
alert_policy=alert_policy,
) | [
"def",
"alert_policy_path",
"(",
"cls",
",",
"project",
",",
"alert_policy",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/alertPolicies/{alert_policy}\"",
",",
"project",
"=",
"project",
",",
"alert_p... | 42.571429 | 12.714286 |
def run(file, access_key, secret_key, **kwargs):
"""命令行运行huobitrade"""
if file:
import sys
file_path, file_name = os.path.split(file)
sys.path.append(file_path)
strategy_module = importlib.import_module(os.path.splitext(file_name)[0])
init = getattr(strategy_module, 'init... | [
"def",
"run",
"(",
"file",
",",
"access_key",
",",
"secret_key",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"file",
":",
"import",
"sys",
"file_path",
",",
"file_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"file",
")",
"sys",
".",
"path",
".",
... | 28.230769 | 19.098901 |
def get_chirp_params(mass1, mass2, spin1z, spin2z, f0, order,
quadparam1=None, quadparam2=None, lambda1=None,
lambda2=None):
"""
Take a set of masses and spins and convert to the various lambda
coordinates that describe the orbital phase. Accepted PN orders are:
... | [
"def",
"get_chirp_params",
"(",
"mass1",
",",
"mass2",
",",
"spin1z",
",",
"spin2z",
",",
"f0",
",",
"order",
",",
"quadparam1",
"=",
"None",
",",
"quadparam2",
"=",
"None",
",",
"lambda1",
"=",
"None",
",",
"lambda2",
"=",
"None",
")",
":",
"# Determi... | 37.021739 | 17.108696 |
def register_date_conversion_handler(date_specifier_patterns):
"""Decorator for registering handlers that convert text dates to dates.
Args:
date_specifier_patterns (str): the date specifier (in regex pattern format) for which the handler is registered
"""
def _decorator(func):
global ... | [
"def",
"register_date_conversion_handler",
"(",
"date_specifier_patterns",
")",
":",
"def",
"_decorator",
"(",
"func",
")",
":",
"global",
"DATE_SPECIFIERS_CONVERSION_HANDLERS",
"DATE_SPECIFIERS_CONVERSION_HANDLERS",
"[",
"DATE_SPECIFIERS_REGEXES",
"[",
"date_specifier_patterns",... | 37.461538 | 29 |
def _get_hit_nearest_ref_start(self, hits):
'''Returns the hit nearest to the start of the ref sequence from the input list of hits'''
nearest_to_start = hits[0]
for hit in hits[1:]:
if hit.ref_coords().start < nearest_to_start.ref_coords().start:
nearest_to_start = h... | [
"def",
"_get_hit_nearest_ref_start",
"(",
"self",
",",
"hits",
")",
":",
"nearest_to_start",
"=",
"hits",
"[",
"0",
"]",
"for",
"hit",
"in",
"hits",
"[",
"1",
":",
"]",
":",
"if",
"hit",
".",
"ref_coords",
"(",
")",
".",
"start",
"<",
"nearest_to_start... | 49.714286 | 18 |
def get_publications(gene_names, save_json_name=None):
"""Return evidence publications for interaction between the given genes.
Parameters
----------
gene_names : list[str]
A list of gene names (HGNC symbols) to query interactions between.
Currently supports exactly two genes only.
... | [
"def",
"get_publications",
"(",
"gene_names",
",",
"save_json_name",
"=",
"None",
")",
":",
"if",
"len",
"(",
"gene_names",
")",
"!=",
"2",
":",
"logger",
".",
"warning",
"(",
"'Other than 2 gene names given.'",
")",
"return",
"[",
"]",
"res_dict",
"=",
"_se... | 36.387097 | 17.709677 |
def interface_temperature(Ts, Tatm, **kwargs):
'''Compute temperature at model layer interfaces.'''
# Actually it's not clear to me how the RRTM code uses these values
lev = Tatm.domain.axes['lev'].points
lev_bounds = Tatm.domain.axes['lev'].bounds
# Interpolate to layer interfaces
f = interp1... | [
"def",
"interface_temperature",
"(",
"Ts",
",",
"Tatm",
",",
"*",
"*",
"kwargs",
")",
":",
"# Actually it's not clear to me how the RRTM code uses these values",
"lev",
"=",
"Tatm",
".",
"domain",
".",
"axes",
"[",
"'lev'",
"]",
".",
"points",
"lev_bounds",
"=",
... | 48 | 16.166667 |
def coroutine(
func: Callable[..., "Generator[Any, Any, _T]"]
) -> Callable[..., "Future[_T]"]:
"""Decorator for asynchronous generators.
For compatibility with older versions of Python, coroutines may
also "return" by raising the special exception `Return(value)
<Return>`.
Functions with this... | [
"def",
"coroutine",
"(",
"func",
":",
"Callable",
"[",
"...",
",",
"\"Generator[Any, Any, _T]\"",
"]",
")",
"->",
"Callable",
"[",
"...",
",",
"\"Future[_T]\"",
"]",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args... | 43.722222 | 21.477778 |
def get_one_required(self, locator):
"""
Gets a required component reference that matches specified locator.
:param locator: the locator to find a reference by.
:return: a matching component reference.
:raises: a [[ReferenceException]] when no references found.
""... | [
"def",
"get_one_required",
"(",
"self",
",",
"locator",
")",
":",
"components",
"=",
"self",
".",
"find",
"(",
"locator",
",",
"True",
")",
"return",
"components",
"[",
"0",
"]",
"if",
"len",
"(",
"components",
")",
">",
"0",
"else",
"None"
] | 34.833333 | 20.25 |
def to_camel_case(snake_case_name):
"""
Converts snake_cased_names to CamelCaseNames.
:param snake_case_name: The name you'd like to convert from.
:type snake_case_name: string
:returns: A converted string
:rtype: string
"""
bits = snake_case_name.split('_')
return ''.join([bit.cap... | [
"def",
"to_camel_case",
"(",
"snake_case_name",
")",
":",
"bits",
"=",
"snake_case_name",
".",
"split",
"(",
"'_'",
")",
"return",
"''",
".",
"join",
"(",
"[",
"bit",
".",
"capitalize",
"(",
")",
"for",
"bit",
"in",
"bits",
"]",
")"
] | 28 | 14.333333 |
def get_loadbalancer_members(self, datacenter_id, loadbalancer_id,
depth=1):
"""
Retrieves the list of NICs that are associated with a load balancer.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
... | [
"def",
"get_loadbalancer_members",
"(",
"self",
",",
"datacenter_id",
",",
"loadbalancer_id",
",",
"depth",
"=",
"1",
")",
":",
"response",
"=",
"self",
".",
"_perform_request",
"(",
"'/datacenters/%s/loadbalancers/%s/balancednics?depth=%s'",
"%",
"(",
"datacenter_id",
... | 36 | 21.2 |
def get_reverse_index(self, base_index):
"""Get index into this segment's data given the index into the base data
Raises IndexError if the base index doesn't map to anything in this
segment's data
"""
r = self.reverse_index_mapping[base_index]
if r < 0:
raise... | [
"def",
"get_reverse_index",
"(",
"self",
",",
"base_index",
")",
":",
"r",
"=",
"self",
".",
"reverse_index_mapping",
"[",
"base_index",
"]",
"if",
"r",
"<",
"0",
":",
"raise",
"IndexError",
"(",
"\"index %d not mapped in this segment\"",
"%",
"base_index",
")",... | 39.1 | 19 |
def secant2(value_and_gradients_function,
val_0,
search_interval,
f_lim,
sufficient_decrease_param=0.1,
curvature_param=0.9,
name=None):
"""Performs the secant square procedure of Hager Zhang.
Given an interval that brackets a root, this proce... | [
"def",
"secant2",
"(",
"value_and_gradients_function",
",",
"val_0",
",",
"search_interval",
",",
"f_lim",
",",
"sufficient_decrease_param",
"=",
"0.1",
",",
"curvature_param",
"=",
"0.9",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
... | 49.104348 | 23.93913 |
def load_cufflinks(self, filter_ok=True):
"""
Load a Cufflinks gene expression data for a cohort
Parameters
----------
filter_ok : bool, optional
If true, filter Cufflinks data to row with FPKM_status == "OK"
Returns
-------
cufflinks_data : ... | [
"def",
"load_cufflinks",
"(",
"self",
",",
"filter_ok",
"=",
"True",
")",
":",
"return",
"pd",
".",
"concat",
"(",
"[",
"self",
".",
"_load_single_patient_cufflinks",
"(",
"patient",
",",
"filter_ok",
")",
"for",
"patient",
"in",
"self",
"]",
",",
"copy",
... | 33.3 | 22.9 |
def make_back_matter(self):
"""
The <back> element may have 0 or 1 <label> elements and 0 or 1 <title>
elements. Then it may have any combination of the following: <ack>,
<app-group>, <bio>, <fn-group>, <glossary>, <ref-list>, <notes>, and
<sec>. <sec> is employed here as a catch... | [
"def",
"make_back_matter",
"(",
"self",
")",
":",
"#Back is technically metadata content that needs to be interpreted to",
"#presentable content",
"body",
"=",
"self",
".",
"main",
".",
"getroot",
"(",
")",
".",
"find",
"(",
"'body'",
")",
"if",
"self",
".",
"articl... | 46.722222 | 23.055556 |
def _encrypt(cipher, key, data, iv, padding):
"""
Encrypts plaintext
:param cipher:
A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
"rc2", "rc4"
:param key:
The encryption key - a byte string 5-16 bytes long
:param data:
The plaintext - a byte... | [
"def",
"_encrypt",
"(",
"cipher",
",",
"key",
",",
"data",
",",
"iv",
",",
"padding",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"byte_cls",
")",
":",
"raise",
"TypeError",
"(",
"pretty_message",
"(",
"'''\n key must be a byte string, not... | 26.779661 | 21.559322 |
def filter(configs, settings):
"""Main entry function to filtering configuration types
Parameters
----------
configs: Nx4 array
array containing A-B-M-N configurations
settings: dict
'only_types': ['dd', 'other'], # filter only for those types
Returns
-------
dict
... | [
"def",
"filter",
"(",
"configs",
",",
"settings",
")",
":",
"if",
"isinstance",
"(",
"configs",
",",
"pd",
".",
"DataFrame",
")",
":",
"configs",
"=",
"configs",
"[",
"[",
"'a'",
",",
"'b'",
",",
"'m'",
",",
"'n'",
"]",
"]",
".",
"values",
"# assig... | 30.14 | 21.66 |
def is_able_to_convert_detailed(self, strict: bool, from_type: Type[Any], to_type: Type[Any]):
"""
Overrides the parent method to delegate left check to the first (left) converter of the chain and right check
to the last (right) converter of the chain. This includes custom checking if they have ... | [
"def",
"is_able_to_convert_detailed",
"(",
"self",
",",
"strict",
":",
"bool",
",",
"from_type",
":",
"Type",
"[",
"Any",
"]",
",",
"to_type",
":",
"Type",
"[",
"Any",
"]",
")",
":",
"# check if first and last converters are happy",
"if",
"not",
"self",
".",
... | 52.315789 | 31.052632 |
def human_uuid():
"""Returns a good UUID for using as a human readable string."""
return base64.b32encode(
hashlib.sha1(uuid.uuid4().bytes).digest()).lower().strip('=') | [
"def",
"human_uuid",
"(",
")",
":",
"return",
"base64",
".",
"b32encode",
"(",
"hashlib",
".",
"sha1",
"(",
"uuid",
".",
"uuid4",
"(",
")",
".",
"bytes",
")",
".",
"digest",
"(",
")",
")",
".",
"lower",
"(",
")",
".",
"strip",
"(",
"'='",
")"
] | 45.25 | 16 |
def to_pandas(self):
"""Return a Pandas dataframe of the minimum spanning tree.
Each row is an edge in the tree; the columns are `from`,
`to`, and `distance` giving the two vertices of the edge
which are indices into the dataset, and the distance
between those datapoints.
... | [
"def",
"to_pandas",
"(",
"self",
")",
":",
"try",
":",
"from",
"pandas",
"import",
"DataFrame",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"'You must have pandas installed to export pandas DataFrames'",
")",
"result",
"=",
"DataFrame",
"(",
"{",
"'fr... | 40.529412 | 20.352941 |
def _set_init_system(self, client):
"""Determine the init system of distribution."""
if not self.init_system:
try:
out = ipa_utils.execute_ssh_command(
client,
'ps -p 1 -o comm='
)
except Exception as e:
... | [
"def",
"_set_init_system",
"(",
"self",
",",
"client",
")",
":",
"if",
"not",
"self",
".",
"init_system",
":",
"try",
":",
"out",
"=",
"ipa_utils",
".",
"execute_ssh_command",
"(",
"client",
",",
"'ps -p 1 -o comm='",
")",
"except",
"Exception",
"as",
"e",
... | 35.933333 | 11.533333 |
def update_cache_for_instance(
model_name, instance_pk, instance=None, version=None):
"""Update the cache for an instance, with cascading updates."""
cache = SampleCache()
invalid = cache.update_instance(model_name, instance_pk, instance, version)
for invalid_name, invalid_pk, invalid_version in... | [
"def",
"update_cache_for_instance",
"(",
"model_name",
",",
"instance_pk",
",",
"instance",
"=",
"None",
",",
"version",
"=",
"None",
")",
":",
"cache",
"=",
"SampleCache",
"(",
")",
"invalid",
"=",
"cache",
".",
"update_instance",
"(",
"model_name",
",",
"i... | 53.25 | 16.125 |
def get_chunk_information(self, chk, lun, chunk_name):
"""Get chunk information"""
cmd = ["nvm_cmd rprt_lun", self.envs,
"%d %d > %s" % (chk, lun, chunk_name)]
status, _, _ = cij.ssh.command(cmd, shell=True)
return status | [
"def",
"get_chunk_information",
"(",
"self",
",",
"chk",
",",
"lun",
",",
"chunk_name",
")",
":",
"cmd",
"=",
"[",
"\"nvm_cmd rprt_lun\"",
",",
"self",
".",
"envs",
",",
"\"%d %d > %s\"",
"%",
"(",
"chk",
",",
"lun",
",",
"chunk_name",
")",
"]",
"status"... | 44.666667 | 11.666667 |
def to_labeled_point(sc, features, labels, categorical=False):
"""Convert numpy arrays of features and labels into
a LabeledPoint RDD for MLlib and ML integration.
:param sc: Spark context
:param features: numpy array with features
:param labels: numpy array with labels
:param categorical: bool... | [
"def",
"to_labeled_point",
"(",
"sc",
",",
"features",
",",
"labels",
",",
"categorical",
"=",
"False",
")",
":",
"labeled_points",
"=",
"[",
"]",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"features",
",",
"labels",
")",
":",
"if",
"categorical",
":",
... | 39 | 13.555556 |
def find(self, key):
"Exact matching (returns value)"
index = self.follow_bytes(key, self.ROOT)
if index is None:
return -1
if not self.has_value(index):
return -1
return self.value(index) | [
"def",
"find",
"(",
"self",
",",
"key",
")",
":",
"index",
"=",
"self",
".",
"follow_bytes",
"(",
"key",
",",
"self",
".",
"ROOT",
")",
"if",
"index",
"is",
"None",
":",
"return",
"-",
"1",
"if",
"not",
"self",
".",
"has_value",
"(",
"index",
")"... | 30.625 | 11.625 |
def clone(client):
'''Clone the redis client to be slowlog-compatible'''
kwargs = client.redis.connection_pool.connection_kwargs
kwargs['parser_class'] = redis.connection.PythonParser
pool = redis.connection.ConnectionPool(**kwargs)
return redis.Redis(connection_pool=pool) | [
"def",
"clone",
"(",
"client",
")",
":",
"kwargs",
"=",
"client",
".",
"redis",
".",
"connection_pool",
".",
"connection_kwargs",
"kwargs",
"[",
"'parser_class'",
"]",
"=",
"redis",
".",
"connection",
".",
"PythonParser",
"pool",
"=",
"redis",
".",
"connecti... | 51.333333 | 18.666667 |
def close_list(ctx, root):
"""Close already opened list if needed.
This will try to see if it is needed to close already opened list.
:Args:
- ctx (:class:`Context`): Context object
- root (Element): lxml element representing current position.
:Returns:
lxml element where future co... | [
"def",
"close_list",
"(",
"ctx",
",",
"root",
")",
":",
"try",
":",
"n",
"=",
"len",
"(",
"ctx",
".",
"in_list",
")",
"if",
"n",
"<=",
"0",
":",
"return",
"root",
"elem",
"=",
"root",
"while",
"n",
">",
"0",
":",
"while",
"True",
":",
"if",
"... | 21.342857 | 24.314286 |
def start_accepting_passive_svc_checks(self):
"""Enable passive service check submission (globally)
Format of the line that triggers function call::
START_ACCEPTING_PASSIVE_SVC_CHECKS
:return: None
"""
# todo: #783 create a dedicated brok for global parameters
i... | [
"def",
"start_accepting_passive_svc_checks",
"(",
"self",
")",
":",
"# todo: #783 create a dedicated brok for global parameters",
"if",
"not",
"self",
".",
"my_conf",
".",
"accept_passive_service_checks",
":",
"self",
".",
"my_conf",
".",
"modified_attributes",
"|=",
"DICT_... | 43.857143 | 18.571429 |
def lowstate_file_refs(chunks, extras=''):
'''
Create a list of file ref objects to reconcile
'''
refs = {}
for chunk in chunks:
if not isinstance(chunk, dict):
continue
saltenv = 'base'
crefs = []
for state in chunk:
if state == '__env__':
... | [
"def",
"lowstate_file_refs",
"(",
"chunks",
",",
"extras",
"=",
"''",
")",
":",
"refs",
"=",
"{",
"}",
"for",
"chunk",
"in",
"chunks",
":",
"if",
"not",
"isinstance",
"(",
"chunk",
",",
"dict",
")",
":",
"continue",
"saltenv",
"=",
"'base'",
"crefs",
... | 28.407407 | 13.222222 |
def _ProcessLockAcquired(self):
"""Context manager for process locks with timeout."""
try:
is_locked = self._process_lock.acquire(timeout=self._lock_timeout)
yield is_locked
finally:
if is_locked:
self._process_lock.release() | [
"def",
"_ProcessLockAcquired",
"(",
"self",
")",
":",
"try",
":",
"is_locked",
"=",
"self",
".",
"_process_lock",
".",
"acquire",
"(",
"timeout",
"=",
"self",
".",
"_lock_timeout",
")",
"yield",
"is_locked",
"finally",
":",
"if",
"is_locked",
":",
"self",
... | 36.75 | 16.375 |
def _field_value_html(self, field):
"""Return the html representation of the value of the given field"""
if field in self.fields:
return unicode(self.get(field))
else:
return self.get_timemachine_instance(field)._object_name_html() | [
"def",
"_field_value_html",
"(",
"self",
",",
"field",
")",
":",
"if",
"field",
"in",
"self",
".",
"fields",
":",
"return",
"unicode",
"(",
"self",
".",
"get",
"(",
"field",
")",
")",
"else",
":",
"return",
"self",
".",
"get_timemachine_instance",
"(",
... | 45.666667 | 13 |
def expr_str(expr, sc_expr_str_fn=standard_sc_expr_str):
"""
Returns the string representation of the expression 'expr', as in a Kconfig
file.
Passing subexpressions of expressions to this function works as expected.
sc_expr_str_fn (default: standard_sc_expr_str):
This function is called for... | [
"def",
"expr_str",
"(",
"expr",
",",
"sc_expr_str_fn",
"=",
"standard_sc_expr_str",
")",
":",
"if",
"expr",
".",
"__class__",
"is",
"not",
"tuple",
":",
"return",
"sc_expr_str_fn",
"(",
"expr",
")",
"if",
"expr",
"[",
"0",
"]",
"is",
"AND",
":",
"return"... | 40.52381 | 26.47619 |
def _configure(configuration_details):
"""Adds alias to shell config."""
path = Path(configuration_details.path).expanduser()
with path.open('a') as shell_config:
shell_config.write(u'\n')
shell_config.write(configuration_details.content)
shell_config.write(u'\n') | [
"def",
"_configure",
"(",
"configuration_details",
")",
":",
"path",
"=",
"Path",
"(",
"configuration_details",
".",
"path",
")",
".",
"expanduser",
"(",
")",
"with",
"path",
".",
"open",
"(",
"'a'",
")",
"as",
"shell_config",
":",
"shell_config",
".",
"wr... | 42 | 7 |
def get_return_line_item_by_id(cls, return_line_item_id, **kwargs):
"""Find ReturnLineItem
Return single instance of ReturnLineItem by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.g... | [
"def",
"get_return_line_item_by_id",
"(",
"cls",
",",
"return_line_item_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_get_ret... | 45.761905 | 23.238095 |
def tokenize_arabic_words(text):
"""
Tokenize text into words
@param text: the input text.
@type text: unicode.
@return: list of words.
@rtype: list.
"""
specific_tokens = []
if not text:
return specific_tokens
else:
specific_tokens = araby.to... | [
"def",
"tokenize_arabic_words",
"(",
"text",
")",
":",
"specific_tokens",
"=",
"[",
"]",
"if",
"not",
"text",
":",
"return",
"specific_tokens",
"else",
":",
"specific_tokens",
"=",
"araby",
".",
"tokenize",
"(",
"text",
")",
"return",
"specific_tokens"
] | 23.266667 | 13.133333 |
def transpose(self, *dims):
"""Return a new Dataset object with all array dimensions transposed.
Although the order of dimensions on each array will change, the dataset
dimensions themselves will remain in fixed (sorted) order.
Parameters
----------
*dims : str, optiona... | [
"def",
"transpose",
"(",
"self",
",",
"*",
"dims",
")",
":",
"if",
"dims",
":",
"if",
"set",
"(",
"dims",
")",
"^",
"set",
"(",
"self",
".",
"dims",
")",
":",
"raise",
"ValueError",
"(",
"'arguments to transpose (%s) must be '",
"'permuted dataset dimensions... | 35.564103 | 22.307692 |
def calculateRange(self, values):
"""
Calculates the range of values for this axis based on the dataset
value amount.
:param values | [<variant>, ..]
"""
vals = filter(lambda x: x is not None, values)
try:
min_val = min... | [
"def",
"calculateRange",
"(",
"self",
",",
"values",
")",
":",
"vals",
"=",
"filter",
"(",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
",",
"values",
")",
"try",
":",
"min_val",
"=",
"min",
"(",
"min",
"(",
"vals",
")",
",",
"0",
")",
"except",... | 31.307692 | 17.846154 |
def get_zonefile_instance(new_instance=False):
"""
This is a convenience function which provides a :class:`ZoneInfoFile`
instance using the data provided by the ``dateutil`` package. By default, it
caches a single instance of the ZoneInfoFile object and returns that.
:param new_instance:
If... | [
"def",
"get_zonefile_instance",
"(",
"new_instance",
"=",
"False",
")",
":",
"if",
"new_instance",
":",
"zif",
"=",
"None",
"else",
":",
"zif",
"=",
"getattr",
"(",
"get_zonefile_instance",
",",
"'_cached_instance'",
",",
"None",
")",
"if",
"zif",
"is",
"Non... | 31.296296 | 24.925926 |
def sync_label_shape(self, it, verbose=False):
"""Synchronize label shape with the input iterator. This is useful when
train/validation iterators have different label padding.
Parameters
----------
it : ImageDetIter
The other iterator to synchronize
verbose :... | [
"def",
"sync_label_shape",
"(",
"self",
",",
"it",
",",
"verbose",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"it",
",",
"ImageDetIter",
")",
",",
"'Synchronize with invalid iterator.'",
"train_label_shape",
"=",
"self",
".",
"label_shape",
"val_label_sh... | 40.357143 | 22.452381 |
def simBirth(self,which_agents):
'''
Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and permanent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrmI... | [
"def",
"simBirth",
"(",
"self",
",",
"which_agents",
")",
":",
"IndShockConsumerType",
".",
"simBirth",
"(",
"self",
",",
"which_agents",
")",
"if",
"hasattr",
"(",
"self",
",",
"'aLvlNow'",
")",
":",
"self",
".",
"aLvlNow",
"[",
"which_agents",
"]",
"=",
... | 39.8 | 30.1 |
def git_tag_list(pattern=None):
"""
Return a list of all the tags in the git repo matching a regex passed in
`pattern`. If `pattern` is None, return all the tags.
"""
with chdir(get_root()):
result = run_command('git tag', capture=True).stdout
result = result.splitlines()
if not... | [
"def",
"git_tag_list",
"(",
"pattern",
"=",
"None",
")",
":",
"with",
"chdir",
"(",
"get_root",
"(",
")",
")",
":",
"result",
"=",
"run_command",
"(",
"'git tag'",
",",
"capture",
"=",
"True",
")",
".",
"stdout",
"result",
"=",
"result",
".",
"splitlin... | 29.785714 | 16.642857 |
def get_gewest_by_id(self, id):
'''
Get a `gewest` by id.
:param integer id: The id of a `gewest`.
:rtype: A :class:`Gewest`.
'''
def creator():
nl = crab_gateway_request(
self.client, 'GetGewestByGewestIdAndTaalCode', id, 'nl'
)
... | [
"def",
"get_gewest_by_id",
"(",
"self",
",",
"id",
")",
":",
"def",
"creator",
"(",
")",
":",
"nl",
"=",
"crab_gateway_request",
"(",
"self",
".",
"client",
",",
"'GetGewestByGewestIdAndTaalCode'",
",",
"id",
",",
"'nl'",
")",
"fr",
"=",
"crab_gateway_reques... | 34.055556 | 16.611111 |
def coarseMaximum(arr, shape):
'''
return an array of [shape]
where every cell equals the localised maximum of the given array [arr]
at the same (scalled) position
'''
ss0, ss1 = shape
s0, s1 = arr.shape
pos0 = linspace2(0, s0, ss0, dtype=int)
pos1 = linspace2(0, s1, ss1, ... | [
"def",
"coarseMaximum",
"(",
"arr",
",",
"shape",
")",
":",
"ss0",
",",
"ss1",
"=",
"shape",
"s0",
",",
"s1",
"=",
"arr",
".",
"shape",
"pos0",
"=",
"linspace2",
"(",
"0",
",",
"s0",
",",
"ss0",
",",
"dtype",
"=",
"int",
")",
"pos1",
"=",
"lins... | 25.777778 | 20.444444 |
def generate(env):
"""Add Builders and construction variables for gfortran to an
Environment."""
fortran.generate(env)
for dialect in ['F77', 'F90', 'FORTRAN', 'F95', 'F03', 'F08']:
env['%s' % dialect] = 'gfortran'
env['SH%s' % dialect] = '$%s' % dialect
if env['PLATFORM'] in ['... | [
"def",
"generate",
"(",
"env",
")",
":",
"fortran",
".",
"generate",
"(",
"env",
")",
"for",
"dialect",
"in",
"[",
"'F77'",
",",
"'F90'",
",",
"'FORTRAN'",
",",
"'F95'",
",",
"'F03'",
",",
"'F08'",
"]",
":",
"env",
"[",
"'%s'",
"%",
"dialect",
"]",... | 39.4 | 18.333333 |
def _add_parameterized_validator_internal(param_validator, base_tag):
"with builtin tag prefixing"
add_parameterized_validator(param_validator, base_tag, tag_prefix=u'!~~%s(' % param_validator.__name__) | [
"def",
"_add_parameterized_validator_internal",
"(",
"param_validator",
",",
"base_tag",
")",
":",
"add_parameterized_validator",
"(",
"param_validator",
",",
"base_tag",
",",
"tag_prefix",
"=",
"u'!~~%s('",
"%",
"param_validator",
".",
"__name__",
")"
] | 69.333333 | 34.666667 |
def _check_public_functions(self, primary_header, all_headers):
"""Verify all the public functions are also declared in a header
file."""
public_symbols = {}
declared_only_symbols = {}
if primary_header:
for name, symbol in primary_header.public_symbols.items():
... | [
"def",
"_check_public_functions",
"(",
"self",
",",
"primary_header",
",",
"all_headers",
")",
":",
"public_symbols",
"=",
"{",
"}",
"declared_only_symbols",
"=",
"{",
"}",
"if",
"primary_header",
":",
"for",
"name",
",",
"symbol",
"in",
"primary_header",
".",
... | 46.425 | 18.775 |
def prox_max_entropy(X, step, gamma=1):
"""Proximal operator for maximum entropy regularization.
g(x) = gamma \sum_i x_i ln(x_i)
has the analytical solution of gamma W(1/gamma exp((X-gamma)/gamma)), where
W is the Lambert W function.
"""
from scipy.special import lambertw
gamma_ = _step_ga... | [
"def",
"prox_max_entropy",
"(",
"X",
",",
"step",
",",
"gamma",
"=",
"1",
")",
":",
"from",
"scipy",
".",
"special",
"import",
"lambertw",
"gamma_",
"=",
"_step_gamma",
"(",
"step",
",",
"gamma",
")",
"# minimize entropy: return gamma_ * np.real(lambertw(np.exp((X... | 38 | 20.357143 |
def from_representation(self, data):
"""Convert representation value to ``bool`` if it has expected form."""
if data in self._TRUE_VALUES:
return True
elif data in self._FALSE_VALUES:
return False
else:
raise ValueError(
"{type} type va... | [
"def",
"from_representation",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"in",
"self",
".",
"_TRUE_VALUES",
":",
"return",
"True",
"elif",
"data",
"in",
"self",
".",
"_FALSE_VALUES",
":",
"return",
"False",
"else",
":",
"raise",
"ValueError",
"(",
... | 37.153846 | 14.615385 |
def use_in(ContentHandler):
"""
Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Array and
ArrayStream classes defined in this module when parsing XML
documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> class MyContentHandler(ligolw.LIGOLWConten... | [
"def",
"use_in",
"(",
"ContentHandler",
")",
":",
"def",
"startStream",
"(",
"self",
",",
"parent",
",",
"attrs",
",",
"__orig_startStream",
"=",
"ContentHandler",
".",
"startStream",
")",
":",
"if",
"parent",
".",
"tagName",
"==",
"ligolw",
".",
"Array",
... | 28.535714 | 19.25 |
def _pull_out_unaffected_blocks_rhs(rest, rhs, out_port, in_port):
"""Similar to :func:`_pull_out_unaffected_blocks_lhs` but on the RHS of a
series product self-feedback.
"""
_, block_index = rhs.index_in_block(in_port)
rest = tuple(rest)
bs = rhs.block_structure
(nbefore, nblock, nafter) = ... | [
"def",
"_pull_out_unaffected_blocks_rhs",
"(",
"rest",
",",
"rhs",
",",
"out_port",
",",
"in_port",
")",
":",
"_",
",",
"block_index",
"=",
"rhs",
".",
"index_in_block",
"(",
"in_port",
")",
"rest",
"=",
"tuple",
"(",
"rest",
")",
"bs",
"=",
"rhs",
".",
... | 51.095238 | 16.714286 |
def _TableFactory(tag, stream, offset, length):
"""
Return an instance of |Table| appropriate to *tag*, loaded from
*font_file* with content of *length* starting at *offset*.
"""
TableClass = {
'head': _HeadTable,
'name': _NameTable,
}.get(tag, _BaseTable)
return TableClass(t... | [
"def",
"_TableFactory",
"(",
"tag",
",",
"stream",
",",
"offset",
",",
"length",
")",
":",
"TableClass",
"=",
"{",
"'head'",
":",
"_HeadTable",
",",
"'name'",
":",
"_NameTable",
",",
"}",
".",
"get",
"(",
"tag",
",",
"_BaseTable",
")",
"return",
"Table... | 33.8 | 12.8 |
def Plot_Impact_PolProjPoly(lS, Leg="", ax=None, Ang='theta', AngUnit='rad',
Sketch=True, dP=None,
dLeg=_def.TorLegd, draw=True, fs=None,
wintit=None, tit=None, Test=True):
""" Plotting the toroidal projection of a Ves instance
... | [
"def",
"Plot_Impact_PolProjPoly",
"(",
"lS",
",",
"Leg",
"=",
"\"\"",
",",
"ax",
"=",
"None",
",",
"Ang",
"=",
"'theta'",
",",
"AngUnit",
"=",
"'rad'",
",",
"Sketch",
"=",
"True",
",",
"dP",
"=",
"None",
",",
"dLeg",
"=",
"_def",
".",
"TorLegd",
",... | 38.045455 | 23.465909 |
def _parse_gcs_uri(self, raw_uri):
"""Return a valid docker_path for a GCS bucket."""
# Assume URI is a directory path.
raw_uri = directory_fmt(raw_uri)
_, docker_path = _gcs_uri_rewriter(raw_uri)
docker_uri = os.path.join(self._relative_path, docker_path)
return docker_uri | [
"def",
"_parse_gcs_uri",
"(",
"self",
",",
"raw_uri",
")",
":",
"# Assume URI is a directory path.",
"raw_uri",
"=",
"directory_fmt",
"(",
"raw_uri",
")",
"_",
",",
"docker_path",
"=",
"_gcs_uri_rewriter",
"(",
"raw_uri",
")",
"docker_uri",
"=",
"os",
".",
"path... | 41.714286 | 8.857143 |
def get_netconf_client_capabilities_input_session_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_netconf_client_capabilities = ET.Element("get_netconf_client_capabilities")
config = get_netconf_client_capabilities
input = ET.SubElement(ge... | [
"def",
"get_netconf_client_capabilities_input_session_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_netconf_client_capabilities",
"=",
"ET",
".",
"Element",
"(",
"\"get_netconf_client_capabilitie... | 45.5 | 17.416667 |
def read_gsc_sfr(self):
"""Read the gain-scaling-coefficient and sample flow rate.
:returns: dictionary containing GSC and SFR
"""
config = []
data = {}
# Send the command byte and sleep for 10 ms
self.cnxn.xfer([0x33])
sleep(10e-3)
# Read t... | [
"def",
"read_gsc_sfr",
"(",
"self",
")",
":",
"config",
"=",
"[",
"]",
"data",
"=",
"{",
"}",
"# Send the command byte and sleep for 10 ms",
"self",
".",
"cnxn",
".",
"xfer",
"(",
"[",
"0x33",
"]",
")",
"sleep",
"(",
"10e-3",
")",
"# Read the config variable... | 27.857143 | 19.52381 |
def _getattrs(self, obj, *attrs):
""" Return dictionary of given attrs on given object, if they exist,
processing through _filter_value().
"""
filtered_attrs = {}
for attr in attrs:
if hasattr(obj, attr):
filtered_attrs[attr] = obj_to_string(
... | [
"def",
"_getattrs",
"(",
"self",
",",
"obj",
",",
"*",
"attrs",
")",
":",
"filtered_attrs",
"=",
"{",
"}",
"for",
"attr",
"in",
"attrs",
":",
"if",
"hasattr",
"(",
"obj",
",",
"attr",
")",
":",
"filtered_attrs",
"[",
"attr",
"]",
"=",
"obj_to_string"... | 37.909091 | 9.636364 |
def _special_value_rows(em):
'''
_special_value_rows - Handle "rows" special attribute, which differs if tagName is a textarea or frameset
'''
if em.tagName == 'textarea':
return convertToIntRange(em.getAttribute('rows', 2), minValue=1, maxValue=None, invalidDefault=2)
else:
# fr... | [
"def",
"_special_value_rows",
"(",
"em",
")",
":",
"if",
"em",
".",
"tagName",
"==",
"'textarea'",
":",
"return",
"convertToIntRange",
"(",
"em",
".",
"getAttribute",
"(",
"'rows'",
",",
"2",
")",
",",
"minValue",
"=",
"1",
",",
"maxValue",
"=",
"None",
... | 40.111111 | 31 |
def file_reader(self):
"""Generator process to read file"""
self.update_config()
path = self.config['path']
# open file to get dimensions
with self.subprocess(
['ffmpeg', '-v', 'info', '-y', '-an', '-vn', '-i', path, '-'],
stdout=subprocess.PIPE, s... | [
"def",
"file_reader",
"(",
"self",
")",
":",
"self",
".",
"update_config",
"(",
")",
"path",
"=",
"self",
".",
"config",
"[",
"'path'",
"]",
"# open file to get dimensions",
"with",
"self",
".",
"subprocess",
"(",
"[",
"'ffmpeg'",
",",
"'-v'",
",",
"'info'... | 46.12069 | 15.948276 |
def login_required(view_function):
""" This decorator ensures that the current user is logged in.
Example::
@route('/member_page')
@login_required
def member_page(): # User must be logged in
...
If USER_ENABLE_EMAIL is True and USER_ENABLE_CONFIRM_EMAIL is True,
t... | [
"def",
"login_required",
"(",
"view_function",
")",
":",
"@",
"wraps",
"(",
"view_function",
")",
"# Tells debuggers that is is a function wrapper",
"def",
"decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"user_manager",
"=",
"current_app",
".",
... | 34.677419 | 21.032258 |
def on_download_to_activated(self, menu_item):
'''下载文件/目录到指定的文件夹里.'''
tree_paths = self.iconview.get_selected_items()
if not tree_paths:
return
dialog = Gtk.FileChooserDialog(_('Save to...'), self.app.window,
Gtk.FileChooserAction.SELECT_FOLDER,
... | [
"def",
"on_download_to_activated",
"(",
"self",
",",
"menu_item",
")",
":",
"tree_paths",
"=",
"self",
".",
"iconview",
".",
"get_selected_items",
"(",
")",
"if",
"not",
"tree_paths",
":",
"return",
"dialog",
"=",
"Gtk",
".",
"FileChooserDialog",
"(",
"_",
"... | 38.3 | 16.9 |
def _full_axis_reduce_along_select_indices(self, func, axis, index):
"""Reduce Manger along select indices using function that needs full axis.
Args:
func: Callable that reduces the dimension of the object and requires full
knowledge of the entire axis.
axis: 0 f... | [
"def",
"_full_axis_reduce_along_select_indices",
"(",
"self",
",",
"func",
",",
"axis",
",",
"index",
")",
":",
"# Convert indices to numeric indices",
"old_index",
"=",
"self",
".",
"index",
"if",
"axis",
"else",
"self",
".",
"columns",
"numeric_indices",
"=",
"[... | 44.105263 | 22.578947 |
def tenant_forgot_password_login(self, data, tenant_id=None, api_version="v2.0"):
"""
Forgot password API
**Parameters:**:
- **data**: Dictionary containing data to POST as JSON
- **tenant_id**: Tenant ID
- **api_version**: API version to use (default v2.0)
... | [
"def",
"tenant_forgot_password_login",
"(",
"self",
",",
"data",
",",
"tenant_id",
"=",
"None",
",",
"api_version",
"=",
"\"v2.0\"",
")",
":",
"if",
"tenant_id",
"is",
"None",
"and",
"self",
".",
"_parent_class",
".",
"tenant_id",
":",
"# Pull tenant_id from par... | 41.538462 | 25.846154 |
def check_unused(intersection, duplicates, intersections):
"""Check if a "valid" ``intersection`` is already in ``intersections``.
This assumes that
* ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0``
* At least one of the intersections in ``intersections`` is classified as
... | [
"def",
"check_unused",
"(",
"intersection",
",",
"duplicates",
",",
"intersections",
")",
":",
"for",
"other",
"in",
"intersections",
":",
"if",
"(",
"other",
".",
"interior_curve",
"==",
"UNUSED_T",
"and",
"intersection",
".",
"index_first",
"==",
"other",
".... | 35.575758 | 22.606061 |
def prepare_url_list(urlresolver, namespace_path='', namespace=''):
"""
returns list of tuples [(<url_name>, <url_patern_tuple> ), ...]
"""
exclude_ns = getattr(settings, 'JS_REVERSE_EXCLUDE_NAMESPACES', JS_EXCLUDE_NAMESPACES)
include_only_ns = getattr(settings, 'JS_REVERSE_INCLUDE_ONLY_NAMESPACES',... | [
"def",
"prepare_url_list",
"(",
"urlresolver",
",",
"namespace_path",
"=",
"''",
",",
"namespace",
"=",
"''",
")",
":",
"exclude_ns",
"=",
"getattr",
"(",
"settings",
",",
"'JS_REVERSE_EXCLUDE_NAMESPACES'",
",",
"JS_EXCLUDE_NAMESPACES",
")",
"include_only_ns",
"=",
... | 41.157143 | 23.985714 |
def select_multi_directory_dialog():
""" Opens a directory selection dialog
Style - specifies style of dialog (read wx documentation for information)
"""
import wx.lib.agw.multidirdialog as MDD
app = wx.App(0)
dlg = MDD.MultiDirDialog(None, title="Select directories", defaultPath=os.getcwd(... | [
"def",
"select_multi_directory_dialog",
"(",
")",
":",
"import",
"wx",
".",
"lib",
".",
"agw",
".",
"multidirdialog",
"as",
"MDD",
"app",
"=",
"wx",
".",
"App",
"(",
"0",
")",
"dlg",
"=",
"MDD",
".",
"MultiDirDialog",
"(",
"None",
",",
"title",
"=",
... | 27 | 24.35 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.