content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def set_season():
"""
Facilitates the user entering what season it is. Returns the appropriate
string.
"""
error = False
while True:
clear_screen()
options = ["Spring", "Summer", "Fall"]
print("What season is it?")
# Prints out the options array in a numbered fas... | 7be0a588460d165fd716bdf83f30b9175f58347f | 3,628,900 |
import http
def extract_rooms_or_global(req, admin=True):
"""
Extracts the rooms / global parameters from the request body checking them for validity and
expanding them as appropriate.
Throws a flask abort on failure, returns (rooms, global) which will be either ([list of Rooms],
None) for a room... | 7ebd6ba77462feb9465cc21e01854f365287a2d6 | 3,628,901 |
def info(msg):
"""
Informational logging statement
:param msg: the message to print
:returns: True -- to allow it as an #assert statement
"""
return log("info", msg, logger) | 2fb1dc02aaf703ffc87381bdd271460e299022c7 | 3,628,902 |
from typing import Counter
def error_correct_BC_or_UMI(records, key, threshold=1):
"""
:param records: should be list of records all from the same gene!
"""
assert key in ('BC', 'UMI')
merge_map = {}
bc_count = Counter()
for r in records: bc_count[r[key]] += 1
# most common BC, in dec... | 4d06243d18b11d2ed18e356882e57e9f6d6bbf81 | 3,628,903 |
def add_category():
"""
Create category for database.
Inject all form data to new category document on submit.
"""
all_plant_types = mongo.db.plant_types.find()
all_shade_tolerance = mongo.db.shade_tolerance.find()
return render_template('addcategory.html',
... | 60d512b1ee22f1b57ab4df5fad4d85a990b567ff | 3,628,904 |
def load_seed_from_file(seed_path):
"""Load urls seed from file"""
seed_urls = urls.load_urls_from_file(seed_path)
return seed_urls | 5161506657dd348a6119f2d97d95230ec9273d3c | 3,628,905 |
def loads(csvdoc, columns=None, cls=Row, delimiter=",", quotechar='"',
typetransfer=False, csv_size_max=None, newline="\n"):
"""Loads csv, but as a python string
Note: Due to way python's internal csv library works, identical headers will overwrite each other.
"""
return _loads(csvdoc, co... | 54373d743a515375e6040b4cdc518866838de610 | 3,628,906 |
import warnings
def cluster_association_test(res, y_col='cmember', method='fishers'):
"""Use output of cluster tallies to test for enrichment of traits within a cluster.
Use Fisher's exact test (test='fishers') to detect enrichment/association of the neighborhood
with one variable.
Tests the 2 x 2 t... | 13c6f5de6c3548eb396ba73128adbc8714a09b5f | 3,628,907 |
def parse_collection_page(wikitext):
"""Parse wikitext of a MediaWiki collection page created by the Collection
extension for MediaWiki.
@param wikitext: wikitext of a MediaWiki collection page
@type mwcollection: unicode
@returns: metabook.collection
@rtype: metabook.collection
""... | 5ed31d3a52d42e4496bc19f522bc1e223a0ed92d | 3,628,908 |
import logging
import shlex
import subprocess
import re
def get_track_info(srcpath, job):
"""Use HandBrake to get track info and updatte Track class\n
srcpath = Path to disc\n
job = Job instance\n
"""
charset_found = False
logging.info("Using HandBrake to get information on all the tracks on ... | f5fa232859cd3479acf9342a41b62a28ad0311a9 | 3,628,909 |
from typing import List
def _ensure_hms(inner_result: ParsedDate, remain_tokens: List[str]) -> ParsedDate:
"""
This function extract value of hour, minute, second
Parameters
----------
inner_result
already generated year, month, day value
remain_tokens
remained tokens used for ... | 5e24e2ec9a8ddd6b866aaaafce054d4e04adba8d | 3,628,910 |
from . import auth, tally
from .auth.models import User
from .tally.models import Bill, Category
def create_app(config=Config):
"""App factory."""
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
migrate.init_app(app, db)
bcrypt.init_app(app)
login_manager.init_app(ap... | 3a39f8ab497fa539ea6609a7e53195e441adce1f | 3,628,911 |
def helper(n, largest_digit):
"""
:param n: int, a number
:param largest_digit: int,
:return: int, the largest digit
"""
if n == 0: # base case
return largest_digit
else:
if n < 0: # convert negative n into positive if any
n = n * -1
if n % 10 > largest_digit:
largest_digit = n % 10
return help... | 557a6ce39a31f7edd2438bea43be9d8abfec47c5 | 3,628,912 |
def peak_compare_data(request, peak_compare_list):
"""
:param request: Request for the peak data for the Peak Explorer page
:return: The cached url of the ajax data for the peak data table.
"""
analysis = Analysis.objects.get(name='Tissue Comparisons')
if peak_compare_list == "All":
pe... | 2d78e803ea1643db24bf4c4695476d16ac254237 | 3,628,913 |
def _generic_filtering_element(F, Q, H, R, y):
"""
Equation 10 in "GPR in Logarithmic Time"
"""
S = H @ (Q @ H.T) + R
chol = cho_factor(S)
Kt = cho_solve(chol, H @ Q)
A = F - (Kt.T @ H) @ F
b= Kt.T @ y
C = Q - (Kt.T @ H) @ Q
HF = H @ F
eta = HF.T @ np.squeeze(cho_solve(ch... | a74f198fc1afcd65f4cc668f9b8aa54b48de1132 | 3,628,914 |
def getStrFromAngles(angles):
"""
Converts all angles of a JointState() to a printable string
:param angles (sensor_msgs.msg.JointState): JointState() angles to be converted
:return (string): string of the angles
"""
d=getDictFromAngles(angles)
return str( dict(d.items())) | a1680e20dc1c58e2f17e8086089a30b3717e2083 | 3,628,915 |
from typing import Callable
import types
def jit_user_function(func: Callable, nopython: bool, nogil: bool, parallel: bool):
"""
JIT the user's function given the configurable arguments.
"""
numba = import_optional_dependency("numba")
if isinstance(func, numba.targets.registry.CPUDispatcher):
... | 41b8551e19ac103e8bd50188a16bf3ca7abfa27b | 3,628,916 |
def aggregate_on_dns(ip_values, ip_fqdns, is_numeric=True):
"""
Aggregates the values in ip_values based on domains accessed from
ip_fqdns. Values from same ip_addresses same domain names are combines
Args:
ip_values (dictionary): maps ip address to some computed value
... | 036edc22544f9e566eb0d76280f59cf68d2bfb33 | 3,628,917 |
def get_users():
"""
Fetch a dictionary of username and their IDs from Slack
"""
slack_api_client = connect()
api_call = slack_api_client.api_call('users.list')
if api_call.get('ok'):
user_list = dict([(x['name'], x['id']) for x in api_call['members']])
return user_list
else:
print 'Error Fetching Users'
... | 7a962d9360f6195ab5185dfb449a2370f5ebc0e0 | 3,628,918 |
import random
def topological_sort(graph):
# type: Dict[str, List[str]] -> Optional[List[Tuple[Union[str, int]]]]
"""Return linear ordering of the vertices of a directed graph.
https://leetcode.com/problems/course-schedule (analogous)
"""
result = []
counter = len(graph)
# Select random ... | fc35bbb92cda977ce5183970844ee20207b3b896 | 3,628,919 |
def lower_bound(expressions):
"""Creates an `Expression` lower bounding the given expressions.
This function introduces a slack variable, and adds constraints forcing this
variable to lower bound all elements of the given expression list. It then
returns the slack variable.
If you're going to be lower-bound... | 948089321ac043254fde3da6d4c139676b7a533c | 3,628,920 |
from typing import List
import os
from sys import version
def get_tensorboard_args(tb_version: str, tfevents_dir: str, add_args: List[str]) -> List[str]:
"""Build tensorboard startup args.
Args are added and deprecated at the mercy of tensorboard; all of the below are necessary to
support versions 1.14, ... | cdb4509f6070625ac2e5ea78f077c860d06f1be9 | 3,628,921 |
import networkx
def do_to_networkx(do):
"""Return a networkx representation of do"""
terms = do.get_terms()
dox = networkx.MultiDiGraph()
dox.add_nodes_from(term for term in terms if not term.obsolete)
for term in dox:
for typedef, id_, name in term.relationships:
dox.add_edge(... | 97c27a5e6ec3c0467fe42f34325aac5b565f5be3 | 3,628,922 |
from typing import List
from typing import Optional
from pathlib import Path
import os
def resolve_executable(name_variants: List[str], env_override: Optional[str] = None) -> str:
"""Resolve platform-specific path to given executable.
Args:
name_variants: List of executable names to look for.
... | 2dd82100486521a53fb613b59346a1733918aefd | 3,628,923 |
def _prepare_data(data):
"""Takes the raw data from the database and prepares it for a sklearn workflow"""
# Get the number of turbines
n_turb = data[0]["lat"].size
# Split the data into the prediction and learning sets
data_learn = [d for d in data if not np.isnan(d["power"])]
data_new = [d fo... | b1397ae90a725958242ac8257db8cccdf299a61f | 3,628,924 |
from .common import parse_gset_format as redirect_func
import warnings
def parse_gset_format(filename):
""" parse gset format """
# pylint: disable=import-outside-toplevel
warnings.warn("parse_gset_format function has been moved to "
"qiskit.optimization.ising.common, "
... | 55a8259720a4680027c345868e2f47e2296532f1 | 3,628,925 |
def find_largest(line: str) -> int:
"""Return the largest value in line, which is a whitespace-delimited string
of integers that each end with a '.'.
>>> find_largest('1. 3. 2. 5. 2.')
5
"""
# The largest value seen so far.
largest = -1
for value in line.split():
# Remove the tra... | 95ceb1e79812e9ef9c7338f393e9d22224eb5a03 | 3,628,926 |
def get_arch(bv):
"""Arch class that gives access to architecture-specific functionality."""
name = bv.arch.name
if name == "x86_64":
return AMD64Arch()
elif name == "x86":
return X86Arch()
elif name == "aarch64":
return AArch64Arch()
else:
raise UnhandledArchitec... | 3895e5a9b8874aea5bdd5a54f46d91a89eeaef7d | 3,628,927 |
import re
from re import DEBUG
def magic_auth(request, magic_token=None):
"""
"""
if request.method == 'POST':
# Validate form
magic_auth_form = MagicAuthForm(request.POST)
if magic_auth_form.is_valid():
# Try to find the user or create a new one
try:
... | dae46830741ffd89a6c07b16d8e97712bdeae769 | 3,628,928 |
def _volume_1_atm(_T, ranged=True):
"""m**3 / mol"""
return 1 / _ro_one_atm(_T, ranged) | 47d8b0f21f9e893c79b477b9edb5892bc74951dd | 3,628,929 |
def isAmdDevice(device):
""" Return whether the specified device is an AMD device or not
Parameters:
device -- DRM device identifier
"""
vid = getSysfsValue(device, 'vendor')
if vid == '0x1002':
return True
return False | 4eb44cafaef5d2251a8152613f185dba680b8501 | 3,628,930 |
def pre_sif_mean_inner(mat, freqs, a, dtype=None):
"""
From *A Simple but Tough-to-Beat Baseline for Sentence Embeddings*
https://openreview.net/forum?id=SyK00v5xx
https://github.com/PrincetonML/SIF
"""
# 1. Normalize
mat = normalize(mat)
# 2. Reweight
rows, cols = mat.shape
for ... | 4ba6f4b30ff4dd763b9cfe975daaaeae842ff866 | 3,628,931 |
import json
def v1() -> Response:
"""
Handle Endpoint: /a2j/v1/
:return: HTTP Response.
:rtype: Response
"""
return Response(json.dumps({
"endpoints": ["parse", "clean"]
}), mimetype="application/json") | 1aee5b7011841951bed21c669b5758bf5d4ef9ed | 3,628,932 |
def apply_phase(signal, phase, frequency, fs):
"""Apply phase fluctuations.
:param signal: Pressure signal.
:param phase: Phase fluctuations.
:param frequency: Frequency of tone.
:param fs: Sample frequency.
Phase fluctuations are applied through a resampling.
"""
delay = delay_fluctu... | 19256fc1bf932b1c064a09ab6feec1367b9b8467 | 3,628,933 |
def __load_aug_img__(path, img_size, img_aug):
"""
"""
img = image.img_to_array(image.load_img(path, target_size=img_size))
if img_aug is not None:
img = img_aug.random_transform(img)
return img | b2be41b76a6a6667ed3ee3f99189975083b931d5 | 3,628,934 |
def _shot_id_to_int(shot_id):
"""
Returns: shot id to integer
"""
tokens = shot_id.split(".")
return int(tokens[0]) | 59d0ecabf874841d616a72ebea1ebac6e6dc3947 | 3,628,935 |
import ctypes
def get_native_pointer_type(pointer_size: int):
"""
:return: A type that can represent a pointer.
"""
return {
ctypes.sizeof(ctypes.c_uint32): ctypes.c_uint32,
ctypes.sizeof(ctypes.c_uint64): ctypes.c_uint64,
}[pointer_size] | 2364bde2f7bfb7ce2b743d8958551156c847f847 | 3,628,936 |
def get_bootinfo():
"""build and return boot info"""
vmraid.set_user_lang(vmraid.session.user)
bootinfo = vmraid._dict()
hooks = vmraid.get_hooks()
doclist = []
# user
get_user(bootinfo)
# system info
bootinfo.sitename = vmraid.local.site
bootinfo.sysdefaults = vmraid.defaults.get_defaults()
bootinfo.serve... | 1eb4060aa184f351b42a3b8fcad4e38e91efab2e | 3,628,937 |
def monkey_all_handler():
"""
@api {get} /v1/monkey/all 查询 Monkey 测试列表
@apiName GetMonkeyAll
@apiGroup 自动化测试
@apiDescription 查询 所有的 monkey 测试信息
@apiParam {int} [page_size] 分页-单页数目
@apiParam {int} [page_index] 分页-页数
@apiParam {int} [user_id] 用户 ID,获取当前用户 ID 的 monkey 测试信息
@apiParam {in... | 212e41f66a363e7a325df8c6459cd7d8a418b78f | 3,628,938 |
from datetime import datetime
def get_all_schedules(db_cur, server_id, is_async):
"""Extract all candidate schedules for a server
+--------- minute (0 - 59)
| +--------- hour (0 - 23)
| | +--------- day of the month (1 - 31)
| | | +--------- month (1 - 12)
| | | | +--------- day of the week (0... | 781697a3d98a6d9bdcad50b7bbb10d42f0385149 | 3,628,939 |
def predicted_win(board: Board, draws: list[int]) -> Prediction:
"""
Goes through the drawn numbers and returns a Prediction, which is a tuple of
two numbers:
- the turn on which the board wins
- the score of the board at that moment
"""
lines = board_lines(board)
for i, draw in enumerat... | 5f45de9ef755eea432e9a80dd6a9109c6673b183 | 3,628,940 |
from typing import Union
from typing import Sequence
from typing import Optional
from typing import Iterable
from typing import Tuple
from typing import List
def quantity_data_frame(bundle: Union[InstanceBundle, Sequence[InstanceBundle]],
quantity_name: str,
us: Optiona... | 1b9787d25ce20bebd73dc9a08743153266e08d06 | 3,628,941 |
from typing import Union
from typing import List
def trim_name(names: Union[List[str], str]) -> Union[List[str], str]:
"""Trims the name from the web API, specifically from IFTTT (removes extra "the ")"""
# Single name
if isinstance(names, str):
trimmed_name = names.lower().replace("the", "").str... | ee0bf0dcb9353fcad1b4af5f50bf2ff208c1dbe2 | 3,628,942 |
def concat(*streams, **kwargs):
"""Concatenate audio and video streams, joining them together one after the other.
The filter works on segments of synchronized video and audio streams. All segments
must have the same number of streams of each type, and that will also be the number
of streams at output.... | a6fe1278191f85c0496ae133c4f36ccf814d6ed6 | 3,628,943 |
def proj(ax,s,ds,
axis='z',title='',vmin=1e0,vmax=1e3,dat=xr.Dataset(),**kwargs):
"""Draw projection plot at given snapshot number
Args:
ax: axes to draw.
s: LoadSim object.
ds: AthenaDataSet object.
axis: axis to project (default:'z').
title: axes title (defaul... | 0b329c8d0173944d4f037795d3b1c5a008c83c44 | 3,628,944 |
from typing import Dict
import aiohttp
from datetime import datetime
import logging
import json
import asyncio
async def fetch_network_node_health(
network_name: str,
time_s: int,
interval_s: int,
node_stats: Dict,
session: aiohttp.ClientSession,
) -> None:
"""Fetch health metric for all nodes... | 4fe082f36bf6c403357268a54a01310cc249ad53 | 3,628,945 |
def get_ingress_address(endpoint_name):
"""Returns an ingress-address belonging to the named endpoint, if
available. Falls back to private-address if necessary."""
return get_ingress_addresses(endpoint_name)[0] | 1b584e20a8b281c2739df1dd24a3c5cc9409a1e0 | 3,628,946 |
import torch
def evaluate_sfp(logits_cls, labels, flag):
""" evaluate same family prediction """
result = {}
result["n"] = len(logits_cls)
result["avg_loss"] = F.binary_cross_entropy_with_logits(logits_cls, labels.float())
if flag["acc"]:
samefamily_hat = logits_cls > 0.5
result[... | b244f57d3d6c74b468d3608d6d2972dab4ee408f | 3,628,947 |
def round(x):
"""Round tensor to nearest integer. Rounds half to even. """
return np.round(x) | c022ac98db8345ec1fe544772746d501c837cb7a | 3,628,948 |
from typing import Any
def regnet_y_8gf(
pretrained: bool = False, progress: bool = True, **kwargs: Any
) -> RegNet:
"""
Constructs a RegNetY-8GF architecture from
`"Designing Network Design Spaces" <https://arxiv.org/abs/2003.13678>`_.
Args:
pretrained (bool): If True, returns a mode... | 83c84bb2706d33c54cce4a9ce0c23eed3fc0f0e6 | 3,628,949 |
def fit_single_univariate_sample(samples):
""" Fit a univariate gaussian model based on the samples given """
gaussian = UnivariateGaussian()
return gaussian.fit(samples) | ab18a34972146d4cd506aaf59014cee0b3d8c4ae | 3,628,950 |
def get_durations_from_alignment(batch_alignments, mels, phonemes, weighted=False, binary=False, fill_gaps=False,
fix_jumps=False, fill_mode='max'):
"""
:param batch_alignments: attention weights from autoregressive model.
:param mels: mel spectrograms.
:param phone... | 192155b6968a276c308290c250f1487a4be5c1e7 | 3,628,951 |
import functools
def argparser_course_required_wrapper(with_argparser):
"""
When applied to a do_x function in the Clanvas class that takes in argparser opts,
will convert/replace course attribute with a corresponding course object either
using the course string as a query or the current (cc'd) course... | b1862167e95480eda5fe746dcd739f31292aebde | 3,628,952 |
from pathlib import Path
from typing import Optional
def read_csv_and_filter_prediction_target(csv: Path, prediction_target: str,
crossval_split_index: Optional[int] = None,
data_split: Optional[ModelExecutionMode] = None,
... | b2034440fc8c198001054edb69edcb9067cae861 | 3,628,953 |
def compare(Target, Population):
"""
This function takes in two picture objects and compares them.
:param Target: target image
:type Target: Picture object
:param Population: The population of the current generations
:type Population: A list of picture objects
:return: Two best members of... | 4456141d1c980c5ca008d614ced05e1ec2efc062 | 3,628,954 |
def normalize_AE_state(states, noSOC=True): # return normalized states for AE (no pred, soc)
"""
:param states: (9, seq, 27)
:return: (9, seq, 19)
"""
state_list = np.split(states, SPLIT_IDX, -1)
result_list = []
for state, func in zip(state_list, func_callbacks):
result_list.append... | 53d0f3d9f23bbc22ab4a3a978a6893b8f1a2238c | 3,628,955 |
def load(image_file):
"""Load the image from file path."""
image = tf.io.read_file(image_file)
image = tf.image.decode_jpeg(image)
width = tf.shape(image)[1]
width = width // 2
real_image = image[:, :width, :]
input_image = image[:, width:, :]
input_image = tf.cast(input_image, tf.flo... | c64f19c3779703dff0b08fc22740cf04ec0561b9 | 3,628,956 |
def get_corpus_directory():
"""Return path of Data/Corpus directory"""
data_directory = get_data_directory()
corpus_directory = data_directory / "Corpus"
return corpus_directory | ecb42b88390a09eb3994034b4982164fa07fc037 | 3,628,957 |
def reconstruction(freq, nfreq, A, d, damping='hysteretic', type='a', residues=False, LR=0, UR=0):
"""generates a FRF from modal parameters.
There is option to consider the upper and lower residues (Ewins, D.J.
and Gleeson, P. T.: A method for modal identification of lightly
damped structures)
... | f082b9b09c8aed79dc7426f510298753a57a7041 | 3,628,958 |
from typing import Optional
from typing import Sequence
from typing import Union
def multilateral_methods(
df: pd.DataFrame,
price_col: str = 'price',
quantity_col: str = 'quantity',
date_col: str='month',
product_id_col: str='id',
characteristics: Optional[Sequence[str]] = None,
groups: O... | 30448b0e9b0f6bff0cfd7042c154cb63d091ee9d | 3,628,959 |
import torch
def causal_fftconv(
signal: torch.Tensor,
kernel: torch.Tensor,
bias: torch.Tensor = None,
) -> torch.Tensor:
"""
Args:
signal: (Tensor) Input tensor to be convolved with the kernel.
kernel: (Tensor) Convolution kernel.
bias: (Optional, Tensor) Bias tensor to a... | 3a9cb98ee6edb00a0bf5523fa1e1e580d5a99523 | 3,628,960 |
def sell_at_loss_switch(value, exchange):
"""enable/disable buy size amount"""
tg_wrapper.helper.config[exchange]["config"].update({"sellatloss": 0})
if "sellatloss" in value:
tg_wrapper.helper.config[exchange]["config"].update({"sellatloss": 1})
return False, False
return True, True | 64ebde92f24f583f18a2a686db4956d29f4f9d64 | 3,628,961 |
def strify(iterable_struct, delimiter=','):
""" Convert an iterable structure to comma separated string.
:param iterable_struct: an iterable structure
:param delimiter: separated character, default comma
:return: a string with delimiter separated
"""
return delimiter.join(map(str, iterable_struc... | 3c8337691c9008449a86e1805fe703d6da73a523 | 3,628,962 |
import copy
def load_shifting_multiple_tech(
fueltypes,
enduse_techs,
technologies,
fuel_yh,
param_lf_improved_cy
):
"""Shift demand in case of multiple technologiesself.
Check how much of each technology is shifted in peak hours.
Calculate the absolute and rel... | 76d57269697ba4b2b7734ede87f9abe019f02243 | 3,628,963 |
def configure_node(
cluster,
node,
certnkey,
dataset_backend_configuration,
provider,
logging_config=None
):
"""
Configure flocker-dataset-agent on a node,
so that it could join an existing Flocker cluster.
:param Cluster cluster: Description of the cluster.
:param Node node... | cdff328b042b6b3a9b8afbad6e103e838735a976 | 3,628,964 |
import torch
def unsubdivide(P, T, iter=1):
"""
Unsubdivides the given mesh n times
In order to work, the mesh is intended subdivided using the method 'subdivide'.
Parameters
----------
P : Tensor
the input points set
T : LongTensor
the topology tensor
iter : int (opt... | 304d98376075925fbac549b2ab042b9e75dc9d98 | 3,628,965 |
def table2sparse(data, shape, order, m_type=lil_matrix):
"""Constructs a 2D sparse matrix from an Orange.data.Table
Note:
This methods sort the columns (=> [rows, cols])
Args:
data: Orange.data.Table
shape: (int, int)
Tuple of integers with the s... | c84309cb330eb3aab2160feb5a525e2147afcfcd | 3,628,966 |
from typing import OrderedDict
def get_s_bi_status(c: analyze.CZSC) -> OrderedDict:
"""倒数第1笔的表里关系信号
:param c: CZSC 对象
:return: 信号字典
"""
freq: Freq = c.freq
s = OrderedDict()
v = Signal(k1=str(freq.value), k2="倒1笔", k3="表里关系", v1="其他", v2='其他', v3='其他')
s[v.key] = v.value
if c.bi_... | 2cb9f416e346a0b4b8bc64081b2049f6f280ff2d | 3,628,967 |
def shuffle_code_book(encode_book):
"""
shuffle the code book
:param encode_book: code book
:return: shuffled code book
"""
codbok = np.array(list(encode_book.items()))
ids0 = np.random.permutation(codbok.shape[0])
ids1 = np.random.permutation(codbok.shape[0])
cod = codbok[ids0, 0]
... | d9f84db17179fd68daa9e5882624267d4e67a9a7 | 3,628,968 |
def default_handler(data: pd.Series, *args, **kwargs) -> pd.Series:
"""Processes given data and indicates if the data matches requirements.
Parameters
----------
data: pd.Series
The data to process.
Returns
-------
pd.Series: The logical list indicating if the data matches requirem... | c0913be67440e41a08788558e20464ef5b02caae | 3,628,969 |
def load_original_data(data, load_dirty=False):
"""
Loads the original dataframe. Missing values are replaced with
np.nan. If load_dirty is set to True, the dirty dataset of a
cleaning experiment is loaded. Otherwise, the default clean dataset
is loaded.
"""
if load_dirty:
df = pd.re... | 15fd528c49d46ea83479f2b35de99c91f5bfe46d | 3,628,970 |
import os
def merge_cpr_fr24_data(date, *, max_speed=DEFAULT_MAX_SPEED,
distance_accuracy=DEFAULT_DISTANCE_ACCURACY):
"""
Match, merge and clean refined CPR and FR24 ADS-B data for the given date.
Parameters
----------
date: string
The date in ISO8601 format, e.g. ... | b1fdbc3b1ec11b0427bc40dfaa9d7aafbb3dfa9c | 3,628,971 |
import torch
from registration_pt import (device, reg_l2_rigid)
from images import gaussian_filter_2d_pt, gaussian_cov
# Overhead
dev = device()
prec = precision()
rot_mtx_T = lambda phi: torch.stack((
torch.stack((torch.cos(phi),torch.sin(phi))),
torch.stack((-torch.sin(phi),to... | dba2c3dc3d27f575f05fb42dc38c5f4fd6f80e32 | 3,628,972 |
from sys import path
def _full_path_to(folder_name: str, i_f_r: str):
"""
Helper method to find the full path to a folder in Data
:param folder_name: Name of the folder in Data
:param i_f_r: 'i' (Input), 'f' (Files) or 'r' (Results). 'r' has subfolders 'l' (Labs), 't' (Tables), 'f' (Figures)
and ... | 31a9519670ee8f64867af3b367a792ae7c32aa5d | 3,628,973 |
def mapped_col_index_nb(mapped_arr, col_arr, n_cols):
"""Identical to `record_col_index_nb`, but for mapped arrays."""
col_index = np.full((n_cols, 2), -1, dtype=np.int_)
prev_col = -1
for r in range(mapped_arr.shape[0]):
col = col_arr[r]
if col < prev_col:
raise ValueError("... | e640da21bce2a570c0d96f588de1739f90a9bc70 | 3,628,974 |
from typing import Set
from typing import Dict
from typing import OrderedDict
def get_greedy_advanced(data: OrderedDictType[_T1, Set[_T2]], unit_counts: Dict[_T1, int], mode: SelectionMode) -> OrderedSet[_T1]:
"""The parameter ngrams needs to be ordered to be able to produce reproductable results."""
assert isins... | 8820dca332cc3c1e833195170327c1bcd49c84c8 | 3,628,975 |
def generate_pattern_eq_ipv4(value):
"""
makes a pattern to check an ip address
"""
return "ipv4-addr:value = '" + value + "'" | 36b4a09363512709c3bdf8046ea52f8ba14aa8e7 | 3,628,976 |
import os
import csv
from fmpy.cross_check import get_vendor_ids
def generate_result_tables(repo_dir, data_dir):
""" Generate the cross-check result tables """
combinations = [] # all permutations of FMI version, type and platform
for fmi_version in ['1.0', '2.0']:
for fmi_type in ['cs', 'me']... | 39ab09791892dfedaf3fa6b5e7ea5dd13837a4ad | 3,628,977 |
import os
def get_dump_date():
"""Iterate through labs dumps and find the newest one."""
dates = sorted(next(os.walk(DIRECTORY))[1], reverse=True)
for date in dates:
if os.path.isfile(FILENAME.format(date=date)):
return date
return None | 69b6160ae2321eb2b1c12b50d77c9b0bf449a886 | 3,628,978 |
def get_pub_velocity_cmd_vel(**kvargs):
"""
Returns publisher for :setpoint_velocity: plugin, :cmd_vel: topic
"""
return rospy.Publisher(mavros.get_topic('setpoint_velocity', 'cmd_vel'), TwistStamped, **kvargs) | 00f0a8331950791a5a072549e13014d32cfbef37 | 3,628,979 |
def get_point_information(form):
"""
Функция для формирования json с полигоном для отрисовки аналитики по точке
:param form: форма из POST запроса с координатами точки и 6 основными фильтрами
:return: json с полигоном с необходимой информацией
"""
point_info = generate_point_information(form)
... | 4e1ec811b1c790aa4940bf2b9a178e6d3ba78d8d | 3,628,980 |
def __kspack(ks):
"""takes a kset and returns an 8-bit number"""
bits = 0
_ks = __make_ks()
for i in range(8):
if _ks[i] in ks:
bits += 2**i
return bits | 44c1a99c1c91c8c2d7991968af5b607eeccf8834 | 3,628,981 |
import warnings
def rec_join(key, r1, r2, jointype='inner', defaults=None, r1postfix='1', r2postfix='2'):
"""
Join record arrays *r1* and *r2* on *key*; *key* is a tuple of
field names -- if *key* is a string it is assumed to be a single
attribute name. If *r1* and *r2* have equal values on all the ke... | c77fb9520edd02817c806930a91058da62a91d12 | 3,628,982 |
from typing import OrderedDict
def cf(data):
"""AFF Community Facts"""
# AFF linked to Community Facts by place name
# CEDSCI links to Community Profiles by GEOID, but we can get around
# that by using search instead
raw_data = OrderedDict(zip(aff_cf, data))
if raw_data["geo_type"] == "zip":
... | 6dbbd1ff5e8d8a2a98950b9a3e7f31bc6a84db12 | 3,628,983 |
import os
import pickle
def perspective_transform(img):
"""
Applies the perspective transformation to the image. If the pickle file
does not exist, the transformation is determined first and saved in the
pickle file.
:param img: The image to be transformed
:return: The warped/transformed imag... | 4ca6a276d5eceec2ac29872677a1d6e09fc8fe0f | 3,628,984 |
import requests
import sys
def print_server_info(ip, user, password):
"""
Fetch and print servers info
@params:
ip - Required : the ip of the server (Str)
user - Required : the administrator username (Str)
password - Required : The administrator password (Str)
"""
try... | 77280b61a71f58f827e879a09f8e72f984d759d9 | 3,628,985 |
def bytes_string(text, encode="utf-8"):
"""Return a bytes object on Python 3 and a str object on Python 2"""
if not PY3:
if isinstance(text, unicode): # pylint: disable=undefined-variable
result = text.encode(encode)
else:
result... | cb8592910081330645d71906f24743736152afc7 | 3,628,986 |
def log_gaussian_prior(map_data, sigma, ps_map):
""" Gaussian prior on the power spectrum of the map
"""
data_ft = jnp.fft.fft2(map_data) / map_data.shape[0]
return -0.5*jnp.sum(jnp.real(data_ft*jnp.conj(data_ft)) / (ps_map+sigma**2)) | ad02d9225a77e476f24c244d426ad29ffc2603c5 | 3,628,987 |
def calculate_cdf(data):
"""Calculate CDF given data points
Parameters
----------
data : array-like
Input values
Returns
-------
cdf : series
Cumulative distribution funvtion calculated at indexed points
"""
data = pd.Series(data)
data = data.fillna(0)
tota... | 2d1f29f2c3f18f6a832553c3a945b027328c327b | 3,628,988 |
from typing import Any
from typing import Optional
from typing import Set
from typing import Deque
from typing import List
def get_special_size(obj: Any, ids: Optional[Set[int]] = None) -> SpecialTuple:
"""
Handles size requests for classes and data structures
:param obj: object to calculate size
:par... | 03e3498789b0a1cc5ca6740a09d38a8361fcdf38 | 3,628,989 |
def sanitize_df(df, d_round=2, **options):
"""All dataframe cleaning and standardizing logic goes here."""
for c in df.columns[df.dtypes == float]:
df[c] = df[c].round(d_round)
return df | cb411b0019112155311a926ec145becc0f8c4ce9 | 3,628,990 |
from typing import Any
from typing import Dict
def bind_args(func: FunctionType, *args: Any, **kwargs: Any) -> Dict[str, Any]:
"""Bind values from `args` and `kwargs` to corresponding arguments of `func`
:param func: function to be inspected
:param args: positional arguments to be bound
:param kwargs... | dc2495b1c53bd93f4ada168abe901e831d8682ac | 3,628,991 |
def register_user(request):
"""
---REGISTER USER---
:param request:
"""
registered = False
if request.method == 'POST':
# Using forms to collect new user data
user_form = UserForm(request.POST)
if user_form.is_valid():
neighborhood = Neighborhood.objects.get(division_title=request.POST['neighborhood_text... | 89773e85a900e93198830c3ceb61591c337f8366 | 3,628,992 |
def trans_quarter(string):
"""Transform from (not lexicographic friendly) {quarter}Q{year} to a datetime object.
>>> trans_quarter('4Q2019')
datetime.datetime(2019, 10, 1, 0, 0)
"""
quarter, year = qy_parser.str_to_tuple(string)
return dt(year=year, month=month_of_quarter[quarter], day=1) | 7e3d12b000ec752a939d8f1cdc92e33ad6804628 | 3,628,993 |
def edit_post(post_id):
"""EDIT-POST page helps in editing of blog post."""
post = Post.query.get(post_id)
if post:
form = PostForm(obj=post)
if form.validate_on_submit():
post.title = form.data.get("title")
post.body = form.data.get("body")
db.session.ad... | eff5144db6eb646350b2a92ba661b0b1d50fb82b | 3,628,994 |
def shutdown(at_time=None):
"""
Shutdown a running system
at_time
The wait time in minutes before the system will be shutdown.
CLI Example:
.. code-block:: bash
salt '*' system.shutdown 5
"""
if (
salt.utils.platform.is_freebsd()
or salt.utils.platform.is_... | 17367da0e3308709347f2853daa5f2c0ed5afdf3 | 3,628,995 |
def _query(
db,
keyword,
person,
album,
uuid,
title,
no_title,
description,
no_description,
ignore_case,
edited,
external_edit,
favorite,
not_favorite,
hidden,
not_hidden,
missing,
not_missing,
shared,
not_shared,
isphoto,
ismovie,
... | 57607818bf35b0eebc864dbb43626ccc69c8c7d7 | 3,628,996 |
def list_products(website, category, search):
"""
There are 3 ways to list the products, 1 by category, 2 by the search bar, 3 by accessing the homepage.
"""
if search:
return Products.objects.filter(websites=website, is_available=True,
title__icontains=se... | 23fa03aebafeef8ff84077df932a0e07ba2ee4b2 | 3,628,997 |
def get_feature_columns(num_hash_buckets, embedding_dimension):
"""Creates sequential input columns to `RNNEstimator`.
Args:
num_hash_buckets: `int`, number of embedding vectors to use.
embedding_dimension: `int`, size of embedding vectors.
Returns:
List of `tf.feature_column` ojects.
"""
id_co... | ab4c60333a556839b9835d405a6c39762f1df2a3 | 3,628,998 |
def afsluitmiddel_soort(damo_gdf=None, obj=None):
""""
Zet naam van SOORTAFSLUITMIDDEL om naar attribuutwaarde
"""
data = [_afsluitmiddel_soort(name) for name in damo_gdf['SOORTAFSLUITMIDDEL']]
df = pd.Series(data=data, index=damo_gdf.index)
return df | 337eadf2bbb8b42fcdc3f4060b5a34bfdd5db13d | 3,628,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.