text stringlengths 8 4.13M |
|---|
use crate::schema::*;
use diesel::{Insertable, Queryable};
use serde::Serialize;
#[derive(Serialize, Queryable, Insertable)]
#[table_name = "blog"]
pub struct Blog {
pub id: uuid::Uuid,
pub title: String,
pub markdown: String,
pub created_time: chrono::NaiveDateTime,
}
impl Blog {
pub fn new(title... |
extern crate itertools;
use itertools::Itertools;
#[derive(Debug, PartialEq)]
pub enum Error {
IncompleteNumber,
Overflow,
}
/// Convert a list of numbers to a stream of bytes encoded with variable length encoding.
pub fn to_bytes(values: &[u32]) -> Vec<u8> {
let mut res = vec![];
for val in values.... |
mod fizzbazz1;
fn main() {
fizzbazz1::run();
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qsessionmanager.h
// dst-file: /src/gui/qsessionmanager.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block be... |
//! A zero overhead Windows I/O library
#![cfg(windows)]
#![deny(missing_docs)]
#![allow(bad_style)]
#![doc(html_root_url = "https://docs.rs/miow/0.1/x86_64-pc-windows-msvc/")]
extern crate kernel32;
extern crate net2;
extern crate winapi;
extern crate ws2_32;
#[cfg(test)] extern crate rand;
use std::cmp;
use std::... |
use crate::utils::EitherIter;
use crate::{CoordinateType, LineString, Point};
use geo_types::PointsIter;
use std::iter::Rev;
pub(crate) fn twice_signed_ring_area<T>(linestring: &LineString<T>) -> T
where
T: CoordinateType,
{
if linestring.0.is_empty() || linestring.0.len() == 1 {
return T::zero();
... |
use std::time::{SystemTime, UNIX_EPOCH};
use diesel::sqlite::SqliteConnection;
use ruma_events::room::message::MessageType;
use ruma_identifiers::UserId;
use slog::Logger;
use api::rocketchat::WebhookMessage;
use api::{MatrixApi, RocketchatApi};
use config::Config;
use errors::*;
use http::header::HeaderValue;
use i1... |
use bigneon_db::models::{FeeSchedule, TicketType};
use bigneon_db::utils::errors::DatabaseError;
use chrono::NaiveDateTime;
use diesel::PgConnection;
use models::DisplayTicketPricing;
use uuid::Uuid;
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct AdminDisplayTicketType {
pub id: Uuid,
pub name:... |
#![cfg_attr(feature = "serde_macros", feature(custom_derive, plugin))]
#![cfg_attr(feature = "serde_macros", plugin(serde_macros))]
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#[macro_use] extern crate clap;
#[macro_use] extern crate log;
extern crate ansi_term;
exte... |
/*
* Copyright (C) 2020-2022 Zixiao Han
*/
use crate::{
def,
util::{self, get_lowest_index, get_highest_index},
};
const SLIDE_ATTACK_PERM_COUNT: usize = 256;
pub struct BitMask {
pub index_masks: [u64; def::BOARD_SIZE],
pub rank_masks: [u64; def::BOARD_SIZE],
pub file_masks: [u64; def::BOARD_S... |
use std::{
future::Future,
io::{self, ErrorKind},
pin::Pin,
};
use actix_http::{body::BoxBody, error::PayloadError};
use actix_web::{
dev::Payload,
error::JsonPayloadError,
http,
http::{Method, StatusCode},
Error, FromRequest, HttpRequest, HttpResponse, Responder, Result,
};
use async_g... |
pub(crate) use _sha1::make_module;
#[pymodule]
mod _sha1 {
use crate::hashlib::_hashlib::{local_sha1, HashArgs};
use crate::vm::{PyPayload, PyResult, VirtualMachine};
#[pyfunction]
fn sha1(args: HashArgs, vm: &VirtualMachine) -> PyResult {
Ok(local_sha1(args).into_pyobject(vm))
}
}
|
use regex::Regex;
use rustc_hash::FxHashSet as HashSet;
use std::cmp;
pub const INPUT: &str = include_str!("../input.txt");
pub fn parse_input(input: &str) -> Vec<Blueprint> {
let regex_str = concat!(
r"Blueprint (\d+): ",
r"Each ore robot costs (\d+) ore. ",
r"Each clay robot costs (\d+) ... |
//! This crate contains the API for the protocol of the analytics server. `Event` is the type which is sent to the
//! analytics server. Here are some examples of `Event` structures using different `Message` variants:
//!
//! `{"received_time":"2017-04-11T04:29:16.064185621Z","serviced_time":"2017-04-11T04:29:16.064188... |
use std::io;
fn main() {
println!("Welcome to Dhrumil's epic Leap Year validator!");
loop {
println!("Which year would you like to try: ");
let mut str_year = String::new();
io::stdin().read_line(&mut str_year)
.expect("Failed to read line");
let year: u32 = match... |
// 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 {
crate::{
font_catalog::TypefaceInAssetIndex, font_db::FontDb, FontCatalog, FontPackageListing,
FontSets,
},
failure::Erro... |
#[cfg(feature = "glob")]
use crate::glob::*;
use crate::{VMetadata, VPath};
use async_stream::{stream, try_stream};
use futures_lite::{Stream, StreamExt};
// use futures_core::{future::BoxFuture, Stream, TryStream};
// use futures_util::{pin_mut, StreamExt};
use std::future::Future;
use std::io;
use std::pin::Pin;
pub... |
use libc::{c_char};
use std::ffi::{CString, CStr};
use ffi::support::{CVec};
use ffi::support::IntoCVec;
use speller::Speller;
#[no_mangle]
pub extern fn speller_vec_free(ptr: *mut CVec<*mut c_char>) {
unsafe {
let vec = Vec::<*mut c_char>::from_c_vec_raw(ptr);
for c_str in vec.into_iter() {
... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {
#[cfg(feature = "Win32_Foundation")]
pub fn AccNotifyTouchInteraction(hwndapp: super::super::Foundation::HWND, hwndtarget: super::super::Foundation::HWND... |
//! Manage xml character escapes
use std::borrow::Cow;
use errors::Result;
use errors::ErrorKind::Escape;
use from_ascii::FromAsciiRadix;
// UTF-8 ranges and tags for encoding characters
const TAG_CONT: u8 = 0b1000_0000;
const TAG_TWO_B: u8 = 0b1100_0000;
const TAG_THREE_B: u8 = 0b1110_0000;
const TAG_FOUR_B: u8 = 0b... |
// use super::varargs::VarArgs;
use wasmer_runtime_core::Instance;
#[allow(clippy::cast_ptr_alignment)]
pub extern "C" fn _sigemptyset(set: u32, instance: &mut Instance) -> i32 {
debug!("emscripten::_sigemptyset");
let set_addr = instance.memory_offset_addr(0, set as _) as *mut u32;
unsafe {
*set_a... |
#[macro_use]
extern crate clap;
extern crate time;
extern crate clog;
use clap::{App, Arg, ArgGroup};
use clog::{LinkStyle, Clog};
fn main () {
let styles = LinkStyle::variants();
let matches = App::new("clog")
// Pull version from Cargo.toml
.version(&format!("v{}", crate_version!())[..])
... |
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::cmp::{min, max};
fn path(wire: Vec<(char, i32)>) -> (Vec<i32>, Vec<i32>) {
let (mut coords, mut steps) = (vec![0, 0], vec![0]);
for (dir, amt) in wire {
coords.push(coords[coords.len() - 2] + match dir {
'U' | 'R' => amt,
'D' | 'L' => -a... |
pub mod weapons;
|
use gtk::prelude::*;
use gtk::{HeaderBarBuilder, StackSwitcherBuilder};
mod settings;
use crate::ui::State;
use settings::Settings;
use std::cell::RefCell;
use std::rc::Rc;
pub struct Header {
pub container: gtk::HeaderBar,
pub stack_switch: gtk::StackSwitcher,
pub settings: Settings,
}
impl Header {
... |
use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use glommio::channels::channel_mesh::Senders as ChannelMeshSender;
use glommio::sync::RwLock;
use glommio::timer::TimerActionOnce;
use glommio::Local;
use tokio::sync::mpsc::Send... |
use crate::parse::{Instruction, ParseError, ParseResult, RollbackableTokenStream, ToneModifier};
fn hex_to_num(hex: u8) -> Option<usize> {
if b'0' <= hex && hex <= b'9' {
Some((hex - b'0') as usize)
} else if b'a' <= hex && hex <= b'f' {
Some((hex - b'a') as usize + 10)
} else if b'A' <= he... |
use chrono;
use failure::Error;
use fern;
use log;
use std::net::SocketAddr;
const ADDRESS: &str = "127.0.0.1:8080";
pub fn make_socket_address() -> SocketAddr {
ADDRESS.parse().expect("Failed to parse address.")
}
pub fn configure_logging() -> Result<(), Error> {
fern::Dispatch::new()
.format(|out, ... |
use crate::{error::ClientError, network::request_async, Result};
use isahc::prelude::*;
use serde_derive::Deserialize;
const API_ENDPOINT: &str = "https://api.wowinterface.com/addons";
const DL_ENDPOINT: &str = "https://cdn.wowinterface.com/downloads/getfile.php?id=";
#[derive(Clone, Debug, Deserialize)]
/// Struct f... |
#[doc = "Reader of register SWPR"]
pub type R = crate::R<u32, super::SWPR>;
#[doc = "Writer for register SWPR"]
pub type W = crate::W<u32, super::SWPR>;
#[doc = "Register SWPR `reset()`'s with value 0"]
impl crate::ResetValue for super::SWPR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Typ... |
// 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 fidl::encoding::OutOfLine;
use fidl_fuchsia_ledger_cloud::{
CloudProviderRequest, CloudProviderRequestStream, DeviceSetRequest, DeviceSetRequestStr... |
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet};
use itertools::Itertools;
use whiteread::parse_line;
const ten97: usize = 1000000007;
fn alphabet2idx(c: char) -> usize {
if c.is_ascii_lowercase() {
c as u8 as usize - 'a' as u8 as usize
} else if c.is_ascii_uppercase() {
c a... |
use super::tree::Node;
/// Iterator type for a binary tree.
/// This is a generator that progresses through an in-order traversal.
pub struct NodeIterator<T> {
branch_stack: Vec<Node<T>>,
}
impl<T> NodeIterator<T>
where
Node<T>: Clone,
{
/// Given a reference to a node, consume it and return an iterator o... |
use cw::Range;
use dict::{Dict, PatternIter};
/// An iterator over all possibilities to fill one of the given ranges with a word from a set of
/// dictionaries.
pub struct WordRangeIter<'a> {
ranges: Vec<(Range, Vec<char>)>,
dicts: &'a [Dict],
range_i: usize,
dict_i: usize,
pi: Option<PatternIter<'... |
use std::fmt;
#[repr(transparent)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Mac([u8; 16]);
impl Mac {
pub fn get_raw(&self) -> &[u8; 16] {
&self.0
}
}
impl From<[u8; 16]> for Mac {
fn from(x: [u8; 16]) -> Self {
Self(x)
}
}
impl fmt::Display for Mac {
fn fmt(&self,... |
extern crate clap;
extern crate json;
use self::clap::{Arg, App};
use std::fs;
pub mod treenode;
pub fn load_json_tests() -> (json::JsonValue, i32) {
let matches = App::new("json test loader")
.version("0.0.1")
.author("Jean-Christophe Pince <jcpince@gmail.com>")
.about("Load JSON descriptions of alg... |
// Copyright 2022 Datafuse Labs.
//
// 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 ... |
use ecs::*;
use engine::*;
use std::cell::RefCell;
use std::fmt::Debug;
use std::ops::{Deref, DerefMut};
#[derive(Debug, Clone)]
pub struct SingletonComponentManager<T>
where T: Component<Manager=SingletonComponentManager<T>> + Debug + Clone + Default,
T::Message: Message<Target=T>,
{
data: T,
me... |
pub struct Solution;
impl Solution {
pub fn largest_number(nums: Vec<i32>) -> String {
let mut bytes_vec = nums
.iter()
.map(|num| num.to_string().into_bytes())
.collect::<Vec<Vec<u8>>>();
bytes_vec.sort_by(new_cmp);
if bytes_vec[0] == [b'0'] {
... |
/// 页大小
pub const PAGE_SIZE: usize = 0x1000;
/// DMA 分配的最大轮询次数
pub const MAX_DMA_ALLOC_COUNT: u32 = 0x10;
/// 虚拟队列大小
pub const VIRT_QUEUE_SIZE: usize = 32;
/// 块大小
pub const BLOCK_SIZE: usize = 512; |
use std::ffi::{CStr, CString, IntoStringError};
use std::fmt::{self, Display, Formatter};
use std::io;
use std::mem::{self, MaybeUninit};
use std::os::raw::{c_int, c_void};
use std::path::PathBuf;
/// Error during working directory retrieval.
#[derive(Debug)]
pub enum Error {
Io(io::Error),
/// Error converti... |
// Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use std::convert::{From, Into};
use rabble::{self, Pid, CorrelationId, Envelope};
use msg::Msg;
use NamespaceMsg;
use vr::vr_fsm::{Transition, VrState, State};
use vr::vr_ctx::VrCtx;
use vr::vr_msg::{VrMsg, EpochStarted, ... |
extern crate serde;
use serde::{Serialize, Deserialize};
extern crate bincode;
use bincode::{serialize, deserialize};
use crate::btree::key_value::{KeyType, ValueType};
use std::error::Error;
use std::marker::PhantomData;
use std::fs::File;
use std::io::Write;
use std::io::Read;
use std::io::SeekFrom;
use std::io::pre... |
use actix_web::{guard, web, App, HttpResponse, HttpServer, Result};
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig};
use async_graphql::{EmptyMutation, EmptySubscription, Schema};
use async_graphql_actix_web::{Request, Response};
use async_graphql::extensions::ApolloTracing;
use async_graphql::*;
... |
// Copyright 2019
// by Centrality Investments Ltd.
// and Parity Technologies (UK) Ltd.
//
// 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/... |
//! # Library to work with the MARC 21 Format for Bibliographic Data
//!
//! ## Examples
//!
//! ### Reading
//!
//! ```rust
//! # use marc::*;
//! # use std::{io, fs};
//! # fn main() -> marc::Result<()> {
//! let input = fs::File::open("test/fixtures/3records.mrc")?;
//! let mut count = 0;
//!
//! for (i, record) in ... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {
#[cfg(feature = "Win32_Foundation")]
pub fn HcsAttachLayerStorageFilter(layerpath: super::super::Foundation::PWSTR, layerdata: super::super::Foundation::... |
use crate::errors::ErrorCx;
use crate::grammar;
use crate::lexer;
use crate::raw;
use crate::source_file::{FileMap, SourceFile};
use crate::span::{FileId, Span};
use crate::token::Token;
use annotate_snippets::snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation};
use lalrpop_util;
use std::fmt;
use s... |
use std::{
collections::{BTreeSet, HashMap},
sync::{
atomic::{AtomicUsize, Ordering},
Arc, Mutex,
},
};
use async_trait::async_trait;
use data_types::{ColumnSet, CompactionLevel, ParquetFile, ParquetFileParams, Timestamp};
use datafusion::physical_plan::SendableRecordBatchStream;
use iox_ti... |
extern crate coinbase_pro_rs;
extern crate futures;
extern crate tokio;
use coinbase_pro_rs::structs::wsfeed::*;
use coinbase_pro_rs::{WSFeed, WS_SANDBOX_URL};
use futures::{Future, Stream};
fn main() {
let stream = WSFeed::new(WS_SANDBOX_URL, &["BTC-USD"], &[ChannelType::Heartbeat]);
let f = stream.take(10)... |
use std::fs;
use std::io::BufReader;
use regex::Regex;
use std::rc::Rc;
use std::error;
use std::fmt;
mod constants {
pub const MAGIC_SAZ: &[u8; 4] = b"\x50\x4B\x03\x04";
pub const MAGIC_SAZ_EMPTY: &[u8; 4] = b"\x50\x4B\x05\x06";
pub const MAGIC_SAZ_SPANNED: &[u8; 4] = b"\x50\x4B\x07\x08";
}
type Resul... |
use crate::ast::AST;
use crate::lexer::LexerError;
use crate::token::Token;
use crate::Position;
use std::error;
use std::fmt;
/// The `Result` of `Parser`.
#[derive(Debug)]
pub enum ParseResult<T> {
/// A success value.
Ok(T),
/// An error value.
Err(ParseError),
/// No expressions found; `Eof` mu... |
fn to_string<T: Into<i64>>(num: T) -> String {
format!("{}", num.into())
}
fn main() {
let foo = &*to_string(0);
println!("{}", foo);
}
|
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri... |
#![allow(non_snake_case)]
use evm::VMTestPatch;
use jsontests::test_transaction;
use serde_json::Value;
// Log format is broken for input limits tests
#[test]
#[ignore]
fn inputLimitsLight() {
let TESTS: Value =
serde_json::from_str(include_str!("../res/files/vmInputLimitsLight/vmInputLimitsLight.json"))... |
use std::env;
use std::os::unix::fs::PermissionsExt;
fn main() -> std::io::Result<()> {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
panic!("Usage: {} file", args[0]);
}
let f = ::std::env::args().nth(1).unwrap();
let metadata = std::fs::metadata(f)?;
let perm = metada... |
/// Trait for fixed size arrays.
pub unsafe trait Array {
/// The array’s element type
type Item;
#[doc(hidden)]
/// The smallest index type that indexes the array.
type Index: Index;
#[doc(hidden)]
fn as_ptr(&self) -> *const Self::Item;
#[doc(hidden)]
fn as_mut_ptr(&mut self) -> *mu... |
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri... |
use proconio::input;
fn main() {
input! {
n: usize,
m: usize,
a: [i64; n],
};
let mut cum_sum = vec![0; n + 1];
for i in 0..n {
cum_sum[i+1] = cum_sum[i] + a[i];
}
let mut s = 0;
for i in 0..m {
s += a[i] * (i + 1) as i64;
}
let mut ans = s;
... |
extern crate digest;
extern crate skein;
use digest::Digest;
use digest::generic_array::typenum::{U32, U64};
fn read_files(path: &str) -> (Vec<u8>, Vec<u8>) {
use std::io::Read;
let mut input = std::fs::File::open(format!("tests/data/{}.input.bin", path)).unwrap();
let mut output = std::fs::File::open(for... |
fn give_closure() -> Box<Fn(u32) -> u32> {
Box::new(move |x: u32| -> u32 { x + 2 })
}
fn main() {
let mut x = 3;
{
let mut addnum = move |number: u32| {
x += number;
println!("{}", x);
};
addnum(10);
}
println!("{}", x);
let result = give_closure()... |
use std::sync::Arc;
use sourcerenderer_core::graphics::{
Backend,
BarrierAccess,
BarrierSync,
BindingFrequency,
CommandBuffer,
Format,
PipelineBinding,
SampleCount,
Texture,
TextureDimension,
TextureInfo,
TextureLayout,
TextureUsage,
TextureView,
TextureViewI... |
use crate::error::BlobError;
use serde::{Deserialize, Serialize};
pub fn read_u64<R: std::io::Read>(r: &mut R) -> Result<u64, BlobError> {
let mut buf = [0u8; 8];
r.read_exact(&mut buf)?;
Ok(bincode::deserialize(&buf[..])?)
}
pub fn write_u64<W: std::io::Write>(w: &mut W, dat: u64) -> anyhow::Result<()> {... |
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... |
// Copyright 2018 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 hex;
use std::fmt;
use std::str;
use crate::errors::BlobIdParseError;
use fidl_fuchsia_pkg as fidl;
#[cfg(test)]
use proptest_derive::Arbitrary;
pu... |
use traits::*;
fn main() {
implement_trait();
default_implementation();
trait_as_parameter();
bound_syntax_parameters();
multiple_trait_bounds();
where_clause();
return_implementation();
get_largest();
trait_bond_conditional_methods();
}
fn implement_trait() {
let tweet = Tweet... |
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
pub struct PatternDto {
pub pattern: String,
}
|
//! Rule
//!
//! A [`Rule`] defines a set of checks to perform on a file. The [`Rule`] contains a `name`
//! describing the [`Rule`] and the `severity` of a violation. The [`Rule`] also may contain a
//! `path` and/or a `content`.
//!
//! If `path` **and** `content` are defined, a file violates the [`Rule`] if the file... |
use raylib::prelude::*;
use std::io;
use std::io::{Read, Write};
use std::net::TcpStream;
use crate::imui::*;
use crate::pong;
use crate::scene::*;
pub struct AwaitingOpponent {
pub lobby_stream: TcpStream,
pub lobby_code: i32,
text_to_copy_to_clipboard: Option<String>,
}
impl AwaitingOpponent {
pub... |
//! Error types for runtimes.
pub use oasis_core_runtime::types::Error as RuntimeError;
use crate::{dispatcher, module::CallResult};
/// A runtime error that gets propagated to the caller.
///
/// It extends `std::error::Error` with module name and error code so that errors can be easily
/// serialized and transferre... |
// consumer_state.rs
//
// Internal handlers for managing static-scope (singleton) server state in a thread-safe manner.
//
// Static server state is guarded for thread-safe access using a blocking RwLock. This is definitely not optimal, and it'd probably be better to use tokio async locks and keep everything async, bu... |
use projecteuler::primes;
fn main() {
//gets optimized into a nop I think
//helper::check_bench(|| {solve(1_000_000);});
assert_eq!(solve(), 748317);
dbg!(solve());
}
fn solve() -> usize {
let single_digit_primes = [1, 2, 3, 5, 7, 9];
let mut pow = 1;
let mut left_inc: Vec<_> = [2, 3, 5, 7... |
fn main() {
let logical: bool = true;
let a_float: f64 = 1.0;
let an_integer = 5i32; // Suffix annotation
let default_float = 3.0; // f64
let default_integer = 7; // i32
let mut inferred_type = 12; // Type i164 is inferred from another line
inferred_type = 4294978697i64;
let mut mut... |
// 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.
#![cfg(test)]
use {
difference::assert_diff,
failure::{bail, format_err, Error},
fdio::{SpawnAction, SpawnOptions},
fidl_fuchsia_sys::Comp... |
pub const VIP_START: u32 = 0x00000000;
pub const VIP_LENGTH: u32 = 0x01000000;
pub const VIP_END: u32 = VIP_START + VIP_LENGTH - 1;
pub const VSU_START: u32 = 0x01000000;
pub const VSU_LENGTH: u32 = 0x01000000;
pub const VSU_END: u32 = VSU_START + VSU_LENGTH - 1;
pub const LINK_CONTROL_REG: u32 = 0x02000000;
pub cons... |
fn main(){
let a = [1,2,3,4,5,6,7,8,9,10];
let mut index = 0;
while index<5 {
println!("{}",a[index]);
index +=1;
}
} |
// Copyright 2021 Datafuse Labs.
//
// 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 ... |
use yew::prelude::*;
use yew_router::prelude::*;
// use yew_router::components::RouterAnchor;
use yew::services::{
ConsoleService,
storage::{ StorageService, Area },
};
use yew::format::{ Json };
// use yewdux::prelude::*;
use yewdux::prelude::WithDispatch;
use yewdux::dispatch::Dispatcher;
use yewtil::NeqAssig... |
//! ```elixir
//! # label 2
//! # pushed to stack: (before)
//! # returned from call: value
//! # full stack: (value, before)
//! # returns: after
//! after = :erlang.monotonic_time()
//! duration = after - before
//! time = :erlang.convert_time_unit(duration, :native, :microsecond)
//! {time, value}
//! ```
use liblu... |
use std::cmp::{min, max};
use std::collections::{HashMap, HashSet, VecDeque};
use std::cmp::Reverse;
use itertools::Itertools;
use whiteread::parse_line;
const ten97: usize = 1000000007;
fn alphabet2idx(c: char) -> usize {
if c.is_ascii_lowercase() {
c as u8 as usize - 'a' as u8 as usize
} else if c.i... |
use error::*;
use std::{ops::Range, ptr::NonNull};
/// Trait for memory allocation and mapping.
pub trait Device: Sized {
/// Memory type that can be used with this device.
type Memory: 'static;
/// Allocate memory object.
///
/// # Parameters
/// `size` - size of the memory object to allocat... |
#[derive(Debug, Clone)]
pub struct StatementPart (pub String);
#[derive(Debug, Clone)]
pub enum Statement {
MacroCall(String),
Normal(Vec<StatementPart>)
}
#[derive(Debug)]
pub enum Expression {
Statement(Statement),
MacroDefinition(String, Vec<Statement>)
} |
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let mut fin = String::from("");
// first arg is the name of the program so skip it
for arg in args.iter().skip(1) {
for (i, c) in arg.chars().enumerate() {
if i % 2 == 0 {
let a = c.to_string()... |
fn main() {
let fname = "Agus ";
let lname = "Susilo";
let full_name = format!("{}{}", fname, lname);
println!("{}", full_name);
println!("{}", hello());
}
fn hello() -> String {
let fname = "Agus ";
let lname = "Susilo";
format!("{}{}", fname, lname)
} |
use rand::prelude::*;
use std::convert::TryInto;
use std::fmt;
use uuid::Uuid;
/// Somebody who tries to hail a `Taxi` will issue a `Request`.
/// A `Request` is therefore represents somebody's desire to be picked up by a `Taxi`.
/// It has a `max_lifetime` which expires the `Request` as if it timed out because it did... |
use std::cmp::{max, min};
use std::collections::HashMap;
use std::convert::From;
use std::ops::{Add, AddAssign};
#[macro_use]
extern crate num_derive;
use aoc2019::aoc_input::get_input;
use aoc2019::intcode::*;
use num_traits::{FromPrimitive, ToPrimitive};
#[derive(Debug, Copy, Clone, PartialEq, Eq, FromPrimitive, ToP... |
use crate::prelude::*;
use std::os::raw::c_void;
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkWin32SurfaceCreateInfoKHR {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub flags: VkWin32SurfaceCreateFlagBitsKHR,
pub hinstance: *mut c_void,
pub hwnd: *mut c_void,
}
impl VkWin32Su... |
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... |
//! Platform-specific types are required to implement the following traits.
use std::fmt::Debug;
use std::rc::Rc;
use num_traits::identities::Zero;
use uom::si::time::{day, hour};
use crate::units::{Bound, ElectricPotential, Energy, Power, Ratio, ThermodynamicTemperature, Time};
use crate::{Result, State, Technology... |
#![cfg_attr(not(test), no_std)]
#![cfg_attr(all(feature = "nightly"), feature(allow_internal_unstable, macro_vis_matcher))]
#![forbid(missing_docs)]
//! A library for defining enums that can be used in compact bit sets. It supports enums up to 128
//! variants, and has a macro to use these sets in constants.
//!
//! #... |
#[cfg(feature = "tokio")]
#[path="simple_daemon_tokio/mod.rs"]
mod simple_daemon_impl;
#[cfg(feature = "tokio-core")]
#[path="simple_daemon_tokio_core/mod.rs"]
mod simple_daemon_impl;
fn main() {
simple_daemon_impl::main()
}
|
use core::{
fmt,
ops::{BitAnd, BitOr, BitXor, Not},
};
use crate::{
iter,
parser::{ParseError, ParseHex, WriteHex},
};
/// Metadata for an individual flag.
pub struct Flag<B> {
name: &'static str,
value: B,
}
impl<B> Flag<B> {
/// Create a new flag with the given name and value.
pub c... |
use std::collections::BTreeSet;
use join::Join;
use proconio::input;
fn main() {
input! {
n: usize,
k: usize,
};
if n / 2 < k {
println!("-1");
return;
}
let mut ans = Vec::new();
let mut set = BTreeSet::new();
for i in (k + 1)..=n {
set.insert(i);... |
use std::collections::HashSet;
fn main() {
let input = include_str!("input.txt");
println!("{}", thingy_day2(&frequencies_from_string(&input)))
}
fn frequencies_from_string(freq_string: &str) -> Vec<i32> {
let thing = freq_string.lines().map(|s| s.parse().unwrap()).collect::<Vec<i32>>();
thing
}
fn t... |
//! Handles all REST endpoints
use actix_web::web::ServiceConfig;
use chrono;
use futures_cpupool::CpuPool;
use handlebars;
use handlebars::Handlebars;
use hyper_tls::HttpsConnector;
use serde::Deserialize;
use serde_json;
use std::sync::Arc;
use crate::db;
mod api;
mod auth;
mod github_login;
mod logger;
mod stati... |
use super::transact::{TransactionConcurrency, TransactionIsolation};
pub(crate) const DEFAULT_TX_TIMEOUT: usize = 0_usize;
pub(crate) const DEFAULT_TX_SERIALIZABLE_ENABLED: bool = false;
pub(crate) const DEFAULT_TX_CONCURRENCY: TransactionConcurrency =
TransactionConcurrency::Pessimistic;
pub(crate) const DEFAULT_... |
//! rootrenderingcomponent.rs - renders the web page
//region: use, const
use crate::divcardmoniker;
use crate::divfordebugging;
use crate::divgridcontainer;
use crate::divplayeractions;
use crate::divplayersandscores;
use crate::divrulesanddescription;
use crate::gamedata::GameData;
//use crate::logmod;
use dodrio::... |
fn main() {
println!("Documents were generated at compile time. Look into project outputs 'book' directory!");
open::that(
concat!(env!("CARGO_MANIFEST_DIR"), "/target/book/index.html")
).expect("Should have opened documentation in web browser!");
} |
use crate::{
builtins::PyIntRef, function::OptionalArg, sliceable::SequenceIndexOp, types::PyComparisonOp,
vm::VirtualMachine, AsObject, PyObject, PyObjectRef, PyResult,
};
use optional::Optioned;
use std::ops::Range;
pub trait MutObjectSequenceOp {
type Guard<'a>: 'a;
fn do_get<'a>(index: usize, guar... |
use winnow::prelude::*;
mod parser;
mod parser_str;
fn main() -> Result<(), lexopt::Error> {
let args = Args::parse()?;
let input = args.input.as_deref().unwrap_or("1 + 1");
if args.binary {
match parser::categories.parse(input.as_bytes()) {
Ok(result) => {
println!("... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.