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 |
|---|---|---|---|---|
insertion.rs | // Copyright 2020 Johannes Köster.
// Licensed under the GNU GPLv3 license (https://opensource.org/licenses/GPL-3.0)
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::RefCell;
use std::cmp;
use std::rc::Rc;
use std::sync::Arc;
use anyhow::Result;
use bio::stat... |
/// Calculate probability for alt and reference allele.
fn allele_support(
&self,
evidence: &Self::Evidence,
_alignment_properties: &AlignmentProperties,
) -> Result<Option<AlleleSupport>> {
match evidence {
PairedEndEvidence::SingleEnd(record) => Ok(Some(
... |
&self.locus
}
| identifier_body |
insertion.rs | // Copyright 2020 Johannes Köster.
// Licensed under the GNU GPLv3 license (https://opensource.org/licenses/GPL-3.0)
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::RefCell;
use std::cmp;
use std::rc::Rc;
use std::sync::Arc;
use anyhow::Result;
use bio::stat... |
&self,
evidence: &Self::Evidence,
_alignment_properties: &AlignmentProperties,
) -> Result<Option<AlleleSupport>> {
match evidence {
PairedEndEvidence::SingleEnd(record) => Ok(Some(
self.realigner
.borrow_mut()
.allel... | llele_support( | identifier_name |
cargo_run.rs | use std::path::Path;
use ops::{self, CompileFilter};
use util::{self, CargoResult, process, ProcessError};
use core::Package;
pub fn run(manifest_path: &Path,
options: &ops::CompileOptions,
args: &[String]) -> CargoResult<Option<ProcessError>> | if bins.next().is_some() {
match options.filter {
CompileFilter::Everything => {
bail!("`cargo run` requires that a project only have one \
executable; use the `--bin` option to specify which one \
to run")
}
C... | {
let config = options.config;
let root = try!(Package::for_path(manifest_path, config));
let mut bins = root.manifest().targets().iter().filter(|a| {
!a.is_lib() && !a.is_custom_build() && match options.filter {
CompileFilter::Everything => a.is_bin(),
CompileFilter::Only {... | identifier_body |
cargo_run.rs | use std::path::Path;
use ops::{self, CompileFilter};
use util::{self, CargoResult, process, ProcessError};
use core::Package;
pub fn run(manifest_path: &Path,
options: &ops::CompileOptions,
args: &[String]) -> CargoResult<Option<ProcessError>> {
let config = options.config;
let root = tr... | if bins.next().is_some() {
match options.filter {
CompileFilter::Everything => {
bail!("`cargo run` requires that a project only have one \
executable; use the `--bin` option to specify which one \
to run")
}
C... | }
}
} | random_line_split |
cargo_run.rs | use std::path::Path;
use ops::{self, CompileFilter};
use util::{self, CargoResult, process, ProcessError};
use core::Package;
pub fn | (manifest_path: &Path,
options: &ops::CompileOptions,
args: &[String]) -> CargoResult<Option<ProcessError>> {
let config = options.config;
let root = try!(Package::for_path(manifest_path, config));
let mut bins = root.manifest().targets().iter().filter(|a| {
!a.is_lib() &&!a.is... | run | identifier_name |
box.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/. */
//! Generic types for box properties.
use values::animated::ToAnimatedZero;
/// A generic value for the `vertica... | }
}
impl<L> ToAnimatedZero for VerticalAlign<L> {
fn to_animated_zero(&self) -> Result<Self, ()> {
Err(())
}
}
/// https://drafts.csswg.org/css-animations/#animation-iteration-count
#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum AnimationIterationCount<Number> {
... | VerticalAlign::Baseline | random_line_split |
box.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/. */
//! Generic types for box properties.
use values::animated::ToAnimatedZero;
/// A generic value for the `vertica... | <NonNegativeLength> {
/// A non-negative length.
Length(NonNegativeLength),
/// The keyword `none`.
None,
}
impl<L> Perspective<L> {
/// Returns `none`.
#[inline]
pub fn none() -> Self {
Perspective::None
}
}
| Perspective | identifier_name |
jit.rs | #![feature(asm)]
use std::io::{prelude::*};
use std::env;
use std::fs::File;
use std::convert::TryInto;
use brainfuck as bf;
extern crate assembler;
use ::assembler::{
ExecutableAnonymousMemoryMap,
InstructionStream,
InstructionStreamHints
};
fn compile(expressions: &Vec<bf::Expression>, stream: &mut I... | // 46: 0f 05 syscall
bf::Expression::OutputValue => {
stream.emit_bytes(b"\x48\xc7\xc0");
stream.emit_double_word(0x02000004);
stream.emit_bytes(b"\x48\xc7\xc7\x01\x00\x00\x00");
stream.emit_bytes(b"\x... | // 0000000000000031 write:
// 31: 48 c7 c0 04 00 00 02 movq $33554436, %rax
// 38: 48 c7 c7 01 00 00 00 movq $1, %rdi
// 3f: 48 c7 c2 01 00 00 00 movq $1, %rdx | random_line_split |
jit.rs | #![feature(asm)]
use std::io::{prelude::*};
use std::env;
use std::fs::File;
use std::convert::TryInto;
use brainfuck as bf;
extern crate assembler;
use ::assembler::{
ExecutableAnonymousMemoryMap,
InstructionStream,
InstructionStreamHints
};
fn compile(expressions: &Vec<bf::Expression>, stream: &mut I... | () {
let args: Vec<String> = env::args().collect();
let filename = match args.get(1) {
Some(s) => s,
None => panic!("missing filename")
};
let mut contents = String::new();
let mut file = File::open(filename).expect("Error opening file");
file.read_to_string(&mut contents).exp... | main | identifier_name |
jit.rs | #![feature(asm)]
use std::io::{prelude::*};
use std::env;
use std::fs::File;
use std::convert::TryInto;
use brainfuck as bf;
extern crate assembler;
use ::assembler::{
ExecutableAnonymousMemoryMap,
InstructionStream,
InstructionStreamHints
};
fn compile(expressions: &Vec<bf::Expression>, stream: &mut I... | {
let args: Vec<String> = env::args().collect();
let filename = match args.get(1) {
Some(s) => s,
None => panic!("missing filename")
};
let mut contents = String::new();
let mut file = File::open(filename).expect("Error opening file");
file.read_to_string(&mut contents).expect... | identifier_body | |
selectors.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 cssparser::Parser;
use selectors::parser::{Selector, ParserContext, parse_selector_list};
use style::selector_... | } | random_line_split | |
selectors.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 cssparser::Parser;
use selectors::parser::{Selector, ParserContext, parse_selector_list};
use style::selector_... |
#[test]
fn test_selectors() {
assert_roundtrip!(parse, "div");
assert_roundtrip!(parse, "svg|circle");
assert_roundtrip!(parse, "p:before", "p::before");
assert_roundtrip!(parse, "[border = \"0\"]:-servo-nonzero-border ~ ::-servo-details-summary");
}
| {
let mut context = ParserContext::new();
context.in_user_agent_stylesheet = true;
context.namespace_prefixes.insert("svg".into(), ns!(svg));
parse_selector_list(&context, input).map(|mut vec| vec.pop().unwrap())
} | identifier_body |
selectors.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 cssparser::Parser;
use selectors::parser::{Selector, ParserContext, parse_selector_list};
use style::selector_... | () {
assert_roundtrip!(parse, "div");
assert_roundtrip!(parse, "svg|circle");
assert_roundtrip!(parse, "p:before", "p::before");
assert_roundtrip!(parse, "[border = \"0\"]:-servo-nonzero-border ~ ::-servo-details-summary");
}
| test_selectors | identifier_name |
webdriver_msg.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 constellation_msg::PipelineId; | use rustc_serialize::json::{Json, ToJson};
use url::Url;
#[derive(Deserialize, Serialize)]
pub enum WebDriverScriptCommand {
ExecuteScript(String, IpcSender<WebDriverJSResult>),
ExecuteAsyncScript(String, IpcSender<WebDriverJSResult>),
FindElementCSS(String, IpcSender<Result<Option<String>, ()>>),
Find... | use ipc_channel::ipc::IpcSender; | random_line_split |
webdriver_msg.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 constellation_msg::PipelineId;
use ipc_channel::ipc::IpcSender;
use rustc_serialize::json::{Json, ToJson};
use... | {
ExecuteScript(String, IpcSender<WebDriverJSResult>),
ExecuteAsyncScript(String, IpcSender<WebDriverJSResult>),
FindElementCSS(String, IpcSender<Result<Option<String>, ()>>),
FindElementsCSS(String, IpcSender<Result<Vec<String>, ()>>),
FocusElement(String, IpcSender<Result<(), ()>>),
GetActive... | WebDriverScriptCommand | identifier_name |
crateresolve4b-2.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 ... | { crateresolve4a::f() } | identifier_body | |
crateresolve4b-2.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 ... | () -> int { crateresolve4a::f() }
| g | identifier_name |
mod.rs | //! The compiler code necessary to implement the `#[derive]` extensions.
use rustc_ast as ast;
use rustc_ast::ptr::P;
use rustc_ast::{Impl, ItemKind, MetaItem};
use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, MultiItemModifier};
use rustc_span::symbol::{sym, Ident, Symbol};
use rustc_span::Span;
macro pa... |
_ => {
(self.0)(ecx, span, meta_item, &item, &mut |a| items.push(a));
}
}
ExpandResult::Ready(items)
}
}
/// Constructs an expression that calls an intrinsic
fn call_intrinsic(
cx: &ExtCtxt<'_>,
span: Span,
intrinsic: Symbol,
args: Vec<P<ast:... | {
if let ast::StmtKind::Item(item) = stmt.into_inner().kind {
(self.0)(ecx, span, meta_item, &Annotatable::Item(item), &mut |a| {
// Cannot use 'ecx.stmt_item' here, because we need to pass 'ecx'
// to the function
... | conditional_block |
mod.rs | //! The compiler code necessary to implement the `#[derive]` extensions.
use rustc_ast as ast;
use rustc_ast::ptr::P;
use rustc_ast::{Impl, ItemKind, MetaItem};
use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, MultiItemModifier};
use rustc_span::symbol::{sym, Ident, Symbol};
use rustc_span::Span;
macro pa... |
macro pathvec_std($($rest:ident)::+) {{
vec![ $( sym::$rest ),+ ]
}}
macro path_std($($x:tt)*) {
generic::ty::Path::new( pathvec_std!( $($x)* ) )
}
pub mod bounds;
pub mod clone;
pub mod debug;
pub mod decodable;
pub mod default;
pub mod encodable;
pub mod hash;
#[path = "cmp/eq.rs"]
pub mod eq;
#[path = "c... | random_line_split | |
structinfo.rs | // GObject Introspection Rust bindings.
// Copyright (C) 2014 Luis Araujo <araujoc.luisf@gmail.com>
// 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 Free Software Foundation; either
// version 2.1 of the Licen... | unsafe { g_struct_info_get_field(info, n as c_int) }
}
/// Obtain the number of methods this structure has.
pub fn get_n_methods(info: *GIStructInfo) -> int {
unsafe { g_struct_info_get_n_methods(info) as int }
}
/// Obtain the type information for method with specified index.
pub fn get_method(info: *GIStruc... | pub fn get_field(info: *GIStructInfo, n: int) -> *GIFieldInfo { | random_line_split |
structinfo.rs | // GObject Introspection Rust bindings.
// Copyright (C) 2014 Luis Araujo <araujoc.luisf@gmail.com>
// 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 Free Software Foundation; either
// version 2.1 of the Licen... |
/// Obtain the required alignment of the structure.
pub fn get_alignment(info: *GIStructInfo) -> size_t {
unsafe { g_struct_info_get_alignment(info) }
}
/// Return true if this structure represents the "class structure" for some
/// GObject or GInterface.
pub fn is_gtype_struct(info: *GIStructInfo) -> GBoolean... | {
unsafe { g_struct_info_get_size(info) }
} | identifier_body |
structinfo.rs | // GObject Introspection Rust bindings.
// Copyright (C) 2014 Luis Araujo <araujoc.luisf@gmail.com>
// 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 Free Software Foundation; either
// version 2.1 of the Licen... | (info: *GIStructInfo) -> GBoolean {
unsafe { g_struct_info_is_foreign(info) }
}
/// Convert GIBaseInfo to GIStructInfo.
pub fn to_gi_struct_info<T>(object: *T) -> *GIStructInfo {
unsafe { transmute(object) }
}
| is_foreign | identifier_name |
mod.rs | use std::slice;
use libc::ptrdiff_t;
use md5 as md5_crate;
use sha2::{Digest, Sha224, Sha256, Sha384, Sha512};
use remacs_macros::lisp_fn;
use crate::{
buffers::{LispBufferOrName, LispBufferRef},
lisp::LispObject,
multibyte::LispStringRef,
remacs_sys::EmacsInt,
remacs_sys::{extract_data_from_obj... |
fn sha512_buffer(buffer: &[u8], dest_buf: &mut [u8]) {
sha2_hash_buffer(Sha512::new(), buffer, dest_buf);
}
/// Return a hash of the contents of BUFFER-OR-NAME.
/// This hash is performed on the raw internal format of the buffer,
/// disregarding any coding systems. If nil, use the current buffer.
#[lisp_fn(min... | {
sha2_hash_buffer(Sha384::new(), buffer, dest_buf);
} | identifier_body |
mod.rs | use std::slice;
use libc::ptrdiff_t;
use md5 as md5_crate;
use sha2::{Digest, Sha224, Sha256, Sha384, Sha512};
use remacs_macros::lisp_fn;
use crate::{
buffers::{LispBufferOrName, LispBufferRef},
lisp::LispObject,
multibyte::LispStringRef,
remacs_sys::EmacsInt,
remacs_sys::{extract_data_from_obj... | sha2_hash_buffer(Sha224::new(), buffer, dest_buf);
}
fn sha256_buffer(buffer: &[u8], dest_buf: &mut [u8]) {
sha2_hash_buffer(Sha256::new(), buffer, dest_buf);
}
fn sha384_buffer(buffer: &[u8], dest_buf: &mut [u8]) {
sha2_hash_buffer(Sha384::new(), buffer, dest_buf);
}
fn sha512_buffer(buffer: &[u8], dest... |
fn sha224_buffer(buffer: &[u8], dest_buf: &mut [u8]) { | random_line_split |
mod.rs | use std::slice;
use libc::ptrdiff_t;
use md5 as md5_crate;
use sha2::{Digest, Sha224, Sha256, Sha384, Sha512};
use remacs_macros::lisp_fn;
use crate::{
buffers::{LispBufferOrName, LispBufferRef},
lisp::LispObject,
multibyte::LispStringRef,
remacs_sys::EmacsInt,
remacs_sys::{extract_data_from_obj... | (
algorithm: HashAlg,
object: LispObject,
start: LispObject,
end: LispObject,
coding_system: LispObject,
noerror: LispObject,
binary: LispObject,
) -> LispObject {
type HashFn = fn(&[u8], &mut [u8]);
let spec = list!(object, start, end, coding_system, noerror);
let mut start_byt... | _secure_hash | identifier_name |
mod.rs | use std::slice;
use libc::ptrdiff_t;
use md5 as md5_crate;
use sha2::{Digest, Sha224, Sha256, Sha384, Sha512};
use remacs_macros::lisp_fn;
use crate::{
buffers::{LispBufferOrName, LispBufferRef},
lisp::LispObject,
multibyte::LispStringRef,
remacs_sys::EmacsInt,
remacs_sys::{extract_data_from_obj... |
digest
}
/// To avoid a copy, buffer is both the source and the destination of
/// this transformation. Buffer must contain len bytes of data and
/// 2*len bytes of space for the final hex string.
fn hexify_digest_string(buffer: &mut [u8], len: usize) {
static hexdigit: [u8; 16] = *b"0123456789abcdef";
de... | {
hexify_digest_string(digest_str.as_mut_slice(), digest_size);
} | conditional_block |
a.rs | use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::error::Error;
static KEYPAD_MAP: [[u8; 3]; 3] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
struct Turtle {
x: i8,
y: i8,
code: String,
}
impl Turtle {
fn new() -> Turtle {
Turtle {
x: 1,
... | }
fn set_x(&mut self, x: i8) {
if self.x + x <= 2 && self.x + x >= 0 {
self.x = self.x + x;
}
}
fn set_y(&mut self, y: i8) {
if self.y + y <= 2 && self.y + y >= 0{
self.y = self.y + y;
}
}
fn move_turtle(&mut self, direction: &char) ... | random_line_split | |
a.rs | use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::error::Error;
static KEYPAD_MAP: [[u8; 3]; 3] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
struct Turtle {
x: i8,
y: i8,
code: String,
}
impl Turtle {
fn new() -> Turtle {
Turtle {
x: 1,
... |
fn press_button(&mut self) {
self.code.push_str(KEYPAD_MAP[self.y as usize][self.x as usize].to_string().as_str());
}
}
fn main() {
let mut turtle = Turtle::new();
let f = match File::open("input.txt") {
Err(e) => panic!("open failed: {}", e.description()),
Ok(file) => file,
... | {
match direction.to_lowercase().collect::<String>().as_str() {
"r" => self.set_x(1),
"l" => self.set_x(-1),
"u" => self.set_y(-1),
"d" => self.set_y(1),
_ => panic!("not a valid direction!"),
};
} | identifier_body |
a.rs | use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::error::Error;
static KEYPAD_MAP: [[u8; 3]; 3] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
struct Turtle {
x: i8,
y: i8,
code: String,
}
impl Turtle {
fn new() -> Turtle {
Turtle {
x: 1,
... | (&mut self, direction: &char) {
match direction.to_lowercase().collect::<String>().as_str() {
"r" => self.set_x(1),
"l" => self.set_x(-1),
"u" => self.set_y(-1),
"d" => self.set_y(1),
_ => panic!("not a valid direction!"),
};
}
fn pr... | move_turtle | identifier_name |
atomic_nand_acq.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_nand_acq;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread; | // pub fn atomic_nand_acq<T>(dst: *mut T, src: T) -> T;
struct A<T> {
v: UnsafeCell<T>
}
unsafe impl Sync for A<T> {}
impl<T> A<T> {
fn new(v: T) -> A<T> {
A { v: UnsafeCell::<T>::new(v) }
}
}
type T = usize;
macro_rules! atomic_nand_acq_test {
($init:expr, $value:expr, $re... | random_line_split | |
atomic_nand_acq.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_nand_acq;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_nand_acq<T>(dst: *mut T, src: T) -> T;
struct A<T> {
v: UnsafeCell<T>
}
unsafe i... | (v: T) -> A<T> {
A { v: UnsafeCell::<T>::new(v) }
}
}
type T = usize;
macro_rules! atomic_nand_acq_test {
($init:expr, $value:expr, $result:expr) => ({
let value: T = $init;
let a: A<T> = A::<T>::new(value);
let data: Arc<A<T>> = Arc::<A<T>>::new(a);
let clone: Arc<A<T>> = data... | new | identifier_name |
headless.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 compositing::*;
use geom::size::Size2D;
use servo_msg::constellation_msg::{ConstellationChan, ExitMsg, Resize... | }
fn handle_message(&self, constellation_chan: ConstellationChan) {
loop {
match self.port.recv() {
Exit(chan) => {
debug!("shutting down the constellation");
let ConstellationChan(ref con_chan) = constellation_chan;
... | {
let compositor = NullCompositor::new(port);
// Tell the constellation about the initial fake size.
{
let ConstellationChan(ref chan) = constellation_chan;
chan.send(ResizedWindowMsg(Size2D(640u, 480u)));
}
compositor.handle_message(constellation_chan);
... | identifier_body |
headless.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 compositing::*;
use geom::size::Size2D;
use servo_msg::constellation_msg::{ConstellationChan, ExitMsg, Resize... | (&self, constellation_chan: ConstellationChan) {
loop {
match self.port.recv() {
Exit(chan) => {
debug!("shutting down the constellation");
let ConstellationChan(ref con_chan) = constellation_chan;
con_chan.send(ExitMsg);
... | handle_message | identifier_name |
headless.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 compositing::*;
use geom::size::Size2D;
use servo_msg::constellation_msg::{ConstellationChan, ExitMsg, Resize... | // Explicitly list ignored messages so that when we add a new one,
// we'll notice and think about whether it needs a response, like
// SetIds.
CreateRootCompositorLayerIfNecessary(..) |
CreateDescendantCompositorLayerIfNecessary(..) | Set... | SetIds(_, response_chan, _) => {
response_chan.send(());
}
| random_line_split |
poll_fn.rs | use crate::fmt;
use crate::future::Future;
use crate::pin::Pin;
use crate::task::{Context, Poll};
/// Creates a future that wraps a function returning [`Poll`].
///
/// Polling the future delegates to the wrapped function.
///
/// # Examples
///
/// ```
/// #![feature(future_poll_fn)]
/// # async fn run() {
/// use co... | (mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
(&mut self.f)(cx)
}
}
| poll | identifier_name |
poll_fn.rs | use crate::fmt;
use crate::future::Future;
use crate::pin::Pin;
use crate::task::{Context, Poll};
/// Creates a future that wraps a function returning [`Poll`].
///
/// Polling the future delegates to the wrapped function.
///
/// # Examples
///
/// ```
/// #![feature(future_poll_fn)]
/// # async fn run() {
/// use co... |
/// A Future that wraps a function returning [`Poll`].
///
/// This `struct` is created by [`poll_fn()`]. See its
/// documentation for more.
#[must_use = "futures do nothing unless you `.await` or poll them"]
#[unstable(feature = "future_poll_fn", issue = "72302")]
pub struct PollFn<F> {
f: F,
}
#[unstable(feat... | {
PollFn { f }
} | identifier_body |
poll_fn.rs | use crate::fmt; | use crate::task::{Context, Poll};
/// Creates a future that wraps a function returning [`Poll`].
///
/// Polling the future delegates to the wrapped function.
///
/// # Examples
///
/// ```
/// #![feature(future_poll_fn)]
/// # async fn run() {
/// use core::future::poll_fn;
/// use std::task::{Context, Poll};
///
///... | use crate::future::Future;
use crate::pin::Pin; | random_line_split |
mod.rs | pub mod vcx;
pub mod connection;
pub mod issuer_credential;
pub mod utils;
pub mod proof;
pub mod credential_def;
pub mod schema;
pub mod credential;
pub mod disclosed_proof;
pub mod wallet;
pub mod logger;
pub mod return_types_u32;
use std::fmt;
/// This macro allows the VcxStateType to be
/// serialized within serd... | (){
let z = VcxStateNone;
let y = serde_json::to_string(&z).unwrap();
assert_eq!(y,"0");
}
}
| test_serialize_vcx_state_type | identifier_name |
mod.rs | pub mod vcx;
pub mod connection;
pub mod issuer_credential;
pub mod utils;
pub mod proof;
pub mod credential_def;
pub mod schema;
pub mod credential;
pub mod disclosed_proof;
pub mod wallet;
pub mod logger;
pub mod return_types_u32;
use std::fmt;
/// This macro allows the VcxStateType to be
/// serialized within serd... | #[cfg(test)]
mod tests {
use super::*;
use serde_json;
use self::VcxStateType::*;
#[test]
fn test_serialize_vcx_state_type(){
let z = VcxStateNone;
let y = serde_json::to_string(&z).unwrap();
assert_eq!(y,"0");
}
} | pub status: libc::c_int,
pub msg: *mut libc::c_char,
}
| random_line_split |
movelist.rs | // This file is part of the shakmaty library.
// Copyright (C) 2017-2022 Niklas Fiekas <niklas.fiekas@backscattering.de>
//
// This program 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... | // GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use arrayvec::ArrayVec;
use crate::types::Move;
/// A container for moves that can be stored inline on the stack.
///
/// The... | // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | random_line_split |
node_count.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 visit_path_list_item(&mut self, prefix: &Path, item: &PathListItem) {
self.count += 1;
walk_path_list_item(self, prefix, item)
}
fn visit_path_parameters(&mut self, path_span: Span, path_parameters: &PathParameters) {
self.count += 1;
walk_path_parameters(self, path_span,... | {
self.count += 1;
walk_path(self, path)
} | identifier_body |
node_count.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 ... | (&mut self, b: &Block) {
self.count += 1;
walk_block(self, b)
}
fn visit_stmt(&mut self, s: &Stmt) {
self.count += 1;
walk_stmt(self, s)
}
fn visit_arm(&mut self, a: &Arm) {
self.count += 1;
walk_arm(self, a)
}
fn visit_pat(&mut self, p: &Pat) {
... | visit_block | identifier_name |
node_count.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 ... | walk_assoc_type_binding(self, type_binding)
}
fn visit_attribute(&mut self, _attr: &Attribute) {
self.count += 1;
}
} | }
fn visit_assoc_type_binding(&mut self, type_binding: &TypeBinding) {
self.count += 1; | random_line_split |
preprocessor.rs | use std::vec::Vec;
use std::string::String;
use std::collections::HashMap;
//Returns a string with comments removed, with everything in lowercase
pub fn sanitize_line(input: &mut String) {
while let Some(i) = input.find(',') {
input.remove(i);
}
match input.find(';') {
Some(i) => *input = ... | }
Ok(converted)
} | sanitize_line(&mut line);
if !line.is_empty() {
converted.push(line);
} | random_line_split |
preprocessor.rs | use std::vec::Vec;
use std::string::String;
use std::collections::HashMap;
//Returns a string with comments removed, with everything in lowercase
pub fn | (input: &mut String) {
while let Some(i) = input.find(',') {
input.remove(i);
}
match input.find(';') {
Some(i) => *input = input[0..i].to_string(),
None => {}
}
*input = input.trim().to_string().to_lowercase();
}
//Preprocessor should support #define VAL xyz
pub fn prepro... | sanitize_line | identifier_name |
preprocessor.rs | use std::vec::Vec;
use std::string::String;
use std::collections::HashMap;
//Returns a string with comments removed, with everything in lowercase
pub fn sanitize_line(input: &mut String) {
while let Some(i) = input.find(',') {
input.remove(i);
}
match input.find(';') {
Some(i) => *input = ... | else {
new.push(word.clone());
}
}
let check_line = current_line.trim_left();
if check_line.starts_with("#") {
//Preprocessor definition
let mut words = check_line.split_whitespace();
match &words.next().unwrap()[1..] {
... | {
let to_check;
if word.ends_with(",") {
to_check = &word[1..word.len() - 1];
} else {
to_check = &word[1..];
}
match definitions.get(to_check) {
Some(n) => new.push(n.clone()),
... | conditional_block |
preprocessor.rs | use std::vec::Vec;
use std::string::String;
use std::collections::HashMap;
//Returns a string with comments removed, with everything in lowercase
pub fn sanitize_line(input: &mut String) |
//Preprocessor should support #define VAL xyz
pub fn preprocess(input: &Vec<&str>) -> Result<Vec<String>, (String, u32)> {
let mut output: Vec<String> = input.iter().map(|x| x.to_string()).collect();
let mut definitions: HashMap<String, String> = HashMap::new();
let mut line_num = 0u32;
//Find defin... | {
while let Some(i) = input.find(',') {
input.remove(i);
}
match input.find(';') {
Some(i) => *input = input[0..i].to_string(),
None => {}
}
*input = input.trim().to_string().to_lowercase();
} | identifier_body |
restrictederrorinfo.rs | // Copyright © 2017 winapi-rs developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modi... | interface IRestrictedErrorInfo(IRestrictedErrorInfoVtbl): IUnknown(IUnknownVtbl) {
fn GetErrorDetails(
description: *mut ::BSTR,
error: *mut ::HRESULT,
restrictedDescription: *mut ::BSTR,
capabilitySid: *mut ::BSTR,
) -> ::HRESULT,
fn GetReference(
reference: *mut ::B... | // except according to those terms.
RIDL!(
#[uuid(0x82ba7092, 0x4c88, 0x427d, 0xa7, 0xbc, 0x16, 0xdd, 0x93, 0xfe, 0xb6, 0x7e)] | random_line_split |
std.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
# The Rust standard library
The Rust standard library is a group of interrelated modules defining
the core language traits, operations on built-in d... | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | random_line_split |
traits.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... |
/// Inject all changes in a single batch.
#[cfg(test)]
fn inject_batch(&mut self) -> Result<u32, UtilError> {
let mut batch = self.backing().transaction();
let res = self.inject(&mut batch)?;
self.backing().write(batch).map(|_| res).map_err(Into::into)
}
}
| {
let mut batch = self.backing().transaction();
let mut ops = self.journal_under(&mut batch, now, id)?;
if let Some((end_era, canon_id)) = end {
ops += self.mark_canonical(&mut batch, end_era, &canon_id)?;
}
let result = self.backing().write(batch).map(|_| ops).map_err(Into::into);
self.flush();
resu... | identifier_body |
traits.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 consolidate(&mut self, overlay: ::memorydb::MemoryDB);
/// Commit all changes in a single batch
#[cfg(test)]
fn commit_batch(&mut self, now: u64, id: &H256, end: Option<(u64, H256)>) -> Result<u32, UtilError> {
let mut batch = self.backing().transaction();
let mut ops = self.journal_under(&mut batch, now, i... | /// Clear internal strucutres. This should called after changes have been written
/// to the backing strage
fn flush(&self) {}
/// Consolidate all the insertions and deletions in the given memory overlay. | random_line_split |
traits.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... |
let result = self.backing().write(batch).map(|_| ops).map_err(Into::into);
self.flush();
result
}
/// Inject all changes in a single batch.
#[cfg(test)]
fn inject_batch(&mut self) -> Result<u32, UtilError> {
let mut batch = self.backing().transaction();
let res = self.inject(&mut batch)?;
self.backin... | {
ops += self.mark_canonical(&mut batch, end_era, &canon_id)?;
} | conditional_block |
traits.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) -> usize { 0 }
/// Check if this database has any commits
fn is_empty(&self) -> bool;
/// Get the earliest era in the DB. None if there isn't yet any data in there.
fn earliest_era(&self) -> Option<u64> { None }
/// Get the latest era in the DB. None if there isn't yet any data in there.
fn latest_era(... | journal_size | identifier_name |
http_parts.rs | //! HTTP parts of a Request/Response interaction
use std::collections::HashMap;
use std::str::from_utf8;
use maplit::hashmap;
use crate::bodies::OptionalBody;
use crate::content_types::{ContentType, detect_content_type_from_string};
use crate::generators::{Generator, GeneratorCategory, Generators};
use crate::matchi... | () {
let request = Request { method: "GET".to_string(), path: "/".to_string(), query: None,
headers: Some(hashmap!{ "Content-Type".to_string() => vec!["application/json; charset=UTF-8".to_string()] }),
body: OptionalBody::Missing,.. Request::default() };
expect!(request.has_header("Content-Type")).t... | http_part_has_header_test | identifier_name |
http_parts.rs | //! HTTP parts of a Request/Response interaction
use std::collections::HashMap;
use std::str::from_utf8;
use maplit::hashmap;
use crate::bodies::OptionalBody;
use crate::content_types::{ContentType, detect_content_type_from_string};
use crate::generators::{Generator, GeneratorCategory, Generators};
use crate::matchi... | else {
match self.lookup_content_type() {
Some(ref h) => match ContentType::parse(h.as_str()) {
Ok(v) => Some(v),
Err(_) => self.detect_content_type()
},
None => self.detect_content_type()
}
}
}
/// Checks if the HTTP Part has the given header
fn has_h... | {
body.content_type()
} | conditional_block |
http_parts.rs | //! HTTP parts of a Request/Response interaction
use std::collections::HashMap;
use std::str::from_utf8;
use maplit::hashmap;
use crate::bodies::OptionalBody;
use crate::content_types::{ContentType, detect_content_type_from_string};
use crate::generators::{Generator, GeneratorCategory, Generators};
use crate::matchi... |
/// Returns a mutable pointer to the body of the HTTP part.
fn body_mut(&mut self) -> &mut OptionalBody;
/// Returns the matching rules of the HTTP part.
fn matching_rules(&self) -> &MatchingRules;
/// Returns the matching rules of the HTTP part.
fn matching_rules_mut(&mut self) -> &mut MatchingRules;
... | /// Returns the body of the HTTP part.
fn body(&self) -> &OptionalBody; | random_line_split |
http_parts.rs | //! HTTP parts of a Request/Response interaction
use std::collections::HashMap;
use std::str::from_utf8;
use maplit::hashmap;
use crate::bodies::OptionalBody;
use crate::content_types::{ContentType, detect_content_type_from_string};
use crate::generators::{Generator, GeneratorCategory, Generators};
use crate::matchi... |
/// Checks if the HTTP Part has the given header
fn lookup_header_value(&self, header_name: &str) -> Option<String> {
match *self.headers() {
Some(ref h) => h.iter()
.find(|kv| kv.0.to_lowercase() == header_name.to_lowercase())
.map(|kv| kv.1.clone().join(", ")),
None => None
}
... | {
self.lookup_header_value(header_name).is_some()
} | identifier_body |
istr.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let s: ~str = ~"a big ol' string";
let t: ~str = ~"a big ol' string";
assert!(s == t);
let u: ~str = ~"a bad ol' string";
assert!((s!= u));
}
fn test_heap_log() { let s = ~"a big ol' string"; println!("{}", s); }
fn test_stack_add() {
assert_eq!(~"a" + "b", ~"ab");
let s: ~str = ~"a";... | test_heap_assign | identifier_name |
istr.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 ... | test_stack_add();
test_stack_heap_add();
test_heap_add();
test_append();
} | test_heap_assign();
test_heap_log(); | random_line_split |
istr.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 ... |
fn test_heap_log() { let s = ~"a big ol' string"; println!("{}", s); }
fn test_stack_add() {
assert_eq!(~"a" + "b", ~"ab");
let s: ~str = ~"a";
assert_eq!(s + s, ~"aa");
assert_eq!(~"" + "", ~"");
}
fn test_stack_heap_add() { assert!((~"a" + "bracadabra" == ~"abracadabra")); }
fn test_heap_add() {
... | {
let s: ~str = ~"a big ol' string";
let t: ~str = ~"a big ol' string";
assert!(s == t);
let u: ~str = ~"a bad ol' string";
assert!((s != u));
} | identifier_body |
associated-types-conditional-dispatch.rs | // run-pass
// Test that we evaluate projection predicates to winnow out
// candidates during trait selection and method resolution (#20296).
// If we don't properly winnow out candidates based on the output type
// `Target=[A]`, then the impl marked with `(*)` is seen to conflict
// with all the others.
// pretty-exp... | (&self) -> &T {
self.as_ref().unwrap()
}
}
impl<T, H: Helper<T>> Deref for DerefWithHelper<H, T> {
type Target = T;
fn deref(&self) -> &T {
self.helper.helper_borrow()
}
}
pub fn check<T: MyEq>(x: T, y: T) -> bool {
let d: DerefWithHelper<Option<T>, T> = DerefWithHelper { helper: ... | helper_borrow | identifier_name |
associated-types-conditional-dispatch.rs | // run-pass
// Test that we evaluate projection predicates to winnow out
// candidates during trait selection and method resolution (#20296).
// If we don't properly winnow out candidates based on the output type
// `Target=[A]`, then the impl marked with `(*)` is seen to conflict
// with all the others.
// pretty-exp... | {
} | identifier_body | |
associated-types-conditional-dispatch.rs | // run-pass
// Test that we evaluate projection predicates to winnow out
// candidates during trait selection and method resolution (#20296).
// If we don't properly winnow out candidates based on the output type
// `Target=[A]`, then the impl marked with `(*)` is seen to conflict
// with all the others.
// pretty-exp... | fn helper_borrow(&self) -> &T {
self.as_ref().unwrap()
}
}
impl<T, H: Helper<T>> Deref for DerefWithHelper<H, T> {
type Target = T;
fn deref(&self) -> &T {
self.helper.helper_borrow()
}
}
pub fn check<T: MyEq>(x: T, y: T) -> bool {
let d: DerefWithHelper<Option<T>, T> = DerefW... | trait Helper<T> {
fn helper_borrow(&self) -> &T;
}
impl<T> Helper<T> for Option<T> { | random_line_split |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... | {
/// The initial URLs to load.
pub urls: Vec<String>,
/// How many threads to use for CPU painting (`-t`).
///
/// FIXME(pcwalton): This is not currently used. All painting is sequential.
pub n_paint_threads: uint,
/// True to use GPU painting via Skia-GL, false to use CPU painting via S... | Opts | identifier_name |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... | {
unsafe {
// If code attempts to retrieve the options and they haven't
// been set by the platform init code, just return a default
// set of options. This is mostly useful for unit tests that
// run through a code path which queries the cmd line options.
if OPTIONS == ptr::... | identifier_body | |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... |
set_opts(opts);
true
}
static mut EXPERIMENTAL_ENABLED: bool = false;
pub fn set_experimental_enabled(new_value: bool) {
unsafe {
EXPERIMENTAL_ENABLED = new_value;
}
}
pub fn experimental_enabled() -> bool {
unsafe {
EXPERIMENTAL_ENABLED
}
}
// Make Opts available globally. ... | dump_flow_tree: debug_options.contains(&"dump-flow-tree"),
validate_display_list_geometry: debug_options.contains(&"validate-display-list-geometry"),
resources_path: opt_match.opt_str("resources-path"),
}; | random_line_split |
readme_sync.rs | // Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
// required by `FutureClient` (not used directly in this example)
#![feature(plugin)]
#![pl... | let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let handle = HelloServer.listen("localhost:0", server::Options::default()).unwrap();
tx.send(handle.addr()).unwrap();
handle.run();
});
let client = SyncClient::connect(rx.recv().unwrap(), client::Options::default()).unwrap(... | }
fn main() { | random_line_split |
readme_sync.rs | // Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
// required by `FutureClient` (not used directly in this example)
#![feature(plugin)]
#![pl... | ;
impl SyncService for HelloServer {
fn hello(&self, name: String) -> Result<String, Never> {
Ok(format!("Hello from thread {}, {}!", thread::current().name().unwrap(), name))
}
}
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let handle = HelloServer.listen("local... | HelloServer | identifier_name |
router.rs | use regex::Regex;
use hyper::Method;
use hyper::server::Request;
use context::{Context, Params, ParamType};
type Handler = fn(Context) -> ::Response;
pub struct Router {
pub routes: Vec<Route>
}
impl Router {
pub fn new() -> Router {
Router {
routes: Vec::new()
}
}
pub fn... |
// Save url params while processing
let mut params = Params::new();
for (index, token) in self.tokenized_path.iter().enumerate() {
match token {
&PathToken::Str(ref s) => {
if *s!= incoming_path[index] {
return None
... | {
return None;
} | conditional_block |
router.rs | use regex::Regex;
use hyper::Method;
use hyper::server::Request;
use context::{Context, Params, ParamType};
type Handler = fn(Context) -> ::Response;
pub struct Router {
pub routes: Vec<Route>
}
impl Router {
pub fn new() -> Router {
Router {
routes: Vec::new()
}
} | }
}
#[derive(Clone)]
pub struct Route {
pub method: Method,
pub path: RoutePath,
pub handler: Handler
}
impl Route {
pub fn new(method: Method, path: &str, handler: Handler) -> Route {
Route {
method: method,
path: RoutePath::new(path),
handler: handler
... |
pub fn get(&mut self, path: &str, handler: Handler) {
self.routes.push(
Route::new(Method::Get, path, handler)
); | random_line_split |
router.rs | use regex::Regex;
use hyper::Method;
use hyper::server::Request;
use context::{Context, Params, ParamType};
type Handler = fn(Context) -> ::Response;
pub struct Router {
pub routes: Vec<Route>
}
impl Router {
pub fn new() -> Router {
Router {
routes: Vec::new()
}
}
pub fn... | () {
let route = Route::new(Method::Get, "/monkeys", generic_handler);
let path = Uri::from_str("http://example.com/nomatch").unwrap();
let request: Request = Request::new(Method::Get, path);
assert!(route.matches_request(&request).is_none());
}
#[test]
fn route_should_match... | route_should_not_be_matched | identifier_name |
mod.rs | //! HTTP Server
//!
//! # Server
//!
//! A `Server` is created to listen on port, parse HTTP requests, and hand
//! them off to a `Handler`. By default, the Server will listen across multiple
//! threads, but that can be configured to a single thread if preferred.
//!
//! # Handling requests
//!
//! You must pass a `Ha... |
}
impl Listening {
/// Stop the server from listening to its socket address.
pub fn close(&mut self) -> ::Result<()> {
let _ = self._guard.take();
debug!("closing server");
Ok(())
}
}
/// A handler that can handle incoming requests for a server.
pub trait Handler: Sync + Send {
... | {
let _ = self._guard.take().map(|g| g.join());
} | identifier_body |
mod.rs | //! HTTP Server
//!
//! # Server
//!
//! A `Server` is created to listen on port, parse HTTP requests, and hand
//! them off to a `Handler`. By default, the Server will listen across multiple
//! threads, but that can be configured to a single thread if preferred.
//!
//! # Handling requests
//!
//! You must pass a `Ha... |
}
self.handler.on_connection_end();
debug!("keep_alive loop ending for {}", addr);
}
fn set_timeouts(&self, s: &NetworkStream) -> io::Result<()> {
try!(self.set_read_timeout(s, self.timeouts.read));
self.set_write_timeout(s, self.timeouts.write)
}
#[cfg(not(f... | {
error!("set_read_timeout keep_alive {:?}", e);
break;
} | conditional_block |
mod.rs | //! HTTP Server
//!
//! # Server
//!
//! A `Server` is created to listen on port, parse HTTP requests, and hand
//! them off to a `Handler`. By default, the Server will listen across multiple
//! threads, but that can be configured to a single thread if preferred.
//!
//! # Handling requests
//!
//! You must pass a `Ha... | (&mut self, timeout: Duration) {
self.timeouts.keep_alive = Some(timeout);
}
#[cfg(feature = "timeouts")]
pub fn set_read_timeout(&mut self, dur: Option<Duration>) {
self.timeouts.read = dur;
}
#[cfg(feature = "timeouts")]
pub fn set_write_timeout(&mut self, dur: Option<Duratio... | keep_alive | identifier_name |
mod.rs | //! HTTP Server
//!
//! # Server
//!
//! A `Server` is created to listen on port, parse HTTP requests, and hand
//! them off to a `Handler`. By default, the Server will listen across multiple
//! threads, but that can be configured to a single thread if preferred.
//!
//! # Handling requests
//!
//! You must pass a `Ha... | use method::Method;
use net::{NetworkListener, NetworkStream, HttpListener, HttpsListener, Ssl};
use status::StatusCode;
use uri::RequestUri;
use version::HttpVersion::Http11;
use self::listener::ListenerPool;
pub mod request;
pub mod response;
mod listener;
/// A server can listen on a TCP socket.
///
/// Once lis... | random_line_split | |
paths.rs | //! Path manipulation utilities
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::path::{Path, PathBuf, Component};
use util::{human, internal, CraftResult, ChainError};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CraftResul... |
Component::ParentDir => {
ret.pop();
}
Component::Normal(c) => {
ret.push(c);
}
}
}
ret
}
pub fn without_prefix<'a>(a: &'a Path, b: &'a Path) -> Option<&'a Path> {
let mut a = a.components();
let mut b = b.componen... | {} | conditional_block |
paths.rs | //! Path manipulation utilities
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::path::{Path, PathBuf, Component};
use util::{human, internal, CraftResult, ChainError};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CraftResul... | }
}
pub fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek()
.cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
... | random_line_split | |
paths.rs | //! Path manipulation utilities
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::path::{Path, PathBuf, Component};
use util::{human, internal, CraftResult, ChainError};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CraftResul... | (path: &Path) -> CraftResult<&[u8]> {
match path.as_os_str().to_str() {
Some(s) => Ok(s.as_bytes()),
None => Err(human(format!("invalid non-unicode path: {}", path.display()))),
}
}
#[cfg(unix)]
pub fn bytes2path(bytes: &[u8]) -> CraftResult<PathBuf> {
use std::os::unix::prelude::*;
use... | path2bytes | identifier_name |
paths.rs | //! Path manipulation utilities
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::path::{Path, PathBuf, Component};
use util::{human, internal, CraftResult, ChainError};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CraftResul... |
pub fn read_bytes(path: &Path) -> CraftResult<Vec<u8>> {
(|| -> CraftResult<_> {
let mut ret = Vec::new();
let mut f = File::open(path)?;
f.read_to_end(&mut ret)?;
Ok(ret)
})()
.map_err(human)
.chain_error(|| human(format!("failed to read `{}`"... | {
(|| -> CraftResult<_> {
let mut ret = String::new();
let mut f = File::open(path)?;
f.read_to_string(&mut ret)?;
Ok(ret)
})()
.map_err(human)
.chain_error(|| human(format!("failed to read `{}`", path.display())))
} | identifier_body |
network.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program 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... | self.send_message(getdata)
}
}
| {
assert!(block_hashes.len() > 0);
let getdata_invs = block_hashes
.iter()
.map(|h| btc_message_blockdata::Inventory {
inv_type: btc_message_blockdata::InvType::Block,
hash: h.clone(),
})
.collect();
let getdata = b... | identifier_body |
network.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program 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... |
btc_message::NetworkMessage::Verack => {
return self.handle_verack(message).and_then(|_r| Ok(true));
}
btc_message::NetworkMessage::Ping(..) => {
return self.handle_ping(message).and_then(|_r| Ok(true));
}
btc_message::NetworkM... | {
return self.handle_version(message).and_then(|_r| Ok(true));
} | conditional_block |
network.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program 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... | // propagate other network error
warn!(
"Failed to handshake with {}:{}: {:?}",
&self.config.peer_host, self.config.peer_port, &e
);
return Err(... | backoff = 2.0 * backoff + (backoff * rng.gen_range(0.0, 1.0));
}
Err(e) => { | random_line_split |
network.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program 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... | (&mut self) -> Result<SocketAddr, btc_error> {
self.with_socket(|ref mut sock| sock.peer_addr().map_err(btc_error::Io))
}
/// Handle and consume message we received, if we can.
/// Returns UnhandledMessage if we can't handle the given message.
pub fn handle_message<T: BitcoinMessageHandler>(
... | get_remote_sockaddr | identifier_name |
macros.rs | #[macro_export]
macro_rules! implement_lua_push {
($ty:ty, $cb:expr) => {
impl<L> $crate::Push<L> for Sound where L: $crate::AsMutLua {
fn push_to_lua(self, lua: L) -> $crate::PushGuard<L> {
$crate::userdata::push_userdata(self, lua, $cb)
}
}
};
}
#[macro... | unsafe { ::std::mem::transmute($crate::userdata::read_userdata::<$ty>(lua, index)) }
}
}
};
} | random_line_split | |
p137.rs | //! [Problem 137](https://projecteuler.net/problem=137) solver.
//!
//! ```math
//! A_F(x) = x F_1 + x^2 F_2 + x^3 F_3 + \dots
//! x A_F(x) = x^2 F_1 + x^3 F_2 + x^4 F_3 + \dots
//! x^2 A_F(x) = x^3 F_1 + x^4 F_2 + x^5 F_3 + \dots
//! (1 - x - x^2) A_F(x) = x F_1 + x^2 (F_2 - F_1) + x^3 (F_3 - F_2 - F_1) + \dots
... | identifier_body | ||
p137.rs | //! [Problem 137](https://projecteuler.net/problem=137) solver.
//!
//! ```math
//! A_F(x) = x F_1 + x^2 F_2 + x^3 F_3 + \dots
//! x A_F(x) = x^2 F_1 + x^3 F_2 + x^4 F_3 + \dots
//! x^2 A_F(x) = x^3 F_1 + x^4 F_2 + x^5 F_3 + \dots
//! (1 - x - x^2) A_F(x) = x F_1 + x^2 (F_2 - F_1) + x^3 (F_3 - F_2 - F_1) + \dots
... | 9));
}
}
| conditional_block | |
p137.rs | //! [Problem 137](https://projecteuler.net/problem=137) solver.
//!
//! ```math
//! A_F(x) = x F_1 + x^2 F_2 + x^3 F_3 + \dots
//! x A_F(x) = x^2 F_1 + x^3 F_2 + x^4 F_3 + \dots
//! x^2 A_F(x) = x^3 F_1 + x^4 F_2 + x^5 F_3 + \dots
//! (1 - x - x^2) A_F(x) = x F_1 + x^2 (F_2 - F_1) + x^3 (F_3 - F_2 - F_1) + \dots
... | } else {
None
}
}).nth(i).unwrap().0
}
fn solve() -> String {
compute(14).to_string()
}
problem!("1120149658760", solve);
#[cfg(test)]
mod tests {
#[test]
fn tenth_sol() {
assert_eq!(74049690, super::compute(9));
}
} | }).filter_map(|(p, q)| {
if p % 5 == 1 {
Some((p / 5, q)) | random_line_split |
p137.rs | //! [Problem 137](https://projecteuler.net/problem=137) solver.
//!
//! ```math
//! A_F(x) = x F_1 + x^2 F_2 + x^3 F_3 + \dots
//! x A_F(x) = x^2 F_1 + x^3 F_2 + x^4 F_3 + \dots
//! x^2 A_F(x) = x^3 F_1 + x^4 F_2 + x^5 F_3 + \dots
//! (1 - x - x^2) A_F(x) = x F_1 + x^2 (F_2 - F_1) + x^3 (F_3 - F_2 - F_1) + \dots
... | identifier_name | ||
time.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/. */
//! Specified time values.
use cssparser::{Parser, Token};
use parser::{ParserContext, Parse};
use std::ascii::As... | was_calc: true,
}
}
fn parse_with_clamping_mode<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType
) -> Result<Self, ParseError<'i>> {
use style_traits::ParsingMode;
let location = input.current_source... | pub fn from_calc(seconds: CSSFloat) -> Self {
Time {
seconds: seconds,
unit: TimeUnit::Second, | random_line_split |
time.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/. */
//! Specified time values.
use cssparser::{Parser, Token};
use parser::{ParserContext, Parse};
use std::ascii::As... | i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType
) -> Result<Self, ParseError<'i>> {
use style_traits::ParsingMode;
let location = input.current_source_location();
// FIXME: remove early returns when lifetimes are non-lex... | rse_with_clamping_mode<' | identifier_name |
time.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/. */
//! Specified time values.
use cssparser::{Parser, Token};
use parser::{ParserContext, Parse};
use std::ascii::As... | fn from_computed_value(computed: &Self::ComputedValue) -> Self {
Time {
seconds: computed.seconds(),
unit: TimeUnit::Second,
was_calc: false,
}
}
}
impl Parse for Time {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self,... | ComputedTime::from_seconds(self.seconds())
}
| identifier_body |
module.rs | use std::fmt;
use libc;
use llvm_sys::prelude::*;
use llvm_sys::core as llvm;
use super::*;
use std::path::Path;
error_chain! {
errors {
ModulePrintFile(t: String) {
description("Error while printing module to file")
display("Error while printing module to file: '{}'", t)
... | (&mut self, name: &str) -> Option<Function> {
let c_name = CString::new(name).unwrap();
let res = unsafe {
llvm::LLVMGetNamedFunction(self.ptr, c_name.as_ptr())
};
if res.is_null() {
None
} else {
Some(Function::from_value_ref(res))
}
... | get_named_function | identifier_name |
module.rs | use std::fmt;
use libc;
use llvm_sys::prelude::*;
use llvm_sys::core as llvm;
use super::*;
use std::path::Path;
error_chain! {
errors {
ModulePrintFile(t: String) {
description("Error while printing module to file")
display("Error while printing module to file: '{}'", t)
... | len + 1,
len + 1
);
write!(f, "{}", s)
}
}
} | unsafe {
let c_str = llvm::LLVMPrintModuleToString(self.ptr);
let len = libc::strlen(c_str);
let s = String::from_raw_parts(
c_str as *mut u8, | random_line_split |
module.rs | use std::fmt;
use libc;
use llvm_sys::prelude::*;
use llvm_sys::core as llvm;
use super::*;
use std::path::Path;
error_chain! {
errors {
ModulePrintFile(t: String) {
description("Error while printing module to file")
display("Error while printing module to file: '{}'", t)
... |
pub fn get_named_function(&mut self, name: &str) -> Option<Function> {
let c_name = CString::new(name).unwrap();
let res = unsafe {
llvm::LLVMGetNamedFunction(self.ptr, c_name.as_ptr())
};
if res.is_null() {
None
} else {
Some(Function::... | {
let c_name = CString::new(name).unwrap();
let p = unsafe {
llvm::LLVMAddFunction(self.ptr, c_name.as_ptr(), func_ty.into())
};
Function {
ptr: p
}
} | identifier_body |
module.rs | use std::fmt;
use libc;
use llvm_sys::prelude::*;
use llvm_sys::core as llvm;
use super::*;
use std::path::Path;
error_chain! {
errors {
ModulePrintFile(t: String) {
description("Error while printing module to file")
display("Error while printing module to file: '{}'", t)
... | else {
Err(ErrorKind::ModulePrintFile(c_str_to_str!(em as *const i8).into()).into())
}
}
}
}
impl fmt::Display for Module {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
unsafe {
let c_str = llvm::LLVMPrintModuleToString(self.ptr);
l... | { // no error message was set
Ok(())
} | conditional_block |
unary.rs | //! Module implementing evaluation of unary operator AST nodes.
use eval::{self, api, Eval, Context, Value};
use parse::ast::UnaryOpNode;
impl Eval for UnaryOpNode {
fn eval(&self, context: &mut Context) -> eval::Result {
let arg = try!(self.arg.eval(context));
match &self.op[..] {
"+... | (arg: Value) -> eval::Result {
eval1!(arg : Integer { -arg });
eval1!(arg : Float { -arg });
UnaryOpNode::err("-", &arg)
}
/// Evaluate the "!" operator for one value.
#[inline]
fn eval_bang(arg: Value) -> eval::Result {
let arg = try!(api::conv::bool(arg)).unwrap_bool()... | eval_minus | identifier_name |
unary.rs | //! Module implementing evaluation of unary operator AST nodes.
use eval::{self, api, Eval, Context, Value};
use parse::ast::UnaryOpNode;
impl Eval for UnaryOpNode {
fn eval(&self, context: &mut Context) -> eval::Result {
let arg = try!(self.arg.eval(context));
match &self.op[..] {
"+... |
}
impl UnaryOpNode {
/// Produce an error about invalid argument for an operator.
#[inline]
fn err(op: &str, arg: &Value) -> eval::Result {
Err(eval::Error::new(&format!(
"invalid argument for `{}` operator: `{:?}`", op, arg
)))
}
}
| {
let arg = try!(api::conv::bool(arg)).unwrap_bool();
Ok(Value::Boolean(!arg))
} | identifier_body |
unary.rs | //! Module implementing evaluation of unary operator AST nodes.
use eval::{self, api, Eval, Context, Value};
use parse::ast::UnaryOpNode;
impl Eval for UnaryOpNode {
fn eval(&self, context: &mut Context) -> eval::Result {
let arg = try!(self.arg.eval(context));
match &self.op[..] {
"+... | /// Evaluate the "+" operator for one value.
fn eval_plus(arg: Value) -> eval::Result {
eval1!(arg : Integer { arg });
eval1!(arg : Float { arg });
UnaryOpNode::err("+", &arg)
}
/// Evaluate the "-" operator for one value.
fn eval_minus(arg: Value) -> eval::Result {
... | }
}
}
impl UnaryOpNode { | random_line_split |
person.rs | use std::time;
use time::Tm;
use mre::model::{Model, Error};
// Create a class to act as our model. Unfortunately Rust's classes aren't
// finished yet, and are missing a couple features that would help clean up
// models. First, there's no way to mix in implementation of functions, so we
// need to duplicate some cod... |
}
// Create a new person model.
pub fn Person(es: elasticsearch::Client, name: ~str) -> Person {
// Create a person. We'll store the model in the ES index named
// "helloeveryone", under the type "person". We'd like ES to make the index
// for us, so we leave the id blank.
let mut person = Person {
... | {
self.model.delete()
} | identifier_body |
person.rs | use std::time;
use time::Tm;
use mre::model::{Model, Error};
// Create a class to act as our model. Unfortunately Rust's classes aren't
// finished yet, and are missing a couple features that would help clean up
// models. First, there's no way to mix in implementation of functions, so we
// need to duplicate some cod... |
fn create(&self) -> Result<(~str, uint), Error> {
self.model.create()
}
fn save(&self) -> Result<(~str, uint), Error> {
self.model.save()
}
fn delete(&self) {
self.model.delete()
}
}
// Create a new person model.
pub fn Person(es: elasticsearch::Client, name: ~str) ->... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.