text stringlengths 8 4.13M |
|---|
//! Iterators over various module-level objects
use crate::llvm_sys::*;
use std::iter::Peekable;
pub fn get_defined_functions(module: LLVMModuleRef) -> impl Iterator<Item = LLVMValueRef> {
FunctionIterator::new(module).filter(|&f| is_defined(f))
}
pub fn get_declared_functions(module: LLVMModuleRef) -> impl Iter... |
#[macro_use]
extern crate serenity;
extern crate chrono;
extern crate rand;
extern crate time;
#[macro_use(object)] extern crate json;
use std::string::*;
use serenity::model::*;
use serenity::Result as SerenityResult;
use serenity::Client;
use serenity::framework::standard::help_commands;
use serenity::framework::St... |
use std::fs::File;
use std::error::Error;
use std::io::Read;
//use std::io::ErrorKind;
fn main() -> Result<(), Box<dyn Error>> {
let mut s = String::new();
File::open("hello.txt")?.read_to_string(&mut s)?;
Ok(())
/*
let f = File::open("hello.txt");
let f = match f {
Ok(file) => fi... |
//! Roundtrip (write-read) tests for supported LAS versions and attributes.
extern crate chrono;
extern crate las;
extern crate uuid;
use las::{Builder, Point, Read, Reader, Write, Writer};
use std::io::Cursor;
pub fn roundtrip(builder: Builder, point: &Point, should_succeed: bool) {
let header = if should_succe... |
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use rand::{thread_rng, Rng};
use super::models::Event;
pub fn abs(x: i32) -> i32 {
if x >= 0 { x } else { -x }
}
pub fn get_new_event_position(new_event: &Event, events: &Vec<Event>) -> usize {
for i in 0..events.len() {
if... |
use std::collections::HashSet;
fn read_line() -> String {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim_end().to_owned()
}
fn main() {
let n = read_line().parse().unwrap();
let solver = Solver::new(n);
let stdout = solver.solve();
stdout.iter().for... |
use std::process::Command;
use std::str;
use date;
//get username from text data
pub fn get_username(text: &str) -> String {
let text_split: Vec<&str> = text.split('=').collect();
//espace directory traversal
let username_split: Vec<&str> = text_split[1].split(' ').collect();
let username_str = userna... |
use crate::renders::{Error, Spinner};
use crate::types::Product;
use spair::prelude::*;
pub struct Home {
pub all_products: Vec<Product>,
pub parent_comp: spair::Comp<crate::App>,
pub error_message: Option<spair::FetchError>,
}
impl Home {
pub fn fetch_all_products(&mut self) -> spair::Command<Self> {... |
use crate::event::Event;
use crate::glue::{self, libevdev, libevdev_uinput};
use std::fs::{File, OpenOptions};
use std::io::{Error, ErrorKind};
use std::mem::MaybeUninit;
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::AsRawFd;
use std::path::Path;
use tokio::io::unix::AsyncFd;
pub(crate) struct EventRea... |
use libsdp::*;
#[test]
fn parse() {
let data = "v=0\r
o=bytebuddha 1303 2598 IN IP4 10.1.10.120\r
s=Talk\r
c=IN IP4 10.1.10.120\r
t=0 0\r
m=audio 7078 RTP/AVP 124 111 110 0 8 101\r
a=rtpmap:124 opus/48000\r
a=fmtp:124 useinbandfec=1; usedtx=1\r
a=rtpmap:111 speex/16000\r
a=fmtp:111 vbr=on\r
a=rtpmap:110 speex/8000... |
// Wicci Shim Module
// Utilities for generating HTML code for debugging & error reporting
// --> Regular HTML should come from the database!
// #![plugin(regex_macros)]
// fn foo() {
// let x:() = regex::new("");
// }
use regex::Regex;
lazy_static! {
pub static ref HTML_ID: Regex = Regex::new(r"^[[:alpha:]]+... |
use std::sync::Mutex;
use ::iot::*;
use actix_web::{get, web, App, HttpResponse, HttpServer, Responder};
use askama::Template;
use awc::Client;
use iot::index::Index;
use serde::Deserialize;
#[derive(Default)]
struct Value {
value: Mutex<u32>,
}
#[derive(Deserialize)]
struct UpdateValue {
value: u32,
}
#[de... |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use core::convert::Infallible;
use core::fmt;
use core::ptr;
use core::str::FromStr;
use std::colle... |
//! Future-aware client for consul
//!
//! This library is an client for consul that gives you stream of changes
//! done in consul
#![deny(missing_docs, missing_debug_implementations, warnings)]
extern crate hyper;
extern crate hyper_tls;
#[macro_use] extern crate log;
extern crate futures;
extern crate native_tls;
... |
use crate::api::*;
use crate::configuration::BenchmarkIds;
use lazy_static::*;
use std::collections::HashMap;
use std::str::FromStr;
fn s(text: &str) -> String {
String::from_str(text).unwrap()
}
fn categorize_ids() -> BenchmarkIds {
let mut ids = BenchmarkIds {
ok: vec![],
ko: vec![],
};
... |
use crate::error::Result;
use crate::operation::OpAdd;
use crate::operation::OpCopy;
use crate::operation::OpMove;
use crate::operation::OpRemove;
use crate::operation::OpReplace;
use crate::operation::OpTest;
use crate::operation::Operation;
pub trait CanPatch {
fn patch_add(&mut self, op: OpAdd) -> Result<()>;
f... |
extern crate haumea;
use std::io;
use std::io::prelude::*;
// Load the CodeGen trait into scope
use haumea::codegen::CodeGen;
fn main() {
let mut source = String::new();
let mut stdin = io::stdin();
stdin.read_to_string(&mut source).expect("Must provide input");
let scanner = haumea::scanner::Scanner:... |
//! ## Query the database
use std::num::ParseIntError;
use super::{
common::{Context, Value, ValueType},
core::Field,
};
use displaydoc::Display;
use thiserror::Error;
/// A struct that can act as a PK filter
///
/// This structure works much like a pre-implemented closure
/// for use in a `filter` function. ... |
#[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 controller reset"]
pub type SYSCFGRST_R = crate::BitReader<SYSCFGRSTW_A>;
#[doc = "System configuration control... |
pub mod img_to_txt;
pub mod txt_to_img;
|
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Direction {
UP,
DOWN,
RIGHT,
LEFT,
}
pub fn get_opposite_direction(direction: &Direction) -> Direction {
match direction {
Direction::UP => Direction::DOWN,
Direction::DOWN => Direction::UP,
Direction::RIGHT => Direction::LEF... |
use crate::chain::{ChainController, ChainService};
use ckb_chain_spec::consensus::Consensus;
use ckb_core::block::Block;
use ckb_core::block::BlockBuilder;
use ckb_core::header::{Header, HeaderBuilder};
use ckb_core::transaction::{CellInput, CellOutput, OutPoint, Transaction, TransactionBuilder};
use ckb_core::uncle::U... |
use crate::{handler_fn, response_ok, Config, Error, Response};
use artell_usecase::user::get_current_art as usecase;
use uuid::Uuid;
use warp::{reject::Rejection, Filter};
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResBody<'a> {
art_id: &'a Uuid,
art_title: &'a str,
art_materials: &... |
use crate::keypair::{PublicKey, SecretKey};
use crate::lbvrf::{Proof, VRFOutput};
use crate::param::Param;
use crate::param::BETA;
use crate::poly::PolyArith;
use crate::poly256::Poly256;
use crate::poly32::Poly32;
use std::io::{Read, Result, Write};
pub trait Serdes {
fn serialize<W: Write>(&self, writer: &mut W)... |
use std::time::Duration;
use std::thread;
use std::process::Command;
fn main() {
for i in 1..100 {
println!("{}", i);
let i_str = i.to_string();
if i % 3 == 0 || contains(i_str){
println!("박수");
say("박수".to_string());
} else {
say(i.to_str... |
use crate::days::day8::{Command, parse_input, default_input};
use std::collections::HashSet;
pub fn run() {
println!("{}", infinite_loop_str(default_input()).unwrap())
}
pub fn infinite_loop_str(input : &str) -> Result<i32, ()> {
infinite_loop(parse_input(input))
}
pub fn infinite_loop(mut code : Vec<Command... |
use std::collections::HashSet;
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct AbilityScore {
value: u32,
}
impl AbilityScore {
pub fn new(value: u32) -> AbilityScore {
AbilityScore { value }
}
pub fn value(&self) -> u32 {
self.value
}
pub fn boost(&m... |
mod commands;
mod expressions;
mod values;
use commands::add_commands_decls;
use expressions::add_expressions_decls;
pub use values::{
convert_sqlite_row_to_nu_value, convert_sqlite_value_to_nu_value, open_connection_in_memory,
SQLiteDatabase,
};
use nu_protocol::engine::StateWorkingSet;
pub fn add_database... |
extern crate bitflags;
extern crate palette;
extern crate cgmath;
extern crate kdtree;
extern crate serde_json;
pub mod layout;
pub mod particle;
use palette::{Rgb, Hsl, RgbHue, IntoColor};
pub fn render_frame(timer: f64) -> Vec<[u8;3]> {
println!("t = {:?}", timer);
(0..200).map(|pixel| {
let x =... |
pub mod opcode;
pub mod types;
pub mod value;
pub mod module;
pub mod function;
pub mod basic_block;
pub mod builder;
|
#[doc = "Register `QUADSPI_HWCFGR` reader"]
pub type R = crate::R<QUADSPI_HWCFGR_SPEC>;
#[doc = "Field `FIFOSIZE` reader - FIFOSIZE"]
pub type FIFOSIZE_R = crate::FieldReader;
#[doc = "Field `FIFOPTR` reader - FIFOPTR"]
pub type FIFOPTR_R = crate::FieldReader;
#[doc = "Field `PRESCVAL` reader - PRESCVAL"]
pub type PRES... |
#[doc = "Register `DDRPHYC_DTPR0` reader"]
pub type R = crate::R<DDRPHYC_DTPR0_SPEC>;
#[doc = "Register `DDRPHYC_DTPR0` writer"]
pub type W = crate::W<DDRPHYC_DTPR0_SPEC>;
#[doc = "Field `TMRD` reader - TMRD"]
pub type TMRD_R = crate::FieldReader;
#[doc = "Field `TMRD` writer - TMRD"]
pub type TMRD_W<'a, REG, const O: ... |
use crate::discovery::{Discovery, DiscoveryConfig};
use friday_error::{FridayError, frierr, propagate};
use friday_logging;
use friday_storage;
use std::sync::{RwLock, Arc};
use friday_web;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct NameMessage {
name: String
}
/// A webvendor... |
pub fn count_primes(n: i32) -> i32 {
if n <= 2 {
0
} else {
let mut primes = vec![2];
'outer: for i in 3..n {
for &prime in &primes {
if i % prime == 0 {
continue 'outer
}
if prime * prime > i {
... |
// 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,... |
use bonuses;
/// An object which tracks morale bonus values.
pub struct MoraleBonus {
tracker: bonuses::NonStackingTracker,
}
impl MoraleBonus {
/// Create an instance of MoraleBonus.
pub fn new() -> MoraleBonus {
MoraleBonus {
tracker: bonuses::NonStackingTracker::new()
}
}
}
impl bonuses::BonusTracker f... |
use super::AminoAcid;
pub fn synthesize(seq: &[AminoAcid]) {} |
use nix::Error;
use nix::errno::Errno;
use nix::unistd::getpid;
use nix::sys::ptrace;
use std::{mem, ptr};
#[test]
fn test_ptrace() {
use nix::sys::ptrace::ptrace::PTRACE_ATTACH;
// Just make sure ptrace can be called at all, for now.
// FIXME: qemu-user doesn't implement ptrace on all arches, so permit E... |
fn main() {
let abi: f32 = 2.4;
let abi: f32 = 120.0 - 20.0 * abi;
println!("Umgewandelt HBZ: {}", abi);
let gewichtung = vec![3, 2, 1, 1];
let math = vec![13, 13, 12, 13, 13];
let deutsch = vec![6, 7, 6, 7];
let englisch = vec![8, 9, 8, 9, 9];
let informatik = vec![14, 11, 12,... |
use crate::conductor::{Item, ItemData, Review};
use crate::error::{ReviseError, ReviseResult};
use crate::sm2;
use chrono::Utc;
use rusqlite::{params, Connection};
use std::path::PathBuf;
pub type ID = i64;
pub trait Store {
fn add_item(&self, desc: &str) -> ReviseResult<()>;
fn edit_item(&self, id: ID, desc:... |
/**
--- Part Two ---
It turns out that this circuit is very timing-sensitive; you actually need to minimize the signal delay.
To do this, calculate the number of steps each wire takes to reach each intersection; choose the intersection where the sum of both wires' steps is lowest. If a wire visits a positi... |
use std::iter::{empty, once};
use std::rc::Rc;
use std::cell::RefCell;
use std::time::Instant;
const RANGE: u64 = 1000000000;
const SZ_PAGE_BTS: u64 = (1 << 14) * 8; // this should be the size of the CPU L1 cache
const SZ_BASE_BTS: u64 = (1 << 7) * 8;
static CLUT: [u8; 256] = [
8, 7, 7, 6, 7, 6, 6, 5, 7, 6, 6, 5, 6,... |
extern crate cursive;
use cursive::Cursive;
use cursive::align::HAlign;
use cursive::view::{TextView, Dialog};
use std::fs::File;
use std::io::Read;
fn main() {
// Read some long text from a file.
let mut file = File::open("assets/lorem.txt").unwrap();
let mut content = String::new();
file.read_to_st... |
// Copyright (c) 2014-2016 Sandstorm Development Group, Inc.
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without li... |
mod compute_mandelbrot;
mod compute_shader;
mod copy_buffers;
mod graphics_pipeline;
mod graphics_window;
mod image_clear;
mod vulkano_particles;
pub use compute_mandelbrot::compute_mandel_and_save;
pub use compute_shader::compute_shader_multiply;
pub use copy_buffers::copy_buffers;
pub use graphics_pipeline::graphics... |
use super::{Cache, Error, Input, Symbol, ParseResult};
use regex::Regex;
use std::collections::HashSet;
// used by macro expansion
pub use std::marker::PhantomData;
pub use std::collections::HashMap;
pub use std::rc::Rc;
// ID :=
// "[a-zA-Z]+"
// FOO :=
// ( "class" ID "{" {MEMBER} "}" )
// MEMBER :=
// ... |
use std::os::raw::c_char;
use std::{
ffi::{CStr, CString},
time::Duration,
};
use tokio_stream::StreamExt;
// "On Unix systems when pthread-based TLS is being used, destructors
// will not be run for TLS values on the main thread when it
// exits. Note that the application will exit immediately after the
// m... |
pub mod models;
pub mod operations;
#[allow(dead_code)]
pub const API_VERSION: &str = "2020-08-04-preview";
|
#![warn(missing_docs)]
//! The structures, as they are serialized
//!
//! This module contains the low-level structs that make up the FDB file. These
//! structures are annotated with `#[repr(C)]` and can be used to read directly
//! from a memory-mapped file on a little-endian machine.
//!
//! Not all values of these ... |
extern crate midir;
use std::error::Error;
use std::io::{stdin, stdout, Write};
use std::thread::sleep;
use std::time::Duration;
use midir::{Ignore, MidiInput, MidiOutput};
fn main() {
match run() {
Ok(_) => (),
Err(err) => println!("Error: {}", err),
}
}
fn run() -> Result<(), Box<dyn Error... |
use super::{Pages, Pagination};
use crate::{
commands::osu::{CommonScoreEntry, CommonUser},
embeds::CommonEmbed,
BotResult,
};
use smallvec::SmallVec;
use twilight_model::channel::Message;
pub struct CommonPagination {
msg: Message,
pages: Pages,
users: SmallVec<[CommonUser; 3]>,
scores_p... |
$NetBSD: patch-vendor_libc-0.2.139_src_unix_bsd_netbsdlike_netbsd_mod.rs,v 1.1 2023/07/10 12:01:24 he Exp $
Add execinfo / backtrace stuff for NetBSD, and handle NetBSD/mips
and NetBSD/riscv64.
--- vendor/libc-0.2.139/src/unix/bsd/netbsdlike/netbsd/mod.rs.orig 2023-04-16 23:32:41.000000000 +0000
+++ vendor/libc-0.2.1... |
//! # Material Information
//!
//! Material allocation and evaluation facilities.
use bytes::{Buf, BufMut};
use std::ffi::c_void;
use crate::gfx::{Error, Result, BufferType, ImageType, ColorFormat};
/// Allocated device memory which can be accessed and modified by host
/// procedures. Different backend might define di... |
use crate::test_utils::{RngCore, TestRandom};
use serde_derive::{Deserialize, Serialize};
use ssz::{Decodable, DecodeError, Encodable, SszStream};
use std::ops::{Deref, DerefMut};
use tree_hash::TreeHash;
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct TreeHashVector<T>(Vec<T>);
impl<T> From<Vec... |
use std::ops::{Add, Div, Mul, Rem, Sub};
use num_bigint::{BigInt, BigUint, RandBigInt, ToBigUint};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct PublicKey {
e: BigUint,
n: BigUint,
}
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub st... |
extern crate ggez;
use ggez::graphics;
use ggez::conf;
use ggez::event;
use ggez::{Context, GameResult};
use ggez::filesystem;
use std::{env, path, str};
use std::io::{Read, Write};
struct MainState {
}
impl MainState {
fn new(_ctx: &mut Context) -> GameResult<MainState> {
let s = MainState {};
... |
use proconio::input;
fn main() {
input! {
s: String,
}
let solver = Solver::new(s);
let stdout = solver.solve();
stdout.iter().for_each(|s| {
println!("{}", s);
})
}
struct Solver {
s: String,
}
impl Solver {
fn new(s: String) -> Solver {
Solver { s: s }
}
... |
use sqlx::{query_file, query_file_as, PgPool};
use time::OffsetDateTime;
use uuid::Uuid;
pub struct Category {
pub id: Uuid,
pub created: OffsetDateTime,
pub category_name: String,
}
impl Category {
pub async fn by_id(id: Uuid, pool: &PgPool) -> Result<Option<Category>, sqlx::Error> {
let res ... |
use xstd::prelude::*;
pub fn predict<T>(frame: &cv::Mat<T>, from: &cv::Point, to: &cv::Point) -> Vec<cv::Point> {
// FIXME
let y = frame.n_rows() - 10;
if from.x() == to.x() {
return vec![*to, cv::Point::new(to.x(), y)];
}
let m = (to.y() - from.y()) as f32 / (to.x() - from.x()) as f32;
... |
use anyhow::Result;
use bincode::{serialize, Result as BincodeResult};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::convert::From;
use std::fs;
use strip_markdown::strip_markdown;
use xorf::HashProxy;
use crate::filter::PostFilters;
use crate::post::{Id, Post};
#[derive(Seri... |
use std::thread;
use std::time::Duration;
use std::io::Read ;
fn main1() {
let handle = thread::spawn(|| {
for i in 0..10 {
println!("thread #1 count {}.", i);
thread::sleep(Duration::from_millis(1000));
}
});
println!("press enter key.");
std::io::stdin().read(&m... |
use num::{Signed, Zero};
use std::ops::Add;
pub trait Monoid: Sized {
fn identity() -> Self;
fn apply(&self, rhs: &Self) -> Self;
}
pub trait Group: Sized {
fn identity() -> Self;
fn inverse(&self) -> Self;
fn apply(&self, rhs: &Self) -> Self;
}
pub trait Abelian {}
#[derive(Copy, Clone, Debug)]... |
use libpulse_sys;
use ffi;
use *;
use std::default::Default;
use std::ffi::CStr;
use std::mem;
fn wrap_context_notify_cb<F>(_: F) -> libpulse_sys::pa_context_notify_cb_t
where F: Fn(&Context, *mut ::libc::c_void)
{
assert!(mem::size_of::<F>() == 0);
unsafe extern "C" fn wrapped<F>(c: *mut libpulse_sys::... |
#![feature(core,io)]
//! library with code shared by all generated implementations
extern crate hyper;
extern crate "rustc-serialize" as rustc_serialize;
extern crate "yup-oauth2" as oauth2;
// just pull it in the check if it compiles
mod cmn;
/// This module is for testing only, its code is used in mako templates
#[... |
use std::{mem, ptr};
pub trait FromBytes: Sized {
fn from_bytes(data: &[u8]) -> Result<Self, &str> {
if data.len() >= mem::size_of::<Self>() {
let s = unsafe { ptr::read(data.as_ptr() as *const Self) };
Ok(s)
} else {
Err("Buffer not long enough.")
}
... |
use futures::sink::SinkExt;
use futures::stream::StreamExt;
use nym_addressing::clients::Recipient;
use nym_duplex::socks::receive_request;
use nym_duplex::transport::{ConnectionId, Packet, Payload};
use nym_websocket::responses::ServerResponse;
use rand::Rng;
use std::collections::BTreeMap;
use structopt::StructOpt;
u... |
pub mod engine;
pub use engine::*;
|
#[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::CR {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W)... |
use priority_queue::PriorityQueue;
use std::collections::HashMap;
use xcg::utils::Trim;
use xcg::model::*;
use xcg::bot::common::Weight;
use xcg::bot::common::{P, a_star_find};
use xcg::bot::common::distance;
#[test]
fn test_a_star() {
let mut gs = game_state(r#"
*.*.*.*.*.*.*.*.*.*.*.
*. ... |
/*
Copyright (c) 2023 Uber Technologies, Inc.
<p>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
<p>http://www.apache.org/licenses/LICENSE-2.0
<p>Unless required by applicable law or agreed to ... |
extern crate advent_of_code_2017_day_3;
use advent_of_code_2017_day_3::*;
#[test]
fn part_1_example_1() {
// Data from square 1 is carried 0 steps, since it's at the access port.
assert_eq!(solve_puzzle_part_1(1), "0");
}
#[test]
fn part_1_example_2() {
// Data from square 12 is carried 3 steps, such as: ... |
extern crate art_1978;
use art_1978::mix;
use art_1978::PrimaryColor;
use std::process;
fn main() {
let red = PrimaryColor::Red;
let yellow = PrimaryColor::Yellow;
mix(red, yellow);
process::exit(0);
}
|
use crate::application::{App, APPLOGO};
use crate::settings::{SetList, TypingTestConfig};
use std::collections::HashMap;
use tui::{
backend::Backend,
layout::{Constraint, Direction, Layout, Rect},
style::{Color, Modifier, Style},
text::Span,
widgets::{Block, Borders, List, ListItem, ListState, Para... |
use crate::attributes::{self, get_pyo3_options, FromPyWithAttribute};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{
parenthesized,
parse::{Parse, ParseStream},
parse_quote,
punctuated::Punctuated,
spanned::Spanned,
Attribute, DataEnum, DeriveInput, Fields, Ident, LitStr, Result, Tok... |
use parenchyma::error::Result;
use parenchyma::prelude::SharedTensor;
use super::{ConvolutionConfiguration, LrnConfiguration, PoolingConfiguration};
pub trait Backward {
/// Computes the gradient of a [CNN convolution] over the input tensor `x` with respect
/// to the data.
///
/// Saves the result to... |
use std::convert::TryFrom;
use std::string::FromUtf8Error;
use svm_types::Type;
use crate::tracking;
/// FFI representation for a byte-array
///
/// # Examples
///
/// ```rust
/// use svm_runtime_ffi::svm_byte_array;
/// use svm_types::Type;
///
/// use std::convert::TryFrom;
/// use std::string::FromUtf8Error;
///
... |
use std::fmt;
use std::fmt::Display;
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Player {
Red,
Yellow,
}
impl Display for Player {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let char = match self {
Player::Red => 'R',
Player::Yellow => 'Y',
};
... |
use std::{
cell::RefCell,
collections::{
hash_map::Entry::{Occupied, Vacant},
HashMap,
},
io::Cursor,
rc::Rc,
};
use byteorder::{LittleEndian, ReadBytesExt};
use encoding::codec::{utf_16, utf_8};
use failure::{ensure, format_err, Error};
use crate::model::{
owned::{Encoding as ... |
fn main() {
const MAX_POINT: u32 = 100_000;
// mut variable
// let x = 5;
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
// const variable
println!("max point is: {}", MAX_POINT);
// shadowing
let y = 5;
println!("The... |
use std::env;
use std::process;
use minigrep::Config;
fn main() {
let args: Vec<String> = env::args().collect();
let config = match Config::new(&args) {
Ok(conf) => conf,
Err(msg) => {
println!("Problem parsing arguments: {}", msg);
process::exit(1);
}
};
... |
/**
* Chapter 8, Common Collections
* https://doc.rust-lang.org/book/second-edition/ch08-03-hash-maps.html#creating-a-new-hash-map
*
* Given a list of integers, use a vector and return
* - the mean (the average value),
* - median (when sorted, the value in the middle position),
* - and mode (the value that o... |
mod challenge10;
mod challenge11;
mod challenge12;
mod challenge13;
mod challenge14;
mod challenge15;
mod challenge16;
mod challenge9;
|
fn main() {
eprintln!("{:?}", "STDERR".chars());
}
|
use std::time::Duration;
use std::net::SocketAddr;
use std::sync::Arc;
use std::collections::HashMap;
use tokio::io;
use tokio::net::UdpSocket;
use tokio::sync::oneshot;
use tokio::time::sleep;
use crate::utils::RemoteAddr;
type Record = HashMap<SocketAddr, (Arc<UdpSocket>, oneshot::Sender<()>)>;
const BUFFERSIZE: u... |
pub mod record;
pub type KeyValueEmitter<'a> = Fn(&[u8], &[u8]) + 'a;
pub type ValueEmitter<'a> = Fn(&[u8]) + 'a;
pub trait Inputter {
fn input(&self, emit: &KeyValueEmitter, num_map_shards: i32, map_shard: i32);
}
pub trait Mapper {
fn map(&self, emit: &KeyValueEmitter, key: &[u8], value: &[u8]);
}
pub tra... |
/// Extract the seconds part from at time span given in seconds.
pub fn seconds(t: u64) -> u64 {
t % 60
}
/// Extract the minutes from a time span given in seconds.
pub fn minutes(t: u64) -> u64 {
(t % 3600) / 60
}
/// Extract the hours from a time span given in seconds.
pub fn hours(t: u64) -> u64 {
t / ... |
fn separator() {
println!("-----------------------------------------");
}
fn conditionals () {
println!("-----------------------------------------");
// let fauvorite_colour: Option<&str> = Some("green");
let fauvorite_colour: Option<&str> = None;
let is_tuesday = false;
let age: Result<u8, _... |
use anyhow::ensure;
use hporecord::{EvalState, ParamDef, Record, StudyId, StudyRecord};
//use indicatif::ProgressBar;
use crate::utils::MeanAndStddev;
use itertools::Itertools;
use ordered_float::OrderedFloat;
use rand::seq::SliceRandom;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::num:... |
// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd.
// Copyright (C) 2021 Subspace Labs, Inc.
// 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
//
... |
use super::{param_header::*, param_type::*, *};
use bytes::{Buf, BufMut, Bytes, BytesMut};
pub(crate) const PARAM_OUTGOING_RESET_REQUEST_STREAM_IDENTIFIERS_OFFSET: usize = 12;
///This parameter is used by the sender to request the reset of some or
///all outgoing streams.
/// 0 1 ... |
#![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 MeterDetails {
#[serde(rename = "meterName", default, skip_serializing_if = "Option::is_none")]
pub meter_n... |
mod gameplay_state_system;
mod input_system;
mod rendering_system;
pub mod box_placed_on_spot_event_handler_system;
pub mod player_hit_obstacle_event_handler_system;
pub mod entity_moved_event_handler_system;
pub use self::gameplay_state_system::GameplayStateSystem;
pub use self::input_system::InputSystem;
pub use se... |
use clap::load_yaml;
use clap::App;
use flexi_logger::Logger;
use log::debug;
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
Logger::with_env_or_str("debug").start()?; // TODO: change this to "error" when ready
let yml = load_yaml!("../cli.yml");
let _cli_matches = App::from_yaml(yml).get_matches(... |
use std::fmt::{Display, Error, Formatter};
use std::io;
use Tile::*;
fn main() {
let mut board: Board = Board {
tiles: [
[Blank, Blank, Blank],
[Blank, Blank, Blank],
[Blank, Blank, Blank],
],
turn: Black,
};
let game_end = false;
while !gam... |
#[cfg(target_arch = "x86")]
#[allow(unused_assignments)]
#[inline(always)]
pub unsafe fn fast_copy(mut dst: *mut u32, mut src: *const u32, mut len: usize) {
asm!("cld
rep movsb"
: "={edi}"(dst), "={esi}"(src), "={ecx}"(len)
: "{edi}"(dst as usize), "{esi}"(src as usize), "{ecx}"(len * 4)
... |
extern crate hellodep;
extern crate proc_macro;
use proc_macro::TokenStream;
use std::str::FromStr;
#[proc_macro_derive(HelloWorld)]
pub fn hello_world(_input: TokenStream) -> TokenStream {
println!("hellodep returned: {}", hellodep::hellodep());
TokenStream::from_str("").unwrap() // no-op
}
|
use crate::cli::setup::traits::Response;
use crate::errors::Error;
use crate::key::generate_key_pair;
use clap::{App, ArgMatches, SubCommand};
use std::fmt;
use tapyrus::{PrivateKey, PublicKey};
pub struct CreateKeyResponse {
private_key: PrivateKey,
public_key: PublicKey,
}
impl CreateKeyResponse {
fn ne... |
//https://blog.csdn.net/guiqulaxi920/article/details/78823541
fn main() {
for i in (0..10).filter(|x| x % 2 == 0) {
println!("{}", i);
}
println!("test....");
for i in (1..5 + 1).rev() {
println!("{}", i);
}
}
|
//! Book data extensions to Polars.
use polars::prelude::*;
use crate::cleaning::names::clean_name;
pub fn udf_clean_name(col: Series) -> PolarsResult<Option<Series>> {
let col = col.utf8()?;
let res: Utf8Chunked = col
.into_iter()
.map(|n| {
if let Some(s) = n {
S... |
use crate::api::BabylonApi;
use crate::core::Scene;
use js_ffi::*;
pub struct HemisphericLight {
_js_ref: JSObject,
}
impl HemisphericLight {
pub fn new(scene: &Scene) -> HemisphericLight {
HemisphericLight {
_js_ref: BabylonApi::create_hemispheric_light(&scene.get_js_ref()),
}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.