text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_intrusion_data(self, inv_points=None):
r"""
Plot a simple drainage curve
"""
net = self.project.network
if "pore.invasion_pressure" not in self.props():
logger.error("Cannot plot drainage curve. Please run " +
" algorithm first")
... | [
"def",
"get_intrusion_data",
"(",
"self",
",",
"inv_points",
"=",
"None",
")",
":",
"net",
"=",
"self",
".",
"project",
".",
"network",
"if",
"\"pore.invasion_pressure\"",
"not",
"in",
"self",
".",
"props",
"(",
")",
":",
"logger",
".",
"error",
"(",
"\"... | 37.625 | 0.001619 |
def get_as_nullable_datetime(self, key):
"""
Converts map element into a Date or returns None if conversion is not possible.
:param key: an index of element to get.
:return: Date value of the element or None if conversion is not supported.
"""
value = self.get(key)
... | [
"def",
"get_as_nullable_datetime",
"(",
"self",
",",
"key",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"key",
")",
"return",
"DateTimeConverter",
".",
"to_nullable_datetime",
"(",
"value",
")"
] | 36.7 | 0.010638 |
def retrieve_public_key(user_repo):
"""Retrieve the public key from the Travis API.
The Travis API response is accessed as JSON so that Travis-Encrypt
can easily find the public key that is to be passed to cryptography's
load_pem_public_key function. Due to issues with some public keys being
return... | [
"def",
"retrieve_public_key",
"(",
"user_repo",
")",
":",
"url",
"=",
"'https://api.travis-ci.org/repos/{}/key'",
".",
"format",
"(",
"user_repo",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"try",
":",
"return",
"response",
".",
"json",
"("... | 38.15625 | 0.001597 |
def get_bb_intersections(recording):
"""
Get all intersections of the bounding boxes of strokes.
Parameters
----------
recording : list of lists of integers
Returns
-------
A symmetrical matrix which indicates if two bounding boxes intersect.
"""
intersections = numpy.zeros((le... | [
"def",
"get_bb_intersections",
"(",
"recording",
")",
":",
"intersections",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"len",
"(",
"recording",
")",
",",
"len",
"(",
"recording",
")",
")",
",",
"dtype",
"=",
"bool",
")",
"for",
"i",
"in",
"range",
"(",
"l... | 34.714286 | 0.001335 |
def run(self):
"""
Executes a started pipeline by pulling results from it's output
``Pipers``. Processing nodes i.e. ``Pipers`` with the ``track``
attribute set ``True`` will have their returned results stored within
the ``Dagger.stats['pipers_tracked']`` dictionary. A running... | [
"def",
"run",
"(",
"self",
")",
":",
"# remove non-block results for end tasks",
"if",
"self",
".",
"_started",
".",
"isSet",
"(",
")",
"and",
"not",
"self",
".",
"_running",
".",
"isSet",
"(",
")",
"and",
"not",
"self",
".",
"_pausing",
".",
"isSet",
"(... | 40.5 | 0.01005 |
def add_shift_view(request, semester):
"""
View for the workshift manager to create new types of workshifts.
"""
page_name = "Add Workshift"
any_management = utils.can_manage(request.user, semester, any_pool=True)
if not any_management:
messages.add_message(
request,
... | [
"def",
"add_shift_view",
"(",
"request",
",",
"semester",
")",
":",
"page_name",
"=",
"\"Add Workshift\"",
"any_management",
"=",
"utils",
".",
"can_manage",
"(",
"request",
".",
"user",
",",
"semester",
",",
"any_pool",
"=",
"True",
")",
"if",
"not",
"any_m... | 32.183333 | 0.000503 |
def fo_pct(self):
"""
Get the by team overall face-off win %.
:returns: dict, ``{ 'home': %, 'away': % }``
"""
tots = self.team_totals
return {
t: tots[t]['won']/(1.0*tots[t]['total']) if tots[t]['total'] else 0.0
for t in [ 'home', 'away'... | [
"def",
"fo_pct",
"(",
"self",
")",
":",
"tots",
"=",
"self",
".",
"team_totals",
"return",
"{",
"t",
":",
"tots",
"[",
"t",
"]",
"[",
"'won'",
"]",
"/",
"(",
"1.0",
"*",
"tots",
"[",
"t",
"]",
"[",
"'total'",
"]",
")",
"if",
"tots",
"[",
"t",... | 29.272727 | 0.018072 |
def strong_connect(self, q, node, index, component):
'''
API: strong_connect (self, q, node, index, component)
Description:
Used by tarjan method. This method should not be called directly by
user.
Input:
q: Node list.
node: Node that is being conn... | [
"def",
"strong_connect",
"(",
"self",
",",
"q",
",",
"node",
",",
"index",
",",
"component",
")",
":",
"self",
".",
"set_node_attr",
"(",
"node",
",",
"'index'",
",",
"index",
")",
"self",
".",
"set_node_attr",
"(",
"node",
",",
"'lowlink'",
",",
"inde... | 43.139535 | 0.002109 |
def parse(self, argv, tokenizer=DefaultTokenizer):
"""
Parse command line to out tree
:type argv object
:type tokenizer AbstractTokenizer
"""
args = tokenizer.tokenize(argv)
_lang = tokenizer.language_definition()
#
# for param in self.__args:
# if self._is_default_arg(param)... | [
"def",
"parse",
"(",
"self",
",",
"argv",
",",
"tokenizer",
"=",
"DefaultTokenizer",
")",
":",
"args",
"=",
"tokenizer",
".",
"tokenize",
"(",
"argv",
")",
"_lang",
"=",
"tokenizer",
".",
"language_definition",
"(",
")",
"#",
"# for param in self.__args:",
"... | 27.421053 | 0.001855 |
def p_partselect_pointer(self, p):
'partselect : pointer LBRACKET expression COLON expression RBRACKET'
p[0] = Partselect(p[1], p[3], p[5], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_partselect_pointer",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Partselect",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"p",
"[",
"5",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
... | 52.25 | 0.009434 |
def add_resource_subscription(self, device_id, _resource_path, **kwargs): # noqa: E501
"""Subscribe to a resource path # noqa: E501
The Device Management Connect eventing model consists of observable resources. This means that endpoints can deliver updated resource content, periodically or with a mo... | [
"def",
"add_resource_subscription",
"(",
"self",
",",
"device_id",
",",
"_resource_path",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":... | 112.272727 | 0.000803 |
def decode(self, codec_options=DEFAULT_CODEC_OPTIONS):
"""Decode this BSON data.
By default, returns a BSON document represented as a Python
:class:`dict`. To use a different :class:`MutableMapping` class,
configure a :class:`~bson.codec_options.CodecOptions`::
>>> import c... | [
"def",
"decode",
"(",
"self",
",",
"codec_options",
"=",
"DEFAULT_CODEC_OPTIONS",
")",
":",
"if",
"not",
"isinstance",
"(",
"codec_options",
",",
"CodecOptions",
")",
":",
"raise",
"_CODEC_OPTIONS_TYPE_ERROR",
"return",
"_bson_to_dict",
"(",
"self",
",",
"codec_op... | 44.522727 | 0.000999 |
def role_create(role, principal, endpoint_id):
"""
Executor for `globus endpoint role show`
"""
principal_type, principal_val = principal
client = get_client()
if principal_type == "identity":
principal_val = maybe_lookup_identity_id(principal_val)
if not principal_val:
... | [
"def",
"role_create",
"(",
"role",
",",
"principal",
",",
"endpoint_id",
")",
":",
"principal_type",
",",
"principal_val",
"=",
"principal",
"client",
"=",
"get_client",
"(",
")",
"if",
"principal_type",
"==",
"\"identity\"",
":",
"principal_val",
"=",
"maybe_lo... | 34.84 | 0.002235 |
def random(self, cascadeFetch=False):
'''
Random - Returns a random record in current filterset.
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetched immediately. If False, foreign objects will be fetched on-access.
@return - Instance of M... | [
"def",
"random",
"(",
"self",
",",
"cascadeFetch",
"=",
"False",
")",
":",
"matchedKeys",
"=",
"list",
"(",
"self",
".",
"getPrimaryKeys",
"(",
")",
")",
"obj",
"=",
"None",
"# Loop so we don't return None when there are items, if item is deleted between getting key and... | 38.333333 | 0.026874 |
def loss(loss_value):
"""Calculates aggregated mean loss."""
total_loss = tf.Variable(0.0, False)
loss_count = tf.Variable(0, False)
total_loss_update = tf.assign_add(total_loss, loss_value)
loss_count_update = tf.assign_add(loss_count, 1)
loss_op = total_loss / tf.cast(loss_count, tf.float32)
return [tot... | [
"def",
"loss",
"(",
"loss_value",
")",
":",
"total_loss",
"=",
"tf",
".",
"Variable",
"(",
"0.0",
",",
"False",
")",
"loss_count",
"=",
"tf",
".",
"Variable",
"(",
"0",
",",
"False",
")",
"total_loss_update",
"=",
"tf",
".",
"assign_add",
"(",
"total_l... | 44.5 | 0.022039 |
def _condense(self, data):
'''
Condense by adding together all of the lists.
'''
rval = {}
for resolution,histogram in data.items():
for value,count in histogram.items():
rval[ value ] = count + rval.get(value,0)
return rval | [
"def",
"_condense",
"(",
"self",
",",
"data",
")",
":",
"rval",
"=",
"{",
"}",
"for",
"resolution",
",",
"histogram",
"in",
"data",
".",
"items",
"(",
")",
":",
"for",
"value",
",",
"count",
"in",
"histogram",
".",
"items",
"(",
")",
":",
"rval",
... | 28.222222 | 0.026718 |
def add_container_output_args(argument_parser):
"""Define command-line arguments for output of a container (result files).
@param argument_parser: an argparse parser instance
"""
argument_parser.add_argument("--output-directory", metavar="DIR", default="output.files",
help="target directory for ... | [
"def",
"add_container_output_args",
"(",
"argument_parser",
")",
":",
"argument_parser",
".",
"add_argument",
"(",
"\"--output-directory\"",
",",
"metavar",
"=",
"\"DIR\"",
",",
"default",
"=",
"\"output.files\"",
",",
"help",
"=",
"\"target directory for result files (de... | 64.666667 | 0.011864 |
def schedule(self):
"""Initiate distribution of the test collection.
Initiate scheduling of the items across the nodes. If this gets called
again later it behaves the same as calling ``._reschedule()`` on all
nodes so that newly added nodes will start to be used.
If ``.collect... | [
"def",
"schedule",
"(",
"self",
")",
":",
"assert",
"self",
".",
"collection_is_completed",
"# Initial distribution already happened, reschedule on all nodes",
"if",
"self",
".",
"collection",
"is",
"not",
"None",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
":",... | 36.271186 | 0.001365 |
def process_experiences(self, current_info: AllBrainInfo, next_info: AllBrainInfo):
"""
Checks agent histories for processing condition, and processes them as necessary.
Processing involves calculating value and advantage targets for model updating step.
:param current_info: Current AllB... | [
"def",
"process_experiences",
"(",
"self",
",",
"current_info",
":",
"AllBrainInfo",
",",
"next_info",
":",
"AllBrainInfo",
")",
":",
"info_teacher",
"=",
"next_info",
"[",
"self",
".",
"brain_to_imitate",
"]",
"for",
"l",
"in",
"range",
"(",
"len",
"(",
"in... | 63.210526 | 0.009844 |
def chloginclass(name, loginclass, root=None):
'''
Change the default login class of the user
.. versionadded:: 2016.3.5
CLI Example:
.. code-block:: bash
salt '*' user.chloginclass foo staff
'''
if loginclass == get_loginclass(name):
return True
cmd = ['pw', 'usermo... | [
"def",
"chloginclass",
"(",
"name",
",",
"loginclass",
",",
"root",
"=",
"None",
")",
":",
"if",
"loginclass",
"==",
"get_loginclass",
"(",
"name",
")",
":",
"return",
"True",
"cmd",
"=",
"[",
"'pw'",
",",
"'usermod'",
",",
"'-L'",
",",
"'{0}'",
".",
... | 22.333333 | 0.002045 |
def get_system_bck_color():
"""
Gets a system color for drawing the fold scope background.
"""
def merged_colors(colorA, colorB, factor):
maxFactor = 100
colorA = QtGui.QColor(colorA)
colorB = QtGui.QColor(colorB)
tmp = colorA
t... | [
"def",
"get_system_bck_color",
"(",
")",
":",
"def",
"merged_colors",
"(",
"colorA",
",",
"colorB",
",",
"factor",
")",
":",
"maxFactor",
"=",
"100",
"colorA",
"=",
"QtGui",
".",
"QColor",
"(",
"colorA",
")",
"colorB",
"=",
"QtGui",
".",
"QColor",
"(",
... | 42.095238 | 0.002212 |
def set(constants):
"""
REACH INTO THE MODULES AND OBJECTS TO SET CONSTANTS.
THINK OF THIS AS PRIMITIVE DEPENDENCY INJECTION FOR MODULES.
USEFUL FOR SETTING DEBUG FLAGS.
"""
if not constants:
return
constants = wrap(constants)
for k, new_value in constants.leaves():
erro... | [
"def",
"set",
"(",
"constants",
")",
":",
"if",
"not",
"constants",
":",
"return",
"constants",
"=",
"wrap",
"(",
"constants",
")",
"for",
"k",
",",
"new_value",
"in",
"constants",
".",
"leaves",
"(",
")",
":",
"errors",
"=",
"[",
"]",
"try",
":",
... | 34.653846 | 0.001619 |
def load(source, triples=False, cls=PENMANCodec, **kwargs):
"""
Deserialize a list of PENMAN-encoded graphs from *source*.
Args:
source: a filename or file-like object to read from
triples: if True, read graphs as triples instead of as PENMAN
cls: serialization codec class
k... | [
"def",
"load",
"(",
"source",
",",
"triples",
"=",
"False",
",",
"cls",
"=",
"PENMANCodec",
",",
"*",
"*",
"kwargs",
")",
":",
"decode",
"=",
"cls",
"(",
"*",
"*",
"kwargs",
")",
".",
"iterdecode",
"if",
"hasattr",
"(",
"source",
",",
"'read'",
")"... | 34.111111 | 0.001585 |
def is_true(value=None):
'''
Returns a boolean value representing the "truth" of the value passed. The
rules for what is a "True" value are:
1. Integer/float values greater than 0
2. The string values "True" and "true"
3. Any object for which bool(obj) returns True
'''
# Fir... | [
"def",
"is_true",
"(",
"value",
"=",
"None",
")",
":",
"# First, try int/float conversion",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"pass",
"try",
":",
"value",
"=",
"float",
"(",
"valu... | 28.576923 | 0.001302 |
def has_free_slots(self):
"""
Checks if there is a free value smaller than self.size
:return: True if there is a free value, False if not
"""
return next(filterfalse(self.numbers.__contains__, count(1))) < self.size | [
"def",
"has_free_slots",
"(",
"self",
")",
":",
"return",
"next",
"(",
"filterfalse",
"(",
"self",
".",
"numbers",
".",
"__contains__",
",",
"count",
"(",
"1",
")",
")",
")",
"<",
"self",
".",
"size"
] | 41.666667 | 0.011765 |
def define_mask_borders(image2d, sought_value, nadditional=0):
"""Generate mask avoiding undesired values at the borders.
Set to True image borders with values equal to 'sought_value'
Parameters
----------
image2d : numpy array
Initial 2D image.
sought_value : int, float, bool
... | [
"def",
"define_mask_borders",
"(",
"image2d",
",",
"sought_value",
",",
"nadditional",
"=",
"0",
")",
":",
"# input image size",
"naxis2",
",",
"naxis1",
"=",
"image2d",
".",
"shape",
"# initialize mask",
"mask2d",
"=",
"np",
".",
"zeros",
"(",
"(",
"naxis2",
... | 29.078431 | 0.000652 |
def set(self, quantity):
'''
Set the item's quantity to the passed in amount. If nothing is
passed in, a quantity of 1 is assumed. If a decimal value is passsed
in, it is rounded to the 4th decimal place as that is the level of
precision which the Cheddar API accepts.
... | [
"def",
"set",
"(",
"self",
",",
"quantity",
")",
":",
"data",
"=",
"{",
"}",
"data",
"[",
"'quantity'",
"]",
"=",
"self",
".",
"_normalize_quantity",
"(",
"quantity",
")",
"response",
"=",
"self",
".",
"subscription",
".",
"customer",
".",
"product",
"... | 38.285714 | 0.015777 |
def infer_domain(terms):
"""
Infer the domain from a collection of terms.
The algorithm for inferring domains is as follows:
- If all input terms have a domain of GENERIC, the result is GENERIC.
- If there is exactly one non-generic domain in the input terms, the result
is that domain.
... | [
"def",
"infer_domain",
"(",
"terms",
")",
":",
"domains",
"=",
"{",
"t",
".",
"domain",
"for",
"t",
"in",
"terms",
"}",
"num_domains",
"=",
"len",
"(",
"domains",
")",
"if",
"num_domains",
"==",
"0",
":",
"return",
"GENERIC",
"elif",
"num_domains",
"==... | 27.707317 | 0.00085 |
def varimp(self, use_pandas=False):
"""
Pretty print the variable importances, or return them in a list.
:param use_pandas: If True, then the variable importances will be returned as a pandas data frame.
:returns: A list or Pandas DataFrame.
"""
model = self._model_json... | [
"def",
"varimp",
"(",
"self",
",",
"use_pandas",
"=",
"False",
")",
":",
"model",
"=",
"self",
".",
"_model_json",
"[",
"\"output\"",
"]",
"if",
"self",
".",
"algo",
"==",
"'glm'",
"or",
"\"variable_importances\"",
"in",
"list",
"(",
"model",
".",
"keys"... | 42.470588 | 0.008125 |
def unindent(lines):
"""
Remove common indentation from string.
Unlike doctrim there is no special treatment of the first line.
"""
try:
# Determine minimum indentation:
indent = min(len(line) - len(line.lstrip())
for line in lines if line)
except ValueErro... | [
"def",
"unindent",
"(",
"lines",
")",
":",
"try",
":",
"# Determine minimum indentation:",
"indent",
"=",
"min",
"(",
"len",
"(",
"line",
")",
"-",
"len",
"(",
"line",
".",
"lstrip",
"(",
")",
")",
"for",
"line",
"in",
"lines",
"if",
"line",
")",
"ex... | 25.866667 | 0.002488 |
def read_nc(self,filename,**kwargs):
'''
data reader based on :class:`altimetry.tools.nctools.nc` object.
.. note:: THIS can be VERY powerful!
'''
#Set filename
self._filename = filename
remove_existing = kwargs.get('remove_exi... | [
"def",
"read_nc",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"#Set filename\r",
"self",
".",
"_filename",
"=",
"filename",
"remove_existing",
"=",
"kwargs",
".",
"get",
"(",
"'remove_existing'",
",",
"True",
")",
"#Read data from NetCDF\r... | 37 | 0.026345 |
def num_qubits(self) -> Optional[int]:
"""Returns number of qubits in the domain if known, None if unknown."""
if not self:
return None
any_gate = next(iter(self))
return any_gate.num_qubits() | [
"def",
"num_qubits",
"(",
"self",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"not",
"self",
":",
"return",
"None",
"any_gate",
"=",
"next",
"(",
"iter",
"(",
"self",
")",
")",
"return",
"any_gate",
".",
"num_qubits",
"(",
")"
] | 38.5 | 0.008475 |
def check_html_warnings(html, parser=None):
"""Check html warnings
:param html: str: raw html text
:param parser: bs4.BeautifulSoup: html parser
:raise VkPageWarningsError: in case of found warnings
"""
if parser is None:
parser = bs4.BeautifulSoup(html, 'html.parser')
# Check warn... | [
"def",
"check_html_warnings",
"(",
"html",
",",
"parser",
"=",
"None",
")",
":",
"if",
"parser",
"is",
"None",
":",
"parser",
"=",
"bs4",
".",
"BeautifulSoup",
"(",
"html",
",",
"'html.parser'",
")",
"# Check warnings",
"warnings",
"=",
"parser",
".",
"fin... | 32.933333 | 0.001969 |
def parse_treasury_csv_column(column):
"""
Parse a treasury CSV column into a more human-readable format.
Columns start with 'RIFLGFC', followed by Y or M (year or month), followed
by a two-digit number signifying number of years/months, followed by _N.B.
We only care about the middle two entries, ... | [
"def",
"parse_treasury_csv_column",
"(",
"column",
")",
":",
"column_re",
"=",
"re",
".",
"compile",
"(",
"r\"^(?P<prefix>RIFLGFC)\"",
"\"(?P<unit>[YM])\"",
"\"(?P<periods>[0-9]{2})\"",
"\"(?P<suffix>_N.B)$\"",
")",
"match",
"=",
"column_re",
".",
"match",
"(",
"column"... | 35.608696 | 0.001189 |
def sensordata(self, event):
"""
Generates a new reference frame from incoming sensordata
:param event: new sensordata to be merged into referenceframe
"""
if len(self.datatypes) == 0:
return
data = event.data
timestamp = event.timestamp
# b... | [
"def",
"sensordata",
"(",
"self",
",",
"event",
")",
":",
"if",
"len",
"(",
"self",
".",
"datatypes",
")",
"==",
"0",
":",
"return",
"data",
"=",
"event",
".",
"data",
"timestamp",
"=",
"event",
".",
"timestamp",
"# bus = event.bus",
"# TODO: What about mu... | 35.328125 | 0.000861 |
def _query(method='GET', profile=None, url=None, path='api/v1',
action=None, api_key=None, service=None, params=None,
data=None, subdomain=None, verify_ssl=True):
'''
Query the PagerDuty API.
This method should be in utils.pagerduty.
'''
if profile:
creds = __salt__[... | [
"def",
"_query",
"(",
"method",
"=",
"'GET'",
",",
"profile",
"=",
"None",
",",
"url",
"=",
"None",
",",
"path",
"=",
"'api/v1'",
",",
"action",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"service",
"=",
"None",
",",
"params",
"=",
"None",
",",... | 31.30137 | 0.001697 |
def datetimeparser(fmt, strict=True):
"""Return a function to parse strings as :class:`datetime.datetime` objects
using a given format. E.g.::
>>> from petl import datetimeparser
>>> isodatetime = datetimeparser('%Y-%m-%dT%H:%M:%S')
>>> isodatetime('2002-12-25T00:00:00')
datetim... | [
"def",
"datetimeparser",
"(",
"fmt",
",",
"strict",
"=",
"True",
")",
":",
"def",
"parser",
"(",
"value",
")",
":",
"try",
":",
"return",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"value",
".",
"strip",
"(",
")",
",",
"fmt",
")",
"except",
... | 30.793103 | 0.001086 |
def from_arrow_schema(arrow_schema):
""" Convert schema from Arrow to Spark.
"""
return StructType(
[StructField(field.name, from_arrow_type(field.type), nullable=field.nullable)
for field in arrow_schema]) | [
"def",
"from_arrow_schema",
"(",
"arrow_schema",
")",
":",
"return",
"StructType",
"(",
"[",
"StructField",
"(",
"field",
".",
"name",
",",
"from_arrow_type",
"(",
"field",
".",
"type",
")",
",",
"nullable",
"=",
"field",
".",
"nullable",
")",
"for",
"fiel... | 38.333333 | 0.008511 |
def set(self, value):
'''
Atomically sets the value to `value`.
:param value: The value to set.
'''
with self._reference.get_lock():
self._reference.value = value
return value | [
"def",
"set",
"(",
"self",
",",
"value",
")",
":",
"with",
"self",
".",
"_reference",
".",
"get_lock",
"(",
")",
":",
"self",
".",
"_reference",
".",
"value",
"=",
"value",
"return",
"value"
] | 25.777778 | 0.008333 |
def _zforce(self,R,z,phi=0.,t=0.):
"""
NAME:
_zforce
PURPOSE:
evaluate the vertical force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | [
"def",
"_zforce",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"dPhidrr",
"=",
"-",
"(",
"R",
"**",
"2.",
"+",
"z",
"**",
"2.",
"+",
"self",
".",
"_b2",
")",
"**",
"-",
"1.5",
"return",
"dPhidrr",
... | 26.055556 | 0.014403 |
def projection(self, axis):
"""Sums all data along all other axes, then return Hist1D"""
axis = self.get_axis_number(axis)
projected_hist = np.sum(self.histogram, axis=self.other_axes(axis))
return Hist1d.from_histogram(projected_hist, bin_edges=self.bin_edges[axis]) | [
"def",
"projection",
"(",
"self",
",",
"axis",
")",
":",
"axis",
"=",
"self",
".",
"get_axis_number",
"(",
"axis",
")",
"projected_hist",
"=",
"np",
".",
"sum",
"(",
"self",
".",
"histogram",
",",
"axis",
"=",
"self",
".",
"other_axes",
"(",
"axis",
... | 59 | 0.010033 |
def _needs_java(data):
"""Check if a caller needs external java for MuTect.
No longer check for older GATK (<3.6) versions because of time cost; this
won't be relevant to most runs so we skip the sanity check.
"""
vc = dd.get_variantcaller(data)
if isinstance(vc, dict):
out = {}
... | [
"def",
"_needs_java",
"(",
"data",
")",
":",
"vc",
"=",
"dd",
".",
"get_variantcaller",
"(",
"data",
")",
"if",
"isinstance",
"(",
"vc",
",",
"dict",
")",
":",
"out",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"vc",
".",
"items",
"(",
")",
":",... | 36.68 | 0.002125 |
def get_cache_item(self):
'''Gets the cached item. Raises AttributeError if it hasn't been set.'''
if settings.DEBUG:
raise AttributeError('Caching disabled in DEBUG mode')
return getattr(self.template, self.options['template_cache_key']) | [
"def",
"get_cache_item",
"(",
"self",
")",
":",
"if",
"settings",
".",
"DEBUG",
":",
"raise",
"AttributeError",
"(",
"'Caching disabled in DEBUG mode'",
")",
"return",
"getattr",
"(",
"self",
".",
"template",
",",
"self",
".",
"options",
"[",
"'template_cache_ke... | 54 | 0.010949 |
def main(args=None):
"""
Main entry point
"""
# parse args
if args is None:
args = parse_args(sys.argv[1:])
# set logging level
if args.verbose > 1:
set_log_debug()
elif args.verbose == 1:
set_log_info()
outpath = os.path.abspath(os.path.expanduser(args.out_... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"# parse args",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"parse_args",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"# set logging level",
"if",
"args",
".",
"verbose",
">",
"1",
":",
"se... | 32 | 0.000842 |
def _SkipFieldContents(tokenizer):
"""Skips over contents (value or message) of a field.
Args:
tokenizer: A tokenizer to parse the field name and values.
"""
# Try to guess the type of this field.
# If this field is not a message, there should be a ":" between the
# field name and the field value and a... | [
"def",
"_SkipFieldContents",
"(",
"tokenizer",
")",
":",
"# Try to guess the type of this field.",
"# If this field is not a message, there should be a \":\" between the",
"# field name and the field value and also the field value should not",
"# start with \"{\" or \"<\" which indicates the begin... | 41.647059 | 0.015193 |
def validate_absolute_path(self, root: str, absolute_path: str) -> Optional[str]:
"""Validate and return the absolute path.
``root`` is the configured path for the `StaticFileHandler`,
and ``path`` is the result of `get_absolute_path`
This is an instance method called during request pr... | [
"def",
"validate_absolute_path",
"(",
"self",
",",
"root",
":",
"str",
",",
"absolute_path",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"# os.path.abspath strips a trailing /.",
"# We must add it back to `root` so that we only match files",
"# in a directory n... | 49.44898 | 0.001619 |
def signup(request, template="accounts/account_signup.html",
extra_context=None):
"""
Signup form.
"""
profile_form = get_profile_form()
form = profile_form(request.POST or None, request.FILES or None)
if request.method == "POST" and form.is_valid():
new_user = form.save()
... | [
"def",
"signup",
"(",
"request",
",",
"template",
"=",
"\"accounts/account_signup.html\"",
",",
"extra_context",
"=",
"None",
")",
":",
"profile_form",
"=",
"get_profile_form",
"(",
")",
"form",
"=",
"profile_form",
"(",
"request",
".",
"POST",
"or",
"None",
"... | 45.269231 | 0.000832 |
def check_cv(cv, X=None, y=None, classifier=False):
"""Input checker utility for building a CV in a user friendly way.
Parameters
----------
cv : int, a cv generator instance, or None
The input specifying which cv generator to use. It can be an
integer, in which case it is the number of... | [
"def",
"check_cv",
"(",
"cv",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
",",
"classifier",
"=",
"False",
")",
":",
"return",
"_check_cv",
"(",
"cv",
",",
"X",
"=",
"X",
",",
"y",
"=",
"y",
",",
"classifier",
"=",
"classifier",
",",
"warn_mask... | 35.321429 | 0.000984 |
def dfromdm(dm):
"""Returns distance given distance modulus.
"""
if np.size(dm)>1:
dm = np.atleast_1d(dm)
return 10**(1+dm/5) | [
"def",
"dfromdm",
"(",
"dm",
")",
":",
"if",
"np",
".",
"size",
"(",
"dm",
")",
">",
"1",
":",
"dm",
"=",
"np",
".",
"atleast_1d",
"(",
"dm",
")",
"return",
"10",
"**",
"(",
"1",
"+",
"dm",
"/",
"5",
")"
] | 24 | 0.013423 |
def _exec_command(adb_cmd):
"""
Format adb command and execute it in shell
:param adb_cmd: list adb command to execute
:return: string '0' and shell command output if successful, otherwise
raise CalledProcessError exception and return error code
"""
t = tempfile.TemporaryFile()
final_adb... | [
"def",
"_exec_command",
"(",
"adb_cmd",
")",
":",
"t",
"=",
"tempfile",
".",
"TemporaryFile",
"(",
")",
"final_adb_cmd",
"=",
"[",
"]",
"for",
"e",
"in",
"adb_cmd",
":",
"if",
"e",
"!=",
"''",
":",
"# avoid items with empty string...",
"final_adb_cmd",
".",
... | 32.24 | 0.001205 |
def assert_present(self, selector, testid=None, **kwargs):
"""Assert that the element is present in the dom
Args:
selector (str): the selector used to find the element
test_id (str): the test_id or a str
Kwargs:
wait_until_present (bool)
Returns:
... | [
"def",
"assert_present",
"(",
"self",
",",
"selector",
",",
"testid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"info_log",
"(",
"\"Assert present selector(%s) testid(%s)\"",
"%",
"(",
"selector",
",",
"testid",
")",
")",
"wait_until_present... | 29.55 | 0.001638 |
def handle_lut(self, pkt):
"""This part of the protocol is used by IRAF to set the frame number.
"""
self.logger.debug("handle lut")
if pkt.subunit & COMMAND:
data_type = str(pkt.nbytes / 2) + 'h'
#size = struct.calcsize(data_type)
line = pkt.datain.re... | [
"def",
"handle_lut",
"(",
"self",
",",
"pkt",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"handle lut\"",
")",
"if",
"pkt",
".",
"subunit",
"&",
"COMMAND",
":",
"data_type",
"=",
"str",
"(",
"pkt",
".",
"nbytes",
"/",
"2",
")",
"+",
"'h'"... | 33.428571 | 0.002372 |
def build_output_coords(
args: list,
signature: _UFuncSignature,
exclude_dims: AbstractSet = frozenset(),
) -> 'List[OrderedDict[Any, Variable]]':
"""Build output coordinates for an operation.
Parameters
----------
args : list
List of raw operation arguments. Any valid types for xar... | [
"def",
"build_output_coords",
"(",
"args",
":",
"list",
",",
"signature",
":",
"_UFuncSignature",
",",
"exclude_dims",
":",
"AbstractSet",
"=",
"frozenset",
"(",
")",
",",
")",
"->",
"'List[OrderedDict[Any, Variable]]'",
":",
"input_coords",
"=",
"_get_coord_variabl... | 33.93617 | 0.000609 |
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.uti... | [
"def",
"_sync",
"(",
"form",
",",
"saltenv",
"=",
"None",
",",
"extmod_whitelist",
"=",
"None",
",",
"extmod_blacklist",
"=",
"None",
")",
":",
"if",
"saltenv",
"is",
"None",
":",
"saltenv",
"=",
"_get_top_file_envs",
"(",
")",
"if",
"isinstance",
"(",
"... | 43.826087 | 0.001942 |
def asyncPipeStrregex(context=None, _INPUT=None, conf=None, **kwargs):
"""A string module that asynchronously replaces text using regexes. Each
has the general format: "In [field] replace [regex pattern] with [text]".
Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT :... | [
"def",
"asyncPipeStrregex",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"splits",
"=",
"yield",
"asyncGetSplits",
"(",
"_INPUT",
",",
"conf",
"[",
"'RULE'",
"]",
",",
"*",
"*",... | 39.074074 | 0.000925 |
def dist_abs(self, src, tar):
"""Return the MRA comparison rating of two strings.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
int
MRA comparison r... | [
"def",
"dist_abs",
"(",
"self",
",",
"src",
",",
"tar",
")",
":",
"if",
"src",
"==",
"tar",
":",
"return",
"6",
"if",
"src",
"==",
"''",
"or",
"tar",
"==",
"''",
":",
"return",
"0",
"src",
"=",
"list",
"(",
"mra",
"(",
"src",
")",
")",
"tar",... | 23.69697 | 0.001228 |
def get_name_locations(self, name):
"""Return a list of ``(resource, lineno)`` tuples"""
result = []
for module in self.names:
if name in self.names[module]:
try:
pymodule = self.project.get_module(module)
if name in pymodule:
... | [
"def",
"get_name_locations",
"(",
"self",
",",
"name",
")",
":",
"result",
"=",
"[",
"]",
"for",
"module",
"in",
"self",
".",
"names",
":",
"if",
"name",
"in",
"self",
".",
"names",
"[",
"module",
"]",
":",
"try",
":",
"pymodule",
"=",
"self",
".",... | 46.411765 | 0.002484 |
def processor(): # pragma: no cover
"""Churns over PostgreSQL notifications on configured channels.
This requires the application be setup and the registry be available.
This function uses the database connection string and a list of
pre configured channels.
"""
registry = get_current_registry... | [
"def",
"processor",
"(",
")",
":",
"# pragma: no cover",
"registry",
"=",
"get_current_registry",
"(",
")",
"settings",
"=",
"registry",
".",
"settings",
"connection_string",
"=",
"settings",
"[",
"CONNECTION_STRING",
"]",
"channels",
"=",
"_get_channels",
"(",
"s... | 41.232558 | 0.000551 |
def add_cpinfo_to_lclist(
checkplots, # list or a directory path
initial_lc_catalog,
magcol, # to indicate checkplot magcol
outfile,
checkplotglob='checkplot*.pkl*',
infokeys=CPINFO_DEFAULTKEYS,
nworkers=NCPUS
):
'''This adds checkplot info to the initial li... | [
"def",
"add_cpinfo_to_lclist",
"(",
"checkplots",
",",
"# list or a directory path",
"initial_lc_catalog",
",",
"magcol",
",",
"# to indicate checkplot magcol",
"outfile",
",",
"checkplotglob",
"=",
"'checkplot*.pkl*'",
",",
"infokeys",
"=",
"CPINFO_DEFAULTKEYS",
",",
"nwor... | 33.843602 | 0.00068 |
def guess_headers(self):
"""
Attempt to guess what headers may be required in order to use this
type. Returns `guess_headers` of all children recursively.
* If the typename is in the :const:`KNOWN_TYPES` dictionary, use the
header specified there
* If it's an STL typ... | [
"def",
"guess_headers",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"name",
".",
"replace",
"(",
"\"*\"",
",",
"\"\"",
")",
"headers",
"=",
"[",
"]",
"if",
"name",
"in",
"KNOWN_TYPES",
":",
"headers",
".",
"append",
"(",
"KNOWN_TYPES",
"[",
"nam... | 39.555556 | 0.001371 |
def _changes(name,
uid=None,
gid=None,
groups=None,
optional_groups=None,
remove_groups=True,
home=None,
createhome=True,
password=None,
enforce_password=True,
empty_password=False,
... | [
"def",
"_changes",
"(",
"name",
",",
"uid",
"=",
"None",
",",
"gid",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"optional_groups",
"=",
"None",
",",
"remove_groups",
"=",
"True",
",",
"home",
"=",
"None",
",",
"createhome",
"=",
"True",
",",
"pass... | 40.035714 | 0.000435 |
def parse(self, configManager, config):
"""
Parses commandline arguments, given a series of configuration options.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration optio... | [
"def",
"parse",
"(",
"self",
",",
"configManager",
",",
"config",
")",
":",
"argParser",
"=",
"self",
".",
"getArgumentParser",
"(",
"configManager",
",",
"config",
")",
"return",
"vars",
"(",
"argParser",
".",
"parse_args",
"(",
")",
")"
] | 45.25 | 0.009025 |
def compute_bleu(reference_corpus, translation_corpus, max_order=4,
use_bp=True):
"""Computes BLEU score of translated segments against one or more references.
Args:
reference_corpus: list of references for each translation. Each
reference should be tokenized into a list of tokens.
... | [
"def",
"compute_bleu",
"(",
"reference_corpus",
",",
"translation_corpus",
",",
"max_order",
"=",
"4",
",",
"use_bp",
"=",
"True",
")",
":",
"reference_length",
"=",
"0",
"translation_length",
"=",
"0",
"bp",
"=",
"1.0",
"geo_mean",
"=",
"0",
"matches_by_order... | 34.03125 | 0.01071 |
async def _handle_telegram_response(self, response, ignore=None):
"""
Parse a response from Telegram. If there's an error, an exception will
be raised with an explicative message.
:param response: Response to parse
:return: Data
"""
if ignore is None:
... | [
"async",
"def",
"_handle_telegram_response",
"(",
"self",
",",
"response",
",",
"ignore",
"=",
"None",
")",
":",
"if",
"ignore",
"is",
"None",
":",
"ignore",
"=",
"set",
"(",
")",
"ok",
"=",
"response",
".",
"status",
"==",
"200",
"try",
":",
"data",
... | 26.903226 | 0.002315 |
def left_stop(self):
"""allows left motor to coast to a stop"""
self.board.digital_write(L_CTRL_1, 0)
self.board.digital_write(L_CTRL_2, 0)
self.board.analog_write(PWM_L, 0) | [
"def",
"left_stop",
"(",
"self",
")",
":",
"self",
".",
"board",
".",
"digital_write",
"(",
"L_CTRL_1",
",",
"0",
")",
"self",
".",
"board",
".",
"digital_write",
"(",
"L_CTRL_2",
",",
"0",
")",
"self",
".",
"board",
".",
"analog_write",
"(",
"PWM_L",
... | 40.2 | 0.009756 |
def pop_all(self):
""" Preserve the context stack by transferring it to a new instance """
ret = ExitStack()
ret._context_stack.append(self._context_stack.pop())
self._context_stack.append([]) | [
"def",
"pop_all",
"(",
"self",
")",
":",
"ret",
"=",
"ExitStack",
"(",
")",
"ret",
".",
"_context_stack",
".",
"append",
"(",
"self",
".",
"_context_stack",
".",
"pop",
"(",
")",
")",
"self",
".",
"_context_stack",
".",
"append",
"(",
"[",
"]",
")"
] | 44 | 0.008929 |
def svmachine(self, data: ['SASdata', str] = None,
autotune: str = None,
code: str = None,
id: str = None,
input: [str, list, dict] = None,
kernel: str = None,
output: [str, bool, 'SASdata'] = None,
... | [
"def",
"svmachine",
"(",
"self",
",",
"data",
":",
"[",
"'SASdata'",
",",
"str",
"]",
"=",
"None",
",",
"autotune",
":",
"str",
"=",
"None",
",",
"code",
":",
"str",
"=",
"None",
",",
"id",
":",
"str",
"=",
"None",
",",
"input",
":",
"[",
"str"... | 58.657143 | 0.010062 |
def apply_payoff(self):
"""Apply the payoff that has been accumulated from immediate
reward and/or payments from successor match sets. Attempting to
call this method before an action has been selected or after it
has already been called for the same match set will result in a
Val... | [
"def",
"apply_payoff",
"(",
"self",
")",
":",
"if",
"self",
".",
"_selected_action",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"The action has not been selected yet.\"",
")",
"if",
"self",
".",
"_closed",
":",
"raise",
"ValueError",
"(",
"\"The payoff for t... | 36.916667 | 0.0022 |
def _show_list_message(resolved_config):
"""
Show the message for when a user has passed in --list.
"""
# Show what's available.
supported_programs = util.get_list_of_all_supported_commands(
resolved_config
)
msg_line_1 = 'Legend: '
msg_line_2 = (
' ' +
util.FL... | [
"def",
"_show_list_message",
"(",
"resolved_config",
")",
":",
"# Show what's available.",
"supported_programs",
"=",
"util",
".",
"get_list_of_all_supported_commands",
"(",
"resolved_config",
")",
"msg_line_1",
"=",
"'Legend: '",
"msg_line_2",
"=",
"(",
"' '",
"+",
... | 23.972222 | 0.001114 |
def compute_deterministic_entropy(self, F, K, x0):
r"""
Given K and F, compute the value of deterministic entropy, which
is
.. math::
\sum_t \beta^t x_t' K'K x_t`
with
.. math::
x_{t+1} = (A - BF + CK) x_t
Parameters
--------... | [
"def",
"compute_deterministic_entropy",
"(",
"self",
",",
"F",
",",
"K",
",",
"x0",
")",
":",
"H0",
"=",
"dot",
"(",
"K",
".",
"T",
",",
"K",
")",
"C0",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"n",
",",
"1",
")",
")",
"A0",
"=",
"se... | 22.648649 | 0.002288 |
def serialize(
self,
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> ET.Element
"""Serialize the value and returns it."""
xml_value = _hooks_apply_before_serialize(self._hooks, state, value)
return self._processor.serialize(x... | [
"def",
"serialize",
"(",
"self",
",",
"value",
",",
"# type: Any",
"state",
"# type: _ProcessorState",
")",
":",
"# type: (...) -> ET.Element",
"xml_value",
"=",
"_hooks_apply_before_serialize",
"(",
"self",
".",
"_hooks",
",",
"state",
",",
"value",
")",
"return",
... | 36.444444 | 0.011905 |
def sg_restore(sess, save_path, category=''):
r""" Restores previously saved variables.
Args:
sess: A `Session` to use to restore the parameters.
save_path: Path where parameters were previously saved.
category: A `String` to filter variables starts with given category.
Returns:
"""... | [
"def",
"sg_restore",
"(",
"sess",
",",
"save_path",
",",
"category",
"=",
"''",
")",
":",
"# to list",
"if",
"not",
"isinstance",
"(",
"category",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"category",
"=",
"[",
"category",
"]",
"# make variable list... | 27.36 | 0.001412 |
def write_entry_to_file(file_descriptor, entry_comment, entry_key):
""" Writes a localization entry to the file
Args:
file_descriptor (file, instance): The file to write the entry to.
entry_comment (str): The entry's comment.
entry_key (str): The entry's key.
"""
escaped_key = r... | [
"def",
"write_entry_to_file",
"(",
"file_descriptor",
",",
"entry_comment",
",",
"entry_key",
")",
":",
"escaped_key",
"=",
"re",
".",
"sub",
"(",
"r'([^\\\\])\"'",
",",
"'\\\\1\\\\\"'",
",",
"entry_key",
")",
"file_descriptor",
".",
"write",
"(",
"u'/* %s */\\n'"... | 43.636364 | 0.002041 |
def to_json(el, schema=None):
"""Convert an element to VDOM JSON
If you wish to validate the JSON, pass in a schema via the schema keyword
argument. If a schema is provided, this raises a ValidationError if JSON
does not match the schema.
"""
if type(el) is str:
json_el = el
elif ty... | [
"def",
"to_json",
"(",
"el",
",",
"schema",
"=",
"None",
")",
":",
"if",
"type",
"(",
"el",
")",
"is",
"str",
":",
"json_el",
"=",
"el",
"elif",
"type",
"(",
"el",
")",
"is",
"list",
":",
"json_el",
"=",
"list",
"(",
"map",
"(",
"to_json",
",",... | 30.233333 | 0.001068 |
def _walk_to_root(path, break_at=None):
"""
Directories starting from the given directory up to the root or break_at
"""
if not os.path.exists(path): # pragma: no cover
raise IOError("Starting path not found")
if os.path.isfile(path): # pragma: no cover
path = os.path.dirname(path... | [
"def",
"_walk_to_root",
"(",
"path",
",",
"break_at",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"# pragma: no cover",
"raise",
"IOError",
"(",
"\"Starting path not found\"",
")",
"if",
"os",
".",
"path",
... | 37.363636 | 0.001186 |
def _safe_output(line):
'''
Looks for rabbitmqctl warning, or general formatting, strings that aren't
intended to be parsed as output.
Returns a boolean whether the line can be parsed as rabbitmqctl output.
'''
return not any([
line.startswith('Listing') and line.endswith('...'),
... | [
"def",
"_safe_output",
"(",
"line",
")",
":",
"return",
"not",
"any",
"(",
"[",
"line",
".",
"startswith",
"(",
"'Listing'",
")",
"and",
"line",
".",
"endswith",
"(",
"'...'",
")",
",",
"line",
".",
"startswith",
"(",
"'Listing'",
")",
"and",
"'\\t'",
... | 35.666667 | 0.002278 |
def _read_all_z_variable_info(self):
"""Gets all CDF z-variable information, not data though.
Maps to calls using var_inquire. Gets information on
data type, number of elements, number of dimensions, etc.
"""
self.z_variable_info = {}
self.z_variable_names_by_num = {}
... | [
"def",
"_read_all_z_variable_info",
"(",
"self",
")",
":",
"self",
".",
"z_variable_info",
"=",
"{",
"}",
"self",
".",
"z_variable_names_by_num",
"=",
"{",
"}",
"# call Fortran that grabs all of the basic stats on all of the",
"# zVariables in one go.",
"info",
"=",
"fort... | 37.934783 | 0.001117 |
def setParameter(self, parameterName, index, parameterValue):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.setParameter`.
Set the value of a Spec parameter. Most parameters are handled
automatically by PyRegion's parameter set mechanism. The ones that need
special treatment are ex... | [
"def",
"setParameter",
"(",
"self",
",",
"parameterName",
",",
"index",
",",
"parameterValue",
")",
":",
"if",
"parameterName",
"in",
"self",
".",
"_spatialArgNames",
":",
"setattr",
"(",
"self",
".",
"_sfdr",
",",
"parameterName",
",",
"parameterValue",
")",
... | 33.913043 | 0.011838 |
def isUrl(urlString):
"""
Attempts to return whether a given URL string is valid by checking
for the presence of the URL scheme and netloc using the urlparse
module, and then using a regex.
From http://stackoverflow.com/questions/7160737/
"""
parsed = urlparse.urlparse(urlString)
urlpar... | [
"def",
"isUrl",
"(",
"urlString",
")",
":",
"parsed",
"=",
"urlparse",
".",
"urlparse",
"(",
"urlString",
")",
"urlparseValid",
"=",
"parsed",
".",
"netloc",
"!=",
"''",
"and",
"parsed",
".",
"scheme",
"!=",
"''",
"regex",
"=",
"re",
".",
"compile",
"(... | 39 | 0.001252 |
def update(self, deltat=1.0):
'''straight lines, with short life'''
DNFZ.update(self, deltat)
self.lifetime -= deltat
if self.lifetime <= 0:
self.randpos()
self.lifetime = random.uniform(300,600) | [
"def",
"update",
"(",
"self",
",",
"deltat",
"=",
"1.0",
")",
":",
"DNFZ",
".",
"update",
"(",
"self",
",",
"deltat",
")",
"self",
".",
"lifetime",
"-=",
"deltat",
"if",
"self",
".",
"lifetime",
"<=",
"0",
":",
"self",
".",
"randpos",
"(",
")",
"... | 35 | 0.011952 |
def flaskify(response, headers=None, encoder=None):
"""Format the response to be consumeable by flask.
The api returns mostly JSON responses. The format method converts the dicts
into a json object (as a string), and the right response is returned (with
the valid mimetype, charset and status.)
Arg... | [
"def",
"flaskify",
"(",
"response",
",",
"headers",
"=",
"None",
",",
"encoder",
"=",
"None",
")",
":",
"status_code",
"=",
"response",
".",
"status",
"data",
"=",
"response",
".",
"errors",
"or",
"response",
".",
"message",
"mimetype",
"=",
"'text/plain'"... | 37.172414 | 0.000904 |
def parse_acl(acl_string):
""" Parse raw string :acl_string: of RAML-defined ACLs.
If :acl_string: is blank or None, all permissions are given.
Values of ACL action and principal are parsed using `actions` and
`special_principals` maps and are looked up after `strip()` and
`lower()`.
ACEs in :... | [
"def",
"parse_acl",
"(",
"acl_string",
")",
":",
"if",
"not",
"acl_string",
":",
"return",
"[",
"ALLOW_ALL",
"]",
"aces_list",
"=",
"acl_string",
".",
"replace",
"(",
"'\\n'",
",",
"';'",
")",
".",
"split",
"(",
"';'",
")",
"aces_list",
"=",
"[",
"ace"... | 35.765957 | 0.000579 |
def create_adjacency_matrix(self, weights=None, fmt='coo', triu=False,
drop_zeros=False):
r"""
Generates a weighted adjacency matrix in the desired sparse format
Parameters
----------
weights : array_like, optional
An array containing ... | [
"def",
"create_adjacency_matrix",
"(",
"self",
",",
"weights",
"=",
"None",
",",
"fmt",
"=",
"'coo'",
",",
"triu",
"=",
"False",
",",
"drop_zeros",
"=",
"False",
")",
":",
"# Check if provided data is valid",
"if",
"weights",
"is",
"None",
":",
"weights",
"=... | 38.708738 | 0.000734 |
def py(sfn, string=False, **kwargs): # pylint: disable=C0103
'''
Render a template from a python source file
Returns::
{'result': bool,
'data': <Error data or rendered file path>}
'''
if not os.path.isfile(sfn):
return {}
base_fname = os.path.basename(sfn)
name =... | [
"def",
"py",
"(",
"sfn",
",",
"string",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C0103",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"sfn",
")",
":",
"return",
"{",
"}",
"base_fname",
"=",
"os",
".",
"path",
".",
... | 30.792453 | 0.000594 |
def build_accumulate(function: Callable[[Any, Any], Tuple[Any, Any]] = None, *,
init: Any = NONE):
""" Decorator to wrap a function to return an Accumulate operator.
:param function: function to be wrapped
:param init: optional initialization for state
"""
_init = init
def... | [
"def",
"build_accumulate",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
",",
"Any",
"]",
",",
"Tuple",
"[",
"Any",
",",
"Any",
"]",
"]",
"=",
"None",
",",
"*",
",",
"init",
":",
"Any",
"=",
"NONE",
")",
":",
"_init",
"=",
"init",
"def",
"... | 34.272727 | 0.00129 |
def _apply_volcanic_front_correction(mean, x_vf, H, imt):
"""
Implement equation for volcanic front correction as described in equation
3.5.2.-2, page 3-149 of "Technical Reports on National Seismic
Hazard Maps for Japan"
"""
V1 = np.zeros_like(x_vf)
if imt.name == 'PGV':
idx = x_vf ... | [
"def",
"_apply_volcanic_front_correction",
"(",
"mean",
",",
"x_vf",
",",
"H",
",",
"imt",
")",
":",
"V1",
"=",
"np",
".",
"zeros_like",
"(",
"x_vf",
")",
"if",
"imt",
".",
"name",
"==",
"'PGV'",
":",
"idx",
"=",
"x_vf",
"<=",
"75",
"V1",
"[",
"idx... | 32.1 | 0.001513 |
def _get_response(self, timeout=1.0, eor=('\n', '\n- ')):
""" Reads a response from the drive.
Reads the response returned by the drive with an optional
timeout. All carriage returns and linefeeds are kept.
Parameters
----------
timeout : number, optional
Op... | [
"def",
"_get_response",
"(",
"self",
",",
"timeout",
"=",
"1.0",
",",
"eor",
"=",
"(",
"'\\n'",
",",
"'\\n- '",
")",
")",
":",
"# If no timeout is given or it is invalid and we are using '\\n'",
"# as the eor, use the wrapper to read a line with an infinite",
"# timeout. Othe... | 45.383721 | 0.000752 |
def video_pixel_noise_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for video."""
input_noise = getattr(model_hparams, "video_modality_input_noise", 0.25)
inputs = x
if model_hparams.mode == tf.estimator.ModeKeys.TRAIN:
background = tfp.stats.percentile(inputs, 50., axis=[0, 1, 2, 3])
i... | [
"def",
"video_pixel_noise_bottom",
"(",
"x",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"input_noise",
"=",
"getattr",
"(",
"model_hparams",
",",
"\"video_modality_input_noise\"",
",",
"0.25",
")",
"inputs",
"=",
"x",
"if",
"model_hparams",
".",
"mode",
... | 51.928571 | 0.008108 |
def create_workshift_profile(sender, instance, created, **kwargs):
'''
Function to add a workshift profile for every User that is created.
Parameters:
instance is an of UserProfile that was just saved.
'''
if instance.user.username == ANONYMOUS_USERNAME or \
instance.status != UserPro... | [
"def",
"create_workshift_profile",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"instance",
".",
"user",
".",
"username",
"==",
"ANONYMOUS_USERNAME",
"or",
"instance",
".",
"status",
"!=",
"UserProfile",
".",
"RESI... | 32.208333 | 0.001256 |
def getsource(obj):
"""Wrapper around inspect.getsource"""
try:
try:
src = to_text_string(inspect.getsource(obj))
except TypeError:
if hasattr(obj, '__class__'):
src = to_text_string(inspect.getsource(obj.__class__))
else:
# Bin... | [
"def",
"getsource",
"(",
"obj",
")",
":",
"try",
":",
"try",
":",
"src",
"=",
"to_text_string",
"(",
"inspect",
".",
"getsource",
"(",
"obj",
")",
")",
"except",
"TypeError",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'__class__'",
")",
":",
"src",
"=",... | 31.928571 | 0.002174 |
def drawPhasePlot(abf,m1=0,m2=None):
"""
Given an ABF object (SWHLab), draw its phase plot of the current sweep.
m1 and m2 are optional marks (in seconds) for plotting only a range of data.
Assume a matplotlib figure is already open and just draw on top if it.
"""
if not m2:
m2 = abf.sw... | [
"def",
"drawPhasePlot",
"(",
"abf",
",",
"m1",
"=",
"0",
",",
"m2",
"=",
"None",
")",
":",
"if",
"not",
"m2",
":",
"m2",
"=",
"abf",
".",
"sweepLength",
"cm",
"=",
"plt",
".",
"get_cmap",
"(",
"'CMRmap'",
")",
"#cm = plt.get_cmap('CMRmap_r')",
"#cm = p... | 28.25 | 0.014474 |
def mutates(f):
'''Decorator for functions that mutate :class:`StringCounter`.
This raises :exc:`~dossier.fc.exceptions.ReadOnlyException` if
the object is read-only, and increments the generation counter
otherwise.
'''
@wraps(f)
def wrapper(self, *args, **kwargs):
if self.read_only... | [
"def",
"mutates",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"read_only",
":",
"raise",
"ReadOnlyException",
"(",
")",
"self",
".",
"next... | 31.142857 | 0.002227 |
def train_eval():
""" train and eval the model
"""
global trainloader
global testloader
global net
(x_train, y_train) = trainloader
(x_test, y_test) = testloader
# train procedure
net.fit(
x=x_train,
y=y_train,
batch_size=args.batch_size,
validation... | [
"def",
"train_eval",
"(",
")",
":",
"global",
"trainloader",
"global",
"testloader",
"global",
"net",
"(",
"x_train",
",",
"y_train",
")",
"=",
"trainloader",
"(",
"x_test",
",",
"y_test",
")",
"=",
"testloader",
"# train procedure",
"net",
".",
"fit",
"(",
... | 23.2 | 0.001379 |
def save_weights(caffe_def_path, caffemodel_path, inputs, output_path, graph_name='Graph', conv_var_names=None,
conv_transpose_var_names=None, use_padding_same=False):
"""Save the weights of the trainable variables, each one in a different file in output_path."""
with caffe_to_tensorflow_sessio... | [
"def",
"save_weights",
"(",
"caffe_def_path",
",",
"caffemodel_path",
",",
"inputs",
",",
"output_path",
",",
"graph_name",
"=",
"'Graph'",
",",
"conv_var_names",
"=",
"None",
",",
"conv_transpose_var_names",
"=",
"None",
",",
"use_padding_same",
"=",
"False",
")"... | 89 | 0.011129 |
def pack(ctx, remove_lib=True):
"""Build a isolated runnable package.
"""
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
with ROOT.joinpath('Pipfile.lock').open() as f:
lockfile = plette.Lockfile.load(f)
libdir = OUTPUT_DIR.joinpath('lib')
paths = {'purelib': libdir, 'platlib': libdir}
... | [
"def",
"pack",
"(",
"ctx",
",",
"remove_lib",
"=",
"True",
")",
":",
"OUTPUT_DIR",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"with",
"ROOT",
".",
"joinpath",
"(",
"'Pipfile.lock'",
")",
".",
"open",
"(",
")",
"as",... | 36.365854 | 0.000653 |
def to_json(self):
""" Writes the complete Morse complex merge hierarchy to a
string object.
@ Out, a string object storing the entire merge hierarchy of
all maxima.
"""
capsule = {}
capsule["Hierarchy"] = []
for (
dying,
... | [
"def",
"to_json",
"(",
"self",
")",
":",
"capsule",
"=",
"{",
"}",
"capsule",
"[",
"\"Hierarchy\"",
"]",
"=",
"[",
"]",
"for",
"(",
"dying",
",",
"(",
"persistence",
",",
"surviving",
",",
"saddle",
")",
",",
")",
"in",
"self",
".",
"merge_sequence",... | 33.481481 | 0.002151 |
def setuptools_install_options(local_storage_folder):
"""
Return options to make setuptools use installations from the given folder.
No other installation source is allowed.
"""
if local_storage_folder is None:
return []
# setuptools expects its find-links parameter to contain... | [
"def",
"setuptools_install_options",
"(",
"local_storage_folder",
")",
":",
"if",
"local_storage_folder",
"is",
"None",
":",
"return",
"[",
"]",
"# setuptools expects its find-links parameter to contain a list of link\r",
"# sources (either local paths, file: URLs pointing to folders o... | 51.207547 | 0.000362 |
def cleanup(self, pin=None):
"""Clean up GPIO event detection for specific pin, or all pins if none
is specified.
"""
if pin is None:
self.bbio_gpio.cleanup()
else:
self.bbio_gpio.cleanup(pin) | [
"def",
"cleanup",
"(",
"self",
",",
"pin",
"=",
"None",
")",
":",
"if",
"pin",
"is",
"None",
":",
"self",
".",
"bbio_gpio",
".",
"cleanup",
"(",
")",
"else",
":",
"self",
".",
"bbio_gpio",
".",
"cleanup",
"(",
"pin",
")"
] | 31.25 | 0.011673 |
def create_hls_stream(self, localStreamNames, targetFolder, **kwargs):
"""
Create an HTTP Live Stream (HLS) out of an existing H.264/AAC stream.
HLS is used to stream live feeds to iOS devices such as iPhones and
iPads.
:param localStreamNames: The stream(s) that will be used as... | [
"def",
"create_hls_stream",
"(",
"self",
",",
"localStreamNames",
",",
"targetFolder",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"protocol",
".",
"execute",
"(",
"'createhlsstream'",
",",
"localStreamNames",
"=",
"localStreamNames",
",",
"targetF... | 42.47619 | 0.000365 |
def GetRequestXML(self, method, *args):
"""Get the raw SOAP XML for a request.
Args:
method: The method name.
*args: A list of arguments to be passed to the method.
Returns:
An element containing the raw XML that would be sent as the request.
"""
packed_args = self._PackArguments... | [
"def",
"GetRequestXML",
"(",
"self",
",",
"method",
",",
"*",
"args",
")",
":",
"packed_args",
"=",
"self",
".",
"_PackArguments",
"(",
"method",
",",
"args",
",",
"set_type_attrs",
"=",
"True",
")",
"headers",
"=",
"self",
".",
"_GetZeepFormattedSOAPHeaders... | 34.266667 | 0.001894 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.