content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def binary_search(items, desired_item, start=0, end=None,):
"""Standard Binary search program takes
Parameters:
items= a sorted list
desired_item = single looking for a match (groovy baby)
start= int value representing the index position of search section
end = end boundary of the sea... | 7adb942e73e5c3945190c7d88882763f9f7b4f08 | 3,595,449 |
def max_intensities(burst_list):
"""Removes all but the max intensity for each burst interval."""
max_bursts = [{(j, k): i for i, j, k in x} for x in burst_list]
return max_bursts | f29d7cb955904981fee31b6d6a98bf193dbc9d69 | 3,595,450 |
import functools
def convert_args(test_fcn, *test_args):
"""
Decorator to be using in formulas to convert ``test_args`` depending on
the ``test_fcn``.
:param test_fcn: A test function that converts arguments.
:type test_fcn: function
:param test_args: Names of args to convert using ``test_fcn... | ca731821ccb8fd77a7c199e51f041ebd82da07c9 | 3,595,451 |
def probabilistic_mapping(codon, productions):
""" Probabilistic mapping, using a PCFG."""
idx_selected_rule = len(productions) - 1
prob_aux = 0.0
for i in range(len(productions)):
prob_aux += productions[i][1]
if codon < prob_aux:
idx_selected_rule = i
break
... | 7dd3e5cd78cd6b32d59c1d62f761e8aeb1db1160 | 3,595,453 |
import importlib
def get_class(m):
"""Import class from string
:param m: string or class to be imported
:type m: str or class
:rtype: class
>>> get_class('microtc.textmodel.TextModel')
<class 'microtc.textmodel.TextModel'>
"""
if isinstance(m, str):
a = m.split('.')
... | 9a8c55524a47224a4e916191d66428aad2bc08d5 | 3,595,454 |
import math
def vec3(a, b, norm=1.0):
"""
x,y,z <- vec3(a, b, norm=1.0)
returns the vector a, b scale to norm
"""
dx = b[0]-a[0]
dy = b[1]-a[1]
dz = b[2]-a[2]
l = norm / math.sqrt( dx*dx + dy*dy +dz*dz)
return [dx*l, dy*l, dz*l] | db0f53cad9c472dd903cb18aabd1a6fad275b5bd | 3,595,456 |
def getCurrentWindow():
# type: () -> String
"""Returns the path of the current "main screen" window, which is
defined as the maximized window.
With the typical navigation, there is only ever one maximized window
at a time.
Returns:
The path of the current "main screen" window - the ma... | 3b99048a556c36e4c1560d9e1673c5d5ff0bde02 | 3,595,457 |
import math
def is_nan(value):
""" Function which identifies the "nan" on empty cells """
try:
return math.isnan(float(value))
except ValueError:
return False | a76abc6c047461786109d84cb002867eeec77888 | 3,595,458 |
def get_types(value_matrix):
""" Classify multi-column dataset by data type
and return a dictionary with type:[features]"""
types = {NUM_TYPE: [], CAT_TYPE: [], TXT_TYPE: [], IGNORE: []}
data = pd.DataFrame(value_matrix)
for column in data.columns:
column_type = get_type(data[column])
... | eabb1aa27594de2b0a6a5e4a88d95d7402e65429 | 3,595,459 |
def to_performance_event_representation(music: "Music", dtype=int) -> ndarray:
"""Encode a Music object to the performance event representation."""
seq = to_performance_event_sequence(music)
return np.array(seq, dtype=dtype) | 6d80e9ef90ccce90a7ad7a1bf87c9ea804b290aa | 3,595,460 |
def create_app():
"""Create and configure an instance of the Flask application"""
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = config('DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
DB.init_app(app)
@app.route('/')
def root():
DB.create_all()
... | 27fe329454c96e5050378da4fc3c4d175410ae2d | 3,595,462 |
def create_user(verification_status=None):
""" Create a new User instance.
Arguments:
verification_status (str): User's verification status. If this value is set an instance of
SoftwareSecurePhotoVerification will be created for the user with the specified status.
"""
user = UserFac... | 42dc20409d1c9cb21b293e7ade5fb674ff371085 | 3,595,463 |
import six
def create_eval_metrics_tuple(fn, kwargs):
"""Creates TPU eval metrics tuple.
Helper function to make eval_metric tuple (eval_metric_fn, fn_kwargs) used
by `TPUEstimator`. TPUEstimator requires that `eval_metric_fn` take
exclusively Tensor arguments. This helper can help create such a function fro... | ee839485e083db8553aebd3d8da403f5d3766282 | 3,595,464 |
def path_to_url(path):
"""Convert a system path to a URL."""
return '/'.join(path.split('\\')) | 79bfd1715420002371fe4201863d736bf9e3b2bf | 3,595,465 |
def list_commands(tk=None):
"""
Lists the system commands registered with the system.
If you leave the optional tk parameter as None, a list of
global commands will be returned. These commands can be executed
at any point and do not require a project or a configuration to
be present. Examples ... | f204934b649c642727cad95f871a589b43ffb897 | 3,595,466 |
def _use_reasonable_speed(preset, frame_count):
"""Return a reasonable speed parameter for the given animation length."""
return preset.settings.get("speed", 0.25) * (frame_count / 30.0) | 9327131fbe8f55ba1ee5c1ccc932132ad3d3162a | 3,595,467 |
def _get_user_by_username(username:str) -> t.Optional[User]:
"""
get the user object if the entered username
present in the database or return None.
:param username:
provide the username to get the User object or None.
"""
user:t.Optional[t.Type["User"]] = User.query.filter_by(username... | e50342b225b973be9d767c7928d4ef77aedcb88f | 3,595,468 |
def blend_color_dodge(cb: float, cs: float) -> float:
"""Blend mode 'dodge'."""
if cb == 0:
return 0
elif cs == 1:
return 1
else:
return min(1, cb / (1 - cs)) | 5a96383ce6f71aca42639c7ac4962ea74ecd02c6 | 3,595,469 |
def change_domain_level(host, domain_level):
"""
>>> change_domain_level('192.168.2.1', 2)
'192.168.2.1'
>>> change_domain_level('192.168.2', 2)
'168.2'
>>> change_domain_level('', 2)
''
>>> change_domain_level('indiana.facebook.com', 2)
'facebook.com'
>>> change_domain_level('fa... | 641e2e78463d90c489a9add44ad314774825735f | 3,595,470 |
def radix_sort(array):
"""
Radix Sort
Complexity: O((N + B) * logb(max)
Where B is the base for representing numbers and
max is the maximum element of the input array. We
basically try to lower the complexity of counting sort.
Even though it seems good, it's good in specific cases only.
... | 2ca57406f0d0190ce8849c50e1ffcadf382db328 | 3,595,471 |
import requests
def get_single_asset(
asset_contract_address=None,
token_id=None,
account_address=None,
):
""" Query Opensea API for signle asset with user inputs.
Args:
asset_contract_address (str, Req): Address of the... | 9c5246711b1e9d5e08e85a35156005ded8dc4d84 | 3,595,472 |
import torch
def quatLoss(R1:torch.Tensor, R2:torch.Tensor) -> torch.Tensor:
"""Computes L1 loss between quaternion rotations by comparing their SO3 rotations"""
return torch.sum(torch.norm(quat_to_RotMat(R1) - quat_to_RotMat(R2), p=2, dim = -1)) / len(R1) | a69945f32c150f16a3495dbfecddf20a6e6a2ce3 | 3,595,473 |
def mock_xonsh_session(monkeypatch, xonsh_events, xonsh_session, env):
"""Mock out most of the builtins xonsh attributes."""
# make sure that all other fixtures call this mock only one time
session = []
def factory(*attrs: str):
"""
Parameters
----------
attrs
... | fbb50b5717b082101b72bf7e787fc69ec7ebb7c6 | 3,595,474 |
from typing import Dict
from datetime import datetime
from pathlib import Path
import json
def _setup_run(cfg: Dict) -> Dict:
"""Create folder structure for this run
Parameters
----------
cfg : dict
Dictionary containing the run config
Returns
-------
dict
Dictionary cont... | b663c75ed13c77948c60d8bc8d7e46b2a6b94701 | 3,595,475 |
def rebuild_unpacked_request(unpacked_req):
"""
Takes an unpacked (user_metrics.utils.unpack_fields) RequestMeta object
and composes a RequestMeta object
Parameters
~~~~~~~~~~
unpacked_req : dict
This dictionary contains keys that map to the attributes o... | 6ff05a94bf83155e6e447fe577c3e4aa217f6082 | 3,595,476 |
def sphere(x):
"""Minimum at 0"""
return x.dot(x) | 67c24f0b5fd711ec9618284f800b75d1db894938 | 3,595,477 |
from typing import List
from typing import Tuple
def read_module_source_from_file(id: str,
lib_path: List[str]) -> Tuple[str, str]:
"""Find and read the source file of a module.
Return a pair (path, file contents). Return (None, None) if the module
could not be found or r... | c74056072f09298f1e8c58be6cd603bbafea7767 | 3,595,478 |
import math
def gamma_scalar_gluon(m_med, g_q):
"""Function to calculate gluon width of a scalar mediator
:param m_med: mediator mass
:type m_med: float
:param g_q: quark coupling
:type g_q: float
"""
alpha_s = 0.130
v = 246
gamma = alpha_s ** 2 * g_q**2 * m_med**3 / (32 * math.pi... | 0d297bd54b736f3cdc95630e0a2bf2d9a075b8b9 | 3,595,479 |
from datetime import datetime
def find_or_create_user(first_name, last_name, email, password, role=None):
""" Find existing user or create new user """
user = User.query.filter(User.email == email).first()
if not user:
user = User(email=email,
first_name=first_name,
... | b9aeb69a775607269a317eb596ee6a1813108905 | 3,595,480 |
def preprocess(f_n, cs=[0, 1], channel_max=CHANNEL_MAX):
""" Preprocessing function (before model-specific preprocess_fn)
Args:
f_n (str): file path/single cell patch identifier
cs (list of int, optional): channels in the input
channel_max (list of float, optional): max val for each cha... | 0ca6adaf71cca02521cb999e1d955bfb52c6dbae | 3,595,481 |
from typing import Dict
def update_player(table: dynamodb.Table, player_token: str, update_map: Dict) -> Dict:
"""
Function to update player information in DynamoDB
:param table: DynamoDB table object
:param player_token: Player ID token linking player to database entry
:param update_map: Diction... | ee9b332fb0b8567493c9254168ff0a655fc32441 | 3,595,482 |
from typing import Type
def make_enum_parser(enum: Type[EnumType]) -> partial:
"""Makes a parser function for enum classes"""
return partial(_make_enum_parser_worker, enum) | 85943826b8bfc75d3a4fce4c3e03ae0d464c1d88 | 3,595,483 |
import requests
import html
import re
def zh_word(word):
"""
Function to define Chinese words and return their readings and meanings. A Chinese word is one that is longer than
a single character.
:param word: Any Chinese word. This function is used for words longer than one character, generally.
... | d1ff2ca58d1e33c0457bf108afb0272f483c27c8 | 3,595,484 |
def is_neutrino(pdg_types):
"""flavor string -> is_neutrino"""
pd = km3pipe.extras.pandas()
return pd.Series(pdg_types).apply(_p_eq_nu) | 6def921f9fe98ae7c8819fe663683aa3014f537c | 3,595,485 |
def make_wcs_for_quats(quats, pixsize=20./3600.):
"""
compute standard realization of the wsc for the provided quaternions
-------
params:
quats : a set of quaternions, for which wcs will be computed
returns;
wcs computed with determined algorithm
"""
vedges = offset_to_vec... | 803e420cf0b9380b6bb6a675cab096963ddf1f86 | 3,595,486 |
def rs_mpc(
horizon=20,
num_samples=1000,
# Adam optimizer settings
lr_dyn=1e-3,
# Training settings
minibatch_size=100,
# Replay Buffer settings
replay_start_size=5000,
replay_buffer_size=1e7,
):
"""
Rnadom shooting MPC (RsMPC) control pre... | 066ba8ffef03e7b3e5b0cacde9b6eeeabd18e89e | 3,595,487 |
def lookRotation(forward, up):
"""
Quaternion that rotates world to face Forward, while keeping orientation dictated by Up
See https://answers.unity.com/questions/467614/what-is-the-source-code-of-quaternionlookrotation.html
:type forward: np.array
:type up: np.array
"""
up /= np.linalg.no... | 5a1884eba4bf174ced8933d1b3b4f44077bb70e4 | 3,595,488 |
def tens2rgb(t):
"""Tensor (HWC) to RGB, [0, 1] -> [0, 255]"""
t = t.detach().cpu().numpy()
return (t * 255).astype('uint8') | 63b8977b69517ed3f5ab5aba006e7d121dc43d53 | 3,595,489 |
import re
def mosaic_date_parser(project_name):
"""
Parses the project name into a date.
Parameters
----------
project_name : str
The project name as a string.
Returns
-------
The date and time (for April 8 b)
"""
# The date is always a sequence of 6 numbers in ... | 46d5cb442ebd8c166ced3c2b509ffa414a627122 | 3,595,491 |
def bayehem(k):
"""
Bayehem function input k-mer val
"""
if k[0] % 2 == 0:
k = k+1
job_id = "k{}".format(k)
assembly_path = evaluate(k)
score = likelihood(assembly_path, k)
return score | a448cfb8e901534746de6c4d46b4937d4a8c75bc | 3,595,492 |
def create_imagelist(pd_dataframe, img_dir, ext):
"""
Creates a list of image paths of the thumbnails
Keyword arguments:
pd_dataframe -- pandas DataFrame object containing the stub info
stub_directory -- location of stub info files
ext -- File extension of the thumbnail
"""
imgs = []... | 1d41b1b02eab9123624c765b1529739b387e3e9c | 3,595,493 |
import torch
def spatial_argmax(logit):
"""
Compute the soft-argmax of a heatmap
:param logit: A tensor of size BS x H x W
:return: A tensor of size BS x 2 the soft-argmax in normalized coordinates (-1 .. 1)
"""
weights = F.softmax(logit.view(logit.size(0), -1), dim=-1).view_as(logit)
... | 07270448b0ed3f5482b5601df6f5953b1fde5cdc | 3,595,494 |
def compute_signing_root(ssz_object, domain: Domain) -> Root:
"""
Return the signing root of an object by calculating the root of the object-domain tree.
"""
domain_wrapped_object = SigningRoot.create(
object_root=ssz_object.get_hash_tree_root(),
domain=domain,
)
return domain_wr... | e42c8ffa551377cb688b6eb8e35c0b1e79d57454 | 3,595,496 |
import logging
import time
def train(dt, model_name,
model_params={},
output_path= None,
fold_num= 5,
cv_params=None,
retrain=False,
cv_process_num=1):
"""
train a SOL model
Parameter
---------
dt: DataSet
the dataset used to tra... | d1494b3a73bedca16205477da618f585196e5f5e | 3,595,498 |
def count_cond(condition):
"""Returns a function with one parameter N that counts all the numbers from
1 to N that satisfy the two-argument predicate function Condition, where
the first argument for Condition is N and the second argument is the
number from 1 to N.
>>> count_factors = count_cond(lam... | 518ea49365b5a4fba1180325302591b97f323478 | 3,595,500 |
def new(key, *args, **kwargs):
"""Create a new Blowfish cipher
:Parameters:
key : byte string
The secret key to use in the symmetric cipher.
Its length can vary from 4 to 56 bytes.
:Keywords:
mode : a *MODE_** constant
The chaining mode to use for encryption or decryptio... | b32181cdef56723e7ea577218f04a508b8aa2e79 | 3,595,502 |
from datetime import datetime
def isoformat(datetime_obj=None, *, preserve_subsecond=False, compact=False):
"""Return datetime to ISO 8601 variant suitable for users.
Assume UTC for datetime objects without a timezone, always use
the Z timezone designator."""
if datetime_obj is None:
datetime_... | 68a4ff591592ea1b845b5bef68b1da3425c419b2 | 3,595,504 |
def drop(n, xs):
"""
drop :: Int -> [a] -> [a]
drop(n, xs) returns the suffix of xs after the first n elements, or [] if n >
length xs
"""
return xs[n:] | e9261686022f5419edade3b47e82c68bd52b5cd8 | 3,595,505 |
def spending_by_category(session, user, budget_id, filter=None):
"""Report the user's spending by category."""
check_session(session)
check_user(user)
# Check existence and authorization for budget id
_load_budget(session, user, budget_id)
q = q_report_by_category(session, budget_id, filter=fi... | 18b267584c81b329dc781c46c07646a4c4a33f1d | 3,595,506 |
import time
def get_cluster_capacity(cluster_name):
"""
:param cluster_name: 集群名称
:return: 容量信息
"""
cluster_capacity = {
"slot_capacity": 0,
"slot_capacity_used": 0,
"slot_usage": 0,
"used_size": 0,
"max_size": 0,
"storage_usage": 0,
"segment... | 85f7b6eeb99e903cd8bad110f5569ae99e471ec7 | 3,595,507 |
def edit_group_view(request):
"""
Update a group by name.
"""
group = ar.get_group_matchdict_checked(request, group_name_key="group_name")
special_groups = [
get_constant("MAGPIE_ANONYMOUS_GROUP", settings_container=request),
get_constant("MAGPIE_ADMIN_GROUP", settings_container=requ... | ce6bd641959bd0e601f886d7dfc0d671fd508715 | 3,595,508 |
def lnprior_difference(p):
"""
log-normal prior on step-by-step changes
"""
# Parameters must all be > 0
if p.min() <= 0:
lp = -np.inf
else:
dpdt = np.diff(np.log(p))
mu = 0.0 # mean expected change - no change
#sigma = np.log(2) #standard deviation - factor of ... | 3866120d9c02b5e9e6e1268320ddd98e8f4dd63f | 3,595,509 |
def postscriptSlantAngleFallback(info):
"""
Fallback to *italicAngle*.
"""
return getAttrWithFallback(info, "italicAngle") | 46f4fc380f1471f9e84b856d1a136cad2714fb21 | 3,595,510 |
def get_pace_units_str(distance_units, time_units):
"""Returns the units in which pace is displayed."""
units_str = ""
if time_units == UNITS_TIME_MINUTES:
units_str = "mins"
elif time_units == UNITS_TIME_SECONDS:
units_str = "secs"
elif time_units == UNITS_TIME_HOURS:
units... | ba9da18da5b4a8555c1d3614ee7dfb0d023099e1 | 3,595,511 |
import itertools
def create_cluster_frame(
histogram_edges,
histogram_values,
bins,
clusters,
columns,
cluster_column_name="CLUSTER",
):
""" Constructs a Data Frame from a histogram and cluster results
Parameters:
histogram_edges (list of nparray): Edges of the bins in every d... | dcaadb24379373a597cd9d24a527b7d0af13cce3 | 3,595,512 |
def purchaseProduct(userID, productID):
"""
Have a user purchase a product
If the user has sufficient funds, they will be transferred to the product's
owner, and the product will be marked as sold
Parameter:
userID: ID of user buying the product
productId: ID of the produ... | 32f1588bcedeff0cf9fbe7648c3518e25bfc7d32 | 3,595,513 |
def sklearn_trainer(
config: SklearnTrainerConfig,
x_train: np.ndarray,
y_train: np.ndarray,
) -> ClassifierMixin:
"""Train SVC from sklearn."""
clf = LogisticRegression(
penalty=config.penalty, solver=config.solver, tol=config.tol, C=config.C
)
clf.fit(x_train.reshape((x_train.shape... | ed2cff994fe7216698749786508145cd72dd7011 | 3,595,515 |
import struct
def _load_point(big_endian, type_bytes, data_bytes):
"""
Convert byte data for a Point to a GeoJSON `dict`.
:param bool big_endian:
If `True`, interpret the ``data_bytes`` in big endian order, else
little endian.
:param str type_bytes:
4-byte integer (as a binary... | 024358e4b8a46339b7ce50b90a79235ff1448ffa | 3,595,518 |
def find_progens(pid_current, pid_target, gid_current, gid_target, pid_hash, n_most=1, min_in_common=0.1, nproc=1):
"""Find most massive and second most massive progenitor/descendants.
Parameters
----------
pids_current : np.ndarray
particle IDs from the current snapshot.
pids_target : n... | bafaa6524ce03234587385179fb644bf6732f8d9 | 3,595,519 |
def intrinsic_mutual_information_constructor(func): # pragma: no cover
"""
Given a measure of shared information, construct an optimizer which computes
its ``intrinsic'' form.
Parameters
----------
func : function
A function which computes the information shared by a set of variables.
... | e497a638dbc4ead926561940919b56831b14f214 | 3,595,520 |
def hist(x: np.ndarray, bins: int) -> np.ndarray:
"""Return the values of the histogram."""
return np.histogram(x, bins)[0] | 419b328c036ada799e851dd47737020bc231a65d | 3,595,521 |
def aniso_magic_nb(infile='specimens.txt', samp_file='samples.txt', site_file='sites.txt', verbose=True,
ipar=False, ihext=True, ivec=False, isite=False, iloc=False, iboot=False, vec=0,
Dir=[], PDir=[], crd="s", num_bootstraps=1000, dir_path=".", fignum=1,
save_p... | 1b73227dd3065479230426761dfffb4978880909 | 3,595,522 |
import requests
import re
def get_extension_details(extension: str, lang: str = 'en'):
"""
Get Extension Details
Parameters
----------
extension: Extension Name
lang: Lang
Returns
-------
None: Can't Find
Or (a, b, c)
a:Description b: English Description c:Applications Lis... | b155b95d84c88aacfd37409f8816dac497978cac | 3,595,523 |
def QueueMetricsView(request): # pylint: disable=invalid-name
"""Exports /api/plugins/capacity-metrics/rq-metrics as a Django view."""
return ExportToDjangoView(request, view="rq-metrics") | b06c8d503c5e3cc46831b7b4bea07999c6063be1 | 3,595,524 |
from rpython.tool.frozenlist import frozenlist
def get_deep_immutable_oplist(operations):
"""
When not we_are_translated(), turns ``operations`` into a frozenlist and
monkey-patch its items to make sure they are not mutated.
When we_are_translated(), do nothing and just return the old list.
"""
... | 833a3ec67e27d256999e5e8d7f85433a616b2ce3 | 3,595,525 |
def encodePadData_x(x, word2ind, maxlen, ukn_words, padding_style):
"""
Transform a data of words in a data of integers, where each entrie as the same length.
:param x: The data to transform
:param word2ind: Dictionary to retrieve the integer for each word in the data
:param maxlen:... | 3683ed8044e23b38fbd47dfa709f11d5d8730f68 | 3,595,526 |
import re
from io import StringIO
import csv
def load_ballots_from_file(filename):
"""
SIMPLE STAR format examples
n,A,B,C
2,0,2,5
3,5,4,3
n:A,B,C
2:0,2,5
3:5,4,3
A B C
0 2 5
5 4 3
"""
# Parse SIMPLE STAR as CSV
valid_delims = ['\s', ':', ',']... | 20686b1e1e15d8419733e10240a00d5baea787cc | 3,595,527 |
from typing import Callable
from typing import Any
from typing import Tuple
def dispatch_work(cost_function: Callable[[np.ndarray, Any], float],
worker: EvoStratWorker,
pop_id: int,
worker_id: int) -> Tuple[float, int, int]:
"""
Dispatches a new population... | 6c6e44f719ba97fc8eff3aaefb3a5cca807115cc | 3,595,528 |
from typing import Optional
def get_authentication_flow(alias: Optional[str] = None,
realm_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAuthenticationFlowResult:
"""
This data source can be used to fetch the ID of... | 632353342b17c449afaeba2f2ff5a83daf0f1cd8 | 3,595,529 |
from lane_lines_finder.perspective_transform import PerspectiveTransform
def perspective_transform(inverse=False):
"""
Transform used in Udacity self-driving-car nanodegree
:param inverse: if the transform must be done or undone
:return: PerspectiveTransform
"""
return PerspectiveTransform(sou... | fa7af039d248a1a4562ca0155b15592fd86158c8 | 3,595,530 |
def MLPMixer(*, image_size, channels, patch_size, dim, depth, num_classes, expansion_factor=4, dropout=0.):
"""An MLP-Mixer model."""
assert (image_size % patch_size) == 0, 'image must be divisible by patch size'
num_patches = (image_size // patch_size) ** 2
chan_first, chan_last = partial(nn.Conv1d, ke... | 4477f7c388da6d65e1c7e6702875705aaa2ef416 | 3,595,531 |
def backwards_search(p, cl, rank, total_length):
"""Perform backwards search using pattern p, count lookup cl and rank rank
reference http://alexbowe.com/fm-index/"""
start = 0
end = total_length - 1
for i in range(len(p)-1,-1,-1):
if end < start:
break
ch... | f8e87dc65b3838d99b7162e1c2ff0eb12b815180 | 3,595,532 |
def formatIntervalHours(cHours):
""" Format a hours interval into a nice 1w 2d 1h string. """
# Simple special cases.
if cHours < 24:
return '%sh' % (cHours,);
# Generic and a bit slower.
cWeeks = cHours / (7 * 24);
cHours %= 7 * 24;
cDays = cHours / 24;
cHours %= 24;... | d7c9be3110eb1ecbfb57ae51854d2e576519ced3 | 3,595,533 |
def _false_discovery_adjust(pvals, return_index=False):
"""Performs the Benjamini-Hochberg procedure for controlling false discovery rate.
Parameters
----------
pvals : 1D array-like
p-values to be adjusted
return_index : bool, optional
If true, will return the indices to sort the o... | eafb27783e7d70c669cd6018d7b33a8bf3f5d920 | 3,595,534 |
def cluster_row(name, parent) -> Row:
"""NB! this is not a descriptor, but an actual Row"""
return Row(by_xpath(f'//tr[./td/a[text()="{name}"]]'), parent) | 3df7b2b523f523586830f8047700c125aa83a8d9 | 3,595,535 |
def swap_http_https(url):
"""Get the url with the other of http/https to start"""
for (one, other) in [("https:", "http:"),
("http:", "https:")]:
if url.startswith(one):
return other+url[len(one):]
raise ValueError("URL doesn't start with http: or https: ({0})".f... | b0af8770ef31f73afa5c95c6bc2a17488eb3d1e2 | 3,595,536 |
import time
def is_input_valid(player, text_box):
"""
check whether the word/characters that the player is trying to enter/save are valid or not.
Args:
player (Player): The Player/user
text_box (TextBox): the text box where the player/user types the words/characters
Returns:
b... | 2e4276da63b34850412e6de534b2ea7ec0155cb5 | 3,595,537 |
def cel2gal(ra, dec):
"""
Converts Celestial J2000 (deg) to Calactic (deg) coordinates
"""
dec = np.radians(dec)
sin_dec = np.sin(dec)
cos_dec = np.cos(dec)
ra = np.radians(ra)
ra_gp = np.radians(192.85948)
de_gp = np.radians(27.12825)
sin_ra_gp = np.sin(ra - ra_gp)
cos_ra_... | a0ca5f4d69cad5672f7dcc588b3d5272f9e09ae8 | 3,595,538 |
def fuzzy_score(search, against, apply_same_case_bonus=False):
"""
Returns the matching score of a *search* string *against* another one.
If case matters, the *apply_same_case_bonus* argument can be set to ``True``
to apply a bonus on a matching characters that have the same case. You
usually do no... | bba975833276910a9e3ed6953aca158eaf20a648 | 3,595,540 |
def list_to_dict(lst):
"""
Takes a list an turns it into a list
:param lst: the list that will be turned into a dict
"""
if len(lst) % 2 != 1:
odd_indexes = []
even_indexes = []
for i in range(len(lst)):
if i % 2 == 0:
odd_indexes.append(lst[i])
... | 2c84950f68cb2e8180511f010a558f370d3ac1ac | 3,595,542 |
import urllib
def get_catalog_id(base_url):
"""Retrieve CVMFS catalog ID from the manifest"""
manifest = urllib.urlopen(base_url + '/.cvmfspublished')
for line in manifest:
if line.startswith('C'):
return line[1:].strip()
raise ValueError('Catalog ID not found in manifest') | 7b3bf5a1f9c3df749f84ba8f8b38ed1c4dc29c6c | 3,595,543 |
def Liquid_Enthalpy_Ref_Liquid(T, Cn_l, T_ref, H_ref):
"""Enthapy (kJ/kmol) disregarding pressure and assuming the specified phase."""
return H_ref + Cn_l.T_dependent_property_integral(T_ref, T) | 5ac806600e59777ee64cc1564677d5d5f38d6540 | 3,595,544 |
def find_version_timestamp_udd(package, version, dbname='udd',
uname='schaliasos', passwd='udd'):
"""Find the release timestamp of a debian project
Args:
project (str): name of project
version (str): version of project
Returns:
data (str): timestamp i... | 29c89d1915a7f3d9baab462f264e74f3311bc89c | 3,595,545 |
import copy
def sortindexes(self):
"""Sorts a list of indexes in an ascending order with no regard to parity"""
selfcopy = copy.deepcopy(self)
alwaystrue = 1
while (alwaystrue):
done = 1
for nindexa in range(len(selfcopy)):
if (not done):
break
indexa = selfcopy[n... | f791bfe39130645ad2e33ef54c3a8c25e5964998 | 3,595,546 |
import requests
def post_answer(year, day_num, level, answer):
"""HTTP POST the problem output.
Once the right answer is submitted, the URL becomes invalid
:param year:
:param day_num:
:param level:
:param answer:
:return:
"""
output_request = requests.post(
"https://adven... | 4d2f5f70d5bb8e234f412b9136a423776f792a5e | 3,595,547 |
import inspect
def get_payloads_with_schemas(from_module):
"""Get the Payload classes with SCHEMAs defined.
:param from_module: module from which to get the classes.
:returns: list of Payload classes that have SCHEMAs defined.
"""
payloads = []
for name, payload in inspect.getmembers(from_mo... | 8f6a3381f8a2c5b70d80ddec82fe41bf3631f48d | 3,595,548 |
def decode_number(data):
"""Decode `data` representing a number."""
if hasattr(data, '__int__'):
return data
elif not is_string(data):
success = False
elif not data.startswith('0x'):
success = False # must start with 0x prefix
elif len(data) > 3 and data[2] == '0':
s... | 98b1f7b40bf6b678a32cdc6f24e98590c836c4a4 | 3,595,549 |
from pathlib import Path
def get_logo_path_for_code(code: str) -> Path:
"""Return the path to the cached country logo"""
return country_logos_path / f"{code}.png" | 48628ff385a2643fd2a878c8cf2f3b853e77bb83 | 3,595,550 |
def load(path, parser=None, grammar=None, decoder=None, **kwargs):
"""Returns a Python object from parsing the file at *path*.
:param path: an :class:`os.PathLike` which presumably has a
PVL Module in it to parse.
:param parser: defaults to :class:`pvl.parser.OmniParser()`.
:param grammar: defa... | dabb18b9b36ac352ce7642441da3b381483c63c6 | 3,595,553 |
def attachURI(metaDict, acc, con, obj):
"""Add URI to dict as `label`"""
if obj != "" and obj is not None:
uri = '/'.join(['', acc, con, obj])
elif con != "" and con is not None:
uri = '/'.join(['', acc, con])
else:
uri = '/' + acc
return {uri: metaDict} | a4b584a041fc9c02b6bdfed9ba61eb3029cc34d2 | 3,595,554 |
def udf_remove_signature(text) -> str:
"""
input:
<event v="3.00">
...
<Signature>
...
</Signature>
</event>
output:
<event v="3.00">
...
</event>
"""
row = etree.fromstring(text, pars... | 100605d3e44cee0cd5e4976c8f7157c237e00295 | 3,595,555 |
from typing import Callable
def loop_in_thread(loop: Loop) -> Callable[[], None]:
"""
Start the given loop in a thread, let it run indefinitely, and
return a function which can be called to signal the loop to stop.
>>> from time import sleep
>>> loop = aio.get_event_loop()
>>> stop = loop_i... | 1df119e396424c5be8389dd30bfb4a01b3dc7228 | 3,595,556 |
import requests
import json
def get_records_from_imoox(endpoint: str) -> dict:
"""Get the response from imoox."""
response = requests.get(endpoint)
return json.loads(response.text.encode("utf-8")) | 8ec1b2aa62341e2c126a9d42a212d2b592385a64 | 3,595,557 |
def standardize_sk(X):
"""
使用 sklearn的库函数实现标准化,方便反标准化操作.
"""
scaler = StandardScaler()
print("Your input data type is: ", type(X))
standard_X = scaler.fit_transform(X)
return scaler, standard_X | 76e7516eef63e9ba06c8a85209b8eacdf6b7668d | 3,595,558 |
def stop_endpoint_security_assessment_command(client: Client) -> CommandResults:
"""Stop a running endpoint security assessment.
Args:
client (Client): Cymulate client.
Returns:
CommandResults: A CommandResults object that is then passed to 'return_results',
contain... | 40d2dc27cbca68d95c8b3596c9a34ee73b4834c1 | 3,595,559 |
def get_q(house_insulation_type, floor_bath_insulation,
U_roof, U_wall, U_door, U_window, U_floor_bath, U_floor_other,
U_base_etrc, U_base_bath, U_base_other,
Psi_prm_etrc, Psi_prm_bath, Psi_prm_other,
Psi_HB_roof, Psi_HB_wall, Psi_HB_floor, Psi_HB_roof_wall,
Psi_HB_wal... | f1ea71cdccc3ef90aebef329f42961c6949697fa | 3,595,560 |
def get_both_filenames(filename):
""" Get a list of both filenames for FUV data
Regardless if rootname_corrtag_a.fits or rootname_corrtag_b.fits
is passed in, both will be returned in a list.
Parameters
----------
filename : str
full path to COS file
Returns
-------
files ... | 76449b6f2719d5c6b7ee6dd01f730b9193e368da | 3,595,561 |
def get_font(name, style=STYLE_NORMAL, ftype=None):
"""Retrieves the best matching font file for the given name and
criteria.
"""
retvals = get_fonts(name, style, ftype)
if len(retvals) > 0:
return retvals[0]
return None | 4c9b5521cdcafc5045ea72f99fcad6dbac958424 | 3,595,562 |
def get_data(data_creator):
"""
使用参数data_creator来获取测试数据
Args:
data_creator: 数据来源,可以是train()或者test()
Return:
result: 包含测试数据(image)和标签(label)的python字典
"""
data_creator = data_creator
data_image = []
data_label = []
for item in data_creator():
data_image.append... | 03023a6f90ede92da05efee12ff17601b96fb2be | 3,595,563 |
from typing import Tuple
def interpolate_pos_embeddings(
pos_embed: tf.Tensor,
src_grid_size: Tuple[int, int],
tgt_grid_size: Tuple[int, int],
nb_tokens: int = 0,
) -> tf.Tensor:
"""
This method allows to interpolate the pre-trained position encodings, to be
able to use the model on higher... | 4fd276fc80e88d14d3edf488162dbe0c172c9359 | 3,595,564 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.