text string | label_name string | labels int64 |
|---|---|---|
}
fn element_node_count(&self, element_index: usize) -> usize {
self.schwarz_connectivity
.get(element_index)
.expect("Element index is assumed to be in bounds")
.len()
}
fn populate_element_nodes(&self, output: &mut [usize], element_index: usize) {
... | Rust | 0 |
crate::memory::GuestAddressSpaceViewMut::from_vmcs(
&vcpu.vmcs,
&mut self.guest_space,
)?;
let event = Event::new(kind, space, responses)?;
dev.write().on_event(event)
}
fn map_data(
image: &[u8],
addr: &GuestPhysAddr,
space: &mut GuestA... | Rust | 0 |
nn.ReLU(),
)
def forward(self, f_list):
f = f_list[-1]
f = self.aspp(f)
low_level_features = f_list[0]
low_h, low_w = low_level_features.size(2), low_level_features.size(3)
low_level_features = self.reduce(low_level_features)
... | Python | 1 |
"""
自然语言配置解析模块
负责解析自然语言配置
"""
from .parser import NLConfigParser
__all__ = ["NLConfigParser"] | Python | 1 |
output.append(Output[key[18:]](outputArgd))
except Exception as e:
return f"[Error] 初始化输出器失败。{e}"
return output
def _runNewDoc(self): # 取 self._queuedList 首位任务,提交执行
if not self._queuedDocs:
logger.warning("文档任务: queuedDocs 已空")
return
... | Python | 1 |
gency contacts and medical information
- Local customs and etiquette tips
- Transportation tips
- Budget breakdown
- Weather forecast for travel dates
- Alternative activities in case of weather changes"""
def format_preferences(preferences: TravelPreferences) -> str:
"""Format travel preferences into a structured... | Python | 1 |
second Monday of June every year.
# From 2023, the date changed to Jun 17 (Special Observed for 2023 on Jun 16).
if self._year <= 2022:
# Queen's Birthday.
self._add_holiday_2nd_mon_of_jun("Queen's Birthday")
else:
# King's Birthday.
self._add_ho... | Python | 1 |
{
let program = input();
b.iter(|| {
let program = program.clone();
black_box(program);
})
}
#[bench]
fn ast_clone_to_stable(b: &mut Bencher) {
let program = input();
b.iter(|| {
let program = program.clone();
let v = swc_ecma_plugin_ast::Program::from_unstable(pro... | Rust | 0 |
a = [5, 5, 10, 100, 10, 5]
cur = a[0]
per = a[0]
for i in range(1, len(a)):
cur = max(cur, a[i]+cur)
per = max(cur, per)
print(per)
print(5&10) | Python | 1 |
#Convolutional Neural Network (CNN) : loading and running a trained model
#Built with Tensorflow 2
#Copyright 2019 Denis Rothman MIT License. READ LICENSE.
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
from keras.preprocessing.... | Python | 1 |
use std::io::{stdin, BufRead};
use intcodeint::Machine;
fn main() {
let stdin = stdin();
let handle = stdin.lock();
let mut lines = handle
.lines()
.map(|result| result.expect("input/output error"));
if let Some(code) = lines.next() {
let nums: Vec<isize> = code
.s... | Rust | 0 |
return 1.0 - pred.mean()
if y == 1: # GT 全白
return pred.mean()
# ─── object-aware term ─────────────────────────────────────────────────
S_fg = _object_score(pred[gt > 0.5])
S_bg = _object_score(1 - pred[gt <= 0.5])
s_object = y * S_fg + (1 - y) * S_bg
# ─── region-aware term ... | Python | 1 |
_score,
*max_degree,
*min_degree,
size_score,
);
score
})
.unwrap()
.clone();
let (v1, v2) = edge;
let mut size = 1;
if !gro... | Rust | 0 |
_start_time)
except:
time_str = "?"
pydev_runfiles_xml_rpc.notifyTest(cond, captured_output, error_contents, address[0], address[1], time_str)
def startTest(self, test):
test._pydev_start_time = time.time()
file, test = self._get_test_address(test)
pydev_runfile... | Python | 1 |
().unwrap(),
Bytes::from_static(&[
MARKER,
SIGNATURE,
string::MARKER_TINY | 14,
b'R',
b'E',
b'T',
b'U',
b'R',
b'N',
b' ',
b'$',
... | Rust | 0 |
*
fn generate(sender: mpsc::SyncSender<Vec<u64>>, input: u64, fn_next: FnNext, n: usize) {
let mut i: usize = 0;
let mut total_i: usize = 0;
let mut c: u64 = input;
loop {
let mut v: Vec<u64> = Vec::with_capacity(CHUNK_SIZE);
while i < CHUNK_SIZE && total_i < n {
v.push(c);
... | Rust | 0 |
o[1]
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
if ratio_diff < best_ratio_diff:
best_ratio_diff = ratio_diff
best_ratio = ratio
elif ratio_diff == best_ratio_diff:
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
best_r... | Python | 1 |
#
G = scipy.sparse.csr_array([[1.]])
G.data.flags['WRITEABLE'] = False
shortest_path(G, method=method)
def test_NaN_warnings():
with warnings.catch_warnings(record=True) as record:
shortest_path(np.array([[0, 1], [np.nan, 0]]))
for r in record:
assert r.category is not RuntimeWar... | Python | 1 |
TestBeamAnalysis.HcalFactor = cms.double(' + hcal + ') \n\n')
pfile.write('process.maxEvents = cms.untracked.PSet( \n')
pfile.write(' input = cms.untracked.int32(' + stat + ') \n')
pfile.write(') \n\n')
pfile.write('process.g4SimHits.Physics.type = "SimG4Core/Physics/' + phys + '" \n\n')
pfile.write('process... | Python | 1 |
import unittest
import sys
import numpy as np
sys.path.append("../..")
from solution import DiffOpt, QP_0, QP_1, QP_2
class testProblem(unittest.TestCase):
problem = DiffOpt
def set_(self, problem):
self.problem = problem
def test_QP0(self):
QP = QP_0
c = np.ones(2)
pr... | Python | 1 |
from appfl.login_manager.globus import GlobusLoginManager
def auth():
"""Command line interface for authenticating with Globus Auth."""
prompt = "Please select whether you are authenticating for the federated learning server or client (Enter 1 or 2)"
while True:
mode = input(
f"{prompt}... | Python | 1 |
import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST2G")
process.maxEvents.input = 3
process.WhatsItESProducer = cms.ESProducer("WhatsItESProducer")
process.DoodadESSource = cms.ESSource("DoodadESSource")
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring('file:testSlimmi... | Python | 1 |
let nibble = (ch & (15u64 << ((15 - x) * 4) as u64)) >> (((15 - x) * 4) as u64);
if !latch { latch = nibble != 0 }
if latch {
try!(write!(f, "{:x}", nibble));
}
}
}
Ok(())
}
}
#[cfg(feature="std")]
impl From<&'static str> for $name {
fn from(s: &'static str) -> Self {... | Rust | 0 |
al_core.pipeline.social_auth.social_user",
"social_core.pipeline.user.get_username",
"social_core.pipeline.user.create_user",
"social_core.pipeline.social_auth.associate_user",
"social_core.pipeline.social_auth.load_extra_data",
... | Python | 1 |
import mysql.connector
def get_db_connection():
config = {
"user": "root",
"password": "Sanidhya@28",
"host": "localhost",
"database": "qc_lab"
}
return mysql.connector.connect(**config)
| Python | 1 |
xceeds
_ = Expression.prompt([
{'role': admin_role, 'content': content.value},
{'role': 'user', 'content': "What's the most tragic event in the novel?"}
])
# Case 3; both exceed
_ = Expression.prompt([
{'role': admin_role, 'content': content.value},
{'role': 'user', 'con... | Python | 1 |
import time
import allure
import pytest
from api.usermanagement import usermanagement
import warnings
from Logs.logs import logging
warnings.simplefilter("ignore", ResourceWarning)
@allure.description(
str(usermanagement.url) + '\n\n' + str(usermanagement.header_print) + '\n\n' + str(usermanagement.response_te... | Python | 1 |
0x0022;
pub const SPI_GETFASTTASKSWITCH: UINT = 0x0023;
pub const SPI_SETFASTTASKSWITCH: UINT = 0x0024;
pub const SPI_SETDRAGFULLWINDOWS: UINT = 0x0025;
pub const SPI_GETDRAGFULLWINDOWS: UINT = 0x0026;
pub const SPI_GETNONCLIENTMETRICS: UINT = 0x0029;
pub const SPI_SETNONCLIENTMETRICS: UINT = 0x002A;
pub const SPI_GET... | Rust | 0 |
block[b] = (v0 ^ v1) ^ (v2 ^ v3);
}
const u64 last = sipblock[EDGE_BLOCK_MASK];
for (short s = EDGE_BLOCK_MASK; s >= 0; s--)
{
u64 lookup = s == EDGE_BLOCK_MASK ? last : sipblock[s] ^ last;
u64 u = lookup & EDGEMASK;
u64 v = (lookup >> 32) & EDGEMASK;
u64 a = u | (v << 32);
u64 b = v | (u << ... | Rust | 0 |
er_matches = self.match_career_paths(text)
# Combine results
return {
"career_clusters": clusters,
"sentiment_analysis": sentiment,
"career_matches": career_matches,
"input_text": text
}
# Example usage
if __name__ == "__main__":
# Sa... | Python | 1 |
].message_type = modules_dot_map_dot_proto_dot_map__geometry__pb2._CURVE
_STOPSIGN.fields_by_name['overlap_id'].message_type = modules_dot_map_dot_proto_dot_map__id__pb2._ID
_STOPSIGN.fields_by_name['type'].enum_type = _STOPSIGN_STOPTYPE
_STOPSIGN_STOPTYPE.containing_type = _STOPSIGN
DESCRIPTOR.message_types_by_name['S... | Python | 1 |
_u8(0b_000_u8)?; // I1 Bit set for options
w.write_i32::<LittleEndian>(length as i32)?; // I4 LENGTH OF VALUE
w.write_i32::<LittleEndian>(*offset as i32)?; // I4 position
*offset += length as i32;
Ok(())
}
// Copyright (C) 2022 <NAME> <<EMAIL>>
// This file is subject to th... | Rust | 0 |
from reactxen.utils.model_inference import watsonx_llm
from agent_hive.utils import json_parser
from langchain.tools import BaseTool
from agent_hive.agents.base_agent import BaseAgent
from agent_hive.logger import logger
class SimpleAgent(BaseAgent):
"""
This class represents a simple agent that can execute a... | Python | 1 |
import numpy as np
import cv2
import imutils
import datetime
# Load the Haar cascade classifier for detecting guns
gun_cascade = cv2.CascadeClassifier("cascadee.xml")
# Open the video file for capturing frames
camera = cv2.VideoCapture(0)
# Initialize a variable to track whether a gun is detected
gun_exist = False
... | Python | 1 |
_get::benches,
scoped::single_set::benches,
scoped::single_set_get::benches,
}use std::fs;
extern crate eventlog_rs;
#[macro_use]
extern crate log;
fn main() {
env_logger::builder().filter(None, log::LevelFilter::Info).init();
let mut event_data = vec![];
let path = "/sys/firmware/acpi/tables/TDE... | Rust | 0 |
ve(Debug)]
pub struct PathTable {
set: RegexSet,
table: Vec<(String, Route)>,
}
impl PartialEq for RoutingTable {
fn eq(&self, other: &RoutingTable) -> bool {
return self.table == other.table;
}
}
impl Eq for RoutingTable {}
impl PartialEq for PathTable {
fn eq(&self, other: &PathTable) -... | Rust | 0 |
).unwrap();
let mut displayed_bank_cards_amount_last_update = Instant::now();
let mut last_player_action = MessageAction::Restart;
while let Some(event) = window.next() {
if Ok(Event::Disconnect) == channel_receiver.try_recv() {
break;
}
let pressed_key = event.pr... | Rust | 0 |
6}, OpaqueExtrinsic, AnySignature
};
/// An index to a block.
pub type BlockNumber = u32;
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
pub type Signature = AnySignature;
/// Some way of identifying an account on the chain. We intentionally make it equivalent
/// to the ... | Rust | 0 |
517u32;
#[doc = "*Required features: `\"Win32_NetworkManagement_NetManagement\"`*"]
pub const NERR_RplBootStartFailed: u32 = 2518u32;
#[doc = "*Required features: `\"Win32_NetworkManagement_NetManagement\"`*"]
pub const NERR_RplCannotEnum: u32 = 2615u32;
#[doc = "*Required features: `\"Win32_NetworkManagement_NetManage... | Rust | 0 |
.set_partner(1, 2)
tree.add_person(3, "Rhaenys")
tree.add_child(1, 3)
tree.add_person(4, "Corlys")
tree.set_partner(3, 4)
tree.add_person(5, "Laena")
tree.add_person(6, "Laenor")
tree.add_child(3, 5)
tree.add_child(3, 6)
tree.add_person(7, "Baelon")
tree.add_person(8, "Aly... | Python | 1 |
fn to_partial_map_index(ray_dir: f32, ray_pos: f32) -> usize {
if ray_pos == ray_pos.trunc() {
if ray_dir > 0.0 {
ray_pos as usize
} else {
ray_pos as usize - 1
}
} else {
ray_pos as usize
}
}
pub fn to_map_... | Rust | 0 |
ions::Empty).into_iter().map(|m| {
LegalMove::from(m)
}).collect::<Vec<LegalMove>>()
);
}
}
#[test]
fn test_oute_only_moves_with_kyou_occupied_opponent_gote() {
let blank_banmen = Banmen([[Blank; 9]; 9]);
const POSITIONS:[(usize,usize); 2] = [
(0,8),(8,8)
];
const OCC_POSITIONS:[(usize,u... | Rust | 0 |
;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _vx_graph {
_unused: [u8; 0],
}
#[doc = " \\brief An opaque reference to a graph"]
#[doc = " \\see vxCreateGraph"]
#[doc = " \\ingroup group_graph"]
#[doc = " \\extends vx_reference"]
pub type vx_graph = *mut _vx_graph;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
p... | Rust | 0 |
dency>,
}
impl IComponent1 for Component1 {
fn dependency(&self) -> &dyn IDependency {
Arc::as_ref(&self.dependency)
}
}
#[derive(Component, Debug)]
#[shaku(interface = IComponent2)]
struct Component2 {
#[shaku(inject)]
dependency: Arc<dyn IDependency>,
}
impl IComponent2 for Component2 {
... | Rust | 0 |
conn.commit()
#Devuelve 1 si la inserción fue exitosa
rows = cursor.rowcount
except Error as e:
print("Error al eliminar Tarifa:", e)
finally:
if cursor:
cursor.close()
conexion = self.closeConnection(conn)
retu... | Python | 1 |
accumulator = e._getElementsByObj(obj, accumulator)
return accumulator
def getElementsByType(self, element):
""" Gets elements based on the type, which is function from text.py, draw.py etc. """
obj = element(check_grammar=False)
return self._getElementsByObj(obj,[])
def isIns... | Python | 1 |
c175, "prwtv20u5m0r", -46.801043021, 155.622507705},
{0x4fa56eeda8aeda6c, "9ykqxve8pve6", 36.329070463, -94.927717648},
{0x458581bb108bb129, "8q2s3fshjfsk", 35.917753992, -167.964224886},
{0x1d1ae9988087df20, "3nefm640hzgk", -8.030963593, -129.492894785},
{0x9b337d43021ea21a, "mdtruhs23u... | Rust | 0 |
rom_file(assets_dir.join("input_bindings.ron"))
.unwrap(),
)?
.with(
systems::CameraMotionSystem::new(),
"camera_motion_system",
&["input_system"],
)
.with_bundle(TransformBundle::new())?
.with_bundle(
PhysicsBundle:... | Rust | 0 |
hon_version():
sys.exit(1)
print("\n📦 Installing required packages...")
# Install from requirements file
if install_requirements_file():
print("✅ All packages installed successfully")
else:
print("❌ Some packages failed to install")
print("You can try installin... | Python | 1 |
import os
import random
import pickle
import hashlib
import aiohttp
from fake_useragent import UserAgent
FILEPATH = os.path.dirname(os.path.abspath(__file__))
# prevent caching
USER_AGENT_LIST = [
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0",
"Mozilla/5.0 (Windows NT 10.... | Python | 1 |
"""Build OSC bundles for client applications."""
from pythonosc import osc_bundle
from pythonosc import osc_message
from pythonosc.parsing import osc_types
# Shortcut to specify an immediate execution of messages in the bundle.
IMMEDIATELY = osc_types.IMMEDIATELY
class BuildError(Exception):
"""Error raised whe... | Python | 1 |
calls the specified closure
/// on the native FFI pointer underlying the python object.
///
/// May be more efficient than `to_py_object` because it does not need
/// to touch any reference counts when the input object already is a python object.
#[inline]
fn with_borrowed_ptr<F, R>(&self, py: ... | Rust | 0 |
"""Test the TextLine class matching and compound splitting functionality."""
import pytest
from extraction.features.utils.text.stemmer import _split_compounds, find_matching_expressions
@pytest.mark.parametrize(
"tokens, split_threshold, expected",
[
(["Sandstein"], 0.4, ["Sand", "Stein"]),
... | Python | 1 |
from picamera2 import Picamera2, Preview
import time
from flask import Flask, render_template, Response
import os
import math
import numpy as np
import pygame
import busio
import board
import libcamera
from scipy.interpolate import griddata
from colour import Color
import adafruit_amg88xx
from PIL import Image, ImageOp... | Python | 1 |
{format, format_args, LineWidth};
/// use rome_formatter::prelude::*;
///
/// let elements = format!(SimpleFormatContext::default(), [
/// group_elements(&format_args![
/// token("["),
/// soft_block_indent(&format_args![
/// token("'Good morning! How are you today?',"),
/// ... | Rust | 0 |
v,
Err(_) => {
self.tcx.sess.delay_span_bug(
span,
"implied_outlives_bounds failed to instantiate"
);
return vec![];
}
};
// Instantiation may have produced new inference variables and const... | Rust | 0 |
ent.status = AppointmentStatus.CANCELLED
await db.commit()
await db.refresh(appointment)
return appointment
@staticmethod
async def delete_appointment(db: AsyncSession, appointment_id: int) -> None:
appointment = await AppointmentService.get_appointment(db, appointment_id)
... | Python | 1 |
# class_names = ['Pedestrian', 'Cyclist']
class_names = ['Car']
# label_dir = Path('/home/anshul/es3cap/kitti_data/testing/ecp_results/data')
label_dir = None
proc = Processor_ROS(config_path, ckpt_path, label_dir)
proc.initialize()
# code added for using ROS
rospy.init_node('second_r... | Python | 1 |
}
struct List<'a, T> {
points: &'a [Point<T, 2>],
order: &'a [PointId],
hashes: Vec<u64>,
prev: Vec<usize>,
next: Vec<usize>,
}
impl<'a, T> List<'a, T> {
fn new(points: &'a [Point<T, 2>], order: &'a [PointId]) -> List<'a, T> {
let size = order.len();
let mut prev = Vec::with_capacity(size);
l... | Rust | 0 |
from kfai.extractors import (
fetch_raw_data,
process_failed_videos,
transcribe_failures,
)
from kfai.loaders import build_vector_store, gradio_app, interactive_qa
from kfai.transformers import clean_locally
RESPONSE_MAP = {
"1": fetch_raw_data.run,
"2": process_failed_videos.run,
"3": transcri... | Python | 1 |
from __future__ import division
import numpy as np
import scipy as sp
import pylab as py
from scipy.cluster.vq import kmeans2,whiten
'''
the scipy contain a kmeans,so there is no need to write one
bu for the convenience of using,I pack it with my code
I don't know how to translate the input space to whitened space
... | Python | 1 |
_forward! {
get_me, log_out, close, get_updates, set_webhook, delete_webhook, get_webhook_info,
forward_message, copy_message, send_video_note, send_media_group, send_location,
edit_message_live_location, edit_message_live_location_inline,
stop_message_live_location, stop_message_live_lo... | Rust | 0 |
unsafe extern "C" fn wrap_class_method(
cls: *mut $crate::_detail::ffi::PyObject,
args: *mut $crate::_detail::ffi::PyObject,
kwargs: *mut $crate::_detail::ffi::PyObject)
-> *mut $crate::_detail::ffi::PyObject
{
const LOCATION: &'static str = _cpytho... | Rust | 0 |
"UPDATE strategies SET status = ?, updated_at = ? WHERE id = ?",
(status, datetime.now(), strategy_id),
)
if not cursor.rowcount:
raise StrategyManagementError(f"策略不存在: {strategy_id}")
conn.commit()
logger... | Python | 1 |
millis(50));
let mut group = criterion.benchmark_group("instruction-requests");
let domain_name = "domain";
let create_domain = RegisterBox::new(IdentifiableBox::Domain(Domain::new(domain_name).into()));
let account_name = "account";
let account_id = AccountId::new(account_name, domain_name);
l... | Rust | 0 |
m4[0]: PA12:D PB08:D PB12:C
// sercom4[1]: PA13:D PB09:D PB13:C
// sercom4[2]: PA14:D PB10:D PB14:C
// sercom4[3]: PA15:D PB11:D PB15:C
#[cfg(any(feature = "samd21g18a", feature = "samd21j18a"))]
pad!(Sercom4Pad0 {
Pa12(PfD),
Pb8(PfD),
Pb12(PfC),
});
#[cfg(any(feature = "samd21g18a", f... | Rust | 0 |
n ["r1", "r2", "r3", "r4"]:
router_compare_json_output(rname, "show ip route json", "show_ip_route.ref")
def test_ldp_adjacencies():
logger.info("Test: verify LDP adjacencies")
tgen = get_topogen()
# Skip if previous fatal error condition is raised
if tgen.routers_have_failure():
pyte... | Python | 1 |
::OpenParen)?;
let args = parse_comma_separated_list(tq, &TokenKind::CloseParen, parse_type, indent_level, target)?;
tq.expect(&TokenKind::Arrow)?;
let ret = parse_type(tq, indent_level, target)?;
Ok(func_type(args, ret))
}
else if tq.is_next(&TokenKind::OpenCurly)
{
... | Rust | 0 |
R(reader)
}
}
#[doc = "Register `I2SPR` writer"]
pub struct W(crate::W<I2SPR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<I2SPR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut... | Rust | 0 |
umber", ()).await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct Provider {
id: AtomicU64,
client: Client,
url: Url,
}
#[derive(Error, Debug)]
/// Error thrown when sending an HTTP request
pub enum ClientError {
/// Thrown if the request failed
#[error(transparent)]
ReqwestError(#[f... | Rust | 0 |
im = embs.weight.shape
# The model may or may not have a '<mask>' embedding yet
assert (
len(dictionary) <= vocab_size <= len(dictionary) + 1
), f"Dictionary len ({len(dictionary)}) doesn't match embs shape ({embs.weight.shape})"
# TODO: we should reuse the pretrained model dict which already h... | Python | 1 |
h period in which the rate index is below the
/// agreed strike rate)
#[serde(rename = "FLR")]
Flr,
/// Forward Rate Agreement
#[serde(rename = "FRA")]
Fra,
/// Loan/lease
#[serde(rename = "LOANLEASE")]
Loanlease,
/// Spot forward
#[serde(rename = "SPOTFWD")]
Spotfwd,
/// Transmission
#[serde(rename = "XM... | Rust | 0 |
MAX_BLOCK_SIZE,
GET_HW_INFO,
SET_KS_POWER,
RESET_STOP_TIMED,
MEASURE_RTCK_REACT,
SELECT_IF,
RW_MEM_ARM79,
GET_COUNTERS,
READ_DCC,
GET_CPU_CAPS,
EXEC_CPU_CMD,
SWO,
WRITE_DCC_EX,
UPDATE_FIRMWARE_EX,
FILE_IO,
... | Rust | 0 |
hv| hv.to_str()) {
Some(Ok(accept)) => accept,
_ => return rsp,
};
let mut encodings = accept
.split(',')
.filter_map(|s| {
let mut parts = s.splitn(2, ';');
let alg = match Encoding::from_str(parts.next()?.trim()) {
... | Rust | 0 |
str::contains("WSLGIT=1"))
.stdout(predicate::str::contains("WSLENV=WSLGIT"));
Command::cargo_bin(env!("CARGO_PKG_NAME"))
.unwrap()
// Use pretty format to call 'env'
.args(&["log", "-1", "--pretty=format:$(env)"])
.env("WSLGIT_USE_INTERACTIVE_SHELL",... | Rust | 0 |
structopt(
name = "PATH_TO_SOURCE_FILE",
default_value = DEFAULT_SOURCE_DIR,
)]
source_files: Vec<String>,
/// Do not emit source map information along with the compiled bytecode.
#[structopt(long = "no-source-maps")]
no_source_maps: bool,
/// Type... | Rust | 0 |
::js_sys::Reflect::set(
self.as_ref(),
&JsValue::from("iceTransportPolicy"),
&JsValue::from(val),
);
debug_assert!(
r.is_ok(),
"setting properties should never fail on our dictionary objects"
);
let _ = r;
self
}
... | Rust | 0 |
import numpy as np
import random
from time import sleep
import math
import frucht_v3
from random import choices
t = 10
k = 20
width = height = 100.0
import networkx as nx
g = nx.DiGraph()
edges = [['a', 'b'],
['b', 'c'],
['c', 'd'],
['d', 'a']]
# g.add_edges_from(edges)
# replace actu... | Python | 1 |
on structure
InvalidJson,
/// Invalid Description
InvalidDescription,
/// AuthorizedAccountsAGV has not been found on the blockchain
AuthorizedAccountsAGVNotFound,
/// Settings data is too short to be valid
AssetGeneratingJsonTooShort,
/// Settings data is too long to be valid
... | Rust | 0 |
g on 127.0.0.1 with port 8080");
HttpServer::new(|| {
App::new()
.service(Files::new("/static", "static").show_files_listing())
.route("/", web::get().to(index))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
use super::*;
use polars_core::prelude::*;
#[test]
fn test_sl... | Rust | 0 |
train_path = 'data/mod_train_2.txt' # 'data/mod_train_2.txt'
test_path = 'data/mod_test_2.txt'
result_path = 'result/mod_test_2.pred.txt'
log_path = 'result/mod_test_2.log'
save_prefix = 'epochs'
pretrain_path = '' # 'param/dia_all_epo20_dim24_conv10/dia_all_epo20_dim24_conv10_filled.pt' # 'param/dia_all_trans_mod_ep... | Python | 1 |
from __future__ import annotations
from dials.algorithms.profile_model.gaussian_rs.calculator import (
_select_reflections_for_sigma_calc,
)
from dials.array_family import flex
def test_select_reflections_for_sigma_calc():
"""Test the reflection selection helper function."""
# first select all if below t... | Python | 1 |
const STBTT_MAC_LANG_RUSSIAN: i32 = 32;
pub const STBTT_MAC_LANG_SPANISH: i32 = 6;
pub const STBTT_MAC_LANG_SWEDISH: i32 = 5;
pub const STBTT_MS_EID_SHIFTJIS: i32 = 2;
pub const STBTT_MS_EID_SYMBOL: i32 = 0;
pub const STBTT_MS_EID_UNICODE_BMP: i32 = 1;
pub const STBTT_MS_EID_UNICODE_FULL: i32 = 10;
pub const STBTT_MS_... | Rust | 0 |
"请输入x的上界(函数显示范围):",
parent=tk_root,
initialvalue=1.0
)
domain = (l, r)
min_point, max_point = find_function_extrema(expr, f, x, domain)
print(1)
xl = min(int(l-1), -int(r+2))
xr = max(-int(l-1), int(r+2))
yl = min(int(min_poin... | Python | 1 |
;
},
'R' =>
{
let mut move_dir = waypoint - pos;
match dist
{
90 => move_dir = move_dir.rotate_90_right(),
180 => move_dir = move_dir.rotate_180(),
270 => move_dir = move_dir.r... | Rust | 0 |
from model import *
from Quali_runner import *
import csv
import pandas as pd
import joblib
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score, mean_squared_error
def train_model():
dataset = []
model = joblib.load("f1_qu... | Python | 1 |
_u8, middle_u32, suffix_u8) = unsafe { spirv_u8.align_to::<u32>() };
assert_eq!(prefix_u8.len(), 0);
assert_eq!(suffix_u8.len(), 0);
middle_u32
};
let create_info = vk::ShaderModuleCreateInfo::builder().code(spirv_u32);
let vk_shader_module = unsafe {
device
.cre... | Rust | 0 |
ine character in addition to carriage return and/or linefeed.
VEOL = 6,
/// Additional end-of-line character.
VEOL2 = 7,
/// Continues paused output (normally control-Q).
VSTART = 8,
/// Pauses output (normally control-S).
VSTOP = 9,
/// Suspends the current program.
VSUSP = 10,
... | Rust | 0 |
ut
class GatedFusion(nn.Module):
"""
Efficient Large-Scale Multi-Modal Classification,
https://arxiv.org/pdf/1802.02892.pdf.
"""
def __init__(self, input_dim=512, dim=512, output_dim=100, x_gate=True):
super(GatedFusion, self).__init__()
self.fc_x = nn.Linear(input_dim, dim)
... | Python | 1 |
track_folder = track_folders[track_index]
files = [os.path.join(track_folder, f) for f in os.listdir(track_folder) if f.endswith('.wav')]
files = sorted(files)[:8] # Limit to the first 8 files
play_audio(track_folder, files, temp_folder, stop_event, pause_event, fastfo... | Python | 1 |
cast(tf.squeeze(pred), tf.int64)
accuracy = tf.reduce_mean(
tf.cast(tf.equal(pred, all_labels), tf.float32))
one_hot_labels = tf.one_hot(all_labels, 12)
loss = tf.losses.softmax_cross_entropy(one_hot_labels, all_logits)
return loss, accuracy
def build_loss_accuracy(
inputs, train,
re... | Python | 1 |
than the target
// range, which in turn lets us not worry about various boundary cases
// below.
// The wavelengths of the virtual samples at the endpoints are set so
// that they are one destination sample spacing beyond the destination
// endpoints. (Note that this potentially means that if we ... | Rust | 0 |
#!/usr/bin/env python
# vim: ts=4:sw=4:expandtab
# BleachBit
# Copyright (C) 2008-2025 Andrew Ziem
# https://www.bleachbit.org
#
# This program 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... | Python | 1 |
}
}
}
pub(crate) fn to_typeinfo(&self) -> TypeInfo {
match self {
Literal::String(s) => TypeInfo::Str(s.as_str().len() as u64),
Literal::Numeric(_) => TypeInfo::Numeric,
Literal::U8(_) => TypeInfo::UnsignedInteger(IntegerBits::Eight),
Literal::U16... | Rust | 0 |
}
Some(())
}
fn update_tweak<T: 'static + FromStr + Clone + Send>(
tweak: &mut TweakValue,
file: &'static str,
) -> Option<()> {
let last_modified = last_modified(file)?;
if tweak.value.is_none()
|| last_modified
.duration_since(tweak.fil... | Rust | 0 |
ntic_maps.shape)
# exit()
if return_dict:
return {
"images": images,
"depth_maps": depth_maps,
"normal_maps": normal_maps,
"similarity_maps": similarity_maps,
"semantic_maps": semantic_maps,
"fragments": fragments,
}
el... | Python | 1 |
ster for HW triggers"]
pub result7: RESULT,
#[doc = "0x44 - Configuration register"]
pub cfg: CFG,
#[doc = "0x48 - General control register"]
pub gc: GC,
#[doc = "0x4c - General status register"]
pub gs: GS,
#[doc = "0x50 - Compare value register"]
pub cv: CV,
#[doc = "0x54 - Off... | Rust | 0 |
ement_rate': float(user_data['engagement_rate']),
'completion_rate': float(user_data['completion_rate']),
'favorite_rate': float(user_data['favorite_rate']),
'persona_description': cluster_description
}
# 如果有大模型特征,添加到用户画像
if user_id in llm_features:
... | Python | 1 |
component in components.iter() {
match component.id().peripheral_id().jep106() {
Some(id) if id == jep106::JEP106Code::new(0x00, 0x20) => {
// STMicroelectronics:
// STM32 parts need TRACE_IOEN set to 1 and TRACE_MODE set to 00.
log::debug!("STMicroel... | Rust | 0 |
line: String,
location: String,
author: String,
content: String,
}
impl Summary for Article
{
fn summarize_author(&self) -> String
{
self.author.clone()
}
fn summarize(&self) -> String
{
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
}
/* Tweet */
struct Tweet
{
username: S... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.