text stringlengths 8 4.13M |
|---|
use crate::ast::{Expr, Stmt};
use super::{
value::{Function, Value},
Interpreter, StmtResult,
};
impl Interpreter {
pub fn eval_stmt(&mut self, stmt: &Stmt) -> StmtResult {
match stmt {
Stmt::FnDef {
ident,
params,
body,
... |
use nb;
use core::{num::Wrapping};
use cortex_m::peripheral::{syst::SystClkSource, SYST};
//use crate::pmc::PMC;
//use cortex_m::peripheral::syst;
//pub use sam3x8e as target;
// https://doc.rust-lang.org/stable/rust-by-example/trait.html
// https://github.com/stm32-rs/stm32f4xx-hal/blob/master/src/timer.rs
// https:... |
use super::super::TextureTable;
use super::util;
use crate::arena::{block, resource, BlockRef};
use crate::libs::random_id::U128Id;
use crate::libs::three;
use std::collections::{HashMap, HashSet};
use wasm_bindgen::JsCast;
pub struct Boxblock {
meshs: HashMap<U128Id, Mesh>,
geometry: Geometry,
geometry_na... |
#![allow(clippy::let_unit_value)]
use super::database::ingredient::ingredient_info;
use oikos_api::models::components::schemas::*;
use serde::{Deserialize, Serialize};
use uniqdb::{
github::{GithubDb, GithubDbError},
UniqDb,
};
#[derive(Debug, thiserror::Error)]
pub enum RecipeError {
#[error("recipe with ... |
/* tshat - chat server for ssh clients
* Copyright 2021 Laurent Ghigonis <ooookiwi@gmail.com> */
extern crate thrussh;
extern crate thrussh_keys;
extern crate thrussh_libsodium;
extern crate futures;
extern crate tokio;
extern crate anyhow;
extern crate chrono;
extern crate clap;
extern crate regex;
extern crate fork... |
mod editor;
mod env_editor;
|
use std::{thread, time};
use std::io::{self, Write};
trait Printable {
fn set_printer_name(&mut self, name: String);
fn get_printer_name(&self) -> String;
fn print(&mut self, string: String);
}
struct Printer {
name: String,
}
impl Printer {
fn new(name: String) -> Printer {
Printer::heab... |
#[doc = "Register `GTZC1_TZIC_IER3` reader"]
pub type R = crate::R<GTZC1_TZIC_IER3_SPEC>;
#[doc = "Register `GTZC1_TZIC_IER3` writer"]
pub type W = crate::W<GTZC1_TZIC_IER3_SPEC>;
#[doc = "Field `LPTIM6IE` reader - illegal access interrupt enable for LPTIM6"]
pub type LPTIM6IE_R = crate::BitReader;
#[doc = "Field `LPTI... |
#[doc = "Register `HWCFGR1` reader"]
pub type R = crate::R<HWCFGR1_SPEC>;
#[doc = "Register `HWCFGR1` writer"]
pub type W = crate::W<HWCFGR1_SPEC>;
#[doc = "Field `CFG1` reader - LUART hardware configuration 1"]
pub type CFG1_R = crate::FieldReader;
#[doc = "Field `CFG1` writer - LUART hardware configuration 1"]
pub ty... |
// This file is part of dpdk. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/dpdk/master/COPYRIGHT. No part of dpdk, including this file, may be copied, modified, propagated, or distributed except accordin... |
#![no_std]
#![no_main]
extern crate memdmp;
#[no_mangle]
pub unsafe extern fn wmain(_argc: isize, _argv: *const *const u16) -> isize {
memdmp::shellcode()
}
|
// 一个包含资源的结构体,它实现了 `Clone` trait
#[derive(Clone, Debug)]
struct Pair(Box<i32>, Box<i32>);
// 定义一个不含资源的单元结构体Nil
#[derive(Debug, Clone, Copy, PartialEq)]
struct Nil;
fn main() {
copy();
move_pair();
clone();
}
/* 变量复制
*/
fn copy() {
// 初始化结构体变量
let x = Nil;
// 复制变量x到y(没有发生移动)
let y = x;
... |
#![allow(missing_docs)]
use byteorder::{BigEndian, ByteOrder, ReadBytesExt};
use bytes::{Bytes, BytesMut};
use fallible_iterator::FallibleIterator;
use memchr::memchr;
use std::cmp;
use std::io::{self, Read};
use std::ops::Range;
use std::str;
use crate::{Lsn, Oid};
// top-level message tags
pub const PARSE_COMPLETE... |
//! Helpers for IO related tasks.
//!
//! These types are often used in combination with hyper or reqwest, as they
//! allow converting between a hyper [`Body`] and [`AsyncRead`].
//!
//! [`Body`]: https://docs.rs/hyper/0.13/hyper/struct.Body.html
//! [`AsyncRead`]: tokio::io::AsyncRead
mod read_buf;
mod reader_stream... |
use pnet::datalink::{self, NetworkInterface};
use pnet::datalink::Channel;
// TODO: set Config.channel_type = Layer3
pub fn get_connection(interface: &NetworkInterface) -> Channel {
match datalink::channel(&interface, Default::default()) {
Ok(ether) => ether,
Err(e) => {
panic!(
... |
struct Solution;
impl Solution {
pub fn num_trees(n: i32) -> i32 {
let n = n as usize;
let mut g = vec![0; n + 1];
g[0] = 1;
g[1] = 1;
for i in 2..=n {
// G[i]
for j in 1..=i {
// j 是根
g[i] += g[j - 1] * g[i - j];
... |
//! Module for database interaction with relation to login
use crate::env::Env;
use rusqlite::named_params;
use crate::api::oauth::LoginData;
use crate::{Result, unwrap_db_err};
/// Save login data to the database
///
/// ## Errors
/// - When a database operation fails
pub fn save_to_database(login_data: &... |
//! The `bank` module tracks client accounts and the progress of smart
//! contracts. It offers a high-level API that signs transactions
//! on behalf of the caller, and a low-level API for when they have
//! already been signed and verified.
use bincode::deserialize;
use bincode::serialize;
use budget_program::Budget... |
mod commands;
#[cfg_attr(test, macro_use)]
mod db;
mod model;
mod server;
mod snek;
use serenity::framework::standard::StandardFramework;
use serenity::prelude::*;
use simplelog::{Config, LogLevelFilter, SimpleLogger};
use failure::*;
use log::*;
use std::env;
use std::fs::File;
use std::io::Read;
use std::sync::Arc;... |
use nom::IResult;
use nom::be_u32;
use nom::be_u64;
pub const HEADER_MAGIC: [u8;4] = [0xd0, 0x0d, 0xfe, 0xed];
pub const VERSION: u32 = 17;
pub const LAST_COMP_VERSION: u32 = 16;
#[derive(Debug,PartialEq,Eq,Copy,Clone)]
pub struct Header {
pub magic: [u8;4],
pub totalsize: u32,
pub off_dt_struct: u32,
... |
//! Compilers should really have intrinsics for making system calls. They're
//! much like regular calls, with custom calling conventions, and calling
//! conventions are otherwise the compiler's job. But for now, use inline asm.
//!
//! # Safety
//!
//! This contains the `asm` statements performing the syscall instruc... |
use crate::registry::Registry;
#[derive(Copy, Clone, Debug)]
pub struct Link {
hash: u128,
}
pub struct Depot<'registry> {
registry: &'registry Registry,
}
impl<'registry> Depot<'registry> {
pub fn new(registry: &'registry Registry) -> Self {
Self { registry }
}
}
|
#[doc = "Register `IMR` reader"]
pub type R = crate::R<IMR_SPEC>;
#[doc = "Register `IMR` writer"]
pub type W = crate::W<IMR_SPEC>;
#[doc = "Field `TXISIE` reader - TXIS interrupt enable"]
pub type TXISIE_R = crate::BitReader;
#[doc = "Field `TXISIE` writer - TXIS interrupt enable"]
pub type TXISIE_W<'a, REG, const O: ... |
//! Types for handling errors in reading.
use lex;
use parse;
use parse::expr::Expr;
use std::error;
use std::fmt;
use std::result;
/// The result of reading a string.
pub type Result = result::Result<Expr, Error>;
/// Indicates an error in lexing or parsing.
#[derive(Debug, PartialEq)]
pub enum Error {
/// Indi... |
use std::io::stdin;
fn main() {
print!("Type any string: ");
let mut line = String::new();
stdin().read_line(&mut line).unwrap();
let input = line[..].trim();
println!("{}", input.chars().next_back().unwrap());
}
|
use std::collections::BinaryHeap;
use crate::{
components::{EntityComponent, TerrainComponent},
indices::RoomPosition,
prelude::{Axial, Hexagon, View},
profile,
tables::hex_grid::HexGrid,
};
use tracing::{debug, trace};
use super::{is_walkable, Node, PathFindingError};
const VISITED_FROM: u8 = 1 ... |
mod blockchain;
mod block;
mod map;
pub use block::{Block, create_block};
pub use blockchain::{Blockchain, create_blockchain};
use std::time::Instant;
fn main() {
let mut n: u64 = 1;
let mut b_chain = create_blockchain();
b_chain.add_first_block();
loop {
let now = Instant::now();
... |
fn main() {
sudo_rs::sudo_main();
}
|
use std::fs::{File, OpenOptions};
use std::io;
use std::io::BufWriter;
use std::io::Write as IoWrite;
use std::path::PathBuf;
#[derive(Debug)]
pub struct FileWriter {
/// The path to the logging file.
path: PathBuf,
writer: BufWriter<File>,
}
impl FileWriter {
pub fn new(path: PathBuf) -> FileWriter {... |
use crate::persistence::{Persistence, PersistenceError, PersistenceResult, SqliteFactory};
use crate::tokens::DatabaseAddress;
use actix::prelude::*;
use crossbeam_channel::Sender;
use futures::FutureExt;
use log::debug;
use rusqlite::InterruptHandle;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std:... |
use std::rc::Rc;
pub use crate::globalstate::GlobalState;
pub use crate::instructions::Instruction;
pub use crate::configuration::Configuration;
//an instruction object which contains all protential instructions for a given function and their rate of occurance
pub struct InstructionObject {
pub probable_ops: Ve... |
// #![allow(unused)]
use std::io::BufReader;
use std::io::prelude::*;
use std::fs::File;
// Exo1
// fn main() {
// let values = values();
// for (i, value) in values[25..].iter().enumerate() {
// let window = &values[i..i + 25];
// if sum_in(window, value) == false {
// println!("re... |
use actix::prelude::*;
use chrono;
use diesel;
use diesel::prelude::*;
use uuid;
use crate::db::schema::report;
#[derive(Debug, Insertable, Queryable, Clone)]
#[table_name = "report"]
pub struct ReportDb {
pub id: String,
name: String,
folder: String,
created_on: chrono::NaiveDateTime,
last_update:... |
use std::sync::Arc;
use std::cell::RefCell;
fn main() {
let mut x = 1;
foo(x);
}
fn foo(mut x : i32)
{
x= 1;
println!("{}", x);
}
fn Interior()
{
let x = Arc::new(5);
let y = x.clone();
}
fn Exterior()
{
let x = RefCell::new(42);
let y = x.borrow_mut();
let z = x.borrow_mu... |
use std::fmt;
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.height > other.height && self.width > other.width
}
}
impl fmt::Display for Rectangle {
fn f... |
pub mod ex01_1;
pub mod ex01_2;
pub mod ex01_3;
|
use anyhow::Result;
use clap::ArgMatches;
use colored::*;
use std::path::PathBuf;
use crate::cfg::Cfg;
use crate::cli::cfg::get_cfg;
use crate::cli::commands::sync::{sync_workflow, SyncSettings};
use crate::cli::error::CliError;
use crate::cli::settings::get_settings;
use crate::cli::terminal::message::success;
use cr... |
#![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)]
AppServiceEnvironments_List(#[from] a... |
use fnd::*;
#[cfg(target_env = "msvc")]
#[link(name = "libcmt")]
extern "C" {
fn exit(status: i32) -> !;
}
#[cfg(not(test))]
#[panic_handler]
fn panic(info: &core::panic::PanicInfo) -> !
{
println!("{}", info);
unsafe {
exit(1);
}
}
#[cfg(not(test))]
#[lang = "eh_personality"]
extern "C" fn r... |
#[doc = "Register `AWD3TR` reader"]
pub type R = crate::R<AWD3TR_SPEC>;
#[doc = "Register `AWD3TR` writer"]
pub type W = crate::W<AWD3TR_SPEC>;
#[doc = "Field `LT3` reader - Analog watchdog 3lower threshold These bits are written by software to define the lower threshold for the analog watchdog. Refer to ADC_AWDxTR) on... |
use std::collections::{HashMap, HashSet};
/*
I tried to implement StructOpt here but decided against it
// use structopt::StructOpt;
// Providing a command line argument to switch between the exact
// and approximated calculation of the Busy time period
#[derive(Debug, StructOpt)]
struct ExC... |
#![allow(non_upper_case_globals)]
use regex::bytes::Regex;
use crate::compiler::error::{Error, Result};
lazy_static! {
static ref re_integer: Regex = Regex::new(r#"^[+-]?[0-9]+$|^-?0x[0-9a-f]+$"#).unwrap();
static ref re_hex_float: Regex = Regex::new(r#"^([0-9a-f]+(\.[0-9a-f]*)?|([0-9a-f]*\.[0-9a-f]+... |
use super::razer_report::{Color, RazerMouseMatrixEffectId, RazerReport, RazerVarstore};
use super::{Device, DeviceFactory};
use errors::Result;
use hidapi::HidDevice;
#[derive(Clone, Debug)]
pub struct MatrixMiceFactory {
name: &'static str,
led_ids: &'static [u8],
}
impl MatrixMiceFactory {
pub fn new(na... |
mod bft_orswot;
mod bft_orswot_net;
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - SYSCFG configuration register 1"]
pub cfgr1: CFGR1,
_reserved1: [u8; 0x14],
#[doc = "0x18 - SYSCFG configuration register 1"]
pub cfgr2: CFGR2,
}
#[doc = "CFGR1 (rw) register accessor: SYSCFG configuration register 1\n\... |
use std::collections::HashMap;
use serde::{Serialize,Deserialize};
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleFirestoreAdminv1IndexField {
#[serde(rename="fieldPath")]
pub field_path: Option<String>,
pub mode: Option<String>,
}
#[derive(Default, Clone, Debug, Serialize, D... |
extern crate cascading_ui;
extern crate wasm_bindgen_test;
use self::{
cascading_ui::{test_header, test_setup},
wasm_bindgen_test::wasm_bindgen_test,
};
test_header!();
#[wasm_bindgen_test]
fn dynamic() {
test_setup! {
text: "click me";
.a {
?click {
text: "I've been clicked!";
b {
text: "hello... |
use thiserror::Error;
#[derive(Error, Debug)]
pub enum LibVoponoError {
#[error("failed to add NetFilter rule")]
NetFilterError(String),
}
|
use super::{
account::{AccountRole, AccountType},
check, get_user_by_name, rand_str, Account, UserContext,
};
use crate::{config, Server};
use anyhow::anyhow;
use anyhow::bail;
use chrono::Local;
use ldap3::{LdapConnAsync, Scope, SearchEntry};
use log::{info, warn};
use spa_server::re_export::{
error::{Erro... |
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// 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... |
//! This module provides capabilities for managing a cache of rendered glyphs in
//! GPU memory, with the goal of minimisng the size and frequency of glyph
//! uploads to GPU memory from the CPU.
//!
//! This module is optional, and not compiled by default. To use it enable the
//! `gpu_cache` feature in your Cargo.tom... |
use dirs::home_dir;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result;
use std::path::PathBuf;
const CHAIN: [&str; 3] = [
"/Library/Sounds/",
"/Network/Library/Sounds/",
"/System/Library/Sounds/",
];
#[derive(Clone, Copy, Debug)]
pub enum Sound {
Default,
Basso,
Blow,
Bottle,
Frog,
... |
use std::fs;
use std::io::Read;
use std::path::PathBuf;
use structopt::clap::arg_enum;
use structopt::StructOpt;
use eyre::Result as AResult;
arg_enum! {
#[derive(Debug)]
enum OutputFormat {
Json,
Debug,
}
}
#[derive(Debug, StructOpt)]
#[structopt(
name = "vim-swapfile-header",
about = "Reads vim sw... |
pub mod camera;
pub mod model;
|
/*!
* Perseus is a blazingly fast frontend web development framework built in Rust with support for major rendering strategies,
* reactivity without a virtual DOM, and extreme customizability. It wraps the lower-level capabilities of [Sycamore](https://github.com/sycamore-rs/sycamore)
* and provides a NextJS-like AP... |
use crate::interpreter::HeaderFlag::PrimSelf;
use crate::objectmemory::{ObjectLayout, ObjectMemory, UWord, Word, CANNOT_RETURN_SEL, CHARACTER_TABLE_PTR, CLASS_ARRAY_PTR, CLASS_BLOCK_CONTEXT_PTR, CLASS_CHARACTER_PTR, CLASS_LARGE_POSITIVEINTEGER_PTR, CLASS_MESSAGE_PTR, CLASS_METHOD_CONTEXT_PTR, CLASS_POINT_PTR, CLASS_STR... |
//! Various tools and techniques for working with expressions
pub mod rpn;
pub mod shunting_yard;
|
use super::stream::Record;
use crate::common;
use crate::common::types::Value;
use json;
use ordered_float::OrderedFloat;
use regex::Regex;
use url;
use json::JsonValue;
use linked_hash_map::LinkedHashMap;
use std::fmt;
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::path::Path;
use std::result;
use std... |
#![macro_use]
use std::cell::{Ref, RefCell, RefMut};
use std::clone::Clone;
use std::iter::Peekable;
use std::rc::Rc;
macro_rules! log_debug {
($fmt:expr) => (
#[cfg(debug_assertions)]
println!($fmt));
($fmt:expr, $($arg:tt)*) => (
#[cfg(debug_assertions)]
println!($fmt, $($arg... |
//! Connect to or provide Fuchsia services.
// Copyright 2017 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.
#![deny(warnings)]
#![deny(missing_docs)]
extern crate fuchsia_async as async;
extern crate fuchsia_zircon as... |
// implements the background segmentation video submodule
pub struct BackgroundSegmenter {
// previous frame
// probability map
}
impl BackgroundSegmenter {
pub fn update(self/*Image*/) {
}
pub fn get_probability_map(self) /*-> image*/ {
}
} |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - GPIO port mode register"]
pub gpiog_moder: GPIOG_MODER,
#[doc = "0x04 - GPIO port output type register"]
pub gpiog_otyper: GPIOG_OTYPER,
#[doc = "0x08 - GPIO port output speed register"]
pub gpiog_ospeedr: GPIOG_OSP... |
#[derive(Clone, Copy)]
struct Point { x: i32, y: i32 }
fn main() {
let c = 'Q';
let ref ref_c1 = c;
let ref_c2 = &c;
println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2);
let point = Point = { x: 0, y: 0 };
let _copy_of_x = {
let Point { x: ref ref_to_x, y: _ }
};
}
|
use nalgebra_glm::Vec3;
use nalgebra_glm::Vec4;
#[derive(Debug, Clone)]
pub enum Light {
Point(PointLight),
}
#[derive(Debug, Clone)]
pub struct PointLight {
pub position: Vec4,
pub color: Vec3,
pub radius: f32,
}
impl PointLight {
pub fn new(position: Vec4, color: Vec3, radius: f32) -> Self {
... |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use crate::field::FieldElement;
use utils::{batch_iter_mut, collections::Vec, iter_mut, uninit_vector};
#[cfg(feature = "concurrent")]
us... |
#[macro_use] extern crate itertools;
use intcode;
use cjp_threadpool::ThreadPool;
const TARGET: i64 = 19_690_720;
fn main() {
let start_time = std::time::Instant::now();
let mut memory = intcode::load_program("day2/input.txt").unwrap_or_else(|err| {
println!("Could not load input file!\n{:?}", er... |
use super::super::ascii85::decode;
use anyhow::{anyhow, ensure, Result};
use std::convert::TryInto;
use std::net::Ipv4Addr;
fn read_as_u16(bytes: &[u8]) -> Result<Vec<u16>> {
let words = bytes
.chunks_exact(2)
.map(|chunk| {
let word: Result<[u8; 2]> = chunk
.try_into()
... |
use std::ops::{Add, Sub};
#[derive(Debug)]
pub enum Error {
SideTooShort,
TriangleInequality,
}
pub struct Triangle<T> {
sides: [T; 3],
}
// I wanted to try satisfying the optional tests without using any crates or creating separate
// impls for each numeric type, so this is a bit wonky.
//
// Any type T... |
extern crate libc;
use libc::c_char;
use std::ffi::{CString, CStr};
use std::env;
use std::time::Instant;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::atomic::{AtomicBool, Ordering};
use std::io::{BufReader, BufRead, Error, ErrorKind};
use std::fs::{... |
use amethyst::ecs::Entity;
use crate::config::MapConfig;
#[derive(Default)]
pub struct Map {
width: usize,
height: usize,
tile_size: usize,
tiles: Vec<Entity>
}
impl Map {
pub fn new(config: &MapConfig) -> Self {
Map {
width: config.width,
height: config.height,
... |
const INPUT: &str = "1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,10,1,19,1,6,19,23,2,23,6,27,1,5,27,31,1,31,9,35,2,10,35,39,1,5,39,43,2,43,10,47,1,47,6,51,2,51,6,55,2,55,13,59,2,6,59,63,1,63,5,67,1,6,67,71,2,71,9,75,1,6,75,79,2,13,79,83,1,9,83,87,1,87,13,91,2,91,10,95,1,6,95,99,1,99,13,103,1,13,103,107,2,107,10,111,1,9,111,115,1... |
// Problem 20 - Factorial digit sum
//
// n! means n x (n - 1) x ... x 3 x 2 x 1
//
// For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
// and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
//
// Find the sum of the digits in the number 100!
fn main() {
println!("{}", solution());... |
#[doc = "Reader of register ISACTIVER0"]
pub type R = crate::R<u32, super::ISACTIVER0>;
#[doc = "Writer for register ISACTIVER0"]
pub type W = crate::W<u32, super::ISACTIVER0>;
#[doc = "Register ISACTIVER0 `reset()`'s with value 0"]
impl crate::ResetValue for super::ISACTIVER0 {
type Type = u32;
#[inline(always... |
#[aoc_generator(day1)]
fn gen(input: &str) -> Vec<i32> {
input.lines()
.map(|line| line.parse().unwrap())
.collect()
}
#[aoc(day1, part1)]
fn part1(input: &Vec<i32>) -> i32 {
input.iter()
.map(|n| n / 3 - 2)
.sum()
}
#[aoc(day1, part2)]
fn part2(input: &Vec<i32>) -> i32 {
i... |
// Problem 42 - Coded triangle numbers
//
// The n-th term of the sequence of triangle numbers is given by, t(n) = ½n(n+1);
// so the first ten triangle numbers are:
//
// 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
//
// By converting each letter in a word to a number corresponding to its
// alphabetical position... |
use rlimit::{setrlimit, Resource};
use cgroups_rs::{MaxValue, CgroupPid};
use cgroups_rs::hierarchies::V2;
use cgroups_rs::cgroup_builder::CgroupBuilder;
use nix::unistd::Pid;
use std::convert::TryInto;
use std::fs::{canonicalize, remove_dir};
use crate::errors::Errcode;
const KMEM_LIMIT: i64 = 1024 * 1024 * 1024;
co... |
/*
搜索旋转排序数组
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
示例 1:
输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
示例 2:
输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1
*/
use crate::array::Solution;
imp... |
//! This library provides extension methods for the `Default` trait.
//!
//! ## Example
//! case1:
//! ```
//! # use default_ext::DefaultExt;
//! assert!(false.is_default());
//! ```
//!
//! case2:
//! ```ignore
//! #[derive(serde::Serialize, serde::Deserialize)]
//! struct Object {
//! #[serde(
//! default,
... |
#[doc = "Register `BDTR` reader"]
pub type R = crate::R<BDTR_SPEC>;
#[doc = "Register `BDTR` writer"]
pub type W = crate::W<BDTR_SPEC>;
#[doc = "Field `DTG` reader - Dead-time generator setup"]
pub type DTG_R = crate::FieldReader;
#[doc = "Field `DTG` writer - Dead-time generator setup"]
pub type DTG_W<'a, REG, const O... |
use {ContextRef, ValueRef};
cpp! {
#include "ffi_helpers.h"
#include "llvm/IR/Module.h"
pub fn LLVMRustBasicBlockCreate(context: ContextRef as "llvm::LLVMContext*")
-> ValueRef as "llvm::Value*" {
return llvm::BasicBlock::Create(*context);
}
}
|
mod debugger;
mod load_cell;
mod load_cell_data;
mod load_header;
mod load_input;
mod load_script;
mod load_script_hash;
mod load_tx;
mod load_witness;
mod utils;
pub use self::debugger::Debugger;
pub use self::load_cell::LoadCell;
pub use self::load_cell_data::LoadCellData;
pub use self::load_header::LoadHeader;
pub ... |
use futures::{Async, Future, Poll};
use std::marker::PhantomData;
use std::net::SocketAddr;
use tokio_io::{AsyncRead, AsyncWrite};
pub trait ConnectService<A> {
type Response: AsyncRead + AsyncWrite;
type Error;
type Future: Future<Item = Self::Response, Error = Self::Error>;
fn connect(&mut self, tar... |
pub fn primes_up_to(upper_bound: u64) -> Vec<u64> {
let mut iter = 1;
let mut vector_primes: Vec<u64> = (2..=upper_bound).collect();
loop {
if iter > upper_bound {
break;
} else {
iter += 1;
}
vector_primes.retain(|x| {
x % iter != 0 || *x... |
pub mod all;
pub mod andor;
pub mod exact;
pub mod factory;
pub mod fuzzy;
pub mod regexp;
mod util;
|
pub mod mylib;
use mylib::{Block, Energe};
trait Machine {
fn new() -> Self {}
fn run(&self) -> Energe {}
fn gen_block() -> Block {
let matchine = Self::new();
let energe = matchine.run();
Block::from_energe(&energe)
}
}
const ID: &'static str = "ID";
#[derive(Clone, Debug)... |
use crate::features::syntax::MiscFeature;
use crate::parse::visitor::tests::assert_misc_feature;
#[test]
fn rest_in_func_expr() {
assert_misc_feature(
"const f = function(a, ...args) {
console.log(a, args);
}",
MiscFeature::RestArguments,
);
}
#[test]
fn rest_in_generator_f... |
extern crate clap;
extern crate regex;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
mod structs;
use std::fs;
use std::io::{Read, Write};
use std::process;
use std::collections::BTreeMap;
#[cfg_attr(rustfmt, rustfmt_skip)]
static HEADER_H : &'static str = "\
//===-- InstBuild... |
/**
MSDN:
Windows Development (Windows) / Windows Application UI Development |=>
Windows and Messages / Window Classes / Window Class Reference |=>
Window Class Styles
**/
use super::super::prelude::WindowClassStyle;
pub static VerticalRedraw : WindowClassStyle = 0x0001;
pub static HorizontalRedraw : WindowCla... |
use proconio::input;
fn main() {
let mut solver = Solver::new();
println!("{}", solver.solve());
}
struct Solver {
h: isize,
w: isize,
a: isize,
b: isize,
ans: i64,
}
impl Solver {
fn new() -> Solver {
input! {
h: isize,
w: isize,
a: isize,
... |
use std::net::{Ipv4Addr, SocketAddrV4, UdpSocket};
use byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use std::thread;
use std::io;
use std::io::Cursor;
mod attributes;
#[allow(dead_code)]
enum MessageType {
Request,
Indication,
SuccessResponse,
ErrorResponse,
}
#[allow(dead_code)]
struct Mes... |
#[doc = "Register `HASH_CSR49` reader"]
pub type R = crate::R<HASH_CSR49_SPEC>;
#[doc = "Register `HASH_CSR49` writer"]
pub type W = crate::W<HASH_CSR49_SPEC>;
#[doc = "Field `CS49` reader - CS49"]
pub type CS49_R = crate::FieldReader<u32>;
#[doc = "Field `CS49` writer - CS49"]
pub type CS49_W<'a, REG, const O: u8> = c... |
#![allow(warnings)]
use std::net::{TcpListener};
use std::collections::HashMap;
use std::io::{BufReader,BufWriter};
use std::net::TcpStream;
use std::sync::{Arc,Condvar,Mutex};
use std::io::prelude::*;
use std::thread;
use std::sync::mpsc::channel;
use std::sync::mpsc::{sync_channel, SyncSender , Receiver};
use std::f... |
use crate::message_prelude::*;
use graphene::color::Color;
use crate::input::InputPreprocessor;
use crate::{
document::DocumentMessageHandler,
tool::{tool_options::ToolOptions, DocumentToolData, ToolFsmState, ToolType},
};
use std::collections::VecDeque;
#[impl_message(Message, Tool)]
#[derive(PartialEq, Clone, Deb... |
use std::fmt;
use std::fmt::Write;
use crate::strum::IntoEnumIterator;
#[derive(Debug, Clone, PartialEq)]
pub struct ApiError {
pub kind: ApiErrorKind,
pub msg: String,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ApiErrorKind {
InvalidFilter,
InvalidFilterValue,
InvalidStructure,
}
impl fmt::D... |
/* This is part of mktcb - which is under the MIT License ********************/
// Traits ---------------------------------------------------------------------
use std::io::Write;
// ----------------------------------------------------------------------------
use std::path::PathBuf;
use std::process::Command;
use sn... |
trait SpecialObject {
fn i_am_special(&self) -> &str;
}
#[derive(Debug)]
struct Object {
id: String,
value: i32
}
impl Object {
fn new(id: String, value: i32) -> Self {
Object {
id,
value
}
}
}
impl SpecialObject for Object{
fn i_am_special(&self) -> &... |
use common::result::Result;
pub trait PasswordHasher: Sync + Send {
fn hash(&self, plain_password: &str) -> Result<String>;
fn compare(&self, hashed_password: &str, plain_password: &str) -> bool;
}
|
//! Classification of bytes withing JSON quote sequences.
//!
//! Provides the [`QuoteClassifiedBlock`] struct and [`QuoteClassifiedIterator`] trait
//! that allow effectively enriching JSON inputs with quote sequence information.
//!
//! The output of quote classification is an iterator of [`QuoteClassifiedBlock`]
//!... |
mod common;
use common::Sudoku6x6;
use dancing_links::{
sudoku::{self, Sudoku},
Solver,
};
use crate::common::{format_sudoku_possibilities, parse_sudoku_possibilities};
// Basing these exact counts off of https://en.wikipedia.org/wiki/Mathematics_of_Sudoku#Sudoku_with_rectangular_regions
#[test]
#[cfg_attr(m... |
//! This module defines the function pointers for supported traits from the standard library.
//!
//! `CloneFromFn` and `DropFn` enable the use of `VecClone`.
//!
//! The remaining traits improve compatibility with the rest of the standard library.
use crate::bytes::*;
use dyn_derive::dyn_trait_method;
use std::fmt;
u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.