text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _format_lon(self, lon):
''' Returned a formated longitude format for the file '''
if self.ppd in [4, 16, 64, 128]:
return None
else:
return map(lambda x: "{0:0>3}".format(int(x)), self._map_center('long', lon)) | [
"def",
"_format_lon",
"(",
"self",
",",
"lon",
")",
":",
"if",
"self",
".",
"ppd",
"in",
"[",
"4",
",",
"16",
",",
"64",
",",
"128",
"]",
":",
"return",
"None",
"else",
":",
"return",
"map",
"(",
"lambda",
"x",
":",
"\"{0:0>3}\"",
".",
"format",
... | 42.833333 | 21.833333 |
def decryption_statem(self, ciphertext_in, key_in, reset):
"""
Builds a multiple cycle AES Decryption state machine circuit
:param reset: a one bit signal telling the state machine
to reset and accept the current plaintext and key
:return ready, plain_text: ready is a one bit ... | [
"def",
"decryption_statem",
"(",
"self",
",",
"ciphertext_in",
",",
"key_in",
",",
"reset",
")",
":",
"if",
"len",
"(",
"key_in",
")",
"!=",
"len",
"(",
"ciphertext_in",
")",
":",
"raise",
"pyrtl",
".",
"PyrtlError",
"(",
"\"AES key and ciphertext should be th... | 39.054545 | 20.290909 |
def setEnabled(self, state):
"""
Updates the drop shadow effect for this widget on enable/disable
state change.
:param state | <bool>
"""
super(XToolButton, self).setEnabled(state)
self.updateUi() | [
"def",
"setEnabled",
"(",
"self",
",",
"state",
")",
":",
"super",
"(",
"XToolButton",
",",
"self",
")",
".",
"setEnabled",
"(",
"state",
")",
"self",
".",
"updateUi",
"(",
")"
] | 27.5 | 15.7 |
def copy(self):
""" Prepare and paste self templates. """
templates = self.prepare_templates()
if self.params.interactive:
keys = list(self.parser.default)
for key in keys:
if key.startswith('_'):
continue
prompt = "{0} ... | [
"def",
"copy",
"(",
"self",
")",
":",
"templates",
"=",
"self",
".",
"prepare_templates",
"(",
")",
"if",
"self",
".",
"params",
".",
"interactive",
":",
"keys",
"=",
"list",
"(",
"self",
".",
"parser",
".",
"default",
")",
"for",
"key",
"in",
"keys"... | 36.875 | 17.09375 |
def SETE(cpu, dest):
"""
Sets byte if equal.
:param cpu: current CPU.
:param dest: destination operand.
"""
dest.write(Operators.ITEBV(dest.size, cpu.ZF, 1, 0)) | [
"def",
"SETE",
"(",
"cpu",
",",
"dest",
")",
":",
"dest",
".",
"write",
"(",
"Operators",
".",
"ITEBV",
"(",
"dest",
".",
"size",
",",
"cpu",
".",
"ZF",
",",
"1",
",",
"0",
")",
")"
] | 25.25 | 12.75 |
def _uminumaxvmin(self,*args,**kwargs):
"""
NAME:
_uminumaxvmin
PURPOSE:
evaluate u_min, u_max, and v_min
INPUT:
Either:
a) R,vR,vT,z,vz
b) Orbit instance: initial condition used if that's it, orbit(t)
if there... | [
"def",
"_uminumaxvmin",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"delta",
"=",
"kwargs",
".",
"pop",
"(",
"'delta'",
",",
"self",
".",
"_delta",
")",
"if",
"(",
"(",
"self",
".",
"_c",
"and",
"not",
"(",
"'c'",
"in",
"k... | 42.695652 | 14.565217 |
def get_configurations_on_targets(self, target_name=None, configuration_name=None):
"""
Retrieves all configuration given a name on the specified target
:param target_name: Searches for a specific target name or a list of target names. If None all targets are used
:param configuration_na... | [
"def",
"get_configurations_on_targets",
"(",
"self",
",",
"target_name",
"=",
"None",
",",
"configuration_name",
"=",
"None",
")",
":",
"for",
"target",
"in",
"self",
".",
"get_targets",
"(",
"target_name",
")",
":",
"configuration_list",
"=",
"self",
"[",
"ta... | 64.571429 | 34.142857 |
def restart(self):
"""
Restarts the whole wizard from the beginning.
"""
# hide all of the pages
for page in self._pages.values():
page.hide()
pageId = self.startId()
try:
first_page = self._pages[pageId]
except KeyError:
... | [
"def",
"restart",
"(",
"self",
")",
":",
"# hide all of the pages",
"for",
"page",
"in",
"self",
".",
"_pages",
".",
"values",
"(",
")",
":",
"page",
".",
"hide",
"(",
")",
"pageId",
"=",
"self",
".",
"startId",
"(",
")",
"try",
":",
"first_page",
"=... | 34.795455 | 17.977273 |
def records():
"""Load test data fixture."""
import uuid
from invenio_records.api import Record
from invenio_pidstore.models import PersistentIdentifier, PIDStatus
create_test_user()
indexer = RecordIndexer()
# Record 1 - Live record
with db.session.begin_nested():
rec_uuid = ... | [
"def",
"records",
"(",
")",
":",
"import",
"uuid",
"from",
"invenio_records",
".",
"api",
"import",
"Record",
"from",
"invenio_pidstore",
".",
"models",
"import",
"PersistentIdentifier",
",",
"PIDStatus",
"create_test_user",
"(",
")",
"indexer",
"=",
"RecordIndexe... | 28.5 | 17.133333 |
def compare(buf_a, buf_b, ignore):
"""Compare of two Buffer item"""
for field in getattr(buf_a, '_fields_'):
name, types = field[0], field[1]
if name in ignore:
continue
val_a = getattr(buf_a, name)
val_b = getattr(buf_b, name)
if isinstance(types, (type(Un... | [
"def",
"compare",
"(",
"buf_a",
",",
"buf_b",
",",
"ignore",
")",
":",
"for",
"field",
"in",
"getattr",
"(",
"buf_a",
",",
"'_fields_'",
")",
":",
"name",
",",
"types",
"=",
"field",
"[",
"0",
"]",
",",
"field",
"[",
"1",
"]",
"if",
"name",
"in",... | 30.481481 | 15.814815 |
def _render_uncached_items(self, items, result):
"""
Render a list of items, that didn't exist in the cache yet.
"""
for contentitem in items:
# Render the item.
# Allow derived classes to skip it.
try:
output = self.render_item(content... | [
"def",
"_render_uncached_items",
"(",
"self",
",",
"items",
",",
"result",
")",
":",
"for",
"contentitem",
"in",
"items",
":",
"# Render the item.",
"# Allow derived classes to skip it.",
"try",
":",
"output",
"=",
"self",
".",
"render_item",
"(",
"contentitem",
"... | 39 | 17.695652 |
def _check_link_completion(self, link, fail_pending=False, fail_running=False):
"""Internal function to check the completion of all the dispatched jobs
Returns
-------
status_vect : `JobStatusVector`
Vector that summarize the number of jobs in various states.
"""
... | [
"def",
"_check_link_completion",
"(",
"self",
",",
"link",
",",
"fail_pending",
"=",
"False",
",",
"fail_running",
"=",
"False",
")",
":",
"status_vect",
"=",
"JobStatusVector",
"(",
")",
"for",
"job_key",
",",
"job_details",
"in",
"link",
".",
"jobs",
".",
... | 39.419355 | 18.322581 |
def to_pybel(self):
"""
Produce a Pybel Molecule object.
It is based on the capabilities of OpenBabel through Pybel. The present
object must have at least `atomcoords`, `atomnos`, `charge` and `mult`
defined.
Returns
-------
`pybel.Molecule`
Exa... | [
"def",
"to_pybel",
"(",
"self",
")",
":",
"# TODO: This only exports last geometry by default.",
"obmol",
"=",
"_makeopenbabel",
"(",
"self",
".",
"atomcoords",
",",
"self",
".",
"atomnos",
",",
"self",
".",
"charge",
",",
"self",
".",
"mult",
")",
"title",
"=... | 31.945946 | 19.027027 |
def _getFieldStats(self):
"""
Method which returns a dictionary of field statistics received from the
input source.
Returns:
fieldStats: dict of dicts where the first level is the field name and
the second level is the statistic. ie. fieldStats['pounds']['min']
"""
fieldStats =... | [
"def",
"_getFieldStats",
"(",
"self",
")",
":",
"fieldStats",
"=",
"dict",
"(",
")",
"fieldNames",
"=",
"self",
".",
"_inputSource",
".",
"getFieldNames",
"(",
")",
"for",
"field",
"in",
"fieldNames",
":",
"curStats",
"=",
"dict",
"(",
")",
"curStats",
"... | 29.55 | 22.55 |
def make_table(grid):
""" Make a RST-compatible table
From http://stackoverflow.com/a/12539081
"""
cell_width = 2 + max(
reduce(
lambda x, y: x+y, [[len(item) for item in row] for row in grid], []
)
)
num_cols = len(grid[0])
rst = table_div(num_cols, cell_width,... | [
"def",
"make_table",
"(",
"grid",
")",
":",
"cell_width",
"=",
"2",
"+",
"max",
"(",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"+",
"y",
",",
"[",
"[",
"len",
"(",
"item",
")",
"for",
"item",
"in",
"row",
"]",
"for",
"row",
"in",
"gri... | 26.809524 | 19.857143 |
def save_group(self, group):
""" Group was saved. """
# If group already exists, take over existing group rather then error.
try:
lgroup = self._get_group(group.name)
changes = changeset(lgroup, {})
except ObjectDoesNotExist:
lgroup = self._group_class... | [
"def",
"save_group",
"(",
"self",
",",
"group",
")",
":",
"# If group already exists, take over existing group rather then error.",
"try",
":",
"lgroup",
"=",
"self",
".",
"_get_group",
"(",
"group",
".",
"name",
")",
"changes",
"=",
"changeset",
"(",
"lgroup",
",... | 33.5 | 13.5 |
def update(self, feedforwardInputI, feedforwardInputE, v, recurrent=True,
envelope=False, iSpeedTuning=False, enforceDale=True):
"""
Do one update of the CAN network, of length self.dt.
:param feedforwardInputI: The feedforward input to inhibitory cells.
:param feedforwardInputR: The feedfo... | [
"def",
"update",
"(",
"self",
",",
"feedforwardInputI",
",",
"feedforwardInputE",
",",
"v",
",",
"recurrent",
"=",
"True",
",",
"envelope",
"=",
"False",
",",
"iSpeedTuning",
"=",
"False",
",",
"enforceDale",
"=",
"True",
")",
":",
"self",
".",
"instantane... | 44.054054 | 22.378378 |
def stop(self):
'''Stop the rpc server.'''
if self.uiautomator_process and self.uiautomator_process.poll() is None:
res = None
try:
res = urllib2.urlopen(self.stop_uri)
self.uiautomator_process.wait()
except:
self.uiauto... | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"uiautomator_process",
"and",
"self",
".",
"uiautomator_process",
".",
"poll",
"(",
")",
"is",
"None",
":",
"res",
"=",
"None",
"try",
":",
"res",
"=",
"urllib2",
".",
"urlopen",
"(",
"self",
"... | 39.545455 | 20.454545 |
def index_in_tree(self, cmd_path):
"""
Return the start index of which the element is not in cmd tree.
:type cmd_path: list or tuple
:return: None if cmd_path already indexed in tree.
"""
current_tree = self.tree
for key in cmd_path:
if key in current_... | [
"def",
"index_in_tree",
"(",
"self",
",",
"cmd_path",
")",
":",
"current_tree",
"=",
"self",
".",
"tree",
"for",
"key",
"in",
"cmd_path",
":",
"if",
"key",
"in",
"current_tree",
"[",
"'children'",
"]",
":",
"current_tree",
"=",
"current_tree",
"[",
"'child... | 35.923077 | 11.615385 |
def extract_time_info(text):
"""
Extract valid time(-range) information from a string according to our specs.
Args:
text (text_type): Raw string containing encoded time(-span) information.
Date/Time-combinations are expected in a ``YYYY-MM-DD hh:mm`` format.
Relative times ... | [
"def",
"extract_time_info",
"(",
"text",
")",
":",
"# [TODO] Add a list of supported formats.",
"def",
"get_time",
"(",
"time",
",",
"seconds",
"=",
"None",
")",
":",
"\"\"\"Convert a times string representation to datetime.time instance.\"\"\"",
"if",
"time",
"is",
"None",... | 36.754902 | 22.617647 |
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.h... | [
"def",
"hexists",
"(",
"key",
",",
"field",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
... | 23.214286 | 23.357143 |
def findPrev( self ):
"""
Looks for the previous occurance of the current search text.
"""
text = self.uiFindTXT.text()
view = self.currentWebView()
options = QWebPage.FindWrapsAroundDocument
options |= QWebPage.FindBackward
if... | [
"def",
"findPrev",
"(",
"self",
")",
":",
"text",
"=",
"self",
".",
"uiFindTXT",
".",
"text",
"(",
")",
"view",
"=",
"self",
".",
"currentWebView",
"(",
")",
"options",
"=",
"QWebPage",
".",
"FindWrapsAroundDocument",
"options",
"|=",
"QWebPage",
".",
"F... | 32.571429 | 13.285714 |
def tilequeue_tile_status(cfg, peripherals, args):
"""
Report the status of the given tiles in the store, queue and TOI.
"""
logger = make_logger(cfg, 'tile_status')
# friendly warning to avoid confusion when this command outputs nothing
# at all when called with no positional arguments.
if... | [
"def",
"tilequeue_tile_status",
"(",
"cfg",
",",
"peripherals",
",",
"args",
")",
":",
"logger",
"=",
"make_logger",
"(",
"cfg",
",",
"'tile_status'",
")",
"# friendly warning to avoid confusion when this command outputs nothing",
"# at all when called with no positional argume... | 33.745098 | 20.607843 |
def update_deps( self ):
"""Update dependencies on all the fields on this Block instance."""
klass = self.__class__
for name in klass._fields:
self.update_deps_on_field( name )
return | [
"def",
"update_deps",
"(",
"self",
")",
":",
"klass",
"=",
"self",
".",
"__class__",
"for",
"name",
"in",
"klass",
".",
"_fields",
":",
"self",
".",
"update_deps_on_field",
"(",
"name",
")",
"return"
] | 31.714286 | 14.714286 |
def parseAttributes(self, attributes=None, **kwAttributes):
"""Parses CSS attribute source strings, and return as an inline stylesheet.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseSingleAttr
"""
attributes = attributes if attributes is not None e... | [
"def",
"parseAttributes",
"(",
"self",
",",
"attributes",
"=",
"None",
",",
"*",
"*",
"kwAttributes",
")",
":",
"attributes",
"=",
"attributes",
"if",
"attributes",
"is",
"not",
"None",
"else",
"{",
"}",
"if",
"attributes",
":",
"kwAttributes",
".",
"updat... | 35.923077 | 19.692308 |
def resource_group_absent(name, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a resource group does not exist in the current subscription.
:param name:
Name of the resource group.
:param connection_auth:
A dict with subscription and authentication parameters to be u... | [
"def",
"resource_group_absent",
"(",
"name",
",",
"connection_auth",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"if",
"not",
"isinstan... | 29.349206 | 28.746032 |
def render(self, **kwargs):
""" Plots the surface and the control points grid. """
# Calling parent function
super(VisSurface, self).render(**kwargs)
# Initialize a list to store VTK actors
vtk_actors = []
# Start plotting
for plot in self._plots:
# ... | [
"def",
"render",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Calling parent function",
"super",
"(",
"VisSurface",
",",
"self",
")",
".",
"render",
"(",
"*",
"*",
"kwargs",
")",
"# Initialize a list to store VTK actors",
"vtk_actors",
"=",
"[",
"]",
"... | 53.529412 | 25.568627 |
def generate_account(self, services, resource_types, permission, expiry, start=None,
ip=None, protocol=None):
'''
Generates a shared access signature for the account.
Use the returned signature with the sas_token parameter of the service
or to create a new accou... | [
"def",
"generate_account",
"(",
"self",
",",
"services",
",",
"resource_types",
",",
"permission",
",",
"expiry",
",",
"start",
"=",
"None",
",",
"ip",
"=",
"None",
",",
"protocol",
"=",
"None",
")",
":",
"sas",
"=",
"_SharedAccessHelper",
"(",
")",
"sas... | 58.269231 | 28.846154 |
def ip_interfaces():
'''
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
'''
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for fa... | [
"def",
"ip_interfaces",
"(",
")",
":",
"# Provides:",
"# ip_interfaces",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_proxy",
"(",
")",
":",
"return",
"{",
"}",
"ret",
"=",
"{",
"}",
"ifaces",
"=",
"_get_interfaces",
"(",
")",
"for",
"face",
... | 31.461538 | 17.769231 |
def calc_next_run(self):
"""Calculate next run time of this task"""
base_time = self.last_run
if self.last_run == HAS_NOT_RUN:
if self.wait_for_schedule is False:
self.next_run = timezone.now()
self.wait_for_schedule = False # reset so we don't run on ... | [
"def",
"calc_next_run",
"(",
"self",
")",
":",
"base_time",
"=",
"self",
".",
"last_run",
"if",
"self",
".",
"last_run",
"==",
"HAS_NOT_RUN",
":",
"if",
"self",
".",
"wait_for_schedule",
"is",
"False",
":",
"self",
".",
"next_run",
"=",
"timezone",
".",
... | 41.076923 | 15.384615 |
def _run_mplp(self, no_iterations):
"""
Updates messages until either Mplp converges or if doesn't converges; halts after no_iterations.
Parameters
--------
no_iterations: integer
Number of maximum iterations that we want MPLP to run.
"""
... | [
"def",
"_run_mplp",
"(",
"self",
",",
"no_iterations",
")",
":",
"for",
"niter",
"in",
"range",
"(",
"no_iterations",
")",
":",
"# We take the clusters in the order they were added in the model and update messages for all factors whose",
"# scope is greater than 1",
"for",
"fac... | 49.4 | 25.3 |
def createqtconf():
"""Create a qt.conf file next to the current executable"""
template = """[Paths]
Prefix = {path}
Binaries = {path}
"""
import PyQt5
exedir = os.path.dirname(sys.executable)
qtpath = os.path.join(exedir, "qt.conf")
pyqt5path = os.path.abspath(PyQt5.__file__)
binpath = o... | [
"def",
"createqtconf",
"(",
")",
":",
"template",
"=",
"\"\"\"[Paths]\nPrefix = {path}\nBinaries = {path}\n\"\"\"",
"import",
"PyQt5",
"exedir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"sys",
".",
"executable",
")",
"qtpath",
"=",
"os",
".",
"path",
".",
... | 23.4 | 19.5 |
def generate_warning_text(self):
"""
generates warnings for the current specimen then adds them to the
current warning text for the GUI which will be rendered on a call to
update_warning_box.
"""
self.warning_text = ""
if self.s in list(self.pmag_results_data['spe... | [
"def",
"generate_warning_text",
"(",
"self",
")",
":",
"self",
".",
"warning_text",
"=",
"\"\"",
"if",
"self",
".",
"s",
"in",
"list",
"(",
"self",
".",
"pmag_results_data",
"[",
"'specimens'",
"]",
".",
"keys",
"(",
")",
")",
":",
"for",
"fit",
"in",
... | 62.816667 | 29.35 |
def _euler_to_dcm(self, euler):
"""
Create DCM (Matrix3) from euler angles
:param euler: array [roll, pitch, yaw] in rad
:returns: Matrix3
"""
assert(len(euler) == 3)
m = Matrix3()
m.from_euler(*euler)
return m | [
"def",
"_euler_to_dcm",
"(",
"self",
",",
"euler",
")",
":",
"assert",
"(",
"len",
"(",
"euler",
")",
"==",
"3",
")",
"m",
"=",
"Matrix3",
"(",
")",
"m",
".",
"from_euler",
"(",
"*",
"euler",
")",
"return",
"m"
] | 27.3 | 10.7 |
def _GetTimeElementsTuple(self, structure):
"""Retrieves a time elements tuple from the structure.
Args:
structure (pyparsing.ParseResults): structure of tokens derived from
a line of a text file.
Returns:
tuple: containing:
year (int): year.
month (int): month, where... | [
"def",
"_GetTimeElementsTuple",
"(",
"self",
",",
"structure",
")",
":",
"month",
",",
"day",
",",
"hours",
",",
"minutes",
",",
"seconds",
"=",
"structure",
".",
"date_time",
"# Note that dfdatetime_time_elements.TimeElements will raise ValueError",
"# for an invalid mon... | 33.111111 | 20.481481 |
def content():
"""Helper method that returns just the content.
This method was added so that the text could be reused in the
dock_help module.
.. versionadded:: 3.2.2
:returns: A message object without brand element.
:rtype: safe.messaging.message.Message
"""
message = m.Message()
... | [
"def",
"content",
"(",
")",
":",
"message",
"=",
"m",
".",
"Message",
"(",
")",
"paragraph",
"=",
"m",
".",
"Paragraph",
"(",
"m",
".",
"Image",
"(",
"'file:///%s/img/screenshots/'",
"'shakemap-converter-screenshot.png'",
"%",
"resources_path",
"(",
")",
")",
... | 32.744186 | 22.744186 |
def update(self, access_token=None, id_token=None, id_token_jwt=None, userinfo=None):
"""
Args:
access_token (str)
id_token (Mapping[str, str])
id_token_jwt (str)
userinfo (Mapping[str, str])
"""
def set_if_defined(session_key, value):
... | [
"def",
"update",
"(",
"self",
",",
"access_token",
"=",
"None",
",",
"id_token",
"=",
"None",
",",
"id_token_jwt",
"=",
"None",
",",
"userinfo",
"=",
"None",
")",
":",
"def",
"set_if_defined",
"(",
"session_key",
",",
"value",
")",
":",
"if",
"value",
... | 34.409091 | 16.136364 |
def is_entailed_by(self, other):
"""
Whether all of self's keys (and values) are in (and within) other's
"""
for (s_key, s_val) in self:
if s_key in other:
if not other[s_key].entails(s_val):
return False
else:
r... | [
"def",
"is_entailed_by",
"(",
"self",
",",
"other",
")",
":",
"for",
"(",
"s_key",
",",
"s_val",
")",
"in",
"self",
":",
"if",
"s_key",
"in",
"other",
":",
"if",
"not",
"other",
"[",
"s_key",
"]",
".",
"entails",
"(",
"s_val",
")",
":",
"return",
... | 31 | 12.090909 |
def _find_udf_record(self, udf_path):
# type: (bytes) -> Tuple[Optional[udfmod.UDFFileIdentifierDescriptor], udfmod.UDFFileEntry]
'''
An internal method to find an directory record on the ISO given a UDF
path. If the entry is found, it returns the directory record object
corresp... | [
"def",
"_find_udf_record",
"(",
"self",
",",
"udf_path",
")",
":",
"# type: (bytes) -> Tuple[Optional[udfmod.UDFFileIdentifierDescriptor], udfmod.UDFFileEntry]",
"# If the path is just the slash, we just want the root directory, so",
"# get the child there and quit.",
"if",
"udf_path",
"==... | 36.333333 | 23 |
def log(stats_resource=None, stats_source=None, log_level=DEFAULT_LOG_LEVEL,
**kwargs):
"""Utility to log given stats to *stats* logger.
Stats to log are given by `stats_source` and in its absence we log
`kwargs`. *stats* logger is configured independently from any logger.
Only stats should be ... | [
"def",
"log",
"(",
"stats_resource",
"=",
"None",
",",
"stats_source",
"=",
"None",
",",
"log_level",
"=",
"DEFAULT_LOG_LEVEL",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get stats from source if given.",
"if",
"stats_source",
"is",
"not",
"None",
":",
"kwargs",
"=... | 39.9 | 21.675 |
def reverse_compl_with_name(old_seq):
"""Reverse a SeqIO sequence, but keep its name intact."""
new_seq = old_seq.reverse_complement()
new_seq.id = old_seq.id
new_seq.description = old_seq.description
return new_seq | [
"def",
"reverse_compl_with_name",
"(",
"old_seq",
")",
":",
"new_seq",
"=",
"old_seq",
".",
"reverse_complement",
"(",
")",
"new_seq",
".",
"id",
"=",
"old_seq",
".",
"id",
"new_seq",
".",
"description",
"=",
"old_seq",
".",
"description",
"return",
"new_seq"
... | 38.333333 | 7.5 |
def load_rml(self, rml_name):
""" loads an rml mapping into memory
args:
rml_name(str): the name of the rml file
"""
conn = CFG.rml_tstore
cache_path = os.path.join(CFG.CACHE_DATA_PATH, 'rml_files', rml_name)
if not os.path.exists(cache_path):
res... | [
"def",
"load_rml",
"(",
"self",
",",
"rml_name",
")",
":",
"conn",
"=",
"CFG",
".",
"rml_tstore",
"cache_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"CFG",
".",
"CACHE_DATA_PATH",
",",
"'rml_files'",
",",
"rml_name",
")",
"if",
"not",
"os",
".",
... | 39.470588 | 15.764706 |
def updateTimeline(self, time, state='stopped', duration=None):
""" Set the timeline progress for this video.
Parameters:
time (int): milliseconds watched
state (string): state of the video, default 'stopped'
duration (int): duration of the item
... | [
"def",
"updateTimeline",
"(",
"self",
",",
"time",
",",
"state",
"=",
"'stopped'",
",",
"duration",
"=",
"None",
")",
":",
"durationStr",
"=",
"'&duration='",
"if",
"duration",
"is",
"not",
"None",
":",
"durationStr",
"=",
"durationStr",
"+",
"str",
"(",
... | 43.117647 | 18.882353 |
def _generate_struct_cstor_signature(self, struct):
"""Emits struct standard constructor signature to be used in the struct's header file."""
fields = struct.all_fields
self.emit(comment_prefix)
description_str = 'Full constructor for the struct (exposes all instance variables).'
... | [
"def",
"_generate_struct_cstor_signature",
"(",
"self",
",",
"struct",
")",
":",
"fields",
"=",
"struct",
".",
"all_fields",
"self",
".",
"emit",
"(",
"comment_prefix",
")",
"description_str",
"=",
"'Full constructor for the struct (exposes all instance variables).'",
"se... | 46.68 | 14.48 |
def materials(self):
"""
Property for accessing :class:`MaterialManager` instance, which is used to manage materials.
:rtype: yagocd.resources.material.MaterialManager
"""
if self._material_manager is None:
self._material_manager = MaterialManager(session=self._sessi... | [
"def",
"materials",
"(",
"self",
")",
":",
"if",
"self",
".",
"_material_manager",
"is",
"None",
":",
"self",
".",
"_material_manager",
"=",
"MaterialManager",
"(",
"session",
"=",
"self",
".",
"_session",
")",
"return",
"self",
".",
"_material_manager"
] | 39.222222 | 19.666667 |
def setup_interpolant(self):
"""Initializes the z(d) interpolation."""
# for computing nearby (z < 1) redshifts
zs = numpy.linspace(0., 1., num=self.numpoints)
ds = self.cosmology.luminosity_distance(zs).value
self.nearby_d2z = interpolate.interp1d(ds, zs, kind='linear',
... | [
"def",
"setup_interpolant",
"(",
"self",
")",
":",
"# for computing nearby (z < 1) redshifts",
"zs",
"=",
"numpy",
".",
"linspace",
"(",
"0.",
",",
"1.",
",",
"num",
"=",
"self",
".",
"numpoints",
")",
"ds",
"=",
"self",
".",
"cosmology",
".",
"luminosity_di... | 54 | 15.133333 |
def post(self, request, bot_id, format=None):
"""
Add a new environment variable
---
serializer: EnvironmentVarSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
""... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"bot_id",
",",
"format",
"=",
"None",
")",
":",
"return",
"super",
"(",
"EnvironmentVarList",
",",
"self",
")",
".",
"post",
"(",
"request",
",",
"bot_id",
",",
"format",
")"
] | 32.25 | 10.416667 |
def resizeEvent(self, event):
"""Mark repaint needed. :qtdoc:`Re-implemented<QWidget.resizeEvent>`"""
self._viewIsDirty = True
super(StimulusView, self).resizeEvent(event) | [
"def",
"resizeEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"_viewIsDirty",
"=",
"True",
"super",
"(",
"StimulusView",
",",
"self",
")",
".",
"resizeEvent",
"(",
"event",
")"
] | 48 | 7.75 |
def iterable(self, iterable_name, *, collection, attribute, word, func=None,
operation=None):
""" Performs a filter with the OData 'iterable_name' keyword
on the collection
For example:
q.iterable('any', collection='email_addresses', attribute='address',
operati... | [
"def",
"iterable",
"(",
"self",
",",
"iterable_name",
",",
"*",
",",
"collection",
",",
"attribute",
",",
"word",
",",
"func",
"=",
"None",
",",
"operation",
"=",
"None",
")",
":",
"if",
"func",
"is",
"None",
"and",
"operation",
"is",
"None",
":",
"r... | 37.469388 | 22.469388 |
def increment_day_start_ut(self, day_start_ut, n_days=1):
"""Increment the GTFS-definition of "day start".
Parameters
----------
day_start_ut : int
unixtime of the previous start of day. If this time is between
12:00 or greater, there *will* be bugs. To solve t... | [
"def",
"increment_day_start_ut",
"(",
"self",
",",
"day_start_ut",
",",
"n_days",
"=",
"1",
")",
":",
"old_tz",
"=",
"self",
".",
"set_current_process_time_zone",
"(",
")",
"day0",
"=",
"time",
".",
"localtime",
"(",
"day_start_ut",
"+",
"43200",
")",
"# tim... | 42.368421 | 18.315789 |
def woa_track_from_file(d, lat, lon, filename, varnames=None):
""" Temporary solution: WOA for surface track
"""
d = np.asanyarray(d)
lat = np.asanyarray(lat)
lon = np.asanyarray(lon)
lon[lon < 0] += 360
doy = np.array([int(dd.strftime('%j')) for dd in d])
nc = netCDF4.Dataset(expandu... | [
"def",
"woa_track_from_file",
"(",
"d",
",",
"lat",
",",
"lon",
",",
"filename",
",",
"varnames",
"=",
"None",
")",
":",
"d",
"=",
"np",
".",
"asanyarray",
"(",
"d",
")",
"lat",
"=",
"np",
".",
"asanyarray",
"(",
"lat",
")",
"lon",
"=",
"np",
"."... | 29.405405 | 20.972973 |
def stop(self):
"""
Stop the monitoring thread of the plugin.
The super-class will send the stop signal on the monitor-IP queue,
which prompts the loop to stop.
"""
super(Tcp, self).stop()
self.monitor_thread.join()
logging.info("TCP health monitor plugi... | [
"def",
"stop",
"(",
"self",
")",
":",
"super",
"(",
"Tcp",
",",
"self",
")",
".",
"stop",
"(",
")",
"self",
".",
"monitor_thread",
".",
"join",
"(",
")",
"logging",
".",
"info",
"(",
"\"TCP health monitor plugin: Stopped\"",
")"
] | 29.272727 | 16.545455 |
def addvPPfunc(self,solution):
'''
Adds the marginal marginal value function to an existing solution, so
that the next solver can evaluate vPP and thus use cubic interpolation.
Parameters
----------
solution : ConsumerSolution
The solution to this single peri... | [
"def",
"addvPPfunc",
"(",
"self",
",",
"solution",
")",
":",
"vPPfuncNow",
"=",
"MargMargValueFunc",
"(",
"solution",
".",
"cFunc",
",",
"self",
".",
"CRRA",
")",
"solution",
".",
"vPPfunc",
"=",
"vPPfuncNow",
"return",
"solution"
] | 36.9 | 24.7 |
def get_user_metadata(
self,
bucket: str,
key: str
) -> typing.Dict[str, str]:
"""
Retrieves the user metadata for a given object in a given bucket. If the platform has any mandatory prefixes or
suffixes for the metadata keys, they should be stripped befo... | [
"def",
"get_user_metadata",
"(",
"self",
",",
"bucket",
":",
"str",
",",
"key",
":",
"str",
")",
"->",
"typing",
".",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"try",
":",
"response",
"=",
"self",
".",
"get_all_metadata",
"(",
"bucket",
",",
"key",
... | 40.096774 | 20.354839 |
def add_fields(self, *args):
"""
This method only works for extensible fields. It allows to add values without precising their fields' names
or indexes.
Parameters
----------
args: field values
"""
if not self.is_extensible():
raise TypeError(... | [
"def",
"add_fields",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"not",
"self",
".",
"is_extensible",
"(",
")",
":",
"raise",
"TypeError",
"(",
"\"Can't use add_fields on a non extensible record.\"",
")",
"# prepare update data",
"self_len",
"=",
"len",
"(",
... | 29.5 | 23.5 |
def _compute(self, inputs, dates, assets, mask):
"""
Compute by delegating to self._wrapped_term._compute on sample dates.
On non-sample dates, forward-fill from previously-computed samples.
"""
to_sample = dates[select_sampling_indices(dates, self._frequency)]
assert to... | [
"def",
"_compute",
"(",
"self",
",",
"inputs",
",",
"dates",
",",
"assets",
",",
"mask",
")",
":",
"to_sample",
"=",
"dates",
"[",
"select_sampling_indices",
"(",
"dates",
",",
"self",
".",
"_frequency",
")",
"]",
"assert",
"to_sample",
"[",
"0",
"]",
... | 40.333333 | 20.025641 |
def plot_oneD(dataset, vars, filename, bins=60):
""" Plot 1D marginalised posteriors for the 'vars' of interest."""
n = len(vars)
fig, axes = plt.subplots(nrows=n,
ncols=1,
sharex=False,
sharey=False)
for i, x in en... | [
"def",
"plot_oneD",
"(",
"dataset",
",",
"vars",
",",
"filename",
",",
"bins",
"=",
"60",
")",
":",
"n",
"=",
"len",
"(",
"vars",
")",
"fig",
",",
"axes",
"=",
"plt",
".",
"subplots",
"(",
"nrows",
"=",
"n",
",",
"ncols",
"=",
"1",
",",
"sharex... | 31.684211 | 16.210526 |
def add_iterative_predicate(self, key, values_list):
"""add an iterative predicate with a key and set of values
which it can be equal to in and or function.
The individual predicates are specified with the type ``equals`` and
combined with a type ``or``.
The main reason for this... | [
"def",
"add_iterative_predicate",
"(",
"self",
",",
"key",
",",
"values_list",
")",
":",
"values",
"=",
"self",
".",
"_extract_values",
"(",
"values_list",
")",
"predicate",
"=",
"{",
"'type'",
":",
"'equals'",
",",
"'key'",
":",
"key",
",",
"'value'",
":"... | 41.347826 | 20.521739 |
def get_power(self):
"""Returns the Power in Watt"""
power_dict = self.get_power_all()
for device in power_dict.keys():
power_dict[device] = float(power_dict[device]) / 1000.0
return power_dict | [
"def",
"get_power",
"(",
"self",
")",
":",
"power_dict",
"=",
"self",
".",
"get_power_all",
"(",
")",
"for",
"device",
"in",
"power_dict",
".",
"keys",
"(",
")",
":",
"power_dict",
"[",
"device",
"]",
"=",
"float",
"(",
"power_dict",
"[",
"device",
"]"... | 38.666667 | 10.5 |
def confirmation_option(*param_decls, **attrs):
"""Shortcut for confirmation prompts that can be ignored by passing
``--yes`` as parameter.
This is equivalent to decorating a function with :func:`option` with
the following parameters::
def callback(ctx, param, value):
if not value:... | [
"def",
"confirmation_option",
"(",
"*",
"param_decls",
",",
"*",
"*",
"attrs",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"def",
"callback",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"ctx",
".",
"abort",
"(... | 36.107143 | 17.392857 |
def get_data(self, create=False):
"""Get dict stored for current running task. Return `None`
or an empty dict if no data was found depending on the
`create` argument value.
:param create: if argument is `True`, create empty dict
for task, default: `False`
... | [
"def",
"get_data",
"(",
"self",
",",
"create",
"=",
"False",
")",
":",
"task",
"=",
"asyncio_current_task",
"(",
"loop",
"=",
"self",
".",
"loop",
")",
"if",
"task",
":",
"task_id",
"=",
"id",
"(",
"task",
")",
"if",
"create",
"and",
"task_id",
"not"... | 38.5 | 12.5625 |
def calc_across_paths_textnodes(paths_nodes, dbg=False):
"""Given a list of parent paths tupled with children textnodes, plus
initialized feature values, we calculate the total and average string
length of the parent's children textnodes.
"""
# for (path, [textnodes],
# num. of... | [
"def",
"calc_across_paths_textnodes",
"(",
"paths_nodes",
",",
"dbg",
"=",
"False",
")",
":",
"# for (path, [textnodes],\r",
"# num. of tnodes,\r",
"# ttl strlen across tnodes,\r",
"# avg strlen across tnodes.])\r",
"for",
"path_nodes",
"in",
"paths_no... | 44.5 | 15.333333 |
def add_statement(self,statement_obj):
"""
Adds a statement to the attribution layer
@type statement_obj: L{Cstatement}
@param statement_obj: the statement object
"""
if self.attribution_layer is None:
self.attribution_layer = Cattribution()
self.r... | [
"def",
"add_statement",
"(",
"self",
",",
"statement_obj",
")",
":",
"if",
"self",
".",
"attribution_layer",
"is",
"None",
":",
"self",
".",
"attribution_layer",
"=",
"Cattribution",
"(",
")",
"self",
".",
"root",
".",
"append",
"(",
"self",
".",
"attribut... | 41.6 | 7.8 |
def after(self, value):
"""
Sets the operator type to Query.Op.After and sets the value to
the amount that this query should be lower than. This is functionally
the same as doing the lessThan operation, but is useful for visual
queries for things like dates.
:p... | [
"def",
"after",
"(",
"self",
",",
"value",
")",
":",
"newq",
"=",
"self",
".",
"copy",
"(",
")",
"newq",
".",
"setOp",
"(",
"Query",
".",
"Op",
".",
"After",
")",
"newq",
".",
"setValue",
"(",
"value",
")",
"return",
"newq"
] | 35.2 | 16.7 |
def fatal(*tokens: Token, **kwargs: Any) -> None:
""" Print an error message and call ``sys.exit`` """
error(*tokens, **kwargs)
sys.exit(1) | [
"def",
"fatal",
"(",
"*",
"tokens",
":",
"Token",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"error",
"(",
"*",
"tokens",
",",
"*",
"*",
"kwargs",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | 37 | 11.5 |
def setActiveWindow(self, win):
"""
Set the given window active (property _NET_ACTIVE_WINDOW)
:param win: the window object"""
self._setProperty('_NET_ACTIVE_WINDOW', [1, X.CurrentTime, win.id],
win) | [
"def",
"setActiveWindow",
"(",
"self",
",",
"win",
")",
":",
"self",
".",
"_setProperty",
"(",
"'_NET_ACTIVE_WINDOW'",
",",
"[",
"1",
",",
"X",
".",
"CurrentTime",
",",
"win",
".",
"id",
"]",
",",
"win",
")"
] | 36 | 17 |
def subclass(self, klass):
"""True if the Class is a subclass of the given one."""
return bool(lib.EnvSubclassP(self._env, self._cls, klass._cls)) | [
"def",
"subclass",
"(",
"self",
",",
"klass",
")",
":",
"return",
"bool",
"(",
"lib",
".",
"EnvSubclassP",
"(",
"self",
".",
"_env",
",",
"self",
".",
"_cls",
",",
"klass",
".",
"_cls",
")",
")"
] | 53.333333 | 15 |
def tiny(x):
'''Compute the tiny-value corresponding to an input's data type.
This is the smallest "usable" number representable in `x`'s
data type (e.g., float32).
This is primarily useful for determining a threshold for
numerical underflow in division or multiplication operations.
Parameter... | [
"def",
"tiny",
"(",
"x",
")",
":",
"# Make sure we have an array view",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"# Only floating types generate a tiny",
"if",
"np",
".",
"issubdtype",
"(",
"x",
".",
"dtype",
",",
"np",
".",
"floating",
")",
"or",
"n... | 22.846154 | 25.461538 |
def list_scheduled_queries(self):
"""
List all scheduled_queries
:return: A list of all scheduled query dicts
:rtype: list of dict
:raises: This will raise a
:class:`ServerException<logentries_api.exceptions.ServerException>`
if there is an error from Lo... | [
"def",
"list_scheduled_queries",
"(",
"self",
")",
":",
"url",
"=",
"'https://logentries.com/rest/{account_id}/api/scheduled_queries/'",
".",
"format",
"(",
"account_id",
"=",
"self",
".",
"account_id",
")",
"return",
"self",
".",
"_api_get",
"(",
"url",
"=",
"url",... | 37.071429 | 17.214286 |
def get_unit_from_dimensions(dimensions, text):
"""Reconcile a unit based on its dimensionality."""
key = l.get_key_from_dimensions(dimensions)
try:
unit = l.DERIVED_UNI[key]
except KeyError:
logging.debug(u'\tCould not find unit for: %s', key)
unit = c.Unit(name=build_unit_name... | [
"def",
"get_unit_from_dimensions",
"(",
"dimensions",
",",
"text",
")",
":",
"key",
"=",
"l",
".",
"get_key_from_dimensions",
"(",
"dimensions",
")",
"try",
":",
"unit",
"=",
"l",
".",
"DERIVED_UNI",
"[",
"key",
"]",
"except",
"KeyError",
":",
"logging",
"... | 35.230769 | 19.307692 |
def handle(self, data, **kwargs):
"""Run marshalling for the specified mapper_class.
Supports both .marshal and .many().marshal Kim interfaces. Handles errors raised
during marshalling and automatically returns a HTTP error response.
:param data: Data to be marshaled.
:returns... | [
"def",
"handle",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"if",
"self",
".",
"many",
":",
"return",
"self",
".",
"mapper",
".",
"many",
"(",
"raw",
"=",
"self",
".",
"raw",
",",
"*",
"*",
"self",
".",
"mapper_kwa... | 38.458333 | 16.5 |
def merge_rdf_list(rdf_list):
""" takes an rdf list and merges it into a python list
args:
rdf_list: the RdfDataset object with the list values
returns:
list of values
"""
# pdb.set_trace()
if isinstance(rdf_list, list):
rdf_list = rdf_list[0]
rtn_list = []
# fo... | [
"def",
"merge_rdf_list",
"(",
"rdf_list",
")",
":",
"# pdb.set_trace()",
"if",
"isinstance",
"(",
"rdf_list",
",",
"list",
")",
":",
"rdf_list",
"=",
"rdf_list",
"[",
"0",
"]",
"rtn_list",
"=",
"[",
"]",
"# for item in rdf_list:",
"item",
"=",
"rdf_list",
"i... | 27.619048 | 18.142857 |
def set_from_template_string(self, string):
"""
Reads the given template (SMTP formatted) and sets all fields
accordingly.
:type string: string
:param string: The template.
"""
in_header = True
body = ''
for line in string.split('\n'):
... | [
"def",
"set_from_template_string",
"(",
"self",
",",
"string",
")",
":",
"in_header",
"=",
"True",
"body",
"=",
"''",
"for",
"line",
"in",
"string",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"not",
"in_header",
":",
"body",
"+=",
"line",
"+",
"'\\n'"... | 32.03125 | 10.84375 |
def delete_resourcegroup(group_id,**kwargs):
"""
Add a new group to a scenario.
"""
group_i = _get_group(group_id)
#This should cascaded to delete all the group items.
db.DBSession.delete(group_i)
db.DBSession.flush()
return 'OK' | [
"def",
"delete_resourcegroup",
"(",
"group_id",
",",
"*",
"*",
"kwargs",
")",
":",
"group_i",
"=",
"_get_group",
"(",
"group_id",
")",
"#This should cascaded to delete all the group items.",
"db",
".",
"DBSession",
".",
"delete",
"(",
"group_i",
")",
"db",
".",
... | 25.7 | 11.7 |
def execute_cmd_direct(self, userid, cmdStr):
""""cmdVM."""
requestData = 'cmdVM ' + userid + ' CMD \'' + cmdStr + '\''
results = self._smt.request(requestData)
return results | [
"def",
"execute_cmd_direct",
"(",
"self",
",",
"userid",
",",
"cmdStr",
")",
":",
"requestData",
"=",
"'cmdVM '",
"+",
"userid",
"+",
"' CMD \\''",
"+",
"cmdStr",
"+",
"'\\''",
"results",
"=",
"self",
".",
"_smt",
".",
"request",
"(",
"requestData",
")",
... | 40.6 | 11.6 |
def find_genome_length(contig_lengths_dict):
"""
Determine the total length of all the contigs for each strain
:param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths
:return: genome_length_dict: dictionary of strain name: total genome length
"""
# Initia... | [
"def",
"find_genome_length",
"(",
"contig_lengths_dict",
")",
":",
"# Initialise the dictionary",
"genome_length_dict",
"=",
"dict",
"(",
")",
"for",
"file_name",
",",
"contig_lengths",
"in",
"contig_lengths_dict",
".",
"items",
"(",
")",
":",
"# Use the sum() method to... | 49.083333 | 19.416667 |
def unnest(self, data, fit=False):
"""
:param data: a dataframe containing a column to be unnested
:param fit: if True, self.sequence_length will exactly accomodate the largest sequence length
:return: 1D array of values with length = rows * sequence_length
"""
with timer... | [
"def",
"unnest",
"(",
"self",
",",
"data",
",",
"fit",
"=",
"False",
")",
":",
"with",
"timer",
"(",
"'unnest %s'",
"%",
"self",
".",
"name",
",",
"logging",
".",
"DEBUG",
")",
":",
"raw",
"=",
"self",
".",
"series",
"(",
"data",
")",
"# lengths of... | 51.76 | 18.96 |
def segment_intersection2(start0, end0, start1, end1):
"""Image for :func:`.segment_intersection` docstring."""
if NO_IMAGES:
return
line0 = bezier.Curve.from_nodes(stack1d(start0, end0))
line1 = bezier.Curve.from_nodes(stack1d(start1, end1))
ax = line0.plot(2)
line1.plot(2, ax=ax)
... | [
"def",
"segment_intersection2",
"(",
"start0",
",",
"end0",
",",
"start1",
",",
"end1",
")",
":",
"if",
"NO_IMAGES",
":",
"return",
"line0",
"=",
"bezier",
".",
"Curve",
".",
"from_nodes",
"(",
"stack1d",
"(",
"start0",
",",
"end0",
")",
")",
"line1",
... | 34.727273 | 18.727273 |
def end_timing(self):
"""
Ends timing of an execution block, calculates elapsed time and updates the associated counter.
"""
if self._callback != None:
elapsed = time.perf_counter() * 1000 - self._start
self._callback.end_timing(self._counter, elapsed) | [
"def",
"end_timing",
"(",
"self",
")",
":",
"if",
"self",
".",
"_callback",
"!=",
"None",
":",
"elapsed",
"=",
"time",
".",
"perf_counter",
"(",
")",
"*",
"1000",
"-",
"self",
".",
"_start",
"self",
".",
"_callback",
".",
"end_timing",
"(",
"self",
"... | 37.75 | 21.25 |
def install(self, update=False):
"""
install conda packages
"""
offline = self.offline or update
self.create_env(offline)
self.install_pkgs(offline)
self.install_pip(offline)
return tuple() | [
"def",
"install",
"(",
"self",
",",
"update",
"=",
"False",
")",
":",
"offline",
"=",
"self",
".",
"offline",
"or",
"update",
"self",
".",
"create_env",
"(",
"offline",
")",
"self",
".",
"install_pkgs",
"(",
"offline",
")",
"self",
".",
"install_pip",
... | 27.222222 | 6.333333 |
def configure_logging(emit_list):
"""Configure logging to send log records to the master."""
if 'sphinx' in sys.modules:
module_base = 'resolwe.flow.executors'
else:
module_base = 'executors'
logging_config = dict(
version=1,
formatters={
'json_formatter': {
... | [
"def",
"configure_logging",
"(",
"emit_list",
")",
":",
"if",
"'sphinx'",
"in",
"sys",
".",
"modules",
":",
"module_base",
"=",
"'resolwe.flow.executors'",
"else",
":",
"module_base",
"=",
"'executors'",
"logging_config",
"=",
"dict",
"(",
"version",
"=",
"1",
... | 27.853659 | 16.585366 |
def render(template, **context):
'''
Render a template with uData frontend specifics
* Theme
'''
theme = current_app.config['THEME']
return render_theme_template(get_theme(theme), template, **context) | [
"def",
"render",
"(",
"template",
",",
"*",
"*",
"context",
")",
":",
"theme",
"=",
"current_app",
".",
"config",
"[",
"'THEME'",
"]",
"return",
"render_theme_template",
"(",
"get_theme",
"(",
"theme",
")",
",",
"template",
",",
"*",
"*",
"context",
")"
... | 27.75 | 22.75 |
def is_arxiv(obj):
"""Return ``True`` if ``obj`` contains an arXiv identifier.
The ``idutils`` library's ``is_arxiv`` function has been
modified here to work with two regular expressions instead
of three and adding a check for valid arxiv categories only"""
arxiv_test = obj.split()
if not arxiv... | [
"def",
"is_arxiv",
"(",
"obj",
")",
":",
"arxiv_test",
"=",
"obj",
".",
"split",
"(",
")",
"if",
"not",
"arxiv_test",
":",
"return",
"False",
"matched_arxiv",
"=",
"(",
"RE_ARXIV_PRE_2007_CLASS",
".",
"match",
"(",
"arxiv_test",
"[",
"0",
"]",
")",
"or",... | 37.173913 | 23.565217 |
def output(self, original_filename):
"""
_filename is not used
Args:
_filename(string)
"""
for contract in self.contracts:
for function in contract.functions + contract.modifiers:
filename = "{}-{}-{}.dot".format(original_filen... | [
"def",
"output",
"(",
"self",
",",
"original_filename",
")",
":",
"for",
"contract",
"in",
"self",
".",
"contracts",
":",
"for",
"function",
"in",
"contract",
".",
"functions",
"+",
"contract",
".",
"modifiers",
":",
"filename",
"=",
"\"{}-{}-{}.dot\"",
".",... | 38.166667 | 16.666667 |
def delete_node(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
if not root: return None
if root.val == key:
if root.left:
# Find the right most leaf of the left sub-tree
left_right_most =... | [
"def",
"delete_node",
"(",
"self",
",",
"root",
",",
"key",
")",
":",
"if",
"not",
"root",
":",
"return",
"None",
"if",
"root",
".",
"val",
"==",
"key",
":",
"if",
"root",
".",
"left",
":",
"# Find the right most leaf of the left sub-tree",
"left_right_most"... | 36.730769 | 16.423077 |
def from_product(cls, iterables, sortorder=None, names=None):
"""
Make a MultiIndex from the cartesian product of multiple iterables.
Parameters
----------
iterables : list / sequence of iterables
Each iterable has unique labels for each level of the index.
s... | [
"def",
"from_product",
"(",
"cls",
",",
"iterables",
",",
"sortorder",
"=",
"None",
",",
"names",
"=",
"None",
")",
":",
"from",
"pandas",
".",
"core",
".",
"arrays",
".",
"categorical",
"import",
"_factorize_from_iterables",
"from",
"pandas",
".",
"core",
... | 38.288889 | 21.311111 |
def modify(board, opts=None):
"""
Reset an existing board using the given options.
:param board: the board to reset
:param opts: dictionary mapping str->Opt
:return: None
"""
opts = get_opts(opts)
if opts['board'] is not None:
board.tiles = _read_tiles_from_string(opts['board'])
... | [
"def",
"modify",
"(",
"board",
",",
"opts",
"=",
"None",
")",
":",
"opts",
"=",
"get_opts",
"(",
"opts",
")",
"if",
"opts",
"[",
"'board'",
"]",
"is",
"not",
"None",
":",
"board",
".",
"tiles",
"=",
"_read_tiles_from_string",
"(",
"opts",
"[",
"'boar... | 37.1875 | 15.8125 |
def set_status(self, status):
"""
Updates the status text
Args:
status (int): The offline/starting/online status of Modis
0: offline, 1: starting, 2: online
"""
text = ""
colour = "#FFFFFF"
if status == 0:
text = "OFFLINE"... | [
"def",
"set_status",
"(",
"self",
",",
"status",
")",
":",
"text",
"=",
"\"\"",
"colour",
"=",
"\"#FFFFFF\"",
"if",
"status",
"==",
"0",
":",
"text",
"=",
"\"OFFLINE\"",
"colour",
"=",
"\"#EF9A9A\"",
"elif",
"status",
"==",
"1",
":",
"text",
"=",
"\"ST... | 25.26087 | 16.304348 |
def _match_derived_terms(self, name):
'''
Returns all (random) terms whose named are derived from the
specified string. For example, 'condition|subject' should match the
terms with names '1|subject', 'condition[T.1]|subject', and so on.
Only works for strings with grouping operat... | [
"def",
"_match_derived_terms",
"(",
"self",
",",
"name",
")",
":",
"if",
"'|'",
"not",
"in",
"name",
":",
"return",
"None",
"patt",
"=",
"r'^([01]+)*[\\s\\+]*([^\\|]+)*\\|(.*)'",
"intcpt",
",",
"pred",
",",
"grpr",
"=",
"re",
".",
"search",
"(",
"patt",
",... | 43.962963 | 26.259259 |
def prune_directory(self):
"""Delete any objects that can be loaded and are expired according to
the current lifetime setting.
A file will be deleted if the following conditions are met:
- The file extension matches :py:meth:`bucketcache.backends.Backend.file_extension`
- The o... | [
"def",
"prune_directory",
"(",
"self",
")",
":",
"glob",
"=",
"'*.{ext}'",
".",
"format",
"(",
"ext",
"=",
"self",
".",
"backend",
".",
"file_extension",
")",
"totalsize",
"=",
"0",
"totalnum",
"=",
"0",
"for",
"f",
"in",
"self",
".",
"_path",
".",
"... | 36.75 | 20.295455 |
def get_browser_datetime(webdriver):
"""
Get the current date/time on the web browser as a Python datetime object.
This date matches 'new Date();' when ran in JavaScript console.
Args:
webdriver: Selenium WebDriver instance
Returns:
datetime - Py... | [
"def",
"get_browser_datetime",
"(",
"webdriver",
")",
":",
"js_stmt",
"=",
"\"\"\"\n var wtf_get_date = new Date();\n return {'month':wtf_get_date.getMonth(), \n 'day':wtf_get_date.getDate(), \n 'year':wtf_get_date.getFullYear(),\n ... | 44.028571 | 17.514286 |
def sunrise_sunset(ephemeris, topos):
"""Build a function of time that returns whether the sun is up.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return ``True`` if the
sun is up, else ``False``.
"""
sun = ephemeris['sun']
... | [
"def",
"sunrise_sunset",
"(",
"ephemeris",
",",
"topos",
")",
":",
"sun",
"=",
"ephemeris",
"[",
"'sun'",
"]",
"topos_at",
"=",
"(",
"ephemeris",
"[",
"'earth'",
"]",
"+",
"topos",
")",
".",
"at",
"def",
"is_sun_up_at",
"(",
"t",
")",
":",
"\"\"\"Retur... | 33.368421 | 19.947368 |
def _import_templates(force=False):
"""Import templates from disk into database
Reads all templates from disk and adds them to the database. By default, any template that has been modified by
the user will not be updated. This can however be changed by setting `force` to `True`, which causes all templates
... | [
"def",
"_import_templates",
"(",
"force",
"=",
"False",
")",
":",
"tmplpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"resource_filename",
"(",
"'cloud_inquisitor'",
",",
"'data'",
")",
",",
"'templates'",
")",
"disk_templates",
"=",
"{",
"f",
":",
"os",... | 38.566667 | 21.766667 |
def adjoint(self):
"""Return the adjoint operator."""
if not self.is_linear:
raise ValueError('operator with nonzero pad_const ({}) is not'
' linear and has no adjoint'
''.format(self.pad_const))
return -PartialDerivative(sel... | [
"def",
"adjoint",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_linear",
":",
"raise",
"ValueError",
"(",
"'operator with nonzero pad_const ({}) is not'",
"' linear and has no adjoint'",
"''",
".",
"format",
"(",
"self",
".",
"pad_const",
")",
")",
"return"... | 46.818182 | 19.727273 |
def subdivide(name, rgstr_stamps=None, save_itrs=SET['SI']):
"""
Induce a new subdivision--a lower level in the timing hierarchy.
Subsequent calls to methods like stamp() operate on this new level.
Notes:
If rgstr_stamps is used, the collection is passed through set() for
uniqueness, an... | [
"def",
"subdivide",
"(",
"name",
",",
"rgstr_stamps",
"=",
"None",
",",
"save_itrs",
"=",
"SET",
"[",
"'SI'",
"]",
")",
":",
"_auto_subdivide",
"(",
"name",
",",
"rgstr_stamps",
",",
"save_itrs",
")",
"f",
".",
"t",
".",
"is_user_subdvsn",
"=",
"True"
] | 47.818182 | 29.636364 |
def _sort_policy(doc):
'''
List-type sub-items in policies don't happen to be order-sensitive, but
compare operations will render them unequal, leading to non-idempotent
state runs. We'll sort any list-type subitems before comparison to reduce
the likelihood of false negatives.
'''
if isins... | [
"def",
"_sort_policy",
"(",
"doc",
")",
":",
"if",
"isinstance",
"(",
"doc",
",",
"list",
")",
":",
"return",
"sorted",
"(",
"[",
"_sort_policy",
"(",
"i",
")",
"for",
"i",
"in",
"doc",
"]",
")",
"elif",
"isinstance",
"(",
"doc",
",",
"(",
"dict",
... | 43.083333 | 23.583333 |
def header_match(cls, header):
'''
Parse the 4-line (320-byte) library member header.
'''
mo = cls.header_re.match(header)
if mo is None:
msg = f'Expected {cls.header_re.pattern!r}, got {header!r}'
raise ValueError(msg)
return {
'name':... | [
"def",
"header_match",
"(",
"cls",
",",
"header",
")",
":",
"mo",
"=",
"cls",
".",
"header_re",
".",
"match",
"(",
"header",
")",
"if",
"mo",
"is",
"None",
":",
"msg",
"=",
"f'Expected {cls.header_re.pattern!r}, got {header!r}'",
"raise",
"ValueError",
"(",
... | 38.5 | 14.944444 |
def view_property( prop ):
"""Wrapper for attributes of a View class which auto-dereferences Refs.
Equivalent to setting a property on the class with the getter wrapped
with property_get(), and the setter wrapped with property_set().
prop
A string containing the name of the class attribute... | [
"def",
"view_property",
"(",
"prop",
")",
":",
"def",
"getter",
"(",
"self",
")",
":",
"return",
"property_get",
"(",
"getattr",
"(",
"self",
",",
"prop",
")",
",",
"self",
".",
"parent",
")",
"def",
"setter",
"(",
"self",
",",
"value",
")",
":",
"... | 34.75 | 23.625 |
def wait_for_process_termination(process, timeout=10):
"""
Wait for a process terminate, and raise asyncio.TimeoutError in case of
timeout.
In theory this can be implemented by just:
yield from asyncio.wait_for(self._iou_process.wait(), timeout=100)
But it's broken before Python 3.4:
http:... | [
"def",
"wait_for_process_termination",
"(",
"process",
",",
"timeout",
"=",
"10",
")",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"5",
")",
":",
"try",
":",
"yield",
"from",
"asyncio",
".",
"wait_for",
"(",
"process",
".",
"wait",
"(",... | 29.666667 | 17.148148 |
def set_id_format(portal, format):
"""Sets the id formatting in setup for the format provided
"""
bs = portal.bika_setup
if 'portal_type' not in format:
return
logger.info("Applying format {} for {}".format(format.get('form', ''),
format.get... | [
"def",
"set_id_format",
"(",
"portal",
",",
"format",
")",
":",
"bs",
"=",
"portal",
".",
"bika_setup",
"if",
"'portal_type'",
"not",
"in",
"format",
":",
"return",
"logger",
".",
"info",
"(",
"\"Applying format {} for {}\"",
".",
"format",
"(",
"format",
".... | 36.055556 | 14.777778 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.