text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def count_nonzero(data, mapper=None, blen=None, storage=None,
create='array', **kwargs):
"""Count the number of non-zero elements."""
return reduce_axis(data, reducer=np.count_nonzero,
block_reducer=np.add, mapper=mapper,
blen=blen, storage=storage... | [
"def",
"count_nonzero",
"(",
"data",
",",
"mapper",
"=",
"None",
",",
"blen",
"=",
"None",
",",
"storage",
"=",
"None",
",",
"create",
"=",
"'array'",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"reduce_axis",
"(",
"data",
",",
"reducer",
"=",
"np",... | 56.833333 | 15.5 |
def _remove_strings(code) :
""" Remove strings in code
"""
removed_string = ""
is_string_now = None
for i in range(0, len(code)-1) :
append_this_turn = False
if code[i] == "'" and (i == 0 or code[i-1] != '\\') :
if is_string_now == "'" :
is_string_now = None
elif is_string_now == None ... | [
"def",
"_remove_strings",
"(",
"code",
")",
":",
"removed_string",
"=",
"\"\"",
"is_string_now",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"code",
")",
"-",
"1",
")",
":",
"append_this_turn",
"=",
"False",
"if",
"code",
"[",
... | 22.166667 | 19.666667 |
def best_fit_likelihood(self):
"""
returns the log likelihood of the best fit model of the current state of this class
:return: log likelihood, float
"""
kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, kwargs_cosmo = self.best_fit(bijective=False)
param_class =... | [
"def",
"best_fit_likelihood",
"(",
"self",
")",
":",
"kwargs_lens",
",",
"kwargs_source",
",",
"kwargs_lens_light",
",",
"kwargs_ps",
",",
"kwargs_cosmo",
"=",
"self",
".",
"best_fit",
"(",
"bijective",
"=",
"False",
")",
"param_class",
"=",
"self",
".",
"_par... | 49.5 | 26.666667 |
def send_message(self, message, mention_id=None, mentions=[]):
"""
Send the specified message to twitter, with appropriate mentions, tokenized as necessary
:param message: Message to be sent
:param mention_id: In-reply-to mention_id (to link messages to a previous message)
:param... | [
"def",
"send_message",
"(",
"self",
",",
"message",
",",
"mention_id",
"=",
"None",
",",
"mentions",
"=",
"[",
"]",
")",
":",
"messages",
"=",
"self",
".",
"tokenize",
"(",
"message",
",",
"self",
".",
"MESSAGE_LENGTH",
",",
"mentions",
")",
"code",
"=... | 50.44 | 24.44 |
def dropAllCollections(self):
"""drops all public collections (graphs included) from the database"""
for graph_name in self.graphs:
self.graphs[graph_name].delete()
for collection_name in self.collections:
# Collections whose name starts with '_' are system collections
... | [
"def",
"dropAllCollections",
"(",
"self",
")",
":",
"for",
"graph_name",
"in",
"self",
".",
"graphs",
":",
"self",
".",
"graphs",
"[",
"graph_name",
"]",
".",
"delete",
"(",
")",
"for",
"collection_name",
"in",
"self",
".",
"collections",
":",
"# Collectio... | 47 | 11.444444 |
def _register_engine(self, uid):
"""New engine with ident `uid` became available."""
# head of the line:
self.targets.insert(0,uid)
self.loads.insert(0,0)
# initialize sets
self.completed[uid] = set()
self.failed[uid] = set()
self.pending[uid] = {}
... | [
"def",
"_register_engine",
"(",
"self",
",",
"uid",
")",
":",
"# head of the line:",
"self",
".",
"targets",
".",
"insert",
"(",
"0",
",",
"uid",
")",
"self",
".",
"loads",
".",
"insert",
"(",
"0",
",",
"0",
")",
"# initialize sets",
"self",
".",
"comp... | 27.846154 | 13.615385 |
def get_parent_obj(obj):
""" Gets the name of the object containing @obj and returns as a string
@obj: any python object
-> #str parent object name or None
..
from redis_structures.debug import get_parent_obj
get_parent_obj(get_parent_obj)
# -> <module ... | [
"def",
"get_parent_obj",
"(",
"obj",
")",
":",
"try",
":",
"cls",
"=",
"get_class_that_defined_method",
"(",
"obj",
")",
"if",
"cls",
"and",
"cls",
"!=",
"obj",
":",
"return",
"cls",
"except",
"AttributeError",
":",
"pass",
"if",
"hasattr",
"(",
"obj",
"... | 30.931818 | 18.068182 |
def unpack(cls, msg):
"""Construct an _OpReply from raw bytes."""
# PYTHON-945: ignore starting_from field.
flags, cursor_id, _, number_returned = cls.UNPACK_FROM(msg)
# Convert Python 3 memoryview to bytes. Note we should call
# memoryview.tobytes() if we start using memoryview... | [
"def",
"unpack",
"(",
"cls",
",",
"msg",
")",
":",
"# PYTHON-945: ignore starting_from field.",
"flags",
",",
"cursor_id",
",",
"_",
",",
"number_returned",
"=",
"cls",
".",
"UNPACK_FROM",
"(",
"msg",
")",
"# Convert Python 3 memoryview to bytes. Note we should call",
... | 47.555556 | 20.555556 |
def get_logger(name, file_name=None, stream=None, template=None, propagate=False, level=None):
"""Get a logger by name.
"""
logger = logging.getLogger(name)
running_tests = (
'test' in sys.argv # running with setup.py
or sys.argv[0].endswith('py.test')) # running with py.test
if ... | [
"def",
"get_logger",
"(",
"name",
",",
"file_name",
"=",
"None",
",",
"stream",
"=",
"None",
",",
"template",
"=",
"None",
",",
"propagate",
"=",
"False",
",",
"level",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
"... | 28.764706 | 21.323529 |
async def listArtifacts(self, *args, **kwargs):
"""
Get Artifacts from Run
Returns a list of artifacts and associated meta-data for a given run.
As a task may have many artifacts paging may be necessary. If this
end-point returns a `continuationToken`, you should call the end-p... | [
"async",
"def",
"listArtifacts",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"listArtifacts\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
... | 38.5 | 27.7 |
def next_question(self):
"""Returns the next `Question` in the questionnaire, or `None` if there
are no questions left. Returns first question for whose key there is no
answer and for which condition is satisfied, or for which there is no
condition.
"""
for key, questions... | [
"def",
"next_question",
"(",
"self",
")",
":",
"for",
"key",
",",
"questions",
"in",
"self",
".",
"questions",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"self",
".",
"answers",
":",
"continue",
"for",
"question",
"in",
"questions",
":",
"if",
"... | 42.538462 | 15.153846 |
def open_file_from_iso(self, **kwargs):
# type: (str) -> PyCdlibIO
'''
Open a file for reading in a context manager. This allows the user to
operate on the file in user-defined chunks (utilizing the read() method
of the returned context manager).
Parameters:
is... | [
"def",
"open_file_from_iso",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (str) -> PyCdlibIO",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInvalidInput",
"(",
"'This object is not yet initialized; call either open()... | 49.471698 | 30.641509 |
def disconnect_sync(self, conn_id):
"""Synchronously disconnect from a connected device
Args:
conn_id (int): A unique identifier that will refer to this connection
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the con... | [
"def",
"disconnect_sync",
"(",
"self",
",",
"conn_id",
")",
":",
"done",
"=",
"threading",
".",
"Event",
"(",
")",
"result",
"=",
"{",
"}",
"def",
"disconnect_done",
"(",
"conn_id",
",",
"adapter_id",
",",
"status",
",",
"reason",
")",
":",
"result",
"... | 30.875 | 23.375 |
def parametric_function(fx='sin(t)', fy='cos(t)', tmin=-1, tmax=1, steps=200, p='t', g=None, erange=False, **kwargs):
"""
Plots the parametric function over the specified range
Parameters
----------
fx='sin(t)', fy='cos(t)'
Functions or (matching) lists of functions to plot;
... | [
"def",
"parametric_function",
"(",
"fx",
"=",
"'sin(t)'",
",",
"fy",
"=",
"'cos(t)'",
",",
"tmin",
"=",
"-",
"1",
",",
"tmax",
"=",
"1",
",",
"steps",
"=",
"200",
",",
"p",
"=",
"'t'",
",",
"g",
"=",
"None",
",",
"erange",
"=",
"False",
",",
"*... | 27.791045 | 21.761194 |
def before_sample(analysis_request):
"""Method triggered before "sample" transition for the Analysis Request
passed in is performed
"""
if not analysis_request.getDateSampled():
analysis_request.setDateSampled(DateTime())
if not analysis_request.getSampler():
analysis_request.setSamp... | [
"def",
"before_sample",
"(",
"analysis_request",
")",
":",
"if",
"not",
"analysis_request",
".",
"getDateSampled",
"(",
")",
":",
"analysis_request",
".",
"setDateSampled",
"(",
"DateTime",
"(",
")",
")",
"if",
"not",
"analysis_request",
".",
"getSampler",
"(",
... | 42.875 | 7.125 |
def get_record(self):
"""Override the base get_record."""
self.update_system_numbers()
self.add_systemnumber("CDS")
self.fields_list = [
"024", "041", "035", "037", "088", "100",
"110", "111", "242", "245", "246", "260",
"269", "300", "502", "650", "65... | [
"def",
"get_record",
"(",
"self",
")",
":",
"self",
".",
"update_system_numbers",
"(",
")",
"self",
".",
"add_systemnumber",
"(",
"\"CDS\"",
")",
"self",
".",
"fields_list",
"=",
"[",
"\"024\"",
",",
"\"041\"",
",",
"\"035\"",
",",
"\"037\"",
",",
"\"088\"... | 33.325 | 13.05 |
def status(self):
"""Get the status of the daemon."""
if self.pidfile is None:
raise DaemonError('Cannot get status of daemon without PID file')
pid = self._read_pidfile()
if pid is None:
self._emit_message(
'{prog} -- not running\n'.format(prog=s... | [
"def",
"status",
"(",
"self",
")",
":",
"if",
"self",
".",
"pidfile",
"is",
"None",
":",
"raise",
"DaemonError",
"(",
"'Cannot get status of daemon without PID file'",
")",
"pid",
"=",
"self",
".",
"_read_pidfile",
"(",
")",
"if",
"pid",
"is",
"None",
":",
... | 37.18 | 19.96 |
def _occursOn(self, myDate):
"""
Returns true iff an occurence of this event starts on this date
(given in the event's own timezone).
(Does not include postponements, but does exclude cancellations.)
"""
# TODO analyse which is faster (rrule or db) and test that first
... | [
"def",
"_occursOn",
"(",
"self",
",",
"myDate",
")",
":",
"# TODO analyse which is faster (rrule or db) and test that first",
"if",
"myDate",
"not",
"in",
"self",
".",
"repeat",
":",
"return",
"False",
"if",
"CancellationPage",
".",
"events",
".",
"child_of",
"(",
... | 39.714286 | 19.285714 |
def _do_write(fname, variable, version, date, table):
"""Write combining tables to filesystem as python code."""
# pylint: disable=R0914
# Too many local variables (19/15) (col 4)
print("writing {} ..".format(fname))
import unicodedata
import datetime
impo... | [
"def",
"_do_write",
"(",
"fname",
",",
"variable",
",",
"version",
",",
"date",
",",
"table",
")",
":",
"# pylint: disable=R0914",
"# Too many local variables (19/15) (col 4)",
"print",
"(",
"\"writing {} ..\"",
".",
"format",
"(",
"fname",
")",
")",
"import... | 45.45 | 13.825 |
def set_result(self, result):
"""Complete all tasks. """
for future in self.traverse():
# All cancelled futures should have callbacks to removed itself
# from this linked list. However, these callbacks are scheduled in
# an event loop, so we could still find them in o... | [
"def",
"set_result",
"(",
"self",
",",
"result",
")",
":",
"for",
"future",
"in",
"self",
".",
"traverse",
"(",
")",
":",
"# All cancelled futures should have callbacks to removed itself",
"# from this linked list. However, these callbacks are scheduled in",
"# an event loop, s... | 47.222222 | 14.777778 |
def factory(self, classname, *args, **kwargs):
"""
Creates an instance of class looking for it in each module registered. You can
add needed params to instance the class.
:param classname: Class name you want to create an instance.
:type classname: str
:return: An instan... | [
"def",
"factory",
"(",
"self",
",",
"classname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"klass",
"=",
"self",
".",
"load_class",
"(",
"classname",
")",
"return",
"self",
".",
"get_factory_by_class",
"(",
"klass",
")",
"(",
"*",
"args",
... | 33.357143 | 18.928571 |
def udot(op1, op2):
"""Matrix or vector dot product that preserves units
This is a wrapper around np.dot that preserves units.
Examples
--------
>>> from unyt import km, s
>>> a = np.eye(2)*km
>>> b = (np.ones((2, 2)) * 2)*s
>>> print(udot(a, b))
[[2. 2.]
[2. 2.]] km*s
"""... | [
"def",
"udot",
"(",
"op1",
",",
"op2",
")",
":",
"dot",
"=",
"np",
".",
"dot",
"(",
"op1",
".",
"d",
",",
"op2",
".",
"d",
")",
"units",
"=",
"op1",
".",
"units",
"*",
"op2",
".",
"units",
"if",
"dot",
".",
"shape",
"==",
"(",
")",
":",
"... | 24.526316 | 16.368421 |
async def _send_report(self, status):
"""
Call all subscribed coroutines in _notify whenever a status
update occurs.
This method is a coroutine
"""
if len(self._notify) > 0:
# Each client gets its own copy of the dict.
asyncio.gather(*[coro(dict(s... | [
"async",
"def",
"_send_report",
"(",
"self",
",",
"status",
")",
":",
"if",
"len",
"(",
"self",
".",
"_notify",
")",
">",
"0",
":",
"# Each client gets its own copy of the dict.",
"asyncio",
".",
"gather",
"(",
"*",
"[",
"coro",
"(",
"dict",
"(",
"status",... | 35.181818 | 13.909091 |
def neutralize_variables(self, tax_benefit_system):
"""
Neutralizing input variables not in input dataframe and keep some crucial variables
"""
for variable_name, variable in tax_benefit_system.variables.items():
if variable.formulas:
continue
if s... | [
"def",
"neutralize_variables",
"(",
"self",
",",
"tax_benefit_system",
")",
":",
"for",
"variable_name",
",",
"variable",
"in",
"tax_benefit_system",
".",
"variables",
".",
"items",
"(",
")",
":",
"if",
"variable",
".",
"formulas",
":",
"continue",
"if",
"self... | 49.933333 | 28.6 |
def collect_analysis(self):
'''
:return: a dictionary which is used to get the serialized analyzer definition from the analyzer class.
'''
analysis = {}
for field in self.fields.values():
for analyzer_name in ('analyzer', 'index_analyzer', 'search_analyzer'):
... | [
"def",
"collect_analysis",
"(",
"self",
")",
":",
"analysis",
"=",
"{",
"}",
"for",
"field",
"in",
"self",
".",
"fields",
".",
"values",
"(",
")",
":",
"for",
"analyzer_name",
"in",
"(",
"'analyzer'",
",",
"'index_analyzer'",
",",
"'search_analyzer'",
")",... | 34.173913 | 24.347826 |
def padded_cross_entropy(logits,
labels,
label_smoothing,
weights_fn=weights_nonzero,
reduce_sum=True,
cutoff=0.0,
gaussian=False):
"""Compute cross-entropy assuming 0s... | [
"def",
"padded_cross_entropy",
"(",
"logits",
",",
"labels",
",",
"label_smoothing",
",",
"weights_fn",
"=",
"weights_nonzero",
",",
"reduce_sum",
"=",
"True",
",",
"cutoff",
"=",
"0.0",
",",
"gaussian",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"logi... | 38.380952 | 16.253968 |
def retrieve_assignment_overridden_dates_for_quizzes(self, course_id, quiz_assignment_overrides_0_quiz_ids=None):
"""
Retrieve assignment-overridden dates for quizzes.
Retrieve the actual due-at, unlock-at, and available-at dates for quizzes
based on the assignment overrides active... | [
"def",
"retrieve_assignment_overridden_dates_for_quizzes",
"(",
"self",
",",
"course_id",
",",
"quiz_assignment_overrides_0_quiz_ids",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
"\... | 52.217391 | 32.869565 |
def fit(self, X, y=None, **fit_params):
"""Fits the inverse covariance model according to the given training
data and parameters.
Parameters
-----------
X : 2D ndarray, shape (n_features, n_features)
Input data.
Returns
-------
self
"... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"fit_params",
")",
":",
"# quic-specific outputs",
"self",
".",
"opt_",
"=",
"None",
"self",
".",
"cputime_",
"=",
"None",
"self",
".",
"iters_",
"=",
"None",
"self",
".",
"... | 33.188406 | 18.043478 |
def _cached_results(self, start_time, end_time):
"""
Retrieves cached results for any bucket that has a single cache entry.
If a bucket has two cache entries, there is a chance that two
different writers previously computed and cached a result since
Kronos has no transaction semantics. While it mi... | [
"def",
"_cached_results",
"(",
"self",
",",
"start_time",
",",
"end_time",
")",
":",
"cached_buckets",
"=",
"self",
".",
"_bucket_events",
"(",
"self",
".",
"_client",
".",
"get",
"(",
"self",
".",
"_scratch_stream",
",",
"start_time",
",",
"end_time",
",",
... | 48 | 16.285714 |
def jsontype(self, name, path=Path.rootPath()):
"""
Gets the type of the JSON value under ``path`` from key ``name``
"""
return self.execute_command('JSON.TYPE', name, str_path(path)) | [
"def",
"jsontype",
"(",
"self",
",",
"name",
",",
"path",
"=",
"Path",
".",
"rootPath",
"(",
")",
")",
":",
"return",
"self",
".",
"execute_command",
"(",
"'JSON.TYPE'",
",",
"name",
",",
"str_path",
"(",
"path",
")",
")"
] | 42.2 | 13.8 |
def tmpl_first(text, count=1, skip=0, sep=u'; ', join_str=u'; '):
"""
* synopsis: ``%first{text}`` or ``%first{text,count,skip}`` or \
``%first{text,count,skip,sep,join}``
* description: Returns the first item, separated by ; . You can use \
%first{text,count,skip}, where... | [
"def",
"tmpl_first",
"(",
"text",
",",
"count",
"=",
"1",
",",
"skip",
"=",
"0",
",",
"sep",
"=",
"u'; '",
",",
"join_str",
"=",
"u'; '",
")",
":",
"skip",
"=",
"int",
"(",
"skip",
")",
"count",
"=",
"skip",
"+",
"int",
"(",
"count",
")",
"retu... | 51.052632 | 21.684211 |
def get_object(cls, api_token, domain_name):
"""
Class method that will return a Domain object by ID.
"""
domain = cls(token=api_token, name=domain_name)
domain.load()
return domain | [
"def",
"get_object",
"(",
"cls",
",",
"api_token",
",",
"domain_name",
")",
":",
"domain",
"=",
"cls",
"(",
"token",
"=",
"api_token",
",",
"name",
"=",
"domain_name",
")",
"domain",
".",
"load",
"(",
")",
"return",
"domain"
] | 32.428571 | 11.571429 |
def update(self, id, body):
"""Modifies a connection.
Args:
id: Id of the connection.
body (dict): Specifies which fields are to be modified, and to what
values.
See: https://auth0.com/docs/api/management/v2#!/Connections/patch_connections_by_id
... | [
"def",
"update",
"(",
"self",
",",
"id",
",",
"body",
")",
":",
"return",
"self",
".",
"client",
".",
"patch",
"(",
"self",
".",
"_url",
"(",
"id",
")",
",",
"data",
"=",
"body",
")"
] | 28.8 | 24.133333 |
def create_window(width, height, title, monitor, share):
"""
Creates a window and its associated context.
Wrapper for:
GLFWwindow* glfwCreateWindow(int width, int height, const char* title, GLFWmonitor* monitor, GLFWwindow* share);
"""
return _glfw.glfwCreateWindow(width, height, _to_char_p... | [
"def",
"create_window",
"(",
"width",
",",
"height",
",",
"title",
",",
"monitor",
",",
"share",
")",
":",
"return",
"_glfw",
".",
"glfwCreateWindow",
"(",
"width",
",",
"height",
",",
"_to_char_p",
"(",
"title",
")",
",",
"monitor",
",",
"share",
")"
] | 41.111111 | 22.666667 |
def _iter_info(self, niter, level=logging.INFO):
"""
Log iteration number and mismatch
Parameters
----------
level
logging level
Returns
-------
None
"""
max_mis = self.iter_mis[niter - 1]
msg = ' Iter {:<d}. max misma... | [
"def",
"_iter_info",
"(",
"self",
",",
"niter",
",",
"level",
"=",
"logging",
".",
"INFO",
")",
":",
"max_mis",
"=",
"self",
".",
"iter_mis",
"[",
"niter",
"-",
"1",
"]",
"msg",
"=",
"' Iter {:<d}. max mismatch = {:8.7f}'",
".",
"format",
"(",
"niter",
... | 24.533333 | 17.733333 |
def get_local_variable_or_declare_one(self, raw_name, type=None):
'''
This function will first check if raw_name has been used to create some variables. If yes, the latest one
named in self.variable_name_mapping[raw_name] will be returned. Otherwise, a new variable will be created and
th... | [
"def",
"get_local_variable_or_declare_one",
"(",
"self",
",",
"raw_name",
",",
"type",
"=",
"None",
")",
":",
"onnx_name",
"=",
"self",
".",
"get_onnx_variable_name",
"(",
"raw_name",
")",
"if",
"onnx_name",
"in",
"self",
".",
"variables",
":",
"return",
"self... | 49.588235 | 26.058824 |
def get_group_members(self, group_id, max_results=None, paging_token=None):
"""GetGroupMembers.
[Preview API] Get direct members of a Group.
:param str group_id: Id of the Group.
:param int max_results: Maximum number of results to retrieve.
:param str paging_token: Paging Token ... | [
"def",
"get_group_members",
"(",
"self",
",",
"group_id",
",",
"max_results",
"=",
"None",
",",
"paging_token",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"group_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'groupId'",
"]",
"=",
... | 63.5 | 29.318182 |
def normalize(W, copy=True):
'''
Normalizes an input weighted connection matrix. If copy is not set, this
function will *modify W in place.*
Parameters
----------
W : np.ndarray
weighted connectivity matrix
copy : bool
if True, returns a copy of the matrix. Otherwise, modif... | [
"def",
"normalize",
"(",
"W",
",",
"copy",
"=",
"True",
")",
":",
"if",
"copy",
":",
"W",
"=",
"W",
".",
"copy",
"(",
")",
"W",
"/=",
"np",
".",
"max",
"(",
"np",
".",
"abs",
"(",
"W",
")",
")",
"return",
"W"
] | 23.454545 | 23.272727 |
def preprocess(self, data):
"""
Processes popcorn JSON and builds a sane data model out of it
@param data : The popcorn editor project json blob
"""
print 'Beginning pre-process...'
for url, video in data['media'][0]['clipData'].iteritems():
print 'Downloadin... | [
"def",
"preprocess",
"(",
"self",
",",
"data",
")",
":",
"print",
"'Beginning pre-process...'",
"for",
"url",
",",
"video",
"in",
"data",
"[",
"'media'",
"]",
"[",
"0",
"]",
"[",
"'clipData'",
"]",
".",
"iteritems",
"(",
")",
":",
"print",
"'Downloading ... | 34.691176 | 18.397059 |
def filter_set(self, name):
"""
Adds filters from a particular global :class:`FilterSet`.
Args:
name (str): The name of the set whose filters should be added.
"""
filter_set = filter_sets[name]
for name, filter in iter(filter_set.filters.items()):
... | [
"def",
"filter_set",
"(",
"self",
",",
"name",
")",
":",
"filter_set",
"=",
"filter_sets",
"[",
"name",
"]",
"for",
"name",
",",
"filter",
"in",
"iter",
"(",
"filter_set",
".",
"filters",
".",
"items",
"(",
")",
")",
":",
"self",
".",
"filters",
"[",... | 32.583333 | 17.916667 |
def check_dependencies():
"""Check external dependecies
Return a tuple with the available generators.
"""
available = []
try:
shell('ebook-convert')
available.append('calibre')
except OSError:
pass
try:
shell('pandoc --help')
available.append('pandoc')... | [
"def",
"check_dependencies",
"(",
")",
":",
"available",
"=",
"[",
"]",
"try",
":",
"shell",
"(",
"'ebook-convert'",
")",
"available",
".",
"append",
"(",
"'calibre'",
")",
"except",
"OSError",
":",
"pass",
"try",
":",
"shell",
"(",
"'pandoc --help'",
")",... | 25.421053 | 16.684211 |
def alternative_parser(self, family_file):
"""
Parse alternative formatted family info
This parses a information with more than six columns.
For alternative information header comlumn must exist and each row
must have the same amount of columns as the header.
... | [
"def",
"alternative_parser",
"(",
"self",
",",
"family_file",
")",
":",
"alternative_header",
"=",
"None",
"for",
"line",
"in",
"family_file",
":",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"alternative_header",
"=",
"line",
"[",
"1",
":",
"]"... | 53.07619 | 23.666667 |
def save(self, path, binary=False):
"""Save a set of constructs into the CLIPS data base.
If binary is True, the constructs will be saved in binary format.
The Python equivalent of the CLIPS load command.
"""
if binary:
ret = lib.EnvBsave(self._env, path.encode())
... | [
"def",
"save",
"(",
"self",
",",
"path",
",",
"binary",
"=",
"False",
")",
":",
"if",
"binary",
":",
"ret",
"=",
"lib",
".",
"EnvBsave",
"(",
"self",
".",
"_env",
",",
"path",
".",
"encode",
"(",
")",
")",
"else",
":",
"ret",
"=",
"lib",
".",
... | 31.214286 | 19.642857 |
def polite_string(a_string):
"""Returns a "proper" string that should work in both Py3/Py2"""
if is_py3() and hasattr(a_string, 'decode'):
try:
return a_string.decode('utf-8')
except UnicodeDecodeError:
return a_string
return a_string | [
"def",
"polite_string",
"(",
"a_string",
")",
":",
"if",
"is_py3",
"(",
")",
"and",
"hasattr",
"(",
"a_string",
",",
"'decode'",
")",
":",
"try",
":",
"return",
"a_string",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"UnicodeDecodeError",
":",
"return",
... | 31 | 14.555556 |
def _set_queues_interface(self, v, load=False):
"""
Setter method for queues_interface, mapped from YANG variable /openflow_state/queues_interface (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_queues_interface is considered as a private
method. Backends... | [
"def",
"_set_queues_interface",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | 81.590909 | 38.045455 |
def parse_value(self, tup_tree):
"""
Parse a VALUE element and return its text content as a unicode string.
Whitespace is preserved.
The conversion of the text representation of the value to a CIM data
type object requires CIM type information which is not available on the
... | [
"def",
"parse_value",
"(",
"self",
",",
"tup_tree",
")",
":",
"self",
".",
"check_node",
"(",
"tup_tree",
",",
"'VALUE'",
",",
"(",
")",
",",
"(",
")",
",",
"(",
")",
",",
"allow_pcdata",
"=",
"True",
")",
"return",
"self",
".",
"pcdata",
"(",
"tup... | 33.111111 | 24.111111 |
async def begin_twophase(self, xid=None):
"""Begin a two-phase or XA transaction and return a transaction
handle.
The returned object is an instance of
TwoPhaseTransaction, which in addition to the
methods provided by Transaction, also provides a
TwoPhaseTransaction.prep... | [
"async",
"def",
"begin_twophase",
"(",
"self",
",",
"xid",
"=",
"None",
")",
":",
"if",
"self",
".",
"_transaction",
"is",
"not",
"None",
":",
"raise",
"exc",
".",
"InvalidRequestError",
"(",
"\"Cannot start a two phase transaction when a transaction \"",
"\"is alre... | 38.090909 | 13.818182 |
def t_bin_ZERO(t):
r'[^01]'
t.lexer.begin('INITIAL')
t.type = 'NUMBER'
t.value = 0
t.lexer.lexpos -= 1
return t | [
"def",
"t_bin_ZERO",
"(",
"t",
")",
":",
"t",
".",
"lexer",
".",
"begin",
"(",
"'INITIAL'",
")",
"t",
".",
"type",
"=",
"'NUMBER'",
"t",
".",
"value",
"=",
"0",
"t",
".",
"lexer",
".",
"lexpos",
"-=",
"1",
"return",
"t"
] | 18.428571 | 21.571429 |
def make_pre_authed_request(self, env, method=None, path=None, body=None,
headers=None):
"""Nearly the same as swift.common.wsgi.make_pre_authed_request
except that this also always sets the 'swift.source' and user
agent.
Newer Swift code will support swi... | [
"def",
"make_pre_authed_request",
"(",
"self",
",",
"env",
",",
"method",
"=",
"None",
",",
"path",
"=",
"None",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"if",
"self",
".",
"default_storage_policy",
":",
"sp",
"=",
"self",
".",
... | 43 | 18.304348 |
async def _workaround_1695335(self, delta, old, new, model):
"""
This is a (hacky) temporary work around for a bug in Juju where the
instance status and agent version fields don't get updated properly
by the AllWatcher.
Deltas never contain a value for `data['agent-status']['ver... | [
"async",
"def",
"_workaround_1695335",
"(",
"self",
",",
"delta",
",",
"old",
",",
"new",
",",
"model",
")",
":",
"if",
"delta",
".",
"data",
".",
"get",
"(",
"'synthetic'",
",",
"False",
")",
":",
"# prevent infinite loops re-processing already processed deltas... | 43.761194 | 24.80597 |
def find(self, header):
"""Return the index of the header in the set or return -1 if not found.
:param header: the header to be looked up.
"""
header = header.lower()
for idx, item in enumerate(self._headers):
if item.lower() == header:
return idx
... | [
"def",
"find",
"(",
"self",
",",
"header",
")",
":",
"header",
"=",
"header",
".",
"lower",
"(",
")",
"for",
"idx",
",",
"item",
"in",
"enumerate",
"(",
"self",
".",
"_headers",
")",
":",
"if",
"item",
".",
"lower",
"(",
")",
"==",
"header",
":",... | 32.5 | 12.5 |
def _download_file(uri, bulk_api):
"""Download the bulk API result file for a single batch"""
resp = requests.get(uri, headers=bulk_api.headers(), stream=True)
with tempfile.TemporaryFile("w+b") as f:
for chunk in resp.iter_content(chunk_size=None):
f.write(chunk)
f.seek(0)
... | [
"def",
"_download_file",
"(",
"uri",
",",
"bulk_api",
")",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"uri",
",",
"headers",
"=",
"bulk_api",
".",
"headers",
"(",
")",
",",
"stream",
"=",
"True",
")",
"with",
"tempfile",
".",
"TemporaryFile",
"(",
... | 40.375 | 14.625 |
def edge_statistics(docgraph):
"""print basic statistics about an edge, e.g. layer/attribute counts"""
print "Edge statistics\n==============="
layer_counts = Counter()
attrib_counts = Counter()
source_counts = Counter()
target_counts = Counter()
for source, target, edge_attrs in docgraph.ed... | [
"def",
"edge_statistics",
"(",
"docgraph",
")",
":",
"print",
"\"Edge statistics\\n===============\"",
"layer_counts",
"=",
"Counter",
"(",
")",
"attrib_counts",
"=",
"Counter",
"(",
")",
"source_counts",
"=",
"Counter",
"(",
")",
"target_counts",
"=",
"Counter",
... | 35.875 | 9 |
def dot(data, color=None, point_size=2, f_tooltip=None):
"""Create a dot density map
:param data: data access object
:param color: color
:param point_size: point size
:param f_tooltip: function to return a tooltip string for a point
"""
from geoplotlib.layers import DotDensityLayer
_glo... | [
"def",
"dot",
"(",
"data",
",",
"color",
"=",
"None",
",",
"point_size",
"=",
"2",
",",
"f_tooltip",
"=",
"None",
")",
":",
"from",
"geoplotlib",
".",
"layers",
"import",
"DotDensityLayer",
"_global_config",
".",
"layers",
".",
"append",
"(",
"DotDensityLa... | 41.5 | 19.5 |
def vector_check(vector):
"""
Check input vector items type.
:param vector: input vector
:type vector : list
:return: bool
"""
for i in vector:
if isinstance(i, int) is False:
return False
if i < 0:
return False
return True | [
"def",
"vector_check",
"(",
"vector",
")",
":",
"for",
"i",
"in",
"vector",
":",
"if",
"isinstance",
"(",
"i",
",",
"int",
")",
"is",
"False",
":",
"return",
"False",
"if",
"i",
"<",
"0",
":",
"return",
"False",
"return",
"True"
] | 20.214286 | 15.071429 |
def auth(username, password):
'''
Authenticate against yubico server
'''
_cred = __get_yubico_users(username)
client = Yubico(_cred['id'], _cred['key'])
try:
return client.verify(password)
except yubico_exceptions.StatusCodeError as e:
log.info('Unable to verify YubiKey `%s... | [
"def",
"auth",
"(",
"username",
",",
"password",
")",
":",
"_cred",
"=",
"__get_yubico_users",
"(",
"username",
")",
"client",
"=",
"Yubico",
"(",
"_cred",
"[",
"'id'",
"]",
",",
"_cred",
"[",
"'key'",
"]",
")",
"try",
":",
"return",
"client",
".",
"... | 25.769231 | 18.538462 |
def get_sitetree(self, alias):
"""Gets site tree items from the given site tree.
Caches result to dictionary.
Returns (tree alias, tree items) tuple.
:param str|unicode alias:
:rtype: tuple
"""
cache_ = self.cache
get_cache_entry = cache_.get_entry
... | [
"def",
"get_sitetree",
"(",
"self",
",",
"alias",
")",
":",
"cache_",
"=",
"self",
".",
"cache",
"get_cache_entry",
"=",
"cache_",
".",
"get_entry",
"set_cache_entry",
"=",
"cache_",
".",
"set_entry",
"caching_required",
"=",
"False",
"if",
"not",
"self",
".... | 35.682353 | 19.141176 |
def split_pem(s):
"""
Split PEM objects. Useful to process concatenated certificates.
"""
pem_strings = []
while s != b"":
start_idx = s.find(b"-----BEGIN")
if start_idx == -1:
break
end_idx = s.find(b"-----END")
end_idx = s.find(b"\n", end_idx) + 1
... | [
"def",
"split_pem",
"(",
"s",
")",
":",
"pem_strings",
"=",
"[",
"]",
"while",
"s",
"!=",
"b\"\"",
":",
"start_idx",
"=",
"s",
".",
"find",
"(",
"b\"-----BEGIN\"",
")",
"if",
"start_idx",
"==",
"-",
"1",
":",
"break",
"end_idx",
"=",
"s",
".",
"fin... | 28.285714 | 12.714286 |
def type(self):
'''Return 'suite' or 'resource' or None
This will return 'suite' if a testcase table is found;
It will return 'resource' if at least one robot table
is found. If no tables are found it will return None
'''
robot_tables = [table for table in self.tables i... | [
"def",
"type",
"(",
"self",
")",
":",
"robot_tables",
"=",
"[",
"table",
"for",
"table",
"in",
"self",
".",
"tables",
"if",
"not",
"isinstance",
"(",
"table",
",",
"UnknownTable",
")",
"]",
"if",
"len",
"(",
"robot_tables",
")",
"==",
"0",
":",
"retu... | 31.941176 | 23.588235 |
def _get_real_ip(self):
"""
Get IP from request.
:param request: A usual request object
:type request: HttpRequest
:return: ipv4 string or None
"""
try:
# Trying to work with most common proxy headers
real_ip = self.request.META['HTTP_X_FO... | [
"def",
"_get_real_ip",
"(",
"self",
")",
":",
"try",
":",
"# Trying to work with most common proxy headers",
"real_ip",
"=",
"self",
".",
"request",
".",
"META",
"[",
"'HTTP_X_FORWARDED_FOR'",
"]",
"return",
"real_ip",
".",
"split",
"(",
"','",
")",
"[",
"0",
... | 30 | 13.529412 |
def setError(self, msg=None, title=None):
""" Shows and error message
"""
if msg is not None:
self.messageLabel.setText(msg)
if title is not None:
self.titleLabel.setText(title) | [
"def",
"setError",
"(",
"self",
",",
"msg",
"=",
"None",
",",
"title",
"=",
"None",
")",
":",
"if",
"msg",
"is",
"not",
"None",
":",
"self",
".",
"messageLabel",
".",
"setText",
"(",
"msg",
")",
"if",
"title",
"is",
"not",
"None",
":",
"self",
".... | 28.375 | 8.625 |
def _load_results(self, container_id):
"""
load results from recent build
:return: BuildResults
"""
if self.temp_dir:
dt = DockerTasker()
# FIXME: load results only when requested
# results_path = os.path.join(self.temp_dir, RESULTS_JSON)
... | [
"def",
"_load_results",
"(",
"self",
",",
"container_id",
")",
":",
"if",
"self",
".",
"temp_dir",
":",
"dt",
"=",
"DockerTasker",
"(",
")",
"# FIXME: load results only when requested",
"# results_path = os.path.join(self.temp_dir, RESULTS_JSON)",
"# df_path = os.path.join(se... | 45.083333 | 17.416667 |
def is_empty(self):
"""Asserts that val is empty."""
if len(self.val) != 0:
if isinstance(self.val, str_types):
self._err('Expected <%s> to be empty string, but was not.' % self.val)
else:
self._err('Expected <%s> to be empty, but was not.' % self.... | [
"def",
"is_empty",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"val",
")",
"!=",
"0",
":",
"if",
"isinstance",
"(",
"self",
".",
"val",
",",
"str_types",
")",
":",
"self",
".",
"_err",
"(",
"'Expected <%s> to be empty string, but was not.'",
"%... | 42.125 | 20.875 |
def merge_groups(self, indices):
"""Extend the lists within the DICOM groups dictionary.
The indices will indicate which list have to be extended by which
other list.
Parameters
----------
indices: list or tuple of 2 iterables of int, bot having the same len
... | [
"def",
"merge_groups",
"(",
"self",
",",
"indices",
")",
":",
"try",
":",
"merged",
"=",
"merge_dict_of_lists",
"(",
"self",
".",
"dicom_groups",
",",
"indices",
",",
"pop_later",
"=",
"True",
",",
"copy",
"=",
"True",
")",
"self",
".",
"dicom_groups",
"... | 46.3 | 22.3 |
def _save_metadata(self):
"""
Write this prefix metadata to disk
Returns:
None
"""
with open(self.paths.metadata(), 'w') as metadata_fd:
utils.json_dump(self.metadata, metadata_fd) | [
"def",
"_save_metadata",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"paths",
".",
"metadata",
"(",
")",
",",
"'w'",
")",
"as",
"metadata_fd",
":",
"utils",
".",
"json_dump",
"(",
"self",
".",
"metadata",
",",
"metadata_fd",
")"
] | 26.333333 | 15.666667 |
def get_graph_csv():
"""
Allows the user to download a graph's data as a CSV file.
:return: show a dialog box that allows the user to download the CSV file.
"""
assert request.method == "POST", "POST request expected received {}".format(request.method)
if request.method == "POST":
try:
... | [
"def",
"get_graph_csv",
"(",
")",
":",
"assert",
"request",
".",
"method",
"==",
"\"POST\"",
",",
"\"POST request expected received {}\"",
".",
"format",
"(",
"request",
".",
"method",
")",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"try",
":",
"... | 48.142857 | 24.571429 |
def addProfile(self, profile):
"""
Adds the inputed profile to the system.
:param profile | <XViewProfile>
"""
if ( profile in self._profiles ):
return
self._profiles.append(profile)
self._profileCombo.blockSignals(True)
... | [
"def",
"addProfile",
"(",
"self",
",",
"profile",
")",
":",
"if",
"(",
"profile",
"in",
"self",
".",
"_profiles",
")",
":",
"return",
"self",
".",
"_profiles",
".",
"append",
"(",
"profile",
")",
"self",
".",
"_profileCombo",
".",
"blockSignals",
"(",
... | 33.5 | 11.642857 |
def add_archive(self, src_file, remove_final=False):
"""
Adds the contents of another tarfile to the build. It will be repackaged during context generation, and added
to the root level of the file system. Therefore, it is not required that tar (or compression utilities) is
present in the... | [
"def",
"add_archive",
"(",
"self",
",",
"src_file",
",",
"remove_final",
"=",
"False",
")",
":",
"with",
"tarfile",
".",
"open",
"(",
"src_file",
",",
"'r'",
")",
"as",
"tf",
":",
"member_names",
"=",
"[",
"member",
".",
"name",
"for",
"member",
"in",
... | 54.2 | 25 |
def get_zorder(self, overlay, key, el):
"""
Computes the z-order of element in the NdOverlay
taking into account possible batching of elements.
"""
spec = util.get_overlay_spec(overlay, key, el)
return self.ordering.index(spec) | [
"def",
"get_zorder",
"(",
"self",
",",
"overlay",
",",
"key",
",",
"el",
")",
":",
"spec",
"=",
"util",
".",
"get_overlay_spec",
"(",
"overlay",
",",
"key",
",",
"el",
")",
"return",
"self",
".",
"ordering",
".",
"index",
"(",
"spec",
")"
] | 38.428571 | 7 |
def check_field_exists(self, field_name):
"""Implements field exists check for debugging purposes.
:param field_name:
:return:
"""
if not settings.DEBUG:
return
try:
self.lookup_opts.get_field(field_name)
except FieldDoesNotExist as e:
... | [
"def",
"check_field_exists",
"(",
"self",
",",
"field_name",
")",
":",
"if",
"not",
"settings",
".",
"DEBUG",
":",
"return",
"try",
":",
"self",
".",
"lookup_opts",
".",
"get_field",
"(",
"field_name",
")",
"except",
"FieldDoesNotExist",
"as",
"e",
":",
"r... | 25.357143 | 17.142857 |
def configure(level=logging.WARNING, handler=None, formatter=None):
"""Configure Logr
@param handler: Logger message handler
@type handler: logging.Handler or None
@param formatter: Logger message Formatter
@type formatter: logging.Formatter or None
"""
if forma... | [
"def",
"configure",
"(",
"level",
"=",
"logging",
".",
"WARNING",
",",
"handler",
"=",
"None",
",",
"formatter",
"=",
"None",
")",
":",
"if",
"formatter",
"is",
"None",
":",
"formatter",
"=",
"LogrFormatter",
"(",
")",
"if",
"handler",
"is",
"None",
":... | 29.722222 | 14.944444 |
def clean_lines(string_list, remove_empty_lines=True):
"""
Strips whitespace, carriage returns and empty lines from a list of strings.
Args:
string_list: List of strings
remove_empty_lines: Set to True to skip lines which are empty after
stripping.
Returns:
List of ... | [
"def",
"clean_lines",
"(",
"string_list",
",",
"remove_empty_lines",
"=",
"True",
")",
":",
"for",
"s",
"in",
"string_list",
":",
"clean_s",
"=",
"s",
"if",
"'#'",
"in",
"s",
":",
"ind",
"=",
"s",
".",
"index",
"(",
"'#'",
")",
"clean_s",
"=",
"s",
... | 27.857143 | 19.571429 |
def _get_file(self, share_name, directory_name, file_name,
start_range=None, end_range=None,
range_get_content_md5=None, timeout=None):
'''
Downloads a file's content, metadata, and properties. You can specify a
range if you don't need to download the file in it... | [
"def",
"_get_file",
"(",
"self",
",",
"share_name",
",",
"directory_name",
",",
"file_name",
",",
"start_range",
"=",
"None",
",",
"end_range",
"=",
"None",
",",
"range_get_content_md5",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"_validate_not_none",... | 48.037736 | 20.45283 |
def Receive(self, replytype, **kw):
'''Parse message, create Python object.
KeyWord data:
faults -- list of WSDL operation.fault typecodes
wsaction -- If using WS-Address, must specify Action value we expect to
receive.
'''
self.ReceiveSOAP(**kw... | [
"def",
"Receive",
"(",
"self",
",",
"replytype",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"ReceiveSOAP",
"(",
"*",
"*",
"kw",
")",
"if",
"self",
".",
"ps",
".",
"IsAFault",
"(",
")",
":",
"msg",
"=",
"FaultFromFaultMessage",
"(",
"self",
".",
... | 32.52381 | 17.857143 |
def _deregister(self, session):
"""
Deregister a session.
"""
if session in self:
self._sessions.pop(self._get_session_key(session), None) | [
"def",
"_deregister",
"(",
"self",
",",
"session",
")",
":",
"if",
"session",
"in",
"self",
":",
"self",
".",
"_sessions",
".",
"pop",
"(",
"self",
".",
"_get_session_key",
"(",
"session",
")",
",",
"None",
")"
] | 29.666667 | 10 |
def _CreateDynamicDisplayAdSettings(media_service, opener):
"""Creates settings for dynamic display ad.
Args:
media_service: a SudsServiceProxy instance for AdWords's MediaService.
opener: an OpenerDirector instance.
Returns:
The dynamic display ad settings.
"""
image = _CreateImage(media_servic... | [
"def",
"_CreateDynamicDisplayAdSettings",
"(",
"media_service",
",",
"opener",
")",
":",
"image",
"=",
"_CreateImage",
"(",
"media_service",
",",
"opener",
",",
"'https://goo.gl/dEvQeF'",
")",
"logo",
"=",
"{",
"'type'",
":",
"'IMAGE'",
",",
"'mediaId'",
":",
"i... | 24.115385 | 21.115385 |
def samtools_index(self, bam_file):
"""Index a bam file."""
cmd = self.tools.samtools + " index {0}".format(bam_file)
return cmd | [
"def",
"samtools_index",
"(",
"self",
",",
"bam_file",
")",
":",
"cmd",
"=",
"self",
".",
"tools",
".",
"samtools",
"+",
"\" index {0}\"",
".",
"format",
"(",
"bam_file",
")",
"return",
"cmd"
] | 37.25 | 13 |
def sample_shape(self):
"""Sample shape of random variable as a `TensorShape`."""
if isinstance(self._sample_shape, tf.Tensor):
return tf.TensorShape(tf.get_static_value(self._sample_shape))
return tf.TensorShape(self._sample_shape) | [
"def",
"sample_shape",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_sample_shape",
",",
"tf",
".",
"Tensor",
")",
":",
"return",
"tf",
".",
"TensorShape",
"(",
"tf",
".",
"get_static_value",
"(",
"self",
".",
"_sample_shape",
")",
")",
... | 49.2 | 11.8 |
def get_sgburst_waveform(template=None, **kwargs):
"""Return the plus and cross polarizations of a time domain
sine-Gaussian burst waveform.
Parameters
----------
template: object
An object that has attached properties. This can be used to subsitute
for keyword arguments. A common e... | [
"def",
"get_sgburst_waveform",
"(",
"template",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"input_params",
"=",
"props_sgburst",
"(",
"template",
",",
"*",
"*",
"kwargs",
")",
"for",
"arg",
"in",
"sgburst_required_args",
":",
"if",
"arg",
"not",
"in",... | 31.675676 | 19.459459 |
def _call_retry(self, force_retry):
"""Call request and retry up to max_attempts times (or none if self.max_attempts=1)"""
last_exception = None
for i in range(self.max_attempts):
try:
log.info("Calling %s %s" % (self.method, self.url))
response = self... | [
"def",
"_call_retry",
"(",
"self",
",",
"force_retry",
")",
":",
"last_exception",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"max_attempts",
")",
":",
"try",
":",
"log",
".",
"info",
"(",
"\"Calling %s %s\"",
"%",
"(",
"self",
".",
"met... | 42.84375 | 21.125 |
def http_redirect_message(message, location, relay_state="", typ="SAMLRequest",
sigalg='', signer=None, **kwargs):
"""The HTTP Redirect binding defines a mechanism by which SAML protocol
messages can be transmitted within URL parameters.
Messages are encoded for use with this bindi... | [
"def",
"http_redirect_message",
"(",
"message",
",",
"location",
",",
"relay_state",
"=",
"\"\"",
",",
"typ",
"=",
"\"SAMLRequest\"",
",",
"sigalg",
"=",
"''",
",",
"signer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",... | 37.018182 | 20.909091 |
def get_providing_power_source_type(self):
"""
Returns GetSystemPowerStatus().ACLineStatus
@raise: WindowsError if any underlying error occures.
"""
power_status = SYSTEM_POWER_STATUS()
if not GetSystemPowerStatus(pointer(power_status)):
raise WinError()
... | [
"def",
"get_providing_power_source_type",
"(",
"self",
")",
":",
"power_status",
"=",
"SYSTEM_POWER_STATUS",
"(",
")",
"if",
"not",
"GetSystemPowerStatus",
"(",
"pointer",
"(",
"power_status",
")",
")",
":",
"raise",
"WinError",
"(",
")",
"return",
"POWER_TYPE_MAP... | 36.3 | 12.5 |
def reset_status(self):
"""Reset progress bars"""
for item in self.items:
item.isProcessing = False
item.currentProgress = 0 | [
"def",
"reset_status",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"items",
":",
"item",
".",
"isProcessing",
"=",
"False",
"item",
".",
"currentProgress",
"=",
"0"
] | 32 | 6.6 |
def add_residue_from_geo(structure, geo):
'''Adds a residue to chain A model 0 of the given structure, and
returns the new structure. The residue to be added is determined by
the geometry object given as second argument.
This function is a helper function and should not normally be called
direc... | [
"def",
"add_residue_from_geo",
"(",
"structure",
",",
"geo",
")",
":",
"resRef",
"=",
"getReferenceResidue",
"(",
"structure",
")",
"AA",
"=",
"geo",
".",
"residue_name",
"segID",
"=",
"resRef",
".",
"get_id",
"(",
")",
"[",
"1",
"]",
"segID",
"+=",
"1",... | 35.141304 | 20.423913 |
def _parse_genotype(self, vcf_fields):
"""Parse genotype from VCF line data"""
format_col = vcf_fields[8].split(':')
genome_data = vcf_fields[9].split(':')
try:
gt_idx = format_col.index('GT')
except ValueError:
return []
return [int(x) for x in re... | [
"def",
"_parse_genotype",
"(",
"self",
",",
"vcf_fields",
")",
":",
"format_col",
"=",
"vcf_fields",
"[",
"8",
"]",
".",
"split",
"(",
"':'",
")",
"genome_data",
"=",
"vcf_fields",
"[",
"9",
"]",
".",
"split",
"(",
"':'",
")",
"try",
":",
"gt_idx",
"... | 37.7 | 12.6 |
def getScriptLocation():
"""Helper function to get the location of a Python file."""
location = os.path.abspath("./")
if __file__.rfind("/") != -1:
location = __file__[:__file__.rfind("/")]
return location | [
"def",
"getScriptLocation",
"(",
")",
":",
"location",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"\"./\"",
")",
"if",
"__file__",
".",
"rfind",
"(",
"\"/\"",
")",
"!=",
"-",
"1",
":",
"location",
"=",
"__file__",
"[",
":",
"__file__",
".",
"rfind"... | 34.333333 | 10 |
def spi_configure(self, polarity, phase, bitorder):
"""Configure the SPI interface."""
ret = api.py_aa_spi_configure(self.handle, polarity, phase, bitorder)
_raise_error_if_negative(ret) | [
"def",
"spi_configure",
"(",
"self",
",",
"polarity",
",",
"phase",
",",
"bitorder",
")",
":",
"ret",
"=",
"api",
".",
"py_aa_spi_configure",
"(",
"self",
".",
"handle",
",",
"polarity",
",",
"phase",
",",
"bitorder",
")",
"_raise_error_if_negative",
"(",
... | 51.75 | 12.75 |
def p_file_contrib_1(self, p):
"""file_contrib : FILE_CONTRIB LINE"""
try:
if six.PY2:
value = p[2].decode(encoding='utf-8')
else:
value = p[2]
self.builder.add_file_contribution(self.document, value)
except OrderError:
... | [
"def",
"p_file_contrib_1",
"(",
"self",
",",
"p",
")",
":",
"try",
":",
"if",
"six",
".",
"PY2",
":",
"value",
"=",
"p",
"[",
"2",
"]",
".",
"decode",
"(",
"encoding",
"=",
"'utf-8'",
")",
"else",
":",
"value",
"=",
"p",
"[",
"2",
"]",
"self",
... | 37.5 | 17.7 |
def doublewrap(f):
'''
a decorator decorator, allowing the decorator to be used as:
@decorator(with, arguments, and=kwargs)
or
@decorator
Ref: http://stackoverflow.com/questions/653368/how-to-create-a-python-decorator-that-can-be-used-either-with-or-without-paramet
'''
@functools.wraps(f... | [
"def",
"doublewrap",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"new_dec",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"len",
"(",
"kwargs",
")",
"==",
"... | 33.611111 | 24.722222 |
def get_differing_atom_residue_ids(self, pdb_name, pdb_list = []):
'''Returns a list of residues in pdb_name which differ from the pdbs corresponding to the names in pdb_list.'''
# partition_by_sequence is a map pdb_name -> Int where two pdb names in the same equivalence class map to the same integer (... | [
"def",
"get_differing_atom_residue_ids",
"(",
"self",
",",
"pdb_name",
",",
"pdb_list",
"=",
"[",
"]",
")",
":",
"# partition_by_sequence is a map pdb_name -> Int where two pdb names in the same equivalence class map to the same integer (i.e. it is a partition)",
"# representative_pdbs i... | 58.162162 | 36.594595 |
def _add_additional_properties(position, properties_dict):
"""
Sets AdditionalProperties of the ProbModelXML.
"""
add_prop = etree.SubElement(position, 'AdditionalProperties')
for key, value in properties_dict.items():
etree.SubElement(add_prop, 'Property', attrib={'n... | [
"def",
"_add_additional_properties",
"(",
"position",
",",
"properties_dict",
")",
":",
"add_prop",
"=",
"etree",
".",
"SubElement",
"(",
"position",
",",
"'AdditionalProperties'",
")",
"for",
"key",
",",
"value",
"in",
"properties_dict",
".",
"items",
"(",
")",... | 48.714286 | 17 |
def inbox_folder(self):
""" Shortcut to get Inbox Folder instance
:rtype: mailbox.Folder
"""
return self.folder_constructor(parent=self, name='Inbox',
folder_id=OutlookWellKnowFolderNames
.INBOX.value) | [
"def",
"inbox_folder",
"(",
"self",
")",
":",
"return",
"self",
".",
"folder_constructor",
"(",
"parent",
"=",
"self",
",",
"name",
"=",
"'Inbox'",
",",
"folder_id",
"=",
"OutlookWellKnowFolderNames",
".",
"INBOX",
".",
"value",
")"
] | 38.125 | 17.375 |
def ssh(container, cmd='', user='root', password='root'):
'''
SSH into a running container, using the host as a jump host. This requires
the container to have a running sshd process.
Args:
* container: Container name or ID
* cmd='': Command to run in the container
* user='root':... | [
"def",
"ssh",
"(",
"container",
",",
"cmd",
"=",
"''",
",",
"user",
"=",
"'root'",
",",
"password",
"=",
"'root'",
")",
":",
"ip",
"=",
"get_ip",
"(",
"container",
")",
"ssh_cmd",
"=",
"'sshpass -p \\'%s\\' ssh -A -t -o StrictHostKeyChecking=no \\'%s\\'@%s'",
"%... | 42.266667 | 23.2 |
def monitor(args):
""" file monitor mode """
filename = args.get('MDFILE')
if not filename:
print col('Need file argument', 2)
raise SystemExit
last_err = ''
last_stat = 0
while True:
if not os.path.exists(filename):
last_err = 'File %s not found. Will continu... | [
"def",
"monitor",
"(",
"args",
")",
":",
"filename",
"=",
"args",
".",
"get",
"(",
"'MDFILE'",
")",
"if",
"not",
"filename",
":",
"print",
"col",
"(",
"'Need file argument'",
",",
"2",
")",
"raise",
"SystemExit",
"last_err",
"=",
"''",
"last_stat",
"=",
... | 30.083333 | 13.125 |
def process_query_result(self, query_result, start_date, end_date):
"""Build the result using the query result."""
def build_buckets(agg, fields, bucket_result):
"""Build recursively result buckets."""
# Add metric results for current bucket
for metric in self.metric_... | [
"def",
"process_query_result",
"(",
"self",
",",
"query_result",
",",
"start_date",
",",
"end_date",
")",
":",
"def",
"build_buckets",
"(",
"agg",
",",
"fields",
",",
"bucket_result",
")",
":",
"\"\"\"Build recursively result buckets.\"\"\"",
"# Add metric results for c... | 44.666667 | 17.242424 |
def render_source(output_dir, package_specs, version):
"""
Render and output
"""
destination_filename = "%s/sbp_out.tex" % output_dir
py_template = JENV.get_template(TEMPLATE_NAME)
stable_msgs = []
unstable_msgs = []
prims = []
for p in sorted(package_specs, key=attrgetter('identifier')):
pkg_name... | [
"def",
"render_source",
"(",
"output_dir",
",",
"package_specs",
",",
"version",
")",
":",
"destination_filename",
"=",
"\"%s/sbp_out.tex\"",
"%",
"output_dir",
"py_template",
"=",
"JENV",
".",
"get_template",
"(",
"TEMPLATE_NAME",
")",
"stable_msgs",
"=",
"[",
"]... | 34.421053 | 14.596491 |
def MappingField(cls, child_key, default=NOTHING, required=True, repr=False,
key=None):
"""
Create new mapping field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param child_key: key field on the child object to be used as the map key.
:param def... | [
"def",
"MappingField",
"(",
"cls",
",",
"child_key",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
... | 53.5 | 23.5 |
def timeAtThreshold(self,dateTime):
'''
A convenience method for checking when a time is on the start/end boundary
for this rule.
'''
# Anything that's not at a day boundary is for sure not at a threshold.
if not (
dateTime.hour == self.dayStarts and dateTime... | [
"def",
"timeAtThreshold",
"(",
"self",
",",
"dateTime",
")",
":",
"# Anything that's not at a day boundary is for sure not at a threshold.",
"if",
"not",
"(",
"dateTime",
".",
"hour",
"==",
"self",
".",
"dayStarts",
"and",
"dateTime",
".",
"minute",
"==",
"0",
"and"... | 36.636364 | 24.636364 |
def set_ports(self, port0 = 0x00, port1 = 0x00):
'Writes specified value to the pins defined as output by method. Writing to input pins has no effect.'
self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port0)
self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port1)
retu... | [
"def",
"set_ports",
"(",
"self",
",",
"port0",
"=",
"0x00",
",",
"port1",
"=",
"0x00",
")",
":",
"self",
".",
"bus",
".",
"write_byte_data",
"(",
"self",
".",
"address",
",",
"self",
".",
"CONTROL_PORT0",
",",
"port0",
")",
"self",
".",
"bus",
".",
... | 63.6 | 34 |
def _ostaunicode(src):
# type: (str) -> bytes
'''
Internal function to create an OSTA byte string from a source string.
'''
if have_py_3:
bytename = src
else:
bytename = src.decode('utf-8') # type: ignore
try:
enc = bytename.encode('latin-1')
encbyte = b'\x0... | [
"def",
"_ostaunicode",
"(",
"src",
")",
":",
"# type: (str) -> bytes",
"if",
"have_py_3",
":",
"bytename",
"=",
"src",
"else",
":",
"bytename",
"=",
"src",
".",
"decode",
"(",
"'utf-8'",
")",
"# type: ignore",
"try",
":",
"enc",
"=",
"bytename",
".",
"enco... | 26.647059 | 20.529412 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.