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 |
|---|---|---|---|---|
moves.rs | only the outermost expression that is needed. The
borrow checker and trans, for example, only care about the outermost
expressions that are moved. It is more efficient therefore just to
store those entries.
Sometimes though we want to know the variables that are moved (in
particular in the borrow checker). For thes... | (&self,
expr: @expr,
expr_mode: UseMode,
visitor: vt<VisitContext>) {
/*!
* Indicates that `expr` is used with a given mode. This will
* in turn trigger calls to the subcomponents of `expr`.
*/
debug!("use_expr(expr... | use_expr | identifier_name |
moves.rs | 's only the outermost expression that is needed. The
borrow checker and trans, for example, only care about the outermost
expressions that are moved. It is more efficient therefore just to
store those entries.
Sometimes though we want to know the variables that are moved (in
particular in the borrow checker). For th... | // We must do this first so that `arms_have_by_move_bindings`
// below knows which bindings are moves.
for arms.iter().advance |arm| {
self.consume_arm(arm, visitor);
}
// The discriminant may, in fact, be partially mov... | expr_match(discr, ref arms) => { | random_line_split |
moves.rs | span: span,
id: node_id,
(cx, v): (VisitContext,
vt<VisitContext>)) {
for decl.inputs.iter().advance |a| {
cx.use_pat(a.pat);
}
visit::visit_fn(fk, decl, body, span, id, (cx, v));
}
fn compute_mo... | {
//! Uses the argument.
self.consume_expr(arg_expr, visitor)
} | identifier_body | |
mod.rs | // Copyright (C) 2019 Ruben Gonzalez <rgonzalez@fluendo.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or dist... | {
gst::Element::register(
Some(plugin),
"claxondec",
gst::Rank::Marginal,
ClaxonDec::static_type(),
)
} | identifier_body | |
mod.rs | // Copyright (C) 2019 Ruben Gonzalez <rgonzalez@fluendo.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or dist... | } | random_line_split | |
mod.rs | // Copyright (C) 2019 Ruben Gonzalez <rgonzalez@fluendo.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or dist... | (plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
gst::Element::register(
Some(plugin),
"claxondec",
gst::Rank::Marginal,
ClaxonDec::static_type(),
)
}
| register | identifier_name |
synonym.rs | use std::collections::HashMap;
use std::collections::hash_map::{Entries, Keys};
use std::fmt::Show;
use std::hash::Hash;
use std::mem;
#[deriving(Clone)]
pub struct SynonymMap<K, V> {
vals: HashMap<K, V>,
syns: HashMap<K, K>,
}
impl<K: Eq + Hash, V> SynonymMap<K, V> {
pub fn new() -> SynonymMap<K, V> {
... | <'a>(&'a self) -> Keys<'a, K, V> {
self.vals.keys()
}
pub fn iter<'a>(&'a self) -> Entries<'a, K, V> {
self.vals.iter()
}
pub fn synonyms<'a>(&'a self) -> Entries<'a, K, K> {
self.syns.iter()
}
pub fn find<'a>(&'a self, k: &K) -> Option<&'a V> {
self.with_key(k... | keys | identifier_name |
synonym.rs | use std::collections::HashMap;
use std::collections::hash_map::{Entries, Keys};
use std::fmt::Show;
use std::hash::Hash;
use std::mem;
#[deriving(Clone)]
pub struct SynonymMap<K, V> {
vals: HashMap<K, V>,
syns: HashMap<K, K>,
}
impl<K: Eq + Hash, V> SynonymMap<K, V> {
pub fn new() -> SynonymMap<K, V> {
... | if self.syns.contains_key(k) {
self.vals.find_mut(&self.syns[*k])
} else {
self.vals.find_mut(k)
}
}
pub fn swap(&mut self, k: K, mut new: V) -> Option<V> {
if self.syns.contains_key(&k) {
let old = self.vals.find_mut(&k).unwrap();
... | pub fn find_mut<'a>(&'a mut self, k: &K) -> Option<&'a mut V> { | random_line_split |
synonym.rs | use std::collections::HashMap;
use std::collections::hash_map::{Entries, Keys};
use std::fmt::Show;
use std::hash::Hash;
use std::mem;
#[deriving(Clone)]
pub struct SynonymMap<K, V> {
vals: HashMap<K, V>,
syns: HashMap<K, K>,
}
impl<K: Eq + Hash, V> SynonymMap<K, V> {
pub fn new() -> SynonymMap<K, V> {
... | else {
self.vals.find_mut(k)
}
}
pub fn swap(&mut self, k: K, mut new: V) -> Option<V> {
if self.syns.contains_key(&k) {
let old = self.vals.find_mut(&k).unwrap();
mem::swap(old, &mut new);
Some(new)
} else {
self.vals.swap(k,... | {
self.vals.find_mut(&self.syns[*k])
} | conditional_block |
synonym.rs | use std::collections::HashMap;
use std::collections::hash_map::{Entries, Keys};
use std::fmt::Show;
use std::hash::Hash;
use std::mem;
#[deriving(Clone)]
pub struct SynonymMap<K, V> {
vals: HashMap<K, V>,
syns: HashMap<K, K>,
}
impl<K: Eq + Hash, V> SynonymMap<K, V> {
pub fn new() -> SynonymMap<K, V> {
... |
}
| {
try!(self.vals.fmt(f));
write!(f, " (synomyns: {})", self.syns.to_string())
} | identifier_body |
link.rs | // Copyright 2014 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... |
#[cfg(feature = "glfw-sys")]
#[link(name = "glfw3", kind = "static")]
extern {}
#[cfg(not(feature = "glfw-sys"))]
// leaving off `kind = static` allows for the specification of a dynamic library if desired
#[link(name = "glfw3")]
extern {}
#[cfg(target_os="linux")]
#[link(name = "X11")]
#[link(name = "GL")]
#[link(n... | random_line_split | |
mod.rs | use std::collections::HashSet;
use conllx::Token;
use failure::{format_err, Error};
mod dependency;
pub use self::dependency::{Dependency, DependencySet}; |
mod parser_state;
pub use self::parser_state::ParserState;
mod trans_system;
pub use self::trans_system::{AttachmentAddr, Transition, TransitionLookup, TransitionSystem};
pub fn sentence_to_dependencies(sentence: &[Token]) -> Result<DependencySet, Error> {
let mut dependencies = HashSet::new();
for (idx, to... | random_line_split | |
mod.rs | use std::collections::HashSet;
use conllx::Token;
use failure::{format_err, Error};
mod dependency;
pub use self::dependency::{Dependency, DependencySet};
mod parser_state;
pub use self::parser_state::ParserState;
mod trans_system;
pub use self::trans_system::{AttachmentAddr, Transition, TransitionLookup, Transitio... | {
let mut dependencies = HashSet::new();
for (idx, token) in sentence.iter().enumerate() {
let head = token
.head()
.ok_or_else(|| format_err!("Token {} has no head", idx))?;
let head_rel = token
.head_rel()
.ok_or_else(|| format_err!("Token {} ha... | identifier_body | |
mod.rs | use std::collections::HashSet;
use conllx::Token;
use failure::{format_err, Error};
mod dependency;
pub use self::dependency::{Dependency, DependencySet};
mod parser_state;
pub use self::parser_state::ParserState;
mod trans_system;
pub use self::trans_system::{AttachmentAddr, Transition, TransitionLookup, Transitio... | (sentence: &[Token]) -> Result<DependencySet, Error> {
let mut dependencies = HashSet::new();
for (idx, token) in sentence.iter().enumerate() {
let head = token
.head()
.ok_or_else(|| format_err!("Token {} has no head", idx))?;
let head_rel = token
.head_rel()
... | sentence_to_dependencies | identifier_name |
htmlcanvaselement.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 base64;
use canvas_traits::canvas::{CanvasMsg, FromScriptMsg};
use dom::attr::Attr;
use dom::bindings::cell::D... |
#[allow(unsafe_code)]
pub fn get_or_init_webgl_context(&self,
cx: *mut JSContext,
attrs: Option<HandleValue>) -> Option<Root<WebGLRenderingContext>> {
if self.context.borrow().is_none() {
let window = window_from_node(self);... | {
if self.context.borrow().is_none() {
let window = window_from_node(self);
let size = self.get_size();
let context = CanvasRenderingContext2D::new(window.upcast::<GlobalScope>(), self, size);
*self.context.borrow_mut() = Some(CanvasContext::Context2d(JS::from_ref... | identifier_body |
htmlcanvaselement.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 base64;
use canvas_traits::canvas::{CanvasMsg, FromScriptMsg};
use dom::attr::Attr;
use dom::bindings::cell::D... | }
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl
unsafe fn ToDataURL(&self,
_context: *mut JSContext,
_mime_type: Option<DOMString>,
_arguments: Vec<HandleValue>) -> Fallible<DOMString> {
// Step... | random_line_split | |
htmlcanvaselement.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 base64;
use canvas_traits::canvas::{CanvasMsg, FromScriptMsg};
use dom::attr::Attr;
use dom::bindings::cell::D... |
}
pub fn get_size(&self) -> Size2D<i32> {
Size2D::new(self.Width() as i32, self.Height() as i32)
}
pub fn origin_is_clean(&self) -> bool {
match *self.context.borrow() {
Some(CanvasContext::Context2d(ref context)) => context.origin_is_clean(),
_ => true,
... | {
match *context {
CanvasContext::Context2d(ref context) => context.set_bitmap_dimensions(size),
CanvasContext::WebGL(ref context) => context.recreate(size),
}
} | conditional_block |
htmlcanvaselement.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 base64;
use canvas_traits::canvas::{CanvasMsg, FromScriptMsg};
use dom::attr::Attr;
use dom::bindings::cell::D... | (&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH),
&local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT),
_ => self.super_type().unwrap().parse_plain_attribut... | parse_plain_attribute | identifier_name |
variant.rs | use vtable::VTable;
use variant_ref::VariantRef;
use variant_ref_mut::VariantRefMut;
use std::any::{Any, TypeId};
use std::fmt::{Debug, Display, Error as FmtError, Formatter};
use std::ops::Deref;
pub struct Variant<'a> {
pub data: *mut (),
pub vtable: &'a VTable,
}
impl<'a> Variant<'a> {
pub fn new<T: Any... | (&self) -> &VariantRef<'a> {
unsafe { &*(self as *const _ as *const VariantRef<'a>) }
}
}
impl<'a> AsMut<VariantRefMut<'a>> for Variant<'a> {
fn as_mut(&mut self) -> &mut VariantRefMut<'a> {
unsafe { &mut *(self as *mut _ as *mut VariantRefMut<'a>) }
}
}
impl<'a> Clone for Variant<'a> {
fn clo... | as_ref | identifier_name |
variant.rs | use vtable::VTable;
use variant_ref::VariantRef;
use variant_ref_mut::VariantRefMut;
use std::any::{Any, TypeId};
use std::fmt::{Debug, Display, Error as FmtError, Formatter};
use std::ops::Deref;
pub struct Variant<'a> {
pub data: *mut (),
pub vtable: &'a VTable,
}
impl<'a> Variant<'a> {
pub fn new<T: Any... |
}
impl<'a> Clone for Variant<'a> {
fn clone(&self) -> Self {
(self.vtable.clone)(self.as_ref())
}
}
impl<'a> Drop for Variant<'a> {
fn drop(&mut self) {
(self.vtable.drop)(self)
}
}
impl<'a> Display for Variant<'a> {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
(self.v... | {
unsafe { &mut *(self as *mut _ as *mut VariantRefMut<'a>) }
} | identifier_body |
variant.rs | use vtable::VTable;
use variant_ref::VariantRef;
use variant_ref_mut::VariantRefMut;
use std::any::{Any, TypeId};
use std::fmt::{Debug, Display, Error as FmtError, Formatter};
use std::ops::Deref;
pub struct Variant<'a> {
pub data: *mut (),
pub vtable: &'a VTable,
}
impl<'a> Variant<'a> {
pub fn new<T: Any... | else {
None
}
}
#[inline]
pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
debug_assert!(self.is::<T>());
&*(self.data as *const T)
}
#[inline]
pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T {
debug_assert!(self.is::<T>());
&mut... | {
unsafe { Some(&mut *(self.data as *mut T)) }
} | conditional_block |
variant.rs | use vtable::VTable;
use variant_ref::VariantRef;
use variant_ref_mut::VariantRefMut;
use std::any::{Any, TypeId};
use std::fmt::{Debug, Display, Error as FmtError, Formatter};
use std::ops::Deref;
pub struct Variant<'a> {
pub data: *mut (),
pub vtable: &'a VTable,
}
impl<'a> Variant<'a> {
pub fn new<T: Any... | impl<'a> Debug for Variant<'a> {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
(self.vtable.debug)(self.as_ref(), f)
}
} | fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
(self.vtable.display)(self.as_ref(), f)
}
}
| random_line_split |
0-1.rs | // http://rosettacode.org/wiki/Knapsack_problem/0-1
use std::cmp::max;
use std::iter::repeat;
// This struct is used to store our items that we want in our knap-sack.
//
// Show is for displaying the fields.
// allow(dead_code) removes a dead code warning when the name of the struct is not
// used (as in this case h... | // maximize value
// subject to weights <= max_weight
fn knap_01_dp<'a>(xs: &[Want<'a>], max_weight: usize) -> Vec<Want<'a>> {
// Save this value, so we don't have to make repeated calls.
let xs_len = xs.len();
// Imagine we wrote a recursive function(item, max_weight) that returns a
// usiz... | random_line_split | |
0-1.rs | // http://rosettacode.org/wiki/Knapsack_problem/0-1
use std::cmp::max;
use std::iter::repeat;
// This struct is used to store our items that we want in our knap-sack.
//
// Show is for displaying the fields.
// allow(dead_code) removes a dead code warning when the name of the struct is not
// used (as in this case h... | //
// best_value(xs_len, max_weight) is equal to the maximum value that we
// can add to the bag.
//
// The problem with using this function is that it performs redudant
// calculations.
//
// The dynamic programming solution is to precompute all of the values we
// need and put them... | {
// Save this value, so we don't have to make repeated calls.
let xs_len = xs.len();
// Imagine we wrote a recursive function(item, max_weight) that returns a
// usize corresponding to the maximum cumulative value by considering a
// subset of items such that the combined weight <= max_weight.
... | identifier_body |
0-1.rs | // http://rosettacode.org/wiki/Knapsack_problem/0-1
use std::cmp::max;
use std::iter::repeat;
// This struct is used to store our items that we want in our knap-sack.
//
// Show is for displaying the fields.
// allow(dead_code) removes a dead code warning when the name of the struct is not
// used (as in this case h... |
}
return result;
}
#[cfg(not(test))]
fn main () {
let xs = knap_01_dp(ITEMS, 400);
// Print the items. We have to reverse the order because we solved the
// problem backward.
for i in xs.iter().rev() {
println!("Item: {}, Weight: {}, Value: {}", i.name, i.weight, i.value);
}
... | {
result.push(xs[i - 1]);
// we remove the weight of the object from the remaining weight
// we can add to the bag
left_weight -= xs[i - 1].weight;
} | conditional_block |
0-1.rs | // http://rosettacode.org/wiki/Knapsack_problem/0-1
use std::cmp::max;
use std::iter::repeat;
// This struct is used to store our items that we want in our knap-sack.
//
// Show is for displaying the fields.
// allow(dead_code) removes a dead code warning when the name of the struct is not
// used (as in this case h... | () {
let xs = knap_01_dp(ITEMS, 400);
// Print the items. We have to reverse the order because we solved the
// problem backward.
for i in xs.iter().rev() {
println!("Item: {}, Weight: {}, Value: {}", i.name, i.weight, i.value);
}
// Print the sum of weights.
let weights = xs.iter... | main | identifier_name |
mod.rs | extern crate time;
extern crate url;
extern crate rand;
use self::url::{FORM_URLENCODED_ENCODE_SET, utf8_percent_encode};
use self::time::now_utc;
use self::rand::{OsRng, Rng};
use std::fmt;
pub mod session;
pub mod temporary_credentials;
#[derive(Copy, Debug, PartialEq, Eq, Clone)]
#[unstable]
pub enum HTTPMethod {... |
#[test]
fn generate_nonce_unique(){
let mut nonces = Vec::new();
for _ in 0..1000 {
nonces.push(generate_nonce())
}
let len = nonces.len();
nonces.dedup();
assert_eq!(len, nonces.len());
}
}
| {
let data = vec!["alpha".to_string()];
assert_eq!(concat(data.as_slice(), "&"), "alpha".to_string())
} | identifier_body |
mod.rs | extern crate time;
extern crate url;
extern crate rand;
use self::url::{FORM_URLENCODED_ENCODE_SET, utf8_percent_encode};
use self::time::now_utc;
use self::rand::{OsRng, Rng};
use std::fmt;
pub mod session;
pub mod temporary_credentials;
#[derive(Copy, Debug, PartialEq, Eq, Clone)]
#[unstable]
pub enum HTTPMethod {... | pub trait BaseString {
/// Returns a base string URI, ecnoded with [RFC3986]. This gets used to
/// generate the `oauth_signature`. It takes a different path dependent
/// on the signature type
fn get_base_string(&self, method: HTTPMethod, base_url: &str, data: Vec<(&str, &str)>) -> String {
// ... | random_line_split | |
mod.rs | extern crate time;
extern crate url;
extern crate rand;
use self::url::{FORM_URLENCODED_ENCODE_SET, utf8_percent_encode};
use self::time::now_utc;
use self::rand::{OsRng, Rng};
use std::fmt;
pub mod session;
pub mod temporary_credentials;
#[derive(Copy, Debug, PartialEq, Eq, Clone)]
#[unstable]
pub enum HTTPMethod {... | (data: &[String], sep : &str) -> String {
match data {
[] => String::new(),
[ref param] => format!("{}", param),
[ref param, rest..] => format!("{}{}{}", param, sep, concat(rest, sep))
}
}
#[cfg(test)]
mod test {
use super::{concat, generate_nonce};
#[tes... | concat | identifier_name |
mod.rs | pub use self::connected::{Connected, AutocommitOff, AutocommitOn, AutocommitMode};
pub use self::hdbc_wrapper::HDbcWrapper;
pub use self::unconnected::Unconnected;
use super::*;
use sys::*;
use std::ops::DerefMut;
mod connected;
mod unconnected;
mod hdbc_wrapper;
/// A `DataSource` is used to query and manipulate a d... | (mut self) -> Return<DataSource<'env, Unconnected<'env>>, Connection<'env, AC>> {
match self.handle.disconnect() {
Success(()) => Success(self.transit()),
Info(()) => Info(self.transit()),
Error(()) => Error(self.transit()),
}
}
/// `true` if the data source ... | disconnect | identifier_name |
mod.rs | pub use self::connected::{Connected, AutocommitOff, AutocommitOn, AutocommitMode};
pub use self::hdbc_wrapper::HDbcWrapper;
pub use self::unconnected::Unconnected;
use super::*;
use sys::*;
use std::ops::DerefMut;
mod connected;
mod unconnected;
mod hdbc_wrapper;
/// A `DataSource` is used to query and manipulate a d... | /// See [Connection Handles in the ODBC Reference][1]
/// [1]: https://docs.microsoft.com/sql/odbc/reference/develop-app/connection-handles
#[derive(Debug)]
pub struct DataSource<'env, S: HDbcWrapper<'env> = Unconnected<'env>> {
/// Connection handle. Either `HDbc` for `Unconnected` or `Connected` for `Connected`.
... | /// in a new binding which will be of type `DataSource::<'env, Connected<'env>>`.
/// | random_line_split |
mod.rs | pub use self::connected::{Connected, AutocommitOff, AutocommitOn, AutocommitMode};
pub use self::hdbc_wrapper::HDbcWrapper;
pub use self::unconnected::Unconnected;
use super::*;
use sys::*;
use std::ops::DerefMut;
mod connected;
mod unconnected;
mod hdbc_wrapper;
/// A `DataSource` is used to query and manipulate a d... |
}
impl<'env> Connection<'env, AutocommitOff> {
/// Set autocommit mode on, per ODBC spec triggers implicit commit of any running transaction
pub fn enable_autocommit(mut self) -> Return<Connection<'env, AutocommitOn>, Self> {
match self.handle.set_autocommit(true) {
Success(_) => Success(s... | {
self.handle.is_read_only()
} | identifier_body |
gradient.rs | extern crate meta_diff;
fn | (nodes_before: usize, nodes_after: usize, source: &str){
let result = meta_diff::core::parseMetaFile(source);
let mut graph = match result {
Ok(g) => g,
Err(msg) => {return assert!(false, "{}", msg);}
};
assert!(graph.len() == nodes_before, "Number of the initial graph nodes expected: {}, was: {}", nodes_... | grad_ok | identifier_name |
gradient.rs | extern crate meta_diff;
fn grad_ok(nodes_before: usize, nodes_after: usize, source: &str){
let result = meta_diff::core::parseMetaFile(source);
let mut graph = match result {
Ok(g) => g,
Err(msg) => {return assert!(false, "{}", msg);}
};
assert!(graph.len() == nodes_before, "Number of the initial graph n... | end"
});
// parametarise_test!(grad_fail,
// ["Error at 2:7: Use of undefined variable \'d\'",
// "function [d] = mat(a,b)
// c = d + b * a';
// d = l2(c,0) * l1(c,0);
// end" ],
// ["Error at 3:28: Can not have a variable with name \'sin\' since it is a built in function",
// "function [L] = mat(@w,x,y)
// h... | 14,19,
"function [L] = mat(@w,x,y)
h = const(w*vertcat(x,1));
s = vdiag(w*horzcat(h,1));
L = l1(s-h,0); | random_line_split |
gradient.rs | extern crate meta_diff;
fn grad_ok(nodes_before: usize, nodes_after: usize, source: &str){
let result = meta_diff::core::parseMetaFile(source);
let mut graph = match result {
Ok(g) => g,
Err(msg) => {return assert!(false, "{}", msg);}
};
assert!(graph.len() == nodes_before, "Number of the initial graph n... | else {
match meta_diff::codegen::write_graphviz(&mut ::std::io::stdout(), &graph){
Ok(_) => (),
Err(msg) => assert!(false, "{}", msg)
}
println!("{}",graph);
assert!(false, "Number of the nodes after gradient - expected: {}, was: {}", nodes_after, graph.len())... | {
assert!(true);
} | conditional_block |
gradient.rs | extern crate meta_diff;
fn grad_ok(nodes_before: usize, nodes_after: usize, source: &str) | },
Err(msg) => assert!(false, "{}", msg)
}
}
// fn grad_fail(fail_msg: &str, source: &str){
// let result = meta_diff::core::parseMetaFile(source);
// match result {
// Ok(_) => {
// assert!(false, "Fail parsed, but should have failed.");
// }
// Err(msg) => {
// assert!(format!("{}",msg) ... | {
let result = meta_diff::core::parseMetaFile(source);
let mut graph = match result {
Ok(g) => g,
Err(msg) => {return assert!(false, "{}", msg);}
};
assert!(graph.len() == nodes_before, "Number of the initial graph nodes expected: {}, was: {}", nodes_before, graph.len());
match graph.direct_gradient(... | identifier_body |
convolve3x3.rs | /*
* Copyright (C) 2012 The Android Open Source Project
*
* 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 app... | uint32_t y2 = max((int32_t)y-1, 0);
float4 sum = convert_float4(rsGetElementAt_uchar4(gIn, x1, y1)) * gCoeffs[0];
sum += convert_float4(rsGetElementAt_uchar4(gIn, x, y1)) * gCoeffs[1];
sum += convert_float4(rsGetElementAt_uchar4(gIn, x2, y1)) * gCoeffs[2];
sum += convert_float4(rsGetElementAt_uchar... | uint32_t x2 = max((int32_t)x-1, 0);
uint32_t y1 = min((int32_t)y+1, gHeight-1); | random_line_split |
callee.rs | {
llfn: ValueRef,
}
pub struct MethodData {
llfn: ValueRef,
llself: ValueRef,
temp_cleanup: Option<ValueRef>,
self_ty: ty::t,
self_mode: ty::SelfMode,
}
pub enum CalleeData {
Closure(Datum),
Fn(FnData),
Method(MethodData)
}
pub struct Callee {
bcx: block,
data: CalleeData... | FnData | identifier_name | |
callee.rs | for impls.
// This doesn't actually work if the trait has param bounds,
// but it does allow us to survive the case when it does not.
let trait_ref = ty::impl_trait_ref(bcx.tcx(), impl_id).get();
@vec::from_elem(trait_ref.substs.tps.len(), @~[])
}
}
fn resolve_default_method_vtable... | type_params,
None);
let new_llval;
match callee.data {
Fn(fn_data) => {
let substituted = ty::subst_tps(callee.bcx.tcx(),
... | trans_fn_ref_with_vtables_to_callee(bcx, did, 0, | random_line_split |
callee.rs | impls.
// This doesn't actually work if the trait has param bounds,
// but it does allow us to survive the case when it does not.
let trait_ref = ty::impl_trait_ref(bcx.tcx(), impl_id).get();
@vec::from_elem(trait_ref.substs.tps.len(), @~[])
}
}
fn resolve_default_method_vtables(bc... |
}
} else {
must_monomorphise = false;
}
// Create a monomorphic verison of generic functions
if must_monomorphise {
// Should be either intra-crate or inlined.
assert_eq!(def_id.crate, ast::local_crate);
let (val, must_cast) =
monomorphize::monomorp... | {
must_monomorphise = false;
} | conditional_block |
cabi_mips.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... |
fn coerce_to_int(size: uint) -> ~[Type] {
let int_ty = Type::i32();
let mut args = ~[];
let mut n = size / 32;
while n > 0 {
args.push(int_ty);
n -= 1;
}
let r = size % 32;
if r > 0 {
unsafe {
args.push(Type::from_ref(llvm::LLVMIntTypeInContext(task_ll... | {
if ((align - 1 ) & offset) > 0 {
return Some(Type::i32());
}
return None;
} | identifier_body |
cabi_mips.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... | (size: uint) -> ~[Type] {
let int_ty = Type::i32();
let mut args = ~[];
let mut n = size / 32;
while n > 0 {
args.push(int_ty);
n -= 1;
}
let r = size % 32;
if r > 0 {
unsafe {
args.push(Type::from_ref(llvm::LLVMIntTypeInContext(task_llcx(), r as c_uint)... | coerce_to_int | identifier_name |
cabi_mips.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... | if ty.is_packed() {
let str_tys = ty.field_types();
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
let str_tys = ty.field_types();
let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t));
align(... | Pointer => 4,
Float => 4,
Double => 8,
Struct => { | random_line_split |
mod.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/. */
//! Computed values.
use {Atom, Namespace};
use context::QuirksMode;
use euclid::Size2D;
use font_metrics::{FontM... |
}
/// <url> | <none>
pub type UrlOrNone = Either<ComputedUrl, None_>;
| {
let string = match *self {
ComputedUrl::Valid(ref url) => url.as_str(),
ComputedUrl::Invalid(ref invalid_string) => invalid_string,
};
dest.write_str("url(")?;
string.to_css(dest)?;
dest.write_str(")")
} | identifier_body |
mod.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/. */
//! Computed values.
use {Atom, Namespace};
use context::QuirksMode;
use euclid::Size2D;
use font_metrics::{FontM... | else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.values.len(), Some(self.values.len()))
}
}
/// A trait to represent the conversion between computed and specified values.
///
/// This trait is derivable with `#[derive(ToComputedValue)]`. The derived
/// im... | {
let ret = next.to_computed_value(self.cx);
self.values = rest;
Some(ret)
} | conditional_block |
mod.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/. */
//! Computed values.
use {Atom, Namespace};
use context::QuirksMode;
use euclid::Size2D;
use font_metrics::{FontM... | (&self, context: &Context) -> Self::ComputedValue {
(self.0.to_computed_value(context), self.1.to_computed_value(context))
}
#[inline]
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
(A::from_computed_value(&computed.0), B::from_computed_value(&computed.1))
}
}
impl<T>... | to_computed_value | identifier_name |
mod.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/. */
//! Computed values.
use {Atom, Namespace};
use context::QuirksMode;
use euclid::Size2D;
use font_metrics::{FontM... |
#[inline]
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
Box::new(T::to_computed_value(self, context))
}
#[inline]
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
Box::new(T::from_computed_value(computed))
}
}
impl<T> ToComputedValue f... |
impl<T> ToComputedValue for Box<T>
where T: ToComputedValue
{
type ComputedValue = Box<<T as ToComputedValue>::ComputedValue>; | random_line_split |
strings3.rs | // Ok, here are a bunch of values-- some are `Strings`, some are `&strs`. Your
// task is to call one of these two functions on each value depending on what
// you think each value is. That is, add either `string_slice` or `string`
// before the parentheses on each line. If you're right, it will compile!
fn string_sli... |
fn string(arg: String) { println!("{}", arg); }
fn main() {
string_slice("blue");
string("red".to_string());
string(String::from("hi"));
string("rust is fun!".to_owned());
string("nice weather".into());
string(format!("Interpolation {}", "Station"));
string_slice(&String::from("abc")[0..1]... | { println!("{}", arg); } | identifier_body |
strings3.rs | // Ok, here are a bunch of values-- some are `Strings`, some are `&strs`. Your
// task is to call one of these two functions on each value depending on what
// you think each value is. That is, add either `string_slice` or `string`
// before the parentheses on each line. If you're right, it will compile!
| string("red".to_string());
string(String::from("hi"));
string("rust is fun!".to_owned());
string("nice weather".into());
string(format!("Interpolation {}", "Station"));
string_slice(&String::from("abc")[0..1]);
string_slice(" hello there ".trim());
string("Happy Monday!".to_string().rep... | fn string_slice(arg: &str) { println!("{}", arg); }
fn string(arg: String) { println!("{}", arg); }
fn main() {
string_slice("blue"); | random_line_split |
strings3.rs | // Ok, here are a bunch of values-- some are `Strings`, some are `&strs`. Your
// task is to call one of these two functions on each value depending on what
// you think each value is. That is, add either `string_slice` or `string`
// before the parentheses on each line. If you're right, it will compile!
fn string_sli... | (arg: String) { println!("{}", arg); }
fn main() {
string_slice("blue");
string("red".to_string());
string(String::from("hi"));
string("rust is fun!".to_owned());
string("nice weather".into());
string(format!("Interpolation {}", "Station"));
string_slice(&String::from("abc")[0..1]);
str... | string | identifier_name |
mod.rs | Self::Utf8Error(Some(Box::new(e)))
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnexpectedBitWidth { expected, actual } => write!(
f,
"Error reading flexbuffer: Expected bitwidth: {:?}, foun... | return Err(Error::FlexbufferOutOfBounds);
}
let keys_offset_address = self.address - 3 * self.width.n_bytes();
let keys_width = {
let kw_addr = self.address - 2 * self.width.n_bytes();
let kw = read_usize(&self.buffer, kw_addr, self.width);
BitWidt... |
fn get_map_info(&self) -> Result<(usize, BitWidth), Error> {
self.expect_type(FlexBufferType::Map)?;
if 3 * self.width.n_bytes() >= self.address { | random_line_split |
mod.rs | Self::Utf8Error(Some(Box::new(e)))
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnexpectedBitWidth { expected, actual } => write!(
f,
"Error reading flexbuffer: Expected bitwidth: {:?}, found... | (&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// skips buffer field
f.debug_struct("Reader")
.field("fxb_type", &self.fxb_type)
.field("width", &self.width)
.field("address", &self.address)
.finish()
}
}
macro_rules! try_cast_fn {
($... | fmt | identifier_name |
mod.rs | Self::Utf8Error(Some(Box::new(e)))
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnexpectedBitWidth { expected, actual } => write!(
f,
"Error reading flexbuffer: Expected bitwidth: {:?}, found... | Err(Error::AlignmentError)
}
}
/// Returns the value of the reader if it is a boolean.
/// Otherwise Returns error.
pub fn get_bool(&self) -> Result<bool, Error> {
self.expect_type(FlexBufferType::Bool)?;
Ok(
self.buffer[self.address..self.address + self... | {
if self.flexbuffer_type().typed_vector_type() != T::VECTOR_TYPE.typed_vector_type() {
self.expect_type(T::VECTOR_TYPE)?;
}
if self.bitwidth().n_bytes() != std::mem::size_of::<T>() {
self.expect_bw(T::WIDTH)?;
}
let end = self.address + self.length() * st... | identifier_body |
issue-17233.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 ... | () {
assert_eq!(Y1, Y2);
assert_eq!(Y1, Y3);
assert_eq!(Y1, Y4);
}
| main | identifier_name |
issue-17233.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 ... | {
assert_eq!(Y1, Y2);
assert_eq!(Y1, Y3);
assert_eq!(Y1, Y4);
} | identifier_body | |
issue-17233.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 http://opensource.org/licenses/MIT>, at your
// option. This file... | random_line_split | |
build.rs | use std::path::Path;
use std::process::Command;
static AFL_SRC_PATH: &str = "AFLplusplus";
// https://github.com/rust-fuzz/afl.rs/issues/148
#[cfg(target_os = "macos")]
static AR_CMD: &str = "/usr/bin/ar";
#[cfg(not(target_os = "macos"))]
static AR_CMD: &str = "ar";
#[path = "src/common.rs"]
mod common;
fn main() {... | {
std::fs::copy(
Path::new(&AFL_SRC_PATH).join("afl-compiler-rt.o"),
common::object_file_path(),
)
.expect("Couldn't copy object file");
let status = Command::new(AR_CMD)
.arg("r")
.arg(common::archive_file_path())
.arg(common::object_file_path())
.status... | identifier_body | |
build.rs | use std::path::Path;
use std::process::Command;
static AFL_SRC_PATH: &str = "AFLplusplus";
// https://github.com/rust-fuzz/afl.rs/issues/148
#[cfg(target_os = "macos")]
static AR_CMD: &str = "/usr/bin/ar";
#[cfg(not(target_os = "macos"))]
static AR_CMD: &str = "ar";
#[path = "src/common.rs"]
mod common;
fn main() {... | () {
std::fs::copy(
Path::new(&AFL_SRC_PATH).join("afl-compiler-rt.o"),
common::object_file_path(),
)
.expect("Couldn't copy object file");
let status = Command::new(AR_CMD)
.arg("r")
.arg(common::archive_file_path())
.arg(common::object_file_path())
.status()... | build_afl_llvm_runtime | identifier_name |
build.rs | use std::path::Path;
use std::process::Command;
static AFL_SRC_PATH: &str = "AFLplusplus";
// https://github.com/rust-fuzz/afl.rs/issues/148
#[cfg(target_os = "macos")]
static AR_CMD: &str = "/usr/bin/ar";
#[cfg(not(target_os = "macos"))]
static AR_CMD: &str = "ar";
#[path = "src/common.rs"]
mod common;
fn main() {... | }
fn build_afl_llvm_runtime() {
std::fs::copy(
Path::new(&AFL_SRC_PATH).join("afl-compiler-rt.o"),
common::object_file_path(),
)
.expect("Couldn't copy object file");
let status = Command::new(AR_CMD)
.arg("r")
.arg(common::archive_file_path())
.arg(common::object_f... | random_line_split | |
colors.rs | use palette;
use palette::pixel::RgbPixel;
pub type Rgb = [f32; 3];
pub type Srgb = [f32; 3];
fn normalize(color: Srgb) -> Srgb {
[color[0] / 255.0, color[1] / 255.0, color[2] / 255.0]
}
fn srgb_to_rgb(color: Srgb) -> Rgb {
let srgb = palette::pixel::Srgb::new(color[0], color[1], color[2]);
let rgb = pal... | (color: &str) -> Srgb {
let rgba = palette::named::from_str(color)
.expect(&format!("unknown color: {}", color))
.to_rgba();
srgb_to_rgb([rgba.0, rgba.1, rgba.2])
}
lazy_static! {
pub static ref BLACK: Rgb = str_to_rgb("black");
pub static ref CYAN: Rgb = str_to_rgb("cyan");
... | str_to_rgb | identifier_name |
colors.rs | use palette;
use palette::pixel::RgbPixel;
pub type Rgb = [f32; 3];
pub type Srgb = [f32; 3];
fn normalize(color: Srgb) -> Srgb {
[color[0] / 255.0, color[1] / 255.0, color[2] / 255.0]
}
fn srgb_to_rgb(color: Srgb) -> Rgb {
let srgb = palette::pixel::Srgb::new(color[0], color[1], color[2]);
let rgb = pal... |
lazy_static! {
pub static ref BLACK: Rgb = str_to_rgb("black");
pub static ref CYAN: Rgb = str_to_rgb("cyan");
pub static ref BROWN: Rgb = str_to_rgb("saddlebrown");
pub static ref BLUE: Rgb = str_to_rgb("blue");
pub static ref RED: Rgb = str_to_rgb("red");
pub static re... | } | random_line_split |
colors.rs | use palette;
use palette::pixel::RgbPixel;
pub type Rgb = [f32; 3];
pub type Srgb = [f32; 3];
fn normalize(color: Srgb) -> Srgb {
[color[0] / 255.0, color[1] / 255.0, color[2] / 255.0]
}
fn srgb_to_rgb(color: Srgb) -> Rgb {
let srgb = palette::pixel::Srgb::new(color[0], color[1], color[2]);
let rgb = pal... |
lazy_static! {
pub static ref BLACK: Rgb = str_to_rgb("black");
pub static ref CYAN: Rgb = str_to_rgb("cyan");
pub static ref BROWN: Rgb = str_to_rgb("saddlebrown");
pub static ref BLUE: Rgb = str_to_rgb("blue");
pub static ref RED: Rgb = str_to_rgb("red");
pub static r... | {
let rgba = palette::named::from_str(color)
.expect(&format!("unknown color: {}", color))
.to_rgba();
srgb_to_rgb([rgba.0, rgba.1, rgba.2])
} | identifier_body |
trait-bounds-sugar.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 c(x: ~Foo:Share) {
a(x); //~ ERROR expected bounds `Send`
}
fn d(x: &'static Foo:Share) {
b(x); //~ ERROR expected bounds `'static`
}
fn main() {}
| { // should be same as &'static Foo:'static
} | identifier_body |
trait-bounds-sugar.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 ... | (_x: ~Foo:Send) {
}
fn b(_x: &'static Foo) { // should be same as &'static Foo:'static
}
fn c(x: ~Foo:Share) {
a(x); //~ ERROR expected bounds `Send`
}
fn d(x: &'static Foo:Share) {
b(x); //~ ERROR expected bounds `'static`
}
fn main() {}
| a | identifier_name |
trait-bounds-sugar.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 b(_x: &'static Foo) { // should be same as &'static Foo:'static
}
fn c(x: ~Foo:Share) {
a(x); //~ ERROR expected bounds `Send`
}
fn d(x: &'static Foo:Share) {
b(x); //~ ERROR expected bounds `'static`
}
fn main() {} | random_line_split | |
address-of.rs | // EMIT_MIR address_of.address_of_reborrow.SimplifyCfg-initial.after.mir
fn | () {
let y = &[0; 10];
let mut z = &mut [0; 10];
y as *const _;
y as *const [i32; 10];
y as *const dyn Send;
y as *const [i32];
y as *const i32; // This is a cast, not a coercion
let p: *const _ = y;
let p: *const [i32; 10] = y;
let p: *const dyn Send = y;
let p:... | address_of_reborrow | identifier_name |
address-of.rs | // EMIT_MIR address_of.address_of_reborrow.SimplifyCfg-initial.after.mir
fn address_of_reborrow() | let p: *const _ = z;
let p: *const [i32; 10] = z;
let p: *const dyn Send = z;
let p: *const [i32] = z;
z as *mut _;
z as *mut [i32; 10];
z as *mut dyn Send;
z as *mut [i32];
let p: *mut _ = z;
let p: *mut [i32; 10] = z;
let p: *mut dyn Send = z;
let p: *mut [i32] = z;
}... | {
let y = &[0; 10];
let mut z = &mut [0; 10];
y as *const _;
y as *const [i32; 10];
y as *const dyn Send;
y as *const [i32];
y as *const i32; // This is a cast, not a coercion
let p: *const _ = y;
let p: *const [i32; 10] = y;
let p: *const dyn Send = y;
let p: *c... | identifier_body |
address-of.rs | // EMIT_MIR address_of.address_of_reborrow.SimplifyCfg-initial.after.mir
fn address_of_reborrow() {
let y = &[0; 10];
let mut z = &mut [0; 10];
y as *const _;
y as *const [i32; 10];
y as *const dyn Send;
y as *const [i32];
y as *const i32; // This is a cast, not a coercion
... | let p: *mut _ = z;
let p: *mut [i32; 10] = z;
let p: *mut dyn Send = z;
let p: *mut [i32] = z;
}
// The normal borrows here should be preserved
// EMIT_MIR address_of.borrow_and_cast.SimplifyCfg-initial.after.mir
fn borrow_and_cast(mut x: i32) {
let p = &x as *const i32;
let q = &mut x as *cons... | z as *mut [i32; 10];
z as *mut dyn Send;
z as *mut [i32];
| random_line_split |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... | (
name: uint,
mut color: Color,
from_rendezvous: Receiver<CreatureInfo>,
to_rendezvous: Sender<CreatureInfo>,
to_rendezvous_log: Sender<String>
) {
let mut creatures_met = 0i32;
let mut evil_clones_met = 0;
let mut rendezvous = from_rendezvous.iter();
loop {
// ask for a pai... | creature | identifier_name |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... |
1 => {" one"}
2 => {" two"}
3 => {" three"}
4 => {" four"}
5 => {" five"}
6 => {" six"}
7 => {" seven"}
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected digits from 0 to 9...")}
}
}
struct Number(uint);
impl fmt::Show for Number ... | {" zero"} | conditional_block |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... | to_creature[fst_creature.name].send(snd_creature);
to_creature[snd_creature.name].send(fst_creature);
}
// tell each creature to stop
drop(to_creature);
// print each color in the set
println!("{}", show_color_list(set));
// print each creature's stats
drop(to_rendezvous_l... | let snd_creature = from_creatures.recv();
creatures_met += 2;
| random_line_split |
astar.rs | use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::{BinaryHeap, HashMap};
use std::hash::Hash;
use super::visit::{EdgeRef, GraphBase, IntoEdges, VisitMap, Visitable};
use crate::scored::MinScored;
use crate::algo::Measure;
/// \[Generic\] A* shortest path algorithm.
///
/// Computes th... | }
} | random_line_split | |
astar.rs | use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::{BinaryHeap, HashMap};
use std::hash::Hash;
use super::visit::{EdgeRef, GraphBase, IntoEdges, VisitMap, Visitable};
use crate::scored::MinScored;
use crate::algo::Measure;
/// \[Generic\] A* shortest path algorithm.
///
/// Computes th... | (&self, last: G::NodeId) -> Vec<G::NodeId> {
let mut path = vec![last];
let mut current = last;
while let Some(&previous) = self.came_from.get(¤t) {
path.push(previous);
current = previous;
}
path.reverse();
path
}
}
| reconstruct_path_to | identifier_name |
astar.rs | use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::{BinaryHeap, HashMap};
use std::hash::Hash;
use super::visit::{EdgeRef, GraphBase, IntoEdges, VisitMap, Visitable};
use crate::scored::MinScored;
use crate::algo::Measure;
/// \[Generic\] A* shortest path algorithm.
///
/// Computes th... |
fn reconstruct_path_to(&self, last: G::NodeId) -> Vec<G::NodeId> {
let mut path = vec![last];
let mut current = last;
while let Some(&previous) = self.came_from.get(¤t) {
path.push(previous);
current = previous;
}
path.reverse();
pat... | {
self.came_from.insert(node, previous);
} | identifier_body |
lib.rs | //! `gel` is an extension of sebcrozet's `nalgebra` crate, designed to facilitate OpenGL
//! mathematics.
extern crate num;
extern crate nalgebra;
extern crate glium;
extern crate rustc_serialize;
use std::mem;
use std::ptr;
use glium::program::BlockLayout;
use glium::uniforms::{
AsUniformValue,
UniformValue... | <N>(n: N) -> N
where N: FloatExt
{
n.degrees()
}
pub fn extend<T, N>(base: T, elem: N) -> T::Output
where T: Extend<N>
{
base.extend(elem)
}
pub fn truncate<T>(base: T) -> T::Output
where T: Truncate
{
base.truncate()
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! test_extend ... | degrees | identifier_name |
lib.rs | //! `gel` is an extension of sebcrozet's `nalgebra` crate, designed to facilitate OpenGL
//! mathematics.
extern crate num;
extern crate nalgebra;
extern crate glium;
extern crate rustc_serialize;
use std::mem;
use std::ptr;
use glium::program::BlockLayout;
use glium::uniforms::{
AsUniformValue,
UniformValue... |
pub fn aspect(&self) -> N {
self.mat.m22 / self.mat.m11
}
pub fn set_aspect(&mut self, aspect: N) {
self.mat.m11 = self.mat.m22 / aspect;
}
pub fn as_mat<'a>(&'a self) -> &'a Mat4<N> {
&self.mat
}
}
impl<N> Perspective<N>
where N: BaseFloat + Clone
{
pub fn ... | {
let one = N::one();
let two = one + one;
let tan_half_fov = (fov / two).tan();
let mut mat = Mat4::zero();
mat.m11 = one / (aspect * tan_half_fov);
mat.m22 = one / (tan_half_fov);
mat.m33 = -(zfar + znear) / (zfar - znear);
mat.m43 = -one;
mat... | identifier_body |
lib.rs | //! `gel` is an extension of sebcrozet's `nalgebra` crate, designed to facilitate OpenGL
//! mathematics.
extern crate num;
extern crate nalgebra;
extern crate glium;
extern crate rustc_serialize;
use std::mem;
use std::ptr;
use glium::program::BlockLayout;
use glium::uniforms::{
AsUniformValue,
UniformValue... | yaxis.x, yaxis.y, yaxis.z,
-zaxis.x, -zaxis.y, -zaxis.z);
let rotmat = unsafe {
Rot3::new_with_mat(mat)
};
let tx = -(camera.dot(&xaxis));
let ty = -(camera.dot(&yaxis));
let tz = camera.dot(&zaxis);
le... |
let mat = Mat3::new(xaxis.x, xaxis.y, xaxis.z, | random_line_split |
serial.rs | // Copyright Dan Schatzberg, 2015. This file is part of Genesis.
// Genesis is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
... | () -> bool {
ioport::inb(PORT_BASE + LINE_STATUS_REG) & LINE_STATUS_REG_THR_EMPTY!= 0
}
unsafe fn putc(c: u8) {
while!is_transmit_empty() {}
ioport::out(PORT_BASE + DATA_REG, c);
}
/// Write `str` to the Serial Port
pub unsafe fn write_str(s: &str) {
for c in s.bytes() {
putc(c);
}
}
| is_transmit_empty | identifier_name |
serial.rs | // Copyright Dan Schatzberg, 2015. This file is part of Genesis.
// Genesis is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
... | for c in s.bytes() {
putc(c);
}
} | random_line_split | |
serial.rs | // Copyright Dan Schatzberg, 2015. This file is part of Genesis.
// Genesis is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
... |
unsafe fn putc(c: u8) {
while!is_transmit_empty() {}
ioport::out(PORT_BASE + DATA_REG, c);
}
/// Write `str` to the Serial Port
pub unsafe fn write_str(s: &str) {
for c in s.bytes() {
putc(c);
}
}
| {
ioport::inb(PORT_BASE + LINE_STATUS_REG) & LINE_STATUS_REG_THR_EMPTY != 0
} | identifier_body |
to_device.rs | //! Common types for the Send-To-Device Messaging
//!
//! [send-to-device]: https://spec.matrix.org/v1.2/client-server-api/#send-to-device-messaging
use std::{
convert::TryFrom,
fmt::{Display, Formatter, Result as FmtResult},
};
use serde::{
de::{self, Unexpected},
Deserialize, Deserializer, Serialize... | <D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = ruma_serde::deserialize_cow_str(deserializer)?;
DeviceIdOrAllDevices::try_from(s.as_ref()).map_err(|_| {
de::Error::invalid_value(Unexpected::Str(&s), &"a valid device identifier or '*'")
... | deserialize | identifier_name |
to_device.rs | //! Common types for the Send-To-Device Messaging
//!
//! [send-to-device]: https://spec.matrix.org/v1.2/client-server-api/#send-to-device-messaging
use std::{
convert::TryFrom,
fmt::{Display, Formatter, Result as FmtResult},
};
use serde::{
de::{self, Unexpected},
Deserialize, Deserializer, Serialize... |
}
impl From<Box<DeviceId>> for DeviceIdOrAllDevices {
fn from(d: Box<DeviceId>) -> Self {
DeviceIdOrAllDevices::DeviceId(d)
}
}
impl TryFrom<&str> for DeviceIdOrAllDevices {
type Error = &'static str;
fn try_from(device_id_or_all_devices: &str) -> Result<Self, Self::Error> {
if devic... | {
match self {
DeviceIdOrAllDevices::DeviceId(device_id) => write!(f, "{}", device_id),
DeviceIdOrAllDevices::AllDevices => write!(f, "*"),
}
} | identifier_body |
to_device.rs | //! Common types for the Send-To-Device Messaging
//!
//! [send-to-device]: https://spec.matrix.org/v1.2/client-server-api/#send-to-device-messaging
use std::{
convert::TryFrom,
fmt::{Display, Formatter, Result as FmtResult},
};
use serde::{
de::{self, Unexpected},
Deserialize, Deserializer, Serialize... |
}
}
impl Serialize for DeviceIdOrAllDevices {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::DeviceId(device_id) => device_id.serialize(serializer),
Self::AllDevices => serializer.serialize_str("*"),
... | {
Ok(DeviceIdOrAllDevices::DeviceId(device_id_or_all_devices.into()))
} | conditional_block |
to_device.rs | //! Common types for the Send-To-Device Messaging
//!
//! [send-to-device]: https://spec.matrix.org/v1.2/client-server-api/#send-to-device-messaging
use std::{
convert::TryFrom,
fmt::{Display, Formatter, Result as FmtResult},
};
use serde::{
de::{self, Unexpected},
Deserialize, Deserializer, Serialize... | match self {
DeviceIdOrAllDevices::DeviceId(device_id) => write!(f, "{}", device_id),
DeviceIdOrAllDevices::AllDevices => write!(f, "*"),
}
}
}
impl From<Box<DeviceId>> for DeviceIdOrAllDevices {
fn from(d: Box<DeviceId>) -> Self {
DeviceIdOrAllDevices::DeviceId(... | fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { | random_line_split |
lib.rs | //! af-cuda-interop package is to used only when the application intends to mix
//! arrayfire code with raw CUDA code.
use arrayfire::{handle_error_general, AfError};
use cuda_runtime_sys::cudaStream_t;
use libc::c_int;
extern "C" {
fn afcu_get_native_id(native_id: *mut c_int, id: c_int) -> c_int;
fn afcu_set... | {
unsafe {
let mut ret_val: cudaStream_t = std::ptr::null_mut();
let err_val = afcu_get_stream(&mut ret_val as *mut cudaStream_t, native_id);
handle_error_general(AfError::from(err_val));
ret_val
}
} | identifier_body | |
lib.rs | //! af-cuda-interop package is to used only when the application intends to mix
//! arrayfire code with raw CUDA code.
use arrayfire::{handle_error_general, AfError};
use cuda_runtime_sys::cudaStream_t;
use libc::c_int;
extern "C" {
fn afcu_get_native_id(native_id: *mut c_int, id: c_int) -> c_int;
fn afcu_set... | (id: i32) -> i32 {
unsafe {
let mut temp: i32 = 0;
let err_val = afcu_get_native_id(&mut temp as *mut c_int, id);
handle_error_general(AfError::from(err_val));
temp
}
}
/// Set active device using CUDA context's id
///
/// # Parameters
///
/// - `id` is the identifier of GPU in ... | get_device_native_id | identifier_name |
lib.rs | //! af-cuda-interop package is to used only when the application intends to mix
//! arrayfire code with raw CUDA code.
use arrayfire::{handle_error_general, AfError};
use cuda_runtime_sys::cudaStream_t;
use libc::c_int;
extern "C" {
fn afcu_get_native_id(native_id: *mut c_int, id: c_int) -> c_int;
fn afcu_set... | }
/// Set active device using CUDA context's id
///
/// # Parameters
///
/// - `id` is the identifier of GPU in CUDA context
pub fn set_device_native_id(native_id: i32) {
unsafe {
let err_val = afcu_set_native_id(native_id);
handle_error_general(AfError::from(err_val));
}
}
/// Get CUDA stream... | } | random_line_split |
lib.rs | //! # Boxcars
//!
//! Boxcars is a [Rocket League](http://www.rocketleaguegame.com/) replay parser library written in
//! Rust.
//!
//! ## Features
//!
//! - ✔ Safe: Stable Rust with no unsafe
//! - ✔ Fast: Parse a hundred replays per second per CPU core
//! - ✔ Fuzzed: Extensively fuzzed against potential malicious in... | //!
//! The above example will parse both the header and network data of a replay file, and return an
//! error if there is an issue either header or network data. Since the network data will often
//! change with each Rocket League patch, the default behavior is to ignore any errors from the
//! network data and stil... | //!
//! # let filename = "assets/replays/good/rumble.replay";
//! # run(filename).unwrap();
//! ``` | random_line_split |
memory.rs | // 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 in writing, software
// distributed ... | // Copyright 2017-2021 int08h LLC
// | random_line_split | |
memory.rs | // Copyright 2017-2021 int08h LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | {
pub port: u16,
pub interface: String,
pub seed: Vec<u8>,
pub batch_size: u8,
pub status_interval: Duration,
pub kms_protection: KmsProtection,
pub health_check_port: Option<u16>,
pub client_stats: bool,
pub fault_percentage: u8,
}
impl MemoryConfig {
pub fn new(port: u16) -> ... | MemoryConfig | identifier_name |
memory.rs | // Copyright 2017-2021 int08h LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... |
fn health_check_port(&self) -> Option<u16> {
self.health_check_port
}
fn client_stats_enabled(&self) -> bool {
self.client_stats
}
fn fault_percentage(&self) -> u8 {
self.fault_percentage
}
}
| {
&self.kms_protection
} | identifier_body |
key-value-expansion.rs | // Regression tests for issue #55414, expansion happens in the value of a key-value attribute,
// and the expanded expression is more complex than simply a macro call.
// aux-build:key-value-expansion.rs
#![feature(rustc_attrs)]
extern crate key_value_expansion;
// Minimized test case.
macro_rules! bug {
($exp... | // Test case from #66804.
macro_rules! doc_comment {
($x:expr) => {
#[doc = $x]
extern {}
};
}
macro_rules! some_macro {
($t1: ty) => {
doc_comment! {format!("{coor}", coor = stringify!($t1)).as_str()}
//~^ ERROR unexpected token: `{
};
}
some_macro!(u8);
fn main() {} | random_line_split | |
key-value-expansion.rs | // Regression tests for issue #55414, expansion happens in the value of a key-value attribute,
// and the expanded expression is more complex than simply a macro call.
// aux-build:key-value-expansion.rs
#![feature(rustc_attrs)]
extern crate key_value_expansion;
// Minimized test case.
macro_rules! bug {
($exp... | () {}
| main | identifier_name |
key-value-expansion.rs | // Regression tests for issue #55414, expansion happens in the value of a key-value attribute,
// and the expanded expression is more complex than simply a macro call.
// aux-build:key-value-expansion.rs
#![feature(rustc_attrs)]
extern crate key_value_expansion;
// Minimized test case.
macro_rules! bug {
($exp... | {} | identifier_body | |
workspace.rs | //! Workspace module for Xt.
//! Handles workspaces and their associated buffers.
// This file is part of Xt.
// This is the Xt text editor; it edits text.
// Copyright (C) 2016-2018 The Xt Developers
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Pu... |
}
| {
let hname = hname.into();
let logger = init_logger().new(o!("workspace" => hname.clone()));
Workspace {
hname: hname,
logger: logger,
buffers: Vec::new(),
}
} | identifier_body |
workspace.rs | //! Workspace module for Xt.
//! Handles workspaces and their associated buffers.
// This file is part of Xt.
// This is the Xt text editor; it edits text.
// Copyright (C) 2016-2018 The Xt Developers
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Pu... | {
/// Human-readable name for workspace.
pub hname: String,
/// Logger instance for workspace.
/// Derived from root Logger.
pub logger: slog::Logger,
/// Vector of Buffer structs.
pub buffers: Vec<Buffer>,
}
impl Workspace {
/// Create a new workspace.
pub fn new<S: Into<String>>(... | Workspace | identifier_name |
workspace.rs | //! Workspace module for Xt.
//! Handles workspaces and their associated buffers.
| // 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 the
// License, or (at your option) any later version.
// This program is distributed in the hope that it will be useful, ... | // This file is part of Xt.
// This is the Xt text editor; it edits text.
// Copyright (C) 2016-2018 The Xt Developers
| random_line_split |
lib.rs | #![crate_name = "rusoto"]
#![crate_type = "lib"]
#![cfg_attr(feature = "unstable", feature(custom_derive, plugin))]
#![cfg_attr(feature = "unstable", plugin(serde_macros))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(feature = "nightly-testing", allow(cyclomatic_complexity, used_underscore_bin... | //! }
//! },
//! Err(error) => {
//! println!("Error: {:?}", error);
//! },
//! }
extern crate chrono;
extern crate hyper;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate log;
extern crate md5;
extern crate regex;
extern crate ring;
extern crate rustc_serialize;
extern crat... | //! println!("{}", table_name);
//! }
//! },
//! None => println!("No tables in database!"), | random_line_split |
local-drop-glue.rs | //
// We specify -C incremental here because we want to test the partitioning for
// incremental compilation
// We specify opt-level=0 because `drop_in_place` is `Internal` when optimizing
// compile-flags:-Zprint-mono-items=lazy -Cincremental=tmp/partitioning-tests/local-drop-glue
// compile-flags:-Zinline-in-all-cgus... | struct Outer {
_a: Struct,
}
//~ MONO_ITEM fn user @@ local_drop_glue[External]
pub fn user() {
let _ = Outer { _a: Struct { _a: 0 } };
}
pub mod mod1 {
use super::Struct;
//~ MONO_ITEM fn std::ptr::drop_in_place::<mod1::Struct2> - shim(Some(mod1::Struct2)) @@ local_drop_glue-fallback.cgu[External]
... |
//~ MONO_ITEM fn std::ptr::drop_in_place::<Outer> - shim(Some(Outer)) @@ local_drop_glue-fallback.cgu[External] | random_line_split |
local-drop-glue.rs | //
// We specify -C incremental here because we want to test the partitioning for
// incremental compilation
// We specify opt-level=0 because `drop_in_place` is `Internal` when optimizing
// compile-flags:-Zprint-mono-items=lazy -Cincremental=tmp/partitioning-tests/local-drop-glue
// compile-flags:-Zinline-in-all-cgus... | {
_a: u32,
}
impl Drop for Struct {
//~ MONO_ITEM fn <Struct as std::ops::Drop>::drop @@ local_drop_glue-fallback.cgu[External]
fn drop(&mut self) {}
}
//~ MONO_ITEM fn std::ptr::drop_in_place::<Outer> - shim(Some(Outer)) @@ local_drop_glue-fallback.cgu[External]
struct Outer {
_a: Struct,
}
//~ MON... | Struct | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.