content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def make_connector(name=None):
"""A connector between constraints"""
informant = None
constraints = []
def set_value(source, value):
nonlocal informant
val = connector["val"]
if val is None:
informant, connector["val"] = source, value
if name is not None:... | 46b6574b6e8965d56f71efa89a1d7389502f2867 | 3,635,400 |
from osgeo import ogr
def read_shp(path):
"""Generates a networkx.DiGraph from shapefiles. Point geometries are
translated into nodes, lines into edges. Coordinate tuples are used as
keys. Attributes are preserved, line geometries are simplified into start
and end coordinates. Accepts a single shapefi... | f68b5e1716c10b9c58f7f661fddbda7a84acfc99 | 3,635,401 |
def network_alignment(network_a, network_b):
"""combines two networks into a new network
| Arguments:
| :-
| network_a (networkx object): biosynthetic network from construct_network
| network_b (networkx object): biosynthetic network from construct_network\n
| Returns:
| :-
| Returns combined network as... | e1aa0fdbbd74d63fe85028339ef9402a21f566b4 | 3,635,402 |
def grab_cpu_scalar(v, nd):
"""
Get a scalar variable value from the tree at `v`.
This function will dig through transfers and dimshuffles to get
the constant value. If no such constant is found, it returns None.
Parameters
----------
v
Aesara variable to extract the constant value... | b842b59f903b23146cbcec5d391e8ecd7db67604 | 3,635,403 |
def _get_interface_name_index(dbapi, host):
"""
Builds a dictionary of interfaces indexed by interface name.
"""
interfaces = {}
for iface in dbapi.iinterface_get_by_ihost(host.id):
interfaces[iface.ifname] = iface
return interfaces | 0217f6ef8d4e5e32d76a4fc0d66bf74aa45f8c36 | 3,635,404 |
def generate_data(shape, num_seed_layers=3, avg_bkg_tracks=3,
noise_prob=0.01, verbose=True, seed=1234):
"""
Top level function to generate a dataset.
Returns arrays (events, sig_tracks, sig_params)
"""
np.random.seed(seed)
num_event, num_det_layers, det_layer_size, _ = shape
... | 74116397ced9085794416a7c2c191e3a4fac135a | 3,635,405 |
import xml
from typing import List
from typing import Optional
from typing import Tuple
import pathlib
def create_project(
root: xml.etree.ElementTree.Element,
include: List[str],
exclude: Optional[List[str]] = None
) -> Tuple[List[str], List[str], List[pathlib.Path], List[pathlib.Path],
List[p... | dda783efec500750dec65823701f186234bbc5dc | 3,635,406 |
import torch
def to_data(x):
"""Converts variable to numpy"""
if torch.cuda.is_available():
x = x.cpu()
return x.data.numpy() | b91f755d43fde06db1bd38158881eb2f84e43d10 | 3,635,407 |
def levmar_bc(func, p0, y, bc, args=(), jacf=None,
mu=1.0e-03, eps1=1.5e-08, eps2=1.5e-08, eps3=1.5e-08,
maxit=1000, cdiff=False):
"""
Parameters
----------
func: callable
Function or method computing the model function, `y = func(p, *args)`.
p0: array_like, shape... | 6d861988290c00b846a8ff35bc36beca778985f7 | 3,635,408 |
import json
def set_name_filter(request):
"""
Sets product filters given by passed request.
"""
product_filters = request.session.get("product_filters", {})
if request.POST.get("name", "") != "":
product_filters["product_name"] = request.POST.get("name")
else:
if product_filte... | a36e9e46a58b71926bafee248312abddaba6ce90 | 3,635,409 |
import argparse
def get_arguments():
"""
Wrapper function to get the command line arguments. Inserting this piece of code
into its own function for conda compatibility.
"""
parser = argparse.ArgumentParser(
prog='KrakMeOpen',
usage='krakmeopen [--input FILE | --input_pickle FILE |... | ad326fdab79874f33e8df005d5d5e470d23f8e42 | 3,635,410 |
def select(
da,
longitude=None,
latitude=None,
T=None,
Z=None,
iT=None,
iZ=None,
extrap=False,
extrap_val=None,
locstream=False,
):
"""Extract output from da at location(s).
Parameters
----------
da: DataArray
Property to take gradients of.
longitude,... | 91fbf82ca99ddc3eb6328b1c435cdb70f706c9a3 | 3,635,411 |
def afsluitmiddel_regelbaarheid(damo_gdf=None, obj=None):
""""
Zet naam van AFSLUITREGELBAARHEID om naar attribuutwaarde
"""
data = [_afsluitmiddel_regelbaarheid(name) for name in damo_gdf['SOORTREGELBAARHEID']]
df = pd.Series(data=data, index=damo_gdf.index)
return df | 66bb59b2cea9e84faafe54adf114a73571f6fd05 | 3,635,412 |
import copy
def generate(i):
"""
Input: {
(output_txt_file) - if !='', generate text file for a given conference
(conf_id) - record names for this conf
}
Output: {
return - return code = 0, if successful
... | ec2de19931fa527cba88baec8775b21c7bcbf88c | 3,635,413 |
def calc_solidangle_particle(
pts=None,
part_traj=None,
part_radius=None,
config=None,
approx=None,
aniso=None,
block=None,
):
""" Compute the solid angle subtended by a particle along a trajectory
The particle has radius r, and trajectory (array of points) traj
It is observed f... | 46a9700c12bc8d734678795a0cb989d025f02685 | 3,635,414 |
def fields_view(arr, fieldNameLst=None):
"""
Return a view of a numpy record array containing only the fields names in
the fields argument. 'fields' should be a list of column names.
"""
# Default to all fields
if not fieldNameLst:
fieldNameLst = arr.dtype.names
dtype2 = np.dtyp... | 5d4e6629c3acf26619033d9d7e103c9e817bea78 | 3,635,415 |
import os
def initialize_servers_and_threads():
"""
Returns a dictionary object containing an initialized server and thread object for each email
"""
servers_and_threads = {}
for email in os.listdir(".emails"):
server = classes.server.Server(email)
servers_and_threads[email] = {"Server": server, "Thread": cl... | 895cddf530e8e77f5356f14ce19a266ba0f9ed0b | 3,635,416 |
from typing import List
from typing import Tuple
def image_detach_with_id_color_list(
color_img: np.ndarray,
id_color_list: List[Tuple[int, Tuple[int, int, int]]],
bin_num: int,
mask_value: float = 1.0,
) -> np.ndarray:
"""
컬러 이미지 `color_img`를 색상에 따른 각 인스턴스 객체로 분리합니다.
Parameters
----... | 941100eb6fed342b4a89a10115ee55350c58ae6e | 3,635,417 |
from typing import Dict
from typing import Any
from typing import List
import copy
def defaultArgs(options: Dict = None, **kwargs: Any) -> List[str]: # noqa: C901,E501
"""Get the default flags the chromium will be launched with.
``options`` or keyword arguments are set of configurable options to set on
... | 3f43e3505b77f232e7f797caff318ffe5f466f7d | 3,635,418 |
from typing import List
def process_v3_fields(fields: List[str], endpoint: str) -> str:
"""
Filter v3 field list to only include valid fields for a given endpoint.
Logs a warning when fields get filtered out.
"""
valid_fields = [field for field in fields if field in FIELDS_V3]
if len(valid_f... | 87f21c58a4a5613dc0c319cf4adcc29a42cd2054 | 3,635,419 |
def getManifestFsLayers(manifest):
""" returns hashes pointing to layers for manifest"""
return manifest["manifest"]["fsLayers"] | a3449c2828222c2b806df8621dd6a24375778ed2 | 3,635,420 |
def Jones_METIS(c, tau, w, q):
""" Returns Jones polynomial evaluated at t(q) via METIS
contraction of the tensor network of the knot encoded
in edgelist c. w is the writhe of the knot. """
nc = len(c) # number of crossings
if nc > 0:
nv = cnf_nvar(c)
ekpotts = -tpotts(q)
... | 77b16bd2737ea3b9628d52c9fa2eea014644af37 | 3,635,421 |
def screen_name_filter(tweet_list, stoplist):
"""
Filter list of tweets by screen_names in stoplist.
Pulls original tweets out of retweets.
stoplist may be a list of usernames, or a string name of a configured
named stoplist.
"""
tweets = []
id_set = set()
if isinstance(stoplist, ba... | da8f292e496503cb70c3cf7f33ba7f87ed874cbb | 3,635,422 |
def insert_into(table_name, values, column_names, create_if_not_exists=False, inspect=True, engine=None):
"""
Inserts a list of values into an existing table
:param table_name: the name of the table into which to insert records
:param values: a list of lists containing literal values to insert into the... | ac9f299da13cb12446e1ac14c1962deb93a1d233 | 3,635,423 |
def delchars(str, chars):
"""Returns a string for which all occurrences of characters in
chars have been removed."""
# Translate demands a mapping string of 256 characters;
# whip up a string that will leave all characters unmolested.
identity = "".join([chr(x) for x in range(256)])
return str... | a220202a05e0ead7afa6226ef309c56940a1d153 | 3,635,424 |
from typing import Optional
from typing import cast
import collections
from typing import Set
from typing import Type
from typing import Union
from typing import List
def normalize_typed_substitution(
value: SomeValueType, data_type: Optional[AllowedTypesType]
) -> NormalizedValueType:
"""
Normalize a mix... | 40250403240d591734770b146dd8253fe24c5083 | 3,635,425 |
def index(request):
"""
View for the static index page
"""
return render(request, 'public/home.html', _get_context('Home')) | 3598ef8776943c63f49787f63f69d8a22536805e | 3,635,426 |
def bytes2hex(bytes_array):
"""
Converts byte array (output of ``pickle.dumps()``) to spaced hexadecimal string representation.
Parameters
----------
bytes_array: bytes
Array of bytes to be converted.
Returns
-------
str
Hexadecimal representation of the byte array.
... | 19019ee1e3cd45d671f53e0ae4fd92b283c3b38d | 3,635,427 |
def atan2(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.arctan2 <numpy.arctan2>`.
See its docstring for more information.
"""
if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allow... | 8a0621bfd0ad8ac4ce9e14cc939e5a8b9e3e511c | 3,635,428 |
import os
def family_directory(fonts):
"""Get the path of font project directory."""
if fonts:
dirname = os.path.dirname(fonts[0])
if dirname == '':
dirname = '.'
return dirname | 91d1f880a01ba2de11e6570272d5748d1dea6d47 | 3,635,429 |
def authorizer(*args, **kwargs):
"""
decorator to register an authorizer.
:param object args: authorizer class constructor arguments.
:param object kwargs: authorizer class constructor keyword arguments.
:keyword bool replace: specifies that if there is another registered
... | 5af038c7e1bebee228bffc24c72aa54e03a8d28e | 3,635,430 |
def option_getter(config_model):
"""Returns a get_option() function using the given config_model and data"""
def get_option(option, x=None, default=None, ignore_inheritance=False):
def _get_option(opt, fail=False):
try:
result = config_model.get_key('techs.' + opt)
... | ad5726bc957e1c5902960ebc0e51af43f0ab31eb | 3,635,431 |
def is_core_dump(file_path):
"""
Determine whether given file is a core file. Works on CentOS and Ubuntu.
Args:
file_path: full path to a possible core file
"""
file_std_out = exec_local_command("file %s" % file_path)
return "core file" in file_std_out and 'ELF' in file_std_out | 33c9974888857f913de1702117a0add2c686c252 | 3,635,432 |
from pathlib import Path
def to_posix(d):
"""Convert the Path objects to string."""
if isinstance(d, dict):
for k, v in d.items():
d[k] = to_posix(v)
elif isinstance(d, list):
return [to_posix(x) for x in d]
elif isinstance(d, Path):
return d.as_posix()
return... | 91dbda7738308dd931b58d59dad8e04a277034ea | 3,635,433 |
from datetime import datetime
def lc_concatenate_worker(task):
"""
This is the parallel worker for the function below.
task is a tuple:
task[0] = base LC file
task[1] = new LC file to be concatenated to base
task[2] = zero-indexed column number to use to sort resulting LC
(if N... | c5b72c4576748949b1968dfc9ed93bf34d347b48 | 3,635,434 |
import traceback
def list_entities(currency, ids=None, page=None, pagesize=None): # noqa: E501
"""Get entities
# noqa: E501
:param currency: The cryptocurrency (e.g., btc)
:type currency: str
:param ids: Restrict result to given set of comma separated IDs
:type ids: List[str]
:param pa... | 7956ab50da50811785be9fd1c834984500460378 | 3,635,435 |
def sensor(request):
"""HTTP/GET /sensor コール時の処理
ADC以外のセンサー値を読んで返す
Args:
request (QueryDict): リクエストパラメータ
Returns:
dict: クライアントに返すjson形式の値
"""
params = request.GET.copy()
api_response = ApiResponse()
params["ids"] = params.getlist("ids")
parse = ParseApiParams(param... | d9df39aeeeb6077c6bf2b6c0019d682f3a05e78f | 3,635,436 |
def stat(lst):
"""Calculate mean and std deviation from the input list."""
n = float(len(lst))
mean = sum(lst) / n
stdev = sqrt((sum(x * x for x in lst) / n) - (mean * mean))
return mean, stdev | c1983fc9da96397a5f55e45d0eac9cbc921a91fc | 3,635,437 |
import attr
def _recursive_generic_validator(typed):
"""Recursively assembles the validators for nested generic types
Walks through the nested type structure and determines whether to recurse all the way to a base type. Once it
hits the base type it bubbles up the correct validator that is nested within ... | dcc89a9c358da848d56d3c031e3967402ef70a28 | 3,635,438 |
import os
def getAllFilesOfExtension(rootDir, extension):
"""Traverse a directory tree and find all the files with a specified extension
Args:
rootDir: The directory to traverse
extension: The extension
Returns:
A list of files
"""
fileList = []
for (dirPath, d... | 13248ca9aef4ff2c52a8281d107b3adf8ce4e479 | 3,635,439 |
def get_posts(di, po, syn):
"""
Gets the postings list for each unique token in the query
"""
words = {}
#goes through each token in the query and returns its postings list
for i in range(len(syn)):
word = syn[i][0]
#goes through each synonym for each word
for k i... | 8a45df246bf6bb19baf570b133427f937d36f5d9 | 3,635,440 |
def need_food(board, bad_positions, snake):
""" Determines if we need food and returns potential food that we can get """
potential_food = []
# food that is not contested (we are the closest)
safe_food = [fud for fud in board.food if board.get_cell(fud) != SPOILED]
# always go for safe food even i... | 73359fa082feda5a2e3efb8d9d7f091d9d23a8bb | 3,635,441 |
def categoriesJSON():
"""Return JSON for all the categories"""
categorys = session.query(Category).all()
return jsonify(categories=[c.serialize for c in categorys]) | 2f300dca846d2c01dca1ea80798fbcf258e459e8 | 3,635,442 |
def rescale_column(img, gt_bboxes, gt_label, gt_num, img_shape):
"""rescale operation for image"""
img_data, scale_factor = rescale_with_tuple(img, (config.img_width, config.img_height))
if img_data.shape[0] > config.img_height:
img_data, scale_factor2 = rescale_with_tuple(img_data, (config.img_heig... | 1f765b69b65ab34b1d272223a2344e6068f3f4ab | 3,635,443 |
def ausc_trapazoidal(mean_df, doses):
"""Performs numerical integration using the trapazoidal rule
to determine the area under the survival curve (AUSC)
for the drug respose.
The only argument, mean_df, is a data frame made from make_mean_std().
"""
y = mean_df.normalized_mean
x = doses
... | fad1c30d6996ea7ea3e4d6cf0d6546f76647e459 | 3,635,444 |
import os
def _get_file_handler(name):
"""
Создание файлового хандлера.
Ротация 5 файлов по 50 мегабайт.
"""
file_obj = RotatingFileHandler(os.path.join(_path, name + ".log"), maxBytes = 50000000, backupCount = 5)
file_obj.setLevel("TRACE")
return file_obj | c1bf53ad63ea0aae49c7ff93c7ab736350bcc752 | 3,635,445 |
def psu_info_table(psu_name):
"""
:param: psu_name: psu name
:return: psu info entry for this psu
"""
return "PSU_INFO" + TABLE_NAME_SEPARATOR_VBAR + psu_name | e3894e0ae5735d8f096cfa72ac50bc6fd3d966da | 3,635,446 |
def delete_rds(rds_client, rds_instances) -> list:
"""Deletes all instances in the instances parameter.
Args:
rds_client: A RDS boto3 client.
rds_instances: A list of instances you want deleted.
Returns:
A count of deleted instances
"""
terminated_instances = []
for ins... | f1e66cce8e2d98c53bc247c2e2b8fd57c195b86c | 3,635,447 |
import itertools
def all_preferences(candidates, concentrate=False):
"""
Generates all possible preferences given a list of candidates
"""
permutations_tuple = list(itertools.permutations(candidates))
permutations_list = list(map(list, list(permutations_tuple)))
if concentrate:
return ... | 53f078a9fd3f66696cc5bc64de9b41d4ccbe2c8c | 3,635,448 |
import torch
def div_reg(net, data, ref):
"""
Regulize the second term of the loss function
"""
mean_f = net(data).mean()
log_mean_ef_ref = torch.logsumexp(net(ref), 0) - np.log(ref.shape[0])
return mean_f - log_mean_ef_ref - log_mean_ef_ref**2 | 04d28e11df8f7b5e723d1930372afca317e1c349 | 3,635,449 |
def action_list():
""" Prints all the available actions present in this file. """
rospy.loginfo(color.BOLD + color.PURPLE + '|-------------------|' + color.END)
rospy.loginfo(color.BOLD + color.PURPLE + '| AVAILABLE ACTIONS |' + color.END)
rospy.loginfo(color.BOLD + color.PURPLE + '| 1: MOVE TO POINT ... | 2c5e80c9e2ddcc127812491e4bfd8ed0a4765b53 | 3,635,450 |
def firstLetterCipher(ciphertext):
"""
Returns the first letters of each word in the ciphertext
Example:
Cipher Text: Horses evertime look positive
Decoded text: Help """
return "".join([i[0] for i in ciphertext.split(" ")]) | 87f37d1a428bde43c07231ab2e5156c680c96f91 | 3,635,451 |
def polar_decode(N, K, P0):
"""
Decode a (N, K) polar code.
P0 must be 1-normalized probabilities
"""
n = np.log2(N).astype(int)
A = polar_hpw(N)[-K:]
# We're not using all the elements in the P array, as each layer lamb
# only uses 2**(n-lamb) elements. Given the current indexing it's ... | c305aaaa124faec73145a87cdbafe35965e26ec6 | 3,635,452 |
from pathlib import Path
from typing import Tuple
import re
def parse_samtools_flagstat(p: Path) -> Tuple[int, int]:
"""Parse total and mapped number of reads from Samtools flagstat file"""
total = 0
mapped = 0
with open(p) as fh:
for line in fh:
m = re.match(r'(\d+)', line)
... | 60c6f9b227cefdea9877b05bb2fe66e4c82b4dd1 | 3,635,453 |
import io
import tarfile
import time
import os
import posixpath
def create_tar_in_memory(files):
"""
Construct a tar file in-memory.
:param files: Sequence of (path, data) tuples.
:type files: list
:return: Tar file.
:rtype: File-like object.
"""
output = io.BytesIO()
with tarfile.... | feb49d92d0790e3d4cec08f7cfc8947f8520b74c | 3,635,454 |
def get_country(country_id=None, incomelevel=None, lendingtype=None, cache=True):
"""
Retrieve information on a country or regional aggregate. Can specify
either country_id, or the aggregates, but not both
:country_id: a country id or sequence thereof. None returns all countries
and aggregates... | b798667f1bd1c0c8649986b948201392eae1f165 | 3,635,455 |
def _PmapWalkARMLevel2(tte, vaddr, verbose_level = vSCRIPT):
""" Pmap walk the level 2 tte.
params:
tte - value object
vaddr - int
returns: str - description of the tte + additional informaiton based on verbose_level
"""
pte_base = kern.PhysToKernelVirt(tte & 0xFFFFFC00)
... | bb4a7dcd70abf5f3f451c5ce56d10673bdb803b4 | 3,635,456 |
def mel_spectrogram_feature(wav, hparams=None):
"""
Derives a mel spectrogram ready to be used by the encoder from a preprocessed audio waveform.
Note: this not a log-mel spectrogram.
"""
hparams = hparams or default_hparams
frames = librosa.feature.melspectrogram(
wav,
hparams.s... | 5f1541109b81b535ca9a263a954ce82b067fe3eb | 3,635,457 |
def getRdkitAtomXYZbyId(rdkitMol,atomId, confId=0):
"""Returns an xyz atom position given atom's id."""
conf = rdkitMol.GetConformer(confId)
return np.array(list(conf.GetAtomPosition(atomId))) | 6a28646e7c7275c2c43da5fea512273e68e4a9e4 | 3,635,458 |
def _mn_minos_ ( self , *args ) :
"""Get MINOS errors for parameter:
>>> m = ... # TMinuit object
>>> result = m.minos( 1 , 2 )
"""
ipars = []
for i in args :
if not i in self : raise IndexError
ipars.append ( i )
return _mn_exec_ ( self , 'MINOS' , 200 , *... | cd99344cb7af2bca3db1abb576ec63ffff2df032 | 3,635,459 |
def app_files(proj_name):
"""Create a list with the project files
Args:
proj_name (str): the name of the project, where the code will be hosted
Returns:
files_list (list): list containing the file structure of the app
"""
files_list = [
"README.md",
"setup.py",
... | 2c6cbf112c7939bea12672668c8a5db1656b6edd | 3,635,460 |
def periodic_name(userword):
"""Generate a sequence of periodic elements from a word or sentence."""
# split up into individual words
sentence = userword.split()
output = []
# match each word with the periodic system
for word in sentence:
sequencer = ElementalWord(word)
basescore... | bfd7b2aa26baa193ac055afc64334058860d9a16 | 3,635,461 |
import json
def presentationRequestApiCallback():
""" This method is called by the VC Request API when the user scans a QR code and presents a Verifiable Credential to the service """
presentationResponse = request.json
print(presentationResponse)
if request.headers['api-key'] != apiKey:
print... | f45e4580d73ec9679679c801aaeaf664011c340a | 3,635,462 |
def process_table(data: document.TableNode, caption: str) -> NoEscape:
"""
Returns a Latex formatted Table Item, wrapped with a NoEscape Command
"""
rows = [
tuple(
" ".join(process(c) for c in table_cell["children"])
for table_cell in table_row["children"]
)
... | bd9b8e450a5c872a83d0d146d7256f581fa4bc39 | 3,635,463 |
def getTracksForArtist(artistName, tracks = None):
"""
Return a Track object for each track found with the specified artistName.
"""
tracksToSearch = tracks or getTracks()
return filter(lambda x:x.artist == artistName, tracksToSearch) | 5df8ead4d3c5f47810ccbb55a9f442e542d9c454 | 3,635,464 |
import torch
def log_safe(x):
"""The same as torch.log(x), but clamps the input to prevent NaNs."""
x = torch.as_tensor(x)
return torch.log(torch.min(x, torch.tensor(33e37).to(x))) | 98c73b316d22ebe9ef4b322b1ba984a734422e7a | 3,635,465 |
def index(request):
"""Redirect to the index page."""
context = {'form': LoginForm() }
return render(request, 'index.htm', context) | f2181aa02dd8709350be8675e5da21e2a94bdf27 | 3,635,466 |
def summarize_chrom_classif_by_sample(psd_list, sample_list):
""" Summarize chromosome classification by sample
Inputs:
psd_list: list of SamplePSD AFTER calc_chrom_props() has been run
sample_list: list of samples in same order as psd_list
Returns:
data frame w... | 64b77680d8e5a3170d4bd8a0680e979d0e3f8e89 | 3,635,467 |
def fake_quant_with_min_max_vars_per_channel_gradient(input_gradients, input_data,
input_min, input_max,
num_bits=8, narrow_range=False):
"""
Computes gradients of Fake-quantize on the 'input_data' tenso... | 36452b2783b35280f87dcbd260fad4f11d95f73a | 3,635,468 |
def test_split(data, test_size=0.3):
"""
Split data to train and test subsets.
:param data: Array like list.
:param test_size: Size of test subset.
:return: Returns tuple of matrix like subsets (train_subset, test_subset).
"""
return sklearn.model_selection.train_test_split(data, test_size) | d53d5957960046e09c6e2fcdf88dc24251689af8 | 3,635,469 |
def unpack_remotedata(o, byte_keys=False, myset=None):
""" Unpack WrappedKey objects from collection
Returns original collection and set of all found keys
Examples
--------
>>> rd = WrappedKey('mykey')
>>> unpack_remotedata(1)
(1, set())
>>> unpack_remotedata(())
((), set())
>>... | d1beda543ff3045bcb603d14dba7a5d6c4689f4b | 3,635,470 |
def xscontrol_Vars(*args):
"""
Args:
pilot(Handle_IFSelect_SessionPilot)
Returns:
static Handle_XSControl_Vars
Returns the Vars of a SessionPilot, it is brought by Session
it provides access to external variables
"""
return _XSControl.xscontrol_Vars(*args) | 280e0d6823fa86adbff02ce633075b5b6c4a4e4e | 3,635,471 |
def swing_twist_decomposition(q, twist_axis):
""" code by janis sprenger based on
Dobrowsolski 2015 Swing-twist decomposition in Clifford algebra. https://arxiv.org/abs/1506.05481
"""
q = normalize(q)
#twist_axis = np.array((q * offset))[0]
projection = np.dot(twist_axis, np.array([q[1], q[2... | 555b7897aafc3085c875513274c44abc3f06fbb4 | 3,635,472 |
import os
def DatasetFileName(filename):
"""Returns location of `filename` within --dataset_dir`."""
return os.path.join(dataset_dir, filename) | b74c7e1c5e8386ef74172f9bd317badff6833d65 | 3,635,473 |
import requests
def resolve_s1_slc(identifier, download_url, project):
"""Resolve S1 SLC using ASF datapool (ASF or NGAP). Fallback to ESA."""
# determine best url and corresponding queue
vertex_url = "https://datapool.asf.alaska.edu/SLC/SA/{}.zip".format(
identifier)
r = requests.head(vertex... | cf489b0d65a83dee3f87887a080d67acd180b0b3 | 3,635,474 |
def equivalent_gaussian_Nsigma_from_logp(logp):
"""Number of Gaussian sigmas corresponding to tail log-probability.
This function computes the value of the characteristic function of a
standard Gaussian distribution for the tail probability equivalent to the
provided p-value, and turns this value into ... | 8dde13e19fe15d2dbdfdc3c1902edcf220672796 | 3,635,475 |
import tempfile
from pathlib import Path
import logging
import zipfile
def fetch_ratings():
"""Fetches ratings from the given URL."""
url = "http://files.grouplens.org/datasets/movielens/ml-25m.zip"
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir, "download.zip")
l... | 439b9603a849d822d30e93e663a3e9195651cd06 | 3,635,476 |
def _parse_affected(text):
"""Extract the affected releases, services, and other software
Args:
text: the text version of the security note
Returns:
a list of the affected releases
"""
valid_releases = ['austin', 'bexar', 'cactus', 'diablo', 'essex',
'folsom', 'gri... | e9da321ee587455d60da09d26a818038ab6e7c0f | 3,635,477 |
def _window_view(a, window, step = None, axis = None, readonly = True):
"""
Create a windowed view over `n`-dimensional input that uses an
`m`-dimensional window, with `m <= n`
Parameters
-------------
a : Array-like
The array to create the view on
... | 2e083a105be37e1fe9e784c0378c3a0bb667601e | 3,635,478 |
def approveReport(id):
"""
Function to approve a report
"""
# Approve the doc source entity record
sgtable = s3db.stats_group
sgt_table = s3db.stats_group_type
resource = s3db.resource("stats_group", id=id, unapproved=True)
resource.approve()
# find the type of report that we ha... | 25a87f20870b5ac90dea6c5013a337ffabfd9e04 | 3,635,479 |
def _maybe_promote_geometry(geom):
""" Either promote the geometry to a Multi-geometry, or return input"""
promoter = _promotion_dispatch.get(geom.type, lambda x: x[0])
return promoter([geom]) | 4b6f5805049025cb3692dff77af708350e3ccc8f | 3,635,480 |
def preprocess_input(frames):
"""Resize and subtract mean from video input
Args:
frames (tf.Tensor): Video frames to preprocess. Expected shape
(frames, rows, columns, channels).
Returns:
A TF Tensor.
"""
# Reshape to 128x171
frames = tf.ima... | 8bbede3ef2d8f131ee09f46bddfd4b66ad868f27 | 3,635,481 |
from pathlib import Path
def get_cache_info(path: Path) -> CacheInfo:
"""Return the information used to check if a file is already formatted or not."""
stat = path.stat()
return stat.st_mtime, stat.st_size | 4559d5e0179c803c7a4b23c9bd15a7317c84a2a7 | 3,635,482 |
def gmm_component_contributions_to_message_length(responsibilities,
log_likelihoods,
covs, weights):
"""
Return the component-wise contributions to the message length.
"""
K, N = responsibilities.shape
... | 0c06c5b5881f58ae63fe8326c87f2fcbac2ddbe7 | 3,635,483 |
def validate(request):
"""Method for validating a common request."""
validation = versioning.validate(request)
if validation['status'] != 'ok':
return validation
cursor = mysql.connection.cursor()
validation = player.validate(request, cursor)
if validation['status'] != 'ok':
re... | 5f4a0205dc002b994b3b49582f82594f84fcc64b | 3,635,484 |
def text_to_list(text):
""" Convert the paper into a list of preformatted sentences. """
s = symbol.substitute_symbol(text)
# Convert all characters to lowercase
s = s.lower()
# Convert text into list of paragraphs
a = s.split("\r\n")
b = ignoretopics.ignore_topics(a)
b = accenter.deacc... | c971423eaa7dcecd3f36019a852cfb400ab014c6 | 3,635,485 |
def make_anagram_dict(filename):
"""Takes a text file containing one word per line.
Returns a dictionary:
Key is an alphabetised duple of letters in each word,
Value is a list of all words that can be formed by those letters"""
result = {}
fin = open(filename)
for line in fin:
w... | c6c0ad29fdf63c91c2103cefc506ae36b64a40ec | 3,635,486 |
def test_hierarchical_seeding(RefSimulator):
"""Changes to subnetworks shouldn't affect seeds in top-level network"""
def create(make_extra, seed):
objs = []
with nengo.Network(seed=seed, label='n1') as model:
objs.append(nengo.Ensemble(10, 1, label='e1'))
with nengo.Net... | 108cc8b05f5ea30a2d8b2892e77bc0b42b880500 | 3,635,487 |
def group_property_types(row : str) -> str:
"""
This functions changes each row in the dataframe to have the one
of five options for building type:
- Residential
- Storage
- Retail
- Office
- Other
this was done to reduce the dimensionality down to the top building
types.
... | 44aa5d70baaa24b0c64b7464b093b59ff39d6d1c | 3,635,488 |
def parseLbannLayer(l, tensorShapes, knownNodes=[]):
"""
Parses a given LBANN layer and returns the equivalent ONNX expressions needed to be represent the layer.
Args:
l (lbann_pb2.Layer): A LBANN layer to be converted.
tensorShapes (dict): Shapes of known named tensors.
knownNodes ... | c915b175ecf7c99dbc675302d055393e90bf8b12 | 3,635,489 |
def write_simple_templates(n_rules, body_predicates=1, order=1):
"""Generate rule template of form C < A ^ B of varying size and order"""
text_list = []
const_term = "("
for i in range(order):
const_term += chr(ord('X') + i) + ","
const_term = const_term[:-1] + ")"
write_string = "{0} ... | 3a911702be9751b0e674171ec961029f5b10a9e7 | 3,635,490 |
def get_datatoken_minter(datatoken_address):
"""
:return: Eth account address of the Datatoken minter
"""
dt = get_dt_contract(get_web3(), datatoken_address)
publisher = dt.caller.minter()
return publisher | da71e8e05569a6cdc2661fd3f8b937510d5e037f | 3,635,491 |
from pixar import UsdviewPlug
import os, time
def GetAssetCreationTime(primStack, assetIdentifier):
"""Finds the weakest layer in which assetInfo.identifier is set to
'assetIdentifier', and considers that an "asset-defining layer". We then
effectively consult the asset resolver plugin to tell us the crea... | 24281a61c9a5dbf18a30ccc4856ebae56b11b96b | 3,635,492 |
def symplectic_map_personal(x, px, step_values, n_iterations, epsilon, alpha, beta, x_star, delta, omega_0, omega_1, omega_2, action_radius, gamma=0.0):
"""computation for personal noise symplectic map
Parameters
----------
x : ndarray
x initial condition
px : ndarray
px initial... | a7f71eb1e160069adbe18a3d2792310fc3c58517 | 3,635,493 |
import os
def wl_offset(input_table, **kwargs):
"""
Derives wavelength offsets for white dwarf exposures.
Cross-correlates flux and net from white dwarf exposures against one another to derive
offsets
Parameters
----------
input_table : abscal.common.exposure_data_table.AbscalDataTa... | 54f4f1acd943d1fab33322c949cf88f3a8fe934f | 3,635,494 |
def GetRevertedRevision(message):
"""Parse message to get the reverted revision if there is one."""
lines = message.strip().splitlines()
if not lines:
return None
if not lines[0].lower().startswith('revert'):
return None
for line in reversed(lines): # pragma: no cover
# TODO: Handle cases where... | eb6f43e3adb906f2f27916ac6071309a24cdf9f4 | 3,635,495 |
def line_center(p0, p1):
"""
given two points p0, p1 inside a poincare disk
find the centre and radius of the arc that defines a line through them
https://en.wikipedia.org/wiki/Poincar%C3%A9_disk_model#Analytic_geometry_constructions_in_the_hyperbolic_plane
"""
u1, u2, u3 = p0
v1, v2, v3 = p... | f8af690c30423621041244ae0cb8da2eebd45063 | 3,635,496 |
import math
import decimal
def infer_decimals(value):
"""
Devuelve la cantidad de cifras decimales del valor, aplicando una heurística de corrección
previa.
Para valores del estilo 1.0000000000000001, (común al serializar números en punto flotante),
se los trunca a 17 - N dígitos, siendo N la can... | b813d5baa2c8fa6e5697a5502a1a5d299f2167a2 | 3,635,497 |
def desalt_smiles(row, smilesfield, desalter):
"""This function creates desalted smiles for a pandas dataframe row
row : row of the dataframe
smilesfiel : str (name of the smiles field in the row)
desalter : instance of Smiles_desalter class
reaction_list : list of dictionaries (rdkit reaction named... | cf722c51a6f5b01a946b2ecabe6e10f9abda6c79 | 3,635,498 |
def mesh_vertex_2_coloring(mesh):
"""Try to color the vertices of a mesh with two colors only without adjacent vertices with the same color.
Parameters
----------
mesh : Mesh
A mesh.
Returns
-------
dict, None
A dictionary with vertex keys pointing to colors, if two-colorab... | 4ba963b94e9db024c2012d8b565e5af9fb838d80 | 3,635,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.