text string | label_name string | labels int64 |
|---|---|---|
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from e_store.cart.models import Cart, CartItem
from e_store.orders.models import Order, OrderDetail, OrderPublic
from e_store.shared.exceptions.http_400s import bad_400_excep
from e_store.users.models.user import User
from . import task... | Python | 1 |
empty query
pub fn new() -> Self {
PgQueryBuilder::default()
}
}
impl QueryBuilder<Pg> for PgQueryBuilder {
fn push_sql(&mut self, sql: &str) {
self.sql.push_str(sql);
}
fn push_identifier(&mut self, identifier: &str) -> QueryResult<()> {
self.push_sql("\"");
self.... | Rust | 0 |
ze::JsonObjectWriter,
input: &crate::input::UpdateFirewallDescriptionInput,
) -> Result<(), aws_smithy_http::operation::SerializationError> {
if let Some(var_93) = &input.update_token {
object.key("UpdateToken").string(var_93);
}
if let Some(var_94) = &input.firewall_arn {
object.key("Fi... | Rust | 0 |
turn set
# scoreSimilarity
path, _ = scoreAlignment(estScore, gtScore)
aList = convertScoreToList(estScore)
bList = convertScoreToList(gtScore)
nSymbols = countSymbols(gtScore)
errors = np.zeros((len(ScoreErrors.__members__)), float)
aStart, aEnd = 0.0, 0.0
bStart, bEnd = 0.0, 0.0
... | Python | 1 |
#!/usr/bin/env python3
import sys,argparse
import pandas as pd
from toolkits import check_file_avail, extract_genome_name
usage = """
Get the filtered genomes information from hierarchical clustering. The genomes information of all the genomes of the cluster
corresponding to these representative genomes is ... | Python | 1 |
iterator(f))
} else {
env.type_error("Type error in m.items(): m is not a map.")
}
}
fn clear(env: &mut Env, pself: &Object, argv: &[Object]) -> FnResult {
match argv.len() {
0 => {}, n => return env.argc_error(n,0,0,"clear")
}
match *pself {
Object::Map(ref m) => {
... | Rust | 0 |
import numpy as np
import os
import librosa
import textgrid
import config
def parse_textgrid(textgrid_path):
tg = textgrid.TextGrid.fromFile(textgrid_path)
verbal_intervals = []
main_tier = tg[0]
for interval in main_tier:
if interval.mark == "verbal":
verbal_intervals.append((int... | Python | 1 |
# Copyright (c) OpenMMLab. All rights reserved.
import multiprocessing as mp
import os
import os.path as osp
import subprocess
def get_shape(vid):
cmd = 'ffprobe -v error -select_streams v:0 -show_entries ' \
'stream=width,height -of csv=s=x:p=0 \"{}\"'.format(vid)
w, h = subprocess.check_output(cmd... | Python | 1 |
lf::Target {
&self.0
}
}
impl R {
#[doc = "Bits 0:6 - 24 MHz TUNING value for USFRCO"]
#[inline(always)]
pub fn band24_tuning(&self) -> BAND24_TUNING_R {
BAND24_TUNING_R::new((self.bits & 0x7f) as u8)
}
#[doc = "Bits 8:13 - 24 MHz FINETUNING value for USFRCO"]
#[inline(always... | Rust | 0 |
ent_finder(item, args, pt_cli::ARG_GRAVITY) {
enable_grav = true;
}
CLI_CONTROL_STREAM_ACCEL.store(enable_accel, atomic::Ordering::Release);
CLI_CONTROL_STREAM_GRAVITY.store(enable_grav, atomic::Ordering::Release);
}
/// Method to put our CLI entry in for IMU control
pub const IMU_CLI_ITEM: cli::C... | Rust | 0 |
s)
initial_state = math_ops.cast(math_ops.argmax(last_score, axis=1), # [B]
dtype=dtypes.int32)
initial_state = array_ops.expand_dims(initial_state, axis=-1) # [B, 1]
decode_tags, _ = rnn.dynamic_rnn( # [B, T - 1, 1]
crf_bwd_cell,
inputs=backpointers,
... | Python | 1 |
列表
daily_clicks["prev_days_history"] = daily_clicks["prev_days_history"].apply(
lambda x: x if isinstance(x, list) else []
)
# --- 将点击历史回传到原始数据 ---
# 6. 创建一个点击历史映射(选择相关列)
history_map = daily_clicks[["user_id", "date", "prev_days_history"]]
# 7. 将历史合并到原始数据(使... | Python | 1 |
n: u16) -> InstructionPacket {
let (addr_l, addr_h) = unpack!(addr);
let (len_l, len_h) = unpack!(len);
let mut param = vec![addr_l, addr_h, len_l, len_h];
param.extend(ids);
InstructionPacket::new(BROADCAST_ID, Instruction::SyncRead, param)
}
fn write_data(id: u8, addr... | Rust | 0 |
Option<unsafe extern "system" fn(dwUserIndex: DWORD) -> DWORD>,
// Ordinals 104 / 108, available as of XInput1_4.dll
// _XInputGetBaseBusInformation (Ordinal 104)
// _XInputGetCapabilitiesEx (Ordinal 108)
}
impl Imports {
pub fn get() -> &'static Self { &*IMPORTS }
fn load_from_linked_xinput(... | Rust | 0 |
t mut pkt_count = 0;
// Workloads:
let workload_path = "/home/jethros/dev/pvn/utils/workloads/rdr_pvn_workloads/rdr_pvn_workload_5.json";
let num_of_secs = 600;
let mut rdr_workload = rdr_load_workload(workload_path.to_string(), num_of_secs, rdr_users.clone()).unwrap();
println!("Workload is gener... | Rust | 0 |
import pytest
from datetime import datetime
import jax.random as jr
from dynamax.linear_gaussian_ssm import LinearGaussianSSM
from dynamax.linear_gaussian_ssm import LinearGaussianConjugateSSM
from dynamax.utils.utils import monotonically_increasing
NUM_TIMESTEPS = 100
CONFIGS = [
(LinearGaussianSSM, dict(state_d... | Python | 1 |
pub struct Placeholder {
langle: Token![<],
pub text: PlaceholderToken,
rangle: Token![>],
}
pub enum PlaceholderToken {
Ident(Ident),
Lit(LitStr),
}
impl Parse for Placeholder {
fn parse(input: ParseStream) -> Result<Self> {
Ok(Placeholder {
langle: input.parse()?,
... | Rust | 0 |
let mut cs = TrivialAssembly::<Bn256, Width4WithCustomGates, Width4MainGateWithDNext>::new();
// let a_f: G1Affine = rng.gen();
// let b_f: Fr = rng.gen();
// let a = AffinePoint::alloc(
// &mut cs,
// Some(a_f),
// ¶ms
// ... | Rust | 0 |
_op(&self) -> &AOp;
fn _set_source(&self, txn: TxnId);
fn gradient(&self, txn: TxnId) {
let epoch = Epoch::new(self._op()._id());
self._set_source(txn);
self._op()._push(epoch, &mut |op| { op._forward(txn); });
self._op()._pop(epoch, &mut |_op| {});
self._op()._push(epoch, &mut |_op| {});
... | Rust | 0 |
StreamingBlob => "streaming blob to storage",
StreamedBlob => "streamed blob to storage",
FailedToStreamBlob => "failed to stream blob to storage",
// Retrieve blob.
RetrievedBlob => "retrieved blob",
FailedToRetrieveBlob => "failed to retrieve blob",
// Contains blob.
ContainsBlob => "... | Rust | 0 |
d. It is good practice to update these whenever
/// a repo is changed.
///
/// Targets, versions, and expirations may be added to their respective roles
/// via the provided "setter" methods. The final step in the process is the
/// `sign()` method, which takes a given set of signing keys, builds each of
/// the roles ... | Rust | 0 |
deps.api.canonical_address(&env.message.sender)? != config.owner {
return Err(StdError::unauthorized());
}
if let Some(owner) = owner {
config.owner = deps.api.canonical_address(&owner)?;
}
store_config(&mut deps.storage, &config)?;
Ok(HandleResponse::default())
}
pub fn register... | Rust | 0 |
list
if root:
Solution.get_inorder(root.left, inorder)
inorder.append(root.data)
Solution.get_inorder(root.right, inorder)
@staticmethod
def _get_merged_inorder(left, right):
# Merge two sorted inorder traversal lists into one sorted list
merged = []... | Python | 1 |
] and [`same_set`] methods are extremely fast and have an amortized complexity of
//! `O(α(n))` where `α` is the inverse Ackermann function and `n` is the length.
//! This complexity is proven to be optimal and `α(n)` has value below 5 for any `n`
//! that can be written in the observable universe.
//! The next element... | Rust | 0 |
ar_equal(prob.get_val("T", units="K"), np.array([400.0, 406.40945984, 422.53992837]), tolerance=1e-9)
assert_near_equal(
prob.get_val("T_out", units="K"), np.array([300.00140593, 350.00050984, 290.00139757]), tolerance=1e-9
)
partials = prob.check_partials(method="cs", compact_print... | Python | 1 |
rop<GraphicsType>>>,
position: Vec3A,
command_data: CommandData<CommandType>,
height_generator: Arc<ShardedLock<HeightGenerator>>,
size_ratio_x: f32,
size_ratio_z: f32,
vertex_count_ratio: f32,
primitive: Option<Primitive>,
entity: DefaultKey,
) -> Mod... | Rust | 0 |
.as_mut_v1().transactions = Vec::new();
SumeragiMessage::BlockCreated(block)
} else {
msg
};
Some(msg)
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Skip<M, R>(PhantomData<M>, PhantomData... | Rust | 0 |
config
self.global_config = global_config
def __call__(self, affine, representations_list, aatype):
"""Predict side chains using multi-rigid representations.
Args:
affine: The affines for each residue (translations in angstroms).
representations_list: A list of activations to predict side c... | Python | 1 |
import math
import torch
from torch import nn
import FrEIA.framework as Ff
import FrEIA.modules as Fm
from .freia_utils import FusionCouplingLayer
def subnet_conv(dims_in, dims_out):
return nn.Sequential(nn.Conv2d(dims_in, dims_in, 3, 1, 1), nn.ReLU(True), nn.Conv2d(dims_in, dims_out, 3, 1, 1))
def subnet_con... | Python | 1 |
Loss with no Bayes is NaN"
def test_checkpoint_saving_loading():
"""Test model checkpoint save/load functionality."""
torch.manual_seed(0)
np.random.seed(0)
with tempfile.TemporaryDirectory() as temp_dir:
# Create model
device = torch.device('cpu')
model = HybridODENN(
... | Python | 1 |
else:
i0, i1, i2 = f[:, 0].long(), f[:, 1].long(), f[:, 2].long()
v0, v1, v2 = v[i0, :], v[i1, :], v[i2, :]
face_normals = torch.cross(v1 - v0, v2 - v0)
face_normals = safe_normalize(face_normals)
vn = torch.zeros_like(v)
vn.scatter_add_(0, i0[:,... | Python | 1 |
eneric::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tcd12_saddr](tcd12_saddr) module"]
pub type TCD12_SADDR = crate::Reg<u32, _TCD12_SADDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TCD12_SADDR;
#[doc = "`read()` method returns [tcd... | Rust | 0 |
import numpy as np
from scipy.linalg import solve
def solve_for_flow(G, Pin, Pout, H):
Nn = 40
Nseg = 40
G = np.where(G == 0, 1e-25, G) # Avoid G zero resulting in singular matrices
C = np.zeros((Nn, Nn)) # Coefficient matrix
B = np.zeros(Nn) # Right vector
# Node 0
C[0,0] = G[0]
B... | Python | 1 |
from Bio.Seq import Seq
outfile = "temptemp.dna"
infile_seq = "read_seq140.txt"
infile_pos = "read_pos140.txt"
infile_noise = "read_noise140.txt"
infile_noisepos = "read_noisepos140.txt"
infile_rev = "read_rev140.txt"
readlen = 100
asciitoint = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':1... | Python | 1 |
import torch
import torch.nn.functional as F
from torch_xla.experimental.custom_kernel import _histogram
def fused_moe(
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
gating_output: torch.Tensor,
topk: int,
renormalize: bool,
) -> torch.Tensor:
"""
Args:
hidde... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is part of ltlf2dfa.
#
# ltlf2dfa is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later v... | Python | 1 |
t(&mut self) -> _FESTATW {
_FESTATW { w: self }
}
}
use std::io::Read;
use once_cell::sync::Lazy;
use regex::{Regex, RegexBuilder};
static TOML_REGEX: Lazy<Regex> = Lazy::new(|| {
RegexBuilder::new(r#"```toml\n(.*?)```"#)
.multi_line(true)
.dot_matches_new_line(true)
.build()
... | Rust | 0 |
from .Tool import Tool
from .Util import _calcule, _eta, f_T
class K_old():
"""
Estimator_k class calculates an aggregated score (k score) based on
similarities scores and Tanimoto values for different tools.
Args:
similarities (dict): Dictionary of similarity scores values for each tool.
... | Python | 1 |
:renderer::fft_ocean::FFTOcean;
use crate::renderer::precomputed_atmosphere::{ Atmosphere, PushConstant_Atmosphere };
use crate::renderer::push_constants::{
NONE_PUSH_CONSTANT,
PushConstant_StaticRenderObject,
PushConstant_SkeletalRenderObject,
PushConstant_GaussianBlur,
PushConstant_RenderCopy,
... | Rust | 0 |
eded for repeated calls to .json()
],
post_request_json_side_effect=[
{"value": []},
{"value": []},
{"value": []}, # these are all needed for repeated calls to .json()
],
)
self.assert_measurement(response, value="0", e... | Python | 1 |
FreeBSD 12:
pub type dev_t = u32;
// Type of `ino_t` changed from `unsigned int` to `unsigned long` in FreeBSD 12:
pub type ino_t = u32;
s! {
pub struct kevent {
pub ident: ::uintptr_t,
pub filter: ::c_short,
pub flags: ::c_ushort,
pub fflags: ::c_uint,
pub data: ::intptr_t,... | Rust | 0 |
"""Definitions for go-eCharger select entities exposed via MQTT."""
from __future__ import annotations
from dataclasses import dataclass
import logging
from homeassistant.components.select import SelectEntityDescription
from homeassistant.helpers.entity import EntityCategory
from . import GoEChargerEntityDescription... | Python | 1 |
str>,
output_file: &str,
db: &ResultsDB,
) -> Result<(), Report> {
const FULL_REGION_WIDTH: f64 = 10f64;
const MAX_COMBINATIONS: usize = 7;
// 80% of `FULL_REGION_WIDTH` when `MAX_COMBINATIONS` is reached
const BAR_WIDTH: f64 = FULL_REGION_WIDTH * 0.8 / MAX_COMBINATIONS as f64;
assert!(
... | Rust | 0 |
candidate_positions:
atom = mol.GetAtomWithIdx(pos)
for nbr in atom.GetNeighbors():
# Skip neighbor if it belongs to the candidate (pyran) ring.
if nbr.GetIdx() in candidate_ring:
continue
if not nbr.GetIsAromatic():
... | Python | 1 |
import math
import cv2
import numpy as np
def Rotate(picture,angle):
new_size=math.ceil(math.sqrt(picture.shape[0]**2 + picture.shape[1]**2))
result = np.zeros((new_size,new_size,3),dtype=np.uint8)
picture_Y = picture.shape[0]-1
picture_X = picture.shape[1]-1
cosA = math.cos(angle)
sinA = math... | Python | 1 |
# @track_context("core_constants.md")
"""
Core constants for the Supabase Auth API
This module contains essential configuration constants that are used
across multiple modules in the application.
"""
class EnvVars:
"""Environment variable names"""
# Core settings
SUPABASE_URL = "SUPABASE_URL"
SUPAB... | Python | 1 |
i64> {
String::from_utf8(bytes.to_vec()).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?.parse::<i64>().map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
}
impl fmt::Debug for Value {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
Value::... | Rust | 0 |
ns', 'rl_blank_1', color='#BF40BF', arrowhead='normal', dir='back')
dot.edge('models', 'rl_blank_1', color='#BF40BF', arrowhead='normal', dir='back', ltail='cluster_candidate_runs')
dot.edge('rl_blank_1', 'rl_blank_2', color='#BF40BF')
dot.edge('rl_blank_2', 'champion_challenger', color='#BF40BF')
do... | Python | 1 |
2,
Name::OR => 2,
Name::XOR => 2,
Name::NOT => 1,
Name::AND => 2,
Name::SHL => 2,
Name::SHR => 2,
Name::SAR => 2,
Name::BYTE => 2,
Name::ADDMOD => 3,
Name::MULMOD => 3,
Name::EXP => 2,
... | Rust | 0 |
#!/usr/bin/env python3
'''Task 0: The basics of async
Write an asynchronous coroutine that takes in an integer
argument (`max_delay`, with a default value of 10) named
`wait_random` that waits for a random delay between 0 and
`max_delay` (included and float value) seconds and
eventually returns it.
Use the `random` mo... | Python | 1 |
}
/// Consume the random oracle and generate a bytestring as output
///
/// Due to limitations of XMD this can produce only a limited amount of data,
/// at most 8160 bytes.
pub fn output_bytestring(self, output_length: usize) -> ThresholdEcdsaResult<Vec<u8>> {
let ro_input = self.form... | Rust | 0 |
s': df['time'], 'last_observed_time': val_df['time'].iloc[-1], 'negative_sample_strategy':'historical', 'seed': 2}
ntest_params = {'src_node_ids': new_test_df['src'], 'dst_node_ids': new_test_df['dst'], 'interact_times': new_test_df['time'], 'last_observed_time': val_df['time'].iloc[-1], 'negative_sample_strategy':... | Python | 1 |
_trim > 21i32 {
i32vddr_sleep_trim = 21i32;
}
if i32vddr_sleep_trim < -10i32 {
i32vddr_sleep_trim = -10i32;
}
*((0x40086200i32 + 0x60i32 + 0x7i32 * 2i32) as (*mut u16)) =
(0x1fi32 << 8i32 | i32vddr_sleep_trim << 0i32 & 0x1fi32) as (u16);
if *((0x40090000i32 + 0x0i32) as (*mut... | Rust | 0 |
00c, 0x00c00c00, 0xc0030030, 0x03003000,
0xf00f0000,
// [582]: 7A "z"
0x000a0e0a, 0xfffffc03, 0x00300c00, 0xc0300300, 0xc00c03ff, 0xfff00000,
// [588]: 7B "{"
0x00061604, 0xc3030c30, 0xc30c30c0, 0xc330c30c, 0x30c30cc3, 0x00000000,
// [594]: 7C "|"
0x00021604, 0xffffffff, 0xfff00000,
// [... | Rust | 0 |
n for the argument
with st.expander("", expanded=True):
st.success(
f"🏆 **Winner: {state['judge_verdict'].debate_winner}**"
)
with st.container():
... | Python | 1 |
service_base(key)};
// if !base.is_type() {
// return Err(Error::MismatchedType{
// key: key,
// expected: type_name::<Svc>(),
// found: type_name::<Svc>(),
// })
// };
// Ok(WriteGuard::wrap(base).ok().unwrap())
// }
... | Rust | 0 |
self.crlf_write_all_utf8(s)
} else {
self.normal_write_all_utf8(s)
}
}
}
struct NlGuard(bool);
impl Drop for NlGuard {
fn drop(&mut self) {
if !self.0 {
panic!("output text stream not ended with newline");
}
}
}
#[cfg(test)]
fn translate... | Rust | 0 |
ass = Some(_class);
}
pub fn with__class(mut self, _class: String) -> HudsonMasterComputermonitorData {
self._class = Some(_class);
self
}
pub fn _class(&self) -> Option<&String> {
self._class.as_ref()
}
pub fn reset__class(&mut self) {
self._class = None;
}
}
<gh_stars>1-10
// stab... | Rust | 0 |
esarlib::{encipher, decipher, rdm_encipher, custom_encipher, custom_decipher};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ciphered_text_can_be_deciphered() {
let enciphered = encipher(13, "FooBar");
assert_eq!("FooBar", decipher(13, &enciphered));
}
#[test]
fn ciphered_t... | Rust | 0 |
, compressed)
else:
d.generate(compressed)
P = d.get_pubkey()
return d, P
def generate_bip340_key_pair(secret=None):
"""Convenience function to generate a BIP0340 private-public key pair."""
d = ECKey()
if (secret):
d.set(secret)
else:
d.generate()
P = d.get_p... | Python | 1 |
import pytest
from pytest import raises
from discopy import tensor as dt
from lambeq.backend.tensor import *
diagrams = [
Id(Dim(1) @ Dim(2) @ Dim(3)), # types
Box("F(A)", Dim(2, 2), Dim(3)) >> Box("F(B)", Dim(3), Dim(3)),
Box("F(A)", Dim(2, 2), Dim(3)) >> Box("F(A)", Dim(2, 2), Dim(3)).dagger(),
... | Python | 1 |
ge_save_path):
current_image = read_image(image_save_path)
else:
current_image = read_image(image_path)
pose_img = add_poseTrack_joint_connection_to_image(current_image, new_coord, sure_threshold=0.3, flag_only_draw_sure=True)
save_... | Python | 1 |
m.embed(|e| {
e.0 = guild_mute_embed.0;
e
})
})
.await?;
Ok(())
}
#[command]
async fn genmuterole(ctx: &Context, msg: &Message) -> CommandResult {
if !permissions_helper::check_administrator(ctx, msg, None).await? {
return Ok(())... | Rust | 0 |
birth_year = input('Birth year: ')
age = 2023 - int(birth_year)
print(age)
| Python | 1 |
"""
Core implementation of :mod:`sklearndf.transformation` loaded
from sklearn 0.24 onwards
"""
import logging
from sklearn.feature_selection import SequentialFeatureSelector
from sklearn.kernel_approximation import PolynomialCountSketch
from sklearndf.transformation.wrapper import (
FeatureSelectionWrapperDF,
... | Python | 1 |
# SPDX-License-Identifier: Apache-2.0
import lm_eval
from ...utils import RemoteOpenAIServer
# arc-easy uses prompt_logprobs=1, logprobs=1
TASK = "arc_easy"
FILTER = "acc_norm,none"
RTOL = 0.03
EXPECTED_VALUE = 0.62
# FIXME(rob): enable prefix caching once supported.
MODEL = "meta-llama/Llama-3.2-1B-Instruct"
MODEL... | Python | 1 |
ilter.minRange = 200
config.postProcessing.thresholdFilter.maxRange = 3_000 # 3m
config.postProcessing.decimationFilter.decimationFactor = 2
config.postProcessing.decimationFilter.decimationMode = (
dai.StereoDepthConfig.PostProcessing.DecimationFilter.DecimationMode... | Python | 1 |
**모델**: Claude 3.7 Sonnet
**Temperature**: 0 (정확성 우선)
**KB_ID**: {st.session_state.kb_id}
**최대 반복**: 5회
""")
# 메인 채팅 영역
if not st.session_state.session_id and st.session_state.session_manager:
session = st.session_state.session_manager.create_session()
st.se... | Python | 1 |
lockdata::script::Builder::new()
.push_scriptint(486604799)
.push_scriptint(4)
.push_slice(b"The Times 03/Jan/2009 Chancellor on brink of second bailout for banks")
.into_script();
let out_script = bitcoin::blockdata::script::Builder::new()
.push_slice... | Rust | 0 |
foo-2, 2.
:param link: The link the string came from, for logging on failure.
s% Could not parse version from link: %si t -t _N(
R R_ R RH R t indexR t replaceRK R ( R t search_nameRc t _egg_info_reR t
full_matchR t look_for( ( sZ /private/var... | Python | 1 |
te: u32,
pub data_bits: DataBits,
pub stop_bits: StopBits,
pub parity: Parity,
}
impl Default for Config {
fn default() -> Self {
Self {
baudrate: 115200,
data_bits: DataBits::DataBits8,
stop_bits: StopBits::STOP1,
parity: Parity::ParityNone,
... | Rust | 0 |
# -*- coding: utf-8 -*-
# ========================================================================
# 2022/6/1 9:13
# _____ _ _ _____ __ _ _____
# / ___| | | | | | ____| | \ | | / ___|
# | | | |_| | | |__ | \| | | |
# | | | ... | Python | 1 |
# Exersize 1
n, d, r = map(int, input().split(' '))
print(2*r*n + 2*d)
# Exersize 2
import math
n = int(input('Enter a number greater than 2: '))
while n > 2:
n = math.sqrt(n)
print("{0:.3f}".format(n))
# Exersize 3
n = int(input())
min = n
for i in range (1, n):
if n % i == 0 and i < min and i > 2:
... | Python | 1 |
user, provider)
}
fn encode_token(token: &originsrv::SessionToken) -> String {
let bytes = protocol::message::encode(token).unwrap(); //Unwrap is safe
base64::encode(&bytes)
}
<reponame>RoyJacobs/mosdev<gh_stars>10-100
pub mod adapters;
pub mod connection;
pub mod protocol;
pub mod types;
use crate::debugger:... | Rust | 0 |
1NEEDCLKSTAT>;
#[doc = "Register USB1NEEDCLKSTAT `reset()`'s with value 0"]
impl crate::ResetValue for super::USB1NEEDCLKSTAT {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Possible values of the field `DEV_NEEDCLK`"]
#[derive(Clone, Copy, Debug, PartialEq)]... | Rust | 0 |
ge_attr` is not passed, else
(:class:`LongTensor`, :obj:`Optional[Tensor]` or :obj:`List[Tensor]]`)
.. warning::
From :pyg:`PyG >= 2.3.0` onwards, this function will always return a
tuple whenever :obj:`edge_attr` is passed as an argument (even in case
it is set to :obj:`None`).
... | Python | 1 |
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import UpdateModelMixin
from rest_framework import permissions
from products.models import Product
from products.api_endpoints.Product.ProductUpdate.serializers import (
ProductUpdateSerializer,
)
class ProductUpdateAPIView(GenericAPIV... | Python | 1 |
geometry_kind: filters.pixels_geometry_kind.value,
view: &matrix_to_16_f32(view),
projection: &matrix_to_16_f32(projection),
ambient_strength: output.ambient_strength,
contrast_factor: filters.extra_... | Rust | 0 |
&ad, nonce, key);
assert_secret_seq_eq!(expected_ct, ct, U8);
assert_secret_array_eq!(expected_tag, tag, U8);
let msg_out = gimli_aead_decrypt(&ct, &ad, tag, nonce, key);
assert_secret_seq_eq!(msg, msg_out, U8);
}
#[test]
fn tg_gimli_aead_105_176() {
let key = Key::from_public_slice(&[
0x... | Rust | 0 |
import logging
import os
import shutil
from typing import Optional
import torch as tr
import torchaudio
from torch import Tensor as T
import fadtk
from fadtk import (
FrechetAudioDistance,
cache_embedding_files,
)
logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(level=os.environ.get("LOGL... | Python | 1 |
test_pyarrow_integration(2, 1, false)
}
#[test]
fn v1_boolean_nullable() -> Result<()> {
test_pyarrow_integration(3, 1, false)
}
#[test]
fn v1_timestamp_nullable() -> Result<()> {
test_pyarrow_integration(4, 1, false)
}
#[test]
#[ignore] // pyarrow issue; s... | Rust | 0 |
mut c_type: *mut c_char = ptr::null_mut();
let c_role = str_to_c_string(role)?;
if unsafe { selinux_sys::get_default_type(c_role.as_ptr(), &mut c_type) } == -1 {
Err(Error::last_io_error("get_default_type()"))
} else {
CAllocatedBlock::new(c_type)
.ok_or_else(|| Error::from_io("... | Rust | 0 |
channel
)]
MissingChannels { channel: PsdChannelKind },
}
impl PsdLayer {
/// Create a new photoshop layer
pub fn new(
layer_record: &LayerRecord,
psd_width: u32,
psd_height: u32,
group_id: Option<u32>,
channels: LayerChannels,
) -> PsdLayer {
Ps... | Rust | 0 |
unction,
/// and provide a `pub const fn from_parts` with equivalent functionality.
///
/// In the distant future, it would be nice if this accepted other kinds of
/// ranges too.
///
/// # Examples
///
/// ```
/// use arcstr::{ArcStr, Substr};
/// const FOOBAR: ArcStr = arcstr::... | Rust | 0 |
f();?VU" #E,,? @ I IE*&q)
i!1!122((G)#
+!,((5":.[7*+!#++g"6
BGGGOOG, ))M
"C
z)S))ic I-I
g
%.E MMO{{011 !I
Y^^J7N]]95N)3
V!!%++.!"e&6&67
4
($T"'',,y*Lc%RS
"|HMMI;W... | Python | 1 |
(0)))
);
}
#[test]
fn test_minus_signed_zero_integer() {
assert_eq!(
integer::<(&str, ErrorKind)>("-0"),
Ok(("", TomlValue::Integer(0)))
);
}
#[test]
fn test_negative_integer() {
assert_eq!(
integer::<(&str, ErrorKind)>("-7"),... | Rust | 0 |
de!(PGMCondition, FlowCondition::IfFlag(vec!["$My_Mixed_Flag".to_string()]) =>
node!(PGMTest, 2, FlowID::from_int(2)),
),
node!(PGMCondition, FlowCondition::IfFlag(vec!["my_flag".to_string()]) =>
node!(PGMTest, 3, FlowID::from_int(3)),
... | Rust | 0 |
[recvmsg(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/recvmsg.html)
pub fn recvmsg<'a>(fd: RawFd, iov: &[IoVec<&mut [u8]>],
mut cmsg_buffer: Option<&'a mut Vec<u8>>,
flags: MsgFlags) -> Result<RecvMsg<'a>>
{
let mut address = mem::MaybeUninit::uninit();
l... | Rust | 0 |
assert!(dead_defn.lookup(&"dead".into()).is_some());
// but not before
assert!(expands_to_defn.lookup(&"dead".into()).is_none());
// and not outside
assert!(afterwards.lookup(&"dead".into()).is_none());
}
fn fake_macro(name: &str) -> DeclarativeMacroItem {
// for thi... | Rust | 0 |
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> ... | Python | 1 |
"""
This module contains constants for Language model.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from django.utils.translation import gettext_lazy as _
if TYPE_CHECKING:
from typing import Final
from django.utils.functional import Promise
MELLOW_APRICOT: Final = "#FFBB78"
FOR... | Python | 1 |
from os import system
from numpy import int64, int16, float64, float16
from pandas import read_table, read_pickle
def x64tox16(dtype):
if dtype == int64: return int16
if dtype == float64:
return float16
else:
raise ValueError
def binarise(time_slots_):
for time_slot in time_slots_:
... | Python | 1 |
VM...")
compute_client.virtual_machines.generalize(resource_group, vm_name)
# Step 3: Create image from VM
print("Creating image from VM...")
image_params = Image(
location=location,
source_virtual_machine=SubResource(
id=f"/subscriptions/{subscri... | Python | 1 |
// splits concatenated DER files (why doesn't rustls/webpki do this?)
pub fn split_der(der_blob: &[u8]) -> Result<Vec<&[u8]>> {
let mut index = 0usize;
let mut start_index = 0usize;
let mut results = vec![];
while index < der_blob.len() {
if der_blob[index] != 0x30 {
// class: univer... | Rust | 0 |
)
engine = Engine(args.model_path, engine_config, csv=args.csv)
requests = sample_requests(args.dataset, args.num_prompts,
engine.tokenizer)
engine.process_request(requests,
temperature=args.temperature,
top_p=args.to... | Python | 1 |
def main():
partOne()
partTwo()
def sortedAndDifference(line):
isSorted = (all(line[i] < line[i + 1] for i in range(len(line) - 1))
or all(line[i] > line[i + 1] for i in range(len(line) - 1)))
difference = all(1 <= abs(line[i] - line[i + 1]) <= 3 for i in range(len(line) - 1))
retu... | Python | 1 |
animateTransform;
circle;
clipPath;
defs;
desc;
discard;
ellipse;
feBlend;
feColorMatrix;
feComponentTransfer;
feComposite;
feConvolveMatrix;
feDiffuseLighting;
feDisplacementMap;
feDistantLight;
feDropShadow;
feFlood;
feFuncA;
feFuncB;
feFuncG... | Rust | 0 |
}
/// Spawns a process with arguments for `apply(module, function, arguments)` on its stack.
///
/// This allows the `apply/3` code to be changed with `apply_3::set_code(code)` to handle new
/// MFA unique to a given application.
pub fn spawn_apply_3(
parent_process: &Process,
o... | Rust | 0 |
_string(&controller.favorite_list())?)?;
}
character_psd_data.insert(character_name, (controller, Default::default()));
}
CHARACTER_PSD_DATA.set(character_psd_data).unwrap();
HttpServer::new(|| App::new().service(character_names).service(character_layers).service(character_favorites).servic... | Rust | 0 |
# ==============================================================================
# Copyright 2019-2020 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://ww... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.