text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def RQ_sigma(self, sigma):
"""
Given a policy `sigma`, return the reward vector `R_sigma` and
the transition probability matrix `Q_sigma`.
Parameters
----------
sigma : array_like(int, ndim=1)
Policy vector, of length n.
Returns
-------
... | [
"def",
"RQ_sigma",
"(",
"self",
",",
"sigma",
")",
":",
"if",
"self",
".",
"_sa_pair",
":",
"sigma",
"=",
"np",
".",
"asarray",
"(",
"sigma",
")",
"sigma_indices",
"=",
"np",
".",
"empty",
"(",
"self",
".",
"num_states",
",",
"dtype",
"=",
"int",
"... | 33.133333 | 19.333333 |
def create_app(path=None, user_content=False, context=None, username=None,
password=None, render_offline=False, render_wide=False,
render_inline=False, api_url=None, title=None, text=None,
autorefresh=None, quiet=None, grip_class=None):
"""
Creates a Grip application... | [
"def",
"create_app",
"(",
"path",
"=",
"None",
",",
"user_content",
"=",
"False",
",",
"context",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"render_offline",
"=",
"False",
",",
"render_wide",
"=",
"False",
",",
"render... | 35.911765 | 20.852941 |
def put_conf(self, configuration, test=False):
"""Send the configuration to the satellite
HTTP request to the satellite (POST /push_configuration)
If test is True, store the configuration internally
:param configuration: The conf to send (data depend on the satellite)
:type con... | [
"def",
"put_conf",
"(",
"self",
",",
"configuration",
",",
"test",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"Sending configuration to %s, %s %s\"",
",",
"self",
".",
"name",
",",
"self",
".",
"alive",
",",
"self",
".",
"reachable",
")",
"# --... | 41.421053 | 26.842105 |
def load(filename):
"""Load a RigidTransform from a file.
The file format is:
from_frame
to_frame
translation (space separated)
rotation_row_0 (space separated)
rotation_row_1 (space separated)
rotation_row_2 (space separated)
Parameters
... | [
"def",
"load",
"(",
"filename",
")",
":",
"file_root",
",",
"file_ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"file_ext",
".",
"lower",
"(",
")",
"!=",
"TF_EXTENSION",
":",
"raise",
"ValueError",
"(",
"'Extension %s not suppo... | 29.4 | 15.9 |
def create(self, acl=None):
'''Creates a directory, optionally include Acl argument to set permissions'''
parent, name = getParentAndBase(self.path)
json = { 'name': name }
if acl is not None:
json['acl'] = acl.to_api_param()
response = self.client.postJsonHelper(Data... | [
"def",
"create",
"(",
"self",
",",
"acl",
"=",
"None",
")",
":",
"parent",
",",
"name",
"=",
"getParentAndBase",
"(",
"self",
".",
"path",
")",
"json",
"=",
"{",
"'name'",
":",
"name",
"}",
"if",
"acl",
"is",
"not",
"None",
":",
"json",
"[",
"'ac... | 53.222222 | 21 |
def ls_moduledirs(path, private=True, full=True):
""" lists all dirs which are python modules in path """
dir_list = ls_dirs(path)
module_dir_iter = filter(is_module_dir, dir_list)
if not private:
module_dir_iter = filterfalse(is_private_module, module_dir_iter)
if not full:
module_d... | [
"def",
"ls_moduledirs",
"(",
"path",
",",
"private",
"=",
"True",
",",
"full",
"=",
"True",
")",
":",
"dir_list",
"=",
"ls_dirs",
"(",
"path",
")",
"module_dir_iter",
"=",
"filter",
"(",
"is_module_dir",
",",
"dir_list",
")",
"if",
"not",
"private",
":",... | 42.777778 | 15.111111 |
def alive(opts):
'''
Return the connection status with the network device.
'''
log.debug('Checking if %s is still alive', opts.get('id', ''))
if not netmiko_device['always_alive']:
return True
if ping() and initialized():
return netmiko_device['connection'].remote_conn.transport.... | [
"def",
"alive",
"(",
"opts",
")",
":",
"log",
".",
"debug",
"(",
"'Checking if %s is still alive'",
",",
"opts",
".",
"get",
"(",
"'id'",
",",
"''",
")",
")",
"if",
"not",
"netmiko_device",
"[",
"'always_alive'",
"]",
":",
"return",
"True",
"if",
"ping",... | 33.8 | 22.4 |
def find_files(path, patterns):
"""
Returns all files from a given path that matches the pattern or list
of patterns
@type path: str
@param path: A path to traverse
@typ patterns: str|list
@param patterns: A pattern or a list of patterns to match
@rtype: list[str]:
@return: A list... | [
"def",
"find_files",
"(",
"path",
",",
"patterns",
")",
":",
"if",
"not",
"isinstance",
"(",
"patterns",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"patterns",
"=",
"[",
"patterns",
"]",
"matches",
"=",
"[",
"]",
"for",
"root",
",",
"dirnames",
... | 28.173913 | 18.869565 |
def get_yield_curve(date=None, tenor=None):
"""
获取某个国家市场指定日期的收益率曲线水平。
数据为2002年至今的中债国债收益率曲线,来源于中央国债登记结算有限责任公司。
:param date: 查询日期,默认为策略当前日期前一天
:type date: `str` | `date` | `datetime` | `pandas.Timestamp`
:param str tenor: 标准期限,'0S' - 隔夜,'1M' - 1个月,'1Y' - 1年,默认为全部期限
:return: `pandas.DataFra... | [
"def",
"get_yield_curve",
"(",
"date",
"=",
"None",
",",
"tenor",
"=",
"None",
")",
":",
"env",
"=",
"Environment",
".",
"get_instance",
"(",
")",
"trading_date",
"=",
"env",
".",
"trading_dt",
".",
"date",
"(",
")",
"yesterday",
"=",
"env",
".",
"data... | 29.44186 | 25.069767 |
def delete(self, key_id=None):
""" Delete one of the ssh keys associated with your account.
Please use with caution as there is NO confimation and NO undo.
"""
url = self.bitbucket.url('DELETE_SSH_KEY', key_id=key_id)
return self.bitbucket.dispatch('DELETE', url, auth=self.bi... | [
"def",
"delete",
"(",
"self",
",",
"key_id",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"bitbucket",
".",
"url",
"(",
"'DELETE_SSH_KEY'",
",",
"key_id",
"=",
"key_id",
")",
"return",
"self",
".",
"bitbucket",
".",
"dispatch",
"(",
"'DELETE'",
",",... | 54.666667 | 18.166667 |
def verify_token(self, token, requested_access):
"""
Check the token bearer is permitted to access the resource
:param token: Access token
:param requested_access: the access level the client has requested
:returns: boolean
"""
client = API(options.url_auth,
... | [
"def",
"verify_token",
"(",
"self",
",",
"token",
",",
"requested_access",
")",
":",
"client",
"=",
"API",
"(",
"options",
".",
"url_auth",
",",
"auth_username",
"=",
"options",
".",
"service_id",
",",
"auth_password",
"=",
"options",
".",
"client_secret",
"... | 41.851852 | 19.925926 |
def CountHuntResultsByType(self, hunt_id, cursor=None):
"""Counts number of hunts results per type."""
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query = ("SELECT type, COUNT(*) FROM flow_results "
"WHERE hunt_id = %s GROUP BY type")
cursor.execute(query, [hunt_id_int])
return dict(c... | [
"def",
"CountHuntResultsByType",
"(",
"self",
",",
"hunt_id",
",",
"cursor",
"=",
"None",
")",
":",
"hunt_id_int",
"=",
"db_utils",
".",
"HuntIDToInt",
"(",
"hunt_id",
")",
"query",
"=",
"(",
"\"SELECT type, COUNT(*) FROM flow_results \"",
"\"WHERE hunt_id = %s GROUP ... | 36.555556 | 14.555556 |
def _normalize_args(args):
'''
Return args as a list of strings
'''
if isinstance(args, six.string_types):
return shlex.split(args)
if isinstance(args, (tuple, list)):
return [six.text_type(arg) for arg in args]
else:
return [six.text_type(args)] | [
"def",
"_normalize_args",
"(",
"args",
")",
":",
"if",
"isinstance",
"(",
"args",
",",
"six",
".",
"string_types",
")",
":",
"return",
"shlex",
".",
"split",
"(",
"args",
")",
"if",
"isinstance",
"(",
"args",
",",
"(",
"tuple",
",",
"list",
")",
")",... | 25.909091 | 16.454545 |
def setTargets(self, targets):
"""
Sets the targets.
"""
if not self.verifyArguments(targets) and not self.patterned:
raise NetworkError('setTargets() requires [[...],[...],...] or [{"layerName": [...]}, ...].', targets)
self.targets = targets | [
"def",
"setTargets",
"(",
"self",
",",
"targets",
")",
":",
"if",
"not",
"self",
".",
"verifyArguments",
"(",
"targets",
")",
"and",
"not",
"self",
".",
"patterned",
":",
"raise",
"NetworkError",
"(",
"'setTargets() requires [[...],[...],...] or [{\"layerName\": [..... | 41.285714 | 19.571429 |
def packageipa(env, console):
"""
Package the built app as an ipa for distribution in iOS App Store
"""
ipa_path, app_path = _get_ipa(env)
output_dir = path.dirname(ipa_path)
if path.exists(ipa_path):
console.quiet('Removing %s' % ipa_path)
os.remove(ipa_path)
zf = zipfile.... | [
"def",
"packageipa",
"(",
"env",
",",
"console",
")",
":",
"ipa_path",
",",
"app_path",
"=",
"_get_ipa",
"(",
"env",
")",
"output_dir",
"=",
"path",
".",
"dirname",
"(",
"ipa_path",
")",
"if",
"path",
".",
"exists",
"(",
"ipa_path",
")",
":",
"console"... | 29.851852 | 19.185185 |
def _comment(self, element):
"""Extracts the character to use for comments in the input file."""
for v in _get_xml_version(element):
self.versions[v].comment = element.text | [
"def",
"_comment",
"(",
"self",
",",
"element",
")",
":",
"for",
"v",
"in",
"_get_xml_version",
"(",
"element",
")",
":",
"self",
".",
"versions",
"[",
"v",
"]",
".",
"comment",
"=",
"element",
".",
"text"
] | 49.25 | 6.5 |
def generate_thumbnail(self, ratio=None, width=None, height=None,
filter='undefined', store=current_store,
_preprocess_image=None, _postprocess_image=None):
"""Resizes the :attr:`original` (scales up or down) and
then store the resized thumbnail into... | [
"def",
"generate_thumbnail",
"(",
"self",
",",
"ratio",
"=",
"None",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"filter",
"=",
"'undefined'",
",",
"store",
"=",
"current_store",
",",
"_preprocess_image",
"=",
"None",
",",
"_postprocess_image... | 44.779221 | 15.857143 |
def hbar_stack(self, stackers, **kw):
''' Generate multiple ``HBar`` renderers for levels stacked left to right.
Args:
stackers (seq[str]) : a list of data source field names to stack
successively for ``left`` and ``right`` bar coordinates.
Additionally, the... | [
"def",
"hbar_stack",
"(",
"self",
",",
"stackers",
",",
"*",
"*",
"kw",
")",
":",
"result",
"=",
"[",
"]",
"for",
"kw",
"in",
"_double_stack",
"(",
"stackers",
",",
"\"left\"",
",",
"\"right\"",
",",
"*",
"*",
"kw",
")",
":",
"result",
".",
"append... | 39.7 | 32.45 |
def get_neutral(array_list):
"""Get list of zero-valued numpy arrays for
specified list of numpy arrays
:param array_list: list of numpy arrays
:return: list of zeros of same shape as input
"""
res = []
for x in array_list:
res.append(np.zeros_like(x))
return res | [
"def",
"get_neutral",
"(",
"array_list",
")",
":",
"res",
"=",
"[",
"]",
"for",
"x",
"in",
"array_list",
":",
"res",
".",
"append",
"(",
"np",
".",
"zeros_like",
"(",
"x",
")",
")",
"return",
"res"
] | 26.727273 | 13.090909 |
def filereplacer(filepath):
"""
This context manager yields two file pointers:
origlines:
a generator that yields lines from the original file
tmp:
a file descriptor as if you had used open(tempfile.mkstemp(), 'w')
NL:
one of "\n", "\r\n" or "\r" depending on what is encount... | [
"def",
"filereplacer",
"(",
"filepath",
")",
":",
"# create the tmp dir if it doesn't exist yet",
"tmpdir",
"=",
"join",
"(",
"ROOT",
",",
"'tmp'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"tmpdir",
")",
":",
"os",
".",
"makedirs",
"(",
"tm... | 37.789474 | 17.508772 |
def dist_abs(
self, src, tar, qval=2, pval=1, normalized=False, alphabet=None
):
"""Return the Minkowski distance (:math:`L^p`-norm) of two strings.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
... | [
"def",
"dist_abs",
"(",
"self",
",",
"src",
",",
"tar",
",",
"qval",
"=",
"2",
",",
"pval",
"=",
"1",
",",
"normalized",
"=",
"False",
",",
"alphabet",
"=",
"None",
")",
":",
"q_src",
",",
"q_tar",
"=",
"self",
".",
"_get_qgrams",
"(",
"src",
","... | 31.095238 | 18.904762 |
def put_data(self, out_path, data, mode=None, utimes=None):
"""
Implement put_file() by caling the corresponding ansible_mitogen.target
function in the target, transferring small files inline. This is
pipelined and will return immediately; failed transfers are reported as
excepti... | [
"def",
"put_data",
"(",
"self",
",",
"out_path",
",",
"data",
",",
"mode",
"=",
"None",
",",
"utimes",
"=",
"None",
")",
":",
"self",
".",
"get_chain",
"(",
")",
".",
"call_no_reply",
"(",
"ansible_mitogen",
".",
"target",
".",
"write_path",
",",
"mito... | 37.210526 | 15.210526 |
def _do_bulk_write_command(
namespace, operation, command, docs, check_keys, opts, ctx):
"""Bulk write commands entry point."""
if ctx.sock_info.max_wire_version > 5:
return _do_batched_op_msg(
namespace, operation, command, docs, check_keys, opts, ctx)
return _do_batched_write_c... | [
"def",
"_do_bulk_write_command",
"(",
"namespace",
",",
"operation",
",",
"command",
",",
"docs",
",",
"check_keys",
",",
"opts",
",",
"ctx",
")",
":",
"if",
"ctx",
".",
"sock_info",
".",
"max_wire_version",
">",
"5",
":",
"return",
"_do_batched_op_msg",
"("... | 48.5 | 13.75 |
def import_patch(self, patch_name, new_name=None):
""" Import patch into the patch queue
The patch is inserted as the next unapplied patch.
"""
if new_name:
dir_name = os.path.dirname(new_name)
name = os.path.basename(new_name)
dest_dir = self.quilt_pa... | [
"def",
"import_patch",
"(",
"self",
",",
"patch_name",
",",
"new_name",
"=",
"None",
")",
":",
"if",
"new_name",
":",
"dir_name",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"new_name",
")",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"new... | 36.352941 | 10.823529 |
def create_instance(
self,
parent,
instance_id,
instance,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a Redis instance based on the specified tier and memory size... | [
"def",
"create_instance",
"(",
"self",
",",
"parent",
",",
"instance_id",
",",
"instance",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
... | 44.933333 | 24.895238 |
def dimensions_from_subgroups(s):
"""
Given a sorted list of subgroups, return a string appropriate to provide as
a composite track's `dimensions` arg.
Parameters
----------
s : list of SubGroup objects (or anything with a `name` attribute)
"""
letters = 'XYABCDEFGHIJKLMNOPQRSTUVWZ'
... | [
"def",
"dimensions_from_subgroups",
"(",
"s",
")",
":",
"letters",
"=",
"'XYABCDEFGHIJKLMNOPQRSTUVWZ'",
"return",
"' '",
".",
"join",
"(",
"[",
"'dim{0}={1}'",
".",
"format",
"(",
"dim",
",",
"sg",
".",
"name",
")",
"for",
"dim",
",",
"sg",
"in",
"zip",
... | 35.818182 | 19.818182 |
def load_arff_files_standardized(path_training, attr_labels, pos_label=None, path_testing=None, survival=True,
standardize_numeric=True, to_numeric=True):
"""Load dataset in ARFF format.
Parameters
----------
path_training : str
Path to ARFF file containing data... | [
"def",
"load_arff_files_standardized",
"(",
"path_training",
",",
"attr_labels",
",",
"pos_label",
"=",
"None",
",",
"path_testing",
"=",
"None",
",",
"survival",
"=",
"True",
",",
"standardize_numeric",
"=",
"True",
",",
"to_numeric",
"=",
"True",
")",
":",
"... | 37.460674 | 23.842697 |
def writetb(path, kvs, java_mem_mb=256):
"""Write typedbytes sequence file to HDFS given an iterator of KeyValue pairs
:param path: HDFS path (string)
:param kvs: Iterator of (key, value)
:param java_mem_mb: Integer of java heap size in MB (default 256)
:raises: IOError: An error occurred while sav... | [
"def",
"writetb",
"(",
"path",
",",
"kvs",
",",
"java_mem_mb",
"=",
"256",
")",
":",
"read_fd",
",",
"write_fd",
"=",
"os",
".",
"pipe",
"(",
")",
"read_fp",
"=",
"os",
".",
"fdopen",
"(",
"read_fd",
",",
"'r'",
")",
"hstreaming",
"=",
"_find_hstream... | 47.043478 | 21.826087 |
def getSiblings(self, textId, subreference):
""" Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:param reference: CapitainsCtsPassage Reference
:return: GetPrevNextUrn request response from the endpoint
"""
textId = "{}:{}".format(textI... | [
"def",
"getSiblings",
"(",
"self",
",",
"textId",
",",
"subreference",
")",
":",
"textId",
"=",
"\"{}:{}\"",
".",
"format",
"(",
"textId",
",",
"subreference",
")",
"return",
"self",
".",
"getPrevNextUrn",
"(",
"urn",
"=",
"textId",
")"
] | 41.666667 | 12.555556 |
def set_mounted(unitname: str, mounted: bool, swallow_exc: bool = False):
""" Mount or unmount a unit.
Worker for the contextlibs
:param unitname: The systemd unit for the mount to affect. This probably
should be one of :py:attr:`_SYSROOT_INACTIVE_UNIT` or
:py:att... | [
"def",
"set_mounted",
"(",
"unitname",
":",
"str",
",",
"mounted",
":",
"bool",
",",
"swallow_exc",
":",
"bool",
"=",
"False",
")",
":",
"try",
":",
"if",
"mounted",
":",
"LOG",
".",
"info",
"(",
"f\"Starting {unitname}\"",
")",
"interface",
"(",
")",
... | 43.5 | 22.678571 |
def _build_color_table():
"""
Build an RGB-to-256 color conversion table
"""
FG = FOREGROUND_COLOR
BG = BACKROUND_COLOR
return [
(0x00, 0x00, 0x00, FG.BLACK, BG.BLACK),
(0x00, 0x00, 0xaa, FG.BLUE, BG.BLUE),
(0x00, 0xaa, 0x00, FG.GREEN,... | [
"def",
"_build_color_table",
"(",
")",
":",
"FG",
"=",
"FOREGROUND_COLOR",
"BG",
"=",
"BACKROUND_COLOR",
"return",
"[",
"(",
"0x00",
",",
"0x00",
",",
"0x00",
",",
"FG",
".",
"BLACK",
",",
"BG",
".",
"BLACK",
")",
",",
"(",
"0x00",
",",
"0x00",
",",
... | 45.444444 | 23.37037 |
def insert(self, meter_db):
""" Insert to :class:`~ekmmeters.MeterDB` subclass.
Please note MeterDB subclassing is only for simplest-case.
Args:
meter_db (MeterDB): Instance of subclass of MeterDB.
"""
if meter_db:
meter_db.dbInsert(self.m_req, self.m_r... | [
"def",
"insert",
"(",
"self",
",",
"meter_db",
")",
":",
"if",
"meter_db",
":",
"meter_db",
".",
"dbInsert",
"(",
"self",
".",
"m_req",
",",
"self",
".",
"m_raw_read_a",
",",
"self",
".",
"m_raw_read_b",
")",
"else",
":",
"ekm_log",
"(",
"\"Attempt to in... | 33.153846 | 23.846154 |
def main(api_endpoint, credentials,
device_model_id, device_id, lang, verbose,
input_audio_file, output_audio_file,
block_size, grpc_deadline, *args, **kwargs):
"""File based sample for the Google Assistant API.
Examples:
$ python -m audiofileinput -i <input file> -o <output fi... | [
"def",
"main",
"(",
"api_endpoint",
",",
"credentials",
",",
"device_model_id",
",",
"device_id",
",",
"lang",
",",
"verbose",
",",
"input_audio_file",
",",
"output_audio_file",
",",
"block_size",
",",
"grpc_deadline",
",",
"*",
"args",
",",
"*",
"*",
"kwargs"... | 42.73494 | 18.096386 |
def NTU_from_P_basic(P1, R1, subtype='crossflow'):
r'''Returns the number of transfer units of a basic heat exchanger type
with a specified (for side 1) thermal effectiveness `P1`, and heat capacity
ratio `R1`. The supported cases are as follows:
* Counterflow (ex. double-pipe) [analytical]
... | [
"def",
"NTU_from_P_basic",
"(",
"P1",
",",
"R1",
",",
"subtype",
"=",
"'crossflow'",
")",
":",
"NTU_min",
"=",
"1E-11",
"function",
"=",
"temperature_effectiveness_basic",
"if",
"subtype",
"==",
"'counterflow'",
":",
"return",
"-",
"log",
"(",
"(",
"P1",
"*"... | 40.018692 | 25.345794 |
def get_labels(data, centroids,K):
"""
Returns a label for each piece of data in the dataset
Parameters
------------
data: array-like, shape= (m_samples,n_samples)
K: integer
number of K clusters
centroids: array-like, shape=(K, n_samples)
returns
-----------... | [
"def",
"get_labels",
"(",
"data",
",",
"centroids",
",",
"K",
")",
":",
"distances",
"=",
"np",
".",
"sqrt",
"(",
"(",
"(",
"data",
"-",
"centroids",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
")",
"**",
"2",
")",
".",
"sum",
"(",
"axis",
"=",
... | 27.882353 | 17.294118 |
def connect(self, host=None, port=None):
"""Connects to given host address and port."""
host = self.host if host is None else host
port = self.port if port is None else port
self.socket.connect(host, port) | [
"def",
"connect",
"(",
"self",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"host",
"=",
"self",
".",
"host",
"if",
"host",
"is",
"None",
"else",
"host",
"port",
"=",
"self",
".",
"port",
"if",
"port",
"is",
"None",
"else",
"port... | 46.6 | 4.2 |
def addCutterTool(actor):
"""Create handles to cut away parts of a mesh.
.. hint:: |cutter| |cutter.py|_
"""
if isinstance(actor, vtk.vtkVolume):
return _addVolumeCutterTool(actor)
elif isinstance(actor, vtk.vtkImageData):
from vtkplotter import Volume
return _addVolumeCutte... | [
"def",
"addCutterTool",
"(",
"actor",
")",
":",
"if",
"isinstance",
"(",
"actor",
",",
"vtk",
".",
"vtkVolume",
")",
":",
"return",
"_addVolumeCutterTool",
"(",
"actor",
")",
"elif",
"isinstance",
"(",
"actor",
",",
"vtk",
".",
"vtkImageData",
")",
":",
... | 30.433735 | 16.831325 |
def list_all_braintree_gateways(cls, **kwargs):
"""List BraintreeGateways
Return a list of BraintreeGateways
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_braintree_gateways(async=T... | [
"def",
"list_all_braintree_gateways",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_list_all_braintree_gateways_with_http_... | 39.086957 | 15.521739 |
def QA_fetch_get_macroindex_list(ip=None, port=None):
"""宏观指标列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
38 10 宏观指标 HG
"""
global extension_market_list
extension_market_list = QA... | [
"def",
"QA_fetch_get_macroindex_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"global",
"extension_market_list",
"extension_market_list",
"=",
"QA_fetch_get_extensionmarket_list",
"(",
")",
"if",
"extension_market_list",
"is",
"None",
"else",
"ext... | 28.5625 | 20.5625 |
def load_config(from_key, to_key):
"""Load configuration from config.
Meant to run only once per system process as
class variable in subclasses."""
from .mappings import mappings
kbs = {}
for key, values in mappings['config'].iteritems():
parse_dict = {}
... | [
"def",
"load_config",
"(",
"from_key",
",",
"to_key",
")",
":",
"from",
".",
"mappings",
"import",
"mappings",
"kbs",
"=",
"{",
"}",
"for",
"key",
",",
"values",
"in",
"mappings",
"[",
"'config'",
"]",
".",
"iteritems",
"(",
")",
":",
"parse_dict",
"="... | 36.8 | 12.666667 |
def _ignore_path(cls, path, ignore_list=None, white_list=None):
"""Returns a whether a path should be ignored or not."""
ignore_list = ignore_list or []
white_list = white_list or []
return (cls._matches_patterns(path, ignore_list) and
not cls._matches_patterns(path, whit... | [
"def",
"_ignore_path",
"(",
"cls",
",",
"path",
",",
"ignore_list",
"=",
"None",
",",
"white_list",
"=",
"None",
")",
":",
"ignore_list",
"=",
"ignore_list",
"or",
"[",
"]",
"white_list",
"=",
"white_list",
"or",
"[",
"]",
"return",
"(",
"cls",
".",
"_... | 53.833333 | 11.166667 |
def ApproximateDistanceBetweenPoints(pa, pb):
"""Finds the distance between two points on the Earth's surface.
This is an approximate distance based on assuming that the Earth is a sphere.
The points are specified by their lattitude and longitude.
Args:
pa: the first (lat, lon) point tuple
pb: the sec... | [
"def",
"ApproximateDistanceBetweenPoints",
"(",
"pa",
",",
"pb",
")",
":",
"alat",
",",
"alon",
"=",
"pa",
"blat",
",",
"blon",
"=",
"pb",
"sa",
"=",
"transitfeed",
".",
"Stop",
"(",
"lat",
"=",
"alat",
",",
"lng",
"=",
"alon",
")",
"sb",
"=",
"tra... | 31.722222 | 17.888889 |
def is_url(name):
"""Returns true if the name looks like a URL"""
if ':' not in name:
return False
scheme = name.split(':', 1)[0].lower()
return scheme in ['http', 'https', 'file', 'ftp'] + vcs.all_schemes | [
"def",
"is_url",
"(",
"name",
")",
":",
"if",
"':'",
"not",
"in",
"name",
":",
"return",
"False",
"scheme",
"=",
"name",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"return",
"scheme",
"in",
"[",
"'http'",
",... | 37.333333 | 15.5 |
def plural(self, text, count=None):
"""
Return the plural of text.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved.
"""
pre, wor... | [
"def",
"plural",
"(",
"self",
",",
"text",
",",
"count",
"=",
"None",
")",
":",
"pre",
",",
"word",
",",
"post",
"=",
"self",
".",
"partition_word",
"(",
"text",
")",
"if",
"not",
"word",
":",
"return",
"text",
"plural",
"=",
"self",
".",
"postproc... | 30.333333 | 15.190476 |
def call_jobs_parallel(
self,
jobs,
expansions=None,
raise_job_errors=True,
raise_action_errors=True,
catch_transport_errors=False,
timeout=None,
**kwargs
):
"""
Build and send multiple job requests to one or more services, each with on... | [
"def",
"call_jobs_parallel",
"(",
"self",
",",
"jobs",
",",
"expansions",
"=",
"None",
",",
"raise_job_errors",
"=",
"True",
",",
"raise_action_errors",
"=",
"True",
",",
"catch_transport_errors",
"=",
"False",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"kw... | 58.637681 | 35.072464 |
def minify_js(input_files, output_file):
"""
Minifies the input javascript files to the output file.
Output file may be same as input to minify in place.
In debug mode this function just concatenates the files
without minifying.
"""
from .modules import minify, utils
if not isinstance... | [
"def",
"minify_js",
"(",
"input_files",
",",
"output_file",
")",
":",
"from",
".",
"modules",
"import",
"minify",
",",
"utils",
"if",
"not",
"isinstance",
"(",
"input_files",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"RuntimeError",
"(",
"'... | 28.285714 | 18.380952 |
def fork(self):
"""Fork this gist.
:returns: :class:`Gist <Gist>` if successful, ``None`` otherwise
"""
url = self._build_url('forks', base_url=self._api)
json = self._json(self._post(url), 201)
return Gist(json, self) if json else None | [
"def",
"fork",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'forks'",
",",
"base_url",
"=",
"self",
".",
"_api",
")",
"json",
"=",
"self",
".",
"_json",
"(",
"self",
".",
"_post",
"(",
"url",
")",
",",
"201",
")",
"return",... | 30.888889 | 19 |
def size(self):
"""Returns:
int : The total number of bytes that will be returned by the iterator.
"""
if hasattr(self._stream, 'len'):
return len(self._stream)
elif hasattr(self._stream, 'fileno'):
return os.fstat(self._stream.fileno()).st_size
el... | [
"def",
"size",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"_stream",
",",
"'len'",
")",
":",
"return",
"len",
"(",
"self",
".",
"_stream",
")",
"elif",
"hasattr",
"(",
"self",
".",
"_stream",
",",
"'fileno'",
")",
":",
"return",
"os"... | 36.076923 | 11.461538 |
def remove_tag_and_push_registries(tag_and_push_registries, version):
"""
Remove matching entries from tag_and_push_registries (in-place)
:param tag_and_push_registries: dict, uri -> dict
:param version: str, 'version' to match against
"""
registries = [uri
... | [
"def",
"remove_tag_and_push_registries",
"(",
"tag_and_push_registries",
",",
"version",
")",
":",
"registries",
"=",
"[",
"uri",
"for",
"uri",
",",
"regdict",
"in",
"tag_and_push_registries",
".",
"items",
"(",
")",
"if",
"regdict",
"[",
"'version'",
"]",
"==",... | 44.692308 | 18.384615 |
def word_to_id(self, word):
"""Returns the integer id of a word string."""
if word in self._vocab:
return self._vocab[word]
else:
return self._unk_id | [
"def",
"word_to_id",
"(",
"self",
",",
"word",
")",
":",
"if",
"word",
"in",
"self",
".",
"_vocab",
":",
"return",
"self",
".",
"_vocab",
"[",
"word",
"]",
"else",
":",
"return",
"self",
".",
"_unk_id"
] | 32 | 10.333333 |
def overlapping(self, start=None, end=None):
"""
:return: occurrences overlapping the given start and end datetimes,
inclusive.
Special logic is applied for all-day occurrences, for which the start
and end times are zeroed to find all occurrences that occur on a DATE
as o... | [
"def",
"overlapping",
"(",
"self",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"qs",
"=",
"self",
"if",
"start",
":",
"dt_start",
"=",
"coerce_dt_awareness",
"(",
"start",
")",
"qs",
"=",
"qs",
".",
"filter",
"(",
"# Exclusive for dat... | 36.24 | 20.72 |
def get_force(self, component_info=None, data=None, component_position=None):
"""Get force data."""
components = []
append_components = components.append
for _ in range(component_info.plate_count):
component_position, plate = QRTPacket._get_exact(
RTForcePlate... | [
"def",
"get_force",
"(",
"self",
",",
"component_info",
"=",
"None",
",",
"data",
"=",
"None",
",",
"component_position",
"=",
"None",
")",
":",
"components",
"=",
"[",
"]",
"append_components",
"=",
"components",
".",
"append",
"for",
"_",
"in",
"range",
... | 42.25 | 14.8125 |
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
v = text
if self.pyclass is not None:
return self.pyclass(v)
m = _magicnums.get(v)
if m: return m
try:
return float(v)
except:
rai... | [
"def",
"text_to_data",
"(",
"self",
",",
"text",
",",
"elt",
",",
"ps",
")",
":",
"v",
"=",
"text",
"if",
"self",
".",
"pyclass",
"is",
"not",
"None",
":",
"return",
"self",
".",
"pyclass",
"(",
"v",
")",
"m",
"=",
"_magicnums",
".",
"get",
"(",
... | 26.8 | 19.066667 |
def _condense(self, data):
'''
Condense by or-ing all of the sets.
'''
if data:
return reduce(operator.ior, data.values())
return set() | [
"def",
"_condense",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
":",
"return",
"reduce",
"(",
"operator",
".",
"ior",
",",
"data",
".",
"values",
"(",
")",
")",
"return",
"set",
"(",
")"
] | 22.142857 | 20.142857 |
async def set_mode(self, target, *modes):
"""
Set mode on target.
Users should only rely on the mode actually being changed when receiving an on_{channel,user}_mode_change callback.
"""
if self.is_channel(target) and not self.in_channel(target):
raise NotInChannel(tar... | [
"async",
"def",
"set_mode",
"(",
"self",
",",
"target",
",",
"*",
"modes",
")",
":",
"if",
"self",
".",
"is_channel",
"(",
"target",
")",
"and",
"not",
"self",
".",
"in_channel",
"(",
"target",
")",
":",
"raise",
"NotInChannel",
"(",
"target",
")",
"... | 40.777778 | 19.444444 |
def _init_actions(self, create_standard_actions):
""" Init context menu action """
menu_advanced = QtWidgets.QMenu(_('Advanced'))
self.add_menu(menu_advanced)
self._sub_menus = {
'Advanced': menu_advanced
}
if create_standard_actions:
# Undo
... | [
"def",
"_init_actions",
"(",
"self",
",",
"create_standard_actions",
")",
":",
"menu_advanced",
"=",
"QtWidgets",
".",
"QMenu",
"(",
"_",
"(",
"'Advanced'",
")",
")",
"self",
".",
"add_menu",
"(",
"menu_advanced",
")",
"self",
".",
"_sub_menus",
"=",
"{",
... | 43.537736 | 11.424528 |
def post_attachment(session, thread_id, attachments):
"""
Add a message to a thread
"""
files = []
filenames = []
for attachment in attachments:
files.append(attachment['file'])
filenames.append(attachment['filename'])
message_data = {
'attachments[]': filenames,
... | [
"def",
"post_attachment",
"(",
"session",
",",
"thread_id",
",",
"attachments",
")",
":",
"files",
"=",
"[",
"]",
"filenames",
"=",
"[",
"]",
"for",
"attachment",
"in",
"attachments",
":",
"files",
".",
"append",
"(",
"attachment",
"[",
"'file'",
"]",
")... | 36.75 | 17 |
def geom_length(geom):
"""
Calculates the length of coordinates in a shapely geometry.
"""
if geom.geom_type == 'Point':
return 1
if hasattr(geom, 'exterior'):
geom = geom.exterior
if not geom.geom_type.startswith('Multi') and hasattr(geom, 'array_interface_base'):
return... | [
"def",
"geom_length",
"(",
"geom",
")",
":",
"if",
"geom",
".",
"geom_type",
"==",
"'Point'",
":",
"return",
"1",
"if",
"hasattr",
"(",
"geom",
",",
"'exterior'",
")",
":",
"geom",
"=",
"geom",
".",
"exterior",
"if",
"not",
"geom",
".",
"geom_type",
... | 30.6 | 16.6 |
def cmd_fernet_genkey(writecfg):
"""Generate a new Fernet Key, optionally write it to ~/.habu.json
Example:
\b
$ habu.fernet.genkey
xgvWCIvjwe9Uq7NBvwO796iI4dsGD623QOT9GWqnuhg=
"""
key = Fernet.generate_key()
print(key.decode())
if writecfg:
habucfg = loadcfg(environment=... | [
"def",
"cmd_fernet_genkey",
"(",
"writecfg",
")",
":",
"key",
"=",
"Fernet",
".",
"generate_key",
"(",
")",
"print",
"(",
"key",
".",
"decode",
"(",
")",
")",
"if",
"writecfg",
":",
"habucfg",
"=",
"loadcfg",
"(",
"environment",
"=",
"False",
")",
"hab... | 26.888889 | 20 |
def hook(self, name):
""" Return a decorator that attaches a callback to a hook. See
:meth:`add_hook` for details."""
def decorator(func):
self.add_hook(name, func)
return func
return decorator | [
"def",
"hook",
"(",
"self",
",",
"name",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"self",
".",
"add_hook",
"(",
"name",
",",
"func",
")",
"return",
"func",
"return",
"decorator"
] | 35.285714 | 9.571429 |
def main(argv=None):
''' Execute the "intake" command line program.
'''
from intake.cli.bootstrap import main as _main
return _main('Intake Catalog CLI', subcommands.all, argv or sys.argv) | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"from",
"intake",
".",
"cli",
".",
"bootstrap",
"import",
"main",
"as",
"_main",
"return",
"_main",
"(",
"'Intake Catalog CLI'",
",",
"subcommands",
".",
"all",
",",
"argv",
"or",
"sys",
".",
"argv",
"... | 28.571429 | 26.571429 |
def get_cutout(self, resource, resolution, x_range, y_range, z_range, time_range=None, id_list=[], access_mode=CacheMode.no_cache, **kwargs):
"""Get a cutout from the volume service.
Args:
resource (intern.resource.boss.resource.ChannelResource): Channel or layer resource.
resol... | [
"def",
"get_cutout",
"(",
"self",
",",
"resource",
",",
"resolution",
",",
"x_range",
",",
"y_range",
",",
"z_range",
",",
"time_range",
"=",
"None",
",",
"id_list",
"=",
"[",
"]",
",",
"access_mode",
"=",
"CacheMode",
".",
"no_cache",
",",
"*",
"*",
"... | 57.925926 | 36.259259 |
def flat_map(self, flatmap_function):
"""Return a new Streamlet by applying map_function to each element of this Streamlet
and flattening the result
"""
from heronpy.streamlet.impl.flatmapbolt import FlatMapStreamlet
fm_streamlet = FlatMapStreamlet(flatmap_function, self)
self._add_child(fm_s... | [
"def",
"flat_map",
"(",
"self",
",",
"flatmap_function",
")",
":",
"from",
"heronpy",
".",
"streamlet",
".",
"impl",
".",
"flatmapbolt",
"import",
"FlatMapStreamlet",
"fm_streamlet",
"=",
"FlatMapStreamlet",
"(",
"flatmap_function",
",",
"self",
")",
"self",
"."... | 43.25 | 10.125 |
def reset(self):
""" Resets the player and discards loaded data. """
self.clip = None
self.loaded_file = None
self.fps = None
self.duration = None
self.status = UNINITIALIZED
self.clock.reset()
self.loop_count = 0 | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"clip",
"=",
"None",
"self",
".",
"loaded_file",
"=",
"None",
"self",
".",
"fps",
"=",
"None",
"self",
".",
"duration",
"=",
"None",
"self",
".",
"status",
"=",
"UNINITIALIZED",
"self",
".",
"clock"... | 18.416667 | 22.666667 |
def get(siren):
'''
renvoie un tuple (str, str, str, rs)
un siren
une categorie d'entreprise
une annee
une raison sociale
param: un siren (str)
:Example:
>>> get('444465736')
(u'2013', u'444465736', u'entreprise de taille inte... | [
"def",
"get",
"(",
"siren",
")",
":",
"# format siren",
"siren",
"=",
"addinterval",
"(",
"siren",
",",
"' '",
",",
"3",
")",
"# send request",
"res",
"=",
"requests",
".",
"get",
"(",
"api",
".",
"format",
"(",
"siren",
")",
")",
"try",
":",
"# if r... | 25 | 19.085106 |
def match_modules(allowed_modules):
"""Creates a matcher that matches a list/set/tuple of allowed modules."""
cleaned_allowed_modules = [
utils.mod_to_mod_name(tmp_mod)
for tmp_mod in allowed_modules
]
cleaned_split_allowed_modules = [
tmp_mod.split(".")
for tmp_mod in cl... | [
"def",
"match_modules",
"(",
"allowed_modules",
")",
":",
"cleaned_allowed_modules",
"=",
"[",
"utils",
".",
"mod_to_mod_name",
"(",
"tmp_mod",
")",
"for",
"tmp_mod",
"in",
"allowed_modules",
"]",
"cleaned_split_allowed_modules",
"=",
"[",
"tmp_mod",
".",
"split",
... | 38.3 | 17.6 |
def _join_info_fields(self):
"""Updates info attribute from info dict."""
if self.info_dict:
info_fields = []
if len(self.info_dict) > 1:
self.info_dict.pop(".", None)
for field, value in self.info_dict.items():
if field == value:
... | [
"def",
"_join_info_fields",
"(",
"self",
")",
":",
"if",
"self",
".",
"info_dict",
":",
"info_fields",
"=",
"[",
"]",
"if",
"len",
"(",
"self",
".",
"info_dict",
")",
">",
"1",
":",
"self",
".",
"info_dict",
".",
"pop",
"(",
"\".\"",
",",
"None",
"... | 37.285714 | 11.285714 |
def exit_config_mode(self, exit_config="", pattern=""):
"""Exit from configuration mode.
:param exit_config: Command to exit configuration mode
:type exit_config: str
:param pattern: Pattern to terminate reading of channel
:type pattern: str
"""
output = ""
... | [
"def",
"exit_config_mode",
"(",
"self",
",",
"exit_config",
"=",
"\"\"",
",",
"pattern",
"=",
"\"\"",
")",
":",
"output",
"=",
"\"\"",
"if",
"self",
".",
"check_config_mode",
"(",
")",
":",
"self",
".",
"write_channel",
"(",
"self",
".",
"normalize_cmd",
... | 38.352941 | 17.470588 |
def get_appliance(self, appliance_id):
"""Get the information for a specified appliance
Args:
appliance_id (string): identifiying string of appliance
Returns:
list: dictionary object containing information about the specified appliance
"""
url = "https://api.neur.io/v1/appliances/%s"%(... | [
"def",
"get_appliance",
"(",
"self",
",",
"appliance_id",
")",
":",
"url",
"=",
"\"https://api.neur.io/v1/appliances/%s\"",
"%",
"(",
"appliance_id",
")",
"headers",
"=",
"self",
".",
"__gen_headers",
"(",
")",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"ap... | 29.1875 | 21.5 |
def smooth(x0, rho, gamma, axis=0):
"""
Proximal operator for a smoothing function enforced via the discrete laplacian operator
Notes
-----
Currently only works with matrices (2-D arrays) as input
Parameters
----------
x0 : array_like
The starting or initial point used in the p... | [
"def",
"smooth",
"(",
"x0",
",",
"rho",
",",
"gamma",
",",
"axis",
"=",
"0",
")",
":",
"# Apply Laplacian smoothing",
"n",
"=",
"x0",
".",
"shape",
"[",
"axis",
"]",
"lap_op",
"=",
"spdiags",
"(",
"[",
"(",
"2",
"+",
"rho",
"/",
"gamma",
")",
"*"... | 29.580645 | 30.096774 |
def splitext2(filepath):
"""Split filepath into root, filename, ext
Args:
filepath (str, path): file path
Returns:
str
"""
root, filename = os.path.split(safepath(filepath))
filename, ext = os.path.splitext(safepath(filename))
return root, filename, ext | [
"def",
"splitext2",
"(",
"filepath",
")",
":",
"root",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"safepath",
"(",
"filepath",
")",
")",
"filename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"safepath",
"(",
"filename... | 24 | 18.75 |
def eval_advs(self, x, y, preds_adv, X_test, Y_test, att_type):
"""
Evaluate the accuracy of the model on adversarial examples
:param x: symbolic input to model.
:param y: symbolic variable for the label.
:param preds_adv: symbolic variable for the prediction on an
adversarial... | [
"def",
"eval_advs",
"(",
"self",
",",
"x",
",",
"y",
",",
"preds_adv",
",",
"X_test",
",",
"Y_test",
",",
"att_type",
")",
":",
"end",
"=",
"(",
"len",
"(",
"X_test",
")",
"//",
"self",
".",
"batch_size",
")",
"*",
"self",
".",
"batch_size",
"if",
... | 38 | 16.181818 |
def with_claims(self, issuer=None, subject=None, audience=None,
additional_claims=None):
"""Returns a copy of these credentials with modified claims.
Args:
issuer (str): The `iss` claim. If unspecified the current issuer
claim will be used.
su... | [
"def",
"with_claims",
"(",
"self",
",",
"issuer",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"audience",
"=",
"None",
",",
"additional_claims",
"=",
"None",
")",
":",
"new_additional_claims",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_additional... | 46.259259 | 22 |
def fetch_all_data(self, limit=50000):
"""
Fetch data for all entities.
"""
# Query text
query = text(
"""
SELECT domain, entity_id, state, last_changed
FROM states
WHERE
state NOT IN ('unknown', 'unavailable')
... | [
"def",
"fetch_all_data",
"(",
"self",
",",
"limit",
"=",
"50000",
")",
":",
"# Query text",
"query",
"=",
"text",
"(",
"\"\"\"\n SELECT domain, entity_id, state, last_changed\n FROM states\n WHERE\n state NOT IN ('unknown', 'unavailable')... | 31.72 | 14.76 |
def get_view_response(self, request, page, view_func, view_args, view_kwargs):
"""
Render the custom view that was exposed by the extra plugin URL patterns.
This gives the ability to add extra middleware logic.
"""
return view_func(request, page, *view_args, **view_kwargs) | [
"def",
"get_view_response",
"(",
"self",
",",
"request",
",",
"page",
",",
"view_func",
",",
"view_args",
",",
"view_kwargs",
")",
":",
"return",
"view_func",
"(",
"request",
",",
"page",
",",
"*",
"view_args",
",",
"*",
"*",
"view_kwargs",
")"
] | 51.333333 | 21 |
def _finish(self, g):
"""Called on completion of an upload greenlet.
Takes care to forward Exceptions or, if there is no error, the
finished TarPartition value across a channel.
"""
assert g.ready()
if g.successful():
finished_tpart = g.get()
sel... | [
"def",
"_finish",
"(",
"self",
",",
"g",
")",
":",
"assert",
"g",
".",
"ready",
"(",
")",
"if",
"g",
".",
"successful",
"(",
")",
":",
"finished_tpart",
"=",
"g",
".",
"get",
"(",
")",
"self",
".",
"wait_change",
".",
"put",
"(",
"finished_tpart",
... | 30.846154 | 16.615385 |
def settle_to_markers(self, frame_no=0, max_distance=0.05, max_iters=300,
states=None):
'''Settle the skeleton to our marker data at a specific frame.
Parameters
----------
frame_no : int, optional
Settle the skeleton to marker data at this frame. D... | [
"def",
"settle_to_markers",
"(",
"self",
",",
"frame_no",
"=",
"0",
",",
"max_distance",
"=",
"0.05",
",",
"max_iters",
"=",
"300",
",",
"states",
"=",
"None",
")",
":",
"if",
"states",
"is",
"not",
"None",
":",
"self",
".",
"skeleton",
".",
"set_body_... | 46.828571 | 20.085714 |
def predict(self, X):
"""Get the index of the grid cell containing each sample in X
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data
Returns
-------
y : array, shape = [n_samples,]
Index of the grid cell cont... | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"if",
"np",
".",
"any",
"(",
"X",
"<",
"self",
".",
"grid",
"[",
":",
",",
"0",
"]",
")",
"or",
"np",
".",
"any",
"(",
"X",
">",
"self",
".",
"grid",
"[",
":",
",",
"-",
"1",
"]",
")",
... | 34.391304 | 21.608696 |
def get_contents_sig(self):
"""
A helper method for get_cachedir_bsig.
It computes and returns the signature for this
node's contents.
"""
try:
return self.contentsig
except AttributeError:
pass
executor = self.get_executor()
... | [
"def",
"get_contents_sig",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"contentsig",
"except",
"AttributeError",
":",
"pass",
"executor",
"=",
"self",
".",
"get_executor",
"(",
")",
"result",
"=",
"self",
".",
"contentsig",
"=",
"SCons",
".",... | 23.941176 | 20.058824 |
def setCurrentLayer(self, layer):
"""
Sets the current layer for this scene to the inputed layer.
:param layer | <XNodeLayer> || None
"""
if self._currentLayer == layer:
return False
old = self._currentLayer
self._currentLayer = ... | [
"def",
"setCurrentLayer",
"(",
"self",
",",
"layer",
")",
":",
"if",
"self",
".",
"_currentLayer",
"==",
"layer",
":",
"return",
"False",
"old",
"=",
"self",
".",
"_currentLayer",
"self",
".",
"_currentLayer",
"=",
"layer",
"if",
"old",
"is",
"not",
"Non... | 24.857143 | 15.714286 |
def html_authors(self):
"""HTML5-formatted authors (`list` of `str`)."""
return self.format_authors(format='html5', deparagraph=True,
mathjax=False, smart=True) | [
"def",
"html_authors",
"(",
"self",
")",
":",
"return",
"self",
".",
"format_authors",
"(",
"format",
"=",
"'html5'",
",",
"deparagraph",
"=",
"True",
",",
"mathjax",
"=",
"False",
",",
"smart",
"=",
"True",
")"
] | 52 | 16.5 |
def fits_recarray_to_data_frame (recarray, drop_nonscalar_ok=True):
"""Convert a FITS data table, stored as a Numpy record array, into a Pandas
DataFrame object. By default, non-scalar columns are discarded, but if
*drop_nonscalar_ok* is False then a :exc:`ValueError` is raised. Column
names are lower-c... | [
"def",
"fits_recarray_to_data_frame",
"(",
"recarray",
",",
"drop_nonscalar_ok",
"=",
"True",
")",
":",
"from",
"pandas",
"import",
"DataFrame",
"def",
"normalize",
"(",
")",
":",
"for",
"column",
"in",
"recarray",
".",
"columns",
":",
"n",
"=",
"column",
".... | 38.184211 | 21.5 |
def gait(self, x):
"""
Extract gait features from estimated heel strikes and accelerometer data.
:param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc.
:type x: pandas.Series
:return number_of_steps: Estimated number of step... | [
"def",
"gait",
"(",
"self",
",",
"x",
")",
":",
"data",
"=",
"x",
"strikes",
",",
"_",
"=",
"self",
".",
"heel_strikes",
"(",
"data",
")",
"step_durations",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"np",
".",
"size",
"(",
"strik... | 45.541284 | 24.761468 |
def _get_inter_event_tau(self, C, mag, num_sites):
"""
Returns the inter-event standard deviation (tau), which is dependent
on magnitude
"""
base_vals = np.zeros(num_sites)
if mag <= 4.5:
return base_vals + C["t1"]
elif mag >= 5.5:
return b... | [
"def",
"_get_inter_event_tau",
"(",
"self",
",",
"C",
",",
"mag",
",",
"num_sites",
")",
":",
"base_vals",
"=",
"np",
".",
"zeros",
"(",
"num_sites",
")",
"if",
"mag",
"<=",
"4.5",
":",
"return",
"base_vals",
"+",
"C",
"[",
"\"t1\"",
"]",
"elif",
"ma... | 34.666667 | 13.833333 |
def _FormatServiceText(self, service):
"""Produces a human readable multi-line string representing the service.
Args:
service (WindowsService): service to format.
Returns:
str: human readable representation of a Windows Service.
"""
string_segments = [
service.name,
'\... | [
"def",
"_FormatServiceText",
"(",
"self",
",",
"service",
")",
":",
"string_segments",
"=",
"[",
"service",
".",
"name",
",",
"'\\tImage Path = {0:s}'",
".",
"format",
"(",
"service",
".",
"image_path",
")",
",",
"'\\tService Type = {0:s}'",
".",
"format",
"... | 37.952381 | 21.142857 |
def create_deletion_handler(preference):
"""
Will generate a dynamic handler to purge related preference
on instance deletion
"""
def delete_related_preferences(sender, instance, *args, **kwargs):
queryset = preference.registry.preference_model.objects\
... | [
"def",
"create_deletion_handler",
"(",
"preference",
")",
":",
"def",
"delete_related_preferences",
"(",
"sender",
",",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"queryset",
"=",
"preference",
".",
"registry",
".",
"preference_model",
".... | 46 | 14.615385 |
def find_previous_sibling(self, *args, **kwargs):
"""
Like :meth:`find`, but searches through :attr:`previous_siblings`
"""
op = operator.methodcaller('find_previous_sibling', *args, **kwargs)
return self._wrap_node(op) | [
"def",
"find_previous_sibling",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"op",
"=",
"operator",
".",
"methodcaller",
"(",
"'find_previous_sibling'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_wrap_no... | 42.333333 | 14 |
def bind_parameters(self, value_dict):
"""Assign parameters to values yielding a new circuit.
Args:
value_dict (dict): {parameter: value, ...}
Raises:
QiskitError: If value_dict contains parameters not present in the circuit
Returns:
QuantumCircuit:... | [
"def",
"bind_parameters",
"(",
"self",
",",
"value_dict",
")",
":",
"new_circuit",
"=",
"self",
".",
"copy",
"(",
")",
"if",
"value_dict",
".",
"keys",
"(",
")",
">",
"self",
".",
"parameters",
":",
"raise",
"QiskitError",
"(",
"'Cannot bind parameters ({}) ... | 36.333333 | 22.125 |
def enforce_periodic_boundary_conditions( self ):
"""
Ensure that all lattice sites are within the central periodic image of the simulation cell.
Sites that are outside the central simulation cell are mapped back into this cell.
Args:
None
Returns:
... | [
"def",
"enforce_periodic_boundary_conditions",
"(",
"self",
")",
":",
"for",
"s",
"in",
"self",
".",
"sites",
":",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"if",
"s",
".",
"r",
"[",
"i",
"]",
"<",
"0.0",
":",
"s",
".",
"r",
"[",
"i",
"]",... | 33.411765 | 20.470588 |
def to_yaml(cls, dumper, data):
"""
Convert a Python object to a representation node.
"""
return dumper.represent_yaml_object(cls.yaml_tag, data, cls,
flow_style=cls.yaml_flow_style) | [
"def",
"to_yaml",
"(",
"cls",
",",
"dumper",
",",
"data",
")",
":",
"return",
"dumper",
".",
"represent_yaml_object",
"(",
"cls",
".",
"yaml_tag",
",",
"data",
",",
"cls",
",",
"flow_style",
"=",
"cls",
".",
"yaml_flow_style",
")"
] | 37.5 | 10.166667 |
def _rename_with_content_disposition(self, response: HTTPResponse):
'''Rename using the Content-Disposition header.'''
if not self._filename:
return
if response.request.url_info.scheme not in ('http', 'https'):
return
header_value = response.fields.get('Content-... | [
"def",
"_rename_with_content_disposition",
"(",
"self",
",",
"response",
":",
"HTTPResponse",
")",
":",
"if",
"not",
"self",
".",
"_filename",
":",
"return",
"if",
"response",
".",
"request",
".",
"url_info",
".",
"scheme",
"not",
"in",
"(",
"'http'",
",",
... | 33.421053 | 25.842105 |
def triangle_area(e1, e2, e3):
"""
Get the area of triangle formed by three vectors.
Parameters are three three-dimensional numpy arrays representing
vectors of triangle's edges in Cartesian space.
:returns:
Float number, the area of the triangle in squared units of coordinates,
or... | [
"def",
"triangle_area",
"(",
"e1",
",",
"e2",
",",
"e3",
")",
":",
"# calculating edges length",
"e1_length",
"=",
"numpy",
".",
"sqrt",
"(",
"numpy",
".",
"sum",
"(",
"e1",
"*",
"e1",
",",
"axis",
"=",
"-",
"1",
")",
")",
"e2_length",
"=",
"numpy",
... | 39.666667 | 20.428571 |
def safe_repr(obj, clip=None):
"""
Convert object to string representation, yielding the same result a `repr`
but catches all exceptions and returns 'N/A' instead of raising the
exception. Strings may be truncated by providing `clip`.
>>> safe_repr(42)
'42'
>>> safe_repr('Clipped text', cli... | [
"def",
"safe_repr",
"(",
"obj",
",",
"clip",
"=",
"None",
")",
":",
"try",
":",
"s",
"=",
"repr",
"(",
"obj",
")",
"if",
"not",
"clip",
"or",
"len",
"(",
"s",
")",
"<=",
"clip",
":",
"return",
"s",
"else",
":",
"return",
"s",
"[",
":",
"clip"... | 26.619048 | 18.904762 |
def check_public_ok(func):
"""
Call after login decorator.
"""
def wrapper(request, *args, **kwargs):
default_to_open = getattr(settings, 'DEFAULT_TO_OPEN_READ', False)
database_name = kwargs.get('database_name', "")
collection_name = kwargs.get('collection_name', "")
... | [
"def",
"check_public_ok",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"default_to_open",
"=",
"getattr",
"(",
"settings",
",",
"'DEFAULT_TO_OPEN_READ'",
",",
"False",
")",
"database_name",
"... | 41.657895 | 19.552632 |
def kill_design_run(self, data_view_id, run_uuid):
"""
Kills an in progress experimental design run
:param data_view_id: The ID number of the data view to which the
run belongs, as a string
:type data_view_id: str
:param run_uuid: The UUID of the design run to kill
... | [
"def",
"kill_design_run",
"(",
"self",
",",
"data_view_id",
",",
"run_uuid",
")",
":",
"url",
"=",
"routes",
".",
"kill_data_view_design_run",
"(",
"data_view_id",
",",
"run_uuid",
")",
"response",
"=",
"self",
".",
"_delete",
"(",
"url",
")",
".",
"json",
... | 33.9375 | 16.0625 |
def parse(cls, line, ns={}):
"""
Parse compositor specifications, returning a list Compositors
"""
definitions = []
parses = [p for p in cls.compositor_spec.scanString(line)]
if len(parses) != 1:
raise SyntaxError("Invalid specification syntax.")
else... | [
"def",
"parse",
"(",
"cls",
",",
"line",
",",
"ns",
"=",
"{",
"}",
")",
":",
"definitions",
"=",
"[",
"]",
"parses",
"=",
"[",
"p",
"for",
"p",
"in",
"cls",
".",
"compositor_spec",
".",
"scanString",
"(",
"line",
")",
"]",
"if",
"len",
"(",
"pa... | 41.352941 | 22.294118 |
def _printDescription(self, hrlinetop=True):
"""generic method to print out a description"""
if hrlinetop:
self._print("----------------")
NOTFOUND = "[not found]"
if self.currentEntity:
obj = self.currentEntity['object']
label = obj.bestLabel() or NOT... | [
"def",
"_printDescription",
"(",
"self",
",",
"hrlinetop",
"=",
"True",
")",
":",
"if",
"hrlinetop",
":",
"self",
".",
"_print",
"(",
"\"----------------\"",
")",
"NOTFOUND",
"=",
"\"[not found]\"",
"if",
"self",
".",
"currentEntity",
":",
"obj",
"=",
"self"... | 54.742857 | 20.714286 |
def get_csv_reader(csvfile, dialect=csv.excel, encoding="utf-8", **kwds):
"""Returns csv reader."""
try:
# pylint: disable=pointless-statement
unicode
return UnicodeReader(csvfile, dialect=dialect, encoding=encoding, **kwds)
except NameError:
return csv.reader(csvfile, dialec... | [
"def",
"get_csv_reader",
"(",
"csvfile",
",",
"dialect",
"=",
"csv",
".",
"excel",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"*",
"*",
"kwds",
")",
":",
"try",
":",
"# pylint: disable=pointless-statement",
"unicode",
"return",
"UnicodeReader",
"(",
"csvfile",
",... | 41.375 | 21.75 |
def fprocess(infilep,outfilep):
"""
Scans an input file for LA equations between double square brackets,
e.g. [[ M3_mymatrix = M3_anothermatrix^-1 ]], and replaces the expression
with a comment containing the equation followed by nested function calls
that implement the equation as C code. A trailin... | [
"def",
"fprocess",
"(",
"infilep",
",",
"outfilep",
")",
":",
"pattern",
"=",
"r'\\[\\[\\s*(.*?)\\s*\\]\\]'",
"eqn",
"=",
"re",
".",
"compile",
"(",
"pattern",
",",
"re",
".",
"DOTALL",
")",
"s",
"=",
"infilep",
".",
"read",
"(",
")",
"def",
"parser",
... | 40.73913 | 22.130435 |
def set_value(self, comp_str):
"""
Set the value of component.
:param string comp_str: value of component
:returns: None
:exception: ValueError - incorrect value of component
"""
self._is_negated = False
self._encoded_value = comp_str
self._stand... | [
"def",
"set_value",
"(",
"self",
",",
"comp_str",
")",
":",
"self",
".",
"_is_negated",
"=",
"False",
"self",
".",
"_encoded_value",
"=",
"comp_str",
"self",
".",
"_standard_value",
"=",
"super",
"(",
"CPEComponent2_3_URI_edpacked",
",",
"self",
")",
".",
"_... | 29.538462 | 13.384615 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.