content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def dummy_annotation_txt_one_segment(tmpdir_factory):
"""Create empty TXT annotations."""
content = ("# MNE-Annotations\n"
"# onset, duration, description\n"
"3.14, 42, AA")
fname = tmpdir_factory.mktemp('data').join('one-annotations.txt')
fname.write(content)
return fn... | 30,600 |
def article_title_meets_posting_requirements(website, article_title):
"""
Validates that the article title meets all requirements to post the list to Reddit.
The validations below check if:
(1) The article contains a number
(2) The article title doesn't contain certain pre-defined keywords
... | 30,601 |
def about():
""" returns about page """
counter = json.load(open(r'filter/OXAs_dict/counter.txt'))
ids = [*counter]
r = csv.reader(open(r'Training_data/Training_data_IC.csv'))
df = pd.DataFrame(data=list(r))
svm_table = df.to_html(index=False, header=False)
return render_template('About.html... | 30,602 |
async def _snipe_deleted_message_command(ctx: SlashContext) -> None:
"""Snipe a deleted message"""
Logger.log(f"Snipe slash command called in channel ID {ctx.channel.id}")
# There's a deleted message available
if ctx.channel.id in MessageDatabases.deleted_messages:
deleted_message: dict = Messa... | 30,603 |
def phys_mem_regions_from_elf(elf: ElfFile, alignment: int) -> List[MemoryRegion]:
"""Determine the physical memory regions for an ELF file with a given
alignment.
The returned region shall be extended (if necessary) so that the start
and end are congruent with the specified alignment (usually a page s... | 30,604 |
def force_float_to_int_in_any_way(x):
"""This force a float to be converted to an int.
Any float is fine. The result is truncated.
Like PHP, if the input float is greater than 2**63, then the result
is 0, even if intmask(int(f)) would return some bits."""
# magic values coming from pypy.rlib.rarith... | 30,605 |
def where(condition : pdarray, A : Union[Union[int,float], pdarray],
B : Union[Union[int,float], pdarray]) -> pdarray:
"""
Returns an array with elements chosen from A and B based upon a
conditioning array. As is the case with numpy.where, the return array
consists of values fr... | 30,606 |
def pre_training_configs(m):
"""
Before training the model, configure it
"""
ordering = range(m.n_visible)
np.random.shuffle(ordering)
trainer = Optimization.MomentumSGD(m.nade, m.nade.__getattribute__(m.loss_function))
trainer.set_datasets([m.training_dataset, m.masks_dataset])
trainer... | 30,607 |
def si_pbesol_nomeshsym(request):
"""Return Phono3py instance of Si 2x2x2.
* without mesh-symmetry
* no fc
"""
yaml_filename = os.path.join(current_dir, "phono3py_si_pbesol.yaml")
forces_fc3_filename = os.path.join(current_dir, "FORCES_FC3_si_pbesol")
enable_v2 = request.config.getoption("... | 30,608 |
def describe_workspace_snapshots(WorkspaceId=None):
"""
Describes the snapshots for the specified WorkSpace.
See also: AWS API Documentation
Exceptions
:example: response = client.describe_workspace_snapshots(
WorkspaceId='string'
)
:type WorkspaceId: string
:... | 30,609 |
def loadClusterModule(pathCheckpoint):
"""
Load CPC Clustering Module from Clustering checkpoint file.
"""
state_dict = torch.load(pathCheckpoint, map_location=torch.device('cpu'))
clusterModule = kMeanCluster(torch.zeros(1, state_dict["n_clusters"], state_dict["dim"]))
clusterModule.load_state_... | 30,610 |
def bash_inline_create_file(name, contents):
"""
Turns a file into bash command.
Parameters
----------
name : str
File name.
contents : bytes
File contents.
Returns
-------
result : str
The resulting command that creates this file.
"""
return f"echo ... | 30,611 |
def rtf_encode(unicode_string):
"""
Converts HTML encoding and Unicode encoding to RTF.
Be sure that autoescaping is off in the template. Autoescaping converts <, >, ", ', &
The unescape function used here is helpful for catching additional escape sequences used for special
characters, greek letters... | 30,612 |
def test_should_get_default_conf_file_path():
"""
Test get default configuration file path
"""
conf_file_path = get_conf_file_default_path(work_dir='test')
assert conf_file_path == join('test', DEFAULT_CONF_FILENAME) | 30,613 |
def get_P(A):
"""
Markov matrix.
P = D^{-1}*A
"""
D = get_D(A)
return np.linalg.inv(D).dot(A) | 30,614 |
def check_file(option, opt_str, value, _parser):
"""See if a file exists on the file system, raises an OptionValueError"""
if not os.path.isfile(value):
raise OptionValueError("Cannot open %s as a file. Please check if it exists." % value)
setattr(_parser.values, option.dest, value) | 30,615 |
def get_movie_and_zmw_from_name(name):
"""Given a string of pacbio zmw name or read name, return movie and zmw"""
try:
fs = name.strip().split(' ')[0].split('/')
movie, zmw = fs[0], fs[1]
return movie, int(zmw)
except ValueError:
raise ValueError("Read %r is not a PacBio read... | 30,616 |
def create_sp_history_copy(sp):
"""
Create a history copy of SP, with end_at value and new pk
return: created service provider object
"""
admins = sp.admins.all()
admin_groups = sp.admin_groups.all()
nameidformat = sp.nameidformat.all()
grant_types = sp.grant_types.all()
response_ty... | 30,617 |
def test_database_error():
"""
test database error
"""
err = errors.DatabaseError()
assert err.status == errors.DatabaseError.status
assert err.title == errors.DatabaseError.title
err = errors.DatabaseError(title='Stuff Happens', status=1990)
assert err.status == 1990
assert err.ti... | 30,618 |
def onehot(arr, num_classes=None, safe=True):
"""
Function to take in a 1D label array and returns the one hot encoded
transformation.
"""
arr = exactly_1d(arr)
if num_classes is None:
num_classes = np.unique(arr).shape[0]
if safe:
if num_classes != np.unique(arr).shape[0]:
... | 30,619 |
def scale_relative_sea_level_rise_rate(mmyr: float, If: float = 1) -> float:
"""Scale a relative sea level rise rate to model time.
This function scales any relative sea level rise rate (RSLR) (e.g., sea
level rise, subsidence) to a rate appropriate for the model time. This is
helpful, because most dis... | 30,620 |
def get_covalent1_radius(Z):
"""
Converts array of nuclear charges to array of corresponding valence.
Args:
Z (numpy ndarray): array with nuclear charges
Returns:
numpy ndarray: array of the same size as Z with the valence of the corresponding atom
"""
global _elements
if _elements is None:
_elem... | 30,621 |
def get_bank_sizes(num_constraints: int,
beam_size: int,
candidate_counts: List[int]) -> List[int]:
"""
Evenly distributes the beam across the banks, where each bank is a portion of the beam devoted
to hypotheses having met the same number of constraints, 0..num_constra... | 30,622 |
def test_files(host, f):
"""Test that the expected files were installed."""
assert host.file(f).exists
assert host.file(f).is_file
assert host.file(f).user == "root"
assert host.file(f).group == "root"
assert host.file(f).mode == 0o600 | 30,623 |
def ssh_connect(openstack_properties):
"""Create a connection to a server via SSH.
Args:
openstack_properties (dict): OpenStack facts and variables from Ansible
which can be used to manipulate OpenStack objects.
Returns:
def: A factory function object.
"""
connections ... | 30,624 |
def test_isup_command_http_error(irc, bot, user, requests_mock):
"""Test URL that returns an HTTP error code."""
requests_mock.head(
'http://example.com',
status_code=503,
reason='Service Unavailable',
)
irc.pm(user, '.isup example.com')
assert len(bot.backend.message_sent)... | 30,625 |
def _season_store_metadata(
db: sql.Connection,
classification: str | int,
start_date: date | None,
stop_date: date | None,
playlist_id: str,
):
"""Saves metadata for a single season in the database"""
# TODO Duplicate Check
min_year = start_date.year if start_date else None
if stop_... | 30,626 |
def prepare(args: dict, overwriting: bool):
"""Load config and key file,create output directories and setup log files.
Args:
args (dict): argparser dictionary
Returns:
Path: output directory path
"""
output_dir = make_dir(args, "results_tmp", "activity_formatting", overwriting)
... | 30,627 |
def parse_data(data):
"""Takes a string from a repr(WSGIRequest) and transliterates it
This is incredibly gross "parsing" code that takes the WSGIRequest
string from an error email and turns it into something that
vaguely resembles the original WSGIRequest so that we can send
it through the system ... | 30,628 |
def create_slack_context_block(elements: List[SlackBlock]) -> dict:
"""
Creates a "context block" as described in the slack documentation here:
https://api.slack.com/reference/messaging/blocks#context
"""
return {
'type': 'context',
'elements': [element.get_formatted_block() for elem... | 30,629 |
def script_synthesize_filters(config):
""" The scripting version of `synthesize_masks`. This function
applies the filter to the entire directory (or single file). It
combines the filter files from the data directory.
Parameters
----------
config : ConfigObj
The configuration object... | 30,630 |
def sample_bar_report(request):
"""
Demonstrates a basic horizontal bar chart report.
"""
profile = request.get_user_profile()
if not profile.super_admin:
raise PermissionDenied('Only super admins can view this report.')
# Run your custom report logic to build the following lists:
#... | 30,631 |
def _is_ref_path(path_elements):
"""
Determine whether the given object path, expressed as an element list
(see _element_list_to_object_path()), ends with a reference and is
therefore eligible for continuation through the reference. The given
object path is assumed to be "completed" down to a singl... | 30,632 |
def apply_along_axis(func1d, axis, arr, *args, **kwargs):
"""Apply the harmonic analysis to 1-D slices along the given axis."""
arr = dask.array.core.asarray(arr)
# Validate and normalize axis.
arr.shape[axis]
axis = len(arr.shape[:axis])
# Rechunk so that analyze is applied over the full axis... | 30,633 |
def current_time_utc(conf):
""" Get time in UTC """
UTC = pytz.utc
curr_time = datetime.now(UTC)
return curr_time | 30,634 |
def CORe50(root=expanduser("~") + "/.avalanche/data/core50/",
scenario="nicv2_391",
run=0,
train_transform=None,
eval_transform=None):
"""
Creates a CL scenario for CORe50.
If the dataset is not present in the computer, this method will
automatically... | 30,635 |
def create_results_dir():
"""
Creates results directory
"""
if not os.path.exists(get_results_dir()):
os.makedirs(get_results_dir()) | 30,636 |
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
res = []
for ele in line:
res.append(ele)
for num in res:
if num == 0:
res = shift(res,res.index(num))
for inde in range(len(res)-1):
if res[inde] == res[inde+1]:
... | 30,637 |
def image_to_bytes(image: "PIL.Image.Image") -> bytes:
"""Convert a PIL Image object to bytes using native compression if possible, otherwise use PNG compression."""
buffer = BytesIO()
format = image.format if image.format in list_image_compression_formats() else "PNG"
image.save(buffer, format=format)
... | 30,638 |
def add_transform(transform_type, transform_tag=None, priority=0, status=TransformStatus.New, locking=TransformLocking.Idle,
retries=0, expired_at=None, transform_metadata=None, workprogress_id=None, session=None):
"""
Add a transform.
:param transform_type: Transform type.
:param tra... | 30,639 |
def load_memmap(path):
"""load_memmap方法用于读取共享数据
Parameters
----------
path : str
文件路径
Returns
----------
"""
memmap_data = joblib.load(path, mmap_mode='r+')
return memmap_data | 30,640 |
def _classical_routine_on_result(
N: int, t: int, x: int, measurement
) -> Tuple[enum.Enum, Optional[Tuple[int, ...]]]:
"""Try to find factors, given x,N,t and the result of a single quantum measurement.
:param N: number to factorise
:param t: number of qubits
:param x: random integer between 0 < x... | 30,641 |
def bump(chart_path: Path):
"""Bump the given Chart to the next patch version."""
next_patch = get_next_patch(chart_path)
print(f"🚢 🆙 Bumping {chart_path} to {next_patch}")
bump_with_version(chart_path, next_patch) | 30,642 |
def get_rst_cls_file_header(collection_name, class_name):
"""produce the rst content to begin an attribute-level *.rst file"""
# use :doc:`class_name<index>` syntax to create reference back to the index.rst file
title = ":doc:`%s<../index>` %s" % (collection_name.capitalize(), class_name)
return get_rs... | 30,643 |
def is_leap(year):
"""
Simply returns true or false depending on if it's leap or not.
"""
return not year%400 or not (year%4 and year%100) | 30,644 |
def ForwardDynamics(thetalist, dthetalist, taulist, g, Ftip, Mlist, \
Glist, Slist):
"""Computes forward dynamics in the space frame for an open chain robot
:param thetalist: A list of joint variables
:param dthetalist: A list of joint rates
:param taulist: An n-vector of joint force... | 30,645 |
def submission_received(submission):
"""Send notifications if this is the first submission"""
attribute_state = inspect(submission).attrs.get('version')
# Check if the speaker has been updated
history = attribute_state.history
# TODO Check for insert rather than assuming the version is immutable
... | 30,646 |
def union(dataframe1, dataframe2) -> pd.DataFrame:
"""The set union between dataframe1 (S) and dataframe2 (T), i.e. it returns the elements that are both in dataframe1
and dataframe2. Formally S ∩ T = {s|s ∈ S and s ∈ T}.
If duplicates exists in either dataframe they are dropped and a UserWarning is is... | 30,647 |
def get_axis_periodic(self, Nper, is_antiperiod=False):
"""Returns the vector 'axis' taking symmetries into account.
Parameters
----------
self: Data1D
a Data1D object
Nper: int
number of periods
is_antiperiod: bool
return values on a semi period (only for antiperiodic si... | 30,648 |
def compute(data, function, key):
"""Calculate some measures.
For single-value measures (like average or median, for example) you need
to specify only one key.
"""
func = COMPUTE_FUNCTIONS[function]
values = [float(value) for value in data]
print func(values) | 30,649 |
def knapsack_fractional(weights,values,capacity):
""" takes weights and values of items and capacity of knapsack as input
and returns the maximum profit possible for the given capacity of knapsack
using the fractional knapsack algorithm"""
#initialisaing the value of max_profit variable
max_profit=... | 30,650 |
def p_subscript_list(p):
""" subscript_list : subscript
| subscript subscript_list"""
if len(p) == 3:
p[0] = [p[1]] + p[2]
else:
p[0] = [] if p[1] is None else [p[1]] | 30,651 |
def check_protonation(selection):
"""
Check if the structure is protonated or not. In case that is not protonated we will rise a critical logger.
:param selection: prody molecule
:return: if not hydrogens detected, prints a message.
"""
try:
if not selection.select("hydrogen"):
... | 30,652 |
def verifier_delete(verifier_id):
"""Delete a verifier record.
:param verifier_id: verifier name or UUID
:raises ResourceNotFound: if verifier does not exist
"""
get_impl().verifier_delete(verifier_id) | 30,653 |
def invert(values: np.array, inversion: int) -> np.array:
"""Return the specified musical inversion of the values."""
if np.abs(inversion) > (len(values) - 1):
raise ValueError("Inversion out of range")
return np.hstack([values[inversion:], values[:inversion]]).astype(int) | 30,654 |
def set_logger(**cli_kwargs):
"""Configured logger.
Sets up handlers for stdout and for output file if the user
passed an output file name.
Sets up message format and level.
:param cli_kwargs: The key/value pairs depicting the CLI arguments
given by the user.
"""
# Setup basic log... | 30,655 |
def prepare_infrastructure():
"""Entry point for preparing the infrastructure in a specific env."""
runner = ForemastRunner()
runner.write_configs()
runner.create_app()
runner.create_iam()
runner.create_s3()
runner.create_secgroups()
eureka = runner.configs[runner.env]['app']['eureka_e... | 30,656 |
def get_libpath():
"""
Get the library path of the the distributed SSA library.
"""
import os
import re
from os.path import dirname, abspath, realpath, join
from platform import system
root = dirname(abspath(realpath(__file__)))
if system() == 'Linux':
librar... | 30,657 |
def getthumb(episode,target="."):
"""
Passed an episode dictionary, retrieves the episode thumbnail & saves with appropriate filename
"""
fn = f"s{episode['airedSeason']:02}e{episode['airedEpisodeNumber']:02}.{episode['episodeName']}.jpg"
fn = os.path.join(target,fn.replace(" ",""))
url = "https... | 30,658 |
def engine_factory(database_url: str) -> Engine:
"""Construct database connection pool."""
url = make_url(database_url)
engine_kwargs: dict[str, Any] = {}
if url.host == "localhost":
engine_kwargs = {
**engine_kwargs,
"connect_args": {"connect_timeout": 1},
"e... | 30,659 |
def _shear_x(video: torch.Tensor, factor: float, **kwargs):
"""
Shear the video along the horizontal axis.
Args:
video (torch.Tensor): Video tensor with shape (T, C, H, W).
factor (float): How much to shear along the horizontal axis using the affine
matrix.
"""
_check_fi... | 30,660 |
def get_smtp_credentials(filters: Optional[Sequence[pulumi.InputType['GetSmtpCredentialsFilterArgs']]] = None,
user_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSmtpCredentialsResult:
"""
This data source provides the lis... | 30,661 |
def coord(row, col):
""" returns coordinate values of specific cell within Sudoku Puzzle"""
return row*9+col | 30,662 |
def analyse_decoupled_steady_state_data( # pylint: disable=too-many-branches
data: Dict[Any, Dict[str, Any]], logger: Logger
) -> None:
"""
Carry out analysis on a series of of steady-state data sets.
:param data:
The data to analyse. This should be a `dict` mapping the file name to the data
... | 30,663 |
def add_interface_ngeo(
config: pyramid.config.Configurator,
route_name: str,
route: str,
renderer: Optional[str] = None,
permission: Optional[str] = None,
) -> None:
"""Add the ngeo interfaces views and routes."""
config.add_route(route_name, route, request_method="GET")
# Permalink th... | 30,664 |
def post_authn_parse(request, client_id, endpoint_context, **kwargs):
"""
:param request:
:param client_id:
:param endpoint_context:
:param kwargs:
:return:
"""
if endpoint_context.args["pkce"]["essential"] is True:
if not "code_challenge" in request:
raise ValueErro... | 30,665 |
def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Argparse Python script',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'positional', metavar='DIR', help='A positional argument', nargs='+')
#nargs=... | 30,666 |
def token2hot(seq, max_length, n_features):
"""
takes in tokenized sequences and returns 1-hot encoded
[1 2 2] -> [1 0 0 0], [0 1 0 0 ], [0 1 0 0]
"""
N = max_length - len(seq)
x = np.pad(seq, (0, N), 'constant')
x = F.one_hot(torch.tensor(x),num_classes=n_features)
return x | 30,667 |
def is_repo_on_known_branch(path):
"""Check if we're on the most recent commit in a well known branch, 'master' or
a version branch."""
remote = find_upstream_remote(None, path)
branches = execute_git(
None,
path,
[
"for-each-ref",
"--format=%(refname:sh... | 30,668 |
def setup(hass, config):
"""Initialize the ADTPulse integration"""
conf = config[ADTPULSE_DOMAIN]
username = conf.get(CONF_USERNAME)
password = conf.get(CONF_PASSWORD)
try:
# share reference to the service with other components/platforms running within HASS
from pyadtpulse import P... | 30,669 |
def external_query( # pylint: disable=too-many-arguments
gcs_client: storage.Client, bq_client: bigquery.Client, gsurl: str,
query: str, job_id: str, table: bigquery.TableReference):
"""Load from query over external table from GCS.
This hinges on a SQL query defined in GCS at _config/*.sql and... | 30,670 |
def get_args():
"""Get the command line arguments for ``tcp-h2-describe``.
Returns:
Tuple[int, int, Optional[str]]: A triple of
* The port for the "describe" proxy
* The port for the server that is being proxied
* The hostname for the server that is being proxied (or :data:`None` if... | 30,671 |
def _Install(vm):
"""Install maven package."""
vm.Install('openjdk')
vm.Install('curl')
# Download and extract maven
maven_full_ver = FLAGS.maven_version
maven_major_ver = maven_full_ver[:maven_full_ver.index('.')]
maven_url = MVN_URL.format(maven_major_ver, maven_full_ver)
maven_tar = maven_url.split(... | 30,672 |
def merge_shopping_cart(sender, user, request, **kwargs):
"""
Check if there are items in shopping cart before login,
merge guest shopping cart to user cart and remove guest cart data
uuid cookie will be expired in 7 days
"""
try:
uuid = request.COOKIES['uuid']
conn = get_redis_... | 30,673 |
def make_key(ns_sep, namespace, *names):
"""Make a redis namespaced key.
>>> make_key(":", "YOO:HOO", "a", "b", "c") == "YOO:HOO:a:b:c"
True
"""
return ns_sep.join(chain((namespace,), names)) | 30,674 |
def test_session_env_lazy(monkeypatch, gdalenv):
"""Create an Env with AWS env vars."""
monkeypatch.setenv('AWS_ACCESS_KEY_ID', 'id')
monkeypatch.setenv('AWS_SECRET_ACCESS_KEY', 'key')
monkeypatch.setenv('AWS_SESSION_TOKEN', 'token')
with rasterio.Env() as s:
s.get_aws_credentials()
... | 30,675 |
def gas_strand_2pipes(method="nikuradse"):
"""
:param method: Which results should be loaded: nikuradse or prandtl-colebrook
:type method: str, default "nikuradse"
:return: net - STANET network converted to a pandapipes network
:rtype: pandapipesNet
:Example:
>>> pandapipes.networks.si... | 30,676 |
def directly_follows(logs_traces, all_activs, noise_threshold=0):
"""
Gets the allowed directly-follows relations given the traces of the log
Parameters
-------------
logs_traces
Traces of the log
all_activs
All the activities
noise_threshold
Noise threshold
Ret... | 30,677 |
def python_name(env_dirpath: Union[Path, str]) -> str:
"""Find the name of the Python in a virtual environment.
Args:
env_dirpath: The path to the root of a virtual environment (Path or str).
Returns:
A descriptive string.
Raises:
ValueError: If the env_dirpath is not a virtua... | 30,678 |
def hfc(x, framesize=1024, hopsize=512, fs=44100):
"""
Calculate HFC (High Frequency Content)
Parameters:
inData: ndarray
input signal
framesize: int
framesize
hopsize: int
hopsize
fs: int
samplingrate
Returns:
result: ndarray
... | 30,679 |
def validate_security_requirement_object(security_requirement_object):
"""
:param security_requirement_object:
"""
pass | 30,680 |
def acronym_buster(message):
"""
Find the first group of words that is in all caps
check if it is in the ACRONYMS dict
if it is, return the first occurrence of the acronym
else return [acronym] is an acronym. I do not like acronyms. Please remove them from your email.
:param message: The message... | 30,681 |
def get_backup_temp_2():
"""
This is the third way to get the temperature
"""
try:
temp = RFM69.temperature
logging.warning("Got second backup temperature")
return temp
except RuntimeError:
logging.error("RFM69 not connected")
return 2222
except... | 30,682 |
def constructed(function):
"""A decorator function for calling when a class is constructed."""
def store_constructed(class_reference):
"""Store the key map."""
setattr(class_reference, "__deserialize_constructed__", function)
return class_reference
return store_constructed | 30,683 |
def generate_functions(
function,
parameters,
name,
name_func,
tag_dict,
tag_func,
docstring_func,
summarize,
num_passing,
num_failing,
key_combs_limit,
execution_group,
timeout,
):
"""
Generate test cases using the given parameter context, use the name_func
... | 30,684 |
def tdt(input_dir_path, experiment_name="Thellier", meas_file_name="measurements.txt",
spec_file_name="specimens.txt", samp_file_name="samples.txt",
site_file_name="sites.txt", loc_file_name="locations.txt",
user="", location="", lab_dec=0, lab_inc=90, moment_units="mA/m",
samp_name_con=... | 30,685 |
def post_multi_tag_datapoints(timeseries_with_datapoints: List[TimeseriesWithDatapoints], **kwargs):
"""Insert data into multiple timeseries.
Args:
timeseries_with_datapoints (List[v04.dto.TimeseriesWithDatapoints]): The timeseries with data to insert.
Keyword Args:
api_key (str): Your api... | 30,686 |
def get_version(pname: str, url: str) -> str:
"""Extract the package version from the url returned by `get_url`."""
match = search(r"/(\d+\.\d+\.\d+)/(\w+(?:-\w+)?)-(\d+\.\d+\.\d+)\.tar\.gz$", url)
# Assert that the package name matches.
assert match[2] == pname
# As a sanity check, also assert that... | 30,687 |
def SmoothMu(trimset, smoothing):
""" Smooth mu or P(mu>thresh). """
Stot = trimset[0]
newmu = trimset[1]
maxflux = Stot.max()
xfine = numpy.exp(numpy.linspace(0, numpy.log(maxflux), 300))
#tck = interpolate.splrep(Stot, newmu, s=1, k=5)
#yfine = interpolate.splev(xfine, tck, der=0)
... | 30,688 |
def spdiags(data, diags, m, n, format=None):
"""
Return a sparse matrix from diagonals.
Parameters
----------
data : array_like
matrix diagonals stored row-wise
diags : diagonals to set
- k = 0 the main diagonal
- k > 0 the k-th upper diagonal
- k < 0 the k... | 30,689 |
def find_object(sha1_prefix) -> str:
"""
Find object with given SHA-1 prefix and return path to object in object
store, or raise ValueError if there are no objects or multiple objects
with this prefix.
"""
if len(sha1_prefix) < 2:
raise ValueError("Hash Prefix must be 2 or more charact... | 30,690 |
def list_files(path: str) -> List[str]:
""" List files inside a directory
Parameters
----------
path
directory path
Returns
-------
list
list of file names
"""
return [f.name for f in os.scandir(path) if os.path.isfile(f)] | 30,691 |
def precision_with_fixed_recall(y_true, y_pred_proba, fixed_recall):
""" Compute precision with a fixed recall, for class 1. The chosen threshold for this couple precision is also returned.
Parameters
----------
y_true : 1d array-like, or label indicator array / sparse matrix
Ground truth (corr... | 30,692 |
def sample_kollege(user, name='Miguel', crm='222'):
"""Create and return a sample tag"""
return Kollege.objects.create(user=user, name=name, crm=crm) | 30,693 |
def display_help():
"""Displays usage and help"""
print(
"usage: echobox [-a|--align name] [-b|--basic-char char] [-d|--debug]",
file=sys.stderr,
)
print(
" [-f|--fill-char char] [-h|--help|-?] [-i|--inter-lines number]",
file=sys.stderr,
)
print(
" ... | 30,694 |
def get_singular_user_metrics(URM_test, recommender_object: BaseRecommender, cutoff=10):
"""
Return a pandas.DataFrame containing the precision, recall and average precision of all the users
:param URM_test: URM to be tested on
:param recommender_object: recommender system to be tested
:param cutof... | 30,695 |
def detect_license(document, cleaned=False):
"""
Finds a license that is most similar to the provided `document`.
/
:document: a license, whose name should be identified
:type document: string
/
:cleaned: shows whether a `document` is prepared for vectorization.
/
Returns the name of... | 30,696 |
def user_profile(request):
"""
Puts user_profile into context if available.
"""
profile = None
if request.user.is_authenticated():
from models import Participant
try:
profile = Participant.objects.get(user__id=request.user.id)
except ObjectDoesNotExist:
pass
return {'user_profile': profile} | 30,697 |
def get_reduced_model(model: torch.nn.Module, x_sample: torch.Tensor,
bias: bool = True, activation: bool = True) -> torch.nn.Module:
"""
Get 1-layer model corresponding to the firing path of the model for a specific sample.
:param model: pytorch model
:param x_sample: input sampl... | 30,698 |
def cosine_sim(a: np.ndarray, b: np.ndarray) -> float:
"""
Computes the cosine similarity between two vectors
Parameters
----------
a: np.ndarray
the first vector
b: np.ndarray
the second vector
Returns
-------
float: the cosine similarity of the two vectors
"""... | 30,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.