text stringlengths 8 4.13M |
|---|
// 2019-07-08
// move permet d'utiliser la donnée d'un thread dans un autre, ownership comprise
use std::thread;
fn main() {
let v = vec![1, 2, 3];
// En rajoutant le mot-clé move, on oblige la closure à prendre l'ownership
// de v.
let handle = thread::spawn(move || {
println!("Voici le vect... |
pub mod crdt;
pub mod backend;
|
use winapi::shared::minwindef::{DWORD, BOOL, ULONG};
use winapi::ctypes::{c_char, c_void};
extern "system" fn MessageBoxThread(param: *mut c_void) -> DWORD {
unsafe {
winapi::um::winuser::MessageBoxA(
std::ptr::null_mut(), // hWnd
b"Hello world!\0" as *const u8 as *const c_char, // ... |
/*
chapter 4
syntax and semantics
*/
fn main() {
let mut a = 5;
let b = &mut a; // -+ &mut borrow of x starts here
// |
*b += 1; // |
// |
println!("{}", a); // -+ - try to borrow x here
} // -+ &mut borrow of x ends he... |
extern crate parser_c;
use parser_c::parse_file_pre;
#[test]
fn simple_file() {
let input_file = "./tests/simple_file.c";
let todo = parse_file_pre(input_file);
println!("OUT {:#?}", todo);
}
|
use std::collections::HashMap;
use std::path::PathBuf;
mod pascal;
mod rms;
const MAX_TILE: i32 = 84;
const MIN_TILE: i32 = 1;
const MAX_ROOMS: u8 = 128;
const TILE_DIMENSIONS: u32 = 15;
const FIRST_OBJECT: u32 = 'd' as u32;
const LAST_OBJECT: u32 = 'w' as u32;
struct RmsTmxIntermediate {
id: u8,
tiles: Vec<... |
#[doc = "Register `AF2` reader"]
pub type R = crate::R<AF2_SPEC>;
#[doc = "Register `AF2` writer"]
pub type W = crate::W<AF2_SPEC>;
#[doc = "Field `BK2INE` reader - BRK2 BKIN input enable"]
pub type BK2INE_R = crate::BitReader;
#[doc = "Field `BK2INE` writer - BRK2 BKIN input enable"]
pub type BK2INE_W<'a, REG, const O... |
// Copyright 2018 The Open AI Team Authors, The Google AI Language Team Authors
// Copyright 2018 The HuggingFace Inc. team.
// Copyright 2019 Guillaume Becquin
// 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... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloudShellConsole {
#[serde(flatten)]
pub resource: Resource,
pub properties: ConsoleProperties,
}
#[de... |
// OUT_DIR is only defined when there is a build script
// https://github.com/rust-lang/cargo/issues/879#issuecomment-215491052
pub fn main() {}
|
pub fn convert(s: String, num_rows: i32) -> String {
if num_rows == 1 || s.len() == 0 {
return s;
}
let n = s.len();
let v: Vec<char> = s.chars().collect();
let mut r = Vec::<char>::with_capacity(n);
let m = (2*num_rows - 2) as usize;
let max_cycle = n / m + 1;
fn safe_insert(... |
//! optimize contains functionality for optimizing the representation of regular expressions for
//! more efficient matching. This means that the pattern is optimized before it being compiled to
//! the state machine.
use std::iter::{FromIterator, Iterator};
use std::ops::Deref;
use crate::repr::{Pattern, Repetition}... |
mod error;
use error::{Result, ResultExt, CliResult, Error, ErrorKind};
mod cli;
mod config;
use config::Config;
mod device;
use device::{Device, Event, RawEvent, OpMode, LatchState, ConnectionState};
mod service;
use service::{Service, DetachState};
use std::convert::TryFrom;
use std::{cell::RefCell, rc::Rc};
use... |
use crate::prelude::*;
const TWO: Decimal = Decimal::from_parts_raw(2, 0, 0, 0);
const PI: Decimal = Decimal::from_parts_raw(1102470953, 185874565, 1703060790, 1835008);
const LN2: Decimal = Decimal::from_parts_raw(2831677809, 328455696, 3757558395, 1900544);
const EXP_TOLERANCE: Decimal = Decimal::from_parts(2, 0, 0,... |
use std::ops::{Index, IndexMut};
#[derive(Debug, Clone, Copy)]
enum InstructionArgument {
Position(usize),
Immediate(i64),
Relative(isize),
}
impl InstructionArgument {
fn from(mode: u8, value: i64) -> Self {
match mode {
0 => InstructionArgument::Position(value as usize),
... |
use proc_macro2::TokenStream;
use quote::quote;
use syn::DeriveInput;
pub(crate) fn delete(input: &DeriveInput) -> TokenStream {
let ident = &input.ident;
quote! {
impl storm::provider::Delete<#ident> for storm::provider::TransactionProvider<'_> {
fn delete<'a>(&'a self, k: &'a <#ident as ... |
use crate::my_ndarray;
use ndarray::Ix2;
use ndarray::LinalgScalar;
#[cfg(test)]
use ndarray::{linalg, Array};
use ndarray::{ArrayView, ArrayViewMut};
#[cfg(test)]
use rand::Rng;
use rayon_adaptive::prelude::*;
use rayon_adaptive::BasicPower;
#[cfg(test)]
use rayon_adaptive::Policy;
pub struct Matrix<'a, 'b, 'd, A> {
... |
use std::sync::Arc;
use async_trait::async_trait;
use bonsaidb_core::{
circulate::Message,
custom_api::CustomApi,
networking::{DatabaseRequest, DatabaseResponse, Request, Response},
pubsub::{PubSub, Subscriber},
schema::Schema,
};
use serde::Serialize;
use crate::Client;
#[async_trait]
impl<DB, A... |
use std::collections::binary_heap::Iter;
use std::collections::{HashMap, HashSet, VecDeque};
use std::convert::TryFrom;
use std::hash::Hash;
use std::iter::Peekable;
use std::ops::{Index, IndexMut};
use std::str::FromStr;
use crate::data_dictionary::{DataDictionary, HEADER_ID, TRAILER_ID};
use crate::fields::*;
use cr... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagementLockOwner {
#[serde(rename = "applicationId", default, skip_serializing_if = "Option::is_none")]
... |
#[doc = "Reader of register CPU_WRITE_REG"]
pub type R = crate::R<u32, super::CPU_WRITE_REG>;
#[doc = "Writer for register CPU_WRITE_REG"]
pub type W = crate::W<u32, super::CPU_WRITE_REG>;
#[doc = "Register CPU_WRITE_REG `reset()`'s with value 0"]
impl crate::ResetValue for super::CPU_WRITE_REG {
type Type = u32;
... |
use std::{ops::Bound::*, ops::RangeBounds, path::PathBuf, str::FromStr};
use super::*;
use crate::preclude::*;
/// A three column data store including Data, Lock, Write
pub struct MultiStore {
data: EngineKind,
lock: EngineKind,
write: EngineKind,
}
impl MultiStore {
/// Create a new MultiStore in giv... |
use diesel::prelude::*;
use serde::Serialize;
use std::error::Error;
use tinytemplate::TinyTemplate;
use clap::{App, ArgMatches};
use feedspool::db;
use feedspool::models;
pub const NAME: &str = "render";
pub fn app() -> App<'static> {
App::new(NAME).about("Render feeds data as HTML")
}
static TEMPLATE: &str =... |
extern crate nfa;
use nfa::*;
#[test]
fn test() {
let re = Regex::Empty;
let fa = re.make_fa();
assert!(fa.accepts(""));
for c in &['a', ' ', 'é'] {
let mut s = String::new();
for _ in 0..100 {
s.push(*c);
assert!(!fa.accepts(&s));
}
}
} |
pub(crate) const IMPORTANCE_EMOJIS: [&str; 5] = [" 0️", "✔️", "❗", "‼️", "️🔥"];
pub(crate) const EVALUATION_EMOJIS: [&str; 5] = ["😡", "🙁", "😐", "😊", "️😀"];
pub(crate) struct RedisKeys;
impl RedisKeys {
pub const PACKS: &'static str = "packs";
pub const LATEST_MESSAGE: &'static str = "latest_message";
}
... |
pub fn part_01(data: &str) -> usize {
let numbers: Vec<_> = data.lines().map(str::parse::<usize>).filter_map(std::result::Result::ok).collect();
let invalid = numbers.iter().skip(25).zip(numbers.windows(25)).find_map(|(elem, window)| {
for a in window.into_iter() {
for b in window.into_iter(... |
use anyhow::format_err;
use cargo::core::{TargetKind, Workspace};
use cargo::ops;
use cargo::util::CargoResult;
use cargo::CliError;
use itertools::Itertools;
use serde::Deserialize;
use std::collections::btree_map::BTreeMap;
use std::env;
use std::fs;
use std::fs::File;
use std::io::Read;
use std::iter::FromIterator;
... |
use std::cmp::Ordering;
#[derive(Debug, PartialEq, Eq)]
pub enum Classification {
Abundant,
Perfect,
Deficient
}
pub fn classify(num: u64) -> Result<Classification, & 'static str> {
if num <= 0 {
return Err("Number must be positive");
}
let aliquot: u64 = (1..num / 2 + 1).filter(|x| n... |
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// AwsLogsAsyncError : Description of errors.
#[derive(Clone, Debug, PartialEq, Serialize, Deseriali... |
use std::cmp;
use std::collections::BTreeMap;
use std::fmt;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::u64;
pub struct Aggregator {
pub min: u64,
pub max: u64,
pub avg: f64,
}
impl Aggregator {
pub fn empty() -> Self {
Aggregator {
min: 0,
max:... |
// MIT License
//
// Copyright (c) 2021 Ferhat Geçdoğan All Rights Reserved.
// Distributed under the terms of the MIT License.
//
//
use {
std::io::BufRead,
crate::{
ast::ast_helpers::{to},
tokenizer::gretea_tokenizer::{is_comment}
}
};
#[derive(Clone)]
pub struct GreteaFileData {
pu... |
use std::fmt::Display;
use apllodb_storage_engine_interface::ColumnName;
use serde::{Deserialize, Serialize};
/// Name of an attribute.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub(crate) enum AttributeName {
/// Column
ColumnNameVariant(ColumnName),
}
impl Attrib... |
#![ feature( optin_builtin_traits ) ]
// TODO:
// - ✔ basic usage (using addr directly uses recipient, so that's already tested)
// Let's test storing Box<Address<M>> to several actors and send/call on that
//
// - ✔ Receiver
// - ✔ construct receiver from address and send/call
// - ✔ cast to Box<Any> and down... |
use crate::actor::*;
use super::actor_io::*;
use rdkafka::producer::{FutureRecord, FutureProducer, future_producer::OwnedDeliveryResult};
use rdkafka::util::Timeout;
pub const BOOTSTRAP_SERVERS: &str = "127.0.0.1:9092";
pub const TOPIC: &str = "blockchain";
pub const EVENTS_KEY: &str = "events";
pub struct MessageB... |
use std::cell::RefCell;
#[derive(Debug)]
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
fn build_user(email: String, username: String) -> User {
User {
email: email,
username: username,
active: true,
sign_in_count: 1,
}
}
#[d... |
use std::convert::Infallible;
use sqlx::PgPool;
use warp::Filter;
use crate::error::Error;
pub fn with_db(pool: PgPool) -> impl Filter<Extract = (PgPool,), Error = Infallible> + Clone {
warp::any().map(move || pool.clone())
}
pub fn string_body() -> impl Filter<Extract = (String,), Error = warp::Rejection> + Co... |
#![feature(proc_macro_hygiene, decl_macro)]
use rocket::*;
use rocket_contrib::{json::Json, serve::StaticFiles, templates::Template};
use std::path::Path;
mod lib;
#[get("/hello/<name>")]
fn hello(name: String) -> String {
format!("Hello, {}! Welcome My Server with Rocket!", name)
}
#[get("/bye/<name>")]
fn bye... |
use super::auto::{HasInner, Abstract};
use super::container::{Container, ContainerInner};
use super::control::{Control};
use super::member::{AMember, MemberBase, Member};
define_abstract! {
MultiContainer: Container {
outer: {
fn len(&self) -> usize;
fn set_child_to(&mut self, index... |
use std::collections::HashMap;
use std::sync::Mutex;
pub struct Repository<T> where T: Clone {
entities: Mutex<HashMap<String, T>>,
}
impl<T> Repository<T> where T: Clone {
pub fn new() -> Repository<T> {
Repository { entities: Mutex::new(HashMap::new()) }
}
pub fn add(&self, key: String, valu... |
use glium;
use glium::glutin;
use primitives::*;
use tree::*;
use render::*;
pub struct Window {
display: glium::Display,
rendering_context: RenderingContext,
tree: Tree,
size: Size,
title: String,
}
pub struct WindowBuilder {
size: Size,
title: String,
content: Option<Box<Element>>,... |
use crate::data::ArcDataSlice;
use crate::hlc;
use crate::network;
use crate::object;
use crate::store;
use crate::transaction;
pub struct Allocate {
pub to: store::Id,
pub from: network::ClientId,
pub new_object_id: object::Id,
pub kind: object::Kind,
pub max_size: Option<u32>,
pub initial_re... |
use crate::states::{loading::LoadingState, menu::MenuState};
use oxygengine::{prelude::*, user_interface::MessageData};
use serde::{Deserialize, Serialize};
#[derive(MessageData, Debug, Default, Copy, Clone, Serialize, Deserialize)]
pub struct IntroStopSignal;
#[derive(Debug, Default)]
pub struct IntroState;
impl St... |
enum UsernameError {
NotLowercase,
NotUnique,
}
fn main() {
match validate_username("user1") {
Ok(()) => println!("Valid username"),
Err(UsernameError::NotLowercase) => println!("Username must be lowercase"),
Err(UsernameError::NotUnique) => println!("Username already exists"),
}
}
fn validate_use... |
pub struct Stack<T> {
head: Link<T>,
}
type Link<T> = Option<Box<Node<T>>>;
struct Node<T> {
elem: T,
next: Link<T>,
}
impl<T> Stack<T> {
pub fn new() -> Self {
Stack { head: None }
}
pub fn push(&mut self, elem: T) {
let new_node = Box::new(Node {
elem: elem,
... |
#[allow(dead_code)]
fn read_line() -> String {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim_end().to_owned()
}
fn main() {
let stdin = read_line();
let mut iter = stdin.split_whitespace();
let h: usize = iter.next().unwrap().parse().unwrap();
let w... |
#[macro_export]
macro_rules! table {
(
$table:ident {
$(
$col:ident -> $ty:ident,
)*
}
) => {
#[allow(
unused_variables,
dead_code,
missing_docs,
non_camel_case_types,
)]
mod $table {
... |
use std::{env, thread, time};
fn main() {
let a: Vec<String> = env::args().collect();
loop {
println!("{:?}", a[1]);
thread::sleep(time::Duration::from_millis(1200));
}
}
|
fn main() {
let number = 8;
if number < 5 {
println!("condition was true");
} else {
println!("conditon was false");
}
if number !=0 {
println!("number is sth else than zero");
}
if number % 4 == 0{
println!("number is dvisible by 4");
} else if number... |
use std::fs::File;
use std::io::{BufReader,BufRead};
fn main() {
let file = File::open("resource/mass.txt").unwrap();
let numbers: Vec<u32> = BufReader::new(file).lines().map(|v| v.unwrap().parse::<u32>().unwrap()).collect();
let total_fuel = |sum:u32, fuel: &u32| {
let mut fuel_fuel = *fuel;
let mut ... |
use proconio::input;
fn main() {
input! {
n:u32,
h:u32,
w:u32,
};
let ans = (n - h + 1) * (n - w + 1);
println!("{}", ans);
}
|
#[doc = "Register `HWCFGR` reader"]
pub type R = crate::R<HWCFGR_SPEC>;
#[doc = "Field `CHANNELS` reader - CHANNELS"]
pub type CHANNELS_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:7 - CHANNELS"]
#[inline(always)]
pub fn channels(&self) -> CHANNELS_R {
CHANNELS_R::new((self.bits & 0xff) as u8)
... |
use crate::{util};
use reqwest::header::HeaderMap;
use reqwest::{RequestBuilder, Response, Url};
use std::str::FromStr;
// TODO: docs
pub fn paginate(
req: &RequestBuilder,
from: u32,
per_page: u32,
) -> Result<Vec<Response>, reqwest::Error> {
let mut pager = Some(from);
let mut out = vec![];
... |
use std::io;
fn main() {
let mut numbers = String::new();
println!("Enter numbers to sort, separated by space -", );
io::stdin().read_line(&mut numbers).ok().expect("read error");
let mut numbers: Vec<i32> = numbers
.split_whitespace()
.map(|s| s.parse().unwrap())
.collect();
... |
struct Solution();
use std::collections::HashMap;
impl Solution {
pub fn contains_duplicate(nums: Vec<i32>) -> bool {
let mut map:HashMap<i32,u8>=HashMap::new();
for i in 0..nums.len(){
match map.get_mut(&nums[i]){
Some(_value)=>{return true;},
None=>{map.... |
use super::{
textinput::TextInputComponent, visibility_blocking,
CommandBlocking, CommandInfo, Component, DrawableComponent,
};
use crate::{
keys,
queue::{InternalEvent, NeedsUpdate, Queue},
strings,
ui::style::SharedTheme,
};
use anyhow::Result;
use asyncgit::{
sync::{self, CommitId},
C... |
use crate::vrs::{Requirement, Version};
use serde::{de, Deserialize, Deserializer};
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use std::str::FromStr;
use thiserror::Error;
#[derive(Deserialize, Debug, Default, Clone)]
pub struct PackageJson {
pub name: Option<Str... |
use crate::{
assets::Color,
hex::pointer::{HexPointer, VerticalDirection},
world::RhombusViewerWorld,
};
use amethyst::{
core::{math::Vector3, transform::Transform},
ecs::prelude::*,
input::{get_key, ElementState},
prelude::*,
winit::VirtualKeyCode,
};
use rhombus_core::hex::coordinates:... |
use std::ffi::CStr;
use std::str;
use esp_idf_bindgen::{esp_err_t, esp_err_to_name};
#[derive(Clone, Debug)]
pub struct EspError { pub(crate) code: esp_err_t }
impl From<!> for EspError {
fn from(_: !) -> Self {
loop {}
}
}
impl core::fmt::Display for EspError {
fn fmt(&self, f: &mut core::fmt::Formatter... |
use crate::Resource;
fn model_set_objective_function(resource: &Resource) -> String {
resource
.knobs
.iter()
.flat_map(|knob| {
knob.layers.iter().flat_map(|layer| {
layer
.basic_nodes
.iter()
.map(|nod... |
use rand::Rng;
use seckey::TempKey;
use ::kex::KeyExchange;
use ::aead::AeadCipher;
pub trait SealedBox: KeyExchange {
fn send<R, AE>(r: R, pk: &Self::PublicKey)
-> (Self::Message, AE)
where
R: Rng,
AE: AeadCipher,
// AE::KEY_LENGTH = Self::SHARED_LENGTH
;
... |
use std::error::Error;
fn read_num() -> Result<(), Box<dyn Error>> {
let s = std::fs::read_to_string("numfile")?;
let num: usize = s.trim().parse()?;
println!("File contains number {}", num);
Ok(())
}
fn main() {
if let Err(e) = read_num() {
eprintln!("Error while reading 'numfile': {:?}",... |
//! This (WIP) example demonstrates how to communicate using Spi and Uart with
//! an external peripheral using Direct Memory Access (DMA)
//! todo: Only a skeleton: Missing critical content.
#![no_main]
#![no_std]
use core::cell::{Cell, RefCell};
use cortex_m::{
interrupt::{self, free, Mutex},
peripheral::... |
//! 13. 罗马数字转整数
//! https://leetcode-cn.com/problems/roman-to-integer/
pub struct Solution;
impl Solution {
pub fn roman_to_int(s: String) -> i32 {
let chars = s.chars();
for _c in chars {}
return 2;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_roman_to_int(... |
//! A Rust implementation of [glMatrix](http://glmatrix.net/)
//!
//! gl_matrix provides utilities or all [glMatrix](http://glmatrix.net/) functions in Rust.
//!
//! # Quick Start
//!
//! Getting started should be easy if you are already familiar with [glMatrix](http://glmatrix.net/)
//! and Rust. All functions have... |
#[macro_use]
extern crate clap;
use anyhow::*;
use drg::*;
use indicatif::{ParallelProgressIterator, ProgressBar, ProgressStyle};
use rayon::iter::*;
use std::io::prelude::*;
use std::io::BufWriter;
use std::path::*;
use walkdir::WalkDir;
fn main() {
let matches = clap_app!(DRGEditor =>
(version: "0.1.0")
(... |
//! Configuration objects for the ATLAS system.
use {Error, Result};
use glacio::atlas::{Efoy, Heartbeat, ReadSbd, SbdSource};
/// ATLAS configuration.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct Config {
/// The path to the SBD storage.
pub path: String,
/// The IMEI number of the modem that... |
pub trait Merge {
/// An implementation for each implementing objects
/// which creates a new instance merging `self` and the `other` item.
fn merge(&self, other: &Self) -> Option<Self>
where
Self: Sized;
/// Merge all items until the size don't change
fn merge_recursive(items: impl Int... |
use log::{debug, trace};
use failure::Error;
// use failure_derive;
use std::sync::{Arc, RwLock};
use portaudio::{
DuplexStreamCallbackArgs, DuplexStreamSettings, PortAudio, Stream, StreamParameters,
};
use hero_studio_core::config::Audio as AudioConfig;
use hero_studio_core::studio::{AudioTime, Studio};
const C... |
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use crate::error;
const INIT_FILE_TEMPLATE: &str = r#"% This file is generated by vesti
docclass article
startdoc
Hello, World!
"#;
pub fn generate_vesti_file(mut project_name: PathBuf) -> error::Result<()> {
project_name.set_extension("ves");
let m... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Comparator control/status register"]
pub c1csr: C1CSR,
#[doc = "0x04 - Comparator control/status register"]
pub c2csr: C2CSR,
#[doc = "0x08 - Comparator control/status register"]
pub c3csr: C3CSR,
#[doc = "0x0c ... |
#![feature(test)]
extern crate test;
use doc_store::DocLoader;
use doc_store::DocStoreWriter;
#[bench]
fn bench_creation_im(b: &mut test::Bencher) {
b.iter(|| {
let mut writer = DocStoreWriter::new(0);
let mut sink = vec![];
for _ in 0..10_000 {
writer.add_doc(r#"{"test":"ok"}"... |
use super::postgres::{Connection, TlsMode};
pub struct Db {
pub conn: Connection,
}
impl Db {
pub fn init(conn_string: &str) -> Db {
let conn = Connection::connect(conn_string, TlsMode::None).unwrap();
let db = Db { conn };
db
}
}
|
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, PipelineData, Signature, Span, Spanned,
SyntaxShape, Value,
};
#[derive(Clone)]
pub struct Group;
impl Command for Group {
fn nam... |
use log::info;
use libapi_net::server::Server;
use libdriver::util::a_sync::AsyncRover;
use libdriver_robohat::RobohatRover;
use libutil::app::bootstrap;
const CONFIG_FILE: &str = "Config.toml";
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
info!("Rover api-net is starting up.");
... |
use std::sync::Arc;
use ntex::{web::types::{State, Path}};
use crate::{
errors::CustomError,
models::user::{Admin, User},
AppState,
};
pub async fn delete_comment(
user: User,
admin: Option<Admin>,
comment_id: Path<(u32,)>,
state: State<Arc<AppState>>,
) -> Result<String, CustomError> {
... |
use crate::features::syntax::MiscFeature;
use crate::parse::visitor::tests::assert_misc_feature;
#[test]
fn normal_method() {
assert_misc_feature(
"const obj = {
method() { return 3 },
}",
MiscFeature::Method,
)
}
#[test]
fn generator_method() {
assert_misc_feature(
... |
fn main() {
let y: Option<u8> = None;
}
|
#[doc = "Reader of register RISR"]
pub type R = crate::R<u32, super::RISR>;
#[doc = "Reader of field `MSTIR`"]
pub type MSTIR_R = crate::R<bool, bool>;
#[doc = "Reader of field `RXFIR`"]
pub type RXFIR_R = crate::R<bool, bool>;
#[doc = "Reader of field `RXOIR`"]
pub type RXOIR_R = crate::R<bool, bool>;
#[doc = "Reader ... |
use super::Pointer;
use std::fmt;
#[derive(Clone, Copy, Default, Debug)]
// Tuple struct
pub struct Register(u8);
impl From<u16> for Register {
fn from(t: u16) -> Self {
Register(t as u8)
}
}
impl From<u8> for Register {
fn from(t: u8) -> Self {
Register(t)
}
}
impl From<usize> for R... |
extern crate walkdir;
extern crate chrono;
#[macro_use]
extern crate log;
use std::path::Path;
use self::walkdir::{DirEntry, WalkDir};
use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;
use self::chrono::{DateTime, UTC};
use std::error::Error;
use std::str::FromStr;
use std::net::SocketAddrV4;
use std::f... |
use libc::getpid;
use std::env::*;
use std::path::PathBuf;
use serde::ser::Serialize;
#[derive(Serialize)]
struct ClientCapabilities;
enum TextDocumentSyncKind {
None, // 0
Full, // 1
Incremental, // 2
}
struct CompletionOptions {
resolveProvider: Option<bool>,
triggerCharacters: Option<Vec<Strin... |
use std::ffi::CString;
use std::path::Path;
use failure::Fallible;
use bindings;
use interpreter::Interpreter;
use op_resolver::OpResolver;
cpp!{{
#include "tensorflow/contrib/lite/model.h"
#include "tensorflow/contrib/lite/kernels/register.h"
using namespace tflite;
}}
pub struct FlatBufferModel {
... |
mod quicksort;
fn main() {
let mut nums = vec![9, 10, 2, 8, 4, 6, 3, 7, 5, 1, 3];
let n = nums.len();
//quicksort::do_sort(&mut nums, 0, n - 1);
quicksort::sort(&mut nums);
println!("Sorted nums: {:?}", nums);
}
|
use actix::prelude::*;
use sha256::digest;
use std::collections::HashMap;
use std::sync::RwLock;
use crate::application::app_to_game;
use crate::game_folder::game::Game;
use crate::game_folder::game_to_app;
use crate::handle_to_app::*;
// //* App State can receive messages about a new Game, the end of a Game, getting... |
fn main() {
let mut fees = 25_000;
println!("fees is {} ",fees);
fees = 35_000;
println!("fees changed is {}",fees);
} |
#![feature(asm)]
#![feature(compiler_builtins_lib)]
#![feature(lang_items)]
#![feature(naked_functions)]
#![no_std]
#[cfg(feature = "semihosting")]
#[macro_use]
extern crate cortex_m_semihosting;
extern crate compiler_builtins;
extern crate cortex_m;
extern crate wiring;
extern crate kbd;
extern crate futures;
extern ... |
use std::sync::MutexGuard;
use nia_interpreter_core::Interpreter;
use nia_interpreter_core::NiaInterpreterCommand;
use nia_interpreter_core::NiaInterpreterCommandResult;
use nia_interpreter_core::{EventLoopHandle, NiaExecuteCodeCommandResult};
use crate::error::{NiaServerError, NiaServerResult};
use crate::protocol:... |
//! Processing a Series of Items with [Iterators]
//!
//! [iterators]: https://doc.rust-lang.org/book/ch13-02-iterators.html
/// `Shoe` type demonstrates the `filter` iterator adaptor.
#[derive(PartialEq, Debug)]
pub struct Shoe {
pub size: f32,
pub style: String,
}
/// Collect the `shoe_size` [`Shoe`]s.
///
... |
#[derive(Debug, Clone, Copy, FromPrimitive, Ord, PartialOrd, Eq, PartialEq)]
pub enum Bytecode {
Nop = 0x0,
LoadNull = 0x1,
LoadConst = 0x2,
LoadValue = 0x3,
LoadDot = 0x4,
LoadSubscript = 0x5,
LoadOp = 0x6,
PopTop = 0x7,
DupTop = 0x8,
Swap2 = 0x9,
Swap3 = 0xA,
SwapN = 0x... |
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
(1..10)
.for_each(|i| {
println!("number {} from spawned thread", i);
thread::sleep(Duration::from_millis(1));
});
});
handle
.join()
.unwra... |
use std::io;
/// どのコンフィグファイルの操作がなされたか
#[derive(Debug)]
pub enum EditConfig {
Make,
Edit(Option<String>, Option<String>),
Remove,
Show,
None,
}
/// codicで発生するErrのバインディング
#[derive(Debug)]
pub enum Error {
/// io::Error
CannotOpenConfig {
error: io::Error
},
/// serde_json::Er... |
use thiserror::Error as Err;
#[derive(Err, Debug, Clone, PartialEq, Eq)]
pub enum Error {
#[error("{0}")]
Standard(String),
}
|
use crate::name::{ NamePtr, NamesPtr };
use crate::level::{ LevelPtr, LevelsPtr };
use crate::env::{ Declar::*, ReducibilityHint::* };
use crate::utils::{
IsCtx,
IsLiveCtx,
List::*,
Ptr,
ListPtr,
Store,
Env,
LiveZst,
HasNanodaDbg
};
pub type ExprPtr<'a> = Ptr<'a, Expr<'a>>;... |
pub struct Index {
index: String,
}
impl Index {
pub fn get_string(&self) -> String {
self.index.clone()
}
pub fn get_section(&self) -> u32 {
self.index
.split(".")
.next()
.unwrap()
.parse::<u32>()
.unwrap()
}
pub fn... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Error {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<ErrorCode>,
#[serde... |
use crate::env::Env;
use crate::error::Result;
use crate::objectify::Translate;
use crate::sexpr::{Sexpr, TrackedSexpr};
use crate::symbol::Symbol;
use crate::syntax::Expression;
use std::cell::Cell;
use std::rc::Rc;
#[derive(Debug, Clone)]
pub struct SyntacticClosure {
sexpr: TrackedSexpr,
closed_syntactic_en... |
use rand;
use std::num::Wrapping;
use math::*;
use super::common::fill_rect;
fn pos_from_idx(index: i32, total: i32, bounds: i32, factor: i32) -> i32 {
let rnd = rand::random::<i32>();
let pos = Wrapping(index) * Wrapping(bounds)
+ (Wrapping(total * (rnd % factor)) >> 6)
- (Wrapping(total * fa... |
// Magical Bitcoin Library
// Written in 2020 by
// Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020 Magical Bitcoin
//
// 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 ... |
use core::fmt;
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::fmt::{Debug, Formatter, LowerHex, UpperHex};
use std::hash::{Hash, Hasher};
use std::ops::{Deref, RangeBounds};
use crate::spi::UnsafeBin;
use crate::{AnyBin, Bin, IntoIter, IntoSync, IntoUnSync, IntoUnSyncView, UnSyncRef};
/// A binary that doe... |
use super::error::Error;
use super::model::*;
pub trait HaveDao {
type Stream: SocksStream;
fn stream(&self) -> &Self::Stream;
}
pub trait SocksStream {
fn recv_method_candidates(&mut self) -> Result<MethodCandidates, Error>;
fn send_method_selection(&mut self, method: MethodSelection) -> Result<(), ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.