content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def extract_signals(y, w):
"""
Extract the mean and variance of an image over the sampling windows.
Parameters
----------
y: 2d array, Image
w: 3d list
list of window indices as output by create_windows()
Returns
-------
mean : 2d array
mean values of signal in each... | 5ad284c42ffff54cec0b745de9a3f4475d4b214d | 55,908 |
def color_selection(sample, sample_error, verbose=True):
"""
Run full SDSS quasar candidates selection as specified in
Richards et al. (2002, AJ 123, 2945-2975).
All the color and photometric criteria are implemented.
The returned arrays contain `True` if the given set of
photometry has passed t... | 33707bbf401a2376aa0986c9ecbd0995f4ef89de | 55,910 |
def geometric_inductance_per_unit_length_finite_thickness(trace, gap, thickness):
"""Return the geometric inductance per unit length of a finite-thickness CPW.
See JG Equation 3.31
The result depends only on ratios of the lengths, so they can be specified in any units as long as they are all the
same;... | b5f015271bbde066392d248040a6a04c6c675f5a | 55,911 |
def wcGeneralSettingLookup(gSettings, sid):
"""
Lookup an ID in WooCommerce general settings.
"""
assert gSettings is not None
assert isinstance(sid, str)
for settings in gSettings:
if "id" in settings and settings["id"] == sid:
return settings
return None | ab3ca8a7f8a15db8fa93eaabd3b0f377d31e3b0c | 55,912 |
def semicolon_str_as_list(s):
"""
see utils.tests.MiscTests.test_semicolon_str_as_list().
"""
if not s:
return []
return [x.strip() for x in s.split(';')
if len(x.strip()) > 0] | 01751bbe2702705c6a39701a9289ae12265b5146 | 55,914 |
def binom_coeff(n):
"""
Calculate the binomial coefficient (n, 2), i.e. the number of distinct pairs possible
in a set of size n
:param n: size of set
:return: number of pairs
"""
return int(n * (n-1) / 2) | b7f249524cda01ab8de14c7148745dd153d08b90 | 55,915 |
def read_dat_file(file):
"""Read a dat file containing meteorological mast metadata
You don't really need to care about this, because your files are unlikely to be in the same form as our
example dat files. You'll need to build your own file readers and test them (or use open-source libraries to do
the... | 73a9c597f53151986235abf532ef7c54dd1a4e36 | 55,916 |
import click
def connect_target(targets, target_id):
"""
Connect to the target defined by target_id. This function does
not actually contact the server so there is no try block
"""
try:
target = targets[target_id]
except Exception as ex:
raise click.ClickException("%s: %s" % ... | 341095cde2c15b975746a2ea62bb63c0fef61330 | 55,918 |
import six
def keras_test(func):
"""Function wrapper to clean up after TensorFlow tests.
# Arguments
func: test function to clean up after.
# Returns
A function wrapping the input function.
"""
@six.wraps(func)
def wrapper(*args, **kwargs):
output = func(*args, **kwargs... | 43bc30a385a932defa722a99c6bd273157bdfe4d | 55,919 |
def graph_factory(graph_type, n, m, epsilon):
""" Creates graph based on given attributes.
:param graph_type: Type of graphs in population: "random" or "euclidean".
:param n: Expected value for generated graph number of vertices.
:param m: Expected value for number of edges of graph.
:param epsilon... | 2025822b46239646327b1bc44848f4c047d53b8c | 55,920 |
def homo_lumo_mix(C, nocc, beta):
"""
Mix a portion of LUMO to HOMO.
Used when generating spin-unrestricted guess.
"""
if beta < 0. or beta > 1.:
raise Exception("Mixing beta must be in [0, 1]")
Cb = C.copy()
homo = C[:, nocc - 1]
lumo = C[:, nocc]
Cb[:, nocc - 1] = (1. - bet... | 081c9149ad2d5fe39a16796943fb4d2c53c7b3d7 | 55,921 |
from pathlib import Path
def chrom_from_csv(filename):
"""
A specific parser for .txt files exported from Shimadzu LabSolutions
software.
Extracts data from the chromatogram file into a dictionary using string
manipulation and regex parsing (not all information in the file is
scraped).
P... | 44318b6aa5bc62745c435866c5e5c8ba7205a9da | 55,922 |
def market_last_split_train(market=None):
"""
使用最后一次切割好的训练集symbols数据
:param market: 待获取测试集市场,eg:EMarketTargetType.E_MARKET_TARGET_US
:return: 最后一次切割好的训练集symbols数据
"""
if market is None:
# None则服从ABuEnv.g_market_target市场设置
market = ABuEnv.g_market_target
market_name = market.v... | 4648f9e844dc498a0fc383da0f4bdc0e2202fc25 | 55,923 |
import time
def run(wrapped):
"""
Special decorator encapsulating query method.
"""
@wraps(wrapped)
def _run(self, query, bindings=None, *args, **kwargs):
self._reconnect_if_missing_connection()
start = time.time()
try:
result = wrapped(self, query, bindings, ... | 0564d145637778660319e4c6df7f9c884d568b03 | 55,924 |
def pipulate(tab, rows, cols, columns=None):
"""All that pipulate really is"""
row1, row2 = rows
col1, col2 = cols
col1, col2 = aa(col1), aa(col2)
cl = tab.range(row1, col1, row2, col2)
list_of_tuples = cl_to_tuples(cl)
if not columns:
columns = tab.range(row1, col1, row1, col2)
... | bdf98fa984b5a589051a1978ce1295e3374f7357 | 55,925 |
def make_rect( cxy , wh, **kwa ):
"""
:param cxy: center of rectangle
:param wh: width, height
"""
ll = ( cxy[0] - wh[0]/2., cxy[1] - wh[1]/2. )
return Rectangle( ll, wh[0], wh[1], **kwa ) | 657096f62c32b017c60a4a70d4b77d4537191cbd | 55,926 |
def guild_owner():
"""A guild owner check
Returns whether or not the author is a guild or bot owner
Returns
-------
bool
If the user owns the guild or the bot this will return True
Otherwise it will return False, raising a check failure
"""
async def inner(ctx: Context):
... | 3d4b8674f24fdfe436e81f7652764ef1bab36271 | 55,927 |
def on_delete(url='/'):
"""
Route registerer for DELETE http method
:param url: str
:return: function
"""
return _utils.register_route(_utils.caller(), url, methods=['DELETE']) | b8dff2a10ec82e41f53e2dc9ceb907310152c594 | 55,928 |
def _npadding_bytes(pkt_byte_len, spb):
"""
Generate sufficient padding such that each packet ultimately ends
up being a multiple of 512 bytes when sent across the USB. We
send 4-byte samples across the USB (16-bit I and 16-bit Q), thus
we want to pad so that after modulation the resulting packet
... | c769381de81e9d0044152ada9617e8225f0009d7 | 55,929 |
def exe_mask_wrapper(func, x0, mask,
parameterfile, parameterwriter, outputfile, outputreader,
kwarg, x):
"""
Same as `exe_wrapper` incl./excl. parameters with mask.
Makes the transformation:
`xx = np.copy(x0)`
`xx[mask] = x`
and calls `exe_w... | 3668e6781606c50a96387dff312859cf63877caf | 55,930 |
def _global_module_cache_path(bin_dir):
"""Returns the path to the location where the Swift compiler should cache modules.
Note that the use of this cache is non-hermetic; the cached modules are not declared inputs or
outputs and they are not wiped between builds. The cache is purely a build performance
... | 67fa6be70c2758475c2f1041822280b051af98ae | 55,931 |
from numpy import asarray
from PIL import Image
def resize_image(image, final_image_shape):
"""Utility to resize an image.
Input:
image: original image (2D numpy array of real numbers)
final_image_shape: final size of the resized image (2-ple of positive integers)
Output:
resized... | 97fdf504152151ca249243cdb56c9387b3eefad3 | 55,932 |
import types
def filter_result(S, algo, asset_filter=None, result=None):
""" Filter assets for algo by their past-performance. """
result = result or algo.run(S)
asset_filter = asset_filter or AssetFilter()
# monkey-patch algo's step
step_fun = algo.step
def step(self, x, last_b, history):
... | 0991f89efb58cc49b817594c4c3033459a5b9de4 | 55,933 |
def construct_source_candidate_set(addr, plen, laddr):
"""
Given all addresses assigned to a specific interface ('laddr' parameter),
this function returns the "candidate set" associated with 'addr/plen'.
Basically, the function filters all interface addresses to keep only those
that have the sa... | fab6c8ec990c5cebaa19b95d2f4a11ccf87c009c | 55,935 |
def H_to_nu(H, ecc):
"""
Retrieves hyperbolic anomaly from true one.
Parameters
----------
H: float
Hyperbolic anomaly
ecc: float
Eccentricity of the orbit
Returns
-------
nu: float
True anomaly
"""
nu = 2 * np.arctan(np.sqrt((ecc + 1) / (ecc - 1)) ... | d1e5730aa2ccc36454ea6524e2a286d41c9db2cb | 55,936 |
def getJumpTargets(disas):
"""Get the targets to jump and call instructions.
Takes a interator of Capstone disassembled instructions.
Returns a list of jump target addresses
Example: [0x0, 0x1, 0x3] <- getJumpTargets(disas)
"""
targets = []
for op in disas:
if op.group(CS_GRP_JUMP):... | da5998f4ce5e8437984712c6b5261307c21fbff1 | 55,937 |
def read_coefficients(filename="A_coefficients.dat"):
"""
read_coefficients() as defined above
Parameter
=========
filename (optional): another path to the A_coefficients.dat file.
"""
# unpack the text file
l, u, As = np.loadtxt(filename, unpack=True, delimiter=",",
... | 38c5610fc4f89ffc0684ee053d869c77ff66fa5f | 55,938 |
import random
def random_sampling(dataset:dict, num_of_images=1000) -> list:
"""
Does a random oversampling of the `dataset` to balance all of the classes.
Parameters
----------
`dataset` : `dict`\n
Dict representation of the dataset.
`num_of_images` : `int`, `optional`\n
Numb... | eaf839734528140952bd07f6447e145376367a7c | 55,939 |
def is_in_display_surface(cell):
"""Return True if given cell is in display surface."""
x, y = cell
return all([x >= 0, x < CELL_WIDTH, y >= 0, y < CELL_HEIGHT]) | 26c09537e50a67da852a2b7d5950620a6db2cb64 | 55,940 |
import email
def quoteaddr(addrstring):
"""
引用RFC 821定义的电子邮件地址的子集
"""
displayname, addr = email.utils.parseaddr(addrstring)
if (displayname, addr) == ('', ''):
# parseaddr 无法解析时,原封不动地使用
if addrstring.strip().startswith('<'):
return addrstring
return "<%s>" % add... | b68ffa8e9a432c442fe17bb5581dfae55c955e3d | 55,941 |
from typing import Optional
def has_matching_phone_number(
source: location.NormalizedLocation,
candidate: dict,
) -> Optional[bool]:
"""Compares phone numbers
- True if has at least one matching phone number
- False is only mismatching phone numbers
- None if no valid phone numbers to compar... | 564a1b7695aedbccc9e3ba61101f39c017ade380 | 55,942 |
import json
def loadJson(jsonfile):
"""
Reads a .json file into a python dictionary.
Requires json package.
"""
with open(jsonfile, "r") as data:
dictname = json.loads(data.read())
return dictname | de059637ea0dc1b0ef729a5d2bbfa7c3e72bb5b1 | 55,945 |
import warnings
def _landsat_stats(
band,
address_prefix,
metadata,
overview_level=None,
max_size=1024,
percentiles=(2, 98),
dst_crs=CRS({"init": "EPSG:4326"}),
histogram_bins=10,
histogram_range=None,
):
"""
Retrieve landsat dataset statistics.
Attributes
--------... | 9da1425b6fda466a0607264290f80915a541b6a5 | 55,946 |
def isEqual(lhs, rhs):
"""types should be a either a list, tuple, etc"""
for x,y in zip(lhs, rhs):
if x == y:
continue
else:
return False
return True | b089afcec393657737dee163b897b376550cedee | 55,947 |
def get_item_id(url):
"""
Gets item id from url
:param url: facebook url string
:return: item id or empty string in case of failure
"""
ret = ""
try:
link = create_original_link(url)
ret = link.split("/")[-1]
if ret.strip() == "":
ret = link.split("/")[-2]... | 795e77fba85d6a2eae1d07c2b23f075d3d8cddff | 55,948 |
def get_texcoord_index_from_shader_node(glTF, name, shader_node):
"""Return the texture coordinate index, if assigned and used."""
from_node = get_shader_image_from_shader_node(name, shader_node)
if from_node is None:
return 0
#
if len(from_node.inputs['Vector'].links) == 0:
retur... | 04749faea42c375578fc628b5ec64e4c584c1943 | 55,949 |
def _FunRewriteIntoAABForm(fun: ir.Fun, unit: ir.Unit) -> int:
"""Bring instructions into A A B form (dst == src1). See README.md"""
return ir.FunGenericRewrite(fun, _InsRewriteIntoAABForm) | b9839e3f8a2c683c1c3e17cdffbe208e20ebdbf9 | 55,951 |
def recall_micro(y_true, y_pred, **args):
"""Recall score based on the `sklearn.metrics.recall_score`_ function.
Average argument set to 'micro'.
More details here : `Precision, recall and F-measures`_
.. _sklearn.metrics.recall_score: https://scikit-learn.org/stable/modules/generated/sklearn.metrics... | 84e2e208fc6a6ec8dfa20ef259e5cb835e5e8894 | 55,955 |
import requests
def find_articles(park_code):
""" Find articles from park code """
global api_key
url = "https://developer.nps.gov/api/v1/articles?parkCode=" + park_code + "&api_key=" + API_KEY
response = requests.get(url)
json_object = response.json()
articles_total = json_object['total']
... | 7041765b578d133e158ac73a88f57ffd470cba72 | 55,956 |
def getLayerAnimCurves(node, layerName):
"""get animation curves asociated to an animationlayer
Args:
node (str): name of an animated node
layerName (str): name of a animation layer
Returns:
list: animation curves names
"""
animCurves = set()
for attr in cmds.listAttr(nod... | efc679d6346ac4973c9844657737133879d261b0 | 55,958 |
def square_crop(image, x_pos, y_pos, size=35):
"""Returns a square crop of size centered on (x_pos, y_pos)
Inputs:
image: np.ndarray, image data in an array
x_pos: int, x-coordinate of the hotspot
y_pos: int, y-coordinate of the hotspot
size: int, side length for the returned cro... | 2e327d5b1a9cc358b0806c86e84241d083a390b1 | 55,959 |
import time
def md5_func(text: str) -> str:
"""md5哈希."""
start = time.time()
result = md5(text.encode("utf-8")).hexdigest()
end = time.time()
log.info("time it", seconds=end - start)
return result | 8d90b35a5a5d5321f8a113f41c6f10f17206337c | 55,960 |
def restrict_chains(data, k):
"""Restrict data to people with at least k rows.
Parameters
----------
data : pandas.DataFrame
The `data` from US to be subsetted.
k : int
The minimum number of measurements needed for a person to be kept.
Returns
-------
data : pandas.DataF... | 106fc9c43d12085392a84a188dcc8d40a89ae817 | 55,962 |
def list_of_elem(elem, length):
"""return a list of given length of given elements"""
return [elem for i in range(length)] | d72bdab16a541714b2a0a781a3077d40e309e9f7 | 55,963 |
def celsius2kelvin(celsius):
"""
Convert temperature in degrees Celsius to degrees Kelvin.
:param celsius: Degrees Celsius
:return: Degrees Kelvin
:rtype: float
"""
return celsius + 273.15 | 7fe8ae285cf1619591762ebed9634b5436a52939 | 55,964 |
def resize_image(x, size):
"""
Resize image using skimage.transform.resize even when range is outside [-1,1].
:param x: np.ndarray
:param size: new size (H,W)
:return: np.ndarray
"""
if size != x.shape[:2]:
minx, maxx = minmax(x)
if maxx > 1 or minx < -1:
x = map... | dcd161008433504f531a902fd27bd36e55420a25 | 55,966 |
def delete_relationship(request, slug, handle_id, rel_id):
"""
Removes the relationship if the node has a relationship matching the
supplied id.
"""
success = False
if request.method == 'POST':
nh, node = helpers.get_nh_node(handle_id)
try:
relationship = nc.get_relat... | 554230da208d8dd97f81fb6da843c318433388f8 | 55,967 |
def extract_pqrst(ecg_detrend, r_idx, fs=100, diagPlot=False):
""" Extract peaks from ECG data
Based on results from extract_r, extract PQRST peaks
Returns
-------
peak_idx, peak_val: N x 5 numpy array, index and value of peaks of PQRST
"""
p_idx, q_idx, s_idx, t_idx = [], [... | 46337a5933966273290e0e268327c760d410ffc0 | 55,968 |
from typing import List
from typing import Tuple
def _qspr_from_padel(smiles: List[str], timeout: int = None) -> Tuple[List[List[float]], List[str]]:
"""
Args:
smiles (list[str]): list of SMILES strings
timeout (int, optional): timeout for PaDEL-Descriptor process call; if None, uses
m... | 6a74d186059c651879e5a9eb601b76ef3b22e595 | 55,969 |
def create_rect_polygon(obj, state):
"""Creates an SVG polygon element from a Faint Rect."""
element = ET.Element('polygon')
point_str = str(obj.get_points())[1:-1]
element.set('faint:type', 'rect')
element.set('points', point_str)
# Bundle as shape_style?
style = (svg_fill_style(obj, stat... | 4c8b30f5cf45a3c74cbb9e610acc9e3970150878 | 55,970 |
def set_median_flux_to_one(flux):
"""Set median flux to one."""
if not np.all(np.isfinite(flux)):
raise ValueError('flux must contain all finite values')
medflux = np.median(flux)
if np.isclose(medflux, 0):
return flux + 1
flux = flux.copy()
flux /= medflux
return flux | 255a90c6b724eac2fab89d6a551ca6b567dcca2f | 55,971 |
def all_ones(vector):
"""
Return True/False if all vector's entries are/are not
1s.
"""
return all([e==1 for e in vector]) | 5bd1509c72945de83f3e84e956efae39bd32fee0 | 55,972 |
def max_pool_1d(incoming, kernel_size, strides=None, padding='same',
name="MaxPool1D"):
""" Max Pooling 1D.
Input:
3-D Tensor [batch, steps, in_channels].
Output:
3-D Tensor [batch, pooled steps, in_channels].
Arguments:
incoming: `Tensor`. Incoming 3-D Layer.
... | 2dc550aa3bae009bb32944bc0d3e464664f2c4ab | 55,973 |
import requests
def get_observer_v():
"""Selects all data from the ObserverV view.
:return: a dictionary of key/ObserverID : value/NickName
Eg. request: https://api.nve.no/hydrology/regobs/v3.0.6/Odata.svc/ObserverV/?$filter=ObserverId%20lt%203000&$format=json
"""
url_1 = 'http://api.nve.no/hyd... | 6614a0d68b3ec7a367f8e52f98729e90a05af540 | 55,974 |
def reverse(number) -> int:
"""
Takes a integer number as input and returns the reverse of it.
"""
rev = 0
while number > 0:
d = number % 10
rev = rev*10+d
number //= 10
return rev | aea32007aeb94cb281a98f0f3daba635d79316e7 | 55,975 |
def controlador(msg):
"""
Vai ser responsavel por filtrar as mensagens que chegam
"""
msg.pop(-1) # remove a ultima palavra da string que é uma msg de controle
t = msg.pop(0) # remove a primeira palavra da string que é o codigo do tipo de msg
if t == '0': #Nós que estão coletando temperat... | 4fc53840a03dcd3f200c6957fdd784834bef8e9b | 55,976 |
def checkLibraries(buildReport=False):
"""
Looks for required libraries, and their matching QA versions.
@ In, buildReport, bool, optional, if True then report all libraries instead of just problems
@ Out, missing, list(tuple(str, str)), list of missing libraries and needed versions
@ Out, notQA, list... | 7b82808f8cecf1d9cb3f10cdb3b9ccc7f2d7980d | 55,978 |
def formatNumber(n):
"""格式化数字到字符串"""
rn = round(n, 2) # 保留两位小数
return format(rn, ',') | 7d7da1f0cec70c0a6814daf9cc4bf3bf88559c14 | 55,979 |
def get_limit(past):
"""
Get the date `past` time ago as the matplotlib representation
"""
return num_now() - float(past) * 365 | 0eb2d77609a55f696a18c238dd8e0099e61af427 | 55,980 |
def kappa_idx(n):
"""
Provide scalar products indexes for kappa values.
Parameter:
n -- integer
Return:
list_kappa_idx -- list of lists
"""
list_kappa_idx = []
if n == 5:
list_kappa_idx0 = [['*00**', 0, False, False],
['*01**', 1, False, True],
['*10**', 2, True, False],
['*11**... | 1e19fb2eca480711346d262e91990b79d3d71928 | 55,981 |
def checkin_file(session,driveid,itemid):
"""
checkin a file to Sharepoint.
"""
# create the Graph endpoint to be used
endpoint = f'drives/{driveid}/items/{itemid}/checkin'
return session.put(api_endpoint(endpoint)) | d3411ecc63966ac31799625626bd3bde8a9ffe35 | 55,982 |
from typing import Sequence
import json
def custom_network_main():
"""
Profile comparison tool, accepts a species and a list of probes and plots the profiles for the selected
"""
form = CustomNetworkForm(request.form)
form.populate_method()
if request.method == 'POST':
terms = request... | d2450b124862157bacc9cb0ff406eb78081d037f | 55,983 |
def find_meaningfull_alias(name,
istringmax=30):
"""
we try to limit the alias to ~40 characters
"""
name = name.replace(',', '') # a bit of preprocessing
if len(name.split(' '))==1: # this means it is not real text, that's a real alias
return name
else:
... | 0f72409a93783ecca6ce78eebcc3db00c85e23f6 | 55,984 |
import yaml
def _load_clean_genres():
"""Auxiliary function to load the file with the clean genre list and
parse it to a python dictionary. Original format is YAML.
"""
with open(GENRE_LIST_PATH, 'r') as fgenre:
genres = yaml.load(fgenre)
return genres | 6a11729c0af00a0bfaa5932f18c05587af6dcaaa | 55,986 |
def gfmul(x, y):
"""Returns the 128-bit carry-less product of 64-bit x and y."""
ret = 0
for i in range(64):
if (x & (1 << i)) != 0:
ret ^= y << i
return ret | 3639195b423e516ad374cd9dff263e9137634e68 | 55,987 |
def add_quote(inp, *, date, user, message):
"""Add new quote."""
if db.Quote.find_one(user=user, channel=inp.channel, text=message):
return lex.quote.already_exists
db.Quote.create(
user=user,
channel=inp.channel,
time=(date or arrow.utcnow()).format('YYYY-MM-DD'),
t... | 904bdf9b3ed9f3a606645c937b1b4fc279c43e69 | 55,988 |
from datetime import datetime
def test_ini(t):
""" Monkey-patch to make doctest think it's always time t:
"""
u = Date.now
d = datetime.datetime.strptime(t, '%Y-%m-%d.%H:%M:%S.%f')
Date.now = lambda x: d
return u | be9b2851343679ca0a05e3a7f0a94f0203f790c3 | 55,989 |
def get_name(node: Node) -> bool:
"""
Evaluate the value of a NAME node.
Parameters
----------
node
The node to be evaluated.
Returns
-------
bool
The node's evaluated value.
"""
name = node.token.value.lower()
if name == "exit":
raise KeyboardInterr... | 2b4785c2c27e3fd57ba87deed93146309b2a40ac | 55,990 |
def search_first(pattern, sequence):
"""从sequence中寻找子串pattern
如果找到,返回第一个下标;否则返回-1。
"""
n = len(pattern)
for i in range(len(sequence)):
if sequence[i:i + n] == pattern:
return i
return -1 | 3139c877e7113f6d860e921aba31635570a2e972 | 55,991 |
import logging
def generate_embedding(token: Token) -> Tensor:
"""Use a pre-trained model to get/calculate a vector for the input `token.name`"""
logging.info(f"\nGenerating embedding for current TOKEN: '{token.name}'")
tensor = EMBEDDING_MODEL.query(token.name) # return: ndarray i.e. Token
return te... | 1c4de2f0e92c63872e73166950a2a66143269fab | 55,992 |
def raw_to_ts(raw, min_date=None, max_date=None, date_format=None):
"""
Turns a raw pd.DataFrame into a time-series DataFrame, by creating a DatetimeIndex and a 'timestamp' column
:param raw: a pd.DataFrame with a date column
:param min_date: Minimum date for the time series
:param max_date: Maximum... | 575f3fbccebc801382f3c43bf4d982af30912647 | 55,993 |
from typing import Callable
def compute_bordawise_distance(election_1: OrdinalElection, election_2: OrdinalElection,
inner_distance: Callable) -> float:
""" Compute Bordawise distance between ordinal elections """
vector_1 = election_1.votes_to_bordawise_vector()
vector_2 = ... | 27d7f0893ee7e719c94e7869043df2b4b5e2859b | 55,994 |
def data_prepocessing(csv_filepath):
"""
Implement load_data
Arguements:
csv_filepath -- the path directory of the csv_filepath in the workspace
Returnes:
X_train, X_test, y_train, y_test
"""
df = pd.read_csv(csv_filepath)
df['extracted features'] = df.apply(lambda row : fin... | 661fc4d0eb7e7149940d76e548542436d6562485 | 55,995 |
def time_frequency_features_estimation(signal, frame, step):
"""
Compute time-frequency features from signal using sliding window method.
:param signal: numpy array signal.
:param frame: sliding window size
:param step: sliding window step size
:return: h_wavelet: list
"""
h_wavelet = []... | dcf3aacd18a4119b7c3df85b175002d5019c62bf | 55,996 |
def permute_labels(in_data, permutation):
"""
Permute the values of the labels in an int image.
:param in_data: array corresponding to an image segmentation.
:param permutation:
:return:
"""
if not is_valid_permutation(permutation):
raise IOError('Input permutation not valid.')
r... | a67212119cdef3e4e47b6be13978cc92f539c07b | 55,997 |
def dhash(img):
"""Compute a perceptual has of an image.
Algo explained here :
https://blog.bearstech.com/2014/07/numpy-par-lexemple-une-implementation-de-dhash.html
:param img: an image
:type img: numpy.ndarray
:return: a perceptual hash of img coded on 64 bits
:rtype: int
"""
T... | 7604a91c32dc42c01d503441280990a6dbd85484 | 55,998 |
def kalman_xy(x,
P,
measurement,
R,
motion=np.matrix('0. 0. 0. 0.').T,
Q=np.matrix(np.eye(4))):
"""
Args:
x: initial state 4-tuple of location and velocity: (x0, x1, x0_dot, x1_dot)
P: initial uncertainty convariance matrix
... | 9583162de055aded2389ed52048d5a69a787a8c0 | 55,999 |
def subtract_mean(images):
"""Takes RGB images with 0-255 values and subtraces
the mean pixel and converts it to float. Expects image
colors in RGB order.
"""
return images.astype(np.float32) - Config.IMAGE.MEAN_PIXEL | 55e52fdab5d47151196e4adcd671a77f348ca6dc | 56,000 |
def _linear_idx2coordinate(mesh_shape, linear_idx):
"""
mapping a linear scala into multidimensional mesh space, return it coordinate in that space.
it is the inverse function of _coordinate2linear_idx.
assume:
the size of i-th dimension to be: S[i]
the index of j-th dimension is: I[... | 94237cb93b8d1daa5e47e0ddb7aebb0ad28db461 | 56,001 |
def create_tab(do_display: bool = True) -> Tab:
"""Creates a `ipywidgets.Tab` which can display outputs in its tabs."""
output = Output()
tab = Tab(children=(output,))
tab.set_title(0, "Info")
if do_display:
display(tab)
with output:
# Prints it in the Output inside the tab.
... | 44df8c8686e2e78aad92fc72205470d3d2fd878f | 56,002 |
def is_slice_as_str(x):
"""
Test if string x is a slice. If not a string return False.
"""
try:
x = x.strip("[]()")
m = SLICE_REG.fullmatch(x)
if m:
return True
except AttributeError:
pass
return False | 8a175547ec133753c35f70dee51497d874536291 | 56,003 |
def response_processing(response):
"""
Выделение подходящих адресов из области поиска.
"""
authorized_areas = [area.title.lower() for area in SearchArea.objects.all()]
all_address = response.json()["response"]["GeoObjectCollection"]["featureMember"]
for address in all_address:
area = ad... | 666c8b13a117b90e1720a6174bb9b83bfa1e726f | 56,004 |
def rollaxis(img, axis, inverse=False):
""" Roll `axis` backwards, until it lies in the first position.
It also reorders the reference coordinates by the same ordering.
This is done to preserve a diagonal affine matrix if image.affine
is diagonal. It also makes it possible to unambiguously specify
... | b55b4845030460d84d8ec8f905c2c63fe9e8e78f | 56,005 |
def get_fingerprint(path, passphrase=None, content=None, backend='pyopenssl', prefer_one=False):
"""Generate the fingerprint of the public key. """
privatekey = load_privatekey(path, passphrase=passphrase, content=content, check_passphrase=False, backend=backend)
return get_fingerprint_of_privatekey(priva... | 83acdd1f941b6094a03d6362bb84c091afcc5ab7 | 56,006 |
import functools
def get_generator_map():
"""Returns a map from the generator ID to a SequenceGenerator class creator.
Binds the `config` argument so that the arguments match the
BaseSequenceGenerator class constructor.
Returns:
Map from the generator ID to its SequenceGenerator class creator with a
... | 593207c3f9857e79c73db7b2d0979caac0f7723e | 56,007 |
def get_file(task_id, name):
"""Helper function for spitting out a file on s3"""
# Validate credentials and check status
app_id, app_key, status = check_credentials_and_status(task_id)
key = "output/" + make_key(app_id, app_key, task_id) + "/" + name
app.logger.info("Results delivered. name: %s, app... | 18d1ec2f5e31b6025bfeddabee4db465d53068bd | 56,008 |
def run_auto_arima(train, m):
"""
Performs grid search to discover optimal order for an ARIMA model
based on Akaike Information Criterion ("AIC")
Args:
train: pandas dataframe training set
m (int): Period for seasonal differencing; 4 for quarterly,
12 for monthly, or 1 f... | 9ba5064dc33b2036fa9e10cf0e810f1af63fcdb0 | 56,010 |
from typing import Union
def is_valid_bind_request(request_data: dict) -> Union[dict, bool]:
"""
Check is a bind request is valid.
:param request_data:
:return:
"""
if 'command' in request_data and request_data['command'] in BIND_FIELDS:
command = request_data['command']
form... | cea376305e3e262731eb27643ff980f6cfee01a3 | 56,011 |
def SignerTest(input_proto, output_proto, _config):
"""Run image tests.
Args:
input_proto (image_pb2.ImageTestRequest): The input message.
output_proto (image_pb2.ImageTestResult): The output message.
_config (api_config.ApiConfig): The API call config.
"""
image_path = input_proto.image.path
re... | 3137974447dbf4f5facfac6bda4b04fa2debbc9e | 56,014 |
def is_circle(root: ET.Element):
"""Returns true if root is an SVG circle."""
return root.tag == circle_tag | bc7b408b11ca9442c603aac75427e60660dd29e6 | 56,015 |
from typing import Dict
from typing import Tuple
def make_densebox_target(gt_boxes: np.array, config: Dict) -> Tuple:
""" v1
Model training target generation function for densebox
Arguments
---------
gt_boxes : np.array
ground truth bounding boxes with class, shape=(N, 5), order=(x0, y0, ... | bd029dae7850fea7beafa9486401c32799406f66 | 56,016 |
def quat_rotate(quat, vec):
"""Rotate a vector by a unit quaternion.
Args:
quat: A unit quaternion [w, i, j, k]. The norm of this vector should be 1.
vec: A 3-vector representing a position.
Returns:
The rotated vector.
"""
vec = np.atleast_2d(vec)
qvec = np.hstack([np.zeros(vec.shape[0:-1] + ... | a19cbd62e9f05ef4aecb5f1e70e6e04084591fab | 56,017 |
def random_clustering(num_nodes, num_clusters):
"""Partitioning graph randomly"""
parts = np.random.choice(num_clusters, size=num_nodes)
return parts | ed862454f30e7cb94abb6b1366c870f33f6aadb2 | 56,018 |
def classifyData(classifier, testdata, classMap):
"""
Classifies data based on the previously trained model.
Args:
classifier: A classifier object that has been trained on the test corpus.
testdata: A dataset to classify based on reads.
classMap: A dictionary mapping class names to ... | ea2782a31b159cc937c8c8c69a634b403959e722 | 56,019 |
def predict(algo, pairs, nprocs=None):
"""
Generate predictions for user-item pairs. The provided algorithm should be a
:py:class:`algorithms.Predictor` or a function of two arguments: the user ID and
a list of item IDs. It should return a dictionary or a :py:class:`pandas.Series`
mapping item IDs ... | 7b032f903b0bd42f3ae89d77296172b44dc1d206 | 56,021 |
def page_1(fake_element_namedtuple):
"""Faked page."""
return Page(
addr='http://mock_url',
contents=[
fake_element_namedtuple(('p', 'Zażółć gęślą jaźń')),
fake_element_namedtuple(('a', 'Etiam aliquam')),
fake_element_namedtuple(('p', '')),
fake_el... | 3609c444a6573ce4bc158f496f0a1cde61f06528 | 56,022 |
def generate_action_single_step(inputs, dim_fc_action):
"""Generate the action for single steps.
Args:
inputs: The input tensor.
dim_fc_action: Dimension of action encoding.
Returns:
The generated action.
"""
with slim.arg_scope(
[slim.fully_connected],
... | a232dbb300d1251ddfcc0cafe8bab058fba31b93 | 56,024 |
import requests
import json
def get_authorization_info(wx, auth_code):
"""
获取微信授权方公众号/小程序的授权信息
:param wx: [dict]
:param auth_code:
:return:
"""
access_token = get_component_access_token(wx)
if not access_token:
return
wx_url = 'https://api.weixin.qq.com/cgi-bin/component/a... | 7c440d9f9301f67717f405046a6224d6b1928dc6 | 56,025 |
import re
from datetime import datetime
def generate_identifier():
"""Generate unique date and time based identifier"""
return re.sub(' |:','',str(datetime.datetime.today())) | 3a44399783c75962760ba4fb4cea078378744fae | 56,026 |
def get_public_key(context, signature_certificate_uuid, signature_key_type):
"""Create the public key object from a retrieved certificate.
:param context: the user context for authentication
:param signature_certificate_uuid: the uuid to use to retrieve the
certificat... | ba78c9cc5d1cc4d92cc8a482877c03a795ec8cd2 | 56,027 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.