text stringlengths 8 4.13M |
|---|
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
// iter(): ๊ฐ ์์๋ฅผ ๋ฐํํ๋ ํจ์
// enumerate(): iter์ ๊ฒฐ๊ณผ๊ฐ์ ํํ์ ์ผ๋ถ๋ก ๋ง๋ค์ด ๋ฐํ
for (i, &item) in bytes.iter().enumerate() {
// ๊ณต๋ฐฑ์ผ ๊ฒฝ์ฐ์๋ ๊ณต๋ฐฑ ์์น ๋ฐํ
if item == b' ' {
return i;
}
}
// ๊ณต๋ฐฑ์ด ์๋ ๊ฒฝ์ฐ์๋ ๋ฌธ์์ด ๊ธธ์ด ๋ฐํ
s... |
{{ name.to_insert() }}::new({{ generator.object(object) }})
|
use crate::errors::*;
use error_chain::bail;
use std::path::Path;
use std::process;
#[derive(Debug, PartialEq)]
pub enum Verbose {
Yes,
No,
}
#[derive(Debug)]
pub struct Output {
pub stdout: String,
pub stderr: String,
}
pub fn run_command(args: &[&str], cwd: &Path, verbose: Verbose) -> Result<Output... |
//! Data structures and implementations.
pub use self::dmat::DMat;
pub use self::dvec::{DVec, DVec1, DVec2, DVec3, DVec4, DVec5, DVec6};
pub use self::vec::{Vec0, Vec1, Vec2, Vec3, Vec4, Vec5, Vec6};
pub use self::pnt::{Pnt0, Pnt1, Pnt2, Pnt3, Pnt4, Pnt5, Pnt6};
pub use self::mat::{Identity, Mat1, Mat2, Mat3, Mat4, Ma... |
extern crate telamon_gen;
use telamon_gen::lexer::*;
use telamon_gen::ir::{CounterKind, CounterVisibility, SetDefKey, CmpOp};
#[test]
fn lexer_initial() {
// Invalid's Token
assert_eq!(Lexer::from(b"!".to_vec()).collect::<Vec<_>>(), vec![
Err(LexicalError::InvalidToken(
Posi... |
use std::u8;
use std::u16;
use std::u32;
use std::u64;
use std::i8;
use std::i16;
use std::i32;
use std::i64;
use std::f32;
use std::f64;
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Type {
U8,
U16,
U32,
U64,
I8,
I16,
I32,
I64,
F32,
F64,
Object
}
pub fn number_tag_to_typ... |
// Copyright 2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
//! High level APIs
mod address;
mod block_builder;
mod consolidation;
mod high_level;
mod types;
pub use self::{address::*, block_builder::*, types::*};
const ADDRESS_GAP_RANGE: u32 = 20;
|
/* This file is part of bacon.
* Copyright (c) Wyatt Campbell.
*
* See repository LICENSE for information.
*/
use crate::ivp::*;
use nalgebra::{VectorN, U1};
fn exp_deriv(_: f64, y: &[f64], _: &mut ()) -> Result<VectorN<f64, U1>, String> {
Ok(VectorN::<f64, U1>::from_column_slice(y))
}
fn quadratic_deriv(t: ... |
use std::io::stdin;
fn number_and_square(num: i32) -> (i32, i32) {
(num, num * num)
}
fn main() {
let mut number: i32;
println!("Enter number:");
loop {
let mut flag = false;
let mut temp_number = String::new();
stdin().read_line(&mut temp_number).expect("Failed to read number ... |
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
// You are given an integer array prices where prices[i] is the price of a given stock on the
// iแตสฐ day, and an integer k.
// Find the maximum profit you can achieve. You may complete at most k transactions.
// Note: You may not engage in multiple t... |
use bastion::prelude::*;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RenderMessage {
Foo,
Bar,
}
pub struct Renderer {}
impl Renderer {
pub async fn exec(ctx: BastionContext) -> Result<(), ()> {
log::debug!("Starting renderer...");
let task = blocking! {
log::debug!("On bl... |
use std::fmt::{Debug, Display};
use crate::error::Result;
use crate::model::{Value, ValueView};
use crate::runtime::{Expression, Runtime};
/// A structure that holds the information of a single parameter in a filter.
/// This includes its name, description and whether it is optional or required.
///
/// This is the r... |
#![feature(stmt_expr_attributes, proc_macro_hygiene)]
fn main() {
tracing_subscriber::fmt().init();
let a = String::from("hello");
let c = 42;
let e = std::io::Error::from(std::io::ErrorKind::Other);
let f = {
let mut map = std::collections::BTreeMap::new();
map.insert("a", 42i32);... |
extern crate num;
extern crate image;
use num::Complex;
use std::str::FromStr;
use image::ColorType;
use image::png::PNGEncoder;
use std::fs::File;
use std::io::Write;
/// This is used by rustdoc to generate documents
fn escape_time(c: Complex<f64>, limit:u32) -> Option<u32> {
let mut z = Complex {re:0.0, im:0.0};
... |
#[doc = "Register `ST4CSCTL` reader"]
pub struct R(crate::R<ST4CSCTL_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<ST4CSCTL_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<ST4CSCTL_SPEC>> for R {
#[inline(always)]
fn from(reader: ... |
#![feature(slice_concat_trait)]
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;
use std::num::ParseIntError;
use std::str::Chars;
use thiserror::Error;
#[derive(Debug, Clone)]
pub enum BencodeType {
BtString(String),
BtInt(i32),
BtList(Vec<BencodeType>),
BtDict(HashMap<BencodeType, BencodeTyp... |
use std::env;
use std::fs::read;
use std::io;
use std::io::prelude::*;
use std::path::Path;
use console::style;
use crc::{Crc, CRC_32_ISO_HDLC};
use rayon::prelude::*;
fn main() {
// Carrega os argumentos enviados por linha de comando
let args: Vec<String> = env::args().collect();
let lista_arquivos = arg... |
struct Solution {}
impl Solution {
pub fn find_restaurant(list1: Vec<String>, list2: Vec<String>) -> Vec<String> {
use std::collections::HashMap;
let mut map = HashMap::new();
for (i, el) in list1.into_iter().enumerate() {
map.insert(el, i);
}
let mut result = v... |
impl Solution {
fn is_valid(r: usize, c: usize, used: &Vec<(i32, i32)>) -> bool {
let mut res = true;
for (used_r, used_c) in used {
let diff_r = (used_r - (r as i32)).abs();
let diff_c = (used_c - (c as i32)).abs();
if diff_r == 0 || diff_c == 0 || diff_r == diff... |
use std::collections::HashMap;
use std::fmt::Debug;
use std::rc::Rc;
use std::cell::RefCell;
use std::iter;
use std::net::SocketAddr;
use std::io::{self, Error, ErrorKind, BufReader};
use std::sync::mpsc::{Sender};
use net2::TcpBuilder;
use futures::{Future, Stream};
use futures::stream::{self};
use futures::sync::mps... |
use crate::mat::mat2::Mat2f;
use crate::vec::vec2::Vec2;
use serde_derive::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;
/// Collection of 2d float vectors
#[wasm_bindgen(js_name=Array2f, inspectable)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Array2f {
#[wasm_bindgen(skip)]
pub data... |
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0.
use crate::errors::Result;
use crate::options::WriteOptions;
pub trait WriteBatchExt: Sized {
type WriteBatch: WriteBatch<Self>;
/// `WriteBatchVec` is used for `multi_batch_write` of LmdbEngine and other Engine could also
/// impl... |
pub use crate::common::prelude::*;
pub use crate::config::CONFIG; // TODO
pub use regex::Regex;
// pub use crate::common::fs::pathbuf_to_string; // TODO
pub trait Runnable {
fn run(&self) -> Result<()>;
}
|
use std::cmp;
use std::fs::read_to_string;
struct MemSpace {
mask: Vec<char>,
memory: Vec<u64>,
}
enum Instruction {
Mask(Vec<char>),
Write(usize, u64),
}
impl MemSpace {
fn new(memsize: usize) -> MemSpace {
MemSpace {
mask: vec!['X'; 36],
memory: vec![0; memsize],... |
// 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... |
// List of traits needed for wrapping regular functions to FunctionContainer.
use crate::expr::*;
use serde_json::Value;
impl From<Operand> for bool {
fn from(op: Operand) -> Self {
if let Operand::Value(val) = op {
if val.is_boolean() {
return val.as_bool().unwrap();
... |
use crate::device::Device;
#[derive(Debug)]
pub struct Memory {
memory: Box<[u8]>,
}
impl Memory {
pub fn new(size: u16) -> Memory {
Memory {
memory: vec![0; size as usize].into_boxed_slice(),
}
}
}
impl Device for Memory {
fn get_u8(&self, address: usize) -> u8 {
se... |
#[macro_use]
mod test_macro;
mod factory;
mod builder;
mod singleton;
mod prototype;
mod adapter;
mod bridge;
mod filter;
mod composite;
mod decorator;
|
#[doc = "Register `TH` reader"]
pub struct R(crate::R<TH_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<TH_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<TH_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<TH_SPEC>) -> Se... |
use std::cmp::{Ord, Ordering};
pub fn sort<T>(list: &mut [T])
where
T: Ord + Clone,
{
let l = list.len();
for i in 1..l {
let mut j: i32 = (i - 1) as i32;
let key = list[i].clone();
while j >= 0 && key < list[j as usize] {
list.swap(j as usize, (j + 1) as usize);
... |
use std::rc::Rc;
use std::num::Zero;
use std::f32;
use super::super::*;
use super::ShapeBase;
use super::quadrics;
/// A two-dimensional disk centered along the Z axis, at a specified height
/// along Z. The disk can be generalized to an annulus.
#[derive(Debug)]
pub struct Disk {
/// The members common to all shap... |
extern crate mclient;
use mclient::{Client};
fn main() {
let mut c = Client::new("127.0.0.1:11211").unwrap();
match c.set("go",0u16,0u,"for") {
Ok(ret) => { println!("ret {}",ret); }
Err(e) => { panic!(e); }
}
match c.get("go") {
Ok(ret) => { println!("ret {}",ret); }
Er... |
use std::env;
fn main() {
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
println!("cargo:rustc-link-search=native={}", manifest_dir);
}
|
#![cfg(test)]
use parse::Match;
use Pos;
mod error;
mod grammar_node;
mod group;
mod link_tree;
mod meta;
mod regression;
fn mat(
(lin0, row0, col0, lin1, row1, col1):
(usize, usize, usize, usize, usize, usize),
named: Vec<(&str, Vec<Match>)>,
) -> Match {
Match::new(
(
... |
#![feature(proc_macro_diagnostic)]
#![deny(clippy::pedantic)]
mod datatypes;
mod state_machine;
mod states;
mod util;
use syn::parse_macro_input;
/// Derive the Serializeable trait and create all required structs
///
/// Use this to create two different `struct`s, one with all fields
/// and one which only has the f... |
#![cfg(test)]
use super::*;
use std::string::ToString;
use crate::featurez::syntax::TokenSource;
macro_rules! single_token_tests {
($($name:ident: $value:expr,)*) => {
$(
#[test]
fn $name() {
let (input_text, expected_token_kind) = $value;
assert_single_token(input_text, expected_token_kind);
}
)*
}... |
pub struct Solution {}
impl Solution {
pub fn is_ugly(num: i32) -> bool {
let mut num = num;
while num > 1 {
if num % 2 == 0 {
num /= 2;
continue;
}
if num % 3 == 0 {
num /= 3;
continue;
... |
use crate::def::{point, FerrisData, FerrisSprite, Frame, SpriteSchedule};
pub(crate) fn ferris() -> FerrisData {
let opening_frames = OPENING.iter().map(|s| Frame::new(s)).collect();
let opening_moves = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)];
let opening_sprite = FerrisSprite::new(opening_frames, opening... |
#![deny(missing_docs)]
#![doc(html_root_url = "https://docs.rs/amq-protocol-codegen/1.0.0/")]
//! # AMQP code generation utilities
//!
//! amq-protocol-codegen is a library aiming at providing tools to generate
//! code from official AMQP specs definition.
extern crate amq_protocol_types;
extern crate handlebars;
ext... |
fn verify_hello_world_bytecode(bytecode: &[u8]) {
#[cfg(target_pointer_width = "64")]
assert_eq!(
bytecode,
[
27, 76, 74, 2, 10, 43, 2, 0, 3, 0, 2, 0, 4, 54, 0, 0, 0, 39, 2, 1, 0, 66, 0, 2, 1, 75, 0, 1, 0, 18, 72, 101, 108, 108, 111, 44, 32, 119,
111, 114, 108, 100, 33, 10, 112, 114, 105, 110, 116, 0
]
)... |
#![feature(test)]
#![feature(wrapping_int_impl)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
// use pyo3::wrap_pyfunction;
mod dfx;
mod discretize;
mod distances;
pub mod pgres;
pub struct Vector_Search_Server {
vs: dfx::Vec_Search,
search_limit: usize,
length_boost: f32,
}
impl Vector_Sea... |
#[derive(Debug, Clone, Hash)]
pub enum AST {
Ident(String),
Int(isize),
List(Vec<AST>),
Str(String),
Null
}
|
pub struct Forker;
|
use std::path::Path;
use handlebars::{to_json, Handlebars};
use serde_json::{Map, Value as Json};
use MarkdownFileList;
use config::Configuration;
use Result;
use file_utils;
/// Construct a generated index page for the site from the list of files used.
pub fn generate_index(files: &MarkdownFileList, config: &Config... |
//! # Tower service discovery
//!
//! Service discovery is the automatic detection of services available to the
//! consumer. These services typically live on other servers and are accessible
//! via the network; however, it is possible to discover services available in
//! other processes or even in process.
#[macro_... |
use schema::posts;
#[derive(Queryable, Serialize, Deserialize, Debug)]
pub struct Post {
pub id: i32,
pub title: String,
pub body: String,
pub published: bool,
}
#[derive(Insertable, Deserialize)]
#[table_name="posts"]
pub struct NewPost {
pub title: String,
pub body: String,
} |
//! configuration for the random spheres scene
use std::sync::Arc;
use rand::prelude::StdRng;
use rand::{Rng, SeedableRng};
use crate::config::SceneConfig;
use crate::object::material::{Dielectric, DiffuseLight};
use crate::object::texture::{CheckerTexture, SolidColor};
use crate::object::{
make_bouncing_sphere,... |
use actix_web::{web, Scope};
use serde::{Deserialize, Serialize};
mod actions;
mod controller;
pub fn register(scope: Scope) -> Scope {
let mut auth_scope = web::scope("auth");
// Debug routes
if cfg!(debug_assertions) {}
auth_scope = auth_scope
.service(controller::login)
.service(c... |
pub fn encode(source: &str) -> String {
if source.len() == 0 {
return "".to_string();
}
let mut result = String::new();
let mut count = 1;
let mut current = '\0';
for c in source.chars() {
if c != current {
if count != 1 {
result.push_str(format!("{}{}... |
/*
* @lc app=leetcode id=122 lang=rust
*
* [122] Best Time to Buy and Sell Stock II
*
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
*
* algorithms
* Easy (52.76%)
* Total Accepted: 384.6K
* Total Submissions: 721.2K
* Testcase Example: '[7,1,5,3,6,4]'
*
* Say you have ... |
#![feature(plugin)]
#![plugin(dynasm)]
extern crate clap;
extern crate dynasmrt;
extern crate motor;
use clap::{App, Arg};
use dynasmrt::DynasmApi;
use motor::binary::Module;
use motor::opcode::*;
use std::fs::File;
use std::mem;
fn main() {
let matches = App::new("Motor")
.version("0.1")
.author... |
use super::*;
use crate::graphics::*;
use std::fmt::{self, Display, Formatter};
#[derive(Default, Debug)]
pub struct OutputRegister(pub u8);
impl Module for OutputRegister {
fn get_name(&self) -> &'static str {
"Output"
}
fn reset(&mut self) {
self.0 = 0;
}
fn bus_read_flag(&self... |
use svm_sdk_mock::template;
#[template]
mod Template {
#[storage]
struct Storage {
qword: u64,
qwords: [u64; 3],
}
}
fn main() {
// `qword`
let qword = Storage::get_qword();
assert_eq!(qword, 0);
Storage::set_qword(0xAAAAAAAA_AAAAAAAA);
let qword = Storage::get_qword()... |
// 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... |
use ckb_jsonrpc_types as json_types;
use ckb_types::H256;
use serde_derive::{Deserialize, Serialize};
use crate::subcommands::tx::ReprMultisigConfig;
// Deployment
#[derive(Clone, Default, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Deployment {
pub lock: json_types::Script,
pub cells: Vec<Cell>... |
use htmlescape::*;
use unic_ucd::category::GeneralCategory as gc;
/// Filters out separators, control codes, unicode surrogates, and a few others
/// as well as single/double quotes, backslashes, and angle braces.
///
/// This is used mainly for passwords/usernames and other user input that
/// should be sanitized w... |
use std::thread;
use std::time::Duration;
fn count() {
let mut children = vec![];
for ii in 0..3 {
children.push(
thread::spawn(move || {
for iii in 0..10 {
println!("Thread {0} puts: {1}", ii, iii);
}
})
);
}
}
... |
fn solution(num: i32) -> i32 {
let mut i = 0;
let mut r = 0;
while i < num {
if i % 3 == 0 || i % 5 == 0{
r += i;
}
i += 1;
}
r
}
fn solution1(num: i32) -> i32 {
(1..num).filter(|x|x % 3 == 0 || x % 5 == 0).sum()
}
fn solution2(num: i32) -> i... |
fn main() {
let array:[i32;5] = [1, 2, 3, 4, 5];
println!("as is {:?}", array);
} |
/**
* [384] Shuffle an Array
*
* Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.
Implement the Solution class:
Solution(int[] nums) Initializes the object with the integer array nums.
int[] reset()... |
use winapi::um::winuser;
use winapi::shared::windef::HWND;
use winapi::um::winuser::{MAPVK_VK_TO_VSC, GetKeyNameTextW, GetForegroundWindow, GetWindowTextW};
use std::fs::OpenOptions;
use std::io::Write;
use std::path::Path;
use crate::network::send_buf;
use std::net::SocketAddr;
pub fn start<T: AsRef<Path>>(server: So... |
use crate::cli;
use std::fs::File;
pub struct Config {
pub input_file: File,
pub output_file: File,
}
impl Config {
pub fn load(args: &cli::Cli) -> Result<Self, Box<dyn std::error::Error>> {
Ok(Self {
input_file: File::open(args.input_file.clone())?,
output_file: {
... |
use anyhow::Result;
use yew::prelude::*;
use yew::format::Nothing;
use yew::services::fetch::{FetchService, FetchTask, Request, Response};
use serde::{Deserialize, Serialize};
use serde_json::from_str;
#[derive(Serialize, Deserialize)]
struct Blog {
posts: Vec<Post>,
}
#[derive(Serialize, Deserialize)]
struct Po... |
use std::collections::{HashSet, HashMap};
use std::net::SocketAddr;
use std::sync::mpsc::SyncSender;
use bip_handshake::Handshaker;
use bip_util::bt::{self, NodeId};
use mio::{Timeout, EventLoop};
use message::find_node::FindNodeRequest;
use routing::bucket::Bucket;
use routing::node::{Node, NodeStatus};
use routing:... |
use crate::bus::memory_map::*;
use crate::Bus;
/// Bank contains functions to configure a PWM.
/// A bank is a set of 4 pins, starting from pin 0 and going in order.
///
/// Bank 0: pins (0->3)
///
/// Bank 1: pins (4->8)
///
/// Bank 2: pins (9->12)
///
/// Bank 3: pins (13->16)
#[derive(Debug, Clone)]
pub struct Ban... |
use super::{Check, CheckView, ParityCheckMatrix};
use itertools::EitherOrBoth;
use itertools::Itertools;
pub(super) struct Concatener<'a> {
left_matrix: &'a ParityCheckMatrix,
right_matrix: &'a ParityCheckMatrix,
}
impl<'a> Concatener<'a> {
pub(super) fn from(
left_matrix: &'a ParityCheckMatrix,
... |
use crate::env::Env;
pub struct Bucket(String);
impl Bucket {
pub fn env() -> Bucket {
Bucket(Env::aws_bucket_name())
}
}
impl Into<String> for Bucket {
fn into(self) -> String {
self.0
}
}
|
//! Time-Based One Time Password Database Model
use crate::{models::User, otp};
use color_eyre::eyre;
use sqlx::sqlite::SqlitePool;
use std::convert::TryInto;
#[derive(Clone, Debug, sqlx::FromRow)]
pub struct TotpParams {
key: Vec<u8>,
step: i64,
base: i64,
digits: u32,
}
impl TotpParams {
/// Ge... |
use super::event_handler::EventHandler;
use crate::error::Result;
use libs::make_family_prefix;
use protobuf;
use sawtooth_sdk::messages::client_event::{
ClientEventsSubscribeRequest, ClientEventsSubscribeResponse,
ClientEventsSubscribeResponse_Status, ClientEventsUnsubscribeRequest,
ClientEventsUnsubscribe... |
use std::{
collections::BTreeSet, fs, io::Read, os::unix::fs::PermissionsExt as _, path::Path,
str::FromStr,
};
use crate::{
errors::{CliError, Error},
oasis_xdg_dir, utils,
};
const OASIS_GENESIS_YEAR: u8 = 19;
const WEEKS_IN_YEAR: u8 = 54;
const INSTALLED_RELEASE_FILE: &str = "installed_release";
co... |
use inflector::Inflector;
use pmutil::{q, IdentExt};
use proc_macro2::Ident;
use std::mem::replace;
use swc_macros_common::{call_site, def_site};
use syn::{
parse_quote::parse, punctuated::Punctuated, spanned::Spanned, Arm, AttrStyle, Attribute, Block,
Expr, ExprBlock, ExprMatch, FieldValue, Fields, FnArg, Gene... |
use actix_web::{
error, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer,
};
use bytes::{Bytes, BytesMut};
use futures::StreamExt;
use json::JsonValue;
use serde::{Deserialize, Serialize};
use actix_multipart::Multipart;
use actix_files;
use std::io::Write;
use std::rc::Rc;
use std::collections::... |
extern crate daas;
extern crate kafka;
extern crate rusoto_core;
use daas::service::processor::{DaaSGenesisProcessorService, DaasGenesisProcessor};
use daas::storage::s3::{S3BucketManager, S3BucketMngr};
use kafka::consumer::{FetchOffset, GroupOffsetStorage};
use rusoto_core::Region;
use std::io;
// NOTE: Modify the ... |
use warp::Filter;
use crate::handlers::*;
pub fn create_room(conn: &Connections) -> impl warp::Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
warp::path("create")
.and(warp::ws())
.and(with_conns(conn.clone()))
.and_then(create_handler)
}
pub fn join_room(conn: &Con... |
use std::env;
pub fn base_rpc_url() -> String {
env::var("RPC_URL").unwrap()
}
pub fn transaction_fee() -> String {
env::var("TRANSACTION_FEE").unwrap_or("0".to_string())
}
pub fn multisend_address() -> String {
env::var("MULTISEND_ADDRESS").unwrap()
}
pub fn factory_address() -> String {
env::var("... |
#![no_main]
#![no_std]
// panic handler
extern crate panic_semihosting;
use cortex_m_semihosting::hprintln;
use dwm1001::{new_usb_uarte, nrf52832_hal as hal, UsbUarteConfig};
use hal::prelude::*;
use hal::target::{interrupt, UARTE0};
use hal::{DMAPool, RXError, TXQSize, UarteRX, UarteTX, DMA_SIZE};
use heapless::{
... |
extern crate rugcc;
use self::rugcc::common::{TK, Token, ND, Node, Type};
fn new_binop(op: ND, lhs: Node, rhs: Node) -> Node {
return Node{ op, lhs: Some(Box::new(lhs)), rhs: Some(Box::new(rhs)), ..Default::default()};
}
fn new_expr(op: ND, expr: Node) -> Node {
return Node{op, expr: Some(Box::new(expr)), .... |
#[macro_use]
extern crate simple_nn;
use simple_nn::Net;
const XOR_NET_EPOCHS: usize = 10;
const SOLVER_NET_EPOCHS: usize = 10;
const T: f64 = 1.0;
const F: f64 = -1.0;
fn main() {
let training_set = sample![
[F, F] => [F],
[F, T] => [T],
[T, F] => [T],
[T, T] => [F]
];
... |
// An async implementation which is currently unused but might be used in the feature.
use crate::ast;
use std::task::Poll;
use tokio::io::AsyncReadExt;
pub struct State {
indent: u16,
position: ast::Position,
}
impl State {
fn start() -> State {
State {
indent: 0,
posit... |
struct Solution;
#[allow(dead_code)]
impl Solution {
pub fn single_number(nums: Vec<i32>) -> i32 {
// let mut s = String::new();
// let mut sr = &mut s;//ๆฟๅฐไบmut ๅผ็จ
// sr.push('a');
// println!("aaaaa{}",&s); // ๆฟๅฐไบ ๅผ็จ
// sr.push('a');//
// let mut res = nums[0];... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::move_command_line_common::files::{MOVE_COMPILED_EXTENSION, MOVE_EXTENSION};
use std::path::{Path, PathBuf};
/// Helper function to iterate through all the files in the given directory, skipping hidden files,
/// and retu... |
pub struct Luhn {
valid: bool,
}
impl Luhn {
pub fn is_valid(&self) -> bool {
self.valid
}
}
/// Here is the example of how the From trait could be implemented
/// for the &str type. Naturally, you can implement this trait
/// by hand for the every other type presented in the test suite,
/// but y... |
#![allow(dead_code, non_camel_case_types, non_upper_case_globals)]
#[macro_use] extern crate gstuff;
extern crate libc;
use std::ffi::CStr;
use std::io::Write;
use std::mem::uninitialized;
use std::ptr::null_mut;
use std::str::from_utf8_unchecked;
pub type uint8_t = u8;
pub type int32_t = i32;
pub type uint32_t = u3... |
use std::ops::{Index, IndexMut};
/// Trait for working with generic list data structures.
pub trait BListAccess<V> {
/// Get a list element at the given index.
fn get(&self, index: usize) -> Option<&V>;
/// Get a mutable list element at the given index.
fn get_mut(&mut self, index: usize) -> Option<&m... |
/**
* Provides Models for objects
*
*/
extern crate serde;
extern crate serde_json;
extern crate uuid;
use serde::{Serialize, Deserialize};
use std::fmt::{self, Formatter, Display};
#[derive(Serialize, Deserialize, Debug)]
pub struct Edges{
pub id: uuid::Uuid,
pub desc:String,
pub url:String,
}
imp... |
// Copyright 2020 Parity Technologies
//
// 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 your
// option. This file may not be copied, modified, or distributed
// except accor... |
//! A utility for writing scripts for use as test executables intended to match the
//! subcommands of Bazel build actions so `rustdoc --test`, which builds and tests
//! code in a single call, can be run as a test target in a hermetic manner.
use std::cmp::Reverse;
use std::collections::{BTreeMap, BTreeSet};
use std:... |
use std::io;
pub(super) fn run() -> io::Result<()> {
{
println!("Year 2019 Day 15 Part 1");
println!("Unimplemented");
}
{
println!("Year 2019 Day 15 Part 2");
println!("Unimplemented");
}
Ok(())
}
|
#![allow(unused_variables)]
mod heightmap;
mod util;
mod voronoi;
mod svg_test;
use std::collections::VecDeque;
use std::iter::successors;
#[cfg(target_arch = "wasm32")]
use std::panic;
use std::num::NonZeroU32;
#[cfg(target_arch = "wasm32")]
use js_sys::{Array, JsString};
use rand::{random, SeedableRng};
use rand::... |
use std::io::{self, Read, Write};
use std::env;
fn main() -> io::Result<()> {
let secret = env::args().nth(1).unwrap_or(char::from(0).to_string());
let mut file = Vec::new();
eprintln!(r#"secret = "{}";"#, secret);
io::stdin().read_to_end(&mut file)?;
let secret = secret.as_bytes().iter().cycle(... |
use gw_common::{sparse_merkle_tree::CompiledMerkleProof, H256};
use gw_types::offchain::RecoverAccount;
use gw_types::packed::{
Bytes, RawL2Block, RawL2BlockVec, Script, VerifyTransactionSignatureWitness,
VerifyTransactionWitness, VerifyWithdrawalWitness,
};
use std::collections::HashMap;
#[derive(Debug, Clon... |
use crate::utils;
use std::collections::{HashMap};
pub struct Solver{
pub route: Vec<u8>,
node_cnt: u8,
pub dist_map: HashMap<(u8,u8),f32>,
pub pher_map: HashMap<(u8,u8),f32>,
alpha: f32,
beta: f32,
ant_cnt: u8,
decay_rate:f32,
seed_rounds:u8,
}
impl Solver{
pub fn new(node_cnt... |
extern crate utils;
extern crate regex;
use utils::utils::read_input;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::collections::BinaryHeap;
use regex::Regex;
#[derive(Eq, Clone)]
struct Step {
id: char,
children: Vec<char>,
requires: Vec<char>,
seconds_left: u8
}
impl Step {
fn... |
use std::io::Cursor;
use byteorder::{BigEndian, ReadBytesExt};
use bit_vec::BitVec;
use std::char;
pub type ReadError = (usize, String);
pub fn read_u16(b1: u8, b2: u8) -> u16 {
return Cursor::new(vec![b1, b2]).read_u16::<BigEndian>().unwrap();
}
pub fn read_u32(b1: u8, b2: u8, b3: u8, b4: u8) -> u32 {
return... |
#![allow(clippy::eval_order_dependence)]
extern crate proc_macro;
// LinkedHashSet is used instead of HashSet in order to insertion order across the board
use linked_hash_set::LinkedHashSet;
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use std::iter::FromIterator;
use syn::visit::Visit;
use sy... |
#[doc = "Register `HFXODEBOUNCE` reader"]
pub struct R(crate::R<HFXODEBOUNCE_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<HFXODEBOUNCE_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<HFXODEBOUNCE_SPEC>> for R {
#[inline(always)]
... |
fn main() {
let x = 5i;
let y = if x == 5i { 10i } else { 15i };
println!("The value of y is: {}", y);
}
|
pub struct Mesh {
pub verts: Vec<f32>,
pub indices: Vec<u16>,
}
impl Mesh {
pub fn new(verts: Vec<f32> , indices: Vec<u16>) -> Self {
Self {
verts: verts, indices: indices,
}
}
}
// returns vertices & indices of a flat grid
// TODO model this after grasshopper
// ((Plane, D... |
use std::collections::HashMap;
use ast::{self, Expr};
pub type Name = usize;
pub enum Ir {
Var(Name),
IntLiteral(i64),
BoolLiteral(bool),
BinOp(Box<BinOp>),
If(Box<If>),
Fun(Box<Fun>),
Apply(Box<Apply>),
}
pub fn desugar(expr: &Expr) -> Ir {
let mut renamer = Renamer::empty();
exp... |
extern crate clipboard;
fn main() {
let mut context = clipboard::ClipboardContext::new().unwrap();
context.set_contents(format!("Hello world!")).unwrap();
std::thread::sleep(std::time::Duration::from_secs(30));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.