text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def stream(identifier=None, priority=LOG_INFO, level_prefix=False):
r"""Return a file object wrapping a stream to journal.
Log messages written to this file as simple newline sepearted text strings
are written to the journal.
The file will be line buffered, so messages are actually sent after a
ne... | [
"def",
"stream",
"(",
"identifier",
"=",
"None",
",",
"priority",
"=",
"LOG_INFO",
",",
"level_prefix",
"=",
"False",
")",
":",
"if",
"identifier",
"is",
"None",
":",
"if",
"not",
"_sys",
".",
"argv",
"or",
"not",
"_sys",
".",
"argv",
"[",
"0",
"]",
... | 37.714286 | 27.119048 |
def T_dependent_property_integral_over_T(self, T1, T2):
r'''Method to calculate the integral of a property over temperature
with respect to temperature, using a specified method. Methods found
valid by `select_valid_methods` are attempted until a method succeeds.
If no methods are vali... | [
"def",
"T_dependent_property_integral_over_T",
"(",
"self",
",",
"T1",
",",
"T2",
")",
":",
"Tavg",
"=",
"0.5",
"*",
"(",
"T1",
"+",
"T2",
")",
"if",
"self",
".",
"method",
":",
"# retest within range",
"if",
"self",
".",
"test_method_validity",
"(",
"Tavg... | 35.046512 | 22.627907 |
def _url_val(val, key, obj, **kwargs):
"""Function applied by `HyperlinksField` to get the correct value in the
schema.
"""
if isinstance(val, URLFor):
return val.serialize(key, obj, **kwargs)
else:
return val | [
"def",
"_url_val",
"(",
"val",
",",
"key",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"URLFor",
")",
":",
"return",
"val",
".",
"serialize",
"(",
"key",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
"else",
... | 29.75 | 12.625 |
def hmean_int(a, a_min=5778, a_max=1149851):
""" Harmonic mean of an array, returns the closest int
"""
from scipy.stats import hmean
return int(round(hmean(np.clip(a, a_min, a_max)))) | [
"def",
"hmean_int",
"(",
"a",
",",
"a_min",
"=",
"5778",
",",
"a_max",
"=",
"1149851",
")",
":",
"from",
"scipy",
".",
"stats",
"import",
"hmean",
"return",
"int",
"(",
"round",
"(",
"hmean",
"(",
"np",
".",
"clip",
"(",
"a",
",",
"a_min",
",",
"... | 39.2 | 5 |
def _create_regex_pattern_add_optional_spaces_to_word_characters(word):
"""Add the regex special characters (\s*) to allow optional spaces between
the characters in a word.
@param word: (string) the word to be inserted into a regex pattern.
@return: string: the regex pattern for that word with ... | [
"def",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"word",
")",
":",
"new_word",
"=",
"u\"\"",
"for",
"ch",
"in",
"word",
":",
"if",
"ch",
".",
"isspace",
"(",
")",
":",
"new_word",
"+=",
"ch",
"else",
":",
"new_word",
"+=",
"ch",
"+... | 37.928571 | 16.857143 |
def propose(self):
"""Use the trained model to propose a new pipeline.
Returns:
int: Index corresponding to pipeline to try in ``dpp_matrix``.
"""
# generate a list of all the untried candidate pipelines
candidates = self._get_candidates()
# get_candidates()... | [
"def",
"propose",
"(",
"self",
")",
":",
"# generate a list of all the untried candidate pipelines",
"candidates",
"=",
"self",
".",
"_get_candidates",
"(",
")",
"# get_candidates() returns None when every possibility has been tried",
"if",
"candidates",
"is",
"None",
":",
"r... | 34.75 | 21.55 |
def dist(ctx, devpi=False, egg=False, wheel=False, auto=True):
"""Distribute the project."""
config.load()
cmd = ["python", "setup.py", "sdist"]
# Automatically create wheels if possible
if auto:
egg = sys.version_info.major == 2
try:
import wheel as _
wheel ... | [
"def",
"dist",
"(",
"ctx",
",",
"devpi",
"=",
"False",
",",
"egg",
"=",
"False",
",",
"wheel",
"=",
"False",
",",
"auto",
"=",
"True",
")",
":",
"config",
".",
"load",
"(",
")",
"cmd",
"=",
"[",
"\"python\"",
",",
"\"setup.py\"",
",",
"\"sdist\"",
... | 25.652174 | 18.043478 |
def sentiment(symbol, type='daily', date=None, token='', version=''):
'''This endpoint provides social sentiment data from StockTwits. Data can be viewed as a daily value, or by minute for a given date.
https://iexcloud.io/docs/api/#social-sentiment
Continuous
Args:
symbol (string); Ticker to ... | [
"def",
"sentiment",
"(",
"symbol",
",",
"type",
"=",
"'daily'",
",",
"date",
"=",
"None",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"_raiseIfNotStr",
"(",
"symbol",
")",
"if",
"date",
":",
"date",
"=",
"_strOrDate",
"(",
"date",
... | 39.190476 | 29.285714 |
def losc_frame_urls(ifo, start_time, end_time):
""" Get a list of urls to losc frame files
Parameters
----------
ifo: str
The name of the IFO to find the information about.
start_time: int
The gps time in GPS seconds
end_time: int
The end time in GPS seconds
Returns... | [
"def",
"losc_frame_urls",
"(",
"ifo",
",",
"start_time",
",",
"end_time",
")",
":",
"data",
"=",
"losc_frame_json",
"(",
"ifo",
",",
"start_time",
",",
"end_time",
")",
"[",
"'strain'",
"]",
"return",
"[",
"d",
"[",
"'url'",
"]",
"for",
"d",
"in",
"dat... | 28.3 | 20.35 |
def main(argString=None):
"""The main function.
:param argString: the options.
:type argString: list
These are the steps of this module:
1. Prints the options.
2. Finds the overlapping markers between the three reference panels and
the source panel (:py:func:`findOverlappingSNPsWit... | [
"def",
"main",
"(",
"argString",
"=",
"None",
")",
":",
"# Getting and checking the options",
"args",
"=",
"parseArgs",
"(",
"argString",
")",
"checkArgs",
"(",
"args",
")",
"logger",
".",
"info",
"(",
"\"Options used:\"",
")",
"for",
"key",
",",
"value",
"i... | 37.918803 | 19.542735 |
def is_fuse_exec(cmd):
'''
Returns true if the command passed is a fuse mountable application.
CLI Example:
.. code-block:: bash
salt '*' mount.is_fuse_exec sshfs
'''
cmd_path = salt.utils.path.which(cmd)
# No point in running ldd on a command that doesn't exist
if not cmd_pa... | [
"def",
"is_fuse_exec",
"(",
"cmd",
")",
":",
"cmd_path",
"=",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"cmd",
")",
"# No point in running ldd on a command that doesn't exist",
"if",
"not",
"cmd_path",
":",
"return",
"False",
"elif",
"not",
"salt",
... | 25.85 | 23.55 |
def addCallSetFromName(self, sampleName):
"""
Adds a CallSet for the specified sample name.
"""
callSet = CallSet(self, sampleName)
self.addCallSet(callSet) | [
"def",
"addCallSetFromName",
"(",
"self",
",",
"sampleName",
")",
":",
"callSet",
"=",
"CallSet",
"(",
"self",
",",
"sampleName",
")",
"self",
".",
"addCallSet",
"(",
"callSet",
")"
] | 31.833333 | 4.166667 |
def notify(self, *args, **kwargs):
"See signal"
loop = kwargs.pop('loop', self.loop)
return self.signal.prepare_notification(
subscribers=self.subscribers, instance=self.instance,
loop=loop).run(*args, **kwargs) | [
"def",
"notify",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"loop",
"=",
"kwargs",
".",
"pop",
"(",
"'loop'",
",",
"self",
".",
"loop",
")",
"return",
"self",
".",
"signal",
".",
"prepare_notification",
"(",
"subscribers",
"=",... | 42.333333 | 11 |
def discover(service="ssdp:all", timeout=1, retries=2, ipAddress="239.255.255.250", port=1900):
"""Discovers UPnP devices in the local network.
Try to discover all devices in the local network which do support UPnP. The discovery process can fail
for various reasons and it is recommended to do ... | [
"def",
"discover",
"(",
"service",
"=",
"\"ssdp:all\"",
",",
"timeout",
"=",
"1",
",",
"retries",
"=",
"2",
",",
"ipAddress",
"=",
"\"239.255.255.250\"",
",",
"port",
"=",
"1900",
")",
":",
"socket",
".",
"setdefaulttimeout",
"(",
"timeout",
")",
"messages... | 40.653846 | 26.371795 |
def sub_dsp_nodes(self):
"""
Returns all sub-dispatcher nodes of the dispatcher.
:return:
All sub-dispatcher nodes of the dispatcher.
:rtype: dict[str, dict]
"""
return {k: v for k, v in self.nodes.items() if
v['type'] == 'dispatcher'} | [
"def",
"sub_dsp_nodes",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"nodes",
".",
"items",
"(",
")",
"if",
"v",
"[",
"'type'",
"]",
"==",
"'dispatcher'",
"}"
] | 27.545455 | 16.272727 |
def read_frames(file_path, frame_size, hop_size, start=0.0,
end=float('inf'), buffer_size=5760000):
"""
Read an audio file frame by frame. The frames are yielded one after another.
Args:
file_path (str): Path to the file to read.
frame_size (int): The number of samples per f... | [
"def",
"read_frames",
"(",
"file_path",
",",
"frame_size",
",",
"hop_size",
",",
"start",
"=",
"0.0",
",",
"end",
"=",
"float",
"(",
"'inf'",
")",
",",
"buffer_size",
"=",
"5760000",
")",
":",
"rest_samples",
"=",
"np",
".",
"array",
"(",
"[",
"]",
"... | 39.142857 | 21.061224 |
def receive_accept(self, msg):
'''
Returns either an Accepted or Nack message in response. The Acceptor's state must be persisted
to disk prior to transmitting the Accepted message.
'''
if self.promised_id is None or msg.proposal_id >= self.promised_id:
self.promised_... | [
"def",
"receive_accept",
"(",
"self",
",",
"msg",
")",
":",
"if",
"self",
".",
"promised_id",
"is",
"None",
"or",
"msg",
".",
"proposal_id",
">=",
"self",
".",
"promised_id",
":",
"self",
".",
"promised_id",
"=",
"msg",
".",
"proposal_id",
"self",
".",
... | 51.416667 | 27.25 |
def get_repo_info(repo_name, profile='github', ignore_cache=False):
'''
Return information for a given repo.
.. versionadded:: 2016.11.0
repo_name
The name of the repository.
profile
The name of the profile configuration to use. Defaults to ``github``.
CLI Example:
.. co... | [
"def",
"get_repo_info",
"(",
"repo_name",
",",
"profile",
"=",
"'github'",
",",
"ignore_cache",
"=",
"False",
")",
":",
"org_name",
"=",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
"key",
"=",
"\"github.{0}:{1}:repo_info\"",
".",
"format",
"(",
... | 30.367347 | 22.857143 |
def verify(self, signing_cert_str, cert_str):
"""
Verifies if a certificate is valid and signed by a given certificate.
:param signing_cert_str: This certificate will be used to verify the
signature. Must be a string representation
... | [
"def",
"verify",
"(",
"self",
",",
"signing_cert_str",
",",
"cert_str",
")",
":",
"try",
":",
"ca_cert",
"=",
"crypto",
".",
"load_certificate",
"(",
"crypto",
".",
"FILETYPE_PEM",
",",
"signing_cert_str",
")",
"cert",
"=",
"crypto",
".",
"load_certificate",
... | 48.421053 | 25.368421 |
def get_asset_admin_session(self, proxy=None):
"""Gets an asset administration session for creating, updating and deleting assets.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetAdminSession) - an
``AssetAdminSession``
raise: NullArgument - ``pr... | [
"def",
"get_asset_admin_session",
"(",
"self",
",",
"proxy",
"=",
"None",
")",
":",
"asset_lookup_session",
"=",
"self",
".",
"_provider_manager",
".",
"get_asset_lookup_session",
"(",
"proxy",
")",
"return",
"AssetAdminSession",
"(",
"self",
".",
"_provider_manager... | 46.333333 | 17.111111 |
def import_locations(self, data):
"""Parse `GNU miscfiles`_ cities data files.
``import_locations()`` returns a list containing :class:`City` objects.
It expects data files in the same format that `GNU miscfiles`_
provides, that is::
ID : 1
Type ... | [
"def",
"import_locations",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_data",
"=",
"data",
"if",
"hasattr",
"(",
"data",
",",
"'read'",
")",
":",
"data",
"=",
"data",
".",
"read",
"(",
")",
".",
"split",
"(",
"'//\\n'",
")",
"elif",
"isinsta... | 38.733333 | 20.077778 |
def import_phantom_module(xml_file):
"""
Insert a fake Python module to sys.modules, based on a XML file.
The XML file is expected to conform to Pydocweb DTD. The fake
module will contain dummy objects, which guarantee the following:
- Docstrings are correct.
- Class inheritance relationships ... | [
"def",
"import_phantom_module",
"(",
"xml_file",
")",
":",
"import",
"lxml",
".",
"etree",
"as",
"etree",
"object_cache",
"=",
"{",
"}",
"tree",
"=",
"etree",
".",
"parse",
"(",
"xml_file",
")",
"root",
"=",
"tree",
".",
"getroot",
"(",
")",
"# Sort item... | 34.231343 | 16.947761 |
def _grid_in_property(field_name, docstring, read_only=False,
closed_only=False):
"""Create a GridIn property."""
def getter(self):
if closed_only and not self._closed:
raise AttributeError("can only get %r on a closed file" %
field_name... | [
"def",
"_grid_in_property",
"(",
"field_name",
",",
"docstring",
",",
"read_only",
"=",
"False",
",",
"closed_only",
"=",
"False",
")",
":",
"def",
"getter",
"(",
"self",
")",
":",
"if",
"closed_only",
"and",
"not",
"self",
".",
"_closed",
":",
"raise",
... | 40.678571 | 16.857143 |
def advance_permutation(a, increasing=True, forward=True):
"""
Advance a list of unique, ordered elements in-place, lexicographically
increasing or backward, by rightmost or leftmost digit.
Returns False if the permutation wrapped around - i.e. went from
lexicographically greatest to least, and Tru... | [
"def",
"advance_permutation",
"(",
"a",
",",
"increasing",
"=",
"True",
",",
"forward",
"=",
"True",
")",
":",
"if",
"not",
"forward",
":",
"a",
".",
"reverse",
"(",
")",
"cmp",
"=",
"operator",
".",
"lt",
"if",
"increasing",
"else",
"operator",
".",
... | 31.484848 | 24.515152 |
def _get_record_attrs(out_keys):
"""Check for records, a single key plus output attributes.
"""
if len(out_keys) == 1:
attr = list(out_keys.keys())[0]
if out_keys[attr]:
return attr, out_keys[attr]
return None, None | [
"def",
"_get_record_attrs",
"(",
"out_keys",
")",
":",
"if",
"len",
"(",
"out_keys",
")",
"==",
"1",
":",
"attr",
"=",
"list",
"(",
"out_keys",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
"if",
"out_keys",
"[",
"attr",
"]",
":",
"return",
"attr",
... | 31.5 | 7.125 |
def clean(self):
"""Delete all of the records"""
# Deleting seems to be really weird and unrelable.
self._session \
.query(Process) \
.filter(Process.d_vid == self._d_vid) \
.delete(synchronize_session='fetch')
for r in self.records:
self... | [
"def",
"clean",
"(",
"self",
")",
":",
"# Deleting seems to be really weird and unrelable.",
"self",
".",
"_session",
".",
"query",
"(",
"Process",
")",
".",
"filter",
"(",
"Process",
".",
"d_vid",
"==",
"self",
".",
"_d_vid",
")",
".",
"delete",
"(",
"synch... | 27.615385 | 18 |
def json_changebase(obj, changer):
"""
Given a primitive compound Python object (i.e. a dict,
string, int, or list) and a changer function that takes
a primitive Python object as an argument, apply the
changer function to the object and each sub-component.
Return the newly-reencoded object.
... | [
"def",
"json_changebase",
"(",
"obj",
",",
"changer",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"return",
"changer",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"(",
"int",
",",
"long",
")... | 28.916667 | 19.416667 |
def display_element_selected(self, f):
"""Decorator routes Alexa Display.ElementSelected request to the wrapped view function.
@ask.display_element_selected
def eval_element():
return "", 200
The wrapped function is registered as the display_element_selected view function
... | [
"def",
"display_element_selected",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"_display_element_selected_func",
"=",
"f",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"_flask_view_func",
... | 32.157895 | 19 |
def merge(self, other):
"""
Merge another object as needed.
"""
other.qualify()
for n in ('name',
'qname',
'min',
'max',
'default',
'type',
'nillable',
'f... | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"other",
".",
"qualify",
"(",
")",
"for",
"n",
"in",
"(",
"'name'",
",",
"'qname'",
",",
"'min'",
",",
"'max'",
",",
"'default'",
",",
"'type'",
",",
"'nillable'",
",",
"'form_qualified'",
",",
")"... | 26.631579 | 10.736842 |
def write_file(self, what, filename, data):
"""Write `data` to `filename` (if not a dry run) after announcing it
`what` is used in a log message to identify what is being written
to the file.
"""
log.info("writing %s to %s", what, filename)
if sys.version_info >= (3,):
... | [
"def",
"write_file",
"(",
"self",
",",
"what",
",",
"filename",
",",
"data",
")",
":",
"log",
".",
"info",
"(",
"\"writing %s to %s\"",
",",
"what",
",",
"filename",
")",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
")",
":",
"data",
"=",
... | 35.384615 | 12.538462 |
def make_iml4(R, iml_disagg, imtls=None, poes_disagg=(None,), curves=()):
"""
:returns: an ArrayWrapper over a 4D array of shape (N, R, M, P)
"""
if imtls is None:
imtls = {imt: [iml] for imt, iml in iml_disagg.items()}
N = len(curves) or 1
M = len(imtls)
P = len(poes_disagg)
arr... | [
"def",
"make_iml4",
"(",
"R",
",",
"iml_disagg",
",",
"imtls",
"=",
"None",
",",
"poes_disagg",
"=",
"(",
"None",
",",
")",
",",
"curves",
"=",
"(",
")",
")",
":",
"if",
"imtls",
"is",
"None",
":",
"imtls",
"=",
"{",
"imt",
":",
"[",
"iml",
"]"... | 38.588235 | 15.176471 |
def gen_data_files(src_dir):
"""
generates a list of files contained in the given directory (and its
subdirectories) in the format required by the ``package_data`` parameter
of the ``setuptools.setup`` function.
Parameters
----------
src_dir : str
(relative) path to the directory st... | [
"def",
"gen_data_files",
"(",
"src_dir",
")",
":",
"fpaths",
"=",
"[",
"]",
"base",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"src_dir",
")",
"for",
"root",
",",
"dir",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"src_dir",
")",
":",
"if",
"le... | 29.541667 | 20.125 |
def make_connector(self, app=None, bind=None):
"""Creates the connector for a given state and bind."""
return _EngineConnector(self, self.get_app(app), bind) | [
"def",
"make_connector",
"(",
"self",
",",
"app",
"=",
"None",
",",
"bind",
"=",
"None",
")",
":",
"return",
"_EngineConnector",
"(",
"self",
",",
"self",
".",
"get_app",
"(",
"app",
")",
",",
"bind",
")"
] | 57 | 9.333333 |
def autodiscover():
"""Import all `ddp` submodules from `settings.INSTALLED_APPS`."""
from django.utils.module_loading import autodiscover_modules
from dddp.api import API
autodiscover_modules('ddp', register_to=API)
return API | [
"def",
"autodiscover",
"(",
")",
":",
"from",
"django",
".",
"utils",
".",
"module_loading",
"import",
"autodiscover_modules",
"from",
"dddp",
".",
"api",
"import",
"API",
"autodiscover_modules",
"(",
"'ddp'",
",",
"register_to",
"=",
"API",
")",
"return",
"AP... | 40.333333 | 15.166667 |
def compress_subproperties (properties):
""" Combine all subproperties into their parent properties
Requires: for every subproperty, there is a parent property. All
features are explicitly expressed.
This rule probably shouldn't be needed, but
build-request.expand-no-defaults is b... | [
"def",
"compress_subproperties",
"(",
"properties",
")",
":",
"from",
".",
"property",
"import",
"Property",
"assert",
"is_iterable_typed",
"(",
"properties",
",",
"Property",
")",
"result",
"=",
"[",
"]",
"matched_subs",
"=",
"set",
"(",
")",
"all_subs",
"=",... | 30.078947 | 20.210526 |
def to_json(self):
"""
Represented as a list of edges:
dependent: index of child
dep: dependency label
governer: index of parent
dependentgloss: gloss of parent
governergloss: gloss of parent
"""
edges = []
for root in s... | [
"def",
"to_json",
"(",
"self",
")",
":",
"edges",
"=",
"[",
"]",
"for",
"root",
"in",
"self",
".",
"roots",
":",
"edges",
".",
"append",
"(",
"{",
"'governer'",
":",
"0",
",",
"'dep'",
":",
"\"root\"",
",",
"'dependent'",
":",
"root",
"+",
"1",
"... | 33.413793 | 11 |
def add_db_germline_flag(line):
"""Adds a DB flag for Germline filters, allowing downstream compatibility with PureCN.
"""
if line.startswith("#CHROM"):
headers = ['##INFO=<ID=DB,Number=0,Type=Flag,Description="Likely germline variant">']
return "\n".join(headers) + "\n" + line
elif line... | [
"def",
"add_db_germline_flag",
"(",
"line",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"\"#CHROM\"",
")",
":",
"headers",
"=",
"[",
"'##INFO=<ID=DB,Number=0,Type=Flag,Description=\"Likely germline variant\">'",
"]",
"return",
"\"\\n\"",
".",
"join",
"(",
"headers... | 38.461538 | 13.461538 |
def main():
'''Base58 encode or decode FILE, or standard input, to standard output.'''
import sys
import argparse
stdout = buffer(sys.stdout)
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument(
'file',
metavar='FILE',
nargs='?',
type... | [
"def",
"main",
"(",
")",
":",
"import",
"sys",
"import",
"argparse",
"stdout",
"=",
"buffer",
"(",
"sys",
".",
"stdout",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"main",
".",
"__doc__",
")",
"parser",
".",
"add_argu... | 24.214286 | 20.738095 |
def getNextNode(nodes,usednodes,parent):
'''Get next node in a breadth-first traversal of nodes that have not been used yet'''
for e in edges:
if e.source==parent:
if e.target in usednodes:
x = e.target
break
elif e.target==parent:
if e.sou... | [
"def",
"getNextNode",
"(",
"nodes",
",",
"usednodes",
",",
"parent",
")",
":",
"for",
"e",
"in",
"edges",
":",
"if",
"e",
".",
"source",
"==",
"parent",
":",
"if",
"e",
".",
"target",
"in",
"usednodes",
":",
"x",
"=",
"e",
".",
"target",
"break",
... | 32.583333 | 15.583333 |
def register_on_machine_data_changed(self, callback):
"""Set the callback function to consume on machine data changed events.
Callback receives a IMachineDataChangedEvent object.
Returns the callback_id
"""
event_type = library.VBoxEventType.on_machine_data_changed
retu... | [
"def",
"register_on_machine_data_changed",
"(",
"self",
",",
"callback",
")",
":",
"event_type",
"=",
"library",
".",
"VBoxEventType",
".",
"on_machine_data_changed",
"return",
"self",
".",
"event_source",
".",
"register_callback",
"(",
"callback",
",",
"event_type",
... | 41.333333 | 20 |
def doublefork(pidfile, logfile, cwd, umask): # pragma: nocover
'''Daemonize current process.
After first fork we return to the shell and removing our self from
controling terminal via `setsid`.
After second fork we are not session leader any more and cant get
controlling terminal when opening files... | [
"def",
"doublefork",
"(",
"pidfile",
",",
"logfile",
",",
"cwd",
",",
"umask",
")",
":",
"# pragma: nocover",
"try",
":",
"if",
"os",
".",
"fork",
"(",
")",
":",
"os",
".",
"_exit",
"(",
"os",
".",
"EX_OK",
")",
"except",
"OSError",
"as",
"e",
":",... | 33.558824 | 17.558824 |
def EndVector(self, vectorNumElems):
"""EndVector writes data necessary to finish vector construction."""
self.assertNested()
## @cond FLATBUFFERS_INTERNAL
self.nested = False
## @endcond
# we already made space for this, so write without PrependUint32
self.Place... | [
"def",
"EndVector",
"(",
"self",
",",
"vectorNumElems",
")",
":",
"self",
".",
"assertNested",
"(",
")",
"## @cond FLATBUFFERS_INTERNAL",
"self",
".",
"nested",
"=",
"False",
"## @endcond",
"# we already made space for this, so write without PrependUint32",
"self",
".",
... | 36.4 | 14 |
def cache_last_modified(request, *argz, **kwz):
'''Last modification date for a cached page.
Intended for usage in conditional views (@condition decorator).'''
response, site, cachekey = kwz.get('_view_data') or initview(request)
if not response: return None
return response[1] | [
"def",
"cache_last_modified",
"(",
"request",
",",
"*",
"argz",
",",
"*",
"*",
"kwz",
")",
":",
"response",
",",
"site",
",",
"cachekey",
"=",
"kwz",
".",
"get",
"(",
"'_view_data'",
")",
"or",
"initview",
"(",
"request",
")",
"if",
"not",
"response",
... | 46.333333 | 17 |
def _sample_points(X, centers, oversampling_factor, random_state):
r"""
Sample points independently with probability
.. math::
p_x = \frac{\ell \cdot d^2(x, \mathcal{C})}{\phi_X(\mathcal{C})}
"""
# re-implement evaluate_cost here, to avoid redundant computation
distances = pairwise_di... | [
"def",
"_sample_points",
"(",
"X",
",",
"centers",
",",
"oversampling_factor",
",",
"random_state",
")",
":",
"# re-implement evaluate_cost here, to avoid redundant computation",
"distances",
"=",
"pairwise_distances",
"(",
"X",
",",
"centers",
")",
".",
"min",
"(",
"... | 27.45 | 23.4 |
def _parse_process_name(name_str):
"""Parses the process string and returns the process name and its
directives
Process strings my contain directive information with the following
syntax::
proc_name={'directive':'val'}
This method parses this string and returns the... | [
"def",
"_parse_process_name",
"(",
"name_str",
")",
":",
"directives",
"=",
"None",
"fields",
"=",
"name_str",
".",
"split",
"(",
"\"=\"",
")",
"process_name",
"=",
"fields",
"[",
"0",
"]",
"if",
"len",
"(",
"fields",
")",
"==",
"2",
":",
"_directives",
... | 32 | 21.021277 |
def logparse(*args, **kwargs):
""" Parse access log on the terminal application.
If list of files are given, parse each file. Otherwise, parse standard
input.
:param args: supporting functions after processed raw log line
:type: list of callables
:rtype: tuple of (statistics, key/value report)
... | [
"def",
"logparse",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"clitool",
".",
"cli",
"import",
"clistream",
"from",
"clitool",
".",
"processor",
"import",
"SimpleDictReporter",
"lst",
"=",
"[",
"parse",
"]",
"+",
"args",
"reporter",
"="... | 34.3125 | 15.6875 |
def simple_callable(decorator):
'''Decorator used to create consistent decorators.
Consistent in the meaning that the wrapper do not have to
care if the wrapped callable is a function or a method,
it will always receive a valid callable.
If the decorator is used with a function, the wrapper will
... | [
"def",
"simple_callable",
"(",
"decorator",
")",
":",
"def",
"meta_decorator",
"(",
"function",
")",
":",
"wrapper",
"=",
"decorator",
"(",
"function",
")",
"if",
"reflect",
".",
"inside_class_definition",
"(",
"depth",
"=",
"2",
")",
":",
"def",
"method_wra... | 30 | 23.345455 |
def receive(self):
""" Returns a single request.
Takes the first request from the list of requests and returns it. If the list
is empty, None is returned.
Returns:
Response: If a new request is available a Request object is returned,
otherwise None is ... | [
"def",
"receive",
"(",
"self",
")",
":",
"pickled_request",
"=",
"self",
".",
"_connection",
".",
"connection",
".",
"lpop",
"(",
"self",
".",
"_request_key",
")",
"return",
"pickle",
".",
"loads",
"(",
"pickled_request",
")",
"if",
"pickled_request",
"is",
... | 41.166667 | 25.666667 |
def members(self):
""" Children of the collection's item
:rtype: [Collection]
"""
return list(
[
self.children_class(child)
for child in self.graph.subjects(RDF_NAMESPACES.DTS.parent, self.asNode())
]
) | [
"def",
"members",
"(",
"self",
")",
":",
"return",
"list",
"(",
"[",
"self",
".",
"children_class",
"(",
"child",
")",
"for",
"child",
"in",
"self",
".",
"graph",
".",
"subjects",
"(",
"RDF_NAMESPACES",
".",
"DTS",
".",
"parent",
",",
"self",
".",
"a... | 26.272727 | 21 |
def CaptureVariableInternal(self, value, depth, limits, can_enqueue=True):
"""Captures a single nameless object into Variable message.
TODO(vlif): safely evaluate iterable types.
TODO(vlif): safely call str(value)
Args:
value: data to capture
depth: nested depth of dictionaries and vectors... | [
"def",
"CaptureVariableInternal",
"(",
"self",
",",
"value",
",",
"depth",
",",
"limits",
",",
"can_enqueue",
"=",
"True",
")",
":",
"if",
"depth",
"==",
"limits",
".",
"max_depth",
":",
"return",
"{",
"'varTableIndex'",
":",
"0",
"}",
"# Buffer full.",
"i... | 37.490385 | 19.144231 |
def remove_index_from_handle(handle_with_index):
'''
Returns index and handle separately, in a tuple.
:handle_with_index: The handle string with an index (e.g.
500:prefix/suffix)
:return: index and handle as a tuple.
'''
split = handle_with_index.split(':')
if len(split) == 2:
... | [
"def",
"remove_index_from_handle",
"(",
"handle_with_index",
")",
":",
"split",
"=",
"handle_with_index",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"split",
")",
"==",
"2",
":",
"split",
"[",
"0",
"]",
"=",
"int",
"(",
"split",
"[",
"0",
"]",
... | 30.8 | 15.3 |
def undisplayable_info(obj, html=False):
"Generate helpful message regarding an undisplayable object"
collate = '<tt>collate</tt>' if html else 'collate'
info = "For more information, please consult the Composing Data tutorial (http://git.io/vtIQh)"
if isinstance(obj, HoloMap):
error = "HoloMap... | [
"def",
"undisplayable_info",
"(",
"obj",
",",
"html",
"=",
"False",
")",
":",
"collate",
"=",
"'<tt>collate</tt>'",
"if",
"html",
"else",
"'collate'",
"info",
"=",
"\"For more information, please consult the Composing Data tutorial (http://git.io/vtIQh)\"",
"if",
"isinstanc... | 53.35 | 28.75 |
def encode(self, value):
'''
:param value: value to encode
'''
encoded = strToBytes(value) + b'\x00'
return Bits(bytes=encoded) | [
"def",
"encode",
"(",
"self",
",",
"value",
")",
":",
"encoded",
"=",
"strToBytes",
"(",
"value",
")",
"+",
"b'\\x00'",
"return",
"Bits",
"(",
"bytes",
"=",
"encoded",
")"
] | 27 | 14.666667 |
def purge(self, jid, node):
"""
Delete all items from a node.
:param jid: JID of the PubSub service
:param node: Name of the PubSub node
:type node: :class:`str`
Requires :attr:`.xso.Feature.PURGE`.
"""
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.... | [
"def",
"purge",
"(",
"self",
",",
"jid",
",",
"node",
")",
":",
"iq",
"=",
"aioxmpp",
".",
"stanza",
".",
"IQ",
"(",
"type_",
"=",
"aioxmpp",
".",
"structs",
".",
"IQType",
".",
"SET",
",",
"to",
"=",
"jid",
",",
"payload",
"=",
"pubsub_xso",
"."... | 24.090909 | 15.272727 |
def maybe_cast_to_datetime(value, dtype, errors='raise'):
""" try to cast the array/value to a datetimelike dtype, converting float
nan to iNaT
"""
from pandas.core.tools.timedeltas import to_timedelta
from pandas.core.tools.datetimes import to_datetime
if dtype is not None:
if isinstan... | [
"def",
"maybe_cast_to_datetime",
"(",
"value",
",",
"dtype",
",",
"errors",
"=",
"'raise'",
")",
":",
"from",
"pandas",
".",
"core",
".",
"tools",
".",
"timedeltas",
"import",
"to_timedelta",
"from",
"pandas",
".",
"core",
".",
"tools",
".",
"datetimes",
"... | 44.07377 | 21.188525 |
def _get_stringlist_from_commastring(self, field):
# type: (str) -> List[str]
"""Return list of strings from comma separated list
Args:
field (str): Field containing comma separated list
Returns:
List[str]: List of strings
"""
strings = self.data... | [
"def",
"_get_stringlist_from_commastring",
"(",
"self",
",",
"field",
")",
":",
"# type: (str) -> List[str]",
"strings",
"=",
"self",
".",
"data",
".",
"get",
"(",
"field",
")",
"if",
"strings",
":",
"return",
"strings",
".",
"split",
"(",
"','",
")",
"else"... | 27.666667 | 15.933333 |
def entities(self):
"""
Access the entities
:returns: twilio.rest.authy.v1.service.entity.EntityList
:rtype: twilio.rest.authy.v1.service.entity.EntityList
"""
if self._entities is None:
self._entities = EntityList(self._version, service_sid=self._solution['s... | [
"def",
"entities",
"(",
"self",
")",
":",
"if",
"self",
".",
"_entities",
"is",
"None",
":",
"self",
".",
"_entities",
"=",
"EntityList",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]",
",",
")",
"r... | 34.8 | 18.8 |
def put(self, coro):
"""Put a coroutine in the queue to be executed."""
# Avoid logging when a coroutine is queued or executed to avoid log
# spam from coroutines that are started on every keypress.
assert asyncio.iscoroutine(coro)
self._queue.put_nowait(coro) | [
"def",
"put",
"(",
"self",
",",
"coro",
")",
":",
"# Avoid logging when a coroutine is queued or executed to avoid log",
"# spam from coroutines that are started on every keypress.",
"assert",
"asyncio",
".",
"iscoroutine",
"(",
"coro",
")",
"self",
".",
"_queue",
".",
"put... | 49.166667 | 14.166667 |
def on_options(self, req, resp, **kwargs):
"""Respond with JSON formatted resource description on OPTIONS request.
Args:
req (falcon.Request): Optional request object. Defaults to None.
resp (falcon.Response): Optional response object. Defaults to None.
kwargs (dict)... | [
"def",
"on_options",
"(",
"self",
",",
"req",
",",
"resp",
",",
"*",
"*",
"kwargs",
")",
":",
"resp",
".",
"set_header",
"(",
"'Allow'",
",",
"', '",
".",
"join",
"(",
"self",
".",
"allowed_methods",
"(",
")",
")",
")",
"resp",
".",
"body",
"=",
... | 37.6 | 22.3 |
def growthfromrange(rangegrowth, startdate, enddate):
"""
Annual growth given growth from start date to end date.
"""
_yrs = (pd.Timestamp(enddate) - pd.Timestamp(startdate)).total_seconds() /\
dt.timedelta(365.25).total_seconds()
return yrlygrowth(rangegrowth, _yrs) | [
"def",
"growthfromrange",
"(",
"rangegrowth",
",",
"startdate",
",",
"enddate",
")",
":",
"_yrs",
"=",
"(",
"pd",
".",
"Timestamp",
"(",
"enddate",
")",
"-",
"pd",
".",
"Timestamp",
"(",
"startdate",
")",
")",
".",
"total_seconds",
"(",
")",
"/",
"dt",... | 41.857143 | 11.285714 |
def symlink_list(self, load):
'''
Return a list of symlinked files and dirs
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
ret = {}
if 'saltenv' not in load:
return {}
if not isinstance(load['sal... | [
"def",
"symlink_list",
"(",
"self",
",",
"load",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"ret",
"=",
"{",
"}",
"if",
"'saltenv'",
"not",
"in",
"load",
":",
"return",... | 34.64 | 19.28 |
def update_in_hdx(self):
# type: () -> None
"""Check if user exists in HDX and if so, update user
Returns:
None
"""
capacity = self.data.get('capacity')
if capacity is not None:
del self.data['capacity'] # remove capacity (which comes from users ... | [
"def",
"update_in_hdx",
"(",
"self",
")",
":",
"# type: () -> None",
"capacity",
"=",
"self",
".",
"data",
".",
"get",
"(",
"'capacity'",
")",
"if",
"capacity",
"is",
"not",
"None",
":",
"del",
"self",
".",
"data",
"[",
"'capacity'",
"]",
"# remove capacit... | 34.307692 | 15.538462 |
def rescale(self, fun):
"""
perform raster computations with custom functions and assign them to the existing raster object in memory
Parameters
----------
fun: function
the custom function to compute on the data
Examples
--------
>>> with Ra... | [
"def",
"rescale",
"(",
"self",
",",
"fun",
")",
":",
"if",
"self",
".",
"bands",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'only single band images are currently supported'",
")",
"# load array",
"mat",
"=",
"self",
".",
"matrix",
"(",
")",
"# scale values"... | 27 | 22.153846 |
def create_cache_database(self):
""" Create a new SQLite3 database for use with Cache objects
:raises: IOError if there is a problem creating the database file
"""
conn = sqlite3.connect(self.database)
conn.text_factory = str
c = conn.cursor()
c.execute("""CR... | [
"def",
"create_cache_database",
"(",
"self",
")",
":",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"self",
".",
"database",
")",
"conn",
".",
"text_factory",
"=",
"str",
"c",
"=",
"conn",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"\"\"\"CREAT... | 32.75 | 15.45 |
def convert_coordinates(coords, origin, wgs84, wrapped):
""" Convert coordinates from one crs to another """
if isinstance(coords, list) or isinstance(coords, tuple):
try:
if isinstance(coords[0], list) or isinstance(coords[0], tuple):
return [convert_coordinates(list(c), ori... | [
"def",
"convert_coordinates",
"(",
"coords",
",",
"origin",
",",
"wgs84",
",",
"wrapped",
")",
":",
"if",
"isinstance",
"(",
"coords",
",",
"list",
")",
"or",
"isinstance",
"(",
"coords",
",",
"tuple",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"co... | 38.625 | 21.4375 |
def AgregarTributo(self, cod_tributo, descripcion=None,
base_imponible=None, alicuota=None, importe=None):
"Agrega la información referente a los tributos de la liquidación"
trib = {'codTributo': cod_tributo, 'descripcion': descripcion,
'baseImponible': base_... | [
"def",
"AgregarTributo",
"(",
"self",
",",
"cod_tributo",
",",
"descripcion",
"=",
"None",
",",
"base_imponible",
"=",
"None",
",",
"alicuota",
"=",
"None",
",",
"importe",
"=",
"None",
")",
":",
"trib",
"=",
"{",
"'codTributo'",
":",
"cod_tributo",
",",
... | 53.090909 | 22.727273 |
def cmd(self, args=None, interact=True):
"""Process command-line arguments."""
if args is None:
parsed_args = arguments.parse_args()
else:
parsed_args = arguments.parse_args(args)
self.exit_code = 0
with self.handling_exceptions():
self.use_arg... | [
"def",
"cmd",
"(",
"self",
",",
"args",
"=",
"None",
",",
"interact",
"=",
"True",
")",
":",
"if",
"args",
"is",
"None",
":",
"parsed_args",
"=",
"arguments",
".",
"parse_args",
"(",
")",
"else",
":",
"parsed_args",
"=",
"arguments",
".",
"parse_args",... | 38.4 | 11.7 |
def _get_supervisorctl_bin(bin_env):
'''
Return supervisorctl command to call, either from a virtualenv, an argument
passed in, or from the global modules options
'''
cmd = 'supervisorctl'
if not bin_env:
which_result = __salt__['cmd.which_bin']([cmd])
if which_result is None:
... | [
"def",
"_get_supervisorctl_bin",
"(",
"bin_env",
")",
":",
"cmd",
"=",
"'supervisorctl'",
"if",
"not",
"bin_env",
":",
"which_result",
"=",
"__salt__",
"[",
"'cmd.which_bin'",
"]",
"(",
"[",
"cmd",
"]",
")",
"if",
"which_result",
"is",
"None",
":",
"raise",
... | 32.636364 | 19.363636 |
def crypto_sign_seed_keypair(seed):
"""
Computes and returns the public key and secret key using the seed ``seed``.
:param seed: bytes
:rtype: (bytes(public_key), bytes(secret_key))
"""
if len(seed) != crypto_sign_SEEDBYTES:
raise exc.ValueError("Invalid seed")
pk = ffi.new("unsign... | [
"def",
"crypto_sign_seed_keypair",
"(",
"seed",
")",
":",
"if",
"len",
"(",
"seed",
")",
"!=",
"crypto_sign_SEEDBYTES",
":",
"raise",
"exc",
".",
"ValueError",
"(",
"\"Invalid seed\"",
")",
"pk",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"cryp... | 30.954545 | 18.772727 |
def _CopyFromDateTimeValues(self, date_time_values):
"""Copies time elements from date and time values.
Args:
date_time_values (dict[str, int]): date and time values, such as year,
month, day of month, hours, minutes, seconds, microseconds.
Raises:
ValueError: if no helper can be cr... | [
"def",
"_CopyFromDateTimeValues",
"(",
"self",
",",
"date_time_values",
")",
":",
"year",
"=",
"date_time_values",
".",
"get",
"(",
"'year'",
",",
"0",
")",
"month",
"=",
"date_time_values",
".",
"get",
"(",
"'month'",
",",
"0",
")",
"day_of_month",
"=",
"... | 39.580645 | 20.516129 |
def eval_objfn(self):
"""Compute components of objective function as well as total
contribution to objective function.
"""
fval = self.obfn_f(self.obfn_fvar())
g0val = self.obfn_g0(self.obfn_g0var())
g1val = self.obfn_g1(self.obfn_g1var())
obj = fval + g0val + g1... | [
"def",
"eval_objfn",
"(",
"self",
")",
":",
"fval",
"=",
"self",
".",
"obfn_f",
"(",
"self",
".",
"obfn_fvar",
"(",
")",
")",
"g0val",
"=",
"self",
".",
"obfn_g0",
"(",
"self",
".",
"obfn_g0var",
"(",
")",
")",
"g1val",
"=",
"self",
".",
"obfn_g1",... | 35.5 | 8.6 |
def find_obfuscatables(tokens, obfunc, ignore_length=False):
"""
Iterates over *tokens*, which must be an equivalent output to what
tokenize.generate_tokens() produces, calling *obfunc* on each with the
following parameters:
- **tokens:** The current list of tokens.
- **index:** ... | [
"def",
"find_obfuscatables",
"(",
"tokens",
",",
"obfunc",
",",
"ignore_length",
"=",
"False",
")",
":",
"global",
"keyword_args",
"keyword_args",
"=",
"analyze",
".",
"enumerate_keyword_args",
"(",
"tokens",
")",
"global",
"imported_modules",
"imported_modules",
"=... | 39.104167 | 18.9375 |
def _get_baremetal_switches(self, port):
"""Get switch ip addresses from baremetal transaction.
This method is used to extract switch information
from the transaction where VNIC_TYPE is baremetal.
:param port: Received port transaction
:returns: list of all switches
:re... | [
"def",
"_get_baremetal_switches",
"(",
"self",
",",
"port",
")",
":",
"all_switches",
"=",
"set",
"(",
")",
"active_switches",
"=",
"set",
"(",
")",
"all_link_info",
"=",
"port",
"[",
"bc",
".",
"portbindings",
".",
"PROFILE",
"]",
"[",
"'local_link_informat... | 34.827586 | 16.862069 |
def lock(remote=None):
'''
Place an update.lk
``remote`` can either be a dictionary containing repo configuration
information, or a pattern. If the latter, then remotes for which the URL
matches the pattern will be locked.
'''
def _do_lock(repo):
success = []
failed = []
... | [
"def",
"lock",
"(",
"remote",
"=",
"None",
")",
":",
"def",
"_do_lock",
"(",
"repo",
")",
":",
"success",
"=",
"[",
"]",
"failed",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"repo",
"[",
"'lockfile'",
"]",
")",
":",
"try... | 31.622222 | 19.444444 |
def write_trailer(self, sector, key_a=(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF), auth_bits=(0xFF, 0x07, 0x80),
user_data=0x69, key_b=(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF)):
"""
Writes sector trailer of specified sector. Tag and auth must be set - does auth.
If value is None, val... | [
"def",
"write_trailer",
"(",
"self",
",",
"sector",
",",
"key_a",
"=",
"(",
"0xFF",
",",
"0xFF",
",",
"0xFF",
",",
"0xFF",
",",
"0xFF",
",",
"0xFF",
")",
",",
"auth_bits",
"=",
"(",
"0xFF",
",",
"0x07",
",",
"0x80",
")",
",",
"user_data",
"=",
"0... | 55.888889 | 25 |
def summoner_names_to_id(summoners):
"""
Gets a list of summoners names and return a dictionary mapping the player name to his/her summoner id
:param summoners: a list of player names
:return: a dictionary name -> id
"""
ids = {}
for start, end in _slice(0, len(summoners), 40):
resul... | [
"def",
"summoner_names_to_id",
"(",
"summoners",
")",
":",
"ids",
"=",
"{",
"}",
"for",
"start",
",",
"end",
"in",
"_slice",
"(",
"0",
",",
"len",
"(",
"summoners",
")",
",",
"40",
")",
":",
"result",
"=",
"get_summoners_by_name",
"(",
"summoners",
"["... | 37.75 | 14.416667 |
def fetch(self, category=CATEGORY_QUESTION, offset=DEFAULT_OFFSET):
"""Fetch questions from the Kitsune url.
:param category: the category of items to fetch
:offset: obtain questions after offset
:returns: a generator of questions
"""
if not offset:
offset = ... | [
"def",
"fetch",
"(",
"self",
",",
"category",
"=",
"CATEGORY_QUESTION",
",",
"offset",
"=",
"DEFAULT_OFFSET",
")",
":",
"if",
"not",
"offset",
":",
"offset",
"=",
"DEFAULT_OFFSET",
"kwargs",
"=",
"{",
"\"offset\"",
":",
"offset",
"}",
"items",
"=",
"super"... | 30.714286 | 16.214286 |
def set(self, time, value, compact=False):
"""Set the value for the time series. If compact is True, only set the
value if it's different from what it would be anyway.
"""
if (len(self) == 0) or (not compact) or \
(compact and self.get(time) != value):
self._... | [
"def",
"set",
"(",
"self",
",",
"time",
",",
"value",
",",
"compact",
"=",
"False",
")",
":",
"if",
"(",
"len",
"(",
"self",
")",
"==",
"0",
")",
"or",
"(",
"not",
"compact",
")",
"or",
"(",
"compact",
"and",
"self",
".",
"get",
"(",
"time",
... | 41 | 11.625 |
def _to_r(o, as_data=False, level=0):
"""Helper function to convert python data structures to R equivalents
TODO: a single model for transforming to r to handle
* function args
* lists as function args
"""
if o is None:
return "NA"
if isinstance(o, basestring):
return o
... | [
"def",
"_to_r",
"(",
"o",
",",
"as_data",
"=",
"False",
",",
"level",
"=",
"0",
")",
":",
"if",
"o",
"is",
"None",
":",
"return",
"\"NA\"",
"if",
"isinstance",
"(",
"o",
",",
"basestring",
")",
":",
"return",
"o",
"if",
"hasattr",
"(",
"o",
",",
... | 36.5 | 16.333333 |
def spring_project(
adata, project_dir, embedding_method,
subplot_name = None,
cell_groupings=None, custom_color_tracks=None,
total_counts_key = 'n_counts', overwrite = False
):
"""Exports to a SPRING project directory [Weinreb17]_.
Visualize annotation present in `adata... | [
"def",
"spring_project",
"(",
"adata",
",",
"project_dir",
",",
"embedding_method",
",",
"subplot_name",
"=",
"None",
",",
"cell_groupings",
"=",
"None",
",",
"custom_color_tracks",
"=",
"None",
",",
"total_counts_key",
"=",
"'n_counts'",
",",
"overwrite",
"=",
... | 44.972973 | 24.297297 |
def censor_entity_types(self, entity_types):
# type: (set) -> TermDocMatrixFactory
'''
Entity types to exclude from feature construction. Terms matching
specificed entities, instead of labeled by their lower case orthographic
form or lemma, will be labeled by their entity type.
... | [
"def",
"censor_entity_types",
"(",
"self",
",",
"entity_types",
")",
":",
"# type: (set) -> TermDocMatrixFactory",
"assert",
"type",
"(",
"entity_types",
")",
"==",
"set",
"self",
".",
"_entity_types_to_censor",
"=",
"entity_types",
"self",
".",
"_feats_from_spacy_doc",... | 36.5 | 22.333333 |
def limit(limit, every=1):
"""This decorator factory creates a decorator that can be applied to
functions in order to limit the rate the function can be invoked.
The rate is `limit` over `every`, where limit is the number of
invocation allowed every `every` seconds.
limit(4, 60) creates ... | [
"def",
"limit",
"(",
"limit",
",",
"every",
"=",
"1",
")",
":",
"def",
"limitdecorator",
"(",
"fn",
")",
":",
"\"\"\"This is the actual decorator that performs the rate-limiting.\"\"\"",
"semaphore",
"=",
"_threading",
".",
"Semaphore",
"(",
"limit",
")",
"@",
"_f... | 37.740741 | 20.592593 |
def zrangebylex(self, name, min, max, start=None, num=None):
"""
Return the lexicographical range of values from sorted set ``name``
between ``min`` and ``max``.
If ``start`` and ``num`` are specified, then return a slice of the
range.
"""
if (start is not None a... | [
"def",
"zrangebylex",
"(",
"self",
",",
"name",
",",
"min",
",",
"max",
",",
"start",
"=",
"None",
",",
"num",
"=",
"None",
")",
":",
"if",
"(",
"start",
"is",
"not",
"None",
"and",
"num",
"is",
"None",
")",
"or",
"(",
"num",
"is",
"not",
"None... | 44.333333 | 17.533333 |
def __dict_to_service_spec(spec):
'''
Converts a dictionary into kubernetes V1ServiceSpec instance.
'''
spec_obj = kubernetes.client.V1ServiceSpec()
for key, value in iteritems(spec): # pylint: disable=too-many-nested-blocks
if key == 'ports':
spec_obj.ports = []
for... | [
"def",
"__dict_to_service_spec",
"(",
"spec",
")",
":",
"spec_obj",
"=",
"kubernetes",
".",
"client",
".",
"V1ServiceSpec",
"(",
")",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"spec",
")",
":",
"# pylint: disable=too-many-nested-blocks",
"if",
"key",
... | 39.238095 | 17.333333 |
def write_to_disk(filename, delete=False, content=get_time()):
"""
Write filename out to disk
"""
if not os.path.exists(os.path.dirname(filename)):
return
if delete:
if os.path.lexists(filename):
os.remove(filename)
else:
with open(filename, 'wb') as f:
... | [
"def",
"write_to_disk",
"(",
"filename",
",",
"delete",
"=",
"False",
",",
"content",
"=",
"get_time",
"(",
")",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
")",
":",
"retur... | 28.916667 | 12.083333 |
def update_g(self, fs=None, qinv=None, fc=None, kappa_tst_re=1.0,
kappa_tst_im=0.0, kappa_pu_re=1.0, kappa_pu_im=0.0,
kappa_c=1.0):
""" Calculate the open loop gain g(f,t) given the new parameters
kappa_c(t), kappa_a(t), f_c(t), fs, and qinv.
Parameters
... | [
"def",
"update_g",
"(",
"self",
",",
"fs",
"=",
"None",
",",
"qinv",
"=",
"None",
",",
"fc",
"=",
"None",
",",
"kappa_tst_re",
"=",
"1.0",
",",
"kappa_tst_im",
"=",
"0.0",
",",
"kappa_pu_re",
"=",
"1.0",
",",
"kappa_pu_im",
"=",
"0.0",
",",
"kappa_c"... | 39.631579 | 19.447368 |
def default_decoder(self, obj):
"""Handle a dict that might contain a wrapped state for a custom type."""
typename, marshalled_state = self.unwrap_callback(obj)
if typename is None:
return obj
try:
cls, unmarshaller = self.serializer.unmarshallers[typename]
... | [
"def",
"default_decoder",
"(",
"self",
",",
"obj",
")",
":",
"typename",
",",
"marshalled_state",
"=",
"self",
".",
"unwrap_callback",
"(",
"obj",
")",
"if",
"typename",
"is",
"None",
":",
"return",
"obj",
"try",
":",
"cls",
",",
"unmarshaller",
"=",
"se... | 37.235294 | 20.352941 |
def write_table(self):
"""
|write_table| with HTML table format.
:Example:
:ref:`example-html-table-writer`
.. note::
- |None| is not written
"""
tags = _get_tags_module()
with self._logger:
self._verify_property()
... | [
"def",
"write_table",
"(",
"self",
")",
":",
"tags",
"=",
"_get_tags_module",
"(",
")",
"with",
"self",
".",
"_logger",
":",
"self",
".",
"_verify_property",
"(",
")",
"self",
".",
"_preprocess",
"(",
")",
"if",
"typepy",
".",
"is_not_null_string",
"(",
... | 26.62069 | 21.034483 |
def prior_H0(self, H0, H0_min=0, H0_max=200):
"""
checks whether the parameter vector has left its bound, if so, adds a big number
"""
if H0 < H0_min or H0 > H0_max:
penalty = -10**15
return penalty, False
else:
return 0, True | [
"def",
"prior_H0",
"(",
"self",
",",
"H0",
",",
"H0_min",
"=",
"0",
",",
"H0_max",
"=",
"200",
")",
":",
"if",
"H0",
"<",
"H0_min",
"or",
"H0",
">",
"H0_max",
":",
"penalty",
"=",
"-",
"10",
"**",
"15",
"return",
"penalty",
",",
"False",
"else",
... | 32.666667 | 12.666667 |
def get_cookies_from_cache(username):
"""
Returns a RequestsCookieJar containing the cached cookies for the given
user.
"""
logging.debug('Trying to get cookies from the cache.')
path = get_cookies_cache_path(username)
cj = requests.cookies.RequestsCookieJar()
try:
cached_cj = ... | [
"def",
"get_cookies_from_cache",
"(",
"username",
")",
":",
"logging",
".",
"debug",
"(",
"'Trying to get cookies from the cache.'",
")",
"path",
"=",
"get_cookies_cache_path",
"(",
"username",
")",
"cj",
"=",
"requests",
".",
"cookies",
".",
"RequestsCookieJar",
"(... | 29.1 | 19.1 |
def index_all(self, index_name):
"""Index all available documents, using streaming_bulk for speed
Args:
index_name (string): The index
"""
oks = 0
notoks = 0
for ok, item in streaming_bulk(
self.es_client,
self._iter_documents(index_name)
... | [
"def",
"index_all",
"(",
"self",
",",
"index_name",
")",
":",
"oks",
"=",
"0",
"notoks",
"=",
"0",
"for",
"ok",
",",
"item",
"in",
"streaming_bulk",
"(",
"self",
".",
"es_client",
",",
"self",
".",
"_iter_documents",
"(",
"index_name",
")",
")",
":",
... | 24.571429 | 16.619048 |
def before_reject(analysis):
"""Function triggered before 'unassign' transition takes place
"""
worksheet = analysis.getWorksheet()
if not worksheet:
return
# Rejection of a routine analysis causes the removal of their duplicates
for dup in worksheet.get_duplicates_for(analysis):
... | [
"def",
"before_reject",
"(",
"analysis",
")",
":",
"worksheet",
"=",
"analysis",
".",
"getWorksheet",
"(",
")",
"if",
"not",
"worksheet",
":",
"return",
"# Rejection of a routine analysis causes the removal of their duplicates",
"for",
"dup",
"in",
"worksheet",
".",
"... | 34.1 | 15.2 |
def OnUpView(self, event):
"""Request to move up the hierarchy to highest-weight parent"""
node = self.activated_node
parents = []
selected_parent = None
if node:
if hasattr( self.adapter, 'best_parent' ):
selected_parent = self.adapter.best_p... | [
"def",
"OnUpView",
"(",
"self",
",",
"event",
")",
":",
"node",
"=",
"self",
".",
"activated_node",
"parents",
"=",
"[",
"]",
"selected_parent",
"=",
"None",
"if",
"node",
":",
"if",
"hasattr",
"(",
"self",
".",
"adapter",
",",
"'best_parent'",
")",
":... | 41.956522 | 18.782609 |
def add(self, name, filt, info='', params=(), setn=None):
"""
Add filter.
Parameters
----------
name : str
filter name
filt : array_like
boolean filter array
info : str
informative description of the filter
params : tup... | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"filt",
",",
"info",
"=",
"''",
",",
"params",
"=",
"(",
")",
",",
"setn",
"=",
"None",
")",
":",
"iname",
"=",
"'{:.0f}_'",
".",
"format",
"(",
"self",
".",
"n",
")",
"+",
"name",
"self",
".",
"in... | 23.775 | 16.925 |
def get_composition_repository_session(self, proxy):
"""Gets the session for retrieving composition to repository
mappings.
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.CompositionRepositorySession) - a
CompositionRepositorySession
raise: O... | [
"def",
"get_composition_repository_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_composition_repository",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"import",
"sessions",
"except",
"ImportErro... | 39 | 17.192308 |
def get_strokes(self):
"""Return a css snippet containing all stroke style options"""
def stroke_dict_to_css(stroke, i=None):
"""Return a css style for the given option"""
css = [
'%s.series%s {\n' %
(self.id, '.serie-%d' % i if i is not None else... | [
"def",
"get_strokes",
"(",
"self",
")",
":",
"def",
"stroke_dict_to_css",
"(",
"stroke",
",",
"i",
"=",
"None",
")",
":",
"\"\"\"Return a css style for the given option\"\"\"",
"css",
"=",
"[",
"'%s.series%s {\\n'",
"%",
"(",
"self",
".",
"id",
",",
"'.serie-%d'... | 39.387097 | 17.870968 |
def format_h4(s, format="text", indents=0):
"""
Encloses string in format text
Args, Returns: see format_h1()
"""
_CHAR = "^"
if format.startswith("text"):
return format_underline(s, _CHAR, indents)
elif format.startswith("markdown"):
return ["#### {}".format(s)]... | [
"def",
"format_h4",
"(",
"s",
",",
"format",
"=",
"\"text\"",
",",
"indents",
"=",
"0",
")",
":",
"_CHAR",
"=",
"\"^\"",
"if",
"format",
".",
"startswith",
"(",
"\"text\"",
")",
":",
"return",
"format_underline",
"(",
"s",
",",
"_CHAR",
",",
"indents",... | 27.857143 | 10.285714 |
def propagate(self, **args):
"""
Propagates activation through the network. Optionally, takes input layer names
as keywords, and their associated activations. If input layer(s) are given, then
propagate() will return the output layer's activation. If there is more than
one output... | [
"def",
"propagate",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"self",
".",
"prePropagate",
"(",
"*",
"*",
"args",
")",
"for",
"key",
"in",
"args",
":",
"layer",
"=",
"self",
".",
"getLayer",
"(",
"key",
")",
"if",
"layer",
".",
"kind",
"==",
... | 44.447761 | 19.671642 |
def hexdump_iter(logger, fd, width=16, skip=True, hexii=False, begin=0, highlight=None):
r"""
Return a hexdump-dump of a string as a generator of lines. Unless you have
massive amounts of data you probably want to use :meth:`hexdump`.
Arguments:
logger(FastLogger): Logger object
fd(fil... | [
"def",
"hexdump_iter",
"(",
"logger",
",",
"fd",
",",
"width",
"=",
"16",
",",
"skip",
"=",
"True",
",",
"hexii",
"=",
"False",
",",
"begin",
"=",
"0",
",",
"highlight",
"=",
"None",
")",
":",
"style",
"=",
"logger",
".",
"style",
".",
"hexdump",
... | 32.111111 | 21.303704 |
def banlist(self, channel):
"""
Get the channel banlist.
Required arguments:
* channel - Channel of which to get the banlist for.
"""
with self.lock:
self.is_in_channel(channel)
self.send('MODE %s b' % channel)
bans = []
w... | [
"def",
"banlist",
"(",
"self",
",",
"channel",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"is_in_channel",
"(",
"channel",
")",
"self",
".",
"send",
"(",
"'MODE %s b'",
"%",
"channel",
")",
"bans",
"=",
"[",
"]",
"while",
"self",
".",
... | 33.904762 | 15.428571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.