text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _create_sqlite_metatable(self):
"""
SQLite doesn't come with any metatables (at least ones that fit into our
framework), so we're going to create them.
"""
sys.stderr.write("Indexing schema. This will take a second...")
rows_to_insert = []
tables = [row[0] for... | [
"def",
"_create_sqlite_metatable",
"(",
"self",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Indexing schema. This will take a second...\"",
")",
"rows_to_insert",
"=",
"[",
"]",
"tables",
"=",
"[",
"row",
"[",
"0",
"]",
"for",
"row",
"in",
"self",
... | 58.571429 | 0.010557 |
def _makeTags(tagStr, xml,
suppress_LT=Suppress("<"),
suppress_GT=Suppress(">")):
"""Internal helper to construct opening and closing tag expressions, given a tag name"""
if isinstance(tagStr,basestring):
resname = tagStr
tagStr = Keyword(tagStr, caseless=not xml)
... | [
"def",
"_makeTags",
"(",
"tagStr",
",",
"xml",
",",
"suppress_LT",
"=",
"Suppress",
"(",
"\"<\"",
")",
",",
"suppress_GT",
"=",
"Suppress",
"(",
"\">\"",
")",
")",
":",
"if",
"isinstance",
"(",
"tagStr",
",",
"basestring",
")",
":",
"resname",
"=",
"ta... | 50.25 | 0.015727 |
def depth(self, pos):
"""determine depth of node at pos"""
parent = self.parent_position(pos)
if parent is None:
return 0
else:
return self.depth(parent) + 1 | [
"def",
"depth",
"(",
"self",
",",
"pos",
")",
":",
"parent",
"=",
"self",
".",
"parent_position",
"(",
"pos",
")",
"if",
"parent",
"is",
"None",
":",
"return",
"0",
"else",
":",
"return",
"self",
".",
"depth",
"(",
"parent",
")",
"+",
"1"
] | 29.571429 | 0.00939 |
def bq(line, cell=None):
"""Implements the bq cell magic for ipython notebooks.
The supported syntax is:
%%bq <command> [<args>]
<cell>
or:
%bq <command> [<args>]
Use %bq --help for a list of commands, or %bq <command> --help for help
on a specific command.
"""
return google.datalab.utils... | [
"def",
"bq",
"(",
"line",
",",
"cell",
"=",
"None",
")",
":",
"return",
"google",
".",
"datalab",
".",
"utils",
".",
"commands",
".",
"handle_magic_line",
"(",
"line",
",",
"cell",
",",
"_bigquery_parser",
")"
] | 22.625 | 0.01061 |
def stream(self, to=values.unset, from_=values.unset,
parent_call_sid=values.unset, status=values.unset,
start_time_before=values.unset, start_time=values.unset,
start_time_after=values.unset, end_time_before=values.unset,
end_time=values.unset, end_time_after... | [
"def",
"stream",
"(",
"self",
",",
"to",
"=",
"values",
".",
"unset",
",",
"from_",
"=",
"values",
".",
"unset",
",",
"parent_call_sid",
"=",
"values",
".",
"unset",
",",
"status",
"=",
"values",
".",
"unset",
",",
"start_time_before",
"=",
"values",
"... | 56.428571 | 0.008532 |
def full_path(self):
"""Requested path as unicode, including the query string."""
return self.path + u"?" + to_unicode(self.query_string, self.url_charset) | [
"def",
"full_path",
"(",
"self",
")",
":",
"return",
"self",
".",
"path",
"+",
"u\"?\"",
"+",
"to_unicode",
"(",
"self",
".",
"query_string",
",",
"self",
".",
"url_charset",
")"
] | 56.333333 | 0.017544 |
def run(self):
"""Run the process to get observation data from Backscatter.io."""
kwargs = {'query': self.get_data()}
if self.data_type == "ip":
kwargs.update({'query_type': 'ip'})
elif self.data_type == "network":
kwargs.update({'query_type': 'network'})
... | [
"def",
"run",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"'query'",
":",
"self",
".",
"get_data",
"(",
")",
"}",
"if",
"self",
".",
"data_type",
"==",
"\"ip\"",
":",
"kwargs",
".",
"update",
"(",
"{",
"'query_type'",
":",
"'ip'",
"}",
")",
"elif",
... | 38.608696 | 0.002198 |
async def message(**payload):
"""Display the onboarding welcome message after receiving a message
that contains "start".
"""
data = payload["data"]
web_client = payload["web_client"]
channel_id = data.get("channel")
user_id = data.get("user")
text = data.get("text")
if text and text... | [
"async",
"def",
"message",
"(",
"*",
"*",
"payload",
")",
":",
"data",
"=",
"payload",
"[",
"\"data\"",
"]",
"web_client",
"=",
"payload",
"[",
"\"web_client\"",
"]",
"channel_id",
"=",
"data",
".",
"get",
"(",
"\"channel\"",
")",
"user_id",
"=",
"data",... | 33.333333 | 0.002433 |
def ends_of_next_whole_turn(self, root):
"""Simulate one complete turn to completion and generate each end of
turn reached during the simulation.
Note on mana drain:
Generates but does not continue simulation of mana drains.
Arguments:
root: a start state with no parent... | [
"def",
"ends_of_next_whole_turn",
"(",
"self",
",",
"root",
")",
":",
"# simple confirmation that the root is actually a root.",
"# otherwise it may seem to work but would be totally out of spec",
"if",
"root",
".",
"parent",
":",
"raise",
"ValueError",
"(",
"'Unexpectedly receiv... | 41.483871 | 0.00152 |
def inject(*positional_dependencies, **keyword_dependencies):
"""
This decorator can be used to specify injection rules for decorated
function arguments. Each argument to this decorator should be
a :term:`specification` for injecting into related argument of decorated
function. `None` can be given ... | [
"def",
"inject",
"(",
"*",
"positional_dependencies",
",",
"*",
"*",
"keyword_dependencies",
")",
":",
"def",
"decorator",
"(",
"function",
")",
":",
"dependencies",
"=",
"get_dependencies",
"(",
"function",
")",
"def",
"process_dependency_tuples",
"(",
"tuples",
... | 41.666667 | 0.000489 |
def validate_sbml_model(filename,
check_model=True,
internal_consistency=True,
check_units_consistency=False,
check_modeling_practice=False, **kwargs):
"""Validate SBML model and returns the model along with a list of er... | [
"def",
"validate_sbml_model",
"(",
"filename",
",",
"check_model",
"=",
"True",
",",
"internal_consistency",
"=",
"True",
",",
"check_units_consistency",
"=",
"False",
",",
"check_modeling_practice",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# Errors and w... | 34.292857 | 0.000202 |
def click_a_point(self, x=0, y=0, duration=100):
""" Click on a point"""
self._info("Clicking on a point (%s,%s)." % (x,y))
driver = self._current_application()
action = TouchAction(driver)
try:
action.press(x=float(x), y=float(y)).wait(float(duration)).release(... | [
"def",
"click_a_point",
"(",
"self",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"duration",
"=",
"100",
")",
":",
"self",
".",
"_info",
"(",
"\"Clicking on a point (%s,%s).\"",
"%",
"(",
"x",
",",
"y",
")",
")",
"driver",
"=",
"self",
".",
"_curr... | 45.666667 | 0.01432 |
def ellbiv (mjr, mnr, pa):
"""Given a 2D Gaussian expressed as an ellipse (major, minor, pa), compute the
equivalent parameters for a Gaussian bivariate distribution. We assume
that the ellipse is normalized so that the functions evaluate identicall
for major = minor.
Inputs:
* mjr: major axis... | [
"def",
"ellbiv",
"(",
"mjr",
",",
"mnr",
",",
"pa",
")",
":",
"_ellcheck",
"(",
"mjr",
",",
"mnr",
",",
"pa",
")",
"cpa",
",",
"spa",
"=",
"np",
".",
"cos",
"(",
"pa",
")",
",",
"np",
".",
"sin",
"(",
"pa",
")",
"q",
"=",
"np",
".",
"asar... | 31.666667 | 0.016343 |
def get_address():
"""
Get one or more existing address(es) owned by your user.
---
parameters:
- name: address
in: body
description: The address you'd like to get info about.
required: false
schema:
$ref: '#/definitions/Address'
responses:
'200'... | [
"def",
"get_address",
"(",
")",
":",
"address",
"=",
"request",
".",
"jws_payload",
"[",
"'data'",
"]",
".",
"get",
"(",
"'address'",
")",
"currency",
"=",
"request",
".",
"jws_payload",
"[",
"'data'",
"]",
".",
"get",
"(",
"'currency'",
")",
"network",
... | 29.866667 | 0.001441 |
def _handle_object_info_reply(self, rep):
""" Handle replies for call tips.
"""
self.log.debug("oinfo: %s", rep.get('content', ''))
cursor = self._get_cursor()
info = self._request_info.get('call_tip')
if info and info.id == rep['parent_header']['msg_id'] and \
... | [
"def",
"_handle_object_info_reply",
"(",
"self",
",",
"rep",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"oinfo: %s\"",
",",
"rep",
".",
"get",
"(",
"'content'",
",",
"''",
")",
")",
"cursor",
"=",
"self",
".",
"_get_cursor",
"(",
")",
"info",
... | 49.826087 | 0.001712 |
def parse(readDataInstance, sectionHeadersInstance):
"""
Returns a new L{Sections} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to be parsed as a L{Sections} object.
@type sectionHeadersInstance: instance
... | [
"def",
"parse",
"(",
"readDataInstance",
",",
"sectionHeadersInstance",
")",
":",
"sData",
"=",
"Sections",
"(",
")",
"for",
"sectionHdr",
"in",
"sectionHeadersInstance",
":",
"if",
"sectionHdr",
".",
"sizeOfRawData",
".",
"value",
">",
"len",
"(",
"readDataInst... | 43.558824 | 0.011229 |
def _rebuild_table(self, new_name, old_name, new_columns, old_columns):
''' a helper method for rebuilding table (by renaming & migrating) '''
# verbosity
print('Rebuilding %s table in %s database' % (self.table_name, self.database_name), end='', flush=True)
from sqla... | [
"def",
"_rebuild_table",
"(",
"self",
",",
"new_name",
",",
"old_name",
",",
"new_columns",
",",
"old_columns",
")",
":",
"# verbosity",
"print",
"(",
"'Rebuilding %s table in %s database'",
"%",
"(",
"self",
".",
"table_name",
",",
"self",
".",
"database_name",
... | 40.754386 | 0.010929 |
def get_preorder_burn_info( outputs ):
"""
Given the set of outputs, find the fee sent
to our burn address. This is always the third output.
Return the fee and burn address on success as {'op_fee': ..., 'burn_address': ...}
Return None if not found
"""
if len(outputs) != 3:
... | [
"def",
"get_preorder_burn_info",
"(",
"outputs",
")",
":",
"if",
"len",
"(",
"outputs",
")",
"!=",
"3",
":",
"# not a well-formed preorder ",
"return",
"None",
"op_fee",
"=",
"outputs",
"[",
"2",
"]",
"[",
"'value'",
"]",
"burn_address",
"=",
"None",
"try",
... | 29.5 | 0.016416 |
def get_variables(text):
"""Extracts variables that can be used in templating engines.
Each variable is defined on a single line in the following way:
~ var: text
The ~ must be at the start of a newline, followed by at least one
space. var can be any sequence of characters that does not conta... | [
"def",
"get_variables",
"(",
"text",
")",
":",
"variables",
"=",
"{",
"var",
":",
"value",
"for",
"var",
",",
"value",
"in",
"re_vars",
".",
"findall",
"(",
"text",
")",
"}",
"text",
"=",
"re_vars",
".",
"sub",
"(",
"''",
",",
"text",
")",
"return"... | 34.555556 | 0.001565 |
def app_class():
"""Create Flask application class.
Invenio-Files-REST needs to patch the Werkzeug form parsing in order to
support streaming large file uploads. This is done by subclassing the Flask
application class.
"""
try:
pkg_resources.get_distribution('invenio-files-rest')
... | [
"def",
"app_class",
"(",
")",
":",
"try",
":",
"pkg_resources",
".",
"get_distribution",
"(",
"'invenio-files-rest'",
")",
"from",
"invenio_files_rest",
".",
"app",
"import",
"Flask",
"as",
"FlaskBase",
"except",
"pkg_resources",
".",
"DistributionNotFound",
":",
... | 32.47619 | 0.001425 |
def save_boundaries_from_params_ds9(params, parmodel,
list_islitlet,
list_csu_bar_slit_center,
uuid, grism, spfilter,
ds9_filename, numpix=100,
... | [
"def",
"save_boundaries_from_params_ds9",
"(",
"params",
",",
"parmodel",
",",
"list_islitlet",
",",
"list_csu_bar_slit_center",
",",
"uuid",
",",
"grism",
",",
"spfilter",
",",
"ds9_filename",
",",
"numpix",
"=",
"100",
",",
"global_offset_x_pix",
"=",
"0",
",",
... | 39.908333 | 0.000204 |
def connectivity(dataset, largest=False):
"""Find and label connected bodies/volumes. This adds an ID array to
the point and cell data to distinguish seperate connected bodies.
This applies a ``vtkConnectivityFilter`` filter which extracts cells
that share common points and/or meet other... | [
"def",
"connectivity",
"(",
"dataset",
",",
"largest",
"=",
"False",
")",
":",
"alg",
"=",
"vtk",
".",
"vtkConnectivityFilter",
"(",
")",
"alg",
".",
"SetInputData",
"(",
"dataset",
")",
"if",
"largest",
":",
"alg",
".",
"SetExtractionModeToLargestRegion",
"... | 39.954545 | 0.002222 |
def solve_series(self, x0, params, varied_data, varied_idx,
internal_x0=None, solver=None, propagate=True, **kwargs):
""" Solve system for a set of parameters in which one is varied
Parameters
----------
x0 : array_like
Guess (subject to ``self.post_proc... | [
"def",
"solve_series",
"(",
"self",
",",
"x0",
",",
"params",
",",
"varied_data",
",",
"varied_idx",
",",
"internal_x0",
"=",
"None",
",",
"solver",
"=",
"None",
",",
"propagate",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"x_... | 43.184211 | 0.001489 |
def incr(self, d):
"""
Increases the value by the argument.
:param d: the value to increase by
:type d: float
"""
with self.lock:
self.p = self.value() + d | [
"def",
"incr",
"(",
"self",
",",
"d",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"p",
"=",
"self",
".",
"value",
"(",
")",
"+",
"d"
] | 23.111111 | 0.009259 |
def _get_acquisition(self, model, space):
"""
Imports the acquisition
"""
from copy import deepcopy
acqOpt_config = deepcopy(self.config['acquisition']['optimizer'])
acqOpt_name = acqOpt_config['name']
del acqOpt_config['name']
from ..opt... | [
"def",
"_get_acquisition",
"(",
"self",
",",
"model",
",",
"space",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"acqOpt_config",
"=",
"deepcopy",
"(",
"self",
".",
"config",
"[",
"'acquisition'",
"]",
"[",
"'optimizer'",
"]",
")",
"acqOpt_name",
"=",
"... | 43.571429 | 0.008026 |
def can_afford(self, item_id: Union[UnitTypeId, UpgradeId, AbilityId], check_supply_cost: bool=True) -> "CanAffordWrapper":
"""Tests if the player has enough resources to build a unit or cast an ability."""
enough_supply = True
if isinstance(item_id, UnitTypeId):
unit = self._game_da... | [
"def",
"can_afford",
"(",
"self",
",",
"item_id",
":",
"Union",
"[",
"UnitTypeId",
",",
"UpgradeId",
",",
"AbilityId",
"]",
",",
"check_supply_cost",
":",
"bool",
"=",
"True",
")",
"->",
"\"CanAffordWrapper\"",
":",
"enough_supply",
"=",
"True",
"if",
"isins... | 57.142857 | 0.00984 |
def get_longest_non_repeat_v1(string):
"""
Find the length of the longest substring
without repeating characters.
Return max_len and the substring as a tuple
"""
if string is None:
return 0, ''
sub_string = ''
dict = {}
max_length = 0
j = 0
for i in range(len(string))... | [
"def",
"get_longest_non_repeat_v1",
"(",
"string",
")",
":",
"if",
"string",
"is",
"None",
":",
"return",
"0",
",",
"''",
"sub_string",
"=",
"''",
"dict",
"=",
"{",
"}",
"max_length",
"=",
"0",
"j",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
... | 27.5 | 0.001757 |
def read_tree_newick(newick):
'''Read a tree from a Newick string or file
Args:
``newick`` (``str``): Either a Newick string or the path to a Newick file (plain-text or gzipped)
Returns:
``Tree``: The tree represented by ``newick``. If the Newick file has multiple trees (one per line), a `... | [
"def",
"read_tree_newick",
"(",
"newick",
")",
":",
"if",
"not",
"isinstance",
"(",
"newick",
",",
"str",
")",
":",
"try",
":",
"newick",
"=",
"str",
"(",
"newick",
")",
"except",
":",
"raise",
"TypeError",
"(",
"\"newick must be a str\"",
")",
"if",
"ne... | 39.115385 | 0.013429 |
def symlink(src, link):
'''
Create a symbolic link to a file
This is only supported with Windows Vista or later and must be executed by
a user with the SeCreateSymbolicLink privilege.
The behavior of this function matches the Unix equivalent, with one
exception - invalid symlinks cannot be cre... | [
"def",
"symlink",
"(",
"src",
",",
"link",
")",
":",
"# When Python 3.2 or later becomes the minimum version, this function can be",
"# replaced with the built-in os.symlink function, which supports Windows.",
"if",
"sys",
".",
"getwindowsversion",
"(",
")",
".",
"major",
"<",
... | 30.596154 | 0.001827 |
def add(self, defn):
"""Adds the given Command Definition to this Command Dictionary."""
self[defn.name] = defn
self.opcodes[defn._opcode] = defn | [
"def",
"add",
"(",
"self",
",",
"defn",
")",
":",
"self",
"[",
"defn",
".",
"name",
"]",
"=",
"defn",
"self",
".",
"opcodes",
"[",
"defn",
".",
"_opcode",
"]",
"=",
"defn"
] | 44.25 | 0.016667 |
def __add_tokenization(self, tree):
"""adds a node for each token ID in the document"""
for token_id in self.get_token_ids(tree):
self.add_node(token_id, layers={self.ns})
self.tokens.append(token_id) | [
"def",
"__add_tokenization",
"(",
"self",
",",
"tree",
")",
":",
"for",
"token_id",
"in",
"self",
".",
"get_token_ids",
"(",
"tree",
")",
":",
"self",
".",
"add_node",
"(",
"token_id",
",",
"layers",
"=",
"{",
"self",
".",
"ns",
"}",
")",
"self",
"."... | 47.2 | 0.008333 |
def visitValueType(self, ctx: jsgParser.ValueTypeContext):
""" valueType: idref | nonRefValueType """
if ctx.idref():
self._typeid = as_token(ctx)
else:
self.visitChildren(ctx) | [
"def",
"visitValueType",
"(",
"self",
",",
"ctx",
":",
"jsgParser",
".",
"ValueTypeContext",
")",
":",
"if",
"ctx",
".",
"idref",
"(",
")",
":",
"self",
".",
"_typeid",
"=",
"as_token",
"(",
"ctx",
")",
"else",
":",
"self",
".",
"visitChildren",
"(",
... | 36.5 | 0.008929 |
def index_last_dim_with_indices(x, indices):
"""Use indices to index into the last axis of x.
This can be useful for recovering the actual probabilities of a sample from a
probability distribution.
Args:
x: Tensor, n-d.
indices: Tensor, (n-1)-d, where the dimension sizes match the first (n-1)
di... | [
"def",
"index_last_dim_with_indices",
"(",
"x",
",",
"indices",
")",
":",
"assert",
"len",
"(",
"x",
".",
"shape",
")",
"==",
"len",
"(",
"indices",
".",
"shape",
")",
"+",
"1",
"x_shape",
"=",
"shape_list",
"(",
"x",
")",
"vocab_size",
"=",
"x_shape",... | 26.617647 | 0.012793 |
def power(self, n):
"""Return the compose of a operator with itself n times.
Args:
n (int): the number of times to compose with self (n>0).
Returns:
BaseOperator: the n-times composed operator.
Raises:
QiskitError: if the input and output dimensions... | [
"def",
"power",
"(",
"self",
",",
"n",
")",
":",
"# NOTE: if a subclass can have negative or non-integer powers",
"# this method should be overriden in that class.",
"if",
"not",
"isinstance",
"(",
"n",
",",
"(",
"int",
",",
"np",
".",
"integer",
")",
")",
"or",
"n"... | 38.782609 | 0.002188 |
def check_for_wkhtmltohtml():
"""
Checks to see if the wkhtmltohtml binary is installed. Raises error if not.
"""
locator = 'where' if sys.platform == 'win32' else 'which'
wkhtmltopdf = (subprocess.Popen([locator, 'wkhtmltopdf'],
stdout=subprocess.PIPE)
... | [
"def",
"check_for_wkhtmltohtml",
"(",
")",
":",
"locator",
"=",
"'where'",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
"else",
"'which'",
"wkhtmltopdf",
"=",
"(",
"subprocess",
".",
"Popen",
"(",
"[",
"locator",
",",
"'wkhtmltopdf'",
"]",
",",
"stdout",
... | 41.647059 | 0.001381 |
def setup_directories(base_dir, subdirs):
"""Setup directories."""
base_dir = os.path.expanduser(base_dir)
tf.gfile.MakeDirs(base_dir)
all_dirs = {}
for subdir in subdirs:
if isinstance(subdir, six.string_types):
subdir_tuple = (subdir,)
else:
subdir_tuple = subdir
dir_name = os.path.... | [
"def",
"setup_directories",
"(",
"base_dir",
",",
"subdirs",
")",
":",
"base_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"base_dir",
")",
"tf",
".",
"gfile",
".",
"MakeDirs",
"(",
"base_dir",
")",
"all_dirs",
"=",
"{",
"}",
"for",
"subdir",
"... | 27.8 | 0.020882 |
def point_before_card(self, card, x, y):
"""Return whether ``(x, y)`` is somewhere before ``card``, given how I
know cards to be arranged.
If the cards are being stacked down and to the right, that
means I'm testing whether ``(x, y)`` is above or to the left
of the card.
... | [
"def",
"point_before_card",
"(",
"self",
",",
"card",
",",
"x",
",",
"y",
")",
":",
"def",
"ycmp",
"(",
")",
":",
"if",
"self",
".",
"card_y_hint_step",
"==",
"0",
":",
"return",
"False",
"elif",
"self",
".",
"card_y_hint_step",
">",
"0",
":",
"# sta... | 31.533333 | 0.002051 |
def init_log(logger, loglevel=0):
"""
Initializes logging.
Prints logs to console with level defined by loglevel
Also prints verbose log to the multiqc data directory if available.
(multiqc_data/multiqc.log)
Args:
loglevel (str): Determines the level of the log output.
"""
# Fil... | [
"def",
"init_log",
"(",
"logger",
",",
"loglevel",
"=",
"0",
")",
":",
"# File for logging",
"global",
"log_tmp_dir",
",",
"log_tmp_fn",
"log_tmp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"log_tmp_fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"log_... | 36.555556 | 0.002221 |
def lsst_doc_shortlink_role(name, rawtext, text, lineno, inliner,
options=None, content=None):
"""Link to LSST documents given their handle using LSST's ls.st link
shortener.
Example::
:ldm:`151`
"""
options = options or {}
content = content or []
node =... | [
"def",
"lsst_doc_shortlink_role",
"(",
"name",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"None",
",",
"content",
"=",
"None",
")",
":",
"options",
"=",
"options",
"or",
"{",
"}",
"content",
"=",
"content",
"or",
"... | 29.5625 | 0.002049 |
def store_vector(self, hash_name, bucket_key, v, data):
"""
Stores vector and JSON-serializable data in MongoDB with specified key.
"""
mongo_key = self._format_mongo_key(hash_name, bucket_key)
val_dict = {}
val_dict['lsh'] = mongo_key
# Depending on type (spars... | [
"def",
"store_vector",
"(",
"self",
",",
"hash_name",
",",
"bucket_key",
",",
"v",
",",
"data",
")",
":",
"mongo_key",
"=",
"self",
".",
"_format_mongo_key",
"(",
"hash_name",
",",
"bucket_key",
")",
"val_dict",
"=",
"{",
"}",
"val_dict",
"[",
"'lsh'",
"... | 34 | 0.00143 |
def variant(samples):
"""Variant calling workflow definition for CWL generation.
"""
checkpoints = _variant_checkpoints(samples)
if checkpoints["align"]:
align_wf = _alignment(checkpoints)
alignin = [["files"], ["analysis"],
["config", "algorithm", "align_split_size"],... | [
"def",
"variant",
"(",
"samples",
")",
":",
"checkpoints",
"=",
"_variant_checkpoints",
"(",
"samples",
")",
"if",
"checkpoints",
"[",
"\"align\"",
"]",
":",
"align_wf",
"=",
"_alignment",
"(",
"checkpoints",
")",
"alignin",
"=",
"[",
"[",
"\"files\"",
"]",
... | 50.791667 | 0.000805 |
def add_incomplete(var_name, dependencies):
"""
Incomplete functions don't really need to be 'builders' as they
add no new real structure, but it's helpful to have a function
in which we can raise a warning about the incomplete equation
at translate time.
"""
warnings.warn('%s has no equa... | [
"def",
"add_incomplete",
"(",
"var_name",
",",
"dependencies",
")",
":",
"warnings",
".",
"warn",
"(",
"'%s has no equation specified'",
"%",
"var_name",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"# first arg is `self` reference",
"return",
"\"functions.... | 41 | 0.001988 |
def process_stencil(cookbook, cookbook_name, template_pack,
force_argument, stencil_set, stencil, written_files):
"""Process the stencil requested, writing any missing files as needed.
The stencil named 'stencilset_name' should be one of
templatepack's stencils.
"""
# force can ... | [
"def",
"process_stencil",
"(",
"cookbook",
",",
"cookbook_name",
",",
"template_pack",
",",
"force_argument",
",",
"stencil_set",
",",
"stencil",
",",
"written_files",
")",
":",
"# force can be passed on the command line or forced in a stencil's options",
"force",
"=",
"for... | 42.321429 | 0.000412 |
def up(self,x,L_change = 12):
"""
Upsample and filter the signal
"""
y = L_change*ssd.upsample(x,L_change)
y = signal.sosfilt(self.sos,y)
return y | [
"def",
"up",
"(",
"self",
",",
"x",
",",
"L_change",
"=",
"12",
")",
":",
"y",
"=",
"L_change",
"*",
"ssd",
".",
"upsample",
"(",
"x",
",",
"L_change",
")",
"y",
"=",
"signal",
".",
"sosfilt",
"(",
"self",
".",
"sos",
",",
"y",
")",
"return",
... | 26.857143 | 0.041237 |
def get_user(email, profile="splunk", **kwargs):
'''
Get a splunk user by name/email
CLI Example:
salt myminion splunk.get_user 'user@example.com' user_details=false
salt myminion splunk.get_user 'user@example.com' user_details=true
'''
user_map = list_users(profile)
user_foun... | [
"def",
"get_user",
"(",
"email",
",",
"profile",
"=",
"\"splunk\"",
",",
"*",
"*",
"kwargs",
")",
":",
"user_map",
"=",
"list_users",
"(",
"profile",
")",
"user_found",
"=",
"email",
".",
"lower",
"(",
")",
"in",
"user_map",
".",
"keys",
"(",
")",
"i... | 28.4 | 0.001135 |
def iter_followers(username, number=-1, etag=None):
"""List the followers of ``username``.
:param str username: (required), login of the person to list the followers
of
:param int number: (optional), number of followers to return, Default: -1,
return all of them
:param str etag: (option... | [
"def",
"iter_followers",
"(",
"username",
",",
"number",
"=",
"-",
"1",
",",
"etag",
"=",
"None",
")",
":",
"return",
"gh",
".",
"iter_followers",
"(",
"username",
",",
"number",
",",
"etag",
")",
"if",
"username",
"else",
"[",
"]"
] | 39.538462 | 0.001901 |
def reactToAMQPMessage(message, send_back):
"""
React to given (AMQP) message. `message` is expected to be
:py:func:`collections.namedtuple` structure from :mod:`.structures` filled
with all necessary data.
Args:
message (object): One of the request objects defined in
... | [
"def",
"reactToAMQPMessage",
"(",
"message",
",",
"send_back",
")",
":",
"if",
"_instanceof",
"(",
"message",
",",
"structures",
".",
"ScanFile",
")",
":",
"result",
"=",
"antivirus",
".",
"save_and_scan",
"(",
"message",
".",
"filename",
",",
"message",
"."... | 35.314286 | 0.000787 |
def convertColors(element):
"""
Recursively converts all color properties into #RRGGBB format if shorter
"""
numBytes = 0
if element.nodeType != Node.ELEMENT_NODE:
return 0
# set up list of color attributes for each element type
attrsToConvert = []
if element.nodeName in ['r... | [
"def",
"convertColors",
"(",
"element",
")",
":",
"numBytes",
"=",
"0",
"if",
"element",
".",
"nodeType",
"!=",
"Node",
".",
"ELEMENT_NODE",
":",
"return",
"0",
"# set up list of color attributes for each element type",
"attrsToConvert",
"=",
"[",
"]",
"if",
"elem... | 36.086957 | 0.000587 |
def on_change_checkout(self):
'''
When you change checkin_date or checkout_date it will checked it
and update the qty of hotel folio line
-----------------------------------------------------------------
@param self: object pointer
'''
configured_addition_hours = ... | [
"def",
"on_change_checkout",
"(",
"self",
")",
":",
"configured_addition_hours",
"=",
"0",
"fwhouse_id",
"=",
"self",
".",
"folio_id",
".",
"warehouse_id",
"fwc_id",
"=",
"fwhouse_id",
"or",
"fwhouse_id",
".",
"company_id",
"if",
"fwc_id",
":",
"configured_additio... | 47.875 | 0.000731 |
def get_subwords(self, word, on_unicode_error='strict'):
"""
Given a word, get the subwords and their indicies.
"""
pair = self.f.getSubwords(word, on_unicode_error)
return pair[0], np.array(pair[1]) | [
"def",
"get_subwords",
"(",
"self",
",",
"word",
",",
"on_unicode_error",
"=",
"'strict'",
")",
":",
"pair",
"=",
"self",
".",
"f",
".",
"getSubwords",
"(",
"word",
",",
"on_unicode_error",
")",
"return",
"pair",
"[",
"0",
"]",
",",
"np",
".",
"array",... | 39 | 0.008368 |
def op_get_mutate_fields( op_name ):
"""
Get the names of the fields that will change
when this operation gets applied to a record.
"""
global MUTATE_FIELDS
if op_name not in MUTATE_FIELDS.keys():
raise Exception("No such operation '%s'" % op_name)
fields = MUTATE_FIELDS[op_name][:... | [
"def",
"op_get_mutate_fields",
"(",
"op_name",
")",
":",
"global",
"MUTATE_FIELDS",
"if",
"op_name",
"not",
"in",
"MUTATE_FIELDS",
".",
"keys",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"No such operation '%s'\"",
"%",
"op_name",
")",
"fields",
"=",
"MUTATE_FI... | 27.333333 | 0.00885 |
def noise_gaussian(self, mean, std):
"""Create a gaussian noise variable"""
assert std > 0
ng = self.sym.sym('ng_{:d}'.format(len(self.scope['ng'])))
self.scope['ng'].append(ng)
return mean + std*ng | [
"def",
"noise_gaussian",
"(",
"self",
",",
"mean",
",",
"std",
")",
":",
"assert",
"std",
">",
"0",
"ng",
"=",
"self",
".",
"sym",
".",
"sym",
"(",
"'ng_{:d}'",
".",
"format",
"(",
"len",
"(",
"self",
".",
"scope",
"[",
"'ng'",
"]",
")",
")",
"... | 38.833333 | 0.008403 |
def accept(self):
"""Launch the multi exposure analysis."""
if not isinstance(
self._multi_exposure_if, MultiExposureImpactFunction):
# This should not happen as the "accept" button must be disabled if
# the impact function is not ready.
return ANALYSI... | [
"def",
"accept",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_multi_exposure_if",
",",
"MultiExposureImpactFunction",
")",
":",
"# This should not happen as the \"accept\" button must be disabled if",
"# the impact function is not ready.",
"return",
"... | 45.006135 | 0.000267 |
def brcktd(number, end1, end2):
"""
Bracket a number. That is, given a number and an acceptable
interval, make sure that the number is contained in the
interval. (If the number is already in the interval, leave it
alone. If not, set it to the nearest endpoint of the interval.)
http://naif.jpl.n... | [
"def",
"brcktd",
"(",
"number",
",",
"end1",
",",
"end2",
")",
":",
"number",
"=",
"ctypes",
".",
"c_double",
"(",
"number",
")",
"end1",
"=",
"ctypes",
".",
"c_double",
"(",
"end1",
")",
"end2",
"=",
"ctypes",
".",
"c_double",
"(",
"end2",
")",
"r... | 36.318182 | 0.00122 |
def image_to_url(image, colormap=None, origin='upper'):
"""Infers the type of an image argument and transforms it into a URL.
Parameters
----------
image: string, file or array-like object
* If string, it will be written directly in the output file.
* If file, it's content will be conve... | [
"def",
"image_to_url",
"(",
"image",
",",
"colormap",
"=",
"None",
",",
"origin",
"=",
"'upper'",
")",
":",
"if",
"hasattr",
"(",
"image",
",",
"'read'",
")",
":",
"# We got an image file.",
"if",
"hasattr",
"(",
"image",
",",
"'name'",
")",
":",
"# We t... | 44.153846 | 0.000568 |
def mat2quat(rmat, precise=False):
"""
Converts given rotation matrix to quaternion.
Args:
rmat: 3x3 rotation matrix
precise: If isprecise is True, the input matrix is assumed to be a precise
rotation matrix and a faster algorithm is used.
Returns:
vec4 float quate... | [
"def",
"mat2quat",
"(",
"rmat",
",",
"precise",
"=",
"False",
")",
":",
"M",
"=",
"np",
".",
"array",
"(",
"rmat",
",",
"dtype",
"=",
"np",
".",
"float32",
",",
"copy",
"=",
"False",
")",
"[",
":",
"3",
",",
":",
"3",
"]",
"if",
"precise",
":... | 29.75 | 0.001627 |
def fit_plots(ax,xfit,xraw,yfit,yraw):
'''
#====================================================================
plot the fitted results for data fit and refit
#====================================================================
'''
global _yfits_
_yfits_ = yfit
ax.plot(xfit, yfit)
... | [
"def",
"fit_plots",
"(",
"ax",
",",
"xfit",
",",
"xraw",
",",
"yfit",
",",
"yraw",
")",
":",
"global",
"_yfits_",
"_yfits_",
"=",
"yfit",
"ax",
".",
"plot",
"(",
"xfit",
",",
"yfit",
")",
"ax",
".",
"plot",
"(",
"xfit",
",",
"np",
".",
"sum",
"... | 34.384615 | 0.013072 |
def start_parallel(self):
"""Initialize all queues and start the worker processes and the log
thread.
"""
self.num_processes = get_num_processes()
self.task_queue = multiprocessing.Queue(maxsize=Q_MAX_SIZE)
self.result_queue = multiprocessing.Queue()
self.log_que... | [
"def",
"start_parallel",
"(",
"self",
")",
":",
"self",
".",
"num_processes",
"=",
"get_num_processes",
"(",
")",
"self",
".",
"task_queue",
"=",
"multiprocessing",
".",
"Queue",
"(",
"maxsize",
"=",
"Q_MAX_SIZE",
")",
"self",
".",
"result_queue",
"=",
"mult... | 35.703704 | 0.00202 |
def set_option(self, name, value):
"""
Sets the specified generic configuration option to the given value.
"""
self.__validate_option_name(name)
self.__options[name] = value | [
"def",
"set_option",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"__validate_option_name",
"(",
"name",
")",
"self",
".",
"__options",
"[",
"name",
"]",
"=",
"value"
] | 34.666667 | 0.00939 |
def projector_functions(self):
"""Dictionary with the PAW projectors indexed by state."""
projector_functions = OrderedDict()
for (mesh, values, attrib) in self._parse_all_radfuncs("projector_function"):
state = attrib["state"]
#val_state = self.valence_states[state]
... | [
"def",
"projector_functions",
"(",
"self",
")",
":",
"projector_functions",
"=",
"OrderedDict",
"(",
")",
"for",
"(",
"mesh",
",",
"values",
",",
"attrib",
")",
"in",
"self",
".",
"_parse_all_radfuncs",
"(",
"\"projector_function\"",
")",
":",
"state",
"=",
... | 45.888889 | 0.009501 |
def clean(document):
""" Perform misc cleaning operations on documents.
Returns cleaned document.
"""
newdocument = document
# Clean empty text and r tags
for t in ('t', 'r'):
rmlist = []
for element in newdocument.iter():
if element.tag == '{%s}%s' % (nsprefixe... | [
"def",
"clean",
"(",
"document",
")",
":",
"newdocument",
"=",
"document",
"# Clean empty text and r tags",
"for",
"t",
"in",
"(",
"'t'",
",",
"'r'",
")",
":",
"rmlist",
"=",
"[",
"]",
"for",
"element",
"in",
"newdocument",
".",
"iter",
"(",
")",
":",
... | 28.777778 | 0.001869 |
def clone(self):
"""
Do not initialize again since everything is ready to launch app.
:return: Initialized monitor instance
"""
return Monitor(org=self.org, app=self.app, env=self.env) | [
"def",
"clone",
"(",
"self",
")",
":",
"return",
"Monitor",
"(",
"org",
"=",
"self",
".",
"org",
",",
"app",
"=",
"self",
".",
"app",
",",
"env",
"=",
"self",
".",
"env",
")"
] | 36.5 | 0.008929 |
def _KillProcess(self, pid):
"""Issues a SIGKILL or equivalent to the process.
Args:
pid (int): process identifier (PID).
"""
if sys.platform.startswith('win'):
process_terminate = 1
handle = ctypes.windll.kernel32.OpenProcess(
process_terminate, False, pid)
ctypes.win... | [
"def",
"_KillProcess",
"(",
"self",
",",
"pid",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
":",
"process_terminate",
"=",
"1",
"handle",
"=",
"ctypes",
".",
"windll",
".",
"kernel32",
".",
"OpenProcess",
"(",
"process_t... | 31.210526 | 0.011457 |
def slurpLines(file, expand=False):
r"""Read in a complete file (specified by a file handler or a filename
string/unicode string) as list of lines"""
file = _normalizeToFile(file, "r", expand)
try: return file.readlines()
finally: file.close() | [
"def",
"slurpLines",
"(",
"file",
",",
"expand",
"=",
"False",
")",
":",
"file",
"=",
"_normalizeToFile",
"(",
"file",
",",
"\"r\"",
",",
"expand",
")",
"try",
":",
"return",
"file",
".",
"readlines",
"(",
")",
"finally",
":",
"file",
".",
"close",
"... | 43.666667 | 0.014981 |
def checkstring(somestr, interchange = ALL):
"""
Checks that some string is palindrome. Checking performs case-insensitive
:param str somestr:
It is some string that will be checked for palindrome as string.
The string is any string that you want. The string also can be multiline.
If t... | [
"def",
"checkstring",
"(",
"somestr",
",",
"interchange",
"=",
"ALL",
")",
":",
"# check invalid data types",
"OnlyStringsCanBeChecked",
"(",
"somestr",
")",
"if",
"somestr",
"!=",
"\"\"",
":",
"# remove all special symbols",
"pattern",
"=",
"r'[^\\w]+|[_]+'",
"purest... | 30.219512 | 0.052385 |
def get_rate_limits():
"""Retrieve status (and optionally) version from the API."""
client = get_rates_api()
with catch_raise_api_exception():
data, _, headers = client.rates_limits_list_with_http_info()
ratelimits.maybe_rate_limit(client, headers)
return {
k: RateLimitsInfo.from_... | [
"def",
"get_rate_limits",
"(",
")",
":",
"client",
"=",
"get_rates_api",
"(",
")",
"with",
"catch_raise_api_exception",
"(",
")",
":",
"data",
",",
"_",
",",
"headers",
"=",
"client",
".",
"rates_limits_list_with_http_info",
"(",
")",
"ratelimits",
".",
"maybe... | 30.153846 | 0.002475 |
def after(self, func=None, other_parents=None):
'''Create a new Future whose completion depends on this one
The new future will have a function that it calls once all its parents
have completed, the return value of which will be its final value.
There is a special case, however, in whic... | [
"def",
"after",
"(",
"self",
",",
"func",
"=",
"None",
",",
"other_parents",
"=",
"None",
")",
":",
"parents",
"=",
"[",
"self",
"]",
"if",
"other_parents",
"is",
"not",
"None",
":",
"parents",
"+=",
"other_parents",
"return",
"after",
"(",
"parents",
... | 45.142857 | 0.001549 |
def assertCategoricalLevelsEqual(self, levels1, levels2, msg=None):
'''Fail if ``levels1`` and ``levels2`` do not have the same
domain.
Parameters
----------
levels1 : iterable
levels2 : iterable
msg : str
If not provided, the :mod:`marbles.mixins` or... | [
"def",
"assertCategoricalLevelsEqual",
"(",
"self",
",",
"levels1",
",",
"levels2",
",",
"msg",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"levels1",
",",
"collections",
".",
"Iterable",
")",
":",
"raise",
"TypeError",
"(",
"'First argument is not ... | 35.517241 | 0.00189 |
def prepare_service(data):
"""Prepare service for catalog endpoint
Parameters:
data (Union[str, dict]): Service ID or service definition
Returns:
Tuple[str, dict]: str is ID and dict is service
Transform ``/v1/health/state/<state>``::
{
"Node": "foobar",
... | [
"def",
"prepare_service",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"None",
",",
"{",
"}",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"return",
"data",
",",
"{",
"}",
"# from /v1/health/service/<service>",
"if",
"all",
"(",
... | 25.376623 | 0.000493 |
def _main(argv, standard_out, standard_error):
"""Run quotes unifying on files.
Returns `1` if any quoting changes are still needed, otherwise
`None`.
"""
import argparse
parser = argparse.ArgumentParser(description=__doc__, prog='unify')
parser.add_argument('-i', '--in-place', action='sto... | [
"def",
"_main",
"(",
"argv",
",",
"standard_out",
",",
"standard_error",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"prog",
"=",
"'unify'",
")",
"parser",
".",
"add_argument",
"(... | 41.787234 | 0.000498 |
def reportDeprecatedWorkerNameUsage(message, stacklevel=None, filename=None,
lineno=None):
"""Hook that is ran when old API name is used.
:param stacklevel: stack level relative to the caller's frame.
Defaults to caller of the caller of this function.
"""
if fil... | [
"def",
"reportDeprecatedWorkerNameUsage",
"(",
"message",
",",
"stacklevel",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"lineno",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"if",
"stacklevel",
"is",
"None",
":",
"# Warning will refer to t... | 30.222222 | 0.001188 |
def write_waypoint(self, **kw):
"""
Write a waypoint to the file::
writer.write_waypoint(
name='Meiersberg',
latitude=51.4,
longitude=7.1
)
# <Waypoint name="Meiersberg">
# <Location latitude="51.4" lon... | [
"def",
"write_waypoint",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"assert",
"'name'",
"in",
"kw",
"assert",
"'latitude'",
"in",
"kw",
"assert",
"'longitude'",
"in",
"kw",
"location_kw",
"=",
"{",
"'latitude'",
":",
"kw",
"[",
"'latitude'",
"]",
",",
... | 30.083333 | 0.001789 |
def markdown_2_rst(lines):
"""
Convert markdown to restructured text
"""
out = []
code = False
for line in lines:
# code blocks
if line.strip() == "```":
code = not code
space = " " * (len(line.rstrip()) - 3)
if code:
out.append... | [
"def",
"markdown_2_rst",
"(",
"lines",
")",
":",
"out",
"=",
"[",
"]",
"code",
"=",
"False",
"for",
"line",
"in",
"lines",
":",
"# code blocks",
"if",
"line",
".",
"strip",
"(",
")",
"==",
"\"```\"",
":",
"code",
"=",
"not",
"code",
"space",
"=",
"... | 27.521739 | 0.001527 |
def _router_address(self, data):
"""only for IPv6 addresses"""
args = data.split()[1:]
try:
self._relay_attrs['ip_v6'].extend(args)
except KeyError:
self._relay_attrs['ip_v6'] = list(args) | [
"def",
"_router_address",
"(",
"self",
",",
"data",
")",
":",
"args",
"=",
"data",
".",
"split",
"(",
")",
"[",
"1",
":",
"]",
"try",
":",
"self",
".",
"_relay_attrs",
"[",
"'ip_v6'",
"]",
".",
"extend",
"(",
"args",
")",
"except",
"KeyError",
":",... | 34 | 0.008197 |
def parse_url(url):
"""Parse Redis connection URI.
Parse according to IANA specs:
* https://www.iana.org/assignments/uri-schemes/prov/redis
* https://www.iana.org/assignments/uri-schemes/prov/rediss
Also more rules applied:
* empty scheme is treated as unix socket path no further parsing is d... | [
"def",
"parse_url",
"(",
"url",
")",
":",
"r",
"=",
"urlparse",
"(",
"url",
")",
"assert",
"r",
".",
"scheme",
"in",
"(",
"''",
",",
"'redis'",
",",
"'rediss'",
",",
"'unix'",
")",
",",
"(",
"\"Unsupported URI scheme\"",
",",
"r",
".",
"scheme",
")",... | 33.391304 | 0.000633 |
def _find_address_values_in_chain(self, base_contexts, addresses_to_find):
"""Breadth first search through the chain of contexts searching for
the bytes values at the addresses in addresses_to_find.
Args:
base_contexts (list of str): The context ids to start with.
addres... | [
"def",
"_find_address_values_in_chain",
"(",
"self",
",",
"base_contexts",
",",
"addresses_to_find",
")",
":",
"contexts_in_chain",
"=",
"deque",
"(",
")",
"contexts_in_chain",
".",
"extend",
"(",
"base_contexts",
")",
"reads",
"=",
"list",
"(",
"addresses_to_find",... | 39.180556 | 0.000692 |
def execute(cls, stage, state, data, next_allowed_exec_time=None):
"""Execute the operation, rate limiting allowing."""
try:
context = Context.from_state(state, stage)
now = datetime.utcnow()
if next_allowed_exec_time and now < next_allowed_exec_time:
... | [
"def",
"execute",
"(",
"cls",
",",
"stage",
",",
"state",
",",
"data",
",",
"next_allowed_exec_time",
"=",
"None",
")",
":",
"try",
":",
"context",
"=",
"Context",
".",
"from_state",
"(",
"state",
",",
"stage",
")",
"now",
"=",
"datetime",
".",
"utcnow... | 46.741935 | 0.001352 |
async def _send_frame(self, message: bytes, opcode: int,
compress: Optional[int]=None) -> None:
"""Send a frame over the websocket with message as its payload."""
if self._closing:
ws_logger.warning('websocket connection is closing.')
rsv = 0
# Onl... | [
"async",
"def",
"_send_frame",
"(",
"self",
",",
"message",
":",
"bytes",
",",
"opcode",
":",
"int",
",",
"compress",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"None",
":",
"if",
"self",
".",
"_closing",
":",
"ws_logger",
".",
"warnin... | 39.166667 | 0.002076 |
def set(self, section, option, value = None, title = None, validate = None, help = None, control = None, args = None, kwargs = None, include = None):
"""
set(self, section, option, value = None, title = None, validate = lambda value: None, help = '', control = None, args = [], kwargs = {}, include = True)
Stor... | [
"def",
"set",
"(",
"self",
",",
"section",
",",
"option",
",",
"value",
"=",
"None",
",",
"title",
"=",
"None",
",",
"validate",
"=",
"None",
",",
"help",
"=",
"None",
",",
"control",
"=",
"None",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"No... | 40.951613 | 0.033077 |
def input_file(self):
"""Returns the input file name, with a default relative path
"""
return path.join(path.dirname(__file__), 'data', 'tgs{:s}.tsv'.format(self.number)) | [
"def",
"input_file",
"(",
"self",
")",
":",
"return",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'data'",
",",
"'tgs{:s}.tsv'",
".",
"format",
"(",
"self",
".",
"number",
")",
")"
] | 47.75 | 0.015464 |
def write_df_tpl(filename,df,sep=',',tpl_marker='~',**kwargs):
"""function write a pandas dataframe to a template file.
Parameters
----------
filename : str
template filename
df : pandas.DataFrame
dataframe to write
sep : char
separate to pass to df.to_csv(). default is '... | [
"def",
"write_df_tpl",
"(",
"filename",
",",
"df",
",",
"sep",
"=",
"','",
",",
"tpl_marker",
"=",
"'~'",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"\"ptf {0}\\n\"",... | 26.827586 | 0.011166 |
def __getRefererUrl(self, url=None):
"""
gets the referer url for the token handler
"""
if url is None:
url = "http://www.arcgis.com/sharing/rest/portals/self"
params = {
"f" : "json",
"token" : self.token
}
val = self._get(url=... | [
"def",
"__getRefererUrl",
"(",
"self",
",",
"url",
"=",
"None",
")",
":",
"if",
"url",
"is",
"None",
":",
"url",
"=",
"\"http://www.arcgis.com/sharing/rest/portals/self\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"token\"",
":",
"self",
".",
"to... | 37.125 | 0.014778 |
def settings_module_reset(self):
"""
Resets the module settings back to default. Uses DELETE to /settings/modules interface.
"""
data = {
"auth_password": self._password
}
response = self._delete(url.settings_modules, body=data)
self._check_response(... | [
"def",
"settings_module_reset",
"(",
"self",
")",
":",
"data",
"=",
"{",
"\"auth_password\"",
":",
"self",
".",
"_password",
"}",
"response",
"=",
"self",
".",
"_delete",
"(",
"url",
".",
"settings_modules",
",",
"body",
"=",
"data",
")",
"self",
".",
"_... | 32.5 | 0.008982 |
def _query(self, url, data = None):
""" query method to do HTTP POST/GET
Parameters:
url -> the url to POST/GET
data -> header_data as a dict (only for POST)
Returns:
Parsed JSON data as dict
or
None on err... | [
"def",
"_query",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
")",
":",
"auth",
"=",
"encodestring",
"(",
"'%s:%s'",
"%",
"(",
"self",
".",
"user",
",",
"self",
".",
"secret",
")",
")",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
"if",
... | 36.655172 | 0.010999 |
def pythonize(self, val):
"""Convert value into a dict::
* If value is a list, try to take the last element
* split "key=value" string and convert to { key:value }
:param val: value to convert
:type val:
:return: log level corresponding to value
:rtype: str
... | [
"def",
"pythonize",
"(",
"self",
",",
"val",
")",
":",
"val",
"=",
"unique_value",
"(",
"val",
")",
"def",
"split",
"(",
"keyval",
")",
":",
"\"\"\"Split key-value string into (key,value)\n\n :param keyval: key value string\n :return: key, value\n ... | 30.925 | 0.002351 |
def ensure_resource_data(self, update_data=False):
"""Retrieves data from OneView and updates resource object.
Args:
update_data: Flag to update resource data when it is required.
"""
# Check for unique identifier in the resource data
if not any(key in self.data for ... | [
"def",
"ensure_resource_data",
"(",
"self",
",",
"update_data",
"=",
"False",
")",
":",
"# Check for unique identifier in the resource data",
"if",
"not",
"any",
"(",
"key",
"in",
"self",
".",
"data",
"for",
"key",
"in",
"self",
".",
"UNIQUE_IDENTIFIERS",
")",
"... | 38.125 | 0.002398 |
def add_code_verifier(request_args, service, **kwargs):
"""
PKCE RFC 7636 support
To be added as a post_construct method to an
:py:class:`oidcservice.oidc.service.AccessToken` instance
:param service: The service that uses this function
:param request_args: Set of request arguments
:return:... | [
"def",
"add_code_verifier",
"(",
"request_args",
",",
"service",
",",
"*",
"*",
"kwargs",
")",
":",
"_item",
"=",
"service",
".",
"get_item",
"(",
"Message",
",",
"'pkce'",
",",
"kwargs",
"[",
"'state'",
"]",
")",
"request_args",
".",
"update",
"(",
"{",... | 38.692308 | 0.001942 |
def line2argv(line):
r"""Parse the given line into an argument vector.
"line" is the line of input to parse.
This may get niggly when dealing with quoting and escaping. The
current state of this parsing may not be completely thorough/correct
in this respect.
>>> from cmdln import line2arg... | [
"def",
"line2argv",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"argv",
"=",
"[",
"]",
"state",
"=",
"\"default\"",
"arg",
"=",
"None",
"# the current argument being parsed",
"i",
"=",
"-",
"1",
"WHITESPACE",
"=",
"'\\t\\n\\x0b\\x0c... | 29.403361 | 0.001935 |
def main():
"""
NAME
zeq.py
DESCRIPTION
plots demagnetization data. The equal area projection has the X direction (usually North in geographic coordinates)
to the top. The red line is the X axis of the Zijderveld diagram. Solid symbols are lower hemisphere.
The solid ... | [
"def",
"main",
"(",
")",
":",
"files",
",",
"fmt",
",",
"plot",
"=",
"{",
"}",
",",
"'svg'",
",",
"0",
"end_pca",
",",
"beg_pca",
"=",
"\"\"",
",",
"\"\"",
"calculation_type",
"=",
"'DE-BFL'",
"if",
"'-h'",
"in",
"sys",
".",
"argv",
":",
"# check i... | 56.114943 | 0.03965 |
def set(self, value):
"""(Helper) Set custom value."""
self._elk.send(cw_encode(self._index, value, self.value_format)) | [
"def",
"set",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_elk",
".",
"send",
"(",
"cw_encode",
"(",
"self",
".",
"_index",
",",
"value",
",",
"self",
".",
"value_format",
")",
")"
] | 44.333333 | 0.014815 |
def write_image_to_disk(self, msg, result, fh):
"""Decode message to PNG and write to disk."""
fh.write(base64.b64decode(result.group(1).encode('utf-8'))) | [
"def",
"write_image_to_disk",
"(",
"self",
",",
"msg",
",",
"result",
",",
"fh",
")",
":",
"fh",
".",
"write",
"(",
"base64",
".",
"b64decode",
"(",
"result",
".",
"group",
"(",
"1",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
")"
] | 56 | 0.011765 |
def get_eff_gain(base_std, base_std_unc, meth_std, meth_std_unc, adjust=1):
r"""Calculates efficiency gain for a new method compared to a base method.
Given the variation in repeated calculations' results using the two
methods, the efficiency gain is:
.. math::
\mathrm{efficiency\,gain}
... | [
"def",
"get_eff_gain",
"(",
"base_std",
",",
"base_std_unc",
",",
"meth_std",
",",
"meth_std_unc",
",",
"adjust",
"=",
"1",
")",
":",
"ratio",
"=",
"base_std",
"/",
"meth_std",
"ratio_unc",
"=",
"array_ratio_std",
"(",
"base_std",
",",
"base_std_unc",
",",
"... | 28.076923 | 0.000883 |
def get_ca_bundle(opts=None):
'''
Return the location of the ca bundle file. See the following article:
http://tinyurl.com/k7rx42a
'''
if hasattr(get_ca_bundle, '__return_value__'):
return get_ca_bundle.__return_value__
if opts is None:
opts = {}
opts_bundle = opts.get... | [
"def",
"get_ca_bundle",
"(",
"opts",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"get_ca_bundle",
",",
"'__return_value__'",
")",
":",
"return",
"get_ca_bundle",
".",
"__return_value__",
"if",
"opts",
"is",
"None",
":",
"opts",
"=",
"{",
"}",
"opts_bundle",... | 30.645833 | 0.000659 |
def _get_old_entry_identifiers(namespace: Namespace) -> Set[NamespaceEntry]:
"""Convert a PyBEL generalized namespace entries to a set.
Default to using the identifier, but can be overridden to use the name instead.
>>> {term.identifier for term in namespace.entries}
"""
return... | [
"def",
"_get_old_entry_identifiers",
"(",
"namespace",
":",
"Namespace",
")",
"->",
"Set",
"[",
"NamespaceEntry",
"]",
":",
"return",
"{",
"term",
".",
"identifier",
"for",
"term",
"in",
"namespace",
".",
"entries",
"}"
] | 45.125 | 0.008152 |
def save(coll, to_save):
"""
Pymongo has deprecated the save logic, even though
MongoDB still advertizes that logic in the core API:
https://docs.mongodb.com/manual/reference/method/db.collection.save/
This function provides a compatible interface.
"""
filter = Projection(['_id'], to_save)
upsert_replace = fun... | [
"def",
"save",
"(",
"coll",
",",
"to_save",
")",
":",
"filter",
"=",
"Projection",
"(",
"[",
"'_id'",
"]",
",",
"to_save",
")",
"upsert_replace",
"=",
"functools",
".",
"partial",
"(",
"coll",
".",
"replace_one",
",",
"filter",
",",
"upsert",
"=",
"Tru... | 36.166667 | 0.024719 |
def configure(self, options, conf):
"""Configure plugin. Plugin is enabled by default.
"""
self.conf = conf
if not options.capture:
self.enabled = False | [
"def",
"configure",
"(",
"self",
",",
"options",
",",
"conf",
")",
":",
"self",
".",
"conf",
"=",
"conf",
"if",
"not",
"options",
".",
"capture",
":",
"self",
".",
"enabled",
"=",
"False"
] | 31.833333 | 0.010204 |
def _glyph_for_monomer_pattern(self, pattern):
"""Add glyph for a PySB MonomerPattern."""
pattern.matches_key = lambda: str(pattern)
agent_id = self._make_agent_id(pattern)
# Handle sources and sinks
if pattern.monomer.name in ('__source', '__sink'):
return None
... | [
"def",
"_glyph_for_monomer_pattern",
"(",
"self",
",",
"pattern",
")",
":",
"pattern",
".",
"matches_key",
"=",
"lambda",
":",
"str",
"(",
"pattern",
")",
"agent_id",
"=",
"self",
".",
"_make_agent_id",
"(",
"pattern",
")",
"# Handle sources and sinks",
"if",
... | 45.055556 | 0.002414 |
def list_users(root=None):
'''
Return a list of all users
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' user.list_users
'''
if root is not None and __grains__['kernel'] != 'AIX':
getpwall = functools.partial(_getpwall, root=root)
els... | [
"def",
"list_users",
"(",
"root",
"=",
"None",
")",
":",
"if",
"root",
"is",
"not",
"None",
"and",
"__grains__",
"[",
"'kernel'",
"]",
"!=",
"'AIX'",
":",
"getpwall",
"=",
"functools",
".",
"partial",
"(",
"_getpwall",
",",
"root",
"=",
"root",
")",
... | 21.736842 | 0.00232 |
def VCTools(self):
"""
Microsoft Visual C++ Tools
"""
si = self.si
tools = [os.path.join(si.VCInstallDir, 'VCPackages')]
forcex86 = True if self.vc_ver <= 10.0 else False
arch_subdir = self.pi.cross_dir(forcex86)
if arch_subdir:
tools += [os.p... | [
"def",
"VCTools",
"(",
"self",
")",
":",
"si",
"=",
"self",
".",
"si",
"tools",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"si",
".",
"VCInstallDir",
",",
"'VCPackages'",
")",
"]",
"forcex86",
"=",
"True",
"if",
"self",
".",
"vc_ver",
"<=",
"... | 34.433333 | 0.001883 |
def slot(self):
"""The slot of this touch event.
See the kernel's multitouch protocol B documentation for more
information.
If the touch event has no assigned slot, for example if it is from
a single touch device, this property returns -1.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_... | [
"def",
"slot",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"==",
"EventType",
".",
"TOUCH_FRAME",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_libinput",
".",
"lib... | 31.458333 | 0.025707 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.