text string | label_name string | labels int64 |
|---|---|---|
r.set_start_index(5);
attr_list.insert(attr);
let mut attr = pango::Attribute::new_scale(1.2);
attr.set_start_index(6);
attr_list.insert(attr);
label.set_attributes(Some(&attr_list));
window.add(&label);
window.show_all();
}
fn main() {
let application = gtk::Application::new(
... | Rust | 0 |
c.error_info_list.push((
MiddleArg::ShortFlag(short_flag, FlagValue::String(String::new())),
ParseError::NotExist,
ParseError::NotExist,
));
self.parse_next_if_flag(local_flags, c)
}
}
}
}
}
/// Parses(or assigns parse functions) args if next args.
pub fn parse_nex... | Rust | 0 |
aproximation of the binary
we do not "see" the exact value we have store in the float
IN python we use Decimal module to see this
twitter: https://lnkd.in/e2ffbrp
web: https://www.pymiami.org
linkedIn: https://lnkd.in/e6hvX8Y
*/
enum Result<T, E> {
Ok(T),
Err(E),
}
fn main() {
//we will get 0 he... | Rust | 0 |
st of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'alphapy', 'AlphaPy Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source ... | Python | 1 |
- unsorted: [201, 209, 2]
//! - sorted: [201, 2, 209]
//! - error: assertion failed: is_sorted
//! ```
//!
//! You can rerun the counterexample by setting an environment variable:
//!
//! ```text
//! DICETEST_DEBUG=/yiA1sab3S4UnCf4ozyMpxMxzg1NtFybCuYLHy0/oscDAAAAAAAAAA== cargo test
//! ```
//!
//! Or you can modi... | Rust | 0 |
scope_4577.number(
#[allow(clippy::useless_conversion)]
aws_smithy_types::Number::NegInt((*var_4578).into()),
);
}
#[allow(unused_mut)]
let mut scope_4579 = writer.prefix("Context");
if let Some(var_4580) = &input.context {
scope_4579.string(var_4580);
}
... | Rust | 0 |
eater_temp(self, heater, target, callback=None, *args):
logging.debug(f"Sending heater {heater} to temp: {target}")
return self._ws.send_method(
"printer.gcode.script",
{
"script": KlippyGcodes.set_heater_temp(heater, target)
},
callback,
... | Python | 1 |
pty glyph and shouldn’t have any glyph data, but if it does we will simply
// ignore it.
} else if glyph.num_contours > 0 {
// Simple glyphs.
// Read the contours. A contour is basically just a continous line. The letter 'O'
// for example has 2 contours. The end_points_of_contours ... | Rust | 0 |
"checkChatUsername",
"checkChatUsernameResultOk",
"checkChatUsernameResultPublicChatsTooMuch",
"checkChatUsernameResultPublicGroupsUnavailable",
"checkChatUsernameResultUsernameInvalid",
"checkChatUsernameResultUsernameOccupied",
];
fn deserialize_check_chat_username_result(
rtd_trait_type... | Rust | 0 |
/%s" % (left, right)
elif oper == "neg":
aststr = "-%s" % parenthesize(strify(values, excluded), mult=False)
elif oper == "pow":
left = parenthesize(strify(values[0], excluded))
x = values[1]
if left == "1":
aststr = "1"
elif (U... | Python | 1 |
import gradio as gr
import pandas as pd
from pathlib import Path
import ast
# --------------------
# File Paths
# --------------------
BASE = Path(__file__).parent
CSV_PATH = BASE / "Combined_QA_inferences.csv"
REVIEW_CSV = BASE / "qa_hallucination_annotations_reviewed.csv"
# --------------------
# Config
# ---------... | Python | 1 |
be the
sum of two distances, namely `point_face(mesh, pcl) + face_point(mesh, pcl)`
`point_face(mesh, pcl)`: Computes the squared distance of each point p in pcl
to the closest triangular face in mesh and averages across all points in pcl
`face_point(mesh, pcl)`: Computes the squared distance of e... | Python | 1 |
List
def _bar_changed(self, new):
self.bar_changed.append(new)
foo = Foo()
self.assertEqual(len(foo.bar_changed), 0)
foo.bar = 1
validate.assert_called_once_with(foo, "bar", 1)
self.assertEqual(foo.bar, "baz")
self.assertEqual(len(foo.bar... | Python | 1 |
- `request.method`
- `request.path`
- `request.header.<name>` (name is the same as the original header name but with dashes replaced with underscores)
- example: `request.header.content_type`
- `response.status`
- `response.body.size`
# Usage
First add `beeline_rocket` to your `Cargo.toml`:
```toml
[depende... | Rust | 0 |
);
stark.eval_packed_base(vars, &mut consumer);
consumer.accumulators()[0]
})
.collect::<Vec<_>>();
let constraint_eval_degree = PolynomialValues::new(constraint_evals).degree();
let maximum_degree = WITNESS_SIZE * stark.constraint_degree() - 1;
ensure!(
... | Rust | 0 |
import os
KAFKA_BROKER = os.getenv("KAFKA_BROKER", "") | Python | 1 |
# -*- coding: utf-8 -*-
# Copyright (C) 2024 BIRU
#
# This file is part of Tenzu.
#
# Tenzu is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or (at your option) any later... | Python | 1 |
[0, 0, 2, 1, 3],
[1, 1, 1, 1, 1]]))
npt.assert_array_equal(obs[0], np.array([0, 1, 1, 0, 2]))
npt.assert_array_equal(obs[1], np.array([0, 0, 2, 1, 3]))
npt.assert_array_equal(obs[2], np.array([1, 1, 1, 1, 1]))
def test_v... | Python | 1 |
::{debug, error};
use os_pipe::PipeWriter;
use sandboxfs::{Mapping, NoCache};
use tempfile::TempDir;
use time::Timespec;
use crate::{util, Mappings, Sandbox};
const MOUNT_OPTIONS: &[&str] = &["-o", "fsname=sandboxfs", "-o", "allow_other"];
const TTL_SECONDS: i64 = 60;
#[derive(Debug)]
pub struct Sandboxfs {
inpu... | Rust | 0 |
o;
use tabin_plugins::Status;
#[test]
fn alerts_when_told_to() {
let mem = MemInfo {
total: Some(100),
available: Some(15), // 15% free means 85% used
free: None,
cached: None,
};
let crit_threshold = 80.0;
assert_eq!(compare_... | Rust | 0 |
::from(dprefix) < BROTLI_NUM_DISTANCE_SHORT_CODES {
let table: [(usize, isize);16]= [(1,0), (2,0),(3,0),(4,0),
(1,-1), (1, 1), (1,-2), (1,2),(1,-3),(1,3),
(2,-1),(2,1),(2,-2),(2,2),(2,-3),(2,3)];
//eprint!("AA {:?} {:?} -> ... | Rust | 0 |
.get(name).expect(format!("{} not found", name).as_str())
.as_table().expect(em.must_be("package data").as_str());
let url = package
.get("url").expect(em.missing("url").as_str())
.as_str().expect(em.missing("url").as_str());
let version = package
.get("version").expec... | Rust | 0 |
})
.copied()
// There should only ever be one associated item that matches from any inherent impl
.next()
// Check if item_name belongs to `impl SomeTrait for SomeItem`
// FIXME(#74563): This gives precedence to `impl So... | Rust | 0 |
if plot is True: plot_networkx(graph, roles)
return graph, roles
def plot_networkx(graph, role_labels):
cmap = plt.get_cmap('hot')
x_range = np.linspace(0, 1, len(np.unique(role_labels)))
coloring = {u: cmap(x_range[i]) for i, u in enumerate(np.unique(role_labels))}
node_color ... | Python | 1 |
zip(fibers[*t..].iter()) {
r.push(a.clone() + b.clone().mul_unity_root_pow(j * m));
}
debug_assert!(r.len() == *t);
r
};
(subring(1), subring(2))
}
fn schoenhage(self, other: Self) -> Self {
let cache = storage::<Self, SchoenhageTriadi... | Rust | 0 |
all(&self) -> Vec<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{
self.children_of_type()
}
/// Retrieves 'i's TerminalNode corresponding to token IDENTIFIER, starting from 0.
/// Returns `None` if number of children corresponding to token IDENTIFIER is less or equal than `i`.
fn IDENTIFIER(&self,... | Rust | 0 |
index, cx - radius, cy + radius - i);
score += self.fitness_cell(index, cx + radius, cy - radius + i);
score += self.fitness_cell(index, cx + radius - i, cy + radius);
}
score
}
fn fitness_apat(&self, index: usize, cx: usize, cy: usize) -> i64 {
self.fitness_cell... | Rust | 0 |
(time_step_results.time_step, time_step_results.c_i)
}),
color_i,
))
.unwrap();
chart
... | Rust | 0 |
= DefaultMachineBuilder::<Box<AsmCoreMachine>>::new(asm_core).build();
let mut machine = AsmMachine::new(core, None);
machine.load_program(&buffer, &["main".into()]).unwrap();
let result = machine.run();
assert!(result.is_ok());
assert_eq!(result.unwrap(), 0);
}
#[cfg(has_asm)]
pub fn aot_v1_imcb(... | Rust | 0 |
v.resolve_references(todo_entry, todo_info['docname'],
app.builder)
# Insert into the todolist
content.append(todo_entry)
content.append(para)
node.replace_self(content)
def purge_todos(app, env, docname):
if not hasattr(env, 'todo_a... | Python | 1 |
conn.write_message(data, binary=True)
return len(data)
on_message = _ffi_api.CreateEventDrivenServer(_fsend, "WebSocketProxyServer", "%toinit")
return on_message
@gen.coroutine
def _connect(key):
conn = yield websocket.websocket_connect(url)
on_message ... | Python | 1 |
let (scale, scale_d_r, scale_dd_r_r);
{
scale = f64::exp(-params.lambda * (dist - params.z0));
let scale_d_dist = -params.lambda * scale;
let scale_dd_dist_dist = -params.lambda * scale_d_dist;
// ...in terms of r
scale_d_r = scale_d_dist * dist_d_r;
scale_dd_r_r = s... | Rust | 0 |
import pygame
from os.path import join
from Laser import Laser
WINDOW_WIDTH, WINDOW_HEIGHT = 1280, 720
class Player(pygame.sprite.Sprite):
def __init__(self, groups, laser_group, laser_surf, laser_sound):
super().__init__(groups)
player_img_path = join('images', 'player.png')
self.image =... | Python | 1 |
"""
Shows how to generate an embedding with the Amazon Titan Embeddings G1 - Text model (on demand).
"""
import json
import logging
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def generate_embedding(model_id, body):
"""... | Python | 1 |
lse:
self.__configureFilter()
on = self.taskFilter.hasActiveFilter()
self.taskFilter.setActive(on)
self.__menuFilteredAct.setChecked(on)
self.__backMenuFilteredAct.setChecked(on)
self.__refreshDisplay()
def __configureFilter(self):
... | Python | 1 |
LengthChangeEvent, Error<VE>> {
require_len!(payload, 11);
Ok(LeDataLengthChangeEvent {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&payload[1..])),
max_tx_octets: LittleEndian::read_u16(&payload[3..]),
max_tx_time: LittleEndian::read_u16(&payload[5..]),
max_rx_octets... | Rust | 0 |
Self::WindowMapRequest(e) => {
write!(f, "Window map [window: {}]", e.window())?;
}
Self::WindowUnmap(e) => {
write!(f, "Window unmap [window: {}]", e.window())?;
}
Self::WindowConfigureRequest(e) => {
write!(f, "Window con... | Rust | 0 |
f}")
logger.info(f"Saved optimal threshold to {threshold_file}")
# Suggest threshold to use in settings
logger.info("\nRecommended settings:")
logger.info(f"Global threshold: {results['optimal_threshold']:.4f}")
logger.info(f"Patch threshold: {results['optimal_threshold'... | Python | 1 |
lock is 0
{
let event_filter = Filter {
from_block: 0,
to_block: 10,
event_keys: vec![EventKey::new_from_address(&genesis_address(), 4)],
limit: Some(20),
reverse: true,
};
let evts = mock_chain.head().filter_events(event_filter).un... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 12 18:09:38 2023
@author: oscar
"""
import os
import random
routes = {}
routes["training_routes/routes_town03_short.xml"] = "scenarios/town03_all_scenarios.json"
routes["training_routes/routes_town03_tiny.xml"] = "scenarios/town03_all_scenarios.js... | Python | 1 |
)
}
}
/* space > space \n */
fn cdelim<'a>(c: &'a ParserConfig) -> impl FnMut(&'a str) -> IResult<&'a str, ()> {
|i| {
let (i, _) = pair(whitespaced(tag(c.cdelim.as_str())), opt(char('\n')))(i)?;
Ok((i, ()))
}
}
// Wraps another parser to allow for whitespaces
fn whitespaced<'a, O1, E, P>(... | Rust | 0 |
HoldEvent {
fn context(&self) -> &Libinput {
match self {
GestureHoldEvent::Begin(event) => event.context(),
GestureHoldEvent::End(event) => event.context(),
}
}
}
ffi_event_struct!(
/// Swipe gesture began
struct GestureSwipeBeginEvent, ffi::libinput_event_gesture, ffi:... | Rust | 0 |
_msg.target_address.clone(),
&release_state,
)?;
CONFIG.update(deps.storage, |mut cfg| -> StdResult<_> {
cfg.claims = cfg.claims.add(Uint64::new(1));
Ok(cfg)
})?;
let res = Response::new()
.add_message(BankMsg::Send {
to_address: claim_msg.clone().target_add... | Rust | 0 |
bboxes[obj_num, 4] = cur_bbox[1, 1]
# 第5维记录角度,这里最好做一个限制角度因为对于rl而言角度不同其实观测也是不同的,直接采用绝对坐标系下的值进行相减即可
curr_obj_bboxes[obj_num, 5] = limit_angle(float(obj_rad) - theta)
# 获取目标物体的tf和bbox
inv_base_tf = np.linalg.inv(robot_tf)
# 获取当前target的tf,在局部坐标系下
curr_goal_tf_xzy = np.dot(inv_base_tf, targe... | Python | 1 |
TextDecoder.detect_url_encoding,
TextDecoder.detect_rot13,
TextDecoder.detect_morse
]
for detector in detectors:
result = detector(text)
if result is not None:
return result
return ("Unknown", text)
def ma... | Python | 1 |
resource.setrlimit(resource.RLIMIT_AS,
(maximum_memory_bytes, maximum_memory_bytes))
resource.setrlimit(resource.RLIMIT_DATA,
(maximum_memory_bytes, maximum_memory_bytes))
if not platform.uname().system == 'Darwin':
resource.set... | Python | 1 |
| 1 |
//! | impl Iterator<Item=T> | | panic | panic | panic | |
//! | impl Iterator<Item=T> | no_panic | skip | ignored | empty iter | 3 |
//! | impl Iterator<Item=Result<T, E>> | ... | Rust | 0 |
import re
from ide.utils.regexes import regexes
def parse_sdk_version(version):
""" Parse an SDK compatible version string
:param version: should be "major[.minor]"
:return: (major, minor)
"""
parsed = re.match(regexes.SDK_VERSION, version)
if not parsed:
raise ValueError("Invalid ver... | Python | 1 |
fields=[{
"name": "Recent Transactions",
"value": format_transaction_history(transactions),
"inline": False
}],
footer="Showing last 10 transactions"
)
await interaction.followup.send(embed=embed)
except E... | Python | 1 |
"""
智能饥饿管理器 - 感知背包物品,智能决策进食和请求食物
"""
import time
import random
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass
import logging
logger = logging.getLogger(__name__)
@dataclass
class FoodItem:
"""食物物品数据"""
name: str
display_name: str
count: int
nutrition_value: ... | Python | 1 |
and will not be downloaded again",
out_path.display(),
);
continue;
}
let url = format!("{}/{}.{}.gz", BASE_URL, dataset, extension);
eprintln!("downloading: {}", url);
let bytes = download_dataset(url.clone())?;
eprintln!("{} downloaded s... | Rust | 0 |
d_atom)))) (atom (unquoted_atom)))
(expression (term (integer)))
(expression
(function_call
(qualified_function_name (expression (term (atom (unquoted_atom)))) (atom (unquoted_atom)))
(expression (term (integer)))
(expression (term (integer)))
(expression (term (integer))))))))"#
... | Rust | 0 |
else {
//! //This will usually not happen, unless the handler is also
//! //assigned to a path without the `id` variable
//! response.send("no id provided");
//! }
//!}
//!```
//!
//!##Other URL Parts
//!
//! * Query variables (`http://example.com?a=b&c=d`) can be found in the
//!`query` field ... | Rust | 0 |
{
std::fmt::Debug::fmt(self, f)
}
}
impl std::error::Error for TrackError {}
impl Into<LayoutError> for TrackError {
fn into(self) -> LayoutError {
LayoutError::Boxed(Box::new(self))
}
}
<reponame>adyta-lda/openmls<gh_stars>1-10
#![no_main]
use libfuzzer_sys::fuzz_target;
use openmls::prel... | Rust | 0 |
// Generate a list of the time zone periods beyond the first that apply
// to this zone, as a string representation of a static slice.
fn format_rest(rest: Vec<(i64, FixedTimespan)>) -> String {
let mut ret = "&[\n".to_string();
for (start, FixedTimespan { utc_offset, dst_offset, name }) in rest {
ret.p... | Rust | 0 |
#[lang = "str"]
impl str {
fn foo(&self) -> i32 {}
}
fn test() {
"foo".foo();
}
"#,
expect![[r#"
39..43 'self': &str
52..54 '{}': ()
68..88 '{ ...o(); }': ()
74..79 '"foo"': &str
... | Rust | 0 |
"""
Define all different types of models.
Created on 2019-01-28-13-17
Author: Stephan Rasp, raspstephan@gmail.com
"""
from .imports import *
from .cam_constants import *
from tensorflow.keras.layers import *
from .layers import *
def act_layer(act):
"""Helper function to return regular and advanced activation l... | Python | 1 |
return Err(Error::MOpt("Error in pso_update".to_string()));
}
}
self.swarm_now = 0;
// After pso_update, go back to pilot-fuzzing module
Ok(())
}
/// This function is used to decide the operator that we want to apply next
/// see <https://github.... | Rust | 0 |
import sys
from src.__init__ import *
if __name__ == "__main__":
clear()
banner()
while True:
try:
major = Major()
major.main()
except KeyboardInterrupt:
log(mrh + f"Interrupted by users, exiting..")
sys.exit() | Python | 1 |
l_count = config.POST_NMS_ROIS_TRAINING
rpn_rois = ProposalLayer(proposal_count=proposal_count, nms_threshold=config.RPN_NMS_THRESHOLD,
name="ROI", config=config)([rpn_class, rpn_bbox, anchors])
active_class_ids = Lambda(lambda x: parse_image_meta_graph(x)["active_class_ids"])(input_ima... | Python | 1 |
r {
input: read_input(2019, "2"),
}
}
#[test]
fn real_a() {
assert_eq!(new().run_a(), String::from("5434663"));
}
#[test]
fn real_b() {
assert_eq!(new().run_b(), String::from("4559"));
}
}
mod eeprom;
pub use self::eeprom::Eeprom;
<reponame>b00f/durian
u... | Rust | 0 |
().unwrap();
let utxo_sender = config.block0_utxo_for_address(&sender);
let new_utxo = do_simple_transaction(
&sender,
&account_receiver,
&utxo_sender,
&utxo_receiver,
&jormungandr,
);
let snapshot_before = take_snapshot(&account_receiver, &jormungandr, new_utxo.... | Rust | 0 |
1,
]),
sapling_raw_addr: None,
orchard_raw_addr: Some([
0xdc, 0xb1, 0xd2, 0xa3, 0x77, 0x62, 0x14, 0x8d, 0xb4, 0xce, 0xe3, 0xbb, 0xf1, 0x9f,
0xb1, 0xec, 0x05, 0x89, 0x18, 0x94, 0xb1, 0x38, 0x01, 0xc6, 0x22, 0xba, 0x6a, 0x90,
0xfa, 0xf1, 0x11, 0x9f, 0x82, 0x24, ... | Rust | 0 |
tate if self.visualization else SupervisorGraphState
supervisor_graph = StateGraph(state_type)
supervisor_graph.add_node("human_input_node", self.human_input_node, metadata={"type":"human"})
supervisor_graph.add_node("chat_history_summarize_node", self.chat_history_summarize_node, metadata={"ty... | Python | 1 |
();
let c = editor.add_comparison("Best Segments");
assert_eq!(c, Err(ComparisonError::DuplicateName));
}
#[test]
fn rename_comparison_editor() {
let mut run = Run::new();
run.push_segment(Segment::new("s"));
run.add_custom_comparison("Custom").ok();
let mut ... | Rust | 0 |
配置 '{alias}' 已更新!")
else:
gr.Error(f"更新API配置失败!")
except Exception as e:
logger.error(f"更新API配置失败: {e}")
gr.Error(f"更新API配置失败: {e}")
return UIComponents.refresh_api_configs()
@staticmethod
def delete_api_config_and_refresh(config_id):
... | Python | 1 |
for being explicit on what `A` is.
/// For clarity, this may be a good idea.
///
/// Use this version instead of [`arbitrary_with`] if you want to be clear which
/// type you want to generate a `Strategy` for, or if you don't have an anchoring
/// type for type inference to work with.
///
/// If you don't want to spec... | Rust | 0 |
abel=f"{eval_model}, #p={n_params}, E={E0}+-{var}, delta= {rel_error}")
fig.suptitle(f" ToricCode2d h={tuple([round(hi, 3) for hi in h])}: size={shape},"
f" n_discard={n_discard_per_chain},"
f" n_chains={n_chains},"
f" n_samples={n_samples} \n"
f" using SR with diag... | Python | 1 |
to_text(&instr, &flags)
.unwrap_or_else(|e| exit_error(&format!("Program too large? ({})", e)));
text::automatic_imports(&mut compiled, flags.debug, flags.kill_interrupts);
if flags.debug {
compiled.insert_str(0, "\tORG\t$20\n");
}
if flags.print_result {
println!("{}", &compiled);
}
if !flags.print_result ... | Rust | 0 |
}
}
}
///New message from this user send to all other players except sender.
fn send_to_other_players(
users: &Users,
ws_uid_of_message: usize,
new_msg: &str,
players_ws_uid: &str,
) {
//info!("send_to_other_players: {}", new_msg);
let vec_players_ws_uid: Vec<usize> = unwrap!(serd... | Rust | 0 |
_version() {
let package_json = indoc! {r###"
{
"private": true,
"name": "or",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
... | Rust | 0 |
impl AsioSample for i16 {
fn to_cpal_sample<T: Sample>(&self) -> T {
T::from(self)
}
fn from_cpal_sample<T: Sample>(t: &T) -> Self {
Sample::from(t)
}
}
impl AsioSample for i32 {
fn to_cpal_sample<T: Sample>(&self) -> T {
let s = (*self >> 16) as i16;
s.to_cpal_sampl... | Rust | 0 |
0x1E => Some(ADD_I_R(x)),
0x29 => Some(LD_F_R(x)),
0x33 => Some(LD_B_R(x)),
0x55 => Some(LD_II_R(x)),
0x65 => Some(LD_R_II(x)),
_ => None,
},
_ => unreachable!(a)
}
}
pub fn to(self) -> u16 {
... | Rust | 0 |
_WS_PORT};
use jsonrpc_http_server::{
hyper::{header, Request, Response, StatusCode},
jsonrpc_core::{
self, Compatibility, Id, MetaIoHandler, Metadata, MethodCall, Params, Value, Version,
},
RequestMiddlewareAction, RestApi, Server, ServerBuilder,
};
use std::collections::BTreeMap;
use std::ite... | Rust | 0 |
(
"VOLTA_INSTALL_DIR",
&shim_exe().parent().unwrap().to_string_lossy(),
)
.build();
#[cfg(unix)]
assert_that!(
s.process(&shim_exe()),
execs()
.with_status(ExitCode::ExecutionFailure as i32)
.with_stderr_contains("VOLTA_BYPASS is e... | Rust | 0 |
v:&T| {
v.write_repr(self.writer);
}
}
fn write_escaped_slice(slice: &str) {
self.writer.write_char('"');
for str::chars_each(slice) |ch| {
self.writer.write_escaped_char(ch);
}
self.writer.write_char('"');
}
fn write_mut_qualifier(mtbl: ... | Rust | 0 |
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | Python | 1 |
sponse(
child_id.into(),
query,
Filter::NodeNexus(node_id.into(), nexus_id.into()),
)
.await
}
async fn get_node_nexus_children(
Path((node_id, nexus_id)): Path<(String, Uuid)>,
) -> Result<Vec<models::Child>, RestError<RestJsonError>> {
g... | Rust | 0 |
[i for i, x in enumerate(self.plan[room]) if x == "Free"]
for idx, dorm in enumerate(self.dorm):
if dorm.position[0] == room:
for i, _name in enumerate(plan):
if _name not in self.operators.keys():
self.add(Operator(_name, ""))
... | Python | 1 |
r should have been in good state.");
// TODO: make a special kind of thing you can pick up.
// TODO: accept that as a system argument, and have some builders
// that make it super-easy to configure.
// The goal here should be that the "block dude" game
// ends up both concise and legible.
let n... | Rust | 0 |
ght }.into()) }
--
left:(@) _ "<" _ right:@ { Expr::Comparison(ComparisonExpr { pos: (start..right.pos().end), left, op: ComparisonOp::Lt, right }.into()) }
left:(@) _ "<=" _ right:@ { Expr::Comparison(ComparisonExpr { pos: (start..right.pos().end), left, op: ComparisonOp::Lte, right... | Rust | 0 |
e long tail of dunder methods and attributes.
actual = set(dir(Mollusc()))
# Check instance names
assert actual == expected
# Check type names
expected = (
set(dir(type))
| {
# Class methods from the MessageMeta metaclass
"copy_from",
"deseriali... | Python | 1 |
inate(mut self, page: i64, per_page: i64) -> Self {
let offset = (page - 1) * per_page;
self.query = self.query.offset(offset).limit(per_page);
self
}
pub fn order_by_created_at(mut self) -> Self {
self.query = self.query.order(transactions::created_at.desc());
self
... | Rust | 0 |
import pytest
from ase.lattice.cubic import FaceCenteredCubic
from ase.lattice.hexagonal import HexagonalClosedPacked
def test_miller_lindep():
with pytest.raises(ValueError):
# The Miller indices of the surfaces are linearly dependent
FaceCenteredCubic(symbol='Cu',
mill... | Python | 1 |
GroupLayout>,
compute_pipeline: wgpu::ComputePipeline,
}
pub struct GPUSetGroupLayout {
pub set_bind_group_layouts: HashMap<u32, HashMap<u32, (wgpu::BindGroupLayoutEntry, String)>>,
}
///
/// Helper to create the layout of bindings (along with set information.)
/// This returns a `GPUSetGroupLayout` which is ... | Rust | 0 |
&str,
_variant_value: EnumVariantValue,
) -> Option<String> {
let mut variant_name = variant_name.to_camel_case();
if let Some(enum_name) = enum_name {
let enum_name = enum_name.replace("enum ", "").to_camel_case();
if variant_name.starts_with(&enum_name) {
... | Rust | 0 |
with codes 301,302,303,307,308)
Redirect(u32),
/// Keep original (bare `=`)
Keep,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorPage {
pub codes: Vec<u32>,
pub response_code: ErrorPageResponse,
pub uri: Value,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Return {
Redirect ... | Rust | 0 |
print([x**2 for x in range(1,21)]) | Python | 1 |
get(|| {
::protobuf::reflect::EnumDescriptor::new_pb_name::<ConvolutionKind>("ConvolutionKind", file_descriptor_proto())
})
}
}
impl ::std::marker::Copy for ConvolutionKind {
}
impl ::std::default::Default for ConvolutionKind {
fn default() -> Self {
ConvolutionKind::INVALID
}
... | Rust | 0 |
def calculate_price(num_people, is_agreement_client=False, is_elderly_team=False, is_student_team=False, is_long_distance_market=False, is_hotel_package=False, is_employee=False, elderly_count=0, student_count=0, employee_relatives_count=0):
"""
计算总花销的函数,并返回详细的计算过程。
参数:
- num_people: 购票人数
- is_agre... | Python | 1 |
"""回測模組
此模組提供回測功能,用於評估交易策略的表現。
"""
import warnings
import matplotlib.pyplot as plt
import pandas as pd
from src.core.data_ingest import load_data
from .utils import detect_close_col, ensure_multiindex
__all__ = ["Backtest"]
# 忽略 FutureWarning
warnings.simplefilter(action="ignore", category=FutureWarning)
class ... | Python | 1 |
let sxmax = max(second.0 .0, second.1 .0);
let x = first.0 .0;
let y = second.0 .1;
if sxmin <= x && x <= sxmax && fymin <= y && y <= fymax {
Some(steps + (first.0 .1 - y).abs() + (second.0 .0 - x).abs())
} else {
... | Rust | 0 |
import json
from difflib import SequenceMatcher
from src import logger
def f1(precision, recall):
if precision + recall == 0:
return 0
return round(2 * precision * recall / (precision + recall), 4)
def compute_label_nums(src_text, trg_text, pred_text, log_error_to_fp=None):
assert len(src_text)... | Python | 1 |
import glob, pygame, os
import numpy as np
import soundfile as sf
from pydub import AudioSegment
from scipy.io.wavfile import write
#Loads list of KEMAR angles to be used by player
kemar = './KEMAR/full/elev0/*.wav'
KEMAR = glob.glob(kemar)
#After splitting file, loop through each KEMAR angle and create a binaural mi... | Python | 1 |
.add_time(Duration::from_millis(PROPOSE_REQUEST_TIMEOUT));
sandbox.send(
sandbox.p(ValidatorId(1)),
&make_request_propose_from_precommit(&sandbox, &precommit_1),
);
sandbox.send(
sandbox.p(ValidatorId(1)),
&make_request_prevote_from_precommit(&sandbox, &precommit_1),
);
... | Rust | 0 |
|x| x.is_numeric()).collect();
match num_str.parse::<u64>() {
Ok(n) => n == self.0,
Err(_) => false,
}
}
}
error_chain::error_chain! {
foreign_links {
Io(::std::io::Error);
Nix(nix::Error);
ParseInt(::std::num::ParseIntError);
Parse(::std:... | Rust | 0 |
_id = connections_from_start.trailing_zeros() as u8;
let destination_bitmask = 1 << destination_id;
connections_from_start ^= destination_bitmask;
let has_visited_destination_once = visited_once_bitset & destination_bitmask > 0;
let destination_is_big_cave = self.big_ca... | Rust | 0 |
commit version
async fn commit_primary(&mut self) -> Result<u64> {
let primary_key = vec![self.mutations[0].key.clone().into()];
let commit_version = self.rpc.clone().get_timestamp().await?.version();
new_commit_request(primary_key, self.start_version, commit_version)
.execute(s... | Rust | 0 |
# -*- coding: utf-8 -*-
#
# __init__.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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 2 of the License, or
# ... | Python | 1 |
val_range
The iterable of values used to create the labels. Determines the exponent.
unit_decimal_places
The number of decimal places to include in the exponent
base_config
Additional arguments to be passed to :class:`~.Integer`.
"""
# uses `fo... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.