content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def parameters_create_lcdm(Omega_c, Omega_b, Omega_k, h, norm_pk, n_s, status):
"""parameters_create_lcdm(double Omega_c, double Omega_b, double Omega_k, double h, double norm_pk, double n_s, int * status) -> parameters"""
return _ccllib.parameters_create_lcdm(Omega_c, Omega_b, Omega_k, h, norm_pk, n_s, status) | d0a623fcfbcee06a387a3bf7add96068a8205824 | 23,544 |
def _split_header_params(s):
"""Split header parameters."""
result = []
while s[:1] == b';':
s = s[1:]
end = s.find(b';')
while end > 0 and s.count(b'"', 0, end) % 2:
end = s.find(b';', end + 1)
if end < 0:
end = len(s)
f = s[:end]
resu... | fabbfb0959133e70019742c6661cb3bb443ca34d | 23,545 |
def countDigits(string):
"""return number of digits in a string (Helper for countHaveTenDigits)"""
count = 0
for char in string:
if char == '0' or char == '1' or char == '2' or char == '3' or char == '4' or \
char == '5' or char == '6' or char == '7' or char == '8' or char == '9':
... | f8d2327e022efc7a117b744588dfe16a3a7ba75e | 23,546 |
def get_process_entry(process_id: int) -> Process:
"""Get process entry
:raises AssertionError: When illegal state: Active processes != 1
:param process_id: specify process
:return: Process entry
"""
active_process_entry_query = db.session.query(Process).filter(Process.id == process_id)
ass... | 442df14f1d032ff1fe8c40598f39a06255982da8 | 23,547 |
def shrink(filename):
"""
The function will make the original image shrink to its half without losing too much quality.
:param filename: The directory of an image tou want to process.
:return img: SimpleImage, a shrink image that is similar to the original image.
"""
img = SimpleImage(filename)
... | 0bff7d59bb7ae512883103bfe21ba80598c28c17 | 23,548 |
import getpass
def get_target_config():
"""
Get details of the target database (Postgres)
"""
print('\n------------------------------------------')
print('Enter target database settings:')
print('------------------------------------------')
config = {}
config['username'] = input('- U... | 36820bae4af66b2db92ce1d467996b6e9a7a2624 | 23,549 |
def GetGPU():
"""Get the global index of GPU.
Returns
-------
int
The global index of GPU.
"""
return option['device_id'] | 2c392c97da988c33ff12f59db4bb10f6b41e3bc1 | 23,550 |
def get_generic_explanation(exception_type):
"""Provides a generic explanation about a particular exception."""
if hasattr(exception_type, "__name__"):
exception_name = exception_type.__name__
else:
exception_name = exception_type
if exception_name in GENERIC:
return GENERIC[exce... | b590be31518f3eabdc1cdeb31b1c66e66b47b253 | 23,551 |
def simple_histogram(queryset, column, bins):
"""
Return a histogram from data in queryset.
:param queryset: A Queryet, Model, or Manager
:param column: The column we are aggregating into a histogram
:param bins: An ordered iterable of left endpoints of the bins. Must have at least two elements.
... | b6f4f2738cdf5e3e610e830886e2c6639aae309e | 23,553 |
def bounding_box(points):
"""Bounding box
Args:
points: Array of shape (amount_of_points, dimensions)
Returns:
numpy.ndarray: Array of [[min, max], [min, max], ...] along the
dimensions of points.
"""
out = np.empty((points.ndim, 2))
for i in range(points.ndim):
... | 44871a584f3592296c982c82a798c05ee8b166f7 | 23,555 |
def get_ts_WFI(self):
"""
Get kinetic energy density
"""
ts = np.zeros((self.grid.Nelem, len(self.solver[0,:]) ))
if self.optInv.ens_spin_sym is not True:
for i in range(self.solver.shape[0]):
for j in range(self.solver.shape[1]):
self.solver[i,j].calc_ked_WFI... | 8384a5c3d1e2cdb5551ecb783101961f73a2d523 | 23,556 |
def _correct_outlier_correlation(rpeaks: pd.DataFrame, bool_mask: np.array, corr_thres: float, **kwargs) -> np.array:
"""Apply outlier correction method 'correlation'.
This function compute the cross-correlation coefficient between every single beat and the average of all detected
beats. It marks beats as ... | 7216b1c8e2c3352d14273aa058e5c9fd4398044b | 23,557 |
import time
def _time_from_timestamp(timestamp: int) -> time:
"""
Casts a timestamp representing the number of seconds from the midnigh to a time object
Parameters
----------
timestamp : int
The number of seconds since midnight
Returns
-------
time
The associated time... | 552f2b3b6841d48f3340ecdd94edb03f791a84c9 | 23,558 |
def get_marginal_frequencies_of_spikes_in_bins(symbol_counts, number_of_bins_d):
"""
Compute for each past bin 1...d the sum of spikes found in that bin across all
observed symbols.
"""
return np.array(sum((emb.symbol_binary_to_array(symbol, number_of_bins_d)
* symbol_counts... | c1ace43f040715c87a3a137bebf64d862060a590 | 23,559 |
def pagination(cl):
"""
Generate the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EA... | cca1b80f1bc2c60c8f4af44f138b5433023298f7 | 23,561 |
def ants_apply_inverse_warps_template_to_func(
workflow, strat, num_strat, num_ants_cores, input_node, input_outfile,
ref_node, ref_outfile, func_name, interp, input_image_type
):
"""Apply the functional-to-structural and structural-to-template warps
inversely to functional time-series in templa... | e1fdd24a9e3b13ff280baf89586eeca85f1f0a7d | 23,562 |
def get_metrics_influx(query, query_index):
""" Function to Query InfluxDB """
influx_connect = InfluxDBClient(
host=defs.INFLUX_DETAILS[query_index][0],
database=defs.INFLUX_DETAILS[query_index][1],
port=8086,
timeout=5,
retries=5)
response = influx_connect.query(que... | 3f5d7c147553d3b16cfb3d18a1b86805f879fda7 | 23,563 |
def find_buckets(pc, target_centres, N, bucket_height=.38, bucket_radius=.15):
"""
Returns: pc, bucket_centres
"""
### find buckets and remove ###
print ('finding buckets')
buckets = pc[pc.z.between(.1, .4)]
# voxelise to speed-up dbscan
buckets.loc[:, 'xx'] = (buckets.x // .0... | e7e5480783235e6e9ad48cbfc4d006e9a0a7b61e | 23,564 |
def red_bg(text):
"""
Red background.
"""
return _create_color_func(text, bgcolor=1) | c867f7415230b6f5c179a4369bf4751f9ee2a442 | 23,567 |
def does_block_type_support_children(block_type):
"""
Does the specified block type (e.g. "html", "vertical") support child
blocks?
"""
try:
return XBlock.load_class(block_type).has_children
except PluginMissingError:
# We don't know if this now-uninstalled block type had childre... | f1e86e6b378ef3e134106653e012c8a06cebf821 | 23,568 |
def jsonDateTimeHandler(obj):
"""Takes an object and tries to serialize it in JSON
by using strftime or isoformat."""
if hasattr(obj, "strftime"):
# To avoid problems with the js date-time format
return obj.strftime("%a %b %d, %Y %I:%M %p")
elif hasattr(obj, 'isoformat'):
return ... | 605f8a379575d185bc2a8b16810252511eec52af | 23,569 |
def get_crypto_price(crypto, fiat):
"""Helper function to convert any cryptocurrency to fiat"""
converted_btc_value = float(binance_convert_crypto(
crypto, "BTC").split('=')[1].strip().split()[0])
# grab latest bitcoin price
btc_price = float(get_price("btc", fiat).split('=')[1].strip().split()... | f91e56c74b3422d3ab272c029352ae94521033b0 | 23,571 |
def boxblur(stream: Stream, *args, **kwargs) -> FilterableStream:
"""https://ffmpeg.org/ffmpeg-filters.html#boxblur"""
return filter(stream, boxblur.__name__, *args, **kwargs) | 5f29981abaf050b43207452649f4ad9e3fafc05c | 23,572 |
def flatten(lis):
"""Given a list, possibly nested to any level, return it flattened."""
new_lis = []
for item in lis:
if type(item) == type([]):
new_lis.extend(flatten(item))
else:
new_lis.append(item)
return new_lis | 7e4e00af9f20f58dc0798a0731c352949dd71cf5 | 23,574 |
def name(ndims=2, ndepth=2):
""" encrypt n and version into a standardized string """
# Model name, depth and version
value = 'care_denoise_%dDdepth%d' % (ndims, ndepth)
return value | 1933ac0454eac4c860d70683e58c922074498b63 | 23,575 |
import string
import random
def _generate_url_slug(size=10, chars=string.ascii_lowercase + string.digits):
"""
This is for a Django project and it assumes your instance
has a model with a slug field and a title character (char) field.
Parameters
----------
size: <Int>
Size of the slug... | 1ebe945730e7e5f977c80666db92cfefb9a1a1a7 | 23,576 |
def mc_compute_stationary(P):
"""
Computes the stationary distribution of Markov matrix P.
Parameters
----------
P : array_like(float, ndim=2)
A discrete Markov transition matrix
Returns
-------
solution : array_like(float, ndim=1)
The stationary distribution for P
... | dc971399bc7b8626347ba9a20a6c8f449870b606 | 23,577 |
def isight_prepare_data_request(a_url, a_query, a_pub_key, a_prv_key):
"""
:param a_url:
:type a_url:
:param a_query:
:type a_query:
:param a_pub_key:
:type a_pub_key:
:param a_prv_key:
:type a_prv_key:
:return:
:rtype:
"""
header = set_header(a_prv_key, a_pub_key, a_... | 8854013b509fa52a35bd1957f6680ce4e4c17dc4 | 23,578 |
def norm_fisher_vector(v, method=['power', 'l2']):
"""
Normalize a set of fisher vectors.
:param v: numpy.array
A matrix with Fisher vectors as rows (each row corresponding to an
image).
:param method: list
A list of normalization methods. Choices: 'power', 'l2'.
:return: n... | 06592b42914902f183d085f584b00cd9a1f057ce | 23,579 |
def get_top_funnels_df(funurl: str, funlen: int, useResolvedUrls: bool, events: DataFrame, limit_rows: int = 0) -> dict:
"""Get top funnels of specified length which contain the specified URL
:param funurl: URL that should be contained in the funnel
:param funlen: funnel length
:param useResolvedUrls: ... | 1fe29668e98076bbb39023e04fc1a5845788d9ef | 23,580 |
from typing import Dict
from typing import Any
def graph_to_json(obj: Graph) -> Dict[str, Any]:
"""
Uses regular serialization but excludes "operator" field to rid of circular references
"""
serialized_obj = {
k: v
for k, v in any_to_json(obj).items()
if k != 'operator' # to p... | 922d53d5fb9b23773cdea13e94930985785f6c77 | 23,582 |
def log_ttest_vs_basal(df, basal_key):
"""Do t-tests in log space to see if sequences has the same activity as basal.
Parameters
----------
df : pd.DataFrame
Index is sequence ID, columns are average RNA/DNA barcode counts for each replicate.
basal_key : str
Index value for basal.
... | b41029c7c61b3b365bf71e2aaba8a81aecf5533a | 23,583 |
def spleen_lymph_cite_seq(
save_path: str = "data/",
protein_join: str = "inner",
remove_outliers: bool = True,
run_setup_anndata: bool = True,
) -> anndata.AnnData:
"""
Immune cells from the murine spleen and lymph nodes [GayosoSteier21]_.
This dataset was used throughout the totalVI manus... | 7eeead5e6f69b7f3b9dff85b33cae675ea0a47ec | 23,584 |
def strftime_local(aware_time, fmt="%Y-%m-%d %H:%M:%S"):
"""
格式化aware_time为本地时间
"""
if not aware_time:
# 当时间字段允许为NULL时,直接返回None
return None
if timezone.is_aware(aware_time):
# translate to time in local timezone
aware_time = timezone.localtime(aware_time)
return a... | 1294795d793c22e7639fb88ca02e34bb6b764892 | 23,586 |
import re
def filter_issues_fixed_by_prs(issues, prs, show_related_prs, show_related_issues):
"""
Find related issues to prs and prs to issues that are fixed.
This adds extra information to the issues and prs listings.
"""
words = [
'close', 'closes', 'fix', 'fixes', 'fixed', 'resolve', '... | 6e63dc9988c9343b4f9d2baae2d995b26b666ed3 | 23,587 |
import re
def run_job(answer: str, job: dict, grade: float, feedback: str):
"""
Match answer to regex inside job dictionary.
Add weight to grade if successful, else add comment to feedback.
:param answer: Answer.
:param job: Dictionary with regex, weight, and comment.
:param grade: Current gr... | 487916da129b8958f8427b11f0118135268f9245 | 23,588 |
def __build_data__(feature, qars):
"""
Return all the data needed to build the Benin republic departments Layer
"""
data = {
'qars': qars,
}
# GEOJSON layer consisting of a single feature
department_name = feature["properties"]["NAME_1"]
data["department"] = department_name
... | e1982a1f610ea724ca8cf06f6641a4bc3428fa47 | 23,589 |
def hook(callback):
"""
Installs a global listener on all available mouses, invoking `callback`
each time it is moved, a key status changes or the wheel is spun. A mouse
event is passed as argument, with type either `mouse.ButtonEvent`,
`mouse.WheelEvent` or `mouse.MoveEvent`.
Returns the g... | 4bf0884de591fc4f0b30bee42b6e36b06c526134 | 23,590 |
def notification_list(request):
"""
returns the notification list
"""
notifications = Notification.get_notifications(user=request.user)
return {"notifications": notifications} | c8e967fa8cef0dfd5cc9673c99289e17813f2e75 | 23,591 |
def predictClass(x, mus, sigmas, X_train, number_of_classes, class_probabilities):
"""
For every model, it calculates the likelihood for each class, and picks the class with max likelihood.
:param x: The datapoint we want to derive the class for.
:param mus: A list with the mean vector for each method.... | dbd9d6227c8877862d74d4bf1932f3f1acd37a2f | 23,593 |
def create_secret_id(vault, name, version=None):
"""
:param vault: The vault uri.
:type vault: str
:param name: The secret name.
:type name: str
:param version: The secret version.
:type version: str
:rtype: KeyVaultId
"""
return create_object_id('secrets', vault, name, version) | 65c918a8f9c1f5c087835ff36a9eb13233bada2d | 23,594 |
def config_output_page():
"""
Configuration landing page
:return: config.html
"""
config_type = "output"
c = ConfigFile()
# First load in all the configuration from the provided configuration file, if it exists
c.load_from_file(DEFAULT_CONFIG_FILE)
cdb = c.get_cdb()
cdb.update_... | 346ae058db6e0081a37a5ebedd6d231f0a3204da | 23,595 |
from typing import Optional
def compute_all_aggregator_metrics(
per_plan_confidences: np.ndarray,
predictions: np.ndarray,
ground_truth: np.ndarray,
metric_name: Optional[str] = None
):
"""Batch size B, we assume consistent number of predictions D per scene.
per_plan_confidences: np.ndarray, ... | cd17c4c1273ec2a23aa16efebd7a4437dc4e16f7 | 23,596 |
import requests
import re
def query_url_base(_url, _proxy=True, _isPC=True, _isPhone=False):
""" 基于requset的模块,不能采集动态网页数据
:param _url<str>
:param _proxy<bool>
:param _isPc<bool>
:param _isPhone<bool>
:return _result<dict>
"""
_result = {}
_headers = {'Connection':'kepp-alive'}
i... | f916b974a472f6a3d079911461902da1ae7cb18d | 23,597 |
def timefstring(dtobj, tz_name=True):
"""Standardize the format used for timestamp string format.
Include 3 letter string for timezone if set to True.
"""
if tz_name:
return f'{dtobj.strftime("%Y-%m-%d_%H:%M:%S%Z")}'
else:
return f'{dtobj.strftime("%Y-%m-%d_%H:%M:%S")}NTZ' | 5bbf0454a76ed1418cbc9c44de909940065fb51f | 23,598 |
def is_block(modules):
"""Check if is ResNet building block."""
if isinstance(modules, (ShuffleUnit, )):
return True
return False | ac6f059b763f25d81508826a3a8c8db5beb769b0 | 23,599 |
def _func(*args, **kwargs):
"""Test function used in some tests."""
return args, kwargs | 7fb2aa947806578e5378e66ce7dc1b4f3f593dbe | 23,601 |
def combine_parallel_circuits(IVprev_cols, pvconst):
"""
Combine crosstied circuits in a substring
:param IVprev_cols: lists of IV curves of crosstied and series circuits
:return:
"""
# combine crosstied circuits
Irows, Vrows = [], []
Isc_rows, Imax_rows = [], []
for IVcols in zip(*... | 31d6a96189b703bca0e9cf212472cb0c8870d3cd | 23,602 |
def _create_pipeline(pipeline_name: str, pipeline_root: str, data_root: str,
module_file: str, serving_model_dir: str,
metadata_path: str) -> tfx.dsl.Pipeline:
"""Creates a three component penguin pipeline with TFX."""
# Brings data into the pipeline.
example_gen = tfx.co... | 6254505a2d0309a8576a277b95a521294f9f8901 | 23,603 |
def create_global_step() -> tf.Variable:
"""Creates a `tf.Variable` suitable for use as a global step counter.
Creating and managing a global step variable may be necessary for
`AbstractTrainer` subclasses that perform multiple parameter updates per
`Controller` "step", or use different optimizers on different... | d1fc499b60d09d50e555977b73eec04971e11b3b | 23,604 |
def supported_coins_balance(balance, tickers):
"""
Return the balance with non-supported coins removed
"""
supported_coins_balance = {}
for coin in balance.keys():
if coin != "BTC":
if f"{coin}/BTC" in tickers:
supported_coins_balance[coin] = balance[coin]
... | aaea856c728d04f47f52c1b07c66be57ff17d8cf | 23,605 |
def _identity_map(size):
"""Function returning list of lambdas mapping vector to itself."""
return [lambda x, id: x[id] for _ in range(size)] | 6236d42d359fdc9b006bffcc597fccbc161eb53d | 23,606 |
def With(prop, val):
"""The 'with <property> <value>' specifier.
Specifies the given property, with no dependencies.
"""
return Specifier(prop, val) | fc4a167322ab5bde74eabf1b69efb5d37f643405 | 23,607 |
def pad_node_id(node_id: np.uint64) -> str:
""" Pad node id to 20 digits
:param node_id: int
:return: str
"""
return "%.20d" % node_id | 28cdaad2aa327143432c5be58598271139574a50 | 23,608 |
def ballcurve(x: ArrayLike, xi: float) -> ArrayLike:
"""
function to generate the curve for the nested structure, given a shape
parameter xi. If xi= 1 is linear.
input:
----------
x: 1D array, [0,1]
initial values to be evaluated on the function
xi: number, >=1
shape paramete... | 6b261793e1bdccc39bc66f25f4013d07d3bfc376 | 23,609 |
def center_vertices(vertices, faces, flip_y=True):
"""
Centroid-align vertices.
Args:
vertices (V x 3): Vertices.
faces (F x 3): Faces.
flip_y (bool): If True, flips y verts to keep with image coordinates convention.
Returns:
vertices, faces
"""
vertices = verti... | 85743c3b3e3838533e78c66b137cc9c8c7702519 | 23,610 |
def fingerprint_atompair(fpSize=2048, count=False):
"""Atom pair fingerprint (list of int).
Args:
fpSize: Size of the generated fingerprint (defaults to 2048).
count: The default value of False will generate fingerprint bits
(0 or 1) whereas a value of True will generate the count o... | cbacf8bdaae11520f2bb71ae825ea574258f6242 | 23,611 |
def bend_euler_s(**kwargs) -> Component:
"""Sbend made of euler bends."""
c = Component()
b = bend_euler(**kwargs)
b1 = c.add_ref(b)
b2 = c.add_ref(b)
b2.mirror()
b2.connect("o1", b1.ports["o2"])
c.add_port("o1", port=b1.ports["o1"])
c.add_port("o2", port=b2.ports["o2"])
return c | 55c3d4dc5cc2766463f088ede2b4f04c6018eac6 | 23,612 |
def phot_error(star_ADU,n_pix,n_b,sky_ADU,dark,read,gain=1.0):
"""
Photometric error including
INPUT:
star_ADU - stellar flux in ADU (total ADU counts within aperture)
n_pix - number of pixels in aperture
n_b - number of background pixels
sky_ADU - in ADU/pix
dark ... | 45d3f335c2b7fad1e2e0f8e8e415a0bda0f774e8 | 23,613 |
def tan(x):
"""
tan(x) -> number
Return the tangent of x; x in radians.
"""
try:
res, x = _init_check_mpfr(x)
gmp.mpfr_tan(res, x, gmp.MPFR_RNDN)
return mpfr._from_c_mpfr(res)
except TypeError:
res, x = _init_check_mpc(x)
gmp.mpc_tan(res, x, gmp.MPC_RNDNN... | 651119ccd44f313b25f49e03a3f5094fa1c1a829 | 23,614 |
def test_wrapped_func():
"""
Test uncertainty-aware functions obtained through wrapping.
"""
########################################
# Function which can automatically handle numbers with
# uncertainties:
def f_auto_unc(angle, *list_var):
return umath.cos(angle) + sum(list_var)
... | 9f432e6fd0c796c733e43c2ca66d2d0373148ee4 | 23,615 |
def T2str_mag_simplified(K, TE, T2str, N):
"""Signal Model of T2str-weighted UTE GRE Magnitude Image
S = K * [ exp(-TE/T2*) ] + N
parameters:
K :: constant (proportional to proton density)
TE :: sequence echo time
T2str :: relaxation due to spin-spin effects and dephasing
N... | ddf829cf8e209602b141f1b13c8fbf5af566a8d7 | 23,616 |
def tune(runner, kernel_options, device_options, tuning_options):
""" Find the best performing kernel configuration in the parameter space
:params runner: A runner from kernel_tuner.runners
:type runner: kernel_tuner.runner
:param kernel_options: A dictionary with all options for the kernel.
:type... | 099b5e513ab52353efbce8ba1e7465acf5b1f6bc | 23,617 |
def getTimeString(t, centi=True):
"""
category: General Utility Functions
Given a value in milliseconds, returns a Lstr with:
(hours if > 0):minutes:seconds:centiseconds.
WARNING: this Lstr value is somewhat large so don't use this to
repeatedly update node values in a timer/etc. For that p... | 12cbcf4fcfd8450af110f93c77c4c5b50285c0fd | 23,618 |
def validation_supervised(model, input_tensor, y_true, loss_fn, multiclass =False, n_classes= 1):
"""
Returns average loss for an input batch of data with a supervised model.
If running on multiclass mode, it also returns the accuracy.
"""
y_pred = model(input_tensor.float())
if multiclass:
... | 901f4416fab5ebc23115ef2f3aab1b971607368e | 23,619 |
def timing(func=None, *, name=None, is_stage=None):
"""
Decorator to measure the time taken by the function to execute
:param func: Function
:param name: Display Name of the function for which the time is being calculated
:param is_stage: Identifier for mining stage
Examples:
... | e7368e64bda81811075a295b6e36f0f9e9e7bcd5 | 23,621 |
def is_skip_file(filename):
""" Should the given file be skipped over for testing
:param filename: The file's name
:type filename: String
:return: True if the given file should be skipped, false otherwise
:rtype: Boolean
"""
filename_len = len(filename)
for skip_name in SKIP_FILES:
... | 066bcfbff6f984fb293c422f613746967713b31b | 23,622 |
def lowercase_or_notify(x):
""" Lowercases the input if it is valid, otherwise logs the error and sets a default value
Args:
String to lowercase
Returns:
Lowercased string if possible, else unmodified string or default value.
"""
try:
return x.lower()
ex... | a9e9cce9450f21f5cec80739d435e362288e8844 | 23,623 |
def is_not_null(node, eval_type, given_variables):
"""Process the is_not_null operator.
:param node: Formula node
:param eval_type: Type of evaluation
:param given_variables: Dictionary of var/values
:return: Boolean result, SQL query, or text result
"""
if eval_type == EVAL_EXP:
# ... | a261731103f81f1e4fe2c6eb191d3127acb163fe | 23,624 |
def search_for_rooms(filters, allow_admin=False, availability=None):
"""Search for a room, using the provided filters.
:param filters: The filters, provided as a dictionary
:param allow_admin: A boolean specifying whether admins have override privileges
:param availability: A boolean specifying whether... | fe29ec5b4bf27d51b45ed2ba87cb7153d176583c | 23,625 |
def get_scalar(obj):
"""obj can either be a value, or a type
Returns the Stella type for the given object"""
type_ = type(obj)
if type_ == type(int):
type_ = obj
elif type_ == PyWrapper:
type_ = obj.py
# HACK {
if type_ == type(None): # noqa
return None_
elif t... | 2b5c829a8a933ff5f80a1d17d0ba8c2a49c90643 | 23,626 |
import math
def sin(x, deg=None, **kwargs):
"""Computes the sine of x in either degrees or radians"""
x = float(x)
if deg or (trigDeg and deg is None):
x = math.radians(x)
return math.sin(x) | 5f5809fac0fd6970fa58a20b8c70e9f6a53d96d7 | 23,628 |
def bloated_nested_block(block_dets, *, repeat=False, **_kwargs):
"""
Look for long indented blocks under conditionals, inside loops etc that are
candidates for separating into functions to simplify the narrative of the
main code.
"""
bloated_outer_types = set()
included_if = False
for l... | fc25529485c9725cf0de3fe5917299b084f499a3 | 23,630 |
from typing import Any
def _to_bytes(value: Any, type_str: str = "bytes32") -> bytes:
"""Convert a value to bytes"""
if isinstance(value, bool) or not isinstance(value, (bytes, str, int)):
raise TypeError(f"Cannot convert {type(value).__name__} '{value}' to {type_str}")
value = _to_hex(value)
... | f324d915377cd281eacb25b3afbde7b83deedad1 | 23,631 |
def _map_sbs_sigs_back(df: pd.DataFrame) -> pd.Series:
"""
Map Back Single-Base Substitution Signatures.
-----------------------
Args:
* df: pandas.core.frame.DataFrame with index to be mapped
Returns:
* pandas.core.series.Series with matching indices to context96
"""
def _c... | d6a8843c80acdaf5320191af51cb40c8ce7e0d42 | 23,632 |
def rmsd(
coords1: np.ndarray,
coords2: np.ndarray,
atomicn1: np.ndarray,
atomicn2: np.ndarray,
center: bool = False,
minimize: bool = False,
atol: float = 1e-9,
) -> float:
"""
Compute RMSD
Parameters
----------
coords1: np.ndarray
Coordinate of molecule 1
c... | e5f430d3ddb330c7bf61e0674c29cba3d6fadd7f | 23,633 |
def get_bridge_interfaces(yaml):
"""Returns a list of all interfaces that are bridgedomain members"""
ret = []
if not "bridgedomains" in yaml:
return ret
for _ifname, iface in yaml["bridgedomains"].items():
if "interfaces" in iface:
ret.extend(iface["interfaces"])
retu... | dad9e634a1c5306289e73d465b08b7ea857518e4 | 23,634 |
from typing import List
import tqdm
def get_entity_matched_docs(doc_id_map: List[str], data: List[dict]):
"""Gets the documents where the document name is contained inside the claim
Args:
doc_id_map (List[str]): A list of document names
data (List[dict]): One of the FEVEROUS datasets
Ret... | dd49d58bd2a4dc4eed06e16d5673c85bf1ed8b73 | 23,636 |
import requests
def getTemplateKeys(k):
"""
Prints out templates key for license or gitignore templates from github api
Params: str
Return: code
"""
code = 0
if k.lower() == "license":
r = requests.get(GITHUB_LICENSE_API)
if r.status_code != 200:
code = 1
... | 641e6aeb599fb206214530b55faea44be7de7d37 | 23,637 |
def get_num_conv2d_layers(model, exclude_downsample=True, include_linear=True):
""" Check the number of Conv2D layers. """
num = 0
for n, m in model.named_modules():
if "downsample" in n and exclude_downsample:
continue
if is_conv2d(m) or (include_linear and isinstance(m, nn.Lin... | 79d1453f4cc49d358329a7d59fdd07bcdbb97736 | 23,638 |
def im_list_to_blob(ims, RGB, NIR, DEPTH):
"""Convert a list of images into a network input.
Assumes images are already prepared (means subtracted, BGR order, ...).
"""
max_shape = np.array([im.shape for im in ims]).max(axis=0)
num_images = len(ims)
if RGB & NIR & DEPTH:
blob = np.zeros((... | 96036933eddd742b9db4e211188c1716933d37dc | 23,639 |
async def async_setup_entry(hass, config_entry, async_add_devices):
"""Set up entry."""
miniserver = get_miniserver_from_config_entry(hass, config_entry)
loxconfig = miniserver.lox_config.json
devices = []
for switch_entity in get_all_switch_entities(loxconfig):
if switch_entity["type"] in ... | 1cd4114645b7454c371bc23a13e212e2ae9f8173 | 23,640 |
import torch
def gradU_from_momenta(x, p, y, sigma):
"""
strain F'(x) for momenta p defined at control points y
a method "convolve_gradient" is doing a similar job but only compute (gradF . z)
x (M, D)
p (N, D)
y (N, D)
return
gradU (M, D, D)
"""
kern = deformetrica.support.k... | 03dc67bf8bc6b8a576b1ed96de841003bcb53383 | 23,641 |
def process(seed, K):
"""
K is model order / number of zeros
"""
print(K, end=" ")
# create the dirac locations with many, many points
rng = np.random.RandomState(seed)
tk = np.sort(rng.rand(K)*period)
# true zeros
uk = np.exp(-1j*2*np.pi*tk/period)
coef_poly = poly.polyfromro... | 544d5116cf5ef3a2bff08253ee697d4a04994a2e | 23,642 |
def _gen_sieve_array(M, factor_base):
"""Sieve Stage of the Quadratic Sieve. For every prime in the factor_base
that doesn't divide the coefficient `a` we add log_p over the sieve_array
such that ``-M <= soln1 + i*p <= M`` and ``-M <= soln2 + i*p <= M`` where `i`
is an integer. When p = 2 then log_p i... | 98a8e5bedaa56dbe53aa8a152c20a015d7b3556d | 23,643 |
def yolo_eval_weighted_nms(yolo_outputs,
anchors,
num_classes,
image_shape,
score_threshold=.6):
""" yolo evaluate
Args:
yolo_outputs: [batch, 13, 13, 3*85]
anchors: [9, 2]
num_cl... | 7066f2dbb4908709a3d762443385376d44d7f9f6 | 23,644 |
def next_coach_id():
"""
Generates the next id for newly added coaches, since their slugs (which combine the id and name fields)
are added post-commit.
"""
c = Coach.objects.aggregate(Max("id"))
return c['id__max']+1 | 55be7f6411685b391e9130bd9248588f3d0d8ffc | 23,645 |
def get_unsigned_short(data, index):
"""Return two bytes from data as an unsigned 16-bit value"""
return (data[index+1] << 8) + data[index] | 9e3b7dc30eaedb99edfb35b944442d7386ad8f9e | 23,646 |
def getObjDetRoI(imgSize, imgPatchSize, objx1, objy1, objx2, objy2):
"""
Get region of interest (ROI) for a given object detection with respect to image and image patch boundaries.
:param imgSize: size of the image of interest (e.g., [1920x1080]).
:param imgPatchSize: Patch size of the image patch of in... | 2feedb9a5f79c24d0fda4eaa9b8db5bd6922b4ce | 23,647 |
def sigma_pp(b):
"""pair production cross section"""
return (
sigma_T
* 3.0
/ 16.0
* (1 - b ** 2)
* (2 * b * (b ** 2 - 2) + (3 - b ** 4) * np.log((1 + b) / (1 - b)))
) | a3745b5f39e71c5f5713e3d7e0c7fbdb53146d15 | 23,648 |
def compute_radii_simple(distances):
"""
Compute the radius for every hypersphere given the pairwise distances
to satisfy Eq. 6 in the paper. Does not implement the heuristic described
in section 3.5.
"""
n_inputs = tf.shape(distances)[1]
sorted_distances = tf.sort(distances, direction="ASC... | a935bbe6539c32d9de87b80dbaa6314152979b07 | 23,649 |
def data_resolution_and_offset(data, fallback_resolution=None):
"""Compute resolution and offset from x/y axis data.
Only uses first two coordinate values, assumes that data is regularly
sampled.
Returns
=======
(resolution: float, offset: float)
"""
if data.size < 2:
if data.s... | 9cb5a14ff5be8509509e67b1576146231258583b | 23,650 |
from typing import List
def get_changed_files_committed_and_workdir(
repo: Git, commithash_to_compare: str
) -> List[str]:
"""Get changed files between given commit and the working copy"""
return repo.repo.git.diff("--name-only", commithash_to_compare).split() | 1696c3bc41084db5d260bc1ddd7811dd9f143586 | 23,651 |
from typing import Optional
from typing import Any
def load_document_by_string(
string: str, uri: str, loadingOptions: Optional[LoadingOptions] = None
) -> Any:
"""Load a CWL object from a serialized YAML string."""
yaml = yaml_no_ts()
result = yaml.load(string)
return load_document_by_yaml(result... | 1750f0df653f155e112b3cbb363e4ee499f76ab6 | 23,652 |
import re
def rename_symbol(symbol):
"""Rename the given symbol.
If it is a C symbol, prepend FLAGS.rename_string to the symbol, but
account for the symbol possibly having a prefix via split_symbol().
If it is a C++ symbol, prepend FLAGS.rename_string to all instances of the
given namespace.
Ar... | 4c2291e3c604157df1f4d8f1f4e3b7a1277ceee2 | 23,653 |
from datetime import datetime
def py_time(data):
""" returns a python Time
"""
if '.' in data:
return datetime.datetime.strptime(data, '%H:%M:%S.%f').time()
else:
return datetime.datetime.strptime(data, '%H:%M:%S').time() | 53f1bb601ab08e06f67b759fdc9f41820ea0ff20 | 23,654 |
def create_empty_copy(G,with_nodes=True):
"""Return a copy of the graph G with all of the edges removed.
Parameters
----------
G : graph
A NetworkX graph
with_nodes : bool (default=True)
Include nodes.
Notes
-----
Graph, node, and edge data is not propagated to the new ... | aea151473bd9f11b4e0cdfdf2ac4a689a1b5af49 | 23,655 |
def trim_resize_frame(frame, resize_ratio, trim_factor):
"""
Resize a frame according to specified ratio while
keeping original the original aspect ratio, then trim
the longer side of the frame according to specified
factor.
Parameters
----------
frame: np.array
The input frame
resize_ratio: floa... | 55569da6aad4b24ef367828a2ce3353048f27ae9 | 23,656 |
def copy_doclist(doclist, no_copy = []):
"""
Save & return a copy of the given doclist
Pass fields that are not to be copied in `no_copy`
"""
cl = []
# main doc
c = Document(fielddata = doclist[0].fields.copy())
# clear no_copy fields
for f in no_copy:
if c.fields.has_key(f):
c.fields[f] = No... | 73e6554696abce1d94ace2b50cb8a28b0563fb30 | 23,657 |
def set_from_tags(tags, title, description, all=True):
"""all=True means include non-public photos"""
user = flickr.test_login()
photos = flickr.photos_search(user_id=user.id, auth=all, tags=tags)
set = flickr.Photoset.create(photos[0], title, description)
set.editPhotos(photos)
return set | 14e30d7334c75d29eccaf7957f53dadc164aedf0 | 23,658 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.