lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/lib.rs
tstellanova/uorb-codec
89b93f0720bfa0edfaf5f505414ad1e8906df349
extern crate bytes; extern crate byteorder; use std::io::{ Error, ErrorKind, Read, Result, Write}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; pub const UORB_MAGIC_V1: u8 = 0xAA; pub trait UorbMsgMeta { const ENCODED_LEN: usize; const MSG_HASH_CODE: u16; const MSG_RAW_NAME: &'static str; ...
extern crate bytes; extern crate byteorder; use std::io::{ Error, ErrorKind, Read, Result, Write}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; pub const UORB_MAGIC_V1: u8 = 0xAA; pub trait UorbMsgMeta { const ENCODED_LEN: usize; const MSG_HASH_CODE: u16; const MSG_RAW_NAME: &'static str; ...
5 { continue; } let payload = &mut payload_buf[..payload_len.into()]; r.read_exact(payload)?; if let Some(msg) = UorbMessage::parse(header.hash, payload) { return Ok((header, msg)); } else { let err = Error::new(E...
function_block-function_prefixed
[ { "content": "pub fn get_sensor_gyro() -> SensorGyroData {\n\n let xgyro = 1111.0;\n\n let ygyro = 2222.0;\n\n let zgyro = 3333.0;\n\n\n\n SensorGyroData {\n\n device_id: 6887,\n\n timestamp: 0x1ed59200230008,\n\n error_count: 0,\n\n x: xgyro,\n\n y: ygyro,\n\n ...
Rust
src/lib.rs
fesoliveira014/voronator-rs
ea8f7d445841dee4409ee422090384ebd3757264
#![warn(missing_docs)] #![warn(rustdoc::missing_doc_code_examples)] pub mod polygon; pub mod delaunator; use rayon::prelude::*; use std::{f64, usize}; use crate::delaunator::*; use crate::polygon::*; pub struct CentroidDiagram<C: Coord + Vector<C>> { pub sites: Vec<C>, pub delaunay: Tri...
#![warn(missing_docs)] #![warn(rustdoc::missing_doc_code_examples)] pub mod polygon; pub mod delaunator; use rayon::prelude::*; use std::{f64, usize}; use crate::delaunator::*; use crate::polygon::*; pub struct CentroidDiagram<C: Coord + Vector<C>> { pub sites: Vec<C>, pub delaunay: Tri...
pub fn cells(&self) -> &[Polygon<C>] { &self.cells[..self.cells.len()-self.num_helper_points] } fn calculate_polygons( points: &[C], centers: &[C], delaunay: &Triangulation, clip_polygon: &Polygon<C>, ) -> Vec<Polygon<C>> { points.par_ite...
let clip_points = vec![C::from_xy(min.0, min.1), C::from_xy(max.0, min.1), C::from_xy(max.0, max.1), C::from_xy(min.0, max.1)]; let clip_polygon = polygon::Polygon::from_points(clip_points); VoronoiDiagram::with_bounding_polygon(points, &clip_polygon) }
function_block-function_prefix_line
[ { "content": "/// Calculates the Delaunay triangulation, if it exists, for a given set of 2D\n\n/// points.\n\n///\n\n/// Points are passed as a tuple, `(f64, f64)`, and converted internally\n\n/// to `delaunator::Point`. It returns both the triangulation and the vector of\n\n/// Points to be used, if desired.\...
Rust
src/main.rs
kierdavis/fina
7360aa6a32294856c997ceae98fefae09f0c37d7
/* * Copyright 2021 Kier Ada Davis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
/* * Copyright 2021 Kier Ada Davis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
; state } Action::Delete { selector } => { let mut deleted_tasks = Vec::new(); let mut side_effect_tasks = Vec::new(); let state = state.derive(|state| { let task_ids_to_delete = state .tasks() .filter_ok(selector.compile()) .map_ok(|task| { ...
print_tasks( state .tasks() .filter_ok(selector.compile()) .collect::<Result<Vec<_>, _>>()?, )
call_expression
[ { "content": "pub trait TaskAccessMut: sakaagari::AccessMut + TaskAccess {\n\n fn add_task(&mut self, task: Task<()>) -> Result<Task<TaskId>, sakaagari::Error> {\n\n self.save_task(task.assign_id(self.next_task_id()))\n\n }\n\n fn save_task(&mut self, task: Task<TaskId>) -> Result<Task<TaskId>, sakaagari:...
Rust
sonora/src/lib.rs
ebeasant-arm/veracruz
59d4938a89743b0fca86c060d66dd8d9dbd11841
#![no_std] #[macro_use] extern crate sgx_tstd as std; use lazy_static::lazy_static; use psa_attestation; use psa_attestation::{ psa_initial_attest_get_token, psa_initial_attest_load_key, t_cose_sign1_get_verification_pubkey, }; use sgx_tdh::{SgxDhInitiator, SgxDhMsg3}; use sgx_types; use sgx_types::{ sgx_cre...
#![no_std] #[macro_use] extern crate sgx_tstd as std; use lazy_static::lazy_static; use psa_attestation; use psa_attestation::{ psa_initial_attest_get_token, psa_initial_attest_load_key, t_cose_sign1_get_verification_pubkey, }; use sgx_tdh::{SgxDhInitiator, SgxDhMsg3}; use sgx_types; use sgx_types::{ sgx_cre...
enclave_cert_hash_size as u64, enclave_name, enclave_name_size as u64, challenge, challenge_size as u64, token, token_buf_size as u64, token_size as *mut u64, ) }; asse...
if status.is_err() { return SonoraStatus::ProcMsg3Error; } let received_veracruz_hash = responder_identity.mr_enclave; let status = unsafe { psa_initial_attest_get_token( received_veracruz_hash.m.as_ptr() as *const u8, ...
random
[ { "content": "pub fn serialize_native_psa_attestation_token(token: &[u8], device_id: i32) -> ColimaResult {\n\n let mut pat_proto = colima::NativePsaAttestationToken::new();\n\n pat_proto.set_token(token.to_vec());\n\n pat_proto.set_device_id(device_id);\n\n let mut tabasco_request = colima::Tabasco...
Rust
benches/syscall_benchmark.rs
cberner/redb
1a0bb4e0628c3160a7364df200e5daaa527de928
use tempfile::{NamedTempFile, TempDir}; use memmap2::MmapMut; use rand::prelude::SliceRandom; use rand::Rng; use std::fs::OpenOptions; use std::io::{Read, Seek, SeekFrom, Write}; use std::os::unix::io::AsRawFd; use std::path::Path; use std::time::SystemTime; const ITERATIONS: usize = 3; const ELEMENTS: usize = 100_00...
use tempfile::{NamedTempFile, TempDir}; use memmap2::MmapMut; use rand::prelude::SliceRandom; use rand::Rng; use std::fs::OpenOptions; use std::io::{Read, Seek, SeekFrom, Write}; use std::os::unix::io::AsRawFd; use std::path::Path; use std::time::SystemTime; const ITERATIONS: usize = 3; const ELEMENTS: usize = 100_00...
fn mmap_bench(path: &Path) { let file = OpenOptions::new() .read(true) .write(true) .create(true) .open(path) .unwrap(); file.set_len(4 * 1024 * 1024 * 1024).unwrap(); let mut mmap = unsafe { MmapMut::map_mut(&file).unwrap() }; drop(file); let pairs = gen...
fn readwrite_bench(path: &Path) { let mut file = OpenOptions::new() .read(true) .write(true) .create(true) .open(path) .unwrap(); let pairs = gen_data(1000, 16, 2000); let start = SystemTime::now(); { for i in 0..ELEMENTS { let (key, value) =...
function_block-full_function
[ { "content": "/// Returns pairs of key, value\n\nfn gen_data(count: usize, key_size: usize, value_size: usize) -> Vec<(Vec<u8>, Vec<u8>)> {\n\n let mut pairs = vec![];\n\n\n\n for _ in 0..count {\n\n let key: Vec<u8> = (0..key_size).map(|_| rand::thread_rng().gen()).collect();\n\n let value:...
Rust
artichoke-backend/src/extn/stdlib/vendor/gen/rubygems.rs
silathdiir/artichoke
ca6a6ebb36e59c155cf703053c14bd9a056df355
use crate::extn::prelude::*; pub fn init(interp: &mut Artichoke) -> InitializeResult<()> { let spec = crate::module::Spec::new(interp, "RbConfig", None)?; interp.0.borrow_mut().def_module::<RbConfig>(spec); let spec = crate::class::Spec::new("StringIO", None, None)?; interp.0.b...
use crate::extn::prelude::*; pub fn init(interp: &mut Artichoke) -> InitializeResult<()> { let spec = crate::module::Spec::new(interp, "RbConfig", None)?; interp.0.borrow_mut().def_module::<RbConfig>(spec); let spec = crate::class::Spec::new("StringIO", None, None)?; interp.0.b...
!("OUT_DIR"), "/src/generated/rubygems/stub_specification.rb"))[..] )?; interp.def_rb_source_file( b"rubygems/util.rb", &include_bytes!(concat!(env!("OUT_DIR"), "/src/generated/rubygems/util.rb"))[..] )?; interp.def_rb_source_file( b"rubygems/util/list.rb", &inc...
or", None, None)?; interp.0.borrow_mut().def_class::<Delegator>(spec); interp.def_rb_source_file( b"rubygems.rb", &include_bytes!(concat!(env!("OUT_DIR"), "/src/generated/rubygems.rb"))[..] )?; interp.def_rb_source_file( b"rubygems/basic_sp...
function_block-random_span
[]
Rust
src/racer/mod.rs
vincom2/racer
4871dfe9af7bdb9b221bb6751b980ac44f761cf7
use std::old_io::File; use std::old_io::BufferedReader; use std::old_path; use std::{str,vec,fmt}; pub mod scopes; pub mod ast; pub mod typeinf; pub mod nameres; pub mod codeiter; pub mod codecleaner; pub mod testutils; pub mod util; pub mod matchers; pub mod snippets; #[cfg(test)] pub mod test; #[cfg(test)] pub mod ...
use std::old_io::File; use std::old_io::BufferedReader; use std::old_path; use std::{str,vec,fmt}; pub mod scopes; pub mod ast; pub mod typeinf; pub mod nameres; pub mod codeiter; pub mod codecleaner; pub mod testutils; pub mod util; pub mod matchers; pub mod snippets; #[cfg(test)] pub mod test; #[cfg(test)] pub mod ...
pub fn load_file_and_mask_comments(filepath: &old_path::Path) -> String { let filetxt = BufferedReader::new(File::open(filepath)).read_to_end().unwrap(); let src = str::from_utf8(&filetxt).unwrap(); let msrc = scopes::mask_comments(src); return msrc; } pub fn complete_from_file(src: &str, filepath: &...
r::new(File::open(filepath)).read_to_end().unwrap(); if rawbytes[0..3] == [0xEF, 0xBB, 0xBF] { let mut it = rawbytes.into_iter(); it.next(); it.next(); it.next(); return String::from_utf8(it.collect::<Vec<_>>()).unwrap(); } else { return String::from_utf8(rawbytes).unwrap()...
function_block-function_prefixed
[ { "content": "pub fn search_for_impls(pos: usize, searchstr: &str, filepath: &Path, local: bool, include_traits: bool) -> vec::IntoIter<Match> {\n\n debug!(\"search_for_impls {}, {}, {:?}\", pos, searchstr, filepath.as_str());\n\n let s = racer::load_file(filepath);\n\n let src = &s[pos..];\n\n\n\n ...
Rust
src/spu/src/config/spu_config.rs
warycat/fluvio
fb1f6b15e7d5c01a4a8ee6e99a852ffcd0471891
use std::env; use std::path::PathBuf; use fluvio_types::defaults::SPU_PUBLIC_PORT; use fluvio_types::defaults::SPU_PRIVATE_PORT; use fluvio_types::defaults::SC_PRIVATE_PORT; use fluvio_types::defaults::SPU_LOG_BASE_DIR; use fluvio_types::defaults::SPU_LOG_SIZE; use fluvio_types::defaults::SPU_LOG_INDEX_MAX_BYTES; us...
use std::env; use std::path::PathBuf; use fluvio_types::defaults::SPU_PUBLIC_PORT; use fluvio_types::defaults::SPU_PRIVATE_PORT; use fluvio_types::defaults::SC_PRIVATE_PORT; use fluvio_types::defaults::SPU_LOG_BASE_DIR; use fluvio_types::defaults::SPU_LOG_SIZE; use fluvio_types::defaults::SPU_LOG_INDEX_MAX_BYTES; us...
} #[allow(unused)] pub fn private_socket_addr(&self) -> &str { &self.private_endpoint } pub fn storage(&self) -> &Log { &self.log } }
es: u32, pub index_max_interval_bytes: u32, pub segment_max_bytes: u32, pub flush_write_count: u32, pub flush_idle_msec: u32, pub max_batch_size: u32, } impl Default for Log { fn default() -> Self { Self { base_dir: PathBuf::from( env::var(FLV_LOG_BASE_DIR).u...
random
[ { "content": "/// Generates a random authorization token\n\npub fn generate_auth_token() -> (String, String) {\n\n const CHARSET: &[u8] = b\"abcdefghijklmnopqrstuvwxyz\\\n\n 0123456789\";\n\n\n\n const ID_SIZE: usize = 6;\n\n let token_name: String = (0..ID_SIZE)\n\n ....
Rust
src/udp.rs
jonahd-g/w5500
7474bf1ce75bfd69c865b29e305ea21a11b50f1e
use crate::bus::Bus; use crate::device::Device; use crate::host::Host; use crate::register::socketn; use crate::socket::Socket; use core::fmt::Debug; use embedded_nal::{nb, IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4, UdpClientStack, UdpFullStack}; pub struct UdpSocket { socket: Socket, } impl UdpSocket { fn n...
use crate::bus::Bus; use crate::device::Device; use crate::host::Host; use crate::register::socketn; use crate::socket::Socket; use core::fmt::Debug; use embedded_nal::{nb, IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4, UdpClientStack, UdpFullStack}; pub struct UdpSocket { socket: Socket, } impl UdpSocket { fn n...
} fn send(&mut self, socket: &mut Self::UdpSocket, buffer: &[u8]) -> nb::Result<(), Self::Error> { socket.send(&mut self.bus, buffer)?; Ok(()) } fn receive( &mut self, socket: &mut Self::UdpSocket, buffer: &mut [u8], ) -> nb::Result<(usize, SocketAddr), Self:...
if let SocketAddr::V4(remote) = remote { socket.open(&mut self.bus, 49849)?; socket.set_destination(&mut self.bus, remote)?; Ok(()) } else { Err(Self::Error::UnsupportedAddress) }
if_condition
[ { "content": "pub trait Host {\n\n /// Gets (if necessary) and sets the host settings on the chip\n\n fn refresh<SpiBus: Bus>(&mut self, bus: &mut SpiBus) -> Result<(), SpiBus::Error>;\n\n\n\n /// Write changed settings to chip\n\n ///\n\n /// Will check all settings and write any new ones to the...
Rust
libchum/src/archive/mod.rs
Jellonator/chum-world
910975e9fff25206aeb0df01aed38717218fa09c
pub mod data; pub mod nametable; pub use data::{TotemArchive, TotemFile, TotemHeader}; use crate::format; use crate::util; use std::collections::{HashMap, HashSet}; use std::io::{self, Read, Write}; use thiserror::Error; pub struct ChumArchive { header: data::TotemHeader, names: HashMap<i32, String>, fi...
pub mod data; pub mod nametable; pub use data::{TotemArchive, TotemFile, TotemHeader}; use crate::format; use crate::util; use std::collections::{HashMap, HashSet}; use std::io::{self, Read, Write}; use thiserror::Error; pub struct ChumArchive { header: data::TotemHeader, names: HashMap<i32, String>, fi...
pub fn get_header(&self) -> &data::TotemHeader { &self.header } pub fn get_files(&self) -> impl Iterator<Item = &ChumFile> { self.files.values() } pub fn take_files(self) -> impl Iterator<Item = ChumFile> { self.files.into_iter().map(|(_i, x)| x) } ...
let subtypestr = file.get_subtype_id().to_string(); if let Some(i) = hashname { self.names.insert(i, file.get_name_id().into()); self.files.insert(i, file); } else { return Err(ChumError::NameCollisionError { id: util...
function_block-function_prefix_line
[ { "content": "/// Hash the given name using the crc32 IEEE algorithm.\n\npub fn hash_name_i32(name: &str) -> i32 {\n\n crc32::checksum_ieee(&name.as_bytes()) as i32\n\n}\n\n\n", "file_path": "libchum/src/util/mod.rs", "rank": 0, "score": 367147.9331533171 }, { "content": "/// Load a chunk...
Rust
protocol-rpc/src/rpc/cross-psi/client.rs
yuyashiraki/Private-ID
71e95b4742902ac08efb32e8324011540373596e
extern crate clap; extern crate common; extern crate ctrlc; extern crate protocol; extern crate retry; extern crate rpc; extern crate tonic; use clap::{App, Arg, ArgGroup}; use log::info; use std::convert::TryInto; use tonic::Request; use common::timer; use crypto::prelude::{ByteBuffer, TPayload, TypeHeEncKey}; mod...
extern crate clap; extern crate common; extern crate ctrlc; extern crate protocol; extern crate retry; extern crate rpc; extern crate tonic; use clap::{App, Arg, ArgGroup}; use log::info; use std::convert::TryInto; use tonic::Request; use common::timer; use crypto::prelude::{ByteBuffer, TPayload, TypeHeEncKey}; mod...
or feature_index in 0..partner_protocol.get_self_num_features() { let mut u_partner_feature = partner_protocol.get_permuted_features(feature_index); u_partner_feature.push(ByteBuffer { buffer: (feature_index as u64).to_le_bytes().to_vec(), }); let...
.args(&[ Arg::with_name("company") .long("company") .short("c") .takes_value(true) .required(true) .help("Host path to connect to, ex: 0.0.0.0:10009"), Arg::with_name("input") .long("input") ...
random
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n tonic_build::compile_protos(\"proto/common.proto\")\n\n .unwrap_or_else(|e| panic!(\"Failed to compile protos {:?}\", e));\n\n tonic_build::compile_protos(\"proto/privateid.proto\")\n\n .unwrap_or_else(|e| panic!(\"Faile...
Rust
daoGovnance/lib.rs
michaelHookon/RainbowDAO-Protocol-Ink-Test-Version-04
ee19e5a0ec3585a42e66ccc13ba0978e341420ba
#![cfg_attr(not(feature = "std"), no_std)] extern crate alloc; use ink_lang as ink; pub use self::dao_govnance::DaoGovnance; #[ink::contract] mod dao_govnance { use alloc::string::String; use alloc::vec::Vec; use ink_storage::{ collections::{ HashMap as StorageHashMap, ...
#![cfg_attr(not(feature = "std"), no_std)] extern crate alloc; use ink_lang as ink; pub use self::dao_govnance::DaoGovnance; #[ink::contract] mod dao_govnance { use alloc::string::String; use alloc::vec::Vec; use ink_storage::{ collections::{ HashMap as StorageHashMap, ...
#[ink(message)] pub fn register_behavior(&mut self , contract_name: String,function_name: String, behavior_title:String) -> bool{ let caller = self.env().caller(); assert!(self.owner ==caller ||self._has_pass(caller, String::from("daoGovnance"), String::from("register"))); let behavior...
e)) { self.behaviors_auth.take(&(account_id,behavior.behavior_id)); return true; } return false; }
function_block-function_prefixed
[]
Rust
derive/src/de.rs
austinabell/miniserde
81d45ee5619c045f2b212c01dece6cbff2c67307
use crate::{attr, bound}; use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{ parse_quote, Data, DataEnum, DataStruct, DeriveInput, Error, Fields, FieldsNamed, Ident, Result, }; pub fn derive(input: DeriveInput) -> Result<TokenStream> { match &input.data { Data::Struct(DataStruct { ...
use crate::{attr, bound}; use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{ parse_quote, Data, DataEnum, DataStruct, DeriveInput, Error, Fields, FieldsNamed, Ident, Result, }; pub fn derive(input: DeriveInput) -> Result<TokenStream> { match &input.data { Data::Struct(DataStruct { ...
pub fn derive_enum(input: &DeriveInput, enumeration: &DataEnum) -> Result<TokenStream> { if input.generics.lt_token.is_some() || input.generics.where_clause.is_some() { return Err(Error::new( Span::call_site(), "Enums with generics are not supported", )); } let ide...
r_ty_generics #bounded_where_clause { fn key(&mut self, __k: &miniserde::__private::str) -> miniserde::Result<&mut dyn miniserde::de::Visitor> { match __k { #( #fieldstr => miniserde::__private::Ok(miniserde::Deserialize::begin(&mut...
function_block-function_prefixed
[ { "content": "/// Determine the name of a field, respecting a rename attribute.\n\npub fn name_of_field(field: &Field) -> Result<String> {\n\n let rename = attr_rename(&field.attrs)?;\n\n Ok(rename.unwrap_or_else(|| field.ident.as_ref().unwrap().to_string()))\n\n}\n\n\n", "file_path": "derive/src/attr...
Rust
lib/lookup/src/lookup_buf/test.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use std::{fs, io::Read, path::Path, str::FromStr}; use once_cell::sync::Lazy; use quickcheck::{QuickCheck, TestResult}; use tracing::trace; use crate::*; const SUFFICIENTLY_COMPLEX: &str = r#"regular."quoted"."quoted but spaces"."quoted.but.periods".lookup[0].nested_lookup[0][0]"#; static SUFFICIENTLY_DECOMPOSE...
use std::{fs, io::Read, path::Path, str::FromStr}; use once_cell::sync::Lazy; use quickcheck::{QuickCheck, TestResult}; use tracing::trace; use crate::*; const SUFFICIENTLY_COMPLEX: &str = r#"regular."quoted"."quoted but spaces"."quoted.but.periods".lookup[0].nested_lookup[0][0]"#; static SUFFICIENTLY_DECOMPOSE...
0)), parsed); assert_eq!("[30]", parsed.to_string()); } #[test] fn parses() { fn inner(path: LookupBuf) -> TestResult { let s = path.to_string(); let path2: LookupBuf = FromStr::from_str(&s).unwrap(); assert_eq!(path, path2); TestResult::passed() } QuickCheck::new() ...
, "Opening."); let buf = parse_artifact(&path).unwrap(); let buf_serialized = serde_json::to_string(&serde_json::to_value(&buf).unwrap()).unwrap(); let lookup: LookupBuf = FromStr::from_str(&buf).unwrap(); tracing::trace!(?path, ?lookup...
random
[ { "content": "fn encode_string(output: &mut String, str: &str) {\n\n let needs_quoting = str.chars().any(|c| c.is_whitespace() || c == '\"');\n\n\n\n if needs_quoting {\n\n output.write_char('\"').unwrap();\n\n }\n\n\n\n for c in str.chars() {\n\n match c {\n\n '\\\\' => out...
Rust
noodles-cram/src/reader/compression_header/preservation_map.rs
slazicoicr/noodles
2a1b086254d32942dbfd5524f07a66207fa09a92
use std::{ convert::TryFrom, io::{self, BufRead, Read}, }; use byteorder::ReadBytesExt; use noodles_bam as bam; use crate::{ container::compression_header::{ preservation_map::Key, PreservationMap, SubstitutionMatrix, TagIdsDictionary, }, num::read_itf8, record, }; pub fn read_preserv...
use std::{ convert::TryFrom, io::{self, BufRead, Read}, }; use byteorder::ReadBytesExt; use noodles_bam as bam; use crate::{ container::compression_header::{ preservation_map::Key, PreservationMap, SubstitutionMatrix, TagIdsDictionary, }, num::read_itf8, record, }; pub fn read_preserv...
e)) } fn read_tag_ids_dictionary<R>(reader: &mut R) -> io::Result<TagIdsDictionary> where R: Read, { let data_len = read_itf8(reader)?; let mut buf = vec![0; data_len as usize]; reader.read_exact(&mut buf)?; let mut buf_reader = &buf[..]; let mut dictionary = Vec::new(); let mut keys_buf ...
mut buf_reader)?; let mut read_names_included = true; let mut ap_data_series_delta = true; let mut reference_required = true; let mut substitution_matrix = None; let mut tag_ids_dictionary = None; let mut key_buf = [0; 2]; for _ in 0..map_len { buf_reader.read_exact(&mut key_buf)?...
random
[ { "content": "fn read_read_name<R>(reader: &mut R, buf: &mut Vec<u8>) -> io::Result<usize>\n\nwhere\n\n R: BufRead,\n\n{\n\n match consume_byte(reader, b'@') {\n\n Ok(n) => read_line(reader, buf).map(|m| m + n),\n\n Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof => Ok(0),\n\n ...
Rust
src/xip_ssi/spi_ctrlr0.rs
Szpadel/rp2040-pac
4006f1937b8f57c4b4d6543bfd7aa7158a640fb0
#[doc = "Reader of register SPI_CTRLR0"] pub type R = crate::R<u32, super::SPI_CTRLR0>; #[doc = "Writer for register SPI_CTRLR0"] pub type W = crate::W<u32, super::SPI_CTRLR0>; #[doc = "Register SPI_CTRLR0 `reset()`'s with value 0x0300_0000"] impl crate::ResetValue for super::SPI_CTRLR0 { type Type = u32; #[inl...
#[doc = "Reader of register SPI_CTRLR0"] pub type R = crate::R<u32, super::SPI_CTRLR0>; #[doc = "Writer for register SPI_CTRLR0"] pub type W = crate::W<u32, super::SPI_CTRLR0>; #[doc = "Register SPI_CTRLR0 `reset()`'s with value 0x0300_0000"] impl crate::ResetValue for super::SPI_CTRLR0 { type Type = u32; #[inl...
(TRANS_TYPE_A::_1C1A), 1 => Val(TRANS_TYPE_A::_1C2A), 2 => Val(TRANS_TYPE_A::_2C2A), i => Res(i), } } #[doc = "Checks if the value of the field is `_1C1A`"] #[inline(always)] pub fn is_1c1a(&self) -> bool { *self == TRANS_TYPE_A::_1C1A } #[doc ...
(&self) -> crate::Variant<u8, TRANS_TYPE_A> { use crate::Variant::*; match self.bits { 0 => Val
function_block-random_span
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
rustracer-core/tests/efloat.rs
abusch/rustracer
d0429dac0b3b02ca6ce8a7fe60e95014f527ddc1
use rand::{rngs::StdRng, Rng, SeedableRng}; use rustracer_core::efloat::EFloat; use rustracer_core::{next_float_down, next_float_up}; const NUM_ITER: usize = 10_000; fn get_float<T: Rng>(rng: &mut T, min_exp: f32, max_exp: f32) -> EFloat { let logu: f32 = rng.gen_range(min_exp..max_exp); let val = (10.0_f32)...
use rand::{rngs::StdRng, Rng, SeedableRng}; use rustracer_core::efloat::EFloat; use rustracer_core::{next_float_down, next_float_up}; const NUM_ITER: usize = 10_000; fn get_float<T: Rng>(rng: &mut T, min_exp: f32, max_exp: f32) -> EFloat { let logu: f32 = rng.gen_range(min_exp..max_exp); let val = (10.0_f32)...
#[test] fn test_efloat_abs() { for trial in 0..NUM_ITER { let mut rng = StdRng::seed_from_u64(trial as u64); let ef = get_float(&mut rng, -6.0, 6.0); let precise = get_precise(&ef, &mut rng); let result = ef.abs(); let precise_result = precise.abs(); assert!(preci...
4 = (1.0 - t) * f64::from(ef.lower_bound()) + t * f64::from(ef.upper_bound()); if p > f64::from(ef.upper_bound()) { f64::from(ef.upper_bound()) } else if p < f64::from(ef.lower_bound()) { f64::from(ef.lower_bound()) } else { p ...
function_block-function_prefixed
[ { "content": "fn gray_code_sample(c: &[u32], n: u32, scramble: u32, p: &mut [f32]) {\n\n let mut v = scramble;\n\n for i in 0..n {\n\n p[i as usize] = (v as f32 * 2.3283064365386963e-10f32).min(ONE_MINUS_EPSILON);\n\n v ^= c[(i + 1).trailing_zeros() as usize];\n\n }\n\n}\n\n\n", "file...
Rust
src/application/emu_window.rs
saeenyoda/Chippus
28d37d857c1b12d160adf54054f7930cdb41877d
use crate::emulator::chip8::Emulator; use crate::emulator::screen::Screen; use crate::imgui_wgpu_backend::{Renderer, Texture, TextureConfig}; use imgui::*; use wgpu::{ CommandEncoderDescriptor, Device, Extent3d, ImageCopyTexture, ImageDataLayout, Origin3d, Queue, TextureFormat, TextureUsage, }; pub struct RGBA...
use crate::emulator::chip8::Emulator; use crate::emulator::screen::Screen; use crate::imgui_wgpu_backend::{Renderer, Texture, TextureConfig}; use imgui::*; use wgpu::{ CommandEncoderDescriptor, Device, Extent3d, ImageCopyTexture, ImageDataLayout, Origin3d, Queue, TextureFormat, TextureUsage, }; pub struct RGBA...
; let pos = (y * 4 * self.width) + (x * 4); self.data[pos..pos + 4].copy_from_slice(&[v, v, v, 0xFF]); } } self.update_texture(renderer, &device, &mut queue); } fn create_texture( renderer: &mut Renderer, device: &Devic...
if emulator.screen.get_pixel(x, y) == 1 { 0xFF } else { 0 }
if_condition
[]
Rust
src/rpc/cacheable.rs
bridgesplit/cacherpc
b3b6aa82ad9ae09b5ed1f5d316f07b6cb79f7c0b
use std::collections::HashSet; use std::sync::Arc; use std::time::Duration; use prometheus::IntCounter; use serde::de::DeserializeOwned; use serde_json::value::RawValue; use crate::metrics::rpc_metrics as metrics; use crate::pubsub::subscription::{Subscription, SubscriptionActive}; use crate::rpc::request::{parse_par...
use std::collections::HashSet; use std::sync::Arc; use std::time::Duration; use prometheus::IntCounter; use serde::de::DeserializeOwned; use serde_json::value::RawValue; use crate::metrics::rpc_metrics as metrics; use crate::pubsub::subscription::{Subscription, SubscriptionActive}; use crate::rpc::request::{parse_par...
fn get_timeout(state: &State) -> Duration { Duration::from_secs(state.config.load().timeouts.account_info_request) } fn get_backoff(state: &State) -> u64 { state.config.load().timeouts.account_info_backoff } fn get_limit(state: &State) -> &SemaphoreQueue { state.account_i...
fn parse<'a>(request: &Request<'a, RawValue>) -> Result<Self, Error<'a>> { let this = parse_params(request).map(|(pubkey, config, config_hash)| Self { pubkey, config, config_hash, })?; emit_request_metrics!(this.config); Ok(this) }
function_block-full_function
[ { "content": "pub fn version() -> &'static str {\n\n static VERSION: Lazy<String> = Lazy::new(|| {\n\n let pkg_version = std::env!(\"CARGO_PKG_VERSION\");\n\n option_env!(\"CI_COMMIT_TAG\")\n\n .map(ToString::to_string)\n\n .unwrap_or_else(|| {\n\n format!(\...
Rust
telebot-derive/src/lib.rs
alun/telebot
d7f41872c74b4624c5329fb6df2196e03acb6a4c
#![recursion_limit = "150"] extern crate log; extern crate proc_macro; #[macro_use] extern crate quote; extern crate syn; use proc_macro::TokenStream; use std::collections::BTreeMap; #[proc_macro_derive(setter, attributes(query))] pub fn derive_setter(input: TokenStream) -> TokenStream { let ast = syn::parse_mac...
#![recursion_limit = "150"] extern crate log; extern crate proc_macro; #[macro_use] extern crate quote; extern crate syn; use proc_macro::TokenStream; use std::collections::BTreeMap; #[proc_macro_derive(setter, attributes(query))] pub fn derive_setter(input: TokenStream) -> TokenStream { let ast = syn::parse_mac...
#[proc_macro_derive(TelegramFunction, attributes(call, answer, function, file_kind))] pub fn derive_telegram_sendable(input: TokenStream) -> TokenStream { let ast = syn::parse_macro_input(&input.to_string()).unwrap(); let expanded = expand_function(ast); expanded.to_string().parse().unwrap() } fn expand_...
panic!("no sane type!"); }) .collect(); if let Some(query_name) = query_kind { quote! { impl #name { #[allow(dead_code)] pub fn new(#( #field_compulsory3: #ty_compulsory2, )*) -> #name { let id = Uuid::new_v4()...
function_block-function_prefix_line
[ { "content": "/// Calls the Telegram API for the function and awaits the result. The result is then converted\n\n/// to a String and returned in a Future.\n\n//pub fn _fetch<T: futures_retry::ErrorHandler<std::io::Error>>(fut_res: FutureRetry<FnMut() -> ResponseFuture, T>) -> impl Future<Item = String, Error = ...
Rust
crates/volta-core/src/project/mod.rs
dherman/nemo
d4fc9df13ab975d7f6424b85a4052f14ab0e9bd5
use std::convert::{TryFrom, TryInto}; use std::env; use std::ffi::OsStr; use std::iter::once; use std::path::{Path, PathBuf}; use lazycell::LazyCell; use semver::Version; use crate::error::{Context, ErrorKind, Fallible, VoltaError}; use crate::layout::volta_home; use crate::platform::PlatformSpec; use crate::tool::...
use std::convert::{TryFrom, TryInto}; use std::env; use std::ffi::OsStr; use std::iter::once; use std::path::{Path, PathBuf}; use lazycell::LazyCell; use semver::Version; use crate::error::{Context, ErrorKind, Fallible, VoltaError}; use crate::layout::volta_home; use crate::platform::PlatformSpec; use crate::tool::...
None; } } Some(dir) } struct PartialPlatform { node: Option<Version>, npm: Option<Version>, yarn: Option<Version>, } impl PartialPlatform { fn merge(self, other: PartialPlatform) -> PartialPlatform { PartialPlatform { node: self.node.or(other.node), np...
(PlatformSpec { node: version, npm: None, yarn: None, }); } Ok(()) } pub fn pin_npm(&mut self, version: Option<Version>) -> Fallible<()> { if let Some(platform) = self.platform.as_mut() { update_manifest(&self...
random
[ { "content": "pub fn node_distro_file_name(version: &str) -> String {\n\n format!(\n\n \"node-v{}-{}-{}.tar.gz\",\n\n version, NODE_DISTRO_OS, NODE_DISTRO_ARCH\n\n )\n\n}\n", "file_path": "tests/smoke/support/temp_project.rs", "rank": 0, "score": 399369.98077679606 }, { "...
Rust
clique-grpc/src/server.rs
gilescope/clique
f725715d4490b5d4866ab034cc546b7d5224f199
use crate::{ proto::{self, server}, Error, }; use clique::transport::{Request, Server}; use futures::sync::oneshot as oneshot01; use futures::{Future as Future01, Stream as Stream01}; use futures03::{future, TryFutureExt}; use std::net::SocketAddr; use tokio_sync::{mpsc, oneshot}; use tokio_tcp::TcpListener; us...
use crate::{ proto::{self, server}, Error, }; use clique::transport::{Request, Server}; use futures::sync::oneshot as oneshot01; use futures::{Future as Future01, Stream as Stream01}; use futures03::{future, TryFutureExt}; use std::net::SocketAddr; use tokio_sync::{mpsc, oneshot}; use tokio_tcp::TcpListener; us...
)).unwrap(); Box::new( res_rx .compat() .map(|r| tower_grpc::Response::new(r.unwrap().into())) .map_err(|_| Status::new(Code::Unknown, "Unknown grpc error")), ) } } impl Future01 for Background { type Item = (); type Error = (); ...
wer_grpc::Request<proto::Request>, ) -> Self::SendRequestFuture { let inbound_req = request.into_inner(); let (res_tx, res_rx) = oneshot::channel(); let req = Request::new(res_tx, inbound_req.into()); self.msg_tx.try_send(Ok(req
function_block-random_span
[ { "content": "type Source = Box<dyn error::Error + Send + Sync + 'static>;\n\n\n\npub struct Error {\n\n kind: ErrorKind,\n\n source: Option<Source>,\n\n}\n\n\n\n#[derive(Debug)]\n\npub(crate) enum ErrorKind {\n\n Start,\n\n Join,\n\n BrokenPipe,\n\n UnexpectedRequestType,\n\n}\n\n\n\nimpl Err...
Rust
test/src/sdk-harness/test_projects/token_ops/mod.rs
FuelLabs/sway
0190b5dac4735fd2a34528e48cc2e0c9606b5ce8
use fuels::prelude::*; use fuels::signers::wallet::Wallet; use fuels::tx::{AssetId, ContractId}; use fuels_abigen_macro::abigen; abigen!( TestFuelCoinContract, "test_projects/token_ops/out/debug/token_ops-abi.json" ); #[tokio::test] async fn can_mint() { let wallet = launch_provider_and_get_single_wallet(...
use fuels::prelude::*; use fuels::signers::wallet::Wallet; use fuels::tx::{AssetId, ContractId}; use fuels_abigen_macro::abigen; abigen!( TestFuelCoinContract, "test_projects/token_ops/out/debug/token_ops-abi.json" ); #[tokio::test]
#[tokio::test] async fn can_burn() { let wallet = launch_provider_and_get_single_wallet().await; let (fuelcoin_instance, fuelcoin_id) = get_fuelcoin_instance(wallet).await; let target = fuelcoin_id.clone(); let asset_id = target.clone(); let mut balance_result = fuelcoin_instance .get_ba...
async fn can_mint() { let wallet = launch_provider_and_get_single_wallet().await; let (fuelcoin_instance, fuelcoin_id) = get_fuelcoin_instance(wallet).await; let target = fuelcoin_id.clone(); let asset_id = target.clone(); let mut balance_result = fuelcoin_instance .get_balance(target.clon...
function_block-full_function
[ { "content": "fn item_use_to_use_statements(\n\n ec: &mut ErrorContext,\n\n item_use: ItemUse,\n\n) -> Result<Vec<UseStatement>, ErrorEmitted> {\n\n if let Some(pub_token) = item_use.visibility {\n\n let error = ConvertParseTreeError::PubUseNotSupported {\n\n span: pub_token.span(),\n...
Rust
tests/alpha_dash.rs
shssoichiro/iron-valid
65d4b15d0379d1842d0253c88b99b3206fa8a578
extern crate iron_valid; extern crate params; use iron_valid::{Rule, validate}; use params::{Map, Value}; use std::collections::BTreeMap; #[test] fn test_alpha_dash_valid_lowercase() { let mut params = Map::new(); params.assign("alpha_dash", Value::String("foobarbaz".to_owned())).ok(); let mut rules = BT...
extern crate iron_valid; extern crate params; use iron_valid::{Rule, validate}; use params::{Map, Value}; use std::collections::BTreeMap; #[test] fn test_alpha_dash_valid_lowercase() { let mut params = Map::new(); params.assign("alpha_dash", Value::String("foobarbaz".to_owned())).ok(); let mut rules = BT...
#[test] fn test_alpha_dash_valid_underscore() { let mut params = Map::new(); params.assign("alpha_dash", Value::String("foo_bar_baz".to_owned())).ok(); let mut rules = BTreeMap::new(); rules.insert("alpha_dash", vec![Rule::AlphaDash]); let result = validate(&rules, params); assert!(result.i...
let mut params = Map::new(); params.assign("alpha_dash", Value::String("foo bar baz".to_owned())).ok(); let mut rules = BTreeMap::new(); rules.insert("alpha_dash", vec![Rule::AlphaDash]); let result = validate(&rules, params); assert!(result.is_err()); assert_eq!(*result.unwrap_err().get("alp...
function_block-function_prefix_line
[ { "content": "pub fn validate_string(values: &Map, field: &[&str]) -> Result<Option<Value>, String> {\n\n match values.find(field) {\n\n Some(&Value::String(_)) => Ok(None),\n\n None => {\n\n // Allow empty values\n\n Ok(None)\n\n }\n\n _ => {\n\n ...
Rust
netlink-packet/src/rtnl/tc/nlas/stats_queue.rs
delbonis/netlink
b374f7ada1d225f7464bc223e85a813ad691bea5
use byteorder::{ByteOrder, NativeEndian}; use crate::{DecodeError, Emitable, Field, Parseable}; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub struct TcStatsQueue { pub qlen: u32, pub backlog: u32, pub drops: u32, pub requeues: u32, pub overlimits: u32, } const QLEN: Fi...
use byteorder::{ByteOrder, NativeEndian}; use crate::{DecodeError, Emitable, Field, Parseable}; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub struct TcStatsQueue { pub qlen: u32, pub backlog: u32, pub drops: u32, pub requeues: u32, pub overlimits: u32, } const QLEN: Fi...
}
TcStatsQueueBuffer::new(buffer); buffer.set_qlen(self.qlen); buffer.set_backlog(self.backlog); buffer.set_drops(self.drops); buffer.set_requeues(self.requeues); buffer.set_overlimits(self.overlimits); }
function_block-function_prefixed
[ { "content": "#[allow(non_snake_case)]\n\nfn BUF(len: usize) -> Field {\n\n BUFLEN.end..(BUFLEN.end + len)\n\n}\n\n\n\n#[derive(Debug, PartialEq, Eq, Clone)]\n\npub struct RuleBuffer<T> {\n\n buffer: T,\n\n}\n\n\n\nimpl<T: AsRef<[u8]>> RuleBuffer<T> {\n\n pub fn new(buffer: T) -> RuleBuffer<T> {\n\n ...
Rust
nextest-runner/tests/integration/fixtures.rs
skyzh/nextest
0c5fc9723d1be392de270d8b08e6f9f014a77cac
use camino::{Utf8Path, Utf8PathBuf}; use duct::cmd; use guppy::{graph::PackageGraph, MetadataCommand}; use maplit::btreemap; use nextest_metadata::{FilterMatch, MismatchReason}; use nextest_runner::{ reporter::TestEvent, runner::{ExecutionResult, ExecutionStatuses, RunStats, TestRunner}, test_list::{Bina...
use camino::{Utf8Path, Utf8PathBuf}; use duct::cmd; use guppy::{graph::PackageGraph, MetadataCommand}; use maplit::btreemap; use nextest_metadata::{FilterMatch, MismatchReason}; use nextest_runner::{ reporter::TestEvent, runner::{ExecutionResult, ExecutionStatuses, RunStats, TestRunner}, test_list::{Bina...
dead_code)] pub(crate) struct InstanceValue<'a> { pub(crate) binary_id: &'a str, pub(crate) cwd: &'a Utf8Path, pub(crate) status: InstanceStatus, } #[derive(Clone)] pub(crate) enum InstanceStatus { Skipped(MismatchReason), Finished(ExecutionStatuses), } impl fmt::Debug for InstanceStatus { fn ...
true), ("nextest-tests::bin/nextest-tests", "nextest-tests", true), ("nextest-tests::bin/other", "other", true), ( "nextest-tests::example/nextest-tests", "nextest-tests", true, ), ("nextest-tests::example/other", "other", true), ("nextest-tests::other", "other", true), ...
random
[]
Rust
rumq-client/src/state_persistence.rs
braeutigamj/rumq
998d03bc33a3a1e3f04532e7ca024a866f35795d
use crate::MqttState; use std::iter::FromIterator; use rumq_core::*; use serde::{Serialize, Deserialize}; use std::collections::VecDeque; use tokio::fs; use async_trait::async_trait; #[async_trait] pub trait StatePersistence: Send + Sync { async fn save(&mut self, state: &MqttState) -> Result<(), tokio::io::Error...
use crate::MqttState; use std::iter::FromIterator; use rumq_core::*; use serde::{Serialize, Deserialize}; use std::collections::VecDeque; use tokio::fs; use async_trait::async_trait; #[async_trait] pub trait StatePersistence: Send + Sync { async fn save(&mut self, state: &MqttState) -> Result<(), tokio::io::Error...
} impl From<StateData> for MqttState { fn from(data: StateData) -> Self { let mut s = MqttState::new(); s.last_pkid = data.last_pkid.into(); s.outgoing_pub = container_into!(VecDeque<Publish>, data.outgoing_pub); s.outgoing_rel = container_into!(VecDeque<PacketIdentifier>, ...
fn from(state: &MqttState) -> Self { StateData { last_pkid: (&state.last_pkid).into(), outgoing_pub: container_into!(Vec<PublishData>, &state.outgoing_pub), outgoing_rel: container_into!(Vec<PacketIdentifierData>, ...
function_block-full_function
[ { "content": "pub fn publish<S: Into<String>, P: Into<Vec<u8>>>(topic: S, qos: QoS, payload: P) -> Publish {\n\n Publish {\n\n dup: false,\n\n qos,\n\n retain: false,\n\n pkid: None,\n\n topic_name: topic.into(),\n\n payload: payload.into(),\n\n }\n\n}\n\n\n\nimpl...
Rust
examples/example_lockfree_stack.rs
solotzg/rs-lockfree
b4d102a4fab3f3c9b273ac697e50d4b6ea12c0a3
#![feature(core_intrinsics)] extern crate core_affinity; extern crate rs_lockfree; #[macro_use] extern crate log; extern crate env_logger; use rs_lockfree::lockfree_stack; use rs_lockfree::util; use std::ops::Deref; use std::ops::DerefMut; use std::mem; use std::thread; use std::intrinsics; use std::time; use std::ti...
#![feature(core_intrinsics)] extern crate core_affinity; extern crate rs_lockfree; #[macro_use] extern crate log; extern crate env_logger; use rs_lockfree::lockfree_stack; use rs_lockfree::util; use std::ops::Deref; use std::ops::DerefMut; use std::mem; use std::thread; use std::intrinsics; use std::time; use std::ti...
unsafe fn consumer_thread(mut global_control: ShardPtr<GlobalControl>) { set_cpu_affinity(); let global_control = global_control.as_mut(); let mut ret = false; let mut tol = 0; let mut tol_val = 0; loop { if let Some(v) = global_control.stack.pop() { let val = v.value; ...
l::get_thread_id() as usize % cpus.len()]); info!( "set_cpu_affinity {} {}", util::get_thread_id(), util::get_thread_id() as usize % cpus.len() ); }
function_block-function_prefixed
[ { "content": "fn get_current_tid() -> i64 {\n\n util::get_thread_id()\n\n}\n\n\n", "file_path": "tests/test_lockfree_stack.rs", "rank": 0, "score": 102148.94849919846 }, { "content": "#[derive(Default)]\n\nstruct StackValue {\n\n a: i64,\n\n b: i64,\n\n sum: i64,\n\n}\n\n\n", ...
Rust
src/sweep_buffer.rs
tinco/rust-go-gc
c74b2e0fc4ec39b930defe11de9572546564888d
use super::memory_span::*; use std::alloc::*; use std::mem; use std::ptr::Unique; use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; use std::sync::{Mutex, MutexGuard}; const GC_SWEEP_BLOCK_ENTRIES: usize = 512; const GC_SWEEP_BUF_INIT_SPINE_CAP: usize = 256; pub struct SweepBuffer { ...
use super::memory_span::*; use std::alloc::*; use std::mem; use std::ptr::Unique; use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; use std::sync::{Mutex, MutexGuard}; const GC_SWEEP_BLOCK_ENTRIES: usize = 512; const GC_SWEEP_BUF_INIT_SPINE_CAP: usize = 256; pub struct SweepBuffer { ...
fn grow_spine(&self, spine_cap: usize) -> usize { let new_cap = match spine_cap { 0 => GC_SWEEP_BUF_INIT_SPINE_CAP, _ => spine_cap * 2, }; let layout = Layout::array::<SweepBlock>(new_cap).expect("Could not layout spine"); let spine = self...
p { *spine_cap = self.grow_spine(*spine_cap); } unsafe { let block = alloc(Layout::new::<SweepBlockData>()); let spine_block_ptr_ref = self.0.spine.load(Ordering::Relaxed).offset(top as isize); let spine_block_ptr: AtomicPtr<u8> = mem::transmute(...
function_block-function_prefixed
[ { "content": "// arenaIndex returns the index into mheap_.arenas of the arena\n\n// containing metadata for p. This index combines of an index into the\n\n// L1 map and an index into the L2 map and should be used as\n\n// mheap_.arenas[ai.l1()][ai.l2()].\n\n//\n\n// If p is outside the range of valid heap addre...
Rust
src/diskstats.rs
derekdreery/linux_proc
c63172563ab4c195ab991cfed44d23a4f6a59880
use std::collections::HashMap; use std::fs::File; use std::io; use std::time::Duration; use crate::{util, Error}; pub struct DiskStats { inner: HashMap<String, DiskStat>, } impl DiskStats { const PATH: &'static str = "/proc/diskstats"; pub fn from_system() -> io::Result<Self> { DiskStats::f...
use std::collections::HashMap; use std::fs::File; use std::io; use std::time::Duration; use crate::{util, Error}; pub struct DiskStats { inner: HashMap<String, DiskStat>, } impl DiskStats { const PATH: &'static str = "/proc/diskstats"; pub fn from_system() -> io::Result<Self> { DiskStats::f...
o = Duration::from_millis(time_io); let (_input, time_io_weighted) = err_msg!( util::parse_u64(input), "weighted time spent doing I/Os (ms)" )?; let time_io_weighted = Duration::from_millis(time_io_weighted); Ok(DiskStat { major, m...
ged) = err_msg!(util::parse_u64(input), "reads merged")?; let (input, sectors_read) = err_msg!(util::parse_u64(input), "sectors read")?; let (input, time_reading) = err_msg!(util::parse_u64(input), "time spent reading (ms)")?; let time_reading = Duration::from_millis(time_reading); let (...
random
[ { "content": "pub fn parse_u64(input: &str) -> Option<(&str, u64)> {\n\n let input = consume_space(input);\n\n let mut chars = input.chars();\n\n let (mut next_idx, mut acc) = match chars.next() {\n\n Some(ch) => match ch.to_digit(10) {\n\n Some(val) => (ch.len_utf8(), val as u64),\n\...
Rust
crates/common/src/name.rs
matthijsr/til-vhdl
ef1bffdf17a976403f2b3b95ea853a4df012cfd7
use std::{ convert::{TryFrom, TryInto}, fmt, iter::FromIterator, ops::Deref, str::FromStr, }; use crate::{ error::{Error, Result, TryOptionalFrom, TryResult}, traits::Identify, }; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Name(String); impl Name { ...
use std::{ convert::{TryFrom, TryInto}, fmt, iter::FromIterator, ops::Deref, str::FromStr, }; use crate::{ error::{Error, Result, TryOptionalFrom, TryResult}, traits::Identify, }; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Name(String); impl Name { ...
} impl From<Name> for String { fn from(name: Name) -> Self { name.0 } } impl From<&Name> for String { fn from(name: &Name) -> Self { name.0.clone() } } impl From<&Name> for Name { fn from(value: &Name) -> Self { value.clone() } } impl Deref for Name { type Target...
pub fn try_new(name: impl Into<String>) -> Result<Self> { let name = name.into(); if name.is_empty() { Err(Error::InvalidArgument("name cannot be empty".to_string())) } else if name.chars().next().unwrap().is_ascii_digit() { Err(Error::InvalidArgument(format!( ...
function_block-full_function
[]
Rust
src/lutxy.rs
shssoichiro/vapoursynth-mpeg2stinx
6e39c64fe632d2f2f2c204e16b7232da4b738f4e
use super::*; use failure::Error; use vapoursynth::core::CoreRef; use vapoursynth::prelude::*; pub(crate) fn lutxy_sharp<'core>( core: CoreRef<'core>, clip1: &FrameRef<'core>, clip2: &FrameRef<'core>, strength: f32, ) -> Result<FrameRef<'core>, Error> { let mut filtered = FrameRefMut::copy_of(core,...
use super::*; use failure::Error; use vapoursynth::core::CoreRef; use vapoursynth::prelude::*; pub(crate) fn lutxy_sharp<'core>( core: CoreRef<'core>, clip1: &FrameRef<'core>, clip2: &FrameRef<'core>, strength: f32, ) -> Result<FrameRef<'core>, Error> { let mut filtered = FrameRefMut::copy_of(core,...
macro_rules! limd_fn { ($pix_ty:ty, $math_ty:ty) => { paste::item! { fn [<limd_loop_ $pix_ty>]<'core>( clip1: &FrameRef<'core>, clip2: &FrameRef<'core>, filtered: &mut FrameRefMut<'core>, plane: usize, scale: f32, ...
pub(crate) fn lutxy_limd<'core>( core: CoreRef<'core>, clip1: &FrameRef<'core>, clip2: &FrameRef<'core>, scale: f32, ) -> Result<FrameRef<'core>, Error> { let mut filtered = FrameRefMut::copy_of(core, &*clip1); let plane_count = clip1.format().plane_count(); let bytes_per_sample = clip...
function_block-full_function
[ { "content": " n: usize,\n\n ) -> Result<FrameRef<'core>, Error> {\n\n let clip1 = self\n\n .clip1\n\n .get_frame_filter(context, n)\n\n .ok_or_else(|| format_err!(\"Min: Couldn't get clip1 frame\"))?;\n\n let clip2 = self\n\n .clip2\n\n ...
Rust
linkerd/proxy/http/src/normalize_uri.rs
ihciah/linkerd2-proxy
dcd95569da4f9356ec4a0ef48c312336228025ac
use super::h1; use futures::{future, TryFutureExt}; use http::uri::Authority; use linkerd_error::Error; use linkerd_stack::{layer, NewService, Param}; use std::task::{Context, Poll}; use tracing::trace; #[derive(Clone, Debug)] pub struct NewNormalizeUri<N> { inner: N, } #[derive(Clone, Debug)] pub struct Normal...
use super::h1; use futures::{future, TryFutureExt}; use http::uri::Authority; use linkerd_error::Error; use linkerd_stack::{layer, NewService, Param}; use std::task::{Context, Poll}; use tracing::trace; #[derive(Clone, Debug)] pub struct NewNormalizeUri<N> { inner: N, } #[derive(Clone, Debug)] pub struct Normal...
} impl std::fmt::Display for NoAuthority { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "failed to normalize URI because no authority could be determined" ) } } impl std::error::Error for NoAuthority {} impl<S> MarkAbsoluteForm<S> { ...
req.uri().authority().is_none() { let authority = match h1::authority_from_host(&req).or_else(|| self.default.clone()) { Some(a) => a, None => return future::Either::Right(future::err(NoAuthority(()).into())), }; ...
function_block-function_prefix_line
[ { "content": "pub fn layer<N, S, Req>() -> impl layer::Layer<N, Service = NewSplit<N, S, Req>> + Clone {\n\n // This RNG doesn't need to be cryptographically secure. Small and fast is\n\n // preferable.\n\n layer::mk(move |inner| NewSplit {\n\n inner,\n\n _service: PhantomData,\n\n })\...
Rust
migration-engine/migration-engine-tests/tests/migrations/id/cockroachdb.rs
prisma-korea/prisma-engines
99ac5a5c95ba2f5308d84fc30a7110f606182d92
use migration_engine_tests::test_api::*; use sql_schema_describer::DefaultKind; #[test_connector(tags(CockroachDb))] fn flipping_autoincrement_on_and_off_works(api: TestApi) { let dm_without = r#" model Post { id BigInt @id title String @default("") } "#;...
use migration_engine_tests::test_api::*; use sql_schema_describer::DefaultKind; #[test_connector(tags(CockroachDb))] fn flipping_autoincrement_on_and_off_works(api: TestApi) {
let dm_with = r#" model Post { id BigInt @id @default(autoincrement()) updatedAt DateTime } "#; for dm in [dm_with, dm_without].iter().cycle().take(5) { api.schema_push_w_datasource(*dm).send().assert_green(); } } #[test_connector(tags(Co...
let dm_without = r#" model Post { id BigInt @id title String @default("") } "#;
assignment_statement
[ { "content": "#[test_connector(capabilities(Enums))]\n\nfn enums_used_in_default_can_be_changed(api: TestApi) {\n\n let dm1 = r#\"\n\n model Panther {\n\n id Int @id\n\n mood CatMood @default(HAPPY)\n\n }\n\n\n\n model Tiger {\n\n id Int @id\n\n ...
Rust
src/astar.rs
brianbruggeman/rltk_rs
27febe22da40750a60b9adedc589aedaf6719c06
use super::BaseMap; use std::collections::HashMap; #[allow(dead_code)] const MAX_DIRECT_PATH_CHECK : f32 = 2048.0; #[allow(dead_code)] const MAX_ASTAR_STEPS :i32 = 2048; #[allow(dead_code)] pub fn a_star_search(start:i32, end:i32, map: &mut BaseMap) -> NavigationPath { let mut searcher = AStar::new(start, end...
use super::BaseMap; use std::collections::HashMap; #[allow(dead_code)] const MAX_DIRECT_PATH_CHECK : f32 = 2048.0; #[allow(dead_code)] const MAX_ASTAR_STEPS :i32 = 2048; #[allow(dead_code)] pub fn a_star_search(start:i32, end:i32, map: &mut BaseMap) -> NavigationPath { let mut searcher = AStar::new(start, end...
let s = Node{ idx:idx, f:distance + cost, g:cost, h:distance }; let mut should_add = true; for e in self.open_list.iter() { if e.f < s.f && e.idx == idx { should_add = false; } } if...
start: start, end : end, open_list : open_list, parents: HashMap::new(), closed_list: HashMap::new(), step_counter: 0 }; } fn distance_to_end(&self, idx :i32, map: &BaseMap) -> f32 { return map.get_pathing_distance(idx, self....
random
[ { "content": "pub fn idx_xy(idx : usize) -> (i32, i32) {\n\n (idx as i32 % 80, idx as i32 / 80)\n\n}\n\n\n\nimpl State {\n\n pub fn new() -> State {\n\n let mut state = State{\n\n map : vec![TileType::Floor; 80*50],\n\n player_position: xy_idx(40, 25),\n\n visible: ...
Rust
tasks/apply-a-digital-filter/src/main.rs
DaveAxiom/rust-rosetta
0fdc52c431f8e9b5a103fce2ed1a102c003c419b
#![allow(clippy::excessive_precision)] struct IIRFilter<'f>(&'f [f32], &'f [f32]); impl<'f> IIRFilter<'f> { pub fn with_coefficients(a: &'f [f32], b: &'f [f32]) -> IIRFilter<'f> { IIRFilter(a, b) } pub fn apply<I: Iterator<Item = &'f f32> + 'f>( &self, samples: I, ) -> im...
#![allow(clippy::excessive_precision)] struct IIRFilter<'f>(&'f [f32], &'f [f32]); impl<'f> IIRFilter<'f> { pub fn with_coefficients(a: &'f [f32], b: &'f [f32]) -> IIRFilter<'f> { IIRFilter(a, b) } pub fn apply<I: Iterator<Item = &'f f32> + 'f>( &self, samples: I, ) -> im...
8, -0.53767651, 0.51705003, 1.05224979, 0.96185434, 0.69568992, 0.42435625, 0.19626230, -0.02783510, -0.21172196, -0.17474557, 0.06925842, 0.38544586, 0.65177077, ] .into_iter(); let actual = IIRFilter::...
function_block-function_prefixed
[ { "content": "fn all_sums(vec: &mut [f32]) -> Vec<f32> {\n\n let mut res = Vec::new();\n\n let mut perms = Heap::new(vec);\n\n loop {\n\n let v = perms.next();\n\n match v {\n\n Some(v) => {\n\n let mut sum = 0.0_f32;\n\n for e in &v {\n\n ...
Rust
bg/src/main.rs
russelltg/deepspeech-rs
ca19b59f71719cc791481c1883122534eafbfb5a
extern crate bindgen; extern crate proc_macro2; extern crate syn; use proc_macro2::{Delimiter, Spacing, TokenStream, TokenTree}; use std::path::Path; use std::path::PathBuf; use syn::export::ToTokens; fn get_binding_functions(file: &mut syn::File) -> Vec<syn::ForeignItemFn> { let mut retvl = Vec::new(); for idx i...
extern crate bindgen; extern crate proc_macro2; extern crate syn; use proc_macro2::{Delimiter, Spacing, TokenStream, TokenTree}; use std::path::Path; use std::path::PathBuf; use syn::export::ToTokens; fn get_binding_functions(file: &mut syn::File) -> Vec<syn::ForeignItemFn> { let mut retvl = Vec::new(); for idx i...
fn main() { let bindings = bindgen::Builder::default() .header("stddef.h") .header("sys/deepspeech/native_client/deepspeech.h") .clang_args(&["-x", "c++", "-std=c++11"]) .generate() .expect("Couldn't generate bindings"); let out_path = PathBuf::from("sys/src"); write_to_file(out_path.join("bindings.rs")...
fn add_spacings(tokens: TokenStream) -> String { let mut res_str = String::new(); struct TokenVisitor<'s> { s: &'s mut String, } impl<'s> TokenVisitor<'s> { fn visit_stream(&mut self, stream: TokenStream) { let mut iter = stream.into_iter().peekable(); while let Some(tree) = iter.next() { self.visit_t...
function_block-full_function
[ { "content": "pub fn from_path (path : impl AsRef < std :: ffi :: OsStr >) -> Result < Self , libloading :: Error > {\n\nlet inner = std :: sync :: Arc :: new (libloading :: Library :: new ( & path ) ?) ;\n\n Ok (Self { inner })\n\n}\n\n pub unsafe fn DS_ErrorCodeToErrorMessage (& self , aErrorCode : :: std :: ...
Rust
src/oracle.rs
curest0x1021/terra-rust
b23e7f870b31df6242f1113df083ea90c90c4fbc
use anyhow::Result; use structopt::StructOpt; use terra_rust_api::Terra; use crate::{NAME, VERSION}; use bitcoin::secp256k1::Secp256k1; use terra_rust_api::client::oracle::Voters; use terra_rust_api::messages::oracle::MsgDelegateFeedConsent; use terra_rust_api::messages::Message; use terra_rust_wallet::Wallet; #[deri...
use anyhow::Result; use structopt::StructOpt; use terra_rust_api::Terra; use crate::{NAME, VERSION}; use bitcoin::secp256k1::Secp256k1; use terra_rust_api::client::oracle::Voters; use terra_rust_api::messages::oracle::MsgDelegateFeedConsent; use terra_rust_api::messages::Message; use terra_rust_wallet::Wallet; #[deri...
println!("{}", resp.txhash); log::info!("{}", resp.raw_log); } OracleCommand::Voters { validator, cmd } => { let voter = terra.oracle().voters(&validator); voter_cmd_parse(&voter, wallet, seed, cmd).await?; } } Ok(()) } pub async fn vote...
let resp = terra .submit_transaction_sync( &secp, &from_key, &messages, Some(format!( "PFC-{}/{}", NAME.unwrap_or("TERRARUST"), VERSION.unwrap_or("DEV")...
assignment_statement
[ { "content": "/// put out into a separate function to facilitate better testing\n\nfn generate_hash<'a>(salt: &'a str, exchange_string: &'a str, validator: &'a str) -> String {\n\n let mut sha = Sha256::new();\n\n let mut to_hash: String = String::new();\n\n to_hash = to_hash.add(salt);\n\n to_hash ...
Rust
crates/til_query/src/ir/streamlet.rs
matthijsr/til-vhdl
ef1bffdf17a976403f2b3b95ea853a4df012cfd7
use std::sync::Arc; use tydi_common::{ error::{Error, Result, TryResult}, map::{InsertionOrderedMap, InsertionOrderedSet}, name::{Name, PathName, PathNameSelf}, traits::{Document, Documents, Identify}, }; use tydi_intern::Id; use super::{ physical_properties::Domain, project::interface::Interf...
use std::sync::Arc; use tydi_common::{ error::{Error, Result, TryResult}, map::{InsertionOrderedMap, InsertionOrderedSet}, name::{Name, PathName, PathNameSelf}, traits::{Document, Documents, Identify}, }; use tydi_intern::Id; use super::{ physical_properties::Domain, project::interface::Interf...
} } impl From<Id<Arc<Interface>>> for Streamlet { fn from(id: Id<Arc<Interface>>) -> Self { Streamlet { name: PathName::new_empty(), implementation: None, interface: Some(id), doc: None, } } }
Ok(Arc::new(Streamlet { name: self.name.clone().with_parents(prefix), implementation, interface, doc: self.doc.clone(), }) .intern(target_db))
call_expression
[]
Rust
src/sampler.rs
vaporgraph/qlog
eb3d03ef72f3ceb067b5dd199838087c84f08f28
use rand::{prelude::Rng, rngs::SmallRng, SeedableRng}; use serde::Serialize; use std::borrow::Cow; use std::collections::hash_map::DefaultHasher; use std::collections::{BTreeMap, HashSet}; use std::fs::File; use std::hash::{Hash, Hasher}; use std::io::{BufWriter, Write}; use crate::common::{INDEX_NODE_SUBGRAPH, SUBGRA...
use rand::{prelude::Rng, rngs::SmallRng, SeedableRng}; use serde::Serialize; use std::borrow::Cow; use std::collections::hash_map::DefaultHasher; use std::collections::{BTreeMap, HashSet}; use std::fs::File; use std::hash::{Hash, Hasher}; use std::io::{BufWriter, Write}; use crate::common::{INDEX_NODE_SUBGRAPH, SUBGRA...
}
timestamp: sample.timestamp.as_ref().map(|s| Cow::from(s)), }; writeln!(self.out, "{}", serde_json::to_string(&entry)?)?; } } Ok(()) }
function_block-function_prefix_line
[]
Rust
crates/ewin-com/src/_cfg/cfg.rs
thinkingreed/ewin
8b39d7f5f0038a581a62ed08738f3e7563e3507b
use crate::{_cfg::*, colors::*, def::*, global::*, log::*, model::*}; use directories::BaseDirs; use serde::{Deserialize, Serialize}; use std::{fs, fs::File, io::Write, sync::Mutex}; use syntect::{ self, highlighting::{Theme, ThemeSet}, parsing::SyntaxSet, }; use theme_loader::ThemeLoader; #[der...
use crate::{_cfg::*, colors::*, def::*, global::*, log::*, model::*}; use directories::BaseDirs; use serde::{Deserialize, Serialize}; use std::{fs, fs::File, io::Write, sync::Mutex}; use syntect::{ self, highlighting::{Theme, ThemeSet}, parsing::SyntaxSet, }; use theme_loader::ThemeLoader; #[der...
}
init(args: &Args, cfg_str: &str) -> String { let mut cfg: Cfg = toml::from_str(cfg_str).unwrap(); let mut err_str = "".to_string(); let mut read_str = String::new(); if let Some(base_dirs) = BaseDirs::new() { let config_dir = base_dirs.config_dir(); if !co...
function_block-function_prefixed
[ { "content": "pub fn cut_str(str: String, limit_width: usize, is_from_before: bool, is_add_continue_str: bool) -> String {\n\n let mut chars: Vec<char> = if is_from_before { str.chars().rev().collect() } else { str.chars().collect() };\n\n let mut width = 0;\n\n\n\n let str_width = get_str_width(&str);...
Rust
src/archive_handler.rs
atlanticaccent/test
9f06eb6dd9930a2c5b961016cb1ec7125f527e21
use std::{fs, error::Error, path::Path}; macro_rules! dbg { ($($x:tt)*) => { { #[cfg(debug_assertions)] { std::dbg!($($x)*) } #[cfg(not(debug_assertions))] { ($($x)*) } } } } mod rar_patch { use std::{fmt, error:...
use std::{fs, error::Error, path::Path}; macro_rules! dbg { ($($x:tt)*) => { { #[cfg(debug_assertions)] { std::dbg!($($x)*) } #[cfg(not(debug_assertions))] { ($($x)*) } } } } mod rar_patch { use std::{fmt, error:...
#[cfg(not(target_os = "linux"))] fn _7z_support(_: &String, _: &String) -> Result<bool, Box<dyn Error + Send>> { Ok(false) } fn _rar_support(dest: &String, file_name: &String, file: &String) -> Result<bool, Box<dyn Error + Send>> { let output_dir = Path::new(dest) .join(file_name) .to_string_lossy() ...
fn compress_tools(file: &String, dest: &String) -> Result<bool, Box<dyn Error + Send>> { match fs::File::open(&file) { Ok(mut source) => { let dest = Path::new(dest); match compress_tools::uncompress_archive(&mut source, &dest, compress_tools::Ownership::Ignore) { Ok(()) => return Ok(tr...
function_block-full_function
[ { "content": "pub fn error<T: AsRef<str>>(message: T) {\n\n Dialog::error(String::from(message.as_ref()));\n\n}\n\n\n", "file_path": "src/gui/util.rs", "rank": 4, "score": 84582.30739717404 }, { "content": "fn parse_game_version(text: &str) -> (Option<String>, Option<String>, Option<String>...
Rust
src/algorithm/broad_phase/sweep_prune.rs
josh65536/collision-rs
586ea56a852958db5ea8fdfc2601afa2ec57c505
pub use self::variance::Variance; use std::cmp::Ordering; use cgmath::num_traits::NumCast; use self::variance::{Variance2, Variance3}; use crate::prelude::*; pub type SweepAndPrune2<S, B> = SweepAndPrune<Variance2<S, B>>; pub type SweepAndPrune3<S, B> = SweepAndPrune<Variance3<S, B>>; pub struct SweepAndPrune<V> ...
pub use self::variance::Variance; use std::cmp::Ordering; use cgmath::num_traits::NumCast; use self::variance::{Variance2, Variance3}; use crate::prelude::*; pub type SweepAndPrune2<S, B> = SweepAndPrune<Variance2<S, B>>; pub type SweepAndPrune3<S, B> = SweepAndPrune<Variance3<S, B>>; pub struct SweepAndPrune<V> ...
t mut pairs = Vec::default(); if shapes.len() <= 1 { return pairs; } shapes.sort_by(|a, b| { let cmp_min = a.bound().min_extent()[self.sweep_axis] .partial_cmp(&b.bound().min_extent()[self.sweep_axis]); match cmp_min { Some(Ord...
der_pairs<A>(&mut self, shapes: &mut [A]) -> Vec<(usize, usize)> where A: HasBound, A::Bound: Bound + Discrete<A::Bound>, V: Variance<Bound = A::Bound>, { le
random
[ { "content": "#[inline]\n\nfn get_left_index<B>(node: &Node<B>) -> usize {\n\n match *node {\n\n Node::Branch(ref b) => b.left,\n\n _ => panic!(),\n\n }\n\n}\n\n\n", "file_path": "src/dbvt/mod.rs", "rank": 0, "score": 144174.37038547988 }, { "content": "#[inline]\n\nfn ge...
Rust
core/bin/zksync_api/src/signature_checker.rs
ihateaher0/zksync
1cda8c7c1a9bfbec6491a1e4634b0fc33b206834
use std::time::Instant; use futures::{ channel::{mpsc, oneshot}, StreamExt, }; use tokio::runtime::{Builder, Handle}; use zksync_config::ZkSyncConfig; use zksync_eth_client::ethereum_gateway::EthereumGateway; use zksync_types::tx::EthSignData; use zksync_types::{tx::TxEthSignature, SignedZkSyncTx, ZkSyncTx}...
use std::time::Instant; use futures::{ channel::{mpsc, oneshot}, StreamExt, }; use tokio::runtime::{Builder, Handle}; use zksync_config::ZkSyncConfig; use zksync_eth_client::ethereum_gateway::EthereumGateway; use zksync_types::tx::EthSignData; use zksync_types::{tx::TxEthSignature, SignedZkSyncTx, ZkSyncTx}...
let handle = runtime.handle().clone(); runtime.block_on(checker_routine(handle, input, eth_checker)); }) .expect("failed to start signature checker thread"); }
ub fn unwrap_tx(self) -> SignedZkSyncTx { match self.0 { TxVariant::Tx(tx) => tx, TxVariant::Batch(_, _) => panic!("called `unwrap_tx` on a `Batch` value"), } } pub fn unwrap_batch(self) -> (Vec<SignedZkSyncTx>, EthSignData) { match self.0 { TxVa...
random
[ { "content": "pub fn append_be_fixed_width<P: PrimeField>(content: &mut Vec<bool>, x: &P, width: usize) {\n\n let mut token_bits: Vec<bool> = BitIterator::new(x.into_repr()).collect();\n\n token_bits.reverse();\n\n token_bits.resize(width, false);\n\n token_bits.reverse();\n\n content.extend(toke...
Rust
sdk/storage_datalake/src/operations/path_patch.rs
rickrain/azure-sdk-for-rust
cca3d9f84e3e813fc9fed842cffa09e6b1ef3ad4
use crate::clients::PathClient; use crate::request_options::*; use crate::Properties; use azure_core::headers::{etag_from_headers, last_modified_from_headers}; use azure_core::prelude::*; use azure_core::{AppendToUrlQuery, Response as HttpResponse}; use azure_storage::core::headers::CommonStorageResponseHeaders; use by...
use crate::clients::PathClient; use crate::request_options::*; use crate::Properties; use azure_core::headers::{etag_from_headers, last_modified_from_headers}; use azure_core::prelude::*; use azure_core::{AppendToUrlQuery, Response as HttpResponse}; use azure_storage::core::headers::CommonStorageResponseHeaders; use by...
}
pub async fn try_from(response: HttpResponse) -> Result<Self, crate::Error> { let (_status_code, headers, _pinned_stream) = response.deconstruct(); let etag = match etag_from_headers(&headers) { Ok(tag) => Some(tag), _ => None, }; let last_modified = match last_...
function_block-full_function
[]
Rust
src/icons.rs
libcala/sprengui
e354113b77b5af52b69fe76fc4110a54299ced51
#![allow(unused)] use footile::{Plotter, Transform}; use pix::chan::Ch8; use pix::chan::Linear; use pix::chan::Premultiplied; use pix::{ el::{Pix1, Pixel}, matte::Matte8, ops::SrcOver, rgb::SRgba8, Raster, }; use rvg::*; const BACK: &[u8] = include_bytes!("../rvg/back.svg.rvg"); const EXIT: &[u8]...
#![allow(unused)] use footile::{Plotter, Transform}; use pix::chan::Ch8; use pix::chan::Linear; use pix::chan::Premultiplied; use pix::{ el::{Pix1, Pixel}, matte::Matte8, ops::SrcOver, rgb::SRgba8, Raster, }; use rvg::*; const BACK: &[u8] = include_bytes!("../rvg/back.svg.rvg"); const EXIT: &[u8]...
pub fn back<P>(&self, r: &mut Raster<P>, x: u16) where P::Chan: From<Ch8>, P: Pixel<Gamma = Linear, Alpha = Premultiplied>, { half(r, &self.back, x); } pub fn next<P>(&self, r: &mut Raster<P>, x: u16) where P::Chan: From<Ch8>, P: Pixel<Gamma = Linear, A...
ide: Graphic::load(HIDE).unwrap(), menu: Graphic::load(MENU).unwrap(), more: Graphic::load(MORE).unwrap(), new: Graphic::load(NEW).unwrap(), next: Graphic::load(NEXT).unwrap(), search: Graphic::load(SEARCH).unwrap(), view: Graphic::load(VIEW).unwra...
function_block-function_prefixed
[ { "content": "/// Text Input Field User Interface.\n\npub trait TextInput {\n\n /// Event handler.\n\n fn event(&mut self, event: TextEv);\n\n}\n\n\n\n/// User Interface Builder.\n\n// FIXME: Rename Ui\n\n#[derive(Default)]\n\npub struct UiBuilder {\n\n text_input: Option<Box<dyn TextInput>>,\n\n}\n\n\...
Rust
k9/tests/assertions/custom_comparison_formatters_test.rs
korrat/k9
cbbffbd015d72a949acf3a8e081ac22a5c575e9e
use crate::assertion_message; use k9::assert_equal; use std::collections::{HashMap, HashSet}; #[cfg(not(feature = "custom_comparison_formatters"))] #[test] fn test_assert_hash_sets_large_diff_without_custom_format() { super::setup_test_env(); let s1 = (1..100).collect::<HashSet<i32>>(); let s2 = (1..101)....
use crate::assertion_message; use k9::assert_equal; use std::collections::{HashMap, HashSet}; #[cfg(not(feature = "custom_comparison_formatters"))] #[test] fn test_assert_hash_sets_large_diff_without_custom_format() { super::setup_test_env(); let s1 = (1..100).collect::<HashSet<i32>>(); let s2 = (1..101)....
#[cfg(feature = "custom_comparison_formatters")] #[test] fn test_assert_hash_sets_large_diff_when_type_is_not_ord() { super::setup_test_env(); #[derive(PartialEq, Eq, Debug, Hash)] struct MyInt(i32); let s1 = ((1..100).map(MyInt)).collect::<HashSet<MyInt>>(); let s2 = ((1..101).map(MyInt)).colle...
fn test_assert_hash_maps_small_diff_with_custom_format() { super::setup_test_env(); let s1 = ((1..10).zip(1..10)).collect::<HashMap<i32, i32>>(); let s2 = ((1..11).zip(1..11)).collect::<HashMap<i32, i32>>(); k9_stable::assert_matches_inline_snapshot!( assertion_message(assert_equal!(s1, s2)), ...
function_block-full_function
[ { "content": "#[test]\n\nfn assert_equals_basic() -> Result<()> {\n\n k9_released::snapshot!(\n\n get_error_message(\"assert_equal_basic\")?,\n\n r\"\n\n\n\nrunning 0 tests\n\n\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n\n\n\n\n\nrunning 1 test\n\ntest assert...
Rust
core/src/views/list.rs
DGriffin91/VIZIA
0572656fe576d413ed1d52ff3aa911e4935e6a89
use std::marker::PhantomData; use keyboard_types::Code; use crate::{Binding, Context, Data, Handle, Lens, Model, MouseButton, TreeExt, View, WindowEvent}; #[derive(Debug)] pub struct ItemPtr<L, T> where L: Lens<Target = Vec<T>>, { lens: L, index: usize, row: usize, col: usize, } impl<L, T> Copy ...
use std::marker::PhantomData; use keyboard_types::Code; use crate::{Binding, Context, Data, Handle, Lens, Model, MouseButton, TreeExt, View, WindowEvent}; #[derive(Debug)] pub struct ItemPtr<L, T> where L: Lens<Target = Vec<T>>, { lens: L, index: usize, row: usize, col: usize, } impl<L, T> Copy ...
if let Some(callback) = self.increment_callback.take() { (callback)(cx); self.increment_callback = Some(callback); } } Code::ArrowUp => { if let Some(callback) = self.decr...
T> where L: Lens<Target = Vec<T>>, { pub fn new(lens: L, index: usize, row: usize, col: usize) -> Self { Self { lens, index, row, col } } pub fn index(&self) -> usize { self.index } pub fn row(&self) -> usize { self.row } pub fn col(&self) -> usize { ...
random
[ { "content": "pub trait Data: 'static + Clone {\n\n fn same(&self, other: &Self) -> bool;\n\n}\n\n\n\nmacro_rules! impl_data_simple {\n\n ($t:ty) => {\n\n impl Data for $t {\n\n fn same(&self, other: &Self) -> bool {\n\n self == other\n\n }\n\n }\n\n }...
Rust
const_format/tests/misc_tests/derive_tests/is_a_attributes.rs
rodrimati1992/const_format_crates
6403b4cbf020e2757aba57adc651f15cb845e563
use cfmt_b::{ coerce_to_fmt, fmt::{Error, Formatter, FormattingFlags, StrWriter}, impl_fmt, try_, wrapper_types::PWrapper, ConstDebug, }; use core::marker::PhantomData; pub struct Bar(pub u32); impl_fmt! { impl[] Bar; const fn const_debug_fmt(&self, f: &mut Formatter<'_>) -> Result<(), E...
use cfmt_b::{ coerce_to_fmt, fmt::{Error, Formatter, FormattingFlags, StrWriter}, impl_fmt, try_, wrapper_types::PWrapper, ConstDebug, }; use core::marker::PhantomData; pub struct Bar(pub u32); impl_fmt! { impl[] Bar; const fn const_debug_fmt(&self, f: &mut Formatter<'_>) -> Result<(), E...
fn opting_out_of_std() { const fn inner(f: &mut Formatter<'_>) -> Result<(), Error> { let wraps_opt = WrapsNamedOption { opt_a: type_named_option::Option(PhantomData), opt_b: type_named_option::Option(PhantomData), opt_c: type_named_option::Option(PhantomData), };...
function_block-full_function
[ { "content": "fn using_writec(writer: &mut StrWriter) -> cfmt::Result {\n\n // Trying to write to a non-writer\n\n writec!((), \"\")?;\n\n\n\n writec!(writer, \"{}\")?;\n\n\n\n writec!(writer, \"{}\", foo = \"\", 100u8)?;\n\n\n\n // trying to write an uninferred integer type\n\n writec!(writer...
Rust
src/ropeext.rs
calmofthestorm/starsector
93fbadde53b8bf687e0181e54ba5984abb694bf0
use std::borrow::Cow; use std::ops::{Bound, RangeBounds}; use ropey::{Rope, RopeSlice}; macro_rules! common_rope_ext_trait { () => { fn to_contiguous<'a>(&'a self) -> Cow<'a, str>; fn discontangle<'a, 'b>(&'a self, contiguous: &'b str, s: &'b str) -> RopeSlice<'a>; fn is_empty(&self) -> bo...
use std::borrow::Cow; use std::ops::{Bound, RangeBounds}; use ropey::{Rope, RopeSlice}; macro_rules! common_rope_ext_trait { () => { fn to_contiguous<'a>(&'a self) -> Cow<'a, str>; fn discontangle<'a, 'b>(&'a self, contiguous: &'b str, s: &'b str) -> RopeSlice<'a>; fn is_empty(&self) -> bo...
]; skip = 0; } match memchr::memchr(needle, &chunk.as_bytes()) { Some(index) => return index + bygones, None => { bygones += chunk.len(); } } } ...
ge.start_bound(), byte_range.end_bound()) { (Bound::Included(start), Bound::Excluded(end)) => { self.slice(self.byte_to_char(*start)..self.byte_to_char(*end)) } (Bound::Included(start), Bound::Included(end)) => { self.slice(self.byt...
random
[ { "content": "pub fn headline_level_str(input: &str, offset: usize) -> u16 {\n\n for (i, c) in input[offset..].as_bytes().iter().enumerate() {\n\n match c {\n\n b'*' => {}\n\n b' ' if i > 0 => return i as u16,\n\n _ => return 0,\n\n }\n\n }\n\n 0\n\n}\n\n\...
Rust
control-plane/rest/service/src/authentication.rs
fossabot/repo
cd08c8032796ab1a3edb8a8d1d4ffece607ec3d8
use actix_web::{Error, HttpRequest}; use jsonwebtoken::{crypto, Algorithm, DecodingKey}; use std::str::FromStr; use http::HeaderValue; use std::fs::File; pub fn init(jwk_path: Option<String>) -> JsonWebKey { match jwk_path { Some(path) => { let jwk_file = File::open(path).expect("Failed to ope...
use actix_web::{Error, HttpRequest}; use jsonwebtoken::{crypto, Algorithm, DecodingKey}; use std::str::FromStr; use http::HeaderValue; use std::fs::File; pub fn init(jwk_path: Option<String>) -> JsonWebKey { match jwk_path { Some(path) => { let jwk_file = File::open(path).expect("Failed to ope...
let token_file = std::env::current_dir() .expect("Failed to get current directory") .join("authentication") .join("token"); let mut token = std::fs::read_to_string(token_file) .expect("Failed to get bearer token"); let jwk_file = std::env::current_dir() .expect("Failed to...
function_block-function_prefix_line
[ { "content": "// Returns the path to the JWK file.\n\nfn jwk_file() -> String {\n\n let jwk_file = std::env::current_dir()\n\n .unwrap()\n\n .join(\"authentication\")\n\n .join(\"jwk\");\n\n jwk_file.to_str().unwrap().into()\n\n}\n\n\n\n// Setup the infrastructure ready for the tests....
Rust
src/structures.rs
BlackYoup/makair-telemetry
d7125865db156089ce17936d86d53eb825fba451
use std::cmp::{Ord, Ordering, PartialOrd}; use std::convert::TryFrom; use std::io; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Mode { Production, Qualification, IntegrationTest, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum Phase { Inhalation, Exhalation, } #[derive(Debug, Clone, Partia...
use std::cmp::{Ord, Ordering, PartialOrd}; use std::convert::TryFrom; use std::io; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Mode { Production, Qualification, IntegrationTest, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum Phase { Inhalation, Exhalation, } #[derive(Debug, Clone, Partia...
} #[derive(Debug, Clone, PartialEq, Eq)] pub struct BootMessage { pub version: String, pub device_id: String, pub systick: u64, pub mode: Mode, pub value128: u8, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct StoppedMessage { pub version: String, ...
y::Low), _ => Err(io::Error::new( io::ErrorKind::InvalidData, format!("Invalid priority {}", value), )), } }
function_block-function_prefixed
[ { "content": "pub fn message(input: &[u8]) -> IResult<&[u8], TelemetryMessage, TelemetryError<&[u8]>> {\n\n nom::branch::alt((\n\n boot,\n\n stopped,\n\n data_snapshot,\n\n machine_state_snapshot,\n\n alarm_trap,\n\n ))(input)\n\n .map_err(nom::Err::convert)\n\n}\n\n\...
Rust
src/mb_std/mb_share_mem/share_mem.rs
shady831213/mailbox_rs
9b809e9bceb54c5478f09f3356936cb15b431a68
use crate::mb_rpcs::*; use std::sync::Arc; use std::sync::Mutex; use crate::mb_std::utils::*; use xmas_elf::program; use xmas_elf::ElfFile; pub struct MBShareMemSpace<M: MBShareMemBlock> { mems: Vec<Arc<Mutex<M>>>, } impl<M: MBShareMemBlock> MBShareMemSpace<M> { pub fn new() -> MBShareMemSpace<M> { MB...
use crate::mb_rpcs::*; use std::sync::Arc; use std::sync::Mutex; use crate::mb_std::utils::*; use xmas_elf::program; use xmas_elf::ElfFile; pub struct MBShareMemSpace<M: MBShareMemBlock> { mems: Vec<Arc<Mutex<M>>>, } impl<M: MBShareMemBlock> MBShareMemSpace<M> { pub fn new() -> MBShareMemSpace<M> { MB...
fn read_slice<T: Sized>(&self, addr: MBPtrT, data: &mut [T]) { let len = self.read(addr, unsafe { std::slice::from_raw_parts_mut( (data.as_mut_ptr() as *mut T) as *mut u8, std::mem::size_of::<T>() * data.len(), ) }); if len != std::me...
fn write_slice<T: Sized>(&mut self, addr: MBPtrT, data: &[T]) { let len = self.write(addr, unsafe { std::slice::from_raw_parts( (data.as_ptr() as *const T) as *const u8, std::mem::size_of::<T>() * data.len(), ) }); if len != std::mem::size_...
function_block-full_function
[ { "content": "pub fn mb_open_file(path: &str, flags: u32) -> std::io::Result<File> {\n\n Ok(File::with_options()\n\n .create(flags & (MB_FILE_WRITE | MB_FILE_APPEND | MB_FILE_TRUNC) != 0)\n\n .write(flags & (MB_FILE_WRITE | MB_FILE_APPEND | MB_FILE_TRUNC) != 0)\n\n .append(flags & MB_FIL...
Rust
truck-rendimpl/src/polygon_instance.rs
ricosjp/truck
abd5b44222a005e6af76d774d2d2e8f7fa1c2dec
use crate::*; impl PolygonInstance { #[inline(always)] pub fn clone_instance(&self) -> PolygonInstance { PolygonInstance { polygon: self.polygon.clone(), state: self.state.clone(), shaders: self.shaders.clone(), id: RenderID::gen(), } } ...
use crate::*; impl PolygonInstance { #[inline(always)] pub fn clone_instance(&self) -> PolygonInstance { PolygonInstance { polygon: self.polygon.clone(), state: self.state.clone(), shaders: self.shaders.clone(), id: RenderID::gen(), } } ...
}, VertexAttribute { format: VertexFormat::Float32x3, offset: 2 * 4 + 3 * 4, shader_location: 2, }, ], }], }, f...
r) -> Arc<BindGroupLayout> { Arc::new(match self.state.texture.is_some() { true => self.textured_bdl(device_handler.device()), false => self.non_textured_bdl(device_handler.device()), }) } #[inline(always)] fn bind_group( &self, device_handler: &Device...
random
[ { "content": "pub fn render_one<R: Rendered>(scene: &mut Scene, object: &R) -> Vec<u8> {\n\n scene.add_object(object);\n\n let res = pollster::block_on(scene.render_to_buffer());\n\n scene.remove_object(object);\n\n res\n\n}\n\n\n", "file_path": "truck-rendimpl/tests/common.rs", "rank": 0, ...
Rust
api/src/quad/stream.rs
hoijui/sophia_rs
6ea179e77f9056ae7ed733e0e2018156bc7c42b7
use std::error::Error; use crate::dataset::*; use crate::quad::streaming_mode::*; use crate::quad::*; pub use crate::triple::stream::{SinkError, SourceError, StreamError, StreamResult}; mod _filter; pub use _filter::*; mod _filter_map; pub use _filter_map::*; mod _iterator; pub use _iterator::*; mod _map; pub use _...
use std::error::Error; use crate::dataset::*; use crate::quad::streaming_mode::*; use crate::quad::*; pub use crate::triple::stream::{SinkError, SourceError, StreamError, StreamResult}; mod _filter; pub use _filter::*; mod _filter_map; pub use _filter_map::*; mod _iterator; pub use _iterator::*; mod _map; pub use _...
#[inline] fn for_some_quad<F>(&mut self, f: &mut F) -> Result<bool, Self::Error> where F: FnMut(StreamedQuad<Self::Quad>), { self.try_for_some_quad(&mut |t| -> Result<(), Self::Error> { f(t); Ok(()) }) .map_err(StreamError::inner_in...
fn try_for_each_quad<F, E>(&mut self, f: F) -> StreamResult<(), Self::Error, E> where F: FnMut(StreamedQuad<Self::Quad>) -> Result<(), E>, E: Error, { let mut f = f; while self.try_for_some_quad(&mut f)? {} Ok(()) }
function_block-full_function
[ { "content": "pub fn as_box_q<Q: Quad, E>(quad: Result<Q, E>) -> ([BoxTerm; 3], Option<BoxTerm>)\n\nwhere\n\n E: Debug,\n\n{\n\n let quad = quad.unwrap();\n\n (\n\n [quad.s().copied(), quad.p().copied(), quad.o().copied()],\n\n quad.g().map(CopyTerm::copy),\n\n )\n\n}\n\n\n", "file...
Rust
carbide_core/src/state/animated_state.rs
HolgerGottChristensen/carbide
dda3c0426b8c6a9001eadb16ab0b2369e26ed1be
use std::fmt::Debug; use std::ops::{Add, DerefMut, Mul}; use std::time::{Duration, Instant}; use crate::environment::Environment; use crate::state::{InnerState, MapOwnedState, State, StateContract, TState}; use crate::state::animation_curve::linear; use crate::state::value_cell::{ValueCell, ValueRef, ValueRefMut}; use...
use std::fmt::Debug; use std::ops::{Add, DerefMut, Mul}; use std::time::{Duration, Instant}; use crate::environment::Environment; use crate::state::{InnerState, MapOwnedState, State, StateContract, TState}; use crate::state::animation_curve::linear; use crate::state::value_cell::{ValueCell, ValueRef, ValueRefMut}; use...
} impl State<f64> for AnimatedState { fn capture_state(&mut self, _: &mut Environment) {} fn release_state(&mut self, _: &mut Environment) {} fn value(&self) -> ValueRef<f64> { self.calc_percentage(); self.percent.borrow() } fn value_mut(&mut self) -> ValueRefMut<f64> { ...
pub fn calc_percentage(&self) { let current_time = self.frame_time.borrow(); let duration = *current_time - self.start_time; let percentage = match self.repeat_mode { RepeatMode::None => { if duration > self.duration { 1.0 } else {...
function_block-full_function
[ { "content": "pub fn linear(input: f64) -> f64 {\n\n input\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 0, "score": 394139.264417755 }, { "content": "pub fn linear_to_ease_out(input: f64) -> f64 {\n\n cubic_bezier(input, Position::new(0.35, 0.91), Posi...
Rust
crates/livesplit-hotkey/src/linux/mod.rs
LiveSplit/livesplit-core
04f0391fed72869c535abd9cb8843954dcecd3c9
use crate::KeyCode; use mio::{unix::SourceFd, Events, Interest, Poll, Token, Waker}; use promising_future::{future_promise, Promise}; use std::{ collections::hash_map::{Entry, HashMap}, mem, os::raw::{c_int, c_uint}, ptr, sync::mpsc::{channel, Sender}, thread::{self, JoinHandle}, }; use x11_dl::...
use crate::KeyCode; use mio::{unix::SourceFd, Events, Interest, Poll, Token, Waker}; use promising_future::{future_promise, Promise}; use std::{ collections::hash_map::{Entry, HashMap}, mem, os::raw::{c_int, c_uint}, ptr, sync::mpsc::{channel, Sender}, thread::{self, JoinHandle}, }; use x11_dl::...
pub fn unregister(&self, hotkey: KeyCode) -> Result<()> { let (future, promise) = future_promise(); self.sender .send(Message::Unregister(hotkey, promise)) .map_err(|_| Error::ThreadStopped)?; self.waker.wake().map_err(|_| Error::ThreadStopped)?; future.v...
pub fn register<F>(&self, hotkey: KeyCode, callback: F) -> Result<()> where F: FnMut() + Send + 'static, { let (future, promise) = future_promise(); self.sender .send(Message::Register(hotkey, Box::new(callback), promise)) .map_err(|_| Error::ThreadStopped)?; ...
function_block-full_function
[ { "content": "type RegisteredKeys = Mutex<HashMap<KeyCode, Box<dyn FnMut() + Send + 'static>>>;\n\n\n\npub struct Hook {\n\n event_loop: RunLoop,\n\n hotkeys: Arc<RegisteredKeys>,\n\n}\n\n\n\nimpl Drop for Hook {\n\n fn drop(&mut self) {\n\n unsafe {\n\n let mode = cf::CFRunLoopCopyCu...
Rust
src/container.rs
macarrie/vidocq
e63d1ad9b603a8920d7a6e1fde9ef96dbb3b8399
extern crate serde; use super::utils; use regex::Regex; #[derive(Debug, PartialEq)] pub enum Container { AVI, Matroska, MP4, MXF, Ogg, QuickTime, } impl serde::Serialize for Container { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serialize...
extern crate serde; use super::utils; use regex::Regex; #[derive(Debug, PartialEq)] pub enum Container { AVI, Matroska, MP4, MXF, Ogg, QuickTime, } impl serde::Serialize for Container { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serialize...
::find_and_strip(&name, RE_MP4.to_vec()); if matched { matched_container = Some(Container::MP4); return (matched_container, stripped_name); } let (matched, stripped_name) = utils::find_and_strip(&name, RE_MXF.to_vec()); if matched { matched_container = Some(Container::MXF); ...
ialize_unit_variant("Container", 0, "avi"), Container::Matroska => serializer.serialize_unit_variant("Container", 0, "mkv"), Container::MP4 => serializer.serialize_unit_variant("Container", 0, "mp4"), Container::MXF => serializer.serialize_unit_variant("Container", 0, "mxf"), ...
random
[ { "content": "pub fn parse(name: &str) -> i32 {\n\n lazy_static! {\n\n static ref RE_UNMARKED_YEAR: Regex = Regex::new(r\"(?P<year>19\\d{2}|20\\d{2})\").unwrap();\n\n static ref RE_MARKED_YEAR: Regex = Regex::new(r\"\\((?P<year>19\\d{2}|20\\d{2})\\)\").unwrap();\n\n }\n\n\n\n let unmarked...
Rust
client-rust/src/animation.rs
AnimatedLEDStrip/AnimatedLEDStripClient
adaa2d157555bf0cd68639718da82c3e918dbf0c
use crate::animation::Animation::*; #[derive(Debug, Eq, PartialEq)] pub enum Animation { Color, CustomAnimation, CustomRepetitiveAnimation, Alternate, Bounce, BounceToColor, CatToy, CatToyToColor, FadeToColor, Fireworks, Meteor, MultiPixelRun, MultiPixelRunToColor, ...
use crate::animation::Animation::*; #[derive(Debug, Eq, PartialEq)] pub enum Animation { Color, CustomAnimation, CustomRepetitiveAnimation, Alternate, Bounce, BounceToColor, CatToy, CatToyToColor, FadeToColor, Fireworks, Meteor, MultiPixelRun, MultiPixelRunToColor, ...
#[test] fn test_anim_from_string() { assert_eq!(animation_from_string("COLOR"), Color); assert_eq!(animation_from_string("CUSTOMANIMATION"), CustomAnimation); assert_eq!(animation_from_string("CUSTOMREPETITIVEANIMATION"), CustomRepetitiveAnimation); assert_eq!(animation_from_st...
assert_eq!(BounceToColor.to_string(), "BOUNCETOCOLOR"); assert_eq!(CatToy.to_string(), "CATTOY"); assert_eq!(CatToyToColor.to_string(), "CATTOYTOCOLOR"); assert_eq!(FadeToColor.to_string(), "FADETOCOLOR"); assert_eq!(Fireworks.to_string(), "FIREWORKS"); assert_eq!(Meteor.to_strin...
function_block-function_prefix_line
[ { "content": "pub fn direction_from_string(direction: &str) -> Direction {\n\n match &direction.to_uppercase()[..] {\n\n \"FORWARD\" => Direction::Forward,\n\n \"BACKWARD\" => Direction::Backward,\n\n _ => Direction::Forward\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg_attr(tarpaulin, skip...
Rust
src/main.rs
mkihr-ojisan/waseda-moodle-checker
39bdb16affcea3f62142e5e01591d9de56c54243
mod error; mod login; use error::{Error, ErrorKind}; use failure::ResultExt; use html_extractor::*; type Result<T> = std::result::Result<T, Error>; macro_rules! print_f { ($($tt:tt)*) => {{ print!($($tt)*); use std::io::Write; std::io::stdout().flush().unwrap(); }}; } #[tokio::main] ...
mod error; mod login; use error::{Error, ErrorKind}; use failure::ResultExt; use html_extractor::*; type Result<T> = std::result::Result<T, Error>; macro_rules! print_f { ($($tt:tt)*) => {{ print!($($tt)*); use std::io::Write; std::io::stdout().flush().unwrap(); }}; } #[tokio::main] ...
write!(writer, "{}", course_page.root_element().html())?; } if !quiet { println!("(status={:?})", status); } Ok(status) } #[derive(Debug, PartialEq)] enum Status { NoUpdates, FirstFetched, Updated, } html_extractor! { CoursePage { content: String = (inner_html...
let mut writer = std::fs::OpenOptions::new() .write(true) .create(true) .truncate(true) .open(downloaded_course_page)?;
assignment_statement
[]
Rust
pallets/kitties/src/lib.rs
fbielejec/exercise-3
edd6ee18821088a90c3784b83a4817c3b112d0f0
#![cfg_attr(not(feature = "std"), no_std)] use frame_support::{pallet_prelude::*, traits::Randomness}; use frame_system::pallet_prelude::*; pub use pallet::*; use sp_io::hashing::blake2_128; use sp_runtime::ArithmeticError; #[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)] pub enum Gender { Male, ...
#![cfg_attr(not(feature = "std"), no_std)] use frame_support::{pallet_prelude::*, traits::Randomness}; use frame_system::pallet_prelude::*; pub use pallet::*; use sp_io::hashing::blake2_128; use sp_runtime::ArithmeticError; #[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)] pub enum Gender { Male, ...
#[pallet::weight(1000)] pub fn breed(origin: OriginFor<T>, parent1: u32, parent2: u32) -> DispatchResult { let sender = ensure_signed(origin)?; let kitty1 = Self::kitties(sender.clone(), parent1).ok_or(Error::<T>::NotKittyOwner)?; let kitty2 =...
lf::next_kitty_id(); let gender = Kitty::gender(&dna); let kitty = Kitty { id, dna, gender }; Kitties::<T>::insert(&sender, id, kitty.clone()); safely_increment_kitty_id::<T>()?; Self::deposit_event(Event::KittyCreated(sender, id, kitty)); Ok(())...
function_block-function_prefixed
[ { "content": "\t#[pallet::config]\n\n\tpub trait Config: frame_system::Config {\n\n\t\t/// Because this pallet emits events, it depends on the runtime's definition of an event.\n\n\t\ttype Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;\n\n\t}\n\n\n\n\t#[pallet::pallet]\n\n\t#[pallet::...
Rust
src/indicators/trix.rs
Mad-ness/yata
96fd889141d2ab18a3b51f7c525b44d08f9a1311
use crate::core::{ Error, IndicatorConfig, IndicatorInstance, IndicatorResult, Method, PeriodType, Source, OHLCV, }; use crate::helpers::{method, RegularMethod, RegularMethods}; use crate::methods::{Change, Cross, ReversalSignal, TMA}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; #[derive(Debug, Cl...
use crate::core::{ Error, IndicatorConfig, IndicatorInstance, IndicatorResult, Method, PeriodType, Source, OHLCV, }; use crate::helpers::{method, RegularMethod, RegularMethods}; use crate::methods::{Change, Cross, ReversalSignal, TMA}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; #[derive(Debug, Cl...
fn size(&self) -> (u8, u8) { (2, 3) } } impl Default for Trix { fn default() -> Self { Self { period1: 18, period2: 6, method2: RegularMethods::EMA, source: Source::Close, } } } #[derive(Debug)] pub struct TRIXInstance { cfg: Trix, tma: TMA, sig: RegularMethod, change: Change, cross1: C...
Err(_) => return Err(Error::ParameterParse(name.to_string(), value.to_string())), Ok(value) => self.source = value, }, _ => { return Err(Error::ParameterParse(name.to_string(), value)); } }; Ok(()) }
function_block-function_prefix_line
[ { "content": "#[inline]\n\n#[must_use]\n\npub fn sign(value: ValueType) -> ValueType {\n\n\t// if value > 0. {\n\n\t// \t1.\n\n\t// } else if value < 0. {\n\n\t// \t-1.\n\n\t// } else {\n\n\t// \t0.\n\n\t// }\n\n\t((value > 0.) as i8 - (value < 0.) as i8) as ValueType\n\n}\n\n\n\n/// signi is like [`f64::signum...
Rust
sqlx-core/src/error.rs
PoiScript/sqlx
fb66cfa66563e45a0f0dad3c8fd7dba8a264d346
use std::error::Error as StdError; use std::fmt::{self, Debug, Display}; use std::io; pub type Result<T, E = Error> = std::result::Result<T, E>; #[derive(Debug)] #[non_exhaustive] pub enum Error { Io(io::Error), UrlParse(url::ParseError), Database(Box<dyn DatabaseError + Send + Sync>), ...
use std::error::Error as StdError; use std::fmt::{self, Debug, Display}; use std::io; pub type Result<T, E = Error> = std::result::Result<T, E>; #[derive(Debug)] #[non_exhaustive] pub enum Error { Io(io::Error), UrlParse(url::ParseError), Database(Box<dyn DatabaseError + Send + Sync>), ...
} } impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::Io(error) => write!(f, "{}", error), Error::UrlParse(error) => write!(f, "{}", error), Error::Decode(error) => write!(f, "{}", error), ...
match self { Error::Io(error) => Some(error), Error::UrlParse(error) => Some(error), Error::PoolTimedOut(Some(error)) => Some(&**error), Error::Decode(error) => Some(&**error), Error::Tls(error) => Some(&**error), _ => None, }
if_condition
[ { "content": "pub trait TypeInfo: Debug + Display + Clone {\n\n /// Compares type information to determine if `other` is compatible at the Rust level\n\n /// with `self`.\n\n fn compatible(&self, other: &Self) -> bool;\n\n}\n\n\n", "file_path": "sqlx-core/src/types.rs", "rank": 1, "score": ...
Rust
contracts/pool-token/src/entrypoints.rs
pylon-protocol/pylon-gateway-contracts
c8be4956d70f4d9da197191e78efc0deb399ba98
#[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, Uint128, }; use cw2::set_contract_version; use cw20::{ AllAccountsResponse, BalanceResponse, Cw20ExecuteMsg, Cw20QueryMsg, DownloadLogoResponse, Marke...
#[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, Uint128, }; use cw2::set_contract_version; use cw20::{ AllAccountsResponse, BalanceResponse, Cw20ExecuteMsg, Cw20QueryMsg, DownloadLogoResponse, Marke...
#[allow(dead_code)] #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, env: Env, info: MessageInfo, msg: Cw20ExecuteMsg, ) -> Result<Response, ContractError> { match msg { Cw20ExecuteMsg::Transfer { recipient, amount } => { executions::execute_tra...
mint: None, }, )?; Config::save(deps.storage, &Config { pool: pool_addr })?; Ok(Response::default()) }
function_block-function_prefix_line
[ { "content": "#[allow(dead_code)]\n\n#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn migrate(deps: DepsMut, env: Env, msg: MigrateMsg) -> Result<Response, ContractError> {\n\n match msg {\n\n MigrateMsg::Pylon {} => migrations::pylon::migrate(deps, env),\n\n MigrateMsg::Nexus {\n...
Rust
top-crates/src/main.rs
alexcrichton/rust-playground
3e85776b5769415f5ce4437b70dce8411367efc7
extern crate cargo; extern crate reqwest; #[macro_use] extern crate lazy_static; extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate toml; use std::collections::{BTreeMap, BTreeSet}; use std::collections::btree_map::Entry; use std::fs::File; use std::io::{Read, Write}; use cargo::core::{Depe...
extern crate cargo; extern crate reqwest; #[macro_use] extern crate lazy_static; extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate toml; use std::collections::{BTreeMap, BTreeSet}; use std::collections::btree_map::Entry; use std::fs::File; use std::io::{Read, Write}; use cargo::core::{Depe...
e {}", path); }
n unique_latest_crates { let pkgid = cargo::core::PackageId::new(&name, &version, &crates_io) .unwrap_or_else(|e| panic!("Unable to build PackageId for {} {}: {}", name, version, e)); let pkg = registry.download(&pkgid) .unwrap_or_else(|e| panic!("Unable to download {} {}: {}", ...
random
[ { "content": "fn run_handler<Req, Resp, F>(req: &mut Request, f: F) -> Result<Resp>\n\nwhere\n\n F: FnOnce(Sandbox, Req) -> Result<Resp>,\n\n Req: DeserializeOwned + Clone + Any + 'static,\n\n{\n\n let body = req.get::<bodyparser::Struct<Req>>()\n\n .map_err(Error::Deserialization)?;\n\n\n\n ...
Rust
examples/draw.rs
abusch/tactile-rs
f5584698d77c0f26d42f10e306022dcb791223ce
use std::{error::Error, io}; use crossterm::{event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode}, execute, terminal::{ disable_raw_mode, enable_raw_mode, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, }}; use glam::{dvec2, DMat3, DVec2}; use tactile::{get_tiling_ty...
use std::{error::Error, io}; use crossterm::{event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode}, execute, terminal::{ disable_raw_mode, enable_raw_mode, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, }}; use glam::{dvec2, DMat3, DVec2}; use tactile::{get_tiling_ty...
fn draw_tile(ctx: &mut Context, app: &App, t: &DMat3, c: Color) { for e in app.tiling.shapes() { let edge = &app.edges_shapes[e.id()]; let transform = *t * e.transform(); let p1 = transform.transform_point2(edge[0]); let p2 = transform.transform_point2(edge[1]); ctx.draw(&L...
t); draw_tile(ctx, app, &tile.transform, colors[c as usize]); } }) .x_bounds([-xbound, xbound]) .y_bounds([-ybound, ybound]); f.render_widget(canvas, chunks[0]); let text = vec![Spans::from(vec![ Span::styled("←/→", Style::default().add_modifier(...
function_block-function_prefixed
[ { "content": "/// Returns the `n`-th valid tiling type, which can be used to initialize a new instance of\n\n/// `IsohedralTiling`.\n\n///\n\n/// # Panics\n\n///\n\n/// This function panic if `n` is greater than 80.\n\npub fn get_tiling_type(n: usize) -> TilingType {\n\n assert!(\n\n n < 81,\n\n ...
Rust
src/bin/2021_day8.rs
ibookstein/aoc
6beb8369f80d47eef95022ced9a9b9a9bccc7d99
use aoc::aoc_input::get_input; use std::{collections::HashMap, str::FromStr}; fn part1(s: &str) { let mut total = 0usize; for line in s.trim().lines() { let output_values = line.split(" | ").nth(1).unwrap().split(' '); for val in output_values { total += match val.len() { ...
use aoc::aoc_input::get_input; use std::{collections::HashMap, str::FromStr}; fn part1(s: &str) { let mut total = 0usize; for line in s.trim().lines() { let output_values = line.split(" | ").nth(1).unwrap().split(' '); for val in output_values { total += match val.len() { ...
} fn part2(s: &str) { let total: u32 = s .trim() .lines() .map(|s| s.parse::<SigEntry>().unwrap().solve().unwrap()) .sum(); println!("Sum of all the output values: {}", total); } fn main() { let input = get_input(2021, 8); part1(&input); part2(&input); } #[cfg(te...
3), (four, 4), (five, 5), (six, 6), (seven, 7), (eight, 8), (nine, 9), ]; let map = HashMap::<_, _>::from_iter(map.into_iter()); let res = 1000 * *map.get(&self.output[0]).unwrap() + 100 * *map.get(&self.output[...
function_block-function_prefixed
[ { "content": "pub fn digits<T>(mut num: T, radix: T) -> impl Iterator<Item = T>\n\nwhere\n\n T: UnsignedDigits<T>,\n\n{\n\n let zero = T::zero();\n\n\n\n let mut divisor = T::one();\n\n while num >= divisor * radix {\n\n divisor *= radix;\n\n }\n\n\n\n std::iter::from_fn(move || {\n\n ...
Rust
cimage/src/filter.rs
cravattlab/abbasov
86d8609f9cb1932855dae054936aeb8e5a534cea
use super::*; #[derive(Clone, Debug, PartialEq, PartialOrd)] pub enum ProteinFilter { Reverse, Spectra(usize), ExcludeMatch(String), } #[derive(Copy, Clone, Default, Debug)] pub struct SecondPassFilter { pub twenties: usize, pub liganded: usize, pub not_liganded: usize, } impl ...
use super::*; #[derive(Clone, Debug, PartialEq, PartialOrd)] pub enum ProteinFilter { Reverse, Spectra(usize), ExcludeMatch(String), } #[derive(Copy, Clone, Default, Debug)] pub struct SecondPassFilter { pub twenties: usize, pub liganded: usize, pub not_liganded: usize, } impl ...
inFilter::Reverse); assert_eq!( filter.filter(Protein::new( String::from("Reverse_QQQQ"), String::default() )), None ); } }
ts() < *count { return None; } } _ => {} } } Some(constructed) } } #[cfg(test)] mod test { use super::PeptideFilter::*; use super::RatioFilter::*; use super::*; #[test] fn filter_20s() { ...
random
[ { "content": "pub fn liganded_tryptic_end(sequence: &str) -> bool {\n\n // .add_peptide_filter(PeptideFilter::ExcludeMatch(\"K.K*\"))\n\n // .add_peptide_filter(PeptideFilter::ExcludeMatch(\"R.K*\"))\n\n // .add_peptide_filter(PeptideFilter::ExcludeMatch(\"K*.K\"))\n\n // .add_peptide_filter(Peptide...
Rust
lapinou/src/lib.rs
gerritsangel/lapin
1d3e730c6ad10e329750649e4bf05cacad13d969
use lapin::{ executor::Executor, heartbeat::Heartbeat, reactor::{Reactor, ReactorBuilder, ReactorHandle, Slot}, socket_state::{SocketEvent, SocketStateHandle}, tcp::{TcpStream, TcpStreamWrapper}, ConnectionProperties, Result, }; use parking_lot::Mutex; use smol::{Async, Task, Timer}; use std::{c...
use lapin::{ executor::Executor, heartbeat::Heartbeat, reactor::{Reactor, ReactorBuilder, ReactorHandle, Slot}, socket_state::{SocketEvent, Soc
::new(Inner::default())), }))) } } impl Reactor for SmolReactor { fn register( &mut self, socket: &mut TcpStream, socket_state: SocketStateHandle, ) -> Result<usize> { let socket = Arc::new(Async::new(unsafe { TcpStreamWrapper::new(socket) })?); let slot = se...
ketStateHandle}, tcp::{TcpStream, TcpStreamWrapper}, ConnectionProperties, Result, }; use parking_lot::Mutex; use smol::{Async, Task, Timer}; use std::{collections::HashMap, fmt, future::Future, pin::Pin, sync::Arc}; pub trait LapinSmolExt { fn with_smol(self) -> Self where Self: Sized; fn...
random
[ { "content": "pub trait LapinTokioExt {\n\n fn with_tokio(self) -> Self\n\n where\n\n Self: Sized;\n\n\n\n fn with_tokio_executor(self) -> Self\n\n where\n\n Self: Sized;\n\n}\n\n\n\nimpl LapinTokioExt for ConnectionProperties {\n\n fn with_tokio(self) -> Self {\n\n self.with...
Rust
src/lib.rs
borisfaure/signin
9fe9ad9c949a5de4b2e32f097422851d17103962
#[macro_use] extern crate serde_derive; extern crate base64; extern crate openssl; extern crate serde; extern crate serde_json; extern crate time; pub mod errors; use errors::Error; use openssl::bn::BigNum; use openssl::hash::MessageDigest; use openssl::pkey::{PKey, Public}; use openssl::rsa::Rsa; use openssl::sign...
#[macro_use] extern crate serde_derive; extern crate base64; extern crate openssl; extern crate serde; extern crate serde_json; extern crate time; pub mod errors; use errors::Error; use openssl::bn::BigNum; use openssl::hash::MessageDigest; use openssl::pkey::{PKey, Public}; use openssl::rsa::Rsa; use openssl::sign...
fn verify_payload(ctx: &Ctx, payload: &Payload) -> Result<(), Error> { if payload.aud != ctx.client_id { return Err(Error::InvalidAudience); } if payload.iss != "accounts.google.com" && payload.iss != "https://accounts.google.com" { return Err(Error::InvalidIssuer); } let now = Off...
fn decode_payload(base64_payload: &str) -> Result<Payload, Error> { let payload_json = base64_decode_url(base64_payload)?; let obj: JsonValue = serde_json::from_slice(&payload_json)?; if !obj.is_object() { return Err(Error::InvalidTypeField("")); } let obj = obj.as_object().unwrap(); le...
function_block-full_function
[ { "content": "use base64;\n\nuse openssl;\n\nuse serde_json;\n\nuse std::fmt;\n\n\n\n#[derive(Debug)]\n\npub enum Error {\n\n DecodeBase64(base64::DecodeError),\n\n DecodeJson(serde_json::Error),\n\n OpensslError(openssl::error::ErrorStack),\n\n InvalidToken,\n\n InvalidIssuer,\n\n InvalidAudi...
Rust
clnt/src/webrtc.rs
leod/catchub
c3a049c1cf69c0bad81968a4df18a1f49dec385c
use std::{cell::RefCell, collections::VecDeque, rc::Rc, time::Duration}; use instant::Instant; use log::{info, warn}; use js_sys::{Reflect, JSON}; use wasm_bindgen::{prelude::*, JsCast}; use wasm_bindgen_futures::JsFuture; use web_sys::{ ErrorEvent, Event, MessageEvent, RtcConfiguration, RtcDataChannel, RtcData...
use std::{cell::RefCell, collections::VecDeque, rc::Rc, time::Duration}; use instant::Instant; use log::{info, warn}; use js_sys::{Reflect, JSON}; use wasm_bindgen::{prelude::*, JsCast}; use wasm_bindgen_futures::JsFuture; use web_sys::{ ErrorEvent, Event, MessageEvent, RtcConfiguration, RtcDataChannel, RtcData...
ectError> { let mut opts = web_sys::RequestInit::new(); opts.method("POST"); opts.mode(web_sys::RequestMode::SameOrigin); opts.body(Some( &Reflect::get(&offer, &JsValue::from_str("sdp")).unwrap(), )); let request = web_sys::Request::new_with_str_and_init(&address, &opts) .map_er...
function_block-function_prefixed
[ { "content": "pub fn event_duration(event: &Event) -> f32 {\n\n use Event::*;\n\n\n\n match event {\n\n PlayerAteFood { .. } => CIRCLE_DURATION,\n\n _ => 0.0,\n\n }\n\n}\n", "file_path": "clnt/src/view/active_event.rs", "rank": 2, "score": 194659.61277834035 }, { "cont...
Rust
src/image.rs
wherkamp/tux_img
bf83356ad97df46d0b8033a2999b8ba7e40311a6
use crate::action::{get_album_by_album_id, get_album_by_id, get_images}; use crate::schema::*; use crate::siteerror::SiteError; use derive_more::Display; use diesel::backend::Backend; use diesel::deserialize::FromSql; use diesel::mysql::Mysql; use diesel::serialize::{Output, ToSql}; use diesel::sql_types::Text; use die...
use crate::action::{get_album_by_album_id, get_album_by_id, get_images}; use crate::schema::*; use crate::siteerror::SiteError; use derive_more::Display; use diesel::backend::Backend; use diesel::deserialize::FromSql; use diesel::mysql::Mysql; use diesel::serialize::{Output, ToSql}; use diesel::sql_types::Text; use die...
lConnection) -> Result<ImageResponse, SiteError> { Ok(ImageResponse { id: image.id, album: get_album_by_id(image.id, conn)?.unwrap().album_id, about: image.about, url: "".to_string(), }) } }
ar("URL").unwrap(), album.album_id, x.file ), }); } Ok(Some(AlbumResponse { id: album.id, album_id: album.album_id, title: album.title, owner: album.owner, about: album.about, created: album.created, imag...
random
[]
Rust
src/core/relaxed_ik.rs
cairo-robotics/planning_core_rust
9a1ff401333276ee8199c682a3968cb7070b7719
use pyo3::prelude::*; use crate::core::vars::AgentVars; use crate::optimization::opt::{OptimizationEngineOpen, OptimizationEngineNLopt}; use crate::optimization::objective_master::ObjectiveMaster; use crate::utils_rust::file_utils::{*}; use crate::utils_rust::subscriber_utils::EEPoseGoalsSubscriber; use crate::utils_r...
use pyo3::prelude::*; use crate::core::vars::AgentVars; use crate::optimization::opt::{OptimizationEngineOpen, OptimizationEngineNLopt}; use crate::optimization::objective_master::ObjectiveMaster; use crate::utils_rust::file_utils::{*}; use crate::utils_rust::subscriber_utils::EEPoseGoalsSubscriber; use crate::utils_r...
pub fn solve_with_user_provided_goals(&mut self, pos_goals: Vec<Vec<f64>>, quat_goals: Vec<Vec<f64>>) -> Vec<f64> { let mut ee_sub = EEPoseGoalsSubscriber::new(); for i in 0..pos_goals.len() { ee_sub.pos_goals.push( Vector3::new( pos_goals[i][0], pos_goals[i][1], pos_goals[i][2] ) ); ...
f.om.tune_weight_priors(&self.vars); } self.groove.optimize(&mut out_x, &self.vars, &self.om, 100); self.vars.update(out_x.clone()); } out_x }
function_block-function_prefixed
[ { "content": "pub fn get_objective_mode(fp: String) -> String {\n\n let yaml_files = get_yaml_obj(fp);\n\n let yaml_file = &yaml_files[0];\n\n\n\n let objective_mode = yaml_file[\"loaded_robot\"][\"objective_mode\"].as_str().unwrap().to_string();\n\n objective_mode\n\n}\n\n\n", "file_path": "src...
Rust
dust-lpc8xx/src/swm/mod.rs
starblue/dust
8930b40a999239806c33d458af1bcf922378372b
#![allow(unused_macros)] #![allow(dead_code)] #[cfg(feature = "lpc802")] pub use self::swm_lpc802 as swm_variant; #[cfg(feature = "lpc804")] pub use self::swm_lpc804 as swm_variant; #[cfg(feature = "lpc81x")] pub use self::swm_lpc81x as swm_variant; #[cfg(feature = "lpc82x")] pub use self::swm_lpc82x as swm_variant;...
#![allow(unused_macros)] #![allow(dead_code)] #[cfg(feature = "lpc802")] pub use self::swm_lpc802 as swm_variant; #[cfg(feature = "lpc804")] pub use self::swm_lpc804 as swm_variant; #[cfg(feature = "lpc81x")] pub use self::swm_lpc81x as swm_variant; #[cfg(feature = "lpc82x")] pub use self::swm_lpc82x as swm_variant;...
} unsafe fn set_movable_fixed_function_pin_internal( &self, f: MovableFixedFunction, value: usize, ) { let shift = 2 * f.index; let mask: u32 = 3 << shift; let data: u32 = (value as u32) << shift; self.pinassign_fixed[f.reg].modify(|w| (w & !mask) | d...
if pin == f.pin1 { self.set_movable_fixed_function_pin_internal(f, 1); } else if pin == f.pin2 { self.set_movable_fixed_function_pin_internal(f, 2); } else { panic!("movable fixed function cannot be assigned to requested pin"); }
if_condition
[ { "content": "/// Dump a register in a nice format\n\nfn write_reg(header: &[u8], data: u32) {\n\n write_bytes(header);\n\n write_32(data);\n\n write_nl();\n\n}\n", "file_path": "dust-hardfault/src/lib.rs", "rank": 0, "score": 205613.59957420875 }, { "content": "/// Reverse the bit ...
Rust
src/announcement.rs
TepelStreeltjeEoA/eras-of-arda-discord-bot
3348fd9b90b5c819963870c6fc169864ba8e56be
use chrono::{DateTime, Utc}; use serde::{Deserialize, Deserializer, Serialize}; use serenity::builder::{CreateEmbed, CreateMessage, EditMessage}; use serenity::client::Context; use serenity::framework::standard::CommandResult; use serenity::futures::future::join_all; use serenity::model::interactions::message_compone...
use chrono::{DateTime, Utc}; use serde::{Deserialize, Deserializer, Serialize}; use serenity::builder::{CreateEmbed, CreateMessage, EditMessage}; use serenity::client::Context; use serenity::framework::standard::CommandResult; use serenity::futures::future::join_all; use serenity::model::interactions::message_compone...
pub async fn announce<'a>( ctx: &Context, channel: ChannelId, message: &'a Announcement, ) -> CommandResult { let mut builder = CreateMessage::default(); if let Some(content) = &message.content { builder.content(content); } if let Some(file) = &message.file { bu...
fn parse_embed(embed: &AnnouncementEmbed) -> CreateEmbed { let mut builder = CreateEmbed::default(); use AnnouncementEmbedAuthor::*; match &embed.author { Some(Object { name, url, icon }) => { builder.author(|a| { if let Some(url) = url { a.url(url);...
function_block-full_function
[ { "content": "pub fn parse_web_colour(name: &str) -> Option<Colour> {\n\n Some(Colour(match name {\n\n \"aliceblue\" => 0xf0f8ff,\n\n \"antiquewhite\" => 0xfaebd7,\n\n \"aqua\" => 0x00ffff,\n\n \"aquamarine\" => 0x7fffd4,\n\n \"azure\" => 0xf0ffff,\n\n \"beige\" => 0...
Rust
src/manifest/bare_version.rs
TDHolmes/cargo-msrv
9c52dc01eb90c888a725649f627f99fc8332998e
use std::convert::TryFrom; use std::fmt::{Display, Formatter}; use std::str::FromStr; type BareVersionUsize = u64; #[derive(Clone, Debug, Eq, PartialEq)] pub enum BareVersion { TwoComponents(BareVersionUsize, BareVersionUsize), ThreeComponents(BareVersionUsize, BareVersionUsize, BareVersionUsize), } impl Fro...
use std::convert::TryFrom; use std::fmt::{Display, Formatter}; use std::str::FromStr; type BareVersionUsize = u64; #[derive(Clone, Debug, Eq, PartialEq)] pub enum BareVersion { TwoComponents(BareVersionUsize, BareVersionUsize), ThreeComponents(BareVersionUsize, BareVersionUsize, BareVersionUsize), } impl Fro...
} } impl Display for BareVersion { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::TwoComponents(major, minor) => f.write_fmt(format_args!("{}.{}", major, minor)), Self::ThreeComponents(major, minor, patch) => { f.write_fmt(format_a...
match self { Self::TwoComponents(major, minor) => crate::semver::Version::new(*major, *minor, 0), Self::ThreeComponents(major, minor, patch) => { crate::semver::Version::new(*major, *minor, *patch) } }
if_condition
[ { "content": "/// Check if the given target is available.\n\n/// with `rustup target list`\n\npub fn is_target_available<S: AsRef<str>>(name: S) -> TResult<()> {\n\n let toolchain = name.as_ref();\n\n let output = RustupCommand::new()\n\n .with_stdout()\n\n .with_args(&[\"list\"])\n\n ...
Rust
hotel-rsvp/rust/src/main.rs
naomijub/tw-old-challenges
1214793e2269a2e589fcdca53a1e32f4336fb10e
use chrono::{prelude::*, Duration}; use model::HotelRsvp; use crate::core::{best_price, parse_client_date}; mod core; mod model; fn main() { let hotels = generate_hotels(); let client = parse_client_date("Regular: 16Mar2009(mon), 17Mar2009(tues), 18Mar2009(wed)").unwrap(); let hotel = best_price...
use chrono::{prelude::*, Duration}; use model::HotelRsvp; use crate::core::{best_price, parse_client_date}; mod core; mod model; fn main() { let hotels = generate_hotels(); let client = parse_client_date("Regular: 16Mar2009(mon), 17Mar2009(tues), 18Mar2009(wed)").unwrap(); let hotel = best_price...
#[test] fn no_blackouts_bridgewood() { let hotels = generate_hotels(); let client = parse_client_date("Regular: 20Mar2009(fri), 21Mar2009(sat), 22Mar2009(sun)").unwrap(); let hotel = best_price(hotels, client); assert_eq!(hotel, "bridgewood") } #[test] ...
fn no_blackouts_lakewood() { let hotels = generate_hotels(); let client = parse_client_date("Regular: 16Mar2009(mon), 17Mar2009(tues), 18Mar2009(wed)").unwrap(); let hotel = best_price(hotels, client); assert_eq!(hotel, "lakewood") }
function_block-full_function
[ { "content": "pub fn get_client_days(days: Vec<&str>) -> Result<Vec<Date<Utc>>, String> {\n\n days.into_iter()\n\n .map(|day| {\n\n format!(\"{} 00:00:00\", day)\n\n .replace(\"tues\", \"tue\")\n\n .replace(\"thur\", \"thu\")\n\n })\n\n .map(|day|...
Rust
kernel/kernel_main/src/handle_backends/process_egg.rs
FranchuFranchu/rust-0bsd-riscv-kernel
e31789c49540d2c1637ebcff72361c5505c52843
use alloc::{boxed::Box, collections::BTreeMap, string::String, sync::Arc}; use flat_bytes::Flat; use kernel_as_register::EncodedError; use kernel_cpu::csr::SATP_SV39; use crate::{ handle::HandleBackend, lock::future::rwlock::RwLock, paging::{ EntryBits::{RWX, USER, VALID}, Paging, },...
use alloc::{boxed::Box, collections::BTreeMap, string::String, sync::Arc}; use flat_bytes::Flat; use kernel_as_register::EncodedError; use kernel_cpu::csr::SATP_SV39; use crate::{ handle::HandleBackend, lock::future::rwlock::RwLock, paging::{ EntryBits::{RWX, USER, VALID}, Paging, },...
} } Entry(v) => { egg.start_address = v; } Hatch => { drop(egg); drop(btreemap_lock); let egg = self .handle_eggs .write() .await ...
if data.len() > index_in_data + page_offset + 4096 { next_page[..4096 - page_offset].copy_from_slice( &data[index_in_data + 4096 - page_offset ..(index_in_data + 4096).min(data.len())], ); }
if_condition
[ { "content": "pub fn new_supervisor_process_with_name(function: fn(), name: String) -> usize {\n\n let pid = new_supervisor_process(function);\n\n try_get_process(&pid).write().name = Some(name);\n\n pid\n\n}\n\n\n", "file_path": "kernel/kernel_main/src/process.rs", "rank": 0, "score": 3083...
Rust
src/lib.rs
heathsc/compress_io
c517fc0238e26e17271c4f82b38ad97018d3d07f
#[macro_use] extern crate lazy_static; pub mod compress; pub mod compress_type; pub mod filter_spec; pub mod tools; pub mod path_utils; #[cfg(feature = "async")] pub mod r#async; #[cfg(test)] mod tests { use crate::{ compress::CompressIo, compress_type::* }; use std::{ path::{PathBuf, Path}, io::{Read, ...
#[macro_use] extern crate lazy_static; pub mod compress; pub mod compress_type; pub mod filter_spec; pub mod tools; pub mod path_utils; #[cfg(feature = "async")] pub mod r#async; #[cfg(test)] mod tests { use crate::{ compress::CompressIo, compress_type::* }; use std::{ path::{PathBuf, Path}, io::{Read, ...
} fn test_rd(name: &Path, ctype: CompressType, test_string: &str) { assert_eq!(crate::path_utils::guess_ctype_from_file(name, None).expect("Error reading file"), ctype); let mut rdr = CompressIo::new().path(name).bufreader().expect("Couldn't open bufreader"); let mut buf = String::new(); rdr.read_to_st...
let name = self.mkpath(name); let test_string = "Testing testing 123"; { let mut wrt = CompressIo::new().path(&name).ctype(ctypes[0]).writer().expect("Could not make file"); write!(wrt, "{}", test_string).expect("Error writing to file"); } let name = crate::path_utils::cond_add_suffix(name, ctypes[0...
function_block-function_prefix_line
[ { "content": "pub fn check_read_ctype<P: AsRef<Path>>(name: Option<P>, ctype: CompressType, buf: Option<&mut CheckBuf>) -> io::Result<CompressType> {\n\n\tif matches!(ctype, CompressType::Unknown) {\n\n\t\tif let Some(s) = name {\n\n\t\t\tguess_ctype_from_file(s.as_ref(), buf)\n\n\t\t} else {\n\n\t\t\tif let So...
Rust
vm.rs
sam-b/gchq_can_you_crack_it
f0be0ffe36a0d2479e57dd5926b6fce8637b9d73
use std::error::Error; use std::io::prelude::*; use std::fs::File; use std::path::Path; const CS: usize = 4; const DS: usize = 5; const FL: usize = 6; const JMP: u8 = 0; const MOVR: u8 = 1; const MOVM: u8 = 2; const ADD: u8 = 3; const XOR: u8 = 4; const CMP: u8 = 5; const JMPE: u8 = 6; const HLT: u8 = 7; cons...
use std::error::Error; use std::io::prelude::*; use std::fs::File; use std::path::Path; const CS: usize = 4; const DS: usize = 5; const FL: usize = 6; const JMP: u8 = 0; const MOVR: u8 = 1; const MOVM: u8 = 2; const ADD: u8 = 3; const XOR: u8 = 4; const CMP: u8 = 5; const JMPE: u8 = 6; const HLT: u8 = 7; cons...
fn decode(ins: u8) -> u8 { (ins >> 5) & 7 } fn mod0(ins: u8) -> bool { ((ins >> 4) & 1) == 0 } fn op1(ins: u8) -> u8 { ins & 15 } fn op2(reg: &[i32], ip: i32, mem: &[u8]) -> i32 { mem[((reg[CS] * ALIGN) + ip) as usize] as i32 }
0x60, 0x62, 0x55, 0x5a, 0x4a, 0x66, 0x61, 0x11, 0x57, 0x68, 0x75, 0x05, 0x62, 0x36, 0x7d, 0x02, 0x10, 0x4b, 0x08, 0x22, 0x42, 0x32, 0xba, 0xe2, 0xb9, 0xe2, 0xd6, 0xb9, 0xff, 0xc3, 0xe9, 0x8a, 0x8f, 0xc1, 0x8f, 0xe1, 0xb8, 0xa4, 0x96, 0xf1, 0x8f, 0x81, 0xb1, 0x8d, 0x89, 0xcc, 0xd4, 0x78, 0x76, 0x61, 0x72, 0x3e, 0x37...
function_block-function_prefixed
[]
Rust
garnet/lib/rust/httpdate-hyper/src/lib.rs
winksaville/Fuchsia
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
use fuchsia_hyper; use futures::compat::Future01CompatExt; use hyper; use lazy_static::lazy_static; use rustls::Certificate; use std::cell::RefCell; use std::sync::{Arc, Mutex}; use webpki; use webpki_roots_fuchsia; type DateTime = chrono::DateTime<chrono::FixedOffset>; #[derive(Debug, PartialEq)] pub enum HttpsDat...
use fuchsia_hyper; use futures::compat::Future01CompatExt; use hyper; use lazy_static::lazy_static; use rustls::Certificate; use std::cell::RefCell; use std::sync::{Arc, Mutex}; use webpki; use webpki_roots_fuchsia; type DateTime = chrono::DateTime<chrono::FixedOffset>; #[derive(Debug, PartialEq)] pub enum HttpsDat...
or::InvalidHostname); Ok(()) }, ) } }
xedOffset::east(0).ymd(5000, 1, 1).and_hms(0, 0, 0); let error = get_network_time_backstop("google com", future_date).await.unwrap_err(); assert!(error.is_network_error() || error == HttpsDateErr
function_block-random_span
[]
Rust
examples/interactive_winit_app.rs
Pytal/skulpin
347daae91838693fb7880ea59dbcaade360f8d2d
use skulpin::skia_safe; use skulpin::app::AppHandler; use skulpin::app::AppError; use skulpin::app::AppBuilder; use skulpin::app::MouseButton; use skulpin::app::VirtualKeyCode; use skulpin::app::PhysicalPosition; use skulpin::LogicalSize; use skulpin::app::AppUpdateArgs; use skulpin::app::AppDrawArgs; use std::ffi::...
use skulpin::skia_safe; use skulpin::app::AppHandler; use skulpin::app::AppError; use skulpin::app::AppBuilder; use skulpin::app::MouseButton; use skulpin::app::VirtualKeyCode; use skulpin::app::PhysicalPosition; use skulpin::LogicalSize; use skulpin::app::AppUpdateArgs; use skulpin::app::AppDrawArgs; use std::ffi::...
} struct ExampleApp { last_fps_text_change: Option<std::time::Instant>, fps_text: String, previous_clicks: VecDeque<PreviousClick>, } impl ExampleApp { pub fn new() -> Self { ExampleApp { last_fps_text_change: None, fps_text: "".to_string(), previous_clicks...
fn new( position: PhysicalPosition<f64>, time: std::time::Instant, ) -> Self { PreviousClick { position, time } }
function_block-full_function
[ { "content": "fn main() {\n\n // Setup logging\n\n env_logger::Builder::from_default_env()\n\n .filter_level(log::LevelFilter::Debug)\n\n .init();\n\n\n\n let example_app = ExampleApp::new();\n\n\n\n AppBuilder::new()\n\n .app_name(CString::new(\"Skulpin Example App\").unwrap())...
Rust
src/header.rs
kiwiyou/paradocs
0f12aa0b08f07ab483881363abd3a20ea488c09f
use ego_tree::NodeRef; use scraper::{ElementRef, Node}; use selectors::attr::CaseSensitivity; use crate::atom::{ parse_code, parse_deprecated, parse_list, parse_p, parse_portability, parse_pre, parse_text_inside, parse_unstable, Details, Paragraph, TextPart, }; pub struct Fqn<'a> { pub title: Vec<TextPart...
use ego_tree::NodeRef; use scraper::{ElementRef, Node}; use selectors::attr::CaseSensitivity; use crate::atom::{ parse_code, parse_deprecated, parse_list, parse_p, parse_portability, parse_pre, parse_text_inside, parse_unstable, Details, Paragraph, TextPart, }; pub struct Fqn<'a> { pub title: Vec<TextPart...
has_class("top-doc", CaseSensitivity::CaseSensitive)) { return None; } for child in maybe_top_doc.children() { if let Some(doc_block) = parse_doc_block(child) { return Some(TopDoc { doc_block }); } } None } pub struct DocBlock<'a> { pub sections: Vec<Section...
else(|| parse_unstable(child)); portability = portability.or_else(|| parse_portability(child)); deprecation = deprecation.or_else(|| parse_deprecated(child)); } Some(ItemInfo { stability, portability, deprecation, }) } pub struct TopDoc<'a> { pub doc_block: DocB...
random
[ { "content": "pub fn parse_text_inside_to<'a>(node: NodeRef<'a, Node>, buffer: &mut Vec<TextPart<'a>>) {\n\n for child in node.children() {\n\n parse_text_outside_to(child, buffer);\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Details<'a> {\n\n pub summary: Vec<TextPart<'a>>,\n\n pub deta...
Rust
src/cpu/opcode.rs
aphistic/gabba
64b9cd0b5907b05b66df3439dfac2958d918b146
use std::fmt; use std::process::id; pub const OP_SIZE: usize = 4; const COND_EQ: u8 = 0b0000; const COND_NE: u8 = 0b0001; const COND_CSHS: u8 = 0b0010; const COND_CCLO: u8 = 0b0011; const COND_MI: u8 = 0b0100; const COND_PL: u8 = 0b0101; const COND_VS: u8 = 0b0110; const COND_VC: u8 = 0b0111; const COND_HI: u8 = 0b10...
use std::fmt; use std::process::id; pub const OP_SIZE: usize = 4; const COND_EQ: u8 = 0b0000; const COND_NE: u8 = 0b0001; const COND_CSHS: u8 = 0b0010; const COND_CCLO: u8 = 0b0011; const COND_MI: u8 = 0b0100; const COND_PL: u8 = 0b0101; const COND_VS: u8 = 0b0110; const COND_VC: u8 = 0b0111; const COND_HI: u8 = 0b10...
ch opdata & MASK_MOV { OP_MOV => { println!("op mov"); let r = (opdata & MASK_MOV_R) as usize; let shifter_operand = (opdata & MASK_MOV_SHIFTER) as i32; Some(Op::Mov(r, shifter_operand)) } _ ...
SR: u32 = 0x0DB00000; const MASK_MSR_R: u32 = 0x00400000; const MASK_MSR_25: u32 = 0x02000000; const MASK_MSR_IMMEDIATE: u32 = 0x000000ff; const MASK_MSR_ROTATE: u32 = 0x00000f00; const MASK_MSR_FIELD_MASK: u32 = 0x000f0000; #[derive(Debug, PartialEq)] pub enum Op { B(i32), Bl(i32), Bx, Blx, M...
random
[ { "content": "use std::collections::BTreeMap;\n\n\n\n// TODO Mirroring support in memory\n\n\n\nconst KBYTE: usize = 1024;\n\n\n\npub const SYS_ROM: u32 = 0x00_00_00_00;\n\nconst SYS_ROM_SIZE: usize = 16 * KBYTE;\n\n\n\npub const EXT_WRAM: u32 = 0x02_00_00_00;\n\nconst EXT_WRAM_SIZE: usize = 256 * KBYTE;\n\n\n\...
Rust
src/syntax/ast/visitor.rs
pvginkel/rjs
61391286b0f0d6ce23720ee13501f62751c26b29
use syntax::ast::*; pub trait AstVisitor<'a> { fn visit_function(&mut self, function: &'a Function) { self.visit_root_block(&function.block); } fn visit_root_block(&mut self, block: &'a RootBlock) { self.visit_block(&block.block); } fn visit_block(&mut self, blo...
use syntax::ast::*; pub trait AstVisitor<'a> { fn visit_function(&mut self, function: &'a Function) { self.visit_root_block(&function.block); } fn visit_root_block(&mut self, block: &'a RootBlock) { self.visit_block(&block.block); } fn visit_block(&mut self, blo...
fn visit_expr_binary(&mut self, expr: &'a Expr) { if let Expr::Binary(_, ref lhs, ref rhs) = *expr { self.visit_expr(lhs); self.visit_expr(rhs); } } fn visit_expr_cast(&mut self, expr: &'a Expr) { if let Expr::Cast(_, ref expr) = *expr { ...
isit_expr_assign(&mut self, expr: &'a Expr) { if let Expr::Assign(_, ref lhs, ref rhs) = *expr { self.visit_expr(lhs); self.visit_expr(rhs); } }
function_block-function_prefixed
[ { "content": "#[allow(unused_variables)]\n\npub trait JsItem {\n\n fn as_value(&self) -> JsValue;\n\n \n\n fn get_own_property(&self, env: &JsEnv, property: Name) -> Option<JsDescriptor> {\n\n None\n\n }\n\n \n\n // 8.12.2 [[GetProperty]] (P)\n\n fn get_property(&self, env: &JsEnv, p...
Rust
src/ecdsa/signer.rs
ipaljak-tbtl/yubihsm.rs
a1d05480264d8797b4b861168f721b095cdfca25
use super::{algorithm::CurveAlgorithm, NistP256, NistP384}; use crate::{object, Client}; use ::ecdsa::{ elliptic_curve::{ consts::{U1, U32}, generic_array::ArrayLength, sec1::{self, UncompressedPointSize, UntaggedPointSize}, weierstrass::{Curve, PointCompression}, }, Signat...
use super::{algorithm::CurveAlgorithm, NistP256, NistP384}; use crate::{object, Client}; use ::ecdsa::{ elliptic_curve::{ consts::{U1, U32}, generic_array::ArrayLength, sec1::{self, UncompressedPointSize, UntaggedPointSize}, weierstrass::{Curve, PointCompression}, }, Signat...
fn sign_ecdsa_digest<D: Digest>(&self, digest: D) -> Result<Vec<u8>, Error> { self.client .sign_ecdsa_prehash_raw(self.signing_key_id, digest.finalize().as_slice()) .map_err(Error::from_source) } pub fn public_key(&self) -> &sec1::EncodedPoint<C> { &self....
pub fn create(client: Client, signing_key_id: object::Id) -> Result<Self, Error> { let public_key = client .get_public_key(signing_key_id)? .ecdsa() .ok_or_else(Error::new)?; Ok(Self { client, signing_key_id, public_key, })...
function_block-function_prefix_line
[ { "content": "/// Initialize an HSM device with the given profile.\n\n///\n\n/// This approach does not erase the device first, but generally assumes\n\n/// the HSM is in a clean state.\n\n///\n\n/// The recommended approach is to use `erase_device_and_init_with_profile`\n\npub fn init_with_profile(client: Clie...
Rust
src/apppath.rs
mkazutaka/ramup
c5d4cf164990379c13cdc1f69d7af92ed714c475
use anyhow::{Context, Result}; use path_abs::PathInfo; use serde::export::TryFrom; use std::path::{Path, PathBuf}; #[derive(Debug)] pub struct AbsPath { path: String, } impl AbsPath { #[allow(dead_code)] pub fn new<P: AsRef<Path>>(p: P) -> Result<Self> { let p = AbsPath::expand(p).expect("|| Faile...
use anyhow::{Context, Result}; use path_abs::PathInfo; use serde::export::TryFrom; use std::path::{Path, PathBuf}; #[derive(Debug)] pub struct AbsPath { path: String, } impl AbsPath { #[allow(dead_code)] pub fn new<P: AsRef<Path>>(p: P) -> Result<Self> { let p = AbsPath::expand(p).expect("|| Faile...
let expect = Path::new(&current).join(".hoge"); let actual = AbsPath::expand(".hoge").unwrap(); assert_eq!(expect, actual); let expect = Path::new(&home).join("hoge"); let actual = AbsPath::expand("~/hoge").unwrap(); assert_eq!(expect, actual); } }
"Failed to strip `.` from path")?; return Ok(current.join(p)); }; if p.starts_with("~") { let home = std::env::var("HOME").with_context(|| "Failed to get home Dir")?; let p = p .strip_prefix("~") .with_context(|| "Failed to strip `~` f...
random
[ { "content": "pub fn relocate<S: AsRef<Path>, P: AsRef<Path>>(from: &S, to: &P) -> Result<()> {\n\n let mut option = CopyOptions::new();\n\n option.overwrite = true;\n\n\n\n let from_str = from.as_ref().to_str().expect(\"failed to convert str\");\n\n\n\n let size = fs_extra::dir::get_size(from)?;\n\...
Rust
shellfn-attribute/src/block_builder.rs
synek317/shellfn
e1917ade0212950a6c0620d61ed59bfe1eae370d
use crate::attributes::Attributes; use crate::output_type::OutputType; use crate::utils::*; use proc_macro2::{Ident, Span, TokenStream as TokenStream2}; use quote::quote; use syn::{FnArg, GenericArgument, PathArguments, ReturnType, Type, TypeImplTrait, TypeParamBound}; const PROGRAM: &'static str = "PROGRAM"; #[deriv...
use crate::attributes::Attributes; use crate::output_type::OutputType; use crate::utils::*; use proc_macro2::{Ident, Span, TokenStream as TokenStream2}; use quote::quote; use syn::{FnArg, GenericArgument, PathArguments, ReturnType, Type, TypeImplTrait, TypeParamBound}; const PROGRAM: &'static str = "PROGRAM"; #[deriv...
fn with_unit_return_type(&mut self) { self.output_type = OutputType::Void; } fn with_vec_return_type(&mut self, typ: &Type) { self.output_type = OutputType::Vec; if let Type::Path(ref type_path) = typ { let args = &type_path.path.segments.last().unwrap().value().argum...
pub fn with_return_type(mut self, return_type: ReturnType) -> Self { match return_type { ReturnType::Default => { self.with_unit_return_type(); } ReturnType::Type(_, ref t) => match **t { Type::Path(ref type_path) if is_result_type_path(type_pa...
function_block-full_function
[ { "content": "#[proc_macro_attribute]\n\npub fn shell(attr: TokenStream, input: TokenStream) -> TokenStream {\n\n let input = syn::parse_macro_input!(input as syn::ItemFn);\n\n let attr_args = syn::parse_macro_input!(attr as syn::AttributeArgs);\n\n let attrs = Attributes::from_list(&attr_args).expect(...
Rust
pathfinder/src/diff_solver/post_processing_v5/hull_calc/mod.rs
Simula-UiB/CRHS
8f3dd34c8b99680188d9314c6897e0c790f5358f
use std::fmt; use std::fmt::Result as FmtResult; use std::collections::BTreeMap; use std::ops::Range; use std::sync::Arc; use std::sync::mpsc::{Receiver, sync_channel, SyncSender}; use std::thread; use vob::Vob; use crush::algebra::Matrix; use crush::soc::bdd::Bdd as Shard; use crush::soc::bdd::differential::{Dept...
use std::fmt; use std::fmt::Result as FmtResult; use std::collections::BTreeMap; use std::ops::Range; use std::sync::Arc; use std::sync::mpsc::{Receiver, sync_channel, SyncSender}; use std::thread; use vob::Vob; use crush::algebra::Matrix; use crush::soc::bdd::Bdd as Shard; use crush::soc::bdd::differential::{Dept...
#[derive(Debug, Clone)] pub struct ResultSectionBuilder { mode: BuildMode, best_estimate: SessEstimate, paths_skipped: Option<usize>, alpha_path: Option<Path>, beta_path: Option<Path>, example_path: Option<Path>, hull_probability: Option<f64>, ...
t, mode, ); cache.record_processed_result_section(extract_result.clone().into()); main_pb.inc(1); ProcessedResult::new(vec![constructed_ab_result, extract_result]) }
function_block-function_prefixed
[ { "content": "/// Return the matrix of linear dependencies of the linear system represented\n\n/// by `mat`.\n\n///\n\n/// To compute the matrix of linear dependencies :\n\n///\n\n/// -> augment the given matrix with the identity matrix\n\n///\n\n/// -> gauss the matrix and apply the same operations on the iden...
Rust
src/models/piece.rs
WSeegers/Filler_Mk2
849870a9a6d515c99b7a745a2e021dfbdbb445c3
use super::point::Point; use rand::prelude::*; use serde::ser::{Serialize, SerializeStruct, Serializer}; use std::fmt; const EMPTY: char = '.'; const OCCUPIED: char = '*'; const RANGE_DEFAULT: [usize; 2] = [3, 8]; #[derive(Debug, Clone)] pub struct Piece { width: usize, height: usize, cells: Vec<bool>, ...
use super::point::Point; use rand::prelude::*; use serde::ser::{Serialize, SerializeStruct, Serializer}; use std::fmt; const EMPTY: char = '.'; const OCCUPIED: char = '*'; const RANGE_DEFAULT: [usize; 2] = [3, 8]; #[derive(Debug, Clone)] pub struct Piece { width: usize, height: usize, cells: Vec<bool>, ...
} impl Serialize for Piece { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { let mut s = serializer.serialize_struct("Person", 3)?; s.serialize_field("width", &self.width)?; s.serialize_field("height", &self.height)?; let cells: Vec<u8> = self ...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "Piece {} {}:", self.height, self.width)?; for y in 0..(self.height) { for x in 0..(self.width) { let c = self.cells[(y * self.width + x) as usize]; let c = match c { true =...
function_block-full_function
[ { "content": "#[derive(Debug, Copy, Clone)]\n\nenum Cell {\n\n Player1(bool),\n\n Player2(bool),\n\n Empty,\n\n}\n\n\n\nimpl PartialEq for Cell {\n\n fn eq(&self, other: &Self) -> bool {\n\n use Cell::*;\n\n match self {\n\n Player1(_) => match other {\n\n Pla...
Rust
src/bin/native_emitter.rs
blt/llrv
9867ffddc0864be5fef4698ed8c3cc575a36efe8
extern crate byteorder; extern crate clap; #[macro_use] extern crate lazy_static; extern crate llrv; extern crate protobuf; extern crate rand; use clap::{App, Arg}; use rand::{thread_rng, Rng}; use std::sync::Arc; use std::net::{TcpStream, ToSocketAddrs}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time; ...
extern crate byteorder; extern crate clap; #[macro_use] extern crate lazy_static; extern crate llrv; extern crate protobuf; extern crate rand; use clap::{App, Arg}; use rand::{thread_rng, Rng}; use std::sync::Arc; use std::net::{TcpStream, ToSocketAddrs}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time; ...
k(_) => {} Err(idx) => { let metric_type: &AggregationMethod = rng.choose(&types).unwrap(); let persist: bool = rng.gen::<bool>(); pool.insert(idx, (metric_name.clone(), *metric_type, persist)); } }; } ...
function_block-function_prefixed
[ { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n unsafe {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n }\n\n}\n", "file_path": "src/protocols/native.rs", "rank": 0, "score": 41...
Rust
src/chat-server/server.rs
nelson137/cs4850-final-project
5cead446137e2de3e14578ae15c4a8640c596057
use std::{ collections::hash_map::Entry, sync::{ atomic::{AtomicBool, Ordering}, Arc, }, thread, time::Duration, }; use libc::POLLIN; use libchat::{ err::MyResult, setup_int_handler, sys::{errno_was_intr, ServerSocket, SockAddr, SocketCommon}, UsersDao, COMMAND_MAX, ...
use std::{ collections::hash_map::Entry, sync::{ atomic::{AtomicBool, Ordering}, Arc, }, thread, time::Duration, }; use libc::POLLIN; use libchat::{ err::MyResult, setup_int_handler, sys::{errno_was_intr, ServerSocket, SockAddr, SocketCommon}, UsersDao, COMMAND_MAX, ...
} _ => (), } if let Some(client) = &mut maybe_client { if !self.handle_connection(client) { maybe_client.take(); } } } Ok(()) } fn handle_con...
if errno_was_intr() { break; } else { info!( %error, "failed to poll for potential new client" ); }
if_condition
[ { "content": "/// Print the graphic and welcome message banner for the server app.\n\npub fn print_server_banner() {\n\n _print_banner_array!(_BANNER_GRAPHIC_ARRAY);\n\n _print_banner_array!(_BANNER_GRAPHIC_SERVER_ARRAY);\n\n print!(_BANNER_WELCOME_MESSAGE_SERVER!());\n\n}\n", "file_path": "src/lib...
Rust
src/le/report.rs
TimYorke/btle
3faed14b19d77225eb2e7d42380683a29a7561ce
use crate::le::advertisement::{RawAdvertisement, StaticAdvBuffer}; use crate::ConversionError; use crate::{BTAddress, BT_ADDRESS_LEN, RSSI}; use core::convert::TryFrom; use core::fmt::Formatter; pub struct NumReports(u8); impl NumReports { pub const NUM_REPORTS_MIN: u8 = 0x01; pub const NUM_REPORTS_MAX: u8 = 0...
use crate::le::advertisement::{RawAdvertisement, StaticAdvBuffer}; use crate::ConversionError; use crate::{BTAddress, BT_ADDRESS_LEN, RSSI}; use core::convert::TryFrom; use core::fmt::Formatter; pub struct NumReports(u8); impl NumReports { pub const NUM_REPORTS_MIN: u8 = 0x01; pub const NUM_REPORTS_MAX: u8 = 0...
} impl From<EventType> for u8 { fn from(e: EventType) -> Self { e as u8 } } #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug, Hash)] pub enum AddressType { PublicDevice = 0x00, RandomDevice = 0x01, PublicIdentity = 0x02, RandomIdentity = 0x03, } impl TryFrom<u8> for AddressTy...
fn try_from(v: u8) -> Result<Self, Self::Error> { match v { 0x00 => Ok(EventType::AdvInd), 0x01 => Ok(EventType::AdvDirectInd), 0x02 => Ok(EventType::AdvScanInd), 0x03 => Ok(EventType::AdvNonconnInd), 0x04 => Ok(EventType::ScanRsp), _ => Er...
function_block-full_function
[ { "content": "pub trait Error: core::fmt::Debug {\n\n /// The lower-level source of this error, if any.\n\n fn source(&self) -> Option<&(dyn Error + 'static)> {\n\n None\n\n }\n\n}\n\n\n\nimpl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {\n\n fn from(e: E) -> Self {\n\n Box::new...
Rust
backend/src/db/v2/items.rs
nicholastmosher/swen343-inventory
900ecfb61a9651010b06731ba2549edcb0b45a03
use actix::{Message, Handler}; use diesel::prelude::*; use crate::app::v2::items::{ReceiveItemsRequest, ItemInRequest, ReceiveItemResponse}; use crate::db::DbExecutor; use crate::models::warehouses::Warehouse; use crate::models::pallets::{NewPallet, Pallet}; use crate::models::boxes::NewBox; impl Message for ReceiveIt...
use actix::{Message, Handler}; use diesel::prelude::*; use crate::app::v2::items::{ReceiveItemsRequest, ItemInRequest, ReceiveItemResponse}; use crate::db::DbExecutor; use crate::models::warehouses::Warehouse; use crate::models::pallets::{NewPallet, Pallet}; use crate::models::boxes::NewBox; impl Message for ReceiveIt...
}
let mut ps = Vec::with_capacity(pallet_count as usize); for _ in 0..pallet_count { ps.push(pallet.clone()); } let inserted_pallets = diesel::insert_into(pallets::table) .values(&ps) .get_result::<Pallet>(conn); let mut bs ...
function_block-function_prefix_line
[ { "content": "export const RECEIVE_PALLETS = \"RECEIVE_PALLETS\";\n", "file_path": "frontend/src/types/ItemActionTypes.ts", "rank": 0, "score": 99098.30117769194 }, { "content": "export const RECEIVE_BOXES = \"RECEIVE_BOXES\";\n", "file_path": "frontend/src/types/ItemActionTypes.ts", ...
Rust
xtask/src/codegen/mod.rs
Nilstrieb/haesli
b86dc98555e73b0301ad7eef4d9da4c7a3e2dc76
#![allow(clippy::needless_late_init)] mod parser; mod random; mod write; use std::{ fs, fs::File, io::Write, iter::Peekable, path::{Path, PathBuf}, process::Command, str::FromStr, }; use anyhow::{bail, Context}; use heck::ToUpperCamelCase; use strong_xml::XmlRead; #[derive(Debug, XmlRea...
#![allow(clippy::needless_late_init)] mod parser; mod random; mod write; use std::{ fs, fs::File, io::Write, iter::Peekable, path::{Path, PathBuf}, process::Command, str::FromStr, }; use anyhow::{bail, Context}; use heck::ToUpperCamelCase; use strong_xml::XmlRead; #[derive(Debug, XmlRea...
_type, field_docs) = self.get_invariants_with_type( self.field_type(field), field.asserts.as_ref(), ); if !field_docs.is_empty() { writeln!(self.output, " /// {field_docs}").ok(); ...
self.output, "#[derive(Debug, Clone, PartialEq)] pub struct {class_name}{method_name}" ) .ok(); if !method.fields.is_empty() { writeln!(self.output, " {{").ok(); for field in &method.fields { ...
random
[ { "content": "fn method_function_name(class_name: &str) -> impl Fn(&Method) -> String + '_ {\n\n move |method| {\n\n let method_name = method.name.to_snake_case();\n\n format!(\"{class_name}_{method_name}\")\n\n }\n\n}\n\n\n", "file_path": "xtask/src/codegen/parser.rs", "rank": 0, ...
Rust
rs/rosetta-api/ledger_canister/src/icpts.rs
audieleon/ic
35dd8f93dec82662ed4df35664a9c0be6dbf203a
use candid::CandidType; use core::ops::{Add, AddAssign, Sub, SubAssign}; use serde::{Deserialize, Serialize}; use std::fmt; #[derive( Serialize, Deserialize, CandidType, Clone, Copy, Hash, Debug, PartialEq, Eq, PartialOrd, Ord, Default, )] pub struct ICPTs { ...
use candid::CandidType; use core::ops::{Add, AddAssign, Sub, SubAssign}; use serde::{Deserialize, Serialize}; use std::fmt; #[derive( Serialize, Deserialize, CandidType, Clone, Copy, Hash, Debug, PartialEq, Eq, PartialOrd, Ord, Default, )] pub struct ICPTs { ...
let e8s = icp_part .checked_add(e8s) .ok_or_else(|| CONSTRUCTION_FAILED.to_string())?; Ok(Self { e8s }) } pub const ZERO: Self = ICPTs { e8s: 0 }; pub fn from_icpts(icp: u64) -> Result<Self, String> { Self::new(icp, 0) } ...
if e8s >= ICP_SUBDIVIDABLE_BY { return Err(format!( "You've added too many E8s, make sure there are less than {}", ICP_SUBDIVIDABLE_BY )); }
if_condition
[ { "content": "/// Return the module that generated the given `Record`\n\npub fn get_module(module_path: &'static str) -> String {\n\n let path: Vec<&str> = module_path.split(\"::\").collect();\n\n (*path.last().unwrap_or(&\"\")).to_string()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\...
Rust
src/file/ark.rs
bpa/ark-file-parser
e08da69fdb683ef4296b84f52596feca2ab8c624
use crate::io::{ArrayReader, Reader}; use crate::object::{Names, Object}; use crate::properties::{Properties, Value}; use crate::{Entry, Location}; use std::fs::File; use std::io::{Error, ErrorKind}; use std::io::{Result, SeekFrom, Write}; use std::rc::Rc; use super::CryopodParser; pub struct ArkParser { _class_o...
use crate::io::{ArrayReader, Reader}; use crate::object::{Names, Object}; use crate::properties::{Properties, Value}; use crate::{Entry, Location}; use std::fs::File; use std::io::{Error, ErrorKind}; use std::io::{Result, SeekFrom, Write}; use std::rc::Rc; use super::CryopodParser; pub struct ArkParser { _class_o...
fn read_header(file: &mut dyn Reader) -> Result<(i16, u64, u64)> { let version = file.read_i16()?; if version < 5 || version > 9 { return Err(Error::new( ErrorKind::InvalidData, format!("Unsupported file version {}", version), )); } if version > 6 { let...
None }; let object_properties_offset = file.read_i32()? as u64; let mut properties = Properties::new(); let next_object = file.seek(SeekFrom::Current(4))?; file.seek(SeekFrom::Start( properties_offset + object_properties_offset, ))?; properties.read(...
function_block-function_prefix_line
[ { "content": "fn name_id(lookup: &HashMap<Rc<String>, usize>, name: &str) -> usize {\n\n *lookup.get(&Rc::new(String::from(name))).unwrap_or(&0)\n\n}\n\n\n\nimpl Names {\n\n pub fn len(&self) -> usize {\n\n self.names.len()\n\n }\n\n}\n\n\n\nimpl Index<usize> for Names {\n\n type Output = str...
Rust
src/compact1/operation.rs
hilbert-space/postscript
d696793a457d00f4427cd6b74c8cb7ba87a400f3
use std::collections::HashMap; use crate::compact1::number; use crate::{Result, Tape, Value}; pub type Operand = f32; pub type Operation = (Operator, Vec<Operand>); #[derive(Clone, Debug)] pub struct Operations(pub HashMap<Operator, Vec<Operand>>); impl Value for Operation { fn read<T: Tape>(tape: &mut T) ->...
use std::collections::HashMap; use crate::compact1::number; use crate::{Result, Tape, Value}; pub type Operand = f32; pub type Operation = (Operator, Vec<Operand>); #[derive(Clone, Debug)] pub struct Operations(pub HashMap<Operator, Vec<Operand>>); impl Value for Operation { fn read<T: Tape>(tape: &mut T) ->...
on [0], 0x0c20 => CIDFontRevision [0], 0x0c21 => CIDFontType [0], 0x0c22 => CIDCount [8720], 0x0c23 => UIDBase [], 0x0c24 => FDArray [], 0x0c25 => FDSelect [], 0x0c26 => FontName [], } }
; macro_rules! operator { (pub $name:ident { $($code:pat => $variant:ident $default:tt,)+ }) => ( operator! { @define pub $name { $($variant,)+ } } operator! { @implement pub $name { $($code => $variant $default,)+ } } ); (@define pub $name:ident { $($variant:ident,)* }) => ( ...
random
[ { "content": "pub fn read<T: Tape>(tape: &mut T) -> Result<f32> {\n\n let first = tape.take::<u8>()?;\n\n Ok(match first {\n\n 0x20..=0xf6 => (first as i32 - 139) as f32,\n\n 0xf7..=0xfa => ((first as i32 - 247) * 256 + tape.take::<u8>()? as i32 + 108) as f32,\n\n 0xfb..=0xfe => (-(fi...
Rust
ulist/src/base.rs
tushushu/uvec
ab57251136d375a5e47a61af9a3262394795c0db
use crate::boolean::BooleanList; use crate::index::IndexList; use pyo3::exceptions::PyIndexError; use pyo3::exceptions::PyRuntimeError; use pyo3::exceptions::PyValueError; use pyo3::PyResult; use std::cell::Ref; use std::cell::RefMut; use std::collections::HashSet; pub fn _fill_na<T: Clone>(vec: &mut Vec<T>, na_indexe...
use crate::boolean::BooleanList; use crate::index::IndexList; use pyo3::exceptions::PyIndexError; use pyo3::exceptions::PyRuntimeError; use pyo3::exceptions::PyValueError; use pyo3::PyResult; use std::cell::Ref; use std::cell::RefMut; use std::collections::HashSet; pub fn _fill_na<T: Clone>(vec: &mut Vec<T>, na_indexe...
} else { self.replace_by_na(_old) } } else { if let Some(_new) = new { self.replace_na(_new) } } } fn replace_by_na(&self, old: T) { let n = self.size(); let mut vec = self.values_mut(); for...
ut hset: HashSet<usize> = HashSet::with_capacity(m); let cond = condition.values(); let mut i = 0; for ((j, x), cond) in self.values().iter().enumerate().zip(cond.iter()) { if *cond { vec.push(x.clone()); ...
random
[ { "content": "fn _sort(vec: &mut Vec<f64>, ascending: bool) {\n\n if ascending {\n\n vec.sort_by(|a, b| a.partial_cmp(b).unwrap());\n\n } else {\n\n vec.sort_by(|a, b| b.partial_cmp(a).unwrap());\n\n }\n\n}\n", "file_path": "ulist/src/floatings/float64.rs", "rank": 1, "score":...
Rust
nmk/launcher/src/commands/clean_unused_kernels.rs
nuimk/nmk
347ab549ac90fe8bf6f39f8dab33b465f0c4818e
use std::cmp::Ordering; use std::os::unix::process::CommandExt; use std::process::Command; use dialoguer::theme::ColorfulTheme; use dialoguer::{Confirm, Select}; use duct::cmd; use log::info; use nix::unistd::getuid; use once_cell::sync::Lazy; use regex::{Captures, Regex}; use nmk::consts::bin::SUDO; static INSTALLE...
use std::cmp::Ordering; use std::os::unix::process::CommandExt; use std::process::Command; use dialoguer::theme::ColorfulTheme; use dialoguer::{Confirm, Select}; use duct::cmd; use log::info; use nix::unistd::getuid; use once_cell::sync::Lazy; use regex::{Captures, Regex}; use nmk::consts::bin::SUDO; static INSTALLE...
let a = KernelVersion::from_version_number(a)?; let b = KernelVersion::from_version_number(b)?; Some(a.cmp(&b)) } let a = a.as_ref(); let b = b.as_ref(); compare_version(a, b).unwrap_or_else(|| a.cmp(b)) } #[cfg(test)] mod tests { use super::*; #[test] fn kernel_version() ...
:Result<Vec<String>> { let purge_versions: Vec<&str> = versions .iter() .copied() .filter(|&v| v != keep_version) .collect(); let mut packages = vec![]; for line in cmd!("dpkg", "--get-selections").read()?.lines() { if let Some(c) = INSTALLED_PACKAGES.captures(line) {...
random
[]