content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def read_starlight_output_syn_spec(lines):
""" read syn_spec of starlight output """
Nl_obs = len(lines)
wave = Column(np.zeros((Nl_obs, ), dtype=np.float), 'wave')
flux_obs = Column(np.zeros((Nl_obs, ), dtype=np.float), 'flux_obs')
flux_syn = Column(np.zeros((Nl_obs, ), dtype=np.float), 'flux_syn')... | e25aed3ff9294f07b1549b610030241895b78f67 | 3,647,100 |
def get_stations_trips(station_id):
"""
https://api.rasp.yandex.net/v1.0/schedule/ ?
apikey=<ключ>
& format=<формат>
& station=<код станции>
& lang=<язык>
& [date=<дата>]
& [transport_types=<тип транспорта>]
& [system=<текущая система кодирования>]
& [show_systems=<коды в ответе>]
"""
params = {
'apikey': RASP... | 8b841f19b135e7792e2f8d3aad642f38b2a6cd74 | 3,647,101 |
def _compute_pairwise_kpt_distance(a, b):
"""
Args:
a, b (poses): Two sets of poses to match
Each "poses" is represented as a list of 3x17 or 4x17 np.ndarray
"""
res = np.zeros((len(a), len(b)))
for i in range(len(a)):
for j in range(len(b)):
res[i, j] = pck_dista... | aaf4696292bb7d1e9377347d93d97da321787c6f | 3,647,102 |
def _extract_dialog_node_name(dialog_nodes):
"""
For each dialog_node (node_id) of type *standard*, check if *title exists*.
If exists, use the title for the node_name. otherwise, use the dialog_node
For all other cases, use the dialog_node
dialog_node: (dialog_node_title, dialog_node_type)
In... | 23121efa486c2da16a54b2441bb1435eec5b8b49 | 3,647,103 |
import os
def _get_content(tax_id):
"""Get Kazusa content, either from cached file or remotely."""
target_file = os.path.join(DATA_DIR, "%s.txt" % tax_id)
if not os.path.exists(target_file):
url = (
"http://www.kazusa.or.jp/codon/cgi-bin/showcodon.cgi?"
+ "aa=1&style=N&spe... | d9dafeed28101cf83ba652fcc5d4e92e7757ddc6 | 3,647,104 |
from typing import Dict
from typing import List
def search_all_entities(bsp, **search: Dict[str, str]) -> Dict[str, List[Dict[str, str]]]:
"""search_all_entities(key="value") -> {"LUMP": [{"key": "value", ...}]}"""
out = dict()
for LUMP_name in ("ENTITIES", *(f"ENTITIES_{s}" for s in ("env", "fx", "script... | ca24b50524cc96b35a605bebc5ead0d8d4342314 | 3,647,105 |
import re
def is_probably_beginning_of_sentence(line):
"""Return True if this line begins a new sentence."""
# Check heuristically for a parameter list.
for token in ['@', '-', r'\*']:
if re.search(r'\s' + token + r'\s', line):
return True
stripped_line = line.strip()
is_begin... | 68a6a2151b4559f0b95e0ac82a8a16bd06d9d1ff | 3,647,106 |
def default_attack_handler(deck, discard, hand, turn, supply, attack):
"""Handle some basic attacks in a default manner. Returns True iff the
attack was handled."""
covertool.cover("domsim.py:219")
if attack == COUNCIL_ROOM:
# Not really an attack, but this is an easy way to handle it.
... | 79745f30b5607348771ee6d5778202370e553a7b | 3,647,107 |
from sys import version
import inspect
def deprecate(remove_in, use_instead, module_name=None, name=None):
"""
Decorator that marks a function or class as deprecated.
When the function or class is used, a warning will be issued.
Args:
remove_in (str):
The version in which the ... | 40877f67df96053ebedfbb580082b1c89ea4de6f | 3,647,108 |
import os
def get_available_processors():
"""Return the list of available processors modules."""
modules = [item.replace('.py', '')
for item in os.listdir(PROCESSORS_DIR)
if isfile(join(PROCESSORS_DIR, item))]
return modules | 988d460e4b9c8662318bc0b15232993ef44212e0 | 3,647,109 |
def hello_world():
"""return bool if exists -> take in email"""
email = request.json['email']
c = conn.cursor()
c.execute("select * from Users where Users.email = {}".format(email))
result = False
conn.commit()
conn.close()
return result | c28b33c5106b51144d4b58f3bffd2ea128dd948a | 3,647,110 |
from typing import Callable
from typing import Optional
import torch
def get_model_relations(
model: Callable,
model_args: Optional[tuple] = None,
model_kwargs: Optional[dict] = None,
):
"""
Infer relations of RVs and plates from given model and optionally data.
See https://github.com/pyro-ppl... | b0cc8f58a70575492ba0c5efe7f282b0e9ab0a4e | 3,647,111 |
import os
def progress_enabled():
"""
Checks if progress is enabled. To disable:
export O4_PROGRESS=false
"""
return os.environ.get('O4_PROGRESS', 'true') == 'true' | f04b3375eb4150f23f377472eea659a8d03433ab | 3,647,112 |
from typing import Any
def is_valid_dim(x: Any) -> bool:
"""determine if the argument will be valid dim when included in torch.Size.
"""
return isinstance(x, int) and x > 0 | 09b8dd41b20a835583cd051868f13756e8383342 | 3,647,113 |
def compute_alpha(n, S_d, d_min):
"""
Approximate the alpha of a power law distribution.
Parameters
----------
n: int or np.array of int
Number of entries that are larger than or equal to d_min
S_d: float or np.array of float
Sum of log degrees in the distribution that are lar... | 9df2c39ccaa70e729b1bf2f7bfcc78cde0f649de | 3,647,114 |
from typing import Optional
def _head_object(
s3_conn: S3Client, bucket: str, key: str
) -> Optional[HeadObjectOutputTypeDef]:
"""Retrieve information about an object in S3 if it exists.
Args:
s3_conn: S3 connection to use for operations.
bucket: name of the bucket containing the key.
... | 3b7b239ea09bf3df75c9c9a3e3e19cba505d67a5 | 3,647,115 |
from operator import add
def Residual(feat_maps_in, feat_maps_out, prev_layer):
"""
A customizable residual unit with convolutional and shortcut blocks
Args:
feat_maps_in: number of channels/filters coming in, from input or previous layer
feat_maps_out: how many output channels/filters this bl... | cfb7345340785a8fc7b3068c2baa0e5452b189aa | 3,647,116 |
from typing import List
from datetime import datetime
def clean_detail_line_data(detail_row: List[str], date: str) -> List[str]:
"""
:param detail_row: uncleaned detail row
:param date: job data to be added to data
:return: a cleaned list of details fields
"""
if not detail_row:
print... | ff9c3b8f5079674bf9a727f4baedc264443dbdeb | 3,647,117 |
def lammps_prod(job):
"""Run npt ensemble production."""
in_script_name = "in.prod"
modify_submit_lammps(in_script_name, job.sp)
msg = f"sbatch submit.slurm {in_script_name} {job.sp.replica} {job.sp.temperature} {job.sp.pressure} {job.sp.cutoff}"
return msg | faa122a6e22f54028cd536f78c17094f9c1f07b4 | 3,647,118 |
def gather_tensors(tensors, indices):
"""Performs a tf.gather operation on a set of Tensors.
Args:
tensors: A potentially nested tuple or list of Tensors.
indices: The indices to use for the gather operation.
Returns:
gathered_tensors: A potentially nested tuple or list of Tensors with the
sa... | 68fd88121cdca7beb13f3f5633401ddb420f34d4 | 3,647,119 |
import logging
def _get_log_level(log_level_name):
"""
Get numeric log level corresponding to specified log level name
"""
# TODO: Is there a built-in method to do a reverse lookup?
if log_level_name == LOG_LEVEL_NAME_CRITICAL:
return logging.CRITICAL
elif log_level_name == LOG_LEVEL... | 47b4f238069905f9c9f8a668cb18766a8f883a5e | 3,647,120 |
import types
def is_iterator(obj):
"""
Predicate that returns whether an object is an iterator.
"""
return type(obj) == types.GeneratorType or ('__iter__' in dir(obj) and 'next' in dir(obj)) | db57a2a1f171a48cc43ba4c248387191780dfd04 | 3,647,121 |
import shutil
def delete_entries(keytab_file: str, slots: t.List[int]) -> bool:
"""
Deletes one or more entries from a Kerberos keytab.
This function will only delete slots that exist within the keylist.
Once the slots are deleted, the current keylist will be written to
a temporary file. Th... | cc488778abdc75a9814702642fcfc9b245b6a99c | 3,647,122 |
def detect(environ, context=None):
"""
parse HTTP user agent string and detect a mobile device.
"""
context = context or Context()
try:
## if key 'HTTP_USER_AGENT' doesn't exist,
## we are not able to decide agent class in the first place.
## so raise KeyError to return NonMo... | 2977cb2847c4917904cc096c5787b6ddb3a889b9 | 3,647,123 |
import os
import urllib
def _sniff_scheme(uri_as_string):
"""Returns the scheme of the URL only, as a string."""
#
# urlsplit doesn't work on Windows -- it parses the drive as the scheme...
# no protocol given => assume a local file
#
if os.name == 'nt' and '://' not in uri_as_string:
... | 0dcff614b026a5bbaf87fce56ed1465d78eda58b | 3,647,124 |
async def get_product(id: UUID4): # noqa: A002
"""Return ProductGinoModel instance."""
return await ProductGinoModel.get_or_404(id) | f7988faf08da081a1922f8df24b843be67658c16 | 3,647,125 |
def LSIIR_unc(H,UH,Nb,Na,f,Fs,tau=0):
"""Design of stabel IIR filter as fit to reciprocal of given frequency response with uncertainty
Least-squares fit of a digital IIR filter to the reciprocal of a given set
of frequency response values with given associated uncertainty. Propagation of uncertainties is
carried o... | d262065fdfe49514101ff65a6c4ea7329e8aef84 | 3,647,126 |
import time
def genMeasureCircuit(H, Nq, commutativity_type, clique_cover_method=BronKerbosch):
"""
Take in a given Hamiltonian, H, and produce the minimum number of
necessary circuits to measure each term of H.
Returns:
List[QuantumCircuits]
"""
start_time = time.time()
term_r... | 1128592a61da7601e41c0328abbf8770f187d009 | 3,647,127 |
def run_test(session, m, data, batch_size, num_steps):
"""Runs the model on the given data."""
costs = 0.0
iters = 0
state = session.run(m.initial_state)
for step, (x, y) in enumerate(reader.dataset_iterator(data, batch_size, num_steps)):
cost, state = session.run([m.cost, m.final_state]... | 681a11e7cd52c0f690a3ad79e69fac4951906796 | 3,647,128 |
def table_to_dict(table):
"""Convert Astropy Table to Python dict.
Numpy arrays are converted to lists. This Can work with multi-dimensional
array columns, by representing them as list of list.
e.g. This is useful in the following situation.
foo = Table.read('foo.fits')
foo.to_pandas(... | 8ad9206222101bbd4d40913e3b43c8ffee9dd6ad | 3,647,129 |
def margin_loss(y_true, y_pred):
"""
Margin loss for Eq.(4). When y_true[i, :] contains not just one `1`, this loss should work too. Not test it.
:param y_true: [None, n_classes]
:param y_pred: [None, num_capsule]
:return: a scalar loss value.
"""
L = y_true * K.square(K.maximum(0., 0.9 - y_... | 252c26949b6255742df90cc9c83a586dfcbb8ac6 | 3,647,130 |
def strip_quotes(string):
"""Remove quotes from front and back of string
>>> strip_quotes('"fred"') == 'fred'
True
"""
if not string:
return string
first_ = string[0]
last = string[-1]
if first_ == last and first_ in '"\'':
return string[1:-1]
return string | 7e10d37e5b5bb4569c88b4de17ffde31a4456e15 | 3,647,131 |
from xclim.core.indicator import registry
def generate_local_dict(locale: str, init_english: bool = False):
"""Generate a dictionary with keys for each indicators and translatable attributes.
Parameters
----------
locale : str
Locale in the IETF format
init_english : bool
If True,... | 34398b297bb269df4668a09d055a69d409fe7bec | 3,647,132 |
import csv
def generate_scheme_from_file(filename=None, fileobj=None, filetype='bson', alimit=1000, verbose=0, encoding='utf8', delimiter=",", quotechar='"'):
"""Generates schema of the data BSON file"""
if not filetype and filename is not None:
filetype = __get_filetype_by_ext(filename)
datacache... | 5a160dabd6141724075e3645342b804b556094d6 | 3,647,133 |
def getTests():
"""Returns a dictionary of document samples for the Entity Types Person, Location, and Organization.
Returns:
[type] -- Returns a dictionary of document samples for the Entity Types Person, Location, and Organization.
"""
personDocument = gtWorkingCopy.find_one({"$and": [{'enti... | 63d1ff2e2f77f33ef634d495a1d318f688a1d51b | 3,647,134 |
def ts_cor(a, b, min_sample = 3, axis = 0, data = None, state = None):
"""
ts_cor(a) is equivalent to a.cor()[0][1]
- supports numpy arrays
- handles nan
- supports state management
:Example: matching pandas
-------------------------
>>> # create sample data:
>>> from pyg_... | 217b8c2196c270ffe22905884586b7466eb59c88 | 3,647,135 |
def get_robin_bndry_conditions(kappa,alpha,Vh):
"""
Do not pass element=function_space.ufl_element()
as want forcing to be a scalar pass degree instead
"""
bndry_obj = get_2d_unit_square_mesh_boundaries()
boundary_conditions=[]
ii=0
for phys_var in [0,1]:
for normal in [1,-1]:
... | 65bb3f9d216ddc146866cf8aa570c2ee73e6d7f2 | 3,647,136 |
def get_prop_datatypes(labels, propnames, MB=None):
"""Retrieve the per-property output datatypes."""
rp = regionprops(labels, intensity_image=MB, cache=True)
datatypes = []
for propname in propnames:
if np.array(rp[0][propname]).dtype == 'int64':
datatypes.append('int32')
e... | b706e724bee867a23c290580f2b865d967946d1b | 3,647,137 |
from typing import Tuple
def parse_html(html: str) -> Tuple[str, str]:
"""
This function parses the html, strips the tags an return
the title and the body of the html file.
Parameters
----------
html : str
The HTML text
Returns
-------
Tuple[str, str]
A tuple of (... | a57e5ae50c8eae16c06333a3de5cc388524504ab | 3,647,138 |
from .._common import header
def block(keyword, multi=False, noend=False):
"""Decorate block writing functions."""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
head_fmt = "{:5}{}" if noend else "{:5}{}\n"
out = [head_fmt.format(keyword, header)]
... | 5a0ec1cdec6c2f956d47d13f7beea41814a0db5d | 3,647,139 |
def data(path):
"""Get the file from the specified path from the data directory.
Parameters
----------
path : str
The relative path to the file in the data directory.
Returns
-------
file : File
The requested file.
"""
return send_from_directory(app.config['DATA_DI... | 8f1cde6d248026fbadd2a81519f8f2beed7ab308 | 3,647,140 |
import requests
import logging
def search_software_fuzzy(query, max=None, csv_filename=None):
"""Returns a list of dict for the software results.
"""
results = _search_software(query)
num = 0
softwares = []
while True:
for r in results:
r = _remove_useless_keys(r)
... | ef0124670b02b148f918d3f573e22ca3f646cf96 | 3,647,141 |
def fitCirc(x,y,xerr = None, rIni = None, aveR=False):
"""
Performs a circle fit to data using least square residuals.
Parameters
----------
x : An array of length N.
y : An array of length N.
xerr : None or an array of length N,
If provided, it is the standard-deviation of poi... | fd384526b385f33a8ddd91c7c631afb204afa0db | 3,647,142 |
def get_clients():
"""
Return current clients
---
tags:
- clients
operationId: listClients
produces:
- application/json
schemes: ['http', 'https']
responses:
200:
description: List of clients
schema:
type: array
items:
$re... | e38c8da6094303415bc285f847b9915a4a55f7e7 | 3,647,143 |
def GetInstanceListForHypervisor(hname, hvparams=None,
get_hv_fn=hypervisor.GetHypervisor):
"""Provides a list of instances of the given hypervisor.
@type hname: string
@param hname: name of the hypervisor
@type hvparams: dict of strings
@param hvparams: hypervisor parameters... | b42e19af31d17ff6ca2343ce274572f15950c8d5 | 3,647,144 |
def is_nersc_system(system = system()):
"""Whether current system is a supported NERSC system."""
return (system is not None) and (system in _system_params.keys()) | 6ac968e45f7d586d56b28578eb685f705abafe0f | 3,647,145 |
def is_string_type_suspicious_score(confidence_score, params):
"""
determine if string type confidence score is suspicious in reputation_params
"""
return not isinstance(confidence_score, int) and CONFIDENCE_LEVEL_PRIORITY.get(
params['override_confidence_level_suspicious'], 10) <= CONFIDENC... | 9282ca6e58638fb240ca4c0b752a6dddbaa05255 | 3,647,146 |
def align_embeddings(base_embed, other_embed, sample_size=1):
"""Fit the regression that aligns model1 and model2."""
regression = fit_w2v_regression(base_embed, other_embed, sample_size)
aligned_model = apply_w2v_regression(base_embed, regression)
return aligned_model | 3e017f1a0049cac40f6f7311be2dd531895fc436 | 3,647,147 |
from typing import Optional
import logging
def validate_dict_keys(dict_to_check: dict,
allowed_keys: set,
necessary_keys: Optional[set] = None,
dict_name: Optional[str] = None) -> bool:
"""If you use dictionaries to pass parameters, there are tw... | ede2995994b5616ae4f2f8cb02799295cc008f7f | 3,647,148 |
def data_unmerged():
"""
Load HEWL diffraction data from APS 24-ID-C
"""
datapath = ["data", "data_unmerged.mtz"]
return load_dataset(datapath) | f7fb453f617191e19f948fc9097d10bc104478b3 | 3,647,149 |
def copy(object, *args):
"""Copy the object."""
copiedWrapper = wrapCopy( object )
try: copiedWrapper.name = copiedWrapper.name + "_Copy"
except AttributeError: pass
return copiedWrapper.createAndFillObject(None, *args) | fd5e7dfb3e5d6c920ebcb73477d19c9a8be152d3 | 3,647,150 |
def convert_to_n0(n):
"""
Convert count vector to vector of "greater than" counts.
Parameters
-------
n : 1D array, size K
each entry k represents the count of items assigned to comp k.
Returns
-------
n0 : 1D array, size K
each entry k gives the total count of items at... | c75ce9e68bc949ef9fed55283c4dd2a424acadc7 | 3,647,151 |
def application(environ, start_response):
"""Serve the button HTML."""
with open('wsgi/button.html') as f:
response_body = f.read()
status = '200 OK'
response_headers = [
('Content-Type', 'text/html'),
('Content-Length', str(len(response_body))),
]
start_response(status, ... | 97f1f793f234dbd3c29e9c4a791a224ba32c984b | 3,647,152 |
def get_handler():
"""
Return the handler configured by the most recent call to
:func:`configure`.
If :func:`configure` has not yet been called, this returns ``None``.
"""
return current_handler | 0508343f6775544204de9a35186d92ddf829533f | 3,647,153 |
def display_rf_feature_importance(cache, save_location: str = None):
"""
Displays which pixels have the most influence in the model's decision.
This is based on sklearn,ensemble.RandomForestClassifier's feature_importance array
Parameters
----------
save_location : str
the location to s... | 86fc921f4f3ffcd004a2995b0a82f69ba3088e5a | 3,647,154 |
def first_order(A, AB, B):
"""
First order estimator following Saltelli et al. 2010 CPC, normalized by
sample variance
"""
return np.mean(B * (AB - A), axis=0) / np.var(np.r_[A, B], axis=0) | 3a94fdcf17a10242fb07d60e1468a21e17182a25 | 3,647,155 |
import array
def mod_df(arr,timevar,istart,istop,mod_name,ts):
"""
return time series (DataFrame) from model interpolated onto uniform time base
"""
t=timevar.points[istart:istop]
jd = timevar.units.num2date(t)
# eliminate any data that is closer together than 10 seconds
# this was requir... | 6740d74bcfa82a3f813b991b8593b9c2cd5fddb5 | 3,647,156 |
def hydrate_reserve_state(data={}):
"""
Given a dictionary, allow the viewmodel to hydrate the data needed by this view
"""
vm = State()
return vm.hydrate(data) | 203c9c4143713cf8f386a2ac95d91b50a9525a3c | 3,647,157 |
def get_devstudio_versions ():
"""Get list of devstudio versions from the Windows registry. Return a
list of strings containing version numbers; the list will be
empty if we were unable to access the registry (eg. couldn't import
a registry-access module) or the appropriate registry keys weren... | ad02e38e216649cb0f29cfffe256aee7b79d80ea | 3,647,158 |
def mapDictToProfile(wordD, tdm):
"""
Take the document in as a dictionary with word:wordcount format, and map
it to a p profile
Parameters
----------
wordD : Dictionary
Dictionary where the keys are words, and the values are the corrosponding word
count
tdm : termDocMatrix o... | df178e7a6857ff9f85caedbfb5abac77e4f04d55 | 3,647,159 |
from typing import VT
from typing import Tuple
from typing import List
def _to_tikz(g: BaseGraph[VT,ET],
xoffset:FloatInt=0, yoffset:FloatInt=0, idoffset:int=0) -> Tuple[List[str],List[str]]:
"""Converts a ZX-graph ``g`` to a string representing a tikz diagram.
The optional arguments are used by :func:`t... | 0c5fab1fcd0f5db9e8b7d267de5e4b5ea2444046 | 3,647,160 |
def _fix_server_adress(raw_server):
""" Prepend http:// there. """
if not raw_server.startswith("http://"):
raw_server = "http://" + raw_server
return raw_server | 64171be5033930fd5ecb3cd275cc0d859b7e6ca0 | 3,647,161 |
def _parse_output_keys(val):
"""Parse expected output keys from string, handling records.
"""
out = {}
for k in val.split(","):
# record output
if ":" in k:
name, attrs = k.split(":")
out[name] = attrs.split(";")
else:
out[k] = None
return ... | abd739026574b1a3fa87c42d2719d172e36a1c4a | 3,647,162 |
import sqlite3
def check(sync_urls: list, cursor: sqlite3.Cursor, db: sqlite3.Connection, status: str):
"""Checking update in the back.
Args:
sync_urls: URL(s) to be checked as a list
cursor: Cursor object of sqlite3
db: Connection object of sqlite3
status: 'viewed' or 'unview... | a9d7160d7f08d51b4ef596692fa10136f1f21375 | 3,647,163 |
from typing import Dict
from typing import Tuple
from typing import OrderedDict
from typing import Type
import torch
def _get_output_structure(
text: str,
model: PreTrainedModel,
tokenizer: PreTrainedTokenizer,
tokenizer_args: Dict,
) -> Tuple[OrderedDict, Type]:
"""Function needed for saving in a... | 0f268b3fb9208b8f447b0c030744b9ce310049e6 | 3,647,164 |
def encode_board(board):
""" Encode the 2D board list to a 64-bit integer """
new_board = 0
for row in board.board:
for tile in row:
new_board <<= 4
if tile is not None:
new_board += tile.val
return new_board | 2c85964902dc3b2d097e30b71f11e7c17b80297a | 3,647,165 |
def get_symbol(i):
"""Get the symbol corresponding to int ``i`` - runs through the usual 52
letters before resorting to unicode characters, starting at ``chr(192)``.
Examples
--------
>>> get_symbol(2)
'c'
>>> oe.get_symbol(200)
'Ŕ'
>>> oe.get_symbol(20000)
'京'
"""
if ... | e6e9a91fa48e04ed591b22fba62bf2ba6fd5d81f | 3,647,166 |
def longest_common_substring(string1, string2):
"""
Function to find the longest common substring of two strings
"""
m = [[0] * (1 + len(string2)) for i in range(1 + len(string1))]
longest, x_longest = 0, 0
for x in range(1, 1 + len(string1)):
for y in range(1, 1 + len(string2)):
... | f567c629f5bd02143f0ed6bbbdc11f0e59e5f4bd | 3,647,167 |
def elapsed_time_id(trace, event_index: int):
"""Calculate elapsed time by event index in trace
:param trace:
:param event_index:
:return:
"""
try:
event = trace[event_index]
except IndexError:
# catch for 0 padding.
# calculate using the last event in trace
... | 7e94531f13458fc32ca5d971178b79fc13aa65f8 | 3,647,168 |
def build_candidate_digest(proof, leaf_hash):
"""
Build the candidate digest representing the entire ledger from the Proof hashes.
:type proof: dict
:param proof: The Proof object.
:type leaf_hash: bytes
:param leaf_hash: The revision hash to pair with the first hash in the Proof hashes list.
... | 1434cf5e1da9edbd6b41caacd42a67df235267f5 | 3,647,169 |
from typing import Iterable
import torch
def confusion_matrix_eval(cnn, data_loader):
"""Retrieves false positives and false negatives for further investigation
Parameters
----------
cnn : torchvision.models
A trained pytorch model.
data_loader : torch.utils.data.DataLoader
A data... | 411a7d95f7713ff00dbcb7b25db7bd497f427593 | 3,647,170 |
import hashlib
def match_by_hashed_faceting(*keys):
"""Match method 3 - Hashed Faceted Search"""
matches = []
hfs = []
for i in range(len(__lookup_attrs__)):
key = [x for x in keys if x[0] == __lookup_attrs__[i]]
if key:
hfs.append(key[0])
hashed_val = hashlib.sha256(str(hfs).encode('utf-8')).... | b2b849583e732747b42a4d4e7ec56c1090ddb1a8 | 3,647,171 |
def get_derivative_density_matrix(mat_diag,mat_Rabi,sigma_moins_array,**kwargs):
"""
Returns function for t-evolution using the numerical integration of the density matrix
\dot{\rho}=-i(H_eff \rho-\rho H_eff^{\dagger})
+\Gamma \sum_j \sigma_j^_ \rho \sigma_j^+
"""
dim=len(mat_diag)
tunneling... | 1dc1321a6578b6bd9b3c5e937f9c7ed8a787f5a6 | 3,647,172 |
import os
import threading
def start_http_server():
"""Starts a simple http server for the test files"""
# For the http handler
os.chdir(TEST_FILES_DIR)
handler = SimpleHTTPServer.SimpleHTTPRequestHandler
handler.extensions_map['.html'] = 'text/html; charset=UTF-8'
httpd = ThreadedTCPServer(("... | 30455072e0213d8a509caccfe1c0bc50d6b33512 | 3,647,173 |
def area_of_polygon(polygon):
"""
Returns the area of an OpenQuake polygon in square kilometres
"""
lon0 = np.mean(polygon.lons)
lat0 = np.mean(polygon.lats)
# Transform to lamber equal area projection
x, y = lonlat_to_laea(polygon.lons, polygon.lats, lon0, lat0)
# Build shapely polygons... | bc57bd58b2ae64b33e34b1bee4582e3c6733fe4d | 3,647,174 |
def build_dataset_values(claim_object, data_value):
""" Build results with different datasets.
Parameters:
claim_object (obj): Onject to modify and add to rows .
data_value (obj): result object
Returns:
Modified claim_boject according to data_value.type
"""
... | f3d267a4e9ac099f6d2313deffb2f45d35b90217 | 3,647,175 |
import os
def get_yolk_dir():
"""Return location we store config files and data."""
return os.path.abspath('%s/.yolk' % os.path.expanduser('~')) | 788e44d2f95ce720d10154465198a3f86625453b | 3,647,176 |
def gen_csrv_msome(shape, n_parts, mic_rad, min_ip_dst):
"""
Generates a list of 3D coordinates and rotations a CSRV pattern
:param shape: tomogram shape
:param n_parts: number of particles to try to generate
:param mic_rad: microsome radius
:param min_ip_dst: minimum interparticle distance
... | ba0033859e4e18b55d877a6db957b64674171d74 | 3,647,177 |
def electra_model(request):
"""Exposes the command-line option to a test case."""
electra_model_path = request.config.getoption("--electra_model")
if not electra_model_path:
pytest.skip("No --electra_model given")
else:
return electra_model_path | 9273ddfe253c7dc0ab3307b4fb6f009aa806821b | 3,647,178 |
def By_2d_approximation(x, w, d, j):
"""Approximation of By_surface valid except near edges of slab."""
mu0_over_4pi = 1e-7
return 2e-7 * j * d * np.log((w/2 + x) / (w/2 - x)) | 2d64957d0dbec677b6d8b6e825c18ac32b25f7e7 | 3,647,179 |
from typing import Dict
from pathlib import Path
from typing import List
def read_lists(paths: Dict[str, Path]) -> Dict[str, List[str]]:
"""Return a dictionary of song lists read from file.
Arguments:
paths {Dict[str, Path]} -- A dictionary of type returned by find_paths.
Returns:
Dict[s... | 13d6618293e17e5a7388ca9f3d44ffffe913f482 | 3,647,180 |
def learningCurve(theta, X_train, y_train, X_cv, y_cv, lambda_param):
"""
:param X_train:
:param y_train:
:param X_cv:
:param y_cv:
:param lambda_param:
:return:
"""
number_examples = y_train.shape[0]
J_train, J_cv = [], []
for i in range(1, number_examples + 1):
th... | c15f5b3af34beb4c20982c2b339919c50b3336b1 | 3,647,181 |
def reduce_labels(y):
"""Reduziert die Themen und Disziplinen auf die höchste Hierarchiestufe"""
labels = [] # new y
themes = []
disciplines = []
for i, elements in enumerate(y):
tmp_all_labels = []
tmp_themes = []
tmp_disciplines = []
#print("... | 9dc5d3b1d07f7fd7f72911b891533d90bae4ad63 | 3,647,182 |
def api_get_categories(self):
"""
Gets a list of all the categories.
"""
response = TestCategory.objects.all()
s = ""
for cat in response:
s += b64(cat.name) + "," + b64(cat.description) + ","
return HttpResponse(s.rstrip(',')) | f7c523437c8f9d538bb4c5411232458ae3e10450 | 3,647,183 |
def histtab(items, headers=None, item="item", count="count", percent="percent",
cols=None):
"""Make a histogram table."""
if cols is not None:
# items is a Table.
items = items.as_tuples(cols=cols)
if headers is None:
headers = cols + [count, percent]
if head... | ca6bc51d80a179f693ca84fa27753908dcf30ca8 | 3,647,184 |
from rdkit import Chem
def read_sdf_to_mol(sdf_file, sanitize=False, add_hs=False, remove_hs=False):
"""Reads a list of molecules from an SDF file.
:param add_hs: Specifies whether to add hydrogens. Defaults to False
:type add_hs: bool
:param remove_hs: Specifies whether to remove hydrogens. Defaults... | c1917b5dcdad3a88bfd2b181e6c1e757393a4de8 | 3,647,185 |
import math
def search_and_score(milvus_collection_name, mongo_name, field_name, vectors,
topk, nprobe, inner_score_mode: str):
"""
search vectors from milvus and score by inner field score mode
:param milvus_collection_name: collection name will be search
:param mongo_name: mongo... | 885d0e912e76a379dbb55b15945f898c419254bc | 3,647,186 |
def fix_simulation():
""" Create instance of Simulation class."""
return Simulation() | fc36a880342bb6e6be6e6735c3ebd09891d09502 | 3,647,187 |
def build_tree(vectors, algorithm='kd_tree', metric='minkowski', **kwargs):
"""Build NearestNeighbors tree."""
kwargs.pop('algorithm', None)
kwargs.pop('metric', None)
return NearestNeighbors(algorithm=algorithm, metric=metric,
**kwargs).fit(vectors) | 42df608eb0e4e5f420bd0a8391ad748b18eb5f4f | 3,647,188 |
def _expectedValues():
"""
These values are expected for well exposed spot data. The dictionary has a tuple for each wavelength.
Note that for example focus is data set dependent and should be used only as an indicator of a possible value.
keys: l600, l700, l800, l890
tuple = [radius, focus, width... | 7ddd7031313ac5c90f022a6a60c81ad12b4d5dac | 3,647,189 |
import time
def storyOne(player):
"""First Story Event"""
player.story += 1
clear()
print("The dust gathers around, swirling, shaking, taking some sort of shape.")
time.sleep(2)
print("Its the bloody hermit again!")
time.sleep(2)
clear()
print("Hermit: Greetings, " + str(player.nam... | fbaff47f27c5ec474caa73d2f87d77029f4814a4 | 3,647,190 |
def mcat(i):
"""Concatenate a list of matrices into a single matrix using separators
',' and ';'. The ',' means horizontal concatenation and the ';' means
vertical concatenation.
"""
if i is None:
return marray()
# calculate the shape
rows = [[]]
final_rows = 0
final_cols = ... | ef424209b7c8f2e08d549bccf62a58c24c5048f3 | 3,647,191 |
import h5py
import torch
import tensorflow
from typing import Dict
from typing import Union
def get_optional_info() -> Dict[str, Union[str, bool]]:
"""Get optional package info (tensorflow, pytorch, hdf5_bloscfilter, etc.)
Returns
-------
Dict[str, Union[str, False]]
package name, package ver... | 07255d4e889b669497628cd9b9c6e102ceb22bbf | 3,647,192 |
import timeit
def epsilon_experiment(dataset, n: int, eps_values: list):
"""
Function for the experiment explained in part (g).
eps_values is a list, such as: [0.0001, 0.001, 0.005, 0.01, 0.05, 0.1, 1.0]
Returns the errors as a list: [9786.5, 1234.5, ...] such that 9786.5 is the error when... | 7aabe10dd97f594533a2da4a901b61790c8435f8 | 3,647,193 |
def infer_scaletype(scales):
"""Infer whether `scales` is linearly or exponentially distributed (if latter,
also infers `nv`). Used internally on `scales` and `ssq_freqs`.
Returns one of: 'linear', 'log', 'log-piecewise'
"""
scales = asnumpy(scales).reshape(-1, 1)
if not isinstance(scales, np.n... | 50e961118a3c97835d279832b399ef72946f4b4a | 3,647,194 |
from googleapiclient.http import build_http
import google
def authorized_http(credentials):
"""Returns an http client that is authorized with the given credentials.
Args:
credentials (Union[
google.auth.credentials.Credentials,
oauth2client.client.Credentials]): The credential... | 21d7a05e9d99f0a6e8414da5925f0d69224f846c | 3,647,195 |
from typing import Optional
from typing import List
from typing import Tuple
from typing import Callable
def add_grating_couplers_with_loopback_fiber_array(
component: Component,
grating_coupler: ComponentSpec = grating_coupler_te,
excluded_ports: Optional[List[str]] = None,
grating_separation: float ... | 4452851ecc05f46ebf46cd92d6edbea9062bae35 | 3,647,196 |
import os
import logging
from datetime import datetime
import json
def FEBA_Save_Tables(gene_fit_d, genes_df, organism_name_str,
op_dir, exps_df,
cfg=None,
writeImage=False, debug=False):
"""
Args:
gene_fit_d (python dict): Documentation ... | 6da02333d462afe79f9189cde3b3c92cd6793955 | 3,647,197 |
import pytz
from datetime import datetime
import json
def auto_update_function(cities):
"""Auto-update weather function
The function takes a list of the cities to update.
If the error connecting to sources - an error with
a status of 500 and JSON with the cause of the error and URL.
... | 6c57685b1d4a4c62d6225df17dd1bbee6c1a3934 | 3,647,198 |
def absolute_sum_of_changes(x):
"""
Returns the sum over the absolute value of consecutive changes in the series x
.. math::
\\sum_{i=1, \ldots, n-1} \\mid x_{i+1}- x_i \\mid
:param x: the time series to calculate the feature of
:type x: pandas.Series
:return: the value of this featur... | b9cc5109335b754d7d6c8014af5d84e75cd94723 | 3,647,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.