text stringlengths 8 4.13M |
|---|
mod tests;
mod serving;
use friday_vendor;
use vendor_scripts;
use friday_audio;
use friday_vad;
use friday_discovery;
use friday_logging;
use friday_signal;
use friday_inference;
use friday_inference::Model;
use tensorflow_models;
use friday_web::server::Server;
use std::sync::{Arc, Mutex};
fn main() {
// T... |
use std::collections::HashSet;
use std::process::Command;
use std::io::Write;
use colored::*;
use chrono::{TimeZone, NaiveDateTime, Local};
use aur;
use aur::types::SearchResult;
// Search the AUR and core repositories for packages mentioning the given terms
pub fn search_packages<'a>(package_names: HashSet<&'a str... |
mod proto;
// use bytes::BufMut;
// use bytes::{Bytes, BytesMut};
// use futures::stream::TryStreamExt;
use byteorder::{BigEndian, ByteOrder};
use bytes::BufMut;
use hyper::body;
use hyper::service::{make_service_fn, service_fn};
use hyper::HeaderMap;
use hyper::{Body, Request, Response, Server, Version};
use prost::Me... |
#[doc = "Register `DDRCTRL_POISONSTAT` reader"]
pub type R = crate::R<DDRCTRL_POISONSTAT_SPEC>;
#[doc = "Field `WR_POISON_INTR_0` reader - WR_POISON_INTR_0"]
pub type WR_POISON_INTR_0_R = crate::BitReader;
#[doc = "Field `WR_POISON_INTR_1` reader - WR_POISON_INTR_1"]
pub type WR_POISON_INTR_1_R = crate::BitReader;
#[do... |
#![feature(untagged_unions)]
#![feature(c_variadic)]
pub mod defs;
pub mod exceptions;
pub mod predefined;
pub mod symbols;
pub mod error;
|
use serde_json;
use hangouts;
use pblite::Message;
// TODO: Come up with better names for everything here.
error_chain!{}
#[derive(Debug, PartialEq)]
pub struct ContainerArray {
pub channel_arrays: Vec<ChannelArray>,
}
impl ContainerArray {
pub fn parse(string: &str) -> Result<Self> {
let mut value =... |
#[macro_use]
extern crate diesel;
extern crate elastic;
#[macro_use]
extern crate elastic_derive;
use serde::Deserialize;
pub mod constants;
pub mod schema;
pub mod db;
pub mod eventstore;
pub mod eventpublisher;
pub mod dao;
#[derive(Deserialize, Debug)]
pub struct Config {
pub database_url: String,
pub k... |
use std::env;
use std::fs::File;
use std::io::prelude::BufRead;
use std::io::BufReader;
use std::collections::HashMap;
use regex::Regex;
use std::collections::BTreeMap;
extern crate regex;
#[derive(Debug)]
struct WordStore {
counts: HashMap<String, u64>
}
impl WordStore {
fn new() -> WordStore {
Wor... |
use core::MatrixArray;
use core::dimension::{U1, U2, U3};
use geometry::{Rotation, SimilarityBase, UnitQuaternion, UnitComplex};
/// A D-dimensional similarity.
pub type Similarity<N, D> = SimilarityBase<N, D, MatrixArray<N, D, U1>, Rotation<N, D>>;
/// A 2-dimensional similarity.
pub type Similarity2<N> = Similarit... |
//! A backend module for implementing the iterator like
//! [`iterator`][crate::iterator] module and the asynchronous
//! adapter crates.
//!
//! This module contains generic types which abstract over the concrete
//! IO type for the self-pipe. The motivation for having this abstraction
//! are the adapter crates for d... |
use std::fmt;
use std::str::CowString;
use super::escs::{ANSI_D};
use super::nav::{save_cursor,
restore_cursor,
jump_string,
Point,
Frame};
/// XString: these are the valid types of string for xterm markup.
///
/// This will eventually be hidden.
pub ... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - SRAM/NOR flash control register 0"]
pub snctl0: SNCTL0,
#[doc = "0x04 - SRAM/NOR flash timing configuration register 0"]
pub sntcfg0: SNTCFG0,
#[doc = "0x08 - SRAM/NOR flash control register 1"]
pub snctl1: SNCTL1,
... |
use regex::Regex;
use std::cell::RefCell;
use std::collections::HashMap;
use std::io::{self};
struct Rule {
str_value: String,
rule: Option<String>,
}
impl Rule {
fn to_regex(&mut self, rules: &HashMap<i32, RefCell<Rule>>) -> String {
match &self.rule {
Some(rule) => {
... |
use amethyst::core::{SystemDesc, Transform};
use amethyst::derive::SystemDesc;
use amethyst::ecs::{Join, Read, System, SystemData, World, WriteStorage};
use amethyst::input::{InputHandler, StringBindings};
// You'll have to mark PADDLE_HEIGHT as public in pong.rs
use crate::state::Crab;
#[derive(SystemDesc)]
pub stru... |
use rustler::types::{atom::Atom, binary::Binary};
use rustler::Encoder;
use rustler::{Env, NifResult, Term};
mod atoms {
rustler::rustler_atoms! {
atom ok;
}
}
pub fn on_load(_env: Env) {}
pub fn atom_to_string<'a>(env: Env<'a>, args: &[Term<'a>]) -> NifResult<Term<'a>> {
let atom_string = args[0... |
use rand_core::{ RngCore, CryptoRng };
use hacl_star_sys as ffi;
const BASEPOINT: [u8; 32] = [9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
pub const PUBLIC_LENGTH: usize = 32;
pub const SECRET_LENGTH: usize = 32;
define!{
pub struct SecretKey/secretkey(pub [u8... |
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct Counter {
pub name: String,
pub count: i32,
}
|
//! Manage the target inspector sub-process
//!
//! The interogation that lading does of the target sub-process is intentionally
//! limited to in-process concerns. For instance, lading is able to measure the
//! bytes written per second to a target becase lading itself is writing the
//! bytes. It's valuable to have f... |
#[doc = "Register `CRCPR` reader"]
pub type R = crate::R<CRCPR_SPEC>;
#[doc = "Register `CRCPR` writer"]
pub type W = crate::W<CRCPR_SPEC>;
#[doc = "Field `CRCPOLY` reader - CRC polynomial register"]
pub type CRCPOLY_R = crate::FieldReader<u16>;
#[doc = "Field `CRCPOLY` writer - CRC polynomial register"]
pub type CRCPO... |
use super::id_table::{IdColor, IdTable, ObjectId, Surface};
use super::matrix::{camera::CameraMatrix, model::ModelMatrix};
use super::webgl::{program, ProgramType, WebGlF32Vbo, WebGlI16Ibo, WebGlRenderingContext};
use crate::arena::block::{self, BlockId};
use crate::arena::resource;
use ndarray::Array2;
use std::collec... |
//! Types that are commone between different operations.
use std::fmt;
#[allow(clippy::trivially_copy_pass_by_ref)]
fn pretty_on(pretty_print: &bool) -> bool {
*pretty_print
}
/// [Standard Query Parameters](https://cloud.google.com/storage/docs/json_api/v1/parameters#query)
/// can be used in almost any API req... |
#[cfg(windows)]
extern crate ws2_32;
#[cfg(windows)]
use std::mem;
use std::ffi::{CStr, CString};
use libc::c_char;
use std::ptr;
#[cfg(windows)]
pub fn other_init() {
// libtls currently (2.3.1) fails to initialize the
// windows network stack - issue #167
unsafe {
let mut data = mem::zeroed();
... |
use actix_web::HttpResponse;
use super::super::domain::job::DomainJob;
use serde_derive::{
Deserialize,
Serialize,
};
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Job {
id: i32,
company_name: String,
company_logo: String,
company_thumbnail: String,
titl... |
use crate::config;
use crate::util::*;
use std::fs;
pub fn run() {
let name = if args_len() < 3 {
choose_note()
} else {
get_argument(2)
};
if !get_confirmation("Confirm") {
println!("Notes {} was not removed.", name);
return
}
match fs::remove_file(format!("{}... |
use std::process;
use crate::util::Newline;
use crate::util::CmpType;
use crate::util::ScanIter;
use crate::util::char;
#[derive(Debug, PartialEq, Clone)]
pub enum Token {
LeftParen,
RightParen,
LeftBrace,
RightBrace,
DollarSign,
Slash,
Comma,
Bang,
BangEqual,
Equal,
EqualE... |
use std::io::{Write};
use std::fs::File;
use lib::{Node};
use parser_lib;
use asm_lib as asm;
// $ gcc -m32 -masm=intel main.s -o main
pub fn gen(path: & String, filename: & String) {
// println!("----------------");
let ast: Vec<Node::Node> = parser_lib::parse(&path, &filename);
let mut f = File::create(&filenam... |
use ggez::{graphics, Context, GameResult};
use ggez::event::EventHandler;
use rand::Rng;
use std::fs::File;
use std::io::{Read};
#[derive(Clone)]
struct Vector2D {
x: f32,
y: f32
}
impl Vector2D {
pub fn new(x: f32, y: f32) -> Self {
Self {
x,
y
}
}
}
impl Into... |
// q0039_combination_sum
struct Solution;
// impl Solution {
// pub fn combination_sum(candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
// let mut ret = vec![];
// Solution::solve(&candidates, target, &mut ret);
// ret
// }
// fn solve(cddt: &[i32], target: i32, ret: &mut Vec... |
//A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
//
//Find the largest palindrome made from the product of two 3-digit numbers.
// Loop through from 999 to 100 for both multipliers, testing if result is palindrome, return the maximu... |
use crate::grammar::ast::eq::{ast_eq, AstEq};
use crate::grammar::ast::BooleanLit;
use crate::grammar::ast::CharLit;
use crate::grammar::ast::Identifier;
use crate::grammar::ast::NumLitPattern;
use crate::grammar::ast::Pattern;
use crate::grammar::ast::StringLit;
use crate::grammar::ast::Underscore;
use crate::grammar:... |
#![doc(html_logo_url = "https://avatars0.githubusercontent.com/u/54989751?s=200&v=4")]
//! # wapc
//!
//! The `wapc` crate provides a WebAssembly host runtime that conforms to an RPC mechanism
//! called **waPC**. waPC is designed specifically to prevent either side of the call from having
//! to know anything about _... |
extern crate clap;
extern crate kvs;
use clap::{App, AppSettings, Arg, SubCommand};
use kvs::{KvStore, Result};
use std::env;
use std::process::exit;
fn main() -> Result<()> {
let matches = App::new(env!("CARGO_PKG_NAME"))
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about(env!... |
//! Safe abstractions for an I2C bus.
// use core::iter::TrustedLen;
use core::marker::PhantomData;
use core::ops::Deref;
use embedded_hal;
use stm32f7::stm32f7x6::{self as device, i2c1, RCC};
/// This trait marks all valid I2C types. Used to provide generic interfaces.
///
/// TODO: replace by trait alias when they'... |
use super::Control;
use gilrs;
use rov::RovCommand::{self, LightsOn, LightsOff};
pub struct Lights {
// info
button: gilrs::Button,
// state
lights_state: bool,
was_pressed: bool,
need_to_write: bool,
}
impl Lights {
pub fn new(button: gilrs::Button) -> Self {
Lights {
... |
//! [Traits]: Defining Shared Behavior
//!
//! [traits]: https://doc.rust-lang.org/book/ch10-02-traits.html
//!
//! # Examples
//!
//! ```
//! use the_book::ch10::{Article, Tweet, Summary};
//!
//! let article = Article {
//! headline: String::from("Headline!"),
//! content: String::from("Article"),
//! };
//! ... |
// Copyright 2015 click2stream, Inc.
//
// 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... |
use std::cmp;
fn gcd(a: i32, b: i32) -> i32 {
if b == 0 {
return a
}
gcd(b, a % b)
}
fn act2_6_1(p1: &Vec<i32>, p2: &Vec<i32>) -> i32 {
let mut mx:i32 = 0;
let mut mn:i32 = 0;
if p1[0].wrapping_sub(p2[0]) > p1[1].wrapping_sub(p2[1]) {
mx = cmp::max(p1[0], p2[0]).wrapping_sub(cmp::min(p1[0], p2[0]));
mn = ... |
// Copyright 2022 Alibaba Cloud. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use tokio::sync::Notify;
use tokio::time::{error::Elapsed, timeout, Duration};
#[derive(Debug)]
struct Shared {
shutdown: AtomicBool,
... |
#![cfg_attr(target_os = "wasi", feature(wasi_ext))]
mod io {
mod isatty;
mod mmap;
#[cfg(not(target_os = "redox"))] // redox doesn't have cwd/openat
#[cfg(not(target_os = "wasi"))] // wasi support for S_IRUSR etc. submitted to libc in #2264
mod readwrite;
}
|
use crate::item::Item;
use crate::markdown::{markdown_to_html, markdown_to_html_strip_one_paragraph};
use crate::paths::AbsPath;
use crate::{
content::PostItem,
item::{RenderContext, TeraItem},
markdown::find_markdown_files,
site_url::SiteUrl,
};
use chrono::NaiveDate;
use eyre::{eyre, Result};
use item... |
//! A bitmask generator for enum scoped bit flags.
//!
//! The `bitmask!` macro creates a struct and an enum that holds your flags. The enum contains all the
//! bit flag variants and the struct is a mixture of those bit flags called a bitmask.
//! It's syntax is as follows:
//!
//! ```ignore
//! bitmask! {
//! pub... |
use std::fs ;
use std::fs::File;
use std::io::Read;
use std::io::{BufRead, BufReader};
fn main() {
// ファイルを一気に読み込む
let path = "sample.txt" ;
println!("read all liens.");
if let Ok(data) = fs::read_to_string( path ) {
println!("data is {}", data);
} else {
println!("cannot open {}",... |
//! ## deno_bindgen
//! This tool aims to simply types & glue code generation for FFI
//! libraries written in Rust.
//!
//! ### Usage
//! Add `serde` and `deno_bindgen` dependency to your crate.
//!
//! ```
//! use deno_bindgen::deno_bindgen;
//!
//! #[deno_bindgen]
//! pub struct Input {
//! /// Doc comments are tr... |
use std::path::PathBuf;
use crate::os::{SysFreeString, SysStringLen, BSTR, HRESULT, LPSTR, LPWSTR, WCHAR};
use crate::wrapper::*;
use thiserror::Error;
pub(crate) fn to_wide(msg: &str) -> Vec<WCHAR> {
widestring::WideCString::from_str(msg)
.unwrap()
.into_vec_with_nul()
}
pub(crate) fn from_wide(... |
// En déplaçant (move) une variable,
// on laisse son heap intact mais on l'alloue à une autre variable.
// Comment faire pour avoir deux fois le même texte dans le heap ? On clone.
// clone est une MÉTHODE
fn main() {
let s1 = String::from("Hello");
let s2 = s1.clone();
println!("Voici s1 : {}, \net voic... |
pub mod storage;
pub mod query;
pub mod csv;
pub mod failpoints;
pub mod buffering;
pub mod restapi; |
//! Tracer structure.
use arctk::{
access, clone,
geom::Ray,
math::{Dir3, Pos3},
};
/// Colouring tracer.
#[derive(Clone)]
pub struct Tracer {
/// Internal ray.
ray: Ray,
/// Weighting power.
weight: f64,
/// Cumulative distance travelled.
dist_travelled: f64,
}
impl Tracer {
... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use super::{models, API_VERSION};
#[non_exhaustive]
#[derive(Debug, thiserror :: Error)]
#[allow(non_camel_case_types)]
pub enum Error {
#[error(transparent)]
Service_ListFileSystems(#[from] servi... |
#![allow(dead_code, unused_macros)]
extern crate env_logger;
use std::path::PathBuf;
macro_rules! config_test {
($name:ident, $prefix:expr) => {
#[macro_use]
extern crate log;
#[test]
fn test_prim() {
common::init_test();
let password = "hunter2";
... |
use anyhow::Result;
use structopt::StructOpt;
use sparktop::{
event::{Event, EventStream, Next},
sprocs::SProcs,
view::View,
};
#[derive(StructOpt)]
struct Opt {
#[structopt(short, default_value = "1.")]
delay: f64,
// weight given to new samples.
#[structopt(short, default_value = "0.5")]... |
#![feature(async_await)]
#[macro_use]
extern crate rental;
use async_std::sync::RwLock;
use async_std::{io, net};
use std::net::ToSocketAddrs;
use std::str;
use std::sync::Arc;
use async_trait::async_trait;
use path_tree::PathTree;
mod app;
mod date;
mod request;
mod response;
pub mod middleware;
pub use crate::a... |
extern {
fn ext_print_num(data: i64);
fn ext_print_utf8(offset: i32, size: i32);
fn ext_print_hex(offset: i32, size: i32);
fn ext_malloc(size: i32) -> i32;
fn ext_free(addr: i32);
fn ext_get_storage_into(key_data: i32, key_len: i32, value_data: i32, value_len: i32, value_offset: i32) -> i32;
... |
#[cfg(all(test, feature = "futures"))]
mod tests {
use futures::future::{empty, err, ok, Future};
use inspector::FutureInspector;
#[test]
fn future_not_ready() {
let mut inspect_called = false;
let f = empty::<(), ()>();
let _ = f.inspect_err(|_| inspect_called = true).poll();... |
//! Linux-specific things for Heim disk data collection.
use heim::disk::Partition;
pub fn get_device_name(partition: &Partition) -> String {
if let Some(device) = partition.device() {
// See if this disk is actually mounted elsewhere on Linux...
// This is a workaround to properly map I/O in some... |
#![allow(
clippy::from_iter_instead_of_collect, // I like calling from_iter, damnit.
)]
use std::{convert::TryInto, iter::FromIterator, num::NonZeroU64, ops::Not};
use flac_rs::{
encoder::Block,
frame::Subblock,
headers::{
BitsPerSample, BlockSize, ChannelCount, FrameSize, MetadataBlockStreamI... |
use divisors;
use std::time::{Instant};
fn main() {
let n: u128 = 934832147123321;
println!("finding divisors of {}", n);
let start_time = Instant::now();
let v = divisors::get_divisors(n);
println!("time = {:?}, divisors = {:?}", start_time.elapsed(), v);
}
|
pub mod parser;
pub mod runtime;
pub mod tokenizer;
#[cfg(test)]
mod tests {
use expr_eval::{evaluator::Environment, val::Val};
use crate::{parser::parse, runtime, tokenizer::tokenize};
#[test]
fn while_loop() {
let mut env = Environment::new();
let code =
"a=0
while ... |
use std::collections::HashMap;
use bson::{doc, from_document, Bson};
use futures::TryStreamExt;
use semver::VersionReq;
use serde::{Deserialize, Deserializer};
use crate::{
bson::Document,
options::{FindOptions, ReadPreference, SelectionCriteria, SessionOptions},
test::{
log_uncaptured,
sp... |
//!
//! Support to register a [`GbmDevice`](GbmDevice)
//! to an open [`Session`](::backend::session::Session).
//!
use drm::control::{crtc, Device as ControlDevice, ResourceInfo};
use gbm::BufferObject;
use std::cell::RefCell;
use std::collections::HashMap;
use std::os::unix::io::RawFd;
use std::rc::{Rc, Weak};
use ... |
use serenity::prelude::*;
use serenity::model::channel::Message;
use serenity::framework::standard::{
CommandResult,
macros::{
command,
group
}
};
group!({
name: "general",
// options: {
// default_command: hello
// },
commands: [restart, test, ping,... |
use super::error::Result;
use duktape::prelude::*;
use duktape::types::{FromDuktape, ToDuktape};
use duktape::{
error::Error as DukError, error::ErrorKind as DukErrorKind, error::Result as DukResult,
};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use url::Url;
use uuid::Uuid;
#[derive(Debug, Serialize, Des... |
// SPDX-License-Identifier: Apache-2.0
#![deny(clippy::all)]
pub struct Start;
/// A trait containing the function used to enter a keep
pub trait Keep<T> {
/// Enter the keep with the provided input until the next event
fn enter(self: Box<Self>, input: T) -> std::io::Result<Event>;
}
/// All possible keep e... |
use crate::errors::ApiError;
use crate::models::duels::*;
use crate::schema::duels::dsl::{
duels as table_duels, id as col_id, player_1 as col_player_1,
player_2 as col_player_2,
};
use crate::DbConn;
use diesel::prelude::*;
use rocket_contrib::json::{Json, JsonValue};
fn get_duel_id(
new_duel: &NewDuel,
... |
use crate::{FilePos, Span};
use std::collections::HashMap;
// pub fn _init_line_info(global_context: &mut OldContext) -> LineInfoContext {
// let file_pos = FilePos::new();
// let _line_info_list: Vec<usize> = Vec::with_capacity(200);
// let mut context = LineInfoContext::new();
// let li = LineInfo::start_lin... |
//! Defines data structures describing chess moves.
use std::fmt;
use board::*;
/// `MOVE_ENPASSANT`, `MOVE_PROMOTION`, `MOVE_CASTLING`, or `MOVE_NORMAL`.
pub type MoveType = usize;
pub const MOVE_ENPASSANT: MoveType = 0;
pub const MOVE_PROMOTION: MoveType = 1;
pub const MOVE_CASTLING: MoveType = 2;
pub const MOVE_... |
use bs58;
use clear_on_drop::ClearOnDrop;
use crc8;
use ed25519_dalek;
use failure::Error;
use rand::{RngCore};
use sha2;
use std::fmt;
use std::str::FromStr;
#[derive(Debug, Fail)]
pub enum IdentityError {
#[fail(display = "invalid address: length")]
InvalidLen,
#[fail(display = "invalid address")]
I... |
use bc::mem::Mem;
use bc::BlockChain;
use bc::block::*;
use proto::*;
#[test]
fn block_new() {
let b = Block::new(
0,
String::from("id"),
String::from("key"),
String::from("value"),
String::from("prev_hash"),
);
assert_eq!(b.idx, 0);
assert_eq!(b.id, String::from... |
//! Defines the metric length standards as newtypes
use core::{self, fmt};
use length::imperial::*;
use length::astronomical::*;
use composite::UnitName;
/// A newtype that wraps around `f64` and provides convenience functions for unit-aware and type-safe manipulation.
#[derive(Clone, Copy)]
pub struct Meter(pub f6... |
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use rand::{Rng, StdRng};
use error::{Error, Result};
use maze::{Coord, Direction, Maze, Wall};
#[derive(Debug, Clone, Copy)]
pub enum GeneratorType {
DFS,
Kruskal,
Prim,
Eller,
HuntKill,
}
impl GeneratorType {
/// A list of pos... |
mod hextable;
use hextable::hextable;
use std::str::from_utf8;
pub fn encode(inp: String) -> String {
let byt: Vec<u8> = inp.into_bytes();
let mut outbytes: Vec<u8> = vec![];
for b in byt{
match b {
0x20|48..=57|65..=89|97..=122 => outbytes.push(b),
b'%' => {
... |
pub const ROM_START: u16 = 0x0000;
pub const ROM_END: u16 = 0x1fff;
pub const WRAM_START: u16 = 0x2000;
pub const WRAM_END: u16 = 0x23ff;
pub const VRAM_START: u16 = 0x2400;
pub const VRAM_END: u16 = 0x3fff;
//pub const RAM_MIRROR_START: u16 = 0x4000;
|
use std::iter::from_fn;
fn digits_inc_or_same(num: u32) -> bool {
let mut it = rev_digit_iter(num);
let mut lastd = it.next().unwrap();
for d in it {
if lastd < d {
return false;
}
lastd = d;
}
true
}
fn adjacent_digits_same(num: u32) -> bool {
let mut it = ... |
/// given index 'n' and a cache, recursively generate fibonacci numbers, caching the results
pub fn fib(n: usize, cache: &mut Vec<u64>) -> Result<u64, String> {
// using the magic of match to handle the initial conditions,
// and then recursion to handle the rest.
if let Some(result) = cache.get(n) {
... |
use std::fs;
fn parse(input: String) -> Vec<Vec<char>> {
input
.lines()
.map(|x| x.chars().collect())
.collect()
}
fn pos(y: usize, x: usize, input: &Vec<Vec<char>>) -> Option<char> {
// we start with x = 0. y = 0
// with x we go right infintely
// with y we go to the bottom and then retur... |
use std::thread;
//哲学家
struct Philosopher{
name:String
}
impl Philosopher {
//创建一个新的哲学家.
fn new (name:&str) -> Philosopher {
Philosopher{
name:name.to_string(),
}
}
//eat
fn eat(&self) {
println!("{},is eating!",self.name);
thread::sleep_ms(1000);
println!("{},is done eating!",self... |
//! Initialize variables at runtime which then behave like static variables.
//!
//! ```rust
//! extern crate late_static;
//! use late_static::LateStatic;
//!
//! struct Foo {
//! pub value: u32,
//! }
//!
//! static FOO: LateStatic<Foo> = LateStatic::new();
//!
//! fn main() {
//! unsafe {
//! LateSta... |
//! # PubNub Hyper
//!
//! A PubNub client using [`hyper`](hyper) and [`tokio`](tokio) to provide an
//! ultra-fast, incredibly reliable message transport over the PubNub edge
//! network.
//!
//! Uses [`pubnub-core`](pubnub-core) under the hood.
//!
//! # Example
//!
//! ```no_run
//! use futures_util::stream::StreamE... |
use std::collections::BTreeMap;
use std::io::BufRead;
fn main() {
let mut counts = BTreeMap::new();
let stdin = std::io::stdin();
for line_or_error in stdin.lock().lines() {
let line = line_or_error.unwrap();
*counts.entry(line).or_insert(0);
}
for (line, count) in counts.iter() ... |
use nom::{
branch::alt,
bytes::complete::{is_a, tag, take_while1, take_while_m_n},
combinator::{map_res, peek},
sequence::preceded,
IResult,
};
use crate::grammar::ast::NumLit;
use crate::grammar::ast::{eq::AstEq, Expression};
use crate::grammar::model::{HasSourceReference, WrightInput};
use crate... |
//! Labels interface
extern crate serde_json;
use self::super::{Github, Result};
pub struct Labels<'a> {
github: &'a Github,
owner: String,
repo: String,
}
impl<'a> Labels<'a> {
#[doc(hidden)]
pub fn new<O, R>(github: &'a Github, owner: O, repo: R) -> Labels<'a>
where
O: Into<String>... |
use backoff::backoff::Backoff;
use backoff::ExponentialBackoff;
use libp2p::PeerId;
use lru::LruCache;
use std::num::NonZeroUsize;
use std::ops::Add;
use std::time::Instant;
/// Details about temporary ban, used to track lifecycle of retries
#[derive(Debug)]
struct TemporaryBan {
backoff: ExponentialBackoff,
n... |
pub fn immutable_vars(){
let name = "Igor";
let age = 23;
println!("My name is {} I am {} years old",name,age);
}
pub fn mutable_vars(){
let name = "Igor";
let mut age = 23;
println!("My name is {} I am {} years old",name,age);
age = 24;
println!("Next year i will be {} years ... |
/*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com>
All rights reserved.
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 condit... |
mod direct;
mod rmux;
mod routine;
//mod ws;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
pub use self::routine::routine_channels;
pub trait ChannelStream {
fn split(
&mut self,
) -> (
Box<dyn AsyncRead + Send + Unpin + '_>,
Box<dyn AsyncWrite + Send + Unpin + '_>,
);
... |
use std::env;
fn main() {
let mut args = env::args();
if args.len() != 2 {
eprint!("Usage: 9cc <code>\n");
return;
}
print!(".intel_syntax noprefix\n");
print!(".global main\n");
print!("main:\n");
print!(" mov rax, {}\n", args.nth(1).unwrap());
print!(" ret\n");
r... |
fn rot_matrix(v: &Vec<(usize, usize)>) -> Vec<(usize, usize)> {
let mut v_p = Vec::new();
let (x_ubound, y_ubound) = get_bounds(v);
for &(x, y) in v.iter() {
let x_p = y;
let y_p = x_ubound - x;
v_p.push((x_p, y_p));
}
v_p
}
fn get_bounds(v: &Vec<(usize, usize)>) -> (usiz... |
extern crate opencv;
extern crate time;
use self::opencv::core;
use self::opencv::highgui;
use self::opencv::imgproc;
pub struct Camera {
pub cam: highgui::VideoCapture,
//pub red2_lower: core::Scalar,
//pub red2_upper: core::Scalar,
pub red_lower: core::Scalar,
pub red_upper: core::Scalar,
... |
use std::io;
fn get_line() -> String {
let mut out = String::new();
let stdin = io::stdin();
stdin.read_line(&mut out).unwrap();
out
}
fn main() {
let input = get_line();
let mut floor: i32 = 0;
for letter in input.as_str().chars() {
if letter == '(' {
floor = floor + 1... |
use std::fmt;
use super::{Condition, debug_predicates};
#[derive(PartialEq, Clone)]
pub struct SelectQuery<T: fmt::Debug> {
pub table_name: String,
pub columns: Vec<T>,
pub predicates: Option<Condition>
}
impl <T: fmt::Debug> SelectQuery<T> {
pub fn new<I: Into<String>>(table_name: I, columns: Vec<T>... |
use crate::errors::ResT;
use crate::hbs::{PrjCreateData, PmvdData};
use reqwest::{Client, RequestBuilder, StatusCode};
use handlebars::Handlebars;
use xml::escape::escape_str_attribute;
use std::time::Duration;
use std::io::{Error, ErrorKind};
pub fn get_client() -> ResT<Client> {
Ok(Client::builder()
.ti... |
extern crate skim;
use skim::prelude::*;
use std::io::Cursor;
/// `nth` option is supported by SkimItemReader.
/// In the example below, with `nth=2` set, only `123` could be matched.
pub fn main() {
let input = "foo 123";
let options = SkimOptionsBuilder::default().query(Some("f")).build().unwrap();
let... |
#![cfg_attr(feature = "cargo-clippy", allow(clippy::field_reassign_with_default))]
#![recursion_limit = "128"]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate more_asserts;
#[macro_use]
mod common;
mod test_code_search;
mod test_phrase;
mod test_query_generator... |
extern crate log;
extern crate bitflags;
extern crate rust_embed;
pub mod analysis;
pub mod arch;
pub mod basicblock;
pub mod flowmeta;
pub mod loader;
pub mod loaders;
pub mod util;
pub mod workspace;
pub mod xref;
pub mod pagemap;
pub use basicblock::BasicBlock;
pub use xref::Xref;
pub use workspace::Workspace;
//... |
#[derive(Copy, Clone, FromPrimitive, Hash, PartialEq, Eq, Debug)]
pub enum Operator {
Add,
RAdd,
Subtract,
RSubtract,
USubtract,
Multiply,
RMultiply,
Divide,
RDivide,
FloorDiv,
RFloorDiv,
Power,
RPower,
Equals,
REquals,
NotEquals,
RNotEquals,
Great... |
//! Network channels
use crate::jsonrpc;
use std::fmt::{self, Display};
/// Individual network channel (from `/net_info`)
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Channel {
/// Channel ID
#[serde(rename = "ID")]
pub id: Id,
/// Capacity of the send queue
#[serde(
rename ... |
use num::integer::{binomial, div_ceil, gcd, mod_floor, Integer, Roots};
fn main() {
// 整数平方根 √target-1 < ans <= √target < ans+1
println!("{}, {}, {}", 24.sqrt(), 25.sqrt(), 26.sqrt());
// 最大公約数
println!("{}", gcd(24, 36));
// 必ず非負のmod
println!("{} {}", (-34i64).rem_euclid(7), mod_floor(-34, 7... |
use crate::inputs::Cursor;
use crate::util::{
AnchorEdge, Bezier, BoundingBoxQuad, ControlPointQuad, EndpointQuad, FollowBezierAnimation,
Globals, GrandParent, Group, GroupMiddleQuad, MiddlePointQuad, MyShader, TurnRoundAnimation,
UiAction, UiBoard,
};
use bevy::prelude::*;
pub fn move_ui(
cursor: Res... |
use super::{BoltStructure, Single, Value};
use crate::{
constants::STRUCTURE_NAME,
error::{SerdeError, SerdeResult},
};
use serde::{
de, forward_to_deserialize_any,
ser::{self, SerializeTupleStruct},
};
use std::{collections::HashMap, fmt};
#[derive(Debug, PartialEq)]
pub struct Success {
pub metad... |
use std::{cell::RefCell, rc::Rc};
use crate::sqlite::{
sqlite_resource_pool::{db_pool::SqliteDatabasePool, tx_pool::SqliteTxPool},
transaction::sqlite_tx::SqliteTx,
};
use apllodb_shared_components::SessionId;
use apllodb_storage_engine_interface::WithDbMethods;
use futures::FutureExt;
use super::BoxFutRes;
... |
/*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com>
All rights reserved.
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 condit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.