content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import logging
import urllib
import re
def proxyFromPacFiles(pacURLs=None, URL=None, log=True):
"""Attempts to locate and setup a valid proxy server from pac file URLs
:Parameters:
- pacURLs : list
List of locations (URLs) to look for a pac file. This might
come from :func:`... | 90d61afcd7473c43e257bc92cb205b1870273845 | 3,642,500 |
def subplots(times,nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,
gridspec_kw=None, **fig_kw):
""" create figure and subplot axes with same time (x) axis
Non-Market hours will not be included in the plot.
Notably a custom projection is used for the time axis, and the time values
... | dd10ae6939587cac36e9b4bff67e2426357c6635 | 3,642,501 |
def test_env(testenv, agent, config):
"""
Test of a GYM environment with an agent deciding on actions based
on environment state. The test is repeated for the indicated
iterations. Status of environment in each step is displayed if
verbose activated. Test results (frequency count) a... | 7a32e942f22f983e6377568be6e2019a72574eac | 3,642,502 |
def kldivergence(p, q):
"""Kullback-Leibler divergence D(P || Q) for discrete distributions
Parameters
----------
p, q : array-like, dtype=float, shape=n
Discrete probability distributions.
"""
p = np.asarray(p, dtype=np.float)
q = np.asarray(q, dtype=np.float)
return np.sum(np.wher... | 0c0bff8e1f4d9c5ca57b555cffe5d827350106b5 | 3,642,503 |
import os
def read_file(file_dir: str, filename: str) -> bytes:
""" Read file contents to bytes """
with open(os.path.join(file_dir, filename), "rb") as f:
data = f.read()
return data | b0e8207a25d6dd85fcd4701696d40146282a6095 | 3,642,504 |
def sortPermutations(perms, index_return=False):
"""
Sort perms with respect (1) to their length and (2) their lexical order
@param perms:
"""
ans = [None] * len(perms)
indices = np.ndarray(len(perms), dtype="int")
ix = 0
for n in np.sort(np.unique([len(key) for key in perms])):
... | d20833936756f3617e394fdb62f45e798c5cc416 | 3,642,505 |
def get_laplacian(Dx,Dy):
"""
return the laplacian
"""
[H,W] = Dx.shape
Dxx, Dyy = np.zeros((H,W)), np.zeros((H,W))
j,k = np.atleast_2d(np.arange(0,H-1)).T, np.arange(0,W-1)
Dxx[j,k+1] = Dx[j,k+1] - Dx[j,k]
Dyy[j+1,k] = Dy[j+1,k] - Dy[j,k]
return Dxx+Dyy | 77dce6adecdf1effd4922f18dc0ec1d20f4e69f4 | 3,642,506 |
def recipes_ending(language: StrictStr, ending: StrictStr):
"""
Show the recipe for a word-ending.
Given an input language and an ending, present the user with
the recipe that will be used to build grammatical cases
for that specific ending.
And this path operation will:
* returns a singl... | 5584f4005d76a0ac13a73cfffd35b7e1f5d5d538 | 3,642,507 |
def blur(grid, blurring):
"""
Spreads probability out on a grid using a 3x3 blurring window.
The blurring parameter controls how much of a belief spills out
into adjacent cells. If blurring is 0 this function will have
no effect.
"""
height = len(grid)
width = len(grid[0])
center... | dec94ad3d2f14d4ac12b6799d8ee581afe73f53d | 3,642,508 |
def _row_adress(addr='1'):
"""returns the rown number for a column adress"""
return _cell_address(''.join(['A', addr]))[1] | eba4cc5a30a539b6bf021279698070c4ae10ee20 | 3,642,509 |
def split(x, num, axis):
"""
Splits a tensor into a list of tensors.
:param x: [Tensor] A TensorFlow tensor object to be split.
:param num: [int] Number of splits.
:param axis: [int] Axis along which to be split.
:return: [list] A list of TensorFlow tensor objects.
... | 6461e346261cc01e5b2ddc0bee164b49ea03035b | 3,642,510 |
def delete_sensor_values(request):
"""Delete values from a sensor
"""
params = request.GET
action = params.get('action')
sensor_id = params.get('sensor')
delete_where = params.get('delete_where')
where_value = params.get('value')
where_start_date = params.get('start_date')
where_end... | 049119e50ea2613c8f8c2ccaa674fd99a35c07e8 | 3,642,511 |
import collections
def _parse_voc_xml(node):
"""
Extracted from torchvision
"""
voc_dict = {}
children = list(node)
if children:
def_dic = collections.defaultdict(list)
for dc in map(_parse_voc_xml, children):
for ind, v in dc.items():
def_dic[ind].a... | 58ef998cdf36ce4620042736ff27fc06d4c277a6 | 3,642,512 |
from ostap.math.integral import integral as _integral
def sp_integrate_3Dy ( func ,
x , z ,
ymin , ymax , *args , **kwargs ) :
"""Make 1D numerical integration over y-axis
>>> func = ... ## func ( x , y , z )
## x ... | 8e641911a7cbdf215cb5a0e8c12d122a14c83638 | 3,642,513 |
def log_exp_sum_1d(x):
"""
This computes log(exp(x_1) + exp(x_2) + ... + exp(x_n)) as
x* + log(exp(x_1-x*) + exp(x_2-x*) + ... + exp(x_n-x*)), where x* is the
max over all x_i. This can avoid numerical problems.
"""
x_max = x.max()
if isinstance(x, gnp.garray):
return x_max + gnp.l... | 4e0fcf4831e052e1704394e783bd0a76157a123f | 3,642,514 |
def connect_intense_cells(int_cells, conv_buffer):
"""Merge nearby intense cells if they are within a given
convective region search radius.
Parameters
----------
int_cells: (N, M) ndarray
Pixels associated with intense cells.
conv_buffer: integer
Distance to search... | 079ab9f1dad2ee4b45e5e96923bb05b3e3e59c01 | 3,642,515 |
from typing import Union
def _encode_decimal(value: Union[Decimal, int, str]):
"""
Encodes decimal into internal format
"""
value = Decimal(value)
exponent = value.as_tuple().exponent
mantissa = int(value.scaleb(-exponent))
return {
'mantissa': mantissa,
'exponent': expone... | 089bd0dd79d6d75dfb4278c46c801df32f5be608 | 3,642,516 |
def getPristineStore(testCase, creator):
"""
Get an Axiom Store which has been created and initialized by C{creator} but
which has been otherwise untouched. If necessary, C{creator} will be
called to make one.
@type testCase: L{twisted.trial.unittest.TestCase}
@type creator: one-argument calla... | f3be2f5bfff30af298de250d7c2ecf1664cd503f | 3,642,517 |
def data_to_CCA(dic, CCA):
"""
Returns a dictionary of ranking details of each CCA
{name:{placeholder:rank}
"""
final_dic = {}
dic_CCA = dic[CCA][0] #the cca sheet
for key, value in dic_CCA.items():
try: #delete all the useless info
del value["Class"]
except Ke... | fedd8a55e4310c024ede4f474c89463f71a0ecb6 | 3,642,518 |
import os
def quick_nve(mol, confId=0, step=2000, time_step=None, limit=0.0, shake=False, idx=None, tmp_clear=False,
solver='lammps', solver_path=None, work_dir=None, omp=1, mpi=0, gpu=0, **kwargs):
"""
MD.quick_nve
MD simulation with NVE ensemble
Args:
mol: RDKit Mol object
... | 9b59f09bd86ba2dc93bb51cd4338f26b948de858 | 3,642,519 |
from astropy.coordinates import Angle
def deg2hms(x):
"""Transform degrees to *hours:minutes:seconds* strings.
Parameters
----------
x : float
The degree value to be written as a sexagesimal string.
Returns
-------
out : str
The input angle written as a sexagesimal string... | d4172d8cfe5b71115b6fde93469019a4644edce6 | 3,642,520 |
def get_waveforms_scales(we, templates, channel_locations):
"""
Return scales and x_vector for templates plotting
"""
wf_max = np.max(templates)
wf_min = np.max(templates)
x_chans = np.unique(channel_locations[:, 0])
if x_chans.size > 1:
delta_x = np.min(np.diff(x_chans))
else:
... | 98ece821ab449d2cbdfe5c81635b7948de88083e | 3,642,521 |
import time
def rec_findsc(positions, davraddi, davradius='dav', adatom_radius=1.1,
ssamples=1000, return_expositions=True,
print_surf_properties=False, remove_is=True, procs=1):
"""It return the atom site surface(True)/core(Flase) for each atoms in
for each structure pandas da... | 7f48d6c7732a23827879f22fba97c109456d01f8 | 3,642,522 |
from typing import Optional
async def accept_taa(
controller: AcaPyClient, taa: TAARecord, mechanism: Optional[str] = None
):
"""
Accept the TAA
Parameters:
-----------
controller: AcaPyClient
The aries_cloudcontroller object
TAA:
The TAA object we want to agree to
Re... | 40557b41aa2f43a3174dacf20252b11be4b6679d | 3,642,523 |
def discoverYadis(uri):
"""Discover OpenID services for a URI. Tries Yadis and falls back
on old-style <link rel='...'> discovery if Yadis fails.
@param uri: normalized identity URL
@type uri: six.text_type, six.binary_type is deprecated
@return: (claimed_id, services)
@rtype: (six.text_type, ... | 11ec5cb250f331e17fb84a4bc699c4396d4040ad | 3,642,524 |
def mapper_to_func(map_obj):
"""Converts an object providing a mapping to a callable function"""
map_func = map_obj
if isinstance(map_obj, dict):
map_func = map_obj.get
elif isinstance(map_obj, pd.core.series.Series):
map_func = lambda x: map_obj.loc[x]
return map_func | 5da5497b68dc71aec10231f80580fcbaab86c00e | 3,642,525 |
def int_finder(input_v, tol=1e-6, order='all', tol1=1e-6):
"""
The function computes the scaling factor required to multiply the
given input array to obtain an integer array. The integer array is
returned.
Parameters
----------
input1: numpy.array
input array
tol: float
... | c7168a9146def4990174be56c7811663b62e82a2 | 3,642,526 |
def cell_info_for_active_cells(self, porosity_model="MATRIX_MODEL"):
"""Get list of cell info objects for current case
Arguments:
porosity_model(str): String representing an enum.
must be 'MATRIX_MODEL' or 'FRACTURE_MODEL'.
Returns:
List of **CellInfo** objects
**CellInfo ... | f2b211e72bc5c2f651d67fa383dc750b6b9f5c5a | 3,642,527 |
def features(x, encoded):
"""
Given the original images or the encoded images, generate the
features to use for the patch similarity function.
"""
print('start shape',x.shape)
if len(x.shape) == 3:
x = x - np.mean(x,axis=0,keepdims=True)
else:
# count x 100 x 256 x 768
... | 1f3e1514dc67908207c38d75914954cb1af8178b | 3,642,528 |
from datetime import datetime
def create_processing_log(s_url,s_status=settings.Status.PENDING):
"""
Creates a new crawler processing status. Default status PENDING
:param s_url: str - URL/name of the site
:param s_status: str - The chosen processing status
:return: SiteProcessingLog - The new pr... | 05fd2e5b01289f982789b1f7d88b401b25d445c3 | 3,642,529 |
import torch
def pick_action(action_distribution):
"""action selection by sampling from a multinomial.
Parameters
----------
action_distribution : 1d torch.tensor
action distribution, pi(a|s)
Returns
-------
torch.tensor(int), torch.tensor(float)
... | ac7ceb0df860876ec209563eaa6bdd3f8bd09189 | 3,642,530 |
from typing import List
def word_tokenizer(text: str) -> List[str]:
"""Tokenize input text splitting into words
Args:
text : Input text
Returns:
Tokenized text
"""
return text.split() | dc6e4736d7a1f564bcfc6fed081a1869db38eea5 | 3,642,531 |
from google.cloud import datacatalog_v1beta1
def lookup_bigquery_dataset(project_id, dataset_id):
"""Retrieves Data Catalog entry for the given BigQuery Dataset."""
datacatalog = datacatalog_v1beta1.DataCatalogClient()
resource_name = '//bigquery.googleapis.com/projects/{}/datasets/{}'\
.format(... | 847ce43ccea5f462ccf696bc5a098c0e26f27852 | 3,642,532 |
def indicator_structure(Template, LC_instance):
""" given a Template A and a LC instance Sigma
builds the indicator structure of Sigma over A
and passes the identification object """
in_vars, in_cons = LC_instance
# Construct the domain of the indicator by factoring
arities = dict(in_va... | 0652fd3af1a16892496b232e42c2fbdb2525fc78 | 3,642,533 |
def add_depth_dim(X, y):
"""
Add extra dimension at tail for x only. This is trivial to do in-line.
This is slightly more convenient than writing a labmda.
Args:
X (tf.tensor):
y (tf.tensor):
Returns:
tf.tensor, tf.tensor: X, y tuple, with X having a new trailing dimension.
... | 972bcc5df0e333186b39d306c9cec46c23117c9a | 3,642,534 |
import functools
import warnings
import traceback
def catch_exceptions(warning_msg="An exception was caught and ignored.", should_catch=True):
"""Decorator that catches exceptions."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if not should_catch:
... | 4242512d6416ecd97ef0c241d0d719fcdaedd797 | 3,642,535 |
def setSC2p5DAccNodes(lattice, sc_path_length_min, space_charge_calculator, boundary = None):
"""
It will put a set of a space charge SC2p5D_AccNode into the lattice as child nodes of the first level accelerator nodes.
The SC nodes will be inserted at the beginning of a particular part of the first level AccNode ele... | f40c21f625da435ff7b42b157dbce803ebd0bf82 | 3,642,536 |
def transmuting_ring_sizes_score(mapping: LigandAtomMapping):
"""Checks if mapping alters a ring size"""
molA = mapping.molA.to_rdkit()
molB = mapping.molB.to_rdkit()
molA_to_molB = mapping.molA_to_molB
def gen_ringdict(mol):
# maps atom idx to ring sizes
ringinfo = mol.GetRingInfo(... | fb09a123eea6eb155c6c8aecccedf82838ee40ff | 3,642,537 |
def test_translate_six_frames(seq_record):
"""
Given a Biopython sequence record with a DNA (or RNA?) sequence,
translate into amino acid (protein) sequences in six frames.
Returns translations as list of strings.
"""
translation_list = []
for strand, nuc in [(+1, seq_record.seq), (-1, seq_record.... | ce230ee2d8c48d55b269b89e828782456389fc39 | 3,642,538 |
import math
import tokenize
def from_sequence(seq, partition_size=None, npartitions=None):
""" Create dask from Python sequence
This sequence should be relatively small in memory. Dask Bag works
best when it handles loading your data itself. Commonly we load a
sequence of filenames into a Bag and t... | d408f73211af6713f5bf621daf262d3d217419a1 | 3,642,539 |
import os
def smooth_trajectory(
df,
bodyparts,
filter_window=3,
order=1,
deriv=0,
save=False,
output_filename=None,
destfolder=None,
):
"""
Smooths the input data which is a multiindex pandas array generated by DeepLabCut as a result of analyzing a video.
Parameters
-... | aef633d09e0e22de662ddd5fb79f57d8fd56291f | 3,642,540 |
def _get_instances(consul_host, user):
"""Get all deployed component instances for a given user
Sourced from multiple places to ensure we get a complete list of all
component instances no matter what state they are in.
Args
----
consul_host: (string) host string of Consul
user: (string) us... | fa8b85d0c917b20676b74b2123d00f0d4dab41f5 | 3,642,541 |
from typing import Sequence
import glob
async def pool_help(p: 'Player', c: Messageable, msg: Sequence[str]) -> str:
"""Show information of all documented pool commands the player can access."""
prefix = glob.config.command_prefix
cmds = []
for cmd in pool_commands.commands:
if not cmd.doc or... | a21f894585995cfc80717c301906da9634641b30 | 3,642,542 |
def filter_params(params):
"""Filter the dictionary of params for a Bountysource account.
This is so that the Bountysource access token doesn't float
around in a user_info hash (considering nothing else does that).
"""
whitelist = ['id', 'display_name', 'first_name', 'last_name', 'email', 'avatar_ur... | d471ecfa413f6a6821202f14a2506a89e55353b2 | 3,642,543 |
from typing import Counter
def build_vocab(tokens, glove_vocab, min_freq):
""" build vocab from tokens and glove words. """
counter = Counter(t for t in tokens)
# if min_freq > 0, use min_freq, otherwise keep all glove words
if min_freq > 0:
v = sorted([t for t in counter if counter.get(t) >= ... | 797718d6c5d91ac1318b318ca0c254903383304a | 3,642,544 |
def assert_array_approx_equal(x, y, decimal=6, err_msg='', verbose=True):
"""
Checks the equality of two masked arrays, up to given number odecimals.
The equality is checked elementwise.
"""
def compare(x, y):
"Returns the result of the loose comparison between x and y)."
return ap... | 1551ef5b723718644805901fdd041594900cffd2 | 3,642,545 |
def to_bits_string(value: int) -> str:
"""Converts unsigned value to a bit string with _ separators every nibble."""
if value < 0:
raise ValueError(f'Value is not unsigned: {value!r}')
bits = bin(value)[2:]
rev = bits[::-1]
pieces = []
i = 0
while i < len(rev):
pieces.append(rev[i:i + 4])
i +=... | 07dea253378686a1c65c97fad3d0b706e02335c4 | 3,642,546 |
import collections
def comp_days_centered(ndays, offset=0):
"""Return days for pre/onset/post composites centered on onset.
Parameters
----------
ndays : int
Number of days to average in each composite.
offset : int, optional
Number of offset days between pre/onset and onset/post
... | afe62411e5540c9088e929ecc502994a66a4d272 | 3,642,547 |
import os
def createDatabase(name: str) -> bool:
"""
Creates a database in the format of python. If spaces are in the name, it will be cut off through trim(). Returns true if the database is successfully created.
>>> import coconut
#The database format must always be python, it still supports if name ... | 723be430b04c48536423cb8d825af591b9ddf9ce | 3,642,548 |
def linreg_fit_bayes(X, y, **kwargs):
"""
Fit a Bayesian linear regression model.
This is a port of linregFit.m from pmtk3.
:param X: N*D design matrix
:param y: N*1 response vector
"""
pp = preprocessor_create(add_ones=True, standardize_X=False) # default
prior = kwargs['prior'] if '... | 0ba43ff80a4dbc96a8111beadb3efcb7adb7c8eb | 3,642,549 |
def getrv(objwave, objflam, refwave, refflam, maxrv=[-200.,200.], waverange=[-np.inf,np.inf]):
"""
Calculates the rv shift of an object relative to some reference spectrum.
Inputs:
objwave - obj wavelengths, 1d array
objflam - obj flux, 1d array
refwave - ref wavelengths, 1d arr... | 4bf9bea90da74476e38e465d142fa83092e5c3c7 | 3,642,550 |
def ping(host):
"""
Returns True if host (str) responds to a ping request.
Remember that some hosts may not respond to a ping request even if the host name is valid.
"""
# Ping parameters as function of OS
ping_param = "-n 1" if system_name().lower()=="windows" else "-c 1"
# Pinging
re... | 1d19f5f01593099c5a534c0afa4d7bde85ba9d47 | 3,642,551 |
from typing import Counter
def remove_unpopulated_classes(_df, target_column, threshold):
"""
Removes any row of the df for which the label in target_column appears less
than threshold times in the whole frame (not enough populated classes)
:param df: The dataframe to filter
:param target_column: ... | 2ed31cfd3883a3856501dabff935028824141181 | 3,642,552 |
def get_longest_substrings(full_strings):
"""Return a dict of top substrings with hits from a given list of strings.
Args:
full_strings (list[str]): List of strings to test against each other.
Returns:
dict: substrings with their respective frequencies in full_strings.
"""
combos =... | 1eed90129d286988c0ff7e5e5e1229bf871b48bd | 3,642,553 |
def num_weekdays():
"""
Creates a function which returns the number of weekdays in a pandas.Period, typically for use as the average_weight parameter for other functions.
Returns:
callable: Function accepting a single parameter of type pandas.Period and returning the number of weekdays within this
... | bbcb2f8eca0398d46d72cc784f6ec1575159e36d | 3,642,554 |
import os
def reader_from_file(load_dir: str, **kwargs):
"""
Load a reader from a checkpoint.
Args:
load_dir: folder containing the reader being loaded.
Returns: a reader.
"""
shared_resources = create_shared_resources()
shared_resources.load(os.path.join(load_dir, "shared_resour... | 810cd414b99e289f989555b73597e511dfddea1b | 3,642,555 |
import inspect
def add_special_param_to_dependency(
*,
dependency_param: inspect.Parameter,
dependant: Dependant,
) -> bool:
"""Check if param is non field object that should be passed into callable.
Arguments:
dependency_param: param that should be checked.
dependant: dependency ... | d4fa82c6fca8d79ca8b19e8b2aa3447ad38dbd48 | 3,642,556 |
import torch
def mtask_forone_advacc(val_loader, model, criterion, task_name, args, info, epoch=0, writer=None,
comet=None, test_flag=False, test_vis=False, norm='Linf'):
"""
NOTE: test_flag is for the case when we are testing for multiple models, need to return something to be able to... | 17b980f93ff596b0f1c694bcef533ba5a95e09da | 3,642,557 |
from typing import Dict
async def ga4gh_info(host: str) -> Dict:
"""Construct the `Beacon` app information dict in GA4GH Discovery format.
:return beacon_info: A dict that contain information about the ``Beacon`` endpoint.
"""
beacon_info = {
# TO DO implement some fallback mechanism for ID
... | ceb223ff97313bcd0a15b39b3ecf1afa5c16ac8b | 3,642,558 |
def Random_Forest_Classifier_Circoscrizione(X, y, num_features, cat_features):
"""
Funzione che crea, fitta, testa e ritorna una pipeline con il RFC regressor,
(questa volta in riferimento al problema della classificazione di circoscrizioni)
con alcune caratterstiche autoevidenti da codice
Input: X ... | a23253d8fcb724dc3456c7e3506cd2ecf975ba0f | 3,642,559 |
def convert_data_set(data_set, specific_character_set):
""" Convert a DICOM data set to its NIfTI+JSON representation.
"""
result = {}
if odil.registry.SpecificCharacterSet in data_set:
specific_character_set = data_set[odil.registry.SpecificCharacterSet]
for tag, element in data_set.items(... | 68d9eaa54ba244b5b1c31e0d4ffb0af82b564174 | 3,642,560 |
import math
def calc_distance(
p1: Location,
p2: Location
) -> float:
"""
Args:
p1 (Location): planet 1 of interest
p2 (Location): planet 1 of interest
"""
if p1.coords.galaxy != p1.coords.galaxy:
distance = 20000 * math.fabs(p2.coords.galaxy - p1.coords.plane... | 725d7401fee19925b8b154495dc17368b19534fc | 3,642,561 |
def reset_noise_model():
"""Return test reset noise model"""
noise_model = NoiseModel()
error1 = thermal_relaxation_error(50, 50, 0.1)
noise_model.add_all_qubit_quantum_error(error1, ['u1', 'u2', 'u3'])
error2 = error1.tensor(error1)
noise_model.add_all_qubit_quantum_error(error2, ['cx'])
re... | 967ce6da9328f4ed4635d72f67036befde661bcb | 3,642,562 |
def parse_to_timestamp(dt_string):
"""Attempts to parse to Timestamp.
Parameters
----------
dt_string: str
Returns
-------
pandas.Timestamp
Raises
------
ValueError
If the string cannot be parsed to timestamp, or parses to null
"""
timestamp = pd.Timestamp(dt_s... | 766a1028b97e3a5c96430c9fcc5da9610315767a | 3,642,563 |
def __factor(score, items_sum, item_count):
"""Helper method for the pearson correlation coefficient algorithm."""
return score - items_sum/item_count | 2f92b4a5be4375e3083ace9b3855a170f7372460 | 3,642,564 |
from typing import Callable
from typing import Tuple
def cross_validate(estimator: BaseEstimator, X: np.ndarray, y: np.ndarray,
scoring: Callable[[np.ndarray, np.ndarray, ...], float], cv: int = 5) -> Tuple[float, float]:
"""
Evaluate metric by cross-validation for given estimator
Para... | 2d656171a2043cdc7fd07ad199c6e0598de43900 | 3,642,565 |
from pathlib import Path
import sys
def get_img_path() -> Path:
"""
Gets the path of the Mac installation image from the command line
arguments. Fails with an error if the argument is not present or the given
file doesn't exist.
"""
args = sys.argv
if len(args) < 2:
sys.exit(
... | 2ba4ac7f7954cbe2ed76824da41a13b8e6d0b4d9 | 3,642,566 |
def global_info(request):
"""存放用户,会话信息等."""
loginUser = request.session.get('login_username', None)
if loginUser is not None:
user = users.objects.get(username=loginUser)
# audit_users_list_info = WorkflowAuditSetting.objects.filter().values('audit_users').distinct()
audit_users_list... | 12ac1b296fed2a89fbefd8630da00c585e531e8d | 3,642,567 |
def arcsech(val):
"""Inverse hyperbolic secant"""
return np.arccosh(1. / val) | e1a90e1dec3ad7a2e427dc0e93421fd9b9f2b061 | 3,642,568 |
def addEachAtomAutocorrelationMeasures(coordinates, numAtoms):
"""
Computes sum ri*rj, and ri = coords for a single trajectory. Results are stored in different array indexes for different atoms.
"""
rirj = np.zeros((1, 3*numAtoms), dtype=np.float64)
ri = np.zeros((1, 3*numAtoms), dtype=np.float6... | 7413cad78c159af961784f7d2d221ea16c9c9c32 | 3,642,569 |
def api_posts_suggest(request):
"""サジェスト候補の記事をJSONで返す。"""
keyword = request.GET.get('keyword')
if keyword:
post_list = [{'pk': post.pk, 'title': post.title} for post in Post.objects.filter(title__icontains=keyword)]
else:
post_list = []
return JsonResponse({'post_list': post_list}) | 328ec626a6ed477b29ff7f31c82321643a551004 | 3,642,570 |
import os
import configparser
def parse_config(args): # pylint: disable=R0912
"""parses the gitconfig file."""
configpath = os.path.join(HOME, ".gitconfig_2")
# config = configobj.ConfigObj(configpath, interpolation=None, indent_type="\t")
config = configparser.ConfigParser(interpolation=None)
co... | a1fdb77939e7b9092226e8e631085cfbf90bba07 | 3,642,571 |
from os.path import expanduser
import configparser
def _get_config_from_ini_file(f):
"""Load params from the specified filename and return the params as a
dictionary"""
filename = expanduser(f)
_log.debug('Loading parms from {0}'.format(filename))
config = configparser.ConfigParser()
config... | 94c99efdc38e75ed03ced9822271551b3343e8c3 | 3,642,572 |
from typing import Tuple
from typing import List
def read_task_values(task_result: TaskResult) -> Tuple[bool, str, List[float], int]:
"""Reads unitary and federated accuracy from results.json.
Args:
fname (str): Path to results.json file containing required fields.
Example:
>>> print(rea... | 3b562709492c4bfad834236aba1ed97ee3dcc393 | 3,642,573 |
def get_two_dots(full=1):
""" return all posible simple two-dots """
bg= bottomGates()
two_dots = [dict({'gates':bg[0:3]+bg[2:5]})] # two dot case
for td in two_dots:
td['name'] = '-'.join(td['gates'])
return two_dots | 3529e4b6f1056930f0cc864d86ebe8ec5bfbd9b6 | 3,642,574 |
def read_values_of_line(line):
"""Read values in line. Line is splitted by INPUT_FILE_VALUE_DELIMITER."""
if INPUT_FILE_VALUE_DELIMITER == INPUT_FILE_DECIMAL_DELIMITER:
exit_on_error(f"Input file value delimiter and decimal delimiter are equal. Please set INPUT_FILE_VALUE_DELIMITER and INPUT_FILE_DECIMA... | 5450211b5aa10bbf7cca208ddce511b688abeb85 | 3,642,575 |
def find_allergens(ingredients):
"""Return ingredients with cooresponding allergen."""
by_allergens_count = sorted(ingredients, key=lambda i: len(ingredients[i]))
for ingredient in by_allergens_count:
if len(ingredients[ingredient]) == 1:
for other_ingredient, allergens in ingredients.it... | b5fde42cae0138f3bd819eb60629bb2d7ddf2f38 | 3,642,576 |
def send_calendar_events():
"""Sends calendar events."""
error_msg = None
try:
with benchmark("Send calendar events"):
builder = calendar_event_builder.CalendarEventBuilder()
builder.build_cycle_tasks()
sync = calendar_event_sync.CalendarEventsSync()
sync.sync_cycle_tasks_events()
ex... | 501941c968e67178cd2f1d7c6eac293e1617e4a5 | 3,642,577 |
import os
import json
def custom_precision(labels: np.array, predictions: np.array, exp_path: str, exp_name: str):
"""
Calculate custom precision value.
Parameters
----------
exp_name : str
experiment name
exp_path : str
path to experiment folder
labels : np.array
pred... | 8d699f48efd762f3d010e22d964ed3c342425589 | 3,642,578 |
import os
def detect_or_create_config(config_file, output_root, theseargs,
newname=None, logger=None):
""" return path to config file, or die trying.
if a config file exists, just return the path. If not,
create it using "make_riboSeed_config.py"
"""
assert logger is n... | 75167be82d65014749354697fdd4a7c42689ed0a | 3,642,579 |
def gaussian(x, p):
"""
Gaussian function
@param x : variable
@param p : parameters [height, center, sigma]
"""
return p[0] * (1/np.sqrt(2*pi*(p[2]**2))) * np.exp(-(x-p[1])**2/(2*p[2]**2)) | 1a42fabe572d9be2794ccf6e06c8ba2c0cc162fc | 3,642,580 |
def get_exploration_ids_subscribed_to(user_id):
"""Returns a list with ids of all explorations that the given user
subscribes to.
WARNING: Callers of this function should ensure that the user_id is valid.
Args:
user_id: str. The user ID of the subscriber.
Returns:
list(str). IDs o... | 2d8ff3570705ffd59fbf5a83ae23a4b07f49c6a7 | 3,642,581 |
def generate_trials(olh_samples: np.array, roi_space: Space) -> list[dict]:
"""
Generates trials from the given normalized orthogonal Latin hypercube samples
Parameters
----------
olh_samples: `numpy.array`
Samples from the orthogonal Latin hypercube
roi_space: orion.algo.space.Space
... | db58954fffc4b4dfdf57a43eb4b41bee4b87fb33 | 3,642,582 |
def check_all_flash(matrix_2d):
"""
Check if all octopuses flashed.
:param matrix_2d: 2D matrix
:return: Boolean
"""
for line in matrix_2d:
for digit in line:
if digit != 0:
return True
return False | 9dca0174cd0272773e9b9330977bd3fac86f413a | 3,642,583 |
import os
import torch
def train(request, pretrained):
"""
Train a model, and save it to disk.
"""
if pretrained:
return dash.no_update
dataset = get_dataset(request["dataset_name"])
train_set = dataset["train_set"]
val_set = dataset["val_set"]
lake_set = dataset["lake_set"]
... | 82126fcc69719f43b041fe3e1620af54ffd615ad | 3,642,584 |
def cache_get(cache, key, fcn, force=False):
"""Get key from cache, or compute one."""
if cache is None:
cache = {}
if force or (key not in cache):
cache[key] = fcn()
return cache[key] | b358bf01dc657d8cd983830d18ef5a85a48d69ec | 3,642,585 |
def _BreadthFirstSearch(to_visit, children, visited_key=lambda x: x):
"""Runs breadth first search starting from the nodes in |to_visit|
Args:
to_visit: the starting nodes
children: a function which takes a node and returns the nodes adjacent to it
visited_key: a function for deduplicating node visits.... | 1c7153f61af81bb4bd9a06e0213bfcee4aab5cb8 | 3,642,586 |
def get_receptor_from_receptor_ligand_model(receptor_ligand_model):
"""
This function obtains the name of receptor based on receptor_ligand_model
Example of input: compl_ns3pro_dm_0_-_NuBBE_485_obabel_3D+----+20
"""
separator_model = get_separator_filename_mode()
separator_receptor = "_-_"
s... | 58b83ad160181bb04c533feb7fa3d37de44303ef | 3,642,587 |
import tokenize
def build_model():
"""
Selects the best model with optimal parameters
"""
pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('svd', TruncatedSVD()),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassifier(RandomForestClassifier(c... | 99aea3019fd55b84f7252e0c72cc7bf2bdb8d4e6 | 3,642,588 |
import copy
def monthly_expenses(costs, saleprice, propvalue, boyprincipal, rent):
"""Calculate monthly expenses
costs list of MonthlyCost objects
saleprice sale price of the property
propvalue actual value of the property
boyprincipal principal at beginning of year to ca... | 92887f624ce8d87d2f787087f6bb23f80c8186c7 | 3,642,589 |
def get_spitfire_template_class(prefer_c_extension=True):
"""Returns an appropriate SpitfireTemplate class.
Args:
prefer_c_extension: If set True and _template loaded properly, use the
C extension's baseclass implementation.
Returns:
A SpitfireTemplate class with an appropriate base cl... | f5e4c8e285d070b3b0c5716335fef42aef57e845 | 3,642,590 |
def _create_player_points(
pool: pd.DataFrame,
teams: np.ndarray,
n_iterations: int,
n_teams: int,
n_players: int,
team_points: np.ndarray
) -> np.ndarray:
"""Calculates playerpoints
Args:
pool (pd.DataFrame): the player pool
statscols... | c6b7d55ce5041552a113436faf450ca96c84a15e | 3,642,591 |
def get_SolverSettings(instance):
""" get solver settings """
instance.sSolver = ""
instance.dicPyomoOption = {}
instance.dicSolverOption = {}
file_setting = "../Input/1_model_config/01_SolverConfig.csv"
dt_data = genfromtxt(file_setting, dtype = str, skip_header=0, delimiter=',')
... | aa9a1299d3a1a1ea7c3f2315117b097641ed22be | 3,642,592 |
import signal
def demod_from_array(mod_array, faraday_sampling_rate = 5e6, start_time = 0, end_time = 'max', reference_frequency = 736089.8, reference_phase_deg = 0, lowpas_freq = 10000, plot_demod = False, decimate_factor = 4, time_stamp = '', label = '', save = False):
"""
Sweet lord above this function washes t... | 7661ba4dbb39a5a3bd2336e386605b1361a6b287 | 3,642,593 |
import numpy
import os
def find_many_files_gridrad(
top_directory_name, radar_field_names, radar_heights_m_agl,
start_time_unix_sec, end_time_unix_sec, one_file_per_time_step=True,
raise_error_if_all_missing=True):
"""Finds many files with storm-centered images from GridRad data.
T = ... | 0e240dbcd5a4f1a2edf129fd48c692fb4ac76e85 | 3,642,594 |
import click
def cli_num_postproc_workers(
usage_help: str = "Number of workers to post-process the network output.",
default: int = 0,
) -> callable:
"""Enables --num-postproc-workers option for cli."""
return click.option(
"--num-postproc-workers",
help=add_default_to_usage_help(usag... | a34c1f75e26bfe8aca9569dd7e3102d20315deab | 3,642,595 |
import json
def create_cluster(redshift, iam, ec2, cluster_config, wait_status=False):
""" Create publicly available redshift cluster per provided cluster configuration.
:param redshift: boto.redshift object to use
:param iam: boto.iam object to use
:param ec2: boto.ec2 object to use
:param clust... | 2f93e8bcf3c2f9a43a370fb34f513df56dc312e7 | 3,642,596 |
def index():
""" Application entry point. """
return render_template("index.html") | fa84b6a2f6ae8c0ef7f976a6e58419913e8cbc1a | 3,642,597 |
def add_filepath(parent, filename, definition=''):
"""returns the path to filename under `parent`."""
if filename is None:
raise ValueError("filename cannot be None")
# FIXME implementation specifics! only works with FileSystemDatabase
parent_path = parent._repr
file_path = parent_path / f... | 615dc918a01c4c7f5dc216959f5b3ebe7e1a7b38 | 3,642,598 |
from typing import Callable
def silhouette_to_prediction_function(
silhouette: np.ndarray
) -> Callable[[np.ndarray], bool]:
"""
Takes a silhouette and returns a function.
The returned function takes x,y point and
returns wether it is in the silhouette.
Args:
silhouette:
Re... | 802bf4dc83739fff171178f0b2b95e6900c1f725 | 3,642,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.