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 |
|---|---|---|---|---|
admin_script_builder.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use diem_framework::compile_script;
use diem_types::{
account_address::AccountAddress,
account_config::diem_root_address,
transaction::{Script, WriteSetPayload},
};
use handlebars::Handlebars;
use serde::... | (validators: Vec<AccountAddress>) -> WriteSetPayload {
assert!(!validators.is_empty(), "Unexpected validator set length");
let mut script = template_path();
script.push("remove_validators.move");
let script = {
let mut hb = Handlebars::new();
hb.set_strict_mode(true);
hb.registe... | encode_remove_validators_payload | identifier_name |
admin_script_builder.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use diem_framework::compile_script;
use diem_types::{
account_address::AccountAddress,
account_config::diem_root_address,
transaction::{Script, WriteSetPayload},
};
use handlebars::Handlebars;
use serde::... |
pub fn template_path() -> PathBuf {
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push(SCRIPTS_DIR_PATH.to_string());
path
}
pub fn encode_remove_validators_payload(validators: Vec<AccountAddress>) -> WriteSetPayload {
assert!(!validators.is_empty(), "Unexpected validator set length"... | {
let mut temp_file = NamedTempFile::new()?;
temp_file.write_all(input.as_bytes())?;
let cur_path = temp_file.path().to_str().unwrap().to_owned();
Ok(Script::new(compile_script(cur_path), vec![], vec![]))
} | identifier_body |
admin_script_builder.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use diem_framework::compile_script;
use diem_types::{
account_address::AccountAddress,
account_config::diem_root_address,
transaction::{Script, WriteSetPayload},
};
use handlebars::Handlebars;
use serde::... | ) -> WriteSetPayload {
let mut script = template_path();
script.push(script_name_in_templates);
let script = {
let mut hb = Handlebars::new();
hb.register_template_file("script", script).unwrap();
hb.set_strict_mode(true);
let output = hb.render("script", args).unwrap();
... | execute_as: Option<AccountAddress>, | random_line_split |
ring_slices.rs | use core::ptr::{self};
/// Returns the two slices that cover the `VecDeque`'s valid range
pub trait RingSlices: Sized {
fn slice(self, from: usize, to: usize) -> Self;
fn split_at(self, i: usize) -> (Self, Self);
fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
let contiguous ... |
}
}
impl<T> RingSlices for &[T] {
fn slice(self, from: usize, to: usize) -> Self {
&self[from..to]
}
fn split_at(self, i: usize) -> (Self, Self) {
(*self).split_at(i)
}
}
impl<T> RingSlices for &mut [T] {
fn slice(self, from: usize, to: usize) -> Self {
&mut self[from.... | {
let (mid, right) = buf.split_at(tail);
let (left, _) = mid.split_at(head);
(right, left)
} | conditional_block |
ring_slices.rs | use core::ptr::{self};
/// Returns the two slices that cover the `VecDeque`'s valid range
pub trait RingSlices: Sized {
fn slice(self, from: usize, to: usize) -> Self;
fn split_at(self, i: usize) -> (Self, Self);
fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
let contiguous ... | (self, mid: usize) -> (Self, Self) {
let len = self.len();
let ptr = self.as_mut_ptr();
assert!(mid <= len);
(
ptr::slice_from_raw_parts_mut(ptr, mid),
ptr::slice_from_raw_parts_mut(ptr.wrapping_add(mid), len - mid),
)
}
}
| split_at | identifier_name |
ring_slices.rs | use core::ptr::{self};
/// Returns the two slices that cover the `VecDeque`'s valid range
pub trait RingSlices: Sized {
fn slice(self, from: usize, to: usize) -> Self;
fn split_at(self, i: usize) -> (Self, Self);
fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
let contiguous ... | }
impl<T> RingSlices for *mut [T] {
fn slice(self, from: usize, to: usize) -> Self {
assert!(from <= to && to < self.len());
// Not using `get_unchecked_mut` to keep this a safe operation.
let len = to - from;
ptr::slice_from_raw_parts_mut(self.as_mut_ptr().wrapping_add(from), len)
... | random_line_split | |
ring_slices.rs | use core::ptr::{self};
/// Returns the two slices that cover the `VecDeque`'s valid range
pub trait RingSlices: Sized {
fn slice(self, from: usize, to: usize) -> Self;
fn split_at(self, i: usize) -> (Self, Self);
fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
let contiguous ... |
fn split_at(self, mid: usize) -> (Self, Self) {
let len = self.len();
let ptr = self.as_mut_ptr();
assert!(mid <= len);
(
ptr::slice_from_raw_parts_mut(ptr, mid),
ptr::slice_from_raw_parts_mut(ptr.wrapping_add(mid), len - mid),
)
}
}
| {
assert!(from <= to && to < self.len());
// Not using `get_unchecked_mut` to keep this a safe operation.
let len = to - from;
ptr::slice_from_raw_parts_mut(self.as_mut_ptr().wrapping_add(from), len)
} | identifier_body |
write_ogr.rs | extern crate gdal;
use std::path::Path;
use std::fs;
use gdal::errors::Error;
use gdal::vector::{Defn, Driver, Feature, FieldDefn, FieldValue, Geometry, OGRFieldType};
/// Example 1, the detailed way:
fn example_1() -> Result<(), Error> {
let _ = fs::remove_file("/tmp/output1.geojson");
let drv = Driver::get(... | () -> Result<(), Error> {
let _ = fs::remove_file("/tmp/output2.geojson");
let driver = Driver::get("GeoJSON")?;
let mut ds = driver.create(Path::new("/tmp/output2.geojson"))?;
let layer = ds.create_layer()?;
layer.create_defn_fields(&[
("Name", OGRFieldType::OFTString),
("Value", O... | example_2 | identifier_name |
write_ogr.rs | extern crate gdal;
use std::path::Path;
use std::fs;
use gdal::errors::Error;
use gdal::vector::{Defn, Driver, Feature, FieldDefn, FieldValue, Geometry, OGRFieldType};
/// Example 1, the detailed way:
fn example_1() -> Result<(), Error> {
let _ = fs::remove_file("/tmp/output1.geojson");
let drv = Driver::get(... | {
example_1().unwrap();
example_2().unwrap();
} | identifier_body | |
write_ogr.rs | extern crate gdal;
use std::path::Path;
use std::fs;
use gdal::errors::Error;
use gdal::vector::{Defn, Driver, Feature, FieldDefn, FieldValue, Geometry, OGRFieldType};
/// Example 1, the detailed way:
fn example_1() -> Result<(), Error> {
let _ = fs::remove_file("/tmp/output1.geojson");
let drv = Driver::get(... | let mut ft = Feature::new(&defn)?;
ft.set_geometry(Geometry::from_wkt("POINT (46.50 22.50)")?)?;
ft.set_field_string("Name", "Feature 2")?;
match ft.set_field_double("Values", 0.789) {
Ok(v) => v,
Err(err) => println!("{}", err),
};
ft.create(lyr)?;
Ok(())
}
/// Example 2, ... | random_line_split | |
lib.rs | // Copyright © 2018 Cormac O'Brien
//
// 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, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission noti... | random_line_split | |
comments.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub fn doc_comment_style(comment: &str) -> ast::AttrStyle {
assert!(is_doc_comment(comment));
if comment.starts_with("//!") || comment.starts_with("/*!") {
ast::AttrInner
} else {
ast::AttrOuter
}
}
pub fn strip_doc_comment_decoration(comment: &str) -> ~str {
/// remove whitespac... | {
(s.starts_with("///") && !is_line_non_doc_comment(s)) ||
s.starts_with("//!") ||
(s.starts_with("/**") && !is_block_non_doc_comment(s)) ||
s.starts_with("/*!")
} | identifier_body |
comments.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | ,
lines: ~[read_one_line_comment(rdr)],
pos: p
});
}
fn read_line_comments(rdr: @mut StringReader, code_to_the_left: bool,
comments: &mut ~[cmnt]) {
debug2!(">>> line comments");
let p = rdr.last_pos;
let mut lines: ~[~str] = ~[];
while rdr.... | { isolated } | conditional_block |
comments.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (comment: &str) -> ast::AttrStyle {
assert!(is_doc_comment(comment));
if comment.starts_with("//!") || comment.starts_with("/*!") {
ast::AttrInner
} else {
ast::AttrOuter
}
}
pub fn strip_doc_comment_decoration(comment: &str) -> ~str {
/// remove whitespace-only lines from the star... | doc_comment_style | identifier_name |
comments.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | let comment = "/**\n * Test\n * Test\n*/";
let stripped = strip_doc_comment_decoration(comment);
assert_eq!(stripped, ~" Test\n Test");
}
#[test] fn test_block_doc_comment_3() {
let comment = "/**\n let a: *int;\n *a = 5;\n*/";
let stripped = strip_doc_comment_decorati... |
#[test] fn test_block_doc_comment_2() { | random_line_split |
lib.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... | pub mod evm;
pub mod interpreter;
#[macro_use]
pub mod factory;
mod vmtype;
mod instructions;
#[cfg(feature = "jit" )]
mod jit;
#[cfg(test)]
mod tests;
#[cfg(all(feature="benches", test))]
mod benches;
pub use vm::{
Schedule, CleanDustMode, EnvInfo, CallType, ActionParams, Ext,
ContractCreateResult, Message... | random_line_split | |
num_format.rs | //! handles creating printed output for numeric substitutions
use std::env;
use std::vec::Vec;
use cli;
use super::format_field::{FormatField, FieldType};
use super::formatter::{Formatter, FormatPrimitive, InPrefix, Base};
use super::formatters::intf::Intf;
use super::formatters::floatf::Floatf;
use super::formatters:... |
}
// if decimal, keep last zero if one exists
// (it's possible for last zero to
// not exist at this branch if we're in hex input)
'.' => break,
// other digit, etc.
... | {
ret.offset += 1;
} | conditional_block |
num_format.rs | //! handles creating printed output for numeric substitutions
use std::env;
use std::vec::Vec;
use cli;
use super::format_field::{FormatField, FieldType};
use super::formatter::{Formatter, FormatPrimitive, InPrefix, Base};
use super::formatters::intf::Intf;
use super::formatters::floatf::Floatf;
use super::formatters:... | (str_in_opt: Option<&String>) -> Option<u8> {
const C_S_QUOTE: u8 = 39;
const C_D_QUOTE: u8 = 34;
match str_in_opt {
Some(str_in) => {
let mut byte_it = str_in.bytes();
if let Some(qchar) = byte_it.next() {
match qchar {
C_S_QUOTE | C_D_QUO... | get_provided | identifier_name |
num_format.rs | //! handles creating printed output for numeric substitutions
use std::env;
use std::vec::Vec;
use cli;
use super::format_field::{FormatField, FieldType};
use super::formatter::{Formatter, FormatPrimitive, InPrefix, Base};
use super::formatters::intf::Intf;
use super::formatters::floatf::Floatf;
use super::formatters:... | // whereas at that point octal knows its
// current offset is not the final offset.
match ch_zero {
'0' => {
if!(is_hex && first) {
ret.offset += 1;
... | // first zero it does not move its offset
// forward because it does not know for sure
// that it's current offset (of that zero)
// is not the final offset, | random_line_split |
num_format.rs | //! handles creating printed output for numeric substitutions
use std::env;
use std::vec::Vec;
use cli;
use super::format_field::{FormatField, FieldType};
use super::formatter::{Formatter, FormatPrimitive, InPrefix, Base};
use super::formatters::intf::Intf;
use super::formatters::floatf::Floatf;
use super::formatters:... |
// this function looks at the first few
// characters of an argument and returns a value if we can learn
// a value from that (e.g. no argument? return 0, char constant? ret value)
fn get_provided(str_in_opt: Option<&String>) -> Option<u8> {
const C_S_QUOTE: u8 = 39;
const C_D_QUOTE: u8 = 34;
match str_in... | {
match env::var("POSIXLY_CORRECT") {
Ok(_) => {}
Err(e) => {
match e {
env::VarError::NotPresent => {
cli::err_msg(&format!("warning: {:?}: character(s) following character \
constant have been ignored",
... | identifier_body |
main.rs | use std::env;
// Rust doesn't make it easy to do things like: 'a' + x to get the letter matching a digit.
static DIGITS: [char; 26] = [
'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p',
'q', 'r','s', 't',
'u', 'v', 'w', 'x',
'y', 'z'];
fn main() {
let input... |
fn has_straight_and_pairs(candidate: &Vec<char>) -> bool {
let mut idx = 0;
let mut pairs = 0;
let mut straight = false;
while idx < candidate.len() {
straight |= is_straight(candidate, idx);
if idx > 0 && candidate[idx] == candidate[idx - 1] {
pairs += 1;
idx +... | {
let chars : Vec<_> = candidate.chars().collect();
!candidate.contains('i') &&
!candidate.contains('o') &&
!candidate.contains('l') &&
has_straight_and_pairs(&chars)
} | identifier_body |
main.rs | use std::env;
// Rust doesn't make it easy to do things like: 'a' + x to get the letter matching a digit.
static DIGITS: [char; 26] = [
'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p',
'q', 'r','s', 't',
'u', 'v', 'w', 'x',
'y', 'z'];
fn main() {
let input... |
};
let next = find_next_password(&input);
println!("found next valid password: {}", next);
let next_next = find_next_password(&input);
println!("found next next valid password: {}", next_next);
}
fn find_next_password(input: &str) -> String {
let mut candidate = increment_string(&input);
... | {
println!("usage: day11 <input value>");
return
} | conditional_block |
main.rs | use std::env;
// Rust doesn't make it easy to do things like: 'a' + x to get the letter matching a digit.
static DIGITS: [char; 26] = [
'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p',
'q', 'r','s', 't',
'u', 'v', 'w', 'x',
'y', 'z'];
fn main() {
let input... | pairs += 1;
idx += 1;
}
idx += 1;
}
straight && pairs > 1
}
fn is_straight(candidate: &Vec<char>, idx: usize) -> bool {
idx > 1 && {
let c = candidate[idx];
candidate[idx - 1] == std::char::from_u32(c as u32 - 1).unwrap() &&
candidate[idx ... | let mut straight = false;
while idx < candidate.len() {
straight |= is_straight(candidate, idx);
if idx > 0 && candidate[idx] == candidate[idx - 1] { | random_line_split |
main.rs | use std::env;
// Rust doesn't make it easy to do things like: 'a' + x to get the letter matching a digit.
static DIGITS: [char; 26] = [
'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p',
'q', 'r','s', 't',
'u', 'v', 'w', 'x',
'y', 'z'];
fn main() {
let input... | (candidate: &str) -> bool {
let chars : Vec<_> = candidate.chars().collect();
!candidate.contains('i') &&
!candidate.contains('o') &&
!candidate.contains('l') &&
has_straight_and_pairs(&chars)
}
fn has_straight_and_pairs(candidate: &Vec<char>) -> bool {
let mut idx = 0;
let mut pai... | is_acceptable_password | identifier_name |
event.rs | //! Main interface for a stream of events the Supervisor can send out
//! in the course of its operations.
//!
//! Currently, the Supervisor is able to send events to a [NATS][1]
//! server. The `init_stream` function must be called
//! before sending events to initialize the publishing thread in the
//! background. Th... | () {
let (tx, rx) = futures_mpsc::unbounded();
NATS_MESSAGE_STREAM.set(NatsMessageStream(tx));
EVENT_CORE.set(EventCore { supervisor_id: String::from("supervisor_id"),
ip_address: "127.0.0.1:8080".parse().unwrap(),
fqdn: ... | health_check_event | identifier_name |
event.rs | //! Main interface for a stream of events the Supervisor can send out
//! in the course of its operations.
//!
//! Currently, the Supervisor is able to send events to a [NATS][1]
//! server. The `init_stream` function must be called
//! before sending events to initialize the publishing thread in the
//! background. Th... |
/// Publish an event. This is the main interface that client code will
/// use.
///
/// If `init_stream` has not been called already, this function will
/// be a no-op.
fn publish(subject: &'static Subject, mut event: impl EventMessage) {
if let Some(stream) = NATS_MESSAGE_STREAM.try_get() {
// TODO (CM):... | { NATS_MESSAGE_STREAM.try_get().is_some() } | identifier_body |
event.rs | //! Main interface for a stream of events the Supervisor can send out
//! in the course of its operations.
//!
//! Currently, the Supervisor is able to send events to a [NATS][1]
//! server. The `init_stream` function must be called
//! before sending events to initialize the publishing thread in the
//! background. Th... |
}
#[cfg(test)]
mod tests {
use super::{nats_message_stream::NatsMessageStream,
*};
use crate::prost::Message;
use futures::{channel::mpsc as futures_mpsc,
stream::StreamExt};
#[cfg(windows)]
use habitat_core::os::process::windows_child::ExitStatus;
use habitat... | {
// TODO (CM): Yeah... this is looking pretty gross. The
// intention is to be able to timestamp the events right as
// they go out.
//
// We *could* set the time when we convert the EventCore to a
// EventMetadata struct, but that seems odd.
//
// It pro... | conditional_block |
event.rs | //! Main interface for a stream of events the Supervisor can send out
//! in the course of its operations.
//!
//! Currently, the Supervisor is able to send events to a [NATS][1]
//! server. The `init_stream` function must be called
//! before sending events to initialize the publishing thread in the
//! background. Th... | assert_eq!(event.exit_status, Some(3));
// `ExitStatus::from_raw` sets the signal not the code
#[cfg(unix)]
assert_eq!(event.exit_status, None);
assert_eq!(event.stdout, None);
assert_eq!(event.stderr, Some(String::from("stderr")));
}
} | random_line_split | |
response.rs | //! Data structures containing information about the outcome of an executed query.
//!
//! This module implements the step "Receive responses" as described in [Writing RethinkDB drivers]
//! (http://rethinkdb.com/docs/writing-drivers/#receive-responses).
use std::io::{self, Read};
use std::marker::PhantomData;
use byt... | /// The profile if requested in the corresponding query.
profile: Option<Box<Profile>>,
/// The backtrace says where in the query the error occurred.
backtrace: Option<Vec<Frame>>,
}
impl<O> Response<O> {
/// Returns the token identifying this `Response`.
pub fn token(&self) -> u64 {
s... | /// Additional notes which indicate special properties the response has.
notes: Option<Vec<Note>>,
| random_line_split |
response.rs | //! Data structures containing information about the outcome of an executed query.
//!
//! This module implements the step "Receive responses" as described in [Writing RethinkDB drivers]
//! (http://rethinkdb.com/docs/writing-drivers/#receive-responses).
use std::io::{self, Read};
use std::marker::PhantomData;
use byt... | (num: u64) -> Option<Note> {
match num {
1 => Some(Note::SequenceFeed),
2 => Some(Note::AtomFeed),
3 => Some(Note::OrderByLimitFeed),
4 => Some(Note::UnionedFeed),
5 => Some(Note::IncludesStates),
_ => None,
}
}
}
impl Deserial... | from_u64 | identifier_name |
actions.rs | use chrono::NaiveDateTime;
use diesel::{dsl::exists, prelude::*, select};
use regex::Regex;
use std::str::FromStr;
use url::Url;
use crate::{
models::{Mention, NewMention},
DbError,
};
pub fn target_exists(url: &Url, conn: &PgConnection) -> Option<(String, i32)> {
use crate::schema::articles::dsl::{articl... | (
source_url: String,
target_url: String,
object_type: &str,
id: i32,
author: String,
title: String,
conn: &PgConnection,
) -> Result<Mention, DbError> {
use crate::schema::mentions;
let now = select(diesel::dsl::now).get_result::<NaiveDateTime>(conn)?;
let mut data = NewMention... | create_mention | identifier_name |
actions.rs | use chrono::NaiveDateTime;
use diesel::{dsl::exists, prelude::*, select};
use regex::Regex;
use std::str::FromStr;
use url::Url;
use crate::{
models::{Mention, NewMention},
DbError,
};
pub fn target_exists(url: &Url, conn: &PgConnection) -> Option<(String, i32)> {
use crate::schema::articles::dsl::{articl... |
if rslt.is_none() {
return None;
}
let caps = rslt.unwrap();
let object_type = caps.get(1);
let id_str = caps.get(2);
if object_type.is_none() || id_str.is_none() {
return None;
}
let object_type = object_type.unwrap().as_str();
let id: Result<i32, _> = FromStr::... | random_line_split | |
actions.rs | use chrono::NaiveDateTime;
use diesel::{dsl::exists, prelude::*, select};
use regex::Regex;
use std::str::FromStr;
use url::Url;
use crate::{
models::{Mention, NewMention},
DbError,
};
pub fn target_exists(url: &Url, conn: &PgConnection) -> Option<(String, i32)> {
use crate::schema::articles::dsl::{articl... |
Some((object_type.to_owned(), id.unwrap()))
}
pub fn mention_exists(source: &str, target: &str, conn: &PgConnection) -> bool {
use crate::schema::mentions::dsl::*;
select(exists(
mentions.filter(target_url.eq(target)).filter(source_url.eq(source)),
))
.get_result(conn)
.unwrap_or_else(... | {
return None;
} | conditional_block |
actions.rs | use chrono::NaiveDateTime;
use diesel::{dsl::exists, prelude::*, select};
use regex::Regex;
use std::str::FromStr;
use url::Url;
use crate::{
models::{Mention, NewMention},
DbError,
};
pub fn target_exists(url: &Url, conn: &PgConnection) -> Option<(String, i32)> {
use crate::schema::articles::dsl::{articl... | let id: Result<i32, _> = FromStr::from_str(id_str.unwrap().as_str());
if id.is_err() {
return None;
}
Some((object_type.to_owned(), id.unwrap()))
}
pub fn mention_exists(source: &str, target: &str, conn: &PgConnection) -> bool {
use crate::schema::mentions::dsl::*;
select(exists(
... | {
let path = url.path();
let re = Regex::new(r"^/([^/]+)/(\d+)$").unwrap();
let rslt = re.captures(path);
if rslt.is_none() {
return None;
}
let caps = rslt.unwrap();
let object_type = caps.get(1);
let id_str = caps.get(2);
if object_type.is_none() || id_str.is_none() {
... | identifier_body |
icmp.rs | use core::mem::size_of;
use core::option::Option;
use common::debug::*;
use common::vec::*;
use network::common::*;
#[derive(Copy, Clone)]
#[repr(packed)]
pub struct ICMPHeader {
pub _type: u8,
pub code: u8,
pub checksum: Checksum,
pub data: [u8; 4]
}
pub struct ICMP {
pub header: ICMPHeader,
... |
}
| {
d("ICMP ");
dbh(self.header._type);
d(" code ");
dbh(self.header.code);
d(" data ");
dd(self.data.len());
} | identifier_body |
icmp.rs | use core::mem::size_of;
use core::option::Option;
use common::debug::*;
use common::vec::*;
use network::common::*;
#[derive(Copy, Clone)]
#[repr(packed)]
pub struct ICMPHeader {
pub _type: u8,
pub code: u8,
pub checksum: Checksum,
pub data: [u8; 4]
}
pub struct ICMP {
pub header: ICMPHeader,
... | unsafe {
return Option::Some(ICMP {
header: *(bytes.as_ptr() as *const ICMPHeader),
data: bytes.sub(size_of::<ICMPHeader>(), bytes.len() - size_of::<ICMPHeader>())
});
}
}
return Option::None;
}
}
impl T... | impl FromBytes for ICMP {
fn from_bytes(bytes: Vec<u8>) -> Option<ICMP> {
if bytes.len() >= size_of::<ICMPHeader>() { | random_line_split |
icmp.rs | use core::mem::size_of;
use core::option::Option;
use common::debug::*;
use common::vec::*;
use network::common::*;
#[derive(Copy, Clone)]
#[repr(packed)]
pub struct ICMPHeader {
pub _type: u8,
pub code: u8,
pub checksum: Checksum,
pub data: [u8; 4]
}
pub struct ICMP {
pub header: ICMPHeader,
... | (&self) -> Vec<u8> {
unsafe{
let header_ptr: *const ICMPHeader = &self.header;
let mut ret = Vec::from_raw_buf(header_ptr as *const u8, size_of::<ICMPHeader>());
ret.push_all(&self.data);
return ret;
}
}
}
impl ICMP {
pub fn d(&self){
d("I... | to_bytes | identifier_name |
icmp.rs | use core::mem::size_of;
use core::option::Option;
use common::debug::*;
use common::vec::*;
use network::common::*;
#[derive(Copy, Clone)]
#[repr(packed)]
pub struct ICMPHeader {
pub _type: u8,
pub code: u8,
pub checksum: Checksum,
pub data: [u8; 4]
}
pub struct ICMP {
pub header: ICMPHeader,
... |
return Option::None;
}
}
impl ToBytes for ICMP {
fn to_bytes(&self) -> Vec<u8> {
unsafe{
let header_ptr: *const ICMPHeader = &self.header;
let mut ret = Vec::from_raw_buf(header_ptr as *const u8, size_of::<ICMPHeader>());
ret.push_all(&self.data);
... | {
unsafe {
return Option::Some(ICMP {
header: *(bytes.as_ptr() as *const ICMPHeader),
data: bytes.sub(size_of::<ICMPHeader>(), bytes.len() - size_of::<ICMPHeader>())
});
}
} | conditional_block |
error.rs | //! The module defining custom leveldb error type.
use libc::{c_void, free};
use std;
/// A leveldb error, just containing the error string
/// provided by leveldb.
#[derive(Debug)]
pub struct Error {
message: String,
}
impl Error {
/// create a new Error, using the String provided
pub fn new(message: St... |
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "LevelDB error: {}", self.message)
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
&self.message
}
fn cause(&self) -> Option<&std::error::Error> {... | {
use std::str::from_utf8;
use std::ffi::CStr;
let err_string =
unsafe { from_utf8(CStr::from_ptr(message).to_bytes()).unwrap().to_string() };
unsafe { free(message as *mut c_void) };
Error::new(err_string)
} | identifier_body |
error.rs | //! The module defining custom leveldb error type.
use libc::{c_void, free};
use std;
/// A leveldb error, just containing the error string
/// provided by leveldb.
#[derive(Debug)]
pub struct Error {
message: String,
}
impl Error {
/// create a new Error, using the String provided
pub fn new(message: St... | (&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "LevelDB error: {}", self.message)
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
&self.message
}
fn cause(&self) -> Option<&std::error::Error> {
None
}
}
| fmt | identifier_name |
error.rs | //! The module defining custom leveldb error type.
use libc::{c_void, free};
use std;
/// A leveldb error, just containing the error string
/// provided by leveldb.
#[derive(Debug)]
pub struct Error {
message: String,
}
impl Error {
/// create a new Error, using the String provided
pub fn new(message: St... | impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "LevelDB error: {}", self.message)
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
&self.message
}
fn cause(&self) -> Option<&std::error::Error> {
... | Error::new(err_string)
}
}
| random_line_split |
process-status-inherits-stdin.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let mut s = String::new();
io::stdin().read_line(&mut s).unwrap();
assert_eq!(s, "foo\n");
}
}
}
| {
let mut args = env::args();
let me = args.next().unwrap();
let arg = args.next();
match arg.as_ref().map(|s| &s[..]) {
None => {
let mut s = Command::new(&me)
.arg("a1")
.stdin(Stdio::piped())
... | identifier_body |
process-status-inherits-stdin.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut args = env::args();
let me = args.next().unwrap();
let arg = args.next();
match arg.as_ref().map(|s| &s[..]) {
None => {
let mut s = Command::new(&me)
.arg("a1")
.stdin(Stdio::piped())
... | main | identifier_name |
process-status-inherits-stdin.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
Some(..) => {
let mut s = String::new();
io::stdin().read_line(&mut s).unwrap();
assert_eq!(s, "foo\n");
}
}
}
| {
let s = Command::new(&me).arg("a2").status().unwrap();
assert!(s.success());
} | conditional_block |
process-status-inherits-stdin.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// igno... | // http://rust-lang.org/COPYRIGHT.
// | random_line_split |
tokens.rs | use std::collections::HashMap;
#[allow(dead_code)]
#[derive(PartialEq, Eq, Debug, Clone, Hash)]
pub enum Keyword {
AND,
BREAK,
DO,
ELSE,
ELSEIF,
END,
FALSE,
FOR,
FUNCTION,
GOTO,
IF,
IN,
LOCAL,
NIL,
NOT,
OR,
REPEAT,
RETURN,
THEN,
TRUE,
... | TokenType::Keyword(ref keyword) => Some(keyword.clone()),
_ => None,
}
}
}
impl Into<TokenType> for Token {
fn into(self) -> TokenType {
self.token.clone()
}
}
| _ => None,
}
}
pub fn keyword(&self) -> Option<Keyword> {
match self.token {
| identifier_body |
tokens.rs | use std::collections::HashMap;
#[allow(dead_code)]
#[derive(PartialEq, Eq, Debug, Clone, Hash)]
pub enum Keyword {
AND,
BREAK,
DO,
ELSE,
ELSEIF,
END,
FALSE,
FOR,
FUNCTION,
GOTO,
IF,
IN,
LOCAL,
NIL,
NOT,
OR,
REPEAT,
RETURN,
THEN,
TRUE,
... | ("break", Keyword::BREAK),
("do", Keyword::DO),
("else", Keyword::ELSE),
("elseif", Keyword::ELSEIF),
("end", Keyword::END),
("false", Keyword::FALSE),
("for", Keyword::FOR),
("function", Keyword::FUNCTION),
("goto", Keyword::GOTO),
("if", Ke... | yword::AND),
| identifier_name |
tokens.rs | use std::collections::HashMap;
#[allow(dead_code)]
#[derive(PartialEq, Eq, Debug, Clone, Hash)]
pub enum Keyword {
AND,
BREAK,
DO,
ELSE,
ELSEIF,
END,
FALSE,
FOR,
FUNCTION,
GOTO,
IF,
IN,
LOCAL,
NIL,
NOT,
OR,
REPEAT,
RETURN,
THEN,
TRUE,
... | ("[", Keyword::LSBRACKET),
("]", Keyword::RSBRACKET),
("{", Keyword::LCBRACKET),
("}", Keyword::RCBRACKET),
("::", Keyword::PATH),
(";", Keyword::SEMICOLONS),
(":", Keyword::COLONS),
(",", Keyword::COMMA),
(".", Keyword::DOT),
("..", Keywor... | ("(", Keyword::LBRACE),
(")", Keyword::RBRACE), | random_line_split |
fns.rs | //! Random utility Lisp functions.
use std::{ptr, slice};
use libc;
use remacs_macros::lisp_fn;
use crate::{
casefiddle::downcase,
dispnew::{ding, sleep_for},
eval::{record_unwind_protect, un_autoload, unbind_to},
lisp::LispObject,
lists::{assq, car, get, mapcar1, member, memq, put},
lists::... |
mapcar1(leni, ptr::null_mut(), function, sequence);
sequence
}
/* List of features currently being require'd, innermost first. */
declare_GC_protected_static!(require_nesting_list, Qnil);
unsafe extern "C" fn require_unwind(old_value: LispObject) {
require_nesting_list = old_value;
}
/// If feature FE... | {
wrong_type!(Qlistp, sequence);
} | conditional_block |
fns.rs | //! Random utility Lisp functions.
use std::{ptr, slice};
use libc;
use remacs_macros::lisp_fn;
use crate::{
casefiddle::downcase,
dispnew::{ding, sleep_for},
eval::{record_unwind_protect, un_autoload, unbind_to},
lisp::LispObject,
lists::{assq, car, get, mapcar1, member, memq, put},
lists::... |
#[cfg(windows)]
unsafe fn getloadaverage(loadavg: *mut libc::c_double, nelem: libc::c_int) -> libc::c_int {
crate::remacs_sys::getloadavg(loadavg, nelem)
}
#[cfg(not(windows))]
unsafe fn getloadaverage(loadavg: *mut libc::c_double, nelem: libc::c_int) -> libc::c_int {
libc::getloadavg(loadavg, nelem)
}
/// ... | {
o1.equal_no_quit(o2)
} | identifier_body |
fns.rs | //! Random utility Lisp functions.
use std::{ptr, slice};
use libc;
use remacs_macros::lisp_fn;
use crate::{
casefiddle::downcase,
dispnew::{ding, sleep_for},
eval::{record_unwind_protect, un_autoload, unbind_to},
lisp::LispObject,
lists::{assq, car, get, mapcar1, member, memq, put},
lists::... |
let next = args[i + 1];
tail.set_cdr(next);
if next.is_nil() {
args[i + 1] = tail.into();
}
}
val
}
include!(concat!(env!("OUT_DIR"), "/fns_exports.rs")); | random_line_split | |
fns.rs | //! Random utility Lisp functions.
use std::{ptr, slice};
use libc;
use remacs_macros::lisp_fn;
use crate::{
casefiddle::downcase,
dispnew::{ding, sleep_for},
eval::{record_unwind_protect, un_autoload, unbind_to},
lisp::LispObject,
lists::{assq, car, get, mapcar1, member, memq, put},
lists::... | (args: &mut [LispObject]) -> LispObject {
unsafe {
lisp_concat(
args.len() as isize,
args.as_mut_ptr() as *mut LispObject,
Lisp_Type::Lisp_String,
false,
)
}
}
/// Return the reversed copy of list, vector, or string SEQ.
/// See also the function ... | concat | identifier_name |
build.rs | extern crate build_utils;
extern crate protoc_grpcio;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use build_utils::BuildRoot;
fn main() | "google/rpc/status.proto",
"google/longrunning/operations.proto",
"google/protobuf/empty.proto",
],
&[
thirdpartyprotobuf.join("googleapis"),
thirdpartyprotobuf.join("standard"),
thirdpartyprotobuf.join("rust-protobuf"),
],
&gen_dir,
).expect("Failed to compile prot... | {
let build_root = BuildRoot::find().unwrap();
let thirdpartyprotobuf = build_root.join("3rdparty/protobuf");
println!(
"cargo:rerun-if-changed={}",
thirdpartyprotobuf.to_str().unwrap()
);
let gen_dir = PathBuf::from("src/gen");
// Re-gen if, say, someone does a git clean on the gen dir but not th... | identifier_body |
build.rs | extern crate build_utils;
extern crate protoc_grpcio;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use build_utils::BuildRoot;
fn main() {
let build_root = BuildRoot::find().unwrap();
let thirdpartyprotobuf = build_root.join("3rdparty/protobuf");
println!(
"cargo:rerun-if-changed={}",
... | .filter_map(|d| {
let dirent = d.unwrap();
let file_name = dirent.file_name().into_string().unwrap();
match file_name.trim_right_matches(".rs") {
"mod" | ".gitignore" => None,
module_name => Some(format!("pub mod {};", module_name)),
}
})
.collect::<Vec<_>>();
pub_mod... | let listing = gen_dir.read_dir().unwrap();
let mut pub_mod_stmts = listing | random_line_split |
build.rs | extern crate build_utils;
extern crate protoc_grpcio;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use build_utils::BuildRoot;
fn | () {
let build_root = BuildRoot::find().unwrap();
let thirdpartyprotobuf = build_root.join("3rdparty/protobuf");
println!(
"cargo:rerun-if-changed={}",
thirdpartyprotobuf.to_str().unwrap()
);
let gen_dir = PathBuf::from("src/gen");
// Re-gen if, say, someone does a git clean on the gen dir but not... | main | identifier_name |
main.rs | extern crate rusty_machine as rm;
extern crate rand;
use rm::linalg::{Matrix, BaseMatrix};
use rand::{Rng, ThreadRng};
use std::collections::HashMap;
fn generate_arm(content_id: &usize, arms: &HashMap<usize, Arm>, feature_dim: &usize) -> Arm {
let arm: Arm;
if!arms.contains_key(content_id) {
arm = Ar... | struct Rulet{
rng: ThreadRng,
}
impl Rulet{
fn new() -> Rulet {
Rulet{
rng: rand::thread_rng(),
}
}
fn generate_features(&mut self, viewer: &Viewer) -> Matrix<f64> {
let features = Some(&viewer.gender)
.and_then(|gender|
if gender=="man" {... | if &self.gender=="man" {
// Men are easy to click on ads with id 5 or less
if *content_id < 6 {
return Some(self.rng.next_f32()).and_then(|n| if n>0.3 {Some(true)} else {Some(false)}).unwrap();
} else{
return Some(self.rng.next_f32()).and_then(|n... | identifier_body |
main.rs | extern crate rusty_machine as rm;
extern crate rand;
use rm::linalg::{Matrix, BaseMatrix};
use rand::{Rng, ThreadRng};
use std::collections::HashMap;
fn generate_arm(content_id: &usize, arms: &HashMap<usize, Arm>, feature_dim: &usize) -> Arm {
let arm: Arm;
if!arms.contains_key(content_id) {
arm = Ar... | }
}
fn main() {
/*Context is for men and women only
Men are easy to click on ads with id 5 or less
Women are easy to click on ads with id 6 or higher
*/
let feature_dim = 2;
let num_of_views = 10000;
let mut rulet = Rulet::new();
let mut content_id: usize;
let mut features: Matri... | return "women".to_string();
}
| conditional_block |
main.rs | extern crate rusty_machine as rm;
extern crate rand;
use rm::linalg::{Matrix, BaseMatrix};
use rand::{Rng, ThreadRng};
use std::collections::HashMap;
fn generate_arm(content_id: &usize, arms: &HashMap<usize, Arm>, feature_dim: &usize) -> Arm {
let arm: Arm;
if!arms.contains_key(content_id) {
arm = Ar... | let theta = &one_div_cov.elemul(&self.norm_mean);
// Again, the inverse matrix of the covariance matrix
// is computed by taking reciprocal
let mut tmp: f64 = ((features.elemul(&one_div_cov))*features.transpose()).data()[0];
tmp = &tmp.sqrt()*&self.alpha;
(theta*feature... | self.cov_matrix.cols(), one_div_cov_vec);
// Since the covariance matrix preserves only the diagonal components,
// it suffices to take the inverse matrix | random_line_split |
main.rs | extern crate rusty_machine as rm;
extern crate rand;
use rm::linalg::{Matrix, BaseMatrix};
use rand::{Rng, ThreadRng};
use std::collections::HashMap;
fn generate_arm(content_id: &usize, arms: &HashMap<usize, Arm>, feature_dim: &usize) -> Arm {
let arm: Arm;
if!arms.contains_key(content_id) {
arm = Ar... | rng: ThreadRng,
}
impl Rulet{
fn new() -> Rulet {
Rulet{
rng: rand::thread_rng(),
}
}
fn generate_features(&mut self, viewer: &Viewer) -> Matrix<f64> {
let features = Some(&viewer.gender)
.and_then(|gender|
if gender=="man" {Some(Matrix::new... | t{
| identifier_name |
temporary_roles.rs | use crate::database::{
schema::*,
models::U64,
};
insertable! {
#[derive(Debug, Queryable, Identifiable, AsChangeset)]
pub struct TemporaryRole,
#[derive(Debug, Insertable)]
#[table_name = "temporary_roles"]
pub struct NewTemporaryRole {
pub guild_id: U64,
pub user_id: U64,
pub role_id: U64,
... |
}
| {
NewTemporaryRole {
guild_id: guild_id.into(),
user_id: user_id.into(),
role_id: role_id.into(),
message_id: message_id.into(),
channel_id: channel_id.map(|x| x as i64),
messages,
expires_on,
}
} | identifier_body |
temporary_roles.rs | use crate::database::{
schema::*,
models::U64,
};
insertable! {
#[derive(Debug, Queryable, Identifiable, AsChangeset)]
pub struct TemporaryRole,
#[derive(Debug, Insertable)]
#[table_name = "temporary_roles"]
pub struct NewTemporaryRole {
pub guild_id: U64,
pub user_id: U64,
pub role_id: U64,
... | (guild_id: u64, user_id: u64, role_id: u64, message_id: u64, channel_id: Option<u64>, messages: Option<i32>, expires_on: Option<i64>) -> Self {
NewTemporaryRole {
guild_id: guild_id.into(),
user_id: user_id.into(),
role_id: role_id.into(),
message_id: message_id.into(),
channel_id: cha... | new | identifier_name |
temporary_roles.rs | use crate::database::{
schema::*,
models::U64,
};
insertable! {
#[derive(Debug, Queryable, Identifiable, AsChangeset)]
pub struct TemporaryRole,
#[derive(Debug, Insertable)]
#[table_name = "temporary_roles"]
pub struct NewTemporaryRole {
pub guild_id: U64,
pub user_id: U64,
pub role_id: U64,
... | impl NewTemporaryRole {
pub fn new(guild_id: u64, user_id: u64, role_id: u64, message_id: u64, channel_id: Option<u64>, messages: Option<i32>, expires_on: Option<i64>) -> Self {
NewTemporaryRole {
guild_id: guild_id.into(),
user_id: user_id.into(),
role_id: role_id.into(),
message_id: mess... | random_line_split | |
time.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use ipc_channel::ipc;
use profile::time;
use profile_traits::ipc as ProfiledIpc;
use profile_traits::time::{Profil... | time::Profiler::get_statistics(&unsorted_data);
}
#[cfg(debug_assertions)]
#[test]
#[should_panic]
fn time_profiler_data_len_zero() {
let zero_data = vec![];
time::Profiler::get_statistics(&zero_data);
} | fn time_profiler_unsorted_stats_test() {
let unsorted_data = vec![5.0, 7.5, 1.0, 8.9]; | random_line_split |
time.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use ipc_channel::ipc;
use profile::time;
use profile_traits::ipc as ProfiledIpc;
use profile_traits::time::{Profil... |
#[test]
fn channel_profiler_test() {
let chan = time::Profiler::create(&Some(OutputOptions::Stdout(5.0)), None);
let (profiled_sender, profiled_receiver) = ProfiledIpc::channel(chan.clone()).unwrap();
thread::spawn(move || {
thread::sleep(Duration::from_secs(2));
profiled_sender.send(43).u... | {
let even_data = vec![1.234, 3.24567, 3.54578, 5.0, 5.324, 7.345,
9.2345, 10.2342345, 13.2599, 15.0];
let (even_mean, even_median, even_min, even_max) = time::Profiler::get_statistics(&even_data);
assert_eq!(7.34230845, even_mean);
assert_eq!(7.345, even_median);
assert_eq... | identifier_body |
time.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use ipc_channel::ipc;
use profile::time;
use profile_traits::ipc as ProfiledIpc;
use profile_traits::time::{Profil... | () {
let chan = time::Profiler::create(&None, None);
assert!(true, "Can create the profiler thread");
let (ipcchan, _ipcport) = ipc::channel().unwrap();
chan.send(ProfilerMsg::Exit(ipcchan));
assert!(true, "Can tell the profiler thread to exit");
}
#[test]
fn time_profiler_stats_test() {
let e... | time_profiler_smoke_test | identifier_name |
non_blocking.rs | //! A demonstration of constructing and using a non-blocking stream.
//!
//! Audio from the default input device is passed directly to the default output device in a duplex
//! stream, so beware of feedback!
extern crate portaudio;
use portaudio as pa;
const SAMPLE_RATE: f64 = 44_100.0;
const FRAMES: u32 = 256;
con... |
};
// Construct a stream with input and output sample types of f32.
let mut stream = try!(pa.open_non_blocking_stream(settings, callback));
try!(stream.start());
// Loop while the non-blocking stream is active.
while let true = try!(stream.is_active()) {
// Do some stuff!
wh... | { pa::Complete } | conditional_block |
non_blocking.rs | //! A demonstration of constructing and using a non-blocking stream.
//!
//! Audio from the default input device is passed directly to the default output device in a duplex
//! stream, so beware of feedback!
extern crate portaudio;
use portaudio as pa;
const SAMPLE_RATE: f64 = 44_100.0;
const FRAMES: u32 = 256;
con... | let latency = output_info.default_low_output_latency;
let output_params = pa::StreamParameters::new(def_output, CHANNELS, INTERLEAVED, latency);
// Check that the stream format is supported.
try!(pa.is_duplex_format_supported(input_params, output_params, SAMPLE_RATE));
// Construct the settings wi... | let output_info = try!(pa.device_info(def_output));
println!("Default output device info: {:#?}", &output_info);
// Construct the output stream parameters. | random_line_split |
non_blocking.rs | //! A demonstration of constructing and using a non-blocking stream.
//!
//! Audio from the default input device is passed directly to the default output device in a duplex
//! stream, so beware of feedback!
extern crate portaudio;
use portaudio as pa;
const SAMPLE_RATE: f64 = 44_100.0;
const FRAMES: u32 = 256;
con... |
fn run() -> Result<(), pa::Error> {
let pa = try!(pa::PortAudio::new());
println!("PortAudio:");
println!("version: {}", pa.version());
println!("version text: {:?}", pa.version_text());
println!("host count: {}", try!(pa.host_api_count()));
let default_host = try!(pa.default_host_api());
... | {
run().unwrap()
} | identifier_body |
non_blocking.rs | //! A demonstration of constructing and using a non-blocking stream.
//!
//! Audio from the default input device is passed directly to the default output device in a duplex
//! stream, so beware of feedback!
extern crate portaudio;
use portaudio as pa;
const SAMPLE_RATE: f64 = 44_100.0;
const FRAMES: u32 = 256;
con... | () -> Result<(), pa::Error> {
let pa = try!(pa::PortAudio::new());
println!("PortAudio:");
println!("version: {}", pa.version());
println!("version text: {:?}", pa.version_text());
println!("host count: {}", try!(pa.host_api_count()));
let default_host = try!(pa.default_host_api());
print... | run | identifier_name |
segmentgraph.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Write;
use clidispatch::errors;
use cliparser::define_flags;
use dag::render::render_segment_dag;
use super::Repo;
use super... | {
"display segment graph for a given group and level"
} | identifier_body | |
segmentgraph.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Write;
use clidispatch::errors;
use cliparser::define_flags;
use dag::render::render_segment_dag;
use super::Repo;
use super... | Ok(level) => level,
_ => return Err(errors::Abort("invalid level".into()).into()),
};
let mut out = io.output();
write!(out, "{}, Level: {}\n", group, level)?;
let dag = dag::Dag::open(repo.store_path().join("segments/v1"))?;
render_segment_dag(out, &dag, level, group)?;
Ok(0)... | };
let level: dag::Level = match opts.level.try_into() { | random_line_split |
segmentgraph.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Write;
use clidispatch::errors;
use cliparser::define_flags;
use dag::render::render_segment_dag;
use super::Repo;
use super... | () -> &'static str {
"debugsegmentgraph"
}
pub fn doc() -> &'static str {
"display segment graph for a given group and level"
}
| name | identifier_name |
creader.rs | None => i.ident.to_string(),
};
Some(CrateInfo {
ident: i.ident.to_string(),
name: name,
id: i.id,
should_link: should_link(i),
})
}
_ => None
}... | }
// When the hash is None we're dealing with a top-level dependency
// in which case we may have a specification on the command line for
// this library. Even though an upstream library may have loaded
// something of the same name, we have to make sure it w... |
match hash {
Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
Some(..) => return,
None => {} | random_line_split |
creader.rs | }
None => { load_ctxt.report_load_errs(); unreachable!() },
};
let dylib = library.dylib.clone();
let register = should_link && self.existing_match(&info.name,
None,
... | are_equal_modulo_startpos | identifier_name | |
creader.rs | None => i.ident.to_string(),
};
Some(CrateInfo {
ident: i.ident.to_string(),
name: name,
id: i.id,
should_link: should_link(i),
})
}
_ => None
}
... |
}
}
}
fn process_item(&mut self, i: &ast::Item) {
match i.node {
ast::ItemExternCrate(_) => {
if!should_link(i) {
return;
}
match self.creader.extract_crate_info(i) {
Some(info) => ... | { /* fallthrough */ } | conditional_block |
creader.rs | None => i.ident.to_string(),
};
Some(CrateInfo {
ident: i.ident.to_string(),
name: name,
id: i.id,
should_link: should_link(i),
})
}
_ => None
}
... | let source = self.sess.cstore.get_used_crate_source(cnum).unwrap();
if let Some(locs) = self.sess.opts.externs.get(name) {
let found = locs.iter().any(|l| {
let l = fs::canonicalize(l).ok();
source.dylib.as_ref().map(|p| &p.0) == l.as_ref()... | {
let mut ret = None;
self.sess.cstore.iter_crate_data(|cnum, data| {
if data.name != name { return }
match hash {
Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
Some(..) => return,
None => {}
}
... | identifier_body |
async_utils.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Virtio device async helper functions.
use std::cell::RefCell;
use std::rc::Rc;
use anyhow::{Context, Result};
use base::Event;
use cros_async::{E... |
Ok(())
}
| {
// No resample event; park the future.
let () = futures::future::pending().await;
} | conditional_block |
async_utils.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Virtio device async helper functions.
use std::cell::RefCell;
use std::rc::Rc;
use anyhow::{Context, Result};
use base::Event;
use cros_async::{E... | }
Ok(())
} | // No resample event; park the future.
let () = futures::future::pending().await; | random_line_split |
async_utils.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Virtio device async helper functions.
use std::cell::RefCell;
use std::rc::Rc;
use anyhow::{Context, Result};
use base::Event;
use cros_async::{E... |
/// Async task that resamples the status of the interrupt when the guest sends a request by
/// signalling the resample event associated with the interrupt.
pub async fn handle_irq_resample(ex: &Executor, interrupt: Rc<RefCell<Interrupt>>) -> Result<()> {
// Clone resample_evt if interrupt has one.
// This is... | {
let event_async = EventAsync::new(event.0, ex).context("failed to create EventAsync")?;
let _ = event_async.next_val().await;
Ok(())
} | identifier_body |
async_utils.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Virtio device async helper functions.
use std::cell::RefCell;
use std::rc::Rc;
use anyhow::{Context, Result};
use base::Event;
use cros_async::{E... | (ex: &Executor, interrupt: Rc<RefCell<Interrupt>>) -> Result<()> {
// Clone resample_evt if interrupt has one.
// This is a separate block so that we do not hold a RefCell borrow across await.
let resample_evt = if let Some(resample_evt) = interrupt.borrow().get_resample_evt() {
let resample_evt = r... | handle_irq_resample | identifier_name |
profiling_support.rs | use measureme::{StringComponent, StringId};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::profiling::SelfProfiler;
use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc_hir::definitions::DefPathData;
use rustc_middle::ty::{TyCtxt, WithOptConstPara... | let dis;
let end_index;
match def_key.disambiguated_data.data {
DefPathData::CrateRoot => {
crate_name = self.tcx.crate_name(def_id.krate).as_str();
name = &*crate_name;
dis = "";
end_index = 3;
}
... | {
if let Some(&string_id) = self.string_cache.def_id_cache.get(&def_id) {
return string_id;
}
let def_key = self.tcx.def_key(def_id);
let (parent_string_id, start_index) = match def_key.parent {
Some(parent_index) => {
let parent_def_id = DefId {... | identifier_body |
profiling_support.rs | use measureme::{StringComponent, StringId};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::profiling::SelfProfiler;
use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc_hir::definitions::DefPathData;
use rustc_middle::ty::{TyCtxt, WithOptConstPara... | // efficient query keys.
fn def_id_to_string_id(&mut self, def_id: DefId) -> StringId {
if let Some(&string_id) = self.string_cache.def_id_cache.get(&def_id) {
return string_id;
}
let def_key = self.tcx.def_key(def_id);
let (parent_string_id, start_index) = match de... | }
// The current implementation is rather crude. In the future it might be a
// good idea to base this on `ty::print` in order to get nicer and more | random_line_split |
profiling_support.rs | use measureme::{StringComponent, StringId};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::profiling::SelfProfiler;
use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc_hir::definitions::DefPathData;
use rustc_middle::ty::{TyCtxt, WithOptConstPara... | (
&self,
builder: &mut QueryKeyStringBuilder<'_, '_, '_>,
) -> StringId {
builder.def_id_to_string_id(DefId { krate: LOCAL_CRATE, index: self.local_def_index })
}
}
impl<T: SpecIntoSelfProfilingString> SpecIntoSelfProfilingString for WithOptConstParam<T> {
fn spec_to_self_profile_st... | spec_to_self_profile_string | identifier_name |
permission.rs | use std::{error::Error as StdError, fmt, io::Write, str::FromStr};
use diesel::{backend::Backend, deserialize, serialize, sql_types::Text};
#[derive(AsExpression, Clone, Copy, Debug, Eq, FromSqlRow, Hash, PartialEq)]
#[sql_type = "Text"]
pub enum Permission {
MakePost,
MakeMediaPost,
MakeComment,
Foll... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Failed to parse Permission")
}
}
impl StdError for PermissionParseError {
fn description(&self) -> &str {
"Failed to parse Permission"
}
fn cause(&self) -> Option<&StdError> {
None
}
}
| fmt | identifier_name |
permission.rs | use std::{error::Error as StdError, fmt, io::Write, str::FromStr};
use diesel::{backend::Backend, deserialize, serialize, sql_types::Text};
#[derive(AsExpression, Clone, Copy, Debug, Eq, FromSqlRow, Hash, PartialEq)]
#[sql_type = "Text"]
pub enum Permission {
MakePost,
MakeMediaPost,
MakeComment,
Foll... |
impl fmt::Display for Permission {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Permission::MakePost => write!(f, "make-post"),
Permission::MakeMediaPost => write!(f, "make-media-post"),
Permission::MakeComment => write!(f, "make-comment"),
... | BlockInstance,
GrantRole,
RevokeRole,
} | random_line_split |
spawn.rs | //extern crate scoped_threadpool;
extern crate threadpool;
extern crate thread_local;
extern crate hwloc;
use matrix::{Scalar,Mat};
use core::marker::{PhantomData};
use thread_comm::{ThreadComm,ThreadInfo};
use composables::{GemmNode,AlgorithmStep};
use std::sync::{Arc,Mutex};
use std::cell::{RefCell};
use self::thre... | (&mut self, n_threads: usize){
//Create new thread pool
self.n_threads = n_threads;
if n_threads > 1 {
self.pool = ThreadPool::new(n_threads-1);
} else {
self.pool = ThreadPool::new(1);
}
//Clear the control tree cache
Arc::get_mut(&mut s... | set_n_threads | identifier_name |
spawn.rs | //extern crate scoped_threadpool;
extern crate threadpool;
extern crate thread_local;
extern crate hwloc;
use matrix::{Scalar,Mat};
use core::marker::{PhantomData};
use thread_comm::{ThreadComm,ThreadInfo};
use composables::{GemmNode,AlgorithmStep};
use std::sync::{Arc,Mutex};
use std::cell::{RefCell};
use self::thre... |
}
| {
S::hierarchy_description()
} | identifier_body |
spawn.rs | //extern crate scoped_threadpool;
extern crate threadpool;
extern crate thread_local;
extern crate hwloc;
use matrix::{Scalar,Mat};
use core::marker::{PhantomData};
use thread_comm::{ThreadComm,ThreadInfo};
use composables::{GemmNode,AlgorithmStep};
use std::sync::{Arc,Mutex};
use std::cell::{RefCell};
use self::thre... |
//Clear the control tree cache
Arc::get_mut(&mut self.cntl_cache).expect("").clear();
//Bind threads to cores
self.bind_threads();
}
fn bind_threads(&mut self) {
//Get topology
let topo = Arc::new(Mutex::new(Topology::new()));
let comm : Arc<Thre... | if n_threads > 1 {
self.pool = ThreadPool::new(n_threads-1);
} else {
self.pool = ThreadPool::new(1);
} | random_line_split |
method-on-enum.rs | // Copyright 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
// <LICENSE-MI... | () {
let stack = Enum::Variant2(117901063);
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
let owned: Box<_> = box Enum::Variant1{ x: 1799, y: 1799 };
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
}
fn zzz() ... | main | identifier_name |
method-on-enum.rs | // Copyright 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
// <LICENSE-MI... |
impl Enum {
fn self_by_ref(&self, arg1: isize, arg2: isize) -> isize {
zzz(); // #break
arg1 + arg2
}
fn self_by_val(self, arg1: isize, arg2: isize) -> isize {
zzz(); // #break
arg1 + arg2
}
fn self_owned(self: Box<Enum>, arg1: isize, arg2: isize) -> isize {
... | Variant2 (u32)
} | random_line_split |
method-on-enum.rs | // Copyright 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
// <LICENSE-MI... |
}
fn main() {
let stack = Enum::Variant2(117901063);
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
let owned: Box<_> = box Enum::Variant1{ x: 1799, y: 1799 };
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
}... | {
zzz(); // #break
arg1 + arg2
} | identifier_body |
react_native_xcode.rs | //! Implements a command for uploading react-native projects.
use std::env;
use std::fs;
use std::path::PathBuf;
use std::process;
use chrono::Duration;
use clap::{App, Arg, ArgMatches};
use failure::{bail, Error};
use if_chain::if_chain;
use log::info;
use serde::{Deserialize, Serialize};
use crate::api::{Api, NewRe... | (matches: &ArgMatches<'_>) -> Result<(), Error> {
let config = Config::current();
let (org, project) = config.get_org_and_project(matches)?;
let should_wrap = matches.is_present("force")
|| match env::var("CONFIGURATION") {
Ok(config) =>!&config.contains("Debug"),
Err(_) => b... | execute | identifier_name |
react_native_xcode.rs | //! Implements a command for uploading react-native projects.
use std::env;
use std::fs;
use std::path::PathBuf;
use std::process;
use chrono::Duration;
use clap::{App, Arg, ArgMatches};
use failure::{bail, Error};
use if_chain::if_chain;
use log::info;
use serde::{Deserialize, Serialize};
use crate::api::{Api, NewRe... | sourcemap_url = format!(
"~/{}",
sourcemap_path.file_name().unwrap().to_string_lossy()
);
}
// now that we have all the data, we can now process and upload the
// sourcemaps.
println!("Processing react-native sourcemaps for Sentry ... | }
bundle_path = report.bundle_path.unwrap();
bundle_url = format!("~/{}", bundle_path.file_name().unwrap().to_string_lossy());
sourcemap_path = report.sourcemap_path.unwrap(); | random_line_split |
issue-46604.rs | // Copyright 2017 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 ... | {
write(&buf);
buf[0]=2; //[ast]~ ERROR E0389
//[mir]~^ ERROR E0594
} | identifier_body | |
issue-46604.rs | // Copyright 2017 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 ... | static buf: &mut [u8] = &mut [1u8,2,3,4,5,7]; //[ast]~ ERROR E0017
//[mir]~^ ERROR E0017
fn write<T: AsRef<[u8]>>(buffer: T) { }
fn main() {
write(&buf);
buf[0]=2; //[ast]~ ERROR E0389
... |
// revisions: ast mir
//[mir]compile-flags: -Z borrowck=mir
| random_line_split |
issue-46604.rs | // Copyright 2017 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: AsRef<[u8]>>(buffer: T) { }
fn main() {
write(&buf);
buf[0]=2; //[ast]~ ERROR E0389
//[mir]~^ ERROR E0594
}
| write | identifier_name |
main.rs | extern crate futures;
extern crate tokio_proto;
extern crate tokio_service;
extern crate hyper;
#[macro_use] | extern crate serde_json;
extern crate num_cpus;
extern crate mime;
use tokio_proto::TcpServer;
use futures::future;
use hyper::Method::Get;
use hyper::header::{ContentLength, ContentType, Server};
use hyper::StatusCode::NotFound;
use hyper::server::{Http, Service, Request, Response};
use std::net::SocketAddr;
static ... | extern crate serde_derive; | random_line_split |
main.rs | extern crate futures;
extern crate tokio_proto;
extern crate tokio_service;
extern crate hyper;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate num_cpus;
extern crate mime;
use tokio_proto::TcpServer;
use futures::future;
use hyper::Method::Get;
use hyper::header::{ContentLength, ContentT... | (&self, req: Request) -> Self::Future {
let response = match (req.method(), req.path()) {
(&Get, "/plaintext") => {
Response::new()
.with_header(ContentLength(HELLOWORLD.len() as u64))
.with_header(ContentType(mime::TEXT_PLAIN))
... | call | identifier_name |
main.rs | extern crate futures;
extern crate tokio_proto;
extern crate tokio_service;
extern crate hyper;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate num_cpus;
extern crate mime;
use tokio_proto::TcpServer;
use futures::future;
use hyper::Method::Get;
use hyper::header::{ContentLength, ContentT... | {
let addr: SocketAddr = "0.0.0.0:8080".parse().unwrap();
let mut srv = TcpServer::new(Http::new(), addr);
println!("Listening on http://{} using {} threads",
addr,
num_cpus::get());
srv.threads(num_cpus::get());
srv.serve(move || Ok(TechEmpower))
} | identifier_body | |
input_process.rs | extern crate glutin;
extern crate state;
use state::{GraphicsState, CoreState};
use glutin::Event::{Closed, KeyboardInput};
use glutin::ElementState::{Pressed};
use glutin::VirtualKeyCode as VK;
pub fn execute(graphics_state: &mut GraphicsState, core_state: &mut CoreState) -> () {
for event in graphics_state.displ... | KeyboardInput(Pressed, _, Some(VK::F3)) => {
graphics_state.reload_shaders = true;
}
KeyboardInput(Pressed, _, Some(VK::F4)) => {
core_state.reload = true
}
KeyboardInput(Pressed, _, Some(VK::F5)) => {
core_state... | } | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.