content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def sampleWST_boundedFromOneHalf(m,h,decimal_precision=10):
"""sampleWST_boundedFromOneHalf: Returns a Sample of a Reciprocal Relation Q with `m` alternatives, which is WST and whose entries Q[i,j] fulfill |Q[i,j]-0.5|>h.
m: Number of Alternatives
h: `float` in the interval :... | 5aa27a3a5f318fc636cfb87db8888203ee0f4491 | 3,631,200 |
import os
def which(program):
"""Returns path of the executable, if it exists"""
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in ... | 0f334c76db98b0624082a8097c47bbded64657a6 | 3,631,201 |
def mstep(X: np.ndarray, responsibilities: np.ndarray) -> GaussianMixture:
"""
M-step: Updates the gaussian mixture by maximizing the log-likelihood
of the weighted dataset
:param X: (n, d) array holding the data
:param responsibilities: (n, K) array holding the responsibilities for all components ... | 4b2c79d786fd613598248937a34e86bbc413e10b | 3,631,202 |
def gene_mode(reference, reads, compress, tab, keep):
"""For when inputs are in-frame genes"""
check_input(reference, reads)
tab = check_tab(tab)
ids = []
names = []
seqs = []
og_seqs = {}
err = []
for record in SeqIO.parse(reference, 'fasta'):
ids.append(record.id)
n... | 3b9406ac52f88855983942f0b406154c5aa08e00 | 3,631,203 |
def _acceptance_rule(fx: float, fn: float, temp: float) -> bool:
"""Metropolis acceptance rule"""
dfx = fn - fx
return (dfx < 0) or (
(dfx > 0) and (np.random.rand() <= np.exp(-(fn - fx) / temp))
) | d3c01d194cd23a1201326fd5f968b08df5d705e0 | 3,631,204 |
def listGenericServerEndpoints():
"""Return list of names of generic server endpoints"""
return getObjectNameList( 'GenericServerEndpoint' ) | c05256b4c9a6701eaf393ea0284e31eaddf42966 | 3,631,205 |
def fnCalculate_MaxUnamRangeRate(prf,centre_frequency):
"""
Calculate the maximum unambiguous range rate in the case of unknown direction
Date: 19 June 2017
"""
return AstCnst.c*prf/(4.*centre_frequency); | 7bb24520bf37313246e4335ec1f7c26c67552b94 | 3,631,206 |
from datetime import datetime
def convert_moz_time( moz_time_entry ):
""" Convert Mozilla timestamp-alike data entries to an ISO 8601-ish representation """
# [ https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR/Reference/PRTime ]
## result = datetime.fromtimestamp( moz_time_entry/1000000 ).s... | ba15a7ed86d9b608799384e9663d36c1cff36fae | 3,631,207 |
from pydantic import BaseModel # noqa: E0611
def generate_model_from_yaml(serialized,
tablename,
primary_key,
deserialize_function = None,
cls = BaseModel,
serialization_co... | 901f1223e9eb59ebd31eaa4420c8c06ce28d9b46 | 3,631,208 |
import signal
def stft_power(data, sf, window=2, step=.2, band=(1, 30), interp=True,
norm=False):
"""Compute the pointwise power via STFT and interpolation.
Parameters
----------
data : array_like
Single-channel data.
sf : float
Sampling frequency of the data.
w... | 25533d6bc9f353f12ef63a093d284ea4c81ffe17 | 3,631,209 |
from opf_python.universal import get_HNF_diagonals
def base_mono_29_30(n):
"""Finds the symmetry preserving HNFs for the base centered monoclinic
lattices with a determinant of n. Assuming for basis 29 A =
[[-0.666125, 1.16613 , 2.04852 ], [ 1. , 1. , 0. ], [ 1.61803 ,
-0.618034, 1. ]], for basis ... | a3ed438b9cf4c60523698838fe90d628f8dc4aac | 3,631,210 |
import argparse
def create_parser():
"""
Create the CLI parser
:returns: a parser with subparsers: init, populate, update & query --------
"""
parser = argparse.ArgumentParser(description=__doc__, epilog=epi)
parser.add_argument('-v', '--verbose', action='store_true', default=False,
... | 5dfd5f55ca1e372af7f823253beb64f198eec3f2 | 3,631,211 |
from ._common import connections
def _write_conne(parameters):
"""Write CONNE block data."""
# Reorder connections
if parameters["connections_order"] is not None:
order = parameters["connections_order"]
else:
order = parameters["connections"].keys()
# Format
label_length = le... | 2cdd27db72f98c7265273aa90ba1968102ff0e0f | 3,631,212 |
def objects_to_coordinate_arrays(posobjs,coords='auto',degrees=True):
"""
converts a sequence of position objects into an array of coordinates.
`coords` determines the order of the output coordinates - it can be a
comma-seperated list of coordinate names or if 'auto', it will be 'lat,long'
f... | 0b9e4a0bd2a253242e7c88a8119010f94d2294a5 | 3,631,213 |
def primset_var(*prims):
"""Create a variable that matches a Primitive node."""
return var(lambda node: is_constant(node) and node.value in prims) | d8ef25d456052326d338f7ca8ef9a6b55d070709 | 3,631,214 |
def flatten_basis_data(basis):
"""
Takes in a dictionary of basis set info and flattens
all primitive data into vectors.
"""
nshells = len(basis)
coeffs = []
exps = []
atoms = []
ams = []
indices = []
dims = []
# Smush primitive data together into vectors
nbf = 0
... | 83929bf7237caa1fca0db8e47f5674c2729ed8bc | 3,631,215 |
def generate_spherical_1D_filter(size):
"""
Generate a discrete circle-shaped 1D filter of odd size
Return a list of length size
Le filtre en forme de demi-cercle a été choisi car il présente une forme de plateau
"""
assert size%2==1
x = np.linspace(-1,1,num = size+2)[1:-1]
... | 551dbab78eb18297085e2835368b8618de0670e2 | 3,631,216 |
def send_email_with_rate_control(
user: User,
alert_type: str,
to_email: str,
subject,
plaintext,
html=None,
max_nb_alert=MAX_ALERT_24H,
nb_day=1,
) -> bool:
"""Same as send_email with rate control over alert_type.
Make sure no more than `max_nb_alert` emails are sent over the pe... | 94abf02d10bbf49ac59a8a0ebc1ac1f258911eef | 3,631,217 |
def equatorial_to_ecliptic(ra, dec):
""" translate from equatorial ra & dec to ecliptic ones """
sc = SkyCoord(ra, dec, unit='deg', frame='icrs', obstime='J2000') \
.transform_to('barycentrictrueecliptic')
return sc.lat.value, sc.lon.value | ba12d078e47aeefc3a6c3c7df0919bbf81e5e68b | 3,631,218 |
def get_decode_dir_name(ckpt_name):
"""Make a descriptive name for the decode dir, including the name of the checkpoint we use to decode. This is called in single_pass mode."""
if "train" in FLAGS.data_path: dataset = "train"
elif "val" in FLAGS.data_path: dataset = "val"
elif "test" in FLAGS.data_path: datase... | 8d0f7283ae4342dfd6e3d017c91d7a6a1bc1f11a | 3,631,219 |
from xone import calendar
def trade_day(dt, cal='US'):
"""
Latest trading day w.r.t given dt
Args:
dt: date of reference
cal: trading calendar
Returns:
pd.Timestamp: last trading day
Examples:
>>> trade_day('2018-12-25', cal='US').strftime('%Y-%m-%d')
'20... | bd9fc3e1262f6bff1d7945b140f64f5d7b369bbe | 3,631,220 |
def read_cclist(self):
"""
Read cross-correlation data from file 'cclist.dat'.
Parameters:
-----------
self (saes_core), an instance of the saes_core class.
Returns:
---------
evid1
evid2
sta_cc
cc_val
evdict
"""
evid1,evid2 = None,None
data = np.genfromtxt(... | 2a5c765b226fdc00c54df673a08c49be471a3828 | 3,631,221 |
def witchingHours(symbol="", **kwargs):
"""This is when option contracts and futures contracts expire on the exact same day.
https://iexcloud.io/docs/api/#witching-hours
Args:
symbol (str): symbol to use
"""
return _base(id="PREMIUM_WALLSTREETHORIZON_WITCHING_HOURS", symbol=symbol, **kwargs... | ae779cc2c9f000cb7a7e394cc7aa190079db4deb | 3,631,222 |
import requests
import logging
def is_downloadable(major: int, minor: int, patch: int) -> bool:
"""Test whether is a downloadable nuke version.
Args:
major (int): Major version
minor (int): Minor version
patch (int): Patch version
Returns:
bool: Test result
"""
v... | 97e7f4c8dc86ac5b5c03c20f34f349800b679abc | 3,631,223 |
def create_write_buffer(context, host):
"""Shorthand for creating a write-only buffer on the GPU."""
return ocl.Buffer(context, ocl.mem_flags.WRITE_ONLY, host.nbytes) | 1efdcabb32dd12341bdc1a5b91ac851d9b77e20a | 3,631,224 |
import struct
import binascii
def packet_read(serial_connection):
"""Read a packet from given serial connection.
"""
header = serial_connection.read(3)
if len(header) != 3:
print('error: failed to read packet header')
return None, None
command_type, payload_size = struct.unpack... | 6396cb748d4b2c72525d16d8983450634f643635 | 3,631,225 |
def is_nonnegative_length(G, l):
""" Checks whether a length function, defined on the arcs, satisfies the non-negative condition.
Args:
G: An instance of Graph class.
l: A dictionary that defines a length function on the edge set.
Returns:
A boolean, True if the length function sat... | c99aaf07b65f9a192b6421b4b3ccf73c98917500 | 3,631,226 |
def prepare():
""" Configure environment for testing (like ansible playbook) """
tmt.steps.Prepare.enabled = True
return 'prepare' | f3ca8a5914a6e4747cb3ea46cfbe8115c0331245 | 3,631,227 |
import os
def get_verified_absolute_path(path):
"""Verify and return absolute path of argument.
Args:
path : Relative/absolute path
Returns:
Absolute path
"""
installed_path = os.path.abspath(path)
if not os.path.exists(installed_path):
raise RuntimeError("No valid pa... | 2d7c6dcb6066c81b3506837534a72aa814e1faa6 | 3,631,228 |
def unflatten_tensor(input, feat_size, anchors):
"""
Un-flattens and un-permutes a tensor from size
[B x (W x H) x C] --> [B x C x W x H]
"""
bsize = input.shape[0]
if len(input.shape) >= 3: csize = input.shape[2]
else: csize = 1
input = input.view(bsize, feat_size[0] * anchors.shape[... | 9e7b603071312ea35fa214b3e5a6f586d652c760 | 3,631,229 |
def pct_change(df_or_series, periods=1, fill_method='pad',
limit=None, freq=None, **kwargs):
"""
Percentage change between the current and a prior element.
Computes the percentage change from the immediately previous row by
default. This is useful in comparing the percentage of change in... | e4bc49bdaa2fb5ebf0919a68d685eef612819864 | 3,631,230 |
def get_percentage_from_total(total_serie, fraction_serie):
"""
Get which percentage is each element of a serie from the same element
(same date) on another serie.
"""
return compute_time_series(
[fraction_serie, total_serie], utils.get_percent) | eb08c429da50c3408c6cdb90ea24c67d9f099680 | 3,631,231 |
def get_isotope_data(isotope_string: str) -> dict:
"""Get the isotope's intrinsinc properties from a JSON data file."""
formatted_isotope_string = format_isotope_string(isotope_string)
isotope_dict = dict(ISOTOPE_DATA[formatted_isotope_string])
isotope_dict.update({"isotope": formatted_isotope_string})
... | 08c5271e49db49f5cef45eb539797db8a2575eeb | 3,631,232 |
def resample_bins(xb, yb, min_bin=10, beta=0.5):
"""
Do a bootstrap resample within the len(xb) bins in the list yb.
Only resample if there are at least min_bin elements in a bin,
otherwise reject the entire bin with probability (1-beta).
"""
xb = np.asarray(xb)
bin_size = np.array(map(len,... | f9aa729266562332e5a5b67beb0e218a20b65733 | 3,631,233 |
from typing import Dict
from typing import Any
import logging
def _run_optimizers(
product_batch: Dict[str, Any],
language: str,
country: str,
currency: str,
cached_optimizers: optimizer_cache.OptimizerCache,
) -> (Dict[str, Any], Dict[str, optimization_result.OptimizationResult]):
"""Transforms... | e2346bd670099e86787d2b8690d7294a5da9f7d2 | 3,631,234 |
import curses
import math
def get_colour_depth():
"""
Returns the maximum number of possible values per color channel,
that can be used with the availible number of
colours and colour pairs in the terminal.
"""
nr_colours = curses.COLORS
return int(math.pow(nr_colours, 1. / 3.)) | 3bd47ee65a7db72d87ac7cc965a43e37724e148a | 3,631,235 |
def find_best_hand(*args):
"""Takes some cards and produces the best possible hand.
Parameters
----------
args : Multiple 'Card' type.
These cards form the sample of cards to use to attempt to make the
best hand possible.
Returns
-------
TODO
"""
assert len(... | ba6cc2d190d06783210031124b2f92aeef0319ce | 3,631,236 |
def google_translate(request):
"""Get translation from Google machine translation service."""
try:
text = request.GET["text"]
locale_code = request.GET["locale"]
if not locale_code:
raise ValueError("Locale code is empty")
except (MultiValueDictKeyError, ValueError) as ... | 03d5746ac0eddb953d0f02fd78f6883c6c0809c9 | 3,631,237 |
import re
def parseLemma(lines):
"""
:param lines:
:param normalize:
:return:
# ToDo: Fix issue with
Caeres2=Cāeres|miles|Cāerĭt,Cāerĭtēt||ĭtis, (-ētis), f.|2
Caerēs=Cāerēs|diues|Cāerĭt||ĭtis|2
"""
lemmas = {}
lemma_without_variations = re.compile(
r"^(?P<lemma>\w+\d... | c45f80badb3f3d2a2d04777bec304608269f28d4 | 3,631,238 |
from typing import Optional
import re
def get_genre_regexp(ctx: Context, actor: Actor) -> Optional[str]:
"""
Extract the genre from user request if present
Use adapter to insert as a condition or a processing function
"""
last_request = ctx.last_request
for key in GENRE_DICT.keys():
if... | 3d15c7babdb76be6ae63970df59366cbe4ebeaef | 3,631,239 |
def mapper(request_id, bucket, prefix):
"""Get instructions on how to process an input zarr store by chunk.
For a zarr store at s3://bucket/prefix, return a list of row boundaries
that correspond to chunks in the store. Assumes that the s3 path is
readable by an anonymous client.
"""
s3_path =... | e025a26521a53c8b9aec7410a63ae9c9875123c8 | 3,631,240 |
from typing import Optional
from typing import Union
def byteify(data: Optional[Union[str, bytes]], encoding='utf-8', if_none=None) -> bytes:
"""
Convert a piece of data into bytes if it isn't already::
>>> byteify("hello world")
b"hello world"
By default, if ``data`` is ``No... | aac62c4925ab204386d4fcfb927972fbc47c974b | 3,631,241 |
def vote_details(request, id):
"""
Details for a vote.
Parameters:
id -- the id of the `Vote`.
"""
vote = Vote.objects.filter(uid=id)
if not vote:
return {}
data = {
'id': vote.id,
'author_id': vote.author.id,
'author': vote.author.name,
'post_id... | f8066bc8f94308b2df2e0acc7d4703bd8937b48a | 3,631,242 |
def get_p_vals(location_median_results, author_gender_median_results, date_median_results):
"""
Takes results from **results_by_location(results, 'median')**, **results_by_author_gender**,
**results_by_date**.
ANOVA test for independence of:
- male vs female authors' median distance between female... | 8bd4f9ef60891f2767c79f28a9d51bcff72d2851 | 3,631,243 |
from shutil import copyfile
def copyfiles(filelist, dest, copy=False):
"""Copy or symlink files in ``filelist`` to ``dest`` directory.
Parameters
----------
filelist : list
List of files to copy.
dest : path/files
full path to destination. If it is a list of length greater
... | 1e05b1ff194babbe7f32ec59dfb0d426656caec4 | 3,631,244 |
def ancestors(repo, subset, x):
"""Changesets that are ancestors of changesets in set, including the
given changesets themselves.
If depth is specified, the result only includes changesets up to
the specified generation.
"""
# startdepth is for internal use only until we can decide the UI
a... | 06642e762d040a49600084db94ea36c6c1cec0e7 | 3,631,245 |
def mock_down_payment_time_with_raise_closure(option = 1):
"""
@fn mock_down_payment_time_with_raise_closure
"""
def mock_down_payment_time_with_raise_input(input_prompt):
if "annual salary" in input_prompt.lower():
return down_payment_time_with_raise_test_values(
option).annual_salary
if... | 669f7dc5b9945d0d153d908f63b6ea7c0d0ec332 | 3,631,246 |
def hist_intersection(histA, histB):
""" Calcuates the intersection of two histograms.
If two normalised histograms are the same then the sum of the intersection
will be one.
Assumes histograms are normalised.
Parameters
----------
histA: 1D numpy array
normalised array where the ... | 029c2d81a80d9ce89b5fd383fe1db1b8e40cf0ba | 3,631,247 |
import six
import traceback
def failure_format_traceback(fail):
"""
:param fail: must be an IFailedFuture
returns a string
"""
try:
f = six.StringIO()
traceback.print_exception(
fail._type,
fail.value,
fail._traceback,
file=f,
... | fdcbdf9f7617f401d511c9ce9b58420367419250 | 3,631,248 |
def ConvT3D(parent, filters, kernel_size, strides=[1, 1, 1], padding="same",
use_bias=True, groups=1, dilation_rate=[1, 1, 1], name=""):
"""\
3D Transposed convolution layer (sometimes called deconvolution).
The need for transposed convolutions generally arises from the desire to
use a tran... | e56980ec2a09c16d4392eca96ad0156e4c17fc1d | 3,631,249 |
def bytes_to_int(b: bytes) -> int:
"""
Convert bytes to a big-endian unsigned int.
:param b: The bytes to be converted.
:return: The int.
"""
return int.from_bytes(bytes=b, byteorder='big', signed=False) | eb08ae0b2663047557b8f102c6c6ed565aae8044 | 3,631,250 |
import argparse
def parse_arguments() -> argparse.Namespace:
"""Parse arguments provided by the command-line
:return: list of decoded arguments
"""
parser = argparse.ArgumentParser(description=__doc__)
pa = parser.add_argument
pa('filename', type=str, help='input contents filename')
pa('-... | 637775c9c4950a07ff5ed3391db76c0502ef3068 | 3,631,251 |
def train_step(sess, dataset, sequence_number, model, parameters):
"""
Train.
"""
# Perform one iteration
token_indices_sequence = dataset.token_indices['train'][sequence_number]
for i, token_index in enumerate(token_indices_sequence):
if token_index in dataset.infrequent_token_indices ... | bd5b1aef942b585d0ecaad3b1f90ad1b02a21fb4 | 3,631,252 |
import numpy
def cos_distance_numpy_vector(v1, v2):
"""get cos angle (similarity) between two vectors"""
d1 = numpy.sum(v1 * v1)
d1 = numpy.sqrt(d1) # magnitude of v1
d2 = numpy.sum(v2 * v2)
d2 = numpy.sqrt(d2) # magnitude of v2
n1 = v1 / d1
n2 = v2 / d2
return numpy.sum(n1 *... | fdbc02c5cba377c561843dd57e9ca13a2e9c6960 | 3,631,253 |
import os
def send_smart_contract_thresholds(request, pk):
"""
Create a smartcontract file on disk and transmit it.
"""
try:
print("IN SEND_SAMART_COTNRA")
templ = Template.objects.get(id=pk)
... | 7ff6b827dd7d83f2e4e7440b1252ce0322beb7a8 | 3,631,254 |
def list_all_submodules(package):
""" List all the modules in this package with their fully qualified names."""
root_modname = package.__name__
# if the module is not a package do nothing, we check this by the
# presence of the __path__ attribute which only packages have
if not hasattr(package, "_... | 81c22be084ebbba6bd300d95e52642b9b33954bc | 3,631,255 |
def int_greater_than(x, inclusive: bool = False):
"""Creates property that must be an int greater than (or equal to)
some value
Parameters:
x: Value that the property must be greater than
inclusive (bool): If set to True, includes x as a possibility.
Returns:
property
"""... | 8b8a74fe09590d90a77fda2d932a4b3b2905dbcc | 3,631,256 |
from typing import Optional
async def get_Sales_with_date_with_login(q: Query, start_date: Optional[str] = "", end_date: Optional[str] = ""):
"""
Get the sales of a particular day
"""
try:
tkit = Toolkit(shop_url=q.shop_url, api_secret=q.api_secret)
results = tkit.getSales(start_date,... | f83fc10fe5fbfaec6805c9a2079217b1e64c6c1e | 3,631,257 |
def cell_to_se2_batch(cell_idx, mapmin, mapres):
"""
Coversion for Batch input : cell_idx = [batch_size, 2]
OUTPUT: [batch_size, 2]
"""
return (cell_idx[:,0] + 0.5) * mapres[0] + mapmin[0], (cell_idx[:,1] + 0.5) * mapres[1] + mapmin[1] | 72a91b5b3a90014322ad8754848e5f85751d3b3a | 3,631,258 |
def merge(elems, field = None, **kwargs):
"""
merge the fields for all elements in a list return it as a single
element.
Parameters
-----------
elems : list. a list of element object
kwargs: dict. other properties of the new element.
Examples
----------
>>> bpm = getElements('... | 0801709d9af67963ab0223f502513bf9825e44f1 | 3,631,259 |
def add_answerset(m_json, mid=None, **kwargs):
"""Add answerset."""
if mid is None:
mid = str(uuid4())
with session_scope() as session:
aset = Answerset(m_json, id=mid, **kwargs)
session.add(aset)
return mid | 8bf0d9cc9ef0636a465af67eb26a9d0fe446f3ec | 3,631,260 |
def is_reserved(ips):
"""Indicates whether each address is reserved.
*** Addresses must be IPv4. IPv6 not yet supported. ***
"""
res = cudf.Series(rmm.device_array(len(ips), dtype="bool"))
ptr = res.data.mem.device_ctypes_pointer.value
reserved_ipv4_REGEX = r"^(2(4[0-9]|5[0-5]))\.([0-9]|[1-9][0-... | d40a0092268eee5c6a8d6b22e0b6de9b1ebd8132 | 3,631,261 |
def split_last_dimension(x, n):
"""Reshape x so that the last dimension becomes two dimensions.
The first of these two dimensions is n.
Parameters
----------
x
A Tensor with shape [..., m]
n: int
An integer.
Returns
-------
y
A Tensor with shape [..., n, m/... | 9909db0fda7cc5ee0666b910459c598741d5c6e3 | 3,631,262 |
from typing import Tuple
async def authenticate_user(
request: web.Request, for_password_modification=False
) -> Tuple[User, Claims]:
"""Multiple schemes authentication using request Authorization header.
Raises HTTPUnauthorized on failure.
"""
if not request.headers.get("Authorization"):
... | 72b0daa26f4b4c8e589223313c6fbba3e348decf | 3,631,263 |
def nest(collection, *properties):
"""This method is like :func:`group_by` except that it supports nested
grouping by multiple string `properties`. If only a single key is given, it
is like calling ``group_by(collection, prop)``.
Args:
collection (list|dict): Collection to iterate over.
... | ca66ca29c9a33674d8c8bb3dc1937cb1e6018a2d | 3,631,264 |
def pyav_decode_stream(
container, start_pts, end_pts, stream, stream_name, buffer_size=0
):
"""
Decode the video with PyAV decoder.
Args:
container (container): PyAV container.
start_pts (int): the starting Presentation TimeStamp to fetch the
video frames.
end_pts (i... | 5b012899c047dcd3ee90d793c68ebdd1d2f413c1 | 3,631,265 |
import sqlite3
def encode_data_for_sqlite(value):
"""Fix encoding bytes."""
try:
return value.decode()
except (UnicodeDecodeError, AttributeError):
return sqlite3.Binary(value) | fe59a2b0dde5ff7c41acc02c4de6724cc75553fb | 3,631,266 |
def inject_sync_poller(sender, caller, st_type, user, **kwargs):
"""Inject javascript code."""
condition = (
caller != "top" or
st_type != "js" or
not hasattr(user, "mailbox") or
not user.parameters.get_value("enable_carddav_sync")
)
if condition:
return ""
re... | 18479a46f02424e7b3e4a0a6e8d2543621ad1115 | 3,631,267 |
import logging
import json
def findExtensions(extensionsPath):
"""
Finds extensions in the selected Firefox profile.
Parameters
----------
extensionsPath : str
Path to the extensions.json file.
Return Values
-------------
extensionsList : [Extension]
List of identified extens... | e455d0159e345622705f96bcdd98df9fa7c974f7 | 3,631,268 |
def parse_pointstamped(point_input):
"""
Parse point_input into PointStamped.
"""
try:
assert isinstance(point_input, PointStamped)
return point_input
except:
pass
try:
assert isinstance(point_input, Point)
point = PointStamped(point = point_input)
... | 0103abc2b73581daa73c8981d45ad87d77cfba78 | 3,631,269 |
def ext_binary_gcd_env(a, b):
"""Extended binary GCD.
Given input a, b the function returns
d, s, t such that gcd(a,b) = d = as + bt."""
u, v, s, t, r = 1, 0, 0, 1, 0
while (a & 1 == 0) and (b & 1 == 0):
a, b, r = a >> 1, b >> 1, r + 1
alpha, beta = a, b
#
# from here on we ma... | c189fbdd27dcff14bec9093924067f247ea38f88 | 3,631,270 |
import os
import yaml
def write_init_file(name, data, path=""):
"""
This function writes config files for devices and default files
:param name: Name of the file to be written to
:param data: Data in Dict format
:param path: Path where to write
:return:
"""
# ... | 18c7d6d5b2eb9b0eee3b09a5f15635da32dce015 | 3,631,271 |
import random
def gen_tasksets(
number_of_sets=100, number_of_task=15, util_req=0.5,
period_pdf=[0.03, 0.02, 0.02, 0.25, 0.40, 0.03, 0.2, 0.01, 0.04],
scalingFlag=True, threshold=0.1, cylinder=4, sumRunnable=True):
"""Main function to generate task sets with the WATERS benchmark.
Varia... | ac1f09df006d31dfc1b772c850906ec236d07f4d | 3,631,272 |
from typing import Dict
from pathlib import Path
import yaml
def get_categories_and_file_names() -> Dict:
"""Returns a dictionary of categories and files
Returns
-------
Dict
Key is the name of the category, value is a dictionary with information on files in that \
category
"""
... | 4e7d0295e6e40e5c443f5d91c18d83d138b092f4 | 3,631,273 |
from typing import Dict
from typing import Set
def process_class_items(game_class: GameClass, categories: Dict[str, Dict[str, int]], items_def: Dict,
removals: Set[str], locked: Set[str]) -> ClassUnlockables:
"""
Process a hierarchical definition of a class's items into a ClassUnlockab... | 64290748b72dac3590e6677dcd65af62677cee79 | 3,631,274 |
from typing import Optional
async def resolve_rrid(
identifier: str, client: ClientSession, settings: SciCrunchSettings
) -> Optional[ResolvedItem]:
"""
Provides a API to access to results as provided by this web https://scicrunch.org/resolver
"""
# Example https://scicrunch.org/resolver/RRID:AB_... | 8818711de82448f91eb807c68eb19e0af2776938 | 3,631,275 |
def MakeByte(ea):
"""
Convert the current item to a byte
@param ea: linear address
@return: 1-ok, 0-failure
"""
return idaapi.doByte(ea, 1) | ce8925c66d3e4a6c811f2a244f56b4317c66a877 | 3,631,276 |
import inspect
import sys
def get_all():
"""Returns all activation functions."""
fns = inspect.getmembers(sys.modules[__name__])
fns = [f[1] for f in fns if len(f)>1 and f[0] != "get_all"\
and isinstance(f[1], type(get_all))]
return fns | 52772f2aac04a9d68f9c6470a19d99afb79f7f7f | 3,631,277 |
def upload_persons(request):
"""
Options for upload form to define person and person roles
:param request:
:return:
"""
print('persons upload request: ', request.GET)
selection = NmPersonsEntries.objects.all().distinct('entry_id')
myFilter = PersonsFilter(request.GET, queryset=selection... | 2caf9a8c10c12aaa9b46bd83666c39dac4dd6492 | 3,631,278 |
from neon.backends.nervanacpu import NervanaCPU
from neon.backends.util import check_gpu
from neon.backends.nervanagpu import NervanaGPU
from mgpu.nervanamgpu import NervanaMGPU
from argon.neon_backend.ar_backend import ArBackend
import logging
import atexit
def gen_backend(backend='cpu', rng_seed=None, datatype=np.f... | 8e6127d70a1fa4bee0d1e3a5c6855338f1254218 | 3,631,279 |
from redis import exceptions
import socket
def get_redis_error_classes():
"""Return tuple of redis error classes."""
# This exception suddenly changed name between redis-py versions
if hasattr(exceptions, 'InvalidData'):
DataError = exceptions.InvalidData
else:
DataError = exceptions.... | 7d2331de649430a857c1575ccc590c642ff36e4a | 3,631,280 |
from typing import Dict
from typing import Any
def create_property(supported_prop: Dict[str, Any]) -> HydraClassProp:
"""Create a HydraClassProp object from the supportedProperty."""
# Syntax checks
doc_keys = {
"property" : False,
"title": False,
"readonly": True,
"writeo... | 7f0aa8252f995d0ae7a9fad5f5690a034d159458 | 3,631,281 |
import scipy.weave.md5_load as md5
def expr_to_filename(expr):
""" Convert an arbitrary expr string to a valid file name.
The name is based on the md5 check sum for the string and
Something that was a little more human readable would be
nice, but the computer doesn't seem to care.
"""... | 0fde1beda5e073890258f3fba5a8b5f38b1129fb | 3,631,282 |
def getIDList():
"""getIDList() -> list(string)
Returns a list of all lanes in the network.
"""
return _getUniversal(tc.ID_LIST, "") | e7c3f0134f8a91778cc8caf252eaf0f11cdb8e46 | 3,631,283 |
def cmor(B, C):
"""
Returns the n-point continuous Morlet wavelet
Args:
B the bandwidth parameter
C the central frequency
"""
def time(t, s=1.):
s = jnp.atleast_2d(jnp.asarray(s)).T
t = t / s
# the sinusoid
output = jnp.exp(1j * 2 * jnp.pi * C * t)
... | dc7e521113837423e37c20d2f31ad7222dd37fd6 | 3,631,284 |
def calculateMid(paddle):
"""Calculates midpoint for each paddle, much easier to move the paddle this way"""
midpoint = int(paddle[0][1] + paddle[1][1]) / 2
return midpoint | 83fbba67945d158807bd9c3aebcab63342ce7599 | 3,631,285 |
def autotune(i):
"""
Input: {
See 'crowdsource program.optimization'
(iterations) - change iterations
Force:
local = yes
only_one_run = yes
keep_tmp = yes
skip_exchange... | 22e29831cfaa040ff0425a87f482be857a12004f | 3,631,286 |
import io
def generate_from_file(abouts, is_about_input, license_dict, scancode, min_license_score, template_loc=None, vartext=None):
"""
Generate an attribution text from an `abouts` list of About objects, a
`template_loc` template file location and a `vartext` optional
dict of extra variables.
... | 099152905ded65278d1b382956f35b110692b8f2 | 3,631,287 |
from typing import Match
from datetime import datetime
def user_past_parties():
"""List parties the logged in user has been in.
Params:
page (int): Optional. Page number to return.
"""
received = request.get_json()
page = received.get('page', 1)
# User record
user = util.user_fro... | 6a6cd86abe39e962a2b09a7204ad62f5be894df4 | 3,631,288 |
def bits_list(number):
"""return list of bits in number
Keyword arguments:
number -- an integer >= 0
"""
# https://wiki.python.org/moin/BitManipulation
if number == 0:
return [0]
else:
# binary_literal string e.g. '0b101'
binary_literal = bin(number)
bit... | 6f27715dbccefe56d77c800a44c4fa5e82d35b50 | 3,631,289 |
def show_funcs():
"""
List of of algos presently available
"""
return(sorted(func_registry.keys())) | e685c92ee8cbc8a7d5d1c7323976eaccd10fa4fa | 3,631,290 |
def _FakeQuantWithMinMaxVars(inputs, min_var, max_var, per_channel, num_bits,
narrow_range):
"""Adds a fake quantization operation.
Depending on value of per_channel, this operation may do global quantization
or per channel quantization. min_var and max_var should have corresponding... | 1457d7f7661ed336421f715f4841c6e7a1518537 | 3,631,291 |
def join_and_keep_order(left, right, remove_duplicates, keep='first', **kwargs):
"""
:type left: DataFrame
:type right: DataFrame
:rtype: DataFrame
"""
left = left.copy()
right = right.copy()
left['_left_id'] = range(left.shape[0])
right['_right_id'] = range(right.shape[0])
result = left.merge(right=right, **... | a3044f7de9c1f8ffb50cf1e57997307ee0e3d840 | 3,631,292 |
import typing
from typing import Counter
def count_variants(graph) -> typing.Counter[str]:
"""Count how many of each type of variant a graph has.
:param pybel.BELGraph graph: A BEL graph
"""
return Counter(
variant_data[KIND]
for data in graph
if has_variant(graph, data)
... | 194a3881e0cb4b73520293ec587cae96de932958 | 3,631,293 |
def collate(expression, collation):
"""Return the clause ``expression COLLATE collation``.
e.g.::
collate(mycolumn, 'utf8_bin')
produces::
mycolumn COLLATE utf8_bin
"""
expr = _literal_as_binds(expression)
return _BinaryExpression(
expr,
_literal_as_text(col... | 37896bfce0f7c02c4021af75105a878831de4838 | 3,631,294 |
def crop_images(x, y, w, h, *args):
"""
Crops all the images passed as parameter using the box coordinates passed
"""
assert len(args) > 0, "At least 1 image needed."
cropped = []
for img in args:
cropped.append(img[x : x + h, y : y + w])
return cropped | e8f78246c0bfeb3d370b8fe01e264b2f7e0e1c49 | 3,631,295 |
import time
import json
def WriteResultToJSONFile(test_suites, results, json_path):
"""Aggregate a list of unittest result object and write to a file as a JSON.
This takes a list of result object from one or more runs (for retry purpose)
of Python unittest tests; aggregates the list by appending each test resu... | cb53b65bf5c8ceb1d0695e38c4ebeedd4916fe14 | 3,631,296 |
def svn_prop_has_svn_prop(*args):
"""svn_prop_has_svn_prop(apr_hash_t props, apr_pool_t pool) -> svn_boolean_t"""
return _core.svn_prop_has_svn_prop(*args) | 5ca451ecd2d945ace6f690ada61abc6de1bef445 | 3,631,297 |
def test_analysis_dual_grad(n, lbda):
""" Test the gradient of dual analysis. """
rng = check_random_state(None)
x, _, _, _, D, A = synthetic_1d_dataset(n=n, s=0.5, snr=0.0, seed=rng)
eps = 1e-3
v_dim = D.shape[1]
v = np.clip(rng.randn(n, v_dim), -(lbda - eps), (lbda - eps))
Psi_A = np.linal... | 5ba56bc1621f7e159c4cb5c5e2309272690b787f | 3,631,298 |
def dojo_gbrv_results(pseudo, struct_type, num_sites, volumes, etotals):
"""
This function computes the GBRV results and returns the dictionary
to be inserted in the dojoreport file.
Args:
pseudo: Pseudopotential object.
struct_type: "fcc" or "bcc"
num_sites: Number of sites in ... | f20eac647f4bc83235ea71187dcd493392028472 | 3,631,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.