text stringlengths 8 4.13M |
|---|
use crate::{FunctionCtx, Backend};
use crate::ptr::Pointer;
use crate::value::Value;
use lowlang_syntax as syntax;
use syntax::layout::TyLayout;
use cranelift_codegen::ir;
use cranelift_module::Module;
pub enum PassMode {
ByRef,
ByVal(ir::Type),
NoPass,
}
pub fn pass_mode<'t, 'l>(module: &Module<impl Back... |
use libc;
use crate::clist::*;
use crate::mailimf_types::*;
use crate::mailmime::*;
use crate::mailmime_types::*;
use crate::x::*;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct mailmime_single_fields {
pub fld_content: *mut mailmime_content,
pub fld_content_charset: *mut libc::c_char,
pub fld_content_bound... |
use std::any::Any;
use super::CrossoverStep;
use crate::{DefaultMutator, Mutator, CROSSOVER_RATE};
/// Default mutator of `Box<T>`
#[derive(Default)]
pub struct BoxMutator<M> {
mutator: M,
rng: fastrand::Rng,
}
impl<M> BoxMutator<M> {
#[no_coverage]
pub fn new(mutator: M) -> Self {
Self {
... |
use procon_reader::ProconReader;
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let s: Vec<char> = rd.get_chars();
let n = s.len();
if n == 1 {
println!("1");
return;
}
let mo: u64 = 1_000_000_000 + 7;
let mut dp = vec![0; n];
... |
trait Train {
fn get_name(&self) -> String;
fn clone(&self) -> Box<Train>;
}
struct TrainProto {
name: String,
}
struct OtherProto {
name: String,
}
impl Train for TrainProto {
fn get_name(&self) -> String {
self.name.clone()
}
fn clone(&self) -> Box<Train> {
Box::new(Tra... |
//! Types for handling information about C++ library APIs.
use crate::cpp_function::CppFunction;
pub use crate::cpp_operator::CppOperator;
use crate::cpp_type::{CppTemplateParameter, CppType};
use crate::database::DatabaseClient;
use itertools::Itertools;
use ritual_common::errors::{bail, ensure, Error, Result};
use r... |
use super::{
PositionIterInternal, PyDictRef, PyIntRef, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef,
};
use crate::{
anystr::{self, AnyStr},
atomic_func,
bytesinner::{
bytes_decode, ByteInnerFindOptions, ByteInnerNewOptions, ByteInnerPaddingOptions,
ByteInnerSplitOptions, ByteInnerT... |
use wasm_encoder::{
CodeSection, ExportKind, ExportSection, Function, FunctionSection,
Instruction, Module, TypeSection, ValType,
};
use std::env;
use std::fs::File;
use std::io::Write;
fn main() -> std::io::Result<()> {
let mut module = Module::new();
let mut types = TypeSection::new();
types.f... |
use std::cmp::max;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::iter;
use super::super::matrix::Matrix;
use super::levelset::LevelSet;
// ____ _
// | _ \ __ _ _ __ __ _ _ __ ___ ___| |_ ___ _ __ ___
// | |_) / _` | '__/ _` | '_ ` _ \ / _ \ __/ _ \ '__/ __|
// | ... |
use crate::Result;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub(crate) struct Response {
pub image: Image,
}
#[derive(Serialize, Deserialize)]
pub(crate) struct ResponseList {
pub images: Vec<Image>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struc... |
/**
The `sabi_extern_fn` attribute macro allows defining `extern "C"` function that
abort on unwind instead of causing undefined behavior.
This macro is syntactic sugar to transform this:
```ignore
<visibility> fn function_name( <params> ) -> <return type> {
<code here>
}
```
into this:
```ignore
<visibility> ex... |
use juniper::{
graphql_object, graphql_subscription, Context, GraphQLInputObject,
GraphQLObject, RootNode, Variables,
};
use juniper::futures::channel::mpsc;
use juniper::futures::executor;
use juniper::futures::{Stream, StreamExt};
use juniper_subscriptions::Connection;
use std::pin::Pin;
use std::sync::{Ar... |
use anyhow::Result;
pub trait Parser {
fn name(&self) -> String;
fn parse_tokens_str<'a>(&self, input: &'a str) -> Result<()>;
fn parse_tokens_string(&self, input: String) -> Result<()>;
// This mutable reference results in unwind unsafe code
fn parse_tokens_reader<'a>(&self, input: &'a mut dyn st... |
use regex::Regex;
use std::fs;
#[test]
fn validate_2_1() {
assert_eq!(algorithm("src/day_2/input_test.txt"), (3, 2));
}
fn parse_data(s: &str) -> Vec<&str> {
let re = Regex::new(":? |-").unwrap();
re.split(s).collect()
}
fn algorithm(file_location: &str) -> (usize, usize) {
let contents = fs::read_to... |
use super::crc;
use super::error;
use std::io::prelude::*;
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct RawGenericChunk {
pub data_length: [u8; 4],
pub chunk_type: [u8; 4],
pub data: Vec<u8>,
pub crc: [u8; 4],
}
impl RawGenericChunk {
pub fn load<R: Read>(reader: &mut R) -> Result<RawG... |
pub mod users;
pub mod roles; |
use std::{
fs::{File, OpenOptions},
io::BufReader,
};
use crate::{bed::Bed, bedgraph::BedGraph, error::Error};
pub enum TrackVariant {
Bed(Bed),
BedGraph(BedGraph),
}
pub fn get_buf(filename: &str) -> Result<BufReader<File>, Error> {
match OpenOptions::new().read(true).open(filename) {
Er... |
use sltunnel::rustls::internal::pemfile::{certs, rsa_private_keys};
use sltunnel::rustls::{Certificate, NoClientAuth, PrivateKey, ServerConfig};
use sltunnel::Server;
use std::env::args;
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::net::SocketAddr;
use std::path::Path;
use std::str::FromSt... |
// Taken from https://github.com/rustwasm/wasm-bindgen/blob/master/crates/backend/src/error.rs
//
// Copyright (c) 2014 Alex Crichton
//
// 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 ... |
#![cfg_attr(feature = "nightly", feature(catch_panic))]
extern crate disque;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread::{spawn, JoinHandle};
#[cfg(feature = "nightly")] use std::thread::catch_panic;
use disque::Disque;
/// Once a j... |
use actix_web_static_files::NpmBuild;
fn main() -> std::io::Result<()> {
NpmBuild::new("./pitunes-frontend")
.executable("yarn")
.install()?
.run("build")?
.target("./pitunes-frontend/build")
.to_resource_dir()
.build()?;
Ok(())
} |
mod config;
#[macro_use]
extern crate lazy_static;
use serde_json::Value;
use std::fs;
use std::io::Write;
pub fn send(channel: String, title: String, content: String) -> anyhow::Result<String> {
use reqwest::blocking::multipart::Form;
use reqwest::blocking::Client;
let mut f = fs::File::create("buf.txt... |
use advent::helpers;
use std::error::Error;
type BoxedError = Box<dyn Error + Send + Sync>;
type Res = Result<u8, BoxedError>;
fn row_op_to_binary(c: &u8) -> Res {
match *c as char {
'F' => Ok(b'0'),
'B' => Ok(b'1'),
_ => Err(From::from(format!("Invalid row op: '{}'", *c as char))),
}
... |
use proconio::input;
fn main() {
input! {
s: String,
};
let words = ["ACE", "BDF", "CEG", "DFA", "EGB", "FAC", "GBD"];
if words.contains(&s.as_str()) {
println!("Yes");
} else {
println!("No");
}
}
|
use std::ffi::c_void;
use std::fmt;
use std::path::{Path, PathBuf};
use firefly_diagnostics::Severity;
use firefly_util::diagnostics::{DiagnosticsHandler, FileName, InFlightDiagnostic, LabelStyle};
use crate::support::MlirStringCallback;
use crate::*;
/// Register our global diagnostics handler as the diagnostic han... |
use crate::interfaces::{Address, OldAddress, Value};
use chain_impl_mockchain::{
certificate,
legacy::UtxoDeclaration,
message::Message,
transaction::{AuthenticatedTransaction, NoExtra, Output, Transaction},
};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Clone, Serialize, De... |
use actix_web::{fs, Application};
use actix_web::middleware::Logger;
use api::State;
pub fn app(state: State) -> Application<State> {
Application::with_state(state)
.middleware(Logger::default())
.handler(
"/",
fs::StaticFiles::new("/www/", false).index_file("index.html"),
... |
use crate::{Cache, Flags, HashChain, Vm};
use std::sync::Arc;
#[test]
fn compute_hash() {
let mut flags = Flags::recommended();
flags.set_full_mem(false);
let cache = Arc::new(Cache::new(flags, &[0; 32], 16).unwrap());
let mut vm = Vm::new(cache).unwrap();
let hash = vm.hash(b"hello world");
as... |
use cpu::CPU;
pub fn nop() -> u8 {
4
}
pub fn hlt(cpu: &mut CPU) -> u8 {
cpu.exit = true;
7
}
|
// 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... |
use std::{ffi::OsStr, time::Duration};
use async_fuse::FileAttr;
use menmos_client::{Meta, Type};
use super::{build_attributes, Error, Result};
use crate::{constants, MenmosFS};
pub struct CreateReply {
pub ttl: Duration,
pub attrs: FileAttr,
pub generation: u64,
pub file_handle: u64,
}
impl MenmosF... |
use goose::prelude::*;
use serde::{de::DeserializeOwned, Deserialize};
use serde_json::json;
use stark_hash::Felt;
use crate::types::{
Block, ContractClass, FeeEstimate, StateUpdate, Transaction, TransactionReceipt,
};
type MethodResult<T> = Result<T, Box<goose::goose::TransactionError>>;
pub async fn get_block... |
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn serialize_synthetic_batch_execute_statement_input_body(
input: &crate::input::BatchExecuteStatementInput,
) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> {
let body = crate::serializer::BatchExecuteStatemen... |
#![feature(stmt_expr_attributes)]
#![feature(proc_macro_hygiene)]
#![feature(async_closure)]
#![deny(rust_2018_idioms, deprecated)]
mod commands;
use std::collections::HashSet;
use serenity::async_trait;
use serenity::framework::standard::help_commands::with_embeds;
use serenity::framework::standard::*;
use serenity... |
// 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 {
component_manager_lib::{klog, model::AbsoluteMoniker, startup},
failure::{Error, ResultExt},
fuchsia_async as fasync,
futures::prelud... |
pub mod accounts;
pub mod providers;
pub mod transactions;
use sqlx::PgPool;
#[derive(Clone)]
pub struct Db(PgPool);
impl Db {
pub async fn connect(url: &str) -> sqlx::Result<Db> {
Ok(Db(PgPool::connect(url).await?))
}
pub fn pool(&self) -> &PgPool {
&self.0
}
pub async fn close... |
use winapi::shared::minwindef::DWORD;
use winapi::shared::windef::{HWND};
use super::ControlHandle;
use crate::win32::window::{build_hwnd_control, build_timer, build_notice};
use crate::{NwgError};
#[cfg(feature = "menu")] use crate::win32::menu::build_hmenu_control;
#[cfg(feature = "menu")] use winapi::shared::windef... |
// 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_fuchsia_router_config::{RouterAdminRequest, RouterStateRequest};
/// The events that can trigger an action in the event loop.
#[derive(Debug)]
pu... |
// 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 ... |
// revisions: base nll
// ignore-compare-mode-nll
//[nll] compile-flags: -Z borrowck=mir
fn test<'x>(x: &'x isize) {
drop::<Box<dyn for<'z> FnMut(&'z isize) -> &'z isize>>(Box::new(|z| {
x
//[base]~^ ERROR E0312
//[nll]~^^ ERROR lifetime may not live long enough
}));
}
fn main() {}
|
extern crate chrono;
#[macro_use] extern crate log;
#[macro_use]
extern crate error_chain;
extern crate indextree;
extern crate libc;
extern crate nix;
extern crate serde;
extern crate spawn_ptrace;
mod errors;
pub use errors::*;
use chrono::{Duration, Local, DateTime};
use indextree::{Arena, NodeId};
pub use indext... |
use crate::KafkaMessage;
use rskafka_proto::{Record, RecordBatch};
use std::borrow::Cow;
pub struct KafkaBatch<'a> {
pub topic: String,
pub partition_index: i32,
pub base_offset: i64,
pub records: Vec<KafkaBatchRecord<'a>>,
}
impl<'a> KafkaBatch<'a> {
pub(crate) fn new(data: RecordBatch<'a>, topic... |
#[doc = "Reader of register MCR"]
pub type R = crate::R<u32, super::MCR>;
#[doc = "Writer for register MCR"]
pub type W = crate::W<u32, super::MCR>;
#[doc = "Register MCR `reset()`'s with value 0"]
impl crate::ResetValue for super::MCR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
... |
//! A module for controlling the fan speed of AMD GPUs.
use std::string::String;
use std::path::{PathBuf, Path};
use std::{io, fs, fmt};
use std::io::{BufRead};
#[derive(Debug)]
pub enum GpuError {
/// IO failure while accessing the GPU device files
Io(io::Error),
/// Unexpected data has been read from a ... |
//! Type-safe units for buffers.
//!
//! It is often ambiguous what an index or offset means when dealing with text. This module
//! provides types that include a strongly-typed unit to make the use of byte and codepoint
//! indices more explicit.
use euclid::{Length, Point2D};
#[derive(Debug)]
pub struct ByteSpace;
... |
use super::button::Button;
use seed::{prelude::*, *};
use std::{borrow::Cow, rc::Rc};
use uuid::Uuid;
use wasm_bindgen::JsCast;
use web_sys::{EventTarget, HtmlElement, MouseEvent};
type PopperInstance = JsValue;
// ------ ------
// Init
// ------ ------
pub fn init(orders: &mut impl Orders<Msg>) -> Model {
M... |
//! Rust bindings to libevdev, an wrapper for evdev devices.
//!
//! This library intends to provide a safe interface to the libevdev library. It
//! will look for the library on the local system, and link to the installed copy.
//!
//! # Examples
//!
//! ## Intializing a evdev device
//!
//! ```
//! use evdev_rs::Devi... |
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qgridlayout.h
// dst-file: /src/widgets/qgridlayout.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block be... |
use super::{crypto_util, Authenticator};
use crate::protocol::parts::AuthFields;
use crate::{HdbError, HdbResult};
use byteorder::{LittleEndian, WriteBytesExt};
use rand::{thread_rng, RngCore};
use secstr::SecUtf8;
use std::io::Write;
const CLIENT_PROOF_SIZE: u8 = 32;
pub struct ScramSha256 {
client_challenge: Ve... |
extern crate ndarray;
use ndarray::prelude::*;
fn testfunc(mut s: Array2<i64>) {}
fn main() {
let n = 3;
let mut s = Array::<i64, _>::zeros(n * n).into_shape((n, n)).unwrap();
testfunc(s);
}
|
// Copyright 2019 Liebi Technologies.
// This file is part of Bifrost.
// Bifrost is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
... |
use n3_machine_ffi::WorkId;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
BuildError(n3_builder::Error),
MachineError(n3_machine_ffi::Error),
NoSuchWork { id: WorkId },
RequireAKey,
// Exposing database error can cause fatal security problem.
DatabaseErr... |
use clap::Parser;
use cli::{Args, RunCmd};
use color_eyre::eyre::Result;
const BUILD_TIME: &str = include!(concat!(env!("OUT_DIR"), "/compiled_at.txt"));
mod built_info {
include!(concat!(env!("OUT_DIR"), "/built.rs"));
}
#[derive(Parser, Debug)]
pub enum Cmd {
/// Display the current version.
#[clap(nam... |
// Ignore me, I'm an empty Rust file that forces Docker to build the project dependencies during `docker build`
// This allows Docker to cache the dependencies, so compilation happens only once instead of at every `docker run`
fn main() {}
|
use stark_hash::Felt;
pub mod proto {
pub mod common {
include!(concat!(env!("OUT_DIR"), "/starknet.common.rs"));
}
pub mod propagation {
include!(concat!(env!("OUT_DIR"), "/starknet.propagation.rs"));
}
pub mod sync {
include!(concat!(env!("OUT_DIR"), "/starknet.sync.rs"));... |
use audio_device::windows::AsyncEvent;
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let runtime = audio_device::runtime::Runtime::new()?;
let guard = runtime.enter();
let event = Arc::new(AsyncEvent::new(false)?);
let event2 = event.clone();
tokio::spawn(async move {
... |
pub fn gcd<T: Int>(a: T, b: T) -> T {
use std::num::Zero;
if b == Zero::zero() {
a
} else {
gcd(b, a % b)
}
}
|
use ::amethyst::core::math::{Vector2, Vector3};
/// Accelerates the given `relative` vector by the given `acceleration` and `input`.
/// The `maximum_velocity` is only taken into account for the projection of the acceleration vector on the `relative` vector.
/// This allows going over the speed limit by performing wha... |
extern crate rand;
use rand::Rng;
fn main() {
let months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
let month = rand::thread_rng().gen_range(1, months.len());
println!("The random month is: {}", months[mo... |
use super::*;
pub fn gen_handle() -> TokenStream {
quote! {
#[derive(::core::clone::Clone, ::core::marker::Copy, ::core::default::Default, ::core::fmt::Debug, ::core::cmp::PartialEq, ::core::cmp::Eq)]
#[repr(transparent)]
pub struct HANDLE(pub isize);
unsafe impl ::windows::core::Ha... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]... |
// This allows us to try and get constants from sets of ASTNodes
// Useful, for example, for emmitting compile-time constant globals.
use crate::parser::ast_utils::{ASTNode, ASTBinaryOperation};
pub fn get_constant_value_from_node(node: &ASTNode) -> isize {
match node {
ASTNode::IntegerLiteral(int) => *int... |
extern crate kiss3d;
extern crate nalgebra as na;
extern crate num;
mod core;
use na::{
Point3,
Vector3,
UnitQuaternion
};
use kiss3d::window::Window;
use kiss3d::light::Light;
use kiss3d::window::State;
use kiss3d::scene::SceneNode;
fn main() {
let mut window = Window::new("kiss");
let eye = ... |
#[doc = "Reader of register WRP2AR"]
pub type R = crate::R<u32, super::WRP2AR>;
#[doc = "Writer for register WRP2AR"]
pub type W = crate::W<u32, super::WRP2AR>;
#[doc = "Register WRP2AR `reset()`'s with value 0xff00_ff00"]
impl crate::ResetValue for super::WRP2AR {
type Type = u32;
#[inline(always)]
fn rese... |
pub mod material;
pub mod mesh;
pub mod model;
|
#[macro_use]
mod common;
use common::util::*;
static UTIL_NAME: &'static str = "expr";
#[test]
fn test_simple_arithmetic() {
let (_, mut ucmd) = testing(UTIL_NAME);
let out = ucmd.args(&["1", "+", "1"]).run().stdout;
assert_eq!(out, "2\n");
let (_, mut ucmd) = testing(UTIL_NAME);
let out = ucmd.... |
use std::fmt::{Debug, Display};
use data_types::ParquetFile;
pub mod and;
pub mod level_range;
pub trait FileFilter: Debug + Display + Send + Sync {
fn apply(&self, file: &ParquetFile) -> bool;
}
|
use rust_gpiozero::{LED, PWMLED, Button};
use std::thread::sleep;
use std::time::Duration;
use reqwest::Client;
use std::thread;
enum CallType{
InCall,
InitiatingCall,
Idle,
}
static ADDRESS_INFO: &str = "http://localhost:8080/callstatus";
static ADDRESS_CALL: &str = "http://localhost:8080/ring";
fn main... |
#[doc = "Reader of register CCR"]
pub type R = crate::R<u32, super::CCR>;
#[doc = "Writer for register CCR"]
pub type W = crate::W<u32, super::CCR>;
#[doc = "Register CCR `reset()`'s with value 0"]
impl crate::ResetValue for super::CCR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
... |
use libsm::sm3::hash::Sm3Hash;
use crate::address::traits::checksum::ChecksumI;
pub struct ChecksumSM2P256V1 {}
impl ChecksumSM2P256V1 {
pub fn new() -> Self {
ChecksumSM2P256V1 {
}
}
}
// -------------------------------------------------------------------------------... |
use nalgebra::{Scalar, SimdRealField};
use crate::odometry::OdometryModel;
use crate::sensor_models::SensorModel;
use crate::{Pose, PoseCovariance};
pub mod kalman_filter;
pub mod particle_filter;
pub trait StateFilter<N: Scalar + SimdRealField> {
fn pose(&self) -> Pose<N>;
fn covariance(&self) -> PoseCovaria... |
extern crate progress_streams;
use progress_streams::ProgressWriter;
use std::io::{Write, sink};
fn main() {
let mut total = 0;
let mut file = sink();
let mut writer = ProgressWriter::new(&mut file, |progress: usize| {
total += progress;
println!("Written {} Kib", total / 1024);
});
... |
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
use anyhow::Result;
use juniper_actix::{graphiql_handler, graphql_handler, playground_handler};
use log::*;
use crate::db::Db;
use crate::graphql::{schema, Context, Image, Schema};
async fn graphiql_route() -> Result<HttpResponse, Error> {
gr... |
use crate::prelude::*;
use rstar::{RTreeObject, AABB};
pub struct My<T>(pub T);
// https://docs.rs/rstar/0.9.1/rstar/trait.RTreeObject.html
impl RTreeObject for My<Point2> {
type Envelope = AABB<[f32; 2]>;
fn envelope(&self) -> Self::Envelope {
let point = self.0;
AABB::from_point([point.x, p... |
// 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 ... |
use std::collections::HashMap;
use std::sync::Arc;
use smallvec::SmallVec;
use sourcerenderer_core::graphics::{
AccelerationStructureInstance,
AccelerationStructureMeshRange,
Backend,
Barrier,
BarrierAccess,
BarrierSync,
BottomLevelAccelerationStructureInfo,
BufferInfo,
BufferUsage,... |
use std::net::{TcpListener, TcpStream};
use std::io::{BufRead, BufReader, Write};
use std::{str, fmt, thread};
#[macro_use]
extern crate tcpproxy;
use tcpproxy::consts;
#[allow(dead_code)]
struct RequestLine {
method: Option<String>,
path: Option<String>,
protocol: Option<String>,
}
#[derive(Debug)]
struc... |
//! An implementation of the Observer pattern.
use std::{
cell::RefCell,
rc::Rc,
};
/// A value that implements the Observer pattern.
///
/// Consumers can connect to receive callbacks when the value changes.
pub struct ObservableValue<T>
where T: Clone
{
value: T,
subs: Vec<Subscription<T>>,
... |
#[macro_use]
extern crate failure;
extern crate rayon;
#[macro_use]
extern crate lazy_static;
mod cipher;
mod interactif;
use failure::Error;
fn main() -> Result<(), Error> {
let cipher_text = interactif::get_cipher_text()
.map_err(|err| format_err!("could get cipher text: {}", err))?;
let key = int... |
use std::collections::HashMap;
fn main() {
let mut string_hash_map: HashMap<String, i32> = HashMap::new();
string_hash_map.insert(String::from("hello world"), 1000);
println!("{:?}", string_hash_map);
let keys = vec![String::from("hello"), String::from("world")];
let values = vec![1, 2];
... |
use std::fmt::{Result, Display, Formatter};
#[derive(Default, Eq, Ord, Copy, Clone, Debug, PartialEq, PartialOrd, Hash)]
pub struct File(u8);
impl File {
pub fn from_bits(bits: u8) -> Self {
debug_assert!(bits < 8);
File(bits)
}
pub fn parse(input: char) -> Self {
debug_assert!((in... |
fn main() {
let x = 5;
match x {
1..=5 => println!("satu sampai lima"),
_ => println!("yang lain"),
}
match_char();
}
fn match_char() {
let x = 'c';
match x {
'a'..='j' => println!("awal huruf ASCII"),
'k'..='z' => println!("akhir huruf ASCII"),
_ => println!("yang ... |
use std::convert::TryFrom;
pub(crate) type Score = i32;
pub(crate) const SCORE_STARTER: Score = 0;
pub(crate) const SCORE_DEFAULT_BONUS: Score = 0;
pub(crate) const SCORE_MAX: Score = Score::MAX;
pub(crate) const SCORE_MIN: Score = Score::MIN;
pub(crate) const SCORE_GAP_LEADING: Score = -1;
pub(crate) const SCORE_GA... |
#![allow(non_camel_case_types)]
#![cfg_attr(miri, allow(unused_imports))]
mod layout_tests {
#[cfg(all(test, not(feature = "only_new_tests")))]
mod erased_types;
#[cfg(all(test, not(feature = "only_new_tests")))]
mod prefix_types;
#[cfg(all(test, not(feature = "only_new_tests")))]
mod value;
... |
//! Types for the compiled format of a QVM.
/// Size of procedure stack adjustment.
pub type FrameSize = u32;
/// Size of memory block to copy.
pub type BlockSize = u32;
/// Offset within stack frame.
pub type FrameOffset = u32;
/// Offset within the argument marshalling space.
pub type ArgOffset = u8;
/// Absolut... |
fn main() {
println!("Sum result {}", sum(5,8));
}
fn sum(x:i32, y:i32) -> i32 {
let z = {
x + y
};
z
}
|
#[unstable(feature = "stdsimd", issue = "0")]
pub mod arch {
pub use coresimd::arch::*;
pub mod detect;
}
#[unstable(feature = "stdsimd", issue = "0")]
pub use coresimd::simd;
|
use self::*;
#[test]
fn it_works() {
assert_eq!(say_hello!([1,2,3]), 2);
}
|
use std::path::PathBuf;
use clap::ArgMatches;
use app::{NodeConnection, AppConfig,
NamedRelayAddress, NamedIndexServerAddress,
load_relay_from_file, load_index_server_from_file,
load_friend_from_file, PublicKey};
use app::report::{NodeReport, ChannelStatusReport};
#[derive(Debug)]
pub enum ConfigError ... |
extern crate serde_json;
extern crate clap;
use rocket::State;
use rocket::response::{Responder, Response};
use rocket::http::{Status, ContentType};
use rocket::request::Request;
use rocket::response;
use rocket_contrib::json::{Json, JsonValue};
use crate::store::TinStore;
#[derive(Deserialize)]
pub struct Element {... |
use rand::Rng;
use rayon::prelude::*;
use std::{fs::File, io::BufWriter, sync::Arc};
#[macro_use]
mod macros;
mod camera;
mod config;
pub mod hittables;
pub mod materials;
mod ray;
mod vec3;
pub use camera::Camera;
pub use config::{CameraConfig, ImgConfig, RunConfig, SceneConfig};
pub use hittables::Hittable;
use hi... |
#[doc = "Reader of register ISR"]
pub type R = crate::R<u32, super::ISR>;
#[doc = "Writer for register ISR"]
pub type W = crate::W<u32, super::ISR>;
#[doc = "Register ISR `reset()`'s with value 0"]
impl crate::ResetValue for super::ISR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
... |
use raylib::prelude::*;
use std::io::{Read, Write};
use std::net::TcpStream;
use crate::awaiting_opponent;
use crate::imui::*;
use crate::pong;
use crate::scene::*;
use common::{DEVEL_IP, PROD_IP};
pub struct TitleScreen {
should_quit: bool,
failed_to_connect_to_lobby: bool,
production_url: bool,
}
imp... |
use std::io::{Error, Read, Write};//引入IO口中的读、写、错误方法
use std::net::{TcpListener, TcpStream};//引入TCP监听和TCP数据流格式
use std::thread;//引用线程包
use std::time;//引入时间包
fn handle_client(mut stream: TcpStream) -> Result<(), Error>{
let mut buf = [0;512];//生成一个缓存数组
println!("服务器在等待客户端发送消息");
for _ in 0..1000{ //循环执行1000次... |
use std::mem;
use textwrap;
#[derive(Debug, Clone)]
/// A word wrapper.
/// Takes input lines like a vector (with [WordWrapper::push]).
/// The wrapped text (to the specified width) is returned with [WordWrapper::get_text].
/// The text is only rerendered, when the content was modified or marked dirty with [WordWrappe... |
extern crate num;
// return true if the number is a palendrome in decimal
pub fn is_dec_palendrome(x: u32) -> bool {
let mut reverse: u32 = 0;
let mut temp = x;
while temp > 0 {
reverse *= 10;
reverse += temp % 10;
temp /= 10;
}
reverse == x
}
// return true if the number ... |
#{script}
|
use regex::Regex;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::fs;
fn main() {
let data = fs::read_to_string("input").expect("Error");
println!("Oy, oy, oy, the result is {}", run_input(data));
}
fn run_input(data: String) -> u32 {
let mut rules: BTreeMap<String, HashMap<String,... |
// Copyright 2014 The Servo Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... |
use derive_more::From;
use futures::stream::BoxStream;
use iso_country::Country as CountryBase;
use serde::{
de::{self, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};
use serde_json::Value;
use std::{
collections::{BTreeMap, HashMap},
hash::Hash,
net::SocketAddr,
ops::Deref,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.