text stringlengths 8 4.13M |
|---|
use crate::{
geo::{Geo, HitResult, HitTemp, Material, Texture, TextureRaw},
linalg::{Ray, Transform, Vct},
Deserialize, Flt, Serialize, EPS,
};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Sphere {
pub radius: Flt,
pub texture: Texture,
pub transform: Transform,
}
impl Sphere {
... |
use kiss3d::light::Light;
use kiss3d::{window::Window, scene::PlanarSceneNode};
use nalgebra::{Vector2, Point2, Translation2};
use rand::{Rng, thread_rng};
const MAX_SEPARATION: f32 = 16.0;
const MAX_ALIGNMENT: f32 = 32.0;
const MAX_COHESION: f32 = 16.0;
const MAX_VELOCITY: f32 = 6.0;
const MAX_FORCE: f32 = 0.05;
con... |
// 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 2014 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 ... |
for (pos, &{{#if set.arg~}}(arg, obj){{else}}obj{{/if~}})
in {{>set.new_objs def=set objs="new_objs"}}.iter().enumerate() {
{{#if set.arg~}}
let arg = {{>set.item_getter def=set.arg id="arg"}};
{{/if~}}
let obj = {{>set.item_getter def=set id="obj" var="arg"}};
{{#each arg_conflicts~}}
... |
use std::fmt::Display;
use async_trait::async_trait;
use data_types::ParquetFile;
use metric::{Registry, U64Counter};
use crate::{error::DynError, PartitionInfo};
use super::PartitionFilter;
const METRIC_NAME_PARTITION_FILTER_COUNT: &str = "iox_compactor_partition_filter_count";
#[derive(Debug)]
pub struct Metrics... |
use arrow_util::assert_batches_eq;
use mutable_batch::writer::Writer;
use mutable_batch::MutableBatch;
use schema::Projection;
#[test]
fn test_new_column() {
let mut batch = MutableBatch::new();
let mut writer = Writer::new(&mut batch, 2);
writer
.write_bool("b1", None, vec![true, false].into_iter... |
use tui::{Terminal, Frame};
use std::io::Stdout;
use tui::backend::CrosstermBackend;
use crossterm::terminal::{ClearType, Clear};
use crossterm::ExecutableCommand;
use crate::runtime::data::launches::structures::{Launch, Article};
use chrono::{DateTime, Local};
use crate::languages::LanguagePack;
use tui::layout::{Rect... |
{{#each arguments}}{{this.[0]}}: &{{this.[1].def.keys.ItemType}}, {{/each~}}
|
use crate::teams::send_message;
use futures::StreamExt;
use k8s_openapi::api::core::v1::Event;
use kube::{
api::{Api, ListParams},
Client, Config,
};
use kube_runtime::controller::{Context, Controller, ReconcilerAction};
use log::{info, warn};
use tokio::time::Duration;
pub struct KubeClient {
client: Clie... |
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use async_io::Async;
use futures_io::{AsyncRead, AsyncWrite};
use ssh2::{File, FileStat, OpenFlags, OpenType, RenameFlags, Sftp};
use crate::util::poll_once;
pub struct AsyncSftp<S... |
use std::collections::BTreeMap;
use std::io::{Read, Seek};
use {builder, Date, EventReader, PlistEvent, Result};
#[derive(Clone, Debug, PartialEq)]
pub enum Plist {
Array(Vec<Plist>),
Dictionary(BTreeMap<String, Plist>),
Boolean(bool),
Data(Vec<u8>),
Date(Date),
Real(f64),
Integer(i64),
... |
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
fn main() {
// Put the linker script somewhere the linker can find it
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
let linker = match (cfg!(feature = "stm32l0x1"), cfg!(feature = "stm32l0x2")) {
(false, fals... |
use ggez::Context;
use ggez::graphics::Font;
pub struct Assets {
pub debug_font: Font
}
impl Assets {
pub fn load(ctx: &mut Context) -> Assets {
let debug_font_bytes = std::include_bytes!("../../resources/font/5x5.ttf");
let debug_font = Font::new_glyph_font_bytes(ctx, debug_font_bytes)
... |
pub use grass_biome::*;
use game::*;
#[allow(dead_code, unused_variables)]
pub fn step_biomes(game: &mut Game1){
}
#[allow(unused_variables)]
#[allow(dead_code)]
pub fn end_step_biomes(game: &mut Game1){
}
|
//! Implement the NewType pattern with inherit_methods macro.
use inherit_methods_macro::inherit_methods;
use std::vec::Vec;
pub struct Stack<T>(Vec<T>);
// The following methods are inherited from Vec automatically
#[inherit_methods(from = "self.0")]
#[rustfmt::skip]
impl<T> Stack<T> {
// Normal methods can be ... |
//#![feature(box_into_boxed_slice)]
//TODO: reduce usage of cloned and clone. ensure cache
// optimal at least with addressing? TODO: macro generic for
// variable kwargs and generic input types. same thing
// for output vector? not as important yet unless easy to
// implement. TODO: ensure all types T can be disc... |
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qtextobject.h
// dst-file: /src/gui/qtextobject.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
/... |
use anyhow::Result;
use diesel::{r2d2, SqliteConnection};
pub type Connection = SqliteConnection;
pub type Pool = r2d2::Pool<r2d2::ConnectionManager<Connection>>;
embed_migrations!("./migrations/sqlite");
pub fn setup() -> Result<Pool> {
let manager = r2d2::ConnectionManager::<SqliteConnection>::new(":memory:");... |
pub const SPEED_OF_LIGHT: f64 = 2.99792458E8;
pub const G: f64 = 6.67408E-11;
pub const PLANCK: f64 = 6.626070040E-34;
pub const PLANCK_REDUCED: f64 = 1.054571800E-34;
pub const ELEMENTARY_CHARGE: f64 = 1.6021766208E-19;
pub const MU0: f64 = 1.256637061435917E-6;
pub const EPSILON0: f64 = 8.854187817620E-12;
pub const... |
#[doc = "Reader of register CAL0"]
pub type R = crate::R<u32, super::CAL0>;
#[doc = "Reader of field `SEC`"]
pub type SEC_R = crate::R<u8, u8>;
#[doc = "Reader of field `MIN`"]
pub type MIN_R = crate::R<u8, u8>;
#[doc = "Reader of field `HR`"]
pub type HR_R = crate::R<u8, u8>;
#[doc = "Reader of field `AMPM`"]
pub type... |
// 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 std::cmp::{max, min};
use handlebars::Handlebars;
use v_htmlescape::escape;
use super::utils::{self, rematch, Difference};
use crate::{config::Diff2HtmlConfig, parse};
static GENERIC_COLUMN_LINE_NUMBER: &'static str =
include_str!("../templates/generic-column-line-number.hbs");
static GENERIC_EMPTY_DIFF: &'s... |
#[path = "with_arity_zero/with_environment.rs"]
mod with_environment;
#[path = "with_arity_zero/without_environment.rs"]
mod without_environment;
|
use std::fmt::{Result, Display, Formatter};
use mask::Mask;
use file::{File, parse_file};
use rank::{Rank, parse_rank};
use color::Color;
use color::Color::*;
pub use self::squares::*;
mod squares;
// Note that index 0 corresponds to a8, and NOT a1!
// Indexes read left to right, top to bottom!
#[derive(Default, Eq, ... |
// 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.
//! Common utilities for pseudo file implementations
use {
fidl_fuchsia_io::{
MODE_PROTECTION_MASK, MODE_TYPE_DIRECTORY, MODE_TYPE_FILE, OPEN_... |
use std::fmt;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Seedling {
pub current_age: u32,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum FloraVariant {
Sapling(Seedling),
Tree(u32),
Elder(u32),
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct Woodcutter {
pub lumber_colle... |
pub fn sum_odd_length_subarrays(arr: Vec<i32>) -> i32 {
(1..=arr.len())
.step_by(2)
.map(|x| arr.windows(x).map(|y| y.iter().sum::<i32>()).sum::<i32>())
.sum()
}
#[cfg(test)]
mod sum_odd_length_subarrays_tests {
use super::*;
#[test]
fn sum_odd_length_subarrays_one() {
... |
// 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 2017 Parity Technologies (UK) Ltd.
//
// 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 limitation
// the rights to use, copy, modify, mer... |
/// Knobs are a linear control that can be plugged into various components. They're thread-safe
/// underneath so you can share them all over the place.
use std;
use std::sync::{Arc, RwLock};
/// A Knob
pub struct Knob {
value: Arc<RwLock<f64>>,
max: Arc<RwLock<f64>>,
min: Arc<RwLock<f64>>,
}
/// Allow m... |
use autopilot::bitmap::Bitmap;
use std::path::{Path, PathBuf};
lazy_static! {
pub static ref RES_PATH: PathBuf =
Path::new("/home/ITRANSITION.CORP/a.sinilo/MyProjects/Rust/jde_versions_autocreate/res/en")
.to_path_buf();
pub static ref IV_HEADER: Bitmap = Bitmap::new(
image::open(RE... |
fn main() {
use text_grid::*;
struct RowData {
a: String,
b: u32,
c: u32,
d: f64,
}
impl CellsSource for RowData {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.column("a", |&s| &s.a);
f.column("b", |&s| s.b);
f.column("... |
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use log::{info, trace};
use serde_derive::Deserialize;
use crate::input::keyboard::Key;
use crate::{CoreError, CoreResult};
pub mod keyboard {
use serde_derive::Deserialize;
#[derive(Debug, Copy, Clone, Eq, Partia... |
use crate::tuple::flip::FlipTuple;
/// Flips argument order of `self`.
///
/// # Example
/// ```
/// use fntools::unstable::flip;
///
/// let fun = |a: &str, b: i32, c: char| format!("{}{}{}", a, b, c);
/// let fun = flip(fun);
///
/// assert_eq!(fun('c', 17, "hello, "), "hello, 17c")
/// ```
pub fn flip<A, F>(f: F) -... |
pub(crate) const WORDS: &[&str] = &[
"Advantage",
"Anaconda",
"Apple",
"Argument",
"Banana",
"Bear",
"Bee",
"Belief",
"Bob",
"Bravery",
"Building",
"Bull",
"Bunny",
"Car",
"Care",
"Cat",
"Chair",
"Character",
"Chicken",
"Childhood",
"C... |
mod deps;
mod scripts;
#[async_std::main]
async fn main() {
let mut args = std::env::args();
args.next(); // The first argument is the program itself.
match args.next().unwrap_or_default().as_str() {
"scripts" => print!("{}", scripts::fetch_npm_scripts().await.unwrap_or_default()),
"add" =... |
use std::collections::HashMap;
fn evolve(prev_state: String, rules: &HashMap<String, char>) -> String {
let state = "....".to_owned() + &prev_state + "....";
let mut result = String::new();
for i in 2..(state.len() - 2) {
result.push(*rules.get(state[(i - 2)..(i + 3)].into()).unwrap_or(&'.'));
... |
#[doc = "Reader of register AHBENR"]
pub type R = crate::R<u32, super::AHBENR>;
#[doc = "Writer for register AHBENR"]
pub type W = crate::W<u32, super::AHBENR>;
#[doc = "Register AHBENR `reset()`'s with value 0x8000"]
impl crate::ResetValue for super::AHBENR {
type Type = u32;
#[inline(always)]
fn reset_val... |
//! This CI script for `xshell`.
//!
//! It also serves as a real-world example, yay bootstrap!
use std::{env, process, time::Instant};
use xshell::{cmd, Result, Shell};
fn main() {
if let Err(err) = try_main() {
eprintln!("{}", err);
process::exit(1);
}
}
fn try_main() -> Result<()> {
le... |
use k8s_openapi::api::core::v1::{Container, Pod, Volume, VolumeMount};
use serde_json::json;
use std::sync::Arc;
pub struct PodLifetimeOwner {
pub pod: Pod,
_tempdirs: Vec<Arc<tempfile::TempDir>>, // only to keep the directories alive
}
pub struct WasmerciserContainerSpec {
pub name: &'static str,
pub... |
pub mod break_handler;
pub mod host;
pub mod io;
pub mod random;
|
pub fn setup() {
// setup code specific to your library'ss tests would go here
}
|
#![deny(broken_intra_doc_links, rust_2018_idioms)]
#![warn(
missing_copy_implementations,
missing_debug_implementations,
missing_docs,
clippy::explicit_iter_loop,
clippy::use_self,
clippy::clone_on_ref_ptr,
clippy::future_not_send
)]
//! # influxdb2
//!
//! This is a Rust client to InfluxD... |
use gotham::handler::HandlerError;
use gotham_derive::StateData;
use rand::Rng;
use reqwest::Response;
use serde::ser::{Serialize, SerializeStruct, Serializer};
use serde_derive::Serialize;
use simple_error::SimpleError;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashSet;
use std::hash::{Hash,... |
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn serialize_operation_add_tags_to_certificate(
input: &crate::input::AddTagsToCertificateInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::seri... |
enum ContentType {
TextHtml,
TextPlain,
Other(String),
}
enum Charset
{
UTF8,
Other(String),
}
pub struct Response {
code: i16,
content_type: ContentType,
charset: Charset,
body: String,
}
impl Response {
pub fn new() -> Self
{
Response { code: 200, content_type:... |
use std::iter::Enumerate;
use std::mem::size_of;
pub fn third<A, B, C>(t: (A, B, C)) -> C { t.2 }
pub fn enumerate<I>(iterable: I) -> Enumerate<I::IntoIter>
where I: IntoIterator
{
iterable.into_iter().enumerate()
}
/// return the number of steps from a to b
pub fn ptrdistance<T>(a: *const T, b: *const T) -... |
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qtemporarydir.h
// dst-file: /src/core/qtemporarydir.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begi... |
use std::fmt;
use rand::Rng;
use serde_derive::{Deserialize,Serialize};
// The Shelvacu Fast Word Square VM: SFWSVM -> SVM
// registers (32-bit each)
// 00 output
// 01..16 input
// 16..64 work registers, initialized to 0
const SVM_NUM_REGISTERS:usize = 32;
type SvmRegister = u32;
type SvmMemory = Box<[SvmRegister; SV... |
use mav::ma::BtcTokenType;
use mav::{kits, CFalse, NetType, WalletType};
use std::ptr::null_mut;
use wallets_cdl::chain_btc_c::{ChainBtc_start, ChainBtc_loadNowBlockNumber, ChainBtc_loadBalance};
use wallets_cdl::mem_c::{CWallet_dFree, CBtcNowLoadBlock_dAlloc, CBtcBalance_dAlloc};
use wallets_cdl::parameters::{CCreateW... |
pub struct Solution;
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: List,
}
type List = Option<Box<ListNode>>;
impl Solution {
pub fn delete_duplicates(head: List) -> List {
let mut head = head;
let mut current = &mut head;
while current.is_so... |
use ecc::e256::E256;
use ecc::ec::{Ec, Point};
use ecc::gf256::Gf256;
use rayon::prelude::*;
fn main() {
let a = Gf256::from(23);
let b = Gf256::from(107);
let ec = E256::new(a, b);
ec.points().par_iter().for_each(|p| {
println!(
"{}",
match p {
Point::Id... |
use crate::controller::inner::ControllerInner;
use crate::controller::migrate::Migration;
use crate::controller::recipe::Recipe;
use crate::coordination::CoordinationMessage;
use crate::coordination::CoordinationPayload;
use crate::startup::Event;
use crate::Config;
use async_bincode::AsyncBincodeReader;
use dataflow::... |
use std::iter;
use crate::ast::constrain::Constraint;
use crate::ast::context::CheckerContext;
use crate::ast::error::TypeError;
use crate::ast::{
type_check_code, type_check_enum_values, ChoiceDef, ChoiceInstance, Condition,
CounterBody, CounterVal, VarDef, VarMap,
};
use crate::ir::{self, Adaptable};
use cra... |
use std::fmt;
#[cfg(feature = "serialization")]
use serde::{Deserialize, Serialize};
/// Enum describing supported Purposed platforms.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))]
#[cfg_attr(feature = "serialization", serde(rename_all = "lowercase"))]
pub e... |
use na::{Vector3, Matrix3}
struct Light {
localLightOrigin: Vector3,
localLightAxis: Matrix3
baseColor: Vector3
}
impl Light {
pub fn new() -> Light{
Light {
localLightOrigin: Vector3::new(na::zero())
}
}
pub fn set_color(red: f32, green: f32, blue: f32) {
}
... |
use std::io::{self};
use aoc_2019_11::{self, error::Error, Prog};
fn main() -> Result<(), Error> {
let mut input = String::new();
let _ = io::stdin().read_line(&mut input)?;
let mem_state = aoc_2019_11::parse_mem_state(&input)?;
let prog = Prog::new(&mem_state);
let panels = aoc_2019_11::paint_hu... |
// 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.
//! Common data structures.
mod id_map;
mod id_map_collection;
pub(crate) mod token_bucket;
pub use id_map::Entry;
pub(crate) use id_map::IdMap;
pub use ... |
use std::fs::File;
use std::io::{BufRead, BufReader, Error, ErrorKind, Read};
use intcode::*;
fn read<R: Read>(io: R) -> Result<Vec<i64>, Error> {
let br = BufReader::new(io);
br.lines()
.map(|line| line.unwrap())
.next()
.unwrap()
.split(',')
.map(|x| {
x.p... |
//! Parser module, enabled with "parsing" feature
//!
//! This module provides the possibility to parse svg files.
//!
//! # Examples
//! ## Getting a svg from a file
//! *The feature "parsing" needs to be enabled for this*
//! ```
//! use svg_definitions::prelude::*;
//!
//! let shape = SVGParseFile("/path/to/file.svg... |
pub mod coordinates;
pub mod simulation;
|
mod io;
mod types;
mod output;
mod utils;
#[macro_use]
extern crate clap;
extern crate colorsys;
use termion::{color, style};
use types::*;
use dirs;
use utils::*;
fn main()
{
let mut path = dirs::home_dir().unwrap().into_os_string().to_str().unwrap().to_owned();
path.push_str("/.cli-todo");
let mut use... |
use std::fmt::{Display, Formatter};
struct NumberSet {
numbers: Vec<u32>
}
struct Point<T, U> {
x: T,
y: U
}
trait PrettyPrint {
fn pretty_print(&self) -> String;
}
fn write_summary<T: PrettyPrint>(t: &T) {
print!("{}", t.pretty_print())
}
impl<T, U> PrettyPrint for Point<T, U> where
T : D... |
use std::fs;
use std::fs::OpenOptions;
use std::io::Write;
use std::process::Child;
use std::process::Command;
use std::process::Stdio;
use std::thread;
use std::time;
use timetrack::get_config;
struct Backup;
impl Backup {
fn new() -> Self {
let config = get_config();
fs::copy(
&conf... |
#![deny(rustdoc::broken_intra_doc_links, rustdoc::bare_urls, rust_2018_idioms)]
#![warn(
missing_debug_implementations,
clippy::explicit_iter_loop,
clippy::use_self,
clippy::clone_on_ref_ptr,
// See https://github.com/influxdata/influxdb_iox/pull/1671
clippy::future_not_send,
clippy::todo,
... |
//! UART4
//!
//! Synopsys DesignWare ABP UART
//!
//! Size: 1K
//! Rx: PD3
//! Tx: PD2
//! CTS: PD5
//! RTS: PD4
use crate::uart_common::{
NotConfigured, Receive, ReceiveRegisterBlock, RegisterBlock, Transmit, TransmitRegisterBlock,
UartMode,
};
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};... |
extern crate cgl;
use cgl::{Color, Image, Mat4, Vec3};
mod demo;
fn main() {
let model = demo::african_head_obj();
let mut image = Image::with_dimensions(512, 512);
let mut zbuf = Image::filled(512, 512, std::f32::MIN);
let perspective = {
let mut p = Mat4::identity();
p[(2, 3)] = 5.... |
#[doc = "Reader of register MPCBB1_VCTR57"]
pub type R = crate::R<u32, super::MPCBB1_VCTR57>;
#[doc = "Writer for register MPCBB1_VCTR57"]
pub type W = crate::W<u32, super::MPCBB1_VCTR57>;
#[doc = "Register MPCBB1_VCTR57 `reset()`'s with value 0xffff_ffff"]
impl crate::ResetValue for super::MPCBB1_VCTR57 {
type Typ... |
//https://leetcode.com/problems/determine-if-string-halves-are-alike/
impl Solution {
pub fn halves_are_alike(s: String) -> bool {
let mut valid: Vec<bool> = vec![false; 200];
valid['a' as usize] = true; valid['A' as usize] = true;
valid['o' as usize] = true; valid['O' as usize] = true;
... |
use execution::Execution;
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub enum OrderStatus {
NotSent,
Sent,
Filled(Execution),
Cancelled(CancellationReason)
}
#[derive(Serialize, Deserialize, Clone, Eq, PartialEq, Hash, Debug)]
pub enum CancellationReason {
FilledOca,
OutdatedOr... |
use std::io::Read;
use crate::rlew_reader::RlewReader;
use byteorder::{ReadBytesExt, LittleEndian};
pub struct MapHead {
pub rlew_tag: u16,
pub header_offsets: [u32; 100],
pub tile_info: Vec<u8>
}
impl MapHead {
pub fn parse(s: &mut Read) -> Option<MapHead> {
let mut buffer: Vec<u8> = Vec::new... |
use std::{
collections::HashSet,
fmt::Display,
io,
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
sync::Arc,
time::Duration,
};
use log::{debug, error, info, trace, warn};
use tokio::{net::TcpListener, select, time};
use trust_dns_proto::{
op::{header::MessageType, response_code::ResponseCo... |
//https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/
impl Solution {
pub fn count_negatives(grid: Vec<Vec<i32>>) -> i32 {
let mut count_negative = 0;
for i in 0..grid.len() {
for j in 0..grid[i].len() {
count_negative += if grid[i][j] < 0 {... |
use std::fs::File;
use std::io::Read;
struct Param {
mode: u8,
value: i64,
}
impl Param {
fn new(vec: &Vec<i64>, index: usize, param_index: usize) -> Param {
let mode = ((vec[index] / 10i64.pow((param_index + 1) as u32)) % 10) as u8;
let value = vec[index + param_index];
assert!(m... |
//! APIs for testing.
#![cfg(test)]
use crate::error;
use crate::plan::SchemaProvider;
use chrono::{DateTime, NaiveDate, Utc};
use datafusion::common::Result as DataFusionResult;
use datafusion::datasource::empty::EmptyTable;
use datafusion::datasource::provider_as_source;
use datafusion::logical_expr::{AggregateUDF, ... |
//! Tests auto-converted from "sass-spec/spec/libsass/precision"
#[allow(unused)]
use super::rsass;
#[allow(unused)]
use rsass::precision;
/// From "sass-spec/spec/libsass/precision/default"
#[test]
fn default() {
assert_eq!(
rsass(
"test {\r\n foo: 0.4999 round(0.4999);\r\n bar: 0.49999 roun... |
use crate::cpu::Cpu;
use crate::display::{Display, FONT};
use crate::keyboard::Keyboard;
use crate::ram::Ram;
use crate::color::Color;
pub struct Chip8Machine {
display: Display,
keyboard: Keyboard,
cpu: Cpu,
memory: Ram,
}
impl Chip8Machine {
pub fn new() -> Chip8Machine {
Chip8Machine {
... |
extern crate futures;
extern crate stream_combinators;
extern crate tokio;
extern crate tokio_stdin;
extern crate tokio_timer;
use futures::stream::{once, Stream};
use std::time::Duration;
use stream_combinators::SequenceStream;
use tokio_stdin::spawn_stdin_stream_unbounded;
use tokio_timer::Interval;
enum Event {
... |
fn main() {
#[derive(Debug)]
enum IpAddrKind {
V4,
V6,
}
#[derive(Debug)]
struct IpAddr {
kind: IpAddrKind,
address: String,
}
let home = IpAddr {
kind: IpAddrKind::V4,
address: String::from("127.0.0.1"),
};
let loopback = IpAddr {
kind: IpAddrKind::V6,
address: Stri... |
use pyo3::prelude::PyResult;
use pyo3::prelude::PyErr;
use pyo3::prelude::PyModule;
use pyo3::prelude::pyfunction;
use pyo3::prelude::pymodule;
use pyo3::prelude::Python;
use pyo3::wrap_pyfunction;
use pyo3::exceptions;
#[pyfunction]
fn hello() -> PyResult<String> {
Err(PyErr::new::<exceptions::TypeError, _>("Erro... |
#[doc = "Reader of register MMC_RX_INTERRUPT"]
pub type R = crate::R<u32, super::MMC_RX_INTERRUPT>;
#[doc = "Reader of field `RXCRCERPIS`"]
pub type RXCRCERPIS_R = crate::R<bool, bool>;
#[doc = "Reader of field `RXALGNERPIS`"]
pub type RXALGNERPIS_R = crate::R<bool, bool>;
#[doc = "Reader of field `RXUCGPIS`"]
pub type... |
extern crate iron;
extern crate router;
extern crate postgres;
use iron::prelude::*;
use iron::status;
use iron::headers::{Headers, ContentType};
use iron::modifiers::Header;
use router::Router;
//fn doit(req: &mut Request) -> IronResult<Response> {
fn doit(req: &mut Request) -> IronResult<Response> {
Ok(Respons... |
extern crate combine;
extern crate combine_language;
use combine::char::{string, letter, digit, spaces};
use combine::{Parser, many};
use combine_language::{Assoc, Fixity, expression_parser};
//TODO unignore once its stops ICEing
use self::Expr::*;
#[derive(PartialEq, Debug)]
enum Expr {
Id(String),
Num(i64),... |
#[cfg(target_arch = "x86")]
use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;
// 参考:
// https://www.intel.cn/content/dam/www/public/us/en/documents/white-papers/carry-less-multiplication-instruction-in-gcm-mode-paper.pdf
#[derive(Debug, Clone)]
pub struct GHash {
h: __m128i,
}
im... |
#[doc = "Reader of register CTRL"]
pub type R = crate::R<u8, super::CTRL>;
#[doc = "Writer for register CTRL"]
pub type W = crate::W<u8, super::CTRL>;
#[doc = "Register CTRL `reset()`'s with value 0"]
impl crate::ResetValue for super::CTRL {
type Type = u8;
#[inline(always)]
fn reset_value() -> Self::Type {... |
#[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::MODE {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut ... |
#![deny(clippy::all)]
mod enumrepr;
mod enumselect;
mod game;
mod model;
mod score;
mod selection;
mod semantic;
mod words;
pub use game::start_app;
|
fn main() {
GameState::new();
}
/// Next we create an enum that will represent all the possible
/// directions that our entity could move.
#[derive(Debug, Copy, Clone)]
enum Direction {
Up,
Down,
Left,
Right,
}
/// Now we define a struct that will hold an entity's position on our game board
/// or... |
// RGB standard library
// Written in 2020 by
// Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warr... |
// 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 your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Small vectors i... |
use anyhow::{bail, Result};
use serde::{Deserialize, Serialize};
use std::net::{IpAddr, SocketAddr};
pub struct CPlaneApi {
auth_endpoint: &'static str,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct DatabaseInfo {
pub host: IpAddr, // TODO: allow host name here too
pub port: u16,
pub dbname: S... |
use crate::{
protocol::parts::option_part::{OptionId, OptionPart},
HdbResult,
};
#[cfg(feature = "sync")]
use byteorder::{LittleEndian, ReadBytesExt};
use std::{fmt::Debug, hash::Hash};
#[derive(Debug)]
pub struct MultilineOptionPart<T: OptionId<T> + Debug + Eq + PartialEq + Hash>(Vec<OptionPart<T>>);
impl<T:... |
//! Functions, such as factorisation and similar computations, which require use of prime numbers
//! to be calculated.
use segment;
use sieve::Sieve;
impl Sieve {
/// Uses trial division to determine if the given number is prime.
fn trial_division(&self, n: u64) -> bool {
for p in self.iter() {
... |
const SQUARES: u32 = 64;
pub fn square(s: u32) -> u64 {
assert!(s > 0 && s < 65, "Square must be between 1 and 64");
2u64.pow(s-1)
}
pub fn total() -> u64 {
(1..SQUARES+1).map(|n| square(n)).sum()
}
|
pub mod anm;
pub mod arc;
pub mod arz;
|
use crate::{ast::Symbol, parser::ParserSettings, AST};
use std::collections::{BTreeMap, BTreeSet};
mod forward;
mod rewrite;
mod traits;
mod utils;
#[derive(Debug, Clone)]
pub struct Runner {
parser: ParserSettings,
ctx: Context,
}
#[derive(Debug, Clone, Default)]
pub struct Context {
index: usize,
i... |
use actix_web::Query;
use actix_web::{http::StatusCode, FromRequest, HttpResponse, Path};
use bigneon_api::controllers::events;
use bigneon_api::controllers::events::SearchParameters;
use bigneon_api::models::{
Paging, PagingParameters, PathParameters, Payload, SearchParam, SortingDir,
UserDisplayTicketType,
};... |
use proptest::prop_assert_eq;
use proptest::strategy::{Just, Strategy};
use liblumen_alloc::erts::term::prelude::*;
use crate::erlang::is_record_3::result;
use crate::test::strategy;
#[test]
fn without_tuple_returns_false() {
run!(
|arc_process| {
(
strategy::term::is_not_tupl... |
extern crate in_order;
use std::io::fs::PathExtensions;
use in_order::config::{Config, Do, Undo};
use std::io::{File, Command, TempDir};
static CONFIG_0: &'static str =
r##"command = "sh"
root = "tests/sequence"
[special]
[special.3]
command = "special"
current_action = 0
"##;
static CONFIG_3: &'static str =
r##"co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.