content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def watershed_aggregation(grid, field, outlet_id, method, **kwds):
"""Aggregate a field value over a watershed.
``watershed_aggregation`` calculates aggregate values on the nodes in a
watershed that drain to *outlet_id*. It supports all methods in the
`numpy`_ namespace that reduce an array to a scalar... | 1d98123f8a8979ef5a0caf3c7294ed745cf34de4 | 55,200 |
import hashlib
import zlib
def object_write(obj, actually_write=True):
"""Creates the vcs object of input data and writes it to a file in compressed form if actually_write is True"""
# Serialize object data
if obj.fmt == b'commit':
data = obj.serialize(obj.commitData) # get the content in byte str... | 7eddbbc06c465277d5df9685ea83cb7a2f58aaea | 55,201 |
import os
import csv
def read_first_available_value(filename, field_name):
"""Reads the first assigned value of the given field in the CSV table.
"""
if not os.path.exists(filename):
return None
with open(filename, 'rb') as csvfile:
reader = csv.DictReader(csvfile)
for row in r... | ac7776795712b004a1f926d43e61610f0657b8d4 | 55,202 |
def _mask_with_shp(cube, shapefilename):
"""Apply a Natural Earth land/sea mask"""
# Create the region
region = _get_geometry_from_shp(shapefilename)
# Create a mask for the data
mask = np.zeros(cube.shape, dtype=bool)
# Create a set of x,y points from the cube
# 1D regular grids
if cu... | 59b015959c184b578f6517faea3b75311bdb3c72 | 55,203 |
def delete_term(*, db_session: Session = Depends(get_db), term_id: int):
"""
Update a term.
"""
term = get(db_session=db_session, term_id=term_id)
if not term:
raise HTTPException(status_code=404, detail="The term with this id does not exist.")
return delete(db_session=db_session, term_i... | 43d23e9e0382ebb27802664f1f959d865291064a | 55,204 |
import torch
from typing import Optional
from typing import Union
def send_backward_recv_forward(
input_tensor_grad: torch.Tensor,
tensor_shape: Shape,
*,
dtype: Optional[torch.dtype] = None,
timers: _Timers = None,
) -> Union[None, torch.Tensor]:
"""Batched send and recv w... | f3d96ce8fe75a9a3b4ed6b27914c143924147364 | 55,205 |
def embedding_sample(name, tensor, sample_type):
""" 转换高维数据的样本到potobuf格式 """
if sample_type == 'text':
tensor = np.array(tensor)
elif sample_type == 'image':
tensor = make_np(tensor)
assert tensor.ndim in [3, 4], f'the shape of image tensors must be (K,H,W) or (K,H,W,C), ' \
... | 75f4feb07330aa054a16fce1adcb023c1b4e8b8a | 55,206 |
def size_to_bytes(size, largeur=6):
""" Convert a size in a bytes with k, m, g, t..."""
if size > 1073741824*1024:
return b"%*.2fT"%(largeur, size / (1073741824.*1024.))
elif size > 1073741824:
return b"%*.2fG"%(largeur, size / 1073741824.)
elif size > 1048576:
return b"%*.2fM"%(largeur, size / 1048576.)
e... | f05e74d89b710936a8253f13b9e6d804f9004b6b | 55,207 |
import optparse
def get_prog_opts(args, usage=""):
"""Returns options and unused args from command line arg list.
usage - optional argurment for help option.
"""
parser = optparse.OptionParser(usage=usage)
parser.add_option("-I", "--inspect",
help="Inspect namespace at 't0'... | 08ffcc0b5697195fc224f9cdf1036f331daecc86 | 55,208 |
from bs4 import BeautifulSoup
from typing import OrderedDict
def query_to_dict(query):
"""
Parameters
----------
query :
Returns
-------
"""
r = query_epmc(query)
soup = BeautifulSoup(r.text, "lxml-xml")
results_dict = OrderedDict()
for result in soup.resultList:
... | a6c4633dbf4210e9d8fc9be704d5e1da57015369 | 55,209 |
from pathlib import Path
def phonons_model_1() -> MEGNetProbModel:
"""Get a model that has been trained to stage 1 on phonons data."""
source = Path(__file__).parents[1] / "static" / "matbench_phonons" / "stage_1"
return MEGNetProbModel.load(source) | e8dca65d2f7f6693d080cbb301462981e23d9576 | 55,210 |
import math
def parse_ham(fname='wannier90_hr.dat',cutoff=None):
"""
wannier90 hr file phaser.
:param cutoff: the energy cutoff. None | number | list (of Emin, Emax).
"""
with open(fname,'r') as myfile:
lines=myfile.readlines()
n_wann=int(lines[1].strip())
n_R=int(lines[2].strip(... | 55660c6fd26f4be63f003280b881be45cf15c019 | 55,211 |
def get_pm_by_id(id):
""" function that is called when you visit /portfolio_manager/get/id/<id> that gets a portfolio manager by id """
token = request.headers.get("token")
headers = {"Content-type": "application/x-www-form-urlencoded", "token": token}
message, info = verify_token(token)
if messag... | b32ba764d698660a154b4a57582efab5ccd85921 | 55,212 |
def lcm(a: int, b: int) -> int:
"""
Least Common Multiple.
"""
return a * b // gcd(a, b) | 48ad022bfdc2a45912c3649e3ee06e6cefe0d5c6 | 55,213 |
def make_valid_braille() -> BrailleArray:
"""
Generate a braille character that is valid
"""
braille=_make_braille()
return braille if _is_valid(braille) else make_valid_braille() | 69aee83dc97520942cd77f8209a596ea5cd1a538 | 55,214 |
def choose_molecule():
"""Saves the final choice of molecule for the end of the game as a tuple of
the final molecule's R Group IDs.
Pass R group IDs as queries: /choose?r1=A01&r2=B10
:returns: Tuple of the R Group IDs as a json dict. Access tuple with
'chosen_mol' key.
:rtype: json dict
""... | 60ae2672d9bb506713fd8a5032110d6b50b12a19 | 55,215 |
def map_trace_to_names(trace, params):
"""Map trace to parameter names."""
out = {}
allnames = list(params.keys()) + ['prob']
for name in trace.keys():
tmp_dict = {}
tmp = np.array(trace[name])
for para_name, values in zip(allnames, tmp.T):
tmp_dict[para_name] = value... | d1b288b0dcc38d9d45f98f092ed393a8f332bb57 | 55,216 |
def _get_array(coords):
"""
Return an arcpy.Array() object based on an input GeoJSON coordinates list.
"""
array_obj = arcpy.Array()
#print type(coords[0])
for pnt in coords:
geom = _get_point(pnt)
array_obj.add(geom)
return array_obj | f6d1fc67d07c473fb97b4dd4a2a18bb9eb4242dd | 55,217 |
def get_last_applied_membership_fee():
"""
Get the last applied membership fee.
:rtype: MembershipFee
"""
return MembershipFee.q.filter(
MembershipFee.ends_on <= func.current_timestamp()) \
.order_by(MembershipFee.ends_on.desc()).first() | c093564bd3e13ed197d18caee207b2cf241a1ccb | 55,218 |
import csv
def csv_writer(output_file):
"""
@brief: Get CSV writer
@param output_file: Output file handler
@return: CSV writer
"""
return csv.writer(output_file, delimiter=';', quoting=csv.QUOTE_ALL) | 70a5d6dca84ef2b60c3fb742a38fd6b27724ecfb | 55,219 |
import configparser
def repo_default_config():
"""Defines the config file structure and returns the configparser object"""
# config files is of microsoft INI format
ret = configparser.ConfigParser()
ret.add_section("core")
ret.set("core", "repositoryformatversion", "0")
ret.set("core", "file... | 3b1071caaa0efd967cb075c492544435449e1be2 | 55,220 |
def home():
""" home page """
content = u.get_content()
return render_template(
"home.html",
html_tab_title="Villoro",
portfolio=content["portfolio_main"],
blog=content["blog_main"],
**u.get_page("home"),
) | 9b099c0eb82d871374dbf32dec0cd38c2c934a36 | 55,221 |
def section():
"""
Populates a single text pane via the section.load view (refreshable via ajax)
The text is returned by the get_text() generator method as a series of Text
objects. Converted to a list, the generated output looks like:
[Text(div_path=('Title', '0'),
unit_id='1',
... | d72fe1d9e20ed1539915ea8b8fadbd29c750e71f | 55,222 |
def read_data_catl(path_to_file, survey):
"""
Reads survey catalog from file
Parameters
----------
path_to_file: `string`
Path to survey catalog file
survey: `string`
Name of survey
Returns
---------
catl: `pandas.DataFrame`
Survey catalog with grpcz, abs r... | aa149deb0ffc0bed5c91028a69fe7f459390bcb5 | 55,223 |
import os
def updates_ondevice():
"""
Searches the directory of AIDeveloper for available updates (zip folders)
Returns
list: list contains strings, each is a tag of an -update version
"""
files = os.listdir(dir_root)
files = [file for file in files if file.startswith("AIDeveloper_") a... | 03dedc6bbf9ff99b4cf6f8bcf13b3e091dc11ef1 | 55,224 |
def _make_spc_mess_str(inf_dct):
""" makes the main part of the MESS species block for a given species
"""
mess_writer = getattr(BLOCK_MODULE, inf_dct['writer'])
return mess_writer(inf_dct) | 00a773a7bc58f75f4fc65ca434c5a8838afaf504 | 55,225 |
def calc_fitness_individual(chromosome, video_list, video_data):
"""Calculate the "fitness" of an individual chromosome
Fitness is the determinant of the covariance matrix of the ts data for each
emotion
Parameters
----------
chromosome : np.ndarray
Dummy-coded chromosome of videos
... | d580f5e0ed6423f9c4bc24db1ffea49fc3f44cfb | 55,226 |
def open_ascii_dataset(outdir, iternumber, **kwargs):
"""
Wrapper that opens simulation outputs from standard mitgcm outputs.
Parameters
----------
outdir: string
Output directory
iternumber: List or integer or None
See xmitgcm iters, can be a iterationnumber or 'all'
**kwar... | ebd05d55290caa08ce9d57e53aba5736a0ae4d3c | 55,227 |
import re
def extractDirective(lineStr: str):
""" :param lineStr:
:return: (directive, directiveArgs) """
match = re.search(r'\.[a-zA-z][a-zA-z\d_]+', lineStr)
return match if not match else match.group() | 390331845733d4f6d5f2c4c8318cbac693730026 | 55,228 |
def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return nn.Conv2d(
in_planes,
out_planes,
kernel_size=1,
stride=stride,
bias=False) | 266f975e23eed371d16670c5b50dbbae335a495b | 55,229 |
def main(args):
"""Run the ``hash`` subcommand."""
hash = get_hash(args.task, args.function_type, args.name)
return hash | d2b6b71648b5756e5483b7b69b7355d40635d876 | 55,230 |
def nb_device_type(model):
"""
Look up device type by model name and return id
"""
json = nb_get("dcim/device-types/", {"model": model})
if json["count"] != 1:
bail("failed to find device-type {} in netbox".format(model))
return json["results"][0]["id"] | 9c01a9967f0a2af865070b523b3c61be28e5ce8a | 55,231 |
def sat2latlon(
sx, sy, sz, lon0=-75.0, Re=6378000.0, Rp=6356000.0, h=3600000.0
):
"""
Transforma coordenadas cartesianas con origen
en el satelite sx,sy,sz
en coordenadas de latitud/longitud
En base a 5.2.8.1 de PUG3
Parameters
----------
sx : float, float arr
coordenada hac... | 0b8c2f56f6d7b0c139080c0f50ec6e35313615ff | 55,232 |
def encode_batch(batch, one_hot_dimention=0):
"""Takes a batch of string as input and encode it to a numerical
batch"""
batch_new = np.ndarray((len(batch), len(batch[0])), dtype='int')
for i in range(len(batch)):
for j in range(len(batch[0])):
batch_new[i][j] = vocab.index(batch[i][j... | 24ebbd1499d3533b34465ae56eb97aafe4962a3e | 55,233 |
def constant_stress_block(segments, stress):
"""
A function to calculate P,Mx, and My by line
integral along given line segments for a constant
stress
Parameters
----------
segments: List of two tuples/lists of two floats
each segment should be of the form [[x1,y1],[x2,y2]]
... | f2704f582480a389e6ba7a5368f839f81989f0ad | 55,234 |
def _maybe_convert_usecols(usecols):
"""
Convert `usecols` into a compatible format for parsing in `parsers.py`.
Parameters
----------
usecols : object
The use-columns object to potentially convert.
Returns
-------
converted : object
The compatible format of `usecols`.
... | 6f432b58115a5730aa007ded93bffb4702643fe1 | 55,235 |
def make_connect_data(one_data):
"""
接收数据,使用特定的字符拼接,返回拼接好的数据
:param one_data:
:return:
"""
datas = ['' if elem == None else elem for elem in one_data ]
data = "&#@".join([str(elem) for elem in datas])
# print(data)
return data | 58a64cc50778d419a292e1c6ba5c55cd1030de47 | 55,236 |
import requests
def get_token(access_key, access_secret,
auth_url="https://deviceserver.creatordev.io/oauth/token"):
""" Gets device server access token. """
try:
# POST Body Payload for Auth
payload = {
'grant_type': 'password',
'username': access_key,
... | bc401bf6ff441aa17311d12137250150aadeb686 | 55,237 |
def check_rhat(fit, pars=None, verbose=True):
"""Checks the potential scale reduction factors, i.e., Rhat values
Parameters
----------
fit : StanFit4Model object
pars : {str, sequence of str}, optional
Parameter (or quantile) name(s). Test only specific parameters.
Raises an excepti... | 5e4b1d0b1a74c979d9c631a49dd3fe69f4955fdc | 55,238 |
import math
def Exponential(x, lb=-1., ub=1.):
"""
Description:
-----------
Dimensions: d
Input Domain:
------------
xi ∈ [-1, 1], i = 1, ..., d
Global Minimum:
--------------
f(x) = -1, x = (0, ..., 0)
"""
y = 0.
for i in range(len(x)):
y = y + x[i] ** 2
... | c1391c1820b17ebbd378c7925e40353c13556833 | 55,239 |
import re
def main(textlines, messagefunc, config):
"""
KlipChop func
"""
pattern = re.compile('([0-9A-F]{4,6})', re.IGNORECASE)
result = list()
count = 0
for line in textlines():
line = line.replace(':', '')
m = pattern.findall(line)
for ldev in m:
if ... | 16e763cb5d9b6be04d439d47ace0c7f93d24657e | 55,240 |
import sys
def parse_STRcov(filename):
"""Parse all STR coverage"""
sample_id = get_sample(filename)
try:
cov_data = pd.read_table(filename, delim_whitespace = True,
names = ['chrom', 'start', 'end', 'decoycov'])
except pd.io.common.EmptyDataError:
sys.exit(... | aab35af23fced7373e458d90d548ecf01b50a208 | 55,241 |
import logging
def decode(data, *_):
"""
>>> data = bytes([5, 65, 66, 67, 68, 69, 70, 250, 55, 2, 65, 66, 67, 252, 53, 128])
>>> decode(data)
b'ABCDEF7777777ABC55555'
>>> data = bytes([5, 65])
>>> decode(data)
b''
>>> data = bytes([128])
>>> decode(data)
b''
"""
res =... | 926410ddb43b8e7c2273e38abbde4464d0041ea1 | 55,242 |
from datetime import datetime
def calc_last_datetime_from_attribution_window(attribution_window_days: int):
"""Calculates the last datetime from a attribution window based from the current utc date"""
return datetime.now(timezone.utc).date() - timedelta(days=attribution_window_days) | 4e0e04362ced7e5c2ac388530577b953f3109f5a | 55,243 |
import pyspark
def is_spark_below_2_2():
"""
Check if spark version is below 2.2.
"""
if hasattr(pyspark, "version"):
full_version = pyspark.version.__version__
# We only need the general spark version (eg, 1.6, 2.2).
parts = full_version.split(".")
spark_version = part... | 14ff26f12a667504ece03db13faff64b20e278fe | 55,244 |
import tempfile
import os
import subprocess
def read_qr(image_file, f=None, l=None, x=None, y=None, W=None, H=None):
"""Reads QR codes from a file or files and returns a list of codes found."""
if not isinstance(image_file, (DAFile, DAFileList)):
return word("(Not a DAFile or DAFileList object)")
... | faa2bcb6a2d7d08199c54bde29b9f0deb5c3b901 | 55,245 |
def allow_fully_supported_version(input_func):
"""Decorate function by ensuring versions are fully supported by pyIATI.
In terms of value:
* Valid Decimal Versions will remain unchanged.
* Invalid Decimal Versions will cause an error to be raised.
* Other values will cause an error to be raised.
... | a2188da17e6b039f84e068090a962beb5b022688 | 55,246 |
import os
def load_kraken_db_metadata(kraken2_db):
"""
Load NCBI taxonomic name mappings to be able to convert taxids into taxonomic strings
Args:
kraken2_db (str): path to kraken2 standard database location
Returns:
names_map (dict[str:str]): the taxonomic names for each taxid node
... | 675c434eb7893b45866b7002c12c142cd0118ac6 | 55,247 |
def update_graphs_politicos(data):
"""
When compute_data() returns the data read from mongo. The plot and wordcloud of "tab-politicos" will be updated.
"""
global tpm_politicos, datetime_politicos, wc_politicos, graph_politicos
tpm_changed, tpm_politicos, datetime_politicos = \
update_tpm_... | e258511a50fbe4eb8e040760ac6ce5c6860f4c73 | 55,248 |
def gumbel_softmax(logits, temperature=1.0, hard=False, dim=1):
"""Sample from the Gumbel-Softmax distribution and optionally discretize.
Args:
logits: [batch_size, n_class] unnormalized log-probs
temperature: non-negative scalar
hard: if True, take argmax, but differentiate w.r.t. soft sample... | 26ff37447aac5934a06f685e5ba748fd01436781 | 55,249 |
def weight_norm_and_equal_lr(m: T_Module,
leak: float = 0.,
mode: str = 'fan_in',
init_gain: float = 1.,
lr_gain: float = 1.,
name: str = 'weight') -> T_Module:
"""
Se... | 9e77fe88140e2151e0483088343100d4f34b98e9 | 55,250 |
def switch_activate_menu(request, pk):
"""
Switch active status of a :class:`gestion.models.Menu`.
"""
menu = get_object_or_404(Menu, pk=pk)
menu.is_active = 1 - menu.is_active
menu.save()
messages.success(request, "La disponibilité du menu a bien été changée")
return redirect(reverse('g... | b3feea2cf6818fee87f230cc1851ee2feade5a13 | 55,251 |
import json
def search():
""" Send search results to browser via SSE(Server-sent events)"""
def eventStream():
while True:
try:
data = q.get(timeout=0.5)
except:
data = {'msg': 'Cloud Run cold start'}
yield "event: images\ndata: {}\n\n".format(json.dumps(data))
return Respo... | 92b55388d4f9147e2b7efc38df1400d227ae28b7 | 55,252 |
from scipy import sparse
def to_scipy_sparse_matrix(G, nodelist=None, dtype=None,
weight='weight', format='csr'):
"""Return the graph adjacency matrix as a SciPy sparse matrix.
Parameters
----------
G : graph
The NetworkX graph used to construct the NumPy matrix.
... | 8d29f8349b71f6a08aa3f27d6365bf4d6bd33de8 | 55,253 |
def contour_xy(axes, coord, *data,
fill=False, xy_limits=None, xy_pad=0.02, add_lines=False,
plot_kw=None, line_kw=None, **kwargs):
""" Show data as an contour plot in ax, with slices at x and y in
the subplots axy and axx.
cnt = ax.contour(*data)
plot_x = ... | ba9adfcc930e7f27a9223fd036a8becfc114b912 | 55,254 |
from typing import Iterable
from typing import Any
def nth(
x: Iterable[Any],
n: int,
order_by: Iterable[Any] = None,
default: Any = NA,
base0_: bool = None,
) -> Any:
"""Get the nth element of x
See https://dplyr.tidyverse.org/reference/nth.html
Args:
x: A collection of elem... | f1debb5ab8bf7c315b5ad86b781f1466c493a5d6 | 55,255 |
def get_bookmarks():
"""This method is used to obtain browser bookmarks of all available and
supported browsers for the system platform.
:return: Object of class :py:class:`browser_history.generic.Outputs` with
the data member bookmarks set to
list(tuple(:py:class:`datetime.datetime`, str, ... | d2df75f8bc7e1d33d69fe26fec87669e2bc58353 | 55,256 |
import struct
import logging
def read_iincal(prefix_files_dic, week_orrun_flag, day_orrun_flag, day_is, y, m):
"""
LEVER ARM DETERMINATION.
Reads the iincal_ pospac binary file and returns a pandas dataframe with columns 'Time', 'X',
'Y', and 'Z', where Time is in adjusted GPS seconds and X, Y, and Z ... | 35eb06709e1c6f00b86c02dbd74bab8ee89a678c | 55,257 |
def evaluate(hex_str: str) -> int:
"""Evaluate a hex string."""
packet = parse(hex_str)
return packet.evaluate() | c70646d00d9ee9a5a26c85f50a58182697882dcd | 55,258 |
def excess_entropy_fast(text: str, H_single, H_pair):
"""
Calculates excess entropy of given string in O(n) time complexity
:param text: an input tokenized string
:param H_single: a function that calculates H(i, x_i)
:param H_pair: a function that calculates H(x_i | x_{i-1}) = H(i, x_{i-1}, x_i)
... | 1e590f7577fa9b9185160eea26d3900476f56bf0 | 55,259 |
from typing import Set
import ast
def _h5attr2set(attr: str) -> Set[str]:
"""Convert an HDF5 attribute to a list of strings"""
if not attr or attr == "set()":
return set()
return ast.literal_eval(attr) | 55aa07126efe42fa1f3437ce6206e72db58c7fd3 | 55,260 |
def add_maps(sky_map, noise_map):
"""Check the inputs and return a sum of sky and noise.
"""
print('Adding maps')
if np.atleast_1d(sky_map).size == 1:
print(' Sky map is empty, using the noise map')
return noise_map
if np.atleast_1d(noise_map).size == 1:
print(' Noise ma... | e92432f1a87246dc1843879abf90d6dba6c3974c | 55,261 |
def test_base_circle_id_coords_params():
"""
Params for test_base_circle_id_coords.
"""
dfs = [
pd.DataFrame(
{
"x": [10, 15, 123, -4],
"y": [2, 1, 1, -4],
"name": ["a", "b", "c", "d"],
"radius": [25.0, 25.0, 25.0, 25.0]... | 58899b88ccc18345c00b9b2e30382bad6ccb082a | 55,262 |
def velmodellayers_sdsu(ifile):
"""
Input a SDSU type velocity model file and return number of layers
as defined by SDSU. This is designed for use in the SDSU code
which required the number of layers in a file.
"""
lincount = 0
infile = open(ifile, "r")
for _ in infile:
lincount ... | 922f9443b3b30cbe58639ab51ab9f183205d0dec | 55,263 |
def forms_for_user(user_is_clerk, tally_id=None):
"""Return the forms to display based on whether the user is a clerk or not.
Supervisors and admins can view all unreviewed forms in the Audit state,
Clerks can only view forms that have not been reviewed by the audit team.
:param user_is_clerk: True if... | 0765a11600dfdbfe2576a65ca0dad126185f5863 | 55,264 |
import warnings
def read_cmfgen_density(fname):
"""
Reading a density file of the following structure (example; lines starting with a hash will be ignored):
The first density describes the mean density in the center of the model and is not used.
The file consists of a header row and next row contains ... | b1fd91f0015a61dcdcc7b6f3b23a37496fff0b8a | 55,265 |
import math
def grid_desired_size(
grid,
media_info,
width=Config.contact_sheet_width,
horizontal_margin=Config.grid_horizontal_spacing):
"""Computes the size of the images placed on a mxn grid with given fixed width.
Returns (width, height)
"""
desired_width = (width -... | e5b6e5b10ab8c3928b315924b105f9d987fade93 | 55,266 |
def joinstrings(n_args=2):
""" Return a nipype function that joins up to `n_args` parts. and
leaves the result in `out`.
Parameters
----------
n_args: int
Number of `argX` parameters the function might have.
Example: If `n_args` == 2, then the node will have `arg1` and `arg2` nodes.
... | 298d5619e5e5ff161ddfad82fbc8d3177248eab8 | 55,267 |
import logging
def get_remote_chart_versions(deps: dict, verbose: bool = False) -> dict:
"""Get dependency versions from the remote hosts
Args:
deps (dict): The dependencies to check and their host URLs
dependency (str): The dependency to get a version for
verbose (bool, optional): Pr... | afbd895879a331c9d3d6a93af43aa5022f1d4317 | 55,268 |
from typing import Any
def to_qualified_name(obj: Any) -> str:
"""
Given an object, returns its fully-qualified name, meaning a string that represents its
Python import path
Args:
- obj (Any): an importable Python object
Returns:
- str: the qualified name
"""
return obj._... | 45824d1f84a96f254274e7fe40f2ed9546ccb346 | 55,269 |
from typing import Sequence
from typing import Union
from pathlib import Path
from typing import Optional
import subprocess
import os
def run_subprocess(
cmd: Sequence[Union[str, Path]],
capture_stdout: bool = True,
capture_stderr: bool = True,
log_cmd_str: Optional[str] = None,
) -> subprocess.Comple... | da965cd7b57b792ba1b1eb0f4cff1561cc14d8ca | 55,270 |
def factorial(n):
"""Factorial function implementation."""
return n * factorial(n-1) if n else 1 | 3ebaa4cd6c38773e8c8a6e1c247e0163f0d7d50a | 55,271 |
def get_index(search, names):
""" Find index matching search in names list of 'Key|Value' """
for name_index, name in enumerate(names):
if search == name.split('|')[0]:
return name_index
return None | fbfc6b71b75172e2980a604f53e602c9b3cb9a84 | 55,272 |
from typing import Dict
from datetime import datetime
def pass_objectives(preferences: Dict) -> Dict:
"""Set all objectives into a passing state"""
for bool_obj in BOOL_OBJECTIVES:
preferences[bool_obj] = "true"
for int_obj, dankvalue in INT_OBJECTIVES.items():
preferences[int_obj] = dankv... | 0d04e076e75c76e47875883fc268db74a3577d7b | 55,273 |
def get_signal(prob, num_classes, pred=None):
"""
SNIPPET 10.1 - FROM PROBABILITIES TO BET SIZE
Calculates the given size of the bet given the side and the probability (i.e. confidence) of the prediction. In this
representation, the probability will always be between 1/num_classes and 1.0.
:param p... | 24917d583e89481a89e5f4a65ebcb4da59be1745 | 55,274 |
import json
def autocomplete(query):
"""
Return the name and medicine_id of each medicine that matches the given query.
"""
out = []
medicine_list_json = cache.retrieve('medicine_list')
if medicine_list_json:
logger.debug('calculating autocomplete from cache')
medicine_list = ... | 94c38ba8d058de6cf355cc9295760246525bbcb3 | 55,275 |
def get_target_sound_definition(sound_key):
"""
Return the target sound definition as a dictionary for the given sound key.
:param sound_key: str key for this target sound definition e.g SND_ANIMAL001_ZONE. Defined in
target_sounds.json
"""
return all_target_sound_definitions()[sound_key] | 2d7fbd1426bbc21e0ad51e15484f8882a60c3ab2 | 55,276 |
def edit_split_taxonomy(
ranks: dict,
split_taxa_pd: pd.DataFrame) -> pd.DataFrame:
"""
Parameters
----------
ranks
split_taxa_pd
"""
if len(ranks) == split_taxa_pd.shape[1]:
split_taxa_pd = split_taxa_pd.rename(columns=ranks)
else:
alpha = 'ABCDEFGHIJKLMN... | e75392c8abf4125a3ff643bf7307ac9d09516b8a | 55,277 |
import argparse
import textwrap
def parse_args():
"""Parse command-line args"""
prog = 'github-mv-repos-to-team'
parser = argparse.ArgumentParser(
prog=prog,
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent("""
Move repo(s) from one tea... | 55a968c9b6d1c89942841da576b87afabffcece3 | 55,278 |
import numpy
import csv
def create_low_test_image_from_s3(npixel=16384, polarisation_frame=PolarisationFrame("stokesI"), cellsize=0.000015,
frequency=numpy.array([1e8]), channel_bandwidth=numpy.array([1e6]),
phasecentre=None, fov=20) -> Image:
""... | 17c7cb0367a39c76c328787b6604566554efaca3 | 55,279 |
def readtxt(fn, delimiter=None):
"""
Read in a generic text file containing a 2D flux array as delimited values.
Inputs:
fn (str): Full file name.
Outputs:
flux2D (array): Numpy 2D array of proton flux at the detector
(counts/bin).
flux2D_ref (array): RE... | 4ec5f2043498c423c5901d457bf76dd0238227b9 | 55,280 |
def compile_opinion_text(name, symbol, sentiment):
"""Generates an opinion on a tweet."""
return "%s %s %s" % (name, get_sentiment_emoji(sentiment), symbol) | bcc8224b68efa53a8301b5f982c0368547528fd8 | 55,281 |
import re
import sys
def process_line(args, file_name, file_input, line, container):
"""Process a single element line return an element object, None if empty"""
line = line.rstrip()
if line and line[0] == '#':
return None
line = re.sub(r'#.*', '', line)
if not line:
return NewLine... | 61f0c7319a4f0b048ea142d568f65498de0ad15b | 55,282 |
from datetime import datetime
import pytz
def get_max_timestamps(nwsli):
""" Fetch out our max values """
icursor = ISUAG.cursor()
data = {'hourly': datetime.datetime(2012, 1, 1,
tzinfo=pytz.FixedOffset(-360)),
'15minute': datetime.datetime(2012, 1, 1,
... | 0c1811da90a15897de868035dc424ba89d656014 | 55,283 |
def get_salsa_estimator_from_data_and_hyperparams(X_tr, Y_tr, kernel_type, add_order,
kernel_scale, bandwidths, l2_reg):
""" Returns an estimator using the data. """
problem_dim = np.array(X_tr).shape[1]
kernel = get_salsa_kernel_from_params(kernel_type, add_order... | a056cd3d3ee909a024f15a1597eeaa759ed66b7d | 55,284 |
def create_droid(data):
"""
This function takes one parameter, a dictionary, represnting a person and returns
an instance of the Droid class.
Parameters:
data (dict): a dictionary representing a person
Returns:
Droid object: an instance of the Droid class
"""
return Droid(
... | bbda0aa50d04774fc9b9c5656a8fd7914d0337ff | 55,285 |
from functools import WRAPPER_ASSIGNMENTS
def temporarily_replace_context_keys(context, func, assigned=DEFAULT_ASSIGNED):
"""
Decorate a function - temporarily updates the context keys while running the function
Updates the context if the function is marked by @binds decorator.
"""
binds = getatt... | 059dda6b8068395ac6495a7ae927741bbae25a87 | 55,286 |
from pathlib import Path
def timebin_dur(spect_path, spect_format, timebins_key, n_decimals_trunc=5):
"""get duration of time bins from a spectrogram file
Parameters
----------
spect_path: str, Path
path to spectrogram file.
spect_format : str
format of file containing spectrogram... | 21a2a4d8cafb9e396e1729c7d23756da978c844c | 55,287 |
def get_premature_df() -> pd.DataFrame:
"""Get premature miRNA dataframe."""
return ensure_df(
PREFIX, PREMATURE_URL, version=VERSION,
names=['premature_key', 'mirbase_id', 'mirna_name'],
usecols=[0, 1, 2],
index_col=0,
dtype=str,
) | 323a060a2626a27d27d98a75e43c61d2adfd53c8 | 55,288 |
def compute_coherence(cross_spec, power_ci, power_ref, mean_rate_ci,
mean_rate_ref, meta_dict, n_range):
"""
Compute the coherence of the cross spectrum. Coherence equation from
Uttley et al 2014 eqn 11, bias term equation from footnote 4 on same page.
Parameters
----------
cross_spec :... | 2c87dc4095a9825670acc0a4a4a61407de5463f9 | 55,289 |
from typing import List
def pin_name_deannotate(annotated_pin_name: Text) -> Text:
"""Return only the pin name from an annotated pin name."""
pair: List[Text] = annotated_pin_name.split(':')
return pair[0][1:] | 0c54119aa255b02f672e008f808ab6c5304aa615 | 55,290 |
def getCity(id):
"""Return all targets
---
parameters:
- name: id
in: path
type: integer
required: true
default: 4
responses:
200:
description: Return a specific waypoint
"""
return datamanger.readTableAsJson(query=SELECTS['waypoint'],data={'id... | b7a74a3582b348f8576b32e6eb8d94d04e171a61 | 55,291 |
def whitelist(chain, maximal_number_of_auction_participants):
"""whitelisted well-funded accounts, accounts[0] is not in the whitelist"""
# some other tests do also call add_account and we do not want to
# include them (it just takes longer)
whitelist = list(chain.get_accounts()[1:10]) + [
chain... | 5bc693db2eacb5ab8a98c025e279e464a96453f6 | 55,292 |
def separate_callback_data(data):
"""Separa i dati in entrata"""
return [i for i in data.split(";")] | 0cfef1abf910193a7ad8015862614f3659dd40d5 | 55,293 |
def normalize_project(project):
"""
FIXME:
Parameters
----------
project: str
FIXME:
"""
return project.lower().replace("-", "_") | a45567cb7f84b0958cbf3affe361f896db3cd21c | 55,294 |
def get_constant_term_design_matrix(data, ids=None):
"""
Construct the portion of the design matrix relevant for the linear
parameters of The Joker beyond the amplitude, ``K``.
"""
if ids is None:
ids = np.zeros(len(data), dtype=int)
ids = np.array(ids)
unq_ids = np.unique(ids)
... | 497ee8f0b51f8a592dcd840e06f16d7945d27cdc | 55,295 |
def _upgrading(version, current_version):
"""
>>> _upgrading('0.9.2', '1.9.2')
False
>>> _upgrading('0.11.3', '0.11.2')
True
>>> _upgrading('0.10.2', '0.9.2')
True
>>> _upgrading('1.1.3', '1.1.4')
False
>>> _upgrading('1.1.1', '1.1.1')
False
>>> _upgrading('0.9.1000', '50... | 1ff478ed3c55687ddaa0392f6a071915750f8dfa | 55,296 |
import argparse
def parse_args():
"""
parsing arguments
"""
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
# required argumnets:... | ded823885e43c3899d2ef5a61c54b0bbeb53c251 | 55,297 |
def main(*args):
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
@param args: command line arguments
@type args: list of unicode
"""
pageName = ''
summary = None
generator = None
options = {}
# read command line parameters
... | b1721027ccc0e904b73361b3aa0f2b42ff1f3478 | 55,298 |
def home():
"""Render the home page which displays the UUID of the day."""
uuid = repository.get_uotd()
today = date.today().strftime("%A, %d %B %Y")
return render_template("index.html", uuid=uuid, today=today) | 47332d553c554f8be73ba64ddd26c348392cf210 | 55,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.