text string | label_name string | labels int64 |
|---|---|---|
"]
#[doc = "*This API requires the following crate features to be activated: `Usb`*"]
#[doc = ""]
#[doc = "*This API is unstable and requires `--cfg=web_sys_unstable_apis` to be activated, as"]
#[doc = "[described in the `wasm-bindgen` guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable... | Rust | 0 |
/docs.github.com/rest/reference/reactions#create-reaction-for-a-team-discussion-comment>
*
* **Parameters:**
*
* * `org: &str`
* * `team_slug: &str` -- team_slug parameter.
* * `discussion_number: i64`
* * `comment_number: i64`
*/
pub async fn create_for_team_discussion_comme... | Rust | 0 |
p.serialize_entry(k, &(*v as i32))?;
} else {
map.serialize_entry(k, v)?;
}
}
map.end()
}
}
#[cfg(test)]
mod tests {
use super::*;
use maplit::btreemap;
use serde_test::{assert_ser_tokens, Token};
#[test]
fn serialize_kerning() {
... | Rust | 0 |
bpki;
/// An OpenSSL X509 object
#[allow(non_camel_case_types)]
#[derive(Clone)]
pub struct X509 {
magic: [u8; MAGIC_SIZE],
pub inner: rustls::Certificate,
}
impl OpaquePointerGuard for X509 {
fn check_magic(&self) -> bool {
self.magic == *MAGIC
}
}
#[allow(unused)]
enum EndEntityOrCA<'a> {
... | Rust | 0 |
:.4f}')
# 真实数据
true_array_sst = np.array(total_true_sst)
# 预测数据
pred_array_sst = np.array(total_pred_sst)
print('true_array_sst shape:', true_array_sst.shape)
print('pred_array_ssh shape:', pred_array_sst.shape)
# 将数据进行保存
test_data_save_dir = args.test_data_save_dir
# 获取当前日期
cur... | Python | 1 |
te`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pwd_set](pwd_set) module"]
pub type PWD_SET = crate::Reg<u32, _PWD_SET>;
#[al... | Rust | 0 |
lease/quantii",
"../target/dist/quantii-arm/kernel8.img",
])
.status()
.expect("failed to execute process");
assert!(status.success());
}
fn dist() {
match env::args().nth(2).as_deref() {
None => {
dist_arm();
dist_riscv();
}
S... | Rust | 0 |
leted_str_eq("α");
}
#[test]
fn kill() {
let cl = Listener::new();
let mut s = LineBuffer::init("αßγδε", 6, Some(cl.clone()));
let ok = s.kill_line();
assert_eq!("αßγ", s.buf);
assert_eq!(6, s.pos);
assert_eq!(true, ok);
cl.borrow().assert_deleted_str... | Rust | 0 |
Self {
State(src)
}
}
impl From<State> for usize {
fn from(src: State) -> Self {
src.0
}
}
impl fmt::Debug for State {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("pool::State")
.field("lifecycle", &self.lifecycle())
.f... | Rust | 0 |
ve(Readable, Debug)]
struct InputReport {
timestamp: u8,
misc: u8,
buttons: [u8; 3],
left_stick: [u8; 3],
right_stick: [u8; 3],
unk1: u8
}
#[derive(Readable, Debug)]
#[speedy(tag_type = u8)]
enum DeviceType {
#[speedy(tag = 1)]
LeftJoyCon,
#[speedy(tag = 2)]
RightJoyCon,
#[s... | Rust | 0 |
, 2],
torch.tensor(code_sur_corr[:, base_ctr]),
params,
out_path_name=os.path.join(
out_path,
"neuralgml_spearman_correlation_base{}.png".format(base_ctr),
),
color_ctr=bas... | Python | 1 |
method.tpe().t_dom.len()
)));
}
let expected_types = vec![obj.tpe()];
if !method
.tpe()
.t_dom
.iter()
.zip(&expected_types)
.all(|(expected, actual)| expected == actual)
{
return Err(Inv... | Rust | 0 |
SystemServices"))]
pub union CLUSPROP_BUFFER_HELPER {
pub pb: *mut u8,
pub pw: *mut u16,
pub pdw: *mut u32,
pub pl: *mut i32,
pub psz: ::windows_sys::core::PWSTR,
pub pList: *mut CLUSPROP_LIST,
pub pSyntax: *mut CLUSPROP_SYNTAX,
pub pName: *mut CLUSPROP_SZ,
pub pValue: *mut CLUSPROP_... | Rust | 0 |
else:
fields.append(convert_pandas_type_to_json_field(data))
schema["fields"] = fields
if index and data.index.is_unique and primary_key is None:
if data.index.nlevels == 1:
schema["primaryKey"] = [data.index.name]
else:
schema["primaryKey"] = data.index.nam... | Python | 1 |
MII Write and Read"]
#[inline(always)]
pub fn mii_wr(&mut self) -> MII_WR_W {
MII_WR_W { w: self }
}
#[doc = "Bit 0 - MII Status"]
#[inline(always)]
pub fn mii_busy(&mut self) -> MII_BUSY_W {
MII_BUSY_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inli... | Rust | 0 |
}
}
pub fn current_idx(&self) -> usize {
self.current_selection
}
pub fn num_items(&self) -> usize {
self.items.len() - 2
}
}
<gh_stars>100-1000
use crate::graph::WeightedUndirectedAdjacencyMatrixCondensed;
use ordered_float::OrderedFloat;
use priority_queue::PriorityQueue;... | Rust | 0 |
let instructions = cs
.disasm_count(
unsafe { std::slice::from_raw_parts(actual_pc as *mut u8, 24) },
actual_pc as u64,
3,
)
.unwrap();
let instructions = instructions.iter().collect::<Vec<Insn>>();
let mut insn = ins... | Rust | 0 |
omplexField, D: Dim, S: StorageMut<T, D, D>>(
m: &OMatrix<T, D, D>,
out: &mut SquareMatrix<T, D, S>,
) -> bool
where
DefaultAllocator: Allocator<T, D, D>,
{
let m = m.as_slice();
out[(0, 0)] = m[5].clone() * m[10].clone() * m[15].clone()
- m[5].clone() * m[11].clone() * m[14].clone()
... | Rust | 0 |
-> BusId {
// let new_bus = EventBus::new();
// let id = new_bus.id;
// EVENT_BUSES.write().push_back(new_bus);
//
// id
// }
//
// /// If give id exist in buses list, return given id
// ///
// /// else return a new bus id
// pub fn get_or_create_event_bus(id: u64) -> BusId {
// if let S... | Rust | 0 |
)`: In case of error.
pub fn decode_from_bytes(value: &[u8]) -> Result<(u64, usize)> {
if value.is_empty() {
Err(ErrorKind::InvalidFormat)
} else {
let size = decoded_size(value[0]);
if size == 1 {
Ok((value[0] as u64, size))
} else if value.len() < size {
... | Rust | 0 |
Event::Key(KeyEvent {
code: KeyCode::Char(c),
modifiers: KeyModifiers::NONE | KeyModifiers::SHIFT,
}) => {
let start = UnicodeSegmentation::graphemes(self.content.as_str(), true)
.take(self.cursor_position)
.collect::<String>();
let end = UnicodeSegmentation::graphemes(self.content.as_s... | Rust | 0 |
is {}", 1_000_000u32);
}
fn reverse(pair: (i32, bool)) -> (bool, i32) {
let (integer, boolean) = pair;
(boolean, integer)
}
use std::fmt;
#[derive(Debug)]
struct Matrix(f32, f32, f32, f32);
impl fmt::Display for Matrix {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "( {} {}... | Rust | 0 |
lastfg and not o_unicode_compat:
# Optimize stuff by using UPPER HALF BLOCK and leaving colors alone
# instead of swapping colors and using default char
# XXX: Guess what? yep, causes glitches in xfce4-terminal
ccfg, ccbg = ccbg, ccfg
u = True
if ccfg != lastfg:
tf.write(ctrl_fg(ccfg))
... | Python | 1 |
e_u64(z.to_bits()).await?;
input.write_u32(yaw.to_bits()).await?;
input.write_u32(pitch.to_bits()).await?;
input.write_u8(on_ground as u8).await?;
Ok(())
}
pub(super) async fn write_player_digging<I>(
input: &mut I,
status: u8,
x: i32,
y: i32,
... | Rust | 0 |
import logging
import sys
import textwrap
from typing import Any, Dict
import guidance
from guidance import gen, select, system, user, assistant
_logger = logging.getLogger(__file__)
_logger.setLevel(logging.INFO)
_logger.addHandler(logging.StreamHandler(stream=sys.stdout))
ANSWER_KEY = "string_choice"
COT_KEY = ... | Python | 1 |
Z0-9_\\-\\/\\.]+$",
),
]
class ListProcessesRequest(ObjectBodySchema):
"""
Schema for listing processes. This is used to list all the processes that are currently running.
"""
attributes = [
SchemaAttribute(
name="process_owner",
type_name=SchemaAttributeTyp... | Python | 1 |
ss, field, value)
}
}
/// **get** public [packageName](https://developer.android.com/reference/android/content/res/ObbInfo.html#packageName)
///
/// Required feature: java-lang-String
#[cfg(any(feature = "all", feature = "java-lang-String"))]
pub fn packageNa... | Rust | 0 |
es equally spaced points on the boundary of a polygon.
Body points are described in the paper "CHOMP: Covariant Hamiltonian optimization for motion planning"
"""
body_points = []
linear_ring = LinearRing(vertices) # Convert polygon to linear ring
perimeter = linear_ring.length
t = np.linspace... | Python | 1 |
#!/usr/bin/env PYTHONHASHSEED=1234 python3
import os
# ------------------------------------------------------------------------------
# program: waste memory
# ------------------------------------------------------------------------------
class MyObject:
def __init__(self):
self.data = os.urandom(100)... | Python | 1 |
F: FnOnce(&T) -> io::Result<R>,
{
// We don't hold state, so we can just call the function and
// return.
f(io)
}
}
cfg_neither_epoll_nor_kqueue! {
use crate::{Registry, Token, Interest};
#[cfg(windows)]
use std::os::windows::io::RawSocket;... | Rust | 0 |
tride_events_list, 100)
assert_frame_equal(t.parameters_, temporal_parameters)
def test_multiple_sensor(self, min_vel_stride_list) -> None:
"""Test calculate temporal parameters for multiple sensors , multiple strides for all sensors."""
stride_events_list1, temporal_parameters = min_vel_st... | Python | 1 |
FTPL"),
&("Finney", "FN", "FN"),
&("Fischer", "FXR", "FSKR"),
&("Fisher", "FXR", "FXR"),
&("Fisk", "FSK", "FSK"),
&("Fiske", "FSK", "FSK"),
&("Fletcher", "FLXR", "FLXR"),
&("Folger", "FLKR", "FLJR"),
&("Foliot", "FLT", "FLT"),
&("Folyot", "FLT", "FLT"),
&("Fones", "FNS", "FNS"),
... | Rust | 0 |
環境修復診斷")
print("=" * 60)
# 檢查結果
results = {
"tensorflow": check_tensorflow_environment(),
"mlflow_tf": check_mlflow_tensorflow(),
"training_pipeline": test_training_pipeline_imports(),
"model_governance": test_model_governance_imports(),
"basic_functionality": test_b... | Python | 1 |
ues {
d.dump_expr(expr);
}
});
}
fn dump_expr_dot(&mut self, expr: &ExprDotType) {
self.indent(|d| d.dump_expr(&expr.rhs));
dump!(self, "dot @ {} {}", expr.pos, expr.id);
self.indent(|d| d.dump_expr(&expr.lhs));
}
fn dump_expr_path(&mut self,... | Rust | 0 |
import os
from pathlib import Path
from jhack.conf.conf import check_destructive_commands_allowed
from jhack.helpers import JPopen
def unbork_juju(
model_name: str = "foo",
controller_name: str = "mk8scloud",
juju_channel: str = "stable",
microk8s_channel: str = "stable",
dry_run: bool = False,
)... | Python | 1 |
P::Param,
g1: P::Param,
g_prev: P::Param,
s1: P::Param,
s0_hat: P::Param,
s_history: P::Square,
s_hat_memory: P::Square,
y_tilde: P::Param,
ubar: F,
n_anderson: u64,
}
impl<F: FPFloat, P: FixedPointProblem<Float = F>> std::default::Default for Type1AndersonMixer<F, P>
where
P::... | Rust | 0 |
Co-author initials
initials: String,
/// The name of the co-author, in quotes, e.g. "<NAME>"
name: String,
/// The email of the co-author
email: String,
}
fn main() {
let opt = Opt::parse();
let mut authors = parse_coauthors_file().unwrap_or_default();
let new_author = Author {
... | Rust | 0 |
price.
/// Chunk coords of the pixel are calculated automatically.
/// Calculated chunk will be initialized if no pixel was ever bought on it.
///
/// The dispatch origin for this call must be `Signed` by the transactor.
pub fn purchase_pixel(origin, x: i64, y: i64, color: Colo... | Rust | 0 |
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
import numpy as np
import gc
import segpgd
#global fig_index
#fig_index = 0
criterion = nn.CrossEntropyLoss()
class_mapping = {
"road": 0,
"sidewalk": 1,
"building": 2,
"wall": 3,
"fence": 4,
"pole": 5... | Python | 1 |
array_mask: vec![true, false, true, false, false, true],
max_definition: 3,
level_type: LevelType::Struct(true),
offset: 0,
length: 6,
};
let c_levels =
b_levels.calculate_child_levels(c_offsets, c_mask, LevelType::Struct(true));
... | Rust | 0 |
from .scanobjectnn import ScanObjectNNHardest
| Python | 1 |
import board
from kmk.kmk_keyboard import KMKKeyboard as _KMKKeyboard
from kmk.modules.encoder import EncoderHandler
from kmk.quickpin.pro_micro.bitc_promicro import pinout as pins
from kmk.scanners import DiodeOrientation
# fmt:off
encoder_pinout = [
(pins[13], pins[14], None), # enc 0, button mapped in ... | Python | 1 |
) {
panic!("trampoline compilation should not produce constant relocs");
}
fn reloc_jt(
&mut self,
_offset: binemit::CodeOffset,
_reloc: binemit::Reloc,
_jt: ir::JumpTable,
) {
panic!("trampoline compilation should not produce jump table relocs");
}
}
... | Rust | 0 |
wire_node(
format!("{}-axis-{}", node.name, axis),
AxisOp::Add(axis),
&[wire],
)?[0];
}
Ok(tvec!(wire))
}
as_op!();
}
<reponame>GaiaWorld/pi_render
//! 定义 和 glsl 的 `std140` 布局 相匹配 的 类型 和 Trait
mod dynamic_uniform;
mod primitives;
mod ... | Rust | 0 |
inject(code)
elif c in "abcdefghijklmnopqrstuvwxyz":
# code = 97 + "abcdefghijklmnopqrstuvwxyz".index(c)
code = 4 + "abcdefghijklmnopqrstuvwxyz".index(c)
inject(code)
else:
raise Exception(
"inject_... | Python | 1 |
rc/agents.rs
use std::iter::IntoIterator;
use kappa::Agent;
use kappa::Site;
pub fn unit<R, SR>(registers: R) -> Agent
where
R: IntoIterator<Item = SR>,
SR: AsRef<str>,
{
let mut agent = agent!(UNIT(next[prev.UNIT]));
let mut site_prev = site!(prev[next.UNIT]);
let mut site_r = site!(r { _none })... | Rust | 0 |
self.ids.insert(spatial_entity.entity, item_id);
}
}
}
#[cfg(test)]
mod tests {
use crate::{
components::{BoundingBox, Space},
Point,
};
#[test]
fn space_should_resize() {
let mut space = Space::default();
assert_eq!(space.quadtree.bounding_box().ma... | Rust | 0 |
-> BoxFuture<'static, Result<Option<D>, Self::Error>> {
Box::pin(async move { Ok(self.map.lock().await.get(&chat_id).map(ToOwned::to_owned)) })
}
}
<reponame>replicante-io/replicante
use replictl::run;
fn main() {
let result = run();
let error = match result {
Err(error) => error,
... | Rust | 0 |
_datetime__': o.replace(microsecond=0).isoformat()}
# return {'__{}__'.format(o.__class__.__name__): o.__dict__}
# можно делать и по другому
# return o.replace(microsecond=0).isoformat()
# return [(k, v) for k, v in o.__dict__.items()]
complex = {
'a': a,
'when': datetime(2016, 3, 7),
'arg': 1,
}
# пе... | Python | 1 |
for uma in range (1,11,1):
for deez in range (10,uma,-1):
print(" ",end=" ")
for y in range (1,uma,1):
print("*",end=" ")
for y in range (1,uma,1):
print("*",end=" ")
print()
| Python | 1 |
"""Helper utility functions."""
import json
import uuid
from datetime import datetime
from typing import Any, Dict, Optional
def generate_uuid() -> str:
"""Generate a UUID string."""
return str(uuid.uuid4())
def get_current_timestamp() -> str:
"""Get current timestamp as ISO string."""
return datet... | Python | 1 |
23 => START_SRCR::AUXIO23,
22 => START_SRCR::AUXIO22,
21 => START_SRCR::AUXIO21,
20 => START_SRCR::AUXIO20,
19 => START_SRCR::AUXIO19,
18 => START_SRCR::AUXIO18,
17 => START_SRCR::AUXIO17,
16 => START_SRCR::AUXIO16,
1... | Rust | 0 |
msg or not isinstance(msg['data'], basestring):
print msg
continue
data = msg['data']
# data = aes.decrypt(data)
os.write(self.tun_fd, data)
class ServerWriter(Writer):
server_all_config = {}
def __init__(self, start_ip="10.1.0.1"):
... | Python | 1 |
me() - start_time
# --- Verification ---
final_result = w.result.final
assert final_result["status"] == "complete"
output_path = final_result["output_path"]
with open(output_path, "r", encoding="utf-8") as f:
transformed_data = json.load(f)
num_records_in_source = len(w.result["extrac... | Python | 1 |
import sensor, time, nn, image, os
sensor.reset() # Reset and initialize the sensor.
sensor.set_contrast(3)
sensor.set_pixformat(sensor.RGB565) # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240)
sensor.set_windowing((128, ... | Python | 1 |
KLINES[0] = ' #%d; clk = 0;\n' % Diff1
if CURRENT[0] == '':
CURRENT[0] = CLKLINES[0]
CURRENT[1] = CLKLINES[1]
CURRENT[2] = 1
elif (CURRENT[0] == CLKLINES[0] ) and (CURRENT[1] == CLKLINES[1]):
CURRENT[2] += 1
elif (CURRENT[2] == 1):
Fout2.write(CLKLINES[1])
... | Python | 1 |
println!("log(2)={}", f128::f128::from(2).log());
println!("log(3)={}", f128::f128::from(3).log());
println!("log(100)={}", f128::f128::from(100).log());
println!("exp(1)={}", f128::f128::from(1).exp());
println!("exp(2)={}", f128::f128::from(2).exp());
println!("exp(-1)={}", f128::f128::from(-1).ex... | Rust | 0 |
s GraphSpace(Grammar):
Start = Start()
End = End()
def __init__(self, graph: Graph, initializer=None):
self.graph = graph
self.initializer = initializer or default_initializer
@property
def _start(self):
return [GraphSpace.Start]
def _sample(self, symbol, max_iteration... | Python | 1 |
+ 8) * px_size)) # 获取原始头颅装饰部分
base_canvas = Image.new("RGBA", # 新建空白基础画布, 8(基础大小) *px_size(头颅大小) * wear_scale(全头大小)
(final_size, final_size),
(0, 0, 0, 0))
scaled_head = head.resize((target_size, target_size), Image.Resampling.BOX)
base_canvas.past... | Python | 1 |
ng,
/// When the email forward was created in DNSimple.
pub created_at: String,
/// Then the email forward was last updated in DNSimple.
pub updated_at: String,
}
/// The payload used to create an email forward
#[derive(Debug, Deserialize, Serialize)]
pub struct EmailForwardPayload {
/// The alias... | Rust | 0 |
)]
mod test {
use kvm_bindings::kvm_cpuid_entry2;
use super::*;
use crate::cpuid::transformer::VmSpec;
#[test]
fn test_update_perf_mon_entry() {
use crate::cpuid::cpu_leaf::leaf_0xa::*;
// Test when vpmu is off (level Disabled)
let vm_spec =
VmSpec::new(0, 1, 1,... | Rust | 0 |
FromT<T>
where
T: std::fmt::Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "From({})", self.0)
}
}
pub(super) type FromValue = FromT<Value>;
pub(super) type FromBlock = FromT<Block>;
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct ToT... | Rust | 0 |
from setuptools import setup, Extension
import setuptools
from Cython.Build import cythonize
import numpy
import os
# os.environ['CC'] = 'clang-cl' # following is for compilation with clang
# os.environ['LDSHARED'] = 'clang -shared'
# os.environ['CXX'] = 'clang++'
include = [numpy.get_include()]
cd = {'language_level'... | Python | 1 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def goodNodes(self, root: TreeNode) -> int:
# since we have to calculate the number of good nodes, w... | Python | 1 |
name="test account",
type="ASSET",
commodity=EUR,
parent=racc,
children=[Account(name="test sub-account", type="ASSET", commodity=EUR)],
)
new_book.flush()
assert len(acc.children) == 1
def test_create_unicodename_account(self, new_... | Python | 1 |
self) -> Result<Vec<u8>, FromBase58Error> {
decode_from_base58(self)
}
fn from_mls_b58check(&self, prefix: Option<Vec<u8>>) -> Result<Vec<u8>, FromBase58Error> {
let mut payload: Vec<u8> = self.from_base58()?;
if payload.len() < 5 {
return Err(FromBase58Error::InvalidChecksu... | Rust | 0 |
print(f"{Fore.RED}Unknown step type: {step_type}. Skipping.{Style.RESET_ALL}")
continue
# Ask if the user wants to continue with the next steps
continue_plan = input(f"{Fore.YELLOW}Continue with the next steps? (y/n): {Style.RESET_ALL}")
if continue_plan.lower() != ... | Python | 1 |
te_encoded<W: io::Write>(
&self,
_: Mode,
target: &mut W
) -> Result<(), io::Error> {
if *self == 0 {
target.write_all(&[0x00])?;
}
else if *self == -1 {
target.write_all(&... | Rust | 0 |
from pipeline import parse_args, generate_long_sentence
if __name__ == "__main__":
# data = pd.read_csv("sentences_50agree/train.csv")
args = parse_args()
print(args)
if not args.is_terminal_args:
print("Not Terminal Args")
for c_size in range(8, 11):
for lbl in range(1,2):
... | Python | 1 |
'''
Source codes for Python Machine Learning By Example 3rd Edition (Packt Publishing)
Chapter 14 Making Decision in Complex Environments with Reinforcement Learning
Author: Yuxi (Hayden) Liu (yuxi.liu.ece@gmail.com)
'''
import torch
import gym
env = gym.make('FrozenLake-v0')
gamma = 0.99
threshold = 0.0001
def v... | Python | 1 |
et mut rng = rand::thread_rng();
let a: Column<f32, U3> = [3.0 + rng.gen::<f32>(), 4.0 + rng.gen::<f32>(), 0.0]
.iter()
.map(Clone::clone)
.collect();
let b: Column<f32, U3> = [-3.0 + rng.gen::<f32>(), 4.0 + rng.gen::<f32>(), 0.0]
.iter()
.map(... | Rust | 0 |
nAt>,
) -> Result<Output>
where
FOpen: FnMut(OsString, i32) -> (),
FOpenAt: FnMut(i32, OsString, i32) -> (),
{
use nix::sys::signal::Signal;
use nix::sys::wait::WaitStatus;
let child_pid = nix::unistd::Pid::from_raw(self.id() as i32);
match nix::sys::wait::w... | Rust | 0 |
nsectors = (image.seek(SeekFrom::End(0)).unwrap() as u64) / SECTOR_SIZE;
let mut config = virtio_blk_config::default();
config.capacity = nsectors;
config.blk_size = BLK_SIZE;
config.size_max = 65535;
config.seg_max = 128 - 2;
config.min_io_size = 1;
config.opt_... | Rust | 0 |
import os
import numpy as np
from single_api import CDP
from source import eval_cluster
# params
metric = 'cosinesimil' # supported: 'cosinesimil', 'l1', 'l2', 'linf', 'angulardist', 'bit_hamming'
th_dict = {'cosinesimil': 0.54, 'l1': 0.2, 'l2': 0.2, 'angulardist': 0.35} # reference threshold for face data
th = th_di... | Python | 1 |
Vec<_>>();
assert_eq!(
testing, expected,
"{} test for testcase ({:?}, {:?}) failed.",
$name, input, words
)
};
}
// test forward word boundaries
assert_!(
WordBounds::new(input),... | Rust | 0 |
vec![]);
}
fn test_error_recovery_spans(input: &str, error_span: &str, output: &str) {
let mut errors = vec![];
let result = util::test_err_gen(
|v| error_recovery_span::ExprParser::new().parse(&mut errors, v),
input,
)
.unwrap();
assert_eq!(result, output);
// The "span loc... | Rust | 0 |
("article_view")
.full_height()
.scrollable(),
),
);
});
log::info!("Added the article_view to the article_layout");
// does this article have a table of contents?
if parsed_article.toc.is_some() {
log::info!("The article contains a ta... | Rust | 0 |
84197.0;
# }
```
* Literals cannot be stored in a type too small to hold them
```compile_fail
# use polymorphic_constant::polymorphic_constant;
# polymorphic_constant! {
const FAILS: u64 | nz_i8 = 128;
# }
```
* Negative numbers cannot be stored in unsigned types
```compile_fail
# use... | Rust | 0 |
=> Ok(Self::Absolute),
value => Err(format!(
"invalid metric kind {}, metric kind must be `absolute` or `incremental`",
value
)),
}
}
}
#[cfg(feature = "vrl")]
impl From<MetricKind> for ::value::Value {
fn from(kind: MetricKind) -> Self {
... | Rust | 0 |
import datetime
import pytz
from database.operation import insert_kline, insert_ticker
from logic.fibo import fibo_retracement
from logic.sharp import sharp_finder
from project_types.types import Kline, Tick
def ticker_format(message: dict) -> Tick:
candle = message['k']
return Tick(_id=datetime.datetime.from... | Python | 1 |
};
use std::os::unix::fs::MetadataExt;
use std::collections::BTreeSet;
use time::{Duration, get_time};
use glob::glob;
static KNOWN_STAMPS: [&'static str; 6] = ["/var/lib/systemd/timers/stamp-cron-daily.timer",
"/var/lib/systemd/timers/stamp-cron-weekly.timer",
... | Rust | 0 |
}
/// get the blob contents of a given sha
/// https://developer.github.com/v3/git/blobs/#get-a-blob
pub fn blob<S>(&self, sha: S) -> Result<Blob>
where
S: Into<String>,
{
self.github.get::<Blob>(
&self.path(format!("/blobs/{}", sha.into())),
)
}
//... | Rust | 0 |
"""
Main runner script for weight graph embedding experiments.
"""
import os
import sys
import argparse
import subprocess
import logging
def setup_logging():
"""Set up logging to file and console."""
os.makedirs('logs', exist_ok=True)
log_file = os.path.join('logs', 'runner.log')
# Configure logg... | Python | 1 |
OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWI... | Rust | 0 |
}
}
#[doc = "Reader of field `CHSEL2`"]
pub type CHSEL2_R = crate::R<u8, CHSEL2_A>;
impl CHSEL2_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, CHSEL2_A> {
use crate::Variant::*;
match self.bits {
0 => Val(CHSEL2_A:... | Rust | 0 |
Callable[
[compute.PatchPerInstanceConfigsInstanceGroupManagerRequest],
Union[compute.Operation, Awaitable[compute.Operation]],
]:
raise NotImplementedError()
@property
def recreate_instances(
self,
) -> Callable[
[compute.RecreateInstancesInstanceGroupManagerRe... | Python | 1 |
(),
hash_type: "type".to_string(),
}),
..CachedCell::default()
},
CachedCell {
out_point: Some({
OutPoint {
tx_hash:
"0x67b35360a09ecbdaf7cef55bb9b58b194d1e... | Rust | 0 |
T::AccountId, amount: BalanceOf<T>) -> Result<(), Error> {
ensure!(
T::DOT::reserved_balance(&sender) >= amount,
Error::InsufficientCollateralAvailable
);
T::DOT::unreserve(sender, amount);
Self::decrease_total_collateral(amount);
Self::deposit_event(Raw... | Rust | 0 |
b"user.xattr_toobig").unwrap();
if request.name() == xattr_small {
let mut resp = fuse::GetxattrResponse::new(request.size());
return match resp.try_set_value(b"small xattr value") {
Ok(_) => send_reply.ok(&resp).unwrap(),
Err(_) => {
// TODO: error should either have enough public info to let the... | Rust | 0 |
acts
contacts = {}
# Process each message to extract contacts
for msg_data in messages:
msg_id = msg_data.get("id")
if not msg_id:
continue
# Fetch full message details
msg_params = {"message_id": msg_id}
msg_result = ... | Python | 1 |
,
Decr { var_name: String }
}
#[derive(Debug, Eq, PartialEq)]
pub struct InteractiveProgram {
pub program: Vec<Ast>,
pub inputs: Vec<String>,
pub output: String
}
impl Display for Ast {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
match self {
Decr { var_name } =... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Example solutions for Worksheet 1
Ian Hawke
"""
def MatrixConditionCheck(A):
import numpy as np
MaxConditionNumber = 10 # This is absurdly low
ConditionNumber = np.linalg.cond(A)
if ConditionNumber > MaxConditionNumber:
print "Condition number of matrix\n", A, ... | Python | 1 |
'''
Offline utility tests
'''
from unittest import TestCase
from scutils.argparse_helper import ArgparseHelper
import argparse
from mock import MagicMock
import sys
# from http://stackoverflow.com/questions/4219717/how-to-assert-output-with-nosetest-unittest-in-python
from contextlib import contextmanager
try:
fro... | Python | 1 |
: bool,
/// True, if a chat message draft should be deleted
clear_draft: bool,
}
impl RObject for InputMessageText {
#[doc(hidden)]
fn extra(&self) -> Option<&str> {
self.extra.as_deref()
}
#[doc(hidden)]
fn client_id(&self) -> Option<i32> {
self.client_id
}
}
impl TDIn... | Rust | 0 |
import firebase_admin
from firebase_admin import credentials, storage, firestore, auth
cred = credentials.Certificate("firebase_config/private.json")
# cred = credentials.Certificate("private.json")
if not firebase_admin._apps:
firebase_admin.initialize_app(cred, {'storageBucket': 'sheriai.appspot.com'})
bucket =... | Python | 1 |
marks1 = int(input("enter the marks: "))
marks2 = int(input("enter the marks: "))
marks3 = int(input("enter the marks: "))
total_percentage = ((100) * (marks1 + marks2 + marks3))/300
if(total_percentage >= 40 and marks1 >= 33 and marks2 >= 33 and marks3 >= 33):
print("You are pass")
else:
("You failed!")
... | Python | 1 |
import brownie
import pytest
pytestmark = pytest.mark.usefixtures("mint_bob", "approve_zap")
def test_lp_token_balances(
bob, zap, swap, pool_token, base_pool_token, initial_amounts_underlying, base_amount, n_coins
):
zap.add_liquidity(initial_amounts_underlying, 0, {"from": bob})
assert 0.9999 < pool_t... | Python | 1 |
import os
import requests
from dotenv import load_dotenv
from flask import Flask, request, jsonify, render_template
from flask_cors import cross_origin
from celery import Celery
import openai
app = Flask(__name__)
load_dotenv()
# Configure Celery here we use radis
app.config['CELERY_BROKER_URL'] = os.getenv('CELERY_... | Python | 1 |
from shiny import App, Inputs, Outputs, Session, reactive, ui, render
import pandas as pd
import matplotlib.pyplot as plt
import plotly.express as px
# Definindo o layout da aplicação
app_ui = ui.page_fluid(
ui.h2("Minha Aplicação Shiny em Python"),
# Layout com sidebar em vez de layout_sidebar
ui.row... | Python | 1 |
p();
tmp.square();
let value = evaluate_at_consequitive_powers(&poly, tmp, point);
// evaluate f(z)
poly[4] = value;
poly[4].negate();
// f(x) - f(z)
let opening = polynomial_commitment_opening(4, 2, poly.iter(), point, &srs);
// e(W , hα x )e(g^{v} * W{-z} , hα ) = e(F , h^{x^{−d +max... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.