text stringlengths 8 4.13M |
|---|
use std::io;
use std::mem;
use std::borrow::{Cow, ToOwned};
use std::ops::Range;
use crate::endianness::Endianness;
use crate::writable::Writable;
use crate::writer::Writer;
use crate::context::Context;
use crate::utils::as_bytes;
macro_rules! impl_for_primitive {
($type:ty, $write_name:ident) => {
impl... |
extern crate clap;
use git2::{Repository,Error,SubmoduleUpdateOptions};
use clap::{Arg, App};
use std;
use std::io;
fn get_path(submodule : &str ,path : Option<&str>) -> io::Result<std::path::PathBuf>{
match path{
None =>{
let mut path = std::env::current_dir().unwrap();
// create path:
let result... |
#[cfg(test)]
mod stream_test;
use crate::association::AssociationState;
use crate::chunk::chunk_payload_data::{ChunkPayloadData, PayloadProtocolIdentifier};
use crate::error::Error;
use crate::queue::reassembly_queue::ReassemblyQueue;
use crate::queue::pending_queue::PendingQueue;
use bytes::Bytes;
use std::fmt;
use ... |
use std::iter::Iterator;
use std::ops::{Div, Sub};
/// An iterator that returns successive iterations of the Newton's method.
///
/// This iterator is generic over it's entry, and allows to freely use the Newton method on
/// arbitrary types.
///
/// # Example
///
/// ```
/// use generic_newton::Newton;
///
/// fn mai... |
use libc::c_void;
use util::ConstDefault;
use arch::{IrqHandler, __STACK_START};
pub type VectorTable<I> = arm::VectorTable<ExceptionVectors, I>;
extern fn cortex_m0_isr() {
unsafe {
asm!("
.thumb_func
.global __default_isr_handler
__default_isr_handler:
bkpt
b .
"::::"volatile");
}
}
#[repr(C)]... |
use crate::raw_key::RawKey;
use crate::signers::{Error, Signer};
use hmac::crypto_mac::Mac;
use hmac::Hmac as BaseHmac;
use sha3::Sha3_256;
use std::convert::TryInto;
type Conjuncted = BaseHmac<Sha3_256>;
pub struct Hmac {
pub hmac: Conjuncted,
}
impl Signer for Hmac {
fn make(key: &[u8]) -> Self {
H... |
use nu_path::canonicalize_with;
use nu_protocol::{
ast::{
Argument, Block, Call, Expr, Expression, ImportPattern, ImportPatternHead,
ImportPatternMember, Pipeline,
},
engine::{StateWorkingSet, DEFAULT_OVERLAY_NAME},
span, BlockId, Exportable, Module, PositionalArg, Span, Spanned, SyntaxS... |
extern crate gl;
use gl::types::*;
use gl_buffer::*;
use gl_err::*;
use std::ptr;
pub struct GlVertexArray {
pub gl_handle : GLuint,
pub vertex_count : i32,
_vbs : Vec<GlBufferRaw>
}
pub struct GlVertexArrayTmp<'a> {
pub gl_handle : GLuint,
pub vertex_count : i32,
_vbs : Vec<&'a GlBufferRaw>
}... |
fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {
let mut res = vec![0.0; mat.len()];
for i in 0..n {
for j in 0..(i+1){
let mut s = 0.0;
for k in 0..j {
s += res[i * n + k] * res[j * n + k];
}
res[i * n + j] = if i == j { (mat[i * n + i] ... |
#![feature(plugin)]
#![plugin(rocket_codegen)]
#[macro_use]
extern crate serde_derive;
extern crate rocket;
extern crate serde_json;
mod lib;
use lib::direction::Direction;
use lib::point::Point;
use lib::robot::Robot;
static mut ROBOT: Robot = Robot {
facing: Direction::North,
position: Point { x: 0, y: 0 },... |
use std::collections::HashMap;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
fn serve_order() {}
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
fn seat_at_table() {}
}
mod serving {
fn take_order() {}
... |
use ::{ ActoxError, ActoxResult };
use ::std::{
ptr, collections::HashMap, any::Any,
sync::{ mpsc::Sender, Mutex, atomic::{ AtomicPtr, Ordering } }
};
/// A global `ActorPool` to register input-channels under a name
pub struct ActorPool;
impl ActorPool {
/// Registers a new `actor_input` under `name`
///
/// Par... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceIdentity {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: O... |
use std::slice;
use std::io::{self, Write};
use byteorder::{
ByteOrder,
LittleEndian,
BigEndian,
WriteBytesExt
};
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Endianness {
LittleEndian,
BigEndian
}
impl Endianness {
#[cfg( target_endian = "little" )]
pub cons... |
use anyhow::Result;
use log::{debug, error, info};
use osmpbfreader::objects::{Node, Way};
use osmpbfreader::{OsmObj, OsmPbfReader};
use rusqlite::{params, Connection, Statement};
use std::f64::consts::PI;
use std::fs::File;
use std::hash::{Hash, Hasher};
#[derive(Debug)]
pub struct Database {
conn: Connection,
... |
use std::{
cell::{Ref, RefCell},
rc::Rc,
};
#[derive(Clone)]
pub struct Atom<T> {
value: Rc<RefCell<T>>,
subscribers: Rc<RefCell<Vec<Subscriber>>>,
}
impl<T> Atom<T> {
pub fn new(initial: T) -> Self {
Self {
value: Rc::new(RefCell::new(initial)),
subscribers: Rc::ne... |
pub const GRID_SIZE: (i16, i16) = (30, 20);
pub const GRID_CELL_SIZE: (i16, i16) = (40, 40);
pub const SCREEN_SIZE: (f32, f32) = (
GRID_SIZE.0 as f32 * GRID_CELL_SIZE.0 as f32,
GRID_SIZE.1 as f32 * GRID_CELL_SIZE.1 as f32,
);
pub const UPDATES_PER_SECOND: f32 = 10.0;
pub const MILLIS_PER_UPDATE: u64 = (1.0 / ... |
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Vacant, Occupied};
use std::hash;
pub fn create_or_increment<A: Eq + hash::Hash>(hash: &mut HashMap<A, i64>, key: A) {
match hash.entry(key) {
Vacant(e) => { e.insert(1); },
Occupied(mut e) => { *e.get_mut() += 1 },
}
}
#[c... |
mod cli;
mod parser;
use cli::Cli;
use structopt::StructOpt;
use chrono::prelude::*;
use chrono::{Duration, Utc};
use std::collections::VecDeque;
const EARTH_RADIUS_IN_METERS: f32 = 6_371_000.0;
fn main() {
let args = Cli::from_args();
let coordinates = parser::process(&args.input);
let mut distances = Vec::wit... |
fn main() {
let _s1 = gives_ownership();
let s2 = String::from("Hello");
let _s3 = takes_and_gives_back(s2);
} // here, drop will only be called on _s1 and _s3 as s2 ownership was moved
fn gives_ownership() -> String {
let s = String::from("Hello");
s
}
fn takes_and_gives_back(s: String) -> String... |
fn main() {
println!("Sort numbers in descending order");
let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1];
println!("Before: {:?}", numbers);
quick_sort(&mut numbers, &|x,y| x > y);
println!("After: {:?}\n", numbers);
println!("Sort strings alphabetically");
let mut strings = ["... |
#[derive(PartialEq, Eq, Debug)]
pub enum MessageMethod {
Binding,
Custom(u16),
}
impl MessageMethod {
pub fn from(value: u16) -> MessageMethod {
// make sure the value is at most 12 bits length
if value & 0xFFF != value {
panic!(format!("invalid method value: {}", value))
... |
use std::io::Write;
use serde::de::value::Error;
use serde::ser::{self, Impossible};
use serde::Serialize;
use internal::gob::{Message, Writer};
use internal::types::TypeId;
use internal::utils::Bow;
use schema::Schema;
mod serialize_struct;
pub(crate) use self::serialize_struct::SerializeStructValue;
mod serialize... |
use {
Clipboard,
errors::{ClipboardError, WinError},
clipboard_metadata::{WinContentType, ClipboardContentType}
};
use clipboard_win::{
Clipboard as SystemClipboard,
raw::is_format_avail,
};
pub struct WindowsClipboard { }
impl Clipboard for WindowsClipboard {
type Output = Self;
fn new() -> Result<Self::Out... |
fn main() {
proconio::input! {
n: i32,
r: i32,
}
if n >= 10 {
println!("{}", r);
}else{
println!("{}", r + 100 * (10 - n));
}
} |
use crate::{
diagnostics::Diagnostics,
dirgraphsvg::edges::{EdgeType, SingleEdge},
};
use serde::Deserialize;
use std::collections::{BTreeMap, BTreeSet, HashMap};
pub mod check;
pub mod validation;
///
/// The main struct of this program
/// It describes a GSN element
///
#[derive(Debug, Default, Deserialize)... |
const HELP: &str = r#"
ntbk is a terminal notebook manager.
Usage: ntbk [ACTION]
ntbk find <pattern> - Find notes by path
ntbk grep <pattern> - Search through notes content
ntbk help - Print this usage information
ntbk list - List all notes
ntbk new <name> - ... |
//! Callbacks for the `screen` object in the Lua libraries
use ::luaA;
use ::lua::Lua;
use libc::c_int;
#[repr(C)]
pub struct ScreenState {
// TODO IMPLEMENT
}
#[allow(non_snake_case)]
pub trait Screen {
// Class Methods
fn screen_add_signal(&self, lua: &Lua) -> c_int;
fn screen_connect_signal(&self,... |
extern crate duktape;
use duktape::error::Result;
use duktape::prelude::*;
fn main() -> Result<()> {
let mut ctx = Context::new()?;
let mut builder = class::build();
let global: Object = ctx.push_global_object().getp()?;
builder.method(
"greet",
(1, |ctx: &Context, this: &mut class::... |
extern crate ispc;
use std::env;
use std::path::PathBuf;
fn main() {
let mut embree_include;
if let Ok(e) = env::var("EMBREE_DIR") {
embree_include = PathBuf::from(e);
embree_include.push("include");
} else {
println!("cargo:error=Please set EMBREE_DIR=<path to embree3 root>");
... |
use console::style;
use std::error::Error;
use std::path::{Path, PathBuf};
use std::{env, fs, io, process};
use itertools::Itertools;
use std::hash::{Hash, Hasher};
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
fn find_in_path<F>(dir: &Path, predicate: &F) -> io:... |
mod project;
pub mod projects;
mod task;
|
#![doc = "Peripheral access API for STM32L552 microcontrollers (generated using svd2rust v0.30.0 (8dd361f 2023-08-19))\n\nYou can find an overview of the generated API [here].\n\nAPI features to be included in the [next]
svd2rust release can be generated by cloning the svd2rust [repository], checking out the above comm... |
use actix::{
dev::{MessageResponse, OneshotSender},
Actor, Message,
};
use chrono::{DateTime, Utc};
use yahoo_finance_api::Quote;
use crate::{cli_error::SymbolError, model::ProcessedQuote};
pub struct FetchAll;
impl Message for FetchAll {
type Result = ();
}
pub struct Fetch {
pub symbol: String,
... |
use async_trait::async_trait;
use stable_eyre::eyre;
use tokio::sync::mpsc::Sender;
use toml::value::Datetime;
use super::{util, Graphql, Producer};
#[derive(Debug)]
pub struct ListReposForOrg {
graphql: Graphql,
org_name: String,
repo_names: Vec<String>,
start_date: Datetime,
end_date: Datetime,
... |
use cgmath::{Point3, Vector3, InnerSpace};
use std::cmp::{PartialOrd, Ord, Ordering};
#[derive(Debug, Clone, PartialEq)]
pub struct Intersection {
pub ray_t: f64,
pub origin: Point3<f64>,
pub normal: Vector3<f64>,
}
impl Intersection {
pub fn new(ray_t: f64, origin: Point3<f64>, normal: Vector3<f64>) ... |
use std::cmp::max;
use std::io::{self, BufRead};
fn mass_to_fuel(mass: u64) -> u64 {
max(mass / 3, 2) - 2
}
fn mass_to_fuel_recursive(mass: u64) -> u64 {
let fuel = mass_to_fuel(mass);
if fuel <= 6 {
return fuel;
}
fuel + mass_to_fuel_recursive(fuel)
}
fn part_one() {
let stdin = io:... |
extern crate libc;
#[link(name = "mt", kind = "static")]
extern {
fn sgrnd_(seed: *const libc::c_int);
fn grnd_() -> libc::c_double;
fn gaussrnd_(rr: *mut libc::c_double);
}
pub fn sgrnd(seed: i32) {
unsafe { sgrnd_(&seed); }
}
pub fn seed(seed: &[u8]) {
sgrnd(*::utils::repack_u8s(&seed).get(0).u... |
use std::env;
use std::fs;
#[derive(Copy, Clone, Debug)]
enum Dir {
N = 0,
E = 90,
S = 180,
W = 270,
}
impl Dir {
fn from_val(val: i32) -> Dir {
match val {
0 => Dir::N,
90 => Dir::E,
180 => Dir::S,
270 => Dir::W,
_ => panic!("Inv... |
use serenity::{
client::{bridge::gateway::ShardId, Context},
framework::standard::{macros::command, CommandResult},
model::channel::Message,
};
use crate::{
common::{get_locale, tt},
data::{DatabasePool, ShardManagerContainer},
reply,
};
#[command]
async fn ping(ctx: &Context, msg: &Message) -... |
use crate::context::Data;
use crate::http::{GQLError, GQLRequest, GQLResponse};
use crate::{
ConnectionTransport, Error, FieldError, FieldResult, ObjectType, QueryBuilder, QueryError,
QueryResponse, Result, Schema, SubscriptionStreams, SubscriptionType, Variables,
};
use bytes::Bytes;
use std::collections::Hash... |
use fmod_studio;
use fmod_studio::guid::Guid;
use fmod_studio::error::FmodError;
pub use audio::update::AudioUpdate;
pub mod update;
pub struct System {
pub studio: fmod_studio::system::System,
}
impl System {
pub fn get_id(&self, object: &str) -> Option<Guid> {
match self.studio.lookup_id(object) {... |
extern crate ini;
use self::ini::Ini;
extern crate time;
#[cfg(target_os = "macos")]
use super::osx;
use std::env;
use std::fs;
use std::path;
const INIFILE: &'static str = "connectr.ini";
pub struct Settings {
pub port: u32,
pub secret: String,
pub client_id: String,
pub access_token: Option<Strin... |
use std::sync::mpsc::channel;
use std::thread;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use hydroflow::hydroflow_syntax;
use hydroflow::scheduled::graph_ext::GraphExt;
use static_assertions::const_assert;
use timely::dataflow::operators::{Inspect, Map, ToStream};
const NUM_OPS: usize = ... |
use crate::*;
use crate::{percolator::TimestampOracle, rpc::kvs_service::*};
use std::{net::SocketAddr, time::Duration};
use tonic::{Request, Response, Status};
/// Kvs Server
// #[derive(Clone)]
pub struct KvsBasicServer {
store: MultiStore,
addr: SocketAddr,
ts_oracle: TimestampOracle,
}
impl KvsBasicSe... |
#[macro_use] extern crate proc_macro_starter;
extern crate rocket;
#[derive(FromFormValue)]
pub enum Value {
A,
B,
C,
SomethingElse,
}
pub fn main() { }
|
pub use crate::macros::*;
pub use crate::node::*;
|
#[cfg(not(feature = "std"))]
use crate::no_std_prelude::*;
#[cfg(feature = "std")]
use crate::Sign;
use crate::{
format::parse::{parse, ParseResult, ParsedItems},
Date, DeferredFormat, Duration, OffsetDateTime, Time, UtcOffset, Weekday,
};
#[cfg(feature = "std")]
use core::convert::From;
use core::{
cmp::Or... |
use std::collections::HashSet;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 3 {
println!("Invalid arguments, expected 2 args");
process::exit(1);
}
let to... |
extern crate rustty;
use rustty::{
Terminal,
Event,
Color,
};
struct Cursor {
pos: Position,
lpos: Position,
color: Color,
}
#[derive(Copy, Clone)]
struct Position {
x: usize,
y: usize,
}
fn main() {
let mut cursor = Cursor {
pos: Position { x: 0, y: 0 },
lpos: Po... |
#[doc = "Register `MPCBB1_VCTR16` reader"]
pub type R = crate::R<MPCBB1_VCTR16_SPEC>;
#[doc = "Register `MPCBB1_VCTR16` writer"]
pub type W = crate::W<MPCBB1_VCTR16_SPEC>;
#[doc = "Field `B512` reader - B512"]
pub type B512_R = crate::BitReader;
#[doc = "Field `B512` writer - B512"]
pub type B512_W<'a, REG, const O: u8... |
use super::*;
use crate::{
db::{builders::UserBuilder, ConnectionPool},
tests::DbSession,
};
#[actix_rt::test]
async fn find_by_user_id() {
let session = DbSession::new();
let user = session.create_user(UserBuilder::default());
let record = session.create_record2(user.id);
let result_record =... |
use darling::FromMeta;
#[cfg(feature = "mssql")]
use inflector::Inflector;
#[cfg(feature = "mssql")]
use proc_macro2::TokenStream;
#[cfg(feature = "mssql")]
use syn::{spanned::Spanned, Field};
#[allow(clippy::enum_variant_names)]
#[derive(Clone, Copy, Debug, Eq, FromMeta, PartialEq)]
pub(crate) enum RenameAll {
... |
extern crate atty;
extern crate regex;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::env;
mod config;
mod mailcap;
mod mimetype;
use config::Config;
fn print_usage() {
println!("Usage: run-mailcap-rs [OPTION]... [MIME-TYPE:]FILE");
println!();
println!("Options:");
... |
//! A multiset backed by a HashMap
use std::collections::HashMap;
use std::hash::Hash;
/// A multiset backed by a HashMap
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct HashMultiSet<T: Hash + Eq> {
items: HashMap<T, usize>,
len: usize,
}
impl<T: Hash + Eq> HashMultiSet<T> {
/// Insert item into the mul... |
table! {
posts (id) {
id -> Uuid,
content -> Text,
id_users -> Uuid,
is_private -> Bool,
}
}
table! {
users (id) {
id -> Uuid,
screen_name -> Text,
created_at -> Timestamp,
}
}
joinable!(posts -> users (id_users));
allow_tables_to_appear_in_same... |
extern crate playground;
use playground::collections::vector;
fn main() {
println!("{:?}", vector::get_properties(&vec![2, 1, 3, 2]));
println!("{:?}", vector::get_properties(&vec![]));
println!("{:?}", vector::get_properties(&vec![2, 1, 3, 3, 3]));
}
|
use serde::{Serialize, Deserialize};
use actix_web::{HttpResponse, HttpRequest, Responder, Error};
use futures::future::{ready, Ready};
use sqlx::{postgres::{PgPoolOptions, PgRow}, query_as};
use sqlx::{FromRow, Row, Pool, Postgres};
use anyhow::Result;
use crate::utils::get_unix_timestamp_ms;
#[derive(Deserialize, S... |
use fltk::{button::*, enums::*, frame::*, group::*, prelude::*, window::*};
use std::cell::RefCell;
use std::rc::Rc;
/*
Created:0.0.1
updated:0.0.1
description:
Contains Sidebar widgets and functionality
*/
pub fn create(wind: &mut DoubleWindow, at: i32) -> BarUi{
let frame = Frame::default()
.with... |
use super::super::error::{Error, ErrorKind, Result};
/// Describes the shape of a tensor.
///
/// **note**: `From` conversion implementations are provided for low-rank shapes.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TensorShape {
/// The number of components the associated tensor can store.
///
/... |
use ast;
use name::*;
use ast::walker::*;
use arena::Arena;
use std::collections::hash_map;
use middle::*;
struct Collector<'a, 'ast: 'a> {
arena: &'a Arena<'a, 'ast>,
package: PackageRef<'a, 'ast>,
scope: Vec<Symbol>,
tydef: Option<TypeDefinitionRef<'a, 'ast>>,
}
impl<'a, 'ast> Walker<'ast> for Col... |
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// HostMapWidgetDefinitionRequests : List of definitions.
#[derive(Clone, Debug, PartialEq, Serializ... |
#[doc = "Register `AHB1SMENR` reader"]
pub type R = crate::R<AHB1SMENR_SPEC>;
#[doc = "Register `AHB1SMENR` writer"]
pub type W = crate::W<AHB1SMENR_SPEC>;
#[doc = "Field `DMA1SMEN` reader - CPU1 DMA1 clocks enable during Sleep and Stop modes"]
pub type DMA1SMEN_R = crate::BitReader;
#[doc = "Field `DMA1SMEN` writer - ... |
//! Contains the types for read concerns and write concerns.
#[cfg(test)]
mod test;
use std::time::Duration;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_with::skip_serializing_none;
use typed_builder::TypedBuilder;
use crate::{
bson::{doc, serde_helpers, Timestamp},
error::{Erro... |
#![allow(unused_imports)]
#![allow(unused_variables)]
extern crate regex;
use std::collections::HashSet;
use glr_grammar;
use glr_grammar::Atom as Atom;
use glr_grammar::GrammarItem as GrammarItem;
use std::sync::Arc;
use self::regex::Regex;
#[derive(Debug,Clone,Hash,PartialEq,Eq,PartialOrd,Ord)]
... |
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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
//
// ht... |
use crate::component::{CompositeSurfaceCache, CompositeTilemap, CompositeTilemapAnimation};
use core::{
app::AppLifeCycle,
ecs::{Comp, Universe, WorldRef},
Scalar,
};
pub type CompositeTilemapAnimationSystemResources<'a> = (
WorldRef,
&'a AppLifeCycle,
Comp<&'a mut CompositeTilemap>,
Comp<&... |
//https://gist.github.com/horyu/566a5155db897a47b5d893e9307e1f93
pub fn make_permutation(n: usize) -> Vec<Vec<usize>> {
let mut vecs: Vec<Vec<usize>> = vec![Vec::new(); factorial(n)];
let nums: Vec<usize> = (0..n).collect();
let indexes: Vec<usize> = (0..factorial(n)).collect();
push_recusive(nums, inde... |
use libriakv::RiaKV;
use std::fs::{File, OpenOptions};
use std::io;
use std::path::Path;
#[cfg(target_os = "windows")]
const USAGE: &str = "
CLI client for RiaKV key value store with persistent index.
Usage:
riakv_mem.exe STORAGE_FILE INDEX_FILE get KEY
riakv_mem.exe STORAGE_FILE INDEX_FILE delete KEY
ri... |
#[doc = "Register `GICC_NSAPR0` reader"]
pub type R = crate::R<GICC_NSAPR0_SPEC>;
#[doc = "Register `GICC_NSAPR0` writer"]
pub type W = crate::W<GICC_NSAPR0_SPEC>;
#[doc = "Field `NSAPR0` reader - NSAPR0"]
pub type NSAPR0_R = crate::FieldReader<u32>;
#[doc = "Field `NSAPR0` writer - NSAPR0"]
pub type NSAPR0_W<'a, REG, ... |
#[doc = "Register `I3C_CR_ALTERNATE` writer"]
pub type W = crate::W<I3C_CR_ALTERNATE_SPEC>;
#[doc = "Field `DCNT` writer - count of data to transfer during a read or write message, in bytes (when I3C is acting as controller) Linear encoding up to 64 Kbytes -1. ..."]
pub type DCNT_W<'a, REG, const O: u8> = crate::FieldW... |
mod constraint_solver;
mod typed_constraint;
mod hinge_constraint;
pub use self::constraint_solver::*;
pub use self::typed_constraint::TypedConstraint;
pub use self::hinge_constraint::*;
|
use math::*;
use theme::*;
use render::*;
#[derive(Clone, Copy)]
pub struct Grid {
pub visible: bool,
pub size: Vector2<i16>,
pub offset: Vector2<i16>,
}
impl Grid {
pub fn paint(&self, ctx: &mut Canvas, zoom: i16, rect: Rect<i32>) {
if !self.visible {
return;
}
le... |
use std::{mem, ptr};
struct SpscQueue<V: Send + Sync> {
buffer: *mut V,
capacity: usize,
capacity_mask: usize,
// We implement it at the queue level as it's a common requirement and so that V doesn't have to
// be a heavier enum with an end message variant.
ended: bool,
read_next: usize,
... |
#[doc = "Reader of register SRSS_INTR_CFG"]
pub type R = crate::R<u32, super::SRSS_INTR_CFG>;
#[doc = "Writer for register SRSS_INTR_CFG"]
pub type W = crate::W<u32, super::SRSS_INTR_CFG>;
#[doc = "Register SRSS_INTR_CFG `reset()`'s with value 0"]
impl crate::ResetValue for super::SRSS_INTR_CFG {
type Type = u32;
... |
use crate::transactions::{NotFound, Registration};
#[derive(Debug, Clone)]
pub struct Dialog {
pub computed_id: String,
pub call_id: String,
pub from_tag: String,
pub to_tag: String,
pub flow: DialogFlow,
}
#[derive(Debug, Clone)]
pub enum DialogFlow {
Registration(Registration),
Invite(No... |
// file: max.rs
//
// Copyright 2015-2017 The RsGenetic Developers
//
// 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 ... |
use actix::Running;
use actix::StreamHandler;
use actix::{Actor, ActorContext, Addr, AsyncContext};
use actix_web_actors::ws;
use std::time::Instant;
use actix::prelude::*;
use crate::game_folder::game::Game;
use crate::participants::director_folder::director_structs::{
self, DirectorClientMsg, DirectorClientType, ... |
#![no_std]
#![no_main]
#![feature(asm)]
#![feature(const_slice_len)]
#![feature(slice_patterns)]
#![feature(optin_builtin_traits)]
#![feature(core_intrinsics)]
extern crate alloc;
#[macro_use]
extern crate log;
extern crate uefi;
extern crate uefi_exts;
extern crate uefi_macros;
use alloc::fmt::format;
use core::fmt;... |
use num_bigint::BigUint;
use ropey::Rope;
use sp_ipld::Ipld;
use std::fmt;
use crate::{
ipld_error::IpldError,
literal::Literal,
term::Term,
yatima,
};
use core::convert::{
TryFrom,
TryInto,
};
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum TextOp {
Cons,
LenChars,
LenLines,
LenBytes,
Ap... |
use clap::ArgMatches;
use colored::*;
use failure::Error;
use git2::{Repository, StatusEntry, StatusOptions, Statuses};
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::prelude::*;
use std::io::{self, Error as IOError, Write};
use std::process::Command;
#[derive(Fail, Debug)]... |
#[macro_use]
extern crate dotenv_codegen;
mod dbTest;
mod integrationTest {
use actix_http::HttpService;
use actix_http_test::{ TestServer, TestServerRuntime };
use actix_web::http::header;
use actix_web::{http, App, web};
use actix_http::httpmessage::HttpMessage;
use serde_json::json;
us... |
extern crate cty;
#[allow(dead_code)]
mod bindings;
pub use self::bindings::{osKernelInitialize, osKernelStart, osThreadCreate, osPriority};
pub type RawOSArg = *const cty::c_void;
pub type RawOSArgMut = *mut cty::c_void;
pub type OsPThread = unsafe extern "C" fn(RawOSArg);
pub trait OptPtr<T> {
fn as_ptr<'a>(o... |
/*
* Fast discrete cosine transform algorithms (Rust)
*
* Copyright (c) 2020 Project Nayuki. (MIT License)
* https://www.nayuki.io/page/fast-discrete-cosine-transform-algorithms
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation fil... |
fn main() {
let meshes = pgeom::obj::load("models/gun/Handgun_obj.obj").unwrap();
//let (v, i) = meshes[2].render_data(|v| v.uv);
meshes.iter().for_each(|m| {
println!("{:#?}", m.name);
});
//println!("{:#?}", v);
}
|
struct UnionFind {
par: Vec<usize>,
siz: Vec<usize>,
}
impl UnionFind {
fn new(n: usize) -> Self {
UnionFind {
par: (0..n).collect(),
siz: vec![1; n],
}
}
fn root(&mut self, x: usize) -> usize {
if self.par[x] == x {
x
} else {
... |
#![allow(dead_code)]
pub fn options_test(x: f32, y: f32) {
let result = if y != 0.0 { Some(x/y) } else { None };
match result {
Some(value) => println!("result = {} !!", value),
None => println!("Never divide by zero !!!")
}
}
|
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate serde;
pub mod db;
pub mod r#move; |
use std::{fs::File, io::{BufRead, BufReader}, collections::BTreeMap};
fn main() {
let file = File::open("inputs/input-10.txt").unwrap();
let lines: Vec<usize> = BufReader::new(file).lines().map(|l| l.unwrap().parse().unwrap()).collect();
part_one(&lines);
let mut cache: BTreeMap<usize, usize> = BTre... |
use ability_scores::AbilityScore;
use ability_scores::Charisma;
use ability_scores::Constitution;
use ability_scores::Dexterity;
use ability_scores::Intelligence;
use ability_scores::Strength;
use ability_scores::Wisdom;
use ability_scores;
pub trait Character {
fn get_level(&self) -> &u8;
fn set_level(&mut self... |
use bytes::{Buf, BufMut};
use codec::{BufLen, Codec, VarLen};
use {QuicError, QuicResult};
// On the wire:
// len: VarLen
// ptype: u8
// flags: u8
// payload: [u8]
#[derive(Debug, PartialEq)]
enum HttpFrame {
Settings(SettingsFrame),
}
impl Codec for HttpFrame {
fn encode<T: BufMut>(&self, buf: &mut T) {
... |
/*
Copyright ⓒ 2016 rust-custom-derive contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, m... |
use async_std;
use applications::web;
fn main() -> std::result::Result<(), std::io::Error> {
async_std::task::block_on(web::main())
}
|
/*
First, let’s take a look at the ownership rules. Keep these rules in mind
as we work through the examples that illustrate them:
Each value in Rust has a variable that’s called its owner.
There can only be one owner at a time.
When the owner goes out of scope, the value will be dropped.
*/
fn main() {
println!... |
use std::env;
use std::process;
extern crate log_highlight;
use log_highlight::config::Config;
use log_highlight::highlighter::{Highlighter};
use log_highlight::rule::Rules;
fn main() {
// NOTE: 戻り値がある場合はunwrap_or_else
let config = Config::new(env::args()).unwrap_or_else(|err| {
if ! err.to_string().i... |
use std::cell::Cell;
use nalgebra::Vector2;
#[derive (Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct SerialNumber (pub u64);
impl Default for SerialNumber {
fn default()->Self {
thread_local! {static NEXT_SERIAL_NUMBER: Cell<u64> = Cell::new (0);}
NEXT_SERIAL_NUMBER.with (| next | {
... |
extern crate simple_excel_writer as excel;
use excel::*;
fn main() {
let mut wb = Workbook::create("./tmp/b.xlsx");
let mut sheet = wb.create_sheet("SheetName");
// set column width
sheet.add_column(Column { width: 30.0 });
sheet.add_column(Column { width: 30.0 });
sheet.add_column(Column { wi... |
use crate::error::HttpEndpointError;
use crate::sink::{Sink, SinkError, SinkTarget};
use actix_web::HttpResponse;
use anyhow::Context;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use cloudevents::{event::Data, Event, EventBuilder, EventBuilderV10};
use drogue_client::registry;
use drogue_cloud_service_ap... |
use nmstate::NmstateError;
pub(crate) struct CliError {
pub(crate) msg: String,
}
impl std::fmt::Display for CliError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.msg)
}
}
impl From<std::io::Error> for CliError {
fn from(e: std::io::Error) -> Sel... |
use super::primes;
use clap::Clap;
/// Largest prime factor
///
/// The prime factors of 13195 are 5, 7, 13 and 29.
/// What is the largest prime factor of the number 600851475143 ?
///
#[derive(Clap)]
pub struct Solution {
#[clap(short, long, default_value = "600851475143")]
number: usize,
}
impl Solution {
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.