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 |
|---|---|---|---|---|
build.rs | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::env;
use std::process::Command;
use std::str::{self, FromStr};
fn main() | }
}
fn rustc_minor_version() -> Option<u32> {
let rustc = match env::var_os("RUSTC") {
Some(rustc) => rustc,
None => return None,
};
let output = match Command::new(rustc).arg("--version").output() {
Ok(output) => output,
Err(_) => return None,
};
let version ... | {
println!("cargo:rustc-cfg=build_script_ran");
let minor = match rustc_minor_version() {
Some(minor) => minor,
None => return,
};
let target = env::var("TARGET").unwrap();
if minor >= 34 {
println!("cargo:rustc-cfg=is_new_rustc");
} else {
println!("cargo:rustc... | identifier_body |
build.rs | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::env;
use std::process::Command;
use std::str::{self, FromStr};
fn | () {
println!("cargo:rustc-cfg=build_script_ran");
let minor = match rustc_minor_version() {
Some(minor) => minor,
None => return,
};
let target = env::var("TARGET").unwrap();
if minor >= 34 {
println!("cargo:rustc-cfg=is_new_rustc");
} else {
println!("cargo:ru... | main | identifier_name |
monitor.rs | //! Types useful for interacting with a user's monitors.
//!
//! If you want to get basic information about a monitor, you can use the [`MonitorHandle`][monitor_handle]
//! type. This is retrieved from one of the following methods, which return an iterator of
//! [`MonitorHandle`][monitor_handle]:
//! - [`EventLoopWind... |
}
/// Handle to a monitor.
///
/// Allows you to retrieve information about a given monitor and can be used in [`Window`] creation.
///
/// [`Window`]: crate::window::Window
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct MonitorHandle {
pub(crate) inner: platform_impl::MonitorHandle,
}
impl M... | {
write!(
f,
"{}x{} @ {} Hz ({} bpp)",
self.size().width,
self.size().height,
self.refresh_rate(),
self.bit_depth()
)
} | identifier_body |
monitor.rs | //! Types useful for interacting with a user's monitors.
//!
//! If you want to get basic information about a monitor, you can use the [`MonitorHandle`][monitor_handle]
//! type. This is retrieved from one of the following methods, which return an iterator of
//! [`MonitorHandle`][monitor_handle]:
//! - [`EventLoopWind... | (&self) -> PhysicalPosition<i32> {
self.inner.position()
}
/// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
///
/// See the [`dpi`](crate::dpi) module for more information.
///
/// ## Platform-specific
///
/// - **X11:** Can... | position | identifier_name |
monitor.rs | //! Types useful for interacting with a user's monitors.
//!
//! If you want to get basic information about a monitor, you can use the [`MonitorHandle`][monitor_handle]
//! type. This is retrieved from one of the following methods, which return an iterator of
//! [`MonitorHandle`][monitor_handle]:
//! - [`EventLoopWind... | pub fn name(&self) -> Option<String> {
self.inner.name()
}
/// Returns the monitor's resolution.
///
/// ## Platform-specific
///
/// - **Web:** Always returns (0,0)
#[inline]
pub fn size(&self) -> PhysicalSize<u32> {
self.inner.size()
}
/// Returns the top-... | /// ## Platform-specific
///
/// - **Web:** Always returns None
#[inline] | random_line_split |
mod.rs | //
// Copyright:: Copyright (c) 2016 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// 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... | }
#[cfg(test)]
mod tests {
use cookbook::*;
use std::path::PathBuf;
#[test]
fn test_metadata_version_constructor() {
let version_generator = MetadataVersion::new(None, Some(2), None);
let MetadataVersion {
major: ma,
minor: mi,
patch: pa,
} =... | &["commit", "-m", &commit_msg],
&utils::cwd()
));
Ok(()) | random_line_split |
mod.rs | //
// Copyright:: Copyright (c) 2016 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// 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... |
#[test]
fn verify_version_bumping_using_bump_patchset() {
let version = MetadataVersion {
major: 1,
minor: 2,
patch: 3,
};
let MetadataVersion {
major: ma,
minor: mi,
patch: pa,
} = super::bump_patchset(vers... | {
let version_generator = MetadataVersion::new(None, Some(2), None);
let MetadataVersion {
major: ma,
minor: mi,
patch: pa,
} = version_generator;
assert_eq!(ma, 0);
assert_eq!(mi, 2);
assert_eq!(pa, 0);
assert_eq!("0.2.0", &ver... | identifier_body |
mod.rs | //
// Copyright:: Copyright (c) 2016 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// 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... | (mut version: MetadataVersion) -> Result<MetadataVersion, DeliveryError> {
version = MetadataVersion {
patch: version.patch + 1,
..version
};
Ok(version)
}
// Saves the new version to the metadata and commit the changes
fn save_version(metadata: &PathBuf, version: String) -> Result<(), Deliv... | bump_patchset | identifier_name |
mod.rs | //
// Copyright:: Copyright (c) 2016 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// 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... | ;
if let Some(minor) = metadata.name("minor") {
mi = minor.as_str().parse::<usize>().ok();
};
if let Some(patch) = metadata.name("patch") {
pa = patch.as_str().parse::<usize>().ok();
};
Ok(MetadataVersion::new(ma, mi, pa))
}
// Bump the patchset of the provided version
fn bump_patch... | {
ma = major.as_str().parse::<usize>().ok();
} | conditional_block |
lib.rs | //! Differential dataflow is a high-throughput, low-latency data-parallel programming framework.
//!
//! Differential dataflow programs are written in a collection-oriented style, where you transform
//! collections of records using traditional operations like `map`, `filter`, `join`, and `group_by`.
//! Differential d... | //!
//! Once you have defined a differential dataflow computation, you may then add records to or remove
//! records from its inputs; the system will automatically update the computation's outputs with the
//! appropriate corresponding additions and removals, and report these changes to you.
//!
//! Differential datafl... | //! to repeatedly apply differential dataflow transformations to collections. | random_line_split |
mod.rs | //! Kafka consumers.
use std::ptr;
use std::sync::Arc;
use std::time::Duration;
use rdkafka_sys as rdsys;
use rdkafka_sys::types::*;
use crate::client::{Client, ClientContext, NativeClient};
use crate::error::KafkaResult;
use crate::groups::GroupList;
use crate::log::{error, trace};
use crate::message::BorrowedMessa... |
};
trace!("Running pre-rebalance with {:?}", rebalance);
self.pre_rebalance(&rebalance);
trace!("Running rebalance with {:?}", rebalance);
// Execute rebalance
unsafe {
match err {
RDKafkaRespErr::RD_KAFKA_RESP_ERR__ASSIGN_PARTITIONS => {
... | {
let error = unsafe { cstr_to_owned(rdsys::rd_kafka_err2str(err)) };
error!("Error rebalancing: {}", error);
Rebalance::Error(error)
} | conditional_block |
mod.rs | //! Kafka consumers.
use std::ptr;
use std::sync::Arc;
use std::time::Duration;
use rdkafka_sys as rdsys;
use rdkafka_sys::types::*;
use crate::client::{Client, ClientContext, NativeClient};
use crate::error::KafkaResult;
use crate::groups::GroupList;
use crate::log::{error, trace};
use crate::message::BorrowedMessa... | pub struct DefaultConsumerContext;
impl ClientContext for DefaultConsumerContext {}
impl ConsumerContext for DefaultConsumerContext {}
/// Specifies whether a commit should be performed synchronously or asynchronously.
///
/// Regardless of the `CommitMode`, the commit APIs enqueue the commit request in
/// a local w... | /// An inert [`ConsumerContext`] that can be used when no customizations are
/// needed.
#[derive(Clone, Debug, Default)] | random_line_split |
mod.rs | //! Kafka consumers.
use std::ptr;
use std::sync::Arc;
use std::time::Duration;
use rdkafka_sys as rdsys;
use rdkafka_sys::types::*;
use crate::client::{Client, ClientContext, NativeClient};
use crate::error::KafkaResult;
use crate::groups::GroupList;
use crate::log::{error, trace};
use crate::message::BorrowedMessa... | <'a>(&self, rebalance: &Rebalance<'a>) {}
// TODO: convert pointer to structure
/// Post commit callback. This method will run after a group of offsets was
/// committed to the offset store.
#[allow(unused_variables)]
fn commit_callback(&self, result: KafkaResult<()>, offsets: &TopicPartitionList) ... | post_rebalance | identifier_name |
mod.rs | //! Kafka consumers.
use std::ptr;
use std::sync::Arc;
use std::time::Duration;
use rdkafka_sys as rdsys;
use rdkafka_sys::types::*;
use crate::client::{Client, ClientContext, NativeClient};
use crate::error::KafkaResult;
use crate::groups::GroupList;
use crate::log::{error, trace};
use crate::message::BorrowedMessa... |
/// Returns the minimum interval at which to poll the main queue, which
/// services the logging, stats, and error callbacks.
///
/// The main queue is polled once whenever [`BaseConsumer::poll`] is called.
/// If `poll` is called with a timeout that is larger than this interval,
/// then the ... | {} | identifier_body |
request.rs | use Request;
use hyper::header;
pub trait Referer {
fn referer(&self) -> Option<&str>;
}
| /// # Examples
/// ```{rust}
/// #[macro_use] extern crate nickel;
///
/// use nickel::{Nickel, HttpRouter};
/// use nickel::extensions::{Referer, Redirect};
///
/// fn main() {
/// let mut server = Nickel::new();
/// server.get("/a", middleware! { |req, res|
/// ... | impl<'mw, 'server, D> Referer for Request<'mw, 'server, D> {
/// Get the Request's referer header
/// | random_line_split |
request.rs | use Request;
use hyper::header;
pub trait Referer {
fn referer(&self) -> Option<&str>;
}
impl<'mw,'server, D> Referer for Request<'mw,'server, D> {
/// Get the Request's referer header
///
/// # Examples
/// ```{rust}
/// #[macro_use] extern crate nickel;
///
/// use nickel::{Nickel, H... |
}
| {
self.origin.headers.get::<header::Referer>()
.map(|r| &***r)
} | identifier_body |
request.rs | use Request;
use hyper::header;
pub trait Referer {
fn referer(&self) -> Option<&str>;
}
impl<'mw,'server, D> Referer for Request<'mw,'server, D> {
/// Get the Request's referer header
///
/// # Examples
/// ```{rust}
/// #[macro_use] extern crate nickel;
///
/// use nickel::{Nickel, H... | (&self) -> Option<&str> {
self.origin.headers.get::<header::Referer>()
.map(|r| &***r)
}
}
| referer | identifier_name |
xcrate-private-by-default.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T>() {}
#[start]
fn main(_: int, _: **u8) -> int {
// Actual public items should be public
static_priv_by_default::a;
static_priv_by_default::b;
static_priv_by_default::c;
foo::<static_priv_by_default::d>();
// publicly re-exported items should be available
static_priv_by_default::bar::e;... | foo | identifier_name |
xcrate-private-by-default.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 ... |
#[start]
fn main(_: int, _: **u8) -> int {
// Actual public items should be public
static_priv_by_default::a;
static_priv_by_default::b;
static_priv_by_default::c;
foo::<static_priv_by_default::d>();
// publicly re-exported items should be available
static_priv_by_default::bar::e;
sta... | {} | identifier_body |
xcrate-private-by-default.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 ... | foo::<static_priv_by_default::foo::d>();
//~^ ERROR: type `d` is private
3
} | random_line_split | |
msghandle.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// 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.
// Th... | (con: &Connection, tx_pub: &Sender<(String, Vec<u8>)>, payload: &[u8]) {
if let Ok(msg) = parse_from_bytes::<communication::Message>(payload) {
let t = msg.get_field_type();
let cid = msg.get_cmd_id();
info!("-----cmd_id--------{:?}--------------", display_cmd(cid));
if cid == cmd_id... | handle_rpc | identifier_name |
msghandle.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// 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.
// Th... |
pub fn handle_rpc(con: &Connection, tx_pub: &Sender<(String, Vec<u8>)>, payload: &[u8]) {
if let Ok(msg) = parse_from_bytes::<communication::Message>(payload) {
let t = msg.get_field_type();
let cid = msg.get_cmd_id();
info!("-----cmd_id--------{:?}--------------", display_cmd(cid));
... | use protobuf::Message;
use protobuf::core::parse_from_bytes;
use server::MySender;
use std::io;
use std::sync::mpsc::Sender; | random_line_split |
msghandle.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// 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.
// Th... | topic = "net.sync".to_string();
} else if (cid == cmd_id(submodules::CONSENSUS, topics::CONSENSUS_MSG) && t == MsgType::MSG) || (cid == cmd_id(submodules::CONSENSUS, topics::NEW_PROPOSAL) && t == MsgType::MSG) {
trace!("CONSENSUS pub msg");
topic = "net.msg".to_string();
... | {
if let Ok(msg) = parse_from_bytes::<communication::Message>(payload) {
let mut topic = String::default();
let mut is_proc = true;
let t = msg.get_field_type();
let cid = msg.get_cmd_id();
if cid == cmd_id(submodules::CONSENSUS, topics::NEW_TX) && t == MsgType::TX {
... | identifier_body |
str.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! String utils for attributes and similar stuff.
#![deny(missing_docs)]
use num_traits::ToPrimitive;
use std::... |
}
#[cfg(feature = "gecko")]
impl<'a> From<&'a str> for CssStringBorrow<'a> {
fn from(s: &'a str) -> Self {
CssStringBorrow::UTF8(s)
}
}
#[cfg(feature = "gecko")]
impl<'a> From<&'a ::nsstring::nsString> for CssStringBorrow<'a> {
fn from(s: &'a ::nsstring::nsString) -> Self {
CssStringBorro... | {
match *self {
CssStringBorrow::UTF16(s) => s.is_empty(),
CssStringBorrow::UTF8(s) => s.is_empty(),
}
} | identifier_body |
str.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! String utils for attributes and similar stuff.
#![deny(missing_docs)]
use num_traits::ToPrimitive;
use std::... | <I, T>(strs: I, join: &str) -> String
where
I: IntoIterator<Item = T>,
T: AsRef<str>,
{
strs.into_iter()
.enumerate()
.fold(String::new(), |mut acc, (i, s)| {
if i > 0 {
acc.push_str(join);
}
acc.push_str(s.as_ref());
acc
... | str_join | identifier_name |
str.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! String utils for attributes and similar stuff.
#![deny(missing_docs)]
use num_traits::ToPrimitive;
use std::... | /// String type that coerces to CssStringWriter, used when serialization code
/// needs to allocate a temporary string.
#[cfg(feature = "gecko")]
pub type CssString = ::nsstring::nsString;
/// Certain serialization code needs to interact with borrowed strings, which
/// are sometimes native UTF8 Rust strings, and othe... | random_line_split | |
coherence-blanket-conflicts-with-blanket-implemented.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn main() { } | random_line_split | |
coherence-blanket-conflicts-with-blanket-implemented.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 ... | (&self) -> usize { 0 }
}
impl<T:Odd> MyTrait for T {
fn get(&self) -> usize { 0 }
}
fn main() { }
| get | identifier_name |
coherence-blanket-conflicts-with-blanket-implemented.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
fn main() { }
| { 0 } | identifier_body |
lib.rs | extern crate regex;
use regex::Regex;
struct ParsedTimeStr {
finded_time: String,
finded_type: String,
}
pub struct TimeStr {
time_string: String,
}
impl TimeStr {
pub fn new(t_str: &str) -> TimeStr {
TimeStr {
time_string: t_str.to_string(),
}
}
... | () {
let p1 = TimeStr::new("1m");
assert_eq!(60, p1.to_seconds());
let p2 = TimeStr::new("10m");
assert_eq!(600, p2.to_seconds());
let p3 = TimeStr::new("5m");
assert_eq!(300, p3.to_seconds());
}
#[test]
fn test_seconds() {
let p1 = TimeStr::new("1s");
assert_eq!(1, p1.to_seconds(... | test_minutes | identifier_name |
lib.rs | extern crate regex;
use regex::Regex;
struct ParsedTimeStr {
finded_time: String,
finded_type: String,
}
pub struct TimeStr {
time_string: String,
}
impl TimeStr {
pub fn new(t_str: &str) -> TimeStr {
TimeStr {
time_string: t_str.to_string(),
}
}
... | assert_eq!(600, p2.to_seconds());
let p3 = TimeStr::new("5m");
assert_eq!(300, p3.to_seconds());
}
#[test]
fn test_seconds() {
let p1 = TimeStr::new("1s");
assert_eq!(1, p1.to_seconds());
let p2 = TimeStr::new("10s");
assert_eq!(10, p2.to_seconds());
let p3 = TimeStr::new("5s... |
let p2 = TimeStr::new("10m"); | random_line_split |
lib.rs | extern crate regex;
use regex::Regex;
struct ParsedTimeStr {
finded_time: String,
finded_type: String,
}
pub struct TimeStr {
time_string: String,
}
impl TimeStr {
pub fn new(t_str: &str) -> TimeStr {
TimeStr {
time_string: t_str.to_string(),
}
}
... |
if parsed_string.finded_type == "m" {
return i_time * 60;
}
return i_time;
}
}
#[test]
fn test_hours() {
let p1 = TimeStr::new("1h");
assert_eq!(3600, p1.to_seconds());
let p2 = TimeStr::new("10h");
assert_eq!(36000, p2.to_seconds());
... | {
return i_time * 60 * 60;
} | conditional_block |
det.rs |
// Std imports
use num::traits::{Float, Signed, One};
// local imports
use sralgebra::{CommutativeRingPartial};
use srmatrix::api::{Matrix};
use srmatrix::api::{Shape, Extraction, MatrixBuffer, Search};
use srmatrix::api::eo_traits::ECO;
use srmatrix::api::SRError;
#[doc="Returns the determinant of a matrix.
# Rema... |
#[test]
fn test_empty_mat_det(){
let m : MatrixI64 = Matrix::new_uninitialized(0, 0);
let d = m.det().unwrap();
assert_eq!(d, 1);
}
#[test]
fn test_examples_from_testdata(){
assert_eq!(testdata::matrix::square_0().det().unwrap(), -13.);
assert_eq!(testdata:... | {
let sizes = vec![1, 2, 4, 8];
let determinants = vec![1.0, 0.083333333333333,
1.653439153439264e-07, 2.737050310006999e-33];
let threshold = 1e-10;
for (size, expected_value) in sizes.iter().zip(determinants.iter()){
let m = hilbert(*size);
let d =... | identifier_body |
det.rs |
// Std imports
use num::traits::{Float, Signed, One};
// local imports
use sralgebra::{CommutativeRingPartial};
use srmatrix::api::{Matrix};
use srmatrix::api::{Shape, Extraction, MatrixBuffer, Search};
use srmatrix::api::eo_traits::ECO;
use srmatrix::api::SRError;
#[doc="Returns the determinant of a matrix.
# Rema... | <T:CommutativeRingPartial+Signed+Float+PartialOrd>(a : &mut Matrix<T>)->T{
assert!(a.is_square());
let o = One::one();
let mut result : T = o;
let n = a.num_cols();
// Iterate over rows
for k in 0..n{
// We are working on k-th row.
// Find the pivot position in the row
le... | det_ge | identifier_name |
det.rs |
// Std imports
use num::traits::{Float, Signed, One};
// local imports
use sralgebra::{CommutativeRingPartial};
use srmatrix::api::{Matrix};
use srmatrix::api::{Shape, Extraction, MatrixBuffer, Search};
use srmatrix::api::eo_traits::ECO;
use srmatrix::api::SRError;
#[doc="Returns the determinant of a matrix.
# Rema... |
let a0 = m.get(0, 0).unwrap();
//debug!("m: {}", m);
if m.is_scalar(){
return a0;
}
let n = m.num_cols();
let mut m2 = m.sub_matrix(1,1, n-1, n-1);
let ps = m.as_ptr();
let pd = m2.as_mut_ptr();
let mut sign : T = One::one();
let mut result = sign * a0 * det_naive(&m2);... | {
return One::one();
} | conditional_block |
det.rs | // Std imports
use num::traits::{Float, Signed, One};
// local imports
use sralgebra::{CommutativeRingPartial};
use srmatrix::api::{Matrix};
use srmatrix::api::{Shape, Extraction, MatrixBuffer, Search};
use srmatrix::api::eo_traits::ECO;
use srmatrix::api::SRError;
#[doc="Returns the determinant of a matrix.
# Remar... | /******************************************************
*
* Unit tests
*
******************************************************/
#[cfg(test)]
mod test{
use super::*;
use srmatrix::api::*;
use matrix::mat_traits::*;
use testdata;
#[test]
fn test_det_0(){
let m = matrix_rw_f64(2,2... | random_line_split | |
thread.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 ... | unsafe { start_thread(main); }
0
}
}
pub fn set_name(_name: &str) {
// Windows threads are nameless
// The names in MSVC debugger are obtained using a "magic" exception,
// which requires a use of MS C++ extensions.
// See https://msdn.microsoft.c... | };
extern "system" fn thread_start(main: *mut libc::c_void) -> DWORD { | random_line_split |
thread.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 ... | ;
extern "system" fn thread_start(main: *mut libc::c_void) -> DWORD {
unsafe { start_thread(main); }
0
}
}
pub fn set_name(_name: &str) {
// Windows threads are nameless
// The names in MSVC debugger are obtained using a "magic" exception,
// whi... | {
mem::forget(p); // ownership passed to CreateThread
Ok(Thread { handle: Handle::new(ret) })
} | conditional_block |
thread.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 ... | (self) {
use libc::consts::os::extra::INFINITE;
unsafe { c::WaitForSingleObject(self.handle.raw(), INFINITE); }
}
pub fn yield_now() {
// This function will return 0 if there are no other threads to execute,
// but this also means that the yield was useless so this isn't really ... | join | identifier_name |
thread.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 ... |
}
| { None } | identifier_body |
lint-unused-unsafe.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 ... | unsafe { //~ ERROR: unnecessary `unsafe` block
unsafe { //~ ERROR: unnecessary `unsafe` block
unsf()
}
}
}
unsafe fn good0() { unsf() }
fn good1() { unsafe { unsf() } }
fn good2() {
/* bug uncovered when implementing warning ab... | unsf()
}
}
}
unsafe fn bad7() { | random_line_split |
lint-unused-unsafe.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 ... |
unsafe fn unsf() {}
fn bad1() { unsafe {} } //~ ERROR: unnecessary `unsafe` block
fn bad2() { unsafe { bad1() } } //~ ERROR: unnecessary `unsafe` block
unsafe fn bad3() { unsafe {} } //~ ERROR: unnecessary `unsafe` block
fn bad4() { unsafe { callback(||{}) } } //~ ERROR: unnecessa... | { fail!() } | identifier_body |
lint-unused-unsafe.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 ... | () { unsafe { unsf() } }
fn good2() {
/* bug uncovered when implementing warning about unused unsafe blocks. Be
sure that when purity is inherited that the source of the unsafe-ness
is tracked correctly */
unsafe {
unsafe fn what() -> ~[~str] { fail!() }
callback(|| {
... | good1 | identifier_name |
dbus.rs | use chan::{Sender, Receiver};
use dbus::{self, BusType, Connection, Message, MessageItem, NameFlag, Signature};
use dbus::arg::{Arg, ArgType, Get, Iter};
use dbus::tree::{Argument, Factory};
use std::thread;
use std::convert::From;
use std::str::FromStr;
use uuid::Uuid;
use datatype::{Command, DBusConfig, Event, Insta... | (&self, method: &str, args: &[MessageItem]) -> Message {
let mut msg = Message::new_method_call(&self.dest, &self.path, &self.iface, method).expect("new dbus message");
msg.append_items(args);
msg
}
fn handle_event(&self, event: Event) {
match event {
Event::UpdateAv... | new_message | identifier_name |
dbus.rs | use chan::{Sender, Receiver};
use dbus::{self, BusType, Connection, Message, MessageItem, NameFlag, Signature};
use dbus::arg::{Arg, ArgType, Get, Iter};
use dbus::tree::{Argument, Factory};
use std::thread;
use std::convert::From;
use std::str::FromStr;
use uuid::Uuid;
use datatype::{Command, DBusConfig, Event, Insta... | MessageItem::from(comp.update_image),
MessageItem::from(comp.signature)
]);
self.send_async(msg);
}
Event::InstalledSoftwareNeeded => {
let msg = self.new_message("getInstalledPackages", &[
... | Event::DownloadComplete(comp) => {
let msg = self.new_message("downloadComplete", &[ | random_line_split |
dbus.rs | use chan::{Sender, Receiver};
use dbus::{self, BusType, Connection, Message, MessageItem, NameFlag, Signature};
use dbus::arg::{Arg, ArgType, Get, Iter};
use dbus::tree::{Argument, Factory};
use std::thread;
use std::convert::From;
use std::str::FromStr;
use uuid::Uuid;
use datatype::{Command, DBusConfig, Event, Insta... |
}
| {
None
} | identifier_body |
api.rs | use std::fmt;
use std::ops::Deref;
use std::marker::PhantomData;
use std::error::Error as StdError;
use std::result::Result as StdResult;
use serde::de;
use serde_json::{self, Error as JsonError};
use hyper::client::Client as HttpClient;
use hyper::Error as HttpError;
use url::{self, ParseError as UrlError, Url};
use o... | (err: UrlError) -> Error {
Error::Http(HttpError::Uri(err))
}
}
pub type Result<T> = StdResult<T, Error>;
impl Client {
pub fn auth<K, S>(&self, key: K, secret: S) -> OAuth
where K: Into<String>,
S: Into<String>
{
OAuth::new(&self.client, key.into(), secret.into())
... | from | identifier_name |
api.rs | use std::fmt;
use std::ops::Deref;
use std::marker::PhantomData;
use std::error::Error as StdError;
use std::result::Result as StdResult;
use serde::de;
use serde_json::{self, Error as JsonError};
use hyper::client::Client as HttpClient;
use hyper::Error as HttpError;
use url::{self, ParseError as UrlError, Url};
use o... |
}
impl From<(OwnerId, Id)> for FullId {
fn from(pair: (OwnerId, Id)) -> FullId {
FullId(pair.0, pair.1)
}
}
impl Into<(OwnerId, Id)> for FullId {
fn into(self) -> (OwnerId, Id) {
(self.0, self.1)
}
}
pub struct Client {
client: HttpClient,
}
#[derive(Debug)]
pub enum Error {
... | {
write!(f, "{}_{}", self.0, self.1)
} | identifier_body |
api.rs | use std::fmt;
use std::ops::Deref;
use std::marker::PhantomData;
use std::error::Error as StdError;
use std::result::Result as StdResult;
use serde::de;
use serde_json::{self, Error as JsonError};
use hyper::client::Client as HttpClient;
use hyper::Error as HttpError;
use url::{self, ParseError as UrlError, Url};
use o... | fn from(err: UrlError) -> Error {
Error::Http(HttpError::Uri(err))
}
}
pub type Result<T> = StdResult<T, Error>;
impl Client {
pub fn auth<K, S>(&self, key: K, secret: S) -> OAuth
where K: Into<String>,
S: Into<String>
{
OAuth::new(&self.client, key.into(), secret... | Error::Json(err)
}
}
impl From<UrlError> for Error { | random_line_split |
test.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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 ... | () {
use extra::arc::Arc;
use stylesheet::*;
use types::CssLevel21;
use wapcaplet::LwcString;
use super::CssResult;
let resolve: CssUrlResolutionFn = |a,b| resolve_url(a, b);
let params: CssStylesheetParams = CssStylesheetParams {
params_version: CssStylesheetParamsVersion1,
... | test_arc | identifier_name |
test.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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 ... | color: None,
font: None,
};
let mut sheet: CssStylesheet = css_stylesheet_create(¶ms);
debug!("stylesheet: %?", sheet);
debug!("stylesheet size: %?", sheet.size());
sheet.append_data(data.as_bytes().to_owned());
sheet.data_done();
deb... | resolve: Some(resolve),
import: None, | random_line_split |
test.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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 ... |
}
#[test]
fn run() {
use super::super::stylesheet::{CssUrlResolutionFn, CssStylesheetParams, CssStylesheet,
css_stylesheet_create, CssStylesheetParamsVersion1};
use super::super::computed::CssComputedStyle;
use super::super::values::{CssColorC... | {
unsafe { cast::transmute(self.name) }
} | identifier_body |
udp_stream.rs | // Copyright 2015-2018 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 distributed... | (&mut self.socket, &mut self.outbound_messages)
}
}
impl<S: UdpSocket + Send +'static> Stream for UdpStream<S> {
type Item = Result<SerialMessage, io::Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let (socket, outbound_messages) = self.polla... | &mut self,
) -> (
&mut S,
&mut Peekable<Fuse<UnboundedReceiver<SerialMessage>>>,
) { | random_line_split |
udp_stream.rs | // Copyright 2015-2018 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 distributed... | (&mut self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
self.recv_from(buf).await
}
async fn send_to(&mut self, buf: &[u8], target: &SocketAddr) -> io::Result<usize> {
self.send_to(buf, target).await
}
}
#[cfg(test)]
#[cfg(feature = "tokio-runtime")]
mod tests {
#[cfg(not(targ... | recv_from | identifier_name |
udp_stream.rs | // Copyright 2015-2018 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 distributed... |
}
impl<S: Send> UdpStream<S> {
#[allow(clippy::type_complexity)]
fn pollable_split(
&mut self,
) -> (
&mut S,
&mut Peekable<Fuse<UnboundedReceiver<SerialMessage>>>,
) {
(&mut self.socket, &mut self.outbound_messages)
}
}
impl<S: UdpSocket + Send +'static> Stream fo... | {
UdpStream {
socket,
outbound_messages: outbound_messages.fuse().peekable(),
}
} | identifier_body |
window.rs | use std::rc::Rc;
use super::*;
use crate::{proc_macros::*, widget_base::*};
/// The enumeration of valid window events.
#[derive(Clone, Event)]
pub enum WindowEvent {
Resize { width: f64, height: f64 },
ActiveChanged(bool),
None,
}
pub type WindowHandlerFn = dyn Fn(&mut StatesContext, WindowEvent) -> bo... | {
/// A reference counted handler.
pub handler: Rc<WindowHandlerFn>,
}
impl EventHandler for WindowEventHandler {
fn handle_event(&self, states: &mut StatesContext, event: &EventBox) -> bool {
if let Ok(event) = event.downcast_ref::<WindowEvent>() {
return (self.handler)(states, event.... | WindowEventHandler | identifier_name |
window.rs | use std::rc::Rc;
use super::*;
use crate::{proc_macros::*, widget_base::*};
/// The enumeration of valid window events.
#[derive(Clone, Event)]
pub enum WindowEvent {
Resize { width: f64, height: f64 },
ActiveChanged(bool),
None,
}
pub type WindowHandlerFn = dyn Fn(&mut StatesContext, WindowEvent) -> bo... | /// A reference counted handler.
pub handler: Rc<WindowHandlerFn>,
}
impl EventHandler for WindowEventHandler {
fn handle_event(&self, states: &mut StatesContext, event: &EventBox) -> bool {
if let Ok(event) = event.downcast_ref::<WindowEvent>() {
return (self.handler)(states, event.clo... | random_line_split | |
window.rs | use std::rc::Rc;
use super::*;
use crate::{proc_macros::*, widget_base::*};
/// The enumeration of valid window events.
#[derive(Clone, Event)]
pub enum WindowEvent {
Resize { width: f64, height: f64 },
ActiveChanged(bool),
None,
}
pub type WindowHandlerFn = dyn Fn(&mut StatesContext, WindowEvent) -> bo... |
false
}
fn handles_event(&self, event: &EventBox) -> bool {
event.is_type::<WindowEvent>()
}
}
| {
return (self.handler)(states, event.clone());
} | conditional_block |
error.rs | use crate::error::{Error, ErrorKind, ExpectedNumberOfArgs};
use std::error;
use std::fmt;
use std::io;
#[derive(Debug)]
struct DummyError;
impl fmt::Display for DummyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "dummy")
}
}
impl error::Error for DummyError {}
fn dummy_... |
#[test]
fn error_message_formating() {
let err = Error::new(ErrorKind::WrongNumberOfArgs {
expected: ExpectedNumberOfArgs::Range(0, 1),
actual: 2,
kind: "diff".to_string(),
});
assert!(matches!(err.kind(), ErrorKind::WrongNumberOfArgs {.. }));
let msg = format!("{}", err);
... | {
let inner = DummyError;
let io_err = io::Error::new(io::ErrorKind::Other, inner);
Error::new(ErrorKind::IoError(io_err))
} | identifier_body |
error.rs | use crate::error::{Error, ErrorKind, ExpectedNumberOfArgs};
use std::error;
use std::fmt;
use std::io;
#[derive(Debug)]
struct DummyError;
impl fmt::Display for DummyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "dummy")
}
}
impl error::Error for DummyError {}
fn dummy_... | () {
use error::Error;
let err = crate::error::Error::new(ErrorKind::DiffDotsNotFound);
assert!(err.source().is_none());
let err = dummy_io_error();
let inner = err.source().unwrap();
assert!(format!("{}", inner).contains("dummy"), "{:?}", inner);
}
| inner_error_as_source | identifier_name |
error.rs | use crate::error::{Error, ErrorKind, ExpectedNumberOfArgs};
use std::error;
use std::fmt;
use std::io;
#[derive(Debug)]
struct DummyError;
impl fmt::Display for DummyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "dummy")
}
}
impl error::Error for DummyError {}
fn dummy_... | } | random_line_split | |
ref_mode.rs | use super::{c_type::is_mut_ptr, record_type::RecordType};
use crate::{config::gobjects::GObject, env, library};
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum RefMode {
None,
ByRef,
ByRefMut,
ByRefImmut, //immutable reference with mutable pointer in sys
ByRefConst, //instance parameters in t... | if direction == library::ParameterDirection::In {
RefMode::ByRefMut
} else {
RefMode::None
}
}
Alias(ref alias) => RefMode::of(env, alias.typ, direction),
_ => RefMode::None,
}
}
... | }
Union(..) => { | random_line_split |
ref_mode.rs | use super::{c_type::is_mut_ptr, record_type::RecordType};
use crate::{config::gobjects::GObject, env, library};
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum | {
None,
ByRef,
ByRefMut,
ByRefImmut, //immutable reference with mutable pointer in sys
ByRefConst, //instance parameters in trait function with const pointer in sys
ByRefFake,
}
impl RefMode {
#[inline]
pub fn of(
env: &env::Env,
tid: library::TypeId,
direction:... | RefMode | identifier_name |
ref_mode.rs | use super::{c_type::is_mut_ptr, record_type::RecordType};
use crate::{config::gobjects::GObject, env, library};
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum RefMode {
None,
ByRef,
ByRefMut,
ByRefImmut, //immutable reference with mutable pointer in sys
ByRefConst, //instance parameters in t... |
Union(..) => {
if direction == library::ParameterDirection::In {
RefMode::ByRefMut
} else {
RefMode::None
}
}
Alias(ref alias) => RefMode::of(env, alias.typ, direction),
_ => RefMode:... | {
if direction == library::ParameterDirection::In {
if let RecordType::Refcounted = RecordType::of(record) {
RefMode::ByRef
} else {
RefMode::ByRefMut
}
} else {
... | conditional_block |
arc_slice.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! A thin atomically-reference-counted slice.
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Seri... | () -> Self {
debug_assert!(
mem::align_of::<T>() <= mem::align_of::<u64>(),
"Need to increase the alignment of EMPTY_ARC_SLICE"
);
unsafe {
let empty: ArcSlice<_> = EMPTY_ARC_SLICE.clone();
let empty: Self = mem::transmute(empty);
debug... | default | identifier_name |
arc_slice.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! A thin atomically-reference-counted slice.
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Seri... |
/// Creates an Arc for a slice using the given iterator to generate the
/// slice, and marks the arc as intentionally leaked from the refcount
/// logging point of view.
#[inline]
pub fn from_iter_leaked<I>(items: I) -> Self
where
I: Iterator<Item = T> + ExactSizeIterator,
{
... | {
if items.len() == 0 {
return Self::default();
}
ArcSlice(ThinArc::from_header_and_iter(ARC_SLICE_CANARY, items))
} | identifier_body |
arc_slice.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! A thin atomically-reference-counted slice.
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Seri... |
ArcSlice(ThinArc::from_header_and_iter(ARC_SLICE_CANARY, items))
}
/// Creates an Arc for a slice using the given iterator to generate the
/// slice, and marks the arc as intentionally leaked from the refcount
/// logging point of view.
#[inline]
pub fn from_iter_leaked<I>(items: I) ->... | {
return Self::default();
} | conditional_block |
arc_slice.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! A thin atomically-reference-counted slice.
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Seri... | }
impl<T> Clone for ArcSlice<T> {
fn clone(&self) -> Self {
ArcSlice(self.0.clone())
}
}
lazy_static! {
// ThinArc doesn't support alignments greater than align_of::<u64>.
static ref EMPTY_ARC_SLICE: ArcSlice<u64> = {
ArcSlice::from_iter_leaked(iter::empty())
};
}
impl<T> Default ... | debug_assert_eq!(self.0.header.header, ARC_SLICE_CANARY);
&self.0.slice
} | random_line_split |
sendfn-spawn-with-fn-arg.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | };
let fn_to_send = Cell::new(fn_to_send);
task::spawn(|| {
test05_start(fn_to_send.take());
});
} | let fn_to_send: ~fn(int) = |n| {
error2!("{}", *three + n); // will copy x into the closure
assert_eq!(*three, 3); | random_line_split |
sendfn-spawn-with-fn-arg.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let three = ~3;
let fn_to_send: ~fn(int) = |n| {
error2!("{}", *three + n); // will copy x into the closure
assert_eq!(*three, 3);
};
let fn_to_send = Cell::new(fn_to_send);
task::spawn(|| {
test05_start(fn_to_send.take());
});
} | identifier_body | |
sendfn-spawn-with-fn-arg.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (f: ~fn(int)) {
f(22);
}
fn test05() {
let three = ~3;
let fn_to_send: ~fn(int) = |n| {
error2!("{}", *three + n); // will copy x into the closure
assert_eq!(*three, 3);
};
let fn_to_send = Cell::new(fn_to_send);
task::spawn(|| {
test05_start(fn_to_send.take());
});
... | test05_start | identifier_name |
log_utils.rs | use super::{
log_messages::{CommandLogMessage, ErrorLogMessage, SessionLogMessage},
LogSender,
};
pub async fn log_command(log_tx: &LogSender, player_name: String, message: String) |
pub async fn log_error(log_tx: &LogSender, message: String) {
if let Err(error) = log_tx.send(Box::new(ErrorLogMessage::new(message))).await {
println!("Could not send log message: {:?}", error);
}
}
pub async fn log_session_event(log_tx: &LogSender, source: String, message: String) {
if let Err(... | {
if let Err(error) = log_tx
.send(Box::new(CommandLogMessage::new(player_name, message)))
.await
{
println!("Could not send log message: {:?}", error);
}
} | identifier_body |
log_utils.rs | use super::{
log_messages::{CommandLogMessage, ErrorLogMessage, SessionLogMessage},
LogSender,
};
pub async fn log_command(log_tx: &LogSender, player_name: String, message: String) {
if let Err(error) = log_tx
.send(Box::new(CommandLogMessage::new(player_name, message)))
.await
{
... | (log_tx: &LogSender, message: String) {
if let Err(error) = log_tx.send(Box::new(ErrorLogMessage::new(message))).await {
println!("Could not send log message: {:?}", error);
}
}
pub async fn log_session_event(log_tx: &LogSender, source: String, message: String) {
if let Err(error) = log_tx
.... | log_error | identifier_name |
log_utils.rs | use super::{
log_messages::{CommandLogMessage, ErrorLogMessage, SessionLogMessage},
LogSender,
};
pub async fn log_command(log_tx: &LogSender, player_name: String, message: String) {
if let Err(error) = log_tx
.send(Box::new(CommandLogMessage::new(player_name, message)))
.await
{
... |
}
pub async fn log_session_event(log_tx: &LogSender, source: String, message: String) {
if let Err(error) = log_tx
.send(Box::new(SessionLogMessage::new(source, message)))
.await
{
println!("Could not send log message: {:?}", error);
}
}
| {
println!("Could not send log message: {:?}", error);
} | conditional_block |
log_utils.rs | use super::{
log_messages::{CommandLogMessage, ErrorLogMessage, SessionLogMessage},
LogSender, | .send(Box::new(CommandLogMessage::new(player_name, message)))
.await
{
println!("Could not send log message: {:?}", error);
}
}
pub async fn log_error(log_tx: &LogSender, message: String) {
if let Err(error) = log_tx.send(Box::new(ErrorLogMessage::new(message))).await {
printl... | };
pub async fn log_command(log_tx: &LogSender, player_name: String, message: String) {
if let Err(error) = log_tx | random_line_split |
entry.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
if attr::contains_name(item.attrs.as_slice(), "main") {
if ctxt.attr_main_fn.is_none() {
ctxt.attr_main_fn = Some((item.id, item.span));
} else {
ctxt.session.span_err(
item.span,
"multip... | {
match item.node {
ItemFn(..) => {
if item.ident.name == ctxt.main_name {
ctxt.ast_map.with_path(item.id, |mut path| {
if path.count() == 1 {
// This is a top-level function so can be 'main'
if ctxt... | identifier_body |
entry.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
impl<'a> Visitor<()> for EntryContext<'a> {
fn visit_item(&mut self, item: &Item, _:()) {
find_item(item, self);
}
}
pub fn find_entry_point(session: &Session, krate: &Crate, ast_map: &ast_map::Map) {
let any_exe = session.crate_types.borrow().iter().any(|ty| {
*ty == config::CrateTypeEx... |
// The functions that one might think are 'main' but aren't, e.g.
// main functions not defined at the top level. For diagnostics.
non_main_fns: Vec<(NodeId, Span)> , | random_line_split |
entry.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (item: &Item, ctxt: &mut EntryContext) {
match item.node {
ItemFn(..) => {
if item.ident.name == ctxt.main_name {
ctxt.ast_map.with_path(item.id, |mut path| {
if path.count() == 1 {
// This is a top-level function so can be'mai... | find_item | identifier_name |
client.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
}
fn validate_hash(path: PathBuf, hash: H256, result: Result<Response, FetchError>) -> Result<PathBuf, Error> {
let response = result?;
if!response.is_success() {
return Err(Error::InvalidStatus);
}
// Read the response
let mut reader = io::BufReader::new(response);
let mut writer = io::BufWriter::new(fs::Fi... | {
Error::IO(error)
} | identifier_body |
client.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | return Err(Error::InvalidStatus);
}
// Read the response
let mut reader = io::BufReader::new(response);
let mut writer = io::BufWriter::new(fs::File::create(&path)?);
io::copy(&mut reader, &mut writer)?;
writer.flush()?;
// And validate the hash
let mut file_reader = io::BufReader::new(fs::File::open(&path)... | }
fn validate_hash(path: PathBuf, hash: H256, result: Result<Response, FetchError>) -> Result<PathBuf, Error> {
let response = result?;
if !response.is_success() { | random_line_split |
client.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
}
/// Default Hash-fetching client using on-chain contract to resolve hashes to URLs.
pub struct Client<F: Fetch +'static = FetchClient> {
contract: URLHintContract,
fetch: F,
remote: Remote,
random_path: Arc<Fn() -> PathBuf + Sync + Send>,
}
impl Client {
/// Creates new instance of the `Client` given on-chain... | {
Ok(path)
} | conditional_block |
client.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (contract: Arc<ContractClient>, remote: Remote) -> Self {
Client::with_fetch(contract, FetchClient::new().unwrap(), remote)
}
}
impl<F: Fetch +'static> Client<F> {
/// Creates new instance of the `Client` given on-chain contract client, fetch service and task runner.
pub fn with_fetch(contract: Arc<ContractClient... | new | identifier_name |
std-smallintmap.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn check_sequential(min: uint, max: uint, map: &SmallIntMap<uint>) {
for i in range(min, max) {
assert_eq!(*map.get(&i), i + 22u);
}
}
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_owned(), "100000".to_owned(), "100".to_owned())
}... | {
for i in range(min, max) {
map.insert(i, i + 22u);
}
} | identifier_body |
std-smallintmap.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_owned(), "100000".to_owned(), "100".to_owned())
} else if args.len() <= 1u {
vec!("".to_owned(), "10000".to_owned(), "50".to_owned())
} else {
args.move_iter().collect()
};
let max = from... | random_line_split | |
std-smallintmap.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_owned(), "100000".to_owned(), "100".to_owned())
} else if args.len() <= 1u {
vec!("".to_owned(), "10000".to_owned(), "50".to_owned())
} else {
args.move_iter().collect()
};
let max =... | main | identifier_name |
std-smallintmap.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else if args.len() <= 1u {
vec!("".to_owned(), "10000".to_owned(), "50".to_owned())
} else {
args.move_iter().collect()
};
let max = from_str::<uint>(*args.get(1)).unwrap();
let rep = from_str::<uint>(*args.get(2)).unwrap();
let mut checkf = 0.0;
let mut appendf = 0.0;
for... | {
vec!("".to_owned(), "100000".to_owned(), "100".to_owned())
} | conditional_block |
scope.rs | use std::collections::HashMap;
use ast::Value;
#[derive(Clone)]
pub struct Scope {
// Maps variable names to values.
map: HashMap<String, Value>,
// The scope containing this one.
pub parent: Option<Box<Scope>>,
}
impl Scope {
pub fn new(parent: Option<Self>) -> Self {
Scope { map: HashMa... | (&self) -> Option<&Box<Scope>> {
self.parent.as_ref()
}
}
| parent | identifier_name |
scope.rs | use std::collections::HashMap;
use ast::Value;
#[derive(Clone)]
pub struct Scope {
// Maps variable names to values.
map: HashMap<String, Value>,
// The scope containing this one.
pub parent: Option<Box<Scope>>,
}
impl Scope {
pub fn new(parent: Option<Self>) -> Self { | }
// Assign a value to a given variable.
pub fn assign(&mut self, var: &str, val: Value) {
self.map.insert(String::from(var), val);
}
// Lookup the value associated with a given variable.
pub fn lookup(&self, var: &str) -> Option<&Value> {
self.map.get(var)
}
// Return... | Scope { map: HashMap::new(), parent: parent.map(Box::new) } | random_line_split |
scope.rs | use std::collections::HashMap;
use ast::Value;
#[derive(Clone)]
pub struct Scope {
// Maps variable names to values.
map: HashMap<String, Value>,
// The scope containing this one.
pub parent: Option<Box<Scope>>,
}
impl Scope {
pub fn new(parent: Option<Self>) -> Self {
Scope { map: HashMa... |
// Returns whether the variable is defined int the scope.
pub fn contains_var(&self, var: &str) -> bool {
self.map.contains_key(var)
}
// Returns number of variables in the scope.
pub fn len(&self) -> usize {
self.map.len()
}
// Returns a reference to the containing scope... | {
self.map.get(var)
} | identifier_body |
lib.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | <P: Plugin>(plugin: &mut P) {
mainloop(plugin).unwrap();
}
| start_mainloop | identifier_name |
lib.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | pub use crate::types::Config;
pub fn start_mainloop<P: Plugin>(plugin: &mut P) {
mainloop(plugin).unwrap();
} | random_line_split | |
lib.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | {
mainloop(plugin).unwrap();
} | identifier_body | |
renderer.rs | // This file is part of Mooneye GB.
// Copyright (C) 2014-2020 Joonas Javanainen <joonas.javanainen@gmail.com>
//
// Mooneye GB 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... |
const ASPECT_RATIO: f32 = mooneye_gb::SCREEN_WIDTH as f32 / mooneye_gb::SCREEN_HEIGHT as f32;
fn aspect_ratio_correction(width: u32, height: u32) -> (f32, f32) {
let fb_aspect_ratio = width as f32 / height as f32;
let scale = ASPECT_RATIO / fb_aspect_ratio;
if fb_aspect_ratio >= ASPECT_RATIO {
(scale, 1.0)... | {
texture.main_level().raw_upload_from_pixel_buffer(
pixel_buffer.as_slice(),
0..mooneye_gb::SCREEN_WIDTH as u32,
0..mooneye_gb::SCREEN_HEIGHT as u32,
0..1,
);
} | identifier_body |
renderer.rs | // This file is part of Mooneye GB.
// Copyright (C) 2014-2020 Joonas Javanainen <joonas.javanainen@gmail.com>
//
// Mooneye GB 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... | frame.draw(
&self.vertex_buffer,
&self.index_buffer,
&self.program,
&uniforms,
¶ms,
)?;
Ok(())
}
pub fn update_dimensions<F: Facade>(&mut self, display: &F) {
let (width, height) = display.get_context().get_framebuffer_dimensions();
let (x_scale, y_scale) = aspe... | }; | random_line_split |
renderer.rs | // This file is part of Mooneye GB.
// Copyright (C) 2014-2020 Joonas Javanainen <joonas.javanainen@gmail.com>
//
// Mooneye GB 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... | (width: u32, height: u32) -> (f32, f32) {
let fb_aspect_ratio = width as f32 / height as f32;
let scale = ASPECT_RATIO / fb_aspect_ratio;
if fb_aspect_ratio >= ASPECT_RATIO {
(scale, 1.0)
} else {
(1.0, 1.0 / scale)
}
}
impl Renderer {
pub fn new<F: Facade>(display: &F) -> Result<Renderer, Error> {... | aspect_ratio_correction | identifier_name |
issue-3979.rs | // xfail-test
// Reason: ICE with explicit self
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LI... | { x: int, y: int }
impl Positioned for Point {
fn SetX(&mut self, x: int) {
self.x = x;
}
fn X(&self) -> int {
self.x
}
}
impl Movable for Point;
pub fn main() {
let mut p = Point{ x: 1, y: 2};
p.translate(3);
assert_eq!(p.X(), 4);
}
| Point | identifier_name |
issue-3979.rs | // xfail-test
// Reason: ICE with explicit self
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LI... | {
let mut p = Point{ x: 1, y: 2};
p.translate(3);
assert_eq!(p.X(), 4);
} | identifier_body | |
issue-3979.rs | // xfail-test
// Reason: ICE with explicit self
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LI... | pub fn main() {
let mut p = Point{ x: 1, y: 2};
p.translate(3);
assert_eq!(p.X(), 4);
} | random_line_split | |
import-glob-circular.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn common() -> uint { return 0u; }
}
mod circ2 {
pub use circ1::f1;
pub fn f2() { info!("f2"); }
pub fn common() -> uint { return 1u; }
}
mod test {
use circ1::*;
fn test() { f1066(); }
}
| { info!("f1"); } | identifier_body |
import-glob-circular.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
mod circ1 {
pub use circ2::f2;
pub fn f1() { info!("f1"); }
pub fn common() -> uint { return 0u; }
}
mod circ2 {
pub use circ1::f1;
pub fn f2() { info!("f2"); }
pub fn common() -> uint { return 1u; }
}
mod test {
use circ1::*;
fn test() { f1066(); }
} | // error-pattern: unresolved | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.