text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def guess_depth(self, root_dir):
"""
Try to guess the depth of a directory repository (i.e. whether it has
sub-folders for multiple subjects or visits, depending on where files
and/or derived label files are found in the hierarchy of
sub-directories under the root dir.
P... | [
"def",
"guess_depth",
"(",
"self",
",",
"root_dir",
")",
":",
"deepest",
"=",
"-",
"1",
"for",
"path",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"root_dir",
")",
":",
"depth",
"=",
"self",
".",
"path_depth",
"(",
"path",
")",
"filter... | 44.708333 | 0.000912 |
def _read_remaining(socket):
"""
Reads everything available from the socket - used for debugging when there
is a protocol error
:param socket:
The socket to read from
:return:
A byte string of the remaining data
"""
output = b''
old_timeout = socket.gettimeout()
tr... | [
"def",
"_read_remaining",
"(",
"socket",
")",
":",
"output",
"=",
"b''",
"old_timeout",
"=",
"socket",
".",
"gettimeout",
"(",
")",
"try",
":",
"socket",
".",
"settimeout",
"(",
"0.0",
")",
"output",
"+=",
"socket",
".",
"recv",
"(",
"8192",
")",
"exce... | 21.772727 | 0.002 |
def _sort_schema(schema):
"""Recursively sorts a JSON schema by dict key."""
if isinstance(schema, dict):
for k, v in sorted(schema.items()):
if isinstance(v, dict):
yield k, OrderedDict(_sort_schema(v))
elif isinstance(v, list):
yield k, list(_so... | [
"def",
"_sort_schema",
"(",
"schema",
")",
":",
"if",
"isinstance",
"(",
"schema",
",",
"dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"schema",
".",
"items",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
... | 31.190476 | 0.001481 |
def get_mv_feeder_from_line(line):
"""
Determines MV feeder the given line is in.
MV feeders are identified by the first line segment of the half-ring.
Parameters
----------
line : :class:`~.grid.components.Line`
Line to find the MV feeder for.
Returns
-------
:class:`~.gr... | [
"def",
"get_mv_feeder_from_line",
"(",
"line",
")",
":",
"try",
":",
"# get nodes of line",
"nodes",
"=",
"line",
".",
"grid",
".",
"graph",
".",
"nodes_from_line",
"(",
"line",
")",
"# get feeders",
"feeders",
"=",
"{",
"}",
"for",
"node",
"in",
"nodes",
... | 30.217391 | 0.001394 |
def up(self,x):
"""
Upsample and filter the signal
"""
y = self.M*ssd.upsample(x,self.M)
y = signal.lfilter(self.b,self.a,y)
return y | [
"def",
"up",
"(",
"self",
",",
"x",
")",
":",
"y",
"=",
"self",
".",
"M",
"*",
"ssd",
".",
"upsample",
"(",
"x",
",",
"self",
".",
"M",
")",
"y",
"=",
"signal",
".",
"lfilter",
"(",
"self",
".",
"b",
",",
"self",
".",
"a",
",",
"y",
")",
... | 25 | 0.033149 |
def get_load_balancer(self, id):
"""
Returns a Load Balancer object by its ID.
Args:
id (str): Load Balancer ID
"""
return LoadBalancer.get_object(api_token=self.token, id=id) | [
"def",
"get_load_balancer",
"(",
"self",
",",
"id",
")",
":",
"return",
"LoadBalancer",
".",
"get_object",
"(",
"api_token",
"=",
"self",
".",
"token",
",",
"id",
"=",
"id",
")"
] | 29.125 | 0.008333 |
def _backspace(self):
"""Erase the last character in the snippet command."""
if self.command == ':':
return
logger.log(5, "Snippet keystroke `Backspace`.")
self.command = self.command[:-1] | [
"def",
"_backspace",
"(",
"self",
")",
":",
"if",
"self",
".",
"command",
"==",
"':'",
":",
"return",
"logger",
".",
"log",
"(",
"5",
",",
"\"Snippet keystroke `Backspace`.\"",
")",
"self",
".",
"command",
"=",
"self",
".",
"command",
"[",
":",
"-",
"1... | 37.833333 | 0.008621 |
def id_matches(unique_id, target_name, target_package, nodetypes, model):
"""Return True if the unique ID matches the given name, package, and type.
If package is None, any package is allowed.
nodetypes should be a container of NodeTypes that implements the 'in'
operator.
"""
node_type = model.... | [
"def",
"id_matches",
"(",
"unique_id",
",",
"target_name",
",",
"target_package",
",",
"nodetypes",
",",
"model",
")",
":",
"node_type",
"=",
"model",
".",
"get",
"(",
"'resource_type'",
",",
"'node'",
")",
"node_parts",
"=",
"unique_id",
".",
"split",
"(",
... | 37.387097 | 0.000841 |
def strip_mcs(self, idx):
"""strip(3 byte) radiotap.mcs which contains 802.11n bandwidth,
mcs(modulation and coding scheme) and stbc(space time block coding)
information.
:idx: int
:return: int
idx
:return: collections.namedtuple
"""
mcs = coll... | [
"def",
"strip_mcs",
"(",
"self",
",",
"idx",
")",
":",
"mcs",
"=",
"collections",
".",
"namedtuple",
"(",
"'mcs'",
",",
"[",
"'known'",
",",
"'index'",
",",
"'have_bw'",
",",
"'have_mcs'",
",",
"'have_gi'",
",",
"'have_format'",
",",
"'have_fec'",
",",
"... | 44.793103 | 0.002261 |
def inflate_nd_checker(identifier, definition):
"""
Inflate a no-data checker from a basic definition.
Args:
identifier (str): the no-data checker identifier / name.
definition (bool/dict): a boolean acting as "passes" or a full
dict definition with "pass... | [
"def",
"inflate_nd_checker",
"(",
"identifier",
",",
"definition",
")",
":",
"if",
"isinstance",
"(",
"definition",
",",
"bool",
")",
":",
"return",
"Checker",
"(",
"name",
"=",
"identifier",
",",
"passes",
"=",
"definition",
")",
"elif",
"isinstance",
"(",
... | 39.363636 | 0.002255 |
def action(self, relationship):
"""Add a File Action."""
action_obj = FileAction(self._indicator_data.get('xid'), relationship)
self._file_actions.append(action_obj)
return action_obj | [
"def",
"action",
"(",
"self",
",",
"relationship",
")",
":",
"action_obj",
"=",
"FileAction",
"(",
"self",
".",
"_indicator_data",
".",
"get",
"(",
"'xid'",
")",
",",
"relationship",
")",
"self",
".",
"_file_actions",
".",
"append",
"(",
"action_obj",
")",... | 42.2 | 0.009302 |
def view_task_hazard(token, dstore):
"""
Display info about a given task. Here are a few examples of usage::
$ oq show task_hazard:0 # the fastest task
$ oq show task_hazard:-1 # the slowest task
"""
tasks = set(dstore['task_info'])
if 'source_data' not in dstore:
return 'Missin... | [
"def",
"view_task_hazard",
"(",
"token",
",",
"dstore",
")",
":",
"tasks",
"=",
"set",
"(",
"dstore",
"[",
"'task_info'",
"]",
")",
"if",
"'source_data'",
"not",
"in",
"dstore",
":",
"return",
"'Missing source_data'",
"if",
"'classical_split_filter'",
"in",
"t... | 44.083333 | 0.000925 |
def pmap_field(key_type, value_type, optional=False, invariant=PFIELD_NO_INVARIANT):
"""
Create a checked ``PMap`` field.
:param key: The required type for the keys of the map.
:param value: The required type for the values of the map.
:param optional: If true, ``None`` can be used as a value for
... | [
"def",
"pmap_field",
"(",
"key_type",
",",
"value_type",
",",
"optional",
"=",
"False",
",",
"invariant",
"=",
"PFIELD_NO_INVARIANT",
")",
":",
"TheMap",
"=",
"_make_pmap_field_type",
"(",
"key_type",
",",
"value_type",
")",
"if",
"optional",
":",
"def",
"fact... | 33.692308 | 0.00222 |
def strip_source(self):
"""The source of the interaction with the strip.
If the source is
:attr:`~libinput.constant.TabletPadStripAxisSource.FINGER`, libinput
sends a strip position value of -1 to terminate the current interaction.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_STRI... | [
"def",
"strip_source",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"TABLET_PAD_STRIP",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_libinput",
... | 30.409091 | 0.027536 |
def wait(self, build_id, states):
"""
:param build_id: wait for build to finish
:return:
"""
logger.info("watching build '%s'", build_id)
for changetype, obj in self.watch_resource("builds", build_id):
try:
obj_name = obj["metadata"]["name"]
... | [
"def",
"wait",
"(",
"self",
",",
"build_id",
",",
"states",
")",
":",
"logger",
".",
"info",
"(",
"\"watching build '%s'\"",
",",
"build_id",
")",
"for",
"changetype",
",",
"obj",
"in",
"self",
".",
"watch_resource",
"(",
"\"builds\"",
",",
"build_id",
")"... | 44.634146 | 0.002139 |
def get_current_word_and_position(self, completion=False):
"""Return current word, i.e. word at cursor position,
and the start position"""
cursor = self.textCursor()
if cursor.hasSelection():
# Removes the selection and moves the cursor to the left side
... | [
"def",
"get_current_word_and_position",
"(",
"self",
",",
"completion",
"=",
"False",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"if",
"cursor",
".",
"hasSelection",
"(",
")",
":",
"# Removes the selection and moves the cursor to the left side\r",
... | 52.304348 | 0.000816 |
def add_timeline_to_sketch(self, sketch_id, index_id):
"""Associate the specified timeline and sketch.
Args:
sketch_id (int): ID of sketch
index_id (int): ID of timeline to add to sketch
"""
resource_url = '{0:s}/sketches/{1:d}/timelines/'.format(
self.api_base_url, sketch_id)
f... | [
"def",
"add_timeline_to_sketch",
"(",
"self",
",",
"sketch_id",
",",
"index_id",
")",
":",
"resource_url",
"=",
"'{0:s}/sketches/{1:d}/timelines/'",
".",
"format",
"(",
"self",
".",
"api_base_url",
",",
"sketch_id",
")",
"form_data",
"=",
"{",
"'timeline'",
":",
... | 36.090909 | 0.002457 |
def plot_d_delta_m(fignum, Bdm, DdeltaM, s):
"""
function to plot d (Delta M)/dB curves
Parameters
__________
fignum : matplotlib figure number
Bdm : change in field
Ddelta M : change in delta M
s : specimen name
"""
plt.figure(num=fignum)
plt.clf()
if not isServer:
... | [
"def",
"plot_d_delta_m",
"(",
"fignum",
",",
"Bdm",
",",
"DdeltaM",
",",
"s",
")",
":",
"plt",
".",
"figure",
"(",
"num",
"=",
"fignum",
")",
"plt",
".",
"clf",
"(",
")",
"if",
"not",
"isServer",
":",
"plt",
".",
"figtext",
"(",
".02",
",",
".01"... | 24.5 | 0.001965 |
def cross_validation(learner, dataset, k=10, trials=1):
"""Do k-fold cross_validate and return their mean.
That is, keep out 1/k of the examples for testing on each of k runs.
Shuffle the examples first; If trials>1, average over several shuffles."""
if k is None:
k = len(dataset.examples)
i... | [
"def",
"cross_validation",
"(",
"learner",
",",
"dataset",
",",
"k",
"=",
"10",
",",
"trials",
"=",
"1",
")",
":",
"if",
"k",
"is",
"None",
":",
"k",
"=",
"len",
"(",
"dataset",
".",
"examples",
")",
"if",
"trials",
">",
"1",
":",
"return",
"mean... | 45.5 | 0.001538 |
def _get_available_encodings():
"""Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709
"""
available_encodings = set(encodings.aliases.aliases.values())
paths = [os.path.dirname(encodings.__... | [
"def",
"_get_available_encodings",
"(",
")",
":",
"available_encodings",
"=",
"set",
"(",
"encodings",
".",
"aliases",
".",
"aliases",
".",
"values",
"(",
")",
")",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"encodings",
".",
"__file__",
... | 41.692308 | 0.001805 |
def pay_order_query(self, out_trade_no):
"""
查询订单状态
一般用于无法确定 订单状态时候补偿
:param out_trade_no: 本地订单号
:return: 订单信息dict
"""
package = {
'partner': self.pay_partner_id,
'out_trade_no': out_trade_no,
}
_package = package.items()... | [
"def",
"pay_order_query",
"(",
"self",
",",
"out_trade_no",
")",
":",
"package",
"=",
"{",
"'partner'",
":",
"self",
".",
"pay_partner_id",
",",
"'out_trade_no'",
":",
"out_trade_no",
",",
"}",
"_package",
"=",
"package",
".",
"items",
"(",
")",
"_package",
... | 24.567568 | 0.002116 |
def zGetSurfaceData(self, surfNum):
"""Return surface data"""
if self.pMode == 0: # Sequential mode
surf_data = _co.namedtuple('surface_data', ['radius', 'thick', 'material', 'semidia',
'conic', 'comment'])
surf = self.pLDE... | [
"def",
"zGetSurfaceData",
"(",
"self",
",",
"surfNum",
")",
":",
"if",
"self",
".",
"pMode",
"==",
"0",
":",
"# Sequential mode",
"surf_data",
"=",
"_co",
".",
"namedtuple",
"(",
"'surface_data'",
",",
"[",
"'radius'",
",",
"'thick'",
",",
"'material'",
",... | 59 | 0.011686 |
def dump_ddl(metadata: MetaData,
dialect_name: str,
fileobj: TextIO = sys.stdout,
checkfirst: bool = True) -> None:
"""
Sends schema-creating DDL from the metadata to the dump engine.
This makes ``CREATE TABLE`` statements.
Args:
metadata: SQLAlchemy :clas... | [
"def",
"dump_ddl",
"(",
"metadata",
":",
"MetaData",
",",
"dialect_name",
":",
"str",
",",
"fileobj",
":",
"TextIO",
"=",
"sys",
".",
"stdout",
",",
"checkfirst",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"# http://docs.sqlalchemy.org/en/rel_0_8/faq.ht... | 47.428571 | 0.000738 |
def smoothMLS1D(actor, f=0.2, showNLines=0):
"""
Smooth actor or points with a `Moving Least Squares` variant.
The list ``actor.info['variances']`` contain the residue calculated for each point.
Input actor's polydata is modified.
:param float f: smoothing factor - typical range is [0,2].
:para... | [
"def",
"smoothMLS1D",
"(",
"actor",
",",
"f",
"=",
"0.2",
",",
"showNLines",
"=",
"0",
")",
":",
"coords",
"=",
"actor",
".",
"coordinates",
"(",
")",
"ncoords",
"=",
"len",
"(",
"coords",
")",
"Ncp",
"=",
"int",
"(",
"ncoords",
"*",
"f",
"/",
"1... | 32.140625 | 0.001887 |
def get_shutit_pexpect_session_from_child(self, shutit_pexpect_child):
"""Given a pexpect/child object, return the shutit_pexpect_session object.
"""
shutit_global.shutit_global_object.yield_to_draw()
if not isinstance(shutit_pexpect_child, pexpect.pty_spawn.spawn):
self.fail('Wrong type in get_shutit_pexpec... | [
"def",
"get_shutit_pexpect_session_from_child",
"(",
"self",
",",
"shutit_pexpect_child",
")",
":",
"shutit_global",
".",
"shutit_global_object",
".",
"yield_to_draw",
"(",
")",
"if",
"not",
"isinstance",
"(",
"shutit_pexpect_child",
",",
"pexpect",
".",
"pty_spawn",
... | 66.4 | 0.023774 |
def exists(self, **kwargs):
"""
Returns true if a database with the given name exists. False otherwise.
"""
name = kwargs.pop('name', 'default')
site = kwargs.pop('site', None)
r = self.database_renderer(name=name, site=site)
ret = r.run('mysql -h {db_host} -u {db... | [
"def",
"exists",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
",",
"'default'",
")",
"site",
"=",
"kwargs",
".",
"pop",
"(",
"'site'",
",",
"None",
")",
"r",
"=",
"self",
".",
"database_renderer"... | 42.238095 | 0.00882 |
def generate_crontab(current_crontab, path_to_jobs, path_to_app, unique_id):
"""Returns a crontab with jobs from job path
It replaces jobs previously generated by this function
It preserves jobs not generated by this function
"""
set_disable_envar = ''
if os.environ.get('DISABLE_COLLECTORS') ==... | [
"def",
"generate_crontab",
"(",
"current_crontab",
",",
"path_to_jobs",
",",
"path_to_app",
",",
"unique_id",
")",
":",
"set_disable_envar",
"=",
"''",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'DISABLE_COLLECTORS'",
")",
"==",
"'true'",
":",
"set_disable_en... | 37 | 0.000454 |
def is_lower(self):
"""Asserts that val is non-empty string and all characters are lowercase."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if len(self.val) == 0:
raise ValueError('val is empty')
if self.val != self.val.lower():... | [
"def",
"is_lower",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"val",
",",
"str_types",
")",
":",
"raise",
"TypeError",
"(",
"'val is not a string'",
")",
"if",
"len",
"(",
"self",
".",
"val",
")",
"==",
"0",
":",
"raise",
"Va... | 47.555556 | 0.009174 |
def _post_processing(kwargs, skip_translate, invalid):
'''
Additional container-specific post-translation processing
'''
# Don't allow conflicting options to be set
if kwargs.get('port_bindings') is not None \
and kwargs.get('publish_all_ports'):
kwargs.pop('port_bindings')
... | [
"def",
"_post_processing",
"(",
"kwargs",
",",
"skip_translate",
",",
"invalid",
")",
":",
"# Don't allow conflicting options to be set",
"if",
"kwargs",
".",
"get",
"(",
"'port_bindings'",
")",
"is",
"not",
"None",
"and",
"kwargs",
".",
"get",
"(",
"'publish_all_... | 43.28169 | 0.000955 |
def should_return_304(self) -> bool:
"""Returns True if the headers indicate that we should return 304.
.. versionadded:: 3.1
"""
# If client sent If-None-Match, use it, ignore If-Modified-Since
if self.request.headers.get("If-None-Match"):
return self.check_etag_hea... | [
"def",
"should_return_304",
"(",
"self",
")",
"->",
"bool",
":",
"# If client sent If-None-Match, use it, ignore If-Modified-Since",
"if",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"\"If-None-Match\"",
")",
":",
"return",
"self",
".",
"check_etag_header... | 39.333333 | 0.002364 |
def export_to_hdf5(network, path, export_standard_types=False, **kwargs):
"""
Export network and components to an HDF store.
Both static and series attributes of components are exported, but only
if they have non-default values.
If path does not already exist, it is created.
Parameters
--... | [
"def",
"export_to_hdf5",
"(",
"network",
",",
"path",
",",
"export_standard_types",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'complevel'",
",",
"4",
")",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",... | 30.033333 | 0.001075 |
def main_cli():
"""CLI minimal interface."""
# Get params
args = _cli_argument_parser()
delta_secs = args.delay
i2cbus = args.bus
i2c_address = args.address
sensor_key = args.sensor
sensor_params = args.params
params = {}
if sensor_params:
def _parse_param(str_param):
... | [
"def",
"main_cli",
"(",
")",
":",
"# Get params",
"args",
"=",
"_cli_argument_parser",
"(",
")",
"delta_secs",
"=",
"args",
".",
"delay",
"i2cbus",
"=",
"args",
".",
"bus",
"i2c_address",
"=",
"args",
".",
"address",
"sensor_key",
"=",
"args",
".",
"sensor... | 31.4 | 0.001158 |
def final_bounces(fetches, url):
"""
Resolves redirect chains in `fetches` and returns a list of fetches
representing the final redirect destinations of the given url. There could
be more than one if for example youtube-dl hit the same url with HEAD and
then GET requests.
"""
redirects = {}
... | [
"def",
"final_bounces",
"(",
"fetches",
",",
"url",
")",
":",
"redirects",
"=",
"{",
"}",
"for",
"fetch",
"in",
"fetches",
":",
"# XXX check http status 301,302,303,307? check for \"uri\" header",
"# as well as \"location\"? see urllib.request.HTTPRedirectHandler",
"if",
"'lo... | 35.576923 | 0.008421 |
def make_archive(name, repo, ref, destdir):
"""Makes an archive of a repository in the given destdir.
:param text name: Name to give the archive. For instance foo. The file
that is created will be called foo.tar.gz.
:param text repo: Repository to clone.
:param text ref: Tag/SHA/branch to check o... | [
"def",
"make_archive",
"(",
"name",
",",
"repo",
",",
"ref",
",",
"destdir",
")",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destdir",
",",
"name",
"+",
"'.tar.gz'",
")",
"with",
"tmpdir",
"(",
")",
"as",
"tempdir",
":",
"# Clone ... | 38 | 0.00107 |
def ts(when, tz=None):
"""
Return a Unix timestamp in seconds for the provided datetime. The `totz` function is called
on the datetime to convert it to the provided timezone. It will be converted to UTC if no
timezone is provided.
"""
if not when:
return None
when = totz(when, tz)
... | [
"def",
"ts",
"(",
"when",
",",
"tz",
"=",
"None",
")",
":",
"if",
"not",
"when",
":",
"return",
"None",
"when",
"=",
"totz",
"(",
"when",
",",
"tz",
")",
"return",
"calendar",
".",
"timegm",
"(",
"when",
".",
"timetuple",
"(",
")",
")"
] | 35.3 | 0.008287 |
def commonancestors(*nodes):
"""
Determine common ancestors of `nodes`.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> dan = Node("Dan", parent=udo)
>>> jet = Node("Jet", parent=dan)
>>> jan = Node("Jan... | [
"def",
"commonancestors",
"(",
"*",
"nodes",
")",
":",
"ancestors",
"=",
"[",
"node",
".",
"ancestors",
"for",
"node",
"in",
"nodes",
"]",
"common",
"=",
"[",
"]",
"for",
"parentnodes",
"in",
"zip",
"(",
"*",
"ancestors",
")",
":",
"parentnode",
"=",
... | 28.193548 | 0.001106 |
def wrap_create_channel(create_channel_func, tracer=None):
"""Wrap the google.api_core.grpc_helpers.create_channel."""
def call(*args, **kwargs):
channel = create_channel_func(*args, **kwargs)
try:
target = kwargs.get('target')
tracer_interceptor = OpenCensusClientInterc... | [
"def",
"wrap_create_channel",
"(",
"create_channel_func",
",",
"tracer",
"=",
"None",
")",
":",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"channel",
"=",
"create_channel_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"... | 40.235294 | 0.001429 |
def getexistingdirectory(parent=None, caption='', basedir='',
options=QFileDialog.ShowDirsOnly):
"""Wrapper around QtGui.QFileDialog.getExistingDirectory static method
Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0"""
# Calling QFileDialog static method
if sy... | [
"def",
"getexistingdirectory",
"(",
"parent",
"=",
"None",
",",
"caption",
"=",
"''",
",",
"basedir",
"=",
"''",
",",
"options",
"=",
"QFileDialog",
".",
"ShowDirsOnly",
")",
":",
"# Calling QFileDialog static method\r",
"if",
"sys",
".",
"platform",
"==",
"\"... | 45.4 | 0.001079 |
def main():
'''
main function.
'''
args = parse_args()
if args.multi_thread:
enable_multi_thread()
if args.advisor_class_name:
# advisor is enabled and starts to run
if args.multi_phase:
raise AssertionError('multi_phase has not been supported in advisor')
... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"if",
"args",
".",
"multi_thread",
":",
"enable_multi_thread",
"(",
")",
"if",
"args",
".",
"advisor_class_name",
":",
"# advisor is enabled and starts to run",
"if",
"args",
".",
"multi_phase",
... | 33.717949 | 0.001108 |
def augment_observation(
observation, reward, cum_reward, frame_index, bar_color=None,
header_height=27
):
"""Augments an observation with debug info."""
img = PIL_Image().new(
"RGB", (observation.shape[1], header_height,)
)
draw = PIL_ImageDraw().Draw(img)
draw.text(
(1, 0), "c:{:3}, r:{:... | [
"def",
"augment_observation",
"(",
"observation",
",",
"reward",
",",
"cum_reward",
",",
"frame_index",
",",
"bar_color",
"=",
"None",
",",
"header_height",
"=",
"27",
")",
":",
"img",
"=",
"PIL_Image",
"(",
")",
".",
"new",
"(",
"\"RGB\"",
",",
"(",
"ob... | 28.090909 | 0.015649 |
def parse_entry(self, entry):
"""An attempt to parse pieces of an entry out w/o xpath, by looping
over the entry root's children and slotting them into the right places.
This is going to be way messier than SpeedParserEntries, and maybe
less cleanly usable, but it should be faster."""
... | [
"def",
"parse_entry",
"(",
"self",
",",
"entry",
")",
":",
"e",
"=",
"feedparser",
".",
"FeedParserDict",
"(",
")",
"tag_map",
"=",
"self",
".",
"tag_map",
"nslookup",
"=",
"self",
".",
"nslookup",
"for",
"child",
"in",
"entry",
".",
"getchildren",
"(",
... | 40.318182 | 0.001651 |
def set_source(self, propname, pores):
r"""
Applies a given source term to the specified pores
Parameters
----------
propname : string
The property name of the source term model to be applied
pores : array_like
The pore indices where the source t... | [
"def",
"set_source",
"(",
"self",
",",
"propname",
",",
"pores",
")",
":",
"locs",
"=",
"self",
".",
"tomask",
"(",
"pores",
"=",
"pores",
")",
"if",
"(",
"not",
"np",
".",
"all",
"(",
"np",
".",
"isnan",
"(",
"self",
"[",
"'pore.bc_value'",
"]",
... | 35.692308 | 0.002099 |
def Betainc(a, b, x):
"""
Complemented, incomplete gamma op.
"""
return sp.special.betainc(a, b, x), | [
"def",
"Betainc",
"(",
"a",
",",
"b",
",",
"x",
")",
":",
"return",
"sp",
".",
"special",
".",
"betainc",
"(",
"a",
",",
"b",
",",
"x",
")",
","
] | 22.4 | 0.008621 |
def update_function_config(FunctionName, Role=None, Handler=None,
Description=None, Timeout=None, MemorySize=None,
region=None, key=None, keyid=None, profile=None,
VpcConfig=None, WaitForRole=False, RoleRetries=5,
... | [
"def",
"update_function_config",
"(",
"FunctionName",
",",
"Role",
"=",
"None",
",",
"Handler",
"=",
"None",
",",
"Description",
"=",
"None",
",",
"Timeout",
"=",
"None",
",",
"MemorySize",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None"... | 37.481013 | 0.001974 |
def Ergun(dp, voidage, vs, rho, mu, L=1):
r'''Calculates pressure drop across a packed bed of spheres using a
correlation developed in [1]_, as shown in [2]_ and [3]_. Eighteenth most
accurate correlation overall in the review of [2]_.
Most often presented in the following form:
.. math::
... | [
"def",
"Ergun",
"(",
"dp",
",",
"voidage",
",",
"vs",
",",
"rho",
",",
"mu",
",",
"L",
"=",
"1",
")",
":",
"Re",
"=",
"dp",
"*",
"rho",
"*",
"vs",
"/",
"mu",
"fp",
"=",
"(",
"150",
"+",
"1.75",
"*",
"(",
"Re",
"/",
"(",
"1",
"-",
"voida... | 36.725 | 0.000994 |
def gen_shell(opts, **kwargs):
'''
Return the correct shell interface for the target system
'''
if kwargs['winrm']:
try:
import saltwinshell
shell = saltwinshell.Shell(opts, **kwargs)
except ImportError:
log.error('The saltwinshell library is not avail... | [
"def",
"gen_shell",
"(",
"opts",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
"[",
"'winrm'",
"]",
":",
"try",
":",
"import",
"saltwinshell",
"shell",
"=",
"saltwinshell",
".",
"Shell",
"(",
"opts",
",",
"*",
"*",
"kwargs",
")",
"except",
"Impo... | 31.071429 | 0.002232 |
def fit(self, X, y, lengths):
"""Fit to a set of sequences.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Feature matrix of individual samples.
y : array-like, shape (n_samples,)
Target labels.
lengths : ar... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"lengths",
")",
":",
"decode",
"=",
"self",
".",
"_get_decoder",
"(",
")",
"X",
"=",
"atleast2d_or_csr",
"(",
"X",
")",
"classes",
",",
"y",
"=",
"np",
".",
"unique",
"(",
"y",
",",
"return_inve... | 33.797386 | 0.000376 |
def _request_json(
url,
parameters=None,
body=None,
headers=None,
cache=True,
agent=None,
reattempt=5,
):
""" Queries a url for json data
Note: Requests are cached using requests_cached for a week, this is done
transparently by using the package's monkey patching
"""
ass... | [
"def",
"_request_json",
"(",
"url",
",",
"parameters",
"=",
"None",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"cache",
"=",
"True",
",",
"agent",
"=",
"None",
",",
"reattempt",
"=",
"5",
",",
")",
":",
"assert",
"url",
"content",
... | 29.225352 | 0.000466 |
def write_header(term='bash', tree_dir=None, name=None):
''' Write proper file header in a given shell format
Parameters:
term (str):
The type of shell header to write, can be "bash", "tsch", or "modules"
tree_dir (str):
The path to this repository
name (str):
... | [
"def",
"write_header",
"(",
"term",
"=",
"'bash'",
",",
"tree_dir",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"assert",
"term",
"in",
"[",
"'bash'",
",",
"'tsch'",
",",
"'modules'",
"]",
",",
"'term must be either bash, tsch, or module'",
"product_dir",... | 28.0625 | 0.002152 |
def vector_to_arr(vec, dim):
"""Reshape a vector to a multidimensional array with dimensions 'dim'.
"""
if len(dim) <= 1:
return vec
array = vec
while len(dim) > 1:
i = 0
outer_array = []
for m in range(reduce(mul, dim[0:-1])):
inner_array = []
... | [
"def",
"vector_to_arr",
"(",
"vec",
",",
"dim",
")",
":",
"if",
"len",
"(",
"dim",
")",
"<=",
"1",
":",
"return",
"vec",
"array",
"=",
"vec",
"while",
"len",
"(",
"dim",
")",
">",
"1",
":",
"i",
"=",
"0",
"outer_array",
"=",
"[",
"]",
"for",
... | 27 | 0.001883 |
def make_datapoint_text(self, x, y, value, style=None):
"""
Add text for a datapoint
"""
if not self.show_data_values:
# do nothing
return
# first lay down the text in a wide white stroke to
# differentiate it from the background
e = etree.SubElement(self.foreground, 'text', {
'x': str(x),
'y... | [
"def",
"make_datapoint_text",
"(",
"self",
",",
"x",
",",
"y",
",",
"value",
",",
"style",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"show_data_values",
":",
"# do nothing",
"return",
"# first lay down the text in a wide white stroke to",
"# differentiate it... | 27.125 | 0.037092 |
def _entries_sorted(self):
""":return: list of entries, in a sorted fashion, first by path, then by stage"""
return sorted(self.entries.values(), key=lambda e: (e.path, e.stage)) | [
"def",
"_entries_sorted",
"(",
"self",
")",
":",
"return",
"sorted",
"(",
"self",
".",
"entries",
".",
"values",
"(",
")",
",",
"key",
"=",
"lambda",
"e",
":",
"(",
"e",
".",
"path",
",",
"e",
".",
"stage",
")",
")"
] | 64 | 0.015464 |
def html_title(self):
"""HTML5-formatted document title (`str`)."""
return self.format_title(format='html5', deparagraph=True,
mathjax=False, smart=True) | [
"def",
"html_title",
"(",
"self",
")",
":",
"return",
"self",
".",
"format_title",
"(",
"format",
"=",
"'html5'",
",",
"deparagraph",
"=",
"True",
",",
"mathjax",
"=",
"False",
",",
"smart",
"=",
"True",
")"
] | 49.75 | 0.009901 |
def run(self):
"""Run when button is pressed."""
inside = 0
for draws in range(1, self.data['samples']):
# generate points and check whether they are inside the unit circle
r1, r2 = (random(), random())
if r1 ** 2 + r2 ** 2 < 1.0:
inside += 1
... | [
"def",
"run",
"(",
"self",
")",
":",
"inside",
"=",
"0",
"for",
"draws",
"in",
"range",
"(",
"1",
",",
"self",
".",
"data",
"[",
"'samples'",
"]",
")",
":",
"# generate points and check whether they are inside the unit circle",
"r1",
",",
"r2",
"=",
"(",
"... | 31.148148 | 0.002307 |
def stop_task(cls, task_tag, stop_dependent=True, stop_requirements=False):
""" Stop started task from registry
:param task_tag: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method
:param stop_dependent: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method
:param stop_requirement... | [
"def",
"stop_task",
"(",
"cls",
",",
"task_tag",
",",
"stop_dependent",
"=",
"True",
",",
"stop_requirements",
"=",
"False",
")",
":",
"registry",
"=",
"cls",
".",
"registry_storage",
"(",
")",
"registry",
".",
"stop_task",
"(",
"task_tag",
",",
"stop_depend... | 53.8 | 0.025594 |
def _trigger(self, obj, old, value, hint=None, setter=None):
''' Unconditionally send a change event notification for the property.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property
... | [
"def",
"_trigger",
"(",
"self",
",",
"obj",
",",
"old",
",",
"value",
",",
"hint",
"=",
"None",
",",
"setter",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'trigger'",
")",
":",
"obj",
".",
"trigger",
"(",
"self",
".",
"name",
",",
... | 38.128205 | 0.001311 |
def flexifunction_buffer_function_ack_encode(self, target_system, target_component, func_index, result):
'''
Flexifunction type and parameters for component at function index from
buffer
target_system : System ID (uint8_t)
targ... | [
"def",
"flexifunction_buffer_function_ack_encode",
"(",
"self",
",",
"target_system",
",",
"target_component",
",",
"func_index",
",",
"result",
")",
":",
"return",
"MAVLink_flexifunction_buffer_function_ack_message",
"(",
"target_system",
",",
"target_component",
",",
"fun... | 55.416667 | 0.008876 |
def name(self):
"""str: name of the file entry, without the full path."""
path = getattr(self.path_spec, 'location', None)
if path is not None and not isinstance(path, py2to3.UNICODE_TYPE):
try:
path = path.decode(self._file_system.encoding)
except UnicodeDecodeError:
path = None... | [
"def",
"name",
"(",
"self",
")",
":",
"path",
"=",
"getattr",
"(",
"self",
".",
"path_spec",
",",
"'location'",
",",
"None",
")",
"if",
"path",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"path",
",",
"py2to3",
".",
"UNICODE_TYPE",
")",
":"... | 40 | 0.008152 |
def list_databases(self, session=None, **kwargs):
"""Get a cursor over the databases of the connected server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
- `**kwargs` (optional): Optional parameters of the
`listDatab... | [
"def",
"list_databases",
"(",
"self",
",",
"session",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd",
"=",
"SON",
"(",
"[",
"(",
"\"listDatabases\"",
",",
"1",
")",
"]",
")",
"cmd",
".",
"update",
"(",
"kwargs",
")",
"admin",
"=",
"self",
... | 38.714286 | 0.0018 |
def circuit_to_tensorflow_runnable(
circuit: circuits.Circuit,
initial_state: Union[int, np.ndarray] = 0,
) -> ComputeFuncAndFeedDict:
"""Returns a compute function and feed_dict for a `cirq.Circuit`'s output.
`result.compute()` will return a `tensorflow.Tensor` with
`tensorflow.pla... | [
"def",
"circuit_to_tensorflow_runnable",
"(",
"circuit",
":",
"circuits",
".",
"Circuit",
",",
"initial_state",
":",
"Union",
"[",
"int",
",",
"np",
".",
"ndarray",
"]",
"=",
"0",
",",
")",
"->",
"ComputeFuncAndFeedDict",
":",
"if",
"not",
"circuit",
".",
... | 45.269231 | 0.000554 |
def _check_satisfiability(self, extra_constraints=(), solver=None, model_callback=None):
"""
This function does a constraint check and returns the solvers state
:param solver: The backend solver object.
:param extra_constraints: Extra constraints (as ASTs) to add to s for... | [
"def",
"_check_satisfiability",
"(",
"self",
",",
"extra_constraints",
"=",
"(",
")",
",",
"solver",
"=",
"None",
",",
"model_callback",
"=",
"None",
")",
":",
"return",
"'SAT'",
"if",
"self",
".",
"satisfiable",
"(",
"extra_constraints",
"=",
"extra_constrain... | 63.6 | 0.009302 |
async def update_keys(ui, envelope, block_error=False, signed_only=False):
"""Find and set the encryption keys in an envolope.
:param ui: the main user interface object
:type ui: alot.ui.UI
:param envolope: the envolope buffer object
:type envolope: alot.buffers.EnvelopeBuffer
:param block_erro... | [
"async",
"def",
"update_keys",
"(",
"ui",
",",
"envelope",
",",
"block_error",
"=",
"False",
",",
"signed_only",
"=",
"False",
")",
":",
"encrypt_keys",
"=",
"[",
"]",
"for",
"header",
"in",
"(",
"'To'",
",",
"'Cc'",
")",
":",
"if",
"header",
"not",
... | 37.803922 | 0.000506 |
def recordItemClass(self, record=None):
"""
Returns the record item class instance linked with this tree widget.
:return <XOrbRecordItem>
"""
if record is not None:
key = type(record)
else:
key = None
return... | [
"def",
"recordItemClass",
"(",
"self",
",",
"record",
"=",
"None",
")",
":",
"if",
"record",
"is",
"not",
"None",
":",
"key",
"=",
"type",
"(",
"record",
")",
"else",
":",
"key",
"=",
"None",
"return",
"self",
".",
"_recordItemClass",
".",
"get",
"("... | 30.75 | 0.010526 |
def debug_out(i):
"""
Input: i - dictionary
Output: return = 0
"""
import copy
import json
ii={}
# Check main unprintable keys
for k in i:
try:
s=json.dumps(i[k])
except Exception as e:
pass
else:
ii[k]=i[k]
# Dump
... | [
"def",
"debug_out",
"(",
"i",
")",
":",
"import",
"copy",
"import",
"json",
"ii",
"=",
"{",
"}",
"# Check main unprintable keys",
"for",
"k",
"in",
"i",
":",
"try",
":",
"s",
"=",
"json",
".",
"dumps",
"(",
"i",
"[",
"k",
"]",
")",
"except",
"Excep... | 14.12 | 0.023873 |
def callback_handler(self):
"""RequestHandler for the OAuth 2.0 redirect callback.
Usage::
app = webapp.WSGIApplication([
('/index', MyIndexHandler),
...,
(decorator.callback_path, decorator.callback_handler())
])
Returns... | [
"def",
"callback_handler",
"(",
"self",
")",
":",
"decorator",
"=",
"self",
"class",
"OAuth2Handler",
"(",
"webapp",
".",
"RequestHandler",
")",
":",
"\"\"\"Handler for the redirect_uri of the OAuth 2.0 dance.\"\"\"",
"@",
"login_required",
"def",
"get",
"(",
"self",
... | 39.685185 | 0.000911 |
def has_state_changed(self):
"""
Detect changes in offline detector and real DNS value.
Detect a change either in the offline detector or a
difference between the real DNS value and what the online
detector last got.
This is efficient, since it only generates minimal dns... | [
"def",
"has_state_changed",
"(",
"self",
")",
":",
"self",
".",
"lastcheck",
"=",
"time",
".",
"time",
"(",
")",
"# prefer offline state change detection:",
"if",
"self",
".",
"detector",
".",
"can_detect_offline",
"(",
")",
":",
"self",
".",
"detector",
".",
... | 35.37931 | 0.001898 |
def bethe_find_crystalfield(populations, hopping):
"""Return the orbital energies to have the system populates as
desired by the given individual populations"""
zero = lambda orb: [bethe_filling_zeroT(-em, tz) - pop \
for em, tz, pop in zip(orb, hopping, populations)]
return... | [
"def",
"bethe_find_crystalfield",
"(",
"populations",
",",
"hopping",
")",
":",
"zero",
"=",
"lambda",
"orb",
":",
"[",
"bethe_filling_zeroT",
"(",
"-",
"em",
",",
"tz",
")",
"-",
"pop",
"for",
"em",
",",
"tz",
",",
"pop",
"in",
"zip",
"(",
"orb",
",... | 44.25 | 0.00831 |
def _eval_grid(grid_params):
"""
This function receives a dictionary with the parameters defining the
radial mesh and returns a `ndarray` with the mesh
"""
eq = grid_params.get("eq").replace(" ", "")
istart, iend = int(grid_params.get("istart")), int(grid_params.get("iend... | [
"def",
"_eval_grid",
"(",
"grid_params",
")",
":",
"eq",
"=",
"grid_params",
".",
"get",
"(",
"\"eq\"",
")",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
")",
"istart",
",",
"iend",
"=",
"int",
"(",
"grid_params",
".",
"get",
"(",
"\"istart\"",
")",
")... | 36.818182 | 0.002406 |
def setup(self):
""" performs data collection for qpid dispatch router """
options = ""
if self.get_option("port"):
options = (options + " -b " + gethostname() +
":%s" % (self.get_option("port")))
# gethostname() is due to DISPATCH-156
# for ei... | [
"def",
"setup",
"(",
"self",
")",
":",
"options",
"=",
"\"\"",
"if",
"self",
".",
"get_option",
"(",
"\"port\"",
")",
":",
"options",
"=",
"(",
"options",
"+",
"\" -b \"",
"+",
"gethostname",
"(",
")",
"+",
"\":%s\"",
"%",
"(",
"self",
".",
"get_opti... | 39.375 | 0.002066 |
def get_function_for_cognito_trigger(self, trigger):
"""
Get the associated function to execute for a cognito trigger
"""
print("get_function_for_cognito_trigger", self.settings.COGNITO_TRIGGER_MAPPING, trigger, self.settings.COGNITO_TRIGGER_MAPPING.get(trigger))
return self.sett... | [
"def",
"get_function_for_cognito_trigger",
"(",
"self",
",",
"trigger",
")",
":",
"print",
"(",
"\"get_function_for_cognito_trigger\"",
",",
"self",
".",
"settings",
".",
"COGNITO_TRIGGER_MAPPING",
",",
"trigger",
",",
"self",
".",
"settings",
".",
"COGNITO_TRIGGER_MA... | 59.333333 | 0.00831 |
def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
"""Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
by ``tarfile.open()``). See ``unpack_archive()`` for an explanation
of the `progress_filter` a... | [
"def",
"unpack_tarfile",
"(",
"filename",
",",
"extract_dir",
",",
"progress_filter",
"=",
"default_filter",
")",
":",
"try",
":",
"tarobj",
"=",
"tarfile",
".",
"open",
"(",
"filename",
")",
"except",
"tarfile",
".",
"TarError",
":",
"raise",
"UnrecognizedFor... | 45.454545 | 0.000979 |
def add_xpaths_to_stream_item(si):
'''Mutably tag tokens with xpath offsets.
Given some stream item, this will tag all tokens from all taggings
in the document that contain character offsets. Note that some
tokens may not have computable xpath offsets, so an xpath offset
for those tokens will not b... | [
"def",
"add_xpaths_to_stream_item",
"(",
"si",
")",
":",
"def",
"sentences_to_xpaths",
"(",
"sentences",
")",
":",
"tokens",
"=",
"sentences_to_char_tokens",
"(",
"sentences",
")",
"offsets",
"=",
"char_tokens_to_char_offsets",
"(",
"tokens",
")",
"return",
"char_of... | 44.911765 | 0.000641 |
def _obtain_lock_or_raise(self):
"""Create a lock file as flag for other instances, mark our instance as lock-holder
:raise IOError: if a lock was already present or a lock file could not be written"""
if self._has_lock():
return
lock_file = self._lock_file_path()
if... | [
"def",
"_obtain_lock_or_raise",
"(",
"self",
")",
":",
"if",
"self",
".",
"_has_lock",
"(",
")",
":",
"return",
"lock_file",
"=",
"self",
".",
"_lock_file_path",
"(",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"lock_file",
")",
":",
"raise",
"IO... | 39.588235 | 0.008708 |
def readPrefixArray(self, kind, numberOfTrees):
"""Read prefix code array"""
prefixes = []
for i in range(numberOfTrees):
if kind==L: alphabet = LiteralAlphabet(i)
elif kind==I: alphabet = InsertAndCopyAlphabet(i)
elif kind==D: alphabet = DistanceAlphabet(
... | [
"def",
"readPrefixArray",
"(",
"self",
",",
"kind",
",",
"numberOfTrees",
")",
":",
"prefixes",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"numberOfTrees",
")",
":",
"if",
"kind",
"==",
"L",
":",
"alphabet",
"=",
"LiteralAlphabet",
"(",
"i",
")",
... | 44.818182 | 0.015905 |
def process_token(self, tok):
"""count lines and track position of classes and functions"""
if tok[0] == Token.Text:
count = tok[1].count('\n')
if count:
self._line += count # adjust linecount
if self._detector.process(tok):
pass # works bee... | [
"def",
"process_token",
"(",
"self",
",",
"tok",
")",
":",
"if",
"tok",
"[",
"0",
"]",
"==",
"Token",
".",
"Text",
":",
"count",
"=",
"tok",
"[",
"1",
"]",
".",
"count",
"(",
"'\\n'",
")",
"if",
"count",
":",
"self",
".",
"_line",
"+=",
"count"... | 47.52381 | 0.001965 |
def visit_Num(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s number as string."""
return str(node.n) | [
"def",
"visit_Num",
"(",
"self",
",",
"node",
":",
"AST",
",",
"dfltChaining",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"return",
"str",
"(",
"node",
".",
"n",
")"
] | 45.666667 | 0.014388 |
def get_source(self, objtxt):
"""Get object source"""
obj, valid = self._eval(objtxt)
if valid:
return getsource(obj) | [
"def",
"get_source",
"(",
"self",
",",
"objtxt",
")",
":",
"obj",
",",
"valid",
"=",
"self",
".",
"_eval",
"(",
"objtxt",
")",
"if",
"valid",
":",
"return",
"getsource",
"(",
"obj",
")"
] | 30.6 | 0.012739 |
def week_schedule(index, on_time=None, off_time=None, off_days=None):
""" Return boolean time series following given week schedule.
Parameters
----------
index : pandas.DatetimeIndex
Datetime index
on_time : str or datetime.time
Daily opening time. Default: '09:00'
off_time : st... | [
"def",
"week_schedule",
"(",
"index",
",",
"on_time",
"=",
"None",
",",
"off_time",
"=",
"None",
",",
"off_days",
"=",
"None",
")",
":",
"if",
"on_time",
"is",
"None",
":",
"on_time",
"=",
"'9:00'",
"if",
"off_time",
"is",
"None",
":",
"off_time",
"=",... | 33.973684 | 0.001506 |
def _check_command_response(response, msg=None, allowable_errors=None,
parse_write_concern_error=False):
"""Check the response to a command for errors.
"""
if "ok" not in response:
# Server didn't recognize our message as a command.
raise OperationFailure(response... | [
"def",
"_check_command_response",
"(",
"response",
",",
"msg",
"=",
"None",
",",
"allowable_errors",
"=",
"None",
",",
"parse_write_concern_error",
"=",
"False",
")",
":",
"if",
"\"ok\"",
"not",
"in",
"response",
":",
"# Server didn't recognize our message as a comman... | 42.222222 | 0.000367 |
def color_sequence(palette=None, n_colors=None):
"""
Return a `ListedColormap` object from a named sequence palette. Useful
for continuous color scheme values and color maps.
Calling this function with ``palette=None`` will return the default
color sequence: Color Brewer RdBu.
Parameters
-... | [
"def",
"color_sequence",
"(",
"palette",
"=",
"None",
",",
"n_colors",
"=",
"None",
")",
":",
"# Select the default colormap if None is passed in.",
"palette",
"=",
"palette",
"or",
"DEFAULT_SEQUENCE",
"# Create a listed color map from the sequence",
"if",
"not",
"isinstanc... | 33.365591 | 0.000626 |
def substitute_xml(cls, value, make_quoted_attribute=False):
"""Substitute XML entities for special XML characters.
:param value: A string to be substituted. The less-than sign
will become <, the greater-than sign will become >,
and any ampersands will become &. If you wan... | [
"def",
"substitute_xml",
"(",
"cls",
",",
"value",
",",
"make_quoted_attribute",
"=",
"False",
")",
":",
"# Escape angle brackets and ampersands.",
"value",
"=",
"cls",
".",
"AMPERSAND_OR_BRACKET",
".",
"sub",
"(",
"cls",
".",
"_substitute_xml_entity",
",",
"value",... | 43.736842 | 0.002356 |
def extract(body, sender):
"""Strips signature from the body of the message.
Returns stripped body and signature as a tuple.
If no signature is found the corresponding returned value is None.
"""
try:
delimiter = get_delimiter(body)
body = body.strip()
if has_signature(bod... | [
"def",
"extract",
"(",
"body",
",",
"sender",
")",
":",
"try",
":",
"delimiter",
"=",
"get_delimiter",
"(",
"body",
")",
"body",
"=",
"body",
".",
"strip",
"(",
")",
"if",
"has_signature",
"(",
"body",
",",
"sender",
")",
":",
"lines",
"=",
"body",
... | 30.16 | 0.001285 |
def slice(self, order_by='pk', n=None):
""" return n objects according to specified ordering """
if n is not None and n < 0:
raise ValueError('slice parameter cannot be negative')
queryset = self.order_by(order_by)
if n is None:
return queryset[0... | [
"def",
"slice",
"(",
"self",
",",
"order_by",
"=",
"'pk'",
",",
"n",
"=",
"None",
")",
":",
"if",
"n",
"is",
"not",
"None",
"and",
"n",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'slice parameter cannot be negative'",
")",
"queryset",
"=",
"self",
"."... | 32.545455 | 0.01087 |
def kill(self) -> None:
"""Kill ffmpeg job."""
self._proc.kill()
self._loop.run_in_executor(None, self._proc.communicate) | [
"def",
"kill",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_proc",
".",
"kill",
"(",
")",
"self",
".",
"_loop",
".",
"run_in_executor",
"(",
"None",
",",
"self",
".",
"_proc",
".",
"communicate",
")"
] | 35.5 | 0.013793 |
def set_dict_item(dct, name_string, set_to):
"""Sets dictionary item identified by name_string to set_to.
name_string is the indentifier generated using flatten_dict.
Maintains the type of the orginal object in dct and tries to convert set_to
to that type.
"""
key_strings = str(name_string).sp... | [
"def",
"set_dict_item",
"(",
"dct",
",",
"name_string",
",",
"set_to",
")",
":",
"key_strings",
"=",
"str",
"(",
"name_string",
")",
".",
"split",
"(",
"'-->'",
")",
"d",
"=",
"dct",
"for",
"ks",
"in",
"key_strings",
"[",
":",
"-",
"1",
"]",
":",
"... | 33.071429 | 0.002101 |
def _check_cellpy_file(self, filename):
"""Get the file-ids for the cellpy_file."""
strip_filenames = True
check_on = self.filestatuschecker
self.logger.debug("checking cellpy-file")
self.logger.debug(filename)
if not os.path.isfile(filename):
self.logger.deb... | [
"def",
"_check_cellpy_file",
"(",
"self",
",",
"filename",
")",
":",
"strip_filenames",
"=",
"True",
"check_on",
"=",
"self",
".",
"filestatuschecker",
"self",
".",
"logger",
".",
"debug",
"(",
"\"checking cellpy-file\"",
")",
"self",
".",
"logger",
".",
"debu... | 37.26 | 0.001046 |
def annotate(self, text, lang = None, customParams = None):
"""
identify the list of entities and nonentities mentioned in the text
@param text: input text to annotate
@param lang: language of the provided document (can be an ISO2 or ISO3 code). If None is provided, the language will be ... | [
"def",
"annotate",
"(",
"self",
",",
"text",
",",
"lang",
"=",
"None",
",",
"customParams",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"lang\"",
":",
"lang",
",",
"\"text\"",
":",
"text",
"}",
"if",
"customParams",
":",
"params",
".",
"update",
"("... | 54.25 | 0.012085 |
def getDecodableAttributes(self, obj, attrs, codec=None):
"""
Returns a dictionary of attributes for C{obj} that has been filtered,
based on the supplied C{attrs}. This allows for fine grain control
over what will finally end up on the object or not.
@param obj: The object that ... | [
"def",
"getDecodableAttributes",
"(",
"self",
",",
"obj",
",",
"attrs",
",",
"codec",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_compiled",
":",
"self",
".",
"compile",
"(",
")",
"changed",
"=",
"False",
"props",
"=",
"set",
"(",
"attrs",
"."... | 28.371795 | 0.00131 |
def UV_B(self):
"""
returns UV = all respected U->Ux in ternary coding (1=V,2=U)
"""
h = reduce(lambda x,y:x&y,(B(g,self.width-1) for g in self))
return UV_B(h, self.width) | [
"def",
"UV_B",
"(",
"self",
")",
":",
"h",
"=",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"&",
"y",
",",
"(",
"B",
"(",
"g",
",",
"self",
".",
"width",
"-",
"1",
")",
"for",
"g",
"in",
"self",
")",
")",
"return",
"UV_B",
"(",
"h",... | 34.5 | 0.033019 |
def linkable_users(self):
"""Search Plone users which are not linked to a contact or lab contact
"""
# Only users with at nost these roles are displayed
linkable_roles = {"Authenticated", "Member", "Client"}
out = []
for user in self.get_users():
userid = us... | [
"def",
"linkable_users",
"(",
"self",
")",
":",
"# Only users with at nost these roles are displayed",
"linkable_roles",
"=",
"{",
"\"Authenticated\"",
",",
"\"Member\"",
",",
"\"Client\"",
"}",
"out",
"=",
"[",
"]",
"for",
"user",
"in",
"self",
".",
"get_users",
... | 36.44 | 0.001069 |
def _refresh_http(api_request, operation_name):
"""Refresh an operation using a JSON/HTTP client.
Args:
api_request (Callable): A callable used to make an API request. This
should generally be
:meth:`google.cloud._http.Connection.api_request`.
operation_name (str): The n... | [
"def",
"_refresh_http",
"(",
"api_request",
",",
"operation_name",
")",
":",
"path",
"=",
"\"operations/{}\"",
".",
"format",
"(",
"operation_name",
")",
"api_response",
"=",
"api_request",
"(",
"method",
"=",
"\"GET\"",
",",
"path",
"=",
"path",
")",
"return"... | 39.866667 | 0.001634 |
def _do_http(opts, profile='default'):
'''
Make the http request and return the data
'''
ret = {}
url = __salt__['config.get']('modjk:{0}:url'.format(profile), '')
user = __salt__['config.get']('modjk:{0}:user'.format(profile), '')
passwd = __salt__['config.get']('modjk:{0}:pass'.format(pr... | [
"def",
"_do_http",
"(",
"opts",
",",
"profile",
"=",
"'default'",
")",
":",
"ret",
"=",
"{",
"}",
"url",
"=",
"__salt__",
"[",
"'config.get'",
"]",
"(",
"'modjk:{0}:url'",
".",
"format",
"(",
"profile",
")",
",",
"''",
")",
"user",
"=",
"__salt__",
"... | 31.833333 | 0.001016 |
def cli(ctx, env):
"""Print shell help text."""
env.out("Welcome to the SoftLayer shell.")
env.out("")
formatter = formatting.HelpFormatter()
commands = []
shell_commands = []
for name in cli_core.cli.list_commands(ctx):
command = cli_core.cli.get_command(ctx, name)
if comma... | [
"def",
"cli",
"(",
"ctx",
",",
"env",
")",
":",
"env",
".",
"out",
"(",
"\"Welcome to the SoftLayer shell.\"",
")",
"env",
".",
"out",
"(",
"\"\"",
")",
"formatter",
"=",
"formatting",
".",
"HelpFormatter",
"(",
")",
"commands",
"=",
"[",
"]",
"shell_com... | 30.230769 | 0.001233 |
def get_headers(self, container):
"""
Return the headers for the specified container.
"""
uri = "/%s" % utils.get_name(container)
resp, resp_body = self.api.method_head(uri)
return resp.headers | [
"def",
"get_headers",
"(",
"self",
",",
"container",
")",
":",
"uri",
"=",
"\"/%s\"",
"%",
"utils",
".",
"get_name",
"(",
"container",
")",
"resp",
",",
"resp_body",
"=",
"self",
".",
"api",
".",
"method_head",
"(",
"uri",
")",
"return",
"resp",
".",
... | 33.571429 | 0.008299 |
def junos_cli(command, format=None, dev_timeout=None, dest=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Execute a CLI command and return the output in the specified format.
command
The command to execute on the Junos CLI.
format: ``text``
Format in which to get the CLI output (... | [
"def",
"junos_cli",
"(",
"command",
",",
"format",
"=",
"None",
",",
"dev_timeout",
"=",
"None",
",",
"dest",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"prep",
"=",
"_junos_prep_fun",
"(",
"napalm_device",
")",
"# pylint: disable=undefined-variable",
"... | 31.5 | 0.001812 |
def encrypt(self, document_id, content, account):
"""
Encrypt string data using the DID as an secret store id,
if secret store is enabled then return the result from secret store encryption
None for no encryption performed
:param document_id: hex str id of document to use for e... | [
"def",
"encrypt",
"(",
"self",
",",
"document_id",
",",
"content",
",",
"account",
")",
":",
"return",
"self",
".",
"_secret_store",
"(",
"account",
")",
".",
"encrypt_document",
"(",
"document_id",
",",
"content",
")"
] | 43.923077 | 0.008576 |
def clean(self):
""" Validates the form. """
if not self.instance.pk:
# Only set user on post creation
if not self.user.is_anonymous:
self.instance.poster = self.user
else:
self.instance.anonymous_key = get_anonymous_user_forum_key(self... | [
"def",
"clean",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"instance",
".",
"pk",
":",
"# Only set user on post creation",
"if",
"not",
"self",
".",
"user",
".",
"is_anonymous",
":",
"self",
".",
"instance",
".",
"poster",
"=",
"self",
".",
"user",... | 38.777778 | 0.008403 |
def sample_uniform(domain, rng):
"""Sample a value uniformly from a domain.
Args:
domain: An `IntInterval`, `RealInterval`, or `Discrete` domain.
rng: A `random.Random` object; defaults to the `random` module.
Raises:
TypeError: If `domain` is not a known kind of domain.
IndexError: If the domai... | [
"def",
"sample_uniform",
"(",
"domain",
",",
"rng",
")",
":",
"if",
"isinstance",
"(",
"domain",
",",
"hp",
".",
"IntInterval",
")",
":",
"return",
"rng",
".",
"randint",
"(",
"domain",
".",
"min_value",
",",
"domain",
".",
"max_value",
")",
"elif",
"i... | 35.052632 | 0.008772 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CommandContext for this CommandInstance
:rtype: twilio.rest.preview.wireless.command.CommandConte... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"CommandContext",
"(",
"self",
".",
"_version",
",",
"sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]",
",",
")",
"return",
... | 43.090909 | 0.010331 |
def recipients_incremental(self, start_time):
"""
Retrieve NPS Recipients incremental
:param start_time: time to retrieve events from.
"""
return self._query_zendesk(self.endpoint.recipients_incremental, 'recipients', start_time=start_time) | [
"def",
"recipients_incremental",
"(",
"self",
",",
"start_time",
")",
":",
"return",
"self",
".",
"_query_zendesk",
"(",
"self",
".",
"endpoint",
".",
"recipients_incremental",
",",
"'recipients'",
",",
"start_time",
"=",
"start_time",
")"
] | 39.285714 | 0.010676 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.