text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _findlinestarts(code):
"""Find the offsets in a byte code which are start of lines in the source.
Generate pairs (offset, lineno) as described in Python/compile.c.
Arguments:
code: code object.
Yields:
Address and line number pairs.
"""
byte_increments = [ord(c) for c in code.co_lnotab[0::2]]... | [
"def",
"_findlinestarts",
"(",
"code",
")",
":",
"byte_increments",
"=",
"[",
"ord",
"(",
"c",
")",
"for",
"c",
"in",
"code",
".",
"co_lnotab",
"[",
"0",
":",
":",
"2",
"]",
"]",
"line_increments",
"=",
"[",
"ord",
"(",
"c",
")",
"for",
"c",
"in"... | 26.615385 | 20.423077 |
def image_as_moving_sequence(
image, sequence_length=20, output_size=(64, 64), velocity=0.1,
start_position=None):
"""Turn simple static images into sequences of the originals bouncing around.
Adapted from Srivastava et al.
http://www.cs.toronto.edu/~nitish/unsupervised_video/
Example usage:
```pyth... | [
"def",
"image_as_moving_sequence",
"(",
"image",
",",
"sequence_length",
"=",
"20",
",",
"output_size",
"=",
"(",
"64",
",",
"64",
")",
",",
"velocity",
"=",
"0.1",
",",
"start_position",
"=",
"None",
")",
":",
"ndims",
"=",
"2",
"image",
"=",
"tf",
".... | 39.283333 | 21.083333 |
def _EnsureFileExists(self):
"""Touches a file; returns False on error, True on success."""
if not os.path.exists(self._filename):
old_umask = os.umask(0o177)
try:
open(self._filename, 'a+b').close()
except OSError:
return False
... | [
"def",
"_EnsureFileExists",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_filename",
")",
":",
"old_umask",
"=",
"os",
".",
"umask",
"(",
"0o177",
")",
"try",
":",
"open",
"(",
"self",
".",
"_filename",
"... | 34.454545 | 11.363636 |
def _compute_filename(self, request: BaseRequest):
'''Get the appropriate filename from the request.'''
path = self._path_namer.get_filename(request.url_info)
if os.path.isdir(path):
path += '.f'
else:
dir_name, name = os.path.split(path)
path = os.pa... | [
"def",
"_compute_filename",
"(",
"self",
",",
"request",
":",
"BaseRequest",
")",
":",
"path",
"=",
"self",
".",
"_path_namer",
".",
"get_filename",
"(",
"request",
".",
"url_info",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"pa... | 34.272727 | 22.090909 |
def unregister_service(self, registration):
# type: (ServiceRegistration) -> bool
"""
Unregisters the given service
:param registration: A ServiceRegistration to the service to unregister
:raise BundleException: Invalid reference
"""
# Get the Service Reference
... | [
"def",
"unregister_service",
"(",
"self",
",",
"registration",
")",
":",
"# type: (ServiceRegistration) -> bool",
"# Get the Service Reference",
"reference",
"=",
"registration",
".",
"get_reference",
"(",
")",
"# Remove the service from the registry",
"svc_instance",
"=",
"s... | 35 | 17.214286 |
def zip_dir(path, zip_handler, include_dir=True, use_arc_name=False):
"""
zip all files and items in dir
:param only_init:
:param path:
:param zip_handler: zip file handler
:param boolean include_dir: specify if we want the archive with or without the directory
"""
for root, dirs, files... | [
"def",
"zip_dir",
"(",
"path",
",",
"zip_handler",
",",
"include_dir",
"=",
"True",
",",
"use_arc_name",
"=",
"False",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"file_to_zip",
"in",
"fi... | 33.777778 | 18.777778 |
def namespace(sharing=None, owner=None, app=None, **kwargs):
"""This function constructs a Splunk namespace.
Every Splunk resource belongs to a namespace. The namespace is specified by
the pair of values ``owner`` and ``app`` and is governed by a ``sharing`` mode.
The possible values for ``sharing`` ar... | [
"def",
"namespace",
"(",
"sharing",
"=",
"None",
",",
"owner",
"=",
"None",
",",
"app",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"sharing",
"in",
"[",
"\"system\"",
"]",
":",
"return",
"record",
"(",
"{",
"'sharing'",
":",
"sharing",
"... | 43.62069 | 26.793103 |
def _parse(self,filename):
"""
Reads an isochrone in the old Padova format (Girardi 2002,
Marigo 2008) and determines the age (log10 yrs and Gyr),
metallicity (Z and [Fe/H]), and creates arrays with the
initial stellar mass and corresponding magnitudes for each
step along... | [
"def",
"_parse",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"columns",
"=",
"self",
".",
"columns",
"[",
"self",
".",
"survey",
".",
"lower",
"(",
")",
"]",
"except",
"KeyError",
"as",
"e",
":",
"logger",
".",
"warning",
"(",
"'did not recog... | 41.675676 | 17.297297 |
def _Fierz_to_Bern_III_IV_V(Fqqqq, qqqq):
"""From Fierz to 4-quark Bern basis for Classes III, IV and V.
`qqqq` should be of the form 'sbuc', 'sdcc', 'ucuu' etc."""
# 2nd != 4th, color-octet redundant
if qqqq in ['sbss', 'dbdd', 'dbds', 'sbsd', 'bsbd', 'dsdd']:
return {
'1' + qqqq : -Fqq... | [
"def",
"_Fierz_to_Bern_III_IV_V",
"(",
"Fqqqq",
",",
"qqqq",
")",
":",
"# 2nd != 4th, color-octet redundant",
"if",
"qqqq",
"in",
"[",
"'sbss'",
",",
"'dbdd'",
",",
"'dbds'",
",",
"'sbsd'",
",",
"'bsbd'",
",",
"'dsdd'",
"]",
":",
"return",
"{",
"'1'",
"+",
... | 54.460177 | 17.849558 |
def preprocess_search_hit(pid, record_hit, links_factory=None, **kwargs):
"""Prepare a record hit from Elasticsearch for serialization."""
links_factory = links_factory or (lambda x, **k: dict())
record = dict(
pid=pid,
metadata=record_hit['_source'],
links=li... | [
"def",
"preprocess_search_hit",
"(",
"pid",
",",
"record_hit",
",",
"links_factory",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"links_factory",
"=",
"links_factory",
"or",
"(",
"lambda",
"x",
",",
"*",
"*",
"k",
":",
"dict",
"(",
")",
")",
"recor... | 43.058824 | 15.058824 |
def hide_ticks(plot, min_tick_value=None, max_tick_value=None):
"""Hide tick values that are outside of [min_tick_value, max_tick_value]"""
for tick, tick_value in zip(plot.get_yticklabels(), plot.get_yticks()):
tick_label = as_numeric(tick_value)
if tick_label:
if (min_tick_value is... | [
"def",
"hide_ticks",
"(",
"plot",
",",
"min_tick_value",
"=",
"None",
",",
"max_tick_value",
"=",
"None",
")",
":",
"for",
"tick",
",",
"tick_value",
"in",
"zip",
"(",
"plot",
".",
"get_yticklabels",
"(",
")",
",",
"plot",
".",
"get_yticks",
"(",
")",
... | 59.5 | 19.375 |
def add_timing_signal_1d_given_position(x,
position,
min_timescale=1.0,
max_timescale=1.0e4):
"""Adds sinusoids of diff frequencies to a Tensor, with timing position given.
Args:
x: a Tensor ... | [
"def",
"add_timing_signal_1d_given_position",
"(",
"x",
",",
"position",
",",
"min_timescale",
"=",
"1.0",
",",
"max_timescale",
"=",
"1.0e4",
")",
":",
"channels",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"[",
"2",
"]",
"num_timescales",
"=",
... | 39.655172 | 16.103448 |
def _start(self, args):
"""
start connection negotiation
This method starts the connection negotiation process by
telling the client the protocol version that the server
proposes, along with a list of security mechanisms which the
client can use for authentication.
... | [
"def",
"_start",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"version_major",
"=",
"args",
".",
"read_octet",
"(",
")",
"self",
".",
"version_minor",
"=",
"args",
".",
"read_octet",
"(",
")",
"self",
".",
"server_properties",
"=",
"args",
".",
"re... | 33.067568 | 24.445946 |
def _import_to_py_ast(ctx: GeneratorContext, node: Import) -> GeneratedPyAST:
"""Return a Python AST node for a Basilisp `import*` expression."""
assert node.op == NodeOp.IMPORT
last = None
deps: List[ast.AST] = []
for alias in node.aliases:
safe_name = munge(alias.name)
try:
... | [
"def",
"_import_to_py_ast",
"(",
"ctx",
":",
"GeneratorContext",
",",
"node",
":",
"Import",
")",
"->",
"GeneratedPyAST",
":",
"assert",
"node",
".",
"op",
"==",
"NodeOp",
".",
"IMPORT",
"last",
"=",
"None",
"deps",
":",
"List",
"[",
"ast",
".",
"AST",
... | 36.754386 | 21.684211 |
def register(self, cls):
"""
Adds a preview to the index.
"""
preview = cls(site=self)
logger.debug('Registering %r with %r', preview, self)
index = self.__previews.setdefault(preview.module, {})
index[cls.__name__] = preview | [
"def",
"register",
"(",
"self",
",",
"cls",
")",
":",
"preview",
"=",
"cls",
"(",
"site",
"=",
"self",
")",
"logger",
".",
"debug",
"(",
"'Registering %r with %r'",
",",
"preview",
",",
"self",
")",
"index",
"=",
"self",
".",
"__previews",
".",
"setdef... | 34.25 | 9.25 |
def from_dict(data, ctx):
"""
Instantiate a new MarketOrderTransaction from a dict (generally from
loading a JSON response). The data used to instantiate the
MarketOrderTransaction is a shallow copy of the dict passed in, with
any complex child types instantiated appropriately.
... | [
"def",
"from_dict",
"(",
"data",
",",
"ctx",
")",
":",
"data",
"=",
"data",
".",
"copy",
"(",
")",
"if",
"data",
".",
"get",
"(",
"'units'",
")",
"is",
"not",
"None",
":",
"data",
"[",
"'units'",
"]",
"=",
"ctx",
".",
"convert_decimal_number",
"(",... | 36.444444 | 19.185185 |
def run_simulation(self):
"""Runs the complete simulation"""
print('Starting simulations...')
for i in range(self.num_trials):
print('---Trial {}---'.format(i))
self.run_trial(i)
print('Simulation completed.') | [
"def",
"run_simulation",
"(",
"self",
")",
":",
"print",
"(",
"'Starting simulations...'",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"num_trials",
")",
":",
"print",
"(",
"'---Trial {}---'",
".",
"format",
"(",
"i",
")",
")",
"self",
".",
"run_tr... | 37 | 4.714286 |
def commit_comment(self, comment_id):
"""Get a single commit comment.
:param int comment_id: (required), id of the comment used by GitHub
:returns: :class:`RepoComment <github3.repos.comment.RepoComment>` if
successful, otherwise None
"""
url = self._build_url('comme... | [
"def",
"commit_comment",
"(",
"self",
",",
"comment_id",
")",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'comments'",
",",
"str",
"(",
"comment_id",
")",
",",
"base_url",
"=",
"self",
".",
"_api",
")",
"json",
"=",
"self",
".",
"_json",
"(",
"... | 45.7 | 17.7 |
def run(self):
""" Todo """
self.logger.debug("heartbeat started")
while True:
time.sleep(self.interval)
self.send_heartbeat() | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"heartbeat started\"",
")",
"while",
"True",
":",
"time",
".",
"sleep",
"(",
"self",
".",
"interval",
")",
"self",
".",
"send_heartbeat",
"(",
")"
] | 24.166667 | 12.5 |
def _notify_unload_dll(self, event):
"""
Notify the release of a loaded module.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{UnloadDLLEvent}
@param event: Unload DLL event.
@rtype: bool
@retu... | [
"def",
"_notify_unload_dll",
"(",
"self",
",",
"event",
")",
":",
"lpBaseOfDll",
"=",
"event",
".",
"get_module_base",
"(",
")",
"## if self.has_module(lpBaseOfDll): # XXX this would trigger a scan",
"if",
"lpBaseOfDll",
"in",
"self",
".",
"__moduleDict",
":",
"... | 33.777778 | 16.777778 |
def within_n_mads(n, series):
"""Return true if all values in sequence are within n MADs"""
mad_score = (series - series.mean()) / series.mad()
return (mad_score.abs() <= n).all() | [
"def",
"within_n_mads",
"(",
"n",
",",
"series",
")",
":",
"mad_score",
"=",
"(",
"series",
"-",
"series",
".",
"mean",
"(",
")",
")",
"/",
"series",
".",
"mad",
"(",
")",
"return",
"(",
"mad_score",
".",
"abs",
"(",
")",
"<=",
"n",
")",
".",
"... | 47 | 6.75 |
def score_alignment(a, b, gap_open, gap_extend, matrix):
'''Calculate the alignment score from two aligned sequences.
:param a: The first aligned sequence.
:type a: str
:param b: The second aligned sequence.
:type b: str
:param gap_open: The cost of opening a gap (negative number).
:type ga... | [
"def",
"score_alignment",
"(",
"a",
",",
"b",
",",
"gap_open",
",",
"gap_extend",
",",
"matrix",
")",
":",
"al",
"=",
"a",
"bl",
"=",
"b",
"l",
"=",
"len",
"(",
"al",
")",
"score",
"=",
"0",
"assert",
"len",
"(",
"bl",
")",
"==",
"l",
",",
"'... | 30.3125 | 22.125 |
def stderr(self):
"""
The job stderr
:return: string or None
"""
streams = self._payload.get('streams', None)
return streams[1] if streams is not None and len(streams) >= 2 else '' | [
"def",
"stderr",
"(",
"self",
")",
":",
"streams",
"=",
"self",
".",
"_payload",
".",
"get",
"(",
"'streams'",
",",
"None",
")",
"return",
"streams",
"[",
"1",
"]",
"if",
"streams",
"is",
"not",
"None",
"and",
"len",
"(",
"streams",
")",
">=",
"2",... | 31.714286 | 14.285714 |
def raw_rsa_public_crypt(certificate_or_public_key, data):
"""
Performs a raw RSA algorithm in a byte string using a certificate or
public key. This is a low-level primitive and is prone to disastrous results
if used incorrectly.
:param certificate_or_public_key:
An oscrypto.asymmetric.Publ... | [
"def",
"raw_rsa_public_crypt",
"(",
"certificate_or_public_key",
",",
"data",
")",
":",
"if",
"_backend",
"!=",
"'winlegacy'",
":",
"raise",
"SystemError",
"(",
"'Pure-python RSA crypt is only for Windows XP/2003'",
")",
"has_asn1",
"=",
"hasattr",
"(",
"certificate_or_pu... | 33.887097 | 22.532258 |
def insert(self, database, key, value, callback=None):
"""
Insert an item into the given database.
:param database: The database into which to insert the value.
:type database: .BlobDatabaseID
:param key: The key to insert.
:type key: uuid.UUID
:param value: The ... | [
"def",
"insert",
"(",
"self",
",",
"database",
",",
"key",
",",
"value",
",",
"callback",
"=",
"None",
")",
":",
"token",
"=",
"self",
".",
"_get_token",
"(",
")",
"self",
".",
"_enqueue",
"(",
"self",
".",
"_PendingItem",
"(",
"token",
",",
"BlobCom... | 44.9375 | 18.0625 |
def get_or_add_childTnLst(self):
"""Return parent element for a new `p:video` child element.
The `p:video` element causes play controls to appear under a video
shape (pic shape containing video). There can be more than one video
shape on a slide, which causes the precondition to vary. I... | [
"def",
"get_or_add_childTnLst",
"(",
"self",
")",
":",
"childTnLst",
"=",
"self",
".",
"_childTnLst",
"if",
"childTnLst",
"is",
"None",
":",
"childTnLst",
"=",
"self",
".",
"_add_childTnLst",
"(",
")",
"return",
"childTnLst"
] | 50.529412 | 22.294118 |
def step_next_char(self):
"""Puts the cursor on the next character."""
self._index += 1
self._col_offset += 1
if self._index > self._maxindex:
self._maxindex = self._index
self._maxcol = self._col_offset
self._maxline = self._lineno | [
"def",
"step_next_char",
"(",
"self",
")",
":",
"self",
".",
"_index",
"+=",
"1",
"self",
".",
"_col_offset",
"+=",
"1",
"if",
"self",
".",
"_index",
">",
"self",
".",
"_maxindex",
":",
"self",
".",
"_maxindex",
"=",
"self",
".",
"_index",
"self",
".... | 36.625 | 5.625 |
def dumps(self) -> str:
"""Writes the step information to an HTML-formatted string"""
code_file_path = os.path.join(
self.project.source_directory,
self.filename
)
code = dict(
filename=self.filename,
path=code_file_path,
code=r... | [
"def",
"dumps",
"(",
"self",
")",
"->",
"str",
":",
"code_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"project",
".",
"source_directory",
",",
"self",
".",
"filename",
")",
"code",
"=",
"dict",
"(",
"filename",
"=",
"self",
"."... | 34.789474 | 16.539474 |
def _postprocess_variants(record_file, data, ref_file, out_file):
"""Post-process variants, converting into standard VCF file.
"""
if not utils.file_uptodate(out_file, record_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = ["dv_postprocess_variants.py", "--ref", ref_fi... | [
"def",
"_postprocess_variants",
"(",
"record_file",
",",
"data",
",",
"ref_file",
",",
"out_file",
")",
":",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"record_file",
")",
":",
"with",
"file_transaction",
"(",
"data",
",",
"out_file",
... | 55 | 20.666667 |
def build_option_parser(self, description, version):
"""Return an argparse option parser for this application.
Subclasses may override this method to extend
the parser with more global options.
:param description: full description of the application
:paramtype description: str
... | [
"def",
"build_option_parser",
"(",
"self",
",",
"description",
",",
"version",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
",",
"add_help",
"=",
"False",
",",
")",
"parser",
".",
"add_argument",
"(",
"'... | 36.416667 | 13.875 |
def fitlin_clipped(xy,uv,verbose=False,mode='rscale',nclip=3,reject=3):
""" Perform a clipped fit based on the number of iterations and rejection limit
(in sigma) specified by the user. This will more closely replicate the results
obtained by 'geomap' using 'maxiter' and 'reject' parameters.
"""... | [
"def",
"fitlin_clipped",
"(",
"xy",
",",
"uv",
",",
"verbose",
"=",
"False",
",",
"mode",
"=",
"'rscale'",
",",
"nclip",
"=",
"3",
",",
"reject",
"=",
"3",
")",
":",
"fitting_funcs",
"=",
"{",
"'rscale'",
":",
"fitlin_rscale",
",",
"'general'",
":",
... | 37.552632 | 19.026316 |
def pretty_xml(string_input, add_ns=False):
""" pretty indent string_input """
if add_ns:
elem = "<foo "
for key, value in DOC_CONTENT_ATTRIB.items():
elem += ' %s="%s"' % (key, value)
string_input = elem + ">" + string_input + "</foo>"
doc = minidom.parseString(string_in... | [
"def",
"pretty_xml",
"(",
"string_input",
",",
"add_ns",
"=",
"False",
")",
":",
"if",
"add_ns",
":",
"elem",
"=",
"\"<foo \"",
"for",
"key",
",",
"value",
"in",
"DOC_CONTENT_ATTRIB",
".",
"items",
"(",
")",
":",
"elem",
"+=",
"' %s=\"%s\"'",
"%",
"(",
... | 34.538462 | 15.307692 |
def update_ip_rule(self, ip, mac):
"""Update a rule associated with given ip and mac."""
rule_no = self._find_rule_no(mac)
chain = self._find_chain_name(mac)
if not rule_no or not chain:
LOG.error('Failed to update ip rule for %(ip)s %(mac)s',
{'ip': ip... | [
"def",
"update_ip_rule",
"(",
"self",
",",
"ip",
",",
"mac",
")",
":",
"rule_no",
"=",
"self",
".",
"_find_rule_no",
"(",
"mac",
")",
"chain",
"=",
"self",
".",
"_find_chain_name",
"(",
"mac",
")",
"if",
"not",
"rule_no",
"or",
"not",
"chain",
":",
"... | 43.533333 | 17.066667 |
def _eval_function_wrapper(func):
"""Decorate an eval function.
Note
----
For multi-class task, the y_pred is group by class_id first, then group by row_id.
If you want to get i-th row y_pred in j-th class, the access way is y_pred[j * num_data + i].
Parameters
----------
func : callab... | [
"def",
"_eval_function_wrapper",
"(",
"func",
")",
":",
"def",
"inner",
"(",
"preds",
",",
"dataset",
")",
":",
"\"\"\"Call passed function with appropriate arguments.\"\"\"",
"labels",
"=",
"dataset",
".",
"get_label",
"(",
")",
"argc",
"=",
"argc_",
"(",
"func",... | 39.54 | 23.7 |
def get_boundaries(bounddict_file, slitlet_number):
"""Read the bounddict json file and return the polynomial boundaries.
Parameters
----------
bounddict_file : file handler
File containing the bounddict JSON data.
slitlet_number : int
Number of slitlet.
Returns
-------
... | [
"def",
"get_boundaries",
"(",
"bounddict_file",
",",
"slitlet_number",
")",
":",
"bounddict",
"=",
"json",
".",
"loads",
"(",
"open",
"(",
"bounddict_file",
".",
"name",
")",
".",
"read",
"(",
")",
")",
"# return values in case the requested slitlet number is not de... | 36.701493 | 18.61194 |
def set_mappings(cls, index_name, doc_type, mappings):
""" set new mapped-items structure into cache """
cache.set(cls.get_cache_item_name(index_name, doc_type), mappings) | [
"def",
"set_mappings",
"(",
"cls",
",",
"index_name",
",",
"doc_type",
",",
"mappings",
")",
":",
"cache",
".",
"set",
"(",
"cls",
".",
"get_cache_item_name",
"(",
"index_name",
",",
"doc_type",
")",
",",
"mappings",
")"
] | 61.666667 | 16 |
def get_salt(request):
"""
return the user password salt.
If the user doesn't exist return a pseudo salt.
"""
try:
username = request.POST["username"]
except KeyError:
# log.error("No 'username' in POST data?!?")
return HttpResponseBadRequest()
try:
request.s... | [
"def",
"get_salt",
"(",
"request",
")",
":",
"try",
":",
"username",
"=",
"request",
".",
"POST",
"[",
"\"username\"",
"]",
"except",
"KeyError",
":",
"# log.error(\"No 'username' in POST data?!?\")",
"return",
"HttpResponseBadRequest",
"(",
")",
"try",
":",
"requ... | 34.680851 | 22.680851 |
def upload(self, cmd: str, meta: dict):
"""Push the current state of the registry to Git."""
index = os.path.join(self.cached_repo, self.INDEX_FILE)
if os.path.exists(index):
os.remove(index)
self._log.info("Writing the new index.json ...")
with open(index, "w") as _o... | [
"def",
"upload",
"(",
"self",
",",
"cmd",
":",
"str",
",",
"meta",
":",
"dict",
")",
":",
"index",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cached_repo",
",",
"self",
".",
"INDEX_FILE",
")",
"if",
"os",
".",
"path",
".",
"exists",
... | 51.971429 | 17.571429 |
def _get_request_url(self, instance, url):
"""
Get the request address, build with proxy if necessary
"""
parsed = urlparse(url)
_url = url
if not (parsed.netloc and parsed.scheme) and is_affirmative(instance.get('spark_proxy_enabled', False)):
master_address... | [
"def",
"_get_request_url",
"(",
"self",
",",
"instance",
",",
"url",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"_url",
"=",
"url",
"if",
"not",
"(",
"parsed",
".",
"netloc",
"and",
"parsed",
".",
"scheme",
")",
"and",
"is_affirmative",
"(",... | 36.846154 | 21.769231 |
def run(self, args=None):
"""Applicatin starting point.
This will run the associated method/function/module or print a help
list if it's an unknown keyword or the syntax is incorrect.
Keyword arguments:
args -- Custom application arguments (default sys.argv)
"""
... | [
"def",
"run",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"# TODO: Add tests to how command line arguments are passed in",
"raw_args",
"=",
"self",
".",
"__parser",
".",
"parse_args",
"(",
"args",
"=",
"args",
")",
"args",
"=",
"vars",
"(",
"raw_args",
")... | 34 | 20 |
def _note_local_option(self, option, state):
"""Record the status of local negotiated Telnet options."""
if not self.telnet_opt_dict.has_key(option):
self.telnet_opt_dict[option] = TelnetOption()
self.telnet_opt_dict[option].local_option = state | [
"def",
"_note_local_option",
"(",
"self",
",",
"option",
",",
"state",
")",
":",
"if",
"not",
"self",
".",
"telnet_opt_dict",
".",
"has_key",
"(",
"option",
")",
":",
"self",
".",
"telnet_opt_dict",
"[",
"option",
"]",
"=",
"TelnetOption",
"(",
")",
"sel... | 55.4 | 10 |
def normalize_sort(sort=None):
"""
CONVERT SORT PARAMETERS TO A NORMAL FORM SO EASIER TO USE
"""
if not sort:
return Null
output = FlatList()
for s in listwrap(sort):
if is_text(s) or mo_math.is_integer(s):
output.append({"value": s, "sort": 1})
elif not s.f... | [
"def",
"normalize_sort",
"(",
"sort",
"=",
"None",
")",
":",
"if",
"not",
"sort",
":",
"return",
"Null",
"output",
"=",
"FlatList",
"(",
")",
"for",
"s",
"in",
"listwrap",
"(",
"sort",
")",
":",
"if",
"is_text",
"(",
"s",
")",
"or",
"mo_math",
".",... | 33.263158 | 19.578947 |
def enable_debug(self):
"""Open the debug interface on the connected device."""
if not self.connected:
raise HardwareError("Cannot enable debug if we are not in a connected state")
self._loop.run_coroutine(self.adapter.open_interface(0, 'debug')) | [
"def",
"enable_debug",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"HardwareError",
"(",
"\"Cannot enable debug if we are not in a connected state\"",
")",
"self",
".",
"_loop",
".",
"run_coroutine",
"(",
"self",
".",
"adapter",
"."... | 39.714286 | 27 |
def calc_conf_intervals(self,
conf_percentage,
interval_type='all',
init_vals=None,
epsilon=abc.EPSILON,
**fit_kwargs):
"""
Calculates percentile, bias-corrected an... | [
"def",
"calc_conf_intervals",
"(",
"self",
",",
"conf_percentage",
",",
"interval_type",
"=",
"'all'",
",",
"init_vals",
"=",
"None",
",",
"epsilon",
"=",
"abc",
".",
"EPSILON",
",",
"*",
"*",
"fit_kwargs",
")",
":",
"if",
"interval_type",
"==",
"'pi'",
":... | 50.644444 | 20.177778 |
def _proc_member(self, tarfile):
"""Choose the right processing method depending on
the type and call it.
"""
if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
return self._proc_gnulong(tarfile)
elif self.type == GNUTYPE_SPARSE:
return self._proc_sp... | [
"def",
"_proc_member",
"(",
"self",
",",
"tarfile",
")",
":",
"if",
"self",
".",
"type",
"in",
"(",
"GNUTYPE_LONGNAME",
",",
"GNUTYPE_LONGLINK",
")",
":",
"return",
"self",
".",
"_proc_gnulong",
"(",
"tarfile",
")",
"elif",
"self",
".",
"type",
"==",
"GN... | 40.75 | 8.833333 |
def _put(self, rtracker):
"""
Put a resource back in the queue.
:param rtracker: A resource.
:type rtracker: :class:`_ResourceTracker`
:raises PoolFullError: If pool is full.
:raises UnknownResourceError: If resource can't be found.
"""
with self._lock:
... | [
"def",
"_put",
"(",
"self",
",",
"rtracker",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_available",
"<",
"self",
".",
"capacity",
":",
"for",
"i",
"in",
"self",
".",
"_unavailable_range",
"(",
")",
":",
"if",
"self",
".",
"_r... | 34 | 15.866667 |
def cmd_link_ports(self):
'''show available ports'''
ports = mavutil.auto_detect_serial(preferred_list=['*FTDI*',"*Arduino_Mega_2560*", "*3D_Robotics*", "*USB_to_UART*", '*PX4*', '*FMU*'])
for p in ports:
print("%s : %s : %s" % (p.device, p.description, p.hwid)) | [
"def",
"cmd_link_ports",
"(",
"self",
")",
":",
"ports",
"=",
"mavutil",
".",
"auto_detect_serial",
"(",
"preferred_list",
"=",
"[",
"'*FTDI*'",
",",
"\"*Arduino_Mega_2560*\"",
",",
"\"*3D_Robotics*\"",
",",
"\"*USB_to_UART*\"",
",",
"'*PX4*'",
",",
"'*FMU*'",
"]"... | 58.8 | 34 |
def generate(env):
"""Add Builders and construction variables for qt to an Environment."""
CLVar = SCons.Util.CLVar
Action = SCons.Action.Action
Builder = SCons.Builder.Builder
env.SetDefault(QTDIR = _detect(env),
QT_BINPATH = os.path.join('$QTDIR', 'bin'),
QT... | [
"def",
"generate",
"(",
"env",
")",
":",
"CLVar",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"Action",
"=",
"SCons",
".",
"Action",
".",
"Action",
"Builder",
"=",
"SCons",
".",
"Builder",
".",
"Builder",
"env",
".",
"SetDefault",
"(",
"QTDIR",
"=",
"_d... | 46.67033 | 16.351648 |
def _conform_pair(self, pair):
"""Force a given key/value pair into a certain form.
Override the _conform_key and _conform_value if you want to change
the mapping behaviour.
"""
pair = tuple(pair)
if len(pair) != 2:
raise ValueError('MultiMap... | [
"def",
"_conform_pair",
"(",
"self",
",",
"pair",
")",
":",
"pair",
"=",
"tuple",
"(",
"pair",
")",
"if",
"len",
"(",
"pair",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'MultiMap element must have length 2'",
")",
"return",
"(",
"self",
".",
"_con... | 37.545455 | 18.727273 |
def counter(self, key, value, timestamp=None):
"""Set a counter value
If the inner key does not exist is is created
:param key: counter to update
:type key: str
:param value: counter value
:type value: float
:return: An alignak_stat brok if broks are enabled els... | [
"def",
"counter",
"(",
"self",
",",
"key",
",",
"value",
",",
"timestamp",
"=",
"None",
")",
":",
"_min",
",",
"_max",
",",
"count",
",",
"_sum",
"=",
"self",
".",
"stats",
".",
"get",
"(",
"key",
",",
"(",
"None",
",",
"None",
",",
"0",
",",
... | 38.057143 | 18.185714 |
def get_all(self):
"""
Gets all captured counters.
:return: a list with counters.
"""
self._lock.acquire()
try:
return list(self._cache.values())
finally:
self._lock.release() | [
"def",
"get_all",
"(",
"self",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"return",
"list",
"(",
"self",
".",
"_cache",
".",
"values",
"(",
")",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | 22.363636 | 13.272727 |
def create_pipeline(name, unique_id, description='', region=None, key=None, keyid=None,
profile=None):
'''
Create a new, empty pipeline. This function is idempotent.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.create_pipeline my_name my_unique_id
... | [
"def",
"create_pipeline",
"(",
"name",
",",
"unique_id",
",",
"description",
"=",
"''",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"client",
"=",
"_get_client",
"(",
"region",
... | 30.521739 | 24.173913 |
def InitAgeCheck(self):
"""make an interactive grid in which users can edit ages"""
age_df = self.contribution.tables['ages'].df
self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER)
self.grid_frame = grid_frame3.GridFrame(self.contribution, self.WD,
... | [
"def",
"InitAgeCheck",
"(",
"self",
")",
":",
"age_df",
"=",
"self",
".",
"contribution",
".",
"tables",
"[",
"'ages'",
"]",
".",
"df",
"self",
".",
"panel",
"=",
"wx",
".",
"Panel",
"(",
"self",
",",
"style",
"=",
"wx",
".",
"SIMPLE_BORDER",
")",
... | 51.652174 | 21.782609 |
def count(data):
"""
count reads mapping to genes using featureCounts
http://subread.sourceforge.net
"""
in_bam = dd.get_work_bam(data) or dd.get_align_bam(data)
out_dir = os.path.join(dd.get_work_dir(data), "align", dd.get_sample_name(data))
if dd.get_aligner(data) == "star":
out_di... | [
"def",
"count",
"(",
"data",
")",
":",
"in_bam",
"=",
"dd",
".",
"get_work_bam",
"(",
"data",
")",
"or",
"dd",
".",
"get_align_bam",
"(",
"data",
")",
"out_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dd",
".",
"get_work_dir",
"(",
"data",
")",... | 44.25 | 21.55 |
def report(usaf):
"""generate report for usaf base"""
fig = plt.figure()
ax = fig.add_subplot(111)
station_info = geo.station_info(usaf)
y = {}
for i in range(1991, 2011):
monthData = monthly(usaf, i)
t = sum(monthData)
y[i] = t
print t
tmy3tot = tmy3.total(us... | [
"def",
"report",
"(",
"usaf",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"111",
")",
"station_info",
"=",
"geo",
".",
"station_info",
"(",
"usaf",
")",
"y",
"=",
"{",
"}",
"for",
"i",
"in",
... | 35.78 | 12.4 |
def to_file(self, filename):
"""
Write the ANTsImage to file
Args
----
filename : string
filepath to which the image will be written
"""
filename = os.path.expanduser(filename)
libfn = utils.get_lib_fn('toFile%s'%self._libsuffix)
libfn... | [
"def",
"to_file",
"(",
"self",
",",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'toFile%s'",
"%",
"self",
".",
"_libsuffix",
")",
"libfn",
"(",
"self... | 27.75 | 14.416667 |
def gender(word, pos=NOUN):
""" Returns the gender (MALE, FEMALE or NEUTRAL) for nouns (majority vote).
Returns None for words that are not nouns.
"""
w = word.lower()
if pos == NOUN:
# Default rules (baseline = 32%).
if w.endswith(gender_masculine):
return MASCULINE
... | [
"def",
"gender",
"(",
"word",
",",
"pos",
"=",
"NOUN",
")",
":",
"w",
"=",
"word",
".",
"lower",
"(",
")",
"if",
"pos",
"==",
"NOUN",
":",
"# Default rules (baseline = 32%).",
"if",
"w",
".",
"endswith",
"(",
"gender_masculine",
")",
":",
"return",
"MA... | 33.882353 | 9.058824 |
def target_sequence(self):
# type: () -> SeqRecord
"""Get the target sequence in the vector.
The target sequence if the part of the plasmid that is not discarded
during the assembly (everything except the placeholder sequence).
"""
if self.cutter.is_3overhang():
... | [
"def",
"target_sequence",
"(",
"self",
")",
":",
"# type: () -> SeqRecord",
"if",
"self",
".",
"cutter",
".",
"is_3overhang",
"(",
")",
":",
"start",
",",
"end",
"=",
"self",
".",
"_match",
".",
"span",
"(",
"2",
")",
"[",
"0",
"]",
",",
"self",
".",... | 44.916667 | 21.916667 |
def add_static_url(self, url_path, directory, endpoint=None, roles=None):
"""Add a new url rule for static files.
:param url_path: subpath from application static url path. No heading
or trailing slash.
:param directory: directory to serve content from.
:param endpoint: flas... | [
"def",
"add_static_url",
"(",
"self",
",",
"url_path",
",",
"directory",
",",
"endpoint",
"=",
"None",
",",
"roles",
"=",
"None",
")",
":",
"url_path",
"=",
"self",
".",
"static_url_path",
"+",
"\"/\"",
"+",
"url_path",
"+",
"\"/<path:filename>\"",
"self",
... | 38.888889 | 23.333333 |
def _handle_properties(self, stmt: Statement, sctx: SchemaContext) -> None:
"""Handle **bit** statements."""
nextpos = 0
for bst in stmt.find_all("bit"):
if not sctx.schema_data.if_features(bst, sctx.text_mid):
continue
label = bst.argument
pst... | [
"def",
"_handle_properties",
"(",
"self",
",",
"stmt",
":",
"Statement",
",",
"sctx",
":",
"SchemaContext",
")",
"->",
"None",
":",
"nextpos",
"=",
"0",
"for",
"bst",
"in",
"stmt",
".",
"find_all",
"(",
"\"bit\"",
")",
":",
"if",
"not",
"sctx",
".",
... | 36.25 | 11.75 |
def add_to_rc(self, content):
"""
add content to the rc script.
"""
if not self.rewrite_config:
raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.")
if not self.rc_file:
self.rc_path, self.rc_file = self.__get_rc_handle(self.r... | [
"def",
"add_to_rc",
"(",
"self",
",",
"content",
")",
":",
"if",
"not",
"self",
".",
"rewrite_config",
":",
"raise",
"DirectoryException",
"(",
"\"Error! Directory was not intialized w/ rewrite_config.\"",
")",
"if",
"not",
"self",
".",
"rc_file",
":",
"self",
"."... | 40.333333 | 13.666667 |
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
... | [
"def",
"_check_for_changes",
"(",
"entity_type",
",",
"ret",
",",
"existing",
",",
"modified",
")",
":",
"ret",
"[",
"'result'",
"]",
"=",
"True",
"#were there any changes? generation always changes, remove it.",
"if",
"isinstance",
"(",
"existing",
",",
"dict",
")"... | 45.617647 | 33.911765 |
def get_user_policy(self, user_name, policy_name):
"""
Retrieves the specified policy document for the specified user.
:type user_name: string
:param user_name: The name of the user the policy is associated with.
:type policy_name: string
:param policy_name: The policy ... | [
"def",
"get_user_policy",
"(",
"self",
",",
"user_name",
",",
"policy_name",
")",
":",
"params",
"=",
"{",
"'UserName'",
":",
"user_name",
",",
"'PolicyName'",
":",
"policy_name",
"}",
"return",
"self",
".",
"get_response",
"(",
"'GetUserPolicy'",
",",
"params... | 35.928571 | 18.357143 |
def plt2xyz(fname):
"""Convert a Compass plot file to XYZ pointcloud"""
parser = CompassPltParser(fname)
plt = parser.parse()
for segment in plt:
for command in segment:
if command.cmd == 'd':
if plt.utm_zone:
x, y, z = command.x * FT_TO_M, command.y * FT_TO_M, command.z * FT_TO_M
else:
x, y... | [
"def",
"plt2xyz",
"(",
"fname",
")",
":",
"parser",
"=",
"CompassPltParser",
"(",
"fname",
")",
"plt",
"=",
"parser",
".",
"parse",
"(",
")",
"for",
"segment",
"in",
"plt",
":",
"for",
"command",
"in",
"segment",
":",
"if",
"command",
".",
"cmd",
"==... | 29.769231 | 17.769231 |
def download_url(self, project, file_name, run=None, entity=None):
"""Generate download urls
Args:
project (str): The project to download
file_name (str): The name of the file to download
run (str, optional): The run to upload to
entity (str, optional): T... | [
"def",
"download_url",
"(",
"self",
",",
"project",
",",
"file_name",
",",
"run",
"=",
"None",
",",
"entity",
"=",
"None",
")",
":",
"query",
"=",
"gql",
"(",
"'''\n query Model($name: String!, $fileName: String!, $entity: String!, $run: String!) {\n mo... | 39.789474 | 22.578947 |
def _tempfile(filename):
"""
Create a NamedTemporaryFile instance to be passed to atomic_writer
"""
return tempfile.NamedTemporaryFile(mode='w',
dir=os.path.dirname(filename),
prefix=os.path.basename(filename),
... | [
"def",
"_tempfile",
"(",
"filename",
")",
":",
"return",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w'",
",",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
",",
"prefix",
"=",
"os",
".",
"path",
".",
"basename",
... | 46.222222 | 17.111111 |
def get_thumbnail(original, size, **options):
"""
Creates or gets an already created thumbnail for the given image with the given size and
options.
:param original: File-path, url or base64-encoded string of the image that you want an
thumbnail.
:param size: String with the wan... | [
"def",
"get_thumbnail",
"(",
"original",
",",
"size",
",",
"*",
"*",
"options",
")",
":",
"engine",
"=",
"get_engine",
"(",
")",
"cache",
"=",
"get_cache_backend",
"(",
")",
"original",
"=",
"SourceFile",
"(",
"original",
")",
"crop",
"=",
"options",
"."... | 46.945455 | 28.8 |
def transform_system(principal_vec, principal_default, other_vecs,
matrix=None):
"""Transform vectors with either ``matrix`` or based on ``principal_vec``.
The logic of this function is as follows:
- If ``matrix`` is not ``None``, transform ``principal_vec`` and
all vectors in `... | [
"def",
"transform_system",
"(",
"principal_vec",
",",
"principal_default",
",",
"other_vecs",
",",
"matrix",
"=",
"None",
")",
":",
"transformed_vecs",
"=",
"[",
"]",
"principal_vec",
"=",
"np",
".",
"asarray",
"(",
"principal_vec",
",",
"dtype",
"=",
"float",... | 40.773196 | 21.938144 |
def to_tf_matrix(expression_matrix,
gene_names,
tf_names):
"""
:param expression_matrix: numpy matrix. Rows are observations and columns are genes.
:param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index.
:param tf... | [
"def",
"to_tf_matrix",
"(",
"expression_matrix",
",",
"gene_names",
",",
"tf_names",
")",
":",
"tuples",
"=",
"[",
"(",
"index",
",",
"gene",
")",
"for",
"index",
",",
"gene",
"in",
"enumerate",
"(",
"gene_names",
")",
"if",
"gene",
"in",
"tf_names",
"]"... | 45.722222 | 28.166667 |
def update_distant_reference(self, ref):
"""Validate and update the reference in Zotero.
Existing fields not present will be left unmodified.
"""
self.validate_reference_data(ref["data"])
self._zotero_lib.update_item(ref) | [
"def",
"update_distant_reference",
"(",
"self",
",",
"ref",
")",
":",
"self",
".",
"validate_reference_data",
"(",
"ref",
"[",
"\"data\"",
"]",
")",
"self",
".",
"_zotero_lib",
".",
"update_item",
"(",
"ref",
")"
] | 36.571429 | 10 |
def gen_sites(path):
" Seek sites by path. "
for root, _, _ in walklevel(path, 2):
try:
yield Site(root)
except AssertionError:
continue | [
"def",
"gen_sites",
"(",
"path",
")",
":",
"for",
"root",
",",
"_",
",",
"_",
"in",
"walklevel",
"(",
"path",
",",
"2",
")",
":",
"try",
":",
"yield",
"Site",
"(",
"root",
")",
"except",
"AssertionError",
":",
"continue"
] | 22.25 | 18 |
def attrdict(prev, attr_names):
"""attrdict pipe can extract attribute values of object into a dict.
The argument attr_names can be a list or a dict.
If attr_names is a list and its item is not a valid attribute of
prev's object. It will be excluded from yielded dict.
If attr_names is dict and th... | [
"def",
"attrdict",
"(",
"prev",
",",
"attr_names",
")",
":",
"if",
"isinstance",
"(",
"attr_names",
",",
"dict",
")",
":",
"for",
"obj",
"in",
"prev",
":",
"attr_values",
"=",
"dict",
"(",
")",
"for",
"name",
"in",
"attr_names",
".",
"keys",
"(",
")"... | 35.787879 | 16.363636 |
def set_rectangle(self, rectangle):
"""
Set the rectangle for the selection.
:param rectangle:
:return:
"""
if rectangle == self.rectangle():
return False
if rectangle is None:
self.reset()
else:
self.start_point = QgsP... | [
"def",
"set_rectangle",
"(",
"self",
",",
"rectangle",
")",
":",
"if",
"rectangle",
"==",
"self",
".",
"rectangle",
"(",
")",
":",
"return",
"False",
"if",
"rectangle",
"is",
"None",
":",
"self",
".",
"reset",
"(",
")",
"else",
":",
"self",
".",
"sta... | 30.944444 | 13.611111 |
def image_groups_download(self, image_group_id):
"""Get data file for image group with given identifier.
Parameters
----------
image_group_id : string
Unique image group identifier
Returns
-------
FileInfo
Information about image group ar... | [
"def",
"image_groups_download",
"(",
"self",
",",
"image_group_id",
")",
":",
"# Retrieve image group to ensure that it exist",
"img_grp",
"=",
"self",
".",
"image_groups_get",
"(",
"image_group_id",
")",
"if",
"img_grp",
"is",
"None",
":",
"# Return None if image group i... | 34 | 18.538462 |
def query_int_attribute(self, target, display_mask, attr):
"""Return the value of an integer attribute"""
reply = NVCtrlQueryAttributeReplyRequest(display=self.display,
opcode=self.display.get_extension_major(extname),
tar... | [
"def",
"query_int_attribute",
"(",
"self",
",",
"target",
",",
"display_mask",
",",
"attr",
")",
":",
"reply",
"=",
"NVCtrlQueryAttributeReplyRequest",
"(",
"display",
"=",
"self",
".",
"display",
",",
"opcode",
"=",
"self",
".",
"display",
".",
"get_extension... | 57 | 20.636364 |
def decode(self, binSequence):
"""decodes a binary sequence to return a string"""
try:
binSeq = iter(binSequence[0])
except TypeError, te:
binSeq = binSequence
ret = ''
for b in binSeq :
ch = ''
for c in self.charToBin :
if b & self.forma[self.charToBin[c]] > 0 :
ch += c +'/'
if c... | [
"def",
"decode",
"(",
"self",
",",
"binSequence",
")",
":",
"try",
":",
"binSeq",
"=",
"iter",
"(",
"binSequence",
"[",
"0",
"]",
")",
"except",
"TypeError",
",",
"te",
":",
"binSeq",
"=",
"binSequence",
"ret",
"=",
"''",
"for",
"b",
"in",
"binSeq",
... | 22.222222 | 20.444444 |
def pause(self):
"""Pauses a playing animation. A subsequent call to play will continue where it left off."""
if self.state == PygAnimation.PLAYING:
self.elapsedAtPause = self.elapsed
# only change state if it was playing
self.state = PygAnimation.PAUSED
... | [
"def",
"pause",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"==",
"PygAnimation",
".",
"PLAYING",
":",
"self",
".",
"elapsedAtPause",
"=",
"self",
".",
"elapsed",
"# only change state if it was playing\r",
"self",
".",
"state",
"=",
"PygAnimation",
".",... | 38.083333 | 14.75 |
def mark(self, scope='process'):
"""Set up the profiler state to record operator.
Parameters
----------
scope : string, optional
Indicates what scope the marker should refer to.
Can be 'global', 'process', thread', task', and 'marker'
Default is `proc... | [
"def",
"mark",
"(",
"self",
",",
"scope",
"=",
"'process'",
")",
":",
"check_call",
"(",
"_LIB",
".",
"MXProfileSetMarker",
"(",
"self",
".",
"domain",
".",
"handle",
",",
"c_str",
"(",
"self",
".",
"name",
")",
",",
"c_str",
"(",
"scope",
")",
")",
... | 38.454545 | 19.090909 |
def write_word_at(self, index: int, value: Union[int, BitVec, bool, Bool]) -> None:
"""Writes a 32 byte word to memory at the specified index`
:param index: index to write to
:param value: the value to write to memory
"""
try:
# Attempt to concretize value
... | [
"def",
"write_word_at",
"(",
"self",
",",
"index",
":",
"int",
",",
"value",
":",
"Union",
"[",
"int",
",",
"BitVec",
",",
"bool",
",",
"Bool",
"]",
")",
"->",
"None",
":",
"try",
":",
"# Attempt to concretize value",
"if",
"isinstance",
"(",
"value",
... | 40.125 | 16.03125 |
def change_last_focused_widget(self, old, now):
"""To keep track of to the last focused widget"""
if (now is None and QApplication.activeWindow() is not None):
QApplication.activeWindow().setFocus()
self.last_focused_widget = QApplication.focusWidget()
elif now is no... | [
"def",
"change_last_focused_widget",
"(",
"self",
",",
"old",
",",
"now",
")",
":",
"if",
"(",
"now",
"is",
"None",
"and",
"QApplication",
".",
"activeWindow",
"(",
")",
"is",
"not",
"None",
")",
":",
"QApplication",
".",
"activeWindow",
"(",
")",
".",
... | 45.555556 | 14.444444 |
def from_requirement(cls, provider, requirement, parent):
"""Build an instance from a requirement.
"""
candidates = provider.find_matches(requirement)
if not candidates:
raise NoVersionsAvailable(requirement, parent)
return cls(
candidates=candidates,
... | [
"def",
"from_requirement",
"(",
"cls",
",",
"provider",
",",
"requirement",
",",
"parent",
")",
":",
"candidates",
"=",
"provider",
".",
"find_matches",
"(",
"requirement",
")",
"if",
"not",
"candidates",
":",
"raise",
"NoVersionsAvailable",
"(",
"requirement",
... | 38.7 | 15.2 |
def delete_entry(sender, instance, **kwargs):
"""
Deletes Entry instance corresponding to specified instance.
:param sender: the sending class.
:param instance: the instance being deleted.
"""
from ..models import Entry
Entry.objects.get_for_model(instance)[0].delete() | [
"def",
"delete_entry",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"models",
"import",
"Entry",
"Entry",
".",
"objects",
".",
"get_for_model",
"(",
"instance",
")",
"[",
"0",
"]",
".",
"delete",
"(",
")"
] | 29 | 14.2 |
def get_compile_mode(node):
"""
Get the mode for `compile` of a given node. If the node is not a `mod`
node (`Expression`, `Module` etc.) a `TypeError` is thrown.
"""
if not isinstance(node, mod):
raise TypeError('expected mod node, got %r' % node.__class__.__name__)
return {
Ex... | [
"def",
"get_compile_mode",
"(",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"mod",
")",
":",
"raise",
"TypeError",
"(",
"'expected mod node, got %r'",
"%",
"node",
".",
"__class__",
".",
"__name__",
")",
"return",
"{",
"Expression",
":",
... | 35.545455 | 15.909091 |
def _refined_glimpse_sensor(self, x_t, l_p):
"""
Parameters:
x_t - 28x28 image
l_p - 2x1 focus vector
Returns:
7*14 matrix
"""
# Turn l_p to the left-top point of rectangle
l_p = l_p * 14 + 14 - 4
l_p = T.cast(T.round(l_p), "int... | [
"def",
"_refined_glimpse_sensor",
"(",
"self",
",",
"x_t",
",",
"l_p",
")",
":",
"# Turn l_p to the left-top point of rectangle",
"l_p",
"=",
"l_p",
"*",
"14",
"+",
"14",
"-",
"4",
"l_p",
"=",
"T",
".",
"cast",
"(",
"T",
".",
"round",
"(",
"l_p",
")",
... | 34.111111 | 14.444444 |
def update(self, path, node):
'''Update the dict with a new color using a 'path' through the dict. You can either pass an existing path e.g.
'Scaffold.mutations' to override a color or part of the hierarchy or you can add a new leaf node or dict.'''
assert(type(path) == type(self.name))
... | [
"def",
"update",
"(",
"self",
",",
"path",
",",
"node",
")",
":",
"assert",
"(",
"type",
"(",
"path",
")",
"==",
"type",
"(",
"self",
".",
"name",
")",
")",
"assert",
"(",
"type",
"(",
"node",
")",
"==",
"type",
"(",
"self",
".",
"name",
")",
... | 47.076923 | 26.153846 |
def _process_hdu (self, hdu):
"We've hacked the load order a bit to get t0 and mjd0 in _process_main()."
if hdu.name == 'EVENTS':
pass
else:
super (Events, self)._process_hdu (hdu) | [
"def",
"_process_hdu",
"(",
"self",
",",
"hdu",
")",
":",
"if",
"hdu",
".",
"name",
"==",
"'EVENTS'",
":",
"pass",
"else",
":",
"super",
"(",
"Events",
",",
"self",
")",
".",
"_process_hdu",
"(",
"hdu",
")"
] | 31.857143 | 23.285714 |
def page(self, number):
"""
Returns a Page object for the given 1-based page number.
"""
number = self.validate_number(number)
bottom = (number - 1) * self.per_page
top = bottom + self.per_page
page_items = self.object_list[bottom:top]
# check moved from v... | [
"def",
"page",
"(",
"self",
",",
"number",
")",
":",
"number",
"=",
"self",
".",
"validate_number",
"(",
"number",
")",
"bottom",
"=",
"(",
"number",
"-",
"1",
")",
"*",
"self",
".",
"per_page",
"top",
"=",
"bottom",
"+",
"self",
".",
"per_page",
"... | 37.666667 | 11.933333 |
def search_index_path(self, index=None, **options):
"""
Builds a Yokozuna search index URL.
:param index: optional name of a yz index
:type index: string
:param options: optional list of additional arguments
:type index: dict
:rtype URL string
"""
... | [
"def",
"search_index_path",
"(",
"self",
",",
"index",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"if",
"not",
"self",
".",
"yz_wm_index",
":",
"raise",
"RiakError",
"(",
"\"Yokozuna search is unsupported by this Riak node\"",
")",
"if",
"index",
":",
"q... | 35.066667 | 15.6 |
def weighted_sum(groupe, var):
'''
Fonction qui calcule la moyenne pondérée par groupe d'une variable
'''
data = groupe[var]
weights = groupe['pondmen']
return (data * weights).sum() | [
"def",
"weighted_sum",
"(",
"groupe",
",",
"var",
")",
":",
"data",
"=",
"groupe",
"[",
"var",
"]",
"weights",
"=",
"groupe",
"[",
"'pondmen'",
"]",
"return",
"(",
"data",
"*",
"weights",
")",
".",
"sum",
"(",
")"
] | 28.571429 | 20 |
def launchd(
state, host, name,
running=True, restarted=False, command=None,
):
'''
Manage the state of systemd managed services.
+ name: name of the service to manage
+ running: whether the service should be running
+ restarted: whether the service should be restarted
+ command: custom... | [
"def",
"launchd",
"(",
"state",
",",
"host",
",",
"name",
",",
"running",
"=",
"True",
",",
"restarted",
"=",
"False",
",",
"command",
"=",
"None",
",",
")",
":",
"yield",
"_handle_service_control",
"(",
"name",
",",
"host",
".",
"fact",
".",
"launchd_... | 34.37037 | 19.407407 |
def calculate(self, T, method):
r'''Method to calculate low-pressure gas thermal conductivity at
tempearture `T` with a given method.
This method has no exception handling; see `T_dependent_property`
for that.
Parameters
----------
T : float
Temperat... | [
"def",
"calculate",
"(",
"self",
",",
"T",
",",
"method",
")",
":",
"if",
"method",
"==",
"GHARAGHEIZI_G",
":",
"kg",
"=",
"Gharagheizi_gas",
"(",
"T",
",",
"self",
".",
"MW",
",",
"self",
".",
"Tb",
",",
"self",
".",
"Pc",
",",
"self",
".",
"ome... | 43.980392 | 21.117647 |
def reference_pix_from_wcs_imgs(imgs, pixref, origin=1):
"""Compute reference pixels between frames using WCS information.
The sky world coordinates are computed on *pixref* using
the WCS of the first frame in the sequence. Then, the
pixel coordinates of the reference sky world-coordinates
are comp... | [
"def",
"reference_pix_from_wcs_imgs",
"(",
"imgs",
",",
"pixref",
",",
"origin",
"=",
"1",
")",
":",
"result",
"=",
"[",
"]",
"refimg",
"=",
"imgs",
"[",
"0",
"]",
"wcsh",
"=",
"wcs",
".",
"WCS",
"(",
"refimg",
"[",
"0",
"]",
".",
"header",
")",
... | 28.333333 | 20.62963 |
def validate_checksum( filename, md5sum ):
"""
Compares the md5 checksum of a file with an expected value.
If the calculated and expected checksum values are not equal,
ValueError is raised.
If the filename `foo` is not found, will try to read a gzipped file named
`foo.gz`. In this case, the ch... | [
"def",
"validate_checksum",
"(",
"filename",
",",
"md5sum",
")",
":",
"filename",
"=",
"match_filename",
"(",
"filename",
")",
"md5_hash",
"=",
"file_md5",
"(",
"filename",
"=",
"filename",
")",
"if",
"md5_hash",
"!=",
"md5sum",
":",
"raise",
"ValueError",
"... | 36.736842 | 20.842105 |
def readchunk(self):
"""Reads a chunk at a time. If the current position is within a
chunk the remainder of the chunk is returned.
"""
received = len(self.__buffer)
chunk_data = EMPTY
chunk_size = int(self.chunk_size)
if received > 0:
chunk_data = sel... | [
"def",
"readchunk",
"(",
"self",
")",
":",
"received",
"=",
"len",
"(",
"self",
".",
"__buffer",
")",
"chunk_data",
"=",
"EMPTY",
"chunk_size",
"=",
"int",
"(",
"self",
".",
"chunk_size",
")",
"if",
"received",
">",
"0",
":",
"chunk_data",
"=",
"self",... | 36.2 | 16.2 |
def replace(self, key):
"""Selects a different image to be shown.
Parameters:
| key - a key in the original dictionary to specify which image to show
"""
if not (key in self.imagesDict):
print('The key', key, 'was not found in the collection of images di... | [
"def",
"replace",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"(",
"key",
"in",
"self",
".",
"imagesDict",
")",
":",
"print",
"(",
"'The key'",
",",
"key",
",",
"'was not found in the collection of images dictionary'",
")",
"raise",
"KeyError",
"self",
"... | 36.238095 | 19.380952 |
def _parse_broadcast(self, msg):
"""
Given a broacast message, returns the message that was broadcast.
"""
# get message, remove surrounding quotes, and unescape
return self._unescape(self._get_type(msg[self.broadcast_prefix_len:])) | [
"def",
"_parse_broadcast",
"(",
"self",
",",
"msg",
")",
":",
"# get message, remove surrounding quotes, and unescape",
"return",
"self",
".",
"_unescape",
"(",
"self",
".",
"_get_type",
"(",
"msg",
"[",
"self",
".",
"broadcast_prefix_len",
":",
"]",
")",
")"
] | 44.5 | 16.833333 |
def _strict_date(self, lean):
"""
Return a `time.struct_time` representation of the date.
"""
return struct_time(
(
self._precise_year(lean),
self._precise_month(lean),
self._precise_day(lean),
) + tuple(TIME_EMPTY_T... | [
"def",
"_strict_date",
"(",
"self",
",",
"lean",
")",
":",
"return",
"struct_time",
"(",
"(",
"self",
".",
"_precise_year",
"(",
"lean",
")",
",",
"self",
".",
"_precise_month",
"(",
"lean",
")",
",",
"self",
".",
"_precise_day",
"(",
"lean",
")",
",",... | 31.909091 | 12.090909 |
def disable(self, clear_cache=True):
"""
Disable the cache and clear its contents
:param clear_cache: clear the cache contents as well as disabling (defaults to True)
"""
logger.debug('disable(clear_cache={})'.format(clear_cache))
if clear_cache:
self.clear()... | [
"def",
"disable",
"(",
"self",
",",
"clear_cache",
"=",
"True",
")",
":",
"logger",
".",
"debug",
"(",
"'disable(clear_cache={})'",
".",
"format",
"(",
"clear_cache",
")",
")",
"if",
"clear_cache",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"optio... | 35 | 15.545455 |
def plot_conf(fignum, s, datablock, pars, new):
"""
plots directions and confidence ellipses
"""
# make the stereonet
if new == 1:
plot_net(fignum)
#
# plot the data
#
DIblock = []
for plotrec in datablock:
DIblock.append((float(plotrec["dec"]), float(plotrec["inc"])))
if l... | [
"def",
"plot_conf",
"(",
"fignum",
",",
"s",
",",
"datablock",
",",
"pars",
",",
"new",
")",
":",
"# make the stereonet",
"if",
"new",
"==",
"1",
":",
"plot_net",
"(",
"fignum",
")",
"#",
"# plot the data",
"#",
"DIblock",
"=",
"[",
"]",
"for",
"plot... | 24.057143 | 20.171429 |
def list_items(item, details=False, group_by='UUID'):
'''
Return a list of a specific type of item. The following items are available:
vms
runningvms
ostypes
hostdvds
hostfloppies
intnets
bridgedifs
hostonlyifs
natnets
dhcpservers
... | [
"def",
"list_items",
"(",
"item",
",",
"details",
"=",
"False",
",",
"group_by",
"=",
"'UUID'",
")",
":",
"types",
"=",
"(",
"'vms'",
",",
"'runningvms'",
",",
"'ostypes'",
",",
"'hostdvds'",
",",
"'hostfloppies'",
",",
"'intnets'",
",",
"'bridgedifs'",
",... | 27.4 | 24.253333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.