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 |
|---|---|---|---|---|
string_utils.rs | //! Various utilities for string operations.
/// Join items of a collection with separator.
pub trait JoinWithSeparator<S> {
/// Result type of the operation
type Output;
/// Join items of `self` with `separator`.
fn join(self, separator: S) -> Self::Output;
}
impl<S, S2, X> JoinWithSeparator<S2> for X
wher... | replace_all_sub_vecs(&mut parts, vec!["3", "d"]);
replace_all_sub_vecs(&mut parts, vec!["4", "d"]);
let mut str = String::new();
for (i, part) in parts.into_iter().enumerate() {
if part.is_empty() {
continue;
}
if i > 0 &&!(part.chars().all(|c| c.is_digit(10)) &&!ends_with_digit(&str)) {
... | let mut parts: Vec<_> = it.map(|x| x.as_ref().to_lowercase()).collect();
replace_all_sub_vecs(&mut parts, vec!["na", "n"]);
replace_all_sub_vecs(&mut parts, vec!["open", "g", "l"]);
replace_all_sub_vecs(&mut parts, vec!["i", "o"]);
replace_all_sub_vecs(&mut parts, vec!["2", "d"]); | random_line_split |
test_register_deregister.rs | use mio::*;
use mio::tcp::*;
use bytes::SliceBuf;
use super::localhost;
const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);
struct TestHandler {
server: TcpListener,
client: TcpStream,
state: usize,
}
impl TestHandler {
fn new(srv: TcpListener, cli: TcpStream) -> TestHandler {
Tes... |
}
impl Handler for TestHandler {
type Timeout = usize;
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<TestHandler>, token: Token, events: EventSet) {
if events.is_readable() {
self.handle_read(event_loop, token, events);
}
if events.is_writable() {
... | {
debug!("handle_write; token={:?}; state={:?}", token, self.state);
assert!(token == CLIENT, "unexpected token {:?}", token);
assert!(self.state == 1, "unexpected state {}", self.state);
self.state = 2;
event_loop.deregister(&self.client).unwrap();
event_loop.timeout_m... | identifier_body |
test_register_deregister.rs | use mio::*;
use mio::tcp::*;
use bytes::SliceBuf;
use super::localhost;
const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);
struct TestHandler {
server: TcpListener,
client: TcpStream,
state: usize,
}
impl TestHandler {
fn new(srv: TcpListener, cli: TcpStream) -> TestHandler {
Tes... | let addr = localhost();
let server = TcpListener::bind(&addr).unwrap();
info!("register server socket");
event_loop.register(&server, SERVER, EventSet::readable(), PollOpt::edge()).unwrap();
let client = TcpStream::connect(&addr).unwrap();
// Register client socket only as writable
event... | random_line_split | |
test_register_deregister.rs | use mio::*;
use mio::tcp::*;
use bytes::SliceBuf;
use super::localhost;
const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);
struct TestHandler {
server: TcpListener,
client: TcpStream,
state: usize,
}
impl TestHandler {
fn new(srv: TcpListener, cli: TcpStream) -> TestHandler {
Tes... | (&mut self, event_loop: &mut EventLoop<TestHandler>, token: Token, _: EventSet) {
debug!("handle_write; token={:?}; state={:?}", token, self.state);
assert!(token == CLIENT, "unexpected token {:?}", token);
assert!(self.state == 1, "unexpected state {}", self.state);
self.state = 2;
... | handle_write | identifier_name |
global.rs | //! The global state.
use parking_lot::Mutex;
use std::collections::HashSet;
use std::{mem, panic};
use {rand, hazard, mpsc, debug, settings};
use garbage::Garbage;
lazy_static! {
/// The global state.
///
/// This state is shared between all the threads.
static ref STATE: State = State::new();
}
///... | {
/// The channel of messages.
chan: mpsc::Receiver<Message>,
/// The to-be-destroyed garbage.
garbage: Vec<Garbage>,
/// The current hazards.
hazards: Vec<hazard::Reader>,
}
impl Garbo {
/// Handle a given message.
///
/// "Handle" in this case refers to applying the operation def... | Garbo | identifier_name |
global.rs | //! The global state.
use parking_lot::Mutex;
use std::collections::HashSet;
use std::{mem, panic};
use {rand, hazard, mpsc, debug, settings};
use garbage::Garbage;
lazy_static! {
/// The global state.
///
/// This state is shared between all the threads.
static ref STATE: State = State::new();
}
///... | }
}
#[test]
fn clean_up_state() {
fn dtor(x: *const u8) {
unsafe {
*(x as *mut u8) = 1;
}
}
for _ in 0..1000 {
let b = Box::new(0);
{
let s = State::new();
s.export_garbage(vec!... | {
fn dtor(x: *const u8) {
unsafe {
*(x as *mut u8) = 1;
}
}
let s = State::new();
for _ in 0..1000 {
let b = Box::new(0);
let h = s.create_hazard();
h.protect(&*b);
s.export_garbage(vec![Garbage::new... | identifier_body |
global.rs | //! The global state.
use parking_lot::Mutex;
use std::collections::HashSet;
use std::{mem, panic};
use {rand, hazard, mpsc, debug, settings};
use garbage::Garbage;
lazy_static! {
/// The global state.
///
/// This state is shared between all the threads.
static ref STATE: State = State::new();
}
///... | /// garbage. If another thread is currently collecting garbage, `Err(())` is returned,
/// otherwise it returns `Ok(())`.
///
/// Garbage collection works by scanning the hazards and dropping all the garbage which is not
/// currently active in the hazards.
fn try_gc(&self) -> Result<(), ()> {
... |
/// Try to collect the garbage.
///
/// This will handle all of the messages in the channel and then attempt at collect the | random_line_split |
hash.rs | use std::collections::HashMap;
fn | (number: &str) -> &str {
match number {
"798-1364" => "We're sorry, the call cannot be completed as dialed.
Please hang up and try again.",
"645-7689" => "Hello, this is Mr. Awesome's Pizza. My name is Fred.
What can I get for you today?",
_ => "Hi! Who is this again... | call | identifier_name |
hash.rs | use std::collections::HashMap;
| "645-7689" => "Hello, this is Mr. Awesome's Pizza. My name is Fred.
What can I get for you today?",
_ => "Hi! Who is this again?"
}
}
fn main() {
let mut contacts = HashMap::new();
contacts.insert("Daniel", "798-1364");
contacts.insert("Ashley", "645-7689");
contacts.i... | fn call(number: &str) -> &str {
match number {
"798-1364" => "We're sorry, the call cannot be completed as dialed.
Please hang up and try again.", | random_line_split |
hash.rs | use std::collections::HashMap;
fn call(number: &str) -> &str {
match number {
"798-1364" => "We're sorry, the call cannot be completed as dialed.
Please hang up and try again.",
"645-7689" => "Hello, this is Mr. Awesome's Pizza. My name is Fred.
What can I get for you today... | _ => println!("Don't have Ashley's number."),
}
contacts.remove(&("Ashley"));
// `HashMap::iter()` 返回一个迭代器,该迭代器获得
// 任意顺序的 (&'a key, &'a value) 对。
// (原文:`HashMap::iter()` returns an iterator that yields
// (&'a key, &'a value) pairs in arbitrary order.)
for (contact, &number) in... | {
let mut contacts = HashMap::new();
contacts.insert("Daniel", "798-1364");
contacts.insert("Ashley", "645-7689");
contacts.insert("Katie", "435-8291");
contacts.insert("Robert", "956-1745");
// 接受一个引用并返回 Option<&V>
match contacts.get(&"Daniel") {
Some(&number) => println!("Callin... | identifier_body |
sections.rs | use super::{ConfigParseError, Error};
use std::io::Read;
#[derive(Clone, Debug)]
pub struct Sections {
pub common_section: String,
pub page_sections: Vec<String>,
pub char_sections: Vec<String>,
pub kerning_sections: Vec<String>,
}
impl Sections {
pub fn new<R>(mut source: R) -> Result<Sections, E... | ))));
}
let mut lines = lines.skip(page_sections.len());
// Expect the "char" sections.
let _ = lines.next().unwrap(); // char_count_section
let char_sections = lines
.clone()
.take_while(|l| l.starts_with("char"))
.map(|s| s.to_strin... | return Err(Error::from(ConfigParseError::MissingSection(String::from(
"page", | random_line_split |
sections.rs | use super::{ConfigParseError, Error};
use std::io::Read;
#[derive(Clone, Debug)]
pub struct Sections {
pub common_section: String,
pub page_sections: Vec<String>,
pub char_sections: Vec<String>,
pub kerning_sections: Vec<String>,
}
impl Sections {
pub fn new<R>(mut source: R) -> Result<Sections, E... | ;
Ok(Sections {
common_section,
page_sections,
char_sections,
kerning_sections,
})
}
}
| {
Vec::new()
} | conditional_block |
sections.rs | use super::{ConfigParseError, Error};
use std::io::Read;
#[derive(Clone, Debug)]
pub struct | {
pub common_section: String,
pub page_sections: Vec<String>,
pub char_sections: Vec<String>,
pub kerning_sections: Vec<String>,
}
impl Sections {
pub fn new<R>(mut source: R) -> Result<Sections, Error>
where
R: Read,
{
// Load the entire file into a String.
let mut... | Sections | identifier_name |
pack.rs | // Copyright 2017 ThetaSinner
//
// This file is part of Osmium.
// Osmium is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Osmi... |
}
| {
target.extend(rest);
} | conditional_block |
pack.rs | // Copyright 2017 ThetaSinner
//
// This file is part of Osmium.
// Osmium is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Osmi... | if header_name == literal_without_indexing_header_name {
return true;
}
}
false
}
fn pack_indexed_header(index: usize, target: &mut Vec<u8>) {
let encoded_index = number::encode(index as u32, 7);
target.push(flags::INDEXED_HEADER_FLAG | encoded_index.prefix);
if let So... | fn is_literal_without_indexing_header(header_name: &String) -> bool {
for literal_without_indexing_header_name in LITERAL_WITHOUT_INDEXING.into_iter() { | random_line_split |
pack.rs | // Copyright 2017 ThetaSinner
//
// This file is part of Osmium.
// Osmium is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Osmi... | (field: &table::Field, use_huffman_coding: bool, target: &mut Vec<u8>) {
target.push(flags::LITERAL_WITH_INDEXING_FLAG);
target.extend(string::encode(String::from(field.name.clone()), use_huffman_coding));
target.extend(string::encode(String::from(field.value.clone()), use_huffman_coding));
}
fn pack_lite... | pack_literal_with_indexing | identifier_name |
pack.rs | // Copyright 2017 ThetaSinner
//
// This file is part of Osmium.
// Osmium is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Osmi... |
fn pack_literal_without_indexing(field: &table::Field, use_huffman_coding: bool, target: &mut Vec<u8>) {
target.push(0u8);
target.extend(string::encode(String::from(field.name.clone()), use_huffman_coding));
target.extend(string::encode(String::from(field.value.clone()), use_huffman_coding));
}
fn pack_... | {
trace!("index to use {}", index);
let encoded_name_index = number::encode(index as u32, 4);
trace!("prefix {}", encoded_name_index.prefix);
target.push((!flags::LITERAL_WITH_INDEXING_FLAG) & encoded_name_index.prefix);
if let Some(rest) = encoded_name_index.rest {
target.extend(rest);
... | identifier_body |
in6addr.rs | // Copyright © 2015-2017 winapi-rs developers
// 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.
// All files in the project carrying such notice may not be copied,... | // except according to those terms.
use shared::minwindef::{UCHAR, USHORT};
UNION!{union in6_addr_u {
[u16; 8],
Byte Byte_mut: [UCHAR; 16],
Word Word_mut: [USHORT; 8],
}}
STRUCT!{struct in6_addr {
u: in6_addr_u,
}}
pub type IN6_ADDR = in6_addr;
pub type PIN6_ADDR = *mut IN6_ADDR;
pub type LPIN6_ADDR = *... | random_line_split | |
common.rs | use bindings::types::*;
/* automatically generated by rust-bindgen */
pub type mraa_boolean_t = ::libc::c_uint;
#[link(name = "mraa")]
extern "C" { | -> mraa_boolean_t;
pub fn mraa_adc_raw_bits() -> ::libc::c_uint;
pub fn mraa_adc_supported_bits() -> ::libc::c_uint;
pub fn mraa_set_log_level(level: ::libc::c_int) -> mraa_result_t;
pub fn mraa_get_platform_name() -> *mut ::libc::c_char;
pub fn mraa_set_priority(priority: ::libc::c_uint) -> ::... | pub fn mraa_init() -> mraa_result_t;
pub fn mraa_deinit() -> ();
pub fn mraa_pin_mode_test(pin: ::libc::c_int, mode: mraa_pinmodes_t) | random_line_split |
map_renderer.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/state/game/map_renderer.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
A client-only state that depends on
the shared game state. This st... | (&mut self)
{
self.prev_visible_voxel_count = self.visible_voxels.get_ref().len() as u32;
let cam = gfx::Camera::get_active();
let dist = (cam.near_far.y / self.map.voxel_size) as i32; /* How far the camera can see. */
let res = self.map.resolution as f32;
let pos = math::Vec3f::new(cam.position... | update_visibility | identifier_name |
map_renderer.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/state/game/map_renderer.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
A client-only state that depends on
the shared game state. This st... |
}
| {
match name
{
"map.wireframe" =>
{
let res = console::Util::parse_bool(name, val);
match res
{
Ok(val) => { self.wireframe = val; None },
Err(msg) => { Some(msg) }
}
}
_ => Some(~"ERROR"),
}
} | identifier_body |
map_renderer.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson | Author: Jesse 'Jeaye' Wilkerson
Description:
A client-only state that depends on
the shared game state. This state is
used only to render the voxel map.
*/
use std::{ vec, ptr, mem, cast, cell };
use extra;
use gl2 = opengles::gl2;
use gfx;
use math;
use obj;
use obj::voxel;
use log::Log;
use... | See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/state/game/map_renderer.rs | random_line_split |
map_renderer.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/state/game/map_renderer.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
A client-only state that depends on
the shared game state. This st... |
}
}
}
/* Upload the data to the inactive buffer. */
check!(gl2::bind_buffer(gl2::ARRAY_BUFFER, ibo));
unsafe
{
let size = visible_voxels.len() * mem::size_of::<u32>();
let mem = check!(gl2::map_buffer_range(gl2::ARRAY_BUFFER, 0, size as i64, gl2::MAP_WRI... | { visible_voxels.push(states[index] & !voxel::Visible); } | conditional_block |
too-much-recursion-unwinding.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... |
fn r(recursed: *mut bool) -> r {
r { recursed: recursed }
}
fn main() {
let mut recursed = false;
let _r = r(&mut recursed);
recurse();
} | random_line_split | |
too-much-recursion-unwinding.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... | () {
println!("don't optimize me out");
recurse();
}
struct r {
recursed: *mut bool,
}
impl Drop for r {
fn drop(&mut self) {
unsafe {
if!*(self.recursed) {
*(self.recursed) = true;
recurse();
}
}
}
}
fn r(recursed: *mut bool... | recurse | identifier_name |
too-much-recursion-unwinding.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... |
}
}
}
fn r(recursed: *mut bool) -> r {
r { recursed: recursed }
}
fn main() {
let mut recursed = false;
let _r = r(&mut recursed);
recurse();
}
| {
*(self.recursed) = true;
recurse();
} | conditional_block |
committed.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | else {
output_commits.push(over_commit);
}
}
sum_commits(output_commits, input_commits)
}
/// Vector of input commitments to verify.
fn inputs_committed(&self) -> Vec<Commitment>;
/// Vector of output commitments to verify.
fn outputs_committed(&self) -> Vec<Commitment>;
/// Vector of kernel exces... | {
input_commits.push(over_commit);
} | conditional_block |
committed.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... |
}
/// Utility to sum positive and negative commitments, eliminating zero values
pub fn sum_commits(
mut positive: Vec<Commitment>,
mut negative: Vec<Commitment>,
) -> Result<Commitment, Error> {
let zero_commit = secp_static::commit_to_zero_value();
positive.retain(|x| *x!= zero_commit);
negative.retain(|x| *x!=... | {
// Sum all input|output|overage commitments.
let utxo_sum = self.sum_commitments(overage)?;
// Sum the kernel excesses accounting for the kernel offset.
let (kernel_sum, kernel_sum_plus_offset) = self.sum_kernel_excesses(&kernel_offset)?;
if utxo_sum != kernel_sum_plus_offset {
return Err(Error::Kernel... | identifier_body |
committed.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | (e: keychain::Error) -> Error {
Error::Keychain(e)
}
}
/// Implemented by types that hold inputs and outputs (and kernels)
/// containing Pedersen commitments.
/// Handles the collection of the commitments as well as their
/// summing, taking potential explicit overages of fees into account.
pub trait Committed {
... | from | identifier_name |
committed.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. | // distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The Committed trait and associated errors.
use failure::Fail;
us... | // You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software | random_line_split |
error.rs | use std::old_io::IoError;
use std::error::Error;
use std::fmt;
pub type ProtobufResult<T> = Result<T, ProtobufError>;
#[derive(Debug,Eq,PartialEq)]
pub enum ProtobufError {
IoError(IoError),
WireError(String),
}
impl fmt::Display for ProtobufError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
... | (&self) -> Option<&Error> {
match self {
&ProtobufError::IoError(ref e) => Some(e as &Error),
&ProtobufError::WireError(..) => None,
}
}
}
| cause | identifier_name |
error.rs | use std::old_io::IoError;
use std::error::Error;
use std::fmt;
pub type ProtobufResult<T> = Result<T, ProtobufError>;
#[derive(Debug,Eq,PartialEq)]
pub enum ProtobufError { | }
impl fmt::Display for ProtobufError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl Error for ProtobufError {
fn description(&self) -> &str {
match self {
// not sure that cause should be included in message
&ProtobufErro... | IoError(IoError),
WireError(String), | random_line_split |
error.rs | use std::old_io::IoError;
use std::error::Error;
use std::fmt;
pub type ProtobufResult<T> = Result<T, ProtobufError>;
#[derive(Debug,Eq,PartialEq)]
pub enum ProtobufError {
IoError(IoError),
WireError(String),
}
impl fmt::Display for ProtobufError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
impl Error for ProtobufError {
fn description(&self) -> &str {
match self {
// not sure that cause should be included in message
&ProtobufError::IoError(ref e) => e.description(),
&ProtobufError::WireError(ref e) => e.as_slice(),
}
}
fn cause(&self) -... | {
fmt::Debug::fmt(self, f)
} | identifier_body |
types.rs | use byteorder::{BigEndian, WriteBytesExt};
use protobuf::Message;
use std::io::Write;
use crate::protocol;
#[derive(Debug, PartialEq, Eq)]
pub enum MercuryMethod {
Get,
Sub,
Unsub,
Send,
}
#[derive(Debug)]
pub struct MercuryRequest {
pub method: MercuryMethod,
pub uri: String,
pub content... | (&self) -> u8 {
match *self {
MercuryMethod::Get | MercuryMethod::Send => 0xb2,
MercuryMethod::Sub => 0xb3,
MercuryMethod::Unsub => 0xb4,
}
}
}
impl MercuryRequest {
pub fn encode(&self, seq: &[u8]) -> Vec<u8> {
let mut packet = Vec::new();
pa... | command | identifier_name |
types.rs | use byteorder::{BigEndian, WriteBytesExt};
use protobuf::Message;
use std::io::Write;
use crate::protocol;
#[derive(Debug, PartialEq, Eq)]
pub enum MercuryMethod {
Get,
Sub,
Unsub,
Send,
}
#[derive(Debug)]
pub struct MercuryRequest {
pub method: MercuryMethod,
pub uri: String,
pub content... | header.write_to_writer(&mut packet).unwrap();
for p in &self.payload {
packet.write_u16::<BigEndian>(p.len() as u16).unwrap();
packet.write(p).unwrap();
}
packet
}
} | random_line_split | |
tests.rs | use super::*;
#[test]
fn test_struct_info_roundtrip() {
let s = ItemEnum::Struct(Struct {
struct_type: StructType::Plain,
generics: Generics { params: vec![], where_predicates: vec![] },
fields_stripped: false,
fields: vec![],
impls: vec![],
});
let struct_json = se... | impls: vec![],
});
let union_json = serde_json::to_string(&u).unwrap();
let de_u = serde_json::from_str(&union_json).unwrap();
assert_eq!(u, de_u);
} | random_line_split | |
tests.rs | use super::*;
#[test]
fn test_struct_info_roundtrip() {
let s = ItemEnum::Struct(Struct {
struct_type: StructType::Plain,
generics: Generics { params: vec![], where_predicates: vec![] },
fields_stripped: false,
fields: vec![],
impls: vec![],
});
let struct_json = se... | {
let u = ItemEnum::Union(Union {
generics: Generics { params: vec![], where_predicates: vec![] },
fields_stripped: false,
fields: vec![],
impls: vec![],
});
let union_json = serde_json::to_string(&u).unwrap();
let de_u = serde_json::from_str(&union_json).unwrap();
... | identifier_body | |
tests.rs | use super::*;
#[test]
fn test_struct_info_roundtrip() {
let s = ItemEnum::Struct(Struct {
struct_type: StructType::Plain,
generics: Generics { params: vec![], where_predicates: vec![] },
fields_stripped: false,
fields: vec![],
impls: vec![],
});
let struct_json = se... | () {
let u = ItemEnum::Union(Union {
generics: Generics { params: vec![], where_predicates: vec![] },
fields_stripped: false,
fields: vec![],
impls: vec![],
});
let union_json = serde_json::to_string(&u).unwrap();
let de_u = serde_json::from_str(&union_json).unwrap();
... | test_union_info_roundtrip | identifier_name |
rec-align-u64.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | #[cfg(target_os = "android")]
mod m {
#[cfg(target_arch = "arm")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
pub fn main() {
unsafe {
let x = Outer {c8: 22u8, t: Inner {c64: 44u64}};
let y = format!("{:?}", x);
println!("align i... | pub fn size() -> uint { 16u }
}
}
| random_line_split |
rec-align-u64.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () -> uint { 16u }
}
#[cfg(target_arch = "x86_64")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "android")]
mod m {
#[cfg(target_arch = "arm")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16... | size | identifier_name |
lib.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/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... | #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko;
#[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings;
pub mod hash;
pub mod invalidation;
#[allow(missing_docs)] // TODO.
pub mod logical_geometry;
pub mod matching;
pub mod media_queries;
pub mod parallel;
pub mod parser;
pub mod rule_cac... | pub mod font_face;
pub mod font_metrics; | random_line_split |
lib.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/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... |
}
| {
match self {
selectors::attr::CaseSensitivity::CaseSensitive => a == b,
selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
} | identifier_body |
lib.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/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... | (self, a: &WeakAtom, b: &WeakAtom) -> bool {
match self {
selectors::attr::CaseSensitivity::CaseSensitive => a == b,
selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
}
}
| eq_atom | identifier_name |
day_14.rs | use tdd_kata::string_calc_kata::iter_1::day_14::evaluate;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_eval_simple_num() {
assert_eq!(evaluate("1"), Ok(1.0));
}
#[test]
fn test_eval_three_digit_num() {
assert_eq!(evaluate("256"), Ok(256.0));
}
#[test]
f... | () {
assert_eq!(evaluate("125.256"), Ok(125.256));
}
#[test]
fn test_eval_add() {
assert_eq!(evaluate("1+2"), Ok(3.0));
}
#[test]
fn test_eval_sub() {
assert_eq!(evaluate("3-1"), Ok(2.0));
}
#[test]
fn test_eval_few_operations() {
assert_eq!(evaluat... | test_eval_real_num | identifier_name |
day_14.rs | use tdd_kata::string_calc_kata::iter_1::day_14::evaluate;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_eval_simple_num() {
assert_eq!(evaluate("1"), Ok(1.0));
}
#[test]
fn test_eval_three_digit_num() {
assert_eq!(evaluate("256"), Ok(256.0));
}
#[test]
f... |
#[test]
fn test_eval_div() {
assert_eq!(evaluate("10÷2"), Ok(5.0));
}
#[test]
fn test_eval_operations_with_diff_priority() {
assert_eq!(evaluate("20+2×5-100÷4"), Ok(5.0));
}
#[test]
fn test_eval_operations_with_parentheses() {
assert_eq!(evaluate("2+(2-3+5×2)-8... | {
assert_eq!(evaluate("2×5"), Ok(10.0));
}
| identifier_body |
day_14.rs | use tdd_kata::string_calc_kata::iter_1::day_14::evaluate;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_eval_simple_num() {
assert_eq!(evaluate("1"), Ok(1.0));
}
#[test]
fn test_eval_three_digit_num() {
assert_eq!(evaluate("256"), Ok(256.0));
}
#[test]
f... |
#[test]
fn test_eval_operations_with_parentheses() {
assert_eq!(evaluate("2+(2-3+5×2)-8"), Ok(3.0));
}
#[test]
fn test_eval_operations_with_two_levels_of_parentheses() {
assert_eq!(evaluate("2+(2-3+5×2)-((1+1)×4)"), Ok(3.0));
}
} | random_line_split | |
extern-crate-only-used-in-link.rs | // This test is just a little cursed. | // aux-crate:priv:empty=empty.rs
// aux-build:empty2.rs
// aux-crate:priv:empty2=empty2.rs
// build-aux-docs
// compile-flags:-Z unstable-options --edition 2018
// @has extern_crate_only_used_in_link/index.html
// @has - '//a[@href="../issue_66159_1/struct.Something.html"]' 'issue_66159_1::Something'
//! [issue_66159_... | // aux-build:issue-66159-1.rs
// aux-crate:priv:issue_66159_1=issue-66159-1.rs
// aux-build:empty.rs | random_line_split |
ecdsa_common.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
EllipticCurveType::NistP521 => {
if hash_alg!= HashType::Sha512 {
return Err("invalid hash type, expect SHA-512".into());
}
}
_ => return Err(format!("unsupported curve: {:?}", curve).into()),
}
Ok(encoding)
}
| {
if hash_alg != HashType::Sha384 && hash_alg != HashType::Sha512 {
return Err("invalid hash type, expect SHA-384 or SHA-512".into());
}
} | conditional_block |
ecdsa_common.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | {
Der,
IeeeP1363,
}
/// Validate ECDSA parameters.
/// The hash's strength must not be weaker than the curve's strength.
/// DER and IEEE_P1363 encodings are supported.
pub fn validate_ecdsa_params(
hash_alg: tink_proto::HashType,
curve: tink_proto::EllipticCurveType,
encoding: tink_proto::EcdsaSi... | SignatureEncoding | identifier_name |
ecdsa_common.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | }
}
_ => return Err(format!("unsupported curve: {:?}", curve).into()),
}
Ok(encoding)
}
| {
let encoding = match encoding {
EcdsaSignatureEncoding::IeeeP1363 => SignatureEncoding::IeeeP1363,
EcdsaSignatureEncoding::Der => SignatureEncoding::Der,
_ => return Err("ecdsa: unsupported encoding".into()),
};
match curve {
EllipticCurveType::NistP256 => {
if ... | identifier_body |
ecdsa_common.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
use tink_core::TinkError;
use tink_proto::{EcdsaSignatureEncoding, EllipticCurveType, HashType};
/// Supported signature encodings. This is a precise subset of the protobuf enum,
/// allowing exact `match`es.
#[derive(Clone, Debug)]
pub enum SignatureEncoding {
Der,
IeeeP1363,
}
/// Validate ECDSA parameter... | random_line_split | |
common.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... |
}
#[derive(Clone)]
pub struct Config {
// The library paths required for running the compiler
pub compile_lib_path: String,
// The library paths required for running compiled programs
pub run_lib_path: String,
// The rustc executable
pub rustc_path: PathBuf,
// The rustdoc executable
... | {
fmt::Display::fmt(match *self {
CompileFail => "compile-fail",
ParseFail => "parse-fail",
RunFail => "run-fail",
RunPass => "run-pass",
RunPassValgrind => "run-pass-valgrind",
Pretty => "pretty",
DebugInfoGdb => "debuginfo-gdb... | identifier_body |
common.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... | pub python: String,
// The llvm binaries path
pub llvm_bin_path: Option<PathBuf>,
// The valgrind path
pub valgrind_path: Option<String>,
// Whether to fail if we can't run run-pass-valgrind tests under valgrind
// (or, alternatively, to silently run them like regular run-pass tests).
... | // The python executable | random_line_split |
common.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... | {
// The library paths required for running the compiler
pub compile_lib_path: String,
// The library paths required for running compiled programs
pub run_lib_path: String,
// The rustc executable
pub rustc_path: PathBuf,
// The rustdoc executable
pub rustdoc_path: PathBuf,
// T... | Config | identifier_name |
main.rs | //
// main.rs
//
// Copyright 2015-2019 Laurent Wandrebeck <l.wandrebeck@quelquesmots.fr>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your op... | 2 => rush.prompt = Prompt::get(&mut rush, "PS2"),
3 => rush.prompt = Prompt::get(&mut rush, "PS3"),
4 => rush.prompt = Prompt::get(&mut rush, "PS4"),
_ => panic!("wrong line_case value."),
}
}
} | match rush.line_case {
1 => rush.prompt = Prompt::get(&mut rush, "PS1"), | random_line_split |
main.rs | //
// main.rs
//
// Copyright 2015-2019 Laurent Wandrebeck <l.wandrebeck@quelquesmots.fr>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your op... | match line {
Ok(input) => {
// TODO fix history management
// rl.add_history_entry(&input);
parse(&mut rush, &input);
rush.cmd_nb += 1;
}
Err(_) => break,
}
// Use correct variable to define next ... | {
let mut rush = RuSh::default();
//rush.prompt = Prompt::get(&mut rush.shell_vars, "PS1");
rush.prompt = Prompt::get(&mut rush, "PS1");
//let mut stdin = io::stdin();
let mut rl = rustyline::Editor::<()>::new();
// take care of SECOND env var
//~ let child = thread::spawn(move || {
//~... | identifier_body |
main.rs | //
// main.rs
//
// Copyright 2015-2019 Laurent Wandrebeck <l.wandrebeck@quelquesmots.fr>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your op... | () {
let mut rush = RuSh::default();
//rush.prompt = Prompt::get(&mut rush.shell_vars, "PS1");
rush.prompt = Prompt::get(&mut rush, "PS1");
//let mut stdin = io::stdin();
let mut rl = rustyline::Editor::<()>::new();
// take care of SECOND env var
//~ let child = thread::spawn(move || {
... | main | identifier_name |
fulfill.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | typer: &Typer<'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
try!(self.select_where_possible(infcx, param_env, typer));
// Anything left is ambiguous.
let errors: Vec<FulfillmentError> =
self.trait_obligat... | infcx: &InferCtxt<'a,'tcx>,
param_env: &ty::ParameterEnvironment<'tcx>, | random_line_split |
fulfill.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn register_obligation(&mut self,
tcx: &ty::ctxt<'tcx>,
obligation: Obligation<'tcx>)
{
debug!("register_obligation({})", obligation.repr(tcx));
assert!(!obligation.trait_ref.has_escaping_regions());
self.trait_obligatio... | {
FulfillmentContext {
trait_obligations: Vec::new(),
attempted_mark: 0,
}
} | identifier_body |
fulfill.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
param_env: &ty::ParameterEnvironment<'tcx>,
typer: &Typer<'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
let mut... | select_where_possible | identifier_name |
callback.rs | // Copyright (c) 2016 Yusuke Sasaki
//
// This software is released under the MIT License.
// See http://opensource.org/licenses/mit-license.php or <LICENSE>.
extern crate gurobi;
use gurobi::*;
use std::io::{BufWriter, Write};
use std::fs::OpenOptions;
fn main() | // Ignore polling callback
}
// Currently performing presolve
PreSolve { coldel, rowdel,.. } => {
println!("@PreSolve");
if coldel > 0 || rowdel > 0 {
println!("**** {} columns and {} rows are removed. ****",
coldel,
... | {
let mut env = Env::new("callback.log").unwrap();
env.set(param::OutputFlag, 0).unwrap();
env.set(param::Heuristics, 0.0).unwrap();
let mut model = Model::read_from(&std::env::args().nth(1).unwrap(), &env).unwrap();
let callback = {
let mut lastiter = -INFINITY;
let mut lastnode = -INFINITY;
le... | identifier_body |
callback.rs | // Copyright (c) 2016 Yusuke Sasaki
//
// This software is released under the MIT License.
// See http://opensource.org/licenses/mit-license.php or <LICENSE>.
extern crate gurobi;
use gurobi::*;
use std::io::{BufWriter, Write};
use std::fs::OpenOptions;
fn main() {
let mut env = Env::new("callback.log").unwrap();
... | ctx.terminate();
}
}
// Found a new MIP incumbent
MIPSol { solcnt, obj, nodcnt,.. } => {
println!("@MIPSol: ");
let x = try!(ctx.get_solution(vars.as_slice()));
println!("**** New solution at node {}, obj {}, sol {}, x[0] = {} ****",
... | {
if nodcnt - lastnode >= 100.0 {
lastnode = nodcnt;
println!("@MIP: nodcnt={}, actnodes={}, itrcnt={}, objbst={}, objbnd={}, solcnt={}, cutcnt={}.",
nodcnt,
actnodes,
itrcnt,
objbst,
... | conditional_block |
callback.rs | // Copyright (c) 2016 Yusuke Sasaki
//
// This software is released under the MIT License.
// See http://opensource.org/licenses/mit-license.php or <LICENSE>.
extern crate gurobi;
use gurobi::*;
use std::io::{BufWriter, Write};
use std::fs::OpenOptions;
fn main() {
let mut env = Env::new("callback.log").unwrap();
... | writer.write_all(message.as_bytes()).unwrap();
writer.write_all(&[b'\n']).unwrap();
}
}
Ok(())
}
};
model.optimize_with_callback(callback).unwrap();
println!("\nOptimization complete");
if model.get(attr::SolCount).unwrap() == 0 {
println!("No solution found. op... | }
// Printing a log message
Message(message) => { | random_line_split |
callback.rs | // Copyright (c) 2016 Yusuke Sasaki
//
// This software is released under the MIT License.
// See http://opensource.org/licenses/mit-license.php or <LICENSE>.
extern crate gurobi;
use gurobi::*;
use std::io::{BufWriter, Write};
use std::fs::OpenOptions;
fn | () {
let mut env = Env::new("callback.log").unwrap();
env.set(param::OutputFlag, 0).unwrap();
env.set(param::Heuristics, 0.0).unwrap();
let mut model = Model::read_from(&std::env::args().nth(1).unwrap(), &env).unwrap();
let callback = {
let mut lastiter = -INFINITY;
let mut lastnode = -INFINITY;
... | main | identifier_name |
performanceentry.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::codegen::Bindings::PerformanceEntryBinding;
use dom::bindings::codegen::Bindings::PerformanceEn... |
// https://w3c.github.io/performance-timeline/#dom-performanceentry-duration
fn Duration(&self) -> Finite<f64> {
Finite::wrap(self.duration)
}
} | random_line_split | |
performanceentry.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::codegen::Bindings::PerformanceEntryBinding;
use dom::bindings::codegen::Bindings::PerformanceEn... | (&self) -> Finite<f64> {
Finite::wrap(self.duration)
}
}
| Duration | identifier_name |
performanceentry.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::codegen::Bindings::PerformanceEntryBinding;
use dom::bindings::codegen::Bindings::PerformanceEn... |
pub fn entry_type(&self) -> &DOMString {
&self.entry_type
}
pub fn name(&self) -> &DOMString {
&self.name
}
pub fn start_time(&self) -> f64 {
self.start_time
}
}
impl PerformanceEntryMethods for PerformanceEntry {
// https://w3c.github.io/performance-timeline/#do... | {
let entry = PerformanceEntry::new_inherited(name, entry_type, start_time, duration);
reflect_dom_object(Box::new(entry), global, PerformanceEntryBinding::Wrap)
} | identifier_body |
is_negative_zero.rs | use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::float::NiceFloat;
use malachite_base_test_util::generators::primitive_float_gen;
fn is_negative_zero_helper<T: PrimitiveFloat>() {
let test = |n: T, out| {
assert_eq!(n.is_negative_zero(), out);
};
test(T::ZERO, false)... | test(T::from(1.234), false);
test(T::from(-1.234), false);
}
#[test]
fn test_is_negative_zero() {
apply_fn_to_primitive_floats!(is_negative_zero_helper);
}
fn is_negative_zero_properties_helper<T: PrimitiveFloat>() {
primitive_float_gen::<T>().test_properties(|x| {
assert_eq!(
x.is... | test(T::POSITIVE_INFINITY, false);
test(T::NEGATIVE_INFINITY, false);
test(T::ONE, false);
test(T::NEGATIVE_ONE, false); | random_line_split |
is_negative_zero.rs | use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::float::NiceFloat;
use malachite_base_test_util::generators::primitive_float_gen;
fn is_negative_zero_helper<T: PrimitiveFloat>() {
let test = |n: T, out| {
assert_eq!(n.is_negative_zero(), out);
};
test(T::ZERO, false)... |
#[test]
fn is_negative_zero_properties() {
apply_fn_to_primitive_floats!(is_negative_zero_properties_helper);
}
| {
primitive_float_gen::<T>().test_properties(|x| {
assert_eq!(
x.is_negative_zero(),
NiceFloat(x) != NiceFloat(x.abs_negative_zero())
);
});
} | identifier_body |
is_negative_zero.rs | use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::float::NiceFloat;
use malachite_base_test_util::generators::primitive_float_gen;
fn is_negative_zero_helper<T: PrimitiveFloat>() {
let test = |n: T, out| {
assert_eq!(n.is_negative_zero(), out);
};
test(T::ZERO, false)... | () {
apply_fn_to_primitive_floats!(is_negative_zero_helper);
}
fn is_negative_zero_properties_helper<T: PrimitiveFloat>() {
primitive_float_gen::<T>().test_properties(|x| {
assert_eq!(
x.is_negative_zero(),
NiceFloat(x)!= NiceFloat(x.abs_negative_zero())
);
});
}
#[... | test_is_negative_zero | identifier_name |
borrowck-borrowed-uniq-rvalue.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut buggy_map: HashMap<usize, &usize> = HashMap::new();
buggy_map.insert(42, &*box 1); //~ ERROR borrowed value does not live long enough
// but it is ok if we use a temporary
let tmp = box 2;
buggy_map.insert(43, &*tmp);
}
| main | identifier_name |
borrowck-borrowed-uniq-rvalue.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let mut buggy_map: HashMap<usize, &usize> = HashMap::new();
buggy_map.insert(42, &*box 1); //~ ERROR borrowed value does not live long enough
// but it is ok if we use a temporary
let tmp = box 2;
buggy_map.insert(43, &*tmp);
} | identifier_body | |
borrowck-borrowed-uniq-rvalue.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let mut buggy_map: HashMap<usize, &usize> = HashMap::new();
buggy_map.insert(42, &*box 1); //~ ERROR borrowed value does not live long enough
// but it is ok if we use a temporary
let tmp = box 2;
buggy_map.insert(43, &*tmp);
} | use std::collections::HashMap; | random_line_split |
playlist_track.rs | use std::collections::BTreeMap;
use uuid::Uuid;
use chrono::{NaiveDateTime, Utc};
use postgres;
use error::Error;
use super::{conn, Model};
use model::track::{Track, PROPS as TRACK_PROPS};
use model::playlist::Playlist;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PlaylistTrack {
pub playlist_id: U... |
fn row_to_item(row: postgres::rows::Row) -> Self {
let offset = TRACK_PROPS.len();
PlaylistTrack {
playlist_id: row.get(offset),
track_id: row.get(offset + 1),
created_at: row.get(offset + 2),
updated_at: row.get(offset + 3),
track: ... | {
PROPS
.iter()
.map(|&p| format!("{}{}", prefix, p))
.collect::<Vec<String>>().join(",")
} | identifier_body |
playlist_track.rs | use std::collections::BTreeMap;
use uuid::Uuid;
use chrono::{NaiveDateTime, Utc};
use postgres;
use error::Error;
use super::{conn, Model};
use model::track::{Track, PROPS as TRACK_PROPS};
use model::playlist::Playlist;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct | {
pub playlist_id: Uuid,
pub track_id: Uuid,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub track: Track,
}
static PROPS: [&'static str; 4] = ["playlist_id",
"track_id",
"created_at",
... | PlaylistTrack | identifier_name |
playlist_track.rs | use std::collections::BTreeMap;
use uuid::Uuid;
use chrono::{NaiveDateTime, Utc};
use postgres;
use error::Error;
use super::{conn, Model};
use model::track::{Track, PROPS as TRACK_PROPS};
use model::playlist::Playlist;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PlaylistTrack {
pub playlist_id: U... |
};
Ok(items)
}
pub fn upsert(playlist: &Playlist, track: &Track) -> Result<PlaylistTrack, Error> {
let conn = conn()?;
let stmt = conn.prepare("INSERT INTO playlist_tracks
(track_id, playlist_id, created_at, updated_at)
VALUES ($1, $2,... | {
let pt = PlaylistTrack::row_to_item(row);
playlist_tracks.push(pt);
} | conditional_block |
playlist_track.rs | use std::collections::BTreeMap;
use uuid::Uuid;
use chrono::{NaiveDateTime, Utc};
use postgres;
use error::Error;
use super::{conn, Model};
use model::track::{Track, PROPS as TRACK_PROPS};
use model::playlist::Playlist;
| #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PlaylistTrack {
pub playlist_id: Uuid,
pub track_id: Uuid,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub track: Track,
}
static PROPS: [&'static str; 4] = ["playlist_id",
... | random_line_split | |
crateresolve8.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
assert_eq!(crateresolve8::f(), 20);
} | identifier_body | |
crateresolve8.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
assert_eq!(crateresolve8::f(), 20);
}
| main | identifier_name |
crateresolve8.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast
// aux-build:crateresolve8-1.rs
#[pkgid="crateresolve8#0.1"];
extern mod crateresolve8(vers = "0.1", package_id="crateresolve8#0.1");
//extern mod crateresolve8(vers = "0.1");
pub fn main() {
asser... | random_line_split | |
mod_power_of_2_square.rs | use malachite_base::num::arithmetic::traits::{Square, WrappingSquare};
use malachite_base::num::conversion::traits::SplitInHalf;
use malachite_nz::natural::arithmetic::add_mul::limbs_slice_add_mul_limb_same_length_in_place_left;
use malachite_nz::natural::arithmetic::mod_power_of_2_square::limbs_square_diagonal_shl_add... | limbs_slice_add_mul_limb_same_length_in_place_left(
&mut scratch[two_i..],
&xs[i + 1..n - i],
xs[i],
);
}
limbs_square_diagonal_shl_add(out, &mut scratch, xs);
}
}
}
| {
let n = xs.len();
let out = &mut out[..n];
assert_ne!(n, 0);
let xs_0 = xs[0];
match n {
1 => out[0] = xs_0.wrapping_square(),
2 => {
let (p_hi, p_lo) = DoubleLimb::from(xs_0).square().split_in_half();
out[0] = p_lo;
out[1] = (xs_0.wrapping_mul(x... | identifier_body |
mod_power_of_2_square.rs | use malachite_base::num::arithmetic::traits::{Square, WrappingSquare};
use malachite_base::num::conversion::traits::SplitInHalf;
use malachite_nz::natural::arithmetic::add_mul::limbs_slice_add_mul_limb_same_length_in_place_left;
use malachite_nz::natural::arithmetic::mod_power_of_2_square::limbs_square_diagonal_shl_add... | (out: &mut [Limb], xs: &[Limb]) {
let n = xs.len();
let out = &mut out[..n];
assert_ne!(n, 0);
let xs_0 = xs[0];
match n {
1 => out[0] = xs_0.wrapping_square(),
2 => {
let (p_hi, p_lo) = DoubleLimb::from(xs_0).square().split_in_half();
out[0] = p_lo;
... | limbs_square_low_basecase_unrestricted | identifier_name |
mod_power_of_2_square.rs | use malachite_base::num::arithmetic::traits::{Square, WrappingSquare};
use malachite_base::num::conversion::traits::SplitInHalf;
use malachite_nz::natural::arithmetic::add_mul::limbs_slice_add_mul_limb_same_length_in_place_left;
use malachite_nz::natural::arithmetic::mod_power_of_2_square::limbs_square_diagonal_shl_add... | use malachite_nz::platform::{DoubleLimb, Limb};
pub fn limbs_square_low_basecase_unrestricted(out: &mut [Limb], xs: &[Limb]) {
let n = xs.len();
let out = &mut out[..n];
assert_ne!(n, 0);
let xs_0 = xs[0];
match n {
1 => out[0] = xs_0.wrapping_square(),
2 => {
let (p_hi,... | use malachite_nz::natural::arithmetic::mul::limb::limbs_mul_limb_to_out; | random_line_split |
current_page_table.rs | //! Handles interactions with the current page table.
use super::inactive_page_table::InactivePageTable;
use super::page_table::{Level1, Level4, PageTable};
use super::page_table_entry::*;
use super::page_table_manager::PageTableManager;
use super::{Page, PageFrame};
use core::cell::UnsafeCell;
use core::ops::{Deref, ... | ///
/// Note that this is only valid if the level 4 table is mapped recursively on
/// the last entry.
const L4_TABLE: *mut PageTable<Level4> = 0xfffffffffffff000 as *mut PageTable<Level4>;
/// The base address for all temporary addresses.
const TEMPORARY_ADDRESS_BASE: VirtualAddress = VirtualAddress::from_const(0xfff... | random_line_split | |
current_page_table.rs | //! Handles interactions with the current page table.
use super::inactive_page_table::InactivePageTable;
use super::page_table::{Level1, Level4, PageTable};
use super::page_table_entry::*;
use super::page_table_manager::PageTableManager;
use super::{Page, PageFrame};
use core::cell::UnsafeCell;
use core::ops::{Deref, ... |
/// Switches to the new page table returning the current one.
///
/// The old page table will not be mapped into the new one. This should be
/// done manually.
pub unsafe fn switch(&mut self, new_table: InactivePageTable) -> InactivePageTable {
let old_frame =
PageFrame::from_a... | {
self.with_temporary_page(&PageFrame::from_address(physical_address), |page| {
let virtual_address =
page.get_address().as_usize() | (physical_address.offset_in_page());
unsafe { ptr::read(virtual_address as *mut T) }
})
} | identifier_body |
current_page_table.rs | //! Handles interactions with the current page table.
use super::inactive_page_table::InactivePageTable;
use super::page_table::{Level1, Level4, PageTable};
use super::page_table_entry::*;
use super::page_table_manager::PageTableManager;
use super::{Page, PageFrame};
use core::cell::UnsafeCell;
use core::ops::{Deref, ... |
// Perform the action.
let result: T = action(&mut Page::from_address(virtual_address));
// Unlock this entry.
entry.unlock(&preemption_state);
result
}
/// Writes the given value to the given physical address.
pub fn write_at_physical<T: Sized + Copy>(
&... | {
tlb::flush(::x86_64::VirtualAddress(virtual_address.as_usize()));
entry.set_address(frame.get_address());
entry.set_flags(PRESENT | WRITABLE | DISABLE_CACHE | NO_EXECUTE);
} | conditional_block |
current_page_table.rs | //! Handles interactions with the current page table.
use super::inactive_page_table::InactivePageTable;
use super::page_table::{Level1, Level4, PageTable};
use super::page_table_entry::*;
use super::page_table_manager::PageTableManager;
use super::{Page, PageFrame};
use core::cell::UnsafeCell;
use core::ops::{Deref, ... | (&mut self, new_table: InactivePageTable) -> InactivePageTable {
let old_frame =
PageFrame::from_address(PhysicalAddress::from_usize(control_regs::cr3().0 as usize));
let old_table = InactivePageTable::from_frame(old_frame.copy(), &new_table);
let new_frame = new_table.get_frame();
... | switch | identifier_name |
lib.rs | // Copyright 2018 Stichting Organism
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... |
//given a series of bytes match emojis
pub fn from_bytes(&self, tosum: &[u8]) -> Option<String> {
//check that it is 32bytes
if tosum.len() < 32 { return None }
let mut result = String::new();
for byte in tosum {
result.push_str(&(self.emojiwords[*byte as ... | {
let json_file_path = Path::new(file_path);
let json_file = File::open(json_file_path).expect("file not found");
let deserialized: Emojisum =
serde_json::from_reader(json_file).expect("error while reading json");
return deserialized;
} | identifier_body |
lib.rs | // Copyright 2018 Stichting Organism
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | (file_path: &str) -> Emojisum {
let json_file_path = Path::new(file_path);
let json_file = File::open(json_file_path).expect("file not found");
let deserialized: Emojisum =
serde_json::from_reader(json_file).expect("error while reading json");
return deserialized;
}
//g... | init | identifier_name |
lib.rs | // Copyright 2018 Stichting Organism
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// | // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.... | random_line_split | |
lib.rs | // Copyright 2018 Stichting Organism
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... |
let mut result = String::new();
for byte in tosum {
result.push_str(&(self.emojiwords[*byte as usize])[0])
}
return Some(result);
}
//given a vector of bytes, we hash and return checksum
pub fn hash_to_emojisum(&self, data: Vec<u8>) -> Option<String>... | { return None } | conditional_block |
response.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/. */
//! The [Response](https://fetch.spec.whatwg.org/#responses) object
//! resulting from a [fetch operation](https:/... |
}
/// Convert to a filtered response, of type `filter_type`.
/// Do not use with type Error or Default
pub fn to_filtered(self, filter_type: ResponseType) -> Response {
match filter_type {
ResponseType::Default | ResponseType::Error(..) => panic!(),
_ => (),
}
... | {
self
} | conditional_block |
response.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/. */
//! The [Response](https://fetch.spec.whatwg.org/#responses) object
//! resulting from a [fetch operation](https:/... | (e: NetworkError) -> Response {
Response {
response_type: ResponseType::Error(e),
termination_reason: None,
url: None,
url_list: RefCell::new(vec![]),
status: None,
raw_status: None,
headers: Headers::new(),
body: Ar... | network_error | identifier_name |
response.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/. */
//! The [Response](https://fetch.spec.whatwg.org/#responses) object
//! resulting from a [fetch operation](https:/... |
ResponseType::Basic => {
let headers = old_headers.iter().filter(|header| {
match &*header.name().to_ascii_lowercase() {
"set-cookie" | "set-cookie2" => false,
_ => true
}
}).collect();
... |
match response.response_type {
ResponseType::Default | ResponseType::Error(..) => unreachable!(), | random_line_split |
response.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/. */
//! The [Response](https://fetch.spec.whatwg.org/#responses) object
//! resulting from a [fetch operation](https:/... | ;
if let Some(error) = self.get_network_error() {
return Err(error.clone());
}
let metadata = self.url.as_ref().map(|url| init_metadata(self, url));
if let Some(ref response) = self.internal_response {
match response.url {
Some(ref url) => {
... | {
let mut metadata = Metadata::default(url.clone());
metadata.set_content_type(match response.headers.get() {
Some(&ContentType(ref mime)) => Some(mime),
None => None
});
metadata.headers = Some(Serde(response.headers.clone()));
... | identifier_body |
sessions.rs | use iron::headers::ContentType;
use iron::prelude::*;
use iron::status;
use serde_json;
use authentication::{authenticate_user, delete_session};
use super::common::*;
pub fn | (request: &mut Request) -> IronResult<Response> {
use models::NewSession;
let email = get_param(request, "email")?;
let password = get_param(request, "password")?;
let (user, session) = authenticate_user(&email, &password)?;
let new_session = NewSession {
token: session.token,
use... | login | identifier_name |
sessions.rs | use iron::headers::ContentType;
use iron::prelude::*;
use iron::status;
use serde_json;
use authentication::{authenticate_user, delete_session};
use super::common::*;
pub fn login(request: &mut Request) -> IronResult<Response> |
pub fn logout(request: &mut Request) -> IronResult<Response> {
use models::Session;
let current_session = request.extensions.get::<Session>().unwrap();
delete_session(current_session.token.as_str())?;
Ok(Response::with((ContentType::json().0, status::NoContent)))
}
| {
use models::NewSession;
let email = get_param(request, "email")?;
let password = get_param(request, "password")?;
let (user, session) = authenticate_user(&email, &password)?;
let new_session = NewSession {
token: session.token,
user_id: user.id,
expired_at: session.expir... | identifier_body |
sessions.rs | use iron::headers::ContentType;
use iron::prelude::*;
use iron::status;
use serde_json;
use authentication::{authenticate_user, delete_session};
use super::common::*;
pub fn login(request: &mut Request) -> IronResult<Response> {
use models::NewSession;
let email = get_param(request, "email")?;
let passwo... | user_id: user.id,
expired_at: session.expired_at,
};
let payload = serde_json::to_string(&new_session).unwrap();
Ok(Response::with((ContentType::json().0, status::Created, payload)))
}
pub fn logout(request: &mut Request) -> IronResult<Response> {
use models::Session;
let current... | token: session.token, | random_line_split |
service.rs | use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use crate::futures;
use crate::jsonrpc::{middleware, MetaIoHandler, Metadata, Middleware};
pub struct Service<M: Metadata = (), S: Middleware<M> = middleware::Noop> {
handler: Arc<MetaIoHandler<M... | (&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
// Produce a future for computing a response from a request.
fn call(&mut self, req: String) -> Self::Future {
use futures::FutureExt;
trace!(target: "tcp", "Accepted request from peer {}: {}", &self.peer_addr, req);
B... | poll_ready | identifier_name |
service.rs | use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use crate::futures;
use crate::jsonrpc::{middleware, MetaIoHandler, Metadata, Middleware};
pub struct Service<M: Metadata = (), S: Middleware<M> = middleware::Noop> {
handler: Arc<MetaIoHandler<M... | use futures::FutureExt;
trace!(target: "tcp", "Accepted request from peer {}: {}", &self.peer_addr, req);
Box::pin(self.handler.handle_request(&req, self.meta.clone()).map(Ok))
}
} | Poll::Ready(Ok(()))
}
// Produce a future for computing a response from a request.
fn call(&mut self, req: String) -> Self::Future { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.