content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def clean_time_series(time, val, nPoi):
"""
Clean doubled time values and checks with wanted number of nPoi
:param time: Time.
:param val: Variable values.
:param nPoi: Number of result points.
"""
import numpy as np
# Create shift array
Shift = np.array([0.0], dtype='f')
# Shif... | 43,400 |
def deep_se_print(func: Callable) -> Callable:
"""Transforms the function to print nested side effects.
Searches recursively for changes on deep inner attributes of the arguments.
Goes down a tree until it finds some element which has no __dict__. For
each element of the tree, if it has no __dict__ or... | 43,401 |
def test_convert_satoshis_to_btc(mock_rest_client):
"""It should convert between satoshis and BTC and vice versa."""
sat = Price(10000, Price.SAT, mock_rest_client)
btc = sat.bitcoins
assert sat.denomination == Price.SAT
assert btc == 10000 / 1e8
new_btc = Price(btc, Price.BTC, mock_rest_client... | 43,402 |
def test_1_FBlockingIOError():
"""
Tests formatting a FBlockingIOError exception.
"""
with pytest.raises(Exception) as excinfo:
exc_args = {
'main_message': 'Problem with the construction project.',
'expected_result': 'A door',
'returned_result': 'A window',
... | 43,403 |
def prepare_checkpoints(path_to_checkpoints:str, link_keys=["link1","link2","link3","link4"], real_data=True,*args, **kwargs)-> str:
""" The main function preparing checkpoints for pre-trained SinGANs of Polyp images.
Parameters
-----------
path_to_checkpoints: str
A directory path to download ... | 43,404 |
def clean(deck_path: Path = Path(".")) -> None:
"""Wipe the build directory."""
logger = getLogger(__name__)
paths = Paths.from_defaults(deck_path)
if not paths.build_dir.exists():
logger.info(f"Nothing to do: {paths.build_dir} doesn't exist")
else:
logger.info(f"Deleting {paths.buil... | 43,405 |
def data_count():
"""
:return: 数据集大小
"""
return 300 | 43,406 |
def grid_name_lookup(engine):
"""Constructs a lookup table of Institute names to ids by combining names with
aliases and cleaned names containing country names in brackets. Multinationals are
detected.
Args:
engine (:obj:`sqlalchemy.engine.base.Engine`): connection to the database
Returns:... | 43,407 |
def sample_vMF(theta, kappa,size=1):
"""
Sampling from vMF
This is based on the implementation I found online here:
http://stats.stackexchange.com/questions/156729/sampling-from-von-mises-fisher-distribution-in-python
(**** NOTE THE FIX BY KEVIN *****)
which is based on :
... | 43,408 |
def fbx_mat_properties_from_texture(tex):
"""
Returns a set of FBX metarial properties that are affected by the given texture.
Quite obviously, this is a fuzzy and far-from-perfect mapping! Amounts of influence are completely lost, e.g.
Note tex is actually expected to be a texture slot.
"""
# M... | 43,409 |
def get_from_STEAD(key=None,
h5file_path='/mnt/GPT_disk/DL_datasets/STEAD/waveforms.hdf5'):
"""
Input:
key, h5file_path
Output:
data, p_t, s_t
"""
HDF5 = h5py.File(h5file_path, 'r')
if key.split('_')[-1] == 'EV':
dataset = HDF5.get('earthquake/... | 43,410 |
def test_dag_defaults_callbacks():
"""DAG has default callbacks, but these can be overwritten by individual tasks."""
dag = create_dag("./tests/projects/dag_callbacks") # The DAG has specified default callbacks
task1 = dag.get_task("task_1")
task2 = dag.get_task("task_2")
# Task 1 must have the DAG... | 43,411 |
def test_app():
"""
"""
"""End Test""" | 43,412 |
def test_empty_list_entry_polygon_check(poly_geo_plot):
"""Check that the polygon assert fails a list with an empty entry."""
with pytest.raises(ValueError, match="Empty list or GeoDataFrame "):
poly_geo_plot.assert_polygons([[]])
plt.close("all") | 43,413 |
def _safeFormat(formatter, o):
"""
Helper function for L{safe_repr} and L{safe_str}.
"""
try:
return formatter(o)
except:
io = NativeStringIO()
traceback.print_exc(file=io)
className = _determineClassName(o)
tbValue = io.getvalue()
return "<%s instance... | 43,414 |
def get_int(name, default):
"""
Get an environment variable as an int.
Args:
name (str): An environment variable name
default (int): The default value to use if the environment variable doesn't exist.
Returns:
int:
The environment variable value parsed as an int
... | 43,415 |
def test_validate_version_parameter():
"""
test of the version parameter validation
"""
rcdr = RenderedConfigDocsResource()
with pytest.raises(ApiError):
rcdr._validate_version_parameter('asdfjkl')
try:
rcdr._validate_version_parameter('buffer')
rcdr._validate_version_pa... | 43,416 |
def now_func():
"""Return current datetime
"""
func = get_now_func()
dt = func()
if isinstance(dt, datetime.datetime):
if dt.tzinfo is None:
return dt.replace(tzinfo=pytz.utc)
return dt | 43,417 |
def flatten_search_result(search_result):
"""
Converts all nested objects from the provided search result into non-nested `field->field-value` dicts.
Raw values (such as memory size, timestamps and durations) are transformed into easy-to-read values.
:param search_result: result to flatten
:return... | 43,418 |
def handle_interrupt_signals(handler_function):
"""Process interrupt signals"""
signal.signal(signal.SIGINT, handler_function)
signal.signal(signal.SIGPIPE, handler_function) | 43,419 |
def get_stretch_directory(sub_directory=''):
"""Returns path to stretch_user dir if HELLO_FLEET_PATH env var exists
Parameters
----------
sub_directory : str
valid sub_directory within stretch_user/
Returns
-------
str
dirpath to stretch_user/ or dir within it if stretch_us... | 43,420 |
def xroot(x, mu):
"""The equation of which we must find the root."""
return -x + (mu * (-1 + mu + x))/abs(-1 + mu + x)**3 - ((-1 + mu)*(mu + x))/abs(mu + x)**3 | 43,421 |
def spliter(data_dict, ratio=[6, 1, 1], shuffle=True):
"""split dict dataset into train, valid and tests set
Args:
data_dict (dict): dataset in dict
ratio (list): list of ratio for train, valid and tests split
shuffle (bool): shuffle or not
"""
if len(ratio) != 3:
r... | 43,422 |
def remove_setuptools():
"""
Remove setuptools from the current environment.
"""
print("Removing setuptools")
cmd = [sys.executable, '-m', 'pip', 'uninstall', '-y', 'setuptools']
# set cwd to something other than '.' to avoid detecting
# '.' as the installed package.
subprocess.check_cal... | 43,423 |
def NormaliseBinWidth(hist):
"""
Normalise each bin by its width
@param hist: Histogram to normalize by the bin width
"""
for mybin in range(1,hist.GetXaxis().GetNbins()+1):
bw = hist.GetXaxis().GetBinWidth(mybin)
hist.SetBinContent(mybin, hist.GetBinContent(mybin)/bw)
hist.S... | 43,424 |
def smooth(x, window_len=None, window='flat', method='zeros'):
"""Smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with the signal.
:param x: the input signal (numpy array)
:param window_len: the dimension of the smoothing window; should be... | 43,425 |
def copy_signatures(
target_function: Callable,
template_functions: List[TemplateFunction],
exclude_args: Iterable[str] = None,
) -> Callable:
"""A decorator that copies function signatures from one or more template functions to a
target function.
Args:
target_function: Function to modi... | 43,426 |
def landing():
"""
displays the landing page.
"""
return render_template('landing.html') | 43,427 |
def partition_and_save_models(hex_prisms, base_prisms, partition_indices, filename = "hex_prism_grid.stl"):
"""Returns a list of fused sub-volumes which can be individually printed
Args:
hex_prisms: the hexagonal pillars of the model which hold the mirorrs
base_prisms: the bottom hexagonal base... | 43,428 |
def _get_start_command(city: str) -> str:
"""Returns the docker run command needed for the MTS in order to train on the given city.
Parameters
----------
city: str
City the MTS should train on.
Returns
-------
docker_run_command: str
Corresponding docker run command.
""... | 43,429 |
def dict2pdb(d):
"""Transform an atom dictionary into a valid PDB line."""
(x, y, z) = d['coords']
args = (d['at_type'], d['ser_num'], d['at_name'], d['alt_loc'],
d['res_name'][-3:], d['chain_id'], d['res_id'], d['res_ic'],
x , y , z , d['occupancy'], d['bfactor'], d['seg_id'], d['el... | 43,430 |
def spark_collect():
"""Spark's collect
:input RDD data: The RDD to collect.
:output list result: The collected list.
"""
def inner(data: pyspark.rdd.RDD) -> ReturnType[list]:
o = data.collect()
return ReturnEntry(result=o)
return inner | 43,431 |
def freeze_layers(
model: torch.nn.Sequential,
n_layers_to_train: int
) -> torch.nn.Sequential:
"""
Function to freeze given number of layers for selected model
:param model: Instance of Pytorch model
:param n_layers_to_train: number of layers to train, counting from the last one.
... | 43,432 |
def is_figlet() -> bool:
"""Ensure figlet exists"""
process = subprocess.Popen(
['which', 'figlet'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
return process.wait() == 0 | 43,433 |
def createDatabase(_database_folder):
"""
Downloads trading data for available markets and saves it to a folder.
Downloads historical trading data with the highest resolution available and serializes it. It is recommended
to pause between downloads to not trigger server's DDOS filter.
:param _data... | 43,434 |
def generateHumanActivityBusiestDays(database):
"""Generate the Top 20 days with most human activity from the MySQL Database"""
try:
conn = pymysql.connect(host=conf.MYSQL_HOST, port=conf.MYSQL_PORT, user=conf.MYSQL_USER, passwd=conf.MYSQL_PWD, db=database)
except pymysql.MySQLError as e:
pr... | 43,435 |
def test_clear_error():
"""Check that rcParams cannot be cleared."""
with pytest.raises(TypeError, match="keys cannot be deleted"):
rcParams.clear() | 43,436 |
def test_derive_files_CyTOF_analysis():
"""Check that CyTOF analysis CSV is derived as expected."""
ct = load_ct_example("CT_cytof_with_analysis")
artifact_format_specific_data = {
"cell_counts_assignment": {"B Cell (CD27-)": 272727, "B Cell (Memory)": 11111},
"cell_counts_compartment": {"... | 43,437 |
def test_colorby_change(viewer_plugin):
"""
Check that arboretum widget colours change when the attribute that the
track is coloured by changes.
"""
viewer, plugin = viewer_plugin
id = 140
plugin.track_id = id
tree = plugin.plotter.tree
old_color = tree.get_branch_color(branch_id=id... | 43,438 |
def get_headers(wsgi_env):
"""
Extracts HTTP_* variables from a WSGI environment as
title-cased header names.
"""
return {
key[5:].replace('_', '-').title(): value
for key, value in wsgi_env.iteritems() if key.startswith('HTTP_')} | 43,439 |
def get_chats_between_users(user1, user2):
"""
Returns all chat objects between 2 users sorted by date posted.
Note: It does not check if they are a connection
"""
return Chat.objects.filter(Q(sender = user1, receiver = user2) | Q(sender = user2, receiver = user1)).order_by('-date_posted') | 43,440 |
def merge(source, destination):
"""
Deep-Merge two dictionaries.
Taken from http://stackoverflow.com/a/20666342/1928484.
>>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
>>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }
>>> merge(b, a) == { 'fir... | 43,441 |
def SequenceToConjunction(node):
"""Transform all SEQUENCE nodes into CONJUNCTION nodes.
Sequences have the same semantic meaning as conjunctions, so we transform them
to conjunctions to make query matching code simpler.
Arguments:
node: Root of the tree to transform.
Returns:
A tree with all SEQUE... | 43,442 |
def email_addresses_view_all(self) -> dict:
"""
Retrieve all existing EmailAddresses.
:param self:
:return
{
"ResponseType":"EmailAddresses",
"Version":"1.0",
"EmailAddresses":
[
{
"Version":"1.0",
... | 43,443 |
def adjusted_r2_score(ctx, pipeline, initial_metrics, num_rows):
"""Calculates the Adjusted R2 Score.
See: https://en.wikipedia.org/wiki/Coefficient_of_determination#Adjusted_R2
Parameters:
ctx (RecordingContext): The current context.
pipeline (Pipeline): The pipeline being evaluated.
... | 43,444 |
def bilinear_sampling(img, dp):
"""
warp rgbd images using projected depth * pixel and bilinear sampling
"""
b, hw, _ = dp.shape
_, _, h, w = img.shape
dp = dp.reshape(-1, 3) # reshape dp to (b*h*w, 3)
# homogeneous coord (wx, wy, w) -> real coord (x, y, 1)
# restrict depth not to negat... | 43,445 |
def mname(obj):
""" Get the full dotted name of the test method """
mod_name = obj.__class__.__module__.replace('h5py.tests.','')
return "%s.%s.%s" % (mod_name, obj.__class__.__name__, obj._testMethodName) | 43,446 |
def sharpe(simple_returns, riskfree_rate, period=period.MONTHLY):
"""Compute the sharpe ratio of series of returns. Commonly used to measure the performance
of an investment compared to a risk-free asset, after adjusting for its risk.
Return the difference between the returns of the investment and the risk... | 43,447 |
def get_all_listing_types():
"""
Get all listing types
"""
return models.ListingType.objects.all() | 43,448 |
def load_model(config_path, model_path):
""" Not knowing exactly what model we may have saved, try to load both types. """
def load_gpt():
try:
mconf = GPTConfig.from_json(config_path)
model = GPT(mconf)
model.load_state_dict(torch.load(model_path, map_location=devic... | 43,449 |
def protocol(monkeypatch):
"""Rflinkprotocol instance with mocked handle_packet."""
monkeypatch.setattr(PacketHandling, "handle_packet", Mock())
return PacketHandling(None) | 43,450 |
def new_from_at_rest(ethereum_network_at_rest: Dict[str, Any]) -> "EthereumNetwork":
"""Instantiate a new EthereumNetwork model from storage
Args:
ethereum_network_at_rest: The dto of the at-rest network from storage
Returns:
Instantiated EthereumNetwork client
Raises:
NotImpleme... | 43,451 |
def run(tests_names=None, common_kwargs=None):
"""
main function, launch the tests function from a list of test modules names
:param tests_names: testers to execute
:param common_kwargs: kwargs for all modules' functions
:return:
"""
if common_kwargs is None:
common_kwargs = {}
t... | 43,452 |
def get_auth_twitter_consumer(hashed_twitter_id: str) -> tweepy.OAuthHandler:
"""auth twitter with saved tokens.
Args:
hashed_twitter_id(str):
Returns:
tweepy.OAuthHandler:
"""
user = user_db_session.query(User.token, User.token_secret).filter(User.hashed_user_id == hashed_twitter_id... | 43,453 |
def retrieve_object_coordinates_from_db(
con,
object_ids,
key_object,
verbose=False):
"""
object_ids is a pd.DataFrame with rows representing objects and columns
Plate_Name
Image_Metadata_WellID
Image_Metadata_FieldID
<key_object>_Number_Object_Num... | 43,454 |
def zip(fn):
"""
Higher-order tensor zip function.
fn_zip = zip(fn)
c = fn_zip(a, b)
Args:
fn: function from two floats-to-float to apply
a (:class:`Tensor`): tensor to zip over
b (:class:`Tensor`): tensor to zip over
Returns:
:class:`Tensor` : new tensor d... | 43,455 |
def config_file_has_self_install_dirs(config_file):
"""Config file has self install dirs"""
has_self_install_dirs = False
with open(config_file) as _f:
for line in _f:
if re.search(r'^hard_drive_\d+_label\s*=\s*(amigaosdir|kickstartdir|userpackagesdir)', line, re.I) or \
... | 43,456 |
def implied_volatility(price, F, K, r, t, flag):
"""Returns the Black delta of an option.
:param price:
:type price: float
:param F: underlying futures price
:type F: float
:param K: strike price
:type K: float
:param r: annual risk-free interest rate
:type r: float
:param t: ti... | 43,457 |
def __generate_node_config(boot_conf, hb_conf):
"""
Generates the node configuration for snaps-kubernetes
:param boot_conf: the snaps-boot config dict
:param hb_conf: the adrenaline config dict
:return: list of dict containing the configuration of each kubernetes node
"""
out_list = list()
... | 43,458 |
def cmdReset():
"""Function added to reset TI board, no longer used."""
try:
mySocket.sendto('s' * 35 + ' reset', SERVER_IP)
except TypeError:
mainFrame.complain('Not connected') | 43,459 |
def cc_audio_offset(audio_file_1, audio_file_2):
"""
Get the audio offset between two WAV files, uses cross correlation
Code influenced by https://github.com/rpuntaie/syncstart/blob/main/syncstart.py
:param audio_file_1:
:param audio_file_2:
:return:
"""
sample_rate_1, audio_1 = wavfi... | 43,460 |
def main():
"""main.
"""
args = parse_args()
begin_event_file = args["file"][0]
end_event_file = args["file"][1]
troposphere_file = args["tfile"]
if args["tfile"] is not None:
meteo_tool = meteotool.MeteoTools(troposphere_file)
lat, lon = meteo_tool.get_lat_lon()
rh_... | 43,461 |
def crosstab(index: numpy.ndarray, columns: numpy.ndarray):
"""
usage.statsmodels: 2
"""
... | 43,462 |
def add_monoatomic(mof,ads_species,ads_pos):
"""
Add adsorbate to the ASE atoms object
Args:
mof (ASE Atoms object): starting ASE Atoms object of structure
ads_species (string): adsorbate species
ads_pos (numpy array): 1D numpy array for the proposed
adsorption position
Returns:
mof (ASE Atoms object... | 43,463 |
def make_parser(parser_constructor=argparse.ArgumentParser):
"""Make argparse parser object for RedPen server.
"""
parser = parser_constructor(
'redpen',
usage='%(prog)s [Options] [<INPUT FILE>]',
description='CLI for RedPen server',
add_help=False)
parser.add_argument(
... | 43,464 |
def df_aidxf_ctl():
"""Example df_aidxf of a molecule with a fragment combination of type connection tripodal linker."""
mol = Chem.MolFromSmiles('C1CC2CC1CCCCC1CCNC3CCCCCCC4CC2CC4CCCC13')
return pd.DataFrame([
['mol_ctl', 'XXX', 'QA', 0, [9, 10, 11, 12, 13, 28], 56.0, mol, Chem.Mol... | 43,465 |
def test_redirect():
"""
python ~/misc/tests/python/test_tee.py
"""
# sys_attr = 'stdout'
# redirector = PosixRedictSystemStream(sys_attr)
# with redirector:
# import ubelt as ub
# cmake_exe = ub.find_exe('cmake')
# subprocess.run([cmake_exe, '--version'])
# print... | 43,466 |
def make_dunder_main(manifest):
"""Generate a __main__.py file for the given manifest."""
prelude = manifest.get("prelude_points", [])
main = manifest.get("entry_point")
scripts = prelude + [main]
return MAIN_TEMPLATE.format(**locals()) | 43,467 |
def test_detect_duplicate_upload_items(duplicate_items: List[JSONDict]) -> None:
"""Test duplicate items detected"""
with pytest.raises(ValidationError) as e:
invalid_collection = UploadCollection(items=duplicate_items) # noqa: F841
assert e.value.errors() == [
{
"loc": ("item... | 43,468 |
def prefix_exists(bucket, key):
"""ensure_object_exists
:param bucket:
:param key:
"""
objects = S3_CLIENT.list_objects(Bucket=bucket, Prefix=key)
contents = objects.get('Contents')
if contents:
return len(contents) > 0
return False | 43,469 |
def cron_task_container(task_dict, add_task_only=False):
"""
定时任务容器. 调用目标函数, 并在运行结束后创建下一次定时
:param task_dict: 定时任务的相关参数, dict
{ "target":目标函数(可调用的函数对象,不是函数名字符串) 必须,
"iterval":任务延时(秒) 可选,
"priority":优先级 可选,
"name":定时任务别名 可选
"args":位置型参数 (arg1,arg2) 可选,
"kwargs":... | 43,470 |
def computeKxxPert(inpath, outpath, fraction):
"""
Takes a given matrix and sets randomly a fraction of all matrix values to nan.
@param inpath: Matrix given in h5 file where values are set to nan
@param outpath: Permuted matrix is stored in that h5 file
@param fraction: determines how many values a... | 43,471 |
def abort():
"""Stop exectution and return nonzero error code"""
sys.exit(1) | 43,472 |
def mae(y, y_pred):
"""mean absolute error for two ranks(encoded as strings)"""
errors = [abs(i - find_position(y, c))
for i,c in enumerate(y_pred) ]
return np.mean(errors) | 43,473 |
def newMsgWin(tw):
"""
New task message window
Create a new task message window, run the task displaying messages
and handling communications
* tw = TaskWindow for task to be executed.
"""
################################################################
# Be sure gui thread started... | 43,474 |
def __add_common_args(parser: argparse.ArgumentParser):
"""
add common arguments to sub-parsers
"""
parser.add_argument("--model", help="name of the model to use. Use query --get-models to get a list of valid names.")
parser.add_argument("--grid-type", help="type of the grid to use.")
parser.add... | 43,475 |
def _get_config_dict():
"""return the configuration dictionary with environment variables replaced"""
with open(f"{path_to_here}/_config_calc.yml") as fid:
config_dict_in = yaml.safe_load(fid)
required_keys = ["project_tmpdir", "model_data_dir", "dash_asset_fname"]
for key in required_keys:
... | 43,476 |
def plot_formatting(files_to_l, verbose=False):
"""
Reformats and writes the dictionary output to a text file to make plotting it in Excel easy
Input:
info_tuple --- a triplet from the calculate_generalized output
"""
num = 0
file_name = "GeneralizedDResultsByFile{0}.txt".format(num)
wh... | 43,477 |
def create_update_model_fn():
""" """
def update_model(model):
""" """
utils.apply_mask(model, use_cuda=False)
return model
return update_model | 43,478 |
def index_select_batch(data, indices):
"""Gather `indices` as batch indices from `data`, which can either be typical nd array or a
list of nd array"""
assert isinstance(indices, (tuple, list)) or (isndarray(indices) and len(indices.shape) == 1)
if isndarray(data):
return data[indices]
asse... | 43,479 |
def gen_cmd(dali_root_dir, file_list, process_includes=False):
"""
Command for calling cpplint.py
"""
if not file_list:
return ["true"]
cmd = ["python",
os.path.join(dali_root_dir, "third_party", "cpplint.py"),
"--quiet",
"--linelength=100",
"--roo... | 43,480 |
def start_process(cmd):
"""
Start BrowserStackLocal foreground process.
Monitor its output to find a specific text that indicates that the process has
successfully established connection to BrowserStack server and ready to serve.
Credits to https://stackoverflow.com/questions/10756383
:param ... | 43,481 |
def test_process_stream_good(responses_framer):
"""Test a buffer of good messages without noise."""
buffer = EXCEPTION_RESPONSE_FRAME + VALID_RESPONSE_FRAME
callback = MagicMock(return_value=None)
responses_framer.processIncomingPacket(buffer, callback)
assert len(callback.call_args_list) == 2
... | 43,482 |
def tnr_diff(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1):
""" Returns the between-group difference of True Negative Rates
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
prtc_attr (str): name of the protected attribute
... | 43,483 |
def call(value):
"""Call is meant to be used with the Method filter. It attempts to call
the method specified.
Usage:
{% load custom_filters %}
{% if foo|method:"has_access"|call %}
This will invoke foo.has_access()
"""
if not callable(value):
return "[%s is not calla... | 43,484 |
def permute_by_indices(list_of_things, *list_of_index_transpositions):
"""Given a list_of_things and a list of pairs of transpositions of indices
[(i, j), (k, m), ...], return the list_of_things with the i-th an j-th
values swapped, the k-th- and m-th values swapped, and so on.
Examples
--------
... | 43,485 |
def _string_to_int(string: str) -> int:
"""
a helper function convert from string to int, like S1 -> 1
Args:
string (str): input string
Returns:
(int): return value if this is a int, return 0 if this is not a int
"""
r = re.findall('\d+', string)
if (len(r) > 0):
... | 43,486 |
def create_moving_path(**kwargs):
"""
User interface function to create Path object for moving load.
:keyword:
* start_point (`Point`): Start point of path
* end_point (`Point`): End point of path
* increments (`int`): Increment of path steps. Default is 50
* mid_point (`Point`): Default =... | 43,487 |
def np_ortho(shape, random_state, scale=1.):
"""
Builds a numpy variable filled with orthonormal random values
Parameters
----------
shape, tuple of ints or tuple of tuples
shape of values to initialize
tuple of ints should be single shape
tuple of tuples is primarily for co... | 43,488 |
def _bind_generic_argument_list(field_list):
# type: (syntax.GenericArgumentList) -> ast.GenericArgumentList
"""Bind a generic argument list."""
ast_field_list = _bind_field_list(field_list, ast.GenericArgumentList)
ast_field_list.fields = [_bind_field_list_entry(f) for f in field_list.fields]
retur... | 43,489 |
def message_to_string(msg):
"""
Converts python message to string in a proper way.
"""
with closing(StringIO()) as fp:
if six.PY3:
g = Generator(fp, mangle_from_=False, policy=_compat32_crlf)
g.flatten(msg, unixfrom=False)
return fp.getvalue()
g = Gen... | 43,490 |
def calculate_diag_OR(clusters,clusters_ind,status):
"""Calculate the Odds Ratio for the probability of being diagnosed linked to being in a certain cluster
Parameters: clusters (dict): dictionary with cluster number as key and list of patients in cluster as value
clusters_ind (list): indices... | 43,491 |
def build(obj, parent=None):
"""
Safely builds the object by calling its method 'build' only if 'obj' possesses a 'build' method. Otherwise, will convert it to a string using the 'str' function. If a parent is passed, all packages and preamble lines needed to the object will be added to the packages and preambl... | 43,492 |
def _no_negative_zero(val):
"""Make sure -0 is never output. Makes diff tests easier."""
if val == 0:
return 0
return val | 43,493 |
def plot_predictions(ax, preds, satmut_len, seq_len, buffer):
""" Plot the raw predictions for a sequence and target
across the specificed saturated mutagenesis region.
Args:
ax (Axis): matplotlib axis to plot to.
preds (L array): Target predictions for one sequence.
satmut_len (i... | 43,494 |
def create_transformer_vectorizer(speech_file: SpeechFile) -> None:
"""
Creates a CountVectorizer and TfIdf transformer trained on all speeches of the given speech file. Stores them
in the folder tfidf
:param speech_file: File containing all the speeches
"""
speeches = [s.contents for s in speec... | 43,495 |
def weights(basis, X, deriv=None):
"""
Calculates the interpolant value or derivative weights for points X.
:param basis: interpolation function in each direction, eg,
``['L1', 'L1']`` for bilinear.
:type basis: list of strings
:param X: locations to calculate interpolant weights
:t... | 43,496 |
def svn_stream_readline(*args):
"""
svn_stream_readline(svn_stream_t stream, svn_stringbuf_t stringbuf, char eol,
svn_boolean_t eof, apr_pool_t pool) -> svn_error_t
"""
return apply(_core.svn_stream_readline, args) | 43,497 |
def stream_json(data: Iterable[Dict[Hashable, any]]) -> StreamingHttpResponse:
"""
Stream all elements in `data` as JSON array using the StreamingHttpResponse class.
Parameters
----------
data: Iterable[Dict[Hashable, any]]
An Iterable of JSON-encodable elements.
Returns
-------
StreamingHttpResponse
A st... | 43,498 |
def real_network_measures():
"""
""" | 43,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.