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 |
|---|---|---|---|---|
test.rs | //!
//! test.rs.rs
//!
//! Created by Mitchell Nordine at 05:57PM on December 19, 2014.
//!
//! Always remember to run high performance Rust code with the --release flag. `Synth`
//!
extern crate dsp;
extern crate pitch_calc as pitch;
extern crate portaudio;
extern crate synth;
extern crate time_calc as time;
use... |
fn run() -> Result<(), pa::Error> {
// Construct our fancy Synth!
let mut synth = {
use synth::{Point, Oscillator, mode, oscillator, Envelope};
// The following envelopes should create a downward pitching sine wave that gradually quietens.
// Try messing around with the points and ad... | {
run().unwrap()
} | identifier_body |
test.rs | //!
//! test.rs.rs
//!
//! Created by Mitchell Nordine at 05:57PM on December 19, 2014.
//!
//! Always remember to run high performance Rust code with the --release flag. `Synth`
//!
extern crate dsp;
extern crate pitch_calc as pitch;
extern crate portaudio;
extern crate synth;
extern crate time_calc as time;
use... | else {
pa::Complete
}
};
// Construct PortAudio and the stream.
let pa = try!(pa::PortAudio::new());
let settings = try!(pa.default_output_stream_settings::<f32>(CHANNELS, SAMPLE_HZ, FRAMES));
let mut stream = try!(pa.open_non_blocking_stream(settings, callback));
try!(stre... | {
let last_time = prev_time.unwrap_or(time.current);
let dt = time.current - last_time;
timer += dt;
prev_time = Some(time.current);
// Once the timer exceeds our note duration, send the note_off.
if timer > note_duration {
if !is... | conditional_block |
test.rs | //!
//! test.rs.rs
//!
//! Created by Mitchell Nordine at 05:57PM on December 19, 2014.
//!
//! Always remember to run high performance Rust code with the --release flag. `Synth`
//!
extern crate dsp;
extern crate pitch_calc as pitch;
extern crate portaudio;
extern crate synth;
extern crate time_calc as time;
use... | synth.note_off(note);
is_note_off = true;
}
}
pa::Continue
} else {
pa::Complete
}
};
// Construct PortAudio and the stream.
let pa = try!(pa::PortAudio::new());
let settings = try!(pa.default_ou... | if timer > note_duration {
if !is_note_off { | random_line_split |
part2.rs | // adventofcode - day 5
// part 2
use std::io::prelude::*;
use std::fs::File;
fn main(){
println!("Advent of Code - day 5 | part 2");
// import data
let wordlist = import_data();
let mut nice_words = 0i32;
for word in wordlist.lines(){
if contains_repeating_letter(word.to_string())
... |
// This function simply imports the data set from a file called input.txt
fn import_data() -> String {
let mut file = match File::open("../../inputs/05.txt") {
Ok(f) => f,
Err(e) => panic!("file error: {}", e),
};
let mut data = String::new();
match file.read_to_string(&mut data){
... | {
for ii in 0..word.len() - 1 {
let pair = &word[ii..ii+2];
let remainder = &word[ii+2..word.len()];
if remainder.contains(pair) {
return true;
}
}
false
} | identifier_body |
part2.rs | // adventofcode - day 5
// part 2
use std::io::prelude::*;
use std::fs::File;
fn main(){
println!("Advent of Code - day 5 | part 2");
// import data
let wordlist = import_data();
let mut nice_words = 0i32;
for word in wordlist.lines(){
if contains_repeating_letter(word.to_string())
... | }
fn contains_pair(word: String) -> bool {
for ii in 0..word.len() - 1 {
let pair = &word[ii..ii+2];
let remainder = &word[ii+2..word.len()];
if remainder.contains(pair) {
return true;
}
}
false
}
// This function simply imports the data set from a file calle... | random_line_split | |
part2.rs | // adventofcode - day 5
// part 2
use std::io::prelude::*;
use std::fs::File;
fn main(){
println!("Advent of Code - day 5 | part 2");
// import data
let wordlist = import_data();
let mut nice_words = 0i32;
for word in wordlist.lines(){
if contains_repeating_letter(word.to_string())
... | (word: String) -> bool {
for ii in 0..word.len() - 2 {
let tripple = &word[ii..ii+3];
if tripple.chars().nth(0) == tripple.chars().nth(2) {
return true;
}
}
false
}
fn contains_pair(word: String) -> bool {
for ii in 0..word.len() - 1 {
let pair = &word[ii... | contains_repeating_letter | identifier_name |
flat_map.rs | use consumer::*;
use std::cell::RefCell;
use std::rc::Rc;
use stream::*;
struct FlatmapState<C, F> {
child: Rc<RefCell<Option<C>>>,
func: F,
}
impl<C, F, I, S> Consumer<I> for FlatmapState<C, F>
where F: FnMut(I) -> S,
C: Consumer<S::Item>,
S: Stream
{
fn emit(&mut self, item: I) -... |
}
#[must_use = "stream adaptors are lazy and do nothing unless consumed"]
pub struct Flatmap<S, F> {
func: F,
stream: S,
}
impl<S, F> Flatmap<S, F> {
pub fn new(stream: S, func: F) -> Self {
Flatmap {
func: func,
stream: stream,
}
}
}
impl<S, F, SO> Stream for... | {
let mut consumer = self.borrow_mut();
if let Some(ref mut consumer) = *consumer {
if consumer.emit(item) {
return true;
}
}
*consumer = None;
false
} | identifier_body |
flat_map.rs | use consumer::*;
use std::cell::RefCell;
use std::rc::Rc;
use stream::*;
struct FlatmapState<C, F> {
child: Rc<RefCell<Option<C>>>,
func: F,
}
impl<C, F, I, S> Consumer<I> for FlatmapState<C, F>
where F: FnMut(I) -> S,
C: Consumer<S::Item>,
S: Stream
{
fn emit(&mut self, item: I) -... | (stream: S, func: F) -> Self {
Flatmap {
func: func,
stream: stream,
}
}
}
impl<S, F, SO> Stream for Flatmap<S, F>
where S: Stream,
F: FnMut(S::Item) -> SO,
SO: Stream
{
type Item = SO::Item;
fn consume<C>(self, consumer: C)
where C: ... | new | identifier_name |
flat_map.rs | use consumer::*;
use std::cell::RefCell;
use std::rc::Rc;
use stream::*;
struct FlatmapState<C, F> {
child: Rc<RefCell<Option<C>>>,
func: F,
}
impl<C, F, I, S> Consumer<I> for FlatmapState<C, F>
where F: FnMut(I) -> S,
C: Consumer<S::Item>,
S: Stream
{
fn emit(&mut self, item: I) -... | func: func,
stream: stream,
}
}
}
impl<S, F, SO> Stream for Flatmap<S, F>
where S: Stream,
F: FnMut(S::Item) -> SO,
SO: Stream
{
type Item = SO::Item;
fn consume<C>(self, consumer: C)
where C: Consumer<Self::Item>
{
self.stream.co... | pub fn new(stream: S, func: F) -> Self {
Flatmap { | random_line_split |
flat_map.rs | use consumer::*;
use std::cell::RefCell;
use std::rc::Rc;
use stream::*;
struct FlatmapState<C, F> {
child: Rc<RefCell<Option<C>>>,
func: F,
}
impl<C, F, I, S> Consumer<I> for FlatmapState<C, F>
where F: FnMut(I) -> S,
C: Consumer<S::Item>,
S: Stream
{
fn emit(&mut self, item: I) -... |
let stream = (self.func)(item);
stream.consume(self.child.clone());
self.child.borrow().is_some()
}
}
impl<C, T> Consumer<T> for Rc<RefCell<Option<C>>>
where C: Consumer<T>
{
fn emit(&mut self, item: T) -> bool {
let mut consumer = self.borrow_mut();
if let Some(r... | {
return false;
} | conditional_block |
moves-based-on-type-no-recursive-stack-closure.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut x = Some(~"hello");
do conspirator |f, writer| {
if writer {
x = None;
} else {
match x {
Some(ref msg) => {
(f.c)(f, true);
printfln!(msg);
},
None => fail!("oops"),
... | innocent_looking_victim | identifier_name |
moves-based-on-type-no-recursive-stack-closure.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 ... |
}
}
fn conspirator(f: &fn(&R, bool)) {
let r = R {c: f};
f(&r, false) //~ ERROR use of moved value
}
fn main() { innocent_looking_victim() }
| {
match x {
Some(ref msg) => {
(f.c)(f, true);
printfln!(msg);
},
None => fail!("oops"),
}
} | conditional_block |
moves-based-on-type-no-recursive-stack-closure.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 ... | Some(ref msg) => {
(f.c)(f, true);
printfln!(msg);
},
None => fail!("oops"),
}
}
}
}
fn conspirator(f: &fn(&R, bool)) {
let r = R {c: f};
f(&r, false) //~ ERROR use of moved value
}
fn main() { inno... | if writer {
x = None;
} else {
match x { | random_line_split |
lib.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
fn prop(ExprWithMatching {e, s}: ExprWithMatching) -> bool {
use regex::bytes::Regex;
let re = Regex::new(&e.to_string()).unwrap();
let caps = re.captures(&s.as_bytes());
caps.unwrap().pos(0).unwrap().0 == 0
}
qc(prop as fn(ExprWithMatching) -> bool);
} | identifier_body | |
lib.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | for e in v.iter() {
sample_language(g, acc, e);
}
},
&Expr::Alternate(ref v) => {
let i = g.gen_range(0, v.len());
sample_language(g, acc, &v[i])
},
_ => panic!("zero-width assertions unsupported"),
}
}
fn remove_zero_w... | &Expr::Concat(ref v) => { | random_line_split |
lib.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | ;
let x: u32 = if g.gen_range(0, s1 + s0) < s0 {
g.gen_range(l0, h0 + 1)
} else {
g.gen_range(l1, h1 + 1)
};
assert!(low <= x && x <= high);
::std::char::from_u32(x).unwrap()
}
pub fn sample_language<G: Rng>(g: &mut G, acc: &mut Vec<char>, expr: &Expr) {
match expr {
&Ex... | {h1 - l1 + 1} | conditional_block |
lib.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <G: Rng>(g: &mut G, acc: &mut Vec<char>, expr: &Expr) {
match expr {
&Expr::Empty => (),
&Expr::Literal { ref chars, casei, } => {
if!casei || g.gen() {
acc.extend(chars.iter());
} else {
acc.extend(chars.iter().map(|&c| randomize_case(g, c)))
... | sample_language | identifier_name |
main.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/. */
//! The `servo` test application.
//!
//! Creates a `Browser` instance with a simple implementation of
//! the com... | if!self.browser.handle_events(vec![event]) {
return false;
}
if is_resize {
self.browser.repaint_synchronously()
}
true
}
}
#[cfg(target_os = "android")]
fn setup_logging() {
// Piping logs from stdout/stderr to logcat happens in android_injected_... | random_line_split | |
main.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/. */
//! The `servo` test application.
//!
//! Creates a `Browser` instance with a simple implementation of
//! the com... | (app: *mut ()) {
android_injected_glue::android_main2(app as *mut _, move |_, _| main());
}
| android_main | identifier_name |
main.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/. */
//! The `servo` test application.
//!
//! Creates a `Browser` instance with a simple implementation of
//! the com... | {
android_injected_glue::android_main2(app as *mut _, move |_, _| main());
} | identifier_body | |
supertypes.rs | use std::vec::Vec;
use analysis::rust_type::used_rust_type;
use analysis::namespaces;
use env::Env;
use super::general::StatusedTypeId;
use super::imports::Imports;
use library::TypeId;
pub fn | (env: &Env, type_id: TypeId, imports: &mut Imports) -> Vec<StatusedTypeId> {
let mut parents = Vec::new();
let gobject_id = env.library.find_type(0, "GObject.Object").unwrap();
for &super_tid in env.class_hierarchy.supertypes(type_id) {
// skip GObject, it's inherited implicitly
if super_ti... | analyze | identifier_name |
supertypes.rs | use std::vec::Vec;
use analysis::rust_type::used_rust_type;
use analysis::namespaces;
use env::Env;
use super::general::StatusedTypeId;
use super::imports::Imports;
use library::TypeId;
pub fn analyze(env: &Env, type_id: TypeId, imports: &mut Imports) -> Vec<StatusedTypeId> {
let mut parents = Vec::new();
let... | }
}
}
parents
} | } else {
let ns = &env.namespaces[super_tid.ns_id];
imports.add(&ns.crate_name, None);
imports.add(&ns.ffi_crate_name, None);
} | random_line_split |
supertypes.rs | use std::vec::Vec;
use analysis::rust_type::used_rust_type;
use analysis::namespaces;
use env::Env;
use super::general::StatusedTypeId;
use super::imports::Imports;
use library::TypeId;
pub fn analyze(env: &Env, type_id: TypeId, imports: &mut Imports) -> Vec<StatusedTypeId> {
let mut parents = Vec::new();
let... |
}
parents
}
| {
if let Ok(s) = used_rust_type(env, super_tid) {
if super_tid.ns_id == namespaces::MAIN {
imports.add(&s, None);
} else {
let ns = &env.namespaces[super_tid.ns_id];
imports.add(&ns.crate_name, None);
... | conditional_block |
supertypes.rs | use std::vec::Vec;
use analysis::rust_type::used_rust_type;
use analysis::namespaces;
use env::Env;
use super::general::StatusedTypeId;
use super::imports::Imports;
use library::TypeId;
pub fn analyze(env: &Env, type_id: TypeId, imports: &mut Imports) -> Vec<StatusedTypeId> | if super_tid.ns_id == namespaces::MAIN {
imports.add(&s, None);
} else {
let ns = &env.namespaces[super_tid.ns_id];
imports.add(&ns.crate_name, None);
imports.add(&ns.ffi_crate_name, None);
}
... | {
let mut parents = Vec::new();
let gobject_id = env.library.find_type(0, "GObject.Object").unwrap();
for &super_tid in env.class_hierarchy.supertypes(type_id) {
// skip GObject, it's inherited implicitly
if super_tid == gobject_id {
continue
}
let status = env.... | identifier_body |
lib.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub mod back {
pub use rustc_back::abi;
pub use rustc_back::archive;
pub use rustc_back::arm;
pub use rustc_back::mips;
pub use rustc_back::mipsel;
pub use rustc_back::rpath;
pub use rustc_back::svh;
pub use rustc_back::target_strs;
pub use rustc_back::x86;
pub use rustc_back::x... | pub use rustc::util; | random_line_split |
dst-deref.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 ... | {
ptr: Box<[usize]>
}
impl Deref for Arr {
type Target = [usize];
fn deref(&self) -> &[usize] {
&*self.ptr
}
}
pub fn foo(arr: &Arr) {
assert_eq!(arr.len(), 3);
let x: &[usize] = &**arr;
assert_eq!(x[0], 1);
assert_eq!(x[1], 2);
assert_eq!(x[2], 3);
}
fn main() {
// ... | Arr | identifier_name |
dst-deref.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 ... |
}
pub fn foo(arr: &Arr) {
assert_eq!(arr.len(), 3);
let x: &[usize] = &**arr;
assert_eq!(x[0], 1);
assert_eq!(x[1], 2);
assert_eq!(x[2], 3);
}
fn main() {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let a = Arr { ptr: Box::new([1, 2, 3]) };
foo(&a);
}
| {
&*self.ptr
} | identifier_body |
dst-deref.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 ... |
pub struct Arr {
ptr: Box<[usize]>
}
impl Deref for Arr {
type Target = [usize];
fn deref(&self) -> &[usize] {
&*self.ptr
}
}
pub fn foo(arr: &Arr) {
assert_eq!(arr.len(), 3);
let x: &[usize] = &**arr;
assert_eq!(x[0], 1);
assert_eq!(x[1], 2);
assert_eq!(x[2], 3);
}
fn m... | random_line_split | |
li_Seguidos.rs | <?xml version="1.0" encoding="UTF-8"?>
<WebElementEntity>
<description></description>
<name>li_Seguidos</name>
<tag></tag>
<elementGuidId>af9ff76e-0068-44d1-94ca-a6265eeda570</elementGuidId>
<selectorCollection>
<entry>
<key>XPATH</key>
<value>(.//*[normalize-space(text()) and nor... | 2
</value>
</webElementProperties>
<webElementProperties>
<isSelected>false</isSelected>
<matchCondition>equals</matchCondition>
<name>xpath</name>
<type>Main</type>
<value>/html[1]/body[@class="bg-light"]/div[@class="container-fluid"... | <value>
Seguidos
| random_line_split |
pull.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use bytes::Bytes;
use gotham::state::{FromState, State};
use gotham_derive::{StateData, StaticResponseExtender};
use serde::Deserialize;
u... | use crate::context::ServerContext;
use crate::errors::MononokeErrorExt;
use crate::handlers::{EdenApiMethod, HandlerInfo};
use crate::middleware::RequestContext;
use crate::utils::{cbor, get_repo, parse_wire_request};
#[derive(Debug, Deserialize, StateData, StaticResponseExtender)]
pub struct PullFastForwardParams {
... | use gotham_ext::error::HttpError;
use gotham_ext::response::BytesBody;
use mercurial_types::HgChangesetId;
use types::HgId;
| random_line_split |
pull.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use bytes::Bytes;
use gotham::state::{FromState, State};
use gotham_derive::{StateData, StaticResponseExtender};
use serde::Deserialize;
u... | (state: &mut State) -> Result<BytesBody<Bytes>, HttpError> {
let params = PullLazyParams::take_from(state);
state.put(HandlerInfo::new(¶ms.repo, EdenApiMethod::PullLazy));
let request = parse_wire_request::<WirePullLazyRequest>(state).await?;
let sctx = ServerContext::borrow_from(state);
let r... | pull_lazy | identifier_name |
pull.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use bytes::Bytes;
use gotham::state::{FromState, State};
use gotham_derive::{StateData, StaticResponseExtender};
use serde::Deserialize;
u... | dag_id: k.to_wire(),
hg_id: HgId::from(v.into_nodehash()).to_wire(),
})
.collect();
let wire_clone_data = WireCloneData {
flat_segments: clone_data
.flat_segments
.segments
.into_iter()
.collect::<Vec<_>>()
.to_wir... | {
let params = PullLazyParams::take_from(state);
state.put(HandlerInfo::new(¶ms.repo, EdenApiMethod::PullLazy));
let request = parse_wire_request::<WirePullLazyRequest>(state).await?;
let sctx = ServerContext::borrow_from(state);
let rctx = RequestContext::borrow_from(state).clone();
let h... | identifier_body |
closure.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 ... | abi::RustCall,
expected_sig);
let region = match fcx.anon_regions(expr.span, 1) {
Err(_) => {
fcx.ccx.tcx.sess.span_bug(expr.span,
"can't make anon regions here?!")
}
Ok(regions) => regions[0],
};
let closure_type = ... | {
let expr_def_id = ast_util::local_def(expr.id);
debug!("check_unboxed_closure kind={:?} expected_sig={}",
kind,
expected_sig.repr(fcx.tcx()));
let mut fn_ty = astconv::ty_of_closure(
fcx,
ast::Unsafety::Normal,
ast::Many,
// The `RegionTraitStore` a... | identifier_body |
closure.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 ... | {
match expected_ty.sty {
ty::ty_trait(ref object_type) => {
let trait_ref =
object_type.principal_trait_ref_with_self_ty(fcx.tcx(),
fcx.tcx().types.err);
deduce_unboxed_closure_expectations_from_trait_ref(f... |
fn deduce_unboxed_closure_expectations_from_expected_type<'a,'tcx>(
fcx: &FnCtxt<'a,'tcx>,
expected_ty: Ty<'tcx>)
-> Option<(ty::FnSig<'tcx>,ty::UnboxedClosureKind)> | random_line_split |
closure.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 ... | <'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
expr: &ast::Expr,
kind: ty::UnboxedClosureKind,
decl: &ast::FnDecl,
body: &ast::Block,
expected_sig: Option<ty::FnSig... | check_unboxed_closure | identifier_name |
webglshaderprecisionformat.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/. */
#![allow(dead_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::code... |
}
impl WebGLShaderPrecisionFormatMethods for WebGLShaderPrecisionFormat {
// https://www.khronos.org/registry/webgl/specs/1.0/#5.12.1
fn RangeMin(&self) -> i32 {
self.range_min
}
// https://www.khronos.org/registry/webgl/specs/1.0/#5.12.1
fn RangeMax(&self) -> i32 {
self.range_max... | {
reflect_dom_object(
Box::new(WebGLShaderPrecisionFormat::new_inherited(range_min, range_max, precision)),
window,
WebGLShaderPrecisionFormatBinding::Wrap)
} | identifier_body |
webglshaderprecisionformat.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/. */
#![allow(dead_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::code... | (window: &Window,
range_min: i32,
range_max: i32,
precision: i32) -> DomRoot<WebGLShaderPrecisionFormat> {
reflect_dom_object(
Box::new(WebGLShaderPrecisionFormat::new_inherited(range_min, range_max, precision)),
window,
WebGLShade... | new | identifier_name |
webglshaderprecisionformat.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/. */
#![allow(dead_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::code... | // https://www.khronos.org/registry/webgl/specs/1.0/#5.12.1
fn RangeMin(&self) -> i32 {
self.range_min
}
// https://www.khronos.org/registry/webgl/specs/1.0/#5.12.1
fn RangeMax(&self) -> i32 {
self.range_max
}
// https://www.khronos.org/registry/webgl/specs/1.0/#5.12.1
... | random_line_split | |
main.rs | // #![feature(plugin)]
// #![plugin(clippy)]
// #![deny(clippy)]
#[macro_use]
extern crate serde_derive;
extern crate docopt;
mod cli;
mod cmd;
mod rules;
mod yaml;
use std::fs::File;
use std::io;
#[warn(unused_imports)]
use std::io::prelude::*;
use cli::*;
use docopt::Docopt;
const VERSION: &'static str = env!("... |
None => show("Nothing to run"),
};
}
_ => {
let watches = Watches::from(&from_file(cli::watch::DEFAULT_FILENAME));
execute(WatchCommand::new(watches, args.flag_verbose));
}
}
}
fn execute<T: Command>(command: T) {
if let Err(err) = c... | {
let watches = Watches::new(rules::from_string(content, arg_command));
execute(WatchCommand::new(watches, args.flag_verbose));
} | conditional_block |
main.rs | // #![feature(plugin)]
// #![plugin(clippy)]
// #![deny(clippy)]
#[macro_use]
extern crate serde_derive;
extern crate docopt;
mod cli;
mod cmd;
mod rules;
mod yaml;
use std::fs::File;
use std::io;
#[warn(unused_imports)]
use std::io::prelude::*;
use cli::*;
use docopt::Docopt;
const VERSION: &'static str = env!("... | () {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
match args {
// Metainfo
Args { flag_v: true,.. } => show(VERSION),
Args { flag_h: true,.. } => show(USAGE),
// Commands
Args { cmd_init: true,.. } => ex... | main | identifier_name |
main.rs | // #![feature(plugin)]
// #![plugin(clippy)]
// #![deny(clippy)]
#[macro_use]
extern crate serde_derive;
extern crate docopt;
mod cli;
mod cmd;
mod rules;
mod yaml;
use std::fs::File;
use std::io;
#[warn(unused_imports)]
use std::io::prelude::*;
use cli::*;
use docopt::Docopt;
const VERSION: &'static str = env!("... |
fn show(text: &str) ->! {
println!("{}", text);
std::process::exit(0)
}
| {
let mut file = match File::open(filename) {
Ok(f) => f,
Err(err) => show(
format!(
"File {} cannot be opened. Cause: {}",
cli::watch::DEFAULT_FILENAME,
err
)
.as_str(),
),
};
let mut content = Stri... | identifier_body |
main.rs | // #![feature(plugin)]
// #![plugin(clippy)]
// #![deny(clippy)]
#[macro_use]
extern crate serde_derive;
extern crate docopt;
mod cli;
mod cmd;
mod rules;
mod yaml;
use std::fs::File;
use std::io;
#[warn(unused_imports)]
use std::io::prelude::*;
use cli::*;
use docopt::Docopt;
const VERSION: &'static str = env!("... | pub cmd_init: bool,
pub cmd_watch: bool,
pub cmd_run: bool,
pub arg_command: String,
pub arg_interval: u64,
// options
pub flag_c: bool,
pub flag_h: bool,
pub flag_v: bool,
pub flag_verbose: bool,
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.des... |
#[derive(Debug, Deserialize)]
pub struct Args {
// comand | random_line_split |
ifmt.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 ... | {
// Various edge cases without formats
t!(format!(""), "");
t!(format!("hello"), "hello");
t!(format!("hello {{"), "hello {");
// default formatters should work
t!(format!("{}", 1.0f32), "1");
t!(format!("{}", 1.0f64), "1");
t!(format!("{}", "a"), "a");
t!(format!("{}", "a".to_str... | in() | identifier_name |
ifmt.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 ... | t!(format!("{:+10.3}", 1.0f64), " +1.000");
t!(format!("{:+10.3}", -1.0f64), " -1.000");
t!(format!("{:e}", 1.2345e6f32), "1.2345e6");
t!(format!("{:e}", 1.2345e6f64), "1.2345e6");
t!(format!("{:E}", 1.2345e6f64), "1.2345E6");
t!(format!("{:.3e}", 1.2345e6f64), "1.234e6");
t!(format!... | t!(format!("{:.3}", 1.0f64), "1.000");
t!(format!("{:10.3}", 1.0f64), " 1.000"); | random_line_split |
ifmt.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 ... |
}
impl fmt::UpperHex for B {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write("adios".as_bytes())
}
}
impl fmt::Show for C {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad_integral(true, "☃", "123".as_bytes())
}
}
macro_rules! t(($a:expr, $b:expr) => { asser... | {
f.write("aloha".as_bytes())
} | identifier_body |
ls-files.rs | extern crate gitters;
extern crate rustc_serialize;
extern crate docopt;
#[macro_use]
extern crate lazy_static;
use docopt::Docopt;
use gitters::cli;
use gitters::index;
use std::env;
use std::path::{Path, PathBuf};
const USAGE: &'static str = "
ls-files - Show information about files in the index
Usage:
ls-files... | } else {
list_cached_files()
}
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
cli::exit_with(dispatch_for_args(&args))
} | list_other_files() | random_line_split |
ls-files.rs | extern crate gitters;
extern crate rustc_serialize;
extern crate docopt;
#[macro_use]
extern crate lazy_static;
use docopt::Docopt;
use gitters::cli;
use gitters::index;
use std::env;
use std::path::{Path, PathBuf};
const USAGE: &'static str = "
ls-files - Show information about files in the index
Usage:
ls-files... |
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
cli::exit_with(dispatch_for_args(&args))
}
| {
list_cached_files()
} | conditional_block |
ls-files.rs | extern crate gitters;
extern crate rustc_serialize;
extern crate docopt;
#[macro_use]
extern crate lazy_static;
use docopt::Docopt;
use gitters::cli;
use gitters::index;
use std::env;
use std::path::{Path, PathBuf};
const USAGE: &'static str = "
ls-files - Show information about files in the index
Usage:
ls-files... |
fn list_cached_files() -> cli::Result {
let index = try!(cli::wrap_with_status(index::Index::read(), 2));
for entry in index.entries {
println!("{}", try!(path_display(&entry.path)));
}
cli::success()
}
fn list_other_files() -> cli::Result {
let files = try!(cli::wrap_with_status(index::... | {
lazy_static! {
static ref CURRENT_DIR_PREFIX: PathBuf = env::current_dir().unwrap();
}
let relative_path =
try!(cli::wrap_with_status(path.strip_prefix(CURRENT_DIR_PREFIX.as_path()), 2));
Ok(relative_path.display().to_string())
} | identifier_body |
ls-files.rs | extern crate gitters;
extern crate rustc_serialize;
extern crate docopt;
#[macro_use]
extern crate lazy_static;
use docopt::Docopt;
use gitters::cli;
use gitters::index;
use std::env;
use std::path::{Path, PathBuf};
const USAGE: &'static str = "
ls-files - Show information about files in the index
Usage:
ls-files... | {
flag_o: bool,
}
fn path_display(path: &Path) -> Result<String, cli::Error> {
lazy_static! {
static ref CURRENT_DIR_PREFIX: PathBuf = env::current_dir().unwrap();
}
let relative_path =
try!(cli::wrap_with_status(path.strip_prefix(CURRENT_DIR_PREFIX.as_path()), 2));
Ok(relative_pa... | Args | identifier_name |
tests.rs | extern crate cge;
use cge::Network;
use cge::gene::Gene;
use cge::gene::GeneExtras::*;
use cge::Activation;
const TEST_GENOME: [Gene; 12] = [
Gene {
weight: 1.0,
id: 0,
variant: Neuron(0.0, 3)
},
Gene {
weight: 1.0,
id: 1,
variant: Neuron(0.0, 2)
},
... | () {
let network = Network::load_from_file("tests/foo.txt").unwrap();
let test_genome = TEST_GENOME.to_vec();
network.save_to_file("tests/bar.txt").unwrap();
let network = Network::load_from_file("tests/bar.txt").unwrap();
assert_eq!(network.size, 11);
assert!(equal(test_genome, network.genom... | test_write_file | identifier_name |
tests.rs | extern crate cge;
use cge::Network;
use cge::gene::Gene;
use cge::gene::GeneExtras::*;
use cge::Activation;
const TEST_GENOME: [Gene; 12] = [
Gene {
weight: 1.0,
id: 0,
variant: Neuron(0.0, 3)
},
Gene {
weight: 1.0,
id: 1,
variant: Neuron(0.0, 2)
},
... |
#[test]
fn test_read_file() {
let network = Network::load_from_file("tests/foo.txt").unwrap();
let test_genome = TEST_GENOME.to_vec();
assert_eq!(network.size, 11);
assert!(equal(test_genome, network.genome));
}
#[test]
fn test_write_file() {
let network = Network::load_from_file("tests/foo... | {
for i in 0..a.len() {
let ga = &a[i];
let gb = &b[i];
if ga.weight != gb.weight ||
ga.id != gb.id ||
ga.variant != gb.variant {
false;
}
}
true
} | identifier_body |
tests.rs | extern crate cge;
use cge::Network;
use cge::gene::Gene;
use cge::gene::GeneExtras::*;
use cge::Activation;
const TEST_GENOME: [Gene; 12] = [
Gene {
weight: 1.0,
id: 0,
variant: Neuron(0.0, 3)
},
Gene {
weight: 1.0,
id: 1,
variant: Neuron(0.0, 2)
},
... | id: 3,
variant: Forward
},
Gene {
weight: 1.0,
id: 0,
variant: Input(0.0)
},
Gene {
weight: 1.0,
id: 1,
variant: Input(0.0)
},
Gene {
weight: 1.0,
id: 0,
variant: Recurrent
},
Gene {
weight: 1... | weight: 1.0, | random_line_split |
tests.rs | extern crate cge;
use cge::Network;
use cge::gene::Gene;
use cge::gene::GeneExtras::*;
use cge::Activation;
const TEST_GENOME: [Gene; 12] = [
Gene {
weight: 1.0,
id: 0,
variant: Neuron(0.0, 3)
},
Gene {
weight: 1.0,
id: 1,
variant: Neuron(0.0, 2)
},
... |
}
true
}
#[test]
fn test_read_file() {
let network = Network::load_from_file("tests/foo.txt").unwrap();
let test_genome = TEST_GENOME.to_vec();
assert_eq!(network.size, 11);
assert!(equal(test_genome, network.genome));
}
#[test]
fn test_write_file() {
let network = Network::loa... | {
false;
} | conditional_block |
source_map.rs | //! This module contains utilities that work with the `SourceMap` from `libsyntax`/`syntex_syntax`.
//! This includes extension traits and methods for looking up spans and line ranges for AST nodes.
use rustc_span::{BytePos, Span};
use crate::comment::FindUncommented;
use crate::config::file_lines::LineRange;
use cra... | (&self, original: Span, needle: &str) -> Option<BytePos> {
self.opt_span_before(original, needle)
.map(|bytepos| bytepos + BytePos(needle.len() as u32))
}
fn opt_span_before(&self, original: Span, needle: &str) -> Option<BytePos> {
let snippet = self.span_to_snippet(original)?;
... | opt_span_after | identifier_name |
source_map.rs | //! This module contains utilities that work with the `SourceMap` from `libsyntax`/`syntex_syntax`.
//! This includes extension traits and methods for looking up spans and line ranges for AST nodes.
use rustc_span::{BytePos, Span};
use crate::comment::FindUncommented;
use crate::config::file_lines::LineRange;
use cra... |
fn opt_span_after(&self, original: Span, needle: &str) -> Option<BytePos> {
self.opt_span_before(original, needle)
.map(|bytepos| bytepos + BytePos(needle.len() as u32))
}
fn opt_span_before(&self, original: Span, needle: &str) -> Option<BytePos> {
let snippet = self.span_to_sn... | {
let snippet = self.span_to_snippet(original).unwrap();
let mut offset = 0;
while let Some(additional_offset) = snippet[offset..].find_uncommented(needle) {
offset += additional_offset + needle.len();
}
original.lo() + BytePos(offset as u32 - 1)
} | identifier_body |
source_map.rs | //! This module contains utilities that work with the `SourceMap` from `libsyntax`/`syntex_syntax`.
//! This includes extension traits and methods for looking up spans and line ranges for AST nodes.
use rustc_span::{BytePos, Span};
use crate::comment::FindUncommented;
use crate::config::file_lines::LineRange;
use cra... |
Some(original.lo() + BytePos(offset as u32))
}
} | }
fn opt_span_before(&self, original: Span, needle: &str) -> Option<BytePos> {
let snippet = self.span_to_snippet(original)?;
let offset = snippet.find_uncommented(needle)?; | random_line_split |
link.rs | use std::{cmp};
use prelude::*;
pub fn read_link(fs: &mut Filesystem, ino: u64) -> Result<Vec<u8>> {
let inode = try!(get_inode(fs, ino));
if inode.mode.file_type == FileType::Symlink {
read_link_data(fs, &inode)
} else {
Err(Error::new(format!("inode is not a symlink")))
}
}
pub fn is_fast_symlink(fs... | {
try!(truncate_inode_blocks(fs, inode, 0));
if data.len() <= 15 * 4 {
use std::iter;
let data_buf: Vec<u8> = data.iter().cloned().chain(iter::repeat(0))
.take(15 * 4).collect();
for i in 0..15 {
inode.block[i] = decode_u32(&data_buf[i*4..]);
}
inode.size = data.len() as u64;
try... | identifier_body | |
link.rs | use std::{cmp};
use prelude::*;
pub fn read_link(fs: &mut Filesystem, ino: u64) -> Result<Vec<u8>> {
let inode = try!(get_inode(fs, ino));
if inode.mode.file_type == FileType::Symlink {
read_link_data(fs, &inode)
} else {
Err(Error::new(format!("inode is not a symlink")))
}
}
pub fn is_fast_symlink(fs... | inode.size
} else {
try!(read_inode_data(fs, &inode, 0, &mut buffer[..]))
};
buffer.truncate(length as usize);
Ok(buffer)
}
pub fn write_link_data(fs: &mut Filesystem, inode: &mut Inode, data: &[u8]) -> Result<()> {
try!(truncate_inode_blocks(fs, inode, 0));
if data.len() <= 15 * 4 {
us... | if is_fast_symlink(fs, &inode) {
for i in 0..cmp::min(inode.block.len(), inode.size as usize / 4 + 1) {
encode_u32(inode.block[i], &mut buffer[4*i..]);
} | random_line_split |
link.rs | use std::{cmp};
use prelude::*;
pub fn read_link(fs: &mut Filesystem, ino: u64) -> Result<Vec<u8>> {
let inode = try!(get_inode(fs, ino));
if inode.mode.file_type == FileType::Symlink {
read_link_data(fs, &inode)
} else {
Err(Error::new(format!("inode is not a symlink")))
}
}
pub fn is_fast_symlink(fs... | (fs: &mut Filesystem, inode: &mut Inode, data: &[u8]) -> Result<()> {
try!(truncate_inode_blocks(fs, inode, 0));
if data.len() <= 15 * 4 {
use std::iter;
let data_buf: Vec<u8> = data.iter().cloned().chain(iter::repeat(0))
.take(15 * 4).collect();
for i in 0..15 {
inode.block[i] = decode_u32(&... | write_link_data | identifier_name |
link.rs | use std::{cmp};
use prelude::*;
pub fn read_link(fs: &mut Filesystem, ino: u64) -> Result<Vec<u8>> {
let inode = try!(get_inode(fs, ino));
if inode.mode.file_type == FileType::Symlink {
read_link_data(fs, &inode)
} else |
}
pub fn is_fast_symlink(fs: &Filesystem, inode: &Inode) -> bool {
if inode.mode.file_type!= FileType::Symlink {
return false
}
if inode.file_acl!= 0 {
inode.size_512 as u64 == fs.block_size() / 512
} else {
inode.size_512 == 0
}
}
pub fn read_link_data(fs: &mut Filesystem, inode: &Inode) -> ... | {
Err(Error::new(format!("inode is not a symlink")))
} | conditional_block |
stream_format.rs | //! A rustification of the `AudioStreamBasicDescription` type.
//!
//! Find the original `AudioStreamBasicDescription` reference [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Reference/CoreAudioDataTypesRef/#//apple_ref/c/tdef/AudioStreamBasicDescription).
use bindings::audio_unit as au;
use ... | mFormatFlags: flag,
mBytesPerPacket: bytes_per_packet,
mFramesPerPacket: FRAMES_PER_PACKET,
mBytesPerFrame: bytes_per_frame,
mChannelsPerFrame: channels_per_frame,
mBitsPerChannel: bits_per_channel,
mReserved: 0,
}
}
}
| {
let StreamFormat {
sample_rate,
flags,
sample_format,
channels_per_frame,
} = self;
let (format, maybe_flag) = AudioFormat::LinearPCM(flags).to_format_and_flag();
let flag = maybe_flag.unwrap_or(::std::u32::MAX -2147483647);
le... | identifier_body |
stream_format.rs | //! A rustification of the `AudioStreamBasicDescription` type.
//!
//! Find the original `AudioStreamBasicDescription` reference [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Reference/CoreAudioDataTypesRef/#//apple_ref/c/tdef/AudioStreamBasicDescription).
use bindings::audio_unit as au;
use ... | {
/// The number of frames of audio data per second used to represent a signal.
pub sample_rate: f64,
/// The sample format used to represent the audio data.
///
/// In OS X, Core Audio xpects audio data to be in native-endian, 32-bit floating-point,
/// linear PCM format.
///
/// iOS u... | StreamFormat | identifier_name |
stream_format.rs | //! A rustification of the `AudioStreamBasicDescription` type.
//!
//! Find the original `AudioStreamBasicDescription` reference [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Reference/CoreAudioDataTypesRef/#//apple_ref/c/tdef/AudioStreamBasicDescription).
use bindings::audio_unit as au;
use ... | ///
/// Seeing as `LinearPCM` data (the `AudioFormat` used by the `AudioUnit` API) implies a single
/// frame per packet, we can infer many of the fields in an ASBD from the sample type.
///
/// `bytes_per_packet` = size_of::<S>()
/// `bytes_per_frame` = size_of::<S>()
/// `frames_per_packet` = 1
/// `bits_per_channel`... | /// A representation of the AudioStreamBasicDescription specifically for use with the AudioUnit API.
///
/// By using a type specific to the audio unit API, we can remove a lot of unnecessary boilerplate
/// that is normally associated with the AudioStreamBasicDescription. | random_line_split |
token.rs |
}
#[deriving(Clone, Encodable, Decodable, Eq, TotalEq, Hash)]
/// For interpolation during macro expansion.
pub enum Nonterminal {
NtItem(@ast::Item),
NtBlock(P<ast::Block>),
NtStmt(@ast::Stmt),
NtPat( @ast::Pat),
NtExpr(@ast::Expr),
NtTy( P<ast::Ty>),
NtIdent(~ast::Ident, bool),
NtMe... | (t: &Token) -> bool {
match *t { BINOP(OR) | OROR => true, _ => false }
}
// Get the first "argument"
macro_rules! first {
( $first:expr, $( $remainder:expr, )* ) => ( $first )
}
// Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
macro_rules! last {
( $first:expr... | is_bar | identifier_name |
token.rs | ,
}
#[deriving(Clone, Encodable, Decodable, Eq, TotalEq, Hash)]
/// For interpolation during macro expansion.
pub enum Nonterminal {
NtItem(@ast::Item),
NtBlock(P<ast::Block>),
NtStmt(@ast::Stmt),
NtPat( @ast::Pat),
NtExpr(@ast::Expr),
NtTy( P<ast::Ty>),
NtIdent(~ast::Ident, bool),
NtM... | // Get the first "argument"
macro_rules! first {
( $first:expr, $( $remainder:expr, )* ) => ( $first )
}
// Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
macro_rules! last {
( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
( $first:expr... | pub fn is_bar(t: &Token) -> bool {
match *t { BINOP(OR) | OROR => true, _ => false }
}
| random_line_split |
token.rs | )"),
NtStmt(..) => f.pad("NtStmt(..)"),
NtPat(..) => f.pad("NtPat(..)"),
NtExpr(..) => f.pad("NtExpr(..)"),
NtTy(..) => f.pad("NtTy(..)"),
NtIdent(..) => f.pad("NtIdent(..)"),
NtMeta(..) => f.pad("NtMeta(..)"),
NtPath(..) => f.pad("NtPa... | {
// FIXME(pcwalton): This is a workaround for the incorrect signature
// of `BytesContainer`, which is itself a workaround for the lack of
// DST.
unsafe {
let this = self.get();
cast::transmute(this.container_as_bytes())
}
} | identifier_body | |
error.rs | //! IRC protocol errors using `failure`.
use thiserror::Error;
/// A `Result` type for IRC `ProtocolErrors`.
pub type Result<T, E = ProtocolError> = ::std::result::Result<T, E>;
/// An IRC protocol error.
#[derive(Debug, Error)]
pub enum ProtocolError {
/// An internal I/O error.
#[error("an io error occurre... | {
/// Invalid modifier used in a mode string (only + and - are valid).
#[error("invalid mode modifier: {}", modifier)]
InvalidModeModifier {
/// The invalid mode modifier.
modifier: char,
},
/// Missing modifier used in a mode string.
#[error("missing mode modifier")]
Missi... | ModeParseError | identifier_name |
error.rs | //! IRC protocol errors using `failure`.
use thiserror::Error;
/// A `Result` type for IRC `ProtocolErrors`.
pub type Result<T, E = ProtocolError> = ::std::result::Result<T, E>;
/// An IRC protocol error.
#[derive(Debug, Error)]
pub enum ProtocolError {
/// An internal I/O error.
#[error("an io error occurre... | }
}
/// Errors that occur when parsing messages.
#[derive(Debug, Error)]
pub enum MessageParseError {
/// The message was empty.
#[error("empty message")]
EmptyMessage,
/// The command was invalid (i.e. missing).
#[error("invalid command")]
InvalidCommand,
/// The mode string was malf... | ProtocolError::Io(e) | random_line_split |
destructors.rs | use cpp_core::{CppBox, CppDeletable, Ptr};
use moqt_core::{BaseHandle, HandleFactory};
#[test]
fn basic_destructors() {
unsafe {
let factory = HandleFactory::new();
assert_eq!(factory.counter(), 0);
let h1 = CppBox::new(factory.create());
let h2 = factory.create();
assert_e... | }
#[test]
fn virtual_destructors() {
unsafe {
let factory = HandleFactory::new();
assert_eq!(factory.counter(), 0);
let h1 = CppBox::new(factory.create_derived());
assert_eq!(factory.counter(), 2);
let h2 = factory.create_derived2();
assert_eq!(factory.counter(), 5)... | random_line_split | |
destructors.rs | use cpp_core::{CppBox, CppDeletable, Ptr};
use moqt_core::{BaseHandle, HandleFactory};
#[test]
fn basic_destructors() |
#[test]
fn virtual_destructors() {
unsafe {
let factory = HandleFactory::new();
assert_eq!(factory.counter(), 0);
let h1 = CppBox::new(factory.create_derived());
assert_eq!(factory.counter(), 2);
let h2 = factory.create_derived2();
assert_eq!(factory.counter(), 5);... | {
unsafe {
let factory = HandleFactory::new();
assert_eq!(factory.counter(), 0);
let h1 = CppBox::new(factory.create());
let h2 = factory.create();
assert_eq!(factory.counter(), 2);
drop(h1);
assert_eq!(factory.counter(), 1);
h2.delete();
asse... | identifier_body |
destructors.rs | use cpp_core::{CppBox, CppDeletable, Ptr};
use moqt_core::{BaseHandle, HandleFactory};
#[test]
fn | () {
unsafe {
let factory = HandleFactory::new();
assert_eq!(factory.counter(), 0);
let h1 = CppBox::new(factory.create());
let h2 = factory.create();
assert_eq!(factory.counter(), 2);
drop(h1);
assert_eq!(factory.counter(), 1);
h2.delete();
a... | basic_destructors | identifier_name |
main.rs | fn | () {
println!("{} days", 31);
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
println!("{subject} {verb} {object}",
object="the lazy dog",
subject="the quick brown fox",
verb="jumps over");
println!("{} of {:b} people know binary, the other half ... | main | identifier_name |
main.rs | fn main() {
println!("{} days", 31);
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
println!("{subject} {verb} {object}",
object="the lazy dog",
subject="the quick brown fox",
verb="jumps over");
println!("{} of {:b} people know binary, the othe... | println!("Pi is roughly {:.*}", 3, pi);
} | random_line_split | |
main.rs | fn main() |
// println!("This struct `{}` won't print...", Structure(3));
let pi = 3.141592;
println!("Pi is roughly {:.*}", 3, pi);
}
| {
println!("{} days", 31);
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
println!("{subject} {verb} {object}",
object="the lazy dog",
subject="the quick brown fox",
verb="jumps over");
println!("{} of {:b} people know binary, the other half don... | identifier_body |
error.rs | use std::convert::TryFrom;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct EvalErr {
pub pos: u32,
pub err: EvalErrType,
}
impl EvalErr {
pub fn | (pos: u32, err: EvalErrType) -> EvalErr {
EvalErr { pos, err }
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(u8)]
pub enum EvalErrType {
ScriptRetFalse = 0x00,
UnexpectedEOF = 0x01,
HeaderReadErr = 0x02,
InvalidEntryPoint = 0x03,
UnknownOp = 0x04,
UnknownFn = 0x05,
Unknown... | new | identifier_name |
error.rs | use std::convert::TryFrom;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct EvalErr {
pub pos: u32,
pub err: EvalErrType,
}
impl EvalErr {
pub fn new(pos: u32, err: EvalErrType) -> EvalErr {
EvalErr { pos, err }
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(u8)]
pub enum EvalErrType ... | t if t == Self::Arithmetic as u8 => Self::Arithmetic,
t if t == Self::InvalidAmount as u8 => Self::InvalidAmount,
_ => return Err(()),
})
}
} | random_line_split | |
error.rs | use std::convert::TryFrom;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct EvalErr {
pub pos: u32,
pub err: EvalErrType,
}
impl EvalErr {
pub fn new(pos: u32, err: EvalErrType) -> EvalErr |
}
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(u8)]
pub enum EvalErrType {
ScriptRetFalse = 0x00,
UnexpectedEOF = 0x01,
HeaderReadErr = 0x02,
InvalidEntryPoint = 0x03,
UnknownOp = 0x04,
UnknownFn = 0x05,
UnknownArgType = 0x06,
ArgDeserialization = 0x07,
InvalidItemOnStack = 0x08... | {
EvalErr { pos, err }
} | identifier_body |
format.rs | use std::fmt;
use std::cell::RefCell;
/// Format all iterator elements lazily, separated by `sep`.
///
/// The format value can only be formatted once, after that the iterator is
/// exhausted.
///
/// See [`.format_with()`](../trait.Itertools.html#method.format_with) for more information.
#[derive(Clone)]
pub struct ... |
format(elt, &mut |disp: &dyn fmt::Display| disp.fmt(f))?;
}
}
Ok(())
}
}
impl<'a, I> Format<'a, I>
where I: Iterator,
{
fn format<F>(&self, f: &mut fmt::Formatter, mut cb: F) -> fmt::Result
where F: FnMut(&I::Item, &mut fmt::Formatter) -> fmt::Result,
... | {
f.write_str(self.sep)?;
} | conditional_block |
format.rs | use std::fmt;
use std::cell::RefCell;
/// Format all iterator elements lazily, separated by `sep`.
///
/// The format value can only be formatted once, after that the iterator is
/// exhausted.
///
/// See [`.format_with()`](../trait.Itertools.html#method.format_with) for more information.
#[derive(Clone)]
pub struct ... | {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.format(f, fmt::$fmt_trait::fmt)
}
}
)*
}
}
impl_format!{Display Debug
UpperExp LowerExp UpperHex LowerHex Octal Binary Pointer} | ($($fmt_trait:ident)*) => {
$(
impl<'a, I> fmt::$fmt_trait for Format<'a, I>
where I: Iterator,
I::Item: fmt::$fmt_trait, | random_line_split |
format.rs | use std::fmt;
use std::cell::RefCell;
/// Format all iterator elements lazily, separated by `sep`.
///
/// The format value can only be formatted once, after that the iterator is
/// exhausted.
///
/// See [`.format_with()`](../trait.Itertools.html#method.format_with) for more information.
#[derive(Clone)]
pub struct ... |
impl<'a, I, F> fmt::Display for FormatWith<'a, I, F>
where I: Iterator,
F: FnMut(I::Item, &mut dyn FnMut(&dyn fmt::Display) -> fmt::Result) -> fmt::Result
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let (mut iter, mut format) = match self.inner.borrow_mut().take() {
... | {
Format {
sep: separator,
inner: RefCell::new(Some(iter)),
}
} | identifier_body |
format.rs | use std::fmt;
use std::cell::RefCell;
/// Format all iterator elements lazily, separated by `sep`.
///
/// The format value can only be formatted once, after that the iterator is
/// exhausted.
///
/// See [`.format_with()`](../trait.Itertools.html#method.format_with) for more information.
#[derive(Clone)]
pub struct ... | <F>(&self, f: &mut fmt::Formatter, mut cb: F) -> fmt::Result
where F: FnMut(&I::Item, &mut fmt::Formatter) -> fmt::Result,
{
let mut iter = match self.inner.borrow_mut().take() {
Some(t) => t,
None => panic!("Format: was already formatted once"),
};
if let So... | format | identifier_name |
migration_with_helper.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | }
fn main() {
perform_migration(migration_with_helper);
} | }
migrate_wallets(&helper);
// Call `MigrationHelper::finish` to merge changes to the database.
helper.finish().expect("Migration finish failed."); | random_line_split |
migration_with_helper.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | history_hash: history.object_hash(),
};
new_schema.wallets.put(&public_key, new_wallet);
}
if i % 1_000 == 999 {
println!("Processed {} wallets", i + 1);
}
}
}
fn migration_with_helper(db: Arc<dyn Database>) {
// Creating helper to p... | {
let old_schema = v1::Schema::new(helper.old_data());
let mut new_schema = v2::Schema::new(helper.new_data());
// Migrate wallets.
for (i, (public_key, wallet)) in old_schema.wallets.iter().enumerate() {
if wallet.username == "Eve" {
// We don't like Eves 'round these parts. Remove... | identifier_body |
migration_with_helper.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | else {
// Merkelize the wallet history.
let mut history = new_schema.histories.get(&public_key);
history.extend(&old_schema.histories.get(&public_key));
let new_wallet = v2::Wallet {
username: wallet.username,
balance: wallet.balance,
... | {
// We don't like Eves 'round these parts. Remove her transaction history
// and don't migrate the wallet.
helper
.new_data()
.create_tombstone(("histories", &public_key));
} | conditional_block |
migration_with_helper.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | () {
perform_migration(migration_with_helper);
}
| main | identifier_name |
htmlembedelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
| use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use html5ever_atoms::LocalName;
#[dom_struct]
pub struct HTMLEmbedElement {
htmlelement: HTMLElement
}
impl HTMLEmbedElement {
fn new_inherited(local_name: Local... | use dom::bindings::codegen::Bindings::HTMLEmbedElementBinding; | random_line_split |
htmlembedelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLEmbedElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str... | (local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLEmbedElement> {
Node::reflect_node(box HTMLEmbedElement::new_inherited(local_name, prefix, document),
document,
HTMLEmbedElementBinding::Wrap)
... | new | identifier_name |
htmlembedelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLEmbedElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str... |
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLEmbedElement> {
Node::reflect_node(box HTMLEmbedElement::new_inherited(local_name, prefix, document),
document,
... | {
HTMLEmbedElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document)
}
} | identifier_body |
bf.rs | use std::io;
enum Op {
Inc(isize),
Move(isize),
Loop(Box<[Op]>),
Print
}
use Op::*;
struct Tape {
pos: usize,
tape: Vec<isize>
}
impl Tape {
fn new() -> Tape { Tape { pos: 0, tape: vec![0] } }
fn | (&self) -> isize { self.tape[self.pos] }
fn getc(&self) -> char { self.get() as u8 as char }
fn inc(&mut self, x: isize) { self.tape[self.pos] += x; }
fn mov(&mut self, x: isize) {
self.pos = (self.pos as isize + x) as usize;
while self.pos >= self.tape.len() { self.tape.push(0); }
}
}
fn _run(program... | get | identifier_name |
bf.rs | use std::io;
enum Op {
Inc(isize),
Move(isize),
Loop(Box<[Op]>),
Print
}
use Op::*;
struct Tape {
pos: usize,
tape: Vec<isize>
}
impl Tape {
fn new() -> Tape { Tape { pos: 0, tape: vec![0] } }
fn get(&self) -> isize { self.tape[self.pos] }
fn getc(&self) -> char { self.get() as u8 as char }... |
struct Program {
ops: Box<[Op]>
}
impl Program {
fn new(code: String) -> Program { Program { ops: parse(&mut code.chars()) } }
fn run(&self) {
let mut tape = Tape::new();
_run(&self.ops, &mut tape);
}
}
fn main() {
use std::fs::File;
use std::path::Path;
use std::io::prelude::*;
use... | {
let mut buf = Vec::new();
while let Some(c) = it.next() {
buf.push( match c {
'+' => Inc(1),
'-' => Inc(-1),
'>' => Move(1),
'<' => Move(-1),
'.' => Print,
'[' => Loop(parse(it)),
']' => break,
_ => continu... | identifier_body |
bf.rs | use std::io;
enum Op {
Inc(isize),
Move(isize),
Loop(Box<[Op]>),
Print
}
use Op::*;
struct Tape {
pos: usize,
tape: Vec<isize>
}
impl Tape {
fn new() -> Tape { Tape { pos: 0, tape: vec![0] } }
fn get(&self) -> isize { self.tape[self.pos] }
fn getc(&self) -> char { self.get() as u8 as char }... | use std::fs::File;
use std::path::Path;
use std::io::prelude::*;
use std::env;
let arg1 = env::args().nth(1).unwrap();
let path = Path::new(&arg1);
let mut s = String::new();
let mut file = File::open(&path).unwrap();
file.read_to_string(&mut s).unwrap();
let program = Program::... | fn main() { | random_line_split |
resolve-error.rs | // aux-build:derive-foo.rs
// aux-build:derive-clona.rs
// aux-build:test-macros.rs
#[macro_use]
extern crate derive_foo;
#[macro_use]
extern crate derive_clona;
extern crate test_macros;
use test_macros::empty as bang_proc_macro;
use test_macros::empty_attr as attr_proc_macro;
macro_rules! FooWithLongNam {
() =... | ;
#[derive(Dlona)]
//~^ ERROR cannot find
//~| ERROR cannot find
struct B;
#[derive(attr_proc_macra)]
//~^ ERROR cannot find
//~| ERROR cannot find
struct C;
fn main() {
FooWithLongNama!();
//~^ ERROR cannot find
attr_proc_macra!();
//~^ ERROR cannot find
Dlona!();
//~^ ERROR cannot find
... | A | identifier_name |
resolve-error.rs | // aux-build:derive-foo.rs
// aux-build:derive-clona.rs
// aux-build:test-macros.rs
| #[macro_use]
extern crate derive_clona;
extern crate test_macros;
use test_macros::empty as bang_proc_macro;
use test_macros::empty_attr as attr_proc_macro;
macro_rules! FooWithLongNam {
() => {}
}
macro_rules! attr_proc_mac {
() => {}
}
#[derive(FooWithLongNan)]
//~^ ERROR cannot find
//~| ERROR cannot fin... | #[macro_use]
extern crate derive_foo; | random_line_split |
lib.rs | //! Top-level lib.rs for `cranelift_module`.
#![deny(missing_docs, trivial_numeric_casts, unused_extern_crates)]
#![warn(unused_import_braces)]
#![cfg_attr(feature = "std", deny(unstable_features))]
#![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../../clippy.toml")))]
#![cfg_attr(feature = "cargo-clippy", ... | pub const VERSION: &str = env!("CARGO_PKG_VERSION"); | random_line_split | |
fetcher.rs | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
}
| {
let request: ::http::request::Request<Vec<u8>> = request.try_into()?;
let request = request.map(fastly::Body::from);
let request: FastlyRequest = request.try_into()?;
let response: FastlyResponse = request
.send(self.backend_name)
.map_err(|e| Error::new(e).cont... | identifier_body |
fetcher.rs | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (&self, request: HttpRequest) -> Result<HttpResponse> {
let request: ::http::request::Request<Vec<u8>> = request.try_into()?;
let request = request.map(fastly::Body::from);
let request: FastlyRequest = request.try_into()?;
let response: FastlyResponse = request
.send(self.back... | fetch | identifier_name |
fetcher.rs | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | // limitations under the License.
use anyhow::{Error, Result};
use async_trait::async_trait;
use fastly::{Request as FastlyRequest, Response as FastlyResponse};
use std::convert::TryInto;
use sxg_rs::{
fetcher::Fetcher,
http::{HttpRequest, HttpResponse},
};
/// A [`Fetcher`] implemented by
/// [Fastly backend... | random_line_split | |
actionable.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use Widget;
use ffi;
use glib;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct Actionable(Object<ffi::GtkActionable>): Widget;
match fn {
get_type => || ffi::gtk_actionable_get_type(),
}
... | }
}
} | random_line_split | |
actionable.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use Widget;
use ffi;
use glib;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct Actionable(Object<ffi::GtkActionable>): Widget;
match fn {
get_type => || ffi::gtk_actionable_get_type(),
}
... |
//fn set_action_target(&self, format_string: &str, : /*Unknown conversion*//*Unimplemented*/Fundamental: VarArgs) {
// unsafe { TODO: call ffi::gtk_actionable_set_action_target() }
//}
fn set_action_target_value(&self, target_value: &glib::Variant) {
unsafe {
ffi::gtk_actionabl... | {
let action_name = action_name.into();
let action_name = action_name.to_glib_none();
unsafe {
ffi::gtk_actionable_set_action_name(self.to_glib_none().0, action_name.0);
}
} | identifier_body |
actionable.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use Widget;
use ffi;
use glib;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct Actionable(Object<ffi::GtkActionable>): Widget;
match fn {
get_type => || ffi::gtk_actionable_get_type(),
}
... | (&self) -> Option<glib::Variant> {
unsafe {
from_glib_none(ffi::gtk_actionable_get_action_target_value(self.to_glib_none().0))
}
}
fn set_action_name<'a, P: Into<Option<&'a str>>>(&self, action_name: P) {
let action_name = action_name.into();
let action_name = action... | get_action_target_value | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.