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 |
|---|---|---|---|---|
mod.rs | use super::{Event, Ins, Prop, Mod, FDVar, Propagator, LeXY, GeXY, LeXYC, GeXYC, LeXC, GeXC};
use std::rc::{Rc, Weak};
/// X = Y
pub struct EqXY;
impl EqXY {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>) {
// TODO merge or at least intersect domains
LeXY::new(model.clone(), x.clone(), y.c... |
else if self.y().is_instanciated() {
self.unregister();
self.x().remove(self.y().min() + self.c)
} else {
vec![]
}
}
}
#[cfg(test)]
mod tests;
| {
self.unregister();
self.y().remove(self.x().min() - self.c)
} | conditional_block |
mod.rs | use super::{Event, Ins, Prop, Mod, FDVar, Propagator, LeXY, GeXY, LeXYC, GeXYC, LeXC, GeXC};
use std::rc::{Rc, Weak};
/// X = Y
pub struct EqXY;
impl EqXY {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>) {
// TODO merge or at least intersect domains
LeXY::new(model.clone(), x.clone(), y.c... | (model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>, c: int) {
NeqXYCxy::new(model, x, y, c);
}
}
/// X!= C
pub struct NeqXC;
#[allow(unused_variable)]
impl NeqXC {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, c: int) {
x.remove(c);
}
}
struct NeqXYCxy : Prop {
c: int
}
impl NeqXYCxy {
fn ne... | new | identifier_name |
mod.rs | use super::{Event, Ins, Prop, Mod, FDVar, Propagator, LeXY, GeXY, LeXYC, GeXYC, LeXC, GeXC};
use std::rc::{Rc, Weak};
/// X = Y
pub struct EqXY;
impl EqXY {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>) {
// TODO merge or at least intersect domains
LeXY::new(model.clone(), x.clone(), y.c... | let p = Rc::new((box this) as Box<Propagator>);
model.add_prop(p);
}
fn x(&self) -> Rc<FDVar> {
self.vars.get(0).clone()
}
fn y(&self) -> Rc<FDVar> {
self.vars.get(1).clone()
}
}
impl Propagator for NeqXYCxy {
fn id(&self) -> uint {
self.id
}
fn... | fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>, c: int) {
let id = model.propagators.borrow().len();
let this = NeqXYCxy { model: model.downgrade(), id: id, vars: vec![x, y], c: c}; | random_line_split |
config.rs | extern crate serde_json;
use log::LogLevelFilter;
use logger::MetricsLoggerFactory;
use logger::MetricsLogger;
use self::serde_json::Value;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::collections::BTreeMap;
// This is the config file that reads all the json from m... |
failing "get_u64 should fail for a missing key" {
cfg.get_u64("start22Time");
}
it "get_string should return a string for an existing key" {
let save_path: String = cfg.get_string("savePath").to_string();
assert_eq!(save_path, "testSavePath");
}
failing "get_string should ... | random_line_split | |
config.rs | extern crate serde_json;
use log::LogLevelFilter;
use logger::MetricsLoggerFactory;
use logger::MetricsLogger;
use self::serde_json::Value;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::collections::BTreeMap;
// This is the config file that reads all the json from m... | Err(why) => {
logger().log(LogLevelFilter::Error, format!("Error: {}", why).as_str());
return false;
}
Ok(_) => {
logger().log(LogLevelFilter::Debug,
format!("file contains: {}", s).as_str())
}
... | {
// TODO: Need to make this look at env variable or take a path to the file.
logger().log(LogLevelFilter::Debug,
format!("config file: {}", file_name).as_str());
let path = Path::new(file_name);
let display = path.display();
// Open the path in read-only mo... | identifier_body |
config.rs | extern crate serde_json;
use log::LogLevelFilter;
use logger::MetricsLoggerFactory;
use logger::MetricsLogger;
use self::serde_json::Value;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::collections::BTreeMap;
// This is the config file that reads all the json from m... | (&mut self, key: &str) -> String {
if let Some(ref mut parsed_json) = self.parsed_json {
let val = parsed_json.get(key);
match val {
Some(v) => {
let nv = v.clone();
match nv {
Value::String(nv) => nv.clone()... | get_string | identifier_name |
config.rs | extern crate serde_json;
use log::LogLevelFilter;
use logger::MetricsLoggerFactory;
use logger::MetricsLogger;
use self::serde_json::Value;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::collections::BTreeMap;
// This is the config file that reads all the json from m... |
Err(e) => panic!("cannot open file: {}", e),
};
}
pub fn init(&mut self, file_name: &str) -> bool {
// TODO: Need to make this look at env variable or take a path to the file.
logger().log(LogLevelFilter::Debug,
format!("config file: {}", file_name).as... | {
let _ = t.write(json.as_bytes());
} | conditional_block |
unix.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 s2 = s1.clone();
let (done, rx) = channel();
spawn(proc() {
let mut s2 = s2;
let mut buf = [0, 0];
s2.read(buf).unwrap();
tx2.send(());
done.send(());
});
let mut buf = [0, 0];
s1.read(buf).unwrap();
... | let mut s1 = acceptor.accept().unwrap(); | random_line_split |
unix.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
impl Reader for UnixStream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.obj.read(buf) }
}
impl Writer for UnixStream {
fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.obj.write(buf) }
}
/// A value that can listen for incoming named pipe connection requests.
pub struct UnixListener... | {
UnixStream { obj: self.obj.clone() }
} | identifier_body |
unix.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 ... | <P: ToCStr>(path: &P) -> IoResult<UnixListener> {
LocalIo::maybe_raise(|io| {
io.unix_bind(&path.to_c_str()).map(|s| UnixListener { obj: s })
})
}
}
impl Listener<UnixStream, UnixAcceptor> for UnixListener {
fn listen(self) -> IoResult<UnixAcceptor> {
self.obj.listen().map(|... | bind | identifier_name |
numeric.rs | use backend::Backend;
use expression::{Expression, SelectableExpression, NonAggregate};
use query_builder::*;
use types;
macro_rules! numeric_operation {
($name:ident, $op:expr) => {
pub struct $name<Lhs, Rhs> {
lhs: Lhs,
rhs: Rhs,
}
impl<Lhs, Rhs> $name<Lhs, Rhs> {... |
numeric_operation!(Add, " + ");
numeric_operation!(Sub, " - ");
numeric_operation!(Mul, " * ");
numeric_operation!(Div, " / "); | random_line_split | |
auth.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of screenruster.
//
// screenruster 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 Licen... | }
}
});
Ok(Auth {
receiver: i_receiver,
sender: i_sender,
})
}
pub fn authenticate<S: Into<String>>(&self, password: S) -> Result<(), SendError<Request>> {
self.sender.send(Request::Authenticate(password.into()))
}
}
impl Deref for Auth {
type Target = Receiver<Response>;
fn deref(&self) ... | if methods.is_empty() {
warn!("no authentication method");
sender.send(Response::Success).unwrap();
continue 'main;
}
for method in &mut methods {
if let Ok(true) = method.authenticate(user.to_str().unwrap(), &password) {
sender.send(Response::Success).unwrap();
... | conditional_block |
auth.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of screenruster.
//
// screenruster 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 Licen... | // screenruster is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
//... | // | random_line_split |
auth.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of screenruster.
//
// screenruster 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 Licen... | : Into<String>>(&self, password: S) -> Result<(), SendError<Request>> {
self.sender.send(Request::Authenticate(password.into()))
}
}
impl Deref for Auth {
type Target = Receiver<Response>;
fn deref(&self) -> &Receiver<Response> {
&self.receiver
}
}
| thenticate<S | identifier_name |
util.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 ... |
}
| { ~";" }
pub fn logv(config: &config, s: ~str) {
debug!("{}", s);
if config.verbose { println!("{}", s); } | identifier_body |
util.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 ... | () -> ~str { ~"PATH" }
#[cfg(target_os = "win32")]
pub fn path_div() -> ~str { ~";" }
pub fn logv(config: &config, s: ~str) {
debug!("{}", s);
if config.verbose { println!("{}", s); }
}
| lib_path_env_var | identifier_name |
util.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 ... |
/// Conversion table from triple OS name to Rust SYSNAME
static OS_TABLE: &'static [(&'static str, &'static str)] = &[
("mingw32", "win32"),
("win32", "win32"),
("darwin", "macos"),
("android", "android"),
("linux", "linux"),
("freebsd", "freebsd"),
];
pub fn get_os(triple: &str) -> &'static s... | random_line_split | |
no-landing-pads.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 ... | {
thread::spawn(move|| -> () {
let _a = A;
panic!();
}).join().err().unwrap();
assert!(unsafe { !HIT });
} | identifier_body | |
no-landing-pads.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 ... | () {
thread::spawn(move|| -> () {
let _a = A;
panic!();
}).join().err().unwrap();
assert!(unsafe {!HIT });
}
| main | identifier_name |
no-landing-pads.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 ... | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -Z no-landing-pads
use std::thread;
static mut HIT: bool = false;
struct A;
impl Drop for A {
fn drop(&mut self) {
unsafe { HIT = true; }
}
}
fn main() {
thread::spawn(move|| ... | random_line_split | |
cookiesetter.rs | /*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0
*
* © Gregor Reitzenstein
*/
use iron::prelude::*;
use iron::AfterMiddleware;
use iron::headers::SetCookie;
use iron::typemap::Key;
use cookie::Cookie;
use api::API;
/// This Struct sets Cookies on outgoing Responses as ... |
impl AfterMiddleware for CookieSetter
{
fn after(&self, req: &mut Request, mut res: Response) -> IronResult<Response>
{
// If the Request contains a CookieReq struct, set the specified Cookie
if req.extensions.contains::<CookieReq>()
{
let cookievalvec: Vec<[String; 2]> = re... | CookieSetter
}
} | random_line_split |
cookiesetter.rs | /*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0
*
* © Gregor Reitzenstein
*/
use iron::prelude::*;
use iron::AfterMiddleware;
use iron::headers::SetCookie;
use iron::typemap::Key;
use cookie::Cookie;
use api::API;
/// This Struct sets Cookies on outgoing Responses as ... | Ok(res)
}
}
// This Struct notifies CookieSetter to set a cookie.
pub struct CookieReq;
// Key needs to be implented so this Struct can be inserted to req.extensions
impl Key for CookieReq { type Value = Vec<[String; 2]>; }
|
let cookievalvec: Vec<[String; 2]> = req.extensions.remove::<CookieReq>().unwrap();
// A Cookie is a slice of two Strings: The key and the associated value
let cookies: Vec<Cookie> = cookievalvec.into_iter().map(|x| Cookie::new(x[1].clone(),x[2].clone())).collect();
res... | conditional_block |
cookiesetter.rs | /*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0
*
* © Gregor Reitzenstein
*/
use iron::prelude::*;
use iron::AfterMiddleware;
use iron::headers::SetCookie;
use iron::typemap::Key;
use cookie::Cookie;
use api::API;
/// This Struct sets Cookies on outgoing Responses as ... | _: &API) -> CookieSetter
{
CookieSetter
}
}
impl AfterMiddleware for CookieSetter
{
fn after(&self, req: &mut Request, mut res: Response) -> IronResult<Response>
{
// If the Request contains a CookieReq struct, set the specified Cookie
if req.extensions.contains::<CookieReq>()
... | ew( | identifier_name |
bitstream.rs | //! This module provides bit readers and writers
use std::io::{self, Write};
/// Containes either the consumed bytes and reconstructed bits or
/// only the consumed bytes if the supplied buffer was not bit enough
pub enum Bits {
/// Consumed bytes, reconstructed bits
Some(usize, u16),
/// Consumed bytes
... |
let mut consumed = 0;
while self.bits < n {
let byte = if buf.len() > 0 {
let byte = buf[0];
buf = &buf[1..];
byte
} else {
return Bits::None(consumed)
};
self.acc |= (byte as u32) << self.bi... | {
// This is a logic error the program should have prevented this
// Ideally we would used bounded a integer value instead of u8
panic!("Cannot read more than 16 bits")
} | conditional_block |
bitstream.rs | //! This module provides bit readers and writers
use std::io::{self, Write};
/// Containes either the consumed bytes and reconstructed bits or
/// only the consumed bytes if the supplied buffer was not bit enough
pub enum Bits {
/// Consumed bytes, reconstructed bits
Some(usize, u16),
/// Consumed bytes
... | () {
let data = [255, 20, 40, 120, 128];
let mut offset = 0;
let mut expanded_data = Vec::new();
let mut reader = super::LsbReader::new();
while let Bits::Some(consumed, b) = reader.read_bits(&data[offset..], 10) {
offset += consumed;
expanded_data.push(b)... | reader_writer | identifier_name |
bitstream.rs | //! This module provides bit readers and writers
use std::io::{self, Write};
/// Containes either the consumed bytes and reconstructed bits or
/// only the consumed bytes if the supplied buffer was not bit enough
pub enum Bits {
/// Consumed bytes, reconstructed bits
Some(usize, u16),
/// Consumed bytes
... | }
assert_eq!(&data[..], &compressed_data[..])
}
} | for &datum in expanded_data.iter() {
let _ = writer.write_bits(datum, 10);
} | random_line_split |
bitstream.rs | //! This module provides bit readers and writers
use std::io::{self, Write};
/// Containes either the consumed bytes and reconstructed bits or
/// only the consumed bytes if the supplied buffer was not bit enough
pub enum Bits {
/// Consumed bytes, reconstructed bits
Some(usize, u16),
/// Consumed bytes
... |
}
impl<W: Write> BitWriter for MsbWriter<W> {
fn write_bits(&mut self, v: u16, n: u8) -> io::Result<()> {
self.acc |= (v as u32) << (32 - n - self.bits);
self.bits += n;
while self.bits >= 8 {
try!(self.w.write_all(&[(self.acc >> 24) as u8]));
self.acc <<= 8;
... | {
self.acc |= (v as u32) << self.bits;
self.bits += n;
while self.bits >= 8 {
try!(self.w.write_all(&[self.acc as u8]));
self.acc >>= 8;
self.bits -= 8
}
Ok(())
} | identifier_body |
api.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/. */
extern crate hyper;
extern crate time;
extern crate url;
use foxbox_taxonomy::api::{ Error, InternalError };
use ... | };
let mut options = fs::OpenOptions::new();
options.write(true);
options.create(true);
options.truncate(true);
let filename_base = time::strftime("%Y-%m-%d-%H%M%S", &time::now()).unwrap();
let mut full_filename;
let image_file;
let mut loop_coun... | random_line_split | |
api.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/. */
extern crate hyper;
extern crate time;
extern crate url;
use foxbox_taxonomy::api::{ Error, InternalError };
use ... |
}
}
#[derive(Clone)]
pub struct IpCamera {
pub udn: String,
url: String,
snapshot_dir: String,
pub image_list_id: Id<Getter>,
pub image_newest_id: Id<Getter>,
pub snapshot_id: Id<Setter>,
}
impl IpCamera {
pub fn new(udn: &str, url: &str, root_snapshot_dir: &str) -> Result<Self, Erro... | {
warn!("read of image data from {} failed: {}", url, err);
Err(Error::InternalError(InternalError::InvalidInitialService))
} | conditional_block |
api.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/. */
extern crate hyper;
extern crate time;
extern crate url;
use foxbox_taxonomy::api::{ Error, InternalError };
use ... | <IO>(prefix: &str, operation: &str, service_id: &str) -> Id<IO>
where IO: IOMechanism
{
Id::new(&format!("{}:{}.{}@link.mozilla.org", prefix, operation, service_id))
}
fn get_bytes(url: String) -> Result<Vec<u8>, Error> {
let client = hyper::Client::new();
let get_result = client.get(&url)
... | create_io_mechanism_id | identifier_name |
api.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/. */
extern crate hyper;
extern crate time;
extern crate url;
use foxbox_taxonomy::api::{ Error, InternalError };
use ... |
pub fn create_setter_id(operation: &str, service_id: &str) -> Id<Setter> {
create_io_mechanism_id("setter", operation, service_id)
}
pub fn create_getter_id(operation: &str, service_id: &str) -> Id<Getter> {
create_io_mechanism_id("getter", operation, service_id)
}
pub fn create_io_mechanism_id<IO>(prefix: ... | {
Id::new(&format!("service:{}@link.mozilla.org", service_id))
} | identifier_body |
lib.rs | // option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A lightweight logging facade.
//!
//! A logging facade provides a single logging API that abstracts over the
//! actual logging implementation. Libraries can use the logging API provided
//! by this crate, and the ... | }
}
impl PartialOrd<LogLevel> for LogLevelFilter {
#[inline]
fn partial_cmp(&self, other: &LogLevel) -> Option<cmp::Ordering> {
other.partial_cmp(self).map(|x| x.reverse())
}
}
impl Ord for LogLevelFilter {
#[inline]
fn cmp(&self, other: &LogLevelFilter) -> cmp::Ordering {
(*se... | #[inline]
fn partial_cmp(&self, other: &LogLevelFilter) -> Option<cmp::Ordering> {
Some(self.cmp(other)) | random_line_split |
lib.rs | option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A lightweight logging facade.
//!
//! A logging facade provides a single logging API that abstracts over the
//! actual logging implementation. Libraries can use the logging API provided
//! by this crate, and the co... |
/// The name of the target of the directive.
pub fn target(&self) -> &str {
self.metadata.target()
}
}
/// Metadata about a log message.
pub struct LogMetadata<'a> {
level: LogLevel,
target: &'a str,
}
impl<'a> LogMetadata<'a> {
/// The verbosity level of the message.
pub fn leve... | {
self.metadata.level()
} | identifier_body |
lib.rs | option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A lightweight logging facade.
//!
//! A logging facade provides a single logging API that abstracts over the
//! actual logging implementation. Libraries can use the logging API provided
//! by this crate, and the co... | (&self, other: &LogLevelFilter) -> bool {
*self as usize == *other as usize
}
}
impl PartialEq<LogLevel> for LogLevelFilter {
#[inline]
fn eq(&self, other: &LogLevel) -> bool {
other.eq(self)
}
}
impl PartialOrd for LogLevelFilter {
#[inline]
fn partial_cmp(&self, other: &LogLe... | eq | identifier_name |
lib.rs | option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A lightweight logging facade.
//!
//! A logging facade provides a single logging API that abstracts over the
//! actual logging implementation. Libraries can use the logging API provided
//! by this crate, and the co... |
}
// WARNING
// This is not considered part of the crate's public API. It is subject to
// change at any time.
#[doc(hidden)]
pub fn __log(level: LogLevel, target: &str, loc: &LogLocation,
args: fmt::Arguments) {
if let Some(logger) = logger() {
let record = LogRecord {
metadata: ... | {
false
} | conditional_block |
main.rs | extern crate crypto;
extern crate itertools;
use std::env;
use crypto::md5::Md5;
use crypto::digest::Digest;
use std::collections::HashMap;
fn main() {
let raw_input = env::args().nth(1).unwrap_or("".to_string());
let input = raw_input.as_bytes();
let mut index : i64 = -1;
let mut hash = Md5::new();
... |
if pos < 8 &&!output2.contains_key(&pos) {
output2.insert(pos, out2);
}
}
println!("P1 {}", output);
let empty = " ".to_string();
let temp = (0..8)
.map(|i| output2.get(&(i as i32)).unwrap_or(&empty))
.cloned()
.collect::<Vec<_>>()
.concat();
... | {
output.push_str(&out);
} | conditional_block |
main.rs | extern crate crypto;
extern crate itertools;
use std::env;
use crypto::md5::Md5;
use crypto::digest::Digest;
use std::collections::HashMap;
fn | () {
let raw_input = env::args().nth(1).unwrap_or("".to_string());
let input = raw_input.as_bytes();
let mut index : i64 = -1;
let mut hash = Md5::new();
let mut output = String::new();
let mut output2 = HashMap::new();
while {output.len() < 8 || output2.len() < 8} {
let mut temp =... | main | identifier_name |
main.rs | extern crate crypto;
extern crate itertools;
use std::env;
use crypto::md5::Md5;
use crypto::digest::Digest;
use std::collections::HashMap;
fn main() |
(temp[0] as i32 + temp[1] as i32 + (temp[2] >> 4) as i32)!= 0
} {}
let out = format!("{:x}", temp[2] & 0xf);
let out2 = format!("{:x}", temp[3] >> 4);
let pos = (temp[2] & 0x0f) as i32;
if output.len() < 8 {
output.push_str(&out);
}
if ... | {
let raw_input = env::args().nth(1).unwrap_or("".to_string());
let input = raw_input.as_bytes();
let mut index : i64 = -1;
let mut hash = Md5::new();
let mut output = String::new();
let mut output2 = HashMap::new();
while {output.len() < 8 || output2.len() < 8} {
let mut temp = [0... | identifier_body |
main.rs | extern crate crypto;
extern crate itertools;
use std::env;
use crypto::md5::Md5;
use crypto::digest::Digest;
use std::collections::HashMap;
fn main() {
let raw_input = env::args().nth(1).unwrap_or("".to_string());
let input = raw_input.as_bytes();
let mut index : i64 = -1;
let mut hash = Md5::new();
... |
hash.input(input);
hash.input(index.to_string().as_bytes());
hash.result(&mut temp);
(temp[0] as i32 + temp[1] as i32 + (temp[2] >> 4) as i32)!= 0
} {}
let out = format!("{:x}", temp[2] & 0xf);
let out2 = format!("{:x}", temp[3] >> 4);
... | random_line_split | |
dependency.rs | use std::fmt;
use std::rc::Rc;
use std::str::FromStr;
use semver::VersionReq;
use semver::ReqParseError;
use serde::ser;
use core::{PackageId, SourceId, Summary};
use core::interning::InternedString;
use util::{Cfg, CfgExpr, Config};
use util::errors::{CargoError, CargoResult, CargoResultExt};
/// Information about ... | (&self) -> Option<&str> {
self.inner.rename.as_ref().map(|s| &**s)
}
pub fn set_kind(&mut self, kind: Kind) -> &mut Dependency {
Rc::make_mut(&mut self.inner).kind = kind;
self
}
/// Sets the list of features requested for the package.
pub fn set_features(&mut self, feature... | rename | identifier_name |
dependency.rs | use std::fmt;
use std::rc::Rc;
use std::str::FromStr;
use semver::VersionReq;
use semver::ReqParseError;
use serde::ser;
use core::{PackageId, SourceId, Summary};
use core::interning::InternedString;
use util::{Cfg, CfgExpr, Config};
use util::errors::{CargoError, CargoResult, CargoResultExt};
/// Information about ... | } | random_line_split | |
dependency.rs | use std::fmt;
use std::rc::Rc;
use std::str::FromStr;
use semver::VersionReq;
use semver::ReqParseError;
use serde::ser;
use core::{PackageId, SourceId, Summary};
use core::interning::InternedString;
use util::{Cfg, CfgExpr, Config};
use util::errors::{CargoError, CargoResult, CargoResultExt};
/// Information about ... |
/// Returns true if the default features of the dependency are requested.
pub fn uses_default_features(&self) -> bool {
self.inner.default_features
}
/// Returns the list of features that are requested by the dependency.
pub fn features(&self) -> &[InternedString] {
&self.inner.fea... | {
self.inner.optional
} | identifier_body |
tcp_client.rs | use std::{fmt, io};
use std::sync::Arc;
use std::net::SocketAddr;
use std::marker::PhantomData;
use BindClient;
use tokio_core::reactor::Handle;
use tokio_core::net::{TcpStream, TcpStreamNew};
use futures::{Future, Poll, Async};
// TODO: add configuration, e.g.:
// - connection timeout
// - multiple addresses
// - re... | #[derive(Debug)]
pub struct TcpClient<Kind, P> {
_kind: PhantomData<Kind>,
proto: Arc<P>,
}
/// A future for establishing a client connection.
///
/// Yields a service for interacting with the server.
pub struct Connect<Kind, P> {
_kind: PhantomData<Kind>,
proto: Arc<P>,
socket: TcpStreamNew,
h... | ///
/// At the moment, this builder offers minimal configuration, but more will be
/// added over time. | random_line_split |
tcp_client.rs | use std::{fmt, io};
use std::sync::Arc;
use std::net::SocketAddr;
use std::marker::PhantomData;
use BindClient;
use tokio_core::reactor::Handle;
use tokio_core::net::{TcpStream, TcpStreamNew};
use futures::{Future, Poll, Async};
// TODO: add configuration, e.g.:
// - connection timeout
// - multiple addresses
// - re... | (&self, addr: &SocketAddr, handle: &Handle) -> Connect<Kind, P> {
Connect {
_kind: PhantomData,
proto: self.proto.clone(),
socket: TcpStream::connect(addr, handle),
handle: handle.clone(),
}
}
}
impl<Kind, P> fmt::Debug for Connect<Kind, P> {
fn f... | connect | identifier_name |
tcp_client.rs | use std::{fmt, io};
use std::sync::Arc;
use std::net::SocketAddr;
use std::marker::PhantomData;
use BindClient;
use tokio_core::reactor::Handle;
use tokio_core::net::{TcpStream, TcpStreamNew};
use futures::{Future, Poll, Async};
// TODO: add configuration, e.g.:
// - connection timeout
// - multiple addresses
// - re... |
}
| {
write!(f, "Connect {{ ... }}")
} | identifier_body |
structure.rs | // Copyright 2016 Dario Domizioli
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | pub fn get_title(&self) -> &str { &self.title }
}
#[derive(Clone, PartialEq)]
pub struct Content {
pub chunks: Vec<String>
}
impl Content {
fn build_title_page(st: &Structure) -> Result<String, String> {
let book_header =
r#"<div class="book_cover">"#.to_string() +
r#"<div... | random_line_split | |
structure.rs | // Copyright 2016 Dario Domizioli
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... |
fn build_toc(st: &Structure) -> Result<String, String> {
let mut toc = String::new();
toc = toc + r#"<div class="toc">"# + "\n\n";
let mut part_index = 1;
for part in st.parts.iter() {
let part_link = format!(
"- **[{0} {1}](#kos_ref_part_{0})**\n\n", pa... | {
let book_header =
r#"<div class="book_cover">"#.to_string() +
r#"<div class="book_author">"# +
&st.author +
r#"</div>"# +
r#"<div class="book_title">"# +
r#"<a id="kos_book_title">"# +
&st.title +
"</a></div>" +
... | identifier_body |
structure.rs | // Copyright 2016 Dario Domizioli
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | {
title: String,
author: String,
license: String,
parts: Vec<Part>
}
impl Structure {
pub fn from_json(js: &str) -> Result<Structure, json::DecoderError> {
json::decode::<Structure>(js)
}
pub fn get_title(&self) -> &str { &self.title }
}
#[derive(Clone, PartialEq)]
pub struct Con... | Structure | identifier_name |
htmltablecolelement.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::root::DomRoot;
use crate::dom::documen... | )),
document,
);
n.upcast::<Node>().set_weird_parser_insertion_mode();
n
}
} | ) -> DomRoot<HTMLTableColElement> {
let n = Node::reflect_node(
Box::new(HTMLTableColElement::new_inherited(
local_name, prefix, document, | random_line_split |
htmltablecolelement.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::root::DomRoot;
use crate::dom::documen... |
}
| {
let n = Node::reflect_node(
Box::new(HTMLTableColElement::new_inherited(
local_name, prefix, document,
)),
document,
);
n.upcast::<Node>().set_weird_parser_insertion_mode();
n
} | identifier_body |
htmltablecolelement.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::root::DomRoot;
use crate::dom::documen... | (
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> DomRoot<HTMLTableColElement> {
let n = Node::reflect_node(
Box::new(HTMLTableColElement::new_inherited(
local_name, prefix, document,
)),
document,
)... | new | identifier_name |
error.rs | use rustc_serialize::json;
use rustc_serialize::Decoder;
use rustc_serialize::Decodable;
use std::str;
use std::fmt;
/// Documentation References:
/// https://developer.github.com/v3/#client-errors
/// `ErrorCode` represents the type of error that was reported
/// as a response on a request to th Github API.
#[deriv... | (code: u32) -> bool {
code == STATUS_OK
}
| check_status_code | identifier_name |
error.rs | use rustc_serialize::json;
use rustc_serialize::Decoder;
use rustc_serialize::Decodable;
use std::str;
use std::fmt;
/// Documentation References:
/// https://developer.github.com/v3/#client-errors
/// `ErrorCode` represents the type of error that was reported
/// as a response on a request to th Github API.
#[deriv... | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let msg: &str = match *self {
ErrorCode::Missing => "resource does not exist",
ErrorCode::MissingField => "required field on the resource has not been set",
ErrorCode::Invalid => "the formatting of the field is invali... | Unknown(String),
}
/// Allowing `ErrorCode` to be printed via `{}`.
impl fmt::Display for ErrorCode { | random_line_split |
check_internal.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/gfx/check_internal.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Provides a handy macro to check the outcome
of an OpenGL call for error... | {
use gl2 = opengles::gl2;
use log::Log;
let err = gl2::get_error();
if err!= gl2::NO_ERROR
{
log_error!(func);
log_fail!(util::get_err_str(err));
}
}
#[cfg(not(check_gl))]
pub fn check_gl(_func: &str)
{ }
macro_rules! check
(
($func:expr) =>
({
let ret = $func;
check::check_gl(str... | #[path = "../log/macros.rs"]
mod macros;
#[cfg(check_gl)]
pub fn check_gl(func: &str) | random_line_split |
check_internal.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/gfx/check_internal.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Provides a handy macro to check the outcome
of an OpenGL call for error... | (_func: &str)
{ }
macro_rules! check
(
($func:expr) =>
({
let ret = $func;
check::check_gl(stringify!($func));
ret
});
)
macro_rules! check_unsafe
(
($func:expr) =>
({
unsafe { check!($func) }
});
)
| check_gl | identifier_name |
check_internal.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/gfx/check_internal.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Provides a handy macro to check the outcome
of an OpenGL call for error... |
macro_rules! check
(
($func:expr) =>
({
let ret = $func;
check::check_gl(stringify!($func));
ret
});
)
macro_rules! check_unsafe
(
($func:expr) =>
({
unsafe { check!($func) }
});
)
| { } | identifier_body |
check_internal.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/gfx/check_internal.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Provides a handy macro to check the outcome
of an OpenGL call for error... |
}
#[cfg(not(check_gl))]
pub fn check_gl(_func: &str)
{ }
macro_rules! check
(
($func:expr) =>
({
let ret = $func;
check::check_gl(stringify!($func));
ret
});
)
macro_rules! check_unsafe
(
($func:expr) =>
({
unsafe { check!($func) }
});
)
| {
log_error!(func);
log_fail!(util::get_err_str(err));
} | conditional_block |
env.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 ... | /// Poison allocations on free
poison_on_free: bool,
/// The argc value passed to main
argc: c_int,
/// The argv value passed to main
argv: **c_char,
/// Print GC debugging info
debug_mem: bool
}
/// Get the global environment settings
/// # Safety Note
/// This will abort the process i... | logspec: *c_char,
/// Record and report detailed information about memory leaks
detailed_leaks: bool,
/// Seed the random number generator
rust_seed: *c_char, | random_line_split |
env.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 ... | {
/// The number of threads to use by default
num_sched_threads: size_t,
/// The minimum size of a stack segment
min_stack_size: size_t,
/// The maximum amount of total stack per task before aborting
max_stack_size: size_t,
/// The default logging configuration
logspec: *c_char,
///... | Environment | identifier_name |
env.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 ... |
extern {
fn rust_get_rt_env() -> &Environment;
}
| {
unsafe { rust_get_rt_env() }
} | identifier_body |
task.rs | Runtime;
use local::Local;
use local_heap::LocalHeap;
use rtio::LocalIo;
use unwind;
use unwind::Unwinder;
use collections::str::SendStr;
/// State associated with Rust tasks.
///
/// Rust tasks are primarily built with two separate components. One is this
/// structure which handles standard services such as TLD, un... | /// println!("Hello with a native runtime!");
/// }).destroy();
/// # }
/// ```
pub fn run(mut self: Box<Task>, f: ||) -> Box<Task> {
assert!(!self.is_destroyed(), "cannot re-use a destroyed task");
// First, make sure that no one else is in TLS. This does not allow
// r... | /// task.run(|| { | random_line_split |
task.rs | ;
use local::Local;
use local_heap::LocalHeap;
use rtio::LocalIo;
use unwind;
use unwind::Unwinder;
use collections::str::SendStr;
/// State associated with Rust tasks.
///
/// Rust tasks are primarily built with two separate components. One is this
/// structure which handles standard services such as TLD, unwinding ... | (mut self: Box<Task>) {
let ops = self.imp.take().unwrap();
ops.yield_now(self);
}
/// Similar to `yield_now`, except that this function may immediately return
/// without yielding (depending on what the runtime decides to do).
pub fn maybe_yield(mut self: Box<Task>) {
let ops =... | yield_now | identifier_name |
task.rs | ;
use local::Local;
use local_heap::LocalHeap;
use rtio::LocalIo;
use unwind;
use unwind::Unwinder;
use collections::str::SendStr;
/// State associated with Rust tasks.
///
/// Rust tasks are primarily built with two separate components. One is this
/// structure which handles standard services such as TLD, unwinding ... |
Shared(arc) => {
let blocked_task_ptr: uint = mem::transmute(box arc);
rtassert!(blocked_task_ptr & 0x1 == 0);
blocked_task_ptr | 0x1
}
}
}
/// Convert from an unsafe uint value. Useful for retrieving a pipe's state
/// flag.
... | {
let blocked_task_ptr: uint = mem::transmute(task);
rtassert!(blocked_task_ptr & 0x1 == 0);
blocked_task_ptr
} | conditional_block |
task.rs | ;
use local::Local;
use local_heap::LocalHeap;
use rtio::LocalIo;
use unwind;
use unwind::Unwinder;
use collections::str::SendStr;
/// State associated with Rust tasks.
///
/// Rust tasks are primarily built with two separate components. One is this
/// structure which handles standard services such as TLD, unwinding ... |
/// Create a blocked task, unless the task was already killed.
pub fn block(task: Box<Task>) -> BlockedTask {
Owned(task)
}
/// Converts one blocked task handle to a list of many handles to the same.
pub fn make_selectable(self, num_handles: uint) -> Take<BlockedTasks> {
let arc =... | { assert!(self.wake().is_none()); } | identifier_body |
htmlmodelement.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::HTMLModElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLModElem... | use dom::document::Document;
use dom::element::HTMLModElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[dom_struct]
pub struct HTMLModElement {
htmlelement: HTMLElement
}
impl HTMLMod... | use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector}; | random_line_split |
htmlmodelement.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::HTMLModElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLModElem... |
}
impl HTMLModElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLModElement {
HTMLModElement {
htmlelement: HTMLElement::new_inherited(HTMLModElementTypeId, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]... | {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLModElementTypeId))
} | identifier_body |
htmlmodelement.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::HTMLModElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLModElem... | (localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLModElement> {
let element = HTMLModElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLModElementBinding::Wrap)
}
}
impl Reflectable for HTMLModElement {
... | new | identifier_name |
ui.rs | info.enable();
shader.texture_offset.enable();
shader.color.enable();
shader.position.vertex_pointer_int(3, gl::SHORT, 28, 0);
shader.texture_info.vertex_pointer(4, gl::UNSIGNED_SHORT, false, 28, 8);
shader.texture_offset.vertex_pointer_int(3, gl::SHORT, 28, 16);
shader.c... | r: u8,
g: u8,
b: u8)
-> UIText {
self.create_text(val, x, y, sx, sy, 0.0, r, g, b)
}
pub fn new_text_rotated(&mut self,
val: &str,
x: f64,
... | identifier_name | |
ui.rs | _info.enable();
shader.texture_offset.enable();
shader.color.enable();
shader.position.vertex_pointer_int(3, gl::SHORT, 28, 0);
shader.texture_info.vertex_pointer(4, gl::UNSIGNED_SHORT, false, 28, 8);
shader.texture_offset.vertex_pointer_int(3, gl::SHORT, 28, 16);
shader.... | g: u8,
b: u8)
-> UIText {
self.create_text(val, x, y, sx, sy, rotation, r, g, b)
}
fn create_text(&mut self,
val: &str,
x: f64,
y: f64,
sx: f64... | random_line_split | |
ui.rs | info.enable();
shader.texture_offset.enable();
shader.color.enable();
shader.position.vertex_pointer_int(3, gl::SHORT, 28, 0);
shader.texture_info.vertex_pointer(4, gl::UNSIGNED_SHORT, false, 28, 8);
shader.texture_offset.vertex_pointer_int(3, gl::SHORT, 28, 16);
shader.c... | sw = (self.page_width / 16.0) as u32;
let sh = (self.page_height / 16.0) as u32;
return p.relative((cx * sw + info.0 as u32) as f32 / (self.page_width as f32),
(cy * sh) as f32 / (self.page_height as f32),
(info.1 - info.0) as f32 / (s... | _character_info[raw as usize];
if page == 0 {
let | conditional_block |
font_context.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 freetype::freetype::FT_Add_Default_Modules;
use freetype::freetype::FT_Done_Library;
use freetype::freetype::F... |
FT_Add_Default_Modules(ctx);
FontContextHandle {
ctx: Rc::new(FreeTypeLibraryHandle {
ctx: ctx,
mem: mem,
user: user,
}),
}
}
}
}
| {
panic!("Unable to initialize FreeType library");
} | conditional_block |
font_context.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 freetype::freetype::FT_Add_Default_Modules;
use freetype::freetype::FT_Done_Library;
use freetype::freetype::F... | }
impl FontContextHandle {
pub fn new() -> FontContextHandle {
let user = Box::into_raw(Box::new(User { size: 0 }));
let mem = Box::into_raw(Box::new(FT_MemoryRec_ {
user: user as *mut c_void,
alloc: Some(ft_alloc),
free: Some(ft_free),
realloc: Some(... | } | random_line_split |
font_context.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 freetype::freetype::FT_Add_Default_Modules;
use freetype::freetype::FT_Done_Library;
use freetype::freetype::F... | (&self, ops: &mut MallocSizeOfOps) -> usize {
self.ctx.size_of(ops)
}
}
impl FontContextHandle {
pub fn new() -> FontContextHandle {
let user = Box::into_raw(Box::new(User { size: 0 }));
let mem = Box::into_raw(Box::new(FT_MemoryRec_ {
user: user as *mut c_void,
... | size_of | identifier_name |
config.rs | use std::io::{Read, Write};
use std::fs::{self, File};
use std::path::PathBuf;
use std::env::home_dir;
use error::*;
use serde_json;
lazy_static! {
pub static ref CONFIG: Config = read_config().expect("Failed to read configuration.");
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub host: ... | {
let path = config_path();
fs::create_dir_all(&path.parent().unwrap())?; // path.parent() never panics
let mut file = File::open(path)?;
let body = serde_json::to_string(&Config {
host: host.to_string(),
key: key.to_string()
})?;
serde_json::from_str(&body)
.map_err(Comf... | identifier_body | |
config.rs | use std::io::{Read, Write};
use std::fs::{self, File};
use std::path::PathBuf;
use std::env::home_dir;
use error::*;
use serde_json;
lazy_static! {
pub static ref CONFIG: Config = read_config().expect("Failed to read configuration.");
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub host: ... | pub fn write_config(host: &str, key: &str) -> ComfyResult<Config> {
let path = config_path();
fs::create_dir_all(&path.parent().unwrap())?; // path.parent() never panics
let mut file = File::open(path)?;
let body = serde_json::to_string(&Config {
host: host.to_string(),
key: key.to_strin... | .map_err(ComfyError::from)
}
| random_line_split |
config.rs | use std::io::{Read, Write};
use std::fs::{self, File};
use std::path::PathBuf;
use std::env::home_dir;
use error::*;
use serde_json;
lazy_static! {
pub static ref CONFIG: Config = read_config().expect("Failed to read configuration.");
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub host: ... | (host: &str, key: &str) -> ComfyResult<Config> {
let path = config_path();
fs::create_dir_all(&path.parent().unwrap())?; // path.parent() never panics
let mut file = File::open(path)?;
let body = serde_json::to_string(&Config {
host: host.to_string(),
key: key.to_string()
})?;
se... | write_config | identifier_name |
buddy.rs | //! An implementation of a buddy allocator.
use core::ptr;
use core::mem;
use core::cmp;
use intrusive::link::Link;
use intrusive::list::{List, Node};
use Allocator;
pub type FreeBlock = PhantomNode;
pub type FreeList = List<ptr::Unique<FreeBlock>, FreeBlock>;
#[allow(dead_code)]
pub struct Buddy<'a> {
min_blo... |
}
}
cursor.next();
}
if found {
cursor.remove();
return buddy_ptr
}
ptr::null_mut()
}
fn get_order_from_size(&self, mut size: usize, _align: usize) -> u32 {
size = Buddy::next_power_of_two(size);
... | {
found = true;
break;
} | conditional_block |
buddy.rs | //! An implementation of a buddy allocator.
use core::ptr;
use core::mem;
use core::cmp;
use intrusive::link::Link;
use intrusive::list::{List, Node};
use Allocator;
pub type FreeBlock = PhantomNode;
pub type FreeList = List<ptr::Unique<FreeBlock>, FreeBlock>;
#[allow(dead_code)]
pub struct Buddy<'a> {
min_blo... | }
#[allow(exceeding_bitshifts)]
pub fn next_power_of_two(mut num: usize) -> usize {
if num == 0 {
return 1;
}
num -= 1;
num |= num >> 1;
num |= num >> 2;
num |= num >> 4;
num |= num >> 8;
num |= num >> 16;
if mem::size_o... | random_line_split | |
buddy.rs | //! An implementation of a buddy allocator.
use core::ptr;
use core::mem;
use core::cmp;
use intrusive::link::Link;
use intrusive::list::{List, Node};
use Allocator;
pub type FreeBlock = PhantomNode;
pub type FreeList = List<ptr::Unique<FreeBlock>, FreeBlock>;
#[allow(dead_code)]
pub struct Buddy<'a> {
min_blo... |
#[allow(exceeding_bitshifts)]
pub fn next_power_of_two(mut num: usize) -> usize {
if num == 0 {
return 1;
}
num -= 1;
num |= num >> 1;
num |= num >> 2;
num |= num >> 4;
num |= num >> 8;
num |= num >> 16;
if mem::size_of::<u... | {
assert!(min_block_size >= ::core::mem::size_of::<FreeBlock>());
Buddy {
min_block_size: min_block_size,
min_block_order: Buddy::log2(min_block_size) as u32,
max_order: max_order,
free_lists: free_lists,
}
} | identifier_body |
buddy.rs | //! An implementation of a buddy allocator.
use core::ptr;
use core::mem;
use core::cmp;
use intrusive::link::Link;
use intrusive::list::{List, Node};
use Allocator;
pub type FreeBlock = PhantomNode;
pub type FreeList = List<ptr::Unique<FreeBlock>, FreeBlock>;
#[allow(dead_code)]
pub struct Buddy<'a> {
min_blo... | (&mut self, order: u32, start: *mut u8) {
let link = ptr::Unique::new(start as *mut FreeBlock);
self.free_lists[order as usize].push_front(link);
}
unsafe fn split_block(&mut self, block: *mut u8, mut order: u32,
target_order: u32) {
while order > target_order... | add_block_order | identifier_name |
mod.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... |
pub fn type_inference(cx: &ExtCtxt, agrammar: AGrammar) -> Partial<Grammar> {
let mut grammar = Grammar {
name: agrammar.name,
rules: HashMap::with_capacity(agrammar.rules.len()),
rust_functions: agrammar.rust_functions,
rust_items: agrammar.rust_items,
attributes: agrammar.attributes
};
Infe... | mod bottom_up_unit;
mod top_down_unit;
mod recursive_type;
// mod printer; | random_line_split |
mod.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... | {
let mut grammar = Grammar {
name: agrammar.name,
rules: HashMap::with_capacity(agrammar.rules.len()),
rust_functions: agrammar.rust_functions,
rust_items: agrammar.rust_items,
attributes: agrammar.attributes
};
InferenceEngine::infer(&mut grammar, agrammar.rules);
bottom_up_unit_inference(... | identifier_body | |
mod.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... | (cx: &ExtCtxt, agrammar: AGrammar) -> Partial<Grammar> {
let mut grammar = Grammar {
name: agrammar.name,
rules: HashMap::with_capacity(agrammar.rules.len()),
rust_functions: agrammar.rust_functions,
rust_items: agrammar.rust_items,
attributes: agrammar.attributes
};
InferenceEngine::infer(&mu... | type_inference | identifier_name |
buffer.rs | use std::io;
use crossbeam::sync::MsQueue;
// Ensures that we have enough buffers to keep workers busy.
const TOTAL_BUFFERS_MULTIPLICATIVE: usize = 2;
const TOTAL_BUFFERS_ADDITIVE: usize = 0;
/// Stores a set number of piece buffers to be used and re-used.
pub struct PieceBuffers {
piece_queue: MsQueue<PieceBuff... | (num_workers: usize) -> usize {
num_workers * TOTAL_BUFFERS_MULTIPLICATIVE + TOTAL_BUFFERS_ADDITIVE
}
// ----------------------------------------------------------------------------//
/// Piece buffer that can be filled up until it contains a full piece.
#[derive(PartialEq, Eq)]
pub struct PieceBuffer {
buffe... | calculate_total_buffers | identifier_name |
buffer.rs | use std::io;
use crossbeam::sync::MsQueue;
// Ensures that we have enough buffers to keep workers busy.
const TOTAL_BUFFERS_MULTIPLICATIVE: usize = 2;
const TOTAL_BUFFERS_ADDITIVE: usize = 0;
/// Stores a set number of piece buffers to be used and re-used.
pub struct PieceBuffers {
piece_queue: MsQueue<PieceBuff... |
}
/// Calculates the optimal number of piece buffers given the number of workers.
fn calculate_total_buffers(num_workers: usize) -> usize {
num_workers * TOTAL_BUFFERS_MULTIPLICATIVE + TOTAL_BUFFERS_ADDITIVE
}
// ----------------------------------------------------------------------------//
/// Piece buffer tha... | {
self.piece_queue.pop()
} | identifier_body |
buffer.rs | use std::io;
use crossbeam::sync::MsQueue;
// Ensures that we have enough buffers to keep workers busy.
const TOTAL_BUFFERS_MULTIPLICATIVE: usize = 2;
const TOTAL_BUFFERS_ADDITIVE: usize = 0;
/// Stores a set number of piece buffers to be used and re-used.
pub struct PieceBuffers {
piece_queue: MsQueue<PieceBuff... | PieceBuffers { piece_queue: piece_queue }
}
/// Checkin the given piece buffer to be re-used.
pub fn checkin(&self, mut buffer: PieceBuffer) {
buffer.bytes_read = 0;
self.piece_queue.push(buffer);
}
/// Checkout a piece buffer (possibly blocking) to be used.
pub fn che... | }
| random_line_split |
day_10.rs | pub use tdd_kata::stack_kata::day_10::Stack;
describe! stack_tests {
before_each {
let mut stack: Stack<i32> = Stack::new(20);
}
it "should create a new empty stack" {
assert_eq!(stack.size(), 0);
assert!(stack.is_empty());
}
it "should increase stack size when push into ... |
it "should decrease stack size when pop from it" {
stack.push(20);
let old_size = stack.size();
stack.pop();
assert_eq!(stack.size(), old_size - 1);
}
it "should pop value that was pushed into the stack" {
stack.push(20);
assert_eq!(stack.pop(), Some(20));... | } | random_line_split |
commands.rs | #![allow(dead_code)]
extern crate jam;
extern crate cgmath;
extern crate time;
extern crate glutin;
extern crate image;
extern crate gfx_device_gl;
#[macro_use]
extern crate aphid;
use std::f64::consts::PI;
use std::path::{Path, PathBuf};
use cgmath::Rad;
use aphid::{HashSet, Seconds};
use jam::color;
use jam::{Ve... | (&self) -> GeometryTesselator {
let upp = self.units_per_point();
let tesselator_scale = Vec3::new(upp, upp, upp);
GeometryTesselator::new(tesselator_scale)
}
fn update(&mut self, input_state:&InputState, dimensions:Dimensions, delta_time: Seconds) {
use glutin::VirtualKeyCode;
... | tesselator | identifier_name |
commands.rs | #![allow(dead_code)]
extern crate jam;
extern crate cgmath;
extern crate time;
extern crate glutin;
extern crate image;
extern crate gfx_device_gl;
#[macro_use]
extern crate aphid;
use std::f64::consts::PI;
use std::path::{Path, PathBuf};
use cgmath::Rad;
use aphid::{HashSet, Seconds};
use jam::color;
use jam::{Ve... | }
fn units_per_point(&self) -> f64 {
1.0 / self.points_per_unit
}
fn tesselator(&self) -> GeometryTesselator {
let upp = self.units_per_point();
let tesselator_scale = Vec3::new(upp, upp, upp);
GeometryTesselator::new(tesselator_scale)
}
fn update(&mut self, i... | {
let mut last_time = time::precise_time_ns();
'main: loop {
let (dimensions, input_state) = self.renderer.begin_frame(rgb(132, 193, 255));
if input_state.close {
break;
}
// println!("dimensions -> {:?}", dimensions);
let time... | identifier_body |
commands.rs | #![allow(dead_code)]
extern crate jam;
extern crate cgmath;
extern crate time;
extern crate glutin;
extern crate image;
extern crate gfx_device_gl;
#[macro_use]
extern crate aphid;
use std::f64::consts::PI;
use std::path::{Path, PathBuf};
use cgmath::Rad;
use aphid::{HashSet, Seconds};
use jam::color;
use jam::{Ve... |
}
}
// draw ui text
// if let Some((font, layer)) = self.renderer.get_font(&font_description) {
// // println!("ok we got a font to use to draw layer -> {:?}", layer);
// let scale = 1.0 / self.camera.viewport.scale();
// let mut t = GeometryTessela... | {
let blend = match rem {
0 => Blend::Alpha,
1 => Blend::Add,
_ => Blend::None,
};
self.renderer.draw(geo, Uniforms {
transform: down_size_m4(self.camera.view_pr... | conditional_block |
commands.rs | #![allow(dead_code)]
extern crate jam;
extern crate cgmath;
extern crate time;
extern crate glutin;
extern crate image;
extern crate gfx_device_gl;
#[macro_use]
extern crate aphid;
use std::f64::consts::PI;
use std::path::{Path, PathBuf};
use cgmath::Rad;
use aphid::{HashSet, Seconds};
use jam::color;
use jam::{Ve... | //
// frame.draw_vertices(&vertices, Uniforms {
// transform : down_size_m4(self.camera.ui_projection().into()),
// color: color::WHITE,
// }, Blend::Alpha);
// }
self.renderer.finish_frame().expect("a finished frame");
Ok(())
}
}
fn rast... | // ); | random_line_split |
stats.rs | use clap::ArgMatches;
use chrono::Local;
use serde_json;
use serde::ser::{MapVisitor, Serialize, Serializer};
use ilc_base;
use ilc_ops::stats::Stats;
use Environment;
use Cli;
use error;
struct StatFormat {
version: String,
master_hash: Option<String>,
time: String,
stats: Stats,
}
impl Serialize ... | }
}
pub fn output_as_json(args: &ArgMatches, cli: &Cli, stats: Stats) -> ilc_base::Result<()> {
let e = Environment(args);
// let count = value_t!(args, "count", usize).unwrap_or(usize::MAX);
// let mut stats: Vec<(String, Person)> = stats.into_iter().collect();
// stats.sort_by(|&(_, ref a), &(_... | {
struct Visitor<'a>(&'a StatFormat);
impl<'a> MapVisitor for Visitor<'a> {
fn visit<S>(&mut self, s: &mut S) -> Result<Option<()>, S::Error>
where S: Serializer
{
try!(s.serialize_struct_elt("version", &self.0.version));
if let &So... | identifier_body |
stats.rs | use clap::ArgMatches;
use chrono::Local;
use serde_json;
use serde::ser::{MapVisitor, Serialize, Serializer};
use ilc_base;
use ilc_ops::stats::Stats;
use Environment;
use Cli;
use error;
struct StatFormat {
version: String,
master_hash: Option<String>,
time: String,
stats: Stats,
}
impl Serialize ... |
try!(s.serialize_struct_elt("time", &self.0.time));
try!(s.serialize_struct_elt("stats", &self.0.stats));
Ok(None)
}
fn len(&self) -> Option<usize> {
Some(4)
}
}
s.serialize_struct("StatFormat", Visitor... | {
try!(s.serialize_struct_elt("master_hash", h));
} | conditional_block |
stats.rs | use clap::ArgMatches;
use chrono::Local;
use serde_json;
use serde::ser::{MapVisitor, Serialize, Serializer};
use ilc_base;
use ilc_ops::stats::Stats;
use Environment;
use Cli;
use error;
struct StatFormat {
version: String,
master_hash: Option<String>,
time: String,
stats: Stats,
}
impl Serialize ... | <S>(&self, s: &mut S) -> Result<(), S::Error>
where S: Serializer
{
struct Visitor<'a>(&'a StatFormat);
impl<'a> MapVisitor for Visitor<'a> {
fn visit<S>(&mut self, s: &mut S) -> Result<Option<()>, S::Error>
where S: Serializer
{
try!(s... | serialize | identifier_name |
stats.rs | use clap::ArgMatches; |
use serde_json;
use serde::ser::{MapVisitor, Serialize, Serializer};
use ilc_base;
use ilc_ops::stats::Stats;
use Environment;
use Cli;
use error;
struct StatFormat {
version: String,
master_hash: Option<String>,
time: String,
stats: Stats,
}
impl Serialize for StatFormat {
fn serialize<S>(&self... |
use chrono::Local; | random_line_split |
mir.rs | /// ///////////////////////////////////////////////////////////////////////////
/// File: Annealing/Solver/MIPS.rs
/// ///////////////////////////////////////////////////////////////////////////
/// Copyright 2017 Giovanni Mazzeo
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may no... | // given by the user and by other num_workers-1 states generated in a random way
let mut initial_state = problem.initial_state();
let mut initial_states_pool = common::StatesPool::new();
initial_states_pool.push(initial_state.clone());
for i in 1..num_workers {
initia... | {
let cooler = StepsCooler {
max_steps: self.tuner_params.max_step,
min_temp: self.tuner_params.min_temp.unwrap(),
max_temp: self.tuner_params.max_temp.unwrap(),
};
("{}",Green.paint("\n-----------------------------------------------------------------------... | identifier_body |
mir.rs | /// ///////////////////////////////////////////////////////////////////////////
/// File: Annealing/Solver/MIPS.rs
/// ///////////////////////////////////////////////////////////////////////////
/// Copyright 2017 Giovanni Mazzeo
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may no... | (&mut self, problem: &mut Problem, num_workers: usize) -> MrResult {
let cooler = StepsCooler {
max_steps: self.tuner_params.max_step,
min_temp: self.tuner_params.min_temp.unwrap(),
max_temp: self.tuner_params.max_temp.unwrap(),
};
("{}",Green.paint("\n----... | solve | identifier_name |
mir.rs | /// ///////////////////////////////////////////////////////////////////////////
/// File: Annealing/Solver/MIPS.rs
/// ///////////////////////////////////////////////////////////////////////////
/// Copyright 2017 Giovanni Mazzeo
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may no... | worker_nrg,
last_nrg);
println!("{}",Green.paint("-------------------------------------------------------------------------------------------------------------------------------------------------------"));
pb.message(&format!("TID [{}] - Sta... | random_line_split | |
cli.rs | extern crate tetrs;
use std::io::prelude::*;
// FIXME! Little hack to clear the screen :)
extern "C" { fn system(s: *const u8); }
fn clear_screen() { unsafe {
system("@clear||cls\0".as_ptr());
}}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum Input {
None,
Left,
Right,
RotateCW,
RotateCCW,
SoftDrop,
HardD... |
fn bot(state: &mut tetrs::State) -> bool {
let weights = tetrs::Weights::default();
let bot = tetrs::PlayI::play(&weights, state.well(), *state.player().unwrap());
if bot.play.len() == 0 {
state.hard_drop();
return false;
}
let mut result = true;
for play in bot.play {
use tetrs::Play;
result &= match p... | {
print!(">>> ");
std::io::stdout().flush().unwrap();
let mut action = String::new();
std::io::stdin().read_line(&mut action).unwrap();
match &*action.trim().to_uppercase() {
"" => Input::None,
"A" | "Q" | "LEFT" => Input::Left,
"D" | "RIGHT" => Input::Right,
"CW" | "RR" | "ROT" => Input::RotateCW,
"CCW"... | identifier_body |
cli.rs | extern crate tetrs;
use std::io::prelude::*;
// FIXME! Little hack to clear the screen :)
extern "C" { fn system(s: *const u8); }
fn clear_screen() { unsafe {
system("@clear||cls\0".as_ptr());
}}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum | {
None,
Left,
Right,
RotateCW,
RotateCCW,
SoftDrop,
HardDrop,
Gravity,
Quit,
Help,
Invalid,
}
fn input() -> Input {
print!(">>> ");
std::io::stdout().flush().unwrap();
let mut action = String::new();
std::io::stdin().read_line(&mut action).unwrap();
match &*action.trim().to_uppercase() {
"" => Input:... | Input | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.