text stringlengths 8 4.13M |
|---|
use svm_sdk_mock::template;
#[template]
mod Template {
#[storage]
struct Storage {
dword: u32,
dwords: [u32; 3],
}
}
fn main() {
// `dword`
let dword = Storage::get_dword();
assert_eq!(dword, 0);
Storage::set_dword(0xAABBCCDD);
let dword = Storage::get_dword();
ass... |
use raytracing::{
rand_f64, rand_in_range, write_sampled_color, Camera, Color, Dieletric, Hittable, HittableList,
Lambertian, Material, Metal, Point3, Ray, Sphere, Vec3,
};
use std::rc::Rc;
fn random_scene() -> HittableList {
let mut world = HittableList::default();
let ground_material = Rc::new(Lamber... |
use crate::{
blockcfg::{Block, HeaderHash},
network::p2p::topology::NodeId,
network::BlockConfig,
settings::start::network::Peer,
};
use futures::prelude::*;
use http::{HttpTryFrom, Uri};
use hyper::client::connect::{Destination, HttpConnector};
use network_core::client::{BlockService, Client as _};
use... |
//!An example of generating julia fractals.
extern crate num_complex;
extern crate image;
use std::fs::File;
use std::path::Path;
use num_complex::Complex;
fn main() {
let max_iterations = 256u16;
let imgx = 800;
let imgy = 800;
let scalex = 4.0 / imgx as f32;
let scaley = 4.0 / imgy as f32;
... |
extern crate fst;
extern crate fst_levenshtein;
extern crate itertools;
extern crate rayon;
pub mod errors;
mod utils;
use std::path::PathBuf;
use std::collections::HashMap;
use fst::{IntoStreamer, Set};
use fst_levenshtein::Levenshtein;
use errors::DictionaryError;
use utils::*;
use rayon::prelude::*;
pub struct D... |
pub mod package;
pub mod actions;
pub mod variants;
pub mod message;
use std::fmt;
use log::*;
pub use message::*;
pub trait Agent: fmt::Debug
+ Action
+ DeadOrAlive
{
fn get_id(&self) -> usize;
fn get_kind(&self) -> &Kind;
fn kind_count(&self) -> isize;
}
pub trait Action {
fn act(&mut ... |
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
pub const my_enum1_A: my_enum1 = 0;
pub type my_enum1 = u32;
pub const my_enum2_B: my_enum2 = -1;
pub type my_enum2 = i32;
pub const my_enum3_C: my_enum3 = 0;
pub type my_enum3 = i16;
pub const my_enum4_D: my_enum4 = 2... |
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Softwa... |
// syscall.rs
// System calls
// Stephen Marz
// 3 Jan 2020
use crate::{block::block_op,
cpu::{dump_registers, TrapFrame},
minixfs,
page::{virt_to_phys, Table},
process::{Process, PROCESS_LIST, PROCESS_LIST_MUTEX, delete_process, get_by_pid, set_sleeping, set_waiting}};
... |
use std::collections::HashMap;
use aoc::get_input;
use aoc::intcode::Program;
struct Point {
x: i64,
y: i64,
}
impl Point {
pub fn turn_left(&mut self) {
let new_x = self.y;
let new_y = -self.x;
self.x = new_x;
self.y = new_y;
}
pub fn turn_right(&mut self) {
... |
#[macro_use]
extern crate lazy_static;
extern crate unzip_n;
mod animation;
mod display;
mod display_list;
mod dom;
mod eval;
mod t;
mod utils;
// use itertools::Itertools;
// use serde::{Deserialize, Serialize};
// use std::iter;
use display::{Text, TextBuilder};
use display_list::{Spacing, TextConfig};
use swc_comm... |
use futures::{Future, Poll, Stream};
use tokio::net::UnixStream;
use tokio::prelude::*;
use crate::clip::handle_action;
use crate::codec::Codec;
use crate::errors::*;
use log::*;
pub struct Peer {
codec: Codec,
}
impl Peer {
pub fn new(socket: UnixStream) -> Self {
Peer {
codec: Codec::ne... |
extern crate structopt;
extern crate fastwalkdir;
use std::path::PathBuf;
use structopt::StructOpt;
use fastwalkdir::Dir;
#[derive(StructOpt)]
struct Args {
#[structopt(parse(from_os_str))]
/// Path to recursively scan
dir: PathBuf,
}
fn main() -> Result<(), fastwalkdir::Error> {
let args = Args::from_args()... |
//! Virtual machine.
use std::rc::Rc;
use std::{error, result};
use std::fmt;
use std::collections::HashMap;
use std::error::Error as StdError;
use item::{Block, BlockItem, Stack};
pub type Result<T> = result::Result<T, Error>;
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum Error {
TypeError,
OutOfBounds,
... |
//Anything related to GET requests for heroku logs and it's properties goes here.
use super::LogDrain;
use crate::framework::endpoint::{HerokuEndpoint, Method};
/// Log Drain List
///
/// List existing log drains.
///
/// [See Heroku documentation for more information about this endpoint](https://devcenter.heroku.com... |
impl Solution {
pub fn length_of_last_word(s: String) -> i32 {
let mut x = s.len();
if x == 0 {
return 0;
}
let mut l = 0;
let b = s.as_bytes();
for index in (0..x).rev() {
let tmp = b[index];
if tmp == b' ' && l == 0 {
... |
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[repr(u8)]
pub enum GameState {
Play = 0,
Pause = 1,
Result = 2,
}
|
fn main() {
let _ = sqlx::query!("select '127.0.0.1'::inet");
let _ = sqlx::query!("select '2001:4f8:3:ba::/64'::cidr");
let _ = sqlx::query!("select $1::inet", ());
let _ = sqlx::query!("select $1::cidr", ());
}
|
pub use self::{
core::{api, green, Direction, Text},
ptr::{AstPtr, NodePtr},
token_text::TokenText,
};
use crate::{format_to, SyntaxKind, T};
pub use smol_str::SmolStr;
use std::{fmt, marker::PhantomData};
use triomphe::Arc;
pub mod macros;
pub mod text;
pub use text::{Indel, TextRange, TextSize};
pub mod... |
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct NodeStatusNodeNvram {
/// This node's NVRAM battery status information.
#[serde(rename = "batteries")]
pub batteries: Option<Vec <crate::models::NodeStatusNodeNvramBattery>>,
/// This node's NVRAM batter... |
use tokio::prelude::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Hello, world!");
return Ok(());
}
|
//! Inspired by https://github.com/LedgerHQ/ledgerjs/blob/v6.9.0/packages/devices/src/hid-framing.ts#L27
//! TODO consider moving the `HidTokenizer` implementation into `HidProtocol`.
use crate::transport::apdu::APDUCommand;
use byteorder::{BigEndian, ByteOrder};
/// https://github.com/LedgerHQ/ledgerjs/blob/v6.9.0/p... |
use rocket::serde::json::Json;
use crate::{
app,
core::auth::{authorize_character, AuthenticatedAccount},
util::{madness::Madness, types::Character},
};
#[get("/api/pilot/info?<character_id>")]
async fn pilot_info(
account: AuthenticatedAccount,
character_id: i64,
app: &rocket::State<app::Appl... |
//! Program instructions
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use solana_program::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
};
use crate::{get_associated_token_address, id};
/// Instructions supported by the AssociatedTokenAccount program
#[derive(Clone, Debug, Partial... |
use fastset::*;
use wasm_result::*;
macro_rules! info {
($res_var:ident, $( $arg:tt )+) => {
$res_var.push_line(format!($($arg)+));
};
}
#[no_mangle]
pub fn rho(n: u32, m: u32, h: u32) -> RawCString {
let mut result = WasmResult::new();
let mut smallest_set = empty_set();
let mut curr_sma... |
#[macro_export]
macro_rules! csi {
($( $l:expr ),*) => { concat!("\x1B[", $( $l ),*) };
}
|
use crate::GameEvent;
use crate::packages::package_buffer::Package;
/// Serialize a game event to be transfer in network compact format
pub fn serialize(e: GameEvent) -> Package {
unimplemented!()
}
/// Parse a network compact format into a game event
pub fn parse(package: Package) -> GameEvent {
unimplemente... |
/*
* @lc app=leetcode.cn id=1 lang=rust
*
* [1] 两数之和
*/
// @lc code=start
use std::collections::HashMap;
impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut mem = HashMap::with_capacity(nums.len());
for (i,n) in nums.iter().enumerate() {
mem.insert(n, i)... |
pub mod convert_names;
pub mod gaf2paf;
pub mod gfa2vcf;
pub mod saboten;
pub mod snps;
pub mod stats;
pub mod subgraph;
use std::io::{BufReader, Read};
use bstr::io::*;
use gfa::{
gfa::{SegmentId, GFA},
optfields::OptFields,
parser::GFAParser,
};
#[allow(unused_imports)]
use log::{debug, info, warn};
p... |
use num_traits::{Num, Pow};
/// A macro to generate terms quickly. Can either be used to
/// generate a Vec of terms, or a single term
///
/// # Examples
/// ```
/// use cakcukus::{terms, Polynomial, Term};
///
/// let terms = terms!(2., 2., -3., 1.); // Can generate a Vec of Terms,
///
/// assert_eq!(terms, Polynomia... |
use model;
use rusoto_core::Region;
use rusoto_dynamodb::{
AttributeDefinition, CreateTableInput, DynamoDb, DynamoDbClient, KeySchemaElement,
ProvisionedThroughput, PutItemError, PutItemInput, PutItemOutput, ScanError, ScanInput,
};
use std::env;
use std::str::FromStr;
#[derive(Debug)]
pub struct Move<T> {
... |
#[macro_use]
extern crate error_chain;
extern crate toml;
extern crate rustc_serialize;
extern crate byteorder;
#[cfg(windows)]
extern crate winapi;
#[cfg(windows)]
extern crate kernel32;
extern crate hlua;
#[macro_use]
mod error;
mod tas;
mod config;
mod lua;
#[cfg(windows)]
mod inject;
use std::fs::File;
use std::r... |
//! Represenattion of lipa na mpesa online query request api
//!
//! test url: POST https://sandbox.safaricom.co.ke/mpesa/stkpushquery/v1/query
/// A struct containing requesr parametrs for the lipa na mpesa online query request api
#[derive(Debug)]
pub struct LipaNaMpesaOnlineQueryRequest {
/// Business Short C... |
extern crate threadpool;
extern crate tasks_framework;
use tasks_framework::runnable::Runnable;
use tasks_framework::actor_runner::ActorRunner;
use threadpool::ThreadPool;
use std::cell::Cell;
use std::sync::Arc;
struct Actor {
value: Arc<Cell<usize>>
}
unsafe impl Send for Actor {}
unsafe impl Sync for Actor {... |
include!("../unix/tokio.rs.in");
|
#![warn(warnings)] // Prevent `-Dwarnings` from causing breakage.
#![allow(clippy::all)]
#![cfg_attr(rustfmt, rustfmt::skip)]
#![allow(nonstandard_style, unused_imports)]
use ::core::{mem, ops::Not as _};
use ::proc_macro::TokenStream;
use ::proc_macro2::{Span, TokenTree as TT, TokenStream as TokenStream2};
use ::quot... |
use yew::agent::{Agent, AgentLink, Context, HandlerId};
use yew::prelude::*;
#[derive(Clone)]
pub enum NotificationAgentInput {
Notify(Notification),
}
#[derive(Clone)]
pub enum NotificationAgentOutput {
Notify(Notification),
}
#[derive(Clone, PartialEq)]
pub struct Notification {
pub content: String,
... |
use aoc2020::*;
use scan_fmt::*;
fn main() {
// let (_ret, dt) = execute_timed(|| aoc::aoc_1_0(99920044));
// println!("aoc 1_0(bigboy): finished in {} ms...", dt);
// let (_ret, dt) = execute_timed(|| aoc::aoc_1_1(99920044));
// println!("aoc 1_1(bigboy): finished in {} ms...", dt);
// let (_ret... |
//! The RFC 959 Change To Parent Directory (`CDUP`) command
//
// This command is a special case of CWD, and is included to
// simplify the implementation of programs for transferring
// directory trees between operating systems having different
// syntaxes for naming the parent directory. The reply codes
// shall be ... |
// Textbook recursive implementation
// Fully generic version that takes anything that can be compared in both
fn _find<T: PartialEq + PartialOrd, A: AsRef<[T]>>(
array: A,
key: T,
index: usize,
) -> Option<usize> {
let array = array.as_ref();
if array.len() == 1 {
if array[0] == key {
... |
extern crate num;
extern crate rand;
extern crate rand_distr;
use crate::{
indexed_triangles::IndexedTriangles,
light::Light,
material::{Mat, Material},
object::Object,
vec::{Ray, Vec3, Vector},
};
use num::{traits::float::FloatConst, Float, Zero};
use rand::prelude::*;
use rand_distr::{Standard, StandardNorm... |
extern crate env_logger;
use actix_web::{web, App, HttpResponse, HttpServer};
use async_graphql::extensions::ApolloTracing;
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig};
use async_graphql::{EmptyMutation, EmptySubscription, Schema};
use async_graphql_actix_web::{Request, Response};
mod state;
... |
use std::fmt::Debug;
use crate::{
dds::{participant::*, typedesc::*, qos::*, values::result::*, traits::dds_entity::DDSEntity},
};
pub use crate::structure::topic_kind::TopicKind;
/// Trait estimate of DDS 2.2.2.3.1 TopicDescription Class
pub trait TopicDescription {
fn get_participant(&self) -> Option<DomainPar... |
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::string::ToString;
use lego_config::read::{DataManagementObjects, LegoConfig};
pub struct CompositeObject {
info: CompositeInformation,
data: Vec<Composite>,
}
impl Composite... |
use sc_client::{AddAction, DumpOscMode, Options, ScClientResult, Server, Synth, SynthDefinition};
use std::env;
use std::fs::File;
use std::io::Read;
fn main() -> ScClientResult<()> {
env::set_var("RUST_LOG", "sc_client=debug");
env_logger::init();
let options = Options::new("examples/settings.toml");
... |
use ithkuil_learning::checks::*;
use ithkuil_learning::variants::*;
use ithkuil_learning::morpho_phonology::*;
mod common;
#[test]
fn slot41() {
let data = Data::new();
let variant = vec![Morpheme::C, Morpheme::Function(Function::Stative),
Morpheme::Specification(Specification::Basic),
... |
// https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/
// Given an array of integers preorder, which represents the preorder traversal of a BST
// (i.e., binary search tree), construct the tree and return its root.
// It is guaranteed that there is always possible to find a binary searc... |
// Copyright 2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
//! In this example we will send a transaction.
//! Run: `cargo run --example transaction --release`.
use iota_client::{secret::SecretManager, Client, Result};
#[tokio::main]
async fn main() -> Result<()> {
// This example uses dotenv, which ... |
use std::fmt::{self, Display, Formatter};
use std::os::raw::c_int;
use std::str::FromStr;
use libsqlite3_sys::{SQLITE_BLOB, SQLITE_FLOAT, SQLITE_INTEGER, SQLITE_NULL, SQLITE_TEXT};
use crate::error::BoxDynError;
pub(crate) use sqlx_core::type_info::*;
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(fe... |
use serde;
use serde_json;
use std::{fmt, io, error::Error, fs::File};
#[derive(Debug)]
pub enum SerializeError {
Io(io::Error),
Json(serde_json::Error),
}
impl fmt::Display for SerializeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
SerializeError::Io(re... |
#[test]
fn create_classic_model() {
let d = tempfile::tempdir().unwrap();
let path = d.path().join("create_classic.nc");
let mut file = netcdf::create_with(path, netcdf::Options::CLASSIC).unwrap();
// Classic mode does not support groups
file.add_group("grp").unwrap_err();
}
#[test]
fn create_with... |
use crate::type_object::PyBorrowFlagLayout;
use crate::{Py, PyClass, PyClassInitializer, PyTypeInfo, Python};
use serde::{de, ser, Deserialize, Deserializer, Serialize, Serializer};
impl<T> Serialize for Py<T>
where
T: Serialize + PyClass,
{
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok... |
// Copyright 2015-2018 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
use convopt::{
DVec,
optimization::{solve_min_problem},
test_problems::Rosenbrook
};
fn main() {
let min_prob = Rosenbrook::new(1f64,10f64);
let eps = 1e-4;
let max_iter = 100usize;
println!("\nSolving problem Rosenbrook, minimum at (x,y)=(1,-1):");
match solve_min_problem(&min_prob, e... |
// This code was expanded by `xtask`.
pub use self::internal_bit::*;
mod internal_bit {
// Skipped:
//
// - `bsf` = `__builtin_ctz`: is equivalent to `{integer}::trailing_zeros`
#[allow(dead_code)]
pub fn ceil_pow2(n: u32) -> u32 {
32 - n.saturating_sub(1).leading_zeros()
}
#[cfg... |
pub fn hit_trees(input: Vec<&str>, slope_x: usize, slope_y: usize) -> usize {
let y_max = input.len();
let trees = convert_trees_to_points(input);
let mut x = 0;
let mut y = 0;
let mut hits = 0;
while y <= y_max {
y += slope_y;
x += slope_x;
if trees.iter().any(|t| t.y_coordinate == y && (x %... |
struct Solution;
use util::*;
impl Solution {
fn reverse_between(mut head: ListLink, m: i32, n: i32) -> ListLink {
let mut v1: Vec<ListLink> = vec![];
let mut v2: Vec<ListLink> = vec![];
let mut v3: Vec<ListLink> = vec![];
let mut i = 0;
while let Some(mut node) = head {
... |
use std::fmt;
use rowan::GreenNodeBuilder;
use crate::{ast::Document, Error, SyntaxElement, SyntaxKind};
use super::GraphQLLanguage;
/// An AST generated by the parser.
pub struct SyntaxTree {
pub(crate) ast: rowan::SyntaxNode<GraphQLLanguage>,
pub(crate) errors: Vec<crate::Error>,
}
impl SyntaxTree {
... |
use crate::output::ResultsFormatter;
use crate::util::WritableBuffer;
#[derive(Default)]
pub struct CsvFormatter {
records: Vec<String>,
}
impl ResultsFormatter for CsvFormatter {
fn header(&mut self) -> Option<String> {
None
}
fn row_started(&mut self) -> Option<String> {
None
}
... |
use graph;
use std::collections::HashMap;
pub type AdjList = HashMap<i32, Vec<i32>>;
pub type Vertex = i32;
pub type Edge = (i32, i32);
impl graph::Graph for AdjList {
type Vertex = Vertex;
type Edge = Edge;
fn src(&self, edge: Self::Edge) -> Vertex { edge.1 }
fn tgt(&self, edge: Self::Edge) -> Verte... |
use std::fs::File;
use std::io::{self, Read};
use std::thread::sleep;
use std::time::{Duration, Instant};
use rand::{thread_rng, Rng};
use redis::Value::Okay;
use redis::{Client, IntoConnectionInfo, RedisError, RedisResult, Value};
const DEFAULT_RETRY_COUNT: u32 = 3;
const DEFAULT_RETRY_DELAY: u32 = 200;
const CLOCK_... |
#![feature(test)]
pub mod util;
extern crate test;
#[cfg(test)]
mod tests {
use test::Bencher;
use util::primes;
#[bench]
fn benchmark_primes(b: &mut Bencher) {
b.iter(|| primes().nth(1000));
}
}
|
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::account_config::core_code_address;
use crate::serde_helper::vec_bytes;
use bcs_ext::Sample;
use move_core_types::identifier::{IdentStr, Identifier};
use move_core_types::language_storage::{ModuleId, TypeTag};
use schemars::{... |
use crate::controllers::handlers::{
server_options, create_file, create_folder, delete_file, delete_folder, get_disks, get_file, get_folder, rename,
};
use crate::controllers::middleware;
pub fn start_server(addr: &str) {
rouille::start_server(addr, move |request| {
if let Some(forbidding_response) = m... |
// Copyright 2016 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 ... |
// Copyright 2020 Datafuse Labs.
//
// 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 ... |
use nannou::prelude::*;
mod palette;
use palette::Palette;
const PALETTE: [u32; 4] = [0x142850, 0x27496d, 0x0c7b93, 0x00a8cc];
const W: u32 = 600;
const H: u32 = 600;
struct Model {
ellipse_offset: f32
}
fn random_xy(w: f32, h: f32) -> Point2 {
let x = if random::<bool>() { -random::<f32>() } else { random... |
fn main() -> () {
let boarding_passes = BoardingPasses::parse(INPUT);
println!("{}", boarding_passes.highest_seat_id());
println!("{}", boarding_passes.missing_seat_id());
}
#[derive(Debug)]
struct BoardingPass(String);
#[derive(Debug)]
struct BoardingPasses {
passes: Vec<BoardingPass>,
}
impl Boardi... |
#![allow(dead_code)]
use crate::entity::Entity;
use crate::events::*;
use crate::mouse::*;
use crate::{BuildHandler, Justify, Length, PropSet, State, Visibility, WindowEvent, Window};
use glutin::event::VirtualKeyCode;
use std::collections::HashMap;
use femtovg::{
renderer::OpenGl,
Align,
Baseline,
... |
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use failure::Fail;
use log::LevelFilter;
use sentry::internals::Dsn;
use serde::Deserialize;
use crate::types::SourceConfig;
#[derive(Debug, Fail, derive_more::From)]
pub enum ConfigError {
#[fail(display = "Fa... |
use crate::alignments::SAlignmentFunc;
use readers::prelude::{Index, Value};
use readers::ra_reader::RAReader;
use crate::lang::Attribute;
#[derive(Debug)]
pub struct SglChainAlign<'a> {
// |readers| = |funcs| - 1, we get the value from index that the function yield from the corresponding reader
readers: Vec<&'a B... |
fn main() {
another_function(5, 6);
let a = five();
let b = {
let a = 3;
a + 1
};
let condition = true;
let number = if condition {
5
} else {
6
};
println!("The value of number is: {}", number);
println!("The value of b is: {}", b);
l... |
use std::fmt;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use pin_project_lite::pin_project;
use super::{delay_until, Delay};
pub fn timeout<T>(duration: Duration, future: T) -> Timeout<T>
where
T: Future,
{
timeout_at(Instant::... |
use std::io;
use std::io::Read;
use nom::character::complete::{char, digit1};
use nom::multi::separated_list;
use nom::IResult;
fn number_p(input: &str) -> IResult<&str, usize> {
let (input, num_str) = digit1(input)?;
Ok((input, num_str.parse().unwrap()))
}
fn program_p(input: &str) -> IResult<&str, Vec<usiz... |
use actix_web::http::Method;
use actix_web::*;
use clarity::Address;
use failure::Error;
use guac_core::types::{NewChannelTx, ReDrawTx, UpdateTx};
use guac_core::CounterpartyApi;
use guac_core::Guac;
use guac_core::GuacError;
use futures::future;
use futures::Future;
fn convert_error(err: Error) -> HttpResponse {
... |
//
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... |
extern crate rand;
use rand::distributions::{IndependentSample, Range};
fn main() {
let range = Range::new(-30, 30);
let mut rng = rand::thread_rng();
let mut v: Vec<i32> = Vec::new();
for _ in 0..10 {
v.push(range.ind_sample(&mut rng));
}
println!("{:?}", v);
let r = max_sub_array... |
//! Issues and tracks dynamic clients
use crate::{
config::DhcpConfig,
models::{Session, User},
};
use color_eyre::eyre::{self, WrapErr};
use parking_lot::RwLock;
use sqlx::sqlite::SqlitePool;
use std::{collections::HashMap, net::Ipv4Addr, sync::Arc};
use uuid::Uuid;
/// Responsible for tracking Internet Prof... |
use std::io::{Write,Read};
use std::net::TcpListener;
use std::net::TcpStream;
use std::collections::HashMap;
fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
}
}
type Hea... |
use std::fmt;
#[derive(Debug)]
struct Complex {
real: f64,
imaginary: f64,
}
impl fmt::Display for Complex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Complex: {{real: {},imag: {}}}",
self.real, self.imaginary
)
}
}
fn ma... |
struct Solution;
impl Solution {
fn fizz_buzz(n: i32) -> Vec<String> {
let mut res = vec![];
for i in 1..=n {
let fizz = i % 3 == 0;
let buzz = i % 5 == 0;
let s = match (fizz, buzz) {
(true, true) => "FizzBuzz".to_string(),
(true,... |
use std::collections::HashMap;
type Mapping = HashMap<char, u8>;
#[derive(Debug)]
struct Puzzle {
unique_chars: Vec<char>,
left: Vec<String>,
right: Vec<String>,
leading_chars: Vec<char>,
}
fn part_value(s: &Vec<String>, map: &Mapping) -> u32 {
s.into_iter()
.map(|word| {
word... |
fn main() {
let pair = (1, 3);
// TODO ^ Try different values for `pair`
println!("Tell me about {:?}", pair);
// Match can be used to destructure a tuple
match pair {
// Destructure the second
(0, y) => println!("First is `0` and `y` is `{:?}`", y),
(x, 0) => println!("`x` ... |
/// Wrapper type for write dynamic ansi string
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[doc(hidden)]
pub struct Ansi<T>(pub T);
|
// Adapted from SC3's ResonZ
use crate::Float;
use super::{Filter, FilterData};
pub struct ResonZ {
sample_rate: Float,
radians_per_sample: Float,
reso_factor: Float,
reso_offset: Float,
y1: Float,
y2: Float,
a0: Float,
b1: Float,
b2: Float,
}
impl ResonZ {
pub fn new(sample_... |
use util::{Scanner, Joinable};
fn insertion_sort(a: &Vec<i32>) -> Vec<i32> {
let mut result = a.clone();
let n = a.len() as i32;
for i in 1..n {
let v = result[i as usize];
let mut j: i32 = i - 1;
while j >= 0 && result[j as usize] > v {
result[(j+1) as usize] = result[j as usize];
j -= 1... |
use std::sync::Arc;
use futures01::future::Future;
use futures01::Poll;
use sentry::{Hub, Scope};
pub struct SentryFuture<F> {
pub(crate) hub: Arc<Hub>,
pub(crate) inner: F,
}
impl<F> Future for SentryFuture<F>
where
F: Future,
{
type Item = F::Item;
type Error = F::Error;
fn poll(&mut self... |
use rand::prelude::*;
use crate::{
vec3::{Vec3},
ray::{Ray},
};
pub struct Camera {
pub origin: Vec3,
pub lower_left_corner: Vec3,
pub horizontal: Vec3,
pub vertical: Vec3,
pub u: Vec3,
pub v: Vec3,
pub w: Vec3,
pub lens_radius: f32,
}
impl Camera {
// vfov is top to botto... |
use crate::lang::argument::ArgumentHandler;
use crate::lang::errors::{to_crush_error, CrushResult};
use crate::lang::execution_context::ExecutionContext;
use crate::lang::r#struct::Struct;
use crate::lang::scope::Scope;
use crate::lang::value::Value;
use signature::signature;
use sys_info;
#[signature(name, can_block ... |
#![allow(unused_variables)]
use std::fmt::Display;
// fn longest(x: &str, y: &str) -> &str {
// if x.len() > y.len() {
// x
// } else {
// y
// }
// }
// Lifetime annotations have a slightly unusual syntax: the names of lifetime
// parameters must start with an apostrophe (') and are usuall... |
// Read 2 numbers and sum them
use std::io;
fn sum_numbers(num_a: &f64, num_b: &f64) {
println!("X = {}", (num_a + num_b));
}
fn main() {
println!("Input two numbers to sum!");
println!("First number:");
let mut a = String::new();
println!("Seconde number:");
let mut b = String::new();
... |
use std::str::FromStr;
use error::ParseError;
use ast::{Ident, Type, Expr, CmpOp, CmpBinOp, ArithOp, ArithBinOp, If, Fun, LetFun, LetRec, Apply, Literal};
pub fn parse(input: &str) -> Result<Expr, ParseError> {
let tokenizer = Tokenizer::new(input);
let mut parser = Parser::new(tokenizer);
parser.parse()... |
/* SPDX-License-Identifier: MIT */
mod config;
mod generator;
mod kernlog;
mod setup;
use anyhow::Result;
use clap::{crate_description, crate_name, crate_version, App, Arg};
use log::{info, LevelFilter};
use std::borrow::Cow;
use std::env;
use std::path::{Path, PathBuf};
#[derive(Debug)]
enum Opts {
/// Generate... |
pub mod compiled_trie;
pub mod from_trie;
pub mod index;
pub mod trie_node;
pub mod trie_node_interface;
|
//! The Value Type
//!
//! The [`Value`] struct is the standard representation of a data value
//! in the Molt language. It represents a single immutable data value; the
//! data is reference-counted, so instances can be cloned efficiently. Its
//! content may be any TCL data value: e.g., a number, a list, a string, ... |
use libavif_sys as sys;
use std::fmt::{Binary, Formatter, LowerHex, Octal, UpperHex};
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not};
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(transparent)]
/// Flags when adding an image to the encoder using [`Encoder::add_image`](crate::... |
use std::io::Read;
use hyper::method::Method;
use hyper::header::{Headers, Authorization};
use rustc_serialize::json;
use hyper::status::StatusCode;
use chrono::NaiveDate;
use utils::Address;
use dto::{FromDTO, UserDTO, ProfileDTO, AuthenticationCodeDTO, ResponseDTO, UpdateUserDTO,
SearchUserDTO};
use super... |
use types::*;
use std::ops::*;
pub struct Operation<T: ?Sized>(Box<T>);
pub type ParseOperation<R> = Operation<Fn(&mut TwoWay) -> R>;
pub fn one_char(c: char) -> ParseOperation<Result<(), ()>> {
Operation(Box::new(move |s| {
let ptr = s.ptr();
if Some(c) == s.read() {
Ok(())
} else {
s.set(ptr);
Err(... |
#![allow(clippy::cast_ref_to_mut)]
extern crate byteorder;
extern crate clap;
extern crate kaiju_core as core;
extern crate kaiju_vm_core as vm_core;
extern crate minifb;
#[macro_use]
extern crate lazy_static;
extern crate rayon;
mod cartridge;
mod processor;
mod render;
use crate::cartridge::*;
use crate::processor... |
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use riichi_tools_rs::riichi::hand::Hand;
pub fn shanten_benchmark(c: &mut Criterion) {
let mut group = c.benchmark_group("shanten hands");
for hand in [
Hand::from_text("333699m17p13678s8m", false).unwrap(),
Hand::from_te... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.