text stringlengths 8 4.13M |
|---|
//! Caches objects in memory
mod object_ref;
pub mod store;
pub use self::object_ref::{Extra as ObjectRefExtra, ObjectRef};
use crate::watcher;
use futures::{Stream, TryStreamExt};
use kube_client::Resource;
use std::hash::Hash;
pub use store::{store, Store};
/// Cache objects from a [`watcher()`] stream into a loca... |
extern crate dotenv;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::iter::Peekable;
mod macros;
#[derive(Default, Debug)]
struct Options {
input: Option<String>,
out: Option<String>
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum MacroValue {
BOOL(bool),
STRING(String)
}
impl MacroValue {... |
use rslsk::Slsk;
#[test]
#[ignore]
fn login() {
match Slsk::connect("server.slsknet.org", 2242, "ginogino", "ginogino") {
Ok(slsk) => {
let result = slsk.login();
loop {
}
assert!(result.is_ok());
},
Err(e) => unreachable!()
}
} |
use z2p::telemetry::{get_subscriber, init_subscriber};
#[cfg(not(tarpaulin_include))]
#[async_std::main]
async fn main() -> tide::Result<()> {
init_subscriber(get_subscriber("z2p", "info"));
let configs = z2p::configuration::get_configuration().expect("Failed to read configuration");
let host = format!("{... |
// needed to use normal codegen
pub use crate as quix;
include!("./quix.net.rs");
include!("./quix.process.rs");
include!("./quix.memkv.rs");
impl<A> Into<Pid<A>> for PidProto
where A: DynHandler
{
fn into(self) -> Pid<A> {
Pid::Remote(crate::util::uuid(self.pid))
}
}
impl<A> From<Pid<A>> for PidProt... |
use std::ops::Range;
pub fn new(x:Range<i32>, y:Range<i32>) -> Vec<(i32, i32)> {
let mut xy = Vec::<(i32, i32)>::new();
for j in y.start..y.end + 1 {
for i in x.start..x.end + 1 {
xy.push((i, j));
}
}
xy
}
|
pub mod off;
|
use std::collections::HashMap;
use std::collections::HashSet;
use regex::Regex;
fn map_contains_keys(map: &HashMap<String, String>, keys: &[&str]) -> bool {
keys.iter().all(|&s| map.contains_key(s))
}
pub fn part_one(input: &str) -> String {
let required_fields = ["ecl", "eyr", "pid", "hcl", "byr", "iyr", "hg... |
use math::{Point2, BaseIntExt};
use super::{CanvasRead, CanvasWrite};
impl<T, C, N> ScanlineFill<C, N> for T
where
C: Copy + Eq,
N: BaseIntExt,
T: CanvasRead<C, N> + CanvasWrite<C, N>
{}
/// see http://will.thimbleby.net/scanline-flood-fill/
pub trait ScanlineFill<C, N>: CanvasRead<C, N> +... |
use csv::StringRecord;
use kana;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use super::constants::*;
use super::errors::ButterflyError::{self, *};
/// CSV data extracted from `butterfly.csv`
#[derive(Debug, PartialEq, PartialOrd, Clone, Serialize, Deserialize)]
pub struct CSVData {
pub di... |
#![allow(clippy::excessive_precision)]
#[macro_use]
mod support;
macro_rules! impl_quat_tests {
($t:ident, $new:ident, $mat3:ident, $mat4:ident, $quat:ident, $vec2:ident, $vec3:ident, $vec4:ident) => {
use core::$t::INFINITY;
use core::$t::NAN;
use core::$t::NEG_INFINITY;
glam_tes... |
use anyhow::Result;
use nom::{
bytes::complete::tag,
character::complete::{digit1, line_ending},
combinator::map,
multi::separated_list1,
sequence::pair,
IResult,
};
use std::{
cmp::Ordering,
collections::{HashSet, VecDeque},
fs,
str::FromStr,
};
fn parse_num<T>(input: &str) -> ... |
// use std::io::BufReader;
use rodio::{Decoder, OutputStream, Sink};
// use std::fs::File;
mod downloader;
use dirs;
mod api_type;
mod app;
#[allow(dead_code)]
mod util;
use anyhow::Result;
use crate::app::{ui, App};
use crate::util::network;
use argh::FromArgs;
use crossterm::{
event::{self, DisableMouseCapture, ... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - MCU Device ID Code Register"]
pub idcode: IDCODE,
#[doc = "0x04 - Debug MCU Configuration Register"]
pub cr: CR,
_reserved2: [u8; 0x34],
#[doc = "0x3c - APB1 Low Freeze Register CPU1"]
pub apb1fzr1: APB1FZR1,
... |
use quickcheck::quickcheck;
fn sieve(n: usize) -> Vec<usize> {
if n <= 1 {
return vec![];
}
let mut marked = vec![false; n + 1];
marked[0] = true;
marked[1] = true;
marked[2] = true;
for p in 2..n {
for i in (2 * p..n).filter(|&n| n % p == 0) {
marked[i] = true;... |
// 2019-03-12
// Jusqu'à présent, les structs contenaient des types dont ils avaient
// l'ownership. Ils peuvent aussi contenir des références, mais il faut annoter
// des lifetimes pour chaque référence.
// Définir le struct, avec la lifetime 'a
// il contient une variable 'part', une référence à une string slice
// ... |
//! OS Memory functionality and Structures
#![no_std]
#![feature(asm)]
#![feature(const_mut_refs, lang_items, alloc_error_handler)]
use bootloader::boot_info::Optional;
use core::ops::Index;
use spin::{Mutex, Once};
use virt::deallocate_pages;
use x86_64::{
registers::control::Cr3,
structures::paging::{PageTab... |
use tokio::sync::mpsc;
use crate::actor::*;
pub struct ActorJackI<I>(mpsc::Receiver<I>);
pub struct ActorJackO<O>(mpsc::Sender<O>);
pub struct ActorJack<I, O> {
input: ActorJackI<I>,
output: ActorJackO<O>,
}
#[async_trait::async_trait]
impl<I: Send> ActorI<I> for ActorJackI<I> {
async fn recv(&mut sel... |
use deno_bindgen::deno_bindgen;
// Test "primitives"
#[deno_bindgen]
fn add(a: i32, b: i32) -> i32 {
a + b
}
// Test Structs
#[deno_bindgen]
/// Doc comment for `Input` struct.
/// ...testing multiline
pub struct Input {
/// Doc comments get
/// transformed to JS doc
/// comments.
a: i32,
b: i32,
}
#[den... |
use crate::chunk::Chunk;
use crate::chunk::{CHUNK_DEPTH, CHUNK_WIDTH};
use crate::world::WorldCoordinate;
use math::vector::Vector2;
use std::collections::HashMap;
use std::convert::TryInto;
#[derive(PartialEq, Eq, Hash, Default, Copy, Clone, Debug)]
pub struct ChunkGridCoordinate {
pub x: i64,
pub z: i64,
}
... |
use parenchyma::error::Result;
use parenchyma::prelude::SharedTensor;
use super::{ConvolutionConfiguration, LrnConfiguration, PoolingConfiguration};
pub trait Forward {
/// Computes a [CNN convolution] over the input tensor `x`, and then saves the `result`.
///
/// [CNN convolution]: https://en.wikipedia.o... |
#[cfg(feature = "alloc")]
use alloc::fmt::{self, Debug, Display, Formatter};
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
#[cfg(feature = "heapless")]
use heapless::Vec as HeaplessVec;
use crate::{constants::crc_u16::*, lookup_table::LookUpTable};
#[allow(clippy::upper_case_acronyms)]
/// This struct can help you ... |
#[derive(Debug)]
struct Stack<T> {
top: Option<Box<StackNode<T>>>,
}
#[derive(Debug, Clone)]
struct StackNode<T> {
val: T,
next: Option<Box<StackNode<T>>>,
}
impl<T> StackNode<T> {
fn new(val: T) -> StackNode<T> {
StackNode {
val: val,
next: None,
}
}
}
imp... |
// This file is part of Bit.Country.
// Extension of orml vesting schedule to support multi-currencies vesting.
// Copyright (C) 2020-2021 Bit.Country.
// 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 Li... |
use std::cell::RefCell;
use std::collections::HashMap;
use std::io;
use std::rc::Rc;
use rand::Rng;
macro_rules! parse_input {
($x:expr, $t:ident) => {
$x.trim().parse::<$t>().unwrap()
};
}
type C = i32; // common type
#[derive(Debug, Clone)]
struct Locate {
x: C,
y: C,
}
impl Locate {
fn... |
use approx::ApproxEq;
use alga::general::Field;
use core::{Scalar, Matrix, SquareMatrix, OwnedSquareMatrix};
use core::dimension::Dim;
use core::storage::{Storage, StorageMut};
impl<N, D: Dim, S> SquareMatrix<N, D, S>
where N: Scalar + Field + ApproxEq,
S: Storage<N, D, D> {
/// Attempts to invert... |
use super::Transport;
use futures::prelude::*;
use futures::task::Context;
use http::Request;
use pin_project::pin_project;
use std::future::Future;
use std::pin::Pin;
use std::task::Poll;
pub struct HyperTransport<C = ::hyper::client::HttpConnector, B = ::hyper::body::Body>(
hyper::Client<C, B>,
);
impl<C, B> Hy... |
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// ht... |
const INF: usize = 1 << 61;
use std::collections::VecDeque;
use std::cmp::min;
struct Dinic {
n: usize,
edges: Vec<Vec<(usize, i64, i64)>>, // adjacent list
level: Vec<i64>,
iter: Vec<usize>
}
impl Dinic {
fn new(n: usize) -> Self {
Dinic {
n,
edges: vec![Vec::new(... |
/// const crc32 implementation by leo60288
macro_rules! reflect {
($bits:expr, $value:expr) => {{
let mut reflection = 0;
let mut value = $value;
let mut i = 0;
while i < $bits {
if (value & 0x01) == 1 {
reflection |= 1 << (($bits - 1) - i)
}... |
use bitreader::BitReader;
use bmp_header::{BMPHeader,BMPError,BMPVersion};
use byteorder::{LittleEndian,ReadBytesExt};
use std::io::{self,Read,Seek,SeekFrom};
pub struct Pixel {
pub red: u32,
pub green: u32,
pub blue: u32,
pub alpha: u32,
}
fn upscale(from: u32, bits: u8) -> u32 {
let mut to = fro... |
use super::{
CompilerData, DispError, DispResult, Function, FunctionType, LLVMCompiler, LLVMTypeCache,
NativeFunction,
};
/// the builder is responsible for building LLVM code.
/// this is a separate layer from the codegen portion as it enables
/// behavior such as:
/// * setting return types dynamically (LLVM ... |
extern crate proc_macro;
use lazy_static::lazy_static;
use oxygengine_ignite_types::*;
use proc_macro::TokenStream;
use quote::ToTokens;
use std::{
collections::HashMap,
fs::{create_dir_all, write},
path::PathBuf,
sync::{Arc, RwLock},
};
use syn::{
parse_macro_input, Attribute, Data, DeriveInput, E... |
use actix::{
fut::{err, ok},
prelude::*,
};
use backoff::{backoff::Backoff, ExponentialBackoff};
use bytes::{BufMut, Bytes, BytesMut};
use elasticsearch::{
cat::{CatIndices, CatIndicesParts},
http::{
request::JsonBody,
transport::{SingleNodeConnectionPool, TransportBuilder},
},
B... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - IWDG key register"]
pub kr: KR,
#[doc = "0x04 - IWDG prescaler register"]
pub pr: PR,
#[doc = "0x08 - IWDG reload register"]
pub rlr: RLR,
#[doc = "0x0c - IWDG status register"]
pub sr: SR,
#[doc = "0x10... |
#[doc = "Register `CSR` reader"]
pub type R = crate::R<CSR_SPEC>;
#[doc = "Field `SOF` reader - Synchronization overrun event flag"]
pub type SOF_R = crate::FieldReader<u16>;
impl R {
#[doc = "Bits 0:15 - Synchronization overrun event flag"]
#[inline(always)]
pub fn sof(&self) -> SOF_R {
SOF_R::new(... |
use std::fs::File;
use std::io::prelude::*;
fn read_file() -> Vec<u16> {
let mut file = File::open("./input/input5.txt").unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
contents.lines().map(read_as_binary).collect()
}
// to get the seat ID, rather than split in... |
use crate::lexer::{lex, Token};
use std::iter::Peekable;
use std::slice::Iter;
#[derive(Debug, PartialEq)]
pub struct Select {
pub select_list: SelectList,
pub from: From,
}
#[derive(Debug, PartialEq)]
pub struct From {
pub table: String,
}
#[derive(Debug, PartialEq)]
pub enum SelectList {
All,
S... |
use std::process::Command;
fn main() {
let mut child = Command::new("sleep").arg("5").spawn().unwrap();
let result = child.wait().unwrap();
println!("{:?}", result);// ExitStatus(ExitStatus(0))
println!("reached end of main");
} |
use super::*;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[repr(transparent)]
pub struct BackgroundControl(u16);
impl BackgroundControl {
const_new!();
bitfield_int!(u16; 0..=1: u8, priority, with_priority, set_priority);
bitfield_int!(u16; 2..=3: u8, char_base_block, with_char_base_block, set_char_ba... |
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
//the websys Canvas bindings uses it
use wasm_bindgen::JsCa... |
#![allow(bare_trait_objects)]
use exonum::{
blockchain::{ExecutionError, ExecutionResult, Transaction, TransactionContext},
crypto::{PublicKey, SecretKey},
messages::{Message, RawTransaction, Signed},
};
use super::{proto, schema::Schema, SERVICE_ID};
/// Error codes emitted by pipes transactions during ... |
use crate::errors::Errcode;
use rand::Rng;
use rand::seq::SliceRandom;
use nix::unistd::sethostname;
const HOSTNAME_NAMES: [&'static str; 8] = [
"cat", "world", "coffee", "girl",
"man", "book", "pinguin", "moon"];
const HOSTNAME_ADJ: [&'static str; 16] = [
"blue", "red", "green", "yellow",
"big", "sm... |
use super::{GreyType,GreyError,Callable};
use interpreter::Interpreter;
use std::io::{self,Read};
use std::borrow::Borrow;
use std::convert::TryFrom;
use std::boxed::Box;
macro_rules! callable_fn {
($fn:expr,$name:tt,$arity:expr) => {
#[derive(Debug,Clone)]
pub struct $name;
im... |
use shader_roy_metal_sl_interface::*;
pub fn pixel_color(coordinates: Vec2) -> Vec4 {
let Vec2 { x: cx, y: cy } = screen_to_world(coordinates);
let mut x: f32 = 0.0;
let mut y = 0.0;
let mut iteration = 0;
let max_iteration = 1000;
while (x * x + y * y) <= 4.0 && iteration < max_iteration {
let xtemp =... |
use anyhow::{Result};
use console::style;
use log::{info, trace};
use std::fs::OpenOptions;
use std::process;
use structopt::{
clap::crate_authors, clap::crate_description, clap::crate_version, clap::AppSettings, StructOpt,
};
use uvm_cli;
use uvm_cli::{options::ColorOption, set_colors_enabled, set_loglevel};
use u... |
use anyhow::{anyhow, Context, Error};
use byteorder::ByteOrder;
use byteorder::{BigEndian, WriteBytesExt};
use crypto::CryptedFileContent;
use std::io::Read;
use std::io::Write;
#[derive(Debug)]
pub struct VaultHeader {
version: u16,
keyfile_size: usize,
secret_bytes_size: usize,
}
#[derive(Debug)]
pub st... |
use crate::Result;
use anyhow::anyhow;
const CMD_PREFIX: &str = "pkger%:";
#[derive(Clone, Debug)]
pub struct Cmd {
pub cmd: String,
pub images: Vec<String>,
}
impl Cmd {
pub fn new(cmd: &str) -> Result<Self> {
if let Some(cmd) = cmd.strip_prefix(CMD_PREFIX) {
Self::parse_prefixed_com... |
// Copyright (c) 2021, Roel Schut. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
pub use bullet::*;
pub use player::*;
mod bullet;
pub mod effects;
mod player;
pub const RES_BULLET: &str = "res://player/bullet/PlayerBullet.tscn";
pub cons... |
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::path::Path;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
pub fn input(name: &str) -> io::Result<String> {
let mut s = String::new();
File::open(Path::new("input").join(name))?.read_to_string(&mut s)?;
Ok(s)
}
#[... |
//! Pull-based operator helpers, i.e. [`Iterator`] helpers.
#![allow(missing_docs)] // TODO(mingwei)
mod cross_join;
pub use cross_join::*;
mod symmetric_hash_join;
pub use symmetric_hash_join::*;
mod half_join_state;
pub use half_join_state::*;
mod anti_join;
pub use anti_join::*;
|
pub mod bool_fn;
pub mod char_fn;
pub mod dec_fn;
pub mod int_fn;
pub mod null_fn;
pub mod option_fn;
pub mod string_fn;
pub mod tuple_fn;
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
enum Encoding {
Ascii,
Utf8,
Utf16Be,
Utf16Le,
Utf32Be,
Utf32Le,
}
impl Encoding {
pub fn from_str(v... |
//! Tests auto-converted from "sass-spec/spec/libsass-closed-issues/issue_1757"
#[allow(unused)]
use super::rsass;
// From "sass-spec/spec/libsass-closed-issues/issue_1757/each.hrx"
#[test]
fn each() {
assert_eq!(
rsass(
".test .nest {\
\n length: length(&);\
\n @each ... |
// Copyright 2018 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... |
//! Special function module
pub mod function;
|
#[derive(Debug)]
pub enum Variable {
Unit { name: String },
Array { name: String, start: i64, end: i64 },
}
impl Variable {
pub fn size(&self) -> usize {
use Variable::*;
match self {
Unit { .. } => 1,
Array { start, end, .. } => (end - start + 1) as usize,
}... |
//! Numerous constants used as parameters to GC behavior
//!
//! The journal and GC parameters of these should become runtime rather than compile time.
// Journal and GC parameters
pub const JOURNAL_BUFFER_SIZE: usize = 32768;
pub const BUFFER_RUN: usize = 1024;
pub const JOURNAL_RUN: usize = 32;
pub const MAX_SLEEP_... |
// Copyright 2019 Google LLC
//
// 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 in ... |
extern crate upload_images;
#[cfg(test)]
mod dataset;
#[cfg(test)]
mod utils;
use std::env;
use rocket::http::{ContentType, Header, Status};
use rocket::local::Client;
use upload_images::rocket;
#[test]
fn test_invalid_url() {
let mut form = utils::Form::new();
form.add_text("image[]", "https://github.com/Chug... |
use osmpbfreader;
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
#[pyfunction]
fn count(pbf_filename: String) -> i64 {
let path = std::path::Path::new(&pbf_filename);
let fh = std::fs::File::open(&path).unwrap();
let mut pbf_reader = osmpbfreader::OsmPbfReader::new(fh);
let mut n_nodes: i64 = 0;
... |
use super::Block;
use super::Content as BlockContent;
use crate::config::*;
use crate::crypto::hash::{Hashable, H256};
use crate::crypto::merkle::MerkleTree;
use crate::experiment::performance_counter::PayloadSize;
/// The content of a proposer block.
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
pub struct... |
#[macro_use]
extern crate inherit;
#[derive(Nothing)]
struct AStruct {
}
#[nothing]
fn a_func() {
}
other_nothing! {
}
trait ATrait {
fn do_something(&self) -> usize;
}
#[derive(ATrait)]
struct AnotherStruct {
}
trait Node {
fn source_location(&self) -> (usize, usize);
}
#[inherit(Node)]
struct Expr ... |
use crate::stdlib::{fclose, free, FILE};
/* * dtors4plugins.h
* (C) 2018 Erik Zscheile
*/
#[no_mangle]
pub unsafe extern "C" fn _Z10do_destroyP8_IO_FILE(f: *mut FILE) -> bool {
return 0i32 == fclose(f);
}
/* fclose */
#[no_mangle]
pub unsafe extern "C" fn _Z10do_destroyPv(ptr: *mut libc::c_void) -> bool {
f... |
use crate::{IntegerMachineType, RealMachineType};
use strum_macros::EnumString;
#[derive(Debug, PartialEq)]
pub enum Token {
IntegerConstant(IntegerMachineType),
RealConstant(RealMachineType),
Plus,
Minus,
Multiply,
RealDivision,
ParenthesisStart,
ParenthesisEnd,
Eof,
Keyword(Ke... |
use ggez::{
audio::{self, Source},
conf, graphics,
graphics::Image,
timer, Context, GameResult,
};
pub struct Assets {
pub a: AudioAssets,
pub i: ImageAssets,
}
impl Assets {
pub fn new(ctx: &mut Context) -> GameResult<Self> {
Ok(Assets {
i: ImageAssets::new(ctx)?,
... |
use crate::prelude::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Position {
pub x: i32,
pub y: i32,
}
impl Position {
pub fn to_point(&self) -> Point {
Point {
x: self.x,
y: self.y,
}
}
}
impl From<Position> for Point {
fn from(position:... |
use byteorder::BE;
use tokio::io::AsyncRead;
use tokio_byteorder::AsyncReadBytesExt;
use crate::error::{parse_io, TychoResult};
use crate::Number;
use crate::read::async_::func::read_byte_async;
use crate::read::number::parse_number_ident;
use crate::types::ident::NumberIdent;
pub(crate) async fn read_number_ident_as... |
pub struct Bar {
command_mode: bool,
left_aligned: String,
right_aligned: String,
}
impl Bar {
pub fn new() -> Bar {
Bar {
command_mode: false,
left_aligned: String::new(),
right_aligned: String::new(),
}
}
fn left_text (val: String) {}
fn right_text (val: String) {}
}
|
#![allow(clippy::type_complexity)]
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;
use anyhow::Result;
use chrono::Utc;
use serde_json::Value as JsonValue;
use svc_agent::{
error::Error as AgentError,
mqtt::{
OutgoingMessage,... |
use mio::Token;
use super::super::Response;
#[derive(Debug)]
pub enum Notification {
CloseConnection(Token),
Shutdown,
Response(Token, Response),
}
impl Notification {
pub fn close_connection(token: Token) -> Notification {
Notification::CloseConnection(token)
}
pub fn shutdown() -> N... |
// The MD5 Message-Digest Algorithm
// https://tools.ietf.org/html/rfc1321
//
// https://people.csail.mit.edu/rivest/Md5.c
//
// ❗️ MD5算法在1996年后被证实存在弱点,可以被加以破解。
// ‼️ MD5算法在2004年被证实无法防止碰撞攻击,因此不适用于安全性认证。
use core::convert::TryFrom;
// Use binary integer part of the sines of integers (Radians) as constants:
// for i ... |
use pyo3::create_exception;
use pyo3::exceptions::PyException;
create_exception!(cramjam, CompressionError, PyException);
create_exception!(cramjam, DecompressionError, PyException);
|
// Problem 1
// If we list all the natural numbers below 10 that are multiples of 3 or 5,
// we get 3, 5, 6 and 9. The sum of these multiples is 23.
// Find the sum of all the multiples of 3 or 5 below 1000.
fn main() {
const MAX_VAL: u32 = 1_000;
let mut sum = 0;
for i in 0..MAX_VAL {
if div_b... |
use instant::Instant;
use std::time::Duration;
/// A timer that you can use to fix the time between actions, for example updates or draw calls.
pub struct Timer {
period: Duration,
init: Instant,
}
impl Timer {
pub fn time_per_second(times: f32) -> Timer {
Timer::with_duration(Duration::from_secs_f... |
use simple_error::bail;
use std::collections;
use std::error;
use std::io;
use std::io::BufRead;
use topological_sort;
use crate::day;
pub type BoxResult<T> = Result<T, Box<dyn error::Error>>;
pub struct Day06 {}
impl day::Day for Day06 {
fn tag(&self) -> &str { "06" }
fn part1(&self, input: &dyn Fn() -> Bo... |
use core::fmt;
use alloc::sync::Arc;
use crate::{
fs::{inode::FileLike, opened_file::OpenOptions},
net::socket::SockAddr,
result::{Errno, Result},
};
pub struct UnixSocket {}
impl UnixSocket {
pub fn new() -> Arc<UnixSocket> {
Arc::new(UnixSocket {})
}
}
impl FileLike for UnixSocket {
... |
use crate::bgp::{BgpEvent, BgpSessionType};
use crate::event::{Event, EventQueue};
use crate::external_router::ExternalRouter;
use crate::router::{RIBEntry, Router};
use crate::{
AsId, DeviceError, IgpNetwork, LinkWeight, NetworkDevice, NetworkError, Prefix, RouterId,
};
use std::collections::{HashMap, HashSet};
s... |
// Copyright 2021 The MWC Developers
//
// 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... |
use crate::interpreter::InstanceSpecification;
use crate::objectmemory::{ObjectLayout, ObjectMemory, OOP};
use byteorder::{BigEndian, ByteOrder as _, ReadBytesExt};
use std::fs::File;
use std::io::{self, prelude::*, SeekFrom};
use std::path::Path;
pub enum DistFormat {}
struct ObjTblEntry {
flags: u16,
locati... |
fn main() {
let data = "foo";
let mut s1 = data.to_string();
let s2 = "s";
let s3 = "ss";
let s5 = format!("{}{}{}", s1, s2, s3);
println!("s1 is {}", s2);
}
|
//! Tests for the `cargo login` command.
use cargo_test_support::install::cargo_home;
use cargo_test_support::registry::RegistryBuilder;
use cargo_test_support::{cargo_process, t};
use std::fs::{self};
use std::path::PathBuf;
use toml_edit::easy as toml;
const TOKEN: &str = "test-token";
const TOKEN2: &str = "test-to... |
use exonum::crypto::{Hash, PublicKey};
use super::proto;
/// Wallet information stored in the database.
#[derive(Clone, Debug, ProtobufConvert)]
#[exonum(pb = "proto::Profile", serde_pb_convert)]
pub struct Profile {
/// `PublicKey` of the profile.
pub key: PublicKey,
///public key of user
pub user_key... |
type ResultSend<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync + 'static>>;
#[derive(Debug)]
pub enum Message {
RunCheck,
Terminate,
}
#[derive(Debug)]
pub struct ServiceController {
receiver: tokio::sync::mpsc::Receiver<Message>,
}
impl ServiceController {
pub fn new(receiver: t... |
use ckb_logger::{debug, error, trace};
use ckb_stop_handler::{SignalSender, StopHandler};
use ckb_types::{
core::{service::Request, BlockView},
packed::Alert,
};
use crossbeam_channel::{bounded, select, Receiver, RecvError, Sender};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::pr... |
pub use plygui_api::callbacks;
pub use plygui_api::controls::*;
pub use plygui_api::external;
pub use plygui_api::ids::*;
pub use plygui_api::layout;
pub use plygui_api::types::{*, self};
pub use plygui_api::utils;
pub mod common;
#[cfg(all(any(target_os = "linux", target_os = "dragonfly", target_os = "free... |
// Copyright 2020 The VectorDB Authors.
//
// Code is licensed under Apache License, Version 2.0.
use crate::datums::Datum;
use crate::errors::Error;
use super::IExpression;
#[derive(Debug)]
pub struct ConstantExpression {
pub val: Datum,
}
impl ConstantExpression {
pub fn new(val: Datum) -> Self {
... |
struct Point<T, U> {
x: T,
y: U,
}
fn main(){
let a = Point{x: 100, y: -1};
println!{"x = {} y = {}", a.x, a.y};
let b = Point{x: 10.1, y: -2};
println!{"x = {} y = {}", b.x, b.y};
} |
mod cameraposition;
mod data;
mod inputcommands;
pub use cameraposition::CameraPosition;
pub use data::Data;
pub use inputcommands::InputCommands;
|
use serde::Serialize;
use common::result::Result;
use crate::application::dtos::{AuthorDto, CategoryDto, CollectionDto, PublicationDto};
use crate::domain::author::AuthorRepository;
use crate::domain::category::CategoryRepository;
use crate::domain::collection::CollectionRepository;
use crate::domain::publication::Pu... |
pub mod aggregation;
pub mod duration;
pub mod point;
pub mod series;
|
use super::{ENDPOINT, USERNAME};
use anyhow::{anyhow, Result};
use futures::StreamExt;
use protocol::stream_log_response;
use serial_test::serial;
use server::server;
use std::collections::HashMap;
#[tokio::test]
#[serial]
async fn spawn_capture_verify_stdout() {
async fn test() -> Result<()> {
tokio::spaw... |
#![feature(conservative_impl_trait)]
#![feature(rand)] extern crate rand;
extern crate regex_syntax;
extern crate itertools;
extern crate regex;
#[cfg(test)] extern crate quickcheck;
extern crate time;
extern crate clap;
// #[macro_use] extern crate chan;
// extern crate chan_signal;
#[macro_use] extern crate lazy_stat... |
use std::ops::Mul;
trait HasArea<T> {
fn area(&self) -> T;
}
struct Square<T> {
x : T,
y : T,
side : T,
}
impl<T> HasArea <T> for Square<T> where T:Mul<Output=T> + Copy {
fn area(&self) -> T {
self.side * self.side
}
}
fn main(){
let s = Square {x:1.0f64,y:1.0f64,side:1.0f64... |
#[macro_use]
extern crate arrayref;
#[macro_use]
extern crate bitflags;
extern crate blip_buf;
extern crate clap;
extern crate sdl2;
extern crate time;
mod cpu;
mod debugger;
mod gebemula;
mod graphics;
mod mem;
mod peripherals;
mod util;
use clap::{App, Arg};
use std::fs::File;
use std::io::{Read, Write};
use std::p... |
use anyhow::anyhow;
use frodobuf::render::{OutputLanguage, RenderConfig, Renderer};
use midl_parser::parse_string;
const INPUT_FILE: &str = "./system.midl";
fn main() -> Result<(), Box<dyn std::error::Error>> {
let out_dir = std::path::PathBuf::from(&std::env::var("OUT_DIR").unwrap());
let t = std::time::Sys... |
#![deny(clippy::all, clippy::pedantic)]
use std::collections::BTreeMap;
pub fn transform(h: &BTreeMap<i32, Vec<char>>) -> BTreeMap<char, i32> {
h.iter()
.flat_map(|(&score, letters)| letters.iter().map(move |c| (c.to_ascii_lowercase(), score)))
.collect::<BTreeMap<char, i32>>()
}
|
fn main() {
let f = std::env::args().skip(1).next().unwrap();
println!("{:#x?}", plist::Value::from_file(f));
}
|
//! Common data definitions for sightglass.
//!
//! These are in one place, pulled out from the rest of the crates, so that many
//! different crates can serialize and deserialize data by using the same
//! definitions.
#![deny(missing_docs, missing_debug_implementations)]
mod format;
pub use format::Format;
use ser... |
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Options {
pub random: bool,
pub auto: bool,
pub quiet: bool,
pub no_slam: bool,
pub test: bool,
pub attack: bool,
}
|
/*
* 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
*/
/// SloCorrectionUpdateData : The data object associated with the SLO correction to be updated
#[deri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.