text stringlengths 8 4.13M |
|---|
// Copyright 2020-Present (c) Raja Lehtihet & Wael El Oraiby
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions ... |
pub mod linked_list {
pub struct LinkedList {
pub val: i32,
}
}
pub fn testshit() {
let x = linked_list::LinkedList { val: 10 };
}
|
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_imports)]
#![feature(const_transmute)]
#[macro_use]
extern crate bitflags;
#[path = "util.rs"]
pub mod util_;
pub use ad_hoc_sys as sys;
pub mod org {
pub mod c... |
use async_net::{TcpListener, TcpStream};
use futures_lite::prelude::*;
use trillium_http::{Conn, Stopper};
async fn handler(mut conn: Conn<TcpStream>) -> Conn<TcpStream> {
let mut body = conn.request_body().await;
while let Some(chunk) = body.next().await {
log::info!("< {}", String::from_utf8(chunk).u... |
/*
* 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
*/
/// IntakePayloadAccepted : The payload accepted for intake.
#[derive(Clone, Debug, PartialEq, Serial... |
#[doc = "Register `SECWM2R1` reader"]
pub type R = crate::R<SECWM2R1_SPEC>;
#[doc = "Register `SECWM2R1` writer"]
pub type W = crate::W<SECWM2R1_SPEC>;
#[doc = "Field `SECWM2_PSTRT` reader - SECWM2_PSTRT"]
pub type SECWM2_PSTRT_R = crate::FieldReader;
#[doc = "Field `SECWM2_PSTRT` writer - SECWM2_PSTRT"]
pub type SECWM... |
use core::prelude::*;
use num::div_rem;
use int2dec::digits::{Digits64, Digits32, Digits16, Digits8};
use int2dec::digits::{NDIGITS64, NDIGITS32, NDIGITS16, NDIGITS8};
pub fn u64_to_digits(mut n: u64) -> Digits64 {
let mut buf: Digits64 = [b'0'; NDIGITS64];
for i in (0..NDIGITS64).rev() {
if n == 0 { ... |
// Des fonctions peuvent transférer l'ownership, le prendre, le rendre
fn main() {
// Une fonction peut donner l'ownership
let s1 = donne_ownership(); // la fonction déplace sa valeur retour dans s1.
// s1 est valide dans le scope actuel
// Créons une variable dans le sco... |
use std::collections::{BTreeMap};
use std::env;
use std::fs;
#[derive(Clone, Eq, PartialEq)]
struct ChemicalAmount {
name: String,
quantity: u32,
}
impl ChemicalAmount {
fn parse(s: &str) -> Result<ChemicalAmount, String> {
let parts: Vec<&str> = s.trim().split_whitespace().collect();
if p... |
//!
//! A micro Web framework based on Hyper, Futures and Tokio.
//!
//! ## WARNING
//! This project is not production ready.
//!
#[doc(hidden)]
pub extern crate futures;
#[doc(hidden)]
pub extern crate hyper;
extern crate regex;
extern crate tokio_core;
#[doc(hidden)]
pub extern crate typemap;
extern crate unsafe_any... |
pub mod box_demo;
pub mod deref_demo;
pub mod drop_demo;
|
use crate::utils::{fill_read_buf, make_io_error};
use bytes::BytesMut;
use futures::stream::{SplitSink, SplitStream};
use futures::{Future, SinkExt, Stream};
use std::error::Error;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_tungstenite::WebSocketStream;
use tung... |
use crate::{
lua_simple_enum::{LuaAlignment, LuaLinkType},
lua_tag::LuaTag,
};
use pulldown_cmark::{CodeBlockKind, CowStr, Tag};
#[derive(Debug, Clone, Copy)]
pub struct LuaTagModule;
impl mlua::UserData for LuaTagModule {
fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
... |
extern crate image;
extern crate time;
use std::path::Path;
use std::thread;
use vector::*;
use objects::*;
mod lighting;
pub type Image = image::RgbImage;
pub fn write_image(image: Image, filename: &str) {
let _ = image.save(&Path::new(filename));
}
pub fn raytrace(scene: &Scene, width: u32, height: u32, h_fo... |
mod cli;
mod common;
#[cfg(test)]
mod tests;
// TODO mod server;
mod client;
use crate::cli::CliArgs;
use crate::command_is_executing::CommandIsExecuting;
use crate::os_input_output::get_os_input;
use crate::utils::{
consts::{ZELLIJ_IPC_PIPE, ZELLIJ_TMP_DIR, ZELLIJ_TMP_LOG_DIR},
logging::*,
};
use client::{bou... |
#![allow(dead_code)]
extern crate chrono;
use std::mem;
use std::result::Result;
use std::convert::TryInto;
use chrono::{DateTime, Utc, NaiveDateTime};
use crate::errors::*;
#[derive(Debug, Default)]
pub struct CoffHeader {
f_machine: u16, /* machine type */
f_nscns: u16, /* number of sections */
... |
// Copyright 2017 Gerald Haesendonck
// Licensed under the Academic Free License version 3.0
//! ntriple, a library to parse N-Triples on a per string basis.
//!
//! # Examples
//!
//! Here's a typical example. It sends an input string (can be a line from a
//! file for example) to the `triple_line()` method of the `p... |
use svc_agent::AccountId;
use svc_authz::{
Authenticable, ClientMap, Config, ConfigMap, IntentObject, LocalWhitelistConfig,
LocalWhitelistRecord,
};
use crate::app::AuthzObject;
use crate::test_helpers::USR_AUDIENCE;
///////////////////////////////////////////////////////////////////////////////
#[derive(Clo... |
/* Copyright (c) 2021 Jeremy Carter <jeremy@jeremycarter.ca>
All uses of this project in part or in whole are governed
by the terms of the license contained in the file titled
"LICENSE" that's distributed along with the project, which
can be found in the top-level directory of this project.
If yo... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub mod profiles {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn ... |
extern crate sdl2;
extern crate rand;
use rand::Rng;
use std::io::{Write, stdout};
mod grid;
mod render;
mod input;
mod view;
mod file_reader;
macro_rules! enum_str {
(enum $name:ident {
$($variant:ident),*,
}) => {
enum $name {
$($variant),*
}
impl std::fmt::Disp... |
use wasm_bindgen::prelude::*;
use web_sys::console;
// When the `wee_alloc` feature is enabled, this uses `wee_alloc` as the global
// allocator.
//
// If you don't want to use `wee_alloc`, you can safely delete this.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeA... |
extern crate bsearch;
#[test]
fn find_indices() {
let mut v = vec![0; 100];
for n in 0..100 {
v[n] = n as i32;
}
for (expected_index, n) in (0..100).enumerate() {
let index = match bsearch::bsearch(&v, n) {
Some(i) => i,
None => 1,
};
assert_eq!(... |
#![allow(non_snake_case, non_upper_case_globals)]
extern crate time;
use time::precise_time_s;
///////////////////////////////////////////////////////////////////////////////
// 1. Calibration
///////////////////////////////////////////////////////////////////////////////
const aalpha:f64 = 0.33333333333; // Elastici... |
#![feature(test)]
extern crate test;
extern crate byteorder;
extern crate speedy;
use std::io::{Read, Write};
use test::{Bencher, black_box};
use byteorder::{ReadBytesExt, NativeEndian};
use speedy::{Readable, Writable, Endianness};
#[bench]
fn deserialization_manual_bytes( b: &mut Bencher ) {
let original: &[u8... |
use iced::{Application, Element, TextInput, Settings, Column, Align, text_input, Text, Length, HorizontalAlignment, Container, Command, executor, Subscription, Color, scrollable, Scrollable};
use std::fs;
use std::process;
use std::cmp::max;
use std::cmp::min;
use std::env;
pub fn main() {
// only open one finder ... |
use serde::Deserialize;
use std::{collections::BinaryHeap, convert::TryFrom, iter::FromIterator};
use necsim_core::event::PackedEvent;
mod globbed;
pub mod segment;
mod sorted_segments;
use globbed::GlobbedSortedSegments;
use segment::SortedSegment;
use sorted_segments::SortedSortedSegments;
#[allow(clippy::module_... |
use std::fs;
use intcode::Computer;
fn main() {
let input: Vec<i64> = fs::read_to_string("input")
.unwrap()
.split(',')
.map(|n| n.trim().parse().unwrap())
.collect();
let cpu = Computer::from(&input[..]);
part1(cpu.clone());
part2(cpu.clone());
}
fn part1(mut cpu: C... |
use ndarray_vision::core::*;
use ndarray_vision::format::netpbm::*;
use ndarray_vision::format::*;
use ndarray_vision::processing::*;
use std::env::current_exe;
use std::path::PathBuf;
fn canny_edges(img: &Image<f64, Gray>) -> Image<f64, Gray> {
let x = CannyBuilder::<f64>::new()
.lower_threshold(0.3)
... |
extern crate nuklear_rust;
#[macro_use]
extern crate gfx;
use nuklear_rust::{NkHandle, NkContext, NkConvertConfig, NkVec2, NkBuffer, NkDrawVertexLayoutElements, NkDrawVertexLayoutAttribute, NkDrawVertexLayoutFormat};
use gfx::{Factory, Resources, Encoder};
use gfx::texture::{Kind, AaMode};
use gfx::format::{R8_G8_B8... |
use iron::prelude::*;
use iron::status;
use iron::headers::ContentType;
use iron::modifiers::Header;
use jsonway;
use persistent::Read;
use postgres::rows::Rows;
use postgres::rows::Row;
use rustc_serialize::json;
use serde_json::value::Value as serde_Value;
use uuid::Uuid;
use iron_helpers;
use jsonapi;
#[derive(Deb... |
use crate::headers::from_headers::*;
use crate::prelude::*;
use crate::resources::Database;
use crate::ResourceQuota;
use azure_core::headers::{etag_from_headers, session_token_from_headers};
use azure_core::{collect_pinned_stream, Request as HttpRequest, Response as HttpResponse};
use chrono::{DateTime, Utc};
#[deriv... |
extern crate chrono;
use chrono::Utc;
use jsonwebtoken::{decode, encode, Header, Validation};
use rand::{Rng, thread_rng};
use rand::distributions::Alphanumeric;
use rocket::http::Status;
use crate::mongodb::db::ThreadedDatabase;
use crate::user::{get_user, get_username_with_token, User};
use crate::utils::mongo::con... |
const BIT_NOISE1: u64 = 0xB5297A4D;
const BIT_NOISE2: u64 = 0x68E31DA4;
const BIT_NOISE3: u64 = 0x1B56C4E9;
fn squirrel3(position: u64, seed: u64) -> u64 {
let mut mangled = position;
mangled = mangled.wrapping_mul(BIT_NOISE1);
mangled = mangled.wrapping_add(seed);
mangled ^= mangled >> 8;
mangled =... |
// If even x 2 , if odd x 3 +1 ---> should end with 4,2,1.
//TESTS
//collatz(5) => [5,16,8,4,2,1]
//collatz(12) => [12,6,3,10,5,16,8,4,2,1]
use std::io;
fn main() {
println!("To test the Collatz Conjeture, please, type a number:");
let mut input_01 = String::new();
io::stdin()
.read_line(&mut ... |
use futures::stream::StreamExt;
use kube::Resource;
use kube::ResourceExt;
use kube::{api::ListParams, client::Client, Api};
use kube_runtime::controller::{Context, ReconcilerAction};
use kube_runtime::Controller;
use tokio::time::Duration;
use crate::crd::Echo;
pub mod crd;
mod echo;
mod finalizer;
#[tokio::main]
a... |
extern crate chrono;
extern crate hostname;
extern crate serde;
extern crate serde_json;
extern crate uuid;
use chrono::{DateTime, FixedOffset};
use hostname::get_hostname;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;
use crate::event::SpecVersion;
use crate::event::Payload;
con... |
#[doc = "Register `MISR` reader"]
pub type R = crate::R<MISR_SPEC>;
#[doc = "Field `ALRAMF` reader - Alarm A masked flag This flag is set by hardware when the alarm A non-secure interrupt occurs."]
pub type ALRAMF_R = crate::BitReader;
#[doc = "Field `ALRBMF` reader - Alarm B non-secure masked flag This flag is set by ... |
#[doc = "RCB LL control register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modi... |
extern crate plotters;
use chrono::DateTime;
use plotters::prelude::*;
use serde::Deserialize;
use std::env;
#[derive(Debug, PartialOrd, PartialEq, Clone, Default, Deserialize)]
struct YfRow {
symb: String,
t: f32,
o: f32,
h: f32,
l: f32,
c: f32,
v: u64,
}
#[derive(Debug, PartialOrd, Partia... |
#!/usr/local/bin/rust run
/**
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
*/
extern mod extra;
use std::*;
fn main(){
let startnum = 13195;
let mut result = startnum;
let mut value = 1;
loop{
value += 1;
if value >= result{
break;
... |
use std::borrow::Borrow;
use bytes::{Buf, BufMut, BytesMut};
use dencode::{Decoder, Encoder, FramedRead, FramedWrite};
use crate::{
messages::{SBPMessage, SBP},
parser::{parse_sbp, ParseResult},
Error, Result,
};
const MAX_FRAME_LENGTH: usize =
crate::MSG_HEADER_LEN + crate::SBP_MAX_PAYLOAD_SIZE + cr... |
use mio::{Ready, Registration};
use std::{
io::{self, prelude::*},
sync::mpsc::{self, Receiver},
thread
};
pub struct MioStdin {
pub reg: Registration,
pub rx: Receiver<Vec<u8>>
}
impl MioStdin {
pub fn new() -> Self {
let (reg, control) = Registration::new2();
let (tx, rx) = mp... |
use std::collections::{HashMap, HashSet, BinaryHeap, VecDeque};
use std::collections::hash_map::Entry;
use crate::data::component::{Component, PortType, StateChange};
use crate::data::subnet::{Subnet, SubnetState};
use std::cmp::Reverse;
pub(crate) mod subnet;
pub(crate) mod component;
#[cfg(test)]
mod test;
/// St... |
use ::file::text::Point;
use std::sync::mpsc::Sender;
#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)]
pub struct FileThreadId(pub usize);
/// Messages that can be sent to the file thread to manipulate text
#[derive(Debug)]
pub enum ToFileThreadMsg {
/// Replace text between the start point and end point with t... |
extern crate url;
use self::url::percent_encoding::from_hex;
extern crate hyper;
use hyper::uri::RequestUri;
use std::collections::HashMap;
/// Percent-decode the input string
///
/// Not using url::percent_decode because it does not throw an error for malformed percent encoding
/// such as %AK
pub fn percent_decode... |
// This file is part of Basilisk-node.
// Copyright (C) 2020-2021 Intergalactic, Limited (GIB).
// 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
//
/... |
use crate::database::Database;
use crate::entities::aggregation::NewAggregationStrategy;
use crate::entities::point::{Point, QueryOptions};
use crate::entities::series::RetentionPolicy;
use bincode::serialize;
use chrono::prelude::*;
use chrono::Duration;
use rocksdb::WriteBatch;
use std::str;
use std::sync::{Arc, RwLo... |
use clap::App;
fn generate_manpage(app: &App) -> String {
let mut lines = vec![];
let version = version::version(app).unwrap();
lines.push(format!(".TH {} 1 \"{}\"", app.get_name(), version));
lines.join("\n")
}
#[cfg(test)]
mod tests {
use crate::generate_man::generate_manpage;
use clap::App... |
//! Result and errors.
use std::result;
use failure::Fail;
/// Internal results representation.
pub type Result<T> = result::Result<T, Error>;
/// Internal error representation.
#[derive(Fail, Debug)]
pub enum Error {
/// Error thrown when a Generation is initialized with one or more invalid dimension.
#[fa... |
#[derive(VulkanoShader)]
#[ty = "compute"]
#[src = "
#version 450
// TODO: 64 ?
layout(local_size_x = 32, local_size_y = 32, local_size_z = 1) in;
layout(set = 0, binding = 0) uniform usampler2D tmp_image;
layout(set = 0, binding = 1) uniform usampler2D tmp_erase_image;
/// It is important that this buffer is clear... |
// 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 {
anyhow::Error, fidl_fuchsia_images as images, fidl_fuchsia_ui_gfx as ui_gfx,
fuchsia_scenic as scenic, fuchsia_scenic,
};
/// A struct that ... |
use std::env;
use std::fs;
use regex::Regex;
fn main() {
let args: Vec<String> = env::args().collect();
let filename = &args[1];
let contents = fs::read_to_string(filename)
.expect("Something went wrong reading the file");
let split_contents = contents.lines();
let passwords: Vec<&str> = split_conte... |
#![cfg(feature = "derive")]
#![cfg(feature = "std")]
use tabled::Tabled;
// https://users.rust-lang.org/t/create-a-struct-from-macro-rules/19829
macro_rules! test_tuple {
(
$test_name:ident,
t: $(#[$struct_attr:meta])* { $( $(#[$attr:meta])* $ty:ty)* },
init: { $($init:expr)* },
ex... |
use std::{borrow::Cow, collections::HashMap, sync::Arc, time::Duration};
use bson::Document;
use serde::Deserialize;
use crate::{
bson::{doc, Bson},
coll::options::FindOptions,
error::{CommandError, Error, ErrorKind},
event::cmap::CmapEvent,
hello::LEGACY_HELLO_COMMAND_NAME,
options::{AuthMech... |
use sorbet::tap::Monitor;
use std::thread::sleep;
use std::time::Duration;
fn main() {
let mut monitor = Monitor::new().repeat(false).pressed(true);
let mut count = 1;
let _ = monitor.spawn();
'demo: loop {
println!("Loop #{}", count);
while let Some(event) = monitor.next() {
println!("Monito... |
pub mod point;
pub mod rect;
pub type Point<T> = point::Point<T>;
pub type Rect<T> = rect::Rect<T>;
pub trait One {
fn one() -> Self;
}
impl One for f32 {
fn one() -> f32 {
f32::default() + 1.0
}
}
impl One for f64 {
fn one() -> f64 {
f64::default() + 1.0
}
}
impl One for i16 {
... |
use std::error::Error;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use futures::future::SharedError;
use asset::AssetSpec;
/// Error type returned when loading an asset.
/// Includes the `AssetSpec` and the error (`LoadError`).
#[derive(Debug)]
pub struct AssetError<A, F, S> {
/// The specifi... |
#![feature(test)]
use std::usize;
extern crate console_error_panic_hook;
use wasm_bindgen::prelude::*;
extern crate web_sys;
use crate::CameFrom::Match;
use crate::CameFrom::SkipA;
use crate::CameFrom::SkipB;
extern crate test;
use test::Bencher;
#[wasm_bindgen]
#[derive(Debug)]
pub struct ScoredAlignment {
... |
use crate::api::BabylonApi;
use crate::core::*;
use crate::materials::*;
use crate::math::*;
use js_ffi::*;
pub struct Sphere {
position: Vector3<f64>,
js_ref: JSObject,
}
impl Sphere {
pub fn new(scene: &Scene, size: f64) -> Sphere {
Sphere {
position: Vector3::new(0.0, 0.0, 0.0),
... |
use std::collections::HashMap;
use ::serde::Serialize;
use rusqlite::{params, Connection};
#[derive(Clone, Debug, Serialize)]
pub struct Account {
pub guid: String,
pub parent: Option<Box<Account>>,
pub name: String
}
impl Account {
pub fn is_expense(&self) -> bool {
match self.parent {
... |
extern crate piston;
extern crate graphics;
extern crate glutin_window;
extern crate opengl_graphics;
extern crate rand;
extern crate find_folder;
use opengl_graphics::{GlGraphics, Texture};
use std::f64;
use models::vector::Vector;
use self::rand::Rng;
use game::Direction; //where is player in relation to enemy shoot... |
use crate::listnode::{ListNode, list_to_vec, arr_to_list};
pub fn reverse_between(head: Option<Box<ListNode>>, m: i32, n: i32) -> Option<Box<ListNode>> {
let m = m as usize;
let n = n as usize;
if m == n {
return head
}
let mut dummy = Box::new(ListNode { val: 0, next: head });
let mut... |
use bigint::{Address, H256, U256};
use rlp::{Encodable, RlpStream};
#[derive(Debug)]
pub struct Log {
pub address: Address,
pub data: U256,
pub topics: Vec<H256>,
}
impl Encodable for Log {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(3);
s.append(&self.address);
s.ap... |
#[cfg(test)]
pub mod problem1;
pub mod problem2;
pub mod problem3;
pub mod problem4;
pub mod tests_provided;
pub mod tests_student;
|
use rstest::rstest;
use std::net::SocketAddr;
pub mod utils;
use utils::app;
mod subscribe {
use crate::utils::App;
use super::*;
use surf::Response;
async fn do_request(address: &SocketAddr, body: &str) -> Response {
surf::post(format!("http://{}/subscriptions", address))
.he... |
use std::time::{Duration, Instant};
use crossbeam_channel::{self, Receiver, Sender};
use failure::Fallible;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Command {
Shutdown,
VolumeUp,
VolumeDown,
}
#[derive(Debug, Clone)]
pub struct Config {
pub shutdown_pin: Option<u32>,
pub volume_up_pin: Opt... |
use core::ffi::c_void;
// @Todo These may not be correct on all architectures
pub type PVOID = *mut c_void;
pub type LPVOID = *mut c_void;
pub type LPCVOID = *const c_void;
pub type HANDLE = PVOID;
pub type HMODULE = HANDLE;
pub type HICON = HANDLE;
pub type HCURSOR = HANDLE;
pub type HBRUSH = HANDLE;
pub type HINSTA... |
use bevy::app::AppExit;
use bevy::{prelude::*, tasks::IoTaskPool};
use rand::prelude::random;
use crossbeam_channel::{unbounded, Receiver, Sender};
use std::net::{TcpListener, IpAddr, Ipv4Addr, SocketAddr};
use std::thread::spawn;
use tungstenite::{
accept_hdr,
handshake::server::{Request, Response},
protoc... |
use super::{internal::Io, AsyncRead, AsyncWrite, PeerAddr, Poll};
use bytes::{Buf, BufMut};
use std::{mem::MaybeUninit, pin::Pin, task::Context};
/// A public wrapper around a `Box<Io>`.
///
/// This type ensures that the proper write_buf method is called,
/// to allow vectored writes to occur.
pub struct BoxedIo(Pin<... |
use clap::{App, ArgMatches, SubCommand};
use webbrowser;
use database::DB;
pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {
SubCommand::with_name("open")
.about("Open bookmark")
.arg_from_usage("<ID>... 'Open bookmark matching the specified ids'")
}
pub fn execute(args: &ArgMatches) {
let db... |
// MIT License
// Copyright (c) 2018-2021 The orion Developers
// 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, cop... |
use std::env;
fn main() {
//initialize what to an Option<String>
let what = env::args().next();
//Check if what is empty or not and do something
match what {
Some(string) => println!("Hello, {}", string),
None => panic!("Nothing to print passed!")
}
}
|
pub mod damerau_levenshtein;
pub mod jaro;
pub mod jaro_winkler;
pub mod levenshtein;
pub mod sorensen_dice;
mod utils;
|
#![feature(non_ascii_idents)]
extern crate crossbeam;
extern crate music_tools;
extern crate portaudio;
extern crate rand;
extern crate console;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
use console::Term;
use std::thread;
use std::collections::{HashSet};
use std::f64::const... |
// 引用类库用于监听读取,
use std::{io::{Read, Write}, net::{TcpListener, TcpStream}};
// 引用类库用于多线程处理
use std::thread;
// 引用类库用于类型转换。
use std::str;
// 程序主函数
fn main() {
// 定义一个请求地址和IP:端口
let addr = "127.0.0.1:8866".to_string();
// 创建一个Tcp监听,通过字符串切片将addr传入
let listener = TcpListener::bind(&addr).unwrap();
// ... |
#[derive(PartialEq)]
#[derive(Debug)]
pub enum Cell {
Dead,
Alive
}
pub struct Cells {
pub width: usize,
pub height: usize,
cells: Vec<Vec<Cell>>
}
impl Cells {
pub fn new(width: usize, height: usize) -> Cells {
let mut cells = vec![];
for _ in 0..height {
let mut r... |
use cursive::{views::*, view::*};
use super::State;
use super::task;
use crate::model::*;
pub fn column(state: State, project: &Project, column: &Column) -> impl View {
let column_view = column.tasks().iter()
.filter_map(|task_id| project.task_with_id(task_id))
.map(|t| task::card(state.clone(), t)... |
#[macro_use] extern crate lalrpop_util;
lalrpop_mod!(pub parser);
fn main()
{
println!("Hello, world!");
let parser = parser::TermParser::new();
println!("{}", parser.parse("(((((15)))))").unwrap());
}
|
// Reference Pointers - Point to a resource in memory
pub fn run() {
//Primitive Array
let arr1=[1,2,3];
let arr2=arr1;
//With non-primitives,if you assign another variable to a piece of data, the first variable will no onger hold that value. You 'll need to use a reference (&) to point to the resourc... |
// A port of the simplistic benchmark from
//
// http://github.com/PaulKeeble/ScalaVErlangAgents
//
// I *think* it's the same, more or less.
use std;
import std::io::writer;
import std::io::writer_util;
enum request {
get_count,
bytes(uint),
stop
}
fn server(requests: comm::port<request>, responses: ... |
#[doc = "Register `SWIER2` reader"]
pub type R = crate::R<SWIER2_SPEC>;
#[doc = "Register `SWIER2` writer"]
pub type W = crate::W<SWIER2_SPEC>;
#[doc = "Field `SWIER49` reader - Software interrupt on line x+32"]
pub type SWIER49_R = crate::BitReader<SWIER49W_A>;
#[doc = "Software interrupt on line x+32\n\nValue on rese... |
extern crate minifb;
extern crate clap;
use clap::{Arg, App};
use minifb::{WindowOptions, Window, Key};
use std::io::Read;
use std::time::Instant;
struct Registers {
a: u8,
b: u8,
c: u8,
d: u8,
e: u8,
f: FlagsRegister,
h: u8,
l: u8,
}
impl Registers {
fn new() -> Registers {
... |
use std::fs::File;
use std::io::{BufRead, BufReader};
fn parse_input(file_name: &str) -> Vec<String> {
let br = BufReader::new(File::open(file_name).unwrap());
let mut v: Vec<String> = Vec::new();
for line in br.lines() {
let current = match line {
Ok(val) => val.clone(),
Er... |
//!
//! cd C:\Users\むずでょ\OneDrive\ドキュメント\practice-rust\kirimoti\max
//! cargo check --example main-3
//! cargo run --example main-3
//!
//! [crates.io](https://crates.io/)
//!
fn main() {
let table = vec![
vec![-1, 3, -2, 10]
,vec![16, -15, 9, -7]
,vec![8, -11, 4, 5]
,vec![-6, 9, ... |
pub fn run() {
greeting("Hello", "Haardik");
// Function values to vars
let sum = add(5, 5);
println!("Sum: {}", sum);
let dif = sub(10, 5);
println!("Diff: {}", dif);
// Closures (pipes)
let add_nums = |n1: i32, n2: i32| n1 + n2;
println!("Closure Sum: {}", add_nums(3, 4));
... |
use rand::Rng;
#[derive(Debug, Copy, Clone, PartialEq, Default)]
pub struct Vec2 {
pub x: f32,
pub y: f32,
}
impl Vec2 {
#[allow(dead_code)]
pub fn randomize(origin: Vec2, spread: f32) -> Vec2 {
let mut x = origin.x;
let mut y = origin.y;
x += rand::thread_rng().gen_range(-spre... |
#![feature(option_result_contains)]
pub mod config;
pub mod services;
pub mod constants;
pub mod api;
pub mod queries;
pub mod websocket;
|
use image::EncodableLayout;
use pix_engine::prelude::*;
use rand::distributions::{Distribution, Uniform};
use rand::rngs::ThreadRng;
use std::time::Instant;
use structopt::StructOpt;
#[derive(StructOpt)]
struct ProgArgs {
// #[structopt(short, long, default_value = "800")]
// width: u32,
// #[structopt(sh... |
use std::os::raw::{c_int, c_uchar, c_uint};
use libc::uint16_t;
pub use rte_sys::*;
/// Error number value, stored per-thread, which can be queried after
/// calls to certain functions to determine why those functions failed.
pub fn rte_errno() -> i32 {
unsafe { rte_sys::_rte_errno() }
}
|
use std::{env, path::Path};
use crate::{
git_actions::GitActions, hg_actions::HgActions,
version_control_actions::VersionControlActions,
};
pub fn get_current_version_control() -> Option<Box<dyn VersionControlActions>> {
let mut args = env::args();
if let Some(dir) = args.nth(1) {
let dir = Pa... |
use crate::*;
cfg_mysql_support!(
pub(crate) mod mysql;
pub(crate) use mysql::establish_connection;
embed_migrations!("./migrations/mysql");
);
cfg_postgres_support!(
pub(crate) mod postgres;
pub(crate) use postgres::establish_connection;
embed_migrations!("./migrations/postgres");
);
pub ... |
#![warn(rust_2018_idioms)]
#[macro_use]
extern crate glium;
#[macro_use]
extern crate slog;
#[macro_use(define_roles)]
extern crate smithay;
use slog::Drain;
use smithay::reexports::{calloop::EventLoop, wayland_server::Display};
#[macro_use]
mod shaders;
mod glium_drawer;
mod input_handler;
mod shell;
mod shm_load;
... |
//! ```cargo
//! [dependencies]
//! toml = "0.5"
//! serde = { version = "1.0", features = ["derive"] }
//! ```
// Copyright Jeron Aldaron Lau 2017 - 2020.
// Distributed under either the Apache License, Version 2.0
// (See accompanying file LICENSE_APACHE_2_0.txt or copy at
// https://apache.org/licenses/... |
mod client;
mod config;
mod miner;
mod worker;
use byteorder::{ByteOrder, LittleEndian};
pub use crate::client::Client;
pub use crate::config::MinerConfig;
pub use crate::miner::Miner;
use ckb_core::block::{Block, BlockBuilder};
use ckb_jsonrpc_types::BlockTemplate;
use std::convert::From;
use ckb_core::difficulty::d... |
use super::super::entity::CategoryResult;
use super::super::entity::Category;
use log::{trace};
const TOLERANCE: f64 = 0.00000000001;
struct Combinatorial {
total: u32, // n
current: Vec<u32>, // has size m
current_n: u32,
}
// iterate through all possible combinations where sum of vector entries = tota... |
use crate::{Context, Error};
use reqwest::header;
use serde::Deserialize;
const USER_AGENT: &str = "kangalioo/rustbot";
#[derive(Debug, Deserialize)]
struct Crates {
crates: Vec<Crate>,
}
#[derive(Debug, Deserialize)]
struct Crate {
id: String,
name: String,
newest_version: String,
updated_at: St... |
use crate::query::refs::*;
use crate::query::*;
#[derive(Debug)]
pub struct MinifiedFormatter {
buf: String,
}
impl Default for MinifiedFormatter {
fn default() -> Self {
Self {
buf: String::with_capacity(1024),
}
}
}
pub trait MinifiedString {
/// writes the minified stri... |
use ::*;
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum MouseEventType {
Click,
MouseDown,
MouseUp,
DblClick,
MouseMove,
MouseEnter,
MouseLeave,
}
impl MouseEventType {
fn from(event: EM_EVENT_TYPE) -> MouseEventType {
match event {
EMSCRIPTEN_EVENT_CLI... |
#![cfg_attr(feature = "unstable-testing", feature(plugin))]
#![cfg_attr(feature = "unstable-testing", plugin(clippy))]
extern crate k5test;
extern crate gssapi;
extern crate gssapi_sys;
fn create_k5realm() -> k5test::K5Realm {
let realm = "KRBTEST.COM".to_owned();
k5test::K5RealmBuilder::new(realm.clone())
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.