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 |
|---|---|---|---|---|
main.rs | extern crate rusoto_core;
extern crate rusoto_rds;
use std::{thread, time};
use rusoto_rds::{Rds, RdsClient, CreateDBInstanceMessage, DescribeDBInstancesMessage};
use rusoto_core::{DefaultCredentialsProvider, Region, default_tls_client};
fn main() {
let database_instance_name = "rusototester2";
let credentia... | endpoint = endpoint_result.clone();
break;
},
None => {
println!("Waiting for db to be available...");
thread::sleep(ten_seconds);
continue;
},
};
}
let endpoint_address = endpoint.addres... | .db_instances.expect("Didn't get a result for DB instances request")[0].endpoint {
Some(ref endpoint_result) => { | random_line_split |
ffi.rs | use std::default::Default;
use std::ffi::CStr;
use std::str;
use libc::{c_int, c_double, c_char, c_void, uint64_t};
#[link(name = "sigar")]
extern {
// SIGAR_DECLARE(int) sigar_open(sigar_t **sigar);
pub fn sigar_open(sigar: *mut *mut sigar_t) -> c_int;
// SIGAR_DECLARE(int) sigar_close(sigar_t *sigar);
... | pub ram: uint64_t,
pub total: uint64_t,
pub used: uint64_t,
pub free: uint64_t,
pub actual_used: uint64_t,
pub actual_free: uint64_t,
pub used_percent: c_double,
pub free_percent: c_double
}
impl Default for sigar_mem_t {
fn default() -> sigar_mem_t {
sigar_mem_t {
... | random_line_split | |
ffi.rs | use std::default::Default;
use std::ffi::CStr;
use std::str;
use libc::{c_int, c_double, c_char, c_void, uint64_t};
#[link(name = "sigar")]
extern {
// SIGAR_DECLARE(int) sigar_open(sigar_t **sigar);
pub fn sigar_open(sigar: *mut *mut sigar_t) -> c_int;
// SIGAR_DECLARE(int) sigar_close(sigar_t *sigar);
... | {
pub user: uint64_t,
pub sys: uint64_t,
pub nice: uint64_t,
pub idle: uint64_t,
pub wait: uint64_t,
pub irq: uint64_t,
pub soft_irq: uint64_t,
pub stolen: uint64_t,
pub total: uint64_t,
}
impl Default for sigar_cpu_t {
fn default() -> sigar_cpu_t {
sigar_cpu_t {
... | sigar_cpu_t | identifier_name |
ffi.rs | use std::default::Default;
use std::ffi::CStr;
use std::str;
use libc::{c_int, c_double, c_char, c_void, uint64_t};
#[link(name = "sigar")]
extern {
// SIGAR_DECLARE(int) sigar_open(sigar_t **sigar);
pub fn sigar_open(sigar: *mut *mut sigar_t) -> c_int;
// SIGAR_DECLARE(int) sigar_close(sigar_t *sigar);
... | {
unsafe {
let ptr = sigar_strerror(sigar, code);
let bytes = CStr::from_ptr(ptr).to_bytes();
str::from_utf8(bytes).ok().expect("Invalid UTF8 string").to_string()
}
} | identifier_body | |
status.rs | // Copyright (C) 2015, Alberto Corona <ac@albertocorona.com>
// All rights reserved. This file is part of rpf, distributed under the
// BSD 3-Clause license. For full terms please see the LICENSE file.
use utils::PathMod;
use utils::Styled;
use utils::Color;
use std::path::PathBuf;
use utils::Prog;
/// Enum used fo... | (&self, mesg: T, item: PathBuf) {
println!("{}{} {}", item.as_str().paint(Color::Red),
":".paint(Color::Red), mesg.as_ref().paint(Color::Red));
&self.exit(ExitStatus::Error);
}
}
| path_error | identifier_name |
status.rs | // Copyright (C) 2015, Alberto Corona <ac@albertocorona.com>
// All rights reserved. This file is part of rpf, distributed under the
// BSD 3-Clause license. For full terms please see the LICENSE file.
use utils::PathMod;
use utils::Styled;
use utils::Color;
use std::path::PathBuf;
use utils::Prog;
/// Enum used fo... |
/// Used for errors when working with paths, works similar to `error`
fn path_error(&self, mesg: T, item: PathBuf);
}
impl <T: AsRef<str>> Exit<T> for Prog {
fn error(&self, mesg: T, status: ExitStatus) {
println!("{}{} {}", self.name.paint(Color::Red), ":".paint(Color::Red),
mesg.as_ref()... | ///
/// let prog = Prog { name: "test", vers: "0.1.0", yr: "2015" };
/// prog.error("Some kind of error occured!".to_string(), ExitStatus::Error);
/// ```
fn error(&self, mesg: T, status: ExitStatus); | random_line_split |
status.rs | // Copyright (C) 2015, Alberto Corona <ac@albertocorona.com>
// All rights reserved. This file is part of rpf, distributed under the
// BSD 3-Clause license. For full terms please see the LICENSE file.
use utils::PathMod;
use utils::Styled;
use utils::Color;
use std::path::PathBuf;
use utils::Prog;
/// Enum used fo... |
fn path_error(&self, mesg: T, item: PathBuf) {
println!("{}{} {}", item.as_str().paint(Color::Red),
":".paint(Color::Red), mesg.as_ref().paint(Color::Red));
&self.exit(ExitStatus::Error);
}
}
| {
println!("{}{} {}", self.name.paint(Color::Red), ":".paint(Color::Red),
mesg.as_ref().paint(Color::Red));
&self.exit(status);
} | identifier_body |
text.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/. */
//! Text layout.
use std::vec;
use gfx::text::text_run::TextRun;
use gfx::text::util::{CompressWhitespaceNewline... | () -> TextRunScanner {
TextRunScanner {
clump: Range::empty(),
}
}
pub fn scan_for_runs(&mut self, ctx: &LayoutContext, flow: &mut FlowContext) {
{
let inline = flow.imm_inline();
// FIXME: this assertion fails on wikipedia, but doesn't seem
... | new | identifier_name |
text.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/. */
//! Text layout.
use std::vec;
use gfx::text::text_run::TextRun;
use gfx::text::util::{CompressWhitespaceNewline... | pub fn scan_for_runs(&mut self, ctx: &LayoutContext, flow: &mut FlowContext) {
{
let inline = flow.imm_inline();
// FIXME: this assertion fails on wikipedia, but doesn't seem
// to cause problems.
// assert!(inline.boxes.len() > 0);
debug!("TextRun... | random_line_split | |
text.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/. */
//! Text layout.
use std::vec;
use gfx::text::text_run::TextRun;
use gfx::text::util::{CompressWhitespaceNewline... |
pub fn scan_for_runs(&mut self, ctx: &LayoutContext, flow: &mut FlowContext) {
{
let inline = flow.imm_inline();
// FIXME: this assertion fails on wikipedia, but doesn't seem
// to cause problems.
// assert!(inline.boxes.len() > 0);
debug!("TextR... | {
TextRunScanner {
clump: Range::empty(),
}
} | identifier_body |
text.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/. */
//! Text layout.
use std::vec;
use gfx::text::text_run::TextRun;
use gfx::text::util::{CompressWhitespaceNewline... | ,
(true, true) => {
let old_box = in_boxes[self.clump.begin()];
let text = old_box.raw_text();
let font_style = old_box.font_style();
let underline = has_underline(old_box.text_decoration());
// TODO(#115): Use the actual CSS ... | {
debug!("TextRunScanner: pushing single non-text box in range: %?", self.clump);
out_boxes.push(in_boxes[self.clump.begin()]);
} | conditional_block |
list.rs | /* Copyright 2016 Jordan Miner
*
* Licensed under the MIT license <LICENSE or
* http://opensource.org/licenses/MIT>. This file may not be copied,
* modified, or distributed except according to those terms.
*/
use super::control_prelude::*;
use attributes::set_attribute_ptr;
use std::ffi::CStr;
#[derive(Clone)]
p... | else { "NO\0" });
self
}
// An `index` of 0 is the first item.
pub fn item(&self, index: usize) -> String {
get_str_attribute(self.handle(), &format!("{}\0", index + 1))
}
// An `index` of 0 is the first item.
pub fn set_item(&self, index: usize, text: &str) -> &Self {
... | { "YES\0" } | conditional_block |
list.rs | /* Copyright 2016 Jordan Miner
*
* Licensed under the MIT license <LICENSE or
* http://opensource.org/licenses/MIT>. This file may not be copied,
* modified, or distributed except according to those terms.
*/
use super::control_prelude::*;
use attributes::set_attribute_ptr;
use std::ffi::CStr;
#[derive(Clone)]
p... | (&self, index: usize) -> String {
get_str_attribute(self.handle(), &format!("{}\0", index + 1))
}
// An `index` of 0 is the first item.
pub fn set_item(&self, index: usize, text: &str) -> &Self {
set_str_attribute(self.handle(), &format!("{}\0", index + 1), text);
self
}
pu... | item | identifier_name |
list.rs | /* Copyright 2016 Jordan Miner
*
* Licensed under the MIT license <LICENSE or
* http://opensource.org/licenses/MIT>. This file may not be copied,
* modified, or distributed except according to those terms.
*/
use super::control_prelude::*;
use attributes::set_attribute_ptr;
use std::ffi::CStr;
#[derive(Clone)]
p... |
pub fn set_dropdown(&self, dropdown: bool) -> &Self {
set_str_attribute(self.handle(), "DROPDOWN\0", if dropdown { "YES\0" } else { "NO\0" });
self
}
pub fn edit_box(&self) -> bool {
unsafe {
get_str_attribute_slice(self.handle(), "EDITBOX\0") == "YES"
}
}
... | {
unsafe {
get_str_attribute_slice(self.handle(), "DROPDOWN\0") == "YES"
}
} | identifier_body |
list.rs | /* Copyright 2016 Jordan Miner
*
* Licensed under the MIT license <LICENSE or
* http://opensource.org/licenses/MIT>. This file may not be copied,
* modified, or distributed except according to those terms.
*/
use super::control_prelude::*;
use attributes::set_attribute_ptr;
use std::ffi::CStr;
#[derive(Clone)]
p... | set_str_attribute(self.handle(), &format!("INSERTITEM{}\0", index + 1), text);
self
}
// An `index` of 0 is the first item.
pub fn remove_item(&self, index: usize) -> &Self {
set_str_attribute(self.handle(), "REMOVEITEM\0", &format!("{}\0", index + 1));
self
}
pub f... | pub fn insert_item(&self, index: usize, text: &str) -> &Self { | random_line_split |
config.rs | //! Create and define the main configuration through toml files and command line args
pub mod components;
pub mod styling;
use components::*;
use crate::common::Result;
use async_std::fs;
use async_std::os::unix::io::AsRawFd;
use async_std::sync::Arc;
use serde::Deserialize;
use std::fs::File;
use std::io::Read;
us... | (&self, file_path: &str) -> Result<String> {
let mut file = File::open(file_path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
}
| read_file | identifier_name |
config.rs | //! Create and define the main configuration through toml files and command line args
pub mod components;
pub mod styling;
use components::*;
use crate::common::Result;
use async_std::fs;
use async_std::os::unix::io::AsRawFd;
use async_std::sync::Arc;
use serde::Deserialize;
use std::fs::File;
use std::io::Read;
us... |
Err(_) => log::trace!("Failed to load contents from $HOME/.config/scout.toml"),
};
};
};
self
}
/// Read configuration from the given path
pub fn from_file<'a>(&'a mut self, file_path: &str) -> &'a mut Self {
match self.read_file(fil... | {
self.from_toml(&contents);
} | conditional_block |
config.rs | //! Create and define the main configuration through toml files and command line args
pub mod components;
pub mod styling;
use components::*;
use crate::common::Result;
use async_std::fs;
use async_std::os::unix::io::AsRawFd;
use async_std::sync::Arc;
use serde::Deserialize;
use std::fs::File;
use std::io::Read;
us... |
fn read_file(&self, file_path: &str) -> Result<String> {
let mut file = File::open(file_path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
}
| {
match self.config.take() {
Some(config) => Arc::new(config),
None => Default::default(),
}
} | identifier_body |
config.rs | //! Create and define the main configuration through toml files and command line args
pub mod components;
pub mod styling;
use components::*;
use crate::common::Result;
use async_std::fs;
use async_std::os::unix::io::AsRawFd;
use async_std::sync::Arc;
use serde::Deserialize;
use std::fs::File;
use std::io::Read; | #[derive(Debug, Default)]
pub struct Args {
// flags
pub full_screen: bool,
pub inline: bool,
// options
pub lines: Option<usize>,
pub config: Option<String>,
pub search: Option<String>,
}
/// Arc version of Cfg
pub type Config = Arc<Cfg>;
/// Main configuration structure
#[derive(Deseria... |
use crate::terminal_size::terminal_size;
| random_line_split |
utils.rs | use config::*;
use env_logger;
use std::io::{BufReader, BufWriter};
use std::sync::Arc; | use std::sync::atomic::AtomicBool;
use vm::VM;
use vm::memory::Memory;
macro_rules! to_hex {
($data:expr, Word) => {
format!("0x{:04x}", $data)
};
($data:expr) => {
format!("0x{:02x}", $data)
};
}
pub fn data_to_hex(data: DataSlice) -> String {
data.iter()
.map(|i| to_hex!(i))
... | random_line_split | |
utils.rs | use config::*;
use env_logger;
use std::io::{BufReader, BufWriter};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use vm::VM;
use vm::memory::Memory;
macro_rules! to_hex {
($data:expr, Word) => {
format!("0x{:04x}", $data)
};
($data:expr) => {
format!("0x{:02x}", $data)
};
}
pub fn | (data: DataSlice) -> String {
data.iter()
.map(|i| to_hex!(i))
.collect::<Vec<String>>()
.join(" ")
}
pub fn test_run(input: DataSlice,
mut executable: Data,
data_size: Word)
-> (Data, VM<BufReader<DataSlice>, BufWriter<Data>>) {
let _ = env_... | data_to_hex | identifier_name |
utils.rs | use config::*;
use env_logger;
use std::io::{BufReader, BufWriter};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use vm::VM;
use vm::memory::Memory;
macro_rules! to_hex {
($data:expr, Word) => {
format!("0x{:04x}", $data)
};
($data:expr) => {
format!("0x{:02x}", $data)
};
}
pub fn ... | .collect::<Data>();
(output, vm)
}
| {
let _ = env_logger::init();
let code_size = executable.len() as Word - CODE_OFFSET - data_size;
Memory::write_word(&mut executable, 0, code_size);
let input = BufReader::new(input);
let output: Data = vec![];
let output = BufWriter::new(output);
let termination_scheduled = Arc::new(Ato... | identifier_body |
scryptsalsa208sha256.rs | //! `crypto_pwhash_scryptsalsa208sha256`, a particular combination of Scrypt, Salsa20/8
//! and SHA-256
use ffi;
use randombytes::randombytes_into;
use libc::{c_ulonglong, size_t};
use rustc_serialize;
pub const SALTBYTES: usize = ffi::crypto_pwhash_scryptsalsa208sha256_SALTBYTES;
pub const STRBYTES: usize = ffi::cryp... | else {
Err(())
}
}
/// The `pwhash()` returns a `HashedPassword` which
/// includes:
///
/// - the result of a memory-hard, CPU-intensive hash function applied to the password
/// `passwd`
/// - the automatically generated salt used for the
/// previous computation
/// - the other parameters required ... | {
Ok(key)
} | conditional_block |
scryptsalsa208sha256.rs | //! `crypto_pwhash_scryptsalsa208sha256`, a particular combination of Scrypt, Salsa20/8
//! and SHA-256
use ffi;
use randombytes::randombytes_into;
use libc::{c_ulonglong, size_t};
use rustc_serialize;
pub const SALTBYTES: usize = ffi::crypto_pwhash_scryptsalsa208sha256_SALTBYTES;
pub const STRBYTES: usize = ffi::cryp... | () {
use randombytes::randombytes;
for i in (0..16usize) {
let mut pw = randombytes(i);
let pwh = pwhash(&pw, OPSLIMIT_INTERACTIVE, MEMLIMIT_INTERACTIVE).unwrap();
for j in (0..pw.len()) {
pw[j] ^= 0x20;
assert!(!pwhash_verify(&pwh, &pw... | test_pwhash_verify_tamper | identifier_name |
scryptsalsa208sha256.rs | //! `crypto_pwhash_scryptsalsa208sha256`, a particular combination of Scrypt, Salsa20/8
//! and SHA-256
use ffi;
use randombytes::randombytes_into;
use libc::{c_ulonglong, size_t};
use rustc_serialize;
pub const SALTBYTES: usize = ffi::crypto_pwhash_scryptsalsa208sha256_SALTBYTES;
pub const STRBYTES: usize = ffi::cryp... |
#[test]
fn test_pwhash_verify_tamper() {
use randombytes::randombytes;
for i in (0..16usize) {
let mut pw = randombytes(i);
let pwh = pwhash(&pw, OPSLIMIT_INTERACTIVE, MEMLIMIT_INTERACTIVE).unwrap();
for j in (0..pw.len()) {
pw[j] ^= 0x20;
... | {
use randombytes::randombytes;
for i in (0..32usize) {
let pw = randombytes(i);
let pwh = pwhash(&pw, OPSLIMIT_INTERACTIVE, MEMLIMIT_INTERACTIVE).unwrap();
assert!(pwhash_verify(&pwh, &pw));
}
} | identifier_body |
scryptsalsa208sha256.rs | //! `crypto_pwhash_scryptsalsa208sha256`, a particular combination of Scrypt, Salsa20/8
//! and SHA-256
use ffi;
use randombytes::randombytes_into;
use libc::{c_ulonglong, size_t};
use rustc_serialize;
pub const SALTBYTES: usize = ffi::crypto_pwhash_scryptsalsa208sha256_SALTBYTES;
pub const STRBYTES: usize = ffi::cryp... |
/// `pwhash_verify()` verifies that the password `str_` is a valid password
/// verification string (as generated by `pwhash()`) for `passwd`
///
/// It returns `true` if the verification succeeds, and `false` on error.
pub fn pwhash_verify(&HashedPassword(ref str_): &HashedPassword,
passwd: &[u8]... | random_line_split | |
render_file.rs | extern crate env_logger;
extern crate handlebars;
extern crate rustc_serialize;
use std::io::prelude::*;
use std::io;
use std::fs::File;
use std::path::Path;
use std::collections::BTreeMap;
use handlebars::{Handlebars, RenderError, RenderContext, Helper, Context};
use rustc_serialize::json::{Json, ToJson};
struct Te... | () -> BTreeMap<String, Json> {
let mut data = BTreeMap::new();
data.insert("year".to_string(), "2015".to_json());
let teams = vec![ Team { name: "Jiangsu Sainty".to_string(),
pts: 43u16 },
Team { name: "Beijing Guoan".to_string(),
... | make_data | identifier_name |
render_file.rs | extern crate env_logger;
extern crate handlebars; | extern crate rustc_serialize;
use std::io::prelude::*;
use std::io;
use std::fs::File;
use std::path::Path;
use std::collections::BTreeMap;
use handlebars::{Handlebars, RenderError, RenderContext, Helper, Context};
use rustc_serialize::json::{Json, ToJson};
struct Team {
name: String,
pts: u16
}
impl ToJson... | random_line_split | |
render_file.rs | extern crate env_logger;
extern crate handlebars;
extern crate rustc_serialize;
use std::io::prelude::*;
use std::io;
use std::fs::File;
use std::path::Path;
use std::collections::BTreeMap;
use handlebars::{Handlebars, RenderError, RenderContext, Helper, Context};
use rustc_serialize::json::{Json, ToJson};
struct Te... |
}
| {
println!("Failed to create target/table.html");
} | conditional_block |
test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use super::*;
// Ensure serialization of MessagingProtocolVersion enum takes 1 byte.
#[test]
fn net_protocol() -> bcs::Result<()> {
let protocol = MessagingProtocolVersion::V1;
assert_eq!(bcs::to_bytes(&protocol)?, vec![0x00]);... | MessagingProtocolVersion::V1,
[ProtocolId::ConsensusRpc, ProtocolId::MempoolDirectSend]
.iter()
.into(),
);
let h2 = HandshakeMsg {
chain_id,
network_id: network_id.clone(),
supported_protocols,
};
assert_eq!(
(
Messaging... | {
let network_id = NetworkId::default();
let chain_id = ChainId::default();
let mut supported_protocols = BTreeMap::new();
supported_protocols.insert(
MessagingProtocolVersion::V1,
[ProtocolId::ConsensusRpc, ProtocolId::DiscoveryDirectSend]
.iter()
.into(),
);... | identifier_body |
test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use super::*;
// Ensure serialization of MessagingProtocolVersion enum takes 1 byte.
#[test]
fn net_protocol() -> bcs::Result<()> {
let protocol = MessagingProtocolVersion::V1;
assert_eq!(bcs::to_bytes(&protocol)?, vec![0x00]);... | h1.perform_handshake(&h2).unwrap()
);
} | random_line_split | |
test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use super::*;
// Ensure serialization of MessagingProtocolVersion enum takes 1 byte.
#[test]
fn net_protocol() -> bcs::Result<()> {
let protocol = MessagingProtocolVersion::V1;
assert_eq!(bcs::to_bytes(&protocol)?, vec![0x00]);... | () {
let mut handshake_msg = HandshakeMsg::new_for_testing();
handshake_msg.network_id = NetworkId::vfn_network();
// succeeds: Positive case
let h1 = handshake_msg.clone();
let h2 = handshake_msg.clone();
h1.perform_handshake(&h2).unwrap();
// fails: another private network
let mut h2... | represents_same_network | identifier_name |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::i... |
};
});
}
println!("Connection terminates.");
}
}
}
}
| {
println("File does not exist. 404!.");
let no_such_file_string: ~str =
~"HTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n
<doctype !html><html><head><title>Hello, ... | conditional_block |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::i... | stream.write(message_bytes);
}
None => {
println("File does not exist. 404!.");
let no_such_file_string: ~str =
~"HTTP/1.1 404 Not Fou... | Some(mut file) => {
let message_bytes: ~[u8] = file.read_to_end(); | random_line_split |
char.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... | ol { derived_property::XID_Continue(self) }
/// Indicates whether a character is in lowercase.
///
/// This is defined according to the terms of the Unicode Derived Core
/// Property `Lowercase`.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_lowercase(self) -> bool {
... | nue(self) -> bo | identifier_name |
char.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... | dicates whether a character is a control code point.
///
/// Control code points are defined in terms of the Unicode General
/// Category `Cc`.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_control(self) -> bool { general_category::Cc(self) }
/// Indicates whether the ch... | lf.is_alphabetic() || self.is_numeric()
}
/// In | identifier_body |
char.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... | /// ```
/// assert_eq!(Some('C'), 'c'.to_uppercase().next());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_uppercase(self) -> ToUppercase {
ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
}
/// Returns this character's displayed width ... | ///
/// # Examples
/// | random_line_split |
mod.rs | //! Provides the trainers for the [Network][network].
//! [network]:../network/index.html
//!
//! The optimal state of a neural network would be the one where
//! for any given input to the network, it would produce an output perfectly
//! matching the target function. In that state the loss function would have its
//!... | // /// [1]: https://en.wikipedia.org/wiki/Backpropagation#Phase_2:_Weight_update
// ///
// /// Used by [step][2] to optimize the network.
// ///
// /// [2]:./struct.Solver.html#method.step
// //
// // TODO: the actual update can probably be pulled out of this function,
// // since that s... | random_line_split | |
octree.rs | use cgmath::{Point3};
use collision::{Aabb3};
use std::fmt::Debug;
use std::ptr;
pub const MIN_CELL_WIDTH: f32 = 0.1;
fn aabb_overlap(aabb1: &Aabb3<f32>, aabb2: &Aabb3<f32>) -> bool {
true
&& aabb1.min.x < aabb2.max.x
&& aabb1.min.y < aabb2.max.y
&& aabb1.min.z < aabb2.max.z
&& aabb2.min.x < aabb1.max.x
&... | else {
unsafe {
assert!(!self.parent.is_null());
(*self.parent).on_mut_ancestor(bounds, f)
}
}
}
// Find whether there are objects overlapping the object & bounds provided in
// this/child trees. Uses equality comparison on V to ignore "same" objects.
// Returns the value assoc... | {
f(self)
} | conditional_block |
octree.rs | use cgmath::{Point3};
use collision::{Aabb3};
use std::fmt::Debug;
use std::ptr;
pub const MIN_CELL_WIDTH: f32 = 0.1;
fn aabb_overlap(aabb1: &Aabb3<f32>, aabb2: &Aabb3<f32>) -> bool {
true
&& aabb1.min.x < aabb2.max.x
&& aabb1.min.y < aabb2.max.y
&& aabb1.min.z < aabb2.max.z
&& aabb2.min.x < aabb1.max.x
&... | (bounds: &Aabb3<f32>, d: Dimension) -> f32 {
get(d, &bounds.max) - get(d, &bounds.min)
}
fn middle(bounds: &Aabb3<f32>, d: Dimension) -> f32 {
(get(d, &bounds.max) + get(d, &bounds.min)) / 2.0
}
fn get(d: Dimension, p: &Point3<f32>) -> f32 {
match d {
Dimension::X => p.x,
Dimension::Y => p.y,
Dimens... | length | identifier_name |
octree.rs | use cgmath::{Point3};
use collision::{Aabb3};
use std::fmt::Debug;
use std::ptr;
pub const MIN_CELL_WIDTH: f32 = 0.1;
fn aabb_overlap(aabb1: &Aabb3<f32>, aabb2: &Aabb3<f32>) -> bool {
true
&& aabb1.min.x < aabb2.max.x
&& aabb1.min.y < aabb2.max.y
&& aabb1.min.z < aabb2.max.z
&& aabb2.min.x < aabb1.max.x
&... |
pub fn insert(&mut self, bounds: &Aabb3<f32>, v: V) {
let this: *mut Octree<V> = self;
assert!(contains(&self.bounds, &bounds));
let contents = match self.contents {
OctreeContents::Leaf(ref mut vs) => {
vs.push((*bounds, v));
let d = self.dimension;
let avg_length =
... | random_line_split | |
octree.rs | use cgmath::{Point3};
use collision::{Aabb3};
use std::fmt::Debug;
use std::ptr;
pub const MIN_CELL_WIDTH: f32 = 0.1;
fn aabb_overlap(aabb1: &Aabb3<f32>, aabb2: &Aabb3<f32>) -> bool {
true
&& aabb1.min.x < aabb2.max.x
&& aabb1.min.y < aabb2.max.y
&& aabb1.min.z < aabb2.max.z
&& aabb2.min.x < aabb1.max.x
&... |
}
| {
self.remove(bounds, v);
self.insert_from(new_bounds, v)
} | identifier_body |
register.rs | use super::super::{IrcMsg, numerics};
use super::super::message_types::server;
pub type RegisterResult = Result<(), RegisterError>;
#[derive(Clone, Debug)]
pub struct RegisterError {
pub errtype: RegisterErrorType,
pub message: IrcMsg,
}
impl RegisterError {
pub fn should_pick_new_nickname(&self) -> bool... | numerics::ERR_ERRONEUSNICKNAME => Some(RegisterErrorType::ErroneousNickname),
numerics::ERR_NICKCOLLISION => Some(RegisterErrorType::NicknameCollision),
numerics::ERR_RESTRICTED => Some(RegisterErrorType::Restricted),
_ => None
}
}
} | match result {
numerics::ERR_NONICKNAMEGIVEN => Some(RegisterErrorType::NoNicknameGiven),
numerics::ERR_NICKNAMEINUSE => Some(RegisterErrorType::NicknameInUse),
numerics::ERR_UNAVAILRESOURCE => Some(RegisterErrorType::UnavailableResource), | random_line_split |
register.rs | use super::super::{IrcMsg, numerics};
use super::super::message_types::server;
pub type RegisterResult = Result<(), RegisterError>;
#[derive(Clone, Debug)]
pub struct RegisterError {
pub errtype: RegisterErrorType,
pub message: IrcMsg,
}
impl RegisterError {
pub fn should_pick_new_nickname(&self) -> bool... | (result: i32) -> bool {
RegisterErrorType::from_ord_known(result).is_some()
}
pub fn from_ord_known(result: i32) -> Option<RegisterErrorType> {
match result {
numerics::ERR_NONICKNAMEGIVEN => Some(RegisterErrorType::NoNicknameGiven),
numerics::ERR_NICKNAMEINUSE => Some(R... | is_known_error | identifier_name |
reflect.rs | 'b> Reflector<'a, 'b> {
pub fn c_uint(&mut self, u: uint) -> ValueRef {
C_uint(self.bcx.ccx(), u)
}
pub fn c_bool(&mut self, b: bool) -> ValueRef {
C_bool(self.bcx.ccx(), b)
}
pub fn c_slice(&mut self, s: InternedString) -> ValueRef {
// We're careful to not use first clas... |
ty::ty_str => self.visit("estr_uniq", &[]),
_ => {
let extra = self.c_mt(&ty::mt {
ty: typ,
mutbl: ast::MutImmutable,
});
self.visit("uniq", extra.as_slice())
... | {
let extra = Vec::new();
let extra = extra.append(self.c_mt(mt).as_slice());
self.visit("evec_uniq", extra.as_slice())
} | conditional_block |
reflect.rs | 'b> Reflector<'a, 'b> {
pub fn c_uint(&mut self, u: uint) -> ValueRef |
pub fn c_bool(&mut self, b: bool) -> ValueRef {
C_bool(self.bcx.ccx(), b)
}
pub fn c_slice(&mut self, s: InternedString) -> ValueRef {
// We're careful to not use first class aggregates here because that
// will kick us off fast isel. (Issue #4352.)
let bcx = self.bcx;
... | {
C_uint(self.bcx.ccx(), u)
} | identifier_body |
reflect.rs | ReStatic, ast::MutImmutable);
let scratch = rvalue_scratch_datum(bcx, str_ty, "");
let len = C_uint(bcx.ccx(), s.get().len());
let c_str = PointerCast(bcx, C_cstr(bcx.ccx(), s, false), Type::i8p(bcx.ccx()));
Store(bcx, c_str, GEPi(bcx, scratch.val, [ 0, 0 ]));
Store(bcx, len, GEP... | let modeval = 5u; // "by copy"
let extra = vec!(self.c_uint(i), | random_line_split | |
reflect.rs | {
// We're careful to not use first class aggregates here because that
// will kick us off fast isel. (Issue #4352.)
let bcx = self.bcx;
let str_ty = ty::mk_str_slice(bcx.tcx(), ty::ReStatic, ast::MutImmutable);
let scratch = rvalue_scratch_datum(bcx, str_ty, "");
let le... | visit_sig | identifier_name | |
listener.rs | use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::RwLock;
use apm::event::{CommandStarted, CommandResult};
use Client;
use error::Result;
pub type StartHook = fn(Client, &CommandStarted);
pub type CompletionHook = fn(Client, &CommandResult);
pub struct Listener {
no_s... | pub fn new() -> Listener {
Listener {
no_start_hooks: AtomicBool::new(true),
no_completion_hooks: AtomicBool::new(true),
start_hooks: RwLock::new(Vec::new()),
completion_hooks: RwLock::new(Vec::new()),
}
}
pub fn add_start_hook(&self, hook: St... | start_hooks: RwLock<Vec<StartHook>>,
completion_hooks: RwLock<Vec<CompletionHook>>,
}
impl Listener { | random_line_split |
listener.rs | use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::RwLock;
use apm::event::{CommandStarted, CommandResult};
use Client;
use error::Result;
pub type StartHook = fn(Client, &CommandStarted);
pub type CompletionHook = fn(Client, &CommandResult);
pub struct Listener {
no_s... |
let guard = self.start_hooks.read()?;
for hook in guard.deref().iter() {
hook(client.clone(), started);
}
Ok(())
}
pub fn run_completion_hooks(&self, client: Client, result: &CommandResult) -> Result<()> {
if self.no_completion_hooks.load(Ordering::SeqCst... | {
return Ok(());
} | conditional_block |
listener.rs | use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::RwLock;
use apm::event::{CommandStarted, CommandResult};
use Client;
use error::Result;
pub type StartHook = fn(Client, &CommandStarted);
pub type CompletionHook = fn(Client, &CommandResult);
pub struct Listener {
no_s... | (&self, hook: CompletionHook) -> Result<()> {
let mut guard = self.completion_hooks.write()?;
self.no_completion_hooks.store(false, Ordering::SeqCst);
Ok(guard.deref_mut().push(hook))
}
pub fn run_start_hooks(&self, client: Client, started: &CommandStarted) -> Result<()> {
if se... | add_completion_hook | identifier_name |
lib.rs | //! The operational library makes it easy to implement monads with tricky control flow.
//!
//! This is very useful for: writing web applications in a sequential style,
//! programming games with a uniform interface for human and AI players and easy replay,
//! implementing fast parser monads, designing monadic DSLs, e... | /// The case `Pure(a)` means that the program contains no instructions and just returns the result `a`.
Pure(Box<A>),
/// The case `Then(instr, k)` means that the first instruction is `instr` and the remaining program is given by the kleisli arrow `k`.
Then(Box<I>, Kleisli<'a, I, I::Return, A>)
}
impl<... | /// - `A` is the return type of the program.
pub enum Program<'a, I: Instr, A> { | random_line_split |
lib.rs | //! The operational library makes it easy to implement monads with tricky control flow.
//!
//! This is very useful for: writing web applications in a sequential style,
//! programming games with a uniform interface for human and AI players and easy replay,
//! implementing fast parser monads, designing monadic DSLs, e... | {
Program::Pure(Box::new(a))
} | identifier_body | |
lib.rs | //! The operational library makes it easy to implement monads with tricky control flow.
//!
//! This is very useful for: writing web applications in a sequential style,
//! programming games with a uniform interface for human and AI players and easy replay,
//! implementing fast parser monads, designing monadic DSLs, e... | <'a, I: 'a + Instr, A>(a: A) -> Program<'a, I, A> {
Program::Pure(Box::new(a))
}
| point | identifier_name |
paint_listener.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 LayerId;
use LayerProperties;
use layers::layers::{BufferRequest, LayerBufferSet};
use layers::platform::surfa... |
/// Informs the compositor of the layers for the given pipeline. The compositor responds by
/// creating and/or destroying paint layers as necessary.
fn initialize_layers_for_pipeline(&mut self,
pipeline_id: PipelineId,
properties:... | fn native_display(&mut self) -> Option<NativeDisplay>; | random_line_split |
cell.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... |
}
/// Copy a `Ref`.
///
/// The `RefCell` is already immutably borrowed, so this cannot fail.
///
/// A `Clone` implementation would interfere with the widespread
/// use of `r.borrow().clone()` to clone the contents of a `RefCell`.
#[experimental = "likely to be moved to a method, pending language changes"]
pub fn c... | {
self._value
} | identifier_body |
cell.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... |
/// Mutably borrows the wrapped value.
///
/// The borrow lasts until the returned `RefMut` exits scope. The value
/// cannot be borrowed while this borrow is active.
///
/// # Panics
///
/// Panics if the value is currently borrowed.
#[unstable]
pub fn borrow_mut<'a>(&'a self) ... | }
} | random_line_split |
cell.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... | (value: T) -> UnsafeCell<T> {
UnsafeCell { value: value }
}
/// Gets a mutable pointer to the wrapped value.
///
/// This function is unsafe as the pointer returned is an unsafe pointer and
/// no guarantees are made about the aliasing of the pointers being handed
/// out in this or oth... | new | identifier_name |
uart.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | Forced1,
/// Partity bit forced to 0.
Forced0,
} | random_line_split | |
uart.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | {
/// Partity disabled.
Disabled,
/// Partity bit added to make number of 1s odd.
Odd,
/// Partity bit added to make number of 1s even.
Even,
/// Partity bit forced to 1.
Forced1,
/// Partity bit forced to 0.
Forced0,
}
| Parity | identifier_name |
legacy.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 super::super::NameDag;
use super::IdStaticSet;
use super::NameSet;
use crate::IdSet;
/// A legacy token that enables conversion betwee... | (value: (LegacyCodeNeedIdAccess, IdSet, &'a NameDag)) -> NameSet {
NameSet::from_spans_dag(value.1, value.2).unwrap()
}
}
#[cfg(test)]
mod tests {
use nonblocking::non_blocking_result as r;
use super::super::id_static::tests::with_dag;
use super::*;
use crate::DagAlgorithm;
use crate::... | from | identifier_name |
legacy.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 super::super::NameDag;
use super::IdStaticSet; | /// A legacy token that enables conversion between IdSet (id-based)
/// and NameSet (hash-based). It should not be used for new Rust code.
#[derive(Copy, Clone)]
pub struct LegacyCodeNeedIdAccess;
// This is ideally not provided. However revision numbers in revset still have
// large use-cases in Python and for now w... | use super::NameSet;
use crate::IdSet;
| random_line_split |
ffi.rs | // The MIT License (MIT)
//
// Copyright (c) 2016 Vladislav Nikonov
//
// 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 us... | {
pub sum: c_double,
pub delay: [c_double; DC_FILTER_SIZE],
}
impl Clone for DCFilter {
fn clone(&self) -> Self {
*self
}
}
impl Default for DCFilter {
fn default() -> Self {
unsafe { mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Ayumi {
pub channels: [ToneChann... | DCFilter | identifier_name |
ffi.rs | // The MIT License (MIT)
//
// Copyright (c) 2016 Vladislav Nikonov
//
// 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 us... |
}
#[repr(C)]
#[derive(Copy)]
pub struct DCFilter {
pub sum: c_double,
pub delay: [c_double; DC_FILTER_SIZE],
}
impl Clone for DCFilter {
fn clone(&self) -> Self {
*self
}
}
impl Default for DCFilter {
fn default() -> Self {
unsafe { mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy... | {
unsafe { mem::zeroed() }
} | identifier_body |
ffi.rs | // The MIT License (MIT)
//
// Copyright (c) 2016 Vladislav Nikonov
//
// 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 us... | unsafe { mem::zeroed() }
}
}
extern "C" {
pub fn ayumi_configure(ay: *mut Ayumi, is_ym: c_int, clock_rate: c_double, sr: c_int);
pub fn ayumi_set_pan(ay: *mut Ayumi, index: c_int, pan: c_double, is_eqp: c_int);
pub fn ayumi_set_tone(ay: *mut Ayumi, index: c_int, period: c_int);
pub fn ayumi_... | *self
}
}
impl Default for Ayumi {
fn default() -> Self { | random_line_split |
fmt.rs | #![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(rust_2018_idioms, unused_lifetimes)]
use std::path::PathBuf;
use std::process::Command;
#[test]
fn fmt() | .output()
.unwrap();
println!("status: {}", output.status);
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
assert!(
output.status.success(),
"Formatting check failed. Run `cargo dev fmt` to... | {
if option_env!("RUSTC_TEST_SUITE").is_some() || option_env!("NO_FMT_TEST").is_some() {
return;
}
// Skip this test if nightly rustfmt is unavailable
let rustup_output = Command::new("rustup")
.args(&["component", "list", "--toolchain", "nightly"])
.output()
.unwrap();
... | identifier_body |
fmt.rs | #![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(rust_2018_idioms, unused_lifetimes)]
use std::path::PathBuf;
use std::process::Command;
#[test]
fn fmt() {
if option_env!("RUSTC_TEST_SUITE").is_some() || option_env!("NO_FMT_TEST").is_some() {
return;
}
// Skip this test if nightly ... |
assert!(
output.status.success(),
"Formatting check failed. Run `cargo dev fmt` to update formatting."
);
} | .unwrap();
println!("status: {}", output.status);
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("stderr: {}", String::from_utf8_lossy(&output.stderr)); | random_line_split |
fmt.rs | #![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(rust_2018_idioms, unused_lifetimes)]
use std::path::PathBuf;
use std::process::Command;
#[test]
fn fmt() {
if option_env!("RUSTC_TEST_SUITE").is_some() || option_env!("NO_FMT_TEST").is_some() |
// Skip this test if nightly rustfmt is unavailable
let rustup_output = Command::new("rustup")
.args(&["component", "list", "--toolchain", "nightly"])
.output()
.unwrap();
assert!(rustup_output.status.success());
let component_output = String::from_utf8_lossy(&rustup_output.stdout... | {
return;
} | conditional_block |
fmt.rs | #![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(rust_2018_idioms, unused_lifetimes)]
use std::path::PathBuf;
use std::process::Command;
#[test]
fn | () {
if option_env!("RUSTC_TEST_SUITE").is_some() || option_env!("NO_FMT_TEST").is_some() {
return;
}
// Skip this test if nightly rustfmt is unavailable
let rustup_output = Command::new("rustup")
.args(&["component", "list", "--toolchain", "nightly"])
.output()
.unwrap();
... | fmt | identifier_name |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FormDataBinding; | use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::str::{DOMString, USVString};
use dom::blob::{Blob, BlobImpl};
use dom::file::File;
use dom::htmlformelement::HTMLFormElement;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use strin... | use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods;
use dom::bindings::codegen::UnionTypes::BlobOrUSVString;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, Root}; | random_line_split |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FormDataBinding;
use dom::bindings::cod... |
pub fn Constructor(global: GlobalRef, form: Option<&HTMLFormElement>) -> Fallible<Root<FormData>> {
// TODO: Construct form data set for form if it is supplied
Ok(FormData::new(form, global))
}
}
impl FormDataMethods for FormData {
// https://xhr.spec.whatwg.org/#dom-formdata-append
f... | {
reflect_dom_object(box FormData::new_inherited(form),
global, FormDataBinding::Wrap)
} | identifier_body |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FormDataBinding;
use dom::bindings::cod... | {
reflector_: Reflector,
data: DOMRefCell<HashMap<Atom, Vec<FormDatum>>>,
form: Option<JS<HTMLFormElement>>
}
impl FormData {
fn new_inherited(form: Option<&HTMLFormElement>) -> FormData {
FormData {
reflector_: Reflector::new(),
data: DOMRefCell::new(HashMap::new()),
... | FormData | identifier_name |
no-renderer.rs | extern crate sdl2;
use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::video::Window;
use sdl2::rect::Rect;
use std::time::Duration;
const WINDOW_WIDTH : u32 = 800;
const WINDOW_HEIGHT : u32 = 600;
#[derive(Clone, Copy)]
enum Gradient { | }
fn set_window_gradient(window: &mut Window, event_pump: &sdl2::EventPump, gradient: Gradient) -> Result<(), String> {
let mut surface = window.surface(event_pump)?;
for i in 0.. (WINDOW_WIDTH / 4) {
let c : u8 = 255 - (i as u8);
let i = i as i32;
let color = match gradient {
... | Red,
Cyan,
Green,
Blue,
White | random_line_split |
no-renderer.rs | extern crate sdl2;
use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::video::Window;
use sdl2::rect::Rect;
use std::time::Duration;
const WINDOW_WIDTH : u32 = 800;
const WINDOW_HEIGHT : u32 = 600;
#[derive(Clone, Copy)]
enum | {
Red,
Cyan,
Green,
Blue,
White
}
fn set_window_gradient(window: &mut Window, event_pump: &sdl2::EventPump, gradient: Gradient) -> Result<(), String> {
let mut surface = window.surface(event_pump)?;
for i in 0.. (WINDOW_WIDTH / 4) {
let c : u8 = 255 - (i as u8);
let i = i a... | Gradient | identifier_name |
no-renderer.rs | extern crate sdl2;
use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::video::Window;
use sdl2::rect::Rect;
use std::time::Duration;
const WINDOW_WIDTH : u32 = 800;
const WINDOW_HEIGHT : u32 = 600;
#[derive(Clone, Copy)]
enum Gradient {
Red,
Cyan,
Green,
Blue,
... |
pub fn main() -> Result<(), String> {
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
let mut window = video_subsystem.window("rust-sdl2 demo: No Renderer", WINDOW_WIDTH, WINDOW_HEIGHT)
.position_centered()
.build()
.map_err(|e| e.to_string())?;
let m... | {
use crate::Gradient::*;
match gradient {
Red => Cyan,
Cyan => Green,
Green => Blue,
Blue => White,
White => Red,
}
} | identifier_body |
reseeding.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 ... |
}
}
impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> {
fn next_u32(&mut self) -> u32 {
self.reseed_if_necessary();
self.bytes_generated += 4;
self.rng.next_u32()
}
fn next_u64(&mut self) -> u64 {
self.reseed_if_necessary();
self.bytes_generated +=... | {
self.reseeder.reseed(&mut self.rng);
self.bytes_generated = 0;
} | conditional_block |
reseeding.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 ... |
/// Reseed the internal RNG if the number of bytes that have been
/// generated exceed the threshold.
pub fn reseed_if_necessary(&mut self) {
if self.bytes_generated >= self.generation_threshold {
self.reseeder.reseed(&mut self.rng);
self.bytes_generated = 0;
}
... | {
ReseedingRng {
rng: rng,
generation_threshold: generation_threshold,
bytes_generated: 0,
reseeder: reseeder
}
} | identifier_body |
reseeding.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 ... | <R, Rsdr> {
rng: R,
generation_threshold: usize,
bytes_generated: usize,
/// Controls the behaviour when reseeding the RNG.
pub reseeder: Rsdr,
}
impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> {
/// Create a new `ReseedingRng` with the given parameters.
///
/// # Arguments
//... | ReseedingRng | identifier_name |
reseeding.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 core::iter::{order, repeat};
use super::{ReseedingRng, ReseedWithDefault};
use {SeedableRng, Rng};
struct Counter {
i: u32
}
impl Rng for Counter {
fn next_u32(&mut self) -> u32 {
self.i += 1;
// very random
self.i - 1
}
}
... |
#[cfg(test)]
mod tests {
use std::prelude::v1::*;
| random_line_split |
into_iter.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::option::IntoIter;
// #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub enum Option<T> {
// /// No value
// #[stable(feature = "rust1", since... |
}
| {
let x: Option<T> = None::<T>;
let mut n: usize = 0;
for v in x {
n += 1;
assert_eq!(v, "string");
}
assert_eq!(n, 0);
} | identifier_body |
into_iter.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::option::IntoIter;
// #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub enum Option<T> {
// /// No value
// #[stable(feature = "rust1", since... | // Some(T)
// }
// impl<T> IntoIterator for Option<T> {
// type Item = T;
// type IntoIter = IntoIter<T>;
//
// /// Returns a consuming iterator over the possibly contained value.
// ///
// /// # Examples
// ///
// /// ```
// /// let x... | random_line_split | |
into_iter.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::option::IntoIter;
// #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub enum Option<T> {
// /// No value
// #[stable(feature = "rust1", since... | () {
let x: Option<T> = None::<T>;
let mut n: usize = 0;
for v in x {
n += 1;
assert_eq!(v, "string");
}
assert_eq!(n, 0);
}
}
| into_iter_test4 | identifier_name |
time.rs | use std::io::{self, Write};
use std::time::{Duration, Instant};
/// RAII timer to measure how long phases take.
#[derive(Debug)]
pub struct Timer<'a> {
output: bool,
name: &'a str,
start: Instant,
}
impl<'a> Timer<'a> {
/// Creates a Timer with the given name, and starts it. By default,
/// will p... |
/// Returns the time elapsed since the timer's creation
pub fn elapsed(&self) -> Duration {
Instant::now() - self.start
}
fn print_elapsed(&mut self) {
if self.output {
let elapsed = self.elapsed();
let time = (elapsed.as_secs() as f64) * 1e3 +
... | {
self.output = output;
self
} | identifier_body |
time.rs | use std::io::{self, Write};
use std::time::{Duration, Instant};
/// RAII timer to measure how long phases take.
#[derive(Debug)]
pub struct Timer<'a> {
output: bool,
name: &'a str,
start: Instant,
}
impl<'a> Timer<'a> {
/// Creates a Timer with the given name, and starts it. By default,
/// will p... |
}
}
impl<'a> Drop for Timer<'a> {
fn drop(&mut self) {
self.print_elapsed();
}
}
| {
let elapsed = self.elapsed();
let time = (elapsed.as_secs() as f64) * 1e3 +
(elapsed.subsec_nanos() as f64) / 1e6;
let stderr = io::stderr();
// Arbitrary output format, subject to change.
writeln!(stderr.lock(), " time: {:>9.3} ms.\t{}", ti... | conditional_block |
time.rs | use std::io::{self, Write};
use std::time::{Duration, Instant};
/// RAII timer to measure how long phases take.
#[derive(Debug)]
pub struct Timer<'a> {
output: bool,
name: &'a str,
start: Instant,
}
impl<'a> Timer<'a> {
/// Creates a Timer with the given name, and starts it. By default,
/// will p... | pub fn with_output(mut self, output: bool) -> Self {
self.output = output;
self
}
/// Returns the time elapsed since the timer's creation
pub fn elapsed(&self) -> Duration {
Instant::now() - self.start
}
fn print_elapsed(&mut self) {
if self.output {
... |
/// Sets whether or not the Timer will print a message
/// when it is dropped. | random_line_split |
time.rs | use std::io::{self, Write};
use std::time::{Duration, Instant};
/// RAII timer to measure how long phases take.
#[derive(Debug)]
pub struct Timer<'a> {
output: bool,
name: &'a str,
start: Instant,
}
impl<'a> Timer<'a> {
/// Creates a Timer with the given name, and starts it. By default,
/// will p... | (name: &'a str) -> Self {
Timer {
output: true,
name,
start: Instant::now(),
}
}
/// Sets whether or not the Timer will print a message
/// when it is dropped.
pub fn with_output(mut self, output: bool) -> Self {
self.output = output;
... | new | identifier_name |
flexbox_sub_layout.rs | /*!
A very simple application that show how to use a flexbox layout.
Requires the following features: `cargo run --example flexbox --features "flexbox"`
*/
extern crate native_windows_gui as nwg;
use nwg::NativeUi;
#[derive(Default)]
pub struct FlexBoxApp {
window: nwg::Window,
layout: nwg::FlexboxL... |
impl FlexBoxApp {
fn exit(&self) {
nwg::stop_thread_dispatch();
}
}
//
// ALL of this stuff is handled by native-windows-derive
//
mod flexbox_app_ui {
use native_windows_gui as nwg;
use super::*;
use std::rc::Rc;
use std::cell::RefCell;
use std::ops::Deref;
pub struct FlexB... | button1: nwg::Button,
layout2: nwg::FlexboxLayout,
button2: nwg::Button,
button3: nwg::Button,
} | random_line_split |
flexbox_sub_layout.rs | /*!
A very simple application that show how to use a flexbox layout.
Requires the following features: `cargo run --example flexbox --features "flexbox"`
*/
extern crate native_windows_gui as nwg;
use nwg::NativeUi;
#[derive(Default)]
pub struct FlexBoxApp {
window: nwg::Window,
layout: nwg::FlexboxL... | (mut data: FlexBoxApp) -> Result<FlexBoxAppUi, nwg::NwgError> {
use nwg::Event as E;
// Controls
nwg::Window::builder()
.size((500, 500))
.position((300, 300))
.title("Flexbox example")
.build(&mut data.window)?... | build_ui | identifier_name |
flexbox_sub_layout.rs | /*!
A very simple application that show how to use a flexbox layout.
Requires the following features: `cargo run --example flexbox --features "flexbox"`
*/
extern crate native_windows_gui as nwg;
use nwg::NativeUi;
#[derive(Default)]
pub struct FlexBoxApp {
window: nwg::Window,
layout: nwg::FlexboxL... | .build(&mut data.button2)?;
nwg::Button::builder()
.text("Btn 3")
.parent(&data.window)
.focus(true)
.build(&mut data.button3)?;
// Wrap-up
let ui =FlexBoxAppUi {
inner: Rc::new(data),
... | {
use nwg::Event as E;
// Controls
nwg::Window::builder()
.size((500, 500))
.position((300, 300))
.title("Flexbox example")
.build(&mut data.window)?;
nwg::Button::builder()
.tex... | identifier_body |
url.rs | use std::{error::Error as StdError, io::Write, str::FromStr};
use diesel::{backend::Backend, deserialize, serialize, sql_types::Text};
use url::Url as OrigUrl;
#[derive(AsExpression, Clone, Debug, FromSqlRow)]
#[sql_type = "Text"]
pub struct Url(pub OrigUrl);
impl<DB> serialize::ToSql<Text, DB> for Url
where
DB:... | (u: OrigUrl) -> Self {
Url(u)
}
}
impl FromStr for Url {
type Err = <OrigUrl as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
FromStr::from_str(s).map(Url)
}
}
| from | identifier_name |
url.rs | use std::{error::Error as StdError, io::Write, str::FromStr};
use diesel::{backend::Backend, deserialize, serialize, sql_types::Text};
use url::Url as OrigUrl;
#[derive(AsExpression, Clone, Debug, FromSqlRow)]
#[sql_type = "Text"]
pub struct Url(pub OrigUrl);
| serialize::ToSql::<Text, DB>::to_sql(self.0.as_str(), out)
}
}
impl<DB> deserialize::FromSql<Text, DB> for Url
where
DB: Backend<RawValue = [u8]>,
{
fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
deserialize::FromSql::<Text, DB>::from_sql(bytes).and_then(|s: String... | impl<DB> serialize::ToSql<Text, DB> for Url
where
DB: Backend,
{
fn to_sql<W: Write>(&self, out: &mut serialize::Output<W, DB>) -> serialize::Result { | random_line_split |
url.rs | use std::{error::Error as StdError, io::Write, str::FromStr};
use diesel::{backend::Backend, deserialize, serialize, sql_types::Text};
use url::Url as OrigUrl;
#[derive(AsExpression, Clone, Debug, FromSqlRow)]
#[sql_type = "Text"]
pub struct Url(pub OrigUrl);
impl<DB> serialize::ToSql<Text, DB> for Url
where
DB:... |
}
impl FromStr for Url {
type Err = <OrigUrl as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
FromStr::from_str(s).map(Url)
}
}
| {
Url(u)
} | identifier_body |
animated_mesh.rs | //! Defines an animated triangle mesh geometry. It is required that the topology
//! of the mesh being animated does not change. While properties of triangles can
//! be changed over time triangles can't be added or removed. Intersection test
//! are accelerated internally by storing the triangles of the mesh in a BVH
... | {
bvh: BVH<AnimatedTriangle>,
}
impl AnimatedMesh {
/// Create a new AnimatedMesh from the meshes passed. It's assumed the meshes
/// are sorted in ascending time
pub fn new(meshes: Vec<Arc<Mesh>>, times: Vec<f32>) -> AnimatedMesh {
let pos = meshes.iter().map(|m| m.bvh.iter().next().unwrap().... | AnimatedMesh | identifier_name |
animated_mesh.rs | //! Defines an animated triangle mesh geometry. It is required that the topology
//! of the mesh being animated does not change. While properties of triangles can
//! be changed over time triangles can't be added or removed. Intersection test
//! are accelerated internally by storing the triangles of the mesh in a BVH
... |
}
impl Boundable for AnimatedMesh {
fn bounds(&self, start: f32, end: f32) -> BBox {
self.bvh.bounds(start, end)
}
fn update_deformation(&mut self, start: f32, end: f32) {
self.bvh.rebuild(start, end);
}
}
/// An animated triangle in the mesh. Just stores a reference to the mesh
/// a... | {
self.bvh.intersect(ray, |r, i| i.intersect(r))
} | identifier_body |
animated_mesh.rs | //! Defines an animated triangle mesh geometry. It is required that the topology
//! of the mesh being animated does not change. While properties of triangles can
//! be changed over time triangles can't be added or removed. Intersection test
//! are accelerated internally by storing the triangles of the mesh in a BVH
... | ,
}
}
/// Get the position at some time
fn position(&self, i: usize, time: f32) -> Point {
match self.active_keyframes(time) {
(lo, None) => (*self.positions[lo])[i],
(lo, Some(hi)) => {
let a = (*self.positions[lo])[i];
let b = (*self.... | {
if i == self.times.len() {
(i - 1, None)
} else if i == 0 {
(0, None)
} else {
(i - 1, Some(i))
}
} | conditional_block |
animated_mesh.rs | //! Defines an animated triangle mesh geometry. It is required that the topology
//! of the mesh being animated does not change. While properties of triangles can
//! be changed over time triangles can't be added or removed. Intersection test
//! are accelerated internally by storing the triangles of the mesh in a BVH
... | fn active_keyframes(&self, time: f32) -> (usize, Option<usize>) {
match self.times.binary_search_by(|t| t.partial_cmp(&time).unwrap()) {
Ok(i) => (i, None),
Err(i) => {
if i == self.times.len() {
(i - 1, None)
} else if i == 0 {
... | }
/// Get the active indices in the buffers for some time | random_line_split |
particle.rs | use crate::numeric::StateVector;
use crate::typenum::consts::{U1, U2, U3};
use crate::typenum::{Exp, Pow, Prod, Same, Unsigned};
use diffgeom::coordinates::{ConversionTo, CoordinateSystem, Point};
use diffgeom::inner;
use diffgeom::metric::MetricSystem;
use diffgeom::tensors::Vector;
use generic_array::{ArrayLength, Ge... | }
StateVector(result)
}
}
impl<C: CoordinateSystem> Particle<C>
where
C::Dimension: Pow<U1>,
Exp<C::Dimension, U1>: ArrayLength<f64>,
{
pub fn convert<C2: CoordinateSystem +'static>(&self) -> Particle<C2>
where
C: ConversionTo<C2>,
C2::Dimension: Pow<U1> + Pow<U2>,
... | random_line_split | |
particle.rs | use crate::numeric::StateVector;
use crate::typenum::consts::{U1, U2, U3};
use crate::typenum::{Exp, Pow, Prod, Same, Unsigned};
use diffgeom::coordinates::{ConversionTo, CoordinateSystem, Point};
use diffgeom::inner;
use diffgeom::metric::MetricSystem;
use diffgeom::tensors::Vector;
use generic_array::{ArrayLength, Ge... | (&mut self, dir: &Self::Derivative, amount: f64) {
let d = C::Dimension::to_usize();
for i in 0..d {
self.x[i] += dir.0[i] * amount;
self.v[i] += dir.0[i + d] * amount;
self.v.set_point(self.x.clone());
}
}
}
impl<C: CoordinateSystem> Particle<C>
where
... | shift_in_place | identifier_name |
particle.rs | use crate::numeric::StateVector;
use crate::typenum::consts::{U1, U2, U3};
use crate::typenum::{Exp, Pow, Prod, Same, Unsigned};
use diffgeom::coordinates::{ConversionTo, CoordinateSystem, Point};
use diffgeom::inner;
use diffgeom::metric::MetricSystem;
use diffgeom::tensors::Vector;
use generic_array::{ArrayLength, Ge... |
pub fn get_vel(&self) -> &Vector<C> {
&self.v
}
}
impl<C: CoordinateSystem> State for Particle<C>
where
C::Dimension: Pow<U1> + Mul<U2> + Unsigned,
Exp<C::Dimension, U1>: ArrayLength<f64>,
Prod<C::Dimension, U2>: ArrayLength<f64>,
<Prod<C::Dimension, U2> as ArrayLength<f64>>::ArrayTyp... | {
&self.x
} | identifier_body |
thread.rs | //
// Copyright (c) 2011-2017, UDI Contributors
// All rights reserved.
//
// 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/.
//
#![deny(warnings)]
#![allow(unused_varia... | pub fn get_pc(&mut self) -> Result<u64> {
let reg = match self.architecture {
Architecture::X86 => Register::X86_EIP,
Architecture::X86_64 => Register::X86_64_RIP
};
self.read_register(reg)
}
pub fn set_single_step(&mut self, setting: bool) -> Result<()> {
... | pub fn get_state(&self) -> super::ThreadState {
self.state
}
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.