text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def rows_to_columns(data, schema=None):
"""
:param data: array of objects
:param schema: Known schema, will be extended to include all properties found in data
:return: Table
"""
if not schema:
schema = SchemaTree()
all_schema = schema
all_leaves = schema.leaves
values = {ful... | [
"def",
"rows_to_columns",
"(",
"data",
",",
"schema",
"=",
"None",
")",
":",
"if",
"not",
"schema",
":",
"schema",
"=",
"SchemaTree",
"(",
")",
"all_schema",
"=",
"schema",
"all_leaves",
"=",
"schema",
".",
"leaves",
"values",
"=",
"{",
"full_name",
":",... | 44.309735 | 0.002149 |
def mouseMoveEvent(self, event):
"""Determines if a drag is taking place, and initiates it"""
super(AbstractDragView, self).mouseMoveEvent(event)
if self.dragStartPosition is None or \
(event.pos() - self.dragStartPosition).manhattanLength() < QtGui.QApplication.startDragDistance():
... | [
"def",
"mouseMoveEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"AbstractDragView",
",",
"self",
")",
".",
"mouseMoveEvent",
"(",
"event",
")",
"if",
"self",
".",
"dragStartPosition",
"is",
"None",
"or",
"(",
"event",
".",
"pos",
"(",
")",
... | 39.076923 | 0.004321 |
def word(cap=False):
""" This function generates a fake word by creating between two and three
random syllables and then joining them together.
"""
syllables = []
for x in range(random.randint(2,3)):
syllables.append(_syllable())
word = "".join(syllables)
if cap: word = word[0].u... | [
"def",
"word",
"(",
"cap",
"=",
"False",
")",
":",
"syllables",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"random",
".",
"randint",
"(",
"2",
",",
"3",
")",
")",
":",
"syllables",
".",
"append",
"(",
"_syllable",
"(",
")",
")",
"word",
"="... | 34.4 | 0.008499 |
def parse(self, rrstr):
# type: (bytes) -> None
'''
Parse a Rock Ridge Sharing Protocol record out of a string.
Parameters:
rrstr - The string to parse the record out of.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexcep... | [
"def",
"parse",
"(",
"self",
",",
"rrstr",
")",
":",
"# type: (bytes) -> None",
"if",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'SP record already initialized!'",
")",
"(",
"su_len",
",",
"su_entry_version_unused... | 37.36 | 0.006263 |
def get_consensus_tree(self, cutoff=0.0, best_tree=None):
"""
Returns an extended majority rule consensus tree as a Toytree object.
Node labels include 'support' values showing the occurrence of clades
in the consensus tree across trees in the input treelist.
Clades with suppor... | [
"def",
"get_consensus_tree",
"(",
"self",
",",
"cutoff",
"=",
"0.0",
",",
"best_tree",
"=",
"None",
")",
":",
"if",
"best_tree",
":",
"raise",
"NotImplementedError",
"(",
"\"best_tree option not yet supported.\"",
")",
"cons",
"=",
"ConsensusTree",
"(",
"self",
... | 49.08 | 0.008793 |
def add_child(self, label_str, type_str):
"""Add a child node."""
child_node = SubjectInfoNode(label_str, type_str)
child_node.parent = self
self.child_list.append(child_node)
return child_node | [
"def",
"add_child",
"(",
"self",
",",
"label_str",
",",
"type_str",
")",
":",
"child_node",
"=",
"SubjectInfoNode",
"(",
"label_str",
",",
"type_str",
")",
"child_node",
".",
"parent",
"=",
"self",
"self",
".",
"child_list",
".",
"append",
"(",
"child_node",... | 38 | 0.008584 |
def namedbidict(typename, keyname, valname, base_type=bidict):
r"""Create a new subclass of *base_type* with custom accessors.
Analagous to :func:`collections.namedtuple`.
The new class's ``__name__`` will be set to *typename*.
Instances of it will provide access to their
:attr:`inverse <Bidirect... | [
"def",
"namedbidict",
"(",
"typename",
",",
"keyname",
",",
"valname",
",",
"base_type",
"=",
"bidict",
")",
":",
"# Re the `base_type` docs above:",
"# The additional requirements (providing _isinv and __getstate__) do not belong in the",
"# BidirectionalMapping interface, and it's ... | 41.549296 | 0.00298 |
def optimize(self, **kwargs):
"""Iteratively optimize the ROI model. The optimization is
performed in three sequential steps:
* Free the normalization of the N largest components (as
determined from NPred) that contain a fraction ``npred_frac``
of the total predicted counts... | [
"def",
"optimize",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"loglevel",
"=",
"kwargs",
".",
"pop",
"(",
"'loglevel'",
",",
"self",
".",
"loglevel",
")",
"timer",
"=",
"Timer",
".",
"create",
"(",
"start",
"=",
"True",
")",
"self",
".",
"logg... | 37.203488 | 0.000913 |
def read(file, system):
"""Read a MATPOWER data file into mpc and build andes device elements"""
func = re.compile('function\\s')
mva = re.compile('\\s*mpc.baseMVA\\s*=\\s*')
bus = re.compile('\\s*mpc.bus\\s*=\\s*\\[')
gen = re.compile('\\s*mpc.gen\\s*=\\s*\\[')
branch = re.compile('\\s*mpc.bran... | [
"def",
"read",
"(",
"file",
",",
"system",
")",
":",
"func",
"=",
"re",
".",
"compile",
"(",
"'function\\\\s'",
")",
"mva",
"=",
"re",
".",
"compile",
"(",
"'\\\\s*mpc.baseMVA\\\\s*=\\\\s*'",
")",
"bus",
"=",
"re",
".",
"compile",
"(",
"'\\\\s*mpc.bus\\\\s... | 29.696203 | 0.000137 |
def get_provisioned_table_write_units(table_name):
""" Returns the number of provisioned write units for the table
:type table_name: str
:param table_name: Name of the DynamoDB table
:returns: int -- Number of write units
"""
try:
desc = DYNAMODB_CONNECTION.describe_table(table_name)
... | [
"def",
"get_provisioned_table_write_units",
"(",
"table_name",
")",
":",
"try",
":",
"desc",
"=",
"DYNAMODB_CONNECTION",
".",
"describe_table",
"(",
"table_name",
")",
"except",
"JSONResponseError",
":",
"raise",
"write_units",
"=",
"int",
"(",
"desc",
"[",
"u'Tab... | 31.833333 | 0.001695 |
def tickUpdate(self, tickDict):
''' consume ticks '''
if not self.__trakers:
self.__setUpTrakers()
for symbol, tick in tickDict.items():
if symbol in self.__trakers:
self.__trakers[symbol].tickUpdate(tick) | [
"def",
"tickUpdate",
"(",
"self",
",",
"tickDict",
")",
":",
"if",
"not",
"self",
".",
"__trakers",
":",
"self",
".",
"__setUpTrakers",
"(",
")",
"for",
"symbol",
",",
"tick",
"in",
"tickDict",
".",
"items",
"(",
")",
":",
"if",
"symbol",
"in",
"self... | 32.875 | 0.007407 |
def reg_event(self, flags):
"""
reg events
"""
command = const.CMD_REG_EVENT
command_string = pack ("I", flags)
cmd_response = self.__send_command(command, command_string)
if not cmd_response.get('status'):
raise ZKErrorResponse("cant' reg events %i" %... | [
"def",
"reg_event",
"(",
"self",
",",
"flags",
")",
":",
"command",
"=",
"const",
".",
"CMD_REG_EVENT",
"command_string",
"=",
"pack",
"(",
"\"I\"",
",",
"flags",
")",
"cmd_response",
"=",
"self",
".",
"__send_command",
"(",
"command",
",",
"command_string",... | 35.444444 | 0.009174 |
def update(self, counter, f, x_orig, gradient_orig):
"""Perform an update of the linear transformation
Arguments:
| ``counter`` -- the iteration counter of the minimizer
| ``f`` -- the function value at ``x_orig``
| ``x_orig`` -- the unknowns in original coo... | [
"def",
"update",
"(",
"self",
",",
"counter",
",",
"f",
",",
"x_orig",
",",
"gradient_orig",
")",
":",
"do_update",
"=",
"Preconditioner",
".",
"update",
"(",
"self",
",",
"counter",
",",
"f",
",",
"x_orig",
",",
"gradient_orig",
")",
"if",
"do_update",
... | 40.351351 | 0.002616 |
def regexpExec(self, content):
"""Check if the regular expression generates the value """
ret = libxml2mod.xmlRegexpExec(self._o, content)
return ret | [
"def",
"regexpExec",
"(",
"self",
",",
"content",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlRegexpExec",
"(",
"self",
".",
"_o",
",",
"content",
")",
"return",
"ret"
] | 42.5 | 0.011561 |
def beacon(config):
'''
Emit the load averages of this host.
Specify thresholds for each load average
and only emit a beacon if any of them are
exceeded.
`onchangeonly`: when `onchangeonly` is True the beacon will fire
events only when the load average pass one threshold. Otherwise, it wi... | [
"def",
"beacon",
"(",
"config",
")",
":",
"log",
".",
"trace",
"(",
"'load beacon starting'",
")",
"_config",
"=",
"{",
"}",
"list",
"(",
"map",
"(",
"_config",
".",
"update",
",",
"config",
")",
")",
"# Default config if not present",
"if",
"'emitatstartup'... | 34.524272 | 0.00082 |
def editor_example():
"""This editor example shows how to interact with holodeck worlds while they are being built
in the Unreal Engine. Most people that use holodeck will not need this.
"""
sensors = [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR]
agent = AgentDefinition("u... | [
"def",
"editor_example",
"(",
")",
":",
"sensors",
"=",
"[",
"Sensors",
".",
"PIXEL_CAMERA",
",",
"Sensors",
".",
"LOCATION_SENSOR",
",",
"Sensors",
".",
"VELOCITY_SENSOR",
"]",
"agent",
"=",
"AgentDefinition",
"(",
"\"uav0\"",
",",
"agents",
".",
"UavAgent",
... | 43 | 0.004878 |
def subclass(cls, vt_code, vt_args):
"""Return a dynamic subclass that has the extra parameters built in"""
from geoid import get_class
import geoid.census
parser = get_class(geoid.census, vt_args.strip('/')).parse
cls = type(vt_code.replace('/', '_'), (cls,), {'vt_code': vt_co... | [
"def",
"subclass",
"(",
"cls",
",",
"vt_code",
",",
"vt_args",
")",
":",
"from",
"geoid",
"import",
"get_class",
"import",
"geoid",
".",
"census",
"parser",
"=",
"get_class",
"(",
"geoid",
".",
"census",
",",
"vt_args",
".",
"strip",
"(",
"'/'",
")",
"... | 34.583333 | 0.007042 |
def location(self):
"""
Returns the geolocation as a lat/lng pair
"""
try:
lat, lng = self["metadata"]["latitude"], self["metadata"]["longitude"]
except KeyError:
return None
if not lat or not lng:
return None
return lat, lng | [
"def",
"location",
"(",
"self",
")",
":",
"try",
":",
"lat",
",",
"lng",
"=",
"self",
"[",
"\"metadata\"",
"]",
"[",
"\"latitude\"",
"]",
",",
"self",
"[",
"\"metadata\"",
"]",
"[",
"\"longitude\"",
"]",
"except",
"KeyError",
":",
"return",
"None",
"if... | 23.615385 | 0.009404 |
def streamer(main_method):
"""Open a stream for the first file in arguments, or stdin"""
def main(arguments):
streams = [StringIO(get_clipboard_data())] if (arguments and '-c' in arguments) else []
streams = streams or ([file(_, 'r') for _ in arguments if os.path.isfile(argument)] if arguments e... | [
"def",
"streamer",
"(",
"main_method",
")",
":",
"def",
"main",
"(",
"arguments",
")",
":",
"streams",
"=",
"[",
"StringIO",
"(",
"get_clipboard_data",
"(",
")",
")",
"]",
"if",
"(",
"arguments",
"and",
"'-c'",
"in",
"arguments",
")",
"else",
"[",
"]",... | 58 | 0.008493 |
def _copy(src_file, dest_path):
"""Copy data read from src file obj to new file in dest_path."""
tf.io.gfile.makedirs(os.path.dirname(dest_path))
with tf.io.gfile.GFile(dest_path, 'wb') as dest_file:
while True:
data = src_file.read(io.DEFAULT_BUFFER_SIZE)
if not data:
break
dest_fil... | [
"def",
"_copy",
"(",
"src_file",
",",
"dest_path",
")",
":",
"tf",
".",
"io",
".",
"gfile",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"dest_path",
")",
")",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"dest_path",
... | 36.111111 | 0.021021 |
def infos(self):
""":py:class:`OrbitInfos` object of ``self``
"""
if not hasattr(self, '_infos'):
self._infos = OrbitInfos(self)
return self._infos | [
"def",
"infos",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_infos'",
")",
":",
"self",
".",
"_infos",
"=",
"OrbitInfos",
"(",
"self",
")",
"return",
"self",
".",
"_infos"
] | 31 | 0.010471 |
def fetch(self, method, path, query=None, body=None, timeout=0, **kwargs):
"""send a Message
:param method: string, something like "POST" or "GET"
:param path: string, the path part of a uri (eg, /foo/bar)
:param body: dict, what you want to send to "method path"
:param timeout:... | [
"def",
"fetch",
"(",
"self",
",",
"method",
",",
"path",
",",
"query",
"=",
"None",
",",
"body",
"=",
"None",
",",
"timeout",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"None",
"if",
"not",
"query",
":",
"query",
"=",
"{",
"}",
... | 38.333333 | 0.004239 |
async def parse_response(response: ClientResponse, schema: dict) -> Any:
"""
Validate and parse the BMA answer
:param response: Response of aiohttp request
:param schema: The expected response structure
:return: the json data
"""
try:
data = await response.json()
response.cl... | [
"async",
"def",
"parse_response",
"(",
"response",
":",
"ClientResponse",
",",
"schema",
":",
"dict",
")",
"->",
"Any",
":",
"try",
":",
"data",
"=",
"await",
"response",
".",
"json",
"(",
")",
"response",
".",
"close",
"(",
")",
"if",
"schema",
"is",
... | 34.5 | 0.003527 |
def field_to_markdown(field):
"""Genera texto en markdown a partir de los metadatos de un `field`.
Args:
field (dict): Diccionario con metadatos de un `field`.
Returns:
str: Texto que describe un `field`.
"""
if "title" in field:
field_title = "**{}**".format(field["title"]... | [
"def",
"field_to_markdown",
"(",
"field",
")",
":",
"if",
"\"title\"",
"in",
"field",
":",
"field_title",
"=",
"\"**{}**\"",
".",
"format",
"(",
"field",
"[",
"\"title\"",
"]",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Es necesario un `title` para describi... | 32.478261 | 0.0013 |
def get_received(self, age=None, for_all=True):
"""Retrieve a list of transfers sent to you or your company
from other people.
:param age: between 1 and 90 days.
:param for_all: If ``True`` will return received files for
all users in the same business. (Available for business ... | [
"def",
"get_received",
"(",
"self",
",",
"age",
"=",
"None",
",",
"for_all",
"=",
"True",
")",
":",
"method",
",",
"url",
"=",
"get_URL",
"(",
"'received_get'",
")",
"if",
"age",
":",
"if",
"not",
"isinstance",
"(",
"age",
",",
"int",
")",
"or",
"a... | 32.371429 | 0.001714 |
def PX4_update(IMU, ATT):
'''implement full DCM using PX4 native SD log data'''
global px4_state
if px4_state is None:
px4_state = PX4_State(degrees(ATT.Roll), degrees(ATT.Pitch), degrees(ATT.Yaw), IMU._timestamp)
gyro = Vector3(IMU.GyroX, IMU.GyroY, IMU.GyroZ)
accel = Vector3(IMU.AccX, IM... | [
"def",
"PX4_update",
"(",
"IMU",
",",
"ATT",
")",
":",
"global",
"px4_state",
"if",
"px4_state",
"is",
"None",
":",
"px4_state",
"=",
"PX4_State",
"(",
"degrees",
"(",
"ATT",
".",
"Roll",
")",
",",
"degrees",
"(",
"ATT",
".",
"Pitch",
")",
",",
"degr... | 39.9 | 0.007353 |
def multitaper_cross_spectrum(self, clm, slm, k, convention='power',
unit='per_l', **kwargs):
"""
Return the multitaper cross-spectrum estimate and standard error.
Usage
-----
mtse, sd = x.multitaper_cross_spectrum(clm, slm, k, [convention, unit... | [
"def",
"multitaper_cross_spectrum",
"(",
"self",
",",
"clm",
",",
"slm",
",",
"k",
",",
"convention",
"=",
"'power'",
",",
"unit",
"=",
"'per_l'",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_multitaper_cross_spectrum",
"(",
"clm",
",",
"s... | 48.614035 | 0.001061 |
def parse_new_packages(apt_output, include_automatic=False):
"""
Given the output from an apt or aptitude command, determine which packages
are newly-installed.
"""
pat = r'^The following NEW packages will be installed:[\r\n]+(.*?)[\r\n]\w'
matcher = re.search(pat, apt_output, re.DOTALL | re.MUL... | [
"def",
"parse_new_packages",
"(",
"apt_output",
",",
"include_automatic",
"=",
"False",
")",
":",
"pat",
"=",
"r'^The following NEW packages will be installed:[\\r\\n]+(.*?)[\\r\\n]\\w'",
"matcher",
"=",
"re",
".",
"search",
"(",
"pat",
",",
"apt_output",
",",
"re",
"... | 46.357143 | 0.001511 |
def set_list_predicates(self):
"""
Reads through the rml mappings and determines all fields that should
map to a list/array with a json output
"""
results = self.rml.query("""
SELECT DISTINCT ?subj_class ?list_field
{
?bn rr:dat... | [
"def",
"set_list_predicates",
"(",
"self",
")",
":",
"results",
"=",
"self",
".",
"rml",
".",
"query",
"(",
"\"\"\"\n SELECT DISTINCT ?subj_class ?list_field\n {\n ?bn rr:datatype rdf:List .\n ?bn rr:predicate ?list_fiel... | 37.565217 | 0.002257 |
def p_exit(p):
""" statement : EXIT WHILE
| EXIT DO
| EXIT FOR
"""
q = p[2]
p[0] = make_sentence('EXIT_%s' % q)
for i in gl.LOOPS:
if q == i[0]:
return
syntax_error(p.lineno(1), 'Syntax Error: EXIT %s out of loop' % q) | [
"def",
"p_exit",
"(",
"p",
")",
":",
"q",
"=",
"p",
"[",
"2",
"]",
"p",
"[",
"0",
"]",
"=",
"make_sentence",
"(",
"'EXIT_%s'",
"%",
"q",
")",
"for",
"i",
"in",
"gl",
".",
"LOOPS",
":",
"if",
"q",
"==",
"i",
"[",
"0",
"]",
":",
"return",
"... | 22.153846 | 0.003333 |
def unlock_subscription_message(self, topic_name, subscription_name,
sequence_number, lock_token):
'''
Unlock a message for processing by other receivers on a given
subscription. This operation deletes the lock object, causing the
message to be unlocke... | [
"def",
"unlock_subscription_message",
"(",
"self",
",",
"topic_name",
",",
"subscription_name",
",",
"sequence_number",
",",
"lock_token",
")",
":",
"_validate_not_none",
"(",
"'topic_name'",
",",
"topic_name",
")",
"_validate_not_none",
"(",
"'subscription_name'",
",",... | 49.575758 | 0.002398 |
def close(self):
"""Release system resources"""
# free parsed data
if not self.is_opened():
return
self.__open_status = False
# abort all running threads first
if self.__reading_thread and self.__reading_thread.is_alive():
self.__reading_... | [
"def",
"close",
"(",
"self",
")",
":",
"# free parsed data\r",
"if",
"not",
"self",
".",
"is_opened",
"(",
")",
":",
"return",
"self",
".",
"__open_status",
"=",
"False",
"# abort all running threads first\r",
"if",
"self",
".",
"__reading_thread",
"and",
"self"... | 33.906977 | 0.003333 |
def to_csv(objects, filename, digits=5, warnings=True):
"""
Export the flatten indicators of one or several users to CSV.
Parameters
----------
objects : list
List of objects to be exported.
filename : string
File to export to.
digits : int
Precision of floats.
... | [
"def",
"to_csv",
"(",
"objects",
",",
"filename",
",",
"digits",
"=",
"5",
",",
"warnings",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"objects",
",",
"list",
")",
":",
"objects",
"=",
"[",
"objects",
"]",
"data",
"=",
"[",
"flatten",
"... | 29.235294 | 0.000649 |
def memoize(func):
"""
Decorator to cause a function to cache it's results for each combination of
inputs and return the cached result on subsequent calls. Does not support
named arguments or arg values that are not hashable.
>>> @memoize
... def foo(x):
... print('running function wit... | [
"def",
"memoize",
"(",
"func",
")",
":",
"func",
".",
"_result_cache",
"=",
"{",
"}",
"# pylint: disable-msg=W0212",
"@",
"wraps",
"(",
"func",
")",
"def",
"_memoized_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"(",
"args",
... | 30.320755 | 0.001808 |
def tileSize(self, zoom):
"Returns the size (in meters) of a tile"
assert zoom in range(0, len(self.RESOLUTIONS))
return self.tileSizePx * self.RESOLUTIONS[int(zoom)] | [
"def",
"tileSize",
"(",
"self",
",",
"zoom",
")",
":",
"assert",
"zoom",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"RESOLUTIONS",
")",
")",
"return",
"self",
".",
"tileSizePx",
"*",
"self",
".",
"RESOLUTIONS",
"[",
"int",
"(",
"zoom",
... | 46.75 | 0.010526 |
def checkin_remote_bundle(self, ref, remote=None):
""" Checkin a remote bundle to this library.
:param ref: Any bundle reference
:param remote: If specified, use this remote. If not, search for the reference
in cached directory listings
:param cb: A one argument progress cal... | [
"def",
"checkin_remote_bundle",
"(",
"self",
",",
"ref",
",",
"remote",
"=",
"None",
")",
":",
"if",
"not",
"remote",
":",
"remote",
",",
"vname",
"=",
"self",
".",
"find_remote_bundle",
"(",
"ref",
")",
"if",
"vname",
":",
"ref",
"=",
"vname",
"else",... | 28.666667 | 0.005 |
def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to.
:rtype: WizardStep instance or None
"""
subcategory = self.parent.step_kw_subcategory.selected_subcategory()
is_raster = is_raster_layer(self.parent.l... | [
"def",
"get_next_step",
"(",
"self",
")",
":",
"subcategory",
"=",
"self",
".",
"parent",
".",
"step_kw_subcategory",
".",
"selected_subcategory",
"(",
")",
"is_raster",
"=",
"is_raster_layer",
"(",
"self",
".",
"parent",
".",
"layer",
")",
"has_classifications"... | 37.388889 | 0.002899 |
async def ChangeModelCredential(self, model_credentials):
'''
model_credentials : typing.Sequence[~ChangeModelCredentialParams]
Returns -> typing.Sequence[~ErrorResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='ModelManager',
... | [
"async",
"def",
"ChangeModelCredential",
"(",
"self",
",",
"model_credentials",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'ModelManager'",
",",
"request",
"=",
"'ChangeModelCredential'",
",",... | 37.428571 | 0.003724 |
def _set_logicalgroup(self, v, load=False):
"""
Setter method for logicalgroup, mapped from YANG variable /rbridge_id/maps/logicalgroup (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_logicalgroup is considered as a private
method. Backends looking to populate... | [
"def",
"_set_logicalgroup",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"b... | 130.772727 | 0.003796 |
def update_from_dict(self, data_dict):
"""
:param data_dict: Dictionary to be mapped into object attributes
:type data_dict: dict
:return:
"""
for k, v in data_dict.items():
setattr(self, k, v)
if "item_queue_id" in data_dict:
self.id = da... | [
"def",
"update_from_dict",
"(",
"self",
",",
"data_dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"data_dict",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"k",
",",
"v",
")",
"if",
"\"item_queue_id\"",
"in",
"data_dict",
":",
"self",
".",... | 30.363636 | 0.005814 |
def make_dataloader(data_train, data_val, data_test, args,
use_average_length=False, num_shards=0, num_workers=8):
"""Create data loaders for training/validation/test."""
data_train_lengths = get_data_lengths(data_train)
data_val_lengths = get_data_lengths(data_val)
data_test_lengths... | [
"def",
"make_dataloader",
"(",
"data_train",
",",
"data_val",
",",
"data_test",
",",
"args",
",",
"use_average_length",
"=",
"False",
",",
"num_shards",
"=",
"0",
",",
"num_workers",
"=",
"8",
")",
":",
"data_train_lengths",
"=",
"get_data_lengths",
"(",
"data... | 67.216667 | 0.004643 |
def make_serviceitem_descriptivename(descriptive_name, condition='is', negate=False, preserve_case=False):
"""
Create a node for ServiceItem/descriptiveName
:return: A IndicatorItem represented as an Element node
"""
document = 'ServiceItem'
search = 'ServiceItem/descriptiveName'
conten... | [
"def",
"make_serviceitem_descriptivename",
"(",
"descriptive_name",
",",
"condition",
"=",
"'is'",
",",
"negate",
"=",
"False",
",",
"preserve_case",
"=",
"False",
")",
":",
"document",
"=",
"'ServiceItem'",
"search",
"=",
"'ServiceItem/descriptiveName'",
"content_typ... | 43.307692 | 0.008696 |
def reply(self, text):
"""POSTs reply to message with own message. Returns posted message.
URL: ``http://www.reddit.com/api/comment/``
:param text: body text of message
"""
data = {
'thing_id': self.name,
'id': '#commentreply_{0}'.format... | [
"def",
"reply",
"(",
"self",
",",
"text",
")",
":",
"data",
"=",
"{",
"'thing_id'",
":",
"self",
".",
"name",
",",
"'id'",
":",
"'#commentreply_{0}'",
".",
"format",
"(",
"self",
".",
"name",
")",
",",
"'text'",
":",
"text",
",",
"}",
"j",
"=",
"... | 34.176471 | 0.008375 |
def _GetValueAsObject(self, property_value):
"""Retrieves the property value as a Python object.
Args:
property_value (pyolecf.property_value): OLECF property value.
Returns:
object: property value as a Python object.
"""
if property_value.type == pyolecf.value_types.BOOLEAN:
ret... | [
"def",
"_GetValueAsObject",
"(",
"self",
",",
"property_value",
")",
":",
"if",
"property_value",
".",
"type",
"==",
"pyolecf",
".",
"value_types",
".",
"BOOLEAN",
":",
"return",
"property_value",
".",
"data_as_boolean",
"if",
"property_value",
".",
"type",
"in"... | 25.791667 | 0.009346 |
def SetServerInformation(self, server, port):
"""Set the server information.
Args:
server (str): IP address or hostname of the server.
port (int): Port number of the server.
"""
self._host = server
self._port = port
logger.debug('Elasticsearch server: {0!s} port: {1:d}'.format(
... | [
"def",
"SetServerInformation",
"(",
"self",
",",
"server",
",",
"port",
")",
":",
"self",
".",
"_host",
"=",
"server",
"self",
".",
"_port",
"=",
"port",
"logger",
".",
"debug",
"(",
"'Elasticsearch server: {0!s} port: {1:d}'",
".",
"format",
"(",
"server",
... | 29.818182 | 0.002959 |
def comma_separated_positions(text):
"""
Start and end positions of comma separated text items.
Commas and trailing spaces should not be included.
>>> comma_separated_positions("ABC, 2,3")
[(0, 3), (5, 6), (7, 8)]
"""
chunks = []
start = 0
end = 0
for item in text.split(","):
... | [
"def",
"comma_separated_positions",
"(",
"text",
")",
":",
"chunks",
"=",
"[",
"]",
"start",
"=",
"0",
"end",
"=",
"0",
"for",
"item",
"in",
"text",
".",
"split",
"(",
"\",\"",
")",
":",
"space_increment",
"=",
"1",
"if",
"item",
"[",
"0",
"]",
"==... | 30.85 | 0.003145 |
def responsive_sleep(self, seconds, wait_reason=''):
"""Sleep for the specified number of seconds, logging every
'wait_log_interval' seconds with progress info."""
for x in xrange(int(seconds)):
if (self.config.wait_log_interval and
not x % self.config.wait_log_in... | [
"def",
"responsive_sleep",
"(",
"self",
",",
"seconds",
",",
"wait_reason",
"=",
"''",
")",
":",
"for",
"x",
"in",
"xrange",
"(",
"int",
"(",
"seconds",
")",
")",
":",
"if",
"(",
"self",
".",
"config",
".",
"wait_log_interval",
"and",
"not",
"x",
"%"... | 45.909091 | 0.003883 |
def cdx_load(sources, query, process=True):
"""
merge text CDX lines from sources, return an iterator for
filtered and access-checked sequence of CDX objects.
:param sources: iterable for text CDX sources.
:param process: bool, perform processing sorting/filtering/grouping ops
"""
cdx_iter ... | [
"def",
"cdx_load",
"(",
"sources",
",",
"query",
",",
"process",
"=",
"True",
")",
":",
"cdx_iter",
"=",
"create_merged_cdx_gen",
"(",
"sources",
",",
"query",
")",
"# page count is a special case, no further processing",
"if",
"query",
".",
"page_count",
":",
"re... | 30.413793 | 0.001099 |
def add_replica(self, partition_name, count=1):
"""Increase the replication-factor for a partition.
The replication-group to add to is determined as follows:
1. Find all replication-groups that have brokers not already
replicating the partition.
2. Of these, find... | [
"def",
"add_replica",
"(",
"self",
",",
"partition_name",
",",
"count",
"=",
"1",
")",
":",
"try",
":",
"partition",
"=",
"self",
".",
"cluster_topology",
".",
"partitions",
"[",
"partition_name",
"]",
"except",
"KeyError",
":",
"raise",
"InvalidPartitionError... | 40.258621 | 0.001254 |
def from_template_file(cls, template_file_path, command=None):
""" Factory function to create a specific document of the
class given by the `command` or the extension of `template_file_path`.
See get_doctype_by_command and get_doctype_by_extension.
Parameters
----------
... | [
"def",
"from_template_file",
"(",
"cls",
",",
"template_file_path",
",",
"command",
"=",
"None",
")",
":",
"# get template file extension",
"ext",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"template_file_path",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"-... | 26.642857 | 0.003881 |
def options(self, url, url_params=empty.dict, headers=empty.dict, timeout=None, **params):
"""Calls the service at the specified URL using the "OPTIONS" method"""
return self.request('OPTIONS', url=url, headers=headers, timeout=timeout, **params) | [
"def",
"options",
"(",
"self",
",",
"url",
",",
"url_params",
"=",
"empty",
".",
"dict",
",",
"headers",
"=",
"empty",
".",
"dict",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"request",
"(",
"'OPTIONS'",
... | 86.666667 | 0.015267 |
def parse_cmd_kwarg(text, off=0):
'''
Parse a foo:bar=<valu> kwarg into (prop,valu),off
'''
_, off = nom(text, off, whites)
prop, off = nom(text, off, varset)
_, off = nom(text, off, whites)
if not nextchar(text, off, '='):
raise s_exc.BadSyntax(expected='= for kwarg ' + prop, at=... | [
"def",
"parse_cmd_kwarg",
"(",
"text",
",",
"off",
"=",
"0",
")",
":",
"_",
",",
"off",
"=",
"nom",
"(",
"text",
",",
"off",
",",
"whites",
")",
"prop",
",",
"off",
"=",
"nom",
"(",
"text",
",",
"off",
",",
"varset",
")",
"_",
",",
"off",
"="... | 24.882353 | 0.002278 |
def obtain_token(self):
"""
Try to obtain token from all end-points that were ever used to serve the
token. If the request returns 404 NOT FOUND, retry with older version of
the URL.
"""
token_end_points = ('token/obtain',
'obtain-token',
... | [
"def",
"obtain_token",
"(",
"self",
")",
":",
"token_end_points",
"=",
"(",
"'token/obtain'",
",",
"'obtain-token'",
",",
"'obtain_token'",
")",
"for",
"end_point",
"in",
"token_end_points",
":",
"try",
":",
"return",
"self",
".",
"auth",
"[",
"end_point",
"]"... | 41.375 | 0.005908 |
def get_message_voice(self, msgid):
"""
根据消息 ID 获取语音消息内容
:param msgid: 消息 ID
:return: 二进制 MP3 音频字符串, 可直接作为 File Object 中 write 的参数
:raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据
:raises ValueError: 参数出错, 错误原因直接打印异常即可, 错误内容: ``voice message not exist``: msg参数无效... | [
"def",
"get_message_voice",
"(",
"self",
",",
"msgid",
")",
":",
"url",
"=",
"'https://mp.weixin.qq.com/cgi-bin/getvoicedata?msgid={msgid}&fileid=&token={token}&lang=zh_CN'",
".",
"format",
"(",
"msgid",
"=",
"msgid",
",",
"token",
"=",
"self",
".",
"__token",
",",
")... | 38.034483 | 0.004421 |
def delete(self, *items):
"""
Delete all specified items and all their descendants. The root item may not be deleted.
:param items: list of item identifiers
:type items: sequence[str]
"""
self._visual_drag.delete(*items)
ttk.Treeview.delete(self, *items) | [
"def",
"delete",
"(",
"self",
",",
"*",
"items",
")",
":",
"self",
".",
"_visual_drag",
".",
"delete",
"(",
"*",
"items",
")",
"ttk",
".",
"Treeview",
".",
"delete",
"(",
"self",
",",
"*",
"items",
")"
] | 33.666667 | 0.009646 |
def disassociate(self, group, parent, **kwargs):
"""Disassociate this group from the specified group.
=====API DOCS=====
Disassociate this group with the specified group.
:param group: Primary key or name of the child group to disassociate.
:type group: str
:param paren... | [
"def",
"disassociate",
"(",
"self",
",",
"group",
",",
"parent",
",",
"*",
"*",
"kwargs",
")",
":",
"parent_id",
"=",
"self",
".",
"lookup_with_inventory",
"(",
"parent",
",",
"kwargs",
".",
"get",
"(",
"'inventory'",
",",
"None",
")",
")",
"[",
"'id'"... | 46.8 | 0.00733 |
def _timesheet_url(url_name, pk, date=None):
"""Utility to create a time sheet URL with optional date parameters."""
url = reverse(url_name, args=(pk,))
if date:
params = {'month': date.month, 'year': date.year}
return '?'.join((url, urlencode(params)))
return url | [
"def",
"_timesheet_url",
"(",
"url_name",
",",
"pk",
",",
"date",
"=",
"None",
")",
":",
"url",
"=",
"reverse",
"(",
"url_name",
",",
"args",
"=",
"(",
"pk",
",",
")",
")",
"if",
"date",
":",
"params",
"=",
"{",
"'month'",
":",
"date",
".",
"mont... | 41.428571 | 0.003378 |
def _call_api(self, url, method='GET', params=None, data=None):
""" Method used to call the API.
It returns the raw JSON returned by the API or raises an exception
if something goes wrong.
:arg url: the URL to call
:kwarg method: the HTTP method to use when calling the specified... | [
"def",
"_call_api",
"(",
"self",
",",
"url",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"req",
"=",
"self",
".",
"session",
".",
"request",
"(",
"method",
"=",
"method",
",",
"url",
"=",
"url",
",... | 31.75 | 0.001698 |
def update_view_bounds(self):
"""Update the camera's view bounds."""
self.view_bounds.left = self.pan.X - self.world_center.X
self.view_bounds.top = self.pan.Y - self.world_center.Y
self.view_bounds.width = self.world_center.X * 2
self.view_bounds.height = self.world_center.Y * 2 | [
"def",
"update_view_bounds",
"(",
"self",
")",
":",
"self",
".",
"view_bounds",
".",
"left",
"=",
"self",
".",
"pan",
".",
"X",
"-",
"self",
".",
"world_center",
".",
"X",
"self",
".",
"view_bounds",
".",
"top",
"=",
"self",
".",
"pan",
".",
"Y",
"... | 52.5 | 0.00625 |
def CreateReply(self, **attributes):
"""Create a new packet as a reply to this one. This method
makes sure the authenticator and secret are copied over
to the new instance.
"""
return AcctPacket(AccountingResponse, self.id,
self.secret, self.authenticator, dict=self.d... | [
"def",
"CreateReply",
"(",
"self",
",",
"*",
"*",
"attributes",
")",
":",
"return",
"AcctPacket",
"(",
"AccountingResponse",
",",
"self",
".",
"id",
",",
"self",
".",
"secret",
",",
"self",
".",
"authenticator",
",",
"dict",
"=",
"self",
".",
"dict",
"... | 42.875 | 0.011429 |
def legacy_requests_view(request, rtype):
"""
View to see legacy requests of rtype request type, which should be either
'food' or 'maintenance'.
"""
if not rtype in ['food', 'maintenance']:
raise Http404
requests_dict = [] # [(req, [req_responses]), (req2, [req2_responses]), ...]
req... | [
"def",
"legacy_requests_view",
"(",
"request",
",",
"rtype",
")",
":",
"if",
"not",
"rtype",
"in",
"[",
"'food'",
",",
"'maintenance'",
"]",
":",
"raise",
"Http404",
"requests_dict",
"=",
"[",
"]",
"# [(req, [req_responses]), (req2, [req2_responses]), ...]",
"reques... | 35.34375 | 0.004303 |
def resample(input_data, ratio, converter_type='sinc_best', verbose=False):
"""Resample the signal in `input_data` at once.
Parameters
----------
input_data : ndarray
Input data. A single channel is provided as a 1D array of `num_frames` length.
Input data with several channels is repre... | [
"def",
"resample",
"(",
"input_data",
",",
"ratio",
",",
"converter_type",
"=",
"'sinc_best'",
",",
"verbose",
"=",
"False",
")",
":",
"from",
"samplerate",
".",
"lowlevel",
"import",
"src_simple",
"from",
"samplerate",
".",
"exceptions",
"import",
"ResamplingEr... | 35.7 | 0.001363 |
def get_user_obj(self, username=None, attribute_list=None, metadata=None,
attr_map=None):
"""
Returns the specified
:param username: Username of the user
:param attribute_list: List of tuples that represent the user's
attributes as returned by the admin_g... | [
"def",
"get_user_obj",
"(",
"self",
",",
"username",
"=",
"None",
",",
"attribute_list",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"attr_map",
"=",
"None",
")",
":",
"return",
"self",
".",
"user_class",
"(",
"username",
"=",
"username",
",",
"attri... | 49.2 | 0.007979 |
def gabor(x, y, xsigma, ysigma, frequency, phase):
"""
Gabor pattern (sine grating multiplied by a circular Gaussian).
"""
if xsigma==0.0 or ysigma==0.0:
return x*0.0
with float_error_ignore():
x_w = np.divide(x,xsigma)
y_h = np.divide(y,ysigma)
p = np.exp(-0.5*x_w*x... | [
"def",
"gabor",
"(",
"x",
",",
"y",
",",
"xsigma",
",",
"ysigma",
",",
"frequency",
",",
"phase",
")",
":",
"if",
"xsigma",
"==",
"0.0",
"or",
"ysigma",
"==",
"0.0",
":",
"return",
"x",
"*",
"0.0",
"with",
"float_error_ignore",
"(",
")",
":",
"x_w"... | 31.583333 | 0.012821 |
def copy_or_replace(src, dst):
'''try to copy with mode, and if it fails, try replacing
'''
try:
shutil.copy(src, dst)
except (OSError, IOError), e:
# It's possible that the file existed, but was owned by someone
# else - in that situation, shutil.copy might then fail when it
... | [
"def",
"copy_or_replace",
"(",
"src",
",",
"dst",
")",
":",
"try",
":",
"shutil",
".",
"copy",
"(",
"src",
",",
"dst",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
",",
"e",
":",
"# It's possible that the file existed, but was owned by someone",
"# else... | 41.741935 | 0.000755 |
def set_state(_id, body):
"""
Set a devices state.
"""
url = DEVICE_URL % _id
if "mode" in body:
url = MODES_URL % _id
arequest = requests.put(url, headers=HEADERS, data=json.dumps(body))
status_code = str(arequest.status_code)
if status_code !... | [
"def",
"set_state",
"(",
"_id",
",",
"body",
")",
":",
"url",
"=",
"DEVICE_URL",
"%",
"_id",
"if",
"\"mode\"",
"in",
"body",
":",
"url",
"=",
"MODES_URL",
"%",
"_id",
"arequest",
"=",
"requests",
".",
"put",
"(",
"url",
",",
"headers",
"=",
"HEADERS"... | 33.833333 | 0.004796 |
def _patch_stats_request(request):
'''If the request has no filter config, add one that should do what is
expected (include all items)
see: PE-11813
'''
filt = request.get('filter', {})
if not filt.get('config', None):
request['filter'] = filters.date_range('acquired',
... | [
"def",
"_patch_stats_request",
"(",
"request",
")",
":",
"filt",
"=",
"request",
".",
"get",
"(",
"'filter'",
",",
"{",
"}",
")",
"if",
"not",
"filt",
".",
"get",
"(",
"'config'",
",",
"None",
")",
":",
"request",
"[",
"'filter'",
"]",
"=",
"filters"... | 38.5 | 0.002538 |
def get_function_in_responses(service, operation, protocol):
"""refers to definition of API in botocore, and autogenerates function
You can see example of elbv2 from link below.
https://github.com/boto/botocore/blob/develop/botocore/data/elbv2/2015-12-01/service-2.json
"""
client = boto3.client(se... | [
"def",
"get_function_in_responses",
"(",
"service",
",",
"operation",
",",
"protocol",
")",
":",
"client",
"=",
"boto3",
".",
"client",
"(",
"service",
")",
"aws_operation_name",
"=",
"to_upper_camel_case",
"(",
"operation",
")",
"op_model",
"=",
"client",
".",
... | 49.25 | 0.003167 |
def stream_url(self):
"""Build url for stream."""
rtsp_url = RTSP_URL.format(
host=self.config.host, video=self.video_query,
audio=self.audio_query, event=self.event_query)
_LOGGER.debug(rtsp_url)
return rtsp_url | [
"def",
"stream_url",
"(",
"self",
")",
":",
"rtsp_url",
"=",
"RTSP_URL",
".",
"format",
"(",
"host",
"=",
"self",
".",
"config",
".",
"host",
",",
"video",
"=",
"self",
".",
"video_query",
",",
"audio",
"=",
"self",
".",
"audio_query",
",",
"event",
... | 37.428571 | 0.007463 |
def genrepo(opts=None, fire_event=True):
'''
Generate winrepo_cachefile based on sls files in the winrepo_dir
opts
Specify an alternate opts dict. Should not be used unless this function
is imported into an execution module.
fire_event : True
Fire an event on failure. Only supp... | [
"def",
"genrepo",
"(",
"opts",
"=",
"None",
",",
"fire_event",
"=",
"True",
")",
":",
"if",
"opts",
"is",
"None",
":",
"opts",
"=",
"__opts__",
"winrepo_dir",
"=",
"opts",
"[",
"'winrepo_dir'",
"]",
"winrepo_cachefile",
"=",
"opts",
"[",
"'winrepo_cachefil... | 41.697674 | 0.000545 |
def response_middleware(api=None):
"""Registers a middleware function that will be called on every response"""
def decorator(middleware_method):
apply_to_api = hug.API(api) if api else hug.api.from_object(middleware_method)
class MiddlewareRouter(object):
__slots__ = ()
... | [
"def",
"response_middleware",
"(",
"api",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"middleware_method",
")",
":",
"apply_to_api",
"=",
"hug",
".",
"API",
"(",
"api",
")",
"if",
"api",
"else",
"hug",
".",
"api",
".",
"from_object",
"(",
"middleware... | 40.357143 | 0.00519 |
def classify_import(module_name, application_directories=('.',)):
"""Classifies an import by its package.
Returns a value in ImportType.__all__
:param text module_name: The dotted notation of a module
:param tuple application_directories: tuple of paths which are considered
application roots.
... | [
"def",
"classify_import",
"(",
"module_name",
",",
"application_directories",
"=",
"(",
"'.'",
",",
")",
")",
":",
"# Only really care about the first part of the path",
"base",
",",
"_",
",",
"_",
"=",
"module_name",
".",
"partition",
"(",
"'.'",
")",
"found",
... | 35.111111 | 0.00077 |
def for_sz(code):
"""深市代码分类
Arguments:
code {[type]} -- [description]
Returns:
[type] -- [description]
"""
if str(code)[0:2] in ['00', '30', '02']:
return 'stock_cn'
elif str(code)[0:2] in ['39']:
return 'index_cn'
elif str(code)[0:2] in ['15']:
ret... | [
"def",
"for_sz",
"(",
"code",
")",
":",
"if",
"str",
"(",
"code",
")",
"[",
"0",
":",
"2",
"]",
"in",
"[",
"'00'",
",",
"'30'",
",",
"'02'",
"]",
":",
"return",
"'stock_cn'",
"elif",
"str",
"(",
"code",
")",
"[",
"0",
":",
"2",
"]",
"in",
"... | 21.148148 | 0.001675 |
def collect(self, *keys, **kwargs):
"""Generator function traversing
tree structure to collect values of a specified key.
:param keys: the keys to look for in the report
:type key: str
:keyword recursive: look for key in children nodes
:type recursive: bool
:keyw... | [
"def",
"collect",
"(",
"self",
",",
"*",
"keys",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"keys",
":",
"raise",
"Exception",
"(",
"'Missing key'",
")",
"has_values",
"=",
"functools",
".",
"reduce",
"(",
"operator",
".",
"__and__",
",",
"[",
"... | 37.588235 | 0.001526 |
def accept(self, reply_socket, channel):
"""Sends ACCEPT reply."""
info = self.info or b''
self.send_raw(reply_socket, ACCEPT, info, *channel) | [
"def",
"accept",
"(",
"self",
",",
"reply_socket",
",",
"channel",
")",
":",
"info",
"=",
"self",
".",
"info",
"or",
"b''",
"self",
".",
"send_raw",
"(",
"reply_socket",
",",
"ACCEPT",
",",
"info",
",",
"*",
"channel",
")"
] | 40.75 | 0.012048 |
def extract_source_hypocentral_depths(src):
"""
Extract source hypocentral depths.
"""
if "pointSource" not in src.tag and "areaSource" not in src.tag:
hds = dict([(key, None) for key, _ in HDEPTH_PARAMS])
hdsw = dict([(key, None) for key, _ in HDW_PARAMS])
return hds, hdsw
... | [
"def",
"extract_source_hypocentral_depths",
"(",
"src",
")",
":",
"if",
"\"pointSource\"",
"not",
"in",
"src",
".",
"tag",
"and",
"\"areaSource\"",
"not",
"in",
"src",
".",
"tag",
":",
"hds",
"=",
"dict",
"(",
"[",
"(",
"key",
",",
"None",
")",
"for",
... | 37.793103 | 0.00089 |
def bland_altman(x, y, interval=None, indep_conf=None, ax=None, c=None, **kwargs):
"""
Draw a Bland-Altman plot of x and y data.
https://en.wikipedia.org/wiki/Bland%E2%80%93Altman_plot
Parameters
----------
x, y : array-like
x and y data to compare.
interval : float
... | [
"def",
"bland_altman",
"(",
"x",
",",
"y",
",",
"interval",
"=",
"None",
",",
"indep_conf",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"c",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"False",
"if",
"ax",
"is",
"None",
":",
"fig"... | 25.982143 | 0.009934 |
def _close_received(self, error):
"""Callback called when a connection CLOSE frame is received.
This callback will process the received CLOSE error to determine if
the connection is recoverable or whether it should be shutdown.
:param error: The error information from the close
... | [
"def",
"_close_received",
"(",
"self",
",",
"error",
")",
":",
"if",
"error",
":",
"condition",
"=",
"error",
".",
"condition",
"description",
"=",
"error",
".",
"description",
"info",
"=",
"error",
".",
"info",
"else",
":",
"condition",
"=",
"b\"amqp:unkn... | 47.157895 | 0.004376 |
def color_labels(labels, distance_transform = False):
'''Color a labels matrix so that no adjacent labels have the same color
distance_transform - if true, distance transform the labels to find out
which objects are closest to each other.
Create a label coloring matrix which assigns ... | [
"def",
"color_labels",
"(",
"labels",
",",
"distance_transform",
"=",
"False",
")",
":",
"if",
"distance_transform",
":",
"i",
",",
"j",
"=",
"scind",
".",
"distance_transform_edt",
"(",
"labels",
"==",
"0",
",",
"return_distances",
"=",
"False",
",",
"retur... | 42.704225 | 0.00548 |
def user_event(uid):
"""获取用户动态
:param uid: 用户的ID,可通过登录或者其他接口获取
"""
if uid is None:
raise ParamsError()
r = NCloudBot()
r.method = 'USER_EVENT'
r.params = {'uid': uid}
r.data = {'time': -1, 'getcounts': True, "csrf_token": ""}
r.send()
return r.response | [
"def",
"user_event",
"(",
"uid",
")",
":",
"if",
"uid",
"is",
"None",
":",
"raise",
"ParamsError",
"(",
")",
"r",
"=",
"NCloudBot",
"(",
")",
"r",
".",
"method",
"=",
"'USER_EVENT'",
"r",
".",
"params",
"=",
"{",
"'uid'",
":",
"uid",
"}",
"r",
".... | 20.642857 | 0.003311 |
def maximum_vline_bundle(self, x0, y0, y1):
"""Compute a maximum set of vertical lines in the unit cells ``(x0,y)``
for :math:`y0 \leq y \leq y1`.
INPUTS:
y0,x0,x1: int
OUTPUT:
list of lists of qubits
"""
y_range = range(y1, y0 - 1, -1) if y0 < ... | [
"def",
"maximum_vline_bundle",
"(",
"self",
",",
"x0",
",",
"y0",
",",
"y1",
")",
":",
"y_range",
"=",
"range",
"(",
"y1",
",",
"y0",
"-",
"1",
",",
"-",
"1",
")",
"if",
"y0",
"<",
"y1",
"else",
"range",
"(",
"y1",
",",
"y0",
"+",
"1",
")",
... | 33.142857 | 0.008386 |
def _copy(self, other, copy_func):
"""
Copies the contents of another Choice object to itself
:param object:
Another instance of the same class
:param copy_func:
An reference of copy.copy() or copy.deepcopy() to use when copying
lists, dicts and obje... | [
"def",
"_copy",
"(",
"self",
",",
"other",
",",
"copy_func",
")",
":",
"super",
"(",
"Choice",
",",
"self",
")",
".",
"_copy",
"(",
"other",
",",
"copy_func",
")",
"self",
".",
"_choice",
"=",
"other",
".",
"_choice",
"self",
".",
"_name",
"=",
"ot... | 30.6875 | 0.003953 |
async def play(self, board: chess.Board, limit: Limit, *, game: object = None, info: Info = INFO_NONE, ponder: bool = False, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> PlayResult:
"""
Play a position.
:param board: The position. The entire move stack will... | [
"async",
"def",
"play",
"(",
"self",
",",
"board",
":",
"chess",
".",
"Board",
",",
"limit",
":",
"Limit",
",",
"*",
",",
"game",
":",
"object",
"=",
"None",
",",
"info",
":",
"Info",
"=",
"INFO_NONE",
",",
"ponder",
":",
"bool",
"=",
"False",
",... | 63 | 0.002502 |
def makeSingleBandWKBRaster(cls, session, width, height, upperLeftX, upperLeftY, cellSizeX, cellSizeY, skewX, skewY, srid, dataArray, initialValue=None, noDataValue=None):
"""
Generate Well Known Binary via SQL. Must be used on a PostGIS database as it relies on several PostGIS
database function... | [
"def",
"makeSingleBandWKBRaster",
"(",
"cls",
",",
"session",
",",
"width",
",",
"height",
",",
"upperLeftX",
",",
"upperLeftY",
",",
"cellSizeX",
",",
"cellSizeY",
",",
"skewX",
",",
"skewY",
",",
"srid",
",",
"dataArray",
",",
"initialValue",
"=",
"None",
... | 42.910448 | 0.0034 |
def wrap_in_fn_call(fn_name, args, prefix=None):
"""
Example:
>>> wrap_in_fn_call("oldstr", (arg,))
oldstr(arg)
>>> wrap_in_fn_call("olddiv", (arg1, arg2))
olddiv(arg1, arg2)
>>> wrap_in_fn_call("olddiv", [arg1, comma, arg2, comma, arg3])
olddiv(arg1, arg2, arg3)
"""
assert len... | [
"def",
"wrap_in_fn_call",
"(",
"fn_name",
",",
"args",
",",
"prefix",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"args",
")",
">",
"0",
"if",
"len",
"(",
"args",
")",
"==",
"2",
":",
"expr1",
",",
"expr2",
"=",
"args",
"newargs",
"=",
"[",
"exp... | 25.947368 | 0.001957 |
def update_backend_info(self, interval=60):
"""Updates the monitor info
Called from another thread.
"""
my_thread = threading.currentThread()
current_interval = 0
started = False
all_dead = False
stati = [None]*len(self._backends)
while getattr(my_thread, "do_run", True) and not all_... | [
"def",
"update_backend_info",
"(",
"self",
",",
"interval",
"=",
"60",
")",
":",
"my_thread",
"=",
"threading",
".",
"currentThread",
"(",
")",
"current_interval",
"=",
"0",
"started",
"=",
"False",
"all_dead",
"=",
"False",
"stati",
"=",
"[",
"None",
"]",... | 43.309091 | 0.002463 |
def _fill_sample_count(self, node):
"""Counts and fills sample counts inside call tree."""
node['sampleCount'] += sum(
self._fill_sample_count(child) for child in node['children'])
return node['sampleCount'] | [
"def",
"_fill_sample_count",
"(",
"self",
",",
"node",
")",
":",
"node",
"[",
"'sampleCount'",
"]",
"+=",
"sum",
"(",
"self",
".",
"_fill_sample_count",
"(",
"child",
")",
"for",
"child",
"in",
"node",
"[",
"'children'",
"]",
")",
"return",
"node",
"[",
... | 47.8 | 0.00823 |
def on_mouse_scroll(self, x, y, dx, dy):
"""
Zoom the view.
"""
self.view['ball'].scroll(dy)
self.scene.camera.transform = self.view['ball'].pose | [
"def",
"on_mouse_scroll",
"(",
"self",
",",
"x",
",",
"y",
",",
"dx",
",",
"dy",
")",
":",
"self",
".",
"view",
"[",
"'ball'",
"]",
".",
"scroll",
"(",
"dy",
")",
"self",
".",
"scene",
".",
"camera",
".",
"transform",
"=",
"self",
".",
"view",
... | 30 | 0.010811 |
def _dyad_update(y, c): # pylint:disable=too-many-locals
# This function has many locals so it can be compared
# with the original algorithm.
"""
Inner function of the fast distance covariance.
This function is compiled because otherwise it would become
a bottleneck.
"""
n = y.shape[0... | [
"def",
"_dyad_update",
"(",
"y",
",",
"c",
")",
":",
"# pylint:disable=too-many-locals",
"# This function has many locals so it can be compared",
"# with the original algorithm.",
"n",
"=",
"y",
".",
"shape",
"[",
"0",
"]",
"gamma",
"=",
"np",
".",
"zeros",
"(",
"n"... | 25.395833 | 0.00237 |
def node_working_directory(self, node):
"""
Returns a working directory for a specific node.
If the directory doesn't exist, the directory is created.
:param node: Node instance
:returns: Node working directory
"""
workdir = self.node_working_path(node)
... | [
"def",
"node_working_directory",
"(",
"self",
",",
"node",
")",
":",
"workdir",
"=",
"self",
".",
"node_working_path",
"(",
"node",
")",
"if",
"not",
"self",
".",
"_deleted",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"workdir",
",",
"exist_ok",
"=",
... | 33.823529 | 0.005076 |
def _object_with_attr(self, name):
"""
Returns the first object that has the attribute `name`
:param name: the attribute to filter by
:type name: `str`
:raises AttributeError: when no object has the named attribute
"""
for obj in self._objects:
if has... | [
"def",
"_object_with_attr",
"(",
"self",
",",
"name",
")",
":",
"for",
"obj",
"in",
"self",
".",
"_objects",
":",
"if",
"hasattr",
"(",
"obj",
",",
"name",
")",
":",
"return",
"obj",
"raise",
"AttributeError",
"(",
"\"No object has attribute {!r}\"",
".",
... | 32.769231 | 0.004566 |
def mBank_set_iph_id(transactions, tag, tag_dict, *args):
"""
mBank Collect uses ID IPH to distinguish between virtual accounts,
adding iph_id may be helpful in further processing
"""
matches = iph_id_re.search(tag_dict[tag.slug])
if matches: # pragma no branch
tag_dict['iph_id'] = mat... | [
"def",
"mBank_set_iph_id",
"(",
"transactions",
",",
"tag",
",",
"tag_dict",
",",
"*",
"args",
")",
":",
"matches",
"=",
"iph_id_re",
".",
"search",
"(",
"tag_dict",
"[",
"tag",
".",
"slug",
"]",
")",
"if",
"matches",
":",
"# pragma no branch",
"tag_dict",... | 32.454545 | 0.002725 |
def get_db_meta(app=DEFAULT_APP_NAME, db_alias=None, table=None, verbosity=0, column=None):
"""Return a dict of dicts containing metadata about the database tables associated with an app
TODO: allow multiple apps
>>> get_db_meta('crawler', db_alias='default', table='crawler_wikiitem') # doctest: +ELLIPSIS... | [
"def",
"get_db_meta",
"(",
"app",
"=",
"DEFAULT_APP_NAME",
",",
"db_alias",
"=",
"None",
",",
"table",
"=",
"None",
",",
"verbosity",
"=",
"0",
",",
"column",
"=",
"None",
")",
":",
"if",
"verbosity",
">",
"0",
":",
"print",
"'Looking for app %r.'",
"%",... | 48.539474 | 0.005579 |
def json_output(f):
"""
Format response to json and in case of web-request set response content type
to 'application/json'.
"""
@wraps(f)
def json_output_decorator(*args, **kwargs):
@inject(config=Config)
def get_config(config):
return config
config = get_co... | [
"def",
"json_output",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"json_output_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"@",
"inject",
"(",
"config",
"=",
"Config",
")",
"def",
"get_config",
"(",
"config",
")",
"... | 27.291667 | 0.00295 |
def _xmlTextReaderErrorFunc(xxx_todo_changeme,msg,severity,locator):
"""Intermediate callback to wrap the locator"""
(f,arg) = xxx_todo_changeme
return f(arg,msg,severity,xmlTextReaderLocator(locator)) | [
"def",
"_xmlTextReaderErrorFunc",
"(",
"xxx_todo_changeme",
",",
"msg",
",",
"severity",
",",
"locator",
")",
":",
"(",
"f",
",",
"arg",
")",
"=",
"xxx_todo_changeme",
"return",
"f",
"(",
"arg",
",",
"msg",
",",
"severity",
",",
"xmlTextReaderLocator",
"(",
... | 52.5 | 0.037559 |
def transform_coords(self, width, height):
"""Return the current absolute (x, y) coordinates of
the tablet tool event, transformed to screen coordinates and
whether they have changed in this event.
Note:
On some devices, returned value may be negative or larger than
the width of the device. See `Out-of-b... | [
"def",
"transform_coords",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"x",
"=",
"self",
".",
"_libinput",
".",
"libinput_event_tablet_tool_get_x_transformed",
"(",
"self",
".",
"_handle",
",",
"width",
")",
"y",
"=",
"self",
".",
"_libinput",
".",
... | 38.346154 | 0.024462 |
def _apply_over_vars_with_dim(func, self, dim=None, **kwargs):
'''wrapper for datasets'''
ds = type(self)(coords=self.coords, attrs=self.attrs)
for name, var in self.data_vars.items():
if dim in var.dims:
ds[name] = func(var, dim=dim, **kwargs)
else:
ds[name] = var
... | [
"def",
"_apply_over_vars_with_dim",
"(",
"func",
",",
"self",
",",
"dim",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ds",
"=",
"type",
"(",
"self",
")",
"(",
"coords",
"=",
"self",
".",
"coords",
",",
"attrs",
"=",
"self",
".",
"attrs",
")",
... | 26.916667 | 0.002994 |
def wait_for_tasks(self, tasks):
"""Given the service instance si and tasks, it returns after all the
tasks are complete
"""
property_collector = self.service_instance.RetrieveContent().propertyCollector
task_list = [str(task) for task in tasks]
# Create filter
obj_... | [
"def",
"wait_for_tasks",
"(",
"self",
",",
"tasks",
")",
":",
"property_collector",
"=",
"self",
".",
"service_instance",
".",
"RetrieveContent",
"(",
")",
".",
"propertyCollector",
"task_list",
"=",
"[",
"str",
"(",
"task",
")",
"for",
"task",
"in",
"tasks"... | 47.777778 | 0.002279 |
def resolve_var(self, varname, context=None):
"""Resolves name as a variable in a given context.
If no context specified page context' is considered as context.
:param str|unicode varname:
:param Context context:
:return:
"""
context = context or self.current_pa... | [
"def",
"resolve_var",
"(",
"self",
",",
"varname",
",",
"context",
"=",
"None",
")",
":",
"context",
"=",
"context",
"or",
"self",
".",
"current_page_context",
"if",
"isinstance",
"(",
"varname",
",",
"FilterExpression",
")",
":",
"varname",
"=",
"varname",
... | 28.954545 | 0.00304 |
def gen_self_signed_cert(filepath, keyfile, days, silent=False):
"""
generate self signed ssl certificate, i.e. a private CA certificate
:param filepath: file path to the key file
:param keyfile: file path to the private key
:param days: valid duration for the certificate
:param silent: whether ... | [
"def",
"gen_self_signed_cert",
"(",
"filepath",
",",
"keyfile",
",",
"days",
",",
"silent",
"=",
"False",
")",
":",
"cmd",
"=",
"(",
"'openssl req -x509 -new -nodes -key {} -days {} -out {} -subj \"{}\"'",
")",
".",
"format",
"(",
"keyfile",
",",
"days",
",",
"fil... | 43.071429 | 0.001623 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.