content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import numpy
def create_grid(bbox,height):
"""Create a vector-based grid
Args:
bbox ([type]): [description]
height ([type]): [description]
Returns:
[type]: [description]
"""
# set xmin,ymin,xmax,and ymax of the grid
xmin, ymin = pygeos.total_bounds(bbox)[0],pygeo... | c112601a0c66f7baf863b365d57bc5bb89ad8f50 | 49,617 |
def divmod_vectorize(df):
"""
1. Use divmod to transfom HHMMSSCC to miliseconds integer with vectorize
2. Outside the njit function cast date as np.datetime and time to timedelta
3. Sum date and time
"""
@vectorize([int32(int32)])
def _fix_time(mtime):
aux, cent = divmo... | e99f2b76527ce1e2aafaebfda38fb9e11c3d0821 | 49,618 |
def fib_mem(n, computed={0:0,1:1}):
"""find fibonacci number using memoization"""
if n not in computed:
computed[n] = fib_mem(n-1, computed) + fib_mem (n-2, computed)
return computed[n] | 5d25c22ccdc5ea41fbd0faf21a8b35ac535acaef | 49,620 |
import string
def modify_fare(df, n: int = 4):
"""Introduce n new intervals (based on quantiles) for the feature fare, such that it is modified from
being continuous to being discrete
Parameters
----------
df : panda dataframe
n: number of new intervals (int)
Returns
-------
... | 1f67f0b7b55e7e61a6ee4abefb256ffadbb72345 | 49,621 |
def synthesizeChebyshevNTF(order=3, OSR=64, opt=0, H_inf=1.5, f0=0.):
"""Synthesize a noise transfer function for a delta-sigma modulator.
The NTF is a type-2 highpass Chebyshev function.
:func:`synthesizeNTF` assumes that magnitude of the denominator of the NTF
is approximately constant in the passba... | ab91df555ea2834395894b0f40a0ad6e4e8a461e | 49,622 |
import json
def get_alert_by_id(id=1):
"""Get alert data from DB given id."""
results = alert_db.read(AlertModel.id == int(id))
return Response(json.dumps(results, cls=AlchemyEncoder), mimetype='application/json') | 5fd9c430cf121fbb2c356c0c549e0e319374d635 | 49,623 |
def get_name_url_pairs(request):
"""
Return a list of (group name, group calendar URL) pairs.
Make sure that the Brothers or Pledges pair is last in the list, because
the embedded calendar is set to the URL from the last pair in the list,
and we want office positions' calendars to show up with prio... | 6d68cf288a5683afbd892627bdba7f8f02a92b36 | 49,624 |
def mean(dataframe):
"""
Compute mean of column's element in a dataframe.
"""
mean = [
compute_mean(serie)
for _, serie in dataframe.iteritems()
]
return mean | afd186d765b5fe1f13c4219916e3cb84772e1d5d | 49,625 |
def search_nearest_point(points, base_point):
"""
Parameters
-----------
points : numpy.ndarray, shape is (2, N)
base_point : numpy.ndarray, shape is (2, 1)
Returns
-------
nearest_index :
nearest_point :
"""
distance_mat = np.sqrt(np.sum((points - base_point)**2, axis=0))... | 77e76b09c62c6b8f76e059cab46dc550ceea8110 | 49,626 |
def determine_electrode_name(name, **kwargs):
"""electrode names"""
electrode_patterns = [
"(Pt|pt)[-]{0,1}[\W]ring",
"(PDX_Ch1)((_|)|dis(c|k))",
"(PDX_Ch2)((_|)|ring)",
"(PDX P[1-9]{1}K)(-|)(Ch[1-3]{1})",
"(#[1-3]{1}_|)((D|d)is(c|k)|(R|r)ing)",
"(#[1-3]{1}_|)Dis(... | e6f24e33f40abff3400909797d2a6837e92bd912 | 49,627 |
def towns_flooding_risk(stations, N):
""" Return list of towns and risk of flooding """
#find the flooding level of each town
towns_level = towns_average_level(stations)[:N]
towns_risk = []
#give a rating of each water level in town
for town, level in towns_level:
risk = "Low"
if... | f63417b1215f0121ca0427e5d36d9fd214eed8ba | 49,629 |
def adjust_learning_rate(optimizer, epoch):
"""decrease the learning rate"""
lr = args.lr
if epoch >= 100:
lr = args.lr * 0.1
if epoch >= 150:
lr = args.lr * 0.01
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr | 37734ad97fb85a71e352ce340351929fbdf00e19 | 49,630 |
def get_hash_tuple(a_dict, included_keys=None):
""" Helps in hashing a dictionary by flattening it to a flat list of its keys and values, and then converting it into a tuple (which is what the hash function expects). """
if included_keys is not None:
a_dict = {included_key:a_dict[included_key] for inclu... | b35feea54e6e4446ac1097487445027a07751910 | 49,631 |
def distance_transform(im: np.ndarray) -> np.ndarray:
"""
A function that computes the distance to the closest boundary pixel.
args:
im: np.ndarray of shape (H, W) with boolean values (dtype=np.bool)
return:
(np.ndarray) of shape (H, W). dtype=np.int32
"""
##... | 93cd39a32710ce951243c9dda1e7115aaa6cd4da | 49,632 |
def get_cfg_option(cfg, sec, opt, verbose=False):
"""
Retrieve value of a specific option of a configuration.
Parameters
----------
cfg : configparser.ConfigParser()
Configuration as retrieved by the function read_cfg_file().
sec : str
The section in which the option is located.... | 1f387c63d241f1364aa17caec76efe3b33f41b88 | 49,634 |
def send_text(openid, content):
"""组装文本回复数据"""
data = {
"touser": openid,
"msgtype": "text",
"text":
{
"content": content
}
}
return send_message(data) | c0b20bd7c9a54c038ab4fd21d7bd21bd9bb95abd | 49,635 |
import random
def run_aqrm_task(epsilon, env, learned_rm_file, tester_true, tester_learned, curriculum, show_print, is_rm_learned, currentstep, previous_testing_reward, q):
"""
This code runs one training episode.
- rm_file: It is the path towards the RM machine to solve on this episode
- envi... | a9e3acd06ee59a28bb69ebb41492eac0d67587e9 | 49,637 |
def parse_modifier(modifier):
"""Parse modifier part, return list with name, function and number."""
return [func(value) for value, func in zip(
modifier, (lambda x: x, get_action_function, int))] | 3309ea056546176e9c9b41ac6a6fef5e47dcbace | 49,638 |
def RePackFromDataPackStrings(inputs,
allowlist,
suppress_removed_key_output=False):
"""Combines all inputs into one.
Args:
inputs: a list of (resources_by_id, encoding) tuples to be combined.
allowlist: a list of resource IDs that should be k... | 7c3730e1bcb66cac61c50d7dda167035d18ff324 | 49,640 |
def toTypes(thing, types, typeError='wrong type'):
"""Convert something to any of the given types, printing an error if impossible."""
if needsLazyEvaluation(thing):
# cannot check the type now; create proxy object to check type after evaluation
return TypeChecker(thing, types, typeError)
else:
return coerceTo... | 406f79b8affb7f234b11cdf6e71c7df197a7e37a | 49,641 |
from typing import Optional
from typing import Tuple
from typing import List
def load_data(
mgf_filename: str,
*,
range_spectrum: tuple = (0, 1600), # spectrum range
min_intensity: Optional[float] = None, # determine threshold to remove
mz_binning_width: float = 5.0,
) -> Tuple[List[float], List... | a62f5dc0cb3447e52f45287b34bc45b8ad21096d | 49,642 |
import warnings
def find_plane_corner(object_name, x, y, axis, camera=None, *args, **kwargs):
"""Find the location in camera space of a plane's corner"""
if args or kwargs:
# I've added args / kwargs as a compatibility measure with future versions
warnings.warn("Unknown Parameters Passed to \"... | 34d18b37498a72882c2900a28fc923f1d2eb6356 | 49,643 |
def within_index(b, e, s, i):
"""Return a boolean value that indicates if i is within the given index.
Parameters
----------
b : Expr
beginning of the index
e : Expr
end of the index
s : Expr
strides of index
i : Expr
array position
Returns
-------
se... | e0f137c9b113f173cd0a7f2cfc5b81299ccee6bd | 49,645 |
def directed_triplet_motif_index(G):
"""Return the directed motif index of three-node graph G (G is a nx graph type)
The motif index is then computed as follows:
Each possible (undirected) edge on the nodes of G is sorted in lexicographic order.
For each pair of vertices, two bits encode, in order, the... | dba5b90617f79e38a1b1aed9cd0b3e6aca0798dd | 49,646 |
def twitter_auth():
"""OAuth procedure for the Twitter API"""
consumer_key = '8U4SH1S8MqMlxFASj6GlgeobL'
consumer_secret = 'iHGgrHBnGJJhnLfH7g2ZaggAwuun2QuNEspvg2ftUD4Ij6UnTp'
access_token = '928672057042391043-Niz2uWC8iXeXepr0NVn8GEzZ8yh5gDG'
access_token_secret = 'DSIXLThko0e0Dcem7OGsa1ht2zpR... | d1f23518258d0e2f5dfd3b4a72a24bc0aff58911 | 49,647 |
def index():
"""Index view."""
if current_user.is_authenticated:
if current_user.role == 2:
issues = Issue.query.order_by(Issue.id).all()
elif current_user.roles.role_label == 'assignee':
issues = Issue.query.order_by(Issue.id).filter((Issue.assignee == current_user.id)... | ebb42cfe3b9816ceb4b174dfa81a6de661f34a86 | 49,648 |
def get_data_parallel_rank():
"""Return my rank for the data parallel group."""
dp_group = get_data_parallel_group()
if dp_group is not None:
return get_rank(dp_group)
else:
return get_global_rank() | fe498b6f22fe37df81b5cef8e1bc7609c6ad9eaa | 49,650 |
import math
def kelvin_to_rgb(kelvin):
"""
Convert a color temperature given in kelvin to an approximate RGB value.
:param kelvin: Color temp in K
:return: Tuple of (r, g, b), equivalent color for the temperature
"""
temp = kelvin / 100.0
# Calculate Red:
if temp <= 66:
red =... | 8855f14452b63072e38498a35952ec3ee7a9ae04 | 49,651 |
def get_priors(source, version):
"""Retrieves prior pdfs for each parameter
"""
params = get_parameter(source=source, version=version, parameter='param_keys')
pdfs = {}
for param in params:
default = source_defaults['priors'][source].get(param, flat_prior)
v_definition = version_defi... | de43665767084cef8067cee116c033d61aeab2c8 | 49,652 |
def get_package_relative(file, package_dir):
"""
Get path of file relative to package directory.
If the file is not in the package directory, an error is raised.
Args:
file (File): The file.
package_dir (string): The package directory, for instance gotten from `get_package_dirname`.
Returns:
st... | 4363f161140fc7a99a2a1f8adcff5b0476a34bd3 | 49,653 |
def prepare_study_with_trials(
no_trials: bool = False,
less_than_two: bool = False,
more_than_three: bool = False,
with_c_d: bool = True,
n_objectives: int = 1,
direction: str = "minimize",
) -> Study:
"""Prepare a study for tests.
Args:
no_trials: If :obj:`False`, create a st... | 7f57a4fbc5854062c2504bed791f3a1eb0a57edc | 49,654 |
from typing import Callable
def get_from_algorithm_wrapper_registry(algorithm_name: str) -> Callable:
"""
Gets a wrapper function from algorithm wrapper registry.
:param algorithm_name: Algorithm for which the wrapper should be returned.
:return: The previously registered wrapper function.
"""
... | 8338b5540f0e6cb054354bf79f02b8789ebc2f42 | 49,655 |
import multiprocessing
def run_simulator(fitparams):
"""
runs the function simulator with the multiprocessing manager (if function is called sequentially, this stores memory, otherwise same as calling sumulator directly)
fitparams: list, for description see function simulator
retu... | 278af74d8c668d4705247bfff9f58f8368f84954 | 49,657 |
def nthRuler(n, dow):
""" Returns the n-th hour ruler since last sunrise
by day of week. Both arguments are zero based.
"""
index = (dow * 24 + n) % 7
return ROUND_LIST[index] | fbd0fbfa83009d33d7172ec699cec17b8dc79510 | 49,658 |
def load_vowel(file, sr=None, normalize=True):
"""Use librosa to to load a single vowel with a specified sample rate
"""
data, rate = librosa.load(file, sr=sr)
if normalize:
data = normalize_vowel(data)
return data | e434d35ce86834ea58aebfa0b3ccdfa9ac869206 | 49,659 |
import click
def make_pass_instance_decorator(obj, ensure=False):
"""Given an object type this creates a decorator that will work
similar to :func:`pass_obj` but instead of passing the object of the
current context, it will inject the passed object instance.
This generates a decorator that works roug... | 9319b7f450961eae2e56c3c39ed8971761828cf3 | 49,660 |
def clip_channel(coord: float, bounds: Bounds) -> float:
"""Clipping channel."""
a = bounds.lower # type: Optional[float]
b = bounds.upper # type: Optional[float]
is_bound = isinstance(bounds, GamutBound)
# These parameters are unbounded
if not is_bound: # pragma: no cover
# Will no... | ccf8c309d53d4a1ae2c752d682c36e1340c32ff6 | 49,662 |
def members_to_rep(otus):
"""Provides a lookup for a cluster member to its rep"""
res = {}
for rep, members in otus.iteritems():
for member in members:
res[member] = rep
return res | fa2a1e951a40a2872572883cf814260da8093e3a | 49,663 |
from typing import Mapping
def load_content(path: str, class_indices: Mapping[str, int]):
"""
Load .content files.
.content files (like used in cora) contain node features on separate lines. Each
line is of the form
```
node_id feature_0 feature_1 ... class_label
```
where values are ... | 2a88df9f0dfe6169f643c27ce6ea1367adfd0230 | 49,664 |
def num_2_byte_list(num):
"""
convert num to byte list
:param num:
:return:
"""
byte = []
while num > 0:
b = num & 0xff # 获取最低位的一个字节的值
byte.append(b)
num = num >> 8 # 移除最低位的一个字节
return list(reversed(byte)) | bdd80bb1a42c07f0cddc9b6a27c88204df58d7a8 | 49,665 |
def fixoutaff(outpath='',newaff='1'):
""" quick way to create test data sets - set all aff to 1 or 2 for
some hapmap data and then merge
[rerla@beast galaxy]$ head tool-data/rg/library/pbed/affyHM_CEU.fam
1341 14 0 0 2 1
1341 2 13 14 2 1
1341 13 0 0 1 1
1340 9 0 0 1 1
1340 10 0 0 2 1
... | beddabec122f7927669f324062ea8251cc6823f1 | 49,666 |
def update_accel_time(driver, at):
"""
Updates the accel time of the driver
:param driver: driver
:param at: new accel time
:type driver: DriverProfile
:return: updated driver profile
"""
return driver.update_accel_time(at) | 897c4d7ed30dc82c85481064653dea679755dc68 | 49,667 |
def _simplify(shp, tol=0.05):
"""
Generate a simplified shape, within a specified tolerance.
"""
simp = None
for thresh in [0.001, 0.0005, 0.0004, 0.0003, 0.0002, 0.0001]:
simp = shp.simplify(thresh)
if shp.difference(simp).area / shp.area < tol:
break
return simp | bf4ba42ce612477aa9606d7c710a242fbcf9dd61 | 49,668 |
import re
def _match(pattern, value):
"""User-defined function to implement SQL MATCH/STIX MATCHES"""
return bool(re.match(pattern, value)) | e644a5bf45cf298dec3c94b0782ab6fe606b8fdf | 49,670 |
from datetime import datetime
def parse_date(s):
"""
Convert date string into datetime timestamp.
Parameters
----------
s : str
Date string.
Returns
-------
data : datetime
Timestamp.
"""
return datetime.datetime.strptime(s, '%Y%m%d') | 3b36230018c95193798f6af4d298ce5940f556d2 | 49,673 |
import pkg_resources
def create_app():
"""Create and configure an instance of the Flask application."""
app = Flask(__name__)
app.managers = {}
# https://stackoverflow.com/a/32965521/8903959
version = pkg_resources.get_distribution('lib_ddos_simulator').version
template = {
"swagger": "... | d0d4c23e34a799d0bf2353dea0b0a3494442bc7a | 49,674 |
import platform
import logging
def get_chromedriver(executable_path=None, cookies=None, proxy=None, user_agent=None,
headless=False, images=False, fast_load=False):
"""Returns a Chrome WebDriver using proxies and user-agent if specified.
"""
drive = None
chrome_options = webdr... | 3df29131e4590c787373ed20171e5a8c7b58553b | 49,675 |
import random
import json
import traceback
def getRecommendArticle(request):
"""输入文章id,返回一个list,包括推荐的id
可以假设arxivID=“”时,利用用户浏览记录推荐,非空时按输入推荐。
用户浏览记录可以用session/cookie储存,建议session,读教程。
Args:
request (GET): arxivID:String,article的ID
Returns:
list,[(arxiv_id,title,author,category)... | 060de0d8fdce3151507596c0d1fba41f96b11644 | 49,676 |
from typing import Callable
def check_callback(callback):
"""
Check if callback is a callable or a list of callables.
"""
if callback is not None:
if isinstance(callback, Callable):
return [callback]
elif (isinstance(callback, list) and
all([isinstance(c, Cal... | 1e0be3680c934a79777dbe99a47ecc406df19d2a | 49,678 |
import re
def compress_json(json):
"""Compresses json output by removing quotes from keys. This makes the
return value invalid json (all json keys must be double-quoted), but
the result is still valid javascript."""
return re.sub(r'"(\w+)":', r'\1:', json) | 63aa497580ef4fe3d6d8d6c830652a7369f65723 | 49,679 |
def get_magmom_mae(poscar, mag_init):
"""
mae
"""
mae_magmom = []
sites_dict = poscar.as_dict()['structure']['sites']
# initialize a magnetic moment on the transition metal
# in vector form on the x-direction
for n, s in enumerate(sites_dict):
if Element(s['label']).is_transit... | ac863e57f8b6c337b401f3305bda70c5db306ad7 | 49,680 |
import builtins
def is_bytes(value):
"""Indicate if object is bytes-like.
future.utils.isbytes is deprecated, so re-implementing, as per their
recommendation.
"""
return isinstance(value, builtins.bytes) | baec6eca7b2ddf6bf95b1a93cae5821fe4cc3d19 | 49,681 |
def parse_ref_input(ref_input):
"""
The reference paths, it support multiple paths, use '|' as the separator between all paths, the format is
'tgt_input_1|tgt_input_2|tgt_input_3'. Each tgt_input is 'key1?=value1,key2?=value2,key3?=value3'.
1. 'path?=path1,name?=name1,audio?=audio_path... | 8ee8f556d82786f1b1fc05c24e077ac2c30a4085 | 49,682 |
def GlorotNormalInitializer(out_dim=0, in_dim=1, scale=onp.sqrt(2)):
"""An initializer function for random Glorot-scaled coefficients."""
def Init(shape, rng):
fan_in, fan_out = shape[in_dim], shape[out_dim]
size = onp.prod(onp.delete(shape, [in_dim, out_dim]))
std = scale / backend.numpy.sqrt((fan_in +... | 3666cc83baf55f12c8cdb13dcf4d643e8f8170ae | 49,684 |
from typing import Any
import json
def dumps(obj: Any) -> str:
"""Generate JSON from a Python object."""
return json.dumps(obj, cls=CanonicalEncoder) | c53e3965b45982b93f93f6f2cfaa3bf747fe6482 | 49,685 |
def get_postal_code_by_coords(latitude, longitude):
"""
Finds the nearest postal code to the provided coordinates.
:param latitude:
:param longitude:
:return:
"""
retn = None
result_count = 0
radius = 1
while result_count == 0:
postal_codes = postal_codes_within_radius(l... | e5279457d3cb2e2f886e44f1a7b52d928daaccd3 | 49,686 |
def GetNumResColumnName(doc:NexDoc, col) -> str:
"""Returns the name of the specified column of the Numerical Results Window."""
return NexRun("GetNumResColumnName", locals()) | 999ab27daa4fa6cc65d8065de0a9a5b9f35270ea | 49,687 |
def calc_error(center_value, mc_values, ci=0.683):
"""
Calculate the uncertainties/errors.
"""
data = np.concatenate([[center_value], mc_values])
median, q_lower, q_upper = np.percentile(data, q=(50, 50-50*ci, 50+50*ci))
mean = np.mean(data)
std = np.std(data)
return {
"mean": ... | a1512cf4e6ad15c17c45c0fc5a1eba27113f7033 | 49,688 |
def get_prob_distribution (df_class, save_full_path=None, label_name=None, cols=None, plot=True):
"""
This function generates and plot the probability distributions for a given dataframe containing the probabilities
for each label in the classification problem.
:param df_class (pd.dataframe or string):... | 11ddc762784d0d74fbe278b3e0a195d3fd2a522f | 49,690 |
def plot_shape(shape, params, row=0, display_values=False):
"""
Plot shape features in a bidimensional plot.
Parameters
----------
shape: 1D array, pd.Series or pd.DataFrame
Shape features computed with shape_features function.
params: pd.DataFrame
Pandas datafr... | fa9d926206f04d967785ca5c344e24bbe4c9127a | 49,691 |
def dletseq(tree, *, args, syntax, expander, **kw):
"""[syntax, decorator] Decorator version of letseq, for 'letseq over def'.
Expands to nested function definitions, each with one ``dlet`` decorator.
Example::
@dletseq[x << 1,
x << x + 1,
x << x + 2]
def... | 9579c4b2be8e6019d7c90bab5c35b7064f6be0a4 | 49,695 |
def read_phases(paths, index, fractions=None, beta=None):
"""Read the relevant data from a list of exapnded ensemble
simulations with the same reference point.
Args:
paths: A list of directories containing the data to read.
index: The reference subensemble index.
fractions: The refe... | b0b07a889dcacc443e54206c4ae87391e5959586 | 49,697 |
def fasta_name_seq(s):
"""
Interprets a string as a FASTA record. Does not make any
assumptions about wrapping of the sequence string.
"""
DELIMITER = ">"
try:
lines = s.splitlines()
assert len(lines) > 1
assert lines[0][0] == DELIMITE... | e450455710a945df25ad2cf4cc3c7f9ad662e7d3 | 49,698 |
def convert_pem_to_openssh(pem_key):
"""
Converts a given public key from PEM to OpenSSH format.
:param pem_key: PEM-encoded key bytes
:type pem_key: bytearray
:return: OpenSSH-encoded key bytes
:rtype: bytearray
"""
loaded_key = crypto_serialization.load_pem_public_key(pem_key, backend... | 1c7210220893c71906a3efaa7c4fcf76a0c71749 | 49,699 |
def diff_kerning(font_before, font_after, thresh=2, scale_upms=True):
"""Find kerning differences between two fonts.
Class kerns are flattened and then tested for differences.
Rows are matched by the left and right glyph keys.
Some fonts use a kern table instead of gpos kerns, test these
if no gp... | 156b60e132da47e5f25dda68bdd8cb969adaba34 | 49,700 |
def str_tspec(tspec, arg_names):
""" Turn a single tspec into human readable form"""
# an all "False" will convert to an empty string unless we do the following
# where we create an all False tuple of the appropriate length
if tspec==tuple([False]*len(arg_names)):
return "(nothing)"
return "... | eaba40d79561d8f8cdb2c0a3a29dffd62f256217 | 49,701 |
def get_option(prompt: str, options: list[str] = MENU_OPTIONS) -> int:
"""Gets an option from the user and ensures it's valid."""
while True:
option: int = int(input(prompt))
if option > 0 and option <= len(options):
return option
else:
raise ValueError('Not a val... | 211041c437330eab3f50b3bfcb4cfd4881fcd81a | 49,702 |
from datetime import datetime
def form_DateDifferentEmpty(request):
"""
A simple date field but with the ``empty`` attribute value set to todays date
"""
schema = schemaish.Structure()
schema.add('myDateField', schemaish.Date())
form = formish.Form(schema, 'form')
form['myDateField'].widge... | 145e6f48b3a490edc21e39f0ce9fd473957f1f03 | 49,703 |
def render_toolbar(context, config):
"""Render the toolbar for the given config."""
quill_config = getattr(quill_app, config)
t = template.loader.get_template(quill_config['toolbar_template'])
return t.render(context) | 50bce69f078b7a787b009383d055cb638af3c5c9 | 49,704 |
def get_commit_timestamps(commits):
"""Get all commit timestamps for the given ebuild.
Args:
commits (list[Commit]): The commits in question.
Returns:
list[int]: The uprev commit unix timestamps, in order.
"""
return [int(commit.timestamp) for commit in commits] | 72694219664d0d6cf83d793e9ccce2b0642ec89f | 49,705 |
def mask_tokens_after_eos(input_ids, input_masks,
eos_token_id=VatexDataset.EOS, pad_token_id=VatexDataset.PAD):
"""replace values after `[EOS]` with `[PAD]`,
used to compute memory for next sentence generation"""
for row_idx in range(len(input_ids)):
# possibly more than o... | 589b13c266836ca2641f2d796ace1dd8ba001212 | 49,706 |
def xywh_to_xyxy(xywh):
"""Convert [x1 y1 w h] box format to [x1 y1 x2 y2] format."""
if isinstance(xywh, (list, tuple)):
# Single box given as a list of coordinates
assert len(xywh) == 4
x1, y1 = xywh[0], xywh[1]
x2 = x1 + np.maximum(0.0, xywh[2] - 1.0)
y2 = y1 + np.maxi... | 2d6469d309c92354f33cd196be2d24967bf9d966 | 49,707 |
from pathlib import Path
from typing import List
import ast
import re
def get_entry_point(filename: Path, prefix: str, import_path: str) -> List[str]:
"""Returns the entry point string for a given path.
This looks for LIBTBX_SET_DISPATCHER_NAME, and a root function
named 'run'. It can return multiple res... | 02031fe25f58f8aed009c407349cfbfb7002c63f | 49,708 |
def DataUsed_TypeInfo():
"""DataUsed_TypeInfo() -> RTTI"""
return _DataModel.DataUsed_TypeInfo() | b8468185277d98d5190b1d0b697f3471d69764af | 49,709 |
def get_min(filename):
"""
Isolate the minimum search size from a file name.
Example
input: github_notebooks_200..203_p3.json
output: 200
"""
return int(filename.split("_")[2].split("..")[0]) | defc634a9b41ec2c6a4c821014e3c34119c3ea24 | 49,710 |
def scatter_complex(series: pd.Series) -> str:
"""Scatter plot (or hexbin plot) from a series of complex values
Examples:
>>> complex_series = pd.Series([complex(1, 3), complex(3, 1)])
>>> scatter_complex(complex_series)
Args:
series: the Series
Returns:
A string conta... | 75026a609fe1656a80a95115a5caa491ded1fcca | 49,711 |
from typing import Mapping
def get_operations(managed_portfolio: portfolio.Portfolio
) -> Mapping[Text, operation.Operation]:
"""Gets all the position of all assets in the portfolio.
Args:
managed_portfolio: Portfolio from which to obtain operations.
Returns:
Map of portfolio operat... | 28c5fa37482b70aa51ba571f4cbf27286181a7fe | 49,712 |
def commonprefix(m):
"""Given a list of pathnames, returns the longest common leading component without trailing /"""
if not m:
return ""
m = [p.rstrip("/").split("/") for p in m]
s1 = min(m)
s2 = max(m)
s = s1
for i, (c1, c2) in enumerate(zip(s1, s2)):
if c1 != c2:
... | 4d0bb25fd1eb1dbcd4ee28f67b61574751b6e091 | 49,713 |
def edgecolor_by_source(G, node_colors):
""" Returns a list of colors to set as edge colors based on the source node for each edge.
Parameters
----------
G : graph.
A networkx graph.
node_colors : list
List of node colors.
Example
--------
>>> colormap = {'male':... | 961205e100cf208f5471c08afdd8b3c7328713c0 | 49,714 |
def get_random_colors(n, name="hsv", hex_format=True):
"""Returns a function that maps each index in 0, 1, ..., n-1 to a distinct
RGB color; the keyword argument name must be a standard mpl colormap name."""
cmap = plt.cm.get_cmap(name, n)
result = []
for i in range(n):
color = cmap(i)
... | c077e0e143c539766907c961b3246a9fc9ae6ab0 | 49,715 |
def fdwDdz(k,t,a):
"""Function for calculating :math:`\\frac{dt}{dz}` in order to calculate the electric field in x and y direction.
"""
return fdwDdt(k,t)*fdtDdz(a) | eac9405be9e9cf2a44076479b4e1be129b9e39c0 | 49,716 |
import json
import base64
def _load_credentials_file(credentials_file):
"""Load credentials from the given file handle.
The file is expected to be in this format:
{
"file_version": 2,
"credentials": {
"key": "base64 encoded json representation of credentials."... | e01c47db0d1849a70d9623a9a5c4c33c40584d42 | 49,717 |
def __CallStoredProcedure(self, sProcedureName, pArguments):
"""Calls the given SQL stored procedure"""
pRows = None
error_string = ""
locked_state = False
try:
# Acquire the database lock
self.database_lock.Acquire(10)
locked_state = True
# Acquire the cursor and in... | da2cdf71254b38c687b1c3cb0a1771e85ec44341 | 49,718 |
from telegram import Message
from telegram import Update
def effective_message_type(entity):
"""
Extracts the type of message as a string identifier from a :class:`telegram.Message` or a
:class:`telegram.Update`.
Args:
entity (:obj:`Update` | :obj:`Message`) The ``update`` or ``message`` to e... | 5ed152cc88900d1d6167b9cf28637f29099189fc | 49,719 |
from datetime import datetime
def create_post(i):
"""
Helper to create one remote post.
:param i:
:return:
"""
i = i.get('posts')[0]
post = Post()
post.id = i.get('id')
post.author = create_author(i.get('author'))
post.contentType = i.get('contentType')
post.description = ... | c0ff9d105ad7a4ebc78c2c10a29eca7cfd2fcedb | 49,720 |
import pathlib
def get_valid_executable_path_or_empty_path(arg_string: str) -> pathlib.Path:
"""
>>> if lib_detect_testenv.is_doctest_active(): assert get_valid_executable_path_or_empty_path(__main__.__file__) == empty_path
>>> assert get_valid_executable_path_or_empty_path(__file__) == pathlib.Path(__fil... | 9134817cf8e191855f416208bfe329e2a0b66201 | 49,722 |
def _ignore_filter(referrers, ignore, extraids, getid=id):
""" Ignore objects on the referrers list if ignore(x) is true or if x is in extra """
r = []
for ref in referrers:
if ignore is not None:
extraids.update(set([getid(o) for o in ignore(ref)]))
if getid(ref) in extraids: c... | e13a28ba1610de9d6bc835a03cf02a0f6752f7b2 | 49,723 |
def request_fake():
"""Create request with fake i18n subscribers on."""
config = testing.setUp()
config.scan("pyramid_localize.subscribers.fake")
request = Request({})
request.registry = config.registry
return request | 6f6cd5e6388b6ab5d495fabd2d7da0e13f91a4be | 49,724 |
def read_settings(key=None):
"""
Read application settings.
Parameters
----------
key : str, optional
Setting key to read, by default `None`.
Returns
-------
str | dict
If `key` is given, the corresponding value. If key is `None`, return all settings in
a dictio... | c99b13864889f8af9a3f71ab4213f45693236858 | 49,725 |
def navigable_thresh(img, rgb_thresh=(160, 160, 160)):
"""Identify the image pixels that are above the provided threshold. Each
threshold value can range between 0 and 255, with 160 doing a nice job
of identifying ground pixels only.
:param img: Numpy 3d array (x, y, RGB layers)
:param rgb_threh: 3 ... | ba5d927149c26bd96611840250c92a4e844c514f | 49,726 |
def Hbeta(D=np.array([]), sigma=1.0):
"""
Compute the P_ji matrix and the entropy for some data given a sigma value.
Params:
D - Squared difference of two vectors. Must be a numpy array.
sigma - a float
Output:
H, P - Entropy and P_ji matrix
"""
# Compute P-row and corresponding pe... | 3035d88e1db6d0cc46076dc5cdf23fc04e9cf765 | 49,727 |
def gaia_morph(gaia):
"""Retrieve morphological type for Gaia sources.
Parameters
----------
gaia: :class:`~numpy.ndarray`
Numpy structured array containing at least the columns,
`GAIA_PHOT_G_MEAN_MAG` and `GAIA_ASTROMETRIC_EXCESS_NOISE`.
Returns
-------
:class:`~numpy.arra... | 7433d0b148d37c2310d0200bfc3e5af6d2deadbe | 49,728 |
def motherfucking_rainbows(string, inputmode=False, end="\n"):
"""
I cANtT FeELLE MyYE FACECsEE ANYrrMOROeeee
"""
for character in string:
print(choice(colors) + character, end="")
print('\033[0m', end="")
if inputmode:
return input("")
return print(end, end="") | 9359889925841df59b25c964d37349fb3318caf9 | 49,729 |
from typing import Tuple
def negative_distances(
negative_mining_strategy: str,
distances: FloatTensor,
negative_mask: BoolTensor,
positive_mask: BoolTensor,
) -> Tuple[FloatTensor, FloatTensor]:
"""Negative distance computation.
Args:
negative_mining_strategy: What mining strategy to... | 64ea23280fd1fce937f9561d5873d3fab0dfc810 | 49,731 |
def get_courses(input_urls: list[str]):
"""
Return course_dict of list of courses
"""
courses = []
for input_url in input_urls:
course_data = get_course_data(input_url)
course_dict = {}
if course_data:
course_dict = get_course_dict(course_data)
courses.app... | d13534fad5e35cd24d179917fc8e8010050fc090 | 49,732 |
import requests
import json
def get_course_info(orgUnitId):
"""Returns basic info for a course offering"""
url = DOMAIN + "/lp/{}/courses/{}".format(LP_VERSION, orgUnitId)
response = requests.get(url, headers=HEADERS)
code_log(response, "GET course offering info org unit".format(orgUnitId))
return... | c7e0d465634a1457623a01c94c77f9b88de5ebb2 | 49,733 |
def process_remove_outliers_ph(df: pd.DataFrame) -> pd.DataFrame:
"""Remove waters with ph <= 1 or ph>13 and potability=1."""
df = df[
~((df["Potability"] == 1) & (df["ph"].apply(lambda x: x <= 1 or x >= 13)))
].copy()
return df | 1ba7615045f4bf2624c355fbf1ddce63f1f80f35 | 49,734 |
import numpy as np
def deserialize_numpy(serialized_np, shape):
"""
Deserializes a numpy array from a JSON-compatible string.
from https://stackoverflow.com/questions/30698004/how-can-i-serialize-a-numpy-array-while-preserving-matrix-dimensions#30699208
Parameters
----------
serialized_np : ... | b8981fc98909eb570e59c36c9c0f003e445e2358 | 49,735 |
import json
def get_field_data_from_room():
"""
1. Get required arguments
2. Call the worker method
3. Render the response
"""
# 1. Get required arguments
args = Eg003Controller.get_args()
try:
# 2. Call the worker method
results = Eg003Controller.worker(args)
exce... | 5c9c95308a3774e547fae1089118517a6d269424 | 49,736 |
def build_tuple_for_feet_structure(quantity):
"""
Builds the tuple required to create a FeetAndInches object
:param quantity: string containing the feet, inches, and fractional inches
:return: tuple containing feet, inches, and calculated fractional inches
"""
feet = float(quantity[0])
inche... | 2a66e7bf859e120d224c097a628445342a987067 | 49,737 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.