text stringlengths 8 4.13M |
|---|
#[doc = "Reader of register MISR"]
pub type R = crate::R<u32, super::MISR>;
#[doc = "Reader of field `ISEM0`"]
pub type ISEM0_R = crate::R<bool, bool>;
#[doc = "Reader of field `ISEM1`"]
pub type ISEM1_R = crate::R<bool, bool>;
#[doc = "Reader of field `ISEM2`"]
pub type ISEM2_R = crate::R<bool, bool>;
#[doc = "Reader ... |
fn main() {
let text = "YELLOW SUBMARINE";
println!("{:?}",pad(text.as_bytes().to_vec(),10));
}
fn pad(text: Vec<u8>, length: u8) -> Vec<u8>{
let mut padded = text.clone();
let mut i = 1;
while (length as i8*i-text.len() as i8) <0 {
i += 1;
}
let padding = length*i as u8-text.len() ... |
// 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 eventual::{Future, Async, Complete};
use mio::{Token, EventLoop, Sender, TryRead, TryWrite, EventSet};
use mio::tcp::TcpStream;
use mio::util::Slab;
use mio;
use std::net::{SocketAddr,IpAddr,Ipv4Addr};
use std::collections::BTreeMap;
use std::borrow::Cow;
use std::error::Error;
use def::CqlEvent;
use error::{RCRes... |
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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.
use crate::lexer::preproc... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type CompositionConditionalValue = *mut ::core::ffi::c_void;
pub type CompositionInteractionSourceCollection = *mut ::core::ffi::c_void;
pub type ICompositi... |
// 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 ... |
#![allow(non_camel_case_types)]
#![allow(unused_unsafe)]
use crate::ctx::WasiCtx;
use crate::fdentry::Descriptor;
use crate::host;
use crate::sys::errno_from_host;
use crate::sys::host_impl;
use std::fs::File;
use std::os::windows::prelude::{AsRawHandle, FromRawHandle};
use std::path::{Component, Path};
/// Normalize... |
use rocket_contrib::json::JsonValue;
use crate::db;
use crate::util;
pub fn start_server() {
log::info!("Starting HTTP service...");
rocket::ignite()
.mount("/", routes![init_sh, pubkey_users])
.launch();
}
/// curl -H "Content-Type: text/plain" http://127.0.0.1:8000/init.sh
#[get("/init.sh")... |
pub fn count_primes(n: i32) -> i32 {
let mut acc = 0;
if n <= 1 {
return acc;
}
let mut n = n;
while n > 1 {
if n % 2 != 0 {
acc += 1;
}
n -= 1;
}
acc
}
#[cfg(test)]
mod count_primes_tests {
use super::*;
#[test]
fn count_primes_t... |
use std::borrow::Cow;
use crate::spec::TargetOptions;
use Arch::*;
#[allow(dead_code, non_camel_case_types)]
#[derive(Copy, Clone)]
pub enum Arch {
Armv7,
Armv7s,
Arm64,
I386,
X86_64,
X86_64_macabi,
Arm64_macabi,
Arm64_sim,
}
fn target_abi(arch: Arch) -> &'static str {
match arch ... |
#[doc = "Reader of register CSR"]
pub type R = crate::R<u32, super::CSR>;
#[doc = "Writer for register CSR"]
pub type W = crate::W<u32, super::CSR>;
#[doc = "Register CSR `reset()`'s with value 0"]
impl crate::ResetValue for super::CSR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
... |
pub mod aot_generator;
pub mod code_builder;
pub mod compile;
pub mod context;
pub mod gcc;
|
#![feature(box_syntax)]
#[cfg(test)]
extern crate quickcheck;
#[cfg(test)]
#[macro_use(quickcheck)]
extern crate quickcheck_macros;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::rc::Rc;
use leetcode_rust::bst::BinarySearchTree;
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub str... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "Gaming_Input")]
pub mod Input;
#[cfg(feature = "Gaming_Preview")]
pub mod Preview;
#[cfg(feature = "Gaming_UI")]
pub mod UI;
#[cfg(feature = "Gaming_XboxLive")]
pub mod XboxLive;
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use failure::{err_msg, format_err, Error};
pub fn expect_eq<T>(expected: &T, actual: &T) -> Result<(), Error>
where
T: std::fmt::Debug + std::cmp::Par... |
pub mod add;
pub mod apply;
pub mod current;
pub mod edit;
pub mod init;
pub mod list;
pub mod remove;
pub mod show;
|
pub mod redis_cache_decorators;
pub use redis_cache_decorators::*; |
use crate::*;
use std::cell::RefCell;
mod control_test;
use control_test::*;
mod thread_test;
use thread_test::*;
mod freeing_test;
use freeing_test::*;
mod other;
#[derive(Default)]
pub struct TestControlPanel {
window: Window,
layout: FlexboxLayout,
controls_test_button: Button,
thread_test_bu... |
#[derive(Debug,Clone,Copy,PartialEq,Eq,Hash)]
pub struct Health {
pub hp: usize,
pub max_hp: usize,
pub temp_hp: usize,
}
impl Health {
pub fn take_damage(&mut self, mut amount: usize) {
if self.temp_hp > 0 {
if amount > self.temp_hp {
amount -= self.temp_hp;
... |
use yew::prelude::*;
use yewdux::prelude::*;
use yewtil::NeqAssign;
use yew_router::components::RouterAnchor;
use crate::app::AppRoute;
use yew::services::storage::{
StorageService,
Area,
};
use crate::store::reducer_account::{
AppDispatch,
DataAccountAction,
// DataAccount,
};
use crate::types::{
... |
use std::fs::read_to_string;
use std::path::Path;
use itertools::Itertools;
use lazy_static::lazy_static
lazy_static! {
static ref REGEXP: Regex = Regex::new(r"(?P<x>\d+)-(?P<y>\d+) (?P<letter>[a-z]): (?P<password>[a-z]+)").unwrap();
}
fn parse_input(input: &str) -> Vec<i32> {
input.lines()
.filter_m... |
extern crate base64;
mod hamming;
mod utils;
use std::fs::File;
use std::io::prelude::*;
use hamming::*;
use utils::*;
fn main() {
println!("reading file...");
let text1 = get_text_from_file("/home/zeegomo/Documents/hack/cryptopals/set1/challenge6/src/data.txt");
println!("decoding base64...");
let ... |
use std::str;
use std::thread::sleep;
use std::time::{Duration, SystemTime};
use quick_xml::de::from_str;
use reqwest::Client;
use crate::errors::NSError;
use crate::nation::Nation;
use crate::region::Region;
const NS_API_URL: &str = "https://www.nationstates.net/cgi-bin/api.cgi";
const RATE_LIMIT: usize = 49;
const... |
//! A module providing the wrapping driver for a custom runner.
use std::env;
use std::ffi::OsString;
use std::io;
use std::path::Path;
use std::process::Command;
/// The prefix line for the target host output.
const HOST_PREFIX: &[u8] = b"host: ";
/// Act as a driver for `cargo run`/`cargo test`, but with special r... |
use std::fmt::{Debug, Display};
use std::path::PathBuf;
use crate::traits::{CorpusDelta, Pool, SaveToStatsFolder, Stats};
use crate::{CSVField, CompatibleWithObservations, PoolStorageIndex, ToCSV};
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct Unit;
struct Input {
input_id: PoolStorageIndex,
complexity:... |
/// Verify and extract login from an email address
///
/// Validated that an email address is formatted correctly, and extracts
/// everything before the @ symble.
///
use errors::*;
use regex::Regex;
fn extract_login(input: &str) -> Option<&str> {
lazy_static! {
static ref RE: Regex = Regex::new(r"(?x)
... |
pub mod token;
pub use token::*;
pub mod commands;
pub mod queries;
// Holds specific repository contracts that aren't pulled from the generic ones in domain_patterns crates.
pub mod repository_contracts;
|
mod connection;
mod error;
mod go_away;
mod peer;
mod ping_pong;
mod settings;
mod streams;
pub(crate) use self::connection::{Config, Connection};
pub(crate) use self::error::Error;
pub(crate) use self::peer::{Peer, Dyn as DynPeer};
pub(crate) use self::streams::{StreamRef, OpaqueStreamRef, Streams};
pub(crate) use se... |
//! Probabilistic distributions.
use rand::distributions::Distribution;
use rand::Rng;
use rand_distr::weighted::WeightedIndex;
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
/// A distribution used for random assignments.
pub struct AssignmentDistribution<T: Hash> {
weights: HashMap<T, f32>,
... |
use rust::prelude::*;
use types::{uchar_t, char_t, int_t, size_t};
#[no_mangle]
pub unsafe extern fn memcpy(dst: *mut char_t, src: *const char_t, n: size_t) -> *mut char_t {
for i in range(0, n as isize).rev() {
*offset_mut(dst, i) = *offset(src, i);
}
dst
}
#[no_mangle]
pub unsafe extern fn memm... |
use crate::beam::{Beam, BeamIntersect};
pub struct BeamIter {
beam: Beam,
}
impl Beam {
const fn iter(self) -> BeamIter {
BeamIter { beam: self }
}
}
impl Iterator for BeamIter {
type Item = BeamIntersect;
fn next(&mut self) -> Option<Self::Item> {
self.beam.next_intersect()
... |
#![feature(test)]
extern crate peg_syntax_ext;
use peg_syntax_ext::peg_file;
extern crate test;
use test::Bencher;
peg_file!(parser("expr.rustpeg"));
#[bench]
fn expr(b: &mut Bencher) {
let bench_str = "1+2+3+4*5*6^7^8^(0^1*2+1)";
b.bytes = bench_str.len() as u64;
b.iter(|| {
parser::expr(bench_str).unwrap();... |
// Copyright (c) Calibra Research
// SPDX-License-Identifier: Apache-2.0
use super::*;
use std::collections::BTreeMap;
#[cfg(test)]
#[path = "unit_tests/configuration_tests.rs"]
mod configuration_tests;
impl EpochConfiguration {
pub fn new(voting_rights: BTreeMap<Author, usize>) -> Self {
let total_votes... |
//! A TCP proxy server. Forwards connections from port 8081 to port 8080.
use futures::prelude::*;
use futures::try_join;
use runtime::net::{TcpListener, TcpStream};
#[runtime::main]
async fn main() -> std::io::Result<()> {
let mut listener = TcpListener::bind("127.0.0.1:8081")?;
println!("Listening on {}", l... |
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
use std::collections::HashSet;
use regex::Regex;
fn acc_instr(op : &str, val : i64) -> i64 {
if op == "+" {
return val;
} else {
return -val;
}
}
fn jmp_instr(op : &str, val : i64, curr : usize) -> usize {
let n : i64 = acc... |
// Copyright 2014-2018 Optimal Computing (NZ) Ltd.
// Licensed under the MIT license. See LICENSE for details.
use std::mem;
use num_traits::NumCast;
/// A trait for floating point numbers which computes the number of representable
/// values or ULPs (Units of Least Precision) that separate the two given values.
pub... |
use crate::{AbstractIndices, Buffer, BufferDataUsage, Context, RenderPrimitiveType};
/// Represents WebGL programs.
///
/// This type should only be implemented by the [`Program`][super::Program] macro.
pub trait Program: Sized {
/// The struct generated for storing attributes.
/// Always `#[repr(C)]`.
typ... |
use crate::utils::StatefulList;
use std::collections::{BTreeMap, HashMap};
use chrono::{
Date,
DateTime,
offset::Utc};
use std::error::Error;
use ::reqwest::blocking::Client;
use graphql_client::{reqwest::post_graphql_blocking as post_graphql, GraphQLQuery};
#[derive(Debug)]
struct Transaction {
amoun... |
pub struct User {
pub id: i32,
pub data: UserData,
}
#[derive(Debug)]
pub struct UserData {
pub user_id: i64,
pub name: String,
}
|
use crate::{feed_generator::FeedGenerator, feed_worker::FeedWorker};
use actix_web::{middleware::Logger, App};
use log::error;
use std::collections::BTreeMap;
pub trait SourceBuilder {
fn build_source() -> Source;
}
pub struct Source {
pub prefix: &'static str,
pub entries: BTreeMap<&'static str, FeedWork... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
pub const ATA_FLAGS_48BIT_COMMAND: u32 = 8u32;
pub const ATA_FLAGS_DATA_IN: u32 = 2u32;
pub const ATA_FLAGS_DATA_OUT: u32 = 4u32;
pub const ATA_FLAGS_DRDY_REQUIRED: u32 = 1u32;
pub const ATA_... |
//! Asynchronous ARQ Connections
//!
//! This module exposes the `ArqStream` type which implements
//! `AsyncRead` and `AsyncWrite`. These traits enable access
//! to RF connections much as one would use a TCP socket.
use std::fmt;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::t... |
use core::fmt;
use core::iter::{Iterator, Peekable};
use core::mem;
use core::ops::Add;
use core::str::Bytes;
mod tests;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ByteIdx(usize);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ByteLen(usize);
#[derive(Debug, Clone, PartialEq, Eq)]... |
use std::str::SplitTerminator;
pub trait StrUtils {
fn digits(&self) -> Vec<u8>;
fn paragraphs(&self) -> SplitTerminator<&str>;
}
impl StrUtils for str {
fn digits(&self) -> Vec<u8> {
self.chars().map(|c| c as u8 - 0x30).collect()
}
fn paragraphs(&self) -> SplitTerminator<&str> {
... |
use proconio::input;
fn main() {
input! {
a:i32,
b:i32,
}
println!("{}", a / b);
}
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
#[repr(transparent)]
pub struct AudioRenderCategory(pub i32);
impl AudioRenderCategory {
pub const Other: Self = Self(0i32);
pub const ForegroundOnlyMed... |
mod expand_records;
mod expand_substitutions;
mod expand_unqualified_calls;
use std::collections::BTreeMap;
use std::sync::Arc;
use firefly_diagnostics::*;
use firefly_pass::Pass;
use crate::ast;
use self::expand_records::ExpandRecords;
use self::expand_substitutions::ExpandSubstitutions;
use self::expand_unqualifi... |
//! Small amethyst demo app to illustrate sprite ordering
//!
//! Press Space to change the order of the sprites.
use amethyst::{
Logger,
GameDataBuilder,
Application,
SimpleState,
StateData,
GameData,
StateEvent,
SimpleTrans,
Trans,
core::{
Transform,
TransformB... |
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use itertools::Itertools;
use crate::seq;
use crate::utl;
#[derive(Debug)]
pub struct Sequence {
pub class_name: String,
pub codebook_size: u32,
pub symbols: Vec<u16>,
}
impl Sequence {
pub fn show(&mut self, opts: &seq::SeqShowOpts) ... |
#[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::ACCTL1 {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &... |
use binary_search::BinarySearch;
use procon_reader::ProconReader;
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let n: usize = rd.get();
let mut g = vec![vec![]; n];
for i in 1..n {
let p: usize = rd.get();
g[p - 1].push(i);
}
let ... |
extern crate regex;
use std::io;
use std::fs;
use std::io::BufRead;
use std::path::Path;
use std::collections::HashMap;
use regex::Regex;
use std::ops::RangeInclusive;
fn main() {
let input = parse_input();
let invalid_sum: usize = input.other_tickets.iter().map(|ticket| {
ticket.values.iter().filter... |
use std::{convert::TryFrom, fmt, ops};
use crate::util::{floats_equal, round, round_stp, round_tp};
use super::WorldCoords;
const TILE_POSITION_PRECISION: usize = 8;
#[derive(Clone)]
pub struct TilePosition {
pub x: u32,
pub y: u32,
// Offset from Tile Lower Left
pub rel_x: f32,
pub rel_y: f32,
... |
// 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 {
crate::{capability::*, model::*},
by_addr::ByAddr,
cm_rust::ComponentDecl,
futures::{future::BoxFuture, lock::Mutex},
std::{
... |
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::Term;
#[native_implemented::function(erlang:get/1)]
pub fn result(process: &Process, key: Term) -> Term {
process.get_value_from_key(key)
}
|
use std::io::Cursor;
use std::str;
use neon::prelude::*;
use manifest::{Manifest, NodeId, NodeType, StreamType};
use uuid::Uuid;
use ::MANIFEST;
/// Creates a "name" node on the given node.
///
/// # Arguments
/// [
/// node ID: String,
/// default language: String,
/// names: Array of objects
/// ]
///... |
table! {
transfers (id) {
id -> Int4,
amount -> Text,
currency -> Text,
to_name -> Text,
to_number -> Text,
to_email -> Text,
complete -> Bool,
}
}
table! {
users (id) {
id -> Int4,
first_name -> Varchar,
last_name -> Varchar,
... |
#[doc = "Reader of register DMASBMR"]
pub type R = crate::R<u32, super::DMASBMR>;
#[doc = "Writer for register DMASBMR"]
pub type W = crate::W<u32, super::DMASBMR>;
#[doc = "Register DMASBMR `reset()`'s with value 0x0101_0000"]
impl crate::ResetValue for super::DMASBMR {
type Type = u32;
#[inline(always)]
f... |
#![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 ISocialDashboardItemUpdater(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISocialDashboardItemUpdater {
typ... |
use crate::error::{GameError, GameResult};
use winit::window::Fullscreen;
use winit::monitor::{VideoMode, MonitorHandle};
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub enum FullscreenMode {
Exclusive,
Borderless,
}
impl FullscreenMode {
pub(crate) fn from_raw(fullscreen: Fullscreen) -> Self {
... |
fn main() {
println!("Hello, world!");
// Sharing Versus Mutation
// Rust ensures no ref will ever point to a variable that has gone out of scope. But there are other ways to introduce dangling pointers. Example:
let v = vec![4, 8, 19, 27, 34, 10];
let r = &v;
let aside = v; // move vector t... |
use std::fmt;
use super::{Expression, Operand};
#[derive(Debug, Clone, PartialEq)]
pub struct Expr {
pub operand: Option<Operand>,
pub args: Vec<Box<Expression>>,
pub parent: Option<Box<Expr>>,
}
impl fmt::Display for Expr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut disp;... |
#[macro_export]
macro_rules! uri_path {
{ $( $val:ident )/ * } => {
$crate::uri::UriPath::new(vec![ $( stringify!($val) ),* ])
}
}
#[macro_export]
macro_rules! uri_params {
{ $( $key:ident => $val:expr ),* } => {
{
use std::collections::HashMap;
use std::borrow::Cow;... |
use std::cmp::{min, max};
#[derive(Debug)]
enum Spell {
MagicMissile = 0,
Drain = 1,
Shield = 2,
Poison = 3,
Recharge = 4,
}
static SPELLS: [Spell; 5] = [Spell::MagicMissile, Spell::Drain, Spell::Shield, Spell::Poison, Spell::Recharge];
static SPELLCOST: [i32; 5] = [53, 73, 113, 173, 229];
const ... |
use crate::{
device::Device,
hook::{Hook, Op},
};
use failure::{bail, Error};
#[derive(Debug)]
pub enum Token {
String(String),
Immediate(i64),
Open,
Close,
Comma,
}
impl Token {
fn as_string(self) -> Result<String, Error> {
match self {
Token::String(string) => Ok(... |
use iced::{button, Button, Row, Element, Sandbox, Settings, Text, scrollable, Scrollable,
HorizontalAlignment, Length, Column, Container, text_input, TextInput, Align, Radio};
const DEFAULT_SIZE: (u32, u32) = (450, 250);
const MIN_SIZE: (u32, u32) = (400, 200);
const PAD: u16 = 10;
const SPACING: u16 = 5;
... |
fn main() {
/*
A macro is code that writes code, saving us some time.
println! and vec! are macros that generate code, they do not have a pre-determined number of parameters.
*/
// Here is the vector macro which is a declarative macro
{
// This brings the macro into the scope when the create is imp... |
extern crate error_chain;
extern crate serde_derive;
extern crate serde_json;
extern crate reqwest;
use super::card;
error_chain! {
foreign_links {
Reqwest(reqwest::Error);
}
}
pub struct QueryResults {
pub cards: Vec<card::Card>,
pub not_found: Vec<String>,
}
#[derive(Deserialize, Debug, Cl... |
use crate::mesh::*;
use crate::texture::*;
use nalgebra_glm as glm;
use std::path::{Path, PathBuf};
#[derive(Default)]
pub struct Model {
meshes: Vec<Mesh>,
}
impl Model {
pub fn from_file(path: &str) -> Self {
let path = Path::new(path);
let root_dir = Path::new(path.parent().unwrap());
... |
use std::collections::hash_map::RandomState;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::io;
use employee_list::print::eprint_list;
use employee_list::{run, Command, Employees};
fn main() {
eprint_commands();
let s = RandomState::new();
let mut employees: Employees = HashMap::with_... |
//! Raspberry PI 3 Model B/B+
use bcm2837::{addr::bus_to_phys, atags::Atags};
pub mod emmc;
pub mod irq;
pub mod mailbox;
pub mod serial;
pub mod timer;
pub mod gpu;
use crate::drivers::gpu::fb::{self, ColorDepth, ColorFormat, FramebufferInfo, FramebufferResult};
use crate::consts::{KERNEL_OFFSET};
use core::convert... |
use scrabble_score::*;
use std::collections::HashMap;
#[test]
fn a_is_worth_one_point() {
assert_eq!(score("a"), 1);
}
#[test]
fn scoring_is_case_insensitive() {
assert_eq!(score("A"), 1);
}
#[test]
fn f_is_worth_four() {
assert_eq!(score("f"), 4);
}
#[test]
fn two_one_point_letters_make_a_two_point_wor... |
use crate::object::Object;
use crate::service::*;
use crate::errors::EvalErr;
use std::rc::Rc;
/// The family of functions which names match with pattern `c[ad]{1,4}r`.
pub fn cadr(name: &str, obj: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
let mut obj = expect_1_arg(obj, name)?;
for op in name[1..name... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type BindableVectorChangedEventHandler = *mut ::core::ffi::c_void;
pub type IBindableIterable = *mut ::core::ffi::c_void;
pub type IBindableIterator = *mut ... |
use std::mem::size_of;
enum Never { }
struct ZeroSize;
type NeverFailResult<T> = Result<T, Never>;
type ZeroSizeResult<T> = Result<T, ZeroSize>;
fn main() {
println!("{}", size_of::<u32>()); // 4
println!("{}", size_of::<NeverFailResult<u32>>()); // 4
println!("{}", size_of::<Option<u32>>()); // 8
pr... |
use byteorder::LittleEndian;
use crate::mysql::io::BufExt;
#[derive(Debug)]
pub struct ColumnCount {
pub columns: u64,
}
impl ColumnCount {
pub(crate) fn read(mut buf: &[u8]) -> crate::Result<Self> {
let columns = buf.get_uint_lenenc::<LittleEndian>()?.unwrap_or(0);
Ok(Self { columns })
... |
//! Unix user, group, and process identifiers.
//!
//! # Safety
//!
//! The `Uid`, `Gid`, and `Pid` types can be constructed from raw integers,
//! which is marked unsafe because actual OS's assign special meaning to some
//! integer values.
#![allow(unsafe_code)]
use crate::{backend, io};
use alloc::vec::Vec;
#[cfg(l... |
#[derive(Debug)]
struct User {
id: u64,
name: String,
sex: String,
age: u8,
}
struct Ipv4 {
ip: String,
ip_address: (u8, u8, u8, u8),
host: String,
}
struct Ipv6 {
ip: String,
ip_address: (u8, u8, u8, u8, u8, u8),
host: String,
}
enum Ip {
V4(Ipv4),
V6(Ipv6),
}
pub en... |
pub mod action;
pub mod contract;
pub mod permission;
pub mod print;
pub mod system;
pub mod table;
pub use action::*;
pub use contract::*;
pub use permission::*;
pub use print::*;
pub use system::*;
pub use table::*;
|
use super::{FromArgs, FuncArgs};
use crate::{
convert::ToPyResult, object::PyThreadingConstraint, Py, PyPayload, PyRef, PyResult,
VirtualMachine,
};
use std::marker::PhantomData;
/// A built-in Python function.
// PyCFunction in CPython
pub type PyNativeFn = py_dyn_fn!(dyn Fn(&VirtualMachine, FuncArgs) -> PyRe... |
mod boxed;
mod path_ext;
mod types;
#[cfg(feature = "util")]
pub mod util;
pub use self::{
boxed::{vfs_box, vpath_box, VFSBox, VFileBox, VMetadataBox, VPathBox},
path_ext::VPathExt,
types::*,
};
|
pub struct Solution;
impl Solution {
pub fn simplify_path(path: String) -> String {
let mut dir_names = Vec::new();
let mut cur_dir = String::new();
for c in path.chars().skip(1) {
if c == '/' {
dir_names.push(cur_dir);
cur_dir = String::new();
... |
// 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.
//! The special-purpose event loop used by the network manager.
//!
//! This event loop takes in events from Admin and State FIDL,
//! and implements handl... |
use buckets::Buckets;
use metric::{AggregationMethod, LogLine, TagMap, Telemetry};
use sink::{Sink, Valve};
use source::report_telemetry;
use std::cmp;
use std::io::Write as IoWrite;
use std::mem;
use std::net::TcpStream;
use std::net::ToSocketAddrs;
use std::string;
use std::sync;
use time;
pub struct Wavefront {
... |
// Copyright 2018 Evgeniy Reizner
//
// 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... |
use radio::RadioStation;
use radio::song::{radio_1live, radio_ndr, radio_antenne};
/// Radiostations
pub const RADIOSTATIONS: &'static [RadioStation] = &[
// Stations 1LIVE and WDR
RadioStation {
name: "1LIVE",
shorthand: "1live",
url: "http://www.wdr.de/radio/radiotext/streamtitle_1liv... |
use {Status};
#[repr(C)]
pub struct SimpleFileSystem
{
revision: u64,
open_volume: extern "win64" fn(&SimpleFileSystem, &mut *mut super::File) -> Status,
}
impl super::Protocol for SimpleFileSystem
{
fn guid() -> ::Guid {
::Guid( 0x0964e5b22,0x6459,0x11d2, [0x8e,0x39,0x00,0xa0,0xc9,0x69,0x72,0x3b] )
}
unsafe ... |
use std::env;
use std::io::{self, Error, ErrorKind, Write};
use std::process::{exit, Command, Stdio};
extern crate serde;
#[macro_use]
extern crate serde_json;
use serde_json::Value;
fn main() {
query_watchman().unwrap_or_else(|e| {
eprintln!("{}", e);
exit(1);
})
}
fn query_watchman() -> i... |
use std::collections::HashMap;
use bip78::bitcoin::util::psbt::PartiallySignedTransaction as Psbt;
use bitcoincore_rpc::RpcApi;
fn main() {
let mut args = std::env::args_os();
let _program_name = args
.next()
.expect("not even program name given");
let port = args
.next()
.e... |
extern crate ply_rs;
use ply_rs as ply;
/// Sometimes only the meta data is interesting to us.
/// Reading the entire ply file would be a waste of ressources.
fn main() {
// set up a reader, in this a file.
let path = "example_plys/greg_turk_example1_ok_ascii.ply";
let f = std::fs::File::open(path).unwrap(... |
#[macro_use]
extern crate lazy_static;
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Result, Write};
use std::path::Path;
#[allow(dead_code)]
mod encoding;
use encoding::{
get_base_enc, Encoding, SYMBOL_ENCODING, ZAPFDINGBATS_ENCODING,
};
fn write_cond(
f: &mut BufWriter<File>... |
#[macro_export]
macro_rules! path {
(@segment $s:literal) => {
$crate::PathSegment::Literal($s)
};
(@segment $i:ident) => {
$crate::PathSegment::Dynamic($crate::PathParam::new(
stringify!($i),
$crate::PathToken::Any,
))
};
(@segment [$i:ident ~ $re:lit... |
//! Implements basic compacting. This is based on the compaction logic from
//! diffy by Brandon Williams.
use std::ops::Index;
use crate::{DiffOp, DiffTag};
use super::utils::{common_prefix_len, common_suffix_len};
use super::DiffHook;
/// Performs semantic cleanup operations on a diff.
///
/// This merges similar... |
use crate::*;
#[derive(Clone, Copy, Debug, Default)]
#[cfg_attr(feature = "with_serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "with_serde", serde(default))]
pub(crate) struct State {
/// Positive offset means scrolling down/right
offset: Vec2,
show_scroll: bool, // TODO: defa... |
use rust_blog::handlers::*;
use actix_web::{get, App, HttpResponse, HttpServer, Responder};
use diesel::r2d2::ConnectionManager;
use diesel::MysqlConnection;
use dotenv::dotenv;
use std::env;
#[get("/")]
async fn index() -> impl Responder {
HttpResponse::Ok().body("hello there, ya filthy animal!")
}
#[actix_web:... |
//! # Amiwô - API Documentation
//!
//! Hello, and welcome to the core Amiwô API documentation!
//! This crate contains both various utility functions & types
//! that I used across several applications as well as
//! contribution to other third party modules
//!
//! # Structure
//! Each module in this library is held... |
use specs::{DispatcherBuilder, Dispatcher, World};
use shrev::{EventChannel};
use crate::event;
pub mod systems;
pub mod viewport;
use crate::app::viewport::Viewport;
pub struct App {
pub world: World,
pub update_dispatcher: Dispatcher<'static, 'static>,
}
impl App {
pub fn new(mut update_dispatcher: Di... |
use glib::translate::*;
use javascriptcore_sys;
glib_wrapper! {
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GlobalContextRef(Shared<javascriptcore_sys::_JSGlobalContextRef>);
match fn {
ref => |ptr| javascriptcore_sys::JSGlobalContextRetain(ptr),
unref => |ptr| javasc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.