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 |
|---|---|---|---|---|
associated-types-eq-hr.rs | // Check testing of equality constraints in a higher-ranked context.
pub trait TheTrait<T> {
type A;
fn get(&self, t: T) -> Self::A;
}
struct IntStruct {
x: isize,
}
impl<'a> TheTrait<&'a isize> for IntStruct {
type A = &'a isize;
fn get(&self, t: &'a isize) -> &'a isize {
t
}
}
st... | fn tuple_four<T>()
where
T: for<'x, 'y> TheTrait<(&'x isize, &'y isize)>,
{
// not ok for tuple, two lifetimes, and lifetime matching is invariant
}
pub fn call_foo() {
foo::<IntStruct>();
foo::<UintStruct>(); //~ ERROR type mismatch
}
pub fn call_bar() {
bar::<IntStruct>(); //~ ERROR type mismatc... | // ok for tuple
}
| random_line_split |
associated-types-eq-hr.rs | // Check testing of equality constraints in a higher-ranked context.
pub trait TheTrait<T> {
type A;
fn get(&self, t: T) -> Self::A;
}
struct IntStruct {
x: isize,
}
impl<'a> TheTrait<&'a isize> for IntStruct {
type A = &'a isize;
fn get(&self, t: &'a isize) -> &'a isize {
t
}
}
st... | <T>()
where
T: for<'x, 'y> TheTrait<(&'x isize, &'y isize), A = &'x isize>,
{
// not ok for tuple, two lifetimes and we pick first
}
fn tuple_two<T>()
where
T: for<'x, 'y> TheTrait<(&'x isize, &'y isize), A = &'y isize>,
{
// not ok for tuple, two lifetimes and we pick second
}
fn tuple_three<T>()
whe... | tuple_one | identifier_name |
gameboy.rs | use super::cpu::*;
use super::mmu::*;
use super::mem_map;
use std::str;
pub struct Gameboy {
cpu: CPU,
mmu: MMU,
}
impl Gameboy {
pub fn new(boot_rom: Box<[u8]>, cart_rom: Box<[u8]>) -> Gameboy {
Gameboy {
cpu: CPU::new(),
mmu: MMU::new(boot_rom, cart_rom),
}
}... | println!("Cartridge Type: {0}", mem_map::cartridge_type(cart_type));
// Cart ROM size
let rom_size = self.mmu.read(0x0148);
println!("ROM Size: {0}", mem_map::rom_size(rom_size));
// Cart RAM size
let ram_size = self.mmu.read(0x0149);
println!("RAM Size: {0}", m... | println!("SBG Flag: {0:#x}", sgb_flag);
// Cart Type
let cart_type = self.mmu.read(0x0147); | random_line_split |
gameboy.rs | use super::cpu::*;
use super::mmu::*;
use super::mem_map;
use std::str;
pub struct Gameboy {
cpu: CPU,
mmu: MMU,
}
impl Gameboy {
pub fn | (boot_rom: Box<[u8]>, cart_rom: Box<[u8]>) -> Gameboy {
Gameboy {
cpu: CPU::new(),
mmu: MMU::new(boot_rom, cart_rom),
}
}
pub fn power_up(&mut self) {
println!("");
println!("####################");
// Read Name
let buffer = &[
... | new | identifier_name |
gameboy.rs | use super::cpu::*;
use super::mmu::*;
use super::mem_map;
use std::str;
pub struct Gameboy {
cpu: CPU,
mmu: MMU,
}
impl Gameboy {
pub fn new(boot_rom: Box<[u8]>, cart_rom: Box<[u8]>) -> Gameboy {
Gameboy {
cpu: CPU::new(),
mmu: MMU::new(boot_rom, cart_rom),
}
}... |
}
| {
self.cpu.step(&mut self.mmu);
} | identifier_body |
main.rs | /*
* SPKI - Simple Public Key Infrastructure
*
* Copyright © 2014 Senso-Rezo
* All rigths reserved.
*
* See LICENSE file for licensing information.
* See http://github/olemaire/spki for more information.
*/
fn main() {
Usage();
}
fn Usage() { | Exemples:
spki --issue server www.senso-rezo.org
spki --issue user olivier.lemaire@senso-rezo.org
spki --info www.senso-rezo.org
spki --revoke ldap.senso-rezo.org
spki --revoke www.senso-rezo.org keyCompromise
spki --renew olivier.lemaire@senso-rezo.org
spki --crl... |
let message = "Copyright (C) Senso-Rezo - SPKI (http://github.com/olemaire/spki)
Usage: spki <option> (<subject>)
Available options are:
--initialize Initialize a new Certificate Authority
--issue <type> <subject> Issue a certificate of <type> for <subject>
server <... | identifier_body |
main.rs | /*
* SPKI - Simple Public Key Infrastructure
*
* Copyright © 2014 Senso-Rezo
* All rigths reserved.
*
* See LICENSE file for licensing information.
* See http://github/olemaire/spki for more information.
*/
fn main() {
Usage();
}
fn U | ) {
let message = "Copyright (C) Senso-Rezo - SPKI (http://github.com/olemaire/spki)
Usage: spki <option> (<subject>)
Available options are:
--initialize Initialize a new Certificate Authority
--issue <type> <subject> Issue a certificate of <type> for <subject>
serve... | sage( | identifier_name |
main.rs | /*
* SPKI - Simple Public Key Infrastructure
*
* Copyright © 2014 Senso-Rezo
* All rigths reserved.
*
* See LICENSE file for licensing information.
* See http://github/olemaire/spki for more information.
*/
fn main() {
Usage();
}
fn Usage() {
let message = "Copyright (C) Senso-Rezo - SPKI (http://github... | --revoke <email,fqdn> (reason) Revoke a given certificate
--crl Generate a Certificate Revocation List
--print <email,fqdn,ca,crl> Will display a raw print of certificate/CRL
--info (email,fqdn,ca,crl) Will give human readable information on SPKI certificate/CA/CR... | random_line_split | |
find_requires_correct_type.rs | #[macro_use]
extern crate diesel;
use diesel::*;
use diesel::pg::PgConnection;
table! {
int_primary_key {
id -> Integer,
}
}
table! {
string_primary_key {
id -> VarChar,
} | let connection = PgConnection::establish("").unwrap();
int_primary_key::table.find("1").first(&connection).unwrap();
//~^ ERROR no method named `first` found for type `diesel::query_source::filter::FilteredQuerySource<int_primary_key::table, diesel::expression::predicates::Eq<int_primary_key::columns::id, &... | }
fn main() { | random_line_split |
find_requires_correct_type.rs | #[macro_use]
extern crate diesel;
use diesel::*;
use diesel::pg::PgConnection;
table! {
int_primary_key {
id -> Integer,
}
}
table! {
string_primary_key {
id -> VarChar,
}
}
fn | () {
let connection = PgConnection::establish("").unwrap();
int_primary_key::table.find("1").first(&connection).unwrap();
//~^ ERROR no method named `first` found for type `diesel::query_source::filter::FilteredQuerySource<int_primary_key::table, diesel::expression::predicates::Eq<int_primary_key::columns::... | main | identifier_name |
find_requires_correct_type.rs | #[macro_use]
extern crate diesel;
use diesel::*;
use diesel::pg::PgConnection;
table! {
int_primary_key {
id -> Integer,
}
}
table! {
string_primary_key {
id -> VarChar,
}
}
fn main() | {
let connection = PgConnection::establish("").unwrap();
int_primary_key::table.find("1").first(&connection).unwrap();
//~^ ERROR no method named `first` found for type `diesel::query_source::filter::FilteredQuerySource<int_primary_key::table, diesel::expression::predicates::Eq<int_primary_key::columns::id,... | identifier_body | |
stylist.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 html5ever_atoms::LocalName;
use selectors::parser::LocalName as LocalNameSelector;
use selectors::parser::Sele... | "div:nth-last-child(2)",
"div:nth-of-type(2)",
"div:nth-last-of-type(2)",
"div:first-of-type",
"div:last-of-type",
"div:only-of-type",
// Note: it would be nice to test :moz-any and the various other non-TS
// pseudo classes supported by gecko, but we don... | random_line_split | |
stylist.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 html5ever_atoms::LocalName;
use selectors::parser::LocalName as LocalNameSelector;
use selectors::parser::Sele... |
#[test]
fn test_get_class_name() {
let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]);
assert_eq!(SelectorMap::get_class_name(&rules_list[0][0]), Some(Atom::from("foo")));
assert_eq!(SelectorMap::get_class_name(&rules_list[1][0]), None);
}
#[test]
fn test_get_local_name() {
let (rules_list... | {
let (rules_list, _) = get_mock_rules(&[".intro", "#top"]);
assert_eq!(SelectorMap::get_id_name(&rules_list[0][0]), None);
assert_eq!(SelectorMap::get_id_name(&rules_list[1][0]), Some(Atom::from("top")));
} | identifier_body |
stylist.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 html5ever_atoms::LocalName;
use selectors::parser::LocalName as LocalNameSelector;
use selectors::parser::Sele... | () {
let (rules_list, _) = get_mock_rules(&["a.intro", "img.sidebar"]);
let a = &rules_list[0][0];
let b = &rules_list[1][0];
assert!((a.specificity(), a.source_order) < ((b.specificity(), b.source_order)),
"The rule that comes later should win.");
}
#[test]
fn test_get_id_name() {
let... | test_rule_ordering_same_specificity | identifier_name |
deriving-primitive.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 |
use std::num::FromPrimitive;
use std::isize;
#[derive(FromPrimitive)]
struct A { x: isize }
//~^^ ERROR `FromPrimitive` cannot be derived for structs
//~^^^ ERROR `FromPrimitive` cannot be derived for structs
#[derive(FromPrimitive)]
struct B(isize);
//~^^ ERROR `FromPrimitive` cannot be derived for structs
//~^^^ E... | // 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. | random_line_split |
deriving-primitive.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 ... | { x: isize }
//~^^ ERROR `FromPrimitive` cannot be derived for structs
//~^^^ ERROR `FromPrimitive` cannot be derived for structs
#[derive(FromPrimitive)]
struct B(isize);
//~^^ ERROR `FromPrimitive` cannot be derived for structs
//~^^^ ERROR `FromPrimitive` cannot be derived for structs
#[derive(FromPrimitive)]
enu... | A | identifier_name |
skip_null_arguments_transform.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use graphql_ir::{Argument, ConstantValue, Program, Transformed, Transformer, Value};
/// Removes arguments with a `null` value. Th... |
struct SkipNullArgumentsTransform;
impl Transformer for SkipNullArgumentsTransform {
const NAME: &'static str = "SkipNullArgumentsTransform";
const VISIT_ARGUMENTS: bool = true;
const VISIT_DIRECTIVES: bool = true;
fn transform_argument(&mut self, argument: &Argument) -> Transformed<Argument> {
... | {
SkipNullArgumentsTransform
.transform_program(program)
.replace_or_else(|| program.clone())
} | identifier_body |
skip_null_arguments_transform.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use graphql_ir::{Argument, ConstantValue, Program, Transformed, Transformer, Value};
/// Removes arguments with a `null` value. Th... | } | } | random_line_split |
skip_null_arguments_transform.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use graphql_ir::{Argument, ConstantValue, Program, Transformed, Transformer, Value};
/// Removes arguments with a `null` value. Th... | (program: &Program) -> Program {
SkipNullArgumentsTransform
.transform_program(program)
.replace_or_else(|| program.clone())
}
struct SkipNullArgumentsTransform;
impl Transformer for SkipNullArgumentsTransform {
const NAME: &'static str = "SkipNullArgumentsTransform";
const VISIT_ARGUMENTS: ... | skip_null_arguments_transform | identifier_name |
skip_null_arguments_transform.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use graphql_ir::{Argument, ConstantValue, Program, Transformed, Transformer, Value};
/// Removes arguments with a `null` value. Th... | else {
Transformed::Keep
}
}
}
| {
Transformed::Delete
} | conditional_block |
command.rs | use std::error;
use clap;
use crate::config;
use super::executer::Executer;
use super::{Arguments, Program};
pub struct Command<'c> {
config: &'c config::command::Config,
program: Program<'c>,
args: Arguments<'c>,
}
impl<'c> Command<'c> {
pub fn from_args(
config: &'c config::command::Confi... |
}
| {
trace!("command::params::exec::Command::run");
if let Some(params_config) = self.config.params.as_ref() {
let exec = Executer::from_config(params_config);
exec.run(&self.program, &self.args).await?;
}
Ok(())
} | identifier_body |
command.rs | use std::error;
use clap;
use crate::config;
use super::executer::Executer;
use super::{Arguments, Program};
pub struct Command<'c> {
config: &'c config::command::Config,
program: Program<'c>,
args: Arguments<'c>,
}
impl<'c> Command<'c> {
pub fn from_args(
config: &'c config::command::Confi... | (&self) -> Result<(), Box<dyn error::Error>> {
trace!("command::params::exec::Command::run");
if let Some(params_config) = self.config.params.as_ref() {
let exec = Executer::from_config(params_config);
exec.run(&self.program, &self.args).await?;
}
Ok(())
}
}
| run | identifier_name |
command.rs | use std::error;
use clap;
use crate::config;
use super::executer::Executer;
use super::{Arguments, Program};
pub struct Command<'c> {
config: &'c config::command::Config,
program: Program<'c>,
args: Arguments<'c>,
}
impl<'c> Command<'c> {
pub fn from_args(
config: &'c config::command::Confi... | }
Ok(())
}
} | pub async fn run(&self) -> Result<(), Box<dyn error::Error>> {
trace!("command::params::exec::Command::run");
if let Some(params_config) = self.config.params.as_ref() {
let exec = Executer::from_config(params_config);
exec.run(&self.program, &self.args).await?; | random_line_split |
time.rs | use core::cmp::Ordering;
use core::ops::{Add, Sub};
pub const NANOS_PER_MICRO: i32 = 1000;
pub const NANOS_PER_MILLI: i32 = 1000000;
pub const NANOS_PER_SEC: i32 = 1000000000;
/// A duration
#[derive(Copy, Clone)]
pub struct Duration {
/// The seconds
pub secs: i64,
/// The nano seconds
pub nanos: i32... | (self, other: Self) -> Self {
Duration::new(self.secs + other.secs, self.nanos + other.nanos)
}
}
impl Sub for Duration {
type Output = Duration;
fn sub(self, other: Self) -> Self {
Duration::new(self.secs - other.secs, self.nanos - other.nanos)
}
}
impl PartialEq for Duration {
f... | add | identifier_name |
time.rs | use core::cmp::Ordering;
use core::ops::{Add, Sub};
pub const NANOS_PER_MICRO: i32 = 1000;
pub const NANOS_PER_MILLI: i32 = 1000000;
pub const NANOS_PER_SEC: i32 = 1000000000;
/// A duration
#[derive(Copy, Clone)]
pub struct Duration {
/// The seconds
pub secs: i64,
/// The nano seconds
pub nanos: i32... | }
while nanos < 0 && secs > 0 {
secs -= 1;
nanos += NANOS_PER_SEC;
}
Duration {
secs: secs,
nanos: nanos,
}
}
/// Get the current duration
pub fn monotonic() -> Self {
::env().clock_monotonic.lock().clone()
... | /// Create a new duration
pub fn new(mut secs: i64, mut nanos: i32) -> Self {
while nanos >= NANOS_PER_SEC || (nanos > 0 && secs < 0) {
secs += 1;
nanos -= NANOS_PER_SEC; | random_line_split |
time.rs | use core::cmp::Ordering;
use core::ops::{Add, Sub};
pub const NANOS_PER_MICRO: i32 = 1000;
pub const NANOS_PER_MILLI: i32 = 1000000;
pub const NANOS_PER_SEC: i32 = 1000000000;
/// A duration
#[derive(Copy, Clone)]
pub struct Duration {
/// The seconds
pub secs: i64,
/// The nano seconds
pub nanos: i32... |
/// Get the current duration
pub fn monotonic() -> Self {
::env().clock_monotonic.lock().clone()
}
/// Get the realtime
pub fn realtime() -> Self {
::env().clock_realtime.lock().clone()
}
}
impl Add for Duration {
type Output = Duration;
fn add(self, other: Self) -> ... | {
while nanos >= NANOS_PER_SEC || (nanos > 0 && secs < 0) {
secs += 1;
nanos -= NANOS_PER_SEC;
}
while nanos < 0 && secs > 0 {
secs -= 1;
nanos += NANOS_PER_SEC;
}
Duration {
secs: secs,
nanos: nanos,
... | identifier_body |
time.rs | use core::cmp::Ordering;
use core::ops::{Add, Sub};
pub const NANOS_PER_MICRO: i32 = 1000;
pub const NANOS_PER_MILLI: i32 = 1000000;
pub const NANOS_PER_SEC: i32 = 1000000000;
/// A duration
#[derive(Copy, Clone)]
pub struct Duration {
/// The seconds
pub secs: i64,
/// The nano seconds
pub nanos: i32... |
}
}
| {
Some(Ordering::Equal)
} | conditional_block |
ai_qoff_player.rs | //! offline reinforcement learning (q learning after match is over)
#![allow(dead_code)]
extern crate rand;
extern crate nn;
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::io::prelude::*;
use self::rand::Rng;
use self::nn::{NN, HaltCondition, Activation};
use super::Player;
use super::super::field::... | for (i, val) in field.get_field().iter().enumerate()
{ //2 nodes for every square: -1 enemy, 0 free, 1 own; 0 square will not be reached with one move, 1 square can be directly filled
if *val == p { input.push(1f64); input.push(0f64); }
else if *val == op { input.push(-1f64); input.push(0f64); }
else
{ ... | random_line_split | |
ai_qoff_player.rs | //! offline reinforcement learning (q learning after match is over)
#![allow(dead_code)]
extern crate rand;
extern crate nn;
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::io::prelude::*;
use self::rand::Rng;
use self::nn::{NN, HaltCondition, Activation};
use super::Player;
use super::super::field::... |
//perform action
res = field.play(self.pid, x);
//save play data if not fixed, but learn if move did not was rule-conform
if!self.fixed ||!res
{
//calculate q update or collect data for later learn
if!res { qval[x as usize] = 0f64; } //invalid play instant learn
else { qval[x as usiz... | {
x = rng.gen::<u32>() % field.get_w();
} | conditional_block |
ai_qoff_player.rs | //! offline reinforcement learning (q learning after match is over)
#![allow(dead_code)]
extern crate rand;
extern crate nn;
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::io::prelude::*;
use self::rand::Rng;
use self::nn::{NN, HaltCondition, Activation};
use super::Player;
use super::super::field::... | (&self) -> f64
{
LR_MIN.max(LR * (2f64).powf(-(self.games_played as f64)/LR_DECAY))
}
fn argmax(slice:&[f64]) -> u32
{
let mut x:u32 = 0;
let mut max = slice[0];
for i in 1..slice.len()
{
if max<slice[i]
{
x = i as u32;
max = slice[i];
}
}
x
}
fn field_to_input(field:&mut Field,... | get_lr | identifier_name |
ai_qoff_player.rs | //! offline reinforcement learning (q learning after match is over)
#![allow(dead_code)]
extern crate rand;
extern crate nn;
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::io::prelude::*;
use self::rand::Rng;
use self::nn::{NN, HaltCondition, Activation};
use super::Player;
use super::super::field::... |
fn get_exploration(&self) -> f64
{
RND_PICK_START * (2f64).powf(-(self.games_played as f64)/RND_PICK_DEC)
}
fn get_lr(&self) -> f64
{
LR_MIN.max(LR * (2f64).powf(-(self.games_played as f64)/LR_DECAY))
}
fn argmax(slice:&[f64]) -> u32
{
let mut x:u32 = 0;
let mut max = slice[0];
for i in 1..slic... | {
Box::new(PlayerAIQOff { initialized: false, fixed: fix, filename: String::new(), pid: 0,
nn: None, games_played: 0, lr: LR, exploration: RND_PICK_START,
play_buffer: Vec::new(), num_buffered: 0 })
} | identifier_body |
builtin-superkinds-capabilities-xc.rs | // Copyright 2013-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... | <T: RequiresRequiresShareAndSend +'static>(val: T, chan: Sender<T>) {
chan.send(val).unwrap();
}
pub fn main() {
let (tx, rx): (Sender<X<isize>>, Receiver<X<isize>>) = channel();
foo(X(31337), tx);
assert_eq!(rx.recv().unwrap(), X(31337));
}
| foo | identifier_name |
builtin-superkinds-capabilities-xc.rs | // Copyright 2013-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... |
fn foo<T: RequiresRequiresShareAndSend +'static>(val: T, chan: Sender<T>) {
chan.send(val).unwrap();
}
pub fn main() {
let (tx, rx): (Sender<X<isize>>, Receiver<X<isize>>) = channel();
foo(X(31337), tx);
assert_eq!(rx.recv().unwrap(), X(31337));
} | impl <T: Sync+Send> RequiresRequiresShareAndSend for X<T> { } | random_line_split |
ai.rs | use level::*;
pub fn ai_step(level : &mut Level, player_pos: (i32,i32)) {
let mut x = 0;
let mut y = 0;
let mut enemies = Vec::with_capacity(16);
for line in &level.tiles {
for tile in line {
match tile.entity {
Some(Entity::Dragon{..}) => {
enem... | if distance<6f32 {
let dir = if dx<0f32 {
Direction::Left
} else if dx>0f32 {
Direction::Right
} else if dy<0f32 {
Direction::Up
} else {
Direction::Down
};
level.interact((x,y... | let distance = (dx*dx + dy*dy).sqrt();
| random_line_split |
ai.rs | use level::*;
pub fn | (level : &mut Level, player_pos: (i32,i32)) {
let mut x = 0;
let mut y = 0;
let mut enemies = Vec::with_capacity(16);
for line in &level.tiles {
for tile in line {
match tile.entity {
Some(Entity::Dragon{..}) => {
enemies.push((x,y));
... | ai_step | identifier_name |
ai.rs | use level::*;
pub fn ai_step(level : &mut Level, player_pos: (i32,i32)) {
let mut x = 0;
let mut y = 0;
let mut enemies = Vec::with_capacity(16);
for line in &level.tiles {
for tile in line {
match tile.entity {
Some(Entity::Dragon{..}) => {
enem... |
}
}
| {
let dir = if dx<0f32 {
Direction::Left
} else if dx>0f32 {
Direction::Right
} else if dy<0f32 {
Direction::Up
} else {
Direction::Down
};
level.interact((x,y), dir);
} | conditional_block |
ai.rs | use level::*;
pub fn ai_step(level : &mut Level, player_pos: (i32,i32)) | for e in enemies {
let (x,y) = e;
let dx = (px-x) as f32;
let dy = (py-y) as f32;
let distance = (dx*dx + dy*dy).sqrt();
if distance<6f32 {
let dir = if dx<0f32 {
Direction::Left
} else if dx>0f32 {
Direction::Right
... | {
let mut x = 0;
let mut y = 0;
let mut enemies = Vec::with_capacity(16);
for line in &level.tiles {
for tile in line {
match tile.entity {
Some(Entity::Dragon{..}) => {
enemies.push((x,y));
},
_ => {}
}... | identifier_body |
htmlareaelement.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 dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLAreaEl... | (localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLAreaElement {
HTMLAreaElement {
htmlelement: HTMLElement::new_inherited(HTMLAreaElementTypeId, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefi... | new_inherited | identifier_name |
htmlareaelement.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 dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLAreaEl... | use servo_util::str::DOMString;
#[jstraceable]
#[must_root]
#[privatize]
pub struct HTMLAreaElement {
htmlelement: HTMLElement
}
impl HTMLAreaElementDerived for EventTarget {
fn is_htmlareaelement(&self) -> bool {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLAreaElementTypeId))
}
}
i... | use dom::htmlelement::HTMLElement;
use dom::node::{Node, NodeHelpers, ElementNodeTypeId};
| random_line_split |
htmlareaelement.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 dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLAreaEl... |
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLAreaElement> {
let element = HTMLAreaElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap)... | {
HTMLAreaElement {
htmlelement: HTMLElement::new_inherited(HTMLAreaElementTypeId, localName, prefix, document)
}
} | identifier_body |
option.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 ... | #[test] #[should_fail]
fn test_option_too_much_dance() {
let mut y = Some(marker::NoCopy);
let _y2 = y.take().unwrap();
let _y3 = y.take().unwrap();
}
#[test]
fn test_and() {
let x: Option<int> = Some(1i);
assert_eq!(x.and(Some(2i)), Some(2));
assert_eq!(x.and(None::<int>), None);
let x: O... | assert_eq!(y2, 5);
assert!(y.is_none());
}
| random_line_split |
option.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 ... |
None => assert!(false),
}
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
assert_eq!(x, Some(new_val));
}
#[test]
fn test_ord() {
let small = Some(1.0f64);
let big = Some(5.0f64);
let nan = Some(0.0f64/0.0);
assert!(!(nan < big));
... | {
assert_eq!(*interior, val);
*interior = new_val;
} | conditional_block |
option.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 ... | () {
let x: Option<int> = Some(1);
assert_eq!(x.or_else(|| Some(2)), Some(1));
assert_eq!(x.or_else(|| None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or_else(|| Some(2)), Some(2));
assert_eq!(x.or_else(|| None), None);
}
#[test]
fn test_unwrap() {
assert_eq!(Some(1i).unwrap(), 1)... | test_or_else | identifier_name |
global.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 ... | let mut maybe_clone: Option<T> = None;
do global_data_modify(key) |current| {
match ¤t {
&Some(~ref value) => {
maybe_clone = Some(value.clone());
}
&None => ()
}
current
}
return maybe_clone;
}
// GlobalState is a map fr... | random_line_split | |
global.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 ... |
};
match maybe_new_value {
Some(value) => {
let data: *c_void = transmute(value);
let dtor: ~fn() = match maybe_dtor {
Some(dtor) => dtor,
None => {
let dtor: ~fn() = || {
... | {
(op(None), None)
} | conditional_block |
global.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 ... |
#[test]
fn test_modify() {
fn key(_v: UnsafeAtomicRcBox<int>) { }
unsafe {
do global_data_modify(key) |v| {
match v {
None => { Some(~UnsafeAtomicRcBox::new(10)) }
_ => fail!()
}
}
do global_data_modify(key) |v| {
ma... | {
fn key(_v: UnsafeAtomicRcBox<int>) { }
for uint::range(0, 100) |_| {
do spawn {
unsafe {
let val = do global_data_clone_create(key) {
~UnsafeAtomicRcBox::new(10)
};
assert!(val.get() == &10);
}
}
... | identifier_body |
global.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 ... | () -> Exclusive<GlobalState> {
static POISON: int = -1;
// FIXME #4728: Doing atomic_cxchg to initialize the global state
// lazily, which wouldn't be necessary with a runtime written
// in Rust
let global_ptr = unsafe { rust_get_global_data_ptr() };
if unsafe { *global_ptr } == 0 {
/... | get_global_state | identifier_name |
test_cargo_clean.rs | use support::{project, execs, main_file, basic_bin_manifest, cargo_dir};
use hamcrest::{assert_that, existing_dir, is_not};
fn setup() |
test!(cargo_clean_simple {
let p = project("foo")
.file("Cargo.toml", basic_bin_manifest("foo").as_slice())
.file("src/foo.rs", main_file(r#""i am foo""#, []).as_slice());
assert_that(p.cargo_process("build"), execs().with_status(0));
assert_that(&p.build_dir(), existing_dir());... | {
} | identifier_body |
test_cargo_clean.rs | use support::{project, execs, main_file, basic_bin_manifest, cargo_dir};
use hamcrest::{assert_that, existing_dir, is_not};
fn | () {
}
test!(cargo_clean_simple {
let p = project("foo")
.file("Cargo.toml", basic_bin_manifest("foo").as_slice())
.file("src/foo.rs", main_file(r#""i am foo""#, []).as_slice());
assert_that(p.cargo_process("build"), execs().with_status(0));
assert_that(&p.build_dir(), existing_d... | setup | identifier_name |
test_cargo_clean.rs | use support::{project, execs, main_file, basic_bin_manifest, cargo_dir};
use hamcrest::{assert_that, existing_dir, is_not};
fn setup() {
}
test!(cargo_clean_simple {
let p = project("foo")
.file("Cargo.toml", basic_bin_manifest("foo").as_slice())
.file("src/foo.rs", main_file(r#""i am fo... | execs().with_status(0));
assert_that(&p.build_dir(), is_not(existing_dir()));
})
test!(different_dir {
let p = project("foo")
.file("Cargo.toml", basic_bin_manifest("foo").as_slice())
.file("src/foo.rs", main_file(r#""i am foo""#, []).as_slice())
.file("sr... |
assert_that(p.cargo_process("build"), execs().with_status(0));
assert_that(&p.build_dir(), existing_dir());
assert_that(p.process(cargo_dir().join("cargo")).arg("clean"), | random_line_split |
autoderef-method-priority.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 ... |
}
impl double for Box<uint> {
fn double(self) -> uint { *self * 2_usize }
}
pub fn main() {
let x = box 3_usize;
assert_eq!(x.double(), 6_usize);
}
| { self } | identifier_body |
autoderef-method-priority.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 ... | trait double {
fn double(self) -> uint;
}
impl double for uint {
fn double(self) -> uint { self }
}
impl double for Box<uint> {
fn double(self) -> uint { *self * 2_usize }
}
pub fn main() {
let x = box 3_usize;
assert_eq!(x.double(), 6_usize);
} | random_line_split | |
autoderef-method-priority.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 ... | (self) -> uint { self }
}
impl double for Box<uint> {
fn double(self) -> uint { *self * 2_usize }
}
pub fn main() {
let x = box 3_usize;
assert_eq!(x.double(), 6_usize);
}
| double | identifier_name |
tessellation.rs | #[macro_use]
extern crate glium;
#[allow(unused_imports)]
use glium::{glutin, Surface};
use glium::index::PrimitiveType;
mod support;
fn | () {
// building the display, ie. the main object
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb = glutin::ContextBuilder::new();
let display = glium::Display::new(wb, cb, &event_loop).unwrap();
// building the vertex buffer, which c... | main | identifier_name |
tessellation.rs | #[macro_use]
extern crate glium;
#[allow(unused_imports)]
use glium::{glutin, Surface};
use glium::index::PrimitiveType;
mod support;
fn main() {
// building the display, ie. the main object
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb =... | } | }); | random_line_split |
mediaquerylistevent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... |
}
impl MediaQueryListEventMethods for MediaQueryListEvent {
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-media
fn Media(&self) -> DOMString {
self.media.clone()
}
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-matches
fn Matches(&self) -> bool {
... | {
let global = window.upcast::<GlobalScope>();
Ok(MediaQueryListEvent::new(
global,
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
init.media.clone(),
init.matches,
))
} | identifier_body |
mediaquerylistevent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... | (
global: &GlobalScope,
media: DOMString,
matches: bool,
) -> DomRoot<MediaQueryListEvent> {
let ev = Box::new(MediaQueryListEvent {
event: Event::new_inherited(),
media: media,
matches: Cell::new(matches),
});
reflect_dom_object(ev... | new_initialized | identifier_name |
mediaquerylistevent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... | fn Matches(&self) -> bool {
self.matches.get()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.upcast::<Event>().IsTrusted()
}
} | self.media.clone()
}
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-matches | random_line_split |
hello.rs | #![feature(proc_macro)]
extern crate hayaku_http;
extern crate hayaku_path;
#[macro_use]
extern crate serde_derive; |
use hayaku_http::{Http, Request, Response};
use hayaku_path::Router;
use std::sync::Arc;
fn main() {
let addr = "127.0.0.1:3000".parse().unwrap();
let mut router = Router::new();
router.get("/", Arc::new(hello_handler)).unwrap();
router.get("/plaintext", Arc::new(plain_handler)).unwrap();
router... | extern crate serde_json; | random_line_split |
hello.rs | #![feature(proc_macro)]
extern crate hayaku_http;
extern crate hayaku_path;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
use hayaku_http::{Http, Request, Response};
use hayaku_path::Router;
use std::sync::Arc;
fn main() {
let addr = "127.0.0.1:3000".parse().unwrap();
let mut router = Ro... | {
message: String,
}
fn json_handler(_req: &Request, res: &mut Response, _ctx: &()) {
let msg = Message { message: "Hello, World!".to_string() };
let data = serde_json::to_vec(&msg).unwrap();
res.add_header("Content-Type".to_string(), "application/json".to_string());
res.body(&data);
}
| Message | identifier_name |
hello.rs | #![feature(proc_macro)]
extern crate hayaku_http;
extern crate hayaku_path;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
use hayaku_http::{Http, Request, Response};
use hayaku_path::Router;
use std::sync::Arc;
fn main() {
let addr = "127.0.0.1:3000".parse().unwrap();
let mut router = Ro... | {
let msg = Message { message: "Hello, World!".to_string() };
let data = serde_json::to_vec(&msg).unwrap();
res.add_header("Content-Type".to_string(), "application/json".to_string());
res.body(&data);
} | identifier_body | |
buffer.rs | use buffer::{BufferView, BufferViewAny, BufferType, BufferCreationError};
use buffer::Mapping as BufferMapping;
use uniforms::{AsUniformValue, UniformValue, UniformBlock, UniformType};
| #[derive(Debug)]
pub struct UniformBuffer<T> where T: Copy + Send +'static {
buffer: BufferView<T>,
}
/// Mapping of a buffer in memory.
pub struct Mapping<'a, T> {
mapping: BufferMapping<'a, T>,
}
/// Same as `UniformBuffer` but doesn't contain any information about the type.
#[derive(Debug)]
pub struct Type... | use std::ops::{Deref, DerefMut};
use backend::Facade;
/// Buffer that contains a uniform block. | random_line_split |
buffer.rs | use buffer::{BufferView, BufferViewAny, BufferType, BufferCreationError};
use buffer::Mapping as BufferMapping;
use uniforms::{AsUniformValue, UniformValue, UniformBlock, UniformType};
use std::ops::{Deref, DerefMut};
use backend::Facade;
/// Buffer that contains a uniform block.
#[derive(Debug)]
pub struct UniformB... | (&mut self) -> &mut D {
&mut self.mapping.deref_mut()[0]
}
}
impl<T> DerefMut for UniformBuffer<T> where T: Send + Copy +'static {
fn deref_mut(&mut self) -> &mut BufferView<T> {
&mut self.buffer
}
}
impl<'a, T> AsUniformValue for &'a UniformBuffer<T> where T: UniformBlock + Send + Copy +'... | deref_mut | identifier_name |
buffer.rs | use buffer::{BufferView, BufferViewAny, BufferType, BufferCreationError};
use buffer::Mapping as BufferMapping;
use uniforms::{AsUniformValue, UniformValue, UniformBlock, UniformType};
use std::ops::{Deref, DerefMut};
use backend::Facade;
/// Buffer that contains a uniform block.
#[derive(Debug)]
pub struct UniformB... |
}
impl<'a, T> AsUniformValue for &'a UniformBuffer<T> where T: UniformBlock + Send + Copy +'static {
fn as_uniform_value(&self) -> UniformValue {
UniformValue::Block(self.buffer.as_slice_any(), <T as UniformBlock>::matches)
}
fn matches(_: &UniformType) -> bool {
false
}
}
| {
&mut self.buffer
} | identifier_body |
lib.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... |
}
/// A queue of events being executed in a loop on a single thread.
pub struct EventLoop {
// daemons: TaskSetImpl,
_last_runnable_state: bool,
events: RefCell<handle_table::HandleTable<private::EventNode>>,
head: private::EventHandle,
tail: Cell<private::EventHandle>,
depth_first_insertion_p... | {
Err(self.0.clone())
} | identifier_body |
lib.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... |
}
});
result
}
fn arm_depth_first(&self, event_handle: private::EventHandle) {
let insertion_node_next = self.events.borrow()[self.depth_first_insertion_point.get().0]
.next;
match insertion_node_next {
Some(next_ha... | {
// If there is still an event other than the head event, then there must have
// been a memory leak.
let remaining_events = event_loop.events.borrow().len();
if remaining_events > 1 {
::std::mem::forget(event_loop)... | conditional_block |
lib.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... | Err(e) => Err(func(e)),
}
})
}
/// Maps errors into a more general type.
pub fn lift<E1>(self) -> Promise<T, E1>
where E: Into<E1>
{
self.map_err(|e| e.into())
}
/// Returns a new promise that resolves when either `self` or `other` resolves. ... | random_line_split | |
lib.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... | (::std::marker::PhantomData<*mut u8>); // impl!Sync for WaitScope {}
/// The result of `Promise::fork()`. Allows branches to be created. Dropping the `ForkedPromise`
/// along with any branches created through `add_branch()` will cancel the computation.
pub struct ForkedPromise<T, E>
where T:'static + Clone,
... | WaitScope | identifier_name |
facility.rs | #[cfg(feature = "serde-serialize")]
use serde::{Serialize, Serializer};
use std::convert::TryFrom;
use thiserror::Error;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
#[allow(non_camel_case_types)]
/// Syslog facilities. Taken From RFC 5424, but I've heard that some platforms mix these around.
/// Na... |
/// Convert a syslog facility into a unique string representation
pub fn as_str(self) -> &'static str {
match self {
SyslogFacility::LOG_KERN => "kern",
SyslogFacility::LOG_USER => "user",
SyslogFacility::LOG_MAIL => "mail",
SyslogFacility::LOG_DAEMON =>... | {
Self::try_from(i).ok()
} | identifier_body |
facility.rs | #[cfg(feature = "serde-serialize")]
use serde::{Serialize, Serializer};
use std::convert::TryFrom;
use thiserror::Error;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
#[allow(non_camel_case_types)]
/// Syslog facilities. Taken From RFC 5424, but I've heard that some platforms mix these around.
/// Na... | LOG_CLOCKD = 15,
LOG_LOCAL0 = 16,
LOG_LOCAL1 = 17,
LOG_LOCAL2 = 18,
LOG_LOCAL3 = 19,
LOG_LOCAL4 = 20,
LOG_LOCAL5 = 21,
LOG_LOCAL6 = 22,
LOG_LOCAL7 = 23,
}
#[derive(Debug, Error)]
pub enum SyslogFacilityError {
#[error("integer does not correspond to a known facility")]
Inval... | LOG_AUTHPRIV = 10,
LOG_FTP = 11,
LOG_NTP = 12,
LOG_AUDIT = 13,
LOG_ALERT = 14, | random_line_split |
facility.rs | #[cfg(feature = "serde-serialize")]
use serde::{Serialize, Serializer};
use std::convert::TryFrom;
use thiserror::Error;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
#[allow(non_camel_case_types)]
/// Syslog facilities. Taken From RFC 5424, but I've heard that some platforms mix these around.
/// Na... | {
#[error("integer does not correspond to a known facility")]
InvalidInteger,
}
impl TryFrom<i32> for SyslogFacility {
type Error = SyslogFacilityError;
#[inline(always)]
fn try_from(i: i32) -> Result<SyslogFacility, Self::Error> {
Ok(match i {
0 => SyslogFacility::LOG_KERN,
... | SyslogFacilityError | identifier_name |
struct-namespace.rs | // Copyright 2013-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-MI... |
pub struct Struct2(pub u32);
}
fn main() {
let struct1 = Struct1 {
a: 0,
b: 1,
};
let struct2 = Struct2(2);
let mod1_struct1 = mod1::Struct1 {
a: 3,
b: 4,
};
let mod1_struct2 = mod1::Struct2(5);
zzz(); // #break
}
#[inline(never)]
fn zzz() {()} | pub b: u64,
} | random_line_split |
struct-namespace.rs | // Copyright 2013-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-MI... | {
pub a: u32,
pub b: u64,
}
pub struct Struct2(pub u32);
}
fn main() {
let struct1 = Struct1 {
a: 0,
b: 1,
};
let struct2 = Struct2(2);
let mod1_struct1 = mod1::Struct1 {
a: 3,
b: 4,
};
let mod1_struct2 = mod1::Struct2(5);
zzz()... | Struct1 | identifier_name |
monch.rs | #![feature(old_io)]
#![feature(std_misc)]
#![feature(collections)]
#![feature(test)]
#![feature(io)]
#![feature(libc)]
// logging needs this
#![feature(rustc_private)]
#[macro_use] extern crate log;
extern crate env_logger;
extern crate getopts;
extern crate time;
extern crate test;
use std::old_io::TcpStream;
use s... | (sock: &mut Writer) -> IoResult<()> {
try!(sock.write_i8(MESSAGE_TYPE_HEARTBEAT));
try!(sock.write_be_i32(0));
try!(sock.flush());
Ok(())
}
#[derive(Debug)]
enum MyError {
Io(IoError),
Other(String)
}
impl FromError<IoError> for MyError {
fn from_error(err: IoError) -> MyError {
MyError::Io(err)
... | send_heartbeat | identifier_name |
monch.rs | #![feature(old_io)]
#![feature(std_misc)]
#![feature(collections)]
#![feature(test)]
#![feature(io)]
#![feature(libc)]
// logging needs this
#![feature(rustc_private)]
#[macro_use] extern crate log;
extern crate env_logger;
extern crate getopts;
extern crate time;
extern crate test;
use std::old_io::TcpStream;
use s... | else {
if body.len() as i32 == first_size.unwrap() {
same_size_count += 1;
}
}
if i % 1000 == 0 {
print!("\rCompleted {} requests.", i);
io::stdout().flush();
}
i += 1;
first = false;
},
other => return Err(MyError::Other(format!("Invalid message type. Expecting hear... | {
println!("First response attributes {:?}", attributes);
first_response = Some(body.clone());
first_size = Some(body.len() as i32)
} | conditional_block |
monch.rs | #![feature(old_io)]
#![feature(std_misc)]
#![feature(collections)]
#![feature(test)]
#![feature(io)]
#![feature(libc)]
// logging needs this
#![feature(rustc_private)]
#[macro_use] extern crate log;
extern crate env_logger;
extern crate getopts;
extern crate time;
extern crate test;
use std::old_io::TcpStream;
use s... |
fn connect(host: &str, port: u16, timeout: Duration) -> IoResult<TcpStream> {
//log("resolving %s..." % host)
//let address = socket.gethostbyname(host)
let sock = try!(TcpStream::connect_timeout((host, port), timeout));
Ok(sock)
}
fn parse_attributes(str: &Vec<String>) -> Result<Vec<(String, String)>, String> {... | {
let reference = try!(sock.read_be_u32());
let (attr, attr_len) = try!(recv_attributes(sock));
let remaining_length = length - 4 - attr_len;
let response = try!(sock.read_exact(remaining_length as usize));
let frame = ResponseData {
reference: reference as i32,
attributes: attr,
body: response
};
Ok(F... | identifier_body |
monch.rs | #![feature(old_io)]
#![feature(std_misc)]
#![feature(collections)]
#![feature(test)]
#![feature(io)]
#![feature(libc)]
// logging needs this
#![feature(rustc_private)]
#[macro_use] extern crate log;
extern crate env_logger;
extern crate getopts;
extern crate time;
extern crate test;
use std::old_io::TcpStream;
use s... | println!("Response size: {:>7} bytes", response_size.unwrap_or(-1));
println!("Received responses: {:>7} requests", received_count);
println!("Time outs: {:>7} requests", options.number - received_count as u32);
println!("OK responses: {:>7} requests", result.ok_c... | println!("");
println!("Total time taken for tests: {:>7} ms", total_time);
println!("Connection time: {:>7} µs", connection_time); | random_line_split |
build.rs | // Copyright 2015, 2016 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 la... | () {
inner::main();
}
| main | identifier_name |
build.rs | // Copyright 2015, 2016 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 la... | {
inner::main();
} | identifier_body | |
build.rs | // Copyright 2015, 2016 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 la... | // 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/>.
#[cfg(not(feature = "serde_macros"))]
mod inner {
extern crate se... | // but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
kdtu.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... | self.state.config_recv(ep, buf, ord, msg_ord, 0);
self.write_ep_local(ep);
Ok(())
}
pub fn write_ep_remote(&mut self, vpe: &VPEDesc, ep: EpId, regs: &[Reg]) -> Result<(), Error> {
let eps = vpe.vpe().unwrap().eps_addr();
let addr = eps + ep * EPS_RCNT * util::size_of::<... | _size: usize) -> Result<(), Error> {
Err(Error::new(Code::NotSup))
}
pub fn recv_msgs(&mut self, ep: EpId, buf: goff, ord: i32, msg_ord: i32) -> Result<(), Error> { | random_line_split |
kdtu.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... | () {
INST.set(Some(KDTU {
state: State::new(),
}));
}
pub fn get() -> &'static mut KDTU {
INST.get_mut().as_mut().unwrap()
}
pub fn write_ep_local(&mut self, ep: EpId) {
DTU::set_ep_regs(ep, self.state.get_ep(ep));
}
pub fn invalidate_ep_remote(&mut... | init | identifier_name |
kdtu.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... |
pub fn reset(&mut self, _vpe: &VPEDesc) -> Result<(), Error> {
// nothing to do
Ok(())
}
}
| {
let eps = vpe.vpe().unwrap().eps_addr();
let addr = eps + ep * EPS_RCNT * util::size_of::<Reg>();
let bytes = EPS_RCNT * util::size_of::<Reg>();
self.try_write_mem(vpe, addr as goff, regs.as_ptr() as *const u8, bytes)
} | identifier_body |
timeranges.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::TimeRangesBinding;
use c... | else if new_range.is_before(&self.ranges[idx]) &&
(idx == 0 || self.ranges[idx - 1].is_before(&new_range))
{
// We are exactly after the current previous range and before the current
// range, while not overlapping with none of them.
// Or we ... | {
// The ranges are either overlapping or contiguous,
// we need to merge the new range with the existing one.
new_range.union(&self.ranges[idx]);
self.ranges.remove(idx);
} | conditional_block |
timeranges.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::TimeRangesBinding;
use c... |
fn is_overlapping(&self, other: &TimeRange) -> bool {
// This also covers the case where `self` is entirely contained within `other`,
// for example: `self` = [2,3) and `other` = [1,4).
self.contains(other.start) || self.contains(other.end) || other.contains(self.start)
}
fn is_co... | {
self.start <= time && time < self.end
} | identifier_body |
timeranges.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::TimeRangesBinding;
use c... | }
pub fn is_before(&self, other: &TimeRange) -> bool {
other.start >= self.end
}
}
impl fmt::Debug for TimeRange {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(fmt, "[{},{})", self.start, self.end)
}
}
#[derive(Debug)]
pub enum TimeRangesError {
E... | self.contains(other.start) || self.contains(other.end) || other.contains(self.start)
}
fn is_contiguous(&self, other: &TimeRange) -> bool {
other.start == self.end || other.end == self.start | random_line_split |
timeranges.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::TimeRangesBinding;
use c... | (&self, index: u32) -> Result<f64, TimeRangesError> {
self.ranges
.get(index as usize)
.map(|r| r.end)
.ok_or(TimeRangesError::OutOfRange)
}
pub fn add(&mut self, start: f64, end: f64) -> Result<(), TimeRangesError> {
if start > end {
return Err(Time... | end | identifier_name |
sync.rs | extern crate redis;
use std::sync::{Arc, Mutex};
use std::thread;
use backend::{RoundRobinBackend, GetBackend};
pub fn create_sync_thread(backend: Arc<Mutex<RoundRobinBackend>>, redis_url: String) {
thread::spawn(move || {
let pubsub = subscribe_to_redis(&redis_url).unwrap();
loop {
l... |
fn handle_message(backend: Arc<Mutex<RoundRobinBackend>>,
msg: redis::Msg)
-> redis::RedisResult<()> {
let channel = msg.get_channel_name();
let payload: String = try!(msg.get_payload());
debug!("New message on Redis channel {}: '{}'", channel, payload);
match chan... | {
let client = try!(redis::Client::open(url));
let mut pubsub: redis::PubSub = try!(client.get_pubsub());
try!(pubsub.subscribe("backend_add"));
try!(pubsub.subscribe("backend_remove"));
info!("Subscribed to Redis channels 'backend_add' and 'backend_remove'");
Ok(pubsub)
} | identifier_body |
sync.rs | extern crate redis;
use std::sync::{Arc, Mutex};
use std::thread;
use backend::{RoundRobinBackend, GetBackend};
pub fn create_sync_thread(backend: Arc<Mutex<RoundRobinBackend>>, redis_url: String) {
thread::spawn(move || {
let pubsub = subscribe_to_redis(&redis_url).unwrap();
loop {
l... | msg: redis::Msg)
-> redis::RedisResult<()> {
let channel = msg.get_channel_name();
let payload: String = try!(msg.get_payload());
debug!("New message on Redis channel {}: '{}'", channel, payload);
match channel {
"backend_add" => {
let mut backend... | info!("Subscribed to Redis channels 'backend_add' and 'backend_remove'");
Ok(pubsub)
}
fn handle_message(backend: Arc<Mutex<RoundRobinBackend>>, | random_line_split |
sync.rs | extern crate redis;
use std::sync::{Arc, Mutex};
use std::thread;
use backend::{RoundRobinBackend, GetBackend};
pub fn | (backend: Arc<Mutex<RoundRobinBackend>>, redis_url: String) {
thread::spawn(move || {
let pubsub = subscribe_to_redis(&redis_url).unwrap();
loop {
let msg = pubsub.get_message().unwrap();
handle_message(backend.clone(), msg).unwrap();
}
});
}
fn subscribe_to_redi... | create_sync_thread | identifier_name |
sync.rs | extern crate redis;
use std::sync::{Arc, Mutex};
use std::thread;
use backend::{RoundRobinBackend, GetBackend};
pub fn create_sync_thread(backend: Arc<Mutex<RoundRobinBackend>>, redis_url: String) {
thread::spawn(move || {
let pubsub = subscribe_to_redis(&redis_url).unwrap();
loop {
l... |
}
}
"backend_remove" => {
let mut backend = backend.lock().unwrap();
match backend.remove(&payload) {
Ok(_) => info!("Removed server {}", payload),
_ => {}
}
}
_ => info!("Cannot parse Redis message"),
}... | {} | conditional_block |
transaction.rs | // Copyright 2015, 2016 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 la... | () {
let s = r#"{
"address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6",
"caller" : "cd1722f2947def4cf144679da39c4c32bdc35681",
"code" : "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01600055",
"data" : "0x",
"gas... | transaction_deserialization | identifier_name |
transaction.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
| // the Free Software Foundation, either version 3 of the License, or
// (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
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Publ... | // Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by | random_line_split |
layout_image.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 https://mozilla.org/MPL/2.0/. */
//! Infrastructure to initiate network requests for images needed by the layout
//! thread. The script thread nee... |
}
impl PreInvoke for LayoutImageContext {}
pub fn fetch_image_for_layout(
url: ServoUrl,
node: &Node,
id: PendingImageId,
cache: Arc<dyn ImageCache>,
) {
let document = document_from_node(node);
let context = Arc::new(Mutex::new(LayoutImageContext {
id: id,
cache: cache,
... | {
self.doc.root().global()
} | identifier_body |
layout_image.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 https://mozilla.org/MPL/2.0/. */
//! Infrastructure to initiate network requests for images needed by the layout
//! thread. The script thread nee... | node: &Node,
id: PendingImageId,
cache: Arc<dyn ImageCache>,
) {
let document = document_from_node(node);
let context = Arc::new(Mutex::new(LayoutImageContext {
id: id,
cache: cache,
resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource),
doc: Truste... | url: ServoUrl, | random_line_split |
layout_image.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 https://mozilla.org/MPL/2.0/. */
//! Infrastructure to initiate network requests for images needed by the layout
//! thread. The script thread nee... | (&mut self, metadata: Result<FetchMetadata, NetworkError>) {
self.cache
.notify_pending_response(self.id, FetchResponseMsg::ProcessResponse(metadata));
}
fn process_response_chunk(&mut self, payload: Vec<u8>) {
self.cache
.notify_pending_response(self.id, FetchResponseMsg:... | process_response | identifier_name |
tls.rs | #![allow(unused_variables)]
#![allow(unused_imports)]
/// Note: Fred must be compiled with the `enable-tls` feature for this to work.
extern crate fred;
extern crate tokio_core;
extern crate futures;
use fred::RedisClient;
use fred::owned::RedisClientOwned;
use fred::types::*;
use tokio_core::reactor::Core;
use fut... | let commands = client.on_connect().and_then(|client| {
println!("Client connected.");
client.select(0)
})
.and_then(|client| {
println!("Selected database.");
client.info(None)
})
.and_then(|(client, info)| {
println!("Redis server info: {}", info);
client.get("foo")
})
.and_then(|... | {
let config = RedisConfig::Centralized {
// Note: this must match the hostname tied to the cert
host: "foo.bar.com".into(),
port: 6379,
key: Some("key".into()),
// if compiled without `enable-tls` setting this to `true` does nothing, which is done to avoid requiring TLS dependencies unless necess... | identifier_body |
tls.rs | #![allow(unused_variables)]
#![allow(unused_imports)]
/// Note: Fred must be compiled with the `enable-tls` feature for this to work.
extern crate fred;
extern crate tokio_core;
extern crate futures;
use fred::RedisClient;
use fred::owned::RedisClientOwned;
use fred::types::*;
use tokio_core::reactor::Core;
use fut... | () {
let config = RedisConfig::Centralized {
// Note: this must match the hostname tied to the cert
host: "foo.bar.com".into(),
port: 6379,
key: Some("key".into()),
// if compiled without `enable-tls` setting this to `true` does nothing, which is done to avoid requiring TLS dependencies unless nec... | main | identifier_name |
tls.rs | #![allow(unused_variables)]
#![allow(unused_imports)]
/// Note: Fred must be compiled with the `enable-tls` feature for this to work.
extern crate fred;
extern crate tokio_core;
extern crate futures;
use fred::RedisClient;
use fred::owned::RedisClientOwned;
use fred::types::*;
use tokio_core::reactor::Core;
use fut... |
let (reason, client) = match core.run(connection.join(commands)) {
Ok((r, c)) => (r, c),
Err(e) => panic!("Connection closed abruptly: {}", e)
};
println!("Connection closed gracefully with error: {:?}", reason);
} | }); | random_line_split |
addressbook_send.rs | // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... | pub mod addressbook_capnp {
include!(concat!(env!("OUT_DIR"), "/addressbook_capnp.rs"));
}
use capnp::message::{Builder, HeapAllocator, TypedReader};
use std::sync::mpsc;
use std::thread;
pub mod addressbook {
use addressbook_capnp::{address_book, person};
use capnp::message::{Builder, HeapAllocator, TypedR... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.