text stringlengths 8 4.13M |
|---|
use std::rc::Rc;
use std::cell::RefCell;
use html::HtmlElement;
use html::RustEventHandler;
make_app_setup!{ pub fn app_setup() app_thread_state = APP_STATE, render = render }
thread_local!(static APP_STATE: RefCell<AppState> = RefCell::new(AppState::new()));
struct TodoItem {
id: u32,
name: String,
editi... |
use hdk::{
self,
error::ZomeApiResult,
entry_definition::ValidatingEntryType,
holochain_core_types::{
dna::entry_types::Sharing,
},
holochain_json_api::{
json::JsonString,
error::JsonError,
},
};
#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone)]
pub struc... |
extern crate regex;
use std::fs;
use std::path::{Path, PathBuf};
use regex::Regex;
mod metadata;
fn is_gopro_file<S>(file_name: S) -> bool
where
S: AsRef<str>,
{
let re = Regex::new("^G[HX]\\d{6}.(mp|MP)4").unwrap();
re.is_match(file_name.as_ref())
}
pub fn fix<P>(path: P) -> Option<PathBuf>
where
... |
#[test]
#[cfg(not(feature = "panic"))]
fn test_error() {
bitrange! {
Test: u8, "u8",
"1111_111a",
a: _first
}
// Because the pattern is 1111_111
// This means that all bits, except the last, should always be 1
// Because `0` does not match this criteria, this function panics
... |
use aoc2019::halp;
type CoordType = i32;
#[derive(Debug)]
enum Move {
U(CoordType),
D(CoordType),
L(CoordType),
R(CoordType),
}
type Pos = (CoordType, CoordType);
type LineSeg = (Pos, Pos);
#[derive(Debug)]
struct CumLineSeg {
start_steps: i32,
end_steps: i32,
this_steps: i32,
seg: Li... |
// TODO: add toml, read tomls and make sure we handle [[bin]] and [[test]] and [[bench]]
use anyhow::anyhow;
use std::ffi;
use std::fs;
use std::path::{Path, PathBuf};
use structopt::StructOpt;
use walkdir::{DirEntry, WalkDir};
mod config;
type Result<T> = anyhow::Result<T>;
#[derive(Debug, StructOpt)]
struct Args ... |
use std::collections::HashMap;
pub fn format_line(team: String, mp: String, w: String, d: String, l: String, p: String) -> String {
format!("{:<31}| {:^2} | {:^3}| {:^3}| {:^3}| {:^3}", team, mp, w, d, l, p)
}
pub fn format_line_values(team: String, mp: String, w: String, d: String, l: String, p: String) -> Strin... |
use crate::generated::packed::{Byte32, OutPoint};
use ckb_error::{Error, ErrorKind};
use failure::Fail;
#[derive(Fail, Debug, PartialEq, Eq, Clone)]
pub enum OutPointError {
/// The specified cell is already dead
#[fail(display = "Dead({:?})", _0)]
Dead(OutPoint),
/// The specified cells is unknown in... |
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
fn main() {
println!("SDE CLI v{}", VERSION);
}
|
// Copyright 2023 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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 ... |
use gtk::glib;
use gtk::prelude::*;
use sysinfo::{ComponentExt, CpuExt, SystemExt};
use std::cell::RefCell;
use std::iter;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use crate::graph::GraphWidget;
use crate::settings::Settings;
use crate::utils::{format_number, graph_label_units, RotateVec};
pub fn create_header(... |
//! bextr
/// Bit field extract
pub trait Bextr {
/// Bit field extract.
///
/// Extracts bits in range `[start, start + length)` from the `source` to
/// the least significant bits of the result.
///
/// Bits `[7,0]` of `range` specify the index to the first bit in the
/// range to be extr... |
use std::env;
use std::path::{Path, PathBuf};
use std::ffi::OsStr;
use std::fs::{self, File};
use std::io::{self, Read};
use zip::{self, ZipArchive};
use walkdir::WalkDir;
use defs::*;
fn dir_producer(directories: &[&String], queue: &WorkQueue) -> Option<Vec<u8>> {
let gcno_ext = Some(OsStr::new("gcno"));
let... |
#[macro_use]
extern crate rocket;
mod scraper;
#[get("/version")]
fn version() -> String {
format!("0.1")
}
#[get("/info/<tickers>")]
fn ticker(tickers: String) -> String {
scraper::run(tickers.split(",").map(|s| s.to_string()).collect());
format!("Ticker = {}", tickers)
}
#[launch]
fn rocket() -> rocke... |
use std::env;
use std::ops::Add;
use std::str::FromStr;
fn calculate_fuel_requirement_naively(mass: i64) -> i64 {
(mass / 3) - 2
}
fn calculate_fuel_requirement_recursively(mass: i64) -> i64 {
let fuel_requirement = calculate_fuel_requirement_naively(mass);
if fuel_requirement > 0 {
fuel_requirem... |
// Copyright (c) The diem-devtools Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Configuration for nextest.
use crate::errors::*;
use anyhow::Context;
use camino::{Utf8Path, Utf8PathBuf};
use serde::Deserialize;
use std::{
collections::{hash_map::Entry, HashMap},
fmt,
};
/// Configuration fo... |
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::AUX0 {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut ... |
use std::fs;
#[test]
fn test_insta() {
tracing_subscriber::fmt::init();
insta::glob!("corpus/*.nix", |path| {
let input = fs::read_to_string(path).unwrap();
let (ty, sol, sink) = succ_nix::run(&path.display().to_string(), &input, 65536);
if !sink.is_error() {
insta::assert... |
use rtm::{Bot, Channel, Group, Im, Mpim, Team, User};
use timestamp::Timestamp;
/// Starts a Real Time Messaging session.
///
/// Wraps https://api.slack.com/methods/rtm.connect
#[derive(Clone, Debug, Serialize, new)]
pub struct ConnectRequest {
#[new(default)]
batch_presence_aware: Option<bool>,
#[new(de... |
use glium::texture::{MipmapsOption, Texture1d, UncompressedFloatFormat};
use tiled::Tileset;
use std::collections::HashMap;
use graphics::{self, TextureId};
pub struct TilesetDesc {
pub tileset: Tileset,
pub tile_gids: HashMap<u16, u16>,
pub texture: TextureId,
pub tile_uv: Texture1d,
pub rows: u... |
pub use cortex_m::peripheral::syst;
//pub use sam3x8e as target;
// #[macro_use]
// // Source: https://github.com/stm32-rs/stm32f4xx-hal/blob/9dab1701bc68efe3a1df8eb3b93c866d7ef1fa0e/src/lib.rs
// #[cfg(not(feature = "device-selected"))]
// compile_error!("This crate requires one of the following device features enabl... |
#[macro_export]
macro_rules! __linea_impl_comma_sep_length {
() => (U0);
($x:tt) => (U1);
($x:tt, $($y:tt),+) => (typenum::operator_aliases::Add1<__linea_impl_comma_sep_length!($($y),*)>)
}
/// Example use:
/// ```
/// # #[macro_use] extern crate linea; extern crate typenum; use linea::Matrix; use typenum:... |
#[derive(Debug, Clone)]
pub enum Token {
WORD(String),
FUNCTION,
RETURN,
NUMBER(i32),
IF,
LParen,
RParen,
LBrace,
RBrace,
WHITESPACE,
SEMICOIN,
UNKNOW,
}
pub trait ITokenizer {
fn new() -> Self;
fn next_token(&self, item: &str) -> Token;
}
pub trait ILexer {
... |
use crate::{
bit_set,
bit_set::{
ops::{Access, Capacity},
word::cast,
Word,
},
};
/// Trait to manipulate bits.
pub trait Remove: Access {
/// Remove bit, and return a **previous** value.
fn remove(&mut self, i: u64) -> bool;
}
macro_rules! impl_Remove_for_words {
($($t... |
use crate::{
ir::*,
types::{self, Type},
};
use std::{error::Error, fmt::Display};
#[derive(Clone, Debug, PartialEq)]
pub enum TypeCheckError {
ElementIndexOutOfBounds(RecordElement),
ForeignDefinitionNotFound(ForeignDefinition),
FunctionExpected(Expression),
NoAlternativeFound(Case),
TypeN... |
// #![feature(async_closure)]
#[macro_use]
extern crate log;
mod client;
mod commands;
mod core;
#[macro_use]
mod macros;
mod monitors;
mod utils;
use crate::client::Zero2Client;
#[tokio::main]
async fn main() {
if let Err(_) = kankyo::load(false) {
warn!("Failed to load .env file. Falling back to env v... |
use super::Cartridge;
pub struct Console {
pub cartridge: Cartridge,
pub ram: Vec<i8>,
}
|
#[doc = "Reader of register SPINLOCK21"]
pub type R = crate::R<u32, super::SPINLOCK21>;
impl R {}
|
use crate::backend;
use crate::errors::FinError;
use crate::global::ROOT;
use crate::server;
use std::collections::HashMap;
lazy_static! {
static ref LOGGER: slog::Logger =
(*ROOT).clone().new(o!("mod" => "portfolio_server"));
}
pub fn get_incomplete_by_proj_id(
proj_id: i64,
res_tasks_backend: Re... |
use generated::DropboxUploadAPI;
use hyper::Client;
use hyper::header::{Authorization, ContentType};
use hyper::mime::{Mime, SubLevel, TopLevel};
use result::Result;
use serde_json;
header!{ (DropboxAPIArg, "Dropbox-API-Arg") => [String] }
const UPLOAD_URL: &'static str = "https://content.dropboxapi.com/2/files/uploa... |
use std::convert::From;
pub struct Rom {
bytes: Box<[u8]>,
//ptr: *mut u8,
}
impl Rom {
pub(crate) fn read_byte(&self, addr: u16) -> u8 {
self.bytes[addr as usize]
// let mask = (self.bytes.len() - 1) as u16;
// let addr = addr & mask;
// unsafe { *self.ptr.offset(addr a... |
use std::convert::TryInto;
use std::fs::File;
use std::fs::OpenOptions;
use std::os::unix::io::AsRawFd;
use cvt::cvt_r;
use libc::ioctl;
use mmap::MapOption;
use mmap::MemoryMap;
use vmm_sys_util::ioctl_iowr_nr;
use crate::error::Error;
use crate::error::Result;
const DRM_IOCTL_BASE: u32 = 'd' as u32;
#[derive(Clon... |
///// chapter 4 "structuring data and matching patterns"
///// program section:
//
fn main() {
let aliens =
["cherfer", "fynock", "shirack", "zuxu"];
let pa = &aliens;
println!("third item via pointer: {}", pa[2]);
}
///// output should be:
/*
third item via pointer: shirack
*/// end of output
|
#[doc = "Register `SDMMC_RESPCMDR` reader"]
pub type R = crate::R<SDMMC_RESPCMDR_SPEC>;
#[doc = "Field `RESPCMD` reader - Response command index"]
pub type RESPCMD_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:5 - Response command index"]
#[inline(always)]
pub fn respcmd(&self) -> RESPCMD_R {
RES... |
use std::io::{self};
fn get_result_1(file_content: &Vec<String>) -> usize {
let line = &file_content[0];
line.chars().filter(|&x| x == '(').count() - line.chars().filter(|&x| x == ')').count()
}
fn get_result_2(file_content: &Vec<String>) -> Option<usize> {
let mut floor = 0;
let line = &file_content[0... |
use parsing::*;
use std::mem::discriminant;
use std::string::ToString;
use shell::segments::*;
use std::collections::{ HashSet, HashMap };
#[derive( Debug, Clone, Eq, PartialEq, Hash )]
pub enum ShellTokenKind {
String( String ),
Interp( Vec<ShellToken> ),
Dollar,
Semi,
Amp,
Pipe,
// <
... |
use hdpath::{AccountHDPath};
pub struct WalletConf {
pub seed: [u8; 64],
pub account: AccountHDPath,
}
#[derive(Clone)]
pub struct ExecutionConf {
pub start: usize,
pub end: usize,
}
pub struct SearchConfig {
pub start: usize,
pub end: usize,
pub chunksize: usize,
pub passphrase: Stri... |
/// Potential validation errors that we might have.
#[derive(Debug)]
pub enum ValidationError {
/// The value is required.
Required,
/// Expected an email address.
Email,
/// Exceeds the maximum length.
MaxLength(usize),
/// Doesn't meet the minimum length.
MinLength(usize),
/// Does... |
#[path = "support/macros.rs"]
#[macro_use]
mod macros;
mod support;
use criterion::{criterion_group, criterion_main, Criterion};
use glam::Vec4;
use std::ops::Mul;
use support::random_vec4;
bench_binop!(
vec4_mul_vec4,
"vec4 mul vec4",
op => mul,
from1 => random_vec4,
from2 => random_vec4
);
benc... |
#![recursion_limit = "128"]
extern crate chrono;
extern crate config as config_crate;
#[macro_use]
extern crate derive_more;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate failure;
extern crate futures;
extern crate futures_cpupool;
extern crate hyper;
extern crate hyper_tls;
#[macro_use]
extern crate log;... |
use crate::{
grid::config::ColoredConfig,
grid::records::{ExactRecords, Records, RecordsMut, Resizable},
settings::TableOption,
};
use super::Panel;
/// Header inserts a [`Panel`] at the top.
/// See [`Panel`].
#[derive(Debug)]
pub struct Header<S>(S);
impl<S> Header<S> {
/// Creates a new object.
... |
//! Codes for each MetroRail line.
use crate::{
error::Error,
rail::{client::responses, traits::NeedsLine},
requests::Fetch,
};
use serde::{
de::{Deserializer, Error as SerdeError},
Deserialize,
};
use std::{error, fmt, str::FromStr};
/// All MetroRail lines.
#[derive(Debug, Copy, Clone, PartialEq)... |
//! Pre-defined SDP solver
use super::prelude::*;
use super::matsvd::{MatSVD, SVDS};
use super::matlinalg;
use std::io::Write;
macro_rules! writeln_or {
( $( $arg: expr ),* ) => {
writeln!( $( $arg ),* ).or(Err("log: I/O Error"))
};
}
use std::cell::RefCell;
/// Semidefinite program
///
/// <script... |
//! Types used to communicate with the drawing backend.
mod color;
mod context;
mod fillmode;
mod texcoord;
mod text;
pub use color::*;
pub use context::*;
pub use fillmode::*;
pub use texcoord::*;
pub use text::*;
use std::ops;
use std::sync::atomic::{AtomicUsize, Ordering};
/// Unique texture id.
#[derive(Debug, Cl... |
mod commands;
mod consume;
mod data;
mod publish;
mod register;
pub use commands::*;
pub use consume::*;
pub use publish::*;
pub use register::*;
use crate::{
backend::{Backend, Token},
data::SharedDataBridge,
examples::data::ExampleData,
};
use anyhow::Error;
use data::CoreExampleData;
use drogue_cloud_s... |
//! Utilities for working with Sutron-style data.
//!
//! This includes stuff like datetime parsing and SBD message reconstruction.
pub mod message;
pub use self::message::Message;
use chrono::{DateTime, ParseError, TimeZone, Utc};
/// The format of Sutron datetimes.
pub const DATETIME_FORMAT: &'static str = "%m/%d/... |
use super::schema::stats;
use super::Website;
use chrono::NaiveDateTime;
use diesel::Queryable;
use serde::Serialize;
use std::collections::BTreeMap;
pub trait CmpStat {
fn cmp(&mut self, is_new_user: bool, is_new_session: bool, duration: f32);
}
#[derive(
Serialize, Associations, AsChangeset, Queryable, Part... |
use super::api::ApiClient;
use clap::{App, Arg, ArgMatches};
use fuzzy_filter::FuzzyFilter;
use twitch_api2::helix::tags::TwitchTag;
pub fn get_tags_app<'a>() -> App<'a, 'a> {
App::new("tags")
.about("manipulate a streams tags")
.arg(
Arg::with_name("locale")
.short("i")... |
use colored::*;
use rand::{Rng, prelude::ThreadRng, thread_rng};
use terminal_size::{terminal_size};
use std::char;
use std::{thread, time};
use std::env;
fn random_line(width: u16, mut rng: ThreadRng) -> String {
let mut res = String::new();
for _ in 0..width {
let print_or_not = rng.gen_range(0, 3) ... |
use super::model::Favorite;
pub fn search(searched_word: &str, favorites: Vec<Favorite>) -> Vec<Favorite> {
favorites
.into_iter()
.filter(|favorite| favorite.name().contains(searched_word))
.collect::<Vec<Favorite>>()
}
|
use std::process::exit;
use structopt::StructOpt;
pub fn get_args() -> Args {
Args::from_optargs(OptArgs::from_args())
}
#[derive(Debug, StructOpt)]
pub struct OptArgs {
#[structopt(short = "h", long = "height")]
pub height: Option<u16>,
#[structopt(short = "w", long = "width")]
pub width: Option<u16>
}
pub s... |
/* Copyright 2020 Yuchen Wong*/
use opencv::core::{Mat, MatExprTrait, Vec3b, Vec3f};
use opencv::prelude::*;
use opencv::types::VectorOfMat;
use std::error::Error;
use std::time::SystemTime;
#[path = "../base/math_utils.rs"] mod math_utils;
#[path = "../base/opencv_utils.rs"] mod opencv_utils;
use math_utils::{hat};... |
use sudo_test::{Command, Env};
use crate::{Result, SUDOERS_ALL_ALL_NOPASSWD};
macro_rules! assert_snapshot {
($($tt:tt)*) => {
insta::with_settings!({
prepend_module_to_snapshot => false,
snapshot_path => "../snapshots/secure_path",
}, {
insta::assert_snapshot!(... |
// Copyright 2020 The Grin 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 by applicable law or agree... |
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::{KvsError, Result};
#[allow(non_snake_case)]
pub struct KvStore {
path: PathBuf,
}
impl KvStore {
pub fn open(path: impl Into<PathBuf>) -> Result<KvStore> {
let path = path.into();
... |
//! A partially-parallel young generation collector.
//!
//! Reading the journal into the root map is single-threaded.
//!
//! This is similar in construction to ParHeap, except that this object map must deal
//! with reference counts from the journal.
use std::cmp::max;
use std::mem::transmute;
use std::raw::TraitOb... |
use git2::Repository;
use std::{
fmt::{self, Display},
path::Path,
};
#[derive(Debug)]
pub enum RepositoryError {
/// The directory is ocupied and a repository cant be opend there.
OcupiedDir,
CantOpenDir(std::io::Error),
LibGit2Error(git2::Error),
/// The origin of the repo in the given f... |
/// An enum to represent all characters in the MiscellaneousSymbols block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum MiscellaneousSymbols {
/// \u{2600}: '☀'
BlackSunWithRays,
/// \u{2601}: '☁'
Cloud,
/// \u{2602}: '☂'
Umbrella,
/// \u{2603}: '☃'
Snowman,
/// \u{26... |
pub mod inputs;
pub mod moves;
pub mod plugin;
pub mod spawner;
pub mod util;
pub use inputs::*;
pub use moves::*;
pub use plugin::*;
pub use spawner::*;
pub use util::*;
|
use crate::error::{check_status, Error};
use crate::ErrorKind;
use std::ptr;
/// A range of floating-point values, and a step-by amount
#[derive(Clone)]
pub struct Range(uhd_sys::uhd_range_t);
impl Default for Range {
fn default() -> Self {
Range(uhd_sys::uhd_range_t {
start: 0.0,
... |
use std::cmp::max;
use std::io::{self, BufRead};
fn fuel(mass: u64) -> u64 {
max(mass / 3, 2) - 2
}
fn total_fuel(mass: u64) -> u64 {
let mut total = 0u64;
let mut extra_fuel = fuel(mass);
while extra_fuel > 0 {
total += extra_fuel;
extra_fuel = fuel(extra_fuel);
}
total
}
#[c... |
//! Implements game I/O using standard input and standard output.
use super::io::{Score, IO};
use super::lander::Lander;
use std::error::Error;
use std::io;
use std::io::prelude::*;
use std::marker::{Send, Sync};
use std::process;
use std::str::FromStr;
/// Implementation of the `lunar::io::IO` trait using standard ... |
use serde_derive::*;
use std::io::Read;
#[derive(Serialize, Deserialize, Debug)]
pub struct Person {
name: String,
age: Option<i32>,
dob: Option<String>,
children: Vec<Person>,
}
fn main() -> anyhow::Result<()> {
let mut v = Vec::new();
for a in std::env::args().skip(1) {
let mut s = S... |
/*
* 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
*/
/// Creator : Object describing the creator of the shared element.
#[derive(Clone, Debug, PartialEq, ... |
use std::cell::RefCell;
use std::fmt::Formatter;
use std::rc::{Rc, Weak};
pub static mut DEBUG: bool = false;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CellValue {
Fixed(u8),
Unknown(Vec<u8>),
}
/// A representation of a single cell in a Sudoku grid. Don't make this directly; make a Grid.
pub struct Ce... |
mod account;
pub mod block;
mod gas;
mod log;
mod memory;
mod stack;
use tiny_keccak::keccak256;
use asm::instruction::{Instruction, ProgramReader};
use bigint::{Address, Gas, U256, U512};
use errors::{Error, Result};
use rlp;
use std::cmp;
use vm::account::AccountManager;
use vm::block::Block;
use vm::gas::GasMeter;... |
use std::path::Path;
use crate::error::*;
/// Represents an input markup format for a config file.
///
/// The variants that exist correspond to the features that have been enabled.
/// For example, if the `json-parsing` feature is not enabled, then the
/// `Format::Json` variant will not exist.
#[derive(Debug, Clone... |
use std::ops::{Mul, MulAssign, Div, DivAssign};
use alga::general::Real;
use alga::linear::Rotation;
use core::ColumnVector;
use core::dimension::{DimName, U1, U3, U4};
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
use geometry::{PointBase, RotationBase, IsometryBase, TranslationBase, UnitQua... |
use crate::rtb_type_strict;
rtb_type_strict! {
PlacementPosition,
AboveTheFold=1;
Locked=2;
BelowTheFold=3;
Header=4;
Footer=5;
Slidebar=6;
Fullscreen=7
}
|
use std::io;
use std::io::Result;
use std::io::Write;
use std::time::Duration;
use termion::color;
use termion::cursor;
use termion::event::Key;
use termion::input::TermRead;
use termion::raw::IntoRawMode;
use tetris::Game;
use tetris::State;
mod draw;
fn main() -> Result<()> {
let stdout = io::stdout();
le... |
pub mod atcoder;
pub mod input;
pub mod output;
pub mod binary_indexed_tree;
pub mod binary_search;
pub mod group;
pub mod prime;
pub mod union_find;
pub mod vector;
|
#![feature(trace_macros)]
#[macro_use]
extern crate mac_derive;
use std::marker::PhantomData;
#[enum_repr(rename_all = "UPPERCASE", other(Meta1, Meta2))]
#[repr(C)]
#[derive(Debug, EnumRepr)]
#[enum_repr(default(PathBaseDefault))]
#[cfg_attr(target_os = "linux", enum_repr(rename_all = "UPPERCASE"))]
#[enum_repr(renam... |
use std::str;
pub fn index_of_first_null_byte(seq: &[u8]) -> Option<usize> {
let null_byte: u8 = 0x0;
for (i, item) in seq.iter().enumerate() {
if *item == null_byte {
return Some(i);
}
}
None
}
// Given a null-terminated sequence of bytes, return a slice without the null b... |
--- cargo-crates/cpal-0.10.0/src/platform/mod.rs.orig 2019-07-05 18:30:36 UTC
+++ cargo-crates/cpal-0.10.0/src/platform/mod.rs
@@ -456,7 +456,7 @@ macro_rules! impl_platform_host {
}
// TODO: Add pulseaudio and jack here eventually.
-#[cfg(any(target_os = "linux", target_os = "freebsd"))]
+#[cfg(any(target_os = "li... |
use anchor_lang::prelude::*;
declare_id!("4H8RWS5zZsj34WitF4JEuVLUxmsQgYBA9XxWBQBT52Sz");
mod quotes_gif_internals {
use super::*;
pub fn do_vote(base_account: &mut Account<BaseAccount>, index: usize, vote: Vote) -> Result<()> {
if index < base_account.gif_list.len() {
let mut item = &mut base_account.... |
#[doc = "Register `CDCFGR1` reader"]
pub type R = crate::R<CDCFGR1_SPEC>;
#[doc = "Register `CDCFGR1` writer"]
pub type W = crate::W<CDCFGR1_SPEC>;
#[doc = "Field `HPRE` reader - CPU domain AHB prescaler Set and reset by software to control the division factor of rcc_hclk3 and rcc_aclk. Changing this division ratio has... |
use std::ffi::{CString};
use std::os::raw::{c_char};
mod handler;
#[no_mangle]
pub extern fn _planetr_run_func(req_json: *mut c_char) -> *const c_char {
let reqjs = match planetr::wasm::wasm_parse_func_args(req_json){
Ok(reqjs) => reqjs,
Err(err) => return planetr::wasm::wasm_error(&err.to_string... |
//! Z80 CPU module
use crate::{
opcode::{
execute_bits, execute_extended, execute_normal, execute_pop_16, execute_push_16, Opcode,
Prefix,
},
RegName16, Regs, Z80Bus,
};
/// Interrupt mode enum
#[derive(Debug, Clone, Copy)]
pub enum IntMode {
Im0,
Im1,
Im2,
}
impl From<IntMode... |
use ::components::find_named_child;
use ::waiting_late_init::*;
use amethyst::core::*;
use amethyst::ecs::*;
use amethyst_editor_sync::*;
/// Key entities in the hierarchy of the revolver model.
///
/// These entities are key points in the hierarchy of the revolver model, and are manipulated
/// at runtime in order to... |
/// Conway's Game of Life
extern crate rand;
use rand::Rng;
use std::time::Duration;
use std::thread;
const F: usize = 54;
const C: usize = 70;
const DELAY_MS : u64 = 100;
fn main() {
let mut canvas : [[bool; C]; F] = [[false; C]; F];
let mut vecinos : [[u8; C]; F] = [[0; C]; F];
// Estado inicial ... |
//! The offline state submodule.
use std::sync::mpsc::Receiver;
use state::State;
use input::Input;
use input::help::print_help;
/// Enter the offline state.
pub fn start(input_rx: &Receiver<Input>) -> State {
match input_rx.recv() {
Ok(input) => handle_input(input),
Err(e) => {
prin... |
// Copyright 2016 Leo Schwarz <mail@leoschwarz.com>
//
// 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 la... |
mod medal_count;
mod rarity;
mod user_value;
use std::sync::Arc;
use twilight_model::application::interaction::{
application_command::CommandOptionValue, ApplicationCommand,
};
use crate::{
commands::{MyCommand, MyCommandOption},
custom_client::{
Badges, LovedMapsets, RankedMapsets, Replays, Stan... |
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize)]
pub struct ProducerServerMsg {
pub msg_type: ProducerServerType,
}
#[derive(Debug, Serialize)]
pub enum ProducerServerType {
Info(Info),
GameEnded,
TurnAdvanced(f64, f64),
TurnInfo(TurnInfo),
ChoiceSubmitted(f64, f64),
ChoiceFailed(String),
NewO... |
#![allow(dead_code)]
#![allow(unused_assignments)]
#![allow(unused_mut)]
#![allow(unused_variables)]
static ARRAY1_SIZE: usize = 16;
// static CACHE_HIT_THRESHOLD: usize = 80;
static CACHE_HIT_THRESHOLD: usize = 500;
extern {
fn get_host_info() -> i64;
fn get_data_size() -> i64;
fn get_data3() -> i64;
... |
#[doc = "Register `TX_LPI_TRAN_CNTR` reader"]
pub type R = crate::R<TX_LPI_TRAN_CNTR_SPEC>;
#[doc = "Field `TXLPITRC` reader - TXLPITRC"]
pub type TXLPITRC_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - TXLPITRC"]
#[inline(always)]
pub fn txlpitrc(&self) -> TXLPITRC_R {
TXLPITRC_R::new(s... |
// Copyright 2019 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.
use {failure::Error, fidl_fuchsia_settings::*};
pub async fn command(
proxy: AccessibilityProxy,
audio_description: Option<bool>,
screen_reade... |
use crate::*;
use std::fs::DirBuilder;
pub struct Xz;
pub type EditorXzInstaller = Installer<UnityEditor, Xz, InstallerWithDestination>;
pub type ModuleXzInstaller = Installer<UnityModule, Xz, InstallerWithDestination>;
impl<V, I> Installer<V, Xz, I> {
fn untar<P, D>(&self, source: P, destination: D) -> Result<()>... |
// TODO: replace with actual types generated from .xsd
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
pub struct Lang {}
|
extern crate futures;
#[macro_use]
extern crate mime;
extern crate hyper;
extern crate slog;
extern crate tokio_core;
extern crate papers;
extern crate serde_json as json;
use futures::future;
use futures::{Future, Stream, Sink};
use hyper::client::{Client, Request};
use hyper::server;
use hyper::header::ContentType;
... |
extern crate RustSucT4ever_lib;
extern crate bv;
use bv::{BitVec};
use RustSucT4ever_lib::common_tree::BpLoudsCommonTrait;
use RustSucT4ever_lib::bp::*;
#[test]
fn test_pre_rank(){
let test_tree = create_test_tree();
assert_eq!(test_tree.pre_rank(0), 1);
assert_eq!(test_tree.pre_rank(1), 2);
assert_eq... |
#![allow(dead_code)]
use std::marker::PhantomData;
use expr::*;
pub struct Symbol<S: Sym>{
s: PhantomData<S>
}
impl <S: Sym>Expr for Symbol<S> {
fn to_string() -> String {
S::to_string()
}
}
pub trait Sym {
fn to_string() -> String;
}
pub trait SymChar{
fn to_string() -> String;
}
pub str... |
fn main() {
let string = String::from("Denisovici");
let length = calculate_lenght(&string);
println!("The lenght of {} is {}", string, length);
let mut hello = String::from("Hello");
muttable_reference(&mut hello);
println!("{}", hello);
muttable_reference(&mut hello);
}
fn calcula... |
use std::convert::TryInto;
use crate::models::{ComicId, ImageType};
use crate::util::NewsUpdater;
use anyhow::{anyhow, Context, Result};
use chrono::{DateTime, Datelike, Duration, NaiveTime, TimeZone, Timelike, Utc, Weekday};
use const_format::concatcp;
use database::models::Comic as DatabaseComic;
use database::DbPoo... |
use std::collections::VecDeque;
type Line = VecDeque<char>;
fn main() {
let (score, incomplete_lines) = part1();
println!("First solution: {}", score);
println!("Second solution: {}", part2(incomplete_lines));
}
fn part1() -> (usize, Vec<Line>) {
let mut score = 0;
let mut input = input();
i... |
use tide::{Request, Response, StatusCode, Error};
use crate::libs::ctx::Context;
use crate::libs::multipart::read_multipart_data;
use crate::email::Email;
pub async fn parse_inbound_payload(mut req: Request<Context>) -> tide::Result {
let res = Response::new(StatusCode::Ok);
let remote = req.remote().ok_or(Er... |
pub fn read<T: std::str::FromStr>() -> T {
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok();
s.trim().parse().ok().unwrap()
}
pub fn read_vec<T: std::str::FromStr>() -> Vec<T> {
read::<String>()
.split_whitespace()
.map(|e| e.parse().ok().unwrap())
.collect()
}... |
fn main() {
let color = "red";
let fav = format!("my fav = {}", color);
println!("{}", fav);
let fav_num = format!("fav num = {}", 42);
println!("{}", fav_num);
let duck = format!("{0} {0} {1} {0}", "duck", "goose");
println!("{}", duck);
let name = format!("{first}, {last}", first =... |
use amethyst::assets::{RonFormat, PrefabLoader};
use amethyst::core::ecs::World;
/*
pub fn load_prefab<T>(prefab_name : &str, world: &mut World) {
let prefab_handle = world.exec(|loader: PrefabLoader<'_, T>| {
loader.load(prefab_name, RonFormat, ())
});
world.insert(prefab_handle);
}
*/ |
extern crate diffgeom;
extern crate gr_engine;
#[macro_use]
extern crate generic_array;
extern crate numeric_algs;
use diffgeom::coordinates::Point;
use diffgeom::tensors::Vector;
use gr_engine::coord_systems::schwarzschild::{Mass, Schwarzschild};
use gr_engine::particle::Particle;
use numeric_algs::integration::{DPIn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.