text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def walk(start, ofn, cyc=None):
""" Non recursive DFS to detect cycles
:param start: start vertex in graph
:param ofn: function to get the list of outgoing edges of a vertex
:param cyc: list of existing cycles, cycles are represented in a list started with minimum vertex.
:return: cycles
:rtype... | [
"def",
"walk",
"(",
"start",
",",
"ofn",
",",
"cyc",
"=",
"None",
")",
":",
"ctx",
",",
"stk",
"=",
"{",
"}",
",",
"[",
"start",
"]",
"cyc",
"=",
"[",
"]",
"if",
"cyc",
"==",
"None",
"else",
"cyc",
"while",
"len",
"(",
"stk",
")",
":",
"top... | 28.97619 | 17.380952 |
def pg_version(using=None):
"""
Return tuple with PostgreSQL version of a specific connection
:type using: str
:param using: Connection name
:rtype: tuple
:return: PostgreSQL version
"""
connection = get_connection(using)
cursor = connection.cursor()
cursor.execute('SHOW server_... | [
"def",
"pg_version",
"(",
"using",
"=",
"None",
")",
":",
"connection",
"=",
"get_connection",
"(",
"using",
")",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"'SHOW server_version'",
")",
"row",
"=",
"cursor",
".",
... | 26.533333 | 14.266667 |
def list_tables(self):
"""
Runs the ``\\dt`` command and returns a list of column values with
information about all tables in the database.
"""
lines = output_lines(self.exec_psql('\\dt'))
return [line.split('|') for line in lines] | [
"def",
"list_tables",
"(",
"self",
")",
":",
"lines",
"=",
"output_lines",
"(",
"self",
".",
"exec_psql",
"(",
"'\\\\dt'",
")",
")",
"return",
"[",
"line",
".",
"split",
"(",
"'|'",
")",
"for",
"line",
"in",
"lines",
"]"
] | 39 | 12.428571 |
def _factored_dims(self, shape):
"""Should we use a factored second moment estimator.
Based on the shape of the variable.
If we factor the accumulator, then this function returns a list of two
mtf.Dimensions to reduce over. We always pick the two largest dimensions.
If there are not two dimensions... | [
"def",
"_factored_dims",
"(",
"self",
",",
"shape",
")",
":",
"if",
"not",
"self",
".",
"_factored",
"or",
"shape",
".",
"ndims",
"<",
"2",
":",
"return",
"None",
"sorted_dims",
"=",
"sorted",
"(",
"shape",
".",
"dims",
",",
"key",
"=",
"lambda",
"d"... | 34.4 | 20.25 |
def _map(self, lat, long, zoom, tiles):
"""
Returns a map
"""
if tiles == "map":
tiles = "OpenStreetMap"
elif tiles == "terrain":
tiles = "Stamen Terrain"
elif tiles == "basic":
tiles = "Stamen Toner"
try:
xmap = fol... | [
"def",
"_map",
"(",
"self",
",",
"lat",
",",
"long",
",",
"zoom",
",",
"tiles",
")",
":",
"if",
"tiles",
"==",
"\"map\"",
":",
"tiles",
"=",
"\"OpenStreetMap\"",
"elif",
"tiles",
"==",
"\"terrain\"",
":",
"tiles",
"=",
"\"Stamen Terrain\"",
"elif",
"tile... | 28.052632 | 10.368421 |
def uninstall(pkg):
'''
Uninstall the specified package.
Args:
pkg (str): The package name.
Returns:
dict: The ``result`` and ``output``.
CLI Example:
.. code-block:: bash
salt '*' flatpak.uninstall org.gimp.GIMP
'''
ret = {'result': None, 'output': ''}
... | [
"def",
"uninstall",
"(",
"pkg",
")",
":",
"ret",
"=",
"{",
"'result'",
":",
"None",
",",
"'output'",
":",
"''",
"}",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"FLATPAK_BINARY_NAME",
"+",
"' uninstall '",
"+",
"pkg",
")",
"if",
"out",
"[",... | 20.857143 | 23.285714 |
def EmitSignal(self, interface, name, signature, args):
'''Emit a signal from the object.
interface: D-Bus interface to send the signal from. For convenience you
can specify '' here to add the method to the object's main
interface (as specified on construction).
... | [
"def",
"EmitSignal",
"(",
"self",
",",
"interface",
",",
"name",
",",
"signature",
",",
"args",
")",
":",
"if",
"not",
"interface",
":",
"interface",
"=",
"self",
".",
"interface",
"# convert types of arguments according to signature, using",
"# MethodCallMessage.appe... | 49.4375 | 25.5625 |
def checkSubstitute(self, typecode):
'''If this is True, allow typecode to be substituted
for "self" typecode.
'''
if not isinstance(typecode, ElementDeclaration):
return False
try:
nsuri,ncname = typecode.substitutionGroup
except (AttributeError... | [
"def",
"checkSubstitute",
"(",
"self",
",",
"typecode",
")",
":",
"if",
"not",
"isinstance",
"(",
"typecode",
",",
"ElementDeclaration",
")",
":",
"return",
"False",
"try",
":",
"nsuri",
",",
"ncname",
"=",
"typecode",
".",
"substitutionGroup",
"except",
"("... | 29.625 | 20.458333 |
def _send_update(self, data):
"""Send a NetworkTables update via the stored send_update callback"""
if isinstance(data, dict):
data = json.dumps(data)
self.update_callback(data) | [
"def",
"_send_update",
"(",
"self",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
"self",
".",
"update_callback",
"(",
"data",
")"
] | 41.8 | 5.6 |
def validate_program(self):
"""Rough check that the embedded program in the object is valid."""
terminals = [0]
for node in self.program:
if isinstance(node, _Function):
terminals.append(node.arity)
else:
terminals[-1] -= 1
... | [
"def",
"validate_program",
"(",
"self",
")",
":",
"terminals",
"=",
"[",
"0",
"]",
"for",
"node",
"in",
"self",
".",
"program",
":",
"if",
"isinstance",
"(",
"node",
",",
"_Function",
")",
":",
"terminals",
".",
"append",
"(",
"node",
".",
"arity",
"... | 36.833333 | 7.416667 |
def remove_content_history(self, page_id, version_number):
"""
Remove content history. It works as experimental method
:param page_id:
:param version_number: version number
:return:
"""
url = 'rest/experimental/content/{id}/version/{versionNumber}'.format(id=page_... | [
"def",
"remove_content_history",
"(",
"self",
",",
"page_id",
",",
"version_number",
")",
":",
"url",
"=",
"'rest/experimental/content/{id}/version/{versionNumber}'",
".",
"format",
"(",
"id",
"=",
"page_id",
",",
"versionNumber",
"=",
"version_number",
")",
"self",
... | 41.111111 | 20.222222 |
def to_pb(self):
"""Converts the :class:`TimestampRange` to a protobuf.
:rtype: :class:`.data_v2_pb2.TimestampRange`
:returns: The converted current object.
"""
timestamp_range_kwargs = {}
if self.start is not None:
timestamp_range_kwargs["start_timestamp_mic... | [
"def",
"to_pb",
"(",
"self",
")",
":",
"timestamp_range_kwargs",
"=",
"{",
"}",
"if",
"self",
".",
"start",
"is",
"not",
"None",
":",
"timestamp_range_kwargs",
"[",
"\"start_timestamp_micros\"",
"]",
"=",
"(",
"_microseconds_from_datetime",
"(",
"self",
".",
"... | 42.647059 | 16.470588 |
def close(self):
"""
Close the node process.
"""
if self._closed:
return False
log.info("{module}: '{name}' [{id}]: is closing".format(module=self.manager.module_name,
name=self.name,
... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"return",
"False",
"log",
".",
"info",
"(",
"\"{module}: '{name}' [{id}]: is closing\"",
".",
"format",
"(",
"module",
"=",
"self",
".",
"manager",
".",
"module_name",
",",
"name",
"... | 34.44 | 25.8 |
def xgroup_delconsumer(self, name, groupname, consumername):
"""
Remove a specific consumer from a consumer group.
Returns the number of pending messages that the consumer had before it
was deleted.
name: name of the stream.
groupname: name of the consumer group.
... | [
"def",
"xgroup_delconsumer",
"(",
"self",
",",
"name",
",",
"groupname",
",",
"consumername",
")",
":",
"return",
"self",
".",
"execute_command",
"(",
"'XGROUP DELCONSUMER'",
",",
"name",
",",
"groupname",
",",
"consumername",
")"
] | 44.272727 | 14.454545 |
def normalize(path_name, override=None):
"""
Prepares a path name to be worked with. Path name must not be empty. This
function will return the 'normpath'ed path and the identity of the path.
This function takes an optional overriding argument for the identity.
ONLY PROVIDE OVERRIDE IF:
1) ... | [
"def",
"normalize",
"(",
"path_name",
",",
"override",
"=",
"None",
")",
":",
"identity",
"=",
"identify",
"(",
"path_name",
",",
"override",
"=",
"override",
")",
"new_path_name",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"... | 39.066667 | 21.733333 |
def _logpdf(self, **kwargs):
"""Returns the log of the pdf at the given values. The keyword
arguments must contain all of parameters in self's params. Unrecognized
arguments are ignored.
"""
for p in self._params:
if p not in kwargs.keys():
raise Value... | [
"def",
"_logpdf",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"p",
"in",
"self",
".",
"_params",
":",
"if",
"p",
"not",
"in",
"kwargs",
".",
"keys",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Missing parameter {} to construct pdf.'",
".",
... | 40.1875 | 13.625 |
def _construct_post_data(self):
"""
Constructs the data structure that is required from the atlas API based
on measurements, sources and times user has specified.
"""
definitions = [msm.build_api_struct() for msm in self.measurements]
probes = [source.build_api_struct() f... | [
"def",
"_construct_post_data",
"(",
"self",
")",
":",
"definitions",
"=",
"[",
"msm",
".",
"build_api_struct",
"(",
")",
"for",
"msm",
"in",
"self",
".",
"measurements",
"]",
"probes",
"=",
"[",
"source",
".",
"build_api_struct",
"(",
")",
"for",
"source",... | 35.666667 | 20.777778 |
def make_composite_source(name, spectrum):
"""Construct and return a `fermipy.roi_model.CompositeSource` object
"""
data = dict(SpatialType='CompositeSource',
SpatialModel='CompositeSource',
SourceType='CompositeSource')
if spectrum is not None:
data.update(spectr... | [
"def",
"make_composite_source",
"(",
"name",
",",
"spectrum",
")",
":",
"data",
"=",
"dict",
"(",
"SpatialType",
"=",
"'CompositeSource'",
",",
"SpatialModel",
"=",
"'CompositeSource'",
",",
"SourceType",
"=",
"'CompositeSource'",
")",
"if",
"spectrum",
"is",
"n... | 40.444444 | 5.666667 |
def xpointerNewCollapsedRange(self):
"""Create a new xmlXPathObjectPtr of type range using a single
nodes """
ret = libxml2mod.xmlXPtrNewCollapsedRange(self._o)
if ret is None:raise treeError('xmlXPtrNewCollapsedRange() failed')
return xpathObjectRet(ret) | [
"def",
"xpointerNewCollapsedRange",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlXPtrNewCollapsedRange",
"(",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlXPtrNewCollapsedRange() failed'",
")",
"return",
"x... | 48.833333 | 10.5 |
def _reserved_symbols(self):
"""
Helper property for the build_remap_symbols method. This
property first resolves _all_ local references from parents,
skipping all locally declared symbols as the goal is to generate
a local mapping for them, but in a way not to shadow over any
... | [
"def",
"_reserved_symbols",
"(",
"self",
")",
":",
"# In practice, and as a possible optimisation, the parent's",
"# remapped symbols table can be merged into this instance, but",
"# this bloats memory use and cause unspecified reservations that",
"# may not be applicable this or any child scope. ... | 43.83871 | 20.806452 |
def register_functions(lib, ignore_errors):
"""Register function prototypes with a libclang library instance.
This must be called as part of library instantiation so Python knows how
to call out to the shared library.
"""
def register(item):
return register_function(lib, item, ignore_error... | [
"def",
"register_functions",
"(",
"lib",
",",
"ignore_errors",
")",
":",
"def",
"register",
"(",
"item",
")",
":",
"return",
"register_function",
"(",
"lib",
",",
"item",
",",
"ignore_errors",
")",
"for",
"f",
"in",
"functionList",
":",
"register",
"(",
"f... | 29.916667 | 19.25 |
def to_xdr_object(self):
"""Get an XDR object representation of this
:class:`TransactionEnvelope`.
"""
tx = self.tx.to_xdr_object()
return Xdr.types.TransactionEnvelope(tx, self.signatures) | [
"def",
"to_xdr_object",
"(",
"self",
")",
":",
"tx",
"=",
"self",
".",
"tx",
".",
"to_xdr_object",
"(",
")",
"return",
"Xdr",
".",
"types",
".",
"TransactionEnvelope",
"(",
"tx",
",",
"self",
".",
"signatures",
")"
] | 32 | 12.571429 |
def uninstall(self, auto_confirm=False):
"""
Uninstall the distribution currently satisfying this requirement.
Prompts before removing or modifying files unless
``auto_confirm`` is True.
Refuses to delete or modify files outside of ``sys.prefix`` -
thus uninstallation w... | [
"def",
"uninstall",
"(",
"self",
",",
"auto_confirm",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"check_if_exists",
"(",
")",
":",
"raise",
"UninstallationError",
"(",
"\"Cannot uninstall requirement %s, not installed\"",
"%",
"(",
"self",
".",
"name",
",... | 45.84252 | 19.259843 |
def _draw_rect(self, rect, painter):
"""
Draw the background rectangle using the current style primitive color
or foldIndicatorBackground if nativeFoldingIndicator is true.
:param rect: The fold zone rect to draw
:param painter: The widget's painter.
"""
c = sel... | [
"def",
"_draw_rect",
"(",
"self",
",",
"rect",
",",
"painter",
")",
":",
"c",
"=",
"self",
".",
"_custom_color",
"if",
"self",
".",
"_native",
":",
"c",
"=",
"self",
".",
"get_system_bck_color",
"(",
")",
"grad",
"=",
"QtGui",
".",
"QLinearGradient",
"... | 39.8 | 9 |
def template_ellipsoid(shape):
r"""
Returns an ellipsoid binary structure of a of the supplied radius that can be used as
template input to the generalized hough transform.
Parameters
----------
shape : tuple of integers
The main axes of the ellipsoid in voxel units.
Return... | [
"def",
"template_ellipsoid",
"(",
"shape",
")",
":",
"# prepare template array",
"template",
"=",
"numpy",
".",
"zeros",
"(",
"[",
"int",
"(",
"x",
"//",
"2",
"+",
"(",
"x",
"%",
"2",
")",
")",
"for",
"x",
"in",
"shape",
"]",
",",
"dtype",
"=",
"nu... | 52.723404 | 34.87234 |
def update_launch_config(self, scaling_group, server_name=None, image=None,
flavor=None, disk_config=None, metadata=None, personality=None,
networks=None, load_balancers=None, key_name=None, config_drive=False,
user_data=None):
"""
Updates the server launch configurat... | [
"def",
"update_launch_config",
"(",
"self",
",",
"scaling_group",
",",
"server_name",
"=",
"None",
",",
"image",
"=",
"None",
",",
"flavor",
"=",
"None",
",",
"disk_config",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"personality",
"=",
"None",
",",
... | 56.777778 | 25.777778 |
def get_username(self):
"""Get a username formatted for a specific token version."""
_from = self.auth_context['from']
if self.token_version == 1:
return '{0}'.format(_from)
elif self.token_version == 2:
_user_type = self.auth_context['user_type']
retu... | [
"def",
"get_username",
"(",
"self",
")",
":",
"_from",
"=",
"self",
".",
"auth_context",
"[",
"'from'",
"]",
"if",
"self",
".",
"token_version",
"==",
"1",
":",
"return",
"'{0}'",
".",
"format",
"(",
"_from",
")",
"elif",
"self",
".",
"token_version",
... | 36.083333 | 8.916667 |
def _get_seal_key_ntlm1(negotiate_flags, exported_session_key):
"""
3.4.5.3 SEALKEY
Calculates the seal_key used to seal (encrypt) messages. This for
authentication where NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY has not
been negotiated. Will weaken the keys if NTLMSSP_NEGOTIATE_56 is not
negot... | [
"def",
"_get_seal_key_ntlm1",
"(",
"negotiate_flags",
",",
"exported_session_key",
")",
":",
"if",
"negotiate_flags",
"&",
"NegotiateFlags",
".",
"NTLMSSP_NEGOTIATE_56",
":",
"seal_key",
"=",
"exported_session_key",
"[",
":",
"7",
"]",
"+",
"b\"\\xa0\"",
"else",
":"... | 41.421053 | 22.684211 |
def exception_format():
"""
Convert exception info into a string suitable for display.
"""
return "".join(traceback.format_exception(
sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
)) | [
"def",
"exception_format",
"(",
")",
":",
"return",
"\"\"",
".",
"join",
"(",
"traceback",
".",
"format_exception",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"0",
"]",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
",",
"sys",
".",
"exc_in... | 30.571429 | 14.571429 |
def guess_content_type_and_encoding(path):
"""Guess the content type of a path, using ``mimetypes``.
Falls back to "application/binary" if no content type is found.
Args:
path (str): the path to guess the mimetype of
Returns:
str: the content type of the file
"""
for ext, con... | [
"def",
"guess_content_type_and_encoding",
"(",
"path",
")",
":",
"for",
"ext",
",",
"content_type",
"in",
"_EXTENSION_TO_MIME_TYPE",
".",
"items",
"(",
")",
":",
"if",
"path",
".",
"endswith",
"(",
"ext",
")",
":",
"return",
"content_type",
"content_type",
","... | 29.315789 | 19.947368 |
def includeme(config):
""" Set up event subscribers. """
from .models import (
AuthUserMixin,
random_uuid,
lower_strip,
encrypt_password,
)
add_proc = config.add_field_processors
add_proc(
[random_uuid, lower_strip],
model=AuthUserMixin, field='usernam... | [
"def",
"includeme",
"(",
"config",
")",
":",
"from",
".",
"models",
"import",
"(",
"AuthUserMixin",
",",
"random_uuid",
",",
"lower_strip",
",",
"encrypt_password",
",",
")",
"add_proc",
"=",
"config",
".",
"add_field_processors",
"add_proc",
"(",
"[",
"random... | 31.857143 | 16.785714 |
def insert(self, data):
"""
Inserts item into this collection. An _id field will be generated if not assigned in the data.
:param data: Document to insert
:type data: ``string``
:return: _id of inserted object
:rtype: ``dict``
"""
return json.loads(self.... | [
"def",
"insert",
"(",
"self",
",",
"data",
")",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"_post",
"(",
"''",
",",
"headers",
"=",
"KVStoreCollectionData",
".",
"JSON_HEADER",
",",
"body",
"=",
"data",
")",
".",
"body",
".",
"read",
"(",... | 36.545455 | 24.545455 |
def get_birthday(self):
""":returns: contacts birthday or None if not available
:rtype: datetime.datetime or str
"""
# vcard 4.0 could contain a single text value
try:
if self.vcard.bday.params.get("VALUE")[0] == "text":
return self.vcard.bday.valu... | [
"def",
"get_birthday",
"(",
"self",
")",
":",
"# vcard 4.0 could contain a single text value",
"try",
":",
"if",
"self",
".",
"vcard",
".",
"bday",
".",
"params",
".",
"get",
"(",
"\"VALUE\"",
")",
"[",
"0",
"]",
"==",
"\"text\"",
":",
"return",
"self",
".... | 36.875 | 15 |
def _cleanup(self):
"""
Frees lots of non-textual information, such as the fonts
and images and the objects that were needed to parse the
PDF.
"""
self.device = None
self.doc = None
self.parser = None
self.resmgr = None
self.interpreter = N... | [
"def",
"_cleanup",
"(",
"self",
")",
":",
"self",
".",
"device",
"=",
"None",
"self",
".",
"doc",
"=",
"None",
"self",
".",
"parser",
"=",
"None",
"self",
".",
"resmgr",
"=",
"None",
"self",
".",
"interpreter",
"=",
"None"
] | 28.454545 | 15 |
def save_positions(post_data, queryset=None):
"""
Function to update a queryset of position objects with a post data dict.
:post_data: Typical post data dictionary like ``request.POST``, which
contains the keys of the position inputs.
:queryset: Queryset of the model ``ObjectPosition``.
"""
... | [
"def",
"save_positions",
"(",
"post_data",
",",
"queryset",
"=",
"None",
")",
":",
"if",
"not",
"queryset",
":",
"queryset",
"=",
"ObjectPosition",
".",
"objects",
".",
"all",
"(",
")",
"for",
"key",
"in",
"post_data",
":",
"if",
"key",
".",
"startswith"... | 35.555556 | 17.666667 |
def start_push_sync(self):
"""
Starts the detection of unsynced Git data.
"""
self.active_thread = True
self.active_push = True
self.thread_push_instance = Thread(target=self.thread_push)
self.thread_push_instance.daemon = True
self.thread_push_instance.s... | [
"def",
"start_push_sync",
"(",
"self",
")",
":",
"self",
".",
"active_thread",
"=",
"True",
"self",
".",
"active_push",
"=",
"True",
"self",
".",
"thread_push_instance",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"thread_push",
")",
"self",
".",
"thre... | 31.7 | 11.5 |
def _read_config(self):
"""Read the configuration file."""
config = configparser.ConfigParser()
config.read(self.path)
if config.has_section('distutils'):
server_names = config.get('distutils', 'index-servers')
servers = [name.strip() for name in server_names.spli... | [
"def",
"_read_config",
"(",
"self",
")",
":",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"self",
".",
"path",
")",
"if",
"config",
".",
"has_section",
"(",
"'distutils'",
")",
":",
"server_names",
"=",
"conf... | 41.875 | 15.875 |
def get_session_list(self, account):
"""
获取客服的会话列表
详情请参考
http://mp.weixin.qq.com/wiki/2/6c20f3e323bdf5986cfcb33cbd3b829a.html
:param account: 完整客服账号
:return: 客服的会话列表
"""
res = self._get(
'https://api.weixin.qq.com/customservice/kfsession/getse... | [
"def",
"get_session_list",
"(",
"self",
",",
"account",
")",
":",
"res",
"=",
"self",
".",
"_get",
"(",
"'https://api.weixin.qq.com/customservice/kfsession/getsessionlist'",
",",
"params",
"=",
"{",
"'kf_account'",
":",
"account",
"}",
",",
"result_processor",
"=",
... | 29.733333 | 18.8 |
def _search_val(matches, compiled_pattern, fld_val):
"""Search for user-regex in scalar data values."""
mtch = compiled_pattern.search(fld_val)
if mtch:
matches.append(fld_val) | [
"def",
"_search_val",
"(",
"matches",
",",
"compiled_pattern",
",",
"fld_val",
")",
":",
"mtch",
"=",
"compiled_pattern",
".",
"search",
"(",
"fld_val",
")",
"if",
"mtch",
":",
"matches",
".",
"append",
"(",
"fld_val",
")"
] | 41.6 | 9.6 |
def _prefix_description_for_number(data, longest_prefix, numobj, lang, script=None, region=None):
"""Return a text description of a PhoneNumber for the given language.
Arguments:
data -- Prefix dictionary to lookup up number in.
longest_prefix -- Length of the longest key in data.
numobj -- The Pho... | [
"def",
"_prefix_description_for_number",
"(",
"data",
",",
"longest_prefix",
",",
"numobj",
",",
"lang",
",",
"script",
"=",
"None",
",",
"region",
"=",
"None",
")",
":",
"e164_num",
"=",
"format_number",
"(",
"numobj",
",",
"PhoneNumberFormat",
".",
"E164",
... | 51.875 | 22.40625 |
def masked_local_attention_1d(x,
kv_channels,
heads,
window_size=128,
master_dtype=tf.float32,
slice_dtype=tf.float32,
length_per_split=None... | [
"def",
"masked_local_attention_1d",
"(",
"x",
",",
"kv_channels",
",",
"heads",
",",
"window_size",
"=",
"128",
",",
"master_dtype",
"=",
"tf",
".",
"float32",
",",
"slice_dtype",
"=",
"tf",
".",
"float32",
",",
"length_per_split",
"=",
"None",
",",
"return_... | 43.827957 | 19.16129 |
def _parse_var_array(self, X: np.ndarray) -> dict:
"""
Unpack the numpy array and bind each column to one of the variables in self.var_names
Returns inferred dict of variable: val pairs
"""
arg_vars = {}
# Get the shape and tensor rank
shape = X.shape
tens... | [
"def",
"_parse_var_array",
"(",
"self",
",",
"X",
":",
"np",
".",
"ndarray",
")",
"->",
"dict",
":",
"arg_vars",
"=",
"{",
"}",
"# Get the shape and tensor rank",
"shape",
"=",
"X",
".",
"shape",
"tensor_rank",
"=",
"len",
"(",
"shape",
")",
"T",
"=",
... | 43.04 | 13.04 |
def main():
"""Mainloop for the application"""
logging.basicConfig(level=logging.INFO)
app = RunSnakeRunApp(0)
app.MainLoop() | [
"def",
"main",
"(",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
")",
"app",
"=",
"RunSnakeRunApp",
"(",
"0",
")",
"app",
".",
"MainLoop",
"(",
")"
] | 27.4 | 13.4 |
def page(self, status=values.unset, date_created_after=values.unset,
date_created_before=values.unset, room_sid=values.unset,
page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of CompositionInstance records from ... | [
"def",
"page",
"(",
"self",
",",
"status",
"=",
"values",
".",
"unset",
",",
"date_created_after",
"=",
"values",
".",
"unset",
",",
"date_created_before",
"=",
"values",
".",
"unset",
",",
"room_sid",
"=",
"values",
".",
"unset",
",",
"page_token",
"=",
... | 46.138889 | 26.083333 |
def get_redirect_url(self, request, **kwargs):
"""
Return the URL redirect to. Keyword arguments from the
URL pattern match generating the redirect request
are provided as kwargs to this method.
"""
if self.url:
url = self.url % kwargs
args = reque... | [
"def",
"get_redirect_url",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"url",
":",
"url",
"=",
"self",
".",
"url",
"%",
"kwargs",
"args",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'QUERY_STRING'",
",",
"'... | 34.714286 | 11.285714 |
def _get_tick_frac_labels(self):
"""Get the major ticks, minor ticks, and major labels"""
minor_num = 4 # number of minor ticks per major division
if (self.axis.scale_type == 'linear'):
domain = self.axis.domain
if domain[1] < domain[0]:
flip = True
... | [
"def",
"_get_tick_frac_labels",
"(",
"self",
")",
":",
"minor_num",
"=",
"4",
"# number of minor ticks per major division",
"if",
"(",
"self",
".",
"axis",
".",
"scale_type",
"==",
"'linear'",
")",
":",
"domain",
"=",
"self",
".",
"axis",
".",
"domain",
"if",
... | 46.511111 | 15.622222 |
def buffer_read_into(self, buffer, dtype):
"""Read from the file into a given buffer object.
Fills the given `buffer` with frames in the given data format
starting at the current read/write position (which can be
changed with :meth:`.seek`) until the buffer is full or the end
of... | [
"def",
"buffer_read_into",
"(",
"self",
",",
"buffer",
",",
"dtype",
")",
":",
"ctype",
"=",
"self",
".",
"_check_dtype",
"(",
"dtype",
")",
"cdata",
",",
"frames",
"=",
"self",
".",
"_check_buffer",
"(",
"buffer",
",",
"ctype",
")",
"frames",
"=",
"se... | 35.15625 | 21.40625 |
def debugTreePrint(node,pfx="->"):
"""Purely a debugging aid: Ascii-art picture of a tree descended from node"""
print pfx,node.item
for c in node.children:
debugTreePrint(c," "+pfx) | [
"def",
"debugTreePrint",
"(",
"node",
",",
"pfx",
"=",
"\"->\"",
")",
":",
"print",
"pfx",
",",
"node",
".",
"item",
"for",
"c",
"in",
"node",
".",
"children",
":",
"debugTreePrint",
"(",
"c",
",",
"\" \"",
"+",
"pfx",
")"
] | 37.8 | 10 |
def select_from_drop_down_by_text(self, drop_down_locator, option_locator, option_text, params=None):
"""
Select option from drop down widget using text.
:param drop_down_locator: locator tuple (if any, params needs to be in place) or WebElement instance
:param option_locator: locator t... | [
"def",
"select_from_drop_down_by_text",
"(",
"self",
",",
"drop_down_locator",
",",
"option_locator",
",",
"option_text",
",",
"params",
"=",
"None",
")",
":",
"# Open/activate drop down",
"self",
".",
"click",
"(",
"drop_down_locator",
",",
"params",
"[",
"'drop_do... | 47.5 | 27.388889 |
def package_removed(name, image=None, restart=False):
'''
Uninstall a package
Args:
name (str): The full path to the package. Can be either a .cab file or a
folder. Should point to the original source of the package, not to
where the file is installed. This can also be the n... | [
"def",
"package_removed",
"(",
"name",
",",
"image",
"=",
"None",
",",
"restart",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"# Fa... | 34.328947 | 22.907895 |
def get_all_bandwidth_groups(self):
"""Get all managed bandwidth groups.
return bandwidth_groups of type :class:`IBandwidthGroup`
The array of managed bandwidth groups.
"""
bandwidth_groups = self._call("getAllBandwidthGroups")
bandwidth_groups = [IBandwidthGroup(a)... | [
"def",
"get_all_bandwidth_groups",
"(",
"self",
")",
":",
"bandwidth_groups",
"=",
"self",
".",
"_call",
"(",
"\"getAllBandwidthGroups\"",
")",
"bandwidth_groups",
"=",
"[",
"IBandwidthGroup",
"(",
"a",
")",
"for",
"a",
"in",
"bandwidth_groups",
"]",
"return",
"... | 37 | 18.3 |
def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info):
"""
[MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol
3.3.2 NTLM v2 Authentication
Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and th... | [
"def",
"get_ntlmv2_response",
"(",
"domain",
",",
"user",
",",
"password",
",",
"server_challenge",
",",
"client_challenge",
",",
"timestamp",
",",
"target_info",
")",
":",
"lo_response_version",
"=",
"b'\\x01'",
"hi_response_version",
"=",
"b'\\x01'",
"reserved_dword... | 52.74359 | 24.384615 |
async def close(self, code: int = 1006, reason: str = "Connection closed"):
"""
Closes the websocket.
"""
if self._closed:
return
self._closed = True
if self._scope is not None:
await self._scope.cancel()
# cancel any outstanding list... | [
"async",
"def",
"close",
"(",
"self",
",",
"code",
":",
"int",
"=",
"1006",
",",
"reason",
":",
"str",
"=",
"\"Connection closed\"",
")",
":",
"if",
"self",
".",
"_closed",
":",
"return",
"self",
".",
"_closed",
"=",
"True",
"if",
"self",
".",
"_scop... | 28.5 | 18.166667 |
def parse_friends(self, friends_page):
"""Parses the DOM and returns user friends attributes.
:type friends_page: :class:`bs4.BeautifulSoup`
:param friends_page: MAL user friends page's DOM
:rtype: dict
:return: User friends attributes.
"""
user_info = self.parse_sidebar(friends_page)
... | [
"def",
"parse_friends",
"(",
"self",
",",
"friends_page",
")",
":",
"user_info",
"=",
"self",
".",
"parse_sidebar",
"(",
"friends_page",
")",
"second_col",
"=",
"friends_page",
".",
"find",
"(",
"u'div'",
",",
"{",
"u'id'",
":",
"u'content'",
"}",
")",
"."... | 34.324324 | 24.783784 |
def named_object(name):
"""Gets a fully named module-global object."""
name_parts = name.split('.')
module = named_module('.'.join(name_parts[:-1]))
return getattr(module, name_parts[-1]) | [
"def",
"named_object",
"(",
"name",
")",
":",
"name_parts",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"module",
"=",
"named_module",
"(",
"'.'",
".",
"join",
"(",
"name_parts",
"[",
":",
"-",
"1",
"]",
")",
")",
"return",
"getattr",
"(",
"module",
... | 39.8 | 7.8 |
def next_object(self):
"""Get next GridOut object from cursor."""
grid_out = super(self.__class__, self).next_object()
if grid_out:
grid_out_class = create_class_with_framework(
AgnosticGridOut, self._framework, self.__module__)
return grid_out_class(self... | [
"def",
"next_object",
"(",
"self",
")",
":",
"grid_out",
"=",
"super",
"(",
"self",
".",
"__class__",
",",
"self",
")",
".",
"next_object",
"(",
")",
"if",
"grid_out",
":",
"grid_out_class",
"=",
"create_class_with_framework",
"(",
"AgnosticGridOut",
",",
"s... | 36.727273 | 20.909091 |
def add_reader(self, fd, callback):
" Start watching the file descriptor for read availability. "
h = msvcrt.get_osfhandle(fd)
self._read_fds[h] = callback | [
"def",
"add_reader",
"(",
"self",
",",
"fd",
",",
"callback",
")",
":",
"h",
"=",
"msvcrt",
".",
"get_osfhandle",
"(",
"fd",
")",
"self",
".",
"_read_fds",
"[",
"h",
"]",
"=",
"callback"
] | 44 | 10.5 |
def _run_sync(self, method: Callable, *args, **kwargs) -> Any:
"""
Utility method to run commands synchronously for testing.
"""
if self.loop.is_running():
raise RuntimeError("Event loop is already running.")
if not self.is_connected:
self.loop.run_until_... | [
"def",
"_run_sync",
"(",
"self",
",",
"method",
":",
"Callable",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Any",
":",
"if",
"self",
".",
"loop",
".",
"is_running",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Event loop is already running... | 32.8125 | 20.4375 |
def dePeriod(arr):
"""make an array of periodic angles increase linearly"""
diff= arr-nu.roll(arr,1,axis=1)
w= diff < -6.
addto= nu.cumsum(w.astype(int),axis=1)
return arr+_TWOPI*addto | [
"def",
"dePeriod",
"(",
"arr",
")",
":",
"diff",
"=",
"arr",
"-",
"nu",
".",
"roll",
"(",
"arr",
",",
"1",
",",
"axis",
"=",
"1",
")",
"w",
"=",
"diff",
"<",
"-",
"6.",
"addto",
"=",
"nu",
".",
"cumsum",
"(",
"w",
".",
"astype",
"(",
"int",... | 33.166667 | 10.833333 |
def _to_dataframe_bqstorage(self, bqstorage_client, dtypes, progress_bar=None):
"""Use (faster, but billable) BQ Storage API to construct DataFrame."""
if bigquery_storage_v1beta1 is None:
raise ValueError(_NO_BQSTORAGE_ERROR)
if "$" in self._table.table_id:
raise ValueE... | [
"def",
"_to_dataframe_bqstorage",
"(",
"self",
",",
"bqstorage_client",
",",
"dtypes",
",",
"progress_bar",
"=",
"None",
")",
":",
"if",
"bigquery_storage_v1beta1",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"_NO_BQSTORAGE_ERROR",
")",
"if",
"\"$\"",
"in",
"... | 39.683168 | 20.980198 |
def contribute_to_class(self, cls, name):
"""
I need a way to ensure that this signal gets created for all child
models, and since model inheritance doesn't have a 'contrubite_to_class'
style hook, I am creating a fake virtual field which will be added to
all subclasses and handl... | [
"def",
"contribute_to_class",
"(",
"self",
",",
"cls",
",",
"name",
")",
":",
"super",
"(",
"EmbeddedMediaField",
",",
"self",
")",
".",
"contribute_to_class",
"(",
"cls",
",",
"name",
")",
"register_field",
"(",
"cls",
",",
"self",
")",
"# add a virtual fie... | 49.916667 | 21.25 |
def scale(self, service, count=None, delta=None, **kwargs):
"""Scale a service to a requested number of instances.
Adds or removes containers to match the requested number of instances.
The number of instances for the service can be specified either as a
total count or a delta in that c... | [
"def",
"scale",
"(",
"self",
",",
"service",
",",
"count",
"=",
"None",
",",
"delta",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'instances'",
"in",
"kwargs",
":",
"count",
"=",
"kwargs",
".",
"pop",
"(",
"'instances'",
")",
"warnings",
... | 42.106383 | 20.468085 |
def fmt_routes(bottle_app):
"""Return a pretty formatted string of the list of routes."""
routes = [(r.method, r.rule) for r in bottle_app.routes]
if not routes:
return
string = 'Routes:\n'
string += fmt_pairs(routes, sort_key=operator.itemgetter(1))
return string | [
"def",
"fmt_routes",
"(",
"bottle_app",
")",
":",
"routes",
"=",
"[",
"(",
"r",
".",
"method",
",",
"r",
".",
"rule",
")",
"for",
"r",
"in",
"bottle_app",
".",
"routes",
"]",
"if",
"not",
"routes",
":",
"return",
"string",
"=",
"'Routes:\\n'",
"strin... | 36.125 | 18 |
def create_layout(graph, graphviz_prog=DEFAULT_GRAPHVIZ_PROG):
"""Return {node: position} for given graph"""
graphviz_layout = graphutils.graphviz_layout(graph, prog=graphviz_prog)
# print('GRAPHIZ LAYOUT:', graphviz_layout)
layout = {k: (int(x // 10), int(y // 10))
for k, (x, y) in graphv... | [
"def",
"create_layout",
"(",
"graph",
",",
"graphviz_prog",
"=",
"DEFAULT_GRAPHVIZ_PROG",
")",
":",
"graphviz_layout",
"=",
"graphutils",
".",
"graphviz_layout",
"(",
"graph",
",",
"prog",
"=",
"graphviz_prog",
")",
"# print('GRAPHIZ LAYOUT:', graphviz_layout)",
"layout... | 45.411765 | 14.647059 |
def delete_framework(cls, framework=None):
# type: (Optional[Framework]) -> bool
# pylint: disable=W0212
"""
Removes the framework singleton
:return: True on success, else False
"""
if framework is None:
framework = cls.__singleton
if framewo... | [
"def",
"delete_framework",
"(",
"cls",
",",
"framework",
"=",
"None",
")",
":",
"# type: (Optional[Framework]) -> bool",
"# pylint: disable=W0212",
"if",
"framework",
"is",
"None",
":",
"framework",
"=",
"cls",
".",
"__singleton",
"if",
"framework",
"is",
"cls",
"... | 28.27027 | 13.837838 |
def compute_laplacian_matrix(self, copy=True, return_lapsym=False, **kwargs):
"""
Note: this function will compute the laplacian matrix. In order to acquire
the existing laplacian matrix use self.laplacian_matrix as
comptute_laplacian_matrix() will re-compute the laplacian matrix... | [
"def",
"compute_laplacian_matrix",
"(",
"self",
",",
"copy",
"=",
"True",
",",
"return_lapsym",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"affinity_matrix",
"is",
"None",
":",
"self",
".",
"compute_affinity_matrix",
"(",
")",
"kwd... | 40.674419 | 19.465116 |
def emergence(network, state, do_blackbox=False, do_coarse_grain=True,
time_scales=None):
"""Check for the emergence of a micro-system into a macro-system.
Checks all possible blackboxings and coarse-grainings of a system to find
the spatial scale with maximum integrated information.
Use... | [
"def",
"emergence",
"(",
"network",
",",
"state",
",",
"do_blackbox",
"=",
"False",
",",
"do_coarse_grain",
"=",
"True",
",",
"time_scales",
"=",
"None",
")",
":",
"micro_phi",
"=",
"compute",
".",
"major_complex",
"(",
"network",
",",
"state",
")",
".",
... | 38.702128 | 22.106383 |
def ensure_netmiko_conn(func):
"""Decorator that ensures Netmiko connection exists."""
def wrap_function(self, filename=None, config=None):
try:
netmiko_object = self._netmiko_device
if netmiko_object is None:
raise AttributeError()
except AttributeError:... | [
"def",
"ensure_netmiko_conn",
"(",
"func",
")",
":",
"def",
"wrap_function",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"config",
"=",
"None",
")",
":",
"try",
":",
"netmiko_object",
"=",
"self",
".",
"_netmiko_device",
"if",
"netmiko_object",
"is",
"... | 38.368421 | 16.736842 |
def OnSelectReader(self, reader):
"""Called when a reader is selected by clicking on the reader
tree control or toolbar."""
SimpleSCardAppEventObserver.OnSelectReader(self, reader)
self.feedbacktext.SetLabel('Selected reader: ' + repr(reader)) | [
"def",
"OnSelectReader",
"(",
"self",
",",
"reader",
")",
":",
"SimpleSCardAppEventObserver",
".",
"OnSelectReader",
"(",
"self",
",",
"reader",
")",
"self",
".",
"feedbacktext",
".",
"SetLabel",
"(",
"'Selected reader: '",
"+",
"repr",
"(",
"reader",
")",
")"... | 54.2 | 12.2 |
def dict_to_hdf5(dic, endpoint):
"""Dump a dict to an HDF5 file.
"""
filename = gen_filename(endpoint)
with h5py.File(filename, 'w') as handler:
walk_dict_to_hdf5(dic, handler)
print('dumped to', filename) | [
"def",
"dict_to_hdf5",
"(",
"dic",
",",
"endpoint",
")",
":",
"filename",
"=",
"gen_filename",
"(",
"endpoint",
")",
"with",
"h5py",
".",
"File",
"(",
"filename",
",",
"'w'",
")",
"as",
"handler",
":",
"walk_dict_to_hdf5",
"(",
"dic",
",",
"handler",
")"... | 32.428571 | 3.571429 |
def _from_attr_(mcs, cls, attr_name: str, attr_value: Any) -> TypeVar:
"""
Returns the enumeration item regarding to the attribute name and value,
or None if not found for the given cls
:param attr_name: str: attribute's name
:param attr_value: different values: key to search fo... | [
"def",
"_from_attr_",
"(",
"mcs",
",",
"cls",
",",
"attr_name",
":",
"str",
",",
"attr_value",
":",
"Any",
")",
"->",
"TypeVar",
":",
"return",
"next",
"(",
"iter",
"(",
"filter",
"(",
"lambda",
"x",
":",
"getattr",
"(",
"x",
",",
"attr_name",
")",
... | 44.272727 | 18.090909 |
def pb2json(pb):
''' convert google.protobuf.descriptor instance to JSON string '''
js = {}
# fields = pb.DESCRIPTOR.fields #all fields
fields = pb.ListFields() #only filled (including extensions)
for field,value in fields:
if field.type == FD.TYPE_MESSAGE:
ftype = pb2json
... | [
"def",
"pb2json",
"(",
"pb",
")",
":",
"js",
"=",
"{",
"}",
"# fields = pb.DESCRIPTOR.fields #all fields",
"fields",
"=",
"pb",
".",
"ListFields",
"(",
")",
"#only filled (including extensions)",
"for",
"field",
",",
"value",
"in",
"fields",
":",
"if",
"field",
... | 38.909091 | 17.090909 |
def list_(properties='size,alloc,free,cap,frag,health', zpool=None, parsable=True):
'''
.. versionadded:: 2015.5.0
Return information about (all) storage pools
zpool : string
optional name of storage pool
properties : string
comma-separated list of properties to list
parsable... | [
"def",
"list_",
"(",
"properties",
"=",
"'size,alloc,free,cap,frag,health'",
",",
"zpool",
"=",
"None",
",",
"parsable",
"=",
"True",
")",
":",
"ret",
"=",
"OrderedDict",
"(",
")",
"## update properties",
"# NOTE: properties should be a list",
"if",
"not",
"isinstan... | 27.094737 | 21.2 |
def catalogs(self, **kwargs):
"""Get the catalog information from the infrastructure based on path
and/or query results. It is strongly recommended to include query
and/or paging parameters for this endpoint to prevent large result
sets or PuppetDB performance bottlenecks.
:para... | [
"def",
"catalogs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"catalogs",
"=",
"self",
".",
"_query",
"(",
"'catalogs'",
",",
"*",
"*",
"kwargs",
")",
"if",
"type",
"(",
"catalogs",
")",
"==",
"dict",
":",
"catalogs",
"=",
"[",
"catalogs",
","... | 44.769231 | 19.115385 |
def import_obj(cls, slc_to_import, slc_to_override, import_time=None):
"""Inserts or overrides slc in the database.
remote_id and import_time fields in params_dict are set to track the
slice origin and ensure correct overrides for multiple imports.
Slice.perm is used to find the datasou... | [
"def",
"import_obj",
"(",
"cls",
",",
"slc_to_import",
",",
"slc_to_override",
",",
"import_time",
"=",
"None",
")",
":",
"session",
"=",
"db",
".",
"session",
"make_transient",
"(",
"slc_to_import",
")",
"slc_to_import",
".",
"dashboards",
"=",
"[",
"]",
"s... | 43.870968 | 18.935484 |
def delete(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Delete a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain th... | [
"def",
"delete",
"(",
"name",
",",
"table",
"=",
"'filter'",
",",
"family",
"=",
"'ipv4'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
... | 34.103448 | 19.068966 |
def mapped_read_count(self, force=False):
"""
Counts total reads in a BAM file.
If a file self.bam + '.scale' exists, then just read the first line of
that file that doesn't start with a "#". If such a file doesn't exist,
then it will be created with the number of reads as the ... | [
"def",
"mapped_read_count",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"# Already run?",
"if",
"self",
".",
"_readcount",
"and",
"not",
"force",
":",
"return",
"self",
".",
"_readcount",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
... | 34.058824 | 18.568627 |
def delete_user(ctx, yes):
"""Delete a local user"""
if ctx.obj['username'] is None:
username = _ask("Please enter username:")
else:
username = ctx.obj['username']
del_user = ctx.obj['db'].objectmodels['user'].find_one({'name': username})
if yes or _ask('Confirm deletion', default=... | [
"def",
"delete_user",
"(",
"ctx",
",",
"yes",
")",
":",
"if",
"ctx",
".",
"obj",
"[",
"'username'",
"]",
"is",
"None",
":",
"username",
"=",
"_ask",
"(",
"\"Please enter username:\"",
")",
"else",
":",
"username",
"=",
"ctx",
".",
"obj",
"[",
"'usernam... | 29.764706 | 19.235294 |
def get_all_tags_with_auth(image_name, branch=None):
"""
Get the tag information using authentication credentials provided by the
user.
:param image_name: The image name to query
:param branch: The branch to filter by
:return: A list of Version instances, latest first
"""
logging.debug(... | [
"def",
"get_all_tags_with_auth",
"(",
"image_name",
",",
"branch",
"=",
"None",
")",
":",
"logging",
".",
"debug",
"(",
"'Getting %s with authentication'",
"%",
"image_name",
")",
"url",
"=",
"'%s/%s/images'",
"%",
"(",
"API_URL",
",",
"image_name",
")",
"regist... | 35.525773 | 23.051546 |
def horz_dpi(self):
"""
Integer dots per inch for the width of this image. Defaults to 72
when not present in the file, as is often the case.
"""
pHYs = self._chunks.pHYs
if pHYs is None:
return 72
return self._dpi(pHYs.units_specifier, pHYs.horz_px_pe... | [
"def",
"horz_dpi",
"(",
"self",
")",
":",
"pHYs",
"=",
"self",
".",
"_chunks",
".",
"pHYs",
"if",
"pHYs",
"is",
"None",
":",
"return",
"72",
"return",
"self",
".",
"_dpi",
"(",
"pHYs",
".",
"units_specifier",
",",
"pHYs",
".",
"horz_px_per_unit",
")"
] | 35.444444 | 16.111111 |
def process_params(mod_id, params, type_params):
"""
Takes as input a dictionary of parameters defined on a module and the
information about the required parameters defined on the corresponding
module type. Validatates that are required parameters were supplied and
fills any missing parameters with ... | [
"def",
"process_params",
"(",
"mod_id",
",",
"params",
",",
"type_params",
")",
":",
"res",
"=",
"{",
"}",
"for",
"param_name",
",",
"param_info",
"in",
"type_params",
".",
"items",
"(",
")",
":",
"val",
"=",
"params",
".",
"get",
"(",
"param_name",
",... | 47.25 | 19.166667 |
def _get_em(length):
'''
::param: length \
the length specified in the CSS.
::return:
the length in em's.
'''
m = CssParse.RE_UNIT.search(length)
value = float(m.group(1))
unit = m.group(2)
if unit not in ('em', 'qem', 'rem'):
... | [
"def",
"_get_em",
"(",
"length",
")",
":",
"m",
"=",
"CssParse",
".",
"RE_UNIT",
".",
"search",
"(",
"length",
")",
"value",
"=",
"float",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"unit",
"=",
"m",
".",
"group",
"(",
"2",
")",
"if",
"unit",
... | 24.4375 | 16.9375 |
def htg(args):
"""
%prog htg fastafile template.sbt
Prepare sqnfiles for Genbank HTG submission to update existing records.
`fastafile` contains the records to update, multiple records are allowed
(with each one generating separate sqn file in the sqn/ folder). The record
defline has the acces... | [
"def",
"htg",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"fasta",
"import",
"sequin",
",",
"ids",
"from",
"jcvi",
".",
"formats",
".",
"agp",
"import",
"phase",
"from",
"jcvi",
".",
"apps",
".",
"fetch",
"import",
"entrez",
"p",
"=",... | 34.094937 | 22.677215 |
def args(self) -> str:
"""Provides arguments for the command."""
value = self._value
if not value:
value = datetime.now()
return value.strftime('%y%m%d%w%H%M') | [
"def",
"args",
"(",
"self",
")",
"->",
"str",
":",
"value",
"=",
"self",
".",
"_value",
"if",
"not",
"value",
":",
"value",
"=",
"datetime",
".",
"now",
"(",
")",
"return",
"value",
".",
"strftime",
"(",
"'%y%m%d%w%H%M'",
")"
] | 33 | 10.166667 |
def move_up(lines=1, file=sys.stdout):
""" Move the cursor up a number of lines.
Esc[ValueA:
Moves the cursor up by the specified number of lines without changing
columns. If the cursor is already on the top line, ANSI.SYS ignores
this sequence.
"""
move.up(lines).write(file... | [
"def",
"move_up",
"(",
"lines",
"=",
"1",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"move",
".",
"up",
"(",
"lines",
")",
".",
"write",
"(",
"file",
"=",
"file",
")"
] | 35.333333 | 17.555556 |
def instantiate_references_json(references_json):
''' Given a JSON representation of all the models in a graph, return a
dict of new model objects.
Args:
references_json (``JSON``)
JSON specifying new Bokeh models to create
Returns:
dict[str, Model]
'''
# Create a... | [
"def",
"instantiate_references_json",
"(",
"references_json",
")",
":",
"# Create all instances, but without setting their props",
"references",
"=",
"{",
"}",
"for",
"obj",
"in",
"references_json",
":",
"obj_id",
"=",
"obj",
"[",
"'id'",
"]",
"obj_type",
"=",
"obj",
... | 28.884615 | 23.192308 |
def get_number(self, num, table=None):
"""Get a specific entry by its number."""
if table is None: table = self.main_table
self.own_cursor.execute('SELECT * from "%s" LIMIT 1 OFFSET %i;' % (self.main_table, num))
return self.own_cursor.fetchone() | [
"def",
"get_number",
"(",
"self",
",",
"num",
",",
"table",
"=",
"None",
")",
":",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"self",
".",
"own_cursor",
".",
"execute",
"(",
"'SELECT * from \"%s\" LIMIT 1 OFFSET %i;'",
"%",
... | 54.8 | 13.8 |
def fire_ret_load(self, load):
'''
Fire events based on information in the return load
'''
if load.get('retcode') and load.get('fun'):
if isinstance(load['fun'], list):
# Multi-function job
if isinstance(load['retcode'], list):
... | [
"def",
"fire_ret_load",
"(",
"self",
",",
"load",
")",
":",
"if",
"load",
".",
"get",
"(",
"'retcode'",
")",
"and",
"load",
".",
"get",
"(",
"'fun'",
")",
":",
"if",
"isinstance",
"(",
"load",
"[",
"'fun'",
"]",
",",
"list",
")",
":",
"# Multi-func... | 46.448276 | 18.310345 |
def __sort_draw(self):
"""Sort the drawable objects according to ascending order"""
if self.__do_need_sort_draw:
self.__draw_objects.sort(self.__draw_cmp)
self.__do_need_sort_draw = False | [
"def",
"__sort_draw",
"(",
"self",
")",
":",
"if",
"self",
".",
"__do_need_sort_draw",
":",
"self",
".",
"__draw_objects",
".",
"sort",
"(",
"self",
".",
"__draw_cmp",
")",
"self",
".",
"__do_need_sort_draw",
"=",
"False"
] | 44.6 | 7.8 |
def get_type_properties(self, property_obj, name, additional_prop=False):
"""
Extend parents 'Get internal properties of property'-method
"""
property_type, property_format, property_dict = \
super(Schema, self).get_type_properties(property_obj, name, additional_prop=addition... | [
"def",
"get_type_properties",
"(",
"self",
",",
"property_obj",
",",
"name",
",",
"additional_prop",
"=",
"False",
")",
":",
"property_type",
",",
"property_format",
",",
"property_dict",
"=",
"super",
"(",
"Schema",
",",
"self",
")",
".",
"get_type_properties",... | 55.941176 | 26.764706 |
def print_warning(cls):
"""Print a missing progress bar warning if it was not printed.
"""
if not cls.warning:
cls.warning = True
print('Can\'t create progress bar:', str(TQDM_IMPORT_ERROR),
file=sys.stderr) | [
"def",
"print_warning",
"(",
"cls",
")",
":",
"if",
"not",
"cls",
".",
"warning",
":",
"cls",
".",
"warning",
"=",
"True",
"print",
"(",
"'Can\\'t create progress bar:'",
",",
"str",
"(",
"TQDM_IMPORT_ERROR",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
... | 38.142857 | 11.142857 |
def stop(self):
"""
Releases the db mutex lock. Throws an error if the lock was released before the function finished.
"""
if not DBMutex.objects.filter(id=self.lock.id).exists():
raise DBMutexTimeoutError('Lock {0} expired before function completed'.format(self.lock_id))
... | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"DBMutex",
".",
"objects",
".",
"filter",
"(",
"id",
"=",
"self",
".",
"lock",
".",
"id",
")",
".",
"exists",
"(",
")",
":",
"raise",
"DBMutexTimeoutError",
"(",
"'Lock {0} expired before function complete... | 44.25 | 27 |
def direct_messages_sent(self, since_id=None, max_id=None, count=None,
include_entities=None, page=None):
"""
Gets the 20 most recent direct messages sent by the authenticating
user.
https://dev.twitter.com/docs/api/1.1/get/direct_messages/sent
:par... | [
"def",
"direct_messages_sent",
"(",
"self",
",",
"since_id",
"=",
"None",
",",
"max_id",
"=",
"None",
",",
"count",
"=",
"None",
",",
"include_entities",
"=",
"None",
",",
"page",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"set_str_param",
"(",
"p... | 39.25641 | 23.512821 |
def pull(self):
"""
Returns an iterable that can be used to iterate over incoming messages,
that were pushed by a push socket. Note that the iterable returns as
many parts as sent by pushers.
:rtype: generator
"""
sock = self.__sock(zmq.PULL)
return self.... | [
"def",
"pull",
"(",
"self",
")",
":",
"sock",
"=",
"self",
".",
"__sock",
"(",
"zmq",
".",
"PULL",
")",
"return",
"self",
".",
"__recv_generator",
"(",
"sock",
")"
] | 33.3 | 16.3 |
def interpolate_data(self, data, times, resampled_times):
""" Interpolates data feature
:param data: Array in a shape of t x nobs, where nobs = h x w x n
:type data: numpy.ndarray
:param times: Array of reference times in second relative to the first timestamp
:type times: numpy... | [
"def",
"interpolate_data",
"(",
"self",
",",
"data",
",",
"times",
",",
"resampled_times",
")",
":",
"if",
"True",
"in",
"np",
".",
"unique",
"(",
"np",
".",
"isnan",
"(",
"data",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Data must not contain any maske... | 49.318182 | 25.772727 |
def fit_toy_potential(orbit, force_harmonic_oscillator=False):
"""
Fit a best fitting toy potential to the orbit provided. If the orbit is a
tube (loop) orbit, use the Isochrone potential. If the orbit is a box
potential, use the harmonic oscillator potential. An option is available to
force using t... | [
"def",
"fit_toy_potential",
"(",
"orbit",
",",
"force_harmonic_oscillator",
"=",
"False",
")",
":",
"circulation",
"=",
"orbit",
".",
"circulation",
"(",
")",
"if",
"np",
".",
"any",
"(",
"circulation",
"==",
"1",
")",
"and",
"not",
"force_harmonic_oscillator"... | 39.95 | 25.4 |
def hibernate(app):
"""Pause an experiment and remove costly resources."""
backup(app)
log("Scaling down the web servers...")
subprocess.call("heroku ps:scale web=0" + " --app " + app, shell=True)
subprocess.call("heroku ps:scale worker=0" + " --app " + app, shell=True)
subprocess.call("heroku ... | [
"def",
"hibernate",
"(",
"app",
")",
":",
"backup",
"(",
"app",
")",
"log",
"(",
"\"Scaling down the web servers...\"",
")",
"subprocess",
".",
"call",
"(",
"\"heroku ps:scale web=0\"",
"+",
"\" --app \"",
"+",
"app",
",",
"shell",
"=",
"True",
")",
"subproces... | 29.333333 | 22.833333 |
def handle_errors(
cls, message, *format_args,
re_raise=True, exception_class=Exception,
do_finally=None, do_except=None, do_else=None,
**format_kwds
):
"""
provides a context manager that will intercept exceptions and repackage
them as Buzz in... | [
"def",
"handle_errors",
"(",
"cls",
",",
"message",
",",
"*",
"format_args",
",",
"re_raise",
"=",
"True",
",",
"exception_class",
"=",
"Exception",
",",
"do_finally",
"=",
"None",
",",
"do_except",
"=",
"None",
",",
"do_else",
"=",
"None",
",",
"*",
"*"... | 44.711864 | 22.135593 |
def removeChild(self, child):
'''
removeChild - Remove a child tag, if present.
@param child <AdvancedTag> - The child to remove
@return - The child [with parentNode cleared] if removed, otherwise None.
NOTE: This removes a tag. If removing a text b... | [
"def",
"removeChild",
"(",
"self",
",",
"child",
")",
":",
"try",
":",
"# Remove from children and blocks",
"self",
".",
"children",
".",
"remove",
"(",
"child",
")",
"self",
".",
"blocks",
".",
"remove",
"(",
"child",
")",
"# Clear parent node association on ch... | 39.612903 | 26.83871 |
def set_daily(self, interval, **kwargs):
""" Set to repeat every x no. of days
:param int interval: no. of days to repeat at
:keyword date start: Start date of repetition (kwargs)
:keyword date end: End date of repetition (kwargs)
:keyword int occurrences: no of occurrences (kwa... | [
"def",
"set_daily",
"(",
"self",
",",
"interval",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_clear_pattern",
"(",
")",
"self",
".",
"__interval",
"=",
"interval",
"self",
".",
"set_range",
"(",
"*",
"*",
"kwargs",
")"
] | 38.545455 | 12.545455 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.