text stringlengths 8 4.13M |
|---|
use prelude::*;
mod api;
mod config;
mod models;
mod node;
mod prelude;
mod repo;
#[actix_rt::main]
async fn main() {
if let Err(e) = run().await {
eprintln!("Node failed:\n\n{:?}", e);
}
}
async fn run() -> Result<()> {
dotenv::dotenv().ok();
env_logger::init();
log::info!("Starting nod... |
//! A concurrent work-stealing deque.
//!
//! This data structure is most commonly used in schedulers. The typical setup involves a number of
//! threads where each thread has its own deque containing tasks. A thread may push tasks into its
//! deque as well as pop tasks from it. Once it runs out of tasks, it may steal... |
pub struct BootCodeComputer {
accumulator: i64,
code: Vec<(String, i64)>,
instruction_index: usize,
}
impl BootCodeComputer {
pub fn new(code: &Vec<String>) -> BootCodeComputer {
let mut parsed_code = Vec::new();
for i in code {
parsed_code.push(BootCodeComputer::parse_instr... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - TZSC control register"]
pub tzsc_cr: TZSC_CR,
_reserved1: [u8; 12usize],
#[doc = "0x10 - TZSC secure configuration register 1"]
pub tzsc_seccfgr1: TZSC_SECCFGR1,
#[doc = "0x14 - TZSC secure configuration register 2"... |
/*
Patterns that will match for any possible value passed are irrefutable. An
example would be x in the statement let x = 5; because x matches anything and
therefore cannot fail to match. Patterns that can fail to match for some
possible value are refutable. An example would be Some(x) in the expression if
let Some... |
use std::sync::Arc;
use tokio::{
net::{ToSocketAddrs, UdpSocket},
sync::mpsc,
};
use crate::{handle::GossipHandle, reactor::Reactor, Dispatcher};
/// Gossip subsystem configuration and initialisation.
#[derive(Debug)]
pub struct Builder<T> {
seed_addrs: Vec<String>,
dispatcher: T,
metric: Arc<met... |
// Copyright 2023 Datafuse Labs.
//
// 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 agre... |
use bevy::{
core::Bytes,
prelude::*,
reflect::TypeUuid,
render::{
mesh::shape,
pipeline::{
BlendFactor, BlendOperation, BlendState, ColorTargetState, ColorWrite, CompareFunction,
CullMode, DepthBiasState, DepthStencilState, FrontFace, PipelineDescriptor,
... |
use core::fmt::{self, Debug};
use futures::future::{BoxFuture, FutureExt};
use futures::task::ArcWake;
use crate::executor::EXECUTOR;
use crate::prelude::*;
use crate::sched::SchedInfo;
use crate::task::{LocalsMap, TaskId};
pub struct Task {
tid: TaskId,
sched_info: SchedInfo,
future: Mutex<Option<BoxFut... |
use crate::objects::*;
use std::collections::HashMap;
pub fn add_action(e: &mut exec::Exec, data: HashMap<String, action::ActionData>) {
let (player_id, exec_id) = (&p.id, &e.id);
let mut id = "";
let action = action::Action::new(id, player_id, exec_id, data);
}
#[cfg(test)]
mod tests {
use crate::obj... |
use actix_web::{http::StatusCode, HttpResponse, Json};
use bigneon_api::controllers::cart;
use bigneon_api::controllers::cart::{CartResponse, PaymentRequest};
use bigneon_db::models::*;
use bigneon_db::schema::orders;
use chrono::prelude::*;
use chrono::Duration;
use diesel;
use diesel::prelude::*;
use serde_json;
use ... |
extern crate rand;
extern crate termion;
use crate::menu::main_menu;
use rand::Rng;
use std::env;
use std::fs::File;
use std::io::Read;
use std::io::{stdin, stdout, Write};
use std::process::exit;
use termion::clear;
use termion::color;
use termion::event::Key;
use termion::input::TermRead;
use termion::raw::IntoRawMod... |
use actix_identity::{CookieIdentityPolicy, IdentityService};
use actix_web::{middleware, web, App, HttpServer};
use api::config;
use diesel::prelude::*;
use diesel::r2d2::{self, ConnectionManager};
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
dotenv::dotenv().ok();
std::env::set_var("RUST_LOG", "... |
use crate::{
a_sync::AsyncAmPsCore,
conn::AmConnCore,
protocol::{parts::AmRsCore, Part, PartAttributes, PartKind, ReplyType, Request, RequestType},
HdbError, HdbResult, ResultSetMetadata, Row, Rows, ServerUsage,
};
use std::sync::Arc;
// the references to the connection (core) and the prepared stateme... |
use std::cell::RefCell;
use std::collections::VecDeque;
use ggez::graphics as ggraphics;
use crate::graphics::drawable::*;
use crate::graphics::object::sub_screen;
use crate::graphics::object::sub_screen::SubScreen;
use crate::graphics::object::*;
use crate::numeric;
struct DebugScreen {
font_info: FontInformati... |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate xml;
... |
use tge::error::GameResult;
use tge::math::Angle;
use tge::engine::{Engine, EngineBuilder};
use tge::window::WindowConfig;
use tge::graphics::*;
use tge::game::Game;
use chrono::{Local, Timelike};
struct App {
clock_disk: Texture,
hour_angle: Angle,
minute_angle: Angle,
second_angle: Angle,
}
impl App... |
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use juniper::InputValue;
use juniper_benchmarks as j;
fn bench_sync_vs_async_users_flat_instant(c: &mut Criterion) {
// language=GraphQL
const ASYNC_QUERY: &str = r#"
query Query($id: Int) {
users_async_instant(ids: ... |
#[doc = "Reader of register COMP_C7CSR"]
pub type R = crate::R<u32, super::COMP_C7CSR>;
#[doc = "Writer for register COMP_C7CSR"]
pub type W = crate::W<u32, super::COMP_C7CSR>;
#[doc = "Register COMP_C7CSR `reset()`'s with value 0"]
impl crate::ResetValue for super::COMP_C7CSR {
type Type = u32;
#[inline(always... |
// use std::fmt::Write;
use std::io;
use std::io::Write;
use crate::errors::ErrorBox;
use crate::solver::IndexedTerm;
pub trait Renderer: io::Write {
fn set_names(&mut self, names: Vec<String>);
fn name(&self, index: usize) -> String;
fn write_system<L: Iterator<Item = IndexedTerm>, R: Iterator<Item = Ind... |
#[derive(Serialize, Deserialize)]
pub enum Unit {
Meters,
Feet,
Inches,
Yards,
None,
}
pub fn parse_unit(unit: Unit) -> String {
match unit {
Unit::Meters => "Meters".to_string(),
Unit::Feet => "Feet".to_string(),
Unit::Inches => "Inches".to_string(),
Unit::Yards... |
use crate::{
memory::{Memory, MAX_ADDR, MAX_INT},
operations::Operation,
values::{Register, Value},
};
use anyhow::{bail, Result};
use std::io;
struct InputBuffer {
buffer: Vec<u8>,
cursor: usize,
}
impl InputBuffer {
fn next(&mut self) -> u8 {
if self.cursor == self.buffer.len() {
... |
#![deny(warnings)]
extern crate futures;
extern crate tokio_mock_task;
extern crate tokio_sync;
use tokio_mock_task::*;
use tokio_sync::mpsc;
use futures::prelude::*;
use std::sync::Arc;
use std::thread;
trait AssertSend: Send {}
impl AssertSend for mpsc::Sender<i32> {}
impl AssertSend for mpsc::Receiver<i32> {}
... |
use juniper::{graphql_interface, GraphQLInputObject};
#[derive(GraphQLInputObject)]
pub struct ObjB {
id: i32,
}
#[graphql_interface]
struct Character {
id: ObjB,
}
fn main() {}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "System_Profile_SystemManufacturers")]
pub mod SystemManufacturers;
#[link(name = "windows")]
extern "system" {}
pub type AnalyticsVersionInfo = *mut ::core::ffi::c_void;
pub type HardwareT... |
use super::Var;
pub struct Parameters(pub Vec<Var>);
macro_rules! conversion_wrapper {
( $( ($fn_name:ident, $fn_wrapped:ident, $result:ident) $(,)? )* ) => {
$(
#[inline]
pub fn $fn_name(&self) -> Result<Vec<$result>, String> {
Ok(self
.0
.iter()
... |
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 ... |
use darling::{util::Flag, FromDeriveInput, FromVariant};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{DeriveInput, Ident};
use crate::generators::{self as gen, CodedVariant};
#[derive(FromDeriveInput)]
#[darling(supports(enum_any), attributes(sdk_event))]
struct Event {
ident: Ident,
... |
use std;
fn max(x: i32, y: i32) -> i32 {
if x < y { y } else { x }
}
enum Tree {
Empty,
Leaf(i32),
Node(Box<Tree>, Box<Tree>)
}
impl std::fmt::Display for Tree {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
&Tree::Empty => write!(f, "Empty: ({})", 0),
&Tree::Leaf... |
//! Code generation for `#[derive(GraphQLObject)]` macro.
use std::marker::PhantomData;
use proc_macro2::TokenStream;
use proc_macro_error::ResultExt as _;
use quote::ToTokens;
use syn::{ext::IdentExt as _, parse_quote, spanned::Spanned as _};
use crate::common::{diagnostic, field, parse::TypeExt as _, rename, scala... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct ACPI_REAL_TIME {
pub Year: u16,
pub Month: u8,
pub Day: u8,
pub Hour: u8,
pub Minute:... |
use coi::{container, Inject, Provide};
use std::sync::Arc;
trait Trait1: Inject {}
#[derive(Inject)]
#[coi(provides dyn Trait1 with Impl1)]
struct Impl1;
impl Trait1 for Impl1 {}
trait Trait2: Inject {}
#[derive(Inject)]
#[coi(provides dyn Trait2 with Impl2)]
struct Impl2;
impl Trait2 for Impl2 {}
trait Trait3: Inje... |
#[macro_use]
extern crate honggfuzz;
extern crate orion;
pub mod utils;
use utils::{make_seeded_rng, ChaChaRng, RngCore};
/// `orion::aead`
fn fuzz_aead(fuzzer_input: &[u8], seeded_rng: &mut ChaChaRng) {
let mut key = [0u8; 32];
seeded_rng.fill_bytes(&mut key);
let aead_key = orion::aead::SecretKey::from... |
use std::{
sync::Mutex,
collections::BTreeMap,
};
use chrono::*;
lazy_static::lazy_static! {
static ref EVENTS: Mutex<BTreeMap<DateTime<Local>, String>> = Mutex::new(BTreeMap::new());
}
#[wasm_interface]
pub fn add_event(date: String, title: String) -> Result<(), ()> {
let date = unimplemented!("parse... |
use core::iter::range;
pub static PIN_1 : u8 = 0x02;
pub static PIN_2 : u8 = 0x04;
pub static PIN_3 : u8 = 0x08;
fn set_config(port: u32, pins: u8) {
for bit in range(0, 8) {
if pins & (1 << bit) != 0 {
let pc_addr = port + ::map::gpio::O_PC;
let mut pc = ::io::read32(pc_addr);
... |
/// Provides utilities for running futures in tests.
use std::future::Future;
use tokio_current_thread::{block_on_all as block_on_all_old, spawn as spawn_old};
use tokio_futures::compat::into_01;
/// Run the executor bootstrapping the execution with the provided future.
///
/// This creates a new [`CurrentThread`] exe... |
//! This test was separated because the `metrics` crate uses a singleton recorder, so keeping a test
//! that relies on metric values in a separate binary makes more sense than using an inter-test
//! locking mechanism which can cause weird test failures without any obvious clue to what might
//! have caused those fail... |
use super::Constant;
pub fn len(args: Vec<Constant>) -> Constant {
let arg = args.get(0).unwrap();
match arg {
&Constant::List(ref l) => Constant::Integer(l.len() as i32),
_ => {
eprintln!("Invalid arguments passed to \"len\"!");
panic!()
}
}
} |
use swc_ecma_ast::*;
use swc_ecma_visit::{Fold, FoldWith};
struct OptionalCatchBinding;
noop_fold_type!(OptionalCatchBinding);
pub fn optional_catch_binding() -> impl Fold {
OptionalCatchBinding
}
impl Fold for OptionalCatchBinding {
fn fold_catch_clause(&mut self, mut cc: CatchClause) -> CatchClause {
... |
use procinfo::pid::{stat, stat_self, Stat};
use std::fs;
use std::io::Error;
use uname::uname;
fn main() -> Result<(), Error> {
let exec_order = exec_list()?;
println!(
"Commands: {:?}",
exec_order
.iter()
.map(|s| s.command.clone())
.rev()
.coll... |
use std::fmt::Display;
use color_eyre::eyre::WrapErr;
use color_eyre::eyre::{eyre, Result};
use semver::Identifier;
use serde::Deserialize;
use crate::{package_json, pyproject};
/// The various rules that can be used when bumping the current version of a project via
/// [`crate::step::Step::BumpVersion`].
#[derive(D... |
// Copyright 2023 Datafuse Labs.
//
// 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 agre... |
use common::aoc::{load_input, run_many, print_time, print_result};
fn main() {
let input = load_input("day03");
let (wires, dur_parse) = run_many(1000, || parse_input(&input));
let w1 = &wires[0];
let w2 = &wires[1];
let (res_part1, dur_part1) = run_many(1000, || w1.closest_intersection(&w2));
... |
pub mod vector;
pub mod vector2;
pub mod vector3;
pub use self::vector::*;
pub use self::vector2::*;
pub use self::vector3::*;
use crate::math;
use crate::types::Float;
use crate::Vector3f;
pub fn coordinate_system(v1: Vector3f) -> (Vector3f, Vector3f) {
let v2 = if v1.x.abs() > v1.y.abs() {
let v = v1.x ... |
use iox_query::pruning::NotPrunedReason;
use metric::{Attributes, U64Counter};
#[derive(Debug)]
pub struct PruneMetricsGroup {
/// number of chunks
chunks: U64Counter,
/// number of rows
rows: U64Counter,
/// estimated size in bytes
bytes: U64Counter,
}
impl PruneMetricsGroup {
fn new(me... |
extern crate semver;
extern crate cargo;
extern crate curl;
extern crate rustc_serialize;
#[macro_use]
mod easy_resolver;
mod composer_parser;
mod composer_vendor_parser;
mod dependency_container;
mod flatten_dependency_resolver;
use cargo::core::{Dependency, Summary};
use std::collections::HashMap;
use easy_resolver::... |
extern crate rand;
use self::rand::Rng;
trait SpeedController {
fn stop(&self);
}
struct EmergencyBrake;
impl SpeedController for EmergencyBrake {
fn stop(&self) {
println!("stop using EMERGENCY brake !!!");
}
}
struct PanicBrake;
impl SpeedController for PanicBrake {
fn stop(&self) {
... |
//! 烟雾传感器
#![no_main]
#![no_std]
#![feature(alloc_error_handler)]
use bluepill::clocks::*;
use bluepill::display::*;
use bluepill::hal::delay::Delay;
use bluepill::hal::gpio::gpioc::PC13;
use bluepill::hal::gpio::{Output, PushPull};
use bluepill::hal::prelude::*;
use bluepill::io::*;
use bluepill::led::*;
use bluepill... |
use std::fs::File;
use std::io;
use std::path::Path;
static ERROR_MESSAGE: &str = "same-file is not supported on this platform.";
// This implementation is to allow same-file to be compiled on
// unsupported platforms in case it was incidentally included
// as a transitive, unused dependency
#[derive(Debug, Hash)]
pub... |
//! `posix` compatible module for `not(any(unix, windows))`
use crate::{builtins::PyModule, PyRef, VirtualMachine};
pub(crate) fn make_module(vm: &VirtualMachine) -> PyRef<PyModule> {
let module = module::make_module(vm);
super::os::extend_module(vm, &module);
module
}
#[pymodule(name = "posix", with(supe... |
use super::*;
use bindings::{Windows::Win32::Foundation::*, Windows::Win32::System::Memory::*};
// TODO: why not Option<RawPtr>
pub fn heap_alloc(bytes: usize) -> Result<RawPtr> {
let ptr = unsafe { HeapAlloc(GetProcessHeap(), HEAP_NONE, bytes) };
if ptr.is_null() {
Err(E_OUTOFMEMORY.into())
} els... |
use crate::{Force, Point, MIN_DISTANCE};
use petgraph::graph::{Graph, IndexType, NodeIndex};
use petgraph::EdgeType;
pub struct CollideForce {
radius: Vec<f32>,
strength: f32,
iterations: usize,
}
impl CollideForce {
pub fn new<
N,
E,
Ty: EdgeType,
Ix: IndexType,
... |
#![crate_name = "syncazoom"]
use argh::FromArgs;
use chrono::offset::Utc;
use chrono::DateTime;
use cron::Schedule;
use job_scheduler::{Job, JobScheduler};
use jsonwebtoken::{encode, EncodingKey, Header};
use rusqlite::{params, Connection};
use serde::{Deserialize, Serialize};
use serde_json::value::Value;
use std::er... |
use assert_cmd::Command;
use std::fs;
use std::path::PathBuf;
pub struct CliSupport {}
impl CliSupport {
pub fn coco_run(path: PathBuf) -> Command {
let mut cmd = CliSupport::coco();
cmd.arg("-c")
.arg(format!("{}", path.into_os_string().to_str().unwrap()));
cmd
}
fn ... |
use crate::{config::Flavor, curse_api, tukui_api, utility::strip_non_digits, wowi_api};
use chrono::prelude::*;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::path::PathBuf;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AddonVersionKey {
Local,
Remote,
... |
use std::env;
use std::error::Error;
use std::ffi::OsStr;
use std::path::Path;
use assert_cmd::{assert::Assert, Command};
pub const MOCK_CMD_PATH: &'static str = env!("CARGO_BIN_EXE_retry-mock-cmd");
pub type TestResult<T = ()> = Result<T, Box<dyn Error>>;
pub struct RetryCommand {
retry: Command,
command: Vec<... |
use support::{decl_storage, decl_module, StorageValue, StorageMap,
dispatch::Result, ensure, decl_event, traits::Currency};
use system::ensure_signed;
use runtime_primitives::traits::{As, Hash};
use parity_codec::{Encode, Decode};
use rstd::prelude::Vec;
const AUCTION_DURATION: u64 = 24*600;
#[derive(Encode, Deco... |
use std::fmt;
use std::mem;
use std::slice;
use num;
use num::cast;
use approx;
use channel::{PosNormalBoundedChannel, ColorChannel, PosNormalChannelScalar, AngularChannelScalar,
ChannelFormatCast, ChannelCast};
use color;
use color::{Color, HomogeneousColor, FromTuple};
use convert;
use angle;
use hsv;
u... |
use std::fmt;
use std::ops::{
Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign,
};
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Vec3 {
pub x: f64,
pub y: f64,
pub z: f64,
}
pub fn vec3(x: f64, y: f64, z: f64) -> Vec3 {
Vec3 { x, y, z }
}
pub fn scalar(f: f... |
fn main(){
proconio::input!{n:String};
println!("{}",if 0 ==n.chars().filter(|x|x.to_string()=="7").count(){"No"}else{"Yes"})
} |
#[cfg(feature = "cli")]
use weather_util_rust::{config::Config, weather_opts::WeatherOpts, Error};
#[cfg(not(tarpaulin_include))]
#[cfg(feature = "cli")]
#[tokio::main]
async fn main() -> Result<(), Error> {
let config = Config::init_config(None)?;
match tokio::spawn(async move { WeatherOpts::parse_opts(&conf... |
//! GraphQL support for [url](https://github.com/servo/rust-url) types.
use crate::{graphql_scalar, InputValue, ScalarValue, Value};
#[graphql_scalar(with = url_scalar, parse_token(String))]
type Url = url::Url;
mod url_scalar {
use super::*;
pub(super) fn to_output<S: ScalarValue>(v: &Url) -> Value<S> {
... |
// Copyright 2019 The Tari Project
//
// 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 conditions and the following
// disclaim... |
use std::convert::identity;
use bincode::Options;
use serde::{Deserialize, Serialize};
use zerocopy::{AsBytes, ByteSlice};
#[derive(Serialize, Deserialize)]
pub struct Pair<'a> {
pub key: &'a [u8],
pub value: &'a [u8],
}
impl<'a> Pair<'a> {
fn to_bytes(&self) -> Vec<u8> {
bincode::options().seria... |
#[macro_use]
extern crate log;
#[macro_use]
extern crate yaserde_derive;
pub mod discovery;
pub mod schema;
pub mod soap;
mod transport;
mod utils;
|
use super::rule::{SigmaRule, SigmaRuleDetection, SigmaValues};
use std::sync::Arc;
mod agrupation;
use agrupation::{agrupation_from_rule, SigmaAgrupation};
use std::collections::BTreeMap;
use usiem::events::SiemLog;
use usiem::events::field::{SiemField, SiemIp};
mod value_modifiers;
mod matches;
use matches::*;
pub s... |
use std::fs::File;
use std::io::{BufReader, BufRead};
fn turn_left(old_heading: i32) -> i32 {
(old_heading + 3) % 4
}
fn turn_right(old_heading: i32) -> i32 {
(old_heading + 1) % 4
}
fn main() {
let input = File::open("input").expect("oeuaeouoeauoeuaeo");
// N0
// W3 E1
// S2
l... |
#[macro_use]
extern crate diesel;
use diesel::{
r2d2::{self, ConnectionManager},
PgConnection,
};
pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;
pub mod config;
pub mod error;
pub mod frontend;
pub mod models;
pub mod schema;
pub mod views;
|
extern crate serial;
use std::env;
use std::io;
use std::time::Duration;
use std::process;
use std::io::prelude::*;
use serial::prelude::*;
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let data = Arc::new(Mutex::new(0));
let run = Arc::new(Mutex::new(true));
let data_log = data.clone();
... |
use std::collections::HashMap;
fn main() {
assert_eq!(std::mem::size_of::<()>(), 0);
let mut h: HashMap<&str, ()> = HashMap::new();
h.insert("size of", ());
h.insert("value", ());
h.insert("is", ());
h.insert("zero.", ());
println!("{:?}", h);
// overflow!
let n1 = std::u8::MAX;
... |
#![allow(non_snake_case)]
use test_winrt_signatures::*;
use windows::core::*;
use Component::Signatures::*;
#[implement(Component::Signatures::ITestBoolean)]
struct RustTest();
impl RustTest {
fn SignatureBoolean(&self, a: bool, b: &mut bool) -> Result<bool> {
*b = a;
Ok(a)
}
fn ArraySign... |
use mav::ma::{MAddress, MChainShared, MTokenShared, MWallet, MTokenAddress};
use crate::{deref_type, ContextTrait,WalletError};
use mav::ma::Dao;
#[derive(Debug, Clone, Default)]
pub struct Address {
pub m: MAddress,
}
deref_type!(Address,MAddress);
impl Address{
pub async fn load(&mut self,context: &dyn Con... |
use abi_stable::{
nonexhaustive_enum::NonExhaustiveFor as NEFor,
StableAbi,
};
#[repr(u8)]
#[derive(StableAbi)]
#[sabi(kind(WithNonExhaustive(
size = 1,
align = 1,
)))]
#[sabi(with_constructor)]
pub enum TooLarge<T = u8> {
Foo,
Bar,
Baz(T),
}
const _: () = { std::mem::forget(NEFor::new(<To... |
/*
* Copyright 2020 Draphar
*
* 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 to in writi... |
/// returns the angle between the edges represented as vectors (x1, y1) and (x2, y2).
/// returns None if the angle could not be defined
pub fn edge_angle(x1: f32, y1: f32, x2: f32, y2: f32) -> Option<f32> {
let cos = (x1 * x2 + y1 * y2) / (x1.hypot(y1) * x2.hypot(y2));
let angle = cos.acos();
if angle.is_f... |
use chrono::NaiveDateTime;
use crate::schema::users;
#[derive(Serialize, Deserialize, Queryable)]
pub struct Users {
pub id: i32,
pub login: String,
pub password_hash: String,
pub role: String,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
}
#[derive(Deserialize, Insertable)]
... |
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 ... |
use crate::commands::{LllCommand, LllRunnable};
use crate::context::LllContext;
use crate::error::LllError;
use crate::window::LllView;
#[derive(Clone, Debug)]
pub struct Quit;
impl Quit {
pub fn new() -> Self {
Self::default()
}
pub const fn command() -> &'static str {
"quit"
}
p... |
//! Utilities
use std::borrow::Cow;
use std::error::Error;
use std::fs::{self, File};
use std::io::{self, Read};
use std::path::Path;
use flate2::read::GzDecoder;
use indicatif::{HumanBytes, ProgressBar, ProgressStyle};
use reqwest::{header, Client, Url};
use tar::Archive;
/// Download/Resume Downloading a file from... |
// Copyright (C) 2019, Cloudflare, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list... |
//inefficient and slow way
/*
fn testdivisible(test: i32, max: i32) -> bool{
let mut div: bool = true;
for i in 1..max+1{
if test%i != 0 {
div=false;
}
}
return div;
}
fn main(){
let mut count=1;
loop{
println!("{}", count);
if testdivisible(count, 2... |
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet, VecDeque};
use itertools::Itertools;
use whiteread::parse_line;
fn main() {
let (r, c): (usize, usize) = parse_line().unwrap();
let (sy, sx): (usize, usize) = parse_line().unwrap();
let (sy, sx) = (sy - 1, sx - 1);
let (gy, gx): (usize... |
#![type_length_limit = "2149570"]
#[cfg(target_os = "macos")]
extern crate tempdir;
pub mod errors {
pub use anyhow::{anyhow, bail, Context, Error, Result};
}
mod android;
pub mod config;
pub mod device;
mod host;
#[cfg(target_os = "macos")]
mod ios;
pub mod overlay;
pub mod platform;
pub mod project;
mod script;... |
use std::fmt::{self, Display};
use readme_interface::{AppenderBox, Appender_TO, BoxedInterface, ExampleLib, ExampleLib_Ref};
use abi_stable::{
export_root_module,
prefix_type::PrefixTypeTrait,
sabi_extern_fn,
sabi_trait::prelude::TD_Opaque,
std_types::{RString, RVec},
DynTrait,
};
/// The fun... |
#![deny(warnings, rust_2018_idioms)]
mod api;
use std::net::SocketAddr;
use structopt::StructOpt;
use tokio_compat_02::FutureExt;
#[derive(Clone, Debug, StructOpt)]
#[structopt(about = "Load target")]
pub struct Server {
#[structopt(long, parse(try_from_str), default_value = "0.0.0.0:8079")]
grpc_addr: Socke... |
// [Type-Safe Modular Hash-Consing](https://www.lri.fr/~filliatr/ftp/publis/hash-consing2.pdf)
#![allow(dead_code)]
use std::borrow::Borrow;
use std::collections::HashMap;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::rc::Rc;
use std::rc::Weak;
use std::sync::atomic::AtomicU64;
use std::syn... |
// Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
mod replica;
#[macro_use]
pub mod vr_fsm;
pub mod vr_msg;
pub mod states;
pub mod vr_ctx;
pub use self::vr_fsm::{
VrState
};
pub use self::vr_ctx::{
VrCtx
};
pub use self::replica::{
Replica,
Versioned... |
//! Wrap an external type to implement [Channels][crate::Channels] and
//! [ChannelsMut][crate::ChannelsMut].
mod interleaved;
pub use self::interleaved::Interleaved;
mod sequential;
pub use self::sequential::Sequential;
/// Wrap a `value` as an interleaved buffer with the given number of channels.
///
/// Certain i... |
use PT_FIRSTMACH;
pub type c_long = i32;
pub type c_ulong = u32;
pub type c_char = u8;
pub type __cpu_simple_lock_nv_t = ::c_int;
pub const PT_GETREGS: ::c_int = PT_FIRSTMACH + 1;
pub const PT_SETREGS: ::c_int = PT_FIRSTMACH + 2;
pub const PT_GETFPREGS: ::c_int = PT_FIRSTMACH + 3;
pub const PT_SETFPREGS: ::c_int = PT... |
use openexr_sys as sys;
use crate::{
core::{
channel_list::Channel,
cppstd::CppString,
error::Error,
refptr::{OpaquePtr, Ref, RefMut},
LevelMode, LevelRoundingMode,
},
flat::flat_image_level::{FlatImageLevelRef, FlatImageLevelRefMut},
};
use imath_traits::Bound2;
t... |
use serde::{
Deserialize,
Serialize,
};
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct LocalStorage {
pub username: Option<String>,
pub email: Option<String>,
pub token: Option<String>,
}
#[derive(Deserialize, Debug, Clone)]
pub struct ResponseLogin {
pub email: String,
pub use... |
extern crate poe_api as poe;
fn main() {
let data = poe::leagues()
.expect("Failed to get data.");
for league in data {
println!("{:?}", league);
}
}
|
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn serialize_synthetic_put_lexicon_input_body(
input: &crate::input::PutLexiconInput,
) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> {
let body = crate::serializer::PutLexiconInputBody {
content: &inp... |
#[doc = "Reader of register HPMS"]
pub type R = crate::R<u32, super::HPMS>;
#[doc = "Reader of field `BIDX`"]
pub type BIDX_R = crate::R<u8, u8>;
#[doc = "Reader of field `MSI`"]
pub type MSI_R = crate::R<u8, u8>;
#[doc = "Reader of field `FIDX`"]
pub type FIDX_R = crate::R<u8, u8>;
#[doc = "Reader of field `FLST`"]
pu... |
use piston_window::*;
use piston_window::text::Text;
use crate::widget::Widget;
use crate::widget::WidgetImpl;
use crate::widget::Rect;
pub struct GridPanel {
background_color: [f32; 4],
widget: WidgetImpl
}
impl GridPanel {
pub fn new(background_color: [f32; 4]) -> Self {
let widget = WidgetImpl... |
//! Low-level implementation details for libc-like runtime libraries such as
//! [origin].
//!
//! Do not use the functions in this module unless you've read all of their
//! code, *and* you know all the relevant internal implementation details of
//! any libc in the process they'll be used.
//!
//! These functions are... |
use rand::{self, Rng};
use super::Cmd;
use encode::Color;
use Cmd::*;
/// Definitions:
/// A "Bytebeat Unit" is a basic unit of a formula, typically
/// one to three commands in length. These should always end with
/// remaining value on the stack, so that one could place this unit anywhere
/// within a valid bytebeat... |
use crate::{datastore::prelude::*, users::service::get_user_by_email};
use actix_web::HttpRequest;
pub async fn authenticate(
client: &Client,
auth_data: super::AuthenticationData,
) -> Response<super::Session> {
// Getting user from db
let user = get_user_by_email(client, &auth_data.email).await?;
... |
use std::fmt;
use std::ops::{Deref, DerefMut};
use cranelift_entity::entity_impl;
use intrusive_collections::{intrusive_adapter, LinkedListLink, UnsafeRef};
use firefly_binary::BinaryEntrySpecifier;
use firefly_diagnostics::{Span, Spanned};
use firefly_syntax_base::Type;
use super::*;
#[derive(Copy, Clone, PartialE... |
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub enum Attachment {
Color(u32),
Depth,
Stencil,
DepthStencil,
}
impl Attachment {
pub(crate) fn to_flag(&self) -> u32 {
match self {
Attachment::Color(i) => glow::COLOR_ATTACHMENT0 + *i,
Attachment::Depth => glow... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.