text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def location (self, pos):
"""Formats the location of the given SeqPos as:
filename:line:col:
"""
result = ''
if self.filename:
result += self.filename + ':'
if pos:
result += str(pos)
return result | [
"def",
"location",
"(",
"self",
",",
"pos",
")",
":",
"result",
"=",
"''",
"if",
"self",
".",
"filename",
":",
"result",
"+=",
"self",
".",
"filename",
"+",
"':'",
"if",
"pos",
":",
"result",
"+=",
"str",
"(",
"pos",
")",
"return",
"result"
] | 21.090909 | 16.909091 |
def _creation_options_for_cog(creation_options, source_profile, blocksize):
"""
it uses the profile of the source raster, override anything using the creation_options
and guarantees we will have tiled raster and blocksize
"""
if not(creation_options):
creation_options = {}
creation_opti... | [
"def",
"_creation_options_for_cog",
"(",
"creation_options",
",",
"source_profile",
",",
"blocksize",
")",
":",
"if",
"not",
"(",
"creation_options",
")",
":",
"creation_options",
"=",
"{",
"}",
"creation_options",
"[",
"\"blocksize\"",
"]",
"=",
"blocksize",
"cre... | 40.533333 | 15.866667 |
def create(self, set):
"""
Creates a new Set.
"""
target_url = self.client.get_url('SET', 'POST', 'create')
r = self.client.request('POST', target_url, json=set._serialize())
return set._deserialize(r.json(), self) | [
"def",
"create",
"(",
"self",
",",
"set",
")",
":",
"target_url",
"=",
"self",
".",
"client",
".",
"get_url",
"(",
"'SET'",
",",
"'POST'",
",",
"'create'",
")",
"r",
"=",
"self",
".",
"client",
".",
"request",
"(",
"'POST'",
",",
"target_url",
",",
... | 36.571429 | 14 |
def load(file_or_path):
"""
Load a previously pickled model, using `m.pickle('path/to/file.pickle)'`
:param file_name: path/to/file.pickle
"""
from pickle import UnpicklingError
_python3 = True
try:
import cPickle as pickle
_python3 = False
except ImportError: #python3
... | [
"def",
"load",
"(",
"file_or_path",
")",
":",
"from",
"pickle",
"import",
"UnpicklingError",
"_python3",
"=",
"True",
"try",
":",
"import",
"cPickle",
"as",
"pickle",
"_python3",
"=",
"False",
"except",
"ImportError",
":",
"#python3",
"import",
"pickle",
"try"... | 27.703704 | 18.222222 |
def delete(self, filename=''):
"""Deletes given file or directory. If no filename is passed, current
directory is removed.
"""
self._raise_if_none()
fn = path_join(self.path, filename)
try:
if isfile(fn):
remove(fn)
else:
... | [
"def",
"delete",
"(",
"self",
",",
"filename",
"=",
"''",
")",
":",
"self",
".",
"_raise_if_none",
"(",
")",
"fn",
"=",
"path_join",
"(",
"self",
".",
"path",
",",
"filename",
")",
"try",
":",
"if",
"isfile",
"(",
"fn",
")",
":",
"remove",
"(",
"... | 27.235294 | 13.705882 |
async def destroy(self, container = None):
"""
Destroy the created subqueue to change the behavior back to Lock
"""
if container is None:
container = RoutineContainer(self.scheduler)
if self.queue is not None:
await container.syscall_noreturn(syscall_remov... | [
"async",
"def",
"destroy",
"(",
"self",
",",
"container",
"=",
"None",
")",
":",
"if",
"container",
"is",
"None",
":",
"container",
"=",
"RoutineContainer",
"(",
"self",
".",
"scheduler",
")",
"if",
"self",
".",
"queue",
"is",
"not",
"None",
":",
"awai... | 42.555556 | 15.222222 |
def ace(args):
"""
%prog ace bamfile fastafile
convert bam format to ace format. This often allows the remapping to be
assessed as a denovo assembly format. bam file needs to be indexed. also
creates a .mates file to be used in amos/bambus, and .astat file to mark
whether the contig is unique o... | [
"def",
"ace",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"ace",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--splitdir\"",
",",
"dest",
"=",
"\"splitdir\"",
",",
"default",
"=",
"\"outRoot\"",
",",
"help",
"=",
"\"split the ace per cont... | 33.008696 | 21.686957 |
def pop_cell(self, idy=None, idx=None, tags=False):
"""Pops a cell, default the last of the last row"""
idy = idy if idy is not None else len(self.body) - 1
idx = idx if idx is not None else len(self.body[idy]) - 1
cell = self.body[idy].pop(idx)
return cell if tags else cell.chil... | [
"def",
"pop_cell",
"(",
"self",
",",
"idy",
"=",
"None",
",",
"idx",
"=",
"None",
",",
"tags",
"=",
"False",
")",
":",
"idy",
"=",
"idy",
"if",
"idy",
"is",
"not",
"None",
"else",
"len",
"(",
"self",
".",
"body",
")",
"-",
"1",
"idx",
"=",
"i... | 53.333333 | 10.833333 |
def update_attr(self, attr):
"""Update input attr in self.
Return list of attributes with changed values.
"""
changed_attr = []
for key, value in attr.items():
if value is None:
continue
if getattr(self, "_{0}".format(key), None) != value:... | [
"def",
"update_attr",
"(",
"self",
",",
"attr",
")",
":",
"changed_attr",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"attr",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"continue",
"if",
"getattr",
"(",
"self",
",",
"\"_{0}... | 36.714286 | 14.428571 |
async def invoke(self, context):
"""Claims and processes Taskcluster work.
Args:
context (scriptworker.context.Context): context of worker
Returns: status code of build
"""
try:
# Note: claim_work(...) might not be safely interruptible! See
... | [
"async",
"def",
"invoke",
"(",
"self",
",",
"context",
")",
":",
"try",
":",
"# Note: claim_work(...) might not be safely interruptible! See",
"# https://bugzilla.mozilla.org/show_bug.cgi?id=1524069",
"tasks",
"=",
"await",
"self",
".",
"_run_cancellable",
"(",
"claim_work",
... | 48.357143 | 27.880952 |
def _compute_centers(self, X, sparse, rs):
"""Generate centers, then compute tau, dF and dN vals"""
super(GRBFRandomLayer, self)._compute_centers(X, sparse, rs)
centers = self.components_['centers']
sorted_distances = np.sort(squareform(pdist(centers)))
self.dF_vals = sorted_di... | [
"def",
"_compute_centers",
"(",
"self",
",",
"X",
",",
"sparse",
",",
"rs",
")",
":",
"super",
"(",
"GRBFRandomLayer",
",",
"self",
")",
".",
"_compute_centers",
"(",
"X",
",",
"sparse",
",",
"rs",
")",
"centers",
"=",
"self",
".",
"components_",
"[",
... | 35.894737 | 20 |
def epochs(self):
"""Get epochs as generator
Returns
-------
list of dict
each epoch is defined by start_time and end_time (in s in reference
to the start of the recordings) and a string of the sleep stage,
and a string of the signal quality.
... | [
"def",
"epochs",
"(",
"self",
")",
":",
"if",
"self",
".",
"rater",
"is",
"None",
":",
"raise",
"IndexError",
"(",
"'You need to have at least one rater'",
")",
"for",
"one_epoch",
"in",
"self",
".",
"rater",
".",
"iterfind",
"(",
"'stages/epoch'",
")",
":",... | 37.259259 | 23.148148 |
def pathsplit(value, sep=os.pathsep):
'''
Get enviroment PATH elements as list.
This function only cares about spliting across OSes.
:param value: path string, as given by os.environ['PATH']
:type value: str
:param sep: PATH separator, defaults to os.pathsep
:type sep: str
:yields: eve... | [
"def",
"pathsplit",
"(",
"value",
",",
"sep",
"=",
"os",
".",
"pathsep",
")",
":",
"for",
"part",
"in",
"value",
".",
"split",
"(",
"sep",
")",
":",
"if",
"part",
"[",
":",
"1",
"]",
"==",
"part",
"[",
"-",
"1",
":",
"]",
"==",
"'\"'",
"or",
... | 28.941176 | 21.058824 |
def detect_credentials(config_name, extra_environ=None, filenames=None,
aws_profile_name=None, default_value=Ellipsis):
'''
detect_credentials(config_name) attempts to locate Amazon S3 Bucket credentials from the given
configuration item config_name.
The following optional argu... | [
"def",
"detect_credentials",
"(",
"config_name",
",",
"extra_environ",
"=",
"None",
",",
"filenames",
"=",
"None",
",",
"aws_profile_name",
"=",
"None",
",",
"default_value",
"=",
"Ellipsis",
")",
":",
"# Check the config first:",
"if",
"config_name",
"is",
"not",... | 59.877778 | 28.344444 |
def wait_until(obj, att, desired, callback=None, interval=5, attempts=0,
verbose=False, verbose_atts=None):
"""
When changing the state of an object, it will commonly be in a transitional
state until the change is complete. This will reload the object every
`interval` seconds, and check its `att... | [
"def",
"wait_until",
"(",
"obj",
",",
"att",
",",
"desired",
",",
"callback",
"=",
"None",
",",
"interval",
"=",
"5",
",",
"attempts",
"=",
"0",
",",
"verbose",
"=",
"False",
",",
"verbose_atts",
"=",
"None",
")",
":",
"if",
"callback",
":",
"waiter"... | 57.686275 | 30.235294 |
def get_jwt_secret():
"""
Get the JWT secret
:return: str
"""
secret_key = __options__.get("jwt_secret") or config("JWT_SECRET") or config("SECRET_KEY")
if not secret_key:
raise exceptions.AuthError("Missing config JWT/SECRET_KEY")
return secret_key | [
"def",
"get_jwt_secret",
"(",
")",
":",
"secret_key",
"=",
"__options__",
".",
"get",
"(",
"\"jwt_secret\"",
")",
"or",
"config",
"(",
"\"JWT_SECRET\"",
")",
"or",
"config",
"(",
"\"SECRET_KEY\"",
")",
"if",
"not",
"secret_key",
":",
"raise",
"exceptions",
"... | 30.777778 | 19.888889 |
def atlas_peer_getinfo( peer_hostport, timeout=None, peer_table=None ):
"""
Get host info
Return the rpc_getinfo() response on success
Return None on error
"""
if timeout is None:
timeout = atlas_ping_timeout()
host, port = url_to_host_port( peer_hostport )
RPC = get_rpc_client... | [
"def",
"atlas_peer_getinfo",
"(",
"peer_hostport",
",",
"timeout",
"=",
"None",
",",
"peer_table",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"atlas_ping_timeout",
"(",
")",
"host",
",",
"port",
"=",
"url_to_host_port",
"(",
... | 40.234568 | 30.283951 |
def req(self, method, params=()):
"""send request to ppcoind"""
response = self.session.post(
self.url,
data=json.dumps({"method": method, "params": params, "jsonrpc": "1.1"}),
).json()
if response["error"] is not None:
return response["error"]
... | [
"def",
"req",
"(",
"self",
",",
"method",
",",
"params",
"=",
"(",
")",
")",
":",
"response",
"=",
"self",
".",
"session",
".",
"post",
"(",
"self",
".",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"\"method\"",
":",
"method",
",",
... | 29.583333 | 17.666667 |
def get_all_lower(self):
"""Return all parent GO IDs through both reverse 'is_a' and all relationships."""
all_lower = set()
for lower in self.get_goterms_lower():
all_lower.add(lower.item_id)
all_lower |= lower.get_all_lower()
return all_lower | [
"def",
"get_all_lower",
"(",
"self",
")",
":",
"all_lower",
"=",
"set",
"(",
")",
"for",
"lower",
"in",
"self",
".",
"get_goterms_lower",
"(",
")",
":",
"all_lower",
".",
"add",
"(",
"lower",
".",
"item_id",
")",
"all_lower",
"|=",
"lower",
".",
"get_a... | 42 | 8.428571 |
def extract_subset(self, input_data_tiles=None, out_tile=None):
"""
Extract subset from multiple tiles.
input_data_tiles : list of (``Tile``, process data) tuples
out_tile : ``Tile``
Returns
-------
NumPy array or list of features.
"""
if self.ME... | [
"def",
"extract_subset",
"(",
"self",
",",
"input_data_tiles",
"=",
"None",
",",
"out_tile",
"=",
"None",
")",
":",
"if",
"self",
".",
"METADATA",
"[",
"\"data_type\"",
"]",
"==",
"\"raster\"",
":",
"mosaic",
"=",
"create_mosaic",
"(",
"input_data_tiles",
")... | 34.586207 | 15.896552 |
def ko_bindings(model):
"""
Given a model, returns the Knockout data bindings.
"""
try:
if isinstance(model, str):
modelName = model
else:
modelName = model.__class__.__name__
modelBindingsString = "ko.applyBindings(new " + modelName + "ViewModel(), $('#... | [
"def",
"ko_bindings",
"(",
"model",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"model",
",",
"str",
")",
":",
"modelName",
"=",
"model",
"else",
":",
"modelName",
"=",
"model",
".",
"__class__",
".",
"__name__",
"modelBindingsString",
"=",
"\"ko.applyB... | 26.058824 | 22.058824 |
def add(message, level=0, user=None, message_short=None,log_file_name='%s/pyscada_daemon.log' % settings.BASE_DIR,):
"""
add a new massage/error notice to the log
<0 - Debug
1 - Emergency
2 - Critical
3 - Errors
4 - Alerts
5 - Warnings
6 - Notification (webnotice)
7 - Information... | [
"def",
"add",
"(",
"message",
",",
"level",
"=",
"0",
",",
"user",
"=",
"None",
",",
"message_short",
"=",
"None",
",",
"log_file_name",
"=",
"'%s/pyscada_daemon.log'",
"%",
"settings",
".",
"BASE_DIR",
",",
")",
":",
"#if not access(path.dirname(self.log_file_n... | 32.388889 | 22 |
def reset_clipboard(self):
""" Resets the clipboard, so that old elements do not pollute the new selection that is copied into the
clipboard.
:return:
"""
# reset selections
for state_element_attr in ContainerState.state_element_attrs:
self.model_copies[s... | [
"def",
"reset_clipboard",
"(",
"self",
")",
":",
"# reset selections",
"for",
"state_element_attr",
"in",
"ContainerState",
".",
"state_element_attrs",
":",
"self",
".",
"model_copies",
"[",
"state_element_attr",
"]",
"=",
"[",
"]",
"# reset parent state_id the copied e... | 34.642857 | 18.785714 |
def get(tag: {str, 'Language'}, normalize=True) -> 'Language':
"""
Create a Language object from a language tag string.
If normalize=True, non-standard or overlong tags will be replaced as
they're interpreted. This is recommended.
Here are several examples of language codes, wh... | [
"def",
"get",
"(",
"tag",
":",
"{",
"str",
",",
"'Language'",
"}",
",",
"normalize",
"=",
"True",
")",
"->",
"'Language'",
":",
"if",
"isinstance",
"(",
"tag",
",",
"Language",
")",
":",
"if",
"not",
"normalize",
":",
"# shortcut: we have the tag already",... | 39.39759 | 22.542169 |
def smart_cast2(var):
r"""
if the variable is a string tries to cast it to a reasonable value.
maybe can just use eval. FIXME: funcname
Args:
var (unknown):
Returns:
unknown: some var
CommandLine:
python -m utool.util_type --test-smart_cast2
Example:
>>> #... | [
"def",
"smart_cast2",
"(",
"var",
")",
":",
"if",
"var",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"var",
",",
"six",
".",
"string_types",
")",
":",
"castvar",
"=",
"None",
"lower",
"=",
"var",
".",
"lower",
"(",
")",
"if",
"low... | 31.053571 | 18.178571 |
def set_cookie(self, key, value, expiration='Infinity', path='/', domain='', secure=False):
"""
expiration (int): seconds after with the cookie automatically gets deleted
"""
secure = 'true' if secure else 'false'
self.app_instance.execute_javascript("""
var sKey = "... | [
"def",
"set_cookie",
"(",
"self",
",",
"key",
",",
"value",
",",
"expiration",
"=",
"'Infinity'",
",",
"path",
"=",
"'/'",
",",
"domain",
"=",
"''",
",",
"secure",
"=",
"False",
")",
":",
"secure",
"=",
"'true'",
"if",
"secure",
"else",
"'false'",
"s... | 50.064516 | 21.032258 |
def all_pairs(sets, similarity_func_name="jaccard",
similarity_threshold=0.5):
"""Find all pairs of sets with similarity greater than a threshold.
This is an implementation of the All-Pair-Binary algorithm in the paper
"Scaling Up All Pairs Similarity Search" by Bayardo et al., with
position fil... | [
"def",
"all_pairs",
"(",
"sets",
",",
"similarity_func_name",
"=",
"\"jaccard\"",
",",
"similarity_threshold",
"=",
"0.5",
")",
":",
"if",
"not",
"isinstance",
"(",
"sets",
",",
"list",
")",
"or",
"len",
"(",
"sets",
")",
"==",
"0",
":",
"raise",
"ValueE... | 47.898305 | 19.118644 |
def _addUserToGroup(self, username, group="Clients"):
"""Add user to the goup
"""
portal_groups = api.portal.get_tool("portal_groups")
group = portal_groups.getGroupById('Clients')
group.addMember(username) | [
"def",
"_addUserToGroup",
"(",
"self",
",",
"username",
",",
"group",
"=",
"\"Clients\"",
")",
":",
"portal_groups",
"=",
"api",
".",
"portal",
".",
"get_tool",
"(",
"\"portal_groups\"",
")",
"group",
"=",
"portal_groups",
".",
"getGroupById",
"(",
"'Clients'"... | 40.166667 | 8.833333 |
def query_domain(self, domain, typenames, domainquerytype='list', count=False):
"""
Query by property domain values
"""
objects = self._get_repo_filter(Layer.objects)
if domainquerytype == 'range':
return [tuple(objects.aggregate(Min(domain), Max(domain)).values())]... | [
"def",
"query_domain",
"(",
"self",
",",
"domain",
",",
"typenames",
",",
"domainquerytype",
"=",
"'list'",
",",
"count",
"=",
"False",
")",
":",
"objects",
"=",
"self",
".",
"_get_repo_filter",
"(",
"Layer",
".",
"objects",
")",
"if",
"domainquerytype",
"... | 37.6 | 21.733333 |
def is_in_plane(self, pp, dist_tolerance):
"""
Determines if point pp is in the plane within the tolerance dist_tolerance
:param pp: point to be tested
:param dist_tolerance: tolerance on the distance to the plane within which point pp is considered in the plane
:return: True if ... | [
"def",
"is_in_plane",
"(",
"self",
",",
"pp",
",",
"dist_tolerance",
")",
":",
"return",
"np",
".",
"abs",
"(",
"np",
".",
"dot",
"(",
"self",
".",
"normal_vector",
",",
"pp",
")",
"+",
"self",
".",
"_coefficients",
"[",
"3",
"]",
")",
"<=",
"dist_... | 57 | 25 |
def find_mean_vector(*args, **kwargs):
"""
Returns the mean vector for a set of measurments. By default, this expects
the input to be plunges and bearings, but the type of input can be
controlled through the ``measurement`` kwarg.
Parameters
----------
*args : 2 or 3 sequences of measureme... | [
"def",
"find_mean_vector",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lon",
",",
"lat",
"=",
"_convert_measurements",
"(",
"args",
",",
"kwargs",
".",
"get",
"(",
"'measurement'",
",",
"'lines'",
")",
")",
"vector",
",",
"r_value",
"=",
"ste... | 41.434783 | 23.478261 |
def calc_paired_insert_stats(in_bam, nsample=1000000):
"""Retrieve statistics for paired end read insert distances.
"""
dists = []
n = 0
with pysam.Samfile(in_bam, "rb") as in_pysam:
for read in in_pysam:
if read.is_proper_pair and read.is_read1:
n += 1
... | [
"def",
"calc_paired_insert_stats",
"(",
"in_bam",
",",
"nsample",
"=",
"1000000",
")",
":",
"dists",
"=",
"[",
"]",
"n",
"=",
"0",
"with",
"pysam",
".",
"Samfile",
"(",
"in_bam",
",",
"\"rb\"",
")",
"as",
"in_pysam",
":",
"for",
"read",
"in",
"in_pysam... | 33.692308 | 11.923077 |
def create_sysdig_capture(self, hostname, capture_name, duration, capture_filter='', folder='/'):
'''**Description**
Create a new sysdig capture. The capture will be immediately started.
**Arguments**
- **hostname**: the hostname of the instrumented host where the capture will b... | [
"def",
"create_sysdig_capture",
"(",
"self",
",",
"hostname",
",",
"capture_name",
",",
"duration",
",",
"capture_filter",
"=",
"''",
",",
"folder",
"=",
"'/'",
")",
":",
"res",
"=",
"self",
".",
"get_connected_agents",
"(",
")",
"if",
"not",
"res",
"[",
... | 37.255814 | 25.348837 |
def rnaseq_prep_samples(config, run_info_yaml, parallel, dirs, samples):
"""
organizes RNA-seq and small-RNAseq samples, converting from BAM if
necessary and trimming if necessary
"""
pipeline = dd.get_in_samples(samples, dd.get_analysis)
trim_reads_set = any([tz.get_in(["algorithm", "trim_reads... | [
"def",
"rnaseq_prep_samples",
"(",
"config",
",",
"run_info_yaml",
",",
"parallel",
",",
"dirs",
",",
"samples",
")",
":",
"pipeline",
"=",
"dd",
".",
"get_in_samples",
"(",
"samples",
",",
"dd",
".",
"get_analysis",
")",
"trim_reads_set",
"=",
"any",
"(",
... | 52.2 | 22.28 |
def cursor_up(self, count=None):
"""Move cursor up the indicated # of lines in same column.
Cursor stops at top margin.
:param int count: number of lines to skip.
"""
top, _bottom = self.margins or Margins(0, self.lines - 1)
self.cursor.y = max(self.cursor.y - (count or ... | [
"def",
"cursor_up",
"(",
"self",
",",
"count",
"=",
"None",
")",
":",
"top",
",",
"_bottom",
"=",
"self",
".",
"margins",
"or",
"Margins",
"(",
"0",
",",
"self",
".",
"lines",
"-",
"1",
")",
"self",
".",
"cursor",
".",
"y",
"=",
"max",
"(",
"se... | 40.125 | 13.75 |
def is_instance_throughput_too_low(self, inst_id):
"""
Return whether the throughput of the master instance is greater than the
acceptable threshold
"""
r = self.instance_throughput_ratio(inst_id)
if r is None:
logger.debug("{} instance {} throughput is not "
... | [
"def",
"is_instance_throughput_too_low",
"(",
"self",
",",
"inst_id",
")",
":",
"r",
"=",
"self",
".",
"instance_throughput_ratio",
"(",
"inst_id",
")",
"if",
"r",
"is",
"None",
":",
"logger",
".",
"debug",
"(",
"\"{} instance {} throughput is not \"",
"\"measurab... | 43.444444 | 20.222222 |
def get_source_code(items):
"""
Extract source code of given items, and concatenate and dedent it.
"""
sources = []
prev_class_name = None
for func in items:
try:
lines, lineno = inspect.getsourcelines(func)
except TypeError:
continue
if not line... | [
"def",
"get_source_code",
"(",
"items",
")",
":",
"sources",
"=",
"[",
"]",
"prev_class_name",
"=",
"None",
"for",
"func",
"in",
"items",
":",
"try",
":",
"lines",
",",
"lineno",
"=",
"inspect",
".",
"getsourcelines",
"(",
"func",
")",
"except",
"TypeErr... | 28.75 | 17.1 |
def process(self):
"""Periodic nonblocking processes"""
super(NativeBLEVirtualInterface, self).process()
if (not self._stream_sm_running) and (not self.reports.empty()):
self._stream_data()
if (not self._trace_sm_running) and (not self.traces.empty()):
self._se... | [
"def",
"process",
"(",
"self",
")",
":",
"super",
"(",
"NativeBLEVirtualInterface",
",",
"self",
")",
".",
"process",
"(",
")",
"if",
"(",
"not",
"self",
".",
"_stream_sm_running",
")",
"and",
"(",
"not",
"self",
".",
"reports",
".",
"empty",
"(",
")",... | 32.1 | 23.9 |
def _get_artifact_context(run, file_type):
"""Gets the artifact details for the given run and file_type."""
sha1sum = None
image_file = False
log_file = False
config_file = False
if request.path == '/image':
image_file = True
if file_type == 'before':
sha1sum = run.r... | [
"def",
"_get_artifact_context",
"(",
"run",
",",
"file_type",
")",
":",
"sha1sum",
"=",
"None",
"image_file",
"=",
"False",
"log_file",
"=",
"False",
"config_file",
"=",
"False",
"if",
"request",
".",
"path",
"==",
"'/image'",
":",
"image_file",
"=",
"True",... | 28.567568 | 13 |
def match(self, command_context=None, **command_env):
""" Check if context request is compatible with adapters specification. True - if compatible,
False - otherwise
:param command_context: context to check
:param command_env: command environment
:return: bool
"""
spec = self.specification()
if command... | [
"def",
"match",
"(",
"self",
",",
"command_context",
"=",
"None",
",",
"*",
"*",
"command_env",
")",
":",
"spec",
"=",
"self",
".",
"specification",
"(",
")",
"if",
"command_context",
"is",
"None",
"and",
"spec",
"is",
"None",
":",
"return",
"True",
"e... | 33 | 13.857143 |
def get_store_profile_by_id(cls, store_profile_id, **kwargs):
"""Find StoreProfile
Return single instance of StoreProfile by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_store_p... | [
"def",
"get_store_profile_by_id",
"(",
"cls",
",",
"store_profile_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_get_store_pro... | 44.095238 | 21.857143 |
def prototype(self, name, argtypes, restype=None):
"""Define argument / return types for the specified C function"""
function = self.function(name)
function.argtypes = argtypes
if restype:
function.restype = restype | [
"def",
"prototype",
"(",
"self",
",",
"name",
",",
"argtypes",
",",
"restype",
"=",
"None",
")",
":",
"function",
"=",
"self",
".",
"function",
"(",
"name",
")",
"function",
".",
"argtypes",
"=",
"argtypes",
"if",
"restype",
":",
"function",
".",
"rest... | 42.333333 | 6.5 |
def read_umi_tools(filename: PathLike, dtype: str='float32') -> AnnData:
"""Read a gzipped condensed count matrix from umi_tools.
Parameters
----------
filename
File name to read from.
"""
# import pandas for conversion of a dict of dicts into a matrix
# import gzip to read a gzippe... | [
"def",
"read_umi_tools",
"(",
"filename",
":",
"PathLike",
",",
"dtype",
":",
"str",
"=",
"'float32'",
")",
"->",
"AnnData",
":",
"# import pandas for conversion of a dict of dicts into a matrix",
"# import gzip to read a gzipped file :-)",
"import",
"gzip",
"from",
"pandas... | 35.777778 | 22.259259 |
def from_filename(cls, filename, sync_from_start=True):
"""
Create a `Lexer` from a filename.
"""
# Inline imports: the Pygments dependency is optional!
from pygments.util import ClassNotFound
from pygments.lexers import get_lexer_for_filename
try:
py... | [
"def",
"from_filename",
"(",
"cls",
",",
"filename",
",",
"sync_from_start",
"=",
"True",
")",
":",
"# Inline imports: the Pygments dependency is optional!",
"from",
"pygments",
".",
"util",
"import",
"ClassNotFound",
"from",
"pygments",
".",
"lexers",
"import",
"get_... | 36.642857 | 17.071429 |
def validate(self, value, add_comments=False, schema_name="map"):
"""
verbose - also return the jsonschema error details
"""
validator = self.get_schema_validator(schema_name)
error_messages = []
if isinstance(value, list):
for d in value:
er... | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"add_comments",
"=",
"False",
",",
"schema_name",
"=",
"\"map\"",
")",
":",
"validator",
"=",
"self",
".",
"get_schema_validator",
"(",
"schema_name",
")",
"error_messages",
"=",
"[",
"]",
"if",
"isinstance"... | 34.066667 | 23.133333 |
def sendMessage(self, data):
"""
Send websocket data frame to the client.
If data is a unicode object then the frame is sent as Text.
If the data is a bytearray object then the frame is sent as Binary.
"""
opcode = BINARY
if _check_unicode(data):
... | [
"def",
"sendMessage",
"(",
"self",
",",
"data",
")",
":",
"opcode",
"=",
"BINARY",
"if",
"_check_unicode",
"(",
"data",
")",
":",
"opcode",
"=",
"TEXT",
"self",
".",
"_sendMessage",
"(",
"False",
",",
"opcode",
",",
"data",
")"
] | 34.363636 | 16.363636 |
def import_submodules(name, submodules=None):
"""Import all submodules for a package/module name"""
sys.path.insert(0, name)
if submodules:
for submodule in submodules:
import_string('{0}.{1}'.format(name, submodule))
else:
for item in pkgutil.walk_packages([name]):
... | [
"def",
"import_submodules",
"(",
"name",
",",
"submodules",
"=",
"None",
")",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"name",
")",
"if",
"submodules",
":",
"for",
"submodule",
"in",
"submodules",
":",
"import_string",
"(",
"'{0}.{1}'",
"."... | 40.111111 | 13.555556 |
def next_release(major=False, minor=False, patch=True):
"""Get next release version (by major, minor or patch)"""
import semantic_version
prev = run('git describe --abbrev=0 --tags', warn=True, hide=True).stdout or '0.0.0'
ver = semantic_version.Version.coerce(prev.strip())
print('current version:... | [
"def",
"next_release",
"(",
"major",
"=",
"False",
",",
"minor",
"=",
"False",
",",
"patch",
"=",
"True",
")",
":",
"import",
"semantic_version",
"prev",
"=",
"run",
"(",
"'git describe --abbrev=0 --tags'",
",",
"warn",
"=",
"True",
",",
"hide",
"=",
"True... | 35.052632 | 18.684211 |
def get_property_names(self, is_allprop):
"""Return list of supported property names in Clark Notation.
See DAVResource.get_property_names()
"""
# Let base class implementation add supported live and dead properties
propNameList = super(VirtualResource, self).get_property_names(... | [
"def",
"get_property_names",
"(",
"self",
",",
"is_allprop",
")",
":",
"# Let base class implementation add supported live and dead properties",
"propNameList",
"=",
"super",
"(",
"VirtualResource",
",",
"self",
")",
".",
"get_property_names",
"(",
"is_allprop",
")",
"# A... | 48.6 | 19.2 |
def check(id_):
"""Check bibdocs."""
BibRecDocs, BibDoc = _import_bibdoc()
try:
BibDoc(id_).list_all_files()
except Exception:
click.secho("BibDoc {0} failed check.".format(id_), fg='red') | [
"def",
"check",
"(",
"id_",
")",
":",
"BibRecDocs",
",",
"BibDoc",
"=",
"_import_bibdoc",
"(",
")",
"try",
":",
"BibDoc",
"(",
"id_",
")",
".",
"list_all_files",
"(",
")",
"except",
"Exception",
":",
"click",
".",
"secho",
"(",
"\"BibDoc {0} failed check.\... | 26.75 | 18.75 |
def set_command_attributes(self, name, attributes):
""" Sets the xml attributes of a specified command. """
if self.command_exists(name):
command = self.commands.get(name)
command['attributes'] = attributes | [
"def",
"set_command_attributes",
"(",
"self",
",",
"name",
",",
"attributes",
")",
":",
"if",
"self",
".",
"command_exists",
"(",
"name",
")",
":",
"command",
"=",
"self",
".",
"commands",
".",
"get",
"(",
"name",
")",
"command",
"[",
"'attributes'",
"]"... | 48.4 | 5 |
def get_environ(self, key, default=None, cast=None):
"""Get value from environment variable using os.environ.get
:param key: The name of the setting value, will always be upper case
:param default: In case of not found it will be returned
:param cast: Should cast in to @int, @float, @bo... | [
"def",
"get_environ",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"cast",
"=",
"None",
")",
":",
"key",
"=",
"key",
".",
"upper",
"(",
")",
"data",
"=",
"self",
".",
"environ",
".",
"get",
"(",
"key",
",",
"default",
")",
"if",
"... | 42.058824 | 16.058824 |
def create_namespaced_deployment_rollback(self, name, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_deployment_rollback # noqa: E501
create rollback of a Deployment # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP requ... | [
"def",
"create_namespaced_deployment_rollback",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_re... | 66.653846 | 39.384615 |
def get_scrollbar_position_height(self):
"""Return the pixel span height of the scrollbar area in which
the slider handle may move"""
vsb = self.editor.verticalScrollBar()
style = vsb.style()
opt = QStyleOptionSlider()
vsb.initStyleOption(opt)
# Get the area in w... | [
"def",
"get_scrollbar_position_height",
"(",
"self",
")",
":",
"vsb",
"=",
"self",
".",
"editor",
".",
"verticalScrollBar",
"(",
")",
"style",
"=",
"vsb",
".",
"style",
"(",
")",
"opt",
"=",
"QStyleOptionSlider",
"(",
")",
"vsb",
".",
"initStyleOption",
"(... | 38.692308 | 13.076923 |
def addMenuLabel(menu, text):
"""Adds a QLabel contaning text to the given menu"""
qaw = QWidgetAction(menu)
lab = QLabel(text, menu)
qaw.setDefaultWidget(lab)
lab.setAlignment(Qt.AlignCenter)
lab.setFrameShape(QFrame.StyledPanel)
lab.setFrameShadow(QFrame.Sunken)
menu.addAction(qaw)
... | [
"def",
"addMenuLabel",
"(",
"menu",
",",
"text",
")",
":",
"qaw",
"=",
"QWidgetAction",
"(",
"menu",
")",
"lab",
"=",
"QLabel",
"(",
"text",
",",
"menu",
")",
"qaw",
".",
"setDefaultWidget",
"(",
"lab",
")",
"lab",
".",
"setAlignment",
"(",
"Qt",
"."... | 32.2 | 9.6 |
def read(self, vals):
"""Read values.
Args:
vals (list): list of strings representing values
"""
i = 0
if len(vals[i]) == 0:
self.ground_temperature_depth = None
else:
self.ground_temperature_depth = vals[i]
i += 1
if ... | [
"def",
"read",
"(",
"self",
",",
"vals",
")",
":",
"i",
"=",
"0",
"if",
"len",
"(",
"vals",
"[",
"i",
"]",
")",
"==",
"0",
":",
"self",
".",
"ground_temperature_depth",
"=",
"None",
"else",
":",
"self",
".",
"ground_temperature_depth",
"=",
"vals",
... | 33.761364 | 21.034091 |
def actualize (self, scanner = None):
""" Generates all the actual targets and sets up build actions for
this target.
If 'scanner' is specified, creates an additional target
with the same location as actual target, which will depend on the
actual target and be as... | [
"def",
"actualize",
"(",
"self",
",",
"scanner",
"=",
"None",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"scanner",
"import",
"Scanner",
"assert",
"scanner",
"is",
"None",
"or",
"isinstance",
"(",
"scanner",
",",
"Scanner",
")",
"actual_name",
"=",
"... | 36.435897 | 25.384615 |
def update_edge_keys(G):
"""
Update the keys of edges that share a u, v with another edge but differ in
geometry. For example, two one-way streets from u to v that bow away from
each other as separate streets, rather than opposite direction edges of a
single street.
Parameters
--------... | [
"def",
"update_edge_keys",
"(",
"G",
")",
":",
"# identify all the edges that are duplicates based on a sorted combination",
"# of their origin, destination, and key. that is, edge uv will match edge vu",
"# as a duplicate, but only if they have the same key",
"edges",
"=",
"graph_to_gdfs",
... | 42.654545 | 26.254545 |
def dlogpdf_dlink(self, link_f, y, Y_metadata=None):
"""
Gradient of the log likelihood function at y, given link(f) w.r.t link(f)
.. math::
\\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)} = \\beta (\\log \\beta y_{i}) - \\Psi(\\alpha_{i})\\beta\\\\
\\alpha_{i} = \... | [
"def",
"dlogpdf_dlink",
"(",
"self",
",",
"link_f",
",",
"y",
",",
"Y_metadata",
"=",
"None",
")",
":",
"grad",
"=",
"self",
".",
"beta",
"*",
"np",
".",
"log",
"(",
"self",
".",
"beta",
"*",
"y",
")",
"-",
"special",
".",
"psi",
"(",
"self",
"... | 42.47619 | 29.047619 |
def run_mp(songs):
"""
Concurrently calls get_lyrics to fetch the lyrics of a large list of songs.
"""
stats = Stats()
if CONFIG['debug']:
good = open('found', 'w')
bad = open('notfound', 'w')
logger.debug('Launching a pool of %d processes\n', CONFIG['jobcount'])
chunksize =... | [
"def",
"run_mp",
"(",
"songs",
")",
":",
"stats",
"=",
"Stats",
"(",
")",
"if",
"CONFIG",
"[",
"'debug'",
"]",
":",
"good",
"=",
"open",
"(",
"'found'",
",",
"'w'",
")",
"bad",
"=",
"open",
"(",
"'notfound'",
",",
"'w'",
")",
"logger",
".",
"debu... | 32.085714 | 20.257143 |
def write(self, filename=None):
"""Write array to xvg file *filename* in NXY format.
.. Note:: Only plain files working at the moment, not compressed.
"""
self._init_filename(filename)
with utilities.openany(self.real_filename, 'w') as xvg:
xvg.write("# xmgrace compa... | [
"def",
"write",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"self",
".",
"_init_filename",
"(",
"filename",
")",
"with",
"utilities",
".",
"openany",
"(",
"self",
".",
"real_filename",
",",
"'w'",
")",
"as",
"xvg",
":",
"xvg",
".",
"write",
... | 48.692308 | 19.384615 |
def close(self, code=3000, message='Go away!'):
""" Close session.
@param code: Closing code
@param message: Closing message
"""
if self.state != SESSION_STATE.CLOSED:
# Notify handler
if self.handler is not None:
self.handler.send_pack(p... | [
"def",
"close",
"(",
"self",
",",
"code",
"=",
"3000",
",",
"message",
"=",
"'Go away!'",
")",
":",
"if",
"self",
".",
"state",
"!=",
"SESSION_STATE",
".",
"CLOSED",
":",
"# Notify handler",
"if",
"self",
".",
"handler",
"is",
"not",
"None",
":",
"self... | 30 | 14.846154 |
def infix(self, node, children):
'infix = "(" expr operator expr ")"'
_, expr1, operator, expr2, _ = children
return operator(expr1, expr2) | [
"def",
"infix",
"(",
"self",
",",
"node",
",",
"children",
")",
":",
"_",
",",
"expr1",
",",
"operator",
",",
"expr2",
",",
"_",
"=",
"children",
"return",
"operator",
"(",
"expr1",
",",
"expr2",
")"
] | 40 | 5.5 |
def should_skip_file(name):
"""
Checks if a file should be skipped based on its name.
If it should be skipped, returns the reason, otherwise returns
None.
"""
if name.startswith('.'):
return 'Skipping hidden file %(filename)s'
if name.endswith('~') or name.endswith('.bak'):
... | [
"def",
"should_skip_file",
"(",
"name",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'.'",
")",
":",
"return",
"'Skipping hidden file %(filename)s'",
"if",
"name",
".",
"endswith",
"(",
"'~'",
")",
"or",
"name",
".",
"endswith",
"(",
"'.bak'",
")",
":"... | 38 | 16.555556 |
def get_default_config_help(self):
"""
Returns the help text for the configuration options for this handler
"""
config = super(NullHandler, self).get_default_config_help()
config.update({
})
return config | [
"def",
"get_default_config_help",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"NullHandler",
",",
"self",
")",
".",
"get_default_config_help",
"(",
")",
"config",
".",
"update",
"(",
"{",
"}",
")",
"return",
"config"
] | 25.3 | 21.5 |
def solve(self):
"""
Solve the OLL. Returns an Formula.
"""
if not isinstance(self.cube, Cube):
raise ValueError("Use Solver.feed(cube) to feed the cube to solver.")
self.recognise()
self.cube(algo_dict[self.case])
return algo_dict[self.case] | [
"def",
"solve",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"cube",
",",
"Cube",
")",
":",
"raise",
"ValueError",
"(",
"\"Use Solver.feed(cube) to feed the cube to solver.\"",
")",
"self",
".",
"recognise",
"(",
")",
"self",
".",
"cub... | 33.555556 | 10.222222 |
def _set_raw_return(self, sep):
"""Set the output raw return section
:param sep: the separator of current style
"""
raw = ''
if self.dst.style['out'] == 'numpydoc':
raw += '\n'
spaces = ' ' * 4
with_space = lambda s: '\n'.join([self.docs['out... | [
"def",
"_set_raw_return",
"(",
"self",
",",
"sep",
")",
":",
"raw",
"=",
"''",
"if",
"self",
".",
"dst",
".",
"style",
"[",
"'out'",
"]",
"==",
"'numpydoc'",
":",
"raw",
"+=",
"'\\n'",
"spaces",
"=",
"' '",
"*",
"4",
"with_space",
"=",
"lambda",
"s... | 54.47619 | 24.988095 |
def check_solver(self, image_x, image_y, kwargs_lens):
"""
returns the precision of the solver to match the image position
:param kwargs_lens: full lens model (including solved parameters)
:param image_x: point source in image
:param image_y: point source in image
:retur... | [
"def",
"check_solver",
"(",
"self",
",",
"image_x",
",",
"image_y",
",",
"kwargs_lens",
")",
":",
"source_x",
",",
"source_y",
"=",
"self",
".",
"_lensModel",
".",
"ray_shooting",
"(",
"image_x",
",",
"image_y",
",",
"kwargs_lens",
")",
"dist",
"=",
"np",
... | 50.833333 | 25.833333 |
def wsgi_wrap(app):
'''
Wraps a standard wsgi application e.g.:
def app(environ, start_response)
It intercepts the start_response callback and grabs the results from it
so it can return the status, headers, and body as a tuple
'''
@wraps(app)
def wrapped(environ, start_response):
... | [
"def",
"wsgi_wrap",
"(",
"app",
")",
":",
"@",
"wraps",
"(",
"app",
")",
"def",
"wrapped",
"(",
"environ",
",",
"start_response",
")",
":",
"status_headers",
"=",
"[",
"None",
",",
"None",
"]",
"def",
"_start_response",
"(",
"status",
",",
"headers",
"... | 35.9375 | 15.8125 |
def override_tab_value(data, headers, new_value=' ', **_):
"""Override tab values in the *data* with *new_value*.
:param iterable data: An :term:`iterable` (e.g. list) of rows.
:param iterable headers: The column headers.
:param new_value: The new value to use for tab.
:return: The processed dat... | [
"def",
"override_tab_value",
"(",
"data",
",",
"headers",
",",
"new_value",
"=",
"' '",
",",
"*",
"*",
"_",
")",
":",
"return",
"(",
"(",
"[",
"v",
".",
"replace",
"(",
"'\\t'",
",",
"new_value",
")",
"if",
"isinstance",
"(",
"v",
",",
"text_type"... | 37.846154 | 17.923077 |
def _find_field(cls, field, doc):
"""Find the field in the document which matches the given field.
The field may be in dot notation, eg "a.b.c". Returns a list with
a single tuple (path, field_value) or the empty list if the field
is not present.
"""
path = field.split("... | [
"def",
"_find_field",
"(",
"cls",
",",
"field",
",",
"doc",
")",
":",
"path",
"=",
"field",
".",
"split",
"(",
"\".\"",
")",
"try",
":",
"for",
"key",
"in",
"path",
":",
"doc",
"=",
"doc",
"[",
"key",
"]",
"return",
"[",
"(",
"path",
",",
"doc"... | 34 | 15.642857 |
def login():
"""
This route has two purposes. First, it is used by the user
to login. Second, it is used by the CAS to respond with the
`ticket` after the user logs in successfully.
When the user accesses this url, they are redirected to the CAS
to login. If the login was successful, the CAS wi... | [
"def",
"login",
"(",
")",
":",
"cas_token_session_key",
"=",
"current_app",
".",
"config",
"[",
"'CAS_TOKEN_SESSION_KEY'",
"]",
"redirect_url",
"=",
"create_cas_login_url",
"(",
"current_app",
".",
"config",
"[",
"'CAS_SERVER'",
"]",
",",
"current_app",
".",
"conf... | 41.121951 | 22.682927 |
def cumulative_sum(self):
"""
Return the cumulative sum of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
sum of all the elements preceding and including it. The SArray is
expected to be of numeric type (int, float), or a numeri... | [
"def",
"cumulative_sum",
"(",
"self",
")",
":",
"from",
".",
".",
"import",
"extensions",
"agg_op",
"=",
"\"__builtin__cum_sum__\"",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"builtin_cumulative_aggregate",
"(",
"agg_op",
")",
")"
] | 31.966667 | 22.166667 |
def create_rename_entry(
step: 'projects.ProjectStep',
insertion_index: int = None,
stash_path: str = None
) -> typing.Union[None, STEP_RENAME]:
"""
Creates a STEP_RENAME for the given ProjectStep instance
:param step:
The ProjectStep instance for which the STEP_RENAME will ... | [
"def",
"create_rename_entry",
"(",
"step",
":",
"'projects.ProjectStep'",
",",
"insertion_index",
":",
"int",
"=",
"None",
",",
"stash_path",
":",
"str",
"=",
"None",
")",
"->",
"typing",
".",
"Union",
"[",
"None",
",",
"STEP_RENAME",
"]",
":",
"project",
... | 29.226415 | 19.415094 |
def nonspeech_fragments(self):
"""
Iterates through the nonspeech fragments in the list
(which are sorted).
:rtype: generator of (int, :class:`~aeneas.syncmap.SyncMapFragment`)
"""
for i, fragment in enumerate(self.__fragments):
if fragment.fragment_type == S... | [
"def",
"nonspeech_fragments",
"(",
"self",
")",
":",
"for",
"i",
",",
"fragment",
"in",
"enumerate",
"(",
"self",
".",
"__fragments",
")",
":",
"if",
"fragment",
".",
"fragment_type",
"==",
"SyncMapFragment",
".",
"NONSPEECH",
":",
"yield",
"(",
"i",
",",
... | 37.2 | 16.6 |
def get_pkg_module_names(package_path):
"""Returns module filenames from package.
Args:
package_path: Path to Python package.
Returns:
A set of module filenames.
"""
module_names = set()
for fobj, modname, _ in pkgutil.iter_modules(path=[package_path]):
filename = os.pat... | [
"def",
"get_pkg_module_names",
"(",
"package_path",
")",
":",
"module_names",
"=",
"set",
"(",
")",
"for",
"fobj",
",",
"modname",
",",
"_",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"path",
"=",
"[",
"package_path",
"]",
")",
":",
"filename",
"=",
"os"... | 32.857143 | 15.285714 |
def _run_configure_script(self, script):
"""Run the script to install the Juju agent on the target machine.
:param str script: The script returned by the ProvisioningScript API
:raises: :class:`paramiko.ssh_exception.AuthenticationException`
if the upload fails
"""
... | [
"def",
"_run_configure_script",
"(",
"self",
",",
"script",
")",
":",
"_",
",",
"tmpFile",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"with",
"open",
"(",
"tmpFile",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"script",
")",
"try",
":"... | 30.026316 | 19.473684 |
def format_modified(self, modified, sep=" "):
"""Format modification date in UTC if it's not None.
@param modified: modification date in UTC
@ptype modified: datetime or None
@return: formatted date or empty string
@rtype: unicode
"""
if modified is not None:
... | [
"def",
"format_modified",
"(",
"self",
",",
"modified",
",",
"sep",
"=",
"\" \"",
")",
":",
"if",
"modified",
"is",
"not",
"None",
":",
"return",
"modified",
".",
"strftime",
"(",
"\"%Y-%m-%d{0}%H:%M:%S.%fZ\"",
".",
"format",
"(",
"sep",
")",
")",
"return"... | 40.1 | 10.4 |
def upgrade(self, flag):
"""Upgrade Slackware binary packages with new
"""
for pkg in self.binary:
try:
subprocess.call("upgradepkg {0} {1}".format(flag, pkg),
shell=True)
check = pkg[:-4].split("/")[-1]
... | [
"def",
"upgrade",
"(",
"self",
",",
"flag",
")",
":",
"for",
"pkg",
"in",
"self",
".",
"binary",
":",
"try",
":",
"subprocess",
".",
"call",
"(",
"\"upgradepkg {0} {1}\"",
".",
"format",
"(",
"flag",
",",
"pkg",
")",
",",
"shell",
"=",
"True",
")",
... | 40.533333 | 11.6 |
def extract_metainfo_files_from_package(
package,
output_folder,
debug=False
):
""" Extracts metdata files from the given package to the given folder,
which may be referenced in any way that is permitted in
a requirements.txt file or install_requires=[] listing.
... | [
"def",
"extract_metainfo_files_from_package",
"(",
"package",
",",
"output_folder",
",",
"debug",
"=",
"False",
")",
":",
"if",
"package",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"package cannot be None\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"e... | 38.8 | 19.385714 |
def IntGreaterThanZero(n):
"""If *n* is an integer > 0, returns it, otherwise an error."""
try:
n = int(n)
except:
raise ValueError("%s is not an integer" % n)
if n <= 0:
raise ValueError("%d is not > 0" % n)
else:
return n | [
"def",
"IntGreaterThanZero",
"(",
"n",
")",
":",
"try",
":",
"n",
"=",
"int",
"(",
"n",
")",
"except",
":",
"raise",
"ValueError",
"(",
"\"%s is not an integer\"",
"%",
"n",
")",
"if",
"n",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"%d is not > 0\"",... | 26.6 | 19.5 |
def friendships_destroy(self, user_id=None, screen_name=None):
"""
Allows the authenticating user to unfollow the specified user.
https://dev.twitter.com/docs/api/1.1/post/friendships/destroy
:param str user_id:
The screen name of the user for whom to unfollow. Required if
... | [
"def",
"friendships_destroy",
"(",
"self",
",",
"user_id",
"=",
"None",
",",
"screen_name",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"set_str_param",
"(",
"params",
",",
"'user_id'",
",",
"user_id",
")",
"set_str_param",
"(",
"params",
",",
"'screen... | 37.85 | 20.95 |
def get_active_choices(self, language_code=None, site_id=None):
"""
Find out which translations should be visible in the site.
It returns a list with either a single choice (the current language),
or a list with the current language + fallback language.
"""
if language_co... | [
"def",
"get_active_choices",
"(",
"self",
",",
"language_code",
"=",
"None",
",",
"site_id",
"=",
"None",
")",
":",
"if",
"language_code",
"is",
"None",
":",
"language_code",
"=",
"get_language",
"(",
")",
"lang_dict",
"=",
"self",
".",
"get_language",
"(",
... | 45.142857 | 20.714286 |
def install_programmer(programmer_id, programmer_options, replace_existing=False):
"""install programmer in programmers.txt.
:param programmer_id: string identifier
:param programmer_options: dict like
:param replace_existing: bool
:rtype: None
"""
doaction = 0
if programmer_id in prog... | [
"def",
"install_programmer",
"(",
"programmer_id",
",",
"programmer_options",
",",
"replace_existing",
"=",
"False",
")",
":",
"doaction",
"=",
"0",
"if",
"programmer_id",
"in",
"programmers",
"(",
")",
".",
"keys",
"(",
")",
":",
"log",
".",
"debug",
"(",
... | 32.818182 | 19.363636 |
def _set_ip_acl_interface(self, v, load=False):
"""
Setter method for ip_acl_interface, mapped from YANG variable /interface/tengigabitethernet/ip_acl_interface (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ip_acl_interface is considered as a private
me... | [
"def",
"_set_ip_acl_interface",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | 78.863636 | 37 |
def indent_func(input_):
"""
Takes either no arguments or an alias label
"""
if isinstance(input_, six.string_types):
# A label was specified
lbl = input_
return _indent_decor(lbl)
elif isinstance(input_, (bool, tuple)):
# Allow individually turning of of this decorat... | [
"def",
"indent_func",
"(",
"input_",
")",
":",
"if",
"isinstance",
"(",
"input_",
",",
"six",
".",
"string_types",
")",
":",
"# A label was specified",
"lbl",
"=",
"input_",
"return",
"_indent_decor",
"(",
"lbl",
")",
"elif",
"isinstance",
"(",
"input_",
","... | 30.823529 | 11.529412 |
def get_current_time(self):
"""
Get current time
:return: datetime.time
"""
hms = [int(self.get_current_controller_value(i)) for i in range(406, 409)]
return datetime.time(*hms) | [
"def",
"get_current_time",
"(",
"self",
")",
":",
"hms",
"=",
"[",
"int",
"(",
"self",
".",
"get_current_controller_value",
"(",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"406",
",",
"409",
")",
"]",
"return",
"datetime",
".",
"time",
"(",
"*",
... | 27.375 | 15.875 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'text') and self.text is not None:
_dict['text'] = self.text
return _dict | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'text'",
")",
"and",
"self",
".",
"text",
"is",
"not",
"None",
":",
"_dict",
"[",
"'text'",
"]",
"=",
"self",
".",
"text",
"return",
"_dict"
] | 36 | 14.166667 |
def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
"""
Combines signals from multiple instruments within
given bounds.
Parameters
----------
bounds1 : (min, max)
Bounds for selecting data on the axis of label1
D... | [
"def",
"add",
"(",
"self",
",",
"bounds1",
",",
"label1",
",",
"bounds2",
",",
"label2",
",",
"bin3",
",",
"label3",
",",
"data_label",
")",
":",
"# TODO Update for 2.7 compatability.",
"if",
"isinstance",
"(",
"data_label",
",",
"str",
")",
":",
"data_label... | 38.25 | 19.75 |
def write_connection_file(fname=None, shell_port=0, iopub_port=0, stdin_port=0, hb_port=0,
ip=LOCALHOST, key=b''):
"""Generates a JSON config file, including the selection of random ports.
Parameters
----------
fname : unicode
The path to the file to write
she... | [
"def",
"write_connection_file",
"(",
"fname",
"=",
"None",
",",
"shell_port",
"=",
"0",
",",
"iopub_port",
"=",
"0",
",",
"stdin_port",
"=",
"0",
",",
"hb_port",
"=",
"0",
",",
"ip",
"=",
"LOCALHOST",
",",
"key",
"=",
"b''",
")",
":",
"# default to tem... | 27.469697 | 17.5 |
def get_id(id_or_obj):
"""
Returns the 'id' attribute of 'id_or_obj' if present; if not,
returns 'id_or_obj'.
"""
if isinstance(id_or_obj, six.string_types + (int,)):
# It's an ID
return id_or_obj
try:
return id_or_obj.id
except AttributeError:
return id_or_ob... | [
"def",
"get_id",
"(",
"id_or_obj",
")",
":",
"if",
"isinstance",
"(",
"id_or_obj",
",",
"six",
".",
"string_types",
"+",
"(",
"int",
",",
")",
")",
":",
"# It's an ID",
"return",
"id_or_obj",
"try",
":",
"return",
"id_or_obj",
".",
"id",
"except",
"Attri... | 25.833333 | 15.5 |
def get_data(self, compact=True):
'''
Returns data representing current state of the form. While
Form.raw_data may contain alien fields and invalid data, this method
returns only valid fields that belong to this form only. It's designed
to pass somewhere current state of the form... | [
"def",
"get_data",
"(",
"self",
",",
"compact",
"=",
"True",
")",
":",
"data",
"=",
"MultiDict",
"(",
")",
"for",
"field",
"in",
"self",
".",
"fields",
":",
"raw_value",
"=",
"field",
".",
"from_python",
"(",
"self",
".",
"python_data",
"[",
"field",
... | 43.6 | 23.2 |
def update_pop(self):
"""Assigns fitnesses to particles that are within bounds."""
valid_particles = []
invalid_particles = []
for part in self.population:
if any(x > 1 or x < -1 for x in part):
invalid_particles.append(part)
else:
... | [
"def",
"update_pop",
"(",
"self",
")",
":",
"valid_particles",
"=",
"[",
"]",
"invalid_particles",
"=",
"[",
"]",
"for",
"part",
"in",
"self",
".",
"population",
":",
"if",
"any",
"(",
"x",
">",
"1",
"or",
"x",
"<",
"-",
"1",
"for",
"x",
"in",
"p... | 42.47619 | 8.952381 |
def get_parameter(self):
"""
get the parameter object from the system for this var
needs to be backend safe (not passing or storing bundle)
"""
if not self.is_param:
raise ValueError("this var does not point to a parameter")
# this is quite expensive, so let... | [
"def",
"get_parameter",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_param",
":",
"raise",
"ValueError",
"(",
"\"this var does not point to a parameter\"",
")",
"# this is quite expensive, so let's cache the parameter object so we only",
"# have to filter on the first tim... | 39.933333 | 25.4 |
def sendcontrol(self, char):
'''Helper method that wraps send() with mnemonic access for sending control
character to the child (such as Ctrl-C or Ctrl-D). For example, to send
Ctrl-G (ASCII 7, bell, '\a')::
child.sendcontrol('g')
See also, sendintr() and sendeof().
... | [
"def",
"sendcontrol",
"(",
"self",
",",
"char",
")",
":",
"char",
"=",
"char",
".",
"lower",
"(",
")",
"a",
"=",
"ord",
"(",
"char",
")",
"if",
"97",
"<=",
"a",
"<=",
"122",
":",
"a",
"=",
"a",
"-",
"ord",
"(",
"'a'",
")",
"+",
"1",
"byte",... | 29.518519 | 17.074074 |
def get_max_instability(self, min_voltage=None, max_voltage=None):
"""
The maximum instability along a path for a specific voltage range.
Args:
min_voltage: The minimum allowable voltage.
max_voltage: The maximum allowable voltage.
Returns:
Maximum d... | [
"def",
"get_max_instability",
"(",
"self",
",",
"min_voltage",
"=",
"None",
",",
"max_voltage",
"=",
"None",
")",
":",
"data",
"=",
"[",
"]",
"for",
"pair",
"in",
"self",
".",
"_select_in_voltage_range",
"(",
"min_voltage",
",",
"max_voltage",
")",
":",
"i... | 42.157895 | 21.421053 |
def storage_command(self, name, method_name=None, command_type=None, oauth=False, generic_update=None, **kwargs):
""" Registers an Azure CLI Storage Data Plane command. These commands always include the four parameters which
can be used to obtain a storage client: account-name, account-key, connection-s... | [
"def",
"storage_command",
"(",
"self",
",",
"name",
",",
"method_name",
"=",
"None",
",",
"command_type",
"=",
"None",
",",
"oauth",
"=",
"False",
",",
"generic_update",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"generic_update",
":",
"comman... | 66.769231 | 27.230769 |
def cull_edges(self, stat, threshold=0.5, comparator=ge):
"""Delete edges whose stat >= ``threshold`` (default 0.5).
Optional argument ``comparator`` will replace >= as the test
for whether to cull. You can use the name of a stored function.
"""
return self.cull_portals(stat, t... | [
"def",
"cull_edges",
"(",
"self",
",",
"stat",
",",
"threshold",
"=",
"0.5",
",",
"comparator",
"=",
"ge",
")",
":",
"return",
"self",
".",
"cull_portals",
"(",
"stat",
",",
"threshold",
",",
"comparator",
")"
] | 41.75 | 22.125 |
def _get_grammar_errors(self,pos,text,tokens):
"""
Internal function to get the number of grammar errors in given text
pos - part of speech tagged text (list)
text - normal text (list)
tokens - list of lists of tokenized text
"""
word_counts = [max(len(t),1) for t... | [
"def",
"_get_grammar_errors",
"(",
"self",
",",
"pos",
",",
"text",
",",
"tokens",
")",
":",
"word_counts",
"=",
"[",
"max",
"(",
"len",
"(",
"t",
")",
",",
"1",
")",
"for",
"t",
"in",
"tokens",
"]",
"good_pos_tags",
"=",
"[",
"]",
"min_pos_seq",
"... | 48.820513 | 20.25641 |
def resetAndRejoin(self, timeout):
"""reset and join back Thread Network with a given timeout delay
Args:
timeout: a timeout interval before rejoin Thread Network
Returns:
True: successful to reset and rejoin Thread Network
False: fail to reset and rejoin th... | [
"def",
"resetAndRejoin",
"(",
"self",
",",
"timeout",
")",
":",
"print",
"'%s call resetAndRejoin'",
"%",
"self",
".",
"port",
"print",
"timeout",
"try",
":",
"if",
"self",
".",
"__sendCommand",
"(",
"WPANCTL_CMD",
"+",
"'setprop Daemon:AutoAssociateAfterReset false... | 38 | 24.075 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.