text
stringlengths
8
4.13M
extern crate byteorder; extern crate leb128; pub mod binary; pub mod opcode;
/*! Link: https://adventofcode.com/2019/day/2 --- Day 2: 1202 Program Alarm --- On the way to your gravity assist around the Moon, your ship computer beeps angrily about a "1202 program alarm". On the radio, an Elf is already explaining how to handle the situation: "Don't worry, that's perfectly norma--" The ship com...
// This file is part of Substrate. // Copyright (C) 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 // // http://www.a...
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use move_core_types::{ errmap::{ErrorDescription, ErrorMapping}, language_storage::ModuleId, }; /// Given the module ID and the abort code raised from that module, returns the human-readable /// explanation of that abort if pos...
use async_graphql::{ErrorExtensions, FieldResult}; use uuid::Uuid; use db::Database; use schema::error::common::CommonError; use schema::object::user::UserObject; pub async fn get_all(db: &Database) -> FieldResult<Vec<UserObject>> { let users_row = db.get_users().await?; Ok(users_row.into_iter().map(UserObje...
use super::field_visitor::FieldVisitor; use serde::de::{Deserialize, Deserializer}; pub enum Field { FileId, Name, FolderId, Public, Extension, } impl<'de> Deserialize<'de> for Field { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { ...
//! Bindings for emulating a PostgreSQL server (protocol v3). //! You can find overview of the protocol at //! <https://www.postgresql.org/docs/10/protocol.html> #![feature(backtrace)] #![feature(type_ascription)] mod decoding; mod encoding; pub mod buffer; pub mod extended; pub mod pg_type; pub mod protocol; pub u...
use anyhow::{anyhow, bail, Result}; use std::net::ToSocketAddrs; use tokio::io::{self}; use std::{fs, net::SocketAddr, time::Instant}; #[tokio::main] async fn main() -> Result<()> { let dirs = directories::UserDirs::new().unwrap(); let path = dirs.home_dir(); let cert_path = path.join("cert.der"); let...
use std::collections::BTreeMap; use std::convert::TryInto; use std::sync::{Arc, Mutex}; use crate::error::{FormatContext, FormatError}; use crate::prim::ReadCursor; /// The integers corresponding to each of the possible values in a map. const TAG_BYTES: u16 = 1; const TAG_STRING: u16 = 2; const TAG_OFFSET_RANGE: u16 ...
//! YubiKey PC/SC transactions use crate::{ apdu::Response, apdu::{Apdu, Ins, StatusWords}, consts::{CB_BUF_MAX, CB_OBJ_MAX}, error::{Error, Result}, piv::{AlgorithmId, SlotId}, serialization::*, yubikey::*, Buffer, ObjectId, }; use log::{error, trace}; use std::convert::TryInto; use ze...
use crate::config::{factory_address}; use crate::models::{DeployPayload}; use crate::providers::ethereum::transaction::Transaction; use crate::providers::accounts::{check_fee, Estimation}; use crate::providers::ethereum::{to_string_result, Call, CallOptions, EthereumProvider}; use crate::providers::ethereum::types::Byt...
#![allow(dead_code)] #![allow(unused_variables)] /* 構造体がドロップされると、まず構造体自体がドロップされ、 その次にその子要素が個別に削除される。 */ struct Bar { x: i32, } struct Foo { bar: Bar, } fn main() { let foo = Foo { bar: Bar { x: 42 } }; println!("{}", foo.bar.x); // foo が最初にドロップ // 次にfoo.barがドロップ }
// Copyright (c) 2018 Atsushi Miyake // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or http://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 t...
#[async_std::main] async fn main() -> config_link::error::Result<()> { match config_link::read_option().await { Err(e) => { eprintln!("{}", e); } Ok(_) => {} } Ok(()) }
/* * Isilon SDK * * Isilon SDK - Language bindings for the OneFS API * * OpenAPI spec version: 5 * Contact: sdk@isilon.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ use std::borrow::Borrow; use std::rc::Rc; use futures; use futures::Future; use hyper; use super::{configuration, pu...
use quote::{quote}; use proc_macro::TokenStream; use syn::{parse_macro_input, AttributeArgs, ItemFn}; #[proc_macro_attribute] pub fn route(args: TokenStream, input: TokenStream) -> TokenStream { // let args = parse_macro_input!(args as AttributeArgs); let input = parse_macro_input!(input as ItemFn); let to...
use crate::protocol::ast::*; use super::symbol_table::*; use super::{Module, ModuleCompilationPhase, PassCtx}; use super::tokens::*; use super::token_parsing::*; use crate::protocol::input_source::{InputSource as InputSource, InputSpan, ParseError}; use crate::collections::*; /// Parses all the imports in the module t...
use bus::*; use err::BusError; use std::vec::Vec; use std::ops::Index; #[derive(Debug)] pub struct Mem { address_ranges: Vec<AddressRange>, ram: Vec<u8> } /// Memory is a Device with a single address range. impl Mem { pub fn new(start_address: usize, len: usize) -> Mem { Mem { address...
extern crate libc; use self::libc::*; pub const TINFL_LZ_DICT_SIZE: usize = 32768; #[repr(C)] #[allow(bad_style)] pub struct tinfl_huff_table { pub m_code_size: [u8; 288usize], pub m_look_up: [c_short; 1024usize], pub m_tree: [c_short; 576usize], } const TINFL_MAX_HUFF_TABLES: usize = 3; const TINFL_MAX...
use std::i32; pub fn atoi(s: &str) -> Option<i32> { enum Sign { Positive, Negative, } let mut sign = Sign::Positive; let st = s.trim_left(); let mut chars = st.chars(); if st.starts_with('-') { sign = Sign::Negative; chars.next(); } if st.st...
use crate::{ components::{ lists::{ContainerMsg, TrackList, TrackMsg}, tabs::{MusicTabModel, MusicTabMsg, MusicTabParams, TracksObserver}, }, loaders::QueueLoader, }; use relm::{Relm, Widget}; use relm_derive::widget; #[widget] impl Widget for QueueTab { view! { #[name="tracks_v...
use rand::{Rng, thread_rng}; use std::mem::swap; use color::RayTraceColor; use light::RayTraceShading; use sample::RayTraceSampleFilter; pub trait RayTraceSampling { fn apply(&self, x: f64, y: f64) -> (f64, f64); fn get_ray_count(&self) -> usize; } #[allow(dead_code)] pub struct RayTraceOutputParams { width: usiz...
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module lays out the basic abstract costing schedule for bytecode instructions. //! //! It is important to note that the cost schedule defined in this file does not track hashing //! operations or other native operations; the c...
#![no_std] #![no_main] #![feature(asm)] use panic_halt as _; extern crate stm32f1xx_hal as hal; use rtic::app; use cortex_m::{ asm::{ wfi,delay } //peripheral::SCB, }; use stm32f1xx_hal::{ prelude::*, pac::{RCC,USB}, pac, gpio::{ Floating, Input, Output, PushPull, gpioa::{PA11, PA12}, gpioc:...
use crate::parsing::{Parser, Expr, Precedence, ExprKind}; use regexlexer::Token; use crate::typechecking::Ty; use crate::error::Error; pub(crate) fn parse_prefix_op<'a>(parser: &mut Parser<'a>, token: Token<'a>) -> Result<(ExprKind, Option<Ty>), Error> { let expr = parser.parse_expression(Precedence::ZERO)?; l...
use beryllium::*; use rusty_boy_advance::GBABox; #[allow(clippy::unneeded_field_pattern)] pub fn run(mut gba: GBABox, frames_to_run: u32) -> Result<(), Box<dyn std::error::Error>> { let mut frames_left_to_run = frames_to_run; let sdl = beryllium::init()?; let mut surface = sdl.create_rgb_surface(240, 160, Surfac...
use core::convert::{TryFrom, TryInto}; use core::result::Result; use crate::{check_args_len, FromRaw, Serialize}; const TASK_DATA_LEN: usize = 85; const TASK_TYPE_ARGS_LEN: usize = 1; #[derive(Debug, Copy, Clone, PartialOrd, PartialEq, Ord, Eq)] #[repr(u8)] pub enum TaskCellMode { Task = 0, Challenge, } impl...
//! Helper utilities for working with [`predicates`](https://docs.rs/predicates), //! inspired in part by //! [Google Mock matchers](https://github.com/google/googletest/blob/master/googlemock/docs/cheat_sheet.md#matchers-matcherlist). pub use predicates; pub use predicates_tree; /// Make predicate-based assertions w...
use std::convert::TryFrom; use aglet_text::Span; use crate::parse::ast::*; use crate::parse::error::*; use crate::parse::input::{ expect_tok, illegal_next_tok, match_one, match_tok, matches_one, matches_tok, Input, }; use crate::tokenize::{self, Token, TokenKind}; /// Parse regular expres...
use std::collections::HashMap; use std::convert::TryInto; use std::num::Wrapping; use std::time; use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{anyhow, Context, Result}; use async_channel::{Receiver, Sender}; use async_io::Timer; use async_tungstenite::async_std as async_ws; use async_tungstenite::async_std::Co...
mod binding; use binding::{ cn_msg, nlmsghdr, proc_cn_mcast_op, sockaddr_nl, CN_IDX_PROC, NETLINK_CONNECTOR, PROC_CN_MCAST_LISTEN, }; use libc; use std::io::{Error, Result}; // these are some macros defined in netlink.h fn nlmsg_align(len: usize) -> usize { (len + 3) & !3 } fn nlmsg_hdrlen() -> usize { ...
use serde::{Deserialize, Serialize}; use std::io; #[allow(non_snake_case)] #[derive(Debug, Deserialize, Serialize)] struct Body { id: String, name: String, englishName: String, isPlanet: bool, semimajorAxis: f64, perihelion: f64, aphelion: f64, eccentricity: f64, inclination: f64, }...
use std::future::Future; /// A future-based worker that for each input, one output is produced. pub trait Oneshot: Future { /// Incoming message type. type Input; /// Creates an oneshot worker. fn create(input: Self::Input) -> Self; }
use log; use simplelog; pub fn init() { let log_config = simplelog::ConfigBuilder::new() .set_time_format_str("[%+]") .build(); simplelog::CombinedLogger::init(vec![ simplelog::TermLogger::new( simplelog::LevelFilter::Info, log_config.clone(), simple...
extern { fn c_debug(val: i32); } fn main() { println!("Hello, world!"); unsafe {c_debug(8);} }
#![allow(clippy::field_reassign_with_default)] pub mod event_types; use crate::event_types::EventType; pub mod repos; use crate::repos::Repo; pub mod influx; pub mod tracking_numbers; #[macro_use] extern crate serde_json; use std::collections::HashMap; use std::convert::TryInto; use std::env; use std::fs::File; use st...
fn main() { ctex::par_util::par_write_ctex("input/*.png", "output"); }
use jsonwebtoken::{encode, decode, Header, Algorithm, Validation, EncodingKey, DecodingKey}; use serde_derive::{Serialize, Deserialize}; use actix_web::{HttpRequest}; pub const X_TESSERACT_JWT_TOKEN: &str = "x-tesseract-jwt-token"; use crate::app::AppState; use tesseract_core::{DEFAULT_ALLOWED_ACCESS}; #[derive(Debug...
use crate::{ state::State, traits::{TransitionEvidence, Transitionable}, types::SharedState, }; use std::{ cell::{Ref, RefCell, RefMut}, rc::Rc, }; fn clone_downcasted_state<S>(orig: &SharedState) -> Option<Rc<RefCell<S>>> where S: State, { let rc = Rc::clone(orig); let ptr = Rc::into_...
mod imt; pub use imt::{process_command, Command, Filer};
pub mod config; pub mod database; pub mod rabbitmq; pub mod redis;
use std::path::Path; use regex::bytes::Regex; use std::io::{BufRead, BufReader}; const PROTOCOLS: [&str; 4] = ["tcp", "tcp6", "udp", "udp6"]; cfg_if::cfg_if! { if #[cfg(test)] { use crate::lib::MockFS as FS; } else { use crate::lib::FS; } } pub fn scan_inodes_for_port(port: &str) -> Optio...
mod fast_input; use fast_input::{FastInput, FastParse}; use std::cmp::Reverse; use std::collections::BinaryHeap; struct Candidate { has_idol: bool, id: usize, distances: Vec<i32>, } impl Candidate { fn new(id: usize, has_idol: bool) -> Self { Self { has_idol, id, ...
mod button; mod button_list; pub use self::button::*; pub use self::button_list::*;
use super::*; use reduxr::*; #[derive(Default, Clone)] pub struct State { pub counter: usize, } impl Reduce<Action> for State { fn reduce(self, action: Action) -> Self { match action { Action::Increment => State { counter: self.counter + 1, }, Action...
#![warn( clippy::all, // clippy::restriction, // clippy::pedantic, clippy::cargo )]
// Copyright (c) 2015 Alcatel-Lucent, (c) 2016 Nokia // // 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,...
use crate::colors; pub fn multi_to_multi_no_hidden_layers() { let toes: Vec<f32> = vec![8.5, 9.5, 9.9, 9.0]; let winloss: Vec<f32> = vec![0.65, 0.8, 0.8, 0.9]; let fans: Vec<f32> = vec![1.2, 1.3, 0.5, 1.0]; let weights: Vec<Vec<f32>> = vec![ vec![0.3, 0.1, 0.4], vec![0.1, 0.2, 0.0], ...
#[macro_use] extern crate nom; extern crate regex; use nom::types::CompleteStr as NS; named!(null<&str, &str>, tag!("null")); named!(tuple<&str, f64 >, ws!(alt!( null => { |_| 1.0 } | tag!("true") => { |_| 2.0 } | tag!("false") => { |_| 3.0 } )) ); named!(identifier(NS) -> NS, ws!(re_...
//! Multihash implementation. //! //! Feature Flags //! ------------- //! //! Multihash has lots of [feature flags], by default, all features (except for `test`) are //! enabled. //! //! Some of them are about specific hash functions, these are: //! //! - `blake2b`: Enable Blake2b hashers //! - `blake2s`: Enable Blak...
// Copyright © 2021 Intel Corporation // // SPDX-License-Identifier: Apache-2.0 use crate::GuestMemoryMmap; use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use thiserror::Error; use vm_memory::{ByteValued, Bytes, GuestAddress, GuestMemoryError}; #[derive(Error, Debug)] pub enum TdvfError { #[error("Failed ...
use crate::goap::Condition; pub struct Reaction { conditions: Vec<Condition>, }
#![cfg(test)] use std::marker::PhantomData; use super::*; struct MinimizeFn<F, Arg, Out>(PhantomData<(F, Arg, Out)>); impl<F, Arg, Out> MinimizeFn<F, Arg, Out> { fn new() -> Self { MinimizeFn(PhantomData) } } impl<F, Arg, Out> Problem for MinimizeFn<F, Arg, Out> where F: for<'a> Fn(&'a Arg, ) -> Out, ...
// This file is part of Substrate. // // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free So...
use common::{HttpStatusCode, StatusCode}; use derive_more::Display; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::MmError; use crate::{lp_coinfind_or_err, utxo::{rpc_clients::UtxoRpcError, UtxoCommonOps}, CoinFindError, MmCoinEnum}; pub type GetCurrentMtpRpcResult<T> = Result<T, Mm...
// Copyright (c) Starcoin // SPDX-License-Identifier: Apache-2.0 use crate::{ account_universe::{AUTransactionGen, AccountUniverse}, common_transactions::rotate_key_txn, gas_costs, }; use move_core_types::vm_status::KeptVMStatus; use proptest::prelude::*; use proptest_derive::Arbitrary; use starcoin_crypto...
// Copyright 2020 WHTCORPS INC Project Authors. Licensed Under Apache-2.0 use ekvproto::violetabft_cmd_timeshare::{CmdType, VioletaBftCmdRequest, Request}; use violetabft::evioletabft_timeshare::Entry; use protobuf::{self, Message}; use rand::{thread_rng, RngCore}; use test::Bencher; use violetabftstore::interlock::...
#![allow(dead_code)] #![allow(unused_variables)] use std::mem; // STACK : short term memory storage structure - allocation // HEAP : longer term memory storage structure - allocation : let x = Box::new(5) // the assigns a pointer to the value - retrieve : println!("{}", *x); struct Poi...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use bcs_ext::BCSCodec; use clap::Parser; use jsonrpc_core_client::{RpcChannel, RpcError}; use serde::Deserialize; use starcoin_crypto::{HashValue, ValidCryptoMaterialStringExt}; use starcoin_rpc_api::types::{Reso...
#[cfg(all(unix, not(target_os="macos")))] pub const EXAMPLELIB: &'static str = "test/.build/libexamplelib.so"; #[cfg(all(unix, target_os="macos"))] pub const EXAMPLELIB: &'static str = "test/.build/libexamplelib.dylib"; #[cfg(windows)] pub const EXAMPLELIB: &'static str = "test/.build/examplelib.dll";
use std::fs; fn read_input() -> String { fs::read_to_string("./../../../data/day06.txt").expect("Something went wrong reading the file") } fn part_one() { // Get the challenge data let data = read_input(); let data_vector: Vec<&str> = data.split("\n").collect(); let mut vec = vec![vec![false; 1000]; 1000];...
use failure_derive::Fail; #[derive(Debug, Fail)] pub enum AdbError { #[fail(display = "io error: {}", _0)] Io(#[cause] ::std::io::Error), #[fail(display = "data crc mismatch")] Crc, #[fail(display = "auth not supported")] AuthNotSupported, #[fail(display = "unknown command: {:x}", _0)] UnknownComman...
use claxon::FlacReader; use crate::prelude::*; use sample::conv; use std::io::Read; #[derive(Debug, Fail)] pub enum AssetError { #[fail(display = "FLAC Decoding error: {:?}", 0)] FLACDecoding(claxon::Error), } impl From<claxon::Error> for AssetError { fn from(err: claxon::Error) -> Self { AssetErr...
extern crate zmq; pub struct CommandSocket { pub ctx: zmq::Context, pub server_location: String, } impl CommandSocket { pub fn send_command(&self, command: String) { let socket = self.ctx.socket(zmq::REQ).unwrap(); let connect_status = socket.connect(format!("ipc://{}/rep-server", ...
use dir; use std::io; use std::process::Command; pub fn cut_fade() { println!("обрезать и притушить mp3 введите длину 00:00:00 :"); let mut t = String::new(); let mut tt = String::new(); io::stdin().read_line(&mut t).expect("fuck off"); let t = t.trim(); let t = t.replace(".", ":"); let t...
#![deny(warnings)] // Note: `hyper::upgrade` docs link to this upgrade. use std::net::SocketAddr; use std::str; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; use tokio::sync::watch; use bytes::Bytes; use http_body_util::Empty; use hyper::header::{HeaderValue, UPGRADE}; use h...
use image::{DynamicImage,Luma}; use std::thread; use std::thread::JoinHandle; use std::sync::Arc; use num_cpus; use geometry::{Viewable}; use scene::Scene; const IMGX: u32 = 1000; const IMGY: u32 = 1000; const SCALE: f64 = 0.0025; pub fn chunk(w: u32, h: u32, n: u32) -> Vec<Vec<(u32, u32)>> { let mut v = vec![];...
use std::{fmt, sync::Arc}; use std::{ pin::Pin, time::{Duration, Instant}, }; use crate::rt::Sleep; use crate::rt::Timer; /// A user-provided timer to time background tasks. #[derive(Clone)] pub(crate) enum Time { Timer(Arc<dyn Timer + Send + Sync>), Empty, } impl fmt::Debug for Time { fn fmt(&se...
#[doc = "Register `STAT` reader"] pub struct R(crate::R<STAT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<STAT_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<STAT_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<STAT_SP...
use std::borrow::Borrow; use std::cmp::min; use std::io::{Error, ErrorKind, Result}; use std::pin::Pin; use std::task::{Context, Poll}; use async_trait::async_trait; use bytes::{Buf, BufMut, BytesMut}; use log::{info, warn}; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use tokio::net::UdpSocket; use crate::protoc...
extern crate rand; // external crate to deal with random numbers use std::io; use rand::Rng; // random number generator trait use std::cmp::Ordering; // import for the ordering enum fn main() { println!("Guessing Game"); // working title let secret = rand::thread_rng().gen_range(1, 101);//generate a number b...
use std::collections::HashMap; use crate::ast::*; use crate::parsing::{ParseError}; #[derive(Default)] struct Scope { decls: HashMap<String, Decl>, /// Next local variable slot index to assign /// this is only used for local variables next_idx: usize, } /// Represent an environment with multiple leve...
use std::sync::mpsc::Sender; use std::sync::mpsc::Receiver; use std::sync::mpsc::channel; use std::ptr; use super::packets::*; #[derive(Debug)] pub struct RecordProcessor { // 发送器 这里我们使用Rust的异步管道做缓冲 sender: Sender<AudioPacket>, // 音频开始采集的时间 is_recording_flag: bool, startTimeMills: i128, } impl Re...
use super::store::{MetaStore, MetaStoreError, MigrationType}; use crate::broker::store::InconsistentError; use crate::common::cluster::{Cluster, DBName, MigrationTaskMeta, Node, Proxy}; use crate::common::version::UNDERMOON_VERSION; use crate::coordinator::http_meta_broker::{ ClusterNamesPayload, ClusterPayload, Fa...
struct Solution; #[allow(dead_code)] impl Solution { pub fn single_number(nums: Vec<i32>) -> i32 { let mut set = std::collections::HashSet::new(); let mut sum: i64 = 0; for i in nums { sum += i as i64; set.insert(i as i64); } ((set.iter().sum::<i64>()...
use tokio::net::TcpStream; use crate::{ network::{self, Frame, NetPacket, NetPacketState}, value::DataValue, }; pub struct DoreaClient { connection: TcpStream, } impl DoreaClient { /// connect dorea-server /// /// ```rust /// use dorea::client::DoreaClient; /// #[tokio::main] /// ...
use rand::Rng; use rand::rngs::ThreadRng; use super::color; use super::attributes::{Stats}; #[derive(Debug, Clone)] pub enum Kind { Weapon, Potion } pub trait WeaponType: WeaponTypeClone { fn attack(&self, stats: Stats) -> (i8, DamageType); fn show_power(&self) -> i8; fn description(&self) -> Str...
//! Image functionality. use lib; /// Represents a clear video image. pub struct Image { pub(crate) img: *mut lib::vpx_image_t, } impl Image { /// Return the width of the image in pixels. pub fn width(&self) -> u32 { unsafe { (*self.img).w as u32 } } /// Return the he...
// Copyright 2017 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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...
use jsonrpc::client::Client ; use jsonrpc::Request; use serde_json::{json, Value}; fn main() { let client = Client::new("http://localhost:26657".to_owned(), None, None); let name="status"; let params: Vec<Value>= vec![]; let request = client.build_request(name, &params); println!("{:?}", request); ...
// Copyright 2020 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 agreed to ...
fn main() { another_function(5); } fn another_function(x: i32) { println!("The value of x is: {}", x); println!("The value of 5 is: {}", five()); } fn five() -> u32 { 5 }
pub use self::perceptron::Perceptron; mod perceptron;
//@compile-flags: -Zmiri-disable-isolation fn main() { assert_eq!(std::env::var("MIRI_ENV_VAR_TEST"), Ok("0".to_owned())); }
extern crate hex; #[macro_use] extern crate structopt; use structopt::StructOpt; use std::fmt; use std::ffi::CStr; use std::str::FromStr; mod portmidi; use portmidi::*; mod output; use output::*; #[derive(Debug)] struct HexData(pub Vec<u8>); impl FromStr for HexData { type Err = hex::FromHexError; fn fr...
use std::error::Error; use std::fs::read_to_string; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; pub fn farenheit(celsius: i32) -> i32 { (((celsius as f32) - 32.) * 5. / 9.) as i32 } pub fn bmi(weight: u32, height: f32) -> &'static str { match weight as f32 / height.powf(2.0) { ...
use crate::db::DbPool; #[derive(Clone)] pub struct Context { pub db_pool: DbPool, } impl juniper::Context for Context {} impl AsRef<Self> for Context { #[inline] fn as_ref(&self) -> &Self { self } }
/// event invoked by the the ezgfx plugin whenever a /// renderer is ready. this is useful for initializing /// render pipelines, textures, and other assets. it's /// invoked as many times as there are ezgfx::*::Renderer /// components. pub const READY: &str = "ezgfx_ready";
use core::cell::UnsafeCell; // TODO // - no real locking going on here, just a place holder // - named single core to remind me to fix it later pub struct SingleCoreLock<T> { data: UnsafeCell<T>, } unsafe impl<T> Sync for SingleCoreLock<T> {} impl<T> SingleCoreLock<T> { pub const fn new(data: T) -> SingleCor...
// x11api code is taken from github.com/jD91mZM2/xidlehook mod x11api; mod colors; mod xft; pub use crate::colors::Colors; pub use crate::x11api::{XDisplay, get_xrm_resource, query_xrdb}; pub use crate::xft::{Xft, FontName}; #[cfg(test)] mod tests { #[test] fn xterm_colors() { use crate::colors::Color...
use std::collections::HashMap; use crate::{card::Rank, Card, GameType}; pub fn get_one_pair( game_type: GameType, cards: &[Card], rank_map: &HashMap<Rank, Vec<Card>>, player_cards: &[Card], board: &[Card], ) -> Option<Vec<Card>> { let pair = rank_map.values().find(|cards| cards.len() == 2); ...
//! Utility function for formatting a device with filesystem use std::process::Command; use blkid::probe::Probe; pub(crate) async fn prepare_device( device: &str, fstype: &str, ) -> Result<(), String> { debug!("Probing device {}", device); let probe = Probe::new_from_filename(device) .map_er...
use std::io::prelude::*; use std::fs::File; use std::path::Path; use rustc_serialize::json; #[derive(RustcDecodable, RustcEncodable, Clone)] pub struct ConfigStruct { pub port: u16, pub path_to_files: String, pub index: String, pub path_to_error_pages: String, } // Read config file. Returns ConfigStru...
#![allow(unused)] use js_sys::Function; use wasm_bindgen::{prelude::*, JsCast}; use wasm_bindgen_test::*; use web_tree_sitter_sys::*; #[wasm_bindgen_test] async fn new() { async fn inner() -> Result<(), JsValue> { TreeSitter::init().await?; let _parser = Parser::new()?; Ok(()) } as...
// Copyright (c) Starcoin // SPDX-License-Identifier: Apache-2.0 use crate::{ account::{Account, AccountData, AccountRoleSpecifier}, account_universe::{ txn_one_account_result, AUTransactionGen, AccountPair, AccountPairGen, AccountUniverse, }, common_transactions::create_account_txn, gas_co...
extern crate bip_peer; extern crate bip_handshake; extern crate bip_util; extern crate futures; extern crate tokio_core; extern crate tokio_io; use std::io; use futures::{StartSend, Poll}; use futures::sink::{Sink}; use futures::stream::{Stream}; use futures::sync::mpsc::{self, Sender, Receiver}; mod peer_manager_se...
use opencv::{core::SparseMat_Hdr, prelude::*, Result}; #[test] fn slice_override() -> Result<()> { let mut hdr = SparseMat_Hdr::new(&[4, 2], i32::opencv_type())?; assert_eq!(4, hdr.size()[0]); assert_eq!(2, hdr.size()[1]); assert_eq!(0, hdr.size()[2]); Ok(()) }
extern crate time; use time::Tm; extern crate wiringpi; use wiringpi::pin::Value::{High, Low}; use wiringpi::pin::{Pin, OutputPin}; use wiringpi::time::{delay, delay_microseconds}; use wiringpi::thread::priority; use std::cmp; use std::num::Wrapping; fn send_header<P: Pin>(pin: &OutputPin<P>) { pin.digital_write(Hi...
// Copyright 2020 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 agreed to ...
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0. use std::cmp::Ordering; use std::convert::TryFrom; use milevadb_query_codegen::AggrFunction; use milevadb_query_datatype::{Collation, EvalType, FieldTypeAccessor}; use fidel_timeshare::{Expr, ExprType, FieldType}; use super::*; use milevadb_q...