file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
main.rs
num() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess:...
fn do_init() { //mut and default immutable let mut i = 0; println!("init i :{}", i); i = 100; println!("change i: {}", i); // const declare const MAX_POINTS: u32 = 100_000; println!("constant variable MAX_POINT: {}", MAX_POINTS); //shadowing let x = 5; let x = x + 1; l...
e { width: 10, height: 40, }; let rect3 = Rectangle { width: 60, height: 45, }; println!("rect1 area: {}", rect1.area()); println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3)); println!("re...
identifier_body
tgsw.rs
use crate::numerics::Torus32; use crate::polynomial::{IntPolynomial, Polynomial, TorusPolynomial}; use crate::tlwe::{TLweKey, TLweParameters, TLweSample}; use itertools::Itertools; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub struct TGswParams { /// Decompositi...
for j in 0..n as usize { let temp1 = (buf[j] >> decal) & mask_mod as i32; res_p[j] = temp1 - half_bg; } } } #[cfg(test)] mod tests { use super::*; use crate::polynomial::TorusPolynomial; fn generate_parameters() -> Vec<TGswParams> { vec![ TGswParams::new(4, 8, TLweParameters::ne...
{ let n = params.tlwe_params.n; let l = params.l; let bg_bit = params.bg_bit; let mask_mod = params.mask_mod; let half_bg = params.half_bg; let offset = params.offset; // First, add offset to everyone let buf: Vec<i32> = sample .coefs .iter() .map(|c| c.wrapping_add(offset as i32)) .col...
identifier_body
tgsw.rs
use crate::numerics::Torus32; use crate::polynomial::{IntPolynomial, Polynomial, TorusPolynomial}; use crate::tlwe::{TLweKey, TLweParameters, TLweSample}; use itertools::Itertools; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub struct TGswParams { /// Decompositi...
() { for params in generate_parameters() { let mut sample = TGswSample::new(&params); let kpl = params.kpl; let l = params.l; let k = params.tlwe_params.k; let n = params.tlwe_params.n; let h = &params.h; let alpha = 4.2; fully_random_tgsw(&mut sample, alpha, &params...
test_add_h
identifier_name
tgsw.rs
use crate::numerics::Torus32; use crate::polynomial::{IntPolynomial, Polynomial, TorusPolynomial}; use crate::tlwe::{TLweKey, TLweParameters, TLweSample}; use itertools::Itertools; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub struct TGswParams { /// Decompositi...
assert_eq!( new_polynomial.coefs[0], // Should this be i == u? old_polynomial.coefs[0] + (if j == u { dbg!(h[i]) } else { 0 }) ); assert_eq!(new_polynomial.coefs[1..], old_polynomial.coefs[1..]); } } } } } }
{ assert!(new_polynomial .coefs .iter() .zip_eq(old_polynomial.coefs.iter()) .all(|(a, b)| a == b)); }
conditional_block
tgsw.rs
use crate::numerics::Torus32; use crate::polynomial::{IntPolynomial, Polynomial, TorusPolynomial}; use crate::tlwe::{TLweKey, TLweParameters, TLweSample}; use itertools::Itertools; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub struct TGswParams { /// Decompositi...
// ); // } } else { assert!(new_polynomial .coefs .iter() .zip_eq(old_polynomial.coefs.iter()) .all(|(a, b)| a == b)); } assert_eq!( new_polynomial.coefs[0], // Should th...
random_line_split
trie.rs
use std::fmt::Debug; use super::bit_cache::BitCache; use crate::double_array::DoubleArray; use bincode; use serde::Serialize; use serde::de::DeserializeOwned; struct Node<T> { key : u8, values: Vec<T>, nexts : Vec<Node<T>>, } /// トライ木の実装。 /// ダブル配列は直接構築することはできないので、トライ木を構築してから変換することで構築する。 /// /// # Exa...
while!stack.is_empty() { let (curr_idx, mut node) = stack.pop().unwrap(); bit_cache.update_start(); // base値を探索・セット if!node.values.is_empty() { // valuesが存在する場合はkey=255のノードとして計算する node.nexts.push(Node { key: u8::max_value(), values...
let mut stack: Vec<(usize, Node<T>)> = Vec::with_capacity(self.len); if !self.root.nexts.is_empty() { stack.push((1, self.root)); }
random_line_split
trie.rs
use std::fmt::Debug; use super::bit_cache::BitCache; use crate::double_array::DoubleArray; use bincode; use serde::Serialize; use serde::de::DeserializeOwned; struct Node<T> { key : u8, values: Vec<T>, nexts : Vec<Node<T>>, } /// トライ木の実装。 /// ダブル配列は直接構築することはできないので、トライ木を構築してから変換することで構築する。 /// /// # Exa...
/// /// # Arguments /// /// * `len` - ダブル配列の初期サイズ pub fn to_double_array(self) -> Result<DoubleArray<T>, std::io::Err or> { let max_key = u8::max_value() as usize + 1; // keyが取りうる値のパターン let mut len = if max_key > (4 * self.len) { max_key } else { 4 * self.len }; let mut ...
> { return None; } } } if node.values.is_empty() { None } else { Some(&node.values) } } /// トライ木をダブル配列に変換する /// /// # Panics /// dataをバイト列に変換できなかった場合にpanicする。 /// /// # Errors ///
identifier_body
trie.rs
use std::fmt::Debug; use super::bit_cache::BitCache; use crate::double_array::DoubleArray; use bincode; use serde::Serialize; use serde::de::DeserializeOwned; struct Node<T> { key : u8, values: Vec<T>, nexts : Vec<Node<T>>, } /// トライ木の実装。 /// ダブル配列は直接構築することはできないので、トライ木を構築してから変換することで構築する。 /// /// # Exa...
identifier_name
trie.rs
use std::fmt::Debug; use super::bit_cache::BitCache; use crate::double_array::DoubleArray; use bincode; use serde::Serialize; use serde::de::DeserializeOwned; struct Node<T> { key : u8, values: Vec<T>, nexts : Vec<Node<T>>, } /// トライ木の実装。 /// ダブル配列は直接構築することはできないので、トライ木を構築してから変換することで構築する。 /// /// # Exa...
o::Error> { let max_key = u8::max_value() as usize + 1; // keyが取りうる値のパターン let mut len = if max_key > (4 * self.len) { max_key } else { 4 * self.len }; let mut base_arr: Vec<u32> = vec![0; len]; let mut check_arr: Vec<u32> = vec![0; len]; let mut data_arr: Vec<u8> = Vec::w...
ray(self) -> Result<DoubleArray<T>, std::i
conditional_block
main.rs
extern crate jemallocator; extern crate num_cpus; extern crate quick_protobuf; mod osm_pbf; use crossbeam_channel::{bounded, unbounded}; use crossbeam_utils::thread; use memmap::MmapOptions; use osm_pbf::{Blob, BlobHeader, DenseNodes, Info, Node, PrimitiveBlock, Relation, Way}; use quick_protobuf::{BytesReader, Messa...
{ timestamp_min: i64, timestamp_max: i64, nodes: u64, ways: u64, relations: u64, lon_min: f64, lon_max: f64, lat_min: f64, lat_max: f64, } fn main() { let args: Vec<_> = std::env::args_os().collect(); let filename = &args[1]; let orig_handler = panic::take_hook(); ...
OsmStats
identifier_name
main.rs
extern crate jemallocator; extern crate num_cpus; extern crate quick_protobuf; mod osm_pbf; use crossbeam_channel::{bounded, unbounded}; use crossbeam_utils::thread; use memmap::MmapOptions; use osm_pbf::{Blob, BlobHeader, DenseNodes, Info, Node, PrimitiveBlock, Relation, Way}; use quick_protobuf::{BytesReader, Messa...
let (sender, receiver) = bounded::<Blob>(WORK_BOUND); let (return_sender, return_received) = unbounded::<OsmStats>(); thread::scope(|s| { for _ in 0..thread_count { let cloned_receiver = receiver.clone(); let cloned_return_sender = return_sender.clone(); s.spawn(...
random_line_split
main.rs
extern crate jemallocator; extern crate num_cpus; extern crate quick_protobuf; mod osm_pbf; use crossbeam_channel::{bounded, unbounded}; use crossbeam_utils::thread; use memmap::MmapOptions; use osm_pbf::{Blob, BlobHeader, DenseNodes, Info, Node, PrimitiveBlock, Relation, Way}; use quick_protobuf::{BytesReader, Messa...
received_messages += 1; } Ok(format!("{:#?}", osm_stats)) }) .unwrap() } fn handle_block(mut osm_stats: &mut OsmStats, blob: &Blob, buffer: &mut Vec<u8>) { let zlib_data_ref = blob.zlib_data.as_ref(); let tried_block = if blob.raw.is_some() { let bytes = blob.raw.as_...
{ osm_stats.lon_min = worker_stats.lon_min }
conditional_block
main.rs
extern crate jemallocator; extern crate num_cpus; extern crate quick_protobuf; mod osm_pbf; use crossbeam_channel::{bounded, unbounded}; use crossbeam_utils::thread; use memmap::MmapOptions; use osm_pbf::{Blob, BlobHeader, DenseNodes, Info, Node, PrimitiveBlock, Relation, Way}; use quick_protobuf::{BytesReader, Messa...
fn handle_latitude(osm_stats: &mut OsmStats, latitude: i64, primitive: &PrimitiveBlock) { let latitude_f = 0.000000001 * ((primitive.lat_offset + ((primitive.granularity as i64) * latitude)) as f64); if latitude_f < osm_stats.lat_min { osm_stats.lat_min = latitude_f } if latitude_f > o...
{ let millisec_stamp = timestamp * (date_granularity as i64); if millisec_stamp < osm_stats.timestamp_min { osm_stats.timestamp_min = millisec_stamp } if millisec_stamp > osm_stats.timestamp_max { osm_stats.timestamp_max = millisec_stamp } }
identifier_body
lptim.rs
use core::marker::PhantomData; use embedded_time::duration::Microseconds; use embedded_time::rate::Hertz; use void::Void; mod sealed { pub trait Sealed {} } /// Low-Power Timer counting in one-shot mode. pub enum OneShot {} /// Low-Power Timer counting in periodic mode. pub enum Periodic {} /// Low-Power Timer...
{ /// Drive LPTIM with APB1 clock. Apb1 = 0b00, /// Drive LPTIM with Low-Speed Internal (LSI) clock. /// /// The user has to ensure that the LSI clock is running, or the timer won't /// start counting. Lsi = 0b01, /// Drive LPTIM with Internal 16 MHz clock. Hsi16 = 0b10, /// ...
ClockSrc
identifier_name
lptim.rs
use core::marker::PhantomData; use embedded_time::duration::Microseconds; use embedded_time::rate::Hertz; use void::Void; mod sealed { pub trait Sealed {} } /// Low-Power Timer counting in one-shot mode. pub enum OneShot {} /// Low-Power Timer counting in periodic mode. pub enum Periodic {} /// Low-Power Timer...
} impl LpTimer<Encoder> { /// Initializes the Low-Power Timer in encoder mode. /// /// The `start` method must be called to enable the encoder input. pub fn init_encoder( lptim: LPTIM, pwr: &mut PWR, rcc: &mut Rcc, clk: ClockSrc, (pb5, pb7): (gpiob::PB5<gpio::An...
{ Self::init(lptim, pwr, rcc, clk) }
identifier_body
lptim.rs
; use core::marker::PhantomData; use embedded_time::duration::Microseconds; use embedded_time::rate::Hertz; use void::Void; mod sealed { pub trait Sealed {} } /// Low-Power Timer counting in one-shot mode. pub enum OneShot {} /// Low-Power Timer counting in periodic mode. pub enum Periodic {} /// Low-Power Time...
// The slowest LPTIM clock source is LSE at 32768 Hz, the fastest CPU clock is ~80 MHz. At // these conditions, one cycle of the LPTIM clock takes 2500 CPU cycles, so sleep for 5000. cortex_m::asm::delay(5000); // ARR can only be changed while the timer is *en*abled self.lptim.a...
self.lptim.cr.write(|w| w.enable().set_bit()); // "After setting the ENABLE bit, a delay of two counter clock is needed before the LPTIM is // actually enabled."
random_line_split
campaign_loader.rs
use std::path::{Path, PathBuf}; use std::ffi::OsStr; //For image loading and hooking into the Task system use coffee::{ load::Task, graphics::Image, }; use coffee::graphics::Gpu; //For config file loading and parsing use config::*; //To locate all config files extern crate walkdir; use walkdir::WalkDir; u...
else { error!("[Asset Loading] Failed to load asset relating to config file {}. {}", config_path.to_str().unwrap(), "Please review previous warnings." ); } } } //make sure file is one of the right formats for configuration files fn is_config_...
{ info!("[Asset Loading] Loaded asset relating to config file {}", config_path.to_str().unwrap()); }
conditional_block
campaign_loader.rs
use std::path::{Path, PathBuf}; use std::ffi::OsStr; //For image loading and hooking into the Task system use coffee::{ load::Task, graphics::Image, }; use coffee::graphics::Gpu; //For config file loading and parsing use config::*; //To locate all config files extern crate walkdir; use walkdir::WalkDir; u...
// assume image path is given as relative to config path hence taking the parent as a starting point. let audio_path = match config_path.parent() { Some(dir_path) => dir_path.join(file.ok().expect("File value is missing while loading.")), //getting parent from path failed somehow. ...
); return false; } };
random_line_split
campaign_loader.rs
use std::path::{Path, PathBuf}; use std::ffi::OsStr; //For image loading and hooking into the Task system use coffee::{ load::Task, graphics::Image, }; use coffee::graphics::Gpu; //For config file loading and parsing use config::*; //To locate all config files extern crate walkdir; use walkdir::WalkDir; u...
//creates a task for loading a config file and it's resources fn load_config_task(file_path: &PathBuf) -> Task<Config> { //needed so closure below can capture let path = file_path.clone(); Task::new(move || { //coerce into string value or return error let str_path = ...
{ coffee::Error::IO( std::io::Error::new( std::io::ErrorKind::Other, msg ) ) }
identifier_body
campaign_loader.rs
use std::path::{Path, PathBuf}; use std::ffi::OsStr; //For image loading and hooking into the Task system use coffee::{ load::Task, graphics::Image, }; use coffee::graphics::Gpu; //For config file loading and parsing use config::*; //To locate all config files extern crate walkdir; use walkdir::WalkDir; u...
(path: &str, gpu: &mut Gpu, asset_db: &mut AssetDatabase) { //load all config files under the campain folder let mut campaign_config_paths = find_config_files(path); //for each config file, load it then load the associated asset while let Some(config_path) = campaign_config_paths.pop() { ...
load_campaign_data
identifier_name
mod.rs
use std::borrow::Cow; use std::pin::Pin; use std::sync::{ atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, Arc, }; use std::task::{Context, Poll}; use std::time::{Duration, Instant}; use backoff::backoff::Backoff; use futures::prelude::*; use futures::task::AtomicWaker; use log::{debug, error, warn}; us...
fn str_sanitize(input: String) -> String { match memchr(0, input.as_bytes()) { Some(_) => input.replace(char::from(0), ""), None => input, } }
false => Poll::Pending, } } }
random_line_split
mod.rs
use std::borrow::Cow; use std::pin::Pin; use std::sync::{ atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, Arc, }; use std::task::{Context, Poll}; use std::time::{Duration, Instant}; use backoff::backoff::Backoff; use futures::prelude::*; use futures::task::AtomicWaker; use log::{debug, error, warn}; us...
(self: Pin<&mut Self>, item: Vec<imageboard::Post>) -> Result<(), Self::Error> { if item.len() > 0 { self.inner .inflight_posts .fetch_add(item.len(), Ordering::AcqRel); self.inner.process_tx.send(Some(item)).unwrap(); } Ok(()) } fn ...
start_send
identifier_name
mod.rs
use std::borrow::Cow; use std::pin::Pin; use std::sync::{ atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, Arc, }; use std::task::{Context, Poll}; use std::time::{Duration, Instant}; use backoff::backoff::Backoff; use futures::prelude::*; use futures::task::AtomicWaker; use log::{debug, error, warn}; us...
self.inner.flush_waker.register(cx.waker()); match self.inner.is_empty() { true => Poll::Ready(Ok(())), false => Poll::Pending, } } fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { let _ = self.inner.process_tx.sen...
{ return Poll::Ready(Err(Error::ArchiveError)); }
conditional_block
mod.rs
use std::borrow::Cow; use std::pin::Pin; use std::sync::{ atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, Arc, }; use std::task::{Context, Poll}; use std::time::{Duration, Instant}; use backoff::backoff::Backoff; use futures::prelude::*; use futures::task::AtomicWaker; use log::{debug, error, warn}; us...
fn is_empty(&self) -> bool { let posts = self.inflight_posts.load(Ordering::Acquire); posts == 0 } fn has_failed(&self) -> bool { return self.fail_on_save_error && self.failed.load(Ordering::Relaxed); } } impl Sink<Vec<imageboard::Post>> for Search { type Error = Error; ...
{ let posts = self.inflight_posts.load(Ordering::Acquire); posts < self.max_inflight_posts }
identifier_body
metadata.rs
from a cargo workspace root fn generate_lockfile(&self, crate_root_dir: &Utf8Path) -> Result<Lockfile> { let lockfile_path = crate_root_dir.join("Cargo.lock"); // Generate lockfile let output = std::process::Command::new(&self.cargo_bin_path) .arg("generate-lockfile") .current_dir(crate_root_d...
} } let metadata = self .metadata_fetcher .fetch_metadata(utf8_cargo_dir, /*include_deps=*/ true)?; // In this function because it's metadata, even though it's not returned by `cargo-metadata` let platform_features = match self.settings.as_ref() { Some(settings) => get_per_platf...
{ checksums.insert( package_ident(package.name.as_ref(), &package.version.to_string()), checksum.to_string(), ); }
conditional_block
metadata.rs
} impl MetadataFetcher for CargoMetadataFetcher { fn fetch_metadata(&self, working_dir: &Utf8Path, include_deps: bool) -> Result<Metadata> { let mut command = MetadataCommand::new(); if!include_deps { command.no_deps(); } command .cargo_path(&self.cargo_bin_path) .current_dir(worki...
{ CargoMetadataFetcher { cargo_bin_path: cargo_bin_path(), } }
identifier_body
metadata.rs
did not contain a Cargo.toml file: `{}`", crate_member_id_re.as_str(), workspace_member_directory ))); } // Copy the Cargo.toml files into the temp directory to match the directory structure on disk let path_diff = diff_paths( &workspace_member_directory, ...
random_line_split
metadata.rs
{ cargo_bin_path: Utf8PathBuf, } impl LockfileGenerator for CargoLockfileGenerator { /// Generate lockfile information from a cargo workspace root fn generate_lockfile(&self, crate_root_dir: &Utf8Path) -> Result<Lockfile> { let lockfile_path = crate_root_dir.join("Cargo.lock"); // Generate lockfile ...
CargoLockfileGenerator
identifier_name
main.rs
extern crate gl; extern crate glfw; extern crate time; extern crate point; use std::sync::mpsc::channel; use std::thread::spawn; use std::mem; use std::ptr; use std::ffi::CString; use std::fs::File; use std::io::Read; use std::fmt::{ Display, Formatter }; use std::fmt; use std::cmp::{Eq, PartialEq}; use gl::types::*;...
let new_tile_spec = TileSpecification { pixels: pixels, center: center, zoom: zoom }; let needs_new_tile = match current_tile { None => true, Some(ref tile) => { tile.specification!= new_tile_spec }, }; if tile_queue_empty && needs_n...
unsafe { gl::ClearColor(0.2, 0.1, 0.05, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT); } unsafe { set_viewport(program, zoom, &pixels, &center) }; match current_tile { Some(ref tile) => { draw_fractal(&tile.po...
conditional_block
main.rs
extern crate gl; extern crate glfw; extern crate time; extern crate point; use std::sync::mpsc::channel; use std::thread::spawn; use std::mem; use std::ptr; use std::ffi::CString; use std::fs::File; use std::io::Read; use std::fmt::{ Display, Formatter }; use std::fmt; use std::cmp::{Eq, PartialEq}; use gl::types::*;...
unsafe { set_viewport(program, zoom, &pixels, &center) }; match current_tile { Some(ref tile) => { draw_fractal(&tile.positions, &tile.colors, vertex_buffer, color_buffer, &mut window); } None => { /* no tile ready yet */ } ...
gl::Clear(gl::COLOR_BUFFER_BIT); }
random_line_split
main.rs
extern crate gl; extern crate glfw; extern crate time; extern crate point; use std::sync::mpsc::channel; use std::thread::spawn; use std::mem; use std::ptr; use std::ffi::CString; use std::fs::File; use std::io::Read; use std::fmt::{ Display, Formatter }; use std::fmt; use std::cmp::{Eq, PartialEq}; use gl::types::*;...
fn main() { let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(WindowHint::ContextVersion(3, 2)); glfw.window_hint(WindowHint::OpenGlForwardCompat(true)); glfw.window_hint(WindowHint::OpenGlProfile(OpenGlProfileHint::Core)); let x_initial_points = 500; let y_initial_po...
let points = colors.len() / 3; unsafe { load_vector_in_buffer(vertex_buffer, &positions); load_vector_in_buffer(color_buffer, &colors); gl::DrawArrays(gl::POINTS, 0, points as i32); window.swap_buffers(); } }
identifier_body
main.rs
extern crate gl; extern crate glfw; extern crate time; extern crate point; use std::sync::mpsc::channel; use std::thread::spawn; use std::mem; use std::ptr; use std::ffi::CString; use std::fs::File; use std::io::Read; use std::fmt::{ Display, Formatter }; use std::fmt; use std::cmp::{Eq, PartialEq}; use gl::types::*;...
buffer: u32, values: &Vec<GLfloat>) { gl::BindBuffer(gl::ARRAY_BUFFER, buffer); gl::BufferData(gl::ARRAY_BUFFER, (values.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, mem::transmute(&values[0]), gl::STATIC_DRAW); } unsafe fn bind_attribute_to_buffer(...
oad_vector_in_buffer(
identifier_name
model.rs
use std::collections::{BTreeMap, HashMap}; use task::*; use task_ref::TaskRef; use std::io; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Effect { AddTask(Task), ChangeTaskTags { uuid: Uuid, added: Tags, removed: Tags, }, ChangeTaskState(Uuid, TaskStat...
fn test_short_uuid_ref() { for s in vec!["abcdef", "123abc", "000000"] { assert_eq!(TaskRef::from_str(s), Ok(TaskRef::ShortUUID(s.into()))); } assert!( TaskRef::from_str("abcde").is_err(), "Short-UUID with len of 5" ); assert!( ...
#[test]
random_line_split
model.rs
use std::collections::{BTreeMap, HashMap}; use task::*; use task_ref::TaskRef; use std::io; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Effect { AddTask(Task), ChangeTaskTags { uuid: Uuid, added: Tags, removed: Tags, }, ChangeTaskState(Uuid, TaskStat...
pub fn apply_effect(&mut self, effect: &Effect) -> () { use Effect::*; match effect.clone() { AddTask(task) => { self.add_task(task); } ChangeTaskTags { uuid, added, removed, } => { ...
{ let mut model = Self::new(); for effect in effects { model.apply_effect(&effect) } model.is_dirty = false; model }
identifier_body
model.rs
use std::collections::{BTreeMap, HashMap}; use task::*; use task_ref::TaskRef; use std::io; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Effect { AddTask(Task), ChangeTaskTags { uuid: Uuid, added: Tags, removed: Tags, }, ChangeTaskState(Uuid, TaskStat...
ChangeTaskTags { uuid, added, removed, } => { self.change_task_tags(&uuid, added, removed); } ChangeTaskState(uuid, state) => { self.change_task_state(&uuid, state); } ...
{ self.add_task(task); }
conditional_block
model.rs
use std::collections::{BTreeMap, HashMap}; use task::*; use task_ref::TaskRef; use std::io; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Effect { AddTask(Task), ChangeTaskTags { uuid: Uuid, added: Tags, removed: Tags, }, ChangeTaskState(Uuid, TaskStat...
(&self) -> bool { self.is_dirty } } #[cfg(test)] mod tests { use super::*; use chrono; use std::str::FromStr; use uuid::Uuid; use {Priority, Task, TaskState}; #[test] fn test_add_delete_task() { let mut m = Model::new(); let t = Task::new("foo"); m.add_t...
is_dirty
identifier_name
lib.rs
#![warn(rust_2018_idioms)] #![cfg_attr(feature = "strict", deny(warnings))] use std::num::NonZeroUsize; use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{ parse_macro_input, Error, Expr, ExprLit, ExprRange, FnArg, Index, ItemFn, Li...
(attr: TokenStream, item: TokenStream) -> TokenStream { let punctuated_args = parse_macro_input!(attr with Punctuated<LitStr, Token![,]>::parse_separated_nonempty); let input = parse_macro_input!(item as ItemFn); match create_hook(punctuated_args, input) { Ok(ts) => ts, Err(err) => ...
hook
identifier_name
lib.rs
#![warn(rust_2018_idioms)] #![cfg_attr(feature = "strict", deny(warnings))] use std::num::NonZeroUsize; use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{ parse_macro_input, Error, Expr, ExprLit, ExprRange, FnArg, Index, ItemFn, Li...
fn create_impl_arguments_parameters(range: ExprRange) -> Result<TokenStream, Error> { let span = range.span(); let start = range .from .ok_or_else(|| Error::new(span, "Tuple length range must have a lower bound"))?; let start = parse_range_bound(*start)?; let end = range .to ...
{ let range = parse_macro_input!(input as ExprRange); match create_impl_arguments_parameters(range) { Ok(ts) => ts, Err(err) => err.to_compile_error().into(), } }
identifier_body
lib.rs
#![warn(rust_2018_idioms)] #![cfg_attr(feature = "strict", deny(warnings))] use std::num::NonZeroUsize; use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{ parse_macro_input, Error, Expr, ExprLit, ExprRange, FnArg, Index, ItemFn, Li...
let name = sig.ident; let return_type = sig.output; let typecheck_return_type = match &return_type { ReturnType::Default => quote! { () }, ReturnType::Type(_, ty) => quote! { #ty }, }; let hook_name = format_ident!("{}_hook", name); let hook_args = sig.inputs; let mut this_...
random_line_split
imaginate.rs
use crate::wasm_application_io::WasmEditorApi; use core::any::TypeId; use core::future::Future; use futures::{future::Either, TryFutureExt}; use glam::{DVec2, U64Vec2}; use graph_craft::imaginate_input::{ImaginateController, ImaginateMaskStartingFill, ImaginatePreferences, ImaginateSamplingMethod, ImaginateServerStatus...
fn initiate_server_check_maybe_fail(&mut self) -> Result<Option<ImaginateFuture>, Error> { use futures::future::FutureExt; let Some(client) = &self.client else { return Ok(None); }; if self.pending_server_check.is_some() { return Ok(None); } self.server_status = ImaginateServerStatus::Checking; l...
{ match parse_url(name) { Ok(url) => self.host_name = url, Err(err) => self.server_status = ImaginateServerStatus::Failed(err.to_string()), } }
identifier_body
imaginate.rs
use crate::wasm_application_io::WasmEditorApi; use core::any::TypeId; use core::future::Future; use futures::{future::Either, TryFutureExt}; use glam::{DVec2, U64Vec2}; use graph_craft::imaginate_input::{ImaginateController, ImaginateMaskStartingFill, ImaginatePreferences, ImaginateSamplingMethod, ImaginateServerStatus...
}; }; let response = match response { Ok(response) => response.and_then(reqwest::Response::error_for_status).map_err(Error::Request)?, Err(_aborted) => { set_progress(ImaginateStatus::Terminating); let url = join_url(&base_url, SDAPI_TERMINATE)?; let request = client.post(url).build().map_err(Error::...
{ if let Ok(ProgressResponse { progress }) = progress { set_progress(ImaginateStatus::Generating(progress * 100.)); } response_future }
conditional_block
imaginate.rs
use crate::wasm_application_io::WasmEditorApi; use core::any::TypeId; use core::future::Future; use futures::{future::Either, TryFutureExt}; use glam::{DVec2, U64Vec2}; use graph_craft::imaginate_input::{ImaginateController, ImaginateMaskStartingFill, ImaginatePreferences, ImaginateSamplingMethod, ImaginateServerStatus...
(futures::future::AbortHandle); impl ImaginateTerminationHandle for ImaginateFutureAbortHandle { fn terminate(&self) { self.0.abort() } } #[derive(Debug)] enum Error { UrlParse { text: String, err: <&'static str as TryInto<Url>>::Error }, ClientBuild(reqwest::Error), RequestBuild(reqwest::Error), Request(reqw...
ImaginateFutureAbortHandle
identifier_name
imaginate.rs
use crate::wasm_application_io::WasmEditorApi; use core::any::TypeId; use core::future::Future; use futures::{future::Either, TryFutureExt}; use glam::{DVec2, U64Vec2}; use graph_craft::imaginate_input::{ImaginateController, ImaginateMaskStartingFill, ImaginatePreferences, ImaginateSamplingMethod, ImaginateServerStatus...
width: res.x, height: res.y, restore_faces: improve_faces.await, tiling: tiling.await, negative_prompt: negative_prompt.await, sampler_index, }; let request_builder = if adapt_input_image.await { let base64_data = image_to_base64(image)?; let request_data = ImaginateImageToImageRequest { common: co...
seed: seed.await, steps: samples.await, cfg_scale: prompt_guidance.await as f64,
random_line_split
nn.rs
//! Neural networks use crate::matrix::*; /// a network #[derive(Debug)] pub struct Network { // activation functions activations: Vec<Box<dyn Activation>>, // topology topology: Vec<usize>, // weights weights: Vec<Matrix> } impl Network { /// create a new random network with the given top...
/// back propagation pub fn backward(&mut self, inputs :&[f64], outputs :Vec<Vec<f64>>, target :&[f64], learning_rate: f64 ) { debug!("Error: {}", error(target, outputs.last().expect("outputs"))); let l = outputs.len(); let mut new_weights = self.weights.clone(); let mut new_ta...
{ assert_eq!(self.topology[0],inputs.len()); let mut m = Matrix::new(1,inputs.len(),inputs); let mut all_results = Vec::with_capacity(self.topology.len() - 1); self.weights.iter().enumerate().for_each(| (ix,wm) | { add_column(&mut m,vec!(1.0)); m = mul(&m,wm); ...
identifier_body
nn.rs
//! Neural networks use crate::matrix::*; /// a network #[derive(Debug)] pub struct Network { // activation functions activations: Vec<Box<dyn Activation>>, // topology topology: Vec<usize>, // weights weights: Vec<Matrix> } impl Network { /// create a new random network with the given top...
} } /// Softmax activation function #[derive(Debug)] pub struct Softmax{} impl Activation for Softmax { fn activate(&self, inputs: &[f64]) -> Vec<f64> { softmax(inputs) } fn derive(&self, outputs: &[f64], index: usize) -> f64 { let s: f64 = outputs.iter().sum(); let el = out...
{0.0}
conditional_block
nn.rs
//! Neural networks use crate::matrix::*; /// a network #[derive(Debug)] pub struct Network { // activation functions activations: Vec<Box<dyn Activation>>, // topology topology: Vec<usize>, // weights weights: Vec<Matrix> } impl Network { /// create a new random network with the given top...
inputs }; let previous_size = size(&weights).0; debug!("previous size: {}",previous_size); debug!("weights to update: {:?}",size(&weights)); new_targets.push(vec!(0.0; previous_size)); for (i,o) in outputs[rev_order]...
} else {
random_line_split
nn.rs
//! Neural networks use crate::matrix::*; /// a network #[derive(Debug)] pub struct Network { // activation functions activations: Vec<Box<dyn Activation>>, // topology topology: Vec<usize>, // weights weights: Vec<Matrix> } impl Network { /// create a new random network with the given top...
(&self, inputs :&[f64]) -> Vec<Vec<f64>> { assert_eq!(self.topology[0],inputs.len()); let mut m = Matrix::new(1,inputs.len(),inputs); let mut all_results = Vec::with_capacity(self.topology.len() - 1); self.weights.iter().enumerate().for_each(| (ix,wm) | { add_column(&mut m,ve...
forward
identifier_name
vm.rs
Translation to Rust, MetaBuff/multiple classes addition, hashmaps for syscalls) // Copyright 2020 Solana Maintainers <maintainers@solana.com> // // Licensed under the Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0> or // the MIT license <http://opensource.org/licenses/MIT>, at your option. This...
{ /// Contains the register state at every instruction in order of execution pub trace_log: Vec<TraceLogEntry>, /// Maximal amount of instructions which still can be executed pub remaining: u64, } impl ContextObject for TestContextObject { fn trace(&mut self, state: [u64; 12]) { self.trace...
TestContextObject
identifier_name
vm.rs
Translation to Rust, MetaBuff/multiple classes addition, hashmaps for syscalls) // Copyright 2020 Solana Maintainers <maintainers@solana.com> // // Licensed under the Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0> or // the MIT license <http://opensource.org/licenses/MIT>, at your option. This...
crate::debugger::execute(&mut interpreter, debug_port); } else { while interpreter.step() {} } #[cfg(not(feature = "debugger"))] while interpreter.step() {} interpreter.due_insn_count } else { #[cfg(all(featu...
{ let mut registers = [0u64; 12]; // R1 points to beginning of input memory, R10 to the stack of the first frame, R11 is the pc (hidden) registers[1] = ebpf::MM_INPUT_START; registers[ebpf::FRAME_PTR_REG] = self.stack_pointer; registers[11] = executable.get_entrypoint_instruction...
identifier_body
vm.rs
(Translation to Rust, MetaBuff/multiple classes addition, hashmaps for syscalls) // Copyright 2020 Solana Maintainers <maintainers@solana.com> // // Licensed under the Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0> or // the MIT license <http://opensource.org/licenses/MIT>, at your option. Th...
impl<'a, C: ContextObject> EbpfVm<'a, C> { /// Creates a new virtual machine instance. pub fn new( config: &Config, sbpf_version: &SBPFVersion, context_object: &'a mut C, mut memory_mapping: MemoryMapping<'a>, stack_len: usize, ) -> Self { let stack_pointer =...
pub debug_port: Option<u16>, }
random_line_split
vm.rs
Translation to Rust, MetaBuff/multiple classes addition, hashmaps for syscalls) // Copyright 2020 Solana Maintainers <maintainers@solana.com> // // Licensed under the Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0> or // the MIT license <http://opensource.org/licenses/MIT>, at your option. This...
} ; let instruction_count = if config.enable_instruction_meter { self.context_object_pointer.consume(due_insn_count); initial_insn_count.saturating_sub(self.context_object_pointer.get_remaining()) } else { 0 }; let mut result = ProgramResult::O...
{ #[cfg(all(feature = "jit", not(target_os = "windows"), target_arch = "x86_64"))] { let compiled_program = match executable .get_compiled_program() .ok_or_else(|| Box::new(EbpfError::JitNotCompiled)) { O...
conditional_block
ed25519.rs
: // - Isis Agora Lovecruft <isis@patternsinthevoid.net> //! A Rust implementation of ed25519 EdDSA key generation, signing, and //! verification. use core::fmt::Debug; #[cfg(feature = "std")] use rand::Rng; use digest::BlockInput; use digest::Digest; use digest::Input; use digest::FixedOutput; use generic_array::...
TestSignVerify let mut cspring: OsRng; let keypair: Keypair; let good_sig: Signature; let bad_sig: Signature; let good: &[u8] = "test message".as_bytes(); let bad: &[u8] = "wrong message".as_bytes(); cspring = OsRng::new().unwrap(); keypair = Keypai...
ify() { //
identifier_name
ed25519.rs
Authors: // - Isis Agora Lovecruft <isis@patternsinthevoid.net> //! A Rust implementation of ed25519 EdDSA key generation, signing, and //! verification. use core::fmt::Debug; #[cfg(feature = "std")] use rand::Rng; use digest::BlockInput; use digest::Digest; use digest::Input; use digest::FixedOutput; use generic...
if ao.is_some() { a = ao.unwrap(); } else { return false; } a = -(&a); let top_half: &[u8; 32] = array_ref!(&signature.0, 32, 32); let bottom_half: &[u8; 32] = array_ref!(&signature.0, 0, 32); h.input(&bottom_half[..]); h.inpu...
return false; } ao = self.decompress();
random_line_split
ed25519.rs
: // - Isis Agora Lovecruft <isis@patternsinthevoid.net> //! A Rust implementation of ed25519 EdDSA key generation, signing, and //! verification. use core::fmt::Debug; #[cfg(feature = "std")] use rand::Rng; use digest::BlockInput; use digest::Digest; use digest::Input; use digest::FixedOutput; use generic_array::...
/// View this public key as a byte array. #[inline] pub fn as_bytes<'a>(&'a self) -> &'a [u8; PUBLIC_KEY_LENGTH] { &(self.0).0 } /// Construct a `PublicKey` from a slice of bytes. /// /// # Warning /// /// The caller is responsible for ensuring that the bytes passed into this ...
self.0.to_bytes() }
identifier_body
ed25519.rs
: // - Isis Agora Lovecruft <isis@patternsinthevoid.net> //! A Rust implementation of ed25519 EdDSA key generation, signing, and //! verification. use core::fmt::Debug; #[cfg(feature = "std")] use rand::Rng; use digest::BlockInput; use digest::Digest; use digest::Input; use digest::FixedOutput; use generic_array::...
lse { return false; } } } impl Signature { /// View this `Signature` as a byte array. #[inline] pub fn to_bytes(&self) -> [u8; SIGNATURE_LENGTH] { self.0 } /// View this `Signature` as a byte array. #[inline] pub fn as_bytes<'a>(&'a self) -> &'a [u8; SIGNATU...
return true; } e
conditional_block
nsis.rs
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #[cfg(target_os = "windows")] use crate::bundle::windows::util::try_sign; use crate::{ bundle::{ common::CommandExt, windows::util::{ download, download_and_verif...
(settings: &Settings, updater: bool) -> crate::Result<Vec<PathBuf>> { let tauri_tools_path = dirs_next::cache_dir().unwrap().join("tauri"); let nsis_toolset_path = tauri_tools_path.join("NSIS"); if!nsis_toolset_path.exists() { get_and_extract_nsis(&nsis_toolset_path, &tauri_tools_path)?; } else if NSIS_REQ...
bundle_project
identifier_name
nsis.rs
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #[cfg(target_os = "windows")] use crate::bundle::windows::util::try_sign; use crate::{ bundle::{ common::CommandExt, windows::util::{ download, download_and_verif...
rename(_tauri_tools_path.join("nsis-3.08"), nsis_toolset_path)?; } let nsis_plugins = nsis_toolset_path.join("Plugins"); let data = download(NSIS_APPLICATIONID_URL)?; info!("extracting NSIS ApplicationID plugin"); extract_zip(&data, &nsis_plugins)?; create_dir_all(nsis_plugins.join("x86-unicode"))?; ...
info!("extracting NSIS"); extract_zip(&data, _tauri_tools_path)?;
random_line_split
nsis.rs
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #[cfg(target_os = "windows")] use crate::bundle::windows::util::try_sign; use crate::{ bundle::{ common::CommandExt, windows::util::{ download, download_and_verif...
)), "persian" => Some(include_str!("./templates/nsis-languages/Persian.nsh")), "turkish" => Some(include_str!("./templates/nsis-languages/Turkish.nsh")), "swedish" => Some(include_str!("./templates/nsis-languages/Swedish.nsh")), _ => return Ok(None), }; Ok(Some((lang_path, lang_content))) } f...
{ if let Some(path) = custom_lang_files.and_then(|h| h.get(lang)) { return Ok(Some((dunce::canonicalize(path)?, None))); } let lang_path = PathBuf::from(format!("{lang}.nsh")); let lang_content = match lang.to_lowercase().as_str() { "arabic" => Some(include_str!("./templates/nsis-languages/Arabic.nsh")...
identifier_body
mod.rs
//! Abstraction over multiple versions of the file format allowed //! //! Because we want to continue to properly handle old config file formats - even when they'll no //! longer be generated by default. In the future, we might provide some kind of feature-gating for //! older versions, so that the dependencies associa...
/// An immutable handle on an entry in the file pub trait EntryRef { /// Returns the title of the entry fn name(&self) -> &str; /// Returns all the tags associated with the entry fn tags(&self) -> Vec<&str>; /// Returns the date + time at which the fn first_added(&self) -> SystemTime; ///...
fn remove_entry(&mut self, idx: usize); }
random_line_split
mod.rs
//! Abstraction over multiple versions of the file format allowed //! //! Because we want to continue to properly handle old config file formats - even when they'll no //! longer be generated by default. In the future, we might provide some kind of feature-gating for //! older versions, so that the dependencies associa...
}
{ PlaintextContent { last_update: SystemTime::now(), entries: Vec::new(), } }
identifier_body
mod.rs
//! Abstraction over multiple versions of the file format allowed //! //! Because we want to continue to properly handle old config file formats - even when they'll no //! longer be generated by default. In the future, we might provide some kind of feature-gating for //! older versions, so that the dependencies associa...
}; macro_rules! prefix_match { ($val:expr => { $($str:literal => $arm:expr,)* _ => $else_arm:expr, }) => {{ let v = $val; $(if v.starts_with($str) { $arm } else)* { $else_arm } }}; } prefix_match!(content....
{ eprintln!("failed to read file {:?}: {}", file.to_string_lossy(), e); exit(1); }
conditional_block
mod.rs
//! Abstraction over multiple versions of the file format allowed //! //! Because we want to continue to properly handle old config file formats - even when they'll no //! longer be generated by default. In the future, we might provide some kind of feature-gating for //! older versions, so that the dependencies associa...
{ Basic, Protected, Totp, } impl Display for ValueKind { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { ValueKind::Basic => f.write_str("Basic"), ValueKind::Protected => f.write_str("Protected"), ValueKind::Totp => f.write_str("TOTP"), ...
ValueKind
identifier_name
main.rs
extern crate petgraph; extern crate rand; extern crate time; extern crate clap; use std::cmp::{max, min}; use std::collections::HashSet; use rand::Rng; use time::PreciseTime; enum Method { Any, All, } fn main() { let matches = clap::App::new("square-sum") .about("Calculates solutions to the squar...
( g: &mut petgraph::Graph<(), (), petgraph::Undirected, usize>, square_numbers: &[usize], ) { let i = g.node_count() + 1; g.add_node(()); for sq in square_numbers .iter() .skip_while(|&sq| sq <= &i) .take_while(|&sq| sq <= &((i * 2) - 1)) { let i_index = petgraph::gr...
add_square_sum_node
identifier_name
main.rs
extern crate petgraph; extern crate rand; extern crate time; extern crate clap; use std::cmp::{max, min}; use std::collections::HashSet; use rand::Rng; use time::PreciseTime; enum Method { Any, All, } fn main() { let matches = clap::App::new("square-sum") .about("Calculates solutions to the squar...
fn push(&mut self, node_index: usize) { self.path.push(node_index); self.member[node_index] = true; } fn len(&self) -> usize { self.path.len() } fn contains(&self, node_index: usize) -> bool { self.member[node_index] } fn backtrack(&mut self, amount: usiz...
{ // TODO check that size >= seed.len() let mut path = Vec::with_capacity(size); let mut member = vec![false; size]; for i in seed.iter() { path.push(i - 1); member[*i - 1] = true; } Path { path, member } }
identifier_body
main.rs
extern crate petgraph; extern crate rand; extern crate time; extern crate clap; use std::cmp::{max, min}; use std::collections::HashSet; use rand::Rng; use time::PreciseTime; enum Method { Any, All, } fn main() { let matches = clap::App::new("square-sum") .about("Calculates solutions to the squar...
fn reverse(&mut self) { self.path.reverse(); } fn iter(&self) -> std::slice::Iter<usize> { self.path.iter() } } fn setup_path<N, E, Ty>(g: &petgraph::Graph<N, E, Ty, usize>) -> Result<Path, &'static str> where Ty: petgraph::EdgeType, { let mut rng = rand::thread_rng(); let...
self.path.truncate(new_size); }
random_line_split
lib.rs
mod utils; use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{ImageData, WebGlProgram, WebGlRenderingContext, WebGlShader}; const WIDTH: i32 = 128; const HEIGHT: i32 = 128; const CHANNELS: i32 = 4; const BUFFER_SIZE: usize = ((WIDTH * HEIGHT) * CHANNELS) as ...
else { Err(context .get_shader_info_log(&shader) .unwrap_or_else(|| String::from("Unknown error creating shader"))) } } pub fn link_program( context: &WebGlRenderingContext, vert_shader: &WebGlShader, frag_shader: &WebGlShader, ) -> Result<WebGlProgram, String> { let ...
{ Ok(shader) }
conditional_block
lib.rs
mod utils; use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{ImageData, WebGlProgram, WebGlRenderingContext, WebGlShader}; const WIDTH: i32 = 128; const HEIGHT: i32 = 128; const CHANNELS: i32 = 4; const BUFFER_SIZE: usize = ((WIDTH * HEIGHT) * CHANNELS) as ...
pub fn start() { utils::set_panic_hook(); log!("Hello there! Compositor canvas starting/loading"); } #[wasm_bindgen] pub fn initialise(element_id: String) -> Result<(), JsValue> { log!( "Compositor canvas (element_id: String = `{}`) initialisation", &element_id ); let document = we...
.expect("should register `requestAnimationFrame` OK"); } #[wasm_bindgen(start)]
random_line_split
lib.rs
mod utils; use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{ImageData, WebGlProgram, WebGlRenderingContext, WebGlShader}; const WIDTH: i32 = 128; const HEIGHT: i32 = 128; const CHANNELS: i32 = 4; const BUFFER_SIZE: usize = ((WIDTH * HEIGHT) * CHANNELS) as ...
( context: &WebGlRenderingContext, shader_type: u32, source: &str, ) -> Result<WebGlShader, String> { let shader = context .create_shader(shader_type) .ok_or_else(|| String::from("Unable to create shader object"))?; context.shader_source(&shader, source); context.compile_shader(&sh...
compile_shader
identifier_name
lib.rs
mod utils; use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{ImageData, WebGlProgram, WebGlRenderingContext, WebGlShader}; const WIDTH: i32 = 128; const HEIGHT: i32 = 128; const CHANNELS: i32 = 4; const BUFFER_SIZE: usize = ((WIDTH * HEIGHT) * CHANNELS) as ...
#[wasm_bindgen(start)] pub fn start() { utils::set_panic_hook(); log!("Hello there! Compositor canvas starting/loading"); } #[wasm_bindgen] pub fn initialise(element_id: String) -> Result<(), JsValue> { log!( "Compositor canvas (element_id: String = `{}`) initialisation", &element_id ...
{ window() .request_animation_frame(f.as_ref().unchecked_ref()) .expect("should register `requestAnimationFrame` OK"); }
identifier_body
async_stream_cdc.rs
// // Copyright (c) 2023 Nathan Fiedler // use super::*; #[cfg(all(feature = "futures", not(feature = "tokio")))] use futures::{ io::{AsyncRead, AsyncReadExt}, stream::Stream, }; #[cfg(all(feature = "tokio", not(feature = "futures")))] use tokio_stream::Stream; #[cfg(all(feature = "tokio", not(feature = "fu...
() { let array = [0u8; 1024]; AsyncStreamCDC::new(array.as_slice(), 64, 255, 1024); } #[test] #[should_panic] fn test_average_too_high() { let array = [0u8; 1024]; AsyncStreamCDC::new(array.as_slice(), 64, 268_435_457, 1024); } #[test] #[should_panic] fn...
test_average_too_low
identifier_name
async_stream_cdc.rs
// // Copyright (c) 2023 Nathan Fiedler // use super::*; #[cfg(all(feature = "futures", not(feature = "tokio")))] use futures::{ io::{AsyncRead, AsyncReadExt}, stream::Stream, }; #[cfg(all(feature = "tokio", not(feature = "futures")))] use tokio_stream::Stream; #[cfg(all(feature = "tokio", not(feature = "fu...
} Ok(all_bytes_read) } } /// Drains a specified number of bytes from the buffer, then resizes the /// buffer back to `capacity` size in preparation for further reads. fn drain_bytes(&mut self, count: usize) -> Result<Vec<u8>, Error> { // this code originally cop...
{ self.length += bytes_read; all_bytes_read += bytes_read; }
conditional_block
async_stream_cdc.rs
// // Copyright (c) 2023 Nathan Fiedler // use super::*; #[cfg(all(feature = "futures", not(feature = "tokio")))] use futures::{ io::{AsyncRead, AsyncReadExt}, stream::Stream, }; #[cfg(all(feature = "tokio", not(feature = "futures")))] use tokio_stream::Stream; #[cfg(all(feature = "tokio", not(feature = "fu...
max_size: usize, mask_s: u64, mask_l: u64, mask_s_ls: u64, mask_l_ls: u64, } impl<R: AsyncRead + Unpin> AsyncStreamCDC<R> { /// /// Construct a `StreamCDC` that will process bytes from the given source. /// /// Uses chunk size normalization level 1 by default. /// pub fn new...
/// True when the source produces no more data. eof: bool, min_size: usize, avg_size: usize,
random_line_split
impl_encryption.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use openssl::hash::{self, MessageDigest}; use tidb_query_codegen::rpn_fn; use tidb_query_datatype::expr::{Error, EvalContext}; use tidb_query_common::Result; use tidb_query_datatype::codec::data_type::*; use tidb_query_shared_expr::rand::{gen_random_...
assert_eq!(None, res) } }
KV", "*cca644408381f962dba8dfb9889db1371ee74208"), ("Pingcap", "*f33bc75eac70ac317621fbbfa560d6251c43cf8a"), ("rust", "*090c2b08e0c1776910e777b917c2185be6554c2e"), ("database", "*02e86b4af5219d0ba6c974908aea62d42eb7da24"), ("raft", "*b23a77787ed44e62ef2570f03ce8982d119fb6...
identifier_body
impl_encryption.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use openssl::hash::{self, MessageDigest}; use tidb_query_codegen::rpn_fn; use tidb_query_datatype::expr::{Error, EvalContext}; use tidb_query_common::Result; use tidb_query_datatype::codec::data_type::*; use tidb_query_shared_expr::rand::{gen_random_...
(b"abc".to_vec(), "900150983cd24fb0d6963f7d28e17f72"), (b"123".to_vec(), "202cb962ac59075b964b07152d234b70"), ( "你好".as_bytes().to_vec(), "7eca689f0d3389d9dea66ae112e5cfd7", ), ( "分布式データベース".as_bytes().to_vec(), ...
(vec![], "d41d8cd98f00b204e9800998ecf8427e"), (b"a".to_vec(), "0cc175b9c0f1b6a831c399e269772661"), (b"ab".to_vec(), "187ef4436122d1cc2f40dc2b92f0eba0"),
random_line_split
impl_encryption.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use openssl::hash::{self, MessageDigest}; use tidb_query_codegen::rpn_fn; use tidb_query_datatype::expr::{Error, EvalContext}; use tidb_query_common::Result; use tidb_query_datatype::codec::data_type::*; use tidb_query_shared_expr::rand::{gen_random_...
"pingcap", 0, "2871823be240f8ecd1d72f24c99eaa2e58af18b4b8ba99a4fc2823ba5c43930a"), ("pingcap", 224, "cd036dc9bec69e758401379c522454ea24a6327b48724b449b40c6b7"), ("pingcap", 256, "2871823be240f8ecd1d72f24c99eaa2e58af18b4b8ba99a4fc2823ba5c43930a"), ("pingcap", 384, "c50955b6b0c7b991974...
(
identifier_name
d.rs
*/ use crate::algo::graph::flow::*; use crate::algo::graph::*; use crate::util::grid::constants::*; use crate::util::grid::{Grid, GridCoord, GridRowColVec}; use crate::util::input::*; //use std::thread; use bimap::BiMap; use bit_vec::BitVec; use indexmap::IndexSet; use std::collections::HashSet; use std::collections::V...
cycle_edges.push_back(edge); debug!( "pushed Edge {:?} ", format!("{}->{}", vertex_to_string(edge.0), vertex_to_string(edge.1)) ); //adj list returns an (internal edge index, next vertex) edge = (edge.1, H.adj_list_with_edges(ed...
while !visited[edge.0] { visited.set(edge.0, true);
random_line_split
d.rs
use crate::algo::graph::flow::*; use crate::algo::graph::*; use crate::util::grid::constants::*; use crate::util::grid::{Grid, GridCoord, GridRowColVec}; use crate::util::input::*; //use std::thread; use bimap::BiMap; use bit_vec::BitVec; use indexmap::IndexSet; use std::collections::HashSet; use std::collections::Vec...
break; } } } r } /* impl<L, R> FromIterator<(L, R)> for BiMap<L, R> { fn from_iter<I: IntoIterator<Item = (L, R)>>(iter: I) -> Self { let mut c = BiMap::new(); for i in iter { c.insert(i.0, i.1); } c } }*/ fn solve...
{ let mut r = HashSet::new(); //debug!("\nTracing {} starting at {}", location, direction); for direction in DIRECTIONS.iter() { let mut loc: GridRowColVec = location.convert(); for _ in 0..=grid.R + grid.C { loc += direction; if let Some(tile) = grid.get_value(&lo...
identifier_body
d.rs
use crate::algo::graph::flow::*; use crate::algo::graph::*; use crate::util::grid::constants::*; use crate::util::grid::{Grid, GridCoord, GridRowColVec}; use crate::util::input::*; //use std::thread; use bimap::BiMap; use bit_vec::BitVec; use indexmap::IndexSet; use std::collections::HashSet; use std::collections::Vec...
}
{ return Err(err); }
conditional_block
d.rs
use crate::algo::graph::flow::*; use crate::algo::graph::*; use crate::util::grid::constants::*; use crate::util::grid::{Grid, GridCoord, GridRowColVec}; use crate::util::input::*; //use std::thread; use bimap::BiMap; use bit_vec::BitVec; use indexmap::IndexSet; use std::collections::HashSet; use std::collections::Vec...
<'a>(case_no: u32, grid: &mut Grid<Tile>, M_soldier_limit: usize) -> String { debug!( "Solving case {}\nM={}\n{}\n", case_no, M_soldier_limit, grid ); //original solider & turret index to location map let S_map = grid .filter_by_val(&Soldier) .enumerate() .collect::...
solve
identifier_name
simple_http.rs
self.addr, username.as_str(), password.as_str(), )? } else { Socks5Stream::connect(self.proxy_addr, self.addr)? }; Ok(stream.into_inner()) } #[cfg(not(feature = "proxy"))] fn fresh_socket(&self) -> Result<TcpStream, Error...
| IncompleteResponse { .. } => None, SocketError(ref e) => Some(e), Json(ref e) => Some(e), } } } impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Error::SocketError(e) } } impl From<serde_json::Error> for Erro...
{ use self::Error::*; match *self { InvalidUrl { .. } | HttpResponseTooShort { .. } | HttpResponseNonAsciiHello(..) | HttpResponseBadHello { .. } | HttpRespons...
identifier_body
simple_http.rs
self.addr, username.as_str(), password.as_str(), )? } else { Socks5Stream::connect(self.proxy_addr, self.addr)? }; Ok(stream.into_inner()) } #[cfg(not(feature = "proxy"))] fn fresh_socket(&self) -> Result<TcpStream, Error...
(self) -> SimpleHttpTransport { self.tp } } impl Default for Builder { fn default() -> Self { Builder::new() } } impl crate::Client { /// Creates a new JSON-RPC client using a bare-minimum HTTP transport. pub fn simple_http( url: &str, user: Option<String>, ...
build
identifier_name
simple_http.rs
line(&mut header_buf)?; } if header_buf.len() < 12 { return Err(Error::HttpResponseTooShort { actual: header_buf.len(), needed: 12, }); } if!header_buf.as_bytes()[..12].is_ascii() { return Err(Error::HttpResponseNonAsci...
random_line_split
ser.rs
} impl<'a> Drop for Serializer<'a> { fn drop(&mut self) { // Drop layers in reverse order. while!self.stack.is_empty() { self.stack.pop(); } } } #[allow(nonstandard_style)] struct write_u64 { major: u8, v: u64, } impl write_u64 { fn into(self, out: &'_ mut (dyn...
enum Layer<'a> { Seq(Box<dyn Seq<'a> + 'a>), Map(Box<dyn Map<'a> + 'a>),
random_line_split
ser.rs
(self, out: &'_ mut (dyn io::Write)) -> io::Result<()> { let Self { major, v: value } = self; let mask = major << 5; macro_rules! with_uNs {( $($uN:ident)<* ) => ({ mod c { $( pub mod $uN { pub const MAX: u64 = ::core::$uN::MAX as _; } )* ...
into
identifier_name
ser.rs
..=-1 => write_u64 { major: 1, v: (-(i + 1)) as u64, } .into(out)?, 0..=MAX => write_u64 { major: 0, v: i as u64, } .into(out)...
let vec = to_vec(&42.5f32).unwrap(); assert_eq_hex!(vec, b"\xF9\x51\x50"); assert_eq!(from_slice::<f32>(&vec[..]).unwrap(), 42.5f32); } } }
identifier_body
apply.rs
use anyhow::{anyhow, Context, Result}; use rand::seq::SliceRandom; use std::fs; use std::io::{self, Read}; use std::path; use std::process; use std::str; use std::thread; use crate::config::Config; use crate::find::find; use crate::operations::build::build_template; use crate::scheme::Scheme; /// Picks a random path,...
else { process::Command::new(&command_vec[0]) .args(&command_vec[1..]) .stdout(process::Stdio::null()) .stderr(process::Stdio::null()) .status() .with_context(|| format!("Couldn't run hook '{}'", full_command))?; } } ...
{ process::Command::new(&command_vec[0]) .stdout(process::Stdio::null()) .stderr(process::Stdio::null()) .status() .with_context(|| format!("Couldn't run hook '{}'", full_command))?; }
conditional_block
apply.rs
use anyhow::{anyhow, Context, Result}; use rand::seq::SliceRandom; use std::fs; use std::io::{self, Read}; use std::path; use std::process; use std::str; use std::thread; use crate::config::Config; use crate::find::find; use crate::operations::build::build_template; use crate::scheme::Scheme; /// Picks a random path,...
( file_content: &str, start: &str, end: &str, built_template: &str, ) -> Result<String> { let mut changed_content = String::new(); let mut found_start = false; let mut found_end = false; let mut appended = false; for line in file_content.lines() { if found_start &&!found_e...
replace_delimiter
identifier_name
apply.rs
use anyhow::{anyhow, Context, Result}; use rand::seq::SliceRandom; use std::fs; use std::io::{self, Read}; use std::path; use std::process; use std::str; use std::thread; use crate::config::Config; use crate::find::find; use crate::operations::build::build_template; use crate::scheme::Scheme; /// Picks a random path,...
//Check if config file exists if!config_path.exists() { eprintln!("Config {:?} doesn't exist, creating", config_path); let default_content = match fs::read_to_string(path::Path::new("/etc/flavours.conf")) { Ok(content) => content, Err(_) => String::from(""), }; ...
println!(); }
random_line_split
apply.rs
use anyhow::{anyhow, Context, Result}; use rand::seq::SliceRandom; use std::fs; use std::io::{self, Read}; use std::path; use std::process; use std::str; use std::thread; use crate::config::Config; use crate::find::find; use crate::operations::build::build_template; use crate::scheme::Scheme; /// Picks a random path,...
.with_context(|| format!("Couldn't run hook '{}'", full_command))?; } } Ok(()) } /// Replace with delimiter lines /// /// In a string, removes everything from one line to another, and puts the built template in place /// /// * `file_content` - String with lines to be replaced /// * `st...
{ if let Some(command) = command { let full_command = shell.replace("{}", &command); if verbose { println!("running {}", full_command); } let command_vec = shell_words::split(&full_command)?; if command_vec.len() == 1 { process::Command::new(&command_...
identifier_body
player.rs
use std::collections::HashMap; use crate::card::{Card, Colour}; use crate::game::{Action, VisibleGame}; use crate::power::Power; use crate::power::ScienceItem; use crate::resources::{ProducedResources, Resources}; use crate::wonder::{WonderBoard, WonderSide, WonderType}; use std::fmt::Debug; use crate::algorithms::Pla...
#[test] fn do_action_returns_false_if_action_not_playable() { let mut player = new_player(vec![LumberYard]); assert_eq!(false, player.do_action(&Action::Build(StonePit), &visible_game(), &mut vec![])); } #[test] fn do_action_transfers_built_card_from_hand_to_built_structures() { ...
{ // TODO implement }
identifier_body
player.rs
use std::collections::HashMap; use crate::card::{Card, Colour}; use crate::game::{Action, VisibleGame}; use crate::power::Power; use crate::power::ScienceItem; use crate::resources::{ProducedResources, Resources}; use crate::wonder::{WonderBoard, WonderSide, WonderType}; use std::fmt::Debug; use crate::algorithms::Pla...
() { let mut player = new_player(vec![LumberYard]); assert_eq!(false, player.do_action(&Action::Build(StonePit), &visible_game(), &mut vec![])); } #[test] fn do_action_transfers_built_card_from_hand_to_built_structures() { let mut player = new_player(vec![LumberYard]); asser...
do_action_returns_false_if_action_not_playable
identifier_name
player.rs
use std::collections::HashMap; use crate::card::{Card, Colour}; use crate::game::{Action, VisibleGame}; use crate::power::Power; use crate::power::ScienceItem; use crate::resources::{ProducedResources, Resources}; use crate::wonder::{WonderBoard, WonderSide, WonderType}; use std::fmt::Debug; use crate::algorithms::Pla...
// "choice" cards. At the same time, make a vector of resources choices available to us. let mut choices = Vec::new(); for card in &self.built_structures { match card.power() { // TODO: can we write these four options more succinctly? Power::Purchasabl...
// Initialise a Resources struct with the number of coins we have. let mut available_resources = Resources::coins(self.coins); // Add all the other resources we always have access to (ie. those that are not resource
random_line_split
runtime.rs
use crate::runtime::blocking::BlockingPool; use crate::runtime::scheduler::CurrentThread; use crate::runtime::{context, EnterGuard, Handle}; use crate::task::JoinHandle; use std::future::Future; use std::time::Duration; cfg_rt_multi_thread! { use crate::runtime::Builder; use crate::runtime::scheduler::MultiTh...
/// [runtime builder]: crate::runtime::Builder #[cfg(feature = "rt-multi-thread")] #[cfg_attr(docsrs, doc(cfg(feature = "rt-multi-thread")))] pub fn new() -> std::io::Result<Runtime> { Builder::new_multi_thread().enable_all().build() } } /// Returns a handle ...
/// /// [mod]: index.html /// [main]: ../attr.main.html /// [threaded scheduler]: index.html#threaded-scheduler
random_line_split
runtime.rs
use crate::runtime::blocking::BlockingPool; use crate::runtime::scheduler::CurrentThread; use crate::runtime::{context, EnterGuard, Handle}; use crate::task::JoinHandle; use std::future::Future; use std::time::Duration; cfg_rt_multi_thread! { use crate::runtime::Builder; use crate::runtime::scheduler::MultiTh...
( scheduler: Scheduler, handle: Handle, blocking_pool: BlockingPool, ) -> Runtime { Runtime { scheduler, handle, blocking_pool, } } cfg_not_wasi! { /// Creates a new runtime instance with default configuration values. ...
from_parts
identifier_name
runtime.rs
use crate::runtime::blocking::BlockingPool; use crate::runtime::scheduler::CurrentThread; use crate::runtime::{context, EnterGuard, Handle}; use crate::task::JoinHandle; use std::future::Future; use std::time::Duration; cfg_rt_multi_thread! { use crate::runtime::Builder; use crate::runtime::scheduler::MultiTh...
} } } cfg_metrics! { impl Runtime { /// TODO pub fn metrics(&self) -> crate::runtime::RuntimeMetrics { self.handle.metrics() } } }
{ match &mut self.scheduler { Scheduler::CurrentThread(current_thread) => { // This ensures that tasks spawned on the current-thread // runtime are dropped inside the runtime's context. let _guard = context::try_set_current(&self.handle.inner); ...
identifier_body
pool.rs
//! `LoggedPool` structure for logging raw tasks events. #![macro_use] // we can now use performance counters to tag subgraphs #[cfg(feature = "perf")] use perfcnt::linux::PerfCounterBuilderLinux; #[cfg(feature = "perf")] use perfcnt::linux::{CacheId, CacheOpId, CacheOpResultId, HardwareEventType, SoftwareEventType}; ...
where OP: FnOnce() -> R + Send, R: Send, { self.reset(); let id = next_task_id(); let c = || { log(RayonEvent::TaskStart(id, now())); let result = op(); log(RayonEvent::TaskEnd(now())); result }; let start = ...
/// After running, we post-process the logs and return a `RunLog` together with the closure's /// result. pub fn logging_install<OP, R>(&self, op: OP) -> (R, RunLog)
random_line_split
pool.rs
//! `LoggedPool` structure for logging raw tasks events. #![macro_use] // we can now use performance counters to tag subgraphs #[cfg(feature = "perf")] use perfcnt::linux::PerfCounterBuilderLinux; #[cfg(feature = "perf")] use perfcnt::linux::{CacheId, CacheOpId, CacheOpResultId, HardwareEventType, SoftwareEventType}; ...
/// Identical to `join`, except that the closures have a parameter /// that provides context for the way the closure has been called, /// especially indicating whether they're executing on a different /// thread than where `join_context` was called. This will occur if /// the second job is stolen by a different thre...
{ let continuation_task_id = next_task_id(); logs!( RayonEvent::SubgraphEnd(tag, measured_value), RayonEvent::Child(continuation_task_id), RayonEvent::TaskEnd(now()), // start continuation task RayonEvent::TaskStart(continuation_task_id, now()) ); }
identifier_body
pool.rs
//! `LoggedPool` structure for logging raw tasks events. #![macro_use] // we can now use performance counters to tag subgraphs #[cfg(feature = "perf")] use perfcnt::linux::PerfCounterBuilderLinux; #[cfg(feature = "perf")] use perfcnt::linux::{CacheId, CacheOpId, CacheOpResultId, HardwareEventType, SoftwareEventType}; ...
<OP, R>(&self, op: OP) -> (R, RunLog) where OP: FnOnce() -> R + Send, R: Send, { self.reset(); let id = next_task_id(); let c = || { log(RayonEvent::TaskStart(id, now())); let result = op(); log(RayonEvent::TaskEnd(now())); ...
logging_install
identifier_name
main.rs
fn main() { //Rust deals with stack and heaps for memory managment no gc or direct memory management //The stack memory is a first in last off type queue //Stack data must take up a known and fixed size //In rust the heap is used for when we don't know the size of the vector at compile time //or if ...
r on us since we are trying to //modify a borrowed variable. We will always get an //error for this function even if we never call it. // fn change(some_string: &String) { // some_string.push_str(", world"); // } //This fixes the above code by making a mutable reference that we can now modify. fn change(some_stri...
ction will erro
identifier_body
main.rs
fn main() { //Rust deals with stack and heaps for memory managment no gc or direct memory management //The stack memory is a first in last off type queue //Stack data must take up a known and fixed size //In rust the heap is used for when we don't know the size of the vector at compile time //or if ...
.i]; } } &s[..] }
conditional_block