file_name large_stringlengths 4 69 | prefix large_stringlengths 0 26.7k | suffix large_stringlengths 0 24.8k | middle large_stringlengths 0 2.12k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
issue-2834.rs | // Copyright 2012 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 ... | () {
let (s, c) = streamp::init();
let streams: ~[streamp::client::open<int>] = ~[c];
error!("%?", streams[0]);
}
pub fn main() {
//os::getenv("FOO");
rendezvous();
}
| rendezvous | identifier_name |
thread.rs | // Verifies that ThreadSanitizer is able to detect a data race in heap allocated
// memory block.
//
// Test case minimizes the use of the standard library to avoid its ambiguous
// status with respect to instrumentation (it could vary depending on whatever
// a function call is inlined or not).
//
// The conflicting d... | (c: *mut libc::c_void) -> *mut libc::c_void {
unsafe {
let c: *mut u32 = c.cast();
*c += 1;
__tsan_testonly_barrier_wait(&raw mut BARRIER);
ptr::null_mut()
}
}
fn main() {
unsafe {
__tsan_testonly_barrier_init(&raw mut BARRIER, 2);
let c: *mut u32 = Box::into... | start | identifier_name |
thread.rs | // Verifies that ThreadSanitizer is able to detect a data race in heap allocated
// memory block.
//
// Test case minimizes the use of the standard library to avoid its ambiguous
// status with respect to instrumentation (it could vary depending on whatever
// a function call is inlined or not).
//
// The conflicting d... | {
unsafe {
__tsan_testonly_barrier_init(&raw mut BARRIER, 2);
let c: *mut u32 = Box::into_raw(Box::new(1));
let mut t: libc::pthread_t = mem::zeroed();
libc::pthread_create(&mut t, ptr::null(), start, c.cast());
__tsan_testonly_barrier_wait(&raw mut BARRIER);
*c += 1;... | identifier_body | |
thread.rs | // Verifies that ThreadSanitizer is able to detect a data race in heap allocated | // status with respect to instrumentation (it could vary depending on whatever
// a function call is inlined or not).
//
// The conflicting data access is de-facto synchronized with a special TSAN
// barrier, which does not introduce synchronization from TSAN perspective, but
// is necessary to make the test robust. Wi... | // memory block.
//
// Test case minimizes the use of the standard library to avoid its ambiguous | random_line_split |
child_ps.rs | use kekbit::api::ReadError::*;
use kekbit::api::{EncoderHandler, Reader, Writer};
use kekbit::core::*;
use log::{error, info};
use nix::sys::wait::waitpid;
use nix::unistd::{fork, getpid, ForkResult};
use simple_logger::SimpleLogger;
use std::path::Path;
use std::process::exit;
use std::result::Result;
const ITERATION... | // let to_wr = m.as_bytes();
// let len = to_wr.len() as u32;
// let res = writer.write(&to_wr, len);
// match res {
// WriteResult::Success(_) => (),
// err => {
// error!("Write failed {:?}", err);
// ... | random_line_split | |
child_ps.rs | use kekbit::api::ReadError::*;
use kekbit::api::{EncoderHandler, Reader, Writer};
use kekbit::core::*;
use log::{error, info};
use nix::sys::wait::waitpid;
use nix::unistd::{fork, getpid, ForkResult};
use simple_logger::SimpleLogger;
use std::path::Path;
use std::process::exit;
use std::result::Result;
const ITERATION... | panic!("Read failed!!!!");
}
},
}
}
info!(
"We read {} bytes in {} messages. Channel state is {:?}",
reader.position(),
msg_count,
reader.exhausted()
);
Ok(())
}
fn main() {
SimpleLogger::new().init().unwrap();... | {
info!("Creating reader porcess ...{}", getpid());
let mut reader = try_shm_reader(&Path::new(Q_PATH), 1000, 2000, 200).unwrap();
let mut stop = false;
let mut msg_count = 0;
while !stop {
match reader.try_read() {
Ok(Some(_)) => msg_count += 1,
Ok(None) => (),
... | identifier_body |
child_ps.rs | use kekbit::api::ReadError::*;
use kekbit::api::{EncoderHandler, Reader, Writer};
use kekbit::core::*;
use log::{error, info};
use nix::sys::wait::waitpid;
use nix::unistd::{fork, getpid, ForkResult};
use simple_logger::SimpleLogger;
use std::path::Path;
use std::process::exit;
use std::result::Result;
const ITERATION... | () -> Result<(), ()> {
info!("Creating reader porcess...{}", getpid());
let mut reader = try_shm_reader(&Path::new(Q_PATH), 1000, 2000, 200).unwrap();
let mut stop = false;
let mut msg_count = 0;
while!stop {
match reader.try_read() {
Ok(Some(_)) => msg_count += 1,
Ok... | run_reader | identifier_name |
run.rs | use std::env;
use std::fs::{read_link};
use std::io::{stdout, stderr};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use libc::pid_t;
use argparse::{ArgumentParser, Store, List, StoreTrue};
use unshare::{Command};
use container::uidmap::{map_users};
use super::setup;
use super::Wrapper;
use path_util::PathEx... | .add_argument("command", Store,
"Command to run inside the container");
ap.refer(&mut args)
.add_argument("args", List,
"Arguments for the command");
ap.stop_on_first_argument(true);
match ap.parse(cmdline, &mut stdout(), &mut stderr()) {
... | {
let mut container: String = "".to_string();
let mut command: String = "".to_string();
let mut args = Vec::<String>::new();
let mut copy = false;
{
let mut ap = ArgumentParser::new();
ap.set_description("
Runs arbitrary command inside the container
");
... | identifier_body |
run.rs | use std::env;
use std::fs::{read_link};
use std::io::{stdout, stderr};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use libc::pid_t;
use argparse::{ArgumentParser, Store, List, StoreTrue};
use unshare::{Command};
use container::uidmap::{map_users};
use super::setup;
use super::Wrapper;
use path_util::PathEx... | Ok(s) => Ok(convert_status(s)),
Err(e) => Err(format!("Error running {:?}: {}", cmd, e)),
}
} | }
match cmd.status() { | random_line_split |
run.rs | use std::env;
use std::fs::{read_link};
use std::io::{stdout, stderr};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use libc::pid_t;
use argparse::{ArgumentParser, Store, List, StoreTrue};
use unshare::{Command};
use container::uidmap::{map_users};
use super::setup;
use super::Wrapper;
use path_util::PathEx... | (wrapper: &Wrapper, cmdline: Vec<String>, user_ns: bool)
-> Result<i32, String>
{
let mut container: String = "".to_string();
let mut command: String = "".to_string();
let mut args = Vec::<String>::new();
let mut copy = false;
{
let mut ap = ArgumentParser::new();
ap.set_descript... | run_command_cmd | identifier_name |
issue-30438-b.rs | // Copyright 2016 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 ... | <'a> {
s: &'a String
}
impl <'a> Index<usize> for Test<'a> {
type Output = Test<'a>;
fn index(&self, _: usize) -> &Self::Output {
&Test { s: &self.s}
//~^ ERROR: borrowed value does not live long enough
}
}
fn main() {
let s = "Hello World".to_string();
let test = Test{s: &s};
... | Test | identifier_name |
issue-30438-b.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | //
// 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.
// Modified regr... | // http://rust-lang.org/COPYRIGHT. | random_line_split |
mod.rs | /*!
* Normalization processes a parse tree until it is in suitable form to
* be converted to the more canonical form. This is done as a series of
* passes, each contained in their own module below.
*/
use grammar::parse_tree as pt;
use grammar::repr as r;
pub type NormResult<T> = Result<T, NormError>;
#[derive(C... | mod resolve;
// Expands macros and expressions
//
// X =...1 Comma<X> (X Y Z)...2
//
// to
//
// X =...1 `Comma<X>` `(X Y Z)`...2
// `Comma_X`: Vec<<X>> =...;
// `(X Y Z)` = X Y Z;
//
// AFTER THIS POINT: No more macros, macro references, guarded
// alternatives, repeats, or expr symbols, though type i... |
// Resolve identifiers into terminals/nonterminals etc. | random_line_split |
mod.rs | /*!
* Normalization processes a parse tree until it is in suitable form to
* be converted to the more canonical form. This is done as a series of
* passes, each contained in their own module below.
*/
use grammar::parse_tree as pt;
use grammar::repr as r;
pub type NormResult<T> = Result<T, NormError>;
#[derive(C... |
let grammar = try!(resolve::resolve(grammar));
let grammar = try!(macro_expand::expand_macros(grammar));
let grammar = try!(token_check::validate(grammar));
let types = try!(tyinfer::infer_types(&grammar));
lower::lower(grammar, types)
}
// These are executed *IN ORDER*:
// Check most safety cond... | { try!(prevalidate::validate(&grammar)); } | conditional_block |
mod.rs | /*!
* Normalization processes a parse tree until it is in suitable form to
* be converted to the more canonical form. This is done as a series of
* passes, each contained in their own module below.
*/
use grammar::parse_tree as pt;
use grammar::repr as r;
pub type NormResult<T> = Result<T, NormError>;
#[derive(C... | (grammar: pt::Grammar, validate: bool) -> NormResult<r::Grammar> {
if validate { try!(prevalidate::validate(&grammar)); }
let grammar = try!(resolve::resolve(grammar));
let grammar = try!(macro_expand::expand_macros(grammar));
let grammar = try!(token_check::validate(grammar));
let types = try!(tyin... | normalize_helper | identifier_name |
mod.rs | /*!
* Normalization processes a parse tree until it is in suitable form to
* be converted to the more canonical form. This is done as a series of
* passes, each contained in their own module below.
*/
use grammar::parse_tree as pt;
use grammar::repr as r;
pub type NormResult<T> = Result<T, NormError>;
#[derive(C... |
fn normalize_helper(grammar: pt::Grammar, validate: bool) -> NormResult<r::Grammar> {
if validate { try!(prevalidate::validate(&grammar)); }
let grammar = try!(resolve::resolve(grammar));
let grammar = try!(macro_expand::expand_macros(grammar));
let grammar = try!(token_check::validate(grammar));
... | {
normalize_helper(grammar, false)
} | identifier_body |
trainer.rs | extern crate rand;
use super::super::Grid;
use super::*;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use rand::Rng;
pub fn evaluate_parallel(
n_threads: i32,
problems: &Vec<Grid<Clue>>,
param: EvaluatorParam,
) -> Vec<Option<f64>> {
let res = Arc::new(Mutex::new(vec![None; problems.le... | }
let ret = res.lock().unwrap().clone();
ret
}
pub fn evaluate_score(score: &[Option<f64>], expected: &[f64]) -> f64 {
let mut sx = 0.0f64;
let mut sxx = 0.0f64;
let mut sy = 0.0f64;
let mut sxy = 0.0f64;
let mut n = 0.0f64;
for i in 0..score.len() {
if let Some(x) = score[... | th.join().unwrap(); | random_line_split |
trainer.rs | extern crate rand;
use super::super::Grid;
use super::*;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use rand::Rng;
pub fn | (
n_threads: i32,
problems: &Vec<Grid<Clue>>,
param: EvaluatorParam,
) -> Vec<Option<f64>> {
let res = Arc::new(Mutex::new(vec![None; problems.len()]));
let checked = Arc::new(Mutex::new(0));
let mut threads = vec![];
for _ in 0..n_threads {
let problems = problems.clone();
... | evaluate_parallel | identifier_name |
trainer.rs | extern crate rand;
use super::super::Grid;
use super::*;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use rand::Rng;
pub fn evaluate_parallel(
n_threads: i32,
problems: &Vec<Grid<Clue>>,
param: EvaluatorParam,
) -> Vec<Option<f64>> {
let res = Arc::new(Mutex::new(vec![None; problems.le... | rng.shuffle(&mut move_cand);
for mv in move_cand {
let mut param2 = param;
*param_value(&mut param2, mv.0) += mv.1;
let score2 = evaluate_score(&evaluate_parallel(n_threads, problems, param2), expected);
if current_score > score2 || rng.gen::<f64>() < (... | {
let n_threads = 10;
let mut param = start;
let mut current_score =
evaluate_score(&evaluate_parallel(n_threads, problems, param), expected);
let mut temp = 0.001f64;
let mut rng = rand::thread_rng();
for _ in 0..500 {
let mut move_cand = vec![];
for i in 0..10 {
... | identifier_body |
to_css.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cg;
use darling::{Error, FromMetaItem};
use quote::Tokens;
use syn::{self, DeriveInput, Ident};
use synstructu... | #[derive(Default, FromDeriveInput)]
struct CssInputAttrs {
derive_debug: bool,
function: Option<Function>,
comma: bool,
}
#[darling(attributes(css), default)]
#[derive(Default, FromVariant)]
pub struct CssVariantAttrs {
pub function: Option<Function>,
pub iterable: bool,
pub comma: bool,
pu... |
#[darling(attributes(css), default)] | random_line_split |
to_css.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cg;
use darling::{Error, FromMetaItem};
use quote::Tokens;
use syn::{self, DeriveInput, Ident};
use synstructu... | (name: &str) -> Result<Self, Error> {
let name = syn::parse_ident(name).map_err(Error::custom)?;
Ok(Self { name: Some(name) })
}
}
| from_string | identifier_name |
input-tests.rs | extern crate tiny_http;
use std::io::{Read, Write};
use std::sync::mpsc;
use std::net::Shutdown;
use std::thread;
#[allow(dead_code)]
mod support;
#[test]
fn basic_string_input() {
let (server, client) = support::new_one_server_one_client();
{
let mut client = client;
(write!(client, "GET / ... |
#[test]
fn expect_100_continue() {
let (server, client) = support::new_one_server_one_client();
let mut client = client;
(write!(client, "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nExpect: 100-continue\r\nContent-Type: text/plain; charset=utf8\r\nContent-Length: 5\r\n\r\n")).unwrap();
... | {
let (server, client) = support::new_one_server_one_client();
{
let mut client = client;
(write!(client, "GET / HTTP/1.1\r\nHost: localhost\r\nContent-Type: text/plain; charset=utf8\r\nContent-Length: 3\r\n\r\nhello")).unwrap();
}
let mut request = server.recv().unwrap();
let mut... | identifier_body |
input-tests.rs | extern crate tiny_http;
use std::io::{Read, Write};
use std::sync::mpsc;
use std::net::Shutdown;
use std::thread;
#[allow(dead_code)]
mod support;
#[test]
fn basic_string_input() {
let (server, client) = support::new_one_server_one_client();
{
let mut client = client;
(write!(client, "GET / ... | () {
let (server, client) = support::new_one_server_one_client();
let mut client = client;
(write!(client, "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nExpect: 100-continue\r\nContent-Type: text/plain; charset=utf8\r\nContent-Length: 5\r\n\r\n")).unwrap();
client.flush().unwrap();
le... | expect_100_continue | identifier_name |
input-tests.rs | extern crate tiny_http;
use std::io::{Read, Write};
use std::sync::mpsc;
use std::net::Shutdown;
use std::thread;
#[allow(dead_code)]
mod support;
#[test]
fn basic_string_input() {
let (server, client) = support::new_one_server_one_client();
{
let mut client = client;
(write!(client, "GET / ... | fn unsupported_expect_header() {
let mut client = support::new_client_to_hello_world_server();
(write!(client, "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nExpect: 189-dummy\r\nContent-Type: text/plain; charset=utf8\r\n\r\n")).unwrap();
// client.set_keepalive(Some(3)).unwrap(); FIXME: reena... | #[test] | random_line_split |
diagnostics.rs | // 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 ... | E0284, // cannot resolve type
E0285, // overflow evaluation builtin bounds
E0296, // malformed recursion limit attribute
E0297, // refutable pattern in for loop binding
E0298, // mismatched types between arms
E0299, // mismatched types between arms
E0300, // unexpanded macro
E0301, // ca... | E0282, // unable to infer enough type information about
E0283, // cannot resolve type | random_line_split |
main.rs | extern crate num;
use num::traits::{PrimInt, Zero};
fn | <T: PrimInt + Zero>(cs: &[T], x: T) -> T {
cs.iter()
.rev()
.fold(Zero::zero(), |acc: T, c| (acc * x) + (*c))
}
fn main() {
println!("{}", horner(&[-19i32, 7, -4, 6], 3i32)); // 128
}
#[cfg(test)]
mod tests {
use super::horner;
#[test]
fn test() {
assert_eq!(horner(&[-19i32,... | horner | identifier_name |
main.rs | extern crate num;
use num::traits::{PrimInt, Zero};
fn horner<T: PrimInt + Zero>(cs: &[T], x: T) -> T {
cs.iter()
.rev()
.fold(Zero::zero(), |acc: T, c| (acc * x) + (*c))
}
fn main() {
println!("{}", horner(&[-19i32, 7, -4, 6], 3i32)); // 128
}
#[cfg(test)]
mod tests {
use super::horner;
... | assert_eq!(horner(&[-19i32, 7, -4, 6], 3i32), 128);
assert_eq!(horner(&[-1i32, 7, -4, 6], 0i32), -1);
assert_eq!(horner(&[-0i32, 3], 100i32), 300);
assert_eq!(horner(&[-20i32, 7, 1], 10i32), 150);
assert_eq!(horner(&[-19i32, 7, -4, 0], 5i32), -84);
}
} | fn test() { | random_line_split |
main.rs | extern crate num;
use num::traits::{PrimInt, Zero};
fn horner<T: PrimInt + Zero>(cs: &[T], x: T) -> T |
fn main() {
println!("{}", horner(&[-19i32, 7, -4, 6], 3i32)); // 128
}
#[cfg(test)]
mod tests {
use super::horner;
#[test]
fn test() {
assert_eq!(horner(&[-19i32, 7, -4, 6], 3i32), 128);
assert_eq!(horner(&[-1i32, 7, -4, 6], 0i32), -1);
assert_eq!(horner(&[-0i32, 3], 100i32)... | {
cs.iter()
.rev()
.fold(Zero::zero(), |acc: T, c| (acc * x) + (*c))
} | identifier_body |
regexdna.rs | use test::Bencher;
use {Regex, Text};
// USAGE: dna!(name, pattern, count)
//
// This is same as bench_find, except it always uses the regexdna haystack.
macro_rules! dna {
($name:ident, $pattern:expr, $count:expr) => {
bench_find!(
$name,
$pattern,
$count,
... | dna!(variant7, r"agggt[cgt]aa|tt[acg]accct", 137);
dna!(variant8, r"agggta[cgt]a|t[acg]taccct", 139);
dna!(variant9, r"agggtaa[cgt]|[acg]ttaccct", 197);
dna!(subst1, r"B", 29963);
dna!(subst2, r"D", 29987);
dna!(subst3, r"H", 30004);
dna!(subst4, r"K", 29974);
dna!(subst5, r"M", 29979);
dna!(subst6, r"N", 29959);
dna!(... | dna!(variant5, r"agg[act]taaa|ttta[agt]cct", 466);
dna!(variant6, r"aggg[acg]aaa|ttt[cgt]ccct", 135); | random_line_split |
mon_stream.rs | //! TCP stream with flow statistic monitored
use std::{
io::{self, IoSlice},
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use pin_project::pin_project;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use super::flow::FlowStat;
/// Monitored `ProxyStream`
#[pin_project]
pub struct MonProxyStream<S... | (&self) -> &S {
&self.stream
}
#[inline]
pub fn get_mut(&mut self) -> &mut S {
&mut self.stream
}
}
impl<S> AsyncRead for MonProxyStream<S>
where
S: AsyncRead + Unpin,
{
#[inline]
fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Re... | get_ref | identifier_name |
mon_stream.rs | //! TCP stream with flow statistic monitored
use std::{
io::{self, IoSlice},
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use pin_project::pin_project;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use super::flow::FlowStat;
/// Monitored `ProxyStream`
#[pin_project]
pub struct MonProxyStream<S... |
#[inline]
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.project().stream.poll_flush(cx)
}
#[inline]
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.project().stream.poll_shutdown(cx)
}
... | {
let this = self.project();
match this.stream.poll_write(cx, buf) {
Poll::Pending => Poll::Pending,
Poll::Ready(Ok(n)) => {
this.flow_stat.incr_tx(n as u64);
Poll::Ready(Ok(n))
}
Poll::Ready(Err(err)) => Poll::Ready(Err(err... | identifier_body |
mon_stream.rs | //! TCP stream with flow statistic monitored
use std::{
io::{self, IoSlice},
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use pin_project::pin_project;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use super::flow::FlowStat;
/// Monitored `ProxyStream`
#[pin_project]
pub struct MonProxyStream<S... | Poll::Pending => Poll::Pending,
Poll::Ready(Ok(n)) => {
this.flow_stat.incr_tx(n as u64);
Poll::Ready(Ok(n))
}
Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
}
}
#[inline]
fn poll_flush(self: Pin<&mut Self>, cx: &mut C... | random_line_split | |
brownian.rs | // Copyright 2013 The Noise-rs Developers.
//
// 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 ... |
fn brownian4_for_image(seed: &Seed, point: &Point2<f32>) -> f32 {
Brownian4::new(perlin4, 4).wavelength(16.0).apply(seed, &[point[0], point[1], 0.0, 0.0])
}
| {
Brownian3::new(perlin3, 4).wavelength(16.0).apply(seed, &[point[0], point[1], 0.0])
} | identifier_body |
brownian.rs | // Copyright 2013 The Noise-rs Developers.
//
// 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 ... | extern crate noise;
use noise::{Brownian2, Brownian3, Brownian4, perlin2, perlin3, perlin4, Seed, Point2};
mod debug;
fn main() {
debug::render_png("brownian2.png", &Seed::new(0), 1024, 1024, brownian2_for_image);
debug::render_png("brownian3.png", &Seed::new(0), 1024, 1024, brownian3_for_image);
debug::... | random_line_split | |
brownian.rs | // Copyright 2013 The Noise-rs Developers.
//
// 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 ... | (seed: &Seed, point: &Point2<f32>) -> f32 {
Brownian2::new(perlin2, 4).wavelength(16.0).apply(seed, point)
}
fn brownian3_for_image(seed: &Seed, point: &Point2<f32>) -> f32 {
Brownian3::new(perlin3, 4).wavelength(16.0).apply(seed, &[point[0], point[1], 0.0])
}
fn brownian4_for_image(seed: &Seed, point: &Point... | brownian2_for_image | identifier_name |
mod_dir_recursive.rs | // Copyright 2012-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-MI... | {
assert_eq!(mod_dir_simple::load_another_mod::test::foo(), 10);
} | identifier_body | |
mod_dir_recursive.rs | // Copyright 2012-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-MI... | () {
assert_eq!(mod_dir_simple::load_another_mod::test::foo(), 10);
}
| main | identifier_name |
mod_dir_recursive.rs | // Copyright 2012-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-MI... | // ignore-fast
// Testing that the parser for each file tracks its modules
// and paths independently. The load_another_mod module should
// not try to reuse the'mod_dir_simple' path.
mod mod_dir_simple {
pub mod load_another_mod;
}
pub fn main() {
assert_eq!(mod_dir_simple::load_another_mod::test::foo(), 10... | random_line_split | |
timer.rs | //! Timers that can invoke a callback on an interval.
use widget_prelude::*;
use ::callback::Callback;
/// A timer that can invoke a callback on a configurable interval.
///
/// ##Note: Not a Renderable Widget
/// While this type can be dereferenced and converted to `BaseWidget`, it is *not* a renderable
/// widget... |
/// Stop the timer. The callback will not be invoked until the timer is restarted.
pub fn stop(self) -> Self {
self.set_bool_attribute(::attrs::RUN, false);
self
}
}
impl_widget! { Timer, "timer" }
impl Destroy for Timer {}
| {
self.set_bool_attribute(::attrs::RUN, true);
self
} | identifier_body |
timer.rs | //! Timers that can invoke a callback on an interval.
use widget_prelude::*;
use ::callback::Callback;
/// A timer that can invoke a callback on a configurable interval.
///
/// ##Note: Not a Renderable Widget
/// While this type can be dereferenced and converted to `BaseWidget`, it is *not* a renderable
/// widget... | (self) -> Self {
self.set_bool_attribute(::attrs::RUN, true);
self
}
/// Stop the timer. The callback will not be invoked until the timer is restarted.
pub fn stop(self) -> Self {
self.set_bool_attribute(::attrs::RUN, false);
self
}
}
impl_widget! { Timer, "timer" }
i... | start | identifier_name |
timer.rs | //! Timers that can invoke a callback on an interval.
use widget_prelude::*;
use ::callback::Callback;
/// A timer that can invoke a callback on a configurable interval.
///
/// ##Note: Not a Renderable Widget
/// While this type can be dereferenced and converted to `BaseWidget`, it is *not* a renderable
/// widget... | /// Stop the timer. The callback will not be invoked until the timer is restarted.
pub fn stop(self) -> Self {
self.set_bool_attribute(::attrs::RUN, false);
self
}
}
impl_widget! { Timer, "timer" }
impl Destroy for Timer {} | self.set_bool_attribute(::attrs::RUN, true);
self
}
| random_line_split |
align.rs | macro_rules! expand_align {
() => {
s! {
#[cfg_attr(any(target_pointer_width = "32",
target_arch = "x86_64",
target_arch = "powerpc64",
target_arch = "mips64",
target_arch = "s390x",
... | #[repr(align(4))]
pub struct pthread_condattr_t {
size: [u8; ::__SIZEOF_PTHREAD_CONDATTR_T],
}
}
};
} | random_line_split | |
main.rs |
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
// Number of permutations summing to value N
// Values: container sizes
// target: remaining eggnog to be stored
// prior_used: containers used prior to this call
// hist: histogram of container counts
fn ... | () {
{
let test_values = vec![20, 15, 10, 5, 5];
let mut hist = vec![0; test_values.len()];
//println!("{:?}", test_values);
find_permutation_sums(&test_values[..], 25, 0, &mut hist);
let num_permutations_25 = hist.iter().fold(0, |sum, x| sum + x);
//println!("{:?}", hist);
//println!("Number of test va... | main | identifier_name |
main.rs |
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
// Number of permutations summing to value N
// Values: container sizes
// target: remaining eggnog to be stored
// prior_used: containers used prior to this call
// hist: histogram of container counts
fn ... | else if i < values.len() - 1 {
// Check this value plus the sum from remaining values
let subslice = &values[i+1..values.len()];
find_permutation_sums(subslice, remaining_target, prior_used + 1, hist);
}
}
}
fn main() {
{
let test_values = vec![20, 15, 10, 5, 5];
let mut hist = vec![0; test_value... | {
// Number is just the right size. Don't check extra values.
hist[prior_used + 1] += 1; // Record number of containers used
continue;
} | conditional_block |
main.rs | use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
// Number of permutations summing to value N
// Values: container sizes
// target: remaining eggnog to be stored
// prior_used: containers used prior to this call
// hist: histogram of container counts
fn f... | find_permutation_sums(&test_values[..], 25, 0, &mut hist);
let num_permutations_25 = hist.iter().fold(0, |sum, x| sum + x);
//println!("{:?}", hist);
//println!("Number of test values summing to 25 is {}", num_permutations_25);
assert_eq!(num_permutations_25, 4);
}
let path = Path::new("day17.txt");
... | random_line_split | |
main.rs |
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
// Number of permutations summing to value N
// Values: container sizes
// target: remaining eggnog to be stored
// prior_used: containers used prior to this call
// hist: histogram of container counts
fn ... | }
}
fn main() {
{
let test_values = vec![20, 15, 10, 5, 5];
let mut hist = vec![0; test_values.len()];
//println!("{:?}", test_values);
find_permutation_sums(&test_values[..], 25, 0, &mut hist);
let num_permutations_25 = hist.iter().fold(0, |sum, x| sum + x);
//println!("{:?}", hist);
//println!("Nu... | {
//let indent = 21-values.len();
//print!("{spacer:>0width$}", spacer=" ", width=indent);
//println!("{:?} : {}", values, target);
for i in 0..values.len() {
let remaining_target = target - values[i];
if remaining_target < 0 {
// Current value is too big
continue;
} else if remaining_target == 0 {
... | identifier_body |
fake_sign.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... | <B: MiningBlockChainClient, M: MinerService>(
client: &Arc<B>,
miner: &Arc<M>,
request: CallRequest,
) -> Result<SignedTransaction, Error> {
let from = request.from.unwrap_or(0.into());
Ok(Transaction {
nonce: request.nonce.unwrap_or_else(|| client.latest_nonce(&from)),
action: request.to.map_or(Action::Creat... | sign_call | identifier_name |
fake_sign.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... | {
let from = request.from.unwrap_or(0.into());
Ok(Transaction {
nonce: request.nonce.unwrap_or_else(|| client.latest_nonce(&from)),
action: request.to.map_or(Action::Create, Action::Call),
gas: request.gas.unwrap_or(50_000_000.into()),
gas_price: request.gas_price.unwrap_or_else(|| default_gas_price(&**clien... | identifier_body | |
fake_sign.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use ethcore::client::MiningBlockChainClient;
use ... | // (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
print_help.rs | extern crate clap;
use clap::App;
#[test]
fn print_app_help() {
let mut app = App::new("test")
.author("Kevin K.")
.about("tests stuff")
.version("1.3")
.args_from_usage("-f, --flag'some flag'
--option [opt]'some option'");
// We call a get_matches method ... | let mut help = vec![];
app.write_help(&mut help).ok().expect("failed to print help");
assert_eq!(&*String::from_utf8_lossy(&*help), &*String::from("test 1.3\n\
Kevin K.
tests stuff
USAGE:
\ttest [FLAGS] [OPTIONS]
FLAGS:
-f, --flag some flag
-h, --help Prints help information
-V, --... | let _ = app.get_matches_from_safe_borrow(vec![""]);
// Now we check the output of print_help() | random_line_split |
print_help.rs | extern crate clap;
use clap::App;
#[test]
fn | () {
let mut app = App::new("test")
.author("Kevin K.")
.about("tests stuff")
.version("1.3")
.args_from_usage("-f, --flag'some flag'
--option [opt]'some option'");
// We call a get_matches method to cause --help and --version to be built
let _ = app.get... | print_app_help | identifier_name |
print_help.rs | extern crate clap;
use clap::App;
#[test]
fn print_app_help() | FLAGS:
-f, --flag some flag
-h, --help Prints help information
-V, --version Prints version information
OPTIONS:
--option <opt> some option\n"));
}
| {
let mut app = App::new("test")
.author("Kevin K.")
.about("tests stuff")
.version("1.3")
.args_from_usage("-f, --flag 'some flag'
--option [opt] 'some option'");
// We call a get_matches method to cause --help and --version to be built
let _ = app.... | identifier_body |
main.rs | extern crate rand;
use std::io;
use std::slice;
use rand::Rng;
#[derive(Eq, PartialEq)]
enum Move {
Rock,
Paper,
Scissors,
}
#[derive(Debug)]
enum GameResult {
Human,
Computer,
Draw,
}
struct Game {
frequencies: [u32; 3],
}
impl Move {
fn beaten_by(&self) -> Move |
fn variants() -> slice::Iter<'static, Move> {
static VARIANTS: &'static [Move] = &[Move::Rock, Move::Paper, Move::Scissors];
VARIANTS.iter()
}
}
impl Game {
fn new() -> Game {
Game{frequencies: [0, 0, 0]}
}
fn increment_frequency(&mut self, m: &Move) {
let i = Mov... | {
match *self {
Move::Rock => Move::Paper,
Move::Paper => Move::Scissors,
Move::Scissors => Move::Rock,
}
} | identifier_body |
main.rs | extern crate rand;
use std::io;
use std::slice;
use rand::Rng;
#[derive(Eq, PartialEq)]
enum Move {
Rock,
Paper,
Scissors,
}
#[derive(Debug)]
enum GameResult {
Human,
Computer,
Draw,
}
struct Game {
frequencies: [u32; 3],
}
impl Move {
fn beaten_by(&self) -> Move {
match *s... | VARIANTS.iter()
}
}
impl Game {
fn new() -> Game {
Game{frequencies: [0, 0, 0]}
}
fn increment_frequency(&mut self, m: &Move) {
let i = Move::variants().position(|n| n == m).expect("Unknown frequency.");
self.frequencies[i] += 1;
}
fn pick(&self) -> Move {
... | }
fn variants() -> slice::Iter<'static, Move> {
static VARIANTS: &'static [Move] = &[Move::Rock, Move::Paper, Move::Scissors]; | random_line_split |
main.rs | extern crate rand;
use std::io;
use std::slice;
use rand::Rng;
#[derive(Eq, PartialEq)]
enum Move {
Rock,
Paper,
Scissors,
}
#[derive(Debug)]
enum GameResult {
Human,
Computer,
Draw,
}
struct Game {
frequencies: [u32; 3],
}
impl Move {
fn beaten_by(&self) -> Move {
match *s... | else {
GameResult::Draw
}
}
}
fn main() {
let mut game = Game::new();
loop {
println!("Enter a guess (r, p, s): ");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.ok()
.expect("Could not read input.");
let ... | {
GameResult::Human
} | conditional_block |
main.rs | extern crate rand;
use std::io;
use std::slice;
use rand::Rng;
#[derive(Eq, PartialEq)]
enum Move {
Rock,
Paper,
Scissors,
}
#[derive(Debug)]
enum GameResult {
Human,
Computer,
Draw,
}
struct | {
frequencies: [u32; 3],
}
impl Move {
fn beaten_by(&self) -> Move {
match *self {
Move::Rock => Move::Paper,
Move::Paper => Move::Scissors,
Move::Scissors => Move::Rock,
}
}
fn variants() -> slice::Iter<'static, Move> {
static VARIANTS: &'... | Game | identifier_name |
command.rs | ::Stage;
use {Resources, Buffer, Texture, Pipeline};
use encoder::MetalEncoder;
use MTL_MAX_BUFFER_BINDINGS;
use native::{Rtv, Srv, Dsv};
use metal::*;
use std::ptr;
use std::collections::hash_map::{HashMap, Entry};
pub struct CommandBuffer {
queue: MTLCommandQueue,
device: MTLDevice,
encoder: MetalE... | (&mut self, start: VertexCount, count: VertexCount, instances: Option<command::InstanceParams>) {
self.ensure_render_encoder();
match instances {
Some((ninst, offset)) => {
self.encoder.draw_instanced(count as u64,
ninst as u64,
... | call_draw | identifier_name |
command.rs | ::Stage;
use {Resources, Buffer, Texture, Pipeline};
use encoder::MetalEncoder;
use MTL_MAX_BUFFER_BINDINGS;
use native::{Rtv, Srv, Dsv};
use metal::*;
use std::ptr;
use std::collections::hash_map::{HashMap, Entry};
pub struct CommandBuffer {
queue: MTLCommandQueue,
device: MTLDevice,
encoder: MetalE... |
fn set_scissor(&mut self, rect: target::Rect) {
// TODO(fkaa): why are getting 1x1 scissor?
/*self.encoder.set_scissor_rect(MTLScissorRect {
x: rect.x as u64,
y: rect.y as u64,
width: (rect.x + rect.w) as u64,
height: (rect.y + rect.h) as u64,
... | {
use map::map_index_type;
// TODO(fkaa): pass wrapper instead
self.encoder.set_index_buffer(unsafe { *(buf.0).0 }, map_index_type(idx_type));
} | identifier_body |
command.rs | ::shade::Stage;
use {Resources, Buffer, Texture, Pipeline};
use encoder::MetalEncoder;
use MTL_MAX_BUFFER_BINDINGS;
use native::{Rtv, Srv, Dsv};
use metal::*;
use std::ptr;
use std::collections::hash_map::{HashMap, Entry};
pub struct CommandBuffer {
queue: MTLCommandQueue,
device: MTLDevice,
encoder:... | stencil_attachment.set_load_action(MTLLoadAction::Load);
}
}
}
self.encoder.set_render_pass_descriptor(render_pass_descriptor);
if let Some(dim) = targets.dimensions {
self.encoder.set_viewport(MTLViewport {
originX: 0f... | } else {
// see above
attachment.set_load_action(MTLLoadAction::Load);
if let Some(stencil_attachment) = stencil_attachment { | random_line_split |
regula_falsi.rs | // Copyright (c) 2015, Mikhail Vorotilov
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of... | /// + Robust
/// + No need for derivative function
///
/// Contra
///
/// - Slow
/// - Needs initial bracketing
///
/// # Failures
/// ## NoBracketing
/// Initial values do not bracket the root.
/// ## NoConvergency
/// Algorithm cannot find a root within the given number of iterations.
/// # Examples
///... | ///
/// Pro
///
/// + Simple
| random_line_split |
regula_falsi.rs | // Copyright (c) 2015, Mikhail Vorotilov
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of... | () {
let f = |x| 1f64 * x * x - 1f64;
let mut conv = debug_convergency::DebugConvergency::new(1e-15f64, 30);
conv.reset();
assert_float_eq!(
1e-15f64,
find_root_regula_falsi(10f64, 0f64, &f, &mut conv).ok().unwrap(),
1f64
);
... | test_find_root_regula_falsi | identifier_name |
regula_falsi.rs | // Copyright (c) 2015, Mikhail Vorotilov
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of... | conv.reset();
assert_eq!(
find_root_regula_falsi(10f64, 20f64, &f, &mut conv),
Err(SearchError::NoBracketing)
);
let result = find_root_regula_falsi(10f64, 20f64, &f, &mut conv);
assert_eq!(result.unwrap_err().to_string(), "Bracketing Error");
... | {
let f = |x| 1f64 * x * x - 1f64;
let mut conv = debug_convergency::DebugConvergency::new(1e-15f64, 30);
conv.reset();
assert_float_eq!(
1e-15f64,
find_root_regula_falsi(10f64, 0f64, &f, &mut conv).ok().unwrap(),
1f64
);
ass... | identifier_body |
strict_transport_security.rs | use std::fmt;
use std::str::{self, FromStr};
use unicase::UniCase;
use header::{Header, Raw, parsing};
/// `StrictTransportSecurity` header, defined in [RFC6797](https://tools.ietf.org/html/rfc6797)
///
/// This specification defines a mechanism enabling web sites to declare
/// themselves accessible only via secure... |
#[test]
fn test_parse_max_age_nan() {
let h: ::Result<StrictTransportSecurity> = Header::parse_header(&"max-age = derp".into());
assert!(h.is_err());
}
#[test]
fn test_parse_duplicate_directives() {
assert!(StrictTransportSecurity::parse_header(&"max-age=100; max-age=5; ma... | {
let h: ::Result<StrictTransportSecurity> = Header::parse_header(&"includeSubDomains".into());
assert!(h.is_err());
} | identifier_body |
strict_transport_security.rs | use std::fmt;
use std::str::{self, FromStr};
use unicase::UniCase;
use header::{Header, Raw, parsing};
/// `StrictTransportSecurity` header, defined in [RFC6797](https://tools.ietf.org/html/rfc6797)
///
/// This specification defines a mechanism enabling web sites to declare
/// themselves accessible only via secure... | (raw: &Raw) -> ::Result<StrictTransportSecurity> {
parsing::from_one_raw_str(raw)
}
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.include_subdomains {
write!(f, "max-age={}; includeSubdomains", self.max_age)
} else {
write!(f, "max-age={}"... | parse_header | identifier_name |
strict_transport_security.rs | use std::fmt;
use std::str::{self, FromStr};
use unicase::UniCase;
use header::{Header, Raw, parsing};
/// `StrictTransportSecurity` header, defined in [RFC6797](https://tools.ietf.org/html/rfc6797)
///
/// This specification defines a mechanism enabling web sites to declare
/// themselves accessible only via secure... | fn parse_header(raw: &Raw) -> ::Result<StrictTransportSecurity> {
parsing::from_one_raw_str(raw)
}
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.include_subdomains {
write!(f, "max-age={}; includeSubdomains", self.max_age)
} else {
wri... | random_line_split | |
strict_transport_security.rs | use std::fmt;
use std::str::{self, FromStr};
use unicase::UniCase;
use header::{Header, Raw, parsing};
/// `StrictTransportSecurity` header, defined in [RFC6797](https://tools.ietf.org/html/rfc6797)
///
/// This specification defines a mechanism enabling web sites to declare
/// themselves accessible only via secure... | else {
write!(f, "max-age={}", self.max_age)
}
}
}
#[cfg(test)]
mod tests {
use super::StrictTransportSecurity;
use header::Header;
#[test]
fn test_parse_max_age() {
let h = Header::parse_header(&"max-age=31536000".into());
assert_eq!(h.ok(), Some(StrictTranspo... | {
write!(f, "max-age={}; includeSubdomains", self.max_age)
} | conditional_block |
mir_build_match_comparisons.rs | // Copyright 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-MIT or ... |
const U: Option<i8> = Some(10);
const S: &'static str = "hello";
fn test2(x: i8) -> i32 {
match Some(x) {
U => 0,
_ => 1,
}
}
fn test3(x: &'static str) -> i32 {
match x {
S => 0,
_ => 1,
}
}
enum Opt<T> {
Some { v: T },
None
}
fn test4(x: u64) -> i32 {
let opt = Opt::Some{ v: x }... | {
match x {
1...10 => 0,
_ => 1,
}
} | identifier_body |
mir_build_match_comparisons.rs | // Copyright 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-MIT or ... | () {
assert_eq!(test1(0), 1);
assert_eq!(test1(1), 0);
assert_eq!(test1(2), 0);
assert_eq!(test1(5), 0);
assert_eq!(test1(9), 0);
assert_eq!(test1(10), 0);
assert_eq!(test1(11), 1);
assert_eq!(test1(20), 1);
assert_eq!(test2(10), 0);
assert_eq!(test2(0), 1);
assert_eq!(test2(20), 1);
assert_eq!(... | main | identifier_name |
mir_build_match_comparisons.rs | // Copyright 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-MIT or ... | assert_eq!(test2(0), 1);
assert_eq!(test2(20), 1);
assert_eq!(test3("hello"), 0);
assert_eq!(test3(""), 1);
assert_eq!(test3("world"), 1);
assert_eq!(test4(10), 0);
assert_eq!(test4(0), 1);
assert_eq!(test4(20), 1);
} | assert_eq!(test1(9), 0);
assert_eq!(test1(10), 0);
assert_eq!(test1(11), 1);
assert_eq!(test1(20), 1);
assert_eq!(test2(10), 0); | random_line_split |
lifetime.rs | use std::cmp::Ordering;
use std::fmt::{self, Display};
use std::hash::{Hash, Hasher};
use proc_macro2::{Ident, Span};
#[cfg(feature = "parsing")]
use crate::lookahead;
/// A Rust lifetime: `'a`.
///
/// Lifetime names must conform to the following rules:
///
/// - Must start with an apostrophe.
/// - Must not consis... |
}
}
#[cfg(feature = "printing")]
mod printing {
use super::*;
use proc_macro2::{Punct, Spacing, TokenStream};
use quote::{ToTokens, TokenStreamExt};
impl ToTokens for Lifetime {
fn to_tokens(&self, tokens: &mut TokenStream) {
let mut apostrophe = Punct::new('\'', Spacing::Joi... | {
input.step(|cursor| {
cursor
.lifetime()
.ok_or_else(|| cursor.error("expected lifetime"))
})
} | identifier_body |
lifetime.rs | use std::cmp::Ordering;
use std::fmt::{self, Display};
use std::hash::{Hash, Hasher};
use proc_macro2::{Ident, Span};
#[cfg(feature = "parsing")]
use crate::lookahead;
/// A Rust lifetime: `'a`.
///
/// Lifetime names must conform to the following rules:
///
/// - Must start with an apostrophe.
/// - Must not consis... | {
pub apostrophe: Span,
pub ident: Ident,
}
impl Lifetime {
/// # Panics
///
/// Panics if the lifetime does not conform to the bulleted rules above.
///
/// # Invocation
///
/// ```
/// # use proc_macro2::Span;
/// # use syn::Lifetime;
/// #
/// # fn f() -> Lifetim... | Lifetime | identifier_name |
lifetime.rs | use std::cmp::Ordering;
use std::fmt::{self, Display};
use std::hash::{Hash, Hasher};
use proc_macro2::{Ident, Span};
#[cfg(feature = "parsing")]
use crate::lookahead;
/// A Rust lifetime: `'a`.
///
/// Lifetime names must conform to the following rules:
///
/// - Must start with an apostrophe.
/// - Must not consis... | use proc_macro2::{Punct, Spacing, TokenStream};
use quote::{ToTokens, TokenStreamExt};
impl ToTokens for Lifetime {
fn to_tokens(&self, tokens: &mut TokenStream) {
let mut apostrophe = Punct::new('\'', Spacing::Joint);
apostrophe.set_span(self.apostrophe);
tokens... | #[cfg(feature = "printing")]
mod printing {
use super::*;
| random_line_split |
lifetime.rs | use std::cmp::Ordering;
use std::fmt::{self, Display};
use std::hash::{Hash, Hasher};
use proc_macro2::{Ident, Span};
#[cfg(feature = "parsing")]
use crate::lookahead;
/// A Rust lifetime: `'a`.
///
/// Lifetime names must conform to the following rules:
///
/// - Must start with an apostrophe.
/// - Must not consis... |
if symbol == "'" {
panic!("lifetime name must not be empty");
}
if!crate::ident::xid_ok(&symbol[1..]) {
panic!("{:?} is not a valid lifetime name", symbol);
}
Lifetime {
apostrophe: span,
ident: Ident::new(&symbol[1..], span),
... | {
panic!(
"lifetime name must start with apostrophe as in \"'a\", got {:?}",
symbol
);
} | conditional_block |
parser.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// 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... | },
rtok::Ident(id, _) => {
if self.is_rule_lhs() { None }
else {
self.bump();
Some(self.last_respan(NonTerminalSymbol(id)))
}
},
rtok::OpenDelim(rust::DelimToken::Bracket) => {
self.bump();
let res = self.parse_char_class(rule_name);
... | {
let token = self.rp.token.clone();
if token.is_any_keyword() {
return None
}
match token {
rtok::Literal(rust::token::Lit::Str_(name),_) => {
self.bump();
let cooked_lit = cook_lit(name);
Some(self.last_respan(StrLiteral(cooked_lit)))
},
rtok::Dot => {
... | identifier_body |
parser.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// 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... |
_ => ()
}
loop {
match self.parse_char_range(&mut ranges, rule_name) {
Some(char_set) => intervals.push_all(char_set.as_slice()),
None => break
}
}
Some(respan_expr(self.rp.span, CharacterClass(CharacterClassExpr{intervals: intervals})))
}
fn parse_char_range<'b>(... | {
intervals.push(CharacterInterval{lo: '-', hi: '-'});
ranges.next();
} | conditional_block |
parser.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// 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... | None => return None
};
let hi = self.rp.span.hi;
let token = self.rp.token.clone();
match token {
rtok::BinOp(rbtok::Star) => {
self.bump();
Some(spanned_expr(lo, hi, ZeroOrMore(expr)))
},
rtok::BinOp(rbtok::Plus) => {
self.bump();
Some(spanned_exp... |
fn parse_rule_suffixed(&mut self, rule_name: &str) -> Option<Box<Expression>> {
let lo = self.rp.span.lo;
let expr = match self.parse_rule_atom(rule_name){
Some(expr) => expr, | random_line_split |
parser.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// 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... | (&self, expr: ExpressionNode) -> Box<Expression> {
respan_expr(self.rp.last_span, expr)
}
fn parse_rule_atom(&mut self, rule_name: &str) -> Option<Box<Expression>> {
let token = self.rp.token.clone();
if token.is_any_keyword() {
return None
}
match token {
rtok::Literal(rust::token:... | last_respan | identifier_name |
weak_lang_items.rs | // 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 ... | /// Checks the crate for usage of weak lang items, returning a vector of all the
/// language items required by this crate, but not defined yet.
pub fn check_crate(krate: &ast::Crate,
sess: &Session,
items: &mut lang_items::LanguageItems) {
// These are never called by user cod... | random_line_split | |
lib.rs | extern crate log;
extern crate flexi_logger;
extern crate ansi_term;
extern crate wrust_types;
extern crate wrust_conf;
pub mod conf;
use log::{LogLevel, LogRecord};
use wrust_types::{Error, Result};
use wrust_conf::{Conf, FromConf};
use conf::{LogConf, LogDevice};
/// Initialize logging system using configuration ... | {
match record.level() {
LogLevel::Error => format!("[!] {} in {} ({}:{})", record.args(), record.location().module_path(), record.location().file(), record.location().line()),
LogLevel::Warn => format!("[W] {} in {} ({}:{})", record.args(), record.location().module_path(), record.location().file(), record.locatio... | identifier_body | |
lib.rs | extern crate log;
extern crate flexi_logger;
extern crate ansi_term;
extern crate wrust_types;
extern crate wrust_conf;
pub mod conf;
use log::{LogLevel, LogRecord};
use wrust_types::{Error, Result};
use wrust_conf::{Conf, FromConf};
use conf::{LogConf, LogDevice};
/// Initialize logging system using configuration ... | let mut flexi_config = LogConfig::new();
flexi_config.print_message = false;
flexi_config.duplicate_error = false;
flexi_config.duplicate_info = false;
// Setup flexi logger based on log device
match config.device {
LogDevice::Stderr(colorize) => {
flexi_config.format = if colorize {
colorized_format
... | random_line_split | |
lib.rs | extern crate log;
extern crate flexi_logger;
extern crate ansi_term;
extern crate wrust_types;
extern crate wrust_conf;
pub mod conf;
use log::{LogLevel, LogRecord};
use wrust_types::{Error, Result};
use wrust_conf::{Conf, FromConf};
use conf::{LogConf, LogDevice};
/// Initialize logging system using configuration ... | (config: &Conf, xpath: &str) -> Result<()> {
// Initialize logger
match LogConf::from_conf(&config, xpath) {
Ok(settings) => init(settings),
Err(err) => Error::new("Logger configuration failed").because(err).result()
}
}
fn colorized_format(record: &LogRecord) -> String {
use ansi_term::Colour::{Red, Green, Y... | init_from_conf | identifier_name |
nested-enum-same-names.rs | // Copyright 2013 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 ... |
}
pub fn main() {}
| {
enum Panic { Common };
} | identifier_body |
nested-enum-same-names.rs | // Copyright 2013 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 ... | name, rustc gives the same LLVM symbol for the two of them and fails,
as it does not include the method name in the symbol name.
*/
pub struct Foo;
impl Foo {
pub fn foo() {
enum Panic { Common };
}
pub fn bar() {
enum Panic { Common };
}
}
pub fn main() {} |
If you have two methods in an impl block, each containing an enum
(with the same name), each containing at least one value with the same | random_line_split |
nested-enum-same-names.rs | // Copyright 2013 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 ... | () {
enum Panic { Common };
}
}
pub fn main() {}
| bar | identifier_name |
webgluniformlocation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLUn... |
pub fn new(global: GlobalRef, id: u32) -> Temporary<WebGLUniformLocation> {
reflect_dom_object(box WebGLUniformLocation::new_inherited(id), global, WebGLUniformLocationBinding::Wrap)
}
}
pub trait WebGLUniformLocationHelpers {
fn get_id(&self) -> u32;
}
impl<'a> WebGLUniformLocationHelpers for J... | {
WebGLUniformLocation {
reflector_: Reflector::new(),
id: id,
}
} | identifier_body |
webgluniformlocation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLUn... | {
reflector_: Reflector,
id: u32,
}
impl WebGLUniformLocation {
fn new_inherited(id: u32) -> WebGLUniformLocation {
WebGLUniformLocation {
reflector_: Reflector::new(),
id: id,
}
}
pub fn new(global: GlobalRef, id: u32) -> Temporary<WebGLUniformLocation> {
... | WebGLUniformLocation | identifier_name |
webgluniformlocation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLUn... | }
} | impl<'a> WebGLUniformLocationHelpers for JSRef<'a, WebGLUniformLocation> {
fn get_id(&self) -> u32 {
self.id | random_line_split |
deriving-non-type.rs | // 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 ... |
#[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums
const c: usize = 0us;
#[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums
mod m { }
#[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums
extern "C" { }
#[derive(PartialEq)] //... | #[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums
static s: usize = 0us; | random_line_split |
deriving-non-type.rs | // 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 ... | ;
#[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums
trait T { }
#[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums
impl S { }
#[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums
impl T for S { }
#[derive(PartialEq)] //~ ERR... | S | identifier_name |
lib.rs | //
// Copyright (c) ShuYu Wang <andelf@gmail.com>, Feather Workshop and Pirmin Kalberer. All rights reserved.
//
//! An extension to rust-postgres, adds support for PostGIS.
//!
//! - PostGIS type helper
//! - GCJ02 support (used offically in Mainland China)
//! - Tiny WKB (TWKB) support
//!
//! ```rust,no_run
//! use... | //! let route = row.try_get::<_, Option<ewkb::LineString>>("route");
//! match route {
//! Ok(Some(geom)) => { println!("{:?}", geom) }
//! Ok(None) => { /* Handle NULL value */ }
//! Err(err) => { println!("Error: {}", err) }
//! }
//! ```
pub mod error;
mod types;
pub use types::{LineString, MultiLineStr... | //! # let row = rows.first().unwrap(); | random_line_split |
pam.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of screenruster.
//
// screenruster 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 Licen... | // Probably the password, since it doesn't want us to echo it.
PamMessageStyle::PROMPT_ECHO_OFF => {
response.resp = strdup(info.password);
}
PamMessageStyle::ERROR_MSG => {
result = PamReturnCode::CONV_ERR;
error!("{}", String::from_utf8_lossy(CStr::from_ptr(message.msg).to_bytes()));
... | response.resp = strdup(info.user);
}
| conditional_block |
pam.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of screenruster.
//
// screenruster 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 Licen... |
PamMessageStyle::ERROR_MSG => {
result = PamReturnCode::CONV_ERR;
error!("{}", String::from_utf8_lossy(CStr::from_ptr(message.msg).to_bytes()));
}
PamMessageStyle::TEXT_INFO => {
info!("{}", String::from_utf8_lossy(CStr::from_ptr(message.msg).to_bytes()));
}
}
}
if result!= PamR... | unsafe {
let info = &*(data as *mut Info as *const Info);
let mut result = PamReturnCode::SUCCESS;
*responses = calloc(count as size_t, mem::size_of::<PamResponse>() as size_t).as_mut().unwrap() as *mut _ as *mut _;
for i in 0 .. count as isize {
let message = &**messages.offset(i);
let response... | identifier_body |
pam.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of screenruster.
//
// screenruster 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 Licen... |
accounts: bool,
}
pub fn new(_config: toml::value::Table) -> error::Result<Auth> {
Ok(Auth {
accounts: cfg!(feature = "auth-pam-accounts"),
})
}
struct Info {
user: *const c_char,
password: *const c_char,
}
impl Authenticate for Auth {
fn authenticate(&mut self, user: &str, password: &str) -> error::Res... | th { | identifier_name |
pam.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of screenruster.
//
// screenruster 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 Licen... |
(set_item $ty:ident => $value:expr) => (
pam!(checked pam_set_item(&mut *handle.assume_init(), PamItemType::$ty as i32, strdup($value.as_ptr() as *const _) as *mut _))
);
(authenticate) => (
pam!(checked pam_authenticate(&mut *handle.assume_init(), PamFlag::NONE as i32))
);
(end) => (
... |
(start) => (
pam!(check pam_start(b"screenruster\x00".as_ptr() as *const _, ptr::null(), &conv, handle.as_mut_ptr() as *mut *const _))
); | random_line_split |
factor.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) 2020 nicoo <nicoo@debian.org>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
use smallvec::SmallVec;
use std::cell::RefCell;
use std::fmt;
use crate::numeric::... | me: u64) {
self.add(prime, 1);
}
#[cfg(test)]
fn product(&self) -> u64 {
self.0.borrow().product()
}
}
impl fmt::Display for Factors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let v = &mut (self.0).borrow_mut().0;
v.sort_unstable();
for (p... | pri | identifier_name |
factor.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) 2020 nicoo <nicoo@debian.org>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
use smallvec::SmallVec;
use std::cell::RefCell;
use std::fmt;
use crate::numeric::... | // We are overflowing u64, retry
continue 'attempt;
}
}
}
return f;
}
}
}
#[cfg(test)]
impl quickcheck::Arbitrary for Factors {
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
factor(u64::arbitrary... | f.push(n);
g = h;
} else {
| conditional_block |
factor.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) 2020 nicoo <nicoo@debian.org>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
use smallvec::SmallVec;
use std::cell::RefCell;
use std::fmt;
use crate::numeric::... | // Repeat the test 20 times, as it only fails some fraction
// of the time.
assert!(factor(pseudoprime).product() == pseudoprime);
}
}
quickcheck! {
fn factor_recombines(i: u64) -> bool {
i == 0 || factor(i).product() == i
}
fn re... | // miller_rabbin::Result::Composite
let pseudoprime = 17179869183;
for _ in 0..20 { | random_line_split |
factor.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) 2020 nicoo <nicoo@debian.org>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
use smallvec::SmallVec;
use std::cell::RefCell;
use std::fmt;
use crate::numeric::... | sh(&mut self, prime: u64) {
self.add(prime, 1);
}
#[cfg(test)]
fn product(&self) -> u64 {
self.0.borrow().product()
}
}
impl fmt::Display for Factors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let v = &mut (self.0).borrow_mut().0;
v.sort_unstable()... | _assert!(miller_rabin::is_prime(prime));
self.0.borrow_mut().add(prime, exp);
}
pub fn pu | identifier_body |
html.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unrooted_must_root)]
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateEleme... | (&mut self) {
self.inner.set_plaintext_state();
}
}
#[allow(unsafe_code)]
unsafe impl JSTraceable for HtmlTokenizer<TreeBuilder<JS<Node>, Sink>> {
unsafe fn trace(&self, trc: *mut JSTracer) {
struct Tracer(*mut JSTracer);
let tracer = Tracer(trc);
impl HtmlTracer for Tracer {
... | set_plaintext_state | identifier_name |
html.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unrooted_must_root)]
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateEleme... |
pub fn set_plaintext_state(&mut self) {
self.inner.set_plaintext_state();
}
}
#[allow(unsafe_code)]
unsafe impl JSTraceable for HtmlTokenizer<TreeBuilder<JS<Node>, Sink>> {
unsafe fn trace(&self, trc: *mut JSTracer) {
struct Tracer(*mut JSTracer);
let tracer = Tracer(trc);
... | {
&self.inner.sink.sink.base_url
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.