lang
stringclasses
10 values
seed
stringlengths
5
2.12k
rust
#[doc = "Bits 0:6 - K1-Divider Value"] #[inline(always)] pub fn k1div(&self) -> K1DIV_R { K1DIV_R::new((self.bits & 0x7f) as u8) } #[doc = "Bits 8:14 - N-Divider Value"] #[inline(always)] pub fn ndiv(&self) -> NDIV_R { NDIV_R::new(((self.bits >> 8) & 0x7f) as u8)
rust
while buf.clone().uncons().is_ok() { match parse_http_request(buf) { Ok(((_, _), b)) => { buf = b; } Err(err) => panic!("{:?}", err), } } }); }
rust
draw_calls.push(DrawCall::load_model("house_one".to_string())); draw_calls.push(DrawCall::load_model("house_two".to_string())); draw_calls.push(DrawCall::load_model("house_double".to_string())); draw_calls.push(DrawCall::load_model("unit_floor".to_string())); draw_calls.push(DrawCall::load_model("hug_cube".to_string())); draw_calls.push(DrawCall::load_model("debug_cube".to_string()));
rust
pub queues: Vec<Arc<Queue>>, } pub trait InstanceFactory { fn create_instance(&self) -> Arc<Instance>; } pub trait DeviceFactory{
rust
conf.define("MBEDTLS_CONFIG_FILE", Some("<config-asn1.h>")); conf.include("../../ext/mbedtls/include"); conf.include("../../ext/tinycrypt/lib/include"); conf.file("../../boot/zephyr/keys.c");
rust
b.iter(|| { let res = read_i64(&mut &buf[..]).unwrap(); test::black_box(res); }); } #[bench] fn from_i64_read_int(b: &mut Bencher) { let buf = [0xd3, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]; b.iter(|| { let res: i64 = read_int(&mut &buf[..]).unwrap(); test::black_box(res);
rust
attribute vec2 position; attribute vec4 color; varying vec4 v_color;
rust
/// Parser. /// /// # Iteration /// /// `Box<Parser>` implements `IntoIterator<Item = Result<Event, ParserError>>`, /// and thus can be used in `for` loops. The iterator is fused, and produces /// `None` forever after the end of stream or after a first encountered error. pub struct Parser<'a> { inner: sys::yaml_parser_t, reader: Box<dyn io::Read + 'a>, reader_error: Option<io::Error>, }
rust
// use enum_primitive::cast::FromPrimitive; pub static mut FLAGS: u32 = 0; enum_from_primitive!{
rust
} _ => { _data.insert(k, vec![v]); } } if ! &val.is_null() {
rust
#[doc = "Pin Control Register n"] pub struct PCR12 { register: ::vcell::VolatileCell<u32>, } #[doc = "Pin Control Register n"] pub mod pcr12; #[doc = "Pin Control Register n"] pub struct PCR13 { register: ::vcell::VolatileCell<u32>, } #[doc = "Pin Control Register n"]
rust
@center@ = @lib.check_number(diff,30)@ @lib.check_string(sign[1],15)@ @lib.check_number(term[1],30)@ = @lib.check_number(value[1],30)@ @vspace@ @center@ x - (y - @term[2]@) = @lib.check_number(diff,30)@ @lib.check_string(sign[1],15)@ @lib.check_number(term[2],30)@ = @lib.check_number(value[2],30)@ @vspace@ @center@ (x - @term[3]@) - y = @lib.check_number(diff,30)@ @lib.check_string(sign[2],15)@ @lib.check_number(term[3],30)@ = @lib.check_number(value[3],30)@ @vspace@ @center@ x - (y + @term[4]@) = @lib.check_number(diff,30)@ @lib.check_string(sign[2],15)@ @lib.check_number(term[4],30)@ = @lib.check_number(value[4],30)@ @vspace@
rust
pub struct Rtcdate { pub second: usize, pub minute: usize, pub hour: usize, pub day: usize, pub month: usize, pub year: usize, }
rust
fn main() { let source: Source = Source::from_string("42"); let module: &str = "examples/lexer"; let lexer: Lexer = Lexer::new(source, module); let parser: Result<Parser, Exception> = Parser::new(lexer); let rast: Result<AbstractSyntaxTree, Exception> = parser.unwrap().run(); assert_eq!(false, rast.is_err()); let _ast: AbstractSyntaxTree = rast.unwrap();
rust
('\u{3400}', '\u{4dbf}'), ('\u{4e00}', '\u{9ffc}'), ('\u{f900}', '\u{fa6d}'), ('\u{fa70}', '\u{fad9}'), ('\u{20000}', '\u{2a6dd}'), ('\u{2a700}', '\u{2b734}'), ('\u{2b740}', '\u{2b81d}'), ('\u{2b820}', '\u{2cea1}'), ('\u{2ceb0}', '\u{2ebe0}'), ('\u{2f800}', '\u{2fa1d}'), ('\u{30000}', '\u{3134a}') ];
rust
"GetSnapshotRequest", fields, file_descriptor_proto() ) }) }
rust
fn from_compatible_slice(slice: &[u8]) -> VerificationResult<Self>; fn new_builder() -> Self::Builder; fn as_builder(self) -> Self::Builder; }
rust
} for (key, order) in current { let entry = counts.entry(key).or_insert_with(|| FunctionStatistics{current_own: 0, current_total: 0, overall_own: 0, overall_total: 0}); entry.current_total += 1; entry.overall_total += 1; if order == 0 { entry.current_own += 1;
rust
impl MessageUpdateEvent { /// Fetch the message. pub async fn message(&self, cx: &Context) -> Result<Message> { Message::fetch(cx, &self.channel_id, &self.message_id).await } /// Fetch the channel. pub async fn channel(&self, cx: &Context) -> Result<Channel> { Channel::fetch(cx, &self.channel_id).await } } /// A partial message.
rust
server_pk: SPub, ) -> SodokenResult<()> where R: Into<BufWriteSized<SESSIONKEYBYTES>> + 'static + Send, T: Into<BufWriteSized<SESSIONKEYBYTES>> + 'static + Send, CPub: Into<BufReadSized<PUBLICKEYBYTES>> + 'static + Send, CSec: Into<BufReadSized<SECRETKEYBYTES>> + 'static + Send,
rust
} } } else { if in_cargo { println!("cargo:warning=No link script found, please check that you have selected a known device variant from the following:"); for v in device.variants.iter() { println!("cargo:warning= {}", v.name); } }
rust
InboundWireError::InputProcessor(x) => { error!("Process error on wire: {}", x); true } }, }
rust
let cost = start.elapsed().as_millis(); // ms let s = format!("{} {}ms {} {}", remote, cost, method, uri); match res {
rust
pub(crate) fn new(map : HashM<String, (usize, ListDefValue)>) -> ListDefMap{ ListDefMap{ map } } pub fn get(&self, key : &str) -> Option<&ListDefValue>{ self.map.get(key).map(|(_,v)| v) } pub fn get_with_id(&self, key : &str) -> Option<(usize, &ListDefValue)>{ self.map.get(key).map(|(k,v)| (*k,v)) } pub fn contains_key(&self, key : &str) -> bool{ self.map.contains_key(key) } pub(crate) fn iter(&self) -> ListDefMapIter{ ListDefMapIter{ hash_iter : self.map.iter() } } pub fn len(&self) -> usize{ self.map.len() } } pub struct ListDefMapIter<'a>{ hash_iter : Iter<'a, String, (usize, ListDefValue)>,
rust
} else { Status::InternalServerError } } #[catch(401)] pub fn un_authorized(_req: &Request) -> String { "User must be authenticated".to_string() } #[catch(403)] pub fn forbidden(_req: &Request) -> String {
rust
// CHECK-LABEL: qreg_low4: // CHECK: @APP // CHECK: vorr q0, q0, q0 // CHECK: @NO_APP check!(qreg_low4 "" qreg_low4 f32x4 "vmov");
rust
eta: Float, } impl SpecularBTDF { pub fn new(color: Color, eta: Float) -> Self { Self { color, eta }
rust
let avoid_cross_crate_conflicts = // If this is an instance of a generic function, we also hash in // the ID of the instantiating crate. This avoids symbol conflicts // in case the same instances is emitted in two crates of the same // project. is_generic(substs) || // If we're dealing with an instance of a function that's inlined from // another crate but we're marking it as globally shared to our // compliation (aka we're not making an internal copy in each of our // codegen units) then this symbol may become an exported (but hidden // visibility) symbol. This means that multiple crates may do the same // and we want to be sure to avoid any symbol conflicts here. matches!(MonoItem::Fn(instance).instantiation_mode(tcx), InstantiationMode::GloballyShared { may_conflict: true });
rust
struct Win { model: Model, window: Window, } impl Update for Win { type Model = Model; type ModelParam = (); type Msg = Msg; fn model(_: &Relm<Self>, _: ()) -> Model { Model {}
rust
let string = string_table.get_string(index)?; Ok(string) } fn get_line(&self) -> Result<u32, Error> { let mut cursor = Cursor::new(self.raw_data); cursor.set_position(8); Ok(cursor.read_u32::<LittleEndian>()?)
rust
.map(|(collection, values)| (collection, Value::Array(values))) .collect::<Map<String, Value>>() .into() }; Ok(as_value) } } impl TryFrom<&Namespace> for Sampler { type Error = anyhow::Error; fn try_from(namespace: &Namespace) -> Result<Self> { Ok(Self {
rust
pub mod error; pub mod rest_api; pub mod webserver; extern crate miette; #[macro_use] extern crate rocket; #[macro_use] extern crate rocket_okapi; #[macro_use] extern crate serde_derive;
rust
hashes.map(|hashes| InventoryStatus::Advertised((hashes, peer))) } /// Returns a new missing multiple inventory change, if `hashes` contains at least one change. #[allow(dead_code)] pub fn new_missing_multi<'a>( hashes: impl IntoIterator<Item = &'a InventoryHash>, peer: SocketAddr, ) -> Option<Self> { let hashes: Vec<InventoryHash> = hashes.into_iter().copied().collect(); let hashes = hashes.try_into().ok(); hashes.map(|hashes| InventoryStatus::Missing((hashes, peer))) } }
rust
fn ethdir_path() -> std::path::PathBuf { let options: crate::Opt = argh::from_env(); path::Path::new(&options.dev_path).join("class/ethernet") } async fn device_found(filename: &std::path::PathBuf) -> Result<Option<OIRInfo>, anyhow::Error> { let file_path = ethdir_path().join(filename); let device = fs::File::open(&file_path)
rust
pub mod dict_like_api; pub mod list_like_api;
rust
pub icachecnf: ICACHECNF, _reserved3: [u8; 4usize], #[doc = "0x548 - I-Code cache hit counter."] pub ihit: IHIT, #[doc = "0x54c - I-Code cache miss counter."] pub imiss: IMISS, } #[doc = "Ready flag"] pub struct READY { register: ::vcell::VolatileCell<u32>, } #[doc = "Ready flag"]
rust
ErrorRepr::FromNix(ref e) => e.description(), ErrorRepr::WithDescription(_, description) => description, } } fn cause(&self) -> Option<&dyn Error> { match self.repr { ErrorRepr::FromNix(ref e) => Some(e as &dyn Error), _ => None, } } }
rust
let center = to_screen * *point; let radius = aux_stroke.width * 3.0; let circle = CircleShape { center, radius, fill: aux_stroke.color, stroke: *aux_stroke,
rust
for node in thermal_load_driver_nodes { let temperature_handler_node_deps = node["dependencies"].as_object().unwrap() ["temperature_handler_node_names"] .as_array() .unwrap()
rust
result.errors = Some(vec![QueryError::from(e)]); result } } impl From<Vec<QueryExecutionError>> for QueryResult { fn from(e: Vec<QueryExecutionError>) -> Self { QueryResult { data: None, errors: Some(e.into_iter().map(QueryError::from).collect()), extensions: None, }
rust
org.apache.commons.io.filefilter.AgeFileFilter
rust
use futuresdr::blocks::NullSourceBuilder; use futuresdr::blocks::VectorSink; use futuresdr::blocks::VectorSinkBuilder; use futuresdr::runtime::scheduler::TpbScheduler; use futuresdr::runtime::Flowgraph; use futuresdr::runtime::Runtime; #[test] fn flowgraph_tpb() -> Result<()> { let mut fg = Flowgraph::new(); let copy = CopyBuilder::new(4).build();
rust
pub mod log; pub mod bib; pub mod config; pub mod document; pub mod errors; pub(crate) mod pandoc; pub mod utils; pub use document::DocumentBuilder; pub use document::{Chapter, Document}; pub use errors::Error; pub const CONFIG_FILE: &str = "mdoc.toml";
rust
#[derive(Serialize, Deserialize)] pub struct Settings { pub rendering: String, pub fov: usize, pub window_size: u32, pub vertex_size: f32, } impl Settings { pub fn store(&self){ let filename = "settings.json"; let serialized = serde_json::to_string(self).unwrap();
rust
} pub struct Fps { pub fps: f64, last_frame_start: f64, current_period: Period } impl Period { fn new() -> Period {
rust
hot_cache.pretransfer_time /= n; hot_cache.redirect_time /= n; hot_cache.starttransfer_time /= n; hot_cache.download_time /= n; hot_cache.total_time /= n; let hot_cache_result = format!(
rust
// Rust CHIP-8 emulator, created by <NAME> // Distributed under the MIT license // // Input //************************************************************************ pub trait KeyInput { fn is_key_pressed(&self, key: u8) -> bool; fn get_key(&mut self) -> u8;
rust
]; for (n,e) in test_cases { assert_eq!(e, Solution::find_nth_digit(n), "n: {}", n); } }
rust
/// Metadata containing the badge's size. pub meta: BTreeMap<String, Vec<i32>>, /// The badge's identifier. pub id: i32, /// The identifier of the badge's channel. pub relid: i32, /// The badge's image URL string. pub url: String, /// Where the badge image is stored. pub store: String, /// The path at which the badge image can be found on Beam. pub remotePath: String, /// The date string, in UTC, at which the badge was created. pub createdAt: String, /// The date string, in UTC, at which the badge was last updated.
rust
use super::bishop::generate_bishop_moves; use super::rook::generate_rook_moves; pub fn generate_queen_moves(board: &Board, sq: usize, piece: &Piece) -> Vec<usize> {
rust
} } } ProgramResult::Halt } fn get_phase_settings(n: usize, values: std::ops::Range<usize>) -> Vec<Vec<i32>> {
rust
}) } } impl S3PackageRepository { async fn make_presigned_url(&self, method: &str) -> Result<String, RemoteError> { let extra_env = match &self.auth_strategy { AuthStrategy::Script(auth_script) => extract_env_from_script(auth_script)?, AuthStrategy::DefaultAwsAuth => BTreeMap::default(), AuthStrategy::None => { return Ok(self.url.clone()); } };
rust
} #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct WantsToAttack { pub attacker: Entity, pub target: Entity, }
rust
.set_ctx(self.ctx.clone()), ); } for param in constructor_params { let param_e = self.interpret_node(param); if param_e.should_return() { return param_e; } constructor_params_e.push(param_e.val.unwrap()); } class.unwrap().value.init_class(constructor_params_e, self) }
rust
mod encoded_point; mod encoded_scalar; pub mod error; mod generator; mod point; mod scalar; mod serde_support; pub use self::{ encoded_point::EncodedPoint, encoded_scalar::EncodedScalar, generator::Generator, point::Point, scalar::Scalar, };
rust
fn draw_input_buffer<B: Backend>(f: &mut Frame<B>, rect: Rect, app: &app::App, _: &Handlebars) { let input_buf = Paragraph::new(Spans::from(vec![ Span::styled( app.config() .general()
rust
use kaitai_struct::KaitaiStruct; use rust::RepeatUntilSized; #[test] fn test_repeat_until_sized() { if let Ok(r) = RepeatUntilSized::from_file("src/repeat_until_process.bin") { assert_eq!(r.records.len(), 3); assert_eq!(r.records[0].marker, 232); assert_eq!(r.records[0].body, 2863311546); assert_eq!(r.records[1].marker, 250); assert_eq!(r.records[1].body, 2863315102); assert_eq!(r.records[2].marker, 170); assert_eq!(r.records[2].body, 1431655765); } }
rust
Complete the solution so that it reverses the string value passed into it. solution("world") // returns "dlrow" */ fn solution(phrase: &str) -> String { phrase.chars().rev().collect() } #[test] fn sample_test() {
rust
// The problem was specified to casting to `*`, as creating unsafe // pointers was not being fully checked. Issue #20791. fn main() { let x: &i32; let y = x as *const i32; //~ ERROR [E0381] }
rust
} pub fn set_name(&mut self, name: String) { self.name = Some(name); } pub fn with_name(mut self, name: String) -> RunningRace { self.name = Some(name);
rust
result } } impl fmt::Display for Mate { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}: {}", self.name, self.duck_points)
rust
file_count += 1; match_count = match_count + results.len(); if config.count { // Display only filenames if printed_count < config.max { writeln!(writer, "{}: \t{}", pathname, results.len())?; printed_count += 1; }
rust
// println!("5 % 4 = {}", 5 % 4); let mut neg_4 = -4i32; println!("abs(-4) = {}", neg_4.abs()); println!("4 ^ 6 = {}", 4i32.pow(6)); println!("sqrt 9 = {}", 9f32.sqrt());
rust
} } //impl Bluetooth for BluetoothOptions { // fn get_scan_type(&self) -> &BluetoothScanType { // &self.scan_type
rust
async fn call<P, R>(&self, method: &str, params: P) -> Result<R, CallError> where P: Serialize, R: DeserializeOwned, {
rust
impl<F, B> Future for H2Stream<F, B> where F: Future<Item=Response<B>>, F::Error: Into<Box<dyn StdError + Send + Sync>>, B: Payload, { type Item = ();
rust
cmp::max((self.x - other.x).abs(), (self.y - other.y).abs()) as usize } } impl PartialOrd for Coord { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { if self == other {
rust
if updated_user.id != context.user().id { Err(UserServiceErrorKind::NotAuthorizedToModifyProfile)? } let user = User::update(conn, WithAudit::new(context.user().username.as_str(), updated_user))?; Ok(user) }) } pub fn get_profile(context: &dyn Context) -> Result<User, UserServiceError> { Ok(context.user().clone()) }
rust
pub mod file_store; pub mod fts; pub mod http; pub mod indexer; pub mod manager; pub mod scorer;
rust
Ok(STATIC_KEY.as_bytes().to_vec()) } } #[tokio::test] async fn test_allocation_lifetime_deletion_zero_lifetime() -> Result<(), Error> {
rust
use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use toml; use url::Url; use crate::db::DbType; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] pub struct Settings { pub bind: String, pub port: usize, #[serde(with = "url_serde")]
rust
} } // special cases for certain lifecycle commands match args.subcommand() { ("init", Some(init_args)) => { if init_args.is_present("here") { current_dir = Some(env::current_dir().unwrap_or_else(|e| { panic!("Error creating config file: {}", e); })); } create_path = true; } _ => {}
rust
impl_from_err!(PersistentDescriptorSetBuildError, VkDescSetErr); impl_from_err!(FramebufferCreationError, VkFramebufferErr); impl_from_err!(BeginRenderPassError, VkBeginRenderPassErr); impl_from_err!(DrawError, VkDrawErr); impl_from_err!( AutoCommandBufferBuilderContextError, VkCommandBufferContextErr ); impl_from_err!(BuildError, VkCommandBufferBuildErr); impl_from_err!(CommandBufferExecError, VkExecError); */ mod pass { use vulkano::format::{ClearValue, Format}; use vulkano::framebuffer::{
rust
//! Consensus service interfaces. pub mod address; pub mod beacon; pub mod registry; pub mod roothash; pub mod scheduler; pub mod staking; pub mod state; pub mod tendermint;
rust
let addr = self.sock_addr(); thread::spawn(move || { self.server.listen_on_socket(self.listener_sock); }); Self::wait_for_health_check(addr); } fn wait_for_health_check(addr: SocketAddr) { let client = reqwest::blocking::Client::builder() .timeout(Some(Duration::from_secs(1))) .build() .expect("failed to build a reqwest client");
rust
// Configure files app services pub fn service_config(cfg: &mut web::ServiceConfig) { cfg //.service(last_changed::last_changed)// POST /last_changed .service(ping::ping)// GET /ping .service(ping::secure_ping);// GET /secure-ping }
rust
Either::Right(x) } fn m(x: Either<i32, bool>) -> i32 { match x { Either::Left(x) => x, Either::Right(x) => if x { 1 } else { 0 }, } } fn i(n: i32) -> i32 {
rust
pub struct Stats { pub actor: Entity, } into_action!(Stats); pub fn stats_system( mut action_reader: EventReader<Action>, mut stats_query: Query<(&Health, &Attributes)>, mut messages_query: Query<&mut Messages>, ) { for action in action_reader.iter() {
rust
// Now we build a noise map for use in spawning entities later self.noise_areas = generate_voronoi_spawn_regions(&self.map, &mut rng); // Spawn the entities for area in self.noise_areas.iter() { spawner::spawn_region(&self.map, &mut rng, area.1, self.depth, &mut self.spawn_list); } } fn render_tile_gallery(&mut self, constraints: &[MapChunk], chunk_size: i32) { self.map = Map::new(0); let mut counter = 0; let mut x = 1;
rust
/// Doku's pretty-printers mod printers; pub use self::{objects::*, printers::*}; pub use doku_derive::*;
rust
let task_center = Point2::new( task.position.x as f32 + 0.5, task.position.y as f32 + 0.5 ); // Check if we're at the destination if (task_center.x - unit_position.x).abs() < 1.1 && (task_center.y - unit_position.y).abs() < 1.1 { // We're there, apply work task.apply_work(delta); // If the work's done, we can add an object to the tile
rust
mod deployment_resource_types; mod deployment_resources; pub use deployment_resource_types::*; pub use deployment_resources::*;
rust
//! __FUZZ_GENERATE_COMMENT__ #[macro_use] extern crate afl; extern crate fuzz_targets; use fuzz_targets::__FUZZ_CLI_TARGET__ as fuzz_target; fn main() { fuzz!(|data: &[u8]| { let _ = fuzz_target(data); });
rust
["users", _, "guilds", _] => UsersIdGuildsId, ["users", _, "guilds", _, "member"] => UsersIdGuildsIdMember, ["voice", "regions"] => VoiceRegions, ["webhooks", id] => WebhooksId(parse_id(id)?), ["webhooks", id, token] => WebhooksIdToken(parse_id(id)?, token.to_string()), ["webhooks", id, token, "messages", _] => { WebhooksIdTokenMessagesId(parse_id(id)?, token.to_string()) } _ => {
rust
// writing { let mut root: RootMutSpace = RootMutSpace::new(raw_space); let mut frame = (&mut root as &mut dyn MutSpace) .create_atom_frame(unsafe { URID::<()>::new_unchecked(1) }) .unwrap(); {
rust
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // U+0010 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // U+0011 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // U+0012 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // U+0013 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // U+0014 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // U+0015 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // U+0016 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // U+0017 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // U+0018 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // U+0019 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // U+001A [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // U+001B [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // U+001C [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], // U+001D
rust
}; game_state_to_return }
rust
/// Where to draw the sprite. pub rect: Rect, /// Rotation (in radians) of the sprite. pub rotation: f32, } /// Draw data for a single instance in a non-textured batched sprite draw. pub struct SpriteBatchColorDraw { /// Color to fill with. pub color: Color, /// Where to draw the sprite. pub rect: Rect, /// Rotation (in radians) of the sprite. pub rotation: f32,
rust
child.generate_tree_recursive(level + 1, lines); } } fn generate_details(&self, lines: &mut Vec<String>) { self.generate_details_recursive("", lines); } fn generate_details_recursive(&self, prefix: &str, lines: &mut Vec<String>) { let moniker = format!("{}{}:{}", prefix, self.name, self.id);
rust
principal } else { println!( "Failed to parse json from stock API on ticker {}!", ticker.ticker
rust
IfSourceModifiedSinceCondition::Unmodified(date) => { builder.header(SOURCE_IF_UNMODIFIED_SINCE, &date.to_rfc2822() as &str) } } } }
rust
return Err(Error::new(ErrorKind::UnexpectedEof, "Read 0 bytes")); } return Ok(total_bytes_read); }, Ok(bytes_read) => { total_bytes_read += bytes_read; }, Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { return Ok(total_bytes_read) } Err(e) => return Err(e) } } }
rust
let w: ArrayView3<f32> = inputs[1].to_array_view::<f32>()?.into_dimensionality()?; // [num_directions, 4*hidden_size, input_size] let r: ArrayView3<f32> = inputs[2].to_array_view::<f32>()?.into_dimensionality()?; // [num_directions, 4*hidden_size, hidden_size] let bias = if let Some(bias) = inputs.get(3) { Some(bias.to_array_view::<f32>()?.into_dimensionality::<Ix2>()?) // [num_directions, 8*hidden_size] } else { None }; let seq_length = x.shape()[0]; let batch_size = x.shape()[1];
rust
use futures_stats::{Timed, TimedStreamTrait}; fn main() { let mut runtime = tokio_old::runtime::Runtime::new().unwrap(); let fut = future::lazy(|| { println!("future polled"); Ok(()) }) .timed(|stats, _: Result<&(), &()>| { println!("{:#?}", stats); Ok(()) });
rust
impl From<[u8; 6]> for MacAddress { /// Creates an `Ipv4Addr` from a six element byte array. /// /// # Examples /// /// ``` /// use w5500::MacAddress; ///
rust
let numbers = generate_seq(limit); output_seq(&numbers) } fn generate_seq(limit: u8) -> Vec<u8> { (1..=limit).collect() } fn output_seq(numbers: &[u8]) {
rust
use rust_team_data::v1; use std::path::Path; pub(crate) struct Generator<'a> { dest: &'a Path,
rust
helpers::{ check_header_timestamp_greater_than_median, check_pow_data, check_target_difficulty, check_timestamp_ftl, }, HeaderValidation, ValidationError, }, };
rust
/// /// # Returns /// Returns a `bool`, true if the password is valid, false if not valid. /// /// # Errors
rust
process .list_fds() .expect("Expected list_fds to find file descriptors, but it returned None"), vec![0, 1, 2, 4, 5] ); let _ = test_subprocess.kill(); } #[test]