text stringlengths 8 4.13M |
|---|
//! # RedisRs
//! A simple redis client library
//! This library revolves around the Connection struct.
//! Every request is sent via Connection methods.
//! Requests can also be sent using the `send_raw_request` function.
//! Examples
//! Create a connection and send requests
//!```
//! extern crate redis_rs;
//! use... |
use std::convert::Infallible;
use juniper::graphql_object;
struct Query;
#[graphql_object]
impl Query {
fn ping() -> Result<bool, Infallible> {
Ok(false)
}
}
|
use aoc2018::*;
struct Recipe {
pub data: Vec<usize>,
a: usize,
b: usize,
}
impl Recipe {
fn new() -> Self {
let mut data = Vec::new();
data.push(3);
data.push(7);
Recipe { data, a: 0, b: 1 }
}
fn make(&mut self) -> usize {
let a = self.a;
let ... |
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
pub enum Command {
/// Query the Vault database
Query {
/// Extract fastqs
#[structopt(short,long, parse(from_os_str))]
extract: Option<PathBuf>,
/// Create samplesheet from results. Format depends o... |
pub mod algorithms;
mod among;
mod snowball_env;
pub use snowball::among::Among;
pub use snowball::snowball_env::SnowballEnv;
|
extern crate json;
use algo_tools::load_json_tests;
struct Solution;
impl Solution {
pub fn find_peak_element(nums: Vec<i32>) -> i32 {
let len = nums.len();
let mut left : usize = 0;
let mut right : usize = len - 1;
if (len < 2) || (nums[0] > nums[1]) {
return 0;
... |
use crate::gl_wrapper::fbo::{FBO, DepthStencilTarget};
use crate::gl_wrapper::texture_2d::Texture2D;
use crate::gl_wrapper::rbo::RBO;
use crate::containers::CONTAINER;
use crate::shaders::post_processing::{KernelShader, GaussianBlurShader};
use crate::shapes::PredefinedShapes;
use crate::gl_wrapper::TextureFormat;
pub... |
use std::fmt;
use std::collections::HashSet;
// strum::IntoEnumIterator is required for EnumIter, but produces unused import warning
#[allow(unused_imports)]
use strum::IntoEnumIterator;
use strum_macros::EnumIter;
/// Color is one of the intrisic parts of the game of Magic. This enum is used to designate
/// a sing... |
use std::{collections::BTreeMap, str::FromStr};
use mysql::chrono::{NaiveDate};
use mysql_common::bigdecimal::BigDecimal;
use crate::timeseries::TimeSeries;
pub struct AlphaVantage {
key: String,
}
impl AlphaVantage {
pub fn with_key(key: &str) -> Self {
AlphaVantage {
key: String::from_... |
use {
crate::controls::CameraRotation,
derive_new::new,
rough::{
amethyst::{
controls::{HideCursor, WindowFocus},
core::{ecs::prelude::*, timing::Time, transform::Transform, ParentHierarchy},
derive::SystemDesc,
renderer::Camera,
},
mat... |
fn main() {
println!("{} {}", say_hello("me"), say_hello("you"));
}
pub fn say_hello(name: &str) -> String {
let message = format!("hello, {}!", name);
message
}
|
// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! Structs for reading and writing manifests of flash boot stage images.
//!
//! Note: The structs below must match the definitions in
//! sw/device/silicon_creator/lib... |
use anyhow::{bail, Context};
use itertools::{Itertools, MinMaxResult};
const INPUT: &str = include_str!("input.txt");
fn part1(values: &[usize]) -> anyhow::Result<usize> {
let result = values
.iter()
.enumerate()
.skip(25)
.map(|(i, &x)| (&values[i - 25..i], x))
.find(|&(pr... |
use std::ops::Not;
pub type CartId = String;
pub type ItemId = String;
pub type Quantity = u32;
pub type OrderId = String;
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub enum CartCommand {
Create {
cart_id: CartId,
},
Cancel {
cart_id: CartId,
},
ChangeQty {
cart_id: Cart... |
mod lib;
use lib::readcsv;
fn main() {
let r = readcsv("1.csv");
println!("{:?}", r);
}
|
mod tests {
use test::Bencher;
#[bench]
fn bench_add1(b : &mut Bencher) {
b.iter(|| {
let mut res = 0i32;
for _ in (0..2000) {
match res {
-1 => {}
x if x < 1000 => res += 1,
_ => res = -... |
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::DSLPPWRCFG {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&... |
pub fn dec_ith(decnum: i32, i: i32) -> u8 {
return ((decnum % (10_i32.pow(i as u32))) / 10_i32.pow((i - 1) as u32)) as u8;
}
pub fn bitstring_to_i32(bitstr: &str) -> i32 {
let mut num: i32 = 0;
for (i, bitchar) in bitstr.chars().enumerate() {
if bitchar == '1' {
num |= 1 << (bitstr.len(... |
use std::env;
use std::fmt::Display;
use std::fs;
use std::io;
use std::io::{BufRead, BufReader};
use std::mem;
use std::os::unix::io::AsRawFd;
use std::ptr;
use std::str;
use crate::kb::Key;
use crate::term::Term;
pub use crate::common_term::*;
pub const DEFAULT_WIDTH: u16 = 80;
#[inline]
pub fn is_a_terminal(out:... |
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... |
extern crate json;
use algo_tools::load_json_tests;
struct Solution;
// impl Solution {
// pub fn eval_rpn(tokens: Vec<String>) -> i32 {
// let mut numbers = Vec::new();
// let mut res = tokens[0].parse::<i32>().unwrap();
// for token in tokens[1..].iter() {
// match token.as_... |
use std::backtrace::Backtrace;
use std::fmt::{Debug, Display};
use std::hash::Hash;
use std::sync::Arc;
use liblumen_term::Tag;
use crate::erts::term::prelude::*;
pub trait Repr:
Sized + Copy + Debug + Display + PartialEq<Self> + Eq + PartialOrd<Self> + Ord + Hash + Send
{
type Encoding: liblumen_term::Encod... |
use std::env;
use std::fs::File;
use std::io;
use std::io::Read;
use std::io::Write;
use crc::crc32;
const FORMAT: &[u8] = b"BPS1";
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 4 {
println!("usage: beatr <patch> <original> <output>");
}
let patch: Vec<u8> = slu... |
extern crate proc_macro;
use proc_macro::TokenStream;
#[proc_macro_attribute]
pub fn command(attr: TokenStream, item: TokenStream) -> TokenStream {
println!("{}", attr);
println!("{}", item);
item
} |
use crate::metrics::{handle_time, Scoped, Stats};
use futures::{future, try_ready, Future, Poll};
use http::{Request, Response};
use linkerd2_proxy_transport::tls;
use std::marker::PhantomData;
use tower::retry as tower_retry;
pub use tower::retry::budget::Budget;
use tracing::trace;
pub trait CanRetry {
type Retr... |
// Copyright 2019, The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... |
mod with_atom_class;
use proptest::prop_assert_eq;
use liblumen_alloc::atom;
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::term::prelude::*;
use crate::erlang::raise_3::result;
use crate::test::strategy;
#[test]
fn without_atom_class_errors_badarg() {
run!(
|arc_process| {
(... |
use std::fmt;
use serde::de::{SeqAccess, Visitor};
use serde::ser::SerializeTuple;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Debug, PartialEq)]
pub struct Varuint32(u32);
impl Serialize for Varuint32 {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
... |
use crate::{
component::UserInterfaceView,
resource::{ApplicationData, UserInterfaceRes},
};
use core::{
app::AppLifeCycle,
ecs::{Join, Read, ReadExpect, System, Write, WriteStorage},
};
use input::resource::{InputController, TriggerState};
use raui_core::{
application::Application,
interactive:... |
use std::env;
use std::fs::{self, File};
use std::io;
use std::io::prelude::*;
use std::path::Path;
use toml::Value;
use crate::cmd::call;
use crate::error::FatalError;
use crate::Features;
fn cargo() -> String {
env::var("CARGO").unwrap_or_else(|_| "cargo".to_owned())
}
pub fn publish(
dry_run: bool,
m... |
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub enum TouchPhase {
Start,
Move,
End,
Cancel,
}
impl From<winit::event::TouchPhase> for TouchPhase {
fn from(phase: winit::event::TouchPhase) -> Self {
match phase {
winit::event::TouchPhase::Started => TouchPhase::Start,
... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type IJsonValue = *mut ::core::ffi::c_void;
pub type JsonArray = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct JsonErrorStatus(pub i32);
impl Js... |
use crate::Edge;
pub struct DirectedGraph<V> {
vertices: Vec<Vertex<V>>,
edges: usize,
}
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
struct Vertex<V> {
incoming: Vec<Edge<usize>>,
outgoing: Vec<Edge<usize>>,
data: V,
}
impl<V> DirectedGraph<V> {
pub fn new... |
// actor/player.rs
use std::cmp::Ordering;
#[derive(Eq)]
pub struct Player {
pub name: String,
pub money: i32,
pub knowledge: i32,
pub tiles: Vec<usize>,
pub skip_one_turn: bool,
pub still_playing: bool,
pub is_computer: bool,
}
impl PartialEq for Player {
fn eq(&self, other: &Player)... |
use std::io;
use std::iter;
fn rpt
fn main(){
let reader = io::stdin();
let rpt = iter::repeat;
let mut ip = String::new();
reader.read_line(&mut ip);
let n = ip.trim().parse();
for i in (1..n) {
println!(rpt("*"));
}
} |
// Copyright 2015 Jerome Rasky <jerome@rasky.co>
//
// 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... |
pub struct Lehmer64 {
value: u128,
}
impl Lehmer64 {
pub fn new() -> Lehmer64 {
let res = Lehmer64 {
value: unsafe { core::arch::x86_64::_rdtsc() } as u128,
};
res
}
pub fn rand(&mut self) -> usize {
self.value = unsafe { std::intrinsics::unchecked_mul(self... |
// 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 {
failure::Error,
fidl_fuchsia_io::DirectoryProxy,
fidl_fuchsia_space::{
ErrorCode as SpaceErrorCode, ManagerRequest as SpaceManage... |
//! Widget and data binding utilities
use crate::prelude::WidgetData;
pub mod decorator;
pub mod wrapper;
/// Helper type to contain bound data and data changed callback.
pub struct WidgetDataHolder<W, D = ()>
where
D: WidgetData,
{
pub data: D,
pub last_version: D::Version,
pub on_data_changed: fn(&... |
use procon_reader::ProconReader;
use std::cmp::Ordering;
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let t: usize = rd.get();
for _ in 0..t {
let k: u64 = rd.get();
solve(k);
}
}
fn solve(k: u64) {
let mut diag = 1;
for x in 1.. ... |
//! Repositories under http://github.com/lumen that have Erlang code that needs to be tested to be
//! compiled with `lumen` and `liblumen_otp` BIFs.
#[path = "lumen/otp.rs"]
mod otp;
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 ... |
extern crate serde_json;
use datamodel_parser::RootTypes;
pub struct JSONFormatterOptions {
pub pretty: bool,
}
pub fn format(
options: JSONFormatterOptions,
types: Vec<RootTypes>,
) -> Result<String, String> {
if options.pretty {
match serde_json::to_string_pretty(&types) {
Ok(f)... |
#[cfg_attr(rustfmt, rustfmt_skip)]
#[allow(unknown_lints)]
#[allow(clippy)]
mod grammar;
/// Contains all structures related to the AST for the WebIDL grammar.
pub mod ast;
/// Contains the visitor trait needed to traverse the AST and helper walk functions.
pub mod visitor;
pub use lalrpop_util::ParseError;
use lex... |
use crate::PubComId;
use std::collections::HashSet;
use toml::Value;
static VALUE_MISSING: &str = "value is missing";
static VALUE_TYPEERROR: &str = "value is not of type Integer";
static SPOTS_MISSING: &str = "spots is missing";
static SPOTS_TYPEERROR: &str = "spots is not of type Integer";
static VALUES_MISSING: &st... |
use tui::{buffer::Buffer, layout::Rect, widgets::Widget};
pub struct Clear<T: Widget>(T);
impl<T: Widget> Clear<T> {
pub fn new(w: T) -> Self {
Self(w)
}
}
impl<T: Widget> Widget for Clear<T> {
fn draw(&mut self, area: Rect, buf: &mut Buffer) {
if area.width < 2 || area.height < 2 {
... |
/**
* Copyright ยฉ 2019
* Sami Shalayel <sami.shalayel@tutamail.com>,
* Carl Schwan <carl@carlschwan.eu>,
* Daniel Freiermuth <d_freiermu14@cs.uni-kl.de>
*
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published... |
// This is the file that gets imported when using 'mod world;'
// re-export modules so they are visible to modules using this one.
pub mod geometry;
pub mod items;
pub mod world; |
#![feature(nll)]
#![feature(integer_atomics)]
extern crate gtk;
#[macro_use]
extern crate relm;
#[macro_use]
extern crate relm_derive;
extern crate crossbeam_channel;
#[macro_use]
extern crate failure;
extern crate packt_core;
extern crate tokio;
extern crate tokio_core;
extern crate tokio_io;
extern crate tokio_proce... |
extern crate rand;
use go::GoGame;
use mcts::Controller;
use std::collections;
use go::Stone;
use go::Vertex;
extern crate time;
pub struct Engine {
game: GoGame,
controller: Controller,
rng: rand::StdRng,
commands: collections::HashMap<String, fn(&mut Engine, Vec<&str>) -> Result<String, String> >,
analyze... |
// Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... |
fn main() {
// mut
let mut mutability = 32; // mut : ๋ณ์์ ๋ณํ
println!("The value of mutability : {}", mutability);
mutability = 6;
println!("The value of mutability : {}", mutability);
println!("");
// const
/*
์์, immutable ๋ณ์์ ์ฐจ์ด์
์์ : variable shadowing ๋ถ๊ฐ๋ฅ
let a ... |
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
impl super::INPUT {
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
}
#[doc = r" Value of the field"]
pub struct AIN0R {
bits: ... |
use std::collections::BTreeMap;
pub fn solve(input: Vec<&str>, result: i32) {
let number: Vec<i32> = input.iter().map(|x| x.parse().unwrap()).collect();
part1(&number, result);
part2(&number, result);
}
fn part1(list: &Vec<i32>, result: i32) {
for i in list.iter() {
for j in list.iter() {
... |
//! Port controller (PIO)
//!
//! Size: 1K
//!
//! PxY_Select variants mapped to alt functions:
//! * 000 (U0): input
//! * 001 (U1): output
//! * 010 (U2): AF0
//! * 011 (U3): AF1
//! * 100 (U4): AF2
//! * 101 (U5): AF3
//! * 110 (U6): AF4
//! * 111 (U7): disabled
use core::marker::PhantomData;
use co... |
extern crate rayon;
extern crate clap;
extern crate atty;
extern crate regex;
extern crate grusp_core;
pub mod args;
use rayon::prelude::*;
use std::path::PathBuf;
use std::io::BufReader;
use std::fs::File;
use std::io::stdin;
use grusp_core::grusp;
fn main() {
let opts = match args::get_opts() {
Ok(o) =... |
use std::collections::{HashMap, HashSet};
use std::iter::FromIterator;
use std::str;
/* Mirror the product(repeat=n) iter from Python itertools
https://github.com/python/cpython/blob/234531b4462b20d668762bd78406fd2ebab129c9/Modules/itertoolsmodule.c#L2095
https://dev.to/naufraghi/procedural-macro-in-rust-101-k... |
#![allow(dead_code)]
#![allow(unused_imports)]
use crate::traits::{ReadoutError, ShellFormat};
use crate::extra;
use std::io::Error;
use std::path::Path;
use std::process::{Command, Stdio};
use std::{env, fs};
use std::{ffi::CStr, path::PathBuf};
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "andro... |
use std::io::Write;
use std::time::Instant;
use compresstimator::Compresstimator;
fn main() -> std::io::Result<()> {
let estimator = Compresstimator::default();
for path in std::env::args_os().skip(1) {
let path = std::path::PathBuf::from(path);
print!("{}\t", path.display());
let s... |
// 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 ... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::headblock_pacemaker::HeadBlockPacemaker;
use crate::ondemand_pacemaker::OndemandPacemaker;
use crate::schedule_pacemaker::SchedulePacemaker;
use crate::stratum::mint;
use actix::prelude::*;
use anyhow::Result;
use bus::Bu... |
use std::io::BufRead;
use rand::Rng;
type yao6 = Vec<u8>;
fn main() {
// let res=coin_divinate();
let res = dayanshi_divinate("").0;
println!("{:?}", res)
}
pub fn coin_divinate(event:&str) -> yao6 {
let mut rng = rand::thread_rng();
let mut res_vec: Vec<u8> = Vec::new();
for times in 0..6 ... |
use std::{borrow::BorrowMut, sync::mpsc::TryRecvError, time::Duration};
use actyx_sdk::service::EventService;
use tello::{command_mode::CommandModeState, odometry::Odometry, CommandMode, Drone};
use tokio::time::sleep;
use crate::twins::{
drone_twin::DroneTwin,
mission_twin::types::{DelayWaypoint, GoToWaypoin... |
extern crate log;
extern crate simplelog;
use simplelog::*;
use std::fs::File;
pub fn logger(logfile: &str) {
CombinedLogger::init(vec![
TermLogger::new(LevelFilter::Debug, Config::default(), TerminalMode::Mixed).unwrap(),
WriteLogger::new(
LevelFilter::Info,
Config::defaul... |
extern crate hex;
extern crate rand;
extern crate rayon;
use algebra::fields::mnt6753::Fr as MNT6753Fr;
use algebra::fields::mnt4753::Fr as MNT4753Fr;
use algebra::{PrimeField, MulShort};
use std::marker::PhantomData;
use crate::crh::{
FieldBasedHashParameters, poseidon::{
parameters::{MNT4753PoseidonPar... |
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "cache")]
pub struct Model {
#[sea_orm(primary_key)]
#[serde(skip_deserializing)]
pub id: i32,
#[sea_orm(unique)]
pub path: String,
pub ... |
use crate::tokenizer::TokenType;
#[derive(Debug, Clone)]
pub struct Identifier {
pub name: String,
pub range: (usize, usize)
}
#[derive(Debug, Clone)]
pub struct Literal {
pub value: String,
pub raw_value: String,
pub range: (usize, usize)
}
impl Literal {
pub fn new() -> Self {
Self ... |
use std::fmt::{self, Display};
use crate::ast::{BinOp, Expression, LValue, Program, Statement, UnaryOp};
#[derive(Debug, Clone)]
pub enum Operand {
Literal(String),
Variable(String),
}
impl Display for Operand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
O... |
// Copyright 2016 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... |
//! Implementation of `errno` functionality for WASI.
//!
//! Adapted from `unix.rs`.
// 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 o... |
// 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.
mod data; // Inspect data maintainer/updater/scanner-from-vmo; compare engine
mod metrics; // Evaluates memory performance of Inspect library
mod puppet; /... |
use std::io::prelude::*;
fn main() {
let schema = schemars::schema_for!(trycmd::schema::OneShot);
let schema = serde_json::to_string_pretty(&schema).unwrap();
std::io::stdout().write_all(schema.as_bytes()).unwrap();
}
|
use std::time::Instant;
extern crate rustypawn;
use rustypawn::Game;
use rustypawn::millis_since;
fn perft_sub(game: &mut Game, depth: usize) -> usize {
if depth == 0 {
return 1;
}
let move_list = game.generate_moves();
let mut result = 0;
for mv in move_list {
if game.make_move(... |
#![feature(async_closure)]
mod entrypoint;
pub use entrypoint::entrypoint;
|
use std::{fs, slice};
use ve_shader_reflect::*;
fn main() {
let path = format!(
"{}/examples/shaders/gpass_simple_frag.spv",
env!("CARGO_MANIFEST_DIR")
);
let spv = fs::read(path).unwrap();
let info = ve_shader_reflect::reflect_shader(unsafe {
slice::from_raw_parts(spv.as_ptr()... |
pub mod ping;
pub mod about;
// pub mod imageboard;
pub mod vend;
pub mod eightball;
pub mod thesevoices; |
//match if let loop while break continue return if for
fn hoge(m:isize){
match m {
0 => println!("0"),
1...10=> println!("small number!"),
n => println!("too big : {}",n)
}
match (0.0,100){
(0.0,0) => println!("all zeros"),
(f,0...10) => println!("float {} with small... |
#[derive(Debug)]
pub struct Bitfield {
pub bf: Vec<u8>,
}
impl Bitfield {
/// returns true if the bitfield has item at location x
pub fn has(&self, x: usize) -> bool {
if self.bf.len() == 0 || self.bf.len() * 8 < x {
return false;
}
let i = x / 8;
let j = 7 - x ... |
use std::io::{self, BufRead};
fn main() {
let mut valid_count = 0;
for line in io::stdin().lock().lines() {
let line = line.expect("Line to be readable");
let mut space_split = line.split(" ");
match (space_split.next(), space_split.next(), space_split.next()) {
(Some(coun... |
use std::collections::HashSet;
pub fn primes_up_to(upper_bound: u64) -> Vec<u64> {
const NOT_PRIME: u64 = 0;
let mut nums: Vec<u64> = (2..=upper_bound).collect();
(0..nums.len())
.filter_map(|i| {
let prime: u64 = nums[i];
if prime == NOT_PRIME {
return None;... |
use std::mem;
use crate::bindings::tflite as bindings;
use crate::interpreter::op_resolver::OpResolver;
use std::ffi::c_void;
cpp! {{
#include "tensorflow/lite/kernels/register.h"
using namespace tflite::ops::builtin;
}}
pub struct Resolver {
handle: Box<bindings::OpResolver>,
}
impl Resolver {
pub... |
//! ```elixir
//! # label 4
//! # pushed to stack: (document, parent, old_child)
//! # returned form call: :ok
//! # full stack: (:ok, document, parent, old_child)
//! # returns: {:ok, new_child}
//! {:ok, new_child} = Lumen.Web.Document.create_element(document, "ul");
//! {:ok, replaced_child} = Lumen.Web.replace_chil... |
// 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 std::mem::size_of;
#[allow(dead_code)]
struct S {
a: u64,
b: u64,
c: u64,
d: u64,
}
fn main() {
println!("{}", size_of::<u32>()); // 4
println!("{}", size_of::<u64>()); // 8
println!("{}", size_of::<Option<u32>>()); // 8
println!("{}", size_of::<Option<u64>>()); // 16
println!... |
pub mod zstd_proto_graph;
pub use zstd_proto_graph::{
GraphDescriptionSerializer,
GraphDescriptionSerializerError,
IdentifiedGraphSerializer,
IdentifiedGraphSerializerError,
MergedGraphSerializer,
MergedGraphSerializerError,
};
|
use crate::columns::{
CellDelegate, CellRenderExt, HeaderCell, ProvidedColumns, TableColumn, TextCell,
};
use crate::axis_measure::{AxisMeasure, AxisPair, LogIdx, TableAxis};
use crate::config::TableConfig;
use crate::data::{IndexedData, IndexedItems};
use crate::headings::{HeadersFromIndices, SuppliedHeaders};
us... |
use super::math::vector::Vec2;
#[allow(dead_code)]
pub struct Map {
pub height: i32,
pub width: i32,
pub stride:i32,
pub values: Vec<u8>,
}
impl Map {
pub fn _dimensions(&self) -> Vec2<i32> {
let res = Vec2{x:self.width, y:self.height};
res
}
pub fn index(map:&Map, v:(i32,i... |
#![feature(alloc)]
use std::boxed;
use std::thread;
use std::sync::mpsc::channel;
struct Data {
values: [usize; 512]
}
fn main() {
let count = 10000000;
let (tx, rx) = channel();//2^20);
let threads = 1;
for _ in 0..threads {
let tx = tx.clone();
thread::spawn(move || {
... |
pub mod forget_password;
pub mod home;
pub mod login;
pub mod register;
|
extern crate futures;
extern crate tempdir;
extern crate tokio_fs;
use futures::{Future, Stream};
use std::fs;
use std::sync::{Arc, Mutex};
use tempdir::TempDir;
use tokio_fs::*;
mod pool;
#[test]
fn create() {
let base_dir = TempDir::new("base").unwrap();
let new_dir = base_dir.path().join("foo");
pool... |
#[doc = "Reader of register SCSR"]
pub type R = crate::R<u32, super::SCSR>;
#[doc = "Reader of field `DA`"]
pub type DA_R = crate::R<bool, bool>;
#[doc = "Reader of field `RREQ`"]
pub type RREQ_R = crate::R<bool, bool>;
#[doc = "Reader of field `TREQ`"]
pub type TREQ_R = crate::R<bool, bool>;
#[doc = "Reader of field `... |
// Copyright 2023 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 super::*;
use std::iter::FusedIterator;
///////////////////////////////////////////////////////////////////////////////
/// An iterator which receives the values sent through the channel,
/// blocking until a value is received.
///
/// If the channel is disconnected this will return None without blocking.
pub st... |
use std::collections::BTreeMap;
use std::fs;
struct Instruction {
name: String,
value: i32,
done: bool,
}
impl Clone for Instruction {
fn clone(&self) -> Instruction {
Instruction {
name: self.name.clone(),
value: self.value,
done: self.done,
}
}... |
// 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 std::env;
fn main() {
let mut sum = 0;
for input in env::args() {
let _i = match input.parse::<i32>() {
Ok(_i) => {
sum += _i
},
Err(_e) => {
println!("{}: Not a valid integer!", input)
}
};
println!("S... |
// Copyright 2020-2021, The Tremor Team
//
// 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 agr... |
pub fn hello_box() {
box_demo();
cons_in_rust();
}
fn box_demo() {
let b = Box::new(5);
println!("b = {}", b);
}
enum List {
Cons(i32, Box<List>),
Nil,
}
fn cons_in_rust() {
let list = List::Cons(
1,
Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil))))),
... |
pub fn example12()
{
let sum_nums = |x: i32, y: i32| x + y;
xprintln!("7 + 8 = {}", sum_nums(7, 8));
let num_ten = 10;
let add_ten = |x: i32| x + num_ten;
xprintln!("5 + 10 = {}", add_ten(5));
} |
use gcd::Gcd;
use num::traits::PrimInt;
#[derive(Clone, Copy, Debug)]
pub struct Fraction<Int> {
num: Int,
den: Int,
}
impl<Int> Fraction<Int>
where
Int: PrimInt,
{
pub fn new(num: Int, den: Int) -> Self {
Self { num: num, den: den }
}
pub fn num(&self) -> Int {
self.num
}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.