content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def class_fullname(obj):
"""Returns the full class name of an object"""
return obj.__module__ + "." + obj.__class__.__name__ | a7b5915e15122664943a181a48d3f52dff232c88 | 3,607,900 |
def tpr_diff(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1):
""" Returns the between-group difference of True Positive Rates
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
prtc_attr (str): name of the protected attribute
... | eeaa7799d3953fc891da5b42d3acfb64146b3948 | 3,607,901 |
import re
def remember_me_login(request, template_name='registration/login.html',
redirect_field_name=REDIRECT_FIELD_NAME,
authentication_form=AuthenticationRememberMeForm):
"""
Based on login view cribbed from
https://github.com/django/django/blob/1.2.7/django/contrib/auth/... | c68f164a016184a91bfe63294beb860a42b304dc | 3,607,902 |
def extract_values_mgd(batch_evals, thetas, circuits_details, results,
sample_error_mitigation=None,
noise_matrix=None,
value_error_mitigation=None,
samples_filename=None,
save_samples=False,
**kwargs):
... | 909efeb1d9d01f6feff3a872f8af01f8eaab22dd | 3,607,903 |
def exists(path):
"""
Test whether a path exists. Returns False for broken symbolic links.
"""
return op.exists(path) | 76431a6d898c447180a43783ea9abd1173cb3d70 | 3,607,904 |
from crds.tests import test_newcontext, tstmod
import unittest
def main():
"""Run module tests, for now just doctests only."""
suite = unittest.TestLoader().loadTestsFromTestCase(TestNewContext)
unittest.TextTestRunner().run(suite)
old_state = test_config.setup()
result = tstmod(test_newcontext... | 1216046d1567aa1b335aeb770e3d17232731c4e6 | 3,607,905 |
from typing import List
import os
def get_all_files(path: str, endswith: str = '', startswith: str = '', only_names: bool = False,
recurse: bool = True, remove_root_folder: bool = False) -> List[str]:
"""
Returns all files in the directory
Args:
path: path to the directory
... | dff2e98b002ae327a8348b5ef304f2001d9b7c26 | 3,607,906 |
def run_pca(dataset, num_components):
"""run_pca
Reduces the dimensionality of the dataset with principle component analysis
Arguments: dataset - (array_like) The data to be reduced
num_components - (int) The number of principle components to keep
Returns: transformed_dataset - (array_li... | f2e299936eda06fa3ec9671cacda7c34a603872a | 3,607,907 |
from typing import List
def split_users(grouped_data: List[str]) -> List[List[str]]:
"""
Group user groups into votes per person
"""
return [value.split(" ") for value in grouped_data] | ea61cedff0441a420ccbcb32584bf294348ac15a | 3,607,908 |
def ang2vec(phi, theta):
"""
Get vector from spherical angles (phi, theta)
:param phi: range (pi, -pi), 0 points in x-direction, pi/2 in y-direction
:param theta: range (pi/2, -pi/2), pi/2 points in z-direction
:return: vector of shape (3, n)
"""
assert np.ndim(phi) == np.ndim(theta), "Inpu... | de85a2b082c10c7b620f15328dc0e330531e52e1 | 3,607,909 |
import ctypes
def __comtype_to_pywin_obj(ptr, interface):
"""Convert a comtypes pointer 'ptr' into a pythoncom PyI<interface> object.
'interface' specifies the interface we want; it must be a comtypes
interface class. The interface must be implemented by the object;
and the interface must be known t... | 2233e9e0e9718d24d6208f5f154d2a45edd7196a | 3,607,910 |
def strxor(a, b):
"""
Realiza a operação xor para toda a string a e b
sabendo qual das duas é maior
"""
# xor em duas strings de tamanhos diferentes
if len(a) > len(b):
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
else:
return "".join([chr(ord(x) ^ ... | c97b7eba2ce53c9bd136ebfabc762a5e733c3c4a | 3,607,911 |
def parse_reply(param, reply):
"""
Returns a list of (value, cf) pairs for the Parameter param from a text
reply. Expected a single value (with an implicit CF of true) or a list of
value/cf pairs val1 cf1, val2 cf2, ....
"""
if reply.find(',') >= 0:
vals = []
for pair in reply.s... | df1f961075ab5e86b25012b1a950ad66892e2dc4 | 3,607,912 |
def agg_drug_data(file_path,file_name):
"""Create and write to disk a .csv file of aggregated drug data rows.
Args:
file_path: Path to csv file of drug data.
file_name: Name of the drug data file.
"""
# Read drug data frame
drug_df = pd.read_csv(r"{}\{}.csv".format(file_path,file_na... | f01db2e46d30e5102c44ddef03136409e44d5baa | 3,607,913 |
def view_queries():
"""Render the query catalog."""
queries = manager.list_queries()
return render_template(
'query/queries.html',
queries=queries,
manager=manager,
) | 4c06efb055fcfb9647c28a148f637373c4fcd0d9 | 3,607,914 |
def get_model_ref(data, name_weights):
"""
Returns model reference if found by model name and model weights pair. Returns None otherwise.
data - list of tuples (model_name, model_weights_path, model_ref)
"""
for x in data:
if name_weights == x[:2]:
return x[2]
return None | 8525d77c018ec696619161afb3fbb0342ff46a27 | 3,607,915 |
def make_serie(results, criteria, lang, is_time=False):
"""Create a serie for Flot from request"""
return {'label': labelize(criteria, lang),
'data': [(visit.key, visit.count)
for visit in results]} | 33101b0824dfa4979fdb1479d3f1f0ab23b72d80 | 3,607,916 |
def _bootstrap_sample(vel_data, v_table, samples, error):
"""Generate a Monte Carlo error sample of the differential distribution."""
# Generate some Monte Carlo samples where each element is perturbed by
# a Gaussian, sigma given by error.
index = np.random.random_integers(0, np.size(vel_data)-1, sampl... | eea62f2db0b4ed82f63324dab1add28459b3f90d | 3,607,917 |
def parse_punishment(argument):
"""Converts a punishment name to its code"""
punishments = {
"none": 0,
"note": 1,
"warn": 1,
"mute": 2,
"kick": 3,
"ban": 4
}
return punishments[argument.lower()] | 9ca9ad052c5636dd58f1b375296137de8b55712b | 3,607,918 |
def polygon_iou(list1, list2):
"""
Intersection over union between two shapely polygons.
"""
polygon_points1 = np.array(list1).reshape(4, 2)
poly1 = Polygon(polygon_points1).convex_hull
polygon_points2 = np.array(list2).reshape(4, 2)
poly2 = Polygon(polygon_points2).convex_hull
union_pol... | f3a84b480fc999d9a08db21148621320f1050e5a | 3,607,919 |
import re
def varnames2matlab(name, tmodel):
"""
Transforms reaction variable pairs from `('ACALD','ACALD_reverse_xxxxx')` to
`('F_ACALD','B_ACALD')` if it is a reaction, else leaves is as is
:return:
"""
reverse_regex = re.compile(r'(.+_reverse)_[a-f0-9]{5}')
new_name = name
if ... | d7dbf917b6d84d41fc825e912cd8817a22d02eba | 3,607,920 |
def get_total_fish(days):
"""
Returns a list of 7 elements containing the number of fish
that would be present after "days" days
"""
countdowns = {
0: 1,
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0,
7: 0,
8: 0,
}
fish_count = []... | ac2bb8d317ee6b9a7077429e55d0f2bf26f99ad2 | 3,607,921 |
from pathlib import Path
def _preconvert(item):
"""Preconverts objects from native types into JSONifyiable types"""
if isinstance(item, (set, frozenset)):
return list(item)
if isinstance(item, WrapModes):
return item.name
if isinstance(item, Path):
return str(item)
if calla... | 7ad7004f7b15de226fca14ae7f609bc04d920b94 | 3,607,922 |
def build_icon_from_cmap(cmap, width=24, height=24):
"""
Builds an icon representing the colormap
"""
data = zeros((width, height), uint8)
line = linspace(0, 255, width)
data[:, :] = line[:, newaxis]
img = toQImage(data)
img.setColorTable(cmap.colorTable(FULLRANGE))
return QIcon(QPix... | c3c33c143e6a6d75b836696c2fdba300556028e7 | 3,607,923 |
import socket
def http_proxy_connect(address, proxy, auth=None):
"""
Establish a socket connection through an HTTP proxy.
Arguments:
address (required) = The address of the target
proxy (required) = The address of the proxy server
auth (def: None) = A tuple of the userna... | f77b21647cf8141bc957c9e73ba847e5b0d9e3ee | 3,607,924 |
def lookup_wn(pos_tags, num_synsets):
"""Looks up the tokens on WordNet and annotates it with the first result
that is found. Returns a list of tuples with the word and the WordNet result."""
# To-do: incorporate named entities as fixed WordNet results, for
# example Celestial-Seasonings (organization) ... | 685367780d89bf043ba271036761602f904014be | 3,607,925 |
import configparser
def get_api_config(filename):
"""
Attempt to pull in twitter app API key and secret. If the key
and secret don't exist prompt for them.
Arguments:
filename -- name of the config file to try and parse
Returns:
config_api_store -- contains the twitter API key and s... | 8723e77f2cc30b9f102d141dd46b66a147ee67ef | 3,607,926 |
def make_sequences(texts, training_length = 50,
lower = True, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n'):
"""Turn a set of texts into sequences of integers"""
# Create the tokenizer object and train on texts
tokenizer = Tokenizer(lower=lower, filters=filters)
tokenizer.fit_o... | ac95162b90c7f6d8cafe3599b1a7ac2b78273ad1 | 3,607,927 |
import torch
def simple_dot_product(x, y):
"""
TODO: Implement a function that computes the dot product of
two rank 1 tensors and returns the result.
"""
return torch.dot(x, y) | 77637d037704da00ef6a6dbda456ced033d9de2a | 3,607,928 |
import requests
def read_unit_test_coverage(ci_jobs, repository):
"""Read and process unit test coverage."""
log.info("Reading unit test coverage")
url = ci_jobs.get_console_output_url(repository)
report_type = None
if url is not None:
response = requests.get(url)
if response.statu... | bbbc1dd004d27bdf80a72ba51eacce8597ed6058 | 3,607,929 |
def fetch(fp, path):
"""Fetches an array from hdf5 file.
:param str fp: hdf5 file path.
:param str path: path inside the hdf5 file.
:returns: An :class:`numpy.ndarray` representation of the corresponding hdf5 dataset.
"""
with h5py.File(fp, 'r') as f:
return f[path][:] | 563c20b1d63b28b6594586b3e3b16b1e47ac8ad8 | 3,607,930 |
def infix_to_postfix(infix_str):
"""Convert Infix to Postfix notation."""
infix_list = infix_str.split()
opstack = Stack()
postfix_list = []
for token in infix_list:
if is_operand(token):
postfix_list.append(token)
elif token == '(':
opstack.push('(')
... | dfe99e0f4897fd67efb66524ae7872f85ce926bd | 3,607,931 |
from typing import Any
from typing import Dict
import enum
def to_dictionary(obj: Any) -> Dict[str, Any]:
"""Creates a dictionary representation of a class instance. The
keys are taken from the API description and may differ from language
specific variable names of properties.
Args:
obj: The ... | b95bfe624899ebfce8db78ef30298f52220a8a29 | 3,607,932 |
from typing import Dict
from typing import Set
def reverse_graph(graph: Dict[ArrayOrNames, Set[ArrayOrNames]]) \
-> Dict[ArrayOrNames, Set[ArrayOrNames]]:
"""Reverses a graph.
:param graph: A :class:`dict` representation of a directed graph, mapping each
node to other nodes to which it is con... | 543d634adcea4557c3c95d5e9bdb08250977a4ac | 3,607,933 |
import os
import time
def predict_table(
model_path, data_path, glob, max_seq_len, batch_size, output_csv, stats
):
"""
See the preamble (help) for a description of these arguments.
For each file matching `glob`, the `raw_text` is parsed into sentences
and run through the classifier. Recognized e... | 24996c59f438c8fa26bd8598e4b4c755fdbc8985 | 3,607,934 |
def get_event_series_upload_path(series, filename):
"""Create upload path for an event series by primary key.
Required by model FileField/ImageField.
Args:
component (Series): Series object file is being added to.
filename (str): Filename of file.
Returns:
String of path and f... | b16996db081a1b3b1768e703fa916daee14c911c | 3,607,935 |
import re
import sys
def check_equation(equation):
"""checks the format of the equation"""
equation = equation.replace(" ", "")
equation = equation.upper()
if (re.search(input_format, equation) == None):
print("Error, wrong characters in equation")
sys.exit(0)
if (equation.count("=... | ca9b44d2ecead7c4ee89651a354435aea3693cf4 | 3,607,936 |
def stack_v3(x,
filters,
blocks,
bottleneck=False,
stride1=2,
expansion=4,
activation='leaky_relu',
bn_sync=BN_SYNC,
name=None):
"""A set of stacked residual blocks.
Arguments:
x: input tensor.
filters: integer, filters of the bottleneck layer in a block.... | bf037fd701f61168014163a57e47f03d56244aa6 | 3,607,937 |
import subprocess
import logging
def call_popen_output(cmd, log_output=True):
"""
Executes a command.
Parameters
----------
cmd: list
Command line as list of strings.
log_output: bool
Write error messages to logfile if set.
Returns
-------
str
The ... | b6a18cfbee596f7fb3af1afcf420985568ab354d | 3,607,938 |
from typing import Set
def dbc_dist(dbc_a: Openable, dbc_b: Openable) -> float:
"""
Calculate the "distance" between two DBC files, used for performance measuring. Compares only those
properties which physically influence the data on the wire, like signal bit position and size. Purely
semantic propert... | c1aa83219d16475670e0892dd49ca9bfa4459f7d | 3,607,939 |
def build_graph(x_placeholder, vocab_size, embedding_size, dropout_placeholder, sequence_length, filter_sizes,
num_filters, initW, pretrained=False, multichannel=False):
""" Build the computational graph for forward and backward propagation """
# Keeping track of l2 regularization loss
l2_l... | 1d48fef4d626f47bf92f855964d8e712c7015929 | 3,607,940 |
def get_sub_dataframe(data_df, boundaries_gdf, date_start, date_end, bin_sizes):
""" Returns count data inside the new york boroughs. """
df = data_df.copy()
#get data related only to PD_DESC_FILTER
if PD_DESC_FILTER is not None:
df = df[df['PD_DESC'] == PD_DESC_FILTER].copy()
#ge... | 5db6b1898c9e9dc190e2d8fb665e2e395fd87a0e | 3,607,941 |
def minspantree_helper(matrix, start_node, priority_queue, final_tree):
"""recursive helper function for question3()
inputs: adjacency dictionary, value of start node, priority queue, and final adjacency dict
output: final adjacency dict"""
# iterate through edges of start node
for tup in matrix[sta... | 9f0b56d7f2e60c269744ef265e531154cc87600a | 3,607,942 |
from typing import Optional
import tqdm
from datetime import datetime
from typing import Dict
from typing import Any
def describe(
config: Settings,
df: pd.DataFrame,
summarizer: BaseSummarizer,
typeset: VisionsTypeset,
sample: Optional[dict] = None,
) -> dict:
"""Calculate the statistics for ... | 4a1fee12d1946d7994a19937580d978afbc92e26 | 3,607,943 |
def square_root_with_type_annotations(x: float) -> float:
"""Computes the square root of x, using the Newton-Raphson method"""
return square_root(x) | 1facc3c44e00ba2ae71b43e478e4d4a7936ed46d | 3,607,944 |
def labrad_hdf5_get_parameters(dir_path, file_num, file_name):
"""
Get parameter settings from a labrad hdf5 file
Parameters
----------
dir_path : string
Usually this is "vault" directory
file_num : int
hdf5 file number. ex. '00033 - measurement_name.hdf5'
file_name : st... | 7b77073fdac63fd6e5d506d93566418d28a5dba7 | 3,607,945 |
def get_blue():
""" create a blue (friendly) actor """
# return name of actor, grazing speed, self defense
return 'Boar', 2 | d0776c362ff841dfdd635f089d6dac0c81d13993 | 3,607,946 |
def make_data_row(url, item_name, scrape_datetime, soup_result_item):
""" Returns dictionary """
# Dates and times
scrape_date = scrape_datetime.date().isoformat()
scrape_weekday = scrape_datetime.strftime('%A')
scrape_time = scrape_datetime.time().isoformat()
# Price data
product_size = so... | 356c76bd3c6b86b711c9964f2fe14b629942b3c2 | 3,607,947 |
def freq_to_wavenumber(freq, units_in='Hz', return_quantity=False,
units_out='cm-1'):
"""Converts frequency to wavenumber
Parameters
----------
freq : float
Frequency
units_in : str, optional
Units corresponding to ``freq``. Default is 'Hz'.
... | 2be9a318a63da98c9f3d0810d78d0f275cd5a721 | 3,607,948 |
def document_vector_gensim(doc):
"""Create document vectors by averaging word vectors. Remove out-of-vocabulary words."""
vocab_doc = [word for word in doc if word in gensim_vocab]
if len(vocab_doc) != 0:
return list(np.mean(gensim_embeddings.wv[vocab_doc], axis=0))
else:
retur... | 00274a8a7940c8e25821fd06013484a8a6568641 | 3,607,949 |
def const(a, b):
"""``const :: a -> b -> a``
Constant function.
"""
return a | 1b3e03d98ab495d1795d3e89d0a57728b1dcef47 | 3,607,950 |
def compute_wealth_moments(scf, bin_weights):
"""
This function computes moments (wealth shares, Gini coefficient,
var[ln(wealth)]) from the distribution of wealth using SCF data.
Args:
scf (Pandas DataFrame): pooled cross-sectional data from SCFs
bin_weights (Numpy Array) = ability wei... | 02b25221638b88ff8e63e1ad7d6eea05cd264d45 | 3,607,951 |
def photon_path(tau_max):
"""
This function tracks the path of photon exiting the core.
uncomment to get the mu and number of scattering.
"""
tau, mu = emit_photon(tau_max)
numOfScattered = 0
while tau >= 0:
tau, mu = scatter_photon(tau)
if tau > tau_max:
tau, mu ... | a7a994f718cfa8ea8d17081b56e144d32bbfd6d9 | 3,607,952 |
def make_issuing(vasp, idx):
"""
Populate variable fields in a certificate issued record
uses `fixtures/datagen/templates/no_cert.json` as template
"""
return make_unverified(vasp, idx, state="ISSUING_CERTIFICATE") | f42d4a9e58d629e4e40e571fe90f2451a86d6a2d | 3,607,953 |
def add_tages_ratio(uid, userid_grouped, flag):
""" 添加 tags 的比率 """
if flag == 0:
return -1
df = userid_grouped[uid]
if df.shape[0] == 0:
return -1
else:
return 1.0 * df[df['tags'] == ['None']].shape[0] / df.shape[0] | 2ea37f3ddc16654eb1a840ae4327e5acde8cbe39 | 3,607,954 |
def block3(x, filters, kernel_size=3, stride=1, groups=32, conv_shortcut=True, name=None):
"""A residual block.
Arguments:
x: input tensor.
filters: integer, filters of the bottleneck layer.
kernel_size: default 3, kernel size of the bottleneck layer.
stride: default 1, stride of the fi... | 214fa4bc19e6df639fe616f5c5f246d2cc1e5cfa | 3,607,955 |
import functools
def returns(*accepted_return_type_tuple):
"""
Validates the return type. Since there's only ever one
return type, this makes life simpler. Along with the
accepts() decorator, this also only does a check for
the top argument. For example you couldn't check
(<type 'tuple'>, <typ... | 16db31084cb284c45206580eba4f849017bb4ba0 | 3,607,956 |
import requests
def data_timestamp() -> pd.Timestamp:
"""Return the timestamp of the last commit to the .csv-file."""
r = requests.get(
r"https://api.github.com/repos/CSSEGISandData/COVID-19/commits",
params={
"path": r"csse_covid_19_data/csse_covid_19_time_series"
r"/t... | c36e6a69c152aefe70cb878660e9f6f7494713d0 | 3,607,957 |
import torch
def sharpness(predictions:list, total = True):
"""
Calculate the mean size of the intervals, called the sharpness (lower the better)
Parameters
----------
predictions : list
- predictions[0] = y_pred_upper, predicted upper limit of the target variable (torch.Tensor)
-... | 16c4fa826e9ffd4a42a3c987fc9fe6767feb9ebb | 3,607,958 |
def pause_scaling_group(request, log, tenantId, groupId):
"""
Pause a scaling group. This means that no scaling policies will get
executed (execution will be rejected). This is an idempotent operation -
pausing an already paused group does nothing.
"""
group = get_store().get_scaling_group(log... | 2d2299b7e8b3088252ee04768b90828367083f69 | 3,607,959 |
import os
def find_last_checkpoint_version(path_to_logs: str):
"""Sort the log directory to pick the last timestamped checkpoint filename."""
def get_time_from_version_name(name: str):
# name format example `version_16-10-2020_08-12-48`
timestamp = name[6:]
return timestamp
ckpt_... | 9a00bbc794aff0202c661286c4cc8b0d42193a8b | 3,607,960 |
import json
import uuid
def new_annotation(request, document_id):
"""Adds a annotation, queried by document id.
Edits the text pack of a document, queried by id.
The function is accessible for users with 'edit_annotation' permission of the project and the owner of the project.
Args:
docum... | 6e34a6be660bf2b601bff150779e92b4aa57ee57 | 3,607,961 |
def get_conf_file():
"""Return the path to the conf file."""
return get_option("config") or get_conf_file_path() | 1de81ad59d64472bd4b685b8471c773af4aa99e0 | 3,607,962 |
import numpy
def parse_endl_covariance(covFile):
"""
Returns a list of (energy bins, covariance matrix, covariance_type, [enminmax]) tuples.
The list may be empty (some ENDL cov.xml files are empty).
"""
xdoc = cElementTree.parse(covFile)
root = xdoc.getroot()
ebins, covariances, covaria... | 53823296d82712b091681eda69b0f9bce498df10 | 3,607,963 |
def unique(new_cmp_dict, old_cmp_dict):
"""Return a list dict of
the unique keys in new_cmp_dict
"""
newkeys = set(new_cmp_dict)
oldkeys = set(old_cmp_dict)
unique = newkeys - oldkeys
unique_ldict = []
for key in unique:
unique_ldict.append(new_cmp_dict[key])
return unique... | d67d356185b44718e3be788e37340b97a29df352 | 3,607,964 |
import click
def common_gateway_options(func):
"""Supply common gateway options."""
func = click.option(
"-v",
"--protocol_version",
help="Protocol version of the gateway.",
default="2.2",
show_default=True,
)(func)
func = click.option(
"-s", "--persiste... | 7611356364201f357623a873f8e35a37cbf4ff9a | 3,607,965 |
from typing import Iterable
def klasify(sers: Iterable, klases: Iterable, args: Iterable=None):
"""
Convert each qb64 serialization ser in sers to instance of corresponding
klas in klases modified by corresponding arg in args.
Useful for converting iterable of CESR serializations to associated iterab... | 7fead9f6965f4ea24e08f734c529eb04b84d038e | 3,607,966 |
def render(template_name, **kwargs):
"""Функция рендеринга шаблонов"""
template = jinja_env.get_template(template_name)
return template.render(**kwargs) | df812e7857cfb79020cdca0a47b231c4e322f692 | 3,607,967 |
import asyncio
async def _createServer(host, port):
"""
Create async server that listens host:port, reads client request and puts
value to some future that can be used then for checks
:return: reference to server and future for request
"""
indicator = asyncio.Future()
async def _handle(r... | bbd21ede887ae93ba8127aa1bb0a9ff4264b8399 | 3,607,968 |
def interval(*intervals):
"""Decorate a function to be called by the bot every *n* seconds.
:param int intervals: one or more duration(s), in seconds
This decorator can be used multiple times for multiple intervals, or
multiple intervals can be given in multiple arguments. The first time the
funct... | 4d580cea0853228896c8dec2308a243376c56770 | 3,607,969 |
import re
def generate_ignore_character():
"""
生成删除无效字符的pattern和dict
:return:
"""
translate_list = const.USELESS_STRING_LIST
translate_dict = {items: '' for items in translate_list}
translate_dict = dict((re.escape(key), value) for key, value in translate_dict.items())
pattern = re.com... | d2d50f71ea22b4f7b397c0c87248ef540207ee2d | 3,607,970 |
import os
def dir_test_data():
""" Return path to the data directory in tests"""
current_file_dir = os.dirname(__file__)
return os.path_join(current_file_dir, "data") | 44a2beb384ae82afb752e0022ab07dd2e9a8ef2a | 3,607,971 |
import datasets
import os
def _get_filename_by_index(dataset, index):
"""Default function which maps the index of an image to a filename.
"""
if isinstance(dataset, datasets.ImageFolder):
# filename is the path of the image relative to the dataset root
full_path = dataset.imgs[index][0]
... | d18dfd11cb8ec3823af219f1b6713a2900baeedf | 3,607,972 |
def _exclude_swift_incompatible_define(define):
"""A `map_each` helper that excludes a define if it is not Swift-compatible.
This function rejects any defines that are not of the form `FOO=1` or `FOO`.
Note that in C-family languages, the option `-DFOO` is equivalent to
`-DFOO=1` so we must preserve bo... | 9ce87f52f8829636364e2671f59a0eb9e66f5a9b | 3,607,973 |
def get_user_url(username: str) -> str:
"""Get user page's URL.
"""
return f"{PREFIX}user/{username}" | 79e0d5220e6106d81e619a40bee0fc6682f2d064 | 3,607,974 |
def get_expected_data_from_company_referral(referral):
"""Returns company referral data as a dictionary"""
return {
'company_id': str(referral.company_id),
'completed_by_id': get_attr_or_none(referral, 'completed_by_id'),
'completed_on': format_date_or_datetime(referral.completed_on),
... | a8398a62c8042f87775cb767ef0a730dd37ce3f5 | 3,607,975 |
def get_prediction(id_, url=DEFAULT_URL):
"""
Get the predictions for a specific submission.
Parameters
----------
id_ : int
The id of the submission.
url : str
The url of the running Flask app.
Returns
-------
prediction : pd.DataFrame
"""
return pd.read_cs... | c2edf224a047b3c9f655b0f6b86fc089c86e9d0f | 3,607,976 |
def commands_almost_equal(command1: str, command2: str, delta: float = 1.0) -> bool:
"""Check if two commands are almost equal.
Almost equal means we allow numerical parts in the commands to differ by the defined delta.
Args:
command1 (str): first command.
command2 (str): s... | 4d75afadb2b6db5911a227d205c81f4cbfdc7f01 | 3,607,977 |
import re
def hex_color_code(value: str):
"""
Hex color validator
Example Result:
[#00ff00,
#fff]
"""
_hex_color_pat = r'#(?:[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})'
return re.findall(_hex_color_pat, value) | 760db0bd1b729b62171b6964d1615546e32dbe52 | 3,607,978 |
def get_charge_composition(charge):
"""Return the composition of a given charge (only H+).
Parameters
----------
charge : int
Peptide charge.
Returns
-------
pyteomics.mass.Composition
Composition of the change (H+).
"""
charge_composition = mass.Composition()
... | d76483b5ca43b25f50d6d779bf772a4fb2f2019c | 3,607,979 |
def parse_value(type, val):
"""
Parses a given OBD value of a given type (PID)
and returns the parsed value.
If the PID is unknown / not implemented a PIDParserUnknownError
will be raised including the type which was unknown
:param type:
:param val:
:return:
"""
if type in PARSER... | 2933b8125a4e2a67cd6089583712e42d0fe37361 | 3,607,980 |
import re
import logging
def parse(fqdn):
"""Parses an M-Lab FQDN into its constituent parts.
Args:
fqdn: str, an M-Lab FQDN e.g., ndt-iupui-mlab1-den05.mlab-oti.measurement-lab.org
Returns:
dict representing the constituent parts.
"""
# This regex *should* match all valid M-Lab ... | a05a7125b1818668dc681be460a326c2a5a2f065 | 3,607,981 |
def buffer_type(request):
"""
Fixture that yields types that support the buffer protocol.
"""
return request.param | afc79bf3ac5bfeb53fe9cb8de707b2f0a93ae6f8 | 3,607,982 |
def minargmin(sequence):
"""Returns the minimum value and the first index at which it can be
found in the input sequence."""
best = (None, None)
for (i, value) in enumerate(sequence):
if best[0] is None or value < best[0]:
best = (value, i)
return best | cf66ccd0dc76d3530fe7b2503bb3ed3b31c7ba61 | 3,607,983 |
import torch
def test(epoch, test_loader_mnist):
"""
Network evaluation, testing stage
"""
net.eval()
test_accuracy = 0
test_loss = 0
with torch.no_grad():
for idx, (img, target) in enumerate(test_loader_mnist):
output, _, _ = net(img)
loss = criterion(outpu... | 30f1c64505b13897ea05420d4db6722cfa2a2d96 | 3,607,984 |
def silent_preload(silent_file_path):
"""
Returns index,out
"""
# sfd = pyrosetta.rosetta.core.io.silent.SilentFileData(
# pyrosetta.rosetta.core.io.silent.SilentFileOptions()
# )
# sfd.read_file(silent_file_path)
silent_index = silent_tools.get_silent_index(silent_file_path)
s... | 0d7ca76ed3c8ad87e2f7b718abe6a8169002e8d5 | 3,607,985 |
def django_id_to_cloudsearch(s):
""" convert haystack ids to legal cloudsearch index field names """
return s.replace('.', '__') | e70a5961b5189b1177b5ba2adeac3287ca2fc091 | 3,607,986 |
import time
def validate_address(addr_spec, metrics=False):
"""
Given an addr-spec, runs the pre-parser, the parser, DNS MX checks,
MX existence checks, and if available, ESP specific grammar for the
local part.
In the case of a valid address returns an EmailAddress object, otherwise
returns ... | 4f762d7658261a5b514331bf79b7c4c8c009510d | 3,607,987 |
import signal
def input_to(getch, timeout=0.3):
"""Taking input from user."""
signal.signal(signal.SIGALRM, alarmHandler)
signal.setitimer(signal.ITIMER_REAL, timeout)
try:
text = getch()
signal.alarm(0)
return text
except AlarmException:
signal.signal(signal.SIGALR... | 823e27adec266d81f5f1760faea7f110c02e05a5 | 3,607,988 |
def get_data(self):
"""Generate the toothsaw vector
Parameters
----------
self : ImportGenToothSaw
An ImportGenToothSaw object
Returns
-------
vect: ndarray
The generated toothsaw vector
"""
time = linspace(start=0, stop=self.Tf, num=self.N, endpoint=False)
T... | aaaa6a58b5f383c5e20bce3b8a9f86c3bb23589e | 3,607,989 |
def _is_eqsine(opts):
"""
Checks to see if 'eqsine' option is set to true
Parameters
----------
opts : dict
Dictionary of :func:`pyyeti.srs.srs` options; can be empty.
Returns
-------
flag : bool
True if the eqsine option is set to true.
"""
if "eqsine" in opts:... | 3515a75eb2c0976198700e1fe068cd15b0017d8f | 3,607,990 |
from typing import Union
from datetime import datetime
def dividends(date: Union[str, datetime.date, None] = None, filter: str = ''):
"""
This call details upcoming dividend information and other corporate actions, such as stock splits, for IEX-listed
securities.
Records are added once known by the E... | 489f8a2b4904ae2e92ebcf8386769e0353f58f28 | 3,607,991 |
from cla_frontend.apps.status.tests.smoketests import SmokeTests
def smoketests_json(request):
"""
Run smoke tests and return results as JSON datastructure
"""
return JsonResponse(smoketest(SmokeTests)) | 72ba96fa2538cf60ce59ca6c067ea78eb558dbc0 | 3,607,992 |
def request_preemptible_resource_with_priority_in_parallel(preemptible_resource_port, priority_expr, stream_port):
"""Request for or preempt the resource in case of need with the given priority in parallel without delaying the current stream of data.
The less priority is higher. The priority must be specifi... | 4df26ccdcc79b1b0f913677cd84a1e5e9a1af3ab | 3,607,993 |
def get_title(unique_reasons, top_n_worst):
"""generate the report title"""
title_end = ""
if unique_reasons:
title_end = "uniquely bad"
else:
title_end = "worst"
title = "top %i %s" % (top_n_worst, title_end)
underline = util.write_underline(title)
return "%s\n%s\n" % (title... | 6e78fe2eeadd75421092f36c257bb79d3f93f2cd | 3,607,994 |
from typing import Callable
from typing import List
def generate_definition(cls: Callable) -> List[str]:
"""Generates a function signature from a pyDantic class object"""
# Fetch parameters
params = cls.__annotations__
return [
f"{name}: {data_type},"
if "Optional" not in data_type
... | 2e0a40875f78eb07733fa94fbadbd1d5ee06f2c7 | 3,607,995 |
def expressionToAST(ex):
"""Take an expression tree made out of expressions.ExpressionNode,
and convert to an AST tree.
This is necessary as ExpressionNode overrides many methods to act
like a number.
"""
return ASTNode(ex.astType, ex.astKind, ex.value,
[expressionToAST(c) fo... | 188de9b51e6f05a72f5efc094a64f1960d55b5fc | 3,607,996 |
import itertools
def _limited_walk(node, app):
"""Walk the tree like preorder, expand nodes iff placement is feasible."""
if node.check_app_constraints(app):
return itertools.chain(
[node],
*[_limited_walk(child, app) for child in node.children]
)
else:
retu... | 663a107264e33115f0cbacf1e791db4b662db991 | 3,607,997 |
def preprocessing(questions):
""" 对问题预处理
Args:
questions: 从数据库中获取的问题
Returns:
dictionary: 基于问题分词后构建的词典
texts: 分词后的问题
"""
# 1.分词,去除停用词
stoplist = set('的 ? ? 能 与 和 是'.split())
# 载入自定义词典
# 这里如果php调用就不能写相对路径啦,要写绝对路径才可以的
# jieba.load_userdict('../dict.txt')
... | 69f94ecdd33353a29f3dc703fd8bf134c76398e3 | 3,607,998 |
import os
def test_user_invalid_max_tweets(sample_users):
"""
Check that an improper max_tweets value in the config raises a
ValueError exception
"""
error_str = 'max_tweets must be between 10 and 100. max_tweets: 5'
with pytest.raises(ValueError) as error_info:
for sample_user in samp... | 1b74ca1201ffb4f54f932dbe22ac121bf5b322bf | 3,607,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.