content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def treynor(rp: np.ndarray, rb: np.ndarray, rf: np.ndarray) -> np.ndarray:
"""Returns the treynor ratios for all pairs of p portfolios and b benchmarks
Args:
rp (np.ndarray): p-by-n matrix where the (i, j) entry corresponds to the
j-th return of the i-th portfolio
rb (np.ndarray): b-b... | dd247f7ea1c710939ac27e626b3f863f49818fec | 12,800 |
def virus_tsne_list(tsne_df, virus_df):
"""
return data dic
"""
tsne_df.rename(columns={"Unnamed: 0": "barcode"}, inplace=True)
df = pd.merge(tsne_df, virus_df, on="barcode", how="left")
df["UMI"] = df["UMI"].fillna(0)
tSNE_1 = list(df.tSNE_1)
tSNE_2 = list(df.tSNE_2)
virus_UMI = lis... | b8265f3f3d6b602d045a890434322727d8e1adc5 | 12,801 |
def sometimes(aug):
"""
Return a shortcut for iaa.Sometimes
:param aug: augmentation method
:type aug: iaa.meta.Augmenter
:return: wrapped augmentation method
:rtype: iaa.meta.Augmenter
"""
return iaa.Sometimes(0.5, aug) | 95f7ece0b1da30c5a4e3be4d1a21e089e11d9036 | 12,802 |
def rev_to_b10(letters):
"""Convert an alphabet number to its decimal representation"""
return sum(
(ord(letter) - A_UPPERCASE + 1) * ALPHABET_SIZE**i
for i, letter in enumerate(reversed(letters.upper()))
) | b4850e97754f0404894673a51c1cce930e437f6c | 12,803 |
import os
import fnmatch
def AddPath(match):
"""Helper for adding file path for WebRTC header files, ignoring other."""
file_to_examine = match.group(1) + '.h'
# TODO(mflodman) Use current directory and find webrtc/.
for path, _, files in os.walk('./webrtc'):
for filename in files:
if fnmatch.fnmatc... | 8afe9abcd29a2a92ed142f743bd1469f823b5b14 | 12,804 |
def test_from_rsid(rsids, start_rsid):
"""Continue collecting publications for rsids in list, beginning with start_rsid
Args:
rsids (list): list of rsids to collect publications on
start_rsid (str): rsid identifier to resume collecting publications on
Returns:
runtime_rsids (list):... | bf2be86f28645addc08737e64f08695cd6b3a6d3 | 12,805 |
def _average_scada(times, values, nvalues):
"""
Function which down samples scada values.
:param times: Unix times of the data points.
:param values: Corresponding sensor value
:param nvalues: Number of samples we average over.
:return: new time values and
"""
if len(times) % nvalues:
... | 8743e5065741299befe37b230a22512c65001a09 | 12,806 |
def main():
"""
Test harness
"""
def game_factory():
"""
Creates the game we need
"""
return Maze(Layout.from_string(Layout.MEDIUM_STR))
bot_factory = PlannedBot
trainer = BotTrainer(game_factory, bot_factory, 16, 2, goal_score=13)
start_time = time()
gen... | 0528a4a4c51a4b9491314555d2ccd5c5b9baf328 | 12,807 |
def behavior_of(classname):
"""
Finds and loads the behavior class for C++ (decoded) classname or returns
None if there isn't one.
Behaviors do not have a required base class, and they may be used with
Awkward Array's ``ak.behavior``.
The search strategy for finding behavior classes is:
1... | ce588881e283f53755c7e468de298e6bc360cecc | 12,808 |
import os
def _abs_user_path(fpath):
"""don't overload the ap type"""
return os.path.abspath(os.path.expanduser(fpath)) | c5ee29b13783afcd5c6ad99d9e751f7ed5db58be | 12,809 |
def adjust(data):
"""Calculate mean of list of values and subtract the mean of every element
in the list, making a new list.
Returns tuple of mean, list of adjusted values
"""
mu = mean(data)
return mu, map(lambda x: (x-mu), data) | c0ddf7140dee90903452c16afb2625ded34c4d73 | 12,810 |
def clear():
"""
Clears the world, and then returns the cleared representation
"""
myWorld.clear()
return jsonify(myWorld.world()) | 4d999388696986ad9a0a954f3791f0a4795ef69a | 12,811 |
from typing import Optional
from typing import TextIO
def _create_terminal_writer_factory(output: Optional[TextIO]):
"""
A factory method for creating a `create_terminal_writer` function.
:param output: The receiver of all original pytest output.
"""
def _create_terminal_writer(config: Config, _f... | 9c06bd4b10eb5b1dc0e3e4f4f9bdb20074cacf6e | 12,812 |
import typing
def filter(
f: typing.Callable,
stage: Stage = pypeln_utils.UNDEFINED,
workers: int = 1,
maxsize: int = 0,
timeout: float = 0,
on_start: typing.Callable = None,
on_done: typing.Callable = None,
) -> Stage:
"""
Creates a stage that filter the data given a predicate fun... | 741a1d4f941a293b41c98872c59c8bf7e451bba5 | 12,813 |
import numpy
def function_factory(model, loss, dataset):
"""A factory to create a function required by tfp.optimizer.lbfgs_minimize.
Args:
model [in]: an instance of `tf.keras.Model` or its subclasses.
loss [in]: a function with signature loss_value = loss(pred_y, true_y).
train_x [in... | 2e50b3e085d2a88d76de31ba0fccb49f4f38dd1e | 12,814 |
import copy
import time
def nn_CPRAND(tensor,rank,n_samples,n_samples_err,factors=None,exact_err=False,it_max=100,err_it_max=20,tol=1e-7,list_factors=False,time_rec=False):
"""
Add argument n_samples_err
CPRAND for CP-decomposition in non negative case, with err_rand
return also exact error
Paramet... | 8cd3402407a54579ef279efd8b3459c34933c9cb | 12,815 |
def get_base_url(host_name, customer_id):
"""
:arg host_name: the host name of the IDNow gateway server
:arg customer_id: your customer id
:returns the base url of the IDNow API and the selected customer
"""
return 'https://{0}/api/v1/{1}'.format(host_name, customer_id) | 5a24a87f597cf01c61ab6a01202b2e01e3b00bf8 | 12,816 |
def sample_category(user, **params):
"""Create and return a sample category"""
defaults = {
'name': 'Sample category',
'persian_title': 'persian',
'parent_category': None
}
defaults.update(params)
return Category.objects.create(user=user, **defaults) | ec013f1b699c4ae76acb0c78819da875b2453846 | 12,817 |
from typing import Dict
def lindbladian_average_infid_set(
propagators: dict, instructions: Dict[str, Instruction], index, dims, n_eval
):
"""
Mean average fidelity over all gates in propagators.
Parameters
----------
propagators : dict
Contains unitary representations of the gates, i... | 71fcc97afc80bae0e53aea2fafd30b8279f76d08 | 12,818 |
def edit(request, course_id):
"""
Teacher form for editing a course
"""
course = get_object_or_404(Course, id=course_id)
courseForm = CourseForm(request.POST or None, instance=course)
if request.method == 'POST': # Form was submitted
if courseForm.is_valid():
courseForm.sa... | d4f39a26598108d9d5f03ad18fa6de26d88d849d | 12,819 |
def _build_ontology_embedded_list():
""" Helper function intended to be used to create the embedded list for ontology.
All types should implement a function like this going forward.
"""
synonym_terms_embed = DependencyEmbedder.embed_defaults_for_type(base_path='synonym_terms',
... | 2245b82313e26ba741200e24d323f6aa6b9741e0 | 12,820 |
def interp1d(x,y,xi,axis=None,extrap=True):
"""
Args:
x (uniformly sampled vector/array): sampled x values
y (array): sampled y values
xi (array): x values to interpolate onto
axis (int): axis along which to interpolate.
extrap (bool): if True, use linear extrapolation ba... | 081c4f5156cc653804cbd770edaf01ecdb426a51 | 12,821 |
import threading
def _back_operate(
servicer, callback, work_pool, transmission_pool, utility_pool,
termination_action, ticket, default_timeout, maximum_timeout):
"""Constructs objects necessary for back-side operation management.
Also begins back-side operation by feeding the first received ticket into ... | 46999af151338d0d8b15704e913801d9f2c80696 | 12,822 |
from typing import Tuple
import datasets
def load_train_val_data(
data_dir: str, batch_size: int,
training_fraction: float) -> Tuple[DataLoader, DataLoader]:
"""
Returns two DataLoader objects that wrap training and validation data.
Training and validation data are extracted from the full ... | 9cc0c67532e5d77fa8653d43c4f537137905767c | 12,823 |
def match(input_string, start_node):
"""匹配字符串
input_string :: 需要配备的字符串
start_node :: NFA起始节点
return :: True | False
"""
# 初始化运行状态的状态集合: 起始节点+空转移能到达的节点
current_state_set = [start_node]
next_state_set = closure(current_state_set)
# 循环读入字符生成状态集合
for i, ch in enumerate(inp... | fdc7c971cfeb3d0b13716ca1017c6557889d3f52 | 12,824 |
def _H_to_h(H):
"""Converts CIECAM02/CAM02-UCS hue composition (H) to raw hue angle (h)."""
x0 = H % 400 * 360 / 400
h, _, _ = fmin_l_bfgs_b(lambda x: abs(h_to_H(x) - H), x0, approx_grad=True)
return h % 360 | a9ccf1ec14b467b8a5e05b5e71141a4113cf0c07 | 12,825 |
def filter_df_merge(cpu_df, filter_column=None):
"""
process cpu data frame, merge by 'model_name', 'batch_size'
Args:
cpu_df ([type]): [description]
"""
if not filter_column:
raise Exception(
"please assign filter_column for filter_df_merge function")
df_lists = []
... | bc0e147ada18cbbb3e8450f8764d80be3ca32315 | 12,826 |
def MRP2Euler121(q):
"""
MRP2Euler121(Q)
E = MRP2Euler121(Q) translates the MRP
vector Q into the (1-2-1) euler angle vector E.
"""
return EP2Euler121(MRP2EP(q)) | 9cd8da8d38ad668b928ed896004611e85571be0d | 12,827 |
def nlayer(depth=64):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = NLayer_D(depth=depth)
return model | b8e57716e6b9576de9524cf730309885a79d0bfa | 12,828 |
import typing
def deserialize(
value: ElementTree.Element,
cipher: PSCryptoProvider,
**kwargs: typing.Any,
) -> typing.Optional[typing.Union[bool, PSObject]]:
"""Deserialize CLIXML to a Python object.
Deserializes a CLIXML XML Element from .NET to a Python object.
Args:
value: The CL... | 96b53a08c5c8273f29e108e020c40ab806c0949c | 12,829 |
import requests
def is_url_ok(url: str) -> bool:
"""Check if the given URL is down."""
try:
r = requests.get(url)
return r.status_code == 200
except Exception:
return False | 97e0ba4b609282ef0dc166f0f0407e4aacdf30b2 | 12,830 |
def calculate_pair_energy_np(coordinates, i_particle, box_length, cutoff):
"""
Calculate interaction energy of particle w/ its environment (all other particles in sys)
Parameters
----------------
coordinates : list
the coordinates for all particles in sys
i_particle : int
pa... | c626d1398312e42fd72d70c9b23d397fce5070fd | 12,831 |
def lwhere(mappings, **cond):
"""Selects mappings containing all pairs in cond."""
return list(where(mappings, **cond)) | ade55be28f75ae082833948306c43e4070525f7e | 12,832 |
import re
def get_number(message, limit=4):
"""
convert Chinese to pinyin and extract useful numbers
attention:
1. only for integer
2. before apply this method, the message should be preprocessed
input:
message: the message you want to extract numbers from.
limit: lim... | ae1cc6886a4a2931baa61fcb201ffa67f70aecf6 | 12,833 |
import traceback
import time
import sqlite3
import os
def get_db_connection(path, timeout=30, okay_to_create=False):
"""
Returns a properly configured SQLite database connection.
:param path: path to DB
:param timeout: timeout for connection
:param okay_to_create: if True, create the DB if it doe... | ad15cb2352a6d92edfe71fd741494fcacb723a50 | 12,834 |
import sqlite3
def create_connection(db_file):
"""
Creates a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
... | 37571690b5e970fc4344ee1d5d449b16cfc15896 | 12,835 |
def convex_hull(poly):
"""
ratio of the convex hull area to the area of the shape itself
Altman's A_3 measure, from Neimi et al 1991.
"""
chull = to_shapely_geom(poly).convex_hull
return poly.area / chull.area | 0ed9b4803b87b4138cb5490b153376aae6e71e99 | 12,836 |
from typing import Dict
from typing import List
from typing import Tuple
import torch
def create_scifact_annotations(
claims, corpus, tokenizer, class_to_id: Dict[str, int], neutral_class: str
) -> List[SciFactAnnotation]:
"""Create a SciFactAnnotation for each claim - evidence/cited document pair."""
de... | 0a38b572bac113d6aa0a47e7628a5cc9fec85f16 | 12,837 |
import os
def epsilon(tagfile):
"""Compute the total epsilon factor for each event
Compute the flatfield correction from the P-flat and L-flat reference files
(PFLTFILE and LFLTFILE respectively).
Parameters
----------
tagfile, str
input STIS time-tag data file
Returns
-----... | a2170036c9047d0137fcd5a2564eeb404c88ad35 | 12,838 |
import math
def sort_by_value(front, values):
"""
This function sorts the front list according to the values
:param front: List of indexes of elements in the value
:param values: List of values. Can be longer than the front list
:return:
"""
copied_values = values.copy() # Copy so we can modify it
sor... | 2d259ebbc0117f9aa043d78394b6423e596f176e | 12,839 |
import os
def save_exposure(fitstbl, frame, spectrograph, science_path, par, caliBrate, all_spec2d, all_specobjs):
"""
Save the outputs from extraction for a given exposure
Args:
frame (:obj:`int`):
0-indexed row in the metadata table with the frame
that has been reduced.
... | 2e4ee240fc5d2e5607966aa3d77d50777f300e81 | 12,840 |
def get_cell_area(self, indices=[]):
"""Return the area of the cells on the outer surface.
Parameters
----------
self : MeshVTK
a MeshVTK object
indices : list
list of the points to extract (optional)
Returns
-------
areas: ndarray
Area of the cells
"""
... | 518416acfae67f1b6e1280d5fd903d311d57f4d8 | 12,841 |
def _to_dataarray(origins, sources, values):
""" Converts grid_search inputs to DataArray
"""
origin_dims = ('origin_idx',)
origin_coords = [np.arange(len(origins))]
origin_shape = (len(origins),)
source_dims = sources.dims
source_coords = sources.coords
source_shape = sources.shape
... | d7ac153f4e872e55ab55ddb76dfcf994e4523443 | 12,842 |
from typing import Optional
from typing import List
from pathlib import Path
import inspect
import pprint
import tempfile
import warnings
import json
def package(metadata: Metadata, requirements: Optional[List[str]] = None, path: Optional[str] = None):
"""Packages the chatbot into a single archive for deployment.... | 0fb974eef4c36bc5fa0e5366eb1bf4634585025a | 12,843 |
def warp_grid(grid: tf.Tensor, theta: tf.Tensor) -> tf.Tensor:
"""
Perform transformation on the grid.
- grid_padded[i,j,k,:] = [i j k 1]
- grid_warped[b,i,j,k,p] = sum_over_q (grid_padded[i,j,k,q] * theta[b,q,p])
:param grid: shape = (dim1, dim2, dim3, 3), grid[i,j,k,:] = [i j k]
:param theta... | 570c3acb6c57aff18b27deaa2ab5401e0fac23b6 | 12,844 |
async def makenotifyrole(guild):
"""Make the notify role in the given guild.
:type guild: discord.Guild
:rtype: None | discord.Role
:param guild: Guild instance to create the role in.
:return: The created role, possibly None if the creation failed.
"""
userrole = None
try:
# The... | 1da1eea0a1d510abdf21bc532f6c1d4ab6d41140 | 12,845 |
def mape(forecast: Forecast, target: Target) -> np.ndarray:
"""
Calculate MAPE.
This method accepts one or many timeseries.
For multiple timeseries pass matrix (N, M) where N is number of timeseries and M is number of time steps.
:param forecast: Predicted values.
:param target: Target values.
... | 47d68499aa351b70d466940d7f3722566cf67568 | 12,846 |
def reverse_weighted_graph(graph):
"""
Function for reverting direction of the graph (weights still the same)
Args:
graph: graph representation as Example: {1: {2: 1, 3: 5}, 2: {3: 2}, 4: {1: 2}}
Returns:
reversed graph
Examples:
>>> reverse_weighted_graph({1: {2: 1, 3: 5}... | 100e05bf3b5e937133321673531103c7abd94bdb | 12,847 |
def clean_bin():
"""permanently deletes entries - crud delete"""
mongo.db.bin.remove()
mongo.db.bin.insert({'_id': ObjectId()})
return redirect(url_for('get_bin', data_requested="teams")) | bb1cb957112826710572bb5930dd1683d4295997 | 12,848 |
def correct_by_threshold(img, threshold):
"""
correct the fMRI RSA results by threshold
Parameters
----------
img : array
A 3-D array of the fMRI RSA results.
The shape of img should be [nx, ny, nz]. nx, ny, nz represent the shape of the fMRI-img.
threshold : int
The nu... | 67750aba6d03d82d9e41d2d53a82550e5a68a3e2 | 12,849 |
def config_date(dut, date):
"""
:param dut:
:param date:
:return:
"""
st.log("config date")
command = "date --set='{}'".format(date)
st.config(dut, command)
return True | 055db1a0ddb4d640d154aae4dec29e3845d7dfb8 | 12,850 |
def read_dicom():
"""Read in DICOM series"""
dicomPath = join(expanduser('~'), 'Documents', 'SlicerDICOMDatabase',
'TCIALocal', '0', 'images', '')
reader = sitk.ImageSeriesReader()
seriesIDread = reader.GetGDCMSeriesIDs(dicomPath)[1]
dicomFilenames = reader.GetGDCMSeriesFileNam... | 64c4aae3c1cc0e31d6db46e741a3ecc52be580cc | 12,851 |
import codecs
import os
def read_file(*file_paths):
"""Read text file."""
with codecs.open(os.path.join(ROOT_DIR, *file_paths), 'r') as fp:
return fp.read() | 485c69428bbff5fc0aaf3c1a9bafe2b6863a7bcd | 12,852 |
import os
import toml
def load_config():
"""Load the config file and validate contents."""
filename = os.path.join(user_config_dir("timetagger_cli"), config_fname)
if not os.path.isfile(filename):
raise RuntimeError("Config not set, run 'timetagger setup' first.")
with open(filename, "rb") as... | 7440fb2a96fe360bcf99bef0085ecfa8a07f2aaa | 12,853 |
import subprocess
def zfs_upgrade_list(supported: bool = False) -> str:
"""
zfs upgrade [-v]
Displays a list of file systems that are not the most recent version.
-v Displays ZFS filesystem versions supported by the current
software. The current ZFS filesystem version and all previous
... | a9665900425a9d6c9398762999e8c76193d9ee85 | 12,854 |
def L_model_backward(AL, Y, caches):
"""
完成L层神经网络模型后向传播计算
Arguments:
AL -- 模型输出值
Y -- 真实值
caches -- 包含Relu和Sigmoid激活函数的linear_activation_forward()中每一个cache
Returns:
grads -- 包含所有梯度的字典
grads["dA" + str(l)] = ...
grads["dW" + str(l)] = ...
grads["db... | ef296179d51e8c4b8be474414f65f812b6f8ffb0 | 12,855 |
from sys import path
def findbps(reads, output, bowtie_options, motif, length, threshold, strand):
"""
Input:
reads: str of name of file where single-end, stranded
RNA-seq reads in fastq format are located
output:str of desired basename of output files
bowtie_options: str of bowtie opt... | eee9d313359b9ce00d67e27682038e9ec0c2f630 | 12,856 |
def Cnot(idx0: int = 0, idx1: int = 1) -> Operator:
"""Controlled Not between idx0 and idx1, controlled by |1>."""
return ControlledU(idx0, idx1, PauliX()) | a087aa4d7fb22343523a8b6114a7b50eea971e21 | 12,857 |
def init_sql_references(conn):
"""
Utility function to get references from SQL.
The returned objects conveniently identify users based on kb_name or user hashkey
"""
# get kb_names to kb_id
kb_ref = pds.read_sql("""SELECT id, kb_name, directory_id FROM dbo.kb_raw""", conn)
get_kb_dir_id = ... | 3f9874632d50cd8a483d75573cc1d63561f253d2 | 12,858 |
def inoptimal_truncation_square_root(A, B, C, k, check_stability=False):
"""Use scipy to perform balanced truncation
Use scipy to perform balanced truncation on a linear state-space system.
This method is the natural application of scipy and inoptimal performance
wise compared to `truncation_square_roo... | 3c4fa1ac73f22f5e07d49314e1cf3d3b022349e8 | 12,859 |
def _tessellate_bed(chrom: str, chromStart: int, chromEnd: int, window_size: int) -> pd.DataFrame:
"""Return tessellated pandas dataframe splitting given window.
Parameters
-----------------------
chrom: str,
Chromosome containing given window.
chromStart: int,
Position where the wi... | 706b031069dd334bc6f364e077398ced56b152a8 | 12,860 |
import os
import pathlib
def _replace_variables(dictionary):
"""Replace environment variables in a nested dict."""
for path in _walk(dictionary):
value = path.pop()
if isinstance(value, str) and _ispath(value):
value = os.path.expandvars(value)
value = pathlib.Path(value)
last_key = path.p... | 0e753dad54a14d931a1b8075f5e14c0670245090 | 12,861 |
def compute_locksroot(locks: PendingLocksState) -> Locksroot:
"""Compute the hash representing all pending locks
The hash is submitted in TokenNetwork.settleChannel() call.
"""
return Locksroot(keccak(b"".join(locks.locks))) | 05c4996a9cc837939c662ef419e36421cb00033d | 12,862 |
from typing import Union
from typing import List
def flatten(text: Union[str, List[str]], separator: str = None) -> str:
"""
Flattens the text item to a string. If the input is a string, that
same string is returned. Otherwise, the text is joined together with
the separator.
Parameters
------... | 3980e0d0d14ac5764c4c5844ab3a943d1971d0ad | 12,863 |
def convert_byte32_arr_to_hex_arr(byte32_arr):
"""
This function takes in an array of byte32 strings and
returns an array of hex strings.
Parameters:
byte32_arr Strings to convert from a byte32 array to a hex array
"""
hex_ids = []
for byte32_str in byte32_arr:
hex_ids = hex_ids... | 9185c1e98b6eb10a42714e1fc53ebaed88997a82 | 12,864 |
import sys
import tqdm
def process_ring(cat, ref, pairs, ringpairs, area, radius, sigma, sigma_init=None, gamma=None, niter=10, nextr=100, mid=True,
printprogress=True, printerror=False):
"""
Estimate omega with robust algorithm in rings. Obtain optimal estimate from best ring.
Internal function t... | 871488f467825d5226a19dc6840e9c145f7754d8 | 12,865 |
from typing import Union
from typing import Tuple
def backtest_loop(
start_time: Union[pd.Timestamp, str],
end_time: Union[pd.Timestamp, str],
trade_strategy: BaseStrategy,
trade_executor: BaseExecutor,
) -> Tuple[PortfolioMetrics, Indicator]:
"""backtest function for the interaction of the outerm... | 74620671f0e37b7439d15d76e0e3e92b8984a608 | 12,866 |
import functools
def failOnNonTransient(func):
"""Only allow function execution when immutable is transient."""
@functools.wraps(func)
def wrapper(inst, *args, **kwargs):
# make the call fail if the object is not transient
if inst.__im_state__ != interfaces.IM_STATE_TRANSIENT:
... | 46b94385084a6b7dae9149cfe8864b94df3ed5ea | 12,867 |
def text_has_emoji(text):
"""判断文本中是否包含emoji"""
for character in text:
if character in emoji.UNICODE_EMOJI:
return True
return False | 8fd0cfb2aed42a6b149f29ffea5d65bc901c5353 | 12,868 |
def rod_faces(n1, n2, xform, dim1, dim2): # validated
"""
defines points in a circle with triangle based end caps
"""
# 4,8,12,16,... becomes 5,9,13,17,...
thetas = np.radians(np.linspace(0., 360., 17))
ntheta = len(thetas)
nfaces = 0
all_faces = []
points_list = []
x = np.zeros... | 306fdde57121f497d6ef263c2caea187bfc7af10 | 12,869 |
def xfork():
""" xfork() is similar to fork but doesn't throw an OSError exception.
Returns -1 on error, otherwise it returns the same value as fork() does.
"""
try:
ret = fork()
except OSError:
ret = -1
return ret | 1bc0c16a2d71e4e1607d45af485a7c2999fbe631 | 12,870 |
import re
def cigar_segment_bounds(cigar, start):
"""
Determine the start and end positions on a chromosome of a non-no-matching part of an
RNA-seq read based on a read's cigar string.
cigar string meaning: http://bioinformatics.cvr.ac.uk/blog/tag/cigar-string/
Example:
'50M25N50M' with ... | c870dfb9b11e2fd1df9fb347528252f114b8d70f | 12,871 |
def augument(data_dir, img_path, steering_angle, range_x=100, range_y=10):
"""
Generate an augumented image and adjust steering angle.
(The steering angle is associated with the image)
"""
image, steering_angle = choose_image(data_dir, img_path, steering_angle)
image, steering_angle = random_fli... | 1eafb5ea4ed024e6bab4008155c8364e8a480b8f | 12,872 |
def ldns_buffer_limit(*args):
"""LDNS buffer."""
return _ldns.ldns_buffer_limit(*args) | d7a4c3c50ffd6db98d78a6a092c256bd1e0e3c11 | 12,873 |
import os
import sqlite3
import sys
def language():
"""
Loads languages.
:return: None
"""
if os.path.isfile(omw_db):
omw_connection = sqlite3.connect(omw_db)
cursor = omw_connection.cursor()
known = dict()
cursor.execute("""SELECT id, iso639 from lang""")
... | 486971b6357b472833a3b71e6935d986dee9629e | 12,874 |
import os
import ntpath
import urllib
def test_data_folder():
"""
This fixture returns path to folder with shared test resources among all tests
"""
data_dir = os.path.join(script_dir, "testdata")
if not os.path.exists(data_dir):
os.mkdir(data_dir)
files_to_download = ["https://ra... | df590eecb07fe15ed88635e0b307739868b082d5 | 12,875 |
def _call_godot(environment, source, arguments, target):
"""Runs the Godot executable with the specified command line arguments
@param environment Environment in which the Godot executable will be run
@param source Input files that will be involved
@param arguments Arguments that will be p... | 4320a6af9d2d1f8e8a06494df201c9c4a6f2416b | 12,876 |
def random_seeded(func):
""" Decorator that uses the `random_seed` parameter from functions to seed the RNG. """
@wraps(func)
def wrapper(*args, random_seed: int = None, **kwargs):
_RNG.seed(random_seed)
return func(*args, **kwargs)
return wrapper | 1bf572625092680fb996b34469a9a990627acd59 | 12,877 |
def getCRS(station_name=None, crs=None, autoCreate=True):
"""
Method to get CRS code for the give station name. This method may not
scale nicely for a production environment. Use a proper DB instead.
@param station_name: Some characters for the station name.
@param crs: CRS code if known
@p... | e44cda3f0299cc5cc57c2574debe011809e716e6 | 12,878 |
def _initialize_object_from_dict(object_dict, parent=None):
"""Initialize a python object from dict."""
provider = object_dict['provider']
args = object_dict.get('args') or []
kwargs = object_dict.get('kwargs') or {}
obj = _get_object_by_referance(provider)
if parent is not None:
kwarg... | a6fb19c0db1e839514d19df50e223bf98a2241f8 | 12,879 |
def from_hdf(in_path, index=None, keypoints=True, descriptors=True):
"""
For a given node, load the keypoints and descriptors from a hdf5 file. The
keypoints and descriptors kwargs support returning only keypoints or descriptors.
The index kwarg supports returning a subset of the data.
Parameters
... | 2ec00092e04dcd41c7a263781b8a5f7e8d888e5f | 12,880 |
def main(cfg):
"""Solve the CVRP problem."""
# Instantiate the data problem.
data = create_data_model(cfg)
print(data)
if len(data['distance_matrix'])==0:
result = {
"solution":False,
"error-message":"unable to calculate distance matrix"
}
return resul... | a33c1df5462e9af2eb508b7e2803dfd371609656 | 12,881 |
def get_corners(p, fov):
"""Get corners relative to DSS coordinates. xy coords anti-clockwise"""
c = np.array([[0, 0], fov[::-1]]) # lower left, upper right xy
# corners = np.c_[c[0], c[:, 1], c[1], c[::-1, 0]].T # / clockwise yx
corners = np.c_[c[0], c[::-1, 0], c[1], c[:, 1]].T # / clockwise xy
... | e66e4dfd8eb26dc2caacd2e59c64de5d85bc7d10 | 12,882 |
from typing import Dict
from typing import Any
from typing import Tuple
from typing import List
def mixnet_m(
num_classes: int = 1000,
multiplier: float = 1.0,
divisor: int = 8,
min_depth: int = None,
dataset: str = "IMAGENET",
) -> Dict[str, Any]:
"""Build MixNet-M."""
if dataset == "IMAG... | 839852df3bc535613093c752addc6aed64e61e5b | 12,883 |
import functools
import asyncio
def no_block(func):
"""Turns a blocking function into a non-blocking coroutine function."""
@functools.wraps(func)
async def no_blocking_handler(*args, **kwargs):
partial = functools.partial(func, *args, **kwargs)
return await asyncio.get_event_loop().run_i... | 5681fe7275a89c522384b28f9473fded8bba846b | 12,884 |
def wgan_g_loss(scores_fake):
"""
Input:
- scores_fake: Tensor of shape (N,) containing scores for fake samples
Output:
- loss: Tensor of shape (,) giving WGAN generator loss
"""
return -scores_fake.mean() | 089561b47059a4bf07bf878012ce650cd6e34b4f | 12,885 |
import time
def centroid_avg(stats):
"""
Read centroid X and Y 10x and return mean of centroids.
stats : stats method of ophyd camera object to use, e.g. cam_8.stats4
Examples
--------
centroid_avg(cam_8.stats4)
centroidY = centroid_avg(cam_8.stats4)[1]
"""
centroidX... | 5fb1715ab77858084f25400bd8c2508689b57cc1 | 12,886 |
def get_address_host_port(addr, strict=False):
"""
Get a (host, port) tuple out of the given address.
For definition of strict check parse_address
ValueError is raised if the address scheme doesn't allow extracting
the requested information.
>>> get_address_host_port('tcp://1.2.3.4:80')
('1... | a0ec20c347becc6f403b9ee121d127fee41c6b0d | 12,887 |
def get_ua_list():
"""
获取ua列表
"""
with open('zhihu_spider/misc/ua_list.txt', 'r') as f:
return [x.replace('\n', '') for x in f.readlines()] | 6ebcf5d85650ad6644ccdf48aafed0160bd52ec0 | 12,888 |
import time
def measure_time(func):
"""add time measure decorator to the functions"""
def func_wrapper(*args, **kwargs):
start_time = time.time()
a = func(*args, **kwargs)
end_time = time.time()
#print("time in seconds: " + str(end_time-start_time))
return end_time - st... | e9fb4c1b7260cfe686204b50cbe46f27f25c467a | 12,889 |
def generate_dummy_targets(bounds, label, n_points, field_keys=[], seed=1):
"""
Generate dummy points with randomly generated positions. Points
are generated on node 0 and distributed to other nodes if running
in parallel.
Parameters
----------
bounds : tuple of float
Bounding box t... | 6986161499aa62c3e0a9bea4367886dc51736c74 | 12,890 |
from typing import List
def load_numbers_sorted(txt: str) -> List[int]:
"""ファイルから番号を読み込みソートしてリストを返す
Args:
txt (str): ファイルのパス
Returns:
List[int]: 番号のリスト
"""
numbers = []
with open(txt) as f:
numbers = sorted(map(lambda e: int(e), f))
return numbers | 6f10badd417a2ceefefa9f28a5c40583ea077d43 | 12,891 |
import os
import sys
import logging
def start_logger(log_directory_path):
"""To set up the log file folder and default configuration give a log directory path
Args:
log_directory_path (str): The directory path to create a folder containing the log files.
Returns:
logger (object):... | 2fb4ec745368277d3e2ee2c1b8f98abfe47ad650 | 12,892 |
def translate_pt(p, offset):
"""Translates point p=(x,y) by offset=(x,y)"""
return (p[0] + offset[0], p[1] + offset[1]) | 9fdc578d461219e9e5d1b557b9fde3d7a0946815 | 12,893 |
import os
def inference(hypes, images, train=True):
"""Build the MNIST model up to where it may be used for inference.
Args:
images: Images placeholder, from inputs().
train: whether the network is used for train of inference
Returns:
softmax_linear: Output tensor with the computed log... | f612becb6a6fe3bfa808ccee2ef0462b600fcf23 | 12,894 |
def truncate(sequence):
""" Do nothing. Just a placeholder. """
string = str(sequence)
return string.split()[0] | 2e8eeffb08d6d3d5d6ad5e6a83e596ec61a2eea2 | 12,895 |
def unbind(port: int) -> dict:
"""Request browser port unbinding.
Parameters
----------
port: int
Port number to unbind.
"""
return {"method": "Tethering.unbind", "params": {"port": port}} | c980eaa28e29dd44139035f0c8882d2960322328 | 12,896 |
import os
def get_files(dir="."):
""" Gets all the files recursivly from a given base directory.
Args:
dir (str): The base directory path.
Returns:
list: A list that contains all files.
"""
folder_queue = [dir]
files = set()
while(folder_queue):
next_fold... | 4c29efa262c2b1be04952beb9acb6a2d8b622a3a | 12,897 |
def xy_to_ellipse(x,Vx,y,Vy):
"""
Takes the Cartesian variables.
This function returns the particle's position relative to an ellipse and parameters of the ellipse.
Returns a,e,theta,theta_E
"""
# radius using x and y
r = np.sqrt(x ** 2 + y ** 2)
# speed of the particle
V =... | 2606a81899431349adc419b04d87063f2e75936a | 12,898 |
from typing import List
from typing import Dict
from typing import OrderedDict
def leak_dictionary_by_ignore_sha(
policy_breaks: List[PolicyBreak],
) -> Dict[str, List[PolicyBreak]]:
"""
leak_dictionary_by_ignore_sha sorts matches and incidents by
first appearance in file.
sort incidents by first... | d94bc10b8f2d94eee639bd94e75ad5835d9b6f1a | 12,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.