text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def validate_endpoint(ctx, param, value):
"""Validate endpoint."""
try:
config = ctx.obj['config']
except Exception:
return
endpoint = default_endpoint(ctx, param, value)
if endpoint not in config.get('endpoints', {}):
raise click.UsageError('Unknown endpoint: {0}'.format(e... | [
"def",
"validate_endpoint",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"try",
":",
"config",
"=",
"ctx",
".",
"obj",
"[",
"'config'",
"]",
"except",
"Exception",
":",
"return",
"endpoint",
"=",
"default_endpoint",
"(",
"ctx",
",",
"param",
",",
... | 26 | 21.384615 |
def to_hdf5(input):
"""
Convert .xml and .npz files to .hdf5 files.
"""
with performance.Monitor('to_hdf5') as mon:
for input_file in input:
if input_file.endswith('.npz'):
output = convert_npz_hdf5(input_file, input_file[:-3] + 'hdf5')
elif input_file... | [
"def",
"to_hdf5",
"(",
"input",
")",
":",
"with",
"performance",
".",
"Monitor",
"(",
"'to_hdf5'",
")",
"as",
"mon",
":",
"for",
"input_file",
"in",
"input",
":",
"if",
"input_file",
".",
"endswith",
"(",
"'.npz'",
")",
":",
"output",
"=",
"convert_npz_h... | 38 | 15.857143 |
def use(self, algorithm):
"""Change the hash algorithm you gonna use.
"""
algorithm = algorithm.lower()
if algorithm == "md5":
self.default_hash_method = hashlib.md5
elif algorithm == "sha1":
self.default_hash_method = hashlib.sha1
elif algorithm =... | [
"def",
"use",
"(",
"self",
",",
"algorithm",
")",
":",
"algorithm",
"=",
"algorithm",
".",
"lower",
"(",
")",
"if",
"algorithm",
"==",
"\"md5\"",
":",
"self",
".",
"default_hash_method",
"=",
"hashlib",
".",
"md5",
"elif",
"algorithm",
"==",
"\"sha1\"",
... | 44.8 | 13.9 |
def contains_key(self, key):
"""
Determines whether this multimap contains an entry with the key.
**Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations
of __hash__ and __eq__ defined in key's class.**
:param key: (obje... | [
"def",
"contains_key",
"(",
"self",
",",
"key",
")",
":",
"check_not_none",
"(",
"key",
",",
"\"key can't be None\"",
")",
"key_data",
"=",
"self",
".",
"_to_data",
"(",
"key",
")",
"return",
"self",
".",
"_encode_invoke_on_key",
"(",
"multi_map_contains_key_cod... | 48.714286 | 26.428571 |
def compute_k(self, memory_antecedent):
"""Compute key Tensor k.
Args:
memory_antecedent: a Tensor with dimensions
{memory_input_dim} + other_dims
Returns:
a Tensor with dimensions
memory_heads_dims + {key_dim} + other_dims
"""
if self.shared_kv:
raise ValueError("... | [
"def",
"compute_k",
"(",
"self",
",",
"memory_antecedent",
")",
":",
"if",
"self",
".",
"shared_kv",
":",
"raise",
"ValueError",
"(",
"\"compute_k cannot be called with shared_kv\"",
")",
"ret",
"=",
"mtf",
".",
"einsum",
"(",
"[",
"memory_antecedent",
",",
"sel... | 32.882353 | 17.764706 |
def serve_get(self, path, **params):
"""
Find a GET callback for the given HTTP path, call it and return the
results. The callback is called with two arguments, the path used to
match it, and params which include the BaseHTTPRequestHandler instance.
The callback must return a t... | [
"def",
"serve_get",
"(",
"self",
",",
"path",
",",
"*",
"*",
"params",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"None",
"matched",
"=",
"self",
".",
"_match_path",
"(",
"path",
",",
"self",
".",
"get_registrations",
")",
"if",
"matched",
... | 35.73913 | 23.217391 |
def fetch(self):
"""
Returns a tuple of the major version together with the
appropriate SHA and dirty bit (for development version only).
"""
if self._release is not None:
return self
self._release = self.expected_release
if not self.fpath:
... | [
"def",
"fetch",
"(",
"self",
")",
":",
"if",
"self",
".",
"_release",
"is",
"not",
"None",
":",
"return",
"self",
"self",
".",
"_release",
"=",
"self",
".",
"expected_release",
"if",
"not",
"self",
".",
"fpath",
":",
"self",
".",
"_commit",
"=",
"sel... | 30.47619 | 16.857143 |
def get_ip(host):
'''
Return the ip associated with the named host
CLI Example:
.. code-block:: bash
salt '*' hosts.get_ip <hostname>
'''
hosts = _list_hosts()
if not hosts:
return ''
# Look for the op
for addr in hosts:
if host in hosts[addr]:
... | [
"def",
"get_ip",
"(",
"host",
")",
":",
"hosts",
"=",
"_list_hosts",
"(",
")",
"if",
"not",
"hosts",
":",
"return",
"''",
"# Look for the op",
"for",
"addr",
"in",
"hosts",
":",
"if",
"host",
"in",
"hosts",
"[",
"addr",
"]",
":",
"return",
"addr",
"#... | 18.210526 | 22.631579 |
def get(self, label, default=None):
"""
Returns value occupying requested label, default to specified
missing value if not present. Analogous to dict.get
Parameters
----------
label : object
Label value looking for
default : object, optional
... | [
"def",
"get",
"(",
"self",
",",
"label",
",",
"default",
"=",
"None",
")",
":",
"if",
"label",
"in",
"self",
".",
"index",
":",
"loc",
"=",
"self",
".",
"index",
".",
"get_loc",
"(",
"label",
")",
"return",
"self",
".",
"_get_val_at",
"(",
"loc",
... | 26.761905 | 16.190476 |
def kl_reverse(logu, self_normalized=False, name=None):
"""The reverse Kullback-Leibler Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the KL-reverse Csiszar-function is:
```none
f(u) = -log(u) + (u - 1)
`... | [
"def",
"kl_reverse",
"(",
"logu",
",",
"self_normalized",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"\"kl_reverse\"",
",",
"[",
"logu",
"]",
")",
":",
"return",
"ama... | 29.673913 | 28.826087 |
def moderate_model(ParentModel, publication_date_field=None, enable_comments_field=None):
"""
Register a parent model (e.g. ``Blog`` or ``Article``) that should receive comment moderation.
:param ParentModel: The parent model, e.g. a ``Blog`` or ``Article`` model.
:param publication_date_field: The fie... | [
"def",
"moderate_model",
"(",
"ParentModel",
",",
"publication_date_field",
"=",
"None",
",",
"enable_comments_field",
"=",
"None",
")",
":",
"attrs",
"=",
"{",
"'auto_close_field'",
":",
"publication_date_field",
",",
"'auto_moderate_field'",
":",
"publication_date_fie... | 57.705882 | 34.411765 |
def eventFilter(self, object, event):
"""
Filters events for the popup tree widget.
:param object | <QObject>
event | <QEvent>
:retuen <bool> | consumed
"""
edit = self.lineEdit()
if not (object a... | [
"def",
"eventFilter",
"(",
"self",
",",
"object",
",",
"event",
")",
":",
"edit",
"=",
"self",
".",
"lineEdit",
"(",
")",
"if",
"not",
"(",
"object",
"and",
"object",
"==",
"self",
".",
"_treePopupWidget",
")",
":",
"return",
"super",
"(",
"XOrbRecordB... | 34.769231 | 12.666667 |
def process_raw_data(cls, raw_data):
"""Create a new model using raw API response."""
properties = raw_data.get("properties", {})
raw_metadata = raw_data.get("resourceMetadata", None)
if raw_metadata is not None:
metadata = ResourceMetadata.from_raw_data(raw_metadata)
... | [
"def",
"process_raw_data",
"(",
"cls",
",",
"raw_data",
")",
":",
"properties",
"=",
"raw_data",
".",
"get",
"(",
"\"properties\"",
",",
"{",
"}",
")",
"raw_metadata",
"=",
"raw_data",
".",
"get",
"(",
"\"resourceMetadata\"",
",",
"None",
")",
"if",
"raw_m... | 43.4 | 20.333333 |
def create_missing_perms(self):
"""Creates missing perms for datasources, schemas and metrics"""
from superset import db
from superset.models import core as models
logging.info(
'Fetching a set of all perms to lookup which ones are missing')
all_pvs = set()
f... | [
"def",
"create_missing_perms",
"(",
"self",
")",
":",
"from",
"superset",
"import",
"db",
"from",
"superset",
".",
"models",
"import",
"core",
"as",
"models",
"logging",
".",
"info",
"(",
"'Fetching a set of all perms to lookup which ones are missing'",
")",
"all_pvs"... | 43.722222 | 20.777778 |
def to_b58check(self, testnet=False):
""" Generates a Base58Check encoding of this key.
Args:
testnet (bool): True if the key is to be used with
testnet, False otherwise.
Returns:
str: A Base58Check encoded string representing the key.
"""
... | [
"def",
"to_b58check",
"(",
"self",
",",
"testnet",
"=",
"False",
")",
":",
"b",
"=",
"self",
".",
"testnet_bytes",
"if",
"testnet",
"else",
"bytes",
"(",
"self",
")",
"return",
"base58",
".",
"b58encode_check",
"(",
"b",
")"
] | 36.545455 | 14.727273 |
def make_short_chunks_from_unused(
self,min_length,overlap=0,play=0,sl=0,excl_play=0):
"""
Create a chunk that uses up the unused data in the science segment
@param min_length: the unused data must be greater than min_length to make a
chunk.
@param overlap: overlap between chunks in seconds.
... | [
"def",
"make_short_chunks_from_unused",
"(",
"self",
",",
"min_length",
",",
"overlap",
"=",
"0",
",",
"play",
"=",
"0",
",",
"sl",
"=",
"0",
",",
"excl_play",
"=",
"0",
")",
":",
"for",
"seg",
"in",
"self",
".",
"__sci_segs",
":",
"if",
"seg",
".",
... | 45.809524 | 18.380952 |
def fixed_point_density_preserving(points, cells, *args, **kwargs):
"""Idea:
Move interior mesh points into the weighted averages of the circumcenters
of their adjacent cells. If a triangle cell switches orientation in the
process, don't move quite so far.
"""
def get_new_points(mesh):
... | [
"def",
"fixed_point_density_preserving",
"(",
"points",
",",
"cells",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"get_new_points",
"(",
"mesh",
")",
":",
"# Get circumcenters everywhere except at cells adjacent to the boundary;",
"# barycenters there.",
... | 40.85 | 16.2 |
def get_flake8_options(config_dir='.'):
# type: (str) -> List[str]
"""Checks for local config overrides for `flake8`
and add them in the correct `flake8` `options` format.
:param config_dir:
:return: List[str]
"""
if FLAKE8_CONFIG_NAME in os.listdir(config_dir):
flake8_config_path =... | [
"def",
"get_flake8_options",
"(",
"config_dir",
"=",
"'.'",
")",
":",
"# type: (str) -> List[str]",
"if",
"FLAKE8_CONFIG_NAME",
"in",
"os",
".",
"listdir",
"(",
"config_dir",
")",
":",
"flake8_config_path",
"=",
"FLAKE8_CONFIG_NAME",
"else",
":",
"flake8_config_path",... | 31.928571 | 15.928571 |
def _set_virtual(self, key, value):
""" Recursively set or update virtual keys. Do nothing if non-virtual
value is present. """
if key in self and key not in self._virtual_keys:
return # Do nothing for non-virtual keys.
self._virtual_keys.add(key)
if key in self... | [
"def",
"_set_virtual",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"in",
"self",
"and",
"key",
"not",
"in",
"self",
".",
"_virtual_keys",
":",
"return",
"# Do nothing for non-virtual keys.",
"self",
".",
"_virtual_keys",
".",
"add",
"(",
... | 42.583333 | 8.583333 |
def change_logger_levels(logger=None, level=logging.DEBUG):
"""
Go through the logger and handlers and update their levels to the
one specified.
:param logger: logging name or object to modify, defaults to root logger
:param level: logging level to set at (10=Debug, 20=Info, 30=Warn, 40=Error)
... | [
"def",
"change_logger_levels",
"(",
"logger",
"=",
"None",
",",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"if",
"not",
"isinstance",
"(",
"logger",
",",
"logging",
".",
"Logger",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"logger",... | 35.285714 | 18.857143 |
def _flags_changed(self, name, old, new):
"""ensure flags dict is valid"""
for key,value in new.iteritems():
assert len(value) == 2, "Bad flag: %r:%s"%(key,value)
assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s"%(key,value)
assert isinstance(value[1], ba... | [
"def",
"_flags_changed",
"(",
"self",
",",
"name",
",",
"old",
",",
"new",
")",
":",
"for",
"key",
",",
"value",
"in",
"new",
".",
"iteritems",
"(",
")",
":",
"assert",
"len",
"(",
"value",
")",
"==",
"2",
",",
"\"Bad flag: %r:%s\"",
"%",
"(",
"key... | 59.166667 | 19.166667 |
def add_route(self, route):
''' Add a route object, but do not change the :data:`Route.app`
attribute.'''
self.routes.append(route)
self.router.add(route.rule, route.method, route, name=route.name)
if DEBUG: route.prepare() | [
"def",
"add_route",
"(",
"self",
",",
"route",
")",
":",
"self",
".",
"routes",
".",
"append",
"(",
"route",
")",
"self",
".",
"router",
".",
"add",
"(",
"route",
".",
"rule",
",",
"route",
".",
"method",
",",
"route",
",",
"name",
"=",
"route",
... | 43.666667 | 17.666667 |
def file_enumerator(filepath, block_size=10240, *args, **kwargs):
"""Return an enumerator that knows how to read a physical file."""
_LOGGER.debug("Enumerating through archive file: %s", filepath)
def opener(archive_res):
_LOGGER.debug("Opening from file (file_enumerator): %s", filepath)
_... | [
"def",
"file_enumerator",
"(",
"filepath",
",",
"block_size",
"=",
"10240",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Enumerating through archive file: %s\"",
",",
"filepath",
")",
"def",
"opener",
"(",
"archive_res"... | 36.733333 | 22.466667 |
def handle_call(self, frame, argument_list):
"""This method is called when there is the remote possibility
that we ever need to stop in this function."""
fun = frame.f_code.co_name
log.info('Calling: %r' % fun)
init = 'Echo|%s' % dump({
'for':
'__call... | [
"def",
"handle_call",
"(",
"self",
",",
"frame",
",",
"argument_list",
")",
":",
"fun",
"=",
"frame",
".",
"f_code",
".",
"co_name",
"log",
".",
"info",
"(",
"'Calling: %r'",
"%",
"fun",
")",
"init",
"=",
"'Echo|%s'",
"%",
"dump",
"(",
"{",
"'for'",
... | 34.25 | 16.7 |
def sigterm_handler(signum, frame):
'''Intercept sigterm and terminate all processes.
'''
if captureproc and captureproc.poll() is None:
captureproc.terminate()
terminate(True)
sys.exit(0) | [
"def",
"sigterm_handler",
"(",
"signum",
",",
"frame",
")",
":",
"if",
"captureproc",
"and",
"captureproc",
".",
"poll",
"(",
")",
"is",
"None",
":",
"captureproc",
".",
"terminate",
"(",
")",
"terminate",
"(",
"True",
")",
"sys",
".",
"exit",
"(",
"0"... | 30 | 16.571429 |
def _calculate_credit_charge(self, message):
"""
Calculates the credit charge for a request based on the command. If
connection.supports_multi_credit is not True then the credit charge
isn't valid so it returns 0.
The credit charge is the number of credits that are required for
... | [
"def",
"_calculate_credit_charge",
"(",
"self",
",",
"message",
")",
":",
"credit_size",
"=",
"65536",
"if",
"not",
"self",
".",
"supports_multi_credit",
":",
"credit_charge",
"=",
"0",
"elif",
"message",
".",
"COMMAND",
"==",
"Commands",
".",
"SMB2_READ",
":"... | 48.088889 | 21.511111 |
def _finalize_namespaces(self, ns_dict=None):
"""Returns a dictionary of namespaces to be exported with an XML
document.
This loops over all the namespaces that were discovered and built
during the execution of ``collect()`` and
``_parse_collected_classes()`` and attempts to mer... | [
"def",
"_finalize_namespaces",
"(",
"self",
",",
"ns_dict",
"=",
"None",
")",
":",
"if",
"ns_dict",
":",
"# Add the user's entries to our set",
"for",
"ns",
",",
"alias",
"in",
"six",
".",
"iteritems",
"(",
"ns_dict",
")",
":",
"self",
".",
"_collected_namespa... | 39.672131 | 23.393443 |
def jsonify_timedelta(value):
"""Converts a `datetime.timedelta` to an ISO 8601 duration
string for JSON-ification.
:param value: something to convert
:type value: datetime.timedelta
:return: the value after conversion
:rtype unicode
"""
assert isinstance(value, datetime.timedelta)
... | [
"def",
"jsonify_timedelta",
"(",
"value",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"timedelta",
")",
"# split seconds to larger units",
"seconds",
"=",
"value",
".",
"total_seconds",
"(",
")",
"minutes",
",",
"seconds",
"=",
"divmod"... | 23.519231 | 18.461538 |
def stop(self):
"""Stop the thread, making this object unusable."""
if not self._dead:
self._killed = True
self._cancelled.set()
self._busy_sem.release()
self.join()
if not self._ready_sem.acquire(False):
warning("ISOTP Timer th... | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_dead",
":",
"self",
".",
"_killed",
"=",
"True",
"self",
".",
"_cancelled",
".",
"set",
"(",
")",
"self",
".",
"_busy_sem",
".",
"release",
"(",
")",
"self",
".",
"join",
"(",
")",... | 37.5 | 11.6 |
def fork(self, state, expression, policy='ALL', setstate=None):
"""
Fork state on expression concretizations.
Using policy build a list of solutions for expression.
For the state on each solution setting the new state with setstate
For example if expression is a Bool it may have... | [
"def",
"fork",
"(",
"self",
",",
"state",
",",
"expression",
",",
"policy",
"=",
"'ALL'",
",",
"setstate",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"expression",
",",
"Expression",
")",
"if",
"setstate",
"is",
"None",
":",
"setstate",
"=",
"... | 35.915254 | 23.101695 |
def disable_detailed_monitoring(name, call=None):
'''
Enable/disable detailed monitoring on a node
CLI Example:
'''
if call != 'action':
raise SaltCloudSystemExit(
'The enable_term_protect action must be called with '
'-a or --action.'
)
instance_id = _g... | [
"def",
"disable_detailed_monitoring",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The enable_term_protect action must be called with '",
"'-a or --action.'",
")",
"instance_id",
"=",
"_get_... | 30.958333 | 18.708333 |
def code_events(self):
"""Returns processed memory usage."""
if self._resulting_events:
return self._resulting_events
for i, (lineno, mem, func, fname) in enumerate(self._events_list):
mem_in_mb = float(mem - self.mem_overhead) / _BYTES_IN_MB
if (self._resulti... | [
"def",
"code_events",
"(",
"self",
")",
":",
"if",
"self",
".",
"_resulting_events",
":",
"return",
"self",
".",
"_resulting_events",
"for",
"i",
",",
"(",
"lineno",
",",
"mem",
",",
"func",
",",
"fname",
")",
"in",
"enumerate",
"(",
"self",
".",
"_eve... | 49.5625 | 15.5 |
def PushItem(self, item, block=True):
"""Pushes an item onto the queue.
Args:
item (object): item to add.
block (Optional[bool]): True to block the process when the queue is full.
Raises:
QueueFull: if the item could not be pushed the queue because it's full.
"""
try:
self.... | [
"def",
"PushItem",
"(",
"self",
",",
"item",
",",
"block",
"=",
"True",
")",
":",
"try",
":",
"self",
".",
"_queue",
".",
"put",
"(",
"item",
",",
"block",
"=",
"block",
")",
"except",
"Queue",
".",
"Full",
"as",
"exception",
":",
"raise",
"errors"... | 29.428571 | 18.857143 |
def get_instance(self, payload):
"""
Build an instance of IpAccessControlListInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance
:rtype: twilio.rest.api.v2010.account.sip.ip_a... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"IpAccessControlListInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")"
] | 37.285714 | 23.285714 |
def write_to_screen(self, cli, screen, mouse_handlers, write_position):
"""
Write window to screen. This renders the user control, the margins and
copies everything over to the absolute position at the given screen.
"""
# Calculate margin sizes.
left_margin_widths = [self... | [
"def",
"write_to_screen",
"(",
"self",
",",
"cli",
",",
"screen",
",",
"mouse_handlers",
",",
"write_position",
")",
":",
"# Calculate margin sizes.",
"left_margin_widths",
"=",
"[",
"self",
".",
"_get_margin_width",
"(",
"cli",
",",
"m",
")",
"for",
"m",
"in"... | 43.609375 | 22.023438 |
def set_pin_retries(ctx, pw_attempts, admin_pin, force):
"""
Manage pin-retries.
Sets the number of attempts available before locking for each PIN.
PW_ATTEMPTS should be three integer values corresponding to the number of
attempts for the PIN, Reset Code, and Admin PIN, respectively.
"""
c... | [
"def",
"set_pin_retries",
"(",
"ctx",
",",
"pw_attempts",
",",
"admin_pin",
",",
"force",
")",
":",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"resets_pins",
"=",
"controller",
".",
"version",
"<",
"(",
"4",
",",
"0",
",",
"0",
")"... | 40.428571 | 19.285714 |
def _multiline_width(multiline_s, line_width_fn=len):
"""Visible width of a potentially multiline content."""
return max(map(line_width_fn, re.split("[\r\n]", multiline_s))) | [
"def",
"_multiline_width",
"(",
"multiline_s",
",",
"line_width_fn",
"=",
"len",
")",
":",
"return",
"max",
"(",
"map",
"(",
"line_width_fn",
",",
"re",
".",
"split",
"(",
"\"[\\r\\n]\"",
",",
"multiline_s",
")",
")",
")"
] | 59.666667 | 13.333333 |
def _deconv_rl_gpu_conv(data_g, h_g, Niter=10):
"""
using convolve
"""
# set up some gpu buffers
u_g = OCLArray.empty(data_g.shape, np.float32)
u_g.copy_buffer(data_g)
tmp_g = OCLArray.empty(data_g.shape, np.float32)
tmp2_g = OCLArray.empty(data_g.shape, np.float32)
# fix this
... | [
"def",
"_deconv_rl_gpu_conv",
"(",
"data_g",
",",
"h_g",
",",
"Niter",
"=",
"10",
")",
":",
"# set up some gpu buffers",
"u_g",
"=",
"OCLArray",
".",
"empty",
"(",
"data_g",
".",
"shape",
",",
"np",
".",
"float32",
")",
"u_g",
".",
"copy_buffer",
"(",
"d... | 17.555556 | 24.333333 |
def generate_inverse_mapping(order):
"""Genereate a lambda entry -> PN order map.
This function will generate the opposite of generate mapping. So where
generate_mapping gives dict[key] = item this will give
dict[item] = key. Valid PN orders are:
{}
Parameters
----------
order : string... | [
"def",
"generate_inverse_mapping",
"(",
"order",
")",
":",
"mapping",
"=",
"generate_mapping",
"(",
"order",
")",
"inv_mapping",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"mapping",
".",
"items",
"(",
")",
":",
"inv_mapping",
"[",
"value",
"]",
"=... | 26.8 | 21.64 |
def _safe_read(path, length):
"""Read file contents."""
if not os.path.exists(os.path.join(HERE, path)):
return ''
file_handle = codecs.open(os.path.join(HERE, path), encoding='utf-8')
contents = file_handle.read(length)
file_handle.close()
return contents | [
"def",
"_safe_read",
"(",
"path",
",",
"length",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"HERE",
",",
"path",
")",
")",
":",
"return",
"''",
"file_handle",
"=",
"codecs",
".",
"open",
"("... | 35.125 | 14.75 |
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
query = '''SELECT minion_id, last_fun FROM {keyspace}.minions
WHERE last_fun = ?;'''.format(keyspace=_get_keyspace())
ret = {}
# cassandra_cql.cql_query may raise a CommandExecutionError
try:... | [
"def",
"get_fun",
"(",
"fun",
")",
":",
"query",
"=",
"'''SELECT minion_id, last_fun FROM {keyspace}.minions\n WHERE last_fun = ?;'''",
".",
"format",
"(",
"keyspace",
"=",
"_get_keyspace",
"(",
")",
")",
"ret",
"=",
"{",
"}",
"# cassandra_cql.cql_query may ... | 31.37037 | 22.925926 |
def _convert_from_thrift_binary_annotations(self, thrift_binary_annotations):
"""Accepts a thrift decoded binary annotation and converts it
to a v1 binary annotation.
"""
tags = {}
local_endpoint = None
remote_endpoint = None
for binary_annotation in thrift_binar... | [
"def",
"_convert_from_thrift_binary_annotations",
"(",
"self",
",",
"thrift_binary_annotations",
")",
":",
"tags",
"=",
"{",
"}",
"local_endpoint",
"=",
"None",
"remote_endpoint",
"=",
"None",
"for",
"binary_annotation",
"in",
"thrift_binary_annotations",
":",
"if",
"... | 41.606061 | 21.848485 |
def mag_yaw(RAW_IMU, inclination, declination):
'''estimate yaw from mag'''
m = mag_rotation(RAW_IMU, inclination, declination)
(r, p, y) = m.to_euler()
y = degrees(y)
if y < 0:
y += 360
return y | [
"def",
"mag_yaw",
"(",
"RAW_IMU",
",",
"inclination",
",",
"declination",
")",
":",
"m",
"=",
"mag_rotation",
"(",
"RAW_IMU",
",",
"inclination",
",",
"declination",
")",
"(",
"r",
",",
"p",
",",
"y",
")",
"=",
"m",
".",
"to_euler",
"(",
")",
"y",
... | 27.5 | 18 |
def get_one(self, qry, tpl):
''' get a single from from a query
limit 1 is automatically added '''
self.cur.execute(qry + ' LIMIT 1', tpl)
result = self.cur.fetchone()
# unpack tuple if it has only
# one element
# TODO unpack results
if type(result) is tup... | [
"def",
"get_one",
"(",
"self",
",",
"qry",
",",
"tpl",
")",
":",
"self",
".",
"cur",
".",
"execute",
"(",
"qry",
"+",
"' LIMIT 1'",
",",
"tpl",
")",
"result",
"=",
"self",
".",
"cur",
".",
"fetchone",
"(",
")",
"# unpack tuple if it has only",
"# one e... | 35.181818 | 9.363636 |
def deref(self, ctx):
"""
Returns the value this reference is pointing to. This method uses 'ctx' to resolve the reference and return
the value this reference references.
If the call was already made, it returns a cached result.
It also makes sure there's no cyclic reference, and... | [
"def",
"deref",
"(",
"self",
",",
"ctx",
")",
":",
"if",
"self",
"in",
"ctx",
".",
"call_nodes",
":",
"raise",
"CyclicReferenceError",
"(",
"ctx",
",",
"self",
")",
"if",
"self",
"in",
"ctx",
".",
"cached_results",
":",
"return",
"ctx",
".",
"cached_re... | 35.222222 | 17.888889 |
def get_stream_url(self, session_id, stream_id=None):
""" this method returns the url to get streams information """
url = self.api_url + '/v2/project/' + self.api_key + '/session/' + session_id + '/stream'
if stream_id:
url = url + '/' + stream_id
return url | [
"def",
"get_stream_url",
"(",
"self",
",",
"session_id",
",",
"stream_id",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"api_url",
"+",
"'/v2/project/'",
"+",
"self",
".",
"api_key",
"+",
"'/session/'",
"+",
"session_id",
"+",
"'/stream'",
"if",
"stream... | 49.666667 | 18.666667 |
def getServiceNamesToTraceIds(self, time_stamp, service_name, rpc_name):
"""
Given a time stamp, server service name, and rpc name, fetch all of the client services calling in paired
with the lists of every trace Ids (list<i64>) from the server to client.
The three arguments specify epoch time in micro... | [
"def",
"getServiceNamesToTraceIds",
"(",
"self",
",",
"time_stamp",
",",
"service_name",
",",
"rpc_name",
")",
":",
"self",
".",
"send_getServiceNamesToTraceIds",
"(",
"time_stamp",
",",
"service_name",
",",
"rpc_name",
")",
"return",
"self",
".",
"recv_getServiceNa... | 42.933333 | 30.533333 |
def add_castle(self, position):
"""
Adds kingside and queenside castling moves if legal
:type: position: Board
"""
if self.has_moved or self.in_check(position):
return
if self.color == color.white:
rook_rank = 0
else:
rook_ran... | [
"def",
"add_castle",
"(",
"self",
",",
"position",
")",
":",
"if",
"self",
".",
"has_moved",
"or",
"self",
".",
"in_check",
"(",
"position",
")",
":",
"return",
"if",
"self",
".",
"color",
"==",
"color",
".",
"white",
":",
"rook_rank",
"=",
"0",
"els... | 37.266667 | 22 |
def insert_group(node, target):
"""Insert node into in target tree, in appropriate group.
Uses group and lang from target function. This assumes the node and
target share a structure of a first child that determines the grouping,
and a second child that will be accumulated in the group.
"""
gr... | [
"def",
"insert_group",
"(",
"node",
",",
"target",
")",
":",
"group",
"=",
"target",
".",
"sort",
"lang",
"=",
"target",
".",
"lang",
"collator",
"=",
"Collator",
".",
"createInstance",
"(",
"Locale",
"(",
"lang",
")",
"if",
"lang",
"else",
"Locale",
"... | 34.454545 | 18.909091 |
def find_site_python(module_name, paths=None):
"""Find the rez native python package that contains the given module.
This function is used by python 'native' rez installers to find the native
rez python package that represents the python installation that this module
is installed into.
Note:
... | [
"def",
"find_site_python",
"(",
"module_name",
",",
"paths",
"=",
"None",
")",
":",
"from",
"rez",
".",
"packages_",
"import",
"iter_packages",
"import",
"subprocess",
"import",
"ast",
"import",
"os",
"py_cmd",
"=",
"'import {x}; print {x}.__path__'",
".",
"format... | 33.810345 | 23.982759 |
def traverseItems(self,
mode=TraverseMode.DepthFirst,
parent=None):
"""
Generates a tree iterator that will traverse the items of this tree
in either a depth-first or breadth-first fashion.
:param mode | <XTreeWidget.Traver... | [
"def",
"traverseItems",
"(",
"self",
",",
"mode",
"=",
"TraverseMode",
".",
"DepthFirst",
",",
"parent",
"=",
"None",
")",
":",
"try",
":",
"if",
"parent",
":",
"count",
"=",
"parent",
".",
"childCount",
"(",
")",
"func",
"=",
"parent",
".",
"child",
... | 33.536585 | 15.878049 |
def login(request, user):
"""
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
"""
session_auth_hash = ''
if user is None:
user = request... | [
"def",
"login",
"(",
"request",
",",
"user",
")",
":",
"session_auth_hash",
"=",
"''",
"if",
"user",
"is",
"None",
":",
"user",
"=",
"request",
".",
"user",
"if",
"hasattr",
"(",
"user",
",",
"'get_session_auth_hash'",
")",
":",
"session_auth_hash",
"=",
... | 39.5 | 17.5 |
def draw_flow(img, flow, step=16, dtype=uint8):
"""
draws flow vectors on image
this came from opencv/examples directory
another way: http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_drawing_functions/py_drawing_functions.html
"""
maxval = iinfo(img.dtype).max
# scaleFact = 1. #arbit... | [
"def",
"draw_flow",
"(",
"img",
",",
"flow",
",",
"step",
"=",
"16",
",",
"dtype",
"=",
"uint8",
")",
":",
"maxval",
"=",
"iinfo",
"(",
"img",
".",
"dtype",
")",
".",
"max",
"# scaleFact = 1. #arbitary factor to make flow visible",
"canno",
"=",
"(",
"0",
... | 37.666667 | 17.814815 |
def get_config_values(config_path, section, default='default'):
"""
Parse ini config file and return a dict of values.
The provided section overrides any values in default section.
"""
values = {}
if not os.path.isfile(config_path):
raise IpaUtilsException(
'Config file not... | [
"def",
"get_config_values",
"(",
"config_path",
",",
"section",
",",
"default",
"=",
"'default'",
")",
":",
"values",
"=",
"{",
"}",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"config_path",
")",
":",
"raise",
"IpaUtilsException",
"(",
"'Config fi... | 21.636364 | 21.454545 |
def get_tools(whitelist, known_plugins):
"""
Filter all known plugins by a whitelist specified. If the whitelist is
empty, default to all plugins.
"""
def getpath(c):
return "%s:%s" % (c.__module__, c.__class__.__name__)
tools = [x for x in known_plugins if getpath(x) in whitelist]
... | [
"def",
"get_tools",
"(",
"whitelist",
",",
"known_plugins",
")",
":",
"def",
"getpath",
"(",
"c",
")",
":",
"return",
"\"%s:%s\"",
"%",
"(",
"c",
".",
"__module__",
",",
"c",
".",
"__class__",
".",
"__name__",
")",
"tools",
"=",
"[",
"x",
"for",
"x",... | 29.933333 | 18.866667 |
def headers_as_list(self):
"""
Does the same as 'headers' except it is returned as a list.
"""
headers = self.headers
headers_list = ['{}: {}'.format(key, value) for key, value in iteritems(headers)]
return headers_list | [
"def",
"headers_as_list",
"(",
"self",
")",
":",
"headers",
"=",
"self",
".",
"headers",
"headers_list",
"=",
"[",
"'{}: {}'",
".",
"format",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"headers",
")",
"]",
"retur... | 37.285714 | 16.142857 |
def add_url (self, url, line=0, column=0, page=0, name=u"", base=None):
"""Add new URL to queue."""
if base:
base_ref = urlutil.url_norm(base)[0]
else:
base_ref = None
url_data = get_url_from(url, self.recursion_level+1, self.aggregate,
parent_url=self... | [
"def",
"add_url",
"(",
"self",
",",
"url",
",",
"line",
"=",
"0",
",",
"column",
"=",
"0",
",",
"page",
"=",
"0",
",",
"name",
"=",
"u\"\"",
",",
"base",
"=",
"None",
")",
":",
"if",
"base",
":",
"base_ref",
"=",
"urlutil",
".",
"url_norm",
"("... | 48 | 21.3 |
def _check_properties(cls, property_names, require_indexed=True):
"""Internal helper to check the given properties exist and meet specified
requirements.
Called from query.py.
Args:
property_names: List or tuple of property names -- each being a string,
possibly containing dots (to addre... | [
"def",
"_check_properties",
"(",
"cls",
",",
"property_names",
",",
"require_indexed",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"property_names",
",",
"(",
"list",
",",
"tuple",
")",
")",
",",
"repr",
"(",
"property_names",
")",
"for",
"name",
"... | 34.62963 | 21.962963 |
def completelist(self, text):
"""Return a list of potential matches for completion
n.b. you want to complete to a file in the current working directory
that starts with a ~, use ./~ when typing in. Paths that start with
~ are magical and specify users' home paths
"""
... | [
"def",
"completelist",
"(",
"self",
",",
"text",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"text",
")",
"if",
"len",
"(",
"path",
")",
"==",
"0",
"or",
"path",
"[",
"0",
"]",
"!=",
"os",
".",
"path",
".",
"sep",
":",
"... | 42 | 16.034483 |
def _struct_or_lob_handler(c, ctx):
"""Handles tokens that begin with an open brace."""
assert c == _OPEN_BRACE
c, self = yield
yield ctx.immediate_transition(_STRUCT_OR_LOB_TABLE[c](c, ctx)) | [
"def",
"_struct_or_lob_handler",
"(",
"c",
",",
"ctx",
")",
":",
"assert",
"c",
"==",
"_OPEN_BRACE",
"c",
",",
"self",
"=",
"yield",
"yield",
"ctx",
".",
"immediate_transition",
"(",
"_STRUCT_OR_LOB_TABLE",
"[",
"c",
"]",
"(",
"c",
",",
"ctx",
")",
")"
] | 40.6 | 13.2 |
def submit_unseal_key(self, key=None, reset=False, migrate=False):
"""Enter a single master key share to progress the unsealing of the Vault.
If the threshold number of master key shares is reached, Vault will attempt to unseal the Vault. Otherwise, this
API must be called multiple times until ... | [
"def",
"submit_unseal_key",
"(",
"self",
",",
"key",
"=",
"None",
",",
"reset",
"=",
"False",
",",
"migrate",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'migrate'",
":",
"migrate",
",",
"}",
"if",
"not",
"reset",
"and",
"key",
"is",
"not",
"None",
... | 39.416667 | 26.055556 |
def load_plan(self, fname):
""" read the list of thoughts from a text file """
with open(fname, "r") as f:
for line in f:
if line != '':
tpe, txt = self.parse_plan_from_string(line)
#print('tpe= "' + tpe + '"', txt)
... | [
"def",
"load_plan",
"(",
"self",
",",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
",",
"\"r\"",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"line",
"!=",
"''",
":",
"tpe",
",",
"txt",
"=",
"self",
".",
"parse_plan_from_string",
... | 42.764706 | 6.529412 |
def manage_beacons(self, tag, data):
'''
Manage Beacons
'''
func = data.get('func', None)
name = data.get('name', None)
beacon_data = data.get('beacon_data', None)
include_pillar = data.get('include_pillar', None)
include_opts = data.get('include_opts', No... | [
"def",
"manage_beacons",
"(",
"self",
",",
"tag",
",",
"data",
")",
":",
"func",
"=",
"data",
".",
"get",
"(",
"'func'",
",",
"None",
")",
"name",
"=",
"data",
".",
"get",
"(",
"'name'",
",",
"None",
")",
"beacon_data",
"=",
"data",
".",
"get",
"... | 42.805556 | 17.638889 |
def _compute_term1(self, C, mag):
"""
Compute magnitude dependent terms (2nd and 3rd) in equation 3
page 46.
"""
mag_diff = mag - 6
return C['c2'] * mag_diff + C['c3'] * mag_diff ** 2 | [
"def",
"_compute_term1",
"(",
"self",
",",
"C",
",",
"mag",
")",
":",
"mag_diff",
"=",
"mag",
"-",
"6",
"return",
"C",
"[",
"'c2'",
"]",
"*",
"mag_diff",
"+",
"C",
"[",
"'c3'",
"]",
"*",
"mag_diff",
"**",
"2"
] | 28.125 | 16.625 |
def json_call(cls, method, url, **kwargs):
""" Call a remote api using json format """
# retrieve api key if needed
empty_key = kwargs.pop('empty_key', False)
send_key = kwargs.pop('send_key', True)
return_header = kwargs.pop('return_header', False)
try:
apike... | [
"def",
"json_call",
"(",
"cls",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"# retrieve api key if needed",
"empty_key",
"=",
"kwargs",
".",
"pop",
"(",
"'empty_key'",
",",
"False",
")",
"send_key",
"=",
"kwargs",
".",
"pop",
"(",
"'sen... | 40.71875 | 13.1875 |
def create_chapter_from_string(self, html_string, url=None, title=None):
"""
Creates a Chapter object from a string. Sanitizes the
string using the clean_function method, and saves
it as the content of the created chapter.
Args:
html_string (string): The html or xhtm... | [
"def",
"create_chapter_from_string",
"(",
"self",
",",
"html_string",
",",
"url",
"=",
"None",
",",
"title",
"=",
"None",
")",
":",
"clean_html_string",
"=",
"self",
".",
"clean_function",
"(",
"html_string",
")",
"clean_xhtml_string",
"=",
"clean",
".",
"html... | 42.212121 | 20.393939 |
def ip_rtm_config_route_static_bfd_bfd_static_route_bfd_static_route_src(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
rtm_config = ET.SubElement(ip, "rtm-config", xmlns=... | [
"def",
"ip_rtm_config_route_static_bfd_bfd_static_route_bfd_static_route_src",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"ip",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ip\"",
",",
"... | 56.823529 | 25.235294 |
def qos_red_profile_min_threshold(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
red_profile = ET.SubElement(qos, "red-profile")
profile_id_key = ET.SubElement(red_prof... | [
"def",
"qos_red_profile_min_threshold",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"qos",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"qos\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:m... | 45.923077 | 16.923077 |
def create_system(self, **system_options):
"""
Create an OpenMM system for every supported topology file with given system options
"""
if self.master is None:
raise ValueError('Handler {} is not able to create systems.'.format(self))
if isinstance(self.master, ForceF... | [
"def",
"create_system",
"(",
"self",
",",
"*",
"*",
"system_options",
")",
":",
"if",
"self",
".",
"master",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Handler {} is not able to create systems.'",
".",
"format",
"(",
"self",
")",
")",
"if",
"isinstance",... | 48.904762 | 26.047619 |
def cost(self, logits, target):
"""Returns cost.
Args:
logits: model output.
target: target.
Returns:
Cross-entropy loss for a sequence of logits. The loss will be averaged
across time steps if time_average_cost was enabled at construction time.
"""
logits = tf.reshape(logi... | [
"def",
"cost",
"(",
"self",
",",
"logits",
",",
"target",
")",
":",
"logits",
"=",
"tf",
".",
"reshape",
"(",
"logits",
",",
"[",
"self",
".",
"_num_steps",
"*",
"self",
".",
"_batch_size",
",",
"-",
"1",
"]",
")",
"target",
"=",
"tf",
".",
"resh... | 33.588235 | 24.470588 |
def get_fixers(self):
"""Inspects the options to load the requested patterns and handlers.
Returns:
(pre_order, post_order), where pre_order is the list of fixers that
want a pre-order AST traversal, and post_order is the list that want
post-order traversal.
"""
... | [
"def",
"get_fixers",
"(",
"self",
")",
":",
"pre_order_fixers",
"=",
"[",
"]",
"post_order_fixers",
"=",
"[",
"]",
"for",
"fix_mod_path",
"in",
"self",
".",
"fixers",
":",
"mod",
"=",
"__import__",
"(",
"fix_mod_path",
",",
"{",
"}",
",",
"{",
"}",
","... | 44.051282 | 17.615385 |
def start_logger(log_to_file=False, \
log_to_stream=False, \
log_to_file_level=logging.INFO, \
log_to_stream_level=logging.INFO, \
log_filename=None, \
log_stream=None, \
log_rotate=True, \
log_size=52... | [
"def",
"start_logger",
"(",
"log_to_file",
"=",
"False",
",",
"log_to_stream",
"=",
"False",
",",
"log_to_file_level",
"=",
"logging",
".",
"INFO",
",",
"log_to_stream_level",
"=",
"logging",
".",
"INFO",
",",
"log_filename",
"=",
"None",
",",
"log_stream",
"=... | 43.79661 | 19.491525 |
def __msg_curse_sum(self, ret, sep_char='_', mmm=None, args=None):
"""
Build the sum message (only when filter is on) and add it to the ret dict.
* ret: list of string where the message is added
* sep_char: define the line separation char
* mmm: display min, max, mean or current... | [
"def",
"__msg_curse_sum",
"(",
"self",
",",
"ret",
",",
"sep_char",
"=",
"'_'",
",",
"mmm",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"ret",
".",
"append",
"(",
"self",
".",
"curse_new_line",
"(",
")",
")",
"if",
"mmm",
"is",
"None",
":",
... | 51.382022 | 24.078652 |
def valueFromString(self, value, extra=None, db=None):
"""
Converts the inputted string text to a value that matches the type from
this column type.
:param value | <str>
extra | <variant>
"""
try:
return projex.text.safe_eval(value)
... | [
"def",
"valueFromString",
"(",
"self",
",",
"value",
",",
"extra",
"=",
"None",
",",
"db",
"=",
"None",
")",
":",
"try",
":",
"return",
"projex",
".",
"text",
".",
"safe_eval",
"(",
"value",
")",
"except",
"ValueError",
":",
"return",
"0"
] | 29.583333 | 15.583333 |
def init_dirs(rootdir_or_loader, outputpath, saveto_dir='data',
auximages_dir='auximages', prefix='crd'):
"""Initialize the directiories.
Inputs:
rootdir_or_loader: depends on the type:
str:
the root directory of the SAXSCtrl/CCT
software, i.e. ... | [
"def",
"init_dirs",
"(",
"rootdir_or_loader",
",",
"outputpath",
",",
"saveto_dir",
"=",
"'data'",
",",
"auximages_dir",
"=",
"'auximages'",
",",
"prefix",
"=",
"'crd'",
")",
":",
"ip",
"=",
"get_ipython",
"(",
")",
"if",
"isinstance",
"(",
"rootdir_or_loader"... | 49.015152 | 23.530303 |
def distribute(self, f, n):
"""Distribute the computations amongst the multiprocessing pools
Parameters
----------
f : function
Function to be distributed to the processors
n : int
The values in range(0,n) will be passed as arguments to the
function... | [
"def",
"distribute",
"(",
"self",
",",
"f",
",",
"n",
")",
":",
"if",
"self",
".",
"pool",
"is",
"None",
":",
"return",
"[",
"f",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"else",
":",
"return",
"self",
".",
"pool",
".",
... | 28.4375 | 18.125 |
def delete(self):
"""Delete this column family.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_delete_column_family]
:end-before: [END bigtable_delete_column_family]
"""
modification = table_admin_v2_pb2.ModifyColumnFam... | [
"def",
"delete",
"(",
"self",
")",
":",
"modification",
"=",
"table_admin_v2_pb2",
".",
"ModifyColumnFamiliesRequest",
".",
"Modification",
"(",
"id",
"=",
"self",
".",
"column_family_id",
",",
"drop",
"=",
"True",
")",
"client",
"=",
"self",
".",
"_table",
... | 32.85 | 21.55 |
def computeActivity(self, activePresynapticCells, connectedPermanence):
"""
Compute each segment's number of active synapses for a given input.
In the returned lists, a segment's active synapse count is stored at index
``segment.flatIdx``.
:param activePresynapticCells: (iter) Active cells.
:p... | [
"def",
"computeActivity",
"(",
"self",
",",
"activePresynapticCells",
",",
"connectedPermanence",
")",
":",
"numActiveConnectedSynapsesForSegment",
"=",
"[",
"0",
"]",
"*",
"self",
".",
"_nextFlatIdx",
"numActivePotentialSynapsesForSegment",
"=",
"[",
"0",
"]",
"*",
... | 40.785714 | 22.107143 |
def tz_convert(dt, to_tz, from_tz=None) -> str:
"""
Convert to tz
Args:
dt: date time
to_tz: to tz
from_tz: from tz - will be ignored if tz from dt is given
Returns:
str: date & time
Examples:
>>> dt_1 = pd.Timestamp('2018-09-10 16:00', tz='Asia/Hong_Kong')... | [
"def",
"tz_convert",
"(",
"dt",
",",
"to_tz",
",",
"from_tz",
"=",
"None",
")",
"->",
"str",
":",
"logger",
"=",
"logs",
".",
"get_logger",
"(",
"tz_convert",
",",
"level",
"=",
"'info'",
")",
"f_tz",
",",
"t_tz",
"=",
"get_tz",
"(",
"from_tz",
")",
... | 31.827586 | 17.689655 |
def p_range(self, p):
"""range : value DOT_DOT value
| value"""
n = len(p)
if n == 2:
p[0] = (p[1],)
elif n == 4:
p[0] = (p[1], p[3]) | [
"def",
"p_range",
"(",
"self",
",",
"p",
")",
":",
"n",
"=",
"len",
"(",
"p",
")",
"if",
"n",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"p",
"[",
"1",
"]",
",",
")",
"elif",
"n",
"==",
"4",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"p"... | 24.875 | 13.25 |
def pack_factorisation(facto_list):
"""
:param facto_list: list of parser or tuple of factorisation
:return:
"""
_sum = []
for f in facto_list:
if isinstance(f, Script):
_sum.append(f)
else:
# tuple of factorisation
_sum.append(MultiplicativeSc... | [
"def",
"pack_factorisation",
"(",
"facto_list",
")",
":",
"_sum",
"=",
"[",
"]",
"for",
"f",
"in",
"facto_list",
":",
"if",
"isinstance",
"(",
"f",
",",
"Script",
")",
":",
"_sum",
".",
"append",
"(",
"f",
")",
"else",
":",
"# tuple of factorisation",
... | 27.058824 | 18.588235 |
def is_allowed(self, role, method, resource):
"""Check whether role is allowed to access resource
:param role: Role to be checked.
:param method: Method to be checked.
:param resource: View function to be checked.
"""
return (role, method, resource) in self._allowed | [
"def",
"is_allowed",
"(",
"self",
",",
"role",
",",
"method",
",",
"resource",
")",
":",
"return",
"(",
"role",
",",
"method",
",",
"resource",
")",
"in",
"self",
".",
"_allowed"
] | 38.5 | 9.75 |
def number(ctx, seq=None):
'''
Yields one float, derived from the first item in the argument sequence (unless empty in which case yield NaN) as follows:
* If string with optional whitespace followed by an optional minus sign followed by a Number followed by whitespace, converte to the IEEE 754 number that ... | [
"def",
"number",
"(",
"ctx",
",",
"seq",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'compute'",
")",
":",
"obj",
"=",
"next",
"(",
"seq",
".",
"compute",
"(",
"ctx",
")",
",",
"''",
")",
"else",
":",
"obj",
"=",
"seq",
"yield",
... | 60.692308 | 49.769231 |
def get_report_details(self, report_id, id_type=None):
"""
Retrieves a report by its ID. Internal and external IDs are both allowed.
:param str report_id: The ID of the incident report.
:param str id_type: Indicates whether ID is internal or external.
:return: The retrieved |R... | [
"def",
"get_report_details",
"(",
"self",
",",
"report_id",
",",
"id_type",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'idType'",
":",
"id_type",
"}",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"reports/%s\"",
"%",
"report_id",
",",
"params... | 34.709677 | 22.580645 |
def ProcessClients(self, responses):
"""Does the work."""
del responses
end = rdfvalue.RDFDatetime.Now() - db.CLIENT_STATS_RETENTION
client_urns = export_utils.GetAllClients(token=self.token)
for batch in collection.Batch(client_urns, 10000):
with data_store.DB.GetMutationPool() as mutation_... | [
"def",
"ProcessClients",
"(",
"self",
",",
"responses",
")",
":",
"del",
"responses",
"end",
"=",
"rdfvalue",
".",
"RDFDatetime",
".",
"Now",
"(",
")",
"-",
"db",
".",
"CLIENT_STATS_RETENTION",
"client_urns",
"=",
"export_utils",
".",
"GetAllClients",
"(",
"... | 38.333333 | 17.166667 |
def index(self, name=None): # pylint: disable=C6409
"""Returns index number of supplied column name.
Args:
name: string of column name.
Raises:
TableError: If name not found.
Returns:
Index of the specified header entry.
"""
try:
return self.header.index(name)
exc... | [
"def",
"index",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"# pylint: disable=C6409",
"try",
":",
"return",
"self",
".",
"header",
".",
"index",
"(",
"name",
")",
"except",
"ValueError",
":",
"raise",
"TableError",
"(",
"'Unknown index name %s.'",
"%",... | 23.5 | 18.8125 |
def cleanShutdown(self, quickMode=False, stopReactor=True, _reactor=reactor):
"""Shut down the entire process, once all currently-running builds are
complete.
quickMode will mark all builds as retry (except the ones that were triggered)
"""
if self.shuttingDown:
retur... | [
"def",
"cleanShutdown",
"(",
"self",
",",
"quickMode",
"=",
"False",
",",
"stopReactor",
"=",
"True",
",",
"_reactor",
"=",
"reactor",
")",
":",
"if",
"self",
".",
"shuttingDown",
":",
"return",
"log",
".",
"msg",
"(",
"\"Initiating clean shutdown\"",
")",
... | 46.414286 | 19.057143 |
def learn_ids(self, item_list):
""" read in already set ids on objects """
self._reset_sequence()
for item in item_list:
key = self.nondup_key_for_item(item)
self.ids[key] = item[self.id_key] | [
"def",
"learn_ids",
"(",
"self",
",",
"item_list",
")",
":",
"self",
".",
"_reset_sequence",
"(",
")",
"for",
"item",
"in",
"item_list",
":",
"key",
"=",
"self",
".",
"nondup_key_for_item",
"(",
"item",
")",
"self",
".",
"ids",
"[",
"key",
"]",
"=",
... | 39 | 7 |
def shuffle_cols(seqarr, newarr, cols):
""" used in bootstrap resampling without a map file """
for idx in xrange(cols.shape[0]):
newarr[:, idx] = seqarr[:, cols[idx]]
return newarr | [
"def",
"shuffle_cols",
"(",
"seqarr",
",",
"newarr",
",",
"cols",
")",
":",
"for",
"idx",
"in",
"xrange",
"(",
"cols",
".",
"shape",
"[",
"0",
"]",
")",
":",
"newarr",
"[",
":",
",",
"idx",
"]",
"=",
"seqarr",
"[",
":",
",",
"cols",
"[",
"idx",... | 39.4 | 6.4 |
def plot_sed(sed, showlnl=False, **kwargs):
"""Render a plot of a spectral energy distribution.
Parameters
----------
showlnl : bool
Overlay a map of the delta-loglikelihood values vs. flux
in each energy bin.
cmap : str
Color... | [
"def",
"plot_sed",
"(",
"sed",
",",
"showlnl",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"ax",
"=",
"kwargs",
".",
"pop",
"(",
"'ax'",
",",
"plt",
".",
"gca",
"(",
")",
")",
"cmap",
"=",
"kwargs",
".",
"get",
"(",
"'cmap'",
",",
"'BuGn'"... | 28.609756 | 19.390244 |
def subscribe(self, topic=b''):
"""subscribe to the SUB socket, to listen for incomming variables, return a stream that can be listened to."""
self.sockets[zmq.SUB].setsockopt(zmq.SUBSCRIBE, topic)
poller = self.pollers[zmq.SUB]
return poller | [
"def",
"subscribe",
"(",
"self",
",",
"topic",
"=",
"b''",
")",
":",
"self",
".",
"sockets",
"[",
"zmq",
".",
"SUB",
"]",
".",
"setsockopt",
"(",
"zmq",
".",
"SUBSCRIBE",
",",
"topic",
")",
"poller",
"=",
"self",
".",
"pollers",
"[",
"zmq",
".",
... | 54 | 10.4 |
def non_tag_chars_from_raw(html):
'''generator that yields clean visible as it transitions through
states in the raw `html`
'''
n = 0
while n < len(html):
# find start of tag
angle = html.find('<', n)
if angle == -1:
yield html[n:]
n = len(html)
... | [
"def",
"non_tag_chars_from_raw",
"(",
"html",
")",
":",
"n",
"=",
"0",
"while",
"n",
"<",
"len",
"(",
"html",
")",
":",
"# find start of tag",
"angle",
"=",
"html",
".",
"find",
"(",
"'<'",
",",
"n",
")",
"if",
"angle",
"==",
"-",
"1",
":",
"yield"... | 39.362069 | 13.258621 |
def parse_findPeaks(self, f):
""" Parse HOMER findPeaks file headers. """
parsed_data = dict()
s_name = f['s_name']
for l in f['f']:
# Start of data
if l.strip() and not l.strip().startswith('#'):
break
# Automatically parse header line... | [
"def",
"parse_findPeaks",
"(",
"self",
",",
"f",
")",
":",
"parsed_data",
"=",
"dict",
"(",
")",
"s_name",
"=",
"f",
"[",
"'s_name'",
"]",
"for",
"l",
"in",
"f",
"[",
"'f'",
"]",
":",
"# Start of data",
"if",
"l",
".",
"strip",
"(",
")",
"and",
"... | 42.04 | 16.08 |
def remove_menu(self, name):
"""Remove a top-level menu.
Only removes menus created by the same menu manager.
"""
if name not in self._menus:
raise exceptions.MenuNotFound(
"Menu {!r} was not found. It might be deleted, or belong to another menu manager.".for... | [
"def",
"remove_menu",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_menus",
":",
"raise",
"exceptions",
".",
"MenuNotFound",
"(",
"\"Menu {!r} was not found. It might be deleted, or belong to another menu manager.\"",
".",
"format",
"("... | 37.727273 | 20.454545 |
def delete_message(self, id, remove):
"""
Delete a message.
Delete messages from this conversation. Note that this only affects this
user's view of the conversation. If all messages are deleted, the
conversation will be as well (equivalent to DELETE)
"""
... | [
"def",
"delete_message",
"(",
"self",
",",
"id",
",",
"remove",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"id\"",
"]",
"=",
"id",
"# REQUIRED - remove\r",
... | 38.909091 | 27.636364 |
def _remove_session_save_objects(self):
"""Used during exception handling in case we need to remove() session:
keep instances and merge them in the new session.
"""
if self.testing:
return
# Before destroying the session, get all instances to be attached to the
... | [
"def",
"_remove_session_save_objects",
"(",
"self",
")",
":",
"if",
"self",
".",
"testing",
":",
"return",
"# Before destroying the session, get all instances to be attached to the",
"# new session. Without this, we get DetachedInstance errors, like when",
"# tryin to get user's attribut... | 38.5625 | 20.53125 |
def getSignalHeader(self, chn):
"""
Returns the header of one signal as dicts
Parameters
----------
None
"""
return {'label': self.getLabel(chn),
'dimension': self.getPhysicalDimension(chn),
'sample_rate': self.g... | [
"def",
"getSignalHeader",
"(",
"self",
",",
"chn",
")",
":",
"return",
"{",
"'label'",
":",
"self",
".",
"getLabel",
"(",
"chn",
")",
",",
"'dimension'",
":",
"self",
".",
"getPhysicalDimension",
"(",
"chn",
")",
",",
"'sample_rate'",
":",
"self",
".",
... | 39.823529 | 17.470588 |
def normalize_vector(x, y, z):
"""
Normalizes vector to produce a unit vector.
Parameters
----------
x : float or array-like
X component of vector
y : float or array-like
Y component of vector
z : float or array-like
Z component of vector
Returns
... | [
"def",
"normalize_vector",
"(",
"x",
",",
"y",
",",
"z",
")",
":",
"mag",
"=",
"np",
".",
"sqrt",
"(",
"x",
"**",
"2",
"+",
"y",
"**",
"2",
"+",
"z",
"**",
"2",
")",
"x",
"=",
"x",
"/",
"mag",
"y",
"=",
"y",
"/",
"mag",
"z",
"=",
"z",
... | 18.96 | 18.96 |
def info(ctx):
"""
Display status of YubiKey Slots.
"""
dev = ctx.obj['dev']
controller = ctx.obj['controller']
slot1, slot2 = controller.slot_status
click.echo('Slot 1: {}'.format(slot1 and 'programmed' or 'empty'))
click.echo('Slot 2: {}'.format(slot2 and 'programmed' or 'empty'))
... | [
"def",
"info",
"(",
"ctx",
")",
":",
"dev",
"=",
"ctx",
".",
"obj",
"[",
"'dev'",
"]",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"slot1",
",",
"slot2",
"=",
"controller",
".",
"slot_status",
"click",
".",
"echo",
"(",
"'Slot 1: ... | 31.142857 | 17.142857 |
def getPlainText(self, iv, key, ciphertext):
"""
:type iv: bytearray
:type key: bytearray
:type ciphertext: bytearray
"""
try:
cipher = AESCipher(key, iv)
plaintext = cipher.decrypt(ciphertext)
if sys.version_info >= (3, 0):
... | [
"def",
"getPlainText",
"(",
"self",
",",
"iv",
",",
"key",
",",
"ciphertext",
")",
":",
"try",
":",
"cipher",
"=",
"AESCipher",
"(",
"key",
",",
"iv",
")",
"plaintext",
"=",
"cipher",
".",
"decrypt",
"(",
"ciphertext",
")",
"if",
"sys",
".",
"version... | 31.571429 | 7.285714 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.