text
string
label_name
string
labels
int64
#!/usr/bin/python # -*- coding:Utf-8 -*- """ pylint helper plugin for validating RedBaron Handles special cases like RedBaron's magic use of imports to create missing nodes. Taken in part from https://bitbucket.org/pfctdayelise/pylint-pytest/downloads """ from astroid import MANAGER from astroid import nodes from as...
Python
1
Host DMA Channel Next Descriptor Address Register (n = 1)"] pub mod usbhs_hstdma; #[doc = "DEVCTRL register accessor: an alias for `Reg<DEVCTRL_SPEC>`"] pub type DEVCTRL = crate::Reg<devctrl::DEVCTRL_SPEC>; #[doc = "Device General Control Register"] pub mod devctrl; #[doc = "DEVISR register accessor: an alias for `Reg<...
Rust
0
let want_type = match path_type { PathType::Symlink => { // There's nothing to check on a symlink encountered _while // looking up the target_; its permissions and ownership do not // actually matter. return; } PathType:...
Rust
0
<< idx; let render_mask = quote! { if self.#name { flags |= #mask; } }; match position { BitfieldPosition::Start => quote!( let mut flags = 0; #render_mask ), BitfieldPosition::Intermediate => render_mask, BitfieldPositi...
Rust
0
ing())); assert_eq!( p.next().tok, Token::LiteralUURString("foo\n\\\"bar".to_string()) ); let mut p = Lexer::<DefaultContext>::new(b"uR\"hello(foo)hello\" u8R\"world(foo\n\\\"bar)world\""); assert_eq!(p.next().tok, Token::LiteralURString("foo".to_stri...
Rust
0
in 0..4 { let color_value = if density_pattern & (1 << (dy * 4 + dx)) != 0 { 255 } else { 0 }; let target_base_index = (((y * 4 + dy) * (w * 4) + x * 4 + dx) * 4) as usize; ...
Rust
0
: InternedStringContent::new(), symbols: Arena::new(), symbol_handles: FxHashMap::default(), files: Arena::new(), file_handles: FxHashMap::default(), nodes, node_id_handles: NodeIDHandles::new(), jump_to_node, root_node, ...
Rust
0
} else { let s = match CStr::from_ptr(*item).to_str() { Ok(s) => s, Err(_) => return -libc::EINVAL, }; let vol_tuple: Vec<&str> = s.split(':').collect(); if vol_tuple.len() != 2 { return -libc::EINVAL; } ...
Rust
0
ions(request, id): survey = get_object_or_404(Survey, id=id) context = { 'survey': survey, 'questions': Question.objects.filter(survey=survey), } return render(request, 'manage/survey_edit_questions.html', context) @require_POST @staff_required @permission_required('surveys.delete_ques...
Python
1
6 => Val(RESET_SRC_A::SYSRESET), 5 => Val(RESET_SRC_A::CLK_LOSS), 4 => Val(RESET_SRC_A::VDDR_LOSS), 2 => Val(RESET_SRC_A::VDDS_LOSS), 1 => Val(RESET_SRC_A::PIN_RESET), 0 => Val(RESET_SRC_A::PWR_ON), i => Res(i), } } #[doc = "Ch...
Rust
0
elapsed = time.time() - start_time times[name] = elapsed results[name] = (ciphertext, decrypted) # 计算吞吐量 total_data = len(plaintext) * test_rounds * 2 # 加密+解密 throughput = (total_data / (1024 * 1024)) / elapsed # 验证正...
Python
1
ator uninitialized").init_memmap(base, npage, begin); } pub fn alloc_at(&self, addr: usize, layout: Layout, pgdir: *const usize) -> Result<*mut u8, AllocErr> { self.0.lock().as_mut().expect("allocator uninitialized").alloc_at(addr, layout, pgdir) } pub fn switch_content(&self, alloc_from: &imp...
Rust
0
e_clause)) } pub fn dump_program_clauses<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { if !tcx.features().rustc_attrs { return; } let mut visitor = ClauseDumper { tcx }; tcx.hir() .krate() .visit_all_item_likes(&mut visitor.as_deep_visitor()); } struct ClauseDumper<'a, 'tcx: 'a> { ...
Rust
0
= artifact_unchecked.to_account_info(); spl_token_transfer(TokenTransferParams { source: staking_escrow.to_account_info(), destination: staking_account.to_account_info(), amount: staking_escrow.amount, authority: artifact_info, authority_signer_seeds:...
Rust
0
layers: u32, pub mip_count: u32, pub sample_count: u32, pub format: ImageFormat, // pub dimension: 2D // pub usage: T_SRC T_DST ATTACHMENT SAMPLER } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum ImageFormat { // Normal 32 bit formats Rgba8Unorm, Rgba8UnormSrgb, // Pa...
Rust
0
''' 主函数,负责选择feature调用分类器 ''' import data import bayes import svm import self_model import mlp AllFeatureChoices = [["balance", "duration", "pdays"], ["balance", "duration", "previous"], ["balance", "duration", "poutcome"], ["duration", "pdays"], ["duration",...
Python
1
tle_entry, num: entry, num_label, lyrics_buffer, } } } impl Update for AlbumWindow { type Model = Model; type ModelParam = (String, Vec<(String, String)>); type Msg = Msg; fn model(_: &Relm<Self>, (title, tracks): (String, Vec<(String, String)>)) -> Mode...
Rust
0
#r# ===================================== #r# Relay drived by a bipolar transistor #r# ===================================== #r# This example shows the simulation of ... #################################################################################################### import matplotlib.pyplot as plt ############...
Python
1
::ensure_signed; //! # type VoteIndex = u64; //! pub trait Trait: democracy::Trait { } //! //! decl_module! { //! pub struct Module<T: Trait> for enum Call where origin: T::Origin { //! //! fn proxy_set_approvals(origin, votes: Vec<bool>, index: VoteIndex) -> Result { //! let who = <democracy::Module<T>>::proxy(e...
Rust
0
approx_kl = torch.mean((ratio - 1) - log_ratio) pg_loss1 = -advantages * ratio pg_loss2 = -advantages * torch.clamp( ratio, 1.0 - self.cliprange, 1.0 + self.cliprange, ) pg_loss = torch.sum(torch.max(pg_loss1, pg_loss2) * mask) / n p...
Python
1
divisor: GLuint)>; extern "C" { pub fn glGetInternalformativ( target: GLenum, internalformat: GLenum, pname: GLenum, bufSize: GLsizei, params: *mut GLint, ); } pub type PFNGLGETINTERNALFORMATIVPROC = ::std::option::Option< unsafe extern "C" fn( target: GLenum...
Rust
0
chema) schema.dump_json(conf_schema, build_path / 'schema_grouped.json') # # 4 = schema.yml # elif config_dump == 4: print("Generating schema.yml ...") try: import yaml except ImportE...
Python
1
: u32 = 10; //! const BAR: u32 = 0; //! const _: () = assert_non_zero(FOO, BAR); //! //! #[track_caller] //! const fn assert_non_zero(foo: u32, bar: u32) { //! concat_assert!{ //! foo != 0 && bar != 0, //! "\nneither foo nor bar can be zero!\nfoo: ", foo, "\nbar: ", bar //! } //! } //! ``` //! T...
Rust
0
root, viz, below_main, main, port_selection, label, above_nodes, above_nodes_text, panel, panel_text, node_searcher, node_searcher_text, edited_node, edited_n...
Rust
0
from random import randint from max_heap import MaxHeap max_heap = MaxHeap() arr = [randint(1, 100) for _ in range(100)] max_heap.heapify(arr) max_heap.insert(4) max_heap.insert(18) max_heap.insert(11) max_heap.insert(2) max_heap.extract_max() max_heap.extract_max() max_heap.insert(13) max_heap.insert(5) max_heap.inse...
Python
1
""" These callables are used by django-wiki to check various permissions a user has on an article. """ from django.conf import settings from django.utils.translation import gettext_noop as _ from lms.djangoapps.courseware.tabs import EnrolledTab class WikiTab(EnrolledTab): """ Defines the Wiki view type th...
Python
1
let avg = total_time / SAMPLES; let avg = avg.subsec_nanos() as f64 / 1_000_000_000f64 + (avg.as_secs() as f64); println!("Average proving time (in seconds): {}", avg); } use inflector::Inflector; use botocore::{Service, Shape, ShapeType, Operation}; use std::ascii::AsciiExt; use self::ec2::Ec2Generator;...
Rust
0
fn err() -> Resource { unsafe { Resource::from_raw(crate::sys::io_get_stderr()) } } } pub mod random { use super::sys; pub fn i31() -> i32 { unsafe { sys::random_i32() } } pub fn i63() -> i64 { unsafe { sys::random_i64() } } } #[macro_export] macro_rules! entrypoint {...
Rust
0
print timing print('Test: [{0:05d}/{1:05d}]\t' 'Time {batch_time.val:.2f} ({batch_time.avg:.2f})'.format( iter_idx, len(val_loader), batch_time=batch_time)) # gather all stats and evaluate results['t-start'] = torch.cat(results['t-start']).numpy() results['t-en...
Python
1
# %% import yaml2plot as y2p # Use the test data we have available spice_file = "./raw_data/Ring_Oscillator_7stage.raw" dataset = y2p.load_spice_raw(spice_file) spec = y2p.PlotSpec.from_yaml(""" title: "Ring Oscillator - Key Nodes" X: signal: "time" label: "Time (s)" Y: - label: "Voltages (V)" signals: ...
Python
1
Attention = functools.partial( og_DotProductCausalAttention, max_inference_length=16384, ) # gin_config.append( # '\nMixedLSHSelfAttention.std_length=16384' # ) gin_config = [l for l in gin_config if 'mira' not in l] gin_config = [l for l in gin_config if 'okenize' not in l] # tokenize gin_config = ''.join(...
Python
1
ude::UserHwnd::CreateWindowEx). pub fn new(parent: &impl GuiParent, opts: ButtonOpts) -> Button { let opts = ButtonOpts::define_ctrl_id(opts); let (ctrl_id, horz, vert) = (opts.ctrl_id, opts.horz_resize, opts.vert_resize); let new_self = Self( Arc::new( Obj { base: BaseNativeControl::new(paren...
Rust
0
import os from numpy.distutils.misc_util import Configuration def configuration(parent_package="", top_path=None): config = Configuration("metrics", parent_package, top_path) libraries = [] if os.name == 'posix': libraries.append('m') config.add_subpackage('_plot') config.add_subpackage...
Python
1
{ let mut ctx = CfgBindCtx { _phantom: &(), usage: BindUsage::Executable, }; self.start(Closure::from_fn_const(func.bind(binder, &mut ctx))) } } // ---------------------------------------------------------------------------- /// A trait for closures that can receiv...
Rust
0
# -*- coding: utf-8 -*- # # Copyright 2021 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
<u8> = Rgba([181, 194, 217, 255]); pub const CASTRO: Rgba<u8> = Rgba([77, 11, 35, 255]); pub const CEDAR: Rgba<u8> = Rgba([51, 18, 4, 255]); pub const CERULEAN_BLUE: Rgba<u8> = Rgba([51, 84, 195, 255]); pub const CHARTREUSE: Rgba<u8> = Rgba([127, 255, 0, 255]); pub const CHATEAU_GREEN: Rgba<u8> = Rgba([49, 154, 68, 255...
Rust
0
ret = value + 1; // self.ranges[index].b = value; // if value + 1 < r.b { // self.ranges.insert(index, Range{a: value + 2, b: r.b}); // } // return ret; // } // } // fn insert_after(&mut self, value: i64, x: i64) { // let mut index...
Rust
0
import sys import re input = sys.stdin.read() state = re.findall(r'(?<=Begin in state )\w+(?=.)',input)[0] steps = int(re.findall(r'(?<=Perform a diagnostic checksum after )[0-9]+(?= steps.)',input)[0]) input = input.split('In ') #Generate turing machine state lookup lookup = {} for l in input: s = re.findall(r'(...
Python
1
pl", input), ]) .unwrap(); assert_eq!(tera.render("tpl", context.clone()).unwrap(), expected); } } <reponame>FreeMasen/wasmer-plugin<filename>crates/wasmer_plugin_macro/src/lib.rs #![recursion_limit="128"] extern crate proc_macro; use proc_macro::TokenStream; use syn::{ Item as SynItem, ...
Rust
0
ne: rvec_avg, tvec_avg = average_pose(rvec1, tvec1, rvec2, tvec2) print(f"Averaged Position:{tvec_avg.flatten()}") print(f"Averaged Rotation Vector: {rvec_avg.flatten()}") # Display frames cv2.namedWindow('Camera 1', cv2.WINDOW_NORMAL) cv2.resizeWindow('Camera 1', 3840, 2160) cv...
Python
1
s.len()); for shard in shards { let shard = match shard { Some(x) => x, None => panic!("Missing shard"), }; result.push(shard); } result } #[test] fn test_no_data_shards() { assert_eq!(Error::TooFewDataShards, ReedSolomon::new(0, 1).unwrap_err()); } #[t...
Rust
0
new(100.0, 100.0); //let inner_rec = api::Rectangle::new(100.0, 100.0); /* let inner = api::Label::new(&text_renderer, "Hello world!".to_string()); let outer_rec = api::Rectangle::new_with_child(inner.as_widget()); //inner_rec.reposition(150.0, 150.0); outer_rec.reposition(100.0, 100.0); */ let mut state = ...
Rust
0
pected.vert_materials), len(actual.vert_materials)) for i in range(len(expected.vert_materials)): compare_vertex_materials(self, expected.vert_materials[i], actual.vert_materials[i]) self.assertEqual(len(expected.textures), len(actual.textures)) for i in range(len(expected.textures)): compa...
Python
1
nhev4(p1, p0, q0, q1, bd - 8), mask, MAX_LOOP_FILTER + 1) as usize; // sse for each; short-circuit the 'special' no-op cases. let sse_none = stride_sse(a, &none, src_pitch); let sse_narrow2 = if nhev != mask { stride_sse(a, &narrow2, src_pitch) } else { sse_none }; let sse_narrow4 = if nhev <= MA...
Rust
0
()); let hash_2_id_mem_size = self.hash_2_id.capacity() * 12; let hash_mem_size = mem::size_of::<Hash>(); let id_2_hash_mem_size = self.id_2_hash.capacity() * hash_mem_size; let row_sum_mem_size = self.row_sum.capacity() * 4; let pair_index_mem_size = self.pair_index.capacity() ...
Rust
0
)] #![feature(never_type)] #![allow(incomplete_features)] pub use rp2040_pac2 as pac; // This mod MUST go first, so that the others see its macros. pub(crate) mod fmt; pub mod interrupt; pub mod dma; pub mod gpio; pub mod pll; pub mod resets; pub mod uart; embassy_extras::peripherals! { PIN_0, PIN_1, P...
Rust
0
print("contagem regressiva") contador = 10 while contador >= 0: print (contador) contador = contador -1 # -= 1 print ("seu foguete esta decolando!!")
Python
1
= libm::sin(temp); #[cfg(feature = "std")] let temp_sin = temp.sin(); post_fix.scale(-0.5 * temp_sin).add(*self.range.start()) } else { #[cfg(feature = "libm")] let scalar = libm::pow(2.0, t * -10.0); #[cfg(feature = "std")] ...
Rust
0
from datetime import timedelta from odoo import fields from odoo.exceptions import UserError from odoo.tests import tagged from odoo.addons.account.tests.test_account_move_send import TestAccountMoveSendCommon @tagged('post_install_l10n', 'post_install', '-at_install') class TestKEAccountMoveSend(TestAccountMoveSend...
Python
1
1, column=3, padx=10, pady=20, sticky='nsew') self.avariaLabel.grid(row=2, column=2, padx=10, pady=20, sticky='nsew') self.avaria.grid(row=2, column=3, padx=10, pady=20, sticky='nsew') self.potencialLabel.grid(row=3, column=2, padx=10, pady=20, sticky='nsew') self.potencial.grid(row=3, c...
Python
1
# -*- coding: utf-8 -*- """ Задание 4.5 Из строк command1 и command2 получить список VLANов, которые есть и в команде command1 и в команде command2 (пересечение). В данном случае, результатом должен быть такой список: ['1', '3', '8'] Записать итоговый список в переменную result. (именно эта переменная будет проверят...
Python
1
checked_bytes:ident, $src:expr, $ctx:ident, $generic1:tt $(: $bound1:ident $(+ $other1:ident)*)?, $generic2:tt $(: $bound2:ident $(+ $other2:ident)*)?) => { generic_from_reader!(new_with_capacity, insert, $typ, $reader, $unchecked_reader, $checked_bytes, $src, $ctx, $generic1 $(: $bound1 $(+ $other1)*)?, $gener...
Rust
0
); do_test!( U10, U7, test_count_u10_u7, test_unique_u10_u7, test_increasing_u10_u7, test_sorted_u10_u7, test_valid_u10_u7 ); do_test!( U10, U8, test_count_u10_u8, test_unique_u10_u8, test_increasing_u10_u8, ...
Rust
0
KNXConnectionstateResponse, service_identifier=0x0208) bind_layers(KNX, KNXDisconnectResponse, service_identifier=0x020A) bind_layers(KNX, KNXDisconnectRequest, service_identifier=0x0209) bind_layers(KNX, KNXConfigurationRequest, service_identifier=0x0310) bind_layers(KNX, KNXConfigurationACK, service_identifier=0x0311...
Python
1
x == index) } pub fn from_shader_layouts(shader_layouts: &mut [ShaderLayout]) -> Self { let mut bind_groups = HashMap::<u32, BindGroupDescriptor>::default(); let mut vertex_buffer_descriptors = Vec::new(); for shader_layout in shader_layouts.iter_mut() { for shader_bind_grou...
Rust
0
/* TODO: duplicated glyph */ tt_add_glyph(glyphs, gid, cid); /* !NO_GHOSTSCRIPT_BUG */ num_glyphs = num_glyphs.wrapping_add(1) } } } /* * Vertical */ if !v_used_chars.is_null() { let mut gsub_list; /* ...
Rust
0
import hangman_creator hangman = hangman_creator.Hangman('d://wordlist.txt') hangman.choose_the_word() hangman.fill_the_word_status() while True: hangman.get_word_status() hangman.guess_the_letter() if hangman.attempts_remaining == 0: print("out of attempts.the word was{}.game over!".format(hang...
Python
1
NE : i32 where LANE == 0); let c: float32x4_t = simd_shuffle4!(c, c, <const LANE: i32> [2 * LANE as u32, 2 * LANE as u32 + 1, 2 * LANE as u32, 2 * LANE as u32 + 1]); vcmlaq_f32(a, b, c) } /// Floating-point complex multiply accumulate #[inline] #[target_feature(enable = "neon,fcma")] #[cfg_attr(test, assert_in...
Rust
0
'Win32_System_Wmi'*"] pub const WBEM_E_ILLEGAL_NULL: WBEMSTATUS = -2147217368i32; #[doc = "*Required features: 'Win32_System_Wmi'*"] pub const WBEM_E_INVALID_QUALIFIER_TYPE: WBEMSTATUS = -2147217367i32; #[doc = "*Required features: 'Win32_System_Wmi'*"] pub const WBEM_E_INVALID_PROPERTY_TYPE: WBEMSTATUS = -2147217366i...
Rust
0
tate_db) self.schedule_filename = either( 'beat_schedule_filename', schedule_filename, ) self.scheduler = either('beat_scheduler', scheduler, scheduler_cls) self.time_limit = either( 'task_time_limit', time_limit, task_time_limit) self.soft_time_limit = ei...
Python
1
Punkt for p in &p_list { dist_list.push(T::dist(&punkt, p)); } let w_list: Vec<f64> = T::get_w_list(&dist_list, &g_list); //Implementation in den Dimensionen selber (Siehe z.B. f32) let diff_list: Vec<f64> = T::get_dim_diff(&punkt); //Liste von den Unterschieden der jeweili...
Rust
0
= array_ops.concat( 0, (math_ops.range(m, vec_rank), math_ops.range(0, m))) return array_ops.transpose(vec, perm=perm) x_flipped = control_flow_ops.cond( math_ops.less(0, m), _flip_front_dims_to_back, lambda: array_ops.expand_dims(vec, -1)) return array_ops.reshape(x_flipped, new_sha...
Python
1
class BaseParseError(Exception): ... class MissingArgumentsError(BaseParseError): ... class TooManyArgumentsError(BaseParseError): ... class InvalidArgumentError(BaseParseError): ...
Python
1
print(f"train_accuracy: {train_accuracy:.4f}\t valid_accuracy: {valid_accuracy:.4f}") print('*'*80+Style.RESET_ALL) if valid_loss < best_loss: best_loss = valid_loss torch.save({ 'model_state_dict': model.state_dict(), 'epoch'...
Python
1
FRONTEND__ => instr::string(alloc, "hackc"), G__LINE__ => instr::int( alloc, p.info_pos_extended().1.try_into().map_err(|_| { emit_fatal::raise_fatal_parse(p, "error converting end of line from usize to isize") })?, ), G__NAMESPACE__ => instr::...
Rust
0
b'A'), EntryState::Mutated)), (1, StorageEntry::new(None, EntryState::Mutated)), (2, StorageEntry::new(Some(b'C'), EntryState::Mutated)), (3, StorageEntry::new(None, EntryState::Mutated)), ], ); } #[test] #[should_panic(expected = "index o...
Rust
0
f = open("day4.txt", "r") result = 0 for rowOri in f: if rowOri != "\n" and rowOri != '': rowLeft=rowOri[rowOri.index(':')+1:rowOri.index('|')-1].strip() rowRight = rowOri[rowOri.index('|')+1:-1].strip() winningNb = rowLeft.split(" ") while(winningNb.count("")): winningNb.remove("") ...
Python
1
est we can't set up a device the device's integration setting disabled.""" with patch( "homeassistant.components.aranet.config_flow.async_discovered_service_info", return_value=[DISABLED_INTEGRATIONS_SERVICE_INFO], ): result = await hass.config_entries.flow.async_init( DOMAIN...
Python
1
ively small radii to fit in the legs and horns. // WARNING: This will take a while (as in 4 hours) to generate!!! println!("Packing spheres into cow..."); let now = Instant::now(); let mut sizes = Uniform::new(0.03, 0.05); let packed = PackedVolume::new(boundary, &mut sizes).unwrap(); println!( ...
Rust
0
where K: Borrow<Q>, Q: TrieKey, { let mut nv = key.encode(); let (ancestor_node, depth) = self.node.get_raw_ancestor(&nv); nv.split(depth); ancestor_node.as_subtrie(nv) } /// Fetch the closest descendant for a given key. /// /// If the key is in t...
Rust
0
import torch from diffusers import ControlNetModel, StableDiffusionControlNetInpaintPipeline import yaml # Approach 1: My ControlNet weights to diffusers library --> too many differences # Approach 2: Load cldm model and hook it to diffusers library # Approach 3: Adapt cldm model to be used for inpainting # Define to...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # File : views.py # Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------ # Author's Blog: https://blog.csdn.net/qq_32394351 # Date : 2023/12/7 from fastapi import APIRouter, Request, Depends, Query, File, UploadFile from typing import Any from sqlalchemy.orm import Session from ...
Python
1
from flet import * import nova_assistencia_tecnica import novo_cliente import nova_os import procurar def main(page: Page): page.title = "ASSIST-1.0" def mudanca_de_rota(route): page.views.clear() page.views.append( View( "/", [ A...
Python
1
'lm_args': config.get('lm', None), 'neck_args': config.get('neck', None), 'decoder_args': config.get('decoder', None), 'state_dict': self.model.state_dict(), 'optimizer': self.optimizer.state_dict(), }, '{}/ckpt_task{}'.format(self.ck...
Python
1
from config import * from google import genai # Extra keys client = genai.Client(api_key=GEMINI) client2 = genai.Client(api_key="AIzaSyBwqN60ljF6pSIO0P7v0GFzeNW_i55YMOE") chat = client.chats.create(model="gemini-2.0-flash") #initial_subject = input("Please enter the subject you'd like to teach: ").strip() #print(f"Su...
Python
1
class NotValidPhoneNumber(ValueError): pass class NotValidDate(ValueError): pass class NameIsString(ValueError): pass class NoContacts(Exception): pass class NoNotes(Exception): pass class NoBirthdays(Exception): """The date of birth search is limited to 365 days""" class LimitSearchB...
Python
1
get(&JsValue::from_str(KEYS::SYNC_TOKEN))? .await? .map(|f| self.deserialize_event(f)) .transpose() } pub async fn save_changes(&self, changes: &StateChanges) -> Result<()> { let mut stores: Vec<&'static str> = [ (changes.sync_token.is_some(), KEYS::SYNC_...
Rust
0
print('# documents: %d --> %d'%(len(data), len(new_docs))) data.js = new_js data.documents = new_docs return data def get_test_fold(data, fold): print('Getting test fold %d...'%fold) l = int(len(data) * 0.1 * fold) r = int(len(data) * 0.1 * (fold+1)) new_js = [] new_docs = [] for i ...
Python
1
>>> question = "what's his name?" >>> words = example["words"] >>> boxes = example["bboxes"] >>> encoding = tokenizer( ... question.split(), words, is_split_into_words=True, return_token_type_ids=True, return_tensors="tf" ... ) >>> bbox = [] >>> for i, s, w...
Python
1
import time from tqdm import tqdm from .gate import Gate from .fast_full_update import FastFullUpdater from ..utils.logger import logger import logging def evolve(ipeps, dtau, steps, model, config): """ Evolves the iPEPS tensor network over a given number of steps. Args: ipeps (Ipeps): The iPEPS o...
Python
1
import sys sys.path.append(r'D:\Dev\Source\Falcom\Decompiler2') from Falcom.ED6.Parser.scena_writer_helper import * try: import T4241_hook except ModuleNotFoundError: pass scena = createScenaWriter('T4241 ._SN') # id: 0xFFFF offset: 0x0 @scena.Header('Header') def Header(): header = ScenaHeader() h...
Python
1
n-wasm) or Web Console (wasm). pub fn $lower(text:impl AsRef<str>) { cfg_if::cfg_if! { if #[cfg(target_arch="wasm32")] { use web_sys::console::*; concat_idents!($lower,_1)(&wasm_bindgen::JsValue::from_str(text.as_ref())); } else...
Rust
0
("Labels initialized.") else: labels_shape = list(dataset[0][1].unsqueeze(0).shape) labels_shape[0] = len(dataset) labels = torch.zeros(tuple(labels_shape), device='cpu') outputs_shape = list(model(dataset[0][0].unsqueeze(0).to(device)).shape) outputs_shape[0] = len(dataset) outp...
Python
1
c_page_ids) topics = topic_fetchers.get_topics_by_ids(topic_ids, strict=True) all_learner_group_subtopic_page_summaries: List[ subtopic_page_domain.SubtopicPageSummaryDict ] = [] for topic in topics: for subtopic in topic.subtopics: subtopic_page_id = '{}:{}'.format(topic.id...
Python
1
lution::sub_str_hash(s, power, modulo, k, hash_value); assert_eq!( ret, "bzzrtrrpppigevriaooetwawtnfwddgdvoldxucsbyaufhygdxpnxupmvwbr" ); } } <reponame>kcollinssibley/sysadmin // This file is generated. Do not edit // @generated // https://github.com/Manishearth/rust-clippy/...
Rust
0
if let Some(fromiter) = it.next() { *item = fromiter; } else { panic!("iterator too short for grid type"); } } assert!(!it.next().is_some(), "iterator too long for grid type"); g } } // Extend impl<T, const W: u16, const H...
Rust
0
lf, path: P, buf: B) -> Result<()> where P: AsRef<Path>, B: AsRef<[u8]>; /// Returns the contents of `path`. /// /// # Errors /// /// * `path` does not exist. /// * `path` is a directory. /// * Current user has insufficient permissions. fn read_file<P: AsRef<Path>>(&...
Rust
0
.handle_map .remove(&node_id) .expect("thread handle is missing") .join() .expect("SCPNode join failed"); } } fn push_value(&self, node_id: &NodeID, value: &str) { self.nodes_map .lock() .expect("lock failed...
Rust
0
from datetime import timedelta from odoo import fields, models, api class HostelStudent(models.Model): _name = "hostel.student" _description = "Hostel Student Information" @api.depends("admission_date", "discharge_date") def _compute_check_duration(self): """Method to check duration""" ...
Python
1
illing-group"), ); let test_data = ""; let _m = testutil::create_mock_server(url, test_data, "POST"); let projects = vec!["project1", "projec2"]; match client .billing_group() .assign_projects("my-billing-group", projects) .await { Ok(_response) => { assert!(true); } Err(e) => assert...
Rust
0
# -*- coding: utf-8 -*- """ Created on Tue Mar 02 10:17:40 2015 @author: Sudalai Rajkumar S Module to produce the seed based bench mark given in the competition """ import csv import numpy as np import pandas as pd def getSeedStats(seeds_file): seeds_file_handle = open(seeds_file, 'r') reader = csv....
Python
1
r.push(300); for i in &container { println!("The value is {}",i); } } /** * Now that you know how to create, update, and destroy vectors, knowing how to read their contents is a good next step. * 两种访问Vector元素的方式: * 1. &V[index]; 返回对应下标的具体元素。有可能出现下标越界 * 2. V.get(index);返回一个Some(&element) Or No...
Rust
0
0x07,// W 0x00,// Invalid 0x09,// VectorLength 0x14,// KkHW_3b 0x4D,// XMM0 0x86, 0x16,// EVEX_Vpcmpeqq_kr_k1_xmm_xmmm128b64 0x0B,// N16b8 0x14,// KkHW_3b 0x6D,// YMM0 0x87, 0x16,// EVEX_Vpcmpeqq_kr_k1_ymm_ymmm256b64 0x0C,// N32b8 0x14,// KkHW_3b 0x8D,// ZMM0 0x...
Rust
0
options: Some(SortOptions { descending: false, nulls_first: false, }), }, SortColumn { values: Arc::new(StringArray::from(vec![ Some("foo"), Some("bar"), ...
Rust
0
rt((12, "test12", "<EMAIL>")); table.insert((13, "test13", "<EMAIL>")); table.insert((14, "test14", "<EMAIL>")); table.insert((15, "test15", "<EMAIL>")); table.insert((16, "test16", "<EMAIL>")); table.insert((17, "test17", "<EMAIL>")); assert_eq!(table.num_rows, 17); ...
Rust
0
end_commitment(b"open_proof", &batch_proof.opening_proof)?; transcript.append_commitment(b"shifted_open_proof", &batch_proof.shifted_opening_proof)?; let u = transcript.get_and_append_challenge::<E>(b"u")?; Ok(Challenges { tau, alpha, beta, gamma, ...
Rust
0
odel::{Runner, RunnerError}, crate::ns_util::{self, PKG_PATH}, cm_rust::data::DictionaryExt, failure::{err_msg, format_err, Error, ResultExt}, fdio::fdio_sys, fidl_fuchsia_data as fdata, fidl_fuchsia_process as fproc, fidl_fuchsia_sys2 as fsys, fuchsia_component::client::connect_to_service, ...
Rust
0
gram = (gram + [hyp[i].item()])[-self.block_ngram_repeat:] # skip the blocking if any token in gram is excluded if set(gram) & self.exclusion_tokens: continue if tuple(gram) in ngrams: fail = True ...
Python
1
gs>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<SaasCreationProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SaasResourceResponseWithContinu...
Rust
0
<Item = (CountryTag, &'a [N])>) where N: 'a + PartialEq + Default + Display, { let mut ded = Vec::new(); let mut found_indices = HashSet::new(); let mut max_indices = 0; let default_val = N::default(); for (tag, vals) in iter { max_indices = std::cmp::max(max_indices, vals.len()); ...
Rust
0