text stringlengths 8 4.13M |
|---|
#[macro_use]
extern crate hyper;
extern crate hyper_tls;
extern crate clap;
extern crate futures;
extern crate tokio_core;
use std::fmt::Display;
use clap::{App, Arg};
use futures::{Future};
use hyper_tls::HttpsConnector;
use hyper::Client;
use hyper::header::{Header, Headers};
use hyper::header::StrictTransportSecuri... |
// Copyright (c) 2020 ESRLabs
//
// 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 agre... |
use serde::{Deserialize, Serialize, Serializer};
use std::collections::HashMap;
use std::error::Error;
use std::io;
pub struct TransactionProcessor {
/// Keep track of all client accounts and associated values
accounts: HashMap<u16, ClientAccount>,
/// Keep basic info on deposit and withdrawal transactions... |
pub fn brackets_are_balanced(string: &str) -> bool {
let delimiters = "()[]{}";
let mut stack = Vec::new();
for char in string.chars() {
match delimiters.find(char) {
None => (),
Some(index) => match index % 2 {
0 => stack.push(index + 1),
_ =... |
use super::prelude::*;
use super::rest_client::{AZURE_VERSION, HEADER_DATE, HEADER_VERSION};
use crate::PerformRequestResponse;
use azure_core::errors::AzureError;
use azure_core::util::{format_header_value, RequestBuilderExt};
use http::request::Builder;
use hyper::{header, Method};
use hyper_rustls::HttpsConnector;
u... |
use ast::abstract_syntax_tree::Ast;
use lang_result::LangError;
use s_expression::SExpression;
use std::collections::HashMap;
/// Shorthand for a HashMap that maps Strings to Mutability enums
pub type MutabilityMap = HashMap<String, Mutability>;
// The Void indicates that check was successful without any errors, the ... |
#[doc = "Register `MPCBB1_VCTR32` reader"]
pub type R = crate::R<MPCBB1_VCTR32_SPEC>;
#[doc = "Register `MPCBB1_VCTR32` writer"]
pub type W = crate::W<MPCBB1_VCTR32_SPEC>;
#[doc = "Field `B1024` reader - B1024"]
pub type B1024_R = crate::BitReader;
#[doc = "Field `B1024` writer - B1024"]
pub type B1024_W<'a, REG, const... |
use crate::prelude::*;
use crate::resources::ResourceType;
use crate::responses::ListPermissionsResponse;
use azure_core::prelude::*;
use futures::stream::{unfold, Stream};
use http::StatusCode;
use std::convert::TryInto;
#[derive(Debug, Clone)]
pub struct ListPermissionsBuilder<'a, 'b> {
user_client: &'a UserClie... |
mod gates;
mod wire;
pub use self::wire::wiring;
pub use self::gates::NANDGate;
pub use self::gates::NOTGate;
pub use self::gates::ANDGate;
pub use self::gates::ORGate;
pub use self::gates::XORGate;
pub use self::gates::NORGate;
mod components {}
|
use super::*;
pub trait SDLConsuming: Clone {
const JOYPAD: bool;
const CONTROLLER: bool;
const GESTURE: bool;
const FINGER: bool;
const APP: bool;
const WINDOW: bool;
const KEYBOARD: bool;
const TEXT_OP: bool;
const MOUSE: bool;
const WHEEL: bool;
const CLIPBOARD_UPDATE: bo... |
use crate::prelude::*;
use derive_new::new;
use getset::Getters;
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(
Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Getters, Serialize, Deserialize, new,
)]
#[get = "pub(crate)"]
pub struct ExternalCommand {
name: Tag,
}
impl ToDebug for ExternalCo... |
use crate::{candidate_type::CandidateType, ice_candidate::IceCandidate};
use regex::Regex;
pub struct Sdp {
pub ufrag: String,
pub pwd: String,
}
impl Default for Sdp {
fn default() -> Self {
Sdp {
ufrag: "".into(),
pwd: "".into(),
}
}
}
impl From<&str> for Sdp... |
use core::{fmt, iter::*, marker::PhantomData, mem, ptr};
use std::os::windows::ffi::OsStringExt;
use std::{ffi::*, io};
use winapi::{
shared::{guiddef::GUID, minwindef::*, windef::HWND, winerror::*},
um::{errhandlingapi::*, handleapi::*, heapapi::*, setupapi::*, winnt::*},
};
pub use winapi::um::setupapi::HDEV... |
// CPU affinity using the `core_affinity` crate.
#[cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]
mod affinity_core_affinity;
#[cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]
pub use affinity_core_affinity::bind_to_single_core;
// CPU affinity using the `hwloc`... |
use std::error::Error as StdError;
use std::fmt;
use std::time::SystemTimeError;
/// Represents an Error that occurred while interacting with the Last.fm API
///
/// `ScrobblerError` contains an error message, which is set when an error occurs and exposed via Trait standard error
/// Trait implementations.
///
/// ... |
//! This crate implements code for computing a tree-child sequence of a collection of trees.
pub mod clusters;
pub mod network;
pub mod newick;
pub mod tree;
pub mod tree_child_sequence;
|
/// My fizzbuzz for rust cause...
use std::env::args;
use std::fmt::{Display, Error, Formatter};
use std::ops::Add;
struct FizzBuzz(i32);
impl FizzBuzz {
fn new(n: i32) -> FizzBuzz {
FizzBuzz(n)
}
}
impl Display for FizzBuzz {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match ... |
struct Solution();
// impl Solution {
// pub fn find_kth_largest(nums: Vec<i32>, k: i32) -> i32 {
// let mut nums=nums;
// nums.sort();
// nums[nums.len()-k as usize]
// }
// }
use std::collections::BinaryHeap ;
impl Solution {
pub fn find_kth_largest(nums: Vec<i32>, k: i32) -> i32 {... |
use crate::components::PathCacheComponent;
use crate::indices::EntityId;
use serde::{Deserialize, Serialize};
/// Update the path cache
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CachePathIntent {
pub bot: EntityId,
pub cache: PathCacheComponent,
}
/// Remove the top item from the pat... |
use syn::{Expr, ExprUnary, ExprBinary, UnOp, BinOp, ExprParen};
use syn::spanned::Spanned;
use proc_macro2::Span;
// Negate an expression.
pub fn negate(expr: &Expr) -> Expr {
match expr {
Expr::Unary(ExprUnary { op: UnOp::Neg(_), expr, .. }) => {
*expr.clone()
}
_ => ExprUnary ... |
use futures::Future;
use warp::{path, Filter};
use reqwest;
mod score;
use score::{ScoreRepo, ScoreView};
fn main() {
env_logger::init();
let help = path::end()
.and_then(|| {
let config = match ScoreRepo::new() {
Some(c) => c,
None => panic!("Error"),
... |
use actix_web::http::HeaderValue;
use url::Url;
mod support;
#[actix_rt::test]
async fn health_check_works() {
// Arrange
let address = support::spawn_app(Url::parse("http://example.com/").unwrap());
// Act
let response = support::client()
.get(&format!("{}/health_check", &address))
.... |
use github_v3::IssueCommenter;
use github_v3::types::repos::Repository;
use github_v3::types::comments::CreateIssueComment;
use types::SimplifiedIssueCommentEvent;
use rand::{thread_rng, sample};
use itertools::Itertools;
pub struct ReviewTagger {
reviewers: Vec<String>
}
impl ReviewTagger {
pub fn new(reviewe... |
#![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 SchemaId {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Cl... |
#[doc = "Reader of register INIT_WINDOW_NI_ANCHOR_PT"]
pub type R = crate::R<u32, super::INIT_WINDOW_NI_ANCHOR_PT>;
#[doc = "Reader of field `INIT_INT_OFF_CAPT`"]
pub type INIT_INT_OFF_CAPT_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:15 - Initiator interval offset captured at conn request. The value indicates ... |
use std::ffi::OsStr;
use anyhow::{bail, format_err, Context as _, Result};
use camino::{Utf8Path, Utf8PathBuf};
use cargo_config2::Config;
use crate::{
cli::{ManifestOptions, Subcommand},
context::Context,
env,
process::ProcessBuilder,
};
pub(crate) struct Workspace {
pub(crate) name: String,
... |
use advent_of_code_2019::intcode_computer;
use std::fs;
fn main() {
let mut input = fs::read_to_string("resources/day2.input").unwrap();
input.pop();
let instructions = input
.split(",")
.map(|s| s.parse::<i32>().unwrap())
.collect::<Vec<i32>>();
const PROGRAM_OUTPUT: i32 = 196... |
use criterion::{criterion_group, criterion_main};
mod page_bench;
mod sm_bench;
criterion_group!(benches, page_bench::page_benchmark, sm_bench::sm_ins_bench);
criterion_main!(benches);
|
use crate::gui::make_dropdown_list_option;
use crate::sidebar::make_section;
use crate::{
gui::{BuildContext, Ui, UiMessage, UiNode},
physics::{Collider, Joint, RigidBody},
scene::commands::CommandGroup,
scene::{
commands::{
physics::{
AddJointCommand, DeleteBodyComma... |
use std::path::PathBuf;
use common::computer::{read_program_file, computer};
use std::collections::VecDeque;
pub fn part_1() -> i64 {
let path = PathBuf::from("./assets/boost.txt");
let memory = read_program_file(path).unwrap();
let (_, buffer) = computer(memory, Some(VecDeque::from(vec![1])));
buffer.... |
//! The `Document` struct represents an entire org file.
use super::*;
/// A complete org document/file.
///
/// Contains the global document properties and section before the first headline as well as the
/// list of all top level headlines.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct Document {... |
#![allow(unused_imports)]
pub mod glr_lex;
pub mod glr_grammar;
pub mod glr;
|
pub enum NetworkId {
// Germany
VVO,
}
|
use crate::errors::*;
use crate::types::*;
use uuid::Uuid;
/// Contains part of the list of user photos
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UserProfilePhotos {
#[doc(hidden)]
#[serde(rename(serialize = "@type", deserialize = "@type"))]
td_name: String,
#[doc(hidden)]
... |
extern crate petgraph;
extern crate onig;
use petgraph::graph::NodeIndex;
use onig::*;
use std::collections::HashMap;
use petgraph::Graph;
use petgraph::dot::{Dot, Config};
pub fn convert_horizontal_patterns_to_graph(graph: &mut Graph::<(usize, usize), u32, petgraph::Undirected>,
lines: &[&str],
delimiter: ch... |
fn main() {
println!("{}", farenheit_to_celcius(68.00));
println!("{}", fibonaaci(5))
}
fn farenheit_to_celcius(temprature: f64) -> f64 {
(temprature - 32.0) * 5.0/9.0
}
fn fibonaaci(n: i64) -> i64 {
if n == 0 {
return 0;
} else if n == 1 {
return 1;
} else {
return fi... |
use super::super::*;
use math::*;
use glium;
use glium::{
glutin::{
event_loop::{
EventLoop,
ControlFlow,
},
event::{
Event,
StartCause,
WindowEvent,
ElementState,
},
window::WindowBuilder,
Conte... |
use std::collections::HashSet;
use std::env;
use std::path::PathBuf;
// https://github.com/rust-lang/rust-bindgen/issues/687#issuecomment-450750547
#[derive(Debug)]
struct IgnoreMacros(HashSet<String>);
impl bindgen::callbacks::ParseCallbacks for IgnoreMacros {
fn will_parse_macro(&self, name: &str) -> bindgen::c... |
use crate::pong::{ARENA_HEIGHT, ARENA_WIDTH};
use amethyst::{
assets::Handle,
core::transform::Transform,
ecs::{Component, DenseVecStorage, Entity},
prelude::*,
renderer::{SpriteRender, SpriteSheet},
};
pub const BALL_VELOCITY_X: f32 = 75.0 * 2.;
pub const BALL_VELOCITY_Y: f32 = 50.0 * 2.;
pub cons... |
use bson;
use ron;
use serde::{Deserialize, Serialize};
use serde_json;
use std::io::{Read, Result, Seek, SeekFrom, Write};
fn main() {
json_with_file();
ron_with_buffer();
let f = std::fs::OpenOptions::new()
.create(true)
.read(true)
.write(true)
.open("/tmp/b.bson")
... |
fn main() {
let (m, n, first_n) = {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let mut ws = line.trim_end().split_whitespace();
let n1: usize = ws.next().unwrap().parse().unwrap();
let n2: usize = ws.next().unwrap().parse().unwrap();
... |
#[cfg(test)]
#[path = "../../../tests/unit/solver/objectives/total_value_test.rs"]
mod total_value_test;
use crate::construction::constraints::*;
use crate::construction::heuristics::{RouteContext, SolutionContext};
use crate::models::problem::{Job, TargetConstraint, TargetObjective};
use crate::solver::objectives::Ge... |
use std::{collections::BTreeMap, iter::Extend, sync::Arc};
use rosu_v2::model::user::User;
use twilight_model::channel::Message;
use crate::{
custom_client::{OsuStatsParams, OsuStatsScore},
embeds::OsuStatsGlobalsEmbed,
BotResult, Context,
};
use super::{Pages, Pagination, ReactionVec};
pub struct Osu... |
/*
* 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
*/
use reqwest;
use crate::apis::ResponseContent;
use super::{Error, configuration};
/// struct for typ... |
use plotters::prelude::*;
fn main() {
// 画像サイズが600 x 400の画像を`./images/`配下に作成
let root_area = BitMapBackend::new("images/2.5.png", (600, 400)).into_drawing_area();
// 背景を白に設定
root_area.fill(&WHITE).unwrap();
let mut ctx = ChartBuilder::on(&root_area)
// グラフのラベルを設定
... |
use std::fmt;
use std::rc::Rc;
#[allow(dead_code)]
pub enum LTL<A> {
Top,
Bottom(String),
// Accept rules take a state which is global to the aggregate LTL<A> formula.
// There is no way to "scope" information using closures, such as there is
// in Coq or Haskell, so intermediate states must be re... |
use std::collections::HashMap;
fn main() {
let input = include_str!("../data/2015-07.txt");
println!("Part 1: {}", part1(input));
println!("Part 2: {}", part2(input));
}
fn part1(input: &str) -> u16 {
let mut wires = parse(input);
calc(&mut wires, "a")
}
fn part2(input: &str) -> u16 {
let mut... |
//! A one-time send - receive channel.
use std::cell::UnsafeCell;
use std::future::Future;
use std::marker::PhantomData;
use std::rc::Rc;
use std::task::{Poll, Waker};
use thiserror::Error;
/// Error returned by awaiting the [`Receiver`].
#[derive(Debug, Error)]
#[error("channel has been closed.")]
pub struct RecvEr... |
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Config {
#[serde(default)]
pub option: ConfigOption,
#[serde(default)]
pub verilog: ConfigVerilog,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ConfigOption {
#[s... |
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer};
use std::fmt;
use std::str::FromStr;
use uuid::Uuid;
use chrono::{Utc};
struct F64InQuotes;
impl<'de> Visitor<'de> for F64InQuotes {
type Value = f64;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("f64 ... |
use crate::renderer::render;
use image::codecs::tiff::TiffEncoder;
use std::fs::File;
use std::io::BufReader;
pub mod primitive;
pub mod renderer;
pub mod scene;
fn main() {
// Rendering images
std::fs::create_dir("rendered");
let file = File::open("./assets/cornell2.ron").unwrap();
let buf_reader = ... |
#[doc = "Register `HASH_MID` reader"]
pub type R = crate::R<HASH_MID_SPEC>;
#[doc = "Field `MID` reader - MID"]
pub type MID_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - MID"]
#[inline(always)]
pub fn mid(&self) -> MID_R {
MID_R::new(self.bits)
}
}
#[doc = "HASH Hardware Magic ID\n... |
use chess::{Board, Color, Square, Piece, Rank, File};
use std::fmt::Write;
const EMPTY_SQUARE: &str = " _ ";
const BLACK_MARKER: &str = "*";
const BOARD_HEADER: &str = " A B C D E F G H ";
pub fn board_to_string(board: &Board, perspective: Color) -> String {
let (iter_order, actual_header) = if persp... |
#[doc = "Register `CFR` writer"]
pub type W = crate::W<CFR_SPEC>;
#[doc = "Field `CSOF0` writer - Clear synchronization overrun event flag"]
pub type CSOF0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSOF1` writer - Clear synchronization overrun event flag"]
pub type CSOF1_W<'a, REG, const O... |
use super::*;
/// A babel call element.
///
/// # Sematics
///
/// Used to execute [`SrcBlock`]s and put their results into the org file.
///
/// # Syntax
///
/// ```text
/// #+CALL: FUNCTION[INSIDE-HEADER](ARGUMENTS) END-HEADER
/// ```
///
/// `FUNCTION` is the name of a [`SrcBlock`] to execute. `INSIDE-HEADER`, `ARG... |
extern crate termion;
use termion::input::TermRead;
use termion::event::Key;
use termion::raw::IntoRawMode;
use termion::screen::ToMainScreen;
use std::{io::{Write, stdout, stdin},
sync::mpsc,
thread
};
use termion::screen::AlternateScreen;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
#... |
pub fn is_literal_bash_string(command: &[u8]) -> bool {
let mut previous = None;
for &c in command {
if b"\t\n !\"$&'()*,;<>?[\\]^`{|}".contains(&c) {
return false;
}
if previous.is_none() && b"#-~".contains(&c) {
// Special case: `-` isn't a part of bash syntax, ... |
/// x86 page directory
///
/// for details:
/// Intel@ 64 and IA-32 Architectures Software Developer's Manual,
/// Vol.3: System Programming Guide - 4.3 (32-bit Paging)
pub mod pg_dir {
use alloc::boxed::Box;
use utils::address::{PAddr, VAddr};
/// # directory entries per page directory
pub con... |
use std::fmt;
use std::hash::Hash;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct BlockId {
filename: String,
blknum: u64,
}
impl BlockId {
pub fn new(filename: impl Into<String>, blknum: u64) -> BlockId {
BlockId {
filename: filename.into(),
blknum,
}
... |
use chrono::Duration;
use once_cell::sync::Lazy;
use prometheus::{
register_histogram, register_int_counter_vec, Histogram, HistogramTimer, IntCounter,
};
use prometheus_static_metric::make_static_metric;
use super::error::Error;
make_static_metric! {
struct MqttStats: IntCounter {
"method" => {
... |
extern crate regex;
use regex::Regex;
use std::collections::HashMap;
use std::u32;
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
const LINEBREAK: &'static str = include_str!("unicode-data/LineBreak-11.0.0.txt");
const UNICODEDATA: &'static str = include_str!("unicode-data/UnicodeData.txt")... |
use crate::normal::Normal;
use crate::points::HasPoints;
use crate::suit::Suit;
use crate::suit_value::SuitValue;
use crate::traits::{Discardable, Power, Representation};
use crate::trump::Trump;
use colored::ColoredString;
use ordered_float::OrderedFloat;
use std::fmt;
#[derive(Copy, Ord, Clone, Debug, Eq, PartialEq,... |
use std::mem;
use std::ptr;
use messages::Message;
use libc::{c_char, size_t};
use assets::TradeAsset;
use capi::common::*;
use transactions::ask_offer::AskOfferWrapper;
use error::{Error, ErrorKind};
ffi_fn! {
fn dmbc_tx_ask_offer_create(
public_key: *const c_char,
asset: *mut TradeAsset,
... |
use std::collections::HashSet;
pub fn part1(input: &HashSet<i64>) -> Option<i64> {
for num in input.iter() {
let find = 2020 - num;
if input.contains(&find) {
return Some(num * find);
}
}
None
}
pub fn part2(input: &HashSet<i64>) -> Option<i64> {
for (a_index, a) ... |
use crate::features::syntax::StatementFeature;
use crate::parse::visitor::tests::assert_no_stmt_feature;
use crate::parse::visitor::tests::assert_stmt_feature;
#[test]
fn continue_no_label() {
assert_stmt_feature(
"while (cond) {
continue;
}",
StatementFeature::ContinueStatement... |
// Copyright (c) 2017 oic 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 copied,
// mo... |
use crate::memory::Memory;
pub fn update_dma(mem: &mut Memory) {
if mem.read(0xff46) != 0 {
//println!("/!\\ DMA HAS OCCURRED");
let source: u16 = (mem.read(0xff46) as u16) << 8;
let dest: u16 = 0xFE00;
for i in 0..0xA0 {
mem.write(dest + i, mem.read(source + i));
... |
pub mod oauth2;
pub mod client;
pub mod util;
pub mod senum;
pub mod model;
|
/// # RESP2
/// This module provides utilities to parse the RESP2 protocol.
use nom::branch::alt;
use nom::multi::many_m_n;
use nom::{bytes::streaming::tag, IResult};
use crate::utils::{parse_bytes_with_length, parse_integer_with_prefix, parse_str_with_prefix};
/// Resp2Type represents all possible response types fro... |
// Copyright (C) 2021 Subspace Labs, Inc.
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option)... |
#[doc = "Register `CFGR` reader"]
pub type R = crate::R<CFGR_SPEC>;
#[doc = "Register `CFGR` writer"]
pub type W = crate::W<CFGR_SPEC>;
#[doc = "Field `SW` reader - System clock Switch"]
pub type SW_R = crate::FieldReader<SW_A>;
#[doc = "System clock Switch\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq,... |
use super::prelude::*;
#[derive(Debug, Clone, PartialEq)]
pub struct PrefixExpr {
pub ope: Operator,
pub right: Box<Expr>,
}
impl Display for PrefixExpr {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "({}{})", self.ope, self.right.as_ref())
}
}
impl TryFrom<Expr> for Prefix... |
use byteorder::{LittleEndian, ByteOrder};
use scroll_derive::Pread;
#[derive(Debug, Pread)]
pub(crate) struct ArcHeader {
pub music_file_section_offset: u64,
pub file_section_offset: u64,
pub music_section_offset: u64,
pub node_section_offset: u64,
pub unk_section_offset: u64,
}
pub(crate) const AR... |
#[macro_export]
macro_rules! leak {
($name:expr) => {
Box::into_raw(Box::new($name)) as *mut c_void
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Control"]
pub ctl: CTL,
_reserved1: [u8; 12usize],
#[doc = "0x10 - Clock control"]
pub clock_ctl: CLOCK_CTL,
#[doc = "0x14 - Mode control"]
pub mode_ctl: MODE_CTL,
#[doc = "0x18 - Data control"]
pub data... |
pub struct Delay {
buffer: Vec<f64>,
index: usize,
}
impl Delay {
pub fn new(length: usize) -> Delay {
Delay {
buffer: vec![0.; length],
index: 0,
}
}
pub fn read(&self) -> f64 {
self.buffer[self.index]
}
pub fn write_and_advance(&mut self, ... |
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::time::timeout;
use tokio_io_timeout::TimeoutStream;
use hyper::client::connect::{Connected, Connection};
use hyper::{service::Service, Uri};
mod stream;... |
use crate::page::{self, route, Page, Route};
use seed::prelude::*;
use seed::{a, attrs, log, C};
pub struct Model {
route: Route,
page: Page,
}
#[derive(Debug)]
pub enum Msg {
NavigateTo(Route),
RepoListMsg(page::repo_list::Msg),
RepoMsg(page::repo::Msg),
}
pub fn init(url: Url, orders: &mut imp... |
#[doc = "Register `DFSDM_FLT2ICR` reader"]
pub type R = crate::R<DFSDM_FLT2ICR_SPEC>;
#[doc = "Register `DFSDM_FLT2ICR` writer"]
pub type W = crate::W<DFSDM_FLT2ICR_SPEC>;
#[doc = "Field `CLRJOVRF` reader - Clear the injected conversion overrun flag"]
pub type CLRJOVRF_R = crate::BitReader;
#[doc = "Field `CLRJOVRF` wr... |
//Solving first with brute force
pub fn find_error_part_one(expenses: Vec<i32>) -> i32 {
for first in &expenses {
for second in &expenses {
let sum = first + second;
if sum == 2020 {
return first * second
}
}
}
return 0;
}
pub fn find_error_part_two(expenses: Vec<i32>) -> i32 ... |
// unihernandez22
// https://codeforces.com/problemset/problem/1195/c
// dp
use std::io::stdin;
use std::cmp::max;
fn main() {
let mut n = String::new();
stdin().read_line(&mut n).unwrap();
let n: i64 = n.trim().parse().unwrap();
let mut line = String::new();
stdin().read_line(&mut line).unwrap()... |
mod core;
mod messages;
mod transaction;
mod transport;
pub use self::core::{
CapabilitiesSnitch, CorePanic, CoreSnitch, RegistrarSnitch, ReqProcessorPanic,
};
pub use self::transaction::{TransactionEmptySnitch, TransactionPanic};
pub use self::transport::{TransportErrorSnitch, TransportPanic, TransportSnitch};
pu... |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use crate::decl_parser_options::DeclParserOptions;
use crate::parser_options::ParserOptions;
impl DeclParserOptions<'_> {
pub const... |
use std;
pub unsafe fn cast_slice<A, B>(slice_ref: &[A]) -> &[B] {
use std::slice;
let raw_len = std::mem::size_of::<A>().wrapping_mul(slice_ref.len());
let len = raw_len / std::mem::size_of::<B>();
assert_eq!(raw_len, std::mem::size_of::<B>().wrapping_mul(len));
slice::from_raw_parts(slice_ref.as_ptr() as *cons... |
use envy;
use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct Config {
mins: u64,
title: String,
}
fn main() {
match envy::from_env::<Config>() {
Ok(config) => println!("{:#?}", config),
Err(error) => eprintln!("{:#?}", error),
}
}
|
/// A platform system independent window identifier.
///
/// This allows other crates to reference windows without needing to
/// specify what platform crate is being used.
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub struct WindowId {
riddle_window_id: u32,
}
impl WindowId {
pub fn new(id: u32) -> Self {
... |
struct FunctionalTable<C> {
priv name : ~str,
priv map : ~::std::hashmap::HashMap<Entity, C>
}
impl<C : ToStr + Clone> FunctionalTable<C> {
pub fn new(name : ~str) -> FunctionalTable<C>{
info!("create_table name={}",name);
FunctionalTable{
name : name,
map : ~::std::hashmap::HashMap::new()... |
use subspace_codec::Spartan;
#[test]
fn test_random_piece() {
let public_key = rand::random::<[u8; 32]>();
let nonce = rand::random();
let spartan = Spartan::new(public_key.as_ref());
let encoding = spartan.encode(nonce);
assert!(spartan.is_encoding_valid(encoding, nonce));
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct CH {
#[doc = "0x00 - channel configuration y register"]
pub cfgr1: CFGR1,
#[doc = "0x04 - channel configuration y register"]
pub cfgr2: CFGR2,
#[doc = "0x08 - analog watchdog and short-circuit detector register"]
pub awscdr: AWSCDR,
#[doc = "0... |
use crate::bit_set::ops::*;
#[test]
fn access() {
let slice = [1u64, 0b10101100001, 0b0000100000];
assert!(slice.access(0));
assert!(slice.access(70));
}
#[test]
fn count() {
let slice = [0u64, 0b10101100000, 0b0000100000];
assert_eq!(slice.count1(), 5);
}
#[test]
fn rank() {
let slice = [0u8... |
use actix_web::{middleware::Logger, web, App, HttpServer, Responder};
use anyhow::Result;
use dotenv;
use std::env;
mod errors;
mod init;
mod models;
mod routes;
mod validation;
async fn helo() -> impl Responder {
"yeeeeeeeeee"
}
#[actix_web::main]
async fn main() -> Result<()> {
dotenv::dotenv().expect(".en... |
pub use crate::common::{Const, Id, Op2};
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub enum Expr {
Var(Id),
Const(Const),
Op2(Op2, Box<Expr>, Box<Expr>),
Fun(Id, Box<Expr>),
App(Box<Expr>, Box<Expr>),
If(Box<Expr>, Box<Expr>, Box<Expr>),
Let(Id, Box<Expr>, Box<Expr>),
Fix(Id, Box<Exp... |
use christmas_tree::{
fold::{folder, Control, Folder},
visit::{visitor, Visitor},
DefaultNode, DefaultTreeFactory, FromDiscriminantError, GreenNode, GreenTree, GreenTreeFactory,
NodeType, OwnedRoot, RefRoot, TreeNode,
};
use core::{convert::TryFrom, ops::Range as OpsRange};
#[cfg(feature = "serializati... |
use radix::tree::Tree;
use std::mem;
pub struct Node<T> {
pub key: Vec<u8>,
pub value: Option<T>,
pub next: Tree<T>,
pub child: Tree<T>,
}
impl<T> Node<T> {
pub fn new(key: Vec<u8>, value: Option<T>) -> Self {
Self {
key,
value,
next: None,
c... |
fn m() {
// single
let server = Server::new();
server.start();
client.connect(server);
// multi
// server
let server = Server::new();
server.start();
//client
let address = input!(address);
client.connect(address);
}
fn server() {
loop {
let data = receive_from_... |
use _const::DAMAGE_RANGE;
use component::{Component, Health};
use entity::Entity;
pub fn hit_once(health: &mut Health, damage_taken: Option<i32>) {
health.0 -= match &damage_taken {
None => DAMAGE_RANGE,
Some(v) => v.clone(),
};
}
pub fn get(entity: &Entity) -> &Health {
match entity
... |
#![allow(non_upper_case_globals)]
#![allow(dead_code)]
use ui::*;
use render::Canvas;
use draw::Shape;
pub const TRANSPARENT: u32 = 0x000000_00;
pub static PAL_GAMEBOY: &[u32] = &[
0xCADC9F_FF,
0x0F380F_FF,
0x306230_FF,
0x8BAC0F_FF,
0x9BBC0F_FF,
];
pub const GRID_COLOR: u32 = 0xFF0000_AA;
pub co... |
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(untagged)]
pub enum MaterialParameterType {
Scalar(f32),
Vector([f32; 3]),
}
impl MaterialParameterType {
pub fn as_vec3(&self) -> [f32; 3] {
match self {
Self::Scalar(c) => [*c; 3],... |
extern crate game;
use std::env;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
let config = game::app::safety::Config::new(&args);
config.run().unwrap_or_else(|err| {
eprintln!("Error: {}", err);
process::exit(1);
});
}
|
use std::sync::Arc;
use vulkano::command_buffer::SubpassContents;
use vulkano::buffer::{CpuAccessibleBuffer, BufferUsage};
use vulkano::pipeline::{GraphicsPipeline, GraphicsPipelineAbstract};
use gristmill::renderer::{LoadContext, RenderContext, scene};
// ------------------------------------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.