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
users.rs
#![crate_name = "users"] /* * This file is part of the uutils coreutils package. * * (c) KokaKiwi <kokakiwi@kokakiwi.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.22 */ // Allow dead code here in order to keep all fields, constants here, for consistency. #![allow(dead_code)] extern crate getopts; extern crate libc; #[macro_use] extern crate uucore; use getopts::Options; use std::ffi::{CStr, CString}; use std::mem; use std::ptr; use uucore::utmpx::*; extern { fn getutxent() -> *const c_utmp; fn getutxid(ut: *const c_utmp) -> *const c_utmp; fn getutxline(ut: *const c_utmp) -> *const c_utmp; fn pututxline(ut: *const c_utmp) -> *const c_utmp; fn setutxent(); fn endutxent(); #[cfg(any(target_os = "macos", target_os = "linux"))] fn utmpxname(file: *const libc::c_char) -> libc::c_int; } #[cfg(target_os = "freebsd")] unsafe extern fn utmpxname(_file: *const libc::c_char) -> libc::c_int { 0 } static NAME: &'static str = "users"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!("{}", f), }; if matches.opt_present("help") { println!("{} {}", NAME, VERSION); println!(""); println!("Usage:"); println!(" {} [OPTION]... [FILE]", NAME); println!(""); println!("{}", opts.usage("Output who is currently logged in according to FILE.")); return 0; } if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } let filename = if matches.free.len() > 0 { matches.free[0].as_ref() } else { DEFAULT_FILE }; exec(filename); 0 } fn exec(filename: &str)
#[allow(dead_code)] fn main() { std::process::exit(uumain(std::env::args().collect())); }
{ unsafe { utmpxname(CString::new(filename).unwrap().as_ptr()); } let mut users = vec!(); unsafe { setutxent(); loop { let line = getutxent(); if line == ptr::null() { break; } if (*line).ut_type == USER_PROCESS { let user = String::from_utf8_lossy(CStr::from_ptr(mem::transmute(&(*line).ut_user)).to_bytes()).to_string(); users.push(user); } } endutxent(); } if users.len() > 0 { users.sort(); println!("{}", users.join(" ")); } }
identifier_body
users.rs
#![crate_name = "users"] /* * This file is part of the uutils coreutils package. * * (c) KokaKiwi <kokakiwi@kokakiwi.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.22 */ // Allow dead code here in order to keep all fields, constants here, for consistency. #![allow(dead_code)] extern crate getopts; extern crate libc; #[macro_use] extern crate uucore; use getopts::Options; use std::ffi::{CStr, CString}; use std::mem; use std::ptr; use uucore::utmpx::*; extern { fn getutxent() -> *const c_utmp; fn getutxid(ut: *const c_utmp) -> *const c_utmp; fn getutxline(ut: *const c_utmp) -> *const c_utmp; fn pututxline(ut: *const c_utmp) -> *const c_utmp; fn setutxent(); fn endutxent(); #[cfg(any(target_os = "macos", target_os = "linux"))] fn utmpxname(file: *const libc::c_char) -> libc::c_int; } #[cfg(target_os = "freebsd")] unsafe extern fn utmpxname(_file: *const libc::c_char) -> libc::c_int { 0 } static NAME: &'static str = "users"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!("{}", f), }; if matches.opt_present("help") { println!("{} {}", NAME, VERSION); println!(""); println!("Usage:"); println!(" {} [OPTION]... [FILE]", NAME); println!(""); println!("{}", opts.usage("Output who is currently logged in according to FILE.")); return 0; } if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } let filename = if matches.free.len() > 0 { matches.free[0].as_ref() } else { DEFAULT_FILE }; exec(filename); 0 } fn exec(filename: &str) { unsafe { utmpxname(CString::new(filename).unwrap().as_ptr()); } let mut users = vec!(); unsafe { setutxent(); loop { let line = getutxent(); if line == ptr::null() { break; } if (*line).ut_type == USER_PROCESS { let user = String::from_utf8_lossy(CStr::from_ptr(mem::transmute(&(*line).ut_user)).to_bytes()).to_string(); users.push(user); } } endutxent(); } if users.len() > 0 { users.sort(); println!("{}", users.join(" ")); } } #[allow(dead_code)] fn
() { std::process::exit(uumain(std::env::args().collect())); }
main
identifier_name
users.rs
#![crate_name = "users"] /* * This file is part of the uutils coreutils package. * * (c) KokaKiwi <kokakiwi@kokakiwi.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.22 */ // Allow dead code here in order to keep all fields, constants here, for consistency. #![allow(dead_code)] extern crate getopts; extern crate libc; #[macro_use] extern crate uucore; use getopts::Options; use std::ffi::{CStr, CString}; use std::mem; use std::ptr; use uucore::utmpx::*; extern { fn getutxent() -> *const c_utmp; fn getutxid(ut: *const c_utmp) -> *const c_utmp; fn getutxline(ut: *const c_utmp) -> *const c_utmp; fn pututxline(ut: *const c_utmp) -> *const c_utmp; fn setutxent(); fn endutxent(); #[cfg(any(target_os = "macos", target_os = "linux"))] fn utmpxname(file: *const libc::c_char) -> libc::c_int; } #[cfg(target_os = "freebsd")] unsafe extern fn utmpxname(_file: *const libc::c_char) -> libc::c_int { 0 } static NAME: &'static str = "users"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!("{}", f), }; if matches.opt_present("help") { println!("{} {}", NAME, VERSION); println!(""); println!("Usage:"); println!(" {} [OPTION]... [FILE]", NAME); println!(""); println!("{}", opts.usage("Output who is currently logged in according to FILE.")); return 0; } if matches.opt_present("version")
let filename = if matches.free.len() > 0 { matches.free[0].as_ref() } else { DEFAULT_FILE }; exec(filename); 0 } fn exec(filename: &str) { unsafe { utmpxname(CString::new(filename).unwrap().as_ptr()); } let mut users = vec!(); unsafe { setutxent(); loop { let line = getutxent(); if line == ptr::null() { break; } if (*line).ut_type == USER_PROCESS { let user = String::from_utf8_lossy(CStr::from_ptr(mem::transmute(&(*line).ut_user)).to_bytes()).to_string(); users.push(user); } } endutxent(); } if users.len() > 0 { users.sort(); println!("{}", users.join(" ")); } } #[allow(dead_code)] fn main() { std::process::exit(uumain(std::env::args().collect())); }
{ println!("{} {}", NAME, VERSION); return 0; }
conditional_block
users.rs
#![crate_name = "users"] /* * This file is part of the uutils coreutils package. * * (c) KokaKiwi <kokakiwi@kokakiwi.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.22 */ // Allow dead code here in order to keep all fields, constants here, for consistency. #![allow(dead_code)]
extern crate libc; #[macro_use] extern crate uucore; use getopts::Options; use std::ffi::{CStr, CString}; use std::mem; use std::ptr; use uucore::utmpx::*; extern { fn getutxent() -> *const c_utmp; fn getutxid(ut: *const c_utmp) -> *const c_utmp; fn getutxline(ut: *const c_utmp) -> *const c_utmp; fn pututxline(ut: *const c_utmp) -> *const c_utmp; fn setutxent(); fn endutxent(); #[cfg(any(target_os = "macos", target_os = "linux"))] fn utmpxname(file: *const libc::c_char) -> libc::c_int; } #[cfg(target_os = "freebsd")] unsafe extern fn utmpxname(_file: *const libc::c_char) -> libc::c_int { 0 } static NAME: &'static str = "users"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!("{}", f), }; if matches.opt_present("help") { println!("{} {}", NAME, VERSION); println!(""); println!("Usage:"); println!(" {} [OPTION]... [FILE]", NAME); println!(""); println!("{}", opts.usage("Output who is currently logged in according to FILE.")); return 0; } if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } let filename = if matches.free.len() > 0 { matches.free[0].as_ref() } else { DEFAULT_FILE }; exec(filename); 0 } fn exec(filename: &str) { unsafe { utmpxname(CString::new(filename).unwrap().as_ptr()); } let mut users = vec!(); unsafe { setutxent(); loop { let line = getutxent(); if line == ptr::null() { break; } if (*line).ut_type == USER_PROCESS { let user = String::from_utf8_lossy(CStr::from_ptr(mem::transmute(&(*line).ut_user)).to_bytes()).to_string(); users.push(user); } } endutxent(); } if users.len() > 0 { users.sort(); println!("{}", users.join(" ")); } } #[allow(dead_code)] fn main() { std::process::exit(uumain(std::env::args().collect())); }
extern crate getopts;
random_line_split
compat.py
"""Python 2.x/3.x compatibility tools""" import sys __all__ = ['geterror', 'long_', 'xrange_', 'ord_', 'unichr_', 'unicode_', 'raw_input_', 'as_bytes', 'as_unicode'] def geterror (): return sys.exc_info()[1] try: long_ = long except NameError: long_ = int try: xrange_ = xrange except NameError: xrange_ = range def get_BytesIO(): try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO return BytesIO def get_StringIO(): try: from cStringIO import StringIO except ImportError: from io import StringIO return StringIO def ord_(o): try: return ord(o) except TypeError: return o try: unichr_ = unichr except NameError: unichr_ = chr try: unicode_ = unicode except NameError: unicode_ = str try: bytes_ = bytes except NameError: bytes_ = str try: raw_input_ = raw_input except NameError: raw_input_ = input if sys.platform == 'win32': filesystem_errors = "replace" elif sys.version_info >= (3, 0, 0):
else: filesystem_errors = "strict" def filesystem_encode(u): return u.encode(sys.getfilesystemencoding(), filesystem_errors) # Represent escaped bytes and strings in a portable way. # # as_bytes: Allow a Python 3.x string to represent a bytes object. # e.g.: as_bytes("a\x01\b") == b"a\x01b" # Python 3.x # as_bytes("a\x01\b") == "a\x01b" # Python 2.x # as_unicode: Allow a Python "r" string to represent a unicode string. # e.g.: as_unicode(r"Bo\u00F6tes") == u"Bo\u00F6tes" # Python 2.x # as_unicode(r"Bo\u00F6tes") == "Bo\u00F6tes" # Python 3.x try: unicode def as_bytes(string): """ '<binary literal>' => '<binary literal>' """ return string def as_unicode(rstring): """ r'<Unicode literal>' => u'<Unicode literal>' """ return rstring.decode('unicode_escape', 'strict') except NameError: def as_bytes(string): """ '<binary literal>' => b'<binary literal>' """ return string.encode('latin-1', 'strict') def as_unicode(rstring): """ r'<Unicode literal>' => '<Unicode literal>' """ return rstring.encode('ascii', 'strict').decode('unicode_escape', 'stict') # Include a next compatible function for Python versions < 2.6 try: next_ = next except NameError: def next_(i, *args): try: return i.next() except StopIteration: if args: return args[0] raise # itertools.imap is missing in 3.x try: import itertools.imap as imap_ except ImportError: imap_ = map
filesystem_errors = "surrogateescape"
conditional_block
compat.py
"""Python 2.x/3.x compatibility tools""" import sys __all__ = ['geterror', 'long_', 'xrange_', 'ord_', 'unichr_', 'unicode_', 'raw_input_', 'as_bytes', 'as_unicode'] def geterror (): return sys.exc_info()[1] try: long_ = long except NameError: long_ = int try: xrange_ = xrange except NameError: xrange_ = range def
(): try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO return BytesIO def get_StringIO(): try: from cStringIO import StringIO except ImportError: from io import StringIO return StringIO def ord_(o): try: return ord(o) except TypeError: return o try: unichr_ = unichr except NameError: unichr_ = chr try: unicode_ = unicode except NameError: unicode_ = str try: bytes_ = bytes except NameError: bytes_ = str try: raw_input_ = raw_input except NameError: raw_input_ = input if sys.platform == 'win32': filesystem_errors = "replace" elif sys.version_info >= (3, 0, 0): filesystem_errors = "surrogateescape" else: filesystem_errors = "strict" def filesystem_encode(u): return u.encode(sys.getfilesystemencoding(), filesystem_errors) # Represent escaped bytes and strings in a portable way. # # as_bytes: Allow a Python 3.x string to represent a bytes object. # e.g.: as_bytes("a\x01\b") == b"a\x01b" # Python 3.x # as_bytes("a\x01\b") == "a\x01b" # Python 2.x # as_unicode: Allow a Python "r" string to represent a unicode string. # e.g.: as_unicode(r"Bo\u00F6tes") == u"Bo\u00F6tes" # Python 2.x # as_unicode(r"Bo\u00F6tes") == "Bo\u00F6tes" # Python 3.x try: unicode def as_bytes(string): """ '<binary literal>' => '<binary literal>' """ return string def as_unicode(rstring): """ r'<Unicode literal>' => u'<Unicode literal>' """ return rstring.decode('unicode_escape', 'strict') except NameError: def as_bytes(string): """ '<binary literal>' => b'<binary literal>' """ return string.encode('latin-1', 'strict') def as_unicode(rstring): """ r'<Unicode literal>' => '<Unicode literal>' """ return rstring.encode('ascii', 'strict').decode('unicode_escape', 'stict') # Include a next compatible function for Python versions < 2.6 try: next_ = next except NameError: def next_(i, *args): try: return i.next() except StopIteration: if args: return args[0] raise # itertools.imap is missing in 3.x try: import itertools.imap as imap_ except ImportError: imap_ = map
get_BytesIO
identifier_name
compat.py
"""Python 2.x/3.x compatibility tools""" import sys __all__ = ['geterror', 'long_', 'xrange_', 'ord_', 'unichr_', 'unicode_', 'raw_input_', 'as_bytes', 'as_unicode'] def geterror (): return sys.exc_info()[1] try: long_ = long except NameError: long_ = int try: xrange_ = xrange except NameError: xrange_ = range def get_BytesIO(): try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO return BytesIO def get_StringIO(): try: from cStringIO import StringIO except ImportError: from io import StringIO return StringIO def ord_(o): try: return ord(o) except TypeError: return o try: unichr_ = unichr except NameError: unichr_ = chr try: unicode_ = unicode except NameError: unicode_ = str try: bytes_ = bytes except NameError: bytes_ = str try: raw_input_ = raw_input except NameError: raw_input_ = input if sys.platform == 'win32': filesystem_errors = "replace" elif sys.version_info >= (3, 0, 0): filesystem_errors = "surrogateescape"
return u.encode(sys.getfilesystemencoding(), filesystem_errors) # Represent escaped bytes and strings in a portable way. # # as_bytes: Allow a Python 3.x string to represent a bytes object. # e.g.: as_bytes("a\x01\b") == b"a\x01b" # Python 3.x # as_bytes("a\x01\b") == "a\x01b" # Python 2.x # as_unicode: Allow a Python "r" string to represent a unicode string. # e.g.: as_unicode(r"Bo\u00F6tes") == u"Bo\u00F6tes" # Python 2.x # as_unicode(r"Bo\u00F6tes") == "Bo\u00F6tes" # Python 3.x try: unicode def as_bytes(string): """ '<binary literal>' => '<binary literal>' """ return string def as_unicode(rstring): """ r'<Unicode literal>' => u'<Unicode literal>' """ return rstring.decode('unicode_escape', 'strict') except NameError: def as_bytes(string): """ '<binary literal>' => b'<binary literal>' """ return string.encode('latin-1', 'strict') def as_unicode(rstring): """ r'<Unicode literal>' => '<Unicode literal>' """ return rstring.encode('ascii', 'strict').decode('unicode_escape', 'stict') # Include a next compatible function for Python versions < 2.6 try: next_ = next except NameError: def next_(i, *args): try: return i.next() except StopIteration: if args: return args[0] raise # itertools.imap is missing in 3.x try: import itertools.imap as imap_ except ImportError: imap_ = map
else: filesystem_errors = "strict" def filesystem_encode(u):
random_line_split
compat.py
"""Python 2.x/3.x compatibility tools""" import sys __all__ = ['geterror', 'long_', 'xrange_', 'ord_', 'unichr_', 'unicode_', 'raw_input_', 'as_bytes', 'as_unicode'] def geterror (): return sys.exc_info()[1] try: long_ = long except NameError: long_ = int try: xrange_ = xrange except NameError: xrange_ = range def get_BytesIO(): try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO return BytesIO def get_StringIO(): try: from cStringIO import StringIO except ImportError: from io import StringIO return StringIO def ord_(o): try: return ord(o) except TypeError: return o try: unichr_ = unichr except NameError: unichr_ = chr try: unicode_ = unicode except NameError: unicode_ = str try: bytes_ = bytes except NameError: bytes_ = str try: raw_input_ = raw_input except NameError: raw_input_ = input if sys.platform == 'win32': filesystem_errors = "replace" elif sys.version_info >= (3, 0, 0): filesystem_errors = "surrogateescape" else: filesystem_errors = "strict" def filesystem_encode(u): return u.encode(sys.getfilesystemencoding(), filesystem_errors) # Represent escaped bytes and strings in a portable way. # # as_bytes: Allow a Python 3.x string to represent a bytes object. # e.g.: as_bytes("a\x01\b") == b"a\x01b" # Python 3.x # as_bytes("a\x01\b") == "a\x01b" # Python 2.x # as_unicode: Allow a Python "r" string to represent a unicode string. # e.g.: as_unicode(r"Bo\u00F6tes") == u"Bo\u00F6tes" # Python 2.x # as_unicode(r"Bo\u00F6tes") == "Bo\u00F6tes" # Python 3.x try: unicode def as_bytes(string): """ '<binary literal>' => '<binary literal>' """ return string def as_unicode(rstring): """ r'<Unicode literal>' => u'<Unicode literal>' """ return rstring.decode('unicode_escape', 'strict') except NameError: def as_bytes(string):
def as_unicode(rstring): """ r'<Unicode literal>' => '<Unicode literal>' """ return rstring.encode('ascii', 'strict').decode('unicode_escape', 'stict') # Include a next compatible function for Python versions < 2.6 try: next_ = next except NameError: def next_(i, *args): try: return i.next() except StopIteration: if args: return args[0] raise # itertools.imap is missing in 3.x try: import itertools.imap as imap_ except ImportError: imap_ = map
""" '<binary literal>' => b'<binary literal>' """ return string.encode('latin-1', 'strict')
identifier_body
cmd_isready_test.rs
// Raven is a high performance UCI chess engine // Copyright (C) 2015-2015 Nam Pham // // 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 super::super::types::*; #[test] fn test_create_good_isready_command() { let r = Command::parse("isready"); assert!(r.is_ok()); let cmd = r.ok().unwrap(); assert!(cmd == Command::ISREADY); } #[test] fn test_create_good_isready_command_with_spaces() { let r = Command::parse(" isready "); assert!(r.is_ok()); let cmd = r.ok().unwrap(); assert!(cmd == Command::ISREADY); } #[test] fn test_create_bad_isready_command() { let r = Command::parse("nonexistence"); assert!(r.is_err()); } #[test] fn
() { let r = Command::parse("isready param1 param2"); assert!(r.is_err()); }
test_create_good_isready_command_but_with_extra_params
identifier_name
cmd_isready_test.rs
// Raven is a high performance UCI chess engine // Copyright (C) 2015-2015 Nam Pham // // 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 super::super::types::*; #[test] fn test_create_good_isready_command() { let r = Command::parse("isready"); assert!(r.is_ok()); let cmd = r.ok().unwrap(); assert!(cmd == Command::ISREADY); } #[test] fn test_create_good_isready_command_with_spaces() { let r = Command::parse(" isready "); assert!(r.is_ok()); let cmd = r.ok().unwrap(); assert!(cmd == Command::ISREADY); } #[test] fn test_create_bad_isready_command()
#[test] fn test_create_good_isready_command_but_with_extra_params() { let r = Command::parse("isready param1 param2"); assert!(r.is_err()); }
{ let r = Command::parse("nonexistence"); assert!(r.is_err()); }
identifier_body
cmd_isready_test.rs
// Raven is a high performance UCI chess engine // Copyright (C) 2015-2015 Nam Pham //
// // 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 super::super::types::*; #[test] fn test_create_good_isready_command() { let r = Command::parse("isready"); assert!(r.is_ok()); let cmd = r.ok().unwrap(); assert!(cmd == Command::ISREADY); } #[test] fn test_create_good_isready_command_with_spaces() { let r = Command::parse(" isready "); assert!(r.is_ok()); let cmd = r.ok().unwrap(); assert!(cmd == Command::ISREADY); } #[test] fn test_create_bad_isready_command() { let r = Command::parse("nonexistence"); assert!(r.is_err()); } #[test] fn test_create_good_isready_command_but_with_extra_params() { let r = Command::parse("isready param1 param2"); assert!(r.is_err()); }
// 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.
random_line_split
index.tsx
import React from 'react'; import { isEqual } from 'lodash'; import { Dispatch } from 'redux'; import { useSelector, useDispatch } from 'react-redux'; import { RouteComponentProps, withRouter } from 'react-router-dom'; import Popover from '@material-ui/core/Popover'; import { Button } from '@pluto_network/pluto-design-elements'; import ClickAwayListener from '@material-ui/core/ClickAwayListener'; import { setActiveFilterButton } from '../../actions/searchFilter'; import { ACTION_TYPES, SearchActions } from '../../actions/actionTypes'; import FilterButton, { FILTER_BUTTON_TYPE } from '../filterButton'; import JournalItem from '../journalFilterItem'; import { AppState } from '../../reducers'; import { trackSelectFilter } from '../../helpers/trackSelectFilter'; import makeNewFilterLink from '../../helpers/makeNewFilterLink'; import JournalFilterInput from '../journalFilterInput'; import { AggregationJournal } from '../../model/aggregation'; const useStyles = require('isomorphic-style-loader/useStyles'); const s = require('./journalFilterDropdown.scss'); type Props = RouteComponentProps; const JournalFilterDropdown: React.FC<Props> = ({ location, history }) => { useStyles(s); const dispatch = useDispatch<Dispatch<SearchActions>>(); const selectedJournalIds = useSelector((state: AppState) => state.searchFilterState.selectedJournalIds); const journalData = useSelector((state: AppState) => state.searchFilterState.journals); const isActive = useSelector( (state: AppState) => state.searchFilterState.activeButton === FILTER_BUTTON_TYPE.JOURNAL ); const anchorEl = React.useRef(null); const inputEl = React.useRef<HTMLInputElement | null>(null); const [isHintOpened, setIsHintOpened] = React.useState(false); const [lastSelectedJournals, setLastSelectedJournals] = React.useState(selectedJournalIds); const selectChanged = !isEqual(selectedJournalIds, lastSelectedJournals); React.useEffect( () => { if (!isActive) { setLastSelectedJournals(selectedJournalIds); } }, [isActive, selectedJournalIds] ); let buttonText = 'Any journal · conference'; if (selectedJournalIds.length === 1) { buttonText = `${selectedJournalIds.length} journal · conference`; } else if (selectedJournalIds.length > 1) { buttonText = `${selectedJournalIds.length} journals · conferences`; } const handleClickJournalItem = React.useCallback( (journalId: string) => { dispatch({ type: ACTION_TYPES.ARTICLE_SEARCH_SELECT_JOURNAL_FILTER_ITEM, payload: { journalId }, }); }, [dispatch] ); const journalList = journalData && journalData.map(journal => { return ( <JournalItem key={journal.id} journal={journal} checked={selectedJournalIds.includes(String(journal.id))} onClick={handleClickJournalItem} isHighlight={false} /> ); }); function handleSubmit() { dispatch(setActiveFilterButton(null)); if (selectChanged) { trackSelectFilter('JOURNAL', JSON.stringify(selectedJournalIds)); const link = makeNewFilterLink({ journal: selectedJournalIds }, location); history.push(link); } } return ( <div ref={anchorEl}> <FilterButton onClick={() => { if (isActive) { dispatch(setActiveFilterButton(null)); } else { dispatch(setActiveFilterButton(FILTER_BUTTON_TYPE.JOURNAL)); } }} content={buttonText} isActive={isActive} selected={selectedJournalIds.length > 0} /> <Popover onClose={() => { if (!isActive) return; handleSubmit(); }} open={isActive} anchorEl={anchorEl.current} anchorOrigin={{ vertical: 'bottom', horizontal: 'left', }} transformOrigin={{ vertical: 'top', horizontal: 'left', }}
> <div className={s.filterWrapper}> <JournalFilterInput forwardedRef={inputEl} onSubmit={(journals: AggregationJournal[]) => { dispatch({ type: ACTION_TYPES.ARTICLE_SEARCH_ADD_JOURNAL_FILTER_ITEMS, payload: { journals } }); }} /> {isHintOpened && ( <ClickAwayListener onClickAway={() => { setIsHintOpened(false); }} > <div className={s.hint}>Search journal or conference here</div> </ClickAwayListener> )} </div> <div className={s.content}> <div className={s.journalListWrapper}> <div className={s.listHeader}> <label className={s.journalLabel}>Journal or Conference name</label> <label className={s.IFLabel}>Impact Factor</label> <label className={s.countLabel}>Count</label> </div> {journalList} <div className={s.searchInfo}> <span>{`Couldn't find any journal? `}</span> <button onClick={() => { if (!inputEl.current) return; setIsHintOpened(true); inputEl.current.focus(); }} className={s.searchFocusButton} > Search more journals or conferences! </button> </div> </div> <div className={s.controlBtnsWrapper}> <Button elementType="button" aria-label="Clear journal filter button" variant="text" color="gray" onClick={() => { dispatch({ type: ACTION_TYPES.ARTICLE_SEARCH_CLEAR_JOURNAL_FILTER }); }} > <span>Clear</span> </Button> <Button elementType="button" aria-label="Apply journal filter button" variant="text" color="blue" onClick={handleSubmit} > <span>Apply</span> </Button> </div> </div> </Popover> </div> ); }; export default withRouter(JournalFilterDropdown);
elevation={0} transitionDuration={150} classes={{ paper: s.dropBoxWrapper, }}
random_line_split
single-line-if-else.rs
// rustfmt-single_line_if_else_max_width: 100 // Format if-else expressions on a single line, when possible.
fn main() { let a = if 1 > 2 { unreachable!() } else { 10 }; let a = if x { 1 } else if y { 2 } else { 3 }; let b = if cond() { 5 } else { // Brief comment. 10 }; let c = if cond() { statement(); 5 } else { 10 }; let d = if let Some(val) = turbo { "cool" } else { "beans" }; if cond() { statement(); } else { other_statement(); } if true { do_something() } let x = if veeeeeeeeery_loooooong_condition() { aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa } else { bbbbbbbbbb }; let x = if veeeeeeeeery_loooooong_condition() { aaaaaaaaaaaaaaaaaaaaaaaaa } else { bbbbbbbbbb }; funk(if test() { 1 } else { 2 }, arg2); }
random_line_split
single-line-if-else.rs
// rustfmt-single_line_if_else_max_width: 100 // Format if-else expressions on a single line, when possible. fn main()
{ let a = if 1 > 2 { unreachable!() } else { 10 }; let a = if x { 1 } else if y { 2 } else { 3 }; let b = if cond() { 5 } else { // Brief comment. 10 }; let c = if cond() { statement(); 5 } else { 10 }; let d = if let Some(val) = turbo { "cool" } else { "beans" }; if cond() { statement(); } else { other_statement(); } if true { do_something() } let x = if veeeeeeeeery_loooooong_condition() { aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa } else { bbbbbbbbbb }; let x = if veeeeeeeeery_loooooong_condition() { aaaaaaaaaaaaaaaaaaaaaaaaa } else { bbbbbbbbbb }; funk(if test() { 1 } else { 2 }, arg2); }
identifier_body
single-line-if-else.rs
// rustfmt-single_line_if_else_max_width: 100 // Format if-else expressions on a single line, when possible. fn
() { let a = if 1 > 2 { unreachable!() } else { 10 }; let a = if x { 1 } else if y { 2 } else { 3 }; let b = if cond() { 5 } else { // Brief comment. 10 }; let c = if cond() { statement(); 5 } else { 10 }; let d = if let Some(val) = turbo { "cool" } else { "beans" }; if cond() { statement(); } else { other_statement(); } if true { do_something() } let x = if veeeeeeeeery_loooooong_condition() { aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa } else { bbbbbbbbbb }; let x = if veeeeeeeeery_loooooong_condition() { aaaaaaaaaaaaaaaaaaaaaaaaa } else { bbbbbbbbbb }; funk(if test() { 1 } else { 2 }, arg2); }
main
identifier_name
single-line-if-else.rs
// rustfmt-single_line_if_else_max_width: 100 // Format if-else expressions on a single line, when possible. fn main() { let a = if 1 > 2 { unreachable!() } else { 10 }; let a = if x { 1 } else if y
else { 3 }; let b = if cond() { 5 } else { // Brief comment. 10 }; let c = if cond() { statement(); 5 } else { 10 }; let d = if let Some(val) = turbo { "cool" } else { "beans" }; if cond() { statement(); } else { other_statement(); } if true { do_something() } let x = if veeeeeeeeery_loooooong_condition() { aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa } else { bbbbbbbbbb }; let x = if veeeeeeeeery_loooooong_condition() { aaaaaaaaaaaaaaaaaaaaaaaaa } else { bbbbbbbbbb }; funk(if test() { 1 } else { 2 }, arg2); }
{ 2 }
conditional_block
version.py
from __future__ import unicode_literals import datetime import os import subprocess from django.utils.lru_cache import lru_cache def get_version(version=None): "Returns a PEP 386-compliant version number from VERSION." version = get_complete_version(version) # Now build the two parts of the version number: # major = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha, beta and rc releases major = get_major_version(version) sub = '' if version[3] == 'alpha' and version[4] == 0: git_changeset = get_git_changeset() if git_changeset: sub = '.dev%s' % git_changeset elif version[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} sub = mapping[version[3]] + str(version[4]) return str(major + sub) def get_major_version(version=None): "Returns major version from VERSION." version = get_complete_version(version) parts = 2 if version[2] == 0 else 3 major = '.'.join(str(x) for x in version[:parts]) return major def get_complete_version(version=None): """Returns a tuple of the django version. If version argument is non-empty, then checks for correctness of the tuple provided. """ if version is None: from django import VERSION as version else: assert len(version) == 5 assert version[3] in ('alpha', 'beta', 'rc', 'final') return version @lru_cache() def get_git_changeset():
"""Returns a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers. """ repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=repo_dir, universal_newlines=True) timestamp = git_log.communicate()[0] try: timestamp = datetime.datetime.utcfromtimestamp(int(timestamp)) except ValueError: return None return timestamp.strftime('%Y%m%d%H%M%S')
identifier_body
version.py
from __future__ import unicode_literals import datetime import os import subprocess from django.utils.lru_cache import lru_cache def get_version(version=None): "Returns a PEP 386-compliant version number from VERSION." version = get_complete_version(version) # Now build the two parts of the version number: # major = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha, beta and rc releases major = get_major_version(version) sub = '' if version[3] == 'alpha' and version[4] == 0: git_changeset = get_git_changeset() if git_changeset:
elif version[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} sub = mapping[version[3]] + str(version[4]) return str(major + sub) def get_major_version(version=None): "Returns major version from VERSION." version = get_complete_version(version) parts = 2 if version[2] == 0 else 3 major = '.'.join(str(x) for x in version[:parts]) return major def get_complete_version(version=None): """Returns a tuple of the django version. If version argument is non-empty, then checks for correctness of the tuple provided. """ if version is None: from django import VERSION as version else: assert len(version) == 5 assert version[3] in ('alpha', 'beta', 'rc', 'final') return version @lru_cache() def get_git_changeset(): """Returns a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers. """ repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=repo_dir, universal_newlines=True) timestamp = git_log.communicate()[0] try: timestamp = datetime.datetime.utcfromtimestamp(int(timestamp)) except ValueError: return None return timestamp.strftime('%Y%m%d%H%M%S')
sub = '.dev%s' % git_changeset
conditional_block
version.py
from __future__ import unicode_literals import datetime import os import subprocess from django.utils.lru_cache import lru_cache def get_version(version=None): "Returns a PEP 386-compliant version number from VERSION." version = get_complete_version(version) # Now build the two parts of the version number: # major = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha, beta and rc releases major = get_major_version(version) sub = '' if version[3] == 'alpha' and version[4] == 0: git_changeset = get_git_changeset() if git_changeset: sub = '.dev%s' % git_changeset elif version[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} sub = mapping[version[3]] + str(version[4]) return str(major + sub) def get_major_version(version=None): "Returns major version from VERSION." version = get_complete_version(version) parts = 2 if version[2] == 0 else 3 major = '.'.join(str(x) for x in version[:parts]) return major def
(version=None): """Returns a tuple of the django version. If version argument is non-empty, then checks for correctness of the tuple provided. """ if version is None: from django import VERSION as version else: assert len(version) == 5 assert version[3] in ('alpha', 'beta', 'rc', 'final') return version @lru_cache() def get_git_changeset(): """Returns a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers. """ repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=repo_dir, universal_newlines=True) timestamp = git_log.communicate()[0] try: timestamp = datetime.datetime.utcfromtimestamp(int(timestamp)) except ValueError: return None return timestamp.strftime('%Y%m%d%H%M%S')
get_complete_version
identifier_name
version.py
from __future__ import unicode_literals import datetime import os import subprocess from django.utils.lru_cache import lru_cache def get_version(version=None): "Returns a PEP 386-compliant version number from VERSION." version = get_complete_version(version) # Now build the two parts of the version number: # major = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha, beta and rc releases major = get_major_version(version) sub = '' if version[3] == 'alpha' and version[4] == 0: git_changeset = get_git_changeset() if git_changeset: sub = '.dev%s' % git_changeset elif version[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} sub = mapping[version[3]] + str(version[4]) return str(major + sub) def get_major_version(version=None): "Returns major version from VERSION." version = get_complete_version(version) parts = 2 if version[2] == 0 else 3 major = '.'.join(str(x) for x in version[:parts]) return major
def get_complete_version(version=None): """Returns a tuple of the django version. If version argument is non-empty, then checks for correctness of the tuple provided. """ if version is None: from django import VERSION as version else: assert len(version) == 5 assert version[3] in ('alpha', 'beta', 'rc', 'final') return version @lru_cache() def get_git_changeset(): """Returns a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers. """ repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=repo_dir, universal_newlines=True) timestamp = git_log.communicate()[0] try: timestamp = datetime.datetime.utcfromtimestamp(int(timestamp)) except ValueError: return None return timestamp.strftime('%Y%m%d%H%M%S')
random_line_split
invalid-punct-ident-2.rs
// aux-build:invalid-punct-ident.rs // rustc-env:RUST_BACKTRACE=0 // FIXME https://github.com/rust-lang/rust/issues/59998 // normalize-stderr-test "thread.*panicked.*proc_macro_server.rs.*\n" -> "" // normalize-stderr-test "note:.*RUST_BACKTRACE=1.*\n" -> "" // normalize-stderr-test "\nerror: internal compiler error.*\n\n" -> "" // normalize-stderr-test "note:.*unexpectedly panicked.*\n\n" -> "" // normalize-stderr-test "note: we would appreciate a bug report.*\n\n" -> "" // normalize-stderr-test "note: compiler flags.*\n\n" -> "" // normalize-stderr-test "note: rustc.*running on.*\n\n" -> "" // normalize-stderr-test "query stack during panic:\n" -> "" // normalize-stderr-test "we're just showing a limited slice of the query stack\n" -> "" // normalize-stderr-test "end of query stack\n" -> "" #[macro_use] extern crate invalid_punct_ident; invalid_ident!(); //~ ERROR proc macro panicked fn main()
{}
identifier_body
invalid-punct-ident-2.rs
// aux-build:invalid-punct-ident.rs // rustc-env:RUST_BACKTRACE=0 // FIXME https://github.com/rust-lang/rust/issues/59998 // normalize-stderr-test "thread.*panicked.*proc_macro_server.rs.*\n" -> "" // normalize-stderr-test "note:.*RUST_BACKTRACE=1.*\n" -> "" // normalize-stderr-test "\nerror: internal compiler error.*\n\n" -> "" // normalize-stderr-test "note:.*unexpectedly panicked.*\n\n" -> "" // normalize-stderr-test "note: we would appreciate a bug report.*\n\n" -> "" // normalize-stderr-test "note: compiler flags.*\n\n" -> "" // normalize-stderr-test "note: rustc.*running on.*\n\n" -> "" // normalize-stderr-test "query stack during panic:\n" -> "" // normalize-stderr-test "we're just showing a limited slice of the query stack\n" -> "" // normalize-stderr-test "end of query stack\n" -> "" #[macro_use] extern crate invalid_punct_ident; invalid_ident!(); //~ ERROR proc macro panicked fn
() {}
main
identifier_name
invalid-punct-ident-2.rs
// aux-build:invalid-punct-ident.rs // rustc-env:RUST_BACKTRACE=0 // FIXME https://github.com/rust-lang/rust/issues/59998 // normalize-stderr-test "thread.*panicked.*proc_macro_server.rs.*\n" -> "" // normalize-stderr-test "note:.*RUST_BACKTRACE=1.*\n" -> "" // normalize-stderr-test "\nerror: internal compiler error.*\n\n" -> "" // normalize-stderr-test "note:.*unexpectedly panicked.*\n\n" -> "" // normalize-stderr-test "note: we would appreciate a bug report.*\n\n" -> "" // normalize-stderr-test "note: compiler flags.*\n\n" -> ""
// normalize-stderr-test "end of query stack\n" -> "" #[macro_use] extern crate invalid_punct_ident; invalid_ident!(); //~ ERROR proc macro panicked fn main() {}
// normalize-stderr-test "note: rustc.*running on.*\n\n" -> "" // normalize-stderr-test "query stack during panic:\n" -> "" // normalize-stderr-test "we're just showing a limited slice of the query stack\n" -> ""
random_line_split
sql-meta-provider.js
'use babel'; import utils from '../utils'; class SQLMetaProvider { constructor() { this.selector = '.source.sql, .source.pgsql'; this.disableForSelector = '.source.sql .string, .source.sql .comment' this.filterSuggestions = true; atom.config.observe( // called immediately and on update 'autocomplete-plus.minimumWordLength', (newValue) => this.minimumWordLength = newValue ) } getSchemaNames(editor, search) { let items = editor.dataAtomSchemata || []; if (items.length == 0) return []; return items.map((item) => { return { text: item.name, rightLabelHTML: `<span class="data-atom autocomplete"></span>${item.type}` }; }); } getTableNames(editor, tableSearch, schema) { let tables = editor.dataAtomTables || []; if (tables.length == 0) return []; let results = tables.filter((table) => { if (schema) return table.schemaName === schema; else return true; }); return results.map((table) => { return { text: table.name, displayText: (schema || table.schemaName === editor.defaultSchema) ? table.name : table.schemaName + '.' + table.name, rightLabelHTML: `<span class="data-atom autocomplete autocomplete-tbl"></span>${table.type}` }; }); } getColumnNames(editor, columnSearch, objectName) { let columns = editor.dataAtomColumns || []; if (columns.length == 0) return []; let valid = columns.filter((col) => { if (objectName) return col.tableName === objectName; else return true; }); return valid.map((col) => { return { text: col.name, rightLabelHTML: '<span class="data-atom autocomplete autocomplete-col"></span>Column', leftLabel: col.type || col.udt }; }); } getAliasedObject(editor, lastIdentifier) { let query = editor.getBuffer().getTextInRange(utils.getRangeForQueryAtCursor(editor)); let matches = query.match(new RegExp('([\\w0-9]*)\\s*(?:AS)?\\s*' + lastIdentifier + '[\\s;]', 'i')); if (matches) { return matches[matches.length - 1]; } else { return null; } } getPrefix(editor, bufferPosition) { let line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition]); let matches = line.match(/[\w\.]+$/); if (matches) { return matches[0] || ''; } else { return ''; } } getSuggestions({editor, bufferPosition, scopeDescriptor}) { return new Promise(resolve => { let prefix = this.getPrefix(editor, bufferPosition); let identifiers = prefix.split('.'); let identsLength = identifiers.length; let results = []; let lastIdentifier = (identsLength > 1) && identifiers[identsLength - 2]; let search = identifiers[identsLength - 1]; if (search.length < this.minimumWordLength) return []; results = this.getColumnNames(editor, search, lastIdentifier).concat(this.getTableNames(editor, search, lastIdentifier)); if (!lastIdentifier) results = results.concat(this.getSchemaNames(editor, search)); // If there are no results, check for alias if (!results.length) { let tableName = this.getAliasedObject(editor, lastIdentifier); if (tableName)
} resolve(results); }); } } export default new SQLMetaProvider();
{ // Get by matched alias table results = this.getColumnNames(editor, search, tableName); }
conditional_block
sql-meta-provider.js
'use babel'; import utils from '../utils'; class SQLMetaProvider { constructor() { this.selector = '.source.sql, .source.pgsql'; this.disableForSelector = '.source.sql .string, .source.sql .comment' this.filterSuggestions = true; atom.config.observe( // called immediately and on update 'autocomplete-plus.minimumWordLength', (newValue) => this.minimumWordLength = newValue ) } getSchemaNames(editor, search) { let items = editor.dataAtomSchemata || []; if (items.length == 0) return []; return items.map((item) => { return { text: item.name, rightLabelHTML: `<span class="data-atom autocomplete"></span>${item.type}` }; }); } getTableNames(editor, tableSearch, schema) { let tables = editor.dataAtomTables || []; if (tables.length == 0) return []; let results = tables.filter((table) => { if (schema) return table.schemaName === schema; else return true; }); return results.map((table) => { return { text: table.name, displayText: (schema || table.schemaName === editor.defaultSchema) ? table.name : table.schemaName + '.' + table.name, rightLabelHTML: `<span class="data-atom autocomplete autocomplete-tbl"></span>${table.type}` };
} getColumnNames(editor, columnSearch, objectName) { let columns = editor.dataAtomColumns || []; if (columns.length == 0) return []; let valid = columns.filter((col) => { if (objectName) return col.tableName === objectName; else return true; }); return valid.map((col) => { return { text: col.name, rightLabelHTML: '<span class="data-atom autocomplete autocomplete-col"></span>Column', leftLabel: col.type || col.udt }; }); } getAliasedObject(editor, lastIdentifier) { let query = editor.getBuffer().getTextInRange(utils.getRangeForQueryAtCursor(editor)); let matches = query.match(new RegExp('([\\w0-9]*)\\s*(?:AS)?\\s*' + lastIdentifier + '[\\s;]', 'i')); if (matches) { return matches[matches.length - 1]; } else { return null; } } getPrefix(editor, bufferPosition) { let line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition]); let matches = line.match(/[\w\.]+$/); if (matches) { return matches[0] || ''; } else { return ''; } } getSuggestions({editor, bufferPosition, scopeDescriptor}) { return new Promise(resolve => { let prefix = this.getPrefix(editor, bufferPosition); let identifiers = prefix.split('.'); let identsLength = identifiers.length; let results = []; let lastIdentifier = (identsLength > 1) && identifiers[identsLength - 2]; let search = identifiers[identsLength - 1]; if (search.length < this.minimumWordLength) return []; results = this.getColumnNames(editor, search, lastIdentifier).concat(this.getTableNames(editor, search, lastIdentifier)); if (!lastIdentifier) results = results.concat(this.getSchemaNames(editor, search)); // If there are no results, check for alias if (!results.length) { let tableName = this.getAliasedObject(editor, lastIdentifier); if (tableName) { // Get by matched alias table results = this.getColumnNames(editor, search, tableName); } } resolve(results); }); } } export default new SQLMetaProvider();
});
random_line_split
sql-meta-provider.js
'use babel'; import utils from '../utils'; class SQLMetaProvider { constructor() { this.selector = '.source.sql, .source.pgsql'; this.disableForSelector = '.source.sql .string, .source.sql .comment' this.filterSuggestions = true; atom.config.observe( // called immediately and on update 'autocomplete-plus.minimumWordLength', (newValue) => this.minimumWordLength = newValue ) }
(editor, search) { let items = editor.dataAtomSchemata || []; if (items.length == 0) return []; return items.map((item) => { return { text: item.name, rightLabelHTML: `<span class="data-atom autocomplete"></span>${item.type}` }; }); } getTableNames(editor, tableSearch, schema) { let tables = editor.dataAtomTables || []; if (tables.length == 0) return []; let results = tables.filter((table) => { if (schema) return table.schemaName === schema; else return true; }); return results.map((table) => { return { text: table.name, displayText: (schema || table.schemaName === editor.defaultSchema) ? table.name : table.schemaName + '.' + table.name, rightLabelHTML: `<span class="data-atom autocomplete autocomplete-tbl"></span>${table.type}` }; }); } getColumnNames(editor, columnSearch, objectName) { let columns = editor.dataAtomColumns || []; if (columns.length == 0) return []; let valid = columns.filter((col) => { if (objectName) return col.tableName === objectName; else return true; }); return valid.map((col) => { return { text: col.name, rightLabelHTML: '<span class="data-atom autocomplete autocomplete-col"></span>Column', leftLabel: col.type || col.udt }; }); } getAliasedObject(editor, lastIdentifier) { let query = editor.getBuffer().getTextInRange(utils.getRangeForQueryAtCursor(editor)); let matches = query.match(new RegExp('([\\w0-9]*)\\s*(?:AS)?\\s*' + lastIdentifier + '[\\s;]', 'i')); if (matches) { return matches[matches.length - 1]; } else { return null; } } getPrefix(editor, bufferPosition) { let line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition]); let matches = line.match(/[\w\.]+$/); if (matches) { return matches[0] || ''; } else { return ''; } } getSuggestions({editor, bufferPosition, scopeDescriptor}) { return new Promise(resolve => { let prefix = this.getPrefix(editor, bufferPosition); let identifiers = prefix.split('.'); let identsLength = identifiers.length; let results = []; let lastIdentifier = (identsLength > 1) && identifiers[identsLength - 2]; let search = identifiers[identsLength - 1]; if (search.length < this.minimumWordLength) return []; results = this.getColumnNames(editor, search, lastIdentifier).concat(this.getTableNames(editor, search, lastIdentifier)); if (!lastIdentifier) results = results.concat(this.getSchemaNames(editor, search)); // If there are no results, check for alias if (!results.length) { let tableName = this.getAliasedObject(editor, lastIdentifier); if (tableName) { // Get by matched alias table results = this.getColumnNames(editor, search, tableName); } } resolve(results); }); } } export default new SQLMetaProvider();
getSchemaNames
identifier_name
model.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import math import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import Lasso from data.dbaccess import normalize from data.db import get_db_session, Pinkunhu2015 class LassoModel(object): """ 使用Lasso预测下一年人均年收入 """ def run(self): """ 运行 """ # 获取数据 X, Y = self._fetch_data() clf = self.get_classifier(X, Y) # 测试 X, Y = self._fetch_test_data() res = [] for item in range(11): hit_ratio = self.predict(clf, X, Y, item * 0.1) res.append([item * 0.1 * 100, hit_ratio * 100]) # 绘制误差与命中率的线性关系图 arr = np.array(res) plt.plot(arr[:, 0], arr[:, 1]) # 绘制线 plt.plot(arr[:, 0], arr[:, 1], 'ro') # 绘制点 plt.xlabel('误差率(%)') plt.ylabel('命中率(%)') plt.title('使用Lasso预测下一年人均年收入效果图') plt.show() def get_classifier(self, X, Y): """ 构建Lasso模型 :param X: 训练数据 :param Y: 训练数据结果 :return: 模型 """ clf = Lasso() clf.fit(X, Y) return clf def predict(self, clf, X, Y, deviation=0.1): """ 用当前的模型预测 :param clf: 模型 :param X: 测试数据 :param Y: 测试数据结果 :param deviation: 允许误差率 :return: 命中率 """ Y2 = clf.predict(X) total, hit = len(Y), 0 for idx, v in enumerate(Y2): if math.fabs(Y[idx] - v) <= math.fabs(Y[idx] * deviation): # 误差小于deviation,则认为预测准确 hit += 1 print 'Deviation: %d%%, Total: %d, Hit: %d, Precision: %.2f%%' % (100 * deviation, total, hit, 100.0*hit/total) # 用 镇雄县 的模型去预测 陆良县 的结果 # Deviation: 0%, Total: 40820, Hit: 0, Precision: 0.00% # Deviation: 10%, Total: 40820, Hit: 24513, Precision: 60.05% # Deviation: 20%, Total: 40820, Hit: 33011, Precision: 80.87% # Deviation: 30%, Total: 40820, Hit: 36230, Precision: 88.76% # Deviation: 40%, Total: 40820, Hit: 37379, Precision: 91.57% # Deviation: 50%, Total: 40820, Hit: 38048, Precision: 93.21% # Deviation: 60%, Total: 40820, Hit: 38511, Precision: 94.34% # Deviation: 70%, Total: 40820, Hit: 38830, Precision: 95.12% # Deviation: 80%, Total: 40820, Hit: 39077, Precision: 95.73% # Deviation: 90%, Total: 40820, Hit: 39282, Precision: 96.23% # Deviation: 100%, Total: 40820, Hit: 39429, Precision: 96.59% return hit * 1.0 / total def _fetch_data(self): """ 获取建模数据 """ session = get_db_session() objs = session.query(Pinkunhu2015).filter(Pinkunhu2015.county == '镇雄县', Pinkunhu2015.ny_person_income != -1).all() X, Y = [], [] for item in objs: col_list = [] for col in [ 'tv', 'washing_machine', 'fridge', 'reason', 'is_danger_house', 'is_back_poor', 'is_debt', 'standard', 'arable_land', 'debt_total', 'living_space', 'member_count', 'subsidy_total', 'wood_land', 'xin_nong_he_total', 'xin_yang_lao_total', 'call_number', 'bank_name', 'bank_number', 'help_plan' ]: normalized_value = normalize(col, getattr(item, col)) col_list.append(normalized_value)
Y.append(normalized_value) return X, Y def _fetch_test_data(self): """ 获取测试数据 """ session = get_db_session() objs = session.query(Pinkunhu2015).filter(Pinkunhu2015.county == '彝良县', Pinkunhu2015.ny_person_income != -1).all() X, Y = [], [] for item in objs: col_list = [] for col in [ 'tv', 'washing_machine', 'fridge', 'reason', 'is_danger_house', 'is_back_poor', 'is_debt', 'standard', 'arable_land', 'debt_total', 'living_space', 'member_count', 'subsidy_total', 'wood_land', 'xin_nong_he_total', 'xin_yang_lao_total', 'call_number', 'bank_name', 'bank_number', 'help_plan' ]: normalized_value = normalize(col, getattr(item, col)) col_list.append(normalized_value) X.append(col_list) normalized_value = normalize('ny_person_income', getattr(item, 'ny_person_income')) Y.append(normalized_value) return X, Y if __name__ == '__main__': m = LassoModel() m.run()
X.append(col_list) normalized_value = normalize('ny_person_income', getattr(item, 'ny_person_income'))
random_line_split
model.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import math import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import Lasso from data.dbaccess import normalize from data.db import get_db_session, Pinkunhu2015 class LassoModel(object): """ 使用Lasso预测下一年人均年收入 """ def run(self): """ 运行 """ # 获取数据 X, Y = self._fetch_data() clf = self.get_classifier(X, Y) # 测试 X, Y = self._fetch_test_data() res = [] for item in range(11): hit_ratio = self.predict(clf, X, Y, item * 0.1) res.append([item * 0.1 * 100, hit_ratio * 100]) # 绘制误差与命中率的线性关系图 arr = np.array(res) plt.plot(arr[:, 0], arr[:, 1]) # 绘制线 plt.plot(arr[:, 0], arr[:, 1], 'ro') # 绘制点 plt.xlabel('误差率(%)') plt.ylabel('命中率(%)') plt.title('使用Lasso预测下一年人均年收入效果图') plt.show() def get_classifier(self, X, Y): """ 构建Lasso模型 :param X: 训练数据 :param Y: 训练数据结果 :return: 模型 """ clf = Lasso() clf.fit(X, Y) return clf def predict(self, clf, X, Y, deviation=0.1): """ 用当前的模型预测 :param clf: 模型 :param X: 测试数据 :param Y: 测试数据结果 :param deviation: 允许误差率 :return: 命中率 """ Y2 = clf.predict(X) total, hit = len(Y), 0 for idx, v in enumerate(Y2): if math.fabs(Y[idx] - v) <= math.fabs(Y[idx] * deviation): # 误差小于deviation,则认为预测准确 hit += 1 print 'Deviation: %d%%, Total: %d, Hit: %d, Precision: %.2f%%' % (100 * deviation, total, hit, 100.0*hit/total) # 用 镇雄县 的模型去预测 陆良县 的结果 # Deviation: 0%, Total: 40820, Hit: 0, Precision: 0.00% # Deviation: 10%, Total: 40820, Hit: 24513, Precision: 60.05% # Deviation: 20%, Total: 40820, Hit: 33011, Precision: 80.87% # Deviation: 30%, Total: 40820, Hit: 36230, Precision: 88.76% # Deviation: 40%, Total: 40820, Hit: 37379, Precision: 91.57% # Deviation: 50%, Total: 40820, Hit: 38048, Precision: 93.21% # Deviation: 60%, Total: 40820, Hit: 38511, Precision: 94.34% # Deviation: 70%, Total: 40820, Hit: 38830, Precision: 95.12% # Deviation: 80%, Total: 40820, Hit: 39077, Precision: 95.73% # Deviation: 90%, Total: 40820, Hit: 39282, Precision: 96.23% # Deviation: 100%, Total: 40820, Hit: 39429, Precision: 96.59% return hit * 1.0 / total def _fetch_data(self): """ 获取建模数据 """ session = get_db_session() objs = session.query(Pinkunhu2015).filter(Pinkunhu2015.county == '镇雄县', Pinkunhu2015.ny_person_income != -1).all() X, Y = [], [] for item in objs: col_list = [] for col in [ 'tv', 'washing_machine', 'fridge', 'reason', 'is_danger_house', 'is_back_poor', 'is_debt', 'standard', 'arable_land', 'debt_total', 'living_space', 'member_count', 'subsidy_total', 'wood_land', 'xin_nong_he_total', 'xin_yang_lao_total', 'call_number', 'bank_name', 'bank_number', 'help_plan' ]: normalized_value = normalize(col, getattr(item, col)) col_list.append(normalized_value) X.append(col_list) normalized_value = normalize('ny_person_income', getattr(item, 'ny_person_income')) Y.append(normalized_value) retur
objs = session.query(Pinkunhu2015).filter(Pinkunhu2015.county == '彝良县', Pinkunhu2015.ny_person_income != -1).all() X, Y = [], [] for item in objs: col_list = [] for col in [ 'tv', 'washing_machine', 'fridge', 'reason', 'is_danger_house', 'is_back_poor', 'is_debt', 'standard', 'arable_land', 'debt_total', 'living_space', 'member_count', 'subsidy_total', 'wood_land', 'xin_nong_he_total', 'xin_yang_lao_total', 'call_number', 'bank_name', 'bank_number', 'help_plan' ]: normalized_value = normalize(col, getattr(item, col)) col_list.append(normalized_value) X.append(col_list) normalized_value = normalize('ny_person_income', getattr(item, 'ny_person_income')) Y.append(normalized_value) return X, Y if __name__ == '__main__': m = LassoModel() m.run()
n X, Y def _fetch_test_data(self): """ 获取测试数据 """ session = get_db_session()
conditional_block
model.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import math import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import Lasso from data.dbaccess import normalize from data.db import get_db_session, Pinkunhu2015 class LassoModel(object): """ 使用Lasso预测下一年人均年收入 """ def run(self): """ 运
"" # 获取数据 X, Y = self._fetch_data() clf = self.get_classifier(X, Y) # 测试 X, Y = self._fetch_test_data() res = [] for item in range(11): hit_ratio = self.predict(clf, X, Y, item * 0.1) res.append([item * 0.1 * 100, hit_ratio * 100]) # 绘制误差与命中率的线性关系图 arr = np.array(res) plt.plot(arr[:, 0], arr[:, 1]) # 绘制线 plt.plot(arr[:, 0], arr[:, 1], 'ro') # 绘制点 plt.xlabel('误差率(%)') plt.ylabel('命中率(%)') plt.title('使用Lasso预测下一年人均年收入效果图') plt.show() def get_classifier(self, X, Y): """ 构建Lasso模型 :param X: 训练数据 :param Y: 训练数据结果 :return: 模型 """ clf = Lasso() clf.fit(X, Y) return clf def predict(self, clf, X, Y, deviation=0.1): """ 用当前的模型预测 :param clf: 模型 :param X: 测试数据 :param Y: 测试数据结果 :param deviation: 允许误差率 :return: 命中率 """ Y2 = clf.predict(X) total, hit = len(Y), 0 for idx, v in enumerate(Y2): if math.fabs(Y[idx] - v) <= math.fabs(Y[idx] * deviation): # 误差小于deviation,则认为预测准确 hit += 1 print 'Deviation: %d%%, Total: %d, Hit: %d, Precision: %.2f%%' % (100 * deviation, total, hit, 100.0*hit/total) # 用 镇雄县 的模型去预测 陆良县 的结果 # Deviation: 0%, Total: 40820, Hit: 0, Precision: 0.00% # Deviation: 10%, Total: 40820, Hit: 24513, Precision: 60.05% # Deviation: 20%, Total: 40820, Hit: 33011, Precision: 80.87% # Deviation: 30%, Total: 40820, Hit: 36230, Precision: 88.76% # Deviation: 40%, Total: 40820, Hit: 37379, Precision: 91.57% # Deviation: 50%, Total: 40820, Hit: 38048, Precision: 93.21% # Deviation: 60%, Total: 40820, Hit: 38511, Precision: 94.34% # Deviation: 70%, Total: 40820, Hit: 38830, Precision: 95.12% # Deviation: 80%, Total: 40820, Hit: 39077, Precision: 95.73% # Deviation: 90%, Total: 40820, Hit: 39282, Precision: 96.23% # Deviation: 100%, Total: 40820, Hit: 39429, Precision: 96.59% return hit * 1.0 / total def _fetch_data(self): """ 获取建模数据 """ session = get_db_session() objs = session.query(Pinkunhu2015).filter(Pinkunhu2015.county == '镇雄县', Pinkunhu2015.ny_person_income != -1).all() X, Y = [], [] for item in objs: col_list = [] for col in [ 'tv', 'washing_machine', 'fridge', 'reason', 'is_danger_house', 'is_back_poor', 'is_debt', 'standard', 'arable_land', 'debt_total', 'living_space', 'member_count', 'subsidy_total', 'wood_land', 'xin_nong_he_total', 'xin_yang_lao_total', 'call_number', 'bank_name', 'bank_number', 'help_plan' ]: normalized_value = normalize(col, getattr(item, col)) col_list.append(normalized_value) X.append(col_list) normalized_value = normalize('ny_person_income', getattr(item, 'ny_person_income')) Y.append(normalized_value) return X, Y def _fetch_test_data(self): """ 获取测试数据 """ session = get_db_session() objs = session.query(Pinkunhu2015).filter(Pinkunhu2015.county == '彝良县', Pinkunhu2015.ny_person_income != -1).all() X, Y = [], [] for item in objs: col_list = [] for col in [ 'tv', 'washing_machine', 'fridge', 'reason', 'is_danger_house', 'is_back_poor', 'is_debt', 'standard', 'arable_land', 'debt_total', 'living_space', 'member_count', 'subsidy_total', 'wood_land', 'xin_nong_he_total', 'xin_yang_lao_total', 'call_number', 'bank_name', 'bank_number', 'help_plan' ]: normalized_value = normalize(col, getattr(item, col)) col_list.append(normalized_value) X.append(col_list) normalized_value = normalize('ny_person_income', getattr(item, 'ny_person_income')) Y.append(normalized_value) return X, Y if __name__ == '__main__': m = LassoModel() m.run()
行 "
identifier_name
model.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import math import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import Lasso from data.dbaccess import normalize from data.db import get_db_session, Pinkunhu2015 class LassoModel(object): """ 使用Lasso预测下一年人均年收入 """ def run(self): """ 运行 """ # 获取数据 X, Y = self._fetch_data() clf = self.get_classifier(X, Y) # 测试 X, Y = self._fetch_test_data() res = [] for item in range(11): hit_ratio = self.predict(clf, X, Y, item * 0.1) res.append([item * 0.1 * 100, hit_ratio * 100]) # 绘制误差与命中率的线性关系图 arr = np.array(res) plt.plot(arr[:, 0], arr[:, 1]) # 绘制线 plt.plot(arr[:, 0], arr[:, 1], 'ro') # 绘制点 plt.xlabel('误差率(%)') plt.ylabel('命中率(%)') plt.title('使用Lasso预测下一年人均年收入效果图') plt.show() def get_classifier(self, X, Y): """ 构建Lasso模型 :param X: 训练数据 :param Y: 训练数据结果 :return: 模型 """ clf = Lasso() clf.fit(X, Y) return clf def predict(self, clf, X, Y, deviation=0.1): """ 用当前的模型预测 :param clf: 模型 :param X: 测试数据 :param Y: 测试数据结果 :param deviation: 允许误差率 :return: 命中率 """
col_list = [] for col in [ 'tv', 'washing_machine', 'fridge', 'reason', 'is_danger_house', 'is_back_poor', 'is_debt', 'standard', 'arable_land', 'debt_total', 'living_space', 'member_count', 'subsidy_total', 'wood_land', 'xin_nong_he_total', 'xin_yang_lao_total', 'call_number', 'bank_name', 'bank_number', 'help_plan' ]: normalized_value = normalize(col, getattr(item, col)) col_list.append(normalized_value) X.append(col_list) normalized_value = normalize('ny_person_income', getattr(item, 'ny_person_income')) Y.append(normalized_value) return X, Y def _fetch_test_data(self): """ 获取测试数据 """ session = get_db_session() objs = session.query(Pinkunhu2015).filter(Pinkunhu2015.county == '彝良县', Pinkunhu2015.ny_person_income != -1).all() X, Y = [], [] for item in objs: col_list = [] for col in [ 'tv', 'washing_machine', 'fridge', 'reason', 'is_danger_house', 'is_back_poor', 'is_debt', 'standard', 'arable_land', 'debt_total', 'living_space', 'member_count', 'subsidy_total', 'wood_land', 'xin_nong_he_total', 'xin_yang_lao_total', 'call_number', 'bank_name', 'bank_number', 'help_plan' ]: normalized_value = normalize(col, getattr(item, col)) col_list.append(normalized_value) X.append(col_list) normalized_value = normalize('ny_person_income', getattr(item, 'ny_person_income')) Y.append(normalized_value) return X, Y if __name__ == '__main__': m = LassoModel() m.run()
Y2 = clf.predict(X) total, hit = len(Y), 0 for idx, v in enumerate(Y2): if math.fabs(Y[idx] - v) <= math.fabs(Y[idx] * deviation): # 误差小于deviation,则认为预测准确 hit += 1 print 'Deviation: %d%%, Total: %d, Hit: %d, Precision: %.2f%%' % (100 * deviation, total, hit, 100.0*hit/total) # 用 镇雄县 的模型去预测 陆良县 的结果 # Deviation: 0%, Total: 40820, Hit: 0, Precision: 0.00% # Deviation: 10%, Total: 40820, Hit: 24513, Precision: 60.05% # Deviation: 20%, Total: 40820, Hit: 33011, Precision: 80.87% # Deviation: 30%, Total: 40820, Hit: 36230, Precision: 88.76% # Deviation: 40%, Total: 40820, Hit: 37379, Precision: 91.57% # Deviation: 50%, Total: 40820, Hit: 38048, Precision: 93.21% # Deviation: 60%, Total: 40820, Hit: 38511, Precision: 94.34% # Deviation: 70%, Total: 40820, Hit: 38830, Precision: 95.12% # Deviation: 80%, Total: 40820, Hit: 39077, Precision: 95.73% # Deviation: 90%, Total: 40820, Hit: 39282, Precision: 96.23% # Deviation: 100%, Total: 40820, Hit: 39429, Precision: 96.59% return hit * 1.0 / total def _fetch_data(self): """ 获取建模数据 """ session = get_db_session() objs = session.query(Pinkunhu2015).filter(Pinkunhu2015.county == '镇雄县', Pinkunhu2015.ny_person_income != -1).all() X, Y = [], [] for item in objs:
identifier_body
filter_bodies.py
from __future__ import division import json import os import copy import collections import argparse import csv import neuroglancer import neuroglancer.cli import numpy as np class State(object): def __init__(self, path): self.path = path self.body_labels = collections.OrderedDict() def load(self): if os.path.exists(self.path): with open(self.path, 'r') as f: self.body_labels = collections.OrderedDict(json.load(f)) def save(self): tmp_path = self.path + '.tmp' with open(tmp_path, 'w') as f: f.write(json.dumps(self.body_labels.items())) os.rename(tmp_path, self.path) Body = collections.namedtuple('Body', ['segment_id', 'num_voxels', 'bbox_start', 'bbox_size']) class Tool(object): def __init__(self, state_path, bodies, labels, segmentation_url, image_url, num_to_prefetch): self.state = State(state_path) self.num_to_prefetch = num_to_prefetch self.viewer = neuroglancer.Viewer() self.bodies = bodies self.state.load() self.total_voxels = sum(x.num_voxels for x in bodies) self.cumulative_voxels = np.cumsum([x.num_voxels for x in bodies]) with self.viewer.txn() as s: s.layers['image'] = neuroglancer.ImageLayer(source=image_url) s.layers['segmentation'] = neuroglancer.SegmentationLayer(source=segmentation_url) s.show_slices = False s.concurrent_downloads = 256 s.gpu_memory_limit = 2 * 1024 * 1024 * 1024 s.layout = '3d' key_bindings = [ ['bracketleft', 'prev-index'], ['bracketright', 'next-index'], ['home', 'first-index'], ['end', 'last-index'], ['control+keys', 'save'], ] label_keys = ['keyd', 'keyf', 'keyg', 'keyh'] for label, label_key in zip(labels, label_keys): key_bindings.append([label_key, 'label-%s' % label]) def label_func(s, label=label): self.set_label(s, label) self.viewer.actions.add('label-%s' % label, label_func) self.viewer.actions.add('prev-index', self._prev_index) self.viewer.actions.add('next-index', self._next_index) self.viewer.actions.add('first-index', self._first_index) self.viewer.actions.add('last-index', self._last_index) self.viewer.actions.add('save', self.save) with self.viewer.config_state.txn() as s: for key, command in key_bindings: s.input_event_bindings.viewer[key] = command s.status_messages['help'] = ('KEYS: ' + ' | '.join('%s=%s' % (key, command) for key, command in key_bindings)) self.index = -1 self.set_index(self._find_one_after_last_labeled_index()) def _find_one_after_last_labeled_index(self): body_index = 0 while self.bodies[body_index].segment_id in self.state.body_labels: body_index += 1 return body_index def set_index(self, index): if index == self.index: return body = self.bodies[index] self.index = index def modify_state_for_body(s, body):
with self.viewer.txn() as s: modify_state_for_body(s, body) prefetch_states = [] for i in range(self.num_to_prefetch): prefetch_index = self.index + i + 1 if prefetch_index >= len(self.bodies): break prefetch_state = copy.deepcopy(self.viewer.state) prefetch_state.layout = '3d' modify_state_for_body(prefetch_state, self.bodies[prefetch_index]) prefetch_states.append(prefetch_state) with self.viewer.config_state.txn() as s: s.prefetch = [ neuroglancer.PrefetchState(state=prefetch_state, priority=-i) for i, prefetch_state in enumerate(prefetch_states) ] label = self.state.body_labels.get(body.segment_id, '') with self.viewer.config_state.txn() as s: s.status_messages['status'] = ( '[Segment %d/%d : %d/%d voxels labeled = %.3f fraction] label=%s' % (index, len(self.bodies), self.cumulative_voxels[index], self.total_voxels, self.cumulative_voxels[index] / self.total_voxels, label)) def save(self, s): self.state.save() def set_label(self, s, label): self.state.body_labels[self.bodies[self.index].segment_id] = label self.set_index(self.index + 1) def _first_index(self, s): self.set_index(0) def _last_index(self, s): self.set_index(max(0, self._find_one_after_last_labeled_index() - 1)) def _next_index(self, s): self.set_index(self.index + 1) def _prev_index(self, s): self.set_index(max(0, self.index - 1)) if __name__ == '__main__': ap = argparse.ArgumentParser() neuroglancer.cli.add_server_arguments(ap) ap.add_argument('--image-url', required=True, help='Neuroglancer data source URL for image') ap.add_argument('--segmentation-url', required=True, help='Neuroglancer data source URL for segmentation') ap.add_argument('--state', required=True, help='Path to proofreading state file') ap.add_argument('--bodies', required=True, help='Path to list of bodies to proofread') ap.add_argument('--labels', nargs='+', help='Labels to use') ap.add_argument('--prefetch', type=int, default=10, help='Number of bodies to prefetch') args = ap.parse_args() neuroglancer.cli.handle_server_arguments(args) bodies = [] with open(args.bodies, 'r') as f: csv_reader = csv.DictReader(f) for row in csv_reader: bodies.append( Body( segment_id=int(row['id']), num_voxels=int(row['num_voxels']), bbox_start=np.array([ int(row['bbox.start.x']), int(row['bbox.start.y']), int(row['bbox.start.z']) ], dtype=np.int64), bbox_size=np.array( [int(row['bbox.size.x']), int(row['bbox.size.y']), int(row['bbox.size.z'])], dtype=np.int64), )) tool = Tool( state_path=args.state, image_url=args.image_url, segmentation_url=args.segmentation_url, labels=args.labels, bodies=bodies, num_to_prefetch=args.prefetch, ) print(tool.viewer)
s.layers['segmentation'].segments = frozenset([body.segment_id]) s.voxel_coordinates = body.bbox_start + body.bbox_size // 2
identifier_body
filter_bodies.py
from __future__ import division import json import os import copy import collections import argparse import csv import neuroglancer import neuroglancer.cli import numpy as np class State(object): def __init__(self, path): self.path = path self.body_labels = collections.OrderedDict() def load(self): if os.path.exists(self.path):
def save(self): tmp_path = self.path + '.tmp' with open(tmp_path, 'w') as f: f.write(json.dumps(self.body_labels.items())) os.rename(tmp_path, self.path) Body = collections.namedtuple('Body', ['segment_id', 'num_voxels', 'bbox_start', 'bbox_size']) class Tool(object): def __init__(self, state_path, bodies, labels, segmentation_url, image_url, num_to_prefetch): self.state = State(state_path) self.num_to_prefetch = num_to_prefetch self.viewer = neuroglancer.Viewer() self.bodies = bodies self.state.load() self.total_voxels = sum(x.num_voxels for x in bodies) self.cumulative_voxels = np.cumsum([x.num_voxels for x in bodies]) with self.viewer.txn() as s: s.layers['image'] = neuroglancer.ImageLayer(source=image_url) s.layers['segmentation'] = neuroglancer.SegmentationLayer(source=segmentation_url) s.show_slices = False s.concurrent_downloads = 256 s.gpu_memory_limit = 2 * 1024 * 1024 * 1024 s.layout = '3d' key_bindings = [ ['bracketleft', 'prev-index'], ['bracketright', 'next-index'], ['home', 'first-index'], ['end', 'last-index'], ['control+keys', 'save'], ] label_keys = ['keyd', 'keyf', 'keyg', 'keyh'] for label, label_key in zip(labels, label_keys): key_bindings.append([label_key, 'label-%s' % label]) def label_func(s, label=label): self.set_label(s, label) self.viewer.actions.add('label-%s' % label, label_func) self.viewer.actions.add('prev-index', self._prev_index) self.viewer.actions.add('next-index', self._next_index) self.viewer.actions.add('first-index', self._first_index) self.viewer.actions.add('last-index', self._last_index) self.viewer.actions.add('save', self.save) with self.viewer.config_state.txn() as s: for key, command in key_bindings: s.input_event_bindings.viewer[key] = command s.status_messages['help'] = ('KEYS: ' + ' | '.join('%s=%s' % (key, command) for key, command in key_bindings)) self.index = -1 self.set_index(self._find_one_after_last_labeled_index()) def _find_one_after_last_labeled_index(self): body_index = 0 while self.bodies[body_index].segment_id in self.state.body_labels: body_index += 1 return body_index def set_index(self, index): if index == self.index: return body = self.bodies[index] self.index = index def modify_state_for_body(s, body): s.layers['segmentation'].segments = frozenset([body.segment_id]) s.voxel_coordinates = body.bbox_start + body.bbox_size // 2 with self.viewer.txn() as s: modify_state_for_body(s, body) prefetch_states = [] for i in range(self.num_to_prefetch): prefetch_index = self.index + i + 1 if prefetch_index >= len(self.bodies): break prefetch_state = copy.deepcopy(self.viewer.state) prefetch_state.layout = '3d' modify_state_for_body(prefetch_state, self.bodies[prefetch_index]) prefetch_states.append(prefetch_state) with self.viewer.config_state.txn() as s: s.prefetch = [ neuroglancer.PrefetchState(state=prefetch_state, priority=-i) for i, prefetch_state in enumerate(prefetch_states) ] label = self.state.body_labels.get(body.segment_id, '') with self.viewer.config_state.txn() as s: s.status_messages['status'] = ( '[Segment %d/%d : %d/%d voxels labeled = %.3f fraction] label=%s' % (index, len(self.bodies), self.cumulative_voxels[index], self.total_voxels, self.cumulative_voxels[index] / self.total_voxels, label)) def save(self, s): self.state.save() def set_label(self, s, label): self.state.body_labels[self.bodies[self.index].segment_id] = label self.set_index(self.index + 1) def _first_index(self, s): self.set_index(0) def _last_index(self, s): self.set_index(max(0, self._find_one_after_last_labeled_index() - 1)) def _next_index(self, s): self.set_index(self.index + 1) def _prev_index(self, s): self.set_index(max(0, self.index - 1)) if __name__ == '__main__': ap = argparse.ArgumentParser() neuroglancer.cli.add_server_arguments(ap) ap.add_argument('--image-url', required=True, help='Neuroglancer data source URL for image') ap.add_argument('--segmentation-url', required=True, help='Neuroglancer data source URL for segmentation') ap.add_argument('--state', required=True, help='Path to proofreading state file') ap.add_argument('--bodies', required=True, help='Path to list of bodies to proofread') ap.add_argument('--labels', nargs='+', help='Labels to use') ap.add_argument('--prefetch', type=int, default=10, help='Number of bodies to prefetch') args = ap.parse_args() neuroglancer.cli.handle_server_arguments(args) bodies = [] with open(args.bodies, 'r') as f: csv_reader = csv.DictReader(f) for row in csv_reader: bodies.append( Body( segment_id=int(row['id']), num_voxels=int(row['num_voxels']), bbox_start=np.array([ int(row['bbox.start.x']), int(row['bbox.start.y']), int(row['bbox.start.z']) ], dtype=np.int64), bbox_size=np.array( [int(row['bbox.size.x']), int(row['bbox.size.y']), int(row['bbox.size.z'])], dtype=np.int64), )) tool = Tool( state_path=args.state, image_url=args.image_url, segmentation_url=args.segmentation_url, labels=args.labels, bodies=bodies, num_to_prefetch=args.prefetch, ) print(tool.viewer)
with open(self.path, 'r') as f: self.body_labels = collections.OrderedDict(json.load(f))
conditional_block
filter_bodies.py
from __future__ import division import json import os import copy import collections import argparse import csv import neuroglancer import neuroglancer.cli import numpy as np class State(object): def __init__(self, path): self.path = path self.body_labels = collections.OrderedDict() def load(self): if os.path.exists(self.path): with open(self.path, 'r') as f: self.body_labels = collections.OrderedDict(json.load(f)) def save(self): tmp_path = self.path + '.tmp' with open(tmp_path, 'w') as f: f.write(json.dumps(self.body_labels.items())) os.rename(tmp_path, self.path) Body = collections.namedtuple('Body', ['segment_id', 'num_voxels', 'bbox_start', 'bbox_size']) class Tool(object): def __init__(self, state_path, bodies, labels, segmentation_url, image_url, num_to_prefetch): self.state = State(state_path) self.num_to_prefetch = num_to_prefetch self.viewer = neuroglancer.Viewer() self.bodies = bodies self.state.load() self.total_voxels = sum(x.num_voxels for x in bodies) self.cumulative_voxels = np.cumsum([x.num_voxels for x in bodies])
s.concurrent_downloads = 256 s.gpu_memory_limit = 2 * 1024 * 1024 * 1024 s.layout = '3d' key_bindings = [ ['bracketleft', 'prev-index'], ['bracketright', 'next-index'], ['home', 'first-index'], ['end', 'last-index'], ['control+keys', 'save'], ] label_keys = ['keyd', 'keyf', 'keyg', 'keyh'] for label, label_key in zip(labels, label_keys): key_bindings.append([label_key, 'label-%s' % label]) def label_func(s, label=label): self.set_label(s, label) self.viewer.actions.add('label-%s' % label, label_func) self.viewer.actions.add('prev-index', self._prev_index) self.viewer.actions.add('next-index', self._next_index) self.viewer.actions.add('first-index', self._first_index) self.viewer.actions.add('last-index', self._last_index) self.viewer.actions.add('save', self.save) with self.viewer.config_state.txn() as s: for key, command in key_bindings: s.input_event_bindings.viewer[key] = command s.status_messages['help'] = ('KEYS: ' + ' | '.join('%s=%s' % (key, command) for key, command in key_bindings)) self.index = -1 self.set_index(self._find_one_after_last_labeled_index()) def _find_one_after_last_labeled_index(self): body_index = 0 while self.bodies[body_index].segment_id in self.state.body_labels: body_index += 1 return body_index def set_index(self, index): if index == self.index: return body = self.bodies[index] self.index = index def modify_state_for_body(s, body): s.layers['segmentation'].segments = frozenset([body.segment_id]) s.voxel_coordinates = body.bbox_start + body.bbox_size // 2 with self.viewer.txn() as s: modify_state_for_body(s, body) prefetch_states = [] for i in range(self.num_to_prefetch): prefetch_index = self.index + i + 1 if prefetch_index >= len(self.bodies): break prefetch_state = copy.deepcopy(self.viewer.state) prefetch_state.layout = '3d' modify_state_for_body(prefetch_state, self.bodies[prefetch_index]) prefetch_states.append(prefetch_state) with self.viewer.config_state.txn() as s: s.prefetch = [ neuroglancer.PrefetchState(state=prefetch_state, priority=-i) for i, prefetch_state in enumerate(prefetch_states) ] label = self.state.body_labels.get(body.segment_id, '') with self.viewer.config_state.txn() as s: s.status_messages['status'] = ( '[Segment %d/%d : %d/%d voxels labeled = %.3f fraction] label=%s' % (index, len(self.bodies), self.cumulative_voxels[index], self.total_voxels, self.cumulative_voxels[index] / self.total_voxels, label)) def save(self, s): self.state.save() def set_label(self, s, label): self.state.body_labels[self.bodies[self.index].segment_id] = label self.set_index(self.index + 1) def _first_index(self, s): self.set_index(0) def _last_index(self, s): self.set_index(max(0, self._find_one_after_last_labeled_index() - 1)) def _next_index(self, s): self.set_index(self.index + 1) def _prev_index(self, s): self.set_index(max(0, self.index - 1)) if __name__ == '__main__': ap = argparse.ArgumentParser() neuroglancer.cli.add_server_arguments(ap) ap.add_argument('--image-url', required=True, help='Neuroglancer data source URL for image') ap.add_argument('--segmentation-url', required=True, help='Neuroglancer data source URL for segmentation') ap.add_argument('--state', required=True, help='Path to proofreading state file') ap.add_argument('--bodies', required=True, help='Path to list of bodies to proofread') ap.add_argument('--labels', nargs='+', help='Labels to use') ap.add_argument('--prefetch', type=int, default=10, help='Number of bodies to prefetch') args = ap.parse_args() neuroglancer.cli.handle_server_arguments(args) bodies = [] with open(args.bodies, 'r') as f: csv_reader = csv.DictReader(f) for row in csv_reader: bodies.append( Body( segment_id=int(row['id']), num_voxels=int(row['num_voxels']), bbox_start=np.array([ int(row['bbox.start.x']), int(row['bbox.start.y']), int(row['bbox.start.z']) ], dtype=np.int64), bbox_size=np.array( [int(row['bbox.size.x']), int(row['bbox.size.y']), int(row['bbox.size.z'])], dtype=np.int64), )) tool = Tool( state_path=args.state, image_url=args.image_url, segmentation_url=args.segmentation_url, labels=args.labels, bodies=bodies, num_to_prefetch=args.prefetch, ) print(tool.viewer)
with self.viewer.txn() as s: s.layers['image'] = neuroglancer.ImageLayer(source=image_url) s.layers['segmentation'] = neuroglancer.SegmentationLayer(source=segmentation_url) s.show_slices = False
random_line_split
filter_bodies.py
from __future__ import division import json import os import copy import collections import argparse import csv import neuroglancer import neuroglancer.cli import numpy as np class State(object): def __init__(self, path): self.path = path self.body_labels = collections.OrderedDict() def load(self): if os.path.exists(self.path): with open(self.path, 'r') as f: self.body_labels = collections.OrderedDict(json.load(f)) def save(self): tmp_path = self.path + '.tmp' with open(tmp_path, 'w') as f: f.write(json.dumps(self.body_labels.items())) os.rename(tmp_path, self.path) Body = collections.namedtuple('Body', ['segment_id', 'num_voxels', 'bbox_start', 'bbox_size']) class Tool(object): def __init__(self, state_path, bodies, labels, segmentation_url, image_url, num_to_prefetch): self.state = State(state_path) self.num_to_prefetch = num_to_prefetch self.viewer = neuroglancer.Viewer() self.bodies = bodies self.state.load() self.total_voxels = sum(x.num_voxels for x in bodies) self.cumulative_voxels = np.cumsum([x.num_voxels for x in bodies]) with self.viewer.txn() as s: s.layers['image'] = neuroglancer.ImageLayer(source=image_url) s.layers['segmentation'] = neuroglancer.SegmentationLayer(source=segmentation_url) s.show_slices = False s.concurrent_downloads = 256 s.gpu_memory_limit = 2 * 1024 * 1024 * 1024 s.layout = '3d' key_bindings = [ ['bracketleft', 'prev-index'], ['bracketright', 'next-index'], ['home', 'first-index'], ['end', 'last-index'], ['control+keys', 'save'], ] label_keys = ['keyd', 'keyf', 'keyg', 'keyh'] for label, label_key in zip(labels, label_keys): key_bindings.append([label_key, 'label-%s' % label]) def label_func(s, label=label): self.set_label(s, label) self.viewer.actions.add('label-%s' % label, label_func) self.viewer.actions.add('prev-index', self._prev_index) self.viewer.actions.add('next-index', self._next_index) self.viewer.actions.add('first-index', self._first_index) self.viewer.actions.add('last-index', self._last_index) self.viewer.actions.add('save', self.save) with self.viewer.config_state.txn() as s: for key, command in key_bindings: s.input_event_bindings.viewer[key] = command s.status_messages['help'] = ('KEYS: ' + ' | '.join('%s=%s' % (key, command) for key, command in key_bindings)) self.index = -1 self.set_index(self._find_one_after_last_labeled_index()) def
(self): body_index = 0 while self.bodies[body_index].segment_id in self.state.body_labels: body_index += 1 return body_index def set_index(self, index): if index == self.index: return body = self.bodies[index] self.index = index def modify_state_for_body(s, body): s.layers['segmentation'].segments = frozenset([body.segment_id]) s.voxel_coordinates = body.bbox_start + body.bbox_size // 2 with self.viewer.txn() as s: modify_state_for_body(s, body) prefetch_states = [] for i in range(self.num_to_prefetch): prefetch_index = self.index + i + 1 if prefetch_index >= len(self.bodies): break prefetch_state = copy.deepcopy(self.viewer.state) prefetch_state.layout = '3d' modify_state_for_body(prefetch_state, self.bodies[prefetch_index]) prefetch_states.append(prefetch_state) with self.viewer.config_state.txn() as s: s.prefetch = [ neuroglancer.PrefetchState(state=prefetch_state, priority=-i) for i, prefetch_state in enumerate(prefetch_states) ] label = self.state.body_labels.get(body.segment_id, '') with self.viewer.config_state.txn() as s: s.status_messages['status'] = ( '[Segment %d/%d : %d/%d voxels labeled = %.3f fraction] label=%s' % (index, len(self.bodies), self.cumulative_voxels[index], self.total_voxels, self.cumulative_voxels[index] / self.total_voxels, label)) def save(self, s): self.state.save() def set_label(self, s, label): self.state.body_labels[self.bodies[self.index].segment_id] = label self.set_index(self.index + 1) def _first_index(self, s): self.set_index(0) def _last_index(self, s): self.set_index(max(0, self._find_one_after_last_labeled_index() - 1)) def _next_index(self, s): self.set_index(self.index + 1) def _prev_index(self, s): self.set_index(max(0, self.index - 1)) if __name__ == '__main__': ap = argparse.ArgumentParser() neuroglancer.cli.add_server_arguments(ap) ap.add_argument('--image-url', required=True, help='Neuroglancer data source URL for image') ap.add_argument('--segmentation-url', required=True, help='Neuroglancer data source URL for segmentation') ap.add_argument('--state', required=True, help='Path to proofreading state file') ap.add_argument('--bodies', required=True, help='Path to list of bodies to proofread') ap.add_argument('--labels', nargs='+', help='Labels to use') ap.add_argument('--prefetch', type=int, default=10, help='Number of bodies to prefetch') args = ap.parse_args() neuroglancer.cli.handle_server_arguments(args) bodies = [] with open(args.bodies, 'r') as f: csv_reader = csv.DictReader(f) for row in csv_reader: bodies.append( Body( segment_id=int(row['id']), num_voxels=int(row['num_voxels']), bbox_start=np.array([ int(row['bbox.start.x']), int(row['bbox.start.y']), int(row['bbox.start.z']) ], dtype=np.int64), bbox_size=np.array( [int(row['bbox.size.x']), int(row['bbox.size.y']), int(row['bbox.size.z'])], dtype=np.int64), )) tool = Tool( state_path=args.state, image_url=args.image_url, segmentation_url=args.segmentation_url, labels=args.labels, bodies=bodies, num_to_prefetch=args.prefetch, ) print(tool.viewer)
_find_one_after_last_labeled_index
identifier_name
pressureInitial_n.py
from proteus import * from proteus.default_n import * from pressureInitial_p import * triangleOptions = triangleOptions femSpaces = {0:pbasis} stepController=FixedStep #numericalFluxType = NumericalFlux.ConstantAdvection_Diffusion_SIPG_exterior #weak boundary conditions (upwind ?) matrix = LinearAlgebraTools.SparseMatrix if useSuperlu: multilevelLinearSolver = LinearSolvers.LU levelLinearSolver = LinearSolvers.LU else:
parallelPartitioningType = parallelPartitioningType nLayersOfOverlapForParallel = nLayersOfOverlapForParallel nonlinearSmoother = None linearSmoother = None numericalFluxType = NumericalFlux.ConstantAdvection_exterior linear_solver_options_prefix = 'pinit_' multilevelNonlinearSolver = NonlinearSolvers.Newton levelNonlinearSolver = NonlinearSolvers.Newton #linear solve rtolerance linTolFac = 0.0 l_atol_res = 0.01*phi_nl_atol_res tolFac = 0.0 nl_atol_res = phi_nl_atol_res nonlinearSolverConvergenceTest = 'r' levelNonlinearSolverConvergenceTest = 'r' linearSolverConvergenceTest = 'r-true' maxLineSearches=0 periodicDirichletConditions=None conservativeFlux=None
multilevelLinearSolver = KSP_petsc4py levelLinearSolver = KSP_petsc4py
random_line_split
pressureInitial_n.py
from proteus import * from proteus.default_n import * from pressureInitial_p import * triangleOptions = triangleOptions femSpaces = {0:pbasis} stepController=FixedStep #numericalFluxType = NumericalFlux.ConstantAdvection_Diffusion_SIPG_exterior #weak boundary conditions (upwind ?) matrix = LinearAlgebraTools.SparseMatrix if useSuperlu:
else: multilevelLinearSolver = KSP_petsc4py levelLinearSolver = KSP_petsc4py parallelPartitioningType = parallelPartitioningType nLayersOfOverlapForParallel = nLayersOfOverlapForParallel nonlinearSmoother = None linearSmoother = None numericalFluxType = NumericalFlux.ConstantAdvection_exterior linear_solver_options_prefix = 'pinit_' multilevelNonlinearSolver = NonlinearSolvers.Newton levelNonlinearSolver = NonlinearSolvers.Newton #linear solve rtolerance linTolFac = 0.0 l_atol_res = 0.01*phi_nl_atol_res tolFac = 0.0 nl_atol_res = phi_nl_atol_res nonlinearSolverConvergenceTest = 'r' levelNonlinearSolverConvergenceTest = 'r' linearSolverConvergenceTest = 'r-true' maxLineSearches=0 periodicDirichletConditions=None conservativeFlux=None
multilevelLinearSolver = LinearSolvers.LU levelLinearSolver = LinearSolvers.LU
conditional_block
texture_draw.rs
#[macro_use] extern crate glium; use glium::Surface; mod support; macro_rules! texture_draw_test { ($test_name:ident, $tex_ty:ident, [$($dims:expr),+], $glsl_ty:expr, $glsl_value:expr, $rust_value:expr) => ( #[test]
let program = glium::Program::from_source(&display, " #version 110 attribute vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } ", &format!(" #version 130 out {} color; void main() {{ color = {}; }} ", $glsl_ty, $glsl_value), None); let program = match program { Ok(p) => p, Err(_) => return }; let texture = glium::texture::$tex_ty::empty(&display, $($dims),+).unwrap(); texture.as_surface().clear_color(0.0, 0.0, 0.0, 0.0); texture.as_surface().draw(&vb, &ib, &program, &uniform!{ texture: &texture }, &Default::default()).unwrap(); display.assert_no_error(None); let data: Vec<Vec<(u8, u8, u8, u8)>> = texture.read(); for row in data.iter() { for pixel in row.iter() { assert_eq!(pixel, &$rust_value); } } display.assert_no_error(None); } ); } texture_draw_test!(texture_2d_draw, Texture2d, [1024, 1024], "vec4", "vec4(1.0, 0.0, 1.0, 0.0)", (255, 0, 255, 0));
fn $test_name() { let display = support::build_display(); let (vb, ib) = support::build_rectangle_vb_ib(&display);
random_line_split
v2wizardPage.component.ts
import { IController, module } from 'angular'; import { ModalWizard, IWizardPageState } from './ModalWizard'; /** * Wizard page directive * possible attributes: * - key (required): Any string value, unique within the wizard; it becomes the the hook to access the page state * through the wizard, e.g. wizard.getPage('page-1').markComplete() * - label (required): Any string value; it becomes label in the wizard flow * - done (optional, default: false): when set to true, the page will be marked complete when rendered * - mandatory (optional, default: true): when set to false, the wizard will not consider this page when isComplete * is called * - render (optional, default: true): when set to false, registers the page with the wizard, but does not participate * in the wizard flow. To add the page to the flow, call wizard.includePage(key) * - markCompleteOnView (optional, default: true): when set to false, the page will not be marked complete when * scrolled into view */ export class WizardPageController implements IController { /** * when set to false, the wizard will not consider this page when isComplete is called * default: false * @type {boolean} */ public mandatory: boolean; /** * when set to true, the page will be marked complete when rendered * default: false * @type {boolean} */ public done: boolean; /** * when set to false, the page will not be marked clean when scrolled into view * default: true * @type {boolean} */ public markCleanOnView: boolean; /** * when set to false, the page will not be marked complete when scrolled into view * default: true * @type {boolean} */ public markCompleteOnView: boolean; /** * Any string value, unique within the wizard; it becomes the the hook to access the page state through the wizard, * e.g. wizard.getPage('page-1').markComplete() */ public key: string; /** * Any string value; it becomes label in the wizard flow */ public label: string; /** * when set to false, registers the page with the wizard, but does not participate in the wizard flow. * To add the page to the flow, call wizard.includePage(key) * default: true * @type {boolean} */ public render: boolean; /** * Internal state of the page, initialized based on other public fields */ public state: IWizardPageState; public static $inject = ['$scope']; public constructor(private $scope: ng.IScope) {} public $onInit()
} const wizardPageComponent: ng.IComponentOptions = { bindings: { mandatory: '<', done: '<', markCleanOnView: '<', markCompleteOnView: '<', key: '@', label: '@', render: '<', }, transclude: true, templateUrl: require('./v2wizardPage.component.html'), controller: WizardPageController, }; export const V2_WIZARD_PAGE_COMPONENT = 'spinnaker.core.modal.wizard.wizardPage.component'; module(V2_WIZARD_PAGE_COMPONENT, []).component('v2WizardPage', wizardPageComponent);
{ this.render = this.render !== false; this.markCleanOnView = this.markCleanOnView !== false; this.markCompleteOnView = this.markCompleteOnView !== false; this.state = { blocked: false, current: false, rendered: this.render, done: this.done || !this.mandatory, dirty: false, required: this.mandatory, markCleanOnView: this.markCleanOnView, markCompleteOnView: this.markCompleteOnView, }; ModalWizard.registerPage(this.key, this.label, this.state); this.$scope.$on('$destroy', () => ModalWizard.setRendered(this.key, false)); }
identifier_body
v2wizardPage.component.ts
import { IController, module } from 'angular'; import { ModalWizard, IWizardPageState } from './ModalWizard'; /** * Wizard page directive * possible attributes: * - key (required): Any string value, unique within the wizard; it becomes the the hook to access the page state * through the wizard, e.g. wizard.getPage('page-1').markComplete() * - label (required): Any string value; it becomes label in the wizard flow * - done (optional, default: false): when set to true, the page will be marked complete when rendered * - mandatory (optional, default: true): when set to false, the wizard will not consider this page when isComplete * is called * - render (optional, default: true): when set to false, registers the page with the wizard, but does not participate * in the wizard flow. To add the page to the flow, call wizard.includePage(key) * - markCompleteOnView (optional, default: true): when set to false, the page will not be marked complete when * scrolled into view */ export class WizardPageController implements IController { /** * when set to false, the wizard will not consider this page when isComplete is called * default: false * @type {boolean} */ public mandatory: boolean; /** * when set to true, the page will be marked complete when rendered * default: false * @type {boolean} */ public done: boolean; /** * when set to false, the page will not be marked clean when scrolled into view * default: true * @type {boolean} */ public markCleanOnView: boolean; /** * when set to false, the page will not be marked complete when scrolled into view * default: true * @type {boolean} */ public markCompleteOnView: boolean; /** * Any string value, unique within the wizard; it becomes the the hook to access the page state through the wizard, * e.g. wizard.getPage('page-1').markComplete() */ public key: string; /** * Any string value; it becomes label in the wizard flow */ public label: string;
* when set to false, registers the page with the wizard, but does not participate in the wizard flow. * To add the page to the flow, call wizard.includePage(key) * default: true * @type {boolean} */ public render: boolean; /** * Internal state of the page, initialized based on other public fields */ public state: IWizardPageState; public static $inject = ['$scope']; public constructor(private $scope: ng.IScope) {} public $onInit() { this.render = this.render !== false; this.markCleanOnView = this.markCleanOnView !== false; this.markCompleteOnView = this.markCompleteOnView !== false; this.state = { blocked: false, current: false, rendered: this.render, done: this.done || !this.mandatory, dirty: false, required: this.mandatory, markCleanOnView: this.markCleanOnView, markCompleteOnView: this.markCompleteOnView, }; ModalWizard.registerPage(this.key, this.label, this.state); this.$scope.$on('$destroy', () => ModalWizard.setRendered(this.key, false)); } } const wizardPageComponent: ng.IComponentOptions = { bindings: { mandatory: '<', done: '<', markCleanOnView: '<', markCompleteOnView: '<', key: '@', label: '@', render: '<', }, transclude: true, templateUrl: require('./v2wizardPage.component.html'), controller: WizardPageController, }; export const V2_WIZARD_PAGE_COMPONENT = 'spinnaker.core.modal.wizard.wizardPage.component'; module(V2_WIZARD_PAGE_COMPONENT, []).component('v2WizardPage', wizardPageComponent);
/**
random_line_split
v2wizardPage.component.ts
import { IController, module } from 'angular'; import { ModalWizard, IWizardPageState } from './ModalWizard'; /** * Wizard page directive * possible attributes: * - key (required): Any string value, unique within the wizard; it becomes the the hook to access the page state * through the wizard, e.g. wizard.getPage('page-1').markComplete() * - label (required): Any string value; it becomes label in the wizard flow * - done (optional, default: false): when set to true, the page will be marked complete when rendered * - mandatory (optional, default: true): when set to false, the wizard will not consider this page when isComplete * is called * - render (optional, default: true): when set to false, registers the page with the wizard, but does not participate * in the wizard flow. To add the page to the flow, call wizard.includePage(key) * - markCompleteOnView (optional, default: true): when set to false, the page will not be marked complete when * scrolled into view */ export class WizardPageController implements IController { /** * when set to false, the wizard will not consider this page when isComplete is called * default: false * @type {boolean} */ public mandatory: boolean; /** * when set to true, the page will be marked complete when rendered * default: false * @type {boolean} */ public done: boolean; /** * when set to false, the page will not be marked clean when scrolled into view * default: true * @type {boolean} */ public markCleanOnView: boolean; /** * when set to false, the page will not be marked complete when scrolled into view * default: true * @type {boolean} */ public markCompleteOnView: boolean; /** * Any string value, unique within the wizard; it becomes the the hook to access the page state through the wizard, * e.g. wizard.getPage('page-1').markComplete() */ public key: string; /** * Any string value; it becomes label in the wizard flow */ public label: string; /** * when set to false, registers the page with the wizard, but does not participate in the wizard flow. * To add the page to the flow, call wizard.includePage(key) * default: true * @type {boolean} */ public render: boolean; /** * Internal state of the page, initialized based on other public fields */ public state: IWizardPageState; public static $inject = ['$scope']; public constructor(private $scope: ng.IScope) {} public
() { this.render = this.render !== false; this.markCleanOnView = this.markCleanOnView !== false; this.markCompleteOnView = this.markCompleteOnView !== false; this.state = { blocked: false, current: false, rendered: this.render, done: this.done || !this.mandatory, dirty: false, required: this.mandatory, markCleanOnView: this.markCleanOnView, markCompleteOnView: this.markCompleteOnView, }; ModalWizard.registerPage(this.key, this.label, this.state); this.$scope.$on('$destroy', () => ModalWizard.setRendered(this.key, false)); } } const wizardPageComponent: ng.IComponentOptions = { bindings: { mandatory: '<', done: '<', markCleanOnView: '<', markCompleteOnView: '<', key: '@', label: '@', render: '<', }, transclude: true, templateUrl: require('./v2wizardPage.component.html'), controller: WizardPageController, }; export const V2_WIZARD_PAGE_COMPONENT = 'spinnaker.core.modal.wizard.wizardPage.component'; module(V2_WIZARD_PAGE_COMPONENT, []).component('v2WizardPage', wizardPageComponent);
$onInit
identifier_name
Dialog.js
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @param {!Element} relativeToElement * @param {!WebInspector.DialogDelegate} delegate */ WebInspector.Dialog = function(relativeToElement, delegate) { this._delegate = delegate; this._relativeToElement = relativeToElement; this._glassPane = new WebInspector.GlassPane(/** @type {!Document} */ (relativeToElement.ownerDocument)); WebInspector.GlassPane.DefaultFocusedViewStack.push(this); // Install glass pane capturing events. this._glassPane.element.tabIndex = 0; this._glassPane.element.addEventListener("focus", this._onGlassPaneFocus.bind(this), false); this._element = this._glassPane.element.createChild("div"); this._element.tabIndex = 0; this._element.addEventListener("focus", this._onFocus.bind(this), false); this._element.addEventListener("keydown", this._onKeyDown.bind(this), false); this._closeKeys = [ WebInspector.KeyboardShortcut.Keys.Enter.code, WebInspector.KeyboardShortcut.Keys.Esc.code, ]; delegate.show(this._element); this._position(); this._delegate.focus(); } /** * @return {?WebInspector.Dialog} */ WebInspector.Dialog.currentInstance = function() { return WebInspector.Dialog._instance; } /** * @param {!Element} relativeToElement * @param {!WebInspector.DialogDelegate} delegate */ WebInspector.Dialog.show = function(relativeToElement, delegate) { if (WebInspector.Dialog._instance) return; WebInspector.Dialog._instance = new WebInspector.Dialog(relativeToElement, delegate); } WebInspector.Dialog.hide = function() { if (!WebInspector.Dialog._instance) return; WebInspector.Dialog._instance._hide(); } WebInspector.Dialog.prototype = { focus: function() { this._element.focus(); }, _hide: function() { if (this._isHiding) return; this._isHiding = true; this._delegate.willHide(); delete WebInspector.Dialog._instance; WebInspector.GlassPane.DefaultFocusedViewStack.pop(); this._glassPane.dispose(); }, _onGlassPaneFocus: function(event) { this._hide(); }, _onFocus: function(event) { this._delegate.focus(); }, _position: function() { this._delegate.position(this._element, this._relativeToElement); }, _onKeyDown: function(event) { if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Tab.code) { event.preventDefault(); return; } if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Enter.code) this._delegate.onEnter(event); if (!event.handled && this._closeKeys.indexOf(event.keyCode) >= 0) { this._hide(); event.consume(true); } } }; /** * @constructor * @extends {WebInspector.Object} */ WebInspector.DialogDelegate = function() { /** @type {!Element} */ this.element; } WebInspector.DialogDelegate.prototype = { /** * @param {!Element} element */ show: function(element) { element.appendChild(this.element); this.element.classList.add("dialog-contents"); element.classList.add("dialog"); }, /** * @param {!Element} element * @param {!Element} relativeToElement */ position: function(element, relativeToElement) { var container = WebInspector.Dialog._modalHostView.element; var box = relativeToElement.boxInWindow(window).relativeToElement(container); var positionX = box.x + (relativeToElement.offsetWidth - element.offsetWidth) / 2; positionX = Number.constrain(positionX, 0, container.offsetWidth - element.offsetWidth); var positionY = box.y + (relativeToElement.offsetHeight - element.offsetHeight) / 2; positionY = Number.constrain(positionY, 0, container.offsetHeight - element.offsetHeight); element.style.position = "absolute"; element.positionAt(positionX, positionY, container); }, focus: function() { }, onEnter: function(event) { }, willHide: function() { },
/** @type {?WebInspector.View} */ WebInspector.Dialog._modalHostView = null; /** * @param {!WebInspector.View} view */ WebInspector.Dialog.setModalHostView = function(view) { WebInspector.Dialog._modalHostView = view; }; /** * FIXME: make utility method in Dialog, so clients use it instead of this getter. * Method should be like Dialog.showModalElement(position params, reposition callback). * @return {?WebInspector.View} */ WebInspector.Dialog.modalHostView = function() { return WebInspector.Dialog._modalHostView; }; WebInspector.Dialog.modalHostRepositioned = function() { if (WebInspector.Dialog._instance) WebInspector.Dialog._instance._position(); };
__proto__: WebInspector.Object.prototype }
random_line_split
core.py
#!/usr/bin/python2 # core.py # aoneill - 04/10/17 import sys import random import time import pauschpharos as PF import lumiversepython as L SEQ_LIM = 200 def memoize(ignore = None): if(ignore is None): ignore = set() def inner(func): cache = dict() def wrapper(*args): memo = tuple(filter(lambda x: x, map(lambda (i, e): e if (i not in ignore) else None, enumerate(args)))) if(memo not in cache): cache[memo] = func(*args) return cache[memo] return wrapper return inner def blank(): p = PF.PauschPharos() p.SetBlank() p.Trigger(PF.DEFAULT_ID, None) def fireplace(rig): # Warm up cache for seq in xrange(SEQ_LIM): query(rig, '$sequence=%d' % seq) def init(upload = True, run = True, wipe = True, fire = True): rig = L.Rig("/home/teacher/Lumiverse/PBridge.rig.json") rig.init() # Upload the blank template if(upload): blank() # Run if requested if(run): rig.run() # Wipe if requested if(wipe): for seq in xrange(SEQ_LIM): query(rig, '$sequence=%d' % seq).setRGBRaw(0, 0, 0) # Heat up the cache if(fire and not wipe): fireplace(rig) return rig @memoize(ignore = set([0])) def
(rig, text): return rig.select(text) def seq(rig, num): return query(rig, '$sequence=%d' % num) def rand_color(): func = lambda: random.randint(0, 255) / 255.0 return (func(), func(), func())
query
identifier_name
core.py
#!/usr/bin/python2 # core.py # aoneill - 04/10/17 import sys import random import time import pauschpharos as PF import lumiversepython as L SEQ_LIM = 200 def memoize(ignore = None): if(ignore is None): ignore = set() def inner(func): cache = dict() def wrapper(*args): memo = tuple(filter(lambda x: x, map(lambda (i, e): e if (i not in ignore) else None, enumerate(args)))) if(memo not in cache): cache[memo] = func(*args) return cache[memo] return wrapper return inner def blank(): p = PF.PauschPharos() p.SetBlank() p.Trigger(PF.DEFAULT_ID, None) def fireplace(rig): # Warm up cache for seq in xrange(SEQ_LIM): query(rig, '$sequence=%d' % seq) def init(upload = True, run = True, wipe = True, fire = True): rig = L.Rig("/home/teacher/Lumiverse/PBridge.rig.json") rig.init() # Upload the blank template if(upload): blank() # Run if requested if(run): rig.run() # Wipe if requested if(wipe): for seq in xrange(SEQ_LIM): query(rig, '$sequence=%d' % seq).setRGBRaw(0, 0, 0) # Heat up the cache if(fire and not wipe): fireplace(rig) return rig @memoize(ignore = set([0])) def query(rig, text): return rig.select(text) def seq(rig, num):
def rand_color(): func = lambda: random.randint(0, 255) / 255.0 return (func(), func(), func())
return query(rig, '$sequence=%d' % num)
identifier_body
core.py
#!/usr/bin/python2 # core.py # aoneill - 04/10/17 import sys import random import time import pauschpharos as PF import lumiversepython as L SEQ_LIM = 200 def memoize(ignore = None): if(ignore is None): ignore = set() def inner(func): cache = dict() def wrapper(*args): memo = tuple(filter(lambda x: x, map(lambda (i, e): e if (i not in ignore) else None, enumerate(args)))) if(memo not in cache): cache[memo] = func(*args) return cache[memo] return wrapper return inner def blank(): p = PF.PauschPharos() p.SetBlank() p.Trigger(PF.DEFAULT_ID, None) def fireplace(rig): # Warm up cache for seq in xrange(SEQ_LIM): query(rig, '$sequence=%d' % seq) def init(upload = True, run = True, wipe = True, fire = True): rig = L.Rig("/home/teacher/Lumiverse/PBridge.rig.json") rig.init() # Upload the blank template if(upload): blank() # Run if requested if(run): rig.run() # Wipe if requested if(wipe): for seq in xrange(SEQ_LIM): query(rig, '$sequence=%d' % seq).setRGBRaw(0, 0, 0) # Heat up the cache if(fire and not wipe):
return rig @memoize(ignore = set([0])) def query(rig, text): return rig.select(text) def seq(rig, num): return query(rig, '$sequence=%d' % num) def rand_color(): func = lambda: random.randint(0, 255) / 255.0 return (func(), func(), func())
fireplace(rig)
conditional_block
core.py
#!/usr/bin/python2 # core.py # aoneill - 04/10/17 import sys import random import time import pauschpharos as PF import lumiversepython as L SEQ_LIM = 200 def memoize(ignore = None): if(ignore is None): ignore = set() def inner(func): cache = dict() def wrapper(*args): memo = tuple(filter(lambda x: x, map(lambda (i, e): e if (i not in ignore) else None, enumerate(args)))) if(memo not in cache): cache[memo] = func(*args) return cache[memo] return wrapper return inner def blank(): p = PF.PauschPharos() p.SetBlank() p.Trigger(PF.DEFAULT_ID, None)
query(rig, '$sequence=%d' % seq) def init(upload = True, run = True, wipe = True, fire = True): rig = L.Rig("/home/teacher/Lumiverse/PBridge.rig.json") rig.init() # Upload the blank template if(upload): blank() # Run if requested if(run): rig.run() # Wipe if requested if(wipe): for seq in xrange(SEQ_LIM): query(rig, '$sequence=%d' % seq).setRGBRaw(0, 0, 0) # Heat up the cache if(fire and not wipe): fireplace(rig) return rig @memoize(ignore = set([0])) def query(rig, text): return rig.select(text) def seq(rig, num): return query(rig, '$sequence=%d' % num) def rand_color(): func = lambda: random.randint(0, 255) / 255.0 return (func(), func(), func())
def fireplace(rig): # Warm up cache for seq in xrange(SEQ_LIM):
random_line_split
_part_grammar_processor.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2017 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # 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/>. from typing import Any, Dict, Set from snapcraft import project from snapcraft.internal.project_loader import grammar from snapcraft.internal import pluginhandler, repo from ._package_transformer import package_transformer class PartGrammarProcessor: """Process part properties that support grammar. Stage packages example: >>> from unittest import mock >>> import snapcraft >>> # Pretend that all packages are valid >>> repo = mock.Mock() >>> repo.is_valid.return_value = True >>> plugin = mock.Mock() >>> plugin.stage_packages = [{'try': ['foo']}] >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties={}, ... project=snapcraft.project.Project(), ... repo=repo) >>> processor.get_stage_packages() {'foo'} Build packages example: >>> from unittest import mock >>> import snapcraft >>> # Pretend that all packages are valid >>> repo = mock.Mock() >>> repo.is_valid.return_value = True >>> plugin = mock.Mock() >>> plugin.build_packages = [{'try': ['foo']}] >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties={}, ... project=snapcraft.project.Project(), ... repo=repo) >>> processor.get_build_packages() {'foo'} Source example: >>> from unittest import mock >>> import snapcraft >>> plugin = mock.Mock() >>> plugin.properties = {'source': [{'on amd64': 'foo'}, 'else fail']} >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties=plugin.properties, ... project=snapcraft.project.Project(), ... repo=None) >>> processor.get_source() 'foo' """ def __init__( self, *, plugin: pluginhandler.PluginHandler, properties: Dict[str, Any], project: project.Project, repo: "repo.Ubuntu" ) -> None: self._project = project self._repo = repo self._build_snap_grammar = getattr(plugin, "build_snaps", []) self.__build_snaps = set() # type: Set[str] self._build_package_grammar = getattr(plugin, "build_packages", []) self.__build_packages = set() # type: Set[str] self._stage_package_grammar = getattr(plugin, "stage_packages", []) self.__stage_packages = set() # type: Set[str] source_grammar = properties.get("source", [""]) if not isinstance(source_grammar, list): self._source_grammar = [source_grammar] else: self._source_grammar = source_grammar self.__source = "" def get_source(self) -> str: if not self.__source: # The grammar is array-based, even though we only support a single # source. processor = grammar.GrammarProcessor( self._source_grammar, self._project, lambda s: True ) source_array = processor.process() if len(source_array) > 0: self.__source = source_array.pop() return self.__source def get_build_snaps(self) -> Set[str]:
def get_build_packages(self) -> Set[str]: if not self.__build_packages: processor = grammar.GrammarProcessor( self._build_package_grammar, self._project, self._repo.build_package_is_valid, transformer=package_transformer, ) self.__build_packages = processor.process() return self.__build_packages def get_stage_packages(self) -> Set[str]: if not self.__stage_packages: processor = grammar.GrammarProcessor( self._stage_package_grammar, self._project, self._repo.is_valid, transformer=package_transformer, ) self.__stage_packages = processor.process() return self.__stage_packages
if not self.__build_snaps: processor = grammar.GrammarProcessor( self._build_snap_grammar, self._project, repo.snaps.SnapPackage.is_valid_snap, ) self.__build_snaps = processor.process() return self.__build_snaps
identifier_body
_part_grammar_processor.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2017 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # 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/>. from typing import Any, Dict, Set from snapcraft import project from snapcraft.internal.project_loader import grammar from snapcraft.internal import pluginhandler, repo from ._package_transformer import package_transformer class PartGrammarProcessor: """Process part properties that support grammar. Stage packages example: >>> from unittest import mock >>> import snapcraft >>> # Pretend that all packages are valid >>> repo = mock.Mock() >>> repo.is_valid.return_value = True >>> plugin = mock.Mock() >>> plugin.stage_packages = [{'try': ['foo']}] >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties={}, ... project=snapcraft.project.Project(), ... repo=repo) >>> processor.get_stage_packages() {'foo'} Build packages example: >>> from unittest import mock >>> import snapcraft >>> # Pretend that all packages are valid >>> repo = mock.Mock() >>> repo.is_valid.return_value = True >>> plugin = mock.Mock() >>> plugin.build_packages = [{'try': ['foo']}] >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties={}, ... project=snapcraft.project.Project(), ... repo=repo) >>> processor.get_build_packages() {'foo'} Source example: >>> from unittest import mock >>> import snapcraft >>> plugin = mock.Mock() >>> plugin.properties = {'source': [{'on amd64': 'foo'}, 'else fail']} >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties=plugin.properties, ... project=snapcraft.project.Project(), ... repo=None) >>> processor.get_source() 'foo' """ def __init__( self, *, plugin: pluginhandler.PluginHandler, properties: Dict[str, Any], project: project.Project, repo: "repo.Ubuntu" ) -> None: self._project = project self._repo = repo self._build_snap_grammar = getattr(plugin, "build_snaps", []) self.__build_snaps = set() # type: Set[str] self._build_package_grammar = getattr(plugin, "build_packages", []) self.__build_packages = set() # type: Set[str] self._stage_package_grammar = getattr(plugin, "stage_packages", []) self.__stage_packages = set() # type: Set[str] source_grammar = properties.get("source", [""]) if not isinstance(source_grammar, list): self._source_grammar = [source_grammar] else: self._source_grammar = source_grammar self.__source = "" def
(self) -> str: if not self.__source: # The grammar is array-based, even though we only support a single # source. processor = grammar.GrammarProcessor( self._source_grammar, self._project, lambda s: True ) source_array = processor.process() if len(source_array) > 0: self.__source = source_array.pop() return self.__source def get_build_snaps(self) -> Set[str]: if not self.__build_snaps: processor = grammar.GrammarProcessor( self._build_snap_grammar, self._project, repo.snaps.SnapPackage.is_valid_snap, ) self.__build_snaps = processor.process() return self.__build_snaps def get_build_packages(self) -> Set[str]: if not self.__build_packages: processor = grammar.GrammarProcessor( self._build_package_grammar, self._project, self._repo.build_package_is_valid, transformer=package_transformer, ) self.__build_packages = processor.process() return self.__build_packages def get_stage_packages(self) -> Set[str]: if not self.__stage_packages: processor = grammar.GrammarProcessor( self._stage_package_grammar, self._project, self._repo.is_valid, transformer=package_transformer, ) self.__stage_packages = processor.process() return self.__stage_packages
get_source
identifier_name
_part_grammar_processor.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2017 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # 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/>. from typing import Any, Dict, Set from snapcraft import project from snapcraft.internal.project_loader import grammar from snapcraft.internal import pluginhandler, repo from ._package_transformer import package_transformer class PartGrammarProcessor: """Process part properties that support grammar. Stage packages example: >>> from unittest import mock >>> import snapcraft >>> # Pretend that all packages are valid >>> repo = mock.Mock() >>> repo.is_valid.return_value = True >>> plugin = mock.Mock() >>> plugin.stage_packages = [{'try': ['foo']}] >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties={}, ... project=snapcraft.project.Project(), ... repo=repo) >>> processor.get_stage_packages() {'foo'} Build packages example: >>> from unittest import mock >>> import snapcraft >>> # Pretend that all packages are valid >>> repo = mock.Mock() >>> repo.is_valid.return_value = True >>> plugin = mock.Mock() >>> plugin.build_packages = [{'try': ['foo']}] >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties={}, ... project=snapcraft.project.Project(), ... repo=repo) >>> processor.get_build_packages() {'foo'} Source example: >>> from unittest import mock >>> import snapcraft >>> plugin = mock.Mock() >>> plugin.properties = {'source': [{'on amd64': 'foo'}, 'else fail']} >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties=plugin.properties, ... project=snapcraft.project.Project(), ... repo=None) >>> processor.get_source() 'foo' """ def __init__( self, *, plugin: pluginhandler.PluginHandler, properties: Dict[str, Any], project: project.Project, repo: "repo.Ubuntu" ) -> None: self._project = project self._repo = repo self._build_snap_grammar = getattr(plugin, "build_snaps", []) self.__build_snaps = set() # type: Set[str] self._build_package_grammar = getattr(plugin, "build_packages", []) self.__build_packages = set() # type: Set[str] self._stage_package_grammar = getattr(plugin, "stage_packages", []) self.__stage_packages = set() # type: Set[str] source_grammar = properties.get("source", [""]) if not isinstance(source_grammar, list): self._source_grammar = [source_grammar] else: self._source_grammar = source_grammar self.__source = "" def get_source(self) -> str: if not self.__source: # The grammar is array-based, even though we only support a single # source. processor = grammar.GrammarProcessor( self._source_grammar, self._project, lambda s: True ) source_array = processor.process() if len(source_array) > 0: self.__source = source_array.pop() return self.__source def get_build_snaps(self) -> Set[str]: if not self.__build_snaps: processor = grammar.GrammarProcessor( self._build_snap_grammar, self._project, repo.snaps.SnapPackage.is_valid_snap, ) self.__build_snaps = processor.process() return self.__build_snaps def get_build_packages(self) -> Set[str]: if not self.__build_packages:
return self.__build_packages def get_stage_packages(self) -> Set[str]: if not self.__stage_packages: processor = grammar.GrammarProcessor( self._stage_package_grammar, self._project, self._repo.is_valid, transformer=package_transformer, ) self.__stage_packages = processor.process() return self.__stage_packages
processor = grammar.GrammarProcessor( self._build_package_grammar, self._project, self._repo.build_package_is_valid, transformer=package_transformer, ) self.__build_packages = processor.process()
conditional_block
_part_grammar_processor.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2017 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # 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/>. from typing import Any, Dict, Set from snapcraft import project from snapcraft.internal.project_loader import grammar from snapcraft.internal import pluginhandler, repo from ._package_transformer import package_transformer class PartGrammarProcessor: """Process part properties that support grammar. Stage packages example: >>> from unittest import mock >>> import snapcraft >>> # Pretend that all packages are valid >>> repo = mock.Mock() >>> repo.is_valid.return_value = True >>> plugin = mock.Mock() >>> plugin.stage_packages = [{'try': ['foo']}] >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties={}, ... project=snapcraft.project.Project(), ... repo=repo) >>> processor.get_stage_packages() {'foo'} Build packages example: >>> from unittest import mock >>> import snapcraft >>> # Pretend that all packages are valid >>> repo = mock.Mock() >>> repo.is_valid.return_value = True >>> plugin = mock.Mock() >>> plugin.build_packages = [{'try': ['foo']}] >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties={}, ... project=snapcraft.project.Project(), ... repo=repo) >>> processor.get_build_packages() {'foo'} Source example: >>> from unittest import mock >>> import snapcraft >>> plugin = mock.Mock() >>> plugin.properties = {'source': [{'on amd64': 'foo'}, 'else fail']} >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties=plugin.properties, ... project=snapcraft.project.Project(), ... repo=None) >>> processor.get_source() 'foo' """ def __init__( self, *, plugin: pluginhandler.PluginHandler, properties: Dict[str, Any], project: project.Project, repo: "repo.Ubuntu" ) -> None: self._project = project self._repo = repo self._build_snap_grammar = getattr(plugin, "build_snaps", []) self.__build_snaps = set() # type: Set[str] self._build_package_grammar = getattr(plugin, "build_packages", []) self.__build_packages = set() # type: Set[str] self._stage_package_grammar = getattr(plugin, "stage_packages", []) self.__stage_packages = set() # type: Set[str] source_grammar = properties.get("source", [""]) if not isinstance(source_grammar, list): self._source_grammar = [source_grammar] else: self._source_grammar = source_grammar self.__source = ""
if not self.__source: # The grammar is array-based, even though we only support a single # source. processor = grammar.GrammarProcessor( self._source_grammar, self._project, lambda s: True ) source_array = processor.process() if len(source_array) > 0: self.__source = source_array.pop() return self.__source def get_build_snaps(self) -> Set[str]: if not self.__build_snaps: processor = grammar.GrammarProcessor( self._build_snap_grammar, self._project, repo.snaps.SnapPackage.is_valid_snap, ) self.__build_snaps = processor.process() return self.__build_snaps def get_build_packages(self) -> Set[str]: if not self.__build_packages: processor = grammar.GrammarProcessor( self._build_package_grammar, self._project, self._repo.build_package_is_valid, transformer=package_transformer, ) self.__build_packages = processor.process() return self.__build_packages def get_stage_packages(self) -> Set[str]: if not self.__stage_packages: processor = grammar.GrammarProcessor( self._stage_package_grammar, self._project, self._repo.is_valid, transformer=package_transformer, ) self.__stage_packages = processor.process() return self.__stage_packages
def get_source(self) -> str:
random_line_split
synthetic_rope.py
import numpy as np import cv2 from scipy import interpolate from random import randint import IPython from alan.rgbd.basic_imaging import cos,sin from alan.synthetic.synthetic_util import rand_sign from alan.core.points import Point """ generates rope using non-holonomic car model dynamics (moves with turn radius) generates labels at ends of rope parameters: h, w of image matrix l, w of rope returns: image matrix with rope drawn [left label, right label] """ def get_rope_car(h = 420, w = 420, rope_l_pixels = 800 , rope_w_pixels = 8, pix_per_step = 10, steps_per_curve = 10, lo_turn_delta = 5, hi_turn_delta = 10): #randomize start init_pos = np.array([randint(0, w - 1), randint(0, h - 1), randint(0, 360)]) all_positions = np.array([init_pos]) #dependent parameter (use float division) num_curves = int(rope_l_pixels/(steps_per_curve * pix_per_step * 1.0)) #point generation for c in range(num_curves): turn_delta = rand_sign() * randint(lo_turn_delta, hi_turn_delta) for s in range(steps_per_curve): curr_pos = all_positions[-1] delta_pos = np.array([pix_per_step * cos(curr_pos[2]), pix_per_step * sin(curr_pos[2]), turn_delta]) all_positions = np.append(all_positions, [curr_pos + delta_pos], axis = 0) #center the points (avoid leaving image bounds) mid_x_points = (min(all_positions[:,0]) + max(all_positions[:,0]))/2.0 mid_y_points = (min(all_positions[:,1]) + max(all_positions[:,1]))/2.0 for pos in all_positions: pos[0] -= (mid_x_points - w/2.0) pos[1] -= (mid_y_points - h/2.0) #draw rope image = np.zeros((h, w)) prev_pos = all_positions[0] for curr_pos in all_positions[1:]: cv2.line(image, (int(prev_pos[0]), int(prev_pos[1])), (int(curr_pos[0]), int(curr_pos[1])), 255, rope_w_pixels) prev_pos = curr_pos #get endpoint labels, sorted by x labels = [all_positions[0], all_positions[-1]] if labels[0][0] > labels[1][0]: labels = [labels[1], labels[0]] #labels = [[l[0], l[1], l[2] + 90] for l in labels] #Ignoring Rotation for Now labels = [[l[0], l[1], 0] for l in labels] #rejection sampling for num_label in range(2): c_label = labels[num_label] #case 1- endpoints not in image if check_bounds(c_label, [w, h]) == -1: return image, labels, -1 #case 2- endpoint on top of other rope segment if check_overlap(c_label, [w, h], image, rope_w_pixels) == -1: return image, labels, -1 return image, labels, 1 def check_bounds(label, bounds): bound_tolerance = 5 for dim in range(2): if label[dim] < bound_tolerance or label[dim] > (bounds[dim] - 1 - bound_tolerance): return -1 return 0 def check_overlap(label, bounds, image, rope_w_pixels):
lb = [] ub = [] for dim in range(2): lb.append(int(max(0, label[dim] - rope_w_pixels))) ub.append(int(min(bounds[dim] - 1, label[dim] + rope_w_pixels))) pixel_sum = 0 for x in range(lb[0], ub[0]): for y in range(lb[1], ub[1]): pixel_sum += (image[y][x]/255.0) #if more than 60% of adjacent (2 * rope_w x 2 * rope_w) pixels are white, endpoint is probably lying on rope expected_sum = 0.6 * (ub[1] - lb[1]) * (ub[0] - lb[0]) if pixel_sum > expected_sum: return -1 return 0
identifier_body
synthetic_rope.py
import numpy as np import cv2 from scipy import interpolate from random import randint import IPython from alan.rgbd.basic_imaging import cos,sin from alan.synthetic.synthetic_util import rand_sign from alan.core.points import Point """ generates rope using non-holonomic car model dynamics (moves with turn radius) generates labels at ends of rope parameters: h, w of image matrix l, w of rope returns: image matrix with rope drawn [left label, right label] """ def get_rope_car(h = 420, w = 420, rope_l_pixels = 800 , rope_w_pixels = 8, pix_per_step = 10, steps_per_curve = 10, lo_turn_delta = 5, hi_turn_delta = 10): #randomize start init_pos = np.array([randint(0, w - 1), randint(0, h - 1), randint(0, 360)]) all_positions = np.array([init_pos]) #dependent parameter (use float division) num_curves = int(rope_l_pixels/(steps_per_curve * pix_per_step * 1.0)) #point generation for c in range(num_curves):
#center the points (avoid leaving image bounds) mid_x_points = (min(all_positions[:,0]) + max(all_positions[:,0]))/2.0 mid_y_points = (min(all_positions[:,1]) + max(all_positions[:,1]))/2.0 for pos in all_positions: pos[0] -= (mid_x_points - w/2.0) pos[1] -= (mid_y_points - h/2.0) #draw rope image = np.zeros((h, w)) prev_pos = all_positions[0] for curr_pos in all_positions[1:]: cv2.line(image, (int(prev_pos[0]), int(prev_pos[1])), (int(curr_pos[0]), int(curr_pos[1])), 255, rope_w_pixels) prev_pos = curr_pos #get endpoint labels, sorted by x labels = [all_positions[0], all_positions[-1]] if labels[0][0] > labels[1][0]: labels = [labels[1], labels[0]] #labels = [[l[0], l[1], l[2] + 90] for l in labels] #Ignoring Rotation for Now labels = [[l[0], l[1], 0] for l in labels] #rejection sampling for num_label in range(2): c_label = labels[num_label] #case 1- endpoints not in image if check_bounds(c_label, [w, h]) == -1: return image, labels, -1 #case 2- endpoint on top of other rope segment if check_overlap(c_label, [w, h], image, rope_w_pixels) == -1: return image, labels, -1 return image, labels, 1 def check_bounds(label, bounds): bound_tolerance = 5 for dim in range(2): if label[dim] < bound_tolerance or label[dim] > (bounds[dim] - 1 - bound_tolerance): return -1 return 0 def check_overlap(label, bounds, image, rope_w_pixels): lb = [] ub = [] for dim in range(2): lb.append(int(max(0, label[dim] - rope_w_pixels))) ub.append(int(min(bounds[dim] - 1, label[dim] + rope_w_pixels))) pixel_sum = 0 for x in range(lb[0], ub[0]): for y in range(lb[1], ub[1]): pixel_sum += (image[y][x]/255.0) #if more than 60% of adjacent (2 * rope_w x 2 * rope_w) pixels are white, endpoint is probably lying on rope expected_sum = 0.6 * (ub[1] - lb[1]) * (ub[0] - lb[0]) if pixel_sum > expected_sum: return -1 return 0
turn_delta = rand_sign() * randint(lo_turn_delta, hi_turn_delta) for s in range(steps_per_curve): curr_pos = all_positions[-1] delta_pos = np.array([pix_per_step * cos(curr_pos[2]), pix_per_step * sin(curr_pos[2]), turn_delta]) all_positions = np.append(all_positions, [curr_pos + delta_pos], axis = 0)
conditional_block
synthetic_rope.py
import numpy as np import cv2 from scipy import interpolate from random import randint import IPython from alan.rgbd.basic_imaging import cos,sin from alan.synthetic.synthetic_util import rand_sign from alan.core.points import Point """ generates rope using non-holonomic car model dynamics (moves with turn radius) generates labels at ends of rope parameters: h, w of image matrix l, w of rope returns:
#randomize start init_pos = np.array([randint(0, w - 1), randint(0, h - 1), randint(0, 360)]) all_positions = np.array([init_pos]) #dependent parameter (use float division) num_curves = int(rope_l_pixels/(steps_per_curve * pix_per_step * 1.0)) #point generation for c in range(num_curves): turn_delta = rand_sign() * randint(lo_turn_delta, hi_turn_delta) for s in range(steps_per_curve): curr_pos = all_positions[-1] delta_pos = np.array([pix_per_step * cos(curr_pos[2]), pix_per_step * sin(curr_pos[2]), turn_delta]) all_positions = np.append(all_positions, [curr_pos + delta_pos], axis = 0) #center the points (avoid leaving image bounds) mid_x_points = (min(all_positions[:,0]) + max(all_positions[:,0]))/2.0 mid_y_points = (min(all_positions[:,1]) + max(all_positions[:,1]))/2.0 for pos in all_positions: pos[0] -= (mid_x_points - w/2.0) pos[1] -= (mid_y_points - h/2.0) #draw rope image = np.zeros((h, w)) prev_pos = all_positions[0] for curr_pos in all_positions[1:]: cv2.line(image, (int(prev_pos[0]), int(prev_pos[1])), (int(curr_pos[0]), int(curr_pos[1])), 255, rope_w_pixels) prev_pos = curr_pos #get endpoint labels, sorted by x labels = [all_positions[0], all_positions[-1]] if labels[0][0] > labels[1][0]: labels = [labels[1], labels[0]] #labels = [[l[0], l[1], l[2] + 90] for l in labels] #Ignoring Rotation for Now labels = [[l[0], l[1], 0] for l in labels] #rejection sampling for num_label in range(2): c_label = labels[num_label] #case 1- endpoints not in image if check_bounds(c_label, [w, h]) == -1: return image, labels, -1 #case 2- endpoint on top of other rope segment if check_overlap(c_label, [w, h], image, rope_w_pixels) == -1: return image, labels, -1 return image, labels, 1 def check_bounds(label, bounds): bound_tolerance = 5 for dim in range(2): if label[dim] < bound_tolerance or label[dim] > (bounds[dim] - 1 - bound_tolerance): return -1 return 0 def check_overlap(label, bounds, image, rope_w_pixels): lb = [] ub = [] for dim in range(2): lb.append(int(max(0, label[dim] - rope_w_pixels))) ub.append(int(min(bounds[dim] - 1, label[dim] + rope_w_pixels))) pixel_sum = 0 for x in range(lb[0], ub[0]): for y in range(lb[1], ub[1]): pixel_sum += (image[y][x]/255.0) #if more than 60% of adjacent (2 * rope_w x 2 * rope_w) pixels are white, endpoint is probably lying on rope expected_sum = 0.6 * (ub[1] - lb[1]) * (ub[0] - lb[0]) if pixel_sum > expected_sum: return -1 return 0
image matrix with rope drawn [left label, right label] """ def get_rope_car(h = 420, w = 420, rope_l_pixels = 800 , rope_w_pixels = 8, pix_per_step = 10, steps_per_curve = 10, lo_turn_delta = 5, hi_turn_delta = 10):
random_line_split
synthetic_rope.py
import numpy as np import cv2 from scipy import interpolate from random import randint import IPython from alan.rgbd.basic_imaging import cos,sin from alan.synthetic.synthetic_util import rand_sign from alan.core.points import Point """ generates rope using non-holonomic car model dynamics (moves with turn radius) generates labels at ends of rope parameters: h, w of image matrix l, w of rope returns: image matrix with rope drawn [left label, right label] """ def get_rope_car(h = 420, w = 420, rope_l_pixels = 800 , rope_w_pixels = 8, pix_per_step = 10, steps_per_curve = 10, lo_turn_delta = 5, hi_turn_delta = 10): #randomize start init_pos = np.array([randint(0, w - 1), randint(0, h - 1), randint(0, 360)]) all_positions = np.array([init_pos]) #dependent parameter (use float division) num_curves = int(rope_l_pixels/(steps_per_curve * pix_per_step * 1.0)) #point generation for c in range(num_curves): turn_delta = rand_sign() * randint(lo_turn_delta, hi_turn_delta) for s in range(steps_per_curve): curr_pos = all_positions[-1] delta_pos = np.array([pix_per_step * cos(curr_pos[2]), pix_per_step * sin(curr_pos[2]), turn_delta]) all_positions = np.append(all_positions, [curr_pos + delta_pos], axis = 0) #center the points (avoid leaving image bounds) mid_x_points = (min(all_positions[:,0]) + max(all_positions[:,0]))/2.0 mid_y_points = (min(all_positions[:,1]) + max(all_positions[:,1]))/2.0 for pos in all_positions: pos[0] -= (mid_x_points - w/2.0) pos[1] -= (mid_y_points - h/2.0) #draw rope image = np.zeros((h, w)) prev_pos = all_positions[0] for curr_pos in all_positions[1:]: cv2.line(image, (int(prev_pos[0]), int(prev_pos[1])), (int(curr_pos[0]), int(curr_pos[1])), 255, rope_w_pixels) prev_pos = curr_pos #get endpoint labels, sorted by x labels = [all_positions[0], all_positions[-1]] if labels[0][0] > labels[1][0]: labels = [labels[1], labels[0]] #labels = [[l[0], l[1], l[2] + 90] for l in labels] #Ignoring Rotation for Now labels = [[l[0], l[1], 0] for l in labels] #rejection sampling for num_label in range(2): c_label = labels[num_label] #case 1- endpoints not in image if check_bounds(c_label, [w, h]) == -1: return image, labels, -1 #case 2- endpoint on top of other rope segment if check_overlap(c_label, [w, h], image, rope_w_pixels) == -1: return image, labels, -1 return image, labels, 1 def check_bounds(label, bounds): bound_tolerance = 5 for dim in range(2): if label[dim] < bound_tolerance or label[dim] > (bounds[dim] - 1 - bound_tolerance): return -1 return 0 def
(label, bounds, image, rope_w_pixels): lb = [] ub = [] for dim in range(2): lb.append(int(max(0, label[dim] - rope_w_pixels))) ub.append(int(min(bounds[dim] - 1, label[dim] + rope_w_pixels))) pixel_sum = 0 for x in range(lb[0], ub[0]): for y in range(lb[1], ub[1]): pixel_sum += (image[y][x]/255.0) #if more than 60% of adjacent (2 * rope_w x 2 * rope_w) pixels are white, endpoint is probably lying on rope expected_sum = 0.6 * (ub[1] - lb[1]) * (ub[0] - lb[0]) if pixel_sum > expected_sum: return -1 return 0
check_overlap
identifier_name
param_util.py
#!/usr/bin/env python # T. Carman # January 2017 import os import json def get_CMTs_in_file(aFile): ''' Gets a list of the CMTs found in a file. Parameters ---------- aFile : string, required The path to a file to read. Returns ------- A list of CMTs found in a file. ''' data = read_paramfile(aFile) cmtkey_list = [] for line in data: if line.find('CMT') >= 0: sidx = line.find('CMT') cmtkey_list.append(line[sidx:sidx+5]) return cmtkey_list def find_cmt_start_idx(data, cmtkey): ''' Finds the starting index for a CMT data block in a list of lines. Parameters ---------- data : [str, str, ...] A list of strings (maybe from a parameter file) cmtkey : str A a CMT code string like 'CMT05' to search for in the list. Returns ------- i : int The first index in the list where the CMT key is found. If key is not found returns None. ''' for i, line in enumerate(data): if cmtkey.upper() in line: return i # Key not found return None def read_paramfile(thefile): ''' Opens and reads a file, returning the data as a list of lines (with newlines). Parameters ---------- theFile : str A path to a file to open and read. Returns ------- d : [str, str, str, ...] A list of strings (with newlines at the end of each string). ''' with open(thefile, 'r') as f: data = f.readlines() return data def get_CMT_datablock(afile, cmtnum): ''' Search file, returns the first block of data for one CMT as a list of strings. Parameters ---------- afile : str Path to a file to search. cmtnum : int The CMT number to search for. Converted (internally) to the CMT key. Returns ------- d : [str, str, ...] A list of strings, one item for each line in the CMT's datablock. Each string will have a newline charachter in it. ''' data = read_paramfile(afile) cmtkey = 'CMT%02i' % cmtnum startidx = find_cmt_start_idx(data, cmtkey) end = None for i, line in enumerate(data[startidx:]): if i == 0: # Header line, e.g.: "// CMT07 // Heath Tundra - (ma....."" pass elif i == 1: # PFT name line, e,g.: "//Decid. E.green ...." # Not sure how/why this is working on non-PFT data blocks # but is seems to do the trick? pass if (i > 0) and "CMT" in line: #print "end of datablock, i=", i end = startidx + i break return data[startidx:end] def detect_block_with_pft_info(cmtdatablock): # Perhaps should look at all lines?? secondline = cmtdatablock[1].strip("//").split() if len(secondline) >= 9: #print "Looks like a PFT header line!" return True else: return False def parse_header_line(datablock): '''Splits a header line into components: cmtkey, text name, comment. Assumes a CMT block header line looks like this: // CMT07 // Heath Tundra - (ma..... ''' # Assume header is first line l0 = datablock[0] # Header line, e.g: header = l0.strip().strip("//").strip().split("//") hdr_cmtkey = header[0].strip() txtcmtname = header[1].strip().split('-')[0].strip() hdrcomment = header[1].strip().split('-')[1].strip() return hdr_cmtkey, txtcmtname, hdrcomment def
(cmtkey=None, pftkey=None, cmtnum=None, pftnum=None): path2params = os.path.join(os.path.split(os.path.dirname(os.path.realpath(__file__)))[0], 'parameters/') if cmtkey and cmtnum: raise ValueError("you must provide only one of you cmtkey or cmtnumber") if pftkey and pftnum: raise ValueError("you must provide only one of pftkey or pftnumber") if cmtkey: # convert to number cmtnum = int(cmtkey.lstrip('CMT')) if pftnum: # convert to key pftkey = 'pft%i' % pftnum data = get_CMT_datablock(os.path.join(path2params, 'cmt_calparbgc.txt'), cmtnum) dd = cmtdatablock2dict(data) return dd[pftkey.lower()]['name'] def cmtdatablock2dict(cmtdatablock): ''' Converts a "CMT datablock" (list of strings) into a dict structure. Parameters ---------- cmtdatablock : [str, str, ...] A list of strings (with new lines) holding parameter data for a CMT. Returns ------- d : dict A multi-level dict mapping names (deduced from comments) to parameter values.holding parameter values. ''' cmtdict = {} pftblock = detect_block_with_pft_info(cmtdatablock) hdr_cmtkey, txtcmtname, hdrcomment = parse_header_line(cmtdatablock) cmtdict['tag'] = hdr_cmtkey cmtdict['cmtname'] = txtcmtname cmtdict['comment'] = hdrcomment if pftblock: # Look at the second line for something like this: # PFT name line, like: "//Decid. E.green ...." pftlist = cmtdatablock[1].strip("//").strip().split() pftnames = pftlist[0:10] for i, pftname in enumerate(pftnames): cmtdict['pft%i'%i] = {} cmtdict['pft%i'%i]['name'] = pftname for i, line in enumerate(cmtdatablock): if line.strip()[0:2] == "//": #print "passing line", i continue # Nothing to do...commented line else: # normal data line dline = line.strip().split("//") values = dline[0].split() comment = dline[1].strip().strip("//").split(':')[0] if len(values) >= 5: # <--ARBITRARY! likely a pft data line? for i, value in enumerate(values): cmtdict['pft%i'%i][comment] = float(value) else: cmtdict[comment] = float(values[0]) return cmtdict def format_CMTdatadict(dd, refFile, format=None): ''' Returns a formatted block of CMT data. Parameters ---------- dd : dict Dictionary containing parameter names and values for a CMT. refFile : str A path to a file that should be used for reference in formatting the output. format : str (optional) A string specifying which format to return. Defaults to None. Returns ------- d : [str, str, ...] A list of strings ''' if format is not None: print "NOT IMPLEMENTED YET!" exit(-1) ref_order = generate_reference_order(refFile) dwpftvs = False ll = [] ll.append("// First line comment...") ll.append("// Second line comment (?? PFT string?)") def is_pft_var(v): if v not in dd.keys() and v in dd['pft0'].keys(): return True else: return False for var in ref_order: if not is_pft_var(var): pass else: # get each item from dict, append to line linestring = '' for pft in get_datablock_pftkeys(dd): linestring += "{:>12.6f} ".format(dd[pft][var]) linestring += ('// %s: ' % var) ll.append(linestring) for var in ref_order: if is_pft_var(var): pass # Nothing to do; already did pft stuff else: # get item from dict, append to line ll.append('{:<12.5f} // comment??'.format(dd[var])) return ll def generate_reference_order(aFile): ''' Lists order that variables should be in in a parameter file based on CMT 0. Parameters ---------- aFile: str The file to use as a base. Returns ------- l : [str, str, ...] A list of strings containing the variable names, parsed from the input file in the order they appear in the input file. ''' cmt_calparbgc = [] db = get_CMT_datablock(aFile, 0) pftblock = detect_block_with_pft_info(db) ref_order = [] for line in db: t = comment_splitter(line) if t[0] == '': pass # nothing before the comment, ignore this line - is has no data else: # looks like t0 has some data, so now we need the # comment (t[1]) which we will further refine to get the # tag, which we will append to the "reference order" list tokens = t[1].strip().lstrip("//").strip().split(":") tag = tokens[0] desc = "".join(tokens[1:]) print "Found tag:", tag, " Desc: ", desc ref_order.append(tag) return ref_order def comment_splitter(line): ''' Splits a string into data before comment and after comment. The comment delimiter ('//') will be included in the after component. Parameters ---------- line : str A string representing the line of data. May or may not contain the comment delimiter. Returns ------- t : (str, str) - Tuple of strings. A tuple containing the "before comment" string, and the "after comment" string. The "after commnet" string will include the comment charachter. ''' cmtidx = line.find("//") if cmtidx < 0: return (line, '') else: return (line[0:cmtidx], line[cmtidx:]) def get_datablock_pftkeys(dd): ''' Returns a sorted list of the pft keys present in a CMT data dictionary. Parameters ---------- dd : dict A CMT data dictionary (as might be created from cmtdatablock2dict(..)). Returns ------- A sorted list of the keys present in dd that contain the string 'pft'. ''' return sorted([i for i in dd.keys() if 'pft' in i]) def enforce_initvegc_split(aFile, cmtnum): ''' Makes sure that the 'cpart' compartments variables match the proportions set in initvegc variables in a cmt_bgcvegetation.txt file. The initvegc(leaf, wood, root) variables in cmt_bgcvegetation.txt are the measured values from literature. The cpar(leaf, wood, root) variables, which are in the same file, should be set to the fractional make up of the the components. So if the initvegc values for l, w, r are 100, 200, 300, then the cpart values should be 0.166, 0.33, and 0.5. It is very easy for these values to get out of sync when users manually update the parameter file. Parameters ---------- aFile : str Path to a parameter file to work on. Must have bgcvegetation.txt in the name and must be a 'bgcvegetation' parameter file for this function to make sense and work. cmtnum : int The community number in the file to work on. Returns ------- d : dict A CMT data dictionary with the updated cpart values. ''' if ('bgcvegetation.txt' not in aFile): raise ValueError("This function only makes sense on cmt_bgcvegetation.txt files.") d = get_CMT_datablock(aFile, cmtnum) dd = cmtdatablock2dict(d) for pft in get_datablock_pftkeys(dd): sumC = dd[pft]['initvegcl'] + dd[pft]['initvegcw'] + dd[pft]['initvegcr'] if sumC > 0.0: dd[pft]['cpartl'] = dd[pft]['initvegcl'] / sumC dd[pft]['cpartw'] = dd[pft]['initvegcw'] / sumC dd[pft]['cpartr'] = dd[pft]['initvegcr'] / sumC else: dd[pft]['cpartl'] = 0.0 dd[pft]['cpartw'] = 0.0 dd[pft]['cpartr'] = 0.0 return dd if __name__ == '__main__': print "NOTE! Does not work correctly on non-PFT files yet!!" testFiles = [ 'parameters/cmt_calparbgc.txt', 'parameters/cmt_bgcsoil.txt', 'parameters/cmt_bgcvegetation.txt', 'parameters/cmt_calparbgc.txt.backupsomeparams', 'parameters/cmt_dimground.txt', 'parameters/cmt_dimvegetation.txt', 'parameters/cmt_envcanopy.txt', 'parameters/cmt_envground.txt', 'parameters/cmt_firepar.txt' ] for i in testFiles: print "{:>45s}: {}".format(i, get_CMTs_in_file(i)) # for i in testFiles: # print "{:>45s}".format(i) # print "".join(get_CMT_datablock(i, 2)) # print "{:45s}".format("DONE") d = get_CMT_datablock(testFiles[4], 2) print "".join(d) print json.dumps(cmtdatablock2dict(d), sort_keys=True, indent=2) print "NOTE! Does not work correctly on non-PFT files yet!!"
get_pft_verbose_name
identifier_name
param_util.py
#!/usr/bin/env python # T. Carman # January 2017 import os import json def get_CMTs_in_file(aFile): ''' Gets a list of the CMTs found in a file. Parameters ---------- aFile : string, required The path to a file to read. Returns ------- A list of CMTs found in a file. ''' data = read_paramfile(aFile) cmtkey_list = [] for line in data: if line.find('CMT') >= 0: sidx = line.find('CMT') cmtkey_list.append(line[sidx:sidx+5]) return cmtkey_list def find_cmt_start_idx(data, cmtkey): ''' Finds the starting index for a CMT data block in a list of lines. Parameters ---------- data : [str, str, ...] A list of strings (maybe from a parameter file) cmtkey : str A a CMT code string like 'CMT05' to search for in the list. Returns ------- i : int The first index in the list where the CMT key is found. If key is not found returns None. ''' for i, line in enumerate(data): if cmtkey.upper() in line: return i # Key not found return None def read_paramfile(thefile): ''' Opens and reads a file, returning the data as a list of lines (with newlines). Parameters ---------- theFile : str A path to a file to open and read. Returns ------- d : [str, str, str, ...] A list of strings (with newlines at the end of each string). ''' with open(thefile, 'r') as f: data = f.readlines() return data def get_CMT_datablock(afile, cmtnum): ''' Search file, returns the first block of data for one CMT as a list of strings. Parameters ---------- afile : str Path to a file to search. cmtnum : int The CMT number to search for. Converted (internally) to the CMT key. Returns ------- d : [str, str, ...] A list of strings, one item for each line in the CMT's datablock. Each string will have a newline charachter in it. ''' data = read_paramfile(afile) cmtkey = 'CMT%02i' % cmtnum startidx = find_cmt_start_idx(data, cmtkey) end = None for i, line in enumerate(data[startidx:]): if i == 0: # Header line, e.g.: "// CMT07 // Heath Tundra - (ma....."" pass elif i == 1: # PFT name line, e,g.: "//Decid. E.green ...." # Not sure how/why this is working on non-PFT data blocks # but is seems to do the trick? pass if (i > 0) and "CMT" in line: #print "end of datablock, i=", i end = startidx + i break return data[startidx:end] def detect_block_with_pft_info(cmtdatablock): # Perhaps should look at all lines?? secondline = cmtdatablock[1].strip("//").split() if len(secondline) >= 9: #print "Looks like a PFT header line!" return True else: return False def parse_header_line(datablock):
def get_pft_verbose_name(cmtkey=None, pftkey=None, cmtnum=None, pftnum=None): path2params = os.path.join(os.path.split(os.path.dirname(os.path.realpath(__file__)))[0], 'parameters/') if cmtkey and cmtnum: raise ValueError("you must provide only one of you cmtkey or cmtnumber") if pftkey and pftnum: raise ValueError("you must provide only one of pftkey or pftnumber") if cmtkey: # convert to number cmtnum = int(cmtkey.lstrip('CMT')) if pftnum: # convert to key pftkey = 'pft%i' % pftnum data = get_CMT_datablock(os.path.join(path2params, 'cmt_calparbgc.txt'), cmtnum) dd = cmtdatablock2dict(data) return dd[pftkey.lower()]['name'] def cmtdatablock2dict(cmtdatablock): ''' Converts a "CMT datablock" (list of strings) into a dict structure. Parameters ---------- cmtdatablock : [str, str, ...] A list of strings (with new lines) holding parameter data for a CMT. Returns ------- d : dict A multi-level dict mapping names (deduced from comments) to parameter values.holding parameter values. ''' cmtdict = {} pftblock = detect_block_with_pft_info(cmtdatablock) hdr_cmtkey, txtcmtname, hdrcomment = parse_header_line(cmtdatablock) cmtdict['tag'] = hdr_cmtkey cmtdict['cmtname'] = txtcmtname cmtdict['comment'] = hdrcomment if pftblock: # Look at the second line for something like this: # PFT name line, like: "//Decid. E.green ...." pftlist = cmtdatablock[1].strip("//").strip().split() pftnames = pftlist[0:10] for i, pftname in enumerate(pftnames): cmtdict['pft%i'%i] = {} cmtdict['pft%i'%i]['name'] = pftname for i, line in enumerate(cmtdatablock): if line.strip()[0:2] == "//": #print "passing line", i continue # Nothing to do...commented line else: # normal data line dline = line.strip().split("//") values = dline[0].split() comment = dline[1].strip().strip("//").split(':')[0] if len(values) >= 5: # <--ARBITRARY! likely a pft data line? for i, value in enumerate(values): cmtdict['pft%i'%i][comment] = float(value) else: cmtdict[comment] = float(values[0]) return cmtdict def format_CMTdatadict(dd, refFile, format=None): ''' Returns a formatted block of CMT data. Parameters ---------- dd : dict Dictionary containing parameter names and values for a CMT. refFile : str A path to a file that should be used for reference in formatting the output. format : str (optional) A string specifying which format to return. Defaults to None. Returns ------- d : [str, str, ...] A list of strings ''' if format is not None: print "NOT IMPLEMENTED YET!" exit(-1) ref_order = generate_reference_order(refFile) dwpftvs = False ll = [] ll.append("// First line comment...") ll.append("// Second line comment (?? PFT string?)") def is_pft_var(v): if v not in dd.keys() and v in dd['pft0'].keys(): return True else: return False for var in ref_order: if not is_pft_var(var): pass else: # get each item from dict, append to line linestring = '' for pft in get_datablock_pftkeys(dd): linestring += "{:>12.6f} ".format(dd[pft][var]) linestring += ('// %s: ' % var) ll.append(linestring) for var in ref_order: if is_pft_var(var): pass # Nothing to do; already did pft stuff else: # get item from dict, append to line ll.append('{:<12.5f} // comment??'.format(dd[var])) return ll def generate_reference_order(aFile): ''' Lists order that variables should be in in a parameter file based on CMT 0. Parameters ---------- aFile: str The file to use as a base. Returns ------- l : [str, str, ...] A list of strings containing the variable names, parsed from the input file in the order they appear in the input file. ''' cmt_calparbgc = [] db = get_CMT_datablock(aFile, 0) pftblock = detect_block_with_pft_info(db) ref_order = [] for line in db: t = comment_splitter(line) if t[0] == '': pass # nothing before the comment, ignore this line - is has no data else: # looks like t0 has some data, so now we need the # comment (t[1]) which we will further refine to get the # tag, which we will append to the "reference order" list tokens = t[1].strip().lstrip("//").strip().split(":") tag = tokens[0] desc = "".join(tokens[1:]) print "Found tag:", tag, " Desc: ", desc ref_order.append(tag) return ref_order def comment_splitter(line): ''' Splits a string into data before comment and after comment. The comment delimiter ('//') will be included in the after component. Parameters ---------- line : str A string representing the line of data. May or may not contain the comment delimiter. Returns ------- t : (str, str) - Tuple of strings. A tuple containing the "before comment" string, and the "after comment" string. The "after commnet" string will include the comment charachter. ''' cmtidx = line.find("//") if cmtidx < 0: return (line, '') else: return (line[0:cmtidx], line[cmtidx:]) def get_datablock_pftkeys(dd): ''' Returns a sorted list of the pft keys present in a CMT data dictionary. Parameters ---------- dd : dict A CMT data dictionary (as might be created from cmtdatablock2dict(..)). Returns ------- A sorted list of the keys present in dd that contain the string 'pft'. ''' return sorted([i for i in dd.keys() if 'pft' in i]) def enforce_initvegc_split(aFile, cmtnum): ''' Makes sure that the 'cpart' compartments variables match the proportions set in initvegc variables in a cmt_bgcvegetation.txt file. The initvegc(leaf, wood, root) variables in cmt_bgcvegetation.txt are the measured values from literature. The cpar(leaf, wood, root) variables, which are in the same file, should be set to the fractional make up of the the components. So if the initvegc values for l, w, r are 100, 200, 300, then the cpart values should be 0.166, 0.33, and 0.5. It is very easy for these values to get out of sync when users manually update the parameter file. Parameters ---------- aFile : str Path to a parameter file to work on. Must have bgcvegetation.txt in the name and must be a 'bgcvegetation' parameter file for this function to make sense and work. cmtnum : int The community number in the file to work on. Returns ------- d : dict A CMT data dictionary with the updated cpart values. ''' if ('bgcvegetation.txt' not in aFile): raise ValueError("This function only makes sense on cmt_bgcvegetation.txt files.") d = get_CMT_datablock(aFile, cmtnum) dd = cmtdatablock2dict(d) for pft in get_datablock_pftkeys(dd): sumC = dd[pft]['initvegcl'] + dd[pft]['initvegcw'] + dd[pft]['initvegcr'] if sumC > 0.0: dd[pft]['cpartl'] = dd[pft]['initvegcl'] / sumC dd[pft]['cpartw'] = dd[pft]['initvegcw'] / sumC dd[pft]['cpartr'] = dd[pft]['initvegcr'] / sumC else: dd[pft]['cpartl'] = 0.0 dd[pft]['cpartw'] = 0.0 dd[pft]['cpartr'] = 0.0 return dd if __name__ == '__main__': print "NOTE! Does not work correctly on non-PFT files yet!!" testFiles = [ 'parameters/cmt_calparbgc.txt', 'parameters/cmt_bgcsoil.txt', 'parameters/cmt_bgcvegetation.txt', 'parameters/cmt_calparbgc.txt.backupsomeparams', 'parameters/cmt_dimground.txt', 'parameters/cmt_dimvegetation.txt', 'parameters/cmt_envcanopy.txt', 'parameters/cmt_envground.txt', 'parameters/cmt_firepar.txt' ] for i in testFiles: print "{:>45s}: {}".format(i, get_CMTs_in_file(i)) # for i in testFiles: # print "{:>45s}".format(i) # print "".join(get_CMT_datablock(i, 2)) # print "{:45s}".format("DONE") d = get_CMT_datablock(testFiles[4], 2) print "".join(d) print json.dumps(cmtdatablock2dict(d), sort_keys=True, indent=2) print "NOTE! Does not work correctly on non-PFT files yet!!"
'''Splits a header line into components: cmtkey, text name, comment. Assumes a CMT block header line looks like this: // CMT07 // Heath Tundra - (ma..... ''' # Assume header is first line l0 = datablock[0] # Header line, e.g: header = l0.strip().strip("//").strip().split("//") hdr_cmtkey = header[0].strip() txtcmtname = header[1].strip().split('-')[0].strip() hdrcomment = header[1].strip().split('-')[1].strip() return hdr_cmtkey, txtcmtname, hdrcomment
identifier_body
param_util.py
#!/usr/bin/env python # T. Carman # January 2017 import os import json def get_CMTs_in_file(aFile): ''' Gets a list of the CMTs found in a file. Parameters ---------- aFile : string, required The path to a file to read. Returns ------- A list of CMTs found in a file. ''' data = read_paramfile(aFile) cmtkey_list = [] for line in data: if line.find('CMT') >= 0: sidx = line.find('CMT') cmtkey_list.append(line[sidx:sidx+5]) return cmtkey_list def find_cmt_start_idx(data, cmtkey): ''' Finds the starting index for a CMT data block in a list of lines. Parameters ---------- data : [str, str, ...] A list of strings (maybe from a parameter file) cmtkey : str A a CMT code string like 'CMT05' to search for in the list. Returns ------- i : int The first index in the list where the CMT key is found. If key is not found returns None. ''' for i, line in enumerate(data): if cmtkey.upper() in line: return i # Key not found return None def read_paramfile(thefile): ''' Opens and reads a file, returning the data as a list of lines (with newlines). Parameters ---------- theFile : str A path to a file to open and read. Returns ------- d : [str, str, str, ...] A list of strings (with newlines at the end of each string). ''' with open(thefile, 'r') as f: data = f.readlines() return data def get_CMT_datablock(afile, cmtnum): ''' Search file, returns the first block of data for one CMT as a list of strings. Parameters ---------- afile : str Path to a file to search. cmtnum : int The CMT number to search for. Converted (internally) to the CMT key. Returns ------- d : [str, str, ...] A list of strings, one item for each line in the CMT's datablock. Each string will have a newline charachter in it. ''' data = read_paramfile(afile) cmtkey = 'CMT%02i' % cmtnum startidx = find_cmt_start_idx(data, cmtkey) end = None for i, line in enumerate(data[startidx:]): if i == 0: # Header line, e.g.: "// CMT07 // Heath Tundra - (ma....."" pass elif i == 1: # PFT name line, e,g.: "//Decid. E.green ...." # Not sure how/why this is working on non-PFT data blocks # but is seems to do the trick? pass if (i > 0) and "CMT" in line: #print "end of datablock, i=", i end = startidx + i break return data[startidx:end] def detect_block_with_pft_info(cmtdatablock): # Perhaps should look at all lines?? secondline = cmtdatablock[1].strip("//").split() if len(secondline) >= 9: #print "Looks like a PFT header line!" return True else: return False def parse_header_line(datablock): '''Splits a header line into components: cmtkey, text name, comment. Assumes a CMT block header line looks like this: // CMT07 // Heath Tundra - (ma..... ''' # Assume header is first line l0 = datablock[0] # Header line, e.g: header = l0.strip().strip("//").strip().split("//") hdr_cmtkey = header[0].strip() txtcmtname = header[1].strip().split('-')[0].strip() hdrcomment = header[1].strip().split('-')[1].strip() return hdr_cmtkey, txtcmtname, hdrcomment def get_pft_verbose_name(cmtkey=None, pftkey=None, cmtnum=None, pftnum=None): path2params = os.path.join(os.path.split(os.path.dirname(os.path.realpath(__file__)))[0], 'parameters/') if cmtkey and cmtnum: raise ValueError("you must provide only one of you cmtkey or cmtnumber") if pftkey and pftnum: raise ValueError("you must provide only one of pftkey or pftnumber") if cmtkey: # convert to number cmtnum = int(cmtkey.lstrip('CMT')) if pftnum: # convert to key pftkey = 'pft%i' % pftnum data = get_CMT_datablock(os.path.join(path2params, 'cmt_calparbgc.txt'), cmtnum) dd = cmtdatablock2dict(data) return dd[pftkey.lower()]['name'] def cmtdatablock2dict(cmtdatablock): ''' Converts a "CMT datablock" (list of strings) into a dict structure. Parameters ---------- cmtdatablock : [str, str, ...] A list of strings (with new lines) holding parameter data for a CMT. Returns ------- d : dict A multi-level dict mapping names (deduced from comments) to parameter values.holding parameter values. ''' cmtdict = {} pftblock = detect_block_with_pft_info(cmtdatablock) hdr_cmtkey, txtcmtname, hdrcomment = parse_header_line(cmtdatablock) cmtdict['tag'] = hdr_cmtkey cmtdict['cmtname'] = txtcmtname cmtdict['comment'] = hdrcomment if pftblock: # Look at the second line for something like this: # PFT name line, like: "//Decid. E.green ...." pftlist = cmtdatablock[1].strip("//").strip().split() pftnames = pftlist[0:10] for i, pftname in enumerate(pftnames): cmtdict['pft%i'%i] = {} cmtdict['pft%i'%i]['name'] = pftname for i, line in enumerate(cmtdatablock): if line.strip()[0:2] == "//": #print "passing line", i
else: # normal data line dline = line.strip().split("//") values = dline[0].split() comment = dline[1].strip().strip("//").split(':')[0] if len(values) >= 5: # <--ARBITRARY! likely a pft data line? for i, value in enumerate(values): cmtdict['pft%i'%i][comment] = float(value) else: cmtdict[comment] = float(values[0]) return cmtdict def format_CMTdatadict(dd, refFile, format=None): ''' Returns a formatted block of CMT data. Parameters ---------- dd : dict Dictionary containing parameter names and values for a CMT. refFile : str A path to a file that should be used for reference in formatting the output. format : str (optional) A string specifying which format to return. Defaults to None. Returns ------- d : [str, str, ...] A list of strings ''' if format is not None: print "NOT IMPLEMENTED YET!" exit(-1) ref_order = generate_reference_order(refFile) dwpftvs = False ll = [] ll.append("// First line comment...") ll.append("// Second line comment (?? PFT string?)") def is_pft_var(v): if v not in dd.keys() and v in dd['pft0'].keys(): return True else: return False for var in ref_order: if not is_pft_var(var): pass else: # get each item from dict, append to line linestring = '' for pft in get_datablock_pftkeys(dd): linestring += "{:>12.6f} ".format(dd[pft][var]) linestring += ('// %s: ' % var) ll.append(linestring) for var in ref_order: if is_pft_var(var): pass # Nothing to do; already did pft stuff else: # get item from dict, append to line ll.append('{:<12.5f} // comment??'.format(dd[var])) return ll def generate_reference_order(aFile): ''' Lists order that variables should be in in a parameter file based on CMT 0. Parameters ---------- aFile: str The file to use as a base. Returns ------- l : [str, str, ...] A list of strings containing the variable names, parsed from the input file in the order they appear in the input file. ''' cmt_calparbgc = [] db = get_CMT_datablock(aFile, 0) pftblock = detect_block_with_pft_info(db) ref_order = [] for line in db: t = comment_splitter(line) if t[0] == '': pass # nothing before the comment, ignore this line - is has no data else: # looks like t0 has some data, so now we need the # comment (t[1]) which we will further refine to get the # tag, which we will append to the "reference order" list tokens = t[1].strip().lstrip("//").strip().split(":") tag = tokens[0] desc = "".join(tokens[1:]) print "Found tag:", tag, " Desc: ", desc ref_order.append(tag) return ref_order def comment_splitter(line): ''' Splits a string into data before comment and after comment. The comment delimiter ('//') will be included in the after component. Parameters ---------- line : str A string representing the line of data. May or may not contain the comment delimiter. Returns ------- t : (str, str) - Tuple of strings. A tuple containing the "before comment" string, and the "after comment" string. The "after commnet" string will include the comment charachter. ''' cmtidx = line.find("//") if cmtidx < 0: return (line, '') else: return (line[0:cmtidx], line[cmtidx:]) def get_datablock_pftkeys(dd): ''' Returns a sorted list of the pft keys present in a CMT data dictionary. Parameters ---------- dd : dict A CMT data dictionary (as might be created from cmtdatablock2dict(..)). Returns ------- A sorted list of the keys present in dd that contain the string 'pft'. ''' return sorted([i for i in dd.keys() if 'pft' in i]) def enforce_initvegc_split(aFile, cmtnum): ''' Makes sure that the 'cpart' compartments variables match the proportions set in initvegc variables in a cmt_bgcvegetation.txt file. The initvegc(leaf, wood, root) variables in cmt_bgcvegetation.txt are the measured values from literature. The cpar(leaf, wood, root) variables, which are in the same file, should be set to the fractional make up of the the components. So if the initvegc values for l, w, r are 100, 200, 300, then the cpart values should be 0.166, 0.33, and 0.5. It is very easy for these values to get out of sync when users manually update the parameter file. Parameters ---------- aFile : str Path to a parameter file to work on. Must have bgcvegetation.txt in the name and must be a 'bgcvegetation' parameter file for this function to make sense and work. cmtnum : int The community number in the file to work on. Returns ------- d : dict A CMT data dictionary with the updated cpart values. ''' if ('bgcvegetation.txt' not in aFile): raise ValueError("This function only makes sense on cmt_bgcvegetation.txt files.") d = get_CMT_datablock(aFile, cmtnum) dd = cmtdatablock2dict(d) for pft in get_datablock_pftkeys(dd): sumC = dd[pft]['initvegcl'] + dd[pft]['initvegcw'] + dd[pft]['initvegcr'] if sumC > 0.0: dd[pft]['cpartl'] = dd[pft]['initvegcl'] / sumC dd[pft]['cpartw'] = dd[pft]['initvegcw'] / sumC dd[pft]['cpartr'] = dd[pft]['initvegcr'] / sumC else: dd[pft]['cpartl'] = 0.0 dd[pft]['cpartw'] = 0.0 dd[pft]['cpartr'] = 0.0 return dd if __name__ == '__main__': print "NOTE! Does not work correctly on non-PFT files yet!!" testFiles = [ 'parameters/cmt_calparbgc.txt', 'parameters/cmt_bgcsoil.txt', 'parameters/cmt_bgcvegetation.txt', 'parameters/cmt_calparbgc.txt.backupsomeparams', 'parameters/cmt_dimground.txt', 'parameters/cmt_dimvegetation.txt', 'parameters/cmt_envcanopy.txt', 'parameters/cmt_envground.txt', 'parameters/cmt_firepar.txt' ] for i in testFiles: print "{:>45s}: {}".format(i, get_CMTs_in_file(i)) # for i in testFiles: # print "{:>45s}".format(i) # print "".join(get_CMT_datablock(i, 2)) # print "{:45s}".format("DONE") d = get_CMT_datablock(testFiles[4], 2) print "".join(d) print json.dumps(cmtdatablock2dict(d), sort_keys=True, indent=2) print "NOTE! Does not work correctly on non-PFT files yet!!"
continue # Nothing to do...commented line
conditional_block
param_util.py
#!/usr/bin/env python # T. Carman # January 2017 import os import json def get_CMTs_in_file(aFile): ''' Gets a list of the CMTs found in a file. Parameters ---------- aFile : string, required The path to a file to read. Returns ------- A list of CMTs found in a file. ''' data = read_paramfile(aFile) cmtkey_list = [] for line in data: if line.find('CMT') >= 0: sidx = line.find('CMT') cmtkey_list.append(line[sidx:sidx+5]) return cmtkey_list def find_cmt_start_idx(data, cmtkey): ''' Finds the starting index for a CMT data block in a list of lines. Parameters ---------- data : [str, str, ...] A list of strings (maybe from a parameter file) cmtkey : str A a CMT code string like 'CMT05' to search for in the list. Returns ------- i : int The first index in the list where the CMT key is found. If key is not found returns None. ''' for i, line in enumerate(data): if cmtkey.upper() in line: return i # Key not found return None def read_paramfile(thefile): ''' Opens and reads a file, returning the data as a list of lines (with newlines). Parameters ---------- theFile : str A path to a file to open and read. Returns ------- d : [str, str, str, ...] A list of strings (with newlines at the end of each string). ''' with open(thefile, 'r') as f: data = f.readlines() return data def get_CMT_datablock(afile, cmtnum): ''' Search file, returns the first block of data for one CMT as a list of strings. Parameters ---------- afile : str Path to a file to search. cmtnum : int The CMT number to search for. Converted (internally) to the CMT key. Returns ------- d : [str, str, ...] A list of strings, one item for each line in the CMT's datablock. Each string will have a newline charachter in it. ''' data = read_paramfile(afile) cmtkey = 'CMT%02i' % cmtnum startidx = find_cmt_start_idx(data, cmtkey) end = None for i, line in enumerate(data[startidx:]): if i == 0: # Header line, e.g.: "// CMT07 // Heath Tundra - (ma....."" pass elif i == 1: # PFT name line, e,g.: "//Decid. E.green ...." # Not sure how/why this is working on non-PFT data blocks # but is seems to do the trick? pass if (i > 0) and "CMT" in line: #print "end of datablock, i=", i end = startidx + i break return data[startidx:end] def detect_block_with_pft_info(cmtdatablock): # Perhaps should look at all lines?? secondline = cmtdatablock[1].strip("//").split() if len(secondline) >= 9: #print "Looks like a PFT header line!" return True else: return False def parse_header_line(datablock): '''Splits a header line into components: cmtkey, text name, comment. Assumes a CMT block header line looks like this: // CMT07 // Heath Tundra - (ma.....
# Assume header is first line l0 = datablock[0] # Header line, e.g: header = l0.strip().strip("//").strip().split("//") hdr_cmtkey = header[0].strip() txtcmtname = header[1].strip().split('-')[0].strip() hdrcomment = header[1].strip().split('-')[1].strip() return hdr_cmtkey, txtcmtname, hdrcomment def get_pft_verbose_name(cmtkey=None, pftkey=None, cmtnum=None, pftnum=None): path2params = os.path.join(os.path.split(os.path.dirname(os.path.realpath(__file__)))[0], 'parameters/') if cmtkey and cmtnum: raise ValueError("you must provide only one of you cmtkey or cmtnumber") if pftkey and pftnum: raise ValueError("you must provide only one of pftkey or pftnumber") if cmtkey: # convert to number cmtnum = int(cmtkey.lstrip('CMT')) if pftnum: # convert to key pftkey = 'pft%i' % pftnum data = get_CMT_datablock(os.path.join(path2params, 'cmt_calparbgc.txt'), cmtnum) dd = cmtdatablock2dict(data) return dd[pftkey.lower()]['name'] def cmtdatablock2dict(cmtdatablock): ''' Converts a "CMT datablock" (list of strings) into a dict structure. Parameters ---------- cmtdatablock : [str, str, ...] A list of strings (with new lines) holding parameter data for a CMT. Returns ------- d : dict A multi-level dict mapping names (deduced from comments) to parameter values.holding parameter values. ''' cmtdict = {} pftblock = detect_block_with_pft_info(cmtdatablock) hdr_cmtkey, txtcmtname, hdrcomment = parse_header_line(cmtdatablock) cmtdict['tag'] = hdr_cmtkey cmtdict['cmtname'] = txtcmtname cmtdict['comment'] = hdrcomment if pftblock: # Look at the second line for something like this: # PFT name line, like: "//Decid. E.green ...." pftlist = cmtdatablock[1].strip("//").strip().split() pftnames = pftlist[0:10] for i, pftname in enumerate(pftnames): cmtdict['pft%i'%i] = {} cmtdict['pft%i'%i]['name'] = pftname for i, line in enumerate(cmtdatablock): if line.strip()[0:2] == "//": #print "passing line", i continue # Nothing to do...commented line else: # normal data line dline = line.strip().split("//") values = dline[0].split() comment = dline[1].strip().strip("//").split(':')[0] if len(values) >= 5: # <--ARBITRARY! likely a pft data line? for i, value in enumerate(values): cmtdict['pft%i'%i][comment] = float(value) else: cmtdict[comment] = float(values[0]) return cmtdict def format_CMTdatadict(dd, refFile, format=None): ''' Returns a formatted block of CMT data. Parameters ---------- dd : dict Dictionary containing parameter names and values for a CMT. refFile : str A path to a file that should be used for reference in formatting the output. format : str (optional) A string specifying which format to return. Defaults to None. Returns ------- d : [str, str, ...] A list of strings ''' if format is not None: print "NOT IMPLEMENTED YET!" exit(-1) ref_order = generate_reference_order(refFile) dwpftvs = False ll = [] ll.append("// First line comment...") ll.append("// Second line comment (?? PFT string?)") def is_pft_var(v): if v not in dd.keys() and v in dd['pft0'].keys(): return True else: return False for var in ref_order: if not is_pft_var(var): pass else: # get each item from dict, append to line linestring = '' for pft in get_datablock_pftkeys(dd): linestring += "{:>12.6f} ".format(dd[pft][var]) linestring += ('// %s: ' % var) ll.append(linestring) for var in ref_order: if is_pft_var(var): pass # Nothing to do; already did pft stuff else: # get item from dict, append to line ll.append('{:<12.5f} // comment??'.format(dd[var])) return ll def generate_reference_order(aFile): ''' Lists order that variables should be in in a parameter file based on CMT 0. Parameters ---------- aFile: str The file to use as a base. Returns ------- l : [str, str, ...] A list of strings containing the variable names, parsed from the input file in the order they appear in the input file. ''' cmt_calparbgc = [] db = get_CMT_datablock(aFile, 0) pftblock = detect_block_with_pft_info(db) ref_order = [] for line in db: t = comment_splitter(line) if t[0] == '': pass # nothing before the comment, ignore this line - is has no data else: # looks like t0 has some data, so now we need the # comment (t[1]) which we will further refine to get the # tag, which we will append to the "reference order" list tokens = t[1].strip().lstrip("//").strip().split(":") tag = tokens[0] desc = "".join(tokens[1:]) print "Found tag:", tag, " Desc: ", desc ref_order.append(tag) return ref_order def comment_splitter(line): ''' Splits a string into data before comment and after comment. The comment delimiter ('//') will be included in the after component. Parameters ---------- line : str A string representing the line of data. May or may not contain the comment delimiter. Returns ------- t : (str, str) - Tuple of strings. A tuple containing the "before comment" string, and the "after comment" string. The "after commnet" string will include the comment charachter. ''' cmtidx = line.find("//") if cmtidx < 0: return (line, '') else: return (line[0:cmtidx], line[cmtidx:]) def get_datablock_pftkeys(dd): ''' Returns a sorted list of the pft keys present in a CMT data dictionary. Parameters ---------- dd : dict A CMT data dictionary (as might be created from cmtdatablock2dict(..)). Returns ------- A sorted list of the keys present in dd that contain the string 'pft'. ''' return sorted([i for i in dd.keys() if 'pft' in i]) def enforce_initvegc_split(aFile, cmtnum): ''' Makes sure that the 'cpart' compartments variables match the proportions set in initvegc variables in a cmt_bgcvegetation.txt file. The initvegc(leaf, wood, root) variables in cmt_bgcvegetation.txt are the measured values from literature. The cpar(leaf, wood, root) variables, which are in the same file, should be set to the fractional make up of the the components. So if the initvegc values for l, w, r are 100, 200, 300, then the cpart values should be 0.166, 0.33, and 0.5. It is very easy for these values to get out of sync when users manually update the parameter file. Parameters ---------- aFile : str Path to a parameter file to work on. Must have bgcvegetation.txt in the name and must be a 'bgcvegetation' parameter file for this function to make sense and work. cmtnum : int The community number in the file to work on. Returns ------- d : dict A CMT data dictionary with the updated cpart values. ''' if ('bgcvegetation.txt' not in aFile): raise ValueError("This function only makes sense on cmt_bgcvegetation.txt files.") d = get_CMT_datablock(aFile, cmtnum) dd = cmtdatablock2dict(d) for pft in get_datablock_pftkeys(dd): sumC = dd[pft]['initvegcl'] + dd[pft]['initvegcw'] + dd[pft]['initvegcr'] if sumC > 0.0: dd[pft]['cpartl'] = dd[pft]['initvegcl'] / sumC dd[pft]['cpartw'] = dd[pft]['initvegcw'] / sumC dd[pft]['cpartr'] = dd[pft]['initvegcr'] / sumC else: dd[pft]['cpartl'] = 0.0 dd[pft]['cpartw'] = 0.0 dd[pft]['cpartr'] = 0.0 return dd if __name__ == '__main__': print "NOTE! Does not work correctly on non-PFT files yet!!" testFiles = [ 'parameters/cmt_calparbgc.txt', 'parameters/cmt_bgcsoil.txt', 'parameters/cmt_bgcvegetation.txt', 'parameters/cmt_calparbgc.txt.backupsomeparams', 'parameters/cmt_dimground.txt', 'parameters/cmt_dimvegetation.txt', 'parameters/cmt_envcanopy.txt', 'parameters/cmt_envground.txt', 'parameters/cmt_firepar.txt' ] for i in testFiles: print "{:>45s}: {}".format(i, get_CMTs_in_file(i)) # for i in testFiles: # print "{:>45s}".format(i) # print "".join(get_CMT_datablock(i, 2)) # print "{:45s}".format("DONE") d = get_CMT_datablock(testFiles[4], 2) print "".join(d) print json.dumps(cmtdatablock2dict(d), sort_keys=True, indent=2) print "NOTE! Does not work correctly on non-PFT files yet!!"
'''
random_line_split
customize_juropa_icc_libxc.py
compiler = './icc.py' mpicompiler = './icc.py' mpilinker = 'MPICH_CC=gcc mpicc' scalapack = True library_dirs += ['/opt/intel/Compiler/11.0/074/mkl/lib/em64t'] libraries = ['mkl_intel_lp64' ,'mkl_sequential' ,'mkl_core', 'mkl_lapack', 'mkl_scalapack_lp64', 'mkl_blacs_intelmpi_lp64', 'pthread' ] libraries += ['xc'] # change this to your installation directory LIBXCDIR='/lustre/jhome5/hfr04/hfr047/gridpaw/libxc-2.0.2/install/' library_dirs += [LIBXCDIR + 'lib'] include_dirs += [LIBXCDIR + 'include'] define_macros += [('GPAW_NO_UNDERSCORE_CBLACS', '1')]
define_macros += [('GPAW_NO_UNDERSCORE_CSCALAPACK', '1')] define_macros += [("GPAW_ASYNC",1)] define_macros += [("GPAW_MPI2",1)]
random_line_split
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct App { gl: GlGraphics, // OpenGL drawing backend. rotation: f64 // Rotation for the square. } impl App { fn render(&mut self, args: &RenderArgs) { use graphics::*; const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
let square = rectangle::square(0.0, 0.0, 50.0); let rotation = self.rotation; let (x, y) = ((args.width / 2) as f64, (args.height / 2) as f64); self.gl.draw(args.viewport(), |c, gl| { // Clear the screen. clear(GREEN, gl); let transform = c.transform.trans(x, y) .rot_rad(rotation) .trans(-25.0, -25.0); // Draw a box rotating around the middle of the screen. rectangle(RED, square, transform, gl); }); } fn update(&mut self, args: &UpdateArgs) { // Rotate 2 radians per second. self.rotation += 2.0 * args.dt; } } fn main() { // Change this to OpenGL::V2_1 if not working. let opengl = OpenGL::V3_2; // Create an Glutin window. let mut window: Window = WindowSettings::new( "spinning-square", [200, 200] ) .opengl(opengl) .exit_on_esc(true) .build() .unwrap(); // Create a new game and run it. let mut app = App { gl: GlGraphics::new(opengl), rotation: 0.0 }; let mut events = Events::new(EventSettings::new()); while let Some(e) = events.next(&mut window) { if let Some(r) = e.render_args() { app.render(&r); } if let Some(u) = e.update_args() { app.update(&u); } } }
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
random_line_split
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct
{ gl: GlGraphics, // OpenGL drawing backend. rotation: f64 // Rotation for the square. } impl App { fn render(&mut self, args: &RenderArgs) { use graphics::*; const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; let square = rectangle::square(0.0, 0.0, 50.0); let rotation = self.rotation; let (x, y) = ((args.width / 2) as f64, (args.height / 2) as f64); self.gl.draw(args.viewport(), |c, gl| { // Clear the screen. clear(GREEN, gl); let transform = c.transform.trans(x, y) .rot_rad(rotation) .trans(-25.0, -25.0); // Draw a box rotating around the middle of the screen. rectangle(RED, square, transform, gl); }); } fn update(&mut self, args: &UpdateArgs) { // Rotate 2 radians per second. self.rotation += 2.0 * args.dt; } } fn main() { // Change this to OpenGL::V2_1 if not working. let opengl = OpenGL::V3_2; // Create an Glutin window. let mut window: Window = WindowSettings::new( "spinning-square", [200, 200] ) .opengl(opengl) .exit_on_esc(true) .build() .unwrap(); // Create a new game and run it. let mut app = App { gl: GlGraphics::new(opengl), rotation: 0.0 }; let mut events = Events::new(EventSettings::new()); while let Some(e) = events.next(&mut window) { if let Some(r) = e.render_args() { app.render(&r); } if let Some(u) = e.update_args() { app.update(&u); } } }
App
identifier_name
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct App { gl: GlGraphics, // OpenGL drawing backend. rotation: f64 // Rotation for the square. } impl App { fn render(&mut self, args: &RenderArgs) { use graphics::*; const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; let square = rectangle::square(0.0, 0.0, 50.0); let rotation = self.rotation; let (x, y) = ((args.width / 2) as f64, (args.height / 2) as f64); self.gl.draw(args.viewport(), |c, gl| { // Clear the screen. clear(GREEN, gl); let transform = c.transform.trans(x, y) .rot_rad(rotation) .trans(-25.0, -25.0); // Draw a box rotating around the middle of the screen. rectangle(RED, square, transform, gl); }); } fn update(&mut self, args: &UpdateArgs) { // Rotate 2 radians per second. self.rotation += 2.0 * args.dt; } } fn main() { // Change this to OpenGL::V2_1 if not working. let opengl = OpenGL::V3_2; // Create an Glutin window. let mut window: Window = WindowSettings::new( "spinning-square", [200, 200] ) .opengl(opengl) .exit_on_esc(true) .build() .unwrap(); // Create a new game and run it. let mut app = App { gl: GlGraphics::new(opengl), rotation: 0.0 }; let mut events = Events::new(EventSettings::new()); while let Some(e) = events.next(&mut window) { if let Some(r) = e.render_args()
if let Some(u) = e.update_args() { app.update(&u); } } }
{ app.render(&r); }
conditional_block
example.py
class Beer(object): def sing(self, first, last=0): verses = '' for number in reversed(range(last, first + 1)): verses += self.verse(number) + '\n' return verses def verse(self, number): return ''.join([ "%s of beer on the wall, " % self._bottles(number).capitalize(), "%s of beer.\n" % self._bottles(number), self._action(number), self._next_bottle(number), ]) def _action(self, current_verse): if current_verse == 0: return "Go to the store and buy some more, " else: return "Take %s down and pass it around, " % ( "one" if current_verse > 1 else "it" ) def _next_bottle(self, current_verse):
def _bottles(self, number): if number == 0: return 'no more bottles' if number == 1: return '1 bottle' else: return '%d bottles' % number def _next_verse(self, current_verse): return current_verse - 1 if current_verse > 0 else 99
return "%s of beer on the wall.\n" % self._bottles(self._next_verse(current_verse))
identifier_body
example.py
class Beer(object): def sing(self, first, last=0): verses = '' for number in reversed(range(last, first + 1)): verses += self.verse(number) + '\n' return verses def verse(self, number): return ''.join([ "%s of beer on the wall, " % self._bottles(number).capitalize(), "%s of beer.\n" % self._bottles(number), self._action(number), self._next_bottle(number), ]) def
(self, current_verse): if current_verse == 0: return "Go to the store and buy some more, " else: return "Take %s down and pass it around, " % ( "one" if current_verse > 1 else "it" ) def _next_bottle(self, current_verse): return "%s of beer on the wall.\n" % self._bottles(self._next_verse(current_verse)) def _bottles(self, number): if number == 0: return 'no more bottles' if number == 1: return '1 bottle' else: return '%d bottles' % number def _next_verse(self, current_verse): return current_verse - 1 if current_verse > 0 else 99
_action
identifier_name
example.py
class Beer(object): def sing(self, first, last=0): verses = '' for number in reversed(range(last, first + 1)): verses += self.verse(number) + '\n' return verses def verse(self, number): return ''.join([ "%s of beer on the wall, " % self._bottles(number).capitalize(), "%s of beer.\n" % self._bottles(number), self._action(number), self._next_bottle(number), ]) def _action(self, current_verse): if current_verse == 0:
"one" if current_verse > 1 else "it" ) def _next_bottle(self, current_verse): return "%s of beer on the wall.\n" % self._bottles(self._next_verse(current_verse)) def _bottles(self, number): if number == 0: return 'no more bottles' if number == 1: return '1 bottle' else: return '%d bottles' % number def _next_verse(self, current_verse): return current_verse - 1 if current_verse > 0 else 99
return "Go to the store and buy some more, " else: return "Take %s down and pass it around, " % (
random_line_split
example.py
class Beer(object): def sing(self, first, last=0): verses = '' for number in reversed(range(last, first + 1)): verses += self.verse(number) + '\n' return verses def verse(self, number): return ''.join([ "%s of beer on the wall, " % self._bottles(number).capitalize(), "%s of beer.\n" % self._bottles(number), self._action(number), self._next_bottle(number), ]) def _action(self, current_verse): if current_verse == 0:
else: return "Take %s down and pass it around, " % ( "one" if current_verse > 1 else "it" ) def _next_bottle(self, current_verse): return "%s of beer on the wall.\n" % self._bottles(self._next_verse(current_verse)) def _bottles(self, number): if number == 0: return 'no more bottles' if number == 1: return '1 bottle' else: return '%d bottles' % number def _next_verse(self, current_verse): return current_verse - 1 if current_verse > 0 else 99
return "Go to the store and buy some more, "
conditional_block
ngb-calendar-hebrew.ts
import {NgbDate} from '../ngb-date'; import {fromJSDate, NgbCalendar, NgbPeriod, toJSDate} from '../ngb-calendar'; import {Injectable} from '@angular/core'; import {isNumber} from '../../util/util'; import { fromGregorian, getDayNumberInHebrewYear, getDaysInHebrewMonth, isHebrewLeapYear, toGregorian, setHebrewDay, setHebrewMonth } from './hebrew'; /** * @since 3.2.0 */ @Injectable() export class NgbCalendarHebrew extends NgbCalendar {
() { return 7; } getMonths(year?: number) { if (year && isHebrewLeapYear(year)) { return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; } else { return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; } } getWeeksPerMonth() { return 6; } isValid(date?: NgbDate | null): boolean { if (date != null) { let b = isNumber(date.year) && isNumber(date.month) && isNumber(date.day); b = b && date.month > 0 && date.month <= (isHebrewLeapYear(date.year) ? 13 : 12); b = b && date.day > 0 && date.day <= getDaysInHebrewMonth(date.month, date.year); return b && !isNaN(toGregorian(date).getTime()); } return false; } getNext(date: NgbDate, period: NgbPeriod = 'd', number = 1) { date = new NgbDate(date.year, date.month, date.day); switch (period) { case 'y': date.year += number; date.month = 1; date.day = 1; return date; case 'm': date = setHebrewMonth(date, number); date.day = 1; return date; case 'd': return setHebrewDay(date, number); default: return date; } } getPrev(date: NgbDate, period: NgbPeriod = 'd', number = 1) { return this.getNext(date, period, -number); } getWeekday(date: NgbDate) { const day = toGregorian(date).getDay(); // in JS Date Sun=0, in ISO 8601 Sun=7 return day === 0 ? 7 : day; } getWeekNumber(week: readonly NgbDate[], firstDayOfWeek: number) { const date = week[week.length - 1]; return Math.ceil(getDayNumberInHebrewYear(date) / 7); } getToday(): NgbDate { return fromGregorian(new Date()); } /** * @since 3.4.0 */ toGregorian(date: NgbDate): NgbDate { return fromJSDate(toGregorian(date)); } /** * @since 3.4.0 */ fromGregorian(date: NgbDate): NgbDate { return fromGregorian(toJSDate(date)); } }
getDaysPerWeek
identifier_name
ngb-calendar-hebrew.ts
import {NgbDate} from '../ngb-date'; import {fromJSDate, NgbCalendar, NgbPeriod, toJSDate} from '../ngb-calendar'; import {Injectable} from '@angular/core'; import {isNumber} from '../../util/util'; import { fromGregorian, getDayNumberInHebrewYear, getDaysInHebrewMonth, isHebrewLeapYear, toGregorian, setHebrewDay, setHebrewMonth } from './hebrew'; /** * @since 3.2.0 */ @Injectable() export class NgbCalendarHebrew extends NgbCalendar { getDaysPerWeek() { return 7; } getMonths(year?: number) { if (year && isHebrewLeapYear(year)) { return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; } else { return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; } } getWeeksPerMonth() { return 6; } isValid(date?: NgbDate | null): boolean { if (date != null) { let b = isNumber(date.year) && isNumber(date.month) && isNumber(date.day); b = b && date.month > 0 && date.month <= (isHebrewLeapYear(date.year) ? 13 : 12); b = b && date.day > 0 && date.day <= getDaysInHebrewMonth(date.month, date.year); return b && !isNaN(toGregorian(date).getTime()); } return false; } getNext(date: NgbDate, period: NgbPeriod = 'd', number = 1) { date = new NgbDate(date.year, date.month, date.day); switch (period) { case 'y': date.year += number; date.month = 1; date.day = 1; return date;
date = setHebrewMonth(date, number); date.day = 1; return date; case 'd': return setHebrewDay(date, number); default: return date; } } getPrev(date: NgbDate, period: NgbPeriod = 'd', number = 1) { return this.getNext(date, period, -number); } getWeekday(date: NgbDate) { const day = toGregorian(date).getDay(); // in JS Date Sun=0, in ISO 8601 Sun=7 return day === 0 ? 7 : day; } getWeekNumber(week: readonly NgbDate[], firstDayOfWeek: number) { const date = week[week.length - 1]; return Math.ceil(getDayNumberInHebrewYear(date) / 7); } getToday(): NgbDate { return fromGregorian(new Date()); } /** * @since 3.4.0 */ toGregorian(date: NgbDate): NgbDate { return fromJSDate(toGregorian(date)); } /** * @since 3.4.0 */ fromGregorian(date: NgbDate): NgbDate { return fromGregorian(toJSDate(date)); } }
case 'm':
random_line_split
ngb-calendar-hebrew.ts
import {NgbDate} from '../ngb-date'; import {fromJSDate, NgbCalendar, NgbPeriod, toJSDate} from '../ngb-calendar'; import {Injectable} from '@angular/core'; import {isNumber} from '../../util/util'; import { fromGregorian, getDayNumberInHebrewYear, getDaysInHebrewMonth, isHebrewLeapYear, toGregorian, setHebrewDay, setHebrewMonth } from './hebrew'; /** * @since 3.2.0 */ @Injectable() export class NgbCalendarHebrew extends NgbCalendar { getDaysPerWeek() { return 7; } getMonths(year?: number) { if (year && isHebrewLeapYear(year)) { return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; } else { return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; } } getWeeksPerMonth() { return 6; } isValid(date?: NgbDate | null): boolean { if (date != null) { let b = isNumber(date.year) && isNumber(date.month) && isNumber(date.day); b = b && date.month > 0 && date.month <= (isHebrewLeapYear(date.year) ? 13 : 12); b = b && date.day > 0 && date.day <= getDaysInHebrewMonth(date.month, date.year); return b && !isNaN(toGregorian(date).getTime()); } return false; } getNext(date: NgbDate, period: NgbPeriod = 'd', number = 1) { date = new NgbDate(date.year, date.month, date.day); switch (period) { case 'y': date.year += number; date.month = 1; date.day = 1; return date; case 'm': date = setHebrewMonth(date, number); date.day = 1; return date; case 'd': return setHebrewDay(date, number); default: return date; } } getPrev(date: NgbDate, period: NgbPeriod = 'd', number = 1) { return this.getNext(date, period, -number); } getWeekday(date: NgbDate) { const day = toGregorian(date).getDay(); // in JS Date Sun=0, in ISO 8601 Sun=7 return day === 0 ? 7 : day; } getWeekNumber(week: readonly NgbDate[], firstDayOfWeek: number)
getToday(): NgbDate { return fromGregorian(new Date()); } /** * @since 3.4.0 */ toGregorian(date: NgbDate): NgbDate { return fromJSDate(toGregorian(date)); } /** * @since 3.4.0 */ fromGregorian(date: NgbDate): NgbDate { return fromGregorian(toJSDate(date)); } }
{ const date = week[week.length - 1]; return Math.ceil(getDayNumberInHebrewYear(date) / 7); }
identifier_body
concat2concatws.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import PRIORITY __priority__ = PRIORITY.HIGHEST def dependencies(): pass def
(payload, **kwargs): """ Replaces instances like 'CONCAT(A, B)' with 'CONCAT_WS(MID(CHAR(0), 0, 0), A, B)' Requirement: * MySQL Tested against: * MySQL 5.0 Notes: * Useful to bypass very weak and bespoke web application firewalls that filter the CONCAT() function >>> tamper('CONCAT(1,2)') 'CONCAT_WS(MID(CHAR(0),0,0),1,2)' """ if payload: payload = payload.replace("CONCAT(", "CONCAT_WS(MID(CHAR(0),0,0),") return payload
tamper
identifier_name
concat2concatws.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import PRIORITY __priority__ = PRIORITY.HIGHEST def dependencies(): pass def tamper(payload, **kwargs):
""" Replaces instances like 'CONCAT(A, B)' with 'CONCAT_WS(MID(CHAR(0), 0, 0), A, B)' Requirement: * MySQL Tested against: * MySQL 5.0 Notes: * Useful to bypass very weak and bespoke web application firewalls that filter the CONCAT() function >>> tamper('CONCAT(1,2)') 'CONCAT_WS(MID(CHAR(0),0,0),1,2)' """ if payload: payload = payload.replace("CONCAT(", "CONCAT_WS(MID(CHAR(0),0,0),") return payload
identifier_body
concat2concatws.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import PRIORITY __priority__ = PRIORITY.HIGHEST def dependencies(): pass def tamper(payload, **kwargs): """ Replaces instances like 'CONCAT(A, B)' with 'CONCAT_WS(MID(CHAR(0), 0, 0), A, B)' Requirement: * MySQL Tested against: * MySQL 5.0 Notes: * Useful to bypass very weak and bespoke web application firewalls that filter the CONCAT() function >>> tamper('CONCAT(1,2)') 'CONCAT_WS(MID(CHAR(0),0,0),1,2)' """ if payload:
return payload
payload = payload.replace("CONCAT(", "CONCAT_WS(MID(CHAR(0),0,0),")
conditional_block
concat2concatws.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import PRIORITY __priority__ = PRIORITY.HIGHEST def dependencies(): pass def tamper(payload, **kwargs): """ Replaces instances like 'CONCAT(A, B)' with 'CONCAT_WS(MID(CHAR(0), 0, 0), A, B)' Requirement: * MySQL
* MySQL 5.0 Notes: * Useful to bypass very weak and bespoke web application firewalls that filter the CONCAT() function >>> tamper('CONCAT(1,2)') 'CONCAT_WS(MID(CHAR(0),0,0),1,2)' """ if payload: payload = payload.replace("CONCAT(", "CONCAT_WS(MID(CHAR(0),0,0),") return payload
Tested against:
random_line_split
import-crate-with-invalid-spans.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:crate_with_invalid_spans.rs // pretty-expanded FIXME #23616 extern crate crate_with_invalid_spans; fn main()
{ // The AST of `exported_generic` stored in crate_with_invalid_spans's // metadata should contain an invalid span where span.lo > span.hi. // Let's make sure the compiler doesn't crash when encountering this. let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32); }
identifier_body
import-crate-with-invalid-spans.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:crate_with_invalid_spans.rs // pretty-expanded FIXME #23616 extern crate crate_with_invalid_spans; fn
() { // The AST of `exported_generic` stored in crate_with_invalid_spans's // metadata should contain an invalid span where span.lo > span.hi. // Let's make sure the compiler doesn't crash when encountering this. let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32); }
main
identifier_name
import-crate-with-invalid-spans.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// aux-build:crate_with_invalid_spans.rs // pretty-expanded FIXME #23616 extern crate crate_with_invalid_spans; fn main() { // The AST of `exported_generic` stored in crate_with_invalid_spans's // metadata should contain an invalid span where span.lo > span.hi. // Let's make sure the compiler doesn't crash when encountering this. let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32); }
// 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.
random_line_split
spinner.spec.ts
import {TestBed, ComponentFixture} from '@angular/core/testing'; import {Component} from '@angular/core'; import {createGenericTestComponent} from '../../test/util/helpers'; import {NglSpinnersModule} from './module'; const createTestComponent = (html?: string) => createGenericTestComponent(TestComponent, html) as ComponentFixture<TestComponent>; function getSpinnerElement(element: Element): HTMLDivElement
function getSpinnerContainer(element: Element): HTMLDivElement { return <HTMLDivElement>element.firstElementChild; } describe('Spinner Component', () => { beforeEach(() => TestBed.configureTestingModule({declarations: [TestComponent], imports: [NglSpinnersModule]})); it('should render a medium spinner', () => { const fixture = createTestComponent(); const spinner = getSpinnerElement(fixture.nativeElement); const image: HTMLImageElement = <HTMLImageElement>spinner.firstChild; const container = getSpinnerContainer(fixture.nativeElement); expect(spinner).toBeDefined(); expect(spinner).toHaveCssClass('slds-spinner--medium'); expect(container).not.toHaveCssClass('slds-spinner_container'); expect(image).toBeDefined(); }); it('should render a large spinner based on input', () => { const fixture = createTestComponent(`<ngl-spinner [size]="'large'" ></ngl-spinner>`); const spinner = getSpinnerElement(fixture.nativeElement); expect(spinner).toHaveCssClass('slds-spinner--large'); }); it('should render a themed spinner based on input', () => { const fixture = createTestComponent(`<ngl-spinner type="brand" ></ngl-spinner>`); const spinner = getSpinnerElement(fixture.nativeElement); expect(spinner).toHaveCssClass('slds-spinner--brand'); }); it('should apply container class if attribute exists', () => { const fixture = createTestComponent(`<ngl-spinner container></ngl-spinner>`); const container = getSpinnerContainer(fixture.nativeElement); expect(container).toHaveCssClass('slds-spinner_container'); }); it('should apply container class based on input', () => { const fixture = createTestComponent(`<ngl-spinner [container]="container"></ngl-spinner>`); const {nativeElement, componentInstance} = fixture; const container = getSpinnerContainer(nativeElement); expect(container).toHaveCssClass('slds-spinner_container'); componentInstance.container = false; fixture.detectChanges(); expect(container).not.toHaveCssClass('slds-spinner_container'); }); }); @Component({ template: `<ngl-spinner></ngl-spinner>`, }) export class TestComponent { container = true; }
{ return <HTMLDivElement>element.querySelector('.slds-spinner'); }
identifier_body
spinner.spec.ts
import {TestBed, ComponentFixture} from '@angular/core/testing'; import {Component} from '@angular/core'; import {createGenericTestComponent} from '../../test/util/helpers'; import {NglSpinnersModule} from './module'; const createTestComponent = (html?: string) => createGenericTestComponent(TestComponent, html) as ComponentFixture<TestComponent>; function getSpinnerElement(element: Element): HTMLDivElement { return <HTMLDivElement>element.querySelector('.slds-spinner'); } function getSpinnerContainer(element: Element): HTMLDivElement { return <HTMLDivElement>element.firstElementChild; } describe('Spinner Component', () => { beforeEach(() => TestBed.configureTestingModule({declarations: [TestComponent], imports: [NglSpinnersModule]})); it('should render a medium spinner', () => { const fixture = createTestComponent(); const spinner = getSpinnerElement(fixture.nativeElement); const image: HTMLImageElement = <HTMLImageElement>spinner.firstChild; const container = getSpinnerContainer(fixture.nativeElement); expect(spinner).toBeDefined(); expect(spinner).toHaveCssClass('slds-spinner--medium'); expect(container).not.toHaveCssClass('slds-spinner_container'); expect(image).toBeDefined(); }); it('should render a large spinner based on input', () => { const fixture = createTestComponent(`<ngl-spinner [size]="'large'" ></ngl-spinner>`); const spinner = getSpinnerElement(fixture.nativeElement); expect(spinner).toHaveCssClass('slds-spinner--large'); }); it('should render a themed spinner based on input', () => { const fixture = createTestComponent(`<ngl-spinner type="brand" ></ngl-spinner>`); const spinner = getSpinnerElement(fixture.nativeElement); expect(spinner).toHaveCssClass('slds-spinner--brand'); }); it('should apply container class if attribute exists', () => { const fixture = createTestComponent(`<ngl-spinner container></ngl-spinner>`); const container = getSpinnerContainer(fixture.nativeElement); expect(container).toHaveCssClass('slds-spinner_container'); }); it('should apply container class based on input', () => { const fixture = createTestComponent(`<ngl-spinner [container]="container"></ngl-spinner>`); const {nativeElement, componentInstance} = fixture; const container = getSpinnerContainer(nativeElement); expect(container).toHaveCssClass('slds-spinner_container'); componentInstance.container = false; fixture.detectChanges(); expect(container).not.toHaveCssClass('slds-spinner_container'); }); }); @Component({ template: `<ngl-spinner></ngl-spinner>`, }) export class
{ container = true; }
TestComponent
identifier_name
spinner.spec.ts
import {TestBed, ComponentFixture} from '@angular/core/testing'; import {Component} from '@angular/core'; import {createGenericTestComponent} from '../../test/util/helpers'; import {NglSpinnersModule} from './module'; const createTestComponent = (html?: string) => createGenericTestComponent(TestComponent, html) as ComponentFixture<TestComponent>;
function getSpinnerElement(element: Element): HTMLDivElement { return <HTMLDivElement>element.querySelector('.slds-spinner'); } function getSpinnerContainer(element: Element): HTMLDivElement { return <HTMLDivElement>element.firstElementChild; } describe('Spinner Component', () => { beforeEach(() => TestBed.configureTestingModule({declarations: [TestComponent], imports: [NglSpinnersModule]})); it('should render a medium spinner', () => { const fixture = createTestComponent(); const spinner = getSpinnerElement(fixture.nativeElement); const image: HTMLImageElement = <HTMLImageElement>spinner.firstChild; const container = getSpinnerContainer(fixture.nativeElement); expect(spinner).toBeDefined(); expect(spinner).toHaveCssClass('slds-spinner--medium'); expect(container).not.toHaveCssClass('slds-spinner_container'); expect(image).toBeDefined(); }); it('should render a large spinner based on input', () => { const fixture = createTestComponent(`<ngl-spinner [size]="'large'" ></ngl-spinner>`); const spinner = getSpinnerElement(fixture.nativeElement); expect(spinner).toHaveCssClass('slds-spinner--large'); }); it('should render a themed spinner based on input', () => { const fixture = createTestComponent(`<ngl-spinner type="brand" ></ngl-spinner>`); const spinner = getSpinnerElement(fixture.nativeElement); expect(spinner).toHaveCssClass('slds-spinner--brand'); }); it('should apply container class if attribute exists', () => { const fixture = createTestComponent(`<ngl-spinner container></ngl-spinner>`); const container = getSpinnerContainer(fixture.nativeElement); expect(container).toHaveCssClass('slds-spinner_container'); }); it('should apply container class based on input', () => { const fixture = createTestComponent(`<ngl-spinner [container]="container"></ngl-spinner>`); const {nativeElement, componentInstance} = fixture; const container = getSpinnerContainer(nativeElement); expect(container).toHaveCssClass('slds-spinner_container'); componentInstance.container = false; fixture.detectChanges(); expect(container).not.toHaveCssClass('slds-spinner_container'); }); }); @Component({ template: `<ngl-spinner></ngl-spinner>`, }) export class TestComponent { container = true; }
random_line_split
node_entity.py
"""Entity class that represents Z-Wave node.""" # pylint: disable=import-outside-toplevel from itertools import count from homeassistant.const import ATTR_BATTERY_LEVEL, ATTR_ENTITY_ID, ATTR_WAKEUP from homeassistant.core import callback from homeassistant.helpers.device_registry import async_get_registry as get_dev_reg from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_registry import async_get_registry from .const import ( ATTR_BASIC_LEVEL, ATTR_NODE_ID, ATTR_SCENE_DATA, ATTR_SCENE_ID, COMMAND_CLASS_CENTRAL_SCENE, COMMAND_CLASS_VERSION, COMMAND_CLASS_WAKE_UP, DOMAIN, EVENT_NODE_EVENT, EVENT_SCENE_ACTIVATED, ) from .util import is_node_parsed, node_device_id_and_name, node_name ATTR_QUERY_STAGE = "query_stage" ATTR_AWAKE = "is_awake" ATTR_READY = "is_ready" ATTR_FAILED = "is_failed" ATTR_PRODUCT_NAME = "product_name" ATTR_MANUFACTURER_NAME = "manufacturer_name" ATTR_NODE_NAME = "node_name" ATTR_APPLICATION_VERSION = "application_version" STAGE_COMPLETE = "Complete" _REQUIRED_ATTRIBUTES = [ ATTR_QUERY_STAGE, ATTR_AWAKE, ATTR_READY, ATTR_FAILED, "is_info_received", "max_baud_rate", "is_zwave_plus", ] _OPTIONAL_ATTRIBUTES = ["capabilities", "neighbors", "location"] _COMM_ATTRIBUTES = [ "sentCnt", "sentFailed", "retries", "receivedCnt", "receivedDups", "receivedUnsolicited", "sentTS", "receivedTS", "lastRequestRTT", "averageRequestRTT", "lastResponseRTT", "averageResponseRTT", ] ATTRIBUTES = _REQUIRED_ATTRIBUTES + _OPTIONAL_ATTRIBUTES class ZWaveBaseEntity(Entity): """Base class for Z-Wave Node and Value entities.""" def __init__(self): """Initialize the base Z-Wave class.""" self._update_scheduled = False def maybe_schedule_update(self): """Maybe schedule state update. If value changed after device was created but before setup_platform was called - skip updating state. """ if self.hass and not self._update_scheduled: self.hass.add_job(self._schedule_update) @callback def _schedule_update(self): """Schedule delayed update.""" if self._update_scheduled: return @callback def do_update(): """Really update.""" self.async_write_ha_state() self._update_scheduled = False self._update_scheduled = True self.hass.loop.call_later(0.1, do_update) def try_remove_and_add(self): """Remove this entity and add it back.""" async def _async_remove_and_add(): await self.async_remove() self.entity_id = None await self.platform.async_add_entities([self]) if self.hass and self.platform: self.hass.add_job(_async_remove_and_add) async def node_removed(self): """Call when a node is removed from the Z-Wave network.""" await self.async_remove() registry = await async_get_registry(self.hass) if self.entity_id not in registry.entities: return registry.async_remove(self.entity_id) class ZWaveNodeEntity(ZWaveBaseEntity): """Representation of a Z-Wave node.""" def __init__(self, node, network): """Initialize node.""" # pylint: disable=import-error super().__init__() from openzwave.network import ZWaveNetwork from pydispatch import dispatcher self._network = network self.node = node self.node_id = self.node.node_id self._name = node_name(self.node) self._product_name = node.product_name self._manufacturer_name = node.manufacturer_name self._unique_id = self._compute_unique_id() self._application_version = None self._attributes = {} self.wakeup_interval = None self.location = None self.battery_level = None dispatcher.connect( self.network_node_value_added, ZWaveNetwork.SIGNAL_VALUE_ADDED ) dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_VALUE_CHANGED) dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_NODE) dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_NOTIFICATION) dispatcher.connect(self.network_node_event, ZWaveNetwork.SIGNAL_NODE_EVENT) dispatcher.connect( self.network_scene_activated, ZWaveNetwork.SIGNAL_SCENE_EVENT ) @property def unique_id(self): """Return unique ID of Z-wave node.""" return self._unique_id @property def device_info(self): """Return device information.""" identifier, name = node_device_id_and_name(self.node) info = { "identifiers": {identifier}, "manufacturer": self.node.manufacturer_name, "model": self.node.product_name, "name": name, } if self.node_id > 1: info["via_device"] = (DOMAIN, 1) return info def maybe_update_application_version(self, value): """Update application version if value is a Command Class Version, Application Value.""" if ( value and value.command_class == COMMAND_CLASS_VERSION and value.label == "Application Version" ): self._application_version = value.data def network_node_value_added(self, node=None, value=None, args=None): """Handle a added value to a none on the network.""" if node and node.node_id != self.node_id: return if args is not None and "nodeId" in args and args["nodeId"] != self.node_id: return self.maybe_update_application_version(value) def network_node_changed(self, node=None, value=None, args=None): """Handle a changed node on the network.""" if node and node.node_id != self.node_id: return if args is not None and "nodeId" in args and args["nodeId"] != self.node_id: return # Process central scene activation if value is not None and value.command_class == COMMAND_CLASS_CENTRAL_SCENE: self.central_scene_activated(value.index, value.data) self.maybe_update_application_version(value) self.node_changed() def get_node_statistics(self): """Retrieve statistics from the node.""" return self._network.manager.getNodeStatistics( self._network.home_id, self.node_id ) def node_changed(self): """Update node properties.""" attributes = {} stats = self.get_node_statistics() for attr in ATTRIBUTES: value = getattr(self.node, attr) if attr in _REQUIRED_ATTRIBUTES or value: attributes[attr] = value for attr in _COMM_ATTRIBUTES: attributes[attr] = stats[attr] if self.node.can_wake_up(): for value in self.node.get_values(COMMAND_CLASS_WAKE_UP).values(): if value.index != 0: continue self.wakeup_interval = value.data break else: self.wakeup_interval = None self.battery_level = self.node.get_battery_level() self._product_name = self.node.product_name self._manufacturer_name = self.node.manufacturer_name self._name = node_name(self.node) self._attributes = attributes if not self._unique_id: self._unique_id = self._compute_unique_id() if self._unique_id: # Node info parsed. Remove and re-add self.try_remove_and_add() self.maybe_schedule_update() async def node_renamed(self, update_ids=False): """Rename the node and update any IDs.""" identifier, self._name = node_device_id_and_name(self.node) # Set the name in the devices. If they're customised # the customisation will not be stored as name and will stick. dev_reg = await get_dev_reg(self.hass) device = dev_reg.async_get_device(identifiers={identifier}, connections=set()) dev_reg.async_update_device(device.id, name=self._name) # update sub-devices too for i in count(2): identifier, new_name = node_device_id_and_name(self.node, i) device = dev_reg.async_get_device( identifiers={identifier}, connections=set() ) if not device: break dev_reg.async_update_device(device.id, name=new_name) # Update entity ID. if update_ids: ent_reg = await async_get_registry(self.hass) new_entity_id = ent_reg.async_generate_entity_id( DOMAIN, self._name, self.platform.entities.keys() - {self.entity_id} ) if new_entity_id != self.entity_id: # Don't change the name attribute, it will be None unless # customised and if it's been customised, keep the # customisation. ent_reg.async_update_entity(self.entity_id, new_entity_id=new_entity_id) return # else for the above two ifs, update if not using update_entity self.async_write_ha_state() def network_node_event(self, node, value): """Handle a node activated event on the network.""" if node.node_id == self.node.node_id: self.node_event(value) def node_event(self, value): """Handle a node activated event for this node.""" if self.hass is None: return self.hass.bus.fire( EVENT_NODE_EVENT, { ATTR_ENTITY_ID: self.entity_id, ATTR_NODE_ID: self.node.node_id, ATTR_BASIC_LEVEL: value, }, ) def network_scene_activated(self, node, scene_id): """Handle a scene activated event on the network.""" if node.node_id == self.node.node_id: self.scene_activated(scene_id) def scene_activated(self, scene_id): """Handle an activated scene for this node.""" if self.hass is None: return self.hass.bus.fire( EVENT_SCENE_ACTIVATED, { ATTR_ENTITY_ID: self.entity_id, ATTR_NODE_ID: self.node.node_id, ATTR_SCENE_ID: scene_id, }, ) def central_scene_activated(self, scene_id, scene_data): """Handle an activated central scene for this node.""" if self.hass is None: return self.hass.bus.fire( EVENT_SCENE_ACTIVATED, { ATTR_ENTITY_ID: self.entity_id, ATTR_NODE_ID: self.node_id, ATTR_SCENE_ID: scene_id, ATTR_SCENE_DATA: scene_data, }, ) @property def state(self): """Return the state.""" if ATTR_READY not in self._attributes: return None if self._attributes[ATTR_FAILED]: return "dead" if self._attributes[ATTR_QUERY_STAGE] != "Complete": return "initializing" if not self._attributes[ATTR_AWAKE]: return "sleeping" if self._attributes[ATTR_READY]: return "ready" return None @property def should_poll(self): """No polling needed.""" return False
"""Return the name of the device.""" return self._name @property def device_state_attributes(self): """Return the device specific state attributes.""" attrs = { ATTR_NODE_ID: self.node_id, ATTR_NODE_NAME: self._name, ATTR_MANUFACTURER_NAME: self._manufacturer_name, ATTR_PRODUCT_NAME: self._product_name, } attrs.update(self._attributes) if self.battery_level is not None: attrs[ATTR_BATTERY_LEVEL] = self.battery_level if self.wakeup_interval is not None: attrs[ATTR_WAKEUP] = self.wakeup_interval if self._application_version is not None: attrs[ATTR_APPLICATION_VERSION] = self._application_version return attrs def _compute_unique_id(self): if is_node_parsed(self.node) or self.node.is_ready: return f"node-{self.node_id}" return None
@property def name(self):
random_line_split
node_entity.py
"""Entity class that represents Z-Wave node.""" # pylint: disable=import-outside-toplevel from itertools import count from homeassistant.const import ATTR_BATTERY_LEVEL, ATTR_ENTITY_ID, ATTR_WAKEUP from homeassistant.core import callback from homeassistant.helpers.device_registry import async_get_registry as get_dev_reg from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_registry import async_get_registry from .const import ( ATTR_BASIC_LEVEL, ATTR_NODE_ID, ATTR_SCENE_DATA, ATTR_SCENE_ID, COMMAND_CLASS_CENTRAL_SCENE, COMMAND_CLASS_VERSION, COMMAND_CLASS_WAKE_UP, DOMAIN, EVENT_NODE_EVENT, EVENT_SCENE_ACTIVATED, ) from .util import is_node_parsed, node_device_id_and_name, node_name ATTR_QUERY_STAGE = "query_stage" ATTR_AWAKE = "is_awake" ATTR_READY = "is_ready" ATTR_FAILED = "is_failed" ATTR_PRODUCT_NAME = "product_name" ATTR_MANUFACTURER_NAME = "manufacturer_name" ATTR_NODE_NAME = "node_name" ATTR_APPLICATION_VERSION = "application_version" STAGE_COMPLETE = "Complete" _REQUIRED_ATTRIBUTES = [ ATTR_QUERY_STAGE, ATTR_AWAKE, ATTR_READY, ATTR_FAILED, "is_info_received", "max_baud_rate", "is_zwave_plus", ] _OPTIONAL_ATTRIBUTES = ["capabilities", "neighbors", "location"] _COMM_ATTRIBUTES = [ "sentCnt", "sentFailed", "retries", "receivedCnt", "receivedDups", "receivedUnsolicited", "sentTS", "receivedTS", "lastRequestRTT", "averageRequestRTT", "lastResponseRTT", "averageResponseRTT", ] ATTRIBUTES = _REQUIRED_ATTRIBUTES + _OPTIONAL_ATTRIBUTES class ZWaveBaseEntity(Entity): """Base class for Z-Wave Node and Value entities.""" def __init__(self): """Initialize the base Z-Wave class.""" self._update_scheduled = False def maybe_schedule_update(self): """Maybe schedule state update. If value changed after device was created but before setup_platform was called - skip updating state. """ if self.hass and not self._update_scheduled: self.hass.add_job(self._schedule_update) @callback def _schedule_update(self): """Schedule delayed update.""" if self._update_scheduled: return @callback def do_update(): """Really update.""" self.async_write_ha_state() self._update_scheduled = False self._update_scheduled = True self.hass.loop.call_later(0.1, do_update) def try_remove_and_add(self): """Remove this entity and add it back.""" async def _async_remove_and_add(): await self.async_remove() self.entity_id = None await self.platform.async_add_entities([self]) if self.hass and self.platform: self.hass.add_job(_async_remove_and_add) async def node_removed(self): """Call when a node is removed from the Z-Wave network.""" await self.async_remove() registry = await async_get_registry(self.hass) if self.entity_id not in registry.entities: return registry.async_remove(self.entity_id) class ZWaveNodeEntity(ZWaveBaseEntity): """Representation of a Z-Wave node.""" def __init__(self, node, network): """Initialize node.""" # pylint: disable=import-error super().__init__() from openzwave.network import ZWaveNetwork from pydispatch import dispatcher self._network = network self.node = node self.node_id = self.node.node_id self._name = node_name(self.node) self._product_name = node.product_name self._manufacturer_name = node.manufacturer_name self._unique_id = self._compute_unique_id() self._application_version = None self._attributes = {} self.wakeup_interval = None self.location = None self.battery_level = None dispatcher.connect( self.network_node_value_added, ZWaveNetwork.SIGNAL_VALUE_ADDED ) dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_VALUE_CHANGED) dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_NODE) dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_NOTIFICATION) dispatcher.connect(self.network_node_event, ZWaveNetwork.SIGNAL_NODE_EVENT) dispatcher.connect( self.network_scene_activated, ZWaveNetwork.SIGNAL_SCENE_EVENT ) @property def unique_id(self): """Return unique ID of Z-wave node.""" return self._unique_id @property def device_info(self): """Return device information.""" identifier, name = node_device_id_and_name(self.node) info = { "identifiers": {identifier}, "manufacturer": self.node.manufacturer_name, "model": self.node.product_name, "name": name, } if self.node_id > 1: info["via_device"] = (DOMAIN, 1) return info def maybe_update_application_version(self, value): """Update application version if value is a Command Class Version, Application Value.""" if ( value and value.command_class == COMMAND_CLASS_VERSION and value.label == "Application Version" ): self._application_version = value.data def network_node_value_added(self, node=None, value=None, args=None): """Handle a added value to a none on the network.""" if node and node.node_id != self.node_id: return if args is not None and "nodeId" in args and args["nodeId"] != self.node_id: return self.maybe_update_application_version(value) def network_node_changed(self, node=None, value=None, args=None): """Handle a changed node on the network.""" if node and node.node_id != self.node_id: return if args is not None and "nodeId" in args and args["nodeId"] != self.node_id: return # Process central scene activation if value is not None and value.command_class == COMMAND_CLASS_CENTRAL_SCENE: self.central_scene_activated(value.index, value.data) self.maybe_update_application_version(value) self.node_changed() def get_node_statistics(self): """Retrieve statistics from the node.""" return self._network.manager.getNodeStatistics( self._network.home_id, self.node_id ) def node_changed(self): """Update node properties.""" attributes = {} stats = self.get_node_statistics() for attr in ATTRIBUTES: value = getattr(self.node, attr) if attr in _REQUIRED_ATTRIBUTES or value: attributes[attr] = value for attr in _COMM_ATTRIBUTES: attributes[attr] = stats[attr] if self.node.can_wake_up(): for value in self.node.get_values(COMMAND_CLASS_WAKE_UP).values(): if value.index != 0: continue self.wakeup_interval = value.data break else: self.wakeup_interval = None self.battery_level = self.node.get_battery_level() self._product_name = self.node.product_name self._manufacturer_name = self.node.manufacturer_name self._name = node_name(self.node) self._attributes = attributes if not self._unique_id: self._unique_id = self._compute_unique_id() if self._unique_id: # Node info parsed. Remove and re-add self.try_remove_and_add() self.maybe_schedule_update() async def node_renamed(self, update_ids=False): """Rename the node and update any IDs.""" identifier, self._name = node_device_id_and_name(self.node) # Set the name in the devices. If they're customised # the customisation will not be stored as name and will stick. dev_reg = await get_dev_reg(self.hass) device = dev_reg.async_get_device(identifiers={identifier}, connections=set()) dev_reg.async_update_device(device.id, name=self._name) # update sub-devices too for i in count(2): identifier, new_name = node_device_id_and_name(self.node, i) device = dev_reg.async_get_device( identifiers={identifier}, connections=set() ) if not device: break dev_reg.async_update_device(device.id, name=new_name) # Update entity ID. if update_ids: ent_reg = await async_get_registry(self.hass) new_entity_id = ent_reg.async_generate_entity_id( DOMAIN, self._name, self.platform.entities.keys() - {self.entity_id} ) if new_entity_id != self.entity_id: # Don't change the name attribute, it will be None unless # customised and if it's been customised, keep the # customisation. ent_reg.async_update_entity(self.entity_id, new_entity_id=new_entity_id) return # else for the above two ifs, update if not using update_entity self.async_write_ha_state() def network_node_event(self, node, value): """Handle a node activated event on the network.""" if node.node_id == self.node.node_id: self.node_event(value) def
(self, value): """Handle a node activated event for this node.""" if self.hass is None: return self.hass.bus.fire( EVENT_NODE_EVENT, { ATTR_ENTITY_ID: self.entity_id, ATTR_NODE_ID: self.node.node_id, ATTR_BASIC_LEVEL: value, }, ) def network_scene_activated(self, node, scene_id): """Handle a scene activated event on the network.""" if node.node_id == self.node.node_id: self.scene_activated(scene_id) def scene_activated(self, scene_id): """Handle an activated scene for this node.""" if self.hass is None: return self.hass.bus.fire( EVENT_SCENE_ACTIVATED, { ATTR_ENTITY_ID: self.entity_id, ATTR_NODE_ID: self.node.node_id, ATTR_SCENE_ID: scene_id, }, ) def central_scene_activated(self, scene_id, scene_data): """Handle an activated central scene for this node.""" if self.hass is None: return self.hass.bus.fire( EVENT_SCENE_ACTIVATED, { ATTR_ENTITY_ID: self.entity_id, ATTR_NODE_ID: self.node_id, ATTR_SCENE_ID: scene_id, ATTR_SCENE_DATA: scene_data, }, ) @property def state(self): """Return the state.""" if ATTR_READY not in self._attributes: return None if self._attributes[ATTR_FAILED]: return "dead" if self._attributes[ATTR_QUERY_STAGE] != "Complete": return "initializing" if not self._attributes[ATTR_AWAKE]: return "sleeping" if self._attributes[ATTR_READY]: return "ready" return None @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of the device.""" return self._name @property def device_state_attributes(self): """Return the device specific state attributes.""" attrs = { ATTR_NODE_ID: self.node_id, ATTR_NODE_NAME: self._name, ATTR_MANUFACTURER_NAME: self._manufacturer_name, ATTR_PRODUCT_NAME: self._product_name, } attrs.update(self._attributes) if self.battery_level is not None: attrs[ATTR_BATTERY_LEVEL] = self.battery_level if self.wakeup_interval is not None: attrs[ATTR_WAKEUP] = self.wakeup_interval if self._application_version is not None: attrs[ATTR_APPLICATION_VERSION] = self._application_version return attrs def _compute_unique_id(self): if is_node_parsed(self.node) or self.node.is_ready: return f"node-{self.node_id}" return None
node_event
identifier_name
node_entity.py
"""Entity class that represents Z-Wave node.""" # pylint: disable=import-outside-toplevel from itertools import count from homeassistant.const import ATTR_BATTERY_LEVEL, ATTR_ENTITY_ID, ATTR_WAKEUP from homeassistant.core import callback from homeassistant.helpers.device_registry import async_get_registry as get_dev_reg from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_registry import async_get_registry from .const import ( ATTR_BASIC_LEVEL, ATTR_NODE_ID, ATTR_SCENE_DATA, ATTR_SCENE_ID, COMMAND_CLASS_CENTRAL_SCENE, COMMAND_CLASS_VERSION, COMMAND_CLASS_WAKE_UP, DOMAIN, EVENT_NODE_EVENT, EVENT_SCENE_ACTIVATED, ) from .util import is_node_parsed, node_device_id_and_name, node_name ATTR_QUERY_STAGE = "query_stage" ATTR_AWAKE = "is_awake" ATTR_READY = "is_ready" ATTR_FAILED = "is_failed" ATTR_PRODUCT_NAME = "product_name" ATTR_MANUFACTURER_NAME = "manufacturer_name" ATTR_NODE_NAME = "node_name" ATTR_APPLICATION_VERSION = "application_version" STAGE_COMPLETE = "Complete" _REQUIRED_ATTRIBUTES = [ ATTR_QUERY_STAGE, ATTR_AWAKE, ATTR_READY, ATTR_FAILED, "is_info_received", "max_baud_rate", "is_zwave_plus", ] _OPTIONAL_ATTRIBUTES = ["capabilities", "neighbors", "location"] _COMM_ATTRIBUTES = [ "sentCnt", "sentFailed", "retries", "receivedCnt", "receivedDups", "receivedUnsolicited", "sentTS", "receivedTS", "lastRequestRTT", "averageRequestRTT", "lastResponseRTT", "averageResponseRTT", ] ATTRIBUTES = _REQUIRED_ATTRIBUTES + _OPTIONAL_ATTRIBUTES class ZWaveBaseEntity(Entity): """Base class for Z-Wave Node and Value entities.""" def __init__(self): """Initialize the base Z-Wave class.""" self._update_scheduled = False def maybe_schedule_update(self): """Maybe schedule state update. If value changed after device was created but before setup_platform was called - skip updating state. """ if self.hass and not self._update_scheduled: self.hass.add_job(self._schedule_update) @callback def _schedule_update(self): """Schedule delayed update.""" if self._update_scheduled: return @callback def do_update(): """Really update.""" self.async_write_ha_state() self._update_scheduled = False self._update_scheduled = True self.hass.loop.call_later(0.1, do_update) def try_remove_and_add(self): """Remove this entity and add it back.""" async def _async_remove_and_add(): await self.async_remove() self.entity_id = None await self.platform.async_add_entities([self]) if self.hass and self.platform: self.hass.add_job(_async_remove_and_add) async def node_removed(self): """Call when a node is removed from the Z-Wave network.""" await self.async_remove() registry = await async_get_registry(self.hass) if self.entity_id not in registry.entities: return registry.async_remove(self.entity_id) class ZWaveNodeEntity(ZWaveBaseEntity): """Representation of a Z-Wave node.""" def __init__(self, node, network): """Initialize node.""" # pylint: disable=import-error super().__init__() from openzwave.network import ZWaveNetwork from pydispatch import dispatcher self._network = network self.node = node self.node_id = self.node.node_id self._name = node_name(self.node) self._product_name = node.product_name self._manufacturer_name = node.manufacturer_name self._unique_id = self._compute_unique_id() self._application_version = None self._attributes = {} self.wakeup_interval = None self.location = None self.battery_level = None dispatcher.connect( self.network_node_value_added, ZWaveNetwork.SIGNAL_VALUE_ADDED ) dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_VALUE_CHANGED) dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_NODE) dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_NOTIFICATION) dispatcher.connect(self.network_node_event, ZWaveNetwork.SIGNAL_NODE_EVENT) dispatcher.connect( self.network_scene_activated, ZWaveNetwork.SIGNAL_SCENE_EVENT ) @property def unique_id(self): """Return unique ID of Z-wave node.""" return self._unique_id @property def device_info(self): """Return device information.""" identifier, name = node_device_id_and_name(self.node) info = { "identifiers": {identifier}, "manufacturer": self.node.manufacturer_name, "model": self.node.product_name, "name": name, } if self.node_id > 1: info["via_device"] = (DOMAIN, 1) return info def maybe_update_application_version(self, value): """Update application version if value is a Command Class Version, Application Value.""" if ( value and value.command_class == COMMAND_CLASS_VERSION and value.label == "Application Version" ): self._application_version = value.data def network_node_value_added(self, node=None, value=None, args=None): """Handle a added value to a none on the network.""" if node and node.node_id != self.node_id: return if args is not None and "nodeId" in args and args["nodeId"] != self.node_id: return self.maybe_update_application_version(value) def network_node_changed(self, node=None, value=None, args=None):
def get_node_statistics(self): """Retrieve statistics from the node.""" return self._network.manager.getNodeStatistics( self._network.home_id, self.node_id ) def node_changed(self): """Update node properties.""" attributes = {} stats = self.get_node_statistics() for attr in ATTRIBUTES: value = getattr(self.node, attr) if attr in _REQUIRED_ATTRIBUTES or value: attributes[attr] = value for attr in _COMM_ATTRIBUTES: attributes[attr] = stats[attr] if self.node.can_wake_up(): for value in self.node.get_values(COMMAND_CLASS_WAKE_UP).values(): if value.index != 0: continue self.wakeup_interval = value.data break else: self.wakeup_interval = None self.battery_level = self.node.get_battery_level() self._product_name = self.node.product_name self._manufacturer_name = self.node.manufacturer_name self._name = node_name(self.node) self._attributes = attributes if not self._unique_id: self._unique_id = self._compute_unique_id() if self._unique_id: # Node info parsed. Remove and re-add self.try_remove_and_add() self.maybe_schedule_update() async def node_renamed(self, update_ids=False): """Rename the node and update any IDs.""" identifier, self._name = node_device_id_and_name(self.node) # Set the name in the devices. If they're customised # the customisation will not be stored as name and will stick. dev_reg = await get_dev_reg(self.hass) device = dev_reg.async_get_device(identifiers={identifier}, connections=set()) dev_reg.async_update_device(device.id, name=self._name) # update sub-devices too for i in count(2): identifier, new_name = node_device_id_and_name(self.node, i) device = dev_reg.async_get_device( identifiers={identifier}, connections=set() ) if not device: break dev_reg.async_update_device(device.id, name=new_name) # Update entity ID. if update_ids: ent_reg = await async_get_registry(self.hass) new_entity_id = ent_reg.async_generate_entity_id( DOMAIN, self._name, self.platform.entities.keys() - {self.entity_id} ) if new_entity_id != self.entity_id: # Don't change the name attribute, it will be None unless # customised and if it's been customised, keep the # customisation. ent_reg.async_update_entity(self.entity_id, new_entity_id=new_entity_id) return # else for the above two ifs, update if not using update_entity self.async_write_ha_state() def network_node_event(self, node, value): """Handle a node activated event on the network.""" if node.node_id == self.node.node_id: self.node_event(value) def node_event(self, value): """Handle a node activated event for this node.""" if self.hass is None: return self.hass.bus.fire( EVENT_NODE_EVENT, { ATTR_ENTITY_ID: self.entity_id, ATTR_NODE_ID: self.node.node_id, ATTR_BASIC_LEVEL: value, }, ) def network_scene_activated(self, node, scene_id): """Handle a scene activated event on the network.""" if node.node_id == self.node.node_id: self.scene_activated(scene_id) def scene_activated(self, scene_id): """Handle an activated scene for this node.""" if self.hass is None: return self.hass.bus.fire( EVENT_SCENE_ACTIVATED, { ATTR_ENTITY_ID: self.entity_id, ATTR_NODE_ID: self.node.node_id, ATTR_SCENE_ID: scene_id, }, ) def central_scene_activated(self, scene_id, scene_data): """Handle an activated central scene for this node.""" if self.hass is None: return self.hass.bus.fire( EVENT_SCENE_ACTIVATED, { ATTR_ENTITY_ID: self.entity_id, ATTR_NODE_ID: self.node_id, ATTR_SCENE_ID: scene_id, ATTR_SCENE_DATA: scene_data, }, ) @property def state(self): """Return the state.""" if ATTR_READY not in self._attributes: return None if self._attributes[ATTR_FAILED]: return "dead" if self._attributes[ATTR_QUERY_STAGE] != "Complete": return "initializing" if not self._attributes[ATTR_AWAKE]: return "sleeping" if self._attributes[ATTR_READY]: return "ready" return None @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of the device.""" return self._name @property def device_state_attributes(self): """Return the device specific state attributes.""" attrs = { ATTR_NODE_ID: self.node_id, ATTR_NODE_NAME: self._name, ATTR_MANUFACTURER_NAME: self._manufacturer_name, ATTR_PRODUCT_NAME: self._product_name, } attrs.update(self._attributes) if self.battery_level is not None: attrs[ATTR_BATTERY_LEVEL] = self.battery_level if self.wakeup_interval is not None: attrs[ATTR_WAKEUP] = self.wakeup_interval if self._application_version is not None: attrs[ATTR_APPLICATION_VERSION] = self._application_version return attrs def _compute_unique_id(self): if is_node_parsed(self.node) or self.node.is_ready: return f"node-{self.node_id}" return None
"""Handle a changed node on the network.""" if node and node.node_id != self.node_id: return if args is not None and "nodeId" in args and args["nodeId"] != self.node_id: return # Process central scene activation if value is not None and value.command_class == COMMAND_CLASS_CENTRAL_SCENE: self.central_scene_activated(value.index, value.data) self.maybe_update_application_version(value) self.node_changed()
identifier_body
node_entity.py
"""Entity class that represents Z-Wave node.""" # pylint: disable=import-outside-toplevel from itertools import count from homeassistant.const import ATTR_BATTERY_LEVEL, ATTR_ENTITY_ID, ATTR_WAKEUP from homeassistant.core import callback from homeassistant.helpers.device_registry import async_get_registry as get_dev_reg from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_registry import async_get_registry from .const import ( ATTR_BASIC_LEVEL, ATTR_NODE_ID, ATTR_SCENE_DATA, ATTR_SCENE_ID, COMMAND_CLASS_CENTRAL_SCENE, COMMAND_CLASS_VERSION, COMMAND_CLASS_WAKE_UP, DOMAIN, EVENT_NODE_EVENT, EVENT_SCENE_ACTIVATED, ) from .util import is_node_parsed, node_device_id_and_name, node_name ATTR_QUERY_STAGE = "query_stage" ATTR_AWAKE = "is_awake" ATTR_READY = "is_ready" ATTR_FAILED = "is_failed" ATTR_PRODUCT_NAME = "product_name" ATTR_MANUFACTURER_NAME = "manufacturer_name" ATTR_NODE_NAME = "node_name" ATTR_APPLICATION_VERSION = "application_version" STAGE_COMPLETE = "Complete" _REQUIRED_ATTRIBUTES = [ ATTR_QUERY_STAGE, ATTR_AWAKE, ATTR_READY, ATTR_FAILED, "is_info_received", "max_baud_rate", "is_zwave_plus", ] _OPTIONAL_ATTRIBUTES = ["capabilities", "neighbors", "location"] _COMM_ATTRIBUTES = [ "sentCnt", "sentFailed", "retries", "receivedCnt", "receivedDups", "receivedUnsolicited", "sentTS", "receivedTS", "lastRequestRTT", "averageRequestRTT", "lastResponseRTT", "averageResponseRTT", ] ATTRIBUTES = _REQUIRED_ATTRIBUTES + _OPTIONAL_ATTRIBUTES class ZWaveBaseEntity(Entity): """Base class for Z-Wave Node and Value entities.""" def __init__(self): """Initialize the base Z-Wave class.""" self._update_scheduled = False def maybe_schedule_update(self): """Maybe schedule state update. If value changed after device was created but before setup_platform was called - skip updating state. """ if self.hass and not self._update_scheduled: self.hass.add_job(self._schedule_update) @callback def _schedule_update(self): """Schedule delayed update.""" if self._update_scheduled: return @callback def do_update(): """Really update.""" self.async_write_ha_state() self._update_scheduled = False self._update_scheduled = True self.hass.loop.call_later(0.1, do_update) def try_remove_and_add(self): """Remove this entity and add it back.""" async def _async_remove_and_add(): await self.async_remove() self.entity_id = None await self.platform.async_add_entities([self]) if self.hass and self.platform: self.hass.add_job(_async_remove_and_add) async def node_removed(self): """Call when a node is removed from the Z-Wave network.""" await self.async_remove() registry = await async_get_registry(self.hass) if self.entity_id not in registry.entities: return registry.async_remove(self.entity_id) class ZWaveNodeEntity(ZWaveBaseEntity): """Representation of a Z-Wave node.""" def __init__(self, node, network): """Initialize node.""" # pylint: disable=import-error super().__init__() from openzwave.network import ZWaveNetwork from pydispatch import dispatcher self._network = network self.node = node self.node_id = self.node.node_id self._name = node_name(self.node) self._product_name = node.product_name self._manufacturer_name = node.manufacturer_name self._unique_id = self._compute_unique_id() self._application_version = None self._attributes = {} self.wakeup_interval = None self.location = None self.battery_level = None dispatcher.connect( self.network_node_value_added, ZWaveNetwork.SIGNAL_VALUE_ADDED ) dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_VALUE_CHANGED) dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_NODE) dispatcher.connect(self.network_node_changed, ZWaveNetwork.SIGNAL_NOTIFICATION) dispatcher.connect(self.network_node_event, ZWaveNetwork.SIGNAL_NODE_EVENT) dispatcher.connect( self.network_scene_activated, ZWaveNetwork.SIGNAL_SCENE_EVENT ) @property def unique_id(self): """Return unique ID of Z-wave node.""" return self._unique_id @property def device_info(self): """Return device information.""" identifier, name = node_device_id_and_name(self.node) info = { "identifiers": {identifier}, "manufacturer": self.node.manufacturer_name, "model": self.node.product_name, "name": name, } if self.node_id > 1: info["via_device"] = (DOMAIN, 1) return info def maybe_update_application_version(self, value): """Update application version if value is a Command Class Version, Application Value.""" if ( value and value.command_class == COMMAND_CLASS_VERSION and value.label == "Application Version" ): self._application_version = value.data def network_node_value_added(self, node=None, value=None, args=None): """Handle a added value to a none on the network.""" if node and node.node_id != self.node_id: return if args is not None and "nodeId" in args and args["nodeId"] != self.node_id: return self.maybe_update_application_version(value) def network_node_changed(self, node=None, value=None, args=None): """Handle a changed node on the network.""" if node and node.node_id != self.node_id: return if args is not None and "nodeId" in args and args["nodeId"] != self.node_id: return # Process central scene activation if value is not None and value.command_class == COMMAND_CLASS_CENTRAL_SCENE: self.central_scene_activated(value.index, value.data) self.maybe_update_application_version(value) self.node_changed() def get_node_statistics(self): """Retrieve statistics from the node.""" return self._network.manager.getNodeStatistics( self._network.home_id, self.node_id ) def node_changed(self): """Update node properties.""" attributes = {} stats = self.get_node_statistics() for attr in ATTRIBUTES: value = getattr(self.node, attr) if attr in _REQUIRED_ATTRIBUTES or value: attributes[attr] = value for attr in _COMM_ATTRIBUTES: attributes[attr] = stats[attr] if self.node.can_wake_up(): for value in self.node.get_values(COMMAND_CLASS_WAKE_UP).values(): if value.index != 0: continue self.wakeup_interval = value.data break else: self.wakeup_interval = None self.battery_level = self.node.get_battery_level() self._product_name = self.node.product_name self._manufacturer_name = self.node.manufacturer_name self._name = node_name(self.node) self._attributes = attributes if not self._unique_id: self._unique_id = self._compute_unique_id() if self._unique_id: # Node info parsed. Remove and re-add self.try_remove_and_add() self.maybe_schedule_update() async def node_renamed(self, update_ids=False): """Rename the node and update any IDs.""" identifier, self._name = node_device_id_and_name(self.node) # Set the name in the devices. If they're customised # the customisation will not be stored as name and will stick. dev_reg = await get_dev_reg(self.hass) device = dev_reg.async_get_device(identifiers={identifier}, connections=set()) dev_reg.async_update_device(device.id, name=self._name) # update sub-devices too for i in count(2): identifier, new_name = node_device_id_and_name(self.node, i) device = dev_reg.async_get_device( identifiers={identifier}, connections=set() ) if not device: break dev_reg.async_update_device(device.id, name=new_name) # Update entity ID. if update_ids: ent_reg = await async_get_registry(self.hass) new_entity_id = ent_reg.async_generate_entity_id( DOMAIN, self._name, self.platform.entities.keys() - {self.entity_id} ) if new_entity_id != self.entity_id: # Don't change the name attribute, it will be None unless # customised and if it's been customised, keep the # customisation. ent_reg.async_update_entity(self.entity_id, new_entity_id=new_entity_id) return # else for the above two ifs, update if not using update_entity self.async_write_ha_state() def network_node_event(self, node, value): """Handle a node activated event on the network.""" if node.node_id == self.node.node_id: self.node_event(value) def node_event(self, value): """Handle a node activated event for this node.""" if self.hass is None: return self.hass.bus.fire( EVENT_NODE_EVENT, { ATTR_ENTITY_ID: self.entity_id, ATTR_NODE_ID: self.node.node_id, ATTR_BASIC_LEVEL: value, }, ) def network_scene_activated(self, node, scene_id): """Handle a scene activated event on the network.""" if node.node_id == self.node.node_id: self.scene_activated(scene_id) def scene_activated(self, scene_id): """Handle an activated scene for this node.""" if self.hass is None:
self.hass.bus.fire( EVENT_SCENE_ACTIVATED, { ATTR_ENTITY_ID: self.entity_id, ATTR_NODE_ID: self.node.node_id, ATTR_SCENE_ID: scene_id, }, ) def central_scene_activated(self, scene_id, scene_data): """Handle an activated central scene for this node.""" if self.hass is None: return self.hass.bus.fire( EVENT_SCENE_ACTIVATED, { ATTR_ENTITY_ID: self.entity_id, ATTR_NODE_ID: self.node_id, ATTR_SCENE_ID: scene_id, ATTR_SCENE_DATA: scene_data, }, ) @property def state(self): """Return the state.""" if ATTR_READY not in self._attributes: return None if self._attributes[ATTR_FAILED]: return "dead" if self._attributes[ATTR_QUERY_STAGE] != "Complete": return "initializing" if not self._attributes[ATTR_AWAKE]: return "sleeping" if self._attributes[ATTR_READY]: return "ready" return None @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of the device.""" return self._name @property def device_state_attributes(self): """Return the device specific state attributes.""" attrs = { ATTR_NODE_ID: self.node_id, ATTR_NODE_NAME: self._name, ATTR_MANUFACTURER_NAME: self._manufacturer_name, ATTR_PRODUCT_NAME: self._product_name, } attrs.update(self._attributes) if self.battery_level is not None: attrs[ATTR_BATTERY_LEVEL] = self.battery_level if self.wakeup_interval is not None: attrs[ATTR_WAKEUP] = self.wakeup_interval if self._application_version is not None: attrs[ATTR_APPLICATION_VERSION] = self._application_version return attrs def _compute_unique_id(self): if is_node_parsed(self.node) or self.node.is_ready: return f"node-{self.node_id}" return None
return
conditional_block
ezRPStaticFileStore.py
# Copyright (C) 2013-2015 Computer Sciences Corporation # # 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. # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 import array import math import logging import logging.handlers from pyaccumulo import Accumulo, Mutation, Range class EzRPStaticStore(object): ''' Class to save and retrieve static content from Accumulo. cf = "static" For all rows cq = "hash" Stores the hash_value of Static File cq = "nofchunks" Stores the number of Chunks needed to store Static File cq = "chunk_000" .. "chunk_nnn" Stores the Chunks of Static File ''' def __init__(self, host="localhost", port=42424, user='root', password='secret', chunk_size=int(5*1048576), logger=None): self.__host = host self.__port = port self.__user = user self.__password = password self.__table = 'ezfrontend' self.__cf = 'static' self.__connection = None if logger is not None: self.__log = logger else: self.__log = logging.getLogger(self.__module__ + '.' + self.__class__.__name__) self.__log.addHandler(logging.NullHandler()) self.__chunk_size =int(chunk_size) self._connect(self.__host, self.__port, self.__user, self.__password) def _connect(self, host, port, user, password): try: self.__connection = Accumulo(host, port, user, password) self.__log.debug('Connected to StaticFile Store') except Exception as e: self.__log.exception('Error while connecting to StaticFile Store: %s' % str(e)) raise Exception('Error while connecting to StaticFile Store: %s' % str(e)) def _ensureTableExists(self): ''' Make sure that the table exists before any other operation. Reconnect to Accumulo if the Connection is reset. ''' if not self.__connection.table_exists(self.__table): self.__log.info('table "{table}" does not exist in StaticFile Store. Creating the table'.format(table=self.__table)) self.__connection.create_table(self.__table) if not self.__connection.table_exists(self.__table): self.__log.error('Unable to ensure StaticFile Store table "{table} exists'.format(format(table=self.__table))) raise Exception('StaticFile Store: Unable to ensure table "{table}" exists'.format(table=self.__table)) def _ensureNoDuplicates(self, usrFacingUrlPrefix): ''' Ensure a single copy of file for a given usrFacingUrlPrefix ''' if self._getHash(usrFacingUrlPrefix) is not None: self.deleteFile(usrFacingUrlPrefix) def _putNofChunks(self, usrFacingUrlPrefix, length): ''' Put the number of chunks the static contents is stored ''' chunks = int(math.ceil(length / float(self.__chunk_size))) writer = self.__connection.create_batch_writer(self.__table) m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="nofchunks", val=str(chunks)) writer.add_mutation(m) writer.close() def _getNofChunks(self, usrFacingUrlPrefix): ''' Get the number of chunks the static contents is stored ''' scan_range = Range(srow=usrFacingUrlPrefix, scf=self.__cf, scq="nofchunks", erow=usrFacingUrlPrefix, ecf=self.__cf, ecq="nofchunks") for entry in self.__connection.scan(self.__table, scanrange=scan_range): return int(entry.val) return 0 def _getChunks(self, data): ''' Break the blob into CHUNK_SIZE. less than maxFrameSize in Accumulo proxy.properties ''' data_length = len(data) for i in range(0, data_length + 1, self.__chunk_size): yield data[i:i + self.__chunk_size] def _putHash(self, usrFacingUrlPrefix, hash_str): ''' Puts the Hash for usrFacingUrlPrefix ''' writer = self.__connection.create_batch_writer(self.__table) m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="hash", val=hash_str) writer.add_mutation(m) writer.close() def _getHash(self, usrFacingUrlPrefix): scan_range = Range(srow=usrFacingUrlPrefix, scf=self.__cf, scq="hash", erow=usrFacingUrlPrefix, ecf=self.__cf, ecq="hash") for entry in self.__connection.scan(self.__table, scanrange=scan_range): return str(entry.val) else: return None def reConnection(self): self._connect(self.__host, self.__port, self.__user, self.__password) def putFile(self, usrFacingUrlPrefix, hash_str, data): self._ensureTableExists() self._ensureNoDuplicates(usrFacingUrlPrefix) self._putHash(usrFacingUrlPrefix, hash_str) data_length = len(data) self._putNofChunks(usrFacingUrlPrefix, data_length) writer = self.__connection.create_batch_writer(self.__table) for i, chunk in enumerate(self._getChunks(data)): m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="chunk_{number:010d}".format(number=i), val=chunk) writer.add_mutation(m) self.__log.debug('added static file for "{url}" with hash "{hash}" of length "{length}"'.format(url=usrFacingUrlPrefix, hash=hash_str, length=data_length)) writer.close() def getFile(self, usrFacingUrlPrefix): ''' Assembles all the chunks for this row ''' self._ensureTableExists() data = array.array('c') # Create a byte array chunks = self._getNofChunks(usrFacingUrlPrefix) chunks_read = 0 for i in range(chunks): cq = 'chunk_{number:010d}'.format(number=i) for entry in self.__connection.scan(self.__table, None, cols=[[self.__cf, cq]]): if entry.row == usrFacingUrlPrefix and entry.cq.startswith("chunk_"): chunks_read += 1 data.extend(entry.val) # This code gets following error while retrieving over 96MB. Data stops at first chunk_000 # # java.lang.OutOfMemoryError: Java heap space # -XX:OnOutOfMemoryError="kill -9 %p" # Executing /bin/sh -c "kill -9 32597"... # [1]+ Exit 137 sudo -u accumulo /opt/accumulo/current/bin/accumulo proxy -p /opt/accumulo/current/conf/proxy.properties # startChunk = "chunk_{number:010d}".format(number=0) # endChunk = "chunk_{number:010d}".format(number=chunks) # scan_range = Range(srow=usrFacingUrlPrefix, scf=self.__cf, scq=startChunk, # erow=usrFacingUrlPrefix, ecf=self.__cf, ecq=endChunk) # for entry in self.__connection.scan(self.__table, scanrange=scan_range): # #self.__log.info("getFile: row = {0} cq= {1}".format(entry.row, entry.cq)) # if entry.cq.startswith("chunk_"): # self.__log.info("getFile: row = {0} cq= {1}".format(entry.row, entry.cq)) # chunks_read += 1 # data.extend(entry.val) self.__log.debug('retrieved static file for {url}'.format(url=usrFacingUrlPrefix))
return data.tostring() if data.buffer_info()[1] > 0 else None def deleteFile(self, usrFacingUrlPrefix): self._ensureTableExists() writer = self.__connection.create_batch_writer(self.__table) chunks = self._getNofChunks(usrFacingUrlPrefix) m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="hash", is_delete=True) m.put(cf=self.__cf, cq="nofchunks", is_delete=True) for i in range(chunks): cq = 'chunk_{number:010d}'.format(number=i) m.put(cf=self.__cf, cq=cq, is_delete=True) writer.add_mutation(m) self.__log.debug('removed static file for {url}'.format(url=usrFacingUrlPrefix)) writer.close() def getAttributes(self): ''' Returns the urlprefix and the hash of all the entries in table as tuple ''' self._ensureTableExists() for entry in self.__connection.scan(self.__table, None, cols=[[self.__cf, "hash"]]): yield (entry.row, str(entry.val)) else: yield (None, None)
if chunks_read != chunks: self.__log.error("did not read all the chunks from StaticFile Store")
random_line_split
ezRPStaticFileStore.py
# Copyright (C) 2013-2015 Computer Sciences Corporation # # 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. # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 import array import math import logging import logging.handlers from pyaccumulo import Accumulo, Mutation, Range class EzRPStaticStore(object): ''' Class to save and retrieve static content from Accumulo. cf = "static" For all rows cq = "hash" Stores the hash_value of Static File cq = "nofchunks" Stores the number of Chunks needed to store Static File cq = "chunk_000" .. "chunk_nnn" Stores the Chunks of Static File ''' def __init__(self, host="localhost", port=42424, user='root', password='secret', chunk_size=int(5*1048576), logger=None): self.__host = host self.__port = port self.__user = user self.__password = password self.__table = 'ezfrontend' self.__cf = 'static' self.__connection = None if logger is not None: self.__log = logger else: self.__log = logging.getLogger(self.__module__ + '.' + self.__class__.__name__) self.__log.addHandler(logging.NullHandler()) self.__chunk_size =int(chunk_size) self._connect(self.__host, self.__port, self.__user, self.__password) def _connect(self, host, port, user, password): try: self.__connection = Accumulo(host, port, user, password) self.__log.debug('Connected to StaticFile Store') except Exception as e: self.__log.exception('Error while connecting to StaticFile Store: %s' % str(e)) raise Exception('Error while connecting to StaticFile Store: %s' % str(e)) def _ensureTableExists(self): ''' Make sure that the table exists before any other operation. Reconnect to Accumulo if the Connection is reset. ''' if not self.__connection.table_exists(self.__table): self.__log.info('table "{table}" does not exist in StaticFile Store. Creating the table'.format(table=self.__table)) self.__connection.create_table(self.__table) if not self.__connection.table_exists(self.__table): self.__log.error('Unable to ensure StaticFile Store table "{table} exists'.format(format(table=self.__table))) raise Exception('StaticFile Store: Unable to ensure table "{table}" exists'.format(table=self.__table)) def _ensureNoDuplicates(self, usrFacingUrlPrefix): ''' Ensure a single copy of file for a given usrFacingUrlPrefix ''' if self._getHash(usrFacingUrlPrefix) is not None: self.deleteFile(usrFacingUrlPrefix) def _putNofChunks(self, usrFacingUrlPrefix, length): ''' Put the number of chunks the static contents is stored ''' chunks = int(math.ceil(length / float(self.__chunk_size))) writer = self.__connection.create_batch_writer(self.__table) m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="nofchunks", val=str(chunks)) writer.add_mutation(m) writer.close() def _getNofChunks(self, usrFacingUrlPrefix): ''' Get the number of chunks the static contents is stored ''' scan_range = Range(srow=usrFacingUrlPrefix, scf=self.__cf, scq="nofchunks", erow=usrFacingUrlPrefix, ecf=self.__cf, ecq="nofchunks") for entry in self.__connection.scan(self.__table, scanrange=scan_range): return int(entry.val) return 0 def _getChunks(self, data): ''' Break the blob into CHUNK_SIZE. less than maxFrameSize in Accumulo proxy.properties ''' data_length = len(data) for i in range(0, data_length + 1, self.__chunk_size): yield data[i:i + self.__chunk_size] def _putHash(self, usrFacingUrlPrefix, hash_str): ''' Puts the Hash for usrFacingUrlPrefix ''' writer = self.__connection.create_batch_writer(self.__table) m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="hash", val=hash_str) writer.add_mutation(m) writer.close() def _getHash(self, usrFacingUrlPrefix): scan_range = Range(srow=usrFacingUrlPrefix, scf=self.__cf, scq="hash", erow=usrFacingUrlPrefix, ecf=self.__cf, ecq="hash") for entry in self.__connection.scan(self.__table, scanrange=scan_range): return str(entry.val) else: return None def
(self): self._connect(self.__host, self.__port, self.__user, self.__password) def putFile(self, usrFacingUrlPrefix, hash_str, data): self._ensureTableExists() self._ensureNoDuplicates(usrFacingUrlPrefix) self._putHash(usrFacingUrlPrefix, hash_str) data_length = len(data) self._putNofChunks(usrFacingUrlPrefix, data_length) writer = self.__connection.create_batch_writer(self.__table) for i, chunk in enumerate(self._getChunks(data)): m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="chunk_{number:010d}".format(number=i), val=chunk) writer.add_mutation(m) self.__log.debug('added static file for "{url}" with hash "{hash}" of length "{length}"'.format(url=usrFacingUrlPrefix, hash=hash_str, length=data_length)) writer.close() def getFile(self, usrFacingUrlPrefix): ''' Assembles all the chunks for this row ''' self._ensureTableExists() data = array.array('c') # Create a byte array chunks = self._getNofChunks(usrFacingUrlPrefix) chunks_read = 0 for i in range(chunks): cq = 'chunk_{number:010d}'.format(number=i) for entry in self.__connection.scan(self.__table, None, cols=[[self.__cf, cq]]): if entry.row == usrFacingUrlPrefix and entry.cq.startswith("chunk_"): chunks_read += 1 data.extend(entry.val) # This code gets following error while retrieving over 96MB. Data stops at first chunk_000 # # java.lang.OutOfMemoryError: Java heap space # -XX:OnOutOfMemoryError="kill -9 %p" # Executing /bin/sh -c "kill -9 32597"... # [1]+ Exit 137 sudo -u accumulo /opt/accumulo/current/bin/accumulo proxy -p /opt/accumulo/current/conf/proxy.properties # startChunk = "chunk_{number:010d}".format(number=0) # endChunk = "chunk_{number:010d}".format(number=chunks) # scan_range = Range(srow=usrFacingUrlPrefix, scf=self.__cf, scq=startChunk, # erow=usrFacingUrlPrefix, ecf=self.__cf, ecq=endChunk) # for entry in self.__connection.scan(self.__table, scanrange=scan_range): # #self.__log.info("getFile: row = {0} cq= {1}".format(entry.row, entry.cq)) # if entry.cq.startswith("chunk_"): # self.__log.info("getFile: row = {0} cq= {1}".format(entry.row, entry.cq)) # chunks_read += 1 # data.extend(entry.val) self.__log.debug('retrieved static file for {url}'.format(url=usrFacingUrlPrefix)) if chunks_read != chunks: self.__log.error("did not read all the chunks from StaticFile Store") return data.tostring() if data.buffer_info()[1] > 0 else None def deleteFile(self, usrFacingUrlPrefix): self._ensureTableExists() writer = self.__connection.create_batch_writer(self.__table) chunks = self._getNofChunks(usrFacingUrlPrefix) m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="hash", is_delete=True) m.put(cf=self.__cf, cq="nofchunks", is_delete=True) for i in range(chunks): cq = 'chunk_{number:010d}'.format(number=i) m.put(cf=self.__cf, cq=cq, is_delete=True) writer.add_mutation(m) self.__log.debug('removed static file for {url}'.format(url=usrFacingUrlPrefix)) writer.close() def getAttributes(self): ''' Returns the urlprefix and the hash of all the entries in table as tuple ''' self._ensureTableExists() for entry in self.__connection.scan(self.__table, None, cols=[[self.__cf, "hash"]]): yield (entry.row, str(entry.val)) else: yield (None, None)
reConnection
identifier_name
ezRPStaticFileStore.py
# Copyright (C) 2013-2015 Computer Sciences Corporation # # 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. # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 import array import math import logging import logging.handlers from pyaccumulo import Accumulo, Mutation, Range class EzRPStaticStore(object): ''' Class to save and retrieve static content from Accumulo. cf = "static" For all rows cq = "hash" Stores the hash_value of Static File cq = "nofchunks" Stores the number of Chunks needed to store Static File cq = "chunk_000" .. "chunk_nnn" Stores the Chunks of Static File ''' def __init__(self, host="localhost", port=42424, user='root', password='secret', chunk_size=int(5*1048576), logger=None):
def _connect(self, host, port, user, password): try: self.__connection = Accumulo(host, port, user, password) self.__log.debug('Connected to StaticFile Store') except Exception as e: self.__log.exception('Error while connecting to StaticFile Store: %s' % str(e)) raise Exception('Error while connecting to StaticFile Store: %s' % str(e)) def _ensureTableExists(self): ''' Make sure that the table exists before any other operation. Reconnect to Accumulo if the Connection is reset. ''' if not self.__connection.table_exists(self.__table): self.__log.info('table "{table}" does not exist in StaticFile Store. Creating the table'.format(table=self.__table)) self.__connection.create_table(self.__table) if not self.__connection.table_exists(self.__table): self.__log.error('Unable to ensure StaticFile Store table "{table} exists'.format(format(table=self.__table))) raise Exception('StaticFile Store: Unable to ensure table "{table}" exists'.format(table=self.__table)) def _ensureNoDuplicates(self, usrFacingUrlPrefix): ''' Ensure a single copy of file for a given usrFacingUrlPrefix ''' if self._getHash(usrFacingUrlPrefix) is not None: self.deleteFile(usrFacingUrlPrefix) def _putNofChunks(self, usrFacingUrlPrefix, length): ''' Put the number of chunks the static contents is stored ''' chunks = int(math.ceil(length / float(self.__chunk_size))) writer = self.__connection.create_batch_writer(self.__table) m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="nofchunks", val=str(chunks)) writer.add_mutation(m) writer.close() def _getNofChunks(self, usrFacingUrlPrefix): ''' Get the number of chunks the static contents is stored ''' scan_range = Range(srow=usrFacingUrlPrefix, scf=self.__cf, scq="nofchunks", erow=usrFacingUrlPrefix, ecf=self.__cf, ecq="nofchunks") for entry in self.__connection.scan(self.__table, scanrange=scan_range): return int(entry.val) return 0 def _getChunks(self, data): ''' Break the blob into CHUNK_SIZE. less than maxFrameSize in Accumulo proxy.properties ''' data_length = len(data) for i in range(0, data_length + 1, self.__chunk_size): yield data[i:i + self.__chunk_size] def _putHash(self, usrFacingUrlPrefix, hash_str): ''' Puts the Hash for usrFacingUrlPrefix ''' writer = self.__connection.create_batch_writer(self.__table) m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="hash", val=hash_str) writer.add_mutation(m) writer.close() def _getHash(self, usrFacingUrlPrefix): scan_range = Range(srow=usrFacingUrlPrefix, scf=self.__cf, scq="hash", erow=usrFacingUrlPrefix, ecf=self.__cf, ecq="hash") for entry in self.__connection.scan(self.__table, scanrange=scan_range): return str(entry.val) else: return None def reConnection(self): self._connect(self.__host, self.__port, self.__user, self.__password) def putFile(self, usrFacingUrlPrefix, hash_str, data): self._ensureTableExists() self._ensureNoDuplicates(usrFacingUrlPrefix) self._putHash(usrFacingUrlPrefix, hash_str) data_length = len(data) self._putNofChunks(usrFacingUrlPrefix, data_length) writer = self.__connection.create_batch_writer(self.__table) for i, chunk in enumerate(self._getChunks(data)): m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="chunk_{number:010d}".format(number=i), val=chunk) writer.add_mutation(m) self.__log.debug('added static file for "{url}" with hash "{hash}" of length "{length}"'.format(url=usrFacingUrlPrefix, hash=hash_str, length=data_length)) writer.close() def getFile(self, usrFacingUrlPrefix): ''' Assembles all the chunks for this row ''' self._ensureTableExists() data = array.array('c') # Create a byte array chunks = self._getNofChunks(usrFacingUrlPrefix) chunks_read = 0 for i in range(chunks): cq = 'chunk_{number:010d}'.format(number=i) for entry in self.__connection.scan(self.__table, None, cols=[[self.__cf, cq]]): if entry.row == usrFacingUrlPrefix and entry.cq.startswith("chunk_"): chunks_read += 1 data.extend(entry.val) # This code gets following error while retrieving over 96MB. Data stops at first chunk_000 # # java.lang.OutOfMemoryError: Java heap space # -XX:OnOutOfMemoryError="kill -9 %p" # Executing /bin/sh -c "kill -9 32597"... # [1]+ Exit 137 sudo -u accumulo /opt/accumulo/current/bin/accumulo proxy -p /opt/accumulo/current/conf/proxy.properties # startChunk = "chunk_{number:010d}".format(number=0) # endChunk = "chunk_{number:010d}".format(number=chunks) # scan_range = Range(srow=usrFacingUrlPrefix, scf=self.__cf, scq=startChunk, # erow=usrFacingUrlPrefix, ecf=self.__cf, ecq=endChunk) # for entry in self.__connection.scan(self.__table, scanrange=scan_range): # #self.__log.info("getFile: row = {0} cq= {1}".format(entry.row, entry.cq)) # if entry.cq.startswith("chunk_"): # self.__log.info("getFile: row = {0} cq= {1}".format(entry.row, entry.cq)) # chunks_read += 1 # data.extend(entry.val) self.__log.debug('retrieved static file for {url}'.format(url=usrFacingUrlPrefix)) if chunks_read != chunks: self.__log.error("did not read all the chunks from StaticFile Store") return data.tostring() if data.buffer_info()[1] > 0 else None def deleteFile(self, usrFacingUrlPrefix): self._ensureTableExists() writer = self.__connection.create_batch_writer(self.__table) chunks = self._getNofChunks(usrFacingUrlPrefix) m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="hash", is_delete=True) m.put(cf=self.__cf, cq="nofchunks", is_delete=True) for i in range(chunks): cq = 'chunk_{number:010d}'.format(number=i) m.put(cf=self.__cf, cq=cq, is_delete=True) writer.add_mutation(m) self.__log.debug('removed static file for {url}'.format(url=usrFacingUrlPrefix)) writer.close() def getAttributes(self): ''' Returns the urlprefix and the hash of all the entries in table as tuple ''' self._ensureTableExists() for entry in self.__connection.scan(self.__table, None, cols=[[self.__cf, "hash"]]): yield (entry.row, str(entry.val)) else: yield (None, None)
self.__host = host self.__port = port self.__user = user self.__password = password self.__table = 'ezfrontend' self.__cf = 'static' self.__connection = None if logger is not None: self.__log = logger else: self.__log = logging.getLogger(self.__module__ + '.' + self.__class__.__name__) self.__log.addHandler(logging.NullHandler()) self.__chunk_size =int(chunk_size) self._connect(self.__host, self.__port, self.__user, self.__password)
identifier_body
ezRPStaticFileStore.py
# Copyright (C) 2013-2015 Computer Sciences Corporation # # 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. # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 import array import math import logging import logging.handlers from pyaccumulo import Accumulo, Mutation, Range class EzRPStaticStore(object): ''' Class to save and retrieve static content from Accumulo. cf = "static" For all rows cq = "hash" Stores the hash_value of Static File cq = "nofchunks" Stores the number of Chunks needed to store Static File cq = "chunk_000" .. "chunk_nnn" Stores the Chunks of Static File ''' def __init__(self, host="localhost", port=42424, user='root', password='secret', chunk_size=int(5*1048576), logger=None): self.__host = host self.__port = port self.__user = user self.__password = password self.__table = 'ezfrontend' self.__cf = 'static' self.__connection = None if logger is not None: self.__log = logger else: self.__log = logging.getLogger(self.__module__ + '.' + self.__class__.__name__) self.__log.addHandler(logging.NullHandler()) self.__chunk_size =int(chunk_size) self._connect(self.__host, self.__port, self.__user, self.__password) def _connect(self, host, port, user, password): try: self.__connection = Accumulo(host, port, user, password) self.__log.debug('Connected to StaticFile Store') except Exception as e: self.__log.exception('Error while connecting to StaticFile Store: %s' % str(e)) raise Exception('Error while connecting to StaticFile Store: %s' % str(e)) def _ensureTableExists(self): ''' Make sure that the table exists before any other operation. Reconnect to Accumulo if the Connection is reset. ''' if not self.__connection.table_exists(self.__table):
def _ensureNoDuplicates(self, usrFacingUrlPrefix): ''' Ensure a single copy of file for a given usrFacingUrlPrefix ''' if self._getHash(usrFacingUrlPrefix) is not None: self.deleteFile(usrFacingUrlPrefix) def _putNofChunks(self, usrFacingUrlPrefix, length): ''' Put the number of chunks the static contents is stored ''' chunks = int(math.ceil(length / float(self.__chunk_size))) writer = self.__connection.create_batch_writer(self.__table) m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="nofchunks", val=str(chunks)) writer.add_mutation(m) writer.close() def _getNofChunks(self, usrFacingUrlPrefix): ''' Get the number of chunks the static contents is stored ''' scan_range = Range(srow=usrFacingUrlPrefix, scf=self.__cf, scq="nofchunks", erow=usrFacingUrlPrefix, ecf=self.__cf, ecq="nofchunks") for entry in self.__connection.scan(self.__table, scanrange=scan_range): return int(entry.val) return 0 def _getChunks(self, data): ''' Break the blob into CHUNK_SIZE. less than maxFrameSize in Accumulo proxy.properties ''' data_length = len(data) for i in range(0, data_length + 1, self.__chunk_size): yield data[i:i + self.__chunk_size] def _putHash(self, usrFacingUrlPrefix, hash_str): ''' Puts the Hash for usrFacingUrlPrefix ''' writer = self.__connection.create_batch_writer(self.__table) m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="hash", val=hash_str) writer.add_mutation(m) writer.close() def _getHash(self, usrFacingUrlPrefix): scan_range = Range(srow=usrFacingUrlPrefix, scf=self.__cf, scq="hash", erow=usrFacingUrlPrefix, ecf=self.__cf, ecq="hash") for entry in self.__connection.scan(self.__table, scanrange=scan_range): return str(entry.val) else: return None def reConnection(self): self._connect(self.__host, self.__port, self.__user, self.__password) def putFile(self, usrFacingUrlPrefix, hash_str, data): self._ensureTableExists() self._ensureNoDuplicates(usrFacingUrlPrefix) self._putHash(usrFacingUrlPrefix, hash_str) data_length = len(data) self._putNofChunks(usrFacingUrlPrefix, data_length) writer = self.__connection.create_batch_writer(self.__table) for i, chunk in enumerate(self._getChunks(data)): m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="chunk_{number:010d}".format(number=i), val=chunk) writer.add_mutation(m) self.__log.debug('added static file for "{url}" with hash "{hash}" of length "{length}"'.format(url=usrFacingUrlPrefix, hash=hash_str, length=data_length)) writer.close() def getFile(self, usrFacingUrlPrefix): ''' Assembles all the chunks for this row ''' self._ensureTableExists() data = array.array('c') # Create a byte array chunks = self._getNofChunks(usrFacingUrlPrefix) chunks_read = 0 for i in range(chunks): cq = 'chunk_{number:010d}'.format(number=i) for entry in self.__connection.scan(self.__table, None, cols=[[self.__cf, cq]]): if entry.row == usrFacingUrlPrefix and entry.cq.startswith("chunk_"): chunks_read += 1 data.extend(entry.val) # This code gets following error while retrieving over 96MB. Data stops at first chunk_000 # # java.lang.OutOfMemoryError: Java heap space # -XX:OnOutOfMemoryError="kill -9 %p" # Executing /bin/sh -c "kill -9 32597"... # [1]+ Exit 137 sudo -u accumulo /opt/accumulo/current/bin/accumulo proxy -p /opt/accumulo/current/conf/proxy.properties # startChunk = "chunk_{number:010d}".format(number=0) # endChunk = "chunk_{number:010d}".format(number=chunks) # scan_range = Range(srow=usrFacingUrlPrefix, scf=self.__cf, scq=startChunk, # erow=usrFacingUrlPrefix, ecf=self.__cf, ecq=endChunk) # for entry in self.__connection.scan(self.__table, scanrange=scan_range): # #self.__log.info("getFile: row = {0} cq= {1}".format(entry.row, entry.cq)) # if entry.cq.startswith("chunk_"): # self.__log.info("getFile: row = {0} cq= {1}".format(entry.row, entry.cq)) # chunks_read += 1 # data.extend(entry.val) self.__log.debug('retrieved static file for {url}'.format(url=usrFacingUrlPrefix)) if chunks_read != chunks: self.__log.error("did not read all the chunks from StaticFile Store") return data.tostring() if data.buffer_info()[1] > 0 else None def deleteFile(self, usrFacingUrlPrefix): self._ensureTableExists() writer = self.__connection.create_batch_writer(self.__table) chunks = self._getNofChunks(usrFacingUrlPrefix) m = Mutation(usrFacingUrlPrefix) m.put(cf=self.__cf, cq="hash", is_delete=True) m.put(cf=self.__cf, cq="nofchunks", is_delete=True) for i in range(chunks): cq = 'chunk_{number:010d}'.format(number=i) m.put(cf=self.__cf, cq=cq, is_delete=True) writer.add_mutation(m) self.__log.debug('removed static file for {url}'.format(url=usrFacingUrlPrefix)) writer.close() def getAttributes(self): ''' Returns the urlprefix and the hash of all the entries in table as tuple ''' self._ensureTableExists() for entry in self.__connection.scan(self.__table, None, cols=[[self.__cf, "hash"]]): yield (entry.row, str(entry.val)) else: yield (None, None)
self.__log.info('table "{table}" does not exist in StaticFile Store. Creating the table'.format(table=self.__table)) self.__connection.create_table(self.__table) if not self.__connection.table_exists(self.__table): self.__log.error('Unable to ensure StaticFile Store table "{table} exists'.format(format(table=self.__table))) raise Exception('StaticFile Store: Unable to ensure table "{table}" exists'.format(table=self.__table))
conditional_block
cluster.py
# -*- coding: utf8 ''' Common code for clustering tasks ''' from __future__ import division, print_function from sklearn.cluster import KMeans from sklearn.cluster import MiniBatchKMeans from sklearn.metrics import pairwise from vod.stats.ci import half_confidence_interval_size import numpy as np def kmeans_betacv(data, num_cluster, batch_kmeans=False, n_runs = 10, confidence = 0.90): ''' Computes the BetaCV for running Kmeans on the dataset. This method returns the BetaCV value and half of the size of the confidence interval for the same value (BetaCV is an average or the number of runs given). Arguments --------- data: matrix A matrix of observations. If this is sparse, `batch_kmeans` must be True num_cluster: int number of clusters to run k-means for batch_kmeans: bool (defauts to False) if `sklearn.cluster.MiniBatchKMeans` should be used. This is faster and suitable for sparse datasets, but less accurate. n_runs: int (default = 10) Number of runs to compute the BetaCV confidence: double [0, 1) (default = 0.9) The confidence used to compute half the confidence interval size Returns ------- The betacv and half of the confidence interval size ''' algorithm = None if not batch_kmeans: algorithm = KMeans(num_cluster) else: algorithm = MiniBatchKMeans(num_cluster) inter_array = np.zeros(n_runs) intra_array = np.zeros(n_runs) for i in xrange(n_runs): #Run K-Means algorithm.fit(data) centers = algorithm.cluster_centers_ labels = algorithm.labels_ #KMeans in sklearn uses euclidean dist_centers = pairwise.euclidean_distances(centers) #Inter distance mean_dist_between_centers = np.mean(dist_centers) inter_array[i] = mean_dist_between_centers
dist = dist_all_centers[doc_id, cluster] intra_dists.append(dist) intra_array[i] = np.mean(intra_dists) betacv = intra_array / inter_array cinterval = half_confidence_interval_size(betacv, confidence) return np.mean(betacv), cinterval
#Intra distance dist_all_centers = algorithm.transform(data) intra_dists = [] for doc_id, cluster in enumerate(labels):
random_line_split
cluster.py
# -*- coding: utf8 ''' Common code for clustering tasks ''' from __future__ import division, print_function from sklearn.cluster import KMeans from sklearn.cluster import MiniBatchKMeans from sklearn.metrics import pairwise from vod.stats.ci import half_confidence_interval_size import numpy as np def kmeans_betacv(data, num_cluster, batch_kmeans=False, n_runs = 10, confidence = 0.90):
''' Computes the BetaCV for running Kmeans on the dataset. This method returns the BetaCV value and half of the size of the confidence interval for the same value (BetaCV is an average or the number of runs given). Arguments --------- data: matrix A matrix of observations. If this is sparse, `batch_kmeans` must be True num_cluster: int number of clusters to run k-means for batch_kmeans: bool (defauts to False) if `sklearn.cluster.MiniBatchKMeans` should be used. This is faster and suitable for sparse datasets, but less accurate. n_runs: int (default = 10) Number of runs to compute the BetaCV confidence: double [0, 1) (default = 0.9) The confidence used to compute half the confidence interval size Returns ------- The betacv and half of the confidence interval size ''' algorithm = None if not batch_kmeans: algorithm = KMeans(num_cluster) else: algorithm = MiniBatchKMeans(num_cluster) inter_array = np.zeros(n_runs) intra_array = np.zeros(n_runs) for i in xrange(n_runs): #Run K-Means algorithm.fit(data) centers = algorithm.cluster_centers_ labels = algorithm.labels_ #KMeans in sklearn uses euclidean dist_centers = pairwise.euclidean_distances(centers) #Inter distance mean_dist_between_centers = np.mean(dist_centers) inter_array[i] = mean_dist_between_centers #Intra distance dist_all_centers = algorithm.transform(data) intra_dists = [] for doc_id, cluster in enumerate(labels): dist = dist_all_centers[doc_id, cluster] intra_dists.append(dist) intra_array[i] = np.mean(intra_dists) betacv = intra_array / inter_array cinterval = half_confidence_interval_size(betacv, confidence) return np.mean(betacv), cinterval
identifier_body
cluster.py
# -*- coding: utf8 ''' Common code for clustering tasks ''' from __future__ import division, print_function from sklearn.cluster import KMeans from sklearn.cluster import MiniBatchKMeans from sklearn.metrics import pairwise from vod.stats.ci import half_confidence_interval_size import numpy as np def
(data, num_cluster, batch_kmeans=False, n_runs = 10, confidence = 0.90): ''' Computes the BetaCV for running Kmeans on the dataset. This method returns the BetaCV value and half of the size of the confidence interval for the same value (BetaCV is an average or the number of runs given). Arguments --------- data: matrix A matrix of observations. If this is sparse, `batch_kmeans` must be True num_cluster: int number of clusters to run k-means for batch_kmeans: bool (defauts to False) if `sklearn.cluster.MiniBatchKMeans` should be used. This is faster and suitable for sparse datasets, but less accurate. n_runs: int (default = 10) Number of runs to compute the BetaCV confidence: double [0, 1) (default = 0.9) The confidence used to compute half the confidence interval size Returns ------- The betacv and half of the confidence interval size ''' algorithm = None if not batch_kmeans: algorithm = KMeans(num_cluster) else: algorithm = MiniBatchKMeans(num_cluster) inter_array = np.zeros(n_runs) intra_array = np.zeros(n_runs) for i in xrange(n_runs): #Run K-Means algorithm.fit(data) centers = algorithm.cluster_centers_ labels = algorithm.labels_ #KMeans in sklearn uses euclidean dist_centers = pairwise.euclidean_distances(centers) #Inter distance mean_dist_between_centers = np.mean(dist_centers) inter_array[i] = mean_dist_between_centers #Intra distance dist_all_centers = algorithm.transform(data) intra_dists = [] for doc_id, cluster in enumerate(labels): dist = dist_all_centers[doc_id, cluster] intra_dists.append(dist) intra_array[i] = np.mean(intra_dists) betacv = intra_array / inter_array cinterval = half_confidence_interval_size(betacv, confidence) return np.mean(betacv), cinterval
kmeans_betacv
identifier_name
cluster.py
# -*- coding: utf8 ''' Common code for clustering tasks ''' from __future__ import division, print_function from sklearn.cluster import KMeans from sklearn.cluster import MiniBatchKMeans from sklearn.metrics import pairwise from vod.stats.ci import half_confidence_interval_size import numpy as np def kmeans_betacv(data, num_cluster, batch_kmeans=False, n_runs = 10, confidence = 0.90): ''' Computes the BetaCV for running Kmeans on the dataset. This method returns the BetaCV value and half of the size of the confidence interval for the same value (BetaCV is an average or the number of runs given). Arguments --------- data: matrix A matrix of observations. If this is sparse, `batch_kmeans` must be True num_cluster: int number of clusters to run k-means for batch_kmeans: bool (defauts to False) if `sklearn.cluster.MiniBatchKMeans` should be used. This is faster and suitable for sparse datasets, but less accurate. n_runs: int (default = 10) Number of runs to compute the BetaCV confidence: double [0, 1) (default = 0.9) The confidence used to compute half the confidence interval size Returns ------- The betacv and half of the confidence interval size ''' algorithm = None if not batch_kmeans: algorithm = KMeans(num_cluster) else: algorithm = MiniBatchKMeans(num_cluster) inter_array = np.zeros(n_runs) intra_array = np.zeros(n_runs) for i in xrange(n_runs): #Run K-Means algorithm.fit(data) centers = algorithm.cluster_centers_ labels = algorithm.labels_ #KMeans in sklearn uses euclidean dist_centers = pairwise.euclidean_distances(centers) #Inter distance mean_dist_between_centers = np.mean(dist_centers) inter_array[i] = mean_dist_between_centers #Intra distance dist_all_centers = algorithm.transform(data) intra_dists = [] for doc_id, cluster in enumerate(labels):
intra_array[i] = np.mean(intra_dists) betacv = intra_array / inter_array cinterval = half_confidence_interval_size(betacv, confidence) return np.mean(betacv), cinterval
dist = dist_all_centers[doc_id, cluster] intra_dists.append(dist)
conditional_block
locustfile.py
from locust import HttpLocust, TaskSet, task class WebsiteTasks(TaskSet): @task def page1(self): self.client.get("/sugestoes-para/6a-feira-da-quarta-semana-da-pascoa/") @task def page2(self): self.client.get("/sugestoes-para/5a-feira-da-quarta-semana-da-pascoa/") @task def page3(self): self.client.get("/sugestoes-para/4a-feira-da-quarta-semana-da-pascoa/") @task def page4(self): self.client.get("/sugestoes-para/3a-feira-da-quarta-semana-da-pascoa/") @task def musica1(self): self.client.get("/musica/ressuscitou/") @task def musica2(self): self.client.get("/musica/prova-de-amor-maior-nao-ha/") @task def musica3(self): self.client.get("/musica/porque-ele-vive/") @task
class WebsiteUser(HttpLocust): task_set = WebsiteTasks min_wait = 5000 max_wait = 15000
def musica4(self): self.client.get("/musica/o-senhor-ressuscitou-aleluia/")
random_line_split
locustfile.py
from locust import HttpLocust, TaskSet, task class WebsiteTasks(TaskSet): @task def page1(self): self.client.get("/sugestoes-para/6a-feira-da-quarta-semana-da-pascoa/") @task def page2(self):
@task def page3(self): self.client.get("/sugestoes-para/4a-feira-da-quarta-semana-da-pascoa/") @task def page4(self): self.client.get("/sugestoes-para/3a-feira-da-quarta-semana-da-pascoa/") @task def musica1(self): self.client.get("/musica/ressuscitou/") @task def musica2(self): self.client.get("/musica/prova-de-amor-maior-nao-ha/") @task def musica3(self): self.client.get("/musica/porque-ele-vive/") @task def musica4(self): self.client.get("/musica/o-senhor-ressuscitou-aleluia/") class WebsiteUser(HttpLocust): task_set = WebsiteTasks min_wait = 5000 max_wait = 15000
self.client.get("/sugestoes-para/5a-feira-da-quarta-semana-da-pascoa/")
identifier_body
locustfile.py
from locust import HttpLocust, TaskSet, task class WebsiteTasks(TaskSet): @task def page1(self): self.client.get("/sugestoes-para/6a-feira-da-quarta-semana-da-pascoa/") @task def page2(self): self.client.get("/sugestoes-para/5a-feira-da-quarta-semana-da-pascoa/") @task def page3(self): self.client.get("/sugestoes-para/4a-feira-da-quarta-semana-da-pascoa/") @task def
(self): self.client.get("/sugestoes-para/3a-feira-da-quarta-semana-da-pascoa/") @task def musica1(self): self.client.get("/musica/ressuscitou/") @task def musica2(self): self.client.get("/musica/prova-de-amor-maior-nao-ha/") @task def musica3(self): self.client.get("/musica/porque-ele-vive/") @task def musica4(self): self.client.get("/musica/o-senhor-ressuscitou-aleluia/") class WebsiteUser(HttpLocust): task_set = WebsiteTasks min_wait = 5000 max_wait = 15000
page4
identifier_name
apatite-postgres-connection.js
'use strict'; var ApatiteConnection = require('../apatite-connection.js'); var ApatiteError = require('../../error/apatite-error'); var ApatiteUtil = require('../../util.js'); var pgModuleName = 'pg'; var pg; if (ApatiteUtil.existsModule(pgModuleName)) // must be checked otherwise would get test discovery error for mocha tests in VS pg = require(pgModuleName); class ApatitePostgresConnection extends ApatiteConnection { co
ialect) { super(dialect); this.poolEndConnCallback = null; } static getModuleName() { return pgModuleName; } static createNewPool(configOpts) { return new pg.Pool(configOpts) } basicConnect(onConnected) { var connectionOptions = this.dialect.connectionOptions; var connStr = `postgres://${connectionOptions.userName}:${connectionOptions.password}@${connectionOptions.connectionInfo}`; var self = this; if (this.dialect.useConnectionPool) { self.dialect.connectionPool.connect(function(err, client, done) { self.databaseConnection = client; self.poolEndConnCallback = done; if (err) { done(err); } onConnected(err); }); } else { this.databaseConnection = new pg.Client(connStr); this.databaseConnection.connect(function (err) { if (err) { self.disconnect(function (disconnErr) { onConnected(err); }); } else onConnected(err); }); } } setStatementResult(sqlStatement, result) { if (result) sqlStatement.setSQLResult(result.rows); } basicDisconnect(onDisconnected) { if (this.dialect.useConnectionPool) { if (this.poolEndConnCallback) { this.poolEndConnCallback(); this.poolEndConnCallback = null; } } else if (this.databaseConnection) { this.databaseConnection.end(); } onDisconnected(null); } basicExecuteSQLString(sqlStr, bindVariables, onExecuted, options) { var self = this; this.setDBConnection(function(connErr) { if (connErr) { self.onSQLExecuted(connErr, null, onExecuted, options); return; } var bindVars = self.buildBindVariableValues(bindVariables); if (options && options.returnCursorStream) { var query = self.databaseConnection.query(sqlStr, bindVars); self.onSQLExecuted(null, query, onExecuted, options); } else { self.databaseConnection.query(sqlStr, bindVars, function (err, result) { self.onSQLExecuted(err, result, onExecuted, options); }); } }); } } module.exports = ApatitePostgresConnection;
nstructor(d
identifier_name
apatite-postgres-connection.js
'use strict'; var ApatiteConnection = require('../apatite-connection.js'); var ApatiteError = require('../../error/apatite-error'); var ApatiteUtil = require('../../util.js'); var pgModuleName = 'pg'; var pg; if (ApatiteUtil.existsModule(pgModuleName)) // must be checked otherwise would get test discovery error for mocha tests in VS pg = require(pgModuleName);
static getModuleName() { return pgModuleName; } static createNewPool(configOpts) { return new pg.Pool(configOpts) } basicConnect(onConnected) { var connectionOptions = this.dialect.connectionOptions; var connStr = `postgres://${connectionOptions.userName}:${connectionOptions.password}@${connectionOptions.connectionInfo}`; var self = this; if (this.dialect.useConnectionPool) { self.dialect.connectionPool.connect(function(err, client, done) { self.databaseConnection = client; self.poolEndConnCallback = done; if (err) { done(err); } onConnected(err); }); } else { this.databaseConnection = new pg.Client(connStr); this.databaseConnection.connect(function (err) { if (err) { self.disconnect(function (disconnErr) { onConnected(err); }); } else onConnected(err); }); } } setStatementResult(sqlStatement, result) { if (result) sqlStatement.setSQLResult(result.rows); } basicDisconnect(onDisconnected) { if (this.dialect.useConnectionPool) { if (this.poolEndConnCallback) { this.poolEndConnCallback(); this.poolEndConnCallback = null; } } else if (this.databaseConnection) { this.databaseConnection.end(); } onDisconnected(null); } basicExecuteSQLString(sqlStr, bindVariables, onExecuted, options) { var self = this; this.setDBConnection(function(connErr) { if (connErr) { self.onSQLExecuted(connErr, null, onExecuted, options); return; } var bindVars = self.buildBindVariableValues(bindVariables); if (options && options.returnCursorStream) { var query = self.databaseConnection.query(sqlStr, bindVars); self.onSQLExecuted(null, query, onExecuted, options); } else { self.databaseConnection.query(sqlStr, bindVars, function (err, result) { self.onSQLExecuted(err, result, onExecuted, options); }); } }); } } module.exports = ApatitePostgresConnection;
class ApatitePostgresConnection extends ApatiteConnection { constructor(dialect) { super(dialect); this.poolEndConnCallback = null; }
random_line_split
apatite-postgres-connection.js
'use strict'; var ApatiteConnection = require('../apatite-connection.js'); var ApatiteError = require('../../error/apatite-error'); var ApatiteUtil = require('../../util.js'); var pgModuleName = 'pg'; var pg; if (ApatiteUtil.existsModule(pgModuleName)) // must be checked otherwise would get test discovery error for mocha tests in VS pg = require(pgModuleName); class ApatitePostgresConnection extends ApatiteConnection { constructor(dialect) { super(dialect); this.poolEndConnCallback = null; } static getModuleName() { return pgModuleName; } static createNewPool(configOpts) { return new pg.Pool(configOpts) } basicConnect(onConnected) { var connectionOptions = this.dialect.connectionOptions; var connStr = `postgres://${connectionOptions.userName}:${connectionOptions.password}@${connectionOptions.connectionInfo}`; var self = this; if (this.dialect.useConnectionPool) { self.dialect.connectionPool.connect(function(err, client, done) { self.databaseConnection = client; self.poolEndConnCallback = done; if (err) { done(err); } onConnected(err); }); } else { this.databaseConnection = new pg.Client(connStr); this.databaseConnection.connect(function (err) { if (err) { self.disconnect(function (disconnErr) { onConnected(err); }); } else onConnected(err); }); } } setStatementResult(sqlStatement, result) { if (result) sqlStatement.setSQLResult(result.rows); } basicDisconnect(onDisconnected) { if (this.dialect.useConnectionPool) {
else if (this.databaseConnection) { this.databaseConnection.end(); } onDisconnected(null); } basicExecuteSQLString(sqlStr, bindVariables, onExecuted, options) { var self = this; this.setDBConnection(function(connErr) { if (connErr) { self.onSQLExecuted(connErr, null, onExecuted, options); return; } var bindVars = self.buildBindVariableValues(bindVariables); if (options && options.returnCursorStream) { var query = self.databaseConnection.query(sqlStr, bindVars); self.onSQLExecuted(null, query, onExecuted, options); } else { self.databaseConnection.query(sqlStr, bindVars, function (err, result) { self.onSQLExecuted(err, result, onExecuted, options); }); } }); } } module.exports = ApatitePostgresConnection;
if (this.poolEndConnCallback) { this.poolEndConnCallback(); this.poolEndConnCallback = null; } }
conditional_block
widget.component.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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. */ import * as _ from 'lodash'; const WidgetComponent: ng.IComponentOptions = { template: require('./widget.html'), bindings: { widget: '<' }, controller: function($scope: ng.IScope) { 'ngInject'; $scope.$on('gridster-resized', function () { $scope.$broadcast('onWidgetResize'); }); let that = this; $scope.$on('onTimeframeChange', function (event, timeframe) { // Associate the new timeframe to the chart request _.assignIn(that.widget.chart.request, { interval: timeframe.interval, from: timeframe.from, to: timeframe.to }); that.reload(); }); $scope.$on('onQueryFilterChange', function (event, query) { // Associate the new query filter to the chart request _.assignIn(that.widget.chart.request, { query: query }); that.reload(); }); this.reload = function() { // Call the analytics service this.fetchData = true; let chart = this.widget.chart; // Prepare arguments let args = [this.widget.root, chart.request]; if (! this.widget.root)
chart.service.function .apply(chart.service.caller, args) .then(response => { this.fetchData = false; this.results = response.data; }); }; } }; export default WidgetComponent;
{ args.splice(0,1); }
conditional_block
widget.component.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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. */ import * as _ from 'lodash'; const WidgetComponent: ng.IComponentOptions = { template: require('./widget.html'), bindings: { widget: '<' }, controller: function($scope: ng.IScope) { 'ngInject'; $scope.$on('gridster-resized', function () { $scope.$broadcast('onWidgetResize'); }); let that = this; $scope.$on('onTimeframeChange', function (event, timeframe) { // Associate the new timeframe to the chart request _.assignIn(that.widget.chart.request, { interval: timeframe.interval, from: timeframe.from, to: timeframe.to }); that.reload(); }); $scope.$on('onQueryFilterChange', function (event, query) { // Associate the new query filter to the chart request _.assignIn(that.widget.chart.request, { query: query }); that.reload(); }); this.reload = function() { // Call the analytics service this.fetchData = true; let chart = this.widget.chart; // Prepare arguments let args = [this.widget.root, chart.request]; if (! this.widget.root) { args.splice(0,1); } chart.service.function .apply(chart.service.caller, args) .then(response => { this.fetchData = false; this.results = response.data; }); }; }
}; export default WidgetComponent;
random_line_split
url_extractor.py
""" The consumer's code. It takes HTML from the queue and outputs the URIs found in it. """ import asyncio import json import logging from typing import List from urllib.parse import urljoin import aioredis from bs4 import BeautifulSoup from . import app_cli, redis_queue _log = logging.getLogger('url_extractor') def
(html: str, base_url: str) -> List[str]: """Gets all valid links from a site and returns them as URIs (some links may be relative. If the URIs scraped here would go back into the system to have more URIs scraped from their HTML, we would need to filter out all those who are not HTTP or HTTPS. Also, assuming that many consumers and many producers would be running at the same time, connected to one Redis instance, we would need to cache normalized versions or visited URIs without fragments (https://tools.ietf.org/html/rfc3986#section-3.5) so we don't fall into loops. For example two sites referencing each other. The cached entries could have time-to-live (Redis EXPIRE command), so we could refresh our knowledge about a site eventually. """ soup = BeautifulSoup(html, 'html.parser') href = 'href' return [urljoin(base_url, link.get(href)) for link in soup.find_all('a') if link.has_attr(href)] async def _scrape_urls_from_queued_html(redis_pool: aioredis.RedisPool): _log.info('Processing HTML from queue...') while True: try: html_payload = await redis_queue.pop(redis_pool) _log.info('Processing HTML from URL %s', html_payload.url) scraped_urls = _scrape_urls(html_payload.html, html_payload.url) _log.info('Scraped URIs from URL %s', html_payload.url) output_json = {html_payload.url: scraped_urls} # flush for anyone who is watching the stream print(json.dumps(output_json), flush=True) except redis_queue.QueueEmptyError: # wait for work to become available await asyncio.sleep(1) # pragma: no cover def main(): """Run the URL extractor (the consumer). """ app_cli.setup_logging() args_parser = app_cli.get_redis_args_parser( 'Start a worker that will get URL/HTML pairs from a Redis queue and for each of those ' 'pairs output (on separate lines) a JSON in format {ORIGINATING_URL: [FOUND_URLS_LIST]}') args = args_parser.parse_args() loop = app_cli.get_event_loop() _log.info('Creating a pool of connections to Redis at %s:%d.', args.redis_host, args.redis_port) # the pool won't be closed explicitly, since the process needs to be terminated to stop anyway redis_pool = loop.run_until_complete( aioredis.create_pool((args.redis_host, args.redis_port))) loop.run_until_complete(_scrape_urls_from_queued_html(redis_pool)) if __name__ == '__main__': main()
_scrape_urls
identifier_name
url_extractor.py
""" The consumer's code. It takes HTML from the queue and outputs the URIs found in it. """ import asyncio import json import logging from typing import List from urllib.parse import urljoin import aioredis from bs4 import BeautifulSoup from . import app_cli, redis_queue _log = logging.getLogger('url_extractor') def _scrape_urls(html: str, base_url: str) -> List[str]:
async def _scrape_urls_from_queued_html(redis_pool: aioredis.RedisPool): _log.info('Processing HTML from queue...') while True: try: html_payload = await redis_queue.pop(redis_pool) _log.info('Processing HTML from URL %s', html_payload.url) scraped_urls = _scrape_urls(html_payload.html, html_payload.url) _log.info('Scraped URIs from URL %s', html_payload.url) output_json = {html_payload.url: scraped_urls} # flush for anyone who is watching the stream print(json.dumps(output_json), flush=True) except redis_queue.QueueEmptyError: # wait for work to become available await asyncio.sleep(1) # pragma: no cover def main(): """Run the URL extractor (the consumer). """ app_cli.setup_logging() args_parser = app_cli.get_redis_args_parser( 'Start a worker that will get URL/HTML pairs from a Redis queue and for each of those ' 'pairs output (on separate lines) a JSON in format {ORIGINATING_URL: [FOUND_URLS_LIST]}') args = args_parser.parse_args() loop = app_cli.get_event_loop() _log.info('Creating a pool of connections to Redis at %s:%d.', args.redis_host, args.redis_port) # the pool won't be closed explicitly, since the process needs to be terminated to stop anyway redis_pool = loop.run_until_complete( aioredis.create_pool((args.redis_host, args.redis_port))) loop.run_until_complete(_scrape_urls_from_queued_html(redis_pool)) if __name__ == '__main__': main()
"""Gets all valid links from a site and returns them as URIs (some links may be relative. If the URIs scraped here would go back into the system to have more URIs scraped from their HTML, we would need to filter out all those who are not HTTP or HTTPS. Also, assuming that many consumers and many producers would be running at the same time, connected to one Redis instance, we would need to cache normalized versions or visited URIs without fragments (https://tools.ietf.org/html/rfc3986#section-3.5) so we don't fall into loops. For example two sites referencing each other. The cached entries could have time-to-live (Redis EXPIRE command), so we could refresh our knowledge about a site eventually. """ soup = BeautifulSoup(html, 'html.parser') href = 'href' return [urljoin(base_url, link.get(href)) for link in soup.find_all('a') if link.has_attr(href)]
identifier_body