text stringlengths 8 4.13M |
|---|
use ggez::{GameResult, Context};
use ggez::graphics::{Font, Point2, Text, Vector2};
use globals::*;
use hex::{DirectionIndex, HexPoint};
use text::*;
#[derive(Debug)]
pub struct Assets {
lap1_a: Text,
lap1_b: Text,
lap2: Text,
lap3: Text,
win_a: Text,
win_b: Text,
lose_a: Text,
... |
use wasm_bindgen::prelude::*;
/// Arrow Schema representing a Parquet file.
#[derive(Debug, Clone)]
#[wasm_bindgen]
pub struct ArrowSchema(arrow2::datatypes::Schema);
#[wasm_bindgen]
impl ArrowSchema {
/// Clone this struct in wasm memory.
#[wasm_bindgen]
pub fn copy(&self) -> Self {
ArrowSchema(s... |
// 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 ... |
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use carnelian::{
make_message, set_node_color, AnimationMode, App, AppAssistant, Color, ViewAssistant,
ViewAssistantContext, ViewAssistantPtr, View... |
fn fib(n: u32) -> u32 {
let mut a = 1;
let mut b = 1;
for _ in 1..n {
let t = a;
a += b;
b = t;
}
return a;
}
#[test]
fn fib_values() {
let expected = vec![1, 1, 2, 3, 5, 8, 13];
let actual = (0..7).map(fib).collect::<Vec<_>>();
assert_eq!(actual, expected);
}
... |
//required in order for near_bindgen macro to work outside of lib.rs
use crate::interface::ContractFinancials;
use crate::*;
use crate::{
domain::RedeemLock,
interface::{contract_state::ContractState, AccountManagement},
interface::{Operator, StakingService},
};
use near_sdk::near_bindgen;
#[near_bindgen]
... |
use crate::static_kv::mod_test;
pub mod static_kv {
pub fn mod_test() {
println!("test")
}
}
fn main() {
mod_test();
println!("Hello, world!");
}
|
use std::collections::HashMap;
use crate::types::{Expression, ExpressionType, ProgramError, SourceCodeLocation, Statement, StatementType, Pass};
pub struct Resolver<'a> {
check_used: bool,
scopes: Vec<HashMap<&'a str, bool>>,
uses: Vec<HashMap<&'a str, usize>>,
locations: Vec<HashMap<&'a str, &'a Sourc... |
fn main(){
//ベクトルを用意する
let mut vec = vec![1,2,3];
// ベクトルの要素への参照を取り出す → i
// ベクトルをイミュータブルに参照する
for i in vec.iter(){
//すでにベクトルはイミュータブルに参照されているので、
//ここでベクトルを変更しようとするとエラーが発生(だってイミュータブルなものを書き換えようとしている)
//実際、これを許すと無限ループになってしまう。
vec.push(i*2);
}
} |
//! REST API of the node
mod server;
pub mod v0;
pub use self::server::{Error, Server};
use std::sync::{Arc, Mutex, RwLock};
use crate::blockchain::{Blockchain, Branch};
use crate::fragment::Logs;
use crate::secure::enclave::Enclave;
use crate::settings::start::{Error as ConfigError, Rest};
use crate::stats_counte... |
use crate::headers::{Error, Header, HeaderName, HeaderValue};
use cookie::Cookie as HTTPCookie;
use hyper::http::header;
use itertools::Either;
use std::iter;
use std::ops::Deref;
static COOKIE: &HeaderName = &header::COOKIE;
static SET_COOKIE: &HeaderName = &header::SET_COOKIE;
#[derive(Clone, Debug, PartialEq)]
pub... |
use crate::error::ArweaveError as Error;
use async_trait::async_trait;
use base64::{self, encode_config};
use ring::rand::{SecureRandom, SystemRandom};
use std::{fs as fsstd, path::PathBuf};
use tokio::fs;
pub struct TempDir(pub PathBuf);
#[async_trait]
pub trait TempFrom<T> {
async fn from_str(path_str: &str) ->... |
use bindings::emscripten::*;
use common::Vec2i;
use console;
use std::mem::transmute;
use std::ptr::null;
pub enum Event {
Resize(Vec2i),
Down(Vec2i),
Up(Vec2i),
Move(Vec2i),
}
pub fn init_event_queue(queue: *mut Vec<Event>) {
unsafe {
let evt_ptr = transmute(queue);
on_resize(0, null(), evt_ptr);
emscr... |
use super::address::*;
use super::func::{DefinedFunctionInstance, InstIndex};
use super::module::ModuleIndex;
use super::value::Value;
#[derive(Debug)]
pub enum StackValueType {
Label,
Value,
Activation,
}
const DEFAULT_CALL_STACK_LIMIT: usize = 1024;
#[derive(Debug)]
pub enum Error {
PopEmptyStack,
... |
/// Struktur program sederhana pada rust
///
fn main() {
println!("Hello world");
}
|
use std::io;
use std::time::Duration;
use nats::connect;
fn main() -> io::Result<()> {
let nc = connect("localhost")?;
let sub = nc.subscribe("sample")?;
let res = nc.publish("sample", "test-message-1")?;
println!("*** published: {:?}", res);
if let Some(msg) = sub.next() {
println!("***... |
use {flush, Body, RecvBody};
use futures::{Future, Poll, Stream};
use futures::future::{Executor, Either, Join, MapErr};
use h2::{self, Reason};
use h2::server::{Server as Accept, Handshake, Respond};
use http::{self, Request, Response};
use tokio_io::{AsyncRead, AsyncWrite};
use tower::{NewService, Service};
use std... |
use std::convert::TryInto;
use std::num::NonZeroU8;
use std::ops::{Div, Mul, Sub};
use nalgebra::{distance_squared, Point2, RealField, Scalar, distance};
use num_traits::{CheckedSub, Zero};
use num_traits::{FromPrimitive, ToPrimitive};
use wasm_bindgen::UnwrapThrowExt;
use super::node::Node;
#[derive(Clone, Debug, H... |
pub mod is_unique;
pub mod is_permutation;
pub mod urlify;
pub mod palindrome_permutation;
pub mod one_away;
pub mod string_compression;
pub mod rotation;
pub mod zero_matrix;
pub mod is_rotation; |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialSurfaceInfo(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialSurfaceInfo {
type Vtable = ISpat... |
use projecteuler::helper;
use projecteuler::square_roots;
fn main() {
//gets optimized into a nop I think
helper::check_bench(|| {
solve();
});
assert_eq!(solve(), 5482660);
dbg!(solve());
}
//what is the distance from P_n to P_{n+1}?
/*
P_{n+1}-P_n = (n+1)(3n+3-1)/2 - n(3n-1)/2
P_{n+1}-P_n... |
/*
http://rosalind.info/problems/ba1c/
Find the reverse complement of a string
Sample:
AAAACCCGGT
ACCGGGTTTT
*/
extern crate rosalind_rust;
use rosalind_rust::Cli;
use std::io::{prelude::*, BufReader};
use structopt::StructOpt;
fn revcomp(s: &str) -> String {
s.chars()
.map(|c| match c {
'... |
use std::{cell::RefCell, iter::Peekable, rc::Rc};
use crate::{
algorithm::{Components, ComponentsIter, Sorted, SortedIntersect, SortedIntersectIter},
properties::{WithRegion, WithRegionCore},
records::Bed3,
ChromName,
};
pub struct InvertedIter<C, A>
where
A: Iterator + Sorted,
C: ChromName + ... |
#![warn(clippy::all)]
mod vtable;
mod driver;
mod va_backend;
use va_backend as va;
mod vdpau;
mod vdpau_loader;
mod vdpau_x11;
mod xlib;
const VDPAU_MAX_PROFILES: usize = 12;
const VDPAU_MAX_ENTRYPOINTS: usize = 5;
const VDPAU_MAX_CONFIG_ATTRIBUTES: usize = 10;
const VDPAU_MAX_IMAGE_FORMATS: usize = 10;
const VDPAU_... |
use std::collections::HashMap;
use std::thread;
use std::time::Duration;
use std::io;
extern crate iris;
use iris::portfire;
use iris::script::{self, Cue};
extern crate clap;
use clap::App;
#[cfg(feature="tts")]
use iris::tts::TTS;
fn main() {
let args = App::new("IRIS")
.args_from_usage("
... |
#[doc = "Reader of register CR"]
pub type R = crate::R<u32, super::CR>;
#[doc = "Writer for register CR"]
pub type W = crate::W<u32, super::CR>;
#[doc = "Register CR `reset()`'s with value 0"]
impl crate::ResetValue for super::CR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
... |
#[doc = "Reader of register SECWM2R2"]
pub type R = crate::R<u32, super::SECWM2R2>;
#[doc = "Writer for register SECWM2R2"]
pub type W = crate::W<u32, super::SECWM2R2>;
#[doc = "Register SECWM2R2 `reset()`'s with value 0x0f00_0f00"]
impl crate::ResetValue for super::SECWM2R2 {
type Type = u32;
#[inline(always)]... |
#[allow(unused_imports)]
use proconio::{marker::*, *};
#[fastout]
fn main() {
input! {
n: i32,
k: i32,
}
let mut count = 0;
for red in 1..=n {
for blue in 1..=n {
let white = k - red - blue;
if 1 <= white && white <= n {
count += 1;
... |
use os;
use game;
use gl::types::GLfloat;
use std::num::Float;
pub fn render(window: &os::Window, world: &game::World) -> Vec<GLfloat> {
let mut vertices: Vec<GLfloat> = vec![];
vertices.push_all(&render_player(&world.player)[..]);
vertices.push_all(&render_player(&world.opponent)[..]);
vertices.push_a... |
use std::{
alloc::{self, Layout},
sync::RwLock,
mem
};
use owning_ref::*;
/// An error that may be due to insertion of duplicate key.
#[derive(Debug)]
pub struct DupErr {
pub key: i32
}
#[derive(Clone, Debug)]
struct Item<V> {
key: i32,
value: V,
state: CellState
}
/// Thread-safe HashMa... |
#![allow(clippy::type_complexity)]
use crate::components::{
keyboard_movement::{Direction, KeyboardMovement},
speed::Speed,
};
use oxygengine::prelude::*;
// system that moves tagged entities.
pub struct KeyboardMovementSystem;
impl<'s> System<'s> for KeyboardMovementSystem {
type SystemData = (
... |
// 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 gl::types::*;
use glfw::{Action, Key};
use sepia::app::*;
use sepia::buffer::*;
use sepia::framebuffer::*;
use sepia::shaderprogram::*;
use sepia::texture::*;
use sepia::vao::*;
use std::ptr;
#[rustfmt::skip]
const VERTICES: &[GLfloat; 15] =
&[
-0.5, -0.5, 0.0, 0.0, 0.0,
0.5, -0.5, 0.0, 1.0, 0.0... |
use rustc_serialize::json;
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
use curl::http;
use dependency_container::base_project_dependency::BaseProjectDependencyContainer;
#[derive(RustcDecodable, RustcEncodable, Debug)]
pub struct ComposerJson {
pub require: HashMap<String, String>
}
... |
/// Implementation of the Snake game for an 8x8 LED Dot Screen.
use crate::{Components, Direction};
use crate::peripherals::{Dot, DotScreen, InputSignal, JoyStickSignal};
// Constants for the Snake game.
// The x-coordinate of the egg starting location.
const EGG_START_X: usize = 1;
// The y-coordinate of the egg ... |
// 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... |
pub fn my_sqrt(x: i32) -> i32 {
let result = x >> 1;
println!("{}", result);
result
}
#[cfg(test)]
mod my_sqrt_tests {
use super::*;
#[test]
fn my_sqrt_test_one() {
assert_eq!(my_sqrt(8), 2);
assert_eq!(my_sqrt(36), 6);
}
}
|
pub mod directory_entry;
pub mod fat32_device_driver;
pub mod get_bytes;
pub mod mbr_device_driver;
pub mod partition;
|
// revisions: base nll
// ignore-compare-mode-nll
//[nll] compile-flags: -Z borrowck=mir
fn thing(x: impl FnOnce(&u32)) {}
fn main() {
let f = |_| ();
thing(f);
//[nll]~^ ERROR mismatched types
//~^^ ERROR implementation of `FnOnce` is not general enough
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::wlan::types::{
ClientStateSummary, ConnectionState, DisconnectStatus, NetworkIdentifier, NetworkState,
SecurityType, WlanClientState,
};... |
fn main() {
let input = include_str!("day1.txt");
let mut v: Vec<i32> = Vec::new();
let split = input.split("\n");
let mut counter_upper = 0;
for s in split {
v.push(s.parse().unwrap());
}
for mut module in v {
while module > 0 {
counter_upper += fuel_required(... |
use crate::{
channel::{Channel, ChannelId, Completer, Packet, Performer},
execution_controller::{ExecutionController, RunLimitedNumberOfInstructions},
fiber::{self, EndedReason, Fiber, FiberId, Panic, VmEnded},
heap::{Data, Function, Heap, HirId, InlineObject, SendPort, Struct, SymbolId, Tag},
lir::... |
use std::collections::HashMap;
use serde::Serialize;
use crate::types::{RunInTerminalRequestArgumentsKind, StartDebuggingRequestKind};
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all(deserialize = "camelCase", serialize = "snake_case"))]
pub struct RunInTerminalRequestArguments {
/// What kind of terminal ... |
use nalgebra::Scalar;
use crate::Pose;
pub mod basic;
pub mod kld;
pub trait ParticleResampler<N: Scalar> {
fn resample(&self, poses: &[Pose<N>], weights: &[N]) -> Vec<Pose<N>>;
}
|
#[doc = "Reader of register EMR2"]
pub type R = crate::R<u32, super::EMR2>;
#[doc = "Writer for register EMR2"]
pub type W = crate::W<u32, super::EMR2>;
#[doc = "Register EMR2 `reset()`'s with value 0"]
impl crate::ResetValue for super::EMR2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Typ... |
// 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 ... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - FDCAN Core Release Register"]
pub fdcan_crel: FDCAN_CREL,
#[doc = "0x04 - FDCAN Core Release Register"]
pub fdcan_endn: FDCAN_ENDN,
_reserved2: [u8; 4usize],
#[doc = "0x0c - FDCAN Data Bit Timing and Prescaler Regis... |
use {
crate::types::{HitRecord, Ray, Vec3},
rand::Rng,
};
pub trait Material: Send + Sync {
fn scatter(&self, ray: &Ray, hit_rec: &HitRecord) -> (Vec3, Option<Ray>);
}
pub struct Lambertian {
albedo: Vec3,
}
impl Lambertian {
pub fn new(a: Vec3) -> Self {
Self { albedo: a }
}
}
impl ... |
mod common;
use std::panic;
use std::path::Path;
use std::str;
use std::str::FromStr as _;
use rusty_git::object::{ObjectData, TreeEntry};
use rusty_git::repository::Repository;
use self::common::*;
#[test]
fn reading_head_produces_same_result_as_libgit2() {
run_test(|path| {
git_init(path).expect("fail... |
use projecteuler::{helper, square_roots};
fn main() {
helper::check_bench(|| {
square_roots::get_approximation(2, 1000);
});
//dbg!(find_minimum_solution_in_x_4(&7, &61));
assert_eq!(solve(100, 100), 40886);
}
fn solve(n: usize, precision: u32) -> usize {
return (1..)
.map(|x| (x *... |
pub struct Solution;
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Tree,
pub right: Tree,
}
use std::cell::RefCell;
use std::rc::Rc;
type Tree = Option<Rc<RefCell<TreeNode>>>;
impl Solution {
pub fn has_path_sum(root: Tree, sum: i32) -> bool {
match root.as_re... |
//! Tests CLI commands
use std::fs::read_dir;
use std::sync::Arc;
use std::time::{Duration, Instant};
use arrow_util::assert_batches_sorted_eq;
use assert_cmd::Command;
use assert_matches::assert_matches;
use futures::FutureExt;
use lazy_static::lazy_static;
use predicates::prelude::*;
use tempfile::tempdir;
use test_... |
pub mod filter;
pub mod utils;
|
#[cfg(feature = "poll-driver")]
use crate::alsa::AsyncWriter;
use crate::alsa::{
ChannelArea, Configurator, Error, HardwareParameters, HardwareParametersMut, Result, Sample,
SoftwareParameters, SoftwareParametersMut, State, Stream, Writer,
};
use crate::libc as c;
use crate::unix::poll::PollFlags;
use alsa_sys ... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "UI_Xaml_Automation_Peers")]
pub mod Peers;
#[cfg(feature = "UI_Xaml_Automation_Provider")]
pub mod Provider;
#[cfg(feature = "UI_Xaml_Automation_Text")]
pub mod Text;
#[repr(... |
use std::fs::File;
use std::io::Read;
fn main() -> Result<(), std::io::Error> {
let mut contents = String::new();
let file_open = File::open("hello_world.rs");
let mut file = match file_open {
Ok(f) => f,
Err(e) => {
eprintln!("Fehler beim öffnen! {:?}", e);
}
};
... |
use projecteuler::permutation;
fn main() {
assert_eq!(
permutation::permutation_rank_mod(solve(3), 1_000_000_007),
2294
);
assert_eq!(
permutation::permutation_rank_mod(solve(5), 1_000_000_007),
641839204
);
assert_eq!(solve_2(3, 1_000_000_007), 2294);
assert_eq!... |
use anyhow::Result;
use std::process::Command;
fn main() -> Result<()> {
build_ui_files();
vergen::EmitBuilder::builder()
.all_cargo()
.all_build()
.all_git()
.all_rustc()
.git_describe(true, false, Some("v*"))
.emit()?;
Ok(())
}
fn build_ui_files() {
... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type ISpeechRecognitionConstraint = *mut ::core::ffi::c_void;
pub type SpeechContinuousRecognitionCompletedEventArgs = *mut ::core::ffi::c_void;
#[repr(tran... |
use Board;
use StoneColor;
pub fn apply(mut board: &mut Board, color: &StoneColor, coord: (u32, u32)) -> Result<bool, &'static str> {
place_stone(&mut board, &color, coord)
}
fn place_stone(board: &mut Board, color: &StoneColor, coord: (u32, u32)) -> Result<bool, &'static str> {
match board.place(&color, coor... |
extern crate rand;
use rand::Rng;
fn main() {
let mut rng = rand::thread_rng();
let n1: u8 = rng.gen();
} |
#[doc = "Reader of register MPCBB2_VCTR27"]
pub type R = crate::R<u32, super::MPCBB2_VCTR27>;
#[doc = "Writer for register MPCBB2_VCTR27"]
pub type W = crate::W<u32, super::MPCBB2_VCTR27>;
#[doc = "Register MPCBB2_VCTR27 `reset()`'s with value 0"]
impl crate::ResetValue for super::MPCBB2_VCTR27 {
type Type = u32;
... |
extern crate picl;
use picl::repl::Repl;
fn main() {
let mut repl = Repl::new();
repl.repl()
}
|
use actix_files as fs;
use actix_session::Session;
use actix_web::http::StatusCode;
use actix_web::{get, http, post, web, App, HttpRequest, HttpResponse, HttpServer, Responder};
use askama::Template;
use rand::{distributions::Alphanumeric, Rng};
use redis::{Commands, Connection};
use serde::Deserialize;
use std::sync::... |
use mtree::MTree;
pub fn node_count(tree: &MTree) -> usize {
let sum_child_nodes: usize = tree.get_children().iter().map(|t| node_count(t)).sum();
1 + sum_child_nodes
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_node_count() {
assert_eq!(node_count(&MTree::leaf('a')), 1);
... |
fn main() {
let _s = String::new();
let data = "initial contents";
let _s = data.to_string();
let _s = "initial contents".to_string();
let mut s = String::from("foo");
s.push_str("bar");
let mut s1 = String::from("foo");
let s2 = "bar";
s1.push_str(s2);
println!("s2 is {}", s2... |
// 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 ... |
extern crate chrono;
extern crate env_logger;
#[macro_use]
extern crate log;
extern crate robohome_crypto;
extern crate robohome_shared;
extern crate serde_json;
extern crate uuid;
extern crate warp;
use chrono::{Duration, Utc};
use robohome_crypto::{
bufify_string, gen_pair as gen_auth_key_pair, gen_shared_secret... |
//! __Rust Life Search__, or __rlifesrc__,
//! is a Game of Life pattern searcher written in Rust.
//!
//! The program is based on David Bell's
//! [lifesrc](https://github.com/DavidKinder/Xlife/tree/master/Xlife35/source/lifesearch)
//! and Jason Summers's [WinLifeSearch](https://github.com/jsummers/winlifesearch/),
/... |
use proconio::input;
fn main() {
input! {
n: usize,
k: usize,
points: [(i64, i64); n],
};
if k == 1 {
println!("Infinity");
return;
}
// (y2 - y1) * x - (x2 - x1) * y + (x2 - x1) * y1 - (y2 - y1) * x1 = 0
let mut x_axis = Vec::new();
let mut y_axis ... |
mod vertex;
use ecs::{Entity, ECS};
use renderer::{
RendererDevice, Texture, TextureFiltering, TextureStorage, TextureWrapping,
};
use std::path::Path;
use vertex::Vertex;
pub fn load(ecs: &mut ECS) {
let context = ecs.resources.get_mut::<RendererDevice>().unwrap();
let idx1 = context.register_texture(Te... |
use {Poll, Async};
use stream::Stream;
/// A stream which emits single element and then EOF.
///
/// This stream will never block and is always ready.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Once<T, E>(Option<Result<T, E>>);
/// Creates a stream of single element
///
/// ```rust
/... |
use crate::{DocBase, VarType};
const DESCRIPTION: &'static str = r#"
Difference between current value and previous, `x - x[y]`.
"#;
const PINE_FN_ARGUMENTS: &'static str = "
**source (series(float))**
**length (int)** Offset from the current bar to the previous bar. Optional, if not given, length = 1 is used.
";
pub... |
use anyhow::Result;
fn part1(input: &[u64]) -> u64 {
let (_, ones, threes) =
input
.iter()
.fold((0, 0, 0), |(last, ones, threes), next| match next - last {
1 => (*next, ones + 1, threes),
2 => (*next, ones, threes),
3 => (*next, ones,... |
/*!
Prefix-types are types that derive StableAbi along with the
`#[sabi(kind(Prefix(....)))]` helper attribute.
This is mostly intended for **vtables** and **modules**.
Prefix-types cannot directly be passed through ffi,
instead they must be converted to the type declared with `prefix_ref= Foo_Ref`,
and then pass tha... |
use serde::{Deserialize, Serialize};
use crate::domain::CodePoint;
use crate::domain::Location;
#[repr(C)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CodeFunction {
pub name: String,
// todo: thinking in access
pub vars: Vec<String>,
pub start: CodePoint,
pub end: CodePoint
}
impl... |
mod handshake;
use self::handshake::Handshaker;
use super::{options::ConnectionPoolOptions, Connection};
use crate::{client::auth::Credential, error::Result, runtime::HttpClient};
/// Contains the logic to establish a connection, including handshaking, authenticating, and
/// potentially more.
#[derive(Debug)]
pub(su... |
use grid_search::around;
use procon_reader::ProconReader;
#[rustfmt::skip]
const DIRS: [(isize, isize); 20] = [
(-2, -1), (-2, 0), (-2, 1),
(-1, -2), (-1, -1), (-1, 0), (-1, 1), (-1, 2),
(0, -2), (0, -1), (0, 1), (0, 2),
(1, -2), (1, -1), (1, 0), (1, 1), (1, 2),
(2, -1), (2, 0), (2, 1),
];
const U... |
extern crate iron;
extern crate router;
extern crate time;
use iron::prelude::*;
use iron::status;
use router::Router;
fn main() {
let mut router = Router::new();
router.get("/", handler, "index");
Iron::new(router).http("localhost:3000").unwrap();
fn handler(_: &mut Request) -> IronResult<Response>... |
#[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::INTENSET {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w ... |
use std::thread;
use std::sync::{Arc,Mutex};
use std::vec::Vec;
fn main() {
let number_of_threads = 20;
let mut thread_names = Arc::new(Mutex::new(Vec::new()));
for n in 0..number_of_threads {
let thread_name = format!("thread-{}", n + 1);
thread_names.push(thread_name);
}
fo... |
fn largest_prime_factor(n: u64) -> u64 {
let mut largest_factor = 1;
let mut num = n;
while num % 2 == 0 {
largest_factor = 2;
num = num / 2;
}
let mut factor = 3;
let mut max_factor = (num as f64).sqrt() as u64 + 1;
while num > 1 && factor <= max_factor {
while nu... |
use std::io::{Read, Result as IOResult};
use crate::PrimitiveRead;
pub struct Visibility {
pub num_clusters: i32,
pub byte_offsets: [Box<[i32]>; 2]
}
impl Visibility {
pub fn read(reader: &mut dyn Read) -> IOResult<Self> {
let num_clusters = reader.read_i32()?;
let mut byte_offsets: [Box<[i32]>; 2] = [
... |
#![cfg(feature = "with-deprecated")]
#![allow(deprecated)]
#![deprecated(since = "0.1.4",
note = "replaced with `BiLock` in many cases, otherwise slated \
for removal due to confusion")]
use std::prelude::v1::*;
use std::sync::Arc;
use std::cell::UnsafeCell;
use task_impl;
// One c... |
// 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.
#![feature(repr_align_enum)]
#![allow(warnings)]
use zerocopy::AsBytes;
struct IsAsBytes<T: AsBytes>(T);
// Fail compilation if `$ty: !AsBytes`.
macro_r... |
use crate::context::RpcContext;
use crate::felt::RpcFelt;
use anyhow::{anyhow, Context};
use pathfinder_common::{BlockId, ContractAddress, StorageAddress, StorageValue};
use serde::Deserialize;
#[derive(Deserialize, Debug, PartialEq, Eq)]
pub struct GetStorageAtInput {
pub contract_address: ContractAddress,
pu... |
use std::fs;
#[test]
fn validate_3_1() {
assert_eq!(algorithm("src/day_3/input_test.txt"), 7);
}
fn algorithm(file_location: &str) -> usize {
let contents = fs::read_to_string(file_location).unwrap();
let values: Vec<&str> = contents.lines().collect();
let max_cols = values.first().unwrap().len();
... |
#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(unused_variables)]
extern crate bytes;
extern crate env_logger;
extern crate futures;
extern crate http;
extern crate h2;
extern crate tokio_connect;
extern crate tokio_core;
extern crate tower;
extern crate tower_grpc;
extern crate tower_h2;
use std::net::Socke... |
// 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::any::Any;
use tikv_jemalloc_ctl::{epoch, stats};
use metric::{Attributes, MetricKind, Observation, Reporter};
/// A `metric::Instrument` that reports jemalloc memory statistics, specifically:
///
/// - a u64 gauge called "jemalloc_memstats_bytes"
#[derive(Debug, Clone)]
pub struct JemallocMetrics {
acti... |
use std::fmt::{Debug, Formatter};
use async_trait::async_trait;
use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::Client;
use serde::Deserialize;
use crate::error::Error;
mod code;
mod password;
mod token;
pub use code::CodeAuthenticator;
pub use password::PasswordAuthenticator;
pub use token::TokenAuthen... |
extern crate criterion;
extern crate libdna;
use crate::libdna::libdna_ffi;
use crate::libdna::native;
use criterion::{criterion_group, criterion_main, Criterion};
use std::os::raw::c_char;
const LENGTH: usize = 1_000_000;
fn mutc(c: char) -> char {
const order: [char; 5] = ['A', 'C', 'G', 'T', 'A'];
let in... |
/// `mbe` (short for Macro By Example) crate contains code for handling
/// `macro_rules` macros. It uses `TokenTree` (from `ra_tt` package) as the
/// interface, although it contains some code to bridge `SyntaxNode`s and
/// `TokenTree`s as well!
macro_rules! impl_froms {
($e:ident: $($v:ident), *) => {
$... |
#![feature(arbitrary_enum_discriminant)]
#![feature(associated_type_bounds)]
#![feature(try_blocks)]
#![feature(generic_associated_types)]
#![feature(let_else)]
#![feature(once_cell)]
pub mod linker;
pub mod meta;
pub mod passes;
use firefly_llvm as llvm;
use firefly_mlir as mlir;
/// Perform initialization of MLIR/... |
fn main() {
panic!("panic message {can} be formatted", can = "CaN");
}
|
use af;
use af::{Array, Dim4, MatProp};
use std::sync::{Arc, Mutex};
use utils;
use activations;
use params::Params;
use layer::Layer;
pub struct RNN {
pub input_size: usize,
pub output_size: usize,
}
impl Layer for RNN
{
fn forward(&self, params: Arc<Mutex<Params>>, inputs: &Array) -> Array
{
// get a h... |
use crate::constants;
pub fn parse_cli_args<'a>() -> clap::ArgMatches<'a> {
clap::app_from_crate!()
.arg(
clap::Arg::with_name("bind")
.value_name("address:port")
.help("IP address and port to bind")
.short("b")
.long("bind")
... |
// 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 crate::lttp::{
logic::{
Availability,
RandoLogic,
Rule,
},
Dungeon,
DungeonState,
GameState,
Medallion,
};
use serde::{
Deserialize,
Serialize,
};
use std::cmp::{
max,
min,
};
use tracing::error;
use ts_rs::TS;
#[derive(Debug, Copy, Clone, Serialize, ... |
use std::{default::Default, ffi::CStr, num::NonZeroU32, ops::Deref, sync::mpsc};
// use winit::window::Window;
use ash::vk;
use vulkayes_core::{ash, log, memory::device::naive::NaiveDeviceMemoryAllocator, prelude::*};
use vulkayes_window::winit::winit;
use winit::{event_loop::EventLoop, window::Window};
#[macro_use]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.