text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def triangulate(self):
"""Do the triangulation
"""
self._initialize()
pts = self.pts
front = self._front
## Begin sweep (sec. 3.4)
for i in range(3, pts.shape[0]):
pi = pts[i]
#debug("========== New point %d: %s ==========... | [
"def",
"triangulate",
"(",
"self",
")",
":",
"self",
".",
"_initialize",
"(",
")",
"pts",
"=",
"self",
".",
"pts",
"front",
"=",
"self",
".",
"_front",
"## Begin sweep (sec. 3.4)",
"for",
"i",
"in",
"range",
"(",
"3",
",",
"pts",
".",
"shape",
"[",
"... | 37.678161 | 0.009215 |
def imwrite(file, data=None, shape=None, dtype=None, **kwargs):
"""Write numpy array to TIFF file.
Refer to the TiffWriter class and its asarray function for documentation.
A BigTIFF file is created if the data size in bytes is larger than 4 GB
minus 32 MB (for metadata), and 'bigtiff' is not specifie... | [
"def",
"imwrite",
"(",
"file",
",",
"data",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"tifargs",
"=",
"parse_kwargs",
"(",
"kwargs",
",",
"'append'",
",",
"'bigtiff'",
",",
"'byteorder'",
",... | 38.45614 | 0.000445 |
def to_numpy(nd4j_array):
""" Convert an ND4J array to a numpy array
:param nd4j_array:
:return:
"""
buff = nd4j_array.data()
address = buff.pointer().address()
type_name = java_classes.DataTypeUtil.getDtypeFromContext()
data_type = java_classes.DataTypeUtil.getDTypeForName(type_name)
... | [
"def",
"to_numpy",
"(",
"nd4j_array",
")",
":",
"buff",
"=",
"nd4j_array",
".",
"data",
"(",
")",
"address",
"=",
"buff",
".",
"pointer",
"(",
")",
".",
"address",
"(",
")",
"type_name",
"=",
"java_classes",
".",
"DataTypeUtil",
".",
"getDtypeFromContext",... | 33.882353 | 0.001689 |
def connect(self, protocol=None):
"""! @brief Initialize DAP IO pins for JTAG or SWD"""
self._link.enter_debug(STLink.Protocol.SWD)
self._is_connected = True | [
"def",
"connect",
"(",
"self",
",",
"protocol",
"=",
"None",
")",
":",
"self",
".",
"_link",
".",
"enter_debug",
"(",
"STLink",
".",
"Protocol",
".",
"SWD",
")",
"self",
".",
"_is_connected",
"=",
"True"
] | 44.5 | 0.01105 |
def only_pallets_theme(default=None):
"""Create a decorator that calls a function only if the
``is_pallets_theme`` config is ``True``.
Used to prevent Sphinx event callbacks from doing anything if the
Pallets themes are installed but not used. ::
@only_pallets_theme()
def inject_value(... | [
"def",
"only_pallets_theme",
"(",
"default",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"app",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"app",
".",
... | 25.892857 | 0.00133 |
def parse_change_info(e_change_info):
"""
Parses a ChangeInfo tag. Seen in CreateHostedZone, DeleteHostedZone,
and ChangeResourceRecordSetsRequest.
:param lxml.etree._Element e_change_info: A ChangeInfo element.
:rtype: dict
:returns: A dict representation of the change info.
"""
if e_... | [
"def",
"parse_change_info",
"(",
"e_change_info",
")",
":",
"if",
"e_change_info",
"is",
"None",
":",
"return",
"e_change_info",
"status",
"=",
"e_change_info",
".",
"find",
"(",
"'./{*}Status'",
")",
".",
"text",
"submitted_at",
"=",
"e_change_info",
".",
"find... | 29.363636 | 0.001499 |
def limited_join(sep, items, max_chars=30, overflow_marker="..."):
"""Join a number of strings to one, limiting the length to *max_chars*.
If the string overflows this limit, replace the last fitting item by
*overflow_marker*.
Returns: joined_string
"""
full_str = sep.join(items)
if len(fu... | [
"def",
"limited_join",
"(",
"sep",
",",
"items",
",",
"max_chars",
"=",
"30",
",",
"overflow_marker",
"=",
"\"...\"",
")",
":",
"full_str",
"=",
"sep",
".",
"join",
"(",
"items",
")",
"if",
"len",
"(",
"full_str",
")",
"<",
"max_chars",
":",
"return",
... | 28.590909 | 0.001538 |
def persist(self, ttl=None, **kwargs):
"""Save data from this source to local persistent storage"""
from ..container import container_map
from ..container.persist import PersistStore
import time
if 'original_tok' in self.metadata:
raise ValueError('Cannot persist a so... | [
"def",
"persist",
"(",
"self",
",",
"ttl",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"container",
"import",
"container_map",
"from",
".",
".",
"container",
".",
"persist",
"import",
"PersistStore",
"import",
"time",
"if",
"'origin... | 45.208333 | 0.001805 |
def do_handshake(self):
"""Start the SSL handshake.
This method only needs to be called if this transport was created with
*do_handshake_on_connect* set to False (the default is True).
The handshake needs to be synchronized between the both endpoints, so
that SSL record level d... | [
"def",
"do_handshake",
"(",
"self",
")",
":",
"if",
"self",
".",
"_error",
":",
"raise",
"compat",
".",
"saved_exc",
"(",
"self",
".",
"_error",
")",
"elif",
"self",
".",
"_closing",
"or",
"self",
".",
"_handle",
".",
"closed",
":",
"raise",
"Transport... | 44.944444 | 0.002421 |
def control(self, instances, action):
"""Valid actions: start, stop, reboot, terminate, protect, and
unprotect.
"""
if not isinstance(instances, list) and\
not isinstance(instances, tuple):
instances = [instances]
actions = {'start': {'operation': "StartIns... | [
"def",
"control",
"(",
"self",
",",
"instances",
",",
"action",
")",
":",
"if",
"not",
"isinstance",
"(",
"instances",
",",
"list",
")",
"and",
"not",
"isinstance",
"(",
"instances",
",",
"tuple",
")",
":",
"instances",
"=",
"[",
"instances",
"]",
"act... | 52.878788 | 0.001125 |
def get(self, block=True, timeout=None):
"""get an item out of the queue
.. note::
if `block` is ``True`` (the default) and the queue is
:meth`empty`, this method will block the current coroutine until
something has been :meth:`put`.
:param block:
... | [
"def",
"get",
"(",
"self",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_data",
":",
"if",
"not",
"block",
":",
"raise",
"Empty",
"(",
")",
"current",
"=",
"compat",
".",
"getcurrent",
"(",
")",
"wa... | 33.617021 | 0.00123 |
def get_page(self, rel_url, include_draft=False):
"""
Get custom page for given relative url from filesystem.
Possible input:
- my-page/
- my-page/index.html
- my-another-page.html
- a/b/c/
- a/b/c/d.html
:param rel_url: relative url
:par... | [
"def",
"get_page",
"(",
"self",
",",
"rel_url",
",",
"include_draft",
"=",
"False",
")",
":",
"page_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"rel_url",
".",
"replace",
"(",
"'/'",
",",
"os",
".",
"path",
".",
"sep",
")",
")",
"page_path",
... | 36.97619 | 0.001255 |
def _setPWMFrequency(self, pwm, device, message):
"""
Set the PWM frequency.
:Parameters:
pwm : `int`
The PWN frequency to set in hertz.
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the P... | [
"def",
"_setPWMFrequency",
"(",
"self",
",",
"pwm",
",",
"device",
",",
"message",
")",
":",
"value",
"=",
"self",
".",
"_CONFIG_PWM_TO_VALUE",
".",
"get",
"(",
"pwm",
")",
"if",
"value",
"is",
"None",
":",
"msg",
"=",
"\"Invalid frequency: {}\"",
".",
"... | 35.153846 | 0.00213 |
def vector_to_symmetric(v):
'''Convert an iterable into a symmetric matrix.'''
np = len(v)
N = (int(sqrt(1 + 8*np)) - 1)//2
if N*(N+1)//2 != np:
raise ValueError('Cannot convert vector to symmetric matrix')
sym = ndarray((N,N))
iterable = iter(v)
for r in range(N):
f... | [
"def",
"vector_to_symmetric",
"(",
"v",
")",
":",
"np",
"=",
"len",
"(",
"v",
")",
"N",
"=",
"(",
"int",
"(",
"sqrt",
"(",
"1",
"+",
"8",
"*",
"np",
")",
")",
"-",
"1",
")",
"//",
"2",
"if",
"N",
"*",
"(",
"N",
"+",
"1",
")",
"//",
"2",... | 32.916667 | 0.009852 |
def json_loads(inbox):
"""
Deserializes the first element of the input using the JSON protocol as
implemented by the ``json`` Python 2.6 library.
"""
gc.disable()
obj = json.loads(inbox[0])
gc.enable()
return obj | [
"def",
"json_loads",
"(",
"inbox",
")",
":",
"gc",
".",
"disable",
"(",
")",
"obj",
"=",
"json",
".",
"loads",
"(",
"inbox",
"[",
"0",
"]",
")",
"gc",
".",
"enable",
"(",
")",
"return",
"obj"
] | 24.1 | 0.012 |
def _count_devices(self):
"""See what Windows' GetRawInputDeviceList wants to tell us.
For now, we are just seeing if there is at least one keyboard
and/or mouse attached.
GetRawInputDeviceList could be used to help distinguish between
different keyboards and mice on the system... | [
"def",
"_count_devices",
"(",
"self",
")",
":",
"number_of_devices",
"=",
"ctypes",
".",
"c_uint",
"(",
")",
"if",
"ctypes",
".",
"windll",
".",
"user32",
".",
"GetRawInputDeviceList",
"(",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_int",
")",
"(",
... | 39.404762 | 0.001179 |
def _setuie(self, i):
"""Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i.
Raises CreationError if i < 0.
"""
if i < 0:
raise CreationError("Cannot use negative initialiser for unsigned "
"interleaved expon... | [
"def",
"_setuie",
"(",
"self",
",",
"i",
")",
":",
"if",
"i",
"<",
"0",
":",
"raise",
"CreationError",
"(",
"\"Cannot use negative initialiser for unsigned \"",
"\"interleaved exponential-Golomb.\"",
")",
"self",
".",
"_setbin_unsafe",
"(",
"'1'",
"if",
"i",
"==",... | 41.2 | 0.009501 |
def restore(name):
"""Restores the database from a snapshot"""
app = get_app()
if not name:
snapshot = app.get_latest_snapshot()
if not snapshot:
click.echo(
"Couldn't find any snapshots for project %s" %
load_config()['project_name']
... | [
"def",
"restore",
"(",
"name",
")",
":",
"app",
"=",
"get_app",
"(",
")",
"if",
"not",
"name",
":",
"snapshot",
"=",
"app",
".",
"get_latest_snapshot",
"(",
")",
"if",
"not",
"snapshot",
":",
"click",
".",
"echo",
"(",
"\"Couldn't find any snapshots for pr... | 31.121951 | 0.00076 |
def filter_dirs(root, dirs, excl_paths):
"""Filter directory paths based on the exclusion rules defined in
'excl_paths'.
"""
filtered_dirs = []
for dirpath in dirs:
abspath = os.path.abspath(os.path.join(root, dirpath))
if os.path.basename(abspath) in _SKIP_DIRS:
continue... | [
"def",
"filter_dirs",
"(",
"root",
",",
"dirs",
",",
"excl_paths",
")",
":",
"filtered_dirs",
"=",
"[",
"]",
"for",
"dirpath",
"in",
"dirs",
":",
"abspath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
"... | 34.5 | 0.002353 |
def run(self, cmd, sudo=False, ignore_error=False, success_status=(0,),
error_callback=None, custom_log=None, retry=0):
"""Run a command on the remote host.
The command is run on the remote host, if there is a redirected host
then the command will be run on that redirected host. See... | [
"def",
"run",
"(",
"self",
",",
"cmd",
",",
"sudo",
"=",
"False",
",",
"ignore_error",
"=",
"False",
",",
"success_status",
"=",
"(",
"0",
",",
")",
",",
"error_callback",
"=",
"None",
",",
"custom_log",
"=",
"None",
",",
"retry",
"=",
"0",
")",
":... | 42.610169 | 0.001944 |
def readconf(conffile, section_name=None, log_name=None, defaults=None,
raw=False):
"""
Read config file and return config items as a dict
:param conffile: path to config file, or a file-like object (hasattr
readline)
:param section_name: config section to read (will r... | [
"def",
"readconf",
"(",
"conffile",
",",
"section_name",
"=",
"None",
",",
"log_name",
"=",
"None",
",",
"defaults",
"=",
"None",
",",
"raw",
"=",
"False",
")",
":",
"if",
"defaults",
"is",
"None",
":",
"defaults",
"=",
"{",
"}",
"if",
"raw",
":",
... | 33.934783 | 0.001868 |
def _urlunquote(byte_string, remap=None, preserve=None):
"""
Unquotes a URI portion from a byte string into unicode using UTF-8
:param byte_string:
A byte string of the data to unquote
:param remap:
A list of characters (as unicode) that should be re-mapped to a
%XX encoding. T... | [
"def",
"_urlunquote",
"(",
"byte_string",
",",
"remap",
"=",
"None",
",",
"preserve",
"=",
"None",
")",
":",
"if",
"byte_string",
"is",
"None",
":",
"return",
"byte_string",
"if",
"byte_string",
"==",
"b''",
":",
"return",
"''",
"if",
"preserve",
":",
"r... | 29.489362 | 0.002095 |
def crtGauss2D(varSizeX, varSizeY, varPosX, varPosY, varSd):
"""Create 2D Gaussian kernel.
Parameters
----------
varSizeX : int, positive
Width of the visual field.
varSizeY : int, positive
Height of the visual field..
varPosX : int, positive
X position of centre of 2D G... | [
"def",
"crtGauss2D",
"(",
"varSizeX",
",",
"varSizeY",
",",
"varPosX",
",",
"varPosY",
",",
"varSd",
")",
":",
"varSizeX",
"=",
"int",
"(",
"varSizeX",
")",
"varSizeY",
"=",
"int",
"(",
"varSizeY",
")",
"# aryX and aryY are in reversed order, this seems to be nece... | 27.526316 | 0.000923 |
def enable(self):
"""
Enables WinPair settings
"""
npair = self.npair.value()
for label, xsl, xsr, ys, nx, ny in \
zip(self.label[:npair], self.xsl[:npair], self.xsr[:npair],
self.ys[:npair], self.nx[:npair], self.ny[:npair]):
label... | [
"def",
"enable",
"(",
"self",
")",
":",
"npair",
"=",
"self",
".",
"npair",
".",
"value",
"(",
")",
"for",
"label",
",",
"xsl",
",",
"xsr",
",",
"ys",
",",
"nx",
",",
"ny",
"in",
"zip",
"(",
"self",
".",
"label",
"[",
":",
"npair",
"]",
",",
... | 31.413793 | 0.00213 |
def get_by_id_or_404(self, id, **kwargs):
"""Gets by a instance instance r raises a 404 is one isn't found."""
obj = self.get_by_id(id=id, **kwargs)
if obj:
return obj
raise Http404 | [
"def",
"get_by_id_or_404",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"self",
".",
"get_by_id",
"(",
"id",
"=",
"id",
",",
"*",
"*",
"kwargs",
")",
"if",
"obj",
":",
"return",
"obj",
"raise",
"Http404"
] | 27.5 | 0.008811 |
def to_gds(self, multiplier):
"""
Convert this object to a GDSII element.
Parameters
----------
multiplier : number
A number that multiplies all dimensions written in the GDSII
element.
Returns
-------
out : string
The... | [
"def",
"to_gds",
"(",
"self",
",",
"multiplier",
")",
":",
"name",
"=",
"self",
".",
"ref_cell",
".",
"name",
"if",
"len",
"(",
"name",
")",
"%",
"2",
"!=",
"0",
":",
"name",
"=",
"name",
"+",
"'\\0'",
"data",
"=",
"struct",
".",
"pack",
"(",
"... | 43.206349 | 0.001437 |
def sqs(self):
"""
:rtype: SQSConnection
"""
if self.__sqs is None:
self.__sqs = self.__aws_connect(sqs)
return self.__sqs | [
"def",
"sqs",
"(",
"self",
")",
":",
"if",
"self",
".",
"__sqs",
"is",
"None",
":",
"self",
".",
"__sqs",
"=",
"self",
".",
"__aws_connect",
"(",
"sqs",
")",
"return",
"self",
".",
"__sqs"
] | 24 | 0.011494 |
def add_conditional_state(self, name, state, validator, class_validator=None, cache_for=None, label=None):
"""
Add a conditional state that combines an existing state with a validator
that must also pass. The validator receives the object on which the property
is present as a parameter.
... | [
"def",
"add_conditional_state",
"(",
"self",
",",
"name",
",",
"state",
",",
"validator",
",",
"class_validator",
"=",
"None",
",",
"cache_for",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"# We'll accept a ManagedState with grouped values, but not a ManagedStat... | 62.466667 | 0.008933 |
def point(self, x, y, z=0, m=0):
"""Creates a point shape."""
pointShape = _Shape(self.shapeType)
pointShape.points.append([x, y, z, m])
self._shapes.append(pointShape) | [
"def",
"point",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
"=",
"0",
",",
"m",
"=",
"0",
")",
":",
"pointShape",
"=",
"_Shape",
"(",
"self",
".",
"shapeType",
")",
"pointShape",
".",
"points",
".",
"append",
"(",
"[",
"x",
",",
"y",
",",
"z",... | 40 | 0.009804 |
def get_api_publisher(self, social_user):
"""
and other https://vk.com/dev.php?method=wall.post
"""
def _post(**kwargs):
api = self.get_api(social_user)
from pudb import set_trace; set_trace()
# api.group.getInfo('uids'='your_group_id', 'fields'='... | [
"def",
"get_api_publisher",
"(",
"self",
",",
"social_user",
")",
":",
"def",
"_post",
"(",
"*",
"*",
"kwargs",
")",
":",
"api",
"=",
"self",
".",
"get_api",
"(",
"social_user",
")",
"from",
"pudb",
"import",
"set_trace",
"set_trace",
"(",
")",
"# api.gr... | 32.384615 | 0.011547 |
def _shorten_line_at_tokens_new(tokens, source, indentation,
max_line_length):
"""Shorten the line taking its length into account.
The input is expected to be free of newlines except for inside
multiline strings and at the end.
"""
# Yield the original source so to ... | [
"def",
"_shorten_line_at_tokens_new",
"(",
"tokens",
",",
"source",
",",
"indentation",
",",
"max_line_length",
")",
":",
"# Yield the original source so to see if it's a better choice than the",
"# shortened candidate lines we generate here.",
"yield",
"indentation",
"+",
"source"... | 41.461538 | 0.000907 |
def f2tc(f,base=25):
"""Converts frames to timecode"""
try:
f = int(f)
except:
return "--:--:--:--"
hh = int((f / base) / 3600)
mm = int(((f / base) / 60) - (hh*60))
ss = int((f/base) - (hh*3600) - (mm*60))
ff = int(f - (hh*3600*base) - (mm*60*base) - (ss*base))
return "{... | [
"def",
"f2tc",
"(",
"f",
",",
"base",
"=",
"25",
")",
":",
"try",
":",
"f",
"=",
"int",
"(",
"f",
")",
"except",
":",
"return",
"\"--:--:--:--\"",
"hh",
"=",
"int",
"(",
"(",
"f",
"/",
"base",
")",
"/",
"3600",
")",
"mm",
"=",
"int",
"(",
"... | 32.727273 | 0.008108 |
def create_attributes(klass, attributes, previous_object=None):
"""
Attributes for resource creation.
"""
result = {}
if previous_object is not None:
result = {k: v for k, v in previous_object.to_json().items() if k != 'sys'}
result.update(attributes)
... | [
"def",
"create_attributes",
"(",
"klass",
",",
"attributes",
",",
"previous_object",
"=",
"None",
")",
":",
"result",
"=",
"{",
"}",
"if",
"previous_object",
"is",
"not",
"None",
":",
"result",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"pr... | 25 | 0.008902 |
def _parse_operation_bytes(unpacker):
"""Returns a protobuf message representing the next operation as read from
the byte stream in unpacker
"""
# Check for and parse optional source account field
source_account = None
if unpacker.unpack_bool():
source_account = unpacker.unpack_fopaque(... | [
"def",
"_parse_operation_bytes",
"(",
"unpacker",
")",
":",
"# Check for and parse optional source account field",
"source_account",
"=",
"None",
"if",
"unpacker",
".",
"unpack_bool",
"(",
")",
":",
"source_account",
"=",
"unpacker",
".",
"unpack_fopaque",
"(",
"32",
... | 31.930818 | 0.000573 |
def _initialize_precalculated_series(self,
asset,
trading_calendar,
trading_days,
data_portal):
"""
Internal method that pre-calculates the ... | [
"def",
"_initialize_precalculated_series",
"(",
"self",
",",
"asset",
",",
"trading_calendar",
",",
"trading_days",
",",
"data_portal",
")",
":",
"if",
"self",
".",
"emission_rate",
"==",
"\"minute\"",
":",
"minutes",
"=",
"trading_calendar",
".",
"minutes_for_sessi... | 35.162393 | 0.001418 |
def send_rally_points(self):
'''send rally points from rallyloader'''
self.mav_param.mavset(self.master,'RALLY_TOTAL',self.rallyloader.rally_count(),3)
for i in range(self.rallyloader.rally_count()):
self.send_rally_point(i) | [
"def",
"send_rally_points",
"(",
"self",
")",
":",
"self",
".",
"mav_param",
".",
"mavset",
"(",
"self",
".",
"master",
",",
"'RALLY_TOTAL'",
",",
"self",
".",
"rallyloader",
".",
"rally_count",
"(",
")",
",",
"3",
")",
"for",
"i",
"in",
"range",
"(",
... | 42.666667 | 0.022989 |
def rectify(self, slitlet2d, resampling, inverse=False):
"""Rectify slitlet using computed transformation.
Parameters
----------
slitlet2d : numpy array
Image containing the 2d slitlet image.
resampling : int
1: nearest neighbour, 2: flux preserving inter... | [
"def",
"rectify",
"(",
"self",
",",
"slitlet2d",
",",
"resampling",
",",
"inverse",
"=",
"False",
")",
":",
"if",
"resampling",
"not",
"in",
"[",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",
"\"Unexpected resampling value=\"",
"+",
"str",
"(",
"r... | 29.192308 | 0.001275 |
def removedIssuesEstimateSum(self, board_id, sprint_id):
"""Return the total incompleted points this sprint."""
return self._get_json('rapid/charts/sprintreport?rapidViewId=%s&sprintId=%s' % (board_id, sprint_id),
base=self.AGILE_BASE_URL)['contents']['puntedIssuesEstimateS... | [
"def",
"removedIssuesEstimateSum",
"(",
"self",
",",
"board_id",
",",
"sprint_id",
")",
":",
"return",
"self",
".",
"_get_json",
"(",
"'rapid/charts/sprintreport?rapidViewId=%s&sprintId=%s'",
"%",
"(",
"board_id",
",",
"sprint_id",
")",
",",
"base",
"=",
"self",
"... | 82.5 | 0.012012 |
def dockerCheckOutput(*args, **kwargs):
"""
Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'.
Provided for backwards compatibility with a previous implementation that
used 'subprocess.check_output()'. This has since been supplanted and
apiDockerCall() is recommended.
... | [
"def",
"dockerCheckOutput",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"warn",
"(",
"\"WARNING: dockerCheckOutput() using subprocess.check_output() \"",
"\"is deprecated, please switch to apiDockerCall().\"",
")",
"return",
"subprocessDockerCall",
"("... | 48 | 0.001859 |
def xmlrpc_method(**kwargs):
"""
Support multiple endpoints serving the same views by chaining calls to
xmlrpc_method
"""
# Add some default arguments
kwargs.update(
require_csrf=False,
require_methods=["POST"],
decorator=(submit_xmlrpc_metrics(method=kwargs["method"]),),... | [
"def",
"xmlrpc_method",
"(",
"*",
"*",
"kwargs",
")",
":",
"# Add some default arguments",
"kwargs",
".",
"update",
"(",
"require_csrf",
"=",
"False",
",",
"require_methods",
"=",
"[",
"\"POST\"",
"]",
",",
"decorator",
"=",
"(",
"submit_xmlrpc_metrics",
"(",
... | 30.7 | 0.00158 |
def get_memcached_usage(socket=None):
"""
Returns memcached statistics.
:param socket: Path to memcached's socket file.
"""
cmd = 'echo \'stats\' | nc -U {0}'.format(socket)
output = getoutput(cmd)
curr_items = None
bytes_ = None
rows = output.split('\n')[:-1]
for row in rows:... | [
"def",
"get_memcached_usage",
"(",
"socket",
"=",
"None",
")",
":",
"cmd",
"=",
"'echo \\'stats\\' | nc -U {0}'",
".",
"format",
"(",
"socket",
")",
"output",
"=",
"getoutput",
"(",
"cmd",
")",
"curr_items",
"=",
"None",
"bytes_",
"=",
"None",
"rows",
"=",
... | 24.7 | 0.001949 |
def read_header(self):
"""Read the header from `file`.
The header is also stored in the `header` attribute.
Returns
-------
header : `OrderedDict`
Header from `file`, stored in an ordered dictionary, where each
entry has the following form::
... | [
"def",
"read_header",
"(",
"self",
")",
":",
"# Read all fields except data. We use an OrderedDict such that",
"# the order is the same as in `header_fields`. This makes it simple",
"# to write later on in the correct order, based only on `header`.",
"header",
"=",
"OrderedDict",
"(",
")",... | 39.170455 | 0.000566 |
def write_file(spdx_file, out):
"""
Write a file fields to out.
"""
out.write('# File\n\n')
write_value('FileName', spdx_file.name, out)
write_value('SPDXID', spdx_file.spdx_id, out)
if spdx_file.has_optional_field('type'):
write_file_type(spdx_file.type, out)
write_value('FileCh... | [
"def",
"write_file",
"(",
"spdx_file",
",",
"out",
")",
":",
"out",
".",
"write",
"(",
"'# File\\n\\n'",
")",
"write_value",
"(",
"'FileName'",
",",
"spdx_file",
".",
"name",
",",
"out",
")",
"write_value",
"(",
"'SPDXID'",
",",
"spdx_file",
".",
"spdx_id"... | 39.816327 | 0.001501 |
def rpc(rtype=None):
"""Decorator marks a method for export.
:param type: Specifies which :py:class:`Type` this method will return.
The return type (rtype) must be one of:
- An instance of :py:class:`p4p.Type`
- None, in which case the method must return a :py:class:`p4p.Value`
- One of the N... | [
"def",
"rpc",
"(",
"rtype",
"=",
"None",
")",
":",
"wrap",
"=",
"None",
"if",
"rtype",
"is",
"None",
"or",
"isinstance",
"(",
"rtype",
",",
"Type",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"type",
",",
"(",
"list",
",",
"tuple",
")",
")",
":"... | 31.511628 | 0.002147 |
def cleanup_sessions(self, app=None):
"""Removes all expired session from the store.
Periodically, this function can be called to remove sessions from
the backend store that have expired, as they are not removed
automatically unless the backend supports time-to-live and has been
... | [
"def",
"cleanup_sessions",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"if",
"not",
"app",
":",
"app",
"=",
"current_app",
"for",
"key",
"in",
"app",
".",
"kvsession_store",
".",
"keys",
"(",
")",
":",
"m",
"=",
"self",
".",
"key_regex",
".",
"... | 40.758621 | 0.001653 |
def step( self ):
"""
Returns the step value for this ruler. If the cached value is None,
then a default value will be specified based on the ruler type.
:return <variant>
"""
if ( self._step is not None ):
return self._step
eli... | [
"def",
"step",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_step",
"is",
"not",
"None",
")",
":",
"return",
"self",
".",
"_step",
"elif",
"(",
"self",
".",
"rulerType",
"(",
")",
"==",
"XChartRuler",
".",
"Type",
".",
"Number",
")",
":",
"sel... | 38.045455 | 0.022145 |
def _update_throughput(self, tablename, read, write, index):
""" Update the throughput on a table or index """
def get_desc():
""" Get the table or global index description """
desc = self.describe(tablename, refresh=True, require=True)
if index is not None:
... | [
"def",
"_update_throughput",
"(",
"self",
",",
"tablename",
",",
"read",
",",
"write",
",",
"index",
")",
":",
"def",
"get_desc",
"(",
")",
":",
"\"\"\" Get the table or global index description \"\"\"",
"desc",
"=",
"self",
".",
"describe",
"(",
"tablename",
",... | 33.294118 | 0.001717 |
def _setup_trunk(self, trunk, vlan_id=None):
"""Sets up VLAN trunk and updates the trunk status."""
LOG.info('Binding trunk port: %s.', trunk)
try:
# bind sub_ports to host.
self._trunk_rpc.update_subport_bindings(self._context,
... | [
"def",
"_setup_trunk",
"(",
"self",
",",
"trunk",
",",
"vlan_id",
"=",
"None",
")",
":",
"LOG",
".",
"info",
"(",
"'Binding trunk port: %s.'",
",",
"trunk",
")",
"try",
":",
"# bind sub_ports to host.",
"self",
".",
"_trunk_rpc",
".",
"update_subport_bindings",
... | 47 | 0.002195 |
def _perform_async_update_rule(context, id, db_sg_group, rule_id, action):
"""Updates a SG rule async and return the job information.
Only happens if the security group has associated ports. If the async
connection fails the update continues (legacy mode).
"""
rpc_reply = None
sg_rpc = sg_rpc_a... | [
"def",
"_perform_async_update_rule",
"(",
"context",
",",
"id",
",",
"db_sg_group",
",",
"rule_id",
",",
"action",
")",
":",
"rpc_reply",
"=",
"None",
"sg_rpc",
"=",
"sg_rpc_api",
".",
"QuarkSGAsyncProcessClient",
"(",
")",
"ports",
"=",
"db_api",
".",
"sg_gat... | 43.625 | 0.001403 |
def resize(self, shape, format=None, internalformat=None):
"""Set the texture size and format
Parameters
----------
shape : tuple of integers
New texture shape in zyx order. Optionally, an extra dimention
may be specified to indicate the number of color channels.... | [
"def",
"resize",
"(",
"self",
",",
"shape",
",",
"format",
"=",
"None",
",",
"internalformat",
"=",
"None",
")",
":",
"return",
"self",
".",
"_resize",
"(",
"shape",
",",
"format",
",",
"internalformat",
")"
] | 52 | 0.001642 |
def run_bidirectional_blast(reference, other_genome, dbtype, outdir=''):
"""BLAST a genome against another, and vice versa.
This function requires BLAST to be installed, do so by running:
sudo apt install ncbi-blast+
Args:
reference (str): path to "reference" genome, aka your "base strain"
... | [
"def",
"run_bidirectional_blast",
"(",
"reference",
",",
"other_genome",
",",
"dbtype",
",",
"outdir",
"=",
"''",
")",
":",
"# TODO: add force_rerun option",
"if",
"dbtype",
"==",
"'nucl'",
":",
"command",
"=",
"'blastn'",
"elif",
"dbtype",
"==",
"'prot'",
":",
... | 40.241935 | 0.001565 |
def main():
""" Reports stats on the workflow, use with --stats option to toil.
"""
parser = getBasicOptionParser()
initializeOptions(parser)
options = parseBasicOptions(parser)
checkOptions(options, parser)
config = Config()
config.setOptions(options)
jobStore = Toil.resumeJobStore(... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"getBasicOptionParser",
"(",
")",
"initializeOptions",
"(",
"parser",
")",
"options",
"=",
"parseBasicOptions",
"(",
"parser",
")",
"checkOptions",
"(",
"options",
",",
"parser",
")",
"config",
"=",
"Config",
"(",... | 35.076923 | 0.002137 |
def readObject(self):
"""read object"""
try:
_, res = self._read_and_exec_opcode(ident=0)
position_bak = self.object_stream.tell()
the_rest = self.object_stream.read()
if len(the_rest):
log_error("Warning!!!!: Stream still has %s bytes left.\
Enable debug mode of logging to see ... | [
"def",
"readObject",
"(",
"self",
")",
":",
"try",
":",
"_",
",",
"res",
"=",
"self",
".",
"_read_and_exec_opcode",
"(",
"ident",
"=",
"0",
")",
"position_bak",
"=",
"self",
".",
"object_stream",
".",
"tell",
"(",
")",
"the_rest",
"=",
"self",
".",
"... | 30.473684 | 0.01675 |
def add(self, score, user, ip_address, cookies={}, commit=True):
"""add(score, user, ip_address)
Used to add a rating to an object."""
try:
score = int(score)
except (ValueError, TypeError):
raise InvalidRating("%s is not a valid choice for %s" % (score, ... | [
"def",
"add",
"(",
"self",
",",
"score",
",",
"user",
",",
"ip_address",
",",
"cookies",
"=",
"{",
"}",
",",
"commit",
"=",
"True",
")",
":",
"try",
":",
"score",
"=",
"int",
"(",
"score",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
... | 40.319672 | 0.012897 |
def fromlist(items, accessor=None, keys=None, dims=None, dtype=None, labels=None, npartitions=None, engine=None):
"""
Load images from a list of items using the given accessor.
Parameters
----------
accessor : function
Apply to each item from the list to yield an image.
keys : list, op... | [
"def",
"fromlist",
"(",
"items",
",",
"accessor",
"=",
"None",
",",
"keys",
"=",
"None",
",",
"dims",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"npartitions",
"=",
"None",
",",
"engine",
"=",
"None",
")",
":",
"if",
... | 33.410256 | 0.002237 |
def visit_member(self, attribute_key, attribute, member_node, member_data,
is_link_node, parent_data, index=None):
"""
Visits a member node in a resource data tree.
:param tuple attribute_key: tuple containing the attribute tokens
identifying the member node's pos... | [
"def",
"visit_member",
"(",
"self",
",",
"attribute_key",
",",
"attribute",
",",
"member_node",
",",
"member_data",
",",
"is_link_node",
",",
"parent_data",
",",
"index",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Abstract method.'",
")"
] | 59.5 | 0.002068 |
def flow_removed_handler(self, evt):
"""FlowRemoved event handler. when the removed flow entry was
for LACP, set the status of the slave i/f to disabled, and
send a event."""
msg = evt.msg
datapath = msg.datapath
ofproto = datapath.ofproto
dpid = datapath.id
... | [
"def",
"flow_removed_handler",
"(",
"self",
",",
"evt",
")",
":",
"msg",
"=",
"evt",
".",
"msg",
"datapath",
"=",
"msg",
".",
"datapath",
"ofproto",
"=",
"datapath",
".",
"ofproto",
"dpid",
"=",
"datapath",
".",
"id",
"match",
"=",
"msg",
".",
"match",... | 38.375 | 0.002119 |
def all_synsets(self):
'''
A generator over all the synsets in the GermaNet database.
'''
for synset_dict in self._mongo_db.synsets.find():
yield Synset(self, synset_dict) | [
"def",
"all_synsets",
"(",
"self",
")",
":",
"for",
"synset_dict",
"in",
"self",
".",
"_mongo_db",
".",
"synsets",
".",
"find",
"(",
")",
":",
"yield",
"Synset",
"(",
"self",
",",
"synset_dict",
")"
] | 35 | 0.009302 |
def checkout(self, ref, branch=None):
"""Do a git checkout of `ref`."""
return git_checkout(self.repo_dir, ref, branch=branch) | [
"def",
"checkout",
"(",
"self",
",",
"ref",
",",
"branch",
"=",
"None",
")",
":",
"return",
"git_checkout",
"(",
"self",
".",
"repo_dir",
",",
"ref",
",",
"branch",
"=",
"branch",
")"
] | 46.666667 | 0.014085 |
def after_this_request(func: Callable) -> Callable:
"""Schedule the func to be called after the current request.
This is useful in situations whereby you want an after request
function for a specific route or circumstance only, for example,
.. code-block:: python
def index():
@aft... | [
"def",
"after_this_request",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"_request_ctx_stack",
".",
"top",
".",
"_after_request_functions",
".",
"append",
"(",
"func",
")",
"return",
"func"
] | 30.555556 | 0.001764 |
def preprocess_data():
"""
Get the Enron e-mails from disk.
Represent them as bag-of-words.
Shuffle and split train/test.
"""
print("Importing dataset from disk...")
path = 'enron1/ham/'
ham1 = [open(path + f, 'r', errors='replace').read().strip(r"\n")
for f in os.listdir(pa... | [
"def",
"preprocess_data",
"(",
")",
":",
"print",
"(",
"\"Importing dataset from disk...\"",
")",
"path",
"=",
"'enron1/ham/'",
"ham1",
"=",
"[",
"open",
"(",
"path",
"+",
"f",
",",
"'r'",
",",
"errors",
"=",
"'replace'",
")",
".",
"read",
"(",
")",
".",... | 35.652174 | 0.000593 |
def XML(uri, tc, ps, **keywords):
'''Resolve a URI and return its content as an XML DOM.
'''
source = urllib.urlopen(uri, **keywords)
enc = source.info().getencoding()
if enc in ['7bit', '8bit', 'binary']:
data = source
else:
data = StringIO.StringIO()
mimetools.decode(so... | [
"def",
"XML",
"(",
"uri",
",",
"tc",
",",
"ps",
",",
"*",
"*",
"keywords",
")",
":",
"source",
"=",
"urllib",
".",
"urlopen",
"(",
"uri",
",",
"*",
"*",
"keywords",
")",
"enc",
"=",
"source",
".",
"info",
"(",
")",
".",
"getencoding",
"(",
")",... | 32.615385 | 0.002294 |
def has_role_collective(self, identifiers, role_s, logical_operator):
"""
:param identifiers: a collection of identifiers
:type identifiers: subject_abcs.IdentifierCollection
:param role_s: a collection of 1..N Role identifiers
:type role_s: Set of String(s)
:param log... | [
"def",
"has_role_collective",
"(",
"self",
",",
"identifiers",
",",
"role_s",
",",
"logical_operator",
")",
":",
"self",
".",
"assert_realms_configured",
"(",
")",
"# interim_results is a set of tuples:",
"interim_results",
"=",
"self",
".",
"has_role",
"(",
"identifi... | 36.088235 | 0.001587 |
def to_text(string, encoding="utf-8", errors=None):
"""Force a value to a text-type.
:param string: Some input that can be converted to a unicode representation.
:type string: str or bytes unicode
:param encoding: The encoding to use for conversions, defaults to "utf-8"
:param encoding: str, option... | [
"def",
"to_text",
"(",
"string",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"None",
")",
":",
"unicode_name",
"=",
"get_canonical_encoding_name",
"(",
"\"utf-8\"",
")",
"if",
"not",
"errors",
":",
"if",
"get_canonical_encoding_name",
"(",
"encoding",... | 38.105263 | 0.001347 |
def send(self, diff):
""" Write the diff (toVol from fromVol) to the stream context manager. """
if not self.dryrun:
self._fileSystemSync()
return self.butter.send(
self.getSendPath(diff.toVol),
self.getSendPath(diff.fromVol),
diff,
se... | [
"def",
"send",
"(",
"self",
",",
"diff",
")",
":",
"if",
"not",
"self",
".",
"dryrun",
":",
"self",
".",
"_fileSystemSync",
"(",
")",
"return",
"self",
".",
"butter",
".",
"send",
"(",
"self",
".",
"getSendPath",
"(",
"diff",
".",
"toVol",
")",
","... | 31.272727 | 0.008475 |
def get_version():
"""Obtain InaSAFE's version from version file.
:returns: The current version number.
:rtype: str
"""
# Get location of application wide version info
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__)))
version_file = os.path.join(root_dir, 'safe', 'definit... | [
"def",
"get_version",
"(",
")",
":",
"# Get location of application wide version info",
"root_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
")",
"versio... | 31.681818 | 0.001393 |
def authorization_header(oauth_params):
"""Return Authorization header"""
authorization_headers = 'OAuth realm="",'
authorization_headers += ','.join(['{0}="{1}"'.format(k, urllib.quote(str(v)))
for k, v in oauth_params.items()])
return authorization_headers | [
"def",
"authorization_header",
"(",
"oauth_params",
")",
":",
"authorization_headers",
"=",
"'OAuth realm=\"\",'",
"authorization_headers",
"+=",
"','",
".",
"join",
"(",
"[",
"'{0}=\"{1}\"'",
".",
"format",
"(",
"k",
",",
"urllib",
".",
"quote",
"(",
"str",
"("... | 49.5 | 0.013245 |
def fit(self, data, debug=False):
"""
Fit the model to data and store/return the results.
Parameters
----------
data : pandas.DataFrame
Data to use for fitting the model. Must contain all the
columns referenced by the `model_expression`.
debug : b... | [
"def",
"fit",
"(",
"self",
",",
"data",
",",
"debug",
"=",
"False",
")",
":",
"with",
"log_start_finish",
"(",
"'fitting model {}'",
".",
"format",
"(",
"self",
".",
"name",
")",
",",
"logger",
")",
":",
"fit",
"=",
"fit_model",
"(",
"data",
",",
"se... | 39.473684 | 0.001301 |
def _get_map_from_user_by_id(self, user, map_id):
""" Get a mapfile owned by a user from the database by
map_id. """
req = Session.query(Map).select_from(join(Map, User))
try:
return req.filter(and_(User.login==user, Map.id==map_id)).one()
except Exception, e:
... | [
"def",
"_get_map_from_user_by_id",
"(",
"self",
",",
"user",
",",
"map_id",
")",
":",
"req",
"=",
"Session",
".",
"query",
"(",
"Map",
")",
".",
"select_from",
"(",
"join",
"(",
"Map",
",",
"User",
")",
")",
"try",
":",
"return",
"req",
".",
"filter"... | 41.625 | 0.011765 |
def getAssociationFilename(self, server_url, handle):
"""Create a unique filename for a given server url and
handle. This implementation does not assume anything about the
format of the handle. The filename that is returned will
contain the domain name from the server URL for ease of hum... | [
"def",
"getAssociationFilename",
"(",
"self",
",",
"server_url",
",",
"handle",
")",
":",
"if",
"server_url",
".",
"find",
"(",
"'://'",
")",
"==",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"'Bad server URL: %r'",
"%",
"server_url",
")",
"proto",
",",
"re... | 37.869565 | 0.00224 |
def _get(self, url, method, host):
"""Get a request handler based on the URL of the request, or raises an
error. Internal method for caching.
:param url: request URL
:param method: request method
:return: handler, arguments, keyword arguments
"""
url = host + ur... | [
"def",
"_get",
"(",
"self",
",",
"url",
",",
"method",
",",
"host",
")",
":",
"url",
"=",
"host",
"+",
"url",
"# Check against known static routes",
"route",
"=",
"self",
".",
"routes_static",
".",
"get",
"(",
"url",
")",
"method_not_supported",
"=",
"self... | 42.204082 | 0.000945 |
def F(Document, __raw__=None, **filters):
"""Generate a MongoDB filter document through parameter interpolation.
Arguments passed by name have their name interpreted as an optional prefix (currently only `not`), a double-
underscore
Because this utility is likely going to be used frequently it has been given a ... | [
"def",
"F",
"(",
"Document",
",",
"__raw__",
"=",
"None",
",",
"*",
"*",
"filters",
")",
":",
"ops",
"=",
"Filter",
"(",
"__raw__",
")",
"args",
"=",
"_process_arguments",
"(",
"Document",
",",
"FILTER_PREFIX_MAP",
",",
"FILTER_OPERATION_MAP",
",",
"filter... | 26.333333 | 0.051908 |
def https_policy_from_config(config):
"""
Create an ``IPolicyForHTTPS`` which can authenticate a Kubernetes API
server.
:param KubeConfig config: A Kubernetes configuration containing an active
context identifying a cluster. The resulting ``IPolicyForHTTPS`` will
authenticate the API s... | [
"def",
"https_policy_from_config",
"(",
"config",
")",
":",
"server",
"=",
"config",
".",
"cluster",
"[",
"\"server\"",
"]",
"base_url",
"=",
"URL",
".",
"fromText",
"(",
"native_string_to_unicode",
"(",
"server",
")",
")",
"ca_certs",
"=",
"pem",
".",
"pars... | 34.763158 | 0.000736 |
def symbol_pos(self, cursor, character_type=OPEN, symbol_type=PAREN):
"""
Find the corresponding symbol position (line, column) of the specified
symbol. If symbol type is PAREN and character_type is OPEN, the
function will look for '('.
:param cursor: QTextCursor
:param ... | [
"def",
"symbol_pos",
"(",
"self",
",",
"cursor",
",",
"character_type",
"=",
"OPEN",
",",
"symbol_type",
"=",
"PAREN",
")",
":",
"retval",
"=",
"None",
",",
"None",
"original_cursor",
"=",
"self",
".",
"editor",
".",
"textCursor",
"(",
")",
"self",
".",
... | 43.434783 | 0.001959 |
def intersect(self, start_point, end_point):
"""Intersect the line segment with the box return the first
intersection point and normal vector pointing into space from
the box side intersected.
If the line does not intersect, or lies completely in one side
of the box return... | [
"def",
"intersect",
"(",
"self",
",",
"start_point",
",",
"end_point",
")",
":",
"sx",
",",
"sy",
",",
"sz",
"=",
"start_point",
"ex",
",",
"ey",
",",
"ez",
"=",
"end_point",
"p1x",
",",
"p1y",
",",
"p1z",
"=",
"self",
".",
"point1",
"p2x",
",",
... | 49.578125 | 0.002472 |
def _get_referenced_services(specs):
"""
Returns all services that are referenced in specs.apps.depends.services,
or in specs.bundles.services
"""
active_services = set()
for app_spec in specs['apps'].values():
for service in app_spec['depends']['services']:
active_services.a... | [
"def",
"_get_referenced_services",
"(",
"specs",
")",
":",
"active_services",
"=",
"set",
"(",
")",
"for",
"app_spec",
"in",
"specs",
"[",
"'apps'",
"]",
".",
"values",
"(",
")",
":",
"for",
"service",
"in",
"app_spec",
"[",
"'depends'",
"]",
"[",
"'serv... | 37.307692 | 0.002012 |
def post(self, url: str, data: List[dict]) -> List[dict]:
""" Gives data to database """
data.update({
'key': self.api_key,
})
response = requests.post(
url,
data = json.dumps(data),
headers = {'Content-type': 'application/json'},
... | [
"def",
"post",
"(",
"self",
",",
"url",
":",
"str",
",",
"data",
":",
"List",
"[",
"dict",
"]",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"data",
".",
"update",
"(",
"{",
"'key'",
":",
"self",
".",
"api_key",
",",
"}",
")",
"response",
"=",
"... | 35 | 0.019272 |
def generate_static(self, path):
"""
This method generates a valid path to the public folder of the running project
"""
if not path:
return ""
if path[0] == '/':
return "%s?v=%s" % (path, self.version)
return "%s/%s?v=%s" % (self.static, path, se... | [
"def",
"generate_static",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"path",
":",
"return",
"\"\"",
"if",
"path",
"[",
"0",
"]",
"==",
"'/'",
":",
"return",
"\"%s?v=%s\"",
"%",
"(",
"path",
",",
"self",
".",
"version",
")",
"return",
"\"%s/%s?v... | 29.181818 | 0.009063 |
def leaf_bus(self, df=False):
"""
Return leaf bus idx, line idx, and the line foreign key
Returns
-------
(list, list, list) or DataFrame
"""
# leafs - leaf bus idx
# lines - line idx
# fkey - the foreign key of Line, in 'bus1' or 'bus2', linking... | [
"def",
"leaf_bus",
"(",
"self",
",",
"df",
"=",
"False",
")",
":",
"# leafs - leaf bus idx",
"# lines - line idx",
"# fkey - the foreign key of Line, in 'bus1' or 'bus2', linking the bus",
"leafs",
",",
"lines",
",",
"fkeys",
"=",
"list",
"(",
")",
",",
"list",
"(",
... | 29 | 0.001756 |
def register(self, settings_class=NoSwitcher, *simple_checks,
**conditions):
"""
Register a settings class with the switcher. Can be passed the settings
class to register or be used as a decorator.
:param settings_class: The class to register with the provided
... | [
"def",
"register",
"(",
"self",
",",
"settings_class",
"=",
"NoSwitcher",
",",
"*",
"simple_checks",
",",
"*",
"*",
"conditions",
")",
":",
"if",
"settings_class",
"is",
"NoSwitcher",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"self",
".",
"register",
... | 45.551724 | 0.002224 |
def plot_environments(self, isite, plot_type=None, title='Coordination numbers', max_dist=2.0,
additional_condition=AC.ONLY_ACB, figsize=None, strategy=None):
"""
Plotting of the coordination numbers of a given site for all the distfactor/angfactor parameters. If the
c... | [
"def",
"plot_environments",
"(",
"self",
",",
"isite",
",",
"plot_type",
"=",
"None",
",",
"title",
"=",
"'Coordination numbers'",
",",
"max_dist",
"=",
"2.0",
",",
"additional_condition",
"=",
"AC",
".",
"ONLY_ACB",
",",
"figsize",
"=",
"None",
",",
"strate... | 72.136364 | 0.008085 |
def table(self):
"""
打印出account的内容
"""
return pd.DataFrame([
self.message,
]).set_index(
'account_cookie',
drop=False
).T | [
"def",
"table",
"(",
"self",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"[",
"self",
".",
"message",
",",
"]",
")",
".",
"set_index",
"(",
"'account_cookie'",
",",
"drop",
"=",
"False",
")",
".",
"T"
] | 19.6 | 0.009756 |
def custom_except_hook(exc_info):
"""
A custom excepthook to present python errors produced by the CLI.
We don't want to show end users big scary stacktraces if they aren't python
programmers, so slim it down to some basic info. We keep a "DEBUGMODE" env
variable kicking around to let us turn on sta... | [
"def",
"custom_except_hook",
"(",
"exc_info",
")",
":",
"exception_type",
",",
"exception",
",",
"traceback",
"=",
"exc_info",
"# check if we're in debug mode, and run the real excepthook if we are",
"ctx",
"=",
"click",
".",
"get_current_context",
"(",
")",
"state",
"=",... | 43.319444 | 0.000313 |
def transform(self, X, lenscale=None):
"""
Apply the Fast Food RBF basis to X.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: scalar or ndarray, optional
... | [
"def",
"transform",
"(",
"self",
",",
"X",
",",
"lenscale",
"=",
"None",
")",
":",
"lenscale",
"=",
"self",
".",
"_check_dim",
"(",
"X",
".",
"shape",
"[",
"1",
"]",
",",
"lenscale",
")",
"VX",
"=",
"self",
".",
"_makeVX",
"(",
"X",
"/",
"lenscal... | 33.269231 | 0.002247 |
def remove(self, ids, **kwargs):
"""
Method to delete interface by id.
:param ids: List containing identifiers of interfaces.
"""
url = build_uri_with_ids('api/v3/interface/%s/', ids)
return super(ApiInterfaceRequest, self).delete(self.prepare_url(url, kwargs)) | [
"def",
"remove",
"(",
"self",
",",
"ids",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"build_uri_with_ids",
"(",
"'api/v3/interface/%s/'",
",",
"ids",
")",
"return",
"super",
"(",
"ApiInterfaceRequest",
",",
"self",
")",
".",
"delete",
"(",
"self",
".... | 37.875 | 0.009677 |
def nms(dets, thresh):
"""
greedily select boxes with high confidence and overlap with current maximum <= thresh
rule out overlap >= thresh
:param dets: [[x1, y1, x2, y2 score]]
:param thresh: retain overlap < thresh
:return: indexes to keep
"""
x1 = dets[:, 0]
y1 = dets[:, 1]
x2... | [
"def",
"nms",
"(",
"dets",
",",
"thresh",
")",
":",
"x1",
"=",
"dets",
"[",
":",
",",
"0",
"]",
"y1",
"=",
"dets",
"[",
":",
",",
"1",
"]",
"x2",
"=",
"dets",
"[",
":",
",",
"2",
"]",
"y2",
"=",
"dets",
"[",
":",
",",
"3",
"]",
"scores"... | 27.285714 | 0.002022 |
def getAttr(self, node, name, nsuri=None, default=join):
"""Return the value of the attribute named 'name' with the
optional nsuri, or the default if one is specified. If
nsuri is not specified, an attribute that matches the
given name will be returned regardless of namespace.""... | [
"def",
"getAttr",
"(",
"self",
",",
"node",
",",
"name",
",",
"nsuri",
"=",
"None",
",",
"default",
"=",
"join",
")",
":",
"if",
"nsuri",
"is",
"None",
":",
"result",
"=",
"node",
".",
"_attrs",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
... | 41.894737 | 0.002457 |
def connect(token, protocol=RtmProtocol, factory=WebSocketClientFactory, factory_kwargs=None, api_url=None, debug=False):
"""
Creates a new connection to the Slack Real-Time API.
Returns (connection) which represents this connection to the API server.
"""
if factory_kwargs is None:
factory_kwargs = dict()
me... | [
"def",
"connect",
"(",
"token",
",",
"protocol",
"=",
"RtmProtocol",
",",
"factory",
"=",
"WebSocketClientFactory",
",",
"factory_kwargs",
"=",
"None",
",",
"api_url",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"if",
"factory_kwargs",
"is",
"None",
... | 33.833333 | 0.027157 |
def _buildStartOpts(self, streamUrl, playList=False):
""" Builds the options to pass to subprocess."""
#opts = [self.PLAYER_CMD, "-Irc", "--quiet", streamUrl]
opts = [self.PLAYER_CMD, "-Irc", "-vv", streamUrl]
return opts | [
"def",
"_buildStartOpts",
"(",
"self",
",",
"streamUrl",
",",
"playList",
"=",
"False",
")",
":",
"#opts = [self.PLAYER_CMD, \"-Irc\", \"--quiet\", streamUrl]",
"opts",
"=",
"[",
"self",
".",
"PLAYER_CMD",
",",
"\"-Irc\"",
",",
"\"-vv\"",
",",
"streamUrl",
"]",
"r... | 49.8 | 0.011858 |
def cmp_res_R2(lstRat, lstNiiNames, strPathOut, strPathMdl, lgcSveMdlTc=True,
lgcDel=False, strNmeExt=''):
""""Compare results for different exponents and create winner nii.
Parameters
----------
lstRat : list
List of floats containing the ratios that were tested for surround
... | [
"def",
"cmp_res_R2",
"(",
"lstRat",
",",
"lstNiiNames",
",",
"strPathOut",
",",
"strPathMdl",
",",
"lgcSveMdlTc",
"=",
"True",
",",
"lgcDel",
"=",
"False",
",",
"strNmeExt",
"=",
"''",
")",
":",
"print",
"(",
"'---Compare results for different ratios'",
")",
"... | 46.550459 | 0.000482 |
def is_binary_file(file_obj):
"""
Returns True if file has non-ASCII characters (> 0x7F, or 127)
Should work in both Python 2 and 3
"""
start = file_obj.tell()
fbytes = file_obj.read(1024)
file_obj.seek(start)
is_str = isinstance(fbytes, str)
for fbyte in fbytes:
if is_str:
... | [
"def",
"is_binary_file",
"(",
"file_obj",
")",
":",
"start",
"=",
"file_obj",
".",
"tell",
"(",
")",
"fbytes",
"=",
"file_obj",
".",
"read",
"(",
"1024",
")",
"file_obj",
".",
"seek",
"(",
"start",
")",
"is_str",
"=",
"isinstance",
"(",
"fbytes",
",",
... | 25.588235 | 0.002217 |
def clear_all():
"""DANGER!
*This command is a maintenance tool and clears the complete database.*
"""
sure = input("Are you sure to drop the complete database content? (Type "
"in upppercase YES)")
if not (sure == 'YES'):
db_log('Not deleting the database.')
sys.ex... | [
"def",
"clear_all",
"(",
")",
":",
"sure",
"=",
"input",
"(",
"\"Are you sure to drop the complete database content? (Type \"",
"\"in upppercase YES)\"",
")",
"if",
"not",
"(",
"sure",
"==",
"'YES'",
")",
":",
"db_log",
"(",
"'Not deleting the database.'",
")",
"sys",... | 32.352941 | 0.001767 |
def calculate_cut_coords_by_zoom(
coord, metatile_zoom, cfg_tile_sizes, max_zoom):
"""
Returns a map of nominal zoom to the list of cut coordinates at that
nominal zoom.
Note that max_zoom should be the maximum coordinate zoom, not nominal
zoom.
"""
tile_sizes_by_zoom = calculate_s... | [
"def",
"calculate_cut_coords_by_zoom",
"(",
"coord",
",",
"metatile_zoom",
",",
"cfg_tile_sizes",
",",
"max_zoom",
")",
":",
"tile_sizes_by_zoom",
"=",
"calculate_sizes_by_zoom",
"(",
"coord",
",",
"metatile_zoom",
",",
"cfg_tile_sizes",
",",
"max_zoom",
")",
"cut_coo... | 31.913043 | 0.001323 |
def set_joint_mode(self, ids):
""" Sets the specified motors to joint mode. """
self.set_control_mode(dict(zip(ids, itertools.repeat('joint')))) | [
"def",
"set_joint_mode",
"(",
"self",
",",
"ids",
")",
":",
"self",
".",
"set_control_mode",
"(",
"dict",
"(",
"zip",
"(",
"ids",
",",
"itertools",
".",
"repeat",
"(",
"'joint'",
")",
")",
")",
")"
] | 52.666667 | 0.0125 |
def observe(cls, *args, **kwargs):
"""
Mark a method as receiving notifications. Comes in two flavours:
.. method:: observe(name, **types)
:noindex:
A decorator living in the class. Can be applied more than once to
the same method, provided the names differ.
... | [
"def",
"observe",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"@",
"decorators",
".",
"good_decorator",
"def",
"_decorator",
"(",
"_notified",
")",
":",
"# marks the method with observed properties",
"_list",
"=",
"getattr",
"(",
"_notifie... | 39.326531 | 0.000506 |
def create_and_update_from_json_data(d, user):
"""
Create or update page based on python dict d loaded from JSON data.
This applies all data except for redirect_to, which is done in a
second pass after all pages have been imported,
user is the User instance that will be used if the author can't
... | [
"def",
"create_and_update_from_json_data",
"(",
"d",
",",
"user",
")",
":",
"page",
"=",
"None",
"parent",
"=",
"None",
"parent_required",
"=",
"True",
"created",
"=",
"False",
"messages",
"=",
"[",
"]",
"page_languages",
"=",
"set",
"(",
"lang",
"[",
"0",... | 34.178571 | 0.002031 |
def _update_cache_stats(self, key, result):
"""
Update the cache stats.
If no cache-result is specified, we iniitialize the key.
Otherwise, we increment the correct cache-result.
Note the behavior for expired. A client can be expired and the key
still exists.
... | [
"def",
"_update_cache_stats",
"(",
"self",
",",
"key",
",",
"result",
")",
":",
"if",
"result",
"is",
"None",
":",
"self",
".",
"_CACHE_STATS",
"[",
"'access_stats'",
"]",
".",
"setdefault",
"(",
"key",
",",
"{",
"'hit'",
":",
"0",
",",
"'miss'",
":",
... | 37.333333 | 0.008711 |
def example_rgb_to_xyz():
"""
The reverse is similar.
"""
print("=== RGB Example: RGB->XYZ ===")
# Instantiate an Lab color object with the given values.
rgb = sRGBColor(120, 130, 140)
# Show a string representation.
print(rgb)
# Convert RGB to XYZ using a D50 illuminant.
xyz = ... | [
"def",
"example_rgb_to_xyz",
"(",
")",
":",
"print",
"(",
"\"=== RGB Example: RGB->XYZ ===\"",
")",
"# Instantiate an Lab color object with the given values.",
"rgb",
"=",
"sRGBColor",
"(",
"120",
",",
"130",
",",
"140",
")",
"# Show a string representation.",
"print",
"(... | 29.285714 | 0.002364 |
def delete(self, s, p, o):
"""Remove the given subj-pred-obj triple from the database."""
with self.walrus.atomic():
for key in self.keys_for_values(s, p, o):
del self._z[key] | [
"def",
"delete",
"(",
"self",
",",
"s",
",",
"p",
",",
"o",
")",
":",
"with",
"self",
".",
"walrus",
".",
"atomic",
"(",
")",
":",
"for",
"key",
"in",
"self",
".",
"keys_for_values",
"(",
"s",
",",
"p",
",",
"o",
")",
":",
"del",
"self",
".",... | 43 | 0.009132 |
def com_google_fonts_check_family_tnum_horizontal_metrics(fonts):
"""All tabular figures must have the same width across the RIBBI-family."""
from fontbakery.constants import RIBBI_STYLE_NAMES
from fontTools.ttLib import TTFont
RIBBI_ttFonts = [TTFont(f)
for f in fonts
if s... | [
"def",
"com_google_fonts_check_family_tnum_horizontal_metrics",
"(",
"fonts",
")",
":",
"from",
"fontbakery",
".",
"constants",
"import",
"RIBBI_STYLE_NAMES",
"from",
"fontTools",
".",
"ttLib",
"import",
"TTFont",
"RIBBI_ttFonts",
"=",
"[",
"TTFont",
"(",
"f",
")",
... | 38 | 0.010109 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.