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 |
|---|---|---|---|---|
momentum_indicators.rs | extern crate tars;
use tars::momentum_indicators::rsi::rsi;
use tars::helpers::round_array;
// Some randomly generated data to test against TA-Lib (see generate_data.py & correct_values.py)
const OPEN: &[f64] = &[1984.03, 1959.83, 2041.42, 2019.04, 1969.53, 2082.75, 2209.52, 2200.9,
2364.04, 25... | {
let mut result = rsi(CLOSE, 6).unwrap();
let expected = &[79.9771, 86.5336, 90.5949, 73.0035, 75.8056, 80.7258, 56.706, 44.4766,
57.3488, 63.879, 72.8847, 77.5072, 64.1009, 70.3536];
round_array(result.as_mut(), 4);
assert_eq!(result, expected);
} | identifier_body | |
momentum_indicators.rs | extern crate tars;
use tars::momentum_indicators::rsi::rsi;
use tars::helpers::round_array;
// Some randomly generated data to test against TA-Lib (see generate_data.py & correct_values.py)
const OPEN: &[f64] = &[1984.03, 1959.83, 2041.42, 2019.04, 1969.53, 2082.75, 2209.52, 2200.9,
2364.04, 25... | () {
let mut result = rsi(CLOSE, 6).unwrap();
let expected = &[79.9771, 86.5336, 90.5949, 73.0035, 75.8056, 80.7258, 56.706, 44.4766,
57.3488, 63.879, 72.8847, 77.5072, 64.1009, 70.3536];
round_array(result.as_mut(), 4);
assert_eq!(result, expected);
}
| rsi_works | identifier_name |
font_metrics.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/. */
//! Access to font metrics from the style system.
#![deny(missing_docs)]
use Atom;
use app_units::Au;
use contex... | } | pub fn get_metrics_provider_for_product() -> ServoMetricsProvider {
ServoMetricsProvider | random_line_split |
font_metrics.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/. */
//! Access to font metrics from the style system.
#![deny(missing_docs)]
use Atom;
use app_units::Au;
use contex... | (&self, _font: &Font, _font_size: Au, _wm: WritingMode,
_in_media_query: bool, _device: &Device) -> FontMetricsQueryResult {
FontMetricsQueryResult::NotAvailable
}
/// Get default size of a given language and generic family
fn get_size(&self, font_name: &Atom, font_family: u8) -> Au;
... | query | identifier_name |
mod.rs | pub mod data_cache;
use std::collections::HashMap;
use std::option::Option;
use self::data_cache::base_data::City;
struct DfaState {
name:String,
path:HashMap<char, DfaState>,
}
impl DfaState {
fn new(n:String) -> DfaState {
DfaState{name:n, path:HashMap::default()}
}
fn add_path(&mut self, c:... | } else {
self.scan_recur(chars, from_idx + 1, from_idx + 1, currect_accepted_idx, &self.start_state, current_accepted, res);
},
Some(cs) => if current_idx + 1 == len {
if cs.is_accepted() {
if!res.contains(&cs.name) {
res.push(cs.name.to_string());
}
self.scan_recu... | }
self.scan_recur(chars, currect_accepted_idx + 1, currect_accepted_idx+1, 0, &self.start_state, &self.start_state, res);
| random_line_split |
mod.rs |
pub mod data_cache;
use std::collections::HashMap;
use std::option::Option;
use self::data_cache::base_data::City;
struct DfaState {
name:String,
path:HashMap<char, DfaState>,
}
impl DfaState {
fn new(n:String) -> DfaState {
DfaState{name:n, path:HashMap::default()}
}
fn add_path(&mut self, ... | if (current_accepted as *const DfaState)!= (&self.start_state as * const DfaState) {
if!res.contains(¤t_accepted.name) {
res.push(current_accepted.name.to_string());
}
self.scan_recur(chars, currect_accepted_idx + 1, currect_accepted_idx+1, 0, &self.start_state, &self.start_state, re... | {
if !res.contains(&cs.name) {
res.push(cs.name.to_string());
}
self.scan_recur(chars, from_idx, current_idx+1, currect_accepted_idx, &self.start_state, current_accepted, res);
} | conditional_block |
mod.rs |
pub mod data_cache;
use std::collections::HashMap;
use std::option::Option;
use self::data_cache::base_data::City;
struct DfaState {
name:String,
path:HashMap<char, DfaState>,
}
impl DfaState {
fn new(n:String) -> DfaState {
DfaState{name:n, path:HashMap::default()}
}
fn add_path(&mut self, ... | () -> DFA {
let (citys, name_map) = data_cache::assemble_data();
let mut dfa = DFA{start_state:DfaState::new("".to_string()), citys:citys, name_map: name_map};
for name in dfa.name_map.keys() {
dfa.start_state.add_path_by_name(name);
}
dfa
}
pub fn print_states(&self) {
println!("+++++++++++++... | new | identifier_name |
mod.rs |
pub mod data_cache;
use std::collections::HashMap;
use std::option::Option;
use self::data_cache::base_data::City;
struct DfaState {
name:String,
path:HashMap<char, DfaState>,
}
impl DfaState {
fn new(n:String) -> DfaState |
fn add_path(&mut self, c:char, name:&str) -> &mut DfaState {
let mut res = self.path.entry(c).or_insert(DfaState::new(name.to_string()));
if res.name == "" && name!= "" {
res.name = name.to_string();
}
res
}
fn add_path_by_name(&mut self, name:&str) {
let chars:Vec<char> = name.chars().collec... | {
DfaState{name:n, path:HashMap::default()}
} | identifier_body |
integration.rs | #![feature(duration)]
#![deny(unused_mut)]
extern crate zookeeper;
extern crate env_logger;
use zookeeper::{Acl, CreateMode, Watcher, WatchedEvent, ZooKeeper};
use zookeeper::perms;
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, Command, Stdio};
use std::time::Duration;
struct LoggingWatcher;
im... |
let exists = client.exists("/test", true);
assert!(exists.is_ok());
let children = client.get_children("/", true);
assert!(children.is_ok());
let mut sorted_children = children.unwrap();
sorted_children.sort();
assert_eq!(sorted_children, vec!["test".to_string(), "zookeeper".to_string... | random_line_split | |
integration.rs | #![feature(duration)]
#![deny(unused_mut)]
extern crate zookeeper;
extern crate env_logger;
use zookeeper::{Acl, CreateMode, Watcher, WatchedEvent, ZooKeeper};
use zookeeper::perms;
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, Command, Stdio};
use std::time::Duration;
struct LoggingWatcher;
im... | (server: &mut Child) -> String {
let mut reader = BufReader::new(server.stdout.as_mut().unwrap());
let mut connect_string = String::new();
if reader.read_line(&mut connect_string).is_err() {
panic!("Couldn't read ZK connect_string")
}
connect_string.pop(); // remove '\n'
connect_string
... | get_connect_string | identifier_name |
integration.rs | #![feature(duration)]
#![deny(unused_mut)]
extern crate zookeeper;
extern crate env_logger;
use zookeeper::{Acl, CreateMode, Watcher, WatchedEvent, ZooKeeper};
use zookeeper::perms;
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, Command, Stdio};
use std::time::Duration;
struct LoggingWatcher;
im... |
}
fn start_zk() -> Child {
match Command::new("java")
.arg("-jar")
.arg("zk-test-cluster/target/main.jar")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn() {
Ok(p) => p,
Err(e) => panic!("failed to execute process: {}", e),
}
}
fn ... | {
println!("{:?}", e)
} | identifier_body |
pool.rs | // Copyright 2017 The Gfx-rs 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 ag... | use ash::vk;
use ash::version::DeviceV1_0;
use core::{self, pool};
use core::command::{Encoder};
use core::{CommandPool, GeneralQueue, GraphicsQueue, ComputeQueue, TransferQueue};
use command::CommandBuffer;
use native::{self, GeneralCommandBuffer, GraphicsCommandBuffer, ComputeCommandBuffer, TransferCommandBuffer, Su... | use std::ops::DerefMut;
use std::ptr;
use std::sync::Arc; | random_line_split |
mod.rs | //! Contains the types and functions to communicate with the MusicBrainz API.
use crate::error::{Error, ErrorKind};
use crate::entities::{Mbid, ResourceOld, Resource};
use reqwest_mock::Client as MockClient;
use reqwest_mock::GenericClient as HttpClient;
use reqwest_mock::{StatusCode, Url};
use reqwest_mock::header::... |
self.last_request = now;
}
pub fn get_by_mbid<Res, Resp, Opt>(&mut self, mbid: &Mbid, options: Opt) -> Result<Res, Error>
where
Res: Resource<Options = Opt, Response = Resp>,
Resp: FromXml,
{
let request = Res::request(&options);
let url = request.get_by_mbid_ur... | {
sleep(Duration::from_millis(self.config.waits.requests) - elapsed);
} | conditional_block |
mod.rs | //! Contains the types and functions to communicate with the MusicBrainz API.
use crate::error::{Error, ErrorKind};
use crate::entities::{Mbid, ResourceOld, Resource};
use reqwest_mock::Client as MockClient;
use reqwest_mock::GenericClient as HttpClient;
use reqwest_mock::{StatusCode, Url};
use reqwest_mock::header::... | {
/// The user-agent to be sent with every request to the API.
///
/// Provide a meaningful one as it will be used by MusicBrainz to identify
/// your application and without a user agent sever throttling will be
/// undertaken. The official suggestion is to use either one of the
/// following ... | ClientConfig | identifier_name |
mod.rs | //! Contains the types and functions to communicate with the MusicBrainz API.
use crate::error::{Error, ErrorKind};
use crate::entities::{Mbid, ResourceOld, Resource};
use reqwest_mock::Client as MockClient;
use reqwest_mock::GenericClient as HttpClient;
use reqwest_mock::{StatusCode, Url};
use reqwest_mock::header::... | ((duration.as_secs() as f64) + (duration.subsec_nanos() as f64) * 1e6) as u64
}
/// Returns an `Instant` at least 1000 seconds ago.
fn past_instant() -> Instant {
Instant::now() - Duration::new(1000, 0)
}
/// Configuration for the client.
#[derive(Clone, Debug)]
pub struct ClientConfig {
/// The user-agen... | mod error;
pub(crate) use self::error::check_response_error;
/// Helper extracting the number of milliseconds from a `Duration`.
fn as_millis(duration: &Duration) -> u64 { | random_line_split |
02.rs | use std::fs::File;
use std::io::prelude::*;
fn get_input() -> std::io::Result<String> {
let mut file = File::open("02.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn run_program(program: &mut Vec<usize>) {
let mut pointer = 0;
loop {
let target_value ... |
println!("Part 1: {}", calculate_output(program.clone(), (12, 2)));
for i in 0..=99 {
for j in 0..=99 {
let output = calculate_output(program.clone(), (i, j));
if output == 19690720 {
println!("Part 2: {}", i * 100 + j);
return;
}
}
}
} | .filter_map(|x| x.trim().parse::<usize>().ok())
.collect::<Vec<_>>(); | random_line_split |
02.rs | use std::fs::File;
use std::io::prelude::*;
fn get_input() -> std::io::Result<String> {
let mut file = File::open("02.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn run_program(program: &mut Vec<usize>) {
let mut pointer = 0;
loop {
let target_value ... |
fn main() {
let input = get_input().unwrap();
let program = input.split(',')
.filter_map(|x| x.trim().parse::<usize>().ok())
.collect::<Vec<_>>();
println!("Part 1: {}", calculate_output(program.clone(), (12, 2)));
for i in 0..=99 {
for j in 0..=99 {
let output = calculate_output(program.clo... | {
program[1] = input.0;
program[2] = input.1;
run_program(&mut program);
program[0]
} | identifier_body |
02.rs | use std::fs::File;
use std::io::prelude::*;
fn get_input() -> std::io::Result<String> {
let mut file = File::open("02.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn | (program: &mut Vec<usize>) {
let mut pointer = 0;
loop {
let target_value = {
let get = |p| program[program[p]];
match program[pointer] {
1 => get(pointer + 1) + get(pointer + 2),
2 => get(pointer + 1) * get(pointer + 2),
99 => break,
_ => panic!()
}
};
... | run_program | identifier_name |
mutable_counters.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 crate::error::SubcommandError;
use anyhow::{format_err, Context, Error};
use clap_old::{App, Arg, ArgMatches, SubCommand};
use cmdlib:... |
async fn mutable_counters_get(
ctx: CoreContext,
repo_id: RepositoryId,
name: &str,
mutable_counters: SqlMutableCounters,
) -> Result<(), Error> {
let maybe_value = mutable_counters
.get_counter(ctx.clone(), repo_id, name)
.compat()
.await?;
println!("{:?}", maybe_value);... | {
let counters = mutable_counters
.get_all_counters(ctx.clone(), repo_id)
.compat()
.await?;
for (name, value) in counters {
println!("{:<30}={}", name, value);
}
Ok(())
} | identifier_body |
mutable_counters.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 crate::error::SubcommandError;
use anyhow::{format_err, Context, Error};
use clap_old::{App, Arg, ArgMatches, SubCommand};
use cmdlib:... |
info!(
ctx.logger(),
"Value of {} in {} set to {}", name, repo_id, value
);
Ok(())
} | ) -> Result<(), Error> {
mutable_counters
.set_counter(ctx.clone(), repo_id, name, value, None)
.compat()
.await?; | random_line_split |
mutable_counters.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 crate::error::SubcommandError;
use anyhow::{format_err, Context, Error};
use clap_old::{App, Arg, ArgMatches, SubCommand};
use cmdlib:... |
(_, _) => Err(format_err!("unknown mutable_counters subcommand")),
}
.map_err(SubcommandError::from)
}
async fn mutable_counters_list(
ctx: CoreContext,
repo_id: RepositoryId,
mutable_counters: SqlMutableCounters,
) -> Result<(), Error> {
let counters = mutable_counters
.get_all_... | {
let name = sub_m
.value_of(MUTABLE_COUNTERS_NAME)
.ok_or_else(|| format_err!("{} is required", MUTABLE_COUNTERS_NAME))?;
let value = args::get_i64_opt(sub_m, MUTABLE_COUNTERS_VALUE)
.ok_or_else(|| format_err!("{} is required", MUTABLE_COUNTERS_V... | conditional_block |
mutable_counters.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 crate::error::SubcommandError;
use anyhow::{format_err, Context, Error};
use clap_old::{App, Arg, ArgMatches, SubCommand};
use cmdlib:... | (
ctx: CoreContext,
repo_id: RepositoryId,
mutable_counters: SqlMutableCounters,
) -> Result<(), Error> {
let counters = mutable_counters
.get_all_counters(ctx.clone(), repo_id)
.compat()
.await?;
for (name, value) in counters {
println!("{:<30}={}", name, value);
}... | mutable_counters_list | identifier_name |
bench_engine_main.rs | #[macro_use]
extern crate criterion;
extern crate pleco;
extern crate pleco_engine;
mod eval_benches;
mod multimove_benches;
mod startpos_benches;
trait DepthLimit {
fn depth() -> u16;
}
struct Depth5 {}
struct Depth6 {}
struct Depth7 {}
struct Depth8 {}
struct Depth9 {}
impl DepthLimit for Depth5 { fn dep... | startpos_benches::search_singular
} | random_line_split | |
bench_engine_main.rs | #[macro_use]
extern crate criterion;
extern crate pleco;
extern crate pleco_engine;
mod eval_benches;
mod multimove_benches;
mod startpos_benches;
trait DepthLimit {
fn depth() -> u16;
}
struct Depth5 {}
struct | {}
struct Depth7 {}
struct Depth8 {}
struct Depth9 {}
impl DepthLimit for Depth5 { fn depth() -> u16 {5} }
impl DepthLimit for Depth6 { fn depth() -> u16 {6} }
impl DepthLimit for Depth7 { fn depth() -> u16 {7} }
impl DepthLimit for Depth8 { fn depth() -> u16 {8} }
impl DepthLimit for Depth9 { fn depth() -> u16 {9}... | Depth6 | identifier_name |
mod.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT | // 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... | // file at the top-level directory of this distribution and at | random_line_split |
boilerplate.rs | #![allow(clippy::single_match)]
use vangers::{
config::{settings::Terrain, Settings},
render::{ScreenTargets, DEPTH_FORMAT},
};
use futures::executor::{LocalPool, LocalSpawner};
use log::info;
use winit::{
event,
event_loop::{ControlFlow, EventLoop},
window::{Window, WindowBuilder},
};
pub trait A... | {
task_pool: LocalPool,
event_loop: EventLoop<()>,
window: Window,
pub device: wgpu::Device,
pub queue: wgpu::Queue,
pub downlevel_caps: wgpu::DownlevelCapabilities,
surface: wgpu::Surface,
pub color_format: wgpu::TextureFormat,
pub extent: wgpu::Extent3d,
reload_on_focus: bool,... | Harness | identifier_name |
boilerplate.rs | #![allow(clippy::single_match)]
use vangers::{
config::{settings::Terrain, Settings},
render::{ScreenTargets, DEPTH_FORMAT},
};
use futures::executor::{LocalPool, LocalSpawner};
use log::info;
use winit::{
event,
event_loop::{ControlFlow, EventLoop},
window::{Window, WindowBuilder},
};
pub trait A... | depth_or_array_layers: 1,
};
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: color_format,
width: size.width,
h... | random_line_split | |
boilerplate.rs | #![allow(clippy::single_match)]
use vangers::{
config::{settings::Terrain, Settings},
render::{ScreenTargets, DEPTH_FORMAT},
};
use futures::executor::{LocalPool, LocalSpawner};
use log::info;
use winit::{
event,
event_loop::{ControlFlow, EventLoop},
window::{Window, WindowBuilder},
};
pub trait A... | let _ = window;
*control_flow = ControlFlow::Poll;
task_pool.run_until_stalled();
match event {
event::Event::WindowEvent {
event: event::WindowEvent::Resized(size),
..
} => {
info... | {
use std::time;
let mut last_time = time::Instant::now();
let mut needs_reload = false;
let Harness {
mut task_pool,
event_loop,
window,
device,
queue,
downlevel_caps: _,
surface,
color_form... | identifier_body |
boilerplate.rs | #![allow(clippy::single_match)]
use vangers::{
config::{settings::Terrain, Settings},
render::{ScreenTargets, DEPTH_FORMAT},
};
use futures::executor::{LocalPool, LocalSpawner};
use log::info;
use winit::{
event,
event_loop::{ControlFlow, EventLoop},
window::{Window, WindowBuilder},
};
pub trait A... | else {
Some(std::path::Path::new(&settings.render.wgpu_trace_path))
},
))
.unwrap();
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface
.get_preferred_format(... | {
None
} | conditional_block |
main.rs | extern crate ndarray;
#[macro_use]
extern crate tvm;
use ndarray::Array;
use tvm::{
ffi::runtime::DLTensor,
runtime::{Module, SystemLibModule},
};
fn | () {
let syslib = SystemLibModule::default();
let add = syslib
.get_function("default_function")
.expect("main function not found");
let mut a = Array::from_vec(vec![1f32, 2., 3., 4.]);
let mut b = Array::from_vec(vec![1f32, 0., 1., 0.]);
let mut c = Array::from_vec(vec![0f32; 4]);
let e = Array::from... | main | identifier_name |
main.rs | extern crate ndarray;
#[macro_use]
extern crate tvm;
use ndarray::Array;
use tvm::{
ffi::runtime::DLTensor,
runtime::{Module, SystemLibModule},
};
fn main() | {
let syslib = SystemLibModule::default();
let add = syslib
.get_function("default_function")
.expect("main function not found");
let mut a = Array::from_vec(vec![1f32, 2., 3., 4.]);
let mut b = Array::from_vec(vec![1f32, 0., 1., 0.]);
let mut c = Array::from_vec(vec![0f32; 4]);
let e = Array::from_... | identifier_body | |
main.rs | extern crate ndarray;
#[macro_use]
extern crate tvm;
use ndarray::Array;
use tvm::{
ffi::runtime::DLTensor,
runtime::{Module, SystemLibModule},
};
fn main() {
let syslib = SystemLibModule::default();
let add = syslib
.get_function("default_function")
.expect("main function not found"); | let mut b = Array::from_vec(vec![1f32, 0., 1., 0.]);
let mut c = Array::from_vec(vec![0f32; 4]);
let e = Array::from_vec(vec![2f32, 2., 4., 4.]);
let mut a_dl: DLTensor = (&mut a).into();
let mut b_dl: DLTensor = (&mut b).into();
let mut c_dl: DLTensor = (&mut c).into();
call_packed!(add, &mut a_dl, &mut ... | let mut a = Array::from_vec(vec![1f32, 2., 3., 4.]); | random_line_split |
lib.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | // along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Efficient large, fixed-size big integers and hashes.
#![cfg_attr(asm_available, feature(asm))]
extern crate rand;
extern crate rustc_serialize;
extern crate bigint;
extern crate libc;
#[macro_use] extern crate heapsize;
pub mod hash;
/// A prel... | // You should have received a copy of the GNU General Public License | random_line_split |
protocol.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/. */
//! Low-level wire protocol implementation. Currently only supports
//! [JSON packets]
//! (https://wiki.mozilla.o... | ,
Err(ref e) if e.kind == EndOfFile =>
return Err(IoError { kind: EndOfFile, desc: "EOF", detail: None }),
_ => return Err(IoError { kind: OtherIoError, desc: "connection error", detail: None })
}
}
}
}
| {
let packet_len_str = String::from_utf8(buffer).unwrap();
let packet_len = num::from_str_radix(packet_len_str.as_slice(), 10).unwrap();
let packet_buf = self.read_exact(packet_len).unwrap();
let packet = String::from_utf8(packet_buf).unwra... | conditional_block |
protocol.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/. */
//! Low-level wire protocol implementation. Currently only supports
//! [JSON packets]
//! (https://wiki.mozilla.o... |
fn read_json_packet<'a>(&mut self) -> IoResult<Json> {
// https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport
// In short, each JSON packet is [ascii length]:[JSON data of given length]
let mut buffer = vec!();
loop {
let colon = ':' as u8;
m... | {
let s = json::encode(obj).unwrap().replace("__type__", "type");
println!("<- {}", s);
self.write_str(s.len().to_string().as_slice()).unwrap();
self.write_u8(':' as u8).unwrap();
self.write_str(s.as_slice()).unwrap();
} | identifier_body |
protocol.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/. */
//! Low-level wire protocol implementation. Currently only supports
//! [JSON packets]
//! (https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport#JSON_Packets).
use seria... | random_line_split | |
protocol.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/. */
//! Low-level wire protocol implementation. Currently only supports
//! [JSON packets]
//! (https://wiki.mozilla.o... | <'a>(&mut self) -> IoResult<Json> {
// https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport
// In short, each JSON packet is [ascii length]:[JSON data of given length]
let mut buffer = vec!();
loop {
let colon = ':' as u8;
match self.read_byte() {
... | read_json_packet | identifier_name |
main.rs | #![crate_type = "bin"]
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate gtk;
extern crate gdk;
extern crate glib;
extern crate toml;
extern crate itertools;
extern crate regex;
#[macro_use]
extern crate clap;
use gtk::prelude::*;
use gtk::{TreePath, StyleContext, CellRendererText, Builder, CssProvi... | });
window.set_border_width(0);
window.set_decorated(false);
window.show_all();
let column_types = [glib::Type::String];
let completion_store = ListStore::new(&column_types);
completion_list.set_model(Some(&completion_store));
completion_list.set_headers_visible(false);
append_text... | {
gtk::init().unwrap_or_else(|_| panic!("Failed to initialize GTK."));
debug!("Major: {}, Minor: {}", gtk::get_major_version(), gtk::get_minor_version());
let ui_path = config_directory.join(Path::new("rrun.glade"));
let ui_file = get_or_create(&ui_path, include_str!("rrun.glade"))
.unwrap_or_el... | identifier_body |
main.rs | #![crate_type = "bin"]
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate gtk;
extern crate gdk;
extern crate glib;
extern crate toml;
extern crate itertools;
extern crate regex;
#[macro_use]
extern crate clap;
use gtk::prelude::*;
use gtk::{TreePath, StyleContext, CellRendererText, Builder, CssProvi... | let (ref current_completions, ref selected_completion) = current_and_selected_completions;
*selected_completion.borrow_mut() = Some(current_completions.borrow()[selected_number].clone());
}
}
});
window.connect_key_release_event(move |_, key| {
let ke... | let selected_number = usize::from_str(path.to_string().trim()).unwrap(); | random_line_split |
main.rs | #![crate_type = "bin"]
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate gtk;
extern crate gdk;
extern crate glib;
extern crate toml;
extern crate itertools;
extern crate regex;
#[macro_use]
extern crate clap;
use gtk::prelude::*;
use gtk::{TreePath, StyleContext, CellRendererText, Builder, CssProvi... | (config_directory: &Path, engine: DefaultEngine) {
gtk::init().unwrap_or_else(|_| panic!("Failed to initialize GTK."));
debug!("Major: {}, Minor: {}", gtk::get_major_version(), gtk::get_minor_version());
let ui_path = config_directory.join(Path::new("rrun.glade"));
let ui_file = get_or_create(&ui_path, ... | run_ui | identifier_name |
main.rs | #![crate_type = "bin"]
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate gtk;
extern crate gdk;
extern crate glib;
extern crate toml;
extern crate itertools;
extern crate regex;
#[macro_use]
extern crate clap;
use gtk::prelude::*;
use gtk::{TreePath, StyleContext, CellRendererText, Builder, CssProvi... |
} else {
run_ui(&config_directory, engine);
}
}
fn run_ui(config_directory: &Path, engine: DefaultEngine) {
gtk::init().unwrap_or_else(|_| panic!("Failed to initialize GTK."));
debug!("Major: {}, Minor: {}", gtk::get_major_version(), gtk::get_minor_version());
let ui_path = config_director... | {
panic!("If you call completions, you need to provide type and query\nIf unsure, run 'rrun completions \
--help'")
} | conditional_block |
regionmanip.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 ... | ty::ty_open(_) => {
self.tcx.sess.bug(
&format!("Unexpected type encountered while doing wf check: {}",
ty.repr(self.tcx))[]);
}
}
}
fn accumulate_from_rptr(&mut self,
ty: Ty<'tcx>,
... | random_line_split | |
regionmanip.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 ... |
/// Pushes a constraint that `region <= param_ty`, due to `opt_ty`
fn push_param_constraint(&mut self,
region: ty::Region,
opt_ty: Option<Ty<'tcx>>,
param_ty: ty::ParamTy) {
self.out.push(RegionSubGenericConstraint(... | {
let &(region, opt_ty) = self.stack.last().unwrap();
self.out.push(RegionSubGenericConstraint(
opt_ty, region, GenericKind::Projection(projection_ty.clone())));
} | identifier_body |
regionmanip.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 ... | (&mut self,
ty: Ty<'tcx>,
region_bound: ty::Region,
required_region_bounds: Vec<ty::Region>)
{
// Imagine a type like this:
//
// trait Foo { }
// trait Bar<'c> : 'c { }
... | accumulate_from_object_ty | identifier_name |
rectangle.rs | use crate::{
style::Color,
widgets::canvas::{Line, Painter, Shape},
};
/// Shape to draw a rectangle from a `Rect` with the given color
#[derive(Debug, Clone)]
pub struct Rectangle {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
pub color: Color,
}
impl Shape for Rectangle {
... | (&self, painter: &mut Painter) {
let lines: [Line; 4] = [
Line {
x1: self.x,
y1: self.y,
x2: self.x,
y2: self.y + self.height,
color: self.color,
},
Line {
x1: self.x,
... | draw | identifier_name |
rectangle.rs | use crate::{
style::Color,
widgets::canvas::{Line, Painter, Shape},
};
/// Shape to draw a rectangle from a `Rect` with the given color
#[derive(Debug, Clone)]
pub struct Rectangle {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
pub color: Color,
}
impl Shape for Rectangle {
... | y2: self.y + self.height,
color: self.color,
},
Line {
x1: self.x,
y1: self.y,
x2: self.x + self.width,
y2: self.y,
color: self.color,
},
];
for line in &li... | {
let lines: [Line; 4] = [
Line {
x1: self.x,
y1: self.y,
x2: self.x,
y2: self.y + self.height,
color: self.color,
},
Line {
x1: self.x,
y1: self.y + self.height,
... | identifier_body |
rectangle.rs | use crate::{
style::Color,
widgets::canvas::{Line, Painter, Shape},
};
/// Shape to draw a rectangle from a `Rect` with the given color
#[derive(Debug, Clone)]
pub struct Rectangle {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
pub color: Color,
}
impl Shape for Rectangle {
... | y2: self.y + self.height,
color: self.color,
},
Line {
x1: self.x,
y1: self.y + self.height,
x2: self.x + self.width,
y2: self.y + self.height,
color: self.color,
},
... | let lines: [Line; 4] = [
Line {
x1: self.x,
y1: self.y,
x2: self.x, | random_line_split |
quickcheck_limbs.rs | extern crate quickcheck;
extern crate ramp;
extern crate num_bigint;
use quickcheck::TestResult;
use ramp::ll::limb;
use ramp::ll::limb::Limb;
use num_bigint::BigUint;
#[cfg(feature = "full-quickcheck")]
const QUICKCHECK_THOROUGNESS: u64 = 100;
#[cfg(not(feature = "full-quickcheck"))]
const QUICKCHECK_THOROUGNESS: u6... | fn check_mul(a: usize, b: usize) -> TestResult {
let num_prod = b!(a) * b!(b);
let (hw, lw) = limb::mul(l!(a), l!(b));
let ramp_prod = b!(hw.0, lw.0);
TestResult::from_bool(ramp_prod == num_prod)
}
fn check_div(hn: usize, ln: usize, d: usize) -> TestResult {
let d ... | random_line_split | |
build.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/. */
#![feature(io, path)]
use std::env;
use std::fs::File;
use std::io::Write;
use std::process::{Command, Stdio};
us... | }
| {
let python = if Command::new("python2.7").arg("--version").status().unwrap().success() {
"python2.7"
} else {
"python"
};
let style = Path::new(file!()).parent().unwrap();
let mako = style.join("Mako-0.9.1.zip");
let template = style.join("properties.mako.rs");
let result =... | identifier_body |
build.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/. */
#![feature(io, path)]
use std::env;
use std::fs::File;
use std::io::Write;
use std::process::{Command, Stdio};
us... | else {
"python"
};
let style = Path::new(file!()).parent().unwrap();
let mako = style.join("Mako-0.9.1.zip");
let template = style.join("properties.mako.rs");
let result = Command::new(python)
.env("PYTHONPATH", &mako)
.env("TEMPLATE", &template)
.arg("-c")
.arg(... | {
"python2.7"
} | conditional_block |
build.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/. */
#![feature(io, path)]
use std::env;
use std::fs::File;
use std::io::Write;
use std::process::{Command, Stdio};
us... | } else {
"python"
};
let style = Path::new(file!()).parent().unwrap();
let mako = style.join("Mako-0.9.1.zip");
let template = style.join("properties.mako.rs");
let result = Command::new(python)
.env("PYTHONPATH", &mako)
.env("TEMPLATE", &template)
.arg("-c")
... | fn main() {
let python = if Command::new("python2.7").arg("--version").status().unwrap().success() {
"python2.7" | random_line_split |
build.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/. */
#![feature(io, path)]
use std::env;
use std::fs::File;
use std::io::Write;
use std::process::{Command, Stdio};
us... | () {
let python = if Command::new("python2.7").arg("--version").status().unwrap().success() {
"python2.7"
} else {
"python"
};
let style = Path::new(file!()).parent().unwrap();
let mako = style.join("Mako-0.9.1.zip");
let template = style.join("properties.mako.rs");
let resul... | main | identifier_name |
keyword.rs | use liquid_core::Expression;
use liquid_core::Result;
use liquid_core::Runtime;
use liquid_core::{
Display_filter, Filter, FilterParameters, FilterReflection, FromFilterParameters, ParseFilter,
};
use liquid_core::{Value, ValueView};
#[derive(Debug, FilterParameters)]
struct TestKeywordFilterParameters {
#[par... | ;
#[derive(Debug, FromFilterParameters, Display_filter)]
#[name = "kw"]
pub struct TestKeywordFilter {
#[parameters]
args: TestKeywordFilterParameters,
}
impl Filter for TestKeywordFilter {
fn evaluate(&self, _input: &dyn ValueView, runtime: &dyn Runtime) -> Result<Value> {
let args = self.args.ev... | TestKeywordFilterParser | identifier_name |
keyword.rs | use liquid_core::Expression;
use liquid_core::Result;
use liquid_core::Runtime;
use liquid_core::{
Display_filter, Filter, FilterParameters, FilterReflection, FromFilterParameters, ParseFilter,
};
use liquid_core::{Value, ValueView};
#[derive(Debug, FilterParameters)]
struct TestKeywordFilterParameters {
#[par... | let result = if let Some(optional) = args.optional {
format!("<optional: {}; required: {}>", optional, required)
} else {
format!("<required: {}>", required)
};
Ok(Value::scalar(result))
}
} | random_line_split | |
keyword.rs | use liquid_core::Expression;
use liquid_core::Result;
use liquid_core::Runtime;
use liquid_core::{
Display_filter, Filter, FilterParameters, FilterReflection, FromFilterParameters, ParseFilter,
};
use liquid_core::{Value, ValueView};
#[derive(Debug, FilterParameters)]
struct TestKeywordFilterParameters {
#[par... | ;
Ok(Value::scalar(result))
}
}
| {
format!("<required: {}>", required)
} | conditional_block |
util.rs | use std::hash;
use std::io;
pub fn read_tag<R: io::BufRead>(input: &mut R, tag: &[u8]) -> io::Result<bool> {
let mut buf = vec![0; tag.len()];
input.read_exact(buf.as_mut_slice())?;
Ok(buf.as_slice() == tag)
}
pub fn is_eof<R: io::BufRead>(input: &mut R) -> io::Result<bool> {
let buf = input.fill_buf(... |
}
len
};
input.consume(len);
}
}
// A Read computing a digest on the bytes read.
pub struct HasherRead<'a, R, H>
where
R: 'a + io::Read,
H: 'a + hash::Hasher,
{
read: &'a mut R, // underlying reader
hasher: &'a mut H, // hasher
}
impl<'a, R, H> HasherRea... | {
return Ok(false);
} | conditional_block |
util.rs | use std::hash;
use std::io;
pub fn read_tag<R: io::BufRead>(input: &mut R, tag: &[u8]) -> io::Result<bool> {
let mut buf = vec![0; tag.len()];
input.read_exact(buf.as_mut_slice())?;
Ok(buf.as_slice() == tag)
}
pub fn is_eof<R: io::BufRead>(input: &mut R) -> io::Result<bool> {
let buf = input.fill_buf(... | } | random_line_split | |
util.rs | use std::hash;
use std::io;
pub fn read_tag<R: io::BufRead>(input: &mut R, tag: &[u8]) -> io::Result<bool> {
let mut buf = vec![0; tag.len()];
input.read_exact(buf.as_mut_slice())?;
Ok(buf.as_slice() == tag)
}
pub fn is_eof<R: io::BufRead>(input: &mut R) -> io::Result<bool> {
let buf = input.fill_buf(... | (&mut self) -> io::Result<&[u8]> {
self.read.fill_buf()
}
fn consume(&mut self, amt: usize) {
self.read.consume(amt);
self.count += amt;
}
}
| fill_buf | identifier_name |
util.rs | use std::hash;
use std::io;
pub fn read_tag<R: io::BufRead>(input: &mut R, tag: &[u8]) -> io::Result<bool> {
let mut buf = vec![0; tag.len()];
input.read_exact(buf.as_mut_slice())?;
Ok(buf.as_slice() == tag)
}
pub fn is_eof<R: io::BufRead>(input: &mut R) -> io::Result<bool> {
let buf = input.fill_buf(... |
fn consume(&mut self, amt: usize) {
self.read.consume(amt);
self.count += amt;
}
}
| {
self.read.fill_buf()
} | identifier_body |
message.rs | use std::fmt;
use std::hash::{Hash, Hasher};
use std::str::from_utf8;
use std::collections::HashMap;
use hdata::HData;
use errors::WeechatError;
use errors::WeechatError::ParseError;
use parse::Parse;
use strdata::StrData;
/// Holds header information for data received from relay
#[derive(Debug)]
pub struct Header {... | }
/// Possible types of messages received from relay (almost every message, excluding pongs,
/// will use HData)
#[derive(Debug)]
pub enum Type {
StrData(StrData),
HData(HData),
}
impl Message {
pub fn new(bytes: &[u8]) -> Result<Message, WeechatError> {
// First thing encoded is the identifier fo... | /// Data contained in this message
data_type: Type, | random_line_split |
message.rs | use std::fmt;
use std::hash::{Hash, Hasher};
use std::str::from_utf8;
use std::collections::HashMap;
use hdata::HData;
use errors::WeechatError;
use errors::WeechatError::ParseError;
use parse::Parse;
use strdata::StrData;
/// Holds header information for data received from relay
#[derive(Debug)]
pub struct Header {... | (&self) -> Result<i32, WeechatError> {
match *self {
Object::Int(i) => Ok(i),
_ => Err(ParseError("Item is not a integer".to_string()))
}
}
/// Returns this data as a long if it is a long.
pub fn as_long(&self) -> Result<i64, WeechatError> {
matc... | as_integer | identifier_name |
message.rs | use std::fmt;
use std::hash::{Hash, Hasher};
use std::str::from_utf8;
use std::collections::HashMap;
use hdata::HData;
use errors::WeechatError;
use errors::WeechatError::ParseError;
use parse::Parse;
use strdata::StrData;
/// Holds header information for data received from relay
#[derive(Debug)]
pub struct Header {... |
/// Returns this data as a string if it is a string.
pub fn as_str(&self) -> Result<Option<&str>, WeechatError> {
match *self {
Object::Str(Some(ref s)) => Ok(Some(s)),
Object::Str(None) => Ok(None),
_ => Err(ParseError("Item is not a b... | {
try!(self.as_pointer().map(|p| p.ok_or(ParseError("pointer is null".to_string()))))
} | identifier_body |
coherence.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,'tcx>(selcx: &mut SelectionContext<'a,'tcx>,
impl_def_id: ast::DefId,
substs_fn: SubstsFn)
-> (ty::TraitRef<'tcx>,
Vec<PredicateObligation<'tcx>>)
{
let impl_su... | impl_trait_ref_and_oblig | identifier_name |
coherence.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 ... | infer::Misc(DUMMY_SP),
a_trait_ref.to_poly_trait_ref(),
b_trait_ref.to_poly_trait_ref()) {
return false;
}
debug!("overlap: subtraitref check succeeded")... | {
debug!("overlap(a_def_id={:?}, b_def_id={:?})",
a_def_id,
b_def_id);
let (a_trait_ref, a_obligations) = impl_trait_ref_and_oblig(selcx,
a_def_id,
util::fresh_t... | identifier_body |
coherence.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 ... | // uncovered type parameters.
let uncovered_tys = uncovered_tys(tcx, input_ty, infer_is_local);
for uncovered_ty in uncovered_tys {
if let Some(param) = uncovered_ty.walk().find(|t| is_type_parameter(t)) {
debug!("orphan_check_trait_ref: uncovered ... |
// First local input type. Check that there are no | random_line_split |
main.rs | //! runec - Rune Console.
//!
//! Interactive shell that uses rune for user guided symbolic execution and
//! binary reasoning.
extern crate rune;
extern crate libsmt;
extern crate docopt;
extern crate rustc_serialize;
extern crate r2pipe;
extern crate r2api;
mod interact;
mod console;
use std::process::exit;
use do... | Usage:
runec [-p <path>] <file>
runec (-h | --help)
Options:
-h --help Show this screen.
-p Load a previous configuration of state
";
#[derive(Debug, Clone, RustcDecodable)]
struct Args {
flag_help: bool,
flag_project: bool,
arg_path... | random_line_split | |
main.rs | //! runec - Rune Console.
//!
//! Interactive shell that uses rune for user guided symbolic execution and
//! binary reasoning.
extern crate rune;
extern crate libsmt;
extern crate docopt;
extern crate rustc_serialize;
extern crate r2pipe;
extern crate r2api;
mod interact;
mod console;
use std::process::exit;
use do... | {
flag_help: bool,
flag_project: bool,
arg_path: Option<String>,
arg_file: Option<String>,
}
fn main() {
let args = Docopt::new(USAGE)
.and_then(|dopt| dopt.parse())
.unwrap_or_else(|e| e.exit());
if args.get_bool("-h") {
println!("{}", USAGE)... | Args | identifier_name |
main.rs | //! runec - Rune Console.
//!
//! Interactive shell that uses rune for user guided symbolic execution and
//! binary reasoning.
extern crate rune;
extern crate libsmt;
extern crate docopt;
extern crate rustc_serialize;
extern crate r2pipe;
extern crate r2api;
mod interact;
mod console;
use std::process::exit;
use do... | else {
is.add_const((key.clone(), val as u64));
}
},
Command::Exit => {
c.print_info("Thanks for using rune!");
exit(0);
},
Command::Invalid => {
c.print_error("Invalid command. Please tr... | {
is.set_start_addr(val as u64);
} | conditional_block |
shootout-k-nucleotide-pipes.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... | () {
use std::io::{stdio, MemReader, BufferedReader};
let rdr = if os::getenv("RUST_BENCH").is_some() {
let foo = include_bytes!("shootout-k-nucleotide.data");
box MemReader::new(foo.to_vec()) as Box<Reader>
} else {
box stdio::stdin() as Box<Reader>
};
let mut rdr = Buffere... | main | identifier_name |
shootout-k-nucleotide-pipes.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... |
None => { }
}
}
// break our processing
('>', true) => { break; }
// process the sequence for k-mers
(_, true) => {
let line_bytes = line.as_bytes();
for (ii, _sz) in sizes.iter().enumerate() {
... | { proc_mode = true; } | conditional_block |
shootout-k-nucleotide-pipes.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... | // run it("hell") and it("ello"), then return "llo"
fn windows_with_carry<F>(bb: &[u8], nn: uint, mut it: F) -> Vec<u8> where
F: FnMut(&[u8]),
{
let mut ii = 0u;
let len = bb.len();
while ii < len - (nn - 1u) {
it(&bb[ii..(ii+nn)]);
ii += 1u;
}
return bb[(len - (nn - 1u))..len].to_vec()... | random_line_split | |
shootout-k-nucleotide-pipes.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
let mut pairs = Vec::new();
// map -> [(k,%)]
for (key, &val) in mm.iter() {
pairs.push(((*key).clone(), pct(val, total)));
}
let pairs_sorted = sortKV(pairs);
let mut buffer = String::new();
for &(ref k, v) in pairs_sorted.iter() {
buffer.push_str(format!("{:?} {:0.3}\n",
... | {
orig.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
orig.sort_by(|&(_, a), &(_, b)| f64_cmp(b, a));
orig
} | identifier_body |
main.rs | #[macro_use] extern crate nickel;
extern crate config;
extern crate pulldown_cmark;
| use std::collections::HashMap;
use std::fs::File;
use std::io::{Read,BufReader, Error};
use config::reader;
use config::types::Config;
use pulldown_cmark::Parser;
use pulldown_cmark::html::push_html;
use nickel::*;
use nickel::extensions::Redirect;
fn main() {
let empty_default_config = Config::new(HashMap::new(... | use nickel::Nickel;
use std::path::Path; | random_line_split |
main.rs | #[macro_use] extern crate nickel;
extern crate config;
extern crate pulldown_cmark;
use nickel::Nickel;
use std::path::Path;
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read,BufReader, Error};
use config::reader;
use config::types::Config;
use pulldown_cmark::Parser;
use pulldown_cmark::html::pus... | () {
let empty_default_config = Config::new(HashMap::new());
let configuration = reader::from_file(Path::new("Dokiofile")).unwrap_or(empty_default_config);
let listening_port = configuration.lookup_integer32_or("port", 3000);
let default_file = String::from(configuration.lookup_str_or("default_file", "... | main | identifier_name |
main.rs | #[macro_use] extern crate nickel;
extern crate config;
extern crate pulldown_cmark;
use nickel::Nickel;
use std::path::Path;
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read,BufReader, Error};
use config::reader;
use config::types::Config;
use pulldown_cmark::Parser;
use pulldown_cmark::html::pus... | {
let file_path = format!(".{}", path.unwrap());
let file = File::open(Path::new(file_path.as_str()))?;
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents)?;
Ok(contents)
} | identifier_body | |
golden_outputs.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use goldenfile::Mint;
use std::{cell::RefCell, fmt::Debug, fs::File, io::Write, path::PathBuf};
pub const GOLDEN_DIR_PATH: &str = "goldens";
pub const EXT_NAME: &str = "exp";
pub(crate) struct GoldenOutputs {
#[allow(dead_code)]
... | () -> PathBuf {
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push(GOLDEN_DIR_PATH.to_string());
path
}
impl GoldenOutputs {
pub fn new(name: &str) -> Self {
let mut mint = Mint::new(golden_path());
let mut file_path = PathBuf::new();
file_path.push(name);
... | golden_path | identifier_name |
golden_outputs.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use goldenfile::Mint;
use std::{cell::RefCell, fmt::Debug, fs::File, io::Write, path::PathBuf};
pub const GOLDEN_DIR_PATH: &str = "goldens";
pub const EXT_NAME: &str = "exp";
pub(crate) struct GoldenOutputs {
#[allow(dead_code)]
... | fn golden_path() -> PathBuf {
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push(GOLDEN_DIR_PATH.to_string());
path
}
impl GoldenOutputs {
pub fn new(name: &str) -> Self {
let mut mint = Mint::new(golden_path());
let mut file_path = PathBuf::new();
file_path.pus... | file: RefCell<File>,
}
| random_line_split |
golden_outputs.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use goldenfile::Mint;
use std::{cell::RefCell, fmt::Debug, fs::File, io::Write, path::PathBuf};
pub const GOLDEN_DIR_PATH: &str = "goldens";
pub const EXT_NAME: &str = "exp";
pub(crate) struct GoldenOutputs {
#[allow(dead_code)]
... |
impl GoldenOutputs {
pub fn new(name: &str) -> Self {
let mut mint = Mint::new(golden_path());
let mut file_path = PathBuf::new();
file_path.push(name);
let file = RefCell::new(
mint.new_goldenfile(file_path.with_extension(EXT_NAME))
.unwrap(),
);... | {
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push(GOLDEN_DIR_PATH.to_string());
path
} | identifier_body |
calculator.rs | //! `Calculator` is an easy to use generic method of evaluating string expressions.
use super::*;
use polynomial::Polynomial;
/// `CalculationError` wraps parsing and evaluation errors
#[derive(Debug, PartialEq)]
pub enum CalculationError {
/// `ParsingError` returned from `TokensProcessor`
ParsingError(ParsingEr... | (e: ParsingError) -> CalculationError {
CalculationError::ParsingError(e)
}
}
/// Wraps `EvaluationError` in `CalculationError`
impl From<EvaluationError> for CalculationError {
fn from(e: EvaluationError) -> CalculationError {
CalculationError::EvaluationError(e)
}
}
/// Calculator is the easiest way o... | from | identifier_name |
calculator.rs | //! `Calculator` is an easy to use generic method of evaluating string expressions.
use super::*;
use polynomial::Polynomial;
/// `CalculationError` wraps parsing and evaluation errors
#[derive(Debug, PartialEq)]
pub enum CalculationError {
/// `ParsingError` returned from `TokensProcessor`
ParsingError(ParsingEr... | CalculationError::ParsingError(e)
}
}
/// Wraps `EvaluationError` in `CalculationError`
impl From<EvaluationError> for CalculationError {
fn from(e: EvaluationError) -> CalculationError {
CalculationError::EvaluationError(e)
}
}
/// Calculator is the easiest way of evaluating string expressions
/// into... | /// Wraps `ParsingError` in `CalculationError`
impl From<ParsingError> for CalculationError {
fn from(e: ParsingError) -> CalculationError { | random_line_split |
calculator.rs | //! `Calculator` is an easy to use generic method of evaluating string expressions.
use super::*;
use polynomial::Polynomial;
/// `CalculationError` wraps parsing and evaluation errors
#[derive(Debug, PartialEq)]
pub enum CalculationError {
/// `ParsingError` returned from `TokensProcessor`
ParsingError(ParsingEr... |
}
/// Calculator is the easiest way of evaluating string expressions
/// into a `Polynomial` value.
///
/// A struct which is a calculator (implements this trait) can easily
/// perform evaluation using given `StringProcessor`, `TokensProcessor`
/// and `TokensReducer`.
pub trait Calculator<T, P, E>
where T: String... | {
CalculationError::EvaluationError(e)
} | identifier_body |
lsp_state.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::{
diagnostic_reporter::DiagnosticReporter,
js_language_server::JSLanguageServer,
lsp_runtime_error::LSPRunti... |
pub(crate) fn extract_executable_document_from_text(
&mut self,
position: &TextDocumentPositionParams,
index_offset: usize,
) -> LSPRuntimeResult<(ExecutableDocument, Span, StringKey)> {
extract_executable_document_from_text(
&position,
&self.synced_grap... | {
self.synced_graphql_documents.remove(url);
self.diagnostic_reporter
.clear_quick_diagnostics_for_url(url);
} | identifier_body |
lsp_state.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::{
diagnostic_reporter::DiagnosticReporter,
js_language_server::JSLanguageServer,
lsp_runtime_error::LSPRunti... |
}
fn preload_documentation(&self) {
for project_config in self.config.enabled_projects() {
self.extra_data_provider
.get_schema_documentation(project_config.name.to_string());
}
}
pub fn get_project_config_ref(&self, project_name: StringKey) -> Option<&Proje... | {
tokio::spawn(async move { compiler.watch().await });
} | conditional_block |
lsp_state.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::{
diagnostic_reporter::DiagnosticReporter,
js_language_server::JSLanguageServer,
lsp_runtime_error::LSPRunti... | file_categorizer: FileCategorizer,
schemas: Schemas,
source_programs: SourcePrograms,
synced_graphql_documents: HashMap<Url, Vec<GraphQLSource>>,
perf_logger: Arc<TPerfLogger>,
diagnostic_reporter: Arc<DiagnosticReporter>,
notify_sender: Arc<Notify>,
project_status: ProjectStatusMap,
... | pub extra_data_provider: Box<dyn LSPExtraDataProvider>, | random_line_split |
lsp_state.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::{
diagnostic_reporter::DiagnosticReporter,
js_language_server::JSLanguageServer,
lsp_runtime_error::LSPRunti... | (&self) -> &SourcePrograms {
&self.source_programs
}
pub(crate) fn resolve_node(
&self,
params: TextDocumentPositionParams,
) -> LSPRuntimeResult<NodeResolutionInfo> {
get_node_resolution_info(
params,
&self.synced_graphql_documents,
&self... | get_source_programs_ref | identifier_name |
process.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
persistent_safety_storage::PersistentSafetyStorage,
remote_service::{self, RemoteService},
safety_rules_manager,
};
use diem_config::config::{SafetyRulesConfig, SafetyRulesService};
use std::net::SocketAddr;
p... |
}
impl RemoteService for ProcessService {
fn server_address(&self) -> SocketAddr {
self.server_addr
}
fn network_timeout_ms(&self) -> u64 {
self.network_timeout_ms
}
}
| {
Self {
server_addr,
network_timeout_ms: network_timeout,
}
} | identifier_body |
process.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
persistent_safety_storage::PersistentSafetyStorage,
remote_service::{self, RemoteService},
safety_rules_manager,
};
use diem_config::config::{SafetyRulesConfig, SafetyRulesService};
use std::net::SocketAddr;
p... | (&self) -> SocketAddr {
self.server_addr
}
fn network_timeout_ms(&self) -> u64 {
self.network_timeout_ms
}
}
| server_address | identifier_name |
process.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
persistent_safety_storage::PersistentSafetyStorage,
remote_service::{self, RemoteService},
safety_rules_manager, | pub struct Process {
data: Option<ProcessData>,
}
impl Process {
pub fn new(config: SafetyRulesConfig) -> Self {
let storage = safety_rules_manager::storage(&config);
let verify_vote_proposal_signature = config.verify_vote_proposal_signature;
let export_consensus_key = config.export_co... | };
use diem_config::config::{SafetyRulesConfig, SafetyRulesService};
use std::net::SocketAddr;
| random_line_split |
macros.rs | pub fn macros() {
println!("***Macros***");
basics();
advanced();
common_macros();
println!("");
}
macro_rules! mvec {
( $( $x:expr),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
... | () {
unimplemented!();
}
if false {
unreachable!();
}
let x: Option<i32> = None;
match x {
Some(_) => unreachable!(),
None => println!("I know x is None!"),
}
// will panic because unimp_test is not yet implemented
// unimp_test();
}
| unimp_test | identifier_name |
macros.rs | pub fn macros() |
macro_rules! mvec {
( $( $x:expr),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}
macro_rules! foo {
(x => $e:expr) => (println!("mode X: {}", $e));
(y => $e:expr) => (println!("mode Y: ... | {
println!("***Macros***");
basics();
advanced();
common_macros();
println!("");
} | identifier_body |
macros.rs | pub fn macros() {
println!("***Macros***");
basics();
advanced();
common_macros();
println!("");
}
macro_rules! mvec {
( $( $x:expr),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
... | #[allow(unused_variables, dead_code)]
fn common_macros() {
// panic!("oh no!"); // causes the thread to panic
let v1 = vec![1, 2, 3];
let v2 = vec![0; 10];
assert!(true);
assert_eq!(5, 3+2);
// not really
// assert!(5 < 3);
// assert_eq!(5, 3);
use std;
use std::fs::File;
... | ($x:expr) => ( $crate::increment($x) )
}
| random_line_split |
reader.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 ... | /// # Panics
///
/// It will panic if it there is insufficient data to fulfill a request.
///
/// # Example
///
/// ```rust
/// use std::rand::{reader, Rng};
/// use std::io::MemReader;
///
/// let mut rng = reader::ReaderRng::new(MemReader::new(vec!(1,2,3,4,5,6,7,8)));
/// println!("{:x}", rng.gen::<uint>());
/// ```
... |
/// An RNG that reads random bytes straight from a `Reader`. This will
/// work best with an infinite reader, but this is not required.
/// | random_line_split |
reader.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 ... |
fn next_u64(&mut self) -> u64 {
// see above for explanation.
if cfg!(target_endian="little") {
self.reader.read_le_u64().unwrap()
} else {
self.reader.read_be_u64().unwrap()
}
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { retur... | {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
if cfg!(target_endian="little") {
self.reader.read_le_u32().unwrap()
} else {
... | identifier_body |
reader.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 ... |
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { return }
match self.reader.read_at_least(v.len(), v) {
Ok(_) => {}
Err(e) => panic!("ReaderRng.fill_bytes error: {}", e)
}
}
}
#[cfg(test)]
mod test {
use prelude::*;
use super::ReaderRng;... | {
self.reader.read_be_u64().unwrap()
} | conditional_block |
reader.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 ... | (&mut self) -> u64 {
// see above for explanation.
if cfg!(target_endian="little") {
self.reader.read_le_u64().unwrap()
} else {
self.reader.read_be_u64().unwrap()
}
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { return }
matc... | next_u64 | identifier_name |
lib.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | // Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#![deny(
dead_code,
non_camel_cas... | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | random_line_split |
build.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | () {
let out_dir = env::var("OUT_DIR").unwrap();
let output = Command::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/build_test_lib.py"
))
.arg(&out_dir)
.output()
.expect("Failed to execute command");
assert!(
Path::new(&format!("{}/test.so", out_dir)).exists(),
... | main | identifier_name |
build.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | */
use std::{env, path::Path, process::Command};
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let output = Command::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/build_test_lib.py"
))
.arg(&out_dir)
.output()
.expect("Failed to execute command");
assert!(
... | * 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 |
build.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | }
| {
let out_dir = env::var("OUT_DIR").unwrap();
let output = Command::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/build_test_lib.py"
))
.arg(&out_dir)
.output()
.expect("Failed to execute command");
assert!(
Path::new(&format!("{}/test.so", out_dir)).exists(),
... | identifier_body |
mod.rs | // The MIT License (MIT)
// Copyright (c) 2015 Y. T. Chung <zonyitoo@gmail.com>
| // the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY K... | // Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell co... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.