content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def compute_box_3d_tracker(tracker, P):
""" Takes an tracker object and a projection matrix (P) and projects the 3d
bounding box into the image plane.
Returns:
corners_2d: (8,2) array in left image coord.
corners_3d: (8,3) array in in rect camera coord.
"""
# compute ... | daceaf3740006805216b8e38d3093c83ceb8a89b | 39,224 |
def lang_exists(cursor, lang):
"""Checks if language exists for db"""
query = "SELECT lanname FROM pg_language WHERE lanname = %(lang)s"
cursor.execute(query, {'lang': lang})
return cursor.rowcount > 0 | 085ed58920f3b13464a0f332d695ff39336cda8d | 39,225 |
def create_init(fields, # type: Iterable[Field]
user_init_fun=None, # type: Callable[[...], Any]
inject_fields=False, # type: bool
user_init_args_before=True # type: bool
):
"""
Creates the new init function that... | 1ced8f4dd528fd71ff3275d0c180f7ac6d7d05d6 | 39,226 |
def search_comments_for_terms(terms, comments):
"""
Adds Boolean columns indicating whether a search term was located
Args:
terms {tuple} : a collection of unique search terms
comments {DataFrame} : a Pandas DataFrame with comment data
Returns:
A Pandas DataFrame with the update... | 0654cf1430102e774e03f20939316a2fc38ad399 | 39,227 |
import requests
def update_node_data_join():
"""
This is a route for ALL NODES.
Whenever the PREVIOUS NODE departs from the ring,
all of its data are transfered to us through this route.
"""
start_id = request.form['start_id']
k = int(request.form['k'])
prev_storage = {}
to_be_dele... | 0fa96c05d67f1f87eaf85f6d8aa993fdf072b3ab | 39,229 |
def isMessageBody(line: str) -> bool:
"""
Returns True if line has more than just whitepsace and unempty or is a comment (contains #)
"""
return not (line.isspace() or line.lstrip().startswith('#')) | 990ae3ff01f794a6c8d4d45ecb766a763c51dff8 | 39,231 |
def getHistoricalUmuxChartData(allProjectSnapshots):
"""
UMUX history line chart on project detail page.
Loop thru quarters starting at first meaningful quarter 2 years or less ago.
If a quarter has no (meaningful) snapshot, it gets an empty x-axis tick.
Return: {obj} Chart data with xaxis quarters, scores, and ta... | 0660780b9d5b4d667f47dddd83d9e0cee0ffd467 | 39,232 |
import re
def is_number(string):
"""Test whether a string is number-ish. Ignoring units like 'cwt' and 'hd'."""
if string:
string = re.sub(r'\$|[,-/]|cwt|he?a?d?|per', '', string, flags = re.IGNORECASE)
try:
float(string)
result = True
except ValueError:
... | 3e401d0bedcc7608bb33c7d158f57bd8dd95a35e | 39,233 |
import signal
def downgrade_pan_3d(I_MS , I_PAN, ratio, sensor=None):
"""
downgrade MS and PAN by a ratio factor with given sensor's gains
"""
I_MS=np.double(I_MS)
I_PAN=np.double(I_PAN)
I_MS = np.transpose(I_MS, (2, 0, 1)) #
#I_PAN = np.squeeze(I_PAN) #从数组的形状中删除... | 88c308e08a14ae0de666890510f4be1356786664 | 39,234 |
def readSedML(*args):
"""
readSedML(self, string filename) -> SedDocument
Reads an SEDML document from a file.
This method is identical to readSedMLFromFile().
If the file named 'filename' does not exist or its content is not
valid SEDML, one or more errors will be logged with the SedDocument
object re... | 86e4f3179e70720c109a17b1948c1aa2fd757231 | 39,235 |
from my_library import test_socket, ClassDB
from collections import namedtuple, defaultdict
import json
def show_status_json():
""" List current status of sensors in json-format """
db_ip = server_settings['db_ip']
db_user = server_settings['db_user']
db_pass = server_settings['db_pass']
db_name ... | 70d9a9b78886f73d7f73ee1c54e0a00452bf9c30 | 39,236 |
def get_recommended_dictionary_gcs_path(fuzzer_name):
"""Generate a GCS url to a recommended dictionary.
Returns:
String representing GCS path for a dictionary.
"""
bucket_name = environment.get_value('FUZZ_LOGS_BUCKET')
bucket_subdirectory_name = 'dictionaries'
recommended_dictionary_gcs_path = '/%s/%... | e27dfc9259823754b4ac5738481db810476b469c | 39,237 |
def PlaneEHfield(z, t=0.0, sig=1.0, mu=mu_0, epsilon=epsilon_0, E0=1.0):
"""
Plane wave propagating downward (negative z (depth))
"""
bunja = -E0 * (mu * sig) ** 0.5 * z * np.exp(-(mu * sig * z ** 2) / (4 * t))
bunmo = 2 * np.pi ** 0.5 * t ** 1.5
Ex = bunja / bunmo
Hy = E0 * np.sqrt(sig ... | 9b97030e01718f608003b93c95f50dcf11631fb6 | 39,238 |
from pathlib import Path
def playbook_path(request: SubRequest, tmp_path: Path) -> str:
"""Create a playbook with a role in a temporary directory."""
playbook_text = request.param[0]
role_name = request.param[1]
role_layout = request.param[2]
role_path = tmp_path / role_name
role_path.mkdir()
... | 66457aa20ac74504cac9374ba97d068da6f12b7a | 39,240 |
import posixpath
def _address_to_placement(address):
"""
Parameters
----------
address : str
The address of a node or an actor pool which running in a ray actor.
Returns
-------
tuple
A tuple consisting of placement group name, bundle index, process index.
"""
par... | 1e20394a5deddcb06571273f51dccccead96adca | 39,241 |
def ideal_season_state(season_states, conditions_season):
"""Classify ideal season states # (prefer dry rainy over early/late states)"""
(
dry_condition,
dry_early_condition,
dry_late_condition,
rainy_condition,
rainy_early_condition,
rainy_late_condition,
) =... | f48bab9ddcabce24186204796812f67877363af5 | 39,242 |
def estimate_post_transplant_death(txids, doids):
"""
This function estimate the number of post transplant deaths.
@Input:
@txids: list of patients who received transplants
@doids: list of donated organs
@Output:
@output_totals: number of post transplant deaths for each replication
"""
#set seed
nump.rand... | 3d341214ed3d8ce03c99323c84c01b00af3c8d1c | 39,243 |
def geolytica(location):
"""
# Geolytica
Geocoder.ca - A Canadian and US location geocoder.
Using Geocoder you can retrieve Geolytica's geocoded data from Geocoder.ca.
## Python Example
>>> import geocoder
>>> g = geocoder.geolytica(<address>)
>>> g.lat, g.lng
45.4... | 1e44582548d972aada50e25271e88d264d6bf3dc | 39,244 |
from discopy.monoidal import Functor
def flatten(self):
"""
Takes a diagram of diagrams and returns a diagram.
>>> from discopy.monoidal import *
>>> x, y = Ty('x'), Ty('y')
>>> f0, f1 = Box('f0', x, y), Box('f1', y, x)
>>> g = Box('g', x @ y, y)
>>> d = (Id(y) @ f0 @ Id(x) >> f0.dagger()... | d648bfa88e2343c2e0d91ce023ebde574aa12f38 | 39,245 |
def accuracy_count(y_true, y_pred) -> int:
"""
accuracy 计数
Examples:
# 单标签分类
>>> _y_true = [0,1,2,3]
>>> _y_pred = [0,1,2,2]
>>> accuracy_count(_y_true, _y_pred)
3
# 多标签分类:使用 one-hot 标签
>>> _y_true = [[0,1],[1,1],[1,0],[0,0]]
>>> _y_pred = [[... | d8ee8d30053b0bbc6b7e529e83cfd974d75599db | 39,246 |
import io
import random
def label_image(image_bytes, labels):
"""
Plot an image and corresponding bounding
boxes of detected labels
Parameters
----------
image_bytes : bytes
Image as bytes
labels : [n_label,] dict
Returned from api.get_json() function or from
Reko... | dcaf2c52c53cceb1233d2a18848572d94a0eeef2 | 39,247 |
def parse_prelink_info():
"""Find and parse the kernel __PRELINK_INFO dictionary."""
segments = _find_prelink_info_segments()
for segment in segments:
seg_size = idc.get_segm_end(segment) - idc.get_segm_start(segment)
prelink_info_string = idc.get_bytes(segment, seg_size)
prelink_info_string = prelink_info_str... | 7e2aed1ae52ff9631ee66a3bc7a6f3e58d6119f9 | 39,248 |
def box_plots(df, plotField, groupField, groupFieldItems):
"""
Returns a dictionary of box plot statistics for the plotField,
where the keys are the unique items in the groupField.
"""
# reduce df and drop the nulls
df = df[[plotField, groupField]].dropna()
# group the requests by type and ... | 7ae43364794439d248dca4a62eae9cac44f442dc | 39,249 |
def model(X_train, Y1_train, Y2_train, X_dev, Y1_dev, Y2_dev, numOutputNodes, learning_rate = 0.0001, iterations = 5000, minibatch_size = 16, print_cost = True, \
layer1 = 100, layer2_1 = 50, layer2_2 = 50, beta1 = 0.01, beta2 = 0.1):
""" Three-layer NN to predict Fe coordination numbers around oxygen.
... | 740a7a1fe2d1ae2d52d67329ca3b44eb555fbedb | 39,250 |
def send_shared_files(path):
"""Files used accross different web apps"""
return flask.send_from_directory(SHARED_PATH, path) | 0de2f50ea37724b4084e2cfc7b16b4429b051da8 | 39,251 |
def create_creative_sets(creative_sets):
"""
Creates creative sets in DFP.
Args:
creative sets (arr): an array of objects, each having creative set configuration
Returns:
an array: an array of created creative set IDs
"""
dfp_client = get_client()
creative_set_service = df... | 3eabc5c8850f9521e0d3be90d3ef14a7a63548ee | 39,252 |
def get_combinations(limit, numbers_count, combination):
"""Get all combinations of numbers_count numbers summing to limit."""
if sum(combination) >= limit:
return None
if numbers_count == 1:
return [combination + [limit - sum(combination)]]
combinations = []
for number in range(1, l... | caecaeb8a5ef5f68bc47936c3b4db3d7514b6c52 | 39,253 |
def read_el_cards():
"""
Read information about space group from file to list of cards ldcard.
Info in file fitables:
1 P1 Triclinic
choice: 1
centr: false
pcentr: 0, 0, 0
symmetry: X,Y,Z
2 P-1 Triclinic
...
"""
fid = open(F_ITABLES, "r")
... | fc4b2f5891e4ea924da2d7cd72fb3298d705a644 | 39,254 |
from typing import Union
from typing import List
def resize_image(
image: pygame.surface.Surface, new_size: Union[List[int], CoordsType]
) -> pygame.surface.Surface:
"""
wrapper for pygame.transform.scale
:param image: pygame.surface.Surface
:param new_size: Union[List[int], Tuple[int, int, int]]
... | 401a2d15f2c47feb68ac27730b2da38a7677d68b | 39,255 |
def isoDuration(value):
"""(str) -- Text of contained (inner) text nodes except for any whose localName
starts with URI, for label and reference parts displaying purposes.
(Footnotes, which return serialized html content of footnote.)
"""
if not isinstance(value, str):
raise TypeErr... | 6b75c0dbad9cda86bb48c77b23f6bde095895670 | 39,256 |
def bit_list_to_int(bit_list):
"""
Converts binary number represented as a list of 0's and 1's into its corresponding base 10
integer value.
Args:
bit_list: a binary number represented as a list of 0's and 1's
Returns:
The base 10 integer value of the input binary number
"""
... | ade66899fe1d23a22c76cccf4ba57e9ad9bf0ba1 | 39,257 |
def max_labor_budget_rule(M):
"""
Put upper bound on total labor cost.
Using individual shift variables multiplied by their length and a tour
type specific cost multiplier. Could easily generalize this to make costs
be complex function of time of day, day of week, shift length, tour type,
o... | f2637e4b2dba8cc4eb6e5afcae57c45d1b9560d7 | 39,258 |
def _trace_prefixes(trace: Trace, prefix_length: int) -> list:
"""List of indexes of the position they are in event_names
"""
prefixes = []
for idx, event in enumerate(trace):
if idx == prefix_length:
break
event_name = event['concept:name']
prefixes.append(event_nam... | 837474c0e8b244bc4a49dc2abe31271cec512cf7 | 39,259 |
def _diff_args(type, options):
"""generate argument list to pass to diff or rcsdiff"""
args = []
if type == CONTEXT:
if "context" in options:
if options["context"] is None:
args.append("--context=-1")
else:
args.append("--context=%i" % options[... | f52d7a2513d1726693b4493d0ed9d421476493a4 | 39,260 |
import re
def email(value: str):
"""
Extract email from document
Example Result: ['crazyvn@gmail.com', 'feedback@tp.com']
"""
_email_pat = r'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+'
return re.findall(_email_pat, value) | c8f3dcb4163e99f0aefe7eb42e61b127ffbaa393 | 39,261 |
def TransposeTable(table):
"""Transpose a list of lists, using None to extend all input lists to the
same length.
For example:
>>> TransposeTable(
[ [11, 12, 13],
[21, 22],
[31, 32, 33, 34]])
[ [11, 21, 31],
[12, 22, 32],
[13, None, 33],
[None, None, 34]]
"""
... | d53dc20a9eff391560269e818e99d41f8dc2ce94 | 39,262 |
import typing
def compile_metric_telegraf(
prefix: str,
path: str,
value: str,
type_code: str,
rate: str = "",
tags: typing.Optional[typing.Dict[str, str]] = None,
) -> str:
"""Compile metrics for telegraf."""
rate = serialize_rate(rate)
if tags is None:
return f"{prefix}... | bbb10bfbcb3717d83960637ef005bc4ff07f96ec | 39,263 |
from typing import Optional
from typing import Sequence
def _canonicalize_depends_on(
dep_param, *, max_depth: Optional[int] = None
) -> Sequence[DependencyNode]:
"""
For convenience, we allow specifying the depends_on parameter when submitting a job
in numerous ways.
"""
if max_depth is not N... | be51aed923d61fe54d60f46496cea0815a22d84d | 39,264 |
def handle_exceptions(func):
"""Catch exceptions and return appropriate HTTP error."""
@wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except Exception as err:
return http_500(str(err))
return wrapper | 57fbaa07e9f7549ab6a96ca4650764d461bb4eae | 39,265 |
def stochastic_RSI_strategy(df: pd.DataFrame, window: int = 14, max_investment: float = 0.1) -> pd.DataFrame:
"""
Stochastic Relative Strength Index Strategy
"""
# https://www.investopedia.com/terms/s/stochrsi.asp
stochRSI = signals.stochastic_relative_strength_index(df, window=window)["signal"]
... | 1bc6216a03554885dbee0d286b56188977e78eaf | 39,267 |
def conv3x3(in_planes, out_planes, stride = 1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size = 3, stride = stride, padding = 1, bias = False) | 4e32b1d6f81ecdbe24b59ec46ccba22395faf59b | 39,268 |
async def handler(request: web.Request) -> web.Response:
"""
Expose API specification to the world
"""
return web.json_response(request.app["spec"].to_dict(), dumps=ujson.dumps) | fb8f7e3f6620a8db2265089183ae87198fede1ff | 39,269 |
from operator import or_
def storage_get_active_by_window(context,
begin,
end=None,
project_id=None):
"""Return storages that were active during window."""
session = get_session()
query = session.query(models.H... | 69fd18955ad1f88cd196cd5d4593891a9b30bf8d | 39,270 |
def eval_against_random_bots(env, trained_agents, random_agents, num_episodes):
"""Evaluates `trained_agents` against `random_agents` for `num_episodes`."""
wins = np.zeros(2)
for player_pos in range(2):
if player_pos == 0:
cur_agents = [trained_agents[0], random_agents[1]]
else:... | 9fae8b61062e372273055894af0cd33a0b6e091f | 39,272 |
def _get_number_divisiors(number: int):
"""
Function return number of divisiors of a given number.
"""
if number <= 1:
raise ValueError("Number must be greater than 1.")
return len(list(divisior for divisior in range(1, floor(sqrt(number) + 1)) \
... | b2be8e4cca1d238fa453744562bc679c7b3f6a3e | 39,273 |
def vvisegment2dict( link):
"""
Intern rutine for å gjøre om visveginfo-data til håndterbar liste
"""
start = round( float( link['FromMeasure'] ), 8 )
slutt = round( float( link['ToMeasure'] ), 8 )
mydict = { 'vegref' : str( link['County']).zfill(2) + str( link['Municipality'] ).zfill(2... | ad8c5de2065ee2e935b63674c7f4d11ba11bcff8 | 39,275 |
def pow_frac(T1, T2, freqs):
""" Fractional power between two physical temperatures """
return bb_pow_spec(freqs, T1) / bb_pow_spec(freqs, T2) | 036e40cac05ae0170ce0713bf10df61c77022820 | 39,276 |
def setup_mongo() -> pymongo.collection.Collection:
"""Setup mongo client."""
client = pymongo.MongoClient("mongodb://localhost:27017/")
vdm_database = client["vdm"]
return vdm_database | 2224810aa635c6a7f1cd7b89b30594537a48dd8b | 39,278 |
def add_doub_doub(db1, db2, entityName):
"""
## This function adds two doubles
## Input : db1 - double (number)
: db2 - double (value)
"""
add = Add_of_double(entityName)
add.sin1.value = db1
add.sin2.value = db2
return add | e62fec9496afdd1eb7e4384758a6358d37882787 | 39,279 |
def build_dataset(nb_holograms, nb_file, nb_holograms_class, nb_class, hol_dataset_list):
"""
Build a large dataset with datataset with small datasets.
"""
# Create new dataset
nb_total = nb_holograms * nb_file
hol_dataset = np.zeros([200, 200, nb_total], dtype=complex)
init_list = np.aran... | e5f78fad9837f903bbb218431c45ca9d81d15085 | 39,280 |
def percentage(value):
"""Return a float with 1 point of precision and a percent sign."""
return format(value, ".1%") | 43567c120e4994b54a92570405c02934eb989a6f | 39,281 |
def PricingAddBondPricingDetails(builder, bondPricingDetails):
"""This method is deprecated. Please switch to AddBondPricingDetails."""
return AddBondPricingDetails(builder, bondPricingDetails) | 1278af0118f3d3f51c8879c450d2681e1e8e9746 | 39,282 |
def get_chunk_size(N, n):
"""Given a two-dimensional array with a dimension of size 'N',
determine the number of rows or columns that can fit into memory.
Parameters
----------
N : int
The size of one of the dimensions of a two-dimensional array.
n : int
The number of ar... | d4fb5abbd30a9fe1b1666555b0ac54baf20b8450 | 39,283 |
def get_peering_partner(peering):
"""
Inserts a new node of the type Peering partner and ensures that this node
is unique for AS number.
Returns the created node.
"""
try:
return PEER_AS_CACHE[peering['as_number']]
except KeyError:
logger.info('Peering Partner {name} not in c... | 15b4b896995026a0e837b51fb97319a3004d8c36 | 39,284 |
def get_v3_atlas_fine_path():
"""Get v3 atlas fine path.
Returns
-------
: pathlib.Path
v3 atlas fine path.
"""
return get_data_dir() / "ccfv3_atlas_fine.nrrd" | e9fc612838e20cb1908f7583e8ad9ca0cf2ae95e | 39,285 |
import traceback
def run_action(action, conv_list, params, return_dict):
"""
This method runs the specified action.
Args:
action(str): The action name, e.g., 'retrieval', 'qa', etc.
conv_list(list): List of util.msg.Message, each corresponding to a conversational message from / to the
... | 8db0fc99c346fbda1277f4aeb23c1a8d6a85561c | 39,286 |
def delete_comment(comment_id):
"""Delete an existing comment. For admins only."""
if current_user.roles.role_label != 'admin':
flash("Admin privileges required.", "danger")
return redirect("/")
if request.method == "POST":
comment = Comment.query.get_or_404(comment_id)
... | 51334b0a4ad558d572353d845714f5c657c7f343 | 39,287 |
def bfill(arr, dim=None, limit=None):
"""backfill missing values"""
axis = arr.get_axis_num(dim)
# work around for bottleneck 178
_limit = limit if limit is not None else arr.shape[axis]
return apply_ufunc(
_bfill,
arr,
dask="parallelized",
keep_attrs=True,
... | a3b019a04876e915447e25ca1b199cccfc99bdd2 | 39,288 |
def resource_descriptor(session, Type='String', RepCap='', AttrID=1050304, buffsize=2048, action=['Get', '']):
"""[Get/Set Resource Descriptor]
"""
return session, Type, RepCap, AttrID, buffsize, action | 4547d30bc7260236a5c1718847f7bc9574f27246 | 39,289 |
def min_version_string():
"""Returns the minimum supported API version (as a string)"""
return _MIN_VERSION_STRING | 42f004759c5246d89613ab21397e64d4be76ad29 | 39,292 |
def coord_clip(pos, chrlen, binsize=128000, window_radius=16000000):
"""
Clip the coordinate to make sure that full window
centered at the coordinate to stay within chromosome boundaries.
coord_clip also try to preserve the relative position of the coordinate
to the grid as specified by binsize when... | 81acd78a417bc015eef71c29e0aa675aea9cf374 | 39,293 |
def get_peak_length(lc_table, peak_frac=0.75):
"""Returns peak length for given lightcurve table
"""
lc_filled = fill_lightcurve(lc_table)
peak = np.max(lc_table.flux)
mask = lc_filled[:, 1] > peak_frac*peak
time_slice = lc_filled[mask, 0]
return time_slice[-1] - time_slice[0] | 63d6b922811717e1da9ac3d5cb285a32eeeb5bbb | 39,294 |
from typing import Counter
def get_collocations(relations):
"""
Calculate collocations based on the list of all relations in the corpus
input: list of all binary syntactic relations in the corpus (result of get_relations())
output: pandas DataFrame with all syntactic collocations and their llr scores
... | c6eada543761edc4b7d322e6cb780121c33b0a89 | 39,296 |
def prefix(expof10):
"""
Args:
expof10 : Exponent of a power of 10 associated with a SI unit
character.
Returns:
str : One of the characters in "yzafpnum kMGTPEZY".
"""
prefix_levels = (len(SI_PREFIX_UNITS) - 1) // 2
si_level = expof10 // 3
if abs(si_level) > ... | a66975bfaa93c31ad1de5e5f05b1807958c2784c | 39,297 |
def _Pick_CF3(st, cf3, iniPick, f=np.linspace(50, 1000, 20), tol=10e-3):
"""
input :
st - stream object
cf3 - characteristic function number 3
f - list of frequency (used instead of the Ns parameter)
tol - maximum time to move a pick
"""
sr = st.traces[0].stats['sampling_rate']
ST =... | 47c4ebb2f003e1f4c179ac463e7bb5f4c9ea993c | 39,298 |
def flatten_dims(tensor, start=0, end=None, name=None):
"""Flatten a contiguous range of dimensions in a tensor.
Args:
tensor: The tensor or array to reshape.
start: First dimension to flatten. An integer.
end: One past the last the last dimension to flatten.
An integer or `... | 5bf1a5f31630ea5dd5a55828fbe05f67453bce05 | 39,299 |
def ridgeTest(xArr, yArr):
"""
Desc:
函数 ridgeTest() 用于在一组λ上测试结果
Args:
xArr:样本数据的特征,即 feature
yArr:样本数据的类别标签,即真实数据
Returns:
wMat:将所有的回归系数输出到一个矩阵并返回
"""
xMat = np.mat(xArr)
yMat = np.mat(yArr).T
# 计算Y的均值
yMean = np.mean(yMat, 0)
yMat = yMat - yMe... | 96da9f5c94fd3fd8ae2fadd8ea107337fc7fe71e | 39,300 |
def gumbel_softmax(logits, temperature, hard=True):
"""Sample from the Gumbel-Softmax distribution and optionally discretize.
Args:
logits: [batch_size, n_class] unnormalized log-probs
temperature: non-negative scalar
hard: if True, take argmax, but differentiate w.r.t. soft sample y
Returns:
[bat... | 8b8b8aa357b4d399f3cb672d21c02087a7997165 | 39,301 |
def create_Walternating_layered_ansatz(qc: qiskit.QuantumCircuit,
thetas: np.ndarray,
num_layers: int = 1):
"""Create Walternating layered ansatz
Args:
- qc (qiskit.QuantumCircuit): init circuit
- thetas (np.ndarray): par... | 623a5adaec0e0f003fb17ca295274d809ef4511d | 39,302 |
def screen(corners, h=0.1):
"""
Creates a screen.
Parameters
----------
corners : np.ndarray
A (4 x 3) array that defines four corners of the screen.
h : float
A floating point number specifying the grid size.
Output
-------
grid : bempp.Grid
A structured gr... | 3080412baa596e4b15312911ac5ac3c6689b91bb | 39,303 |
def execute(sql, con, cur=None, params=None, flavor='sqlite'):
"""
Execute the given SQL query using the provided connection object.
Parameters
----------
sql : string
Query to be executed
con : SQLAlchemy engine or DBAPI2 connection (legacy mode)
Using SQLAlchemy makes it possi... | 694b9ef9c96768bcd5c845222ecf89a56b932dd4 | 39,304 |
def lower(s: "Stream[str]") -> "Stream[str]":
"""Computes the lowercase of a string stream.
Parameters
----------
s : `Stream[str]`
A string stream.
Returns
-------
`Stream[str]`
A lowercase string stream.
"""
return s.apply(lambda x: x.lower()).astype("string") | cf02e36d58f67a8269b496131e68135197af7873 | 39,305 |
def mean_feature(data, rolling_window, num):
"""Computes the mean for a given lag and its rolling window
Given a set number of lags in the past, a set rolling window and the input
dataset, computes the rolling average mean for the given window.
Parameters
----------
data: pd.Dataframe
... | 07e637b75eb5db6e1c53a5c6e6bb0aadc3fb18f9 | 39,306 |
def cmgListToWaterArray(stacks:list,product="MOD09CMG") -> "numpy array":
"""
This function takes a list of CMG .hdf files, and returns
a binary array, with "0" for non-water pixels and "1" for
water pixels. If any file flags water in a pixel, its value
is stored as "1"
***
Parameters
----------
stacks:list
... | 23663f3eb4f5e9fbcd556753261dd06831df1de0 | 39,307 |
def decode(packed_list):
"""
implement the function packed the string
"""
# Empty list of tuple
decode_str = ""
list_len = len(packed_list)
for i in range(list_len):
# element of packed list
str_tuple_count = packed_list[i]
# find number of counting from tuple
... | d6fe8de66ead935a14e99b069d3b416089d5a93d | 39,308 |
def travel_space_separated(curr):
"""Print space separated linked list elements."""
if curr is None:
return ""
print(curr.data, end=' ')
travel_space_separated(curr._next) | 19213588f06a569560b236563975bcd6cb5254a0 | 39,309 |
def _generate_subparser(parser, name, description=None, subcommand=False):
"""Helper function to return a subparser with the given options"""
subparser = parser.add_parser(
name,
description=description,
formatter_class=RawDescriptionHelpFormatter
)
if subcommand:
subpar... | e538f931e4ec0129f4b2416dc21d04d0afc0fc1d | 39,311 |
def identity_matrix(dim):
"""Construct an identity matrix.
Parameters
----------
dim : int
The number of rows and/or columns of the matrix.
Returns
-------
list of list
A list of `dim` lists, with each list containing `dim` elements.
The items on the "diagonal" are ... | dd37f0c7df41478e23dd26df727341a37a201ec1 | 39,312 |
def get_zscale(self):
"""Get the qcodes_colorbar scaling
:return: str "linear" or "log"
:raises: AttributeError
"""
if not hasattr(self, 'qcodes_colorbar'):
raise AttributeError("Axes object does not have a colorbar.")
if isinstance(self.qcodes_colorbar.formatter, ticker.LogFormatter):... | 4a2d43c219ed041b3b664bc8d4eff4663b60e18f | 39,313 |
def train_logistic_regression(X_train, y_train, X_val, y_val, min_coef=1, max_iter=2000):
"""
Logistic regression training algorithm on binary features
:param X_train: Pandas DataFrame of train set features
:param y_train: Pandas Series of train set binary target
:param X_val: Pandas DataFrame of v... | 801dc7ef3a60cdde68ef88a39163900cedf3cb7a | 39,314 |
def result2list(foo):
"""Convert from ParseResults to normal list."""
if isinstance(foo, ParseResults):
return [result2list(bar) for bar in foo]
else:
return foo | 03f4c34ed49b44407740fbae7dac9cbebab017db | 39,315 |
def cluster_shutdown(cluster):
"""
Shutdown an entire cluster, cancelling any spot
requests and terminating all instances in the cluster.
Also permanently deletes any record of the cluster.
RouteParams:
cluster: the name of a cluster
Returns:
A status code indicating success
... | 7c92e8ef8eba1ecd5545e843b0905b93b0a83754 | 39,316 |
def collect_jsonschema_errors(metadata, convention, bq_json=None):
"""Evaluate metadata input against metadata convention using JSON schema
returns False if input convention is invalid JSON schema
"""
# this function seems overloaded with its three tasks
# schema validation, non-ontology errors, ont... | 2b7f8b3aa0bfdd5d542376d9ce784c5055d239ad | 39,317 |
def kg2m3H2O_hot(kg):
"""kg -> m^3 (50 C hot water)"""
return kg/988.1 | 060b039db404014ab6cbea6aa5e416efc70aa8a2 | 39,318 |
from typing import List
def feeder(url: str, archived: bool, archived_only: bool, verbose: bool) -> List[str]:
"""Create and return a list of urls according to the input."""
thread_urls = []
# list of thread urls
if url.endswith(".txt"):
with open(url, "r") as f:
thread_urls.extend... | d51f9f1b0f1af4ade834692febe77bca5c1b21c9 | 39,320 |
from typing import OrderedDict
import re
def convert_torch_resnet_weights_to_serialClassificationNet(model, state_dict, strict=True):
"""Convert resnet weights from torchvision to vega weights name."""
names = convert_names(model)
new_state_dict = OrderedDict()
for name in names:
state_name = ... | c827466270fdfce31b1a82f8352e17ac5e02d18e | 39,321 |
import yaml
def load_yaml(file_path):
"""Load a yaml file into a dictionary"""
try:
with open(file_path, 'r') as file:
return yaml.safe_load(file)
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
return None | 3d4fa37794bc99c352959e49057d2e9cfb0d4c92 | 39,323 |
from typing import Set
def build_column(min_trays, max_trays, xD, xB):
"""Builds the column model."""
m = ConcreteModel('benzene-toluene column')
m.comps = Set(initialize=['benzene', 'toluene'])
min_T, max_T = 300, 400
max_flow = 500
m.T_feed = Var(
doc='Feed temperature [K]', domain=N... | 82029468a6817fc3c49c370d920421197c60a220 | 39,324 |
def coerce(fun):
"""Decorates a function and coerces each of the inputs of the function into a
Forward object.
Many of our functions would like to operate on Forward objects instead of raw
values. For example, __add__ might get an integer in the case of Forward('x', 5)
+ 2, but we want the 2 to be ... | 1fa28f6d12dabe6c2ca6ecfa05b567ee4d432608 | 39,325 |
def DatasetWithIndices(cls):
"""
Modifies the given Dataset class to return a tuple data, target, index
instead of just data, target.
"""
def __getitem__(self, index):
data, target = cls.__getitem__(self, index)
return data, target, index
return type(cls.__name__, (cls,), {
... | a8ccdaf26755e92f471c5b0dc330eab86f1b2a31 | 39,326 |
def hex_int_range(min=None, max=None, min_included=True, max_included=True):
"""Validate that the config option is an integer in the given range."""
return All(
hex_int,
Range(min=min, max=max, min_included=min_included, max_included=max_included),
) | 0d6feaf9c7086f6513e3658a1a857f853c4e5567 | 39,327 |
import requests
def execute_graphql_request(payload):
"""Execute queries and mutations on the GraphQL API."""
url = 'http://graphql:5433/graphql' # Should be moved to config file
headers = {'Content-Type': 'application/graphql'}
response = requests.post(url, headers=headers, data=payload)
status ... | d12d30722dccbdd8f1c89084e66f37ef3febf9d0 | 39,328 |
def s3_put(bucket_name, file_path, file_name, payload):
"""
Use for Uploading a file as StringIO object
:param str bucket_name: s3 bucket name
:param str file_path: string name, sub folders are allowed
:param str file_name: name that you need to be in destination S3 Bucket location
:param String... | 086ab5ce4a58cc76b214a75bbe56acb5d3265069 | 39,329 |
def add_contrastive_loss(hidden,
hidden_norm=True,
temperature=1.0,
tpu_context=None,
weights=1.0):
"""Compute the instance discrimination loss for the model.
Args:
hidden: hidden vector (`Tensor`) of shape (bsz... | 63c26c03b02b32277a1eb39417054a37d5e6c63f | 39,330 |
import time
def timed_call(f, args):
"""Call function f with arguments args and time its run time.
Args:
f: The function to call
args: The arguments to pass to f
Returns:
Return the result of the function call and how much time it takes as tuple e.g. (result, time).
"""
s... | e592ecdf5ebb4aa3391b2500b2a3a20d2faa9b40 | 39,331 |
def count_words(texts):
"""
Counts the words in the given texts, ignoring puncuation and the like.
@param texts - Texts (as a single string or list of strings)
@return Word count of texts
"""
if type(texts) is list:
return sum(len(t.split()) for t in texts)
return len(texts.split()) | f08cbb1dcac3cbd6b62829cf4467167ae9b7694e | 39,332 |
def train_circuit(circuit,n_params,n_cnots,X_train,Y_train,X_test,Y_test,optim,optimoptions,inference='wall_clock',rate_type='accuracy',**kwargs):
"""Develop and train your very own variational quantum classifier.
Use the provided training data to train your classifier. The code you write
for this challeng... | 5ef9cbb31bf89c81fdb98a335f85da7a6efe36ce | 39,333 |
def calvin_astgen(source_text, app_name, verify=True):
"""
Generate AST from script, return processed AST and issuetracker.
Parameter app_name is required to provide a namespace for the application.
Optional parameter verify is deprecated, defaults to True.
"""
cg, issuetracker = _calvin_cg(sou... | 63e9a9d169781174a7dfe2d415564160dd7f761f | 39,334 |
def fit(*views):
""" Convenience method to both enable and apply natural fit width and
height constraints with one call. Useful mainly for Buttons and Labels.
You can provide several views, first view is returned. """
for view in views:
enable(view)
view.dock.fit()
return views[0] | a11a525874a46ae5748f6d516e7a652adea6f866 | 39,336 |
def get_subnetwork(project_id, context):
""" Gets a subnetwork name. """
subnet_name = context.properties.get('subnetwork')
is_self_link = '/' in subnet_name or '.' in subnet_name
if is_self_link:
subnet_url = subnet_name
else:
subnet_url = 'projects/{}/regions/{}/subnetworks/{}'
... | de0217b7a78d3278d6dbf70db10b4c270aff2b15 | 39,337 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.