content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import functools
def Debounce(threshold=100):
"""
Simple debouncing decorator for apigpio callbacks.
Example:
`@Debouncer()
def my_cb(gpio, level, tick)
print('gpio cb: {} {} {}'.format(gpio, level, tick))
`
The threshold can be given to the decorator as an argument (in millis... | 156b128ffaa579ead371bff3c4b4f20a2a05646b | 3,644,400 |
import tkinter
import os
def get_folder(default_location, title_string=None):
"""Dialog box to browse to a folder. Returns folder path.
Usage: full_folder_name = get_folder(default_location, [title]),
where "default_location" is a starting folder location,
"title" is an optional message to l... | 8c02ca512d97d4122ebb8afe5a07b436a8cf6a03 | 3,644,401 |
def compute_quasisymmetry_error(
R_lmn,
Z_lmn,
L_lmn,
i_l,
Psi,
R_transform,
Z_transform,
L_transform,
iota,
helicity=(1, 0),
data=None,
):
"""Compute quasi-symmetry triple product and two-term errors.
f_C computation assumes transform grids are a single flux surface... | 6c33dcb70fe0e87f48b5b8d9e7e400ded2417257 | 3,644,402 |
def int_to_uuid(number):
""" convert a positive integer to a UUID :
a string of characters from `symbols` that is at least 3 letters long"""
assert isinstance(number,int) and number >= 0
if number == 0:
return '000'
symbol_string = ''
while number > 0:
remainder = number % base
... | 49ce7bfeb4e11c90b2589b8b4003c3135ba78f53 | 3,644,403 |
import argparse
def key_value_data(string):
"""Validate the string to be in the form key=value."""
if string:
key, value = string.split("=")
if not (key and value):
msg = "{} not in 'key=value' format.".format(string)
raise argparse.ArgumentTypeError(msg)
return... | c7d374f1d45fb49d8629a9956948603a82802f5f | 3,644,404 |
def count_digit(n, digit):
"""Return how many times digit appears in n.
>>> count_digit(55055, 5)
4
"""
if n == 0:
return 0
else:
if n%10 == digit:
return count_digit(n//10, digit) + 1
else:
return count_digit(n//10, digit) | 29cf3db8cca85e14b3b537f96246803d8176441d | 3,644,405 |
def cal_chisquare(data, f, pepoch, bin_profile, F1, F2, F3, F4, parallel=False):
"""
calculate the chisquare distribution for frequency search on the pepoch time.
"""
chi_square = np.zeros(len(f), dtype=np.float64)
t0 = pepoch
if parallel:
for i in prange(len(f)):
phi = (da... | 13dfc33cd975758a3f6c64ff2da4f91409cfdae4 | 3,644,406 |
def get_css_urls(bundle, debug=None):
"""
Fetch URLs for the CSS files in the requested bundle.
:param bundle:
Name of the bundle to fetch.
:param debug:
If True, return URLs for individual files instead of the minified
bundle.
"""
if debug is None:
debug = sett... | 2f16a9da213cfebd58550cab7ffd7a0438dfd840 | 3,644,407 |
def rng() -> np.random.Generator:
"""Random number generator."""
return np.random.default_rng(42) | 2c2f88eed71c9429edc25a06890266f5b7e8fc22 | 3,644,408 |
def add_values_in_dict(sample_dict, key, list_of_values):
"""Append multiple values to a key in the given dictionary"""
if key not in sample_dict:
sample_dict[key] = list()
sample_dict[key].extend(list_of_values)
temp_list = sample_dict[key]
temp_list = list(set(temp_list)) # remove duplica... | 8c30b50256fd16eb1b9eefae5cc6ab5be58fe85f | 3,644,409 |
def parse_length(line, p) -> int:
""" parse length specifer for note or rest """
n_len = voices[ivc].meter.dlen # start with default length
try:
if n_len <= 0:
SyntaxError(f"got len<=0 from current voice {line[p]}")
if line[p].isdigit(): # multiply note length
... | cee6c83eecbea455a53c3d4ac9a778d7351b66e0 | 3,644,410 |
def get_dual_shapes_and_types(bounds_elided):
"""Get shapes and types of dual vars."""
dual_shapes = []
dual_types = []
layer_sizes = utils.layer_sizes_from_bounds(bounds_elided)
for it in range(len(layer_sizes)):
m = layer_sizes[it]
m = [m] if isinstance(m, int) else list(m)
if it < len(layer_siz... | 297a305d8ef71d614eae21c3fc5c52ef08b271a3 | 3,644,411 |
def linear_search(alist, key):
""" Return index of key in alist . Return -1 if key not present."""
for i in range(len(alist)):
if alist[i] == key:
return i
return -1 | ab4c0517f9103a43509b0ba511c75fe03ea6e043 | 3,644,412 |
def overlap_integral(xi, yi, zi, nxi, nyi, nzi, beta_i,
xj, yj, zj, nxj, nyj, nzj, beta_j):
"""
overlap <i|j> between unnormalized Cartesian GTOs
by numerical integration on a multicenter Becke grid
Parameters
----------
xi,yi,zi : floats
Cartesian posit... | 500da2037d5e9f880f239788156cc717163b6b0c | 3,644,413 |
def save_project_id(config: Config, project_id: int):
"""Save the project ID in the project data"""
data_dir = config.project.data_dir
filename = data_dir / DEFAULT_PROJECTID_FILENAME
with open(filename, "w") as f:
return f.write(str(project_id)) | 9769067d222c8430764a2abd4def67a9ce45e49a | 3,644,414 |
async def session_start():
"""
session_start: Creates a new database session for external functions and returns it
- Keep in mind that this is only for external functions that require multiple transactions
- Such as adding songs
:return: A new database session
... | cb84d30a8a89bdf58c63114fa84558d7567396bd | 3,644,415 |
from pm4py.objects.bpmn.obj import BPMN
from pm4py.objects.bpmn.util.sorting import get_sorted_nodes_edges
from typing import Optional
from typing import Dict
from typing import Any
import tempfile
def apply(bpmn_graph: BPMN, parameters: Optional[Dict[Any, Any]] = None) -> graphviz.Digraph:
"""
Visualize a BP... | ca1e25dfe758712125327717e01cba36788b8b38 | 3,644,416 |
def _predict_exp(data, paulistring):
"""Compute expectation values of paulistring given bitstring data."""
expectation_value = 0
for a in data:
val = 1
for i, pauli in enumerate(paulistring):
idx = a[i]
if pauli == "I":
continue
elif pauli ... | 32737920e750780655ba85ae9e57d6e3cd0f194c | 3,644,417 |
import math
def AGI(ymod1, c02500, c02900, XTOT, MARS, sep, DSI, exact, nu18, taxable_ubi,
II_em, II_em_ps, II_prt, II_no_em_nu18,
c00100, pre_c04600, c04600):
"""
Computes Adjusted Gross Income (AGI), c00100, and
compute personal exemption amount, c04600.
"""
# calculate AGI assum... | aed1c311bc6b46b46bfea3e9756cd73933c37ca9 | 3,644,418 |
def tokenize(headline_list):
"""
Takes list of headlines as input and returns a list of lists of tokens.
"""
tokenized = []
for headline in headline_list:
tokens = word_tokenize(headline)
tokenized.append(tokens)
return tokenized | e5cf957a72d6d08d95787bf0f2222e525727c54a | 3,644,419 |
def create_en_sentiment_component(nlp: Language, name: str, force: bool) -> Language:
"""
Allows the English sentiment to be added to a spaCy pipe using nlp.add_pipe("asent_en_v1").
"""
LEXICON.update(E_LEXICON)
return Asent(
nlp,
name=name,
lexicon=LEXICON,
intensif... | f66ab4d86da2d42adb7c8da95cfdff9517dcc34f | 3,644,420 |
import json
def lambda_handler(event, context):
"""
店舗一覧情報を返す
Parameters
----------
event : dict
フロントより渡されたパラメータ
context : dict
コンテキスト内容。
Returns
-------
shop_list : dict
店舗一覧情報
"""
# パラメータログ
logger.info(event)
try:
shop_list = get_sh... | 48eebf18d34e50a98d00bd589b9d8a0712b9f985 | 3,644,421 |
import warnings
def mask_land_ocean(data, land_mask, ocean=False):
"""Mask land or ocean values using a land binary mask.
Parameters
----------
data: xarray.DataArray
This input array can only have one of 2, 3 or 4
dimensions. All spatial dimensions should coincide with those
... | 97d32c2720db12e47738a58d2152d7052af095ed | 3,644,422 |
def create_project_type(project_type_params):
"""
:param project_type_params: The parameters for creating an ProjectType instance -- the dict should include the
'type' key, which specifies the ProjectType subclass name, and key/value pairs matching constructor arguments
for that ProjectType subc... | 446961674985a2f5a64417d6f1f9bc6b39f7fbe4 | 3,644,423 |
def env_str(env_name: str, default: str) -> str:
"""
Get the environment variable's value convert into string
"""
return getenv(env_name, default) | 529adfcfe770a39a5997d92792fdd2c857b32a41 | 3,644,424 |
def server_bam_statistic(ip, snmp_config_data):
"""
:param ip:
:param snmp_config_data:
:return:
"""
try:
var_binds = get_snmp_multiple_oid(oids=oids_bam, ip=ip, snmp_config_data=snmp_config_data)
server_memory_usage = get_memory_usage(var_binds)
server_cpu_usage = get_cp... | 9a22c2dc339defad39df3edd55e2c3f00fc91763 | 3,644,425 |
def extract_sigma_var_names(filename_nam):
"""
Parses a 'sigma.nam' file containing the variable names, and outputs a
list of these names.
Some vector components contain a semicolon in their name; if so, break
the name at the semicolon and keep just the 1st part.
"""
var_names = []
wit... | 930e855d47c4303cac28e9973982392489fb577d | 3,644,426 |
def vectors_to_arrays(vectors):
"""
Convert 1d vectors (lists, arrays or pandas.Series) to C contiguous 1d
arrays.
Arrays must be in C contiguous order for us to pass their memory pointers
to GMT. If any are not, convert them to C order (which requires copying the
memory). This usually happens ... | c9a3878f2d1099ffd985525931f05df1b8631c46 | 3,644,427 |
import random
import string
def random_name_gen(size=6):
"""Generate a random python attribute name."""
return ''.join(
[random.choice(string.ascii_uppercase)] +
[random.choice(string.ascii_uppercase + string.digits) for i in range(size - 1)]
) if size > 0 else '' | 67ade3cde47fffc126cbdb11f01ffda2672d021c | 3,644,428 |
import logging
import pandas
import numpy
def load_player_history_table(div_soup):
"""Parse the HTML/Soup table for the numberfire predictions.
Returns a pandas DataFrame
"""
if not div_soup:
return None
rows = div_soup.findAll('tr')
table_header = [x.getText() for x in rows[0].findAll('th')]
table_... | 64b433bf01f0857714cebb4df677a20578044020 | 3,644,429 |
def is_identity(u, tol=1e-15):
"""Test if a matrix is identity.
Args:
u: np.ndarray
Matrix to be checked.
tol: float
Threshold below which two matrix elements are considered equal.
"""
dims = np.array(u).shape
if dims[0] != dims[1]:
raise Exception("... | 160f33651b9d79448167423542cd1e2ad0bd3110 | 3,644,430 |
def get_metrics():
"""
Collects various system metrics and returns a list of objects.
"""
metrics = {}
metrics.update(get_memory_metrics())
metrics.update(get_cpu_metrics())
metrics.update(get_disk_metrics())
return metrics | d4055e0eb23d9babb9882bc3c089af293c638def | 3,644,431 |
def getPost(blog_id, username, password, post_id, fields=[]):
"""
Parameters
int blog_id
string username
string password
int post_id
array fields: Optional. List of field or meta-field names to include in response.
"""
logger.debug("%s.getPost entered" % __name__)
user = get_user... | 4d3c481bff63a7aa425b6f98d910039bf1a9cbaf | 3,644,432 |
import inspect
def create_fun(name: str, obj, options: dict):
"""
Generate a dictionnary that contains the information about a function
**Parameters**
> **name:** `str` -- name of the function as returned by `inspect.getmembers`
> **obj:** `object` -- object of the function as returned by `inspec... | f95e6fab1ed0cf6a10574b790e81933c40b924c4 | 3,644,433 |
def serial_ss(file_read, forward_rate, file_rateconstant,
file_energy, matrix, species_list, factor,
initial_y, t_final, third_body=None,
chemkin_data=None, smiles=None, chemkin=True):
"""
Iteratively solves the system of ODEs for different rate constants
generated ... | f23693826c3507d9a2327b4b492f20469fca963f | 3,644,434 |
def contains_left_button(buttons) -> bool:
"""
Test if the buttons contains the left mouse button.
The "buttons" should be values returned by get_click() or get_mouse()
:param buttons: the buttons to be tested
:return: if the buttons contains the left mouse button
"""
return (buttons & QtC... | a5cde64ce1d1fa5fd1fe57988f8b60db03fc2dcf | 3,644,435 |
from typing import List
from typing import Dict
def extract_interest_from_import_batch(
import_batch: ImportBatch, interest_rt: ReportType) -> List[Dict]:
"""
The return list contains dictionaries that contain data for accesslog creation,
but without the report_type and import_batch fields
"""... | cbe26e47d5f5214e0599154ae5d3357370fed123 | 3,644,436 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
_LOGGER.debug("Disconnecting from spa")
spa: BalboaSpaWifi = hass.data[DOMAIN][entry.entry_id]
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
hass.dat... | 87216dec99ab9ff14d1ab1f381ea440c61e75fa6 | 3,644,437 |
def is_bst(t: BST) -> bool:
"""Returns true if t is a valid BST object, false otherwise.
Invariant: for each node n in t, if n.left exists, then n.left <= n, and if
n.right exists, then n.right >= n."""
if not isinstance(t, BST):
return False
if t._root and t._root.parent is not None:
... | 5180d01f8306f79b6ed4551e7d2bd4046a088ac2 | 3,644,438 |
def are_embedding_layer_positions_ok_for_testing(model):
"""
Test data can only be generated if all embeddings layers
are positioned directly behind the input nodes
"""
def count_embedding_layers(model):
layers = model.layers
result = 0
for layer in layers:
if is... | 4317cdc11e0b0acf84fda0c2633400851075e124 | 3,644,439 |
from typing import Any
def all_tasks_stopped(tasks_state: Any) -> bool:
"""
Checks if all tasks are stopped or if any are still running.
Parameters
---------
tasks_state: Any
Task state dictionary object
Returns
--------
response: bool
True if all tasks are stopped.
... | 98edffe71052cc114a7dda37a17b3a346ef59ef8 | 3,644,440 |
import PIL
def enhance_color(image, factor):
"""Change the strength of colors in an image.
This function has identical outputs to
``PIL.ImageEnhance.Color``.
Added in 0.4.0.
**Supported dtypes**:
* ``uint8``: yes; fully tested
* ``uint16``: no
* ``uint32``: no
*... | f6654fc0b4dfebecf221e4a34ec0c894e1c72d1f | 3,644,441 |
def random_deceleration(most_comfortable_deceleration, lane_pos):
"""
Return a deceleration based on given attribute of the vehicle
:param most_comfortable_deceleration: the given attribute of the vehicle
:param lane_pos: y
:return: the deceleration adopted by human driver
"""
if lane_pos:
... | c5e4f9ca16285c020b9b7f2376e0b43f198d5173 | 3,644,442 |
def dataclass_fields(dc):
"""Returns a dataclass's fields dictionary."""
return {name: getattr(dc, name)
for name in dc.__dataclass_fields__} | 4b82af3bfbc02f7bbfcf1aecb6f6501ef10d86e1 | 3,644,443 |
import os
import subprocess
def gets_ontology_statistics(file_location: str, owltools_location: str = './pkt_kg/libs/owltools') -> str:
"""Uses the OWL Tools API to generate summary statistics (i.e. counts of axioms, classes, object properties, and
individuals).
Args:
file_location: A string that... | d3293b00a49668a48a788d00a09efe603a6d7aee | 3,644,444 |
from docutils.parsers.rst.directives import _directives, _directive_registry
def get_directives(app: Sphinx):
"""Return all directives available within the current application."""
all_directives = {}
all_directives.update(_directive_registry)
all_directives.update(_directives)
for key, (modulena... | bc65f3453fd9f473b33457ddd06a2052558b02dd | 3,644,445 |
import os
def _get_wavs_from_dir(dir):
"""Return a sorted list of wave files from a directory."""
return [os.path.join(dir, f) for f in sorted(os.listdir(dir)) if \
_is_wav_file(f)] | 6e7c29ffac008afa8cc80a7ce0fccb307d69ea63 | 3,644,446 |
from mabel import DictSet, Reader
from ...internals.group_by import GroupBy
def SqlReader(sql_statement: str, **kwargs):
"""
Use basic SQL queries to filter Reader.
Parameters:
sql_statement: string
kwargs: parameters to pass to the Reader
Note:
`select` is taken from SQL SEL... | 0354dd8b4d8cc6913cc1887b96aba6a06613ffe5 | 3,644,447 |
def _handle_consent_confirmation(user, is_confirmed):
"""
Return server response given user consent.
Args:
user (fence.models.User): authN'd user
is_confirmed (str): confirmation param
"""
if is_confirmed == "yes":
# user has already given consent, continue flow
resp... | c4f61ed8465616a4fad912d02e81840eb9d34604 | 3,644,448 |
import math
def local_coherence(img, window_s=WSIZ):
"""
Calculate the coherence according to methdology described in:
Bazen, Asker M., and Sabih H. Gerez. "Segmentation of fingerprint images."
ProRISC 2001 Workshop on Circuits, Systems and Signal Processing. Veldhoven,
The Netherlands, 2001.
"""
... | d360b388d743a3ada1004be8367ed2d105f7857a | 3,644,449 |
def storeIDToWebID(key, storeid):
"""
Takes a key (int) and storeid (int) and produces a webid (a 16-character
str suitable for including in URLs)
"""
i = key ^ storeid
l = list('%0.16x' % (i,))
for nybbleid in range(0, 8):
a, b = _swapat(key, nybbleid)
_swap(l, a, b)
ret... | 38d9bffaa98c2191e818edd969d51873bb077094 | 3,644,450 |
def _jupyter_server_extension_paths():
"""
Set up the server extension for collecting metrics
"""
return [{"module": "jupyter_resource_usage"}] | f59c343dd8bcdb4755c725107b3c83f12978e9ef | 3,644,451 |
import collections
def _make_ordered_node_map(
pipeline: p_pb2.Pipeline
) -> 'collections.OrderedDict[str, p_pb2.PipelineNode]':
"""Helper function to prepare the Pipeline proto for DAG traversal.
Args:
pipeline: The input Pipeline proto. Since we expect this to come from the
compiler, we assume th... | c0f7af61adf114a3b2211d82de050bf5e1f4e681 | 3,644,452 |
import re
import os
def read_omex_meta_files_for_archive(archive, archive_dirname, config=None):
""" Read all of the OMEX Metadata files in an archive
Args:
archive (:obj:`CombineArchive`): COMBINE/OMEX archive
archive_dirname (:obj:`str`): directory with the content of the archive
co... | 3b4d95a268a7f303e7006dbf61d6c15fef212064 | 3,644,453 |
from typing import Optional
from typing import Tuple
def fmin_b_bfgs(func, x0, args=(), options=None):
"""
The BFGS algorithm from
Algorithm 6.1 from Wright and Nocedal, 'Numerical Optimization', 1999, pg. 136-143
with bounded parameters, using the active set approach from,
Byrd, R. H., L... | 0f8ce3e1873b9a5a955b95489ea454e3c9813524 | 3,644,454 |
def find_broken_in_text(text, ignore_substrings=None):
"""Find broken links
"""
links = _find(text, ignore_substrings=ignore_substrings)
responses = [_check_if_broken(link) for link in links]
return [res.url for res in responses if res.broken] | 43075b6abb1ba8e7fc6f163e1afd1d6f305d99ab | 3,644,455 |
from importlib import resources
import importlib_resources as resources
def revision_info():
"""
Get the git hash and mtime of the repository, or the installed files.
"""
# TODO: test with "pip install -e ." for developer mode
global _REVISION_INFO
if _REVISION_INFO is None:
_REVISION... | ee0899e72265d6cc9408f933320554f84e51b6d9 | 3,644,456 |
def home():
""" route for the index page"""
return jsonify({"message" : "welcome to fast_Food_Fast online restaurant"}) | cad54560f01361ff6d9fed1d117f8b50eff59b50 | 3,644,457 |
def singlediode_voc(effective_irradiance, temp_cell, module_parameters):
"""
Calculate voc using the singlediode model.
Parameters
----------
effective_irradiance
temp_cell
module_parameters
Returns
-------
"""
photocurrent, saturation_current, resistance_series, resistan... | b47cff93f7ad51ce026fd1e28c6427bcaca0a639 | 3,644,458 |
from apysc._file import file_util
from typing import Optional
from typing import List
def _exec_document_lint_and_script(
limit_count: Optional[int] = None) -> List[str]:
"""
Execute each runnable scripts in the documents and check with
each lint.
Parameters
----------
limit_count : i... | a9406dfc5180c5b0f820740ae99522d8141af22d | 3,644,459 |
import seaborn as sns
import warnings
def balance_boxplot(balance_name, data, num_color='#FFFFFF',
denom_color='#FFFFFF',
xlabel="", ylabel="", linewidth=1,
ax=None, **kwargs):
""" Plots a boxplot for a given balance on a discrete metadata category.
... | f15a0168282d59dabb5deddd86935d1417df97ef | 3,644,460 |
import os
def walk(dirname, file_list):
"""
This function is from a book called Think Python
written by Allen B. Downey.
It walks through a directory, gets names of all files
and calls itself recursively on all the directories
"""
for name in os.listdir(dirname):
path=os.pat... | fab10858f2887e30aac9e12a9a47b6d88a778a60 | 3,644,461 |
from typing import Dict
from typing import Union
def _apply_result_filters(key_gender_token_counters: Dict[Union[str, int], GenderTokenCounters],
diff: bool,
sort: bool,
limit: int,
remove_swords: bool) -> KeyGende... | 120bb37936293810796ad6e62cee6b3c0bccabe4 | 3,644,462 |
def blog_delete(request):
"""Delete blog entry by id."""
blog_id = int(request.params.get('id'))
entry = BlogRecordService.by_id(blog_id, request)
if not entry:
return HTTPNotFound()
request.dbsession.delete(entry)
return HTTPFound(location=request.route_url('home')) | 4e1b9a19cd3a33743479de69ee1fbc4ffc9f9a42 | 3,644,463 |
import aiohttp
async def get_ios_cfw():
"""Gets all apps on ios.cfw.guide
Returns
-------
dict
"ios, jailbreaks, devices"
"""
async with aiohttp.ClientSession() as session:
async with session.get("https://api.appledb.dev/main.json") as resp:
if resp.status == 200:... | dfb0dfafef2ef8e27940bc7a154cd4a35f863017 | 3,644,464 |
def server_error(errorMsg):
"""
Shorthand for returning error message.
"""
resp = HttpResponse(status=502)
resp.write("<h3>502 BAD GATEWAY: </h3>")
resp.write("<p>ERROR: {}</p>".format(errorMsg))
return resp | cadadfc0a8c0098832ca08080e3602bdaf01ffc4 | 3,644,465 |
import re
def protein_variant(variant):
"""
Return an HGVS_ variant string containing only the protein changes in a
coding HGVS_ variant string. If all variants are synonymous, returns the
synonymous variant code. If the variant is wild type, returns the wild
type variant.
:param str variant:... | ed9d11759ed5d09f76daa757b9e75d00bfd0f029 | 3,644,466 |
import os
import argparse
def parser():
"""Parses arguments from command line using argparse.
Parameters"""
# default directory for reddit files
default_directory = os.path.join(os.getcwd(), "data")
parser = argparse.ArgumentParser()
# obligatory
parser.add_argument("mode", type = int, he... | 271f4a5db0a5e8f6b201c098830885e768d246b7 | 3,644,467 |
import logging
def dump_func_name(func):
"""This decorator prints out function name when it is called
Args:
func:
Returns:
"""
def echo_func(*func_args, **func_kwargs):
logging.debug('### Start func: {}'.format(func.__name__))
return func(*func_args, **func_kwargs)
r... | 9db126f3c51ed28bb5e8aa206e5a11d36c82e008 | 3,644,468 |
import scipy
from functools import reduce
def calc_predictability_trace_of_avg_cov(x, k, p, ndim=False):
"""
The main evaluation criterion of GPFA, i.e., equation (2) from the paper.
:param x: data array
:param k: number of neighbors for estimate
:param p: number of past time steps to consider
... | a803847ce8f8791edf44d3ba102137e69836f410 | 3,644,469 |
from typing import Dict
from typing import Sequence
def nx_to_loreleai(graph: nx.Graph, relation_map: Dict[str, Predicate] = None) -> Sequence[Atom]:
"""
Converts a NetworkX graph into Loreleai representation
To indicate the type of relations and nodes, the functions looks for a 'type' attribute
Arg... | f847c26d0831bf6bbaf16eabe5a32d27118550da | 3,644,470 |
def _kohn_sham_iteration(
density,
external_potential,
grids,
num_electrons,
xc_energy_density_fn,
interaction_fn,
enforce_reflection_symmetry):
"""One iteration of Kohn-Sham calculation."""
# NOTE(leeley): Since num_electrons in KohnShamState need to specify as
# static argument in ji... | 81ecffb04d0bc76b31187708c3502acead8653ab | 3,644,471 |
def get_sync_func_driver(physical_mesh):
"""Get the sync function on the driver."""
def sync_func_driver():
assert isinstance(physical_mesh, LocalPhysicalDeviceMesh)
physical_mesh.devices[0].synchronize_all_activity()
return sync_func_driver | 13dee330aa22524c52272c1969f3acba23f4378f | 3,644,472 |
def get_nc_BGrid_GFDL(grdfile):
"""
Bgrd = get_nc_BGrid_GFDL(grdfile)
Load B-Grid grid object for GFDL CM2.1 from netCDF grid file
"""
nc = pyroms.io.Dataset(grdfile)
lon_t = nc.variables['geolon_t'][:]
lat_t = nc.variables['geolat_t'][:]
lon_uv = nc.variables['geolon_c'][:]
lat_u... | 0b6f844676da7f357334640eafdb3039127df912 | 3,644,473 |
def _getTimeDistORSlocal(fromLocs, toLocs, travelMode, port, speedMPS):
"""
Generate two dictionaries, one for time, another for distance, using ORS-local
Parameters
----------
fromLocs: list, Required
The start node coordinates in format of [[lat, lon], [lat, lon], ... ]
toLocs: list, Required
The End node ... | 67feca093769c4cef4f4383cb6eaca4e0f584019 | 3,644,474 |
def sequence_plus_one(x_init, iter, dtype=int):
"""
Mathematical sequence: x_n = x_0 + n
:param x_init: initial values of the sequence
:param iter: iteration until the sequence should be evaluated
:param dtype: data type to cast to (either int of float)
:return: element at the given iteration a... | ec84cdb2f98147d2d1d967f7a071d3124ccdf54a | 3,644,475 |
def _is_test_product_type(product_type):
"""Returns whether the given product type is for tests purposes or not."""
return product_type in (
apple_product_type.ui_test_bundle,
apple_product_type.unit_test_bundle,
) | 41847ab87e4a8a0dfc2b2758b70b5f7b5d7b952b | 3,644,476 |
def _synced(method, self, args, kwargs):
"""Underlying synchronized wrapper."""
with self._lock:
return method(*args, **kwargs) | 54ca3cf69742550bd34ff3d2299a2d84f78577a3 | 3,644,477 |
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
return meta('NewBase', bases, {}) | a8257c1d7a4fdec6331985983b65954e9b1d9453 | 3,644,478 |
def team(slug):
"""The team page. Shows statuses for all users in the team."""
db = get_session(current_app)
team = db.query(Team).filter_by(slug=slug).first()
if not team:
return page_not_found('Team not found.')
return render_template(
'status/team.html',
team=team,
... | c702b4837c3e7342e248f81180821c4ff3404793 | 3,644,479 |
def mask_layer(layer, mask, mask_value = np.nan):
"""apply a mask to a layer
layer[mask == True] = mask_value
"""
layer[mask] = mask_value
return layer | b8ac53633bb351eea2e0025eeb5daba1f2eeab54 | 3,644,480 |
import requests
def generate_twitch_clip(user_id):
"""Generate a Twitch Clip from user's channel.
Returns the URL and new clip object on success."""
user = User.get_user_from_id(user_id)
twitch_id = str(user.twitch_id)
payload_clips = {"broadcaster_id": TEST_ID or twitch_id} # Edit this to te... | 1980974b79c07e3759044f5041c2e9c8df040fbb | 3,644,481 |
def get_disabled():
"""
Return a list of all disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
"""
return _get_svc_list(status="DISABLED") | 34d2389bf6e2c3284b06376780c7424205f340be | 3,644,482 |
def calling_method():
"""
call recursive method
:return: list all post 2 days delta-time
"""
list_posts = list()
return create_json_poyload(list_posts) | 587afbf856dbd014a253847816c185edd23f8485 | 3,644,483 |
import syslog
def check_notifier(notifiers):
"""Check if the configured notifier really exists."""
notifiers_available = {
"syslog": notify_syslog,
"pushover": notify_pushover,
"mail": notify_mail,
"twilio": notify_twilio
}
notifiers_valid = []
for notifier in notif... | c5f57209943c9b97bd5e23ff7f3ea410d952d2c4 | 3,644,484 |
import json
def read_json(path):
"""
Read a BayesNet object from the json format. This
format has the ".bn" extension and is completely
unique to pyBN.
Arguments
---------
*path* : a string
The file path
Returns
-------
None
Effects
-------
- Instantiates... | 4c483f8fe148ff3a94bdee4accc22fb2964dc09d | 3,644,485 |
def solve_primal(run_id, problem, mip_solution, solver):
"""Solve primal by fixing integer variables and solving the NLP.
If the search fails and f `mip_solution` has a solution pool, then also
try to find a feasible solution starting at the solution pool points.
Parameters
----------
run_id :... | 9b01b65553a752cebb899bcc8b4f78f5355db5f9 | 3,644,486 |
def SpliceContinuations(tree):
"""Given a pytree, splice the continuation marker into nodes.
Arguments:
tree: (pytree.Node) The tree to work on. The tree is modified by this
function.
"""
def RecSplicer(node):
"""Inserts a continuation marker into the node."""
if isinstance(node, pytree.Leaf... | 9bb36363b3ae8ef2e04649bc966d8e664fa1202f | 3,644,487 |
def rayleigh(flow_resis, air_dens, sound_spd,
poros, freq=np.arange(100, 10001, 1)):
"""
Returns through the Rayleigh Model the Material Charactheristic Impedance
and the Material Wave Number.
Parameters:
----------
flow_resis : int
Resistivity of th... | cf1330591e1f97f831268bd19babac2d682369aa | 3,644,488 |
import requests
import logging
def set_iam_policy(project_id: str, policy: dict, token: str) -> dict:
"""Sets the Cloud IAM access control policy for a ServiceAccount.
Args:
project_id: GCP project ID.
policy: IAM policy.
token: Access token from the Google Authorization Server.
... | 3afc6902bcd20c4af62ba9c3f2e873da5d425d06 | 3,644,489 |
def feature_set_is_deployed(db: Session, fset_id: int) -> bool:
"""
Returns if this feature set is deployed or not
:param db: SqlAlchemy Session
:param feature_set_id: The Feature Set ID in question
:return: True if the feature set is deployed
"""
d = db.query(models.FeatureSetVersion). \
... | e66609ec97a17eb55ea0a6c7218a0f5f9fb1ca9b | 3,644,490 |
from typing import Union
from typing import Optional
def get_retry_request(
request: Request,
*,
spider: Spider,
#response: Response,
reason: Union[str, Exception] = 'unspecified',
max_retry_times: Optional[int] = None,
priority_adjust: Optional[int] = None,
logger: Logger = retry_logg... | f7d46d4edcf30b90fd197e37d9f796c82ccae74f | 3,644,491 |
import time
async def graf(request: Request):
"""
Zobrazí graf nameranej charakteristiky
"""
localtime = time.asctime(time.localtime(time.time()))
print("Graf; Čas:", localtime)
return templates.TemplateResponse("graf.html", {"request": request, "time": localtime}) | a09ad4790cfaf71927b2c3e2b371f4089c8f0937 | 3,644,492 |
def mapRangeUnclamped(Value, InRangeA, InRangeB, OutRangeA, OutRangeB):
"""Returns Value mapped from one range into another where the Value is
clamped to the Input Range.
(e.g. 0.5 normalized from the range 0->1 to 0->50 would result in 25)"""
return lerp(OutRangeA, OutRangeB, GetRangePct(InRangeA, InRa... | 1579359f6585bb17228cf2b94b29ee8cd00e672e | 3,644,493 |
import json
def folders(request):
"""Handle creating, retrieving, updating, deleting of folders.
"""
if request.method == "GET":
q = bookshelf_models.Folder.objects.filter(owner=request.user)
data = [[e.guid, e.title] for e in q]
if request.method == "POST":
if "create" in requ... | 29a3c58970188682724e429d4f8a8a244938f54c | 3,644,494 |
import os
def reponame(url, name=None):
"""
Determine a repo's cloned name from its URL.
"""
if name is not None:
return name
name = os.path.basename(url)
if name.endswith('.git'):
name = name[:-4]
return name | be8bb47f1fc8be940e469d6a999a2039edb2fa3a | 3,644,495 |
import argparse
from typing import Dict
def specified_options(opts: argparse.Namespace, exclude=None) -> Dict:
"""
Cast an argparse Namespace into a dictionary of options.
Remove all options that were not specified (equal to None).
Arguments:
opts: The namespace to cast.
exclude: Nam... | b1200fbedb5edcd8b44fef3e30f644cc582ca23f | 3,644,496 |
def Sort_list_by_Prism_and_Date(lst):
"""
Argument:
- A list containing the prism name, position of recording, decimal year, position and meteo corrected position for each prism.
Return:
- A list containing lists of prisms sorted by name and date.
"""
#text must be a converted GKA file
o... | 164a4c8b646363b3d8c57068ee785b410cbc3cf7 | 3,644,497 |
def _convert_to_RVector(value, force_Rvec=True):
"""
Convert a value or list into an R vector of the appropriate type.
Parameters
----------
value : numeric or str, or list of numeric or str
Value to be converted.
force_Rvec : bool, default True
If `value` is not a... | cc71e8c8906084b33c1638a1423944576fb75366 | 3,644,498 |
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x))
temp=e_x / e_x.sum(axis=0) # only difference
if np.isnan(temp).any()==True:
return [0.0,1.0,0.0]
else:
return temp | ed3a4c5e60dbfaf86acec1357e7700492ab3f69d | 3,644,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.