content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def createMonatomicGas(elm, pascal):
"""createMonatomicGas(elm, pascal)
Create a gas of single atoms of the specified element at the specified pressure in Pascal and 300 K"""
return epq.Gas((elm,), (1,), pascal, 300.0, elm.toString() + " gas at %f Pa" % pascal) | 4552f551c27e0f10dea72c96bc32b9927649f749 | 4,768 |
import torch
def boxes_to_central_line_torch(boxes):
"""See boxes_to_central_line
Args:
boxes (tensor[..., 7]): (x, y, z, l, w, h, theta) of each box
Returns:
boxes_lp (tensor[..., 3]): (a, b, c) line parameters of each box
"""
# in case length is shorter than width
bmask = b... | e96667177cee058fe5f5cd1e8446df97d976474e | 4,769 |
from pyspark.sql import SparkSession
def load_as_spark(url: str) -> "PySparkDataFrame": # noqa: F821
"""
Load the shared table using the give url as a Spark DataFrame. `PySpark` must be installed, and
the application must be a PySpark application with the Apache Spark Connector for Delta Sharing
inst... | d427f71530b982703853146cbaa1ce3585b8f195 | 4,770 |
def calClassSpecificProbPanel(param, expVars, altAvMat, altChosen, obsAv):
"""
Function that calculates the class specific probabilities for each decision-maker in the
dataset
Parameters
----------
param : 1D numpy array of size nExpVars.
Contains parameter values.
expVars : 2D ... | ccb867b44db9f0d7f9b35c92ef66a96097b4b881 | 4,771 |
def build_expression_tree(tokens):
"""Returns an ExpressionTree based upon by a tokenized expression."""
s = [] # we use Python list as stack
for t in tokens:
if t in '+-x*/': # t is an operator symbol
s.append(t) ... | b54ce3c3d784ff80f380774135c7353d6ebd1078 | 4,772 |
import json
def unpack_blockchain(s: str) -> block.Blockchain:
"""Unapck blockchain from JSON string with b64 for bytes."""
blocks = json.loads(s)
return [_unpack_block(block) for block in blocks] | ed43ea73df866489e814fd1bdff357c158aade91 | 4,773 |
import re
def parse(options,full_path):
"""
Parse the data according to several regexes
"""
global p_entering_vip_block, p_exiting_vip_block, p_vip_next, p_vip_number, p_vip_set
in_vip_block = False
vip_list = []
vip_elem = {}
order_keys = []
if (options.input_file !=... | 08177b0ab18c77154053249c2308c4705d1dbb65 | 4,774 |
def update_wishlist_games(cur, table, wishlist_args, update_delay):
"""A function to update wishlist games.
:param cur: database cursor object
:type cur: Cursor
:param table: name of table to work on
:type table: str
:param wishlist_args: list of wishlist g... | fcd80f19065112893af84d0a9862888a13bde372 | 4,775 |
from re import M
def WrapSignal(signal):
"""Wrap a model signal with a corresponding frontend wrapper."""
if type(signal) is M.BitsSignal:
return BitsFrontend(signal)
elif type(signal) is M.ListSignal:
return ListFrontend(signal)
elif type(signal) is M.BundleSignal:
return Bun... | 374c47d5053853bc2b23d56d40a2752521a1351f | 4,776 |
from typing import Any
def is_array_like(element: Any) -> bool:
"""Returns `True` if `element` is a JAX array, a NumPy array, or a Python
`float`/`complex`/`bool`/`int`.
"""
return isinstance(
element, (jnp.ndarray, np.ndarray, float, complex, bool, int)
) or hasattr(element, "__jax_array_... | acb681e329883742009e3e2543158cd602839ae8 | 4,777 |
def parse(javascript_code):
"""Returns syntax tree of javascript_code.
Syntax tree has the same structure as syntax tree produced by esprima.js
Same as PyJsParser().parse For your convenience :) """
p = PyJsParser()
return p.parse(javascript_code) | 295a6d5683b975a9229e27d06cc1369e6a6f0a95 | 4,778 |
def twitterAuth():
""" Authenticate user using Twitter API generated credentials """
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
return tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) | c0522247e22b2a029c7f954960b1f9f91e71e3cb | 4,779 |
def GetInstalledPackageUseFlags(pkg_str, board=None):
"""Gets the list of USE flags for installed packages matching |pkg_str|.
Args:
pkg_str: The package name with optional category, version, and slot.
board: The board to inspect.
Returns:
A dictionary with the key being a package CP and the value b... | 0b203ebe078d56053c4e2c3b23db91492399de55 | 4,780 |
def make_cursor():
"""
Creates a cursor for iterating through results
GetParams:
account: an account
user: a user
handle: a shark client handle
Returns:
a json object container the cursor handle
"""
data, statusCode = cursor()
return jsonify(data), statusCo... | 225cf3bdcb001f90041cb94dc5fd89c935daaf24 | 4,781 |
from typing import Any
def run_result_factory(data: list[tuple[Any, Any]]):
"""
We need to handle dt.datetime and agate.table.Table.
The rest of the types should already be JSON-serializable.
"""
d = {}
for key, val in data:
if isinstance(val, dt.datetime):
val = val.isofor... | 25462e0eaf87d4fcdd1f48161dfa5be4643485f4 | 4,782 |
def compute_steepness(zeroth_moment, peak_wavenumber):
"""Compute characteristic steepness from given peak wave number."""
return np.sqrt(2 * zeroth_moment) * peak_wavenumber | e1cb0beb19ff73e7d2b6a6879d4a388d04644953 | 4,783 |
def secondary_side_radius(mass_ratio, surface_potential):
"""
Side radius of secondary component
:param mass_ratio: float;
:param surface_potential: float;
:return: float; side radius
"""
return calculate_side_radius(1.0, mass_ratio, 1.0, surface_potential, 'secondary') | 3353d5b9cb76f9127ed1066a20a3328fea9b8a46 | 4,784 |
def pts_from_rect_inside(r):
""" returns start_pt, end_pt where end_pt is _inside_ the rectangle """
return (r[0], r[1]), ((r[0] + r[2] - 1), (r[1] + r[3] - 1)) | 51f5ea39763e9f16a2bb3a56eebef4dfe06c5746 | 4,785 |
import numpy as np
def minimum_distance(object_1, object_2):
""" Takes two lists as input
A list of numpy arrays of coordinates that make up object 1 and object 2
Measures the distances between each of the coordinates
Returns the minimum distance between the two objects, as calculated using a vector n... | e61fbb1ab83c5147f69351022f59ebab3295cb5a | 4,786 |
def retrieve_pkl_file(filename, verbose = False):
"""
Retrieve and return contents of pkl file
"""
if verbose == True:
start_time = timelib.time()
print("\n * Retrieving %s file ..."%filename)
data = pd.read_pickle(filename)
if verbose == True:
print("\n %s retrie... | aa7c108d32ea387c2677c0fccf285437d149ec01 | 4,787 |
def extractIpsFile(containerFile,newSimName):
"""
Given a container file, get the ips file in it and write it to current
directory so that it can be used
"""
oldIpsFile=os.path.splitext(containerFile)[0]+os.extsep+"ips"
zf=zipfile.ZipFile(containerFile,"r")
foundFile=""
# Assume that c... | a8135c7d3a10825e539819dfdb62d5f677680e44 | 4,788 |
import torch
def nplr(measure, N, rank=1, dtype=torch.float):
""" Return w, p, q, V, B such that
(w - p q^*, B) is unitarily equivalent to the original HiPPO A, B by the matrix V
i.e. A = V[w - p q^*]V^*, B = V B
"""
assert dtype == torch.float or torch.cfloat
if measure == 'random':
d... | 0451fa5ed1eeb60bef386991b2d953c190282e0e | 4,789 |
def read_data(oldest_year: int = 2020, newest_year: int = 2022):
"""Read in csv files of yearly covid data from the nytimes and concatenate into a single pandas DataFrame.
Args:
oldest_year: first year of data to use
newest_year: most recent year of data to use
"""
df_dicts = {} # diction... | 7b8e55ae41890eef3e4f0ac5a9502b8b19f1ad20 | 4,790 |
def ip_is_v4(ip: str) -> bool:
"""
Determines whether an IP address is IPv4 or not
:param str ip: An IP address as a string, e.g. 192.168.1.1
:raises ValueError: When the given IP address ``ip`` is invalid
:return bool: True if IPv6, False if not (i.e. probably IPv4)
"""
return type(ip_addr... | d0fa8351921e34ee44c1b6c9fecf14c0efe83397 | 4,791 |
def kdump(self_update=False, snapshot=None):
"""Regenerate kdump initrd
A new initrd for kdump is created in a snapshot.
self_update
Check for newer transactional-update versions.
snapshot
Use the given snapshot or, if no number is given, the current
default snapshot as a base... | fd49bf6bfb4af52625b4e479eca60594edb59d9e | 4,792 |
import logging
from datetime import datetime
def register_keywords_user(email, keywords, price):
"""Register users then keywords and creates/updates doc
Keyword arguments:
email - email for user
keywords - string of keywords
price -- (optional) max price can be set to None
"""
logging.in... | 09c0d3ff12fbd99d6e6a6c23906a74b525f91649 | 4,793 |
def plot_distribution(df, inv, ax=None, distribution=None, tau_plot=None, plot_bounds=True, plot_ci=True,
label='', ci_label='', unit_scale='auto', freq_axis=True, area=None, normalize=False,
predict_kw={}, **kw):
"""
Plot the specified distribution as a function of t... | f5f6eb29597abb34b4e0c634112370824cedf907 | 4,794 |
def profitsharing_order(self, transaction_id, out_order_no, receivers, unfreeze_unsplit,
appid=None, sub_appid=None, sub_mchid=None):
"""请求分账
:param transaction_id: 微信支付订单号,示例值:'4208450740201411110007820472'
:param out_order_no: 商户分账单号,只能是数字、大小写字母_-|*@,示例值:'P20150806125346'
:para... | 8885a953de7e74a562fc57ac242fafbf79ada7a8 | 4,795 |
def merge_time_batch_dims(x: Tensor) -> Tensor:
"""
Pack the time dimension into the batch dimension.
Args:
x: input tensor
Returns:
output tensor
"""
if xnmt.backend_dynet:
((hidden_dim, seq_len), batch_size_) = x.dim()
return dy.reshape(x, (hidden_dim,), batch_size=batch_size_ * seq_len)... | 73b09ca714870f18523c07b82e544b208fcde680 | 4,796 |
def get_log_likelihood(P, v, subs_counts):
"""
The stationary distribution of P is empirically derived.
It is proportional to the codon counts by construction.
@param P: a transition matrix using codon counts and free parameters
@param v: stationary distribution proportional to observed codon counts... | b7ed78e1e111a74f08b36f5ac41618318539d1c7 | 4,797 |
def union(l1, l2):
""" return the union of two lists """
return list(set(l1) | set(l2)) | 573e3b0e475b7b33209c4a477ce9cab53ec849d4 | 4,798 |
def actual_kwargs():
"""
Decorator that provides the wrapped function with an attribute 'actual_kwargs' containing just those keyword
arguments actually passed in to the function.
Based on code from http://stackoverflow.com/a/1409284/127480
"""
def decorator(function):
def inner(*args... | 37477edecb9442f759f4a234ea9037f7568f9770 | 4,799 |
def k1(f, t, y, paso):
"""
f : funcion a integrar. Retorna un np.ndarray
t : tiempo en el cual evaluar la funcion f
y : para evaluar la funcion f
paso : tamano del paso a usar.
"""
output = paso * f(t, y)
return output | 55a358a5d099111bd399bf1a0e0211d6616ab3d0 | 4,800 |
import json
def script_from_json_string(json_string, base_dir=None):
"""Returns a Script instance parsed from the given string containing JSON.
"""
raw_json = json.loads(json_string)
if not raw_json:
raw_json = []
return script_from_data(raw_json, base_dir) | 87845df4f365f05753f48e3988bb6f57e9e327ef | 4,801 |
def check_api_key(key: str, hashed: str) -> bool:
"""
Check a API key string against a hashed one from the user database.
:param key: the API key to check
:type key: str
:param hashed: the hashed key to check against
:type hashed: str
"""
return hash_api_key(key) == hashed | 86784ac5b6e79e009423e32a68fbac814e18fd40 | 4,803 |
def travel_chart(user_list, guild):
"""
Builds the chart to display travel data for Animal Crossing
:param user_list:
:param guild:
:return:
"""
out_table = []
fruit_lookup = {'apple': '🍎', 'pear': '🍐', 'cherry': '🍒', 'peach': '🍑', 'orange': '🍊'}
for user in user_list:
... | f866cb792b4382f66f34357e5b39254c4f2f1113 | 4,804 |
def evaluate_hyperparameters(parameterization):
""" Train and evaluate the network to find the best parameters
Args:
parameterization: The hyperparameters that should be evaluated
Returns:
float: classification accuracy """
net = Net()
net, _, _ = train_bayesian_optimization(net=net,... | 28811908e8015cbc95c35368bafd47428b5c31b3 | 4,805 |
from bs4 import BeautifulSoup
def get_post_type(h_entry, custom_properties=[]):
"""
Return the type of a h-entry per the Post Type Discovery algorithm.
:param h_entry: The h-entry whose type to retrieve.
:type h_entry: dict
:param custom_properties: The optional custom properties to use for the P... | 7d6d8e7bb011a78764985d834d259cb794d00cb9 | 4,806 |
def get_start_end(sequence, skiplist=['-','?']):
"""Return position of first and last character which is not in skiplist.
Skiplist defaults to ['-','?'])."""
length=len(sequence)
if length==0:
return None,None
end=length-1
while end>=0 and (sequence[end] in skiplist):
end-=1
... | b67e0355516f5aa5d7f7fad380d262cf0509bcdb | 4,807 |
def view_event(request, eventid):
"""
View an Event.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param eventid: The ObjectId of the event to get details for.
:type eventid: str
:returns: :class:`django.http.HttpResponse`
"""
ana... | 3b0abfaf2579ef660935d99638d0f44655f5676e | 4,808 |
def archiveOpen(self, file, path):
"""
This gets added to the File model to open a path within an archive file.
:param file: the file document.
:param path: the path within the archive file.
:returns: a file-like object that can be used as a context or handle.
"""
return ArchiveFileHandle(s... | e320299a96785d97d67fd91124fa58862c238213 | 4,810 |
def get_masked_bin(args, key: int) -> str:
"""Given an input, output, and mask type: read the bytes, identify the factory, mask the bytes, write them to disk."""
if args.bin == None or args.mask == None:
logger.bad("Please specify -b AND -m (bin file and mask)")
return None
# get the bytes... | d97806f984a6cad9b42d92bfcf050c1e032c5537 | 4,811 |
def count_entries(df, col_name = 'lang'):
"""Return a dictionary with counts of
occurrences as value for each key."""
# Initialize an empty dictionary: cols_count
cols_count = {}
# Extract column from DataFrame: col
col = df[col_name]
# Iterate over the column in DataFrame
for entry in c... | f933b77c8ff1ae123c887813ca559b410a104290 | 4,812 |
def workerfunc(prob, *args, **kwargs):
""" Helper function for wrapping class methods to allow for use
of the multiprocessing package """
return prob.run_simulation(*args, **kwargs) | 620799615b60784e754385fac31e5a7f1db37ed3 | 4,813 |
from unittest.mock import patch
async def client(hass, hass_ws_client):
"""Fixture that can interact with the config manager API."""
with patch.object(config, "SECTIONS", ["core"]):
assert await async_setup_component(hass, "config", {})
return await hass_ws_client(hass) | c42af4334912c05d2ea3413cb2af2f24f9f1cecf | 4,814 |
def test_curve_plot(curve):
"""
Tests mpl image of curve.
"""
fig = curve.plot().get_figure()
return fig | 033ee4ce5f5fa14c60914c34d54af4c39f6f84b3 | 4,815 |
import time
import pickle
import asyncio
async def _app_parser_stats():
"""Retrieve / update cached parser stat information.
Fields:
id: identifier of parser
size_doc: approximate size (bytes) per document or null
"""
parser_cfg = faw_analysis_set_util.lookup_all_parsers(
... | 06c363eee075a045e5ea16947253d4fc11e0cd6d | 4,816 |
def update_wishlists(wishlist_id):
"""
Update a Wishlist
This endpoint will update a Wishlist based the body that is posted
"""
app.logger.info('Request to Update a wishlist with id [%s]', wishlist_id)
check_content_type('application/json')
wishlist = Wishlist.find(wishlist_id)
if not w... | a7f19fa93f733c8419f3caeee2f0c7471282b05b | 4,817 |
def simplifiedview(av_data: dict, filehash: str) -> str:
"""Builds and returns a simplified string containing basic information about the analysis"""
neg_detections = 0
pos_detections = 0
error_detections = 0
for engine in av_data:
if av_data[engine]['category'] == 'malicious' or av_data[e... | c6aecf6c12794453dd8809d53f20f6152ac6d5a3 | 4,818 |
def GetManualInsn(ea):
"""
Get manual representation of instruction
@param ea: linear address
@note: This function returns value set by SetManualInsn earlier.
"""
return idaapi.get_manual_insn(ea) | d3a292d626ced87d4c3f08171d485aada87cad1d | 4,820 |
from datetime import datetime
def feature_time(data: pd.DataFrame) -> pd.DataFrame:
"""
Time Feature Engineering.
"""
# print(data)
# print(data.info())
day = 24*60*60
year = (365.2425)*day
time_stp = data['time'].apply(
lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:00") if is... | fd9322837032204e920a438c7a38ebdd2060b060 | 4,821 |
from typing import Tuple
from typing import List
def _transform(mock_file) -> Tuple[List[Page], SaneJson]:
""" Prepare the data as sections before calling report """
transformer = Transform(get_mock(mock_file, ret_dict=False))
sane_json = transformer.get_sane_json()
pages = transformer.get_pages()
... | 01c090f3af95024752b4adb919659ff7c5bc0d0a | 4,822 |
from typing import List
from typing import Any
from typing import Optional
def make_table(rows: List[List[Any]], labels: Optional[List[Any]] = None, centered: bool = False) -> str:
"""
:param rows: 2D array containing object that can be converted to string using `str(obj)`.
:param labels: Array containing... | cf175dbf9dd40c7e56b0a449b6bcc4f797f36b20 | 4,823 |
def coef_determ(y_sim, y_obs):
"""
calculate the coefficient of determination
:param y_sim: series of simulated values
:param y_obs: series of observed values
:return:
"""
assert y_sim.ndim == 1 and y_obs.ndim == 1 and len(y_sim) == len(y_obs)
r = np.corrcoef(y_sim, y_obs)
r2 = r[0... | ce06c6fffa79d165cf59e98f634725856e44938e | 4,825 |
async def generate_latest_metrics(client):
"""Generate the latest metrics and transform the body."""
resp = await client.get(prometheus.API_ENDPOINT)
assert resp.status == HTTPStatus.OK
assert resp.headers["content-type"] == CONTENT_TYPE_TEXT_PLAIN
body = await resp.text()
body = body.split("\n"... | d86736d8395158f66dc7592eae1d67d3bf06db50 | 4,826 |
def simulate(population: int, n: int, timer: int) -> int:
"""
Recursively simulate population growth of the fish.
Args:
population (int): Starting population
n (int): Number of days to simulate.
timer (int): The reset timer of the fish
initialised at 6 or 8 depending on ... | e69ce89a586b72cdbdcbc197c234c058d6d959b6 | 4,827 |
def normalize_valign(valign, err):
"""
Split align into (valign_type, valign_amount). Raise exception err
if align doesn't match a valid alignment.
"""
if valign in (TOP, MIDDLE, BOTTOM):
return (valign, None)
elif (isinstance(valign, tuple) and len(valign) == 2 and
valign[0... | e16e3c5cfb0425e3b04e64a6df01dd35407e2fbe | 4,828 |
def svn_auth_open(*args):
"""
svn_auth_open(svn_auth_baton_t auth_baton, apr_array_header_t providers,
apr_pool_t pool)
"""
return apply(_core.svn_auth_open, args) | 1083639e25b612ad47df86b39daedc8ae3dc74e2 | 4,829 |
def quote_key(key):
"""特殊字符'/'转义处理
"""
return key.replace('/', '%2F') | ce1978ca23ed3c00489c134a35ae8d04370b49dd | 4,830 |
def middle(word):
"""Returns all but the first and last characters of a string."""
return word[1:-1] | 257a159c46633d3c3987437cb3395ea2be7fad70 | 4,831 |
def surprise_communities(g_original, initial_membership=None, weights=None, node_sizes=None):
"""
Surprise_communities is a model where the quality function to optimize is:
.. math:: Q = m D(q \\parallel \\langle q \\rangle)
where :math:`m` is the number of edges, :math:`q = \\frac{\\sum_c m_c}{m}`,... | 7efba73c4948f4f6735f815e32b8700a08fc2d1e | 4,832 |
def get_azpl(cdec, cinc, gdec, ginc):
"""
gets azimuth and pl from specimen dec inc (cdec,cinc) and gdec,ginc (geographic) coordinates
"""
TOL = 1e-4
Xp = dir2cart([gdec, ginc, 1.])
X = dir2cart([cdec, cinc, 1.])
# find plunge first
az, pl, zdif, ang = 0., -90., 1., 360.
while zdif... | 19b6ec0179223bc453893ffd05fd555f4e6aea76 | 4,835 |
def read_embroidery(reader, f, settings=None, pattern=None):
"""Reads fileobject or filename with reader."""
if reader == None:
return None
if pattern == None:
pattern = EmbPattern()
if is_str(f):
text_mode = False
try:
text_mode = reader.READ_FILE_IN_TEXT_MO... | c84407f3f1969f61558dadafef2defda17a0ac0c | 4,836 |
import re
from pathlib import Path
import json
def load_stdlib_public_names(version: str) -> dict[str, frozenset[str]]:
"""Load stdlib public names data from JSON file"""
if not re.fullmatch(r"\d+\.\d+", version):
raise ValueError(f"{version} is not a valid version")
try:
json_file = Pat... | 02775d96c8a923fc0380fe6976872a7ed2cf953a | 4,837 |
def mask_inside_range(cube, minimum, maximum):
"""
Mask inside a specific threshold range.
Takes a MINIMUM and a MAXIMUM value for the range, and masks off anything
that's between the two in the cube data.
"""
cube.data = np.ma.masked_inside(cube.data, minimum, maximum)
return cube | b7a1ea1415d6f8e0f6b31372dce88355915bd2e6 | 4,839 |
def s3_client() -> client:
"""
Returns a boto3 s3 client - configured to point at a specfic endpoint url if provided
"""
if AWS_RESOURCES_ENDPOINT:
return client("s3", endpoint_url=AWS_RESOURCES_ENDPOINT)
return client("s3") | 256c2c52bc65f6899b1c800c2b53b2415ebc0aef | 4,840 |
def tokenize_with_new_mask(orig_text, max_length, tokenizer, orig_labels, orig_re_labels, label_map, re_label_map):
"""
tokenize a array of raw text and generate corresponding
attention labels array and attention masks array
"""
pad_token_label_id = -100
simple_tokenize_results = [list(tt) for t... | 56be66cf1679db07a2f98a4fa576df6118294fa3 | 4,841 |
def RMSE(stf_mat, stf_mat_max):
"""error defined as RMSE"""
size = stf_mat.shape
err = np.power(np.sum(np.power(stf_mat - stf_mat_max, 2.0))/(size[0]*size[1]), 0.5)
return err | b797e07f24f44b1cd3534de24d304d7de818eca8 | 4,843 |
def get_read_only_permission_codename(model: str) -> str:
"""
Create read only permission code name.
:param model: model name
:type model: str
:return: read only permission code name
:rtype: str
"""
return f"{settings.READ_ONLY_ADMIN_PERMISSION_PREFIX}_{model}" | d95e49067df9977aedc7b6420eada77b7206049d | 4,844 |
def hours_to_minutes( hours: str ) -> int:
"""Converts hours to minutes"""
return int(hours)*60 | 861e8724a2fa752c907e7ead245f0cb370e3fe28 | 4,845 |
def sir_model():
"""
this returns a density dependent population process of an SIR model
"""
ddpp = rmf.DDPP()
ddpp.add_transition([-1, 1, 0], lambda x: x[0]+2*x[0]*x[1])
ddpp.add_transition([0, -1, +1], lambda x: x[1])
ddpp.add_transition([1, 0, -1], lambda x: 3*x[2]**3)
return ddpp | b28e92a9cc142573465925e0c1be1bb58f5ad077 | 4,847 |
import re
def read_cmupd(strip_stress=False, apostrophe="'"):
"""Read the CMU-Pronunciation Dictionary
Parameters
----------
strip_stress : bool
Remove stress from pronunciations (default ``False``).
apostrophe : str | bool
Character to replace apostrophe with in keys (e.g., "COUL... | 0cc9ba95eeccf1e49f01a7e77082fd7a6674cd34 | 4,848 |
import numpy
def my_eval(inputstring, seq, xvalues=None, yvalues=None):
"""
Evaluate a string as an expression to make a data set.
This routine attempts to evaluate a string as an expression.
It uses the python "eval" function. To guard against bad inputs,
only numpy, math and builtin functions ... | 95993e5608e2cd5c8ee0bdedc9fce5f7e6310fc8 | 4,850 |
def readlines(filepath):
"""
read lines from a textfile
:param filepath:
:return: list[line]
"""
with open(filepath, 'rt') as f:
lines = f.readlines()
lines = map(str.strip, lines)
lines = [l for l in lines if l]
return lines | 1aa16c944947be026223b5976000ac38556983c3 | 4,851 |
def n_tuple(n):
"""Factory for n-tuples."""
def custom_tuple(data):
if len(data) != n:
raise TypeError(
f'{n}-tuple requires exactly {n} items '
f'({len(data)} received).'
)
return tuple(data)
return custom_tuple | 0c5d8f0f277e07f73c4909895c8215427fb5e705 | 4,855 |
def novel_normalization(data, base):
"""Initial data preparation of CLASSIX."""
if base == "norm-mean":
# self._mu, self._std = data.mean(axis=0), data.std()
_mu = data.mean(axis=0)
ndata = data - _mu
_scl = ndata.std()
ndata = ndata / _scl
elif base == "pca":
... | 2ab0644687ab3b2cc0daa00f72dcad2bce3c6f73 | 4,856 |
def calc_dof(model):
"""
Calculate degrees of freedom.
Parameters
----------
model : Model
Model.
Returns
-------
int
DoF.
"""
p = len(model.vars['observed'])
return p * (p + 1) // 2 - len(model.param_vals) | ccff8f5a7624b75141400747ec7444ec55eb492d | 4,857 |
def parse_event_export_xls(
file: StrOrBytesPath, parsing_elements: list[str] = _ALL_PARSING_ELEMENTS
) -> ParsedEventResultXlsFile:
"""Parse a Hytek MeetManager .hy3 file.
Args:
file (StrOrBytesPath): A path to the file to parse.
parsing_elements (Sequence[str]): Elements to extract from t... | 7116ffa78d9a4747934fb826cce39035fcf24aa1 | 4,858 |
def create_form(request, *args, **kwargs):
"""
Create a :py:class:`deform.Form` instance for this request.
This request method creates a :py:class:`deform.Form` object which (by
default) will use the renderer configured in the :py:mod:`h.form` module.
"""
env = request.registry[ENVIRONMENT_KEY]... | 152c82abe40995f214c6be88d1070abffba1df79 | 4,859 |
def from_dtw2dict(alignment):
"""Auxiliar function which transform useful information of the dtw function
applied in R using rpy2 to python formats.
"""
dtw_keys = list(alignment.names)
bool_traceback = 'index1' in dtw_keys and 'index2' in dtw_keys
bool_traceback = bool_traceback and 'stepsTake... | ef2c35ea32084c70f67c6bab462d662fe03c6b89 | 4,861 |
def fix_bad_symbols(text):
"""
HTML formatting of characters
"""
text = text.replace("è", "è")
text = text.replace("ä", "ä")
text = text.replace("Ã", "Ä")
text = text.replace("Ã", "Ä")
text = text.replace("ö", "ö")
text = text.replace("é", "é")
text = text.replace("Ã¥", "å"... | e128435a9a9d2eb432e68bf9cff9794f9dcd64ba | 4,862 |
def _level2partition(A, j):
"""Return views into A used by the unblocked algorithms"""
# diagonal element d is A[j,j]
# we access [j, j:j+1] to get a view instead of a copy.
rr = A[j, :j] # row
dd = A[j, j:j+1] # scalar on diagonal / \
B = A[j+1:, :j] # Block in corner | ... | 16ba7715cc28c69ad35cdf3ce6b542c14d5aa195 | 4,863 |
from typing import Optional
def _null_or_int(val: Optional[str]) -> Optional[int]:
"""Nullify unknown elements and convert ints"""
if not isinstance(val, str) or is_unknown(val):
return None
return int(val) | 6bd8d9ed350109444988077f4024b084a2189f91 | 4,864 |
def stackset_exists(stackset_name, cf_client):
"""Check if a stack exists or not
Args:
stackset_name: The stackset name to check
cf_client: Boto3 CloudFormation client
Returns:
True or False depending on whether the stack exists
Raises:
Any exceptions raised .describe_... | 78f6e383a6d4b06f164936edcc3f101e523aee34 | 4,865 |
def convert_l_hertz_to_bins(L_p_Hz, Fs=22050, N=1024, H=512):
"""Convert filter length parameter from Hertz to frequency bins
Notebook: C8/C8S1_HPS.ipynb
Args:
L_p_Hz (float): Filter length (in Hertz)
Fs (scalar): Sample rate (Default value = 22050)
N (int): Window size (Default va... | b7f7d047565dc08021ccbecbd05912ad11e8910b | 4,866 |
from macrostate import Macrostate
def macrostate_to_dnf(macrostate, simplify = True):
""" Returns a macrostate in disjunctive normal form (i.e. an OR of ANDs).
Note that this may lead to exponential explosion in the number of terms.
However it is necessary when creating Multistrand Macrostates, which can
only... | b3fa9666f0f79df21744ec08d0ef9a969210f7ae | 4,867 |
def construct_features(all_data):
# type: (pd.DataFrame) -> pd.DataFrame
"""
Create the features for the model
:param all_data: combined processed df
:return: df with features
"""
feature_constructor = FeatureConstructor(all_data)
return feature_constructor.construct_all_features() | 30bf001abdef6e7cdda927d340e640acc902906a | 4,868 |
from typing import Optional
import logging
def restore_ckpt_from_path(ckpt_path: Text, state: Optional[TrainState] = None):
"""Load a checkpoint from a path."""
if not gfile.exists(ckpt_path):
raise ValueError('Could not find checkpoint: {}'.format(ckpt_path))
logging.info('Restoring checkpoint from %s', c... | 297beb0a45c33522c172e59c0a2767b7f2e75ad2 | 4,869 |
import logging
def _GetChannelData():
"""Look up the channel data from omahaproxy.appspot.com.
Returns:
A string representing the CSV data describing the Chrome channels. None is
returned if reading from the omahaproxy URL fails.
"""
for unused_i in range(_LOOKUP_RETRIES):
try:
channel_csv ... | 6337dc236b310117c8e4f0ec7365c9d37a85a868 | 4,870 |
def look(direction=Dir.HERE):
"""
Looks in a given direction and returns the object found there.
"""
if direction in Dir:
# Issue the command and let the Obj enumeration find out which object is
# in the reply
# Don't use formatted strings in order to stay compatible to Python 3.... | bddae1d8da57cfb4016b96ae4fee72d37da97395 | 4,871 |
def merge(a, b, path=None):
"""Deprecated.
merges b into a
Moved to siem.utils.merge_dicts.
"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge(a[key], b[key], path + [str(key)])
... | 26b9dc9fc8451dc48b86b3e6fcf5f7870ac0fe7e | 4,874 |
import json
import requests
def post_attachment(fbid, media_url, file_type,
is_reusable=False, messaging_type="RESPONSE", tag=None):
""" Sends a media attachment to the specified user
:param str fbid: User id to send the audio.
:param str media_url: Url of a hosted media.
:param s... | fce03f1962038502bef623e227b7a643c2992c44 | 4,875 |
def create_or_update_dns_record(stack, record_name, record_type, record_value, hosted_zone_name, condition_field=""):
"""Create or Update Route53 Record Resource."""
return stack.stack.add_resource(RecordSetType(
'{0}'.format(record_name.replace('.', '').replace('*', 'wildcard')),
Condition=cond... | ba0d30dddde17967480a047fdc47242c1deaf4e6 | 4,877 |
def med_filt(x, k=201):
"""Apply a length-k median filter to a 1D array x.
Boundaries are extended by repeating endpoints.
"""
if x.ndim > 1:
x = np.squeeze(x)
med = np.median(x)
assert k % 2 == 1, "Median filter length must be odd."
assert x.ndim == 1, "Input must be one-dimensional... | ea9abfd6fd4243b1d959f7b499cdceccd851e53f | 4,878 |
def test_plot_grid(od_cup_anno_bboxes, od_cup_path):
""" Test that `plot_grid` works. """
# test callable args
def callable_args():
return od_cup_anno_bboxes, od_cup_path
plot_grid(display_bboxes, callable_args, rows=1)
# test iterable args
od_cup_paths = [od_cup_path, od_cup_path, od... | f41b9c54edd120af456195c417c23dbabbf5427b | 4,879 |
import copy
def sync_or_create_user(openid_user):
"""
Checks the user, returned by the authentication-service
Requires a user-dict with at least: sub, email, updated_at
"""
def _validate_user(openid_user):
error = False
msg = ''
if not openid_user.get('sub'):
er... | b8fb942900c9fd8c3720f473fb0b88285f91f3aa | 4,880 |
def related_tags(parser, token):
"""
Retrieves a list of instances of a given model which are tagged with
a given ``Tag`` and stores them in a context variable.
Usage::
{% related_tags [objects] as [varname] %}
The model is specified in ``[appname].[modelname]`` format.
The tag must b... | 001b63f40c9f63e814398a3ab0eeb358f694dd97 | 4,882 |
from re import T
def assess():
""" RESTful CRUD controller """
# Load Models
assess_tables()
impact_tables()
tablename = "%s_%s" % (module, resourcename)
table = db[tablename]
# Pre-processor
def prep(r):
if session.s3.mobile and r.method == "create" and r.interactive:
... | 7baf776ed295f6ad35272680c140c4283af7e90f | 4,883 |
def local_purity(H, y, nn=None, num_samples=10):
"""
:param H: embedding to evaluate
:param y: ground-truth classes
:param nn: number of neighbours to consider, if nn=None evaluate for nn=[1...size of max cluster]
:param num_samples: number of samples in the range (1, size of max cluster)
"""
... | afbe924bb8516ba6f9172534f57df58689768547 | 4,884 |
import re
def flatten_sxpr(sxpr: str, threshold: int = -1) -> str:
"""
Returns S-expression ``sxpr`` as a one-liner without unnecessary
whitespace.
The ``threshold`` value is a maximum number of
characters allowed in the flattened expression. If this number
is exceeded the the unflattened S-e... | 9109894ca1eeb2055ca48bc8634e6382f9e5557f | 4,885 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.