text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def initialized(self, value):
"""
Setter for **self.__initialized** attribute.
:param value: Attribute value.
:type value: bool
"""
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("initialized", value)
... | [
"def",
"initialized",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"bool",
",",
"\"'{0}' attribute: '{1}' type is not 'bool'!\"",
".",
"format",
"(",
"\"initialized\"",
",",
"value",
... | 31.090909 | 19.090909 |
def writeBoolean(self, n):
"""
Writes a Boolean to the stream.
"""
t = TYPE_BOOL_TRUE
if n is False:
t = TYPE_BOOL_FALSE
self.stream.write(t) | [
"def",
"writeBoolean",
"(",
"self",
",",
"n",
")",
":",
"t",
"=",
"TYPE_BOOL_TRUE",
"if",
"n",
"is",
"False",
":",
"t",
"=",
"TYPE_BOOL_FALSE",
"self",
".",
"stream",
".",
"write",
"(",
"t",
")"
] | 19.4 | 14.8 |
def position_pnl(self):
"""
[float] 昨仓盈亏,策略在当前交易日产生的盈亏中来源于昨仓的部分
"""
last_price = self._data_proxy.get_last_price(self._order_book_id)
if self._direction == POSITION_DIRECTION.LONG:
price_spread = last_price - self._last_price
else:
price_spread = s... | [
"def",
"position_pnl",
"(",
"self",
")",
":",
"last_price",
"=",
"self",
".",
"_data_proxy",
".",
"get_last_price",
"(",
"self",
".",
"_order_book_id",
")",
"if",
"self",
".",
"_direction",
"==",
"POSITION_DIRECTION",
".",
"LONG",
":",
"price_spread",
"=",
"... | 38.545455 | 19.090909 |
def build_args():
"""Create command line argument parser."""
parser = argparse.ArgumentParser(description=u'Compile a sensor graph.')
parser.add_argument(u'sensor_graph', type=str, help=u"the sensor graph file to load and run.")
parser.add_argument(u'-f', u'--format', default=u"nodes", choices=[u'nodes... | [
"def",
"build_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"u'Compile a sensor graph.'",
")",
"parser",
".",
"add_argument",
"(",
"u'sensor_graph'",
",",
"type",
"=",
"str",
",",
"help",
"=",
"u\"the sensor gra... | 76.777778 | 55.222222 |
def update(gandi, resource, name, gateway, create, bandwidth):
""" Update a vlan
``gateway`` can be a vm name or id, or an ip.
"""
params = {}
if name:
params['name'] = name
vlan_id = gandi.vlan.usable_id(resource)
try:
if gateway:
IP(gateway)
param... | [
"def",
"update",
"(",
"gandi",
",",
"resource",
",",
"name",
",",
"gateway",
",",
"create",
",",
"bandwidth",
")",
":",
"params",
"=",
"{",
"}",
"if",
"name",
":",
"params",
"[",
"'name'",
"]",
"=",
"name",
"vlan_id",
"=",
"gandi",
".",
"vlan",
"."... | 31.326087 | 21.891304 |
def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]:
"""
Gets column names (that is, database column names) from an SQLAlchemy
ORM class.
"""
colnames = [col.name for col in get_orm_columns(cls)]
return sorted(colnames) if sort else colnames | [
"def",
"get_orm_column_names",
"(",
"cls",
":",
"Type",
",",
"sort",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"str",
"]",
":",
"colnames",
"=",
"[",
"col",
".",
"name",
"for",
"col",
"in",
"get_orm_columns",
"(",
"cls",
")",
"]",
"return",
... | 39.428571 | 16.285714 |
def randomly_init_variable(simulation, variable_name, period, max_value, condition = None):
"""
Initialise a variable with random values (from 0 to max_value) for the given period.
If a condition vector is provided, only set the value of persons or groups for which condition is True.
Exampl... | [
"def",
"randomly_init_variable",
"(",
"simulation",
",",
"variable_name",
",",
"period",
",",
"max_value",
",",
"condition",
"=",
"None",
")",
":",
"if",
"condition",
"is",
"None",
":",
"condition",
"=",
"True",
"variable",
"=",
"simulation",
".",
"tax_benefit... | 64.05 | 40.65 |
def _zom_arg(lexer):
"""Return zero or more arguments."""
tok = next(lexer)
# ',' EXPR ZOM_X
if isinstance(tok, COMMA):
return (_expr(lexer), ) + _zom_arg(lexer)
# null
else:
lexer.unpop_token(tok)
return tuple() | [
"def",
"_zom_arg",
"(",
"lexer",
")",
":",
"tok",
"=",
"next",
"(",
"lexer",
")",
"# ',' EXPR ZOM_X",
"if",
"isinstance",
"(",
"tok",
",",
"COMMA",
")",
":",
"return",
"(",
"_expr",
"(",
"lexer",
")",
",",
")",
"+",
"_zom_arg",
"(",
"lexer",
")",
"... | 25.1 | 16.7 |
def put_annotation(self, key, value):
"""
Annotate current active trace entity with a key-value pair.
Annotations will be indexed for later search query.
:param str key: annotation key
:param object value: annotation value. Any type other than
string/number/bool will... | [
"def",
"put_annotation",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"entity",
"=",
"self",
".",
"get_trace_entity",
"(",
")",
"if",
"entity",
"and",
"entity",
".",
"sampled",
":",
"entity",
".",
"put_annotation",
"(",
"key",
",",
"value",
")"
] | 38.083333 | 10.916667 |
def to_html(self):
"""Render a Paragraph MessageElement as html
:returns: The html representation of the Paragraph MessageElement
"""
if self.text is None:
return
else:
return '<p%s>%s%s</p>' % (
self.html_attributes(), self.html_icon(), ... | [
"def",
"to_html",
"(",
"self",
")",
":",
"if",
"self",
".",
"text",
"is",
"None",
":",
"return",
"else",
":",
"return",
"'<p%s>%s%s</p>'",
"%",
"(",
"self",
".",
"html_attributes",
"(",
")",
",",
"self",
".",
"html_icon",
"(",
")",
",",
"self",
".",
... | 30 | 21.363636 |
def post_commit(self, results):
'''\
Process results after a commit.
:parameter results: iterator over :class:`stdnet.instance_session_result`
items.
:rtype: a two elements tuple containing a list of instances saved and
a list of ids of instances deleted.'''
tpy = self._meta.pk_to_pytho... | [
"def",
"post_commit",
"(",
"self",
",",
"results",
")",
":",
"tpy",
"=",
"self",
".",
"_meta",
".",
"pk_to_python",
"instances",
"=",
"[",
"]",
"deleted",
"=",
"[",
"]",
"errors",
"=",
"[",
"]",
"# The length of results must be the same as the length of\r",
"#... | 43.085714 | 16.685714 |
def expire_soon(self, seconds):
"""
Returns ``True`` if credentials expire sooner than specified.
:param int seconds:
Number of seconds.
:returns:
``True`` if credentials expire sooner than specified,
else ``False``.
"""
if self.exp... | [
"def",
"expire_soon",
"(",
"self",
",",
"seconds",
")",
":",
"if",
"self",
".",
"expiration_time",
":",
"return",
"self",
".",
"expiration_time",
"<",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"+",
"int",
"(",
"seconds",
")",
"else",
":",
"retu... | 25.294118 | 21.529412 |
def append_row(self, values, value_input_option='RAW'):
"""Adds a row to the worksheet and populates it with values.
Widens the worksheet if there are more values than columns.
:param values: List of values for the new row.
:param value_input_option: (optional) Determines how input data... | [
"def",
"append_row",
"(",
"self",
",",
"values",
",",
"value_input_option",
"=",
"'RAW'",
")",
":",
"params",
"=",
"{",
"'valueInputOption'",
":",
"value_input_option",
"}",
"body",
"=",
"{",
"'values'",
":",
"[",
"values",
"]",
"}",
"return",
"self",
".",... | 36.681818 | 25.909091 |
def sendBox(self, box):
"""
Add the route and send the box.
"""
if self.remoteRouteName is _unspecified:
raise RouteNotConnected()
if self.remoteRouteName is not None:
box[_ROUTE] = self.remoteRouteName.encode('ascii')
self.router._sender.sendBox(b... | [
"def",
"sendBox",
"(",
"self",
",",
"box",
")",
":",
"if",
"self",
".",
"remoteRouteName",
"is",
"_unspecified",
":",
"raise",
"RouteNotConnected",
"(",
")",
"if",
"self",
".",
"remoteRouteName",
"is",
"not",
"None",
":",
"box",
"[",
"_ROUTE",
"]",
"=",
... | 35 | 6.111111 |
def compute_acl(cls, filename, start_index=None, end_index=None,
min_nsamples=10):
"""Computes the autocorrleation length for all model params and
temperatures in the given file.
Parameter values are averaged over all walkers at each iteration and
temperature. The A... | [
"def",
"compute_acl",
"(",
"cls",
",",
"filename",
",",
"start_index",
"=",
"None",
",",
"end_index",
"=",
"None",
",",
"min_nsamples",
"=",
"10",
")",
":",
"acls",
"=",
"{",
"}",
"with",
"cls",
".",
"_io",
"(",
"filename",
",",
"'r'",
")",
"as",
"... | 42.807692 | 17.538462 |
def deserialize(cls, assoc_s):
"""
Parse an association as stored by serialize().
inverse of serialize
@param assoc_s: Association as serialized by serialize()
@type assoc_s: str
@return: instance of this class
"""
pairs = kvform.kvToSeq(assoc_s, str... | [
"def",
"deserialize",
"(",
"cls",
",",
"assoc_s",
")",
":",
"pairs",
"=",
"kvform",
".",
"kvToSeq",
"(",
"assoc_s",
",",
"strict",
"=",
"True",
")",
"keys",
"=",
"[",
"]",
"values",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"pairs",
":",
"keys",... | 27.483871 | 20.387097 |
def push(ol,*eles,**kwargs):
'''
from elist.elist import *
ol=[1,2,3,4]
id(ol)
new = push(ol,5,6,7)
new
id(new)
####
ol=[1,2,3,4]
id(ol)
rslt = push(ol,5,6,7,mode="original")
rslt
id(rslt)
'''
if('mode' in kwargs... | [
"def",
"push",
"(",
"ol",
",",
"*",
"eles",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"'mode'",
"in",
"kwargs",
")",
":",
"mode",
"=",
"kwargs",
"[",
"'mode'",
"]",
"else",
":",
"mode",
"=",
"\"new\"",
"eles",
"=",
"list",
"(",
"eles",
")",... | 20.142857 | 20.333333 |
def subscribe(self, job, id=None):
"""
Subscribes to job logs. It return the subscribe Response object which you will need to call .stream() on
to read the output stream of this job.
Calling subscribe multiple times will cause different subscriptions on the same job, each subscription w... | [
"def",
"subscribe",
"(",
"self",
",",
"job",
",",
"id",
"=",
"None",
")",
":",
"return",
"self",
".",
"raw",
"(",
"'core.subscribe'",
",",
"{",
"'id'",
":",
"job",
"}",
",",
"stream",
"=",
"True",
",",
"id",
"=",
"id",
")"
] | 42.289474 | 30.552632 |
def image_snapshot_delete(call=None, kwargs=None):
'''
Deletes a snapshot from the image.
.. versionadded:: 2016.3.0
image_id
The ID of the image from which to delete the snapshot. Can be used instead of
``image_name``.
image_name
The name of the image from which to delete... | [
"def",
"image_snapshot_delete",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The image_snapshot_delete function must be called with -f or --function.'",
")",
"if",
"kwargs",... | 28.626866 | 24.865672 |
def pose2mat(pose):
"""
Converts pose to homogeneous matrix.
Args:
pose: a (pos, orn) tuple where pos is vec3 float cartesian, and
orn is vec4 float quaternion.
Returns:
4x4 homogeneous matrix
"""
homo_pose_mat = np.zeros((4, 4), dtype=np.float32)
homo_pose_mat[... | [
"def",
"pose2mat",
"(",
"pose",
")",
":",
"homo_pose_mat",
"=",
"np",
".",
"zeros",
"(",
"(",
"4",
",",
"4",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"homo_pose_mat",
"[",
":",
"3",
",",
":",
"3",
"]",
"=",
"quat2mat",
"(",
"pose",
"[... | 28.0625 | 16.9375 |
def get_path(self):
"""Gets the path to the focused statistics. Each step is a hash of
statistics object.
"""
path = deque()
__, node = self.get_focus()
while not node.is_root():
stats = node.get_value()
path.appendleft(hash(stats))
nod... | [
"def",
"get_path",
"(",
"self",
")",
":",
"path",
"=",
"deque",
"(",
")",
"__",
",",
"node",
"=",
"self",
".",
"get_focus",
"(",
")",
"while",
"not",
"node",
".",
"is_root",
"(",
")",
":",
"stats",
"=",
"node",
".",
"get_value",
"(",
")",
"path",... | 31.909091 | 8.545455 |
def _fploadstr(ins):
""" Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
Unlike ploadstr, this version does not push the result
back into the stack.
"""
output = _pload(ins.quad[2], 2)
if ins.quad[1][0] != '$':
output.append('call ... | [
"def",
"_fploadstr",
"(",
"ins",
")",
":",
"output",
"=",
"_pload",
"(",
"ins",
".",
"quad",
"[",
"2",
"]",
",",
"2",
")",
"if",
"ins",
".",
"quad",
"[",
"1",
"]",
"[",
"0",
"]",
"!=",
"'$'",
":",
"output",
".",
"append",
"(",
"'call __LOADSTR'... | 26.642857 | 14.285714 |
def _stop_all_nodes(self, wait=False):
"""
Terminate all cluster nodes. Return number of failures.
"""
failed = 0
for node in self.get_all_nodes():
if not node.instance_id:
log.warning(
"Node `%s` has no instance ID."
... | [
"def",
"_stop_all_nodes",
"(",
"self",
",",
"wait",
"=",
"False",
")",
":",
"failed",
"=",
"0",
"for",
"node",
"in",
"self",
".",
"get_all_nodes",
"(",
")",
":",
"if",
"not",
"node",
".",
"instance_id",
":",
"log",
".",
"warning",
"(",
"\"Node `%s` has... | 40.25 | 15.625 |
def get_result(self, api=None):
"""
Get async job result in bulk format
:return: List of AsyncFileBulkRecord objects
"""
api = api or self._API
if not self.result:
return []
return AsyncFileBulkRecord.parse_records(
result=self.result,
... | [
"def",
"get_result",
"(",
"self",
",",
"api",
"=",
"None",
")",
":",
"api",
"=",
"api",
"or",
"self",
".",
"_API",
"if",
"not",
"self",
".",
"result",
":",
"return",
"[",
"]",
"return",
"AsyncFileBulkRecord",
".",
"parse_records",
"(",
"result",
"=",
... | 27.833333 | 11.333333 |
def load_pkl(filenames):
"""
Unpickle file contents.
Args:
filenames (str): Can be one or a list or tuple of filenames to retrieve.
Returns:
Times: A single object, or from a collection of filenames, a list of Times objects.
Raises:
TypeError: If any loaded object is not a... | [
"def",
"load_pkl",
"(",
"filenames",
")",
":",
"if",
"not",
"isinstance",
"(",
"filenames",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"filenames",
"=",
"[",
"filenames",
"]",
"times",
"=",
"[",
"]",
"for",
"name",
"in",
"filenames",
":",
"name",... | 32.291667 | 20.708333 |
def process_update(self, update):
"""Process an incoming update from a remote NetworkTables"""
data = json.loads(update)
NetworkTables.getEntry(data["k"]).setValue(data["v"]) | [
"def",
"process_update",
"(",
"self",
",",
"update",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"update",
")",
"NetworkTables",
".",
"getEntry",
"(",
"data",
"[",
"\"k\"",
"]",
")",
".",
"setValue",
"(",
"data",
"[",
"\"v\"",
"]",
")"
] | 48.75 | 8.75 |
def fetch_url(src, dst):
"""
Fetch file from URL src and save it to dst.
"""
# we do not use the nicer sys.version_info.major
# for compatibility with Python < 2.7
if sys.version_info[0] > 2:
import urllib.request
class URLopener(urllib.request.FancyURLopener):
def h... | [
"def",
"fetch_url",
"(",
"src",
",",
"dst",
")",
":",
"# we do not use the nicer sys.version_info.major",
"# for compatibility with Python < 2.7",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">",
"2",
":",
"import",
"urllib",
".",
"request",
"class",
"URLopener... | 32.428571 | 18.5 |
def load_reg(self, reg_type, reg_name, name=''):
"""
Load a register value into an LLVM value.
Example: v = load_reg(IntType(32), "eax")
"""
ftype = types.FunctionType(reg_type, [])
return self.asm(ftype, "", "={%s}" % reg_name, [], False, name) | [
"def",
"load_reg",
"(",
"self",
",",
"reg_type",
",",
"reg_name",
",",
"name",
"=",
"''",
")",
":",
"ftype",
"=",
"types",
".",
"FunctionType",
"(",
"reg_type",
",",
"[",
"]",
")",
"return",
"self",
".",
"asm",
"(",
"ftype",
",",
"\"\"",
",",
"\"={... | 41.285714 | 9.571429 |
def check_undelivered(to=None):
"""Sends a notification email if any undelivered dispatches.
Returns undelivered (failed) dispatches count.
:param str|unicode to: Recipient address. If not set Django ADMINS setting is used.
:rtype: int
"""
failed_count = Dispatch.objects.filter(dispatch_statu... | [
"def",
"check_undelivered",
"(",
"to",
"=",
"None",
")",
":",
"failed_count",
"=",
"Dispatch",
".",
"objects",
".",
"filter",
"(",
"dispatch_status",
"=",
"Dispatch",
".",
"DISPATCH_STATUS_FAILED",
")",
".",
"count",
"(",
")",
"if",
"failed_count",
":",
"fro... | 29.823529 | 25.617647 |
def clean_old_entries():
"""Deletes obsolete entries from the queues"""
from indico_livesync.plugin import LiveSyncPlugin
from indico_livesync.models.queue import LiveSyncQueueEntry
queue_entry_ttl = LiveSyncPlugin.settings.get('queue_entry_ttl')
if not queue_entry_ttl:
return
expire_th... | [
"def",
"clean_old_entries",
"(",
")",
":",
"from",
"indico_livesync",
".",
"plugin",
"import",
"LiveSyncPlugin",
"from",
"indico_livesync",
".",
"models",
".",
"queue",
"import",
"LiveSyncQueueEntry",
"queue_entry_ttl",
"=",
"LiveSyncPlugin",
".",
"settings",
".",
"... | 48.545455 | 24.909091 |
def base_url(self, value):
"""Set the Base URI value.
:param value: the new URI to use for the Base URI
"""
logger.debug('StackInABoxService ({0}:{1}) Updating Base URL '
'from {2} to {3}'
.format(self.__id,
self.nam... | [
"def",
"base_url",
"(",
"self",
",",
"value",
")",
":",
"logger",
".",
"debug",
"(",
"'StackInABoxService ({0}:{1}) Updating Base URL '",
"'from {2} to {3}'",
".",
"format",
"(",
"self",
".",
"__id",
",",
"self",
".",
"name",
",",
"self",
".",
"__base_url",
",... | 36.823529 | 11.117647 |
def anyopen(datasource, mode='rt', reset=True):
"""Open datasource (gzipped, bzipped, uncompressed) and return a stream.
`datasource` can be a filename or a stream (see :func:`isstream`). By
default, a stream is reset to its start if possible (via
:meth:`~io.IOBase.seek` or :meth:`~cString.StringIO.res... | [
"def",
"anyopen",
"(",
"datasource",
",",
"mode",
"=",
"'rt'",
",",
"reset",
"=",
"True",
")",
":",
"handlers",
"=",
"{",
"'bz2'",
":",
"bz2_open",
",",
"'gz'",
":",
"gzip",
".",
"open",
",",
"''",
":",
"open",
"}",
"if",
"mode",
".",
"startswith",... | 40.383721 | 22.162791 |
async def serviceNodeMsgs(self, limit: int) -> int:
"""
Process `limit` number of messages from the nodeInBox.
:param limit: the maximum number of messages to process
:return: the number of messages successfully processed
"""
with self.metrics.measure_time(MetricsName.SE... | [
"async",
"def",
"serviceNodeMsgs",
"(",
"self",
",",
"limit",
":",
"int",
")",
"->",
"int",
":",
"with",
"self",
".",
"metrics",
".",
"measure_time",
"(",
"MetricsName",
".",
"SERVICE_NODE_STACK_TIME",
")",
":",
"n",
"=",
"await",
"self",
".",
"nodestack",... | 39.071429 | 24.214286 |
def cmd(self):
"""Returns the (last) saved command line.
If the file was created from a run that resumed from a checkpoint, only
the last command line used is returned.
Returns
-------
cmd : string
The command line that created this InferenceFile.
""... | [
"def",
"cmd",
"(",
"self",
")",
":",
"cmd",
"=",
"self",
".",
"attrs",
"[",
"\"cmd\"",
"]",
"if",
"isinstance",
"(",
"cmd",
",",
"numpy",
".",
"ndarray",
")",
":",
"cmd",
"=",
"cmd",
"[",
"-",
"1",
"]",
"return",
"cmd"
] | 28.466667 | 19.4 |
async def submit_request(pool_handle: int,
request_json: str) -> str:
"""
Publishes request message to validator pool (no signing, unlike sign_and_submit_request).
The request is sent to the validator pool as is. It's assumed that it's already prepared.
:param pool_handle: pool... | [
"async",
"def",
"submit_request",
"(",
"pool_handle",
":",
"int",
",",
"request_json",
":",
"str",
")",
"->",
"str",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"submit_request: >>> pool_handle: %r, reque... | 38.612903 | 19.967742 |
def check(self, line_info):
"Instances of IPyAutocall in user_ns get autocalled immediately"
obj = self.shell.user_ns.get(line_info.ifun, None)
if isinstance(obj, IPyAutocall):
obj.set_ip(self.shell)
return self.prefilter_manager.get_handler_by_name('auto')
else:
... | [
"def",
"check",
"(",
"self",
",",
"line_info",
")",
":",
"obj",
"=",
"self",
".",
"shell",
".",
"user_ns",
".",
"get",
"(",
"line_info",
".",
"ifun",
",",
"None",
")",
"if",
"isinstance",
"(",
"obj",
",",
"IPyAutocall",
")",
":",
"obj",
".",
"set_i... | 42 | 17.75 |
def video_list(request, slug):
"""
Displays list of videos for given event.
"""
event = get_object_or_404(Event, slug=slug)
return render(request, 'video/video_list.html', {
'event': event,
'video_list': event.eventvideo_set.all()
}) | [
"def",
"video_list",
"(",
"request",
",",
"slug",
")",
":",
"event",
"=",
"get_object_or_404",
"(",
"Event",
",",
"slug",
"=",
"slug",
")",
"return",
"render",
"(",
"request",
",",
"'video/video_list.html'",
",",
"{",
"'event'",
":",
"event",
",",
"'video_... | 29.444444 | 10.333333 |
def replace_requirements(self, infilename, outfile_initial=None):
"""
Recursively replaces the requirements in the files with the content of the requirements.
Returns final temporary file opened for reading.
"""
infile = open(infilename, 'r')
# extract the requirements ... | [
"def",
"replace_requirements",
"(",
"self",
",",
"infilename",
",",
"outfile_initial",
"=",
"None",
")",
":",
"infile",
"=",
"open",
"(",
"infilename",
",",
"'r'",
")",
"# extract the requirements for this file that were not skipped from the global database",
"_indexes",
... | 35.909091 | 25.409091 |
def get_dG_at_T(seq, temp):
"""Predict dG at temperature T, using best predictions from Dill or Oobatake methods.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
temp (float): Temperature in degrees C
Returns:
(tuple): tuple containing:
dG (float) Free energy of u... | [
"def",
"get_dG_at_T",
"(",
"seq",
",",
"temp",
")",
":",
"# R (molar gas constant) in calories",
"r_cal",
"=",
"scipy",
".",
"constants",
".",
"R",
"/",
"scipy",
".",
"constants",
".",
"calorie",
"seq",
"=",
"ssbio",
".",
"protein",
".",
"sequence",
".",
"... | 29.289474 | 20.973684 |
def _windows_resolve(command):
"""
Try and find the full path and file extension of the executable to run.
This is so that e.g. calls to 'somescript' will point at 'somescript.cmd'
without the need to set shell=True in the subprocess.
If the executable contains periods it is a special case. Here the... | [
"def",
"_windows_resolve",
"(",
"command",
")",
":",
"try",
":",
"import",
"win32api",
"except",
"ImportError",
":",
"if",
"(",
"2",
",",
"8",
")",
"<",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"5",
")",
":",
"logger",
".",
"info",
"(",
"\"R... | 42.127273 | 24.6 |
def generate_lifetime_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to make a lifetime report."""
parser = subparsers.add_parser(
'lifetime', description=constants.LIFETIME_DESCRIPTION,
epilog=constants.LIFETIME_EPILOG, formatter_class=ParagraphFormatter,
help=const... | [
"def",
"generate_lifetime_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'lifetime'",
",",
"description",
"=",
"constants",
".",
"LIFETIME_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"LIFETIME_EPILOG",
",",
"... | 51.5625 | 10.8125 |
def receivenum_get(self, service_staff_id, start_date, end_date, session):
'''taobao.wangwang.eservice.receivenum.get 客服接待数
根据操作者ID,返回被查者ID指定时间段内每个帐号的"已接待人数" 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"已接待人数"。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"已接待人数"。
- 3、如果操作者是主账户,他可以查询所有子... | [
"def",
"receivenum_get",
"(",
"self",
",",
"service_staff_id",
",",
"start_date",
",",
"end_date",
",",
"session",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.wangwang.eservice.receivenum.get'",
")",
"request",
"[",
"'service_staff_id'",
"]",
"=",
"service... | 43.7 | 14.1 |
def data(tgt):
'''
Return True if the minion matches the given data target
CLI Example:
.. code-block:: bash
salt '*' match.data 'spam:eggs'
'''
matchers = salt.loader.matchers(__opts__)
try:
return matchers['data_match.match'](tgt, opts=__opts__)
except Exception as e... | [
"def",
"data",
"(",
"tgt",
")",
":",
"matchers",
"=",
"salt",
".",
"loader",
".",
"matchers",
"(",
"__opts__",
")",
"try",
":",
"return",
"matchers",
"[",
"'data_match.match'",
"]",
"(",
"tgt",
",",
"opts",
"=",
"__opts__",
")",
"except",
"Exception",
... | 22.25 | 23.625 |
def get_html_content(self):
"""
Parses the element and subelements and parses any HTML enabled text to
its original HTML form for rendering.
:returns: Parsed HTML enabled text content.
:rtype: str
"""
# Extract full element node content (including subelements)
... | [
"def",
"get_html_content",
"(",
"self",
")",
":",
"# Extract full element node content (including subelements)",
"html_content",
"=",
"''",
"if",
"hasattr",
"(",
"self",
",",
"'xml_element'",
")",
":",
"xml",
"=",
"self",
".",
"xml_element",
"content_list",
"=",
"["... | 34.5625 | 20.5625 |
def to_dict(self) -> Dict[str, Any]:
"""
Creates a dictionary-based description of this exception, ready to be
serialised as JSON or YAML.
"""
jsn = {
'kind': self.__class__.__name__,
'message': self.message
} # type: Dict[str, Any]
data = ... | [
"def",
"to_dict",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"jsn",
"=",
"{",
"'kind'",
":",
"self",
".",
"__class__",
".",
"__name__",
",",
"'message'",
":",
"self",
".",
"message",
"}",
"# type: Dict[str, Any]",
"data",
"=",
... | 29.428571 | 12.285714 |
def knearest(self, f_or_start, end=None, chrom=None, k=1):
"""return the n nearest neighbors to the given feature
f: a Feature object
k: the number of features to return
"""
if end is not None:
f = Feature(f_or_start, end, chrom=chrom)
else:
f = ... | [
"def",
"knearest",
"(",
"self",
",",
"f_or_start",
",",
"end",
"=",
"None",
",",
"chrom",
"=",
"None",
",",
"k",
"=",
"1",
")",
":",
"if",
"end",
"is",
"not",
"None",
":",
"f",
"=",
"Feature",
"(",
"f_or_start",
",",
"end",
",",
"chrom",
"=",
"... | 32.166667 | 19.625 |
def get_auditpol_dump():
'''
Gets the contents of an auditpol /backup. Used by the LGPO module to get
fieldnames and GUIDs for Advanced Audit policies.
Returns:
list: A list of lines form the backup file
Usage:
.. code-block:: python
import salt.utils.win_lgpo_auditpol
... | [
"def",
"get_auditpol_dump",
"(",
")",
":",
"# Just get a temporary file name",
"# NamedTemporaryFile will delete the file it creates by default on Windows",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.csv'",
")",
"as",
"tmp_file",
":",
"csv_file",
"=... | 27.923077 | 24.461538 |
def ctor_overridable(cls):
"""Return true if cls has on overridable __init__."""
prev_init = getattr(cls, "__init__", None)
if not callable(prev_init):
return True
if prev_init in [object.__init__, _auto_init]:
return True
if getattr(prev_init, '_clobber_ok', False):
return T... | [
"def",
"ctor_overridable",
"(",
"cls",
")",
":",
"prev_init",
"=",
"getattr",
"(",
"cls",
",",
"\"__init__\"",
",",
"None",
")",
"if",
"not",
"callable",
"(",
"prev_init",
")",
":",
"return",
"True",
"if",
"prev_init",
"in",
"[",
"object",
".",
"__init__... | 33.5 | 17.083333 |
def parse_messages(raw_json):
"""Parse a Telegram JSON messages list.
The method parses the JSON stream and returns an iterator of
dictionaries. Each one of this, contains a Telegram message.
:param raw_json: JSON string to parse
:returns: a generator of parsed messages
... | [
"def",
"parse_messages",
"(",
"raw_json",
")",
":",
"result",
"=",
"json",
".",
"loads",
"(",
"raw_json",
")",
"messages",
"=",
"result",
"[",
"'result'",
"]",
"for",
"msg",
"in",
"messages",
":",
"yield",
"msg"
] | 29.133333 | 18.6 |
def open(self):
"""
Open a connection to an IOS-XR device.
Connects to the device using SSH and drops into XML mode.
"""
try:
self.device = ConnectHandler(device_type='cisco_xr',
ip=self.hostname,
... | [
"def",
"open",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"device",
"=",
"ConnectHandler",
"(",
"device_type",
"=",
"'cisco_xr'",
",",
"ip",
"=",
"self",
".",
"hostname",
",",
"port",
"=",
"self",
".",
"port",
",",
"username",
"=",
"self",
".",
... | 42.818182 | 18.454545 |
def descriptor(obj, path=''):
"""Return descriptor of given object.
If ``path`` is specified, only the content on that path is
returned.
"""
if isinstance(obj, dict):
# Current object is hydrated, so we need to get descriptor from
# dict representation.
desc = obj['__descrip... | [
"def",
"descriptor",
"(",
"obj",
",",
"path",
"=",
"''",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"# Current object is hydrated, so we need to get descriptor from",
"# dict representation.",
"desc",
"=",
"obj",
"[",
"'__descriptor'",
"]",
"... | 25.631579 | 19.947368 |
def __run(self):
"""
The main loop
"""
already_cleaned = False
try:
while not self._done_event.is_set():
try:
# Wait for an action (blocking)
task = self._queue.get(True, self._timeout)
if tas... | [
"def",
"__run",
"(",
"self",
")",
":",
"already_cleaned",
"=",
"False",
"try",
":",
"while",
"not",
"self",
".",
"_done_event",
".",
"is_set",
"(",
")",
":",
"try",
":",
"# Wait for an action (blocking)",
"task",
"=",
"self",
".",
"_queue",
".",
"get",
"... | 39.5 | 15.530303 |
def load_data(data_file, key_name = None, local_file = False, format = 'json'):
"""
Load a JSON data file
:param data_file:
:param key_name:
:param local_file:
:return:
"""
if local_file:
if data_file.startswith('/'):
src_file = data_file
else:
sr... | [
"def",
"load_data",
"(",
"data_file",
",",
"key_name",
"=",
"None",
",",
"local_file",
"=",
"False",
",",
"format",
"=",
"'json'",
")",
":",
"if",
"local_file",
":",
"if",
"data_file",
".",
"startswith",
"(",
"'/'",
")",
":",
"src_file",
"=",
"data_file"... | 32.969697 | 19.69697 |
def collstats(self, scale=1024, verbose=False):
"""
Run collection stats for collection.
see https://docs.mongodb.com/manual/reference/command/collStats/
:param scale: Scale at which to report sizes
:param verbose: used for extended report on legacy MMAPV1 storage engine
... | [
"def",
"collstats",
"(",
"self",
",",
"scale",
"=",
"1024",
",",
"verbose",
"=",
"False",
")",
":",
"self",
".",
"print_doc",
"(",
"self",
".",
"database",
".",
"command",
"(",
"{",
"\"collStats\"",
":",
"self",
".",
"_collection_name",
",",
"\"scale\"",... | 42.769231 | 14 |
def get_stack_info(frames, transformer=transform, capture_locals=True,
frame_allowance=25):
"""
Given a list of frames, returns a list of stack information
dictionary objects that are JSON-ready.
We have to be careful here as certain implementations of the
_Frame class do not con... | [
"def",
"get_stack_info",
"(",
"frames",
",",
"transformer",
"=",
"transform",
",",
"capture_locals",
"=",
"True",
",",
"frame_allowance",
"=",
"25",
")",
":",
"__traceback_hide__",
"=",
"True",
"# NOQA",
"result",
"=",
"[",
"]",
"for",
"frame_info",
"in",
"f... | 31.395349 | 19.372093 |
def complete(self):
""" Return True if the limit has been reached """
if self.scan_limit is not None and self.scan_limit == 0:
return True
if self.item_limit is not None and self.item_limit == 0:
return True
return False | [
"def",
"complete",
"(",
"self",
")",
":",
"if",
"self",
".",
"scan_limit",
"is",
"not",
"None",
"and",
"self",
".",
"scan_limit",
"==",
"0",
":",
"return",
"True",
"if",
"self",
".",
"item_limit",
"is",
"not",
"None",
"and",
"self",
".",
"item_limit",
... | 38.571429 | 17.571429 |
def check(a, b, digits):
"""
Check input ranges, convert them to vector form,
and get a fixed precision integer version of them.
Parameters
--------------
a : (2, ) or (2, n) float
Start and end of a 1D interval
b : (2, ) or (2, n) float
Start and end of a 1D interval
digits... | [
"def",
"check",
"(",
"a",
",",
"b",
",",
"digits",
")",
":",
"a",
"=",
"np",
".",
"array",
"(",
"a",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"b",
"=",
"np",
".",
"array",
"(",
"b",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"if",
... | 25.816327 | 16.836735 |
def icasa(taskname, mult=None, clearstart=False, loadthese=[],**kw0):
"""
runs a CASA task given a list of options.
A given task can be run multiple times with a different options,
in this case the options must be parsed as a list/tuple of dictionaries via mult, e.g
icasa('exportfits',mul... | [
"def",
"icasa",
"(",
"taskname",
",",
"mult",
"=",
"None",
",",
"clearstart",
"=",
"False",
",",
"loadthese",
"=",
"[",
"]",
",",
"*",
"*",
"kw0",
")",
":",
"# create temp directory from which to run casapy",
"td",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"di... | 33.652174 | 21.507246 |
def floor(self):
"""Round `x` and `y` down to integers."""
return Point(int(math.floor(self.x)), int(math.floor(self.y))) | [
"def",
"floor",
"(",
"self",
")",
":",
"return",
"Point",
"(",
"int",
"(",
"math",
".",
"floor",
"(",
"self",
".",
"x",
")",
")",
",",
"int",
"(",
"math",
".",
"floor",
"(",
"self",
".",
"y",
")",
")",
")"
] | 42.333333 | 16.666667 |
def get_args():
"""
Get the command line arguments. use --help to get info on cmd line
arguments
"""
prog = "sendIndications"
usage = '%(prog)s [options] listener-url'
desc = 'Send indications to a listener. Verify set to False'
epilog = """
Examples:
%s https://127.0.0.1 -p 5... | [
"def",
"get_args",
"(",
")",
":",
"prog",
"=",
"\"sendIndications\"",
"usage",
"=",
"'%(prog)s [options] listener-url'",
"desc",
"=",
"'Send indications to a listener. Verify set to False'",
"epilog",
"=",
"\"\"\"\nExamples:\n %s https://127.0.0.1 -p 5001\n %s http://localhost:5000... | 37.618421 | 20.065789 |
def link_to_storage(self, sensor_log):
"""Attach this DataStreamer to an underlying SensorLog.
Calling this method is required if you want to use this DataStreamer
to generate reports from the underlying data in the SensorLog.
You can call it multiple times and it will unlink itself fr... | [
"def",
"link_to_storage",
"(",
"self",
",",
"sensor_log",
")",
":",
"if",
"self",
".",
"walker",
"is",
"not",
"None",
":",
"self",
".",
"_sensor_log",
".",
"destroy_walker",
"(",
"self",
".",
"walker",
")",
"self",
".",
"walker",
"=",
"None",
"self",
"... | 37.6 | 22.9 |
def _populate_worksheet(self, workbook, worksheet):
"""
Write the chart data contents to *worksheet* in category chart
layout. Write categories starting in the first column starting in
the second row, and proceeding one column per category level (for
charts having multi-level cat... | [
"def",
"_populate_worksheet",
"(",
"self",
",",
"workbook",
",",
"worksheet",
")",
":",
"self",
".",
"_write_categories",
"(",
"workbook",
",",
"worksheet",
")",
"self",
".",
"_write_series",
"(",
"workbook",
",",
"worksheet",
")"
] | 50.363636 | 18.727273 |
def _encode_mapping(name, value, check_keys, opts):
"""Encode a mapping type."""
data = b"".join([_element_to_bson(key, val, check_keys, opts)
for key, val in iteritems(value)])
return b"\x03" + name + _PACK_INT(len(data) + 5) + data + b"\x00" | [
"def",
"_encode_mapping",
"(",
"name",
",",
"value",
",",
"check_keys",
",",
"opts",
")",
":",
"data",
"=",
"b\"\"",
".",
"join",
"(",
"[",
"_element_to_bson",
"(",
"key",
",",
"val",
",",
"check_keys",
",",
"opts",
")",
"for",
"key",
",",
"val",
"in... | 54.4 | 16 |
def _set_tm_state(self, v, load=False):
"""
Setter method for tm_state, mapped from YANG variable /tm_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_tm_state is considered as a private
method. Backends looking to populate this variable should
d... | [
"def",
"_set_tm_state",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base"... | 70.291667 | 33.375 |
def get_current_version_by_config_file() -> str:
"""
Get current version from the version variable defined in the configuration
:return: A string with the current version number
:raises ImproperConfigurationError: if version variable cannot be parsed
"""
debug('get_current_version_by_config_fil... | [
"def",
"get_current_version_by_config_file",
"(",
")",
"->",
"str",
":",
"debug",
"(",
"'get_current_version_by_config_file'",
")",
"filename",
",",
"variable",
"=",
"config",
".",
"get",
"(",
"'semantic_release'",
",",
"'version_variable'",
")",
".",
"split",
"(",
... | 35.909091 | 16.545455 |
def past_active_subjunctive(self):
"""
Strong verbs
I
>>> verb = StrongOldNorseVerb()
>>> verb.set_canonic_forms(["líta", "lítr", "leit", "litu", "litinn"])
>>> verb.past_active_subjunctive()
['lita', 'litir', 'liti', 'litim', 'litið', 'liti']
II
... | [
"def",
"past_active_subjunctive",
"(",
"self",
")",
":",
"forms",
"=",
"[",
"]",
"subjunctive_root",
"=",
"apply_i_umlaut",
"(",
"self",
".",
"sfg3ft",
"[",
":",
"-",
"1",
"]",
")",
"if",
"subjunctive_root",
"[",
"-",
"1",
"]",
"in",
"[",
"'g'",
",",
... | 35.936508 | 20.222222 |
def pop_context(self):
"""Pops the last set of keyword arguments provided to the processor."""
processor = getattr(self, 'processor', None)
if processor is not None:
pop_context = getattr(processor, 'pop_context', None)
if pop_context is None:
pop_context ... | [
"def",
"pop_context",
"(",
"self",
")",
":",
"processor",
"=",
"getattr",
"(",
"self",
",",
"'processor'",
",",
"None",
")",
"if",
"processor",
"is",
"not",
"None",
":",
"pop_context",
"=",
"getattr",
"(",
"processor",
",",
"'pop_context'",
",",
"None",
... | 43.818182 | 10.272727 |
def set_marker_color(self, color='#3ea0e4', edgecolor='k'):
""" set the marker color used in the plot
:param color: matplotlib color (ie 'r', '#000000')
"""
# TODO allow a colour set per another variable
self._marker_color = color
self._edge_color = edgecolor | [
"def",
"set_marker_color",
"(",
"self",
",",
"color",
"=",
"'#3ea0e4'",
",",
"edgecolor",
"=",
"'k'",
")",
":",
"# TODO allow a colour set per another variable",
"self",
".",
"_marker_color",
"=",
"color",
"self",
".",
"_edge_color",
"=",
"edgecolor"
] | 43 | 8.714286 |
def create_image(self, instance_id, name,
description=None, no_reboot=False):
"""
Will create an AMI from the instance in the running or stopped
state.
:type instance_id: string
:param instance_id: the ID of the instance to image.
:type name: string... | [
"def",
"create_image",
"(",
"self",
",",
"instance_id",
",",
"name",
",",
"description",
"=",
"None",
",",
"no_reboot",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'InstanceId'",
":",
"instance_id",
",",
"'Name'",
":",
"name",
"}",
"if",
"description",
... | 37.588235 | 20.117647 |
def restore(self):
'Restore the file'
#
#
# As of 2016-06-15, Jottacloud.com has changed their restore api
# To restore, this is what's done
#
# HTTP POST to https://www.jottacloud.com/web/restore/trash/list
# Data:
# hash:undefined
# ... | [
"def",
"restore",
"(",
"self",
")",
":",
"#",
"#",
"# As of 2016-06-15, Jottacloud.com has changed their restore api",
"# To restore, this is what's done",
"#",
"# HTTP POST to https://www.jottacloud.com/web/restore/trash/list",
"# Data:",
"# hash:undefined",
"# files:@0025d37be5... | 44 | 26.72 |
def generate_password_hash(password, digestmod='sha256', salt_length=8):
""" Hash a password with given method and salt length. """
salt = ''.join(random.sample(SALT_CHARS, salt_length))
signature = create_signature(salt, password, digestmod=digestmod)
return '$'.join((digestmod, salt, signature)) | [
"def",
"generate_password_hash",
"(",
"password",
",",
"digestmod",
"=",
"'sha256'",
",",
"salt_length",
"=",
"8",
")",
":",
"salt",
"=",
"''",
".",
"join",
"(",
"random",
".",
"sample",
"(",
"SALT_CHARS",
",",
"salt_length",
")",
")",
"signature",
"=",
... | 51.666667 | 21.333333 |
def AddRoute(self, short_name, long_name, route_type, route_id=None):
"""Add a route to this schedule.
Args:
short_name: Short name of the route, such as "71L"
long_name: Full name of the route, such as "NW 21st Ave/St Helens Rd"
route_type: A type such as "Tram", "Subway" or "Bus"
rout... | [
"def",
"AddRoute",
"(",
"self",
",",
"short_name",
",",
"long_name",
",",
"route_type",
",",
"route_id",
"=",
"None",
")",
":",
"if",
"route_id",
"is",
"None",
":",
"route_id",
"=",
"util",
".",
"FindUniqueId",
"(",
"self",
".",
"routes",
")",
"route",
... | 41.055556 | 21.444444 |
def get_base_indentation(code, include_start=False):
"""Heuristically extracts the base indentation from the provided code.
Finds the smallest indentation following a newline not at the end of the
string.
"""
new_line_indentation = re_new_line_indentation[include_start].finditer(code)
new_line_... | [
"def",
"get_base_indentation",
"(",
"code",
",",
"include_start",
"=",
"False",
")",
":",
"new_line_indentation",
"=",
"re_new_line_indentation",
"[",
"include_start",
"]",
".",
"finditer",
"(",
"code",
")",
"new_line_indentation",
"=",
"tuple",
"(",
"m",
".",
"... | 40.083333 | 22.5 |
def plot_wigner3d(iradon_output, bin_centres, bin_centre_units="", cmap=_cm.cubehelix_r, view=(10, -45), figsize=(10, 10)):
"""
Plots the wigner space representation as a 3D surface plot.
Parameters
----------
iradon_output : ndarray
2d array of size (histbins x histbins)
bin_centres : ... | [
"def",
"plot_wigner3d",
"(",
"iradon_output",
",",
"bin_centres",
",",
"bin_centre_units",
"=",
"\"\"",
",",
"cmap",
"=",
"_cm",
".",
"cubehelix_r",
",",
"view",
"=",
"(",
"10",
",",
"-",
"45",
")",
",",
"figsize",
"=",
"(",
"10",
",",
"10",
")",
")"... | 32.229508 | 19.508197 |
def discardi(self, begin, end, data=None):
"""
Shortcut for discard(Interval(begin, end, data)).
Completes in O(log n) time.
"""
return self.discard(Interval(begin, end, data)) | [
"def",
"discardi",
"(",
"self",
",",
"begin",
",",
"end",
",",
"data",
"=",
"None",
")",
":",
"return",
"self",
".",
"discard",
"(",
"Interval",
"(",
"begin",
",",
"end",
",",
"data",
")",
")"
] | 30.142857 | 11.285714 |
def _get_nets_lacnic(self, *args, **kwargs):
"""
Deprecated. This will be removed in a future release.
"""
from warnings import warn
warn('Whois._get_nets_lacnic() has been deprecated and will be '
'removed. You should now use Whois.get_nets_lacnic().')
retu... | [
"def",
"_get_nets_lacnic",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"'Whois._get_nets_lacnic() has been deprecated and will be '",
"'removed. You should now use Whois.get_nets_lacnic().'",
")",
"r... | 39.111111 | 16 |
def same_player(self, other):
"""
Compares name and color.
Returns True if both are owned by the same player.
"""
return self.name == other.name \
and self.color == other.color | [
"def",
"same_player",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"name",
"==",
"other",
".",
"name",
"and",
"self",
".",
"color",
"==",
"other",
".",
"color"
] | 31.714286 | 5.428571 |
def remove_service(service=str):
'''
Remove Swarm Service
service
The name of the service
CLI Example:
.. code-block:: bash
salt '*' swarm.remove_service service=Test_Service
'''
try:
salt_return = {}
client = docker.APIClient(base_url='unix://var/run/dock... | [
"def",
"remove_service",
"(",
"service",
"=",
"str",
")",
":",
"try",
":",
"salt_return",
"=",
"{",
"}",
"client",
"=",
"docker",
".",
"APIClient",
"(",
"base_url",
"=",
"'unix://var/run/docker.sock'",
")",
"service",
"=",
"client",
".",
"remove_service",
"(... | 26.826087 | 24.130435 |
def load_partition_data(self, index):
"""
Load and return the partition with the given index.
Args:
index (int): The index of partition, that refers to the index in ``self.partitions``.
Returns:
PartitionData: A PartitionData object containing the data for the p... | [
"def",
"load_partition_data",
"(",
"self",
",",
"index",
")",
":",
"info",
"=",
"self",
".",
"partitions",
"[",
"index",
"]",
"data",
"=",
"PartitionData",
"(",
"info",
")",
"for",
"utt_id",
"in",
"info",
".",
"utt_ids",
":",
"utt_data",
"=",
"[",
"c",... | 30.947368 | 24.421053 |
def push_resource_cache(resourceid, info):
"""
Cache resource specific information
:param resourceid: Resource id as string
:param info: Dict to push
:return: Nothing
"""
if not resourceid:
raise ResourceInitError("Resource id missing")
if not... | [
"def",
"push_resource_cache",
"(",
"resourceid",
",",
"info",
")",
":",
"if",
"not",
"resourceid",
":",
"raise",
"ResourceInitError",
"(",
"\"Resource id missing\"",
")",
"if",
"not",
"DutInformationList",
".",
"_cache",
".",
"get",
"(",
"resourceid",
")",
":",
... | 39.153846 | 15.461538 |
def status(self):
"""
The current status of the event (started, finished or pending).
"""
myNow = timezone.localtime(timezone=self.tz)
daysDelta = dt.timedelta(days=self.num_days - 1)
# NB: postponements can be created after the until date
# so ignore that
... | [
"def",
"status",
"(",
"self",
")",
":",
"myNow",
"=",
"timezone",
".",
"localtime",
"(",
"timezone",
"=",
"self",
".",
"tz",
")",
"daysDelta",
"=",
"dt",
".",
"timedelta",
"(",
"days",
"=",
"self",
".",
"num_days",
"-",
"1",
")",
"# NB: postponements c... | 46.5 | 16.666667 |
def _get_transformation_history(path):
"""
Checks for a transformations.json* file and returns the history.
"""
trans_json = glob.glob(os.path.join(path, "transformations.json*"))
if trans_json:
try:
with zopen(trans_json[0]) as f:
return json.load(f)["history"]
... | [
"def",
"_get_transformation_history",
"(",
"path",
")",
":",
"trans_json",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"transformations.json*\"",
")",
")",
"if",
"trans_json",
":",
"try",
":",
"with",
"zopen",
"(",
... | 30.25 | 15.583333 |
def scale_and_center(mol):
"""Center and Scale molecule 2D coordinates.
This method changes mol coordinates directly to center but not scale.
This method returns width, height and MLB(median length of bond)
and scaling will be done by drawer method with these values.
Returns:
width: float
... | [
"def",
"scale_and_center",
"(",
"mol",
")",
":",
"cnt",
"=",
"mol",
".",
"atom_count",
"(",
")",
"if",
"cnt",
"<",
"2",
":",
"mol",
".",
"size2d",
"=",
"(",
"0",
",",
"0",
",",
"1",
")",
"mol",
".",
"descriptors",
".",
"add",
"(",
"\"ScaleAndCent... | 33.136364 | 15.931818 |
def _init_codebook(self):
"""Internal function to set the codebook or to indicate it to the C++
code that it should be randomly initialized.
"""
codebook_size = self._n_columns * self._n_rows * self.n_dim
if self.codebook is None:
if self._initialization == "random":
... | [
"def",
"_init_codebook",
"(",
"self",
")",
":",
"codebook_size",
"=",
"self",
".",
"_n_columns",
"*",
"self",
".",
"_n_rows",
"*",
"self",
".",
"n_dim",
"if",
"self",
".",
"codebook",
"is",
"None",
":",
"if",
"self",
".",
"_initialization",
"==",
"\"rand... | 46.105263 | 14.315789 |
def http_sa_http_server_shutdown(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
http_sa = ET.SubElement(config, "http-sa", xmlns="urn:brocade.com:mgmt:brocade-http")
http = ET.SubElement(http_sa, "http")
server = ET.SubElement(http, "server")
... | [
"def",
"http_sa_http_server_shutdown",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"http_sa",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"http-sa\"",
",",
"xmlns",
"=",
"\"urn:brocad... | 41 | 14 |
def circuit_to_latex(circ: Circuit,
qubits: Qubits = None,
document: bool = True) -> str:
"""
Create an image of a quantum circuit in LaTeX.
Can currently draw X, Y, Z, H, T, S, T_H, S_H, RX, RY, RZ, TX, TY, TZ,
TH, CNOT, CZ, SWAP, ISWAP, CCNOT, CSWAP, XX, YY, ... | [
"def",
"circuit_to_latex",
"(",
"circ",
":",
"Circuit",
",",
"qubits",
":",
"Qubits",
"=",
"None",
",",
"document",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"if",
"qubits",
"is",
"None",
":",
"qubits",
"=",
"circ",
".",
"qubits",
"N",
"=",
... | 40.1 | 15.982353 |
def _set_offline_if(self, v, load=False):
"""
Setter method for offline_if, mapped from YANG variable /rbridge_id/snmp_server/offline_if (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_offline_if is considered as a private
method. Backends looking to popu... | [
"def",
"_set_offline_if",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | 90.318182 | 42.454545 |
def isasteroid(self):
"""`True` if `targetname` appears to be an asteroid."""
if self.asteroid is not None:
return self.asteroid
elif self.comet is not None:
return not self.comet
else:
return any(self.parse_asteroid()) is not None | [
"def",
"isasteroid",
"(",
"self",
")",
":",
"if",
"self",
".",
"asteroid",
"is",
"not",
"None",
":",
"return",
"self",
".",
"asteroid",
"elif",
"self",
".",
"comet",
"is",
"not",
"None",
":",
"return",
"not",
"self",
".",
"comet",
"else",
":",
"retur... | 36.5 | 10.625 |
def count(self, sqlTail = '') :
"Compile filters and counts the number of results. You can use sqlTail to add things such as order by"
sql, sqlValues = self.getSQLQuery(count = True)
return int(self.con.execute('%s %s'% (sql, sqlTail), sqlValues).fetchone()[0]) | [
"def",
"count",
"(",
"self",
",",
"sqlTail",
"=",
"''",
")",
":",
"sql",
",",
"sqlValues",
"=",
"self",
".",
"getSQLQuery",
"(",
"count",
"=",
"True",
")",
"return",
"int",
"(",
"self",
".",
"con",
".",
"execute",
"(",
"'%s %s'",
"%",
"(",
"sql",
... | 66 | 30.5 |
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
... | [
"def",
"modify_node",
"(",
"hostname",
",",
"username",
",",
"password",
",",
"name",
",",
"connection_limit",
"=",
"None",
",",
"description",
"=",
"None",
",",
"dynamic_ratio",
"=",
"None",
",",
"logging",
"=",
"None",
",",
"monitor",
"=",
"None",
",",
... | 25.525641 | 20.192308 |
def _update_centers(X, membs, n_clusters):
""" Update Cluster Centers:
calculate the mean of feature vectors for each cluster
"""
centers = np.empty(shape=(n_clusters, X.shape[1]), dtype=float)
sse = np.empty(shape=n_clusters, dtype=float)
for clust_id in range(n_clusters):
memb_i... | [
"def",
"_update_centers",
"(",
"X",
",",
"membs",
",",
"n_clusters",
")",
":",
"centers",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"(",
"n_clusters",
",",
"X",
".",
"shape",
"[",
"1",
"]",
")",
",",
"dtype",
"=",
"float",
")",
"sse",
"=",
"np"... | 41.875 | 16.5 |
def upload_ssh_key(host, username, password, ssh_key=None, ssh_key_file=None,
protocol=None, port=None, certificate_verify=False):
'''
Upload an ssh key for root to an ESXi host via http PUT.
This function only works for ESXi, not vCenter.
Only one ssh key can be uploaded for root. U... | [
"def",
"upload_ssh_key",
"(",
"host",
",",
"username",
",",
"password",
",",
"ssh_key",
"=",
"None",
",",
"ssh_key_file",
"=",
"None",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"certificate_verify",
"=",
"False",
")",
":",
"if",
"proto... | 42.84058 | 22.927536 |
def freebayes(in_file, ref_file, vrn_files, data):
"""FreeBayes filters: cutoff-based soft filtering.
"""
out_file = _freebayes_cutoff(in_file, data)
#out_file = _freebayes_custom(in_file, ref_file, data)
return out_file | [
"def",
"freebayes",
"(",
"in_file",
",",
"ref_file",
",",
"vrn_files",
",",
"data",
")",
":",
"out_file",
"=",
"_freebayes_cutoff",
"(",
"in_file",
",",
"data",
")",
"#out_file = _freebayes_custom(in_file, ref_file, data)",
"return",
"out_file"
] | 39.166667 | 9.333333 |
def addEntry(self, key='', value=''):
"""
Creates a new entry item for this widget.
:param key | <str>
value | <variant>
"""
img = resources.find('img/close.png')
new_item = XTreeWidgetItem()
new_item.setText(1, nat... | [
"def",
"addEntry",
"(",
"self",
",",
"key",
"=",
"''",
",",
"value",
"=",
"''",
")",
":",
"img",
"=",
"resources",
".",
"find",
"(",
"'img/close.png'",
")",
"new_item",
"=",
"XTreeWidgetItem",
"(",
")",
"new_item",
".",
"setText",
"(",
"1",
",",
"nat... | 35.125 | 10.125 |
def operatorPrecedence(base, operators):
"""
This re-implements pyparsing's operatorPrecedence function.
It gets rid of a few annoying bugs, like always putting operators inside
a Group, and matching the whole grammar with Forward first (there may
actually be a reason for that, but I couldn't find ... | [
"def",
"operatorPrecedence",
"(",
"base",
",",
"operators",
")",
":",
"# The full expression, used to provide sub-expressions",
"expression",
"=",
"Forward",
"(",
")",
"# The initial expression",
"last",
"=",
"base",
"|",
"Suppress",
"(",
"'('",
")",
"+",
"expression"... | 37.949153 | 21.881356 |
def connect_to_database_odbc_sqlserver(self,
odbc_connection_string: str = None,
dsn: str = None,
database: str = None,
user: str = None,
... | [
"def",
"connect_to_database_odbc_sqlserver",
"(",
"self",
",",
"odbc_connection_string",
":",
"str",
"=",
"None",
",",
"dsn",
":",
"str",
"=",
"None",
",",
"database",
":",
"str",
"=",
"None",
",",
"user",
":",
"str",
"=",
"None",
",",
"password",
":",
"... | 60.6875 | 20.9375 |
def _ExecuteTransaction(self, transaction):
"""Get connection from pool and execute transaction."""
def Action(connection):
connection.cursor.execute("START TRANSACTION")
for query in transaction:
connection.cursor.execute(query["query"], query["args"])
connection.cursor.execute("COMM... | [
"def",
"_ExecuteTransaction",
"(",
"self",
",",
"transaction",
")",
":",
"def",
"Action",
"(",
"connection",
")",
":",
"connection",
".",
"cursor",
".",
"execute",
"(",
"\"START TRANSACTION\"",
")",
"for",
"query",
"in",
"transaction",
":",
"connection",
".",
... | 35.909091 | 13.272727 |
def file_or_token(value):
"""
If value is a file path and the file exists its contents are stripped and returned,
otherwise value is returned.
"""
if isfile(value):
with open(value) as fd:
return fd.read().strip()
if any(char in value for char in '/\\.'):
# This char... | [
"def",
"file_or_token",
"(",
"value",
")",
":",
"if",
"isfile",
"(",
"value",
")",
":",
"with",
"open",
"(",
"value",
")",
"as",
"fd",
":",
"return",
"fd",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"if",
"any",
"(",
"char",
"in",
"value",
... | 30.866667 | 18.333333 |
def connect(self):
""" Connects and logins to the server. """
self._ftp.connect()
self._ftp.login(user=self._username, passwd=self._passwd) | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"_ftp",
".",
"connect",
"(",
")",
"self",
".",
"_ftp",
".",
"login",
"(",
"user",
"=",
"self",
".",
"_username",
",",
"passwd",
"=",
"self",
".",
"_passwd",
")"
] | 40 | 15 |
def import_items(item_seq, dest_model, batch_len=500,
clear=False, dry_run=True,
start_batch=0, end_batch=None,
overwrite=True,
run_update=False, ignore_related=True,
ignore_errors=False, verbosity=1):
"""Import a sequence (que... | [
"def",
"import_items",
"(",
"item_seq",
",",
"dest_model",
",",
"batch_len",
"=",
"500",
",",
"clear",
"=",
"False",
",",
"dry_run",
"=",
"True",
",",
"start_batch",
"=",
"0",
",",
"end_batch",
"=",
"None",
",",
"overwrite",
"=",
"True",
",",
"run_update... | 43.389937 | 22.427673 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.