text
string
label_name
string
labels
int64
from typing import List, Tuple, Union, Dict, Any import random import copy from abc import ABC, abstractmethod import os import json import argparse from .common_puzzle_factory import PuzzleFactory from .common_constriants import Constraint, ConstraintRowNoRepeat, ConstraintColNoRepeat, ConstraintSubGridNoRepeat clas...
Python
1
alloc` as the global allocator. extern crate wee_alloc; #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::*; #[wasm_bindgen] pub fn init_blockies() { let doc = &opt_unwrap(window().and_then(|w| w.document())); ...
Rust
0
# Author: Chen Shichao import os import shutil import subprocess import tempfile from ament_index_python.packages import get_package_share_directory def test_cs_urdf_xacro(): # Initialize Arguments cs_type = "cs63" safety_limits = "true" safety_pos_margin = "0.15" safety_k_position = "20" # ...
Python
1
let dirs = config.dirs; let mut valid_dirs: Vec<PathBuf> = vec![]; for path in &dirs { if path.exists() && path.is_dir() { valid_dirs.push(path.clone()); } else if !config.is_force_invalid_dirs { return Err("Invalid Directory Paths"); } } // Sanity Check...
Rust
0
{Some(Color::Red)}, "black" => {Some(Color::Black)}, _ => None }, None => None, }; let parse_coord = |command: &mut std::str::SplitWhitespace| match command.next() { Some(number) => number.parse::<isize>().ok(), None => None }; if let Some...
Rust
0
props(Id = "208"))] TouristDestinations, #[strum(props(Id = "863"))] Toyota, #[strum(props(Id = "432"))] Toys, #[strum(props(Id = "518"))] TrackAndField, #[strum(props(Id = "335"))] TradeShowsAndConventions, #[strum(props(Id = "685"))] TrafficAndPublicTransit, ...
Rust
0
.insert(22716, "jī".to_string()); d.insert(22717, "qiāo,áo".to_string()); d.insert(22718, "kěn".to_string()); d.insert(22719, "yì,tú".to_string()); d.insert(22720, "pí".to_string()); d.insert(22721, "bì".to_string()); d.insert(22722, "diàn".to_string()); d.insert(22723, "jiāng".to_string()); d.insert(22...
Rust
0
from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from rest_framework.test import APIClient from book_service.models import Book from book_service.serializers import BookSerializer def sample_book(**params): defaults = { "title": "test", ...
Python
1
# %% import pickle from pathlib import Path import pandas as pd # %% MODEL_NUM = 10 # モデルの数 # %% # 結果を読み込み df_results_content = [] df_results_satisfaction = [] for i in range(MODEL_NUM): with open( Path(__file__).parent / "data/pickle" / f"df_result_content_{i}.pkl", "rb" ) as f: df_results_...
Python
1
{ let t0 = self.tim.as_timer0(); t0.cc[0].write(|w| unsafe { w.bits(ticks as u32 & 0x00FF_FFFF) }); compiler_fence(core::sync::atomic::Ordering::SeqCst); t0.tasks_clear.write(|w| w.tasks_clear().set_bit()); } } fn clear_compare_flag(&mut self) { ...
Rust
0
Any, fmt::{self, Debug}, sync::Arc, }; /// Create a new user defined plan node, for testing pub fn new(input: LogicalPlan) -> LogicalPlan { let node = Arc::new(TestUserDefinedPlanNode { input }); LogicalPlan::Extension(Extension { node }) } struct TestUserDefinedPlanNode { input: LogicalPlan, } i...
Rust
0
, self.bits()); } fn encode_offset<T>(&self, target: &mut [u8], ctx: &mut T, offset: &mut usize, bits: usize); fn bits(&self) -> usize { Self::bits_with_user_define(self, None) } fn bits_with_user_define(&self, bits: Option<usize>) -> usize; } pub enum ShouldDecode { HasNext(bool), ...
Rust
0
ted: {}", oec2); let iec = ChunkUdp::new( SocketAddr::new(dst.ip(), dst.port()), SocketAddr::new(oec.source_addr().ip(), oec.source_addr().port()), ); log::debug!("i-original : {}", iec); let iic = nat.translate_inbound(&iec).await?.unwrap(); log::debug!("i-translated: {}", iic)...
Rust
0
return artist; // Return the first one we find } Err(rusqlite::Error::QueryReturnedNoRows) } } use std::collections::HashMap; use std::io; use std::io::Read; use std::process; fn main() { let mut twos = 0; let mut threes = 0; let mut input = String::new(); io::stdin() ...
Rust
0
; // Windows flags pub const FONT_INSTANCE_FLAG_FORCE_GDI: u32 = 1 << 16; // Mac flags pub const FONT_INSTANCE_FLAG_FONT_SMOOTHING: u32 = 1 << 16; // FreeType flags pub const FONT_INSTANCE_FLAG_FORCE_AUTOHINT: u32 = 1 << 16; pub const FONT_INSTANCE_FLAG_NO_AUTOHINT: u32 = 1 << 17; pub const FONT_...
Rust
0
DWORD; pub type LPSECURITY_ATTRIBUTES = *const SECURITY_ATTRIBUTES; pub type HDC = LPVOID; pub type HWND = LPVOID; c2rs_def!( struct SECURITY_ATTRIBUTES { DWORD nLength; LPVOID lpSecurityDescriptor; BOOL bInheritHandle; }; ); #[link(name = "user32", kind = "dylib")] extern "system" ...
Rust
0
import unittest from tfaip import PipelineMode, Sample from calamari_ocr.ocr.dataset.textprocessors import TextRegularizerProcessorParams class TextTextRegularizer(unittest.TestCase): def test_space_quotes(self): n = TextRegularizerProcessorParams( rulesets=["quotes", "spaces"], ...
Python
1
]; let z = & (x[2]); println!("{}", *z); } use vm::{gc::GcRef, OpCode, Symbol, Value}; #[derive(Debug, Clone, Copy, Default)] pub struct Location { pub line: usize, pub column: usize, } use crate::tokens::TokenType; #[derive(Debug, Clone, Copy)] pub struct VarDecl { pub name: Symbol, } impl Var...
Rust
0
bs[11] = np.random.uniform(*block_rot_z_range) # blue block if initial_condition["blue_block"] == "slider_right": scene_obs[12:15] = block_slider_right elif initial_condition["blue_block"] == "slider_left": scene_obs[12:15] = block_slider_left elif initial_conditi...
Python
1
# Input: a specific year year = int(input("Enter a year: ")) # Check if it is a leap year if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print(f"{year} is a Leap Year.") else: print(f"{year} is not a Leap Year.") # Correct time conversions days=year*365 hours = days * 24 minutes = hours...
Python
1
""" Random Number Author; Mattea Gallon """ from random import randint print("Creating all integers from 1 to n (inclusive) randomly.") user_input = input("Please enter a number, or 'q' to quit: ") if (user_input == 'q'): exit() user_input = int(user_input) print(f"Creating a random sequence of all integers...
Python
1
a', 'channel': 'Cody\'sLab', 'channel_id': 'UCu6mSoMNzHQiBIOCkHUa2Aw', 'tags': [], 'channel_url': 'https://www.youtube.com/channel/UCu6mSoMNzHQiBIOCkHUa2Aw', 'channel_follower_count': int }, 'playlist_mincount': 650, 'params': { ...
Python
1
e<Output = Result<Void, Error>>) { let (sender, receiver) = mpsc::channel(0); let iface_manager_sender = Arc::new(Mutex::new(iface_manager_api::IfaceManager { sender })); let iface_manager = iface_manager::IfaceManagerService::new( phy_manager, client_update_sender, ap_update_sender,...
Rust
0
| StrType::CvString(StrEnc::Binary)) => "&[u8]".into(), Dir::Out(StrType::StdString(StrEnc::Text) | StrType::CvString(StrEnc::Text) | StrType::CharPtr) => "&mut String".into(), Dir::Out(StrType::StdString(StrEnc::Binary) | StrType::CvString(StrEnc::Binary)) => "&mut Vec<u8>".into(), }; } else if self....
Rust
0
TempF = int(input("Digite a temperatura em Fahrenheit: ")) TempC = (TempF - 32) * 5/9 print("A temperatua de Celsius é: ",TempC)
Python
1
, lsb, &zero)?; let middle_bit = &mut relu_res[exponent_size + 1]; *middle_bit = mux_single_bit(b, &should_be_six, middle_bit, &one)?; let msb = &mut relu_res[exponent_size + 2]; *msb = mux_single_bit(b, &should_be_six, msb, &one)?; for wire in &mut relu_res[..exponent_size] {...
Rust
0
, v) - *point; if r.length_squared().near(0.0) { return Point2::new(u, v); } let su = der_u.get_point(u, v); let sv = der_v.get_point(u, v); if su.dot(r).near(0.0) && sv.dot(r).near(0.0) { ...
Rust
0
projected shape for each float in the tensor. temperature (int): temperature in the sine/cosine function. exchange_xy (bool, optional): exchange pos x and pos y. For example, input tensor is [x,y], the results will be [pos(y), pos(x)]. Defaults to True. Returns: pos_e...
Python
1
needs to be created in the runtime so it can // connect to the reactor. runtime.spawn(bg); // Create some futures representing name lookups. let names = &["www.google.com", "www.reddit.com", "www.wikipedia.org"]; let mut futures = names .iter() .map(|name| (name, resolver.lookup_ip(...
Rust
0
safe { // w.ucrxeie() // .bit(reg.ucrxeie) w.ucsselx() .bits(get_ucssel(reg.ucssel)) .ucswrst().clear_bit() } }); //.ucrxeie() ...
Rust
0
Gasto").place(x=20,y=80) ttk.Entry(vGastos,textvariable=gasto ,width=10).place(x=90,y=80) tk.Label(vGastos,text="Concepto").place(x=20,y=110) ttk.Entry(vGastos,textvariable=concepto ,width=30).place(x=90,y=110) ttk.Button(vGastos,text="Gastar",command=Gastar).place(x=20,y=150) ...
Python
1
self, node); Ok(()) } fn visit_formatted_value(&mut self, node: &ast::FormattedValue) -> Self::T { visitor::walk_formatted_value(self, node); Ok(()) } fn visit_joined_str(&mut self, node: &ast::JoinedStr) -> Self::T { visitor::walk_joined_str(self, node); Ok(())...
Rust
0
tem_monitor.get_peak_metrics() # Generate report report = { 'summary': { 'total_tests': total_tests, 'passed_tests': passed_tests, 'failed_tests': failed_tests, 'success_rate': passed_tests / max(1, total_tests), ...
Python
1
.clone()); assert!(is_new); for term in &set { assert!(map.contains_key(term)) } for (term, val) in &map { println!("looking for `{}`", val); assert!(set.contains(term)) } } #![deny(rust_2018_idioms)] mod directives; mod enum_values; mod enums; mod fields; mod models; mod s...
Rust
0
import win32ui from pywin.mfc import dialog from . import dbgcon class DebuggerOptionsPropPage(dialog.PropertyPage): def __init__(self): dialog.PropertyPage.__init__(self, win32ui.IDD_PP_DEBUGGER) def OnInitDialog(self): options = self.options = dbgcon.LoadDebuggerOptions() self.AddD...
Python
1
""" def __init__(self, args, input_dim=3, output_dim=256, ratio=1.0, norm_layer=nn.BatchNorm2d, init_weight=False): super().__init__() # Config block = BasicBlock block_dims = args.block_dims initial_dim = args.initial_dim self.init_weight = init_weight se...
Python
1
# main.py # Importing modules from the chatbot package from nlp_utils.preprocessing import preprocess from nlp_utils.vectorization import vectorize_text from seq2seq.translator import seq2seq_translate from pattern_matching.matcher import pattern_match from text_generation.generator import generate_text from eliza imp...
Python
1
"""Service installation and management commands.""" from __future__ import annotations import os import subprocess import typer from agent_cli.cli import app from agent_cli.core.utils import console, print_error_message, print_with_style from agent_cli.install.common import ( execute_installation_script, ge...
Python
1
(file_path): # 从视频中提取音频进行测试 clip = VideoFileClip(file_path) output_mp3 = "Y:\\Ai-movie-clip__\\core\\cliptemplate\\coze\\output.mp3" clip.audio.write_audiofile(output_mp3, logger=None) clip.close() # 使用统一函数处理 output_path = get_video_di...
Python
1
_unordered(num_cpus) .for_each(|x| { println!("{:?}", x); futures::future::ready(()) }) .await; } else { println!("syncing {} > {}", &opt.source, &opt.dest); rsync .sync() .await .try_buffer_unord...
Rust
0
: &mut v, pos: 0 }; s.serialize(EslSerializer::new(false, CodePage::Russian, &mut w)).unwrap(); assert_eq!(v, [5, 0, 219, 90, 0, 0, 0, 1, 0, 0, 0, 83]); } #[test] fn serialize_map() { let mut s = Map { map: HashMap::new(), unit: (), i: -3 ...
Rust
0
serde(skip_serializing_if="Option::is_none")] pub intents: Option<i32> } #[derive(Serialize)] pub struct IdentifyProperties<'a> { #[serde(rename="$os")] pub os: &'a str, #[serde(rename="$browser")] pub browser: &'a str, #[serde(rename="$device")] pub device: &'a str, } #[derive(S...
Rust
0
class Treino: def __init__(self, nome: str, nivel_dificuldade: str): self.nome = nome self.nivel_dificuldade = nivel_dificuldade self.exercicios = [] def adicionar_exercicio(self, exercicio): self.exercicios.append(exercicio) def exibir_treino(self): exercicios_info...
Python
1
import matplotlib matplotlib.use("PS") import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer # CountVectorizer from sklearn.linear_model import LogisticRegression import modin.pandas as pd train = pd.read_csv("train.csv") test = pd.read_csv("test.csv") subm = pd.read_csv("sample_submission....
Python
1
configurar_seguranca = { "HARASSMENT": "BLOCK_NONE", "HATE": "BLOCK_NONE", "SEXUAL": "BLOCK_NONE", "DANGEROUS": "BLOCK_NONE", } # Definindo o Modelo Usado para Pesquisa model = genai.GenerativeModel(model_name="ge...
Python
1
_eq!(Foo.to_string_alt(), "success"); } } //! Definitions for the uefi-boot interface /// The magic number. pub const MAGIC: u64 = 0xfedcba9876543210; /// Boot information data structure. /// /// This structure provides information necessary for the kernel to take /// control of the system. /// /// All provide...
Rust
0
&t, &v); /// /// assert!(na::approx_eq(&tv, &Vec3::new(1.0, 1.0, 1.0))) /// } #[inline(always)] pub fn inv_translate<V, M: Translate<V>>(m: &M, v: &V) -> V { m.inv_translate(v) } /* * Rotation<V> */ /// Gets the rotation applicable by `m`. /// /// ```rust /// extern crate nalgebra; /// use nalgebra::na::{Ve...
Rust
0
class ConfigEmail : def __init__(self): self.config = {} # 存储配置的字典 self.load_config() # 加载配置 def load_config(self): # 加载配置 self.config = { "emails": [ ("ivqgnra8601@outlook.com", "EugYAMz9s8n59", "8b4ba9dd-3ea5-4e5...
Python
1
from ultralytics import YOLO # detect model=YOLO('yolov8m.pt') result=model("bus.jpg",show=True, conf=0.4,save=True) # segment model=YOLO('yolov8m-seg.pt') result=model("bus.jpg",show=True, conf=0.4,save=True) # classic model=YOLO('yolov8m-cls.pt') result=model("bus.jpg",show=True, conf=0.4,save=True) # pose mo...
Python
1
cant cast") }.a.as_ref().unwrap().get_v() + " " + if let EContextAll::AddContext(ctx) = cast::<_, EContextAll>(&*_localctx) { ctx } else { unreachable!("cant cast") }.b.as_ref().unwrap().get_v() }.to_owned(); if let EContextAll::AddContext(ctx) = cast_mut::<_, EContextAll>(&mu...
Rust
0
io. //! //! ## Usage //! //! ```toml //! [dependencies] //! ipfs-api = "0.5.2" //! ``` //! //! You can use `actix-web` as a backend instead of `hyper`. //! //! ```toml //! [dependencies] //! ipfs-api = { version = "0.5.2", features = ["actix"], default-features = false } //! ``` //! //! ## Examples //! //! ### Writing ...
Rust
0
aabb: a.join(b), elements: vec![a, b], }; let right = BVHNode::Leaf { aabb: c.join(d), elements: vec![c, d], }; let root = BVHNode::Node { aabb: left.aabb().join(right.aabb()), left: Some(Box::new(left)), ...
Rust
0
import click from src.App import app from src.backuppers.Backupper import Backupper from src.backuppers.services.MinIO import MinIO from src.commands.run_ftp_cleaner import run_ftp_cleaner from src.commands.run_local_cleaner import run_local_cleaner from src.commands.run_rsync_cleaner import run_rsync_cleaner from src...
Python
1
^ {size - 1}, so we just distribute powers of `generator_in_size_minus_one` worker.scope(values.len(), |scope, chunk| { for (i, values) in values.chunks_mut(chunk).enumerate() { scope.spawn(move |_| { let mut current_power = generator_in_size_minus_one.pow(&[(i*chunk) as...
Rust
0
, "Should have retrieved some contexts" print("💬 Running answer generation workflow...") ctx_md = retriever_result.output["contexts_md"] # Pass question as user_prompt and context as separate field for template substitution question_text = "How are funnels computed?" answer_message = { ...
Python
1
# Miro - an RSS based video player application # Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 # Participatory Culture Foundation # # This program 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; eithe...
Python
1
import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../'))) import asyncio from sphero_sdk import SpheroRvrAsync from sphero_sdk import SerialAsyncDal from sphero_sdk import InfraredCodes from sphero_sdk import RawMotorModesEnum loop = asyncio.get_event_loop() rvr = S...
Python
1
xitRevert> for ExitReason { fn from(s: ExitRevert) -> Self { Self::Revert(s) } } /// Exit error reason. #[derive(Clone, Debug, Eq, PartialEq, scale_info::TypeInfo)] #[cfg_attr(feature = "with-codec", derive(codec::Encode, codec::Decode))] #[cfg_attr(feature = "with-serde", derive(serde::Serialize, serde::Deseriali...
Rust
0
// For more information about this see comments in // `crates/environ/src/cranelift.rs` let vmctx = self.vmctx(&mut pos.func); let pointer_type = self.pointer_type(); let base = pos.ins().global_value(pointer_type, vmctx); let offset = i32::try_from(self.offsets.vmctx_interrup...
Rust
0
# import matplotlib.pyplot as plt import numpy as np lista = [31,28,29,19] # Esto se almacena en memoria arr = np.array(lista) # print(lista) # print(arr) """ Ejercicio 3 """ lista_2d=[[2,3,4], [3,4,5], [3,4,5], [3,4,5]] arr_2d = np.array(lista_2d) # print(arr_2d) lista_distinct_data...
Python
1
_label))); assert!(!is_rfc_1035_valid(&format!("{}a", longest_valid_name))); assert!(!is_rfc_1035_valid("01.org")); assert!(!is_rfc_1035_valid("\u{4eca}\u{65e5}\u{306f}")); assert!(!is_rfc_1035_valid("\u{4eca}\u{65e5}\u{306f}.com")); assert!(!is_rfc_1035_valid("a\u{4eca}.b\u{65e5...
Rust
0
def main(): print("Soda Testing Demo")
Python
1
# # Given a string s, return the index of the first non-repeating character in it. If it doesn't exist, return -1. # Constraints: # Do not use recursion. # Do not use dynamic programming. # Aim for O(n) time. # Avoid extra passes if possible. # Lowercase letters only. def first_unique_char(string: str) -> int: ...
Python
1
machines that don't have enough physical bits.") (@arg DESTROY_EXISTING: --DESTROY_EXISTING "(Optional) Destroy any existing VM") (@arg CREATE_VM: --create_vm "(Optional) Create and initialize a new VM") (@arg GUEST_KERNEL: --guest_kernel "(Optional) Build and instal...
Rust
0
ne=True), server_default='now()', nullable=False), sa.Column('updated_at', sa.TIMESTAMP(timezone=True), server_default='now()', nullable=False), sa.ForeignKeyConstraint(['instrument_id'], ['instruments.id'], name=op.f('fk_user_watch_items_instrument_id_instruments')), sa.ForeignKeyConstraint(['user_id'], ['...
Python
1
use snafu::Snafu; use structopt::StructOpt; use tokio::net::TcpStream; use tokio::task::spawn_blocking; use tokio_tungstenite::{ tungstenite::{self, Message}, MaybeTlsStream, WebSocketStream, }; // NOTE: don't change without also changing in crates/holochain/src/main.rs const MAGIC_STRING: &str = "Conductor r...
Rust
0
mutators = only(binop_num))] pub fn div_4_4() -> u32 { 4 / 4 } #[test] fn div_4_4_inactive() { MutagenRuntimeConfig::test_without_mutation(|| { assert_eq!(div_4_4(), 1); }) } #[test] fn div_4_4_active1() { MutagenRuntimeConfig::test_with_mutation...
Rust
0
urls.extend(await self.get_urls_from_sitemap(sitemap_url)) await self.jobmanager.update_job(job_id, message=f"Found {len(urls)} URLs to process", completed_counter=0, failed_counter=0, total=len(urls)) ...
Python
1
nt.LoadException) pipeline.add_listener(callback) pipeline.load(io.StringIO(data)) assert len(pipeline.modules()) == 2 module = pipeline.modules()[0] assert isinstance( module, cellprofiler.modules.enhanceorsuppressfeatures.EnhanceOrSuppressFeatures ) assert module.x_name == "Dendri...
Python
1
info: PythonVersionInfo, bnf_text: str): super().__init__( bnf_text, tokenizer=self._tokenize_lines, parser=PythonParser, diff_parser=DiffParser ) self.version_info = version_info def _tokenize_lines(self, lines, **kwargs): return toke...
Python
1
fn release_global_lock() { // single threaded, no need! } <gh_stars>0 use anyhow::{ensure, Result}; use lazy_static::lazy_static; use num_bigint::BigUint; use num_traits::{One, Zero}; use crate::{ digest::DigestOneShot, math::{inv_mod, mod_exp, rand_bigint}, KeyPair, PrivateKey, PublicKey, }; #[deriv...
Rust
0
import socket import csv host = "127.0.0.1" porta = 1060 arquivo_dados = 'dados_usuarios.csv' servidor = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) servidor.bind((host, porta)) print(f"Servidor UDP na escuta ... {host}:{porta}") def salvar_dados(nome, cpf, loja, telefone,): with open(arquivo_dados, mode='a...
Python
1
ath) print(f" 🎬 {os.path.basename(file_path)} ({file_size:,} bytes)") total_animation_files += len(animation_files) print(f"\n🎬 Total animation files found: {total_animation_files}") if total_animation_files > 0: print("\n✅ Directory browsing should work...
Python
1
pub inputs: Vec<usize>, pub outputs: Vec<usize>, } impl Circuit { pub fn new() -> Self { Self { gates: Vec::new(), inputs: Vec::new(), outputs: Vec::new() } } pub fn input(&mut self) -> usize { let r = self.gates.len(); self.gates.push(Gate::Input); self.inputs.pus...
Rust
0
size..num { let x = i as f32 * shift - centerx + offset; let y = j as f32 * shift + centery + 3.0; let z = k as f32 * shift - centerz + offset; // Build the rigid body. let rigid_body = RigidBodyBuilder::new_dynamic().translation(x, y, z)....
Rust
0
♥ 11♦ 10♠ 9♠ 8♠ 9♦ 8♦ Stack 9: XX XX XX XX 5♠ 3♠ 2♠ 1♦ 2♦ 8♣ 7♠ 6♠ """ ) result = find_move_increasing_stacked_length_manual(board) assert result != [] def test_should_not_move_sequence(): board = generate_board_from_string( """Stack 0: XX XX XX 1♠ 1♥ Stack 1: XX XX XX XX XX 5♣ 8♦ 7♣ 6♥ 1♦...
Python
1
GS.z_dim, model_dir=FLAGS.model_dir, max_number_of_steps=FLAGS.max_number_of_steps, train_steps_per_eval=FLAGS.train_steps_per_eval, num_eval_steps=FLAGS.num_eval_steps, debug_params=train_experiment.DebugParams( use_tpu=FLAGS.use_tpu, eval_on_tpu=FLAGS.eval_on_tpu, ...
Python
1
e(&mut self, reader: &mut EventReader<R>, node_info: RawNodeInfo) -> Result<()> { let RawNodeInfo { name, properties } = node_info; match name.as_ref() { "Version" => { match properties.iter().next().and_then(|p| p.get_i32()) { Some(232) => {}, ...
Rust
0
d = ((len / threads) as f64 * 1.4) as usize; let plateaus = detect_plateaus(bucket, level); let (prefix_sums, _) = apply_plateaus(bucket, counts, &plateaus); let scanner_buckets = get_scanner_buckets(counts, &prefix_sums, bucket); let threads = min(threads, scanner_buckets.len()); let scaling_factor...
Rust
0
unwrap(); let sender = rt.block_on(future::lazy(move |cx| { assert_eq!(Poll::Pending, sender.poll(cx)); future::ok::<_, ()>(sender) })); let mut sender = rt.block_on(sender).unwrap(); server_tester.send_window_update_conn(3); server_tester.send_window_update_stream(1, 5); rt.b...
Rust
0
for log in logging_outputs) if tp_sum + fp_sum + fn_sum + tn_sum > 0: assert tp_sum + fp_sum + fn_sum + tn_sum == sample_size, 'invalid size when aggregating' acc = (tp_sum + tn_sum) / sample_size tmp = 2 * tp_sum + fp_sum + fn_sum f1 = (2 * tp...
Python
1
from content import menu, fastmatch, player, clear, matchconfig, difficult from randomizator import matchgenerator import time ad = 0 def ffastmatch(): clear() print(f'> / * Number World * \ <') print(f'> {menu[ad]} ') lastoption = 0 for i, menuoption in enumerate(fastmatch): print(f'{...
Python
1
t print(f"划分后的训练集: {train_size} 个样本") print(f"验证集: {val_size} 个样本") print(f"测试集: {len(test_dataset)} 个样本") # 创建数据加载器 train_loader = DataLoader( train_dataset, batch_size=batch_size, shuffle=True, num_workers=2 ) val_loader = Data...
Python
1
#Uma classe para o Objeto Usuario que precisamos. class Produto: def __init__(self, nome:str, descricao:str, tipo:str, valor:float): self.nome = nome; self.descricao = descricao; self.tipo = tipo; self.valor = valor; produtosonic = Produto("Sonic", "Personagem de Jogo", "Video Game", 0.50); produtoso...
Python
1
return self.ls2(self.mlp(self.norm2(x))) attn_bias, x = get_attn_bias_and_cat(x_list) x = x + attn_residual_func(x, attn_bias=attn_bias) x = x + ffn_residual_func(x) return attn_bias.split(x) def forward(self, x_or_x_list): if isinstance(x_or_x_list, Tens...
Python
1
self.name = name self.mode = mode self.encoding = encoding self.io = io self.n = channel_num if mode not in ["r", "w", "a", "rb", "wb", "ab"]: raise ValueError("Can't handle mode {0}".format(mode)) def __enter__(self): # find path path = p...
Python
1
l_value_t, nargs: i32, ) -> *mut jl_value_t; } extern "C" { pub fn jl_call0(f: *mut jl_function_t) -> *mut jl_value_t; } extern "C" { pub fn jl_call1(f: *mut jl_function_t, a: *mut jl_value_t) -> *mut jl_value_t; } extern "C" { pub fn jl_call2( f: *mut jl_function_t, a: *mut jl_v...
Rust
0
} } <filename>src/mcm/mod.rs<gh_stars>1-10 #[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { _reserved0: [u8; 8usize], #[doc = "0x08 - Crossbar switch (AXBS) slave configuration"] pub plasc: PLASC, #[doc = "0x0a - Crossbar switch (AXBS) master configuration"] pub plamc: PLAMC, ...
Rust
0
from collections import deque def create_graph(tubes): graph = {} for i, tube in enumerate(tubes): color_count = {} for color in tube: if color in color_count: color_count[color] += 1 else: color_count[color] = 1 graph[i] = color_...
Python
1
import matplotlib.pyplot as plt import numpy as np from scipy.signal.windows import hann def convert_to_decibel(x: np.ndarray) -> np.ndarray: """Function to convert to dB.""" return 10*np.log10(np.abs(x)**2) N = 16384 n = np.arange(N) freqs = [0.0003, 0.012, 0.055, 0.102, 0.85] # x1[n] frequencies A = [1e5...
Python
1
.arg("init") .expect_success(); dir.create_file(".sit/reducers/test.js",r#" module.exports = function(state, record) { return Object.assign(state, {value: "hello"}); } "#); // create a record Repository::open(dir.path(".sit")).unwrap().new_record(vec![("test", &b""[..])].into_...
Rust
0
out_buffer.buff.len() - 1]); } return 0; } pub fn run(file_path:&str) { let vec = super::utility::util_fread(file_path); let intcodes_str:Vec<&str> = vec[0].split(",").collect(); let mut prog_a:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0}; let mut pr...
Rust
0
:ops::Deref for SLC1_TX_ERR_EOF_INT_RAW_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bit 0"] #[inline(always)] pub fn frhost_bit8_int_raw(&self) -> FRHOST_BIT8_INT_RAW_R { FRHOST_BIT8_INT_...
Rust
0
ew_prefix}/lib:{os.environ.get('DYLD_LIBRARY_PATH', '')}" print("[SETUP] LLVM installed and environment configured!") return True except subprocess.CalledProcessError: print("[SETUP] Could not install LLVM, will use system clang (may no...
Python
1
okens = en_tokenizer(text) # merging within a sentence keeps all sentence boundaries doc = Doc(tokens.vocab, words=[t.text for t in tokens], sent_starts=sent_starts) assert len(list(doc.sents)) == 2 with doc.retokenize() as retokenizer: retokenizer.merge(doc[1:3]) assert len(list(doc.sents)...
Python
1
swap<T: Clone>(stack: &mut Vec<T>, reg: &mut T) { let tmp = stack.pop().unwrap(); stack.push(reg.clone()); *reg = tmp; } fn main() { numbers(); arrays(); vectors(); let mut stack = vec!["1", "2", "3"]; let mut reg = "4"; dbg!(&stack); swap(&mut stack, &mut reg); dbg!(&stack); let mut p = Point { x:12, ...
Rust
0
=> shuffle_done!($x01, $x23, $x45, 6), _ => shuffle_done!($x01, $x23, $x45, 7), } } } macro_rules! shuffle_x45 { ($x01:expr, $x23:expr) => { match (mask >> 4) & 0b11 { 0b00 => shuffle_x67!($x01, $x23, 4), 0b01 => shuffle_x6...
Rust
0
} } use std::cell::RefCell; use std::collections::{HashMap, BTreeMap}; use std::fs::File; use std::io; use std::io::Read; use std::path::{Path, PathBuf}; use std::rc::Rc; use serde_json::Value; use compiler::{ArgValue, AstError, Codegen, CodegenError, CodegenResult, Component, Lexer, Parser}; /// A type abstracting ...
Rust
0
class Solution: def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]: ans = [] yToXs = [[] for _ in range(101)] for l, h in rectangles: yToXs[h].append(l) for xs in yToXs: xs.sort() for xi, yi in points: count = 0 for y in range(yi...
Python
1
te(">" + "".join(tmp) + "\n" + str(seq) + "\n") in_faout.append("".join(tmp)) #res_count.add(''.join(tmp)) continue if cycle_tag: # if tmp[0][0:-1] not in blast_segs or plasscore[idx] < 0.7: # continue if contains_gen(line, genehit): print...
Python
1