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 |
|---|---|---|---|---|
htmlimageelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::{AttrHelpers, AttrValue};
use dom::bindings::cell::DOMRefCell;
use dom::bindin... |
fn after_set_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.after_set_attr(attr);
}
match attr.local_name() {
&atom!("src") => {
let window = window_from_node(*self);
let url = window.r().get_url();
... | {
let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
} | identifier_body |
htmlimageelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::{AttrHelpers, AttrValue};
use dom::bindings::cell::DOMRefCell;
use dom::bindin... | (&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.before_remove_attr(attr);
}
match attr.local_name() {
&atom!("src") => self.update_image(None),
_ => ()
}
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> At... | before_remove_attr | identifier_name |
htmlimageelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::{AttrHelpers, AttrValue};
use dom::bindings::cell::DOMRefCell;
use dom::bindin... | "load".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
let event = event.r();
let target = EventTargetCast::from_ref(node);
event.fire(target);
// Trigger reflow
... | let event = Event::new(GlobalRef::Window(window.r()), | random_line_split |
glue.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
use app_units::Au;
use bindings::{RawGeckoDocument, RawGeckoNode};
use bindings::{RawServo... |
#[no_mangle]
pub extern "C" fn Servo_StylesheetFromUTF8Bytes(bytes: *const u8,
length: u32) -> *mut RawServoStyleSheet {
let input = unsafe { from_utf8_unchecked(slice::from_raw_parts(bytes, length as usize)) };
// FIXME(heycam): Pass in the real base URL and s... | pub extern "C" fn Servo_DropNodeData(data: *mut ServoNodeData) -> () {
unsafe {
let _ = Box::<NonOpaqueStyleData>::from_raw(data as *mut NonOpaqueStyleData);
}
} | random_line_split |
glue.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
use app_units::Au;
use bindings::{RawGeckoDocument, RawGeckoNode};
use bindings::{RawServo... | (raw_sheet: *mut RawServoStyleSheet,
raw_data: *mut RawServoStyleSet) {
type Helpers = ArcHelpers<RawServoStyleSheet, Stylesheet>;
let data = PerDocumentStyleData::borrow_mut_from_raw(raw_data);
Helpers::with(raw_sheet, |sheet| {
data.stylesheets.retain(|x|!a... | Servo_AppendStyleSheet | identifier_name |
glue.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
use app_units::Au;
use bindings::{RawGeckoDocument, RawGeckoNode};
use bindings::{RawServo... |
pub struct ArcHelpers<GeckoType, ServoType> {
phantom1: PhantomData<GeckoType>,
phantom2: PhantomData<ServoType>,
}
impl<GeckoType, ServoType> ArcHelpers<GeckoType, ServoType> {
pub fn with<F, Output>(raw: *mut GeckoType, cb: F) -> Output
where F: FnOnce(&Arc<ServoType>) -> Out... | {
let input = unsafe { from_utf8_unchecked(slice::from_raw_parts(bytes, length as usize)) };
// FIXME(heycam): Pass in the real base URL and sheet origin to use.
let url = Url::parse("about:none").unwrap();
let sheet = Arc::new(Stylesheet::from_str(input, url, Origin::Author, Box::new(StdoutErrorRepor... | identifier_body |
glue.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
use app_units::Au;
use bindings::{RawGeckoDocument, RawGeckoNode};
use bindings::{RawServo... |
}
#[no_mangle]
pub extern "C" fn Servo_DropNodeData(data: *mut ServoNodeData) -> () {
unsafe {
let _ = Box::<NonOpaqueStyleData>::from_raw(data as *mut NonOpaqueStyleData);
}
}
#[no_mangle]
pub extern "C" fn Servo_StylesheetFromUTF8Bytes(bytes: *const u8,
... | {
parallel::traverse_dom::<GeckoNode, RecalcStyleOnly>(node, &shared_style_context, &mut data.work_queue);
} | conditional_block |
util.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 ... |
/// Get's the number of scheduler threads requested by the environment
/// either `RUST_THREADS` or `num_cpus`.
pub fn default_sched_threads() -> uint {
match os::getenv("RUST_THREADS") {
Some(nstr) => {
let opt_n: Option<uint> = FromStr::from_str(nstr);
match opt_n {
... | {
(cfg!(target_os="macos")) && running_on_valgrind()
} | identifier_body |
util.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 ... | use os;
use str::StrSlice;
use unstable::running_on_valgrind;
use vec::ImmutableVector;
// Indicates whether we should perform expensive sanity checks, including rtassert!
// XXX: Once the runtime matures remove the `true` below to turn off rtassert, etc.
pub static ENFORCE_SANITY: bool = true ||!cfg!(rtopt) || cfg!(r... | use from_str::FromStr;
use iter::Iterator;
use libc;
use option::{Some, None, Option}; | random_line_split |
util.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
}
}
pub fn dumb_println(args: &fmt::Arguments) {
use io;
use libc;
struct Stderr;
impl io::Writer for Stderr {
fn write(&mut self, data: &[u8]) {
unsafe {
libc::write(libc::STDERR_FILENO,
data.as_ptr() as *libc::c_void,
... | {
num_cpus()
} | conditional_block |
util.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 { libc::abort() }
}
}
| t() - | identifier_name |
main.rs | use std::env;
use std::ffi::OsStr;
use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
macro_rules! except {
($error:ident, $extra:tt) => {{
let stderr = std::io::stderr();
let mut stderr = stderr.lock();
let _ = writeln!(&mut stderr, "{}", $extra);
let _ ... | "--" => {
skip_switches = true;
continue;
}
_ => {
eprintln!("{}: Invalid option!", arg);
eprintln!("");
help(&mut std::io::stderr(), false)... | {
let args = std::env::args_os();
let mut file = None;
let mut skip_switches = false;
for arg_os in args.skip(1) {
if let Some(arg) = arg_os.to_str() {
if !skip_switches && arg.starts_with("-") && arg != "-" {
match arg {
"-h" | "--help" => {
... | identifier_body |
main.rs | use std::env;
use std::ffi::OsStr;
use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
macro_rules! except {
($error:ident, $extra:tt) => {{
let stderr = std::io::stderr();
let mut stderr = stderr.lock();
let _ = writeln!(&mut stderr, "{}", $extra);
let _ ... | help(&mut std::io::stderr(), false);
eprintln!("Try'rewrite --help' for more information");
std::process::exit(-1);
}
}
}
}
if file.replace(arg_os).is_some() {
// A desti... | {
match arg {
"-h" | "--help" => {
help(&mut std::io::stdout(), true);
std::process::exit(0);
}
"-V" | "--version" => {
version(&mut std::io::stdout());
... | conditional_block |
main.rs | use std::env;
use std::ffi::OsStr;
use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
macro_rules! except {
($error:ident, $extra:tt) => {{
let stderr = std::io::stderr();
let mut stderr = stderr.lock();
let _ = writeln!(&mut stderr, "{}", $extra);
let _ ... | (path: &Path) -> PathBuf {
let old_name = path
.file_name()
.expect("Received path to directory instead of file!");
let mut new_name = std::ffi::OsString::new();
new_name.push(".");
new_name.push(old_name);
// Freeze its current value, because it'll serve as a template
let new_nam... | get_temp_dest | identifier_name |
main.rs | use std::env;
use std::ffi::OsStr;
use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
macro_rules! except {
($error:ident, $extra:tt) => {{
let stderr = std::io::stderr();
let mut stderr = stderr.lock();
let _ = writeln!(&mut stderr, "{}", $extra);
let _ ... | };
redirect_to_file(&file);
} | random_line_split | |
logistic.rs | //! Provides the [logistic](http://en.wikipedia.org/wiki/Logistic_function) and
//! related functions
use crate::error::StatsError;
use crate::Result;
/// Computes the logistic function
pub fn logistic(p: f64) -> f64 {
1.0 / ((-p).exp() + 1.0)
}
/// Computes the logit function
///
/// # Panics
///
/// If `p < 0.... | assert_eq!(super::logit(1.0), f64::INFINITY);
}
#[test]
#[should_panic]
fn test_logit_p_lt_0() {
super::logit(-1.0);
}
#[test]
#[should_panic]
fn test_logit_p_gt_1() {
super::logit(2.0);
}
#[test]
fn test_checked_logit_p_lt_0() {
assert!(sup... | random_line_split | |
logistic.rs | //! Provides the [logistic](http://en.wikipedia.org/wiki/Logistic_function) and
//! related functions
use crate::error::StatsError;
use crate::Result;
/// Computes the logistic function
pub fn logistic(p: f64) -> f64 {
1.0 / ((-p).exp() + 1.0)
}
/// Computes the logit function
///
/// # Panics
///
/// If `p < 0.... |
#[test]
#[should_panic]
fn test_logit_p_gt_1() {
super::logit(2.0);
}
#[test]
fn test_checked_logit_p_lt_0() {
assert!(super::checked_logit(-1.0).is_err());
}
#[test]
fn test_checked_logit_p_gt_1() {
assert!(super::checked_logit(2.0).is_err());
}
}
| {
super::logit(-1.0);
} | identifier_body |
logistic.rs | //! Provides the [logistic](http://en.wikipedia.org/wiki/Logistic_function) and
//! related functions
use crate::error::StatsError;
use crate::Result;
/// Computes the logistic function
pub fn logistic(p: f64) -> f64 {
1.0 / ((-p).exp() + 1.0)
}
/// Computes the logit function
///
/// # Panics
///
/// If `p < 0.... |
}
#[rustfmt::skip]
#[cfg(test)]
mod tests {
use std::f64;
#[test]
fn test_logistic() {
assert_eq!(super::logistic(f64::NEG_INFINITY), 0.0);
assert_eq!(super::logistic(-11.512915464920228103874353849992239636376994324587), 0.00001);
assert_almost_eq!(super::logistic(-6.906754778648... | {
Ok((p / (1.0 - p)).ln())
} | conditional_block |
logistic.rs | //! Provides the [logistic](http://en.wikipedia.org/wiki/Logistic_function) and
//! related functions
use crate::error::StatsError;
use crate::Result;
/// Computes the logistic function
pub fn logistic(p: f64) -> f64 {
1.0 / ((-p).exp() + 1.0)
}
/// Computes the logit function
///
/// # Panics
///
/// If `p < 0.... | () {
super::logit(2.0);
}
#[test]
fn test_checked_logit_p_lt_0() {
assert!(super::checked_logit(-1.0).is_err());
}
#[test]
fn test_checked_logit_p_gt_1() {
assert!(super::checked_logit(2.0).is_err());
}
}
| test_logit_p_gt_1 | identifier_name |
set_packing.rs | use bit_vector::BitVector;
pub fn | (subsets: &Vec<Vec<u8>>) -> Vec<usize> {
let bit_vectors = subsets.iter().map(BitVector::from_vec).collect::<Vec<_>>();
let mut packing = vec![];
let mut available_subsets_indexes = (0..subsets.len()).collect::<Vec<_>>();
loop {
// Select the smallest subset that hasn't been used yet.
... | maximum_set_packing | identifier_name |
set_packing.rs | use bit_vector::BitVector;
pub fn maximum_set_packing(subsets: &Vec<Vec<u8>>) -> Vec<usize> | }
}
}
}
| {
let bit_vectors = subsets.iter().map(BitVector::from_vec).collect::<Vec<_>>();
let mut packing = vec![];
let mut available_subsets_indexes = (0..subsets.len()).collect::<Vec<_>>();
loop {
// Select the smallest subset that hasn't been used yet.
// To find a minimum set packing, simpl... | identifier_body |
set_packing.rs |
pub fn maximum_set_packing(subsets: &Vec<Vec<u8>>) -> Vec<usize> {
let bit_vectors = subsets.iter().map(BitVector::from_vec).collect::<Vec<_>>();
let mut packing = vec![];
let mut available_subsets_indexes = (0..subsets.len()).collect::<Vec<_>>();
loop {
// Select the smallest subset that has... | use bit_vector::BitVector; | random_line_split | |
dim4.rs | use poisson::Type::*;
extern crate nalgebra as na;
pub type Vect = na::Vector4<f64>;
mod helper;
use crate::helper::test_with_samples;
#[test]
fn test_4d_1_80_normal() {
test_with_samples::<Vect>(1, 0.8, 200, Normal);
}
#[test]
fn test_4d_1_80_perioditic() {
test_with_samples::<Vect>(1, 0.8, 100, Perioditic... | #[test]
fn test_4d_10_80_perioditic() {
test_with_samples::<Vect>(10, 0.8, 15, Perioditic);
}
#[test]
fn test_4d_100_80_normal() {
test_with_samples::<Vect>(100, 0.8, 10, Normal);
}
#[test]
fn test_4d_100_80_perioditic() {
test_with_samples::<Vect>(100, 0.8, 1, Perioditic);
} | fn test_4d_10_80_normal() {
test_with_samples::<Vect>(10, 0.8, 50, Normal);
}
| random_line_split |
dim4.rs | use poisson::Type::*;
extern crate nalgebra as na;
pub type Vect = na::Vector4<f64>;
mod helper;
use crate::helper::test_with_samples;
#[test]
fn test_4d_1_80_normal() {
test_with_samples::<Vect>(1, 0.8, 200, Normal);
}
#[test]
fn test_4d_1_80_perioditic() {
test_with_samples::<Vect>(1, 0.8, 100, Perioditic... | () {
test_with_samples::<Vect>(10, 0.8, 50, Normal);
}
#[test]
fn test_4d_10_80_perioditic() {
test_with_samples::<Vect>(10, 0.8, 15, Perioditic);
}
#[test]
fn test_4d_100_80_normal() {
test_with_samples::<Vect>(100, 0.8, 10, Normal);
}
#[test]
fn test_4d_100_80_perioditic() {
test_with_samples::<Vec... | test_4d_10_80_normal | identifier_name |
dim4.rs | use poisson::Type::*;
extern crate nalgebra as na;
pub type Vect = na::Vector4<f64>;
mod helper;
use crate::helper::test_with_samples;
#[test]
fn test_4d_1_80_normal() {
test_with_samples::<Vect>(1, 0.8, 200, Normal);
}
#[test]
fn test_4d_1_80_perioditic() |
#[test]
fn test_4d_10_80_normal() {
test_with_samples::<Vect>(10, 0.8, 50, Normal);
}
#[test]
fn test_4d_10_80_perioditic() {
test_with_samples::<Vect>(10, 0.8, 15, Perioditic);
}
#[test]
fn test_4d_100_80_normal() {
test_with_samples::<Vect>(100, 0.8, 10, Normal);
}
#[test]
fn test_4d_100_80_perioditi... | {
test_with_samples::<Vect>(1, 0.8, 100, Perioditic);
} | identifier_body |
tls.rs | #[macro_use] extern crate log;
extern crate env_logger;
extern crate futures;
extern crate lapin_futures as lapin;
extern crate rustls;
extern crate tokio_core;
extern crate tokio_rustls;
extern crate webpki_roots;
use futures::future::Future;
use lapin::client::ConnectionOptions;
use lapin::channel::ConfirmSelectOpti... |
let mut config = ClientConfig::new();
config.root_store.add_trust_anchors(&webpki_roots::ROOTS);
let config = Arc::new(config);
let mut core = Core::new().unwrap();
let handle = core.handle();
let raw_stream = std::net::TcpStream::connect((host, port)).unwrap();
core.run(
TcpStream::from_s... | random_line_split | |
tls.rs | #[macro_use] extern crate log;
extern crate env_logger;
extern crate futures;
extern crate lapin_futures as lapin;
extern crate rustls;
extern crate tokio_core;
extern crate tokio_rustls;
extern crate webpki_roots;
use futures::future::Future;
use lapin::client::ConnectionOptions;
use lapin::channel::ConfirmSelectOpti... | username: username.to_string(),
password: password.to_string(),
..Default::default()
})
}).and_then(|(client, _)| {
client.create_confirm_channel(ConfirmSelectOptions::default()).and_then(|channel| {
let id = channel.id;
info!("created channel with id: {}", id);
... | {
env_logger::init().unwrap();
let host = "localhost";
let port = 5671;
let username = "guest";
let password = "guest";
let mut config = ClientConfig::new();
config.root_store.add_trust_anchors(&webpki_roots::ROOTS);
let config = Arc::new(config);
let mut core = Core::new().unw... | identifier_body |
tls.rs | #[macro_use] extern crate log;
extern crate env_logger;
extern crate futures;
extern crate lapin_futures as lapin;
extern crate rustls;
extern crate tokio_core;
extern crate tokio_rustls;
extern crate webpki_roots;
use futures::future::Future;
use lapin::client::ConnectionOptions;
use lapin::channel::ConfirmSelectOpti... | () {
env_logger::init().unwrap();
let host = "localhost";
let port = 5671;
let username = "guest";
let password = "guest";
let mut config = ClientConfig::new();
config.root_store.add_trust_anchors(&webpki_roots::ROOTS);
let config = Arc::new(config);
let mut core = Core::new().... | main | identifier_name |
schnorr.rs | // Bitcoin secp256k1 bindings
// Written in 2014 by
// Dawid Ciężarkiewicz
// Andrew Poelstra
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warra... | /// Verify a Schnorr signature
pub fn verify_schnorr(&self, msg: &Message, sig: &Signature, pk: &PublicKey) -> Result<(), Error> {
if self.caps == ContextFlag::SignOnly || self.caps == ContextFlag::None {
return Err(Error::IncapableContext);
}
if!pk.is_valid() {
... | if self.caps == ContextFlag::VerifyOnly || self.caps == ContextFlag::None {
return Err(Error::IncapableContext);
}
let mut ret: Signature = unsafe { mem::uninitialized() };
unsafe {
// We can assume the return value because it's not possible to construct
... | identifier_body |
schnorr.rs | // Bitcoin secp256k1 bindings
// Written in 2014 by
// Dawid Ciężarkiewicz
// Andrew Poelstra
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warra... | self, msg: &Message, sk: &SecretKey) -> Result<Signature, Error> {
if self.caps == ContextFlag::VerifyOnly || self.caps == ContextFlag::None {
return Err(Error::IncapableContext);
}
let mut ret: Signature = unsafe { mem::uninitialized() };
unsafe {
// We can assu... | gn_schnorr(& | identifier_name |
schnorr.rs | // Bitcoin secp256k1 bindings
// Written in 2014 by
// Dawid Ciężarkiewicz
// Andrew Poelstra
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warra... |
let mut pk = unsafe { ffi::PublicKey::blank() };
unsafe {
if ffi::secp256k1_schnorr_recover(self.ctx, &mut pk,
sig.as_ptr(), msg.as_ptr())!= 1 {
return Err(Error::InvalidSignature);
}
};
Ok(PublicKey::... | -> Result<PublicKey, Error> {
if self.caps == ContextFlag::SignOnly || self.caps == ContextFlag::None {
return Err(Error::IncapableContext);
} | random_line_split |
schnorr.rs | // Bitcoin secp256k1 bindings
// Written in 2014 by
// Dawid Ciężarkiewicz
// Andrew Poelstra
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warra... | let mut pk = unsafe { ffi::PublicKey::blank() };
unsafe {
if ffi::secp256k1_schnorr_recover(self.ctx, &mut pk,
sig.as_ptr(), msg.as_ptr())!= 1 {
return Err(Error::InvalidSignature);
}
};
Ok(PublicKey::f... | return Err(Error::IncapableContext);
}
| conditional_block |
environ.rs | use std::env;
use std::collections::BTreeSet;
use regex::{Regex, escape};
use failure::{Error, err_msg, ResultExt};
use crate::config::read_settings::MergedSettings;
fn patterns_to_regex(patterns: &BTreeSet<String>) -> Result<Regex, Error> |
pub fn set_initial_vaggaenv_vars(
propagate_env: Vec<String>, set_env: Vec<String>,
settings: &MergedSettings)
-> Result<(), Error>
{
for k in propagate_env.into_iter() {
if k.chars().find(|&c| c == '=').is_some() {
return Err(err_msg("Environment variable name \
(... | {
let mut var_pattern = String::with_capacity(100);
for item in patterns {
if var_pattern.len() > 0 {
var_pattern.push('|');
}
var_pattern.push('^');
var_pattern.push_str(&escape(item).replace(r"\*", ".*"));
var_pattern.push('$');
}
debug!("Propagation... | identifier_body |
environ.rs | use std::env;
use std::collections::BTreeSet;
use regex::{Regex, escape};
use failure::{Error, err_msg, ResultExt};
use crate::config::read_settings::MergedSettings;
fn patterns_to_regex(patterns: &BTreeSet<String>) -> Result<Regex, Error> {
let mut var_pattern = String::with_capacity(100);
for item in pat... | } else {
env::set_var(&("VAGGAENV_".to_string() + &k[..]),
env::var_os(&k).unwrap_or(From::from("")));
}
}
for pair in set_env.into_iter() {
let mut pairiter = pair[..].splitn(2, '=');
let key = "VAGGAENV_".to_string() + pairiter.next().unwrap();
... | (for option `-e`/`--use-env`) \
can't contain equals `=` character. \
To set key-value pair use `-E`/`--environ` option")); | random_line_split |
environ.rs | use std::env;
use std::collections::BTreeSet;
use regex::{Regex, escape};
use failure::{Error, err_msg, ResultExt};
use crate::config::read_settings::MergedSettings;
fn patterns_to_regex(patterns: &BTreeSet<String>) -> Result<Regex, Error> {
let mut var_pattern = String::with_capacity(100);
for item in pat... | (
propagate_env: Vec<String>, set_env: Vec<String>,
settings: &MergedSettings)
-> Result<(), Error>
{
for k in propagate_env.into_iter() {
if k.chars().find(|&c| c == '=').is_some() {
return Err(err_msg("Environment variable name \
(for option `-e`/`--use-env`) \
... | set_initial_vaggaenv_vars | identifier_name |
environ.rs | use std::env;
use std::collections::BTreeSet;
use regex::{Regex, escape};
use failure::{Error, err_msg, ResultExt};
use crate::config::read_settings::MergedSettings;
fn patterns_to_regex(patterns: &BTreeSet<String>) -> Result<Regex, Error> {
let mut var_pattern = String::with_capacity(100);
for item in pat... |
}
for pair in set_env.into_iter() {
let mut pairiter = pair[..].splitn(2, '=');
let key = "VAGGAENV_".to_string() + pairiter.next().unwrap();
if let Some(value) = pairiter.next() {
env::set_var(&key, value.to_string());
} else {
env::remove_var(&key);
... | {
env::set_var(&("VAGGAENV_".to_string() + &k[..]),
env::var_os(&k).unwrap_or(From::from("")));
} | conditional_block |
lib.rs | //! Rsure is a set of utilities for capturing information about files, and later verifying it is
//! still true.
//!
//! The easiest way to use Rsure is to build the `rsure` executable contained in this crate. This
//! program allows you to use most of the functionality of the crate.
//!
//! However, it is also possib... | tmp
};
tmp
} else {
let mut tmp = store.make_temp()?;
let src = fs::scan_fs(dir)?.inspect(|node| {
if let Ok(n @ SureNode::File {.. }) = node {
if n.needs_hash() {
estimate.files += 1;
estimate.bytes += ... | }
}
});
node::save_to(&mut tmp, combiner)?; | random_line_split |
lib.rs | //! Rsure is a set of utilities for capturing information about files, and later verifying it is
//! still true.
//!
//! The easiest way to use Rsure is to build the `rsure` executable contained in this crate. This
//! program allows you to use most of the functionality of the crate.
//!
//! However, it is also possib... |
.into_loader()?;
// TODO: If this is an update, pull in hashes from the old version.
// Update any missing hashes.
let loader = Loader(&*tmp);
let hu = HashUpdater::new(loader, store);
// TODO: This will panic on non-unicode directories.
let hm = hu.compute_parallel(dir.to_str().unwrap(), ... | {
let mut tmp = store.make_temp()?;
let src = fs::scan_fs(dir)?.inspect(|node| {
if let Ok(n @ SureNode::File { .. }) = node {
if n.needs_hash() {
estimate.files += 1;
estimate.bytes += n.size();
}
}
... | conditional_block |
lib.rs | //! Rsure is a set of utilities for capturing information about files, and later verifying it is
//! still true.
//!
//! The easiest way to use Rsure is to build the `rsure` executable contained in this crate. This
//! program allows you to use most of the functionality of the crate.
//!
//! However, it is also possib... | (&self) -> Result<Box<dyn Iterator<Item = Result<SureNode>> + Send>> {
let rd = File::open(self.0.path_ref())?;
Ok(Box::new(load_from(rd)?))
}
}
| iter | identifier_name |
lib.rs | //! Rsure is a set of utilities for capturing information about files, and later verifying it is
//! still true.
//!
//! The easiest way to use Rsure is to build the `rsure` executable contained in this crate. This
//! program allows you to use most of the functionality of the crate.
//!
//! However, it is also possib... | if let Ok(n @ SureNode::File {.. }) = node {
if n.needs_hash() {
estimate.files += 1;
estimate.bytes += n.size();
}
}
});
node::save_to(&mut tmp, combiner)?;
tmp
... | {
let dir = dir.as_ref();
let mut estimate = Estimate { files: 0, bytes: 0 };
let tmp = if is_update {
// In update mode, first tmp file is just the scan.
let scan_temp = {
let mut tmp = store.make_temp()?;
let src = fs::scan_fs(dir)?;
node::save_to(&mut ... | identifier_body |
crate-method-reexport-grrrrrrr2.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 ... | (&self) {
}
}
}
| cx | identifier_name |
crate-method-reexport-grrrrrrr2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // 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 distributed
// except according to those terms.
#![feature(managed_boxes)]
#![crate_id="crate_method_reexport_grrrrrrr2"]
pub use name_... | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
crate-method-reexport-grrrrrrr2.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 mod rust {
pub use name_pool::add;
pub type rt = @();
pub trait cx {
fn cx(&self);
}
impl cx for rt {
fn cx(&self) {
}
}
}
| {
} | identifier_body |
terminate.rs | use crate::protocol;
use super::{HandleResult,
Handler};
use crate::server::ServiceTable;
pub struct TerminateHandler;
impl Handler for TerminateHandler {
type Message = protocol::Terminate;
type Reply = protocol::TerminateOk;
fn | (msg: Self::Message, services: &mut ServiceTable) -> HandleResult<Self::Reply> {
match services.get_mut(msg.pid as u32) {
Some(service) => {
debug!("Terminating: {}", service.id());
let shutdown_method = service.kill();
match service.wait() {
... | handle | identifier_name |
terminate.rs | use crate::protocol;
use super::{HandleResult,
Handler};
use crate::server::ServiceTable; | impl Handler for TerminateHandler {
type Message = protocol::Terminate;
type Reply = protocol::TerminateOk;
fn handle(msg: Self::Message, services: &mut ServiceTable) -> HandleResult<Self::Reply> {
match services.get_mut(msg.pid as u32) {
Some(service) => {
debug!("Termi... |
pub struct TerminateHandler; | random_line_split |
credentials.rs | // Copyright 2018 Benjamin Bader
// Copyright 2016 Mozilla Foundation
//
// 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 req... |
#[test]
fn test_conn_str_with_endpoint_suffix_only() {
let conn = "DefaultEndpointsProtocol=https;AccountName=foo;EndpointSuffix=core.windows.net;AccountKey=bar;";
let creds = parse_connection_string(&conn, "container".to_string()).unwrap();
assert_eq!(
"https://foo.blob.c... | {
let conn = "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;";
let creds = parse_connection_string(&conn, "container".to_string()).unwrap();
assert_eq!(
"http://127.0.0.1:10000/devstoreaccount1/",
creds.az... | identifier_body |
credentials.rs | // Copyright 2018 Benjamin Bader
// Copyright 2016 Mozilla Foundation
//
// 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 req... | (
blob_endpoint: &str,
account_name: &str,
account_key: Option<String>,
container_name: String,
) -> AzureCredentials {
let endpoint = if blob_endpoint.ends_with('/') {
blob_endpoint.to_owned()
} else {
blob_endpoint.to_owned() + "/"
};... | new | identifier_name |
credentials.rs | // Copyright 2018 Benjamin Bader
// Copyright 2016 Mozilla Foundation
//
// 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 req... | &self.container_name
}
}
pub trait AzureCredentialsProvider {
fn provide_credentials(&self) -> Result<AzureCredentials>;
}
pub struct EnvironmentProvider;
impl AzureCredentialsProvider for EnvironmentProvider {
fn provide_credentials(&self) -> Result<AzureCredentials> {
credentials_from_e... | pub fn blob_container_name(&self) -> &str { | random_line_split |
credentials.rs | // Copyright 2018 Benjamin Bader
// Copyright 2016 Mozilla Foundation
//
// 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 req... | ;
AzureCredentials {
blob_endpoint: endpoint,
account_name: account_name.to_owned(),
account_key,
container_name,
}
}
pub fn azure_blob_endpoint(&self) -> &str {
&self.blob_endpoint
}
pub fn azure_account_name(&self) -> &str {
... | {
blob_endpoint.to_owned() + "/"
} | conditional_block |
site_db.rs | use uuid::Uuid;
use deadpool_postgres::{Pool, Manager};
use crate::api::query::Query;
use std::str::FromStr;
pub struct SiteDB {
pool: Pool,
}
impl SiteDB {
pub async fn new(connection_string: &str) -> Result<SiteDB, anyhow::Error> {
let config = tokio_postgres::Config::from_str(connection_string)?... | Ok(client) => client,
Err(err) => {
eprintln!("can't get client: {:?}", err);
return None;
}
};
let rs =
match client.query("SELECT id::uuid FROM query WHERE digest(query_json,'sha256') = digest($1,'... | }
};
let client =
match self.pool.get().await { | random_line_split |
site_db.rs | use uuid::Uuid;
use deadpool_postgres::{Pool, Manager};
use crate::api::query::Query;
use std::str::FromStr;
pub struct SiteDB {
pool: Pool,
}
impl SiteDB {
pub async fn new(connection_string: &str) -> Result<SiteDB, anyhow::Error> {
let config = tokio_postgres::Config::from_str(connection_string)?... | &[uuid, &serde_value]).await {
Ok(_) => (),
Err(e) => return Err(format!("error executing query: {}", e)),
};
match trans.commit().await {
Ok(_) => Ok(()),
Err(e) => Err(format!("error saving query: {}", e)),
}
}
}... | {
let mut client =
match self.pool.get().await {
Ok(client) => client,
Err(err) => {
return Err(format!("error saving query: {}", err));
},
};
let trans = match client.transaction().await {
Ok(t) => ... | identifier_body |
site_db.rs | use uuid::Uuid;
use deadpool_postgres::{Pool, Manager};
use crate::api::query::Query;
use std::str::FromStr;
pub struct SiteDB {
pool: Pool,
}
impl SiteDB {
pub async fn new(connection_string: &str) -> Result<SiteDB, anyhow::Error> {
let config = tokio_postgres::Config::from_str(connection_string)?... | (&self, uuid: &Uuid) -> Option<Query> {
let client =
match self.pool.get().await {
Ok(client) => client,
Err(err) => {
eprintln!("error querying by ID: {}", err);
return None;
},
};
let rs =
... | query_by_id | identifier_name |
heat.rs | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... | else {
debug!(
"Rumor does not exist in map; was probably deleted between retrieval \
and sending"
);
}
}
}
}
}
impl Default for RumorHeat {
fn default() -> RumorHeat {
RumorHea... | {
let heat_map = rumor_map.get_mut(&rk).unwrap();
if heat_map.contains_key(id) {
let heat = heat_map.get_mut(id).unwrap();
*heat += 1;
} else {
heat_map.insert(String::from(id), 1);
... | conditional_block |
heat.rs | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... | .expect("RumorHeat lock poisoned")
.iter()
.map(|(k, heat_map)| (k.clone(), heat_map.get(id).unwrap_or(&0).clone()))
.filter(|&(_, heat)| heat < RUMOR_COOL_DOWN_LIMIT)
.collect();
// Reverse sorting by heat; 0s come last!
rumor_heat.sort_by(|&(_, r... | pub fn currently_hot_rumors(&self, id: &str) -> Vec<RumorKey> {
let mut rumor_heat: Vec<(RumorKey, usize)> = self.0
.read() | random_line_split |
heat.rs | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... |
fn write_to_bytes(&self) -> Result<Vec<u8>> {
Ok(Vec::from(format!("{}-{}", self.id, self.key).as_bytes()))
}
}
/// Helper function that tests that a given rumor is currently
/// considered "hot" for the given member.
fn assert_rumor_is_hot<T>(heat: &RumorHeat, member_id: ... | {
false
} | identifier_body |
heat.rs | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... | () {
let heat = RumorHeat::default();
let member_id = "test_member";
let rumor = FakeRumor::default();
heat.start_hot_rumor(&rumor);
let hot_rumors = heat.currently_hot_rumors(&member_id);
assert_eq!(hot_rumors.len(), 1);
assert_eq!(hot_rumors[0], RumorKey::from... | a_hot_rumor_is_returned_as_such | identifier_name |
reshape3to2.rs | use mli::*;
use ndarray::{Array2, Array3, ArrayBase, Axis, Data};
use std::marker::PhantomData;
type D3 = ndarray::Ix3;
#[derive(Clone, Debug)]
pub struct Reshape3to2<S>(PhantomData<S>);
impl<S> Reshape3to2<S>
where
S: Data,
{
pub fn new() -> Self {
Default::default()
}
}
impl<S> Default for Res... | S::Elem: Clone,
{
type Input = ArrayBase<S, D3>;
type Internal = ();
type Output = Array2<S::Elem>;
fn forward(&self, input: &Self::Input) -> ((), Self::Output) {
((), input.to_owned().index_axis_move(Axis(0), 0))
}
}
impl<S> Backward for Reshape3to2<S>
where
S: Data,
S::Elem: ... | S: Data, | random_line_split |
reshape3to2.rs | use mli::*;
use ndarray::{Array2, Array3, ArrayBase, Axis, Data};
use std::marker::PhantomData;
type D3 = ndarray::Ix3;
#[derive(Clone, Debug)]
pub struct Reshape3to2<S>(PhantomData<S>);
impl<S> Reshape3to2<S>
where
S: Data,
{
pub fn new() -> Self {
Default::default()
}
}
impl<S> Default for Res... |
}
impl<S> Backward for Reshape3to2<S>
where
S: Data,
S::Elem: Clone,
{
type OutputDelta = Array2<S::Elem>;
type InputDelta = Array3<S::Elem>;
// TODO: This is bad, but done to allow multiplying by f32.
type TrainDelta = f32;
fn backward(
&self,
_: &Self::Input,
_: ... | {
((), input.to_owned().index_axis_move(Axis(0), 0))
} | identifier_body |
reshape3to2.rs | use mli::*;
use ndarray::{Array2, Array3, ArrayBase, Axis, Data};
use std::marker::PhantomData;
type D3 = ndarray::Ix3;
#[derive(Clone, Debug)]
pub struct Reshape3to2<S>(PhantomData<S>);
impl<S> Reshape3to2<S>
where
S: Data,
{
pub fn new() -> Self {
Default::default()
}
}
impl<S> Default for Res... | (&self, input: &Self::Input) -> ((), Self::Output) {
((), input.to_owned().index_axis_move(Axis(0), 0))
}
}
impl<S> Backward for Reshape3to2<S>
where
S: Data,
S::Elem: Clone,
{
type OutputDelta = Array2<S::Elem>;
type InputDelta = Array3<S::Elem>;
// TODO: This is bad, but done to allow... | forward | identifier_name |
main.rs | #![feature(slice_patterns)]
extern crate nix;
extern crate libc;
use std::{env, ptr, mem, fmt};
use libc::{pid_t, c_void, waitpid};
use nix::sys::ptrace;
use nix::sys::ptrace::ptrace::{PTRACE_ATTACH, PTRACE_DETACH, PTRACE_GETREGS, PTRACE_POKETEXT,
PTRACE_SETREGS};
// #[cfg(target_arch = ... |
_ => unimplemented!(),
}
}
| {
infect(pid.parse::<i32>().unwrap(), &[]);
} | conditional_block |
main.rs | #![feature(slice_patterns)]
extern crate nix;
extern crate libc;
use std::{env, ptr, mem, fmt};
use libc::{pid_t, c_void, waitpid};
use nix::sys::ptrace;
use nix::sys::ptrace::ptrace::{PTRACE_ATTACH, PTRACE_DETACH, PTRACE_GETREGS, PTRACE_POKETEXT,
PTRACE_SETREGS};
// #[cfg(target_arch = ... | () {
let args: Vec<String> = env::args().collect();
match &args[1..] {
&[ref pid, ref code] => {
infect(pid.parse::<i32>().unwrap(), &[]);
}
_ => unimplemented!(),
}
}
| main | identifier_name |
main.rs | #![feature(slice_patterns)]
extern crate nix;
extern crate libc;
use std::{env, ptr, mem, fmt};
use libc::{pid_t, c_void, waitpid};
use nix::sys::ptrace;
use nix::sys::ptrace::ptrace::{PTRACE_ATTACH, PTRACE_DETACH, PTRACE_GETREGS, PTRACE_POKETEXT,
PTRACE_SETREGS};
// #[cfg(target_arch = ... | &mut regs as *mut user_regs_struct as *mut c_void)
.unwrap(),
0);
for byte in buffer {
// ptrace::ptrace(PTRACE_POKETEXT,
// pid,
// regs.rsp as *mut libc::c_void,
// regs.rip ... | random_line_split | |
main.rs | #![feature(slice_patterns)]
extern crate nix;
extern crate libc;
use std::{env, ptr, mem, fmt};
use libc::{pid_t, c_void, waitpid};
use nix::sys::ptrace;
use nix::sys::ptrace::ptrace::{PTRACE_ATTACH, PTRACE_DETACH, PTRACE_GETREGS, PTRACE_POKETEXT,
PTRACE_SETREGS};
// #[cfg(target_arch = ... | {
let args: Vec<String> = env::args().collect();
match &args[1..] {
&[ref pid, ref code] => {
infect(pid.parse::<i32>().unwrap(), &[]);
}
_ => unimplemented!(),
}
} | identifier_body | |
asm.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
-> Block<'blk, 'tcx> {
let fcx = bcx.fcx;
let mut bcx = bcx;
let mut constraints = Vec::new();
let mut output_types = Vec::new();
let temp_scope = fcx.push_custom_cleanup_scope();
let mut ext_inputs =... | trans_inline_asm | identifier_name |
asm.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | };
let r = ia.asm.get().with_c_str(|a| {
constraints.with_c_str(|c| {
InlineAsmCall(bcx,
a,
c,
inputs.as_slice(),
output_type,
ia.volatile,
... |
let dialect = match ia.dialect {
ast::AsmAtt => llvm::AD_ATT,
ast::AsmIntel => llvm::AD_Intel | random_line_split |
asm.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | callee::trans_arg_datum(bcx,
expr_ty(bcx, &**out),
out_datum,
cleanup::CustomScope(temp_scope),
callee::DontAutorefArg)
}));
... | {
let fcx = bcx.fcx;
let mut bcx = bcx;
let mut constraints = Vec::new();
let mut output_types = Vec::new();
let temp_scope = fcx.push_custom_cleanup_scope();
let mut ext_inputs = Vec::new();
let mut ext_constraints = Vec::new();
// Prepare the output operands
let outputs = ia.out... | identifier_body |
asm.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | else {
for (i, o) in outputs.iter().enumerate() {
let v = ExtractValue(bcx, r, i);
Store(bcx, v, *o);
}
}
// Store expn_id in a metadata node so we can map LLVM errors
// back to source locations. See #17552.
unsafe {
let key = "srcloc";
let kin... | {
Store(bcx, r, outputs[0]);
} | conditional_block |
scheduler.rs | // The MIT License (MIT)
// Copyright (c) 2015 Rustcc Developers
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, c... | <F, T>(f: F, opts: Options) -> JoinHandle<T>
where F: FnOnce() -> T + Send +'static,
T: Send +'static
{
Scheduler::instance().work_counts.fetch_add(1, Ordering::SeqCst);
let (tx, rx) = ::sync::mpsc::channel();
let wrapper = move|| {
let ret = thread::catch_... | spawn_opts | identifier_name |
scheduler.rs | // The MIT License (MIT)
// Copyright (c) 2015 Rustcc Developers
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, c... |
}
guard.push((hdl, stealer));
}
match Processor::current().schedule() {
Ok(..) => {},
Err(err) => panic!("Processor schedule error: {:?}", err),
}
}
match Scheduler::instance().work_thread_futures.loc... | {
error!("Error while sending NewNeighbor {:?}", err);
} | conditional_block |
scheduler.rs | // The MIT License (MIT)
// Copyright (c) 2015 Rustcc Developers
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, c... |
/// Run the scheduler with `n` threads
pub fn run(n: usize) {
Scheduler::start(n);
Scheduler::join();
}
pub fn start(n : usize) {
assert!(n >= 1, "There must be at least 1 thread");
fn do_work() {
{
let mut guard = Scheduler::instance().pro... | {
Scheduler::instance().work_counts.fetch_add(1, Ordering::SeqCst);
let (tx, rx) = ::sync::mpsc::channel();
let wrapper = move|| {
let ret = thread::catch_panic(move|| f());
// No matter whether it is panicked or not, the result will be sent to the channel
l... | identifier_body |
scheduler.rs | // The MIT License (MIT)
// Copyright (c) 2015 Rustcc Developers
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, c... | assert_eq!(1, guard.join().unwrap());
}
#[test]
fn test_scheduler_start_join() {
let guard = Scheduler::spawn(|| 1);
Scheduler::start(1);
Scheduler::join();
assert_eq!(1, guard.join().unwrap());
}
#[test]
fn test_can_spawn_after_start() {
Schedu... | let guard = Scheduler::spawn(|| 1);
Scheduler::run(1);
| random_line_split |
drawingarea.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... |
impl_TraitWidget!(DrawingArea)
impl_widget_events!(DrawingArea)
| let tmp_pointer = unsafe { ffi::gtk_drawing_area_new() };
check_pointer!(tmp_pointer, DrawingArea)
}
} | identifier_body |
drawingarea.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | -> Option<DrawingArea> {
let tmp_pointer = unsafe { ffi::gtk_drawing_area_new() };
check_pointer!(tmp_pointer, DrawingArea)
}
}
impl_TraitWidget!(DrawingArea)
impl_widget_events!(DrawingArea)
| w() | identifier_name |
drawingarea.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | }
impl_TraitWidget!(DrawingArea)
impl_widget_events!(DrawingArea) | let tmp_pointer = unsafe { ffi::gtk_drawing_area_new() };
check_pointer!(tmp_pointer, DrawingArea)
} | random_line_split |
pwm3.rs | //! Output a PWM with a duty cycle of ~6% on all the channels of TIM3
#![deny(warnings)]
#![feature(const_fn)]
#![feature(used)]
#![no_std]
extern crate blue_pill;
extern crate embedded_hal as hal;
// version = "0.2.3"
extern crate cortex_m_rt;
// version = "0.1.0"
#[macro_use]
extern crate cortex_m_rtfm as rtfm;
... | (_prio: P0, _thr: T0) ->! {
// Sleep
loop {
rtfm::wfi();
}
}
// TASKS
tasks!(stm32f103xx, {});
| idle | identifier_name |
pwm3.rs | //! Output a PWM with a duty cycle of ~6% on all the channels of TIM3
#![deny(warnings)]
#![feature(const_fn)]
#![feature(used)]
#![no_std]
extern crate blue_pill;
extern crate embedded_hal as hal;
// version = "0.2.3"
extern crate cortex_m_rt;
// version = "0.1.0"
#[macro_use]
extern crate cortex_m_rtfm as rtfm;
... |
const CHANNELS: [Channel; 2] = [Channel::_1, Channel::_2];
for c in &CHANNELS {
pwm.set_duty(*c, duty);
}
for c in &CHANNELS {
pwm.enable(*c);
rtfm::bkpt();
}
}
// IDLE LOOP
fn idle(_prio: P0, _thr: T0) ->! {
// Sleep
loop {
rtfm::wfi();
}
}
// TASKS
... |
pwm.init(FREQUENCY.invert(), afio, None, gpioa, rcc);
let duty = pwm.get_max_duty() / 16; | random_line_split |
pwm3.rs | //! Output a PWM with a duty cycle of ~6% on all the channels of TIM3
#![deny(warnings)]
#![feature(const_fn)]
#![feature(used)]
#![no_std]
extern crate blue_pill;
extern crate embedded_hal as hal;
// version = "0.2.3"
extern crate cortex_m_rt;
// version = "0.1.0"
#[macro_use]
extern crate cortex_m_rtfm as rtfm;
... |
// TASKS
tasks!(stm32f103xx, {});
| {
// Sleep
loop {
rtfm::wfi();
}
} | identifier_body |
server.rs | use std::collections::HashMap;
use serde_json::Value;
use tokio::net::{TcpListener, ToSocketAddrs};
use log::{debug, info, warn};
use crate::channel::Channel;
use crate::message::{Error, Message, Params, VERSION};
pub type Handler = dyn Fn(Option<&Params>) -> Result<Option<Value>, Error>;
pub struct Server {
li... | (&mut self) -> crate::Result<()> {
loop {
let (stream, peer) = self.listener.accept().await?;
info!("Received connection from {}", peer);
let mut channel = Channel::new(stream)?;
let message = channel.receive_frame().await?;
if message.version()!= VE... | run | identifier_name |
server.rs | use std::collections::HashMap;
use serde_json::Value;
use tokio::net::{TcpListener, ToSocketAddrs};
use log::{debug, info, warn};
use crate::channel::Channel;
use crate::message::{Error, Message, Params, VERSION};
pub type Handler = dyn Fn(Option<&Params>) -> Result<Option<Value>, Error>;
pub struct Server {
li... |
if request.id.is_none() {
warn!("Unexpected notification");
continue;
}
let request_id = request.id.unwrap();
let response = if let Some(handler) = self.handlers.get_mut(&request.method) {
match handler(request.params.as_... | {
loop {
let (stream, peer) = self.listener.accept().await?;
info!("Received connection from {}", peer);
let mut channel = Channel::new(stream)?;
let message = channel.receive_frame().await?;
if message.version() != VERSION {
warn!("U... | identifier_body |
server.rs | use std::collections::HashMap;
use serde_json::Value;
use tokio::net::{TcpListener, ToSocketAddrs}; |
pub type Handler = dyn Fn(Option<&Params>) -> Result<Option<Value>, Error>;
pub struct Server {
listener: TcpListener,
handlers: HashMap<String, Box<Handler>>,
}
pub async fn listen<A: ToSocketAddrs>(addr: A, handlers: HashMap<String, Box<Handler>>) -> crate::Result<Server> {
let listener = TcpListener::... | use log::{debug, info, warn};
use crate::channel::Channel;
use crate::message::{Error, Message, Params, VERSION}; | random_line_split |
sha3.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... |
sha3.update(&input[0..some]);
}
sha3.finalize(&mut output);
Ok(output.into())
}
#[cfg(test)]
mod tests {
use std::fs;
use std::io::{Write, BufReader};
use super::*;
#[test]
fn sha3_empty() {
assert_eq!([0u8; 0].sha3(), SHA3_EMPTY);
}
#[test]
fn sha3_as() {
assert_eq!([0x41u8; 32].sha3(), From::from... | {
break;
} | conditional_block |
sha3.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... | (&self, dest: &mut [u8]) {
self.sha3().copy_to(dest);
}
}
impl<T> Hashable for T where T: AsRef<[u8]> {
fn sha3(&self) -> H256 {
let mut ret: H256 = H256::zero();
self.sha3_into(&mut *ret);
ret
}
fn sha3_into(&self, dest: &mut [u8]) {
let input: &[u8] = self.as_ref();
unsafe {
sha3_256(dest.as_mut_... | sha3_into | identifier_name |
sha3.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... | sha3.finalize(&mut output);
Ok(output.into())
}
#[cfg(test)]
mod tests {
use std::fs;
use std::io::{Write, BufReader};
use super::*;
#[test]
fn sha3_empty() {
assert_eq!([0u8; 0].sha3(), SHA3_EMPTY);
}
#[test]
fn sha3_as() {
assert_eq!([0x41u8; 32].sha3(), From::from("59cad5948673622c1d64e2322488bf01619... | }
sha3.update(&input[0..some]);
}
| random_line_split |
sha3.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... |
}
/// Calculate SHA3 of given stream.
pub fn sha3(r: &mut io::BufRead) -> Result<H256, io::Error> {
let mut output = [0u8; 32];
let mut input = [0u8; 1024];
let mut sha3 = Keccak::new_keccak256();
// read file
loop {
let some = r.read(&mut input)?;
if some == 0 {
break;
}
sha3.update(&input[0..some])... | {
let input: &[u8] = self.as_ref();
unsafe {
sha3_256(dest.as_mut_ptr(), dest.len(), input.as_ptr(), input.len());
}
} | identifier_body |
unzip.rs | use core::mem;
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future};
use futures_core::ready;
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
use pin_project_lite::pin_project;
pin_project! {
/// Future for the [`unzip`](super::StreamExt::unzip) method.
... |
None => return Poll::Ready(self.finish()),
}
}
}
}
| {
this.left.extend(Some(e.0));
this.right.extend(Some(e.1));
} | conditional_block |
unzip.rs | use core::mem;
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future};
use futures_core::ready;
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
use pin_project_lite::pin_project;
pin_project! {
/// Future for the [`unzip`](super::StreamExt::unzip) method.
... | (stream: St) -> Self {
Self { stream, left: Default::default(), right: Default::default() }
}
}
impl<St, A, B, FromA, FromB> FusedFuture for Unzip<St, FromA, FromB>
where
St: FusedStream<Item = (A, B)>,
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
{
fn is_terminated(&self) -> boo... | new | identifier_name |
unzip.rs | use core::mem;
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future};
use futures_core::ready;
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
use pin_project_lite::pin_project;
pin_project! {
/// Future for the [`unzip`](super::StreamExt::unzip) method.
... |
pub(super) fn new(stream: St) -> Self {
Self { stream, left: Default::default(), right: Default::default() }
}
}
impl<St, A, B, FromA, FromB> FusedFuture for Unzip<St, FromA, FromB>
where
St: FusedStream<Item = (A, B)>,
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
{
fn is_t... | {
let this = self.project();
(mem::replace(this.left, Default::default()), mem::replace(this.right, Default::default()))
} | identifier_body |
unzip.rs | use core::mem;
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future};
use futures_core::ready;
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
use pin_project_lite::pin_project;
pin_project! {
/// Future for the [`unzip`](super::StreamExt::unzip) method.
... | St: Stream<Item = (A, B)>,
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
{
type Output = (FromA, FromB);
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<(FromA, FromB)> {
let mut this = self.as_mut().project();
loop {
match ready!(this.stream.as... | impl<St, A, B, FromA, FromB> Future for Unzip<St, FromA, FromB>
where | random_line_split |
htmlstyleelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser as CssParser;
use dom::bindings::codegen::Bindings::HTMLStyleElementBinding;
use dom::bindin... | (&self) {
let node = NodeCast::from_ref(self);
let element = ElementCast::from_ref(self);
assert!(node.is_in_doc());
let win = window_from_node(node);
let win = win.r();
let url = win.get_url();
let mq_attribute = element.get_attribute(&ns!(""), &atom!("media"))... | parse_own_css | identifier_name |
htmlstyleelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser as CssParser;
use dom::bindings::codegen::Bindings::HTMLStyleElementBinding;
use dom::bindin... |
let node = NodeCast::from_ref(self);
if node.is_in_doc() {
self.parse_own_css();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
if tree_in_doc {
self.pa... | {
s.children_changed(mutation);
} | conditional_block |
htmlstyleelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser as CssParser;
use dom::bindings::codegen::Bindings::HTMLStyleElementBinding;
use dom::bindin... | let data = node.GetTextContent().expect("Element.textContent must be a string");
let sheet = Stylesheet::from_str(&data, url, Origin::Author);
let LayoutChan(ref layout_chan) = win.layout_chan();
layout_chan.send(Msg::AddStylesheet(sheet, media)).unwrap();
}
}
impl VirtualMethods fo... | random_line_split | |
htmlstyleelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser as CssParser;
use dom::bindings::codegen::Bindings::HTMLStyleElementBinding;
use dom::bindin... |
}
impl HTMLStyleElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLStyleElement {
HTMLStyleElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLStyleElement, localName, prefix, do... | {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLStyleElement)))
} | identifier_body |
operators.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
Ok(())
}
} | random_line_split | |
operators.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | (self, rhs: Self) -> Self {
binary_expr(self.clone(), Operator::Divide, rhs.clone())
}
}
#[cfg(test)]
mod tests {
use crate::error::Result;
use crate::prelude::lit;
#[test]
fn test_operators() -> Result<()> {
assert_eq!(
format!("{:?}", lit(1u32) + lit(2u32)),
... | div | identifier_name |
percentage.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 percentages.
use std::fmt;
use style_traits::{CssWriter, ToCss};
use values::{CSSFloat, serialize_pe... |
}
| {
serialize_percentage(self.0, dest)
} | identifier_body |
percentage.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 percentages.
use std::fmt;
use style_traits::{CssWriter, ToCss};
use values::{CSSFloat, serialize_pe... | (&self) -> Self {
Percentage(self.0.abs())
}
}
impl ToCss for Percentage {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: fmt::Write,
{
serialize_percentage(self.0, dest)
}
}
| abs | identifier_name |
percentage.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 percentages.
use std::fmt;
use style_traits::{CssWriter, ToCss};
use values::{CSSFloat, serialize_pe... | pub struct Percentage(pub CSSFloat);
impl Percentage {
/// 0%
#[inline]
pub fn zero() -> Self {
Percentage(0.)
}
/// 100%
#[inline]
pub fn hundred() -> Self {
Percentage(1.)
}
/// Returns the absolute value for this percentage.
#[inline]
pub fn abs(&self) -... | #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, Default, MallocSizeOf)]
#[derive(PartialEq, PartialOrd, ToAnimatedZero)] | random_line_split |
syntax-extension-source-utils.rs | // Copyright 2012-2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICEN... |
}
}
macro_rules! indirect_line { () => ( line!() ) }
pub fn main() {
assert_eq!(line!(), 25);
//assert!((column!() == 11));
assert_eq!(indirect_line!(), 27);
assert!((file!().ends_with("syntax-extension-source-utils.rs")));
assert_eq!(stringify!((2*3) + 5).to_string(), "( 2 * 3 ) + 5".to_stri... | {
(module_path!()).to_string()
} | identifier_body |
syntax-extension-source-utils.rs | // Copyright 2012-2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICEN... |
assert!(match (45, "( 2 * 3 ) + 5") {
(line!(), stringify!((2*3) + 5)) => true,
_ => false
})
} | [1] == (42 as u8)); // '*'
// The Windows tests are wrapped in an extra module for some reason
assert!((m1::m2::where_am_i().ends_with("m1::m2"))); | random_line_split |
syntax-extension-source-utils.rs | // Copyright 2012-2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICEN... | () {
assert_eq!(line!(), 25);
//assert!((column!() == 11));
assert_eq!(indirect_line!(), 27);
assert!((file!().ends_with("syntax-extension-source-utils.rs")));
assert_eq!(stringify!((2*3) + 5).to_string(), "( 2 * 3 ) + 5".to_string());
assert!(include!("syntax-extension-source-utils-files/includ... | main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.