text stringlengths 8 4.13M |
|---|
#![feature(plugin)]
#![feature(decl_macro)]
#![plugin(rocket_codegen)]
extern crate rocket;
use rocket::response::{NamedFile};
use rocket::http::{Status, Cookie, Cookies};
use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
extern crate rocket_contrib;
extern crate rand;
#[macro_use]
ext... |
use std::env;
use std::error::Error;
use std::fs;
use std::path::Path;
fn main() -> Result<(), Box<dyn Error>> {
let out_dir = env::var_os("OUT_DIR").unwrap();
let src_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let out_path = Path::new(&out_dir);
let original_path = src_path.join("getti... |
use reqwest::Error;
pub fn error_conversion() -> fn(Error) -> String {
|e| e.to_string()
}
#[derive(Debug, Clone)]
pub struct UrlHelper {
hostname: String,
}
impl UrlHelper {
pub fn new(hostname: String) -> Self {
UrlHelper {
hostname
}
}
pub fn get_database_url(&self... |
use super::*;
#[derive(Clone,Copy,Eq,Serialize,Deserialize)]
pub struct Vertex {
pub id:i32,
pub x: i32,
pub y: i32,
// fuer Dijkstra
pub dist:i32,
pub parent:Option<i32>,
}
js_serializable!(Vertex);
js_deserializable!(Vertex);
impl AsIndexForGraph for Vertex {
fn index(&self) -> &i32 {&(... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "System_RemoteDesktop_Input")]
pub mod Input;
#[repr(transparent)]
#[doc(hidden)]
pub struct IInteractiveSessionStatics(pub ::windows::core::IInspectable);
unsafe impl ::windo... |
pub mod drawable;
pub mod object;
|
use std::io::stdout;
use anyhow::Result;
use clap::{crate_version, App, AppSettings, Arg, Shell, SubCommand};
mod subcommands;
pub mod traits;
use traits::SyntaxDotApp;
static DEFAULT_CLAP_SETTINGS: &[AppSettings] = &[
AppSettings::DontCollapseArgsInUsage,
AppSettings::UnifiedHelpMessage,
AppSettings::S... |
#![allow(unused_imports)]
// main lib.rs
use command_line_apps_in_rust::search_content;
// declare modules
mod constants;
mod http_client;
mod process;
mod subcommands;
// bring data module used data structures
// self says we’re finding a module that’s a child of the current module (is optional, work without self:: to... |
use std::error::Error as StdError;
use std::fmt::{Display, Error as FmtError, Formatter};
use std::io::Error as IoError;
use std::io::ErrorKind as IoErrorKind;
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct ContentClassificationError {
inner: Box<dyn StdError>,
kind: ContentClassificationErrorKind... |
use std::ffi::{CStr, CString, IntoStringError, NulError};
use std::os::raw::c_char;
use std::str::Utf8Error;
use std::marker::Sized;
use std::mem;
// -------------------- Our Trait ------------------------
pub trait ReprC {
type C;
type Error;
fn from_repr_c_owned(c: *mut Self::C) -> Result<Self, Self::E... |
#![allow(unused_imports)]
#![allow(dead_code)]
#![allow(unused_variables)]
use std::env;
use std::fs;
use std::thread;
use std::path::Path;
use std::str::from_utf8;
use basic_common::SOCKET_PATH;
use basic_common::*;
use sodiumoxide;
use std::collections::HashMap;
use serde::{Serialize, Deserialize};
use std::io::{Read... |
mod leapyear;
fn main() {
leapyear::run();
}
|
extern crate num;
use std::env;
use num::BigUint;
struct PalNum {
num: BigUint,
rnum: BigUint,
niter: u32,
}
impl PalNum {
fn next(&mut self) {
self.num = &self.num + &self.rnum;
self.rnum = reverse(&self.num);
self.niter += 1;
}
}
fn reverse(num: &BigUint) -> BigUint {
let mut rnum_str = num.to_string(... |
mod models;
use models::*;
fn main() {
let p = 1205;
let d = Discount::rate_with(10, Rounding::Ceil);
println!("{:?}", d);
println!("{}", d.discount(&p));
}
|
use itertools;
use itertools::Itertools;
use itertools::PutBack;
use std::str::Chars;
const STRING_DELIM: char = '"';
const PIPE_DELIM: char = '|';
#[derive(Debug, PartialEq)]
pub enum Token {
Morpheme(String),
Str(String),
Pipe,
UnterminatedString,
}
pub struct Lex<'a> {
iter: PutBack<Chars<'a>>... |
use std::collections::{HashMap};
use nalgebra::{Vector2};
use render::{Renderer};
use scripting::{ScriptRuntime};
use template::{ComponentTemplate, Attributes};
use {EventSink, ComponentAttributes, Error, ComponentId};
/// The class of a component, defines specific appearance and functionality in response to user
//... |
/// Returns the original function pointer.
///
/// This should only be used from the main game thread.
macro_rules! real {
($f:ident) => {
FUNCTIONS.as_ref().unwrap().$f
};
}
/// Returns a pointer from the POINTERS variable.
///
/// This should only be used from the main game thread.
macro_rules! ptr {... |
//! This crate aims to provide a convenient and lightweight way
//! to clone errors and share them across thread-boundaries.
//!
//! It is designed to be used in conjunction with the
//! [`failure`](https://crates.io/crates/failure) crate.
//!
//! # Example
//!
//! ```rust
//! # extern crate failure;
//! # extern crate... |
fn main() {
let condition = true;
let number = if condition { 5 } else { 6 };
println!("The value of number is: {}", number);
counter_example();
for_loop_ex();
for_loop_reverse_range_ex();
}
fn counter_example() {
let mut counter = 0;
let result = loop {
counter += 1;
if... |
#![allow(dead_code, non_camel_case_types, unused_macros)]
#![no_implicit_prelude]
// TODO: remove this: https://github.com/dtolnay/async-trait/issues/132
use ::async_graphql::{self, InputValueResult, ScalarType, Value};
use ::serde::{Deserialize, Serialize};
use ::std::boxed::Box;
// TODO: remove this: https://github.... |
use {
crate::identity::Keyed,
std::{
collections::{HashMap, HashSet, VecDeque},
hash::Hash,
sync::{Arc, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard},
},
};
/// A unique queue who's key is the same as it's contained type.
pub type UniqueQueueKeyed<T> = UniqueQueue<T,... |
#![allow(dead_code)]
use crate::{aocbail, regex, utils};
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashMap;
use utils::{AOCError, AOCResult};
lazy_static! {
static ref RULE_REGEX: Regex = regex!(r"^([0-9]+): ");
}
#[derive(Debug)]
pub enum Rule {
And(Vec<Rule>),
Or(Vec<Rule>),... |
/*
Copyright (c) 2015, 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, di... |
use std;
use std::cell::RefCell;
use failure::Fail;
use libc;
use telamon;
use telamon_utils::unwrap;
/// Indicates if a telamon function exited correctly.
#[repr(C)]
pub enum TelamonStatus {
Ok,
Fail,
}
#[derive(Debug, Fail)]
#[repr(C)]
pub enum Error {
#[fail(display = "{}", _0)]
IRError(#[cause] ... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "UI_Xaml_Automation")]
pub mod Automation;
#[cfg(feature = "UI_Xaml_Controls")]
pub mod Controls;
#[cfg(feature = "UI_Xaml_Core")]
pub mod Core;
#[cfg(feature = "UI_Xaml_Data"... |
//! External APIs exposed by an ingester & their handlers.
pub(crate) mod grpc;
|
//! Implementation of core data structures.
pub mod matrix;
pub use matrix::Matrix;
|
use std::{convert::TryFrom, result::Result as StdResult};
use conduit::{Database, Error as ConduitError, Ruma, RumaResponse, State};
use libp2p::floodsub;
use ruma::{
api::client::r0::{
account::register::{self, RegistrationKind},
membership::join_room_by_id,
message::create_message_event,
... |
#![cfg(feature = "serde_json_serializer")]
#![allow(unused_attributes)]
#![feature(no_coverage)]
use std::rc::{Rc, Weak};
use fuzzcheck::mutators::grammar::*;
use fuzzcheck::mutators::testing_utilities::test_mutator;
// use fuzzcheck::{DefaultMutator, Mutator};
#[no_coverage]
fn text() -> Rc<Grammar> {
regex("([... |
pub mod ccls;
pub mod clangd;
pub mod codeaction;
pub mod completion;
pub mod cquery;
pub mod document_symbol;
pub mod eclipse_jdt_ls;
pub mod formatting;
pub mod goto;
pub mod highlights;
pub mod hover;
pub mod range_formatting;
pub mod rename;
pub mod rust_analyzer;
pub mod semantic_tokens;
pub mod signature_help;
|
use lazy_static::lazy_static;
use regex::Regex;
lazy_static! {
static ref PERSIAN_STR: Regex = Regex::new(r"^[\u0600-\u06FF]+$").unwrap();
static ref HAS_PERSIAN_CHAR: Regex = Regex::new(r"[\u0600-\u06FF]").unwrap();
}
pub fn has_persian_char<T: AsRef<str>>(s: T) -> bool {
HAS_PERSIAN_CHAR.is_match(s.as_r... |
//! `token` contains the `Token` structure.
use crate::{Identifier, Position};
use std::fmt;
/// `Token` represents a token, containing the token's type and its line and column.
#[derive(Clone, Debug, PartialEq)]
pub struct Token {
/// The `Token`'s type.
pub token: TokenType,
/// The `Token`'s position i... |
use crate::error::{Error, UnexpectedNullError};
pub trait ResultExt<T>: Sized {
fn try_unwrap_optional(self) -> crate::Result<T>;
}
impl<T> ResultExt<T> for crate::Result<T> {
fn try_unwrap_optional(self) -> crate::Result<T> {
self
}
}
impl<T> ResultExt<T> for crate::Result<Option<T>> {
fn tr... |
extern crate bs58;
extern crate ethabi;
extern crate futures;
extern crate graph;
extern crate graph_runtime_derive;
extern crate hex;
extern crate pwasm_utils;
extern crate semver;
extern crate tiny_keccak;
extern crate wasmi;
mod asc_abi;
mod host;
mod module;
mod to_from;
/// Runtime-agnostic implementation of exp... |
#[cfg(feature = "writer")]
pub mod writer_properties;
#[cfg(feature = "async")]
pub mod fetch;
|
//! Holds the latency between each node and its dependencies.
use crate::model::FastBound;
use fxhash::FxHashMap;
use itertools::Itertools;
use std::collections::hash_map;
/// Holds the latency between each node and its dependencies. Nodes must be sorted.
#[derive(Clone, Debug)]
pub struct DependencyMap {
deps: Ve... |
use crate::{BrokerRequest, NodeRequest, QueryRequest, QueryResponse, RequestId, ResponseStatus};
use std::time::Duration;
use im_rc::{HashMap, Vector};
/// Timeline is used to move forward and rewind the simulation.
/// To this end, the user-fronting information is stored in a sequence of immuatble structures.
pub s... |
use crate::base::Mat;
use crate::base::Vector;
use crate::base::Layer;
use crate::base::Node;
pub struct SoftmaxLayer {
pub node: Node,
}
impl SoftmaxLayer {
pub fn new() -> Self {
SoftmaxLayer {
node: Node {
input: vec![],
output: vec![],
},
... |
extern crate gif;
use std::env;
use std::env::args;
use std::fs::File;
use std::io::Read;
use std::borrow::Cow;
use std::iter::Iterator;
use std::collections::HashMap;
use gif::{Frame, Encoder, Repeat, SetParameter};
#[derive(Clone)]
struct Bits<'a> {
bytes: &'a Vec<u8>,
bit_offset: usize,
}
impl<'a> Ite... |
//! WebAssembly bindings to the [`open_ttt_lib`] TicTacToe library
//!
//! This is a simple library to show how to run Rust code in the browser
//! via WebAssembly. All the computation logic is WASM-agnostic (except
//! the random number generator)
//!
//! ### Random numbers in WebAssembly
//! To use the [`rand`] crate... |
pub mod abstract_window;
mod events;
#[cfg(not(target_arch = "wasm32"))]
mod opengl;
#[cfg(target_arch = "wasm32")]
mod webgl;
pub use self::abstract_window::AbstractWindow;
pub use self::events::*;
#[cfg(target_arch = "wasm32")]
pub use self::webgl::WebGLWindow as Window;
#[cfg(not(target_arch = "wasm32"))]
pub use... |
pub type Mat = Vec<Vec<f32>>;
pub type Vector = Vec<f32>;
pub fn vec_sum_mutiplier(vc1: &Vector, vc2: &Vector) -> f32 {
if vc1.len() != vc2.len() {
panic!(
"vector size is not equals!!! {} and {}",
vc1.len(),
vc2.len()
)
}
let mut sum = 0.0f32;
fo... |
// Copyright 2016 PingCAP, Inc.
//
// 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 i... |
use crate::exception::{Fault, RateLimitException};
use ratelimit_meter::{algorithms::NonConformance, KeyedRateLimiter};
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use warp::{Filter, Rejection};
/// Create a filter that gates a request behind a leaky bucket rate limiter.
///
/// # Pa... |
fn main() {
let s = r"
# sample1
markdown sample
* item-1
* item-2
* item-2-1
";
let parser = pulldown_cmark::Parser::new(s);
let mut res = String::new();
pulldown_cmark::html::push_html(&mut res, parser);
println!("{}", res);
}
|
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TokenKind {
Identifier,
Number,
Plus,
Minus,
Times,
Divide,
Exponent,
LParen,
RParen,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Token {
pub kind: TokenKind,
pub value: String,
pub start: usize,
pub end: usize,
pub line: usize,
pub co... |
extern crate test;
use stringify::Stringify;
use std::ffi::{CStr, CString};
use std::borrow::Cow;
use self::test::Bencher;
#[bench]
fn convert_to_cow_str_bench(b: &mut Bencher) {
let s = String::from("hello");
b.iter(|| s.convert_to_cow_str());
}
#[bench]
fn convert_to_cstr_bench(b: &mut Bencher) {
let s = Str... |
use super::{
pending::{prepare_user_activation, PendingUser},
User,
};
use crate::{
datastore::prelude::*,
mail::{send_mail, templates::MailTemplate},
};
use futures::join;
use juniper::ID;
use utils::PathToRef;
pub fn get_user_path<'a>(id: &ID) -> PathToRef<'a> {
vec![(KeyKind("Users"), KeyId::Cui... |
use super::double::double_escape_sequence;
use super::double::interpolated_character_sequence;
use crate::lexer::*;
/// `%q` *non_expanded_delimited_string*
pub(crate) fn quoted_non_expanded_literal_string(i: Input) -> StringResult {
preceded(tag("%q"), non_expanded_delimited_string)(i)
}
/// `%` `Q`? *expanded_d... |
pub enum Shape<T>
where
T: Into<f64> + Copy,
{
Circle(T),
Rectangle(T, T),
Sphere(T),
Parallelepiped(T, T, T),
}
pub mod area {
use crate::Shape;
use std::f64::consts::PI;
pub fn area<T>(s: &Shape<T>) -> f64
where
T: Into<f64> + Copy,
{
match *s {
Sh... |
use std::io;
use std::env;
use pem;
use rsa_fdh;
use rsa_fdh::blind;
use rsa::{RSAPrivateKey, RSAPublicKey};
use sha2::{Sha256};
use rand;
use base64;
use std::error::Error;
fn sign() -> Result<(), Box<dyn Error>> {
let mut rng = rand::thread_rng();
let mut encoded_digest = String::new();
io::stdin... |
pub const HBAR: f64 = 1.0;
pub const PI: f64 = std::f64::consts::PI;
|
extern crate yasna;
extern crate base64;
extern crate num;
extern crate byteorder;
const RSA_ENCRYPTION: [u64; 7] = [1, 2, 840, 113549, 1, 1, 1];
const SSH_RSA_TEXT: &str = "ssh-rsa";
use std::io::{Read, BufRead};
use std::io::{self, BufReader};
use num::bigint::{BigInt, Sign};
use base64::{decode, encode, DecodeErro... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "AI_MachineLearning")]
pub mod MachineLearning;
|
//! <https://github.com/EOSIO/eosio.cdt/blob/4985359a30da1f883418b7133593f835927b8046/libraries/eosiolib/core/eosio/name.hpp#L28-L269>
mod name_type;
use crate::bytes::{NumBytes, Read, Write};
use core::{
convert::TryFrom,
fmt,
str::{self, FromStr},
};
pub use eosio_numstr::ParseNameError;
use eosio_numstr... |
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::DCRIC {
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::... |
//! Contains ffi-safe equivalents of tuples up to 4 elements.
#![allow(non_snake_case)]
macro_rules! declare_tuple {
(
struct_attrs[ $(#[$meta: meta])* ]
into_tuple_attrs[ $(#[$into_tuple_attrs: meta])* ]
from_tuple_attrs[ $(#[$from_tuple_attrs: meta])* ]
$tconstr: ident[$( $tparam: ident ),* $(,)?... |
use std::{cell::Cell, marker::PhantomData};
use self_cell::self_cell;
self_cell! {
struct Foo<'a> {
owner: PhantomData<&'a ()>,
#[not_covariant]
dependent: Dependent,
}
}
type Dependent<'q> = Cell<&'q str>;
fn main() {
let foo = Foo::new(PhantomData, |_| Cell::new(""));
let s... |
pub enum FisType {
/// Register FIS – Host to Device
RegisterFis_H2D = 0x27,
/// Register FIS – Device to Host
RegisterFis_D2H = 0x34,
/// DMA Activate FIS – Device to Host
DmaActivate_D2H = 0x39,
/// DMA Setup FIS – Bi-directional
DmaSetup = 0x41,
/// Data FIS – Bi-directional
D... |
// 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::convert::TryInto;
use crate::{
angle::{DirectionX, DirectionY},
grid::Grid,
position::{SignedTilePosition, TilePosition, WorldCoords},
util::floats_equal,
AngleRad,
};
fn normalize_zeros(tp: &mut SignedTilePosition) {
// Avoid (-0.0)
if floats_equal(tp.rel_x, 0.0) {
tp.rel... |
use psp::sys::{DisplayMode, DisplayPixelFormat, DisplaySetBufSync};
pub struct Renderer {
draw_buffer: *mut u32,
disp_buffer: *mut u32,
}
impl Renderer {
pub unsafe fn new()-> Self {
let draw_buffer = psp::sys::sceGeEdramGetAddr() as *mut u32;
let disp_buffer = psp::sys::sceGeEdramGetAdd... |
use std::fs::File;
// #[warn(unused_variables)]
use std::io::Read;
use crate::slk_type::{Record, RecordType};
pub mod slk_type;
pub mod record;
pub mod document;
#[cfg(target_os = "macos")]
pub const END_RECORD: &str = "\n";
#[cfg(target_os = "windows")]
pub const END_RECORD: &str = "\r\n";
pub const FIELD_SEPARATOR:... |
//! The set of valid values for FTP commands
use std::convert::From;
use std::fmt;
/// A shorthand for a Result whose error type is always an FtpError.
pub type Result<T> = std::result::Result<T, FtpError>;
/// `FtpError` is a library-global error type to describe the different kinds of
/// errors that might occur w... |
#![cfg(test)]
pub(crate) mod headers;
mod request;
mod response;
pub use request::request;
pub use response::TestResponseExt;
|
// 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 super::*;
#[derive(Debug, PartialEq)]
pub struct LogicalAnd {
pub first: Box<Node>,
pub second: Box<Node>,
}
#[derive(Debug, PartialEq)]
pub struct LogicalOr {
pub first: Box<Node>,
pub second: Box<Node>,
}
#[derive(Debug, PartialEq)]
pub struct LogicalNot {
pub expr: Box<Node>,
}
|
use iro::{Cmyk, CmykInt, Hsl, HslInt, Rgb};
fn main() {
let color = Rgb::new(85, 191, 100);
println!("{:?}", &color);
let color: Cmyk = color.into();
println!("{:?}", &color);
let color: CmykInt = color.into();
println!("{:?}", (color.c, color.m, color.y, color.k));
println!("{:?}", &color)... |
// Copyright (c) 2016 The Rouille developers
// 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. All files in the project carrying such
// notice may not be co... |
pub mod new_todo_request;
pub mod new_user_request;
use actix_web::error::{Error as ActixError, InternalError};
use actix_web::FromRequest;
use actix_web::{HttpRequest, HttpResponse};
use actix_web_validator::error::Error;
use actix_web_validator::{Json, JsonConfig};
use serde::de::DeserializeOwned;
use validator::Val... |
//! Translation of Differential's input sessions to unordered
//! collection updates.
//!
//! Although users can directly manipulate timely dataflow streams as
//! collection inputs, the `UnorderedSession` type can make this more
//! efficient and less error-prone. Specifically, the type batches up
//! updates with the... |
#[cfg(test)]
mod tests {
#[test]
fn mutable_and_let() {
// 默认为不可变变量,需要使用mut关键字声明可变
let mut _x = 5;
_x = 6;
println!("x: {}", _x);
// 重复let同一个变量名可以隐藏(shadowing)之前的变量,并且改变类型
// 实际上重新创建了变量,只是复用了变量名
let _y = 10;
let _y = "10";
println!("y: {}",... |
use super::*;
pub fn user_config(cfg: &mut web::ServiceConfig) {
cfg.service(user_account).service(user_playlist);
}
//用户账户
#[get("/user/account")]
async fn user_account(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
let query = req.query();
let mut data: Value = json!({});
... |
//! <https://github.com/EOSIO/eosio.cdt/blob/4985359a30da1f883418b7133593f835927b8046/libraries/eosiolib/core/eosio/ignore.hpp#L12-L20>
use crate::{NumBytes, Read, ReadError, Write, WriteError};
use core::marker::PhantomData;
impl<T> NumBytes for PhantomData<T> {
#[inline]
#[must_use]
fn num_bytes(&self) -... |
// 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 super::{
filter::*,
player_event::{PlayerEvent, SessionsWatcherEvent},
};
use crate::{Result, MAX_EVENTS_SENT_WITHOUT_ACK};
use failure::Result... |
use crate::drawable::Drawable;
use crate::camera::Camera;
use graphics::types::Color;
use graphics::{Context, Graphics};
const PIXEL_PER_UNIT: i32 = 25;
pub struct Scene {
objects: Vec<Box<Drawable>>,
camera: Camera,
// Editor
display_grid: bool,
grid_color: Color
}
impl Scene {
pub fn new() -> Scene... |
use super::core::Filter;
use tree_sitter::{Node, TreeCursor};
enum State {
Curr,
Child,
Sibling,
Parent,
}
pub struct NodeIterator<'a> {
state: State,
cursor: TreeCursor<'a>,
source: &'a str,
sub_tree_filter: &'a dyn Filter,
}
impl<'a> NodeIterator<'a> {
pub fn new(cursor: TreeCur... |
use async_trait::async_trait;
use tokio::sync::mpsc::{error::SendError, Sender, UnboundedSender};
/// Trait to abstract over [bounded](Sender) and [unbounded](UnboundedSender) tokio [MPSC](tokio::sync::mpsc) senders.
#[async_trait]
pub trait AbstractSender: Clone + Send + Sync + 'static {
/// Channel payload type.... |
use crate::{
dfa::{automaton::Automaton, dense, sparse},
util::id::StateID,
};
impl<T: AsRef<[u32]>> fst::Automaton for dense::DFA<T> {
type State = StateID;
#[inline]
fn start(&self) -> StateID {
self.start_state_forward(None, &[], 0, 0)
}
#[inline]
fn is_match(&self, state: ... |
pub mod lexer;
pub mod tokenization;
|
use std::env::var;
//use std::process::Command;
//use std::path::{Path};
fn main() {
let manifest_dir = var("CARGO_MANIFEST_DIR").unwrap();
setup(&manifest_dir);
// println!("cargo:rustc-link-search={}/../build-win32/dist/cpp", manifest_dir);
// println!("cargo:rustc-link-search={}/../build-win32... |
use msfs::{nvg, MSFSEvent};
#[msfs::gauge(name=DEMO)]
async fn demo(mut gauge: msfs::Gauge) -> Result<(), Box<dyn std::error::Error>> {
let nvg = gauge.create_nanovg().unwrap();
let black = nvg::Style::default().fill(nvg::Color::from_rgb(0, 0, 0));
let white = nvg::Style::default().fill(nvg::Color::from_r... |
use crate::{Point, Ray};
#[derive(Clone, Copy)]
pub struct AABB {
pub max: Point,
pub min: Point,
}
impl AABB {
pub fn new(min: Point, max: Point) -> Self {
Self { max, min }
}
pub fn hit(&self, ray: &Ray, mut t_min: f64, mut t_max: f64) -> bool {
for a in 0..3 {
let m... |
use crate::{symbol_code_from_bytes, ParseSymbolCodeError};
use core::{fmt, num::ParseIntError};
/// An error which can be returned when parsing an EOSIO symbol.
#[derive(Debug, PartialEq, Clone)]
pub enum ParseSymbolError {
/// The symbol precision couldn't be parsed.
Precision(ParseIntError),
/// The symb... |
use projecteuler::primes;
fn main() {
let mut total_counters = vec![0; 20];
for i in 2..=20 {
let mut counters = vec![0; 20];
for p in primes::factorize(i) {
counters[p] += 1;
}
//dbg!(&counters);
for i in 0..20 {
if total_counters[i] < counters[i... |
use core::ptr::{null, null_mut, NonNull};
use std::collections::HashMap;
use std::convert::TryInto;
use std::ffi::CString;
use futures_core::future::BoxFuture;
use futures_util::future;
use libsqlite3_sys::{
sqlite3, sqlite3_close, sqlite3_extended_result_codes, sqlite3_open_v2, SQLITE_OK,
SQLITE_OPEN_CREATE,... |
// 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... |
/*
* @lc app=leetcode.cn id=24 lang=rust
*
* [24] 两两交换链表中的节点
*
* https://leetcode-cn.com/problems/swap-nodes-in-pairs/description/
*
* algorithms
* Medium (57.73%)
* Total Accepted: 14.7K
* Total Submissions: 25.4K
* Testcase Example: '[1,2,3,4]'
*
* 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
*
* 你不能只是单纯的改变节点内部的值... |
use crate::{common::*, gui_component::*, prelude::*};
use raylib::prelude::*;
#[derive(PartialEq)]
pub struct Dropdown {
background_colour: Colour,
components: Vec<DrawableType>,
components_fixed_widths: bool,
font_size: i32,
pub actions: Vec<String>,
pub dimensions: Dimensions,
pub positio... |
use std::env;
use std::error::Error;
use std::fs;
#[derive(Debug)]
pub struct Config {
pub query: String,
pub filename: String,
pub case_sensitive: bool,
pub print_help: bool,
}
impl Config {
fn new_print_help() -> Config {
return Config {
query: String::from(""),
f... |
use std::sync::Arc;
pub struct LinkedListPersistent<T> {
head: Link<T>,
}
impl<T> LinkedListPersistent<T> {
pub fn new() -> Self {
LinkedListPersistent { head: None }
}
pub fn append(&self, value: T) -> Self {
LinkedListPersistent { head: Some(Arc::new(Node {
value: valu... |
fn check_if_30(a: i32, b: i32) {
if a + b == 30 {
println!("oh boy!");
}
}
fn main() {
let (a, b) = (10, 20);
check_if_30(a, b);
}
|
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
fn part1(s: &str) -> usize {
let mut v = vec![' '];
for c in s.chars() {
let last = *v.last().unwrap();
if c != last && c.eq_ignore_ascii_case(&last) {
v.pop();
} else {
v.push(c);
}
}
... |
pub mod purescript;
|
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::ICR {
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::re... |
//! Asynchronous UDP bindings.
//!
//! To create a bi-directional UDP socket use [`UdpSocket::bind`]. Sending data from the socket is
//! done by using [`send_to`] which returns the [`SendTo`] future. Reading data from the socket is
//! done by using [`recv_from`] which returns the [`RecvFrom`] future.
//!
//! [`UdpSoc... |
//! AST for the Rune language.
use crate::{Parse, ParseError, Parser, Peek};
use runestick::Span;
#[macro_use]
/// Generated modules.
pub mod generated;
macro_rules! expr_parse {
($ty:ident, $local:ty, $expected:literal) => {
impl crate::Parse for $local {
fn parse(p: &mut crate::Parser<'_>) ... |
// 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
use glib;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use glib::GString;
use glib_sys;
us... |
//! Implement elementary coordinate operations.
use mdio::RVec;
use std::error::Error;
use std::fmt;
use std::fmt::{Display, Formatter};
use std::ops::{Add, AddAssign, Sub, SubAssign, Neg, Mul, MulAssign};
use std::str::FromStr;
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
/// A three-dimensional carthesian... |
#[macro_use] extern crate serde_derive;
extern crate serde_xml_rs;
extern crate libc;
extern crate memmap;
extern crate byteorder;
extern crate zip;
pub mod archive;
pub mod constants;
pub mod ffi;
pub mod transducer;
pub mod types;
pub mod speller;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.