content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import constants as c
import cPickle
def get_word_prob():
"""Returns the probabilities of all the words in the mechanical turk video labels.
"""
data = cPickle.load(open(c.datafile)) # Read in the words from the labels
wordcount = dict()
totalcount = 0
for label in data:
for word in la... | c9f137ad4e844ff3cea3c6f9b1d64e9422359b79 | 22,965 |
def angDistance(ra, dec, df, raCol='fieldRA', decCol='fieldDec'):
"""
"""
df['dist'] = angSep(ra, dec, df[raCol], df[decCol])
idx = df.dist.idxmin()
rval = df.loc[idx]
df.drop('dist', axis=1, inplace=True)
return rval | 9e88711ff33a7ac1a223608ea5441e1cfdbb7a01 | 22,966 |
def offer_in_influencing_offers(offerId, influencing_offers):
"""
Find if a passed offerId is in the influencing_offers list
Parameters
----------
offerId: Offer Id from portfolio dataframe.
influencing_offers : List of offers found for a customer
Returns
-------
1 if of... | 81c4a8bcb7432222a1fc5175449192681002539c | 22,967 |
def identity_block(filters, stage, block):
"""The identity block is the block that has no conv layer at shortcut.
# Arguments
filters: integer, used for first and second conv layers, third conv layer double this value
stage: integer, current stage label, used for generating layer names
b... | 43eb5d56a83d24db9bd60aabf1e7dbd601a093cb | 22,969 |
import psutil
def filebeat_service_running():
"""
Checks if the filebeat service is currently running on the OS.
:return: True if filebeat service detected and running, False otherwise.
"""
result = False
try:
filebeat_service = psutil.win_service_get('filebeat')
filebeat_servi... | 51f9bc865b4f7d2de760fcc6952755b5c7c9106a | 22,970 |
def unhandled_request_message(request, cassette):
"""Generate exception for unhandled requests."""
return UNHANDLED_REQUEST_EXCEPTION.format(
url=request.url, cassette_file_path=cassette.cassette_name,
cassette_record_mode=cassette.record_mode,
cassette_match_options=cassette.match_optio... | dcbfec51a88d3ad62395f48c7c046400177c07fd | 22,971 |
from django.contrib.auth import logout as auth_logout
def logout(request):
"""
Logs out the user and displays 'You are logged out' message.
"""
if request.method == 'GET':
return _new_api_403()
auth_logout(request) | 7e975fdd68295e893d8f14321f722e941833b872 | 22,972 |
def compara_dv(cpf, primeiro_dv, segundo_dv):
"""Valida se dígitos verificadores calculados são iguais aos inseridos."""
return "válido" if primeiro_dv == int(cpf[9]) and segundo_dv == int(cpf[10]) else "inválido" | 4b1794f466ce8c00e91c8c5f281996ea262591f8 | 22,973 |
def write_file(file_name, data, line_length):
""" Writes the results to a text file using a name based on file_name
input: string, list
returns: int
"""
pos = file_name.rfind('.')
fn_o = file_name[:pos] + '.OUT' + file_name[pos:]
f = open(fn_o, "w")
for fsn, sequence in data:
... | 0ad1b25106a6c9120289e8d55caafbebf475f9d5 | 22,974 |
def handle_duplicates(df, cutoff=5, agg_source_col='multiple'):
"""Aggregates duplicate measurements in a DataFrame.
Parameters
----------
df : pandas DataFrame
DataFrame with required columns: 'smiles', 'solvent', 'peakwavs_max'
cutoff : int
Wavelength cutoff in nm. Duplicate meas... | 0f37ba0256d3a73ebc86d628b65d054c049a7456 | 22,975 |
def splitData(features, target, trainFraction=0.25):
"""
Split the data into test and train data
Inputs:
> features: the model feature data (DataFrame)
> target: the target data (Series)
> trainFraction (0.25 by default): fraction of events to use for training
Outputs:
... | b3dba6e5b1082062995c4272c7e42fe24c7c8712 | 22,976 |
def poisson_moment( k, n):
"""
returns the moment of x**n with expectation value k
CURRENTLY A SET OF HARD CODED EXPRESSIONS! VERY FRAGILE!
--> would be *much* better if we could do this algorithmically
"""
if n==0:
return 1
elif n==1:
return k
elif n==2:
ret... | d2af07d550b0cf6ac9a410296b4ec12c78cc1505 | 22,977 |
def drug_encoder(input_smiles):
"""
Drug Encoder
Args:
input_smiles: input drug sequence.
Returns:
v_d: padded drug sequence.
temp_mask_d: masked drug sequence.
"""
temp_d = drug_bpe.process_line(input_smiles).split()
try:
idx_d = np.asarray([drug_idx[i] for... | 79f0e391e5cd72f981b9580d105ac41cc53d5f63 | 22,978 |
def optimise_acqu_func_mledr(acqu_func, bounds, X_ob, func_gradient=True, gridSize=10000, n_start=5):
"""
Optimise acquisition function built on GP- model with learning dr
:param acqu_func: acquisition function
:param bounds: input space bounds
:param X_ob: observed input data
:param func_gradi... | 8a59f9f3c4b7b55a4ae56da93eed1c9820363ef6 | 22,980 |
def get_path_from_pc_name(pc_name):
"""Find out path of a template
Parameters
----------
pc_name : string
Name of template.
Returns
-------
tplPath : string
Path of template
"""
tplPath = pc_name + '.json'
# change path to template if in subdir
for i in p... | f2ee20f9f8728d672bb0658e80f9f04f2c9f0c11 | 22,981 |
def eq(*, alpha=None, omega):
"""Define dyadic comparison function equal to.
Dyadic case:
3 = 2 3 4
0 1 0
"""
return int(alpha == omega) | 1f8d826711e9d24a3b05de5f42a99b36744f4f38 | 22,982 |
import calendar
def generate_days(year):
"""Generates all tuples (YYYY, MM, DD) of days in a year
"""
cal = calendar.Calendar()
days = []
for m in range(1,13):
days.extend(list(cal.itermonthdays3(year, m)))
days = [d for d in set(days) if d[0] == year]
days.sort()
return days | 6d87910572957d21c9d5df668dfb5f2d02627817 | 22,983 |
import requests
import json
def nounClassifier(word):
"""Classifies noun as actor o object
Parameters
----------
word : str
Lematized noun to be classified (case-insensitive).
"""
word = word.lower()
response_raw = requests.get(
f"{API_URL}senses/search?lemma={word}&&&par... | aef33226b956a0d7b9fcb8b1b751d5a11e9136c4 | 22,984 |
def svn_repos_post_lock_hook(*args):
"""svn_repos_post_lock_hook(svn_repos_t repos, apr_pool_t pool) -> char"""
return _repos.svn_repos_post_lock_hook(*args) | 56bdafc41fa76d2a4d2f5e6b213fa86e8ca9416b | 22,985 |
def libdmtx_function(fname, restype, *args):
"""Returns a foreign function exported by `libdmtx`.
Args:
fname (:obj:`str`): Name of the exported function as string.
restype (:obj:): Return type - one of the `ctypes` primitive C data
types.
*args: Arguments - a sequence of `ctype... | ed5f39d435aae453a0aeb8855fc0a21e1db334b8 | 22,986 |
from typing import Any
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: ConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
control_unit: ControlUnit = hass.data[DOMAIN][config_entry.entry_id]
diag: dict[str, Any] = {
"config": async_re... | ac4495e49745f9211a32cfaf3a15c03203282e50 | 22,987 |
async def instance_set_name_inurl(cluster_id: str, vm_uuid: str, new_name: str):
""" Set Instance (VM/Template) Name """
try:
try:
session = create_session(
_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()
)
except KeyError as key_error:
... | 3c942af4a57dad0beaef6f629d4b7900421eadbd | 22,988 |
def key_released(key):
"""
Takes a key, that's either a keycode or a character,
and says if it was released this frame.
"""
keycode = _to_keycode(key)
return (keycode not in current_frame_held_buttons) and \
(keycode in last_frame_held_buttons) | 4cb66ba924aae909f20db59eb2aef0ccc77d2860 | 22,989 |
def trim_snakes_old(lcs,ref,Nb,Ne,dat,Mb,Me):
"""Previously found matches can cause problems if they are not optimal.
In such a case sticking with the matches as found prevents subsequent
more advanced diff routines from recovering from an early sub-optimal
choice. To counter this all snakes and pseudo... | 0bf078ca2198bcf0c25e8a925bd0c096cafa4797 | 22,990 |
import asyncio
async def start(actual_coroutine):
"""
Start the testing coroutine and wait 1 second for it to complete.
:raises asyncio.CancelledError when the coroutine fails to finish its work
in 1 second.
:returns: the return value of the actual_coroutine.
:rtype: Any
"""
try:
... | 26e3737091ca798dbf8c0f6f2a18a1de4b0ec42b | 22,991 |
def get_node(path):
"""Returns a :class:`Node` instance at ``path`` (relative to the current site) or ``None``."""
try:
current_site = Site.objects.get_current()
except Site.DoesNotExist:
current_site = None
trailing_slash = False
if path[-1] == '/':
trailing_slash = True
try:
node, subpath = Node.obj... | 516460d05df4139ce5354f2c3ef5cf948d4b8213 | 22,992 |
from datetime import datetime
def new_post(blog_id, username, password, post, publish):
"""
metaWeblog.newPost(blog_id, username, password, post, publish)
=> post_id
"""
user = authenticate(username, password, 'zinnia.add_entry')
if post.get('dateCreated'):
creation_date = datetime.str... | 4bdd8464458bef5797854776222a178e891d6346 | 22,993 |
def upload(userid, filedata):
"""
Creates a preview-size copy of an uploaded image file for a new avatar
selection file.
"""
if filedata:
media_item = media.make_resized_media_item(filedata, (600, 500), 'FileType')
orm.UserMediaLink.make_or_replace_link(userid, 'avatar-source', media... | 3ffd3d5a26c35f20e5a3885ca597d8c0182ebc8a | 22,994 |
def time_dconv_bn_nolinear(nb_filter, nb_row, nb_col,
stride=(2, 2), activation="relu"):
"""
Create time convolutional Batch Norm layer in decoders.
Parameters:
---------
filter_num : int
number of filters to use in convolution layer.
row_num : int
number of r... | 016082d3c09388a4ff9f8add5cb84a63a65775e8 | 22,996 |
import random
def ___generate_random_row_major_GM___(i, j, s=None):
"""Make a random row major sparse matrix of shape (i,j) at sparsity=s.
:param i:
:param j:
:param s:
:return:
"""
if s is None:
s = random.uniform(0, 0.1)
if s < 0.02: s = 0
if rAnk == mAster_rank:
... | 59eca064d240dc03fdbdc8d1807dbbbb996239d4 | 22,997 |
from typing import Tuple
from typing import Any
def parse_tuple(value: Tuple[Any, ...]) -> RGBA:
"""
Parse a tuple or list as a color.
"""
if len(value) == 3:
r, g, b = [parse_color_value(v) for v in value]
return RGBA(r, g, b, None)
elif len(value) == 4:
r, g, b = [parse_c... | 0766bd7189c5e0cd383d94944dacecd5fbef1320 | 22,998 |
import pathlib
from typing import Optional
def find_path(
start_path: pathlib.Path = pathlib.Path("."),
) -> Optional[pathlib.Path]:
"""Traverse the file system looking for the config file .craftier.ini.
It will stop earlier at the user's home directory, if it encounters a Git or
Mercurial directory,... | 00fbfabc8e0c6dd3c23b190e6278f70af566b25f | 22,999 |
def crop_point_data_to_base_raster(raster_name, raster_directory, csv_file, EPSG_code = 0):
"""
This function create a new csv file cropped to the base raster. It can lower the processing time if your point data is on a significantly larger area than the base raster.
"""
print("ok let me load your datas... | 0392d9633381948ef338c3233ed2f4b81d520678 | 23,000 |
def generate_schedule_report_data(pools_info, pools_allocated_mem):
"""
Generate the schedule report data.
:param pools_info: (dict) The information about the configuration and statistics of the pool participating
in the scheduling.
:param pools_allocated_mem: (dict) The allocated memory of the... | e9fb9f517c1fe29d9f4c867b416969374f4acd36 | 23,001 |
def create_feature_rule_json(device, feature="foo", rule="json"):
"""Creates a Feature/Rule Mapping and Returns the rule."""
feature_obj, _ = ComplianceFeature.objects.get_or_create(slug=feature, name=feature)
rule = ComplianceRule(
feature=feature_obj,
platform=device.platform,
conf... | 985dfccab39c54478ba36f10020779dbd1b6b466 | 23,002 |
def default_sv2_sciencemask():
"""Returns default mask of bits for science targets in SV1 survey.
"""
sciencemask = 0
sciencemask |= sv2_mask["LRG"].mask
sciencemask |= sv2_mask["ELG"].mask
sciencemask |= sv2_mask["QSO"].mask
sciencemask |= sv2_mask["BGS_ANY"].mask
sciencemask |= sv2_mas... | cf6b45d069ab8538350d35ce28d8fae4ed6525b2 | 23,003 |
def solver_softmax(K, R):
"""
K = the number of arms (domains)
R = the sequence of past rewards
"""
softmax = np.zeros(K, dtype=float)
for i, r in R.items():
softmax[i] = np.mean(r)
softmax = np.exp(softmax) / np.exp(softmax).sum()
si = np.random.choice(np.arange(0, K, 1), size... | 3ac8984f70c8594f48b00df4d9b15e69dad416ba | 23,004 |
def mapview(request):
"""Map view."""
context = basecontext(request, 'map')
return render(request, 'map.html', context=context) | 9c03377c3d047b1672c4ac1972e5552ecdc7488a | 23,005 |
def adapt_coastdat_weather_to_pvlib(weather, loc):
"""
Adapt the coastdat weather data sets to the needs of the pvlib.
Parameters
----------
weather : pandas.DataFrame
Coastdat2 weather data set.
loc : pvlib.location.Location
The coordinates of the weather data point.
Retur... | 01a7c4340ed2542bb2fe624d6a02e4c82f3ff984 | 23,006 |
def bprop_distribute(arr, shp, out, dout):
"""Backpropagator for primitive `distribute`."""
return (array_reduce(scalar_add, dout, shape(arr)),
zeros_like(shp)) | 5bfd9f1e6ec3b50e4fd13a3a26466ee57e7f084e | 23,007 |
def ids_to_non_bilu_label_mapping(labelset: LabelSet) -> BiluMappings:
"""Mapping from ids to BILU and non-BILU mapping. This is used to remove the BILU labels to regular labels"""
target_names = list(labelset["ids_to_label"].values())
wo_bilu = [bilu_label.split("-")[-1] for bilu_label in target_names]
... | ed6b42784661a7db693a1ea5ba65e9a1f830a46a | 23,008 |
def generate_input_types():
"""
Define the different input types that are used in the factory
:return: list of items
"""
input_types = ["Angle_irons", "Tubes", "Channels", "Mig_wire", "Argon_gas", "Galvanised_sheets", "Budget_locks",
"Welding_rods", "Body_filler", "Grinding_discs"... | d9e10624daaf5dae92f15512c9b19c47af002139 | 23,009 |
from qharv.inspect.axes_elem_pos import ase_tile as atile
def ase_tile(cell, tmat):
"""Create supercell from primitive cell and tiling matrix
Args:
cell (pyscf.Cell): cell object
tmat (np.array): 3x3 tiling matrix e.g. 2*np.eye(3)
Return:
pyscf.Cell: supercell
"""
try:
except ImportError:
... | d37d5b5d2cab42d10e7495724bd5cba4391c71e4 | 23,010 |
def parse_chat_logs(input_path, user, self):
"""
Get messages from a person, or between that person and yourself.
"self" does not necessarily have to be your name.
Args:
input_path (str): Path to chat log HTML file
user (str): Full name of person, as appears in Messenger app
se... | b0d9a19d7f27589dac7757539c9d1595150ec0f4 | 23,012 |
def pressure_correction(pressure, rigidity):
"""
function to get pressure correction factors, given a pressure time series and rigidity value for the station
:param pressure: time series of pressure values over the time of the data observations
:param rigidity: cut-off rigidity of the station making the... | 9a1baeacc7c954f8825dcd279518357534d84a06 | 23,013 |
def prepare_data(song: dict) -> dict:
"""
Prepares song dataa for database insertion to cut down on duplicates
:param song: Song data
:return: The song data
"""
song['artist'] = song['artist'].upper().strip()
song['title'] = song['title'].upper().strip()
return song | f8f8c9a3a0fe510cb3fb2e7d6d5bd361721337e7 | 23,016 |
def com(struct):
"""
Calculates center of mass of the system.
"""
geo_array = struct.get_geo_array()
element_list = struct.geometry['element']
mass = np.array([atomic_masses_iupac2016[atomic_numbers[x]]
for x in element_list]).reshape(-1)
total = np.sum(mass)
com = n... | 239ff2d153739c80f6a4f723fc8060d7418a4862 | 23,017 |
def distance_matrix(values, metric):
"""Generate a matrix of distances based on the `metric` calculation.
:param values: list of sequences, e.g. list of strings, list of tuples
:param metric: function (value, value) -> number between 0.0 and 1.0"""
matrix = []
progress = ProgressTracker(len(values))... | 339adc59d3b6198d9bc55d7c6504c5489e7770b2 | 23,018 |
import struct
def _Pack(content, offset, format_string, values):
"""Pack values to the content at the offset.
Args:
content: String to be packed.
offset: Offset from the beginning of the file.
format_string: Format string of struct module.
values: Values to struct.pack.
Returns:
Updated con... | c164298e1e8963b20cfabcd38f3d8e44722751ae | 23,019 |
import math
def get_rotation_matrix(orientation):
"""
Get the rotation matrix for a rotation around the x axis of n radians
Args:
- (float) orientation in radian
Return:
- (np.array) rotation matrix for a rotation around the x axis
"""
rotation_matrix = np.array(
[[1, ... | 0f795c974599382039106f28f20c4c48cdd77bb6 | 23,020 |
def machinesize(humansize):
"""convert human-size string to machine-size"""
if humansize == UNKNOWN_SIZE:
return 0
try:
size_str, size_unit = humansize.split(" ")
except AttributeError:
return float(humansize)
unit_converter = {
'Byte': 0, 'Bytes': 0, 'kB': 1, 'MB': 2... | 8694d6ac3b2aa1b6624d2fea7a8ce4544f713c36 | 23,021 |
import networkx
import torch
def generate_erdos_renyi_netx(p, N):
""" Generate random Erdos Renyi graph """
g = networkx.erdos_renyi_graph(N, p)
W = networkx.adjacency_matrix(g).todense()
return g, torch.as_tensor(W, dtype=torch.float) | fbb8e293a1b35958301c2e376a03c30012b0c33b | 23,022 |
def kmc_algorithm(process_list):
"""
:param rate_list: List with all the computed rates for all the neighbours for all the centers
:param process_list: List of elements dict(center, process, new molecule).
The indexes of each rate in rate_list have the same index that the associated process in
proce... | 5812498f83eede2f6de6f669bd87312705c13be3 | 23,023 |
def __matlab_round(x: float = None) -> int:
"""Workaround to cope the rounding differences between MATLAB and python"""
if x - np.floor(x) < 0.5:
return int(np.floor(x))
else:
return int(np.ceil(x)) | d24298c9c072fc83a531fcd498f81c715accf229 | 23,024 |
def rayleightest(circ_data, dim='time'):
"""Returns the p-value for the Rayleigh test of uniformity
This test is used to identify a non-uniform distribution, i.e. it is
designed for detecting an unimodal deviation from uniformity. More
precisely, it assumes the following hypotheses:
- H0 (null hyp... | 74342adefe71f1e3193d52af6f716f20c538848f | 23,025 |
from typing import Union
from pathlib import Path
import yaml
def load_cfg(cfg_file: Union[str, Path]) -> dict:
"""Load the PCC algs config file in YAML format with custom tag
!join.
Parameters
----------
cfg_file : `Union[str, Path]`
The YAML config file.
Returns
-------
`d... | c9137c5052adf8fa62913c352df2bfe9e79fc7ce | 23,026 |
def pdist_triu(x, f=None):
"""Pairwise distance.
Arguments:
x: A set of points.
shape=(n,d)
f (optional): A kernel function that computes the similarity
or dissimilarity between two vectors. The function must
accept two matrices with shape=(m,d).
Returns... | 19d8acb0b38b8dcb6b5b99a1bf7691e055c2ef6d | 23,027 |
def get_model_defaults(cls):
"""
This function receives a model class and returns the default values
for the class in the form of a dict.
If the default value is a function, the function will be executed. This is meant for simple functions such as datetime and uuid.
Args:
cls: (obj) : A Mo... | 93c29af27446c558b165159cee4bb41bbb3cad4d | 23,029 |
def add_response_headers(headers=None):
"""This decorator adds the headers passed in to the response"""
headers = headers or {}
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
resp = make_response(f(*args, **kwargs))
h = resp.headers
... | 9f26048dcff6de65d9a25ede6002c955f1551ff5 | 23,030 |
def restore(request: Request, project_id: int) -> JSONResponse: # pylint: disable=invalid-name,redefined-builtin
"""Restore project.
Args:
project_id {int}: project id
Returns:
starlette.responses.JSONResponse
"""
log_request(request, {
'project_id': project_id
})
... | 0316132e42331ec9fe3b5c4ce73c364cc4726e2b | 23,031 |
def _broadcast_arrays(x, y):
"""Broadcast arrays."""
# Cast inputs as numpy arrays
# with nonzero dimension
x = np.atleast_1d(x)
y = np.atleast_1d(y)
# Get shapes
xshape = list(x.shape)
yshape = list(y.shape)
# Get singltons that mimic shapes
xones = [1] * x.ndim
yones = [1... | 8272e17a05803e529295ded70253b4c80615d426 | 23,032 |
from re import M
def Output(primitive_spec):
"""Mark a typespec as output."""
typespec = BuildTypespec(primitive_spec)
typespec.meta.sigdir = M.SignalDir.OUTPUT
return typespec | 737262c1414e7a33480a4512a9441d1b3eef45c8 | 23,033 |
def partitionFromMask(mask):
""" Return the start and end address of the first substring without
wildcards """
for i in range(len(mask)):
if mask[i] == '*':
continue
for j in range(i+1, len(mask)):
if mask[j] == '*':
break
else:
if ... | 1b77f68a223e36e8dc9ec4b70464924d6b1dbe4a | 23,035 |
def mask_to_bias(mask: Array, dtype: jnp.dtype) -> Array:
"""Converts a mask to a bias-like Array suitable for adding to other biases.
Arguments:
mask: <bool> array of arbitrary shape
dtype: jnp.dtype, desired dtype of the returned array
Returns:
bias: <bool> array of the same shape as the input, wi... | 0e74765bde98fba50e224382e57acf35b7e35e55 | 23,037 |
from typing import Union
from typing import Iterable
from typing import Optional
from typing import Dict
def optimize_clustering(
data,
algorithm_names: Union[Iterable, str] = variables_to_optimize.keys(),
algorithm_parameters: Optional[Dict[str, dict]] = None,
random_search: bool = True,
random_s... | 7bf38c317a17c6803a12316eaa3960bb8198d701 | 23,039 |
def sql_fingerprint(query, hide_columns=True):
"""
Simplify a query, taking away exact values and fields selected.
Imperfect but better than super explicit, value-dependent queries.
"""
parsed_query = parse(query)[0]
sql_recursively_simplify(parsed_query, hide_columns=hide_columns)
return s... | 985f9a5afc9a9acddece29535954f25d29580b62 | 23,040 |
def get_account():
"""Return one account and cache account key for future reuse if needed"""
global _account_key
if _account_key:
return _account_key.get()
acc = Account.query().get()
_account_key = acc.key
return acc | 31f424c1c8e642f6c423f3c0e61896be4ad3b080 | 23,041 |
from typing import Sequence
from typing import Optional
import abc
def is_seq_of(
seq: Sequence, expected_type: type, seq_type: Optional[type] = None
) -> bool:
"""Check whether it is a sequence of some type.
Args:
seq (Sequence):
Sequence to be checked.
expected_type (type):
... | 4937a23a91a507a18519109c1b473add0e263ca7 | 23,042 |
def mutate_single_residue(atomgroup, new_residue_name):
"""
Mutates the residue into new_residue_name. The only atoms retained are
the backbone and CB (unless the new residue is GLY). If the original
resname == new_residue_name the residue is left untouched.
"""
resnames = atomgroup.resnam... | 89ea175809fb518d778390867cb7f311343a06cc | 23,043 |
from typing import Dict
from typing import OrderedDict
import warnings
def future_bi_end_f30_base(s: [Dict, OrderedDict]):
"""期货30分钟笔结束"""
v = Factors.Other.value
for f_ in [Freq.F30.value, Freq.F5.value, Freq.F1.value]:
if f_ not in s['级别列表']:
warnings.warn(f"{f_} not in {s['级别列表']},默... | 3a40cf658bf09ddea2347ce190c46f84c7cc1eb2 | 23,044 |
from typing import OrderedDict
def convert_pre_to_021(cfg):
"""Convert config standard 0.20 into 0.21
Revision 0.20 is the original standard, which lacked a revision.
Variables moved from top level to inside item 'variables'.
Ocean Sites nomenclature moved to CF standard vocabulary:
... | 874751b70481f50a1243791677a1c2ad0f354952 | 23,045 |
def get_alerts_alarms_object():
""" helper function to get alert alarms
"""
result = []
# Get query filters, query SystemEvents using event_filters
event_filters, definition_filters = get_query_filters(request.args)
if event_filters is None: # alerts_alarms
alerts_alarms = db.session.q... | 7ab1c25cdaa30be0e70b110d47e7ea807713f404 | 23,046 |
import glob
import pickle
def data_cubes_combine_by_pixel(filepath, gal_name):
"""
Grabs datacubes and combines them by pixel using addition, finding the mean
and the median.
Parameters
----------
filepath : list of str
the data cubes filepath strings to pass to glob.glob
gal_nam... | 1ae269ade8ac00b269fc52d474e038c9e2ca8d92 | 23,047 |
def usdm_bypoint_service(
fmt: SupportedFormats,
):
"""Replaced above."""
return Response(handler(fmt), media_type=MEDIATYPES[fmt]) | 8f957e8778aab81f94d52cbc07a78346f74ac0c2 | 23,048 |
import pandas as pd
def read_geonames(filename):
"""
Parse geonames file to a pandas.DataFrame. File may be downloaded
from http://download.geonames.org/export/dump/; it should be unzipped
and in a "geonames table" format.
"""
return pd.read_csv(filename, **_GEONAMES_PANDAS_PARAMS) | 638fe3c02d61467fa47ee19e20f4f0022c8b57c2 | 23,049 |
def create_property_map(cls, property_map=None):
""" Helper function for creating property maps """
_property_map = None
if property_map:
if callable(property_map):
_property_map = property_map(cls)
else:
_property_map = property_map.copy()
else:
_propert... | b67d0fdcd75c592f3443993f2948a2686e22322d | 23,050 |
import Scientific
import Scientific.IO
import Scientific.IO.NetCDF
def readNetCDF(filename, varName='intensity'):
"""
Reads a netCDF file and returns the varName variable.
"""
ncfile = Scientific.IO.NetCDF.NetCDFFile(filename,"r")
var1 = ncfile.variables[varName]
data = sp.array(var1.getValue... | 887b88f6cef8767be56d4bf828f048a2b7e09606 | 23,051 |
import click
def show(ctx, name_only, cmds, under, fields, format, **kwargs):
"""Show the parameters of a command"""
cmds = cmds or sorted(config.parameters.readonly.keys())
if under:
cmds = [cmd for cmd in cmds if cmd.startswith(under)]
with TablePrinter(fields, format) as tp, Colorer(kwargs)... | 6f4c959662cc75925cae82143913b7f2b7434a7b | 23,052 |
def make_count_set(conds, r):
"""
returns an r session with a new count data set loaded as cds
"""
#r.assign('conds', vectors.StrVector.factor(vectors.StrVector(conds)))
r.assign('conds', vectors.StrVector(conds))
r('''
require('DSS')
cds = newSeqCountSet(count_matrix, conds)
''')
... | 956ad076d1368cc5c0cf16365d6941157db1c664 | 23,053 |
def RunCommand(cmd, timeout_time=None, retry_count=3, return_output=True,
stdin_input=None):
"""Spawn and retry a subprocess to run the given shell command.
Args:
cmd: shell command to run
timeout_time: time in seconds to wait for command to run before aborting.
retry_count: number of ti... | cc1b4421a3a390bfa296faa279df0338985ff851 | 23,054 |
def get_clusters_low_z(min_mass = 10**4, basepath='/lustre/scratch/mqezlou/TNG300-1/output'):
"""Script to write the position of z ~ 0 large mass halos on file """
halos = il.groupcat.loadHalos(basepath, 98, fields=['GroupMass', 'GroupPos','Group_R_Crit200'])
ind = np.where(halos['GroupMass'][:] > min_mas... | 5b868a8be11e109f126ad920b65d67984a7ffdca | 23,055 |
def _serialize_key(key: rsa.RSAPrivateKeyWithSerialization) -> bytes:
"""Return the PEM bytes from an RSA private key"""
return key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()... | f9064c1d7a1143d04e757d5ad3b3d7620e67e233 | 23,057 |
def ldns_key_algo_supported(*args):
"""LDNS buffer."""
return _ldns.ldns_key_algo_supported(*args) | e5184eb314aa315a852bb5bf0fe9b1ae01e4d9fe | 23,058 |
def read_k_bytes(sock, remaining=0):
"""
Read exactly `remaining` bytes from the socket.
Blocks until the required bytes are available and
return the data read as raw bytes. Call to this
function blocks until required bytes are available
in the socket.
Arguments
---------
sock : So... | 3d75eaa43b84ac99ac37b4b1a048f1a6615901b1 | 23,059 |
def total_minutes(data):
"""
Calcula a quantidade total de minutos com base nas palestras
submetidas.
"""
soma = 0
for item in data.keys():
soma += (item*len(data[item]))
return soma | c85f6ac0a1d58b67d1e53ae5ff87b8762e3d050c | 23,060 |
def grid_to_vector(grid, categories):
"""Transform a grid of active classes into a vector of labels.
In case several classes are active at time i, the label is
set to 'overlap'.
See :func:`ChildProject.metrics.segments_to_grid` for a description of grids.
:param grid: a NumPy array of shape ``(n,... | 849c481ecf1dc608d7457875fef9b6f241d53e91 | 23,061 |
import optparse
def standard_script_options(usage, description):
"""Create option parser pre-populated with standard observation script options.
Parameters
----------
usage, description : string
Usage and description strings to be used for script help
Returns
-------
parser : :cl... | 9d16aeb0481f03e5d19955744c7d29b1c42375b3 | 23,062 |
def default_handler(request):
""" The default handler gets invoked if no handler is set for a request """
return alexa.create_response(message=request.get_slot_map()["Text"]) | ae4343c9de86141bb0b112123b9e420bbf1ac5c6 | 23,064 |
def ajax_available_variants_list(request):
"""Return variants filtered by request GET parameters.
Response format is that of a Select2 JS widget.
"""
available_skills = Skill.objects.published().prefetch_related(
'category',
'skill_type__skill_attributes')
queryset = SkillVariant.ob... | 7093352368d975e3d3e663dd2541fc81a89ede0c | 23,065 |
def jaccard2_coef(y_true, y_pred, smooth=SMOOTH):
"""Jaccard squared index coefficient
:param y_true: true label
:type y_true: int
:param y_pred: predicted label
:type y_pred: int or float
:param smooth: smoothing parameter, defaults to SMOOTH
:type smooth: float, optional
:return: Jacc... | dfd480814737a1d725874ec81287948dded3ba2e | 23,066 |
def marginal_density_from_linear_conditional_relationship(
mean1,cov1,cov2g1,Amat,bvec):
"""
Compute the marginal density of P(x2)
Given p(x1) normal with mean and covariance
m1, C1
Given p(x2|x1) normal with mean and covariance
m_2|1=A*x1+b, C_2|1
P(x2) is normal wit... | 3baa69910cd78a02bec5ba1517ca3a8ea189f845 | 23,067 |
def rowcount_fetcher(cursor):
""" Return the rowcount returned by the cursor. """
return cursor.rowcount | 21b30665391aa16d158083ccb37149bd6ec0f548 | 23,068 |
def view_hello_heartbeat(request):
"""Hello to TA2 with no logging. Used for testing"""
# Let's call the TA2!
#
resp_info = ta2_hello()
if not resp_info.success:
return JsonResponse(get_json_error(resp_info.err_msg))
json_str = resp_info.result_obj
# Convert JSON str to python dic... | 736c5b4d9832f16b6bac36abf2c1a6aa3443b768 | 23,070 |
import functools
import contextlib
def with_environment(server_contexts_fn):
"""A decorator for running tests in an environment."""
def decorator_environment(fn):
@functools.wraps(fn)
def wrapper_environment(self):
with contextlib.ExitStack() as stack:
for server_context in server_contexts... | dbd4b435d920a08b97dd2921c534c14ce8d18acb | 23,071 |
import ast
def get_number_of_unpacking_targets_in_for_loops(node: ast.For) -> int:
"""Get the number of unpacking targets in a `for` loop."""
return get_number_of_unpacking_targets(node.target) | 9ce94f93d18e87cddbd2e2bbbfb05b026901c0da | 23,072 |
def dmp_degree(f, u):
"""Returns leading degree of `f` in `x_0` in `K[X]`. """
if dmp_zero_p(f, u):
return -1
else:
return len(f) - 1 | da2df32019d1121c40424893773928225201e584 | 23,073 |
import requests
def fetch_remote_content(url: str) -> Response:
"""
Executes a GET request to an URL.
"""
response = requests.get(url) # automatically generates a Session object.
return response | 0b98315b8acf1f1a4ad7f177ef689af4c6a7ba63 | 23,074 |
def optimization(loss,
warmup_steps,
num_train_steps,
learning_rate,
train_program,
startup_prog,
weight_decay,
scheduler='linear_warmup_decay',
decay_steps=[],
lr_dec... | f3b2e2311551d13d9e2930847afff38636ea2b27 | 23,075 |
def build_full_record_to(pathToFullRecordFile):
"""structure of full record:
{commitID: {'build-time': time, files: {filename: {record}, filename: {record}}}}
"""
full_record = {}
# this leads to being Killed by OS due to tremendous memory consumtion...
#if os.path.isfile(pathToFullRecordFile):
... | 8c9c070c14ffce848cb98a3e8a71b389418aadd0 | 23,076 |
def xsthrow_format(formula):
"""formats the string to follow the xstool_throw convention for toy
vars
"""
return (formula.
replace('accum_level[0]', 'accum_level[xstool_throw]').
replace('selmu_mom[0]', 'selmu_mom[xstool_throw]').
replace('selmu_theta[0]', 'selmu_thet... | b36183df77e681b967ce48a9164fe37861ffd11c | 23,077 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.