text stringlengths 8 4.13M |
|---|
#[cfg(feature = "new")]
extern crate new_abi_stable as abi_stable;
#[cfg(not(feature = "new"))]
extern crate old_abi_stable as abi_stable;
use abi_stable::{library::RootModule, marker_type::NonOwningPhantom, sabi_types::VersionStrings};
mod many_types {
use std::{marker::PhantomData, sync::atomic};
use abi_... |
use crate::{
error::Error,
model::{CreateUser, User},
service::Service,
};
use async_std::sync::{Arc, RwLock};
use async_trait::async_trait;
use core::cmp::max;
#[derive(Clone)]
pub struct MockService {
users: Arc<RwLock<Vec<User>>>,
}
impl MockService {
pub fn new() -> Self {
MockService ... |
// Copyright 2022 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 ... |
use std::io::{Read, Write};
use codecs::{ToByte, FromByte};
use error::{Error, Result};
use utils::TopicPartitionOffset;
use super::{HeaderRequest, HeaderResponse};
use super::{API_KEY_OFFSET_FETCH, API_KEY_OFFSET_COMMIT, API_VERSION};
//
// XXX Seems like this got replaced: See https://cwiki.apache.org/confluence/p... |
pub enum CommsBackend {
Unix,
TCP,
TLS,
}
pub struct TcpClient {
pub host: String,
pub port: u16,
}
pub struct TlsFiles {
pub key: String,
pub cert: String,
pub ca: String,
}
pub struct Client {
pub backend: CommsBackend,
pub socket_path: Option<String>,
pub tcp_options: O... |
#[doc = "Reader of register DSI_PSR"]
pub type R = crate::R<u32, super::DSI_PSR>;
#[doc = "Reader of field `PD`"]
pub type PD_R = crate::R<bool, bool>;
#[doc = "Reader of field `PSSC`"]
pub type PSSC_R = crate::R<bool, bool>;
#[doc = "Reader of field `UANC`"]
pub type UANC_R = crate::R<bool, bool>;
#[doc = "Reader of f... |
#[doc = "Reader of register CTRL"]
pub type R = crate::R<u8, super::CTRL>;
#[doc = "Writer for register CTRL"]
pub type W = crate::W<u8, super::CTRL>;
#[doc = "Register CTRL `reset()`'s with value 0"]
impl crate::ResetValue for super::CTRL {
type Type = u8;
#[inline(always)]
fn reset_value() -> Self::Type {... |
// 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 {
element_management::{ElementManager, ElementManagerError, SimpleElementManager},
failure::{Error, ResultExt},
fidl_fuchsia_session::{
... |
use std::{
error::Error,
fmt::{self, Display, Formatter},
};
use async_graphql::ParseRequestError;
use warp::{
http::{Response, StatusCode},
hyper::Body,
reject::Reject,
Reply,
};
/// Bad request error.
///
/// It's a wrapper of `async_graphql::ParseRequestError`. It is also a `Reply` -
/// by... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type HidBooleanControl = *mut ::core::ffi::c_void;
pub type HidBooleanControlDescription = *mut ::core::ffi::c_void;
pub type HidCollection = *mut ::core::f... |
use scheme::errors::EvalErr;
use scheme::eval_expr;
use scheme::functions::Function;
use scheme::object::{Number, Object};
use scheme::scope::Scope;
use std::rc::Rc;
use std::time::Instant;
fn seq_sum(args: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
if args.len() > 1 {
return Err(EvalErr::TooManyAr... |
pub enum Format {
Text,
JSON
}
impl Format {
pub fn from_string(f: String) -> Format {
if f.trim().to_lowercase() == "json" {
return Format::JSON;
}
Format::Text
}
} |
pub mod image;
pub use self::image::Image;
use crate::{
geo::{
collection::{BezierRotate, Mesh, Plane, Sphere},
Geo,
},
scene::{Camera, Renderer, World},
Flt,
};
use pbr::ProgressBar;
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::collections::HashMap;
use std::fs;
us... |
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
#[cfg(any(feature = "v2_16", feature = "dox"))]
use glib;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::t... |
//! DAG-Protobuf codec.
use crate::ipld::{BlockError, Ipld, IpldError};
use cid::Cid;
use std::{
collections::BTreeMap,
convert::{TryFrom, TryInto},
};
use thiserror::Error;
/// Protobuf codec.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct DagPbCodec;
impl DagPbCodec {
pub fn encode(ipld: &Ipld... |
#[cfg(feature = "stm32f4xx-hal")]
use stm32f4xx_hal::{
bb,
gpio::{
gpioa::{PA1, PA2, PA7},
gpiob::{PB11, PB12, PB13},
gpioc::{PC1, PC4, PC5},
gpiog::{PG11, PG13, PG14},
Floating, Input,
Speed::VeryHigh,
},
stm32::{RCC, SYSCFG},
};
#[cfg(feature = "stm32f7... |
use std::collections::LinkedList; //std library: linkedlist allows vector Command modifiction
use piston_window::{Context, G2d}; //graph buffer
use piston_window::types::Color; //color
use crate::shapes1:: {make_shape};
const SNAKE_COLOR: Color = [0.0, 0.0, 1.0, 1.0]; //making the color of the snake ... |
use crate::{field::Field, Record};
/// Iterator over fields of a record.
#[derive(Debug, Clone)]
pub struct Fields<'a> {
record: &'a Record<'a>,
offset: usize,
}
impl<'a> Fields<'a> {
#[doc(hidden)]
pub fn new(record: &'a Record<'a>) -> Fields<'a> {
Fields { record, offset: 0 }
}
}
impl<'... |
mod test_utils;
mod server_decode {
use super::test_utils::TestIO;
use async_std::io::prelude::*;
use http_types::headers::TRANSFER_ENCODING;
use http_types::Request;
use http_types::Result;
use http_types::Url;
use pretty_assertions::assert_eq;
async fn decode_lines(lines: Vec<&str>) -... |
use crate::runtime::time::datetime;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
#[native_implemented::function(erlang:date/0)]
pub fn result(process: &Process) -> Term {
let date: [usize; 3] = datetime::local_date();
process.tuple_from_slice(&[
process.integ... |
//! Core definitions module.
use std::{collections::BTreeMap, convert::TryInto};
use anyhow::anyhow;
use thiserror::Error;
pub use oasis_core_keymanager_api_common::KeyManagerError;
use crate::{
callformat,
context::{BatchContext, Context, TxContext},
dispatcher, error,
module::{self, InvariantHandle... |
use anyhow::Result;
use image::RgbaImage;
use std::sync::Arc;
#[derive(Debug)]
pub struct Texture {
pub texture: Arc<wgpu::Texture>,
pub size: wgpu::Extent3d,
pub group: wgpu::BindGroup,
pub layout: wgpu::BindGroupLayout,
pub view: wgpu::TextureView,
pub sampler: wgpu::Sampler,
}
impl Texture ... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "UI_Input_Preview_Injection")]
pub mod Injection;
#[repr(transparent)]
#[doc(hidden)]
pub struct IInputActivationListenerPreviewStatics(pub ::windows::core::IInspectable);
uns... |
pub struct Solution;
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Tree,
pub right: Tree,
}
use std::cell::RefCell;
use std::rc::Rc;
type Tree = Option<Rc<RefCell<TreeNode>>>;
impl Solution {
pub fn max_path_sum(root: Tree) -> i32 {
rec(&root).unwrap().0
}... |
use super::super::store::wasm_store_t;
use super::super::trap::wasm_trap_t;
use super::super::types::{wasm_functype_t, wasm_valkind_enum};
use super::super::value::{wasm_val_inner, wasm_val_t};
use std::convert::TryInto;
use std::ffi::c_void;
use std::sync::Arc;
use wasmer::{Function, Instance, RuntimeError, Val};
#[a... |
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct Triangle {
pub enabled: bool,
pos: usize,
timer_value: u16,
timer_period: u16,
lcl: u8,
control: bool,
length_counter: u8,
length_table: Vec<u8>,
// Linear counter
lc_value: u8,
lc_reload_fla... |
//! Settings variables used throughout the project.
// Gameplay
pub const BALL_SPAWN_DELAY: f32 = 2.0;
// Audio - sfx
pub const BOUNCE_SFX: &str = "audio/sfx/bounce.ogg";
pub const SCORE_SFX: &str = "audio/sfx/score.ogg";
// Audio - tracks
pub const MUSIC_TRACKS: &[&str] = &["audio/tracks/track-01.ogg", "audio/track... |
use super::{Header, Id};
use std::fs::{File};
use std::path::PathBuf;
use std::mem::size_of;
use std::io;
use std::io::{Read, Seek, SeekFrom};
use crate::archives::packages::patches::index::{IndirectIndex, EntriesMeta, BlocksMeta};
use crate::archives::packages::patches::index::IndexStrategy::{DIRECT, INDIRECT};
use cr... |
use super::Context;
use crate::projects::queries::QueryProjects;
use crate::stories::queries::QueryStories;
use crate::users::queries::QueryUsers;
pub struct QueryRoot;
#[juniper::graphql_object(
Context = Context
)]
impl QueryRoot {
fn users(&self) -> QueryUsers {
QueryUsers
}
fn projects(&sel... |
struct Point {
x: i32,
y: i32,
}
enum Color {
Rgb(i32, i32, i32),
Hsv(i32, i32, i32)
}
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(Color),
}
fn main() {
let p = Point { x: 0, y: 7 };
// naming fields in struct
let Point { x: a, y: b } = p;
... |
use gfx_maths::*;
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct DirectionalLight {
pub direction: Vec4,
pub illuminance: Vec4, // in lx = lm / m^2
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PointLight {
pub position: Vec4,
pub luminous_flux: Vec4, // in lm
}
#[d... |
#[doc = "Reader of register TZSC_PRIVCFGR1"]
pub type R = crate::R<u32, super::TZSC_PRIVCFGR1>;
#[doc = "Writer for register TZSC_PRIVCFGR1"]
pub type W = crate::W<u32, super::TZSC_PRIVCFGR1>;
#[doc = "Register TZSC_PRIVCFGR1 `reset()`'s with value 0"]
impl crate::ResetValue for super::TZSC_PRIVCFGR1 {
type Type = ... |
// https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/submissions/
impl Solution {
pub fn number_of_steps(mut num: i32) -> i32 {
oper(num)
}
}
fn oper(mut num: i32) -> i32 {
match num {
0 => 0,
_ => match num %2 {
0 => 1 + oper(num / 2),
... |
use crate::tts::{TtsConstructionError, TtsError, TtsInfo, VoiceDescr};
use reqwest::{RequestBuilder, Url};
use unic_langid::{langid, langids, LanguageIdentifier};
use super::http_tts::HttpsTtsData;
pub struct GttsData();
impl HttpsTtsData for GttsData {
fn make_request_url(&self, voice: &str, input: &str) -> Re... |
// use std::io::Error;
// use std::fmt;
fn main() {
type_synonyms_with_type_aliases();
never_type();
sized_trait();
}
fn type_synonyms_with_type_aliases() {
/*
Because Kilometers and i32 are the same type, we can add values of both
types and we can pass Kilometers values to functions that tak... |
use crate::database::{Database, HasArguments, HasStatement, HasStatementCache, HasValueRef};
use crate::mysql::value::{MySqlValue, MySqlValueRef};
use crate::mysql::{
MySqlArguments, MySqlColumn, MySqlConnection, MySqlQueryResult, MySqlRow, MySqlStatement,
MySqlTransactionManager, MySqlTypeInfo,
};
/// MySQL d... |
//
// Main entry point for the wal_acceptor executable
//
use anyhow::Result;
use clap::{App, Arg};
use daemonize::Daemonize;
use log::*;
use std::env;
use std::path::{Path, PathBuf};
use std::thread;
use zenith_utils::logging;
use walkeeper::s3_offload;
use walkeeper::wal_service;
use walkeeper::WalAcceptorConf;
fn ... |
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Respawning {
pub base_time: f32,
pub time_remaining: Option<f32>,
}
|
#[allow(unused_macros)]
macro_rules! parse_line {
[$( $x:tt : $t:ty ),+] => {
//declare variables
$( let $x: $t; )+
{
use std::str::FromStr;
// read
let mut buf = String::new();
std::io::stdin().read_line(&mut buf).unwrap();
#[allow... |
use std::sync::Arc;
use crate::config::TableConfig;
use std::path::PathBuf;
use crate::table::{TableSchema, ColumnSchema, ColumnId, ColumnType, PrimaryKeySpec, DetachedRowData, ColumnData, ColumnValue, RowData};
use uuid::Uuid;
use crate::time::{ManualClock, MergeTimestamp, HtClock};
const TEST_DIR: &str = "__test__... |
use bigneon_db::models::{FeeSchedule, TicketType, TicketTypeStatus};
use bigneon_db::utils::errors::*;
use chrono::NaiveDateTime;
use diesel::PgConnection;
use models::DisplayTicketPricing;
use uuid::Uuid;
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct UserDisplayTicketType {
pub id: Uuid,
pub ... |
use core::mem;
use core::pin::Pin;
use core::ptr;
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
#[must_use = "futures do nothing unless you `.await` or poll them"]
#[derive(Debug)]
pub(crate) enum Chain<Fut1, Fut2, Data> {
First(Fut1, Data),
Second(Fut2),
Empty,
}
impl<Fut1: U... |
use std::fs::File;
use std::io::prelude::*;
const chain: usize = 13;
fn main() -> std::io::Result<()>{
let mut file = File::open("input.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let N = contents.find('\n').expect("no newlines");
let M = contents.matches('\n').c... |
use spin::{Mutex, RwLock};
use std::any::Any;
use std::marker::PhantomData;
#[cfg(feature = "sgx")]
use std::prelude::v1::*;
use std::sync::{Arc, Weak};
use async_io::event::{Events, Pollee, Poller};
use async_io::file::{Async, File, SeekFrom};
use async_io::prelude::{Result, *};
use futures::future::BoxFuture;
use fu... |
extern crate addr2line;
extern crate fallible_iterator;
extern crate memmap;
extern crate object;
extern crate unwind;
use fallible_iterator::FallibleIterator;
use unwind::{DwarfUnwinder, Unwinder};
use addr2line::Context;
// ugly hack :(
#[inline(never)]
fn no_tailcall_please() {
print!("")
}
#[test]
fn correct... |
extern crate toml;
extern crate clap;
use std::{
str,
fs::{File, create_dir_all, remove_dir_all},
io::{Result, Read, Write},
process::Command
};
use serde::{Serialize, Deserialize};
use toml::value::Array;
use clap::{Arg, App, SubCommand};
#[derive(Debug, Serialize, Deserialize)]
struct Config {
p... |
//! Utilities to report test results to users
mod color;
mod diff;
pub use color::Palette;
pub(crate) use color::Style;
pub use color::Styled;
pub use diff::write_diff;
|
// Copyright 2021 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 2012-2013 The Rust 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-MI... |
use std::process::exit;
use getopts::Options;
use openssl::ssl::{SslMethod, SslContext, SslFiletype, SslVerifyMode};
use mqtt3::{LastWill, SubscribeTopic, QoS, Protocol};
use super::command::{Command, SubscribeCommand, PublishCommand};
pub struct CLI {
program: String,
command: String,
arguments: Vec<Strin... |
// Copyright 2020-2021 the Deno authors. All rights reserved. MIT license.
use crate::lexer::{lex, MediaType, TokenOrComment};
use std::convert::TryFrom;
use swc_ecmascript::parser::token::{Token, Word};
pub trait Colorize {
fn colorize(self) -> String;
}
impl Colorize for markdown::Block {
fn colorize(self) -> S... |
pub const INPUT: &str = include_str!("../input.txt");
pub enum Instruction {
Noop,
Add(i32),
}
pub fn parse_input(input: &str) -> Vec<Instruction> {
input
.lines()
.map(|line| {
if line.starts_with('a') {
Instruction::Add(line[5..].parse().unwrap())
... |
use crate::SystemDataFetch;
use spatialos_sdk::worker::commands::{
CreateEntityRequest, DeleteEntityRequest, EntityQueryRequest, ReserveEntityIdsRequest,
};
use spatialos_sdk::worker::connection::{Connection, WorkerConnection};
use spatialos_sdk::worker::entity::Entity as WorkerEntity;
use spatialos_sdk::worker::op... |
//! The following is derived from Rust's
//! library/std/src/os/windows/io/socket.rs
//! at revision
//! 4f9b394c8a24803e57ba892fa00e539742ebafc0.
//!
//! All code in this file is licensed MIT or Apache 2.0 at your option.
use super::raw::*;
use crate::backend::c;
use crate::backend::fd::LibcFd as LibcSocket;
use core... |
mod adventofcode;
use adventofcode::load_file;
use std::collections::HashSet;
#[cfg(test)]
mod tests {
use validate_passphrase;
#[test]
fn test1() {
let input = "abcde fghij";
assert_eq!(validate_passphrase(&input), true);
}
#[test]
fn test2() {
let input = "abcde xy... |
#[macro_use]
extern crate lazy_static;
use regex::Regex;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
struct Entry {
pw: String,
c: char,
min: usize,
max: usize,
}
fn check1(e: &Entry) -> bool {
let mut count: usize = 0;
for pc in e.pw.chars() {
if pc == ... |
use std::{io, result, str};
use std::io::Read;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
mod simple;
pub use simple::open_simple;
mod memory;
pub use memory::open_memory;
mod wal;
pub use wal::open_wal;
#[derive(Debug)]
pub enum Error {
Io(io::Error),
Utf8Error(str::Utf8Error),
Str... |
use prob1::solver::Solver;
pub struct BruteForceSolver {
upper: u32,
}
impl BruteForceSolver {
pub fn new(upper_limit: u32) -> BruteForceSolver {
BruteForceSolver { upper: upper_limit }
}
}
impl Solver for BruteForceSolver {
fn sequence(&self) -> Box<Iterator<Item=u32>> {
Box::new((1.... |
// 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 {
crate::error::Error,
wlan_common::{
appendable::Appendable,
big_endian::BigEndianU16,
mac::{self, MacAddr},
},
};... |
extern "C" {
fn malloc(x: usize) -> *mut u8;
fn free(x: *mut u8);
pub fn memset(ptr: *mut u8, val: i32, size: usize);
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
pub struct Page {
pub(super) data: *mut u8,
pub(super) top: *mut u8,
pub(super) limit: *mut u8,
pub(super) si... |
extern crate oxygen;
use oxygen::lexer::Lexer;
use oxygen::reader::Reader;
use oxygen::syntax::token::{TokenType};
const SRC: &'static str = "\
let int = 1\n\
let dbl = 1.1\n\
let str = \"hello\"\n\
\n\
fn hello(a, b, c) {\n\
return a + b + c\n\
}\n\
\n\
listen some.evnt {\n\
... |
use crate::{instruction::Instruction, optimizer, parser};
use std::{collections::VecDeque, io, ops::Range};
const TAPE_SIZE: usize = 30_000;
pub type Result = std::result::Result<(), Error>;
pub struct Brainfuck {
instructions: VecDeque<Instruction>,
ip: usize,
tape: [u8; TAPE_SIZE],
dp: usize,
s... |
#![allow(unused_variables)]
extern crate num_traits;
extern crate rand;
extern crate image;
#[macro_use]
extern crate derive_new;
#[cfg(feature="gui")]
extern crate minifb;
pub mod vec3;
pub mod ray;
pub mod hitable;
pub mod hitable_list;
pub mod sphere;
pub mod moving_sphere;
pub mod camera;
pub mod util;
pub mod m... |
#[cfg(test)]
mod test;
use std::convert::TryInto;
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
use crate::runtime::time::{monotonic, system, Unit};
#[native_implemented::function(erlang:time_offset/1)]
pub fn result(process: &Process, u... |
#[doc = "Reader of register PCROP1ASR"]
pub type R = crate::R<u32, super::PCROP1ASR>;
#[doc = "Reader of field `PCROP1A_STRT`"]
pub type PCROP1A_STRT_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:7 - PCROP1A area start offset"]
#[inline(always)]
pub fn pcrop1a_strt(&self) -> PCROP1A_STRT_R {
PCROP1... |
use crate::{HdbError, HdbResult};
// Here we list all those parts that are or should be implemented by this
// driver. ABAP related stuff and "reserved" numbers is omitted.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum PartKind {
Command = 3, // SQL Command Data
ResultSet = 5, ... |
use codeframe::{Codeframe, Color};
use k9::*;
#[test]
fn simple_capture() {
super::setup_test_env();
let raw_lines = "let a: i64 = 12;".to_owned();
let codeframe = Codeframe::new(raw_lines, 1).set_color(Color::Red).capture();
assert_matches_inline_snapshot!(
format!("\n{}", codeframe.expect("... |
use crate::models::manufacturer::Manufacturer;
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Debug)]
pub struct LauncherCommon {
pub id: i32,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct LauncherCommonConfiguration {
pub id: i32,
pub launch_library_id: Option<i3... |
use std::error::Error;
use std::path::PathBuf;
use structopt::StructOpt;
use serde::Serialize;
#[derive(StructOpt, Debug)]
#[structopt(name = "basic", set_term_width(80))]
struct CliOptions {
/// File name for the input CSV file
#[structopt(short, long, parse(from_os_str), display_order(10))]
input: PathBu... |
use ili9163c;
use gpio_traits::pin::{Output, PinState};
use std::cell::Cell;
use std::rc::Rc;
pub struct Pin {
state: Rc<Cell<PinState>>,
}
impl Pin {
pub fn new(state: Rc<Cell<PinState>>) -> Self {
Pin { state: state }
}
}
impl Output for Pin {
fn high(&mut self) {
self.state.set(Pi... |
use gdk_pixbuf::{Pixbuf, Colorspace};
use std::{cell::RefCell, rc::Rc};
use nanocv::{ImgBuf, ImgSize, Img};
use crate::message::Rgba;
pub fn create_pixbuf(width: usize, height: usize) -> Pixbuf {
Pixbuf::new(
Colorspace::Rgb, true, 8, width as i32, height as i32
).expect("No enough memory to create pix... |
// Copyright 2021 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 ... |
use std::ffi::CStr;
use ash::vk;
use super::{
error::{GraphicsError, GraphicsResult},
RendererConfig,
};
const VULKAN_VERSION: (u32, u32) = (1, 2);
pub(crate) fn get_candidates(
instance: &ash::Instance,
) -> GraphicsResult<Vec<(vk::PhysicalDevice, vk::PhysicalDeviceProperties, bool)>> {
let phys_de... |
#![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate rocket;
#[get("/")]
fn hello() -> &'static str {
"Hello, world!"
}
fn main() {
rocket::ignite().mount("/", routes![hello]).launch();
}
//extern crate dotenv;
//#[macro_use] extern crate rocket_contrib;
//#[macro_use] extern crate diesel... |
extern crate self as fuzzcheck;
#[cfg(feature = "serde_json_serializer")]
use serde::{Deserialize, Serialize};
/// An abstract syntax tree.
///
#[cfg_attr(
feature = "serde_json_serializer",
doc = "It can be serialized with [`SerdeSerializer`](crate::SerdeSerializer) on crate feature `serde_json_serializer`"
... |
use crate::eos_formats::format_action;
use crate::proc_macro::TokenStream;
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
use syn::{self, parse_macro_input, ItemFn};
pub fn action(_args: TokenStream, input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as ItemFn);
let ident... |
use std::collections::HashSet;
use proconio::{input, marker::Chars};
fn main() {
input! {
n: usize,
s: [Chars; n],
};
let mut set = HashSet::new();
for s in s {
let mut t = s.clone();
t.reverse();
if set.contains(&s) || set.contains(&t) {
continue;
... |
//! Streaming async HTTP 1.1 parser.
//!
//! At its core HTTP is a stateful RPC protocol, where a client and server
//! communicate with one another by encoding and decoding messages between them.
//!
//! - `client` encodes HTTP requests, and decodes HTTP responses.
//! - `server` decodes HTTP requests, and encodes HTT... |
pub use VkImageType::*;
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VkImageType {
VK_IMAGE_TYPE_1D = 0,
VK_IMAGE_TYPE_2D = 1,
VK_IMAGE_TYPE_3D = 2,
}
|
// Copyright 2020-2021, The Tremor Team
//
// 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 agr... |
//! Poor man's language analyzer.
use keywords::KeywordPriority;
use std::collections::HashMap;
use std::sync::OnceLock;
mod keywords;
const LOWEST_PRIORITY: usize = 1000usize;
/// Display priority of the line.
///
/// Lower is better, the better results will be displayed first.
#[derive(Debug, Copy, Clone, Partial... |
use std::io;
use std::io::Write;
use std::fs::File;
use rustypawn::ThinkInfo;
use rustypawn::MoveTrait;
use rustypawn::Game;
use rustypawn::MAX_DEPTH;
use rustypawn::make_move_algebraic;
use rustypawn::think;
struct Comms {
file: Option<File>
}
impl Comms {
pub fn new(name: Option<&str>) -> Comms {
C... |
use std::{
pin::Pin,
task::{Context, Poll},
};
use futures::{ready, stream::BoxStream, Stream, StreamExt};
use generated_types::{read_response::Frame, ReadResponse};
/// Chunk given [`Frame`]s -- while preserving the order -- into [`ReadResponse`]s that shall at max have the
/// given `size_limit`, in bytes.
... |
//https://leetcode.com/problems/maximum-69-number/submissions/
impl Solution {
pub fn maximum69_number (mut num: i32) -> i32 {
let mut max_69 = 0;
let mut last_change_dif = 0;
let mut ten_power = 1;
while num != 0 {
let current_digit = num % 10;
... |
pub use embedded_hal::digital::v2::*;
pub use embedded_hal::prelude::*;
pub use crate::hal::adc::OneShot as _hal_adc_OneShot;
pub use crate::hal::watchdog::Watchdog as _hal_watchdog_Watchdog;
pub use crate::hal::watchdog::WatchdogEnable as _hal_watchdog_WatchdogEnable;
#[cfg(feature = "stm32l0x1")]
pub use crate::adc... |
mod event;
mod mice;
pub use self::event::*;
pub use self::mice::*;
|
fn main() {
let s = "stressed";
let res = rev(s);
println!("{}", res);
}
fn rev(s: &str) -> String {
s.chars().rev().collect()
}
|
use crate::card::{Effect, EffectPair, Target};
use rand::rngs::SmallRng;
use rand::seq::SliceRandom;
use rand::FromEntropy;
use std::mem;
pub trait Actor: std::fmt::Debug {
fn set_intent(&mut self);
fn take_damage(&mut self, raw_damage: i32);
fn compute_damage(&self, raw_damage: i32) -> i32 {
raw_d... |
use crate::protocol::Command::Xbox;
use crate::protocol::{AlphaKeys, BackKeys, Command, DirectionKeys, MetaKeys, Stick};
pub(super) fn parse_packet(data: &[u8]) -> Option<Command> {
// XBOX key packet
if data.len() == 6 && data[0] == 0x07 {
return Some(Xbox(data[4] != 0));
}
// Not a valid key ... |
extern crate rayon;
extern crate rand;
extern crate statrs;
extern crate petgraph;
extern crate vec_graph;
extern crate capngraph;
extern crate ris;
extern crate bit_set;
extern crate docopt;
#[macro_use]
extern crate slog;
extern crate slog_stream;
extern crate slog_term;
extern crate slog_json;
extern crate serde;
ex... |
extern crate image;
use image::GenericImageView;
use std::fs;
fn save_jpg_clean(path: &str) {
println!("salvando {} em editadas", path);
let img = image::open(path).unwrap();
println!("dimensions: {:?}, color: {:?}\n",
img.dimensions(),
img.color()
);
img.save(format!("editadas/{}",... |
#![allow(non_snake_case)]
use core::convert::TryInto;
use test_winrt_signatures::*;
use windows::core::*;
use Component::Signatures::*;
use Component::Structs::*;
use Windows::Foundation::PropertyValue;
#[implement(Component::Signatures::ITestNonBlittable)]
struct RustTest();
impl RustTest {
fn SignatureNonBlitt... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
pub const APPMODEL_ERROR_DYNAMIC_PROPERTY_INVALID: i32 = 15705i32;
pub const APPMODEL_ERROR_DYNAMIC_PROPERTY_READ_FAILED: i32 = 15704i32;
pub const APPMODEL_ERROR_NO_APPLICATION: i32 = 15703i... |
#[derive(Clone)]
pub enum Yaml {
String(String),
Int(i64),
List(Vec<Yaml>),
Map(Vec<(String, Yaml)>),
Bool(bool),
}
impl Yaml {
pub fn to_yaml_rust(&self) -> yaml_rust::Yaml {
match self {
Yaml::String(s) => yaml_rust::Yaml::String(s.clone()),
Yaml::List(l) => ya... |
// Copyright 2017 The Rust 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 ... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "Win32_Graphics_Printing_PrintTicket")]
pub mod PrintTicket;
#[link(name = "windows")]
extern "system" {
#[cfg(feature = "Win32_Foundation")]
pub fn AbortPrinter(hprinter: super::su... |
use std::collections::HashMap;
#[derive(Debug, PartialEq, Clone)]
pub enum JsonValue {
Null,
Boolean(bool),
Str(String),
Num(f64),
Array(Vec<JsonValue>),
Object(HashMap<String, JsonValue>),
}
|
// Copyright 2017 rust-ipfs-api Developers
//
// 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 accord... |
/*
* Firecracker API
*
* RESTful public-facing API. The API is accessible through HTTP calls on specific URLs carrying JSON modeled data. The transport medium is a Unix Domain Socket.
*
* The version of the OpenAPI document: 0.25.0
* Contact: compute-capsule@amazon.com
* Generated by: https://openapi-generator.t... |
use super::*;
type FaultResult = Result<(), Fault>;
fn init_logger() {
let _ = env_logger::builder().is_test(true).try_init();
}
#[test]
fn test_advancing() -> FaultResult {
init_logger();
let mut ic = IntCodeComputer::from_str("1,0,0,0,2,0,0,0,99")?;
ic.advance(4)?;
assert_eq!(ic.program_count... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.