content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def parse_header(file,string):
"""Function to extract instrument settings from FORC data file header
Inputs:
file: name of data file (string)
string: instrument setting to be extracted (string)
Outputs:
output: value of instrument setting [-1 if setting doesn't exist] (float)
"""
... | 4865e1e54629585281f4ea04258cb44aa68eada7 | 57,328 |
import random
import networkx
def subgraph_stable_topsort_test(graph):
"""Test that sort is stable for subgraph"""
def shuffle_graph(graph):
nodes = list(graph.nodes())
random.shuffle(nodes)
new_graph = networkx.DiGraph()
for name in nodes:
new_graph.add_node(name)
... | c76cb214aef90e769ad66a88e945819a4bc4878d | 57,330 |
import pandas
def get_functions(name=None, **kwargs):
"""Returns all available functions as pandas dataframe.
:param name: optional filter expression for the functions, if it is not included in the name,
the function will not be added to the data set.
:type name: str... | 6c71288f90aa46b8bc78b74b214f2485a1dd4b18 | 57,331 |
def copy_wings(original_wings):
""" This copies VLM attributes for every wing object in original_wings into
a new wings container with new Data objects
Inputs:
original_wings - the original wings container
"""
return copy_large_container(original_wings, "wings") | 340561b594002ac7114a381e07fd1e2c638f4d8b | 57,332 |
def document_toc(document_instance, setting_key="default"):
"""
Get the TOC (Table Of Content) from the content of the given instance (*Pages*
or *Insert*) and settings
"""
return mark_safe( get_toc_with_cache(document_instance, setting_key=setting_key) ) | d4d4b23c1a0f060d2f5fb2db42332a6f22c00c5a | 57,333 |
def get_group(machine, num):
"""
"""
cores = []
idx = 0
r = 0
while num>0:
assert r<machine.get_cores_per_node()
cores.append(idx)
idx += machine.get_cores_per_node()
if idx>=machine.get_num_cores():
r += 1
idx = r
num -= 1
retu... | 2a295b0dc11cc9e195fc54787b5355e340dce366 | 57,334 |
def do_footer(_, token):
"""
Create a footer containing a github link and domain registration information. Take no arguments.
"""
if len(token.split_contents()) != 1:
raise template.TemplateSyntaxError('%r tag requires no arguments' % token.contents.split()[0])
return FooterNode() | 3f11d2eefc909db122df7de03b22c1b03948f10b | 57,336 |
def attachment(url: str, filename="") -> dict:
"""
Returns a dictionary using the expected dicitonary format for attachments.
When creating an attachment, ``url`` is required, and ``filename`` is optional.
Airtable will download the file at the given url and keep its own copy of it.
All other attac... | 24564ca3e7dfb8cc35242b1d16fb7351fc9576ce | 57,337 |
def convert_coverage_to_lookup(country, coverage):
"""
Takes a list of dicts and returns a dict for each access.
"""
GID_level = 'GID_{}'.format(country['regional_level'])
output = {}
for item in coverage:
output[item[GID_level]] = {
'2G': item['2G'],
'3G': ite... | 0190c76efee993d8f27f58dca01338c076b04cb2 | 57,338 |
def _exchange_coupling_terms(coupling_symbols, ordered_edges):
"""Exchange coupling terms between systems
Args:
coupling_symbols (list): coefficients of exchange couplings
ordered_edges (list): list tuples of system indices for the couplings
Returns:
list: exchange coupling strings
... | 30a90118adf783c8cd4116fca415c0df28d3d700 | 57,339 |
import torch
def inv3d(H, sym=False):
"""
Calculates the inverse of a batched 3-D matrix
"""
detH = determinant_3d(H)
Hinv = torch.empty_like(H)
Hinv[..., 0, 0] = H[..., 1, 1] * H[..., 2, 2] - H[..., 1, 2] * H[..., 2, 1]
Hinv[..., 1, 1] = H[..., 0, 0] * H[..., 2, 2] - H[..., 0, 2] * H[...,... | a154268fc9b93b704d4a4c1312e9e0a4d8e3a51b | 57,342 |
def NIST_SU(results):
"""Number of segmentation errors (missed segments and
false alarm segments)
over number of reference segments.
"""
assert len(results) == 3
TPs = results[0]
FPs = results[1]
FNs = results[2]
if (FNs + FPs) == 0:
return 0.0
return ((FNs + FPs)/(TPs + ... | 3c60a612223dc247109d24be45b32739af8587ef | 57,343 |
def _get_identity(op, dtype):
"""Get an appropriate identity for a given operation in a given dtype."""
if op is lax.scatter_add:
return 0
elif op is lax.scatter_mul:
return 1
elif op is lax.scatter_min:
if jnp.issubdtype(dtype, jnp.integer):
return jnp.iinfo(dtype).max
return float('inf')... | 7e92d8df2dc25c8b9d6f423105f7d1ae73cbb6ba | 57,344 |
def val_interm(hsl1, hsl2, pos):
""" Valeur intermédiaire entre la couleur 1 et la couleur 2
pos correspond à la postion dans la transition, entre 0 (couleur 1) et 1 (couleur2)
"""
# res_h = (hsl2[0]-hsl1[0])*pos + hsl1[0]
# hue value transition can be tricky to compute
# we have to decide if we... | 8f4b9ecd5d2e1db084e1a41772086d37d398aa04 | 57,345 |
def pathCountX(stairs: int, X):
"""number of unique ways to climb N stairs using 1 or 2 steps"""
#we've reached the top
if stairs == 0:
return 1
elif stairs < 0:
return 0
else:
validSteps = []
for num in X:
if stairs >= num:
validSteps.app... | 8ee8bf554f6176b5f666fe33eea51a3ee982deee | 57,346 |
def top_value_counts(df, n=5, only_categories = True, cols_to_include = None, cols_to_exclude = None):
""" Function to generate summary information for string or categorical
data in dataframes"""
if cols_to_include:
df = df[cols_to_include]
if cols_to_exclude:
df = df[df.columns[~df.col... | bea88ab28985d71591ad9587b025223ea075aeb4 | 57,347 |
import torch
def tik_reg(mat: ComplexTensor, reg: float = 1e-8, eps: float = 1e-8) -> ComplexTensor:
"""Perform Tikhonov regularization (only modifying real part).
Args:
mat (ComplexTensor): input matrix (..., C, C)
reg (float): regularization factor
eps (float)
Returns:
r... | b148e551b690407cb557e4ad90736af28ae66616 | 57,348 |
def current_cloud_token(service):
"""Get the the current state of the account.
Args:
service: Drive API service instance.
Returns:
int
"""
response = service.changes().getStartPageToken().execute()
return response.get('startPageToken') | dc2b61c2c0e5548269a6c746cf8dc1d152ec953d | 57,349 |
def workflow_create(request, workflows_definition):
"""Create workflow.
:param workflows_definition: Workflows definition
"""
return mistralclient(request).workflows.create(workflows_definition) | 93e4fd97b9f745ed5e609399748926329b6d687c | 57,350 |
import re
import yaml
def scan_info(cell_id, basedir):
"""
Scans the info.dat for meta information about the recording.
Args:
cell_id: id of the cell
basedir: base directory where the data lives
"""
info = open(basedir + cell_id + '/info.dat').readlines()
info = [re.sub(r'[^... | e5404b048827fdb0d52bfa9f52bd26ccbe67748e | 57,351 |
def geo_disjoint(left, right):
"""
Check if the geometries have no points in common.
Parameters
----------
left : geometry
right : geometry
Returns
-------
disjoint : bool scalar
"""
op = ops.GeoDisjoint(left, right)
return op.to_expr() | 0628258944c90230fb4edcf88b529685c1cce0e9 | 57,352 |
import datasets
import tqdm
import torch
def train(model, optimizer, Y, epoch, batch_size, data_path, gpu, version, dicts, quiet):
"""
Training loop.
output: losses for each example for this iteration
"""
print("EPOCH %d" % epoch)
num_labels = len(dicts['ind2c'])
losses = []
#... | 462e9d7836d6b6ec3a7e44f02afa04cafaf6e71c | 57,353 |
def split_line_and_comment(line):
"""
Returns a tuple(line, comment) based on a '//' comment delimiter.
Either `line` or `comment` may be ''.
Does not strip whitespace, nor remove more than two slashes.
"""
split = line.split('//', 1)
if len(split) == 1:
return split[0], ''
... | 32f478d4ce90b012d63ae48a2c75ed59a9dc00fc | 57,354 |
def compare_descriptor_types(a, b):
"""Compare two metric types to sort them in order."""
# pylint: disable=invalid-name
a_root = a['type'][len(StackdriverMetricsService.CUSTOM_PREFIX):]
b_root = b['type'][len(StackdriverMetricsService.CUSTOM_PREFIX):]
return (-1 if a_root < b_root
else 0 if a_root ... | ad6e5f36beb6cf1e766891c4d34cae48c34820c4 | 57,356 |
def build_dict_as_specific_ppdcases_per_member(path_to_file):
"""
Build a dict with the key being the member ASN and the value a set of the ASNs belonging to its customer cone.
"""
print "Cones ASes dataset: {}".format(path_to_file)
if path_to_file.lower().endswith('.txt'): # customer cone datas... | ee5a212318aa1f47b7f1d69121a51801018a23e0 | 57,357 |
def _(tag, child_element_list_or_other=None, attrib_custom={}):
"""XML Element."""
tag_real = tag.split('-')[0]
child_element_list_or_other = child_element_list_or_other or []
attrib = DEFAULT_ATTRIB_MAP.get(tag, {})
attrib.update(attrib_custom)
attrib = dict(zip(attrib.keys(), list(map(str, at... | 0e6c48d4659e10161df2204e797b8969a1ba0ed4 | 57,358 |
def sort_stack(stack_object: list) -> list:
"""
Sorts stack.
:param stack_object: stack object, iterable object
:return: sorted stack, iterable object
"""
tmp_stack = []
while stack_object:
# complexity check
print(f'stack 1')
element = stack_object.pop(-1)
w... | ebdca3c263dfdc72bcdb0843b9e6e7d397ba2236 | 57,360 |
def execute(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, hpc=None,
skip_transpiler=False):
"""Executes a set of circuits.
Args:
circuits (QuantumCircuit or list[QuantumC... | 217bd6bb02a87bf9c95ec40eda5f985e7c69937a | 57,361 |
import torch
def calculate_interaction_nominal(genotypes_t, phenotypes_t, interaction_t, residualizer,
return_sparse=False, tstat_threshold=None):
"""
genotypes_t: [num_genotypes x num_samples]
phenotypes_t: [num_phenotypes x num_samples]
interaction_t: [1 x num_s... | f3270e7623d8c3d3e6cdd706142b43650d21a7b4 | 57,362 |
from datetime import datetime
def sync_run_job(job, settings=None, pid=None, tables=[], silent=False):
""" Run synchronization job """
# Notification helpers
error = lambda message, pid=pid, silent=silent: not silent and \
s3_sync_push_message(message, pid=pid, error=True)
notify ... | a6572843f6cb0a9021763029b21ea6f8e65b6170 | 57,363 |
from typing import List
def remove_too_short(utterances: List[Utterance],
_winlen=25, winstep=10) -> List[Utterance]:
""" Removes utterances that will probably have issues with CTC because of
the number of frames being less than the number of tokens in the
transcription. Assuming char... | 0c64a0a60c34498d7c99f906b08d16bfa710def7 | 57,364 |
from typing import Union
def test_set(startDate: str = None, endDate: str = None, ticker: Union[str, list] = "AAPL", **kwargs) -> pd.DataFrame:
"""Test sets which are called from Quandl each time.
The function currently calls the given ticker close prices from the WIKI/PRICES database from Quandl.
If no s... | 4c2f529887d65370c6d5b793fa9966a2ccf3788d | 57,365 |
def parse_default_kv(default, default_dict):
"""parse a string in form key1=value1;key2=value2,... as used for some template fields
Args:
default: str, in form 'photo=foto;video=vidéo'
default_dict: dict, in form {"photo": "fotos", "video": "vidéos"} with default values
Returns:
di... | 4d461589118915cde5461b6b8ea7cd5e5e4d5165 | 57,366 |
import copy
def train_network(model, train_data, val_data, optimizer, loss_function,
num_epochs=300, patience=20, print_progress=True):
"""Trains NN.
Parameters
----------
model: NeuralNetwork instance
train_data: torch.utils.data.DataLoader
Training data.
val_data : t... | 46b8c600e61625a72a4d515a55e560d47c15c9ee | 57,367 |
def Npts(*args):
"""
(read) Get Number of points in active Loadshape.
(write) Set number of points to allocate for active Loadshape.
"""
# Getter
if len(args) == 0:
return lib.LoadShapes_Get_Npts()
# Setter
Value, = args
lib.LoadShapes_Set_Npts(Value) | a7f778b9adb086290b35cd6be71399d56463f7bf | 57,368 |
def normalize_01(inp: np.ndarray):
"""Squash image input to the value range [0, 1] (no clipping)"""
inp_out = (inp - np.min(inp)) / np.ptp(inp)
return inp_out | c9d62cbf80883dbdcf9dccf455f64cc961d8cb1e | 57,369 |
def rate_map(Hx, Hy=0, Hz=-400, T=3.21):
"""Finds the slowest nonzero eigenvalue of the rate matrix for a given
transverse field H, hard plane angle phi, and longitudinal field Hz."""
return np.sort(np.abs(rate(Hx, T, ph1, ph2, Hy, Hz).eigenenergies()))[1] | 7657e3b361c587b9eb89830bd1fe65e0db0c952a | 57,370 |
def prefix_connection_id(connection_id, parent_connection_id):
"""Used to distinguish connection ids when they have the same id
as a parent_connection. """
if not len(connection_id) > len(parent_connection_id):
return parent_connection_id + connection_id
return connection_id | bdc1f92625a03c6b88dd6c81097aca0522db0929 | 57,371 |
def try_to_open(file_name, mode):
"""Try to open file and retry twice if unsucessful."""
file_handle = None
success = True
try:
file_handle = open(file_name, mode)
except:
sleep(2)
try:
file_handle = open(file_name, mode)
except:
sleep(10)
... | 97dcdf210743bab360adc9940d2599d633b308da | 57,372 |
import itertools
def get_data_for_lang(language):
"""
Extracts Trending data from twitter for a specified language
Input-> language - a string which specifies the language the tweets are required in.
Output -> x - A dataframe consisiting of data for the language specified.
"""
... | 616c6918b3ab48c9a656b1a95de309f6bf5fc458 | 57,373 |
def extract_other_features(paths, path2gt, model_type):
"""Extracts MusiCNN or OpenL3 features and their corresponding ground_truth and identifiers (the path).
OpenL3 features are extracted from non-overlapping audio patches of 1 second,
where each audio patch covers 128 mel bands.
MusiCNN f... | 1c5cefb762a9ce019589766a357667a011c224bc | 57,374 |
def press_key(v_key):
"""
按下某个按键
:param v_key:
:return:
"""
return send_kb_event(v_key, True) | a94d5f3bbc4cbe3c13c2e7b9b964158b11133eac | 57,377 |
def trotz(theta):
"""
Rotation about Z-axis
@type theta: number
@param theta: the rotation angle
@rtype: 4x4 homogeneous matrix
@return: rotation about Z-axis
@see: L{trotx}, L{troty}, L{rotz}
"""
return r2t(rotz(theta)) | 909db720d7924ca0000670603cd8ff786a728312 | 57,378 |
def read_input_file(input_filename):
"""Read a formatted input file and return a dictionary of keywords.
:param input_filename:
Filename of the SENKIN input file.
"""
# Initialize the dictionaries and lists that will be filled by
# the parsing.
keywords = {}
reactants = []
oxidi... | 8280073efa57469e25bbadb73830455d69e826fa | 57,379 |
def welcome():
"""List all available api routes."""
return (
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/start (enter as YYYY-MM-DD)<br/>"
f"/api/v1.0/start/end (enter as YYYY-MM-DD/YYYY-M... | 5062f97d9db404fd3883d0861e2a2e3f9bdb4479 | 57,381 |
def new_keyset(lang: str, template: tink_pb2.KeyTemplate) -> bytes:
"""Returns a new KeysetHandle, implemented in lang."""
global _ts
return _primitives.new_keyset(_ts.keyset_stub(lang), template) | 84fd2e59d3138f2eaac9d4df71476cb832ad5aa1 | 57,382 |
import re
def extract_intro_and_title(filename, docstring):
""" Extract the first paragraph of module-level docstring. max:95 char"""
# lstrip is just in case docstring has a '\n\n' at the beginning
paragraphs = docstring.lstrip().split('\n\n')
# remove comments and other syntax like `.. _link:`
... | f1ae63f112f0c4ff91ba8863313b9bd978e16eb4 | 57,383 |
def _process_symbols(exp, symbol_type, symbols):
"""
Args:
exp (ExperimentSet): The current experiment set
symbol_type (str): CONSTANT, FUNCTION, or TABLE
symbols ([[str]]): List of symbol names and values usually ["SYM","=","VALUE"]
Returns:
ExperimentSet: the passed exper... | 33e03eb4e327becdf472bff9d62a6d2cf046cfdd | 57,384 |
def interp(prec: np.ndarray, method: InterpType = InterpType.ALL) -> np.ndarray:
"""Interpolate the precision over all recall levels. See equation 2 in
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.167.6629&rep=rep1&type=pdf
for more information.
Args:
prec: Precision at all recall l... | 832737de9fdce27c62d6b5468e23737d0d3ce8bd | 57,386 |
def test_array_access_needs_frozenset():
"""Array access fails without frozenset?"""
l = lattice.PartialOrderLattice(3, lat_dir='../lattices')
return l[4] | 5a7d2e726824f146d0166ed60ae87b14e891ce9d | 57,387 |
def likelihood(X, mean, cov, pi):
"""対数尤度関数"""
summation = 0.0
for n in range(len(X)):
temp = 0.0
for k in range(K):
temp += pi[k] * gaussian(X[n], mean[k], cov[k])
summation += np.log(temp)
return summation | a4891947b4abce50701093d796654419b188170d | 57,389 |
def str2dec(s):
"""
string to decimal number.
"""
if not len(s):
return 0
return int(str2hex(s), 16) | ce8befd465843675324886edccb0cfd01ead965a | 57,390 |
def show_k8s_extension(client, resource_group_name, cluster_name, name, cluster_type):
"""Get an existing K8s Extension."""
# Determine ClusterRP
cluster_rp, _ = get_cluster_rp_api_version(cluster_type)
try:
extension = client.get(
resource_group_name, cluster_rp, cluster_type, clus... | 7f174c2b4cb670bce95d88b9391270a455621a9f | 57,391 |
def get_current_connection():
"""Returns the current SMTP connection (i.e. the topmost on the
connection stack).
"""
return _connection_stack.top | 12d3b615123e6fe616fd1f218c623337f199263f | 57,392 |
def __radd__(self, other):
"""Computes the addition between two numbers.
Parameters
----------
self : ee.Number
Right operand.
other : ee.Number | numeric
Left operand. If numeric, an ee.Number is created from its value.
Returns
-------
ee.Number
Addition of two... | 8f2e1bde381a2c482c62b6530f0508423cc34e71 | 57,393 |
def getLMPfile(filepath, filename, tz, squeeze=False, product='lmp'):
"""
To use for MCC, MCL, MCE (instead of LMP):
* Keep default filepath, to io/lmp-nodal/da/, and specify
product='mcc' (or 'mcl' or 'mce')
* OR keep product as 'lmp' or None, and set filepath to the folder
containing the ... | 5c41fec7df3fe41a71515bc698a4ba7c0cc21398 | 57,394 |
def is_valid_customer_category(process_id: int, customer_category: str) -> bool:
"""Checks whether a customer_category string is part of the customer categories of a certain process.
:param process_id: process to be checked
:param customer_category: category to be checked
:return: True or False
"""... | 4e0cdd2a0641a6eff7608cdaa8b003c64980788c | 57,396 |
def _map_job_status_to_human_representation(status, resource, token):
"""
Map an Job Status type code (e.g., 1, 2) to a human readable name.
:param status: integer with the value that we want to transform
:param resource: resource containing all the values and keys
:param token: user token
"""
... | d135b6dd2dce665ecd50f232496ccf8f7866a7ec | 57,398 |
import importlib.resources as pkg_resources
import importlib_resources as pkg_resources
from cortex import binary
def get_cli_path() -> str:
"""
Get the location of the CLI.
Default location is the directory containing the `cortex.binary` package.
The location can be overridden by setting the `CORTEX... | bb97dc1e68616f4d9bc483844724867ef101ad7d | 57,399 |
def is_func_decl(a):
"""Return `True` if `a` is an SMT function declaration.
>>> f = Function('f', IntSort(), IntSort())
>>> is_func_decl(f)
True
>>> x = Real('x')
>>> is_func_decl(x)
False
"""
return isinstance(a, FuncDeclRef) | 11c886078509bdf3c841c82909cc69f4fd063b73 | 57,400 |
def get_instance(ec2_conn, ids=None, tags=None, hostnames=None, state=None):
"""Get single instance matching criteria.
If more than one image match, raise exception NonUniqueError.
"""
instances = list_instances(
ec2_conn, ids=ids, tags=tags, hostnames=hostnames, state=state
)
if not i... | 0cd7f43c75b622bc6eaa53819b6388a93ec5985b | 57,401 |
def MakeKiteFromOverride(override, aero_devices=None):
"""Makes a kite config from override dict.
Args:
override: Dict of overrides to define a kite config.
Returns:
Dict of kite config.
"""
kite = {}
# Setup aero device
# Pick from the dict of provided aero devices - if not provided, make a d... | 60845894c49e159df3b1eaf6502b7818c772f5d4 | 57,402 |
def _createLeafletNodes(mapObject=None, nodes=None, iconPrefix=None, iconType=None, iconColor=None, iconText=None):
"""
A sub-function to create leaflet nodes
Parameters
----------
mapObject: Folium object, Required
Add content to a folium map.
nodes: :ref:`Nodes`, Required
The Nodes dataframe to be generate... | c50f81da11ef998e5502b9edf0355eacc78268d1 | 57,403 |
def doc_param_dict_format(member_list) :
"""
member_list : list of the node of the members of a struct
returns the rst table
"""
member_list2 = treat_member_list(member_list)
h= ['Parameter Name', 'Type', 'Default', 'Documentation']
n_lmax = max(len(h[0]), max(len(m.spelling) for m in... | 68f489a57635b465238a981f3f01c532128b0ea1 | 57,404 |
def get_star_mag(df):
"""Solely for use with star truth catalogs. Computes and creates a list of magnitudes of form '(mag_g, mag_r, mag_i, mag_z)'.
Args:
df (pandas DataFram)
Returns:
m_griz (list of str) -- Stores magnitudes of each filter in form '(mag_g, mag_r, mag_i, mag_z)'.
"""
m_g = df['g_Corr_1']
m... | b78e873a8a0b9d83a06a124895f6c66899ffe938 | 57,405 |
def servers_delete(request, pk):
"""Delete an server"""
object = get_object_or_404(Server, pk=pk)
object.delete()
messages.success(request, 'Server has been deleted.')
return redirect(reverse('servers.views.servers_list', args=())) | aede4939b7d91261f225997502f2a75b206d9147 | 57,406 |
from typing import Callable
def __manage_undefined_ratios(func: Callable):
""" Wraps ratio functions to return NaN values instead of 0.0 in cases
where the ratio is undefined
"""
def wrapper(*args, **kwargs):
funcname = getattr(func, "__name__", "an unknown function")
msg = (
... | ae9f4a014acac2920bc18e852ea8dd28e988cd0d | 57,407 |
def to_one(dest_class, type=RelationType.DIRECT, resource_classes=None,
reverse=None, reverse_type=RelationType.DIRECT,
writable=False):
"""Create a one to one relation to a given target :class:`Resource`.
Args:
dest_class(Resource): The *target* class for the relationship
K... | d38fb795692d3b971853b0fb1c077b6a77f58f08 | 57,408 |
def get_unit_status(code):
"""Get on/off status for given unit."""
unit = int(code[1])
return get_status()[16 - int(unit)] == '1' | aa853535a384ac6d369da4f0a4fa792ebd569c42 | 57,409 |
def is_on(S, j):
"""
Returns 1 if and only if the `j`-th item of the set `S` is on.
Examples
========
Check if the 3-th and then 2-nd item of the set is on:
>>> S = 0b101010
>>> is_on(S, 3), is_on(S, 2)
(1, 0)
"""
return (S & (1 << j)) >> j | 76034f083372ee2cbe0c711e3a09daf26634550a | 57,410 |
def init_infected_symptomatic_70():
"""
Real Name: b'init Infected symptomatic 70'
Original Eqn: b'0'
Units: b'person'
Limits: (None, None)
Type: constant
b''
"""
return 0 | 40ff15eba496f9448055f7aa73468d3c5063b264 | 57,411 |
def fetch_val_for_key(key, delete_key=False):
"""Return the overriding config value for a key.
A successful search returns a string value.
An unsuccessful search raises a KeyError
The (decreasing) priority order is:
- THEANO_FLAGS
- ~./theanorc
"""
# first try to find it in the FLAGS
... | 3b0a10bbab0c1fef2d824267bf6b88beb22d6c58 | 57,415 |
def NEXUSEnvironmentProperties(
allCleanData, propertiesData, env, masking=(True, True, True), VERBOSE=True
):
"""Creates a properties file on the initial data grid for the given environment."""
funcName = "NEXUSEnvironmentProperties"
envList = ["fila", "wall", 3, 2]
if env not in envList:
t... | 8731b31da27bb40764ceb6d89b7ca04439022a7f | 57,416 |
def _get_pil_image_dimensions(pil_image):
"""Gets the dimensions of the Pillow Image.
Args:
pil_image: Image. A file in the Pillow Image format.
Returns:
tuple(int, int). Returns height and width of the image.
"""
width, height = pil_image.size
return height, width | d191ae705df97b1729be2dd03e9a5ff4ddcb4518 | 57,417 |
def loadNeutral(filename):
"""Reads a `Neutral` tetrahedral file format. Return an ``Mesh`` object."""
f = open(filename, "r")
lines = f.readlines()
f.close()
ncoords = int(lines[0])
coords = []
for i in range(1, ncoords + 1):
x, y, z = lines[i].split()
coords.append([float(... | 05be95d839d643c3570161a5b7839a92be9ef8c8 | 57,418 |
import heapq
def solve(n, times):
"""
小根堆/优先队列
"""
if n == 0:
return 0
heap = []
heapq.heappush(heap, times[0][1])
for time in times[1:]:
if time[0] >= heap[0]:
# 不需要新的客服
heapq.heappop(heap)
heapq.heappush(heap, time[1])
print(heap)
r... | 064d582ef76dcae4e69b2c037d3fae07fde3b143 | 57,419 |
from typing import List
def find_subgraphs_matching_pattern(graph: nx.DiGraph, pattern_graph: GraphPattern) -> List[List[str]]:
"""
Find a list of subgraphs for the particular graph that match the pattern expression.
:param graph: The model graph.
:param pattern_graph: A graph consists of patterns for... | 144672921ef37065ba46ed4438cd977b295544d6 | 57,420 |
def trace_stats_by_qu_sess(sessions, analyspar, stimpar, n_quints=4,
qu_idx="all", byroi=True, bysurp=False, integ=False,
ret_arr=False, nan_empty=False, lock="no",
baseline=None, sample_reg=False, datatype="roi"):
"""
trace_sta... | 40962074899a8dfd27181cff1bd278b8f6156741 | 57,421 |
def wrap_list(item):
"""
Returns an object as a list.
If the object is a list, it is returned directly. If it is a tuple or set, it
is returned as a list. If it is another object, it is wrapped in a list and
returned.
"""
if item is None:
return []
elif isinstance(item, list):
... | 6b2af543af39058f7df28e7d89dbb9231cf2b247 | 57,422 |
from typing import Union
import zlib
def zlib_compress(data: Union[bytes, str]) -> bytes:
"""
Compress things in a py2/3 safe fashion
>>> json_str = '{"test": 1}'
>>> blob = zlib_compress(json_str)
"""
if isinstance(data, str):
return zlib.compress(bytes(data, "utf-8"))
return zlib... | 0e7eaf018873ce335b06c4ca4857f9bf8b58864b | 57,423 |
import functools
import logging
def logdec(func):
"""A logging decorator wrapping a function with a standard logging mechanism.
This decorator wraps a function with a standard logging mechanism, providing the following functionalities:
* Logs the calling of the function and the parameters passed to it wh... | fd1ddf475f17758c09d3f44492a8b2ff66cf38de | 57,424 |
from typing import Any
from typing import Dict
from contextlib import suppress
def dictify(value: Any) -> Dict:
"""Ensure value is a dictionary."""
with suppress(AttributeError):
return {k: dictify(v) for k, v in value.items()}
if isinstance(value, str):
return value # type: ignore
... | 30a265fa37a634a8923a554cd89e219b8838a503 | 57,425 |
def crgrow(crarr, grad=3):
"""If a cosmic ray has been identified in the source, delete the pixels around
it according to gradius.
"""
darr=np.where(crarr>0)
xlen=len(crarr[0])
ylen=len(crarr)
#set it up as a box
if grad < 3: grad=3
mbox=int(grad/2)
for i in range(len(darr[0])):
... | 52d7b27bdefec3e06e12fe4c553793d6dd0f1d5e | 57,426 |
def sdbm_hash(name):
"""Calculate SDBM hash over a string."""
ret = 0
for ii in name:
ret = ret * 65599 + ord(ii)
return hex(int(ret & 0xFFFFFFFF)) | 07eb20e27fda5d7a228bc196a55f4ebbefe7c1c1 | 57,427 |
def _get_test_protocol_factory() -> IProtocolFactory:
"""Get a protocol Factory which will build an HTTPChannel
Returns:
interfaces.IProtocolFactory
"""
server_factory = Factory.forProtocol(HTTPChannel)
# Request.finish expects the factory to have a 'log' method.
server_factory.log = _... | e1b69a4eb4cd5becea640fcdff13a3b6eaba9e0a | 57,428 |
def compose_report():
"""
Compose rota report.
:return: A composed submission.
:rtype: html
"""
form = ReportForm()
if form.validate_on_submit():
flash('Report created')
return redirect(url_for('report.view_report'))
return render_template('compose_report.html', title='C... | 99e4e8a8606b1fce232da82e3aea845907a736c4 | 57,429 |
import typing
def score_by_sbs(
sentence_words: StringList,
top_kws: typing.Sequence[ScoredKeyword],
top_kw_words: StringList) -> float:
"""Score sentence (`words`) by summation
Arguments:
sentence_words {StringList} --
sequential list of words in sentence
... | 399d8503eb64bc18e038a88ae718b3879e315894 | 57,430 |
def worker_3d(vals):
"""
same as 2d version of this worker
:param vals: tuple wrapper for (propability, samples, lattice_size,)
:return: number of times percolation did occur in lattice
"""
v = vals[0]
su_rate = 0
for i in range(v[1]):
lat = lattice_gen_3D(v[2], v[2], v[2], v[0]... | d09ed4343c116e236ae86bd24c32a5fb7a6da7a5 | 57,431 |
def get_E(G, mi, xi, vi, mj, xj, vj, xp, vp, mp):
""" Returns the energy of mp and (mi,mj) combined """
m_in = mi + mj
cms_in = (mi * xi + mj * xj) / m_in
v_in = (mi * vi + mj * vj) / m_in
E = 0.5 * (m_in * norm(v_in)**2 + mp * norm(vp)**2) - G * m_in * mp / norm(xp - cms_in)
return E | 6a8d6c71e8d30c4bc874ca8cb41da641ea635ffc | 57,432 |
def mean_average_precision(ranking):
"""
Score is mean average precision. Relevance is binary (nonzero is relevant).
:param ranking: Relevance scores (list or numpy) in rank order (first element is the first item)
:type ranking: list, np.array
:return: Mean average precision
:rtype: float
... | 4c91c09108f4988ebbb6a4c6c4c2070f08e061a9 | 57,433 |
def convert_to_example(image_data, labels, labels_text, bboxes, shape,
difficult, truncated):
"""Build an Example proto for an image example.
Args:
image_data: string, JPEG encoding of RGB image;
labels: list of integers, identifier for the ground truth;
labels_text: li... | 1efb4c04cf552cc46ee29a744b780674d95de589 | 57,434 |
def predict(sample, relations):
"""
Predict entities and interactions of given sample
w.r.t set of known relations.
:param sample: Dict with `id` and `text` as strings
:param relations: Set of relation tuples
:return: Sample augmented with extracted entities and interactions.
"""
text = ... | 44046de044685609cf6252f2f106a60c2ecf5f7a | 57,435 |
def _get_storage_area(storage_area):
"""
:param storage_area: storage area entry in nodes collection.
Either a numpy string or a bytes type
:returns default '--' if the input is an empty string or 0., or the
given input will be converted to a float representation
"""
default_null =... | bd497219d1a0ea6ee5048fabc65431ee14e8dd9c | 57,437 |
def GetEntityViaMemcache(entity_key):
"""Get entity from memcache if available, from datastore if not."""
entity = memcache.get(entity_key)
if entity is not None:
return entity
key = ndb.Key(urlsafe=entity_key)
entity = key.get()
if entity is not None:
memcache.set(entity_key, entity)
return entit... | 1b760a738fd207ba67039fb499e423b1e84f9ea3 | 57,439 |
def ehvicalc_vec(x, y_par, moboInfo, kriglist, pool=None):
"""Vectorised EHVI Function
Vectorises above EHVI function as much as possible. Currently,
still depends on the vectorisation of prediction.py prediction() and
kadal.optim_tools.ehvi.exi2d.exi2d() for best performance boost.
Args:
... | 429de869279320668db5998530caa71a3831b211 | 57,440 |
def resolve_params(obj, params, default=missing):
"""Given a dictionary of keyword arguments, return the same dictionary except with
values enclosed in `< >` resolved to attributes on `obj`.
"""
param_values = {}
for name, attr_tpl in iteritems(params):
attr_name = tpl(str(attr_tpl))
... | 85b32b7212b3c9451f1c2fcf88e443c6cd9015e1 | 57,441 |
def get_manual_iface(manual_iface, node_class):
""" Returns standardized interface dict based on manual_iface """
iface_dict = {
"node_id": "manual",
"node_uri": None,
"node_name": None,
"node_addr": None,
"node_fqdn": None,
"node_class": node_class,
"ifac... | 070207a1ba399b660147f0d3cb95419347e0344e | 57,442 |
from typing import Tuple
from datetime import datetime
def _zipinfo_date_time_to_timestamp(date_time: Tuple) -> float:
"""Converts a date_time of a ZipInfo object to a unix timestamp.
The timestamp is rounded to seconds because that is the resolution of
date_time.
"""
timestamp = datetime.datetime... | c3b03d7c3324a2ad66957fbf4881bd6863bd912f | 57,443 |
def find_tables(clause, check_columns=False,
include_aliases=False, include_joins=False,
include_selects=False, include_crud=False):
"""locate Table objects within the given expression."""
tables = []
_visitors = {}
if include_selects:
_visitors['select'] = _vis... | 4ba03b28ac66b4717b55c0adcf9a3cc5d4cf8282 | 57,444 |
def pluralize(singular: str) -> str:
"""Return plural form of given lowercase singular word.
Refer to: http://code.activestate.com/recipes/577781-pluralize-word-convert-singular-word-to-its-plural/
>>> pluralize('user')
'users'
"""
if not singular:
return ''
plural = ABERRANT_PLURA... | 97e4e02fb0cd77f0b2812e56262d92296df1729a | 57,446 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.