text string | label_name string | labels int64 |
|---|---|---|
/// An extension trait adding ICMP-related functionality to `Ipv4` and `Ipv6`.
pub trait IcmpIpExt: Ip {
/// The type of ICMP messages.
///
/// For `Ipv4`, this is `Icmpv4MessageType`, and for `Ipv6`, this is TODO.
type IcmpMessageType: Into<u8> + Copy;
/// Compute the length of the header of the ... | Rust | 0 |
nwrap(), 0b1);
assert_eq!(stream.pull_bits(3).unwrap(), 0b100);
}
#[test]
fn pull_bits_u16() {
let data: [u8; 3] = [0b10010011, 0b10101010, 0b11110000];
let mut stream = Stream::from(&data[..]);
assert_eq!(stream.pull_bits_u16(9).unwrap(), 0b100100110);
assert_eq!(stream.pull_bits_u16(12).unwrap()... | Rust | 0 |
import tkinter
import threading
from tkinter import messagebox
import sys
tasks = []
timer = threading
real_timer = threading
ok_thread = True
def get_entry(event=""):
text = todo.get()
hour = int(time.get())
todo.delete(0, tkinter.END)
time.delete(0, tkinter.END)
todo.focus_set()
add_list(te... | Python | 1 |
# Copyright 2012 Thomas Tempe <thomas.tempe@alysse.org>
# Copyright 2012 Roland Sieker <ospalh@gmail.com>
# Original: Damien Elmes <anki@ichi2.net> (as japanese/model.py)
# License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html
from .css import style
fields_list = ['Hanzi', 'Color', 'Pinyin', 'Eng... | Python | 1 |
dev = String::from("/dev/i2c-") + bus;
Ok(I2cAdapter {
bus: bus.parse::<u32>().map_err(|_| Error::new(EINVAL))?,
smbus: false,
fd: OpenOptions::new().read(true).write(true).open(i2cdev)?,
})
}
fn bus(&self) -> u32 {
self.bus
}
fn is_smbus(&s... | Rust | 0 |
|| {
let _ = black_box(test_graph_filter(&mut graph, false));
});
}
//#[bench]
fn bench_edgelist_generationr(b: &mut Bencher) {
let mut graph = load_cora().unwrap();
b.iter(|| {
let _ = black_box(test_edgelist_generation(&mut graph));
});
}
//#[bench]
fn bench_nodelabel_holdouts(b: &mu... | Rust | 0 |
import pytest
import pandas as pd
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
# sys.path.append(str(Path(ROOT / "game_engime" / "src")))
# print(str(Path(ROOT, "game_engime", "src")))
# sys.path.append(str(Path(ROOT.parent, "game_engine", "src", "models")))
# from models.dummy_m... | Python | 1 |
=> {}
Namespace(_) => {}
NamespaceUse(_) => {}
SetNamespaceEnv(_) => {}
FileAttributes(_) => {}
Module(_) => {}
SetModule(_) => {}
}
}
}
fn main() {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("... | Rust | 0 |
+ marker, timestamp=timestamp)
eeg.push_sample(marker=marker,timestamp=timestamp)
if do_fixation:
mywin.flip()
# offset
core.wait(soa)
mywin.flip()
if len(event.getKeys()) > 0 or (time.time() - start) > (record_duration_float+5):
... | Python | 1 |
Events
}
#[inline]
async fn setup_http_and_cluster(env: &Env) -> MainResult<HttpAndCluster> {
let http = HttpClient::new(env.token().to_string());
let http = Arc::new(http);
// todo make intents better
let intents = Intents::all();
let (cluster, events) = Cluster::builder(env.token(), intents)
.shard_scheme(Au... | Rust | 0 |
[")[1].split("]")[0]
return obj.pose.bones[bone_name[1:-1]]
animation_data = obj.animation_data
if animation_data:
fcurve_drivers = [fcurve_driver for fcurve_driver in animation_data.drivers]
fcurve_drivers.sort(key=lambda fcurve_driver: fcurve_driver.data_path)
... | Python | 1 |
result=False):
if not inspect.iscoroutinefunction(func):
raise TypeError("Consumer function must be a coroutine.")
@functools.wraps(func)
def wrapper(upstream):
async def run():
res = await func(upstream.run())
if return_result:
return res
ret... | Python | 1 |
PDPT, PDT, PGT)
///
/// See Intel Vol. 3A, Tables 4-14 through 4-19
pub struct PageTableEntryFlags: usize {
/// Set if this entry is valid and points to a page or table.
const PRESENT = 1 << 0;
/// Set if memory referenced by this entry shall be writable.
const WRITABLE = 1 << 1;
/// Set if memory refer... | Rust | 0 |
"action": "key_create",
}))
})
.buffer_unordered(10) // execute 10 `key_create`s simultaniously
.inspect(|_| {
tstat!("key_create,progress");
})
.collect();
tstat!("key_create,done");
let dest_accts: Vec<Account> = tokio_core
... | Rust | 0 |
# Copyright 2022 Google LLC
#
# 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... | Python | 1 |
8usize,
concat!("Alignment of ", stringify!(ovrLayerCube2__bindgen_ty_1))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<ovrLayerCube2__bindgen_ty_1>())).ColorSwapChain as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
... | Rust | 0 |
import logging
from fastapi import APIRouter
from fastapi import APIRouter, HTTPException
from ...core.bootstrapping_treeger import BT
# from ...schemas.scene import ResponseOfSceneNode
from icrms.itreeger import SceneNodeMeta
logger = logging.getLogger(__name__)
router = APIRouter(prefix='/scene', tags=['scene'])
... | Python | 1 |
PDF_ANNOTATION,
color_type: FPDFANNOT_COLORTYPE,
R: *mut c_uint,
G: *mut c_uint,
B: *mut c_uint,
A: *mut c_uint,
) -> FPDF_BOOL {
unsafe { crate::bindgen::FPDFAnnot_GetColor(annot, color_type, R, G, B, A) }
}
#[inline]
#[allow(non_snake_case)]
fn FPDF... | Rust | 0 |
ta. )
if field == "events":
m = md5_digest(line)
rpc_metrics[device]['digest'] = m
if m in rpc_metrics:
# metrics already counted, mark as dupe ignore
dupe = True
first_device=rpc_metrics[m]
... | Python | 1 |
5519e_sk";
fn generate<T: RngCore + CryptoRng>(mut rng: T) -> Self::Secret {
let mut bytes = [0u8; EXTENDED_KEY_SIZE];
rng.fill_bytes(&mut bytes);
bytes[0] &= 0b1111_1000;
bytes[31] &= 0b0011_1111;
bytes[31] |= 0b0100_0000;
ExtendedPriv(bytes)
}
fn compute_... | Rust | 0 |
p[4] == '-':
tmp[4] = get_committer_date(tmp[3])
if modified:
line = tmp[0].ljust(17)
line += tmp[1].ljust(12)
line += tmp[2].ljust(15)
line += tmp[3].ljust(12)
line += tmp[4].ljust(12)
if len(tm... | Python | 1 |
#
# file: esc10_cnn_deep_bn.py
#
# Deeper architecture applied to augmented ESC-10
#
# RTK, 10-Nov-2019
# Last update: 20-Nov-2019
#
################################################################
import time
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from ... | Python | 1 |
`"]
pub type IBUSERR_R = crate::R<bool, IBUSERR_A>;
impl IBUSERR_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> IBUSERR_A {
match self.bits {
false => IBUSERR_A::_0,
true => IBUSERR_A::_1,
}
}
#[doc = "Checks if the va... | Rust | 0 |
= matrix![1.0, 0.0, 0.0;
0.0, 1.0, 0.0;
0.0, 0.0, -1.0];
let qr = HouseholderQr::decompose(x.clone()).unpack();
verify_qr(x, qr);
}
{
let x = matrix![1.0, 0.0, 0.0;
0.0, -1.0, 0.0;
... | Rust | 0 |
to close the connection that have received the `Open` or
/// `Clone` calls. This is too much, as the connection might still be in a good shape.
fn open(
&mut self,
flags: u32,
mode: u32,
path: &mut dyn Iterator<Item = &str>,
server_end: ServerEnd<NodeMarker>,
);
... | Rust | 0 |
from bicycle_model import Bicycle, Manufacturer, BikeShop, Customer
"""create 6 bicycle models"""
b1 = Bicycle('slick', 9, 14, 40, 30, 1, 'Champion', 'Eagle', 0.1)
b2 = Bicycle('medium', 6, 16, 30, 75, 2, 'Tour', 'Eagle', 0.1)
b3 = Bicycle('medium', 6, 16, 15, 300, 3, 'Speedy', 'Eagle', 0.1)
b4 = Bicycle('slick', 9, ... | Python | 1 |
impl ToPrimitive for BigDecimal {
fn to_i64(&self) -> Option<i64> {
match self.sign() {
Sign::Minus | Sign::Plus => self.with_scale(0).int_val.to_i64(),
Sign::NoSign => Some(0),
}
}
fn to_u64(&self) -> Option<u64> {
match self.sign() {
Sign::Plus... | Rust | 0 |
from collections import defaultdict
import re
import six
from six.moves import xrange
from .ngram import NGram
class LangProfile(object):
MINIMUM_FREQ = 2
LESS_FREQ_RATIO = 100000
ROMAN_CHAR_RE = re.compile(r'^[A-Za-z]$')
ROMAN_SUBSTR_RE = re.compile(r'.*[A-Za-z].*')
def __init__(self, name=No... | Python | 1 |
#birth_year = input("enter your birth year")
#age = 2024 - int(birth_year)
#print(age)
# sum of two numbers using type conversion
first = input("first: ")
second = input("second: ")
sum = float(first) + float (second)
strsum = str(sum)
print("sum:", strsum) | Python | 1 |
ATTR_queue: 'workq@' + s2.hostname}
j = Job(TEST_USER, attrs=a)
jid = s1.submit(j)
a['Resource_List.' + self.cres] = 1
j = Job(TEST_USER, attrs=a)
jid2 = s1.submit(j)
s2.expect(JOB, {'job_state': 'Q'}, id=jid)
s2.expect(JOB, {'job_state': 'Q'}, id=jid2)
... | Python | 1 |
(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: samples,
dimension: wgpu::TextureDimension::D2,
... | Rust | 0 |
age,
UncompressedFloatFormat::F32F32F32F32,
MipmapsOption::NoMipmap,
)?;
Ok(texture)
}
<filename>src/messed_up_rugby_tests.rs
//Problem : Messed up Rugby
//Language : Rust
//Compiled Using : rustc
//Version : rustc 1.0.0
//Input for your program will be provided from STDIN
/... | Rust | 0 |
def min_steps_to_equal(a, b):
diff = abs(a - b)
steps = 0
for k in range(10, 0, -1):
steps += diff // k
diff %= k
return steps
a, b = map(int, input().split())
result = min_steps_to_equal(a, b)
print(result)
| Python | 1 |
#[doc = "*Required features: 'Win32_Media_MediaFoundation'*"]
pub const MF_CAPTURE_ENGINE_SINK_TYPE_RECORD: MF_CAPTURE_ENGINE_SINK_TYPE = 0i32;
#[doc = "*Required features: 'Win32_Media_MediaFoundation'*"]
pub const MF_CAPTURE_ENGINE_SINK_TYPE_PREVIEW: MF_CAPTURE_ENGINE_SINK_TYPE = 1i32;
#[doc = "*Required features: '... | Rust | 0 |
PSMRegisters {
(0x00 => force_on: ReadWrite<u32, FRCE_ON::Register>),
(0x04 => force_off: ReadWrite<u32, FRCE_OFF::Register>),
(0x08 => wdsel: ReadWrite<u32, WDSEL::Register>),
(0x0C => done: ReadOnly<u32, DONE::Register>),
(0x10 => @END),
}
}
register_bitfields! [
u3... | Rust | 0 |
def contar_vogais(palavra:str) -> int:
vogais = "aeiouáàãâéêíóôõú"
contador = 0
for letra_atual in palavra.lower():
if letra_atual in vogais:
contador += 1
return contador
def contar_consoantes(palavra:str) -> int:
consoates = "bcdfghjklmnpqrstvxywz"
contador = 0
for let... | Python | 1 |
4-e5 { date=2020-07-17T17:22:09.146Z clock=21877 } .. δg7-h6=E { date=2020-07-17T17:22:15.754Z clock=30277 } .. δf8-e7=E+ { date=2020-07-17T17:22:19.294Z clock=63256 } .. δj6-i7 { date=2020-07-17T17:22:24.160Z clock=67778 }
24. δe5-f6 { date=2020-07-17T17:22:27.846Z clock=18223 } .. Eh6xYh5 { date=2020-07-17T17:22... | Rust | 0 |
#!/usr/bin/env python3
# Helper script to modify the xml results from picolibc.
# Picolibc always puts all the test results into the "picolibc"
# testsuite in the junit xml file. We have multiple variants of
# picolibc, so the xml is modified to group the tests by variant.
import argparse
import os
from xml.etree im... | Python | 1 |
from typing import List
from collections import deque
class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
available = set(supplies)
ingredient_to_recipes = {}
for recipe, ing_list in zip(recipes, ingredients)... | Python | 1 |
or + 'static> error::Error for Error<E> {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
use crate::Error::*;
match *self {
Http(_) => None,
Service(ref e) => Some(e),
Utf8(ref e) => Some(e),
}
}
}
impl<E: Display> Display for Error<E> {... | Rust | 0 |
d than expected')
diffs = np.abs(found_locs - act_locs)
max_diffs = np.array(sigmas) / 5
np.testing.assert_array_less(diffs, max_diffs, 'Maximum location differed' +
'by more than %s' % (max_diffs))
def test_find_peaks_nopeak(self):
"""
V... | Python | 1 |
# -*- coding: utf-8 -*-
"""
==============================================================================
@author: Nikolaos Giakoumoglou
@date: Thu May 6 21:59:57 2021
==============================================================================
"""
import numpy as np
def fos(f, mask):
'''
Parameters
-... | Python | 1 |
md
"#
));
assert_eq!(actual, "3");
}
#[test]
fn out_md_table() {
let actual = nu!(
cwd: ".", pipeline(
r#"
echo '{"name": "jason"}' | from-json | to-md
"#
));
assert_eq!(actual, "|name||-||jason|");
}
<reponame>Phala-Network/rmrk-substrate
// Copyright ... | Rust | 0 |
"""
This is the global script that set the version information of TVM.
This script runs and update all the locations that related to versions
List of affected files:
- tvm-root/python/tvm/_ffi/libinfo.py
- tvm-root/include/tvm/runtime/c_runtime_api.h
- tvm-root/web/tvm_runtime.js
- tvm-root/conda/tvm/meta.yaml
- tvm-r... | Python | 1 |
esetTwo,
ResetThree,
Unknown(u8, u8, u8, u8, u8),
}
impl PanelToDeskMessage {
pub fn as_frame(&self) -> DataFrame {
match *self {
PanelToDeskMessage::Up => build_frame(PANEL_TO_DESK_UP_BYTE, 0u8, 0u8),
PanelToDeskMessage::Down => build_frame(PANEL_TO_DESK_DOWN_BYTE, 0u8, 0u8... | Rust | 0 |
n_dispatcher_type == "alltoall_seq":
self.token_dispatcher = MoEAlltoAllSEQTokenDispatcher(
self.num_local_experts, self.local_expert_indices, config=self.config
)
else:
raise ValueError(
f"Unsupported token dispatcher type: {config.moe_token_d... | Python | 1 |
val: Tagged<Foo, Bar, i64> = Tagged::new(42);
```
*/
pub fn new(value: Value) -> Self {
Tagged(value, PhantomData)
}
/**
Get a reference to the underlying value.
Example:
```rust
# use ibc_integration_test::types::tagged::dual::Tagged;
struct Fo... | Rust | 0 |
ds standards and patterns."""
return await create_complete_workspace({
"name": f"{project_name} Developer",
"model": "gpt-4",
"system_prompt": system_prompt
})
async def list_all_workspaces() -> Dict:
"""List all created workspaces"""
result = await api_request("GET", "/api... | Python | 1 |
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "accelerate",
# "bitsandbytes",
# "marimo",
# "peft",
# "torch",
# "triton",
# "trl",
# "xformers",
# ]
# ///
import marimo
__generated_with = "0.15.5"
app = marimo.App(width="full")
@app.cell
def _():
import marimo a... | Python | 1 |
`{0}` could not be resolved")]
Canonicalize(#[from] std::io::Error),
#[error("File or directory `{0}` is not accessible")]
Inaccessible(String),
}
#[derive(Error, Debug)]
pub enum DeviceError {
#[error("No MTP device found on USB bus")]
NoDeviceAttached,
#[error("No device matching selection c... | Rust | 0 |
:Red),
Some('B') => Ok(Self::Blue),
_ => Err(format!("Did not recognize player color {}", c).into())
}
}
}
impl From<PlayerColor> for char {
fn from(color: PlayerColor) -> char {
match color {
PlayerColor::Red => 'R',
PlayerColor::Blue => 'B'
... | Rust | 0 |
self.position = self.get_position()
# Compute the Euclidean distance from the target point
distance = sqrt(pow((self.position.x - x_start), 2) +
pow((self.position.y - y_start), 2))
# ... | Python | 1 |
'''
Nosso programa ainda não está perfeito, mas agora, se o usuário errar
a primeira opção, ele mostra o menu novamente (linha 27).
Usar a função para "empacotar" o código, permite que a gente use ele
outras vezes sem ter que repetir diversas linhas.
Lembrando que as funções não são executadas até chamarmos, como fizem... | Python | 1 |
mpl Ord for ApplicationContextAttributes
{
#[inline(always)]
fn cmp(&self, other: &Self) -> Ordering
{
self.worker_thread_mode().cmp(&other.worker_thread_mode()).then(self.reserved_space_in_non_blocking_requests().cmp(&other.reserved_space_in_non_blocking_requests()))
}
}
impl Hash for ApplicationContextAttribut... | Rust | 0 |
p 0.8
try:
kv = dict(zip(parts[1::2], parts[2::2]))
if "temp" in kv: c.temp = max(0.0, min(1.0, float(kv["temp"])))
if "top_p" in kv: c.top_p = max(0.0, min(1.0, float(kv["top_p"])))
except Exception:
return await m.answer("usage: /config temp <0..1> top_p <0..1>", disable_web_pa... | Python | 1 |
-1 * (7 - X[:, 4] + X[:, 1])
c_11 = -1 * (7 + X[:, 7] - X[:, 4])
c_12 = -1 * (7 - X[:, 7] + X[:, 4])
c_13 = -1 * (7 + X[:, 10] - X[:, 7])
c_14 = -1 * (7 - X[:, 10] + X[:, 7])
c_15 = -1 * (7 + X[:, 13] - X[:, 10])
c_16 = -1 * (7 - X[:, 13] + X[:, 10])
c_17 = -1 * ... | Python | 1 |
a `FlexBufferType::VectorInt`.
monster.push("coins", &[5, 10, 25, 25, 25, 100]);
// Flexbuffer has special types for fixed-length-typed-vectors (if the length is 3 or 4 and the
// type is int, uint, or float). They're even more compact than typed vectors.
// The monster's position and Velocity will be ... | Rust | 0 |
rguments": {"foo": "bar", "size": 10}}\n</tool_call>\n"""
"""<tool_call>\n{"name": "tool_name", "arguments": {"foo": "bar", "size": 10}}\n</tool_call>"""
"<|im_end|>\n"
]
def test_qwen_tool_formatter():
formatter = ToolFormatter(tool_format="qwen")
wrapped_tool = {"type": "function", "func... | Python | 1 |
# Generated by Django 4.0.8 on 2023-10-06 16:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0004_alter_newsandevents_id_alter_semester_id_and_more'),
]
operations = [
migrations.AlterField(
model_name='semester',
... | Python | 1 |
ATION_STATE_FILE_PATH);
let mut plan = Plan::builder(state_storage);
plan.ctx_provider(DbClientCtxProvider {
file_path: JSON_FILE_PATH.into(),
})
// Add migrations in order one after each other to the plan
.migration("migration-1", Migration1)
.migration("migration-2", Migration2);
... | Rust | 0 |
import uuid
import secrets
import string
from django.db import models
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
def get_default_status_config():
return {
"theme": {
"background_url": "https://infinitypro... | Python | 1 |
let mut rs = self.rs_loaders[i].borrow_mut();
if rs.state == RsState::CALCULATED {
let id = rs.inst_id;
if self.inst_vec[id].r_time.is_none() {
self.inst_vec[id].r_time = Some(self.times);
self.inst_vec[id].w_time = Some(self.t... | Rust | 0 |
"""Player data model with minimal game management logic."""
from __future__ import annotations
import logging
from .map_data import STARTING_LOCATION_ID
from .monsters.monster_class import Monster
from .monster_book import MonsterBook
from . import save_manager, party_manager, synthesis_manager
logger = logging.get... | Python | 1 |
threshold for the TX FIFO and RX FIFO. The threshold is exceeded when the number of bytes in the FIFO is equal to or higher than the threshold value.
#[repr(u8)]
#[derive(Debug, BitfieldSpecifier)]
#[bits = 4]
pub enum FifoThreshold {
/// 61 bytes in TX or 4 bytes in RX.
Tx61Rx4,
/// 57 bytes in TX or 8 by... | Rust | 0 |
import urllib.request
import urllib.parse
import json
import sys
HEIGHT_QUERY = "{}/block?height={}"
STATUS_QUERY = "{}/status?"
def get_block_hash(rpc_url, height):
url = HEIGHT_QUERY.format(rpc_url, height)
try:
with urllib.request.urlopen(url) as response:
if response.status == 200:
... | Python | 1 |
children. If this is set to `None` (the default), the probe will cover
/// all processes on the system.
pub fn pid(mut self, pid: Option<i32>) -> Self {
self.pid = pid;
self
}
/// Restrict the probe to only the given hardware thread. If this is set to
/// `None` (the default), a pr... | Rust | 0 |
handle); // We don't actually use this but we want to call CloseHandle when we are done
// Safe because it's a WINAPI type, using MaybeUninit would be hard because we need to write on its dwSize field.
let mut pe32: PROCESSENTRY32 = unsafe { std::mem::zeroed() };
// We must initialize dwSize here.
pe32... | Rust | 0 |
from db_connect import DatabaseConnection
import json
with open('d:/lyon_study/quiz_check/quiz_check_fun/db/ali-aca-1.json','r',encoding='utf-8') as file:
content = file.read()
ALI_ACA='ALI_ACA_Q'
db = DatabaseConnection()
db.connect()
db.execute_delete('delete from quiz.check_question where id like %s ',... | Python | 1 |
station.
///
/// Note: Utilizes the cache and will fail if the appropriate cache is not initialized.
///
/// Spec v0.12.1
pub fn get_attestation_duties(
&self,
validator_index: usize,
relative_epoch: RelativeEpoch,
) -> Result<Option<AttestationDuty>, Error> {
let... | Rust | 0 |
me te werawera mātao",
"menemene",
"mātao",
"tuwhera",
"werawera",
],
},
#[cfg(feature = "mk")]
crate::Annotation {
lang: "mk",
tts: Some("насмеано лице со отворена уста и пот"),
keyw... | Rust | 0 |
Rmd { path }
}
}
#[async_trait]
impl<S, U> CommandHandler<S, U> for Rmd
where
U: UserDetail + 'static,
S: 'static + storage::StorageBackend<U> + Sync + Send,
S::File: tokio::io::AsyncRead + Send,
S::Metadata: storage::Metadata,
{
async fn handle(&self, args: CommandContext<S, U>) -> Re... | Rust | 0 |
# 加权平均
import pandas as pd
import os
if __name__ == "__main__":
# 读取股票代码
si2 = pd.read_csv('out/codes/si_codes.csv')['code'].tolist()
st2 = pd.read_csv('out/codes/st_codes.csv')['code'].tolist()
# 存储所有股票的数据
all_data = []
for si in si2:
# 读取对应股票代码的预测结果文件
a = pd.read_csv(f'out/... | Python | 1 |
odel, X_scaled, y, cv=cv, scoring='accuracy')
print(f"交叉验证准确率: {cv_scores}")
print(f"平均准确率: {cv_scores.mean():.3f} (+/- {cv_scores.std() * 2:.3f})")
return cv_scores
def demo_usage():
"""
演示如何使用逻辑回归模板
模拟论文中的七分类问题(mRS评分:0-6)
"""
print("=== 逻辑回归通用模板演示 ===")
... | Python | 1 |
param.grad[param.grad == -float('inf')] = 0
param.grad[param.grad == float('inf')] = 0
if torch.isnan(param.grad).any():
loguru.logger.warning(f"Nan gradient detected in {n}, gradient clip is applied!")
# 处理 -inf,例如将其设置为0
... | Python | 1 |
Args:
fn: A callable that will take take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
An iterator equivalent to: map(func,... | Python | 1 |
+') {
LineType::Unknown
} else {
// Mark everything else as a File
LineType::File(line)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn parse_line_filelist() {
let line = "-f sample/files.f\n";
assert_eq!(parse_line(line), LineType::Filelist("sample/fil... | Rust | 0 |
.ok_or(err_msg("no name found"))?
.as_str();
let mid = RE_MID
.captures(&html_s)
.ok_or(err_msg("no mid variable found"))?
.get(1)
.ok_or(err_msg("no mid found"))?
.as_s... | Rust | 0 |
class Employee:
employee_count = 0
def __init__(self, name, family, salary, department):
self.name = name
self.family = family
self.salary = salary
self.department = department
Employee.employee_count += 1
def display_employee_info(self):
print(f"Name: {self.name}, Family: {se... | Python | 1 |
mplified_artists = r#"
[
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/5I8r2w4hf7OYp2cunjihxJ"
},
"href": "https://api.spotify.com/v1/artists/5I8r2w4hf7OYp2cunjihxJ",
"id": "5I8r2w4hf7OYp2cunjihxJ",
"name": "Kularis",
"type": "artist",
"uri": "spotify:artist:5I8r2w4hf7OYp2cunjihxJ"
... | Rust | 0 |
winBuilder::new(&self, device_id.into(), Some(module_id.into()), Method::PUT)
}
/// Update the device twin of a given device
///
/// ```
/// use iothub::service::ServiceClient;
/// use serde_json;
///
/// # let connection_string = "HostName=cool-iot-hub.azure-devices.net;SharedAccessKey... | Rust | 0 |
: root::gli::dx_dxgi_format_dds = 132;
pub const dx_dxgi_format_dds_DXGI_FORMAT_ASTC_4X4_TYPELESS: root::gli::dx_dxgi_format_dds =
133;
pub const dx_dxgi_format_dds_DXGI_FORMAT_ASTC_4X4_UNORM: root::gli::dx_dxgi_format_dds =
134;
pub const dx_dxgi_format_dds_DXGI_FORMAT_A... | Rust | 0 |
} else {
unreachable!("Cannot evaluate value {:?}", expr);
}
})
.expect(&format!("Eval failed to find named value: {:?}", expr))
}
_ => expr,
}
}
/// Directly evaluate an s-expres... | Rust | 0 |
for iv in range(vertex_num2):
vvalues.append(values[-1])
n_cylinders += 1
# almost done, determine quad faces ...
# define single faces
# firstFace = [0, 1, vertex_num+1, vertex_num]
# lastFace = [vertex_num-1, 0, vertex_num, 2*vertex_num-1]
firstFace = [vertex_num, vertex... | Python | 1 |
quiche/src/quic/core/congestion_control/bbr2_sender.cc>
/// and the Linux Kernel TCP BBRv2 implementation, see <https://github.com/google/bbr/blob/v2alpha/net/ipv4/tcp_bbr2.c>
#[derive(Debug, Clone)]
struct BbrCongestionController {
round_counter: round::Counter,
bw_estimator: bandwidth::Estimator,
full_pip... | Rust | 0 |
nt(f"[process_checkin_frame] Detected user: {user_id_detected}")
# print("[process_checkin_frame] Frame processing complete")
# return frame_face_processed, frame_plate_display, user_id_detected, plate_text_detected_this_frame
# if __name__ == "__main__":
# print("Running in standalone mode for debugging.... | Python | 1 |
#!/usr/bin/python3
#
from random import SystemRandom
from math import gcd
from Crypto.Util.number import inverse
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from hashlib import sha3_256
m_prime = 11213
xi1 = 0.31
xi2 = 0.69
w = 10
rand = SystemRan... | Python | 1 |
for date, percentage in progress.burndown_data
]
return jsonify({
"total_completion": progress.total_completion,
"features_completed": progress.features_completed,
"total_features": progress.total_features,
... | Python | 1 |
Ok(parsed_json) = &mut parsed_json {
if parsed_json.is_array() {
for member in parsed_json.members_mut() {
results.push(parse_entry(member))
}
} else {
results.push(parse_entry(parsed_json))
}
} else {
... | Rust | 0 |
else:
df['date'] = df['date'].astype('datetime64[D]')
return df
except:
return None
def lpr_ma_data(year=None):
"""
获取贷款基础利率均值数据
Parameters
------
year:年份(int)
Return
------
date:日期
1Y_5:5日均值
1Y_10:10日均值
1Y_20:20日均值
""... | Python | 1 |
of data written to a host buffer will be saved here
pub fn casper_provision_contract_user_group_uref(
contract_package_hash_ptr: *const u8,
contract_package_hash_size: usize,
label_ptr: *const u8,
label_size: usize,
value_size_ptr: *const usize,
) -> i32;
/// Removes... | Rust | 0 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -------------------------------------------------------------------... | Python | 1 |
import numpy as np
import pandas as pd
import os
import radvel
# This setup file is provided to illustrate how to set up a config
# file for use with Dan Foreman-Mackey's `celerite` package.
# Data from Dai+ 2017
instnames = ['harps-n', 'pfs'] # no spaces in instrument names
data = pd.read_csv(os.path.join(radvel.DA... | Python | 1 |
},
Some("empty") | Some("e") => {
selection.retain(|id| state.rooms.get(id).unwrap().member_count == 0);
true
}
Some("list") | Some("l") => true,
_ => false,
};
... | Rust | 0 |
import pytest
import pandas as pd
from portfolio_toolkit.asset.optimization.optimization_asset import OptimizationAsset
def test_optimization_asset_properties_and_repr():
prices = pd.Series([100, 102, 101, 105], index=pd.date_range("2024-01-01", periods=4))
asset = OptimizationAsset(ticker="AAPL", prices=price... | Python | 1 |
val.clone(), denominator_inv[3].clone() );
// res += val * coefficients[28].
res = prime_field::fadd(res.clone(),
prime_field::fmul(val.clone(), /*coefficients[28]*/ ctx[map::MM_COEFFICIENTS+28].clone() ) );
}
{
// Constraint expression for initial_pc: column17_row0 - initial_pc.
let mut val = prime_field::... | Rust | 0 |
.write(&mut proof_bytes).expect("Could write proof");
let (_ptr, _len, _) = proof_bytes.into_raw_parts();
let proof = Proof {
ptr: _ptr,
len: _len,
};
unsafe { transmute(Box::new(proof)) }
}
fn verify_verkle_proof_multiple(
&mut self,
ptr:... | Rust | 0 |
(path_sp, token::Literal(token::Lit::Str_(s), _)) => (path_sp, s.to_string()),
_ => {
cx.span_err(sp, "argument should be a single string");
return Err(DummyResult::any(sp));
}
};
Ok(Options {
file_path: file_path,
file_path_span: file_path_span,
})
}... | Rust | 0 |
REPORT, # is this in label?
"Situation de patrimoine": DocumentTypes.REPORT,
"Avis": DocumentTypes.REPORT,
}
class EServicePage(LoggedPage, HTMLPage):
def select_documents_tab(self):
# force lowercase, it's not always the same case
# and label to search for depends on child module
... | Python | 1 |
"""
Run setup for CV iteration.
- Add file paths to the TFRecord files for a given CV iteration.
- Load model's hyperparameters from an HPO run.
"""
# 3rd party
import yaml
from pathlib import Path
import argparse
# 3rd party
from src_cv.preprocessing.add_tfrec_dataset_fps_to_config_file import add_tfrec_dataset_fps_... | Python | 1 |
String) -> TlsAcceptor {
let mut file = File::open(identity_file).unwrap();
let mut identity = vec![];
file.read_to_end(&mut identity).unwrap();
let identity = Identity::from_pkcs12(&identity, "solarwinds123").unwrap();
let acceptor = TlsAcceptor::builder(identity).build().unwrap();
acce... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.