text stringlengths 8 4.13M |
|---|
use core::fmt::{self, Write};
use common::time::Duration;
#[derive(Copy, Clone)]
pub enum LogLevel {
Critical,
Error,
Warning,
Info,
Debug,
}
/// Add message to kernel logs with format
#[macro_export]
macro_rules! syslog {
($level:expr, $($arg:tt)*) => ({
$crate::logging::syslog_inner... |
#[doc = "Writer for register CRYP_K1LR"]
pub type W = crate::W<u32, super::CRYP_K1LR>;
#[doc = "Register CRYP_K1LR `reset()`'s with value 0"]
impl crate::ResetValue for super::CRYP_K1LR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Write proxy for field `K1... |
fn main() {
let str_hello = "Hello";
let str_world = "world!";
let str_hello_world = String::from(str_hello) + ", " + str_world;
let str_even = "even number";
let str_odd = "odd number";
for n in 1..5 {
print_even_or_odd(n, &str_hello_world);
//let even_or_odd = is_even_or_odd_b... |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*/
use std::fs::File;
use std::io::{Seek, Read};
use crate::common::{ANNResult, ANNError};
/// Sequential cached reads
pub struct CachedReader {
/// File reader
reader: File,
/// # bytes to cache in one sh... |
#[derive(Clone)]
pub enum SquareContents {
Blocker,
TextContent(String, Option<SquareModifier>),
}
#[derive(Clone)]
pub enum SquareModifier {
Shading,
Circle,
}
#[derive(Clone)]
pub struct Square {
pub content: SquareContents,
pub label: Option<u32>,
pub x: u32,
pub y: u32,
pub acr... |
use std::fs::read_to_string;
fn get_input() -> Vec<i32> {
read_to_string("../inputs/9.txt").unwrap()
.split_whitespace()
.flat_map(|i| i.parse())
.collect()
}
pub fn solve() {
let numbers = get_input();
print!("Day 9 part 1: {}\n", part_1(&numbers, 25));
print!("Day 9 part 2: {... |
use std::env;
use std::fs;
use std::fs::metadata;
use std::path::Path;
use std::path::PathBuf;
use std::process;
pub struct Setup {
pub input: Vec<String>,
pub output: String,
}
impl Setup {
pub fn generate() -> Setup {
let args: Vec<String> = env::args().collect();
let input_files;
... |
#[doc = "Register `CFGR2` reader"]
pub type R = crate::R<CFGR2_SPEC>;
#[doc = "Register `CFGR2` writer"]
pub type W = crate::W<CFGR2_SPEC>;
#[doc = "Field `LOCKUP_LOCK` reader - Cortex-M0+ LOCKUP bit enable bit"]
pub type LOCKUP_LOCK_R = crate::BitReader;
#[doc = "Field `LOCKUP_LOCK` writer - Cortex-M0+ LOCKUP bit enab... |
#[doc = "Reader of register IC_CLR_RX_UNDER"]
pub type R = crate::R<u32, super::IC_CLR_RX_UNDER>;
#[doc = "Reader of field `CLR_RX_UNDER`"]
pub type CLR_RX_UNDER_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Read this register to clear the RX_UNDER interrupt (bit 0) of the IC_RAW_INTR_STAT register.\\n\\n Res... |
use proconio::input;
use std::cmp::min;
fn main() {
input! {
a:u32,
b:u32,
x:u32,
y:u32,
}
if a == b {
println!("{}", x);
} else if a == b + 1 {
println!("{}", x);
} else {
let steps = if a <= b { b - a } else { a - b };
if a <= b {
... |
// Copyright 2018-2019 Mozilla
//
// 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 writing, sof... |
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// 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 F... |
/*
Copyright 2020 <盏一 w@hidva.com>
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 writing, software
distr... |
pub mod attributes;
pub mod events;
mod elements;
pub use self::elements::*;
use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::closure::Closure;
#[derive(Clone, Debug)]
pub enum Html<Msg> {
Element(Element<Msg>),
Text(String),
}
impl<T: ToString, Msg> From<T> for Html<Msg> {
fn from(t: T) -> Ht... |
use std::io;
use docker::Docker;
use strategy::CleanupStrategy;
pub struct ImageCleanup{
docker: Docker
}
impl ImageCleanup {
pub fn new(docker: Docker) -> ImageCleanup{
ImageCleanup {
docker: docker
}
}
pub fn cleanup(&self, strategy: &CleanupStrategy) -> Result<(), io::Error>{
let images = try!(self.... |
fn main() {
// We're going to decrement these in a clever way
let mut num1 = 999;
let mut num2 = 999;
// Keep track of the largest product so far
let mut largest = 0;
// The threshold past which you stop checking
let mut limit = 0;
// Iterate through all (899 choose 2 = 403651) possib... |
use crate::serv_auth::Preauthed;
use crate::serv_conn::ServiceConnection;
use crate::util::ArcExt;
use acme_lib::Certificate;
use serde::{Deserialize, Serialize};
use std::sync::Weak;
// It's important the peek doesn't expect more than the smallest possible request.
// The smallest possible HTTP request would be about... |
use std::env;
use std::error::Error;
use std::result;
type Result<T> = result::Result<T, Box<dyn Error>>;
struct Scores {
scores: Vec<usize>,
elves: [usize; 2],
hold: Vec<usize>,
}
impl Iterator for Scores {
type Item = usize;
fn next(&mut self) -> Option<usize> {
if !self.hold.is_empty(... |
use serde::Deserialize;
use serde_json::Value;
use std::mem;
use std::ops::Range;
#[derive(Clone)]
pub struct Line {
text: String,
/// List of carets, in units of utf-16 code units.
cursor: Vec<usize>,
styles: Vec<StyleSpan>,
invalid: bool,
new_ln: usize,
}
#[derive(Deserialize)]
pub struct St... |
fn main() {
type Account = Box<FnMut(i32) -> Result<i32, &'static str>>;
fn make_withdraw(mut balance: i32) -> Account {
Box::new(move |amount: i32| {
if balance >= amount {
balance -= amount;
Ok(balance)
} else {
Err("Insufficient... |
use pretty_assertions::assert_eq;
use crate::{
bson::doc,
bson_util,
cmap::StreamDescription,
concern::{Acknowledgment, WriteConcern},
error::{ErrorKind, WriteConcernError, WriteError, WriteFailure},
operation::{test::handle_response_test, Delete, Operation},
options::DeleteOptions,
Nam... |
#![warn(rust_2018_idioms, clippy::all)]
mod helpers;
mod services;
use simple_logger::SimpleLogger;
use anyhow::{Result, Error};
use log::{
warn,
LevelFilter
};
use clap::{Arg, App, SubCommand, ArgMatches};
use yansi::Paint;
use crate::services::{
model::{EnsurableEntity, RemovableEntity}... |
use crate::Pred;
use crate::Pred2;
use std::fmt::Debug;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
std_prelude!();
fn iter_adjacent<T: Copy, I: Iterator<Item = T>>(mut iter: I) -> impl Iterator<Item = (T, T)> {
let fst = iter.next();
iter.scan(fst, |x, y| x.replace(y).map(|x| (x, y)))
}
#[der... |
pub mod builder;
mod nfa;
pub use self::nfa::*;
|
//! Data structures used by the JSON-RPC API methods.
use crate::core::{StarknetBlockHash, StarknetBlockNumber};
use serde::{Deserialize, Serialize};
/// Special tag used when specifying the `latest` or `pending` block.
#[derive(Copy, Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
... |
//! Tests auto-converted from "sass-spec/spec/non_conformant/sass/semicolon"
#[allow(unused)]
use super::rsass;
// From "sass-spec/spec/non_conformant/sass/semicolon/at_rule.hrx"
// From "sass-spec/spec/non_conformant/sass/semicolon/content.hrx"
// From "sass-spec/spec/non_conformant/sass/semicolon/debug.hrx"
// Fr... |
use minifb;
pub struct Window {
window: minifb::Window,
width: usize,
height: usize,
}
impl Window {
pub fn new(width: usize, height: usize) -> Window {
let mut options = minifb::WindowOptions::default();
options.scale = minifb::Scale::X8;
let window = minifb::Window::new(
... |
//! Traits and basic implementations of packet encoding/decoding functionality.
//!
//! This module exports two main traits: `FromPacketBytes` and `ToPacketBytes`.
//! These are used to specify how various types are encoded/decoded in the ROTMG
//! network protocol. Implementations are also provided for primitives and ... |
#[doc = "Register `APB2RSTR` reader"]
pub type R = crate::R<APB2RSTR_SPEC>;
#[doc = "Register `APB2RSTR` writer"]
pub type W = crate::W<APB2RSTR_SPEC>;
#[doc = "Field `SYSCFGRST` reader - System configuration (SYSCFG) reset"]
pub type SYSCFGRST_R = crate::BitReader;
#[doc = "Field `SYSCFGRST` writer - System configurat... |
use std::{collections::HashMap, time::Instant};
pub fn main() {
let start = Instant::now();
assert_eq!(part_1_test(), 436);
assert_eq!(part_1_test_2(), 1836);
// println!("part_1 {:?}", part_1());
// assert_eq!(part_2_test(), 175594);
println!("part_2 {:?}", part_2());
let duration = sta... |
// list of math submodules
pub mod bundle_adjustment;
pub mod linear_algebra;
pub mod ransac; |
extern crate nalgebra as na;
extern crate rand;
extern crate image;
mod parser;
mod render;
mod utils;
use parser::Model;
use parser::Texture;
use render::Img;
use na::Vector2;
use na::Vector3;
//use na::Cross;
//use na::Norm;
//use na::Dot;
const WIDTH: u32 = 800;
const HEIGHT: u32 = 800;
const DEPTH: u32 = 250;
... |
use super::population::Population;
use super::*;
#[derive(Default)]
pub struct Optimizer {
repos_lengths: Vec<usize>,
demand_pieces: Vec<DemandPiece>,
spacing: usize,
random_seed: u64,
multiplier: f64,
}
impl Optimizer {
pub fn new(decimal_places: usize) -> Self {
Optimizer {
... |
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
mod database;
use regex::Regex;
use rocket::fairing::AdHoc;
use rocket::request::LenientForm;
use rocket::Request;
use rocket::response::NamedFile;
use rocket::State;
use rocket_contrib::templates::Template;
use std::collections::HashMap;
us... |
// This file is part of Substrate.
// Copyright (C) 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
//
// http://... |
use crate::BoxError;
use derive_more::Display;
use thiserror::Error;
/// The Error returned by storage backends. Storage backend implementations should choose the
/// `ErrorKind` chosen for errors carefully since that will determine what is returned to the FTP
/// client.
#[derive(Debug, Error)]
#[error("storage error... |
use anyhow::Result;
use wasm_bindgen::JsCast;
impl crate::ctx::ClientContext {
pub(crate) fn get_element_by_id(&self, id: &str) -> Result<web_sys::HtmlElement> {
self.get_element_by_id_as::<web_sys::HtmlElement>(id)
}
pub(crate) fn get_element_by_id_as<T: JsCast>(&self, id: &str) -> Result<T> {
match se... |
#[macro_use]
extern crate log;
use rsocket_rust::prelude::*;
use rsocket_rust::Result;
use rsocket_rust_transport_tcp::tokio_native_tls::{native_tls, TlsConnector};
use rsocket_rust_transport_tcp::TlsClientTransport;
#[tokio::main]
async fn main() -> Result<()> {
env_logger::builder().format_timestamp_millis().in... |
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct PowRequest1<Rq> {
pub request: Rq,
}
#[derive(Serialize, Deserialize)]
pub struct PowRequest2<Pz> {
pub puzzle_solution: Pz,
} |
use bson::{doc, Document};
use serde::{Deserialize, Serialize, Serializer};
use std::time::Duration;
use typed_builder::TypedBuilder;
use crate::{
error::Result,
operation::append_options,
runtime,
selection_criteria::SelectionCriteria,
Client,
};
// If you write a tokio test that uses this, make ... |
#[doc = "Register `ICR` writer"]
pub type W = crate::W<ICR_SPEC>;
#[doc = "Field `FLT1C` writer - Fault 1 Interrupt Flag Clear"]
pub type FLT1C_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FLT2C` writer - Fault 2 Interrupt Flag Clear"]
pub type FLT2C_W<'a, REG, const O: u8> = crate::BitWriter... |
extern crate diesel;
extern crate UserManagerCrud;
use self::diesel::prelude::*;
use self::UserManagerCrud::models::*;
use self::UserManagerCrud::*;
use std::io::stdin;
mod lambda_crypt;
fn main() {
use UserManagerCrud::schema::users::dsl::*;
println!("Put you email here:");
let mut emailin = String::ne... |
fn main() {
let mut dir = [1, 0];
let mut coords = [0, 0];
String::from_utf8(std::fs::read("input/day12").unwrap())
.unwrap()
.split_terminator("\n")
.map(|n| (n.chars().next().unwrap(), n[1..].parse::<i32>().unwrap()))
.for_each(|(key, value)| match key {
'N' => ... |
use gtk::{ButtonsType, DialogFlags, Inhibit, MessageDialog, MessageType, Window};
use gtk::Orientation::{Horizontal, Vertical};
use gtk::prelude::*;
use rand::Rng;
use relm_derive::{Msg, widget};
use relm::{Channel, Component, Relm, Sender, Widget, init};
use self::WinMsg::*;
pub struct HeaderModel {
tx: Sender<W... |
pub mod hackernews;
pub mod reddit;
pub mod twitter;
|
use crate::error::NiaServerError;
use crate::error::NiaServerResult;
use crate::protocol::Serializable;
use nia_protocol_rust::RemoveDeviceByNameRequest;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NiaRemoveDeviceByNameRequest {
device_name: String,
}
impl NiaRemoveDeviceByNameRequest {
pub fn new<S>(d... |
#[doc = "Reader of register DDRPHYC_PIR"]
pub type R = crate::R<u32, super::DDRPHYC_PIR>;
#[doc = "Writer for register DDRPHYC_PIR"]
pub type W = crate::W<u32, super::DDRPHYC_PIR>;
#[doc = "Register DDRPHYC_PIR `reset()`'s with value 0"]
impl crate::ResetValue for super::DDRPHYC_PIR {
type Type = u32;
#[inline(... |
// This is the main function
// fn
fn main() {
println!("Hello World!");
}
|
fn main() {
let v1 = vec![1, 2, 3];
let v1_iter = v1.iter();
// fol loop automatically takes ownership of v_iter and
// makes it mutable behind the scenes. This is needed because
// v_iter keeps some internal state (current item) which needs
// to be kept up to date
for val in v1_iter {
... |
use crate::plan::global::NoCopy;
use crate::plan::global::Plan;
use crate::policy::space::Space;
use crate::scheduler::gc_work::*;
use crate::util::Address;
use crate::util::ObjectReference;
use crate::vm::VMBinding;
use crate::MMTK;
use std::ops::{Deref, DerefMut};
use super::MarkSweep;
pub struct MSProcessEdges<VM:... |
use serde::Deserialize;
use serde_state::DeserializeState;
use necsim_core_bond::{Partition, PositiveF64};
#[derive(Debug)]
#[allow(clippy::module_name_repetitions)]
pub struct MonolithicArguments {
pub parallelism_mode: ParallelismMode,
}
impl<'de> DeserializeState<'de, Partition> for MonolithicArguments {
... |
use std::fs;
use std::env;
use std::collections::HashMap;
struct JoltageDifferenceCalculator {
adapters: Vec<i32>,
}
impl JoltageDifferenceCalculator {
fn calculate(&mut self) -> i32 {
self.adapters.sort();
println!("{:?}", self.adapters);
let mut current_joltage = 0;
let mut... |
use std::fs::{File, DirBuilder, read_dir, metadata, remove_file};
use std::path::Path;
use std::error::Error;
use std::io::prelude::*;
use std::time::{Duration, SystemTime};
use std::thread::{self, sleep};
use iron::prelude::*;
use uuid::Uuid;
use serde_json::Value;
use multipart::server::{Multipart, Entries, SaveResu... |
mod mesh;
mod mesh_grouper;
mod sculpt;
pub use self::mesh::{Mesh, Vertex, Instance};
pub use self::mesh_grouper::{MeshGrouper, GroupChange};
pub use self::sculpt::{SculptLine, Surface, SpannedSurface, FlatSurface, Sculpture, SkeletonSpine, RoofSurface, GableSurface}; |
#![feature(used)]
#![no_std]
extern crate cortex_m_semihosting;
#[cfg(not(feature = "use_semihosting"))]
extern crate panic_abort;
#[cfg(feature = "use_semihosting")]
extern crate panic_semihosting;
extern crate cortex_m;
extern crate cortex_m_rt;
extern crate atsamd21_hal;
extern crate metro_m0;
use metro_m0::clo... |
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
#[derive(Debug, Clone)]
pub struct Event{
created: String,
dtend: String,
dtstart: String,
summary: String,
uid: String,
}
#[wasm_bindgen]
pub fn parse_string(data:String) {
let mut created ="";
let mut dtend ="";
let mut dtstart = "";
... |
use std::convert::From;
use std::ops::Deref;
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct U5(u8);
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct U7(u8);
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct U14(u16);
#[derive(Debug, Copy, Clon... |
struct MyStruct {
name : String
}
impl MyStruct {
fn f1(&mut self) {
self.name = "hello".to_string();
self.f2("world");
}
fn f2(&mut self, last_name : &str) {
self.name = last_name.to_string();
println!("{}", self.name);
}
}
fn main() {
let mut x = 1i32;
{... |
//! TODO docs
use serde::{Deserializer, Serializer};
/// TODO docs
#[inline]
pub fn bool_or_integer<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(BoolOrIntegerVisitor)
}
/// TODO docs
pub struct BoolOrIntegerVisitor;
impl<'de> serde::de::Visitor... |
mod gltf;
mod object_trs;
mod curve;
mod primitive;
use nitro::Model;
use db::{Database, ModelId};
use connection::Connection;
use primitives::{Primitives, PolyType, DynamicState};
use skeleton::{Skeleton, Transform, SMatrix};
use super::image_namer::ImageNamer;
use cgmath::Matrix4;
use json::JsonValue;
use self::gltf... |
extern crate image;
use crate::utils;
use image::{DynamicImage, ImageFormat};
use std::fs::{File, OpenOptions};
use std::io::Error;
trait Rotator {
fn rotate(&mut self);
}
//use exif
pub struct JPEGRotator {
path: String,
file: File,
}
impl JPEGRotator {
/// Returns a new JPEG rotator if the image f... |
fn main() {
let numbers_str = include_str!("inputs/day01.txt");
let numbers: Vec<u32> = numbers_str
.lines()
.map(|x| x.parse::<u32>().unwrap())
.collect();
let size = numbers.len();
for (i, v) in numbers.iter().enumerate() {
if v.to_owned() > 2020 {
continue;... |
use std::collections::HashMap;
use std::time::Duration;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::model::{AlbumSimplified, ArtistSimplified, Context, Restrictions, TypeTrack};
macro_rules! inherit_track_simplified {
($(#[$attr:meta])* $name:ident { $($(#[$f_attr:meta])* $f_name... |
#[derive(Debug, Clone)]
struct Point {
x: i32,
y: i32
}
#[derive(Debug)]
enum Quadrant {
Origin,
XAxis,
YAxis,
TopLeft,
TopRight,
BottomLeft,
BottomRight
}
fn quadrant(p: Point) -> Quadrant {
match p {
Point { x: 0, y: 0 } => Quadrant::Origin,
Point { y: 0, .. }... |
use std::net::SocketAddr;
use clap::{Parser, ValueEnum};
use client::run_client;
use hydroflow::tokio;
use hydroflow::util::{bind_udp_lines, ipv4_resolve};
use server::run_server;
mod client;
mod helpers;
mod protocol;
mod server;
#[derive(Clone, ValueEnum, Debug)]
enum Role {
Client,
Server,
}
#[derive(Par... |
#![cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
use log::{Level, Log, Metadata, Record};
use wasm_bindgen::prelude::*;
// Use web-sys once it's published (rustwasm/wasm-bindgen#613)
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn error(s: &str);
#[wasm_bindgen(j... |
pub use highpass::HighPass;
pub use lowpass::LowPass;
mod highpass;
mod lowpass;
/// Audio filter
pub trait Filter {
/// Filters an audio signal
fn filter(&mut self, input: f32) -> f32;
fn reset(&mut self);
}
|
use gpio::{Gpio, PinId, PinMode, PinState};
pub struct GpioMock;
impl Gpio for GpioMock {
fn pin_mode(&mut self, pin: PinId, mode: PinMode) {
}
fn digital_write(&mut self, pin: PinId, state: PinState) {
}
fn digital_read(&self, pin: PinId) -> PinState {
PinState::Low
}
}
|
use std::cell::{ RefCell, Ref, RefMut };
use crate::types::*;
use crate::spawns::*;
/// Pointer is a reference to objects in the scene, which is used to find and update these objects.
/// A Pointer can hold a reference to an object that doesn't exist anymore,
/// the exists(pointer) methode can be used to check a po... |
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use crate::solution::ProblemSolution;
pub struct Solution {}
impl ProblemSolution for Solution {
fn name(&self) -> &'static str {
return "problem_05";
}
fn part1(&self) -> io::Result<i64> {
BufReader::new(Fi... |
//! The `ArrayType` struct.
use SafeWrapper;
use ir::{SequentialType, CompositeType, Type};
use sys;
/// An array type.
pub struct ArrayType<'ctx>(SequentialType<'ctx>);
impl<'ctx> ArrayType<'ctx>
{
/// Creates a new array type.
pub fn new(element_type: &Type, num_elements: u64) -> Self {
unsafe {
... |
#[doc = "Register `RESP1` reader"]
pub type R = crate::R<RESP1_SPEC>;
#[doc = "Field `CARDSTATUS1` reader - see Table 132."]
pub type CARDSTATUS1_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - see Table 132."]
#[inline(always)]
pub fn cardstatus1(&self) -> CARDSTATUS1_R {
CARDSTATUS1_R::... |
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
fn main() {
part1();
part2();
}
fn part1() {
let f = File::open("data/day2.txt").unwrap();
let file = BufReader::new(&f);
let mut sum = 0;
for line in file.lines() {
let l = line.unwrap();
let mut nums: Vec<i32> ... |
mod schema;
mod seed;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
use schema::seeds::dsl::*;
use diesel::{RunQueryDsl, PgConnection, Connection};
use dotenv;
use std::env;
use crate::seed::Seed;
embed_migrations!("migrations");
fn add(conn: &PgConnection, other_prefix: String) -> ... |
use std::net::SocketAddr;
use chrono::prelude::*;
use hydroflow::hydroflow_syntax;
use hydroflow::util::{UdpSink, UdpStream};
use crate::protocol::EchoMsg;
use crate::Opts;
pub(crate) async fn run_client(outbound: UdpSink, inbound: UdpStream, opts: Opts) {
// server_addr is required for client
let server_add... |
#[doc = "Reader of register CH_STATUS"]
pub type R = crate::R<u32, super::CH_STATUS>;
#[doc = "Reader of field `INTR_CAUSE`"]
pub type INTR_CAUSE_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:3 - Specifies the source of the interrupt cause: '0': NO_INTR '1': COMPLETION '2': SRC_BUS_ERROR '3': DST_BUS_ERROR '4': SR... |
// Problem 4 - Largest palindrome product
//
// A palindromic number reads the same both ways. The largest palindrome made
// from the product of two 2-digit numbers is 9009 = 91 × 99.
//
// Find the largest palindrome made from the product of two 3-digit numbers.
fn main() {
println!("{}", solution());
}
fn solu... |
// This file is part of Substrate.
// Copyright (C) 2019-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... |
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::iter::once;
pub fn win32_string( value : &str ) -> Vec<u16> {
OsStr::new( value ).encode_wide().chain( once( 0 ) ).collect()
}
|
use serenity::framework::standard::{macros::command, Args, CommandError, CommandResult};
use serenity::model::channel::Message;
use serenity::prelude::*;
use uwuifier::uwuify_str_sse;
#[command]
#[usage = "[input text]"]
#[aliases("owo")]
#[description = "OwOfy your text, cause why not."]
async fn owoify(context: &Co... |
#[macro_use]
extern crate lazy_static;
use tokio::net::TcpListener;
use tokio::prelude::*;
use crate::http::request::Request;
use crate::http::response::{Response, Status};
use std::collections::HashMap;
use std::sync::{Mutex, Arc};
mod parser;
pub mod http;
pub type Handler = dyn Fn(Request, &mut Response) + Send +... |
extern crate arith;
use std::io::{self, Read};
use arith::{eval, parse};
fn main() {
let mut buffer = String::new();
match io::stdin().read_to_string(&mut buffer) {
Ok(_) => {
let program = parse(&buffer);
match program {
Ok(term) => {
print... |
use std::cmp::{max};
use std::io::{BufWriter, stdin, stdout, Write};
#[derive(Default)]
struct Scanner {
buffer: Vec<String>
}
impl Scanner {
fn next<T: std::str::FromStr>(&mut self) -> T {
loop {
if let Some(token) = self.buffer.pop() {
return token.parse().ok().expect("Fa... |
// This file contains logic to define how templates are rendered
use crate::default_headers::default_headers;
use crate::errors::*;
use crate::Request;
use crate::SsrNode;
use crate::Translator;
use futures::Future;
use http::header::HeaderMap;
use std::collections::HashMap;
use std::pin::Pin;
use std::rc::Rc;
use syc... |
//! Encode utilities
use lib::*;
use super::ValueType;
use super::util::{pad_u32, pad_i32, pad_i64, pad_u64, Hash};
fn pad_bytes(bytes: &[u8]) -> Vec<Hash> {
let mut result = vec![pad_u32(bytes.len() as u32)];
result.extend(pad_fixed_bytes(bytes));
result
}
fn pad_fixed_bytes(bytes: &[u8]) -> Vec<Hash> {
let mut... |
#![feature(question_mark)]
#![feature(stmt_expr_attributes)]
extern crate git2;
extern crate ansi_term;
extern crate chrono;
extern crate lazysort;
extern crate rustc_serialize;
extern crate num_cpus;
#[macro_use]
#[cfg(feature = "qt")]
extern crate qmlrs;
extern crate time;
#[cfg(feature = "csvdump")]
extern crate csv... |
#[doc = "Reader of register BT_SLOT_CAPT_STATUS"]
pub type R = crate::R<u32, super::BT_SLOT_CAPT_STATUS>;
#[doc = "Reader of field `BT_SLOT`"]
pub type BT_SLOT_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:15 - During slave connection event, HW updates this register with the captured BT_SLOT at anchor point, gra... |
use std::{ops::Bound, sync::Arc};
use anyhow::Context;
use axum::extract::Extension;
use hyper::{Body, Response};
use serde_derive::Deserialize;
use svc_agent::AccountId;
use svc_utils::extractors::AccountIdExtractor;
use tracing::{error, info, instrument};
use crate::app::api::v1::{AppError, AppResult};
use crate::a... |
/*===============================================================================================*/
// Copyright 2016 Kyle Finlay
//
// 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
//
// ... |
#![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 Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serd... |
// 34. Find First and Last Position of Element in Sorted Array
/*
Given an array of integers nums sorted in ascending order,
find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
... |
// For tests
#[allow(unused_imports)]
extern crate bytes;
#[allow(unused_imports)]
#[macro_use] extern crate fuel_line_derive;
#[allow(unused_imports)]
extern crate uuid;
pub trait Render {
fn render(&self) -> String;
}
#[macro_export]
macro_rules! templatify {
( $head_template:expr $(;$key:expr; $template:expr)*... |
use super::*;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[repr(transparent)]
pub struct ObjAttr1(u16);
impl ObjAttr1 {
const_new!();
bitfield_int!(u16; 0..=8: u16, x_pos, with_x_pos, set_x_pos);
bitfield_int!(u16; 9..=13: u16, affine_index, with_affine_index, set_affine_index);
bitfield_bool!(u16; ... |
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
// TODO: add diagram
#![allow(dead_code)]
mod buffer_manager;
pub mod commit_phase;
pub mod errors;
pub mod execution_phase;
pub mod ordering_state_computer;
#[cfg(test)]
mod tests;
|
use serde_json::Number;
use serde_json::Value;
use crate::validator::{scope::ScopedSchema, state::ValidationState};
fn validate_as<T, F1, F2>(
scope: &ScopedSchema,
data: &Value,
schema_number_value: F1,
data_value: F2,
) -> ValidationState
where
F1: Fn(&Number) -> Option<T> + Copy,
F2: Fn(&Va... |
//
// Climbing Ropes
//
// Simple program to play around with the 'rope'
// data structure. This is also my second program
// in Rust.
//
struct Rope<'a> {
len: usize,
left: Option<Box<Rope<'a>>>,
right: Option<Box<Rope<'a>>>,
data: &'a String,
}
fn main() {
println!("Hello, world!");
}
|
use ry::parse_path;
#[test]
fn test_parse_path() {
assert_eq!(parse_path("a.b.c").unwrap(), vec!["a", "b", "c"]);
}
#[test]
fn test_parse_path_with_quotes() {
assert_eq!(
parse_path("a.\"foo.bar\".c").unwrap(),
vec!["a", "foo.bar", "c"]
);
}
#[test]
fn test_parse_path_with_one_quote_errs(... |
// Std
use std::convert::Infallible;
// Crates
use anyhow::Result;
use sqlx::sqlite::SqlitePool;
use tracing::info;
use warp::reply::Reply;
use warp::{http, Filter};
// Modules
use crate::db;
use crate::{Entry, Project};
fn json_body_entry() -> impl Filter<Extract = (Entry,), Error = warp::Rejection> + Clone {
w... |
mod database;
mod document_attr_key;
mod indexer;
mod number;
mod ranked_map;
mod serde;
pub use rocksdb;
pub use self::database::{Database, Index, CustomSettings};
pub use self::number::Number;
pub use self::ranked_map::RankedMap;
pub use self::serde::compute_document_id;
|
use std::sync::{Mutex, Arc};
use std::thread;
use crossbeam_channel;
use crossbeam_channel::TryRecvError;
use crate::crl::{RequestCompletionHandler, Crl};
use crate::crl;
use crate::object;
use crate::transaction;
use super::*;
// Used to indicate that an entry is full and cannot accept any more data
struct EntryFu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.