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 |
|---|---|---|---|---|
datatypes.rs | use serde_json;
use std::io;
use std::string::FromUtf8Error;
#[derive(Deserialize, Debug)]
pub struct Event {
pub version: String,
pub event: String,
pub data: DownloadComplete
}
#[derive(Deserialize, Debug)]
pub struct DownloadComplete {
pub update_id: String,
pub update_image: String,
... |
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::Io(err)
}
}
impl From<FromUtf8Error> for Error {
fn from(err: FromUtf8Error) -> Error {
Error::Utf8(err)
}
}
impl From<serde_json::Error> for Error {
fn from(err: serde_json::Error) -> Error {
Error... | Io(io::Error),
Json(serde_json::Error),
Utf8(FromUtf8Error)
} | random_line_split |
datatypes.rs | use serde_json;
use std::io;
use std::string::FromUtf8Error;
#[derive(Deserialize, Debug)]
pub struct Event {
pub version: String,
pub event: String,
pub data: DownloadComplete
}
#[derive(Deserialize, Debug)]
pub struct DownloadComplete {
pub update_id: String,
pub update_image: String,
... |
}
| {
Error::Json(err)
} | identifier_body |
space.rs | use std::marker::PhantomData;
use std::slice;
use cgmath::{BaseFloat, Transform, Transform3};
use id::{Array, Id, Storage};
#[derive(Clone, Copy, Debug)]
pub enum Parent<T> {
None,
Domestic(Id<Node<T>>),
Foreign(Id<Skeleton<T>>, Id<Bone<T>>),
}
#[derive(Debug)]
pub struct Node<T> {
pub name : String,
... | (&mut self, id: Id<Node<T>>) -> &mut Node<T> {
self.nodes.get_mut(id)
}
pub fn find_node(&self, name: &str) -> Option<Id<Node<T>>> {
self.nodes.find_id(|n| n.name == name)
}
pub fn add_node(&mut self, name: String, parent: Parent<T>, local: T)
-> Id<Node<T>> {
... | mut_node | identifier_name |
space.rs | use std::marker::PhantomData;
use std::slice; | None,
Domestic(Id<Node<T>>),
Foreign(Id<Skeleton<T>>, Id<Bone<T>>),
}
#[derive(Debug)]
pub struct Node<T> {
pub name : String,
pub parent: Parent<T>,
pub local: T,
pub world: T,
}
#[derive(Debug)]
pub struct Bone<T> {
pub name : String,
parent: Option<Id<Bone<T>>>,
pub local: T... | use cgmath::{BaseFloat, Transform, Transform3};
use id::{Array, Id, Storage};
#[derive(Clone, Copy, Debug)]
pub enum Parent<T> { | random_line_split |
nodrop.rs | //! The **nodrop** crate from arrayvec
use std::ops::{Deref, DerefMut};
use std::ptr;
/// repr(u8) - Make sure the non-nullable pointer optimization does not occur!
#[repr(u8)]
enum Flag<T> {
Alive(T),
// Dummy u8 field below, again to beat the enum layout opt
Dropped(u8),
}
/// A type holding **T** that... | (&mut self) {
let n = self.0.get();
self.0.set(n + 1);
}
}
{
let _ = NoDrop::new([Bump(flag), Bump(flag)]);
}
assert_eq!(flag.get(), 0);
// test something with the nullable pointer optimization
flag.set(0);
... | drop | identifier_name |
nodrop.rs | //! The **nodrop** crate from arrayvec
use std::ops::{Deref, DerefMut};
use std::ptr;
/// repr(u8) - Make sure the non-nullable pointer optimization does not occur!
#[repr(u8)]
enum Flag<T> {
Alive(T),
// Dummy u8 field below, again to beat the enum layout opt
Dropped(u8),
}
/// A type holding **T** that... | // last one didn't drop.
assert_eq!(flag.get(), 3);
}
} | drop(array.pop());
assert_eq!(flag.get(), 3);
}
| random_line_split |
cursor.rs | //! This module defines a cheaply-copyable cursor into a TokenStream's data.
//!
//! It does this by copying the data into a stably-addressed structured buffer,
//! and holding raw pointers into that buffer to allow walking through delimited
//! sequences cheaply.
//!
//! This module is heavily commented as it contains... | (mut self, seq_delim: Delimiter) -> Option<SeqInfo<'a>> {
// If we're not trying to enter a none-delimited sequence, we want to
// ignore them. We have to make sure to _not_ ignore them when we want
// to enter them, of course. For obvious reasons.
if seq_delim!= Delimiter::None {
... | seq | identifier_name |
cursor.rs | //! This module defines a cheaply-copyable cursor into a TokenStream's data.
//!
//! It does this by copying the data into a stably-addressed structured buffer,
//! and holding raw pointers into that buffer to allow walking through delimited
//! sequences cheaply.
//!
//! This module is heavily commented as it contains... | _ => None
}
}
/// If the cursor is pointing at a Term, return it and a cursor pointing at
/// the next `TokenTree`.
pub fn word(mut self) -> Option<(Cursor<'a>, Span, Term)> {
self.ignore_none();
match *self.entry() {
Entry::Term(span, sym) => {
... | {
// If we're not trying to enter a none-delimited sequence, we want to
// ignore them. We have to make sure to _not_ ignore them when we want
// to enter them, of course. For obvious reasons.
if seq_delim != Delimiter::None {
self.ignore_none();
}
match *sel... | identifier_body |
cursor.rs | //! This module defines a cheaply-copyable cursor into a TokenStream's data.
//!
//! It does this by copying the data into a stably-addressed structured buffer,
//! and holding raw pointers into that buffer to allow walking through delimited
//! sequences cheaply.
//!
//! This module is heavily commented as it contains... | static EMPTY_ENTRY: UnsafeSyncEntry =
UnsafeSyncEntry(Entry::End(0 as *const Entry));
Cursor {
ptr: &EMPTY_ENTRY.0,
scope: &EMPTY_ENTRY.0,
marker: PhantomData,
}
}
/// This create method intelligently exits non-explicitly-entered
/// ... | // This wrapper struct allows us to break the rules and put a `Sync`
// object in global storage.
struct UnsafeSyncEntry(Entry);
unsafe impl Sync for UnsafeSyncEntry {} | random_line_split |
codeblock.rs | use config::highlighting::{get_highlighter, SYNTAX_SET, THEME_SET};
use config::Config;
use std::cmp::min;
use std::collections::HashSet;
use syntect::easy::HighlightLines;
use syntect::highlighting::{Color, Style, Theme};
use syntect::html::{styled_line_to_highlighted_html, IncludeBackground};
use syntect::parsing::Sy... |
}
// Now append the remainder. If the current item was not split, this will
// append the entire item.
if last_split!= item.1.len() {
result.push((item.0, &item.1[last_split..]));
}
}
result
}
fn color_highlighted_lines(data: &mut [(Style, &str)], lines: &... | {
result.push((item.0, &item.1[last_split..split_at]));
last_split = split_at;
} | conditional_block |
codeblock.rs | use config::highlighting::{get_highlighter, SYNTAX_SET, THEME_SET};
use config::Config;
use std::cmp::min;
use std::collections::HashSet;
use syntect::easy::HighlightLines;
use syntect::highlighting::{Color, Style, Theme};
use syntect::html::{styled_line_to_highlighted_html, IncludeBackground};
use syntect::parsing::Sy... | (&mut self, text: &str) -> String {
let highlighted =
self.highlighter.highlight(text, self.extra_syntax_set.unwrap_or(&SYNTAX_SET));
let line_boundaries = self.find_line_boundaries(&highlighted);
// First we make sure that `highlighted` is split at every line
// boundary. T... | highlight | identifier_name |
codeblock.rs | use config::highlighting::{get_highlighter, SYNTAX_SET, THEME_SET};
use config::Config;
use std::cmp::min;
use std::collections::HashSet;
use syntect::easy::HighlightLines;
use syntect::highlighting::{Color, Style, Theme};
use syntect::html::{styled_line_to_highlighted_html, IncludeBackground};
use syntect::parsing::Sy... | }
fn find_line_boundaries(&mut self, styled: &[(Style, &str)]) -> Vec<StyledIdx> {
let mut boundaries = Vec::new();
for (vec_idx, (_style, s)) in styled.iter().enumerate() {
for (str_idx, character) in s.char_indices() {
if character == '\n' {
bou... |
styled_line_to_highlighted_html(&highlighted, self.background) | random_line_split |
codeblock.rs | use config::highlighting::{get_highlighter, SYNTAX_SET, THEME_SET};
use config::Config;
use std::cmp::min;
use std::collections::HashSet;
use syntect::easy::HighlightLines;
use syntect::highlighting::{Color, Style, Theme};
use syntect::html::{styled_line_to_highlighted_html, IncludeBackground};
use syntect::parsing::Sy... |
/// This function assumes that `line_boundaries` is sorted according to the `Ord` impl on
/// the `StyledIdx` type.
fn perform_split<'b>(
split: &[(Style, &'b str)],
line_boundaries: Vec<StyledIdx>,
) -> Vec<(Style, &'b str)> {
let mut result = Vec::new();
let mut idxs_iter = line_boundaries.into_ite... | {
match idx {
Some(idx) if idx.vec_idx == vec_idx => Some(idx.str_idx),
_ => None,
}
} | identifier_body |
predictor.rs | // The MIT License (MIT)
//
// Copyright (c) 2015 dinowernli
//
// 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... | /// Reverts the context tree to a previous state by undoing update
/// operations. The specified size must be at most the current size.
fn revert_to_history_size(&mut self, target_size: usize);
/// Returns the probability, given the current history, that "bits" are the
/// next observed symbols.
fn predict... | random_line_split | |
twister.rs | use std::iter::Iterator;
pub struct Twister {
index: usize,
state: [u32; 624],
}
impl Twister {
pub fn new(seed: u32) -> Twister {
let mut state = [0u32; 624];
state[0] = seed;
for idx in 1..state.len() {
state[idx] = (0x6c078965*(state[idx-1] ^ (state[idx-1] >> 30)) as... | fn first_10_0() {
let t = Twister::new(0);
let first_10 = t.take(10).collect::<Vec<u32>>();
let expected = vec![0x8c7f0aac, 0x97c4aa2f, 0xb716a675, 0xd821ccc0,
0x9a4eb343, 0xdba252fb, 0x8b7d76c3, 0xd8e57d67,
0x6c74a409, 0x9fa1ded3];
... | assert_eq!(t.index, 0);
assert_eq!(t.state[0], 0);
}
#[test] | random_line_split |
twister.rs | use std::iter::Iterator;
pub struct Twister {
index: usize,
state: [u32; 624],
}
impl Twister {
pub fn new(seed: u32) -> Twister {
let mut state = [0u32; 624];
state[0] = seed;
for idx in 1..state.len() {
state[idx] = (0x6c078965*(state[idx-1] ^ (state[idx-1] >> 30)) as... |
fn generate_numbers(&mut self) {
for idx in 0..self.state.len() {
let y = (self.state[idx] & 0x80000000) +
(self.state[(idx + 1) % self.state.len()] & 0x7fffffff);
self.state[idx] = self.state[(idx + 397) % self.state.len()] ^ (y >> 1);
if y % 2!= 0 ... | {
Twister { index: index, state: *state.clone() }
} | identifier_body |
twister.rs | use std::iter::Iterator;
pub struct Twister {
index: usize,
state: [u32; 624],
}
impl Twister {
pub fn new(seed: u32) -> Twister {
let mut state = [0u32; 624];
state[0] = seed;
for idx in 1..state.len() {
state[idx] = (0x6c078965*(state[idx-1] ^ (state[idx-1] >> 30)) as... | () {
let t = Twister::new(0);
let first_10 = t.take(10).collect::<Vec<u32>>();
let expected = vec![0x8c7f0aac, 0x97c4aa2f, 0xb716a675, 0xd821ccc0,
0x9a4eb343, 0xdba252fb, 0x8b7d76c3, 0xd8e57d67,
0x6c74a409, 0x9fa1ded3];
assert_eq![f... | first_10_0 | identifier_name |
twister.rs | use std::iter::Iterator;
pub struct Twister {
index: usize,
state: [u32; 624],
}
impl Twister {
pub fn new(seed: u32) -> Twister {
let mut state = [0u32; 624];
state[0] = seed;
for idx in 1..state.len() {
state[idx] = (0x6c078965*(state[idx-1] ^ (state[idx-1] >> 30)) as... |
}
}
}
impl Iterator for Twister {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.index == 0 {
self.generate_numbers();
}
let mut y = self.state[self.index];
y ^= y >> 11;
y ^= y << 7 & 0x9d2c5680;
y ^= y << 15 & 0xefc60000;
... | {
self.state[idx] ^= 0x9908b0df;
} | conditional_block |
client.rs | use connection::Connection;
use error::{Error, ErrorKind, Result};
use frame::settings::{SettingsFrame, Setting};
use frame::{FrameKind, WriteFrame, ReadFrame};
use {Settings, WindowSize};
pub struct Client<C> {
conn: C,
settings: Settings,
window_in: WindowSize,
window_out: WindowSize,
}
impl<C: Conn... |
#[test]
fn test_client_receive_preface() {
let (mut sconn, cconn) = MockStream::new();
let mut client = Client::new(cconn);
// server preface
let frame = SettingsFrame::default();
sconn.write_frame(frame).unwrap();
client.receive_preface().unwrap();
}
}
| {
let (mut sconn, cconn) = MockStream::new();
let mut client = Client::new(cconn);
client.send_preface().unwrap();
let mut buf = [0; 24];
sconn.read(&mut buf).unwrap();
let preface = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
assert_eq!(&buf, preface);
// settin... | identifier_body |
client.rs | use connection::Connection;
use error::{Error, ErrorKind, Result};
use frame::settings::{SettingsFrame, Setting};
use frame::{FrameKind, WriteFrame, ReadFrame};
use {Settings, WindowSize};
pub struct Client<C> {
conn: C,
settings: Settings,
window_in: WindowSize,
window_out: WindowSize,
}
impl<C: Conn... | (&mut self, frame: SettingsFrame) {
self.settings.update(frame)
}
}
#[cfg(test)]
mod test {
use std::io::Read;
use mock::MockStream;
use super::Client;
use frame::{FrameKind, ReadFrame, WriteFrame};
use frame::settings::SettingsFrame;
#[test]
fn test_client_send_preface() {
... | handle_settings_frame | identifier_name |
client.rs | use connection::Connection;
use error::{Error, ErrorKind, Result};
use frame::settings::{SettingsFrame, Setting};
use frame::{FrameKind, WriteFrame, ReadFrame};
use {Settings, WindowSize};
pub struct Client<C> {
conn: C,
settings: Settings,
window_in: WindowSize,
window_out: WindowSize,
}
impl<C: Conn... | fn test_client_receive_preface() {
let (mut sconn, cconn) = MockStream::new();
let mut client = Client::new(cconn);
// server preface
let frame = SettingsFrame::default();
sconn.write_frame(frame).unwrap();
client.receive_preface().unwrap();
}
} | #[test] | random_line_split |
client.rs | use connection::Connection;
use error::{Error, ErrorKind, Result};
use frame::settings::{SettingsFrame, Setting};
use frame::{FrameKind, WriteFrame, ReadFrame};
use {Settings, WindowSize};
pub struct Client<C> {
conn: C,
settings: Settings,
window_in: WindowSize,
window_out: WindowSize,
}
impl<C: Conn... | else {
return Err(Error::new(ErrorKind::Protocol, "Invalid Preface, bad frame"));
}
Ok(())
}
fn handle_next(&mut self) -> Result<()> {
match try!(self.conn.read_frame(100)) {
FrameKind::Settings(frame) => println!("Settings"),
// Unknown
... | {
if frame.is_ack() {
return Err(Error::new(ErrorKind::Protocol, "Invalid Preface, received ACK"));
}
} | conditional_block |
unreachable-locals.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
fn diverge() ->! {
panic!();
}
| {
after_return();
after_panic();
after_diverging_function();
after_break();
after_continue();
} | identifier_body |
unreachable-locals.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | match (20i32, 'c') {
(a, ref b) => {}
}
for a in &[111i32] {}
}
}
fn after_continue() {
for _ in 0..10i32 {
break;
let x = "0";
let (ref y,z) = (1i32, 2u32);
match (20i32, 'c') {
(a, ref b) => {}
}
for a in &[111i32... | loop {
break;
let x = "0";
let (ref y,z) = (1i32, 2u32); | random_line_split |
unreachable-locals.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
diverge();
let x = "0";
let (ref y,z) = (1i32, 2u32);
match (20i32, 'c') {
(a, ref b) => {}
}
for a in &[111i32] {}
}
fn after_break() {
loop {
break;
let x = "0";
let (ref y,z) = (1i32, 2u32);
match (20i32, 'c') {
(a, ref b) => {}
... | after_diverging_function | identifier_name |
utils.rs | //! Utilities useful for various generations tasks.
use std::ops::{Index, IndexMut};
use std::mem;
use std::iter;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use num::Float;
use na;
use na::{Pnt3, Dim, Cross, Orig};
use ncollide_utils::{HashablePartialEq, AsBytes};
use math::{Scalar, Point, V... |
/// Reverses the clockwising of a set of faces.
#[inline]
pub fn reverse_clockwising(indices: &mut [Pnt3<u32>]) {
for i in indices.iter_mut() {
mem::swap(&mut i.x, &mut i.y);
}
}
/// Duplicates the indices of each triangle on the given index buffer.
///
/// For example: [ (0.0, 1.0, 2.0) ] becomes: [... | {
out.push(Pnt3::new(ul.clone(), dl, dr.clone()));
out.push(Pnt3::new(dr , ur, ul));
} | identifier_body |
utils.rs | //! Utilities useful for various generations tasks.
use std::ops::{Index, IndexMut};
use std::mem;
use std::iter;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use num::Float;
use na;
use na::{Pnt3, Dim, Cross, Orig};
use ncollide_utils::{HashablePartialEq, AsBytes};
use math::{Scalar, Point, V... |
(out, new_coords)
}
/// Computes the normals of a set of vertices.
#[inline]
pub fn compute_normals<P>(coordinates: &[P], faces: &[Pnt3<u32>], normals: &mut Vec<P::Vect>)
where P: Point,
P::Vect: Vect + Cross<CrossProductType = <P as Point>::Vect> {
let mut divisor: Vec<<P::Vect as Vect>::Scalar... | new_coords.shrink_to_fit(); | random_line_split |
utils.rs | //! Utilities useful for various generations tasks.
use std::ops::{Index, IndexMut};
use std::mem;
use std::iter;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use num::Float;
use na;
use na::{Pnt3, Dim, Cross, Orig};
use ncollide_utils::{HashablePartialEq, AsBytes};
use math::{Scalar, Point, V... |
normals[f.x as usize] = normals[f.x as usize] + normal;
normals[f.y as usize] = normals[f.y as usize] + normal;
normals[f.z as usize] = normals[f.z as usize] + normal;
divisor[f.x as usize] = divisor[f.x as usize] + na::one();
divisor[f.y as usize] = divisor[f.y as usize] + na:... |
normal = cross
}
| conditional_block |
utils.rs | //! Utilities useful for various generations tasks.
use std::ops::{Index, IndexMut};
use std::mem;
use std::iter;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use num::Float;
use na;
use na::{Pnt3, Dim, Cross, Orig};
use ncollide_utils::{HashablePartialEq, AsBytes};
use math::{Scalar, Point, V... | (base_circle: u32,
point: u32,
nsubdiv: u32,
out: &mut Vec<Pnt3<u32>>) {
assert!(nsubdiv > 0);
for i in 0.. nsubdiv - 1 {
out.push(Pnt3::new(base_circ... | push_degenerate_open_top_ring_indices | identifier_name |
keyboard.rs | #[cfg(not(any(test, rustdoc)))]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
use std::prelude::v1::*;
use crate::event::Event;
use crate::util::UnsafeContainer;
use crate::KERNEL_EVENTEMITTER;
#[derive(Debug)]
pub enum SpecialKey {
Enter,
}
#[derive(Debug)]
pub enum KeyCode {
Unicode(char),
Spec... | }
lazy_static! {
pub static ref KEYBOARD_HANDLER: UnsafeContainer<KeyboardHandler> =
UnsafeContainer::new(KeyboardHandler::new());
}
#[cfg(all(target_os = "polymorphos", target_arch = "x86_64"))]
pub fn kbd_write_to_screen(c: char) {
vga_print!("{}", c);
}
#[cfg(test)]
pub fn kbd_write_to_screen(c: c... | }
} | random_line_split |
keyboard.rs | #[cfg(not(any(test, rustdoc)))]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
use std::prelude::v1::*;
use crate::event::Event;
use crate::util::UnsafeContainer;
use crate::KERNEL_EVENTEMITTER;
#[derive(Debug)]
pub enum SpecialKey {
Enter,
}
#[derive(Debug)]
pub enum KeyCode {
Unicode(char),
Spec... | {
KEYBOARD_HANDLER.get().process();
} | identifier_body | |
keyboard.rs | #[cfg(not(any(test, rustdoc)))]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
use std::prelude::v1::*;
use crate::event::Event;
use crate::util::UnsafeContainer;
use crate::KERNEL_EVENTEMITTER;
#[derive(Debug)]
pub enum SpecialKey {
Enter,
}
#[derive(Debug)]
pub enum KeyCode {
Unicode(char),
Spec... |
KeyCode::SpecialKey(sp) => match sp {
SpecialKey::Enter => {
kbd_write_to_screen('\n');
let ev = Event::new("console", "input", "keypress", vec!['\n' as u32]);
KERNEL_EVENTEMITTER.get().push_event(ev);
... | {
kbd_write_to_screen(c);
let ev = Event::new("console", "input", "keypress", vec![c as u32]);
KERNEL_EVENTEMITTER.get().push_event(ev);
} | conditional_block |
keyboard.rs | #[cfg(not(any(test, rustdoc)))]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
use std::prelude::v1::*;
use crate::event::Event;
use crate::util::UnsafeContainer;
use crate::KERNEL_EVENTEMITTER;
#[derive(Debug)]
pub enum SpecialKey {
Enter,
}
#[derive(Debug)]
pub enum KeyCode {
Unicode(char),
Spec... | () {
KEYBOARD_HANDLER.get().process();
}
| process_keyboard | identifier_name |
builtin.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | }
struct BuiltinDapp<T: WebApp +'static> {
app: Arc<T>,
}
impl<T: WebApp +'static> BuiltinDapp<T> {
fn new(app: Arc<T>) -> Self {
BuiltinDapp {
app: app,
}
}
}
impl<T: WebApp +'static> handler::Dapp for BuiltinDapp<T> {
type DappFile = BuiltinDappFile<T>;
fn file(&self, path: &str) -> Option<Self::DappF... | author: info.author.into(),
icon_url: info.icon_url.into(),
version: info.version.into(),
}
} | random_line_split |
builtin.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | (&self) -> &File {
self.app.file(&self.path).expect("Check is done when structure is created.")
}
}
impl<T: WebApp +'static> handler::DappFile for BuiltinDappFile<T> {
fn content_type(&self) -> &str {
self.file().content_type
}
fn is_drained(&self) -> bool {
self.write_pos == self.file().content.len()
}
... | file | identifier_name |
builtin.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... |
fn bytes_written(&mut self, bytes: usize) {
self.write_pos += bytes;
}
}
| {
&self.file().content[self.write_pos..]
} | identifier_body |
play_game.rs | use ai2048_lib::game_logic::Grid;
use ai2048_lib::searcher::{self, SearchResult};
use criterion::Criterion;
use criterion::{criterion_group, criterion_main};
use lazy_static::lazy_static;
const MIN_PROBABILITY: f32 = 0.0001; |
fn calc_move(start: Grid) -> SearchResult {
searcher::search(start, MIN_PROBABILITY)
}
lazy_static! {
static ref GRID_DEFAULT: Grid = Grid::default().add_random_tile();
static ref GRID_DEPTH_8: Grid = {
let grid = Grid::from_human([
[8, 2, 4, 2],
[32, 32, 4, 2],
... | random_line_split | |
play_game.rs | use ai2048_lib::game_logic::Grid;
use ai2048_lib::searcher::{self, SearchResult};
use criterion::Criterion;
use criterion::{criterion_group, criterion_main};
use lazy_static::lazy_static;
const MIN_PROBABILITY: f32 = 0.0001;
fn calc_move(start: Grid) -> SearchResult {
searcher::search(start, MIN_PROBABILITY)
}
l... | (c: &mut Criterion) {
c.bench_function("depth 8 move", move |b| b.iter(|| calc_move(*GRID_DEPTH_8)));
}
criterion_group! {
name = large_sample;
config = Criterion::default().sample_size(10);
targets = single_moves
}
criterion_main!(large_sample);
| single_moves | identifier_name |
play_game.rs | use ai2048_lib::game_logic::Grid;
use ai2048_lib::searcher::{self, SearchResult};
use criterion::Criterion;
use criterion::{criterion_group, criterion_main};
use lazy_static::lazy_static;
const MIN_PROBABILITY: f32 = 0.0001;
fn calc_move(start: Grid) -> SearchResult |
lazy_static! {
static ref GRID_DEFAULT: Grid = Grid::default().add_random_tile();
static ref GRID_DEPTH_8: Grid = {
let grid = Grid::from_human([
[8, 2, 4, 2],
[32, 32, 4, 2],
[512, 128, 64, 2],
[1024, 256, 16, 0],
])
.expect("couldn't par... | {
searcher::search(start, MIN_PROBABILITY)
} | identifier_body |
vector.rs | /// A trait for describing vector operations used by vectorized searchers.
///
/// The trait is highly constrained to low level vector operations needed. In
/// general, it was invented mostly to be generic over x86's __m128i and
/// __m256i types. It's likely that once std::simd becomes a thing, we can
/// migrate to ... |
#[inline(always)]
unsafe fn load_unaligned(data: *const u8) -> __m128i {
_mm_loadu_si128(data as *const __m128i)
}
#[inline(always)]
unsafe fn movemask(self) -> u32 {
_mm_movemask_epi8(self) as u32
}
#[inline(always)]
unsafe fn ... | {
_mm_set1_epi8(byte as i8)
} | identifier_body |
vector.rs | /// A trait for describing vector operations used by vectorized searchers.
///
/// The trait is highly constrained to low level vector operations needed. In
/// general, it was invented mostly to be generic over x86's __m128i and
/// __m256i types. It's likely that once std::simd becomes a thing, we can
/// migrate to ... | #[inline(always)]
unsafe fn and(self, vector2: Self) -> __m256i {
_mm256_and_si256(self, vector2)
}
}
} | random_line_split | |
vector.rs | /// A trait for describing vector operations used by vectorized searchers.
///
/// The trait is highly constrained to low level vector operations needed. In
/// general, it was invented mostly to be generic over x86's __m128i and
/// __m256i types. It's likely that once std::simd becomes a thing, we can
/// migrate to ... | (self, vector2: Self) -> __m128i {
_mm_and_si128(self, vector2)
}
}
}
#[cfg(all(feature = "std", target_arch = "x86_64"))]
mod x86avx {
use super::Vector;
use core::arch::x86_64::*;
impl Vector for __m256i {
#[inline(always)]
unsafe fn splat(byte: u8) -> __m256i {
... | and | identifier_name |
out_parameters.rs | use crate::{
analysis::{
self, conversion_type::ConversionType, function_parameters::CParameter,
functions::is_carray_with_direct_elements, imports::Imports, return_value,
rust_type::RustType,
},
config::{self, parameter_matchable::ParameterMatchable},
env::Env,
library::{
... | .find(|c_par| c_par.name == lib_par.name)
{
out.lib_par.typ = c_par.typ;
out.lib_par.nullable = c_par.nullable;
}
info.params.push(out);
} else {
unsupported_outs = true;
}
}
if info.params.is_empty(... | random_line_split | |
out_parameters.rs | use crate::{
analysis::{
self, conversion_type::ConversionType, function_parameters::CParameter,
functions::is_carray_with_direct_elements, imports::Imports, return_value,
rust_type::RustType,
},
config::{self, parameter_matchable::ParameterMatchable},
env::Env,
library::{
... | (
env: &Env,
ret: &return_value::Info,
func_name: &str,
configured_functions: &[&config::functions::Function],
) -> bool {
let typ = ret
.parameter
.as_ref()
.map(|par| par.lib_par.typ)
.unwrap_or_default();
use_function_return_for_result(env, typ, func_name, configur... | use_return_value_for_result | identifier_name |
connection.rs | // Distributed under the OSI-approved BSD 3-Clause License.
// See accompanying LICENSE file for details.
use crates::dbus_bytestream::connection;
use error::*;
use message::{Message, MessageType};
use value::{BasicValue, Value};
bitflags! {
/// Flags for use when requesting a name on the bus from the bus.
p... | }
} else {
bail!(ErrorKind::InvalidReply("ReleaseName: no response".to_string()));
}
}
/// Requests the server to route messages to this connection.
///
/// By default, the server will not deliver any messages to this connection. In order to
/// receive messa... | random_line_split | |
connection.rs | // Distributed under the OSI-approved BSD 3-Clause License.
// See accompanying LICENSE file for details.
use crates::dbus_bytestream::connection;
use error::*;
use message::{Message, MessageType};
use value::{BasicValue, Value};
bitflags! {
/// Flags for use when requesting a name on the bus from the bus.
p... | () -> Result<Self> {
Ok(Connection {
conn: connection::Connection::connect_system()?,
})
}
/// Request a name on the bus.
///
/// By default, the name to address this connection directly is assigned by the daemon managing
/// the bus, but a name for the application may b... | system_new | identifier_name |
connection.rs | // Distributed under the OSI-approved BSD 3-Clause License.
// See accompanying LICENSE file for details.
use crates::dbus_bytestream::connection;
use error::*;
use message::{Message, MessageType};
use value::{BasicValue, Value};
bitflags! {
/// Flags for use when requesting a name on the bus from the bus.
p... |
} else {
bail!(ErrorKind::InvalidReply("RequestName: no response".to_string()));
}
}
/// Release a name on the bus.
pub fn release_name(&self, name: &str) -> Result<ReleaseNameReply> {
// TODO: Use an actual struct with an API for this.
let msg = Message::new_me... | {
bail!(ErrorKind::InvalidReply("RequestName: invalid response".to_string()));
} | conditional_block |
part2.rs | // adventofcode - day 16
// part 2
use std::io::prelude::*;
use std::fs::File;
use std::str::FromStr;
struct Aunt {
id: i32,
children: i32,
cats: i32,
samoyeds: i32,
pomeranians: i32,
akitas: i32,
vizslas: i32,
goldfish: i32,
trees: i32,
cars: i32,
perfumes: i32,
}
impl Au... | () -> String {
let mut file = match File::open("../../inputs/16.txt") {
Ok(f) => f,
Err(e) => panic!("file error: {}", e),
};
let mut data = String::new();
match file.read_to_string(&mut data){
Ok(_) => {},
Err(e) => panic!("file error: {}", e),
};
data
}
| import_data | identifier_name |
part2.rs | // adventofcode - day 16
// part 2
use std::io::prelude::*;
use std::fs::File;
use std::str::FromStr;
struct Aunt {
id: i32,
children: i32,
cats: i32,
samoyeds: i32,
pomeranians: i32,
akitas: i32,
vizslas: i32,
goldfish: i32,
trees: i32,
cars: i32,
perfumes: i32,
}
impl Au... | };
let mut linecount = 1i32;
for mut line in data.lines(){
let aunt = parse_line(&mut line, linecount);
if aunt.matches(&giver) {
aunts.push( aunt );
}
linecount += 1;
}
let matches = aunts.len();
for aunt in aunts {
aunt.print();
}
... | {
println!("Advent of Code - day 16 | part 2");
// import data
let data = import_data();
let mut aunts = Vec::new();
let giver = Aunt{
id: 0,
children: 3,
cats: 7,
samoyeds: 2,
pomeranians: 3,
akitas: 0,
vizslas: 0,
goldfish: 5,
... | identifier_body |
part2.rs | // adventofcode - day 16
// part 2
use std::io::prelude::*;
use std::fs::File;
use std::str::FromStr;
struct Aunt {
id: i32,
children: i32,
cats: i32,
samoyeds: i32,
pomeranians: i32,
akitas: i32,
vizslas: i32,
goldfish: i32,
trees: i32,
cars: i32,
perfumes: i32,
}
impl Au... |
false
}
fn print(&self) {
print!("Sue {}: ", self.id);
print!("{} children, ", self.children);
print!("{} cats, ", self.cats);
print!("{} samoyeds, ", self.samoyeds);
print!("{} pomeranians, ", self.pomeranians);
print!("{} akitas, ", self.akitas);
... | {
return true;
} | conditional_block |
part2.rs | // adventofcode - day 16
// part 2
use std::io::prelude::*;
use std::fs::File;
use std::str::FromStr;
struct Aunt {
id: i32,
children: i32,
cats: i32,
samoyeds: i32,
pomeranians: i32,
akitas: i32,
vizslas: i32,
goldfish: i32,
trees: i32,
cars: i32,
perfumes: i32,
}
impl Au... |
false
}
fn print(&self) {
print!("Sue {}: ", self.id);
print!("{} children, ", self.children);
print!("{} cats, ", self.cats);
print!("{} samoyeds, ", self.samoyeds);
print!("{} pomeranians, ", self.pomeranians);
print!("{} akitas, ", self.akitas);
... | && (self.perfumes == -1 || self.perfumes == other.perfumes) {
return true;
} | random_line_split |
mod.rs | 6_addr,
sockaddr,
sockaddr_in,
sockaddr_in6,
sockaddr_un,
sa_family_t,
};
pub use self::multicast::{
ip_mreq,
ipv6_mreq,
};
pub use self::consts::*;
#[cfg(any(not(target_os = "linux"), not(target_arch = "x86")))]
pub use libc::sockaddr_storage;
// Working around rust-lang/rust#23425
#[cfg... | type Val;
#[doc(hidden)]
fn get(&self, fd: RawFd) -> Result<Self::Val>;
}
/// Represents a socket option that can be accessed or set. Used as an argument
/// to `setsockopt`
pub trait SetSockOpt : Copy {
type Val;
#[doc(hidden)]
fn set(&self, fd: RawFd, val: &Self::Val) -> Result<()>;
}
/// ... | pub trait GetSockOpt : Copy { | random_line_split |
mod.rs | addr,
sockaddr,
sockaddr_in,
sockaddr_in6,
sockaddr_un,
sa_family_t,
};
pub use self::multicast::{
ip_mreq,
ipv6_mreq,
};
pub use self::consts::*;
#[cfg(any(not(target_os = "linux"), not(target_arch = "x86")))]
pub use libc::sockaddr_storage;
// Working around rust-lang/rust#23425
#[cfg(a... | (fd: RawFd, addr: &SockAddr) -> Result<()> {
let res = unsafe {
let (ptr, len) = addr.as_ffi_pair();
ffi::bind(fd, ptr, len)
};
from_ffi(res)
}
/// Accept a connection on a socket
///
/// [Further reading](http://man7.org/linux/man-pages/man2/accept.2.html)
pub fn accept(sockfd: RawFd) -> ... | bind | identifier_name |
mod.rs | addr,
sockaddr,
sockaddr_in,
sockaddr_in6,
sockaddr_un,
sa_family_t,
};
pub use self::multicast::{
ip_mreq,
ipv6_mreq,
};
pub use self::consts::*;
#[cfg(any(not(target_os = "linux"), not(target_arch = "x86")))]
pub use libc::sockaddr_storage;
// Working around rust-lang/rust#23425
#[cfg(a... |
/// Get the current address to which the socket `fd` is bound.
///
/// [Further reading](http://man7.org/linux/man-pages/man2/getsockname.2.html)
pub fn getsockname(fd: RawFd) -> Result<SockAddr> {
unsafe {
let addr: sockaddr_storage = mem::uninitialized();
let mut len = mem::size_of::<sockaddr_st... | {
unsafe {
let addr: sockaddr_storage = mem::uninitialized();
let mut len = mem::size_of::<sockaddr_storage>() as socklen_t;
let ret = ffi::getpeername(fd, mem::transmute(&addr), &mut len);
if ret < 0 {
return Err(Error::last());
}
sockaddr_storage_to_a... | identifier_body |
mod.rs | addr,
sockaddr,
sockaddr_in,
sockaddr_in6,
sockaddr_un,
sa_family_t,
};
pub use self::multicast::{
ip_mreq,
ipv6_mreq,
};
pub use self::consts::*;
#[cfg(any(not(target_os = "linux"), not(target_arch = "x86")))]
pub use libc::sockaddr_storage;
// Working around rust-lang/rust#23425
#[cfg(a... |
}
/// Create an endpoint for communication
///
/// [Further reading](http://man7.org/linux/man-pages/man2/socket.2.html)
pub fn socket(domain: AddressFamily, ty: SockType, flags: SockFlag, protocol: c_int) -> Result<RawFd> {
let mut ty = ty as c_int;
let feat_atomic = features::socket_atomic_cloexec();
... | {
Ok(unsafe { RecvMsg {
bytes: ret as usize,
cmsg_buffer: slice::from_raw_parts(mhdr.msg_control as *const u8,
mhdr.msg_controllen as usize),
address: sockaddr_storage_to_addr(&address,
... | conditional_block |
pat_util.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 ... | (dm: &resolve::DefMap, pat: &Pat) -> bool {
match pat.node {
PatIdent(..) => {
!pat_is_variant_or_struct(dm, pat) &&
!pat_is_const(dm, pat)
}
_ => false
}
}
pub fn pat_is_binding_or_wild(dm: &resolve::DefMap, pat: &Pat) -> bool {
match pat.node {
PatIde... | pat_is_binding | identifier_name |
pat_util.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 ... | }
}
_ => false
}
}
pub fn pat_is_const(dm: &resolve::DefMap, pat: &Pat) -> bool {
match pat.node {
PatIdent(_, _, None) | PatEnum(..) => {
match dm.borrow().find(&pat.id) {
Some(&DefStatic(_, false)) => true,
_ => false
... | PatEnum(_, _) | PatIdent(_, _, None) | PatStruct(..) => {
match dm.borrow().find(&pat.id) {
Some(&DefVariant(..)) | Some(&DefStruct(..)) => true,
_ => false | random_line_split |
pat_util.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 wild() -> Gc<Pat> {
box (GC) Pat { id: 0, node: PatWild(PatWildSingle), span: DUMMY_SP }
}
pub fn raw_pat(p: Gc<Pat>) -> Gc<Pat> {
match p.node {
PatIdent(_, _, Some(s)) => { raw_pat(s) }
_ => { p }
}
}
pub fn def_to_path(tcx: &ty::ctxt, id: DefId) -> Path {
ty::with_path(tcx,... | {
match pat.node {
PatIdent(BindByValue(_), ref path1, None) => {
Some(&path1.node)
}
_ => {
None
}
}
} | identifier_body |
assert-eq-macro-success.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
assert_eq!(14i,14i);
assert_eq!("abc".to_string(),"abc".to_string());
assert_eq!(box Point{x:34},box Point{x:34});
assert_eq!(&Point{x:34},&Point{x:34});
assert_eq!(box(GC) Point{x:34},box(GC) Point{x:34});
}
| main | identifier_name |
assert-eq-macro-success.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert_eq!(&Point{x:34},&Point{x:34});
assert_eq!(box(GC) Point{x:34},box(GC) Point{x:34});
} |
pub fn main() {
assert_eq!(14i,14i);
assert_eq!("abc".to_string(),"abc".to_string());
assert_eq!(box Point{x:34},box Point{x:34}); | random_line_split |
bots.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... | <R>(
client: &R,
token: &str,
request: &InfoRequest<'_>,
) -> Result<InfoResponse, InfoError<R::Error>>
where
R: SlackWebRequestSender,
{
let params = vec![Some(("token", token)), request.bot.map(|bot| ("bot", bot))];
let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
let... | info | identifier_name |
bots.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... | {
let params = vec![Some(("token", token)), request.bot.map(|bot| ("bot", bot))];
let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
let url = crate::get_slack_url_for_method("bots.info");
client
.send(&url, ¶ms[..])
.map_err(InfoError::Client)
.and_then(|... | identifier_body | |
bots.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... |
pub use crate::mod_types::bots_types::*;
use crate::sync::requests::SlackWebRequestSender;
/// Gets information about a bot user.
///
/// Wraps https://api.slack.com/methods/bots.info
pub fn info<R>(
client: &R,
token: &str,
request: &InfoRequest<'_>,
) -> Result<InfoResponse, InfoError<R::Error>>
where
... | random_line_split | |
builtin-superkinds-capabilities.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T: Foo +'static>(val: T, chan: Sender<T>) {
chan.send(val).unwrap();
}
pub fn main() {
let (tx, rx): (Sender<isize>, Receiver<isize>) = channel();
foo(31337, tx);
assert_eq!(rx.recv().unwrap(), 31337);
}
| foo | identifier_name |
builtin-superkinds-capabilities.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let (tx, rx): (Sender<isize>, Receiver<isize>) = channel();
foo(31337, tx);
assert_eq!(rx.recv().unwrap(), 31337);
} | identifier_body | |
builtin-superkinds-capabilities.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
let (tx, rx): (Sender<isize>, Receiver<isize>) = channel();
foo(31337, tx);
assert_eq!(rx.recv().unwrap(), 31337);
} | impl <T: Send> Foo for T { }
fn foo<T: Foo + 'static>(val: T, chan: Sender<T>) {
chan.send(val).unwrap();
} | random_line_split |
collinear.rs | // http://coursera.cs.princeton.edu/algs4/assignments/collinear.html
extern crate algs4;
use std::io::prelude::*;
use std::io;
use std::fmt;
use std::cmp::Ordering;
use algs4::sorting::quick_sort;
use algs4::sorting::comparator::Comparator;
use algs4::sorting::comparator::insertion_sort;
#[derive(Copy, Clone)]
pub s... | (&self, other: &Point) -> bool {
self.x == other.x && self.y == other.y
}
}
// is this point lexicographically smaller than that point?
impl PartialOrd<Point> for Point {
fn partial_cmp(&self, other: &Point) -> Option<Ordering> {
if self.y < other.y || (self.y == other.y && self.x < other.x) {... | eq | identifier_name |
collinear.rs | // http://coursera.cs.princeton.edu/algs4/assignments/collinear.html
extern crate algs4;
use std::io::prelude::*;
use std::io;
use std::fmt;
use std::cmp::Ordering;
use algs4::sorting::quick_sort;
use algs4::sorting::comparator::Comparator;
use algs4::sorting::comparator::insertion_sort;
#[derive(Copy, Clone)]
pub s... |
fn main() {
let mut lines = io::BufReader::new(io::stdin()).lines();
let n = lines.next().unwrap().unwrap().parse().unwrap();
let mut points: Vec<Point> = Vec::new();
for _ in 0.. n {
let segs: Vec<i32> = lines.next().unwrap().unwrap().split(' ').
filter(|s|!s.is_empty()).map(|n| n... | random_line_split | |
collinear.rs | // http://coursera.cs.princeton.edu/algs4/assignments/collinear.html
extern crate algs4;
use std::io::prelude::*;
use std::io;
use std::fmt;
use std::cmp::Ordering;
use algs4::sorting::quick_sort;
use algs4::sorting::comparator::Comparator;
use algs4::sorting::comparator::insertion_sort;
#[derive(Copy, Clone)]
pub s... |
for s in points.iter() {
if s == p || s == q || s == r { break }
let slope = p.slope_to(q);
if slope == p.slope_to(r) && slope == p.slope_to(s) {
println!("{} -> {} -> {} -> {}", p, q, r, s);
}
... | { break } | conditional_block |
block_metadata_config_tests.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
config::{
block_metadata::{build_block_metadata, is_new_block, Entry},
global::Config as GlobalConfig,
},
errors::*,
tests::{
global_config_tests::parse_and_build_config as parse_and_... |
fn parse_and_build_config(global_config: &GlobalConfig, s: &str) -> Result<BlockMetadata> {
build_block_metadata(&global_config, &parse_each_line_as::<Entry>(s)?)
}
#[rustfmt::skip]
#[test]
fn build_transaction_config_1() {
let global = parse_and_build_global_config(r"
//! account: alice
").unwra... | {
assert!(is_new_block("//! block-prologue"));
assert!(is_new_block("//!block-prologue "));
assert!(!is_new_block("//"));
assert!(!is_new_block("//! new block"));
assert!(!is_new_block("//! block"));
} | identifier_body |
block_metadata_config_tests.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
config::{
block_metadata::{build_block_metadata, is_new_block, Entry},
global::Config as GlobalConfig,
},
errors::*,
tests::{
global_config_tests::parse_and_build_config as parse_and_... | () {
assert!(is_new_block("//! block-prologue"));
assert!(is_new_block("//!block-prologue "));
assert!(!is_new_block("//"));
assert!(!is_new_block("//! new block"));
assert!(!is_new_block("//! block"));
}
fn parse_and_build_config(global_config: &GlobalConfig, s: &str) -> Result<BlockMetadata> {
... | parse_new_transaction | identifier_name |
block_metadata_config_tests.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
config::{
block_metadata::{build_block_metadata, is_new_block, Entry},
global::Config as GlobalConfig,
},
errors::*,
tests::{
global_config_tests::parse_and_build_config as parse_and_... |
for s in &[
"//!block-time:",
"//!block-time:abc",
"//!block-time: 123, 45",
] {
s.parse::<Entry>().unwrap_err();
}
}
#[test]
fn parse_new_transaction() {
assert!(is_new_block("//! block-prologue"));
assert!(is_new_block("//!block-prologue "));
assert!(!is_new_b... | } | random_line_split |
http-echo-server.rs | extern crate clap;
#[macro_use] extern crate log;
extern crate env_logger;
extern crate hyper;
extern crate simplesched;
use std::io;
use clap::{Arg, App};
use simplesched::Scheduler;
use simplesched::net::http::Server;
use hyper::{Get, Post};
use hyper::server::{Request, Response};
use hyper::uri::RequestUri::Abs... | *res.status_mut() = hyper::NotFound;
return;
}
},
_ => {
return;
}
};
let mut res = try_return!(res.start());
try_return!(io::copy(&mut req, &mut res));
}
fn main() {
env_logger::init().unwrap();
let matches = App::ne... | random_line_split | |
http-echo-server.rs | extern crate clap;
#[macro_use] extern crate log;
extern crate env_logger;
extern crate hyper;
extern crate simplesched;
use std::io;
use clap::{Arg, App};
use simplesched::Scheduler;
use simplesched::net::http::Server;
use hyper::{Get, Post};
use hyper::server::{Request, Response};
use hyper::uri::RequestUri::Abs... | }
| {
env_logger::init().unwrap();
let matches = App::new("http-echo")
.version(env!("CARGO_PKG_VERSION"))
.author("Y. T. Chung <zonyitoo@gmail.com>")
.arg(Arg::with_name("BIND").short("b").long("bind").takes_value(true).required(true)
.help("Listening on thi... | identifier_body |
http-echo-server.rs | extern crate clap;
#[macro_use] extern crate log;
extern crate env_logger;
extern crate hyper;
extern crate simplesched;
use std::io;
use clap::{Arg, App};
use simplesched::Scheduler;
use simplesched::net::http::Server;
use hyper::{Get, Post};
use hyper::server::{Request, Response};
use hyper::uri::RequestUri::Abs... | ,
(&Post, "/echo") => (), // fall through, fighting mutable borrows
_ => {
*res.status_mut() = hyper::NotFound;
return;
}
},
_ => {
return;
}
};
let mut res = try_return!(res.start());
try_return!(io::co... | {
try_return!(res.send(b"Try POST /echo"));
return;
} | conditional_block |
http-echo-server.rs | extern crate clap;
#[macro_use] extern crate log;
extern crate env_logger;
extern crate hyper;
extern crate simplesched;
use std::io;
use clap::{Arg, App};
use simplesched::Scheduler;
use simplesched::net::http::Server;
use hyper::{Get, Post};
use hyper::server::{Request, Response};
use hyper::uri::RequestUri::Abs... | () {
env_logger::init().unwrap();
let matches = App::new("http-echo")
.version(env!("CARGO_PKG_VERSION"))
.author("Y. T. Chung <zonyitoo@gmail.com>")
.arg(Arg::with_name("BIND").short("b").long("bind").takes_value(true).required(true)
.help("Listening on this... | main | identifier_name |
str.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 geometry::Au;
use cssparser::{self, RGBA, Color};
use libc::c_char;
use num_lib::ToPrimitive;
use std::ascii... | } | random_line_split | |
str.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 geometry::Au;
use cssparser::{self, RGBA, Color};
use libc::c_char;
use num_lib::ToPrimitive;
use std::ascii... | ub fn str_join<T: AsRef<str>>(strs: &[T], join: &str) -> String {
strs.iter().fold(String::new(), |mut acc, s| {
if!acc.is_empty() { acc.push_str(join); }
acc.push_str(s.as_ref());
acc
})
}
// Lifted from Rust's StrExt implementation, which is being removed.
pub fn slice_chars(s: &str, ... | from_utf8(CStr::from_ptr(s).to_bytes()).unwrap().to_owned()
}
p | identifier_body |
str.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 geometry::Au;
use cssparser::{self, RGBA, Color};
use libc::c_char;
use num_lib::ToPrimitive;
use std::ascii... | c: char) -> bool {
WHITESPACE.contains(&c)
}
/// A "space character" according to:
///
/// https://html.spec.whatwg.org/multipage/#space-character
pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[
'\u{0020}',
'\u{0009}',
'\u{000a}',
'\u{000c}',
'\u{000d}',
];
pub fn split_html_space_chars<'... | har_is_whitespace( | identifier_name |
str.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 geometry::Au;
use cssparser::{self, RGBA, Color};
use libc::c_char;
use num_lib::ToPrimitive;
use std::ascii... | let mut end_index = value.len();
let (mut found_full_stop, mut found_percent) = (false, false);
for (i, ch) in value.chars().enumerate() {
match ch {
'0'...'9' => continue,
'%' => {
found_percent = true;
end_index = i;
break
... | return LengthOrPercentageOrAuto::Auto
}
| conditional_block |
cmath.rs | // Copyright 2017 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 ... | (n: c_float) -> c_float {
f64::asin(n as f64) as c_float
}
#[inline]
pub unsafe fn atan2f(n: c_float, b: c_float) -> c_float {
f64::atan2(n as f64, b as f64) as c_float
}
#[inline]
pub unsafe fn atanf(n: c_float) -> c_float {
f64::atan(n as f64) as c_float
}
#[... | asinf | identifier_name |
cmath.rs | // Copyright 2017 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 coshf(n: c_float) -> c_float;
pub fn sinhf(n: c_float) -> c_float;
pub fn tanf(n: c_float) -> c_float;
pub fn tanhf(n: c_float) -> c_float;
}
}
// On MSVC these functions aren't defined, so we just define shims which promote
// everything fo f64, perform the calculation, and ... | pub fn asinf(n: c_float) -> c_float;
pub fn atan2f(a: c_float, b: c_float) -> c_float;
pub fn atanf(n: c_float) -> c_float; | random_line_split |
cmath.rs | // Copyright 2017 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 ... |
#[inline]
pub unsafe fn atan2f(n: c_float, b: c_float) -> c_float {
f64::atan2(n as f64, b as f64) as c_float
}
#[inline]
pub unsafe fn atanf(n: c_float) -> c_float {
f64::atan(n as f64) as c_float
}
#[inline]
pub unsafe fn coshf(n: c_float) -> c_float {
f64::... | {
f64::asin(n as f64) as c_float
} | identifier_body |
main.rs | use self::binary::{builtins, InteractiveShell};
use atty::Stream;
use ion_shell::{BackgroundEvent, BuiltinMap, IonError, PipelineError, Shell, Value};
use liner::KeyBindings;
use nix::{
sys::signal::{self, SaFlags, SigAction, SigHandler, SigSet, Signal},
unistd,
};
use std::{
fs,
io::{stdin, BufReader},... | () -> String { include!(concat!(env!("OUT_DIR"), "/version_string")).to_string() }
fn parse_args() -> Result<CommandLineArgs, ParsingError> {
let mut arg_twice_set = false;
let mut invalid_keybinding = false;
let mut args = env::args().skip(1);
let mut version = false;
let mut help = false;
let... | version | identifier_name |
main.rs | use self::binary::{builtins, InteractiveShell};
use atty::Stream;
use ion_shell::{BackgroundEvent, BuiltinMap, IonError, PipelineError, Shell, Value};
use liner::KeyBindings;
use nix::{
sys::signal::{self, SaFlags, SigAction, SigHandler, SigSet, Signal},
unistd,
};
use std::{
fs,
io::{stdin, BufReader},... | return;
}
if command_line_args.command.is_some() &&!command_line_args.args.is_empty() {
eprintln!("either execute command or file(s)");
process::exit(1);
}
let mut builtins = BuiltinMap::default();
builtins
.with_unsafe()
.add("debug", &builtins::builtin_debug,... | {
let parsedargs = parse_args();
let command_line_args = match parsedargs {
Ok(parsedargs) => parsedargs,
Err(ParsingError::ArgTwiceSet) => {
eprintln!("flag or option set twice, see --help");
process::exit(1);
}
Err(ParsingError::InvalidKeybinding) => {
... | identifier_body |
main.rs | use self::binary::{builtins, InteractiveShell};
use atty::Stream;
use ion_shell::{BackgroundEvent, BuiltinMap, IonError, PipelineError, Shell, Value};
use liner::KeyBindings;
use nix::{
sys::signal::{self, SaFlags, SigAction, SigHandler, SigSet, Signal},
unistd,
};
use std::{
fs,
io::{stdin, BufReader},... | }
"-f" | "--fake-interactive" => {
if fake_interactive {
arg_twice_set = true;
}
fake_interactive = true;
}
"-i" | "--interactive" => {
if interactive {
arg_twice_set =... | no_execute = true; | random_line_split |
main.rs | use self::binary::{builtins, InteractiveShell};
use atty::Stream;
use ion_shell::{BackgroundEvent, BuiltinMap, IonError, PipelineError, Shell, Value};
use liner::KeyBindings;
use nix::{
sys::signal::{self, SaFlags, SigAction, SigHandler, SigSet, Signal},
unistd,
};
use std::{
fs,
io::{stdin, BufReader},... | else {
shell.execute_command(BufReader::new(stdin()))
}
.and_then(|_| shell.wait_for_background().map_err(Into::into));
if let Err(IonError::PipelineExecutionError(PipelineError::Interrupted(_, signal))) = err {
// When the job was aborted because of an interrupt signal, abort with this same... | {
let mut reader = BufReader::new(stdin());
loop {
if let Err(err) = shell.execute_command(&mut reader) {
eprintln!("ion: {}", err);
}
}
} | conditional_block |
constants.rs | pub const GET_TXN: &str = "3";
pub const ATTRIB: &str = "100";
pub const SCHEMA: &str = "101";
pub const CRED_DEF: &str = "102";
pub const GET_ATTR: &str = "104";
pub const GET_NYM: &str = "105";
pub const GET_SCHEMA: &str = "107";
pub const GET_CRED_DEF: &str = "108";
pub const POOL_UPGRADE: &str = "109";
pub const PO... | pub const NODE: &str = "0";
pub const NYM: &str = "1"; | random_line_split | |
constants.rs | pub const NODE: &str = "0";
pub const NYM: &str = "1";
pub const GET_TXN: &str = "3";
pub const ATTRIB: &str = "100";
pub const SCHEMA: &str = "101";
pub const CRED_DEF: &str = "102";
pub const GET_ATTR: &str = "104";
pub const GET_NYM: &str = "105";
pub const GET_SCHEMA: &str = "107";
pub const GET_CRED_DEF: &str = "1... | "REVOC_REG_ENTRY" => Some(REVOC_REG_ENTRY),
"GET_REVOC_REG_DEF" => Some(GET_REVOC_REG_DEF),
"GET_REVOC_REG" => Some(GET_REVOC_REG),
"GET_REVOC_REG_DELTA" => Some(GET_REVOC_REG_DELTA),
"GET_VALIDATOR_INFO" => Some(GET_VALIDATOR_INFO),
"AUTH_RULE" => Some(AUTH_RULE),
... | {
if REQUESTS.contains(&txn) {
return Some(txn)
}
match txn {
"NODE" => Some(NODE),
"NYM" => Some(NYM),
"GET_TXN" => Some(GET_TXN),
"ATTRIB" => Some(ATTRIB),
"SCHEMA" => Some(SCHEMA),
"CRED_DEF" | "CLAIM_DEF" => Some(CRED_DEF),
"GET_ATTR" => S... | identifier_body |
constants.rs | pub const NODE: &str = "0";
pub const NYM: &str = "1";
pub const GET_TXN: &str = "3";
pub const ATTRIB: &str = "100";
pub const SCHEMA: &str = "101";
pub const CRED_DEF: &str = "102";
pub const GET_ATTR: &str = "104";
pub const GET_NYM: &str = "105";
pub const GET_SCHEMA: &str = "107";
pub const GET_CRED_DEF: &str = "1... | (txn: &str) -> Option<&str> {
if REQUESTS.contains(&txn) {
return Some(txn)
}
match txn {
"NODE" => Some(NODE),
"NYM" => Some(NYM),
"GET_TXN" => Some(GET_TXN),
"ATTRIB" => Some(ATTRIB),
"SCHEMA" => Some(SCHEMA),
"CRED_DEF" | "CLAIM_DEF" => Some(CRED_D... | txn_name_to_code | identifier_name |
lib.rs | //! An wrapper for the RealSense library.
//!
//! # Example
//!
//! ```no_run
//! extern crate realsense; | //!
//! fn main() {
//! let context = rs::Context::new().unwrap();
//! let device = context.get_device(0).unwrap();
//! let property = {
//! rs::Properties {
//! format: rs::Format::Z16,
//! ..Default::default()
//! }
//! };
//! device.enable_stream(rs::Stream:... | //! use realsense as rs; | random_line_split |
ivec-tag.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 (tx, rx) = channel::<Vec<u8>>();
let _prod = task::spawn(proc() {
producer(&tx)
});
let _data: Vec<u8> = rx.recv();
} | identifier_body | |
ivec-tag.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 ... | tx.send(
vec!(1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8, 10u8, 11u8, 12u8,
13u8));
}
pub fn main() {
let (tx, rx) = channel::<Vec<u8>>();
let _prod = task::spawn(proc() {
producer(&tx)
});
let _data: Vec<u8> = rx.recv();
} | // except according to those terms.
use std::task;
fn producer(tx: &Sender<Vec<u8>>) { | random_line_split |
ivec-tag.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 ... | (tx: &Sender<Vec<u8>>) {
tx.send(
vec!(1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8, 10u8, 11u8, 12u8,
13u8));
}
pub fn main() {
let (tx, rx) = channel::<Vec<u8>>();
let _prod = task::spawn(proc() {
producer(&tx)
});
let _data: Vec<u8> = rx.recv();
}
| producer | identifier_name |
control.rs | use cgmath;
use claymore_scene::Transform;
pub type MousePos = (i32, i32);
pub struct Control {
rotate_speed: f32,
move_speed: f32,
zoom_speed: f32,
rotate_base: Option<(MousePos, Transform<f32>)>,
move_base: Option<(MousePos, cgmath::Vector3<f32>)>,
last_pos: MousePos,
space: Transform<f... | match self.move_base {
Some((base_pos, ref base_disp)) => {
use cgmath::{Vector, Rotation};
let local_vector = cgmath::vec3(
-(coords.0 - base_pos.0) as f32,
(coords.1 - base_pos.1) as f32,
0.0).mul_s(self.m... | {
self.last_pos = coords;
match self.rotate_base {
Some((ref base_pos, ref base_transform)) => {
use cgmath::Transform;
// p' = Mp * Tc^ * (Tr * Rz * Tr^) * p
// Tx = (Tr * Rz^ * Tr^) * Tc
let path = (coords.0 - base_pos.0) as f... | identifier_body |
control.rs | use cgmath;
use claymore_scene::Transform;
pub type MousePos = (i32, i32);
pub struct Control {
rotate_speed: f32,
move_speed: f32,
zoom_speed: f32,
rotate_base: Option<(MousePos, Transform<f32>)>,
move_base: Option<(MousePos, cgmath::Vector3<f32>)>,
last_pos: MousePos,
space: Transform<f... | }
}
pub fn rot_capture(&mut self, transform: &Transform<f32>) {
self.rotate_base = Some((self.last_pos, transform.clone()));
}
pub fn rot_release(&mut self) {
self.rotate_base = None;
}
pub fn move_capture(&mut self, transform: &Transform<f32>) {
self.move_base... | random_line_split | |
control.rs | use cgmath;
use claymore_scene::Transform;
pub type MousePos = (i32, i32);
pub struct Control {
rotate_speed: f32,
move_speed: f32,
zoom_speed: f32,
rotate_base: Option<(MousePos, Transform<f32>)>,
move_base: Option<(MousePos, cgmath::Vector3<f32>)>,
last_pos: MousePos,
space: Transform<f... | (rot_speed: f32, move_speed: f32, zoom_speed: f32,
space: Transform<f32>) -> Control {
Control {
rotate_speed: rot_speed,
move_speed: move_speed,
zoom_speed: zoom_speed,
rotate_base: None,
move_base: None,
last_pos: (0, 0),
... | new | identifier_name |
mod.rs | // This file is part of rgtk.
//
// rgtk 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 Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | {
Readable,
Writable,
ReadWrite,
Construct,
ConstructOnly,
LaxValidation,
StaticName,
Private,
StaticNick,
StaticBlurb,
Deprecated
}
pub struct ParamSpec {
g_type_instance: TypeInstance,
name: *mut c_char,
flags: ParamFlags,
value_type: GType,
owner_type:... | ParamFlags | identifier_name |
mod.rs | // This file is part of rgtk.
//
// rgtk 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 Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/li... | random_line_split | |
ac.rs | //! Actor-critic algorithms.
use crate::{
domains::Transition,
fa::StateActionUpdate,
policies::Policy,
Function,
Handler,
};
pub trait Critic<'t, S: 't, A: 't> {
fn target(&self, t: &'t Transition<S, A>) -> f64;
}
impl<'t, F, S: 't, A: 't> Critic<'t, S, A> for F
where F: Fn(&'t Transition<S, ... |
}
impl<'m, S, C, P> Handler<&'m Transition<S, P::Action>> for ActorCritic<C, P>
where
C: Critic<'m, S, P::Action>,
P: Policy<&'m S> + Handler<StateActionUpdate<&'m S, &'m <P as Policy<&'m S>>::Action, f64>>,
{
type Response = P::Response;
type Error = P::Error;
fn handle(&mut self, t: &'m Transit... | {
ActorCritic {
critic: TDCritic {
gamma,
v_func,
},
policy,
alpha,
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.