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 |
|---|---|---|---|---|
mod.rs |
use std::fmt;
use super::Tile;
use super::Direction;
use super::Point;
/// Defines the 2D square Grid trait for using the maze generator
pub trait Grid
{
/// Gets tile data at a given position on a grid
fn get_tile_data(&self, Point) -> Result<Tile, &'static str>;
/// Gets the width and height respectiv... | return Result::Err("Cannot carve in desired dirrection");
}
{
let from_tile = &mut tiles[y][x];
// Set full tile as connected
match *from_tile
{
Tile::Connected {
up: ref mut u,
down: r... | {
let (width, height) = self.get_dimensions();
let tiles = &mut self.tiles;
// Determine directon to carve into
let (x_c, y_c): Point = match dir
{
Direction::Up => (x, y + 1),
Direction::Right => (x + 1, y),
// Set direction to same as curre... | identifier_body |
mod.rs | use std::fmt;
use super::Tile;
use super::Direction;
use super::Point;
/// Defines the 2D square Grid trait for using the maze generator
pub trait Grid
{
/// Gets tile data at a given position on a grid
fn get_tile_data(&self, Point) -> Result<Tile, &'static str>;
/// Gets the width and height respective... | maze_temp.tiles.push(vec![]);
// Push new tiles to the row
for _ in 0..width
{
maze_temp.tiles[j].push(Tile::new());
}
}
maze_temp
}
} | random_line_split | |
move-4-unique.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 ... | {a: int, b: int, c: int}
fn test(foo: Box<Triple>) -> Box<Triple> {
let foo = foo;
let bar = foo;
let baz = bar;
let quux = baz;
return quux;
}
pub fn main() {
let x = box Triple{a: 1, b: 2, c: 3};
let y = test(x);
assert!((y.c == 3));
}
| Triple | identifier_name |
move-4-unique.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Triple {a: int, b: int, c: int}
fn test(foo: Box<Triple>) -> Box<Triple> {
let foo = foo;
let bar = foo;
let baz = bar;
let quux ... | random_line_split | |
move-4-unique.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 x = box Triple{a: 1, b: 2, c: 3};
let y = test(x);
assert!((y.c == 3));
} | identifier_body | |
issue-54109-without-witness.rs | // run-rustfix
// This test is to check if suggestions can be applied automatically.
#![allow(dead_code, unused_parens)]
fn main() {}
fn test_and() {
let a = true;
let b = false;
let _ = a and b; //~ ERROR `and` is not a logical operator
if a and b { //~ ERROR `and` is not a logical operator
... |
}
fn test_or_par() {
let a = true;
let b = false;
if (a or b) { //~ ERROR `or` is not a logical operator
println!("both");
}
}
fn test_while_and() {
let a = true;
let b = false;
while a and b { //~ ERROR `and` is not a logical operator
println!("both");
}
}
fn test_... | { //~ ERROR `and` is not a logical operator
println!("both");
} | conditional_block |
issue-54109-without-witness.rs | // run-rustfix
// This test is to check if suggestions can be applied automatically.
#![allow(dead_code, unused_parens)]
fn main() {}
fn test_and() {
let a = true;
let b = false;
let _ = a and b; //~ ERROR `and` is not a logical operator
if a and b { //~ ERROR `and` is not a logical operator
... | }
}
fn test_while_and() {
let a = true;
let b = false;
while a and b { //~ ERROR `and` is not a logical operator
println!("both");
}
}
fn test_while_or() {
let a = true;
let b = false;
while a or b { //~ ERROR `or` is not a logical operator
println!("both");
}
} | fn test_or_par() {
let a = true;
let b = false;
if (a or b) { //~ ERROR `or` is not a logical operator
println!("both"); | random_line_split |
issue-54109-without-witness.rs | // run-rustfix
// This test is to check if suggestions can be applied automatically.
#![allow(dead_code, unused_parens)]
fn main() {}
fn | () {
let a = true;
let b = false;
let _ = a and b; //~ ERROR `and` is not a logical operator
if a and b { //~ ERROR `and` is not a logical operator
println!("both");
}
}
fn test_or() {
let a = true;
let b = false;
let _ = a or b; //~ ERROR `or` is not a logical operator
... | test_and | identifier_name |
issue-54109-without-witness.rs | // run-rustfix
// This test is to check if suggestions can be applied automatically.
#![allow(dead_code, unused_parens)]
fn main() {}
fn test_and() {
let a = true;
let b = false;
let _ = a and b; //~ ERROR `and` is not a logical operator
if a and b { //~ ERROR `and` is not a logical operator
... |
fn test_or_par() {
let a = true;
let b = false;
if (a or b) { //~ ERROR `or` is not a logical operator
println!("both");
}
}
fn test_while_and() {
let a = true;
let b = false;
while a and b { //~ ERROR `and` is not a logical operator
println!("both");
}
}
fn test_wh... | {
let a = true;
let b = false;
if (a and b) { //~ ERROR `and` is not a logical operator
println!("both");
}
} | identifier_body |
pca.rs | //! Principal Component Analysis Module
//!
//! Contains implementation of PCA.
//!
//! # Examples
//!
//! ```
//! use rusty_machine::learning::pca::PCA;
//! use rusty_machine::learning::UnSupModel;
//!
//! use rusty_machine::linalg::Matrix;
//! let mut pca = PCA::default();
//!
//! let inputs = Matrix::new(3, 2, vec![... |
self.components = match self.n {
Some(c) => {
let slicer: Vec<usize> = (0..c).collect();
Some(v.select_cols(&slicer))
},
None => Some(v)
};
self.n_features = Some(inputs.cols());
Ok(())
}
}
/// Subtract center Vect... | if inputs.cols() > inputs.rows() {
v = v.transpose();
self.inv = true;
} | random_line_split |
pca.rs | //! Principal Component Analysis Module
//!
//! Contains implementation of PCA.
//!
//! # Examples
//!
//! ```
//! use rusty_machine::learning::pca::PCA;
//! use rusty_machine::learning::UnSupModel;
//!
//! use rusty_machine::linalg::Matrix;
//! let mut pca = PCA::default();
//!
//! let inputs = Matrix::new(3, 2, vec![... | (inputs: &Matrix<f64>, centers: &Vector<f64>) -> Matrix<f64> {
// Number of inputs columns and centers length must be the same
Matrix::from_fn(inputs.rows(), inputs.cols(),
|c, r| inputs.get_unchecked([r, c]) - centers.data().get_unchecked(c))
}
#[cfg(test)]
mod tests {
use linalg::{Ma... | centering | identifier_name |
pca.rs | //! Principal Component Analysis Module
//!
//! Contains implementation of PCA.
//!
//! # Examples
//!
//! ```
//! use rusty_machine::learning::pca::PCA;
//! use rusty_machine::learning::UnSupModel;
//!
//! use rusty_machine::linalg::Matrix;
//! let mut pca = PCA::default();
//!
//! let inputs = Matrix::new(3, 2, vec![... |
}
/// The default PCA.
///
/// Parameters:
///
/// - `n` = `None` (keep all components)
/// - `center` = `true`
///
/// # Examples
///
/// ```
/// use rusty_machine::learning::pca::PCA;
///
/// let model = PCA::default();
/// ```
impl Default for PCA {
fn default() -> Self {
PCA {
// because n... | {
match self.components {
None => Err(Error::new_untrained()),
Some(ref rot) => { Ok(rot) }
}
} | identifier_body |
openbsd_base.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () -> TargetOptions {
TargetOptions {
linker: "cc".to_string(),
dynamic_linking: true,
executables: true,
morestack: false,
linker_is_gnu: true,
has_rpath: true,
pre_link_args: vec!(
// GNU-style linkers will use this to omit linking to libraries
... | opts | identifier_name |
openbsd_base.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
TargetOptions {
linker: "cc".to_string(),
dynamic_linking: true,
executables: true,
morestack: false,
linker_is_gnu: true,
has_rpath: true,
pre_link_args: vec!(
// GNU-style linkers will use this to omit linking to libraries
// which ... | identifier_body | |
openbsd_base.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | TargetOptions {
linker: "cc".to_string(),
dynamic_linking: true,
executables: true,
morestack: false,
linker_is_gnu: true,
has_rpath: true,
pre_link_args: vec!(
// GNU-style linkers will use this to omit linking to libraries
// which do... | random_line_split | |
resource_manager.rs | /*
* Copyright 2021 Google LLC
*
* 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 i... | {
pub(super) cluster_manager: SharedClusterManager,
pub(super) filter_manager: SharedFilterManager,
pub(super) execution_result_rx: oneshot::Receiver<crate::Result<()>>,
}
impl StaticResourceManagers {
pub(super) fn new(
endpoints: Endpoints,
filter_chain: Arc<FilterChain>,
) -> Re... | DynamicResourceManagers | identifier_name |
resource_manager.rs | /*
* Copyright 2021 Google LLC
*
* 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 i... | ) -> Result<DynamicResourceManagers, InitializeError> {
let (cluster_updates_tx, cluster_updates_rx) = Self::cluster_updates_channel();
let (filter_chain_updates_tx, filter_chain_updates_rx) =
Self::filter_chain_updates_channel();
let listener_manager_args = ListenerManagerArgs:... | shutdown_rx: watch::Receiver<()>, | random_line_split |
p24.rs | use rand::{weak_rng, Rng, SeedableRng};
use util::{MT19937Rng, prng_crypt};
#[test]
fn run() | ks_rng.reseed(s);
let test_ctxt = prng_crypt(&mut ks_rng, &test_input);
&ctxt[2..] == &test_ctxt[2..]
});
assert!(rec_seed.is_some());
assert_eq!(seed, rec_seed.unwrap());
}
| {
let mut wk_rng = weak_rng();
// rng seeded from weak 16-bit seed
let seed = wk_rng.next_u32() & 0xFFFF;
let mut ks_rng = MT19937Rng::from_seed(seed);
let attack_input = "AAAAAAAAAAAAAA".as_bytes();
let rand_prefix: [u8; 2] = wk_rng.gen();
let mut input = Vec::new();
input.extend_from... | identifier_body |
p24.rs | use rand::{weak_rng, Rng, SeedableRng};
use util::{MT19937Rng, prng_crypt};
#[test]
fn | () {
let mut wk_rng = weak_rng();
// rng seeded from weak 16-bit seed
let seed = wk_rng.next_u32() & 0xFFFF;
let mut ks_rng = MT19937Rng::from_seed(seed);
let attack_input = "AAAAAAAAAAAAAA".as_bytes();
let rand_prefix: [u8; 2] = wk_rng.gen();
let mut input = Vec::new();
input.extend_f... | run | identifier_name |
p24.rs | use rand::{weak_rng, Rng, SeedableRng};
use util::{MT19937Rng, prng_crypt};
#[test]
fn run() {
let mut wk_rng = weak_rng();
// rng seeded from weak 16-bit seed
let seed = wk_rng.next_u32() & 0xFFFF;
let mut ks_rng = MT19937Rng::from_seed(seed);
let attack_input = "AAAAAAAAAAAAAA".as_bytes();
... | .find(|&s: &u32| {
ks_rng.reseed(s);
let test_ctxt = prng_crypt(&mut ks_rng, &test_input);
&ctxt[2..] == &test_ctxt[2..]
});
assert!(rec_seed.is_some());
assert_eq!(seed, rec_seed.unwrap());
} | let rec_seed = (0..(1 << 16)) | random_line_split |
test_sup.rs | //! Encapsulate running the `hab-sup` executable for tests.
use std::{collections::HashSet,
env,
net::TcpListener,
path::{Path,
PathBuf},
process::{Child,
Command,
Stdio},
string::ToString,
sync::Mutex,... | service_group: &str)
-> TestSup
where R: AsRef<Path>
{
// We'll give 10 tries to find a free port number
let http_port = unclaimed_port(10);
let butterfly_port = unclaimed_port(10);
let control_port = unc... | random_line_split | |
test_sup.rs | //! Encapsulate running the `hab-sup` executable for tests.
use std::{collections::HashSet,
env,
net::TcpListener,
path::{Path,
PathBuf},
process::{Child,
Command,
Stdio},
string::ToString,
sync::Mutex,... |
impl TestSup {
/// Create a new `TestSup` that will listen on randomly-selected
/// ports for both gossip and HTTP requests so tests run in
/// parallel don't step on each other.
///
/// See also `new`.
pub fn new_with_random_ports<R>(fs_root: R,
origin: &st... | {
if env::args().any(|arg| arg == "--nocapture") {
true
} else {
match env::var("RUST_TEST_NOCAPTURE") {
Ok(val) => &val != "0",
Err(_) => false,
}
}
} | identifier_body |
test_sup.rs | //! Encapsulate running the `hab-sup` executable for tests.
use std::{collections::HashSet,
env,
net::TcpListener,
path::{Path,
PathBuf},
process::{Child,
Command,
Stdio},
string::ToString,
sync::Mutex,... | {
pub hab_root: PathBuf,
pub origin_name: String,
pub package_name: String,
pub service_group: String,
pub http_port: u16,
pub butterfly_port: u16,
pub control_port: u16,
pub butterfly_client: test_butterfly::Client,
pub cmd: Command,
... | TestSup | identifier_name |
indexing_slicing.rs | //! lint on indexing and slicing operations
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
use clippy_utils::higher;
use rustc_ast::ast::RangeLimits;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use ... |
},
Some(_) => None,
None => Some(array_size),
};
(start, end)
}
| {
Some(x)
} | conditional_block |
indexing_slicing.rs | //! lint on indexing and slicing operations
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
use clippy_utils::higher;
use rustc_ast::ast::RangeLimits;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use ... | "range is out of bounds",
);
return;
}
}
if let (_, Some(end)) = const_range {
if end > size {
span_lint(
... | {
if let ExprKind::Index(array, index) = &expr.kind {
let ty = cx.typeck_results().expr_ty(array).peel_refs();
if let Some(range) = higher::Range::hir(index) {
// Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] and &x[..]
if let ty::Array(_, s) = ty.kind(... | identifier_body |
indexing_slicing.rs | //! lint on indexing and slicing operations
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
use clippy_utils::higher;
use rustc_ast::ast::RangeLimits;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use ... | /// &x[2..100];
/// &x[2..];
/// &x[..100];
///
/// // Good
/// x.get(2);
/// x.get(2..100);
/// x.get(2..);
/// x.get(..100);
///
/// // Array
/// let y = [0, 1, 2, 3];
///
/// // Bad
/// &y[10..100];
/// &y[10..];
/// &y[..100];
///
/// // Go... | /// // Vector
/// let x = vec![0; 5];
///
/// // Bad
/// x[2]; | random_line_split |
indexing_slicing.rs | //! lint on indexing and slicing operations
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
use clippy_utils::higher;
use rustc_ast::ast::RangeLimits;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use ... | (&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if let ExprKind::Index(array, index) = &expr.kind {
let ty = cx.typeck_results().expr_ty(array).peel_refs();
if let Some(range) = higher::Range::hir(index) {
// Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] an... | check_expr | identifier_name |
iter_any.rs | fn main() | {
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];
// 对 vec 的 `iter()` 产出 `&i32`(原文:`iter()` for vecs yields
// `&i32`)。解构成 `i32` 类型。
println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2));
// 对 vec 的 `into_iter()` 产出 `i32` 类型。无需解构。
println!("2 in vec2: {}", vec2.into_iter().any(| ... | identifier_body | |
iter_any.rs | fn main() {
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];
// 对 vec 的 `iter()` 产出 `&i32`(原文:`iter()` for vecs yields
// `&i32`)。解构成 `i32` 类型。
println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2));
// 对 vec 的 `into_iter()` 产出 `i32` 类型。无需解构。
println!("2 in vec2: {}", vec2.into_iter... | println!("2 in array2: {}", array2.into_iter().any(|&x| x == 2));
} | random_line_split | |
iter_any.rs | fn | () {
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];
// 对 vec 的 `iter()` 产出 `&i32`(原文:`iter()` for vecs yields
// `&i32`)。解构成 `i32` 类型。
println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2));
// 对 vec 的 `into_iter()` 产出 `i32` 类型。无需解构。
println!("2 in vec2: {}", vec2.into_iter().any(... | main | identifier_name |
window.rs | use std::{collections::VecDeque, rc::Rc};
use crate::{
api::prelude::*, proc_macros::*, shell::prelude::WindowRequest, themes::theme_orbtk::*,
};
// --- KEYS --
pub static STYLE_WINDOW: &str = "window";
// --- KEYS --
// internal type to handle dirty widgets.
type DirtyWidgets = Vec<Entity>;
#[derive(Clone)]
en... | <'a>(widget: &'a WidgetContainer<'a>) -> &'a bool {
Window::resizable_ref(widget)
}
}
impl Template for Window {
fn template(self, id: Entity, _: &mut BuildContext) -> Self {
self.name("Window")
.background(colors::BRIGHT_GRAY_COLOR)
.size(100.0, 100.0)
.style(S... | resizeable_ref | identifier_name |
window.rs | use std::{collections::VecDeque, rc::Rc};
use crate::{
api::prelude::*, proc_macros::*, shell::prelude::WindowRequest, themes::theme_orbtk::*,
};
// --- KEYS --
pub static STYLE_WINDOW: &str = "window";
// --- KEYS --
// internal type to handle dirty widgets.
type DirtyWidgets = Vec<Entity>;
#[derive(Clone)]
en... |
}
| {
GridLayout::new().into()
} | identifier_body |
window.rs | use std::{collections::VecDeque, rc::Rc};
use crate::{
api::prelude::*, proc_macros::*, shell::prelude::WindowRequest, themes::theme_orbtk::*,
};
// --- KEYS --
pub static STYLE_WINDOW: &str = "window";
// --- KEYS --
// internal type to handle dirty widgets.
type DirtyWidgets = Vec<Entity>;
#[derive(Clone)]
en... | }
WindowEvent::ActiveChanged(active) => {
self.active_changed(active, ctx);
}
_ => {}
},
Action::FocusEvent(focus_event) => match focus_event {
FocusEvent::RequestF... | random_line_split | |
mod.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 ... | () { }
| modfn | identifier_name |
mod.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT | // <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.
//! Dox
// @has src/foo/qux/mod.rs.html
// @has foo/qux/index.html '//a/@href' '../../src/foo/qux/mod.rs.html'
// @has foo/qux/bar/index.html '//a/@href'... | // 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 | random_line_split |
mod.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 ... |
}
/// Dox
// @has foo/qux/bar/trait.Foobar.html '//a/@href' '../../../src/foo/qux/mod.rs.html'
pub trait Foobar { fn dummy(&self) { } }
// @has foo/qux/bar/struct.Foo.html '//a/@href' '../../../src/foo/qux/mod.rs.html'
pub struct Foo { x: i32, y: u32 }
// @has foo/qux/bar/fn.prawns.html ... | { } | identifier_body |
issue-1468.rs | fn issue1468() | unread_handle_trail.consumed(),
handle.written());
} else {
unreachable!();
}
});
}
| {
euc_jp_decoder_functions!({
let trail_minus_offset = byte.wrapping_sub(0xA1);
// Fast-track Hiragana (60% according to Lunde)
// and Katakana (10% acconding to Lunde).
if jis0208_lead_minus_offset == 0x03 &&
trail_minus_offset < 0x53 {
// Hiragana
handle.write_upper_bmp(0x3041 + trail_minus_offset as u16)
} else if j... | identifier_body |
issue-1468.rs | fn | () {
euc_jp_decoder_functions!({
let trail_minus_offset = byte.wrapping_sub(0xA1);
// Fast-track Hiragana (60% according to Lunde)
// and Katakana (10% acconding to Lunde).
if jis0208_lead_minus_offset == 0x03 &&
trail_minus_offset < 0x53 {
// Hiragana
handle.write_upper_bmp(0x3041 + trail_minus_offset as u16)
} else i... | issue1468 | identifier_name |
issue-1468.rs | fn issue1468() {
euc_jp_decoder_functions!({
let trail_minus_offset = byte.wrapping_sub(0xA1);
// Fast-track Hiragana (60% according to Lunde)
// and Katakana (10% acconding to Lunde).
if jis0208_lead_minus_offset == 0x03 && | handle.write_upper_bmp(0x3041 + trail_minus_offset as u16)
} else if jis0208_lead_minus_offset == 0x04 &&
trail_minus_offset < 0x56 {
// Katakana
handle.write_upper_bmp(0x30A1 + trail_minus_offset as u16)
} else if trail_minus_offset > (0xFE - 0xA1) {
if byte < 0x80 {
return (DecoderResult::Malformed(1, 0),
unread_hand... | trail_minus_offset < 0x53 {
// Hiragana | random_line_split |
foo.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 ... | /// Dox
// @has foo/bar/baz/fn.baz.html '//a/@href' '../../../src/foo/foo.rs.html'
pub fn baz() { }
}
/// Dox
// @has foo/bar/trait.Foobar.html '//a/@href' '../../src/foo/foo.rs.html'
pub trait Foobar { fn dummy(&self) { } }
// @has foo/bar/struct.Foo.html '//a/@href' '../.... |
/// Dox
// @has foo/bar/baz/index.html '//a/@href' '../../../src/foo/foo.rs.html'
pub mod baz { | random_line_split |
foo.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 ... | { x: i32, y: u32 }
// @has foo/bar/fn.prawns.html '//a/@href' '../../src/foo/foo.rs.html'
pub fn prawns((a, b): (i32, u32), Foo { x, y }: Foo) { }
}
/// Dox
// @has foo/fn.modfn.html '//a/@href' '../src/foo/foo.rs.html'
pub fn modfn() { }
| Foo | identifier_name |
foo.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 ... | }
// @has foo/bar/struct.Foo.html '//a/@href' '../../src/foo/foo.rs.html'
pub struct Foo { x: i32, y: u32 }
// @has foo/bar/fn.prawns.html '//a/@href' '../../src/foo/foo.rs.html'
pub fn prawns((a, b): (i32, u32), Foo { x, y }: Foo) { }
}
/// Dox
// @has foo/fn.modfn.html '//a/@href' '../src/foo/foo.... | { } | identifier_body |
mutex.rs | use crate::cell::UnsafeCell;
use crate::mem::MaybeUninit;
use crate::sys::cvt_nz;
pub struct Mutex {
inner: UnsafeCell<libc::pthread_mutex_t>,
}
pub type MovableMutex = Box<Mutex>;
#[inline]
pub unsafe fn raw(m: &Mutex) -> *mut libc::pthread_mutex_t {
m.inner.get()
}
unsafe impl Send for Mutex {}
unsafe imp... |
pub unsafe fn lock(&self) {
let result = libc::pthread_mutex_lock(self.inner.get());
debug_assert_eq!(result, 0);
}
#[inline]
pub unsafe fn try_lock(&self) -> bool {
libc::pthread_mutex_trylock(self.inner.get()) == 0
}
pub unsafe fn unlock(&self) {
let result ... | {
let mut attr = MaybeUninit::<libc::pthread_mutexattr_t>::uninit();
cvt_nz(libc::pthread_mutexattr_init(attr.as_mut_ptr())).unwrap();
let attr = PthreadMutexAttr(&mut attr);
cvt_nz(libc::pthread_mutexattr_settype(attr.0.as_mut_ptr(), libc::PTHREAD_MUTEX_RECURSIVE))
.unwrap()... | identifier_body |
mutex.rs | use crate::cell::UnsafeCell;
use crate::mem::MaybeUninit;
use crate::sys::cvt_nz;
pub struct Mutex {
inner: UnsafeCell<libc::pthread_mutex_t>,
}
pub type MovableMutex = Box<Mutex>;
#[inline]
pub unsafe fn raw(m: &Mutex) -> *mut libc::pthread_mutex_t {
m.inner.get()
}
unsafe impl Send for Mutex {}
unsafe imp... | let attr = PthreadMutexAttr(&mut attr);
cvt_nz(libc::pthread_mutexattr_settype(attr.0.as_mut_ptr(), libc::PTHREAD_MUTEX_RECURSIVE))
.unwrap();
cvt_nz(libc::pthread_mutex_init(self.inner.get(), attr.0.as_ptr())).unwrap();
}
pub unsafe fn lock(&self) {
let result = libc... | }
pub unsafe fn init(&self) {
let mut attr = MaybeUninit::<libc::pthread_mutexattr_t>::uninit();
cvt_nz(libc::pthread_mutexattr_init(attr.as_mut_ptr())).unwrap(); | random_line_split |
mutex.rs | use crate::cell::UnsafeCell;
use crate::mem::MaybeUninit;
use crate::sys::cvt_nz;
pub struct Mutex {
inner: UnsafeCell<libc::pthread_mutex_t>,
}
pub type MovableMutex = Box<Mutex>;
#[inline]
pub unsafe fn raw(m: &Mutex) -> *mut libc::pthread_mutex_t {
m.inner.get()
}
unsafe impl Send for Mutex {}
unsafe imp... | (&self) {
let result = libc::pthread_mutex_destroy(self.inner.get());
debug_assert_eq!(result, 0);
}
}
struct PthreadMutexAttr<'a>(&'a mut MaybeUninit<libc::pthread_mutexattr_t>);
impl Drop for PthreadMutexAttr<'_> {
fn drop(&mut self) {
unsafe {
let result = libc::pthread_... | destroy | identifier_name |
lub-match.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 ... |
pub fn opt_str3<'a>(maybestr: &'a Option<String>) -> &'static str {
match *maybestr { //~ ERROR mismatched types
Some(ref s) => {
let s: &'a str = s.as_slice();
s
}
None => "(none)",
}
}
fn main() {}
| {
match *maybestr { //~ ERROR mismatched types
None => "(none)",
Some(ref s) => {
let s: &'a str = s.as_slice();
s
}
}
} | identifier_body |
lub-match.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 ... | <'a>(maybestr: &'a Option<String>) -> &'a str {
match *maybestr {
None => "(none)",
Some(ref s) => {
let s: &'a str = s.as_slice();
s
}
}
}
pub fn opt_str2<'a>(maybestr: &'a Option<String>) -> &'static str {
match *maybestr { //~ ERROR mismatched types
... | opt_str1 | identifier_name |
lub-match.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 ... | Some(ref s) => {
let s: &'a str = s.as_slice();
s
}
None => "(none)",
}
}
fn main() {} | match *maybestr { //~ ERROR mismatched types | random_line_split |
rsbegin.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 ... | extern "C" {
fn rust_eh_register_frames(eh_frame_begin: *const u8, object: *mut u8);
fn rust_eh_unregister_frames(eh_frame_begin: *const u8, object: *mut u8);
}
unsafe fn init() {
// register unwind info on module startup
rust_eh_register_frames(
&__EH_FRAME_BEGI... | bool char
}
// Unwind info registration/deregistration routines.
// See the docs of `unwind` module in libstd. | random_line_split |
rsbegin.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 ... |
#[cfg(all(target_os = "windows", target_arch = "x86", target_env = "gnu"))]
pub mod eh_frames {
#[no_mangle]
#[link_section = ".eh_frame"]
// Marks beginning of the stack frame unwind info section
pub static __EH_FRAME_BEGIN__: [u8; 0] = [];
// Scratch space for unwinder's internal book-keeping.
... | {
drop_in_place(to_drop);
} | identifier_body |
rsbegin.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 ... | <T:?Sized>(to_drop: *mut T) {
drop_in_place(to_drop);
}
#[cfg(all(target_os = "windows", target_arch = "x86", target_env = "gnu"))]
pub mod eh_frames {
#[no_mangle]
#[link_section = ".eh_frame"]
// Marks beginning of the stack frame unwind info section
pub static __EH_FRAME_BEGIN__: [u8; 0] = [];
... | drop_in_place | identifier_name |
parser.rs | use regex::Regex;
use std::collections::HashMap;
fn build_rules(path: &str) -> HashMap<String, String> {
let mut map_rules = HashMap::new();
//ASCII character classes
map_rules.insert("alnum".to_string(), "[0-9A-Za-z]".to_string());
map_rules.insert("alpha".to_string(), "[A-Za-z]".to_string());
map_rules.insert(... |
#[test]
fn test_expand_def(){
let rules: HashMap<String, String> = build_rules("path");
let formatted1 = expand_definitions("{digit}+ and {lower}.*", rules.clone());
let formatted2 = expand_definitions("{word}.* or {alnum}", rules.clone());
let formatted3 = expand_definitions("{ascii} and {blank}.*", rules.clone... | {
let re = Regex::new(r"(\{[:alpha:]{1,}\})").unwrap();
let mut text = String::from(s);
for cap in re.captures_iter(s) {
let tmp = cap.at(1).unwrap_or("");
let key = &tmp[1..tmp.len()-1];
text = text.replace(tmp, &map[key]);
}
text
} | identifier_body |
parser.rs | use regex::Regex;
use std::collections::HashMap;
fn build_rules(path: &str) -> HashMap<String, String> {
let mut map_rules = HashMap::new();
//ASCII character classes
map_rules.insert("alnum".to_string(), "[0-9A-Za-z]".to_string());
map_rules.insert("alpha".to_string(), "[A-Za-z]".to_string());
map_rules.insert(... | fn test_expand_def(){
let rules: HashMap<String, String> = build_rules("path");
let formatted1 = expand_definitions("{digit}+ and {lower}.*", rules.clone());
let formatted2 = expand_definitions("{word}.* or {alnum}", rules.clone());
let formatted3 = expand_definitions("{ascii} and {blank}.*", rules.clone());
as... | #[test] | random_line_split |
parser.rs | use regex::Regex;
use std::collections::HashMap;
fn | (path: &str) -> HashMap<String, String> {
let mut map_rules = HashMap::new();
//ASCII character classes
map_rules.insert("alnum".to_string(), "[0-9A-Za-z]".to_string());
map_rules.insert("alpha".to_string(), "[A-Za-z]".to_string());
map_rules.insert("ascii".to_string(), "[\\x00-\\x7F]".to_string());
map_rules.in... | build_rules | identifier_name |
bitstring.rs | /// Bit Strings are length/value pairs, so that bit strings with leading
/// zeros aren't conflated.
#[derive(Eq,PartialEq,Hash,Debug,Clone,Copy)]
pub struct BS {
pub length: i64,
pub value: i64,
}
pub trait BitString {
fn pow(_: i64, _: i64) -> i64;
fn flip(_: i64, _: i64) -> i64;
fn is_set(_: i64... |
/// The maximum supported length of a bitstring is 30 bits.
const MAX_LEN: i64 = 30;
}
#[test]
fn test_pow() {
assert_eq!(BS::pow(0, 0), 1);
assert_eq!(BS::pow(42, 0), 1);
assert_eq!(BS::pow(-2, 0), 1);
assert_eq!(BS::pow(2, 4), 16);
assert_eq!(BS::pow(-2, 3), -8);
}
#[test]
fn test_flip... | {
BS {
length: bs.length,
value:(bs.value << i) & (2i64.pow(bs.length as u32) - 1),
}
} | identifier_body |
bitstring.rs | /// Bit Strings are length/value pairs, so that bit strings with leading | }
pub trait BitString {
fn pow(_: i64, _: i64) -> i64;
fn flip(_: i64, _: i64) -> i64;
fn is_set(_: i64, _: i64) -> bool;
fn prepend(_: i64, _: BS) -> BS;
fn length(_: BS) -> i64;
fn shift_left(_: BS, _: i64) -> BS;
const MAX_LEN: i64;
}
impl BitString for BS {
/// `pow(b, n)` yields ... | /// zeros aren't conflated.
#[derive(Eq,PartialEq,Hash,Debug,Clone,Copy)]
pub struct BS {
pub length: i64,
pub value: i64, | random_line_split |
bitstring.rs | /// Bit Strings are length/value pairs, so that bit strings with leading
/// zeros aren't conflated.
#[derive(Eq,PartialEq,Hash,Debug,Clone,Copy)]
pub struct BS {
pub length: i64,
pub value: i64,
}
pub trait BitString {
fn pow(_: i64, _: i64) -> i64;
fn flip(_: i64, _: i64) -> i64;
fn is_set(_: i64... | () {
assert_eq!(BS::prepend(0, BS { length: 0, value: 0 }), BS { length: 1, value: 0 });
assert_eq!(BS::prepend(1, BS { length: 0, value: 0 }), BS { length: 1, value: 1 });
assert_eq!(BS::prepend(1, BS { length: 1, value: 1 }), BS { length: 2, value: 3 });
assert_eq!(BS::prepend(0, BS { length: 1, value... | test_prepend | identifier_name |
open_close.rs | extern crate xiapi_sys;
extern crate libc;
use xiapi_sys::xiapi;
use libc::c_void;
use std::mem;
use std::ffi::CString;
fn run() -> Result<(),String> {
let mut numDevices = 0u32;
unsafe {
let result = xiapi::xiGetNumberDevices(&mut numDevices);
println!("xiGetNumberDevices:\treturn: {}\tvalue... |
let mut width: i32 = 0;
let mut height: i32 = 0;
let mut data_format: i32 = 0;
// always use auto exposure/gain
let mut mvret = xiapi::xiSetParamInt( *handle, CString::new(xiapi::XI_PRM_AEAG).unwrap().as_ptr(), 1);
println!("set param result {}", mvret);
// al... | {
return Err(String::from("Open XI_DEVICE failed"));
} | conditional_block |
open_close.rs | extern crate xiapi_sys;
extern crate libc;
use xiapi_sys::xiapi;
use libc::c_void;
use std::mem;
use std::ffi::CString;
fn | () -> Result<(),String> {
let mut numDevices = 0u32;
unsafe {
let result = xiapi::xiGetNumberDevices(&mut numDevices);
println!("xiGetNumberDevices:\treturn: {}\tvalue: {}", result, numDevices);
if(numDevices == 0){
return Err(String::from("no devices listed"));
}
... | run | identifier_name |
open_close.rs | extern crate xiapi_sys;
extern crate libc;
use xiapi_sys::xiapi;
use libc::c_void;
use std::mem;
use std::ffi::CString;
fn run() -> Result<(),String> | let mut data_format: i32 = 0;
// always use auto exposure/gain
let mut mvret = xiapi::xiSetParamInt( *handle, CString::new(xiapi::XI_PRM_AEAG).unwrap().as_ptr(), 1);
println!("set param result {}", mvret);
// always use auto white balance for color cameras
mvret = xiapi... | {
let mut numDevices = 0u32;
unsafe {
let result = xiapi::xiGetNumberDevices(&mut numDevices);
println!("xiGetNumberDevices:\treturn: {}\tvalue: {}", result, numDevices);
if(numDevices == 0){
return Err(String::from("no devices listed"));
}
let wIndex = 0;
... | identifier_body |
open_close.rs | extern crate xiapi_sys;
extern crate libc;
use xiapi_sys::xiapi;
use libc::c_void;
use std::mem;
use std::ffi::CString;
fn run() -> Result<(),String> {
let mut numDevices = 0u32;
unsafe {
let result = xiapi::xiGetNumberDevices(&mut numDevices);
println!("xiGetNumberDevices:\treturn: {}\tvalue... |
// always use auto exposure/gain
let mut mvret = xiapi::xiSetParamInt( *handle, CString::new(xiapi::XI_PRM_AEAG).unwrap().as_ptr(), 1);
println!("set param result {}", mvret);
// always use auto white balance for color cameras
mvret = xiapi::xiSetParamInt( *handle, CString::new... | let mut width: i32 = 0;
let mut height: i32 = 0;
let mut data_format: i32 = 0; | random_line_split |
f23.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 mut x = 23is;
let mut y = 23is;
let mut z = 23is;
while x > 0is {
x -= 1is;
while y > 0is {
y -= 1is;
while z > 0is { z -= 1is; }
if x > 10is {
return;
"unreachable";
}
}
}
} | identifier_body | |
f23.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 mut x = 23is;
let mut y = 23is;
let mut z = 23is;
while x > 0is {
x -= 1is;
while y > 0is {
y -= 1is;
while z > 0is { z -= 1is; }
if x > 10is {
return;
"unreachable";
}
}
}
}
| expr_while_23 | identifier_name |
f23.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... | random_line_split | |
f23.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 ... |
}
}
}
| {
return;
"unreachable";
} | conditional_block |
noop_waker.rs | //! Utilities for creating zero-cost wakers that don't do anything.
use core::task::{RawWaker, RawWakerVTable, Waker};
use core::ptr::null;
#[cfg(feature = "std")]
use core::cell::UnsafeCell;
unsafe fn noop_clone(_data: *const ()) -> RawWaker {
noop_raw_waker()
}
unsafe fn noop(_data: *const ()) |
const NOOP_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(noop_clone, noop, noop, noop);
fn noop_raw_waker() -> RawWaker {
RawWaker::new(null(), &NOOP_WAKER_VTABLE)
}
/// Create a new [`Waker`] which does
/// nothing when `wake()` is called on it.
///
/// # Examples
///
/// ```
/// use futures::task::noop_w... | {} | identifier_body |
noop_waker.rs | //! Utilities for creating zero-cost wakers that don't do anything.
use core::task::{RawWaker, RawWakerVTable, Waker};
use core::ptr::null;
#[cfg(feature = "std")]
use core::cell::UnsafeCell;
unsafe fn noop_clone(_data: *const ()) -> RawWaker {
noop_raw_waker()
} | fn noop_raw_waker() -> RawWaker {
RawWaker::new(null(), &NOOP_WAKER_VTABLE)
}
/// Create a new [`Waker`] which does
/// nothing when `wake()` is called on it.
///
/// # Examples
///
/// ```
/// use futures::task::noop_waker;
/// let waker = noop_waker();
/// waker.wake();
/// ```
#[inline]
pub fn noop_waker() -> W... |
unsafe fn noop(_data: *const ()) {}
const NOOP_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(noop_clone, noop, noop, noop);
| random_line_split |
noop_waker.rs | //! Utilities for creating zero-cost wakers that don't do anything.
use core::task::{RawWaker, RawWakerVTable, Waker};
use core::ptr::null;
#[cfg(feature = "std")]
use core::cell::UnsafeCell;
unsafe fn noop_clone(_data: *const ()) -> RawWaker {
noop_raw_waker()
}
unsafe fn noop(_data: *const ()) {}
const NOOP_W... | () -> &'static Waker {
thread_local! {
static NOOP_WAKER_INSTANCE: UnsafeCell<Waker> =
UnsafeCell::new(noop_waker());
}
NOOP_WAKER_INSTANCE.with(|l| unsafe { &*l.get() })
}
| noop_waker_ref | identifier_name |
mod.rs | use std::net::*;
use std::thread::{sleep, spawn, JoinHandle};
use std::time::*;
use super::ai::*;
use super::drawer::*;
use super::map::*;
use super::messages::*;
use super::paths::*;
use super::responses::*;
use super::units::*;
use error::*;
use networking::*;
use settings::*;
mod client;
mod server;
pub use self:... | (map: Map, settings: Settings) -> Result<(Server, ThreadHandle, ThreadHandle)> {
let (ai_1_conn, server_ai_1_conn) = make_connections();
let (ai_2_conn, server_ai_2_conn) = make_connections();
let server = Server::new_local(map, server_ai_1_conn, server_ai_2_conn, settings)?;
let mut ai_1 = AIClient::n... | ai_vs_ai | identifier_name |
mod.rs | use std::net::*;
use std::thread::{sleep, spawn, JoinHandle};
use std::time::*;
use super::ai::*;
use super::drawer::*;
use super::map::*;
use super::messages::*;
use super::paths::*;
use super::responses::*;
use super::units::*;
use error::*;
use networking::*;
use settings::*;
mod client;
mod server;
pub use self:... |
pub fn multiplayer(addr: &str, map: Map, settings: Settings) -> Result<(Client, ThreadHandle)> {
let (client_conn, server_conn) = make_connections();
let mut server = Server::new_one_local(addr, map, server_conn, settings)?;
let server = spawn(move || server.run());
let client = Client::new(client_co... | {
let (player_conn, server_player_conn) = make_connections();
let (ai_conn, server_ai_conn) = make_connections();
let mut server = Server::new_local(map, server_player_conn, server_ai_conn, settings)?;
let server = spawn(move || server.run());
let client = Client::new(player_conn)?;
let mut ai_... | identifier_body |
mod.rs | use std::net::*; | use std::time::*;
use super::ai::*;
use super::drawer::*;
use super::map::*;
use super::messages::*;
use super::paths::*;
use super::responses::*;
use super::units::*;
use error::*;
use networking::*;
use settings::*;
mod client;
mod server;
pub use self::client::*;
use self::server::*;
// A connection from a clien... | use std::thread::{sleep, spawn, JoinHandle}; | random_line_split |
test_modbus_server.rs | use libmodbus::{Modbus, ModbusServer, ModbusTCP};
#[test]
#[ignore]
fn receive() | }
}
#[test]
#[ignore]
fn reply() {
let _modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
}
| {
let mut query = vec![0; Modbus::MAX_ADU_LENGTH as usize];
// create server
match Modbus::new_tcp("127.0.0.1", 1502) {
Ok(mut server) => {
let mut socket = server.tcp_listen(1).expect("could not listen");
server
.tcp_accept(&mut socket)
.expec... | identifier_body |
test_modbus_server.rs | use libmodbus::{Modbus, ModbusServer, ModbusTCP};
#[test]
#[ignore]
fn receive() {
let mut query = vec![0; Modbus::MAX_ADU_LENGTH as usize];
// create server
match Modbus::new_tcp("127.0.0.1", 1502) {
Ok(mut server) => {
let mut socket = server.tcp_listen(1).expect("could not listen");
... | fn reply() {
let _modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
} | #[ignore] | random_line_split |
test_modbus_server.rs | use libmodbus::{Modbus, ModbusServer, ModbusTCP};
#[test]
#[ignore]
fn receive() {
let mut query = vec![0; Modbus::MAX_ADU_LENGTH as usize];
// create server
match Modbus::new_tcp("127.0.0.1", 1502) {
Ok(mut server) => {
let mut socket = server.tcp_listen(1).expect("could not listen");
... | () {
let _modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
}
| reply | identifier_name |
specialcrate.rs | // Code by Johannes Schickling <schickling.j@gmail.com>,
// https://github.com/schickling/rust-examples/tree/master/snake-ncurses
// minor revisions accoring to changed rust-spedicifactions were made in
// order to successfully compile the code, game.rs and main.rs were
// merged into specialcrate.rs. Code was publishe... |
fn give_chance_to_fire (&self) -> Option<Bullet> {
let mut rng = rand::thread_rng();
let temp: f32 = rng.gen_range(0.0, 1.0);
if temp > 0.996 {
Some(Bullet::new(Vector { x: self.position.x,
y: self.position.y + 1 }, Direction::Down))
} else {
... | {
let x = &mut self.position.x;
self.direction = match self.direction {
Direction::Left if *x < 0 => Direction::Right,
Direction::Right if *x == bounds.x => Direction::Left,
_ => self.direction.clone()
};
match self.direction {
Direction::L... | identifier_body |
specialcrate.rs | // Code by Johannes Schickling <schickling.j@gmail.com>,
// https://github.com/schickling/rust-examples/tree/master/snake-ncurses
// minor revisions accoring to changed rust-spedicifactions were made in
// order to successfully compile the code, game.rs and main.rs were
// merged into specialcrate.rs. Code was publishe... | (bounds: Vector) -> Game {
let mut invaders = vec!();
//for i in range(0i32, bounds.x / 3) {
for i in 0i32..(bounds.x / 3) {
invaders.push(Invader::new( Vector { x: 2 * i, y: 0 }));
}
Game {
bounds: bounds,
invaders: invaders,
pl... | new | identifier_name |
specialcrate.rs | // Code by Johannes Schickling <schickling.j@gmail.com>,
// https://github.com/schickling/rust-examples/tree/master/snake-ncurses
// minor revisions accoring to changed rust-spedicifactions were made in
// order to successfully compile the code, game.rs and main.rs were
// merged into specialcrate.rs. Code was publishe... |
if self.snake.hits_wall(self.bounds) {
Err(GameError::Wall)
} else if self.snake.hits_itself() {
Err(GameError::Suicide)
} else {
Ok(())
}
}
pub fn get_snake_vectors (&self) -> &[Vector] {
let ref v = self.snake.segments;
&v[... | {
self.snake.grow();
self.bullet = Vector::random(self.bounds);
} | conditional_block |
specialcrate.rs | // Code by Johannes Schickling <schickling.j@gmail.com>,
// https://github.com/schickling/rust-examples/tree/master/snake-ncurses
// minor revisions accoring to changed rust-spedicifactions were made in
// order to successfully compile the code, game.rs and main.rs were
// merged into specialcrate.rs. Code was publishe... | draw_char(segment, '#');
}
}
direction = get_new_direction(direction);
board.set_direction(direction);
match board.tick() {
Err(err) => {
match err {
GameError::Wall => show_text("You hit the wall, stupid."),
... | for segment in segments.iter() { | random_line_split |
useless_chaining.rs | // Copyright 2018 Chao Lin & William Sergeant (Sorbonne University)
// 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... | } | // test33 = &test32 | random_line_split |
tokenizer.rs | //! Provides functionality for tokenizing sentences and words
use crate::dnm::{DNMRange, DNM};
use crate::stopwords;
use std::cmp;
use std::collections::vec_deque::*;
use std::collections::HashSet;
use std::iter::Peekable;
use std::str::Chars;
use regex::Regex;
/// Stores auxiliary resources required by the tokenizer... | if left_window.len() >= window_size {
left_window.pop_front();
}
}
//TODO: Handle dot-dot-dot "..."
else {
// Not a special case, break the sentence
// Reset the left window
left_w... | {
// Regular word case.
// Check for abbreviations:
// Longest abbreviation is 6 characters, but MathFormula is 11, so take window
// of window_size chars to the left (allow for a space before dot)
let lw_string: String = left_window.clone().into_ite... | conditional_block |
tokenizer.rs | //! Provides functionality for tokenizing sentences and words
use crate::dnm::{DNMRange, DNM};
use crate::stopwords;
use std::cmp;
use std::collections::vec_deque::*;
use std::collections::HashSet;
use std::iter::Peekable;
use std::str::Chars;
use regex::Regex;
/// Stores auxiliary resources required by the tokenizer... | let space_char = text_iterator.next().unwrap();
end += space_char.len_utf8();
}
if text_iterator.peek() == None {
break;
}
// Uppercase next?
if wordlike_with_upper_next(&text_iterator) {
// Ok, uppercase, but is it a stop... | {
let text = &dnm.plaintext;
let mut sentences: Vec<DNMRange<'a>> = Vec::new();
let mut text_iterator = text.chars().peekable();
let mut start = 0;
let mut end = 0;
let window_size = 12; // size of max string + 1
let mut left_window: VecDeque<char> = VecDeque::with_capacity(window_size);
... | identifier_body |
tokenizer.rs | //! Provides functionality for tokenizing sentences and words
use crate::dnm::{DNMRange, DNM};
use crate::stopwords;
use std::cmp;
use std::collections::vec_deque::*;
use std::collections::HashSet;
use std::iter::Peekable;
use std::str::Chars;
use regex::Regex;
/// Stores auxiliary resources required by the tokenizer... | }
}
upper_found
}
impl Tokenizer {
/// gets the sentences from a dnm
pub fn sentences<'a>(&self, dnm: &'a DNM) -> Vec<DNMRange<'a>> {
let text = &dnm.plaintext;
let mut sentences: Vec<DNMRange<'a>> = Vec::new();
let mut text_iterator = text.chars().peekable();
let mut start = 0;
let mut... | }
} else {
break; | random_line_split |
tokenizer.rs | //! Provides functionality for tokenizing sentences and words
use crate::dnm::{DNMRange, DNM};
use crate::stopwords;
use std::cmp;
use std::collections::vec_deque::*;
use std::collections::HashSet;
use std::iter::Peekable;
use std::str::Chars;
use regex::Regex;
/// Stores auxiliary resources required by the tokenizer... | a>(left: Option<&'a char>, right: Option<&'a char>) -> bool {
let pair = [left, right];
match pair {
[Some(&'['), Some(&']')]
| [Some(&'('), Some(&')')]
| [Some(&'{'), Some(&'}')]
| [Some(&'"'), Some(&'"')] => true,
_ => false,
}
}
/// Obtains the next word from the `Peekable<Chars>` iterator... | _bounded<' | identifier_name |
app_chooser.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::{from_glib_none};
use ffi;
use cast::GTK_APP_CHOOSER;
pub trait App... | }
}
fn get_content_info(&self) -> Option<String> {
unsafe {
from_glib_none(
ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget())))
}
}
fn refresh(&self) -> () {
unsafe { ffi::gtk_app_chooser_refresh(GTK_APP_CHOOSER(self... | random_line_split | |
app_chooser.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::{from_glib_none};
use ffi;
use cast::GTK_APP_CHOOSER;
pub trait App... |
fn refresh(&self) -> () {
unsafe { ffi::gtk_app_chooser_refresh(GTK_APP_CHOOSER(self.unwrap_widget())) }
}
}
| {
unsafe {
from_glib_none(
ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget())))
}
} | identifier_body |
app_chooser.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::{from_glib_none};
use ffi;
use cast::GTK_APP_CHOOSER;
pub trait App... | (&self) -> Option<::AppInfo> {
let tmp_pointer = unsafe { ffi::gtk_app_chooser_get_app_info(GTK_APP_CHOOSER(self.unwrap_widget())) };
if tmp_pointer.is_null() {
None
} else {
Some(::FFIWidget::wrap_widget(tmp_pointer as *mut ffi::C_GtkWidget))
}
}
fn get... | get_app_info | identifier_name |
app_chooser.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::{from_glib_none};
use ffi;
use cast::GTK_APP_CHOOSER;
pub trait App... | else {
Some(::FFIWidget::wrap_widget(tmp_pointer as *mut ffi::C_GtkWidget))
}
}
fn get_content_info(&self) -> Option<String> {
unsafe {
from_glib_none(
ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget())))
}
}
fn ... | {
None
} | conditional_block |
size_constraint.rs | use std::cmp::min;
/// Single-dimensional constraint on a view size.
///
/// This describes a possible behaviour for a [`ResizedView`].
///
/// [`ResizedView`]: crate::views::ResizedView
#[derive(Debug, Clone, Copy)]
pub enum SizeConstraint {
/// No constraint imposed, the child view's response is used.
Free,
... | (self, (result, available): (usize, usize)) -> usize {
match self {
SizeConstraint::AtLeast(value) if result < value => value,
SizeConstraint::AtMost(value) if result > value => value,
SizeConstraint::Fixed(value) => value,
SizeConstraint::Full if available > resu... | result | identifier_name |
size_constraint.rs | use std::cmp::min;
/// Single-dimensional constraint on a view size.
///
/// This describes a possible behaviour for a [`ResizedView`].
///
/// [`ResizedView`]: crate::views::ResizedView
#[derive(Debug, Clone, Copy)]
pub enum SizeConstraint {
/// No constraint imposed, the child view's response is used.
Free,
... | }
/// Returns the size the child view should actually use.
///
/// When it said it wanted `result`.
pub fn result(self, (result, available): (usize, usize)) -> usize {
match self {
SizeConstraint::AtLeast(value) if result < value => value,
SizeConstraint::AtMost(valu... | random_line_split | |
size_constraint.rs | use std::cmp::min;
/// Single-dimensional constraint on a view size.
///
/// This describes a possible behaviour for a [`ResizedView`].
///
/// [`ResizedView`]: crate::views::ResizedView
#[derive(Debug, Clone, Copy)]
pub enum SizeConstraint {
/// No constraint imposed, the child view's response is used.
Free,
... |
}
}
/// Returns the size the child view should actually use.
///
/// When it said it wanted `result`.
pub fn result(self, (result, available): (usize, usize)) -> usize {
match self {
SizeConstraint::AtLeast(value) if result < value => value,
SizeConstraint::... | {
min(value, available)
} | conditional_block |
main.rs | #[macro_use] extern crate log;
extern crate env_logger;
extern crate futures;
extern crate hyper;
extern crate tokio_core;
extern crate tokio_process;
extern crate tokio_io;
mod manage;
mod subprocesses;
mod util;
use std::net::SocketAddr;
use std::thread;
use manage::Admin;
use subprocesses::Subprocesses;
use util... | () {
let subprocesses = Subprocesses::new();
let addr: SocketAddr = "0.0.0.0:9989".parse().unwrap();
let admin = Admin::new(addr);
let admin_thread = thread::Builder::new()
.name("admin".into())
.spawn(move || admin.run().expect("could not run admin"))
.expect("could not spawn admi... | main | identifier_name |
main.rs | #[macro_use] extern crate log;
extern crate env_logger;
extern crate futures;
extern crate hyper;
extern crate tokio_core;
extern crate tokio_process;
extern crate tokio_io;
mod manage;
mod subprocesses;
mod util;
use std::net::SocketAddr;
use std::thread;
use manage::Admin;
use subprocesses::Subprocesses;
use util... | {
let subprocesses = Subprocesses::new();
let addr: SocketAddr = "0.0.0.0:9989".parse().unwrap();
let admin = Admin::new(addr);
let admin_thread = thread::Builder::new()
.name("admin".into())
.spawn(move || admin.run().expect("could not run admin"))
.expect("could not spawn admi... | identifier_body | |
main.rs | #[macro_use] extern crate log;
extern crate env_logger;
| extern crate tokio_io;
mod manage;
mod subprocesses;
mod util;
use std::net::SocketAddr;
use std::thread;
use manage::Admin;
use subprocesses::Subprocesses;
use util::Runner;
fn main() {
let subprocesses = Subprocesses::new();
let addr: SocketAddr = "0.0.0.0:9989".parse().unwrap();
let admin = Admin::n... | extern crate futures;
extern crate hyper;
extern crate tokio_core;
extern crate tokio_process; | random_line_split |
async-fn-size.rs | // run-pass
// aux-build:arc_wake.rs
// edition:2018
extern crate arc_wake;
use std::pin::Pin;
use std::future::Future;
use std::sync::{
Arc,
atomic::{self, AtomicUsize},
};
use std::task::{Context, Poll};
use arc_wake::ArcWake;
struct Counter {
wakes: AtomicUsize,
}
impl ArcWake for Counter {
fn wa... |
async fn await3_level1() -> u8 {
base().await + base().await + base().await
}
async fn await3_level2() -> u8 {
await3_level1().await + await3_level1().await + await3_level1().await
}
async fn await3_level3() -> u8 {
await3_level2().await + await3_level2().await + await3_level2().await
}
async fn await3... | {
base().await + base().await
} | identifier_body |
async-fn-size.rs | // run-pass
// aux-build:arc_wake.rs
// edition:2018
extern crate arc_wake;
use std::pin::Pin;
use std::future::Future;
use std::sync::{
Arc,
atomic::{self, AtomicUsize},
};
use std::task::{Context, Poll};
use arc_wake::ArcWake;
struct Counter {
wakes: AtomicUsize,
}
impl ArcWake for Counter {
fn wa... | () -> u8 {
await3_level4().await + await3_level4().await + await3_level4().await
}
fn main() {
assert_eq!(2, std::mem::size_of_val(&base()));
assert_eq!(3, std::mem::size_of_val(&await1_level1()));
assert_eq!(4, std::mem::size_of_val(&await2_level1()));
assert_eq!(5, std::mem::size_of_val(&await3_l... | await3_level5 | identifier_name |
async-fn-size.rs | // run-pass
// aux-build:arc_wake.rs
// edition:2018
extern crate arc_wake;
use std::pin::Pin;
use std::future::Future;
use std::sync::{
Arc,
atomic::{self, AtomicUsize},
};
use std::task::{Context, Poll};
use arc_wake::ArcWake;
struct Counter {
wakes: AtomicUsize,
}
impl ArcWake for Counter {
fn wa... |
async fn await3_level2() -> u8 {
await3_level1().await + await3_level1().await + await3_level1().await
}
async fn await3_level3() -> u8 {
await3_level2().await + await3_level2().await + await3_level2().await
}
async fn await3_level4() -> u8 {
await3_level3().await + await3_level3().await + await3_level3(... | random_line_split | |
matrix_market.rs | use std::fs;
use std::path::Path;
use crate::sparse::CsMatrix; | struct MatrixMarketParser;
// FIXME: return an Error instead of an Option.
/// Parses a Matrix Market file at the given path, and returns the corresponding sparse matrix.
pub fn cs_matrix_from_matrix_market<N: RealField, P: AsRef<Path>>(path: P) -> Option<CsMatrix<N>> {
let file = fs::read_to_string(path).ok()?;
... | use crate::RealField;
use pest::Parser;
#[derive(Parser)]
#[grammar = "io/matrix_market.pest"] | random_line_split |
matrix_market.rs | use std::fs;
use std::path::Path;
use crate::sparse::CsMatrix;
use crate::RealField;
use pest::Parser;
#[derive(Parser)]
#[grammar = "io/matrix_market.pest"]
struct MatrixMarketParser;
// FIXME: return an Error instead of an Option.
/// Parses a Matrix Market file at the given path, and returns the corresponding spa... |
// FIXME: return an Error instead of an Option.
/// Parses a Matrix Market file described by the given string, and returns the corresponding sparse matrix.
pub fn cs_matrix_from_matrix_market_str<N: RealField>(data: &str) -> Option<CsMatrix<N>> {
let file = MatrixMarketParser::parse(Rule::Document, data)
.... | {
let file = fs::read_to_string(path).ok()?;
cs_matrix_from_matrix_market_str(&file)
} | identifier_body |
matrix_market.rs | use std::fs;
use std::path::Path;
use crate::sparse::CsMatrix;
use crate::RealField;
use pest::Parser;
#[derive(Parser)]
#[grammar = "io/matrix_market.pest"]
struct MatrixMarketParser;
// FIXME: return an Error instead of an Option.
/// Parses a Matrix Market file at the given path, and returns the corresponding spa... | <N: RealField, P: AsRef<Path>>(path: P) -> Option<CsMatrix<N>> {
let file = fs::read_to_string(path).ok()?;
cs_matrix_from_matrix_market_str(&file)
}
// FIXME: return an Error instead of an Option.
/// Parses a Matrix Market file described by the given string, and returns the corresponding sparse matrix.
pub f... | cs_matrix_from_matrix_market | identifier_name |
matrix_market.rs | use std::fs;
use std::path::Path;
use crate::sparse::CsMatrix;
use crate::RealField;
use pest::Parser;
#[derive(Parser)]
#[grammar = "io/matrix_market.pest"]
struct MatrixMarketParser;
// FIXME: return an Error instead of an Option.
/// Parses a Matrix Market file at the given path, and returns the corresponding spa... |
_ => return None, // FIXME: return an Err instead.
}
}
Some(CsMatrix::from_triplet(
shape.0, shape.1, &rows, &cols, &data,
))
}
| {
let mut inner = line.into_inner();
// NOTE: indices are 1-based.
rows.push(inner.next()?.as_str().parse::<usize>().ok()? - 1);
cols.push(inner.next()?.as_str().parse::<usize>().ok()? - 1);
data.push(crate::convert(inner.next()?.as_str().p... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.