content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def utcnow():
"""Better version of utcnow() that returns utcnow with a correct TZ."""
return timeutils.utcnow(True) | 46,200 |
def fetch_rows(cursor):
""" Fetch and yield rows """
for row in cursor.fetchall():
yield row | 46,201 |
def test_imagehandler_extract_file_simple(tmp_path, caplog):
"""Extract a file from the tarfile and gets its info."""
caplog.set_level(logging.DEBUG, logger="charmcraft")
# create a tar file with one file inside
test_content = b"test content for the sample file"
sample_file = tmp_path / "testfile.t... | 46,202 |
def build_profile(base_image, se_size=4, se_size_increment=2, num_openings_closings=4):
"""
Build the extended morphological profiles for a given set of images.
Parameters:
base_image: 3d matrix, each 'channel' is considered for applying the morphological profile. It is the spectral inf... | 46,203 |
def mujoco_env(env_id, nenvs=None, seed=None, summarize=True,
normalize_obs=True, normalize_ret=True):
""" Creates and wraps MuJoCo env. """
assert is_mujoco_id(env_id)
seed = get_seed(nenvs, seed)
if nenvs is not None:
env = ParallelEnvBatch([
lambda s=s: mujoco_env(env_id, seed=s, s... | 46,204 |
def polar2cart(r, theta):
"""
Transform polar coordinates to Cartesian.
Parameters
----------
r, theta : floats or arrays
Polar coordinates
Returns
-------
[x, y] : floats or arrays
Cartesian coordinates
"""
return torch.stack((r * theta.cos(), r * theta.sin()... | 46,205 |
def belongs_to(user, group_name):
"""
Check if the user belongs to the given group.
:param user:
:param group_name:
:return:
"""
return user.groups.filter(name__iexact=group_name).exists() | 46,206 |
def test_setting_duplicated_config_flag_sets_only_desired_flag(mocker):
"""Test changing normal_init.type only affects the desired instance of the flag.
This is a regression test as reuse of the same Dict object used to mean that setting
any instance of normal_init.type would change all other instances too... | 46,207 |
def sum_log_loss(logits, mask, reduction='sum'):
"""
:param logits: reranking logits(B x C) or span loss(B x C x L)
:param mask: reranking mask(B x C) or span mask(B x C x L)
:return: sum log p_positive i over all candidates
"""
num_pos = mask.sum(-1) # B x C
gold_s... | 46,208 |
def _get_iat_method(iatmethod):
"""Control routine for selecting the method used to calculate integrated
autocorrelation times (iat)
Parameters
----------
iat_method : string, optional
Routine to use for calculating said iats. Accepts 'ipce', 'acor', and 'icce'.
Returns
------... | 46,209 |
def setup_ubuntu():
"""
Install the required Ubuntu dependencies from the package repository.
These packages are for Ubuntu 14.04
"""
sudo('apt-get -q -y install make gcc python-dev git mercurial nginx python-pip python-setuptools python-virtualenv')
sudo('apt-get -q -y install postgresql-9.3 po... | 46,210 |
def test(model, eval_data):
"""
Computes the average loss on eval_data, which should be a Dataset.
"""
avg_loss = keras.metrics.Mean()
for (labels, chars, sequence_length) in eval_data:
predictions = model((chars, sequence_length), training=False)
avg_loss.update_state(keras.losses... | 46,211 |
def run():
"""Main entry point."""
return cli(obj={}, auto_envvar_prefix='IMPLANT') # noqa | 46,212 |
def test_kmeans():
"""Test implementation of Kmeans."""
X_train, y_train = load_basic_motions(split="train")
X_test, y_test = load_basic_motions(split="test")
kmeans = TimeSeriesKMeans(
averaging_method="mean",
random_state=1,
n_init=2,
n_clusters=4,
init_algorit... | 46,213 |
def writeFile(sentences, filename, maximum=-1, doLog=True):
"""Writes a list of strings to file, seperates by newline"""
start = time.time()
with io.open(filename, 'w+', encoding='utf8') as f:
for i, s in enumerate(sentences):
f.write(s + "\n")
if i == maximum:
... | 46,214 |
def qtl_test_interaction_GxG(pheno, snps1, snps2=None, K=None, covs=None, test="lrt"):
"""
Epistasis test between two sets of SNPs
Args:
pheno: [N x 1] np.array of 1 phenotype for N individuals
snps1: [N x S1] np.array of S1 SNPs for N individuals
snps2: [N x S2] np.array of S2 S... | 46,215 |
def fixture_working_dir():
"""A pytest fixture that creates a temporary working directory, config file, schema, and local user identity
"""
# Create temp dir
config_file, temp_dir = _create_temp_work_dir()
# Create user identity
insert_cached_identity(temp_dir)
# Create test client
sch... | 46,216 |
def log_parser(log):
"""
This takes the EA task log file generated by e-prime and converts it into a
set of numpy-friendly arrays (with mixed numeric and text fields.)
pic -- 'Picture' lines, which contain the participant's ratings.
res -- 'Response' lines, which contain their responses (unclear)
... | 46,217 |
def line_assign_z_to_vertexes(line_2d: ogr.Geometry,
dem: DEM,
allowed_input_types: List[int] = None) -> ogr.Geometry:
"""
Assign Z dimension to vertices of line based on raster value of `dem`. The values from `dem` are interpolated using
bilinear ... | 46,218 |
def test_calibration_ols():
"""Testing ordinary least squares procedure. And compare with device calibrated temperature.
The measurements were calibrated by the device using only section 8--17.m. Those temperatures
are compared up to 2 decimals. Silixa only uses a single calibration constant (I think they
... | 46,219 |
def before_scenario(context, scenario):
"""Environment preparation before other cli tests are run.
Installs kedro by running pip in the top level directory.
"""
# make a venv
kedro_install_venv_dir = _create_new_venv()
context.venv_dir = kedro_install_venv_dir
context = _setup_context_with_... | 46,220 |
def test_featurecount():
"""Test star index creation and mapping."""
map_dir = os.path.join("tests/test_count", "processes", "mapping", "samp5")
if os.path.exists(map_dir) is False:
os.makedirs(map_dir)
cp_cmd = ["tests/data/test_prok/processes/mapping/samp5/samp5_srt.bam", map_dir]
cp[cp_c... | 46,221 |
def backoff_linear(n):
"""
backoff_linear(n) -> float
Linear backoff implementation. This returns n.
See ReconnectingWebSocket for details.
"""
return n | 46,222 |
def _doc():
"""
:rtype: str
"""
return pkg_resources.resource_string(
'dcoscli',
'data/help/config.txt').decode('utf-8') | 46,223 |
def sk_algo(U, gates, n):
"""Solovay-Kitaev Algorithm."""
if n == 0:
return find_closest_u(gates, U)
else:
U_next = sk_algo(U, gates, n-1)
V, W = gc_decomp(U @ U_next.adjoint())
V_next = sk_algo(V, gates, n-1)
W_next = sk_algo(W, gates, n-1)
return V_next @ W_next @ V_next.adjoint() @ W... | 46,224 |
def get_movie_list():
"""
Returns:
A list of populated media.Movie objects
"""
print("Generating movie list...")
movie_list = []
movie_list.append(media.Movie(
title='Four Brothers',
summary='Mark Wahlberg takes on a crime syndicate with his brothers.',
trailer_yo... | 46,225 |
def check_dna_sequence(sequence):
"""Check if a given sequence contains only the allowed letters A, C, T, G."""
return len(sequence) != 0 and all(base.upper() in ['A', 'C', 'T', 'G'] for base in sequence) | 46,226 |
def test_inner_scalar_mod_args_length():
"""
Feature: Check the length of input of inner scalar mod.
Description: The length of input of inner scalar mod should not less than 2.
Expectation: The length of input of inner scalar mod should not less than 2.
"""
class Net(Cell):
def __init__... | 46,227 |
def zip_list_files(url):
"""
cd = central directory
eocd = end of central directory
refer to zip rfcs for further information :sob:
-Erica
"""
# get blog representing the maximum size of a EOBD
# that is 22 bytes of fixed-sized EOCD fields
# plus the max comment len... | 46,228 |
def project_ball(tensor, epsilon=1, ord=2):
"""
Compute the orthogonal projection of the input tensor (as vector) onto the L_ord epsilon-ball.
**Assumes the first dimension to be batch dimension, which is preserved.**
:param tensor: variable or tensor
:type tensor: torch.autograd.Variable or torch... | 46,229 |
def decode_json(filepath="stocks.json"):
"""
Description: Generates a pathname to the service account json file
needed to access the google calendar
"""
# Check for stocks file
if os.path.exists(filepath):
return filepath
creds = os.environ.get("GOOGLE_SERVICE_CREDS")
if creds ... | 46,230 |
def load_model(filename):
"""
Loads the specified Keras model from a file.
Parameters
----------
filename : string
The name of the file to read from
Returns
-------
Keras model
The Keras model loaded from a file
"""
return load_keras_model(__construct_path(file... | 46,231 |
def get_ffmpeg_executable_path(ffmpeg_folder_path):
"""
Get's ffmpeg's executable path for current system, given the folder.
:param ffmpeg_folder_path: Folder path for the ffmpeg and ffprobe executable.
:return: ffmpeg executable path as absolute path.
"""
return os.path.join(ffmpeg_folder_path... | 46,232 |
def testjob(request):
"""
handler for test job request
Actual result from beanstalk instance:
* testjob triggerd at 2019-11-14 01:02:00.105119
[headers]
- Content-Type : application/json
- User-Agent : aws-sqsd/2.4
- X-Aws-Sqsd-Msgid : 6998edf8-3f19-4c69-92cf-7c919241b957
- X-Aws-Sq... | 46,233 |
def args_parser_test():
"""
returns argument parser object used while testing a model
"""
parser = argparse.ArgumentParser()
parser.add_argument('--architecture', type=str, metavar='arch', required=True, help='neural network architecture [vgg19, resnet50]')
parser.add_argument('--dataset',type=str, required=True... | 46,234 |
def todatetime(mydate):
""" Convert the given thing to a datetime.datetime.
This is intended mainly to be used with the mx.DateTime that psycopg
sometimes returns,
but could be extended in the future to take other types.
"""
if isinstance(mydate, datetime.datetime):
return my... | 46,235 |
def generate_datetime(time: str) -> datetime:
"""生成时间戳"""
today: str = datetime.now().strftime("%Y%m%d")
timestamp: str = f"{today} {time}"
dt: datetime = parse_datetime(timestamp)
return dt | 46,236 |
def get_rgb_scores(arr_2d=None, truth=None):
"""
Returns a rgb image of pixelwise separation between ground truth and arr_2d
(predicted image) with different color codes
Easy when needed to inspect segmentation result against ground truth.
:param arr_2d:
:param truth:
:return:
"""
ar... | 46,237 |
def calClassMemProb(param, expVars, classAv):
"""
Function that calculates the class membership probabilities for each observation in the
dataset.
Parameters
----------
param : 1D numpy array of size nExpVars.
Contains parameter values of class membership model.
expVars : 2D num... | 46,238 |
def detect_statistical_outliers(
cloud_xyz: np.ndarray, k: int, std_factor: float = 3.0
) -> List[int]:
"""
Determine the indexes of the points of cloud_xyz to filter.
The removed points have mean distances with their k nearest neighbors
that are greater than a distance threshold (dist_thresh).
... | 46,239 |
def describe_image_builders(Names=None, MaxResults=None, NextToken=None):
"""
Retrieves a list that describes one or more specified image builders, if the image builder names are provided. Otherwise, all image builders in the account are described.
See also: AWS API Documentation
Exceptions
... | 46,240 |
def collinear(cell1, cell2, column_test):
"""Determines whether the given cells are collinear along a dimension.
Returns True if the given cells are in the same row (column_test=False)
or in the same column (column_test=True).
Args:
cell1: The first geocell string.
cell2: The second geocell string.
... | 46,241 |
def plasma_fractal(mapsize=512, wibbledecay=3):
"""Generate a heightmap using diamond-square algorithm.
Modification of the algorithm in
https://github.com/FLHerne/mapgen/blob/master/diamondsquare.py
Args:
mapsize: side length of the heightmap, must be a power of two.
wibbledecay: integer, decay facto... | 46,242 |
def stat_to_longname(st, filename):
"""
Some clients (FileZilla, I'm looking at you!)
require 'longname' field of SSH2_FXP_NAME
to be 'alike' to the output of ls -l.
So, let's build it!
Encoding side: unicode sandwich.
"""
try:
n_link = str(st.st_nlink)
except: # Some stat... | 46,243 |
def driver():
"""
Make sure this driver returns the result.
:return: result - Result of computation.
"""
_n = int(input())
arr = []
for i in range(_n):
arr.append(input())
result = solve(_n, arr)
print(result)
return result | 46,244 |
def synapses_vs_weights(filename="distal", param_list=None):
"""Clump synapses and vary synapse numbers and synapse weights.
param_list contains tuples of (exc_syn, inh_syn, exc_weight, inh_weight, clump)
"""
import itertools
syn_list = param_list
if not syn_list:
syn_list = itertools.... | 46,245 |
def load_element_different(properties, data):
"""
Load elements which include lists of different lengths
based on the element's property-definitions.
Parameters
------------
properties : dict
Property definitions encoded in a dict where the property name is the key
and the property ... | 46,246 |
def start_survey():
"""clears the session and starts the survey"""
# QUESTION: flask session is used to store temporary information. for permanent data, use a database.
# So what's the difference between using an empty list vs session. Is it just for non sens. data like user logged in or not?
# QUESTI... | 46,247 |
def test_scan_and_find_dependencies_maven():
"""Test scan_and_find_dependencies function for Maven."""
manifests = [{
"filename": "dependencies.txt",
"filepath": "/bin/local",
"content": open(str(Path(__file__).parent / "data/dependencies.txt")).read()
}]
res = DependencyFinder()... | 46,248 |
def page(token):
"""``page`` property validation."""
if token.type == 'ident':
return 'auto' if token.lower_value == 'auto' else token.value | 46,249 |
def adjust_learning_rate(optimizer, epoch):
"""
調整學習率
"""
global lr
if epoch % 30 == 0 and epoch != 0:
lr = lr * 0.9
if (lr < min_lr):
lr = min_lr
for param_group in optimizer.param_groups:
param_group['lr'] = lr | 46,250 |
def main():
"""
Challenge 09: Using ImageDraw to draw polygon from points
http://www.pythonchallenge.com/pc/return/good.html
"""
# Read text files and gather numberical points
pattern = re.compile(r'\d+')
dots1 = re.findall(pattern, open("text/lv9-dots1.txt").read())
dots2 = re.findall(p... | 46,251 |
def create_fsns_label(image_dir, anno_file_dirs):
"""Get image path and annotation."""
if not os.path.isdir(image_dir):
raise ValueError(f'Cannot find {image_dir} dataset path.')
image_files_dict = {}
image_anno_dict = {}
images = []
img_id = 0
for anno_file_dir in anno_file_dirs:... | 46,252 |
def index():
"""
Gets the the weight data and displays it to the user.
"""
# Create a base query
weight_data_query = Weight.query.filter_by(member=current_user).order_by(Weight.id.desc())
# Get all the weight data.
all_weight_data = weight_data_query.all()
# Get the last 5 data points f... | 46,253 |
def git_pull(remote='origin', branch='prod'):
"""Updates the repository."""
with cd(env.directory):
run('git fetch --all')
run('git reset --hard %s/%s' % (remote, branch)) | 46,254 |
def upload_binified_data(binified_data, error_handler, survey_id_dict):
""" Takes in binified csv data and handles uploading/downloading+updating
older data to/from S3 for each chunk.
Returns a set of concatenations that have succeeded and can be removed.
Returns the number of failed FTP... | 46,255 |
def system_get_enum_values(enum):
"""Gets all values from a System.Enum instance.
Parameters
----------
enum: System.Enum
A Enum instance.
Returns
-------
list
A list containing the values of the Enum instance
"""
return list(Enum.GetValues(enum)) | 46,256 |
def skip_leading_ws_with_indent(s,i,tab_width):
"""Skips leading whitespace and returns (i, indent),
- i points after the whitespace
- indent is the width of the whitespace, assuming tab_width wide tabs."""
count = 0 ; n = len(s)
while i < n:
ch = s[i]
if ch == ' ':
c... | 46,257 |
def testContactPerson():
"""
@tests:
ContactPerson.__init__
ContactPerson.getFirstName
ContactPerson.setFirstName
ContactPerson.getLastName
ContactPerson.setLastName
ContactPerson.setName
ContactPerson.getInstitution
ContactPerson.setInstitution
ContactPerson.getEmai... | 46,258 |
def streamTap(source, tap):
"""
DEPRECATED!
"""
#print("******** Stream TAP is deprecated. Use streamConnect instead. ********")
streamConnect(source,tap) | 46,259 |
def linkcode_resolve(domain, info):
"""
Determine the URL corresponding to Python object
"""
if domain != 'py':
return None
modname = info['module']
fullname = info['fullname']
submod = sys.modules.get(modname)
if submod is None:
return None
obj = submod
for pa... | 46,260 |
def get_minibam_bed(bamfile, bedfile, minibam=None):
""" samtools view -L could do the work, but it is NOT random access. Here we
are processing multiple regions sequentially. See also:
https://www.biostars.org/p/49306/
"""
pf = op.basename(bedfile).split(".")[0]
minibamfile = minibam or op.bas... | 46,261 |
def test_2():
""" database - simple test with sqlalchemy/elixir unicode test """
file_path = os.path.join(os.path.dirname(__file__), 'helloworld.csv')
try:
f = open(file_path, 'r', encoding='utf-8')
except TypeError:
f = open(file_path, 'r')
reader = csv.reader(f)
res = {}
f... | 46,262 |
def create_app(config_object="tigerhacks_api.settings"):
"""Create application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/.
:param config_object: The configuration object to use.
"""
app = Flask(__name__.split(".")[0])
logger.info("Flask app initialized")
app... | 46,263 |
def dest_in_spiral(data):
"""
The map of the circuit consists of square cells. The first element in the
center is marked as 1, and continuing in a clockwise spiral, the other
elements are marked in ascending order ad infinitum. On the map, you can
move (connect cells) vertically and horizontally.... | 46,264 |
def get_current_time():
""" returns current time w.r.t to the timezone defined in
Returns
-------
: str
time string of now()
"""
import pytz
from datetime import datetime
srv = get_server()
if srv.time_zone is None:
time_zone = 'UTC'
else:
time_zone = srv... | 46,265 |
async def _update_google_domains(hass, session, domain, user, password, timeout):
"""Update Google Domains."""
url = f"https://{user}:{password}@domains.google.com/nic/update"
params = {"hostname": domain}
try:
async with async_timeout.timeout(timeout):
resp = await session.get(url... | 46,266 |
def smoothen_over_time(lane_lines):
"""
Smooth the lane line inference over a window of frames and returns the average lines.
"""
avg_line_lt = np.zeros((len(lane_lines), 4))
avg_line_rt = np.zeros((len(lane_lines), 4))
for t in range(0, len(lane_lines)):
avg_line_lt[t] += lane_lines[t... | 46,267 |
def select_random(nodes: List[DiscoveredNode]) -> Optional[DiscoveredNode]:
"""
Return a random node.
"""
return random.choice(nodes) | 46,268 |
def convert(from_path, ingestor, to_path, egestor, select_only_known_labels, filter_images_without_labels):
"""
Converts between data formats, validating that the converted data matches
`IMAGE_DETECTION_SCHEMA` along the way.
:param from_path: '/path/to/read/from'
:param ingestor: `Ingestor` to rea... | 46,269 |
def timer(method):
"""
Method decorator to capture and print total run time in seconds
:param method: The method or function to time
:return: A function
"""
@wraps(method)
def wrapped(*args, **kw):
timer_start = timeit.default_timer()
result = method(*args, **kw)
time... | 46,270 |
def save_figure(df, filename, output, events, eventtimes):
"""
Takes in a pandas dataframe and saves the graph of the data. Also
labels events on the graph the user defines.
Arguments:
df {pd.DataFrame} -- a dataframe to generate a graph from
filename {str} -- the name to sav... | 46,271 |
def macro_states(macro_df, style, roll_window):
"""
Function to convert macro factors into binary states
Args:
macro_df (pd.DataFrame): contains macro factors data
style (str): specify method used to classify. Accepted values:
'naive'
roll_window (int): specify rolling... | 46,272 |
def test_zsp_gets_right_roles_for_methods():
"""
>>> from AccessControl.unauthorized import Unauthorized
>>> from AccessControl.ZopeSecurityPolicy import ZopeSecurityPolicy
>>> zsp = ZopeSecurityPolicy()
>>> from ExtensionClass import Base
>>> class C(Base):
... def foo(self):
... ... | 46,273 |
def bcd7(num):
"""Converts num to a BCD representation"""
GPIO.output(36, GPIO.HIGH if (num & 0x00000001) > 0 else GPIO.LOW )
GPIO.output(38, GPIO.HIGH if (num & 0x00000002) > 0 else GPIO.LOW )
GPIO.output(40, GPIO.HIGH if (num & 0x00000004) > 0 else GPIO.LOW )
GPIO.output(37, GPIO.HIGH if (num & 0x00000008) ... | 46,274 |
def get_sparsity(lat):
"""Return percentage of nonzero slopes in lat.
Args:
lat (Lattice): instance of Lattice class
"""
# Initialize operators
placeholder_input = torch.tensor([[0., 0]])
op = Operators(lat, placeholder_input)
# convert z, L, H to np.float64 (simplex requires this)
... | 46,275 |
def XYZ_to_Kim2009(
XYZ: ArrayLike,
XYZ_w: ArrayLike,
L_A: FloatingOrArrayLike,
media: MediaParameters_Kim2009 = MEDIA_PARAMETERS_KIM2009["CRT Displays"],
surround: InductionFactors_Kim2009 = VIEWING_CONDITIONS_KIM2009["Average"],
discount_illuminant: Boolean = False,
n_c: Floating = 0.57,
)... | 46,276 |
def load_capsule(path: Union[str, Path],
source_path: Optional[Path] = None,
key: Optional[str] = None,
inference_mode: bool = True) -> BaseCapsule:
"""Load a capsule from the filesystem.
:param path: The path to the capsule file
:param source_path: The pa... | 46,277 |
def geodetic2ecef(lat, lon, alt):
"""Convert geodetic coordinates to ECEF."""
lat, lon = radians(lat), radians(lon)
xi = sqrt(1 - esq * sin(lat))
x = (a / xi + alt) * cos(lat) * cos(lon)
y = (a / xi + alt) * cos(lat) * sin(lon)
z = (a / xi * (1 - esq) + alt) * sin(lat)
return x, y, z | 46,278 |
def processor_group_size(nprocs, number_of_tasks):
"""
Find the number of groups to divide `nprocs` processors into to tackle `number_of_tasks` tasks.
When `number_of_tasks` > `nprocs` the smallest integer multiple of `nprocs` is returned that
equals or exceeds `number_of_tasks` is returned.
When ... | 46,279 |
def skin_base_url(skin, variables):
""" Returns the skin_base_url associated to the skin.
"""
return variables \
.get('skins', {}) \
.get(skin, {}) \
.get('base_url', '') | 46,280 |
def test_output_path_snapshot_local_add_output(tmpdir, version, mode):
"""
Test of output path for local snapshot output created with 'lttng snapshot
add-output'.
"""
nb_loop = 10
datetime_re = "[0-9]{8}-[0-9]{6}"
snapshot_re = "snapshot-1-{}-0".format(datetime_re)
trailing = "{}/ust/{}"... | 46,281 |
def check_is_author_logged_in(author_name: str) -> None:
"""
Check if current user's name equals to item's author.
:param author_name: str item author username.
:raise ClickException: if username and author's name are not equal.
:return: None.
"""
resp = request_api("GET", "/rest-auth/user... | 46,282 |
def load(
name: str,
device: Union[str, torch.device] = 'cuda' if torch.cuda.is_available() else 'cpu',
jit: bool = False,
download_root: str = None,
):
"""Load a CLIP model
Parameters
----------
name : str
A model name listed by `clip.available_models()`, or the path to a model... | 46,283 |
def default_pre_training_callbacks(
logger=default_logger,
with_lr_finder=False,
with_export_augmentations=True,
with_reporting_server=True,
with_profiler=False,
additional_callbacks=None):
"""
Default callbacks to be performed before the fitting of the model
... | 46,284 |
def validate_dumpling(dumpling_json):
"""
Validates a dumpling received from (or about to be sent to) the dumpling
hub. Validation involves ensuring that it's valid JSON and that it includes
a ``metadata.chef`` key.
:param dumpling_json: The dumpling JSON.
:raise: :class:`netdumplings.exception... | 46,285 |
def check_gradient(func,atol=1e-8,rtol=1e-5,quiet=False):
""" Test gradient function with a set of MC photons.
This works with either LCPrimitive or LCTemplate objects.
TODO -- there is trouble with the numerical gradient when
a for the location-related parameters when the finite st... | 46,286 |
def _recurse_to_best_estimate(
lower_bound, upper_bound, num_entities, sample_sizes
):
"""Recursively finds the best estimate of population size by identifying
which half of [lower_bound, upper_bound] contains the best estimate.
Parameters
----------
lower_bound: int
The lower bound... | 46,287 |
def betwix(iterable, start=None, stop=None, inc=False):
""" Extract selected elements from an iterable. But unlike `islice`,
extract based on the element's value instead of its position.
Args:
iterable (iter): The initial sequence
start (str): The fragment to begin with (inclusive)
... | 46,288 |
def map_configuration(config: dict) -> tp.List[MeterReaderNode]: # noqa MC0001
"""
Parsed configuration
:param config: dict from
:return:
"""
# pylint: disable=too-many-locals, too-many-nested-blocks
meter_reader_nodes = []
if 'devices' in config and 'middleware' in config:
try:... | 46,289 |
def places(client, query, location=None, radius=None, language=None,
min_price=None, max_price=None, open_now=False, type=None, region=None,
page_token=None):
"""
Places search.
:param query: The text string on which to search, for example: "restaurant".
:type query: string
:... | 46,290 |
def load_data(_file, pct_split):
"""Load test and train data into a DataFrame
:return pd.DataFrame with ['test'/'train', features]"""
# load train and test data
data = pd.read_csv(_file)
# split into train and test using pct_split
# data_train = ...
# data_test = ...
# concat and labe... | 46,291 |
def sorted_items(d, key=None, reverse=False):
"""Given a dictionary `d` return items: (k1, v1), (k2, v2)... sorted in
ascending order according to key.
:param dict d: dictionary
:param key: optional function remapping key
:param bool reverse: If True return in descending order instead of default as... | 46,292 |
def factorize(eri_full, rank):
""" Do single factorization of the ERI tensor
Args:
eri_full (np.ndarray) - 4D (N x N x N x N) full ERI tensor
rank (int) - number of vectors to retain in ERI rank-reduction procedure
Returns:
eri_rr (np.ndarray) - 4D approximate ERI tensor reconstructed... | 46,293 |
def randint_population(shape, max_value, min_value=0):
"""Generate a random population made of Integers
Args:
(set of ints): shape of the population. Its of the form
(num_chromosomes, chromosome_dim_1, .... chromesome_dim_n)
max_value (int): Maximum value taken by a given gene.
... | 46,294 |
def simplex_creation(
mean_value: np.array, sigma_variation: np.array, rng: RandomNumberGenerator = None
) -> np.array:
"""
Creation of the simplex
@return:
"""
ctrl_par_number = mean_value.shape[0]
##################
# Scale matrix:
# Explain what the scale matrix means here
##... | 46,295 |
def _scale_db(out, data, mask, vmins, vmaxs, scale=1.0, offset=0.0):
# pylint: disable=too-many-arguments
""" decibel data scaling. """
vmins = [0.1*v for v in vmins]
vmaxs = [0.1*v for v in vmaxs]
return _scale_log10(out, data, mask, vmins, vmaxs, scale, offset) | 46,296 |
def make_tree(anime):
"""
Creates anime tree
:param anime: Anime
:return: AnimeTree
"""
tree = AnimeTree(anime)
# queue for BFS
queue = deque()
root = tree.root
queue.appendleft(root)
# set for keeping track of visited anime
visited = {anime}
# BFS downwards
while len(queue) > 0:
current = queue.pop()... | 46,297 |
def draw_bboxes(images, # type: thelper.typedefs.InputType
preds=None, # type: Optional[thelper.typedefs.AnyPredictionType]
bboxes=None, # type: Optional[thelper.typedefs.AnyTargetType]
color_map=None, # type: Optional[thelpe... | 46,298 |
def html_table_from_dict(data, ordering):
"""
>>> ordering = ['administrators', 'key', 'leader', 'project']
>>> data = [ \
{'key': 'DEMO', 'project': 'Demonstration', 'leader': 'leader@example.com', 'administrators': ['admin1@example.com', 'admin2@example.com']}, \
{'key': 'FOO', 'project': ... | 46,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.