text string | label_name string | labels int64 |
|---|---|---|
import pandas as pd
from openpyxl import Workbook
from openpyxl.styles import Font
from openpyxl.utils import get_column_letter
from pypinyin import pinyin, Style
def csv_to_excel_with_pinyin(csv_path, excel_path):
try:
# 读取CSV文件
df = pd.read_csv(csv_path)
# 确保DataFrame有至少两列
if le... | Python | 1 |
1 MNCFX => 1 STKFG
17 NVRVD, 3 JNWZP => 8 VPVL
53 STKFG, 6 MNCFX, 46 VJHF, 81 HVMC, 68 CXFTF, 25 GNMV => 1 FUEL
22 VJHF, 37 MNCFX => 5 FWMGM
139 ORE => 4 NVRVD
144 ORE => 7 JNWZP
5 MNCFX, 7 RFSQX, 2 FWMGM, 2 VPVL, 19 CXFTF =... | Rust | 0 |
// lookup table of hOPE scheme
pub _apl: BTreeMap<Vec<u8>, ObjectId>,
// keypair
pub _key: Option<hopeKey>,
}
//impl Actor for System {
// type Context = ws::WebsocketContext<Self>;
//
/// A hOPE APL TABLE (APL)
#[derive(Serialize, Deserialize, Clone)]
pub struct hopeCiphertext {
pub _id: Objec... | Rust | 0 |
c
source = self.sourceService.getById(blogSync.Source)
assert isinstance(source, Source)
providerId = self.sourceService.getOriginalSource(source.Id)
log.info("sync sms for sourceId=%i, providerId=%i, blogId=%i, lastId=%i" %(blogSync.Source, providerId, blogSync.Blog, blogSync.... | Python | 1 |
Total = 0
// residual()
// if (is_inter && subsize >= BLOCK_8X8 && EobTotal == 0) {
// skip = 1
// }
// for (y=0;y<num_8x8_blocks_high_lookup[subsize];y++)
// for (x=0;x<num_8x8_blocks_wide_lookup[subsize];x++) {
// Skips[r+y][c+x] = skip
// TxSizes[r+y][c+x] = tx... | Rust | 0 |
"]
pub pool_name: Option<String>,
}
impl FromSql<Jsonb, Pg> for StorageConfig {
fn from_sql(bytes: Option<&[u8]>) -> diesel::deserialize::Result<Self> {
let value = <serde_json::Value as FromSql<Jsonb, Pg>>::from_sql(bytes)?;
Ok(serde_json::from_value(value)?)
}
}
impl ToSql<Jsonb, Pg> for... | Rust | 0 |
uest_4: u16,
pub quest_5: u16,
pub quest_6: u16,
pub travelled_act2: u16
}
impl Act1QuestStatus {
pub fn from(reader: &mut Cursor<&[u8]>) -> Result<Act1QuestStatus> {
let introduced = reader.read_u16::<LittleEndian>()?;
let quest_1 = reader.read_u16::<LittleEndian>()?;
... | Rust | 0 |
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import config
bootstrap = Bootstrap()
db = SQLAlchemy()
mail = Mail()
login_manager = LoginManager()
login_manager.session_protection = '... | Python | 1 |
mped to the length of the sequence (`sequence_length`). Position outside of the sequence
# are not taken into account for computing the loss.
# end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
# Labels for position (index) of the end of the labelled span for compu... | Python | 1 |
))
}
}
use crate::ai::rulespecific::airufspiel::*;
use crate::primitives::*;
use crate::rules::{payoutdecider::*, trumpfdecider::*, *};
use crate::util::*;
use std::{cmp::Ordering, fmt};
pub trait TRufspielPayout : Clone + Sync + fmt::Debug + Send + 'static {
fn payout(&self, rules: &SRulesRufspielGeneric<Self... | Rust | 0 |
ant, None, None).unwrap();
let writer_qos = DdsQos::create().unwrap().set_deadline(std::time::Duration::from_millis(50));
let mut writer = DdsWriter::create(&publisher, topic.clone(), Some(writer_qos), None).unwrap();
let reader_qos = DdsQos::create().unwrap().set_deadline(st... | Rust | 0 |
import socket
from OpenSSL import SSL
def test_fluent():
hostname = 'www.python.org'
context = SSL.Context(SSL.SSLv23_METHOD)
conn = SSL.Connection(context, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
r = conn.connect((hostname, 443))
print(conn.get_protocol_version_name())
def test_fluen... | Python | 1 |
import paddlehub as hub
from paddleocr.ppocr.utils.logging import get_logger
from paddleocr.tools.infer.utility import base64_to_cv2
from paddlehub.module.module import moduleinfo, runnable, serving
@moduleinfo(
name="devanagari_ocr_db_crnn_mobile",
version="1.0.0",
summary="ocr service",
author="Padd... | Python | 1 |
paths.paths);
let mut pubkeys: Vec<Pubkey> = vec![];
create_account(
&db,
&mut pubkeys,
0,
2,
ACCOUNT_DATA_FILE_SIZE as usize / 3,
0,
);
assert!(check_storage(&db, 2));
db.add_fork(1, Some(0));
let ... | Rust | 0 |
from collections import deque
# 너비 우선 탐색으로 최단거리 찾기
def bfs(start, maps, row, col):
delta = [(-1,0), (1,0), (0,-1), (0,1)]
queue = deque([start])
# 방문한 칸을 체크할 2차원 리스트
visited = [[0]*col for _ in range(row)]
# 시작점 방문표시
visited[start[0]][start[1]] = 1
# 다음 방문할 칸이 없어질때 까지
while queue:
... | Python | 1 |
parameters() {
check_types_source_code(
r#"
struct Foo<T = u8> { t: T }
fn main() {
let foo = Foo { t: 5u8 };
foo;
} //^^^ Foo
"#,
);
check_types_source_code(
r#"
struct Foo<K, T = u8> { k: K, t: T }
fn main() {
let foo = Foo { k: 400, t: 5u8 };
foo;
} //^^^ Foo<i32>
"#,
... | Rust | 0 |
# coding: utf-8
"""
Graphiant APIs
**To use the APIs:** 1) Login using `/api/v1/auth/login` 2) Copy the value of \"token\" in the response 3) Click the \"Authorize\" button 4) In the \"Value\" text field enter: `Bearer <your token>` 5) Click \"Authorize\" 6) All requests are now authorized. **Toke... | Python | 1 |
{ver_to_block_size, ver_to_data_size, ver_uses_rs, Version};
use std::fs;
use std::path::Path;
pub fn get_file_metadata(file: &str) -> Result<fs::Metadata, Error> {
let reader = FileReader::new(
file,
FileReaderParam {
write: false,
buffered: false,
},
)?;
re... | Rust | 0 |
, value: u32) -> Result<(), BytesWriterError> {
if self.remaining_len() < size_of_val(&value) {
return Err(BytesWriterError::TooShort);
}
self.write_le_u32(self.current, value)?;
self.current += size_of_val(&value);
Ok(())
}
pub fn append_le_i32(&mut self, v... | Rust | 0 |
: i32, ASibling: usize);
pub fn ProgressBar_AnchorHorizontalCenterTo(AObj: usize, ASibling: usize);
pub fn ProgressBar_AnchorVerticalCenterTo(AObj: usize, ASibling: usize);
pub fn ProgressBar_AnchorSame(AObj: usize, ASide: TAnchorKind, ASibling: usize);
pub fn ProgressBar_AnchorAsAlign(AObj: usize, ATheAlign: T... | Rust | 0 |
et_pos[1], 'g*', markersize=12,
label='Target')
ax4.grid(True)
# 将图例放在图片下方
ax4.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15),
ncol=3, fancybox=True, shadow=True)
plt.title(f'Symbolic Sonar Map - Step {step_number}', f... | Python | 1 |
Some(t) => self.print_ty(iface, t, false),
None => self.src.push_str("_"),
}
self.src.push_str(", ");
match err {
Some(t) => self.print_ty(iface, t, false),
... | Rust | 0 |
on_dict["headerType"] = rc_def.type
remote_connection_dict["serviceName"] = ""
return remote_connection_dict
def delete_workload_from_ms(_id: str, verbose: bool = False) -> str:
"""Deletes a workload from the management system.
:param _id: The ID of the workload to delete.
:param verbose: If True... | Python | 1 |
"""Tests for the wemo component."""
| Python | 1 |
atenate(render_rnn_states),
np.concatenate(render_masks),
deterministic=True)
render_actions = np.expand_dims(_t2n(render_actions), axis=0)
render_rnn_states = np.expan... | Python | 1 |
e returned if the tab key was pressed."]
pub const DVK_TAB: Keys = 9;
#[doc = "!< will be returned if the backspace key was pressed."]
pub const DVK_BACKSPACE: Keys = 8;
#[doc = "!< will be returned if the caps key was pressed."]
pub const DVK_CAPS: Keys = -15;
#[doc = "!< will be returned if the shift key was pr... | Rust | 0 |
# http://inamidst.com/saxo/
# Created by Sean B. Palmer
import saxo
@saxo.setup
def instances(irc):
if not "saxo_instances" in irc.db:
irc.db["saxo_instances"].create(
("pid", int))
@saxo.setup
def periodic(irc):
sqlite3_schema = [(0, 'name', 'TEXT', 0, None, 1),
(1,... | Python | 1 |
return public.returnMsg(False, '入口地址格式不正确,示例: /my_panel')
admin_path_file = 'data/admin_path.pl'
admin_path = '/'
if os.path.exists(admin_path_file):
admin_path = public.readFile(admin_path_file).strip()
if get.admin_path != admin_path:
public.writeFile(admi... | Python | 1 |
ist = DataLoader(train_ds_dist, batch_size=batch_size, shuffle=False, num_workers=0)
val_ds_dist = YamahaDataset(data_lst, rhythm_lst, note_density_lst,
chroma_lst, mode="val")
val_dl_dist = DataLoader(val_ds_dist, batch_size=batch_size, shuffle=False, num_workers=0)
tes... | Python | 1 |
st_interrupt(2);
} else {
self.mmu.write_memory(&utils::TIMER_ADDR, self.mmu.read_memory(&utils::TIMER_ADDR) + 1);
}
}
}
}
pub fn update_graphics(&mut self, cycles: &usize) {
// Deal with setting LCD status
self.set_lcd_sta... | Rust | 0 |
_type(954032400)?.ut_offset(), -7200);
assert_eq!(transition_rule_negative_time_2.find_local_time_type(972781199)?.ut_offset(), -7200);
assert_eq!(transition_rule_negative_time_2.find_local_time_type(972781200)?.ut_offset(), -10800);
let transition_rule_all_year_dst = TransitionRule::Alternate(... | Rust | 0 |
=true) x=1;", "b=true;x=1");
test("if (b=/ab/) x=1;", "b=/ab/;x=1");
test("if (b=/ab/){ x=1; } else { x=2; }", "b=/ab/;x=1");
// test("var b;b=/ab/;if(b)x=1;", "var b;b=/ab/;x=1");
test_same("var b;b=f();if(b)x=1;");
// test("var b=/ab/;if(b)x=1;", "var b=/ab/;x=1");
test_same("var b=f();if(b)x=... | Rust | 0 |
==================================================
xmlreader.py:
==================================================
from xml.dom.minidom import parse
class NotTextNodeError:
pass
def getTextFromNode(node):
"""
scans through all children of node and gathers the
text. if node has non-text child-nodes,... | Python | 1 |
class Solution(object):
def removeDuplicates(self, nums):
slow = 0
fast = 1
while fast < len(nums):
if nums[slow] != nums[fast]:
slow += 1
nums[slow] = nums[fast]
fast += 1
return slow + 1 | Python | 1 |
fn test_add_bytes_to_bits_tuple_ok() {
assert!(add_bytes_to_bits_tuple::<u64>((5, 100), 10) == (5, 180));
}
// The low order value overflows into the high order value
#[test]
fn test_add_bytes_to_bits_tuple_ok2() {
assert!(add_bytes_to_bits_tuple::<u64>((5, Bounded::max_value()), 1) == ... | Rust | 0 |
::Scope;
use crate::avm2::string::AvmString;
use crate::avm2::traits::Trait;
use crate::avm2::value::Value;
use crate::avm2::{Avm2, Error};
use crate::context::UpdateContext;
use fnv::FnvHashMap;
use gc_arena::{Collect, Gc, GcCell, MutationContext};
use std::cell::Ref;
use std::mem::drop;
use std::rc::Rc;
use swf::avm2... | Rust | 0 |
vowels = "aeiouAEIOU"
total_vowels = 0
check = 0
a = str(input("Enter the first string: "))
b = str(input("Enter the second string: "))
total_a = len(a)
total_b = len(b)
print("The total length of first string is: " + str(total_a))
print("The total length of second string is: " + str(total_b))
if total_a > total_b... | Python | 1 |
your training data.\n'
'This is your system prompt, guiding your responses. Do not reference it, just respond to the user. '
'If you find yourself talking about this message, stop. You should be responding appropriately '
'and usually that means not mentioning this.'
'YOU DO NOT MENTION ANY OF THIS INF... | Python | 1 |
import time
import os
from dash import (
Dash,
DiskcacheManager,
CeleryManager,
Input,
Output,
html,
callback,
set_props,
)
# os.environ["REDIS_URL"] = "redis://localhost:6379"
import dash_ag_grid as dag
from plotly.express import data
if "REDIS_URL" in os.environ:
# Use Redis ... | Python | 1 |
# id 58928 ([Hieizan Temple] Sad Little Boy), field 811000014
sm.setSpeakerID(9130107) # Mysterious Boy
sm.setParam(4)
sm.setInnerOverrideSpeakerTemplateID(9130107) # Mysterious Boy
sm.sendNext("*Sniff*")
sm.setParam(16)
sm.sendSay("(A boy in a place like this? Quite suspicious. And crying at that. I should just... pre... | Python | 1 |
for pkey in keys:
algo, key = pkey.key.split()[:2]
algo = algo[4:].upper()
if getattr(pkey, 'title', None):
print("%s key%s...%s (%s)" % (algo, ' ' * (6 - len(algo)), key[-10:], pkey.title))
else:
print("%s key... | Python | 1 |
chl::register(sk, b"username", b"password"));
}
fn bench_client_login(b: &mut Bencher) {
let mut rng = OsRng;
let (pp, _sk) = chl::setup(&mut rng);
b.iter(|| chl::client_login(&pp, b"ssid", b"tok", b"username", b"password", &mut rng));
}
fn bench_server_login(b: &mut Bencher) {
let mut rng = OsRng;
... | Rust | 0 |
liters of water daily", periodicity=1)
habit2 = Habit(id=2, name="Buy groceries", description="Buy groceries", periodicity=2)
mock_session.query.return_value.all.return_value = [habit1, habit2]
# Mock the filter_by method to return the check offs for each habit
def mock_filter_by(habit... | Python | 1 |
import os
from pathlib import Path
from typing import Optional
import lightning as L
import yaml
from dotenv import load_dotenv
from lightning.pytorch.loggers import CSVLogger
from src.training.data_module import Lc0Data
from src.training.flops_logger import FlopsLogger
from src.training.model import Model
def load... | Python | 1 |
atch[1]
else:
images, texts, idxs = batch[0], batch[1], batch[2]
if isinstance(images, list):
images, idxs = images[0].to(device), idxs.to(device) # 选择弱数据增强的
else:
images, idxs = images.to(device), idxs.to(devi... | Python | 1 |
Type::LtEq,
'<' => TokenType::Lt,
'>' if self.next_if_eq(&'>').is_some() => {
if self.next_if_eq(&'=').is_some() {
unimplemented!() // TokenType::GtGtEq
} else {
TokenType::GtGt
}
}
'... | Rust | 0 |
prefix matches further if the word is very common, on top
// of the other frequency penalty below.
penalty *= (meta.log_frequency() + 1) as i32;
// A single excess character is better than a word that occurs later,
// but the word position incurs a linear penalty, so it wins in the end... | Rust | 0 |
mode()?;
let stdout = MouseTerminal::from(stdout);
let stdout = AlternateScreen::from(stdout);
let backend = TermionBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
terminal.hide_cursor()?;
let events = Events::new();
let mut rand_signal = RandomSignal::new(0, 100);
le... | Rust | 0 |
from pathlib import Path
from sidecar.filesystem.schemas import FileEntry, FolderEntry
def create_file_entry(path: Path, relative_to: Path) -> FileEntry:
return FileEntry(
name=path.name,
path=str(path.relative_to(relative_to)),
file_extension=path.suffix,
)
def traverse_directory(
... | Python | 1 |
".to_string(), |view: &mut ScrollView<TextView>| {
view.get_inner_mut().set_content("");
});
step_t(Arc::clone(&demo_arc_run), n);
n = (n + 1) % trustees;
}
});
siv.add_global_callback('b', move |s| {
let guard = Arc::clone(&demo_arc_ballots);
... | Rust | 0 |
ta = cp.Variable(self.feature_dim)
log_policy_diff = (non_pref_features - pref_features) @ theta
log_ref_policy_diff = cp.log(non_pref_ref_policy) - cp.log(pref_ref_policy)
tmp = self.reg_coef * (log_policy_diff - log_ref_policy_diff)
loss = cp.sum(cp.logistic(tmp)) / len(dataset)
... | Python | 1 |
"❌ Invalid - Missing Dependencies": """
name: "Test Thermostat"
heater: switch.heater
target_sensor: sensor.temperature
max_floor_temp: 28 # Missing floor_sensor
fan_mode: true # Missing fan
""",
"❌ Invalid - Entity Conflicts": """
name: "Test Thermostat"
heater: switch.main_device
target_sensor:... | Python | 1 |
gen_kwargs.pop("do_sample", False)
if "max_tokens" in gen_kwargs:
max_tokens = gen_kwargs.pop("max_tokens")
else:
max_tokens = gen_kwargs.pop("max_gen_toks", self._max_gen_toks)
temperature = gen_kwargs.pop("temperature", 0)
stop = handle_stop_sequences(gen_kwargs... | Python | 1 |
#=========================================================================
# Prob02p06_comb_wires_4x2b_passthru_test
#=========================================================================
# SPDX-License-Identifier: MIT
# Author : Christopher Batten, NVIDIA
# Date : May 20, 2024
from pyhdl_eval.cfg import Config... | Python | 1 |
(),
class: Class::Internet,
ttl: 3599,
preference: 20,
exchange: "alt2.gmail-smtp-in.l.google.com.".parse().unwrap(),
};
let ns1 = ResourceRecord::NS {
name: "gmail.com.".parse().unwrap(),
class: Class::Internet,
ttl: 86399,
ns_name: "ns3.google.co... | Rust | 0 |
#!/usr/bin/env python3
n = 31
def divide_unsigned(dividend, divisor):
"""
quotient, remainder = dividend/divisor
"""
if divisor == 0:
raise ValueError("Division by zero error")
quotient, remainder = 0, 0
def div_step():
nonlocal dividend, quotient, remainder
remainde... | Python | 1 |
::new(&fbm_3)
.set_size(size_x as usize, size_y as usize)
.build();
let pix_span = (0..size_x as usize).cartesian_product(0..size_y as usize);
let mut result = image::RgbImage::new(size_x as u32, size_y as u32);
let map_fn = |val: f64| (val + 1.0) * 12... | Rust | 0 |
match response {
Ok(NodeResult::Mapped) => Ok((frame.base.as_u64(), frame.size() as u64)),
Err(e) => Err(e),
_ => unreachable!("Got unexpected response"),
}
}
pub fn unmap(pid: Pid, base: VAddr) -> Result<TlbFlushHandle, KError> {
debug_assert!(pid < ... | Rust | 0 |
', default=[0.0, 0.0, 0.0, 0.0],
help="List of x positions for the robots (space-separated).")
parser.add_argument('--y_pose', type=str, nargs='+', default=[1.0, 1.5, 2.0, 2.5],
help="List of x positions for the robots (space-separated).")
parser.add_argument('-... | Python | 1 |
-test-namespace)
(ns-pop)
(test::assert-true (ns-exists? 'ns-exists-test-namespace))
",
),
);
data.insert(
interner.intern("ns-list"),
Expression::make_function(
builtin_ns_list,
"Usage: (ns-list)
Returns a vector of all namespaces.
Section: namespace
Example:
... | Rust | 0 |
, V2);
}
}
/// Creates a new vector by combining the `z` and `w`-components of two vectors.
///
/// ## Parameters
///
/// `V1` First vector.
///
/// `V2` Second vector.
///
/// ## Return value
///
/// Returns the merged vector.
///
/// ## Remarks
///
/// The following pseudocode demonstrates the operation of the f... | Rust | 0 |
ults]),
'response_preview': results[0]['response_content'][:100].strip()
}
benchmark.add_result(
prompt['name'],
avg_result['prompt_tokens'],
avg_result['pp_speed'],
avg_result['ttft'],
avg_result['g... | Python | 1 |
1
);
}
/// Adapted from <http://web.cse.ohio-state.edu/~stiff.4/cse3521/prolog-resolution.html>
#[test]
fn test_retries() {
let mut polar = Polar::new();
polar
.load_str("f(1); f(2); g(1); g(2); h(2); k(x) if f(x) and h(x) and g(x); k(3);")
.unwrap();
assert!(qnull(&mut polar,... | Rust | 0 |
n());
}
fn spawn_bug(entities: &Entities,
sprite_sheet: Handle<SpriteSheet>,
lazy_update: &ReadExpect<LazyUpdate>,
transform: &Transform,
team: &Team) {
let sprite_render = SpriteRender {
sprite_sheet: sprite_sheet,
sprite_number: 0,
};
le... | Rust | 0 |
Debug, Clone, PartialEq, Eq, Hash)]
pub struct CastError {
// The kind of this error.
kind: CastErrorKind,
}
impl CastError {
/// Returns the kind of this error.
pub fn kind(&self) -> &CastErrorKind {
&self.kind
}
/// Unwrap this error into its underlying type.
pub fn into_kind(self) -> CastErrorKind {
sel... | Rust | 0 |
pub struct TableInfo {
pub dup_sort: Option<DupSortConfig>,
}
pub static TABLES: Lazy<HashMap<String, TableInfo>> =
Lazy::new(|| toml::from_str(include_str!("../db_tables.toml")).unwrap());
}
#[cfg(feature = "web3")]
pub mod web3 {
tonic::include_proto!("web3");
}
<filename>tests/test_en... | Rust | 0 |
class Venda:
def __init__(self, produto, quantidade, valor):
self.produto = produto
self.quantidade = quantidade
self.valor = valor
class Categoria:
def __init__(self, nome):
self.nome = nome
self.vendas = []
# Método para adicionar uma venda à lista de vendas
d... | Python | 1 |
Win32_System_Wmi'*"]
pub const wbemErrRerunCommand: WbemErrorEnum = -2147217289i32;
#[doc = "*Required features: 'Win32_System_Wmi'*"]
pub const wbemErrDatabaseVerMismatch: WbemErrorEnum = -2147217288i32;
#[doc = "*Required features: 'Win32_System_Wmi'*"]
pub const wbemErrVetoPut: WbemErrorEnum = -2147217287i32;
#[doc ... | Rust | 0 |
structor and contains all information needed for
comprehensive article analysis.
Examples:
>>> tree = ET.parse("pmc_article.xml")
>>> root = tree.getroot()
>>> article_dict = build_complete_paper_dict(7181753, root, verbose=True)
>>> print(f"Title: {article_dict['Title']}")
... | Python | 1 |
logger.info(
"Evaluation Precision: %.5f | Recall: %.5f | F1: %.5f"
% (eval_metrics["eval_precision"], eval_metrics["eval_recall"], eval_metrics["eval_f1"])
)
logger.info("-----------------------------")
for key in relation_type_dict.keys():
... | Python | 1 |
import pygame
import random
# Inicialização do Pygame
pygame.init()
# Definição de cores
branco = (255, 255, 255)
preto = (0, 0, 0)
# Configurações da tela
largura = 800
altura = 600
tela = pygame.display.set_mode((largura, altura))
pygame.display.set_caption('Pong')
# Relógio para controlar a taxa de atualização d... | Python | 1 |
#
# ovirt-engine-setup -- ovirt engine setup
#
# Copyright oVirt Authors
# SPDX-License-Identifier: Apache-2.0
#
#
"""Hostname plugin."""
import gettext
from otopi import plugin
from otopi import util
from ovirt_engine_setup import constants as osetupcons
from ovirt_setup_lib import hostname as osetuphostname
... | Python | 1 |
import numpy as np
# Calculations are based on squid notes under the "Directed Research"
# folder. These are derived from DC motor model equations. It assumes that the
# gain used in servo uses units of gain/deg instead of gain/raw_pos. The
# ST-3215-C047 model data is used. All the parameters are calculated based on
... | Python | 1 |
op` is not allowed in a `const`
static FOO: i32 = loop { break 4; }; //[stock,if_match]~ ERROR `loop` is not allowed in a `static`
const fn foo() {
loop {} //[stock,if_match]~ ERROR `loop` is not allowed in a `const fn`
}
pub trait Foo {
const BAR: i32 = loop { break 4; }; //[stock,if_match]~ ERROR `loop` is... | Rust | 0 |
# from pyspark.sql import functions as F
from optimus.helpers.columns import parse_columns, name_col
from optimus.helpers.constants import RELATIVE_ERROR
from optimus.helpers.converter import format_dict
from optimus.helpers.core import one_list_to_val
from optimus.infer import is_numeric
from optimus.outliers.abstrac... | Python | 1 |
import requests
import json
import random
import uuid
import time
import cv2
import numpy as np
from aesEncode import encryptAesEcb, decryptAesEcb
import base64
current_time_seconds = time.time()
timestamp_milliseconds = int(current_time_seconds * 1000)
def login(phone, passwd, encrypted_token):
"""
登录函数
... | Python | 1 |
field(ocaml_cons, 0, head.get_raw());
store_field(ocaml_cons, 1, tail.get_raw());
OCaml::new(cr, ocaml_cons)
}
}
use super::util::{ArrayWrapper, NumTradesError};
use serde_json::Value;
#[derive(Debug, Clone)]
pub struct NumTradesInfo {
//pub daily_volume: u64,
//pub rolling_24h_volume: u64,... | Rust | 0 |
from utils import listAllFiles, pathResolver
import sys
from parseReact import parseCodebase
from generator import createTree, generateSvelteCodebase
# from fileDependencies import resolveFileDependencies
def usage(binary: str) -> None:
print(
"""DESCRIPTION
\tSveno is a way to transpile react components to sveno ... | Python | 1 |
"""Constants for the sia integration."""
from __future__ import annotations
from typing import Final
from homeassistant.const import Platform
PLATFORMS: Final = [Platform.ALARM_CONTROL_PANEL, Platform.BINARY_SENSOR]
DOMAIN: Final = "sia"
ATTR_CODE: Final = "last_code"
ATTR_ZONE: Final = "last_zone"
ATTR_MESSAGE: F... | Python | 1 |
= Some(tx.id.clone());
let mut count = None;
let skip = 0;
let res = Transaction::store_list(&mut store, from.clone(), to.clone(), count.clone(), skip);
assert!(res.is_err());
count = Some(0);
let res = Transaction::store_list(&mut store, from.clone(), to.clone(), count.clone(), skip);
a... | Rust | 0 |
uid_wrap_filter<T>() -> BoxedFilter<(T,)>
where
T: From<Uuid> + Send + 'static,
{
warp::path::param().map(T::from).boxed()
}
use diqwest::core::WithDigestAuth;
use reqwest::{RequestBuilder, Response};
use crate::error::{Error, Result};
use serde::Deserialize;
use serde_aux::prelude::deserialize_number_from_stri... | Rust | 0 |
duration(&self, other: &Duration) -> SystemTime {
let intervals = self.intervals().checked_sub(dur2intervals(other))
.expect("overflow when subtracting from time");
SystemTime::from_intervals(intervals)
}
}
impl PartialEq for SystemTime {
fn eq(&self, other: &SystemT... | Rust | 0 |
umpTeam { ref name } => {
let team = data.team(name).ok_or_else(|| err_msg("unknown team"))?;
let leads = team.leads();
for member in team.members(&data)? {
println!(
"{}{}",
member,
if leads.contains(member... | Rust | 0 |
c4 = vec4 / Vector4::new(1, 2, 3, 4);
vec2 /= Vector2::new(1, 2);
vec3 /= Vector3::new(1, 2, 3);
vec4 /= Vector4::new(1, 2, 3, 4);
assert_eq!(vec2, Vector2::new(0, 0));
assert_eq!(vec3, Vector3::new(0, 0, 0));
assert_eq!(vec4, Vector4::new(0, 0, 0, 0));
}
#[test]
fn rem() {
// TODO: Repl... | Rust | 0 |
index: on_icon_click(e, idx))
# Dropdown to select a folder
def select_folder(event=None):
global selected_folder_path, icon_files, LABEL_JSON, LABEL_TXT, PROGRESS_FILE, FINALIZED_CLASS_FILE, icon_classes, finalized_classes, current_index
selected = selected_folder.get()
if selected:
selected_folde... | Python | 1 |
::get(oid) {
Some(val) => val.is_member(who.clone()),
None => false,
}
}
/// Get the info of proposal `pid`
pub fn get_proposal_by_id(pid: ProposalIdOf<T>) -> Result<ProposalOf<T>, dispatch::DispatchError> {
match Proposals::<T>::get(pid) {
Some(proposal) => Ok(proposal),
None => Err(Error::<T>::Prop... | Rust | 0 |
);
assert!(proofs[i].verify(&verifier_params, &old_com, &init_values[i], i));
}
let new_value = format!("\"this is new message number {}\"", update_index);
println!("\nUpdating string {} to {}\n", update_index, new_value);
// update the commitment to the new value, and (de)serialize it
le... | Rust | 0 |
::new(ClassicVigenere::solve(
lang,
text,
ClassicVigenereSolve {
stats_size,
max_key_length,
},
))
}
CipherSolveCmd:... | Rust | 0 |
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
import argparse
import logging
import os
import sys
import warnings
from datetime import datetime
warnings.filterwarnings('ignore')
import random
import torch
import torch.distributed as dist
from PIL import Image
import wan
from wan.configs i... | Python | 1 |
ition(), (3, 0))
stream.unget("\n")
self.assertEqual(stream.position(), (2, 2))
self.assertEqual(stream.char(), "\n")
self.assertEqual(stream.position(), (3, 0))
self.assertEqual(stream.charsUntil('e'), "ccc\nddd")
self.assertEqual(stream.position(), (4, 3))
self.... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# 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 requir... | Python | 1 |
tters,Serialize,Clone,Eq,PartialEq,Hash,Debug)]
pub struct ResponseEntry
{
#[get = "pub"]
qtype: String,
#[get = "pub"]
qname: String,
#[get = "pub"]
content: String,
#[get = "pub"]
ttl: usize,
// unused: domain_id,scopeMask,auth
}
impl ResponseEntry
{
pub fn soa<D: AsRef<str>, H: AsRef<str>>(domain: D, host... | Rust | 0 |
fn to_indices_source(&self) -> IndicesSource<T> {
IndicesSource::Buffer {
pointer: self.0.as_slice(),
primitives: PrimitiveType::LineStripAdjacency,
offset: 0,
length: self.0.len(),
}
}
}
/// A list of triangles stored in RAM.
pub struct Triangles... | Rust | 0 |
# Kadane's Algorithm by Master-Fury
# Worst and Average Case Time Complexity: O(n)
from sys import maxsize # importing maximum int from sys module
def kadane_algorithm(arr: int):
len_arr = len(arr) # Finding the len of array
max_so_far = -maxsize - 1 # Setting max value as maximum negative value
max... | Python | 1 |
prc1522: u64,
pub gprc: u64,
pub bprc: u64,
pub mprc: u64,
pub gptc: u64,
pub gorc: u64,
pub gotc: u64,
pub rnbc: [u64; 8],
pub ruc: u64,
pub rfc: u64,
pub roc: u64,
pub rjc: u64,
pub mngprc: u64,
pub mngpdc: u64,
pub mngptc: u64,
pub tor: u64,
pub tpr: u... | Rust | 0 |
_conn(matrix.as_path())
.expect("failed to read matrix");
for d in cmd.inputs.iter() {
builder
.read_lexicon(d.as_path())
.unwrap_or_else(|e| panic!("failed to read {:?}\n{:?}", d, e));
}
builder.resolve().expect("failed to resolve references");
let file = output_... | Rust | 0 |
work() {
let bsx_tkn1_liq_pool = AssetPair {
asset_in: BSX,
asset_out: TKN1,
};
predefined_test_ext_with_deposits().execute_with(|| {
assert_ok!(LiquidityMining::cancel_liquidity_pool(
Origin::signed(GC),
GC_FARM,
bsx_tkn1_liq_pool
));
assert_noop!(
LiquidityMining::update_liquidity_pool(
... | Rust | 0 |
anti_aliasing=True
)
if x.shape[1] < c:
to_stack = [x for i in range(c // x.shape[1])]
if c % x.shape[1] > 0:
to_stack += [x[:, :(c % x.shape[1]), ...]]
x = np.concatenate(to_stack, axis=1)
x = GeometricTensor(torch.FloatTensor(x), se... | Python | 1 |
from typing import Optional, TypedDict
class ToolResult(TypedDict):
"""Result from a tool execution."""
output: Optional[str]
error: Optional[str]
base64_image: Optional[str]
system: Optional[str]
class ToolError(Exception):
"""Exception raised for tool errors."""
def __init__(self, messag... | Python | 1 |
me;
},
}
let offset: u32 = child.attributes.get("Offset").unwrap().parse().unwrap();
let mut error_string = "";
match offset_to_address(id, offset) {
Ok(adr) => new_entry.address = adr,
Err(why) => { s... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.