content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def getAttributes(obj):
"""Get non hidden and built-in type object attributes that can be persisted"""
d={}
allowed = [str,int,float,list,tuple,bool]
for key in obj.__dict__:
if key.startswith('_'):
continue
item = obj.__dict__[key]
if type(item) in allowed:
... | ea60687e48734f9bd53b96109b101b8a2267e8d1 | 46,999 |
def norm_except(param, dim, power):
"""Computes the norm over all dimensions except dim.
It differs from pytorch implementation that it does not keep dim.
This difference is related with the broadcast mechanism in paddle.
Read elementeise_mul for more.
"""
shape = param.shape
ndim = len(shap... | 0c985766df8e8af0b979e4ec4cf54718506042b7 | 47,000 |
from pathlib import Path
def file_hasher(file_path: Path, hash_method: str) -> FileHash:
"""
Convenience method to hash a file path.
Parameters
----------
file_path : Path
The `pathlib.Path` to a file.
hash_method : {'blake2b','blake2s','md5','sha1','sha224','sha256','sha384','sha... | 5a6ebcf3d077014f669bf6f7967ea310de2c25a7 | 47,001 |
def ClusterRemoveNodes(node_ips,
by_node,
remove_drives,
mvip,
username,
password):
"""
Remove nodes from the cluster
Args:
node_ips: the MIPs of the active nodes to remove
... | 0d74f828bb497d91d2718c24097c39160489dd6c | 47,002 |
def get_network_detach_config_spec(client_factory, device, port_index):
"""Builds the vif detach config spec."""
config_spec = client_factory.create('ns0:VirtualMachineConfigSpec')
virtual_device_config = client_factory.create(
'ns0:VirtualDeviceConfigSpec')
virtual_device_co... | b937b290398dd04f48c1d7b7ec0bc5e2d496c97b | 47,003 |
def sec_title(default_str: str) -> str:
"""Reads in a section title"""
name = input('What would you like to title this section? '
+ '(default is ' + default_str + ')\n')
if name:
return name
return default_str | 3dfc0ddcdc9cb9beb22b02892959334516b2a90b | 47,004 |
def e_timeToString(dateString):
"""
input: string
output: string
description: format dateString to yyyymmddHHMM
example: Wed Aug 29 07:23:03 CST 2018 ->> 201808290723
"""
# define month list for get digital
month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
... | 1a0c3f014bbd95a9da0eb767e1ce219cb0c70195 | 47,006 |
def bayesdb_variable_number(bdb, population_id, generator_id, name):
"""Return the column number of a population variable."""
cursor = bdb.sql_execute('''
SELECT colno FROM bayesdb_variable
WHERE population_id = ?
AND (generator_id IS NULL OR generator_id = ?)
... | 75baa84cc0c0cd79712d48b31e3647011f5dd774 | 47,007 |
def continue_mof():
"""
Update ASE Atoms object after failed job
Returns:
mof (ASE Atoms object): reset ASE Atoms object
"""
try:
mof = read('CONTCAR')
mof = continue_failed_magmoms(mof)
except:
mof = reset_mof()
return mof | 6cabce67e9c0b960e3457c102452b71750a4316f | 47,008 |
def tachycardic_detector(patient_age, patient_heart_rate):
"""
Determines if patient is tachycardic based on their age and heart rate
Args:
patient_age: integer extracted from patient database entry
patient_heart_rate: integer posted to patient database entry
Returns:
tachycardic... | 595bf87d913cd94b9f4aa089a3f1cf32f342ccbf | 47,009 |
import requests
from io import StringIO
def bond_repo_zh_tick(code="sz131802", trade_date="20201028"):
"""
成交明细-每个交易日16:00提供当日数据
http://stockhtm.finance.qq.com/sstock/ggcx/131802.shtml
:param code: 带市场标识的债券-质押式回购代码
:type code: str
:param trade_date: 需要提取数据的日期
:type trade_date: str
:ret... | 4bac9f3aaedb9e4c8679e56d2daecb5b2fbe025a | 47,010 |
def linear_bn_lrelu_dropout_block(in_feat, out_feat, normalize=True, alpha=0.2, p=0.5):
""" linear + batchnorm + leaky relu """
layers = [nn.Linear(in_feat, out_feat)]
if normalize:
layers.append(nn.BatchNorm1d(out_feat))
layers.append(nn.LeakyReLU(alpha, inplace=True))
layers.append(nn.Drop... | 3cd4d5a54cbbf7ef5f96d776b411e975376c1cdb | 47,011 |
def detect_style(docstr):
"""Detect docstr style from existing docstring
Parameters:
docstr (str): docstring whose style we want to know
Returns:
class: one of [GoogleDocstring, NumpyDocstring, None]; None
means no match
"""
docstr = dedent_docstr(docstr)
for c in ... | a1b8c053d84bbf23d549de72f2dac7eab9f66398 | 47,012 |
async def prepare_mail(client: Facade, recipient: Portfolio) -> Mail:
"""Generate one mail to recipient using a facade saving the mail to the outbox."""
message = CreateMail().perform(client.data.portfolio, recipient).message(
Generate.lipsum_sentence(), Generate.lipsum(100).decode()).done()
envelop... | 509ab91c92858fe0401f4861faf958cc7553f4b6 | 47,013 |
def resolve_doi(rec):
"""Resolve the doi of a given record"""
doi = _get_doi(rec)
if doi is not None:
res = None
try:
res = urlopen(DOI_ORG + doi)
except HTTPError as e:
res = e
return res.url | 150b2855a18d0865c68140989114910672344942 | 47,014 |
def reject():
""" Reject the Tic-Tac-Toe Challenge """
global currentGame, resp, slackResponse, message, srb
status = None
obj = {"response_type": "ephemeral"}
challenger = None
opponent = None
if slackResponse is not None:
challenger = "@"+slackResponse['user_name']
oppon... | 9dbe2dce9b027790d2b20d381964d79c1cd9c3a8 | 47,016 |
def make_string(seq):
"""
Don't throw an exception when given an out of range character.
"""
string = ''
for c in seq:
# Screen out non-printing characters
try:
if 32 <= c and c < 256:
string += chr(c)
except TypeError:
pass
# I... | 422cedb92ad325438f76df32d4e184fd5aba3fb3 | 47,017 |
from typing import Any
from typing import Dict
def verify_params(
handler: Any, request: HttpRequest, may_path_params: Dict[str, Any]
) -> Dict[str, Any]:
"""
Verify the parameters, and convert the parameters to the corresponding type.
"""
if is_class_view(handler):
return _verify_params(
... | 73e72c5ee9bff4ac98625b854308d2416dab4d9b | 47,018 |
import re
def get_short_name_for_type(instance):
"""
<class 'datatypes.strings.Smiles'> to smiles
:return: short name
"""
try:
return (re.search('\w+\'', str(instance)).group(0)[:-1].lower())
except:
return None | 9d98d95f712383a461623ce07ed3a0b4fcd521f6 | 47,019 |
import math
def _CalcOrderedCorners(orig, inc, size, gpiline, gpxline, gpx, gpy):
"""
Convert three arbitrary control points to 4 ordered corner points ordered
first il, first xl; last il, first xl, first il, last xl, last il, last xl.
Also return the same 4 corners in annotation- and ordinal coordina... | 57f61111639823b7f5f807c2105742dd99153b07 | 47,020 |
import pickle
def save_to_pkl(pkl, obj):
"""Save experiment resource to file."""
with open(pkl, 'wb') as f:
pickle.dump(obj, f)
return obj | cf8c71617faa88a192e8214bd71a43e78c6acb67 | 47,021 |
def _from_json(dct):
"""convert string keys back to tuples"""
if not isinstance(dct, dict): return dct
for key in dct:
break
if isinstance(key, str) and key.startswith('('):
return {_str2inttuple(key): dct[key] for key in dct}
return dct | 12d5a71db0074e74bab706fc9d7bdf556d6880e0 | 47,022 |
def pen(turtle, pen=None):
"""Return or set the pen's attributes.
Arguments:
turtle -- the turtle
pen -- a dictionary with some or all of the below listed keys.
**pendict -- one or more keyword-arguments with the below
listed keys as keywords.
... | aa5563b5c487a4f7bc0e6afe4b9ad3a36799c97d | 47,023 |
def get_temp_exposure(fname):
"""Given a filename of a phenocam image
Returns the temperature and exposure extracted from the image.
"""
title, temperature_line, exposure_line = _get_lines(fname)
binary_temperature = _get_binary(temperature_line)
temp_str = _extract_digits(binary_temperature)
... | e4cfc65a1f2cb54f8ac91fb879e3ed168ae92845 | 47,025 |
from typing import Tuple
from typing import Dict
import json
def test_API_doc():
"""Should work as expected."""
app = proxy.API(name="test")
@app.route("/test", methods=["POST"])
def _post(body: str) -> Tuple[str, str, str]:
"""Return something."""
return ("OK", "text/plain", "Yo")
... | 4522a932eba8e2e8968b920c2c2c9aeafeea532c | 47,026 |
import torch
def gelu_fast(x):
""" Faster approximate form of GELU activation function
"""
return 0.5 * x * (1.0 + torch.tanh(x * 0.7978845608 * (1.0 + 0.044715 * x * x))) | 39f2e888b8e01edf0aaca4987c8a070850f58484 | 47,028 |
def get_pr_from_gh(pr_name, all_prs):
"""try to obtain existing open PR with name in GH"""
prs = [
pr for pr in all_prs
if pr_name in pr.title
]
if len(prs) > 1:
print(f'Warning: Too many PRs matched query "{pr_name}": {[p.html_url for p in prs]}. Returning first.')
retur... | a55424610fe53225cab0e8fa9b477306ee39f6db | 47,029 |
def mme_matches(case_obj, institute_obj, mme_base_url, mme_token):
"""Show Matchmaker submission data for a sample and eventual matches.
Args:
case_obj(dict): a scout case object
institute_obj(dict): an institute object
mme_base_url(str) base url of the MME server
mme_token(str)... | 31990111f6fd0289edc3a2d4a6747e24f42b6e6d | 47,030 |
def size(archiveentry_handle, p5_connection=None):
"""
Syntax: ArchiveEntry <handle> size
Description: Returns the list of sizes in bytes for each instance of the
given archive entry.
Return Values:
-On Success: the list of file sizes
"""
method_name = "size"
return exec_nsdchat([... | 63da4e08792c7a589baf8f431f3bd8879834f512 | 47,031 |
from itertools import product
def run_tntblast(nproc,
fwd_list,
rev_list,
output_name,
database_name,
min_tm,
max_tm,
primer_conc,
mv_conc,
dntp_conc = 0.8,
... | 8a8c3dfa22cd4d8b2c37874c8dad184c5ae9422b | 47,032 |
def projects(request):
"""Display projects."""
return {} | 749b2a1d5de2427d7059b04c72d28c49f7792187 | 47,033 |
def manage_github_orgs_add(request):
"""
Add an organization slot if the plan allows
"""
# # Redir https
# if request.headers.get('X-Forwarded-Proto') is not None:
# if request.headers['X-Forwarded-Proto'] != 'https':
# return HTTPMovedPermanently(location="https://%s%s" % (
# ... | 0e37a660926c43bf9a516de3b1e2c4eb9b4b011d | 47,034 |
def an(state, i, s, N):
"""Application of c_i,s on a given state (a linear superposition of |m>). Spin should be 0 for up and 1 for down."""
new_state = {}
for basis_state in state:
prefactor_an, state_an = fmulti_an(basis_state, i, s, N)
if state_an != None:
try:
new_state[state_an] += prefactor_an * ... | 65191266867355476931c42d8f50c53f7f48e790 | 47,036 |
def load_data(database_filepath):
""" Load the CLEAN_MESSAGES table from the given SQLite Database """
# load data from database
engine = create_engine('sqlite:///' + database_filepath)
df = pd.read_sql_table("CLEAN_MESSAGES", engine)
X = df['message']
Y = df.iloc[:,4:]
return X, Y, Y.colu... | 49a498a5ee978cf0ee555867382768d65e8871e3 | 47,038 |
from typing import Optional
def load_library(lib_location: Optional[str] = None):
"""Loads the `snap7.dll` library.
Returns:
cdll: a ctypes cdll object with the snap7 shared library loaded.
"""
return Snap7Library(lib_location).cdll | 5dc6e6118bf58bdff5ffee9643c5029a9e440257 | 47,040 |
from typing import List
def _interval_index(intervals: List[Interval], interval: Interval) -> int:
"""Find the index of an interval.
Args:
intervals: A sorted list of non-overlapping Intervals.
interval: The interval for which the index into intervals will be found.
Returns:
The ... | aa1b1cf84a20d82a378307979ea0d31d48e33e2b | 47,041 |
def diff_field(field1, field2):
"""returns true if field1 == field2"""
return field1 == field2 | 6439d8c06c1d5b460141831acf83275795d19ccc | 47,042 |
def block_layer(inputs, filters, bottleneck, block_fn, blocks, strides,
training, name, data_format):
"""Creates one layer of blocks for the ResNet model.
Args:
inputs: A tensor of size [batch, channels, height_in, width_in] or [batch,
height_in, width_in, channels] depending on data_form... | 1331ce44f32d819ec8e66967676ba2e21f2ae9ae | 47,043 |
import logging
def unlock(password):
"""Unlock vault
Returns: session (bytes) or False on error, Error message
"""
res = run(["bw", "unlock", "--raw", password], capture_output=True, check=False)
if not res.stdout:
logging.error(res)
return (False, res.stderr)
return res.... | 91fe38c23a0486e9b9634cfd2d5ef2da22202422 | 47,044 |
import random
def example_classifier(
task_info,
mode="demo",
default_split_prob={
"train": 0.9,
"dev": 0.01,
"test": 0.09,
},
):
"""
This will return the split this data belongs to.
"""
if mode == "demo" or mode == "all":
if random.random() < default_s... | 51aa25630158a4c295df85afc8684be59aca9d25 | 47,045 |
from typing import Optional
def set_file_input_files(
files: list[str],
nodeId: Optional[NodeId] = None,
backendNodeId: Optional[BackendNodeId] = None,
objectId: Optional[runtime.RemoteObjectId] = None,
) -> dict:
"""Sets files for the given file input element.
Parameters
----------
f... | 4375b1b94fefc5d1039b99c013985681c3f92f0a | 47,048 |
def islist(item):
"""Check if an is item is a list - not just a sequence.
Args:
item (mixed): The item to check as a list.
Returns:
result (bool): True if the item is a list, False if not.
"""
return isinstance(item, list) | 02c4157e1867e7b113e9695f2fa8fd4aaccc043d | 47,049 |
def group_parameters(model_params_dict_expanded):
"""Groups the parameters to be estimates
in flat dictionary structure"""
model_params_dict_flat = dict()
model_params_dict_flat["gamma_0s"] = list(
model_params_dict_expanded["const_wage_eq"].values()
)
model_params_dict_flat["gamma_1s... | deb566114d1b40610bf6e1e814e85b1d8d3e3351 | 47,050 |
import pandas
def read_static_info(static_tracks_file):
"""
This method reads the static info file from highD data.
:param static_tracks_file: the input path for the static csv file.
:return: the static dictionary - the key is the track_id and the value is the corresponding data for this track
""... | 295757466640f90b0d3f95dd1d68aab0c90b329b | 47,051 |
def nullify(grammar, state, visiting):
"""Return a list of results: each is the parsed part of reduced(state)
if state can derive the empty string."""
parsed, chain = state = reduced(state)
if not chain: return [parsed]
(tag, x), tail = chain[0], chain[1:]
if tag == 'push':
if x in visit... | ec7b6a209b9562d6d4dcb08044fe8b832cb675e2 | 47,052 |
def positional_encoding(tensor, start_index, omega):
"""
tensor: a reference tensor we use to get shape. actually only T and C are needed. Shape(B, T, C)
start_index: int, we can actually use start and length to specify them.
omega (B,): speaker position rates
return (B, T, C), position embedding
... | 2f9132a4844a8255bc65f9ed5531808c2b2cf22f | 47,053 |
def draw_smopy_basemap(G, figsize=(8, 6), zoom=10, ax=None):
"""Draw a basemap with the extent given by graph G"""
pos_wgs = nx_coordinate_layout(G)
lon = [coords[0] for coords in pos_wgs.values()]
lat = [coords[1] for coords in pos_wgs.values()]
lon_min = min(lon)
lon_max = max(lon)
lat_m... | 96b65fd0de1ebcd373ddc0e521bf4eb87f23ad7e | 47,054 |
def get_conversation_by_name(conversation_name: str) -> dict:
"""
Get a slack conversation by its name. Order of operation is:
1. Check the COMMON_CHANNEL parameter for the conversation
2. Check the integration context for the conversation
3. If DISABLE_CACHING is false, then we will paginate the ap... | 03634e5c15227f1513fcb594ab710651ee185b48 | 47,055 |
def _apply_laplacian(nx, ny, alpha, image):
""" Apply isotropic Laplacian to an image.
Parameters
----------
nx, ny: int
Dimensions of 2D image
alpha: float
Diffusion parameter
image: ndarray, ndim=1
Image as a 1D vector
Returns
-------
output: ndarray, ndim... | 28a92c250ff0a16a803bd94447c53dbd1bf6bae5 | 47,058 |
def get_tree():
"""You probably want to use ET.fromstring"""
root = ET.fromstring(xmlstring)
return ET.ElementTree(root) | d57f907d8929fb0bb448a1b8000677db6646c97a | 47,059 |
def standard_rated_expenses_emiratewise(data, filters):
"""Append emiratewise standard rated expenses and vat."""
total_emiratewise = get_total_emiratewise(filters)
emirates = get_emirates()
amounts_by_emirate = {}
for emirate, amount, vat in total_emiratewise:
amounts_by_emirate[emirate] = {
"legend": emirat... | 8d8ca250e03b0126176ae5cab165441f2109f6d1 | 47,060 |
def MPIBroadcast(inputs, root, mpi_ranks=None, **kwargs):
"""Broadcast a tensor to all nodes in the ``MPIGroup``.
Parameters
----------
inputs : Tensor
The tensor to broadcast.
root : int
The world rank of root node.
mpi_ranks: sequence of int, optional
The world rank of... | 42fa38c70e984d92d93c73833a10f44fcd3c4bef | 47,061 |
def _add_loss_summaries(total_loss):
"""Add summaries for losses.
Generates moving average for all losses and associated summaries for
visualizing the performance of the network.
Args:
total_loss: Total loss from loss().
Returns:
loss_averages_op: op for generating moving averages of l... | 05e3841aae8b3ed823eaca31f40a985d6ea1a9e9 | 47,063 |
import array
def lock2key(lock):
"""
Generates response to $Lock challenge from Direct Connect Servers
Borrowed from free sourcecode online.
"""
lock = array.array('B', lock)
ll = len(lock)
key = list('0'*ll)
for n in xrange(1,ll):
key[n] = lock[n]^lock[n-1]
key[0] = lock[0... | f7bf7c2a4881bfeb44b230d030711e684a674a2e | 47,065 |
def get_channel_count(ods, hw_sys, check_loc=None, test_checker=None, channels_name='channel'):
"""
Utility function for CX hardware overlays.
Gets a channel count for some hardware systems.
Provide check_loc to make sure some data exist.
:param ods: OMAS ODS instance
:param hw_sys: string
... | 9d26666dd611125a41e067bc405b3bbc7705ed3e | 47,066 |
def get_bundle_files_cached(bundle_uuid, bundle_version=None, draft_name=None):
"""
Get the list of files in the bundle, optionally with a version and/or draft
specified.
"""
if draft_name:
return get_bundle_draft_files_cached(bundle_uuid, draft_name)
else:
if bundle_version is N... | 1a8d761f6f93139f9efadc7700b63ab403a40ff5 | 47,067 |
from typing import Dict
def get_token_header(user_id: UUID) -> Dict[str, str]:
"""Get an authentication token header."""
token = encode_token(user_id, FAKE_KEY)
return {"Authorization": f"Bearer {token}"} | e11ee664bd4ae10dbcbedf6ade887d151e8c9d8d | 47,068 |
from typing import Union
def _add_prefix(key_type: Union[PublicKeyTypeAgreement, PublicKeyTypeAuthentication], data: bytes) -> bytes:
"""
Adds prefix to a data
:param key_type: type of key
:param data: data to be prefixed
:return: prefixed data
"""
prefix = varint.encode(key_type.value)
... | 3e0a4f97e59a0f02cb2e6066ec04b6a4c3c690bf | 47,069 |
def tshirt_code(tshirt_string):
""" convert tshirt size strings into a code for us"""
if not tshirt_string:
return ""
tshirt_code = ""
if tshirt_string[0] == "f":
tshirt_code += "0"
tshirt_string = tshirt_string[1:]
else:
tshirt_code += "1"
size_code = {"s": "1"... | f66d908528c6caa47ca878e4115eec00c52e3046 | 47,070 |
import time
import calendar
def dates_to_epoch(d):
"""Recursively converts all dict values that are struct_times to Unix timestamps."""
for key, value in d.iteritems():
if hasattr(value, 'iteritems'):
d[key] = dates_to_epoch(value)
elif type(value) is time.struct_time:
... | 6a0a9a8f1a1636376973e65c4d3b4ff8a3603d3d | 47,072 |
def get_lineage(dag_id: str, execution_date: str):
""" Get Lineage details for a DagRun """
# Convert string datetime into actual datetime
try:
execution_dt = timezone.parse(execution_date)
except ValueError:
error_message = (
'Given execution date, {}, could not be identifie... | 27bbf233d249944300b96064ef6d513f06141b41 | 47,073 |
def get_release_versions(script_bool):
"""Prompt the user for the current and next release versions."""
version = vinfo['version']
if version.endswith('.dev'):
logger.info('Current development version: {0}'.format(version))
relver = version[:-4]
if not script_bool:
overri... | c1d2b451231d5d28b44c59a5008e96bcda59be47 | 47,074 |
from typing import Dict
from typing import Any
import logging
def build_log_config(level: str) -> Dict[str, Any]:
"""Build a log config from a level."""
return {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"basic": {"format": "%(asctime)s %(name)s %(lev... | e20a419ee6c69f6fa0eefbd51e5542349b1a1e8b | 47,075 |
def sum2(n):
"""
sum of n numbers - recursion
n - unsigned
"""
if n == 0:
return 0
if n == 1:
return 1
else:
return n + sum2(n-1) | 0ea4cea90c51077fdd0a2ea8a57f156c5096445e | 47,076 |
def i2n(i):
"""ip to number """
ip = [int(x) for x in i.split('.')]
return ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3] | 14496c2e7c83794a8364732c512f2d3cfdaba1d9 | 47,077 |
def compute_dist_with_visibility(array1, array2, vis1, vis2, dist_type='cosine', avg_by_vis_num=True):
"""Compute the euclidean or cosine distance of all pairs, considering part visibility.
In this version, if a query image does not has some part, don't calculate distance for this part.
If a query has one p... | 02b78a74e1971b1b18dfa8271dfca8edb8c89c31 | 47,078 |
def count_increases(report):
"""Meh
>>> count_increases([199, 200, 208, 210, 200, 207, 240, 269, 260, 263])
7
"""
return sum((1 if report[n] < report[n + 1] else 0 for n in range(len(report) - 1))) | bb38ae2de0f5e7a8f7f2904cdca62a7de80543ab | 47,079 |
def all_qos_for_topic(topic: str):
"""Build a list of (topic, QoS) pairs that covers all quality of service levels."""
return [(topic, QOS_0), (topic, QOS_1), (topic, QOS_2)] | 03efc78b3783b072e306dc4cab41bfe98ab11cd0 | 47,080 |
import numpy
def unumpy_to_numpy_matrix(arr):
"""
If arr in a unumpy.matrix, it is converted to a numpy.matrix.
Otherwise, it is returned unchanged.
"""
if isinstance(arr, matrix):
return arr.view(numpy.matrix)
else:
return arr | 1ae6cc435d2b17da3859ccb8ae62e17652e6b6e5 | 47,081 |
def abtest_power(
group_sizes,
baseline,
alt_lift,
alpha=0.05,
null_lift=0.0,
power=score_power,
lift="relative",
):
"""Power associated with an A/B Test
Parameters
----------
group_sizes : array_like
Number of experimental units in each group.
baseline : float... | dab28f575f61f7515fffdef3165d7aa4c229c9e9 | 47,082 |
from datetime import datetime
def get_image_creation_timestamp(client: Client, image: str, digest: str,) -> datetime:
"""
Return an image's creation timestamp.
Args:
client (Client): A client instance authenticated with a Bearer token and pointed
at version 2 of the Docker registry AP... | 3eb487d98bd07fd7479d3f496328a9a62949731c | 47,083 |
def _deconv_rl_gpu_fft(data_g, h_g, Niter=10):
"""
using fft_convolve
"""
if data_g.shape!=h_g.shape:
raise ValueError("data and h have to be same shape")
# set up some gpu buffers
u_g = OCLArray.empty(data_g.shape, np.complex64)
u_g.copy_buffer(data_g)
tmp_g = OCLArray.empt... | c94a02407fd1689e42610262a26081a76ebfe9f8 | 47,084 |
def pretty_entry(team):
"""Formats a single team entry in a PrettyTable"""
fields = ["Property", "Value"]
table = PrettyTable(field_names=fields)
table.align = "l"
table.title = team.name + " - " + team.player_first_name + " " + team.player_last_name
for attr, value in team.__dict__.items():
... | 3bc536787b0c509c28c1dc40936c6a27e97d9e1d | 47,085 |
def has_conflicts(path):
"""Does repository at path have any conflicts?"""
global svn
changed = svn.status(path, ignore_externals=True)
for f in changed:
if f.text_status == pysvn.wc_status_kind.conflicted:
return True
return False | dcb64e2c12d6b305318eb363889e5221dcdbd26c | 47,086 |
def first_n_false_reducer(data_list, n=0, **kwargs):
"""Reduce a list of boolean values to a single boolean value.
Parameters
----------
data_list : list
A list of dicts containing a "result" key which should correspond with a
boolean value.
n: int
The first n results in `d... | df845f4d195ba1e677f88c8176b22b85554aa51d | 47,087 |
def echo_msmt_induced_dephasing(qubits: list, angles: list, platf_cfg: str,
wait_time: float=0):
"""
Ramsey sequence that varies azimuthal phase instead of time. Works for
a single qubit or multiple qubits. The coherence of the LSQ is measured,
while the whole list of qub... | b332e438792b8f9b3f6d4029e94f1f13dc352988 | 47,088 |
import torch
def compute_huber_loss(predictions, labels, reduction='mean', delta=None):
"""Compute the Huber loss.
Args:
predictions (tensor): a batch of point predictions.
labels (tensor): the labels, an array of shape [batch_size].
reduction (str): the method to aggregate the result... | a4d72134366c1bb254a41823f7508a933dab2666 | 47,089 |
def serialize(hashObject):
"""
Serializes the internal state of the hash object passed in. Calling
restore() on the serialized value afterward will return an equivalent
hash object to the one passed.
:param hashObject: The hash object to serialize.
:type hashObject: _hashlib.HASH
:returns: ... | 84757accf3ec9ed01e5c06d764a41c4a7a5d4421 | 47,092 |
import dash
import dash_core_components as dcc
import dash_html_components as html
import omegaml as om
def create_app(context=None, server=None, uri=None, **kwargs):
"""
the script API execution entry point
:return: result
"""
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'... | c74426e790f2bcf88d55594ab8795408733041ab | 47,093 |
import torch
def overall_accuracy(input, target):
"""Overall accuracy for batches"""
if input.is_cuda:
s = torch.FloatTensor(1).cuda().zero_()
else:
s = torch.FloatTensor(1).zero_()
for i, c in enumerate(zip(input, target)):
s = s + OverallAccuracy().forward(c[0], c[1])
r... | 8d7cee43a27ede3cf61d041d12c9309eac328ef7 | 47,095 |
def _dataset_object_metadata(dataset_object):
"""Return mapping of dataset metadata key to value.
Args:
dataset_object: ArcPy geoprocessing describe data object for dataset.
Returns:
dict.
"""
meta = {"object": dataset_object}
meta["name"] = getattr(meta["object"], "name", None... | 20b9ea45cbb3e754072ad47e2e1c8ad763e35ab7 | 47,096 |
def solve_set_based(discretization,
rect_size,
obs_cpd=1):
"""
"""
disc = discretization.copy()
Q_ref = disc.get_output().get_reference_value()
simpleFunP.regular_partition_uniform_distribution_rectangle_size(
data_set=disc, Q_ref=Q_ref, rect_size=... | 7caca954e1bb82dab70580d84b540f6099f93f32 | 47,097 |
from typing import Iterable
from typing import Optional
def effective_sample_size(
weights: Iterable[float],
total_weight: Optional[float] = None,
) -> float:
"""Computes the "effective sample size" of the given weights
This value represents how "healthy" the underlying samples are. The lower
thi... | 6915abd0484dc4b08b47c1c88b6e19e2af5dd1c4 | 47,098 |
def split_pair_occurrence(input_str):
"""
Q9HD36.A79T (x11) → (Q9HD36.A79T, 11)
"""
if '(x' not in input_str:
return input_str, 1
pair, occurrence = [item.strip() for item in input_str.split()]
occurrence = int(occurrence[2:-1])
return pair, occurrence | 0812e907a97894ff6f2d94722874b3917ce30ad8 | 47,099 |
def index(request):
"""Blog home page view"""
blog_settings = BlogSettings.load()
post_list = Post.get_displayable().all()
page = request.GET.get("page")
ret_dict = {
'blog_settings': blog_settings,
'posts': __get_post_page(post_list, page=page,
blo... | 9dac202c7748b8f3aa1740f82fe254352e49c360 | 47,100 |
def find_joins(df, ids, downstream_col="downstream", upstream_col="upstream", expand=0):
"""Find the joins for a given segment id in a joins table.
Parameters
----------
df : DataFrame
data frame containing the joins
ids : list-like
ids to lookup in upstream or downstream columns
... | 39f16985ddd8e79338e520e56ba6ee793558d03f | 47,101 |
def velocity(sigma, xs, ys, X, Y):
"""
Generalizing the one source case:
xs, ys --> (1,)
X, Y --> (nx, ny)
sigma --> (1,)
To the several sources one:
xs, ys --> (ns, 1, 1)
X, Y --> (ns, nx, ny)
sigma --> (ns, 1, 1)
"""
sigma = np.atleast_1d(sigma)... | ab766a16e3bc27f269847d9e130430acd874e925 | 47,102 |
import functools
def rate_limit(limit, period):
"""This decorator implements rate limiting."""
def decorator(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
if current_app.config['USE_RATE_LIMITS']:
# generate a unique key to represent the decorated function a... | 78a83f85d24083ec7e1155326371a3cb26b56222 | 47,103 |
from typing import Optional
def get_sketch_details(sketch_id: Optional[int] = 0) -> Text:
"""Return back details about an existing sketch.
Args:
sketch_id (int): the sketch ID to check.
Returns:
string containing information about the sketch.
"""
sketch = None
state_obj = state.state()
if not... | 6730aa649b9b74275e3aa92b213b930fdeb2ef9d | 47,104 |
import copy
import torch
def dataProcessing(data_x, data_y, batch_size, training_ratio, validation_ratio,
FM_indices, bool_norm=False):
"""
Data preprocessing.
Parameters:
----------
data_x: 2D Array (nDOF x SampleNum).
The deformation data (x SampleNum) of al... | e7dac71df8e11be2839f77f2397660ff12578076 | 47,106 |
def ten_interp(x, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9):
"""``Approximation degree = 10``
"""
return (
a0
+ a1 * x
+ a2 * (x ** 2)
+ a3 * (x ** 3)
+ a4 * (x ** 4)
+ a5 * (x ** 5)
+ a6 * (x ** 6)
+ a7 * (x ** 7)... | 93ce278f784080602990f386164d71fd8290560f | 47,107 |
def mock_interface_settings_match(mock_interface_settings):
"""
Fixture that yields mock USB interface settings that is the correct USB class, subclass, and protocol.
"""
mock_interface_settings.getClass.return_value = libusb.USB_DEVICE_CLASS
mock_interface_settings.getSubClass.return_value = libusb... | ca97bf1af08abbc39407d99ec959caf425f2469e | 47,108 |
def multinomial_naive_bayes_inference(X, W, b):
"""Multinomial naive Bayes classifier inference.
Parameters
----------
X : ndarray, shape (m, n)
input features (one row per feature vector).
W : ndarray, shape (n, k)
weight vectors, each row representing a different class.
b : ... | 4107e7cc5dbf22fdc874fc50d5e0736df74841c4 | 47,109 |
def sort_dist_matrix(mat, row_col_names):
"""
sort the distance matrix by seg_id_nat
:return:
"""
df = pd.DataFrame(mat, columns=row_col_names, index=row_col_names)
df = df.sort_index(axis=0)
df = df.sort_index(axis=1)
sensor_id_to_ind = {}
for i, sensor_id in enumerate(df.columns):
... | 09144b94db1d2f22ca1543e0e52cbab831e52e1c | 47,110 |
def is_complete(step, lst):
"""
Check required field of question for complete state
Required: question is always require user response to be complete
Conditional: Optional question needed depends on reveal_response value of conditional_target.
"""
if not lst:
return False, []
questio... | 0ae26de169e9ee0eacfdb30cdf349345d42b8ca9 | 47,111 |
def mels_spectrogram(spec, sr, n_mels,
fmin=64, fmax=None, top_db=80.0):
""" Extracting mel-filter bands from power spectrum
(i.e. the output from function
`odin.preprocessing.signal.power_spectrogram`)
Parameters
----------
spec : array [nb_samples, n_fft]
power spectrum array
s... | d64f562b50a22704f3f0f94f2c6b3d06539b7ba9 | 47,112 |
import torch
def create_data_loader(data, batch_size=32, shuffle=True, drop_last=False):
""" Create a data loader given numpy array x and y
Args:
data: a tuple (x, y, z, ...) where they have common first shape dim.
Returns: Pytorch data loader
"""
if drop_last:
batch_size = min(... | 573c6d440812e8d9d504d621ace6db572c9acbb5 | 47,113 |
def set_order(order):
"""decorator to set callback's method order
usage:
@set_order(100)
def method(self):
pass
"""
def inner(meth):
def fn(*args, **kwargs):
return meth(*args, **kwargs)
fn._order = order
return fn
return inner | 60a051e87e9ad0b87511892d5d0545555049c1ab | 47,114 |
from typing import Tuple
def calculate_ci(
values: np.ndarray,
ci_level: float,
**kwargs,
) -> Tuple[np.ndarray, np.ndarray]:
"""Calculate confidence/credibility levels using percentiles.
Parameters
----------
values:
The values used to calculate percentiles.
ci_level:
... | cccff0595dcbfb1456a02d16f488997075492610 | 47,115 |
def display_calibration(probs,
actual,
*,
figure=None,
bins=100,
label=None,
show_ici=True,
alpha=0.05,
n_resamples=None,
... | 7f2545c76f2c37079d15e3874cd5f63421ad6fa1 | 47,117 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.