content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_user():
""" Method that will create an user .
Returns:
user.id: The id of the created user
Raises:
If an error occurs it will be displayed in a error message.
"""
try:
new_user = User(name=login_session['username'], email=login_session[
'emai... | e5d555fb955523c6bff811efe308030de257e05a | 3,650,328 |
import numpy
def buildStartAndEndWigData(thisbam, LOG_EVERY_N=1000, logger=None):
"""parses a bam file for 3' and 5' ends and builds these into wig-track data
Returns a dictionary of various gathered statistics."""
def formatToWig(wigdata):
""" take in the read position dat... | f97a2b2c54f1cf2f978a17ef2b74435153ec4369 | 3,650,329 |
from pathlib import Path
from typing import List
from typing import Optional
def time_series_h5(timefile: Path, colnames: List[str]) -> Optional[DataFrame]:
"""Read temporal series HDF5 file.
If :data:`colnames` is too long, it will be truncated. If it is too short,
additional column names will be deduce... | e28194bcfead5b188ea947efe51fc2bac052bea9 | 3,650,330 |
def decode_jwt(token):
"""decodes a token and returns ID associated (subject) if valid"""
try:
payload = jwt.decode(token.encode(), current_app.config['SECRET_KEY'], algorithms=['HS256'])
return {"isError": False, "payload": payload["sub"]}
except jwt.ExpiredSignatureError as e:
curr... | 15938fc40d2fb5b60c4ef5ccb3d6f3211fa5952f | 3,650,331 |
def format_point(point: Point) -> str:
"""Return a str representing a Point object.
Args:
point:
Point obj to represent.
Returns:
A string representing the Point with ° for grades, ' for minutes and " for seconds.
Latitude is written before Longitude.
Example Output: 30... | 435a13d7198e6da99306c58d35249b666a03571c | 3,650,332 |
def families_horizontal_correctors():
"""."""
return ['CH'] | a3f8de3e0d44ea72d2fb98733050b7a2d598c142 | 3,650,333 |
import requests
def variable_select_source_data_proxy(request):
"""
@summary: 获取下拉框源数据的通用接口
@param request:
@return:
"""
url = request.GET.get('url')
try:
response = requests.get(
url=url,
verify=False
)
except Exception as e:
logger.exce... | c8d131d6c7d0e766e0a4dacd1b0086090ee02c4f | 3,650,334 |
async def select_guild_lfg_events(guild_id: int) -> list[asyncpg.Record]:
"""Gets the lfg messages for a specific guild ordered by the youngest creation date"""
select_sql = f"""
SELECT
id, message_id, creation_time, voice_channel_id
FROM
lfgmessages
WHERE
... | 3a1b98191b75b4ec0bbdb5942a7b5b2d8c8dca48 | 3,650,335 |
def ValueToString(descriptor, field_desc, value):
"""Renders a field value as a PHP literal.
Args:
descriptor: The descriptor module from the protobuf package, e.g.
google.protobuf.descriptor.
field_desc: The type descriptor for the field value to be rendered.
value: The value of the field to b... | e40815ab6e3b55e1a7cb026c33a9c9324da900b4 | 3,650,336 |
def __load_txt_resource__(path):
"""
Loads a txt file template
:param path:
:return:
"""
txt_file = open(path, "r")
return txt_file | 9e3632098c297d1f6407559a86f0d8dc7b68ea75 | 3,650,339 |
def parse_cpu_spec(spec):
"""Parse a CPU set specification.
:param spec: cpu set string eg "1-4,^3,6"
Each element in the list is either a single
CPU number, a range of CPU numbers, or a
caret followed by a CPU number to be excluded
from a previous range.
:returns: a set of CPU indexes
... | fa323a2fc5c27a6645f0abfb3b4878f6ae6390ee | 3,650,340 |
import typing
def distance_fit_from_transits() -> typing.List[float]:
"""
This uses the observers position from full transits and then the runway positions from all
the transit lines fitted to a
"""
((x_mean, x_std), (y_mean, y_std)) = observer_position_mean_std_from_full_transits()
transits =... | 57b201b1328528191b4926a66325ca026855f09a | 3,650,341 |
import torch
def collate_fn_synthesize(batch):
"""
Create batch
Args : batch(tuple) : List of tuples / (x, c) x : list of (T,) c : list of (T, D)
Returns : Tuple of batch / Network inputs x (B, C, T), Network targets (B, T, 1)
"""
local_conditioning = len(batch[0]) >= 2
if local_condi... | b784a45eb753d5d84ae3bf18fd4e7a09e891753d | 3,650,342 |
def max_(context, mapping, args, **kwargs):
"""Return the max of an iterable"""
if len(args) != 1:
# i18n: "max" is a keyword
raise error.ParseError(_("max expects one argument"))
iterable = evalwrapped(context, mapping, args[0])
try:
return iterable.getmax(context, mapping)
... | 068f77031fb83dc9d88446863e39f38c14a7478d | 3,650,343 |
from typing import Optional
from typing import Dict
def dict_to_duration(time_dict: Optional[Dict[str, int]]) -> Duration:
"""Convert a QoS duration profile from YAML into an rclpy Duration."""
if time_dict:
try:
return Duration(seconds=time_dict['sec'], nanoseconds=time_dict['nsec'])
... | 7b20ed1ecbe496f55426562e791e591d8c5104e5 | 3,650,344 |
def gen_ex_tracking_df(subj_dir):
"""Generate subject tracking error data frames from time series CSVs.
This method generates tracking error (Jaccard distance, CSA, T, AR) data
frames from raw time series CSV data for a single subject.
Args:
subj_dir (str): path to subject data directory, incl... | 259f2533bf8a0d9a03c250fc937c4a99903c8994 | 3,650,345 |
def mse(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""Compute the MSE (Mean Squared Error)."""
return sklearn.metrics.mean_squared_error(y_true, y_pred) | f9c669b04bc6a44bcd983c79dec5d630a6acbd09 | 3,650,346 |
import torch
def policy_improvement(env, V, gamma):
"""
Obtain an improved policy based on the values
@param env: OpenAI Gym environment
@param V: policy values
@param gamma: discount factor
@return: the policy
"""
n_state = env.observation_space.n
n_action = env.action_space.n
... | 10587e5d4fb08158eff06a4305de6c02fc2d878c | 3,650,347 |
def loudness_zwst_freq(spectrum, freqs, field_type="free"):
"""Zwicker-loudness calculation for stationary signals
Calculates the acoustic loudness according to Zwicker method for
stationary signals.
Normatice reference:
ISO 532:1975 (method B)
DIN 45631:1991
ISO 532-1:2017 (met... | 391e33784e355675b68b3e95ade084cbcb86d5b5 | 3,650,348 |
def normU(u):
"""
A function to scale Uranium map. We don't know what this function should be
"""
return u | e4bd83a26c502e9129d18091e807e17ab3294fd1 | 3,650,350 |
def exact_riemann_solution(q_l, q_r, gamma=1.4, phase_plane_curves=False):
"""Return the exact solution to the Riemann problem with initial states
q_l, q_r. The solution is given in terms of a list of states, a list of
speeds (each of which may be a pair in case of a rarefaction fan), and a
fu... | a5baa391d88a56026cc02a1a1fa841325e712ea0 | 3,650,351 |
def show_edge_scatter(N, s1, s2, t1, t2, d, dmax=None, fig_ax=None):
"""Draw the cell-edge contour and the displacement vectors.
The contour is drawn using a scatter plot to color-code the displacements."""
if fig_ax is None:
fig, ax = plt.subplots()
else:
fig, ax = fig_ax
plt.f... | d0575ec425828e895f24c3ff8cbf9f472ba62947 | 3,650,352 |
def get_A2_const(alpha1, alpha2, lam_c, A1):
"""Function to compute the constant A2.
Args:
alpha1 (float): The alpha1 parameter of the WHSCM.
alpha2 (float): The alpha2 parameter of the WHSCM.
lam_c (float): The switching point between the
two exponents of the dou... | 16fe12e9ef9d72cfe7250cf840e222512409d377 | 3,650,353 |
def _parse_seq_tf_example(example, uint8_features, shapes):
"""Parse tf.Example containing one or two episode steps."""
def to_feature(key, shape):
if key in uint8_features:
return tf.io.FixedLenSequenceFeature(
shape=[], dtype=tf.string, allow_missing=True)
else:
return tf.io.FixedLen... | 5e0e4a6d3f26c28eb6e5dfe12e9295eb5b53979c | 3,650,355 |
def unique_list(a_list, unique_func=None, replace=False):
"""Unique a list like object.
- collection: list like object
- unique_func: the filter functions to return a hashable sign for unique
- replace: the following replace the above with the same sign
Return the unique subcollection of collectio... | 8d7957a8dffc18b82e8a45129ba3634c28dd0d52 | 3,650,356 |
def calculate_attitude_angle(eccentricity_ratio):
"""Calculates the attitude angle based on the eccentricity ratio.
Parameters
----------
eccentricity_ratio: float
The ratio between the journal displacement, called just eccentricity, and
the radial clearance.
Returns
-------
... | 24dcb463a0ebdcab8582309bf9ff44fdbfc44686 | 3,650,357 |
import torch
import pickle
def enc_obj2bytes(obj, max_size=4094):
"""
Encode Python objects to PyTorch byte tensors
"""
assert max_size <= MAX_SIZE_LIMIT
byte_tensor = torch.zeros(max_size, dtype=torch.uint8)
obj_enc = pickle.dumps(obj)
obj_size = len(obj_enc)
if obj_size > max_size:
... | bca30d1a88db42f66bdd978386a1c4d24c0c790b | 3,650,358 |
def featCompression (feats, deltas, deltas2):
"""
Returns augmented feature vectors for all cases.
"""
feats_total = np.zeros (78)
for i in range (len (feats)):
row_total = np.array ([])
feat_mean = np.mean (np.array (feats[i]), axis = 0)
delt_mean = np.mean (np.array (deltas... | 033b53fec9cf920daadb3ba5bef2fcce7cc11d21 | 3,650,359 |
def _array_indexing(array, key, key_dtype, axis):
"""Index an array or scipy.sparse consistently across NumPy version."""
if np_version < parse_version('1.12') or issparse(array):
# Remove the check for NumPy when using >= 1.12
# check if we have an boolean array-likes to make the proper indexin... | b8c04647ad79ce8ffd973d2b13fe7231854822de | 3,650,360 |
import torch
def test_binary(test_data, model, criterion, batch_size, device, generate_batch=None):
"""Calculate performance of a Pytorch binary classification model
Parameters
----------
test_data : torch.utils.data.Dataset
Pytorch dataset
model: torch.nn.Module
Pytorch Model
... | 9bc8fefffca3d484abbcac48836fde3ca7b5287a | 3,650,362 |
def linear_imputer(y, missing_values=np.nan, copy=True):
"""
Replace missing values in y with values from a linear interpolation on their position in the array.
Parameters
----------
y: list or `numpy.array`
missing_values: number, string, np.nan or None, default=`np.nan`
The placeholder... | 2557e7647e8d7e0246bb15c57605b75bf3d4131b | 3,650,363 |
def gap2d_cx(cx):
"""Accumulates complexity of gap2d into cx = (h, w, flops, params, acts)."""
cx["h"] = 1
cx["w"] = 1
return cx | 28f6ba5f166f0b21674dfd507871743243fb4737 | 3,650,364 |
import requests
def test_is_not_healthy(requests_mock):
"""
Test is not healthy response
"""
metadata = Gen3Metadata("https://example.com")
def _mock_request(url, **kwargs):
assert url.endswith("/_status")
mocked_response = MagicMock(requests.Response)
mocked_response.sta... | 9b6fdb7b822ef83e0441bdafa1c87ea07ad901ad | 3,650,365 |
def kernelTrans(X, A, kTup):
"""
通过核函数将数据转换更高维的空间
Parameters:
X - 数据矩阵
A - 单个数据的向量
kTup - 包含核函数信息的元组
Returns:
K - 计算的核K
"""
m,n = np.shape(X)
K = np.mat(np.zeros((m,1)))
if kTup[0] == 'lin': K = X * A.T #线性核函数,只进行内积。
elif kTup[0] == 'rbf': #高斯核函数,根据高斯核函数公式进行计算
for j in range(m):
... | da43ab6aeff623b32d3287ad07acdc1ef5ec4bc3 | 3,650,366 |
def getBusEquipmentData(bhnd,paraCode):
"""
Retrieves the handle of all equipment of a given type (paraCode)
that is attached to bus [].
Args :
bhnd : [bus handle]
nParaCode : code data (BR_nHandle,GE_nBusHnd...)
Returns:
[][] = [len(bhnd)] [len(all equ... | 6e0e63846c7b934edbe9de078c7ad8561766e58d | 3,650,367 |
from typing import List
from typing import Counter
import click
def build_and_register(
client: "prefect.Client",
flows: "List[FlowLike]",
project_id: str,
labels: List[str] = None,
force: bool = False,
) -> Counter:
"""Build and register all flows.
Args:
- client (prefect.Client)... | 7e4634578b44b7b5a1743fa0cfab21c6c551930b | 3,650,368 |
def creer_element_xml(nom_elem,params):
"""
Créer un élément de la relation qui va donner un des attributs.
Par exemple, pour ajouter le code FANTOIR pour une relation, il faut que le code XML soit <tag k='ref:FR:FANTOIR' v='9300500058T' />"
Pour cela, il faut le nom de l'élément (ici tag) et un diction... | a4cd29b82531c7bc01864ae79de87643afeb8276 | 3,650,371 |
def get_display():
"""Getter function for the display keys
Returns:
list: list of dictionary keys
"""
return data.keys() | dcc8957faf30db15282d2e67025cd6d5fd07e9dd | 3,650,372 |
def calculate_class_probabilities(summaries, row) -> dict():
"""
Calculate the probability of a value using the Gaussian Probability Density Function from inputs:
summaries: prepared summaries of dataset
row: a row in the dataset for predicting its label (a row of X_test)
This function uses th... | ffdff84e27fe5e76d66176d5d1c862f16b1ee494 | 3,650,373 |
from typing import Sequence
from typing import Any
def find(sequence: Sequence, target_element: Any) -> int:
"""Find the index of the first occurrence of target_element in sequence.
Args:
sequence: A sequence which to search through
target_element: An element to search in the sequence
Re... | 20edfae45baafa218d8d7f37e0409e6f4868b75d | 3,650,375 |
def read_time_data(fname, unit):
"""
Read time data (csv) from file and load into Numpy array
"""
data = np.loadtxt(fname, delimiter=',')
t = data[:,0]
x = data[:,1]*unit
f = interp1d(t, x, kind='linear', bounds_error=False, fill_value=x[0])
return f | 588c3bc472aa05eb0ead983405f22ecdf260687c | 3,650,376 |
from pathlib import Path
from typing import List
from typing import Dict
import json
def read_nli_data(p: Path) -> List[Dict]:
"""Read dataset which has been converted to nli form"""
with open(p) as f:
data = json.load(f)
return data | 2218d8dc06e3b9adfe89cb780a9ef4e7cb111d14 | 3,650,378 |
def stanley_control(state, cx, cy, cyaw, last_target_idx):
"""
Stanley steering control.
:param state: (State object)
:param cx: ([float])
:param cy: ([float])
:param cyaw: ([float])
:param last_target_idx: (int)
:return: (float, int)
"""
current_target_idx, error_front_axle = c... | bef2d7d075a6ef637d1423d6c85cdde3ac4d9d70 | 3,650,379 |
def get_predictions(my_map, reviews, restaurants):
"""
Get the topic predictions for all restaurants.
Parameters:
my_map - the Map object representation of the current city
reviews - a dictionary of reviews with restaurant ids for keys
restaurants - a list of restaurants of the curr... | ef900b9d3526a12f64951e9d7b6f4eb80db9f6f4 | 3,650,380 |
def decode_token(token, secret_key):
"""
解密websocket token
:param token:
:param secret_key:
:return:
"""
info = jwt.decode(token, secret_key, algorithms=['HS256'])
return info | 5807ce3428435eb0c15dd464164627fb342e46d6 | 3,650,381 |
import requests
def getPatternID(pattern_url):
"""asssumes pattern_url is a string, representing the URL of a ravelry pattern
e.g.https://www.ravelry.com/patterns/library/velvet-cache-cou
returns an int, the pattern ID
"""
permalink = pattern_url[41:]
with requests.Session() as a_session:
... | 0624457bad8753a9d15f8339c381ec233a207098 | 3,650,382 |
def make_multibonacci_modulo(history_length, limit):
"""Creates a function that generates the Multibonacci sequence modulo n."""
def sequence_fn(seq):
return np.sum(seq[-history_length:]) % limit
return sequence_fn | 358876a91fec23853bde843c7222cd837b45ada3 | 3,650,383 |
def _get_key(arguments):
"""
Determine the config key based on the arguments.
:param arguments: A dictionary of arguments already processed through
this file's docstring with docopt
:return: The datastore path for the config key.
"""
# Get the base path.
if arguments.get("felix"):
... | b68dd68a013ed2289ae60ab49a347858ce447964 | 3,650,384 |
def prepare_data_from_stooq(df, to_prediction = False, return_days = 5):
"""
Prepares data for X, y format from pandas dataframe
downloaded from stooq. Y is created as closing price in return_days
- opening price
Keyword arguments:
df -- data frame contaning data from stooq
return_days -- nu... | 4b5bc45529b70ed1e8517a1d91fb5a6c2ff0b504 | 3,650,385 |
def represents_int_above_0(s: str) -> bool:
"""Returns value evaluating if a string is an integer > 0.
Args:
s: A string to check if it wil be a float.
Returns:
True if it converts to float, False otherwise.
"""
try:
val = int(s)
if val > 0:
return True... | e39c4afeff8f29b86ef2a80be0af475223654449 | 3,650,386 |
def resnet18(pretrained=False, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url('https://download.pytor... | 89b71b447890e8986493abc90cca6e2ac2f0eca8 | 3,650,387 |
def sydney():
"""Import most recent Sydney dataset"""
d = {
'zip':'Sydney_geol_100k_shape',
'snap':-1,
}
return(d) | f79a5002ef548769096d3aeb1ad2c7d77ac5ce68 | 3,650,388 |
def format_non_date(value):
"""Return non-date value as string."""
return_value = None
if value:
return_value = value
return return_value | 9a7a13d7d28a14f5e92920cfef7146f9259315ec | 3,650,390 |
def get_loss(loss_str):
"""Get loss type from config"""
def _get_one_loss(cur_loss_str):
if hasattr(keras_losses, cur_loss_str):
loss_cls = getattr(keras_losses, cur_loss_str)
elif hasattr(custom_losses, cur_loss_str):
loss_cls = getattr(custom_losses, cur_loss_str)
... | 4c5714b7e8ca0becf43922a9624d9a4dccc4ac28 | 3,650,391 |
from functools import cmp_to_key
def _hashable_policy(policy, policy_list):
"""
Takes a policy and returns a list, the contents of which are all hashable and sorted.
Example input policy:
{'Version': '2012-10-17',
'Statement': [{'Action': 's3:PutObjectAcl',
... | beb5b527f38d7d1a9cecf81918a3291c0c9960ad | 3,650,392 |
def LF_CD_NO_VERB(c):
"""
This label function is designed to fire if a given
sentence doesn't contain a verb. Helps cut out some of the titles
hidden in Pubtator abstracts
"""
if len([x for x in nltk.pos_tag(word_tokenize(c.get_parent().text)) if "VB" in x[1]]) == 0:
if "correlates with... | aa36b8a4cd00194fd1d786a7d3619ea46da0e1ab | 3,650,393 |
from typing import Tuple
def has_file_allowed_extension(filename: PATH_TYPE, extensions: Tuple[str, ...]) -> bool:
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
extensions (tuple of strings): extensions to consider (lowercase)
Returns:
bool:... | 2f0d5698ecdb10533b303a637fdc03747ef8060c | 3,650,394 |
def get_account_html(netid, timestamp=None):
"""
The Libraries object has a method for getting information
about a user's library account
"""
return _get_resource(netid, timestamp=timestamp, style='html') | 7c917f6778e42a1166d4a33819c2e51378933226 | 3,650,395 |
import functools
import math
def gcd_multiple(*args) -> int:
"""Return greatest common divisor of integers in args"""
return functools.reduce(math.gcd, args) | c686b9495cd45ff047f091e31a79bedcd61f8842 | 3,650,396 |
from typing import Counter
def chars_to_family(chars):
"""Takes a list of characters and constructs a family from them. So, A1B2
would be created from ['B', 'A', 'B'] for example."""
counter = Counter(chars)
return "".join(sorted([char + str(n) for char, n in counter.items()])) | e78de779599f332045a98edde2aa0a0edc5a653b | 3,650,397 |
import configparser
def get_config_properties(config_file="config.properties", sections_to_fetch = None):
"""
Returns the list of properties as a dict of key/value pairs in the file config.properties.
:param config_file: filename (string).
:param section: name of section to fetch properties from (if s... | 627d21327560595bb4c2905c98604926f03ca655 | 3,650,398 |
import base64
import secrets
import time
def process_speke():
"""Processes an incoming request from MediaLive, which is using SPEKE
A key is created and stored in DynamoDB."""
input_request = request.get_data()
# Parse request
tree = ET.fromstring(input_request)
content_id = tree.get("id")
... | 3caa1c0390ea699feab2f138942b6773933fbada | 3,650,399 |
from typing import Dict
def merge(source: Dict, destination: Dict) -> Dict:
"""
Deep merge two dictionaries
Parameters
----------
source: Dict[Any, Any]
Dictionary to merge from
destination: Dict[Any, Any]
Dictionary to merge to
Returns
-------
Dict[Any, Any]
... | 4ffba933fe1ea939ecaa9f16452b74a4b3859f40 | 3,650,400 |
async def async_api_adjust_volume_step(hass, config, directive, context):
"""Process an adjust volume step request."""
# media_player volume up/down service does not support specifying steps
# each component handles it differently e.g. via config.
# For now we use the volumeSteps returned to figure out ... | 85625118d4185842dd0398ec5dd0adbb951b5d67 | 3,650,401 |
import warnings
import io
def load_img(path, grayscale=False, color_mode='rgb', target_size=None,
interpolation='nearest'):
"""Loads an image into PIL format.
# Arguments
path: Path to image file.
grayscale: DEPRECATED use `color_mode="grayscale"`.
color_mode: The desired ... | 61709400c2bd6379864f2399c2c04c29e0b61b92 | 3,650,403 |
import logging
import platform
def check_compatible_system_and_kernel_and_prepare_profile(args):
"""
Checks if we can do local profiling, that for now is only available
via Linux based platforms and kernel versions >=4.9
Args:
args:
"""
res = True
logging.info("Enabled profilers: {... | 35da3151109ef13c7966ede991b871dca45f4d0b | 3,650,404 |
import logging
import time
import re
def recv_bgpmon_updates(host, port, queue):
"""
Receive and parse the BGP update XML stream of bgpmon
"""
logging.info ("CALL recv_bgpmon_updates (%s:%d)", host, port)
# open connection
sock = _init_bgpmon_sock(host,port)
data = ""
stream = ""
#... | 6cf8e008b2b47437e80b863eab6f7c1fd4a54e18 | 3,650,407 |
import ast
def is_string_expr(expr: ast.AST) -> bool:
"""Check that the expression is a string literal."""
return (
isinstance(expr, ast.Expr)
and isinstance(expr.value, ast.Constant)
and isinstance(expr.value.value, str)
) | f61418b5671c5e11c1e90fce8d90c583659d40e3 | 3,650,408 |
import numba
def events_to_img(
xs: np.ndarray,
ys: np.ndarray,
tots: np.ndarray,
cluster_ids: np.ndarray,
x_img: np.ndarray,
y_img: np.ndarray,
minimum_event_num: int = 30,
extinguish_dist: float = 1.41422, # sqrt(2) = 1.41421356237
) -> np.ndarray:
... | ced70fc290157a4168c8e9ebd589263bbc410c6f | 3,650,409 |
def generate_ar(n_series, n_samples, random_state=0):
"""Generate a linear auto-regressive series.
This simple model is defined as::
X(t) = 0.4 * X(t - 1) - 0.6 * X(t - 4) + 0.5 * N(0, 1)
The task is to predict the current value using all the previous values.
Parameters
----------
n_... | a02b2bb242ecc0eb6cf3d5d23d0982c56d81b617 | 3,650,411 |
import re
def get_raw_code(file_path):
"""
Removes empty lines, leading and trailing whitespaces, single and multi line comments
:param file_path: path to .java file
:return: list with raw code
"""
raw_code = []
multi_line_comment = False
with open(file_path, "r") as f:
for ro... | 6654a0423f024eaea3067c557984c3aa5e9494da | 3,650,413 |
from typing import Pattern
import re
def _yaml_comment_regex() -> Pattern:
"""
From https://yaml-multiline.info/, it states that `#` cannot appear *after* a space
or a newline, otherwise it will be a syntax error (for multiline strings that don't
use a block scalar). This applies to single lines as we... | 3b5739f460c3d2c66f802dd46e061d2d07030525 | 3,650,415 |
def to_list(name: str) -> "Expr":
"""
Aggregate to list
"""
return col(name).list() | 2265c14d13ef92bb5481dc2eee17915288cf95e8 | 3,650,416 |
import re
def format_ipc_dimension(number: float, decimal_places: int = 2) -> str:
"""
Format a dimension (e.g. lead span or height) according to IPC rules.
"""
formatted = '{:.2f}'.format(number)
stripped = re.sub(r'^0\.', '', formatted)
return stripped.replace('.', '') | 60001f99b5f107faba19c664f90ee2e9fb61fe68 | 3,650,417 |
def mean_test(data, muy0, alternative = 'equal', alpha = 0.95):
"""
This function is used to create a confidence interval of two.sided hypothesis
Input:
data (1D array): the sample of the whole column that you want to evaluate
confidence (float) : confidence_level, must be in... | 9a798eeed1ba2debfe42dbb08ed33c8a1f463fd3 | 3,650,418 |
def __build_command(command, name, background=None, enable=None):
""" Constuct args for systemctl command.
Args:
command: The systemctl command
name: The unit name or name pattern
background: True to have systemctl perform the command in the background
enable: True to enable/disable, False to start... | 5f47c19bb24d05b66d02c6d93ed1bf90144afb63 | 3,650,419 |
import requests
def dockerFetchLatestVersion(image_name: str) -> list[str]:
"""
Fetches the latest version of a docker image from hub.docker.com
:param image_name: image to search for
:return: list of version suggestions for the image or 'not found' if error was returned
"""
base_url = "https:... | 5907dfe92b627c272132f97be9019d735aabd570 | 3,650,420 |
import torch
import torchvision
def _dataset(
dataset_type: str,
transform: str,
train: bool = True
) -> torch.utils.data.Dataset:
"""
Dataset:
mnist: MNIST
cifar10: CIFAR-10
cifar100: CIFAR-100
Transform:
default: the default transform for each data set
simclr: the tran... | cdfeefefede97db0a8d8ad6c3f4620855004062c | 3,650,421 |
def inferCustomerClasses(param_file, evidence_dir, year):
"""
This function uses the variable elimination algorithm from libpgm to infer the customer class of each AnswerID, given the evidence presented in the socio-demographic survey responses.
It returns a tuple of the dataframe with the probability... | 212906aacc2bc3d607e1589742591834953de14e | 3,650,422 |
def MidiSegInfo(segment):
""" Midi file info saved in config file for speed """
class segInfo:
iMsPerTick = 0
bpm = 4
ppqn = 480
total_ticks = 0
iLengthInMs = 0
iTracks = 0
trackList = []
ver = "1.5"
ret = segInfo()
savedVer = IniGetValue(... | 7d48b699ed52239cf08e57b217f5dd62f3c64a84 | 3,650,423 |
def num_in_row(board, row, num):
"""True if num is already in the row, False otherwise"""
return num in board[row] | ca9ab9de4514740e25e0c55f3613d03b2844cdb8 | 3,650,424 |
import urllib
def load_mnist(dataset="mnist.pkl.gz"):
"""
dataset: string, the path to dataset (MNIST)
"""
data_dir, data_file = os.path.split(dataset)
# download MNIST if not found
if not os.path.isfile(dataset):
origin = (
'http://www.iro.umontreal.ca/~lisa/deep/... | 2e499431bed7a8c1c775b04d6272153564d9c99f | 3,650,425 |
def factorial_3(n, acc=1):
"""
Replace all recursive tail calls f(x=x1, y=y1, ...) with (x, y, ...) = (x1, y1, ...); continue
"""
while True:
if n < 2:
return 1 * acc
(n, acc) = (n - 1, acc * n)
continue
break | e067cf4564056bf488e56fe58bbd5b998b0175f3 | 3,650,427 |
def autocorr(x, axis=0, fast=False):
"""
Estimate the autocorrelation function of a time series using the FFT.
:param x:
The time series. If multidimensional, set the time axis using the
``axis`` keyword argument and the function will be computed for every
other axis.
:param ax... | e2e4105bd0a4aed3431af6acf4f3669bb3340825 | 3,650,428 |
import re
import dateutil
def parse_date(filename_html):
"""Parse a file, and return the date associated with it.
filename_html -- Name of file to parse.
"""
match = re.search(r"\d{4}-\d{2}-\d{2}", filename_html)
if not match:
return None
match_date = match.group()
file_... | 2ee45c3f70b75fc2d26b9c00861dbb1e7586d4af | 3,650,429 |
def mod(a1, a2):
"""
Function to give the remainder
"""
return a1 % a2 | f5c03a952aed373e43933bafe37dbc75e796b74d | 3,650,431 |
def select_theme_dirs():
"""
Load theme templates, if applicable
"""
if settings.THEME_DIR:
return ["themes/" + settings.THEME_DIR + "/templates", "templates"]
else:
return ["templates"] | df74bc751f701be63276b5481ac222e64ba914e7 | 3,650,432 |
def encode_string(s):
"""
Simple utility function to make sure a string is proper
to be used in a SQL query
EXAMPLE:
That's my boy! -> N'That''s my boy!'
"""
res = "N'"+s.replace("'","''")+"'"
res = res.replace("\\''","''")
res = res.replace("\''","''")
return res | 814822b9aa15def24f98b2b280ab899a3f7ea617 | 3,650,433 |
def email_manage(request, email_pk, action):
"""Set the requested email address as the primary. Can only be
requested by the owner of the email address."""
email_address = get_object_or_404(EmailAddress, pk=email_pk)
if not email_address.user == request.user and not request.user.is_staff:
messag... | 7a533fe34fdc13b737025c01bb0bb15dcbeae0f2 | 3,650,434 |
def get_container_service_api_version():
"""Get zun-api-version with format: 'container X.Y'"""
return 'container ' + CONTAINER_SERVICE_MICROVERSION | c6f83640b50132e24ce96889688afcda49ba6b1c | 3,650,435 |
from django.utils.cache import get_cache_key
from django.core.cache import cache
def invalidate_view_cache(view_name, args=[], namespace=None, key_prefix=None):
"""
This function allows you to invalidate any view-level cache.
view_name: view function you wish to invalidate or it's named url pattern
... | 2622e6ee48cb7565014660858104edba5b20b9eb | 3,650,437 |
def compute_ray_features_segm_2d(seg_binary, position, angle_step=5., smooth_coef=0, edge='up'):
""" compute ray features vector , shift them to be starting from larges
and smooth_coef them by gauss filter
(from given point the close distance to boundary)
:param ndarray seg_binary: np.array<height, wid... | 18b830fe6ac83cf7282be39d368ad7c1261a890c | 3,650,438 |
def visualize_bbox(img, bbox, class_name, color=(255, 0, 0) , thickness=2):
"""Visualizes a single bounding box on the image"""
BOX_COLOR = (255, 0, 0) # Red
TEXT_COLOR = (255, 255, 255) # White
x_min, y_min, x_max, y_max = bbox
cv2.rectangle(img, (x_min, y_min), (x_max, y_max), color=color, thick... | 147335c2e87b57f0bd0ba0840e9dae9f713b513f | 3,650,439 |
import json
def mock_light():
"""Mock UniFi Protect Camera device."""
data = json.loads(load_fixture("sample_light.json", integration=DOMAIN))
return Light.from_unifi_dict(**data) | ba83ae80ddb39ec9f9b6f30b77eabee39f998b39 | 3,650,440 |
def randomize_bulge_i(N, M, bp='G', target='none', ligand='theo'):
"""
Replace the upper stem with the aptamer and randomize the bulge to connect
it to the lower stem.
This is a variant of the rb library with two small differences. First, the
nucleotides flanking the aptamer are not randomized a... | aff8aa9e6ba276bb9d867f24c58c44e0e3c849f6 | 3,650,441 |
import logging
def parse_identifier(db, identifier):
"""Parse the identifier and return an Identifier object representing it.
:param db: Database session
:type db: sqlalchemy.orm.session.Session
:param identifier: String containing the identifier
:type identifier: str
:return: Identifier ob... | 390fc8d44014d2cdb17fc641dab9914ba13bc95e | 3,650,443 |
import textwrap
def wrap_name(dirname, figsize):
"""Wrap name to fit in subfig."""
fontsize = plt.rcParams["font.size"]
# 1/120 = inches/(fontsize*character)
num_chars = int(figsize / fontsize * 72)
return textwrap.fill(dirname, num_chars) | 7fb7430a01781c7c53637ae4a94c72c057faddab | 3,650,444 |
def resolve_shape(tensor, rank=None, scope=None):
"""Fully resolves the shape of a Tensor.
Use as much as possible the shape components already known during graph
creation and resolve the remaining ones during runtime.
Args:
tensor: Input tensor whose shape we query.
rank: The rank of the tensor, provi... | cc1c3a0bd2b5a35580dd94b6c45a2a36cc151e5a | 3,650,445 |
def gradient_clip(gradients, max_gradient_norm):
"""Clipping gradients of a model."""
clipped_gradients, gradient_norm = tf.clip_by_global_norm(
gradients, max_gradient_norm)
gradient_norm_summary = [tf.summary.scalar("grad_norm", gradient_norm)]
gradient_norm_summary.append(
tf.summary.scalar("clip... | 416f9560ad612ab364cd03de39851a559012d26b | 3,650,446 |
def list_species(category_id):
"""
List all the species for the specified category
:return: A list of Species instances
"""
with Session.begin() as session:
species = session.query(Species)\
.filter(Species.categoryId == category_id)\
.order_by(db.asc(Species.name))\... | c49283fdde11456ffc6e4eff4b5043d547fa9908 | 3,650,448 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.