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 |
|---|---|---|---|---|
messages_util.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... |
impl Random for messages::ConnectRequest {
fn generate_random() -> messages::ConnectRequest {
messages::ConnectRequest {
local_endpoints: random_endpoints(),
external_endpoints: random_endpoints(),
requester_fob: Random::generate_random(),
... | {
let range = Range::new(1, 10);
let mut rng = thread_rng();
let count = range.ind_sample(&mut rng);
let mut endpoints = vec![];
for _ in 0..count {
endpoints.push(random_endpoint());
}
endpoints
} | identifier_body |
messages_util.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | // Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
#[cfg(test)]
pub mod test {
use messages;
use crust::Endpoint;
use sodiumoxide::crypto;
use rand::distributions::{IndependentSample, Range};
use rand::{ran... | // | random_line_split |
messages_util.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | () -> Endpoint {
use std::net::{Ipv4Addr, SocketAddrV4, SocketAddr};
Endpoint::Tcp(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(random::<u8>(),
random::<u8>(),
rand... | random_endpoint | identifier_name |
main.rs | use sendgrid::SGClient;
use sendgrid::{Destination, Mail};
fn main() | .add_subject("Rust is rad")
.add_html("<h1>Hello from SendGrid!</h1>")
.add_from_name("Test")
.add_header("x-cool".to_string(), "indeed")
.add_x_smtpapi(&x_smtpapi);
match sg.send(mail_info) {
Err(err) => println!("Error: {}", err),
Ok(body) => println!("Response:... | {
let mut env_vars = std::env::vars();
let api_key_check = env_vars.find(|var| var.0 == "SENDGRID_API_KEY");
let api_key: String;
match api_key_check {
Some(key) => api_key = key.1,
None => panic!("Must supply API key in environment variables to use!"),
}
let sg = SGClient::new(... | identifier_body |
main.rs | use sendgrid::SGClient;
use sendgrid::{Destination, Mail};
fn | () {
let mut env_vars = std::env::vars();
let api_key_check = env_vars.find(|var| var.0 == "SENDGRID_API_KEY");
let api_key: String;
match api_key_check {
Some(key) => api_key = key.1,
None => panic!("Must supply API key in environment variables to use!"),
}
let sg = SGClient::n... | main | identifier_name |
main.rs | use sendgrid::SGClient;
use sendgrid::{Destination, Mail};
fn main() { | let mut env_vars = std::env::vars();
let api_key_check = env_vars.find(|var| var.0 == "SENDGRID_API_KEY");
let api_key: String;
match api_key_check {
Some(key) => api_key = key.1,
None => panic!("Must supply API key in environment variables to use!"),
}
let sg = SGClient::new(ap... | random_line_split | |
logger.rs | use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError};
struct Logger {
log_level: Level,
}
impl Log for Logger {
fn | (&self, metadata: &Metadata) -> bool {
metadata.level() <= self.log_level
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
println!("[{:>5}@{}] {}", record.level(), record.target(), record.args());
}
}
fn flush(&self) {}
}
pub fn init(level: ... | enabled | identifier_name |
logger.rs | use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError};
struct Logger { | fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= self.log_level
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
println!("[{:>5}@{}] {}", record.level(), record.target(), record.args());
}
}
fn flush(&self) {}
}
pub f... | log_level: Level,
}
impl Log for Logger { | random_line_split |
logger.rs | use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError};
struct Logger {
log_level: Level,
}
impl Log for Logger {
fn enabled(&self, metadata: &Metadata) -> bool |
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
println!("[{:>5}@{}] {}", record.level(), record.target(), record.args());
}
}
fn flush(&self) {}
}
pub fn init(level: &str) -> Result<(), SetLoggerError> {
if level!= "off" {
let log_level = ma... | {
metadata.level() <= self.log_level
} | identifier_body |
text_run.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 app_units::Au;
use font::{Font, FontHandleMethods, FontMetrics, ShapingFlags};
use font::{RunMetrics, ShapingO... |
let mut byte_range = self.range.intersect(&slice_glyphs.range);
let slice_range_begin = slice_glyphs.range.begin();
byte_range.shift_by(-slice_range_begin);
if!byte_range.is_empty() {
Some(TextRunSlice {
glyphs: &*slice_glyphs.glyph_store,
of... | random_line_split | |
text_run.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 app_units::Au;
use font::{Font, FontHandleMethods, FontMetrics, ShapingFlags};
use font::{RunMetrics, ShapingO... | (&mut self) -> Option<TextRunSlice<'a>> {
let slice_glyphs;
if self.reverse {
if self.index == 0 {
return None;
}
self.index -= 1;
slice_glyphs = &self.glyphs[self.index];
} else {
if self.index >= self.glyphs.len() {
... | next | identifier_name |
main.rs | extern crate may;
extern crate num_cpus;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate may_minihttp;
use std::io;
use may_minihttp::{HttpServer, HttpService, Request, Response};
#[derive(Serialize)]
struct Message<'a> {
message: &'a str,
}
struct Techempower;
impl HttpService for... | () {
may::config().set_io_workers(num_cpus::get());
let server = HttpServer(Techempower).start("0.0.0.0:8080").unwrap();
server.join().unwrap();
}
| main | identifier_name |
main.rs | extern crate may;
extern crate num_cpus;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate may_minihttp;
use std::io;
use may_minihttp::{HttpServer, HttpService, Request, Response};
#[derive(Serialize)]
struct Message<'a> {
message: &'a str,
}
struct Techempower;
| impl HttpService for Techempower {
fn call(&self, req: Request) -> io::Result<Response> {
let mut resp = Response::new();
// Bare-bones router
match req.path() {
"/json" => {
resp.header("Content-Type", "application/json");
*resp.body_mut() =
... | random_line_split | |
testPriority.rs |
extern mod extra;
use std::rt::io::*;
use std::rt::io::net::ip::SocketAddr;
use std::io::println;
use std::cell::Cell;
use std::{os, str, io, run, uint};
use extra::arc;
use std::comm::*;
use extra::priority_queue::PriorityQueue;
use std::rt::io::net::ip::*;
use std::hashmap::HashMap;
struct sched_msg {
ip:... | println(req_vec.pop().filesize.to_str());
println(req_vec.pop().filesize.to_str());
println(req_vec.pop().filesize.to_str());
}
impl Ord for sched_msg {
fn lt(&self, other: &sched_msg) -> bool {
let selfIP: IpAddr = self.ip;
let otherIP: IpAddr = other.ip;
let selfSize : Option<uint> = self.filesize;
... | {
let mut opt1 : Option<uint> = Some(10u);
let mut opt2 : Option<uint> = Some(3u);
let mut opt3 : Option<uint> = Some(20u);
let mut local: IpAddr = std::rt::io::net::ip::Ipv4Addr(128, 143, -1, -1);
let mut local2: IpAddr = std::rt::io::net::ip::Ipv4Addr(137, 54, -1, -1);
let mut other: IpAddr = std::rt::io::net::ip::... | identifier_body |
testPriority.rs | extern mod extra;
use std::rt::io::*;
use std::rt::io::net::ip::SocketAddr;
use std::io::println;
use std::cell::Cell;
use std::{os, str, io, run, uint};
use extra::arc;
use std::comm::*;
use extra::priority_queue::PriorityQueue;
use std::rt::io::net::ip::*;
use std::hashmap::HashMap;
struct sched_msg {
ip: ... | match selfSize{
Some(i) => {
sSize=i;},
None => {return true;}
}
let otherSize : Option<uint> = other.filesize;
let mut oSize: uint = 0;
match otherSize{
Some(k) => {
oSize=k;},
None => {return true;}
}
let mut sIP : bool = false;
let mut oIP : bool = false;
match selfIP {
... | let mut sSize: uint = 0; | random_line_split |
testPriority.rs |
extern mod extra;
use std::rt::io::*;
use std::rt::io::net::ip::SocketAddr;
use std::io::println;
use std::cell::Cell;
use std::{os, str, io, run, uint};
use extra::arc;
use std::comm::*;
use extra::priority_queue::PriorityQueue;
use std::rt::io::net::ip::*;
use std::hashmap::HashMap;
struct sched_msg {
ip:... | ,
None => {return true;}
}
let mut sIP : bool = false;
let mut oIP : bool = false;
match selfIP {
Ipv4Addr(a, b, c, d) => {
if ((a == 128 && b == 143) || (a == 137 && b == 54)){
sIP = true;
}
},
Ipv6Addr(a, b, c, d, e, f, g, h) => {
if ((a == 128 && b == 143) || (a == 137 && b ==... | {
oSize=k;} | conditional_block |
testPriority.rs |
extern mod extra;
use std::rt::io::*;
use std::rt::io::net::ip::SocketAddr;
use std::io::println;
use std::cell::Cell;
use std::{os, str, io, run, uint};
use extra::arc;
use std::comm::*;
use extra::priority_queue::PriorityQueue;
use std::rt::io::net::ip::*;
use std::hashmap::HashMap;
struct | {
ip: IpAddr,
filesize: Option<uint>, //filesize added to store file size
}
fn main() {
let mut opt1 : Option<uint> = Some(10u);
let mut opt2 : Option<uint> = Some(3u);
let mut opt3 : Option<uint> = Some(20u);
let mut local: IpAddr = std::rt::io::net::ip::Ipv4Addr(128, 143, -1, -1);
let mut local2: IpA... | sched_msg | identifier_name |
diagnostic.rs | s) | FileLine(s) => s
}
}
fn is_full_span(&self) -> bool {
match self {
&FullSpan(..) => true,
&FileLine(..) => false,
}
}
}
#[derive(Clone, Copy)]
pub enum ColorConfig {
Auto,
Always,
Never
}
pub trait Emitter {
fn emit(&mut self, cmsp: Opti... | '\t' => s.push('\t'),
_ => s.push(' '),
};
}
}
try!(write!(&mut err.dst, "{}", s));
let mut s = String::from_str("^");
let hi = cm.lookup_char_pos(sp.hi);
if hi.col!= lo.col {
// the ^ already takes ... | random_line_split | |
diagnostic.rs | ) | FileLine(s) => s
}
}
fn is_full_span(&self) -> bool {
match self {
&FullSpan(..) => true,
&FileLine(..) => false,
}
}
}
#[derive(Clone, Copy)]
pub enum ColorConfig {
Auto,
Always,
Never
}
pub trait Emitter {
fn emit(&mut self, cmsp: Optio... | else {
for &line_number in lines.iter() {
if let Some(line) = fm.get_line(line_number) {
try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
| {
if let Some(line) = fm.get_line(lines[0]) {
try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
lines[0] + 1, line));
}
try!(write!(&mut w.dst, "...\n"));
let last_line_number = lines[lines.len() - 1];
if let Some(last_line) = fm.get_line(last_lin... | conditional_block |
diagnostic.rs | ) | FileLine(s) => s
}
}
fn is_full_span(&self) -> bool {
match self {
&FullSpan(..) => true,
&FileLine(..) => false,
}
}
}
#[derive(Clone, Copy)]
pub enum ColorConfig {
Auto,
Always,
Never
}
pub trait Emitter {
fn emit(&mut self, cmsp: Optio... |
pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Error);
self.handler.bump_err_count();
}
pub fn span_warn(&self, sp: Span, msg: &str) {
self.handler.emit(Some((&self.cm, sp)), msg, Warning);
}
p... | {
self.handler.emit(Some((&self.cm, sp)), msg, Error);
self.handler.bump_err_count();
} | identifier_body |
diagnostic.rs | ) | FileLine(s) => s
}
}
fn is_full_span(&self) -> bool {
match self {
&FullSpan(..) => true,
&FileLine(..) => false,
}
}
}
#[derive(Clone, Copy)]
pub enum ColorConfig {
Auto,
Always,
Never
}
pub trait Emitter {
fn emit(&mut self, cmsp: Optio... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
use std::fmt::Display;
match *self {
Bug => "error: internal compiler error".fmt(f),
Fatal | Error => "error".fmt(f),
Warning => "warning".fmt(f),
Note => "note".fmt(f),
Help => "help".fmt(f),
... | fmt | identifier_name |
issue-7013.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 ... | ()
{
let a = A {v: ~B{v: None} as ~Foo:Send};
//~^ ERROR cannot pack type `~B`, which does not fulfill `Send`
let v = Rc::new(RefCell::new(a));
let w = v.clone();
let b = &*v;
let mut b = b.borrow_mut();
b.v.set(w.clone());
}
| main | identifier_name |
issue-7013.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 ... | }
}
struct A
{
v: ~Foo:Send,
}
fn main()
{
let a = A {v: ~B{v: None} as ~Foo:Send};
//~^ ERROR cannot pack type `~B`, which does not fulfill `Send`
let v = Rc::new(RefCell::new(a));
let w = v.clone();
let b = &*v;
let mut b = b.borrow_mut();
b.v.set(w.clone());
} | impl Foo for B
{
fn set(&mut self, v: Rc<RefCell<A>>)
{
self.v = Some(v); | random_line_split |
mind.rs | .intersection(file)
.pincount();
if blue_servants_in_line > 1 {
valuation += 0.5 * f32::from(blue_servants_in_line - 1);
}
}
// servants should aspire to something more in life someday
let orange_subascendants = world.orang... | ) {
let ws = WorldState | identifier_name | |
mind.rs |
.pincount();
valuation -= 1.8 * f32::from(blue_subascendants);
let low_colonelcy = Pinfield(LOW_COLONELCY);
let blue_subsubascendants = world.blue_servants
.intersection(low_colonelcy)
.pincount();
... | // but they do have well-defined behavior. | random_line_split | |
mind.rs | , and a smarter engine might choose more
// dynamically, but half-a-point is OK, I think.
// Wikipedia has examples where a doubled servant is worth anywhere
// from.3 to.75 points.
if orange_servants_in_line > 1 {
valuation -= 0.5 * f32::from(orange_servants_in_line - 1);
... | }
}
}
};
// Note: if sorting by heuristic were sufficiently expensive, it would, on balance, be better
// to do so only at the higher levels of the tree. From some minor empiric testing, though,
// sorting only at depth >= 1 has no performance impact, and at depth >=... | let mut premonitions = world.reckless_lookahead();
let mut optimum = NEG_INFINITY;
let mut optimand = T::blank();
if depth <= 0 || premonitions.is_empty() {
let potential_score = orientation(world.initiative) * score(world);
match quiet {
None => {
return Lodest... | identifier_body |
statistics.rs | use std::cmp;
use crate::sketch_schemes::KmerCount;
pub fn cardinality(sketch: &[KmerCount]) -> Result<u64, &'static str> {
// Other (possibly more accurate) possibilities:
// "hyper log-log" estimate from lowest value?
// multiset distribution applied to total count number?
// "AKMV" approach: http:/... | extra_count: 0,
label: None,
},
];
let hist_data = hist(&sketch);
assert_eq!(hist_data.len(), 1);
assert_eq!(hist_data[0], 3);
let sketch = vec![
KmerCount {
hash: 1,
kmer: vec![],
count: 4,
extra_count: 0,
... | {
let sketch = vec![
KmerCount {
hash: 1,
kmer: vec![],
count: 1,
extra_count: 0,
label: None,
},
KmerCount {
hash: 2,
kmer: vec![],
count: 1,
extra_count: 0,
label: None,
... | identifier_body |
statistics.rs | use std::cmp;
use crate::sketch_schemes::KmerCount;
pub fn cardinality(sketch: &[KmerCount]) -> Result<u64, &'static str> {
// Other (possibly more accurate) possibilities:
// "hyper log-log" estimate from lowest value?
// multiset distribution applied to total count number?
// "AKMV" approach: http:/... | extra_count: 0,
label: None,
},
KmerCount {
hash: 3,
kmer: vec![],
count: 1,
extra_count: 0,
label: None,
},
];
let hist_data = hist(&sketch);
assert_eq!(hist_data.len(), 1);
assert_eq!(hist_data... | random_line_split | |
statistics.rs | use std::cmp;
use crate::sketch_schemes::KmerCount;
pub fn cardinality(sketch: &[KmerCount]) -> Result<u64, &'static str> {
// Other (possibly more accurate) possibilities:
// "hyper log-log" estimate from lowest value?
// multiset distribution applied to total count number?
// "AKMV" approach: http:/... | (sketch: &[KmerCount]) -> Vec<u64> {
let mut counts = vec![0u64; 65536];
let mut max_count: u64 = 0;
for kmer in sketch {
max_count = cmp::max(max_count, u64::from(kmer.count));
counts[kmer.count as usize - 1] += 1;
}
counts.truncate(max_count as usize);
counts
}
#[test]
fn test... | hist | identifier_name |
statistics.rs | use std::cmp;
use crate::sketch_schemes::KmerCount;
pub fn cardinality(sketch: &[KmerCount]) -> Result<u64, &'static str> {
// Other (possibly more accurate) possibilities:
// "hyper log-log" estimate from lowest value?
// multiset distribution applied to total count number?
// "AKMV" approach: http:/... |
Ok(((sketch.len() - 1) as f32
/ (sketch.last().unwrap().hash as f32 / usize::max_value() as f32)) as u64)
}
/// Generates a Vec of numbers of kmers for each coverage level
///
/// For example, a size 1000 sketch of the same genome repeated 5 times (e.g. 5x coverage) should
/// produce a "histogram" like [... | {
return Ok(0u64);
} | conditional_block |
main.rs | #[macro_use]
extern crate clap;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate chrono;
extern crate responder;
use std::env::{self, VarError};
use std::io::{self, Write};
use std::net::SocketAddr;
use std::path::Path;
use std::process;
use clap::{App, Arg, Format};
use log::{LogRecord, LogLeve... | (arg: String) -> Result<(), String> {
arg.parse::<SocketAddr>()
.map(|_| ())
.map_err(|_| String::from("invalid adrress"))
}
fn run_server(address: Option<&str>, config_file: &Path, reload: bool)
-> Result<(), String>
{
let context = try!(Context::from_config_file(config_file, reload));
... | address_validator | identifier_name |
main.rs | #[macro_use]
extern crate clap;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate chrono;
extern crate responder;
use std::env::{self, VarError};
use std::io::{self, Write};
use std::net::SocketAddr;
use std::path::Path;
use std::process;
use clap::{App, Arg, Format};
use log::{LogRecord, LogLeve... | else {
None
};
let config = matches.value_of("config").map(|c| Path::new(c)).unwrap();
let reload = matches.is_present("reload");
match run_server(address, config, reload) {
Ok(_) => {}
Err(e) => {
write!(io::stderr(), "{} {}\n", Format::Error("error:"), e)
... | {
matches.value_of("bind")
} | conditional_block |
main.rs | #[macro_use]
extern crate clap;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate chrono;
extern crate responder;
use std::env::{self, VarError};
use std::io::{self, Write};
use std::net::SocketAddr;
use std::path::Path;
use std::process;
use clap::{App, Arg, Format};
use log::{LogRecord, LogLeve... |
fn run_server(address: Option<&str>, config_file: &Path, reload: bool)
-> Result<(), String>
{
let context = try!(Context::from_config_file(config_file, reload));
let address = address.or(Some(context.address()))
.unwrap_or(DEFAULT_ADDR)
.to_owned();
info!("Starting http server at http... | {
arg.parse::<SocketAddr>()
.map(|_| ())
.map_err(|_| String::from("invalid adrress"))
} | identifier_body |
main.rs | #[macro_use]
extern crate clap;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate chrono;
extern crate responder;
use std::env::{self, VarError};
use std::io::{self, Write};
use std::net::SocketAddr;
use std::path::Path;
use std::process;
use clap::{App, Arg, Format};
use log::{LogRecord, LogLeve... | -> Result<(), String>
{
let context = try!(Context::from_config_file(config_file, reload));
let address = address.or(Some(context.address()))
.unwrap_or(DEFAULT_ADDR)
.to_owned();
info!("Starting http server at http://{}/", &address);
try!(server::run(context, &address));
Ok(())... | }
fn run_server(address: Option<&str>, config_file: &Path, reload: bool) | random_line_split |
variance-types.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> { //~ ERROR [o]
t: InvariantCell<A>
}
#[rustc_variance]
struct Covariant<A> { //~ ERROR [+]
t: A, u: fn() -> A
}
#[rustc_variance]
struct Contravariant<A> { //~ ERROR [-]
t: fn(A)
}
#[rustc_variance]
enum Enum<A,B,C> { //~ ERROR [+, -, o]
Foo(Covariant<A>),
Bar(Contravariant<B>),
Zed(Cova... | InvariantIndirect | identifier_name |
variance-types.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(dead_code)... | // | random_line_split |
popstateevent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::PopStateEv... | {
event: Event,
#[ignore_heap_size_of = "Defined in rust-mozjs"]
state: MutHeapJSVal,
}
impl PopStateEvent {
fn new_inherited() -> PopStateEvent {
PopStateEvent {
event: Event::new_inherited(),
state: MutHeapJSVal::new(),
}
}
pub fn new_uninitialized(wi... | PopStateEvent | identifier_name |
popstateevent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::PopStateEv... |
}
impl PopStateEventMethods for PopStateEvent {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-popstateevent-state
unsafe fn State(&self, _cx: *mut JSContext) -> JSVal {
self.state.get()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) ->... | {
Ok(PopStateEvent::new(window,
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
unsafe { HandleValue::from_marked_location(&init.state) }))
} | identifier_body |
popstateevent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::PopStateEv... |
pub fn new_uninitialized(window: &Window) -> Root<PopStateEvent> {
reflect_dom_object(box PopStateEvent::new_inherited(),
window,
PopStateEventBinding::Wrap)
}
pub fn new(window: &Window,
type_: Atom,
bubbles: bool... | state: MutHeapJSVal::new(),
}
} | random_line_split |
issue-2631-a.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 ... | <T>(req: &header_map) {
let _x = (**((**req.get(&"METHOD".to_strbuf())).clone()).borrow()
.clone()
.get(0)).clone();
}
| request | identifier_name |
issue-2631-a.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 ... | .clone()
.get(0)).clone();
} | let _x = (**((**req.get(&"METHOD".to_strbuf())).clone()).borrow() | random_line_split |
issue-2631-a.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 _x = (**((**req.get(&"METHOD".to_strbuf())).clone()).borrow()
.clone()
.get(0)).clone();
} | identifier_body | |
dir_reg.rs | use std::io::{self, Read, Write};
use std::fmt;
use instruction::parameter::{Direct, Register, RegisterError, InvalidRegister};
use instruction::parameter::{ParamType, ParamTypeOf};
use instruction::parameter::InvalidParamType;
use instruction::mem_size::MemSize;
use instruction::write_to::WriteTo;
use instruction::get... | DirReg::Register(_) => ParamType::Register,
}
}
}
impl WriteTo for DirReg {
fn write_to<W: Write>(&self, writer: &mut W) -> io::Result<()> {
match *self {
DirReg::Direct(direct) => direct.write_to(writer),
DirReg::Register(register) => register.write_to(write... | impl ParamTypeOf for DirReg {
fn param_type(&self) -> ParamType {
match *self {
DirReg::Direct(_) => ParamType::Direct, | random_line_split |
dir_reg.rs | use std::io::{self, Read, Write};
use std::fmt;
use instruction::parameter::{Direct, Register, RegisterError, InvalidRegister};
use instruction::parameter::{ParamType, ParamTypeOf};
use instruction::parameter::InvalidParamType;
use instruction::mem_size::MemSize;
use instruction::write_to::WriteTo;
use instruction::get... | (&self) -> ParamType {
match *self {
DirReg::Direct(_) => ParamType::Direct,
DirReg::Register(_) => ParamType::Register,
}
}
}
impl WriteTo for DirReg {
fn write_to<W: Write>(&self, writer: &mut W) -> io::Result<()> {
match *self {
DirReg::Direct(dire... | param_type | identifier_name |
mod.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
|
// Modules --------------------------------------------------------------------
pub mod alias;
pub mod ban;
//pub mod debug;
pub mod effect;
pub mod greeting;
pub mod message;
pub mod recording;
pub mod server;
pub mod uploader;
pub mod timed;
pub mod twitch;
// Re-Exports ------------------------------------------... |
// Internal Dependencies ------------------------------------------------------
use ::core::EventQueue;
use ::bot::{Bot, BotConfig}; | random_line_split |
mod.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Internal Dependencies ------------------------------------------------------
use ::core::EventQueue;
use ::bot::{Bot, BotConfig};
// Modules --------------------------------------------------------------------
pub mod a... | (&self) -> bool {
true
}
fn run(&mut self, &mut Bot, &BotConfig, &mut EventQueue) -> ActionGroup;
}
| ready | identifier_name |
mod.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Internal Dependencies ------------------------------------------------------
use ::core::EventQueue;
use ::bot::{Bot, BotConfig};
// Modules --------------------------------------------------------------------
pub mod a... |
fn run(&mut self, &mut Bot, &BotConfig, &mut EventQueue) -> ActionGroup;
}
| {
true
} | identifier_body |
borrowingmutsource0.rs | #[allow(dead_code)]
#[derive(Clone, Copy)]
struct Book {
// `&'static str` est une référence d'une chaîne de caractères allouée
// dans un bloc mémoire qui ne peut être accédé qu'en lecture.
author: &'static str,
title: &'static str,
year: u32,
}
// Cette fonction prend une référence d'une instanc... | let mut mutabook = immutabook;
// Emprunte un objet en lecture seule.
borrow_book(&immutabook);
// Emprunte un objet en lecture seule.
borrow_book(&mutabook);
// Récupère une référence mutable d'un objet mutable.
new_edition(&mut mutabook);
// Erreur! Vous ne pouvez pas récupérer une... | random_line_split | |
borrowingmutsource0.rs | #[allow(dead_code)]
#[derive(Clone, Copy)]
struct Book {
// `&'static str` est une référence d'une chaîne de caractères allouée
// dans un bloc mémoire qui ne peut être accédé qu'en lecture.
author: &'static str,
title: &'static str,
year: u32,
}
// Cette fonction prend une référence d'une instanc... | ) {
println!("I immutably borrowed {} - {} edition", book.title, book.year);
}
// Cette fonction prend une référence mutable d'une instance de la
// structure `Book` en paramètre, et initialise sa date de publication
// à 2014.
fn new_edition(book: &mut Book) {
book.year = 2014;
println!("I mutably borro... | book: &Book | identifier_name |
functions4.rs | // Make me compile! Scroll down for hints :)
// This store is having a sale where if the price is an even number, you get
// 10 (money unit) off, but if it's an odd number, it's 3 (money unit) less.
fn main() |
fn sale_price(price: i32) -> i32 {
if is_even(price) {
price - 10
} else {
price - 3
}
}
fn is_even(num: i32) -> bool {
num % 2 == 0
}
// The error message points to line 10 and says it expects a type after the
// `->`. This is where the function's return type shoul... | {
let original_price: i32 = 51;
println!("Your sale price is {}", sale_price(original_price));
} | identifier_body |
functions4.rs | // Make me compile! Scroll down for hints :)
// This store is having a sale where if the price is an even number, you get
// 10 (money unit) off, but if it's an odd number, it's 3 (money unit) less.
fn main() {
let original_price: i32 = 51;
println!("Your sale price is {}", sale_price(original_price));
}
fn ... | else {
price - 3
}
}
fn is_even(num: i32) -> bool {
num % 2 == 0
}
// The error message points to line 10 and says it expects a type after the
// `->`. This is where the function's return type should be-- take a look at
// the `is_even` function for an example!
| {
price - 10
} | conditional_block |
functions4.rs | // Make me compile! Scroll down for hints :)
// This store is having a sale where if the price is an even number, you get
// 10 (money unit) off, but if it's an odd number, it's 3 (money unit) less.
fn main() {
let original_price: i32 = 51;
println!("Your sale price is {}", sale_price(original_price));
}
fn ... | // The error message points to line 10 and says it expects a type after the
// `->`. This is where the function's return type should be-- take a look at
// the `is_even` function for an example! | random_line_split | |
functions4.rs | // Make me compile! Scroll down for hints :)
// This store is having a sale where if the price is an even number, you get
// 10 (money unit) off, but if it's an odd number, it's 3 (money unit) less.
fn | () {
let original_price: i32 = 51;
println!("Your sale price is {}", sale_price(original_price));
}
fn sale_price(price: i32) -> i32 {
if is_even(price) {
price - 10
} else {
price - 3
}
}
fn is_even(num: i32) -> bool {
num % 2 == 0
}
// The error message poi... | main | identifier_name |
mime.rs | use std::io::{Write, BufRead, BufReader};
use std::fs::File;
use std::collections::HashMap;
use std::borrow::Cow;
macro_rules! or_continue {
($e: expr) => (if let Some(v) = $e {
v
} else {
continue;
})
}
pub fn gen() | let top: Cow<_> = match or_continue!(mime_type.next()) {
"*" => "MaybeKnown::Known(::mime::TopLevel::Star)".into(),
"text" => "MaybeKnown::Known(::mime::TopLevel::Text)".into(),
"image" => "MaybeKnown::Known(::mime::TopLevel::Image)".into(),
"audio" => "MaybeKnown... | {
let input = File::open("build/apache/mime.types").unwrap_or_else(|e| {
panic!("could not open 'build/apache/mime.types': {}", e);
});
let out_path = format!("{}/mime.rs", env!("OUT_DIR"));
let mut output = File::create(&out_path).unwrap_or_else(|e| {
panic!("could not create '{}': {}"... | identifier_body |
mime.rs | use std::io::{Write, BufRead, BufReader};
use std::fs::File;
use std::collections::HashMap;
use std::borrow::Cow;
macro_rules! or_continue {
($e: expr) => (if let Some(v) = $e {
v
} else {
continue;
})
}
pub fn | () {
let input = File::open("build/apache/mime.types").unwrap_or_else(|e| {
panic!("could not open 'build/apache/mime.types': {}", e);
});
let out_path = format!("{}/mime.rs", env!("OUT_DIR"));
let mut output = File::create(&out_path).unwrap_or_else(|e| {
panic!("could not create '{}': ... | gen | identifier_name |
mime.rs | use std::io::{Write, BufRead, BufReader};
use std::fs::File;
use std::collections::HashMap;
use std::borrow::Cow;
macro_rules! or_continue {
($e: expr) => (if let Some(v) = $e {
v
} else {
continue;
})
}
pub fn gen() {
let input = File::open("build/apache/mime.types").unwrap_or_else(|e... | panic!("could not create '{}': {}", out_path, e);
});
let mut types = HashMap::new();
for line in BufReader::new(input).lines().filter_map(Result::ok) {
if let Some('#') = line.chars().next() {
continue;
}
let mut parts = line.split('\t').filter(|v| v.len() > 0... | let out_path = format!("{}/mime.rs", env!("OUT_DIR"));
let mut output = File::create(&out_path).unwrap_or_else(|e| { | random_line_split |
cleanup.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/.
// Code to handle cleanup after a failed operation.
use crate::stratis::{ErrorEnum, StratisError, StratisResult};
u... | else {
let err_msg = format!(
"Failed to teardown already set up pools: {:?}",
untorndown_pools
);
Err(StratisError::Engine(ErrorEnum::Error, err_msg))
}
}
| {
Ok(())
} | conditional_block |
cleanup.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/.
// Code to handle cleanup after a failed operation.
use crate::stratis::{ErrorEnum, StratisError, StratisResult};
u... | (pools: Table<StratPool>) -> StratisResult<()> {
let mut untorndown_pools = Vec::new();
for (_, uuid, mut pool) in pools {
pool.teardown()
.unwrap_or_else(|_| untorndown_pools.push(uuid));
}
if untorndown_pools.is_empty() {
Ok(())
} else {
let err_msg = format!(
... | teardown_pools | identifier_name |
cleanup.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/.
// Code to handle cleanup after a failed operation.
use crate::stratis::{ErrorEnum, StratisError, StratisResult};
u... | );
Err(StratisError::Engine(ErrorEnum::Error, err_msg))
}
} | random_line_split | |
cleanup.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/.
// Code to handle cleanup after a failed operation.
use crate::stratis::{ErrorEnum, StratisError, StratisResult};
u... | {
let mut untorndown_pools = Vec::new();
for (_, uuid, mut pool) in pools {
pool.teardown()
.unwrap_or_else(|_| untorndown_pools.push(uuid));
}
if untorndown_pools.is_empty() {
Ok(())
} else {
let err_msg = format!(
"Failed to teardown already set up p... | identifier_body | |
spi_master.rs | //! Traits and parameters for SPI master communication.
use core::option::Option;
/// Values for the ordering of bits
#[derive(Copy, Clone)]
pub enum DataOrder {MSBFirst, LSBFirst}
/// Values for the clock polarity (idle state or CPOL)
#[derive(Copy, Clone)]
pub enum ClockPolarity {IdleHigh, IdleLow}
/// Which cloc... | {SampleLeading, SampleTrailing}
pub trait SpiCallback {
/// Called when a read/write operation finishes
fn read_write_done(&'static self);
}
/// The `SpiMaster` trait for interacting with SPI slave
/// devices at a byte or buffer level.
///
/// Using SpiMaster normally involves three steps:
///
/// 1. Configu... | ClockPhase | identifier_name |
spi_master.rs | //! Traits and parameters for SPI master communication.
use core::option::Option;
/// Values for the ordering of bits
#[derive(Copy, Clone)]
pub enum DataOrder {MSBFirst, LSBFirst}
/// Values for the clock polarity (idle state or CPOL)
#[derive(Copy, Clone)]
pub enum ClockPolarity {IdleHigh, IdleLow}
/// Which cloc... | /// Returns whether this chip select is valid and was
/// applied, 0 is always valid.
fn set_chip_select(&self, cs: u8) -> bool;
fn clear_chip_select(&self);
/// Returns the actual rate set
fn set_rate(&self, rate: u32) -> u32;
fn set_clock(&self, polarity: ClockPolarity);
fn set_phase(&... | random_line_split | |
main.rs | extern crate term_size;
extern crate getch;
extern crate doh;
use getch::Getch;
use std::process::exit;
use std::io::{Write, stdout, stderr};
fn main() {
let ec = handler_main();
exit(ec);
}
fn handler_main() -> i32 {
if let Err((msg, errc)) = real_main() {
let _ = writeln!(stderr(), "{}", msg);... |
}
fn real_main() -> Result<(), (String, i32)> {
let opts = doh::Options::parse();
let termsize = try!(term_size::dimensions().ok_or_else(|| ("Unknown terminal dimensions.".to_string(), 1)));
let _cursor = doh::util::RaiiGuard::new(|| print!("{}", doh::ops::term::show_cursor(false)),
... | {
0
} | conditional_block |
main.rs | extern crate term_size;
extern crate getch;
extern crate doh;
use getch::Getch;
use std::process::exit;
use std::io::{Write, stdout, stderr};
fn main() |
fn handler_main() -> i32 {
if let Err((msg, errc)) = real_main() {
let _ = writeln!(stderr(), "{}", msg);
errc
} else {
0
}
}
fn real_main() -> Result<(), (String, i32)> {
let opts = doh::Options::parse();
let termsize = try!(term_size::dimensions().ok_or_else(|| ("Unknown... | {
let ec = handler_main();
exit(ec);
} | identifier_body |
main.rs | extern crate term_size;
extern crate getch;
extern crate doh;
use getch::Getch;
use std::process::exit;
use std::io::{Write, stdout, stderr};
fn main() {
let ec = handler_main();
exit(ec); | if let Err((msg, errc)) = real_main() {
let _ = writeln!(stderr(), "{}", msg);
errc
} else {
0
}
}
fn real_main() -> Result<(), (String, i32)> {
let opts = doh::Options::parse();
let termsize = try!(term_size::dimensions().ok_or_else(|| ("Unknown terminal dimensions.".to_str... | }
fn handler_main() -> i32 { | random_line_split |
main.rs | extern crate term_size;
extern crate getch;
extern crate doh;
use getch::Getch;
use std::process::exit;
use std::io::{Write, stdout, stderr};
fn main() {
let ec = handler_main();
exit(ec);
}
fn | () -> i32 {
if let Err((msg, errc)) = real_main() {
let _ = writeln!(stderr(), "{}", msg);
errc
} else {
0
}
}
fn real_main() -> Result<(), (String, i32)> {
let opts = doh::Options::parse();
let termsize = try!(term_size::dimensions().ok_or_else(|| ("Unknown terminal dimensi... | handler_main | identifier_name |
rfc2045.rs | //! Module for dealing with RFC2045 style headers.
use super::rfc5322::Rfc5322Parser;
use std::collections::HashMap;
/// Parser over RFC 2045 style headers.
///
/// Things of the style `value; param1=foo; param2="bar"`
pub struct Rfc2045Parser<'s> {
parser: Rfc5322Parser<'s>,
}
impl<'s> Rfc2045Parser<'s> {
/... | () {
let tests = vec![
ParserTestCase {
input: "foo/bar",
output: ("foo/bar", vec![]),
name: "Basic value",
},
ParserTestCase {
input: "foo/bar; foo=bar",
output: ("foo/bar", vec![
... | test_foo | identifier_name |
rfc2045.rs | //! Module for dealing with RFC2045 style headers.
use super::rfc5322::Rfc5322Parser;
use std::collections::HashMap;
/// Parser over RFC 2045 style headers.
///
/// Things of the style `value; param1=foo; param2="bar"`
pub struct Rfc2045Parser<'s> {
parser: Rfc5322Parser<'s>,
}
impl<'s> Rfc2045Parser<'s> {
/... | (Some(attrib), Some(val)) => {
params.insert(attrib, val);
},
_ => {}
}
}
(value, params)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
struct ParserTestCase<'s> {
inpu... | self.consume_token()
};
match (attribute, value) { | random_line_split |
rfc2045.rs | //! Module for dealing with RFC2045 style headers.
use super::rfc5322::Rfc5322Parser;
use std::collections::HashMap;
/// Parser over RFC 2045 style headers.
///
/// Things of the style `value; param1=foo; param2="bar"`
pub struct Rfc2045Parser<'s> {
parser: Rfc5322Parser<'s>,
}
impl<'s> Rfc2045Parser<'s> {
/... | ,
_ => {}
}
}
(value, params)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
struct ParserTestCase<'s> {
input: &'s str,
output: (&'s str, Vec<(&'s str, &'s str)>),
name: &'s str,
}
#[test]
pu... | {
params.insert(attrib, val);
} | conditional_block |
server.rs | //! A low-level interface to send and receive server-client protocol messages
use std;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{Sender, Receiver, TryRecvError};
use std::sync::atomic::{Ordering, AtomicUsize};
use bincode;
use common::protocol;
use common::socket::{SendSocket, ReceiveSocket};
#[allow(miss... |
impl SSender {
#[allow(missing_docs)]
pub fn new(sender: Sender<Box<[u8]>>) -> SSender {
SSender {
sender: sender,
bytes_sent: Arc::new(AtomicUsize::new(0)),
}
}
#[allow(missing_docs)]
pub fn tell(&self, msg: &protocol::ClientToServer) {
let msg = bincode::serialize(msg, bincode::Inf... | // A boxed slice is used to reduce the sent size
pub sender: Sender<Box<[u8]>>,
// Please replace with AtomicU64 when it becomes stable
pub bytes_sent: Arc<AtomicUsize>,
} | random_line_split |
server.rs | //! A low-level interface to send and receive server-client protocol messages
use std;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{Sender, Receiver, TryRecvError};
use std::sync::atomic::{Ordering, AtomicUsize};
use bincode;
use common::protocol;
use common::socket::{SendSocket, ReceiveSocket};
#[allow(miss... | {
pub talk : SSender,
pub listen : SReceiver,
}
#[allow(missing_docs)]
pub fn new(
server_url: &str,
listen_url: &str,
) -> T {
let (send_send, send_recv) = std::sync::mpsc::channel();
let (recv_send, recv_recv) = std::sync::mpsc::channel();
let _recv_thread ={
let listen_url = listen_url.to_owne... | T | identifier_name |
server.rs | //! A low-level interface to send and receive server-client protocol messages
use std;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{Sender, Receiver, TryRecvError};
use std::sync::atomic::{Ordering, AtomicUsize};
use bincode;
use common::protocol;
use common::socket::{SendSocket, ReceiveSocket};
#[allow(miss... |
#[allow(missing_docs)]
pub fn wait(&self) -> protocol::ServerToClient {
let msg = self.0.lock().unwrap().recv().unwrap();
bincode::deserialize(msg.as_ref()).unwrap()
}
}
#[allow(missing_docs)]
#[derive(Clone)]
pub struct T {
pub talk : SSender,
pub listen : SReceiver,
}
#[allow(missing_docs)]
pu... | {
match self.0.lock().unwrap().try_recv() {
Ok(msg) => Some(bincode::deserialize(&Vec::from(msg)).unwrap()),
Err(TryRecvError::Empty) => None,
e => {
e.unwrap();
unreachable!();
},
}
} | identifier_body |
definition.rs | use iron::mime::Mime;
use iron::prelude::*;
use iron::status;
use serde_json::to_string;
use super::EngineProvider;
use crate::engine::{Buffer, Context, CursorPosition, Definition};
/// Given a location, return where the identifier is defined
///
/// Possible responses include
///
/// - `200 OK` the request was succ... | struct FindDefinitionResponse {
pub file_path: String,
pub column: usize,
pub line: usize,
pub text: String,
pub context: String,
pub kind: String,
pub docs: String,
} | }
#[derive(Debug, Deserialize, Serialize)] | random_line_split |
definition.rs | use iron::mime::Mime;
use iron::prelude::*;
use iron::status;
use serde_json::to_string;
use super::EngineProvider;
use crate::engine::{Buffer, Context, CursorPosition, Definition};
/// Given a location, return where the identifier is defined
///
/// Possible responses include
///
/// - `200 OK` the request was succ... | () {
let s = stringify!({
"file_path": "src.rs",
"buffers": [{
"file_path": "src.rs",
"contents": "fn foo() {}\nfn bar() {}\nfn main() {\nfoo();\n}"
}],
"line": 4,
"column": 3
});
let req: FindDefinitionRequest = serde_json::from_str(s).unwrap... | find_definition_request_from_json | identifier_name |
definition.rs | use iron::mime::Mime;
use iron::prelude::*;
use iron::status;
use serde_json::to_string;
use super::EngineProvider;
use crate::engine::{Buffer, Context, CursorPosition, Definition};
/// Given a location, return where the identifier is defined
///
/// Possible responses include
///
/// - `200 OK` the request was succ... | match engine.find_definition(&fdr.context()) {
// 200 OK; found the definition
Ok(Some(definition)) => {
trace!("definition::find got a match");
let res = FindDefinitionResponse::from(definition);
let content_type = "application/json".parse::<Mime>().unwrap();
... | {
// Parse the request. If the request doesn't parse properly, the request is invalid, and a 400
// BadRequest is returned.
let fdr = match req.get::<::bodyparser::Struct<FindDefinitionRequest>>() {
Ok(Some(s)) => {
trace!("definition::find parsed FindDefinitionRequest");
s
... | identifier_body |
util.rs | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unl... | () -> Result<PackageIdent> {
Ok(PackageIdent::from_str(BUSYBOX_IDENT)?)
}
/// Returns the path to a package prefix for the provided Package Identifier in a root file system.
///
/// # Errors
///
/// * If a package cannot be loaded from in the root file system
pub fn pkg_path_for<P: AsRef<Path>>(ident: &PackageIden... | busybox_ident | identifier_name |
util.rs | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unl... |
/// Returns the path to a package prefix for the provided Package Identifier in a root file system.
///
/// # Errors
///
/// * If a package cannot be loaded from in the root file system
pub fn pkg_path_for<P: AsRef<Path>>(ident: &PackageIdent, rootfs: P) -> Result<PathBuf> {
let pkg_install = PackageInstall::load... | {
Ok(PackageIdent::from_str(BUSYBOX_IDENT)?)
} | identifier_body |
util.rs | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unl... | Path::new("/").join(
pkg_install
.installed_path()
.strip_prefix(rootfs.as_ref())
.expect("installed path contains rootfs path"),
),
)
}
/// Writes a truncated/new file at the provided path with the provided content.
///
/// # Errors
///
/// ... | let pkg_install = PackageInstall::load(ident, Some(rootfs.as_ref()))?;
Ok( | random_line_split |
proteins.rs | extern crate protein_translation as proteins;
#[test]
fn test_methionine() {
let info = proteins::parse(make_pairs());
assert_eq!(info.name_for("ATG"), Ok("methionine"));
}
#[test]
fn test_cysteine_tgt() {
let info = proteins::parse(make_pairs());
assert_eq!(info.name_for("TGT"), Ok("cysteine"));
}
#... | () -> Vec<(&'static str, &'static str)> {
let grouped = vec![
("isoleucine", vec!["ATT", "ATC", "ATA"]),
("leucine", vec!["CTT", "CTC", "CTA", "CTG", "TTA", "TTG"]),
("valine", vec!["GTT", "GTC", "GTA", "GTG"]),
("phenylalanine", vec!["TTT", "TTC"]),
("methionine", vec!["ATG"... | make_pairs | identifier_name |
proteins.rs | extern crate protein_translation as proteins;
#[test]
fn test_methionine() {
let info = proteins::parse(make_pairs());
assert_eq!(info.name_for("ATG"), Ok("methionine"));
}
#[test]
fn test_cysteine_tgt() {
let info = proteins::parse(make_pairs());
assert_eq!(info.name_for("TGT"), Ok("cysteine"));
}
#... | assert!(info.name_for("").is_err());
}
#[test]
fn x_is_not_shorthand_so_is_invalid() {
let info = proteins::parse(make_pairs());
assert!(info.name_for("VWX").is_err());
}
#[test]
fn too_short_is_invalid() {
let info = proteins::parse(make_pairs());
assert!(info.name_for("AT").is_err());
}
#[test]... | random_line_split | |
proteins.rs | extern crate protein_translation as proteins;
#[test]
fn test_methionine() {
let info = proteins::parse(make_pairs());
assert_eq!(info.name_for("ATG"), Ok("methionine"));
}
#[test]
fn test_cysteine_tgt() {
let info = proteins::parse(make_pairs());
assert_eq!(info.name_for("TGT"), Ok("cysteine"));
}
#... |
#[test]
fn test_stop() {
let info = proteins::parse(make_pairs());
assert_eq!(info.name_for("TAA"), Ok("stop codon"));
}
#[test]
fn test_valine() {
let info = proteins::parse(make_pairs());
assert_eq!(info.name_for("GTN"), Ok("valine"));
}
#[test]
fn test_isoleucine() {
let info = proteins::par... | { // "compressed" name for TGT and TGC
let info = proteins::parse(make_pairs());
assert_eq!(info.name_for("TGT"), info.name_for("TGY"));
assert_eq!(info.name_for("TGC"), info.name_for("TGY"));
} | identifier_body |
iced_error.rs | // SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
use alloc::borrow::Cow;
use alloc::string::String;
use core::fmt;
#[cfg(feature = "std")]
use std::error::Error;
/// iced error
#[derive(Debug, Clone)]
pub struct IcedError {
error: Cow<'static, str>,
}
impl IcedError {
... | #[allow(clippy::missing_inline_in_public_items)]
fn description(&self) -> &str {
&self.error
}
}
impl fmt::Display for IcedError {
#[allow(clippy::missing_inline_in_public_items)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", &self.error)
}
} |
#[cfg(feature = "std")]
impl Error for IcedError {
// Required since MSRV < 1.42.0 | random_line_split |
iced_error.rs | // SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
use alloc::borrow::Cow;
use alloc::string::String;
use core::fmt;
#[cfg(feature = "std")]
use std::error::Error;
/// iced error
#[derive(Debug, Clone)]
pub struct IcedError {
error: Cow<'static, str>,
}
impl IcedError {
... | (&self) -> &str {
&self.error
}
}
impl fmt::Display for IcedError {
#[allow(clippy::missing_inline_in_public_items)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", &self.error)
}
}
| description | identifier_name |
iced_error.rs | // SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
use alloc::borrow::Cow;
use alloc::string::String;
use core::fmt;
#[cfg(feature = "std")]
use std::error::Error;
/// iced error
#[derive(Debug, Clone)]
pub struct IcedError {
error: Cow<'static, str>,
}
impl IcedError {
... |
}
| {
write!(f, "{}", &self.error)
} | identifier_body |
ko.rs | /************************************************************************
* *
* Copyright 2014 Urban Hafner, Thomas Poinsot *
* Copyright 2015 Urban Hafner, Igor Polyakov *
* ... | let mut g = Game::new(19, 6.5, AnySizeTrompTaylor);
g = g.play(Play(Black, 4, 4)).unwrap();
g = g.play(Play(White, 5, 4)).unwrap();
g = g.play(Play(Black, 3, 3)).unwrap();
g = g.play(Play(White, 4, 3)).unwrap();
g = g.play(Play(Black, 3, 5)).unwrap();
g = g.play(Play(White, 4, 5)).unwrap();
... | g_directly_on_a_ko_point_should_be_illegal() {
| identifier_name |
ko.rs | /************************************************************************
* *
* Copyright 2014 Urban Hafner, Thomas Poinsot *
* Copyright 2015 Urban Hafner, Igor Polyakov *
* ... | ]
fn positional_super_ko_should_be_illegal() {
let parser = Parser::from_path(Path::new("fixtures/sgf/positional-superko.sgf")).unwrap();
let game = parser.game().unwrap();
let super_ko = game.play(Play(White, 2, 9));
match super_ko {
Err(e) => assert_eq!(e, IllegalMove::SuperKo),
Ok(_... | t mut g = Game::new(19, 6.5, AnySizeTrompTaylor);
g = g.play(Play(Black, 4, 4)).unwrap();
g = g.play(Play(White, 5, 4)).unwrap();
g = g.play(Play(Black, 3, 3)).unwrap();
g = g.play(Play(White, 4, 3)).unwrap();
g = g.play(Play(Black, 3, 5)).unwrap();
g = g.play(Play(White, 4, 5)).unwrap();
g... | identifier_body |
ko.rs | /************************************************************************
* *
* Copyright 2014 Urban Hafner, Thomas Poinsot *
* Copyright 2015 Urban Hafner, Igor Polyakov *
* ... | g = g.play(Play(White, 5, 4)).unwrap();
g = g.play(Play(Black, 3, 3)).unwrap();
g = g.play(Play(White, 4, 3)).unwrap();
g = g.play(Play(Black, 3, 5)).unwrap();
g = g.play(Play(White, 4, 5)).unwrap();
g = g.play(Play(Black, 2, 4)).unwrap();
g = g.play(Play(White, 3, 4)).unwrap();
let ko ... | g = g.play(Play(Black, 4, 4)).unwrap(); | random_line_split |
htmloptionelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::CharacterDataBinding::Chara... |
fn after_set_attr(&self, attr: JSRef<Attr>) {
match self.super_type() {
Some(ref s) => s.after_set_attr(attr),
_ => ()
}
match attr.local_name() {
&atom!("disabled") => {
let node: JSRef<Node> = NodeCast::from_ref(*self);
... | {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
} | identifier_body |
htmloptionelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::CharacterDataBinding::Chara... | (node: &JSRef<Node>, value: &mut DOMString) {
let elem: JSRef<Element> = ElementCast::to_ref(*node).unwrap();
let svg_script = *elem.namespace() == ns!(SVG) && elem.local_name().as_slice() == "script";
let html_script = node.is_htmlscriptelement();
if svg_script || html_script {
return;
} el... | collect_text | identifier_name |
htmloptionelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::CharacterDataBinding::Chara... | let svg_script = *elem.namespace() == ns!(SVG) && elem.local_name().as_slice() == "script";
let html_script = node.is_htmlscriptelement();
if svg_script || html_script {
return;
} else {
for child in node.children() {
if child.is_text() {
let characterdata: JS... | fn collect_text(node: &JSRef<Node>, value: &mut DOMString) {
let elem: JSRef<Element> = ElementCast::to_ref(*node).unwrap(); | random_line_split |
ops.rs | //! Image operations for textures.
/// Flips the image vertically.
pub fn flip_vertical(memory: &[u8], size: [u32; 2], channels: u8) -> Vec<u8> {
let (width, height, channels) = (size[0] as usize, size[1] as usize,
channels as usize);
let mut res = vec![0; width * height];
let stride = width * chan... | (memory: &[u8], size: [u32; 2]) -> Vec<u8> {
let (width, height) = (size[0] as usize, size[1] as usize);
let capacity = width * height * 4;
let stride = width;
let mut res = Vec::with_capacity(capacity);
for y in 0..height {
for x in 0..width {
res.push(255);
res.push... | alpha_to_rgba8 | identifier_name |
ops.rs | //! Image operations for textures.
/// Flips the image vertically.
pub fn flip_vertical(memory: &[u8], size: [u32; 2], channels: u8) -> Vec<u8> {
let (width, height, channels) = (size[0] as usize, size[1] as usize,
channels as usize);
let mut res = vec![0; width * height];
let stride = width * chan... | pub fn alpha_to_rgba8(memory: &[u8], size: [u32; 2]) -> Vec<u8> {
let (width, height) = (size[0] as usize, size[1] as usize);
let capacity = width * height * 4;
let stride = width;
let mut res = Vec::with_capacity(capacity);
for y in 0..height {
for x in 0..width {
res.push(255);... | random_line_split | |
ops.rs | //! Image operations for textures.
/// Flips the image vertically.
pub fn flip_vertical(memory: &[u8], size: [u32; 2], channels: u8) -> Vec<u8> {
let (width, height, channels) = (size[0] as usize, size[1] as usize,
channels as usize);
let mut res = vec![0; width * height];
let stride = width * chan... | {
let (width, height) = (size[0] as usize, size[1] as usize);
let capacity = width * height * 4;
let stride = width;
let mut res = Vec::with_capacity(capacity);
for y in 0..height {
for x in 0..width {
res.push(255);
res.push(255);
res.push(255);
... | identifier_body | |
lib.rs | #[macro_use] extern crate matches;
#[macro_use] extern crate log;
/// Simple Rpc Module.
/// See the submodules for information on how to set up a server and a client.
pub mod rpc;
/// Common code between structs.
// TODO: This probably should not all be public
pub mod common;
///
/// Raft Server
///
pub mod server;... | include!(concat!(env!("OUT_DIR"), "/raft_capnp.rs"));
} | random_line_split | |
main.rs | /* Commented to avoid compile errors an failed build badges on TravisCI,
extern crate orbclient;
extern crate orbclient_window_shortcuts;
use orbclient::{Window, Renderer, EventOption, Color};
use orbclient_window_shortcuts::shortcut::{Comparator, GenericShortcutId, Shortcut, CommonId, Shortcuts};
fn window() -> orb... | supported.push(Shortcut{id: GenericShortcutId::Id(MyId::Decrease), keys: decrease_k});
//Error: Type inferred from line above
//supported.push(Shortcut{id: GenericShortcutId::Id(CommonId::Quit), keys: quit_k});
scs.enable(supported);
'events: loop {
for event in window.events() {
... | {
/*
let mut window = window();
let scs = Shortcuts::new();
//Quit Shortcut with ShortcutId from CommonId
let mut quit_k: Vec<u8> = Vec::new();
quit_k.push(orbclient::event::K_CTRL);
quit_k.push(orbclient::event::K_Q);
quit_k.sort();
let mut decrease_k = Vec::new();
decrease_k.pu... | identifier_body |
main.rs | /* Commented to avoid compile errors an failed build badges on TravisCI,
extern crate orbclient;
extern crate orbclient_window_shortcuts;
use orbclient::{Window, Renderer, EventOption, Color};
use orbclient_window_shortcuts::shortcut::{Comparator, GenericShortcutId, Shortcut, CommonId, Shortcuts};
fn window() -> orb... | () {
/*
let mut window = window();
let scs = Shortcuts::new();
//Quit Shortcut with ShortcutId from CommonId
let mut quit_k: Vec<u8> = Vec::new();
quit_k.push(orbclient::event::K_CTRL);
quit_k.push(orbclient::event::K_Q);
quit_k.sort();
let mut decrease_k = Vec::new();
decrease_k... | main | identifier_name |
main.rs | /* Commented to avoid compile errors an failed build badges on TravisCI,
| use orbclient_window_shortcuts::shortcut::{Comparator, GenericShortcutId, Shortcut, CommonId, Shortcuts};
fn window() -> orbclient::Window {
let (width, height) = orbclient::get_display_size().unwrap();
let mut window = Window::new_flags(0, 0, width / 2, height / 2, "Shortcuts Example", &[orbclient::WindowFlag... | extern crate orbclient;
extern crate orbclient_window_shortcuts;
use orbclient::{Window, Renderer, EventOption, Color}; | random_line_split |
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... | <S: AsRef<str>, T: Iterator<Item = S>>(it: T) -> String {
it.map(|x| if char_at(x.as_ref(), 0).is_digit(10) {
x.as_ref().to_uppercase()
} else {
format!("{}{}",
x.as_ref()[0..1].to_uppercase(),
x.as_ref()[1..].to_lowercase())
})
.join(""... | iterator_to_class_case | identifier_name |
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... |
str.push_str(&part);
}
str
}
fn iterator_to_upper_case_words<S: AsRef<str>, T: Iterator<Item = S>>(it: T) -> String {
it.map(|x| x.as_ref().to_uppercase()).join("_")
}
#[cfg_attr(feature="clippy", allow(needless_range_loop))]
fn replace_all_sub_vecs(parts: &mut Vec<String>, needle: Vec<&str>) {
let mut a... | {
str.push('_');
} | conditional_block |
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... |
#[cfg_attr(feature="clippy", allow(needless_range_loop))]
fn replace_all_sub_vecs(parts: &mut Vec<String>, needle: Vec<&str>) {
let mut any_found = true;
while any_found {
any_found = false;
if parts.len() + 1 >= needle.len() {
// TODO: maybe rewrite this
for i in 0..parts.len() + 1 - needle.l... | {
it.map(|x| x.as_ref().to_uppercase()).join("_")
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.