content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from pathlib import Path
def openW2wFile(path, mode):
"""
Helper function to read/write all files with same encoding and line endings
:param str|Path path: full path to file
:param str mode: open mode: 'r' - read, 'w' - write, 'a' - append
:return TextIO:
"""
if isinstance(path, Path):
... | 6e42a26d2262ed10d15e19292e7b32fffd14aeb8 | 3,600,339 |
def get_temperature ( year=None, latitude=None, longitude=None, \
fname="/data/geospatial_20/ucfajlg/meteo/temp_2m.tif" ):
"""This function grabs the temperature for a given year (or all of them if
set ``year`` is set to ``None``, for the whole globe or for a given location.
"""
# These are fact... | 576ce3672c1835a140c7cac5ef6e43ab57f165a7 | 3,600,340 |
from typing import Callable
from re import T
def capture_action(bound_method: Callable[P, T]) -> Callable[P, T]:
"""A decorator for `Pet`'s methods that captures actions when in battle so
that the battle manager can control ability cast order."""
@wraps(bound_method)
def _impl(self, *args: P.args, **k... | 4ca3aebd70cddd2d030081fa139d2ef4897e4664 | 3,600,341 |
from GPy.models import GPClassification, GPRegression, SparseGPClassification, SparseGPRegression
def make_model_builder(Y, num_inducing=None, name=None, sparse=False):
"""
This is a helper for creating several models. It
returns a function which takes data and makes a GPy
model out of it, with the sp... | 797734a99a9fd4a8122137db05bbe7e4c5ae913e | 3,600,342 |
def th_nearest_interp3d(input, coords):
"""
2d nearest neighbor interpolation th.Tensor
"""
# take clamp of coords so they're in the image bounds
coords[:,0] = th.clamp(coords[:,0], 0, input.size(1)-1).round()
coords[:,1] = th.clamp(coords[:,1], 0, input.size(2)-1).round()
coords[:,2] = th.c... | 44b3d3a1b69aad75c8818605e596eea090d1decc | 3,600,343 |
def ugly_numbers(n: int) -> int:
"""
Returns the nth ugly number.
>>> ugly_numbers(100)
1536
>>> ugly_numbers(0)
1
>>> ugly_numbers(20)
36
>>> ugly_numbers(-5)
1
>>> ugly_numbers(-5.5)
Traceback (most recent call last):
...
TypeError: 'float' object cannot be ... | 69c92c8eea98b6d8d869f0725c49d6b164d24480 | 3,600,344 |
def populate_single_page(args, count, images, pagenos):
""" Return a generator that scales all supplied images to fit on fixed number of pages."""
def _try_it():
builder = make_builder(args, images)
page_count, incomplete = builder.get_page_count(pagenos)
return (page_count, incomplete)
... | dd58870a708b3013b44ef6d2078358a7635ef6f5 | 3,600,345 |
from typing import Any
from typing import Callable
from typing import Pattern
def pattern_from_transform(
step_structure: tree.Structure[Any],
transform: Callable[[ReferenceStep], Pattern]) -> Pattern:
"""Creates a pattern by invoking a transform from step to output structures.
```python
def my_transf... | 6121f5dd5930a2aa514e468f9619d0d83c244d31 | 3,600,346 |
def update_grid(
old_grid: Grid, acceptable: str = ".L#", min_occupied_to_switch: int = 4
) -> Grid:
"""Update the grid"""
new_grid = [""] * len(old_grid)
for i, row in enumerate(old_grid):
for j, seat in enumerate(row):
occupied = get_num_occupied(i, j, old_grid, acceptable)
... | cbee446da34b3c3544a558b740a29ed7760efa90 | 3,600,347 |
import torch
def prepare_device(n_gpu: int, keep_reproducibility=False):
"""
Choose to use CPU or GPU depend on the value of "n_gpu".
Args:
n_gpu(int): the number of GPUs used in the experiment. if n_gpu == 0, use CPU; if n_gpu >= 1, use GPU.
keep_reproducibility (bool): if we need to cons... | ed67768949a842b135798137d01dd40e50fdf47f | 3,600,348 |
def send_self(use_proxy):
"""
A decorator which sends a generator a reference to itself.
The first yield statement will emit the reference.
Useful for creating generators that can leverage callback-based functions
in a linear style, by passing their 'send' method as callbacks.
Note that by def... | 8e64c875f7fcc1132d2a01d08a2fc67ef1eff25b | 3,600,349 |
from typing import Optional
from typing import List
from typing import Dict
def get_request_preview_queries(
*,
db: Session = Depends(deps.get_db),
dataset_keys: Optional[List[str]] = Body(None),
) -> List[DryRunDatasetResponse]:
"""Returns dry run queries given a list of dataset ids"""
dataset_co... | 00a5c6a1a5157fcf1f33b286eb7a6154d893fefb | 3,600,350 |
def get_cz_exp(q0, q1, a):
"""Exponent of entangling CZ building_block."""
return linear_algebra.Graph(linear_algebra.cond_rotate_z(exponent=a)(q0, q1)) | d9fcd6775d740c1c4a8f54cfcb357250ac05b87e | 3,600,351 |
def get_event_by_id(event_id):
"""
:Route: /id/<event_id>
:Description: Returns GeoJSON of singular event matching event ID
:param str event_id: ID string to search database for exact match
"""
search_dict = {'id': event_id}
return event_collector.find_events_in_database(search_dict, True... | 18c7dcc995b40f5c7c27ab3f24629ffbb4cdbd95 | 3,600,352 |
from typing import Iterable
def make_conda_description(summary: str, conda_channels: Iterable[str] = ()) -> str:
"""
Create a description for the Conda package from its summary and a list of channels required to install it.
The description will look like::
This is my fancy Conda package. Hope you like it 😉.
... | b275e3bfcb67da33a4c7a34d7801a0cb4144527a | 3,600,354 |
import hashlib
def sha1(text):
"""
Calculate the SHA1 fingerprint of text.
:param text: The text to fingerprint (a string).
:returns: The fingerprint of the text (a string).
"""
context = hashlib.sha1()
context.update(text.encode('utf-8'))
return context.hexdigest() | 43473e9cc22b6cbe072170244b56b831f0cc88ee | 3,600,355 |
def picks_pair_to_idx(raw, sd_pairs, on_missing='error'):
"""
Return a list of picks for specified source detector pairs.
If multiple channel have the same source detector pair,
for example if there are multiple wavelengths or chromaphore, then
all channels matching the requested sources and detect... | f9e69eb4fde1e84633ef85f6c9d1d2473554a0c1 | 3,600,356 |
import time
import logging
import requests
def post_to_slack(webhook, text=" ", attachment=None, payload={}):
"""Post a message to the slack channel."""
global RETRY_AFTER
global RATE_LIMITED
if time.time() <= RETRY_AFTER:
logging.error("Slack: HTTP 429 Too Many Requests.")
return Fal... | ecd592f16ec3ddac449c4e245384bc419777c67f | 3,600,357 |
def get_xy_subset(x, y, xmin, xmax):
"""Get a subset of values from two array given xmin and xmax.
The array must be sorted in ascending or descending order.
Parameters
----------
x: np.ndarray
The first array to get the subset from, set by xmin and xmax.
y: np.ndarray
The seco... | 6dc076d570496ee651234fd98abb7cdbadf086a3 | 3,600,359 |
from typing import Iterable
def new(convention_spec: str,
user_paths: Iterable[str] = None):
"""Returns a new registry based on the `convention_spec` and `user_paths`.
The registry contains all the environments generated by the named convention
when passed the `user_paths`.
The `convention_spec` is ... | adf283f169f8891a0b935416215e332d6a6c0741 | 3,600,360 |
def _binned_haplotype_matrix_from_ts(
ts: tskit.TreeSequence,
*,
num_samples: int,
num_loci: int,
maf_thresh: int,
) -> np.ndarray:
"""
Non-vector implementation of BinnedHaplotypeMatrix.from_ts().
Assumes the data are phased.
"""
assert ts.num_samples == num_samples
assert ... | b9ca7d9227719cc306522971be05c9302d8b4e0e | 3,600,361 |
import logging
import pprint
def parse_cbgp(srt, name, adj=None):
"""
Parse the routing table received from C-BGP
:param srt: Source routing table
:param name: Name of the router
:param adj: Adjacency information
:return: Routing table as pandas dataframe
"""
logger = logging.getLogger... | 05d7770b288a64f35727bdabcaf8bc5ea035e4be | 3,600,362 |
def query_handler():
"""Build query_handler test fixture."""
class QueryGetter:
def __init__(self):
self.query_handler = QueryHandler()
def search(self, query_str, keyed=False, incl='', excl=''):
return self.query_handler.search(query_str=query_str, keyed=keyed,
... | 7c6dae48f6ebb5f212a8164fda15d04c84aec9b9 | 3,600,363 |
def create_scatter_indices(updates, dim2known_indices):
"""Create scatter indices."""
updates_expanded = tf.expand_dims(updates, -1) # [Ro, S, 1] or [Ro, S, C, 1]
target_shape = tf.shape(updates_expanded)
n_dims = len(tf.shape(updates)) # 2 or 3
dim_indices_list = []
for dim in range(n_dims):
indices... | d00b8611c64dd16e42294868c829bebd2cd7e854 | 3,600,364 |
import json
def add_deduplicated(triple, list_json_triples):
"""Adds a triple to a list, only if it is not there. Return list and bool indicating whether an addition was made"""
addition = False
sorted_triple = dict(sorted(triple.items()))
triple_as_json = json.dumps(triple_to_json(triple))
if t... | 2cd46e85689a5c6bd3d2c88a7ea116c76a205e7c | 3,600,365 |
def get_T_strain_2d(theta):
"""
returns a 2d strain transformation matrix that transforms a global strain vector to a strain vector in
fiber coordinates with a normal orientation perpendicular to the fiber orientation.
Theta defines the angle to the perpendicular orientation in the laminate plane.
... | afdbde7f5563419da406350ed373fc298dbd2fb7 | 3,600,367 |
import re
def is_valid_url(value):
"""Return whether or not given value is a valid URL.
Args:
value(str): URL address string to validate
"""
regex = re.compile(
r'^(?:http|ftp)s?://'
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r... | 056c79091df6ca10e67071e048e023a88876305c | 3,600,368 |
from typing import OrderedDict
def _make_intent_from_args(args):
"""
Create an intent type for a given set of arguments.
:param args: a dict with keys as the names of arguments and values as
:class:`argument`s.
:returns: A new type that can hold all of the data to call a function that
... | df484850916b96f183e0be862960faf6526074c8 | 3,600,369 |
def message(request, message, to=None, sender=None, action=None,
methods='POST', media=None, status_callback=None):
"""
See: https://www.twilio.com/docs/api/twiml/sms/message
Usage::
# urls.py
urlpatterns = patterns('',
# ...
url(r'^sms/$', 'django_twili... | 9bc918af2eb65047fb46c75f28a8af2ea27656f5 | 3,600,370 |
from typing import Dict
def _sop_common_handler(
event: Event
) -> Dict[UID, "SOPClassCommonExtendedNegotiation"]:
"""Default handler for when one or more SOP Class Common Extended
Negotiation items are included in the association request.
See _handlers.doc_handle_sop_common for detailed documentatio... | a4c5afc9c11ea27feb44360ec89078e3f02c354c | 3,600,371 |
def insert_node(graph, node):
"""
"""
if 'properties' not in node:
node['properties'] = {}
if 'name' in node:
node['properties']['name'] = node['name']
if 'hostname' in node:
node['properties']['hostname'] = node['hostname']
node_g = util.create_object(graph, node['type'... | 1985c7b57f0c21c7003e7b2ba9b045cf46b3d187 | 3,600,372 |
def ifirst_is_not(l, v):
"""
Return index of first item in list which is not the specified value.
If the list is empty or if all items are the specified value, raise
a ValueError exception.
Parameters
----------
l : sequence
The list of elements to be inspected.
v : object
... | fef5ae1a512772cf4df75a294057330280047f88 | 3,600,374 |
def group_access_check(message):
"""Access to function only from certain chat"""
return message.chat.id in allowed_chats | ee54c3f1642406d8f10076ceb19c3d76957a011b | 3,600,376 |
import requests
def get_data(ticker, start_date=None, end_date=None, index_as_date=True, interval="1d"):
"""Downloads historical stock price data into a pandas data frame. Interval
must be "1d", "1wk", "1mo", or "1m" for daily, weekly, monthly, or minute data.
Intraday minute data is limited to 7 days.
... | 6627e1ad66a368aa7b9f1c843fcc006a99f1de46 | 3,600,377 |
def get_calls(mock_observer_func):
"""Given a mock IPluginObserver method, returns the plugins that caused its
methods to be called, so basically a list of plugins that
loaded/unloaded"""
return [call_tuple[0][0].name for call_tuple in mock_observer_func.calls] | 41360429df5e71da47946f75f8207f985959528f | 3,600,378 |
def format_date_ihme(date_in):
"""
Formats "m/d/yyy" to "yyyymmdd"
"""
try:
month, day, year = date_in.split('/')
return '%s%02i%02i' % (year, int(month), int(day))
except:
return date_in.replace('-', '') | 166739b2245833c6dddf35fcde87433648697277 | 3,600,379 |
def pi(num):
"""weird way to multiply p by a number"""
return np.pi * num | 99877b47ab565ea529db99a811df3ed57670f22e | 3,600,380 |
def days_to_weekday(wkdy_src: int, wkdy_dest: int) -> int:
"""
Calculate the days to a specific destination weekday.
Notes
-----
Weekday enumeration based on
the `datetime` standard library.
Parameters
----------
wkdy_src : int
Source :class:`~scheduler.util.Weekday` intege... | 3fd47aa796bf71d726f25d7b9e3d2c0b9a986ac4 | 3,600,381 |
def _cdot(left, right):
"""
Function corresponding to "|" operation.
Parameters
----------
left, right : `astropy.modeling.Model` or ndarray
If input is of an array, it is the output of `coord_matrix`.
Returns
-------
result : ndarray
Result from this operation.
"""... | 1e251721b0d5968de737434ee18fb937a69f6a41 | 3,600,382 |
async def get_instances(aws_access_key_id, aws_secret_access_key, regions):
"""Gets a list of all instances on AWS for a list of regions."""
instances = []
session = aiobotocore.get_session()
for region in regions:
async with session.create_client("ec2",
... | e098762dccc685727b1369de5e27c4114643238e | 3,600,384 |
from typing import Union
import httpx
def get_client(
proxies: Union[str, dict] = None, verify: bool = False, headers: dict = None
) -> httpx.Client:
"""Gen and cache a httpx.Client.
Args:
proxies: setup and persistant
"""
# url = "https://translate.google.cn"
if headers is None:
... | 519868043162c5da9e0bb3fd579e600aecb13f4d | 3,600,385 |
def calculate_vertical_speed(altitude, time, *, min_time=0.5):
"""
Calculate the vertical speed in feet per minute given the altitude and time.
Parameters
----------
altitude: float
The altitude [feet].
time: float
The time [Seconds].
min_time: float
The minimum ti... | 1370926d8d6494f58431f1067fb07df3690fe0e2 | 3,600,386 |
def absorption_onset_shift(sp1, sp2, intensity_threshold):
"""
Shift spectrum 2 with respect to spectrum 1 using the difference between
two spectra's onset of absorption.
The onset is determined by ascertaining the lowest incident energy at which
the spectra's absorption intensity reaches the 'inten... | 15c06104b051592d404571d8a45816b955a1491d | 3,600,387 |
def persian_letter(value, **options):
"""
normalize persian letters.
:param str value: value to be normalized.
:keyword bool strip: strip spaces from both ends of value.
defaults to True if not provided.
:keyword bool normalize_none: specifies that if given value is None,... | c2e13c86fde76e3e12cc4c89e74e018ab40ae318 | 3,600,389 |
def patient_ECG_trace_list(MRI_number):
"""Receive the 'GET' request for getting a selected patient's timestamps
of ECG images(except the latest one). The list contains strings as elements,
each of which indicates the info of timestamp for every ECG image
The 'GET' request is send by a client, targetin... | 08d8fc463072a3973bad407abe9e3cbd32469d70 | 3,600,390 |
def remove_deleted(loc_id):
"""
Delete permanently record of given ID from safe_deleted list.
:param loc_id: ID of the record to restore
:return: 200 on success, 404 if not found
"""
location = Geolocation.query.filter(Geolocation.visible == 0).filter_by(
id=loc_id).one_o... | 5a44ef93913a0f767fe26f791367bdc2e2ca2566 | 3,600,391 |
import time
def add_delete_sampler(kernel, s_init, nb_it_max=10, T_max=10):
""" MCMC sampler for generic DPP(kernel), it performs local moves by removing/adding one element at a time.
:param kernel:
Kernel martrix
:type kernel:
array_type
:param s_init:
Initial sample.
:type s_init:
list
:param nb_it... | 952419fea389377827e39c978f42a7edd53cac67 | 3,600,392 |
from mmdet.models.dense_heads import YOLOV3Head
def get_yolov3_head_model():
"""yolov3 Head Config."""
test_cfg = mmcv.Config(
dict(
nms_pre=1000,
min_bbox_size=0,
score_thr=0.05,
conf_thr=0.005,
nms=dict(type='nms', iou_threshold=0.45),
... | 464901b8d1a57339edee1fc2270b91fe18c68996 | 3,600,393 |
def reverse_map(dict_of_sets):
"""Reverse a map of one-to-many.
So the map::
{
'A': {'B', 'C'},
'B': {'C'},
}
becomes
{
'B': {'A'},
'C': {'A', 'B'},
}
Args:
dict_of_sets (dict[set]): A dictionary of sets, mapping
one value ... | 87b0679a0ebd00c3dbdcafc89fd2644b21ecbc85 | 3,600,394 |
def get_class_name(env, obj):
"""
Return the class name of an object.
:param env: the JNIEnv environment
:param obj: a Java object instance
:return: a Python string name of the Java object class
"""
class1 = env.GetObjectClass(obj)
mid_get_class = env.GetMethodID(class1, 'getClass', '()... | dfaa850c0cd88473f3eb42d029d6edbf699498e9 | 3,600,396 |
def angle_between(v1, v2):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
angle_between((1, 0, 0), (0, 1, 0))
1.5707963267948966
angle_between((1, 0, 0), (1, 0, 0))
0.0
angle_between((1, 0, 0), (-1, 0, 0))
3.141592653589793
... | 9aa2f3766c9be92d69d06ea2140583d15df27b17 | 3,600,397 |
from typing import List
import itertools
def _enumerate_all_from_stabilizer_bases(
stabilizer_basis: List[cirq.DensePauliString], n_qubits: int):
"""
Given a stabilizer basis, creates the exhaustive list of Pauli states that
are spanned by the basis.
Args:
stabilizer_basis: A list of ... | bb08c1dbeaa00db6fc3bb5c7dcbc3bff863a1d29 | 3,600,398 |
def get_iemocap_emotion(session_file_name, turn_name):
"""gets the assigned evaluated iemocap emotion for a given turn name in a given session dialogue"""
r = open(session_file_name, 'r')
lines = r.readlines()
for e, l in enumerate(lines):
emo_info = l.split('\t')
if len(emo_info) == 4 ... | e82576633632e0f3cffd8d4187607e955dade594 | 3,600,399 |
def GetTevType(tev):
"""
Return the type of the specified event (TEV_... constants)
@param tev: event number
"""
return idaapi.get_tev_type(tev) | bad1e7696297629563eed7c64b76ce6789248d0a | 3,600,400 |
def create_hparams(hparams=None):
"""Create model hyperparameters. Parse nondefault from given string."""
hparams = Hparams()
return hparams | ee6c3132a9554ea94da41d4d4fb9b95e6b97999c | 3,600,401 |
def extract_categorical_cols_hot(df, cols):
"""Create HOT encoded feature columns for the dataframe, based on the defined categorical columns."""
all_col_features = []
for col in cols:
print(f"Now extracting features from column: '{col}'.")
col_features = pd.get_dummies(df[col], prefix=col, ... | b541bd5a80a4fae2fb976280cfb990f01fc3a251 | 3,600,402 |
import functools
def expand_args(function):
"""Expand arguments passed inside the CallContext object.
Converts internal method signature 'method(ctx)' to whatever
is appropriate to the client code.
Args:
function: Async function expecting CallContext as a last argument.
Returns:
A... | 72e7de46684b2c02d958fad7f9ded71e653bb811 | 3,600,403 |
from app import create_app
import logging
def export(context, output_format='json', quiet=False):
"""
Export swagger.json content
"""
# set logging level to ERROR to avoid [INFO] messages in result
logging.getLogger().setLevel(logging.ERROR)
app = create_app(flask_config_name='testing')
... | 7ee8683ea17895213d38345815adda5b568c700e | 3,600,404 |
def derivative_of_binary_cross_entropy_loss_function(y_predicted, y_true):
"""
Use the derivative of the binary cross entropy (BCE) loss function.
Parameters
----------
y_predicted : ndarray
The predicted output of the model.
y_true : ndarray
The actual output value.
Return... | 7803c852f794ab9eae165c639bfb7a04cd0c1028 | 3,600,405 |
def AUC(answers, scores):
"""
Compute the `AUC <https://en.wikipedia.org/wiki/Area_under_the_curve_(pharmacokinetics)>`_.
@param answers expected answers 0 (false), 1 (true)
@param scores score obtained for class 1
@return number
"""
ab = list(zip(answers,... | 477cdf2a7b51352dd728465c883dae9cb4ab6e9a | 3,600,406 |
def search_geojson_gui(m=None):
"""Generates a tool GUI template using ipywidgets.
Args:
m (leafmap.Map, optional): The leaflet Map object. Defaults to None.
Returns:
ipywidgets: The tool GUI widget.
"""
widget_width = "250px"
padding = "0px 0px 0px 5px" # upper, right, bottom... | 366db5020f55ad51d2803a61991343e30d781d86 | 3,600,407 |
def plot_gradient_descent_path(perceptron, X, y):
"""Plot the gradient descent path of
a trained perceptron.
Args:
perceptron ([class]): trained perceptron. Expects
instance of perceptron.Perceptron.
X ([ndarray]): the data (instaces x features)
y ([array]): labels for ... | 4a2deb99e4475d33b785b81b9894dbc88f8e4798 | 3,600,408 |
import six
import types
import functools
def skip(reason):
"""
Defines a decorator to unconditionally skip a test. Called by conditional
skip wrappers to skip tests that require optional dependencies.
This is needed because nose doesn't respect unittest skip_if decorators.
Based on: https://stack... | 5862e8122cdad2566ba2f925f37b64c7593cab82 | 3,600,409 |
def factorial(number: int) -> int:
"""
Calculating factorial of a number using
prime decomposition method
"""
prime: list = [True] * (number + 1)
result: int = 1
for i in range (2, number + 1):
if prime[i]:
j: int = 2 * i
while j <= number:
p... | 2d6a85daa1b324fe419c3e5aecfbfc8373cffdcf | 3,600,410 |
def analytical_sol(x):
""" function to draw analytical solution """
return -1 / 300 * np.exp(-x) | 4a3daab1cd15b769d4556a1482e50746bb5ac659 | 3,600,411 |
from typing import Optional
from typing import Dict
from typing import Any
from typing import List
def process_args(
*,
dataset: Optional[Dataset] = None,
sibling: Optional[str] = None,
url: Optional[str] = None,
endpoint: Optional[str] = None,
) -> Dict[str, Any]:
"""Process common arguments,... | cedd78169920f06a3dce0bd801eec0ff9604a0ed | 3,600,412 |
from typing import Any
def read_search_terms(
db: Session = Depends(deps.get_db), skip: int = 0, limit: int = 100
) -> Any:
"""
Retrieve search terms.
"""
search_terms = crud.search_term.get_multi(db=db, skip=skip, limit=limit)
return search_terms | aba424374f19d48722a168770dc616b3dceb1d65 | 3,600,413 |
def create_da_bry_std(filename, eta_rho=10, xi_rho=10, s_rho=1, bry=4,
reftime=default_epoch, clobber=False, cdl=None,
title="My BRY STD"):
"""
Create a boundaries standard deviation file
Parameters
----------
filename : string
name and path of fi... | b884e2eb4a5ec35b8c1a57fa10c086fdf9fb8127 | 3,600,414 |
def cluster_jaxpr_by_cost(jaxpr: Jaxpr, layer_num: int, eps: float, costs,
cost_criteria):
"""Clusters the jaxpr by cost."""
layer_num = int(layer_num)
length = len(jaxpr.eqns)
non_trivial, input_sizes, compute_costs = costs
compute_costs_avg = compute_costs.sum() / layer_n... | 6104ddd251e34b0e9ad847292e9b6d597994c082 | 3,600,415 |
def MPI_ApplicationsTeam(mintime = 5, maxtime = 20, cap = 60):
"""
Returns a costOfLaborValue object suitable to attach to a sim or other event
Time is in hours
"""
timeDist = LogNormalValue(maxtime, mintime, cap)
costDist = LogNormalValue(240, 115, 390)
team = costOfLaborValue("Applications... | 2a1bcf41a9f91a5d42eb69ab5e60cc2061a137b9 | 3,600,416 |
def KK_RC59(w, Rs, R_values, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
return (
Rs
+ (R_values[0] / (1 + w * 1j * t_values[0]))
+ (R_values[1] / (1 + w * 1j * t_values[1]))
+ (R_values[2] / (... | 45e91818fa256f127af237cb9374c4fa8d5ad03c | 3,600,418 |
def flirtMatrixToSform(flirtMat, srcImage, refImage):
"""Converts the given ``FLIRT`` transformation matrix into a
transformation from the source image voxel coordinate system to
the reference image world coordinate system.
To construct a transformation from source image voxel coordinates into
refe... | d6cc963154dff8e334d67102bbcd3594776054db | 3,600,419 |
import torch
def device_count():
"""Returns the number of GPUs available."""
if is_available():
return torch._C._cuda_getDeviceCount()
else:
return 0 | 8aab80cb1da63f4726fc23cea685a82a0f7652af | 3,600,420 |
def api_failed(response, endpoint, exit_on_error=True):
"""
Check if api request failed
Can raise exception
"""
if 200 <= response.status_code < 300:
return False
if exit_on_error:
raise Exception("Status code {0} calling {1}".format(
response.status_code, endpoint... | 6a9d803444c4be09806eb6c5b588e1e04062c431 | 3,600,421 |
def select_field(X, cols=None, single_dimension=False):
"""
Select columns from a pandas DataFrame
Args:
X (pandas DataFrame): input data
cols (array-like): list of columns to select
single_dimension (bool): reduce data to
one dimension if only one column
i... | 4f80af3621af5e0c622f2c880e88d95a6e93034e | 3,600,422 |
from pathlib import Path
from typing import Optional
from typing import Iterable
from typing import Callable
def import_images(
*,
input_directory: Path,
origin: Optional[RawImageUploadSession] = None,
builders: Optional[Iterable[Callable]] = None,
recurse_subdirectories: bool = True,
) -> Importe... | eaa270f1cf479fd7b60628d8b50c2057d1dd6b8e | 3,600,423 |
from pydantic import BaseModel # noqa: E0611
def get_model_reference(
model_name: str
) -> BaseModel:
"""Return a reference to the class of a chosen model.
Note that this is different from get_model(), which returns an instance of a model. The reference, returned by this
function, is a class before ... | 6505952b32f55af087cdb98784fa14ab244720e8 | 3,600,424 |
from typing import Optional
def get_subnet(subnet_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSubnetResult:
"""
This data source provides details about a specific Subnet resource in Oracle Cloud Infrastructure Core service.
Gets the specified subne... | b23a29f521a03f25bc423edc92b8ebdd0778a9bf | 3,600,425 |
import time
async def html(request):
"""Return HTML content and a custom header."""
content = "<b>HTML OK</b>"
headers = {'x-time': f"{time.time()}"}
return HttpResponse(content, headers=headers) | fd7cc43333db94dd25d2d9cefeac74b2cbe86db6 | 3,600,426 |
def KaimingUniformInitializer(out_dim=-1, in_dim=-2, param=0.):
"""Returns an initializer for random uniform Kaiming-scaled coefficients."""
return ScaledInitializer(
out_dim, in_dim, 2.0 / jnp.sqrt(1 + param**2), 'fan_in', 'uniform') | d991d0300caec11684df44a2ccb3aec160138c80 | 3,600,427 |
def reactions_block(rxn_param_dct, comments=None):
""" Writes the reaction block of the mechanism file
:param rxn_param_dct: dct containing the reaction parameters
:type rxn_param_dct: dct {rxn:params}
:return total_rxn_str: str containing the reaction block
:rtype: str
"""
... | d7a3a4cc7d5857a063712e69fc0fe17e62aa7e30 | 3,600,428 |
def run_fdr_ranking_labeled(
scores: pd.Series,
target: pd.Series,
decoy_ratio: float,
rule_of_succession: bool,
monotonic: bool,
):
"""Runs an FDR ranking for a list of scores with a separate target/decoy flag.
Returns calculated FDRs for both targets and decoys."""
fdr_map = score_to_f... | 638c57337615048725d27173985926a9738b018c | 3,600,429 |
import logging
def compute_mean_average_precision(logits, labels, suffix='',
suffix_separator='_',
return_per_class_ap=False):
"""Computes mean average precision for multi-label classification.
Args:
logits: Numpy array of shape [num_examp... | 637be28b7042dcae8f2a65b5afc00e92136c649c | 3,600,430 |
import json
def transfer_json_string_to_dict(json_str):
"""把可能是json的字符串转为json字典"""
try:
if isinstance(json_str, bytes):
# bytes转str
json_str = json_str.decode('utf-8')
# str转dict
return json.loads(json_str)
elif isinstance(json_str, str):
... | fde4335ff321592bd3141bd9f6017296a14c449d | 3,600,431 |
def count_non_variant(genotypes):
"""Count variants with no non-reference alleles.
Parameters
----------
genotypes : array_like
An array of shape (n_variants, n_samples, ploidy) where each
element of the array is an integer corresponding to an allele index
(-1 = missing, 0 = re... | 2f6c2ea4b570f7219c6d6d1778d12ac68c520724 | 3,600,433 |
import json
def set_timeline_item_pype_tag(timeline_item, data=None):
"""
Set openpype track item tag to input timeline_item.
Attributes:
trackItem (resolve.TimelineItem): resolve api object
Returns:
dict: json loaded data
"""
data = data or dict()
# get available openpy... | d014da05f7b0082f99f2ac8c2a92b8c75aad02b5 | 3,600,434 |
import json
def GetRecentCompletedBuilds(master_name, builder_name, http_client):
"""Returns a sorted list of recent completed builds for the given builder.
Sorted by completed time, newer builds at beginning of the returned list.
"""
data = {
'name': master_name
}
response_json = DownloadJsonData(_M... | 6479eb57c8d3f0ad5e95eee2f572c273c62cf091 | 3,600,435 |
def gce(cred):
"""
:returns: list
[{'region': str, 'timestamp': int, 'nodes': list}]
"""
result = list()
project_id = cryptotool.decrypt_scalr(app.crypto_key, cred['project_id'])
key = _gce_key(cred)
conn, http = _gce_conn(cred, key=key)
request = conn.zones().list(project=proje... | 67355a9d79c1a41f8a62df0a494aae8e2dc022e9 | 3,600,436 |
from re import A
def findElemArray2D(x, arr2d):
"""
:param x: a scalar
:param arr2d: a 2-dimensional numpy ndarray or matrix
Returns a tuple of arrays (rVec, cVec), where the corresponding elements in
each are the rows and cols where arr2d[r,c] == x.
Returns [] if x not in arr2d. \n
Exam... | 991abbf4ecd511878dd85a6d9318922468d74426 | 3,600,437 |
def calculate_unc_in_ext_coeff(Nsamples):
"""Calculates the uncertainty in each extinction coefficient given the uncertainty in x parameter (Section 5.3 of Schlafly et al. 2016)"""
arr = np.zeros((Nsamples, 13))
for i, x in enumerate(0.02*np.random.randn(Nsamples)):
arr[i, :] = calculate_ext_coeffs(... | f8154c3ba0bdffc93e233bf54863eab568ad8bce | 3,600,438 |
def get_pathless_file_size(data_file):
"""
Takes an open file-like object, gets its end location (in bytes),
and returns it as a measure of the file size.
Traditionally, one would use a systems-call to get the size
of a file (using the `os` module). But `TemporaryFileWrapper`s
do not feature a ... | df1edfa6cb7b97c6abbdb2252b7dd8d505931768 | 3,600,439 |
def find_xss_script(url, **kwargs):
"""
parse the URL for the given XSS payload
"""
data = urlparse.urlparse(url)
payload_parser = {"path": 2, "query": 4, "fragment": 5}
if data[payload_parser["fragment"]] is not "" or None:
retval = "{}{}".format(
data[payload_parser["query"... | fd8a54a7f6ba6cd3a0e35caec481cfc12e512026 | 3,600,441 |
import collections
def _make_repolist(c, path):
"""turn the repo log into a history
input: pathname to the repository
output: dictionary containing the history
"""
## logging.info('processing {}'.format(item))
with c.cd(path):
result = c.run('hg log -v', hide=True)
data = resu... | 5c3d27bcfd52f8b0656d5bf770ce83b0fcbdf5d0 | 3,600,442 |
def EspDB():
"""Return an instance of `SNPDB` configured to search the Exome
Sequencing Project's(ESP) database"""
return SNPDB('ESP') | 3691240f2dc8cdc16fa31e70c501d354c05c2198 | 3,600,443 |
def svn_proplist_invoke_receiver2(*args):
"""svn_proplist_invoke_receiver2(svn_proplist_receiver2_t _obj, void * baton, char const * path, apr_hash_t prop_hash, apr_array_header_t inherited_props, apr_pool_t scratch_pool) -> svn_error_t"""
return _client.svn_proplist_invoke_receiver2(*args) | 98aca1a3d47be403c36da410387bcd2b9f9668b3 | 3,600,445 |
def fizz_buzz_one( start, end ):
""" Note: This method returns a long string not a list. """
fizzbuzz = ''
# range is NOT inclusive of the 2nd number, so add 1 to include it.
# range(1,4) > 1,2,3. range(1, 4 + 1) > 1,2,3,4.
for i in range(start,end+1):
if i%3 == 0:
fizzbuzz += "f... | 9000ed93629bff15a74171565f562eee29814dd0 | 3,600,446 |
import torch
def test_CenteredParameter_fit():
"""Tests fitting a model with probflow.parameters.CenteredParameter"""
class MyModel(Model):
def __init__(self, di, do):
self.w = CenteredParameter([di, do], center_by="column")
def __call__(self, x):
return Bernoulli(tor... | 5ac9be9dc00e3ffce5743308431fa041a3dfaeaa | 3,600,447 |
def max_coupling(v1_probs, v2_probs):
"""max_coupling as described in Jacob's chapter 3 notes.
"""
ncolors = len(v1_probs)
# compute overlap pmf
overlap = np.min([v1_probs, v2_probs], axis=0)
overlap_size = np.sum(overlap)
overlap_size = np.min([1.0, overlap_size]) # protect from roundi... | e2a40ca74602dc80e342613794de309d82b4aaed | 3,600,448 |
async def revision_logs(request: Request):
"""Retrieve the revision log as a JSONL stream.
It contains the revision timestamp and content, and the associated
Tatoeba sentence ids.
"""
current_user = request.session.get('id', 1)
if current_user == 1:
return JSONResponse(
dict... | 725d72b0e46a8c2d5c788d35342c972d9eaab0bf | 3,600,449 |
import logging
import pprint
def apply_change_list(exploration_id, change_list):
"""Applies a changelist to a pristine exploration and returns the result.
Each entry in change_list is a dict that represents an ExplorationChange
object.
Returns:
the resulting exploration domain object.
"""
... | 8fd43550ac0f50111ff467bc079c279027db055e | 3,600,450 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.