content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def rem(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the remainder when x is divided by a.
"""
if x == a:
return 0
elif x < a:
return x
else:
return rem(x-a, a) | 22b421c090970810f9aa4d55ff5a700e1301c0b8 | 3,626,300 |
def update_movie(movie_id):
"""Route handler for endpoint updating a single movie.
Args:
movie_id: An int representing the identifier for the movie to update
Returns:
response: A json object representing info about the updated movie
"""
movie = Movie.query.get(movie_id)
if mov... | e4062f327a077341e71e95d7b589f3bb4c36da5a | 3,626,301 |
def note_list(request):
"""Notes list view
"""
notes = NoteTable(Note.objects.all())
RequestConfig(request).configure(notes)
return render(request, 'note_list.html', {'notes': notes}) | 89c4537712f51ad9559ed04b74fcd774a7774a6a | 3,626,302 |
from datetime import datetime
def getDateTimeFromLocalTimeStamp(ts):
"""
Get a datetime structure from a timestamp.
"""
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
return st | 8282c16f50b34db9ac446fde4da020c614e6ac7f | 3,626,303 |
def c_roots(n, mu=False):
"""Gauss-Chebyshev (first kind) quadrature
Computes the sample points and weights for Gauss-Chebyshev quadrature.
The sample points are the roots of the `n`th degree Chebyshev polynomial of
the first kind, :math:`C_n(x)`. These sample points and weights correctly
integrat... | 0b70b09bdcaffdcd4857af1caaa96512c0720dc9 | 3,626,304 |
from sys import path
import os
def lamost(dr=2,cat='all'):
"""
NAME:
lamost
PURPOSE:
Load the LAMOST data
INPUT:
dr= (2) data release
cat= ('all') 'all', 'A', 'M', 'star' (see LAMOST docs)
OUTPUT:
data table
HISTORY:
2016-10-13 - Written - Bovy (UofT)
... | 0e16610472ce10bfdd493f613164c27fd0aea759 | 3,626,305 |
import platform
import subprocess
import re
import os
def get_env_prefix():
"""
Automatically identify os_type information which use for
install path of bash_completion.d
"""
TARGET_BIN_PATH = '/usr/local/bin/'
os_type = platform.system()
cygwin = r'CYGWIN|cygwin'
if os_type == "Linux... | fd290446484ae0f0392aaf4c34dc2feef0aa3553 | 3,626,306 |
def find_instance_nested(item, instances, match_key=None):
"""
Recursively find instances from lists, dicts, tuples.
`instances` should be a tuple of valid instances
If match_key is given the key must match for an instance to be added to the list of found instances.
"""
matches = []
def v... | 6ee2e7d936c162dcbdde40ca4b58a141568009d4 | 3,626,307 |
def get_filer_image(image_name="test_file.jpg", name="", original_filename=True):
"""
Creates and stores an image to filer and returns it
:param image_name: the name for the file (default "test_file.jpg")
:returns: filer image instance
"""
image = get_image(image_name)
filename = None
i... | 7446eeedd7078bd606006b1605b5406c0f230670 | 3,626,308 |
import subprocess
def check_output(args):
"""
Delegates to subprocess.check_output() if it is available, otherwise
provides a reasonable facsimile.
"""
if 'check_output' in dir(subprocess):
out = subprocess.check_output(args)
else:
proc = subprocess.Popen(args, stdout=subproces... | bbe456c8b3d2e8f1acd0f32478828ce44af7842f | 3,626,309 |
def import_table(file, sep = ","):
"""[Import table (csv or xlsx) into memory]
Args:
file ([string]): [file path]
sep (str, optional): [separator character that should be used]. Defaults to ",".
Returns:
[dataframe]: [the table imported]
"""
file_path = path_checker(file)
... | e821ac5bc6d22d21454525b91cfdf73f2b14ca0e | 3,626,310 |
def unixtime(tz = None):
"""
:param tz: [optional] tzinfo
:return: int
"""
return int(dt.datetime.now(tz).strftime('%s')) | 360b7e23fefe27d730224ac8fb59f46a59eab4be | 3,626,311 |
def demo7(response):
"""在每次请求后运行"""
# eg:修改响应头
print(response)
print('=========== after func run =============')
# response.headers['Content-Type'] = 'application/json;charset=utf-8;'
return response | 86991057bb48f1da33b3417387009d98744d2d94 | 3,626,312 |
def build_distance_layers(cyt_coord, nuc_coord, rna_coord, normalized=True):
"""Compute distance layers as input for the model.
Parameters
----------
cyt_coord : np.ndarray, np.int64
Array of cytoplasm boundaries coordinates with shape (nb_points, 2).
nuc_coord : np.ndarray, np.int64
... | 1b2b3cfd8edb43c8d294fcebd262244391ab8500 | 3,626,313 |
def one_hot_encode(arr, classes=None):
"""
One-hot encode a 1D array.
Based on this StackOverflow answer: https://stackoverflow.com/a/29831596/5863503
Parameters:
-----------
arr : array-like
An array to be one-hot encoded. Must contain only non-negative integers
classes : int or No... | 75d3db88a7ff6c590b3f5862ca2d6d59be149d0d | 3,626,314 |
import os
import sqlite3
def sql_connection():
"""
Establishes a connection to the SQL file database
:return connection object:
"""
path = os.path.abspath('./Twitter_Scraper_without_API/TwitterDatabase.db')
con = sqlite3.connect(path)
return con | f573a34537fb71c33ed9827bf5aa5068bdddf672 | 3,626,315 |
import array
def eig_banded(a_band, lower=False, eigvals_only=False, overwrite_a_band=False,
select='a', select_range=None, max_ev=0, check_finite=True):
"""
Solve real symmetric or complex Hermitian band matrix eigenvalue problem.
Find eigenvalues w and optionally right eigenvectors v of ... | 416953f0f7373bbf631ff94aa28b188af1c36273 | 3,626,316 |
def identity(value):
"""
Node returning the input value.
"""
return value | e1af1346b11bc36a4426ad3c557dc01045657de8 | 3,626,317 |
import asyncio
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
if CONFIG_MAIN_API_KEY in entry.data:
target_domain = "sensor"
elif CONFIG_TARGET_NAME in entry.data:
target_domain = "binary_sensor"
unload_ok = all(
await asyncio.gather(
*[hass.co... | 5f847cc9d2518b0b6d73568fe246ef1917ce6da8 | 3,626,318 |
import re
def strip(input_file_name):
"""
Remove all leading and trailing white-spaces, from 'input_file_name'.
And output result into into current directory.
Args:
input_file_name (str): path to input file
Returns:
int : number of modified lines.
"""
modified_lines = 0
p... | 203211f3ff7ee20a3417b1202b919dacd8291ef7 | 3,626,319 |
def render_post_ioc_init_elements(ioc: IOC) -> str:
"""
Render all of the post-iocInit elements for a given IOC instance
"""
return render_elements(ioc, "render_post_ioc_init") | 07f62ccca8e1325e8266dc7cb2e7cb71b8e83699 | 3,626,320 |
def getZnProjectors(xform_op, n_xforms, print_results=False):
"""
Returns operators which project on to symmetry subspaces associated with a given
symmetry transformation if the symmetry group is a cyclic group. Examples of appropriate
symmetries are translational or pure rotational symmetry.
Repre... | aa745c68393475203e3adb54e748495511fa06be | 3,626,321 |
def small_caves_multigraph():
"""
For each `big_cave` in `big_caves` and for each u, v in the neighborhood of `big_cave`,
add an edge (u, v) to `caves`. Afterwards, remove all big caves. The remaining
edges between the small caves now have multiplicity that can be used to count paths.
"""
caves... | d1c5ca007b2623c8d004d723d3022f89116be692 | 3,626,322 |
import logging
def train_model():
"""Train for a fixed number of steps and decode during training."""
rng = jax.random.PRNGKey(0)
model = create_model(rng)
optimizer = create_optimizer(model, FLAGS.learning_rate)
for step in range(FLAGS.num_train_steps):
batch = get_batch(FLAGS.batch_size)
optimize... | 1d91302b5b66c23e06db786091bf7657db8b4ba4 | 3,626,323 |
def rescale(arr, low=0, high=1, axis=None):
"""Return rescaled array, with values scaled between ``low`` and ``high``
Parameters
----------
arr : ndarray
numpy array to be rescaled
low : float (array scalar) or ndarray, optional
specifies the lower value(s) of the rescaled array
... | 198790b50ebd989ed99e26d68ebf399cc1c687ec | 3,626,324 |
import re
def named_numbers(token_vector):
""" Function to remove numbers out of an array of sentences.
Args:
token_vector (array): Array containing tokenized, lowercased sentence.
Returns:
array: Array containing tokenized sentence removed numbers.
"""
retur... | 6438e329af01e9da28f65f07f0e852096fead5f5 | 3,626,325 |
import re
def parse_members_for_workspace(toml_path):
"""Parse members from Cargo.toml of the worksapce"""
with open(toml_path, mode='rb') as f:
data = f.read()
manifest = data.decode('utf8')
regex = re.compile(r"^members\s*=\s*\[(.*?)\]", re.S | re.M)
members_block = regex.findall(manif... | 63926ac1eaadc360e2407f2fff5f41b7667e52b4 | 3,626,326 |
from typing import Union
from typing import Optional
from typing import Dict
from typing import Any
def _get(
parser: Union[Optional[ConfigParser], SectionProxy], key: str, overrides: Optional[Dict[str, Any]], defaults: Dict[str, Any]
) -> Any:
"""Get a value from a parser, overriding or setting a default as ... | 6ac806f5852c007ea56ca38ced726e47bf8a03e6 | 3,626,327 |
import time
def get_rate(net_card):
"""
统计每秒接收到的数据大小
:parma net_card: 网卡名字
:return : 返回未格式化的信息
"""
net_cards = []
old = [0, 0, 0, 0]
new = [0, 0, 0, 0]
if net_card is None: # 抓取全部网卡的速度
net_cards = net_io_counters(pernic=True).keys()
else:
net_cards.append(net_c... | d0dab4308c25e020a30a1172db91082b926ecfed | 3,626,328 |
def get_application(rawEvent):
"""Return application details."""
application = dict()
application["external_ip"] = rawEvent["details"]["browser"]["address"]
# Process user agent string.
userAgent = rawEvent["details"]["browser"]["user-agent"]
application["name"] = httpagentparser.detect(userAg... | 3e6cc7436a9b8abe7751590c1a1e3e1c40f2ea3a | 3,626,329 |
import torch
def steering(taus, n_fft):
""" This function computes a steering vector by using the time differences
of arrival for each channel (in samples) and the number of bins (n_fft).
The result has the following format: (batch, time_step, n_fft/2 + 1, 2, n_mics).
Arguments:
----------
ta... | c33264516e6903d22533c9f23585739438aa5d75 | 3,626,330 |
import numpy as np
def shoot(lon, lat, azimuth, maxdist=None):
"""Shooter Function
Original javascript on http://williams.best.vwh.net/gccalc.htm
Translated to python by Thomas Lecocq
"""
glat1 = lat * np.pi / 180.
glon1 = lon * np.pi / 180.
s = maxdist / 1.852
faz = azimuth * np.pi / ... | 732571c61b797c5018243b1aaa86f89d055566af | 3,626,331 |
from typing import Dict
def subsitute(clause: Clause, transformation: Dict[Argument, Argument]) -> Clause:
"""Applies given transformations to the clause.
Example: X -> a for P(X) will result in P(a)
"""
for t in transformation:
clause = Clause(
frozenset([substitute_literal(l, t,... | 04becf153a0f9138aeb73708d3cd2fc983dab9b7 | 3,626,332 |
def get_loss_fn_v2(loss_factor=1.0):
"""Gets a loss function for squadv2.0 task"""
def _loss_fn(labels, model_outputs):
start_positions = labels['start_positions']
end_positions = labels['end_positions']
is_impossible = labels['is_impossible']
_, start_logits, end_logits, cls_log... | b409a05462e745b907f891d92365e1d0e61ffbb1 | 3,626,333 |
from sys import path
def BuildUniverse(
use_simplified_universe: bool = False,
modified_types_filepath: str = None,
) -> presubmit_validate_types_lib.ConfigUniverse:
"""Generates the ontology universe.
Args:
use_simplified_universe: boolean to quick load minimal universe instead of
full ontolog... | b135dd4bf738bdd78e21498f32e032e928553456 | 3,626,334 |
def decodeXMLName(name):
"""
Decodes an XML (namespace, localname) pair from an ASCII string as encoded
by encodeXMLName().
"""
if name[0] is not "{": return (None, name.decode("utf-8"))
index = name.find("}")
if (index is -1 or not len(name) > index):
raise ValueError("Invalid enc... | 28a81aed2477b444ac061b21ca838912ee2bf24b | 3,626,335 |
def get_windowing(data):
"""
Retrieves windowing data from dicom metadata
Arguments:
data {pydicom data obj} -- object returned from pydicom dcmread()
Attribution: This code comes from Richard McKinley's Kaggle kernel
"""
dicom_fields = [data.WindowCenter,
data.Windo... | bfb7588126770c5b7403291f991351d18f23b2fd | 3,626,336 |
from typing import List
from typing import Tuple
def convert_mat_non_zero_to_inv_mat(n: int, non_zero_idx_pairs: List[Tuple[int,int]], mat_non_zero: np.array) -> np.array:
"""Convert list of matrice's non-zero elements into the matrice's inverse
Args:
n (int): Size of matrix
non_zero_idx_pai... | c580ff8a0ee79f3b434da58454670985e34b9567 | 3,626,337 |
def Logger_stringToLevel(str):
"""
Logger.stringToLevel(s)
parses a string and returns a Logger::Level
:param str s: the string to parse.
"""
return _roadrunner.Logger_stringToLevel(str) | 7fe5da5f6a7b59e436f2d6b6b7d277673db5a8c8 | 3,626,338 |
import os
import sys
import locale
import subprocess
import time
def execute(command, data_in=None, timeout=0, error=None):
"""
Execute a command and capture outputs.
On Python 2.6 it adds an option to ignore the deprecation warning from
the cryptography package after the first entry of the command p... | eaa08fe86ac431e6f5b3b086e4a739c18b8e66fa | 3,626,339 |
import sys
from io import StringIO
def run(command_line, manager_run, capture_stderr=False):
"""
Returns tuple of standard output and exit code
"""
sys_stderr_orig = sys.stderr
if capture_stderr:
sys.stderr = StringIO.StringIO()
sys.argv = command_line.split()
try:
ma... | 074d71873b7525eab7911cf74a6fa5c3e13cf46b | 3,626,340 |
def get_time_index(path,f):
"""Calculate the number and mass of objects around the centre of mass fro a fixed bubble size.
Parameters
----------
path
Location of hdf5 file from NBODY.
f
hdf5 file
Returns
-------
hdf_index
The index in hdf5 file corresponding t... | 04b155ff4254721399f3e3150914c63a0f055f87 | 3,626,341 |
def save_perm_score(perm_scores, fn, output_folder):
"""
Save the permutation scores to a NumPy array file.
"""
fn = fn + '.npy'
output_path = join(output_folder, fn)
np.save(output_path, perm_scores)
return output_path | 2b28ece5749212d8856dfd3dc6d48a27a5731c83 | 3,626,342 |
def htmlencode(text):
"""Use HTML entities to encode special characters in the given text."""
text = text.replace('&', '&')
text = text.replace('"', '"')
text = text.replace('<', '<')
text = text.replace('>', '>')
return text | a8d26fc21966c64b0daf1f9cbbdbcd2d2a7b9cf2 | 3,626,343 |
def append_entries(
log: list[Entry],
*,
previous_index: int,
previous_term: int,
entries: list[Entry],
) -> bool:
"""Append entries to the log.
This is both idempotent and destructive. If an entry is identical to
the entry that already exists at the index, it, along with any
subseq... | 2db32100fd67bf1b8de93994409bdf571868b7e2 | 3,626,344 |
def request(file_path):
"""Request file by the file path."""
try:
data = read_file(file_path)
mime_type = get_mime_type(file_path)
return data, mime_type, STATUS_CODES['success']
except Exception:
return server_error() | c18be5632ee7eb58c009a1e1ad74faff9bd243eb | 3,626,345 |
def v_include_complex_type(ctx, stmt):
"""Loads complex-types from a submodule.
Checks for complex-type collisions in a submodule.
"""
includes = stmt.search('include')
def get_module(i):
# check if the module to import is already added
modulename = i.arg
r = i.search_one('r... | 585cf6b98f9f8f3873705647288f8ca258506e6d | 3,626,346 |
def fix_roots(poles, fix_roots="incr", fix_mode="reflect"):
"""
Fix (stabilize) LP roots.
Parameters
----------
poles : ndarray
Array of LP roots (poles).
fix_roots : {'incr', 'decr'}
Type of roots which to consider bad and to stabilize. Either those
with increasing sig... | 52a11f4ba991530d077332c11143b39813bac596 | 3,626,347 |
from typing import Iterable
from typing import Dict
def parse_keyword_args(keywords: Iterable[str], args: str) -> (Dict[str, str], str):
"""
:param keywords: Valid keywords
:param args: String argument to parse
:return: (Dict of kwargs, remaining part of args)
"""
kwargs = {}
matches = _KW... | f8e4ecf3856ace099652b8bd04d62d05e16344f6 | 3,626,348 |
def is_lambda(fun):
"""
Check whether the given function is a lambda function.
>>> def not_lambda_fun():
... return None
...
>>> lambda_fun = lambda: None
...
>>> print(
... is_lambda(not_lambda_fun),
... is_lambda(lambda_fun)
... | 7ba75e47fee5f0eac5665ae790c4245a3118e183 | 3,626,349 |
import struct
def _read_gaussian_container(g_file):
"""Read a gaussian container in a binary format"""
# gaussian container
chk = g_file.read(8) # read string of 8bytes
if chk != "GAUSSVEC":
raise Exception("Error: the gaussian container" +
" is not of GAUSSVEC kind %... | 271a2d50d203d2925cd0b4aa4895314f904a3cbe | 3,626,350 |
def voigt_kernel(k, beta,gammaL):
"""Fourier Kernel of the Voigt Profile
Args:
k: conjugated of wavenumber
beta: Gaussian standard deviation
gammaL: Lorentian Half Width
Returns:
kernel (N_x,N_beta,N_gammaL)
Note:
Conversions to the (full) width... | 01e21bcd77f6db8ceb95d3b0425db2f39ad2acf3 | 3,626,351 |
def BOPTools_AlgoTools_GetEdgeOff(*args):
"""
* Returns True if the face theFace contains the edge theEdge but with opposite orientation. If the method returns True theEdgeOff is the edge founded
:param theEdge:
:type theEdge: TopoDS_Edge &
:param theFace:
:type theFace: TopoDS_Face &
:param ... | c121ee4b66cf55ec1eb5d3773a025bcab39e27cb | 3,626,352 |
import argparse
def parse_args() -> argparse.Namespace:
"""Parse user command line arguments."""
parser = argparse.ArgumentParser(
prog="ssacc",
description="Map SSA County Codes to ZIP Codes.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
... | 0ea9ec39d22c2908e9b72452b5553ca62ab02aa7 | 3,626,353 |
def get_voc( df, fit_window = 20 ):
"""
Get open circuit voltage.
:param df: A Pandas DataFrame containing JV sweeps, indexed by voltage.
:param fit_window: Window size to extrapolate if needed. [Default: 20]
:returns: A Pandas Series of open circuit voltages.
"""
df = df.sort_index()
... | 9640f83e807e0bba386a8ac3b270908e1959dfbc | 3,626,354 |
def calc_Rrup( Rx, Ztor, W, dip, azimuth, Rjb=None ):
"""
Compute the closest distance from site the the surface the fault
"""
if Ztor < 0:
print 'Ztor should be larger than 0'
raise ValueError
if W <= 0:
print 'Fault width should be larger than 0'
raise ValueError
if dip<=0 or dip > 90:
pr... | 2be536211aec6ed5f42406a04a7cf717d53fd931 | 3,626,355 |
import glob
import os
def getImagesAndLabels(path: str, resizeDims: int):
"""
For all images in a directory, returns resized images in an array
with a corresponding label based on their subdirectory.
"""
images = []
labels = []
for dir_path in glob.glob(path):
img_label = dir_path... | 8de3011c804865421b6fd15dd5a1d32ea8d2e499 | 3,626,356 |
def split_video_into_chunks(item):
"""
:param item
:return:
"""
item['subtitles'] = clean_subtitles(item['subtitles'])
vtt = pd.DataFrame(item['subtitles'])
if 'word' not in vtt.columns:
raise ValueError(f"'Word' not in item['subtitles'] \n{item}")
if 'title' not in item['info']:... | 1059303d850b24dc8bdf39f0cf20031cca58202d | 3,626,357 |
def not_equal(a, b):
#pdb.set_trace()
""" return 1 if True, else 0 """
name = "not_equal"
a2, b2 = COPY(a), COPY(b)
c = saferound(a2, sigfigs) != saferound(b2, sigfigs)
get_hashes(c, a, b)
return(bound(c)) | a58ac00d97cdf7777f731f6f42455992ff8f3031 | 3,626,358 |
def confidence_interval(A, axis=None, alpha=.05, metric=np.mean,
numResamples=1000, interpolate=True):
"""
Bootstrap confidence interval.
Return the bootstrap confidence interval of an array or along an axis
ignoring NaNs and masked elements.
Parameters
----------
A... | 83b4eddc7bcc5ede30ef5dedce7fd81ac83b5a79 | 3,626,359 |
def read_audio_record(audio_record, output_to_file=None):
"""
#https://stackoverflow.com/questions/42703849/audioset-and-tensorflow-understanding
"""
vid_ids = []
labels = []
start_time_seconds = [] # in secondes
end_time_seconds = []
feat_audio = []
count = 0
with tf.device("/c... | 0383904dacdb776187f36a6b3c0af2ef3d3413f1 | 3,626,360 |
import json
import logging
def _remove_source_ip_ubt_v1(vrf_name, **kwargs):
"""
Perform GET and PUT calls to remove the source IP address for UBT on a VRF.
:param vrf_name: Alphanumeric name of VRF
:param kwargs:
keyword s: requests.session object with loaded cookie jar
keyword url: ... | 9200a878988ce45f2d56266af6dd94cc4ed0f84d | 3,626,361 |
import six
def create_trigger_instance(trigger, payload, occurrence_time):
"""
This creates a trigger instance object given trigger and payload.
Trigger can be just a string reference (pack.name) or a ``dict``
containing 'type' and 'parameters'.
:param trigger: Dictionary with trigger query filt... | 36d4ec7dbb3494ed64f0e754ec2bab679179ac01 | 3,626,362 |
import os
def app_configuration():
"""
Gets the settings for the app for use in other functions and ajax for leaflet
Dependencies: os, App (app)
"""
return {
'app_wksp_path': os.path.join(App.get_app_workspace().path, ''),
'threddsurl': App.get_custom_setting("Thredds WMS URL"),
... | 47e700486111a420fc2284d5829a7ee2101dd45a | 3,626,363 |
from typing import Dict
from typing import Any
from typing import List
import copy
def move_to_location(
object_instance: Dict[str, Any],
location: Dict[str, Any],
object_bounds: List[Dict[str, float]],
previous_object: Dict[str, Any]
) -> Dict[str, Any]:
"""Move the given object to a new location... | 079f7367d04d732a93aa2ac18a1255a061e00243 | 3,626,364 |
import re
def findStationsWithinBoundingBox(config, bbox):
""" Find stations that lie within a bounding box
@param config ConfigParser containing the section 'GHCND' and option
'PATH_OF_STATION_DB'
@param bbox A dict containing keys: minX, minY, maxX, maxY, srs, where srs='EPSG:4326'... | dcf958abbcd101eb3ef4e5cbc3dee86aacdb8f9e | 3,626,365 |
from matlab import engine
from typing import Any
def start_engine() -> Any:
""" """
global MATLAB_ENGINE
if not MATLAB_ENGINE:
print("Starting Matlab")
if True:
MATLAB_ENGINE = engine.start_matlab()
else:
future = engine.start_matlab(background=True)
... | fb191a41a01e0731fe7ae2c397b30e2958b84ced | 3,626,366 |
def format_seq(seq,stop=False):
"""
Takes an amino acid sequence, returns a list of integers in the codex of the babbler.
Here, the default is to strip the stop symbol (stop=False) which would have
otherwise been added to the end of the sequence. If you are trying to generate
a rep, do not include t... | 3c553dcac989fe2bf649633842bb563a13325bbf | 3,626,367 |
def parser_maximum_bitrate_Descriptor(data,i,length,end):
"""\
parser_maximum_bitrate_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "maximum_bitrate", "contents" : unparsed_descriptor_contents }
... | a53ff1ce3f0c93aa37e78bd0f9af2a3b47f6df99 | 3,626,368 |
import warnings
def VACFtraj(traj, dt=1):
"""
Calculate/give velocity autocorrelation for a single trajectory.
The result of the calculation is stored in ``traj.meta['VACF']`` and
``traj.meta['VACFmeta']``. This function checks whether the corresponding
fields exist and if not calculates them. It... | f59689b6238f5a7ae6743b71d9f91f5a73b85621 | 3,626,369 |
import json
def status(request):
"""
Returns a simple HttpResponse
"""
response = "<h1>%s</h1>" % getattr(settings, 'PING_DEFAULT_RESPONSE', PING_DEFAULT_RESPONSE)
content_type = getattr(settings, 'PING_DEFAULT_CONTENT_TYPE', PING_DEFAULT_CONTENT_TYPE)
if request.GET.get('checks') == 'true':... | f35f4aaa0fc1fba11a35fcec69ca436022d5c807 | 3,626,370 |
def get_healthcare_py_str():
"""
Get the code str for the adult_easy pipeline
"""
with open(HEALTHCARE_PY) as file:
test_code = file.read()
return test_code | 16b5c5c7287a8e080367a2772b9d3f9b66670d99 | 3,626,371 |
def create_cluster_metadata(topic_partitions):
"""Create ClusterMetada out of a dict structure for easier mocking.
topic_partitions should be in the format of {'topic1': [partition1, partition2], 'topic2': [partition3]...}
"""
cluster_metadata = ClusterMetadata()
topics_dict = {}
for topic in t... | c4ea6fc43c23c0dc7a77a18c2d6c5921758873f4 | 3,626,372 |
async def custom_request_validation_exception_handler(
request: Request,
exception: RequestValidationError
) -> JSONResponse:
"""Custom handling of fastapi request validation errors"""
log.error(f'{request.method} {request.url.path} : {str(exception)}')
if route_has_tag(request, constants.V1_TAG):
... | 98113a251134f77c03703be3448ddcc8fddbf57c | 3,626,373 |
def complete_line(base_coord, targ_coord, word_len, row_length, column_length):
"""Return list of tuple coordinates which correspond to a straight line inside the matrix.
Args:
base_coord (tuple): A coordinate tuple of the starting position.
targ_coord (tuple): A coordinate tuple of the target ... | 127537093b47b686e284eb3c9585d891863a2af5 | 3,626,374 |
def decompose(data_with_size: bytes) -> list:
"""
Deserialize a byte string into a list of byte strings.
"""
(buf, size) = extract_size(data_with_size)
if size < 0:
raise BadFile()
xs = []
for i in range(size):
(buf2, chunk_size) = extract_size(buf)
chunk = buf2[:chu... | 179cc1d7d1c077c7bd04fe57c53c538218c61a95 | 3,626,375 |
import os
def _compute_name(name, extension, overwrite=False, path_name=SAVE_PATH):
"""Compute a file name, with the script name in prefix and time in suffix
Parameters
----------
name: string
The original name (e.g. "my_figure")
extension: string
The file extansion (e.g. ".txt")
... | e0d1ee518fb40d8f75751d56abeb911bdd1200d8 | 3,626,376 |
def find_stars (ra_cat, dec_cat, ra, dec, dist, search='box',
sort=False):
"""find entries in [ra_cat] and [dec_cat] within [dist] of [ra] and
[dec]; all in degrees
"""
# make a big cut in arrays ra_cat and dec_cat to speed up
index_cut = np.nonzero(np.abs(dec_cat-dec)<=dist... | 4a55d69d06be270f7da257f5fa214292d5773445 | 3,626,377 |
import requests
from bs4 import BeautifulSoup
def pgatour_statistic(url):
"""Get data on give pgatour statistic
Args:
url (str) : pgatour statistic url
Returns:
data of pgatour statistic
"""
with requests.Session() as session:
page = session.get(url)
... | 09a878a3f76999c9efd1963f52aadd52ef68c14e | 3,626,378 |
def align_ners(amr, nodeid2token, unaligned_node_ids=None,
flat_alignments=False, aformat=None):
"""
Align all elements on a NER subgraph that are not surface to the last
of the surface symbols
aformat = 'stack' ensures NER alignments match those of
stack-lstm/Transformer oracle
... | f5711472fcadbb8266acb69ed8e991ba7bd98ec6 | 3,626,379 |
from typing import Iterable
def open_uniform_bspline(control_points: Iterable['Vertex'], order: int = 4,
weights: Iterable[float] = None) -> BSpline:
""" Creates an open uniform (periodic) `B-spline`_ curve (`open curve`_).
This is an unclamped curve, which means the curve passes non... | 4f73622a7fadfc158ee8ab1204fd21544cbbf430 | 3,626,380 |
import optparse
def parse_args():
"""
Parse command line options into variables
"""
parser = optparse.OptionParser(usage="Usage: %prog [options]")
parser.add_option("--film-urls",
type="string",
dest="urls",
help=("Film URLs to pick from, separated by commas")
)
... | e618915c8c6a6211e208b3bca662ad951c46a507 | 3,626,381 |
import re
def get_services(path_obj):
"""
Return a list of GATT Service UUIDs for a given Bluetooth device D-Bus path
:param path_obj: D-Bus path for remote Bluetooth device
:return: List of GATT Service UUIDs
"""
found_services = []
valid_structure = re.match(r'/org/bluez/hci\d+/dev(_([0... | 91d4ba979fd40522d18b46873e70cda4fc0e4628 | 3,626,382 |
def get_env_generating_function(environment_config: EnvironmentConfig) -> t.Callable:
"""Returns a function that generates a Doom environment wrapper."""
return lambda: create_env(environment_config) | 37124d6a44053c69103e5437be6c9bbea3559b61 | 3,626,383 |
def normalize_error(error: str, error_types: set[str]) -> str:
"""Translate any "bad" error types to something more usable."""
error = app.config["OAUTH_FETCH_ERROR_TYPES"].get(error, error)
if error not in error_types:
return errors.SERVER_ERROR
else:
return error | aae5c5e9aceda765d8e26fa343ddc98468d6db07 | 3,626,384 |
def dict_to_joined_export(data, index, indices, name):
"""
Converts a dict into one or more tabular datasets
"""
output = {}
# TODO: test for _geolocation and attachment lists
if isinstance(data, dict):
for key, val in data.iteritems():
if isinstance(val, list) and key not in... | e634ef621d11a6636a3d1ea77b7bdca6ccef2d93 | 3,626,385 |
def inf_get_af2(*args):
"""
inf_get_af2() -> uint32
"""
return _ida_ida.inf_get_af2(*args) | 09acc8ea8b8bb2a6f624799af8445f27ba96d5e7 | 3,626,386 |
def plural(items_or_count,
singular: str,
count_format='',
these: bool = False,
number: bool = True,
are: bool = False) -> str:
"""Returns the singular or plural form of a word based on a count."""
try:
count = len(items_or_count)
except TypeEr... | 01f397579b60538f25710566507973bdc6422874 | 3,626,387 |
def Jaccrad(str1, str2):
"""
S2a,S2b计算
:param str1:
:param str2:
:return:
"""
if (len(str1.split('=')) == 1)|(len(str2.split('=')) == 1):
return 0, 0
# elif (str1 == 'None=str;1') | (str2 == 'None=str;1'):
# return 0, 0
elif (len(str1.split(';')) == 1)|(len(str2.split... | ccecba56bc2f9fcab0f37ebc5abbbc2ac68f9b45 | 3,626,388 |
import os
def load_distance_matrix(layer):
"""
Returns the distance matrix as defined by the features of the provided layer
Note that this must be generated beforehand using generate_dist_func
:type layer: str
:param layer: Feature layer
:return: numpy array
"""
return hkl.load(os.pa... | 1792148049946e41c67d5743c4dce31361f91493 | 3,626,389 |
from typing import List
from typing import Tuple
from typing import Union
from typing import Optional
from typing import Dict
from typing import Any
import os
import json
import tqdm
import multiprocessing
import functools
def many_pairs_featurize(
signature_pairs: List[Tuple[str, str, Union[int, float]]],
da... | be8b4cd386f9a2d246ef4d2587e0106a11ff4ab6 | 3,626,390 |
import sqlite3
def db_setup(db_name):
"""Database setup."""
cxn = sqlite3.connect(db_name, timeout=30.0)
cxn.execute('PRAGMA page_size = {}'.format(2 ** 16))
cxn.execute("PRAGMA journal_mode = WAL")
return cxn | 55092a98aed1e0a42ebf004a116913cfbecfb5f9 | 3,626,391 |
def _dstack_product(x, y):
"""Returns the cartesian product of the elements of x and y vectors.
Args:
x: 1d array
y: 1d array of the same dtype as x.
Returns:
a 2D array containing the elements of [x]x[y].
Example:
x = jnp.array([1, 2, 3])
y = jnp.array([4, 5]
_dstack_product(x,y)
... | f42525ab82f530e0be3446d6f868fc30a03b8671 | 3,626,392 |
from loopy.kernel.data import temp_var_scope
from loopy.kernel.tools import DomainChanger
from pymbolic.primitives import Subscript, Variable
from loopy.kernel.data import Assignment
def restore_and_save_temporaries(kernel):
"""
Add code that loads / spills the temporaries in the kernel which are
live acr... | 844edaa801c42e800fab6ce4f315537f7f5a1a12 | 3,626,393 |
import sys
def load_piece(fn_xml, fn_match, return_all_parts = False, return_units = False):
"""
Load a musicxml file and a match file
"""
parts = parse_music_xml(fn_xml)
assert len(parts) > 0
try:
divs = float(parts[0].timeline.points[0].get_next_of_type(Divisions, True)[0].divs)
... | 4e5fc3109dc16f5d45082b53c055372536eac359 | 3,626,394 |
def readMIG():
"""Reads the Mitutoyo profilometry gauges from HOST:PORT,
returning the values as a list of strings. Bad gauge(es) are
indicated by the string "MIG Error" instead of a value.
"""
# Open the network connection
try:
tn = Telnet(HOST, PORT)
except:
print('Telne... | 1f35735f6f0150a50cf1e9b3700be24a02edb7a4 | 3,626,395 |
def role_object_factory(role_name='role.test_role'):
"""Cook up a fake role."""
role = {
'nameI18n': role_name[:32],
'active': 1
}
return role | e79e7b22a83d9da721b074d32878eabeca4054cd | 3,626,396 |
def main_arg():
""" run all functions of heart_rate_monitoring file
:param: arg arguments from argparse
:return file: return user inputted file
:return brady: return user inputted bradycardia value
:return tachy: return user inputted tachycardia value
:return signal: return user inputted signal... | 880267f3faf87930689571fdba1a1233ca8dbae6 | 3,626,397 |
import os
def get_pager_command(text=None):
"""
Get the command to show a text on the terminal using a pager.
:param text: The text to print to the terminal (a string).
:returns: A list of strings with the pager command and arguments.
The use of a pager helps to avoid the wall of text effect whe... | 358ec55d2b9e297c1593258d33cdd1da0040262b | 3,626,398 |
def get_business_or_personal_relationship():
"""Saves as (B) or (P). This is the relationship type the user has to the contact"""
business_or_personal_relationship = input("Business or Personal | Enter Your Relationship to the Contact (enter B for business) or (enter P for personal), Then Press Enter: ")
i... | 0480dac7163c5a1f71209dff6a444254e6bba4b1 | 3,626,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.