text stringlengths 8 4.13M |
|---|
use std::collections::HashSet;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
fn part1(v: &[i32]) {
let s: i32 = v.iter().sum();
println!("{}", s);
}
fn part2(v: &[i32]) {
let mut freq = 0;
let mut seen = HashSet::new();
seen.insert(freq);
v.iter().cycle().all(|x| {
... |
use crate::snapshot::manifest;
use crate::snapshot::Snapshot;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
pub fn clean_up(app: &nannou::prelude::App, snapshot: &Snapshot) {
if !snapshot.did_capture_frames {
return;
}
app.main_window().await_capture_frame_jobs().unwrap();
f... |
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qpaintdevice.h
// dst-file: /src/gui/qpaintdevice.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>... |
//! Thread-associated operations.
#[cfg(not(target_os = "redox"))]
mod clock;
#[cfg(linux_raw)]
mod futex;
#[cfg(linux_kernel)]
mod id;
#[cfg(linux_kernel)]
mod libcap;
#[cfg(linux_kernel)]
mod prctl;
#[cfg(linux_kernel)]
mod setns;
#[cfg(not(target_os = "redox"))]
pub use clock::*;
#[cfg(linux_raw)]
pub use futex::{... |
use super::sma::declare_ma_var;
use super::VarResult;
use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType};
use crate::helper::{
move_element, pine_ref_to_bool, pine_ref_to_f64, pine_ref_to_f64_series, pine_ref_to_i64,
require_param, series_index,
};
use crate::types::{
d... |
use proconio::input;
fn f(a: &[u32], x: u32, y: u32) -> usize {
for &a in a {
assert!(y <= a && a <= x);
}
let mut last_x = 0;
let mut last_y = 0;
let mut ans = 0;
for i in 0..a.len() {
if a[i] == x {
last_x = i + 1;
}
if a[i] == y {
last_... |
use std::io;
fn main() {
loop {
println!("insert the number between 1...10");
let mut x = String::new();
io::stdin().read_line(&mut x).expect("fail to read");
let x: u32 = match x.trim().parse() {
Ok(result) => result,
Err(_) => {
println!("fai... |
mod call;
mod literal;
mod ops;
|
use super::Float;
use std::ops::{Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign};
use std::cmp::Ordering;
#[derive(Debug, Copy, Clone)]
pub enum Angle<F: Float = f32> {
Radians(F),
Degrees(F),
}
impl<F: Float> Angle<F> {
pub fn radians(value: F) -> Self {
Angle::Radians(value)
... |
use std::cmp;
use std::path::{ Path, PathBuf };
use parser::{ Evaluator, Node };
use fan::Fan;
use util;
// Hwmon PWM fan
//
// Controls a PWM output of a hwmon device. Internally,
// these are represented as a text file, with possible
// values ranging from 0 to 255.
pub struct HwmonPwmFan {
path_to_pwm : Path... |
use std::env;
use std::fs;
use std::time::Instant;
fn main() {
// --snip--
let args: Vec<String> = env::args().collect();
let filename = &args[1];
println!("Opening file {}", filename);
let start = Instant::now();
let contents = fs::read_to_string(filename)
.expect("Something went wr... |
//! # Parsing Partial Input
//!
//! Typically, the input being parsed is all in-memory, or is complete. Some data sources are too
//! large to fit into memory, only allowing parsing an incomplete or [`Partial`] subset of the
//! data, requiring incrementally parsing.
//!
//! By wrapping a stream, like `&[u8]`, with [`... |
#[doc = "Reader of register FSIZE"]
pub type R = crate::R<u32, super::FSIZE>;
#[doc = "Flash Size\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u16)]
pub enum SIZE_A {
#[doc = "127: 256 KB of Flash"]
_256KB = 127,
}
impl From<SIZE_A> for u16 {
#[inline(always)]
fn from(variant: ... |
//! Pulse Width Modulation
/// Pulse Width Modulation
///
/// # Examples
///
/// Use this interface to control the power output of some actuator
///
/// ```
/// extern crate embedded_hal as hal;
///
/// use hal::prelude::*;
///
/// fn main() {
/// let mut pwm: Pwm1 = {
/// // ..
/// # Pwm1
/// };... |
use std::process::Command;
fn main() {
assert!(Command::new("make")
.args(&["-C", "tests/parser"])
.status()
.unwrap()
.success());
}
|
use projecteuler::{helper, square_roots};
fn main() {
helper::check_bench(|| {
solve(100, 1_000_000);
});
helper::check_bench(|| {
solve(100_000_000, 1_000_000);
});
helper::check_bench(|| {
solve(100_000_000, 100_000_000);
});
helper::check_bench(|| {
solve(... |
use super::JniInstance;
use crate::errors::{self, Result};
use crate::store::StoreData;
use crate::{interop, utils, wextern};
use jni::objects::{JClass, JObject, JString};
use jni::sys::jlong;
use jni::JNIEnv;
use wasmtime::{Func, Instance, Memory, Module, Store};
pub(super) struct JniInstanceImpl;
impl<'a> JniInstan... |
mod matrix;
use matrix::*;
mod threadTest;
use threadTest::*;
fn main() {
let a = vec![3,2,1,1,0,2];
let b = vec![1,2,4,5,0,1,3,2,4,0,0,1];
a=7;
let l: usize = 2; //Zeilen von A
let m: usize = 3; //Spalten von A, Zeilen von B
let n: usize = 4; //Spalten von B
//let c = matrix_mul(&a,... |
use self::{
close_encoder::serialize_close_request_body, create_encoder::serialize_create_request_body,
echo_encoder::serialize_serialize_echo_request_body,
negotiate_encoder::serialize_negotiate_request_body,
query_info_encoder::serialize_query_info_request_body,
session_setup_encoder::serialize_se... |
// LCOV_EXCL_START
#![allow(missing_docs)]
use std::error::Error as StdError;
use std::fmt::Error as FmtError;
use std::fmt::{Display, Formatter};
use std::io::Error as IOError;
use std::result::Result as StdResult;
use diesel::result::Error as DieselError;
use diesel_migrations::RunMigrationsError;
use http::header:... |
extern crate serde;
mod test_utils;
use bigdecimal::BigDecimal;
use flexi_logger::LoggerHandle;
use hdbconnect::{Connection, HdbResult, HdbValue};
use log::{debug, info};
use num::FromPrimitive;
use serde::Deserialize;
//cargo test --test test_025_decimals -- --nocapture
#[test]
fn test_025_decimals() -> HdbResult<(... |
use std::collections::HashSet;
use std::str::CharIndices;
use super::super::automaton::{Automaton, Label};
use super::{Mapping, Marker};
/// Enumerate all the matches of a variable automata over a text.
///
/// ** For this naive implementation, there is no garantee that produced matches
/// are distincts. **
pub stru... |
use std::io;
fn main() {
println!("Enter Value : ");
let mut input = String::new();
io::stdin() .read_line(&mut input).expect("Failed to read line");
let input:u8 = match input.trim().parse(){
Ok(num) => num,
Err(_) => (0)
};
println!("You Print : {}", input);
}
|
#[doc = "Reader of register MIIADDR"]
pub type R = crate::R<u32, super::MIIADDR>;
#[doc = "Writer for register MIIADDR"]
pub type W = crate::W<u32, super::MIIADDR>;
#[doc = "Register MIIADDR `reset()`'s with value 0"]
impl crate::ResetValue for super::MIIADDR {
type Type = u32;
#[inline(always)]
fn reset_va... |
// pub mod item;
pub mod locale;
pub mod recipe;
|
use challenges::random_bytes;
use cipher::{self, Mode};
use encoding::base64::*;
use std::collections::HashMap;
use std::convert::TryInto;
fn main() {
println!("🔓 Challenge 14 (should take ~ 16X than chal12)");
let key = Key::new();
break_ecb_harder(&key);
}
fn break_ecb_harder(key: &Key) {
// deciph... |
use std::{borrow::Cow, io::Read, sync::Arc};
#[cfg(feature = "unblock")]
use futures_util::io::AsyncRead;
use crate::{
registry, registry::MetaTypeId, Context, InputType, InputValueError, InputValueResult, Value,
};
/// A file upload value.
pub struct UploadValue {
/// The name of the file.
pub filename:... |
use serde::ser::{Serialize, SerializeStruct, Serializer};
use serde_json;
pub struct City {
pub name: String,
pub population: usize,
}
pub struct Faction {
pub name: String,
pub cities: Vec<City>,
}
impl Faction {
pub fn new(name: String) -> Faction {
Faction {
name,
... |
use rbatis::crud::CRUDTable;
use rbatis_macro_driver::CRUDTable;
use serde::Deserialize;
use serde::Serialize;
use wallets_macro::{db_append_shared, DbBeforeSave, DbBeforeUpdate};
use crate::kits;
use crate::ma::dao::{self, Shared};
use crate::ma::TxShared;
//eee
#[db_append_shared]
#[derive(PartialEq, Serialize, De... |
#![allow(dead_code)]
extern crate tqapi;
extern crate chrono;
use tqapi::api::*;
use std::thread::sleep;
use std::time::Duration;
struct Callback {
}
impl DataApiCallback for Callback {
fn on_quote(&mut self, quote : MarketQuote) {
println!("on_quote {}", quote);
}
fn on_bar (&mut self, cycle :... |
#[crate_id = "redis#0.1"];
#[crate_type = "lib"];
#[license = "BSD"];
#[comment = "Bindings and wrapper functions for redis."];
#[deny(non_camel_case_types)];
#[feature(macro_rules)];
#[feature(globs)];
extern crate extra;
extern crate time;
extern crate collections;
extern crate serialize;
pub use parser::parse_red... |
//! Timers
use nb;
/// A count down timer
///
/// # Contract
///
/// - `self.start(count); block!(self.try_wait());` MUST block for AT LEAST the time specified by
/// `count`.
///
/// *Note* that the implementer doesn't necessarily have to be a *downcounting* timer; it could also
/// be an *upcounting* timer as long ... |
extern crate cgl;
use std::fs::File;
use cgl::{Color, Image, Renderer, read_bmp};
use cgl::{Shader, Vert, Mat4, Vec3, Vec4};
mod demo;
fn main() {
let model = demo::african_head();
let mut renderer = Renderer::with_dimensions(512, 512);
let matrix = demo::african_head_matrix();
let texture = {
... |
use matrix_sdk::identifiers::RoomId;
use regex::Regex;
use serde::de::{self, MapAccess, Visitor};
use serde::{Deserialize, Deserializer};
use std::fmt;
use std::marker::PhantomData;
use std::path::PathBuf;
use std::str::FromStr;
use url::Url;
use void::Void;
/// Holds the configuration for the bot.
#[derive(Clone, Des... |
use super::{DropdownID, ExampleBox, Model, Msg};
use seed::{prelude::*, *};
use seed_bootstrap::button::{self, Button};
use seed_bootstrap::dropdown::{self, Dropdown};
use seed_bootstrap::navbar::{Nav, NavBar, NavLink};
pub fn view(model: &Model) -> Node<Msg> {
div![
C!["pt-5"],
h1!["Navbars"],
... |
use parser::functions::*;
use parser::lists::*;
use parser::primitives::*;
use pest::iterators::Pair;
use pest::Parser;
use std::collections::HashMap;
use super::stdlib;
mod primitives;
pub mod functions;
mod lists;
#[derive(Debug, PartialEq, Clone)]
pub struct Function {
pub args: Vec<Constant>,
pub base_fn: Opt... |
#[macro_use]
pub mod logger;
pub use logger::init as logger_init;
|
use super::{TraitDefinition, *};
use as_derive_utils::parse_utils::ParseBufferExt;
use syn::{parse::ParseBuffer, Attribute, ItemTrait, TraitItem, TraitItemMethod};
#[allow(unused_imports)]
use core_extensions::SelfOps;
use crate::{arenas::Arenas, attribute_parsing::contains_doc_hidden, utils::LinearResult};
/// Co... |
// Copyright 2020-2021, The Tremor Team
//
// 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 agr... |
use crate::{
format::convert_byte_array_to_int,
ntlmssp::{self, challenge::Challenge, AvId, AvPair, MessageType},
};
/// Decodes the NTLMSSP security response body.
pub fn decode_security_response(security_response: Vec<u8>) -> ntlmssp::Header {
let ntlmssp_response = remove_gss_wrapper(security_response);... |
/*!
Implementation of the core in version:
* **v1.0** (see [v1.0 CloudEvents specification](https://github.com/cloudevents/spec/blob/v1.0/spec.md) and [v1.0 JSON Event Format](https://github.com/cloudevents/spec/blob/v1.0/json-format.md))
* **v0.2** (see [v0.2 CloudEvents specification](https://github.com/cloudevents/... |
#[macro_use]
extern crate lazy_static;
extern crate itertools;
extern crate regex;
use itertools::Itertools;
use regex::Regex;
use std::collections::HashMap;
use std::ops::Range;
#[derive(Ord, PartialEq, PartialOrd, Eq, Debug)]
enum Action {
StartShift(i32),
WakeUp,
FallAsleep,
}
#[derive(Ord, PartialOrd... |
mod json;
mod parser;
mod parser_dispatch;
#[allow(dead_code)]
mod parser_partial;
use winnow::error::ErrorKind;
use winnow::prelude::*;
fn main() -> Result<(), lexopt::Error> {
let args = Args::parse()?;
let data = args.input.as_deref().unwrap_or(if args.invalid {
" { \"a\"\t: 42,
\"b\": [ \"x\",... |
use crate::object::{GoogleStorageObjectSource, Key};
use crate::Result;
use std::path::PathBuf;
pub enum RemoteSourceConfig {
GoogleStorage {
bucket: String,
config_path: PathBuf,
},
}
pub enum RemoteSource {
GoogleStorage(GoogleStorageObjectSource),
}
impl RemoteSource {
pub fn initi... |
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(all(feature = "alloc", not(feature = "std")))]
extern crate alloc;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::vec::Vec;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::string::*;
#[cfg(not(feature = "std"))]
use core::prelude::v1:... |
// Copyright (c) Calibra Research
// SPDX-License-Identifier: Apache-2.0
use super::*;
use simulated_context::*;
use smr_context::*;
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
#[test]
fn test_node() {
let mut context = SimulatedContext::new(
Author(0),
/* num... |
#![feature(exhaustive_patterns)]
#![feature(proc_macro, conservative_impl_trait, generators)]
extern crate tokio_core;
extern crate tokio_io;
extern crate futures_await as futures;
extern crate future_utils;
#[macro_use]
extern crate unwrap;
#[macro_use]
extern crate net_literals;
mod priv_prelude;
use priv_prelude:... |
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qabstractanimation.h
// dst-file: /src/core/qabstractanimation.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main ... |
fn calculate_fuel(mass: i64) -> i64 {
mass / 3 - 2
}
fn main() {
use std::io;
let mut res = 0;
loop {
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(_) => {
match input.trim().parse() {
Ok(mass) => {
let mut fuel = calculate_fuel(mass);
while fuel > 0 {... |
mod response_wrapper;
mod error_warning;
pub use response_wrapper::ResponseWrapper;
pub use error_warning::ErrorWarning; |
#[doc = "Reader of register MACECR"]
pub type R = crate::R<u32, super::MACECR>;
#[doc = "Writer for register MACECR"]
pub type W = crate::W<u32, super::MACECR>;
#[doc = "Register MACECR `reset()`'s with value 0"]
impl crate::ResetValue for super::MACECR {
type Type = u32;
#[inline(always)]
fn reset_value() ... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Control register"]
pub cr: CR,
#[doc = "0x04 - Interrupt mask register"]
pub imr: IMR,
#[doc = "0x08 - Status register"]
pub sr: SR,
#[doc = "0x0c - Interrupt Flag Clear register"]
pub ifcr: IFCR,
_reser... |
use hitable::*;
use camera::*;
use output::*;
#[derive(Debug)]
pub struct Scene {
pub world: Box<Hitable>,
pub light_shapes: Box<Hitable>,
pub camera: Camera,
pub num_samples: u32, // TODO: put inside RenderQuality
pub output_settings: OutputSettings,
}
|
//= {
//= "output": {
//= "1": [
//= "",
//= true
//= ],
//= "2": [
//= "",
//= true
//= ]
//= },
//= "children": [],
//= "exit": "Success"
//= }
#![deny(warnings, deprecated)]
extern crate constellation;
use constellation::*;
use std::{process, thread, time};
fn main()... |
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq)]
pub enum StockMoveEvent<Item, Location, Quantity> {
Started {
item: Item,
qty: Quantity,
from: Location,
to: Location,
},
Completed,
Cancelled,
Assigned {
item: Item,
from: Location,
a... |
use super::Constant;
pub fn le(args: Vec<Constant>) -> Constant {
let pair: (&Constant, &Constant) = (args.get(0).unwrap(), args.get(1).unwrap());
match pair {
(&Constant::Float(v1), &Constant::Float(v2)) => Constant::Boolean(v1 <= v2),
(&Constant::Float(v1), &Constant::Integer(v2)) => Constant::Boolean(v... |
/*
Copyright (c) 2015, 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, di... |
use shipyard_scenegraph::traits::required as math_traits;
use shipyard_scenegraph::traits::required::SliceExt;
const MATRIX_IDENTITY: [f32; 16] = [
1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
];
const VECTOR_ZERO: [f32; 3] = [0.0, 0.0, 0.0];
const VECTOR_ONE: [f32; 3] = [1.0, 1... |
#[cfg(test)]
extern crate env_logger;
#[macro_use]
extern crate statechart;
use std::rc::Rc;
use statechart::ast::*;
use statechart::interpreter::*;
#[test]
fn pingpong() {
let _ = env_logger::init();
let sc = states!{ root {
initial_label: Some("init".to_string()),
substates: [
... |
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... |
use git2::{ErrorCode, Repository};
use bindgen;
use cc;
use std::env;
use std::path::PathBuf;
use std::process::Command;
fn main() {
let v8_dir = match env::var("CUSTOM_V8") {
Ok(custom_v8_dir) => {
let custom_v8_dir = PathBuf::from(custom_v8_dir);
assert!(custom_v8_dir.exists());... |
//! DMA
//!
//! Size: 4K
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};
use static_assertions::const_assert_eq;
pub mod channel;
pub const PADDR: usize = 0x01C0_2000;
pub const NUM_CHANNELS: usize = 8;
register! {
IrqEnable,
u32,
RW,
Fields [
Ch0HalfPkgIrqEnable WIDTH(U1) ... |
// revisions: base nll
// ignore-compare-mode-nll
//[nll] compile-flags: -Z borrowck=mir
trait Foo {}
impl<T: Fn(&())> Foo for T {}
fn baz<T: Foo>(_: T) {}
fn main() {
baz(|_| ());
//[base]~^ ERROR mismatched types
//[nll]~^^ ERROR implementation of `FnOnce` is not general enough
//[nll]~| ERROR mis... |
use crate::smb2::requests::query_info::QueryInfo;
/// Serializes a query info request from the corresponding struct.
pub fn serialize_query_info_request_body(request: &QueryInfo) -> Vec<u8> {
let mut serialized_request: Vec<u8> = Vec::new();
serialized_request.append(&mut request.structure_size.clone());
... |
//! Keep stats, and dispaly them to the user. Usually used in a broker, or main node, of some sort.
use alloc::{string::String, vec::Vec};
use core::{time, time::Duration};
use crate::utils::current_time;
const CLIENT_STATS_TIME_WINDOW_SECS: u64 = 5; // 5 seconds
/// A simple struct to keep track of client stats
#[... |
//! The module trait and some useful implementations such as
//! combinators
use crate::{Error, Result, TimerInfo};
use log::warn;
/// A decision each module has to take before a timer is executed:
/// Should it be?
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Progress {
/// Continue the program, ... |
use crate::bomb_party::*;
use serenity::{
builder::CreateEmbed,
framework::standard::{macros::command, Args, CommandResult},
model::prelude::*,
prelude::*,
};
use std::collections::hash_map::Entry;
#[command]
#[description = "Create a new game"]
pub async fn new(ctx: &Context, msg: &Message) -> Comma... |
use crate::qrcode::handler::qrcodes;
use actix_web::web;
pub fn route_qrcode(cfg: &mut web::ServiceConfig) {
cfg.service(web::resource("/qrcodes").route(web::post().to(qrcodes)));
}
|
#[doc = "Reader of register OR"]
pub type R = crate::R<u32, super::OR>;
#[doc = "Writer for register OR"]
pub type W = crate::W<u32, super::OR>;
#[doc = "Register OR `reset()`'s with value 0"]
impl crate::ResetValue for super::OR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
... |
//! A [tasque] extension specialized for [fibers].
//!
//! This provides an extension trait and the default task queues.
//!
//! [tasque]: https://crates.io/crates/tasque
//! [fibers]: https://crates.io/crates/fibers
//!
//! # Examples
//!
//! ```
//! use fibers::{Executor, InPlaceExecutor};
//! use fibers_tasque::{Asy... |
//! Contains the `replace_self_path` function,and the `ReplaceWith` enum.
use as_derive_utils::spanned_err;
use syn::visit_mut::VisitMut;
use syn::{Ident, TraitItemType, TypePath};
use std::mem;
use crate::utils::{LinearResult, SynResultExt};
/// What to do with the a path component when it's found.
#[derive(Debug... |
#![no_std]
#![no_main]
//! Serial port example.
//!
//! The output is viewable with simavr
//!
//! ```
//! cargo build -Z build-std=core --target avr-atmega328p.json --examples --release
//! simavr -m atmega328p target/avr-atmega328p/release/examples/uart.elf
//! ```
use ruduino::legacy::serial;
#[no_mangle]
fn main... |
//! Terminal window context.
use std::error::Error;
use std::fs::File;
use std::io::Write;
use std::mem;
#[cfg(not(windows))]
use std::os::unix::io::{AsRawFd, RawFd};
use std::rc::Rc;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use crossfont::Size;
use glutin::config::GetGlConfig;
use glutin::context::NotCur... |
cfg_if! {
if #[cfg(target_os = "linux")] {
mod linux;
pub type Manager = linux::SysFsManager;
pub type Iterator = linux::SysFsIterator;
pub type Device = linux::SysFsDevice;
} else if #[cfg(any(target_os = "macos", target_os = "ios"))] {
mod darwin;
pub type Man... |
/// Bitmap Graphics example.
///
/// This example uses the CPU to render a simple bitmap image to the screen.
use ctru::prelude::*;
use ctru::services::gfx::{Flush, Screen, Swap};
/// Ferris image taken from <https://rustacean.net> and scaled down to 320x240px.
/// To regenerate the data, you will need to install `ima... |
pub use crate::{
Direction,
Edge,
EdgeIndex,
Edges,
Graph,
Node,
NodeIndex,
};
pub(crate) use crate::Next;
|
use crate::square::Square;
use yew::prelude::*;
#[derive(Clone, PartialEq, Properties)]
pub struct Props {
pub squares: [&'static str; 9],
pub onclick: Callback<usize>,
}
pub enum Msg {
HandleClick(usize),
}
pub struct Board {
link: ComponentLink<Self>,
props: Props,
}
impl Component for Board {... |
use probe_rs::config::MemoryRegion;
use serde::{Deserialize, Serialize};
/// This describes a single chip model.
/// It can come in different configurations (memory, peripherals).
/// E.g. `nRF52832` is a `Chip` where `nRF52832_xxAA` and `nRF52832_xxBB` are its `Variant`s.
#[derive(Debug, Clone, Serialize, Deserialize... |
pub fn demo() {
println!("{}", find_abc());
}
fn find_abc() -> u64 {
let n = 1000;
for c in 3..n-2 {
for b in 2..c {
if let Some(a) = a_given(b) {
if is_pythagorean(a, b, c) && a + b + c == n {
return a * b * c;
}
}
... |
//! Definition of the `Option` (optional step) combinator
use {Future, Poll, Async};
impl<F, T, E> Future for Option<F> where F: Future<Item=T, Error=E> {
type Item = Option<T>;
type Error = E;
fn poll(&mut self) -> Poll<Option<T>, E> {
match *self {
None => Ok(Async::Ready(None)),
... |
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 ... |
// Various experiments with references and mutability.
//
// Lessons to be learned:
// - A value won't be mutated as long as its bound immutably.
// - When a value is moved, its old binding ^^^^^ goes away.
fn main() {
// Not allowed: mutating an immutable variable:
//
// let v = Vec::<i8>::new();
... |
fn main() {
let mut n = 0;
let mut step = 2;
let mut times_in_step = 0;
let mut sum = 0;
let end = 1001_i32.pow(2);
println!("{}", end);
for i in 1..(end + 1) {
if n == 0 {
n = step;
times_in_step += 1;
if (times_in_step) == 4 {
tim... |
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub(crate) mod geometry;
use super::{
acceleration_structure_update,
clustering,
light_binning,
prepass,
rt_shadows,
sharpen,
ssao,
taa,
};
pub(crate) mod desktop_renderer;
pub(crate) mod occlusion;
|
use std::u64;
use std::{fs, str::FromStr};
static FILENAME: &str = "inputs/inputday13";
#[derive(Debug, Copy, Clone)]
enum Bus {
OOS,
ID(u64),
}
#[derive(Debug)]
enum BusParseError {}
impl FromStr for Bus {
type Err = BusParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s ... |
pub struct Solution;
impl Solution {
pub fn longest_increasing_path(matrix: Vec<Vec<i32>>) -> i32 {
if matrix.len() == 0 || matrix[0].len() == 0 {
return 0;
}
Solver::new(matrix).solve()
}
}
struct Solver {
matrix: Vec<Vec<i32>>,
memo: Vec<Vec<i32>>,
}
const TODO: ... |
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
mod test_helpers;
mod tests;
use crate::test_helpers::TextFieldWrapper;
use crate::tests::*;
use failure::{Error, ResultExt};
use fidl_fuchsia_ui_text as ... |
//! A simple game loop implementation.
#![warn(
clippy::all,
clippy::cargo,
clippy::clone_on_ref_ptr,
clippy::indexing_slicing,
clippy::mem_forget,
clippy::missing_docs_in_private_items,
clippy::multiple_inherent_impl,
clippy::nursery,
clippy::option_unwrap_used,
clippy::pedanti... |
//! A macro to help debug unwraps.
use std;
/// Panics after if the value cannot be unwraped.
#[macro_export]
macro_rules! unwrap {
($e:expr) => {
$crate::unwrap::Unwrap::unwrap($e,
format_args!("in module {}, file {}, line {}, column {}",
module_path!(), file!(), line!... |
//! Types for HVIF shapes
use types::path::*;
#[derive(Debug)]
/// An HVIF shape, consisting of a single style, one or more paths, and optional additional transformation data
pub struct HVIFShape {
/// The index of the style used in the shape
pub style_index: u8,
/// The indices of the paths that use this shape... |
use assert_cmd::prelude::*;
use std::process::Command;
fn sub() -> Command {
Command::cargo_bin("sub").unwrap()
}
struct ReplacementTest {
pattern: &'static str,
replacement: &'static str,
input: String,
args: Vec<String>,
}
impl ReplacementTest {
pub fn new(pattern: &'static str, replacement... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Win32_Storage_Xps_Printing")]
pub mod Printing;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))]
pub type ABORTPROC = unsafe extern "system" fn(param... |
pub mod groups;
|
// Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... |
#[macro_export]
macro_rules! compose {
( $last:expr ) => { $last };
( $head:expr, $($tail:expr), +) => {
compose_two($head, compose!($($tail),+))
};
}
pub fn compose_two<A, B, C, G, F>(f: F, g: G) -> impl Fn(A) -> C
where
F: Fn(A) -> B,
G: Fn(B) -> C,
{
move |x| g(f(x))
}
#... |
//! Profiles are configurations that affect how an operation is applied.
//!
//! For instance, a `PublishProfile` might determine how unknown entities in the
//! target are handled when performing a `publish` operation.
use std::default::Default;
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::Path;
... |
mod parser;
use std::fmt;
use std::str::FromStr;
use std::ops::Deref;
pub use parser::ParseError;
#[derive(Debug, Clone)]
pub enum Term {
App(Box<Term>, Box<Term>),
Abs(u32, Box<Term>),
Var(u32),
}
impl PartialEq for Term {
fn eq(&self, other: &Term) -> bool {
match self {
Term::... |
// Proverb Programming
// "Time is money"
// Count duration time, convert it to money, and display.
use std::time;
use std::io;
fn main() {
println!("Please input your hourly wage:");
let mut hourly_wage_string = String::new();
io::stdin().read_line(&mut hourly_wage_string)
.expect("Failed to read... |
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use fidl_fuchsia_sys2::{ComponentDecl, ExposeDecl, OfferDecl, OfferTarget, Relation, RelativeId};
use lazy_static::lazy_static;
use regex::Regex;
use std::... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.