file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
interval.rs
//! Support for creating futures that represent intervals. //! //! This module contains the `Interval` type which is a stream that will //! resolve at a fixed intervals in future use std::io; use std::time::{Duration, Instant}; use futures::{Poll, Async}; use futures::stream::{Stream}; use reactor::{Remote, Handle}; use reactor::timeout_token::TimeoutToken; /// A stream representing notifications at fixed interval /// /// Intervals are created through the `Interval::new` or /// `Interval::new_at` methods indicating when a first notification /// should be triggered and when it will be repeated. /// /// Note that timeouts are not intended for high resolution timers, but rather /// they will likely fire some granularity after the exact instant that they're /// otherwise indicated to fire at. pub struct Interval { token: TimeoutToken, next: Instant, interval: Duration, handle: Remote, } impl Interval { /// Creates a new interval which will fire at `dur` time into the future, /// and will repeat every `dur` interval after /// /// This function will return a future that will resolve to the actual /// interval object. The interval object itself is then a stream which will /// be set to fire at the specified intervals pub fn new(dur: Duration, handle: &Handle) -> io::Result<Interval> { Interval::new_at(Instant::now() + dur, dur, handle) } /// Creates a new interval which will fire at the time specified by `at`, /// and then will repeat every `dur` interval after /// /// This function will return a future that will resolve to the actual /// timeout object. The timeout object itself is then a future which will be /// set to fire at the specified point in the future. pub fn new_at(at: Instant, dur: Duration, handle: &Handle) -> io::Result<Interval> { Ok(Interval { token: try!(TimeoutToken::new(at, &handle)), next: at, interval: dur, handle: handle.remote().clone(), }) } } impl Stream for Interval { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll<Option<()>, io::Error> { // TODO: is this fast enough? let now = Instant::now(); if self.next <= now
else { self.token.update_timeout(&self.handle); Ok(Async::NotReady) } } } impl Drop for Interval { fn drop(&mut self) { self.token.cancel_timeout(&self.handle); } } /// Converts Duration object to raw nanoseconds if possible /// /// This is useful to divide intervals. /// /// While technically for large duration it's impossible to represent any /// duration as nanoseconds, the largest duration we can represent is about /// 427_000 years. Large enough for any interval we would use or calculate in /// tokio. fn duration_to_nanos(dur: Duration) -> Option<u64> { dur.as_secs() .checked_mul(1_000_000_000) .and_then(|v| v.checked_add(dur.subsec_nanos() as u64)) } fn next_interval(prev: Instant, now: Instant, interval: Duration) -> Instant { let new = prev + interval; if new > now { return new; } else { let spent_ns = duration_to_nanos(now.duration_since(prev)) .expect("interval should be expired"); let interval_ns = duration_to_nanos(interval) .expect("interval is less that 427 thousand years"); let mult = spent_ns/interval_ns + 1; assert!(mult < (1 << 32), "can't skip more than 4 billion intervals of {:?} \ (trying to skip {})", interval, mult); return prev + interval * (mult as u32); } } #[cfg(test)] mod test { use std::time::{Instant, Duration}; use super::next_interval; struct Timeline(Instant); impl Timeline { fn new() -> Timeline { Timeline(Instant::now()) } fn at(&self, millis: u64) -> Instant { self.0 + Duration::from_millis(millis) } fn at_ns(&self, sec: u64, nanos: u32) -> Instant { self.0 + Duration::new(sec, nanos) } } fn dur(millis: u64) -> Duration { Duration::from_millis(millis) } #[test] fn norm_next() { let tm = Timeline::new(); assert_eq!(next_interval(tm.at(1), tm.at(2), dur(10)), tm.at(11)); assert_eq!(next_interval(tm.at(7777), tm.at(7788), dur(100)), tm.at(7877)); assert_eq!(next_interval(tm.at(1), tm.at(1000), dur(2100)), tm.at(2101)); } #[test] fn fast_forward() { let tm = Timeline::new(); assert_eq!(next_interval(tm.at(1), tm.at(1000), dur(10)), tm.at(1001)); assert_eq!(next_interval(tm.at(7777), tm.at(8888), dur(100)), tm.at(8977)); assert_eq!(next_interval(tm.at(1), tm.at(10000), dur(2100)), tm.at(10501)); } /// TODO: this test actually should be successful, but since we can't /// multiply Duration on anything larger than u32 easily we decided /// to allow thit to fail for now #[test] #[should_panic(expected = "can't skip more than 4 billion intervals")] fn large_skip() { let tm = Timeline::new(); assert_eq!(next_interval( tm.at_ns(0, 1), tm.at_ns(25, 0), Duration::new(0, 2)), tm.at_ns(25, 1)); } }
{ self.next = next_interval(self.next, now, self.interval); self.token.reset_timeout(self.next, &self.handle); Ok(Async::Ready(Some(()))) }
conditional_block
interval.rs
//! Support for creating futures that represent intervals. //! //! This module contains the `Interval` type which is a stream that will //! resolve at a fixed intervals in future use std::io; use std::time::{Duration, Instant}; use futures::{Poll, Async}; use futures::stream::{Stream}; use reactor::{Remote, Handle}; use reactor::timeout_token::TimeoutToken; /// A stream representing notifications at fixed interval /// /// Intervals are created through the `Interval::new` or /// `Interval::new_at` methods indicating when a first notification /// should be triggered and when it will be repeated. /// /// Note that timeouts are not intended for high resolution timers, but rather
/// otherwise indicated to fire at. pub struct Interval { token: TimeoutToken, next: Instant, interval: Duration, handle: Remote, } impl Interval { /// Creates a new interval which will fire at `dur` time into the future, /// and will repeat every `dur` interval after /// /// This function will return a future that will resolve to the actual /// interval object. The interval object itself is then a stream which will /// be set to fire at the specified intervals pub fn new(dur: Duration, handle: &Handle) -> io::Result<Interval> { Interval::new_at(Instant::now() + dur, dur, handle) } /// Creates a new interval which will fire at the time specified by `at`, /// and then will repeat every `dur` interval after /// /// This function will return a future that will resolve to the actual /// timeout object. The timeout object itself is then a future which will be /// set to fire at the specified point in the future. pub fn new_at(at: Instant, dur: Duration, handle: &Handle) -> io::Result<Interval> { Ok(Interval { token: try!(TimeoutToken::new(at, &handle)), next: at, interval: dur, handle: handle.remote().clone(), }) } } impl Stream for Interval { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll<Option<()>, io::Error> { // TODO: is this fast enough? let now = Instant::now(); if self.next <= now { self.next = next_interval(self.next, now, self.interval); self.token.reset_timeout(self.next, &self.handle); Ok(Async::Ready(Some(()))) } else { self.token.update_timeout(&self.handle); Ok(Async::NotReady) } } } impl Drop for Interval { fn drop(&mut self) { self.token.cancel_timeout(&self.handle); } } /// Converts Duration object to raw nanoseconds if possible /// /// This is useful to divide intervals. /// /// While technically for large duration it's impossible to represent any /// duration as nanoseconds, the largest duration we can represent is about /// 427_000 years. Large enough for any interval we would use or calculate in /// tokio. fn duration_to_nanos(dur: Duration) -> Option<u64> { dur.as_secs() .checked_mul(1_000_000_000) .and_then(|v| v.checked_add(dur.subsec_nanos() as u64)) } fn next_interval(prev: Instant, now: Instant, interval: Duration) -> Instant { let new = prev + interval; if new > now { return new; } else { let spent_ns = duration_to_nanos(now.duration_since(prev)) .expect("interval should be expired"); let interval_ns = duration_to_nanos(interval) .expect("interval is less that 427 thousand years"); let mult = spent_ns/interval_ns + 1; assert!(mult < (1 << 32), "can't skip more than 4 billion intervals of {:?} \ (trying to skip {})", interval, mult); return prev + interval * (mult as u32); } } #[cfg(test)] mod test { use std::time::{Instant, Duration}; use super::next_interval; struct Timeline(Instant); impl Timeline { fn new() -> Timeline { Timeline(Instant::now()) } fn at(&self, millis: u64) -> Instant { self.0 + Duration::from_millis(millis) } fn at_ns(&self, sec: u64, nanos: u32) -> Instant { self.0 + Duration::new(sec, nanos) } } fn dur(millis: u64) -> Duration { Duration::from_millis(millis) } #[test] fn norm_next() { let tm = Timeline::new(); assert_eq!(next_interval(tm.at(1), tm.at(2), dur(10)), tm.at(11)); assert_eq!(next_interval(tm.at(7777), tm.at(7788), dur(100)), tm.at(7877)); assert_eq!(next_interval(tm.at(1), tm.at(1000), dur(2100)), tm.at(2101)); } #[test] fn fast_forward() { let tm = Timeline::new(); assert_eq!(next_interval(tm.at(1), tm.at(1000), dur(10)), tm.at(1001)); assert_eq!(next_interval(tm.at(7777), tm.at(8888), dur(100)), tm.at(8977)); assert_eq!(next_interval(tm.at(1), tm.at(10000), dur(2100)), tm.at(10501)); } /// TODO: this test actually should be successful, but since we can't /// multiply Duration on anything larger than u32 easily we decided /// to allow thit to fail for now #[test] #[should_panic(expected = "can't skip more than 4 billion intervals")] fn large_skip() { let tm = Timeline::new(); assert_eq!(next_interval( tm.at_ns(0, 1), tm.at_ns(25, 0), Duration::new(0, 2)), tm.at_ns(25, 1)); } }
/// they will likely fire some granularity after the exact instant that they're
random_line_split
location.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::LocationBinding; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::window::Window; use page::Page; use servo_util::str::DOMString; use serialize::{Encoder, Encodable}; use std::rc::Rc; use url::query_to_str; #[deriving(Encodable)] pub struct Location { reflector_: Reflector, //XXXjdm cycle: window->Location->window page: Rc<Page>, } impl Location { pub fn new_inherited(page: Rc<Page>) -> Location { Location { reflector_: Reflector::new(), page: page } } pub fn new(window: &JSRef<Window>, page: Rc<Page>) -> Temporary<Location> { reflect_dom_object(box Location::new_inherited(page), window, LocationBinding::Wrap) } } pub trait LocationMethods { fn Href(&self) -> DOMString; fn Search(&self) -> DOMString; } impl<'a> LocationMethods for JSRef<'a, Location> { fn Href(&self) -> DOMString { self.page.get_url().to_str() } fn Search(&self) -> DOMString { let query = query_to_str(&self.page.get_url().query); if query.as_slice() == ""
else { "?".to_string().append(query.as_slice()) } } } impl Reflectable for Location { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } }
{ query }
conditional_block
location.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::LocationBinding; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::window::Window; use page::Page; use servo_util::str::DOMString; use serialize::{Encoder, Encodable}; use std::rc::Rc; use url::query_to_str; #[deriving(Encodable)] pub struct Location { reflector_: Reflector, //XXXjdm cycle: window->Location->window page: Rc<Page>, } impl Location { pub fn new_inherited(page: Rc<Page>) -> Location { Location { reflector_: Reflector::new(), page: page } } pub fn new(window: &JSRef<Window>, page: Rc<Page>) -> Temporary<Location> { reflect_dom_object(box Location::new_inherited(page), window, LocationBinding::Wrap) } } pub trait LocationMethods { fn Href(&self) -> DOMString; fn Search(&self) -> DOMString; } impl<'a> LocationMethods for JSRef<'a, Location> { fn Href(&self) -> DOMString { self.page.get_url().to_str() } fn
(&self) -> DOMString { let query = query_to_str(&self.page.get_url().query); if query.as_slice() == "" { query } else { "?".to_string().append(query.as_slice()) } } } impl Reflectable for Location { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } }
Search
identifier_name
location.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::LocationBinding; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::window::Window; use page::Page; use servo_util::str::DOMString; use serialize::{Encoder, Encodable}; use std::rc::Rc; use url::query_to_str; #[deriving(Encodable)] pub struct Location { reflector_: Reflector, //XXXjdm cycle: window->Location->window page: Rc<Page>, } impl Location { pub fn new_inherited(page: Rc<Page>) -> Location {
pub fn new(window: &JSRef<Window>, page: Rc<Page>) -> Temporary<Location> { reflect_dom_object(box Location::new_inherited(page), window, LocationBinding::Wrap) } } pub trait LocationMethods { fn Href(&self) -> DOMString; fn Search(&self) -> DOMString; } impl<'a> LocationMethods for JSRef<'a, Location> { fn Href(&self) -> DOMString { self.page.get_url().to_str() } fn Search(&self) -> DOMString { let query = query_to_str(&self.page.get_url().query); if query.as_slice() == "" { query } else { "?".to_string().append(query.as_slice()) } } } impl Reflectable for Location { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } }
Location { reflector_: Reflector::new(), page: page } }
random_line_split
location.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::LocationBinding; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::window::Window; use page::Page; use servo_util::str::DOMString; use serialize::{Encoder, Encodable}; use std::rc::Rc; use url::query_to_str; #[deriving(Encodable)] pub struct Location { reflector_: Reflector, //XXXjdm cycle: window->Location->window page: Rc<Page>, } impl Location { pub fn new_inherited(page: Rc<Page>) -> Location { Location { reflector_: Reflector::new(), page: page } } pub fn new(window: &JSRef<Window>, page: Rc<Page>) -> Temporary<Location> { reflect_dom_object(box Location::new_inherited(page), window, LocationBinding::Wrap) } } pub trait LocationMethods { fn Href(&self) -> DOMString; fn Search(&self) -> DOMString; } impl<'a> LocationMethods for JSRef<'a, Location> { fn Href(&self) -> DOMString
fn Search(&self) -> DOMString { let query = query_to_str(&self.page.get_url().query); if query.as_slice() == "" { query } else { "?".to_string().append(query.as_slice()) } } } impl Reflectable for Location { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } }
{ self.page.get_url().to_str() }
identifier_body
main.rs
extern crate chrono; #[macro_use] extern crate derive_builder; extern crate fern; extern crate inflector; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate rand; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate anyhow; extern crate clap; extern crate serde_json; extern crate spade; extern crate statrs; extern crate toml; mod config; mod economy; mod entities; mod game; mod generators; mod resources; mod simulator; mod utils; use anyhow::Result; use clap::{AppSettings, Clap}; use log::LevelFilter; use std::{fs::File, io, io::Read}; fn main() { // Init logger setup_logger().unwrap(); // Parse the command line. let opts: Opts = Opts::parse(); match opts.subcmd { SubCommand::NewGame(t) => { // Display title. let title = include_str!("../res/title.txt"); println!("{}", title); // Gets a value for config if supplied by user, or defaults to "genconfig.toml" let config = match parse_config(&t.config_path) { Ok(config) => config, Err(e) => { warn!( "Failed to get specified config at {}: due to {}. Using default", &t.config_path, e ); config::GameConfig::default() } }; // Start simulator let mut simulator = simulator::Simulator::new(config); simulator.new_game(); } } // TODO: Implement the rest of the program. } /// This doc string acts as a help message when the user runs '--help' /// as do all doc strings on fields #[derive(Clap)] #[clap(version = "1.0", author = "Viktor H. <viktor.holmgren@gmail.com>")] #[clap(setting = AppSettings::ColoredHelp)] struct Opts { /// A level of verbosity, and can be used multiple times #[clap(short, long, parse(from_occurrences))] verbose: i32, #[clap(subcommand)] subcmd: SubCommand, } #[derive(Clap)] enum SubCommand { #[clap(version = "1.3", author = "Viktor H. <viktor.holmgren@gmail.com>")] NewGame(NewGame), //TODO: Add additional subcommands; serve (for server) etc. } /// Subcommand for generating a new world. #[derive(Clap)] struct NewGame { #[clap(short, long, default_value = "genconfig.toml")] config_path: String, } /// Try parse the Generation Config at the specified path. fn parse_config(path: &str) -> Result<config::GameConfig> { let mut file = File::open(&path)?; let mut file_content = String::new(); file.read_to_string(&mut file_content)?; let config: config::GameConfig = toml::from_str(&file_content)?; Ok(config) } pub fn setup_logger() -> Result<()>
{ fern::Dispatch::new() .format(|out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message )) }) .level(log::LevelFilter::Off) .level_for("gemini", LevelFilter::Trace) .chain(io::stdout()) .apply()?; Ok(()) }
identifier_body
main.rs
extern crate chrono; #[macro_use] extern crate derive_builder; extern crate fern; extern crate inflector; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate rand; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate anyhow; extern crate clap; extern crate serde_json; extern crate spade; extern crate statrs; extern crate toml; mod config; mod economy; mod entities; mod game; mod generators; mod resources; mod simulator; mod utils; use anyhow::Result; use clap::{AppSettings, Clap}; use log::LevelFilter; use std::{fs::File, io, io::Read}; fn main() { // Init logger setup_logger().unwrap(); // Parse the command line. let opts: Opts = Opts::parse(); match opts.subcmd { SubCommand::NewGame(t) => { // Display title. let title = include_str!("../res/title.txt"); println!("{}", title); // Gets a value for config if supplied by user, or defaults to "genconfig.toml" let config = match parse_config(&t.config_path) { Ok(config) => config, Err(e) => { warn!( "Failed to get specified config at {}: due to {}. Using default", &t.config_path, e ); config::GameConfig::default() } }; // Start simulator let mut simulator = simulator::Simulator::new(config);
} /// This doc string acts as a help message when the user runs '--help' /// as do all doc strings on fields #[derive(Clap)] #[clap(version = "1.0", author = "Viktor H. <viktor.holmgren@gmail.com>")] #[clap(setting = AppSettings::ColoredHelp)] struct Opts { /// A level of verbosity, and can be used multiple times #[clap(short, long, parse(from_occurrences))] verbose: i32, #[clap(subcommand)] subcmd: SubCommand, } #[derive(Clap)] enum SubCommand { #[clap(version = "1.3", author = "Viktor H. <viktor.holmgren@gmail.com>")] NewGame(NewGame), //TODO: Add additional subcommands; serve (for server) etc. } /// Subcommand for generating a new world. #[derive(Clap)] struct NewGame { #[clap(short, long, default_value = "genconfig.toml")] config_path: String, } /// Try parse the Generation Config at the specified path. fn parse_config(path: &str) -> Result<config::GameConfig> { let mut file = File::open(&path)?; let mut file_content = String::new(); file.read_to_string(&mut file_content)?; let config: config::GameConfig = toml::from_str(&file_content)?; Ok(config) } pub fn setup_logger() -> Result<()> { fern::Dispatch::new() .format(|out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message )) }) .level(log::LevelFilter::Off) .level_for("gemini", LevelFilter::Trace) .chain(io::stdout()) .apply()?; Ok(()) }
simulator.new_game(); } } // TODO: Implement the rest of the program.
random_line_split
main.rs
extern crate chrono; #[macro_use] extern crate derive_builder; extern crate fern; extern crate inflector; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate rand; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate anyhow; extern crate clap; extern crate serde_json; extern crate spade; extern crate statrs; extern crate toml; mod config; mod economy; mod entities; mod game; mod generators; mod resources; mod simulator; mod utils; use anyhow::Result; use clap::{AppSettings, Clap}; use log::LevelFilter; use std::{fs::File, io, io::Read}; fn main() { // Init logger setup_logger().unwrap(); // Parse the command line. let opts: Opts = Opts::parse(); match opts.subcmd { SubCommand::NewGame(t) => { // Display title. let title = include_str!("../res/title.txt"); println!("{}", title); // Gets a value for config if supplied by user, or defaults to "genconfig.toml" let config = match parse_config(&t.config_path) { Ok(config) => config, Err(e) => { warn!( "Failed to get specified config at {}: due to {}. Using default", &t.config_path, e ); config::GameConfig::default() } }; // Start simulator let mut simulator = simulator::Simulator::new(config); simulator.new_game(); } } // TODO: Implement the rest of the program. } /// This doc string acts as a help message when the user runs '--help' /// as do all doc strings on fields #[derive(Clap)] #[clap(version = "1.0", author = "Viktor H. <viktor.holmgren@gmail.com>")] #[clap(setting = AppSettings::ColoredHelp)] struct Opts { /// A level of verbosity, and can be used multiple times #[clap(short, long, parse(from_occurrences))] verbose: i32, #[clap(subcommand)] subcmd: SubCommand, } #[derive(Clap)] enum
{ #[clap(version = "1.3", author = "Viktor H. <viktor.holmgren@gmail.com>")] NewGame(NewGame), //TODO: Add additional subcommands; serve (for server) etc. } /// Subcommand for generating a new world. #[derive(Clap)] struct NewGame { #[clap(short, long, default_value = "genconfig.toml")] config_path: String, } /// Try parse the Generation Config at the specified path. fn parse_config(path: &str) -> Result<config::GameConfig> { let mut file = File::open(&path)?; let mut file_content = String::new(); file.read_to_string(&mut file_content)?; let config: config::GameConfig = toml::from_str(&file_content)?; Ok(config) } pub fn setup_logger() -> Result<()> { fern::Dispatch::new() .format(|out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message )) }) .level(log::LevelFilter::Off) .level_for("gemini", LevelFilter::Trace) .chain(io::stdout()) .apply()?; Ok(()) }
SubCommand
identifier_name
main.rs
extern crate serenity; use serenity::prelude::*; use serenity::model::*; use std::env; // Serenity implements transparent sharding in a way that you do not need to // manually handle separate processes or connections manually. // // Transparent sharding is useful for a shared cache. Instead of having caches // with duplicated data, a shared cache means all your data can be easily // accessible across all shards. // // If your bot is on many guilds - or over the maximum of 2500 - then you // should/must use guild sharding. // // This is an example file showing how guild sharding works. For this to // properly be able to be seen in effect, your bot should be in at least 2 // guilds. // // Taking a scenario of 2 guilds, try saying "!ping" in one guild. It should // print either "0" or "1" in the console. Saying "!ping" in the other guild, // it should cache the other number in the console. This confirms that guild // sharding works. struct Handler; impl EventHandler for Handler { fn
(&self, ctx: Context, msg: Message) { if msg.content == "!ping" { // The current shard needs to be unlocked so it can be read from, as // multiple threads may otherwise attempt to read from or mutate it // concurrently. { let shard = ctx.shard.lock(); let shard_info = shard.shard_info(); println!("Shard {}", shard_info[0]); } if let Err(why) = msg.channel_id.say("Pong!") { println!("Error sending message: {:?}", why); } } } fn on_ready(&self, _: Context, ready: Ready) { println!("{} is connected!", ready.user.name); } } fn main() { // Configure the client with your Discord bot token in the environment. let token = env::var("DISCORD_TOKEN") .expect("Expected a token in the environment"); let mut client = Client::new(&token, Handler); // The total number of shards to use. The "current shard number" of a // shard - that is, the shard it is assigned to - is indexed at 0, // while the total shard count is indexed at 1. // // This means if you have 5 shards, your total shard count will be 5, while // each shard will be assigned numbers 0 through 4. if let Err(why) = client.start_shards(2) { println!("Client error: {:?}", why); } }
on_message
identifier_name
main.rs
extern crate serenity; use serenity::prelude::*; use serenity::model::*; use std::env; // Serenity implements transparent sharding in a way that you do not need to // manually handle separate processes or connections manually. // // Transparent sharding is useful for a shared cache. Instead of having caches // with duplicated data, a shared cache means all your data can be easily // accessible across all shards. // // If your bot is on many guilds - or over the maximum of 2500 - then you // should/must use guild sharding. // // This is an example file showing how guild sharding works. For this to // properly be able to be seen in effect, your bot should be in at least 2 // guilds. // // Taking a scenario of 2 guilds, try saying "!ping" in one guild. It should // print either "0" or "1" in the console. Saying "!ping" in the other guild, // it should cache the other number in the console. This confirms that guild // sharding works. struct Handler; impl EventHandler for Handler { fn on_message(&self, ctx: Context, msg: Message) { if msg.content == "!ping" { // The current shard needs to be unlocked so it can be read from, as // multiple threads may otherwise attempt to read from or mutate it // concurrently. { let shard = ctx.shard.lock(); let shard_info = shard.shard_info(); println!("Shard {}", shard_info[0]); } if let Err(why) = msg.channel_id.say("Pong!") { println!("Error sending message: {:?}", why); } } } fn on_ready(&self, _: Context, ready: Ready)
} fn main() { // Configure the client with your Discord bot token in the environment. let token = env::var("DISCORD_TOKEN") .expect("Expected a token in the environment"); let mut client = Client::new(&token, Handler); // The total number of shards to use. The "current shard number" of a // shard - that is, the shard it is assigned to - is indexed at 0, // while the total shard count is indexed at 1. // // This means if you have 5 shards, your total shard count will be 5, while // each shard will be assigned numbers 0 through 4. if let Err(why) = client.start_shards(2) { println!("Client error: {:?}", why); } }
{ println!("{} is connected!", ready.user.name); }
identifier_body
main.rs
extern crate serenity; use serenity::prelude::*; use serenity::model::*; use std::env; // Serenity implements transparent sharding in a way that you do not need to // manually handle separate processes or connections manually. // // Transparent sharding is useful for a shared cache. Instead of having caches // with duplicated data, a shared cache means all your data can be easily // accessible across all shards. // // If your bot is on many guilds - or over the maximum of 2500 - then you // should/must use guild sharding. // // This is an example file showing how guild sharding works. For this to // properly be able to be seen in effect, your bot should be in at least 2 // guilds. // // Taking a scenario of 2 guilds, try saying "!ping" in one guild. It should // print either "0" or "1" in the console. Saying "!ping" in the other guild, // it should cache the other number in the console. This confirms that guild // sharding works. struct Handler; impl EventHandler for Handler { fn on_message(&self, ctx: Context, msg: Message) { if msg.content == "!ping" { // The current shard needs to be unlocked so it can be read from, as // multiple threads may otherwise attempt to read from or mutate it // concurrently. { let shard = ctx.shard.lock(); let shard_info = shard.shard_info(); println!("Shard {}", shard_info[0]); } if let Err(why) = msg.channel_id.say("Pong!") { println!("Error sending message: {:?}", why); } } } fn on_ready(&self, _: Context, ready: Ready) { println!("{} is connected!", ready.user.name); } } fn main() { // Configure the client with your Discord bot token in the environment. let token = env::var("DISCORD_TOKEN") .expect("Expected a token in the environment"); let mut client = Client::new(&token, Handler); // The total number of shards to use. The "current shard number" of a // shard - that is, the shard it is assigned to - is indexed at 0, // while the total shard count is indexed at 1. // // This means if you have 5 shards, your total shard count will be 5, while // each shard will be assigned numbers 0 through 4. if let Err(why) = client.start_shards(2)
}
{ println!("Client error: {:?}", why); }
conditional_block
main.rs
extern crate serenity; use serenity::prelude::*; use serenity::model::*; use std::env; // Serenity implements transparent sharding in a way that you do not need to // manually handle separate processes or connections manually. // // Transparent sharding is useful for a shared cache. Instead of having caches // with duplicated data, a shared cache means all your data can be easily // accessible across all shards. // // If your bot is on many guilds - or over the maximum of 2500 - then you // should/must use guild sharding. // // This is an example file showing how guild sharding works. For this to // properly be able to be seen in effect, your bot should be in at least 2 // guilds. // // Taking a scenario of 2 guilds, try saying "!ping" in one guild. It should // print either "0" or "1" in the console. Saying "!ping" in the other guild, // it should cache the other number in the console. This confirms that guild // sharding works. struct Handler; impl EventHandler for Handler {
if msg.content == "!ping" { // The current shard needs to be unlocked so it can be read from, as // multiple threads may otherwise attempt to read from or mutate it // concurrently. { let shard = ctx.shard.lock(); let shard_info = shard.shard_info(); println!("Shard {}", shard_info[0]); } if let Err(why) = msg.channel_id.say("Pong!") { println!("Error sending message: {:?}", why); } } } fn on_ready(&self, _: Context, ready: Ready) { println!("{} is connected!", ready.user.name); } } fn main() { // Configure the client with your Discord bot token in the environment. let token = env::var("DISCORD_TOKEN") .expect("Expected a token in the environment"); let mut client = Client::new(&token, Handler); // The total number of shards to use. The "current shard number" of a // shard - that is, the shard it is assigned to - is indexed at 0, // while the total shard count is indexed at 1. // // This means if you have 5 shards, your total shard count will be 5, while // each shard will be assigned numbers 0 through 4. if let Err(why) = client.start_shards(2) { println!("Client error: {:?}", why); } }
fn on_message(&self, ctx: Context, msg: Message) {
random_line_split
std-smallintmap.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Microbenchmark for the smallintmap library extern mod extra; use extra::smallintmap::SmallIntMap; use std::os; use std::uint; fn append_sequential(min: uint, max: uint, map: &mut SmallIntMap<uint>) { for i in range(min, max) { map.insert(i, i + 22u); } } fn check_sequential(min: uint, max: uint, map: &SmallIntMap<uint>) { for i in range(min, max) { assert_eq!(*map.get(&i), i + 22u); } } fn
() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { ~[~"", ~"100000", ~"100"] } else if args.len() <= 1u { ~[~"", ~"10000", ~"50"] } else { args }; let max = from_str::<uint>(args[1]).unwrap(); let rep = from_str::<uint>(args[2]).unwrap(); let mut checkf = 0.0; let mut appendf = 0.0; for _ in range(0u, rep) { let mut map = SmallIntMap::new(); let start = extra::time::precise_time_s(); append_sequential(0u, max, &mut map); let mid = extra::time::precise_time_s(); check_sequential(0u, max, &map); let end = extra::time::precise_time_s(); checkf += (end - mid) as f64; appendf += (mid - start) as f64; } let maxf = max as f64; println!("insert(): {:?} seconds\n", checkf); println!(" : {} op/sec\n", maxf/checkf); println!("get() : {:?} seconds\n", appendf); println!(" : {} op/sec\n", maxf/appendf); }
main
identifier_name
std-smallintmap.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Microbenchmark for the smallintmap library extern mod extra; use extra::smallintmap::SmallIntMap; use std::os; use std::uint; fn append_sequential(min: uint, max: uint, map: &mut SmallIntMap<uint>) { for i in range(min, max) { map.insert(i, i + 22u); } } fn check_sequential(min: uint, max: uint, map: &SmallIntMap<uint>)
fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { ~[~"", ~"100000", ~"100"] } else if args.len() <= 1u { ~[~"", ~"10000", ~"50"] } else { args }; let max = from_str::<uint>(args[1]).unwrap(); let rep = from_str::<uint>(args[2]).unwrap(); let mut checkf = 0.0; let mut appendf = 0.0; for _ in range(0u, rep) { let mut map = SmallIntMap::new(); let start = extra::time::precise_time_s(); append_sequential(0u, max, &mut map); let mid = extra::time::precise_time_s(); check_sequential(0u, max, &map); let end = extra::time::precise_time_s(); checkf += (end - mid) as f64; appendf += (mid - start) as f64; } let maxf = max as f64; println!("insert(): {:?} seconds\n", checkf); println!(" : {} op/sec\n", maxf/checkf); println!("get() : {:?} seconds\n", appendf); println!(" : {} op/sec\n", maxf/appendf); }
{ for i in range(min, max) { assert_eq!(*map.get(&i), i + 22u); } }
identifier_body
std-smallintmap.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Microbenchmark for the smallintmap library extern mod extra; use extra::smallintmap::SmallIntMap; use std::os; use std::uint; fn append_sequential(min: uint, max: uint, map: &mut SmallIntMap<uint>) { for i in range(min, max) { map.insert(i, i + 22u); } } fn check_sequential(min: uint, max: uint, map: &SmallIntMap<uint>) { for i in range(min, max) { assert_eq!(*map.get(&i), i + 22u); } } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { ~[~"", ~"100000", ~"100"] } else if args.len() <= 1u { ~[~"", ~"10000", ~"50"] } else
; let max = from_str::<uint>(args[1]).unwrap(); let rep = from_str::<uint>(args[2]).unwrap(); let mut checkf = 0.0; let mut appendf = 0.0; for _ in range(0u, rep) { let mut map = SmallIntMap::new(); let start = extra::time::precise_time_s(); append_sequential(0u, max, &mut map); let mid = extra::time::precise_time_s(); check_sequential(0u, max, &map); let end = extra::time::precise_time_s(); checkf += (end - mid) as f64; appendf += (mid - start) as f64; } let maxf = max as f64; println!("insert(): {:?} seconds\n", checkf); println!(" : {} op/sec\n", maxf/checkf); println!("get() : {:?} seconds\n", appendf); println!(" : {} op/sec\n", maxf/appendf); }
{ args }
conditional_block
std-smallintmap.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Microbenchmark for the smallintmap library extern mod extra; use extra::smallintmap::SmallIntMap; use std::os; use std::uint; fn append_sequential(min: uint, max: uint, map: &mut SmallIntMap<uint>) { for i in range(min, max) { map.insert(i, i + 22u); } } fn check_sequential(min: uint, max: uint, map: &SmallIntMap<uint>) { for i in range(min, max) { assert_eq!(*map.get(&i), i + 22u); } } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { ~[~"", ~"100000", ~"100"] } else if args.len() <= 1u { ~[~"", ~"10000", ~"50"] } else { args }; let max = from_str::<uint>(args[1]).unwrap(); let rep = from_str::<uint>(args[2]).unwrap(); let mut checkf = 0.0;
append_sequential(0u, max, &mut map); let mid = extra::time::precise_time_s(); check_sequential(0u, max, &map); let end = extra::time::precise_time_s(); checkf += (end - mid) as f64; appendf += (mid - start) as f64; } let maxf = max as f64; println!("insert(): {:?} seconds\n", checkf); println!(" : {} op/sec\n", maxf/checkf); println!("get() : {:?} seconds\n", appendf); println!(" : {} op/sec\n", maxf/appendf); }
let mut appendf = 0.0; for _ in range(0u, rep) { let mut map = SmallIntMap::new(); let start = extra::time::precise_time_s();
random_line_split
SerialChart.d.ts
/** * Serial chart module. */ /** * ============================================================================ * IMPORTS * ============================================================================ * @hidden */ import { Chart, IChartProperties, IChartDataFields, IChartAdapters, IChartEvents, ChartDataItem } from "../Chart"; import { IListEvents, ListTemplate } from "../../core/utils/List";
/** * ============================================================================ * DATA ITEM * ============================================================================ * @hidden */ /** * Defines a [[DataItem]] for [[SerialChart]]. * * @see {@link DataItem} */ export declare class SerialChartDataItem extends ChartDataItem { /** * Defines a type of [[Component]] this data item is used for. */ _component: SerialChart; /** * Constructor */ constructor(); } /** * ============================================================================ * REQUISITES * ============================================================================ * @hidden */ /** * Defines data fields for [[SerialChart]]. */ export interface ISerialChartDataFields extends IChartDataFields { } /** * Defines properties for [[SerialChart]] */ export interface ISerialChartProperties extends IChartProperties { /** * A set of colors to be used for chart elements, like Series, Slices, etc. */ colors?: ColorSet; /** * A set of patterns to use for fills, like Series, Slices, etc. * * @since 4.7.5 */ patterns?: PatternSet; } /** * Defines events for [[SerialChart]]. */ export interface ISerialChartEvents extends IChartEvents { } /** * Defines adapters for [[SerialChart]]. * * @see {@link Adapter} */ export interface ISerialChartAdapters extends IChartAdapters, ISerialChartProperties { } /** * ============================================================================ * MAIN CLASS * ============================================================================ * @hidden */ /** * A base class for all series-based charts, like XY, Pie, etc. * * Is not useful on its own. * * @see {@link ISerialChartEvents} for a list of available Events * @see {@link ISerialChartAdapters} for a list of available Adapters */ export declare class SerialChart extends Chart { /** * Defines data fields. */ _dataFields: ISerialChartDataFields; /** * Defines available properties. */ _properties: ISerialChartProperties; /** * Defines available adapters. */ _adapter: ISerialChartAdapters; /** * Defines available events. */ _events: ISerialChartEvents; /** * Defines a type of series that this chart uses. */ _seriesType: Series; /** * Holds a list of [[Series]] displayed on the chart. */ protected _series: ListTemplate<this["_seriesType"]>; /** * Holds the reference to the container actual series are drawn in. */ readonly seriesContainer: Container; /** * Holds a reference to the container series' bullets are drawn in. */ readonly bulletsContainer: Container; /** * Constructor */ constructor(); dispose(): void; /** * Sets defaults that instantiate some objects that rely on parent, so they * cannot be set in constructor */ protected applyInternalDefaults(): void; /** * A list of chart's series. * * @return Chart's series */ readonly series: ListTemplate<this["_seriesType"]>; protected handleSeriesRemoved(event: IListEvents<Series>["removed"]): void; /** * Decorates a new [[Series]] object with required parameters when it is * added to the chart. * * @ignore Exclude from docs * @param event Event */ handleSeriesAdded(event: IListEvents<Series>["inserted"]): void; protected handleLegendSeriesAdded(series: Series): void; protected handleSeriesAdded2(series: Series): void; /** * Setups the legend to use the chart's data. * @ignore */ feedLegend(): void; /** * Creates and returns a new Series, suitable for this chart type. * * @return New series */ protected createSeries(): this["_seriesType"]; /** * Chart's color list. * * This list can be used by a number of serial items, like applying a new * color for each Series added. Or, applying a new color for each slice * of a Pie chart. * * Please see [[ColorSet]] for information on how you can set up to generate * unique colors. * * A theme you are using may override default pre-defined colors. * * @param value Color list */ /** * @return Color list */ colors: ColorSet; /** * A [[PatternSet]] to use when creating patterned fills for slices. * * @since 4.7.5 * @param value Pattern set */ /** * @return Pattern set */ patterns: PatternSet; /** * Copies all parameters from another [[SerialChart]]. * * @param source Source SerialChart */ copyFrom(source: this): void; /** * Hides the chart instantly and then shows it. If defaultState.transitionDuration > 0, this will result an animation in which properties of hidden state will animate to properties of visible state. */ appear(): void; }
import { Container } from "../../core/Container"; import { Series } from "../series/Series"; import { ColorSet } from "../../core/utils/ColorSet"; import { PatternSet } from "../../core/utils/PatternSet";
random_line_split
SerialChart.d.ts
/** * Serial chart module. */ /** * ============================================================================ * IMPORTS * ============================================================================ * @hidden */ import { Chart, IChartProperties, IChartDataFields, IChartAdapters, IChartEvents, ChartDataItem } from "../Chart"; import { IListEvents, ListTemplate } from "../../core/utils/List"; import { Container } from "../../core/Container"; import { Series } from "../series/Series"; import { ColorSet } from "../../core/utils/ColorSet"; import { PatternSet } from "../../core/utils/PatternSet"; /** * ============================================================================ * DATA ITEM * ============================================================================ * @hidden */ /** * Defines a [[DataItem]] for [[SerialChart]]. * * @see {@link DataItem} */ export declare class
extends ChartDataItem { /** * Defines a type of [[Component]] this data item is used for. */ _component: SerialChart; /** * Constructor */ constructor(); } /** * ============================================================================ * REQUISITES * ============================================================================ * @hidden */ /** * Defines data fields for [[SerialChart]]. */ export interface ISerialChartDataFields extends IChartDataFields { } /** * Defines properties for [[SerialChart]] */ export interface ISerialChartProperties extends IChartProperties { /** * A set of colors to be used for chart elements, like Series, Slices, etc. */ colors?: ColorSet; /** * A set of patterns to use for fills, like Series, Slices, etc. * * @since 4.7.5 */ patterns?: PatternSet; } /** * Defines events for [[SerialChart]]. */ export interface ISerialChartEvents extends IChartEvents { } /** * Defines adapters for [[SerialChart]]. * * @see {@link Adapter} */ export interface ISerialChartAdapters extends IChartAdapters, ISerialChartProperties { } /** * ============================================================================ * MAIN CLASS * ============================================================================ * @hidden */ /** * A base class for all series-based charts, like XY, Pie, etc. * * Is not useful on its own. * * @see {@link ISerialChartEvents} for a list of available Events * @see {@link ISerialChartAdapters} for a list of available Adapters */ export declare class SerialChart extends Chart { /** * Defines data fields. */ _dataFields: ISerialChartDataFields; /** * Defines available properties. */ _properties: ISerialChartProperties; /** * Defines available adapters. */ _adapter: ISerialChartAdapters; /** * Defines available events. */ _events: ISerialChartEvents; /** * Defines a type of series that this chart uses. */ _seriesType: Series; /** * Holds a list of [[Series]] displayed on the chart. */ protected _series: ListTemplate<this["_seriesType"]>; /** * Holds the reference to the container actual series are drawn in. */ readonly seriesContainer: Container; /** * Holds a reference to the container series' bullets are drawn in. */ readonly bulletsContainer: Container; /** * Constructor */ constructor(); dispose(): void; /** * Sets defaults that instantiate some objects that rely on parent, so they * cannot be set in constructor */ protected applyInternalDefaults(): void; /** * A list of chart's series. * * @return Chart's series */ readonly series: ListTemplate<this["_seriesType"]>; protected handleSeriesRemoved(event: IListEvents<Series>["removed"]): void; /** * Decorates a new [[Series]] object with required parameters when it is * added to the chart. * * @ignore Exclude from docs * @param event Event */ handleSeriesAdded(event: IListEvents<Series>["inserted"]): void; protected handleLegendSeriesAdded(series: Series): void; protected handleSeriesAdded2(series: Series): void; /** * Setups the legend to use the chart's data. * @ignore */ feedLegend(): void; /** * Creates and returns a new Series, suitable for this chart type. * * @return New series */ protected createSeries(): this["_seriesType"]; /** * Chart's color list. * * This list can be used by a number of serial items, like applying a new * color for each Series added. Or, applying a new color for each slice * of a Pie chart. * * Please see [[ColorSet]] for information on how you can set up to generate * unique colors. * * A theme you are using may override default pre-defined colors. * * @param value Color list */ /** * @return Color list */ colors: ColorSet; /** * A [[PatternSet]] to use when creating patterned fills for slices. * * @since 4.7.5 * @param value Pattern set */ /** * @return Pattern set */ patterns: PatternSet; /** * Copies all parameters from another [[SerialChart]]. * * @param source Source SerialChart */ copyFrom(source: this): void; /** * Hides the chart instantly and then shows it. If defaultState.transitionDuration > 0, this will result an animation in which properties of hidden state will animate to properties of visible state. */ appear(): void; }
SerialChartDataItem
identifier_name
wallet.rs
use indy::IndyError; use indy::wallet; use indy::future::Future; pub const DEFAULT_WALLET_CREDENTIALS: &'static str = r#"{"key":"8dvfYSt5d1taSd6yJdpjq4emkwsPDDLYxkNFysFD2cZY", "key_derivation_method":"RAW"}"#; pub fn create_wallet(config: &str) -> Result<(), IndyError> { wallet::create_wallet(config, DEFAULT_WALLET_CREDENTIALS).wait() } pub fn open_wallet(config: &str) -> Result<i32, IndyError> { wallet::open_wallet(config, DEFAULT_WALLET_CREDENTIALS).wait() } pub fn create_and_open_wallet() -> Result<i32, IndyError> { let wallet_name = format!("default-wallet-name-{}", super::sequence::get_next_id()); let config = format!(r#"{{"id":"{}"}}"#, wallet_name); create_wallet(&config)?; open_wallet(&config) } pub fn close_wallet(wallet_handle: i32) -> Result<(), IndyError>
{ wallet::close_wallet(wallet_handle).wait() }
identifier_body
wallet.rs
use indy::IndyError; use indy::wallet;
pub const DEFAULT_WALLET_CREDENTIALS: &'static str = r#"{"key":"8dvfYSt5d1taSd6yJdpjq4emkwsPDDLYxkNFysFD2cZY", "key_derivation_method":"RAW"}"#; pub fn create_wallet(config: &str) -> Result<(), IndyError> { wallet::create_wallet(config, DEFAULT_WALLET_CREDENTIALS).wait() } pub fn open_wallet(config: &str) -> Result<i32, IndyError> { wallet::open_wallet(config, DEFAULT_WALLET_CREDENTIALS).wait() } pub fn create_and_open_wallet() -> Result<i32, IndyError> { let wallet_name = format!("default-wallet-name-{}", super::sequence::get_next_id()); let config = format!(r#"{{"id":"{}"}}"#, wallet_name); create_wallet(&config)?; open_wallet(&config) } pub fn close_wallet(wallet_handle: i32) -> Result<(), IndyError> { wallet::close_wallet(wallet_handle).wait() }
use indy::future::Future;
random_line_split
wallet.rs
use indy::IndyError; use indy::wallet; use indy::future::Future; pub const DEFAULT_WALLET_CREDENTIALS: &'static str = r#"{"key":"8dvfYSt5d1taSd6yJdpjq4emkwsPDDLYxkNFysFD2cZY", "key_derivation_method":"RAW"}"#; pub fn create_wallet(config: &str) -> Result<(), IndyError> { wallet::create_wallet(config, DEFAULT_WALLET_CREDENTIALS).wait() } pub fn open_wallet(config: &str) -> Result<i32, IndyError> { wallet::open_wallet(config, DEFAULT_WALLET_CREDENTIALS).wait() } pub fn
() -> Result<i32, IndyError> { let wallet_name = format!("default-wallet-name-{}", super::sequence::get_next_id()); let config = format!(r#"{{"id":"{}"}}"#, wallet_name); create_wallet(&config)?; open_wallet(&config) } pub fn close_wallet(wallet_handle: i32) -> Result<(), IndyError> { wallet::close_wallet(wallet_handle).wait() }
create_and_open_wallet
identifier_name
solver.js
// Copyright (c) 2015 by rapidhere, RANTTU. INC. All Rights Reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 // along with this program. If not, see <http://www.gnu.org/licenses/>. (function() { /** * The game solver * author: rapidhere@gmail.com */ 'use strict'; // namespace rapid var rapidGameSolver = {}; // dx and dy var nd = 5;
var dy = [0, 1, -1, 0, 0]; // a util: create a 2-d array, and fill with zero rapidGameSolver.new2dArray = function(h, w) { var ret = new Array(h); var i; for(i = 0;i < h;i ++) ret[i] = rapidGameSolver.new1dArray(w); return ret; }; // create a 1-d array // and fill with zero rapidGameSolver.new1dArray = function(l) { var ret = new Array(l); var i; for(i = 0;i < l;i ++) ret[i] = 0; return ret; }; // toggle a solve display or not rapidGameSolver.toggleSolve = function($div) { var clicked = parseInt($div.attr('data-clicked')); var sol = parseInt($div.attr('data-sol')); var flag = sol ^ clicked; if(flag) { $div.html('✓'); } else { $div.html(''); } $div.attr('data-clicked', clicked ^ 1); }; // game solve entry rapidGameSolver.solveGame = function(game) { // solve the game with Gaussian Elimination // get board and width, height var bd = game.gb.board; var h = bd.length; var w = bd[0].length; if(game.solved) return ; // mark game as sovled game.solved = true; // currently the solution is only depending on the height // and the width of board // TODO: add broken-box int the board // the solution, equation array // a * x = b var nx = h * w; var a = rapidGameSolver.new2dArray(nx, nx); var x = rapidGameSolver.new1dArray(nx); var b = rapidGameSolver.new1dArray(nx); // construct equantions var i, j, k; for(i = 0;i < h;i ++) for(j = 0;j < w;j ++) { var idx = i * w + j; b[idx] = bd[i][j] ^ 1; for(k = 0;k < nd;k ++) { var ci = i + dx[k], cj = j + dy[k]; if(ci >= 0 && ci < h && cj >= 0 && cj < w) { a[ci * w + cj][idx] = 1; } } } // Elimation var lastj = 0; var tmp; for(i = 0;i < nx;i ++) { // find the coef not zero of current x for(j = lastj;j < nx;j ++) if(a[j][i]) break; // if not found, ignore this x if(j === nx) continue; // swap to this line lastj = i + 1; tmp = a[i]; a[i] = a[j]; a[j] = tmp; tmp = b[i]; b[i] = b[j]; b[j] = tmp; for(j = j + 1;j < nx;j ++) if(a[j][i]) { for(k = i;k < nx;k ++) a[j][k] ^= a[i][k]; b[j] ^= b[i]; } } // solve for(i = nx - 1;i >= 0;i --) { // accumulate x[i] = b[i]; for(j = i + 1;j < nx;j ++) x[i] ^= (a[i][j] & x[j]); if(! a[i][i]){ if(x[i]!=0) console.log("Wrong!No solution "+i+'/('+h+','+w+')'); continue ; } } // render the solution var cx, cy; var coord; var $div; for(i = 0;i < nx;i ++) { cy = parseInt(i % w); cx = parseInt(i / h); coord = '.coord' + cx + 'q' + cy; $div = $('<div data-sol="' + x[i] + '" data-clicked="0"></div>'); $div.css({ 'color': '#a00', 'width': '100%', 'height': '100%', 'font-weight': 'bolder', 'font-size': '24px', 'text-shadow': '1px 2px #8f8f8f' }); $(coord).append($div); rapidGameSolver.toggleSolve($div); /* jshint ignore:start */ $div.click(function() { var $div = $(this); rapidGameSolver.toggleSolve($div); }); /* jshint ignore:end */ } }; // export to global window.solveGame = rapidGameSolver.solveGame; })();
var dx = [0, 0, 0, 1, -1];
random_line_split
solver.js
// Copyright (c) 2015 by rapidhere, RANTTU. INC. All Rights Reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 // along with this program. If not, see <http://www.gnu.org/licenses/>. (function() { /** * The game solver * author: rapidhere@gmail.com */ 'use strict'; // namespace rapid var rapidGameSolver = {}; // dx and dy var nd = 5; var dx = [0, 0, 0, 1, -1]; var dy = [0, 1, -1, 0, 0]; // a util: create a 2-d array, and fill with zero rapidGameSolver.new2dArray = function(h, w) { var ret = new Array(h); var i; for(i = 0;i < h;i ++) ret[i] = rapidGameSolver.new1dArray(w); return ret; }; // create a 1-d array // and fill with zero rapidGameSolver.new1dArray = function(l) { var ret = new Array(l); var i; for(i = 0;i < l;i ++) ret[i] = 0; return ret; }; // toggle a solve display or not rapidGameSolver.toggleSolve = function($div) { var clicked = parseInt($div.attr('data-clicked')); var sol = parseInt($div.attr('data-sol')); var flag = sol ^ clicked; if(flag) { $div.html('✓'); } else {
$div.attr('data-clicked', clicked ^ 1); }; // game solve entry rapidGameSolver.solveGame = function(game) { // solve the game with Gaussian Elimination // get board and width, height var bd = game.gb.board; var h = bd.length; var w = bd[0].length; if(game.solved) return ; // mark game as sovled game.solved = true; // currently the solution is only depending on the height // and the width of board // TODO: add broken-box int the board // the solution, equation array // a * x = b var nx = h * w; var a = rapidGameSolver.new2dArray(nx, nx); var x = rapidGameSolver.new1dArray(nx); var b = rapidGameSolver.new1dArray(nx); // construct equantions var i, j, k; for(i = 0;i < h;i ++) for(j = 0;j < w;j ++) { var idx = i * w + j; b[idx] = bd[i][j] ^ 1; for(k = 0;k < nd;k ++) { var ci = i + dx[k], cj = j + dy[k]; if(ci >= 0 && ci < h && cj >= 0 && cj < w) { a[ci * w + cj][idx] = 1; } } } // Elimation var lastj = 0; var tmp; for(i = 0;i < nx;i ++) { // find the coef not zero of current x for(j = lastj;j < nx;j ++) if(a[j][i]) break; // if not found, ignore this x if(j === nx) continue; // swap to this line lastj = i + 1; tmp = a[i]; a[i] = a[j]; a[j] = tmp; tmp = b[i]; b[i] = b[j]; b[j] = tmp; for(j = j + 1;j < nx;j ++) if(a[j][i]) { for(k = i;k < nx;k ++) a[j][k] ^= a[i][k]; b[j] ^= b[i]; } } // solve for(i = nx - 1;i >= 0;i --) { // accumulate x[i] = b[i]; for(j = i + 1;j < nx;j ++) x[i] ^= (a[i][j] & x[j]); if(! a[i][i]){ if(x[i]!=0) console.log("Wrong!No solution "+i+'/('+h+','+w+')'); continue ; } } // render the solution var cx, cy; var coord; var $div; for(i = 0;i < nx;i ++) { cy = parseInt(i % w); cx = parseInt(i / h); coord = '.coord' + cx + 'q' + cy; $div = $('<div data-sol="' + x[i] + '" data-clicked="0"></div>'); $div.css({ 'color': '#a00', 'width': '100%', 'height': '100%', 'font-weight': 'bolder', 'font-size': '24px', 'text-shadow': '1px 2px #8f8f8f' }); $(coord).append($div); rapidGameSolver.toggleSolve($div); /* jshint ignore:start */ $div.click(function() { var $div = $(this); rapidGameSolver.toggleSolve($div); }); /* jshint ignore:end */ } }; // export to global window.solveGame = rapidGameSolver.solveGame; })();
$div.html(''); }
conditional_block
host.ts
import { Injectable, ApplicationRef, ComponentFactoryResolver, Injector, Component, EmbeddedViewRef, ComponentDecorator } from '@angular/core'; import { ComponentType } from './models'; import { ComponentInstance } from './component-instance'; @Injectable() export class ComponentHost<C> { private compFac; private compRef; private component; private componentProps; compIns: ComponentInstance<C>; constructor( private appRef: ApplicationRef, private compFacResolver: ComponentFactoryResolver, private injector: Injector ) {}
(component: ComponentType<C>, props = {}) { this.component = component; this.componentProps = props; } attach(): ComponentHost<C> { this.compFac = this.compFacResolver.resolveComponentFactory(this.component); this.compRef = this.compFac.create(this.injector); this.compIns = this.compRef.instance = <ComponentInstance<C>>new ComponentInstance( this.compRef.instance, this.componentProps ); this.appRef.attachView(this.compRef.hostView); return this; } getCompIns(): ComponentInstance<C> { return this.compIns; } detach() { this.appRef.detachView(this.compRef.hostView); this.compRef.destroy(); } componentView(): HTMLElement { return (this.compRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement; } }
configure
identifier_name
host.ts
import { Injectable, ApplicationRef, ComponentFactoryResolver, Injector, Component, EmbeddedViewRef, ComponentDecorator } from '@angular/core'; import { ComponentType } from './models'; import { ComponentInstance } from './component-instance'; @Injectable() export class ComponentHost<C> { private compFac; private compRef; private component; private componentProps; compIns: ComponentInstance<C>; constructor( private appRef: ApplicationRef, private compFacResolver: ComponentFactoryResolver, private injector: Injector ) {} configure(component: ComponentType<C>, props = {}) { this.component = component; this.componentProps = props; } attach(): ComponentHost<C> { this.compFac = this.compFacResolver.resolveComponentFactory(this.component); this.compRef = this.compFac.create(this.injector); this.compIns = this.compRef.instance = <ComponentInstance<C>>new ComponentInstance( this.compRef.instance, this.componentProps ); this.appRef.attachView(this.compRef.hostView); return this; } getCompIns(): ComponentInstance<C>
detach() { this.appRef.detachView(this.compRef.hostView); this.compRef.destroy(); } componentView(): HTMLElement { return (this.compRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement; } }
{ return this.compIns; }
identifier_body
host.ts
import { Injectable, ApplicationRef, ComponentFactoryResolver, Injector, Component, EmbeddedViewRef, ComponentDecorator } from '@angular/core';
@Injectable() export class ComponentHost<C> { private compFac; private compRef; private component; private componentProps; compIns: ComponentInstance<C>; constructor( private appRef: ApplicationRef, private compFacResolver: ComponentFactoryResolver, private injector: Injector ) {} configure(component: ComponentType<C>, props = {}) { this.component = component; this.componentProps = props; } attach(): ComponentHost<C> { this.compFac = this.compFacResolver.resolveComponentFactory(this.component); this.compRef = this.compFac.create(this.injector); this.compIns = this.compRef.instance = <ComponentInstance<C>>new ComponentInstance( this.compRef.instance, this.componentProps ); this.appRef.attachView(this.compRef.hostView); return this; } getCompIns(): ComponentInstance<C> { return this.compIns; } detach() { this.appRef.detachView(this.compRef.hostView); this.compRef.destroy(); } componentView(): HTMLElement { return (this.compRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement; } }
import { ComponentType } from './models'; import { ComponentInstance } from './component-instance';
random_line_split
architecture.rs
/* * Panopticon - A libre disassembler * Copyright (C) 2015, 2017 Panopticon authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ use panopticon_core::{Architecture, Match, Region, Result}; #[derive(Clone,Debug)] pub enum Amd64 {} #[derive(Clone,PartialEq,Copy,Debug)] pub enum Mode { Real, // Real mode / Virtual 8086 mode Protected, // Protected mode / Long compatibility mode Long, // Long 64-bit mode } impl Mode { pub fn
(&self) -> usize { match self { &Mode::Real => 32, &Mode::Protected => 16, &Mode::Long => 16, } } pub fn bits(&self) -> usize { match self { &Mode::Real => 16, &Mode::Protected => 32, &Mode::Long => 64, } } } impl Architecture for Amd64 { type Token = u8; type Configuration = Mode; fn prepare(_: &Region, _: &Self::Configuration) -> Result<Vec<(&'static str, u64, &'static str)>> { Ok(vec![]) } fn decode(reg: &Region, start: u64, cfg: &Self::Configuration) -> Result<Match<Self>> { let data = reg.iter(); let mut buf: Vec<u8> = vec![]; let mut i = data.seek(start); let p = start; while let Some(Some(b)) = i.next() { buf.push(b); if buf.len() == 15 { break; } } debug!("disass @ {:#x}: {:?}", p, buf); let ret = crate::disassembler::read(*cfg, &buf, p).and_then( |(len, mne, mut jmp)| { Ok( Match::<Amd64> { tokens: buf[0..len as usize].to_vec(), mnemonics: vec![mne], jumps: jmp.drain(..).map(|x| (p, x.0, x.1)).collect::<Vec<_>>(), configuration: cfg.clone(), } ) } ); debug!(" res: {:?}", ret); ret } }
alt_bits
identifier_name
architecture.rs
/* * Panopticon - A libre disassembler * Copyright (C) 2015, 2017 Panopticon authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ use panopticon_core::{Architecture, Match, Region, Result}; #[derive(Clone,Debug)] pub enum Amd64 {} #[derive(Clone,PartialEq,Copy,Debug)] pub enum Mode { Real, // Real mode / Virtual 8086 mode Protected, // Protected mode / Long compatibility mode Long, // Long 64-bit mode } impl Mode { pub fn alt_bits(&self) -> usize { match self { &Mode::Real => 32, &Mode::Protected => 16, &Mode::Long => 16, } } pub fn bits(&self) -> usize { match self { &Mode::Real => 16, &Mode::Protected => 32, &Mode::Long => 64, } } } impl Architecture for Amd64 { type Token = u8; type Configuration = Mode; fn prepare(_: &Region, _: &Self::Configuration) -> Result<Vec<(&'static str, u64, &'static str)>> { Ok(vec![]) } fn decode(reg: &Region, start: u64, cfg: &Self::Configuration) -> Result<Match<Self>> { let data = reg.iter(); let mut buf: Vec<u8> = vec![]; let mut i = data.seek(start); let p = start; while let Some(Some(b)) = i.next() { buf.push(b); if buf.len() == 15 { break; }
let ret = crate::disassembler::read(*cfg, &buf, p).and_then( |(len, mne, mut jmp)| { Ok( Match::<Amd64> { tokens: buf[0..len as usize].to_vec(), mnemonics: vec![mne], jumps: jmp.drain(..).map(|x| (p, x.0, x.1)).collect::<Vec<_>>(), configuration: cfg.clone(), } ) } ); debug!(" res: {:?}", ret); ret } }
} debug!("disass @ {:#x}: {:?}", p, buf);
random_line_split
sonnet_predict_bed.py
#!/usr/bin/env python # Copyright 2017 Calico LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ========================================================================= from __future__ import print_function from optparse import OptionParser import json import os import pdb import pickle import sys import h5py import numpy as np import pandas as pd import pysam import pyBigWig import tensorflow as tf if tf.__version__[0] == '1': tf.compat.v1.enable_eager_execution() from basenji import bed from basenji import dna_io from basenji import seqnn from basenji import stream ''' basenji_predict_bed.py Predict sequences from a BED file. ''' ################################################################################ # main ################################################################################ def main(): usage = 'usage: %prog [options] <model_file> <bed_file>' parser = OptionParser(usage) parser.add_option('-b', dest='bigwig_indexes', default=None, help='Comma-separated list of target indexes to write BigWigs') parser.add_option('-e', dest='embed_layer', default=None, type='int', help='Embed sequences using the specified layer index.') parser.add_option('-f', dest='genome_fasta', default=None, help='Genome FASTA for sequences [Default: %default]') parser.add_option('-g', dest='genome_file', default=None, help='Chromosome length information [Default: %default]') parser.add_option('-l', dest='site_length', default=None, type='int', help='Prediction site length. [Default: model seq_length]') parser.add_option('-o', dest='out_dir', default='pred_out', help='Output directory [Default: %default]') # parser.add_option('--plots', dest='plots', # default=False, action='store_true', # help='Make heatmap plots [Default: %default]') parser.add_option('-p', dest='processes', default=None, type='int', help='Number of processes, passed by multi script') parser.add_option('--rc', dest='rc', default=False, action='store_true', help='Ensemble forward and reverse complement predictions [Default: %default]') parser.add_option('-s', dest='sum', default=False, action='store_true', help='Sum site predictions [Default: %default]') parser.add_option('--shifts', dest='shifts', default='0', help='Ensemble prediction shifts [Default: %default]') parser.add_option('--species', dest='species', default='human') parser.add_option('-t', dest='targets_file', default=None, type='str', help='File specifying target indexes and labels in table format') (options, args) = parser.parse_args() if len(args) == 2: model_file = args[0] bed_file = args[1] elif len(args) == 4: # multi worker options_pkl_file = args[0] model_file = args[1] bed_file = args[2] worker_index = int(args[3]) # load options options_pkl = open(options_pkl_file, 'rb') options = pickle.load(options_pkl) options_pkl.close() # update output directory options.out_dir = '%s/job%d' % (options.out_dir, worker_index) else: parser.error('Must provide parameter and model files and BED file') if not os.path.isdir(options.out_dir): os.mkdir(options.out_dir) options.shifts = [int(shift) for shift in options.shifts.split(',')] if options.bigwig_indexes is not None: options.bigwig_indexes = [int(bi) for bi in options.bigwig_indexes.split(',')] else: options.bigwig_indexes = [] if len(options.bigwig_indexes) > 0: bigwig_dir = '%s/bigwig' % options.out_dir if not os.path.isdir(bigwig_dir): os.mkdir(bigwig_dir) ################################################################# # read parameters and collet target information if options.targets_file is None: target_slice = None else:
################################################################# # setup model seqnn_model = tf.saved_model.load(model_file).model # query num model targets seq_length = seqnn_model.predict_on_batch.input_signature[0].shape[1] null_1hot = np.zeros((1,seq_length,4)) null_preds = seqnn_model.predict_on_batch(null_1hot) null_preds = null_preds[options.species].numpy() _, preds_length, preds_depth = null_preds.shape # hack sizes preds_window = 128 seq_crop = (seq_length - preds_length*preds_window) // 2 ################################################################# # sequence dataset if options.site_length is None: options.site_length = preds_window*preds_length print('site_length: %d' % options.site_length) # construct model sequences model_seqs_dna, model_seqs_coords = bed.make_bed_seqs( bed_file, options.genome_fasta, seq_length, stranded=False) # construct site coordinates site_seqs_coords = bed.read_bed_coords(bed_file, options.site_length) # filter for worker SNPs if options.processes is not None: worker_bounds = np.linspace(0, len(model_seqs_dna), options.processes+1, dtype='int') model_seqs_dna = model_seqs_dna[worker_bounds[worker_index]:worker_bounds[worker_index+1]] model_seqs_coords = model_seqs_coords[worker_bounds[worker_index]:worker_bounds[worker_index+1]] site_seqs_coords = site_seqs_coords[worker_bounds[worker_index]:worker_bounds[worker_index+1]] num_seqs = len(model_seqs_dna) ################################################################# # setup output assert(preds_length % 2 == 0) preds_mid = preds_length // 2 assert(options.site_length % preds_window == 0) site_preds_length = options.site_length // preds_window assert(site_preds_length % 2 == 0) site_preds_start = preds_mid - site_preds_length//2 site_preds_end = site_preds_start + site_preds_length # initialize HDF5 out_h5_file = '%s/predict.h5' % options.out_dir if os.path.isfile(out_h5_file): os.remove(out_h5_file) out_h5 = h5py.File(out_h5_file, 'w') # create predictions if options.sum: out_h5.create_dataset('preds', shape=(num_seqs, preds_depth), dtype='float16') else: out_h5.create_dataset('preds', shape=(num_seqs, site_preds_length, preds_depth), dtype='float16') # store site coordinates site_seqs_chr, site_seqs_start, site_seqs_end = zip(*site_seqs_coords) site_seqs_chr = np.array(site_seqs_chr, dtype='S') site_seqs_start = np.array(site_seqs_start) site_seqs_end = np.array(site_seqs_end) out_h5.create_dataset('chrom', data=site_seqs_chr) out_h5.create_dataset('start', data=site_seqs_start) out_h5.create_dataset('end', data=site_seqs_end) ################################################################# # predict scores, write output # define sequence generator def seqs_gen(): for seq_dna in model_seqs_dna: yield dna_io.dna_1hot(seq_dna) # initialize predictions stream preds_stream = stream.PredStreamSonnet(seqnn_model, seqs_gen(), rc=options.rc, shifts=options.shifts, species=options.species) for si in range(num_seqs): preds_seq = preds_stream[si] # slice site preds_site = preds_seq[site_preds_start:site_preds_end,:] # write if options.sum: out_h5['preds'][si] = preds_site.sum(axis=0) else: out_h5['preds'][si] = preds_site # write bigwig for ti in options.bigwig_indexes: bw_file = '%s/s%d_t%d.bw' % (bigwig_dir, si, ti) bigwig_write(preds_seq[:,ti], model_seqs_coords[si], bw_file, options.genome_file, seq_crop) # close output HDF5 out_h5.close() def bigwig_open(bw_file, genome_file): """ Open the bigwig file for writing and write the header. """ bw_out = pyBigWig.open(bw_file, 'w') chrom_sizes = [] for line in open(genome_file): a = line.split() chrom_sizes.append((a[0], int(a[1]))) bw_out.addHeader(chrom_sizes) return bw_out def bigwig_write(signal, seq_coords, bw_file, genome_file, seq_crop=0): """ Write a signal track to a BigWig file over the region specified by seqs_coords. Args signal: Sequences x Length signal array seq_coords: (chr,start,end) bw_file: BigWig filename genome_file: Chromosome lengths file seq_crop: Sequence length cropped from each side of the sequence. """ target_length = len(signal) # open bigwig bw_out = bigwig_open(bw_file, genome_file) # initialize entry arrays entry_starts = [] entry_ends = [] # set entries chrm, start, end = seq_coords preds_pool = (end - start - 2 * seq_crop) // target_length bw_start = start + seq_crop for li in range(target_length): bw_end = bw_start + preds_pool entry_starts.append(bw_start) entry_ends.append(bw_end) bw_start = bw_end # add bw_out.addEntries( [chrm]*target_length, entry_starts, ends=entry_ends, values=[float(s) for s in signal]) bw_out.close() ################################################################################ # __main__ ################################################################################ if __name__ == '__main__': main()
targets_df = pd.read_table(options.targets_file, index_col=0) target_slice = targets_df.index
conditional_block
sonnet_predict_bed.py
#!/usr/bin/env python # Copyright 2017 Calico LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ========================================================================= from __future__ import print_function from optparse import OptionParser import json import os import pdb import pickle import sys import h5py import numpy as np import pandas as pd import pysam import pyBigWig import tensorflow as tf if tf.__version__[0] == '1': tf.compat.v1.enable_eager_execution() from basenji import bed from basenji import dna_io from basenji import seqnn from basenji import stream ''' basenji_predict_bed.py Predict sequences from a BED file. ''' ################################################################################ # main ################################################################################ def main(): usage = 'usage: %prog [options] <model_file> <bed_file>' parser = OptionParser(usage) parser.add_option('-b', dest='bigwig_indexes', default=None, help='Comma-separated list of target indexes to write BigWigs') parser.add_option('-e', dest='embed_layer', default=None, type='int', help='Embed sequences using the specified layer index.') parser.add_option('-f', dest='genome_fasta', default=None, help='Genome FASTA for sequences [Default: %default]') parser.add_option('-g', dest='genome_file', default=None, help='Chromosome length information [Default: %default]') parser.add_option('-l', dest='site_length', default=None, type='int', help='Prediction site length. [Default: model seq_length]') parser.add_option('-o', dest='out_dir', default='pred_out', help='Output directory [Default: %default]') # parser.add_option('--plots', dest='plots', # default=False, action='store_true', # help='Make heatmap plots [Default: %default]') parser.add_option('-p', dest='processes', default=None, type='int', help='Number of processes, passed by multi script') parser.add_option('--rc', dest='rc', default=False, action='store_true', help='Ensemble forward and reverse complement predictions [Default: %default]') parser.add_option('-s', dest='sum', default=False, action='store_true', help='Sum site predictions [Default: %default]') parser.add_option('--shifts', dest='shifts', default='0', help='Ensemble prediction shifts [Default: %default]') parser.add_option('--species', dest='species', default='human') parser.add_option('-t', dest='targets_file', default=None, type='str', help='File specifying target indexes and labels in table format') (options, args) = parser.parse_args() if len(args) == 2: model_file = args[0] bed_file = args[1] elif len(args) == 4: # multi worker options_pkl_file = args[0] model_file = args[1] bed_file = args[2] worker_index = int(args[3]) # load options options_pkl = open(options_pkl_file, 'rb') options = pickle.load(options_pkl) options_pkl.close() # update output directory options.out_dir = '%s/job%d' % (options.out_dir, worker_index) else: parser.error('Must provide parameter and model files and BED file') if not os.path.isdir(options.out_dir): os.mkdir(options.out_dir) options.shifts = [int(shift) for shift in options.shifts.split(',')] if options.bigwig_indexes is not None: options.bigwig_indexes = [int(bi) for bi in options.bigwig_indexes.split(',')] else: options.bigwig_indexes = [] if len(options.bigwig_indexes) > 0: bigwig_dir = '%s/bigwig' % options.out_dir if not os.path.isdir(bigwig_dir): os.mkdir(bigwig_dir) ################################################################# # read parameters and collet target information if options.targets_file is None: target_slice = None else: targets_df = pd.read_table(options.targets_file, index_col=0) target_slice = targets_df.index ################################################################# # setup model seqnn_model = tf.saved_model.load(model_file).model # query num model targets seq_length = seqnn_model.predict_on_batch.input_signature[0].shape[1] null_1hot = np.zeros((1,seq_length,4)) null_preds = seqnn_model.predict_on_batch(null_1hot) null_preds = null_preds[options.species].numpy() _, preds_length, preds_depth = null_preds.shape # hack sizes preds_window = 128 seq_crop = (seq_length - preds_length*preds_window) // 2 ################################################################# # sequence dataset if options.site_length is None: options.site_length = preds_window*preds_length print('site_length: %d' % options.site_length) # construct model sequences model_seqs_dna, model_seqs_coords = bed.make_bed_seqs( bed_file, options.genome_fasta, seq_length, stranded=False) # construct site coordinates site_seqs_coords = bed.read_bed_coords(bed_file, options.site_length) # filter for worker SNPs if options.processes is not None: worker_bounds = np.linspace(0, len(model_seqs_dna), options.processes+1, dtype='int') model_seqs_dna = model_seqs_dna[worker_bounds[worker_index]:worker_bounds[worker_index+1]] model_seqs_coords = model_seqs_coords[worker_bounds[worker_index]:worker_bounds[worker_index+1]] site_seqs_coords = site_seqs_coords[worker_bounds[worker_index]:worker_bounds[worker_index+1]] num_seqs = len(model_seqs_dna) ################################################################# # setup output assert(preds_length % 2 == 0) preds_mid = preds_length // 2 assert(options.site_length % preds_window == 0) site_preds_length = options.site_length // preds_window assert(site_preds_length % 2 == 0) site_preds_start = preds_mid - site_preds_length//2 site_preds_end = site_preds_start + site_preds_length # initialize HDF5 out_h5_file = '%s/predict.h5' % options.out_dir if os.path.isfile(out_h5_file): os.remove(out_h5_file) out_h5 = h5py.File(out_h5_file, 'w') # create predictions if options.sum: out_h5.create_dataset('preds', shape=(num_seqs, preds_depth), dtype='float16') else: out_h5.create_dataset('preds', shape=(num_seqs, site_preds_length, preds_depth), dtype='float16') # store site coordinates site_seqs_chr, site_seqs_start, site_seqs_end = zip(*site_seqs_coords) site_seqs_chr = np.array(site_seqs_chr, dtype='S') site_seqs_start = np.array(site_seqs_start) site_seqs_end = np.array(site_seqs_end) out_h5.create_dataset('chrom', data=site_seqs_chr) out_h5.create_dataset('start', data=site_seqs_start) out_h5.create_dataset('end', data=site_seqs_end) ################################################################# # predict scores, write output # define sequence generator def seqs_gen(): for seq_dna in model_seqs_dna: yield dna_io.dna_1hot(seq_dna) # initialize predictions stream preds_stream = stream.PredStreamSonnet(seqnn_model, seqs_gen(), rc=options.rc, shifts=options.shifts, species=options.species) for si in range(num_seqs): preds_seq = preds_stream[si] # slice site preds_site = preds_seq[site_preds_start:site_preds_end,:] # write if options.sum: out_h5['preds'][si] = preds_site.sum(axis=0) else: out_h5['preds'][si] = preds_site # write bigwig for ti in options.bigwig_indexes: bw_file = '%s/s%d_t%d.bw' % (bigwig_dir, si, ti) bigwig_write(preds_seq[:,ti], model_seqs_coords[si], bw_file, options.genome_file, seq_crop) # close output HDF5 out_h5.close() def bigwig_open(bw_file, genome_file): """ Open the bigwig file for writing and write the header. """ bw_out = pyBigWig.open(bw_file, 'w') chrom_sizes = [] for line in open(genome_file): a = line.split() chrom_sizes.append((a[0], int(a[1]))) bw_out.addHeader(chrom_sizes) return bw_out def bigwig_write(signal, seq_coords, bw_file, genome_file, seq_crop=0):
################################################################################ # __main__ ################################################################################ if __name__ == '__main__': main()
""" Write a signal track to a BigWig file over the region specified by seqs_coords. Args signal: Sequences x Length signal array seq_coords: (chr,start,end) bw_file: BigWig filename genome_file: Chromosome lengths file seq_crop: Sequence length cropped from each side of the sequence. """ target_length = len(signal) # open bigwig bw_out = bigwig_open(bw_file, genome_file) # initialize entry arrays entry_starts = [] entry_ends = [] # set entries chrm, start, end = seq_coords preds_pool = (end - start - 2 * seq_crop) // target_length bw_start = start + seq_crop for li in range(target_length): bw_end = bw_start + preds_pool entry_starts.append(bw_start) entry_ends.append(bw_end) bw_start = bw_end # add bw_out.addEntries( [chrm]*target_length, entry_starts, ends=entry_ends, values=[float(s) for s in signal]) bw_out.close()
identifier_body
sonnet_predict_bed.py
#!/usr/bin/env python # Copyright 2017 Calico LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ========================================================================= from __future__ import print_function from optparse import OptionParser import json import os import pdb import pickle import sys import h5py import numpy as np import pandas as pd import pysam import pyBigWig import tensorflow as tf if tf.__version__[0] == '1': tf.compat.v1.enable_eager_execution() from basenji import bed from basenji import dna_io from basenji import seqnn from basenji import stream ''' basenji_predict_bed.py Predict sequences from a BED file. ''' ################################################################################ # main ################################################################################ def main(): usage = 'usage: %prog [options] <model_file> <bed_file>' parser = OptionParser(usage) parser.add_option('-b', dest='bigwig_indexes', default=None, help='Comma-separated list of target indexes to write BigWigs') parser.add_option('-e', dest='embed_layer', default=None, type='int', help='Embed sequences using the specified layer index.') parser.add_option('-f', dest='genome_fasta', default=None, help='Genome FASTA for sequences [Default: %default]') parser.add_option('-g', dest='genome_file', default=None, help='Chromosome length information [Default: %default]') parser.add_option('-l', dest='site_length', default=None, type='int', help='Prediction site length. [Default: model seq_length]') parser.add_option('-o', dest='out_dir', default='pred_out', help='Output directory [Default: %default]') # parser.add_option('--plots', dest='plots', # default=False, action='store_true', # help='Make heatmap plots [Default: %default]') parser.add_option('-p', dest='processes', default=None, type='int', help='Number of processes, passed by multi script') parser.add_option('--rc', dest='rc', default=False, action='store_true', help='Ensemble forward and reverse complement predictions [Default: %default]') parser.add_option('-s', dest='sum', default=False, action='store_true', help='Sum site predictions [Default: %default]') parser.add_option('--shifts', dest='shifts', default='0', help='Ensemble prediction shifts [Default: %default]') parser.add_option('--species', dest='species', default='human') parser.add_option('-t', dest='targets_file', default=None, type='str', help='File specifying target indexes and labels in table format') (options, args) = parser.parse_args() if len(args) == 2: model_file = args[0] bed_file = args[1] elif len(args) == 4: # multi worker options_pkl_file = args[0] model_file = args[1] bed_file = args[2] worker_index = int(args[3]) # load options options_pkl = open(options_pkl_file, 'rb') options = pickle.load(options_pkl) options_pkl.close() # update output directory options.out_dir = '%s/job%d' % (options.out_dir, worker_index) else: parser.error('Must provide parameter and model files and BED file') if not os.path.isdir(options.out_dir): os.mkdir(options.out_dir) options.shifts = [int(shift) for shift in options.shifts.split(',')] if options.bigwig_indexes is not None: options.bigwig_indexes = [int(bi) for bi in options.bigwig_indexes.split(',')] else: options.bigwig_indexes = [] if len(options.bigwig_indexes) > 0: bigwig_dir = '%s/bigwig' % options.out_dir if not os.path.isdir(bigwig_dir): os.mkdir(bigwig_dir) ################################################################# # read parameters and collet target information if options.targets_file is None: target_slice = None else: targets_df = pd.read_table(options.targets_file, index_col=0) target_slice = targets_df.index ################################################################# # setup model seqnn_model = tf.saved_model.load(model_file).model # query num model targets seq_length = seqnn_model.predict_on_batch.input_signature[0].shape[1] null_1hot = np.zeros((1,seq_length,4)) null_preds = seqnn_model.predict_on_batch(null_1hot) null_preds = null_preds[options.species].numpy() _, preds_length, preds_depth = null_preds.shape # hack sizes preds_window = 128 seq_crop = (seq_length - preds_length*preds_window) // 2 ################################################################# # sequence dataset if options.site_length is None: options.site_length = preds_window*preds_length print('site_length: %d' % options.site_length) # construct model sequences model_seqs_dna, model_seqs_coords = bed.make_bed_seqs( bed_file, options.genome_fasta, seq_length, stranded=False) # construct site coordinates site_seqs_coords = bed.read_bed_coords(bed_file, options.site_length) # filter for worker SNPs if options.processes is not None: worker_bounds = np.linspace(0, len(model_seqs_dna), options.processes+1, dtype='int') model_seqs_dna = model_seqs_dna[worker_bounds[worker_index]:worker_bounds[worker_index+1]] model_seqs_coords = model_seqs_coords[worker_bounds[worker_index]:worker_bounds[worker_index+1]] site_seqs_coords = site_seqs_coords[worker_bounds[worker_index]:worker_bounds[worker_index+1]] num_seqs = len(model_seqs_dna) ################################################################# # setup output assert(preds_length % 2 == 0) preds_mid = preds_length // 2 assert(options.site_length % preds_window == 0) site_preds_length = options.site_length // preds_window assert(site_preds_length % 2 == 0) site_preds_start = preds_mid - site_preds_length//2 site_preds_end = site_preds_start + site_preds_length # initialize HDF5 out_h5_file = '%s/predict.h5' % options.out_dir if os.path.isfile(out_h5_file): os.remove(out_h5_file) out_h5 = h5py.File(out_h5_file, 'w') # create predictions if options.sum: out_h5.create_dataset('preds', shape=(num_seqs, preds_depth), dtype='float16') else: out_h5.create_dataset('preds', shape=(num_seqs, site_preds_length, preds_depth), dtype='float16') # store site coordinates site_seqs_chr, site_seqs_start, site_seqs_end = zip(*site_seqs_coords) site_seqs_chr = np.array(site_seqs_chr, dtype='S') site_seqs_start = np.array(site_seqs_start) site_seqs_end = np.array(site_seqs_end)
################################################################# # predict scores, write output # define sequence generator def seqs_gen(): for seq_dna in model_seqs_dna: yield dna_io.dna_1hot(seq_dna) # initialize predictions stream preds_stream = stream.PredStreamSonnet(seqnn_model, seqs_gen(), rc=options.rc, shifts=options.shifts, species=options.species) for si in range(num_seqs): preds_seq = preds_stream[si] # slice site preds_site = preds_seq[site_preds_start:site_preds_end,:] # write if options.sum: out_h5['preds'][si] = preds_site.sum(axis=0) else: out_h5['preds'][si] = preds_site # write bigwig for ti in options.bigwig_indexes: bw_file = '%s/s%d_t%d.bw' % (bigwig_dir, si, ti) bigwig_write(preds_seq[:,ti], model_seqs_coords[si], bw_file, options.genome_file, seq_crop) # close output HDF5 out_h5.close() def bigwig_open(bw_file, genome_file): """ Open the bigwig file for writing and write the header. """ bw_out = pyBigWig.open(bw_file, 'w') chrom_sizes = [] for line in open(genome_file): a = line.split() chrom_sizes.append((a[0], int(a[1]))) bw_out.addHeader(chrom_sizes) return bw_out def bigwig_write(signal, seq_coords, bw_file, genome_file, seq_crop=0): """ Write a signal track to a BigWig file over the region specified by seqs_coords. Args signal: Sequences x Length signal array seq_coords: (chr,start,end) bw_file: BigWig filename genome_file: Chromosome lengths file seq_crop: Sequence length cropped from each side of the sequence. """ target_length = len(signal) # open bigwig bw_out = bigwig_open(bw_file, genome_file) # initialize entry arrays entry_starts = [] entry_ends = [] # set entries chrm, start, end = seq_coords preds_pool = (end - start - 2 * seq_crop) // target_length bw_start = start + seq_crop for li in range(target_length): bw_end = bw_start + preds_pool entry_starts.append(bw_start) entry_ends.append(bw_end) bw_start = bw_end # add bw_out.addEntries( [chrm]*target_length, entry_starts, ends=entry_ends, values=[float(s) for s in signal]) bw_out.close() ################################################################################ # __main__ ################################################################################ if __name__ == '__main__': main()
out_h5.create_dataset('chrom', data=site_seqs_chr) out_h5.create_dataset('start', data=site_seqs_start) out_h5.create_dataset('end', data=site_seqs_end)
random_line_split
sonnet_predict_bed.py
#!/usr/bin/env python # Copyright 2017 Calico LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ========================================================================= from __future__ import print_function from optparse import OptionParser import json import os import pdb import pickle import sys import h5py import numpy as np import pandas as pd import pysam import pyBigWig import tensorflow as tf if tf.__version__[0] == '1': tf.compat.v1.enable_eager_execution() from basenji import bed from basenji import dna_io from basenji import seqnn from basenji import stream ''' basenji_predict_bed.py Predict sequences from a BED file. ''' ################################################################################ # main ################################################################################ def main(): usage = 'usage: %prog [options] <model_file> <bed_file>' parser = OptionParser(usage) parser.add_option('-b', dest='bigwig_indexes', default=None, help='Comma-separated list of target indexes to write BigWigs') parser.add_option('-e', dest='embed_layer', default=None, type='int', help='Embed sequences using the specified layer index.') parser.add_option('-f', dest='genome_fasta', default=None, help='Genome FASTA for sequences [Default: %default]') parser.add_option('-g', dest='genome_file', default=None, help='Chromosome length information [Default: %default]') parser.add_option('-l', dest='site_length', default=None, type='int', help='Prediction site length. [Default: model seq_length]') parser.add_option('-o', dest='out_dir', default='pred_out', help='Output directory [Default: %default]') # parser.add_option('--plots', dest='plots', # default=False, action='store_true', # help='Make heatmap plots [Default: %default]') parser.add_option('-p', dest='processes', default=None, type='int', help='Number of processes, passed by multi script') parser.add_option('--rc', dest='rc', default=False, action='store_true', help='Ensemble forward and reverse complement predictions [Default: %default]') parser.add_option('-s', dest='sum', default=False, action='store_true', help='Sum site predictions [Default: %default]') parser.add_option('--shifts', dest='shifts', default='0', help='Ensemble prediction shifts [Default: %default]') parser.add_option('--species', dest='species', default='human') parser.add_option('-t', dest='targets_file', default=None, type='str', help='File specifying target indexes and labels in table format') (options, args) = parser.parse_args() if len(args) == 2: model_file = args[0] bed_file = args[1] elif len(args) == 4: # multi worker options_pkl_file = args[0] model_file = args[1] bed_file = args[2] worker_index = int(args[3]) # load options options_pkl = open(options_pkl_file, 'rb') options = pickle.load(options_pkl) options_pkl.close() # update output directory options.out_dir = '%s/job%d' % (options.out_dir, worker_index) else: parser.error('Must provide parameter and model files and BED file') if not os.path.isdir(options.out_dir): os.mkdir(options.out_dir) options.shifts = [int(shift) for shift in options.shifts.split(',')] if options.bigwig_indexes is not None: options.bigwig_indexes = [int(bi) for bi in options.bigwig_indexes.split(',')] else: options.bigwig_indexes = [] if len(options.bigwig_indexes) > 0: bigwig_dir = '%s/bigwig' % options.out_dir if not os.path.isdir(bigwig_dir): os.mkdir(bigwig_dir) ################################################################# # read parameters and collet target information if options.targets_file is None: target_slice = None else: targets_df = pd.read_table(options.targets_file, index_col=0) target_slice = targets_df.index ################################################################# # setup model seqnn_model = tf.saved_model.load(model_file).model # query num model targets seq_length = seqnn_model.predict_on_batch.input_signature[0].shape[1] null_1hot = np.zeros((1,seq_length,4)) null_preds = seqnn_model.predict_on_batch(null_1hot) null_preds = null_preds[options.species].numpy() _, preds_length, preds_depth = null_preds.shape # hack sizes preds_window = 128 seq_crop = (seq_length - preds_length*preds_window) // 2 ################################################################# # sequence dataset if options.site_length is None: options.site_length = preds_window*preds_length print('site_length: %d' % options.site_length) # construct model sequences model_seqs_dna, model_seqs_coords = bed.make_bed_seqs( bed_file, options.genome_fasta, seq_length, stranded=False) # construct site coordinates site_seqs_coords = bed.read_bed_coords(bed_file, options.site_length) # filter for worker SNPs if options.processes is not None: worker_bounds = np.linspace(0, len(model_seqs_dna), options.processes+1, dtype='int') model_seqs_dna = model_seqs_dna[worker_bounds[worker_index]:worker_bounds[worker_index+1]] model_seqs_coords = model_seqs_coords[worker_bounds[worker_index]:worker_bounds[worker_index+1]] site_seqs_coords = site_seqs_coords[worker_bounds[worker_index]:worker_bounds[worker_index+1]] num_seqs = len(model_seqs_dna) ################################################################# # setup output assert(preds_length % 2 == 0) preds_mid = preds_length // 2 assert(options.site_length % preds_window == 0) site_preds_length = options.site_length // preds_window assert(site_preds_length % 2 == 0) site_preds_start = preds_mid - site_preds_length//2 site_preds_end = site_preds_start + site_preds_length # initialize HDF5 out_h5_file = '%s/predict.h5' % options.out_dir if os.path.isfile(out_h5_file): os.remove(out_h5_file) out_h5 = h5py.File(out_h5_file, 'w') # create predictions if options.sum: out_h5.create_dataset('preds', shape=(num_seqs, preds_depth), dtype='float16') else: out_h5.create_dataset('preds', shape=(num_seqs, site_preds_length, preds_depth), dtype='float16') # store site coordinates site_seqs_chr, site_seqs_start, site_seqs_end = zip(*site_seqs_coords) site_seqs_chr = np.array(site_seqs_chr, dtype='S') site_seqs_start = np.array(site_seqs_start) site_seqs_end = np.array(site_seqs_end) out_h5.create_dataset('chrom', data=site_seqs_chr) out_h5.create_dataset('start', data=site_seqs_start) out_h5.create_dataset('end', data=site_seqs_end) ################################################################# # predict scores, write output # define sequence generator def
(): for seq_dna in model_seqs_dna: yield dna_io.dna_1hot(seq_dna) # initialize predictions stream preds_stream = stream.PredStreamSonnet(seqnn_model, seqs_gen(), rc=options.rc, shifts=options.shifts, species=options.species) for si in range(num_seqs): preds_seq = preds_stream[si] # slice site preds_site = preds_seq[site_preds_start:site_preds_end,:] # write if options.sum: out_h5['preds'][si] = preds_site.sum(axis=0) else: out_h5['preds'][si] = preds_site # write bigwig for ti in options.bigwig_indexes: bw_file = '%s/s%d_t%d.bw' % (bigwig_dir, si, ti) bigwig_write(preds_seq[:,ti], model_seqs_coords[si], bw_file, options.genome_file, seq_crop) # close output HDF5 out_h5.close() def bigwig_open(bw_file, genome_file): """ Open the bigwig file for writing and write the header. """ bw_out = pyBigWig.open(bw_file, 'w') chrom_sizes = [] for line in open(genome_file): a = line.split() chrom_sizes.append((a[0], int(a[1]))) bw_out.addHeader(chrom_sizes) return bw_out def bigwig_write(signal, seq_coords, bw_file, genome_file, seq_crop=0): """ Write a signal track to a BigWig file over the region specified by seqs_coords. Args signal: Sequences x Length signal array seq_coords: (chr,start,end) bw_file: BigWig filename genome_file: Chromosome lengths file seq_crop: Sequence length cropped from each side of the sequence. """ target_length = len(signal) # open bigwig bw_out = bigwig_open(bw_file, genome_file) # initialize entry arrays entry_starts = [] entry_ends = [] # set entries chrm, start, end = seq_coords preds_pool = (end - start - 2 * seq_crop) // target_length bw_start = start + seq_crop for li in range(target_length): bw_end = bw_start + preds_pool entry_starts.append(bw_start) entry_ends.append(bw_end) bw_start = bw_end # add bw_out.addEntries( [chrm]*target_length, entry_starts, ends=entry_ends, values=[float(s) for s in signal]) bw_out.close() ################################################################################ # __main__ ################################################################################ if __name__ == '__main__': main()
seqs_gen
identifier_name
process_test.py
#!/usr/bin/env python import logging import os import signal import sys from tornado.httpclient import HTTPClient, HTTPError from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.netutil import bind_sockets from tornado.process import fork_processes, task_id from tornado.simple_httpclient import SimpleAsyncHTTPClient from tornado.testing import LogTrapTestCase, get_unused_port from tornado.web import RequestHandler, Application # Not using AsyncHTTPTestCase because we need control over the IOLoop. # Logging is tricky here so you may want to replace LogTrapTestCase # with unittest.TestCase when debugging. class ProcessTest(LogTrapTestCase): def get_app(self): class
(RequestHandler): def get(self): if self.get_argument("exit", None): # must use os._exit instead of sys.exit so unittest's # exception handler doesn't catch it os._exit(int(self.get_argument("exit"))) if self.get_argument("signal", None): os.kill(os.getpid(), int(self.get_argument("signal"))) self.write(str(os.getpid())) return Application([("/", ProcessHandler)]) def tearDown(self): if task_id() is not None: # We're in a child process, and probably got to this point # via an uncaught exception. If we return now, both # processes will continue with the rest of the test suite. # Exit now so the parent process will restart the child # (since we don't have a clean way to signal failure to # the parent that won't restart) logging.error("aborting child process from tearDown") logging.shutdown() os._exit(1) super(ProcessTest, self).tearDown() def test_multi_process(self): self.assertFalse(IOLoop.initialized()) port = get_unused_port() def get_url(path): return "http://127.0.0.1:%d%s" % (port, path) sockets = bind_sockets(port, "127.0.0.1") # ensure that none of these processes live too long signal.alarm(5) # master process try: id = fork_processes(3, max_restarts=3) except SystemExit as e: # if we exit cleanly from fork_processes, all the child processes # finished with status 0 self.assertEqual(e.code, 0) self.assertTrue(task_id() is None) for sock in sockets: sock.close() signal.alarm(0) return signal.alarm(5) # child process try: if id in (0, 1): signal.alarm(5) self.assertEqual(id, task_id()) server = HTTPServer(self.get_app()) server.add_sockets(sockets) IOLoop.instance().start() elif id == 2: signal.alarm(5) self.assertEqual(id, task_id()) for sock in sockets: sock.close() # Always use SimpleAsyncHTTPClient here; the curl # version appears to get confused sometimes if the # connection gets closed before it's had a chance to # switch from writing mode to reading mode. client = HTTPClient(SimpleAsyncHTTPClient) def fetch(url, fail_ok=False): try: return client.fetch(get_url(url)) except HTTPError as e: if not (fail_ok and e.code == 599): raise # Make two processes exit abnormally fetch("/?exit=2", fail_ok=True) fetch("/?exit=3", fail_ok=True) # They've been restarted, so a new fetch will work int(fetch("/").body) # Now the same with signals # Disabled because on the mac a process dying with a signal # can trigger an "Application exited abnormally; send error # report to Apple?" prompt. #fetch("/?signal=%d" % signal.SIGTERM, fail_ok=True) #fetch("/?signal=%d" % signal.SIGABRT, fail_ok=True) #int(fetch("/").body) # Now kill them normally so they won't be restarted fetch("/?exit=0", fail_ok=True) # One process left; watch it's pid change pid = int(fetch("/").body) fetch("/?exit=4", fail_ok=True) pid2 = int(fetch("/").body) self.assertNotEqual(pid, pid2) # Kill the last one so we shut down cleanly fetch("/?exit=0", fail_ok=True) os._exit(0) except Exception: logging.error("exception in child process %d", id, exc_info=True) raise if os.name != 'posix' or sys.platform == 'cygwin': # All sorts of unixisms here del ProcessTest
ProcessHandler
identifier_name
process_test.py
#!/usr/bin/env python import logging import os import signal import sys from tornado.httpclient import HTTPClient, HTTPError from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.netutil import bind_sockets from tornado.process import fork_processes, task_id from tornado.simple_httpclient import SimpleAsyncHTTPClient from tornado.testing import LogTrapTestCase, get_unused_port from tornado.web import RequestHandler, Application # Not using AsyncHTTPTestCase because we need control over the IOLoop. # Logging is tricky here so you may want to replace LogTrapTestCase # with unittest.TestCase when debugging. class ProcessTest(LogTrapTestCase): def get_app(self): class ProcessHandler(RequestHandler):
return Application([("/", ProcessHandler)]) def tearDown(self): if task_id() is not None: # We're in a child process, and probably got to this point # via an uncaught exception. If we return now, both # processes will continue with the rest of the test suite. # Exit now so the parent process will restart the child # (since we don't have a clean way to signal failure to # the parent that won't restart) logging.error("aborting child process from tearDown") logging.shutdown() os._exit(1) super(ProcessTest, self).tearDown() def test_multi_process(self): self.assertFalse(IOLoop.initialized()) port = get_unused_port() def get_url(path): return "http://127.0.0.1:%d%s" % (port, path) sockets = bind_sockets(port, "127.0.0.1") # ensure that none of these processes live too long signal.alarm(5) # master process try: id = fork_processes(3, max_restarts=3) except SystemExit as e: # if we exit cleanly from fork_processes, all the child processes # finished with status 0 self.assertEqual(e.code, 0) self.assertTrue(task_id() is None) for sock in sockets: sock.close() signal.alarm(0) return signal.alarm(5) # child process try: if id in (0, 1): signal.alarm(5) self.assertEqual(id, task_id()) server = HTTPServer(self.get_app()) server.add_sockets(sockets) IOLoop.instance().start() elif id == 2: signal.alarm(5) self.assertEqual(id, task_id()) for sock in sockets: sock.close() # Always use SimpleAsyncHTTPClient here; the curl # version appears to get confused sometimes if the # connection gets closed before it's had a chance to # switch from writing mode to reading mode. client = HTTPClient(SimpleAsyncHTTPClient) def fetch(url, fail_ok=False): try: return client.fetch(get_url(url)) except HTTPError as e: if not (fail_ok and e.code == 599): raise # Make two processes exit abnormally fetch("/?exit=2", fail_ok=True) fetch("/?exit=3", fail_ok=True) # They've been restarted, so a new fetch will work int(fetch("/").body) # Now the same with signals # Disabled because on the mac a process dying with a signal # can trigger an "Application exited abnormally; send error # report to Apple?" prompt. #fetch("/?signal=%d" % signal.SIGTERM, fail_ok=True) #fetch("/?signal=%d" % signal.SIGABRT, fail_ok=True) #int(fetch("/").body) # Now kill them normally so they won't be restarted fetch("/?exit=0", fail_ok=True) # One process left; watch it's pid change pid = int(fetch("/").body) fetch("/?exit=4", fail_ok=True) pid2 = int(fetch("/").body) self.assertNotEqual(pid, pid2) # Kill the last one so we shut down cleanly fetch("/?exit=0", fail_ok=True) os._exit(0) except Exception: logging.error("exception in child process %d", id, exc_info=True) raise if os.name != 'posix' or sys.platform == 'cygwin': # All sorts of unixisms here del ProcessTest
def get(self): if self.get_argument("exit", None): # must use os._exit instead of sys.exit so unittest's # exception handler doesn't catch it os._exit(int(self.get_argument("exit"))) if self.get_argument("signal", None): os.kill(os.getpid(), int(self.get_argument("signal"))) self.write(str(os.getpid()))
identifier_body
process_test.py
#!/usr/bin/env python import logging import os import signal import sys from tornado.httpclient import HTTPClient, HTTPError from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.netutil import bind_sockets from tornado.process import fork_processes, task_id from tornado.simple_httpclient import SimpleAsyncHTTPClient from tornado.testing import LogTrapTestCase, get_unused_port from tornado.web import RequestHandler, Application # Not using AsyncHTTPTestCase because we need control over the IOLoop. # Logging is tricky here so you may want to replace LogTrapTestCase # with unittest.TestCase when debugging. class ProcessTest(LogTrapTestCase): def get_app(self): class ProcessHandler(RequestHandler): def get(self): if self.get_argument("exit", None): # must use os._exit instead of sys.exit so unittest's # exception handler doesn't catch it os._exit(int(self.get_argument("exit"))) if self.get_argument("signal", None): os.kill(os.getpid(), int(self.get_argument("signal"))) self.write(str(os.getpid())) return Application([("/", ProcessHandler)]) def tearDown(self): if task_id() is not None: # We're in a child process, and probably got to this point # via an uncaught exception. If we return now, both # processes will continue with the rest of the test suite. # Exit now so the parent process will restart the child # (since we don't have a clean way to signal failure to # the parent that won't restart) logging.error("aborting child process from tearDown") logging.shutdown() os._exit(1) super(ProcessTest, self).tearDown() def test_multi_process(self): self.assertFalse(IOLoop.initialized()) port = get_unused_port() def get_url(path): return "http://127.0.0.1:%d%s" % (port, path) sockets = bind_sockets(port, "127.0.0.1") # ensure that none of these processes live too long signal.alarm(5) # master process try: id = fork_processes(3, max_restarts=3) except SystemExit as e: # if we exit cleanly from fork_processes, all the child processes # finished with status 0 self.assertEqual(e.code, 0) self.assertTrue(task_id() is None) for sock in sockets: sock.close() signal.alarm(0) return signal.alarm(5) # child process try: if id in (0, 1): signal.alarm(5) self.assertEqual(id, task_id()) server = HTTPServer(self.get_app()) server.add_sockets(sockets) IOLoop.instance().start() elif id == 2: signal.alarm(5) self.assertEqual(id, task_id()) for sock in sockets:
# Always use SimpleAsyncHTTPClient here; the curl # version appears to get confused sometimes if the # connection gets closed before it's had a chance to # switch from writing mode to reading mode. client = HTTPClient(SimpleAsyncHTTPClient) def fetch(url, fail_ok=False): try: return client.fetch(get_url(url)) except HTTPError as e: if not (fail_ok and e.code == 599): raise # Make two processes exit abnormally fetch("/?exit=2", fail_ok=True) fetch("/?exit=3", fail_ok=True) # They've been restarted, so a new fetch will work int(fetch("/").body) # Now the same with signals # Disabled because on the mac a process dying with a signal # can trigger an "Application exited abnormally; send error # report to Apple?" prompt. #fetch("/?signal=%d" % signal.SIGTERM, fail_ok=True) #fetch("/?signal=%d" % signal.SIGABRT, fail_ok=True) #int(fetch("/").body) # Now kill them normally so they won't be restarted fetch("/?exit=0", fail_ok=True) # One process left; watch it's pid change pid = int(fetch("/").body) fetch("/?exit=4", fail_ok=True) pid2 = int(fetch("/").body) self.assertNotEqual(pid, pid2) # Kill the last one so we shut down cleanly fetch("/?exit=0", fail_ok=True) os._exit(0) except Exception: logging.error("exception in child process %d", id, exc_info=True) raise if os.name != 'posix' or sys.platform == 'cygwin': # All sorts of unixisms here del ProcessTest
sock.close()
conditional_block
process_test.py
#!/usr/bin/env python import logging import os import signal import sys from tornado.httpclient import HTTPClient, HTTPError from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.netutil import bind_sockets from tornado.process import fork_processes, task_id from tornado.simple_httpclient import SimpleAsyncHTTPClient from tornado.testing import LogTrapTestCase, get_unused_port from tornado.web import RequestHandler, Application # Not using AsyncHTTPTestCase because we need control over the IOLoop. # Logging is tricky here so you may want to replace LogTrapTestCase # with unittest.TestCase when debugging. class ProcessTest(LogTrapTestCase): def get_app(self): class ProcessHandler(RequestHandler): def get(self): if self.get_argument("exit", None): # must use os._exit instead of sys.exit so unittest's # exception handler doesn't catch it os._exit(int(self.get_argument("exit"))) if self.get_argument("signal", None): os.kill(os.getpid(), int(self.get_argument("signal"))) self.write(str(os.getpid())) return Application([("/", ProcessHandler)]) def tearDown(self): if task_id() is not None: # We're in a child process, and probably got to this point # via an uncaught exception. If we return now, both # processes will continue with the rest of the test suite.
os._exit(1) super(ProcessTest, self).tearDown() def test_multi_process(self): self.assertFalse(IOLoop.initialized()) port = get_unused_port() def get_url(path): return "http://127.0.0.1:%d%s" % (port, path) sockets = bind_sockets(port, "127.0.0.1") # ensure that none of these processes live too long signal.alarm(5) # master process try: id = fork_processes(3, max_restarts=3) except SystemExit as e: # if we exit cleanly from fork_processes, all the child processes # finished with status 0 self.assertEqual(e.code, 0) self.assertTrue(task_id() is None) for sock in sockets: sock.close() signal.alarm(0) return signal.alarm(5) # child process try: if id in (0, 1): signal.alarm(5) self.assertEqual(id, task_id()) server = HTTPServer(self.get_app()) server.add_sockets(sockets) IOLoop.instance().start() elif id == 2: signal.alarm(5) self.assertEqual(id, task_id()) for sock in sockets: sock.close() # Always use SimpleAsyncHTTPClient here; the curl # version appears to get confused sometimes if the # connection gets closed before it's had a chance to # switch from writing mode to reading mode. client = HTTPClient(SimpleAsyncHTTPClient) def fetch(url, fail_ok=False): try: return client.fetch(get_url(url)) except HTTPError as e: if not (fail_ok and e.code == 599): raise # Make two processes exit abnormally fetch("/?exit=2", fail_ok=True) fetch("/?exit=3", fail_ok=True) # They've been restarted, so a new fetch will work int(fetch("/").body) # Now the same with signals # Disabled because on the mac a process dying with a signal # can trigger an "Application exited abnormally; send error # report to Apple?" prompt. #fetch("/?signal=%d" % signal.SIGTERM, fail_ok=True) #fetch("/?signal=%d" % signal.SIGABRT, fail_ok=True) #int(fetch("/").body) # Now kill them normally so they won't be restarted fetch("/?exit=0", fail_ok=True) # One process left; watch it's pid change pid = int(fetch("/").body) fetch("/?exit=4", fail_ok=True) pid2 = int(fetch("/").body) self.assertNotEqual(pid, pid2) # Kill the last one so we shut down cleanly fetch("/?exit=0", fail_ok=True) os._exit(0) except Exception: logging.error("exception in child process %d", id, exc_info=True) raise if os.name != 'posix' or sys.platform == 'cygwin': # All sorts of unixisms here del ProcessTest
# Exit now so the parent process will restart the child # (since we don't have a clean way to signal failure to # the parent that won't restart) logging.error("aborting child process from tearDown") logging.shutdown()
random_line_split
style.ts
// Copyright (c) Jonathan Frederic, see the LICENSE file for more info. import utils = require('../utils/utils'); import generics = require('../utils/generics'); import styles = require('./init'); /** * Style */ export class Style extends utils.PosterClass { public comment: string; public string: string; public class_name: string; public keyword: string; public boolean: string; public function: string; public operator: string; public number: string; public ignore: string; public punctuation: string; public cursor: string; public cursor_width: string; public cursor_height: string; public selection: string; public selection_unfocused: string; public text: string; public background: string; public gutter: string; public gutter_text: string; public gutter_shadow: string; public constructor() { super([ 'comment', 'string', 'class_name', 'keyword', 'boolean', 'function', 'operator', 'number', 'ignore', 'punctuation', 'cursor', 'cursor_width', 'cursor_height', 'selection', 'selection_unfocused', 'text', 'background', 'gutter', 'gutter_text', 'gutter_shadow' ]); // Load the default style. this.load('peacock'); } /** * Get the value of a property of this instance. */ get(name: string, default_value?: any): any { name = name.replace(/-/g, '_'); return this[name] !== undefined ? this[name] : default_value; } /** * Load a rendering style * @param style - name of the built-in style * or style dictionary itself. * @return success */ public load(style: string): boolean; public load(style: generics.IDictionary<any>): boolean; public load(style: any): boolean { try { // Load the style if it's built-in. if (styles.styles[style])
// Read each attribute of the style. for (var key in style) { if (style.hasOwnProperty(key)) { this[key] = style[key]; } } return true; } catch (e) { console.error('Error loading style', e); return false; } } }
{ style = styles.styles[style].style; }
conditional_block
style.ts
// Copyright (c) Jonathan Frederic, see the LICENSE file for more info. import utils = require('../utils/utils'); import generics = require('../utils/generics'); import styles = require('./init'); /** * Style */ export class Style extends utils.PosterClass { public comment: string; public string: string; public class_name: string; public keyword: string; public boolean: string; public function: string; public operator: string; public number: string; public ignore: string; public punctuation: string; public cursor: string; public cursor_width: string; public cursor_height: string; public selection: string; public selection_unfocused: string; public text: string; public background: string; public gutter: string; public gutter_text: string; public gutter_shadow: string; public constructor() { super([ 'comment', 'string', 'class_name', 'keyword', 'boolean', 'function', 'operator', 'number', 'ignore', 'punctuation', 'cursor', 'cursor_width', 'cursor_height', 'selection', 'selection_unfocused', 'text', 'background', 'gutter', 'gutter_text', 'gutter_shadow' ]); // Load the default style. this.load('peacock'); } /** * Get the value of a property of this instance. */
(name: string, default_value?: any): any { name = name.replace(/-/g, '_'); return this[name] !== undefined ? this[name] : default_value; } /** * Load a rendering style * @param style - name of the built-in style * or style dictionary itself. * @return success */ public load(style: string): boolean; public load(style: generics.IDictionary<any>): boolean; public load(style: any): boolean { try { // Load the style if it's built-in. if (styles.styles[style]) { style = styles.styles[style].style; } // Read each attribute of the style. for (var key in style) { if (style.hasOwnProperty(key)) { this[key] = style[key]; } } return true; } catch (e) { console.error('Error loading style', e); return false; } } }
get
identifier_name
style.ts
// Copyright (c) Jonathan Frederic, see the LICENSE file for more info. import utils = require('../utils/utils'); import generics = require('../utils/generics'); import styles = require('./init'); /** * Style */ export class Style extends utils.PosterClass { public comment: string; public string: string; public class_name: string; public keyword: string; public boolean: string; public function: string; public operator: string; public number: string; public ignore: string; public punctuation: string; public cursor: string; public cursor_width: string; public cursor_height: string; public selection: string; public selection_unfocused: string; public text: string; public background: string; public gutter: string; public gutter_text: string; public gutter_shadow: string; public constructor() { super([ 'comment', 'string', 'class_name', 'keyword', 'boolean', 'function', 'operator', 'number', 'ignore', 'punctuation', 'cursor', 'cursor_width', 'cursor_height', 'selection', 'selection_unfocused',
'gutter_text', 'gutter_shadow' ]); // Load the default style. this.load('peacock'); } /** * Get the value of a property of this instance. */ get(name: string, default_value?: any): any { name = name.replace(/-/g, '_'); return this[name] !== undefined ? this[name] : default_value; } /** * Load a rendering style * @param style - name of the built-in style * or style dictionary itself. * @return success */ public load(style: string): boolean; public load(style: generics.IDictionary<any>): boolean; public load(style: any): boolean { try { // Load the style if it's built-in. if (styles.styles[style]) { style = styles.styles[style].style; } // Read each attribute of the style. for (var key in style) { if (style.hasOwnProperty(key)) { this[key] = style[key]; } } return true; } catch (e) { console.error('Error loading style', e); return false; } } }
'text', 'background', 'gutter',
random_line_split
style.ts
// Copyright (c) Jonathan Frederic, see the LICENSE file for more info. import utils = require('../utils/utils'); import generics = require('../utils/generics'); import styles = require('./init'); /** * Style */ export class Style extends utils.PosterClass { public comment: string; public string: string; public class_name: string; public keyword: string; public boolean: string; public function: string; public operator: string; public number: string; public ignore: string; public punctuation: string; public cursor: string; public cursor_width: string; public cursor_height: string; public selection: string; public selection_unfocused: string; public text: string; public background: string; public gutter: string; public gutter_text: string; public gutter_shadow: string; public constructor()
/** * Get the value of a property of this instance. */ get(name: string, default_value?: any): any { name = name.replace(/-/g, '_'); return this[name] !== undefined ? this[name] : default_value; } /** * Load a rendering style * @param style - name of the built-in style * or style dictionary itself. * @return success */ public load(style: string): boolean; public load(style: generics.IDictionary<any>): boolean; public load(style: any): boolean { try { // Load the style if it's built-in. if (styles.styles[style]) { style = styles.styles[style].style; } // Read each attribute of the style. for (var key in style) { if (style.hasOwnProperty(key)) { this[key] = style[key]; } } return true; } catch (e) { console.error('Error loading style', e); return false; } } }
{ super([ 'comment', 'string', 'class_name', 'keyword', 'boolean', 'function', 'operator', 'number', 'ignore', 'punctuation', 'cursor', 'cursor_width', 'cursor_height', 'selection', 'selection_unfocused', 'text', 'background', 'gutter', 'gutter_text', 'gutter_shadow' ]); // Load the default style. this.load('peacock'); }
identifier_body
uievent.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::UIEventBinding; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; use dom::bindings::codegen::InheritTypes::{EventCast, UIEventDerived}; use dom::bindings::error::Fallible; use dom::bindings::global::{GlobalRef, Window}; use dom::bindings::js::{JS, JSRef, RootedReference, Temporary, OptionalSettable}; use dom::bindings::trace::Traceable; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::event::{Event, EventTypeId, UIEventTypeId}; use dom::window::Window; use servo_util::str::DOMString; use std::cell::Cell; #[deriving(Encodable)] #[must_root] pub struct UIEvent { pub event: Event, view: Cell<Option<JS<Window>>>, detail: Traceable<Cell<i32>> } impl UIEventDerived for Event { fn is_uievent(&self) -> bool { self.type_id == UIEventTypeId } } impl UIEvent { pub fn new_inherited(type_id: EventTypeId) -> UIEvent { UIEvent { event: Event::new_inherited(type_id), view: Cell::new(None), detail: Traceable::new(Cell::new(0)), } } pub fn new_uninitialized(window: JSRef<Window>) -> Temporary<UIEvent> { reflect_dom_object(box UIEvent::new_inherited(UIEventTypeId), &Window(window), UIEventBinding::Wrap) }
can_bubble: bool, cancelable: bool, view: Option<JSRef<Window>>, detail: i32) -> Temporary<UIEvent> { let ev = UIEvent::new_uninitialized(window).root(); ev.deref().InitUIEvent(type_, can_bubble, cancelable, view, detail); Temporary::from_rooted(*ev) } pub fn Constructor(global: &GlobalRef, type_: DOMString, init: &UIEventBinding::UIEventInit) -> Fallible<Temporary<UIEvent>> { let event = UIEvent::new(global.as_window(), type_, init.parent.bubbles, init.parent.cancelable, init.view.root_ref(), init.detail); Ok(event) } } impl<'a> UIEventMethods for JSRef<'a, UIEvent> { fn GetView(self) -> Option<Temporary<Window>> { self.view.get().map(|view| Temporary::new(view)) } fn Detail(self) -> i32 { self.detail.deref().get() } fn InitUIEvent(self, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<JSRef<Window>>, detail: i32) { let event: JSRef<Event> = EventCast::from_ref(self); event.InitEvent(type_, can_bubble, cancelable); self.view.assign(view); self.detail.deref().set(detail); } } impl Reflectable for UIEvent { fn reflector<'a>(&'a self) -> &'a Reflector { self.event.reflector() } }
pub fn new(window: JSRef<Window>, type_: DOMString,
random_line_split
uievent.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::UIEventBinding; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; use dom::bindings::codegen::InheritTypes::{EventCast, UIEventDerived}; use dom::bindings::error::Fallible; use dom::bindings::global::{GlobalRef, Window}; use dom::bindings::js::{JS, JSRef, RootedReference, Temporary, OptionalSettable}; use dom::bindings::trace::Traceable; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::event::{Event, EventTypeId, UIEventTypeId}; use dom::window::Window; use servo_util::str::DOMString; use std::cell::Cell; #[deriving(Encodable)] #[must_root] pub struct
{ pub event: Event, view: Cell<Option<JS<Window>>>, detail: Traceable<Cell<i32>> } impl UIEventDerived for Event { fn is_uievent(&self) -> bool { self.type_id == UIEventTypeId } } impl UIEvent { pub fn new_inherited(type_id: EventTypeId) -> UIEvent { UIEvent { event: Event::new_inherited(type_id), view: Cell::new(None), detail: Traceable::new(Cell::new(0)), } } pub fn new_uninitialized(window: JSRef<Window>) -> Temporary<UIEvent> { reflect_dom_object(box UIEvent::new_inherited(UIEventTypeId), &Window(window), UIEventBinding::Wrap) } pub fn new(window: JSRef<Window>, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<JSRef<Window>>, detail: i32) -> Temporary<UIEvent> { let ev = UIEvent::new_uninitialized(window).root(); ev.deref().InitUIEvent(type_, can_bubble, cancelable, view, detail); Temporary::from_rooted(*ev) } pub fn Constructor(global: &GlobalRef, type_: DOMString, init: &UIEventBinding::UIEventInit) -> Fallible<Temporary<UIEvent>> { let event = UIEvent::new(global.as_window(), type_, init.parent.bubbles, init.parent.cancelable, init.view.root_ref(), init.detail); Ok(event) } } impl<'a> UIEventMethods for JSRef<'a, UIEvent> { fn GetView(self) -> Option<Temporary<Window>> { self.view.get().map(|view| Temporary::new(view)) } fn Detail(self) -> i32 { self.detail.deref().get() } fn InitUIEvent(self, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<JSRef<Window>>, detail: i32) { let event: JSRef<Event> = EventCast::from_ref(self); event.InitEvent(type_, can_bubble, cancelable); self.view.assign(view); self.detail.deref().set(detail); } } impl Reflectable for UIEvent { fn reflector<'a>(&'a self) -> &'a Reflector { self.event.reflector() } }
UIEvent
identifier_name
uievent.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::UIEventBinding; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; use dom::bindings::codegen::InheritTypes::{EventCast, UIEventDerived}; use dom::bindings::error::Fallible; use dom::bindings::global::{GlobalRef, Window}; use dom::bindings::js::{JS, JSRef, RootedReference, Temporary, OptionalSettable}; use dom::bindings::trace::Traceable; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::event::{Event, EventTypeId, UIEventTypeId}; use dom::window::Window; use servo_util::str::DOMString; use std::cell::Cell; #[deriving(Encodable)] #[must_root] pub struct UIEvent { pub event: Event, view: Cell<Option<JS<Window>>>, detail: Traceable<Cell<i32>> } impl UIEventDerived for Event { fn is_uievent(&self) -> bool { self.type_id == UIEventTypeId } } impl UIEvent { pub fn new_inherited(type_id: EventTypeId) -> UIEvent
pub fn new_uninitialized(window: JSRef<Window>) -> Temporary<UIEvent> { reflect_dom_object(box UIEvent::new_inherited(UIEventTypeId), &Window(window), UIEventBinding::Wrap) } pub fn new(window: JSRef<Window>, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<JSRef<Window>>, detail: i32) -> Temporary<UIEvent> { let ev = UIEvent::new_uninitialized(window).root(); ev.deref().InitUIEvent(type_, can_bubble, cancelable, view, detail); Temporary::from_rooted(*ev) } pub fn Constructor(global: &GlobalRef, type_: DOMString, init: &UIEventBinding::UIEventInit) -> Fallible<Temporary<UIEvent>> { let event = UIEvent::new(global.as_window(), type_, init.parent.bubbles, init.parent.cancelable, init.view.root_ref(), init.detail); Ok(event) } } impl<'a> UIEventMethods for JSRef<'a, UIEvent> { fn GetView(self) -> Option<Temporary<Window>> { self.view.get().map(|view| Temporary::new(view)) } fn Detail(self) -> i32 { self.detail.deref().get() } fn InitUIEvent(self, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<JSRef<Window>>, detail: i32) { let event: JSRef<Event> = EventCast::from_ref(self); event.InitEvent(type_, can_bubble, cancelable); self.view.assign(view); self.detail.deref().set(detail); } } impl Reflectable for UIEvent { fn reflector<'a>(&'a self) -> &'a Reflector { self.event.reflector() } }
{ UIEvent { event: Event::new_inherited(type_id), view: Cell::new(None), detail: Traceable::new(Cell::new(0)), } }
identifier_body
activityAdd.component.ts
import { Component } from '@angular/core'; import { User } from '../user/user.entity' import { Answer } from '../topics/answer.entity' import { Router, ActivatedRoute } from '@angular/router'; import { LoginService } from "../login/login.service"; import { Activity } from './activity.entity' import { ActivityService } from './activity.service' @Component({ selector: 'activityAdd', templateUrl: './activityAdd.component.html' }) export class ActivityAddComponent { contentN: string; nameActivityN: string; activityTypeN: string='WATCHEDMOVIE'; formData: Activity = { content: '', nameactivity: '', activityType: '' } constructor(private activatedRoute: ActivatedRoute, private router: Router, private loginService: LoginService, private activityService: ActivityService) { }
() { this.formData.content = this.contentN; this.formData.nameactivity = this.nameActivityN; this.formData.activityType = this.activityTypeN; this.activityService.addActivity(this.formData).subscribe( response => this.router.navigate(['/activity']) ); } }
addNewActivity
identifier_name
activityAdd.component.ts
import { Component } from '@angular/core'; import { User } from '../user/user.entity' import { Answer } from '../topics/answer.entity' import { Router, ActivatedRoute } from '@angular/router'; import { LoginService } from "../login/login.service"; import { Activity } from './activity.entity' import { ActivityService } from './activity.service' @Component({ selector: 'activityAdd', templateUrl: './activityAdd.component.html' }) export class ActivityAddComponent { contentN: string; nameActivityN: string; activityTypeN: string='WATCHEDMOVIE'; formData: Activity = { content: '', nameactivity: '', activityType: '' } constructor(private activatedRoute: ActivatedRoute, private router: Router, private loginService: LoginService, private activityService: ActivityService) { }
this.formData.content = this.contentN; this.formData.nameactivity = this.nameActivityN; this.formData.activityType = this.activityTypeN; this.activityService.addActivity(this.formData).subscribe( response => this.router.navigate(['/activity']) ); } }
addNewActivity() {
random_line_split
activityAdd.component.ts
import { Component } from '@angular/core'; import { User } from '../user/user.entity' import { Answer } from '../topics/answer.entity' import { Router, ActivatedRoute } from '@angular/router'; import { LoginService } from "../login/login.service"; import { Activity } from './activity.entity' import { ActivityService } from './activity.service' @Component({ selector: 'activityAdd', templateUrl: './activityAdd.component.html' }) export class ActivityAddComponent { contentN: string; nameActivityN: string; activityTypeN: string='WATCHEDMOVIE'; formData: Activity = { content: '', nameactivity: '', activityType: '' } constructor(private activatedRoute: ActivatedRoute, private router: Router, private loginService: LoginService, private activityService: ActivityService) { } addNewActivity()
}
{ this.formData.content = this.contentN; this.formData.nameactivity = this.nameActivityN; this.formData.activityType = this.activityTypeN; this.activityService.addActivity(this.formData).subscribe( response => this.router.navigate(['/activity']) ); }
identifier_body
customize_form.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. # MIT License. See license.txt from __future__ import unicode_literals """ Customize Form is a Single DocType used to mask the Property Setter Thus providing a better UI from user perspective """ import webnotes from webnotes.utils import cstr class DocType: def __init__(self, doc, doclist=[]): self.doc, self.doclist = doc, doclist self.doctype_properties = [ 'search_fields', 'default_print_format', 'read_only_onload', 'allow_print', 'allow_email', 'allow_copy', 'allow_attach', 'max_attachments' ] self.docfield_properties = [ 'idx', 'label', 'fieldtype', 'fieldname', 'options', 'permlevel', 'width', 'print_width', 'reqd', 'in_filter', 'in_list_view', 'hidden', 'print_hide', 'report_hide', 'allow_on_submit', 'depends_on', 'description', 'default', 'name' ] self.property_restrictions = { 'fieldtype': [['Currency', 'Float'], ['Small Text', 'Data'], ['Text', 'Text Editor', 'Code']], } self.forbidden_properties = ['idx'] def get(self): """ Gets DocFields applied with Property Setter customizations via Customize Form Field """ self.clear() if self.doc.doc_type: from webnotes.model.doc import addchild for d in self.get_ref_doclist(): if d.doctype=='DocField': new = addchild(self.doc, 'fields', 'Customize Form Field', self.doclist) self.set( { 'list': self.docfield_properties, 'doc' : d, 'doc_to_set': new } ) elif d.doctype=='DocType': self.set({ 'list': self.doctype_properties, 'doc': d }) def get_ref_doclist(self): """ * Gets doclist of type self.doc.doc_type * Applies property setter properties on the doclist * returns the modified doclist """ from webnotes.model.doctype import get ref_doclist = get(self.doc.doc_type) ref_doclist = webnotes.doclist([ref_doclist[0]] + ref_doclist.get({"parent": self.doc.doc_type})) return ref_doclist def clear(self):
def set(self, args): """ Set a list of attributes of a doc to a value or to attribute values of a doc passed args can contain: * list --> list of attributes to set * doc_to_set --> defaults to self.doc * value --> to set all attributes to one value eg. None * doc --> copy attributes from doc to doc_to_set """ if not 'doc_to_set' in args: args['doc_to_set'] = self.doc if 'list' in args: if 'value' in args: for f in args['list']: args['doc_to_set'].fields[f] = None elif 'doc' in args: for f in args['list']: args['doc_to_set'].fields[f] = args['doc'].fields.get(f) else: webnotes.msgprint("Please specify args['list'] to set", raise_exception=1) def post(self): """ Save diff between Customize Form Bean and DocType Bean as property setter entries """ if self.doc.doc_type: from webnotes.model import doc from core.doctype.doctype.doctype import validate_fields_for_doctype this_doclist = webnotes.doclist([self.doc] + self.doclist) ref_doclist = self.get_ref_doclist() dt_doclist = doc.get('DocType', self.doc.doc_type) # get a list of property setter docs diff_list = self.diff(this_doclist, ref_doclist, dt_doclist) self.set_properties(diff_list) validate_fields_for_doctype(self.doc.doc_type) webnotes.clear_cache(doctype=self.doc.doc_type) webnotes.msgprint("Updated") def diff(self, new_dl, ref_dl, dt_dl): """ Get difference between new_dl doclist and ref_dl doclist then check how it differs from dt_dl i.e. default doclist """ import re self.defaults = self.get_defaults() diff_list = [] for new_d in new_dl: for ref_d in ref_dl: if ref_d.doctype == 'DocField' and new_d.name == ref_d.name: for prop in self.docfield_properties: # do not set forbidden properties like idx if prop in self.forbidden_properties: continue d = self.prepare_to_set(prop, new_d, ref_d, dt_dl) if d: diff_list.append(d) break elif ref_d.doctype == 'DocType' and new_d.doctype == 'Customize Form': for prop in self.doctype_properties: d = self.prepare_to_set(prop, new_d, ref_d, dt_dl) if d: diff_list.append(d) break return diff_list def get_defaults(self): """ Get fieldtype and default value for properties of a field """ df_defaults = webnotes.conn.sql(""" SELECT fieldname, fieldtype, `default`, label FROM `tabDocField` WHERE parent='DocField' or parent='DocType'""", as_dict=1) defaults = {} for d in df_defaults: defaults[d['fieldname']] = d defaults['idx'] = {'fieldname' : 'idx', 'fieldtype' : 'Int', 'default' : 1, 'label' : 'idx'} defaults['previous_field'] = {'fieldname' : 'previous_field', 'fieldtype' : 'Data', 'default' : None, 'label' : 'Previous Field'} return defaults def prepare_to_set(self, prop, new_d, ref_d, dt_doclist, delete=0): """ Prepares docs of property setter sets delete property if it is required to be deleted """ # Check if property has changed compared to when it was loaded if new_d.fields.get(prop) != ref_d.fields.get(prop) \ and not \ ( \ new_d.fields.get(prop) in [None, 0] \ and ref_d.fields.get(prop) in [None, 0] \ ) and not \ ( \ new_d.fields.get(prop) in [None, ''] \ and ref_d.fields.get(prop) in [None, ''] \ ): #webnotes.msgprint("new: " + str(new_d.fields[prop]) + " | old: " + str(ref_d.fields[prop])) # Check if the new property is same as that in original doctype # If yes, we need to delete the property setter entry for dt_d in dt_doclist: if dt_d.name == ref_d.name \ and (new_d.fields.get(prop) == dt_d.fields.get(prop) \ or \ ( \ new_d.fields.get(prop) in [None, 0] \ and dt_d.fields.get(prop) in [None, 0] \ ) or \ ( \ new_d.fields.get(prop) in [None, ''] \ and dt_d.fields.get(prop) in [None, ''] \ )): delete = 1 break value = new_d.fields.get(prop) if prop in self.property_restrictions: allow_change = False for restrict_list in self.property_restrictions.get(prop): if value in restrict_list and \ ref_d.fields.get(prop) in restrict_list: allow_change = True break if not allow_change: webnotes.msgprint("""\ You cannot change '%s' of '%s' from '%s' to '%s'. %s can only be changed among %s. <i>Ignoring this change and saving.</i>""" % \ (self.defaults.get(prop, {}).get("label") or prop, new_d.fields.get("label") or new_d.fields.get("idx"), ref_d.fields.get(prop), value, self.defaults.get(prop, {}).get("label") or prop, " -or- ".join([", ".join(r) for r in \ self.property_restrictions.get(prop)]))) return None # If the above conditions are fulfilled, # create a property setter doc, but dont save it yet. from webnotes.model.doc import Document d = Document('Property Setter') d.doctype_or_field = ref_d.doctype=='DocField' and 'DocField' or 'DocType' d.doc_type = self.doc.doc_type d.field_name = ref_d.fieldname d.property = prop d.value = value d.property_type = self.defaults[prop]['fieldtype'] #d.default_value = self.defaults[prop]['default'] if delete: d.delete = 1 if d.select_item: d.select_item = self.remove_forbidden(d.select_item) # return the property setter doc return d else: return None def set_properties(self, ps_doclist): """ * Delete a property setter entry + if it already exists + if marked for deletion * Save the property setter doc in the list """ for d in ps_doclist: # Delete existing property setter entry if not d.fields.get("field_name"): webnotes.conn.sql(""" DELETE FROM `tabProperty Setter` WHERE doc_type = %(doc_type)s AND property = %(property)s""", d.fields) else: webnotes.conn.sql(""" DELETE FROM `tabProperty Setter` WHERE doc_type = %(doc_type)s AND field_name = %(field_name)s AND property = %(property)s""", d.fields) # Save the property setter doc if not marked for deletion i.e. delete=0 if not d.delete: d.save(1) def delete(self): """ Deletes all property setter entries for the selected doctype and resets it to standard """ if self.doc.doc_type: webnotes.conn.sql(""" DELETE FROM `tabProperty Setter` WHERE doc_type = %s""", self.doc.doc_type) webnotes.clear_cache(doctype=self.doc.doc_type) self.get() def remove_forbidden(self, string): """ Replace forbidden characters with a space """ forbidden = ['%', "'", '"', '#', '*', '?', '`'] for f in forbidden: string.replace(f, ' ')
""" Clear fields in the doc """ # Clear table before adding new doctype's fields self.doclist = self.doc.clear_table(self.doclist, 'fields') self.set({ 'list': self.doctype_properties, 'value': None })
identifier_body
customize_form.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. # MIT License. See license.txt from __future__ import unicode_literals """ Customize Form is a Single DocType used to mask the Property Setter Thus providing a better UI from user perspective """ import webnotes from webnotes.utils import cstr class DocType: def __init__(self, doc, doclist=[]): self.doc, self.doclist = doc, doclist self.doctype_properties = [ 'search_fields', 'default_print_format', 'read_only_onload', 'allow_print', 'allow_email', 'allow_copy', 'allow_attach', 'max_attachments' ] self.docfield_properties = [ 'idx', 'label', 'fieldtype', 'fieldname', 'options', 'permlevel', 'width', 'print_width', 'reqd', 'in_filter', 'in_list_view', 'hidden', 'print_hide', 'report_hide', 'allow_on_submit', 'depends_on', 'description', 'default', 'name' ] self.property_restrictions = { 'fieldtype': [['Currency', 'Float'], ['Small Text', 'Data'], ['Text', 'Text Editor', 'Code']], } self.forbidden_properties = ['idx'] def get(self): """ Gets DocFields applied with Property Setter customizations via Customize Form Field """ self.clear() if self.doc.doc_type: from webnotes.model.doc import addchild for d in self.get_ref_doclist(): if d.doctype=='DocField': new = addchild(self.doc, 'fields', 'Customize Form Field', self.doclist) self.set( { 'list': self.docfield_properties, 'doc' : d, 'doc_to_set': new } ) elif d.doctype=='DocType': self.set({ 'list': self.doctype_properties, 'doc': d }) def get_ref_doclist(self): """ * Gets doclist of type self.doc.doc_type * Applies property setter properties on the doclist * returns the modified doclist """ from webnotes.model.doctype import get ref_doclist = get(self.doc.doc_type) ref_doclist = webnotes.doclist([ref_doclist[0]] + ref_doclist.get({"parent": self.doc.doc_type})) return ref_doclist def clear(self): """ Clear fields in the doc """ # Clear table before adding new doctype's fields self.doclist = self.doc.clear_table(self.doclist, 'fields') self.set({ 'list': self.doctype_properties, 'value': None }) def set(self, args): """ Set a list of attributes of a doc to a value or to attribute values of a doc passed args can contain: * list --> list of attributes to set * doc_to_set --> defaults to self.doc * value --> to set all attributes to one value eg. None * doc --> copy attributes from doc to doc_to_set """ if not 'doc_to_set' in args: args['doc_to_set'] = self.doc if 'list' in args: if 'value' in args: for f in args['list']: args['doc_to_set'].fields[f] = None elif 'doc' in args: for f in args['list']: args['doc_to_set'].fields[f] = args['doc'].fields.get(f) else: webnotes.msgprint("Please specify args['list'] to set", raise_exception=1) def post(self): """ Save diff between Customize Form Bean and DocType Bean as property setter entries """ if self.doc.doc_type: from webnotes.model import doc from core.doctype.doctype.doctype import validate_fields_for_doctype this_doclist = webnotes.doclist([self.doc] + self.doclist) ref_doclist = self.get_ref_doclist() dt_doclist = doc.get('DocType', self.doc.doc_type) # get a list of property setter docs diff_list = self.diff(this_doclist, ref_doclist, dt_doclist) self.set_properties(diff_list) validate_fields_for_doctype(self.doc.doc_type) webnotes.clear_cache(doctype=self.doc.doc_type) webnotes.msgprint("Updated") def diff(self, new_dl, ref_dl, dt_dl): """ Get difference between new_dl doclist and ref_dl doclist then check how it differs from dt_dl i.e. default doclist """ import re self.defaults = self.get_defaults() diff_list = [] for new_d in new_dl: for ref_d in ref_dl: if ref_d.doctype == 'DocField' and new_d.name == ref_d.name: for prop in self.docfield_properties: # do not set forbidden properties like idx if prop in self.forbidden_properties: continue d = self.prepare_to_set(prop, new_d, ref_d, dt_dl) if d: diff_list.append(d) break elif ref_d.doctype == 'DocType' and new_d.doctype == 'Customize Form': for prop in self.doctype_properties: d = self.prepare_to_set(prop, new_d, ref_d, dt_dl) if d: diff_list.append(d) break return diff_list def get_defaults(self): """ Get fieldtype and default value for properties of a field """ df_defaults = webnotes.conn.sql(""" SELECT fieldname, fieldtype, `default`, label FROM `tabDocField` WHERE parent='DocField' or parent='DocType'""", as_dict=1) defaults = {} for d in df_defaults: defaults[d['fieldname']] = d defaults['idx'] = {'fieldname' : 'idx', 'fieldtype' : 'Int', 'default' : 1, 'label' : 'idx'} defaults['previous_field'] = {'fieldname' : 'previous_field', 'fieldtype' : 'Data', 'default' : None, 'label' : 'Previous Field'} return defaults def prepare_to_set(self, prop, new_d, ref_d, dt_doclist, delete=0): """ Prepares docs of property setter sets delete property if it is required to be deleted """ # Check if property has changed compared to when it was loaded if new_d.fields.get(prop) != ref_d.fields.get(prop) \ and not \ ( \ new_d.fields.get(prop) in [None, 0] \ and ref_d.fields.get(prop) in [None, 0] \ ) and not \ ( \ new_d.fields.get(prop) in [None, ''] \ and ref_d.fields.get(prop) in [None, ''] \ ): #webnotes.msgprint("new: " + str(new_d.fields[prop]) + " | old: " + str(ref_d.fields[prop])) # Check if the new property is same as that in original doctype # If yes, we need to delete the property setter entry for dt_d in dt_doclist: if dt_d.name == ref_d.name \ and (new_d.fields.get(prop) == dt_d.fields.get(prop) \ or \
( \ new_d.fields.get(prop) in [None, ''] \ and dt_d.fields.get(prop) in [None, ''] \ )): delete = 1 break value = new_d.fields.get(prop) if prop in self.property_restrictions: allow_change = False for restrict_list in self.property_restrictions.get(prop): if value in restrict_list and \ ref_d.fields.get(prop) in restrict_list: allow_change = True break if not allow_change: webnotes.msgprint("""\ You cannot change '%s' of '%s' from '%s' to '%s'. %s can only be changed among %s. <i>Ignoring this change and saving.</i>""" % \ (self.defaults.get(prop, {}).get("label") or prop, new_d.fields.get("label") or new_d.fields.get("idx"), ref_d.fields.get(prop), value, self.defaults.get(prop, {}).get("label") or prop, " -or- ".join([", ".join(r) for r in \ self.property_restrictions.get(prop)]))) return None # If the above conditions are fulfilled, # create a property setter doc, but dont save it yet. from webnotes.model.doc import Document d = Document('Property Setter') d.doctype_or_field = ref_d.doctype=='DocField' and 'DocField' or 'DocType' d.doc_type = self.doc.doc_type d.field_name = ref_d.fieldname d.property = prop d.value = value d.property_type = self.defaults[prop]['fieldtype'] #d.default_value = self.defaults[prop]['default'] if delete: d.delete = 1 if d.select_item: d.select_item = self.remove_forbidden(d.select_item) # return the property setter doc return d else: return None def set_properties(self, ps_doclist): """ * Delete a property setter entry + if it already exists + if marked for deletion * Save the property setter doc in the list """ for d in ps_doclist: # Delete existing property setter entry if not d.fields.get("field_name"): webnotes.conn.sql(""" DELETE FROM `tabProperty Setter` WHERE doc_type = %(doc_type)s AND property = %(property)s""", d.fields) else: webnotes.conn.sql(""" DELETE FROM `tabProperty Setter` WHERE doc_type = %(doc_type)s AND field_name = %(field_name)s AND property = %(property)s""", d.fields) # Save the property setter doc if not marked for deletion i.e. delete=0 if not d.delete: d.save(1) def delete(self): """ Deletes all property setter entries for the selected doctype and resets it to standard """ if self.doc.doc_type: webnotes.conn.sql(""" DELETE FROM `tabProperty Setter` WHERE doc_type = %s""", self.doc.doc_type) webnotes.clear_cache(doctype=self.doc.doc_type) self.get() def remove_forbidden(self, string): """ Replace forbidden characters with a space """ forbidden = ['%', "'", '"', '#', '*', '?', '`'] for f in forbidden: string.replace(f, ' ')
( \ new_d.fields.get(prop) in [None, 0] \ and dt_d.fields.get(prop) in [None, 0] \ ) or \
random_line_split
customize_form.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. # MIT License. See license.txt from __future__ import unicode_literals """ Customize Form is a Single DocType used to mask the Property Setter Thus providing a better UI from user perspective """ import webnotes from webnotes.utils import cstr class DocType: def __init__(self, doc, doclist=[]): self.doc, self.doclist = doc, doclist self.doctype_properties = [ 'search_fields', 'default_print_format', 'read_only_onload', 'allow_print', 'allow_email', 'allow_copy', 'allow_attach', 'max_attachments' ] self.docfield_properties = [ 'idx', 'label', 'fieldtype', 'fieldname', 'options', 'permlevel', 'width', 'print_width', 'reqd', 'in_filter', 'in_list_view', 'hidden', 'print_hide', 'report_hide', 'allow_on_submit', 'depends_on', 'description', 'default', 'name' ] self.property_restrictions = { 'fieldtype': [['Currency', 'Float'], ['Small Text', 'Data'], ['Text', 'Text Editor', 'Code']], } self.forbidden_properties = ['idx'] def get(self): """ Gets DocFields applied with Property Setter customizations via Customize Form Field """ self.clear() if self.doc.doc_type: from webnotes.model.doc import addchild for d in self.get_ref_doclist(): if d.doctype=='DocField': new = addchild(self.doc, 'fields', 'Customize Form Field', self.doclist) self.set( { 'list': self.docfield_properties, 'doc' : d, 'doc_to_set': new } ) elif d.doctype=='DocType': self.set({ 'list': self.doctype_properties, 'doc': d }) def get_ref_doclist(self): """ * Gets doclist of type self.doc.doc_type * Applies property setter properties on the doclist * returns the modified doclist """ from webnotes.model.doctype import get ref_doclist = get(self.doc.doc_type) ref_doclist = webnotes.doclist([ref_doclist[0]] + ref_doclist.get({"parent": self.doc.doc_type})) return ref_doclist def clear(self): """ Clear fields in the doc """ # Clear table before adding new doctype's fields self.doclist = self.doc.clear_table(self.doclist, 'fields') self.set({ 'list': self.doctype_properties, 'value': None }) def set(self, args): """ Set a list of attributes of a doc to a value or to attribute values of a doc passed args can contain: * list --> list of attributes to set * doc_to_set --> defaults to self.doc * value --> to set all attributes to one value eg. None * doc --> copy attributes from doc to doc_to_set """ if not 'doc_to_set' in args: args['doc_to_set'] = self.doc if 'list' in args: if 'value' in args: for f in args['list']: args['doc_to_set'].fields[f] = None elif 'doc' in args: for f in args['list']: args['doc_to_set'].fields[f] = args['doc'].fields.get(f) else: webnotes.msgprint("Please specify args['list'] to set", raise_exception=1) def post(self): """ Save diff between Customize Form Bean and DocType Bean as property setter entries """ if self.doc.doc_type: from webnotes.model import doc from core.doctype.doctype.doctype import validate_fields_for_doctype this_doclist = webnotes.doclist([self.doc] + self.doclist) ref_doclist = self.get_ref_doclist() dt_doclist = doc.get('DocType', self.doc.doc_type) # get a list of property setter docs diff_list = self.diff(this_doclist, ref_doclist, dt_doclist) self.set_properties(diff_list) validate_fields_for_doctype(self.doc.doc_type) webnotes.clear_cache(doctype=self.doc.doc_type) webnotes.msgprint("Updated") def diff(self, new_dl, ref_dl, dt_dl): """ Get difference between new_dl doclist and ref_dl doclist then check how it differs from dt_dl i.e. default doclist """ import re self.defaults = self.get_defaults() diff_list = [] for new_d in new_dl: for ref_d in ref_dl: if ref_d.doctype == 'DocField' and new_d.name == ref_d.name: for prop in self.docfield_properties: # do not set forbidden properties like idx if prop in self.forbidden_properties: continue d = self.prepare_to_set(prop, new_d, ref_d, dt_dl) if d:
break elif ref_d.doctype == 'DocType' and new_d.doctype == 'Customize Form': for prop in self.doctype_properties: d = self.prepare_to_set(prop, new_d, ref_d, dt_dl) if d: diff_list.append(d) break return diff_list def get_defaults(self): """ Get fieldtype and default value for properties of a field """ df_defaults = webnotes.conn.sql(""" SELECT fieldname, fieldtype, `default`, label FROM `tabDocField` WHERE parent='DocField' or parent='DocType'""", as_dict=1) defaults = {} for d in df_defaults: defaults[d['fieldname']] = d defaults['idx'] = {'fieldname' : 'idx', 'fieldtype' : 'Int', 'default' : 1, 'label' : 'idx'} defaults['previous_field'] = {'fieldname' : 'previous_field', 'fieldtype' : 'Data', 'default' : None, 'label' : 'Previous Field'} return defaults def prepare_to_set(self, prop, new_d, ref_d, dt_doclist, delete=0): """ Prepares docs of property setter sets delete property if it is required to be deleted """ # Check if property has changed compared to when it was loaded if new_d.fields.get(prop) != ref_d.fields.get(prop) \ and not \ ( \ new_d.fields.get(prop) in [None, 0] \ and ref_d.fields.get(prop) in [None, 0] \ ) and not \ ( \ new_d.fields.get(prop) in [None, ''] \ and ref_d.fields.get(prop) in [None, ''] \ ): #webnotes.msgprint("new: " + str(new_d.fields[prop]) + " | old: " + str(ref_d.fields[prop])) # Check if the new property is same as that in original doctype # If yes, we need to delete the property setter entry for dt_d in dt_doclist: if dt_d.name == ref_d.name \ and (new_d.fields.get(prop) == dt_d.fields.get(prop) \ or \ ( \ new_d.fields.get(prop) in [None, 0] \ and dt_d.fields.get(prop) in [None, 0] \ ) or \ ( \ new_d.fields.get(prop) in [None, ''] \ and dt_d.fields.get(prop) in [None, ''] \ )): delete = 1 break value = new_d.fields.get(prop) if prop in self.property_restrictions: allow_change = False for restrict_list in self.property_restrictions.get(prop): if value in restrict_list and \ ref_d.fields.get(prop) in restrict_list: allow_change = True break if not allow_change: webnotes.msgprint("""\ You cannot change '%s' of '%s' from '%s' to '%s'. %s can only be changed among %s. <i>Ignoring this change and saving.</i>""" % \ (self.defaults.get(prop, {}).get("label") or prop, new_d.fields.get("label") or new_d.fields.get("idx"), ref_d.fields.get(prop), value, self.defaults.get(prop, {}).get("label") or prop, " -or- ".join([", ".join(r) for r in \ self.property_restrictions.get(prop)]))) return None # If the above conditions are fulfilled, # create a property setter doc, but dont save it yet. from webnotes.model.doc import Document d = Document('Property Setter') d.doctype_or_field = ref_d.doctype=='DocField' and 'DocField' or 'DocType' d.doc_type = self.doc.doc_type d.field_name = ref_d.fieldname d.property = prop d.value = value d.property_type = self.defaults[prop]['fieldtype'] #d.default_value = self.defaults[prop]['default'] if delete: d.delete = 1 if d.select_item: d.select_item = self.remove_forbidden(d.select_item) # return the property setter doc return d else: return None def set_properties(self, ps_doclist): """ * Delete a property setter entry + if it already exists + if marked for deletion * Save the property setter doc in the list """ for d in ps_doclist: # Delete existing property setter entry if not d.fields.get("field_name"): webnotes.conn.sql(""" DELETE FROM `tabProperty Setter` WHERE doc_type = %(doc_type)s AND property = %(property)s""", d.fields) else: webnotes.conn.sql(""" DELETE FROM `tabProperty Setter` WHERE doc_type = %(doc_type)s AND field_name = %(field_name)s AND property = %(property)s""", d.fields) # Save the property setter doc if not marked for deletion i.e. delete=0 if not d.delete: d.save(1) def delete(self): """ Deletes all property setter entries for the selected doctype and resets it to standard """ if self.doc.doc_type: webnotes.conn.sql(""" DELETE FROM `tabProperty Setter` WHERE doc_type = %s""", self.doc.doc_type) webnotes.clear_cache(doctype=self.doc.doc_type) self.get() def remove_forbidden(self, string): """ Replace forbidden characters with a space """ forbidden = ['%', "'", '"', '#', '*', '?', '`'] for f in forbidden: string.replace(f, ' ')
diff_list.append(d)
conditional_block
customize_form.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. # MIT License. See license.txt from __future__ import unicode_literals """ Customize Form is a Single DocType used to mask the Property Setter Thus providing a better UI from user perspective """ import webnotes from webnotes.utils import cstr class DocType: def __init__(self, doc, doclist=[]): self.doc, self.doclist = doc, doclist self.doctype_properties = [ 'search_fields', 'default_print_format', 'read_only_onload', 'allow_print', 'allow_email', 'allow_copy', 'allow_attach', 'max_attachments' ] self.docfield_properties = [ 'idx', 'label', 'fieldtype', 'fieldname', 'options', 'permlevel', 'width', 'print_width', 'reqd', 'in_filter', 'in_list_view', 'hidden', 'print_hide', 'report_hide', 'allow_on_submit', 'depends_on', 'description', 'default', 'name' ] self.property_restrictions = { 'fieldtype': [['Currency', 'Float'], ['Small Text', 'Data'], ['Text', 'Text Editor', 'Code']], } self.forbidden_properties = ['idx'] def get(self): """ Gets DocFields applied with Property Setter customizations via Customize Form Field """ self.clear() if self.doc.doc_type: from webnotes.model.doc import addchild for d in self.get_ref_doclist(): if d.doctype=='DocField': new = addchild(self.doc, 'fields', 'Customize Form Field', self.doclist) self.set( { 'list': self.docfield_properties, 'doc' : d, 'doc_to_set': new } ) elif d.doctype=='DocType': self.set({ 'list': self.doctype_properties, 'doc': d }) def get_ref_doclist(self): """ * Gets doclist of type self.doc.doc_type * Applies property setter properties on the doclist * returns the modified doclist """ from webnotes.model.doctype import get ref_doclist = get(self.doc.doc_type) ref_doclist = webnotes.doclist([ref_doclist[0]] + ref_doclist.get({"parent": self.doc.doc_type})) return ref_doclist def
(self): """ Clear fields in the doc """ # Clear table before adding new doctype's fields self.doclist = self.doc.clear_table(self.doclist, 'fields') self.set({ 'list': self.doctype_properties, 'value': None }) def set(self, args): """ Set a list of attributes of a doc to a value or to attribute values of a doc passed args can contain: * list --> list of attributes to set * doc_to_set --> defaults to self.doc * value --> to set all attributes to one value eg. None * doc --> copy attributes from doc to doc_to_set """ if not 'doc_to_set' in args: args['doc_to_set'] = self.doc if 'list' in args: if 'value' in args: for f in args['list']: args['doc_to_set'].fields[f] = None elif 'doc' in args: for f in args['list']: args['doc_to_set'].fields[f] = args['doc'].fields.get(f) else: webnotes.msgprint("Please specify args['list'] to set", raise_exception=1) def post(self): """ Save diff between Customize Form Bean and DocType Bean as property setter entries """ if self.doc.doc_type: from webnotes.model import doc from core.doctype.doctype.doctype import validate_fields_for_doctype this_doclist = webnotes.doclist([self.doc] + self.doclist) ref_doclist = self.get_ref_doclist() dt_doclist = doc.get('DocType', self.doc.doc_type) # get a list of property setter docs diff_list = self.diff(this_doclist, ref_doclist, dt_doclist) self.set_properties(diff_list) validate_fields_for_doctype(self.doc.doc_type) webnotes.clear_cache(doctype=self.doc.doc_type) webnotes.msgprint("Updated") def diff(self, new_dl, ref_dl, dt_dl): """ Get difference between new_dl doclist and ref_dl doclist then check how it differs from dt_dl i.e. default doclist """ import re self.defaults = self.get_defaults() diff_list = [] for new_d in new_dl: for ref_d in ref_dl: if ref_d.doctype == 'DocField' and new_d.name == ref_d.name: for prop in self.docfield_properties: # do not set forbidden properties like idx if prop in self.forbidden_properties: continue d = self.prepare_to_set(prop, new_d, ref_d, dt_dl) if d: diff_list.append(d) break elif ref_d.doctype == 'DocType' and new_d.doctype == 'Customize Form': for prop in self.doctype_properties: d = self.prepare_to_set(prop, new_d, ref_d, dt_dl) if d: diff_list.append(d) break return diff_list def get_defaults(self): """ Get fieldtype and default value for properties of a field """ df_defaults = webnotes.conn.sql(""" SELECT fieldname, fieldtype, `default`, label FROM `tabDocField` WHERE parent='DocField' or parent='DocType'""", as_dict=1) defaults = {} for d in df_defaults: defaults[d['fieldname']] = d defaults['idx'] = {'fieldname' : 'idx', 'fieldtype' : 'Int', 'default' : 1, 'label' : 'idx'} defaults['previous_field'] = {'fieldname' : 'previous_field', 'fieldtype' : 'Data', 'default' : None, 'label' : 'Previous Field'} return defaults def prepare_to_set(self, prop, new_d, ref_d, dt_doclist, delete=0): """ Prepares docs of property setter sets delete property if it is required to be deleted """ # Check if property has changed compared to when it was loaded if new_d.fields.get(prop) != ref_d.fields.get(prop) \ and not \ ( \ new_d.fields.get(prop) in [None, 0] \ and ref_d.fields.get(prop) in [None, 0] \ ) and not \ ( \ new_d.fields.get(prop) in [None, ''] \ and ref_d.fields.get(prop) in [None, ''] \ ): #webnotes.msgprint("new: " + str(new_d.fields[prop]) + " | old: " + str(ref_d.fields[prop])) # Check if the new property is same as that in original doctype # If yes, we need to delete the property setter entry for dt_d in dt_doclist: if dt_d.name == ref_d.name \ and (new_d.fields.get(prop) == dt_d.fields.get(prop) \ or \ ( \ new_d.fields.get(prop) in [None, 0] \ and dt_d.fields.get(prop) in [None, 0] \ ) or \ ( \ new_d.fields.get(prop) in [None, ''] \ and dt_d.fields.get(prop) in [None, ''] \ )): delete = 1 break value = new_d.fields.get(prop) if prop in self.property_restrictions: allow_change = False for restrict_list in self.property_restrictions.get(prop): if value in restrict_list and \ ref_d.fields.get(prop) in restrict_list: allow_change = True break if not allow_change: webnotes.msgprint("""\ You cannot change '%s' of '%s' from '%s' to '%s'. %s can only be changed among %s. <i>Ignoring this change and saving.</i>""" % \ (self.defaults.get(prop, {}).get("label") or prop, new_d.fields.get("label") or new_d.fields.get("idx"), ref_d.fields.get(prop), value, self.defaults.get(prop, {}).get("label") or prop, " -or- ".join([", ".join(r) for r in \ self.property_restrictions.get(prop)]))) return None # If the above conditions are fulfilled, # create a property setter doc, but dont save it yet. from webnotes.model.doc import Document d = Document('Property Setter') d.doctype_or_field = ref_d.doctype=='DocField' and 'DocField' or 'DocType' d.doc_type = self.doc.doc_type d.field_name = ref_d.fieldname d.property = prop d.value = value d.property_type = self.defaults[prop]['fieldtype'] #d.default_value = self.defaults[prop]['default'] if delete: d.delete = 1 if d.select_item: d.select_item = self.remove_forbidden(d.select_item) # return the property setter doc return d else: return None def set_properties(self, ps_doclist): """ * Delete a property setter entry + if it already exists + if marked for deletion * Save the property setter doc in the list """ for d in ps_doclist: # Delete existing property setter entry if not d.fields.get("field_name"): webnotes.conn.sql(""" DELETE FROM `tabProperty Setter` WHERE doc_type = %(doc_type)s AND property = %(property)s""", d.fields) else: webnotes.conn.sql(""" DELETE FROM `tabProperty Setter` WHERE doc_type = %(doc_type)s AND field_name = %(field_name)s AND property = %(property)s""", d.fields) # Save the property setter doc if not marked for deletion i.e. delete=0 if not d.delete: d.save(1) def delete(self): """ Deletes all property setter entries for the selected doctype and resets it to standard """ if self.doc.doc_type: webnotes.conn.sql(""" DELETE FROM `tabProperty Setter` WHERE doc_type = %s""", self.doc.doc_type) webnotes.clear_cache(doctype=self.doc.doc_type) self.get() def remove_forbidden(self, string): """ Replace forbidden characters with a space """ forbidden = ['%', "'", '"', '#', '*', '?', '`'] for f in forbidden: string.replace(f, ' ')
clear
identifier_name
n.js
/************************************************************* * * MathJax/jax/output/HTML-CSS/entities/n.js * * Copyright (c) 2010-2014 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ (function (MATHML) { MathJax.Hub.Insert(MATHML.Parse.Entity,{ 'NJcy': '\u040A', 'Nacute': '\u0143', 'Ncaron': '\u0147', 'Ncedil': '\u0145', 'Ncy': '\u041D', 'NegativeMediumSpace': '\u200B', 'NegativeThickSpace': '\u200B', 'NegativeThinSpace': '\u200B', 'NegativeVeryThinSpace': '\u200B', 'NewLine': '\u000A', 'NoBreak': '\u2060', 'NonBreakingSpace': '\u00A0', 'Not': '\u2AEC', 'NotCongruent': '\u2262', 'NotCupCap': '\u226D', 'NotEqualTilde': '\u2242\u0338', 'NotGreaterFullEqual': '\u2267\u0338', 'NotGreaterGreater': '\u226B\u0338', 'NotGreaterLess': '\u2279', 'NotGreaterSlantEqual': '\u2A7E\u0338', 'NotGreaterTilde': '\u2275', 'NotHumpDownHump': '\u224E\u0338', 'NotHumpEqual': '\u224F\u0338', 'NotLeftTriangleBar': '\u29CF\u0338', 'NotLessGreater': '\u2278', 'NotLessLess': '\u226A\u0338', 'NotLessSlantEqual': '\u2A7D\u0338', 'NotLessTilde': '\u2274', 'NotNestedGreaterGreater': '\u2AA2\u0338', 'NotNestedLessLess': '\u2AA1\u0338', 'NotPrecedesEqual': '\u2AAF\u0338', 'NotReverseElement': '\u220C', 'NotRightTriangleBar': '\u29D0\u0338', 'NotSquareSubset': '\u228F\u0338', 'NotSquareSubsetEqual': '\u22E2', 'NotSquareSuperset': '\u2290\u0338', 'NotSquareSupersetEqual': '\u22E3', 'NotSubset': '\u2282\u20D2', 'NotSucceedsEqual': '\u2AB0\u0338', 'NotSucceedsTilde': '\u227F\u0338', 'NotSuperset': '\u2283\u20D2', 'NotTildeEqual': '\u2244', 'NotTildeFullEqual': '\u2247', 'NotTildeTilde': '\u2249', 'Ntilde': '\u00D1', 'Nu': '\u039D', 'nGg': '\u22D9\u0338', 'nGt': '\u226B\u20D2', 'nGtv': '\u226B\u0338', 'nLl': '\u22D8\u0338', 'nLt': '\u226A\u20D2', 'nLtv': '\u226A\u0338', 'nabla': '\u2207', 'nacute': '\u0144', 'nang': '\u2220\u20D2', 'nap': '\u2249', 'napE': '\u2A70\u0338', 'napid': '\u224B\u0338', 'napos': '\u0149', 'napprox': '\u2249', 'natural': '\u266E', 'naturals': '\u2115', 'nbsp': '\u00A0', 'nbump': '\u224E\u0338', 'nbumpe': '\u224F\u0338', 'ncap': '\u2A43', 'ncaron': '\u0148', 'ncedil': '\u0146', 'ncong': '\u2247', 'ncongdot': '\u2A6D\u0338', 'ncup': '\u2A42', 'ncy': '\u043D', 'ndash': '\u2013', 'ne': '\u2260', 'neArr': '\u21D7', 'nearhk': '\u2924', 'nearrow': '\u2197', 'nedot': '\u2250\u0338', 'nequiv': '\u2262', 'nesear': '\u2928', 'nesim': '\u2242\u0338', 'nexist': '\u2204', 'nexists': '\u2204', 'ngE': '\u2267\u0338', 'nge': '\u2271', 'ngeq': '\u2271', 'ngeqq': '\u2267\u0338', 'ngeqslant': '\u2A7E\u0338', 'nges': '\u2A7E\u0338', 'ngsim': '\u2275', 'ngt': '\u226F', 'ngtr': '\u226F', 'nhArr': '\u21CE', 'nhpar': '\u2AF2', 'ni': '\u220B', 'nis': '\u22FC', 'nisd': '\u22FA', 'niv': '\u220B', 'njcy': '\u045A', 'nlArr': '\u21CD', 'nlE': '\u2266\u0338', 'nldr': '\u2025', 'nle': '\u2270', 'nleftarrow': '\u219A', 'nleftrightarrow': '\u21AE', 'nleq': '\u2270', 'nleqq': '\u2266\u0338', 'nleqslant': '\u2A7D\u0338', 'nles': '\u2A7D\u0338', 'nless': '\u226E', 'nlsim': '\u2274', 'nlt': '\u226E', 'nltri': '\u22EA', 'nltrie': '\u22EC', 'nmid': '\u2224', 'notin': '\u2209', 'notinE': '\u22F9\u0338', 'notindot': '\u22F5\u0338', 'notinva': '\u2209', 'notinvb': '\u22F7',
'notinvc': '\u22F6', 'notni': '\u220C', 'notniva': '\u220C', 'notnivb': '\u22FE', 'notnivc': '\u22FD', 'npar': '\u2226', 'nparallel': '\u2226', 'nparsl': '\u2AFD\u20E5', 'npart': '\u2202\u0338', 'npolint': '\u2A14', 'npr': '\u2280', 'nprcue': '\u22E0', 'npre': '\u2AAF\u0338', 'nprec': '\u2280', 'npreceq': '\u2AAF\u0338', 'nrArr': '\u21CF', 'nrarrc': '\u2933\u0338', 'nrarrw': '\u219D\u0338', 'nrightarrow': '\u219B', 'nrtri': '\u22EB', 'nrtrie': '\u22ED', 'nsc': '\u2281', 'nsccue': '\u22E1', 'nsce': '\u2AB0\u0338', 'nshortmid': '\u2224', 'nshortparallel': '\u2226', 'nsim': '\u2241', 'nsime': '\u2244', 'nsimeq': '\u2244', 'nsmid': '\u2224', 'nspar': '\u2226', 'nsqsube': '\u22E2', 'nsqsupe': '\u22E3', 'nsub': '\u2284', 'nsubE': '\u2AC5\u0338', 'nsube': '\u2288', 'nsubset': '\u2282\u20D2', 'nsubseteq': '\u2288', 'nsubseteqq': '\u2AC5\u0338', 'nsucc': '\u2281', 'nsucceq': '\u2AB0\u0338', 'nsup': '\u2285', 'nsupE': '\u2AC6\u0338', 'nsupe': '\u2289', 'nsupset': '\u2283\u20D2', 'nsupseteq': '\u2289', 'nsupseteqq': '\u2AC6\u0338', 'ntgl': '\u2279', 'ntilde': '\u00F1', 'ntlg': '\u2278', 'ntriangleleft': '\u22EA', 'ntrianglelefteq': '\u22EC', 'ntriangleright': '\u22EB', 'ntrianglerighteq': '\u22ED', 'num': '\u0023', 'numero': '\u2116', 'numsp': '\u2007', 'nvHarr': '\u2904', 'nvap': '\u224D\u20D2', 'nvge': '\u2265\u20D2', 'nvgt': '\u003E\u20D2', 'nvinfin': '\u29DE', 'nvlArr': '\u2902', 'nvle': '\u2264\u20D2', 'nvlt': '\u003C\u20D2', 'nvltrie': '\u22B4\u20D2', 'nvrArr': '\u2903', 'nvrtrie': '\u22B5\u20D2', 'nvsim': '\u223C\u20D2', 'nwArr': '\u21D6', 'nwarhk': '\u2923', 'nwarrow': '\u2196', 'nwnear': '\u2927' }); MathJax.Ajax.loadComplete(MATHML.entityDir+"/n.js"); })(MathJax.InputJax.MathML);
random_line_split
common.py
"""Utilities for multiprocess tests running.""" # pylint: disable=invalid-name,super-init-not-called from __future__ import absolute_import import os import psutil from rotest.common import core_log PROCESS_TERMINATION_TIMEOUT = 10 class
(Exception): """Used to wrapping exceptions so they could be passed via queues. Queue pickles every object it is requires to pass, and since Traceback objects cannot be pickled and therfore cannot be transfered using queue, there is a need to pass the traceback in another way. This class is designed to wrap traceback strings in order to pass them between workers and the manager processes using Queue. """ def __init__(self, exception_string): self.message = exception_string def __str__(self): return self.message def get_item_by_id(test_item, item_id): """Return the requested test item by its identifier. Goes over the test item's sub tests recursively and returns the one that matches the requested identifier. The search algorithm assumes that the identifiers assignment was the default one (use of default indexer), which identifies the tests in a DFS recursion. The algorithm continues the search in the sub-branch which root has the highest identifier that is still smaller or equal to the searched identifier. Args: test_item (object): test instance object. item_id (number): requested test identifier. Returns: TestCase / TestSuite. test item object. """ if test_item.identifier == item_id: return test_item if test_item.IS_COMPLEX: sub_test = max([sub_test for sub_test in test_item if sub_test.identifier <= item_id], key=lambda test: test.identifier) return get_item_by_id(sub_test, item_id) def kill_process(process): """Kill a single process. Args: process (psutil.Process): process to kill. """ if not process.is_running(): return process.kill() try: process.wait(PROCESS_TERMINATION_TIMEOUT) except psutil.TimeoutExpired: core_log.warning("Process %d failed to terminate", process.pid) def kill_process_tree(process): """Kill a process and all its subprocesses. Note: Kill the process and all its sub processes recursively. If the given process is the current process - Kills the sub process before the given process. Otherwise - Kills the given process before its sub processes Args: process (psutil.Process): process to kill. """ sub_processes = process.children(recursive=True) if process.pid == os.getpid(): for sub_process in sub_processes: kill_process(sub_process) kill_process(process) else: kill_process(process) for sub_process in sub_processes: kill_process(sub_process)
WrappedException
identifier_name
common.py
"""Utilities for multiprocess tests running.""" # pylint: disable=invalid-name,super-init-not-called from __future__ import absolute_import import os import psutil from rotest.common import core_log PROCESS_TERMINATION_TIMEOUT = 10 class WrappedException(Exception): """Used to wrapping exceptions so they could be passed via queues. Queue pickles every object it is requires to pass, and since Traceback objects cannot be pickled and therfore cannot be transfered using queue, there is a need to pass the traceback in another way. This class is designed to wrap traceback strings in order to pass them between workers and the manager processes using Queue. """ def __init__(self, exception_string): self.message = exception_string def __str__(self): return self.message def get_item_by_id(test_item, item_id): """Return the requested test item by its identifier. Goes over the test item's sub tests recursively and returns the one that matches the requested identifier. The search algorithm assumes that the identifiers assignment was the default one (use of default indexer), which identifies the tests in a DFS recursion. The algorithm continues the search in the sub-branch which root has the highest identifier that is still smaller or equal to the searched identifier. Args: test_item (object): test instance object. item_id (number): requested test identifier. Returns: TestCase / TestSuite. test item object. """ if test_item.identifier == item_id: return test_item if test_item.IS_COMPLEX: sub_test = max([sub_test for sub_test in test_item if sub_test.identifier <= item_id], key=lambda test: test.identifier) return get_item_by_id(sub_test, item_id) def kill_process(process): """Kill a single process. Args: process (psutil.Process): process to kill. """ if not process.is_running(): return process.kill() try: process.wait(PROCESS_TERMINATION_TIMEOUT) except psutil.TimeoutExpired: core_log.warning("Process %d failed to terminate", process.pid) def kill_process_tree(process):
"""Kill a process and all its subprocesses. Note: Kill the process and all its sub processes recursively. If the given process is the current process - Kills the sub process before the given process. Otherwise - Kills the given process before its sub processes Args: process (psutil.Process): process to kill. """ sub_processes = process.children(recursive=True) if process.pid == os.getpid(): for sub_process in sub_processes: kill_process(sub_process) kill_process(process) else: kill_process(process) for sub_process in sub_processes: kill_process(sub_process)
identifier_body
common.py
"""Utilities for multiprocess tests running.""" # pylint: disable=invalid-name,super-init-not-called from __future__ import absolute_import import os import psutil from rotest.common import core_log PROCESS_TERMINATION_TIMEOUT = 10 class WrappedException(Exception): """Used to wrapping exceptions so they could be passed via queues. Queue pickles every object it is requires to pass, and since Traceback objects cannot be pickled and therfore cannot be transfered using queue, there is a need to pass the traceback in another way. This class is designed to wrap traceback strings in order to pass them between workers and the manager processes using Queue. """ def __init__(self, exception_string): self.message = exception_string def __str__(self): return self.message def get_item_by_id(test_item, item_id): """Return the requested test item by its identifier. Goes over the test item's sub tests recursively and returns the one that matches the requested identifier. The search algorithm assumes that the identifiers assignment was the default one (use of default indexer), which identifies the tests in a DFS recursion. The algorithm continues the search in the sub-branch which root has the highest identifier that is still smaller or equal to the searched identifier. Args: test_item (object): test instance object. item_id (number): requested test identifier. Returns: TestCase / TestSuite. test item object. """ if test_item.identifier == item_id:
if test_item.IS_COMPLEX: sub_test = max([sub_test for sub_test in test_item if sub_test.identifier <= item_id], key=lambda test: test.identifier) return get_item_by_id(sub_test, item_id) def kill_process(process): """Kill a single process. Args: process (psutil.Process): process to kill. """ if not process.is_running(): return process.kill() try: process.wait(PROCESS_TERMINATION_TIMEOUT) except psutil.TimeoutExpired: core_log.warning("Process %d failed to terminate", process.pid) def kill_process_tree(process): """Kill a process and all its subprocesses. Note: Kill the process and all its sub processes recursively. If the given process is the current process - Kills the sub process before the given process. Otherwise - Kills the given process before its sub processes Args: process (psutil.Process): process to kill. """ sub_processes = process.children(recursive=True) if process.pid == os.getpid(): for sub_process in sub_processes: kill_process(sub_process) kill_process(process) else: kill_process(process) for sub_process in sub_processes: kill_process(sub_process)
return test_item
conditional_block
common.py
"""Utilities for multiprocess tests running.""" # pylint: disable=invalid-name,super-init-not-called from __future__ import absolute_import import os import psutil from rotest.common import core_log PROCESS_TERMINATION_TIMEOUT = 10 class WrappedException(Exception): """Used to wrapping exceptions so they could be passed via queues. Queue pickles every object it is requires to pass, and since Traceback objects cannot be pickled and therfore cannot be transfered using queue, there is a need to pass the traceback in another way. This class is designed to wrap traceback strings in order to pass them between workers and the manager processes using Queue. """ def __init__(self, exception_string): self.message = exception_string def __str__(self): return self.message
Goes over the test item's sub tests recursively and returns the one that matches the requested identifier. The search algorithm assumes that the identifiers assignment was the default one (use of default indexer), which identifies the tests in a DFS recursion. The algorithm continues the search in the sub-branch which root has the highest identifier that is still smaller or equal to the searched identifier. Args: test_item (object): test instance object. item_id (number): requested test identifier. Returns: TestCase / TestSuite. test item object. """ if test_item.identifier == item_id: return test_item if test_item.IS_COMPLEX: sub_test = max([sub_test for sub_test in test_item if sub_test.identifier <= item_id], key=lambda test: test.identifier) return get_item_by_id(sub_test, item_id) def kill_process(process): """Kill a single process. Args: process (psutil.Process): process to kill. """ if not process.is_running(): return process.kill() try: process.wait(PROCESS_TERMINATION_TIMEOUT) except psutil.TimeoutExpired: core_log.warning("Process %d failed to terminate", process.pid) def kill_process_tree(process): """Kill a process and all its subprocesses. Note: Kill the process and all its sub processes recursively. If the given process is the current process - Kills the sub process before the given process. Otherwise - Kills the given process before its sub processes Args: process (psutil.Process): process to kill. """ sub_processes = process.children(recursive=True) if process.pid == os.getpid(): for sub_process in sub_processes: kill_process(sub_process) kill_process(process) else: kill_process(process) for sub_process in sub_processes: kill_process(sub_process)
def get_item_by_id(test_item, item_id): """Return the requested test item by its identifier.
random_line_split
mixin.js
this.selector = new(tree.Selector)(elements); this.arguments = args; this.index = index; }; tree.mixin.Call.prototype = { eval: function (env) { var mixins, rules = [], match = false; for (var i = 0; i < env.frames.length; i++) { if ((mixins = env.frames[i].find(this.selector)).length > 0) { for (var m = 0; m < mixins.length; m++) { if (mixins[m].match(this.arguments, env)) { try { Array.prototype.push.apply( rules, mixins[m].eval(env, this.arguments).rules); match = true; } catch (e) { throw { message: e.message, index: e.index, stack: e.stack, call: this.index }; } } } if (match) { return rules; } else { throw { message: 'No matching definition was found for `' + this.selector.toCSS().trim() + '(' + this.arguments.map(function (a) { return a.toCSS(); }).join(', ') + ")`", index: this.index }; } } } throw { message: this.selector.toCSS().trim() + " is undefined", index: this.index }; } }; tree.mixin.Definition = function (name, params, rules) { this.name = name; this.selectors = [new(tree.Selector)([new(tree.Element)(null, name)])]; this.params = params; this.arity = params.length; this.rules = rules; this._lookups = {}; this.required = params.reduce(function (count, p) { if (p.name && !p.value) { return count + 1 } else { return count } }, 0); this.parent = tree.Ruleset.prototype; this.frames = []; }; tree.mixin.Definition.prototype = { toCSS: function () { return "" }, variable: function (name) { return this.parent.variable.call(this, name) }, variables: function () { return this.parent.variables.call(this) }, find: function () { return this.parent.find.apply(this, arguments) }, rulesets: function () { return this.parent.rulesets.apply(this) }, eval: function (env, args) { var frame = new(tree.Ruleset)(null, []), context; for (var i = 0, val; i < this.params.length; i++) { if (this.params[i].name) { if (val = (args && args[i]) || this.params[i].value) { frame.rules.unshift(new(tree.Rule)(this.params[i].name, val.eval(env))); } else { throw { message: "wrong number of arguments for " + this.name + ' (' + args.length + ' for ' + this.arity + ')' }; } } } return new(tree.Ruleset)(null, this.rules.slice(0)).eval({ frames: [this, frame].concat(this.frames, env.frames) }); }, match: function (args, env) { var argsLength = (args && args.length) || 0, len; if (argsLength < this.required) { return false } len = Math.min(argsLength, this.arity); for (var i = 0; i < len; i++) { if (!this.params[i].name) { if (args[i].eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) { return false; } } } return true; } }; })(require('less/tree'));
(function (tree) { tree.mixin = {}; tree.mixin.Call = function (elements, args, index) {
random_line_split
mixin.js
(function (tree) { tree.mixin = {}; tree.mixin.Call = function (elements, args, index) { this.selector = new(tree.Selector)(elements); this.arguments = args; this.index = index; }; tree.mixin.Call.prototype = { eval: function (env) { var mixins, rules = [], match = false; for (var i = 0; i < env.frames.length; i++) { if ((mixins = env.frames[i].find(this.selector)).length > 0) { for (var m = 0; m < mixins.length; m++) { if (mixins[m].match(this.arguments, env)) { try { Array.prototype.push.apply( rules, mixins[m].eval(env, this.arguments).rules); match = true; } catch (e) { throw { message: e.message, index: e.index, stack: e.stack, call: this.index }; } } } if (match) { return rules; } else { throw { message: 'No matching definition was found for `' + this.selector.toCSS().trim() + '(' + this.arguments.map(function (a) { return a.toCSS(); }).join(', ') + ")`", index: this.index }; } } } throw { message: this.selector.toCSS().trim() + " is undefined", index: this.index }; } }; tree.mixin.Definition = function (name, params, rules) { this.name = name; this.selectors = [new(tree.Selector)([new(tree.Element)(null, name)])]; this.params = params; this.arity = params.length; this.rules = rules; this._lookups = {}; this.required = params.reduce(function (count, p) { if (p.name && !p.value) { return count + 1 } else { return count } }, 0); this.parent = tree.Ruleset.prototype; this.frames = []; }; tree.mixin.Definition.prototype = { toCSS: function () { return "" }, variable: function (name) { return this.parent.variable.call(this, name) }, variables: function () { return this.parent.variables.call(this) }, find: function () { return this.parent.find.apply(this, arguments) }, rulesets: function () { return this.parent.rulesets.apply(this) }, eval: function (env, args) { var frame = new(tree.Ruleset)(null, []), context; for (var i = 0, val; i < this.params.length; i++) { if (this.params[i].name)
} return new(tree.Ruleset)(null, this.rules.slice(0)).eval({ frames: [this, frame].concat(this.frames, env.frames) }); }, match: function (args, env) { var argsLength = (args && args.length) || 0, len; if (argsLength < this.required) { return false } len = Math.min(argsLength, this.arity); for (var i = 0; i < len; i++) { if (!this.params[i].name) { if (args[i].eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) { return false; } } } return true; } }; })(require('less/tree'));
{ if (val = (args && args[i]) || this.params[i].value) { frame.rules.unshift(new(tree.Rule)(this.params[i].name, val.eval(env))); } else { throw { message: "wrong number of arguments for " + this.name + ' (' + args.length + ' for ' + this.arity + ')' }; } }
conditional_block
skyTile.py
#!/usr/bin/python # # Fabien Chereau fchereau@eso.org # import gzip import os def writePolys(pl, f): """Write a list of polygons pl into the file f. The result is under the form [[[ra1, de1],[ra2, de2],[ra3, de3],[ra4, de4]], [[ra1, de1],[ra2, de2],[ra3, de3]]]""" f.write('[') for idx, poly in enumerate(pl): f.write('[') for iv, v in enumerate(poly): f.write('[%.8f, %.8f]' % (v[0], v[1])) if iv != len(poly) - 1: f.write(', ') f.write(']') if idx != len(pl) - 1: f.write(', ') f.write(']') class StructCredits:
class SkyImageTile: """Contains all the properties needed to describe a multiresolution image tile""" def __init__(self): self.subTiles = [] self.imageCredits = StructCredits() self.serverCredits = StructCredits() self.imageInfo = StructCredits() self.imageUrl = None self.alphaBlend = None self.maxBrightness = None return def outputJSON(self, prefix='', qCompress=False, maxLevelPerFile=10, outDir=''): """Output the tiles tree in the JSON format""" fName = outDir + prefix + "x%.2d_%.2d_%.2d.json" % (2 ** self.level, self.i, self.j) # Actually write the file with maxLevelPerFile level with open(fName, 'w') as f: self.__subOutJSON(prefix, qCompress, maxLevelPerFile, f, 0, outDir) if (qCompress): with open(fName) as ff: fout = gzip.GzipFile(fName + ".gz", 'w') fout.write(ff.read()) fout.close() os.remove(fName) def __subOutJSON(self, prefix, qCompress, maxLevelPerFile, f, curLev, outDir): """Write the tile in the file f""" levTab = "" for i in range(0, curLev): levTab += '\t' f.write(levTab + '{\n') if self.imageInfo.short != None or self.imageInfo.full != None or self.imageInfo.infoUrl != None: f.write(levTab + '\t"imageInfo": {\n') self.imageInfo.outJSON(f, levTab) f.write(levTab + '\t},\n') if self.imageCredits.short != None or self.imageCredits.full != None or self.imageCredits.infoUrl != None: f.write(levTab + '\t"imageCredits": {\n') self.imageCredits.outJSON(f, levTab) f.write(levTab + '\t},\n') if self.serverCredits.short != None or self.serverCredits.full != None or self.serverCredits.infoUrl != None: f.write(levTab + '\t"serverCredits": {\n') self.serverCredits.outJSON(f, levTab) f.write(levTab + '\t},\n') if self.imageUrl: f.write(levTab + '\t"imageUrl": "' + self.imageUrl + '",\n') f.write(levTab + '\t"worldCoords": ') writePolys(self.skyConvexPolygons, f) f.write(',\n') f.write(levTab + '\t"textureCoords": ') writePolys(self.textureCoords, f) f.write(',\n') if self.maxBrightness: f.write(levTab + '\t"maxBrightness": %f,\n' % self.maxBrightness) if self.alphaBlend: f.write(levTab + '\t"alphaBlend": true,\n') f.write(levTab + '\t"minResolution": %f' % self.minResolution) if not self.subTiles: f.write('\n' + levTab + '}') return f.write(',\n') f.write(levTab + '\t"subTiles": [\n') if curLev + 1 < maxLevelPerFile: # Write the tiles in the same file for st in self.subTiles: assert isinstance(st, SkyImageTile) st.__subOutJSON(prefix, qCompress, maxLevelPerFile, f, curLev + 1, outDir) f.write(',\n') else: # Write the tiles in a new file for st in self.subTiles: st.outputJSON(prefix, qCompress, maxLevelPerFile, outDir) f.write(levTab + '\t\t{"$ref": "' + prefix + "x%.2d_%.2d_%.2d.json" % (2 ** st.level, st.i, st.j)) if qCompress: f.write(".gz") f.write('"},\n') f.seek(-2, os.SEEK_CUR) f.write('\n' + levTab + '\t]\n') f.write(levTab + '}')
def __init__(self): self.short = None self.full = None self.infoUrl = None return def outJSON(self, f, levTab): if self.short != None: f.write(levTab + '\t\t"short": "' + self.short + '",\n') if self.full != None: f.write(levTab + '\t\t"full": "' + self.full + '",\n') if self.infoUrl != None: f.write(levTab + '\t\t"infoUrl": "' + self.infoUrl + '",\n') f.seek(-2, os.SEEK_CUR) f.write('\n')
identifier_body
skyTile.py
#!/usr/bin/python # # Fabien Chereau fchereau@eso.org # import gzip import os def writePolys(pl, f): """Write a list of polygons pl into the file f. The result is under the form [[[ra1, de1],[ra2, de2],[ra3, de3],[ra4, de4]], [[ra1, de1],[ra2, de2],[ra3, de3]]]""" f.write('[') for idx, poly in enumerate(pl): f.write('[') for iv, v in enumerate(poly): f.write('[%.8f, %.8f]' % (v[0], v[1])) if iv != len(poly) - 1: f.write(', ') f.write(']') if idx != len(pl) - 1: f.write(', ') f.write(']') class StructCredits: def __init__(self): self.short = None self.full = None self.infoUrl = None return def outJSON(self, f, levTab): if self.short != None: f.write(levTab + '\t\t"short": "' + self.short + '",\n') if self.full != None: f.write(levTab + '\t\t"full": "' + self.full + '",\n') if self.infoUrl != None: f.write(levTab + '\t\t"infoUrl": "' + self.infoUrl + '",\n') f.seek(-2, os.SEEK_CUR) f.write('\n') class SkyImageTile: """Contains all the properties needed to describe a multiresolution image tile""" def __init__(self): self.subTiles = [] self.imageCredits = StructCredits() self.serverCredits = StructCredits() self.imageInfo = StructCredits() self.imageUrl = None self.alphaBlend = None self.maxBrightness = None return def outputJSON(self, prefix='', qCompress=False, maxLevelPerFile=10, outDir=''): """Output the tiles tree in the JSON format""" fName = outDir + prefix + "x%.2d_%.2d_%.2d.json" % (2 ** self.level, self.i, self.j)
with open(fName) as ff: fout = gzip.GzipFile(fName + ".gz", 'w') fout.write(ff.read()) fout.close() os.remove(fName) def __subOutJSON(self, prefix, qCompress, maxLevelPerFile, f, curLev, outDir): """Write the tile in the file f""" levTab = "" for i in range(0, curLev): levTab += '\t' f.write(levTab + '{\n') if self.imageInfo.short != None or self.imageInfo.full != None or self.imageInfo.infoUrl != None: f.write(levTab + '\t"imageInfo": {\n') self.imageInfo.outJSON(f, levTab) f.write(levTab + '\t},\n') if self.imageCredits.short != None or self.imageCredits.full != None or self.imageCredits.infoUrl != None: f.write(levTab + '\t"imageCredits": {\n') self.imageCredits.outJSON(f, levTab) f.write(levTab + '\t},\n') if self.serverCredits.short != None or self.serverCredits.full != None or self.serverCredits.infoUrl != None: f.write(levTab + '\t"serverCredits": {\n') self.serverCredits.outJSON(f, levTab) f.write(levTab + '\t},\n') if self.imageUrl: f.write(levTab + '\t"imageUrl": "' + self.imageUrl + '",\n') f.write(levTab + '\t"worldCoords": ') writePolys(self.skyConvexPolygons, f) f.write(',\n') f.write(levTab + '\t"textureCoords": ') writePolys(self.textureCoords, f) f.write(',\n') if self.maxBrightness: f.write(levTab + '\t"maxBrightness": %f,\n' % self.maxBrightness) if self.alphaBlend: f.write(levTab + '\t"alphaBlend": true,\n') f.write(levTab + '\t"minResolution": %f' % self.minResolution) if not self.subTiles: f.write('\n' + levTab + '}') return f.write(',\n') f.write(levTab + '\t"subTiles": [\n') if curLev + 1 < maxLevelPerFile: # Write the tiles in the same file for st in self.subTiles: assert isinstance(st, SkyImageTile) st.__subOutJSON(prefix, qCompress, maxLevelPerFile, f, curLev + 1, outDir) f.write(',\n') else: # Write the tiles in a new file for st in self.subTiles: st.outputJSON(prefix, qCompress, maxLevelPerFile, outDir) f.write(levTab + '\t\t{"$ref": "' + prefix + "x%.2d_%.2d_%.2d.json" % (2 ** st.level, st.i, st.j)) if qCompress: f.write(".gz") f.write('"},\n') f.seek(-2, os.SEEK_CUR) f.write('\n' + levTab + '\t]\n') f.write(levTab + '}')
# Actually write the file with maxLevelPerFile level with open(fName, 'w') as f: self.__subOutJSON(prefix, qCompress, maxLevelPerFile, f, 0, outDir) if (qCompress):
random_line_split
skyTile.py
#!/usr/bin/python # # Fabien Chereau fchereau@eso.org # import gzip import os def writePolys(pl, f): """Write a list of polygons pl into the file f. The result is under the form [[[ra1, de1],[ra2, de2],[ra3, de3],[ra4, de4]], [[ra1, de1],[ra2, de2],[ra3, de3]]]""" f.write('[') for idx, poly in enumerate(pl): f.write('[') for iv, v in enumerate(poly): f.write('[%.8f, %.8f]' % (v[0], v[1])) if iv != len(poly) - 1: f.write(', ') f.write(']') if idx != len(pl) - 1: f.write(', ') f.write(']') class StructCredits: def __init__(self): self.short = None self.full = None self.infoUrl = None return def outJSON(self, f, levTab): if self.short != None: f.write(levTab + '\t\t"short": "' + self.short + '",\n') if self.full != None: f.write(levTab + '\t\t"full": "' + self.full + '",\n') if self.infoUrl != None: f.write(levTab + '\t\t"infoUrl": "' + self.infoUrl + '",\n') f.seek(-2, os.SEEK_CUR) f.write('\n') class SkyImageTile: """Contains all the properties needed to describe a multiresolution image tile""" def __init__(self): self.subTiles = [] self.imageCredits = StructCredits() self.serverCredits = StructCredits() self.imageInfo = StructCredits() self.imageUrl = None self.alphaBlend = None self.maxBrightness = None return def outputJSON(self, prefix='', qCompress=False, maxLevelPerFile=10, outDir=''): """Output the tiles tree in the JSON format""" fName = outDir + prefix + "x%.2d_%.2d_%.2d.json" % (2 ** self.level, self.i, self.j) # Actually write the file with maxLevelPerFile level with open(fName, 'w') as f: self.__subOutJSON(prefix, qCompress, maxLevelPerFile, f, 0, outDir) if (qCompress): with open(fName) as ff: fout = gzip.GzipFile(fName + ".gz", 'w') fout.write(ff.read()) fout.close() os.remove(fName) def __subOutJSON(self, prefix, qCompress, maxLevelPerFile, f, curLev, outDir): """Write the tile in the file f""" levTab = "" for i in range(0, curLev): levTab += '\t' f.write(levTab + '{\n') if self.imageInfo.short != None or self.imageInfo.full != None or self.imageInfo.infoUrl != None: f.write(levTab + '\t"imageInfo": {\n') self.imageInfo.outJSON(f, levTab) f.write(levTab + '\t},\n') if self.imageCredits.short != None or self.imageCredits.full != None or self.imageCredits.infoUrl != None: f.write(levTab + '\t"imageCredits": {\n') self.imageCredits.outJSON(f, levTab) f.write(levTab + '\t},\n') if self.serverCredits.short != None or self.serverCredits.full != None or self.serverCredits.infoUrl != None:
if self.imageUrl: f.write(levTab + '\t"imageUrl": "' + self.imageUrl + '",\n') f.write(levTab + '\t"worldCoords": ') writePolys(self.skyConvexPolygons, f) f.write(',\n') f.write(levTab + '\t"textureCoords": ') writePolys(self.textureCoords, f) f.write(',\n') if self.maxBrightness: f.write(levTab + '\t"maxBrightness": %f,\n' % self.maxBrightness) if self.alphaBlend: f.write(levTab + '\t"alphaBlend": true,\n') f.write(levTab + '\t"minResolution": %f' % self.minResolution) if not self.subTiles: f.write('\n' + levTab + '}') return f.write(',\n') f.write(levTab + '\t"subTiles": [\n') if curLev + 1 < maxLevelPerFile: # Write the tiles in the same file for st in self.subTiles: assert isinstance(st, SkyImageTile) st.__subOutJSON(prefix, qCompress, maxLevelPerFile, f, curLev + 1, outDir) f.write(',\n') else: # Write the tiles in a new file for st in self.subTiles: st.outputJSON(prefix, qCompress, maxLevelPerFile, outDir) f.write(levTab + '\t\t{"$ref": "' + prefix + "x%.2d_%.2d_%.2d.json" % (2 ** st.level, st.i, st.j)) if qCompress: f.write(".gz") f.write('"},\n') f.seek(-2, os.SEEK_CUR) f.write('\n' + levTab + '\t]\n') f.write(levTab + '}')
f.write(levTab + '\t"serverCredits": {\n') self.serverCredits.outJSON(f, levTab) f.write(levTab + '\t},\n')
conditional_block
skyTile.py
#!/usr/bin/python # # Fabien Chereau fchereau@eso.org # import gzip import os def writePolys(pl, f): """Write a list of polygons pl into the file f. The result is under the form [[[ra1, de1],[ra2, de2],[ra3, de3],[ra4, de4]], [[ra1, de1],[ra2, de2],[ra3, de3]]]""" f.write('[') for idx, poly in enumerate(pl): f.write('[') for iv, v in enumerate(poly): f.write('[%.8f, %.8f]' % (v[0], v[1])) if iv != len(poly) - 1: f.write(', ') f.write(']') if idx != len(pl) - 1: f.write(', ') f.write(']') class StructCredits: def __init__(self): self.short = None self.full = None self.infoUrl = None return def outJSON(self, f, levTab): if self.short != None: f.write(levTab + '\t\t"short": "' + self.short + '",\n') if self.full != None: f.write(levTab + '\t\t"full": "' + self.full + '",\n') if self.infoUrl != None: f.write(levTab + '\t\t"infoUrl": "' + self.infoUrl + '",\n') f.seek(-2, os.SEEK_CUR) f.write('\n') class SkyImageTile: """Contains all the properties needed to describe a multiresolution image tile""" def
(self): self.subTiles = [] self.imageCredits = StructCredits() self.serverCredits = StructCredits() self.imageInfo = StructCredits() self.imageUrl = None self.alphaBlend = None self.maxBrightness = None return def outputJSON(self, prefix='', qCompress=False, maxLevelPerFile=10, outDir=''): """Output the tiles tree in the JSON format""" fName = outDir + prefix + "x%.2d_%.2d_%.2d.json" % (2 ** self.level, self.i, self.j) # Actually write the file with maxLevelPerFile level with open(fName, 'w') as f: self.__subOutJSON(prefix, qCompress, maxLevelPerFile, f, 0, outDir) if (qCompress): with open(fName) as ff: fout = gzip.GzipFile(fName + ".gz", 'w') fout.write(ff.read()) fout.close() os.remove(fName) def __subOutJSON(self, prefix, qCompress, maxLevelPerFile, f, curLev, outDir): """Write the tile in the file f""" levTab = "" for i in range(0, curLev): levTab += '\t' f.write(levTab + '{\n') if self.imageInfo.short != None or self.imageInfo.full != None or self.imageInfo.infoUrl != None: f.write(levTab + '\t"imageInfo": {\n') self.imageInfo.outJSON(f, levTab) f.write(levTab + '\t},\n') if self.imageCredits.short != None or self.imageCredits.full != None or self.imageCredits.infoUrl != None: f.write(levTab + '\t"imageCredits": {\n') self.imageCredits.outJSON(f, levTab) f.write(levTab + '\t},\n') if self.serverCredits.short != None or self.serverCredits.full != None or self.serverCredits.infoUrl != None: f.write(levTab + '\t"serverCredits": {\n') self.serverCredits.outJSON(f, levTab) f.write(levTab + '\t},\n') if self.imageUrl: f.write(levTab + '\t"imageUrl": "' + self.imageUrl + '",\n') f.write(levTab + '\t"worldCoords": ') writePolys(self.skyConvexPolygons, f) f.write(',\n') f.write(levTab + '\t"textureCoords": ') writePolys(self.textureCoords, f) f.write(',\n') if self.maxBrightness: f.write(levTab + '\t"maxBrightness": %f,\n' % self.maxBrightness) if self.alphaBlend: f.write(levTab + '\t"alphaBlend": true,\n') f.write(levTab + '\t"minResolution": %f' % self.minResolution) if not self.subTiles: f.write('\n' + levTab + '}') return f.write(',\n') f.write(levTab + '\t"subTiles": [\n') if curLev + 1 < maxLevelPerFile: # Write the tiles in the same file for st in self.subTiles: assert isinstance(st, SkyImageTile) st.__subOutJSON(prefix, qCompress, maxLevelPerFile, f, curLev + 1, outDir) f.write(',\n') else: # Write the tiles in a new file for st in self.subTiles: st.outputJSON(prefix, qCompress, maxLevelPerFile, outDir) f.write(levTab + '\t\t{"$ref": "' + prefix + "x%.2d_%.2d_%.2d.json" % (2 ** st.level, st.i, st.j)) if qCompress: f.write(".gz") f.write('"},\n') f.seek(-2, os.SEEK_CUR) f.write('\n' + levTab + '\t]\n') f.write(levTab + '}')
__init__
identifier_name
click_report.test.js
import * as chai from 'chai'; const expect = chai.expect; const chaiAsPromised = require('chai-as-promised'); import * as sinon from 'sinon'; import * as sinonAsPromised from 'sinon-as-promised'; import { ClickReport } from '../src/models/click_report'; chai.use(chaiAsPromised); describe('ClickReport', () => { const tableName = 'ClickReports-table'; const campaignId = 'thatCampaignId'; let tNameStub; const clickReportHashKey = 'campaignId';
}); describe('#get', () => { it('calls the DynamoDB get method with correct params', (done) => { ClickReport.get(campaignId, clickReportRangeKey).then(() => { const args = ClickReport._client.lastCall.args; expect(args[0]).to.equal('get'); expect(args[1]).to.have.deep.property(`Key.${clickReportHashKey}`, campaignId); expect(args[1]).to.have.deep.property(`Key.${clickReportRangeKey}`, clickReportRangeKey); expect(args[1]).to.have.property('TableName', tableName); done(); }); }); }); describe('#hashKey', () => { it('returns the hash key name', () => { expect(ClickReport.hashKey).to.equal(clickReportHashKey); }); }); describe('#rangeKey', () => { it('returns the range key name', () => { expect(ClickReport.rangeKey).to.equal(clickReportRangeKey); }); }); after(() => { ClickReport._client.restore(); tNameStub.restore(); }); });
const clickReportRangeKey = 'timestamp'; before(() => { sinon.stub(ClickReport, '_client').resolves(true); tNameStub = sinon.stub(ClickReport, 'tableName', { get: () => tableName});
random_line_split
server.js
/** * Module dependencies */ var Server = require('annex-ws-node').Server; var http = require('http'); var stack = require('connect-stack'); var pns = require('pack-n-stack'); module.exports = function createServer(opts) { var server = http.createServer(); server.stack = []; server.handle = stack(server.stack); server.use = function(fn) {
server.stack.push(fn); return server; }; var routes = server.routes = {}; var hasPushedRouter = false; server.register = server.fn = function(modName, fnName, cb) { var mod = routes[modName] = routes[modName] || {}; var fn = mod[fnName] = mod[fnName] || []; fn.push(cb); server.emit('register:call', modName, fnName); if (hasPushedRouter) return server; server.use(router); hasPushedRouter = true; return server; }; function router(req, res, next) { var mod = routes[req.module]; if (!mod) return next(); var fn = mod[req.method]; if (!fn) return next(); // TODO support next('route') fn[0](req, res, next); } var wss = new Server({server: server, marshal: opts.marshal}); wss.listen(function(req, res) { // TODO do a domain here server.handle(req, res, function(err) { if (!res._sent) { err ? res.error(err.message) : res.error(req.module + ':' + req.method + ' not implemented'); if (err) console.error(err.stack || err.message); } }); }); return server; }
fn.handle = fn;
random_line_split
server.js
/** * Module dependencies */ var Server = require('annex-ws-node').Server; var http = require('http'); var stack = require('connect-stack'); var pns = require('pack-n-stack'); module.exports = function createServer(opts) { var server = http.createServer(); server.stack = []; server.handle = stack(server.stack); server.use = function(fn) { fn.handle = fn; server.stack.push(fn); return server; }; var routes = server.routes = {}; var hasPushedRouter = false; server.register = server.fn = function(modName, fnName, cb) { var mod = routes[modName] = routes[modName] || {}; var fn = mod[fnName] = mod[fnName] || []; fn.push(cb); server.emit('register:call', modName, fnName); if (hasPushedRouter) return server; server.use(router); hasPushedRouter = true; return server; }; function router(req, res, next)
var wss = new Server({server: server, marshal: opts.marshal}); wss.listen(function(req, res) { // TODO do a domain here server.handle(req, res, function(err) { if (!res._sent) { err ? res.error(err.message) : res.error(req.module + ':' + req.method + ' not implemented'); if (err) console.error(err.stack || err.message); } }); }); return server; }
{ var mod = routes[req.module]; if (!mod) return next(); var fn = mod[req.method]; if (!fn) return next(); // TODO support next('route') fn[0](req, res, next); }
identifier_body
server.js
/** * Module dependencies */ var Server = require('annex-ws-node').Server; var http = require('http'); var stack = require('connect-stack'); var pns = require('pack-n-stack'); module.exports = function createServer(opts) { var server = http.createServer(); server.stack = []; server.handle = stack(server.stack); server.use = function(fn) { fn.handle = fn; server.stack.push(fn); return server; }; var routes = server.routes = {}; var hasPushedRouter = false; server.register = server.fn = function(modName, fnName, cb) { var mod = routes[modName] = routes[modName] || {}; var fn = mod[fnName] = mod[fnName] || []; fn.push(cb); server.emit('register:call', modName, fnName); if (hasPushedRouter) return server; server.use(router); hasPushedRouter = true; return server; }; function
(req, res, next) { var mod = routes[req.module]; if (!mod) return next(); var fn = mod[req.method]; if (!fn) return next(); // TODO support next('route') fn[0](req, res, next); } var wss = new Server({server: server, marshal: opts.marshal}); wss.listen(function(req, res) { // TODO do a domain here server.handle(req, res, function(err) { if (!res._sent) { err ? res.error(err.message) : res.error(req.module + ':' + req.method + ' not implemented'); if (err) console.error(err.stack || err.message); } }); }); return server; }
router
identifier_name
index.js
var engine = require('../'); var express = require('express'); var path = require('path'); var app = express(); app.engine('dot', engine.__express); app.set('views', path.join(__dirname, './views')); app.set('view engine', 'dot'); app.get('/', function(req, res) { res.render('index', { fromServer: 'Hello from server', }); }); app.get('/layout', function(req, res) { res.render('layout/index'); }); app.get('/cascade', function(req, res) { res.render('cascade/me'); }); app.get('/partial', function(req, res) { res.render('partial/index'); }); app.get('/helper', function(req, res) { // helper as a property engine.helper.myHelperProperty = 'Hello from server property helper';
res.render('helper/index', { fromServer: 'Hello from server', }); }); var server = app.listen(2015, function() { console.log('Run the example at http://locahost:%d', server.address().port); });
// helper as a method engine.helper.myHelperMethod = function(param) { return 'Hello from server method helper (parameter: ' + param + ', server model: ' + this.model.fromServer + ')'; }
random_line_split
user.service.ts
import { Injectable, Inject } from '@angular/core'; import { User } from './user.model'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { IdType } from '../shared/shared-types'; import { BACKEND_SERVICE } from '../core/core.module'; import { BackendService } from '../core/backend.service'; @Injectable({ providedIn: 'root' }) export class UserService { constructor(@Inject(BACKEND_SERVICE) private backend: BackendService) { }
return this.backend.findAll(User); } findById(id: IdType): Observable<User | undefined> { return this.backend.findById(User, id); } findByEmail(email: string): Observable<User | undefined> { return this.backend.findAll(User).pipe( map( users => users.find(user => user.email === email) ) ); } create(entity: User): Observable<User | undefined> { return this.backend.add(User, entity); } update(entity: User): Observable<User | undefined> { return this.backend.update(User, entity); } delete(id: IdType): Observable<User | undefined> { return this.backend.delete(User, id); } }
findAll(): Observable<User[]> {
random_line_split
user.service.ts
import { Injectable, Inject } from '@angular/core'; import { User } from './user.model'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { IdType } from '../shared/shared-types'; import { BACKEND_SERVICE } from '../core/core.module'; import { BackendService } from '../core/backend.service'; @Injectable({ providedIn: 'root' }) export class UserService {
(@Inject(BACKEND_SERVICE) private backend: BackendService) { } findAll(): Observable<User[]> { return this.backend.findAll(User); } findById(id: IdType): Observable<User | undefined> { return this.backend.findById(User, id); } findByEmail(email: string): Observable<User | undefined> { return this.backend.findAll(User).pipe( map( users => users.find(user => user.email === email) ) ); } create(entity: User): Observable<User | undefined> { return this.backend.add(User, entity); } update(entity: User): Observable<User | undefined> { return this.backend.update(User, entity); } delete(id: IdType): Observable<User | undefined> { return this.backend.delete(User, id); } }
constructor
identifier_name
user.service.ts
import { Injectable, Inject } from '@angular/core'; import { User } from './user.model'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { IdType } from '../shared/shared-types'; import { BACKEND_SERVICE } from '../core/core.module'; import { BackendService } from '../core/backend.service'; @Injectable({ providedIn: 'root' }) export class UserService { constructor(@Inject(BACKEND_SERVICE) private backend: BackendService) { } findAll(): Observable<User[]> { return this.backend.findAll(User); } findById(id: IdType): Observable<User | undefined>
findByEmail(email: string): Observable<User | undefined> { return this.backend.findAll(User).pipe( map( users => users.find(user => user.email === email) ) ); } create(entity: User): Observable<User | undefined> { return this.backend.add(User, entity); } update(entity: User): Observable<User | undefined> { return this.backend.update(User, entity); } delete(id: IdType): Observable<User | undefined> { return this.backend.delete(User, id); } }
{ return this.backend.findById(User, id); }
identifier_body
regions-steal-closure.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(box_syntax)] #![feature(unboxed_closures)] struct closure_box<'a> { cl: Box<FnMut() + 'a>, }
fn main() { let cl_box = { let mut i = 3i; box_it(box || i += 1) //~ ERROR cannot infer }; cl_box.cl.call_mut(()); }
fn box_it<'r>(x: Box<FnMut() + 'r>) -> closure_box<'r> { closure_box {cl: x} }
random_line_split
regions-steal-closure.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(box_syntax)] #![feature(unboxed_closures)] struct
<'a> { cl: Box<FnMut() + 'a>, } fn box_it<'r>(x: Box<FnMut() + 'r>) -> closure_box<'r> { closure_box {cl: x} } fn main() { let cl_box = { let mut i = 3i; box_it(box || i += 1) //~ ERROR cannot infer }; cl_box.cl.call_mut(()); }
closure_box
identifier_name
regions-steal-closure.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(box_syntax)] #![feature(unboxed_closures)] struct closure_box<'a> { cl: Box<FnMut() + 'a>, } fn box_it<'r>(x: Box<FnMut() + 'r>) -> closure_box<'r> { closure_box {cl: x} } fn main()
{ let cl_box = { let mut i = 3i; box_it(box || i += 1) //~ ERROR cannot infer }; cl_box.cl.call_mut(()); }
identifier_body
options.rs
// The MIT License (MIT) // Copyright (c) 2015 Y. T. Chung <zonyitoo@gmail.com> // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //! Coroutine options use std::rt; use std::default::Default; /// Coroutine options pub struct Options { pub stack_size: usize, pub name: Option<String>, } impl Options { pub fn
() -> Options { Options { stack_size: rt::min_stack(), name: None, } } pub fn stack_size(mut self, size: usize) -> Options { self.stack_size = size; self } pub fn name(mut self, name: Option<String>) -> Options { self.name = name; self } } impl Default for Options { fn default() -> Options { Options::new() } }
new
identifier_name
options.rs
// The MIT License (MIT) // Copyright (c) 2015 Y. T. Chung <zonyitoo@gmail.com> // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //! Coroutine options use std::rt; use std::default::Default;
pub name: Option<String>, } impl Options { pub fn new() -> Options { Options { stack_size: rt::min_stack(), name: None, } } pub fn stack_size(mut self, size: usize) -> Options { self.stack_size = size; self } pub fn name(mut self, name: Option<String>) -> Options { self.name = name; self } } impl Default for Options { fn default() -> Options { Options::new() } }
/// Coroutine options pub struct Options { pub stack_size: usize,
random_line_split
test_utf8.py
import unittest from pystan import stanc, StanModel from pystan._compat import PY2 class
(unittest.TestCase): desired = sorted({"status", "model_cppname", "cppcode", "model_name", "model_code", "include_paths"}) def test_utf8(self): model_code = 'parameters {real y;} model {y ~ normal(0,1);}' result = stanc(model_code=model_code) self.assertEqual(sorted(result.keys()), self.desired) self.assertTrue(result['cppcode'].startswith("// Code generated by Stan ")) self.assertEqual(result['status'], 0) def test_utf8_linecomment(self): model_code = u'parameters {real y;\n //äöéü\n} model {y ~ normal(0,1);}' result = stanc(model_code=model_code) self.assertEqual(sorted(result.keys()), self.desired) self.assertTrue(result['cppcode'].startswith("// Code generated by Stan ")) self.assertEqual(result['status'], 0) def test_utf8_multilinecomment(self): model_code = u'parameters {real y;\n /*äöéü\näöéü*/\n} model {y ~ normal(0,1);}' result = stanc(model_code=model_code) self.assertEqual(sorted(result.keys()), self.desired) self.assertTrue(result['cppcode'].startswith("// Code generated by Stan ")) self.assertEqual(result['status'], 0) def test_utf8_inprogramcode(self): model_code = u'parameters {real ö;\n} model {ö ~ normal(0,1);}' assertRaisesRegex = self.assertRaisesRegexp if PY2 else self.assertRaisesRegex with assertRaisesRegex(ValueError, 'Failed to parse Stan model .*'): stanc(model_code=model_code)
TestUTF8
identifier_name
test_utf8.py
import unittest
class TestUTF8(unittest.TestCase): desired = sorted({"status", "model_cppname", "cppcode", "model_name", "model_code", "include_paths"}) def test_utf8(self): model_code = 'parameters {real y;} model {y ~ normal(0,1);}' result = stanc(model_code=model_code) self.assertEqual(sorted(result.keys()), self.desired) self.assertTrue(result['cppcode'].startswith("// Code generated by Stan ")) self.assertEqual(result['status'], 0) def test_utf8_linecomment(self): model_code = u'parameters {real y;\n //äöéü\n} model {y ~ normal(0,1);}' result = stanc(model_code=model_code) self.assertEqual(sorted(result.keys()), self.desired) self.assertTrue(result['cppcode'].startswith("// Code generated by Stan ")) self.assertEqual(result['status'], 0) def test_utf8_multilinecomment(self): model_code = u'parameters {real y;\n /*äöéü\näöéü*/\n} model {y ~ normal(0,1);}' result = stanc(model_code=model_code) self.assertEqual(sorted(result.keys()), self.desired) self.assertTrue(result['cppcode'].startswith("// Code generated by Stan ")) self.assertEqual(result['status'], 0) def test_utf8_inprogramcode(self): model_code = u'parameters {real ö;\n} model {ö ~ normal(0,1);}' assertRaisesRegex = self.assertRaisesRegexp if PY2 else self.assertRaisesRegex with assertRaisesRegex(ValueError, 'Failed to parse Stan model .*'): stanc(model_code=model_code)
from pystan import stanc, StanModel from pystan._compat import PY2
random_line_split
test_utf8.py
import unittest from pystan import stanc, StanModel from pystan._compat import PY2 class TestUTF8(unittest.TestCase): desired = sorted({"status", "model_cppname", "cppcode", "model_name", "model_code", "include_paths"}) def test_utf8(self): model_code = 'parameters {real y;} model {y ~ normal(0,1);}' result = stanc(model_code=model_code) self.assertEqual(sorted(result.keys()), self.desired) self.assertTrue(result['cppcode'].startswith("// Code generated by Stan ")) self.assertEqual(result['status'], 0) def test_utf8_linecomment(self): model_code = u'parameters {real y;\n //äöéü\n} model {y ~ normal(0,1);}' result = stanc(model_code=model_code) self.assertEqual(sorted(result.keys()), self.desired) self.assertTrue(result['cppcode'].startswith("// Code generated by Stan ")) self.assertEqual(result['status'], 0) def test_utf8_multilinecomment(self): mode
st_utf8_inprogramcode(self): model_code = u'parameters {real ö;\n} model {ö ~ normal(0,1);}' assertRaisesRegex = self.assertRaisesRegexp if PY2 else self.assertRaisesRegex with assertRaisesRegex(ValueError, 'Failed to parse Stan model .*'): stanc(model_code=model_code)
l_code = u'parameters {real y;\n /*äöéü\näöéü*/\n} model {y ~ normal(0,1);}' result = stanc(model_code=model_code) self.assertEqual(sorted(result.keys()), self.desired) self.assertTrue(result['cppcode'].startswith("// Code generated by Stan ")) self.assertEqual(result['status'], 0) def te
identifier_body
setup.py
#!/usr/bin/python3 #from __future__ import print_function from setuptools import setup, Extension import sys import os import psutil # monkey-patch for parallel compilation def parallelCCompile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None): # those lines are copied from distutils.ccompiler.CCompiler directly macros, objects, extra_postargs, pp_opts, build = self._setup_compile(output_dir, macros, include_dirs, sources, depends, extra_postargs) cc_args = self._get_cc_args(pp_opts, debug, extra_preargs) # parallel code N = psutil.cpu_count(logical=False) # number of parallel compilations import multiprocessing.pool def _single_compile(obj): try: src, ext = build[obj] except KeyError: return self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) # convert to list, imap is evaluated on-demand list(multiprocessing.pool.ThreadPool(N).imap(_single_compile,objects)) return objects #import distutils.ccompiler #distutils.ccompiler.CCompiler.compile=parallelCCompile ''' Note: to build Boost.Python on Windows with mingw bjam target-os=windows/python=3.4 toolset=gcc variant=debug,release link=static,shared threading=multi runtime-link=shared cxxflags="-include cmath " also insert this on top of boost/python.hpp : #include <cmath> //fix cmath:1096:11: error: '::hypot' has not been declared ''' def
(): platform = sys.platform extensionsList = [] sources = ['src/Genome.cpp', 'src/Innovation.cpp', 'src/NeuralNetwork.cpp', 'src/Parameters.cpp', 'src/PhenotypeBehavior.cpp', 'src/Population.cpp', 'src/Random.cpp', 'src/Species.cpp', 'src/Substrate.cpp', 'src/Utils.cpp'] extra = ['-march=native', '-mtune=native', '-g', ] if platform == 'darwin': extra += ['-stdlib=libc++', '-std=c++11',] else: extra += ['-std=gnu++11'] is_windows = 'win' in platform and platform != 'darwin' if is_windows: extra.append('/EHsc') else: extra.append('-w') prefix = os.getenv('PREFIX') if prefix and len(prefix) > 0: extra += ["-I{}/include".format(prefix)] build_sys = os.getenv('MN_BUILD') if build_sys is None: if os.path.exists('_MultiNEAT.cpp'): sources.insert(0, '_MultiNEAT.cpp') extra.append('-O3') extensionsList.extend([Extension('MultiNEAT._MultiNEAT', sources, extra_compile_args=extra)], ) else: print('Source file is missing and MN_BUILD environment variable is not set.\n' 'Specify either \'cython\' or \'boost\'. Example to build in Linux with Cython:\n' '\t$ export MN_BUILD=cython') exit(1) elif build_sys == 'cython': from Cython.Build import cythonize sources.insert(0, '_MultiNEAT.pyx') extra.append('-O3') extensionsList.extend(cythonize([Extension('MultiNEAT._MultiNEAT', sources, extra_compile_args=extra)], )) elif build_sys == 'boost': is_python_2 = sys.version_info[0] < 3 sources.insert(0, 'src/PythonBindings.cpp') if is_windows: if is_python_2: raise RuntimeError("Python prior to version 3 is not supported on Windows due to limits of VC++ compiler version") libs = ['boost_system', 'boost_serialization'] if is_python_2: libs += ['boost_python', "boost_numpy"] else: # with boost 1.67 you need boost_python3x and boost_numpy3x where x is python version 3.x libs += ['boost_python36', "boost_numpy36"] # in Ubuntu 14 there is only 'boost_python-py34' # for Windows with mingw # libraries= ['libboost_python-mgw48-mt-1_58', # 'libboost_serialization-mgw48-mt-1_58'], # include_dirs = ['C:/MinGW/include', 'C:/Users/Peter/Desktop/boost_1_58_0'], # library_dirs = ['C:/MinGW/lib', 'C:/Users/Peter/Desktop/boost_1_58_0/stage/lib'], extra.extend(['-DUSE_BOOST_PYTHON', '-DUSE_BOOST_RANDOM', #'-O0', #'-DVDEBUG', ]) exx = Extension('MultiNEAT._MultiNEAT', sources, libraries=libs, extra_compile_args=extra) print(dir(exx)) print(exx) print(exx.extra_compile_args) extensionsList.append(exx) else: raise AttributeError('Unknown tool: {}'.format(build_sys)) return extensionsList setup(name='multineat', version='0.5', # Update version in conda/meta.yaml as well packages=['MultiNEAT'], ext_modules=getExtensions())
getExtensions
identifier_name
setup.py
#!/usr/bin/python3 #from __future__ import print_function from setuptools import setup, Extension import sys import os import psutil # monkey-patch for parallel compilation def parallelCCompile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None): # those lines are copied from distutils.ccompiler.CCompiler directly macros, objects, extra_postargs, pp_opts, build = self._setup_compile(output_dir, macros, include_dirs, sources, depends, extra_postargs) cc_args = self._get_cc_args(pp_opts, debug, extra_preargs) # parallel code N = psutil.cpu_count(logical=False) # number of parallel compilations import multiprocessing.pool def _single_compile(obj): try: src, ext = build[obj] except KeyError: return self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) # convert to list, imap is evaluated on-demand list(multiprocessing.pool.ThreadPool(N).imap(_single_compile,objects)) return objects #import distutils.ccompiler #distutils.ccompiler.CCompiler.compile=parallelCCompile ''' Note: to build Boost.Python on Windows with mingw bjam target-os=windows/python=3.4 toolset=gcc variant=debug,release link=static,shared threading=multi runtime-link=shared cxxflags="-include cmath " also insert this on top of boost/python.hpp : #include <cmath> //fix cmath:1096:11: error: '::hypot' has not been declared ''' def getExtensions(): platform = sys.platform extensionsList = [] sources = ['src/Genome.cpp', 'src/Innovation.cpp', 'src/NeuralNetwork.cpp', 'src/Parameters.cpp', 'src/PhenotypeBehavior.cpp', 'src/Population.cpp', 'src/Random.cpp', 'src/Species.cpp', 'src/Substrate.cpp', 'src/Utils.cpp'] extra = ['-march=native', '-mtune=native', '-g', ]
if platform == 'darwin': extra += ['-stdlib=libc++', '-std=c++11',] else: extra += ['-std=gnu++11'] is_windows = 'win' in platform and platform != 'darwin' if is_windows: extra.append('/EHsc') else: extra.append('-w') prefix = os.getenv('PREFIX') if prefix and len(prefix) > 0: extra += ["-I{}/include".format(prefix)] build_sys = os.getenv('MN_BUILD') if build_sys is None: if os.path.exists('_MultiNEAT.cpp'): sources.insert(0, '_MultiNEAT.cpp') extra.append('-O3') extensionsList.extend([Extension('MultiNEAT._MultiNEAT', sources, extra_compile_args=extra)], ) else: print('Source file is missing and MN_BUILD environment variable is not set.\n' 'Specify either \'cython\' or \'boost\'. Example to build in Linux with Cython:\n' '\t$ export MN_BUILD=cython') exit(1) elif build_sys == 'cython': from Cython.Build import cythonize sources.insert(0, '_MultiNEAT.pyx') extra.append('-O3') extensionsList.extend(cythonize([Extension('MultiNEAT._MultiNEAT', sources, extra_compile_args=extra)], )) elif build_sys == 'boost': is_python_2 = sys.version_info[0] < 3 sources.insert(0, 'src/PythonBindings.cpp') if is_windows: if is_python_2: raise RuntimeError("Python prior to version 3 is not supported on Windows due to limits of VC++ compiler version") libs = ['boost_system', 'boost_serialization'] if is_python_2: libs += ['boost_python', "boost_numpy"] else: # with boost 1.67 you need boost_python3x and boost_numpy3x where x is python version 3.x libs += ['boost_python36', "boost_numpy36"] # in Ubuntu 14 there is only 'boost_python-py34' # for Windows with mingw # libraries= ['libboost_python-mgw48-mt-1_58', # 'libboost_serialization-mgw48-mt-1_58'], # include_dirs = ['C:/MinGW/include', 'C:/Users/Peter/Desktop/boost_1_58_0'], # library_dirs = ['C:/MinGW/lib', 'C:/Users/Peter/Desktop/boost_1_58_0/stage/lib'], extra.extend(['-DUSE_BOOST_PYTHON', '-DUSE_BOOST_RANDOM', #'-O0', #'-DVDEBUG', ]) exx = Extension('MultiNEAT._MultiNEAT', sources, libraries=libs, extra_compile_args=extra) print(dir(exx)) print(exx) print(exx.extra_compile_args) extensionsList.append(exx) else: raise AttributeError('Unknown tool: {}'.format(build_sys)) return extensionsList setup(name='multineat', version='0.5', # Update version in conda/meta.yaml as well packages=['MultiNEAT'], ext_modules=getExtensions())
random_line_split
setup.py
#!/usr/bin/python3 #from __future__ import print_function from setuptools import setup, Extension import sys import os import psutil # monkey-patch for parallel compilation def parallelCCompile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None): # those lines are copied from distutils.ccompiler.CCompiler directly macros, objects, extra_postargs, pp_opts, build = self._setup_compile(output_dir, macros, include_dirs, sources, depends, extra_postargs) cc_args = self._get_cc_args(pp_opts, debug, extra_preargs) # parallel code N = psutil.cpu_count(logical=False) # number of parallel compilations import multiprocessing.pool def _single_compile(obj): try: src, ext = build[obj] except KeyError: return self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) # convert to list, imap is evaluated on-demand list(multiprocessing.pool.ThreadPool(N).imap(_single_compile,objects)) return objects #import distutils.ccompiler #distutils.ccompiler.CCompiler.compile=parallelCCompile ''' Note: to build Boost.Python on Windows with mingw bjam target-os=windows/python=3.4 toolset=gcc variant=debug,release link=static,shared threading=multi runtime-link=shared cxxflags="-include cmath " also insert this on top of boost/python.hpp : #include <cmath> //fix cmath:1096:11: error: '::hypot' has not been declared ''' def getExtensions(): platform = sys.platform extensionsList = [] sources = ['src/Genome.cpp', 'src/Innovation.cpp', 'src/NeuralNetwork.cpp', 'src/Parameters.cpp', 'src/PhenotypeBehavior.cpp', 'src/Population.cpp', 'src/Random.cpp', 'src/Species.cpp', 'src/Substrate.cpp', 'src/Utils.cpp'] extra = ['-march=native', '-mtune=native', '-g', ] if platform == 'darwin': extra += ['-stdlib=libc++', '-std=c++11',] else: extra += ['-std=gnu++11'] is_windows = 'win' in platform and platform != 'darwin' if is_windows: extra.append('/EHsc') else: extra.append('-w') prefix = os.getenv('PREFIX') if prefix and len(prefix) > 0: extra += ["-I{}/include".format(prefix)] build_sys = os.getenv('MN_BUILD') if build_sys is None: if os.path.exists('_MultiNEAT.cpp'): sources.insert(0, '_MultiNEAT.cpp') extra.append('-O3') extensionsList.extend([Extension('MultiNEAT._MultiNEAT', sources, extra_compile_args=extra)], ) else: print('Source file is missing and MN_BUILD environment variable is not set.\n' 'Specify either \'cython\' or \'boost\'. Example to build in Linux with Cython:\n' '\t$ export MN_BUILD=cython') exit(1) elif build_sys == 'cython':
elif build_sys == 'boost': is_python_2 = sys.version_info[0] < 3 sources.insert(0, 'src/PythonBindings.cpp') if is_windows: if is_python_2: raise RuntimeError("Python prior to version 3 is not supported on Windows due to limits of VC++ compiler version") libs = ['boost_system', 'boost_serialization'] if is_python_2: libs += ['boost_python', "boost_numpy"] else: # with boost 1.67 you need boost_python3x and boost_numpy3x where x is python version 3.x libs += ['boost_python36', "boost_numpy36"] # in Ubuntu 14 there is only 'boost_python-py34' # for Windows with mingw # libraries= ['libboost_python-mgw48-mt-1_58', # 'libboost_serialization-mgw48-mt-1_58'], # include_dirs = ['C:/MinGW/include', 'C:/Users/Peter/Desktop/boost_1_58_0'], # library_dirs = ['C:/MinGW/lib', 'C:/Users/Peter/Desktop/boost_1_58_0/stage/lib'], extra.extend(['-DUSE_BOOST_PYTHON', '-DUSE_BOOST_RANDOM', #'-O0', #'-DVDEBUG', ]) exx = Extension('MultiNEAT._MultiNEAT', sources, libraries=libs, extra_compile_args=extra) print(dir(exx)) print(exx) print(exx.extra_compile_args) extensionsList.append(exx) else: raise AttributeError('Unknown tool: {}'.format(build_sys)) return extensionsList setup(name='multineat', version='0.5', # Update version in conda/meta.yaml as well packages=['MultiNEAT'], ext_modules=getExtensions())
from Cython.Build import cythonize sources.insert(0, '_MultiNEAT.pyx') extra.append('-O3') extensionsList.extend(cythonize([Extension('MultiNEAT._MultiNEAT', sources, extra_compile_args=extra)], ))
conditional_block
setup.py
#!/usr/bin/python3 #from __future__ import print_function from setuptools import setup, Extension import sys import os import psutil # monkey-patch for parallel compilation def parallelCCompile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None): # those lines are copied from distutils.ccompiler.CCompiler directly macros, objects, extra_postargs, pp_opts, build = self._setup_compile(output_dir, macros, include_dirs, sources, depends, extra_postargs) cc_args = self._get_cc_args(pp_opts, debug, extra_preargs) # parallel code N = psutil.cpu_count(logical=False) # number of parallel compilations import multiprocessing.pool def _single_compile(obj): try: src, ext = build[obj] except KeyError: return self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) # convert to list, imap is evaluated on-demand list(multiprocessing.pool.ThreadPool(N).imap(_single_compile,objects)) return objects #import distutils.ccompiler #distutils.ccompiler.CCompiler.compile=parallelCCompile ''' Note: to build Boost.Python on Windows with mingw bjam target-os=windows/python=3.4 toolset=gcc variant=debug,release link=static,shared threading=multi runtime-link=shared cxxflags="-include cmath " also insert this on top of boost/python.hpp : #include <cmath> //fix cmath:1096:11: error: '::hypot' has not been declared ''' def getExtensions():
setup(name='multineat', version='0.5', # Update version in conda/meta.yaml as well packages=['MultiNEAT'], ext_modules=getExtensions())
platform = sys.platform extensionsList = [] sources = ['src/Genome.cpp', 'src/Innovation.cpp', 'src/NeuralNetwork.cpp', 'src/Parameters.cpp', 'src/PhenotypeBehavior.cpp', 'src/Population.cpp', 'src/Random.cpp', 'src/Species.cpp', 'src/Substrate.cpp', 'src/Utils.cpp'] extra = ['-march=native', '-mtune=native', '-g', ] if platform == 'darwin': extra += ['-stdlib=libc++', '-std=c++11',] else: extra += ['-std=gnu++11'] is_windows = 'win' in platform and platform != 'darwin' if is_windows: extra.append('/EHsc') else: extra.append('-w') prefix = os.getenv('PREFIX') if prefix and len(prefix) > 0: extra += ["-I{}/include".format(prefix)] build_sys = os.getenv('MN_BUILD') if build_sys is None: if os.path.exists('_MultiNEAT.cpp'): sources.insert(0, '_MultiNEAT.cpp') extra.append('-O3') extensionsList.extend([Extension('MultiNEAT._MultiNEAT', sources, extra_compile_args=extra)], ) else: print('Source file is missing and MN_BUILD environment variable is not set.\n' 'Specify either \'cython\' or \'boost\'. Example to build in Linux with Cython:\n' '\t$ export MN_BUILD=cython') exit(1) elif build_sys == 'cython': from Cython.Build import cythonize sources.insert(0, '_MultiNEAT.pyx') extra.append('-O3') extensionsList.extend(cythonize([Extension('MultiNEAT._MultiNEAT', sources, extra_compile_args=extra)], )) elif build_sys == 'boost': is_python_2 = sys.version_info[0] < 3 sources.insert(0, 'src/PythonBindings.cpp') if is_windows: if is_python_2: raise RuntimeError("Python prior to version 3 is not supported on Windows due to limits of VC++ compiler version") libs = ['boost_system', 'boost_serialization'] if is_python_2: libs += ['boost_python', "boost_numpy"] else: # with boost 1.67 you need boost_python3x and boost_numpy3x where x is python version 3.x libs += ['boost_python36', "boost_numpy36"] # in Ubuntu 14 there is only 'boost_python-py34' # for Windows with mingw # libraries= ['libboost_python-mgw48-mt-1_58', # 'libboost_serialization-mgw48-mt-1_58'], # include_dirs = ['C:/MinGW/include', 'C:/Users/Peter/Desktop/boost_1_58_0'], # library_dirs = ['C:/MinGW/lib', 'C:/Users/Peter/Desktop/boost_1_58_0/stage/lib'], extra.extend(['-DUSE_BOOST_PYTHON', '-DUSE_BOOST_RANDOM', #'-O0', #'-DVDEBUG', ]) exx = Extension('MultiNEAT._MultiNEAT', sources, libraries=libs, extra_compile_args=extra) print(dir(exx)) print(exx) print(exx.extra_compile_args) extensionsList.append(exx) else: raise AttributeError('Unknown tool: {}'.format(build_sys)) return extensionsList
identifier_body
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { MapComponent } from './map/map.component'; import { Ng2MapModule} from 'ng2-map'; import {SearchComponent} from './search/search.component'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {SearchAPIService} from './search/search.api.service'; import {HttpModule, JsonpModule} from '@angular/http'; import {CommonModule} from '@angular/common'; import { OffClickModule } from 'angular2-off-click'; @NgModule({ imports: [ OffClickModule, BrowserModule, Ng2MapModule, FormsModule, ReactiveFormsModule, HttpModule, JsonpModule, CommonModule ], declarations: [ AppComponent, MapComponent, SearchComponent ], providers: [SearchAPIService], bootstrap: [ AppComponent ] }) export class
{ }
AppModule
identifier_name
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { MapComponent } from './map/map.component'; import { Ng2MapModule} from 'ng2-map'; import {SearchComponent} from './search/search.component'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {SearchAPIService} from './search/search.api.service'; import {HttpModule, JsonpModule} from '@angular/http'; import {CommonModule} from '@angular/common'; import { OffClickModule } from 'angular2-off-click'; @NgModule({ imports: [ OffClickModule, BrowserModule, Ng2MapModule, FormsModule,
HttpModule, JsonpModule, CommonModule ], declarations: [ AppComponent, MapComponent, SearchComponent ], providers: [SearchAPIService], bootstrap: [ AppComponent ] }) export class AppModule { }
ReactiveFormsModule,
random_line_split
accessor-test.js
import HasManyHelper from './has-many-helper'; import {module, test} from 'qunit'; module('Integration | ORM | hasMany #accessor'); /* #association behavior works regardless of the state of the parent */ HasManyHelper.forEachScenario((scenario) => { test(`the references of a ${scenario.title} are correct`, function(assert) { let { parent, children, accessor, idsAccessor } = scenario.go(); assert.equal(parent[accessor].models.length, children.length, 'parent has correct number of children'); assert.equal(parent[idsAccessor].length, children.length, 'parent has correct number of child ids'); children.forEach(function(child, i) { assert.deepEqual(parent[accessor].models[i], children[i], 'each child is in parent.children array'); if (!child.isNew()) { assert.ok(parent[idsAccessor].indexOf(child.id) > -1, 'each saved child id is in parent.childrenIds array');
}); }); });
}
random_line_split
accessor-test.js
import HasManyHelper from './has-many-helper'; import {module, test} from 'qunit'; module('Integration | ORM | hasMany #accessor'); /* #association behavior works regardless of the state of the parent */ HasManyHelper.forEachScenario((scenario) => { test(`the references of a ${scenario.title} are correct`, function(assert) { let { parent, children, accessor, idsAccessor } = scenario.go(); assert.equal(parent[accessor].models.length, children.length, 'parent has correct number of children'); assert.equal(parent[idsAccessor].length, children.length, 'parent has correct number of child ids'); children.forEach(function(child, i) { assert.deepEqual(parent[accessor].models[i], children[i], 'each child is in parent.children array'); if (!child.isNew())
}); }); });
{ assert.ok(parent[idsAccessor].indexOf(child.id) > -1, 'each saved child id is in parent.childrenIds array'); }
conditional_block
cursor.js
/** * Baobab Cursors * =============== * * Cursors created by selecting some data within a Baobab tree. */ import Emitter from 'emmett'; import {Monkey} from './monkey'; import type from './type'; import { Archive, arrayFrom, before,
getIn, makeError, shallowClone, solveUpdate } from './helpers'; /** * Traversal helper function for dynamic cursors. Will throw a legible error * if traversal is not possible. * * @param {string} method - The method name, to create a correct error msg. * @param {array} solvedPath - The cursor's solved path. */ function checkPossibilityOfDynamicTraversal(method, solvedPath) { if (!solvedPath) throw makeError( `Baobab.Cursor.${method}: ` + `cannot use ${method} on an unresolved dynamic path.`, {path: solvedPath} ); } /** * Cursor class * * @constructor * @param {Baobab} tree - The cursor's root. * @param {array} path - The cursor's path in the tree. * @param {string} hash - The path's hash computed ahead by the tree. */ export default class Cursor extends Emitter { constructor(tree, path, hash) { super(); // If no path were to be provided, we fallback to an empty path (root) path = path || []; // Privates this._identity = '[object Cursor]'; this._archive = null; // Properties this.tree = tree; this.path = path; this.hash = hash; // State this.state = { killed: false, recording: false, undoing: false }; // Checking whether the given path is dynamic or not this._dynamicPath = type.dynamicPath(this.path); // Checking whether the given path will meet a monkey this._monkeyPath = type.monkeyPath(this.tree._monkeys, this.path); if (!this._dynamicPath) this.solvedPath = this.path; else this.solvedPath = getIn(this.tree._data, this.path).solvedPath; /** * Listener bound to the tree's writes so that cursors with dynamic paths * may update their solved path correctly. * * @param {object} event - The event fired by the tree. */ this._writeHandler = ({data}) => { if (this.state.killed || !solveUpdate([data.path], this._getComparedPaths())) return; this.solvedPath = getIn(this.tree._data, this.path).solvedPath; }; /** * Function in charge of actually trigger the cursor's updates and * deal with the archived records. * * @note: probably should wrap the current solvedPath in closure to avoid * for tricky cases where it would fail. * * @param {mixed} previousData - the tree's previous data. */ const fireUpdate = (previousData) => { const self = this; const eventData = { get previousData() { return getIn(previousData, self.solvedPath).data; }, get currentData() { return self.get(); } }; if (this.state.recording && !this.state.undoing) this.archive.add(eventData.previousData); this.state.undoing = false; return this.emit('update', eventData); }; /** * Listener bound to the tree's updates and determining whether the * cursor is affected and should react accordingly. * * Note that this listener is lazily bound to the tree to be sure * one wouldn't leak listeners when only creating cursors for convenience * and not to listen to updates specifically. * * @param {object} event - The event fired by the tree. */ this._updateHandler = (event) => { if (this.state.killed) return; const {paths, previousData} = event.data, update = fireUpdate.bind(this, previousData), comparedPaths = this._getComparedPaths(); if (solveUpdate(paths, comparedPaths)) return update(); }; // Lazy binding let bound = false; this._lazyBind = () => { if (bound) return; bound = true; if (this._dynamicPath) this.tree.on('write', this._writeHandler); return this.tree.on('update', this._updateHandler); }; // If the path is dynamic, we actually need to listen to the tree if (this._dynamicPath) { this._lazyBind(); } else { // Overriding the emitter `on` and `once` methods this.on = before(this._lazyBind, this.on.bind(this)); this.once = before(this._lazyBind, this.once.bind(this)); } } /** * Internal helpers * ----------------- */ /** * Method returning the paths of the tree watched over by the cursor and that * should be taken into account when solving a potential update. * * @return {array} - Array of paths to compare with a given update. */ _getComparedPaths() { // Checking whether we should keep track of some dependencies const additionalPaths = this._monkeyPath ? getIn(this.tree._monkeys, this._monkeyPath) .data .relatedPaths() : []; return [this.solvedPath].concat(additionalPaths); } /** * Predicates * ----------- */ /** * Method returning whether the cursor is at root level. * * @return {boolean} - Is the cursor the root? */ isRoot() { return !this.path.length; } /** * Method returning whether the cursor is at leaf level. * * @return {boolean} - Is the cursor a leaf? */ isLeaf() { return type.primitive(this._get().data); } /** * Method returning whether the cursor is at branch level. * * @return {boolean} - Is the cursor a branch? */ isBranch() { return !this.isRoot() && !this.isLeaf(); } /** * Traversal Methods * ------------------ */ /** * Method returning the root cursor. * * @return {Baobab} - The root cursor. */ root() { return this.tree.select(); } /** * Method selecting a subpath as a new cursor. * * Arity (1): * @param {path} path - The path to select. * * Arity (*): * @param {...step} path - The path to select. * * @return {Cursor} - The created cursor. */ select(path) { if (arguments.length > 1) path = arrayFrom(arguments); return this.tree.select(this.path.concat(path)); } /** * Method returning the parent node of the cursor or else `null` if the * cursor is already at root level. * * @return {Baobab} - The parent cursor. */ up() { if (!this.isRoot()) return this.tree.select(this.path.slice(0, -1)); return null; } /** * Method returning the child node of the cursor. * * @return {Baobab} - The child cursor. */ down() { checkPossibilityOfDynamicTraversal('down', this.solvedPath); if (!(this._get().data instanceof Array)) throw Error('Baobab.Cursor.down: cannot go down on a non-list type.'); return this.tree.select(this.solvedPath.concat(0)); } /** * Method returning the left sibling node of the cursor if this one is * pointing at a list. Returns `null` if this cursor is already leftmost. * * @return {Baobab} - The left sibling cursor. */ left() { checkPossibilityOfDynamicTraversal('left', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error('Baobab.Cursor.left: cannot go left on a non-list type.'); return last ? this.tree.select(this.solvedPath.slice(0, -1).concat(last - 1)) : null; } /** * Method returning the right sibling node of the cursor if this one is * pointing at a list. Returns `null` if this cursor is already rightmost. * * @return {Baobab} - The right sibling cursor. */ right() { checkPossibilityOfDynamicTraversal('right', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error('Baobab.Cursor.right: cannot go right on a non-list type.'); if (last + 1 === this.up()._get().data.length) return null; return this.tree.select(this.solvedPath.slice(0, -1).concat(last + 1)); } /** * Method returning the leftmost sibling node of the cursor if this one is * pointing at a list. * * @return {Baobab} - The leftmost sibling cursor. */ leftmost() { checkPossibilityOfDynamicTraversal('leftmost', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error('Baobab.Cursor.leftmost: cannot go left on a non-list type.'); return this.tree.select(this.solvedPath.slice(0, -1).concat(0)); } /** * Method returning the rightmost sibling node of the cursor if this one is * pointing at a list. * * @return {Baobab} - The rightmost sibling cursor. */ rightmost() { checkPossibilityOfDynamicTraversal('rightmost', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error( 'Baobab.Cursor.rightmost: cannot go right on a non-list type.'); const list = this.up()._get().data; return this.tree .select(this.solvedPath.slice(0, -1).concat(list.length - 1)); } /** * Method mapping the children nodes of the cursor. * * @param {function} fn - The function to map. * @param {object} [scope] - An optional scope. * @return {array} - The resultant array. */ map(fn, scope) { checkPossibilityOfDynamicTraversal('map', this.solvedPath); const array = this._get().data, l = arguments.length; if (!type.array(array)) throw Error('baobab.Cursor.map: cannot map a non-list type.'); return array.map(function(item, i) { return fn.call( l > 1 ? scope : this, this.select(i), i, array ); }, this); } /** * Getter Methods * --------------- */ /** * Internal get method. Basically contains the main body of the `get` method * without the event emitting. This is sometimes needed not to fire useless * events. * * @param {path} [path=[]] - Path to get in the tree. * @return {object} info - The resultant information. * @return {mixed} info.data - Data at path. * @return {array} info.solvedPath - The path solved when getting. */ _get(path = []) { if (!type.path(path)) throw makeError('Baobab.Cursor.getters: invalid path.', {path}); if (!this.solvedPath) return {data: undefined, solvedPath: null, exists: false}; return getIn(this.tree._data, this.solvedPath.concat(path)); } /** * Method used to check whether a certain path exists in the tree starting * from the current cursor. * * Arity (1): * @param {path} path - Path to check in the tree. * * Arity (2): * @param {..step} path - Path to check in the tree. * * @return {boolean} - Does the given path exists? */ exists(path) { path = coercePath(path); if (arguments.length > 1) path = arrayFrom(arguments); return this._get(path).exists; } /** * Method used to get data from the tree. Will fire a `get` event from the * tree so that the user may sometimes react upon it to fetch data, for * instance. * * Arity (1): * @param {path} path - Path to get in the tree. * * Arity (2): * @param {..step} path - Path to get in the tree. * * @return {mixed} - Data at path. */ get(path) { path = coercePath(path); if (arguments.length > 1) path = arrayFrom(arguments); const {data, solvedPath} = this._get(path); // Emitting the event this.tree.emit('get', {data, solvedPath, path: this.path.concat(path)}); return data; } /** * Method used to shallow clone data from the tree. * * Arity (1): * @param {path} path - Path to get in the tree. * * Arity (2): * @param {..step} path - Path to get in the tree. * * @return {mixed} - Cloned data at path. */ clone(...args) { const data = this.get(...args); return shallowClone(data); } /** * Method used to deep clone data from the tree. * * Arity (1): * @param {path} path - Path to get in the tree. * * Arity (2): * @param {..step} path - Path to get in the tree. * * @return {mixed} - Cloned data at path. */ deepClone(...args) { const data = this.get(...args); return deepClone(data); } /** * Method used to return raw data from the tree, by carefully avoiding * computed one. * * @todo: should be more performant as the cloning should happen as well as * when dropping computed data. * * Arity (1): * @param {path} path - Path to serialize in the tree. * * Arity (2): * @param {..step} path - Path to serialize in the tree. * * @return {mixed} - The retrieved raw data. */ serialize(path) { path = coercePath(path); if (arguments.length > 1) path = arrayFrom(arguments); if (!type.path(path)) throw makeError('Baobab.Cursor.getters: invalid path.', {path}); if (!this.solvedPath) return undefined; const fullPath = this.solvedPath.concat(path); const data = deepClone(getIn(this.tree._data, fullPath).data), monkeys = getIn(this.tree._monkeys, fullPath).data; const dropComputedData = (d, m) => { if (!type.object(m) || !type.object(d)) return; for (const k in m) { if (m[k] instanceof Monkey) delete d[k]; else dropComputedData(d[k], m[k]); } }; dropComputedData(data, monkeys); return data; } /** * Method used to project some of the data at cursor onto a map or a list. * * @param {object|array} projection - The projection's formal definition. * @return {object|array} - The resultant map/list. */ project(projection) { if (type.object(projection)) { const data = {}; for (const k in projection) data[k] = this.get(projection[k]); return data; } else if (type.array(projection)) { const data = []; for (let i = 0, l = projection.length; i < l; i++) data.push(this.get(projection[i])); return data; } throw makeError('Baobab.Cursor.project: wrong projection.', {projection}); } /** * History Methods * ---------------- */ /** * Methods starting to record the cursor's successive states. * * @param {integer} [maxRecords] - Maximum records to keep in memory. Note * that if no number is provided, the cursor * will keep everything. * @return {Cursor} - The cursor instance for chaining purposes. */ startRecording(maxRecords) { maxRecords = maxRecords || Infinity; if (maxRecords < 1) throw makeError('Baobab.Cursor.startRecording: invalid max records.', { value: maxRecords }); this.state.recording = true; if (this.archive) return this; // Lazy binding this._lazyBind(); this.archive = new Archive(maxRecords); return this; } /** * Methods stopping to record the cursor's successive states. * * @return {Cursor} - The cursor instance for chaining purposes. */ stopRecording() { this.state.recording = false; return this; } /** * Methods undoing n steps of the cursor's recorded states. * * @param {integer} [steps=1] - The number of steps to rollback. * @return {Cursor} - The cursor instance for chaining purposes. */ undo(steps = 1) { if (!this.state.recording) throw new Error('Baobab.Cursor.undo: cursor is not recording.'); const record = this.archive.back(steps); if (!record) throw Error('Baobab.Cursor.undo: cannot find a relevant record.'); this.state.undoing = true; this.set(record); return this; } /** * Methods returning whether the cursor has a recorded history. * * @return {boolean} - `true` if the cursor has a recorded history? */ hasHistory() { return !!(this.archive && this.archive.get().length); } /** * Methods returning the cursor's history. * * @return {array} - The cursor's history. */ getHistory() { return this.archive ? this.archive.get() : []; } /** * Methods clearing the cursor's history. * * @return {Cursor} - The cursor instance for chaining purposes. */ clearHistory() { if (this.archive) this.archive.clear(); return this; } /** * Releasing * ---------- */ /** * Methods releasing the cursor from memory. */ release() { // Removing listeners on parent if (this._dynamicPath) this.tree.off('write', this._writeHandler); this.tree.off('update', this._updateHandler); // Unsubscribe from the parent if (this.hash) delete this.tree._cursors[this.hash]; // Dereferencing delete this.tree; delete this.path; delete this.solvedPath; delete this.archive; // Killing emitter this.kill(); this.state.killed = true; } /** * Output * ------- */ /** * Overriding the `toJSON` method for convenient use with JSON.stringify. * * @return {mixed} - Data at cursor. */ toJSON() { return this.serialize(); } /** * Overriding the `toString` method for debugging purposes. * * @return {string} - The cursor's identity. */ toString() { return this._identity; } } /** * Method used to allow iterating over cursors containing list-type data. * * e.g. for(let i of cursor) { ... } * * @returns {object} - Each item sequentially. */ if (typeof Symbol === 'function' && typeof Symbol.iterator !== 'undefined') { Cursor.prototype[Symbol.iterator] = function() { const array = this._get().data; if (!type.array(array)) throw Error('baobab.Cursor.@@iterate: cannot iterate a non-list type.'); let i = 0; const cursor = this, length = array.length; return { next() { if (i < length) { return { value: cursor.select(i++) }; } return { done: true }; } }; }; } /** * Setter Methods * --------------- * * Those methods are dynamically assigned to the class for DRY reasons. */ // Not using a Set so that ES5 consumers don't pay a bundle size price const INTRANSITIVE_SETTERS = { unset: true, pop: true, shift: true }; /** * Function creating a setter method for the Cursor class. * * @param {string} name - the method's name. * @param {function} [typeChecker] - a function checking that the given value is * valid for the given operation. */ function makeSetter(name, typeChecker) { /** * Binding a setter method to the Cursor class and having the following * definition. * * Note: this is not really possible to make those setters variadic because * it would create an impossible polymorphism with path. * * @todo: perform value validation elsewhere so that tree.update can * beneficiate from it. * * Arity (1): * @param {mixed} value - New value to set at cursor's path. * * Arity (2): * @param {path} path - Subpath to update starting from cursor's. * @param {mixed} value - New value to set. * * @return {mixed} - Data at path. */ Cursor.prototype[name] = function(path, value) { // We should warn the user if he applies to many arguments to the function if (arguments.length > 2) throw makeError(`Baobab.Cursor.${name}: too many arguments.`); // Handling arities if (arguments.length === 1 && !INTRANSITIVE_SETTERS[name]) { value = path; path = []; } // Coerce path path = coercePath(path); // Checking the path's validity if (!type.path(path)) throw makeError(`Baobab.Cursor.${name}: invalid path.`, {path}); // Checking the value's validity if (typeChecker && !typeChecker(value)) throw makeError(`Baobab.Cursor.${name}: invalid value.`, {path, value}); // Checking the solvability of the cursor's dynamic path if (!this.solvedPath) throw makeError( `Baobab.Cursor.${name}: the dynamic path of the cursor cannot be solved.`, {path: this.path} ); const fullPath = this.solvedPath.concat(path); // Filing the update to the tree return this.tree.update( fullPath, { type: name, value } ); }; } /** * Making the necessary setters. */ makeSetter('set'); makeSetter('unset'); makeSetter('apply', type.function); makeSetter('push'); makeSetter('concat', type.array); makeSetter('unshift'); makeSetter('pop'); makeSetter('shift'); makeSetter('splice', type.splicer); makeSetter('merge', type.object); makeSetter('deepMerge', type.object);
coercePath, deepClone,
random_line_split
cursor.js
/** * Baobab Cursors * =============== * * Cursors created by selecting some data within a Baobab tree. */ import Emitter from 'emmett'; import {Monkey} from './monkey'; import type from './type'; import { Archive, arrayFrom, before, coercePath, deepClone, getIn, makeError, shallowClone, solveUpdate } from './helpers'; /** * Traversal helper function for dynamic cursors. Will throw a legible error * if traversal is not possible. * * @param {string} method - The method name, to create a correct error msg. * @param {array} solvedPath - The cursor's solved path. */ function checkPossibilityOfDynamicTraversal(method, solvedPath) { if (!solvedPath) throw makeError( `Baobab.Cursor.${method}: ` + `cannot use ${method} on an unresolved dynamic path.`, {path: solvedPath} ); } /** * Cursor class * * @constructor * @param {Baobab} tree - The cursor's root. * @param {array} path - The cursor's path in the tree. * @param {string} hash - The path's hash computed ahead by the tree. */ export default class Cursor extends Emitter { constructor(tree, path, hash) { super(); // If no path were to be provided, we fallback to an empty path (root) path = path || []; // Privates this._identity = '[object Cursor]'; this._archive = null; // Properties this.tree = tree; this.path = path; this.hash = hash; // State this.state = { killed: false, recording: false, undoing: false }; // Checking whether the given path is dynamic or not this._dynamicPath = type.dynamicPath(this.path); // Checking whether the given path will meet a monkey this._monkeyPath = type.monkeyPath(this.tree._monkeys, this.path); if (!this._dynamicPath) this.solvedPath = this.path; else this.solvedPath = getIn(this.tree._data, this.path).solvedPath; /** * Listener bound to the tree's writes so that cursors with dynamic paths * may update their solved path correctly. * * @param {object} event - The event fired by the tree. */ this._writeHandler = ({data}) => { if (this.state.killed || !solveUpdate([data.path], this._getComparedPaths())) return; this.solvedPath = getIn(this.tree._data, this.path).solvedPath; }; /** * Function in charge of actually trigger the cursor's updates and * deal with the archived records. * * @note: probably should wrap the current solvedPath in closure to avoid * for tricky cases where it would fail. * * @param {mixed} previousData - the tree's previous data. */ const fireUpdate = (previousData) => { const self = this; const eventData = { get previousData() { return getIn(previousData, self.solvedPath).data; }, get currentData() { return self.get(); } }; if (this.state.recording && !this.state.undoing) this.archive.add(eventData.previousData); this.state.undoing = false; return this.emit('update', eventData); }; /** * Listener bound to the tree's updates and determining whether the * cursor is affected and should react accordingly. * * Note that this listener is lazily bound to the tree to be sure * one wouldn't leak listeners when only creating cursors for convenience * and not to listen to updates specifically. * * @param {object} event - The event fired by the tree. */ this._updateHandler = (event) => { if (this.state.killed) return; const {paths, previousData} = event.data, update = fireUpdate.bind(this, previousData), comparedPaths = this._getComparedPaths(); if (solveUpdate(paths, comparedPaths)) return update(); }; // Lazy binding let bound = false; this._lazyBind = () => { if (bound) return; bound = true; if (this._dynamicPath) this.tree.on('write', this._writeHandler); return this.tree.on('update', this._updateHandler); }; // If the path is dynamic, we actually need to listen to the tree if (this._dynamicPath) { this._lazyBind(); } else { // Overriding the emitter `on` and `once` methods this.on = before(this._lazyBind, this.on.bind(this)); this.once = before(this._lazyBind, this.once.bind(this)); } } /** * Internal helpers * ----------------- */ /** * Method returning the paths of the tree watched over by the cursor and that * should be taken into account when solving a potential update. * * @return {array} - Array of paths to compare with a given update. */ _getComparedPaths() { // Checking whether we should keep track of some dependencies const additionalPaths = this._monkeyPath ? getIn(this.tree._monkeys, this._monkeyPath) .data .relatedPaths() : []; return [this.solvedPath].concat(additionalPaths); } /** * Predicates * ----------- */ /** * Method returning whether the cursor is at root level. * * @return {boolean} - Is the cursor the root? */ isRoot() { return !this.path.length; } /** * Method returning whether the cursor is at leaf level. * * @return {boolean} - Is the cursor a leaf? */ isLeaf() { return type.primitive(this._get().data); } /** * Method returning whether the cursor is at branch level. * * @return {boolean} - Is the cursor a branch? */ isBranch() { return !this.isRoot() && !this.isLeaf(); } /** * Traversal Methods * ------------------ */ /** * Method returning the root cursor. * * @return {Baobab} - The root cursor. */ root() { return this.tree.select(); } /** * Method selecting a subpath as a new cursor. * * Arity (1): * @param {path} path - The path to select. * * Arity (*): * @param {...step} path - The path to select. * * @return {Cursor} - The created cursor. */ select(path) { if (arguments.length > 1) path = arrayFrom(arguments); return this.tree.select(this.path.concat(path)); } /** * Method returning the parent node of the cursor or else `null` if the * cursor is already at root level. * * @return {Baobab} - The parent cursor. */ up() { if (!this.isRoot()) return this.tree.select(this.path.slice(0, -1)); return null; } /** * Method returning the child node of the cursor. * * @return {Baobab} - The child cursor. */ down()
/** * Method returning the left sibling node of the cursor if this one is * pointing at a list. Returns `null` if this cursor is already leftmost. * * @return {Baobab} - The left sibling cursor. */ left() { checkPossibilityOfDynamicTraversal('left', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error('Baobab.Cursor.left: cannot go left on a non-list type.'); return last ? this.tree.select(this.solvedPath.slice(0, -1).concat(last - 1)) : null; } /** * Method returning the right sibling node of the cursor if this one is * pointing at a list. Returns `null` if this cursor is already rightmost. * * @return {Baobab} - The right sibling cursor. */ right() { checkPossibilityOfDynamicTraversal('right', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error('Baobab.Cursor.right: cannot go right on a non-list type.'); if (last + 1 === this.up()._get().data.length) return null; return this.tree.select(this.solvedPath.slice(0, -1).concat(last + 1)); } /** * Method returning the leftmost sibling node of the cursor if this one is * pointing at a list. * * @return {Baobab} - The leftmost sibling cursor. */ leftmost() { checkPossibilityOfDynamicTraversal('leftmost', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error('Baobab.Cursor.leftmost: cannot go left on a non-list type.'); return this.tree.select(this.solvedPath.slice(0, -1).concat(0)); } /** * Method returning the rightmost sibling node of the cursor if this one is * pointing at a list. * * @return {Baobab} - The rightmost sibling cursor. */ rightmost() { checkPossibilityOfDynamicTraversal('rightmost', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error( 'Baobab.Cursor.rightmost: cannot go right on a non-list type.'); const list = this.up()._get().data; return this.tree .select(this.solvedPath.slice(0, -1).concat(list.length - 1)); } /** * Method mapping the children nodes of the cursor. * * @param {function} fn - The function to map. * @param {object} [scope] - An optional scope. * @return {array} - The resultant array. */ map(fn, scope) { checkPossibilityOfDynamicTraversal('map', this.solvedPath); const array = this._get().data, l = arguments.length; if (!type.array(array)) throw Error('baobab.Cursor.map: cannot map a non-list type.'); return array.map(function(item, i) { return fn.call( l > 1 ? scope : this, this.select(i), i, array ); }, this); } /** * Getter Methods * --------------- */ /** * Internal get method. Basically contains the main body of the `get` method * without the event emitting. This is sometimes needed not to fire useless * events. * * @param {path} [path=[]] - Path to get in the tree. * @return {object} info - The resultant information. * @return {mixed} info.data - Data at path. * @return {array} info.solvedPath - The path solved when getting. */ _get(path = []) { if (!type.path(path)) throw makeError('Baobab.Cursor.getters: invalid path.', {path}); if (!this.solvedPath) return {data: undefined, solvedPath: null, exists: false}; return getIn(this.tree._data, this.solvedPath.concat(path)); } /** * Method used to check whether a certain path exists in the tree starting * from the current cursor. * * Arity (1): * @param {path} path - Path to check in the tree. * * Arity (2): * @param {..step} path - Path to check in the tree. * * @return {boolean} - Does the given path exists? */ exists(path) { path = coercePath(path); if (arguments.length > 1) path = arrayFrom(arguments); return this._get(path).exists; } /** * Method used to get data from the tree. Will fire a `get` event from the * tree so that the user may sometimes react upon it to fetch data, for * instance. * * Arity (1): * @param {path} path - Path to get in the tree. * * Arity (2): * @param {..step} path - Path to get in the tree. * * @return {mixed} - Data at path. */ get(path) { path = coercePath(path); if (arguments.length > 1) path = arrayFrom(arguments); const {data, solvedPath} = this._get(path); // Emitting the event this.tree.emit('get', {data, solvedPath, path: this.path.concat(path)}); return data; } /** * Method used to shallow clone data from the tree. * * Arity (1): * @param {path} path - Path to get in the tree. * * Arity (2): * @param {..step} path - Path to get in the tree. * * @return {mixed} - Cloned data at path. */ clone(...args) { const data = this.get(...args); return shallowClone(data); } /** * Method used to deep clone data from the tree. * * Arity (1): * @param {path} path - Path to get in the tree. * * Arity (2): * @param {..step} path - Path to get in the tree. * * @return {mixed} - Cloned data at path. */ deepClone(...args) { const data = this.get(...args); return deepClone(data); } /** * Method used to return raw data from the tree, by carefully avoiding * computed one. * * @todo: should be more performant as the cloning should happen as well as * when dropping computed data. * * Arity (1): * @param {path} path - Path to serialize in the tree. * * Arity (2): * @param {..step} path - Path to serialize in the tree. * * @return {mixed} - The retrieved raw data. */ serialize(path) { path = coercePath(path); if (arguments.length > 1) path = arrayFrom(arguments); if (!type.path(path)) throw makeError('Baobab.Cursor.getters: invalid path.', {path}); if (!this.solvedPath) return undefined; const fullPath = this.solvedPath.concat(path); const data = deepClone(getIn(this.tree._data, fullPath).data), monkeys = getIn(this.tree._monkeys, fullPath).data; const dropComputedData = (d, m) => { if (!type.object(m) || !type.object(d)) return; for (const k in m) { if (m[k] instanceof Monkey) delete d[k]; else dropComputedData(d[k], m[k]); } }; dropComputedData(data, monkeys); return data; } /** * Method used to project some of the data at cursor onto a map or a list. * * @param {object|array} projection - The projection's formal definition. * @return {object|array} - The resultant map/list. */ project(projection) { if (type.object(projection)) { const data = {}; for (const k in projection) data[k] = this.get(projection[k]); return data; } else if (type.array(projection)) { const data = []; for (let i = 0, l = projection.length; i < l; i++) data.push(this.get(projection[i])); return data; } throw makeError('Baobab.Cursor.project: wrong projection.', {projection}); } /** * History Methods * ---------------- */ /** * Methods starting to record the cursor's successive states. * * @param {integer} [maxRecords] - Maximum records to keep in memory. Note * that if no number is provided, the cursor * will keep everything. * @return {Cursor} - The cursor instance for chaining purposes. */ startRecording(maxRecords) { maxRecords = maxRecords || Infinity; if (maxRecords < 1) throw makeError('Baobab.Cursor.startRecording: invalid max records.', { value: maxRecords }); this.state.recording = true; if (this.archive) return this; // Lazy binding this._lazyBind(); this.archive = new Archive(maxRecords); return this; } /** * Methods stopping to record the cursor's successive states. * * @return {Cursor} - The cursor instance for chaining purposes. */ stopRecording() { this.state.recording = false; return this; } /** * Methods undoing n steps of the cursor's recorded states. * * @param {integer} [steps=1] - The number of steps to rollback. * @return {Cursor} - The cursor instance for chaining purposes. */ undo(steps = 1) { if (!this.state.recording) throw new Error('Baobab.Cursor.undo: cursor is not recording.'); const record = this.archive.back(steps); if (!record) throw Error('Baobab.Cursor.undo: cannot find a relevant record.'); this.state.undoing = true; this.set(record); return this; } /** * Methods returning whether the cursor has a recorded history. * * @return {boolean} - `true` if the cursor has a recorded history? */ hasHistory() { return !!(this.archive && this.archive.get().length); } /** * Methods returning the cursor's history. * * @return {array} - The cursor's history. */ getHistory() { return this.archive ? this.archive.get() : []; } /** * Methods clearing the cursor's history. * * @return {Cursor} - The cursor instance for chaining purposes. */ clearHistory() { if (this.archive) this.archive.clear(); return this; } /** * Releasing * ---------- */ /** * Methods releasing the cursor from memory. */ release() { // Removing listeners on parent if (this._dynamicPath) this.tree.off('write', this._writeHandler); this.tree.off('update', this._updateHandler); // Unsubscribe from the parent if (this.hash) delete this.tree._cursors[this.hash]; // Dereferencing delete this.tree; delete this.path; delete this.solvedPath; delete this.archive; // Killing emitter this.kill(); this.state.killed = true; } /** * Output * ------- */ /** * Overriding the `toJSON` method for convenient use with JSON.stringify. * * @return {mixed} - Data at cursor. */ toJSON() { return this.serialize(); } /** * Overriding the `toString` method for debugging purposes. * * @return {string} - The cursor's identity. */ toString() { return this._identity; } } /** * Method used to allow iterating over cursors containing list-type data. * * e.g. for(let i of cursor) { ... } * * @returns {object} - Each item sequentially. */ if (typeof Symbol === 'function' && typeof Symbol.iterator !== 'undefined') { Cursor.prototype[Symbol.iterator] = function() { const array = this._get().data; if (!type.array(array)) throw Error('baobab.Cursor.@@iterate: cannot iterate a non-list type.'); let i = 0; const cursor = this, length = array.length; return { next() { if (i < length) { return { value: cursor.select(i++) }; } return { done: true }; } }; }; } /** * Setter Methods * --------------- * * Those methods are dynamically assigned to the class for DRY reasons. */ // Not using a Set so that ES5 consumers don't pay a bundle size price const INTRANSITIVE_SETTERS = { unset: true, pop: true, shift: true }; /** * Function creating a setter method for the Cursor class. * * @param {string} name - the method's name. * @param {function} [typeChecker] - a function checking that the given value is * valid for the given operation. */ function makeSetter(name, typeChecker) { /** * Binding a setter method to the Cursor class and having the following * definition. * * Note: this is not really possible to make those setters variadic because * it would create an impossible polymorphism with path. * * @todo: perform value validation elsewhere so that tree.update can * beneficiate from it. * * Arity (1): * @param {mixed} value - New value to set at cursor's path. * * Arity (2): * @param {path} path - Subpath to update starting from cursor's. * @param {mixed} value - New value to set. * * @return {mixed} - Data at path. */ Cursor.prototype[name] = function(path, value) { // We should warn the user if he applies to many arguments to the function if (arguments.length > 2) throw makeError(`Baobab.Cursor.${name}: too many arguments.`); // Handling arities if (arguments.length === 1 && !INTRANSITIVE_SETTERS[name]) { value = path; path = []; } // Coerce path path = coercePath(path); // Checking the path's validity if (!type.path(path)) throw makeError(`Baobab.Cursor.${name}: invalid path.`, {path}); // Checking the value's validity if (typeChecker && !typeChecker(value)) throw makeError(`Baobab.Cursor.${name}: invalid value.`, {path, value}); // Checking the solvability of the cursor's dynamic path if (!this.solvedPath) throw makeError( `Baobab.Cursor.${name}: the dynamic path of the cursor cannot be solved.`, {path: this.path} ); const fullPath = this.solvedPath.concat(path); // Filing the update to the tree return this.tree.update( fullPath, { type: name, value } ); }; } /** * Making the necessary setters. */ makeSetter('set'); makeSetter('unset'); makeSetter('apply', type.function); makeSetter('push'); makeSetter('concat', type.array); makeSetter('unshift'); makeSetter('pop'); makeSetter('shift'); makeSetter('splice', type.splicer); makeSetter('merge', type.object); makeSetter('deepMerge', type.object);
{ checkPossibilityOfDynamicTraversal('down', this.solvedPath); if (!(this._get().data instanceof Array)) throw Error('Baobab.Cursor.down: cannot go down on a non-list type.'); return this.tree.select(this.solvedPath.concat(0)); }
identifier_body
cursor.js
/** * Baobab Cursors * =============== * * Cursors created by selecting some data within a Baobab tree. */ import Emitter from 'emmett'; import {Monkey} from './monkey'; import type from './type'; import { Archive, arrayFrom, before, coercePath, deepClone, getIn, makeError, shallowClone, solveUpdate } from './helpers'; /** * Traversal helper function for dynamic cursors. Will throw a legible error * if traversal is not possible. * * @param {string} method - The method name, to create a correct error msg. * @param {array} solvedPath - The cursor's solved path. */ function checkPossibilityOfDynamicTraversal(method, solvedPath) { if (!solvedPath) throw makeError( `Baobab.Cursor.${method}: ` + `cannot use ${method} on an unresolved dynamic path.`, {path: solvedPath} ); } /** * Cursor class * * @constructor * @param {Baobab} tree - The cursor's root. * @param {array} path - The cursor's path in the tree. * @param {string} hash - The path's hash computed ahead by the tree. */ export default class Cursor extends Emitter { constructor(tree, path, hash) { super(); // If no path were to be provided, we fallback to an empty path (root) path = path || []; // Privates this._identity = '[object Cursor]'; this._archive = null; // Properties this.tree = tree; this.path = path; this.hash = hash; // State this.state = { killed: false, recording: false, undoing: false }; // Checking whether the given path is dynamic or not this._dynamicPath = type.dynamicPath(this.path); // Checking whether the given path will meet a monkey this._monkeyPath = type.monkeyPath(this.tree._monkeys, this.path); if (!this._dynamicPath) this.solvedPath = this.path; else this.solvedPath = getIn(this.tree._data, this.path).solvedPath; /** * Listener bound to the tree's writes so that cursors with dynamic paths * may update their solved path correctly. * * @param {object} event - The event fired by the tree. */ this._writeHandler = ({data}) => { if (this.state.killed || !solveUpdate([data.path], this._getComparedPaths())) return; this.solvedPath = getIn(this.tree._data, this.path).solvedPath; }; /** * Function in charge of actually trigger the cursor's updates and * deal with the archived records. * * @note: probably should wrap the current solvedPath in closure to avoid * for tricky cases where it would fail. * * @param {mixed} previousData - the tree's previous data. */ const fireUpdate = (previousData) => { const self = this; const eventData = { get previousData() { return getIn(previousData, self.solvedPath).data; }, get currentData() { return self.get(); } }; if (this.state.recording && !this.state.undoing) this.archive.add(eventData.previousData); this.state.undoing = false; return this.emit('update', eventData); }; /** * Listener bound to the tree's updates and determining whether the * cursor is affected and should react accordingly. * * Note that this listener is lazily bound to the tree to be sure * one wouldn't leak listeners when only creating cursors for convenience * and not to listen to updates specifically. * * @param {object} event - The event fired by the tree. */ this._updateHandler = (event) => { if (this.state.killed) return; const {paths, previousData} = event.data, update = fireUpdate.bind(this, previousData), comparedPaths = this._getComparedPaths(); if (solveUpdate(paths, comparedPaths)) return update(); }; // Lazy binding let bound = false; this._lazyBind = () => { if (bound) return; bound = true; if (this._dynamicPath) this.tree.on('write', this._writeHandler); return this.tree.on('update', this._updateHandler); }; // If the path is dynamic, we actually need to listen to the tree if (this._dynamicPath) { this._lazyBind(); } else { // Overriding the emitter `on` and `once` methods this.on = before(this._lazyBind, this.on.bind(this)); this.once = before(this._lazyBind, this.once.bind(this)); } } /** * Internal helpers * ----------------- */ /** * Method returning the paths of the tree watched over by the cursor and that * should be taken into account when solving a potential update. * * @return {array} - Array of paths to compare with a given update. */ _getComparedPaths() { // Checking whether we should keep track of some dependencies const additionalPaths = this._monkeyPath ? getIn(this.tree._monkeys, this._monkeyPath) .data .relatedPaths() : []; return [this.solvedPath].concat(additionalPaths); } /** * Predicates * ----------- */ /** * Method returning whether the cursor is at root level. * * @return {boolean} - Is the cursor the root? */ isRoot() { return !this.path.length; } /** * Method returning whether the cursor is at leaf level. * * @return {boolean} - Is the cursor a leaf? */ isLeaf() { return type.primitive(this._get().data); } /** * Method returning whether the cursor is at branch level. * * @return {boolean} - Is the cursor a branch? */ isBranch() { return !this.isRoot() && !this.isLeaf(); } /** * Traversal Methods * ------------------ */ /** * Method returning the root cursor. * * @return {Baobab} - The root cursor. */ root() { return this.tree.select(); } /** * Method selecting a subpath as a new cursor. * * Arity (1): * @param {path} path - The path to select. * * Arity (*): * @param {...step} path - The path to select. * * @return {Cursor} - The created cursor. */ select(path) { if (arguments.length > 1) path = arrayFrom(arguments); return this.tree.select(this.path.concat(path)); } /** * Method returning the parent node of the cursor or else `null` if the * cursor is already at root level. * * @return {Baobab} - The parent cursor. */ up() { if (!this.isRoot()) return this.tree.select(this.path.slice(0, -1)); return null; } /** * Method returning the child node of the cursor. * * @return {Baobab} - The child cursor. */ down() { checkPossibilityOfDynamicTraversal('down', this.solvedPath); if (!(this._get().data instanceof Array)) throw Error('Baobab.Cursor.down: cannot go down on a non-list type.'); return this.tree.select(this.solvedPath.concat(0)); } /** * Method returning the left sibling node of the cursor if this one is * pointing at a list. Returns `null` if this cursor is already leftmost. * * @return {Baobab} - The left sibling cursor. */ left() { checkPossibilityOfDynamicTraversal('left', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error('Baobab.Cursor.left: cannot go left on a non-list type.'); return last ? this.tree.select(this.solvedPath.slice(0, -1).concat(last - 1)) : null; } /** * Method returning the right sibling node of the cursor if this one is * pointing at a list. Returns `null` if this cursor is already rightmost. * * @return {Baobab} - The right sibling cursor. */ right() { checkPossibilityOfDynamicTraversal('right', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error('Baobab.Cursor.right: cannot go right on a non-list type.'); if (last + 1 === this.up()._get().data.length) return null; return this.tree.select(this.solvedPath.slice(0, -1).concat(last + 1)); } /** * Method returning the leftmost sibling node of the cursor if this one is * pointing at a list. * * @return {Baobab} - The leftmost sibling cursor. */ leftmost() { checkPossibilityOfDynamicTraversal('leftmost', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error('Baobab.Cursor.leftmost: cannot go left on a non-list type.'); return this.tree.select(this.solvedPath.slice(0, -1).concat(0)); } /** * Method returning the rightmost sibling node of the cursor if this one is * pointing at a list. * * @return {Baobab} - The rightmost sibling cursor. */ rightmost() { checkPossibilityOfDynamicTraversal('rightmost', this.solvedPath); const last = +this.solvedPath[this.solvedPath.length - 1]; if (isNaN(last)) throw Error( 'Baobab.Cursor.rightmost: cannot go right on a non-list type.'); const list = this.up()._get().data; return this.tree .select(this.solvedPath.slice(0, -1).concat(list.length - 1)); } /** * Method mapping the children nodes of the cursor. * * @param {function} fn - The function to map. * @param {object} [scope] - An optional scope. * @return {array} - The resultant array. */ map(fn, scope) { checkPossibilityOfDynamicTraversal('map', this.solvedPath); const array = this._get().data, l = arguments.length; if (!type.array(array)) throw Error('baobab.Cursor.map: cannot map a non-list type.'); return array.map(function(item, i) { return fn.call( l > 1 ? scope : this, this.select(i), i, array ); }, this); } /** * Getter Methods * --------------- */ /** * Internal get method. Basically contains the main body of the `get` method * without the event emitting. This is sometimes needed not to fire useless * events. * * @param {path} [path=[]] - Path to get in the tree. * @return {object} info - The resultant information. * @return {mixed} info.data - Data at path. * @return {array} info.solvedPath - The path solved when getting. */ _get(path = []) { if (!type.path(path)) throw makeError('Baobab.Cursor.getters: invalid path.', {path}); if (!this.solvedPath) return {data: undefined, solvedPath: null, exists: false}; return getIn(this.tree._data, this.solvedPath.concat(path)); } /** * Method used to check whether a certain path exists in the tree starting * from the current cursor. * * Arity (1): * @param {path} path - Path to check in the tree. * * Arity (2): * @param {..step} path - Path to check in the tree. * * @return {boolean} - Does the given path exists? */ exists(path) { path = coercePath(path); if (arguments.length > 1) path = arrayFrom(arguments); return this._get(path).exists; } /** * Method used to get data from the tree. Will fire a `get` event from the * tree so that the user may sometimes react upon it to fetch data, for * instance. * * Arity (1): * @param {path} path - Path to get in the tree. * * Arity (2): * @param {..step} path - Path to get in the tree. * * @return {mixed} - Data at path. */ get(path) { path = coercePath(path); if (arguments.length > 1) path = arrayFrom(arguments); const {data, solvedPath} = this._get(path); // Emitting the event this.tree.emit('get', {data, solvedPath, path: this.path.concat(path)}); return data; } /** * Method used to shallow clone data from the tree. * * Arity (1): * @param {path} path - Path to get in the tree. * * Arity (2): * @param {..step} path - Path to get in the tree. * * @return {mixed} - Cloned data at path. */ clone(...args) { const data = this.get(...args); return shallowClone(data); } /** * Method used to deep clone data from the tree. * * Arity (1): * @param {path} path - Path to get in the tree. * * Arity (2): * @param {..step} path - Path to get in the tree. * * @return {mixed} - Cloned data at path. */ deepClone(...args) { const data = this.get(...args); return deepClone(data); } /** * Method used to return raw data from the tree, by carefully avoiding * computed one. * * @todo: should be more performant as the cloning should happen as well as * when dropping computed data. * * Arity (1): * @param {path} path - Path to serialize in the tree. * * Arity (2): * @param {..step} path - Path to serialize in the tree. * * @return {mixed} - The retrieved raw data. */
(path) { path = coercePath(path); if (arguments.length > 1) path = arrayFrom(arguments); if (!type.path(path)) throw makeError('Baobab.Cursor.getters: invalid path.', {path}); if (!this.solvedPath) return undefined; const fullPath = this.solvedPath.concat(path); const data = deepClone(getIn(this.tree._data, fullPath).data), monkeys = getIn(this.tree._monkeys, fullPath).data; const dropComputedData = (d, m) => { if (!type.object(m) || !type.object(d)) return; for (const k in m) { if (m[k] instanceof Monkey) delete d[k]; else dropComputedData(d[k], m[k]); } }; dropComputedData(data, monkeys); return data; } /** * Method used to project some of the data at cursor onto a map or a list. * * @param {object|array} projection - The projection's formal definition. * @return {object|array} - The resultant map/list. */ project(projection) { if (type.object(projection)) { const data = {}; for (const k in projection) data[k] = this.get(projection[k]); return data; } else if (type.array(projection)) { const data = []; for (let i = 0, l = projection.length; i < l; i++) data.push(this.get(projection[i])); return data; } throw makeError('Baobab.Cursor.project: wrong projection.', {projection}); } /** * History Methods * ---------------- */ /** * Methods starting to record the cursor's successive states. * * @param {integer} [maxRecords] - Maximum records to keep in memory. Note * that if no number is provided, the cursor * will keep everything. * @return {Cursor} - The cursor instance for chaining purposes. */ startRecording(maxRecords) { maxRecords = maxRecords || Infinity; if (maxRecords < 1) throw makeError('Baobab.Cursor.startRecording: invalid max records.', { value: maxRecords }); this.state.recording = true; if (this.archive) return this; // Lazy binding this._lazyBind(); this.archive = new Archive(maxRecords); return this; } /** * Methods stopping to record the cursor's successive states. * * @return {Cursor} - The cursor instance for chaining purposes. */ stopRecording() { this.state.recording = false; return this; } /** * Methods undoing n steps of the cursor's recorded states. * * @param {integer} [steps=1] - The number of steps to rollback. * @return {Cursor} - The cursor instance for chaining purposes. */ undo(steps = 1) { if (!this.state.recording) throw new Error('Baobab.Cursor.undo: cursor is not recording.'); const record = this.archive.back(steps); if (!record) throw Error('Baobab.Cursor.undo: cannot find a relevant record.'); this.state.undoing = true; this.set(record); return this; } /** * Methods returning whether the cursor has a recorded history. * * @return {boolean} - `true` if the cursor has a recorded history? */ hasHistory() { return !!(this.archive && this.archive.get().length); } /** * Methods returning the cursor's history. * * @return {array} - The cursor's history. */ getHistory() { return this.archive ? this.archive.get() : []; } /** * Methods clearing the cursor's history. * * @return {Cursor} - The cursor instance for chaining purposes. */ clearHistory() { if (this.archive) this.archive.clear(); return this; } /** * Releasing * ---------- */ /** * Methods releasing the cursor from memory. */ release() { // Removing listeners on parent if (this._dynamicPath) this.tree.off('write', this._writeHandler); this.tree.off('update', this._updateHandler); // Unsubscribe from the parent if (this.hash) delete this.tree._cursors[this.hash]; // Dereferencing delete this.tree; delete this.path; delete this.solvedPath; delete this.archive; // Killing emitter this.kill(); this.state.killed = true; } /** * Output * ------- */ /** * Overriding the `toJSON` method for convenient use with JSON.stringify. * * @return {mixed} - Data at cursor. */ toJSON() { return this.serialize(); } /** * Overriding the `toString` method for debugging purposes. * * @return {string} - The cursor's identity. */ toString() { return this._identity; } } /** * Method used to allow iterating over cursors containing list-type data. * * e.g. for(let i of cursor) { ... } * * @returns {object} - Each item sequentially. */ if (typeof Symbol === 'function' && typeof Symbol.iterator !== 'undefined') { Cursor.prototype[Symbol.iterator] = function() { const array = this._get().data; if (!type.array(array)) throw Error('baobab.Cursor.@@iterate: cannot iterate a non-list type.'); let i = 0; const cursor = this, length = array.length; return { next() { if (i < length) { return { value: cursor.select(i++) }; } return { done: true }; } }; }; } /** * Setter Methods * --------------- * * Those methods are dynamically assigned to the class for DRY reasons. */ // Not using a Set so that ES5 consumers don't pay a bundle size price const INTRANSITIVE_SETTERS = { unset: true, pop: true, shift: true }; /** * Function creating a setter method for the Cursor class. * * @param {string} name - the method's name. * @param {function} [typeChecker] - a function checking that the given value is * valid for the given operation. */ function makeSetter(name, typeChecker) { /** * Binding a setter method to the Cursor class and having the following * definition. * * Note: this is not really possible to make those setters variadic because * it would create an impossible polymorphism with path. * * @todo: perform value validation elsewhere so that tree.update can * beneficiate from it. * * Arity (1): * @param {mixed} value - New value to set at cursor's path. * * Arity (2): * @param {path} path - Subpath to update starting from cursor's. * @param {mixed} value - New value to set. * * @return {mixed} - Data at path. */ Cursor.prototype[name] = function(path, value) { // We should warn the user if he applies to many arguments to the function if (arguments.length > 2) throw makeError(`Baobab.Cursor.${name}: too many arguments.`); // Handling arities if (arguments.length === 1 && !INTRANSITIVE_SETTERS[name]) { value = path; path = []; } // Coerce path path = coercePath(path); // Checking the path's validity if (!type.path(path)) throw makeError(`Baobab.Cursor.${name}: invalid path.`, {path}); // Checking the value's validity if (typeChecker && !typeChecker(value)) throw makeError(`Baobab.Cursor.${name}: invalid value.`, {path, value}); // Checking the solvability of the cursor's dynamic path if (!this.solvedPath) throw makeError( `Baobab.Cursor.${name}: the dynamic path of the cursor cannot be solved.`, {path: this.path} ); const fullPath = this.solvedPath.concat(path); // Filing the update to the tree return this.tree.update( fullPath, { type: name, value } ); }; } /** * Making the necessary setters. */ makeSetter('set'); makeSetter('unset'); makeSetter('apply', type.function); makeSetter('push'); makeSetter('concat', type.array); makeSetter('unshift'); makeSetter('pop'); makeSetter('shift'); makeSetter('splice', type.splicer); makeSetter('merge', type.object); makeSetter('deepMerge', type.object);
serialize
identifier_name
map_clone.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_trait_method; use clippy_utils::remove_blocks; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_copy, is_type_diagnostic_item}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::mir::Mutability; use rustc_middle::ty; use rustc_middle::ty::adjustment::Adjust; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::Ident; use rustc_span::{sym, Span}; declare_clippy_lint! { /// ### What it does /// Checks for usage of `map(|x| x.clone())` or /// dereferencing closures for `Copy` types, on `Iterator` or `Option`, /// and suggests `cloned()` or `copied()` instead /// /// ### Why is this bad? /// Readability, this can be written more concisely /// /// ### Example /// ```rust /// let x = vec![42, 43]; /// let y = x.iter(); /// let z = y.map(|i| *i); /// ``` /// /// The correct use would be: /// /// ```rust /// let x = vec![42, 43]; /// let y = x.iter(); /// let z = y.cloned(); /// ``` pub MAP_CLONE, style, "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types" } declare_lint_pass!(MapClone => [MAP_CLONE]); impl<'tcx> LateLintPass<'tcx> for MapClone { fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) { if e.span.from_expansion() { return; } if_chain! { if let hir::ExprKind::MethodCall(method, _, args, _) = e.kind; if args.len() == 2; if method.ident.name == sym::map; let ty = cx.typeck_results().expr_ty(&args[0]); if is_type_diagnostic_item(cx, ty, sym::Option) || is_trait_method(cx, e, sym::Iterator); if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].kind; then { let closure_body = cx.tcx.hir().body(body_id); let closure_expr = remove_blocks(&closure_body.value); match closure_body.params[0].pat.kind { hir::PatKind::Ref(inner, hir::Mutability::Not) => if let hir::PatKind::Binding( hir::BindingAnnotation::Unannotated, .., name, None ) = inner.kind { if ident_eq(name, closure_expr) { lint(cx, e.span, args[0].span, true); } }, hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, .., name, None) => { match closure_expr.kind { hir::ExprKind::Unary(hir::UnOp::Deref, inner) => { if ident_eq(name, inner) { if let ty::Ref(.., Mutability::Not) = cx.typeck_results().expr_ty(inner).kind() { lint(cx, e.span, args[0].span, true); } } }, hir::ExprKind::MethodCall(method, _, [obj], _) => if_chain! { if ident_eq(name, obj) && method.ident.name == sym::clone; if let Some(fn_id) = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id); if let Some(trait_id) = cx.tcx.trait_of_item(fn_id); if cx.tcx.lang_items().clone_trait().map_or(false, |id| id == trait_id); // no autoderefs if !cx.typeck_results().expr_adjustments(obj).iter() .any(|a| matches!(a.kind, Adjust::Deref(Some(..)))); then { let obj_ty = cx.typeck_results().expr_ty(obj); if let ty::Ref(_, ty, mutability) = obj_ty.kind() { if matches!(mutability, Mutability::Not) { let copy = is_copy(cx, ty); lint(cx, e.span, args[0].span, copy); } } else { lint_needless_cloning(cx, e.span, args[0].span); } } }, _ => {}, } }, _ => {}, } } } } } fn ident_eq(name: Ident, path: &hir::Expr<'_>) -> bool { if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = path.kind { path.segments.len() == 1 && path.segments[0].ident == name } else { false } } fn lint_needless_cloning(cx: &LateContext<'_>, root: Span, receiver: Span) { span_lint_and_sugg( cx, MAP_CLONE, root.trim_start(receiver).unwrap(), "you are needlessly cloning iterator elements", "remove the `map` call", String::new(), Applicability::MachineApplicable, ); } fn lint(cx: &LateContext<'_>, replace: Span, root: Span, copied: bool) { let mut applicability = Applicability::MachineApplicable; if copied { span_lint_and_sugg( cx, MAP_CLONE, replace, "you are using an explicit closure for copying elements", "consider calling the dedicated `copied` method", format!( "{}.copied()", snippet_with_applicability(cx, root, "..", &mut applicability) ), applicability, ); } else { span_lint_and_sugg( cx, MAP_CLONE, replace, "you are using an explicit closure for cloning elements", "consider calling the dedicated `cloned` method", format!( "{}.cloned()", snippet_with_applicability(cx, root, "..", &mut applicability) ),
applicability, ); } }
random_line_split
map_clone.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_trait_method; use clippy_utils::remove_blocks; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_copy, is_type_diagnostic_item}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::mir::Mutability; use rustc_middle::ty; use rustc_middle::ty::adjustment::Adjust; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::Ident; use rustc_span::{sym, Span}; declare_clippy_lint! { /// ### What it does /// Checks for usage of `map(|x| x.clone())` or /// dereferencing closures for `Copy` types, on `Iterator` or `Option`, /// and suggests `cloned()` or `copied()` instead /// /// ### Why is this bad? /// Readability, this can be written more concisely /// /// ### Example /// ```rust /// let x = vec![42, 43]; /// let y = x.iter(); /// let z = y.map(|i| *i); /// ``` /// /// The correct use would be: /// /// ```rust /// let x = vec![42, 43]; /// let y = x.iter(); /// let z = y.cloned(); /// ``` pub MAP_CLONE, style, "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types" } declare_lint_pass!(MapClone => [MAP_CLONE]); impl<'tcx> LateLintPass<'tcx> for MapClone { fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) { if e.span.from_expansion() { return; } if_chain! { if let hir::ExprKind::MethodCall(method, _, args, _) = e.kind; if args.len() == 2; if method.ident.name == sym::map; let ty = cx.typeck_results().expr_ty(&args[0]); if is_type_diagnostic_item(cx, ty, sym::Option) || is_trait_method(cx, e, sym::Iterator); if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].kind; then { let closure_body = cx.tcx.hir().body(body_id); let closure_expr = remove_blocks(&closure_body.value); match closure_body.params[0].pat.kind { hir::PatKind::Ref(inner, hir::Mutability::Not) => if let hir::PatKind::Binding( hir::BindingAnnotation::Unannotated, .., name, None ) = inner.kind { if ident_eq(name, closure_expr) { lint(cx, e.span, args[0].span, true); } }, hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, .., name, None) => { match closure_expr.kind { hir::ExprKind::Unary(hir::UnOp::Deref, inner) => { if ident_eq(name, inner) { if let ty::Ref(.., Mutability::Not) = cx.typeck_results().expr_ty(inner).kind() { lint(cx, e.span, args[0].span, true); } } }, hir::ExprKind::MethodCall(method, _, [obj], _) => if_chain! { if ident_eq(name, obj) && method.ident.name == sym::clone; if let Some(fn_id) = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id); if let Some(trait_id) = cx.tcx.trait_of_item(fn_id); if cx.tcx.lang_items().clone_trait().map_or(false, |id| id == trait_id); // no autoderefs if !cx.typeck_results().expr_adjustments(obj).iter() .any(|a| matches!(a.kind, Adjust::Deref(Some(..)))); then { let obj_ty = cx.typeck_results().expr_ty(obj); if let ty::Ref(_, ty, mutability) = obj_ty.kind() { if matches!(mutability, Mutability::Not) { let copy = is_copy(cx, ty); lint(cx, e.span, args[0].span, copy); } } else { lint_needless_cloning(cx, e.span, args[0].span); } } }, _ => {}, } }, _ => {}, } } } } } fn ident_eq(name: Ident, path: &hir::Expr<'_>) -> bool { if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = path.kind { path.segments.len() == 1 && path.segments[0].ident == name } else { false } } fn lint_needless_cloning(cx: &LateContext<'_>, root: Span, receiver: Span) { span_lint_and_sugg( cx, MAP_CLONE, root.trim_start(receiver).unwrap(), "you are needlessly cloning iterator elements", "remove the `map` call", String::new(), Applicability::MachineApplicable, ); } fn
(cx: &LateContext<'_>, replace: Span, root: Span, copied: bool) { let mut applicability = Applicability::MachineApplicable; if copied { span_lint_and_sugg( cx, MAP_CLONE, replace, "you are using an explicit closure for copying elements", "consider calling the dedicated `copied` method", format!( "{}.copied()", snippet_with_applicability(cx, root, "..", &mut applicability) ), applicability, ); } else { span_lint_and_sugg( cx, MAP_CLONE, replace, "you are using an explicit closure for cloning elements", "consider calling the dedicated `cloned` method", format!( "{}.cloned()", snippet_with_applicability(cx, root, "..", &mut applicability) ), applicability, ); } }
lint
identifier_name
map_clone.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_trait_method; use clippy_utils::remove_blocks; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_copy, is_type_diagnostic_item}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::mir::Mutability; use rustc_middle::ty; use rustc_middle::ty::adjustment::Adjust; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::Ident; use rustc_span::{sym, Span}; declare_clippy_lint! { /// ### What it does /// Checks for usage of `map(|x| x.clone())` or /// dereferencing closures for `Copy` types, on `Iterator` or `Option`, /// and suggests `cloned()` or `copied()` instead /// /// ### Why is this bad? /// Readability, this can be written more concisely /// /// ### Example /// ```rust /// let x = vec![42, 43]; /// let y = x.iter(); /// let z = y.map(|i| *i); /// ``` /// /// The correct use would be: /// /// ```rust /// let x = vec![42, 43]; /// let y = x.iter(); /// let z = y.cloned(); /// ``` pub MAP_CLONE, style, "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types" } declare_lint_pass!(MapClone => [MAP_CLONE]); impl<'tcx> LateLintPass<'tcx> for MapClone { fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) { if e.span.from_expansion() { return; } if_chain! { if let hir::ExprKind::MethodCall(method, _, args, _) = e.kind; if args.len() == 2; if method.ident.name == sym::map; let ty = cx.typeck_results().expr_ty(&args[0]); if is_type_diagnostic_item(cx, ty, sym::Option) || is_trait_method(cx, e, sym::Iterator); if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].kind; then { let closure_body = cx.tcx.hir().body(body_id); let closure_expr = remove_blocks(&closure_body.value); match closure_body.params[0].pat.kind { hir::PatKind::Ref(inner, hir::Mutability::Not) => if let hir::PatKind::Binding( hir::BindingAnnotation::Unannotated, .., name, None ) = inner.kind { if ident_eq(name, closure_expr) { lint(cx, e.span, args[0].span, true); } }, hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, .., name, None) => { match closure_expr.kind { hir::ExprKind::Unary(hir::UnOp::Deref, inner) => { if ident_eq(name, inner) { if let ty::Ref(.., Mutability::Not) = cx.typeck_results().expr_ty(inner).kind() { lint(cx, e.span, args[0].span, true); } } }, hir::ExprKind::MethodCall(method, _, [obj], _) => if_chain! { if ident_eq(name, obj) && method.ident.name == sym::clone; if let Some(fn_id) = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id); if let Some(trait_id) = cx.tcx.trait_of_item(fn_id); if cx.tcx.lang_items().clone_trait().map_or(false, |id| id == trait_id); // no autoderefs if !cx.typeck_results().expr_adjustments(obj).iter() .any(|a| matches!(a.kind, Adjust::Deref(Some(..)))); then { let obj_ty = cx.typeck_results().expr_ty(obj); if let ty::Ref(_, ty, mutability) = obj_ty.kind() { if matches!(mutability, Mutability::Not) { let copy = is_copy(cx, ty); lint(cx, e.span, args[0].span, copy); } } else { lint_needless_cloning(cx, e.span, args[0].span); } } }, _ => {}, } }, _ => {}, } } } } } fn ident_eq(name: Ident, path: &hir::Expr<'_>) -> bool { if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = path.kind { path.segments.len() == 1 && path.segments[0].ident == name } else { false } } fn lint_needless_cloning(cx: &LateContext<'_>, root: Span, receiver: Span) { span_lint_and_sugg( cx, MAP_CLONE, root.trim_start(receiver).unwrap(), "you are needlessly cloning iterator elements", "remove the `map` call", String::new(), Applicability::MachineApplicable, ); } fn lint(cx: &LateContext<'_>, replace: Span, root: Span, copied: bool) { let mut applicability = Applicability::MachineApplicable; if copied { span_lint_and_sugg( cx, MAP_CLONE, replace, "you are using an explicit closure for copying elements", "consider calling the dedicated `copied` method", format!( "{}.copied()", snippet_with_applicability(cx, root, "..", &mut applicability) ), applicability, ); } else
}
{ span_lint_and_sugg( cx, MAP_CLONE, replace, "you are using an explicit closure for cloning elements", "consider calling the dedicated `cloned` method", format!( "{}.cloned()", snippet_with_applicability(cx, root, "..", &mut applicability) ), applicability, ); }
conditional_block
map_clone.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_trait_method; use clippy_utils::remove_blocks; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_copy, is_type_diagnostic_item}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::mir::Mutability; use rustc_middle::ty; use rustc_middle::ty::adjustment::Adjust; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::Ident; use rustc_span::{sym, Span}; declare_clippy_lint! { /// ### What it does /// Checks for usage of `map(|x| x.clone())` or /// dereferencing closures for `Copy` types, on `Iterator` or `Option`, /// and suggests `cloned()` or `copied()` instead /// /// ### Why is this bad? /// Readability, this can be written more concisely /// /// ### Example /// ```rust /// let x = vec![42, 43]; /// let y = x.iter(); /// let z = y.map(|i| *i); /// ``` /// /// The correct use would be: /// /// ```rust /// let x = vec![42, 43]; /// let y = x.iter(); /// let z = y.cloned(); /// ``` pub MAP_CLONE, style, "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types" } declare_lint_pass!(MapClone => [MAP_CLONE]); impl<'tcx> LateLintPass<'tcx> for MapClone { fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) { if e.span.from_expansion() { return; } if_chain! { if let hir::ExprKind::MethodCall(method, _, args, _) = e.kind; if args.len() == 2; if method.ident.name == sym::map; let ty = cx.typeck_results().expr_ty(&args[0]); if is_type_diagnostic_item(cx, ty, sym::Option) || is_trait_method(cx, e, sym::Iterator); if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].kind; then { let closure_body = cx.tcx.hir().body(body_id); let closure_expr = remove_blocks(&closure_body.value); match closure_body.params[0].pat.kind { hir::PatKind::Ref(inner, hir::Mutability::Not) => if let hir::PatKind::Binding( hir::BindingAnnotation::Unannotated, .., name, None ) = inner.kind { if ident_eq(name, closure_expr) { lint(cx, e.span, args[0].span, true); } }, hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, .., name, None) => { match closure_expr.kind { hir::ExprKind::Unary(hir::UnOp::Deref, inner) => { if ident_eq(name, inner) { if let ty::Ref(.., Mutability::Not) = cx.typeck_results().expr_ty(inner).kind() { lint(cx, e.span, args[0].span, true); } } }, hir::ExprKind::MethodCall(method, _, [obj], _) => if_chain! { if ident_eq(name, obj) && method.ident.name == sym::clone; if let Some(fn_id) = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id); if let Some(trait_id) = cx.tcx.trait_of_item(fn_id); if cx.tcx.lang_items().clone_trait().map_or(false, |id| id == trait_id); // no autoderefs if !cx.typeck_results().expr_adjustments(obj).iter() .any(|a| matches!(a.kind, Adjust::Deref(Some(..)))); then { let obj_ty = cx.typeck_results().expr_ty(obj); if let ty::Ref(_, ty, mutability) = obj_ty.kind() { if matches!(mutability, Mutability::Not) { let copy = is_copy(cx, ty); lint(cx, e.span, args[0].span, copy); } } else { lint_needless_cloning(cx, e.span, args[0].span); } } }, _ => {}, } }, _ => {}, } } } } } fn ident_eq(name: Ident, path: &hir::Expr<'_>) -> bool { if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = path.kind { path.segments.len() == 1 && path.segments[0].ident == name } else { false } } fn lint_needless_cloning(cx: &LateContext<'_>, root: Span, receiver: Span) { span_lint_and_sugg( cx, MAP_CLONE, root.trim_start(receiver).unwrap(), "you are needlessly cloning iterator elements", "remove the `map` call", String::new(), Applicability::MachineApplicable, ); } fn lint(cx: &LateContext<'_>, replace: Span, root: Span, copied: bool)
{ let mut applicability = Applicability::MachineApplicable; if copied { span_lint_and_sugg( cx, MAP_CLONE, replace, "you are using an explicit closure for copying elements", "consider calling the dedicated `copied` method", format!( "{}.copied()", snippet_with_applicability(cx, root, "..", &mut applicability) ), applicability, ); } else { span_lint_and_sugg( cx, MAP_CLONE, replace, "you are using an explicit closure for cloning elements", "consider calling the dedicated `cloned` method", format!( "{}.cloned()", snippet_with_applicability(cx, root, "..", &mut applicability) ), applicability, ); } }
identifier_body
gamma.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // // ignore-lexer-test FIXME #15679 //! The Gamma and derived distributions. use self::GammaRepr::*; use self::ChiSquaredRepr::*; use core::num::Float; use {Rng, Open01}; use super::normal::StandardNormal; use super::{IndependentSample, Sample, Exp}; /// The Gamma distribution `Gamma(shape, scale)` distribution. /// /// The density function of this distribution is /// /// ```text /// f(x) = x^(k - 1) * exp(-x / θ) / (Γ(k) * θ^k) /// ``` /// /// where `Γ` is the Gamma function, `k` is the shape and `θ` is the /// scale and both `k` and `θ` are strictly positive. /// /// The algorithm used is that described by Marsaglia & Tsang 2000[1], /// falling back to directly sampling from an Exponential for `shape /// == 1`, and using the boosting technique described in [1] for /// `shape < 1`. /// /// # Example /// /// ```rust /// use rand::distributions::{IndependentSample, Gamma}; /// /// let gamma = Gamma::new(2.0, 5.0); /// let v = gamma.ind_sample(&mut rand::thread_rng()); /// println!("{} is from a Gamma(2, 5) distribution", v); /// ``` /// /// [1]: George Marsaglia and Wai Wan Tsang. 2000. "A Simple Method /// for Generating Gamma Variables" *ACM Trans. Math. Softw.* 26, 3 /// (September 2000), /// 363-372. DOI:[10.1145/358407.358414](http://doi.acm.org/10.1145/358407.358414) pub struct Gamma { repr: GammaRepr, } enum GammaRepr { Large(GammaLargeShape), One(Exp), Small(GammaSmallShape) } // These two helpers could be made public, but saving the // match-on-Gamma-enum branch from using them directly (e.g. if one // knows that the shape is always > 1) doesn't appear to be much // faster. /// Gamma distribution where the shape parameter is less than 1. /// /// Note, samples from this require a compulsory floating-point `pow` /// call, which makes it significantly slower than sampling from a /// gamma distribution where the shape parameter is greater than or /// equal to 1. ///
/// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaSmallShape { inv_shape: f64, large_shape: GammaLargeShape } /// Gamma distribution where the shape parameter is larger than 1. /// /// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaLargeShape { scale: f64, c: f64, d: f64 } impl Gamma { /// Construct an object representing the `Gamma(shape, scale)` /// distribution. /// /// Panics if `shape <= 0` or `scale <= 0`. pub fn new(shape: f64, scale: f64) -> Gamma { assert!(shape > 0.0, "Gamma::new called with shape <= 0"); assert!(scale > 0.0, "Gamma::new called with scale <= 0"); let repr = match shape { 1.0 => One(Exp::new(1.0 / scale)), 0.0 ... 1.0 => Small(GammaSmallShape::new_raw(shape, scale)), _ => Large(GammaLargeShape::new_raw(shape, scale)) }; Gamma { repr: repr } } } impl GammaSmallShape { fn new_raw(shape: f64, scale: f64) -> GammaSmallShape { GammaSmallShape { inv_shape: 1. / shape, large_shape: GammaLargeShape::new_raw(shape + 1.0, scale) } } } impl GammaLargeShape { fn new_raw(shape: f64, scale: f64) -> GammaLargeShape { let d = shape - 1. / 3.; GammaLargeShape { scale: scale, c: 1. / (9. * d).sqrt(), d: d } } } impl Sample<f64> for Gamma { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl Sample<f64> for GammaSmallShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl Sample<f64> for GammaLargeShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Gamma { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { match self.repr { Small(ref g) => g.ind_sample(rng), One(ref g) => g.ind_sample(rng), Large(ref g) => g.ind_sample(rng), } } } impl IndependentSample<f64> for GammaSmallShape { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let Open01(u) = rng.gen::<Open01<f64>>(); self.large_shape.ind_sample(rng) * u.powf(self.inv_shape) } } impl IndependentSample<f64> for GammaLargeShape { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { loop { let StandardNormal(x) = rng.gen::<StandardNormal>(); let v_cbrt = 1.0 + self.c * x; if v_cbrt <= 0.0 { // a^3 <= 0 iff a <= 0 continue } let v = v_cbrt * v_cbrt * v_cbrt; let Open01(u) = rng.gen::<Open01<f64>>(); let x_sqr = x * x; if u < 1.0 - 0.0331 * x_sqr * x_sqr || u.ln() < 0.5 * x_sqr + self.d * (1.0 - v + v.ln()) { return self.d * v * self.scale } } } } /// The chi-squared distribution `χ²(k)`, where `k` is the degrees of /// freedom. /// /// For `k > 0` integral, this distribution is the sum of the squares /// of `k` independent standard normal random variables. For other /// `k`, this uses the equivalent characterisation `χ²(k) = Gamma(k/2, /// 2)`. /// /// # Example /// /// ```rust /// use rand::distributions::{ChiSquared, IndependentSample}; /// /// let chi = ChiSquared::new(11.0); /// let v = chi.ind_sample(&mut rand::thread_rng()); /// println!("{} is from a χ²(11) distribution", v) /// ``` pub struct ChiSquared { repr: ChiSquaredRepr, } enum ChiSquaredRepr { // k == 1, Gamma(alpha, ..) is particularly slow for alpha < 1, // e.g. when alpha = 1/2 as it would be for this case, so special- // casing and using the definition of N(0,1)^2 is faster. DoFExactlyOne, DoFAnythingElse(Gamma), } impl ChiSquared { /// Create a new chi-squared distribution with degrees-of-freedom /// `k`. Panics if `k < 0`. pub fn new(k: f64) -> ChiSquared { let repr = if k == 1.0 { DoFExactlyOne } else { assert!(k > 0.0, "ChiSquared::new called with `k` < 0"); DoFAnythingElse(Gamma::new(0.5 * k, 2.0)) }; ChiSquared { repr: repr } } } impl Sample<f64> for ChiSquared { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for ChiSquared { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { match self.repr { DoFExactlyOne => { // k == 1 => N(0,1)^2 let StandardNormal(norm) = rng.gen::<StandardNormal>(); norm * norm } DoFAnythingElse(ref g) => g.ind_sample(rng) } } } /// The Fisher F distribution `F(m, n)`. /// /// This distribution is equivalent to the ratio of two normalised /// chi-squared distributions, that is, `F(m,n) = (χ²(m)/m) / /// (χ²(n)/n)`. /// /// # Example /// /// ```rust /// use rand::distributions::{FisherF, IndependentSample}; /// /// let f = FisherF::new(2.0, 32.0); /// let v = f.ind_sample(&mut rand::thread_rng()); /// println!("{} is from an F(2, 32) distribution", v) /// ``` pub struct FisherF { numer: ChiSquared, denom: ChiSquared, // denom_dof / numer_dof so that this can just be a straight // multiplication, rather than a division. dof_ratio: f64, } impl FisherF { /// Create a new `FisherF` distribution, with the given /// parameter. Panics if either `m` or `n` are not positive. pub fn new(m: f64, n: f64) -> FisherF { assert!(m > 0.0, "FisherF::new called with `m < 0`"); assert!(n > 0.0, "FisherF::new called with `n < 0`"); FisherF { numer: ChiSquared::new(m), denom: ChiSquared::new(n), dof_ratio: n / m } } } impl Sample<f64> for FisherF { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for FisherF { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.numer.ind_sample(rng) / self.denom.ind_sample(rng) * self.dof_ratio } } /// The Student t distribution, `t(nu)`, where `nu` is the degrees of /// freedom. /// /// # Example /// /// ```rust /// use rand::distributions::{StudentT, IndependentSample}; /// /// let t = StudentT::new(11.0); /// let v = t.ind_sample(&mut rand::thread_rng()); /// println!("{} is from a t(11) distribution", v) /// ``` pub struct StudentT { chi: ChiSquared, dof: f64 } impl StudentT { /// Create a new Student t distribution with `n` degrees of /// freedom. Panics if `n <= 0`. pub fn new(n: f64) -> StudentT { assert!(n > 0.0, "StudentT::new called with `n <= 0`"); StudentT { chi: ChiSquared::new(n), dof: n } } } impl Sample<f64> for StudentT { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for StudentT { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(norm) = rng.gen::<StandardNormal>(); norm * (self.dof / self.chi.ind_sample(rng)).sqrt() } } #[cfg(test)] mod test { use distributions::{Sample, IndependentSample}; use super::{ChiSquared, StudentT, FisherF}; #[test] fn test_chi_squared_one() { let mut chi = ChiSquared::new(1.0); let mut rng = ::test::rng(); for _ in 0..1000 { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] fn test_chi_squared_small() { let mut chi = ChiSquared::new(0.5); let mut rng = ::test::rng(); for _ in 0..1000 { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] fn test_chi_squared_large() { let mut chi = ChiSquared::new(30.0); let mut rng = ::test::rng(); for _ in 0..1000 { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_chi_squared_invalid_dof() { ChiSquared::new(-1.0); } #[test] fn test_f() { let mut f = FisherF::new(2.0, 32.0); let mut rng = ::test::rng(); for _ in 0..1000 { f.sample(&mut rng); f.ind_sample(&mut rng); } } #[test] fn test_t() { let mut t = StudentT::new(11.0); let mut rng = ::test::rng(); for _ in 0..1000 { t.sample(&mut rng); t.ind_sample(&mut rng); } } } #[cfg(test)] mod bench { extern crate test; use std::prelude::v1::*; use self::test::Bencher; use std::mem::size_of; use distributions::IndependentSample; use super::Gamma; #[bench] fn bench_gamma_large_shape(b: &mut Bencher) { let gamma = Gamma::new(10., 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in 0..::RAND_BENCH_N { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } #[bench] fn bench_gamma_small_shape(b: &mut Bencher) { let gamma = Gamma::new(0.1, 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in 0..::RAND_BENCH_N { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } }
random_line_split
gamma.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // // ignore-lexer-test FIXME #15679 //! The Gamma and derived distributions. use self::GammaRepr::*; use self::ChiSquaredRepr::*; use core::num::Float; use {Rng, Open01}; use super::normal::StandardNormal; use super::{IndependentSample, Sample, Exp}; /// The Gamma distribution `Gamma(shape, scale)` distribution. /// /// The density function of this distribution is /// /// ```text /// f(x) = x^(k - 1) * exp(-x / θ) / (Γ(k) * θ^k) /// ``` /// /// where `Γ` is the Gamma function, `k` is the shape and `θ` is the /// scale and both `k` and `θ` are strictly positive. /// /// The algorithm used is that described by Marsaglia & Tsang 2000[1], /// falling back to directly sampling from an Exponential for `shape /// == 1`, and using the boosting technique described in [1] for /// `shape < 1`. /// /// # Example /// /// ```rust /// use rand::distributions::{IndependentSample, Gamma}; /// /// let gamma = Gamma::new(2.0, 5.0); /// let v = gamma.ind_sample(&mut rand::thread_rng()); /// println!("{} is from a Gamma(2, 5) distribution", v); /// ``` /// /// [1]: George Marsaglia and Wai Wan Tsang. 2000. "A Simple Method /// for Generating Gamma Variables" *ACM Trans. Math. Softw.* 26, 3 /// (September 2000), /// 363-372. DOI:[10.1145/358407.358414](http://doi.acm.org/10.1145/358407.358414) pub struct Gamma { repr: GammaRepr, } enum GammaRepr { Large(GammaLargeShape), One(Exp), Small(GammaSmallShape) } // These two helpers could be made public, but saving the // match-on-Gamma-enum branch from using them directly (e.g. if one // knows that the shape is always > 1) doesn't appear to be much // faster. /// Gamma distribution where the shape parameter is less than 1. /// /// Note, samples from this require a compulsory floating-point `pow` /// call, which makes it significantly slower than sampling from a /// gamma distribution where the shape parameter is greater than or /// equal to 1. /// /// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaSmallShape { inv_shape: f64, large_shape: GammaLargeShape } /// Gamma distribution where the shape parameter is larger than 1. /// /// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaLargeShape { scale: f64, c: f64, d: f64 } impl Gamma { /// Construct an object representing the `Gamma(shape, scale)` /// distribution. /// /// Panics if `shape <= 0` or `scale <= 0`. pub fn new(shape: f64, scale: f64) -> Gamma { assert!(shape > 0.0, "Gamma::new called with shape <= 0"); assert!(scale > 0.0, "Gamma::new called with scale <= 0"); let repr = match shape { 1.0 => One(Exp::new(1.0 / scale)), 0.0 ... 1.0 => Small(GammaSmallShape::new_raw(shape, scale)), _ => Large(GammaLargeShape::new_raw(shape, scale)) }; Gamma { repr: repr } } } impl GammaSmallShape { fn new_raw(shape: f64, scale: f64) -> GammaSmallShape { GammaSmallShape { inv_shape: 1. / shape, large_shape: GammaLargeShape::new_raw(shape + 1.0, scale) } } } impl GammaLargeShape { fn new_raw(shape: f64, scale: f64) -> GammaLargeShape { let d = shape - 1. / 3.; GammaLargeShape { scale: scale, c: 1. / (9. * d).sqrt(), d: d } } } impl Sample<f64> for Gamma { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl Sample<f64> for GammaSmallShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl Sample<f64> for GammaLargeShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Gamma { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { match self.repr { Small(ref g) => g.ind_sample(rng), One(ref g) => g.ind_sample(rng), Large(ref g) => g.ind_sample(rng), } } } impl IndependentSample<f64> for GammaSmallShape { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let Open01(u) = rng.gen::<Open01<f64>>(); self.large_shape.ind_sample(rng) * u.powf(self.inv_shape) } } impl IndependentSample<f64> for GammaLargeShape { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { loop { let StandardNormal(x) = rng.gen::<StandardNormal>(); let v_cbrt = 1.0 + self.c * x; if v_cbrt <= 0.0 { // a^3 <= 0 iff a <= 0 continue } let v = v_cbrt * v_cbrt * v_cbrt; let Open01(u) = rng.gen::<Open01<f64>>(); let x_sqr = x * x; if u < 1.0 - 0.0331 * x_sqr * x_sqr || u.ln() < 0.5 * x_sqr + self.d * (1.0 - v + v.ln()) { return self.d * v * self.scale } } } } /// The chi-squared distribution `χ²(k)`, where `k` is the degrees of /// freedom. /// /// For `k > 0` integral, this distribution is the sum of the squares /// of `k` independent standard normal random variables. For other /// `k`, this uses the equivalent characterisation `χ²(k) = Gamma(k/2, /// 2)`. /// /// # Example /// /// ```rust /// use rand::distributions::{ChiSquared, IndependentSample}; /// /// let chi = ChiSquared::new(11.0); /// let v = chi.ind_sample(&mut rand::thread_rng()); /// println!("{} is from a χ²(11) distribution", v) /// ``` pub struct ChiSquared { repr: ChiSquaredRepr, } enum ChiSquaredRepr { // k == 1, Gamma(alpha, ..) is particularly slow for alpha < 1, // e.g. when alpha = 1/2 as it would be for this case, so special- // casing and using the definition of N(0,1)^2 is faster. DoFExactlyOne, DoFAnythingElse(Gamma), } impl ChiSquared { /// Create a new chi-squared distribution with degrees-of-freedom /// `k`. Panics if `k < 0`. pub fn new(k: f64) -> ChiSquared { let repr = if k == 1.0 { DoFExactlyOne } else { assert!(k > 0.0, "ChiSquared::new called with `k` < 0"); DoFAnythingElse(Gamma::new(0.5 * k, 2.0)) }; ChiSquared { repr: repr } } } impl Sample<f64> for ChiSquared { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for ChiSquared { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { match self.repr { DoFExactlyOne => { // k == 1 => N(0,1)^2 let StandardNormal(norm) = rng.gen::<StandardNormal>(); norm * norm } DoFAnythingElse(ref g) => g.ind_sample(rng) } } } /// The Fisher F distribution `F(m, n)`. /// /// This distribution is equivalent to the ratio of two normalised /// chi-squared distributions, that is, `F(m,n) = (χ²(m)/m) / /// (χ²(n)/n)`. /// /// # Example /// /// ```rust /// use rand::distributions::{FisherF, IndependentSample}; /// /// let f = FisherF::new(2.0, 32.0); /// let v = f.ind_sample(&mut rand::thread_rng()); /// println!("{} is from an F(2, 32) distribution", v) /// ``` pub struct FisherF { numer: ChiSquared, denom: ChiSquared, // denom_dof / numer_dof so that this can just be a straight // multiplication, rather than a division. dof_ratio: f64, } impl FisherF { /// Create a new `FisherF` distribution, with the given /// parameter. Panics if either `m` or `n` are not positive. pub fn new(m: f64, n: f64) -> FisherF { assert!(m > 0.0, "FisherF::new called with `m < 0`"); assert!(n > 0.0, "FisherF::new called with `n < 0`"); FisherF { numer: ChiSquared::new(m), denom: ChiSquared::new(n), dof_ratio: n / m } } } impl Sample<f64> for FisherF { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for FisherF { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.numer.ind_sample(rng) / self.denom.ind_sample(rng) * self.dof_ratio } } /// The Student t distribution, `t(nu)`, where `nu` is the degrees of /// freedom. /// /// # Example /// /// ```rust /// use rand::distributions::{StudentT, IndependentSample}; /// /// let t = StudentT::new(11.0); /// let v = t.ind_sample(&mut rand::thread_rng()); /// println!("{} is from a t(11) distribution", v) /// ``` pub struct StudentT { chi: ChiSquared, dof: f64 } impl StudentT { /// Create a new Student t distribution with `n` degrees of /// freedom. Panics if `n <= 0`. pub fn new(n: f64) -> StudentT { assert!(n > 0.0, "StudentT::new called with `n <= 0`"); StudentT { chi: ChiSquared::new(n), dof: n } } } impl Sample<f64> for StudentT { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for StudentT { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(norm) = rng.gen::<StandardNormal>(); norm * (self.dof / self.chi.ind_sample(rng)).sqrt() } } #[cfg(test)] mod test { use distributions::{Sample, IndependentSample}; use super::{ChiSquared, StudentT, FisherF}; #[test] fn test_chi_squared_one() { let mut chi = ChiSquared::new(1.0); let mut rng = ::test::rng(); for _ in 0..1000 { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] fn test_chi_squared_small() { let mut chi = ChiSquared::new(0.5); let mut rng = ::test::rng(); for _ in 0..1000 { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] fn test_chi_squared_large() { let mut chi = ChiSquared::new(30.0); let mut rng = ::test::rng(); for _ in 0..1000 { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_chi_squared_invalid_dof() { ChiSquared::new(-1.0); } #[test] fn test_f() { let mut f = FisherF::new(2.0, 32.0); let mut rng = ::test::rng(); for _ in 0..1000 { f.sample(&mut rng); f.ind_sample(&mut rng); } } #[test] fn test_t() { let mut t = StudentT::new(11.0); let mut rng = ::test::rng(); for _ in 0..1000 { t.sample(&mut rng); t.ind_sample(&mut rng); } } } #[cfg(test)] mod bench { extern crate test; use std::prelude::v1::*; use self::test::Bencher; use std::mem::size_of; use distributions::IndependentSample; use super::Gamma; #[bench] fn bench_gamma_larg
) { let gamma = Gamma::new(10., 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in 0..::RAND_BENCH_N { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } #[bench] fn bench_gamma_small_shape(b: &mut Bencher) { let gamma = Gamma::new(0.1, 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in 0..::RAND_BENCH_N { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } }
e_shape(b: &mut Bencher
identifier_name
gamma.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // // ignore-lexer-test FIXME #15679 //! The Gamma and derived distributions. use self::GammaRepr::*; use self::ChiSquaredRepr::*; use core::num::Float; use {Rng, Open01}; use super::normal::StandardNormal; use super::{IndependentSample, Sample, Exp}; /// The Gamma distribution `Gamma(shape, scale)` distribution. /// /// The density function of this distribution is /// /// ```text /// f(x) = x^(k - 1) * exp(-x / θ) / (Γ(k) * θ^k) /// ``` /// /// where `Γ` is the Gamma function, `k` is the shape and `θ` is the /// scale and both `k` and `θ` are strictly positive. /// /// The algorithm used is that described by Marsaglia & Tsang 2000[1], /// falling back to directly sampling from an Exponential for `shape /// == 1`, and using the boosting technique described in [1] for /// `shape < 1`. /// /// # Example /// /// ```rust /// use rand::distributions::{IndependentSample, Gamma}; /// /// let gamma = Gamma::new(2.0, 5.0); /// let v = gamma.ind_sample(&mut rand::thread_rng()); /// println!("{} is from a Gamma(2, 5) distribution", v); /// ``` /// /// [1]: George Marsaglia and Wai Wan Tsang. 2000. "A Simple Method /// for Generating Gamma Variables" *ACM Trans. Math. Softw.* 26, 3 /// (September 2000), /// 363-372. DOI:[10.1145/358407.358414](http://doi.acm.org/10.1145/358407.358414) pub struct Gamma { repr: GammaRepr, } enum GammaRepr { Large(GammaLargeShape), One(Exp), Small(GammaSmallShape) } // These two helpers could be made public, but saving the // match-on-Gamma-enum branch from using them directly (e.g. if one // knows that the shape is always > 1) doesn't appear to be much // faster. /// Gamma distribution where the shape parameter is less than 1. /// /// Note, samples from this require a compulsory floating-point `pow` /// call, which makes it significantly slower than sampling from a /// gamma distribution where the shape parameter is greater than or /// equal to 1. /// /// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaSmallShape { inv_shape: f64, large_shape: GammaLargeShape } /// Gamma distribution where the shape parameter is larger than 1. /// /// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaLargeShape { scale: f64, c: f64, d: f64 } impl Gamma { /// Construct an object representing the `Gamma(shape, scale)` /// distribution. /// /// Panics if `shape <= 0` or `scale <= 0`. pub fn new(shape: f64, scale: f64) -> Gamma { assert!(shape > 0.0, "Gamma::new called with shape <= 0"); assert!(scale > 0.0, "Gamma::new called with scale <= 0"); let repr = match shape { 1.0 => One(Exp::new(1.0 / scale)), 0.0 ... 1.0 => Small(GammaSmallShape::new_raw(shape, scale)), _ => Large(GammaLargeShape::new_raw(shape, scale)) }; Gamma { repr: repr } } } impl GammaSmallShape { fn new_raw(shape: f64, scale: f64) -> GammaSmallShape { GammaSmallShape { inv_shape: 1. / shape, large_shape: GammaLargeShape::new_raw(shape + 1.0, scale) } } } impl GammaLargeShape { fn new_raw(shape: f64, scale: f64) -> GammaLargeShape { let d = shape - 1. / 3.; GammaLargeShape { scale: scale, c: 1. / (9. * d).sqrt(), d: d } } } impl Sample<f64> for Gamma { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self
l Sample<f64> for GammaSmallShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl Sample<f64> for GammaLargeShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Gamma { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { match self.repr { Small(ref g) => g.ind_sample(rng), One(ref g) => g.ind_sample(rng), Large(ref g) => g.ind_sample(rng), } } } impl IndependentSample<f64> for GammaSmallShape { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let Open01(u) = rng.gen::<Open01<f64>>(); self.large_shape.ind_sample(rng) * u.powf(self.inv_shape) } } impl IndependentSample<f64> for GammaLargeShape { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { loop { let StandardNormal(x) = rng.gen::<StandardNormal>(); let v_cbrt = 1.0 + self.c * x; if v_cbrt <= 0.0 { // a^3 <= 0 iff a <= 0 continue } let v = v_cbrt * v_cbrt * v_cbrt; let Open01(u) = rng.gen::<Open01<f64>>(); let x_sqr = x * x; if u < 1.0 - 0.0331 * x_sqr * x_sqr || u.ln() < 0.5 * x_sqr + self.d * (1.0 - v + v.ln()) { return self.d * v * self.scale } } } } /// The chi-squared distribution `χ²(k)`, where `k` is the degrees of /// freedom. /// /// For `k > 0` integral, this distribution is the sum of the squares /// of `k` independent standard normal random variables. For other /// `k`, this uses the equivalent characterisation `χ²(k) = Gamma(k/2, /// 2)`. /// /// # Example /// /// ```rust /// use rand::distributions::{ChiSquared, IndependentSample}; /// /// let chi = ChiSquared::new(11.0); /// let v = chi.ind_sample(&mut rand::thread_rng()); /// println!("{} is from a χ²(11) distribution", v) /// ``` pub struct ChiSquared { repr: ChiSquaredRepr, } enum ChiSquaredRepr { // k == 1, Gamma(alpha, ..) is particularly slow for alpha < 1, // e.g. when alpha = 1/2 as it would be for this case, so special- // casing and using the definition of N(0,1)^2 is faster. DoFExactlyOne, DoFAnythingElse(Gamma), } impl ChiSquared { /// Create a new chi-squared distribution with degrees-of-freedom /// `k`. Panics if `k < 0`. pub fn new(k: f64) -> ChiSquared { let repr = if k == 1.0 { DoFExactlyOne } else { assert!(k > 0.0, "ChiSquared::new called with `k` < 0"); DoFAnythingElse(Gamma::new(0.5 * k, 2.0)) }; ChiSquared { repr: repr } } } impl Sample<f64> for ChiSquared { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for ChiSquared { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { match self.repr { DoFExactlyOne => { // k == 1 => N(0,1)^2 let StandardNormal(norm) = rng.gen::<StandardNormal>(); norm * norm } DoFAnythingElse(ref g) => g.ind_sample(rng) } } } /// The Fisher F distribution `F(m, n)`. /// /// This distribution is equivalent to the ratio of two normalised /// chi-squared distributions, that is, `F(m,n) = (χ²(m)/m) / /// (χ²(n)/n)`. /// /// # Example /// /// ```rust /// use rand::distributions::{FisherF, IndependentSample}; /// /// let f = FisherF::new(2.0, 32.0); /// let v = f.ind_sample(&mut rand::thread_rng()); /// println!("{} is from an F(2, 32) distribution", v) /// ``` pub struct FisherF { numer: ChiSquared, denom: ChiSquared, // denom_dof / numer_dof so that this can just be a straight // multiplication, rather than a division. dof_ratio: f64, } impl FisherF { /// Create a new `FisherF` distribution, with the given /// parameter. Panics if either `m` or `n` are not positive. pub fn new(m: f64, n: f64) -> FisherF { assert!(m > 0.0, "FisherF::new called with `m < 0`"); assert!(n > 0.0, "FisherF::new called with `n < 0`"); FisherF { numer: ChiSquared::new(m), denom: ChiSquared::new(n), dof_ratio: n / m } } } impl Sample<f64> for FisherF { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for FisherF { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.numer.ind_sample(rng) / self.denom.ind_sample(rng) * self.dof_ratio } } /// The Student t distribution, `t(nu)`, where `nu` is the degrees of /// freedom. /// /// # Example /// /// ```rust /// use rand::distributions::{StudentT, IndependentSample}; /// /// let t = StudentT::new(11.0); /// let v = t.ind_sample(&mut rand::thread_rng()); /// println!("{} is from a t(11) distribution", v) /// ``` pub struct StudentT { chi: ChiSquared, dof: f64 } impl StudentT { /// Create a new Student t distribution with `n` degrees of /// freedom. Panics if `n <= 0`. pub fn new(n: f64) -> StudentT { assert!(n > 0.0, "StudentT::new called with `n <= 0`"); StudentT { chi: ChiSquared::new(n), dof: n } } } impl Sample<f64> for StudentT { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for StudentT { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(norm) = rng.gen::<StandardNormal>(); norm * (self.dof / self.chi.ind_sample(rng)).sqrt() } } #[cfg(test)] mod test { use distributions::{Sample, IndependentSample}; use super::{ChiSquared, StudentT, FisherF}; #[test] fn test_chi_squared_one() { let mut chi = ChiSquared::new(1.0); let mut rng = ::test::rng(); for _ in 0..1000 { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] fn test_chi_squared_small() { let mut chi = ChiSquared::new(0.5); let mut rng = ::test::rng(); for _ in 0..1000 { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] fn test_chi_squared_large() { let mut chi = ChiSquared::new(30.0); let mut rng = ::test::rng(); for _ in 0..1000 { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_chi_squared_invalid_dof() { ChiSquared::new(-1.0); } #[test] fn test_f() { let mut f = FisherF::new(2.0, 32.0); let mut rng = ::test::rng(); for _ in 0..1000 { f.sample(&mut rng); f.ind_sample(&mut rng); } } #[test] fn test_t() { let mut t = StudentT::new(11.0); let mut rng = ::test::rng(); for _ in 0..1000 { t.sample(&mut rng); t.ind_sample(&mut rng); } } } #[cfg(test)] mod bench { extern crate test; use std::prelude::v1::*; use self::test::Bencher; use std::mem::size_of; use distributions::IndependentSample; use super::Gamma; #[bench] fn bench_gamma_large_shape(b: &mut Bencher) { let gamma = Gamma::new(10., 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in 0..::RAND_BENCH_N { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } #[bench] fn bench_gamma_small_shape(b: &mut Bencher) { let gamma = Gamma::new(0.1, 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in 0..::RAND_BENCH_N { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } }
.ind_sample(rng) } } imp
identifier_body
get_state_events_for_empty_key.rs
//! [GET /_matrix/client/r0/rooms/{roomId}/state/{eventType}](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-rooms-roomid-state-eventtype) use ruma_api::ruma_api; use ruma_events::EventType; use ruma_identifiers::RoomId; use serde_json::value::RawValue as RawJsonValue; ruma_api! { metadata { description: "Get state events of a given type associated with the empty key.", method: GET, name: "get_state_events_for_empty_key", path: "/_matrix/client/r0/rooms/:room_id/state/:event_type", rate_limited: false, requires_authentication: true, } request { /// The room to look up the state for. #[ruma_api(path)] pub room_id: RoomId, /// The type of state to look up.
response { /// The content of the state event. /// /// To create a `Box<RawJsonValue>`, use `serde_json::value::to_raw_value`. #[ruma_api(body)] pub content: Box<RawJsonValue>, } error: crate::Error }
#[ruma_api(path)] pub event_type: EventType, }
random_line_split
key_value_table_demo.py
import json import pprint from a2qt import QtWidgets from a2widget.key_value_table import KeyValueTable from a2widget.a2text_field import A2CodeField _DEMO_DATA = { 'Name': 'Some Body', 'Surname': 'Body', 'Street. Nr': 'Thingstreet 8', 'Street': 'Thingstreet', 'Nr': '8', 'PLZ': '12354', 'City': 'Frankfurt am Main', 'Phone+': '+1232222222', 'Phone': '2222222', 'Country': 'Germany', } class Demo(QtWidgets.QMainWindow): def __init__(self):
def table_to_code(self): data = self.key_value_table.get_data() self.text_field.setText(json.dumps(data, indent=2)) def code_to_table(self): data = json.loads(self.text_field.text()) self.key_value_table.set_silent(data) def get_data(self): data = self.key_value_table.get_data() print(data) pprint.pprint(data, sort_dicts=False) def set_data(self): data = json.loads(self.text_field.text()) self.key_value_table.set_data(data) def show(): app = QtWidgets.QApplication([]) win = Demo() win.show() app.exec() if __name__ == '__main__': show()
super(Demo, self).__init__() w = QtWidgets.QWidget(self) self.setCentralWidget(w) lyt = QtWidgets.QVBoxLayout(w) self.key_value_table = KeyValueTable(self) self.key_value_table.changed.connect(self.table_to_code) lyt.addWidget(self.key_value_table) btn = QtWidgets.QPushButton('GET DATA') btn.clicked.connect(self.get_data) lyt.addWidget(btn) self.text_field = A2CodeField(self) self.text_field.text_changed.connect(self.code_to_table) lyt.addWidget(self.text_field) btn = QtWidgets.QPushButton('SET DATA') btn.clicked.connect(self.set_data) lyt.addWidget(btn) self.text_field.setText(json.dumps(_DEMO_DATA, indent=2)) self.set_data()
identifier_body
key_value_table_demo.py
import json import pprint from a2qt import QtWidgets from a2widget.key_value_table import KeyValueTable from a2widget.a2text_field import A2CodeField _DEMO_DATA = { 'Name': 'Some Body', 'Surname': 'Body', 'Street. Nr': 'Thingstreet 8', 'Street': 'Thingstreet', 'Nr': '8', 'PLZ': '12354', 'City': 'Frankfurt am Main', 'Phone+': '+1232222222', 'Phone': '2222222', 'Country': 'Germany', } class Demo(QtWidgets.QMainWindow):
super(Demo, self).__init__() w = QtWidgets.QWidget(self) self.setCentralWidget(w) lyt = QtWidgets.QVBoxLayout(w) self.key_value_table = KeyValueTable(self) self.key_value_table.changed.connect(self.table_to_code) lyt.addWidget(self.key_value_table) btn = QtWidgets.QPushButton('GET DATA') btn.clicked.connect(self.get_data) lyt.addWidget(btn) self.text_field = A2CodeField(self) self.text_field.text_changed.connect(self.code_to_table) lyt.addWidget(self.text_field) btn = QtWidgets.QPushButton('SET DATA') btn.clicked.connect(self.set_data) lyt.addWidget(btn) self.text_field.setText(json.dumps(_DEMO_DATA, indent=2)) self.set_data() def table_to_code(self): data = self.key_value_table.get_data() self.text_field.setText(json.dumps(data, indent=2)) def code_to_table(self): data = json.loads(self.text_field.text()) self.key_value_table.set_silent(data) def get_data(self): data = self.key_value_table.get_data() print(data) pprint.pprint(data, sort_dicts=False) def set_data(self): data = json.loads(self.text_field.text()) self.key_value_table.set_data(data) def show(): app = QtWidgets.QApplication([]) win = Demo() win.show() app.exec() if __name__ == '__main__': show()
def __init__(self):
random_line_split
key_value_table_demo.py
import json import pprint from a2qt import QtWidgets from a2widget.key_value_table import KeyValueTable from a2widget.a2text_field import A2CodeField _DEMO_DATA = { 'Name': 'Some Body', 'Surname': 'Body', 'Street. Nr': 'Thingstreet 8', 'Street': 'Thingstreet', 'Nr': '8', 'PLZ': '12354', 'City': 'Frankfurt am Main', 'Phone+': '+1232222222', 'Phone': '2222222', 'Country': 'Germany', } class Demo(QtWidgets.QMainWindow): def __init__(self): super(Demo, self).__init__() w = QtWidgets.QWidget(self) self.setCentralWidget(w) lyt = QtWidgets.QVBoxLayout(w) self.key_value_table = KeyValueTable(self) self.key_value_table.changed.connect(self.table_to_code) lyt.addWidget(self.key_value_table) btn = QtWidgets.QPushButton('GET DATA') btn.clicked.connect(self.get_data) lyt.addWidget(btn) self.text_field = A2CodeField(self) self.text_field.text_changed.connect(self.code_to_table) lyt.addWidget(self.text_field) btn = QtWidgets.QPushButton('SET DATA') btn.clicked.connect(self.set_data) lyt.addWidget(btn) self.text_field.setText(json.dumps(_DEMO_DATA, indent=2)) self.set_data() def
(self): data = self.key_value_table.get_data() self.text_field.setText(json.dumps(data, indent=2)) def code_to_table(self): data = json.loads(self.text_field.text()) self.key_value_table.set_silent(data) def get_data(self): data = self.key_value_table.get_data() print(data) pprint.pprint(data, sort_dicts=False) def set_data(self): data = json.loads(self.text_field.text()) self.key_value_table.set_data(data) def show(): app = QtWidgets.QApplication([]) win = Demo() win.show() app.exec() if __name__ == '__main__': show()
table_to_code
identifier_name