content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def q_fn(x):
"""
The Q-function assesses all possible actions that can be taken, given a state.
Two layer feed forward neural network. All layers are fully connected, biases initialized with 0.
The constants above define the layer sizes.
:param x: Batch input tensor to the network.
:return: Acti... | 4c4fece48773d020c321fd433aa75caa7bc258ee | 20,081 |
def getPlayer(env, name, decoder):
"""Get user's player data"""
players = getPlayers(env, decoder)
if name in players.keys():
return players[name]
else:
return False | fd98e481abab6e7f53bf66d0285f506d06f5e6ea | 20,082 |
import re
def get_config_errors(conf, filename="<no name>"):
"""
Validate a configuration object and return the list of errors found.
"""
rv = []
# Give a clearer error message than what jsonschema would give
# Something like: None is not of type 'object'
if not isinstance(conf, dict):
... | 4020d5dd33f840dc6c0e3c24be77acf80a606d57 | 20,083 |
def process_vcf( info ):
"""
pass izip object of line object and other needed vars
info[0] = list of vcf lines from VCF object iterator.
info[1] = clf object
info[2] = dataset dictionary
info[3] = filter arg supplied by user
info[4] = min classification frequency supplied by user (defaults to None)
"""
... | 389146cd88804935ee2aae85a9e5d84684f81b7e | 20,084 |
def compute_task1_f1_score(truth, solutions):
""" compute f1 score for task 1
:param truth: list of ground truth values for all problem-ids
:param solutions: list of solutions for all problem-ids
:return: f1 score
"""
task1_truth, task1_solution = extract_task_results(truth, solutions, 'multi-au... | 2e44603c547062d85023fb405d3ab511d3ca40d3 | 20,086 |
def multiply(t1,t2):
"""
Multiplies (expands) two binary expressions t1 and t2 based on the distributive rule
Args:
t1 (str): first binary expression
t2 (str): second binary expression
Returns:
A string representing the expansion of the boolean algebraic... | 0078ee94420722600be31edc74a86b1932c4d2f2 | 20,087 |
def source_remove_all(obj_type, obj_id, name, analyst=None):
"""
Remove a source from a top-level object.
:param obj_type: The CRITs type of the top-level object.
:type obj_type: str
:param obj_id: The ObjectId to search for.
:type obj_id: str
:param name: The name of the source.
:type ... | c9c7860f27b230ea9834c4a58324da70ebee9e30 | 20,088 |
def driver(dbname):
"""
Determine driver module
:Parameters:
`dbname` : ``str``
DB name (section token in db.conf)
:Return: Driver module
:Rtype: ``module``
:Exceptions:
- `DBConfigurationError` : DB not configured
- `KeyError` : DB name not found
- `ImportErro... | 01a2b0e10975879f944bbaf51b44d8eef6b97996 | 20,089 |
from typing import Union
def d1tile_x_d2(d1: Union[float, np.ndarray],
d2: np.ndarray) -> np.ndarray:
"""
Create array of repeated values with dimensions that match those of energy array
Useful to multiply frequency-dependent values to frequency-time matrices
:param d1: 1D input vecto... | 68721f7f9ab1b60f77e8199ad917dd47b19aaa95 | 20,090 |
def get_all_gradients_for_Q4( theta, X, Y ):
"""
Do the same thing as Q(iv) but it is actually only for storing and
observing the sample gradient and whole gradient for the Q(iv) step
Output the sample grdient and whole grdient data
"""
# Get difference of uclidean distance
def get_differen... | d508b826f552d844cf95f9d5515c5eb1512dfbcb | 20,091 |
def findSubsetIndices(min_lat,max_lat,min_lon,max_lon,lats,lons):
"""Array to store the results returned from the function"""
res=np.zeros((4),dtype=np.float64)
minLon=min_lon; maxLon=max_lon
distances1 = []; distances2 = []
indices=[]; index=1
for point in lats:
s1 = max_lat-point # ... | 7d41b33fd492fa8b5cd62c368210bcbea2c7bc89 | 20,092 |
def call(stoptime, seconds, method=None):
"""
Returns a dict with route, direction, stop, call time and source.
Call time is in UTC.
"""
result = dict(stoptime._asdict(), call_time=toutc(seconds), source=method or "I")
result["deviation"] = result["call_time"] - stoptime.datetime
return resu... | bfa78ec89b60bf1140b8b24bc91fd1a2dd9c2a63 | 20,093 |
import re
def sanitize_value(val):
"""Remove crap from val string and then convert it into float"""
val = re.sub(u"(\xa0|\s)", '', val)
val = val.replace(',', '.')
# positive or negative multiplier
mult = 1
if '-' in val and len(val) > 1:
mult = -1
val = val.replace('-', '')
... | 0fc67bf519674575451f4fc029bee658ea2bd2da | 20,094 |
def getObjectInfo(fluiddb, about):
"""
Gets object info for an object with the given about tag.
"""
return fluiddb.about[about].get() | 8614edaf44944fcc11882ac2fcaa31ba31d48d30 | 20,095 |
import warnings
def __getattr__(name):
"""Get attribute."""
deprecated = __deprecated__.get(name)
if deprecated:
warnings.warn(
"'{}' is deprecated. Use '{}' instead.".format(name, deprecated[0]),
category=DeprecationWarning,
stacklevel=(3 if PY37 else 4)
... | c904f1221492e8f08786918dd496d3d6861fd35e | 20,096 |
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
return common.read_model('finger.xml'), common.ASSETS | cacb53de08eef5695a5464fbb72a1706ff489276 | 20,097 |
async def process_logout():
"""
Purge the login information from the users session/cookie data
:return: Redirect to main body
"""
# Simply destroy the cookies in this session and get rid of the creds, redirect to landing
response = RedirectResponse("/") # Process the destruction from main app... | 98d9c8c40e0a1fe224538b353a2a803fdd7fce76 | 20,098 |
from typing import Optional
def _lex_label(label: str) -> _LexedLabel:
"""Splits the label into packages and target."""
match = _LABEL_LEXER.match(label)
if match is None:
raise ValueError(f'{label} is not an absolute Bazel label')
groups = match.groupdict()
packages: Optional[str] = groups['packages']
... | f067d5e81b02a4242d8459b41d49c302459f416b | 20,099 |
def generate_extra(candidate: tuple, expansion_set, murder_list=None, attempted=None) -> list:
"""
Special routine for graph based algorithm
:param candidate:
:param expansion_set:
:param murder_list:
:param attempted:
:return:
"""
check = manufacture_lambda(attempted, murder_list)
... | e38d605df2a562b269189c8e7714ec97e89d8f36 | 20,100 |
from typing import Tuple
from typing import Dict
def extract_oe_stereochemistry(
molecule: Molecule, oe_mol: "OEMol"
) -> Tuple[Dict[int, AtomStereochemistry], Dict[int, BondStereochemistry]]:
"""Extracts the CIP stereochemistry of each atom and bond in a OE molecule."""
atom_stereo = {
oe_atom.G... | 0d051e847c94a81585a1478fc10bfac335d700a6 | 20,101 |
from dipy.denoise.nlmeans import nlmeans
from scipy.ndimage.morphology import binary_erosion
from scipy import ndimage
def nlmeans_proxy(in_file, settings,
snr=None,
smask=None,
nmask=None,
out_file=None):
"""
Uses non-local means to deno... | 69629ef536830ccecdee09e5acfadf02d892cc9d | 20,102 |
def jointImgTo3D(sample):
"""
Normalize sample to metric 3D
:param sample: joints in (x,y,z) with x,y in image coordinates and z in mm
:return: normalized joints in mm
"""
ret = np.zeros((3,), np.float32)
# convert to metric using f
ret[0] = (sample[0]-centerX)*sample[2]/focalLengthX
... | 43726ed712e268c9fd2434fa2734ff8aa0ee2d0a | 20,104 |
def build_param_obj(key, val, delim=''):
"""Creates a Parameter object from key and value, surrounding key with delim
Parameters
----------
key : str
* key to use for parameter
value : str
* value to use for parameter
delim : str
* str to surround key with when adding to... | 0fba11c4564ef57eab45ffd02bed887c42a14121 | 20,106 |
def copy_fixtures_to_matrixstore(cls):
"""
Decorator for TestCase classes which copies data from Postgres into an
in-memory MatrixStore instance. This allows us to re-use database fixtures,
and the tests designed to work with those fixtures, to test
MatrixStore-powered code.
"""
# These meth... | b64ef9b23afc76b8f1b2cf1ae6b56635cd6e4f56 | 20,107 |
def intersect_description(first, second):
"""
Intersect two description objects.
:param first: First object to intersect with.
:param second: Other object to intersect with.
:return: New object.
"""
# Check that none of the object is None before processing
if first is None:
retur... | 93d35314f8ab6ef0978de942ecfad3719c8f4971 | 20,108 |
def smooth_correlation_matrix(cor, sigma, exclude_diagonal=True):
"""Apply a simple gaussian filter on a correlation matrix.
Parameters
----------
cor : numpy array
Correlation matrix.
sigma : int, optional
Scale of the gaussian filter.
exclude_diagonal : boolean, optional
... | 753337cc12578b5c2333392f01e028204ac2f0e0 | 20,109 |
def quantize_iir_filter(filter_dict, n_bits):
"""
Quantize the iir filter tuple for sos_filt funcitons
Parameters:
- filter_dict: dict, contains the quantized filter dictionary with the following keys:
- coeff: np.array(size=(M, 6)), float representation of the coefficients
- coeff_scale: n... | a8e93302072733d77acb563cd758725f14c05420 | 20,110 |
import json
import traceback
def add_goods(request, openid, store_id, store_name, dsr,
specification, brand, favorable_rate, pic_path, live_recording_screen_path, daily_price, commission_rate,
pos_price, preferential_way, goods_url, hand_card,
storage_condition, shelf_life, u... | e7a04a316e3fba3a803f20eb459dc8691ccc2642 | 20,111 |
def calcOneFeatureEa(dataSet: list, feature_idx: int):
"""
获取一个特征的E(A)值
:param dataSet: 数据集
:param feature_idx: 指定的一个特征(这里是用下标0,1,2..表示)
:return:
"""
attrs = getOneFeatureAttrs(dataSet, feature_idx)
# 获取数据集的p, n值
p, n = getDatasetPN(dataSet)
ea = 0.0
for attr in attrs:
... | fc800b285bc24246ad9c40070d33ff429e395183 | 20,115 |
def translate_mapping(mapping: list, reference: SimpleNamespace, templ: bool=True, nontempl: bool=True,
correctframe: bool=True, filterframe: bool=True, filternonsense: bool=True):
"""
creates a protein mapping from a dna mapping.
:param mapping: a list/tuple of ops.
:param referen... | 3a05ae38d9bccb8b855c91af850a92426c5031f3 | 20,116 |
from copy import copy
from numpy import zeros, unique
from itertools import product
def trainModel(label,bestModel,obs,trainSet,testSet,modelgrid,cv,optMetric='auc'):
""" Train a message classification model """
pred = zeros(len(obs))
fullpred = zeros((len(obs),len(unique(obs))))
model = copy(bestMode... | 8cea9f0044246972e80684fac584693a500198cc | 20,117 |
def get_device_state():
"""Return the device status."""
state_cmd = get_adb_command_line('get-state')
return execute_command(
state_cmd, timeout=RECOVERY_CMD_TIMEOUT, log_error=True) | e517e7df3f5a7a1bf3925a46ce6a780dbc862910 | 20,118 |
def character_state(combat, character):
"""
Get the combat status of a single character, as a tuple of
current_hp, max_hp, total healing
"""
max_hp = Max_hp(character.base_hp)
total_h = 0
for effect in StatusEffect.objects.filter(character=character, combat=combat, effect_typ__typ='M... | d80315934ac653d34dd73cc1a9861b9c6e2f2c9c | 20,119 |
def load_textfile(path) :
"""Returns text file as a str object
"""
f=open(path, 'r')
recs = f.read() # f.readlines()
f.close()
return recs | 8e12a93bb4918cbae7d7e9aad6f09f562eca0c16 | 20,120 |
import scipy
def interp1d_to_uniform(x, y, axis=None):
"""Resample array to uniformly sampled axis.
Has some limitations due to use of scipy interp1d.
Args:
x (vector): independent variable
y (array): dependent variable, must broadcast with x
axis (int): axis along which to resam... | 379071e0e0b718b4d4f8cc970a2b098cf3cab155 | 20,121 |
from typing import Dict
def flatten_dict(d: Dict):
"""Recursively flatten dictionaries, ordered by keys in ascending order"""
s = ""
for k in sorted(d.keys()):
if d[k] is not None:
if isinstance(d[k], dict):
s += f"{k}|{flatten_dict(d[k])}|"
else:
... | 26663b52ccda2a695aa2367cbaf324698a47d56a | 20,123 |
def getPVvecs(fname):
"""
Generates an ensemble of day long PV activities, sampled 3 different
days for each complete pv data set
"""
datmat = np.zeros((18,48))
df = dd.read_csv(fname)
i = 0
for unique_value in df.Substation.unique():
ttemp, ptemp = PVgettimesandpower("2014-06", unique_value, fname)
t, ... | 322cf6d29d4104953678ec5e4dfbd5a82564ce1c | 20,124 |
def vis9(n): # DONE
"""
O OO OOO
OO OOO OOOO
OOO OOOO OOOOO
Number of Os:
6 9 12"""
result = 'O' * (n - 1) + 'O\n'
result += 'O' * (n - 1) + 'OO\n'
result += 'O' * (n - 1) + 'OOO\n'
return result | c06c9fdf5d71ef89ce83d5fc2136b9854f018988 | 20,125 |
def derivative_circ_dist(x, p):
"""
Derivative of circumferential distance and derivative function, w.r.t. p
d/dp d(x, p) = d/dp min_{z in [-1, 0, 1]} (|z + p - x|)
Args:
x (float): first angle
p (float): second angle
Returns:
float: d/dp d(x, p)
"""
# pylin... | 36a4cc04cda32e8c6e5896d405f96068def8be41 | 20,126 |
def get_MB_compatible_list(OpClass, lhs, rhs):
""" return a list of metablock instance implementing an operation of
type OpClass and compatible with format descriptor @p lhs and @p rhs
"""
fct_map = {
Addition: get_Addition_MB_compatible_list,
Multiplication: get_Multiplication_M... | 172ca13f218f52e5834592fd09abf9444369d60c | 20,127 |
import torch
import random
def create_mock_target(number_of_nodes, number_of_classes):
"""
Creating a mock target vector.
"""
return torch.LongTensor([random.randint(0, number_of_classes-1) for node in range(number_of_nodes)]) | 1be4d86a0291d24f0be555d4eea7d29f0994db29 | 20,128 |
def is_iterable(obj):
"""
Return true if object has iterator but is not a string
:param object obj: Any object
:return: True if object is iterable but not a string.
:rtype: bool
"""
return hasattr(obj, '__iter__') and not isinstance(obj, str) | c7a1353f7f62a567a65d0c4752976fefde6e1904 | 20,129 |
def get_operator_module(operator_string):
"""
Get module name
"""
# the module, for when the operator is not a local operator
operator_path = ".".join(operator_string.split(".")[:-1])
assert len(operator_path) != 0, (
"Please specify a format like 'package.operator' to specify your opera... | 82b4ddc419b09b5874debbe64262b4a4f414cb8f | 20,131 |
def is_fraction(obj):
"""Test whether the object is a valid fraction.
"""
return isinstance(obj, Fraction) | ab0a1b11274f837f479fb62648a144f0e689b499 | 20,132 |
def getExtrusion(matrix):
"""calculates DXF-Extrusion = Arbitrary Xaxis and Zaxis vectors
"""
AZaxis = matrix[2].copy().resize3D().normalize() # = ArbitraryZvector
Extrusion = [AZaxis[0],AZaxis[1],AZaxis[2]]
if AZaxis[2]==1.0:
Extrusion = None
AXaxis = matrix[0].copy().resize3D() # = ArbitraryXvector
else:... | ec6133bddc9093310ffe1e807ae24882aa24edc3 | 20,133 |
def _build_class_include(env, class_name):
"""
If parentns::classname is included and fabric
properties such as puppet_parentns__classname_prop = val1
are set, the class included in puppet will be something like
class { 'parentns::classname':
prop => 'val1',
}
"""
include_def = ... | f58633fefb3ca853ef292f554eea4f98126c3ecb | 20,134 |
async def mention_html(user_id, name):
"""
The function is designed to output a link to a telegram.
"""
return f'<a href="tg://user?id={user_id}">{escape(name)}</a>' | eed9dd188f36e4d23bb16e274382372c6464f890 | 20,135 |
from plasma.flex.messaging.messages import small
def blaze_loader(alias):
"""
Loader for BlazeDS framework compatibility classes, specifically
implementing ISmallMessage.
.. seealso:: `BlazeDS (external)
<http://opensource.adobe.com/wiki/display/blazeds/BlazeDS>`_
:since: 0.1
"""
i... | 956acd6aa9c36c186081a43e271b6a3c61b7a53f | 20,136 |
def get_user_pic(user_id, table):
"""[summary]
Gets users profile picture
Args:
user_id ([int]): [User id]
table ([string]): [Table target]
Returns:
[string]: [Filename]
"""
try:
connection = database_cred()
cursor = connection.cursor()
curso... | 28ea65c793e88b967889fa39dc8588e4afd75e91 | 20,137 |
def convert_file_format(files,size):
"""
Takes filename queue and returns an example from it
using the TF Reader structure
"""
filename_queue = tf.train.string_input_producer(files,shuffle=True)
image_reader = tf.WholeFileReader()
_,image_file = image_reader.read(filename_queue)
image =... | 0a889dbf8b851716f7a7788cee6cc1f7e7b4c0fc | 20,138 |
def validate_access_rule(supported_access_types, supported_access_levels,
access_rule, abort=False):
"""Validate an access rule.
:param access_rule: Access rules to be validated.
:param supported_access_types: List of access types that are regarded
valid.
:param sup... | 2ce7ba446ec583b5b46dbd6a8eceeafe6cc46a6e | 20,139 |
def deduplicate(inp: SHAPE) -> SHAPE:
"""
Remove duplicates from any iterable while retaining the order of elements.
:param inp: iterable to deduplicate
:return: new, unique iterable of same type as input
"""
return type(inp)(dict.fromkeys(list(inp))) | d80ad3e00ce0bfa9a0625308267c5e25d8e3f3c9 | 20,141 |
def access_rules_synchronized(f):
"""Decorator for synchronizing share access rule modification methods."""
def wrapped_func(self, *args, **kwargs):
# The first argument is always a share, which has an ID
key = "share-access-%s" % args[0]['id']
@utils.synchronized(key)
def sou... | 03fe6b1905d825de1f20ed2967eb003f96fb2cce | 20,142 |
def import_python(path, package=None):
"""Get python module or object.
Parameters
----------
path : str
Fully-qualified python path, i.e. `package.module:object`.
package : str or None
Package name to use as an anchor if `path` is relative.
"""
parts = path.split(':')
if ... | ff2755964c0c24c5366e3243a1b2997176b33a4c | 20,143 |
from typing import Callable
from typing import Awaitable
async def feature_flags_scope_per_request(
request: Request, call_next: Callable[[Request], Awaitable[Response]]
) -> Response:
"""Use new feature flags copy for each request."""
# Create new copy of the feature flags, as we'll be modifying them la... | 9169a2f66f7fa60066695cfef5a320eedd566145 | 20,144 |
def get_scenes_need_processing(config_file, sensors):
"""
A function which finds all the processing steps for all the scenes which haven't yet been undertaken.
This is per scene processing rather than per step processing in the functions above.
Steps include:
* Download
* ARD Production
... | a600cd352980184ebe8382a5cabf9d8b09d9f688 | 20,146 |
def startingStateDistribution(env, N=100000):
"""
This function samples initial states for the environment and computes
an empirical estimator for the starting distribution mu_0
"""
rdInit = []
sample = {}
# Computing the starting state distribution
mu_0 =... | 2685ebe6315a085ffdabbb82786499191c33d957 | 20,147 |
def get_changepoint_values_from_config(
changepoints_dict,
time_features_df,
time_col=cst.TIME_COL):
"""Applies the changepoint method specified in `changepoints_dict` to return the changepoint values
:param changepoints_dict: Optional[Dict[str, any]]
Specifies the changepoint c... | 0c38283e5744f180fbd326a549a4ee37b461c213 | 20,149 |
def jitChol(A, maxTries=10, warning=True):
"""Do a Cholesky decomposition with jitter.
Description:
U, jitter = jitChol(A, maxTries, warning) attempts a Cholesky
decomposition on the given matrix, if matrix isn't positive
definite the function adds 'jitter' and tries again. Thereaf... | ac2cbc35a3a0c33208456765512893554d91f75c | 20,150 |
import requests
def stock_individual_info_em(symbol: str = "603777") -> pd.DataFrame:
"""
东方财富-个股-股票信息
http://quote.eastmoney.com/concept/sh603777.html?from=classic
:param symbol: 股票代码
:type symbol: str
:return: 股票信息
:rtype: pandas.DataFrame
"""
code_id_dict = code_id_map_em()
... | 6d04941cb1aeaed49450eff61e957aab26bbf21a | 20,151 |
def InverseDynamicsTool_safeDownCast(obj):
"""
InverseDynamicsTool_safeDownCast(OpenSimObject obj) -> InverseDynamicsTool
Parameters
----------
obj: OpenSim::Object *
"""
return _tools.InverseDynamicsTool_safeDownCast(obj) | 3060244716c54e10953df5aa8db1c55076a040a2 | 20,152 |
def build_decoder(encoding_dim,sparse):
""""build and return the decoder linked with the encoder"""
input_img = Input(shape=(28*28,))
encoder = build_encoder(encoding_dim,sparse)
input_encoded = encoder(input_img)
decoded = Dense(64, activation='relu')(input_encoded)
decoded = Dense(128, activ... | 207535e38fd45e7ea6e0143c34607213747328ba | 20,154 |
def find_usable_exits(room, stuff):
"""
Given a room, and the player's stuff, find a list of exits that they can use right now.
That means the exits must not be hidden, and if they require a key, the player has it.
RETURNS
- a list of exits that are visible (not hidden) and don't require a key!
... | 529bacbf33b5680774b291782fdcefe650cafeca | 20,155 |
def get_normal_map(x, area_weighted=False):
"""
x: [bs, h, w, 3] (x,y,z) -> (nx,ny,nz)
"""
nn = 6
p11 = x
p = tf.pad(x, tf.constant([[0,0], [1,1], [1,1], [0,0]]))
p11 = p[:, 1:-1, 1:-1, :]
p10 = p[:, 1:-1, 0:-2, :]
p01 = p[:, 0:-2, 1:-1, :]
p02 = p[:, 0:-2, 2:, :]
p12 = p... | 1b087113d6bc68a24195459ece006c7a74848a63 | 20,156 |
def _ros_group_rank(df, dl_idx, censorship):
"""
Ranks each observation within the data groups.
In this case, the groups are defined by the record's detection
limit index and censorship status.
Parameters
----------
df : pandas.DataFrame
dl_idx : str
Name of the column in the ... | f4495eb57d158745603899086e59643edec1e489 | 20,157 |
def f_all(predicate, iterable):
"""Return whether predicate(i) is True for all i in iterable
>>> is_odd = lambda num: (num % 2 == 1)
>>> f_all(is_odd, [])
True
>>> f_all(is_odd, [1, 3, 5, 7, 9])
True
>>> f_all(is_odd, [2, 1, 3, 5, 7, 9])
False
"""
return all(predicate(i) for i i... | c0a0e52587a7afc9da143ac936aab87ad531b455 | 20,158 |
from typing import List
from typing import Tuple
from typing import Set
from typing import Dict
def _recursive_replace(data):
"""Searches data structure and replaces 'nan' and 'inf' with respective float values"""
if isinstance(data, str):
if data == "nan":
return float("nan")
if d... | b5c21d806b462070b2d1eec7d91a5dc700f6b0ed | 20,159 |
def trans_text_ch_to_vector(txt_file, word_num_map, txt_label=None):
""" Trans chinese chars to vector
:param txt_file:
:param word_num_map:
:param txt_label:
:return:
"""
words_size = len(word_num_map)
to_num = lambda word: word_num_map.get(word.encode('utf-8'), words_size)
i... | 83370ca18303e1286b099d646362db14cd4b5dbd | 20,160 |
def adjust_bag(request, item_id):
""" Adjust the quantity of a product to the specified amount"""
quantity = int('0'+request.POST.get('quantity'))
bag = request.session.get('bag', {})
if quantity > 0:
bag[item_id] = quantity
else:
messages.error(request, 'Value must greather than o... | a2814adcffbc04ee02b18bd14fc7daf0dbe58677 | 20,161 |
def _condexpr_value(e):
"""Evaluate the value of the input expression.
"""
assert type(e) == tuple
assert len(e) in [2, 3]
if len(e) == 3:
if e[0] in ARITH_SET:
return _expr_value(e)
left = _condexpr_value(e[1])
right = _condexpr_value(e[2])
if type(left... | 3973a22b5c5553c2c1b70b94f97be4d54f224766 | 20,163 |
import socket
def in6_isincluded(addr, prefix, plen):
"""
Returns True when 'addr' belongs to prefix/plen. False otherwise.
"""
temp = inet_pton(socket.AF_INET6, addr)
pref = in6_cidr2mask(plen)
zero = inet_pton(socket.AF_INET6, prefix)
return zero == in6_and(temp, pref) | 4003d9b61ddb8f37207a2d332a31e4ee3a97cad7 | 20,164 |
def vis_channel(model, layer, channel_n):
"""
This function creates a visualization for a single channel in a layer
:param model: model we are visualizing
:type model: lucid.modelzoo
:param layer: the name of the layer we are visualizing
:type layer: string
:param channel_n: The channel ... | b6f1b72be81fa317fc59b3582b9f43afb640a4d6 | 20,165 |
from typing import Tuple
import time
def processing(log: EventLog, causal: Tuple[str, str], follows: Tuple[str, str]):
"""
Applying the Alpha Miner with the new relations
Parameters
-------------
log
Filtered log
causal
Pairs that have a causal relation (->)
follows
... | 5841c82462432edddddf1b0dfd965b1043bc7277 | 20,166 |
from typing import List
import re
def word_tokenize(string: str, language: str = "english") -> List[str]:
"""tokenizes a given string into a list of substrings.
:param string: String to tokenize.
:param language: Language. Either one of ``english'' or ``german''.
"""
if language not in ["english"... | 00cb30031fc5a9e7ddbfcffeae9fad031f463cb3 | 20,167 |
import torch
def modify_scaffolds_with_coords(scaffolds, coords):
""" Gets scaffolds and fills in the right data.
Inputs:
* scaffolds: dict. as returned by `build_scaffolds_from_scn_angles`
* coords: (L, 14, 3). sidechainnet tensor. same device as scaffolds
Outputs: corrected scaf... | 6d0853c3749fbf251cb3147109dab8951603c99c | 20,169 |
import pickle
from .stem import _classification_textcleaning_stemmer
def multinomial(**kwargs):
"""
Load multinomial toxicity model.
Parameters
----------
validate: bool, optional (default=True)
if True, malaya will check model availability and download if not available.
Returns
... | 78bb3ceffefd6b38c304758eda8c0bafe36462ab | 20,170 |
import logging
def create_bucket(bucket_name, region="us-west-2"):
"""Create an S3 bucket in a specified region
:param bucket_name: Bucket to create
:param region: String region to create bucket in, e.g., 'us-west-2'
:return: True if bucket created, else False
"""
# Create bucket
try:
# get list of existing... | c2d655982563c233a027dc94f9b73e8899aeddb7 | 20,171 |
def create_client():
"""Return a client socket that may be connected to a remote address."""
return _new_sock() | 5d0515c731d4c087c7b118923aa579d4bcd1e881 | 20,172 |
import warnings
import copy
def derivative_surface(obj):
""" Computes the hodograph (first derivative) surface of the input surface.
This function constructs the hodograph (first derivative) surface from the input surface by computing the degrees,
knot vectors and the control points of the derivative sur... | f9b846c0b2b17e315ae4b98138719361675df557 | 20,173 |
def configure(config):
"""
| [bing ] | example | purpose |
| -------- | ------- | ------- |
| api_key | VBsdaiY23sdcxuNG1gP+YBsCwJxzjfHgdsXJG5 | Bing Primary Account Key |
"""
chunk = ''
if config.option('Configuring bing search module', False):
config.interactive_add('bing', 'api_k... | 87ccd4694cfbf34d24e6e31f2b485aaa465ba68b | 20,174 |
def CVRMSE(ip1,ip2):
""" The normalized RMSE (= Root Mean Square Error) is defined as CVRMSE(X,Y) = sqrt[ sum_i(Yi-Xi)^2 / N ] / mean(Yi) ) """
stats = ip1.getStatistics()
return RMSE(ip1,ip2) / stats.mean | 0981637da92d2a60c6281f216587fa5bc798d554 | 20,175 |
def get_verified_aid_pairs(ibs):
"""
Example:
>>> # DISABLE_DOCTEST
>>> from wbia_cnn._plugin import * # NOQA
>>> import wbia
>>> ibs = wbia.opendb('NNP_Master3', allow_newdir=True)
>>> verified_aid1_list, verified_aid2_list = get_verified_aid_pairs(ibs)
"""
# Gr... | 91eb788a6b1f781e5796b03f56292a807aaee60d | 20,176 |
def audio_sort_key(ex):
"""Sort using duration time of the sound spectrogram."""
return ex.src.size(1) | ec940df6bf2b74962f221b84717f51beba5c4f5f | 20,177 |
from pathlib import Path
def _filename_to_title(filename, split_char="_"):
"""Convert a file path into a more readable title."""
filename = Path(filename).with_suffix("").name
filename_parts = filename.split(split_char)
try:
# If first part of the filename is a number for ordering, remove it
... | f62ae56901f0a58e53e84e63423bcb9f2ccf4c5a | 20,178 |
def basis_function_contributions(universe, mo, mocoefs='coef',
tol=0.01, ao=None, frame=0):
"""
Provided a universe with momatrix and basis_set_order attributes,
return the major basis function contributions of a particular
molecular orbital.
.. code-block:: python
... | afe695d15d3aa43baae0ce7e0dcf2fb84f53c699 | 20,179 |
from re import S
def bspline_basis(d, knots, n, x, close=True):
"""The `n`-th B-spline at `x` of degree `d` with knots.
B-Splines are piecewise polynomials of degree `d` [1]_. They are defined on
a set of knots, which is a sequence of integers or floats.
The 0th degree splines have a value of one o... | 266a8ef3176e11cc598015ebb963c13ddcee9e31 | 20,180 |
def is_versioned(obj):
"""
Check if a given object is versioned by inspecting some of its attributes.
"""
# before any heuristic, newer versions of RGW will tell if an obj is
# versioned so try that first
if hasattr(obj, 'versioned'):
return obj.versioned
if not hasattr(obj, 'Versio... | 7f5ad90ffce6a8efde50dba47cdc63673ec79f60 | 20,181 |
def preprocess_and_suggest_hyperparams(
task,
X,
y,
estimator_or_predictor,
location=None,
):
"""Preprocess the data and suggest hyperparameters.
Example:
```python
hyperparams, estimator_class, X, y, feature_transformer, label_transformer = \
preprocess_and_suggest_hyperpa... | cd388bea6c9bfbb5d38001c549f2fe92d16aff41 | 20,182 |
def passphrase_from_private_key(private_key):
"""Return passphrase from provided private key."""
return mnemonic.from_private_key(private_key) | aed1c465795d22fd80680c0484d377fa6cabf0c8 | 20,183 |
def merge_on_empty_fields(base, tomerge):
"""Utility to quickly fill empty or falsy field of $base with fields
of $tomerge
"""
has_merged_anything = False
for key in tomerge:
if not base.get(key):
base[key] = tomerge.get(key)
has_merged_anything = True
return has... | f8cb14047d2e17e2155beb1ab86eab7cdf531af0 | 20,184 |
def clear_rows(grid, locked):
"""Deletes the row, if that row is filled."""
increment = 0
for i in range(len(grid) - 1, -1, -1):
row = grid[i]
if (0, 0, 0) not in row:
increment += 1
index = i
for j in range(len(row)):
try:
... | 5974a129ac0bb756ee1038f61c9eeaf625ccbb72 | 20,185 |
import shlex
def call(cmd_args, suppress_output=False):
""" Call an arbitary command and return the exit value, stdout, and stderr as a tuple
Command can be passed in as either a string or iterable
>>> result = call('hatchery', suppress_output=True)
>>> result.exitval
0
>>> result = call(['h... | 1556d52de9d620e74c8a4b946c3120cf3579dede | 20,186 |
def provides(interface):
"""
A validator that raises a :exc:`TypeError` if the initializer is called
with an object that does not provide the requested *interface* (checks are
performed using ``interface.providedBy(value)`` (see `zope.interface
<http://docs.zope.org/zope.interface/>`_).
:param ... | 9b6e29aa8c3e0a1757daa1c0f3eb455ec66fa594 | 20,187 |
def v_t(r):
"""
Mean thermal velocity
"""
return (8/np.pi)**0.5*c(r) | af475d1376a549abe501b7b47e5f9fa35d8258c1 | 20,188 |
from typing import Callable
from typing import cast
def _state_stateful_alarm_controller(
select_state: Callable[[str], OverkizStateType]
) -> str:
"""Return the state of the device."""
if state := cast(str, select_state(OverkizState.CORE_ACTIVE_ZONES)):
# The Stateful Alarm Controller has 3 zones... | 3663d8dda26586dae416ce6d5dbe55fafdb821c8 | 20,189 |
def _connect_new_volume(module, array, answer=False):
"""Connect volume to host"""
api_version = array._list_available_rest_versions()
if AC_REQUIRED_API_VERSION in api_version and module.params['lun']:
try:
array.connect_host(module.params['host'],
module.... | f6b5dea4e78f832b536fdc269dfe1b9c040cb9b7 | 20,190 |
def is_mongo_configured(accessor):
"""
works out if mongodb is configured to run with trackerdash
i.e. first time running
"""
return accessor.verify_essential_collections_present() | c0487f6d899e6cee4f6bbb31bffbd17890812c30 | 20,191 |
from cms.api import add_plugin
def create_default_children_plugins(request, placeholder, lang, parent_plugin, children_conf):
"""
Create all default children plugins in the given ``placeholder``.
If a child have children, this function recurse.
Return all children and grandchildren (etc.) created
... | 121106100c50d7ebdace254b711e6d31611dbf3d | 20,192 |
import sympy
import math
def _split_value_equally(delta, count):
"""Splits an integer or rational into roughly equal parts."""
numer = sympy.numer(delta)
denom = sympy.denom(delta)
return [int(math.floor((numer + i) / count)) / denom for i in range(count)] | e241444100b2e0f3c1a589d87c41aa8710fe5b8e | 20,193 |
import ast
def maybe_get_docstring(node: ast.AST):
"""Get docstring from a constant expression, or return None."""
if (
isinstance(node, ast.Expr)
and isinstance(node.value, ast.Constant)
and isinstance(node.value.value, str)
):
return node.value.value
elif (
is... | 23171c739f3c9ae6d62ecf3307ac7c3409852d6b | 20,194 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.