content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def multi_class_bss(predictions: np.ndarray, targets: np.ndarray) -> float:
"""
Brier Skill Score:
bss = 1 - bs / bs_{ref}
bs_{ref} will be computed for a model that makes a predictions according to the prevalance of each class in dataset
:param predictions: probability score. Expected Shape [N, C... | d932649e2eb1a1b91aa2cf3882b0f4b74531dea7 | 7,565 |
def get_arxiv_id_or_ascl_id(result_record):
"""
:param result_record:
:return:
"""
identifiers = result_record.get("identifier", [])
for identifier in identifiers:
if "arXiv:" in identifier:
return identifier.replace("arXiv:", "")
if "ascl:" in identifier:
... | 4270fe7ad8f2136ad5d53272acb02aaf60970ea3 | 7,566 |
from typing import Mapping
from typing import Tuple
import torch
def get_query_claim_similarities(
sim: Mapping[Tuple[str, int], float],
softmax: bool,
) -> Mapping[Tuple[str, int], float]:
"""
Preprocess query claim similarities.
:param sim:
A mapping from (premise_id, claim_id) to the l... | 6f1eb9495c7b7243f544564315ca3ae09f31da92 | 7,567 |
import re
def regexp(options: dict):
"""
Apply a regexp method to the dataset
:param options: contains two values:
- find: which string should be find
- replace: string that will replace the find string
"""
def apply_regexp(dataset, tag):
"""
Apply a regexp to the... | 20cfaf4f9286ad582dc9f4fea4184cf1c7d0de34 | 7,568 |
def do_one_subject(sub_curr, params, verbose=False):
"""
launch sessions processing for sub_curr
parameters:
-----------
sub_curr: dict
contains subject base directory
contains subject index
params: dict
parameters for layout, data and analysis
... | 68ba212eeccde0197c587a0b929198b2a042328d | 7,569 |
def comp_skin_effect(self, freq, T_op=20, T_ref=20, type_skin_effect=1):
"""Compute the skin effect factor for the conductor
Parameters
----------
self : Conductor
an Conductor object
freq: float
electrical frequency [Hz]
T_op: float
Conductor operational temperature [de... | b71f4385d600713f3fff559e0836d9c532b79b73 | 7,570 |
import glob
def find_paths(initial_path, extension):
"""
From a path, return all the files of a given extension inside.
:param initial_path: the initial directory of search
:param extension: the extension of the files to be searched
:return: list of paths inside the initial path
"""
path... | 0220127050b765feaf423c195d020d65ece8d22e | 7,572 |
def ridge_line(df_act, t_range='day', n=1000):
"""
https://plotly.com/python/violin/
for one day plot the activity distribution over the day
- sample uniform from each interval
"""
df = activities_dist(df_act.copy(), t_range, n)
colors = n_colors('rgb(5, 200, 200)', 'rgb(200, 10, 10... | 7fa2e4946a8de5df6e5c7697236c939703133409 | 7,573 |
def op(name,
value,
display_name=None,
description=None,
collections=None):
"""Create a TensorFlow summary op to record data associated with a particular the given guest.
Arguments:
name: A name for this summary operation.
guest: A rank-0 string `Tensor`.
display_n... | f2a6b65299c417e460f6ca2e41fc82e061b29f30 | 7,574 |
def select_only_top_n_common_types(dataset: pd.DataFrame, n: int = 10) -> pd.DataFrame:
"""
First find the most popular 'n' types. Remove any uncommon types from the
dataset
:param dataset: The complete dataset
:param n: The number of top types to select
:return: Return the dataframe once the t... | b4d95682d1abbf062b4730213cefc6da71a5c605 | 7,575 |
def __one_both_closed(x, y, c = None, l = None):
"""convert coordinates to zero-based, both strand, open/closed coordinates.
Parameters are from, to, is_positive_strand, length of contig.
"""
return x - 1, y | ce4dfca3cc347de925f4c26460e486fb38a2d5e5 | 7,577 |
def get_corners(img, sigma=1, alpha=0.05, thresh=1000):
""" Returns the detected corners as a list of tuples """
ret = []
i_x = diff_x(img)
i_y = diff_y(img)
i_xx = ndimage.gaussian_filter(i_x ** 2, sigma=sigma)
i_yy = ndimage.gaussian_filter(i_y ** 2, sigma=sigma)
i_xy = ndimage.gaussian_fi... | d581df8daff7f20e2f15b5eb5af9ea686c0520e4 | 7,578 |
import numpy
def add_param_starts(this_starts, params_req, global_conf, run_period_len, start_values_min, start_values_max):
"""Process the param starts information taken from the generator, and add it to
the array being constructed.
Inputs:
this_starts: a tuple with (starts_min, starts_max),... | b50f538b9d5096fe6061b4b990ccb9ad6ba05ef6 | 7,579 |
def pareto(data, name=None, exp=None, minval=None, maxval=None, **kwargs):
"""the pareto distribution: val ~ val**exp | minval <= val < maxval
"""
assert (exp is not None) and (minval is not None) and (maxval is not None), \
'must supply exp, minval, and maxval!' ### done to make command-line argume... | 8607bf6783ba5e8be95d2b4319a42e8723b71da0 | 7,580 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_ansible_tower package"""
reload_params = {"package": u"fn_ansible_tower",
"incident_fields": [],
"action_fields": [u"ansible_tower_arguments", u"ansible_tower_credential", u"ansible_tower_hosts",... | 49dee7d9a1dc297ff31f51e4583740c353831cd9 | 7,581 |
def get_text_item(text):
"""Converts a text into a tokenized text item
:param text:
:return:
"""
if config['data']['lowercased']:
text = text.lower()
question_tokens = [Token(t) for t in word_tokenize(text)]
question_sentence = Sentence(' '.join([t.text for t in question_tokens]), q... | 79fdec4cdcb419751d49a564eff7c3b624c80a22 | 7,583 |
def Ltotal(scatter: bool):
"""
Graph for computing 'Ltotal'.
"""
graph = beamline(scatter=scatter)
if not scatter:
return graph
del graph['two_theta']
return graph | d38b7947b4c6397157e1bfec33b275a814dc1ec0 | 7,584 |
def is_valid_page_to_edit(prev_pg_to_edit, pg_to_edit):
"""Check if the page is valid to edit or not
Args:
prev_pg_to_edit (obj): page to edit object of previous page
pg_to_edit (obj): page to edit object of current page
Returns:
boolean: true if valid else false
"""
try:
... | ce594804f105b749062f79d63fc3021296631c1b | 7,586 |
def get_diffs(backups, backup_id, partner_backups, bound=10):
"""
Given a list `backups`, a `backup_id`, and `bound`
Compute the a dict containing diffs/stats of surronding the `backup_id`:
diff_dict = {
"stats": diff_stats_list,
"files": files_list,
"partners": partner_files... | fd896dc22270090eb88b41b3ab3fae2872d2ad06 | 7,587 |
from typing import List
def admits_voc_list(cid: CID) -> List[str]:
"""
Return list of nodes in cid with positive value of control.
"""
return [x for x in list(cid.nodes) if admits_voc(cid, x)] | a2db0dbb062a205ebb75f5db93ed14b11b25ccc1 | 7,588 |
def contour(data2d, levels, container=None, **kwargs):
"""HIDE"""
if container is None:
_checkContainer()
container = current.container
current.object = kaplot.objects.Contour(container, data2d, levels, **kwargs)
return current.object | a9f56a8bcd54cbc38687682f78e684c03315f85b | 7,589 |
def FilterSuboptimal(old_predictions,
new_predictions,
removed_predictions,
min_relative_coverage=0.0,
min_relative_score=0.0,
min_relative_pide=0.0):
"""remove suboptimal alignments.
"""
best_predicti... | 570399a0310f836261d5d65455cfee54e697a23c | 7,590 |
def process_pair(librispeech_md_file, librispeech_dir,
wham_md_file, wham_dir, n_src, pair):
"""Process a pair of sources to mix."""
utt_pair, noise = pair # Indices of the utterances and the noise
# Read the utterance files and get some metadata
source_info, source_list = read_ut... | 3dea4b1dc93b0bc54ad199e09db7612e6dad18d5 | 7,591 |
def getMultiDriverSDKs(driven, sourceDriverFilter=None):
"""get the sdk nodes that are added through a blendweighted node
Args:
driven (string): name of the driven node
sourceDriverFilter (list, pynode): Driver transforms to filter by,
if the connected SDK is not driven by this node it ... | 4f7fe2d959619d3eaca40ba6366a5d4d62e047ff | 7,592 |
def resnet_model_fn(features, labels, mode, model_class,
resnet_size, weight_decay, learning_rate_fn, momentum,
data_format, version, loss_filter_fn=None, multi_gpu=False):
"""Shared functionality for different resnet model_fns.
Initializes the ResnetModel representing t... | 4adc5fc3ca461d4eb4a051861e8c82d2c1aab5dd | 7,593 |
def dataframe_from_stomate(filepattern,largefile=True,multifile=True,
dgvmadj=False,spamask=None,
veget_npindex=np.s_[:],areaind=np.s_[:],
out_timestep='annual',version=1,
replace_nan=False):
"""
Paramete... | ba448d020ea8b41b75bd91d4b48ffca2d527b230 | 7,594 |
from applications.models import Application # circular import
def random_application(request, event, prev_application):
"""
Get a new random application for a particular event,
that hasn't been scored by the request user.
"""
return Application.objects.filter(
form__event=event
).excl... | 1d1b781b61328af67d7cc75c0fe9ec6f404b1b82 | 7,595 |
def flutter_velocity(pressures, speeds_of_sound,
root_chord, tip_chord, semi_span, thickness,
shear_modulus=2.62e9):
"""Calculate flutter velocities for a given fin design.
Fin dimensions are given via the root_chord, tip_chord, semi_span and
thickness arguments. ... | 6a6fcbc2fffe541ef85f824f282924bb38199f46 | 7,596 |
import re
def replace_within(begin_re, end_re, source, data):
"""Replace text in source between two delimeters with specified data."""
pattern = r'(?s)(' + begin_re + r')(?:.*?)(' + end_re + r')'
source = re.sub(pattern, r'\1@@REPL@@\2' , source)
if '@@REPL@@' in source:
source = source.replac... | 23320d11a8bf0d6387f4687555d1fa472ad4c4d0 | 7,597 |
import itertools
def random_outputs_for_tier(rng, input_amount, scale, offset, max_count, allow_extra_change=False):
""" Make up to `max_number` random output values, chosen using exponential
distribution function. All parameters should be positive `int`s.
None can be returned for expected types of failu... | eb3b7d813740e9aa9457fe62c4e0aaf86fad7bce | 7,599 |
def create_connection(host, username, password):
""" create a database connection to the SQLite database
specified by db_file
:return: Connection object or None
"""
try:
conn = mysql.connect(host=host, # your host, usually db-guenette_neutrinos.rc.fas.harvard.edu
... | 09c540115ce788d1f5fd09d789327ac6951cb9a2 | 7,600 |
def Dadjust(profile_ref, profile_sim, diffsys, ph, pp=True, deltaD=None, r=0.02):
"""
Adjust diffusion coefficient fitting function by comparing simulated
profile against reference profile. The purpose is to let simulated
diffusion profile be similar to reference profile.
Parameters
----------
... | d8b13e8d785a31219197936a9bd7b5d275f23351 | 7,601 |
def setup_test():
"""setup test"""
def create_test_tables(db):
"""create test tables"""
db("""
create table if not exists person (
id integer PRIMARY KEY AUTOINCREMENT,
name varchar(100),
age integer,
kids integer,
... | 539ca396ba3098e79ec5064ccde7245d91106ef2 | 7,602 |
def mapdict_values(function, dic):
"""
Apply a function to a dictionary values,
creating a new dictionary with the same keys
and new values created by applying the function
to the old ones.
:param function: A function that takes the dictionary value as argument
:param dic: A dictionary... | 03abbe7d7ec32d70ad0d4729913037f2199e977c | 7,604 |
from typing import Optional
async def callback(
request: Request,
code: str = None,
error: Optional[str] = Query(None),
db: AsyncSession = Depends(get_db),
):
"""
Complete the OAuth2 login flow
"""
client = get_discord_client()
with start_span(op="oauth"):
with start_span(... | f7d76c385360f6d2113cd7fb470344c1e7c96027 | 7,605 |
def align_centroids(config, ref):
"""Align centroids"""
diff_centroids = np.round(ref.mean(axis=0) - config.mean(axis=0))
# diff_centroids = np.round(diff_centroids).astype(int)
config = config + diff_centroids
return config | cd579a911cb4ae59aa274836de156620305e592a | 7,606 |
def _make_headers_df(headers_response):
"""
Parses the headers portion of the watson response and creates the header dataframe.
:param headers_response: the ``row_header`` or ``column_header`` array as returned
from the Watson response,
:return: the completed header dataframe
"""
headers_d... | 621d46da0de2056ac98747a51f2ac2cbfdd52e5e | 7,607 |
def getMemInfo() -> CmdOutput:
"""Returns the RAM size in bytes.
Returns:
CmdOutput: The output of the command, as a `CmdOutput` instance containing
`stdout` and `stderr` as attributes.
"""
return runCommand(exe_args=ExeArgs("wmic", ["memorychip", "get", "capacity"])) | c57312d83182349e0847d0eb49606c401a3a0d27 | 7,608 |
def svn_swig_py_make_editor(*args):
"""svn_swig_py_make_editor(PyObject * py_editor, apr_pool_t pool)"""
return _delta.svn_swig_py_make_editor(*args) | 2041342a1bef3ea0addb004e1bd4539c58445c66 | 7,609 |
def register_confirm(request, activation_key):
"""finish confirmation and active the account
Args:
request: the http request
activation_key: the activation key
Returns:
Http redirect to successful page
"""
user_safety = get_object_or_404(UserSafety, activation_key=activation... | c677f246ff3088d58912bc136f1d2461f58ba10b | 7,610 |
def get_best_z_index(classifications):
"""Get optimal z index based on quality classifications
Ties are broken using the index nearest to the center of the sequence
of all possible z indexes
"""
nz = len(classifications)
best_score = np.min(classifications)
top_z = np.argwhere(np.array(clas... | 90b10dda47c071a3989a9de87061694270e67d69 | 7,611 |
import glob
def mean_z_available():
"""docstring for mean_z_available"""
if glob.glob("annual_mean_z.nc"):
return True
return False | d53f8dc6fe540e8f74fd00760d1c810e510e53b8 | 7,612 |
import time
def wait_for_url(monitor_url, status_code=None, timeout=None):
"""Blocks until the URL is availale"""
if not timeout:
timeout = URL_TIMEOUT
end_time = time.time() + timeout
while (end_time - time.time()) > 0:
if is_url(monitor_url, status_code):
return True
... | 7d7ca1fd51d4415c58ab3928bd163401fb548b9a | 7,613 |
import requests
import io
import tarfile
def sources_from_arxiv(eprint):
"""
Download sources on arXiv for a given preprint.
:param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``).
:returns: A ``TarFile`` object of the sources of the arXiv preprint.
"""
r = requests.get("http://a... | b26c46009b23c5a107d6303b567ab97492f91ad9 | 7,614 |
def render():
"""
This method renders the HTML webside including the isOnline Status and the last 30 database entries.
:return:
"""
online = isonline()
return render_template("index.html", news=News.query.order_by(News.id.desc()).limit(30), online=online) | 4b0584d33fb84f05afbbcfe016d7428c4f75a4d3 | 7,616 |
import aiohttp
async def execute_request(url):
"""Method to execute a http request asynchronously
"""
async with aiohttp.ClientSession() as session:
json = await fetch(session, url)
return json | 1845fed4acce963a0bc1bb780cdea16ba9dec394 | 7,617 |
from typing import List
def game_over(remaining_words: List[str]) -> bool:
"""Return True iff remaining_words is empty.
>>> game_over(['dan', 'paul'])
False
>>> game_over([])
True
"""
return remaining_words == [] | 8d29ef06bd5d60082646cef00f77bbabfbac32eb | 7,618 |
import csv
def read_manifest(instream):
"""Read manifest file into a dictionary
Parameters
----------
instream : readable file like object
"""
reader = csv.reader(instream, delimiter="\t")
header = None
metadata = {}
for row in reader:
if header is None:
header... | afa6c2bb0a9d81267b1d930026a229be924a1994 | 7,619 |
def get_backbone_from_model(model:Model, key_chain:list) -> nn.Cell:
"""Obtain the backbone from a wrapped mindspore Model using the
key chain provided.
Args:
model(Model): A Model instance with wrapped network and loss.
key_chain(list[str]): the keys in the right order according to
... | 0ddabf30c50e9d58ce18b0010107d92f8518b9bc | 7,620 |
def dv_upper_lower_bound(f):
"""
Donsker-Varadhan lower bound, but upper bounded by using log outside.
Similar to MINE, but did not involve the term for moving averages.
"""
first_term = f.diag().mean()
second_term = logmeanexp_nodiag(f)
return first_term - second_term | a7f9a3910a934f836204c5c47d9139be31860ec1 | 7,621 |
def create_training_files_for_document(
file_name,
key_field_names,
ground_truth_df,
ocr_data,
pass_number):
"""
Create the ocr.json file and the label file for a document
:param file_path: location of the document
:param file_name: just the document name.ext
... | 4832e28904f2c950ceb5526eaa8ab61568c55a8c | 7,622 |
def incoming(ui, repo, source="default", **opts):
"""show new changesets found in source
Show new changesets found in the specified path/URL or the default
pull location. These are the changesets that would have been pulled
if a pull at the time you issued this command.
See pull for valid source f... | 9bf41cdc4de5c82634fae038940951ad738fd636 | 7,623 |
import time
def timeout(limit=5):
"""
Timeout
This decorator is used to raise a timeout error when the
given function exceeds the given timeout limit.
"""
@decorator
def _timeout(func, *args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
duration =... | c68fee9530512ce1603ec7976f4f1278205b1f92 | 7,624 |
from typing import Union
def OIII4363_flux_limit(combine_flux_file: str, verbose: bool = False,
log: Logger = log_stdout()) -> \
Union[None, np.ndarray]:
"""
Determine 3-sigma limit on [OIII]4363 based on H-gamma measurements
:param combine_flux_file: Filename of ASCII fil... | 109f887693df16661d7766840b0026f7e9bca82d | 7,625 |
import numpy
def convert_units_co2(ds,old_data,old_units,new_units):
"""
Purpose:
General purpose routine to convert from one set of CO2 concentration units
to another.
Conversions supported are:
umol/m2/s to gC/m2 (per time step)
gC/m2 (per time step) to umol/m2/s
mg/m3 to um... | 38ce2987bfa4c5505fe64779ce752617862138fd | 7,626 |
def query_urlhaus(session, provided_ioc, ioc_type):
""" """
uri_dir = ioc_type
if ioc_type in ["md5_hash", "sha256_hash"]:
uri_dir = "payload"
api = "https://urlhaus-api.abuse.ch/v1/{}/"
resp = session.post(api.format(uri_dir), timeout=180, data={ioc_type: provided_ioc})
ioc_dicts ... | 171bff1e9b1bfdf8ac6b91a4bbbd7226f80c8c4c | 7,627 |
def arrow_to_json(data):
"""
Convert an arrow FileBuffer into a row-wise json format.
Go via pandas (To be revisited!!)
"""
reader = pa.ipc.open_file(data)
try:
frame = reader.read_pandas()
return frame.to_json(orient='records')
except:
raise DataStoreException("Unabl... | d49ee49b7071d0b857feeb878c99ce65e82460e9 | 7,628 |
import pathlib
def get_wmc_pathname(subject_id, bundle_string):
"""Generate a valid pathname of a WMC file given subject_id and
bundle_string (to resolve ACT vs noACT).
The WMC file contrains the bundle-labels for each streamline of the
corresponding tractogram.
"""
global datadir
ACT_str... | fcc570e3e59b99b94de95dc4f15c1fee2fe0f0f2 | 7,629 |
def _union_polygons(polygons, precision = 1e-4, max_points = 4000):
""" Performs the union of all polygons within a PolygonSet or list of
polygons.
Parameters
----------
polygons : PolygonSet or list of polygons
A set containing the input polygons.
precision : float
Desired prec... | f6951a67a2ed4099b5321b98517810de43024036 | 7,630 |
from typing import Callable
from re import T
from typing import Optional
def parse_or_none(
field: str,
field_name: str,
none_value: str,
fn: Callable[[str, str], T],
) -> Optional[T]:
""" If the value is the same as the none value, will return None.
Otherwise will attempt to run the fn with f... | 4a0c2d8ec819fe6b8a9a24a60f54c62cb83e68ac | 7,631 |
def get_lattice_parameter(elements, concentrations, default_title):
"""Finds the lattice parameters for the provided atomic species using Vagars law.
:arg elements: A dictionary of elements in the system and their concentrations.
:arg title: The default system title.
:arg concentrations: The concentrat... | 34e914e38b8c4d25d9ed5fd09f435d7358f99a99 | 7,632 |
import string
def tokenize(text):
"""
Tokenizes,normalizes and lemmatizes a given text.
Input:
text: text string
Output:
- array of lemmatized and normalized tokens
"""
def is_noun(tag):
return tag in ['NN', 'NNS', 'NNP', 'NNPS']
def is_verb(tag):
return tag ... | 672af73d594c7a134226f4ae9a265f19b14ced34 | 7,633 |
def bandpass_filterbank(bands, fs=1.0, order=8, output="sos"):
"""
Create a bank of Butterworth bandpass filters
Parameters
----------
bands: array_like, shape == (n, 2)
The list of bands ``[[flo1, fup1], [flo2, fup2], ...]``
fs: float, optional
Sampling frequency (default 1.)
... | 4cbe3acb30a0f08d39e28b46db520fdac420010d | 7,634 |
def get_couch_client(https: bool = False,
host: str = 'localhost',
port: int = 5984,
request_adapter: BaseHttpClient = HttpxCouchClient,
**kwargs) -> CouchClient:
"""
Initialize CouchClient
Parameters
----------
htt... | db242556c11debc9dff57929182d3e6932ef13d1 | 7,635 |
def compute_rmse(loss_mse):
"""
Computes the root mean squared error.
Args:
loss_mse: numeric value of the mean squared error loss
Returns:
loss_rmse: numeric value of the root mean squared error loss
"""
return np.sqrt(2 * loss_mse) | a81024cd402c00b0d6f3bfaccc089695fb5f4e0a | 7,636 |
def __detect_geometric_decomposition(pet: PETGraphX, root: CUNode) -> bool:
"""Detects geometric decomposition pattern
:param pet: PET graph
:param root: root node
:return: true if GD pattern was discovered
"""
for child in pet.subtree_of_type(root, NodeType.LOOP):
if not (child.reducti... | 27d90b6ced48a0db081d9881e39600d641855343 | 7,637 |
def add_two_frags_together(fragList, atm_list, frag1_id, frag2_id):
"""Combine two fragments in fragList."""
new_id = min(frag1_id, frag2_id)
other_id = max(frag1_id, frag2_id)
new_fragList = fragList[:new_id] # copy up to the combined one
new_frag = { # combined frag
'ids': fragList[frag1... | 9c226883d6c021e151c51889017f56ea6a4cba3a | 7,638 |
def concatenate(arrays, axis=0):
"""
Joins a sequence of tensors along an existing axis.
Args:
arrays: Union[Tensor, tuple(Tensor), list(Tensor)], a tensor or a list
of tensors to be concatenated.
axis (int, optional): The axis along which the tensors will be joined,
if... | a85db3673d3a50d76374b809b583a8ca5325d4c3 | 7,640 |
def withCHID(fcn):
"""decorator to ensure that first argument to a function is a Channel
ID, ``chid``. The test performed is very weak, as any ctypes long or
python int will pass, but it is useful enough to catch most accidental
errors before they would cause a crash of the CA library.
"""
# It... | 98ac8fdc812a8e9b7706e1932db662819e830597 | 7,644 |
def asin(a: Dual) -> Dual:
"""inverse of sine or arcsine of the dual number a, using math.asin(x)"""
if abs(a.value) >= 1:
raise ValueError('Arcsin cannot be evaluated at {}.'.format(a.value))
value = np.arcsin(a.value)
ders = dict()
for k,v in a.ders.items():
ders[k] = 1/(np.sqrt(1-a.value**2))*v
r... | 6b15e737ae5beb69f8963aa752d7fba761dce56f | 7,646 |
def hydrotopeQ(cover,hydrotopemap):
"""Get mean values of the cover map for the hydrotopes"""
grass.message(('Get mean hydrotope values for %s' %cover))
tbl = grass.read_command('r.univar', map=cover, zones=hydrotopemap,
flags='gt').split('\n')[:-1] #:-1 as last line hast line br... | 371dc496a4bb2e33fc382dddaea66e83aa613abc | 7,647 |
import re
def convert_to_seconds(duration_str):
"""
return duration in seconds
"""
seconds = 0
if re.match(r"[0-9]+$", duration_str):
seconds = int(duration_str)
elif re.match(r"[0-9]+s$", duration_str):
seconds = int(duration_str[:-1])
elif re.match(r"[0-9]+m$", duration_... | 222905e6089510c6f204c6ea710572a5b2132d28 | 7,648 |
def get_chunk_n_rows(row_bytes: int,
working_memory: Num,
max_n_rows: int = None) -> int:
"""Calculates how many rows can be processed within working_memory
Parameters
----------
row_bytes : int
The expected number of bytes of memory that will be consum... | b7c2ab10c59edb6c2541e31264b28e06266d2fc3 | 7,649 |
def find_signal_analysis(prior, sparsity, sigma_data):
"""
Generates a signal using an analytic prior.
Works only with square and overcomplete full-rank priors.
"""
N, L = prior.shape
k = np.sum(np.random.random(L) > (1 - sparsity))
V = np.zeros(shape=(L, L - k))
while np.linalg.matrix_... | 49a7c26b6bc934d3588ae25c99eb62e0b544616f | 7,651 |
from typing import List
import asyncio
import requests
def download_images(sorted_urls) -> List:
"""Download images and convert to list of PIL images
Once in an array of PIL.images we can easily convert this to a PDF.
:param sorted_urls: List of sorted URLs for split financial disclosure
:return: im... | 3efde31975c7912e16ab2d990417c2aa753ca5bf | 7,652 |
def get_molecules(struct,
bonds_kw={"mult":1.20, "skin":0.0, "update":False},
ret="idx"):
"""
Returns the index of atoms belonging to each molecule in the Structure.
"""
bonds = struct.get_bonds(**bonds_kw)
## Build connectivity matrix
graph = np.z... | 99b67f95114ddd6c712c8fe63a0713a914b8888f | 7,653 |
def cdivs(a,b,c,d,e,f,al1,al2,al3,x11,x21,x22,x23,x31,x32,x33):
"""Finds the c divides conditions for the symmetry preserving HNFs.
Args:
a (int): a from the HNF.
b (int): b from the HNF.
c (int): c from the HNF.
d (int): d from the HNF.
e (int): e from the HNF.
... | 20a0044050964c5705f3bce2297f2724d6f12f71 | 7,654 |
def numeric_field_list(model_class):
"""Return a list of field names for every numeric field in the class."""
def is_numeric(type):
return type in [BigIntegerField, DecimalField, FloatField, IntegerField,
PositiveIntegerField, PositiveSmallIntegerField,
S... | a501c2a7bc87f7cdea8945a946937f72cc0576a9 | 7,655 |
import tokenize
def _get_lambda_source_code(lambda_fn, src):
"""Attempt to find the source code of the ``lambda_fn`` within the string ``src``."""
def gen_lambdas():
def gen():
yield src + "\n"
g = gen()
step = 0
tokens = []
for tok in tokenize.generate_tok... | 5192a299bf88c9fdc070fae28e585cda3a09aadc | 7,656 |
import requests
import json
def retrieve_keycloak_public_key_and_algorithm(token_kid: str, oidc_server_url: str) -> (str, str):
""" Retrieve the public key for the token from keycloak
:param token_kid: The user token
:param oidc_server_url: Url of the server to authorize with
:return: keycloak public... | 87e706b56c63b991e1524b5d6ffcec86d6a9bc67 | 7,657 |
def read_conformations(filename, version="default", sep="\t", comment="#",
encoding=None, mode="rb", **kw_args):
"""
Extract conformation information.
Parameters
----------
filename: str
Relative or absolute path to file that contains the RegulonDB information.
Returns
---... | 3588ee68a8a498dbfb1f85d65a8eff65b5ff5ed1 | 7,658 |
def maskRipple(inRpl, outFile, mask):
"""maskRipple(inRpl, outFile, mask)
Sets the individual data items to zero based on the specified mask. If mask.getRGB(c,r)>0 /
then copy the contents at(c,r) of inRpl to outFile.rpl. Otherwise the contents of outFile /
is set to all zeros."""
outRpl = "%s.rpl... | 65d5464e9de469cf45b47991ed838a79c587d965 | 7,659 |
def GetCurrentScene() -> Scene:
"""
Returns current scene. Raises SpykeException
if current scene is not set.
"""
if not _currentScene:
raise SpykeException("No scene is set current.")
return _currentScene | 82a065e4cbd0aa4b326d53b3360aac52a99ac682 | 7,660 |
def timeago(seconds=0, accuracy=4, format=0, lang="en", short_name=False):
"""Translate seconds into human-readable.
:param seconds: seconds (float/int).
:param accuracy: 4 by default (units[:accuracy]), determine the length of elements.
:param format: index of [led, literal, dict].
... | b6a5858c3f5c5291b03654d076eb3f1e835f78c0 | 7,662 |
def generate_headline(ids=None):
"""Generate and return an awesome headline.
Args:
ids:
Iterable of five IDs (intro, adjective, prefix, suffix, action).
Optional. If this is ``None``, random values are fetched from the
database.
Returns:
Tuple of parts a... | 09fda0075b036ea51972b2f124733de9f34671fc | 7,663 |
import webbrowser
def open_in_browser(path):
"""
Open directory in web browser.
"""
return webbrowser.open(path) | 41328b2b478f0bd69695da1868c412188e494d08 | 7,664 |
def lstm_cell_forward(xt, a_prev, c_prev, parameters):
"""
Implement a single forward step of the LSTM-cell as described in Figure (4)
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
c_prev ... | 9d1ae3ea6da9de6827b5ecd9f8871ee8aae26d30 | 7,665 |
def encode_letter(letter):
"""
This will encode a tetromino letter as a small integer
"""
value = None
if letter == 'i':
value = 0
elif letter == 'j':
value = 1
elif letter == 'l':
value = 2
elif letter == 'o':
value = 3
elif letter == 's':
... | 6c72c4c9e44c93d045296ab1f49c7783f2b4fc59 | 7,666 |
async def register_log_event(
registration: LogEventRegistration, db: Session = Depends(get_db)
):
"""
Log event registration handler.
:param db:
:param registration: Registration object
:return: None
"""
reg_id = str(uuid4())
# Generate message for registration topic
msg = Log... | 62b84b9efa88512634d9c7a050e7c61ff06ba71a | 7,667 |
def cvAbsDiffS(*args):
"""cvAbsDiffS(CvArr src, CvArr dst, CvScalar value)"""
return _cv.cvAbsDiffS(*args) | b888683d1522c46c9dc7738a18b80f56efe975d3 | 7,668 |
from . import views # this must be placed here, after the app is created
def create_template_app(**kwargs):
"""Create a template Flask app"""
app = create_app(**kwargs)
app.register_blueprints()
return app | fbbb0018cd4da6897842f658ba3baf207e5614cc | 7,669 |
def mse(predict, actual):
"""
Examples(rounded for precision):
>>> actual = [1,2,3];predict = [1,4,3]
>>> np.around(mse(predict,actual),decimals = 2)
1.33
>>> actual = [1,1,1];predict = [1,1,1]
>>> mse(predict,actual)
0.0
"""
predict = np.array(predict)
actual = np.array(actu... | c42ee6d5531d40f727c41463f938c9c8f4ec6e84 | 7,670 |
import random
def make_demo_measurements(num_measurements, extra_tags=frozenset()):
"""Make a measurement object."""
return [
make_flexural_test_measurement(
my_id=__random_my_id(),
deflection=random.random(),
extra_tags=extra_tags
) for _ in range(num_measu... | 10c452936e889a8553afd1a9a570e34abae73470 | 7,671 |
from re import S
def _nrc_coron_rescale(self, res, coord_vals, coord_frame, siaf_ap=None, sp=None):
"""
Function for better scaling of NIRCam coronagraphic output for sources
that overlap the image masks.
"""
if coord_vals is None:
return res
nfield = np.size(coord_vals[0])
psf_... | 3b4e8596177e126955c7665333dd1305603f4e66 | 7,672 |
def csv_to_blob_ref(csv_str, # type: str
blob_service, # type: BlockBlobService
blob_container, # type: str
blob_name, # type: str
blob_path_prefix=None, # type: str
charset=None # type: str
):
... | c0df47839e963a5401204bcd422c7f78a94efc87 | 7,675 |
def col_rev_reduce(matrix, col, return_ops=False):
"""
Reduces a column into reduced echelon form by transforming all numbers above the pivot position into 0's
:param matrix: list of lists of equal length containing numbers
:param col: index of column
:param return_ops: performed operations are retu... | ab97078f0c92537532673d3dba3cb399d932342e | 7,676 |
def query_category_members(category, language='en', limit=100):
"""
action=query,prop=categories
Returns all the members of a category up to the specified limit
"""
url = api_url % (language)
query_args = {
'action': 'query',
'list': 'categorymembers',
'cmtitle': category... | 4a09d73cce237152405031004e967192ad3f8929 | 7,680 |
from typing import List
def _tokenize_text(text: str, language: str) -> List[str]:
"""Splits text into individual words using the correct method for the given language.
Args:
text: Text to be split.
language: The configured language code.
Returns:
The text tokenized into a list of words.
"""
i... | 284f1a7625de149b7f97ce51dcf88110ebae02b0 | 7,681 |
def ml64_sort_order(c):
"""
Sort function for measure contents.
Items are sorted by time and then, for equal times, in this order:
* Patch Change
* Tempo
* Notes and rests
"""
if isinstance(c, chirp.Note):
return (c.start_time, 10)
elif isinstance(c, Rest):
re... | 752a68796a12835661cfce5b2cfe5cba3ad5d7ef | 7,682 |
def electron_mass_MeVc2():
"""The rest mass of the electron in MeV/c**2
https://en.wikipedia.org/wiki/Electron
"""
return 0.5109989461 | 4496ddcc35a0aa6528cc19e47233f5a81626fefe | 7,684 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.