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
session.rs
use std::io::Write; use nickel::{Continue, FormBody, Halt, MediaType, Middleware, MiddlewareResult, Request, Response}; use redis::Commands; use api::consumer::response::BADSESSION;
pub struct SessionMiddleware; impl<D> Middleware<D> for SessionMiddleware { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, mut rep: Response<'mw, D>) -> MiddlewareResult<'mw, D> { // Verify the scrobble session i...
use api::rds::RedisExtension; use api::routes::CONSUMER_HANDSHAKE; pub const SESSION_KEY: &'static str = "audioscrobbler:session";
random_line_split
session.rs
use std::io::Write; use nickel::{Continue, FormBody, Halt, MediaType, Middleware, MiddlewareResult, Request, Response}; use redis::Commands; use api::consumer::response::BADSESSION; use api::rds::RedisExtension; use api::routes::CONSUMER_HANDSHAKE; pub const SESSION_KEY: &'static str = "audioscrobbler:session"; pub...
return Ok(Halt(stream)); } } } Ok(Continue(rep)) } }
{ // Verify the scrobble session id, to be used in all now-playing and submission requests. if req.path_without_query() .map(|p| p.starts_with(CONSUMER_HANDSHAKE) && p.len() > CONSUMER_HANDSHAKE.len()) .unwrap_or(false) { if !match try_with!(rep, req.redis_conn()).get...
identifier_body
session.rs
use std::io::Write; use nickel::{Continue, FormBody, Halt, MediaType, Middleware, MiddlewareResult, Request, Response}; use redis::Commands; use api::consumer::response::BADSESSION; use api::rds::RedisExtension; use api::routes::CONSUMER_HANDSHAKE; pub const SESSION_KEY: &'static str = "audioscrobbler:session"; pub...
<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, mut rep: Response<'mw, D>) -> MiddlewareResult<'mw, D> { // Verify the scrobble session id, to be used in all now-playing and submission requests. if req.path_without_query...
invoke
identifier_name
ai.rs
extern crate rand; use chess::logic::{Figure, Board, Position}; use chess::player::{Player, PlayerType}; use self::rand::{thread_rng, Rng}; /// Returns a move for the AI, depending on which one it is pub fn get_move(board: &Board, me: &Player, other: &Player) -> (Position, Position) { // If AI is stupid if ...
(board: &mut Board, me: &mut Player, other: &mut Player) -> (Position, Position) { let my_moves = me.get_possible_moves(board, other); let move_values: Vec<(i32, (Position, Position))> = my_moves.iter() .map(|x| (capture_and_evade(board, x, me, oth...
get_dumb_move
identifier_name
ai.rs
extern crate rand; use chess::logic::{Figure, Board, Position}; use chess::player::{Player, PlayerType}; use self::rand::{thread_rng, Rng}; /// Returns a move for the AI, depending on which one it is pub fn get_move(board: &Board, me: &Player, other: &Player) -> (Position, Position) { // If AI is stupid if ...
.map(|x| (capture_and_evade(board, x, me, other), *x)) .collect(); if let Some(at) = move_values.iter().max_by_key(|x| x.0) { if at.0 == 0 { return random_move(&my_moves...
let move_values: Vec<(i32, (Position, Position))> = my_moves.iter()
random_line_split
ai.rs
extern crate rand; use chess::logic::{Figure, Board, Position}; use chess::player::{Player, PlayerType}; use self::rand::{thread_rng, Rng}; /// Returns a move for the AI, depending on which one it is pub fn get_move(board: &Board, me: &Player, other: &Player) -> (Position, Position) { // If AI is stupid if ...
/// Return a measure that tries to capture opponent figures and evade being captured fn capture_and_evade(board: &mut Board, pos: &(Position, Position), active: &mut Player, inactive: &mut Player) -> i32 { let capture = { if board.is_capture_move(pos.0, pos.1) { figure_value(&board.get_figure...
{ let my_moves = me.get_possible_moves(board, other); let move_values: Vec<(i32, (Position, Position))> = my_moves.iter() .map(|x| (capture_and_evade(board, x, me, other), *x)) .colle...
identifier_body
table_caption.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/. */ //! CSS table formatting contexts. use layout::block::BlockFlow; use layout::construct::FlowConstructor; use layo...
(&mut self, ctx: &mut LayoutContext) { debug!("assign_height_inorder: assigning height for table_caption"); self.block_flow.assign_height_inorder(ctx); } fn assign_height(&mut self, ctx: &mut LayoutContext) { debug!("assign_height: assigning height for table_caption"); self.bloc...
assign_height_inorder
identifier_name
table_caption.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/. */ //! CSS table formatting contexts. use layout::block::BlockFlow; use layout::construct::FlowConstructor; use layo...
fn debug_str(&self) -> ~str { let txt = ~"TableCaptionFlow: "; txt.append(match self.block_flow.box_ { Some(ref rb) => rb.debug_str(), None => ~"", }) } }
{ }
identifier_body
table_caption.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/. */ //! CSS table formatting contexts. use layout::block::BlockFlow; use layout::construct::FlowConstructor; use layo...
debug!("assign_height: assigning height for table_caption"); self.block_flow.assign_height(ctx); } /// table-caption has margins but is not collapsed with a sibling(table) /// or its parents(table-wrapper). /// Therefore, margins to be collapsed do not exist. fn collapse_margins(&mu...
fn assign_height(&mut self, ctx: &mut LayoutContext) {
random_line_split
buf_writer.rs
use futures_core::task::{Context, Poll}; use futures_io::{AsyncSeek, AsyncWrite, IoSlice, SeekFrom}; use pin_utils::{unsafe_pinned, unsafe_unpinned}; use std::fmt; use std::io::{self, Write}; use std::pin::Pin; use super::DEFAULT_BUF_SIZE; /// Wraps a writer and buffers its output. /// /// It can be excessively ineffi...
fn poll_write_vectored( mut self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>], ) -> Poll<io::Result<usize>> { let total_len = bufs.iter().map(|b| b.len()).sum::<usize>(); if self.buf.len() + total_len > self.buf.capacity() { ready!(self.as_mut...
{ if self.buf.len() + buf.len() > self.buf.capacity() { ready!(self.as_mut().flush_buf(cx))?; } if buf.len() >= self.buf.capacity() { self.inner().poll_write(cx, buf) } else { Poll::Ready(self.buf().write(buf)) } }
identifier_body
buf_writer.rs
use futures_core::task::{Context, Poll}; use futures_io::{AsyncSeek, AsyncWrite, IoSlice, SeekFrom}; use pin_utils::{unsafe_pinned, unsafe_unpinned}; use std::fmt; use std::io::{self, Write}; use std::pin::Pin; use super::DEFAULT_BUF_SIZE; /// Wraps a writer and buffers its output. /// /// It can be excessively ineffi...
if buf.len() >= self.buf.capacity() { self.inner().poll_write(cx, buf) } else { Poll::Ready(self.buf().write(buf)) } } fn poll_write_vectored( mut self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>], ) -> Poll<io::Result<...
{ ready!(self.as_mut().flush_buf(cx))?; }
conditional_block
buf_writer.rs
use futures_core::task::{Context, Poll}; use futures_io::{AsyncSeek, AsyncWrite, IoSlice, SeekFrom}; use pin_utils::{unsafe_pinned, unsafe_unpinned}; use std::fmt; use std::io::{self, Write}; use std::pin::Pin; use super::DEFAULT_BUF_SIZE; /// Wraps a writer and buffers its output. /// /// It can be excessively ineffi...
self.inner().poll_seek(cx, pos) } }
mut self: Pin<&mut Self>, cx: &mut Context<'_>, pos: SeekFrom, ) -> Poll<io::Result<u64>> { ready!(self.as_mut().flush_buf(cx))?;
random_line_split
buf_writer.rs
use futures_core::task::{Context, Poll}; use futures_io::{AsyncSeek, AsyncWrite, IoSlice, SeekFrom}; use pin_utils::{unsafe_pinned, unsafe_unpinned}; use std::fmt; use std::io::{self, Write}; use std::pin::Pin; use super::DEFAULT_BUF_SIZE; /// Wraps a writer and buffers its output. /// /// It can be excessively ineffi...
(inner: W) -> Self { Self::with_capacity(DEFAULT_BUF_SIZE, inner) } /// Creates a new `BufWriter` with the specified buffer capacity. pub fn with_capacity(cap: usize, inner: W) -> Self { Self { inner, buf: Vec::with_capacity(cap), written: 0, } ...
new
identifier_name
edenapi.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::sync::Arc; use std::time::Duration; use futures::StreamExt; use futures_batch::ChunksTimeoutStreamExt; use edenapi::EdenApi; use e...
}; let trees = HashMap::new(); let client = FakeEdenApi::new() .files_with_flags(files) .trees(trees) .into_arc(); let remote_files = EdenApiRemoteStore::<File>::new("repo", client, None); let files_adapter = Arc::new(remote_files.get_scmstore_a...
{ // Set up mocked EdenAPI file and tree stores. let lfs_metadata = Metadata { size: Some(4), flags: Some(Metadata::LFS_FLAG), }; let nonlfs_metadata = Metadata { size: Some(4), flags: None, }; let lfs_key = key("a", "def6f...
identifier_body
edenapi.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::sync::Arc; use std::time::Duration; use futures::StreamExt; use futures_batch::ChunksTimeoutStreamExt; use edenapi::EdenApi; use e...
() -> Result<(), ()> { // Set up mocked EdenAPI file and tree stores. let lfs_metadata = Metadata { size: Some(4), flags: Some(Metadata::LFS_FLAG), }; let nonlfs_metadata = Metadata { size: Some(4), flags: None, }; let lfs_...
test_files_extstore_use
identifier_name
edenapi.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::sync::Arc; use std::time::Duration; use futures::StreamExt; use futures_batch::ChunksTimeoutStreamExt; use edenapi::EdenApi; use e...
lfs_metadata, ); let nonlfs_entry = FileEntry::new( nonlfs_key, nonlfs_bytes.to_vec().into(), Parents::default(), nonlfs_metadata, ); let exepcted = vec![Err(FetchError::not_found(lfs_key)), Ok(nonlfs_entry)]; assert_e...
lfs_key.clone(), lfs_bytes.to_vec().into(), Parents::default(),
random_line_split
raytrace.rs
use rand; use std; use prelude::*; use scene; pub struct Output { data : Vec<RGB>, w : u32, h : u32, } impl Output { pub fn new(w: u32, h: u32) -> Self { Output { data : std::iter::repeat(RGB { r: 0.0, g: 0.0, b: 0.0 }).take((w * h) as usize).collect(), w : w, h : h, } ...
scene::Texture::SolidColor(color) => color, }; let color = work.attenuation * color; *output.pixel_mut(work.pixel_x, work.pixel_y) += color * collision.object.emittance; let make_ray = { let location = collision.location; move |direction| { Ray { direction : direction, o...
let color = match collision.object.texture {
random_line_split
raytrace.rs
use rand; use std; use prelude::*; use scene; pub struct Output { data : Vec<RGB>, w : u32, h : u32, } impl Output { pub fn new(w: u32, h: u32) -> Self { Output { data : std::iter::repeat(RGB { r: 0.0, g: 0.0, b: 0.0 }).take((w * h) as usize).collect(), w : w, h : h, } ...
{ pub ray : Ray, pub pixel_x : u32, pub pixel_y : u32, pub attenuation : RGB, } fn cast<'a>(s: &'a scene::T, ray: &Ray) -> Option<scene::Collision<'a>> { let mut first_collision: Option<scene::Collision<'a>> = None; for object in &s.objects { if let Some(collision) = object.intersect_...
Work
identifier_name
raytrace.rs
use rand; use std; use prelude::*; use scene; pub struct Output { data : Vec<RGB>, w : u32, h : u32, } impl Output { pub fn new(w: u32, h: u32) -> Self { Output { data : std::iter::repeat(RGB { r: 0.0, g: 0.0, b: 0.0 }).take((w * h) as usize).collect(), w : w, h : h, } ...
first_collision = Some(collision); } } first_collision } fn perturb<Rng: rand::Rng>(unperturbed: Vector, normal: Vector, shininess: f32, rng: &mut Rng) -> Vector { let rotation = { let y = unperturbed; let x = if unperturbed.x <= 0.5 { // specialized cross-product for crossing w...
{ if first_collision.toi < collision.toi { continue } }
conditional_block
clone.rs
// Copyright 2012-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-MI...
(&mut self, source: &Self) { *self = source.clone() } } #[stable] impl<'a, T:?Sized> Clone for &'a T { /// Return a shallow copy of the reference. #[inline] fn clone(&self) -> &'a T { *self } } macro_rules! clone_impl { ($t:ty) => { #[stable] impl Clone for $t { ...
clone_from
identifier_name
clone.rs
// Copyright 2012-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-MI...
} macro_rules! clone_impl { ($t:ty) => { #[stable] impl Clone for $t { /// Return a deep copy of the value. #[inline] fn clone(&self) -> $t { *self } } } } clone_impl! { int } clone_impl! { i8 } clone_impl! { i16 } clone_impl! { i32 } clone_impl! { ...
{ *self }
identifier_body
clone.rs
// Copyright 2012-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-MI...
/// Return a copy of a function pointer #[inline] fn clone(&self) -> extern "Rust" fn($($A),*) -> ReturnType { *self } } ) } extern_fn_clone! {} extern_fn_clone! { A } extern_fn_clone! { A, B } extern_fn_clone! { A, B, C } extern_fn_clone! { A, B, C, D } extern_fn_clone!...
#[experimental = "this may not be sufficient for fns with region parameters"] impl<$($A,)* ReturnType> Clone for extern "Rust" fn($($A),*) -> ReturnType {
random_line_split
main.rs
extern crate piston; extern crate piston_window; extern crate graphics; extern crate opengl_graphics; extern crate rand; #[cfg(test)] #[macro_use(expect)] extern crate expectest; use piston_window::WindowSettings; use opengl_graphics::{GlGraphics, OpenGL}; use std::cell::RefCell; use std::rc::Rc; mod actors; mod int...
{ let opengl = OpenGL::V3_2; let config = Config::new(); let dims = [config.width() as u32, config.height() as u32]; let window_settings = WindowSettings::new("vs-game", dims).exit_on_esc(true); let window = Rc::new(RefCell::new(window_settings.build().unwrap())); let mut gl = GlGraphics::new...
identifier_body
main.rs
extern crate piston; extern crate piston_window; extern crate graphics; extern crate opengl_graphics; extern crate rand; #[cfg(test)] #[macro_use(expect)] extern crate expectest; use piston_window::WindowSettings; use opengl_graphics::{GlGraphics, OpenGL}; use std::cell::RefCell; use std::rc::Rc; mod actors; mod int...
let window_settings = WindowSettings::new("vs-game", dims).exit_on_esc(true); let window = Rc::new(RefCell::new(window_settings.build().unwrap())); let mut gl = GlGraphics::new(opengl); let mut rng = rand::thread_rng(); let mut scene: Box<Scene> = Box::new(MainScene::new(1, &config, &mut rng)); ...
let opengl = OpenGL::V3_2; let config = Config::new(); let dims = [config.width() as u32, config.height() as u32];
random_line_split
main.rs
extern crate piston; extern crate piston_window; extern crate graphics; extern crate opengl_graphics; extern crate rand; #[cfg(test)] #[macro_use(expect)] extern crate expectest; use piston_window::WindowSettings; use opengl_graphics::{GlGraphics, OpenGL}; use std::cell::RefCell; use std::rc::Rc; mod actors; mod int...
() { let opengl = OpenGL::V3_2; let config = Config::new(); let dims = [config.width() as u32, config.height() as u32]; let window_settings = WindowSettings::new("vs-game", dims).exit_on_esc(true); let window = Rc::new(RefCell::new(window_settings.build().unwrap())); let mut gl = GlGraphics::...
main
identifier_name
htmlheadelement.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::DocumentBinding::DocumentMethods; use crate::dom::bindings::codegen:...
} } } impl VirtualMethods for HTMLHeadElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree...
{ let content = content.value(); let content_val = content.trim(); if !content_val.is_empty() { doc.set_referrer_policy(determine_policy_for_token(content_val)); return; } }
conditional_block
htmlheadelement.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::DocumentBinding::DocumentMethods; use crate::dom::bindings::codegen:...
}
{ if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } load_script(self); }
identifier_body
htmlheadelement.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::DocumentBinding::DocumentMethods; use crate::dom::bindings::codegen:...
(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } load_script(self); } }
bind_to_tree
identifier_name
htmlheadelement.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::DocumentBinding::DocumentMethods; use crate::dom::bindings::codegen:...
return; } } } } } impl VirtualMethods for HTMLHeadElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(r...
let content_val = content.trim(); if !content_val.is_empty() { doc.set_referrer_policy(determine_policy_for_token(content_val));
random_line_split
area_frame_allocator.rs
use memory::{Frame, FrameAllocator}; use memory::areas::{Area, AreaIter, memory_areas}; use memory::paging::{PhysicalAddress}; #[derive(Debug)] pub struct AreaFrameAllocator { next_free_frame: Frame, current_area: Option<&'static Area>, areas: AreaIter, kernel_start: Frame, kernel_end: Frame, } im...
else { None // no free frames left } } fn deallocate_frame(&mut self, _frame: Frame) { unimplemented!() } }
{ let frame = Frame{ number: self.next_free_frame.number }; let current_area_last_frame = { let address = area.base + area.length - 1; Frame::containing_address(PhysicalAddress::new(address as usize)) }; if frame > current_area_last_frame ...
conditional_block
area_frame_allocator.rs
use memory::{Frame, FrameAllocator}; use memory::areas::{Area, AreaIter, memory_areas}; use memory::paging::{PhysicalAddress}; #[derive(Debug)] pub struct AreaFrameAllocator { next_free_frame: Frame, current_area: Option<&'static Area>, areas: AreaIter, kernel_start: Frame, kernel_end: Frame, } im...
(&mut self) { self.current_area = self.areas.clone().filter(|area| { let address = area.base + area.length - 1; Frame::containing_address(PhysicalAddress::new(address as usize)) >= self.next_free_frame }).min_by_key(|area| area.base); if let Some(area) = self.cur...
choose_next_area
identifier_name
area_frame_allocator.rs
use memory::{Frame, FrameAllocator}; use memory::areas::{Area, AreaIter, memory_areas}; use memory::paging::{PhysicalAddress}; #[derive(Debug)] pub struct AreaFrameAllocator { next_free_frame: Frame, current_area: Option<&'static Area>, areas: AreaIter, kernel_start: Frame, kernel_end: Frame, } im...
}
{ unimplemented!() }
identifier_body
area_frame_allocator.rs
use memory::{Frame, FrameAllocator}; use memory::areas::{Area, AreaIter, memory_areas};
current_area: Option<&'static Area>, areas: AreaIter, kernel_start: Frame, kernel_end: Frame, } impl AreaFrameAllocator { pub fn new(kernel_start: PhysicalAddress, kernel_end: PhysicalAddress) -> AreaFrameAllocator { let mut allocator = AreaFrameAllocator { next_free_frame: Fram...
use memory::paging::{PhysicalAddress}; #[derive(Debug)] pub struct AreaFrameAllocator { next_free_frame: Frame,
random_line_split
k_means.rs
//! K-means Classification //! //! Provides implementation of K-Means classification. //! //! # Usage //! //! ``` //! use rusty_machine::linalg::Matrix; //! use rusty_machine::learning::k_means::KMeansClassifier; //! use rusty_machine::learning::UnSupModel; //! //! let inputs = Matrix::new(3, 2, vec![1.0, 2.0, 1.0, 3.0...
} /// Train the classifier using input data. fn train(&mut self, inputs: &Matrix<f64>) { self.init_centroids(inputs).expect("Could not initialize centroids."); let mut cost = 0.0; let eps = 1e-14; for _i in 0..self.iters { let (idx, distances) = self.get_closes...
{ panic!("Model has not been trained."); }
conditional_block
k_means.rs
//! K-means Classification //! //! Provides implementation of K-Means classification. //! //! # Usage //! //! ``` //! use rusty_machine::linalg::Matrix; //! use rusty_machine::learning::k_means::KMeansClassifier; //! use rusty_machine::learning::UnSupModel; //! //! let inputs = Matrix::new(3, 2, vec![1.0, 2.0, 1.0, 3.0...
} /// The K-means ++ initialization scheme. #[derive(Debug)] pub struct KPlusPlus; impl Initializer for KPlusPlus { fn init_centroids(&self, k: usize, inputs: &Matrix<f64>) -> Result<Matrix<f64>, Error> { let mut rng = thread_rng(); let mut init_centroids = Vec::with_capacity(k * inputs.cols());...
{ // Populate so we have something in each class. let mut random_assignments = (0..k).map(|i| vec![i]).collect::<Vec<Vec<usize>>>(); let mut rng = thread_rng(); for i in k..inputs.rows() { let idx = rng.gen_range(0, k); unsafe { random_assignments.get_unchecked_m...
identifier_body
k_means.rs
//! K-means Classification //! //! Provides implementation of K-Means classification. //! //! # Usage //! //! ``` //! use rusty_machine::linalg::Matrix; //! use rusty_machine::learning::k_means::KMeansClassifier; //! use rusty_machine::learning::UnSupModel; //! //! let inputs = Matrix::new(3, 2, vec![1.0, 2.0, 1.0, 3.0...
; impl Initializer for RandomPartition { fn init_centroids(&self, k: usize, inputs: &Matrix<f64>) -> Result<Matrix<f64>, Error> { // Populate so we have something in each class. let mut random_assignments = (0..k).map(|i| vec![i]).collect::<Vec<Vec<usize>>>(); let mut rng = thread_rng(); ...
RandomPartition
identifier_name
k_means.rs
//! K-means Classification //! //! Provides implementation of K-Means classification. //! //! # Usage //! //! ``` //! use rusty_machine::linalg::Matrix; //! use rusty_machine::learning::k_means::KMeansClassifier; //! use rusty_machine::learning::UnSupModel; //! //! let inputs = Matrix::new(3, 2, vec![1.0, 2.0, 1.0, 3.0...
//! //! // Where test_inputs is a Matrix with features in columns. //! let a = model.predict(&test_inputs); //! ``` //! //! Additionally you can control the initialization //! algorithm and max number of iterations. //! //! # Initializations //! //! Three initialization algorithms are supported. //! //! ## Forgy initia...
//! // Create model with k(=2) classes. //! let mut model = KMeansClassifier::new(2); //! //! // Where inputs is a Matrix with features in columns. //! model.train(&inputs);
random_line_split
eve2pcap.rs
// Copyright (C) 2020 Jason Ish // // 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, including // without limitation the rights to use, copy, modify, merge, publish, // ...
} "payload" => { let ts = event.timestamp().ok_or_else(|| { ApiError::BadRequest("bad or missing timestamp field".to_string()) })?; let packet = pcap::packet_from_payload(&event).map_err(|err| { let msg = format!("Failed to create packe...
let ts = event.timestamp().ok_or_else(|| { ApiError::BadRequest("bad or missing timestamp field".to_string()) })?; let pcap_buffer = pcap::create(linktype, ts, packet); return Ok((headers, pcap_buffer));
random_line_split
eve2pcap.rs
// Copyright (C) 2020 Jason Ish // // 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, including // without limitation the rights to use, copy, modify, merge, publish, // ...
_ => { return Err(ApiError::BadRequest("invalid value for what".to_string())); } } }
{ let ts = event.timestamp().ok_or_else(|| { ApiError::BadRequest("bad or missing timestamp field".to_string()) })?; let packet = pcap::packet_from_payload(&event).map_err(|err| { let msg = format!("Failed to create packet from payload: {:?}", err); ...
conditional_block
eve2pcap.rs
// Copyright (C) 2020 Jason Ish // // 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, including // without limitation the rights to use, copy, modify, merge, publish, // ...
pcap::LinkType::Ethernet as u32 }; let packet = &event["packet"] .as_str() .map(base64::decode) .ok_or_else(|| ApiError::BadRequest("no packet in event".to_string()))? .map_err(|err| { ApiError::BadR...
{ let headers = Headers(vec![ ( HeaderName::from_static("content-type"), HeaderValue::from_static("application/vnc.tcpdump.pcap"), ), ( HeaderName::from_static("content-disposition"), HeaderValue::from_static("attachment; filename=event.pcap"),...
identifier_body
eve2pcap.rs
// Copyright (C) 2020 Jason Ish // // 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, including // without limitation the rights to use, copy, modify, merge, publish, // ...
{ pub what: String, pub event: String, } pub(crate) async fn handler( Extension(_context): Extension<Arc<ServerContext>>, _session: SessionExtractor, Form(form): Form<PcapForm>, ) -> Result<impl IntoResponse, ApiError> { let headers = Headers(vec![ ( HeaderName::from_static...
PcapForm
identifier_name
regions-in-enums.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 ...
enum yes1<'a> { X4(&'a usize) } enum no0 { X5(&'foo usize) //~ ERROR use of undeclared lifetime name `'foo` } enum no1 { X6(&'a usize) //~ ERROR use of undeclared lifetime name `'a` } fn main() {}
random_line_split
regions-in-enums.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 ...
<'lt> { X3(&'lt usize) } enum yes1<'a> { X4(&'a usize) } enum no0 { X5(&'foo usize) //~ ERROR use of undeclared lifetime name `'foo` } enum no1 { X6(&'a usize) //~ ERROR use of undeclared lifetime name `'a` } fn main() {}
yes0
identifier_name
test_cksum.rs
// spell-checker:ignore (words) asdf use crate::common::util::*; #[test] fn test_single_file() { new_ucmd!() .arg("lorem_ipsum.txt") .succeeds() .stdout_is_fixture("single_file.expected"); } #[test] fn test_multiple_files() { new_ucmd!() .arg("lorem_ipsum.txt") .arg("alice_...
() { let (_, mut ucmd) = at_and_ucmd!(); let result = ucmd.arg("larger_than_2056_bytes.txt").succeeds(); let mut stdout_split = result.stdout_str().split(' '); let cksum: i64 = stdout_split.next().unwrap().parse().unwrap(); let bytes_cnt: i64 = stdout_split.next().unwrap().parse().unwrap(); ...
test_stdin_larger_than_128_bytes
identifier_name
test_cksum.rs
// spell-checker:ignore (words) asdf use crate::common::util::*; #[test] fn test_single_file() { new_ucmd!() .arg("lorem_ipsum.txt") .succeeds() .stdout_is_fixture("single_file.expected"); } #[test] fn test_multiple_files() { new_ucmd!() .arg("lorem_ipsum.txt") .arg("alice_...
#[test] fn test_invalid_file() { let ts = TestScenario::new(util_name!()); let at = ts.fixtures.clone(); let folder_name = "asdf"; // First check when file doesn't exist ts.ucmd() .arg(folder_name) .fails() .no_stdout() .stderr_contains("cksum: asdf: No such file or d...
{ let (at, mut ucmd) = at_and_ucmd!(); let input = "foobarfoobar"; // spell-checker:disable-line at.touch("a"); ucmd.arg("a") .pipe_in(input.as_bytes()) // the command might have exited before all bytes have been pipe in. // in that case, we don't care about the error (broken p...
identifier_body
test_cksum.rs
// spell-checker:ignore (words) asdf use crate::common::util::*; #[test] fn test_single_file() { new_ucmd!() .arg("lorem_ipsum.txt") .succeeds() .stdout_is_fixture("single_file.expected"); } #[test] fn test_multiple_files() { new_ucmd!() .arg("lorem_ipsum.txt") .arg("alice_...
fn test_empty() { let (at, mut ucmd) = at_and_ucmd!(); at.touch("a"); ucmd.arg("a") .succeeds() .no_stderr() .normalized_newlines_stdout_is("4294967295 0 a\n"); } #[test] fn test_arg_overrides_stdin() { let (at, mut ucmd) = at_and_ucmd!(); let input = "foobarfoobar"; // spell...
#[test]
random_line_split
screen.rs
extern crate screenshot;
extern crate image; use screenshot::get_screenshot; use bmp::{Image, Pixel}; fn main() { let s = get_screenshot(0).unwrap(); println!("{} x {} x {} = {} bytes", s.height(), s.width(), s.pixel_width(), s.raw_len()); let origin = s.get_pixel(0, 0); println!("(0,0): R: {}, G: {}, B: {}", origin.r, origin.g, origin...
extern crate bmp;
random_line_split
screen.rs
extern crate screenshot; extern crate bmp; extern crate image; use screenshot::get_screenshot; use bmp::{Image, Pixel}; fn
() { let s = get_screenshot(0).unwrap(); println!("{} x {} x {} = {} bytes", s.height(), s.width(), s.pixel_width(), s.raw_len()); let origin = s.get_pixel(0, 0); println!("(0,0): R: {}, G: {}, B: {}", origin.r, origin.g, origin.b); let end_col = s.get_pixel(0, s.width()-1); println!("(0,end): R: {}, G: {}, B:...
main
identifier_name
screen.rs
extern crate screenshot; extern crate bmp; extern crate image; use screenshot::get_screenshot; use bmp::{Image, Pixel}; fn main()
img.set_pixel(col as u32, row as u32, Pixel {r: p.r, g: p.g, b: p.b}); } } img.save("test.bmp").unwrap(); image::save_buffer("test.png", s.as_ref(), s.width() as u32, s.height() as u32, image::RGBA(8)) .unwrap(); }
{ let s = get_screenshot(0).unwrap(); println!("{} x {} x {} = {} bytes", s.height(), s.width(), s.pixel_width(), s.raw_len()); let origin = s.get_pixel(0, 0); println!("(0,0): R: {}, G: {}, B: {}", origin.r, origin.g, origin.b); let end_col = s.get_pixel(0, s.width()-1); println!("(0,end): R: {}, G: {}, B: {}...
identifier_body
geometry.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 app_units::{Au, MAX_AU}; use euclid::point::Point2D; use euclid::rect::Rect; use euclid::size::Size2D; use std...
/// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-independent reference length. This unit corresponds to Android's /// "density-independent pixel" (dip), Mac OS X's "p...
// Units for use with euclid::length and euclid::scale_factor.
random_line_split
geometry.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 app_units::{Au, MAX_AU}; use euclid::point::Point2D; use euclid::rect::Rect; use euclid::size::Size2D; use std...
(rect: Rect<f32>) -> Rect<Au> { Rect::new(Point2D::new(Au::from_f32_px(rect.origin.x), Au::from_f32_px(rect.origin.y)), Size2D::new(Au::from_f32_px(rect.size.width), Au::from_f32_px(rect.size.height))) } /// A helper function to convert a rect of `Au` pixels to a rect of f32 units. pub fn au_rect_to_...
f32_rect_to_au_rect
identifier_name
circle.rs
use {Color, Dimensions, LineStyle, Scalar}; use super::oval::Oval; use super::Style as Style; /// A tiny wrapper around the **Oval** widget type. #[derive(Copy, Clone, Debug)] pub struct Circle; fn rad_to_dim(radius: Scalar) -> Dimensions { let side = radius * 2.0; [side, side] } impl Circle { /// Bu...
(radius: Scalar, color: Color) -> Oval { Oval::fill_with(rad_to_dim(radius), color) } /// Build a new circular **Outline**d **Oval** widget. pub fn outline(radius: Scalar) -> Oval { Oval::outline(rad_to_dim(radius)) } /// Build a new circular **Oval** **Outline**d with the given st...
fill_with
identifier_name
circle.rs
use {Color, Dimensions, LineStyle, Scalar}; use super::oval::Oval; use super::Style as Style; /// A tiny wrapper around the **Oval** widget type. #[derive(Copy, Clone, Debug)] pub struct Circle; fn rad_to_dim(radius: Scalar) -> Dimensions { let side = radius * 2.0; [side, side] } impl Circle { /// Bu...
/// Build a new circular **Oval** **Outline**d with the given style. pub fn outline_styled(radius: Scalar, line_style: LineStyle) -> Oval { Oval::outline_styled(rad_to_dim(radius), line_style) } }
{ Oval::outline(rad_to_dim(radius)) }
identifier_body
circle.rs
use {Color, Dimensions, LineStyle, Scalar}; use super::oval::Oval; use super::Style as Style; /// A tiny wrapper around the **Oval** widget type. #[derive(Copy, Clone, Debug)] pub struct Circle; fn rad_to_dim(radius: Scalar) -> Dimensions { let side = radius * 2.0; [side, side] } impl Circle { /// Bui...
/// Build a new circular **Oval** **Outline**d with the given style. pub fn outline_styled(radius: Scalar, line_style: LineStyle) -> Oval { Oval::outline_styled(rad_to_dim(radius), line_style) } }
pub fn outline(radius: Scalar) -> Oval { Oval::outline(rad_to_dim(radius)) }
random_line_split
day5.rs
extern crate hyper; extern crate rustc_serialize; extern crate url; use std::io::Read; use hyper::Client; use rustc_serialize::{Encodable, json}; use url::form_urlencoded; fn get_content(url: &str) -> hyper::Result<String> { let client = Client::new(); let mut response = client.get(url).send()?; let mut b...
() { println!("24 days of Rust - hyper (day 5)"); println!("{:?}", get_content("http://httpbin.org/status/200")); let query = vec![("key", "value"), ("foo", "bar")]; println!("{}", post_query("http://httpbin.org/post", query).unwrap()); let movie = Movie { title: "You Only Live Twice".to_str...
main
identifier_name
day5.rs
extern crate hyper; extern crate rustc_serialize; extern crate url; use std::io::Read; use hyper::Client; use rustc_serialize::{Encodable, json}; use url::form_urlencoded; fn get_content(url: &str) -> hyper::Result<String> {
response.read_to_string(&mut buf)?; Ok(buf) } type Query<'a> = Vec<(&'a str, &'a str)>; fn post_query(url: &str, query: Query) -> hyper::Result<String> { let client = Client::new(); let body = form_urlencoded::Serializer::new(String::new()) .extend_pairs(query.iter()) .finish(); let ...
let client = Client::new(); let mut response = client.get(url).send()?; let mut buf = String::new();
random_line_split
slice.rs
use super::{Parse, ParseElem, ParseLiteral, ParseSlice, RuleResult}; impl<T> Parse for [T] { type PositionRepr = usize; fn start(&self) -> usize { 0 } fn is_eof(&self, pos: usize) -> bool { pos >= self.len() } fn position_repr(&self, pos: usize) -> usize { pos } } ...
} } impl<'input, T: 'input> ParseSlice<'input> for [T] { type Slice = &'input [T]; fn parse_slice(&'input self, p1: usize, p2: usize) -> &'input [T] { &self[p1..p2] } }
{ RuleResult::Failed }
conditional_block
slice.rs
use super::{Parse, ParseElem, ParseLiteral, ParseSlice, RuleResult}; impl<T> Parse for [T] { type PositionRepr = usize; fn start(&self) -> usize { 0 } fn is_eof(&self, pos: usize) -> bool { pos >= self.len() } fn position_repr(&self, pos: usize) -> usize { pos } } ...
}
{ &self[p1..p2] }
identifier_body
slice.rs
use super::{Parse, ParseElem, ParseLiteral, ParseSlice, RuleResult}; impl<T> Parse for [T] { type PositionRepr = usize; fn start(&self) -> usize { 0 } fn is_eof(&self, pos: usize) -> bool { pos >= self.len() } fn position_repr(&self, pos: usize) -> usize { pos } } ...
(&'input self, pos: usize) -> RuleResult<T> { match self[pos..].first() { Some(c) => RuleResult::Matched(pos + 1, *c), None => RuleResult::Failed, } } } impl ParseLiteral for [u8] { fn parse_string_literal(&self, pos: usize, literal: &str) -> RuleResult<()> { let...
parse_elem
identifier_name
slice.rs
use super::{Parse, ParseElem, ParseLiteral, ParseSlice, RuleResult}; impl<T> Parse for [T] { type PositionRepr = usize; fn start(&self) -> usize { 0 } fn is_eof(&self, pos: usize) -> bool { pos >= self.len() } fn position_repr(&self, pos: usize) -> usize { pos } } ...
} }
random_line_split
pointer.rs
use std::{ fmt, hash::{Hash, Hasher}, marker::PhantomData, }; use crate::{Pending, PendingRef, PointerData}; /// The error type which is returned from upgrading /// [`WeakPointer`](struct.WeakPointer.html). #[derive(Debug, PartialEq)] pub struct DeadComponentError; /// A pointer to a component of type `T...
#[inline] fn drop(&mut self) { self.pending.lock().sub_ref.push(self.data.get_index()); } } /// Weak variant of `Pointer`. /// `WeakPointer`s are used to avoid deadlocking when dropping structures with cycled references to each other. /// In the following example `Storage` will stand in memory even...
} impl<T> Drop for Pointer<T> {
random_line_split
pointer.rs
use std::{ fmt, hash::{Hash, Hasher}, marker::PhantomData, }; use crate::{Pending, PendingRef, PointerData}; /// The error type which is returned from upgrading /// [`WeakPointer`](struct.WeakPointer.html). #[derive(Debug, PartialEq)] pub struct DeadComponentError; /// A pointer to a component of type `T...
(&self, other: &WeakPointer<T>) -> bool { self.data == other.data } } impl<T> Eq for WeakPointer<T> {}
eq
identifier_name
pointer.rs
use std::{ fmt, hash::{Hash, Hasher}, marker::PhantomData, }; use crate::{Pending, PendingRef, PointerData}; /// The error type which is returned from upgrading /// [`WeakPointer`](struct.WeakPointer.html). #[derive(Debug, PartialEq)] pub struct DeadComponentError; /// A pointer to a component of type `T...
} impl<T> PartialOrd for Pointer<T> { fn partial_cmp(&self, other: &Pointer<T>) -> Option<std::cmp::Ordering> { if self.data.get_storage_id() == other.data.get_storage_id() { debug_assert!( self.data.get_index()!= other.data.get_index() || self.data.get_epoc...
{ WeakPointer { data: self.data, pending: self.pending.clone(), marker: PhantomData, } }
identifier_body
pointer.rs
use std::{ fmt, hash::{Hash, Hasher}, marker::PhantomData, }; use crate::{Pending, PendingRef, PointerData}; /// The error type which is returned from upgrading /// [`WeakPointer`](struct.WeakPointer.html). #[derive(Debug, PartialEq)] pub struct DeadComponentError; /// A pointer to a component of type `T...
pending.add_ref.push(self.data.get_index()); Ok(Pointer { data: self.data, pending: self.pending.clone(), marker: PhantomData, }) } } impl<T> Clone for WeakPointer<T> { #[inline] fn clone(&self) -> WeakPointer<T> { WeakPointer { ...
{ return Err(DeadComponentError); }
conditional_block
lib.rs
// Copyright 2015-2017 Intecture Developers. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. //! Intecture is an API for managing your servers. You can think of it as a //!...
#![recursion_limit = "1024"] extern crate bytes; extern crate erased_serde; #[macro_use] extern crate error_chain; extern crate futures; extern crate hostname; #[macro_use] extern crate intecture_core_derive; extern crate ipnetwork; #[macro_use] extern crate log; extern crate pnet; extern crate regex; extern crate ser...
//!```
random_line_split
issue-14456.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(); } fn child() { writeln!(&mut io::stdout(), "foo").unwrap(); writeln!(&mut io::stderr(), "bar").unwrap(); let mut stdin = io::stdin(); let mut s = String::new(); stdin.lock().read_line(&mut s).unwrap(); assert_eq!(s.len(), 0); } fn test() { let args: Vec<String> = env::args()....
{ return child() }
conditional_block
issue-14456.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 ...
writeln!(&mut io::stderr(), "bar").unwrap(); let mut stdin = io::stdin(); let mut s = String::new(); stdin.lock().read_line(&mut s).unwrap(); assert_eq!(s.len(), 0); } fn test() { let args: Vec<String> = env::args().collect(); let mut p = Command::new(&args[0]).arg("child") ...
writeln!(&mut io::stdout(), "foo").unwrap();
random_line_split
issue-14456.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 args: Vec<String> = env::args().collect(); if args.len() > 1 && args[1] == "child" { return child() } test(); } fn child() { writeln!(&mut io::stdout(), "foo").unwrap(); writeln!(&mut io::stderr(), "bar").unwrap(); let mut stdin = io::stdin(); let mut s = String::new()...
main
identifier_name
issue-14456.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 ...
fn test() { let args: Vec<String> = env::args().collect(); let mut p = Command::new(&args[0]).arg("child") .stdin(Stdio::capture()) .stdout(Stdio::capture()) .stderr(Stdio::capture()) ...
{ writeln!(&mut io::stdout(), "foo").unwrap(); writeln!(&mut io::stderr(), "bar").unwrap(); let mut stdin = io::stdin(); let mut s = String::new(); stdin.lock().read_line(&mut s).unwrap(); assert_eq!(s.len(), 0); }
identifier_body
classify.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 ...
(stmt: &ast::stmt) -> bool { return match stmt.node { ast::stmt_decl(d, _) => { match d.node { ast::decl_local(_) => true, ast::decl_item(_) => false } } ast::stmt_expr(e, _) => { expr_requires_semi_to_be_stmt(e) } ast::stmt_sem...
stmt_ends_with_semi
identifier_name
classify.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 expr_is_simple_block(e: @ast::expr) -> bool { match e.node { ast::expr_block( codemap::spanned { node: ast::blk_ { rules: ast::default_blk, _ }, _ } ) => true, _ => false } } // this statement requires a semicolon after it. // note that in one case (st...
{ match e.node { ast::expr_if(*) | ast::expr_match(*) | ast::expr_block(_) | ast::expr_while(*) | ast::expr_loop(*) | ast::expr_call(_, _, ast::DoSugar) | ast::expr_call(_, _, ast::ForSugar) | ast::expr_method_call(_, _, _, _, ast::DoSugar) | ast::expr_method_ca...
identifier_body
classify.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 ...
| ast::expr_method_call(_, _, _, _, ast::ForSugar) => false, _ => true } } pub fn expr_is_simple_block(e: @ast::expr) -> bool { match e.node { ast::expr_block( codemap::spanned { node: ast::blk_ { rules: ast::default_blk, _ }, _ } ) => true, _ => fa...
| ast::expr_method_call(_, _, _, _, ast::DoSugar)
random_line_split
token.rs
// Copyright 2019 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
} /// Returns true if the length of this token is zero. pub fn is_empty(&self) -> bool { self.len == 0 } /// Returns a byte slice containing this token. pub fn as_bytes(&self) -> &[u8] { &self.bytes[..self.len as usize] } } impl std::fmt::Display for MsgToken { fn fmt(...
} /// Returns the length of this token. pub fn len(&self) -> usize { self.len as usize
random_line_split
token.rs
// Copyright 2019 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
(x: &[u8]) -> MsgToken { MsgToken::from(x) } /// Returns the length of this token. pub fn len(&self) -> usize { self.len as usize } /// Returns true if the length of this token is zero. pub fn is_empty(&self) -> bool { self.len == 0 } /// Returns a byte slice c...
new
identifier_name
token.rs
// Copyright 2019 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
} impl core::convert::From<i32> for MsgToken { fn from(x: i32) -> Self { core::convert::Into::into(x as u32) } } impl core::convert::From<u16> for MsgToken { fn from(x: u16) -> Self { core::convert::Into::into(x as u32) } } impl core::convert::From<&[u8]> for MsgToken { // Note: ...
{ let mut bytes = [0u8; 8]; let len = encode_u32(x, &mut bytes).len(); MsgToken { len: len as u8, bytes, } }
identifier_body
main.rs
// Copyright (c) 2015 by Stacy Prowell. All rights reserved. // // Licensed under the BSD 2-Clause license. See the file LICENSE // that is part of this distribution. This file may not be copied, // modified, or distributed except according to those terms.extern extern crate linenoise; extern crate getopts; extern ...
// Now run the REPL. repl(); }
random_line_split
main.rs
// Copyright (c) 2015 by Stacy Prowell. All rights reserved. // // Licensed under the BSD 2-Clause license. See the file LICENSE // that is part of this distribution. This file may not be copied, // modified, or distributed except according to those terms.extern extern crate linenoise; extern crate getopts; extern ...
/// Print the command line help. First print the prototype for using the /// command, and then print help about using the switches. /// progname: The program name. /// switches: The allowed command line switch data structure. fn print_usage(progname: &str, switches: Options) { let prototype = format!("Usage: {} [s...
{ let history_filename = relision::get_config_dir() + ("/repl.history"); linenoise::history_load(&history_filename); loop { let val = linenoise::input("e> "); match val { None => { linenoise::history_save(&history_filename); break; } Some(input) => { ...
identifier_body
main.rs
// Copyright (c) 2015 by Stacy Prowell. All rights reserved. // // Licensed under the BSD 2-Clause license. See the file LICENSE // that is part of this distribution. This file may not be copied, // modified, or distributed except according to those terms.extern extern crate linenoise; extern crate getopts; extern ...
(progname: &str, switches: Options) { let prototype = format!("Usage: {} [switches...] [elision files...]", progname); print!("{}", switches.usage(&prototype)); } /// Entry point when run from the prompt. fn main() { println!("Running on {}.", relision::get_platform()); println!("Configuration stored at: {}.",...
print_usage
identifier_name
mod.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
use super::FileAbstractionInstance; use super::Drain; use super::InMemoryFileAbstraction; use store::Entry; use file_abstraction::iter::PathIterator; pub mod mapper; pub mod out; use self::mapper::Mapper; use self::out::StdoutFileAbstraction; // Because this is not exported in super::inmemory; type Backend = Arc<Mute...
use std::fmt::Formatter; use error::StoreErrorKind as SEK; use error::StoreError as SE; use super::FileAbstraction;
random_line_split
mod.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
} impl<W, M> Debug for StdIoFileAbstraction<W, M> where M: Mapper, W: Write { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { write!(f, "StdIoFileAbstraction({:?}", self.0) } } impl<W, M> Deref for StdIoFileAbstraction<W, M> where M: Mapper, W: Write { type...
{ self.0.backend() }
identifier_body
mod.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
(&self, from: &PathBuf, to: &PathBuf) -> Result<(), SE> { self.0.rename(from, to) } fn create_dir_all(&self, pb: &PathBuf) -> Result<(), SE> { self.0.create_dir_all(pb) } fn new_instance(&self, p: PathBuf) -> Box<FileAbstractionInstance> { self.0.new_instance(p) } fn e...
rename
identifier_name
helpers.rs
/* #![deny(warnings)] */ extern crate clap; extern crate fern; extern crate futures; extern crate futures_cpupool; extern crate git2; extern crate josh; extern crate lazy_static; extern crate log; extern crate regex; extern crate tempdir; extern crate tokio_core; use josh::Shell; use tempdir::TempDir; pub struct TestR...
(&self, r: &str) -> String { let (stdout, _) = self.shell.command(&format!("git rev-parse {}", r)); stdout } }
rev
identifier_name
helpers.rs
/* #![deny(warnings)] */ extern crate clap; extern crate fern; extern crate futures; extern crate futures_cpupool; extern crate git2; extern crate josh; extern crate lazy_static; extern crate log; extern crate regex; extern crate tempdir; extern crate tokio_core; use josh::Shell; use tempdir::TempDir; pub struct TestR...
return tr; } pub fn commit(&self, message: &str) -> String { self.shell .command(&format!("git commit -m \"{}\"", message)); let (stdout, _) = self.shell.command("git rev-parse HEAD"); stdout } pub fn add_file(&self, filename: &str) { self.shell ...
random_line_split
helpers.rs
/* #![deny(warnings)] */ extern crate clap; extern crate fern; extern crate futures; extern crate futures_cpupool; extern crate git2; extern crate josh; extern crate lazy_static; extern crate log; extern crate regex; extern crate tempdir; extern crate tokio_core; use josh::Shell; use tempdir::TempDir; pub struct TestR...
pub fn add_file(&self, filename: &str) { self.shell .command(&format!("mkdir -p $(dirname {})", filename)); self.shell .command(&format!("echo test_content > {}", filename)); self.shell.command(&format!("git add {}", filename)); } pub fn rev(&self, r: &str) -...
{ self.shell .command(&format!("git commit -m \"{}\"", message)); let (stdout, _) = self.shell.command("git rev-parse HEAD"); stdout }
identifier_body
wrap.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
#[bench] fn line_of_offset_col_breaks(b: &mut Bencher) { let text = Rope::from(build_short_lines(10_000)); let mut view = View::new(1.into(), BufferId::new(2)); view.debug_force_rewrap_cols(&text, 20); let total_bytes = text.len(); b.iter(|| { for i in 0..total_bytes { let _lin...
let _line = view.line_of_offset(&text, i); } }) }
random_line_split
wrap.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
(b: &mut Bencher) { let text = Rope::from(build_short_lines(10_000)); let view = View::new(1.into(), BufferId::new(2)); let total_bytes = text.len(); b.iter(|| { for i in 0..total_bytes { let _line = view.line_of_offset(&text, i); } }) } #[bench] fn line_of_offset_col_b...
line_of_offset_no_breaks
identifier_name
wrap.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
#[bench] fn line_of_offset_no_breaks(b: &mut Bencher) { let text = Rope::from(build_short_lines(10_000)); let view = View::new(1.into(), BufferId::new(2)); let total_bytes = text.len(); b.iter(|| { for i in 0..total_bytes { let _line = view.line_of_offset(&text, i); } ...
{ let line = "See it, the beautiful ball Poised in the toyshop window, Rounder than sun or moon.\n"; let mut s = String::new(); for _ in 0..n { s += line; } s }
identifier_body
regions-variance-contravariant-use-contravariant.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 main() {}
random_line_split
regions-variance-contravariant-use-contravariant.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> { f: &'a isize } fn use_<'a>(c: Contravariant<'a>) { let x = 3; // 'b winds up being inferred to this call. // Contravariant<'a> <: Contravariant<'call> is true // if 'call <= 'a, which is true, so no error. collapse(&x, c); fn collapse<'b>(x: &'b isize, c: Contravariant<'b>) { } } ...
Contravariant
identifier_name
regions-variance-contravariant-use-contravariant.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 main() {}
{ }
identifier_body
to_num.rs
//! Types convertable to integers use common::get_slice::GetSlice; /// Parse the string to a integer using a given radix pub trait ToNum { fn to_num_radix(&self, radix: usize) -> usize; fn to_num_radix_signed(&self, radix: usize) -> isize; fn to_num(&self) -> usize; fn to_num_signed(&self) -> isize; }...
}
random_line_split
to_num.rs
//! Types convertable to integers use common::get_slice::GetSlice; /// Parse the string to a integer using a given radix pub trait ToNum { fn to_num_radix(&self, radix: usize) -> usize; fn to_num_radix_signed(&self, radix: usize) -> isize; fn to_num(&self) -> usize; fn to_num_signed(&self) -> isize; }...
(&self) -> usize { self.to_num_radix(10) } /// Parse it as a signed integer in base 10 fn to_num_signed(&self) -> isize { self.to_num_radix_signed(10) } }
to_num
identifier_name
to_num.rs
//! Types convertable to integers use common::get_slice::GetSlice; /// Parse the string to a integer using a given radix pub trait ToNum { fn to_num_radix(&self, radix: usize) -> usize; fn to_num_radix_signed(&self, radix: usize) -> isize; fn to_num(&self) -> usize; fn to_num_signed(&self) -> isize; }...
}
{ self.to_num_radix_signed(10) }
identifier_body
to_num.rs
//! Types convertable to integers use common::get_slice::GetSlice; /// Parse the string to a integer using a given radix pub trait ToNum { fn to_num_radix(&self, radix: usize) -> usize; fn to_num_radix_signed(&self, radix: usize) -> isize; fn to_num(&self) -> usize; fn to_num_signed(&self) -> isize; }...
else { break; } if digit >= radix { break; } num *= radix; num += digit; } num } /// Parse the string as a signed integer using a given radix fn to_num_radix_signed(&self, radix: usize) -> isize ...
{ digit = c as usize - 'a' as usize + 10 }
conditional_block
traits-issue-22019.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 ...
(&'g self) where [Node<'g>]:ToOwned<Vec<Node<'g>>> { loop { } } } impl<'h> GraphWalk<'h, Node<'h>> for u64 { fn nodes(&'h self) where [Node<'h>]:ToOwned<Vec<Node<'h>>> { loop { } } } fn main() { }
nodes
identifier_name
traits-issue-22019.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 ...
#![allow(unused_variables)] use std::borrow::ToOwned; pub struct CFGNode; pub type Node<'a> = &'a CFGNode; pub trait GraphWalk<'c, N> { /// Returns all the nodes in this graph. fn nodes(&'c self) where [N]:ToOwned<Vec<N>>; } impl<'g> GraphWalk<'g, Node<'g>> for u32 { fn nodes(&'g self) where [Node<'g>]...
#![allow(missing_copy_implementations)]
random_line_split
traits-issue-22019.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 ...
} fn main() { }
{ loop { } }
identifier_body
state.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::async_client::JsonRpcResponse; #[derive(Debug, Clone, PartialEq, PartialOrd)] pub struct State { pub chain_id: u8, pub version: u64, pub timestamp_usecs: u64, } impl State { pub fn from_response(resp: &JsonR...
if let Some(state) = &*state_writer { if &resp_state < state { return false; } } *state_writer = Some(resp_state); true } }
} pub fn update_state(&self, resp_state: State) -> bool { let mut state_writer = self.last_known_state.write().unwrap();
random_line_split
state.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::async_client::JsonRpcResponse; #[derive(Debug, Clone, PartialEq, PartialOrd)] pub struct State { pub chain_id: u8, pub version: u64, pub timestamp_usecs: u64, } impl State { pub fn from_response(resp: &JsonR...
*state_writer = Some(resp_state); true } }
{ if &resp_state < state { return false; } }
conditional_block
state.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::async_client::JsonRpcResponse; #[derive(Debug, Clone, PartialEq, PartialOrd)] pub struct State { pub chain_id: u8, pub version: u64, pub timestamp_usecs: u64, } impl State { pub fn from_response(resp: &JsonR...
pub fn last_known_state(&self) -> Option<State> { let data = self.last_known_state.read().unwrap(); data.clone() } pub fn update_state(&self, resp_state: State) -> bool { let mut state_writer = self.last_known_state.write().unwrap(); if let Some(state) = &*state_writer { ...
{ Self::default() }
identifier_body