text string | label_name string | labels int64 |
|---|---|---|
"""Datasources to override command_mapper yaml files."""
from pathlib import Path
from nautobot.apps.datasources import DatasourceContent
from nautobot.extras.choices import LogLevelChoices
from nautobot_device_onboarding.constants import (
ONBOARDING_COMMAND_MAPPERS_CONTENT_IDENTIFIER,
ONBOARDING_COMMAND_MA... | Python | 1 |
"""Añade campo created a Post
Revision ID: 262155567f30
Revises: cb86527f8105
Create Date: 2020-01-15 11:53:21.518238
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '262155567f30'
down_revision = 'cb86527f8105'
branch_labels = None
depends_on = None
def upgr... | Python | 1 |
import contextlib
import fastapi
import typing_extensions as te
from . import abstract_transport
__all__ = ["FastapiWebsocketTransport"]
class FastapiWebsocketTransport(abstract_transport.AbstractTransport):
def __init__(self, websocket: fastapi.WebSocket):
super().__init__()
self._websocket =... | Python | 1 |
"""Modular qlbm quantum circuit components for the CQLBM algorithm :cite:p:`collisionless`."""
from .bounceback_reflection import (
BounceBackReflectionOperator,
BounceBackWallComparator,
)
from .cqlbm import CQLBM
from .primitives import (
CollisionlessInitialConditions,
CollisionlessInitialConditions... | Python | 1 |
o the state.
Have,
/// Implementation of `refine` function. `[(refine rstack), e] -> refine(rstack, ret(e))`
RefineResume,
/// Call refine with the last argument on the stack, if not `#undef`.
/// Part of the `(focus es)` macro.
/// If the bool is true (shown as `refine`), this returns the result of the ref... | Rust | 0 |
return;
}
if target.damage_split() && self.roll_brave_reaction(target) {
self.change_target_hp(target_id, -(amount / 2), Source::Constant("Damage Split"));
self.change_target_hp(user_id, amount / 2, Source::Constant("Damage Split"));
return;
}
if t... | Rust | 0 |
let (address, size) = address_size_attrs(input.attrs);
let name = input.ident;
let expanded = quote! {
impl I2cReadRegister<[u8; #size]> for #name {
fn i2c_read<I2C, Err>(&self, i2c: &mut I2C, device_address: u8) -> Result<[u8; #size], Err>
where
I2C: i2c::Writ... | Rust | 0 |
SongAdmin' or found in the model 'Song'.
>>> class SongAdmin(SongAdmin):
... def awesome_song(self, instance):
... if instance.title == "Born to Run":
... return "Best Ever!"
... return "Status unknown."
>>> validate(SongAdmin, Song)
>>> class SongAdmin(admin.ModelAdmin):
... read... | Python | 1 |
_num_args(1, args)?;
check_num_funcs(0, funcs)?;
check_num_labels(0, labels)?;
get_ptr_type(get_type(env, 0, args)?)?;
Ok(())
}
Instruction::Effect {
op: EffectOps::Speculate | EffectOps::Guard | EffectOps::Commit,
args: _,
funcs: _,
labels: _,
} => {
un... | Rust | 0 |
::new(TestStorageKeys::KeyC.try_to_vec().unwrap()),
};
board.list.insert(&account_vecno!(), &5000);
board.list.insert(&account_nodra!(), &5000);
board.assert_valid(2);
}
#[test]
#[should_panic(expected = "The board can not have more then 1 members")]
fn guild_board_assert_max_members() {
let mut bo... | Rust | 0 |
import pytest
from .utils import *
from ..routers.auth import get_db, authenticate_user, create_access_token, SECRET_KEY, ALGORITHM, get_current_user
from jose import jwt
from datetime import timedelta
from fastapi import HTTPException
app.dependency_overrides[get_db] = override_get_db()
def test_authenticate_user(t... | Python | 1 |
from django.core.exceptions import ValidationError
from django.utils import timezone
def validate_birthday(value):
"""
Validate that the birthday is not in the future.
"""
today = timezone.localdate()
if value > today:
raise ValidationError("Birthday cannot be in the future.")
return va... | Python | 1 |
er_fence(atomic::Ordering::SeqCst);
}
}
impl Deref for SafeString {
type Target = String;
fn deref(&self) -> &String {
&self.inner
}
}
impl DerefMut for SafeString {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl Into<SafeString> for String {
fn i... | Rust | 0 |
新增粉丝数
if '新增粉丝数' in row and pd.notna(row['新增粉丝数']):
score += float(row['新增粉丝数']) * self.highlight_weights['新增粉丝数'] * 10
# 商品点击人数
if '商品点击人数' in row and pd.notna(row['商品点击人数']):
score += float(row['商品点击人数']) * self.highlight_weights['商品点击人数']
# 商品... | Python | 1 |
import random
import numpy as np
import scipy.stats as stats
def normal_sampling(mean, std_dev, size=1):
return np.random.normal(loc=mean, scale=std_dev, size=size)
def fitness_function(decision, components, product):
total_savings = 0
total_cost = 0
total_inspection = 0
total_defect = 0
for... | Python | 1 |
, 'p_condition',
'parser.py', 304),
('relattr_or_value -> relattr', 'relattr_or_value', 1, 'p_relattr_or_value',
'parser.py', 309),
('relattr_or_value -> value', 'relattr_or_value', 1, 'p_relattr_or_value',
'parser.py', 310),
('non_mvalue_list -> value , non_mvalue_list', 'non_mvalue_list', 3... | Python | 1 |
SockFlag::empty(),
None,
)?;
tsocketfd =
match connect(tsocketfd, &SockAddr::Unix(UnixAddr::new(&*tsocket)?)) {
Err(e) => {
if e != ::nix::Error::Sys(Errno::ENOENT) {
let msg = format!("failed to open {}", tsocket);
return Err(e... | Rust | 0 |
: CharacterStaticData = CharacterStaticData {
name: CharacterName::Diluc,
chs: "迪卢克",
element: Element::Pyro,
hp: [1011, 2621, 3488, 5219, 5834, 6712, 7533, 8421, 9036, 9932, 10547, 11453, 12068, 12981],
atk: [26, 68, 90, 135, 151, 173, 194, 217, 233, 256, 272, 295, 311, 335],
def: [61, 158, 211... | Rust | 0 |
onential_mechanism`
//! implementation is `2*alpha*ln(2)*eta` base-e DP. To explicitly scale by `alpha`
//! the caller can either modify the `eta` used or the utility function.
//! ```
//! use b2dp::{exponential_mechanism, Eta, GeneratorOpenSSL, errors::*};
//! # fn main() -> Result<()> {
//! // Scale the privacy para... | Rust | 0 |
RequestGetAttr<'a> {
pub handle: Nfs3Handle<'a>,
}
named!(pub parse_nfs3_request_getattr<Nfs3RequestGetAttr>,
do_parse!(
handle: parse_nfs3_handle
>> (
Nfs3RequestGetAttr {
handle:handle,
}
))
);
#[derive(Debug,PartialEq)]
pub struct Nfs3Requ... | Rust | 0 |
poral integration
for _ in range(num_interactions):
groups_reshaped = rearrange(groups_with_cls, "b n k c -> (b n) k c")
updated_groups = self.temporal_attn(self.temporal_norm1(groups_reshaped), B)
updated_groups = self.temporal_fc(updated_groups) + groups_reshaped
... | Python | 1 |
from .base import Resource
from ..constants.url import URL
class Webhook(Resource):
def __init__(self, client=None):
super(Webhook, self).__init__(client)
self.base_url = URL.V2 + URL.ACCOUNT
def create(self, data={}, account_id=None, **kwargs):
"""
Create webhook from given ... | Python | 1 |
lf.y_step
y2 = y1 + self.y_step
# d <-- c
# ^
# |
# a --> b
a = x * (self.grid_size.y+1) + y
b = (x+1) * (self.grid_size.y+1) + y
c = (x+1) * (self.grid_size.y+1) + (y+1)
... | Python | 1 |
CurveScalar::from)
}
/// Generates an arbitrary blinding.
pub fn arbitrary_blinding() -> impl Strategy<Value = Blinding> {
arbitrary_curve_scalar()
}
/// Generates an arbitrary RistrettoPrivate key.
pub fn arbitrary_ristretto_private() -> impl Strategy<Value = RistrettoPrivate> {
arbitrary_scalar().prop_map(R... | Rust | 0 |
menting this trait incorrectly might break [`Token`]'s invariants.
///
/// [`Token`]: crate::Token
/// [`new`]: SingletonToken::new
pub unsafe trait SingletonTokenFactory {
/// Take a token. Returns `true` if successful.
fn take() -> bool;
/// Return a token.
///
/// # Safety
///
/// Each ca... | Rust | 0 |
let ref last_ep2 = positive_events[positive_events.len() - 2];
dv_pre = (p - pathevent_to_point(last_ep2)).normalize();
last_ep_to = p;
},
&PathEvent::QuadraticTo(c... | Rust | 0 |
data)),
}
}
}
impl Display for Operator {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match *self {
Operator::Add => write!(f, "+="),
Operator::Subtract => write!(f, "-="),
Operator::Divide => write!(f, "/="),
Operator::IntegerDivide => writ... | Rust | 0 |
nt(context, removed_evt, object) {
log::error!("Encountered AVM2 error when dispatching event: {}", e);
}
}
}
/// Dispatch the `addedToStage` event on a child and all of it's grandchildren,
/// recursively.
pub fn dispatch_added_to_stage_event<'gc>(
child: DisplayObject<'gc>,
context: &... | Rust | 0 |
, T21, T22, T23, T24, T25, T26, T27, T28, T29> TupleFlatten for ((T0, T1, T2, T3, T4, T5, T6, T7, T8, T9), (T10, T11, T12, T13, T14, T15, T16, T17, T18, T19), (T20, T21, T22, T23, T24, T25, T26, T27, T28, T29)) {
type OutTuple = (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T... | Rust | 0 |
a: __m512i,
b: __m512i,
) -> __m512i {
let unpackhi = _mm512_unpackhi_epi8(a, b).as_i8x64();
transmute(simd_select_bitmask(k, unpackhi, src.as_i8x64()))
}
/// Unpack and interleave 8-bit integers from the high half of each 128-bit lane in a and b, and store the results in dst using zeromask k (elements... | Rust | 0 |
from discord.ext.commands import Context
from Handlers.AbstractHandler import AbstractHandler
from Handlers.HandlerResponse import HandlerResponse
from Parallelism.AbstractProcessManager import AbstractPlayersManager
from Parallelism.Commands import VCommands, VCommandsType
from Music.VulkanBot import VulkanBot
from ty... | Python | 1 |
"""This program shows how to use the LFO classes to output an
LFO on one of the CV outputs.
Output mapping:
- CV A: A constant sine wave LFO at a frequency of 2 Hz.
- CV B: A variable sawtooth LFO at a frequency determined by the
modulation wheel. 0-10 Hz.
"""
import winterbloom_sol as sol
# The SineLFO, Sawtoo... | Python | 1 |
nce': transaction, 'form': form}
return render_to_string('app/transactions/edit_row.html', context)
""" Common methods """
def get_object(self, pk):
transaction = get_object_or_404(Transaction, id=pk)
return transaction
def get_row_item(self, pk):
transaction = self.get_ob... | Python | 1 |
andler5();
fn irq_handler6();
fn irq_handler7();
fn irq_handler8();
fn irq_handler9();
fn irq_handler10();
fn irq_handler11();
fn irq_handler12();
fn irq_handler13();
fn irq_handler14();
fn irq_handler15();
}
const IRQ_VECTOR_OFFSET: u8 = 32;
const MAX_ENTRIES: usize = 16;
const PORT_MASTER_PIC_CM... | Rust | 0 |
from marshmallow import (
Schema,
fields,
)
class Commit(Schema):
author = fields.Nested(lambda: CommitAuthor())
commit = fields.Nested(lambda: CommitCommit())
files = fields.List(fields.Nested(lambda: CommitFilesItem()))
class CommitFilesItem(Schema):
additions = fields.Integer()
blob_u... | Python | 1 |
tores key_0 that is a part of key material."]
pub struct KEY_0_R(crate::FieldReader<u32, u32>);
impl KEY_0_R {
#[inline(always)]
pub(crate) fn new(bits: u32) -> Self {
KEY_0_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for KEY_0_R {
type Target = crate::FieldReader<u32, u32>;
#... | Rust | 0 |
e[:, :-1:2].long()
# Make the disjunctive graph
edges_t = graph_edges(num_j, num_m, machines, device=device)
# Prepare the features
x = extract_features(num_j, num_m, costs, machines, device=device)
x = standardize(x, dim=0)
# Make the data object of the loaded instance
data = dict(
... | Python | 1 |
def run_assessment():
print("\n--- Avaliação de Maturidade ISO 27001 ---\n")
perguntas = [
"1. O nível de implementação de controles de acesso na organização é:\n 1 - Inexistente\n 2 - Inicial (não formalizado)\n 3 - Parcialmente implementado\n 4 - Bem implementado, mas sem revisão contínua\n ... | Python | 1 |
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger(__name__)
logger.addHandler(RotatingFileHandler('app.log', maxBytes=1024*1024, backupCount=5))
def init_logger():
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') | Python | 1 |
from __future__ import annotations
from collections.abc import Collection
class ETags(Collection):
"""A set that can be used to check if one etag is present in a collection
of etags.
"""
def __init__(self, strong_etags=None, weak_etags=None, star_tag=False):
if not star_tag and strong_etags:... | Python | 1 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow/python/keras/protobuf/projector_config.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf i... | Python | 1 |
Deliver the signal to all processor cores listed in the destination by
/// asserting the INIT signal. All addressed local APICs will assume their
/// INIT state. INIT is always treated as an edge triggered interrupt, even if
/// programmed otherwise. For proper operation, this redirection table entry
//... | Rust | 0 |
file)".to_owned(), s);
}
res
}
}
#[cfg(test)]
mod tests {
use std::thread::sleep;
use std::time::Duration;
use super::current_unix_timestamp;
use super::State;
use super::UpDownStateInner;
#[test]
fn test_current_unix_timestamp() {
let first = current_unix_time... | Rust | 0 |
no_run {
return Ok(());
}
// Because scripts, and therefore worker.execute cannot detect unresolved promises at the moment
// we generate a module for the actual test execution.
let test_options = json!({
"disableLog": quiet,
"filter": filter,
});
let test_module = deno_core::resolve_path("$de... | Rust | 0 |
h('text/html')
has_ct = True
elif k == 'Vary':
assert 'Cookie' in v
assert 'Accept-Language' in v
has_v = True
elif k == 'Cache-Control':
assert 'private' in v
assert '... | Python | 1 |
class Solution:
def smallestRange(self, nums: List[List[int]]) -> List[int]:
merged = []
for i in range(len(nums)):
for num in nums[i]:
merged.append((num,i))
merged.sort()
left = 0
start_range, end_range = 0, float('inf')
# this ... | Python | 1 |
->data is NULL, the encoder will"]
#[doc = " allocate it. The encoder will set avpkt->size to the size"]
#[doc = " of the output packet."]
#[doc = ""]
#[doc = " @param[in] frame AVFrame containing the raw audio data to be encoded."]
#[doc = " May be... | Rust | 0 |
import gmpy2
import libnum
n = 262430990517465815732817631765118429235071786191593561352254021025221629304243994997045687752893459705504539376939384485114122117713979546958833439697644980887710107461284004815890660353565595559916503986680310731817253348303188008236687930175478409355445415583983379588146953753745763370... | Python | 1 |
= &a.0;
let b = &b[..];
let truth = a.contains(b);
TestResult::from_bool(contains(&a, &b) == truth)
}
quickcheck(prop as fn(_, _) -> _);
}
#[test]
fn test_find_str() {
fn prop(a: Text, b: Short<Text>) -> TestResult {
let a = &a.0;
let b = &b[..];
let truth =... | Rust | 0 |
ocol(var)]
pub buddy_id: u64,
#[protocol(var)]
pub time_left: u32,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6303)]
pub struct TeleportToBuddyCloseMessage<'a> {
#[protocol(var)]
pub dungeon_id: u16,
#[protocol(var)]
... | Rust | 0 |
serialize_operation_crate_operation_monitor_instances(
input: &crate::input::MonitorInstancesInput,
) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> {
let mut out = String::new();
#[allow(unused_mut)]
let mut writer = aws_smithy_query::QueryWriter::new(&mut ou... | Rust | 0 |
Err(right.clone()),
(Ok(left), Ok(right)) => Ok(left.merge(right))
}
}
}
pub(crate) mod gui;
use gui::main::launch;
fn main() {
launch();
}
<filename>src/solution/s0436_find_right_interval.rs
/**
* [0436] Find Right Interval
*
* You are given an array of intervals, where intervals[i] ... | Rust | 0 |
import torch
import pytorch_lightning as pl
from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint
from pytorch_lightning.callbacks import TQDMProgressBar
from torch.utils.data import DataLoader
import neptune
import time
import os
import glob
from datetime import datetime
import config as c
from sr... | Python | 1 |
import collections
import logging
from dataclasses import dataclass
from typing import Generator, List, Optional, Sequence, Tuple
from pip._internal.utils.logging import indent_log
from .req_file import parse_requirements
from .req_install import InstallRequirement
from .req_set import RequirementSet
__all__ = [
... | Python | 1 |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
import requests
from airbyte_cdk.sources.streams.http.rate_limiting import default_backoff_handler
class Pardot:
def __init__(
self,
refresh_token: str = None,
token: str = None,
client_id: str = None,
client_sec... | Python | 1 |
in=5))}
)
return self.async_show_form(
step_id="init",
data_schema=self.add_suggested_values_to_schema(
options_schema, self.config_entry.options
),
)
class CannotConnect(HomeAssistantError):
"""Error to indicate we cannot connect."""
... | Python | 1 |
'''
Problem Description:
You are given an integer n. Your task is to return a right-angled triangle pattern of '*' where each side has n characters, represented as a list of strings. The triangle has '*' characters, starting with 1 star in the first row, 2 stars in the second row, and so on until the last row has n st... | Python | 1 |
sh',
'ConvStart', # contains convo_obj, portrait
'ConvStep', # contains value
'FocusGained',
'FocusLost',
'Gameover',
'GamepadDir',
'Gamepaddown',
'Gamepadup',
'Gamestart',
'Keydown',
'Keyup',
'Mousedown',
'Mousemotion',
'Mouseup',
'NetwReceive' # [num] un... | Python | 1 |
>(&self, query: Q) -> Result<SignatureOptions>
where
Q: Into<MethodQuery<'a>>,
{
let query: MethodQuery = query.into();
let method: MethodWrap<U> = self.try_resolve(query)?;
Ok(SignatureOptions::with_purpose(
method.id.to_string(),
query.scope.as_str().to_string(),
))
}
fn reso... | Rust | 0 |
///
/// // The count should always be 1 since the state is thread-local.
/// assert_eq!(count.get(), 1);
/// }
///
/// fn main() {
/// // setup the initializer for thread-local state
/// COUNT.set(|| Cell::new(0));
///
/// // spin up many threads that call `check_count`.
/// let mut threads = ve... | Rust | 0 |
:T0] # Treated units, pre-treatment
# Default regularization following original paper
if zeta_omega is None:
sigma_est = np.std([np.std(np.diff(Y_reordered[i, :T0])) for i in range(N0)])
zeta_omega = ((N1 * T1) ** 0.25) * sigma_est
# Solve for time weights λ
# Predict post-t... | Python | 1 |
he username is '{username}', the operating system is {operating_system}, and the current working directory is '{cwd}'. Can I help with anything else?",
},
{"role": "user", "type": "message", "content": "Nah. I'll talk to you in an hour!"},
{
"role": "assistant",
"type": "message",
"c... | Python | 1 |
from django.urls import path
from . import views
urlpatterns = [
path('', views.Home, name='home'), # Home page
path('submit/', views.submit_form, name='submit_form'), # Form submission
]
| Python | 1 |
or `1 day`. You can even combine values: `1 day 12 hours`
| absolute
| `on`, `at`
| A https://tools.ietf.org/html/rfc3339[RFC3339] Date-Time formatted string.
RFC2822 and keywords like `noon` are wip.
|===
.Example:
in 20 minutes 2 hours
at 2020-02-20 20:20
",
)
.done()
}
<reponame>r3bl-org/r... | Rust | 0 |
{
xcb_kill_client((*xwm).xcb_conn, (*xsurface).window_id);
xcb_flush((*xwm).xcb_conn);
};
}
#[no_mangle]
pub unsafe extern "C" fn xwm_destroy(mut xwm: *mut wlr_xwm) {
if xwm.is_null() { return }
xwm_selection_finish(xwm);
if (*xwm).cursor != 0 { xcb_free_cursor((*xwm).xcb_conn, (*xwm).cu... | Rust | 0 |
;
use std::collections::{HashMap, HashSet};
use std::iter::FromIterator;
use std::ops::{Add, AddAssign, Mul, Neg, Sub};
use CurrOrNext::*;
/// The collection of constants required to evaluate an `Expr`.
pub struct Constants<F> {
/// The challenge alpha from the PLONK IOP.
pub alpha: F,
/// The challenge be... | Rust | 0 |
# Copyright (C) 2009 Google Inc. All rights reserved.
# Copyright (C) 2010 Chris Jerdonek (cjerdonek@webkit.org)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the... | Python | 1 |
rec[0].x = 1
assert_equal(rec[0].x, np.ones(5))
def test_missing_field(self):
# https://github.com/numpy/numpy/issues/4806
arr = np.zeros((3,), dtype=[('x', int), ('y', int)])
assert_raises(KeyError, lambda: arr[['nofield']])
def test_fromarrays_nested_structured_arrays(self):... | Python | 1 |
fn test_arm_req_directive() {
assert_listing!(
"register .req x1",
r#"ROOT@0..16
ALIAS@0..16
REGISTER_ALIAS@0..8 "register"
WHITESPACE@8..9 " "
MNEMONIC@9..13 ".req"
WHITESPACE@13..14 " "
REGISTER@14..16 "x1"
"#,
Architecture::AArch64
);
}
#[test]
fn test_arm_req_a... | Rust | 0 |
So if the episodes list shuffled before calling this method,
the scenes will be in a random order
"""
assert self.group_by_scene
scene_sort_keys: Dict[str, int] = {}
for e in episodes:
if e.scene_id not in scene_sort_keys:
scene_sort_keys[e.scene_... | Python | 1 |
import numpy as np
tokens = np.load('tokens.npy')
real_dists = np.load('dstore_subsampled_0.05_real_mask_dists.npy')
flat_dists = np.load('dstore_subsampled_0.05_faiss_mask_flat_dists.npy')
flat_cpu_dists = np.load('dstore_subsampled_0.05_faiss_mask_flat_cpu_dists.npy')
faiss_dists = np.load('dstore_subsampled_0.05_... | Python | 1 |
"""Pool list widget."""
from __future__ import annotations
from llmling.config.store import ConfigFile, ConfigStore
from textual.containers import ScrollableContainer
from textual.message import Message
from textual.reactive import reactive
from textual.widgets import Static
from upathtools import read_path
from llm... | Python | 1 |
def add(a,b):
return a+b
def substract(a,b):
return a - b
def multiply(a,b):
return a * b
def divide(a,b):
return a / b
def calculator():
while True:
print("Seleccione una operación")
print("1. Suma")
print("2. Resta")
print("3. Multiplicación")
print("4... | Python | 1 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
# -*- coding: utf-8 -*-
import numpy as np
import geatpy as ea
class Schwefel(ea.Problem): # 继承Problem父类
def __init__(self, Dim=30): # Dim : 决策变量维数
name = 'Schwefel' # 初始化name(函数名称,可以随意设置)
M = 1 # 初始化M(目标维数)
maxormins = [1] * M # 初始化maxormins(目标最小最大化标记列表,1:最小化该目标;-1:最大化该目标)
... | Python | 1 |
t
use std::io::{BufRead, Read};
use std::thread;
use std::time::Duration;
#[allow(unused_imports)]
use beep::beep as sound;
use dim::{dimensions::Frequency, si::Hertz};
#[allow(unused_imports)]
use log::{debug, info};
use num_enum::{FromPrimitive, IntoPrimitive};
use num_traits::{Num, ToPrimitive};
use termcolor::{Col... | Rust | 0 |
from marie.clients.mixin import AsyncHealthCheckMixin, AsyncPostMixin, AsyncProfileMixin
from marie.orchestrate.flow.base import Flow
class AsyncFlow(AsyncPostMixin, AsyncProfileMixin, AsyncHealthCheckMixin, Flow):
"""
Asynchronous version of :class:`jina.Flow`. They share the same interface, except
in :c... | Python | 1 |
WDTIS_4,
5 => WDTIS_A::WDTIS_5,
6 => WDTIS_A::WDTIS_6,
7 => WDTIS_A::WDTIS_7,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `WDTIS_0`"]
#[inline(always)]
pub fn is_wdtis_0(&self) -> bool {
*self == WDTIS_A::WDTIS_0
... | Rust | 0 |
查每个类别,并根据优先级更新行驶参数
current_priority = float('inf') # 当前的优先级设置为无限高
for category in detected_class:
cat_priority = priority.get(category, float('inf')) # 获取类别的优先级
if cat_priority < current_priority:
if category in ['stop', 'red', 'zebra crossing']:
... | Python | 1 |
import numpy as np
import cv2
import librosa
def gaussian_filter(data, sigma):
kernel_size = int(6 * sigma + 1)
kernel_size += 1 if kernel_size % 2 == 0 else 0 # Ensure kernel size is odd
kernel = np.fromfunction(
lambda x, y: (1/(2*np.pi*sigma**2)) * np.exp(-((x-kernel_size//2)**2 + (y-kernel_siz... | Python | 1 |
bug_file: Option<File>,
}
impl<'a> Disassembler<'a> {
/// Constructor
pub fn new(cmd: Option<&'a str>, debug_fp: Option<&'a str>) -> Self {
Disassembler {
cmd,
debug_file: debug_fp.map_or(None, |fp| File::create(fp).ok()),
}
}
/// Creates a process to call objdum... | Rust | 0 |
import streamlit as st
def load_tasks():
return st.session_state.get("tasks", [])
def save_tasks(tasks):
st.session_state["tasks"] = tasks
def main():
st.title("📝 To-Do List")
tasks = load_tasks()
new_task = st.text_input("Add a new task:", "")
if st.button("Add Task") and new_task... | Python | 1 |
nvalid_digit(&read_file_to_lines("input/day09.txt"), 25),
258585477
);
assert_eq!(
find_encryrption_weakness(&read_file_to_lines("input/day09.txt"), 258585477),
36981213
);
}
fn day10() {
assert_eq!(
product_of_joltage_diff_1_and_3_counts(&read_file_to_lines("input/day1... | Rust | 0 |
)
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
P3DIR4R::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> P3DIR4R {
match value {
... | Rust | 0 |
//const float hx = 0.72f, hy = 0.72f;
//const float angle1 = 0.0f;
let mut polygon1 = B2polygonShape::default();
polygon1.set_as_box_angle(hx, hy, center, angle1);
let abs_tol: f32 = 2.0 * B2_EPSILON;
let rel_tol: f32 = 2.0 * B2_EPSILON;
assert!(b2_abs(polygon1.m_centroid.x - center.x) < abs_tol + rel... | Rust | 0 |
reward is needed later, it can be set to 0
#[pallet::storage]
#[pallet::getter(fn default_reward)]
pub type DefaultReward<T: Config> = StorageValue<_, BalanceOf<T>, OptionQuery>;
/// The total amount of rewards given to voters when each proposal becomes a formal proposal
#[pallet::storage]
#[pa... | Rust | 0 |
assert (
54 <= lat <= 58
), f"Latitude {lat} out of Denmark range for {dataset_name}"
def test_wrong_coordinates_detection(self, duck_conn):
"""Test that datasets with wrong coordinate order are properly detected."""
from tests.fixtures.sample_geome... | Python | 1 |
ube)
.write(&mut direct_cascades[cascade_i])
.constants((sweep_vx_count, cascade_i as u32, quantum_idx))
.raw_descriptor_set(1, bindless_descriptor_set)
.trace_rays(
tlas,
[
VOLUME_DIMS * CARDINAL_DIRECTION_COUNT as u32,... | Rust | 0 |
default()
}
} else {
pub fn settings() -> DebugSettings {
DebugSettings::default()
}
}
}
<filename>src/lib.rs
extern crate sdl2;
pub mod game;
pub mod paddle;
pub mod ball;
<reponame>trevor-crypto/thaler
mod config;
mod context;
mod ias_client;
mod server;
use structopt::St... | Rust | 0 |
e_width * 0.5, y, 0.0);
// Assign the sprites for the paddles
let sprite_render = SpriteRender {
sprite_sheet: sprite_sheet.clone(),
sprite_number: 0, // paddle is the first sprite in the sprite_sheet
};
// Create a left plank entity.
world
.create_entity()
.with(sp... | Rust | 0 |
# Define variable for hours
hours = 2
# Calculate seconds (1 hour = 60 minutes * 60 seconds = 3600 seconds)
seconds = hours * 3600
# Print the result in the specified format
print(f"{hours} hour(s) is {seconds} seconds.") | Python | 1 |
},
2 => {
if let (Some(y), Some(x)) = (args[0].to_f64(), args[1].to_f64()){
if y.is_zero() && x.is_zero(){
return Err(Error::from(ErrorKind::NAN));
}
let result = y.atan... | Rust | 0 |
# Distributed under Pycameresp License
# Copyright (c) 2023 Remi BERTHOLET
""" Watchdog class """
import sys
try:
import machine
except:
pass
LONG_WATCH_DOG=15*60*1000
SHORT_WATCH_DOG=5*60*1000
class WatchDog:
""" Watch dog timer """
watchdog = None
current = 0
max_duration = 0
timer = None
@staticmethod
def... | Python | 1 |
)
length = len(all_users["GroupList"])
# We don't know exactly how much workspaces there are, because we are running multiple tests at the same time
assert length >= 125
@mock_aws
def test_list_groups__diff_account_region():
ACCOUNT_ID_2 = "998877665544"
client_us = boto3.client("quicksight", ... | Python | 1 |
return cols
else:
return [*list(numeric_cols), *text_cols]
def clustering_preprocessor(data):
# identifies the categorical and numerical columns
categorical_columns = data.select_dtypes(exclude=["number"]).columns
numeric_columns = data.columns[data.dtypes.apply(
lambda c: np.... | Python | 1 |
qu_si128(buf_ptr as *const __m128i);
let a_in_b = _mm_cmpistrm(v_b, v_a, CMPISTRM_ARGS);
a_in_b_mask = _mm_or_si128(a_in_b_mask, a_in_b);
let in_difference = _mm_extract_epi32(a_in_b_mask, 0) ^ 0xFF;
let sm16 = _mm_lddqu_si128((SHUFFLE_MASK16.as_ptr() as *con... | Rust | 0 |
:W](im::W) writer structure"]
impl crate::Writable for IM {}
#[doc = "Hibernation Interrupt Mask"]
pub mod im;
#[doc = "Hibernation Raw Interrupt Status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields s... | Rust | 0 |
set) as *mut u64,
NOT_PRESENT_MASK);
}
return start_addr;
}
}
pub use crate::iter::iterators;
pub use crate::iter::{Enumerate, Filter, Map, WithId};
pub use crate::sparse_set::sort::{
Sort1, Sort10, Sort2, Sort3, Sort4, Sort5, Sort6, Sort7, Sort8, Sort9,
};
pub use crate:... | Rust | 0 |
# Code generated by Lark OpenAPI.
import lark_oapi as lark
from lark_oapi.api.corehr.v1 import *
def main():
# 创建client
client = lark.Client.builder() \
.app_id(lark.APP_ID) \
.app_secret(lark.APP_SECRET) \
.log_level(lark.LogLevel.DEBUG) \
.build()
# 构造请求对象
request: ... | Python | 1 |
import requests
import json
import sys
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
print("=" * 50)
print("TESTING LOG EVENT ENDPOINT")
print("=" * 50)
# Print environment info
print("\nEnvironment Variables:")
print(f"INFURA_URL: {os.environ.get('INFURA_URL')}")
print(f"ETH_AC... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.