text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _collection_default_options(self, name, **kargs):
"""Get a Collection instance with the default settings."""
wc = (self.write_concern
if self.write_concern.acknowledged else WriteConcern())
return self.get_collection(
name, codec_options=DEFAULT_CODEC_OPTIONS,
... | [
"def",
"_collection_default_options",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kargs",
")",
":",
"wc",
"=",
"(",
"self",
".",
"write_concern",
"if",
"self",
".",
"write_concern",
".",
"acknowledged",
"else",
"WriteConcern",
"(",
")",
")",
"return",
"self"... | 48.625 | 0.005051 |
def GetEventTags(self):
"""Retrieves the event tags.
Yields:
EventTag: event tag.
"""
for event_tag in self._GetAttributeContainers(
self._CONTAINER_TYPE_EVENT_TAG):
event_identifier = identifiers.SQLTableIdentifier(
self._CONTAINER_TYPE_EVENT, event_tag.event_row_identifi... | [
"def",
"GetEventTags",
"(",
"self",
")",
":",
"for",
"event_tag",
"in",
"self",
".",
"_GetAttributeContainers",
"(",
"self",
".",
"_CONTAINER_TYPE_EVENT_TAG",
")",
":",
"event_identifier",
"=",
"identifiers",
".",
"SQLTableIdentifier",
"(",
"self",
".",
"_CONTAINE... | 28.466667 | 0.013605 |
def collect_logs(name):
"""
Returns a string representation of the logs from a container.
This is similar to container_logs but uses the `follow` option
and flattens the logs into a string instead of a generator.
:param name: The container name to grab logs for
:return: A string representation ... | [
"def",
"collect_logs",
"(",
"name",
")",
":",
"logs",
"=",
"container_logs",
"(",
"name",
",",
"\"all\"",
",",
"True",
",",
"None",
")",
"string",
"=",
"\"\"",
"for",
"s",
"in",
"logs",
":",
"string",
"+=",
"s",
"return",
"string"
] | 32.142857 | 0.00216 |
def _fire(self, layers, the_plot):
"""Launches a new bolt from a random Marauder."""
# We don't fire if another Marauder fired a bolt just now.
if the_plot.get('last_marauder_shot') == the_plot.frame: return
the_plot['last_marauder_shot'] = the_plot.frame
# Which Marauder should fire the laser bolt?... | [
"def",
"_fire",
"(",
"self",
",",
"layers",
",",
"the_plot",
")",
":",
"# We don't fire if another Marauder fired a bolt just now.",
"if",
"the_plot",
".",
"get",
"(",
"'last_marauder_shot'",
")",
"==",
"the_plot",
".",
"frame",
":",
"return",
"the_plot",
"[",
"'l... | 50.9 | 0.003861 |
def find_version(*args, **kwargs):
"""
Wrapper around :py:class:`~.VersionFinder` and its
:py:meth:`~.VersionFinder.find_package_version` method. Pass arguments and
kwargs to VersionFinder constructor, return the value of its
``find_package_version`` method.
:param package_name: name of the pac... | [
"def",
"find_version",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'caller_frame'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'caller_frame'",
"]",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"1",
"]",
"[",
"0",
"]",
"return",
"V... | 47.791667 | 0.000855 |
def _set_isis_state(self, v, load=False):
"""
Setter method for isis_state, mapped from YANG variable /isis_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_isis_state is considered as a private
method. Backends looking to populate this variable shou... | [
"def",
"_set_isis_state",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | 71.583333 | 0.005744 |
def click(self, x=-1, y=-1, selector=None):
"""
An alias for touch.
:param x:
:param y:
:param selector:
:return:
"""
self.touch(x=x, y=y, selector=selector) | [
"def",
"click",
"(",
"self",
",",
"x",
"=",
"-",
"1",
",",
"y",
"=",
"-",
"1",
",",
"selector",
"=",
"None",
")",
":",
"self",
".",
"touch",
"(",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"selector",
"=",
"selector",
")"
] | 19.363636 | 0.008969 |
def setup_directories(self, use_sudo=True):
"""Create the minimal required directories for deploying multiple
releases of a project.
By default, creation of directories is done with the Fabric
``sudo`` function but can optionally use the ``run`` function.
This method performs o... | [
"def",
"setup_directories",
"(",
"self",
",",
"use_sudo",
"=",
"True",
")",
":",
"runner",
"=",
"self",
".",
"_runner",
".",
"sudo",
"if",
"use_sudo",
"else",
"self",
".",
"_runner",
".",
"run",
"runner",
"(",
"\"mkdir -p '{0}'\"",
".",
"format",
"(",
"s... | 43.133333 | 0.003026 |
def cleanup(self, sched, coro):
"""Remove this coro from the waiting for signal queue."""
try:
sched.sigwait[self.name].remove((self, coro))
except ValueError:
pass
return True | [
"def",
"cleanup",
"(",
"self",
",",
"sched",
",",
"coro",
")",
":",
"try",
":",
"sched",
".",
"sigwait",
"[",
"self",
".",
"name",
"]",
".",
"remove",
"(",
"(",
"self",
",",
"coro",
")",
")",
"except",
"ValueError",
":",
"pass",
"return",
"True"
] | 33.142857 | 0.008403 |
def parse_xml(self, node):
""" Parse a Tile Layer from ElementTree xml node
:param node: ElementTree xml node
:return: self
"""
import struct
import array
self._set_properties(node)
data = None
next_gid = None
data_node = node.find('data'... | [
"def",
"parse_xml",
"(",
"self",
",",
"node",
")",
":",
"import",
"struct",
"import",
"array",
"self",
".",
"_set_properties",
"(",
"node",
")",
"data",
"=",
"None",
"next_gid",
"=",
"None",
"data_node",
"=",
"node",
".",
"find",
"(",
"'data'",
")",
"e... | 32.72 | 0.001187 |
def split(self, cutting_points, shift_times=False, overlap=0.0):
"""
Split the label-list into x parts and return them as new label-lists.
x is defined by the number of cutting-points(``x == len(cutting_points) + 1``)
The result is a list of label-lists corresponding to each part.
... | [
"def",
"split",
"(",
"self",
",",
"cutting_points",
",",
"shift_times",
"=",
"False",
",",
"overlap",
"=",
"0.0",
")",
":",
"if",
"len",
"(",
"cutting_points",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'At least one cutting-point is needed!'",
")",
"... | 33.472222 | 0.002418 |
def delete_features(host_name, client_name, client_pass, feature_names=None):
"""
Remove a number of numerical features in the client. If a list is not provided, remove all features.
Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted.
- cli... | [
"def",
"delete_features",
"(",
"host_name",
",",
"client_name",
",",
"client_pass",
",",
"feature_names",
"=",
"None",
")",
":",
"# Get all features.",
"if",
"feature_names",
"is",
"None",
":",
"feature_names",
"=",
"get_feature_names",
"(",
"host_name",
",",
"cli... | 46.125 | 0.00354 |
def _Viscosity(rho, T, fase=None, drho=None):
"""Equation for the Viscosity
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
fase: dict, optional for calculate critical enhancement
phase properties
drho: float, optional for calculate crit... | [
"def",
"_Viscosity",
"(",
"rho",
",",
"T",
",",
"fase",
"=",
"None",
",",
"drho",
"=",
"None",
")",
":",
"Tr",
"=",
"T",
"/",
"Tc",
"Dr",
"=",
"rho",
"/",
"rhoc",
"# Eq 11",
"H",
"=",
"[",
"1.67752",
",",
"2.20462",
",",
"0.6366564",
",",
"-",
... | 27.551724 | 0.000805 |
def ch_handler(offset=0, length=-1, **kw):
""" Handle standard PRIMARY clipboard access. Note that offset and length
are passed as strings. This differs from CLIPBOARD. """
global _lastSel
offset = int(offset)
length = int(length)
if length < 0: length = len(_lastSel)
return _lastSel[offs... | [
"def",
"ch_handler",
"(",
"offset",
"=",
"0",
",",
"length",
"=",
"-",
"1",
",",
"*",
"*",
"kw",
")",
":",
"global",
"_lastSel",
"offset",
"=",
"int",
"(",
"offset",
")",
"length",
"=",
"int",
"(",
"length",
")",
"if",
"length",
"<",
"0",
":",
... | 36.555556 | 0.005935 |
def handle_unsubscribe_request(cls, request, message, dispatch, hash_is_valid, redirect_to):
"""Handles user subscription cancelling request.
:param Request request: Request instance
:param Message message: Message model instance
:param Dispatch dispatch: Dispatch model instance
... | [
"def",
"handle_unsubscribe_request",
"(",
"cls",
",",
"request",
",",
"message",
",",
"dispatch",
",",
"hash_is_valid",
",",
"redirect_to",
")",
":",
"if",
"hash_is_valid",
":",
"Subscription",
".",
"cancel",
"(",
"dispatch",
".",
"recipient_id",
"or",
"dispatch... | 40.666667 | 0.005721 |
def receive(args, reactor=reactor, _debug_stash_wormhole=None):
"""I implement 'wormhole receive'. I return a Deferred that fires with
None (for success), or signals one of the following errors:
* WrongPasswordError: the two sides didn't use matching passwords
* Timeout: something didn't happen fast eno... | [
"def",
"receive",
"(",
"args",
",",
"reactor",
"=",
"reactor",
",",
"_debug_stash_wormhole",
"=",
"None",
")",
":",
"r",
"=",
"Receiver",
"(",
"args",
",",
"reactor",
")",
"d",
"=",
"r",
".",
"go",
"(",
")",
"if",
"_debug_stash_wormhole",
"is",
"not",
... | 46.538462 | 0.001621 |
def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(StrainCreate, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"StrainCreate",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 59 | 0.011173 |
def canonical_fix_name(fix, avail_fixes):
"""
Examples:
>>> canonical_fix_name('fix_wrap_text_literals')
'libfuturize.fixes.fix_wrap_text_literals'
>>> canonical_fix_name('wrap_text_literals')
'libfuturize.fixes.fix_wrap_text_literals'
>>> canonical_fix_name('wrap_te')
ValueError("unknow... | [
"def",
"canonical_fix_name",
"(",
"fix",
",",
"avail_fixes",
")",
":",
"if",
"\".fix_\"",
"in",
"fix",
":",
"return",
"fix",
"else",
":",
"if",
"fix",
".",
"startswith",
"(",
"'fix_'",
")",
":",
"fix",
"=",
"fix",
"[",
"4",
":",
"]",
"# Infer the full ... | 38.586207 | 0.002616 |
def to_serializable_value(self):
"""
Parses the Hightonmodel to a serializable value such dicts, lists, strings
This can be used to save the model in a NoSQL database
:return: the serialized HightonModel
:rtype: dict
"""
return_dict = {}
for name, field i... | [
"def",
"to_serializable_value",
"(",
"self",
")",
":",
"return_dict",
"=",
"{",
"}",
"for",
"name",
",",
"field",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"field",
",",
"fields",
".",
"Field",
")",
":",
"re... | 36.384615 | 0.006186 |
def convert_bytes(value):
"""
Reduces bytes to more convenient units (i.e. KiB, GiB, TiB, etc.).
Args:
values (int): Value in Bytes
Returns:
tup (tuple): Tuple of value, unit (e.g. (10, 'MiB'))
"""
n = np.rint(len(str(value))/4).astype(int)
return value/(1024**n), sizes[n] | [
"def",
"convert_bytes",
"(",
"value",
")",
":",
"n",
"=",
"np",
".",
"rint",
"(",
"len",
"(",
"str",
"(",
"value",
")",
")",
"/",
"4",
")",
".",
"astype",
"(",
"int",
")",
"return",
"value",
"/",
"(",
"1024",
"**",
"n",
")",
",",
"sizes",
"["... | 25.666667 | 0.003135 |
def go(function_expr, **kwargs):
"""
CloudAux.go(
'list_aliases',
**{
'account_number': '000000000000',
'assume_role': 'role_name',
'session_name': 'cloudaux',
'region': 'us-east-1',
'tech': 'kms',
... | [
"def",
"go",
"(",
"function_expr",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'.'",
"in",
"function_expr",
":",
"tech",
",",
"service_type",
",",
"function_name",
"=",
"function_expr",
".",
"split",
"(",
"'.'",
")",
"else",
":",
"tech",
"=",
"kwargs",
"... | 33.485714 | 0.001658 |
def format_results(self, raw_data, options):
'''
Returns a python structure that later gets serialized.
raw_data
full list of objects matching the search term
options
a dictionary of the given options
'''
page_data = self.paginate_results(raw_data,... | [
"def",
"format_results",
"(",
"self",
",",
"raw_data",
",",
"options",
")",
":",
"page_data",
"=",
"self",
".",
"paginate_results",
"(",
"raw_data",
",",
"options",
")",
"results",
"=",
"{",
"}",
"meta",
"=",
"options",
".",
"copy",
"(",
")",
"meta",
"... | 40.578947 | 0.003802 |
def get_weekday_parameters(self, filename='shlp_weekday_factors.csv'):
""" Retrieve the weekday parameter from csv-file
Parameters
----------
filename : string
name of file where sigmoid factors are stored
"""
file = os.path.join(self.datapath, filename)
... | [
"def",
"get_weekday_parameters",
"(",
"self",
",",
"filename",
"=",
"'shlp_weekday_factors.csv'",
")",
":",
"file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"datapath",
",",
"filename",
")",
"f_df",
"=",
"pd",
".",
"read_csv",
"(",
"file",
... | 37.947368 | 0.002706 |
def itertwo(iterable, wrap=False):
r"""
equivalent to iter_window(iterable, 2, 1, wrap)
Args:
iterable (iter): an iterable sequence
wrap (bool): if True, returns with wraparound
Returns:
iter: returns edges in a sequence
CommandLine:
python -m utool.util_iter --tes... | [
"def",
"itertwo",
"(",
"iterable",
",",
"wrap",
"=",
"False",
")",
":",
"# it.tee may be slow, but works on all iterables",
"iter1",
",",
"iter2",
"=",
"it",
".",
"tee",
"(",
"iterable",
",",
"2",
")",
"if",
"wrap",
":",
"iter2",
"=",
"it",
".",
"cycle",
... | 31.27381 | 0.000369 |
def stage_config(self):
"""
A shortcut property for settings of a stage.
"""
def get_stage_setting(stage, extended_stages=None):
if extended_stages is None:
extended_stages = []
if stage in extended_stages:
raise RuntimeError(stag... | [
"def",
"stage_config",
"(",
"self",
")",
":",
"def",
"get_stage_setting",
"(",
"stage",
",",
"extended_stages",
"=",
"None",
")",
":",
"if",
"extended_stages",
"is",
"None",
":",
"extended_stages",
"=",
"[",
"]",
"if",
"stage",
"in",
"extended_stages",
":",
... | 39.857143 | 0.004899 |
def cache_file(filename):
"""Caches a file locally if possible.
If caching was succesfull, or if
the file was previously successfully cached, this method returns the
path to the local copy of the file. If not, it returns the path to
the original file.
Parameters
----------
filename : s... | [
"def",
"cache_file",
"(",
"filename",
")",
":",
"dataset_local_dir",
"=",
"config",
".",
"local_data_path",
"dataset_remote_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"if",
"dataset_remote_dir",
"==",
"\"\"",
"or",
"dataset_local_dir",
"... | 39.72 | 0.000164 |
def _getInputValue(self, obj, fieldName):
"""
Gets the value of a given field from the input record
"""
if isinstance(obj, dict):
if not fieldName in obj:
knownFields = ", ".join(
key for key in obj.keys() if not key.startswith("_")
)
raise ValueError(
"... | [
"def",
"_getInputValue",
"(",
"self",
",",
"obj",
",",
"fieldName",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"if",
"not",
"fieldName",
"in",
"obj",
":",
"knownFields",
"=",
"\", \"",
".",
"join",
"(",
"key",
"for",
"key",
"in"... | 34.315789 | 0.007463 |
def reload_neuropythy():
'''
reload_neuropythy() reloads all of the modules of neuropythy and returns the reloaded
neuropythy module. This is similar to reload(neuropythy) except that it reloads all the
neuropythy submodules prior to reloading neuropythy.
Example:
import neuropythy as ny
... | [
"def",
"reload_neuropythy",
"(",
")",
":",
"import",
"sys",
",",
"six",
"if",
"not",
"six",
".",
"PY2",
":",
"try",
":",
"from",
"importlib",
"import",
"reload",
"except",
"Exception",
":",
"from",
"imp",
"import",
"reload",
"for",
"mdl",
"in",
"submodul... | 36.631579 | 0.009804 |
def convert_image(File, verbose=False):
"""
Converts a IMAGE data type stored in the database into a data cube
Parameters
----------
File: str
The URL or filepath of the file to be converted into arrays.
verbose: bool
Whether or not to display some diagnostic information (Defaul... | [
"def",
"convert_image",
"(",
"File",
",",
"verbose",
"=",
"False",
")",
":",
"image",
",",
"header",
"=",
"''",
",",
"''",
"if",
"isinstance",
"(",
"File",
",",
"type",
"(",
"b''",
")",
")",
":",
"# Decode if needed (ie, for Python 3)",
"File",
"=",
"Fil... | 33.481013 | 0.007712 |
def load_vi_bindings(get_search_state=None):
"""
Vi extensions.
# Overview of Readline Vi commands:
# http://www.catonmat.net/download/bash-vi-editing-mode-cheat-sheet.pdf
:param get_search_state: None or a callable that takes a
CommandLineInterface and returns a SearchState.
"""
... | [
"def",
"load_vi_bindings",
"(",
"get_search_state",
"=",
"None",
")",
":",
"# Note: Some key bindings have the \"~IsReadOnly()\" filter added. This",
"# prevents the handler to be executed when the focus is on a",
"# read-only buffer.",
"# This is however only required for th... | 34.553584 | 0.002296 |
def create_init(attrs):
"""Create an __init__ method that sets all the attributes
necessary for the function the Descriptor invokes to check the
value.
"""
args = ", ".join(attrs)
vals = ", ".join(['getattr(self, "{}")'.format(attr) for attr in attrs])
attr_lines = "\n ".join(
["... | [
"def",
"create_init",
"(",
"attrs",
")",
":",
"args",
"=",
"\", \"",
".",
"join",
"(",
"attrs",
")",
"vals",
"=",
"\", \"",
".",
"join",
"(",
"[",
"'getattr(self, \"{}\")'",
".",
"format",
"(",
"attr",
")",
"for",
"attr",
"in",
"attrs",
"]",
")",
"at... | 36.944444 | 0.001466 |
async def first(self):
"""Fetch the first row and then close the result set unconditionally.
Returns None if no row is present.
"""
if self._metadata is None:
self._non_result()
try:
return (await self.fetchone())
finally:
await self.c... | [
"async",
"def",
"first",
"(",
"self",
")",
":",
"if",
"self",
".",
"_metadata",
"is",
"None",
":",
"self",
".",
"_non_result",
"(",
")",
"try",
":",
"return",
"(",
"await",
"self",
".",
"fetchone",
"(",
")",
")",
"finally",
":",
"await",
"self",
".... | 28.727273 | 0.006135 |
def index(self, attr):
"""
Indexes the :class:`.Paper`\s in this :class:`.Corpus` instance
by the attribute ``attr``.
New indices are added to :attr:`.indices`\.
Parameters
----------
attr : str
The name of a :class:`.Paper` attribute.
"""
... | [
"def",
"index",
"(",
"self",
",",
"attr",
")",
":",
"for",
"i",
",",
"paper",
"in",
"self",
".",
"indexed_papers",
".",
"iteritems",
"(",
")",
":",
"self",
".",
"index_paper_by_attr",
"(",
"paper",
",",
"attr",
")"
] | 25.6875 | 0.00939 |
def determine_hostname(display_name=None):
"""
Find fqdn if we can
"""
if display_name:
# if display_name is provided, just return the given name
return display_name
else:
socket_gethostname = socket.gethostname()
socket_fqdn = socket.getfqdn()
try:
... | [
"def",
"determine_hostname",
"(",
"display_name",
"=",
"None",
")",
":",
"if",
"display_name",
":",
"# if display_name is provided, just return the given name",
"return",
"display_name",
"else",
":",
"socket_gethostname",
"=",
"socket",
".",
"gethostname",
"(",
")",
"so... | 30.740741 | 0.001168 |
def get_context_data(self, **kwargs):
"""Includes the metrics slugs in the context."""
r = get_r()
data = super(AggregateHistoryView, self).get_context_data(**kwargs)
slug_set = set(kwargs['slugs'].split('+'))
granularity = kwargs.get('granularity', 'daily')
# Accept GET... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"get_r",
"(",
")",
"data",
"=",
"super",
"(",
"AggregateHistoryView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"slug_set",
"=",
"set",
... | 39.333333 | 0.002364 |
def remove_empties(variable):
"""Remove empty objects from the *variable*'s attrs."""
import h5py
for key, val in variable.attrs.items():
if isinstance(val, h5py._hl.base.Empty):
variable.attrs.pop(key)
return variable | [
"def",
"remove_empties",
"(",
"variable",
")",
":",
"import",
"h5py",
"for",
"key",
",",
"val",
"in",
"variable",
".",
"attrs",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"h5py",
".",
"_hl",
".",
"base",
".",
"Empty",
")",
":... | 31 | 0.003922 |
def dequeue(self, destination):
"""
Removes and returns an item from the queue (or C{None} if no items in queue).
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: The first frame in the specified queue, or C{None} if there are none.
... | [
"def",
"dequeue",
"(",
"self",
",",
"destination",
")",
":",
"if",
"not",
"self",
".",
"has_frames",
"(",
"destination",
")",
":",
"return",
"None",
"message_id",
"=",
"self",
".",
"queue_metadata",
"[",
"destination",
"]",
"[",
"'frames'",
"]",
".",
"po... | 30.73913 | 0.006859 |
def export(self, timestamp=None, info={}):
"""
Export the archive, directory or file.
"""
tval = tuple(time.localtime()) if timestamp is None else timestamp
tstamp = time.strftime(self.timestamp_format, tval)
info = dict(info, timestamp=tstamp)
export_name = self... | [
"def",
"export",
"(",
"self",
",",
"timestamp",
"=",
"None",
",",
"info",
"=",
"{",
"}",
")",
":",
"tval",
"=",
"tuple",
"(",
"time",
".",
"localtime",
"(",
")",
")",
"if",
"timestamp",
"is",
"None",
"else",
"timestamp",
"tstamp",
"=",
"time",
".",... | 44.869565 | 0.001898 |
def run(self):
"""
the main loop
"""
try:
master_process = BackgroundProcess.objects.filter(pk=self.process_id).first()
if master_process:
master_process.last_update = now()
master_process.message = 'init child processes'
... | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"master_process",
"=",
"BackgroundProcess",
".",
"objects",
".",
"filter",
"(",
"pk",
"=",
"self",
".",
"process_id",
")",
".",
"first",
"(",
")",
"if",
"master_process",
":",
"master_process",
".",
"last_... | 37.890909 | 0.002806 |
def plot(self, columns=None, parameter=None, **errorbar_kwargs):
"""
Produces a visual representation of the coefficients, including their standard errors and magnitudes.
Parameters
----------
columns : list, optional
specify a subset of the columns to plot
e... | [
"def",
"plot",
"(",
"self",
",",
"columns",
"=",
"None",
",",
"parameter",
"=",
"None",
",",
"*",
"*",
"errorbar_kwargs",
")",
":",
"from",
"matplotlib",
"import",
"pyplot",
"as",
"plt",
"set_kwargs_ax",
"(",
"errorbar_kwargs",
")",
"ax",
"=",
"errorbar_kw... | 35.764706 | 0.002401 |
def get_key(self, command, args):
"""Returns the key a command operates on."""
spec = COMMANDS.get(command.upper())
if spec is None:
raise UnroutableCommand('The command "%r" is unknown to the '
'router and cannot be handled as a '
... | [
"def",
"get_key",
"(",
"self",
",",
"command",
",",
"args",
")",
":",
"spec",
"=",
"COMMANDS",
".",
"get",
"(",
"command",
".",
"upper",
"(",
")",
")",
"if",
"spec",
"is",
"None",
":",
"raise",
"UnroutableCommand",
"(",
"'The command \"%r\" is unknown to t... | 42.846154 | 0.001756 |
def get_droplet(self, droplet_id):
"""
Return a Droplet by its ID.
"""
return Droplet.get_object(api_token=self.token, droplet_id=droplet_id) | [
"def",
"get_droplet",
"(",
"self",
",",
"droplet_id",
")",
":",
"return",
"Droplet",
".",
"get_object",
"(",
"api_token",
"=",
"self",
".",
"token",
",",
"droplet_id",
"=",
"droplet_id",
")"
] | 34.6 | 0.011299 |
def _create_cadvisor_prometheus_instance(self, instance):
"""
Create a copy of the instance and set default values.
This is so the base class can create a scraper_config with the proper values.
"""
cadvisor_instance = deepcopy(instance)
cadvisor_instance.update(
... | [
"def",
"_create_cadvisor_prometheus_instance",
"(",
"self",
",",
"instance",
")",
":",
"cadvisor_instance",
"=",
"deepcopy",
"(",
"instance",
")",
"cadvisor_instance",
".",
"update",
"(",
"{",
"'namespace'",
":",
"self",
".",
"NAMESPACE",
",",
"# We need to specify ... | 53.25641 | 0.004255 |
def span(self, name='child_span'):
"""Create a child span for the current span and append it to the child
spans list.
:type name: str
:param name: (Optional) The name of the child span.
:rtype: :class: `~opencensus.trace.span.Span`
:returns: A child Span to be added to ... | [
"def",
"span",
"(",
"self",
",",
"name",
"=",
"'child_span'",
")",
":",
"child_span",
"=",
"Span",
"(",
"name",
",",
"parent_span",
"=",
"self",
")",
"self",
".",
"_child_spans",
".",
"append",
"(",
"child_span",
")",
"return",
"child_span"
] | 35.230769 | 0.004255 |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(SquidCollector, self).get_default_config()
config.update({
'hosts': ['localhost:3128'],
'path': 'squid',
})
return config | [
"def",
"get_default_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"SquidCollector",
",",
"self",
")",
".",
"get_default_config",
"(",
")",
"config",
".",
"update",
"(",
"{",
"'hosts'",
":",
"[",
"'localhost:3128'",
"]",
",",
"'path'",
":",
... | 28.4 | 0.006826 |
def unregister(self, event, callback, selector=None):
"""
Unregisters an event that was being monitored.
:param event: Name of the event to monitor
:param callback: Callback function for when the event is received (Params: event, interface).
:param selector: `(Optional)` CSS sel... | [
"def",
"unregister",
"(",
"self",
",",
"event",
",",
"callback",
",",
"selector",
"=",
"None",
")",
":",
"self",
".",
"processor",
".",
"unregister",
"(",
"event",
",",
"callback",
",",
"selector",
")"
] | 47.666667 | 0.009153 |
def find_attacker_slider(dest_list, occ_bb, piece_bb, target_bb, pos,
domain):
""" Find a slider attacker
Parameters
----------
dest_list : list
To store the results.
occ_bb : int, bitboard
Occupancy bitboard.
piece_bb : int, bitboard
Bitboar... | [
"def",
"find_attacker_slider",
"(",
"dest_list",
",",
"occ_bb",
",",
"piece_bb",
",",
"target_bb",
",",
"pos",
",",
"domain",
")",
":",
"pos_map",
",",
"domain_trans",
",",
"pos_inv_map",
"=",
"domain",
"r",
"=",
"reach",
"[",
"pos_map",
"(",
"pos",
")",
... | 34.029412 | 0.002521 |
def msg(self, msg):
'''Emit a message. Override to customize log spam.'''
hookenv.log('coordinator.{} {}'.format(self._name(), msg),
level=hookenv.INFO) | [
"def",
"msg",
"(",
"self",
",",
"msg",
")",
":",
"hookenv",
".",
"log",
"(",
"'coordinator.{} {}'",
".",
"format",
"(",
"self",
".",
"_name",
"(",
")",
",",
"msg",
")",
",",
"level",
"=",
"hookenv",
".",
"INFO",
")"
] | 46.25 | 0.010638 |
def check_array(array, accept_sparse=None, dtype=None, order=None, copy=False,
force_all_finite=True, ensure_2d=True, allow_nd=False):
"""Input validation on an array, list, sparse matrix or similar.
By default, the input is converted to an at least 2nd numpy array.
Parameters
--------... | [
"def",
"check_array",
"(",
"array",
",",
"accept_sparse",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"order",
"=",
"None",
",",
"copy",
"=",
"False",
",",
"force_all_finite",
"=",
"True",
",",
"ensure_2d",
"=",
"True",
",",
"allow_nd",
"=",
"False",
... | 34.909091 | 0.000507 |
def get(path, objectType, user=None):
'''
Get the ACL of an object. Will filter by user if one is provided.
Args:
path: The path to the object
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
user: A user name to filter by
Returns (dict): A dictionary containing the A... | [
"def",
"get",
"(",
"path",
",",
"objectType",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'Path'",
":",
"path",
",",
"'ACLs'",
":",
"[",
"]",
"}",
"sidRet",
"=",
"_getUserSid",
"(",
"user",
")",
"if",
"path",
"and",
"objectType",
":",
"... | 29.363636 | 0.000999 |
def get_emails(self, limit=100, offset=0, conditions={}):
"""
Get all certified emails
"""
url = self.EMAILS_URL + "?limit=%s&offset=%s" % (limit, offset)
for key, value in conditions.items():
if key is 'ids':
value = ",".join(value)
url ... | [
"def",
"get_emails",
"(",
"self",
",",
"limit",
"=",
"100",
",",
"offset",
"=",
"0",
",",
"conditions",
"=",
"{",
"}",
")",
":",
"url",
"=",
"self",
".",
"EMAILS_URL",
"+",
"\"?limit=%s&offset=%s\"",
"%",
"(",
"limit",
",",
"offset",
")",
"for",
"key... | 29.125 | 0.004158 |
def get_point_in_block(cls, x, y, block_idx, block_size):
"""Get point coordinates in next block.
Parameters
----------
x : `int`
X coordinate in current block.
y : `int`
Y coordinate in current block.
block_index : `int`
Current block... | [
"def",
"get_point_in_block",
"(",
"cls",
",",
"x",
",",
"y",
",",
"block_idx",
",",
"block_size",
")",
":",
"if",
"block_idx",
"==",
"0",
":",
"return",
"y",
",",
"x",
"if",
"block_idx",
"==",
"1",
":",
"return",
"x",
",",
"y",
"+",
"block_size",
"... | 27.735294 | 0.002049 |
def exists(self, path_or_index):
"""
Checks if a path exists in the document. This is meant to be used
for a corresponding :meth:`~couchbase.subdocument.exists` request.
:param path_or_index: The path (or index) to check
:return: `True` if the path exists, `False` if the path do... | [
"def",
"exists",
"(",
"self",
",",
"path_or_index",
")",
":",
"result",
"=",
"self",
".",
"_resolve",
"(",
"path_or_index",
")",
"if",
"not",
"result",
"[",
"0",
"]",
":",
"return",
"True",
"elif",
"E",
".",
"SubdocPathNotFoundError",
".",
"_can_derive",
... | 40.529412 | 0.002837 |
def checkbox(self, model_view, id_, attr, value):
"""endpoint for checking/unchecking any boolean in a sqla model"""
modelview_to_model = {
'{}ColumnInlineView'.format(name.capitalize()): source.column_class
for name, source in ConnectorRegistry.sources.items()
}
... | [
"def",
"checkbox",
"(",
"self",
",",
"model_view",
",",
"id_",
",",
"attr",
",",
"value",
")",
":",
"modelview_to_model",
"=",
"{",
"'{}ColumnInlineView'",
".",
"format",
"(",
"name",
".",
"capitalize",
"(",
")",
")",
":",
"source",
".",
"column_class",
... | 43.75 | 0.002797 |
def get_list(medium, user, credentials):
"""Returns a MediumList (Anime or Manga depends on [medium]) of user.
If user is not given, the username is taken from the initialized auth
credentials.
:param medium Anime or manga (tokens.Medium.Anime or tokens.Medium.Manga)
:param user The user whose lis... | [
"def",
"get_list",
"(",
"medium",
",",
"user",
",",
"credentials",
")",
":",
"helpers",
".",
"check_creds",
"(",
"credentials",
",",
"header",
")",
"list_url",
"=",
"helpers",
".",
"get_list_url",
"(",
"medium",
",",
"user",
")",
"#for some reason, we don't ne... | 48.647059 | 0.004745 |
def write(self, text):
"""Send a packet to the socket. This function cooks output."""
text = str(text) # eliminate any unicode or other snigglets
text = text.replace(IAC, IAC+IAC)
text = text.replace(chr(10), chr(13)+chr(10))
self.writecooked(text) | [
"def",
"write",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"str",
"(",
"text",
")",
"# eliminate any unicode or other snigglets",
"text",
"=",
"text",
".",
"replace",
"(",
"IAC",
",",
"IAC",
"+",
"IAC",
")",
"text",
"=",
"text",
".",
"replace",
"... | 47.666667 | 0.006873 |
def _do_run(cmd, checks, log_stdout=False):
"""Perform running and check results, raising errors for issues.
"""
cmd, shell_arg, executable_arg = _normalize_cmd_args(cmd)
s = subprocess.Popen(cmd, shell=shell_arg, executable=executable_arg,
stdout=subprocess.PIPE,
... | [
"def",
"_do_run",
"(",
"cmd",
",",
"checks",
",",
"log_stdout",
"=",
"False",
")",
":",
"cmd",
",",
"shell_arg",
",",
"executable_arg",
"=",
"_normalize_cmd_args",
"(",
"cmd",
")",
"s",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"s... | 38.75 | 0.001399 |
def unmarshal(self, values, bind_client=None):
"""
Cast the list.
"""
if values is not None:
return [super(EntityCollection, self).unmarshal(v, bind_client=bind_client) for v in values] | [
"def",
"unmarshal",
"(",
"self",
",",
"values",
",",
"bind_client",
"=",
"None",
")",
":",
"if",
"values",
"is",
"not",
"None",
":",
"return",
"[",
"super",
"(",
"EntityCollection",
",",
"self",
")",
".",
"unmarshal",
"(",
"v",
",",
"bind_client",
"=",... | 37.333333 | 0.0131 |
def medfilt(vector, window):
"""
Apply a window-length median filter to a 1D array vector.
Should get rid of 'spike' value 15.
>>> print(medfilt(np.array([1., 15., 1., 1., 1.]), 3))
[1. 1. 1. 1. 1.]
The 'edge' case is a bit tricky...
>>> print(medfilt(np.array([15., 1., 1., 1., 1.]), 3))
... | [
"def",
"medfilt",
"(",
"vector",
",",
"window",
")",
":",
"if",
"not",
"window",
"%",
"2",
"==",
"1",
":",
"raise",
"ValueError",
"(",
"\"Median filter length must be odd.\"",
")",
"if",
"not",
"vector",
".",
"ndim",
"==",
"1",
":",
"raise",
"ValueError",
... | 31.066667 | 0.001041 |
def unregister_path(self, path):
"""
Unregisters given path.
:param path: Path name.
:type path: unicode
:return: Method success.
:rtype: bool
"""
if not path in self:
raise umbra.exceptions.PathExistsError("{0} | '{1}' path isn't registered!... | [
"def",
"unregister_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"path",
"in",
"self",
":",
"raise",
"umbra",
".",
"exceptions",
".",
"PathExistsError",
"(",
"\"{0} | '{1}' path isn't registered!\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",... | 26 | 0.009281 |
def barracks_in_middle(self) -> Point2:
""" Barracks position in the middle of the 2 depots """
if len(self.upper2_for_ramp_wall) == 2:
points = self.upper2_for_ramp_wall
p1 = points.pop().offset((self.x_offset, self.y_offset))
p2 = points.pop().offset((self.x_offset,... | [
"def",
"barracks_in_middle",
"(",
"self",
")",
"->",
"Point2",
":",
"if",
"len",
"(",
"self",
".",
"upper2_for_ramp_wall",
")",
"==",
"2",
":",
"points",
"=",
"self",
".",
"upper2_for_ramp_wall",
"p1",
"=",
"points",
".",
"pop",
"(",
")",
".",
"offset",
... | 62.909091 | 0.004274 |
def find_default(self, filename):
"""
A generate which looks in common folders for the default configuration
file. The paths goes from system defaults to user specific files.
:param filename: The name of the file to find
:return: The complete path to the found files
"""
... | [
"def",
"find_default",
"(",
"self",
",",
"filename",
")",
":",
"for",
"path",
"in",
"self",
".",
"DEFAULT_PATH",
":",
"# Normalize path",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"expandvars",
"(",
"path",
")",
")... | 40.6 | 0.00321 |
def getFieldMax(self, fieldName):
"""
If underlying implementation does not support min/max stats collection,
or if a field type does not support min/max (non scalars), the return
value will be None.
:param fieldName: (string) name of field to get max
:returns: current maximum value for the fie... | [
"def",
"getFieldMax",
"(",
"self",
",",
"fieldName",
")",
":",
"stats",
"=",
"self",
".",
"getStats",
"(",
")",
"if",
"stats",
"==",
"None",
":",
"return",
"None",
"maxValues",
"=",
"stats",
".",
"get",
"(",
"'max'",
",",
"None",
")",
"if",
"maxValue... | 32.823529 | 0.008711 |
def sliding_window(sequence, win_size, step=1):
"""
Returns a generator that will iterate through
the defined chunks of input sequence. Input sequence
must be iterable.
Credit: http://scipher.wordpress.com/2010/12/02/simple-sliding-window-iterator-in-python/
https://github.com/xguse/scipherPyP... | [
"def",
"sliding_window",
"(",
"sequence",
",",
"win_size",
",",
"step",
"=",
"1",
")",
":",
"# Verify the inputs",
"try",
":",
"it",
"=",
"iter",
"(",
"sequence",
")",
"except",
"TypeError",
":",
"raise",
"ValueError",
"(",
"\"sequence must be iterable.\"",
")... | 36.033333 | 0.004505 |
def intervals(annotation, **kwargs):
'''Plotting wrapper for labeled intervals'''
times, labels = annotation.to_interval_values()
return mir_eval.display.labeled_intervals(times, labels, **kwargs) | [
"def",
"intervals",
"(",
"annotation",
",",
"*",
"*",
"kwargs",
")",
":",
"times",
",",
"labels",
"=",
"annotation",
".",
"to_interval_values",
"(",
")",
"return",
"mir_eval",
".",
"display",
".",
"labeled_intervals",
"(",
"times",
",",
"labels",
",",
"*",... | 41 | 0.004785 |
def add(self, user, status=None, symmetrical=False):
"""
Add a relationship from one user to another with the given status,
which defaults to "following".
Adding a relationship is by default asymmetrical (akin to following
someone on twitter). Specify a symmetrical relationship... | [
"def",
"add",
"(",
"self",
",",
"user",
",",
"status",
"=",
"None",
",",
"symmetrical",
"=",
"False",
")",
":",
"if",
"not",
"status",
":",
"status",
"=",
"RelationshipStatus",
".",
"objects",
".",
"following",
"(",
")",
"relationship",
",",
"created",
... | 35.821429 | 0.002913 |
def decode_csr(self, csr):
"""Decode a CSR and return its data."""
response = self.request(E.decodeCsrSslCertRequest(
E.csr(csr)
))
return response.data | [
"def",
"decode_csr",
"(",
"self",
",",
"csr",
")",
":",
"response",
"=",
"self",
".",
"request",
"(",
"E",
".",
"decodeCsrSslCertRequest",
"(",
"E",
".",
"csr",
"(",
"csr",
")",
")",
")",
"return",
"response",
".",
"data"
] | 23.875 | 0.010101 |
def get_fg_bg(powerline, name, is_last_dir):
"""Returns the foreground and background color to use for the given name.
"""
if requires_special_home_display(powerline, name):
return (powerline.theme.HOME_FG, powerline.theme.HOME_BG,)
if is_last_dir:
return (powerline.theme.CWD_FG, powerl... | [
"def",
"get_fg_bg",
"(",
"powerline",
",",
"name",
",",
"is_last_dir",
")",
":",
"if",
"requires_special_home_display",
"(",
"powerline",
",",
"name",
")",
":",
"return",
"(",
"powerline",
".",
"theme",
".",
"HOME_FG",
",",
"powerline",
".",
"theme",
".",
... | 40.7 | 0.002404 |
def get_sample_data(sample_file):
"""Read and returns sample data to fill form with default sample sequence. """
sequence_sample_in_fasta = None
with open(sample_file) as handle:
sequence_sample_in_fasta = handle.read()
return sequence_sample_in_fasta | [
"def",
"get_sample_data",
"(",
"sample_file",
")",
":",
"sequence_sample_in_fasta",
"=",
"None",
"with",
"open",
"(",
"sample_file",
")",
"as",
"handle",
":",
"sequence_sample_in_fasta",
"=",
"handle",
".",
"read",
"(",
")",
"return",
"sequence_sample_in_fasta"
] | 33.875 | 0.007194 |
def scalar_inc_dec(word, valence, is_cap_diff):
"""
Check if the preceding words increase, decrease, or negate/nullify the
valence
"""
scalar = 0.0
word_lower = word.lower()
if word_lower in BOOSTER_DICT:
scalar = BOOSTER_DICT[word_lower]
if valence < 0:
scalar *=... | [
"def",
"scalar_inc_dec",
"(",
"word",
",",
"valence",
",",
"is_cap_diff",
")",
":",
"scalar",
"=",
"0.0",
"word_lower",
"=",
"word",
".",
"lower",
"(",
")",
"if",
"word_lower",
"in",
"BOOSTER_DICT",
":",
"scalar",
"=",
"BOOSTER_DICT",
"[",
"word_lower",
"]... | 30.888889 | 0.001745 |
def pick_frequency_line(self, filename, frequency, cumulativefield='cumulative_frequency'):
'''Given a numeric frequency, pick a line from a csv with a cumulative frequency field'''
if resource_exists('censusname', filename):
with closing(resource_stream('censusname', filename)) as b:
... | [
"def",
"pick_frequency_line",
"(",
"self",
",",
"filename",
",",
"frequency",
",",
"cumulativefield",
"=",
"'cumulative_frequency'",
")",
":",
"if",
"resource_exists",
"(",
"'censusname'",
",",
"filename",
")",
":",
"with",
"closing",
"(",
"resource_stream",
"(",
... | 65 | 0.006745 |
def checkout(self, branch_name):
""" Checkout a branch by name. """
try:
find(
self.repo.branches, lambda b: b.name == branch_name
).checkout()
except OrigCheckoutError as e:
raise CheckoutError(branch_name, details=e) | [
"def",
"checkout",
"(",
"self",
",",
"branch_name",
")",
":",
"try",
":",
"find",
"(",
"self",
".",
"repo",
".",
"branches",
",",
"lambda",
"b",
":",
"b",
".",
"name",
"==",
"branch_name",
")",
".",
"checkout",
"(",
")",
"except",
"OrigCheckoutError",
... | 36.75 | 0.006645 |
def _anonymize_table(cls, table_data, pii_fields):
"""Anonymize in `table_data` the fields in `pii_fields`.
Args:
table_data (pandas.DataFrame): Original dataframe/table.
pii_fields (list[dict]): Metadata for the fields to transform.
Result:
pandas.DataFrame... | [
"def",
"_anonymize_table",
"(",
"cls",
",",
"table_data",
",",
"pii_fields",
")",
":",
"for",
"pii_field",
"in",
"pii_fields",
":",
"field_name",
"=",
"pii_field",
"[",
"'name'",
"]",
"transformer",
"=",
"cls",
".",
"get_class",
"(",
"TRANSFORMERS",
"[",
"'c... | 37.5625 | 0.003247 |
def asym_list_diff(list1, list2):
""" Asymmetric list difference """
diff_list = []
for item in list1:
if not item in list2:
diff_list.append(item)
return diff_list | [
"def",
"asym_list_diff",
"(",
"list1",
",",
"list2",
")",
":",
"diff_list",
"=",
"[",
"]",
"for",
"item",
"in",
"list1",
":",
"if",
"not",
"item",
"in",
"list2",
":",
"diff_list",
".",
"append",
"(",
"item",
")",
"return",
"diff_list"
] | 27.714286 | 0.01 |
def set_authorization_password(self, password):
"""
Changes the authorization password of the account.
:type password: string
:param password: The new authorization password.
"""
self.authorization_password = password
self.changed_event.emit(self) | [
"def",
"set_authorization_password",
"(",
"self",
",",
"password",
")",
":",
"self",
".",
"authorization_password",
"=",
"password",
"self",
".",
"changed_event",
".",
"emit",
"(",
"self",
")"
] | 33 | 0.006557 |
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None if there
are no params of if the params are numpy.ndarrays."""
if not hasattr(instruction.op, 'params'):
return None
if all([isinstance(param, ndarray) for param in instruction... | [
"def",
"params_for_label",
"(",
"instruction",
")",
":",
"if",
"not",
"hasattr",
"(",
"instruction",
".",
"op",
",",
"'params'",
")",
":",
"return",
"None",
"if",
"all",
"(",
"[",
"isinstance",
"(",
"param",
",",
"ndarray",
")",
"for",
"param",
"in",
"... | 36.375 | 0.005025 |
def get_record_list(db_dir, records='all'):
"""
Get a list of records belonging to a database.
Parameters
----------
db_dir : str
The database directory, usually the same as the database slug.
The location to look for a RECORDS file.
records : list, optional
A Option use... | [
"def",
"get_record_list",
"(",
"db_dir",
",",
"records",
"=",
"'all'",
")",
":",
"# Full url physiobank database",
"db_url",
"=",
"posixpath",
".",
"join",
"(",
"config",
".",
"db_index_url",
",",
"db_dir",
")",
"# Check for a RECORDS file",
"if",
"records",
"==",... | 29.941176 | 0.001903 |
def build_parser():
"""Build argument parsers."""
parser = argparse.ArgumentParser("Release packages to pypi")
parser.add_argument('--check', '-c', action="store_true", help="Do a dry run without uploading")
parser.add_argument('component', help="The component to release as component-version")
retu... | [
"def",
"build_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"\"Release packages to pypi\"",
")",
"parser",
".",
"add_argument",
"(",
"'--check'",
",",
"'-c'",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Do a dry ru... | 46.142857 | 0.009119 |
def volume_rectangular(extents,
count,
transform=None):
"""
Return random samples inside a rectangular volume.
Parameters
----------
extents: (3,) float, side lengths of rectangular solid
count: int, number of points to return
transform: (... | [
"def",
"volume_rectangular",
"(",
"extents",
",",
"count",
",",
"transform",
"=",
"None",
")",
":",
"samples",
"=",
"np",
".",
"random",
".",
"random",
"(",
"(",
"count",
",",
"3",
")",
")",
"-",
".5",
"samples",
"*=",
"extents",
"if",
"transform",
"... | 29.863636 | 0.001475 |
def uniqued(iterable):
"""Return unique list of items preserving order.
>>> uniqued([3, 2, 1, 3, 2, 1, 0])
[3, 2, 1, 0]
"""
seen = set()
add = seen.add
return [i for i in iterable if i not in seen and not add(i)] | [
"def",
"uniqued",
"(",
"iterable",
")",
":",
"seen",
"=",
"set",
"(",
")",
"add",
"=",
"seen",
".",
"add",
"return",
"[",
"i",
"for",
"i",
"in",
"iterable",
"if",
"i",
"not",
"in",
"seen",
"and",
"not",
"add",
"(",
"i",
")",
"]"
] | 25.888889 | 0.004149 |
def _process_axsettings(self, hist, lims, ticks):
"""
Get axis settings options including ticks, x- and y-labels
and limits.
"""
axis_settings = dict(zip(self.axis_settings, [None, None, (None if self.overlaid else ticks)]))
return axis_settings | [
"def",
"_process_axsettings",
"(",
"self",
",",
"hist",
",",
"lims",
",",
"ticks",
")",
":",
"axis_settings",
"=",
"dict",
"(",
"zip",
"(",
"self",
".",
"axis_settings",
",",
"[",
"None",
",",
"None",
",",
"(",
"None",
"if",
"self",
".",
"overlaid",
... | 41 | 0.010239 |
def set_callback(self, ref, callback):
"""
Sets a callback for a ref (reference), setting to None will remove it
"""
# if the callback already exists, remove it
self.remove_callback(ref)
# add it to the callbacks
if callback is not None:
self._callbac... | [
"def",
"set_callback",
"(",
"self",
",",
"ref",
",",
"callback",
")",
":",
"# if the callback already exists, remove it",
"self",
".",
"remove_callback",
"(",
"ref",
")",
"# add it to the callbacks",
"if",
"callback",
"is",
"not",
"None",
":",
"self",
".",
"_callb... | 32.9 | 0.005917 |
def list_dscp_marking_rules(self, policy_id,
retrieve_all=True, **_params):
"""Fetches a list of all DSCP marking rules for the given policy."""
return self.list('dscp_marking_rules',
self.qos_dscp_marking_rules_path % policy_id,
... | [
"def",
"list_dscp_marking_rules",
"(",
"self",
",",
"policy_id",
",",
"retrieve_all",
"=",
"True",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"list",
"(",
"'dscp_marking_rules'",
",",
"self",
".",
"qos_dscp_marking_rules_path",
"%",
"policy_id",
... | 57.833333 | 0.008523 |
async def _playat(self, ctx, index: int):
""" Plays the queue from a specific point. Disregards tracks before the index. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if index < 1:
return await ctx.send('Invalid specified index.')
if len(player.queue) < in... | [
"async",
"def",
"_playat",
"(",
"self",
",",
"ctx",
",",
"index",
":",
"int",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"if",
"index",
"<",
"1",
":",
"ret... | 39.363636 | 0.006772 |
def _load_state(self, context):
"""
Load state from cookie to the context
:type context: satosa.context.Context
:param context: Session context
"""
try:
state = cookie_to_state(
context.cookie,
self.config["COOKIE_STATE... | [
"def",
"_load_state",
"(",
"self",
",",
"context",
")",
":",
"try",
":",
"state",
"=",
"cookie_to_state",
"(",
"context",
".",
"cookie",
",",
"self",
".",
"config",
"[",
"\"COOKIE_STATE_NAME\"",
"]",
",",
"self",
".",
"config",
"[",
"\"STATE_ENCRYPTION_KEY\"... | 36.157895 | 0.002837 |
def htmlFromThing(thing,title):
"""create pretty formatted HTML from a things dictionary."""
try:
thing2 = copy.copy(thing)
except:
print("crashed copying the thing! I can't document it.")
return False
stuff=analyzeThing(thing2)
names2=list(stuff.keys())
for i,na... | [
"def",
"htmlFromThing",
"(",
"thing",
",",
"title",
")",
":",
"try",
":",
"thing2",
"=",
"copy",
".",
"copy",
"(",
"thing",
")",
"except",
":",
"print",
"(",
"\"crashed copying the thing! I can't document it.\"",
")",
"return",
"False",
"stuff",
"=",
"analyzeT... | 36.709302 | 0.018507 |
def get_traceback_stxt():
"""
Result is (bytes) str type on Python 2 and (unicode) str type on Python 3.
"""
#/
exc_cls, exc_obj, tb_obj = sys.exc_info()
#/
txt_s = traceback.format_exception(exc_cls, exc_obj, tb_obj)
#/
res = ''.join... | [
"def",
"get_traceback_stxt",
"(",
")",
":",
"#/",
"exc_cls",
",",
"exc_obj",
",",
"tb_obj",
"=",
"sys",
".",
"exc_info",
"(",
")",
"#/",
"txt_s",
"=",
"traceback",
".",
"format_exception",
"(",
"exc_cls",
",",
"exc_obj",
",",
"tb_obj",
")",
"#/",
"res",
... | 24.142857 | 0.025641 |
def labels(self, text=None, coordinates=None, colorlist=None, sizes=None, fonts=None, opacity=1.0):
'''Display atomic labels for the system'''
if coordinates is None:
coordinates=self.coordinates
l=len(coordinates)
if text is None:
if len(self.topology.get('atom_t... | [
"def",
"labels",
"(",
"self",
",",
"text",
"=",
"None",
",",
"coordinates",
"=",
"None",
",",
"colorlist",
"=",
"None",
",",
"sizes",
"=",
"None",
",",
"fonts",
"=",
"None",
",",
"opacity",
"=",
"1.0",
")",
":",
"if",
"coordinates",
"is",
"None",
"... | 56.809524 | 0.014839 |
def _round_magmoms(magmoms, round_magmoms_mode: Union[int, float]):
"""
If round_magmoms_mode is an integer, simply round to that number
of decimal places, else if set to a float will try and round
intelligently by grouping magmoms.
"""
if isinstance(round_magmoms_mode, ... | [
"def",
"_round_magmoms",
"(",
"magmoms",
",",
"round_magmoms_mode",
":",
"Union",
"[",
"int",
",",
"float",
"]",
")",
":",
"if",
"isinstance",
"(",
"round_magmoms_mode",
",",
"int",
")",
":",
"# simple rounding to number of decimal places",
"magmoms",
"=",
"np",
... | 39.916667 | 0.003057 |
def ellpoint (mjr, mnr, pa, th):
"""Compute a point on an ellipse parametrically. Inputs:
* mjr: major axis (sigma not FWHM) of the ellipse
* mnr: minor axis (sigma not FWHM) of the ellipse
* pa: position angle (from +x to +y) of the ellipse, radians
* th: the parameter, 0 <= th < 2pi: the eccentri... | [
"def",
"ellpoint",
"(",
"mjr",
",",
"mnr",
",",
"pa",
",",
"th",
")",
":",
"_ellcheck",
"(",
"mjr",
",",
"mnr",
",",
"pa",
")",
"from",
"numpy",
"import",
"cos",
",",
"sin",
"ct",
",",
"st",
"=",
"cos",
"(",
"th",
")",
",",
"sin",
"(",
"th",
... | 31 | 0.010955 |
def _get_module_via_parent_enumeration(self, fullname):
"""
Attempt to fetch source code by examining the module's (hopefully less
insane) parent package. Required for older versions of
ansible.compat.six and plumbum.colors.
"""
if fullname not in sys.modules:
... | [
"def",
"_get_module_via_parent_enumeration",
"(",
"self",
",",
"fullname",
")",
":",
"if",
"fullname",
"not",
"in",
"sys",
".",
"modules",
":",
"# Don't attempt this unless a module really exists in sys.modules,",
"# else we could return junk.",
"return",
"pkgname",
",",
"_... | 37.526316 | 0.001367 |
def start_tag(el):
"""
The text representation of the start tag for a tag.
"""
return '<%s%s>' % (
el.tag, ''.join([' %s="%s"' % (name, html_escape(value, True))
for name, value in el.attrib.items()])) | [
"def",
"start_tag",
"(",
"el",
")",
":",
"return",
"'<%s%s>'",
"%",
"(",
"el",
".",
"tag",
",",
"''",
".",
"join",
"(",
"[",
"' %s=\"%s\"'",
"%",
"(",
"name",
",",
"html_escape",
"(",
"value",
",",
"True",
")",
")",
"for",
"name",
",",
"value",
"... | 34.857143 | 0.004 |
def get_version():
"""Get the current version from ``setup.py``.
Assumes that importing ``setup.py`` will have no side-effects (i.e.
assumes the behavior is guarded by ``if __name__ == "__main__"``).
Returns:
str: The current version in ``setup.py``.
"""
# "Spoof" the ``setup.py`` help... | [
"def",
"get_version",
"(",
")",
":",
"# \"Spoof\" the ``setup.py`` helper modules.",
"sys",
".",
"modules",
"[",
"\"setup_helpers\"",
"]",
"=",
"object",
"(",
")",
"sys",
".",
"modules",
"[",
"\"setup_helpers_macos\"",
"]",
"=",
"object",
"(",
")",
"sys",
".",
... | 38.058824 | 0.001508 |
def disassociate_public_ip(self, public_ip_id):
"""Disassociate a external IP"""
floating_ip = self.client.floating_ips.get(public_ip_id)
floating_ip = floating_ip.to_dict()
instance_id = floating_ip.get('instance_id')
address = floating_ip.get('ip')
self.client.servers.... | [
"def",
"disassociate_public_ip",
"(",
"self",
",",
"public_ip_id",
")",
":",
"floating_ip",
"=",
"self",
".",
"client",
".",
"floating_ips",
".",
"get",
"(",
"public_ip_id",
")",
"floating_ip",
"=",
"floating_ip",
".",
"to_dict",
"(",
")",
"instance_id",
"=",
... | 37.2 | 0.005249 |
def get_events(self, name=None, time=None, chan=None, stage=None,
qual=None):
"""Get list of events in the file.
Parameters
----------
name : str, optional
name of the event of interest
time : tuple of two float, optional
start and end ... | [
"def",
"get_events",
"(",
"self",
",",
"name",
"=",
"None",
",",
"time",
"=",
"None",
",",
"chan",
"=",
"None",
",",
"stage",
"=",
"None",
",",
"qual",
"=",
"None",
")",
":",
"# get events inside window",
"events",
"=",
"self",
".",
"rater",
".",
"fi... | 33.92381 | 0.000818 |
async def rank(self) -> Optional[float]:
"""
If there is a text layer inside the request, try to find a matching
text in the specified intent.
"""
if not self.request.has_layer(l.RawText):
return
tl = self.request.get_layer(l.RawText)
matcher = Match... | [
"async",
"def",
"rank",
"(",
"self",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"if",
"not",
"self",
".",
"request",
".",
"has_layer",
"(",
"l",
".",
"RawText",
")",
":",
"return",
"tl",
"=",
"self",
".",
"request",
".",
"get_layer",
"(",
"l",
... | 29.0625 | 0.004167 |
def _getTipArchiveURL(repo):
''' return a string containing a tarball url '''
g = Github(settings.getProperty('github', 'authtoken'))
repo = g.get_repo(repo)
return repo.get_archive_link('tarball') | [
"def",
"_getTipArchiveURL",
"(",
"repo",
")",
":",
"g",
"=",
"Github",
"(",
"settings",
".",
"getProperty",
"(",
"'github'",
",",
"'authtoken'",
")",
")",
"repo",
"=",
"g",
".",
"get_repo",
"(",
"repo",
")",
"return",
"repo",
".",
"get_archive_link",
"("... | 41.8 | 0.004695 |
def str2bool(value):
"""Parse Yes/No/Default string
https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse"""
if value.lower() in ('yes', 'true', 't', 'y', '1'):
return True
if value.lower() in ('no', 'false', 'f', 'n', '0'):
return False
if value.lower() i... | [
"def",
"str2bool",
"(",
"value",
")",
":",
"if",
"value",
".",
"lower",
"(",
")",
"in",
"(",
"'yes'",
",",
"'true'",
",",
"'t'",
",",
"'y'",
",",
"'1'",
")",
":",
"return",
"True",
"if",
"value",
".",
"lower",
"(",
")",
"in",
"(",
"'no'",
",",
... | 44 | 0.006682 |
def load_acknowledge_config(self, file_id):
"""
Loads the CWR acknowledge config
:return: the values matrix
"""
if self._cwr_defaults is None:
self._cwr_defaults = self._reader.read_yaml_file(
'acknowledge_config_%s.yml' % file_id)
return self... | [
"def",
"load_acknowledge_config",
"(",
"self",
",",
"file_id",
")",
":",
"if",
"self",
".",
"_cwr_defaults",
"is",
"None",
":",
"self",
".",
"_cwr_defaults",
"=",
"self",
".",
"_reader",
".",
"read_yaml_file",
"(",
"'acknowledge_config_%s.yml'",
"%",
"file_id",
... | 32.5 | 0.005988 |
def load_commodities(self):
"""
Load the commodities for Amounts in this object.
"""
if isinstance(self.amount, Amount):
self.amount = Amount("{0:.8f} {1}".format(self.amount.to_double(), self.currency))
else:
self.amount = Amount("{0:.8f} {1}".format(self... | [
"def",
"load_commodities",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"amount",
",",
"Amount",
")",
":",
"self",
".",
"amount",
"=",
"Amount",
"(",
"\"{0:.8f} {1}\"",
".",
"format",
"(",
"self",
".",
"amount",
".",
"to_double",
"(",
"... | 42.125 | 0.011628 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.