text string | label_name string | labels int64 |
|---|---|---|
}
if x <= 0 && x.abs() >= y.abs() {
if dy > -7 {
addy = -1;
if dx > 0 {addx = -1;}
}
}
if y >= 0 && y.abs() >= x.abs() {
if dx > -7 {
addx = -1;
if dy < 0 {addy = 1;}
}
}
if y <= 0 && y.abs() >= x.abs() {
if dx < 7 {
addx = 1;
if dy > 0 {addy = -1;}
... | Rust | 0 |
import pytest
from open_rarity.resolver.rarity_providers.rank_resolver import RankResolver
from open_rarity.resolver.rarity_providers.rarity_sniffer import RaritySnifferResolver
class TestRaritySnifferResolver:
BORED_APE_COLLECTION_ADDRESS = "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d"
@pytest.mark.skipif(
... | Python | 1 |
position
const TABLE_END: u32 = 0x1f6ff;
// blank char
const BLANK_CHAR: char = ' ';
// next line char
const NEXT_LINE_CHAR: char = '\n';
// mask number of new line
const NEXT_LINE_MASK: u32 = 0x0f;
// defined struct of `emoji`
#[derive(Debug)]
pub struct Emoji<T> {
// start position
start: T,
// end position
end... | Rust | 0 |
� ⟨consequent⟩)
///
/// If has a few special rules:
/// * The consequent and alternate expressions may only be evaluated if their
/// branch is chosen.
/// * If test yields false without an alternate, the result is unspecified. Marwood
/// will evaluate the `if` expression to #<void>
///... | Rust | 0 |
restriction: @mut restriction,
quote_depth: @mut uint, // not (yet) related to the quasiquoter
reader: @reader,
interner: @token::ident_interner,
keywords: LinearSet<~str>,
strict_keywords: LinearSet<~str>,
reserved_keywords: LinearSet<~str>,
/// The set of seen errors about obsolete sy... | Rust | 0 |
pitch_cond += self.base_pitch_embed(base_pitch[:, :, None])
if infer:
pitch_pred_out = self.pitch_predictor(pitch_cond, infer=True)
else:
pitch_pred_out = self.pitch_predictor(pitch_cond, pitch - base_pitch, infer=False)
else:
pitch_p... | Python | 1 |
from langchain_community.vectorstores.scann import (
ScaNN,
)
__all__ = ["ScaNN"]
| Python | 1 |
CapData_new(guard, guard_size) })
}
pub fn skip(guard_size: u64) -> Self {
Self::new(0, guard_size)
}
}
#[derive(Debug, Copy, Clone)]
pub struct VMAttributes(sys::seL4_ARM_VMAttributes);
impl VMAttributes {
pub const NONE: Self = Self(0);
pub const PAGE_CACHEABLE: Self = Self(sys::seL4_AR... | Rust | 0 |
Input<MouseButton>>) {
if mouse_button_input.pressed(MouseButton::Left) {
println!("left mouse currently pressed");
}
if mouse_button_input.just_pressed(MouseButton::Left) {
println!("left mouse just pressed");
}
if mouse_button_input.just_released(MouseButton::Left) {
prin... | Rust | 0 |
from .processor import *
class THUCNews(CLSProcessor):
"""
@inproceedings{sun2016THUCNews,
title={THUCTC: An Efficient Chinese Text Classifier},
author={Maosong Sun, Jingyang Li, Zhipeng Guo, Yu Zhao, Yabin Zheng, Xiance Si, Zhiyuan Liu},
year={2016}
}
"""
def __init__(self):
su... | Python | 1 |
ATEREPOSITORY_E_BUSY_RECOVERY_RETRY
/// A table in the database is locked. The request will be retried.
pub const E_LOCKED_RETRY : HResultError = HResultError::from_constant(0x80670009); // STATEREPOSITORY_E_LOCKED_RETRY
/// The shared cache for the database is locked by another connection. The request will be retrie... | Rust | 0 |
$1
WHERE board = $2 AND no = $3
RETURNING *
",
deleted_time,
board,
no
).fetch_optional(&self.pool)
.await?;
Ok(post)
}
pub async fn set_missing_posts_deleted(&self, board: &String, thread_no: i64, current_posts: Ve... | Rust | 0 |
;
let mut j = 0;
unsafe {
j = iauUt1utc(2453750.5, 0.892104561, 64.8499, &mut t1, &mut t2);
}
abs_diff_eq!(t1, 2453750.5, epsilon=1e-6);
abs_diff_eq!(t2, 0.8928551385462962963, epsilon=1e-12);
assert_eq!(j, 0);
}
#[test]
fn test_ut1utc() {
... | Rust | 0 |
Ok(self.memory.as_values(self.idx, offset, values.len()))
}
}
fn assign_output<'output>(
&mut self,
output: Output<'output>,
value: *mut jl_value_t,
_: Internal,
) -> Value<'output, 'static> {
unsafe { self.memory.protec... | Rust | 0 |
r"""使能BFD多跳,0:未开启,2-255:BFD跳数
:rtype: int
"""
return self._EnableBfdMultiHop
@EnableBfdMultiHop.setter
def EnableBfdMultiHop(self, EnableBfdMultiHop):
self._EnableBfdMultiHop = EnableBfdMultiHop
@property
def ProbeFailedTimes(self):
r"""健康检查次数
:rtype... | Python | 1 |
const xed_union64_t__bindgen_ty_1 ) ) . b3 as *
const _ as usize } , 3usize , concat ! (
"Alignment of field: " , stringify ! (
xed_union64_t__bindgen_ty_1 ) , "::" , stringify ! ( b3 ) ));
assert_eq! (unsafe {
& ( * ( 0 as * const xed_union64_t__bind... | Rust | 0 |
ATE>
where
STATE: StateTypes,
STATE::Confidential: PartialEq + Eq,
STATE::Confidential:
From<<STATE::Revealed as CommitConceal>::ConcealedCommitment>,
{
fn strict_decode<D: io::Read>(mut d: D) -> Result<Self, Error> {
let format = u8::strict_decode(&mut d)... | Rust | 0 |
array that borrows just one of the channels.
//! let mut dst = Array3x1::fill(extent, 0.0);
//! let src = array.borrow_channels(|(_id, dist)| dist);
//! copy_extent(&extent, &src, &mut dst);
//! ```
mod coords;
mod indexer;
pub mod channels;
pub mod compression;
#[macro_use]
pub mod for_each;
#[cfg(feature = "dot_v... | Rust | 0 |
number of bytes that encoded.
///
/// Note:
/// - VarInt encoding is slow, try avoid using it.
/// - The buffer must reserve 10 bytes for writing, although actual written bytes may be less.
/// - The buffer will be advanced by actual written bytes.
///
/// # Errors
///
/// Returns `... | Rust | 0 |
cene_data: game_type.Scene = cache.scene_data[target_scene_path_str]
target_scene_name = target_scene_data.scene_name
for chara_id in target_scene_data.character_list:
if chara_id:
tar_random_chara_name = cache.character_data[chara_id].name
break
# 地点角色
... | Python | 1 |
# Copyright 2022 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | Python | 1 |
from policyengine_us.model_api import *
class me_property_tax_fairness_credit_countable_rent(Variable):
value_type = float
entity = TaxUnit
unit = USD
label = "Countable rent for Maine property tax fairness credit"
definition_period = YEAR
defined_for = StateCode.ME
reference = "https://ww... | Python | 1 |
= Boss.name
)",
),
(5, "SELECT name FROM Boss WHERE +1 = 1"),
(3, "SELECT id FROM Hunter WHERE -1 = -1"),
(5, "SELECT name FROM Boss WHERE -2.0 < -1.0"),
(3, "SELECT id FROM Hunter WHERE +2 > +1.0"),
(2, "SELECT name FROM Boss WHERE id <= +2"),
(2, "... | Rust | 0 |
import pytest
import importlib
def test_compat_warn():
with pytest.warns(DeprecationWarning):
# something else is importing this,
import cytoolz.compatibility
# reload to be sure we warn
importlib.reload(cytoolz.compatibility)
| Python | 1 |
}
}
pub fn add_tokens(&mut self, add: Balance) {
match add {
Balance::Native(balance) => {
for token in balance.0 {
let index = self.native.iter().enumerate().find_map(|(i, exist)| {
if exist.denom == token.denom {
... | Rust | 0 |
iter.value(), "{} case", j);
r.block_on(iter.next());
}
assert!(!iter.valid());
}
fn test_switch_memtable_and_wal() {
let dir = tempfile::Builder::new()
.prefix("test_switch_memtable_and_wal")
.tempdir()
.unwrap();
let r = Runtime... | Rust | 0 |
gc>,
fn_proto: Object<'gc>,
) -> Object<'gc> {
let object = ScriptObject::object(gc_context, Some(proto));
display_object::define_display_object_proto(gc_context, object, fn_proto);
define_properties_on(PROTO_DECLS, gc_context, object, fn_proto);
object.into()
}
pub fn password<'gc>(
this: EditT... | Rust | 0 |
def solve(grid):
h=len(grid); w=len(grid[0])
count5=[sum(1 for r in range(h) if grid[r][c]==5) for c in range(w)]
blank_cols=[c for c in range(w) if count5[c]==0]
if blank_cols:
inter=[c for c in blank_cols if 0<c<w-1]
c=inter[0] if inter else blank_cols[0]
if c>0 and count5[c-1]... | Python | 1 |
(line);
}
Ok(dictionary)
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_read_key() -> io::Result<()> {
async fn t(mut reader: &[u8], expected: Key) -> io::Result<()> {
let actual = read_key(&mut reader).await?;
assert_eq!(actual, expected);
... | Rust | 0 |
"GSS_UNKNOWN_MESSAGE",
_ => {
return (auth_status).to_string();
},
}.to_string()
}
pub const NFSPROC4_NULL: u32 = 0;
pub const NFSPROC4_COMPOUND: u32 = 1;
/* ops */
pub const NFSPROC4_ACCESS: u32 = 3;
pub const NFSPROC4_CLOSE: u32 = ... | Rust | 0 |
}
}
fn build_union(cx: &DocContext<'_>, did: DefId) -> clean::Union {
let predicates = cx.tcx.explicit_predicates_of(did);
let variant = cx.tcx.adt_def(did).non_enum_variant();
clean::Union {
struct_type: doctree::Plain,
generics: (cx.tcx.generics_of(did), predicates).clean(cx),
... | Rust | 0 |
fmt::Formatter) -> ::std::fmt::Result {
f.debug_struct(&format!("GESVideoSourceClass_ABI_abi @ {:p}", self))
.field(
"disable_scale_in_compositor",
&self.disable_scale_in_compositor,
)
.field("needs_converters", &self.needs_converters)
... | Rust | 0 |
r]
class BertEvalDataset(data_utils.Dataset):
def __init__(self, u2seq, u2answer, max_len, mask_token, negative_samples):
self.u2seq = u2seq
self.users = sorted(self.u2seq.keys())
self.u2answer = u2answer
self.max_len = max_len
self.mask_token = mask_token
self.neg... | Python | 1 |
(status_code=500, detail=f"Error: {str(e)}")
@router.delete("/unfollow/{target_user_id}", tags=["Follow"])
async def unfollow_user(
target_user_id: str,
current_user: dict = Depends(get_current_user)
):
"""
Unfollow a user.
"""
try:
follower_id = current_user["sub"]
# Dele... | Python | 1 |
import os
import time
import sys
from collections import deque
class Queue:
def __init__(self):
self.queue = deque()
def enqueue(self, data):
self.queue.append(data)
def dequeue(self):
if self.queue:
return self.queue.popleft()
return None
# MergeSort the ... | Python | 1 |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flask_cors import CORS
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
db = SQLAlchemy()
jwt = JWTManager()
def create_app():
app = Flask(__name__)
# Configu... | Python | 1 |
, client).unwrap();
rt.block_on(healthcheck).unwrap_err();
}
#[test]
fn influxdb1_healthchecks_ok() {
let mut rt = runtime();
let cx = SinkContext::new_test();
let endpoint = "http://localhost:8086".to_string();
let influxdb1_settings = Some(InfluxDB1Settings {
... | Rust | 0 |
'llm_processed': True,
'llm_model': 'local',
'success': True
}
except Exception as e:
return {
'error': f'Ошибка локальной LLM: {str(e)}',
'success': False,
'llm_processed': False
}
def _mock_llm_response(text: str)... | Python | 1 |
ern crate actix_files;
extern crate console;
use actix_files as fs;
use actix_web::{App, HttpServer, middleware};
use console::Style;
const PORT: &str = "127.0.0.1:8088";
pub fn main() {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
let blue = Style::new()
.blue();
p... | Rust | 0 |
ry_from(supply)?,
manage_contract: protocol_primitive::ContractAddress::try_from(manage_contract)?,
storage_root: protocol_primitive::MerkleRoot::try_from(storage_root)?,
};
Ok(asset)
}
}
// Fee
impl From<protocol_primitive::Fee> for Fee {
fn from(fee: protocol_prim... | Rust | 0 |
unning":
print("WARNING: no results tarball for",
entry,
file=sys.stderr)
k = "hardcoded address"
additional_headers.add(k)
r[k] = addr_count
csv_entries.append(r)
print(".", end="", flush=True)
print()
csv_header_fie... | Python | 1 |
Some(Box::new(1_u64)),
);
let arg3 = Arg::new(
"intarg",
"an int",
ArgType::Kwarg,
std::any::type_name::<i64>(),
Collection::Unit,
Some(Box::new(1_i64)),
);
let arg4 = Arg::new(
"floatarg",
... | Rust | 0 |
e,
away_team="測試龍",
status="已完成",
)
game2 = models.GameResultDB(
game_date=datetime.date(2025, 4, 2),
home_team="測試獅",
away_team=team_name,
status="已完成",
)
game3 = models.GameResultDB(
game_date=datetime.date(2025, 4, 3),
home_team=team_nam... | Python | 1 |
"""
@FileName: Resampler.py
@Description: Implement Resampler
@Author: Ryuk
@CreateDate: 2020/11/03
@LastEditTime: 2020/11/03
@LastEditors: Please set LastEditors
@Version: v0.1
"""
import soundfile as sf
import librosa
from Algorithm import *
import time
upsample_sr = 32000
downsample_sr = 8000
sr = 16000
w = 2
data... | Python | 1 |
members[0].fitness - 1.0 < f64::EPSILON);
// should have averaged fitness
assert!(runtime.species[0].fitness - 1.5 < f64::EPSILON); */
}
#[test]
fn run_neat_till_10_connections() {
fn fitness_function(genome: &Genome) -> Progress {
let fitness = genome.feed_forward.len()... | Rust | 0 |
import json
import os
import sys
from utils import dict_product, generate_configs, generate_shell_script, iwt
with open("../src/ILfD_base.json") as f:
BASE_CONFIG = json.load(f)
PARAMS = {
"game": ["window-open-v2"],
"mode": ["adv_ilfd"],
"out_dir": ["experiments/attack_vanilla_ppo_ilfd/window-open-v... | Python | 1 |
(&[
// Instrumentation
0x01, 0x00, //
// GTS1
0x94, 0x7f, //
// Instrumentation
0x01, 0x00, //
// GTS1
0x94, 0xff, 0x7f, //
// Instrumentation
0x01, 0x00, //
// GTS1
0x94, 0xff... | Rust | 0 |
Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse ... | Rust | 0 |
ock_comment(input)?;
Ok((input, (&s[3..s.len() - 2], true)))
} else if input.starts_with("///") {
let input = input.advance(3);
if input.starts_with("/") {
return Err(LexError);
}
let (input, s) = take_until_newline_or_eof(input);
Ok((input, (s, false)))
... | Rust | 0 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
async fn handler(
args: &mut Arguments<'_>,
msg: &MessageCreate,
http: &HttpClient,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let response = match args.next() {
Some(command) => describe_command(command),
None => {
Ok("List of available commands \n**jisho**: Search Jisho f... | Rust | 0 |
=> "LIST_FRAGMENTS",
ApiName::PutMedia => "PUT_MEDIA",
ApiName::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"GET_CLIP",
"GET_DASH_STREAMING_SESSION_URL",
... | Rust | 0 |
Err(err) => panic!("problem: {:?}", err),
}
};
unsafe {
cmd_buffer.begin_primary(command::CommandBufferFlags::ONE_TIME_SUBMIT);
{
cmd_buffer.begin_render_pass(
&rende... | Rust | 0 |
op of page
gammas = [i / 10.0 for i in range(1, 31)] # [0.1 ... 3.0]
gammas_len = len(gammas)
for i, c in enumerate(rgba_combos_Color_generator()):
gamma = gammas[i % gammas_len]
corrected = pygame.Color(*[gamma_correct(x, gamma)
... | Python | 1 |
.TimeAsVectorOn()
reader2.Update()
diff = vtkImageMathematics()
diff.SetOperationToSubtract()
diff.SetInputConnection(0,reader.GetOutputPort())
diff.SetInputConnection(1,reader2.GetOutputPort())
diff.Update()
diffrange = diff.GetOutput().GetScalarRange()
differr = diffrange[0]**2 + diff... | Python | 1 |
reponame>coreylowman/stag
use crate::prelude::*;
use rand::Rng;
use rand_distr::Standard;
/// Randomly drops out elements from `t` with probability `p`, and multiplies all elements by `1 / (1 - p)`.
///
/// If the `t: T` passed in does **not** have a tape, then no dropout is applied. See [Tape::OWNS_TAPE].
///
/// Des... | Rust | 0 |
import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.functional as F
from torch.autograd import Variable
from TextCNN1 import TextCNN1
from utils import load_model
class Boost_CNN5(nn.Module):
def __init__(self, embed_mat, opt):
super(Boost_CNN5, self).__init__()
se... | Python | 1 |
"""
Qtile plugin that allows a moving floating window's borders
to snap to other windows' borders and screen borders.
Usage:
1. Put this file in the same folder as the Qtile config.py file
usually ~/.config/qtile/
2. In config put:
from floating_window_snapping import move_snap_window
...
mouse = [
Drag([mod], "Bu... | Python | 1 |
result = _simulate_long_run(
# Test of completely overlapping rules.
# Hourly 3 snaps takes precedence over 2-hourly 1 snap.
rules={"2 hour": 1, "1 hour": 3},
how_long_to_run=datetime.timedelta(hours=6),
)
self.assertEqual(
result,
... | Python | 1 |
}" (*in_out_mr2),
"{r9}" (*in_out_mr3),
"{r15}" (*in_out_mr4),
"{rdi}" (dest)
: "memory", "rcx", "rbx", "r11"
: "volatile");
}
#[inline(always)]
unsafe fn x64_sys_null(sys: seL4_Word) {
asm!("movq %rsp, %rbx
syscall
movq %rbx, %rsp"
... | Rust | 0 |
em'), ('Africa/Dar_es_Salaam', 'Africa/Dar_es_Salaam'), ('America/Louisville', 'America/Louisville'), ('America/Edmonton', 'America/Edmonton'), ('America/Fortaleza', 'America/Fortaleza'), ('Asia/Amman', 'Asia/Amman'), ('Asia/Urumqi', 'Asia/Urumqi'), ('America/Virgin', 'America/Virgin'), ('America/Buenos_Aires', 'Americ... | Python | 1 |
}
}
#[no_mangle]
extern "C" fn m_trap_handler(
epc: usize,
tval: usize,
cause: usize,
hart: usize,
_status: usize,
frame: &mut TrapFrame,
) -> usize {
let is_async = cause >> 63 & 1 == 1;
// The cause contains the type of trap (sync, async) as well as the cause
// number. So, here w... | Rust | 0 |
_num):
terrain.height_field_raw[xs[i]:xs[i]+obst_size, ys[i]:ys[i]+obst_size] = -max_height / terrain.vertical_scale
def maze_terrain_func(self, terrain, difficulty):
terrain.height_field_raw[:] = 1.0 / terrain.vertical_scale
path_width = int((1.61 - difficulty * 1.0) / terrain.horizont... | Python | 1 |
int,
inputs: StdTemplateInputs) -> List[Context]:
image_context = super().replace_tag('image', index, inputs)
if media_type == 'image':
return image_context
elif media_type == 'video':
video_segments = get_env_args('video_segments', int, self.video_seg... | Python | 1 |
{union INPUT_RECORD_Event {
[u32; 4],
KeyEvent KeyEvent_mut: KEY_EVENT_RECORD,
MouseEvent MouseEvent_mut: MOUSE_EVENT_RECORD,
WindowBufferSizeEvent WindowBufferSizeEvent_mut: WINDOW_BUFFER_SIZE_RECORD,
MenuEvent MenuEvent_mut: MENU_EVENT_RECORD,
FocusEvent FocusEvent_mut: FOCUS_EVENT_RECORD,
}}
... | Rust | 0 |
fn setnc_7() {
run_test(&Instruction { mnemonic: Mnemonic::SETNC, operand1: Some(Direct(CL)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 147, 193], OperandSize::Qword)
}
fn setnc_8() {
run_test(&Instruct... | Rust | 0 |
ence is
// used to store the closure, request the first frame, and then is dropped
// by this function.
//
// Inside the closure we've got a persistent `Rc` reference, which we use
// for all future iterations of the loop
let f = Rc::new(RefCell::new(None));
let g = f.clone();
let mut i... | Rust | 0 |
module_version($v);
};
(@field $b:ident commands { $($ident:expr => [$($ip:ty),* $(,)*] => $op:ty),* $(,)* }) => {
let mut commands = $b.init_commands(module_metadata!(@count $($ident),*));
module_metadata!(@commands commands 0; $($ident => [$($ip),*] => $op),* ,);
};
// Count
(@co... | Rust | 0 |
Response = MyResponse;
type UserState = MyGraphState;
type DataType = MyDataType;
type ValueType = MyValueType;
// This method will be called when drawing each node. This allows adding
// extra ui elements inside the nodes. In this case, we create an "active"
// button which introduces the con... | Rust | 0 |
IGN_512BYTES");
add_if_includes(section_header.characteristics(), 0x00B00000, &mut flags, "IMAGE_SCN_ALIGN_1024BYTES");
add_if_includes(section_header.characteristics(), 0x00C00000, &mut flags, "IMAGE_SCN_ALIGN_2048BYTES");
add_if_includes(section_header.characteristics(), 0x00D00000, &mut flags... | Rust | 0 |
let constraints_from_leaf =
cs.num_constraints() - constraints_from_params - constraints_from_digest;
println!("constraints from leaf: {}", constraints_from_leaf);
// Allocate MT Path
let mut cw = PathVar::<FieldMTConfig, F, FieldMTConfigVar>::new_witness(
... | Rust | 0 |
65241fda74902cca908a065495c0b2
8b799e71b8f14b7a1059cdadc414c409064a22cf9e970b0ffc6f1fc6fdd539c467677
5455739db882585a7c8b3e9ae7955da7135900d85ab832aa83a34b3ce481efc9e43d4
c2276220c8bcb9d27b5a827a5a2d655700321f3b32d21f578c21316195d8
KE1: 60d71c9f5d2a14568807b869e2c251a8e5f7ad8951cd8386c7e32c0634b26b16
804133133e7ee6836c... | Rust | 0 |
"""@rule dummy (matches ATKEYWORD to remove unknown rule tokens from
stream::
@x;
@x {...}
no nested yet!
"""
def rule(tokens):
saved = []
for t in tokens:
saved.append(t)
if t[1] == '}' or t[1] == ';':
... | Python | 1 |
curr_offset = 1;
for attr_size in attr_sizes {
new_table_meta
.attr_offset_ranges
.push(vec![curr_offset, curr_offset + attr_size]);
curr_offset += attr_size;
}
new_table_meta.row_length = curr_offset;
// create corresponding bin ... | Rust | 0 |
let sides = string.split("x").map(|s| {
let num: usize = s.parse().or(Err("All boxes' dimensions should be made of numbers."))?;
Ok(num)
}).collect::<Result<Vec<usize>, &'static str>>()?;
if sides.len() != 3 {
return Err("All boxes should have three dimensions... | Rust | 0 |
// and read them in from a TSV file
#[derive(PartialEq, Eq, Hash)]
pub struct ILoc {
pub chrom: String,
pub upstream_pos: u64,
pub downstream_pos: u64,
}
impl ILoc {
pub fn length(&self) -> u64 {
self.downstream_pos - self.upstream_pos + 1
}
fn read_line(line: String) -> Option<ILoc> {
... | Rust | 0 |
"C", "D"])
# # y = np.array([3, 8, 1, 10])
# # plt.barh(x, y, color = "hotpink")
# # plt.show()
# # Ex4 Histogram
# # x = np.random.normal(170, 10, 250)
# # plt.hist(x)
# # plt.show()
# # Ex5 Pie Charts
# # y = np.array([35, 25, 25, 15])
# # mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
# # myexplode = [... | Python | 1 |
0, idelta as u64);
while delta > 0 {
if delta & 1 != 0 {
acc_mult *= cur_mult;
acc_plus = acc_plus * cur_mult + cur_plus;
}
cur_plus = (cur_mult + 1) * cur_plus;
cur_mult *= cur_mult;
delta /= 2;
}
self.... | Rust | 0 |
break
# If there are different vars between the origin and optimized program.
for name in self.main_program.block(i).vars:
var = self.main_program.block(i).var(name)
if not self._find_var(var, program, i):
is_different = True
... | Python | 1 |
assert!(!(true <= false));
assert_eq!(true.cmp(&true), Equal);
assert_eq!(false.cmp(&false), Equal);
assert_eq!(true.cmp(&false), Greater);
assert_eq!(false.cmp(&true), Less);
}
<gh_stars>0
#![no_std]
#![feature(asm)]
#![feature(linkage)]
#![feature(naked_functions)]
#[naked]
#[no_mangle]
pub uns... | Rust | 0 |
{
tag("if")
.precedes(with_pos(arg_list))
.map(|Positioned { range, value: args }| match args.as_slice() {
[cond, value_if_true, value_if_false] => Expr::IfOp {
cond: Box::new(cond.clone()),
value_if_true: Box::new(value_if_true.clone()),
... | Rust | 0 |
class QueueNode:
def __init__(self, value):
self.value = value
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def enqueue(self, value):
new_node = QueueNode(value)
if self.rear is None:
self.front = self.rear... | Python | 1 |
pin_1,
pin_2,
pin_3,
pin_enable,
state: PhantomData::<DisabledState>,
};
let _unreachable_result = mux.set_channel_active(16);
}
#[test]
#[should_panic]
fn set_channel_panic_20() {
let pin_0 = PinMock::new(&[]);
let pin_1 ... | Rust | 0 |
-1)
# if rs.norm() > 0: import IPython, sys; IPython.embed(); sys.exit(-1)
return dx, ds, dz, dy
def pre_factor_kkt(Q, G, A):
""" Perform all one-time factorizations and cache relevant matrix products"""
nineq, nz, neq, _ = get_sizes(G, A)
# S = [ A Q^{-1} A^T A Q^{-1} G^T ]
... | Python | 1 |
OPENSSL_NO_SSL3_METHOD"))]
pub fn SSLv3_method() -> *const SSL_METHOD;
pub fn SSLv23_method() -> *const SSL_METHOD;
pub fn SSLv23_client_method() -> *const SSL_METHOD;
pub fn SSLv23_server_method() -> *const SSL_METHOD;
pub fn TLSv1_method() -> *const SSL_... | Rust | 0 |
track_step = 10;
let mut track = Track::new(Interpolator, track_size, track_step);
track.push_aligned(0)?;
track.push_aligned(10)?;
track.insert_not_aligned(3, DataNA(3), |_| {})?;
track.push_aligned(10)?;
track.insert_not_aligned(5, DataNA(5), |_| {})?;
track.push_aligned(10)?;
track.... | Rust | 0 |
, 192, 200, 221, 47, 143, 252, 235, 107, 181, 152, 81, 45, 144, 80, 109, 10,
113, 132, 242, 15, 20, 152, 207, 69, 135, 135, 242, 50, 132, 181, 72, 136, 201,
190, 65, 109, 16, 63, 118, 4, 6, 53, 122, 22, 182, 216, 65, 163, 3, 213, 201, 91,
107, 71, 77, 45, 127, 15, 234, 10, 42, 118, 200, 151, 221, 33, 16, 23... | Rust | 0 |
appropriate to retry, by calling into epoll_wait().
continue;
}
return Err(Error::Epoll(e));
}
};
for event in events.iter().take(num_events) ... | Rust | 0 |
rivative calculation is causing an issue. Let's modify the code to handle the absolute value function and find the minimum value using a different approach.\n\n```python\nfrom sympy import symbols, Piecewise, Min, oo\n\ndef find_minimum_value():\n x, p = symbols('x p')\n f = abs(x - p) + abs(x - 15) + abs(x - p -... | Python | 1 |
#!/usr/bin/env python3
import sys
import xml.etree.ElementTree as ET
import json
if len(sys.argv) != 3:
print("Usage: "+sys.argv[0]+" xmlfile jsonfile")
tree = ET.parse(sys.argv[1])
root = tree.getroot()
j = {"desc": {},
"experiment": {},
"vars": {},
"categories": {},
"tree": {}}
modelDescrip... | Python | 1 |
t_eq!(bm.median_dev(), dev);
}
}
use crate::{
animation::LinearAnimation,
core::{Core, CoreContext, ObjectRef, OnAdded, Property},
status_code::StatusCode,
};
#[derive(Debug, Default)]
pub struct Animation {
name: Property<String>,
}
impl ObjectRef<'_, Animation> {
pub fn name(&self) -> String... | Rust | 0 |
er_code: str,
background_tasks: BackgroundTasks,
session: AsyncSession = Depends(get_db),
):
logger.info("Syncing agent vulnerabilities")
agents = await get_agents_by_customer_code(customer_code, session)
for agent in agents:
if agent.customer_code is None:
logger.info(f"Skipping... | Python | 1 |
_else(||format!("Unknown relation {}", rident))?;
let val = relval_from_record(relid, rec)?;
Ok(Update::Insert{relid: relid as RelId, v: val})
},
record::UpdCmd::Delete(rident, rec) => {
let relid: Relations = relident2id(rident).ok_or_else(||format!("Unknown relation... | Rust | 0 |
if result['success']:
task_data['completed_count'] += 1
task_data['stock_status'][stock_code] = {
'status': 'completed',
'retry_count': result.get('... | Python | 1 |
2(&self) -> Vec2 {
use CompassDir::*;
match self {
N => vec2(0.0, 1.0),
E => vec2(1.0, 0.0),
S => vec2(0.0, -1.0),
W => vec2(-1.0, 0.0),
}
}
}
<reponame>bobotu/kaosu-packer<gh_stars>1-10
/*
* Copyright 2019 <NAME>
*
* Licensed under the Apac... | Rust | 0 |
#[cfg_attr(test, assert_instr(eor3))]
pub unsafe fn veor3q_s32(a: int32x4_t, b: int32x4_t, c: int32x4_t) -> int32x4_t {
#[allow(improper_ctypes)]
extern "unadjusted" {
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.crypto.eor3s.v4i32")]
fn veor3q_s32_(a: int32x4_t, b: int32x4_t, c... | Rust | 0 |
pb: &Arc<Mutex<ProgressBar>>,
scene: &Scene<T>,
shader: &Shader,
cam: &Camera,
) -> Result<Data, Error> {
let w = cam.sensor().res().0 as usize;
let h = cam.sensor().res().1 as usize;
let super_samples = cam.sensor().super_samples();
let h_res = cam.sensor().res().0;
let block_size... | Rust | 0 |
from pydantic import BaseModel, Field
from datetime import datetime
class QueryCreate(BaseModel):
cadastral_number: str = Field(..., description='Кадастровый номер')
latitude: float = Field(..., description='Широта')
longitude: float = Field(..., description='Долгота')
class Config:
from_attr... | Python | 1 |
, Debug)]
#[clap(
name = "adbook is a simple SSG powered by asciidoctor",
setting = clap::AppSettings::ColoredHelp
)]
pub struct Cli {
#[clap(subcommand)]
pub cmd: SubCommand,
}
impl Cli {
pub fn run(&mut self) -> Result<()> {
self.cmd.run()
}
}
#[derive(Clap, Debug)]
pub enum SubComma... | Rust | 0 |
emory(&field_type) {
continue;
}
ctx.emit_block(|| {
let (byte_offset, _) = layout.offsets.get(&field.get_offset()).unwrap();
let field_ptr = self.call_builtin_str(
ctx,
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.