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
main.rs
// Copyright 2016 Gomez Guillaume // // 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. use std::fs; use std::path::Path; use std::str::FromStr; struct CleanOptions { recursive: bool, verbose: bool, confirmation: bool, level: u32 } fn ask_confirmation(file: &Path) -> bool { if let Some(filename) = file.to_str() { loop { print!("clean: remove \x1b[37;1m'{}'\x1b[0m (y/n) ? ", filename); let mut s = String::new(); match std::io::stdin().read_line(&mut s) { Ok(_) => { let tmp_s = s.replace("\r\n", "").replace("\n", ""); if tmp_s == "y" || tmp_s == "yes" { return true; } else if tmp_s == "n" || tmp_s == "no" { return false; } } Err(_) => {} } } } else { println!("Unknown error on '{:?}'...", file); false } } fn start_clean(options: &CleanOptions, entry: &Path, level: u32) { let m = match ::std::fs::metadata(&entry) { Ok(e) => e, Err(e) => { println!("An error occured on '{:?}': {}", entry, e); return } }; let entry_name = match entry.to_str() { Some(n) => n, None => { println!("Invalid entry '{:?}'", entry); return } }; if m.is_file() || m.is_dir() { if m.is_dir() { if (options.recursive || entry_name == ".") && (options.level == 0 || level <= options.level) { match fs::read_dir(entry) { Ok(res) => { if options.verbose { println!("\x1b[36;1m-> Entering {}\x1b[0m", entry_name); } for tmp in res { match tmp { Ok(current) => { start_clean(options, &current.path(), level + 1); }, Err(e) => println!("Error: {:?}", e) }; } if options.verbose
} Err(e) => { println!("\x1b[31;1mProblem with directory '{}': {}\x1b[0m", entry_name, e); } } } } else { match entry.file_name() { Some(s) => { match s.to_str() { Some(ss) => if ss.ends_with("~") { if !options.confirmation || ask_confirmation(&Path::new(s)) { match fs::remove_file(entry) { Ok(_) => { if options.verbose { println!("\x1b[32;1m{} deleted\x1b[0m", entry_name); } } Err(e) => { println!("\x1b[31;1mProblem with this file: {} -> {}\x1b[0m", entry_name, e); } } } }, _ => {} } } None => { println!("\x1b[31;1mProblem with this file: {}\x1b[0m", entry_name); } } } } else { println!("\x1b[31;1mProblem with this entry: {}\x1b[0m", entry_name); } } fn print_help() { println!("./clean [options] [files | dirs]"); println!(" -r : recursive mode"); println!(" -v : verbose mode"); println!(" -i : prompt before every removal"); println!(" -l=[number] : Add a level for recursive mode"); println!("--help : print this help"); } fn main() { let mut args = Vec::new(); for argument in std::env::args() { args.push(argument); } let mut options = CleanOptions{recursive: false, verbose: false, confirmation: false, level: 0}; let mut files = Vec::new(); args.remove(0); for tmp in args.iter() { if tmp.clone().into_bytes()[0] == '-' as u8 { let mut tmp_arg = tmp.to_owned(); tmp_arg.remove(0); if tmp_arg.len() > 0 { for character in tmp_arg.into_bytes().iter() { match *character as char { '-' => { if &*tmp == "--help" { print_help(); return; } } 'r' => { options.recursive = true; } 'v' => { options.verbose = true; } 'i' => { options.confirmation = true; } 'l' => { if tmp.len() < 4 || &tmp[0..3] != "-l=" { println!("The \"-l\" option has to be used like this:"); println!("clean -r -l=2"); return; } options.level = match u32::from_str(&tmp[3..]) { Ok(u) => u, Err(_) => { println!("Please enter a valid number!"); return; } }; println!("Level is set to {}", options.level); break; } _ => { println!("Unknown option: '{}', to have the options list, please launch with '-h' option", *character as char); return; } } } }/* else { files.push(Path::new(tmp)); }*/ } else { files.push(Path::new(tmp)); } } if files.len() == 0 { files.push(Path::new(".")); } if options.verbose { println!("\x1b[33;1m=== VERBOSE MODE ===\x1b[0m"); } for tmp in files.iter() { start_clean(&options, tmp, 0); } if options.verbose { println!("\x1b[33;1mEnd of execution\x1b[0m"); } }
{ println!("\x1b[34;1m<- Leaving {}\x1b[0m", entry_name); }
conditional_block
main.rs
// Copyright 2016 Gomez Guillaume // // 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. use std::fs; use std::path::Path; use std::str::FromStr; struct CleanOptions { recursive: bool, verbose: bool, confirmation: bool, level: u32 } fn ask_confirmation(file: &Path) -> bool { if let Some(filename) = file.to_str() { loop { print!("clean: remove \x1b[37;1m'{}'\x1b[0m (y/n) ? ", filename); let mut s = String::new(); match std::io::stdin().read_line(&mut s) { Ok(_) => { let tmp_s = s.replace("\r\n", "").replace("\n", ""); if tmp_s == "y" || tmp_s == "yes" { return true; } else if tmp_s == "n" || tmp_s == "no" { return false; } } Err(_) => {} } } } else { println!("Unknown error on '{:?}'...", file); false } } fn start_clean(options: &CleanOptions, entry: &Path, level: u32) { let m = match ::std::fs::metadata(&entry) { Ok(e) => e, Err(e) => { println!("An error occured on '{:?}': {}", entry, e); return } }; let entry_name = match entry.to_str() { Some(n) => n, None => { println!("Invalid entry '{:?}'", entry); return } }; if m.is_file() || m.is_dir() { if m.is_dir() { if (options.recursive || entry_name == ".") && (options.level == 0 || level <= options.level) { match fs::read_dir(entry) { Ok(res) => { if options.verbose { println!("\x1b[36;1m-> Entering {}\x1b[0m", entry_name); } for tmp in res { match tmp { Ok(current) => { start_clean(options, &current.path(), level + 1); }, Err(e) => println!("Error: {:?}", e) }; } if options.verbose { println!("\x1b[34;1m<- Leaving {}\x1b[0m", entry_name); } } Err(e) => { println!("\x1b[31;1mProblem with directory '{}': {}\x1b[0m", entry_name, e); } } } } else { match entry.file_name() { Some(s) => { match s.to_str() { Some(ss) => if ss.ends_with("~") { if !options.confirmation || ask_confirmation(&Path::new(s)) { match fs::remove_file(entry) { Ok(_) => { if options.verbose { println!("\x1b[32;1m{} deleted\x1b[0m", entry_name); } } Err(e) => { println!("\x1b[31;1mProblem with this file: {} -> {}\x1b[0m", entry_name, e); } } } }, _ => {} } } None => { println!("\x1b[31;1mProblem with this file: {}\x1b[0m", entry_name); } } } } else { println!("\x1b[31;1mProblem with this entry: {}\x1b[0m", entry_name); } } fn print_help() { println!("./clean [options] [files | dirs]"); println!(" -r : recursive mode"); println!(" -v : verbose mode"); println!(" -i : prompt before every removal"); println!(" -l=[number] : Add a level for recursive mode"); println!("--help : print this help"); } fn main() { let mut args = Vec::new(); for argument in std::env::args() { args.push(argument); } let mut options = CleanOptions{recursive: false, verbose: false, confirmation: false, level: 0}; let mut files = Vec::new(); args.remove(0); for tmp in args.iter() { if tmp.clone().into_bytes()[0] == '-' as u8 { let mut tmp_arg = tmp.to_owned(); tmp_arg.remove(0); if tmp_arg.len() > 0 { for character in tmp_arg.into_bytes().iter() { match *character as char { '-' => { if &*tmp == "--help" { print_help(); return; } } 'r' => { options.recursive = true; } 'v' => { options.verbose = true; } 'i' => { options.confirmation = true; } 'l' => { if tmp.len() < 4 || &tmp[0..3] != "-l=" { println!("The \"-l\" option has to be used like this:"); println!("clean -r -l=2"); return; } options.level = match u32::from_str(&tmp[3..]) { Ok(u) => u, Err(_) => { println!("Please enter a valid number!"); return; } }; println!("Level is set to {}", options.level); break; } _ => { println!("Unknown option: '{}', to have the options list, please launch with '-h' option", *character as char); return; } } } }/* else { files.push(Path::new(tmp)); }*/ } else { files.push(Path::new(tmp));
if files.len() == 0 { files.push(Path::new(".")); } if options.verbose { println!("\x1b[33;1m=== VERBOSE MODE ===\x1b[0m"); } for tmp in files.iter() { start_clean(&options, tmp, 0); } if options.verbose { println!("\x1b[33;1mEnd of execution\x1b[0m"); } }
} }
random_line_split
main.rs
// Copyright 2016 Gomez Guillaume // // 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. use std::fs; use std::path::Path; use std::str::FromStr; struct CleanOptions { recursive: bool, verbose: bool, confirmation: bool, level: u32 } fn ask_confirmation(file: &Path) -> bool { if let Some(filename) = file.to_str() { loop { print!("clean: remove \x1b[37;1m'{}'\x1b[0m (y/n) ? ", filename); let mut s = String::new(); match std::io::stdin().read_line(&mut s) { Ok(_) => { let tmp_s = s.replace("\r\n", "").replace("\n", ""); if tmp_s == "y" || tmp_s == "yes" { return true; } else if tmp_s == "n" || tmp_s == "no" { return false; } } Err(_) => {} } } } else { println!("Unknown error on '{:?}'...", file); false } } fn start_clean(options: &CleanOptions, entry: &Path, level: u32)
fn print_help() { println!("./clean [options] [files | dirs]"); println!(" -r : recursive mode"); println!(" -v : verbose mode"); println!(" -i : prompt before every removal"); println!(" -l=[number] : Add a level for recursive mode"); println!("--help : print this help"); } fn main() { let mut args = Vec::new(); for argument in std::env::args() { args.push(argument); } let mut options = CleanOptions{recursive: false, verbose: false, confirmation: false, level: 0}; let mut files = Vec::new(); args.remove(0); for tmp in args.iter() { if tmp.clone().into_bytes()[0] == '-' as u8 { let mut tmp_arg = tmp.to_owned(); tmp_arg.remove(0); if tmp_arg.len() > 0 { for character in tmp_arg.into_bytes().iter() { match *character as char { '-' => { if &*tmp == "--help" { print_help(); return; } } 'r' => { options.recursive = true; } 'v' => { options.verbose = true; } 'i' => { options.confirmation = true; } 'l' => { if tmp.len() < 4 || &tmp[0..3] != "-l=" { println!("The \"-l\" option has to be used like this:"); println!("clean -r -l=2"); return; } options.level = match u32::from_str(&tmp[3..]) { Ok(u) => u, Err(_) => { println!("Please enter a valid number!"); return; } }; println!("Level is set to {}", options.level); break; } _ => { println!("Unknown option: '{}', to have the options list, please launch with '-h' option", *character as char); return; } } } }/* else { files.push(Path::new(tmp)); }*/ } else { files.push(Path::new(tmp)); } } if files.len() == 0 { files.push(Path::new(".")); } if options.verbose { println!("\x1b[33;1m=== VERBOSE MODE ===\x1b[0m"); } for tmp in files.iter() { start_clean(&options, tmp, 0); } if options.verbose { println!("\x1b[33;1mEnd of execution\x1b[0m"); } }
{ let m = match ::std::fs::metadata(&entry) { Ok(e) => e, Err(e) => { println!("An error occured on '{:?}': {}", entry, e); return } }; let entry_name = match entry.to_str() { Some(n) => n, None => { println!("Invalid entry '{:?}'", entry); return } }; if m.is_file() || m.is_dir() { if m.is_dir() { if (options.recursive || entry_name == ".") && (options.level == 0 || level <= options.level) { match fs::read_dir(entry) { Ok(res) => { if options.verbose { println!("\x1b[36;1m-> Entering {}\x1b[0m", entry_name); } for tmp in res { match tmp { Ok(current) => { start_clean(options, &current.path(), level + 1); }, Err(e) => println!("Error: {:?}", e) }; } if options.verbose { println!("\x1b[34;1m<- Leaving {}\x1b[0m", entry_name); } } Err(e) => { println!("\x1b[31;1mProblem with directory '{}': {}\x1b[0m", entry_name, e); } } } } else { match entry.file_name() { Some(s) => { match s.to_str() { Some(ss) => if ss.ends_with("~") { if !options.confirmation || ask_confirmation(&Path::new(s)) { match fs::remove_file(entry) { Ok(_) => { if options.verbose { println!("\x1b[32;1m{} deleted\x1b[0m", entry_name); } } Err(e) => { println!("\x1b[31;1mProblem with this file: {} -> {}\x1b[0m", entry_name, e); } } } }, _ => {} } } None => { println!("\x1b[31;1mProblem with this file: {}\x1b[0m", entry_name); } } } } else { println!("\x1b[31;1mProblem with this entry: {}\x1b[0m", entry_name); } }
identifier_body
main.rs
// Copyright 2016 Gomez Guillaume // // 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. use std::fs; use std::path::Path; use std::str::FromStr; struct CleanOptions { recursive: bool, verbose: bool, confirmation: bool, level: u32 } fn ask_confirmation(file: &Path) -> bool { if let Some(filename) = file.to_str() { loop { print!("clean: remove \x1b[37;1m'{}'\x1b[0m (y/n) ? ", filename); let mut s = String::new(); match std::io::stdin().read_line(&mut s) { Ok(_) => { let tmp_s = s.replace("\r\n", "").replace("\n", ""); if tmp_s == "y" || tmp_s == "yes" { return true; } else if tmp_s == "n" || tmp_s == "no" { return false; } } Err(_) => {} } } } else { println!("Unknown error on '{:?}'...", file); false } } fn start_clean(options: &CleanOptions, entry: &Path, level: u32) { let m = match ::std::fs::metadata(&entry) { Ok(e) => e, Err(e) => { println!("An error occured on '{:?}': {}", entry, e); return } }; let entry_name = match entry.to_str() { Some(n) => n, None => { println!("Invalid entry '{:?}'", entry); return } }; if m.is_file() || m.is_dir() { if m.is_dir() { if (options.recursive || entry_name == ".") && (options.level == 0 || level <= options.level) { match fs::read_dir(entry) { Ok(res) => { if options.verbose { println!("\x1b[36;1m-> Entering {}\x1b[0m", entry_name); } for tmp in res { match tmp { Ok(current) => { start_clean(options, &current.path(), level + 1); }, Err(e) => println!("Error: {:?}", e) }; } if options.verbose { println!("\x1b[34;1m<- Leaving {}\x1b[0m", entry_name); } } Err(e) => { println!("\x1b[31;1mProblem with directory '{}': {}\x1b[0m", entry_name, e); } } } } else { match entry.file_name() { Some(s) => { match s.to_str() { Some(ss) => if ss.ends_with("~") { if !options.confirmation || ask_confirmation(&Path::new(s)) { match fs::remove_file(entry) { Ok(_) => { if options.verbose { println!("\x1b[32;1m{} deleted\x1b[0m", entry_name); } } Err(e) => { println!("\x1b[31;1mProblem with this file: {} -> {}\x1b[0m", entry_name, e); } } } }, _ => {} } } None => { println!("\x1b[31;1mProblem with this file: {}\x1b[0m", entry_name); } } } } else { println!("\x1b[31;1mProblem with this entry: {}\x1b[0m", entry_name); } } fn print_help() { println!("./clean [options] [files | dirs]"); println!(" -r : recursive mode"); println!(" -v : verbose mode"); println!(" -i : prompt before every removal"); println!(" -l=[number] : Add a level for recursive mode"); println!("--help : print this help"); } fn
() { let mut args = Vec::new(); for argument in std::env::args() { args.push(argument); } let mut options = CleanOptions{recursive: false, verbose: false, confirmation: false, level: 0}; let mut files = Vec::new(); args.remove(0); for tmp in args.iter() { if tmp.clone().into_bytes()[0] == '-' as u8 { let mut tmp_arg = tmp.to_owned(); tmp_arg.remove(0); if tmp_arg.len() > 0 { for character in tmp_arg.into_bytes().iter() { match *character as char { '-' => { if &*tmp == "--help" { print_help(); return; } } 'r' => { options.recursive = true; } 'v' => { options.verbose = true; } 'i' => { options.confirmation = true; } 'l' => { if tmp.len() < 4 || &tmp[0..3] != "-l=" { println!("The \"-l\" option has to be used like this:"); println!("clean -r -l=2"); return; } options.level = match u32::from_str(&tmp[3..]) { Ok(u) => u, Err(_) => { println!("Please enter a valid number!"); return; } }; println!("Level is set to {}", options.level); break; } _ => { println!("Unknown option: '{}', to have the options list, please launch with '-h' option", *character as char); return; } } } }/* else { files.push(Path::new(tmp)); }*/ } else { files.push(Path::new(tmp)); } } if files.len() == 0 { files.push(Path::new(".")); } if options.verbose { println!("\x1b[33;1m=== VERBOSE MODE ===\x1b[0m"); } for tmp in files.iter() { start_clean(&options, tmp, 0); } if options.verbose { println!("\x1b[33;1mEnd of execution\x1b[0m"); } }
main
identifier_name
index.js
/** * @module express-universal-query-validator/util * @description Utility functions needed for this module */ import url from 'url'; import { attempt, some, reject, isError } from 'lodash'; /** * Checks if a key=value param can not be * parsed by global `decodeURIComponent` * @param {string} query * @returns {boolean} - did parsing throw? */ export function isUnparseableQuery(query = 'key=value')
/** * Are all queries parseable? * @param {Array} queries * @returns {boolean} */ export function validateQueryParams(queries = []) { return !some(queries, isUnparseableQuery); } /** * Returns input minus unparseable queries * @param {Array} queries * @returns {Array} */ export function dropInvalidQueryParams(queries = []) { return reject(queries, isUnparseableQuery); }
{ return isError(attempt(decodeURIComponent, query)); }
identifier_body
index.js
/** * @module express-universal-query-validator/util * @description Utility functions needed for this module */ import url from 'url'; import { attempt, some, reject, isError } from 'lodash'; /** * Checks if a key=value param can not be * parsed by global `decodeURIComponent` * @param {string} query * @returns {boolean} - did parsing throw? */ export function
(query = 'key=value') { return isError(attempt(decodeURIComponent, query)); } /** * Are all queries parseable? * @param {Array} queries * @returns {boolean} */ export function validateQueryParams(queries = []) { return !some(queries, isUnparseableQuery); } /** * Returns input minus unparseable queries * @param {Array} queries * @returns {Array} */ export function dropInvalidQueryParams(queries = []) { return reject(queries, isUnparseableQuery); }
isUnparseableQuery
identifier_name
index.js
/** * @module express-universal-query-validator/util * @description Utility functions needed for this module */ import url from 'url'; import { attempt, some, reject, isError } from 'lodash'; /** * Checks if a key=value param can not be * parsed by global `decodeURIComponent` * @param {string} query * @returns {boolean} - did parsing throw? */ export function isUnparseableQuery(query = 'key=value') { return isError(attempt(decodeURIComponent, query)); } /** * Are all queries parseable? * @param {Array} queries * @returns {boolean} */ export function validateQueryParams(queries = []) { return !some(queries, isUnparseableQuery); } /** * Returns input minus unparseable queries
*/ export function dropInvalidQueryParams(queries = []) { return reject(queries, isUnparseableQuery); }
* @param {Array} queries * @returns {Array}
random_line_split
promote.py
import re import subprocess import sys def get_promotion_chain(git_directory, git_branch, upstream_name='origin'): """ For a given git repository & branch, determine the promotion chain Following the promotion path defined for pulp figure out what the full promotion path to master is from wherever we are. For example if given 2.5-release for pulp the promotion path would be 2.5-release -> 2.5-testing -> 2.5-dev -> 2.6-dev -> master :param git_directory: The directory containing the git repo :type git_directory: str :param git_branch: The git branch to start with :type git_branch: str :param upstream_name: The name of the upstream repo, defaults to 'origin', will be overridden by the upstream name if specified in the branch :param upstream_name: str :return: list of branches that the specified branch promotes to :rtype: list of str """ if git_branch.find('/') != -1: upstream_name = git_branch[:git_branch.find('/')] git_branch = git_branch[git_branch.find('/')+1:] git_branch = git_branch.strip() # parse the branch into its component parts if git_branch == 'master':
# parse the git_branch: x.y-(dev|testing|release) branch_regex = "(\d+.\d+)-(dev|testing|release)" match = re.search(branch_regex, git_branch) source_branch_version = match.group(1) source_branch_stream = match.group(2) # get the branch list raw_branch_list = subprocess.check_output(['git', 'branch', '-r'], cwd=git_directory) lines = raw_branch_list.splitlines() target_branch_versions = set() all_branches = set() for line in lines: line = line.strip() # print line match = re.search(branch_regex, line) if match: all_branches.add(match.group(0)) branch_version = match.group(1) if branch_version > source_branch_version: target_branch_versions.add(branch_version) result_list = [git_branch] if source_branch_stream == 'release': result_list.append("%s-testing" % source_branch_version) result_list.append("%s-dev" % source_branch_version) if source_branch_stream == 'testing': result_list.append("%s-dev" % source_branch_version) result_list.extend(["%s-dev" % branch_version for branch_version in sorted(target_branch_versions)]) # Do this check before adding master since we explicitly won't match master in the above regex if not set(result_list).issubset(all_branches): missing_branches = set(result_list).difference(all_branches) print "Error creating git branch promotion list. The following branches are missing: " print missing_branches sys.exit(1) result_list.append('master') result_list = ["%s/%s" % (upstream_name, item) for item in result_list] return result_list def generate_promotion_pairs(promotion_chain): """ For all the items in a promotion path, yield the list of individual promotions that will need to be applied :param promotion_chain: list of branches that will need to be promoted :type promotion_chain: list of str """ for i in range(0, len(promotion_chain), 1): if i < (len(promotion_chain) - 1): yield promotion_chain[i:i + 2] def check_merge_forward(git_directory, promotion_chain): """ For a given git repo & promotion path, validate that all branches have been merged forward :param git_directory: The directory containing the git repo :type git_directory: str :param promotion_chain: git branch promotion path :type promotion_chain: list of str """ for pair in generate_promotion_pairs(promotion_chain): print "checking log comparision of %s -> %s" % (pair[0], pair[1]) output = subprocess.check_output(['git', 'log', "^%s" % pair[1], pair[0]], cwd=git_directory) if output: print "ERROR: in %s: branch %s has not been merged into %s" % \ (git_directory, pair[0], pair[1]) print "Run 'git log ^%s %s' to view the differences." % (pair[1], pair[0]) sys.exit(1) def get_current_git_upstream_branch(git_directory): """ For a given git directory, get the current remote branch :param git_directory: The directory containing the git repo :type git_directory: str :return: remote branch :rtype: str """ command = 'git rev-parse --abbrev-ref --symbolic-full-name @{u}' command = command.split(' ') return subprocess.check_output(command, cwd=git_directory).strip() def get_current_git_branch(git_directory): """ For a given git directory, get the current branch :param git_directory: The directory containing the git repo :type git_directory: str :return: remote branch :rtype: str """ command = 'git rev-parse --abbrev-ref HEAD' command = command.split(' ') return subprocess.check_output(command, cwd=git_directory).strip() def get_local_git_branches(git_directory): command = "git for-each-ref --format %(refname:short) refs/heads/" command = command.split(' ') lines = subprocess.check_output(command, cwd=git_directory) results = [item.strip() for item in lines.splitlines()] return set(results) def checkout_branch(git_directory, branch_name, remote_name='origin'): """ Ensure that branch_name is checkout from the given upstream :param git_directory: directory containing the git project :type git_directory: str :param branch_name: The local branch name. if the remote is specified in the branch name eg upstream/2.6-dev then the remote specified in the branch_name will take precidence over the remote_name specified as a parameter :type branch_name: str :param remote_name: The name of the remote git repo to use, is ignored if the remote is specified as part of the branch name :type remote_name: str """ if branch_name.find('/') != -1: local_branch = branch_name[branch_name.find('/')+1:] remote_name = branch_name[:branch_name.find('/')] else: local_branch = branch_name local_branch = local_branch.strip() full_name = '%s/%s' % (remote_name, local_branch) if not local_branch in get_local_git_branches(git_directory): subprocess.check_call(['git', 'checkout', '-b', local_branch, full_name], cwd=git_directory) subprocess.check_call(['git', 'checkout', local_branch], cwd=git_directory) # validate that the upstream branch is what we expect it to be upstream_branch = get_current_git_upstream_branch(git_directory) if upstream_branch != full_name: print "Error checking out %s in %s" % (full_name, git_directory) print "The upstream branch was already set to %s" % upstream_branch sys.exit(1) subprocess.check_call(['git', 'pull'], cwd=git_directory) def merge_forward(git_directory, push=False): """ From whatever the current checkout is, merge it forward :param git_directory: directory containing the git project :type git_directory: str :param push: Whether or not we should push the results to github :type push: bool """ starting_branch = get_current_git_branch(git_directory) branch = get_current_git_upstream_branch(git_directory) chain = get_promotion_chain(git_directory, branch) for source_branch, target_branch in generate_promotion_pairs(chain): checkout_branch(git_directory, source_branch) checkout_branch(git_directory, target_branch) local_source_branch = source_branch[source_branch.find('/')+1:] print "Merging %s into %s" % (local_source_branch, target_branch) subprocess.check_call(['git', 'merge', '-s', 'ours', local_source_branch, '--no-edit'], cwd=git_directory) if push: subprocess.call(['git', 'push'], cwd=git_directory) # Set the branch back tot he one we started on checkout_branch(git_directory, starting_branch)
return ['master']
conditional_block
promote.py
import re import subprocess import sys def get_promotion_chain(git_directory, git_branch, upstream_name='origin'): """ For a given git repository & branch, determine the promotion chain Following the promotion path defined for pulp figure out what the full promotion path to master is from wherever we are. For example if given 2.5-release for pulp the promotion path would be 2.5-release -> 2.5-testing -> 2.5-dev -> 2.6-dev -> master :param git_directory: The directory containing the git repo :type git_directory: str :param git_branch: The git branch to start with :type git_branch: str :param upstream_name: The name of the upstream repo, defaults to 'origin', will be overridden by the upstream name if specified in the branch :param upstream_name: str :return: list of branches that the specified branch promotes to :rtype: list of str """ if git_branch.find('/') != -1: upstream_name = git_branch[:git_branch.find('/')] git_branch = git_branch[git_branch.find('/')+1:] git_branch = git_branch.strip() # parse the branch into its component parts if git_branch == 'master': return ['master'] # parse the git_branch: x.y-(dev|testing|release) branch_regex = "(\d+.\d+)-(dev|testing|release)" match = re.search(branch_regex, git_branch) source_branch_version = match.group(1) source_branch_stream = match.group(2) # get the branch list raw_branch_list = subprocess.check_output(['git', 'branch', '-r'], cwd=git_directory) lines = raw_branch_list.splitlines() target_branch_versions = set() all_branches = set() for line in lines: line = line.strip() # print line match = re.search(branch_regex, line) if match: all_branches.add(match.group(0)) branch_version = match.group(1) if branch_version > source_branch_version: target_branch_versions.add(branch_version) result_list = [git_branch] if source_branch_stream == 'release': result_list.append("%s-testing" % source_branch_version) result_list.append("%s-dev" % source_branch_version) if source_branch_stream == 'testing': result_list.append("%s-dev" % source_branch_version) result_list.extend(["%s-dev" % branch_version for branch_version in sorted(target_branch_versions)]) # Do this check before adding master since we explicitly won't match master in the above regex if not set(result_list).issubset(all_branches): missing_branches = set(result_list).difference(all_branches) print "Error creating git branch promotion list. The following branches are missing: " print missing_branches sys.exit(1) result_list.append('master') result_list = ["%s/%s" % (upstream_name, item) for item in result_list] return result_list def generate_promotion_pairs(promotion_chain): """ For all the items in a promotion path, yield the list of individual promotions that will need to be applied :param promotion_chain: list of branches that will need to be promoted :type promotion_chain: list of str """ for i in range(0, len(promotion_chain), 1): if i < (len(promotion_chain) - 1): yield promotion_chain[i:i + 2] def check_merge_forward(git_directory, promotion_chain): """ For a given git repo & promotion path, validate that all branches have been merged forward :param git_directory: The directory containing the git repo :type git_directory: str :param promotion_chain: git branch promotion path :type promotion_chain: list of str """ for pair in generate_promotion_pairs(promotion_chain): print "checking log comparision of %s -> %s" % (pair[0], pair[1]) output = subprocess.check_output(['git', 'log', "^%s" % pair[1], pair[0]], cwd=git_directory) if output: print "ERROR: in %s: branch %s has not been merged into %s" % \ (git_directory, pair[0], pair[1]) print "Run 'git log ^%s %s' to view the differences." % (pair[1], pair[0]) sys.exit(1) def get_current_git_upstream_branch(git_directory): """ For a given git directory, get the current remote branch :param git_directory: The directory containing the git repo :type git_directory: str :return: remote branch :rtype: str """ command = 'git rev-parse --abbrev-ref --symbolic-full-name @{u}' command = command.split(' ') return subprocess.check_output(command, cwd=git_directory).strip() def get_current_git_branch(git_directory): """ For a given git directory, get the current branch :param git_directory: The directory containing the git repo :type git_directory: str :return: remote branch :rtype: str """ command = 'git rev-parse --abbrev-ref HEAD' command = command.split(' ') return subprocess.check_output(command, cwd=git_directory).strip() def get_local_git_branches(git_directory): command = "git for-each-ref --format %(refname:short) refs/heads/" command = command.split(' ') lines = subprocess.check_output(command, cwd=git_directory) results = [item.strip() for item in lines.splitlines()] return set(results) def checkout_branch(git_directory, branch_name, remote_name='origin'):
def merge_forward(git_directory, push=False): """ From whatever the current checkout is, merge it forward :param git_directory: directory containing the git project :type git_directory: str :param push: Whether or not we should push the results to github :type push: bool """ starting_branch = get_current_git_branch(git_directory) branch = get_current_git_upstream_branch(git_directory) chain = get_promotion_chain(git_directory, branch) for source_branch, target_branch in generate_promotion_pairs(chain): checkout_branch(git_directory, source_branch) checkout_branch(git_directory, target_branch) local_source_branch = source_branch[source_branch.find('/')+1:] print "Merging %s into %s" % (local_source_branch, target_branch) subprocess.check_call(['git', 'merge', '-s', 'ours', local_source_branch, '--no-edit'], cwd=git_directory) if push: subprocess.call(['git', 'push'], cwd=git_directory) # Set the branch back tot he one we started on checkout_branch(git_directory, starting_branch)
""" Ensure that branch_name is checkout from the given upstream :param git_directory: directory containing the git project :type git_directory: str :param branch_name: The local branch name. if the remote is specified in the branch name eg upstream/2.6-dev then the remote specified in the branch_name will take precidence over the remote_name specified as a parameter :type branch_name: str :param remote_name: The name of the remote git repo to use, is ignored if the remote is specified as part of the branch name :type remote_name: str """ if branch_name.find('/') != -1: local_branch = branch_name[branch_name.find('/')+1:] remote_name = branch_name[:branch_name.find('/')] else: local_branch = branch_name local_branch = local_branch.strip() full_name = '%s/%s' % (remote_name, local_branch) if not local_branch in get_local_git_branches(git_directory): subprocess.check_call(['git', 'checkout', '-b', local_branch, full_name], cwd=git_directory) subprocess.check_call(['git', 'checkout', local_branch], cwd=git_directory) # validate that the upstream branch is what we expect it to be upstream_branch = get_current_git_upstream_branch(git_directory) if upstream_branch != full_name: print "Error checking out %s in %s" % (full_name, git_directory) print "The upstream branch was already set to %s" % upstream_branch sys.exit(1) subprocess.check_call(['git', 'pull'], cwd=git_directory)
identifier_body
promote.py
import re import subprocess import sys def get_promotion_chain(git_directory, git_branch, upstream_name='origin'): """ For a given git repository & branch, determine the promotion chain Following the promotion path defined for pulp figure out what the full promotion path to master is from wherever we are. For example if given 2.5-release for pulp the promotion path would be 2.5-release -> 2.5-testing -> 2.5-dev -> 2.6-dev -> master :param git_directory: The directory containing the git repo :type git_directory: str :param git_branch: The git branch to start with :type git_branch: str :param upstream_name: The name of the upstream repo, defaults to 'origin', will be overridden by the upstream name if specified in the branch :param upstream_name: str :return: list of branches that the specified branch promotes to :rtype: list of str """ if git_branch.find('/') != -1: upstream_name = git_branch[:git_branch.find('/')] git_branch = git_branch[git_branch.find('/')+1:] git_branch = git_branch.strip() # parse the branch into its component parts if git_branch == 'master': return ['master'] # parse the git_branch: x.y-(dev|testing|release) branch_regex = "(\d+.\d+)-(dev|testing|release)" match = re.search(branch_regex, git_branch) source_branch_version = match.group(1) source_branch_stream = match.group(2) # get the branch list raw_branch_list = subprocess.check_output(['git', 'branch', '-r'], cwd=git_directory) lines = raw_branch_list.splitlines() target_branch_versions = set() all_branches = set() for line in lines: line = line.strip() # print line match = re.search(branch_regex, line) if match: all_branches.add(match.group(0)) branch_version = match.group(1) if branch_version > source_branch_version: target_branch_versions.add(branch_version) result_list = [git_branch] if source_branch_stream == 'release': result_list.append("%s-testing" % source_branch_version) result_list.append("%s-dev" % source_branch_version) if source_branch_stream == 'testing': result_list.append("%s-dev" % source_branch_version) result_list.extend(["%s-dev" % branch_version for branch_version in sorted(target_branch_versions)]) # Do this check before adding master since we explicitly won't match master in the above regex if not set(result_list).issubset(all_branches): missing_branches = set(result_list).difference(all_branches) print "Error creating git branch promotion list. The following branches are missing: " print missing_branches sys.exit(1) result_list.append('master') result_list = ["%s/%s" % (upstream_name, item) for item in result_list] return result_list def generate_promotion_pairs(promotion_chain): """ For all the items in a promotion path, yield the list of individual promotions that will need to be applied :param promotion_chain: list of branches that will need to be promoted :type promotion_chain: list of str """ for i in range(0, len(promotion_chain), 1): if i < (len(promotion_chain) - 1): yield promotion_chain[i:i + 2] def check_merge_forward(git_directory, promotion_chain): """ For a given git repo & promotion path, validate that all branches have been merged forward :param git_directory: The directory containing the git repo :type git_directory: str :param promotion_chain: git branch promotion path :type promotion_chain: list of str """ for pair in generate_promotion_pairs(promotion_chain): print "checking log comparision of %s -> %s" % (pair[0], pair[1]) output = subprocess.check_output(['git', 'log', "^%s" % pair[1], pair[0]], cwd=git_directory) if output: print "ERROR: in %s: branch %s has not been merged into %s" % \ (git_directory, pair[0], pair[1]) print "Run 'git log ^%s %s' to view the differences." % (pair[1], pair[0]) sys.exit(1) def get_current_git_upstream_branch(git_directory): """ For a given git directory, get the current remote branch :param git_directory: The directory containing the git repo :type git_directory: str :return: remote branch :rtype: str """ command = 'git rev-parse --abbrev-ref --symbolic-full-name @{u}' command = command.split(' ') return subprocess.check_output(command, cwd=git_directory).strip() def get_current_git_branch(git_directory): """ For a given git directory, get the current branch :param git_directory: The directory containing the git repo :type git_directory: str :return: remote branch :rtype: str """ command = 'git rev-parse --abbrev-ref HEAD' command = command.split(' ') return subprocess.check_output(command, cwd=git_directory).strip() def get_local_git_branches(git_directory): command = "git for-each-ref --format %(refname:short) refs/heads/" command = command.split(' ') lines = subprocess.check_output(command, cwd=git_directory) results = [item.strip() for item in lines.splitlines()] return set(results) def checkout_branch(git_directory, branch_name, remote_name='origin'): """ Ensure that branch_name is checkout from the given upstream :param git_directory: directory containing the git project :type git_directory: str :param branch_name: The local branch name. if the remote is specified in the branch name eg upstream/2.6-dev then the remote specified in the branch_name will take precidence over the remote_name specified as a parameter :type branch_name: str :param remote_name: The name of the remote git repo to use, is ignored if the remote is specified as part of the branch name :type remote_name: str """ if branch_name.find('/') != -1: local_branch = branch_name[branch_name.find('/')+1:] remote_name = branch_name[:branch_name.find('/')] else: local_branch = branch_name local_branch = local_branch.strip() full_name = '%s/%s' % (remote_name, local_branch) if not local_branch in get_local_git_branches(git_directory): subprocess.check_call(['git', 'checkout', '-b', local_branch, full_name], cwd=git_directory) subprocess.check_call(['git', 'checkout', local_branch], cwd=git_directory) # validate that the upstream branch is what we expect it to be upstream_branch = get_current_git_upstream_branch(git_directory) if upstream_branch != full_name: print "Error checking out %s in %s" % (full_name, git_directory) print "The upstream branch was already set to %s" % upstream_branch sys.exit(1) subprocess.check_call(['git', 'pull'], cwd=git_directory) def
(git_directory, push=False): """ From whatever the current checkout is, merge it forward :param git_directory: directory containing the git project :type git_directory: str :param push: Whether or not we should push the results to github :type push: bool """ starting_branch = get_current_git_branch(git_directory) branch = get_current_git_upstream_branch(git_directory) chain = get_promotion_chain(git_directory, branch) for source_branch, target_branch in generate_promotion_pairs(chain): checkout_branch(git_directory, source_branch) checkout_branch(git_directory, target_branch) local_source_branch = source_branch[source_branch.find('/')+1:] print "Merging %s into %s" % (local_source_branch, target_branch) subprocess.check_call(['git', 'merge', '-s', 'ours', local_source_branch, '--no-edit'], cwd=git_directory) if push: subprocess.call(['git', 'push'], cwd=git_directory) # Set the branch back tot he one we started on checkout_branch(git_directory, starting_branch)
merge_forward
identifier_name
promote.py
import re import subprocess import sys def get_promotion_chain(git_directory, git_branch, upstream_name='origin'): """ For a given git repository & branch, determine the promotion chain Following the promotion path defined for pulp figure out what the full promotion path to master is from wherever we are. For example if given 2.5-release for pulp the promotion path would be 2.5-release -> 2.5-testing -> 2.5-dev -> 2.6-dev -> master :param git_directory: The directory containing the git repo :type git_directory: str :param git_branch: The git branch to start with :type git_branch: str :param upstream_name: The name of the upstream repo, defaults to 'origin', will be overridden by the upstream name if specified in the branch :param upstream_name: str :return: list of branches that the specified branch promotes to :rtype: list of str """ if git_branch.find('/') != -1: upstream_name = git_branch[:git_branch.find('/')] git_branch = git_branch[git_branch.find('/')+1:] git_branch = git_branch.strip() # parse the branch into its component parts if git_branch == 'master': return ['master'] # parse the git_branch: x.y-(dev|testing|release) branch_regex = "(\d+.\d+)-(dev|testing|release)" match = re.search(branch_regex, git_branch) source_branch_version = match.group(1) source_branch_stream = match.group(2) # get the branch list raw_branch_list = subprocess.check_output(['git', 'branch', '-r'], cwd=git_directory) lines = raw_branch_list.splitlines() target_branch_versions = set() all_branches = set() for line in lines: line = line.strip() # print line match = re.search(branch_regex, line) if match: all_branches.add(match.group(0)) branch_version = match.group(1) if branch_version > source_branch_version: target_branch_versions.add(branch_version) result_list = [git_branch] if source_branch_stream == 'release': result_list.append("%s-testing" % source_branch_version) result_list.append("%s-dev" % source_branch_version) if source_branch_stream == 'testing': result_list.append("%s-dev" % source_branch_version) result_list.extend(["%s-dev" % branch_version for branch_version in sorted(target_branch_versions)]) # Do this check before adding master since we explicitly won't match master in the above regex if not set(result_list).issubset(all_branches): missing_branches = set(result_list).difference(all_branches) print "Error creating git branch promotion list. The following branches are missing: " print missing_branches sys.exit(1) result_list.append('master') result_list = ["%s/%s" % (upstream_name, item) for item in result_list] return result_list def generate_promotion_pairs(promotion_chain): """ For all the items in a promotion path, yield the list of individual promotions that will need to be applied :param promotion_chain: list of branches that will need to be promoted :type promotion_chain: list of str """ for i in range(0, len(promotion_chain), 1): if i < (len(promotion_chain) - 1): yield promotion_chain[i:i + 2] def check_merge_forward(git_directory, promotion_chain): """ For a given git repo & promotion path, validate that all branches have been merged forward :param git_directory: The directory containing the git repo :type git_directory: str :param promotion_chain: git branch promotion path :type promotion_chain: list of str """ for pair in generate_promotion_pairs(promotion_chain): print "checking log comparision of %s -> %s" % (pair[0], pair[1]) output = subprocess.check_output(['git', 'log', "^%s" % pair[1], pair[0]], cwd=git_directory) if output: print "ERROR: in %s: branch %s has not been merged into %s" % \ (git_directory, pair[0], pair[1]) print "Run 'git log ^%s %s' to view the differences." % (pair[1], pair[0]) sys.exit(1)
""" For a given git directory, get the current remote branch :param git_directory: The directory containing the git repo :type git_directory: str :return: remote branch :rtype: str """ command = 'git rev-parse --abbrev-ref --symbolic-full-name @{u}' command = command.split(' ') return subprocess.check_output(command, cwd=git_directory).strip() def get_current_git_branch(git_directory): """ For a given git directory, get the current branch :param git_directory: The directory containing the git repo :type git_directory: str :return: remote branch :rtype: str """ command = 'git rev-parse --abbrev-ref HEAD' command = command.split(' ') return subprocess.check_output(command, cwd=git_directory).strip() def get_local_git_branches(git_directory): command = "git for-each-ref --format %(refname:short) refs/heads/" command = command.split(' ') lines = subprocess.check_output(command, cwd=git_directory) results = [item.strip() for item in lines.splitlines()] return set(results) def checkout_branch(git_directory, branch_name, remote_name='origin'): """ Ensure that branch_name is checkout from the given upstream :param git_directory: directory containing the git project :type git_directory: str :param branch_name: The local branch name. if the remote is specified in the branch name eg upstream/2.6-dev then the remote specified in the branch_name will take precidence over the remote_name specified as a parameter :type branch_name: str :param remote_name: The name of the remote git repo to use, is ignored if the remote is specified as part of the branch name :type remote_name: str """ if branch_name.find('/') != -1: local_branch = branch_name[branch_name.find('/')+1:] remote_name = branch_name[:branch_name.find('/')] else: local_branch = branch_name local_branch = local_branch.strip() full_name = '%s/%s' % (remote_name, local_branch) if not local_branch in get_local_git_branches(git_directory): subprocess.check_call(['git', 'checkout', '-b', local_branch, full_name], cwd=git_directory) subprocess.check_call(['git', 'checkout', local_branch], cwd=git_directory) # validate that the upstream branch is what we expect it to be upstream_branch = get_current_git_upstream_branch(git_directory) if upstream_branch != full_name: print "Error checking out %s in %s" % (full_name, git_directory) print "The upstream branch was already set to %s" % upstream_branch sys.exit(1) subprocess.check_call(['git', 'pull'], cwd=git_directory) def merge_forward(git_directory, push=False): """ From whatever the current checkout is, merge it forward :param git_directory: directory containing the git project :type git_directory: str :param push: Whether or not we should push the results to github :type push: bool """ starting_branch = get_current_git_branch(git_directory) branch = get_current_git_upstream_branch(git_directory) chain = get_promotion_chain(git_directory, branch) for source_branch, target_branch in generate_promotion_pairs(chain): checkout_branch(git_directory, source_branch) checkout_branch(git_directory, target_branch) local_source_branch = source_branch[source_branch.find('/')+1:] print "Merging %s into %s" % (local_source_branch, target_branch) subprocess.check_call(['git', 'merge', '-s', 'ours', local_source_branch, '--no-edit'], cwd=git_directory) if push: subprocess.call(['git', 'push'], cwd=git_directory) # Set the branch back tot he one we started on checkout_branch(git_directory, starting_branch)
def get_current_git_upstream_branch(git_directory):
random_line_split
team-item.controller.ts
/* * Copyright (c) [2015] - [2017] Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ 'use strict'; import {CodenvyTeam} from '../../../../components/api/codenvy-team.factory'; /** * Controller for a team item. * * @author Ann Shumilova */ export class TeamItemController { /** * Service for displaying dialogs. */ private confirmDialogService: any; /** * Location service. */ private $location: ng.ILocationService; /** * Team API interaction. */ private codenvyTeam: CodenvyTeam; /** * Service for displaying notifications. */ private cheNotification: any; /** * Team details (the value is set in directive attributes). */ private team: any; /** * Callback needed to react on teams updation (the value is set in directive attributes). */ private onUpdate: Function; /** * Default constructor that is using resource injection * @ngInject for Dependency injection */ constructor($location: ng.ILocationService, codenvyTeam: CodenvyTeam, confirmDialogService: any, cheNotification: any) { this.$location = $location; this.confirmDialogService = confirmDialogService; this.codenvyTeam = codenvyTeam; this.cheNotification = cheNotification; } /** * Redirect to team details. */
(tab: string) { this.$location.path('/team/' + this.team.qualifiedName).search(!tab ? {} : {tab: tab}); } /** * Removes team after confirmation. */ removeTeam(): void { this.confirmRemoval().then(() => { this.codenvyTeam.deleteTeam(this.team.id).then(() => { this.onUpdate(); }, (error: any) => { this.cheNotification.showError(error && error.data && error.data.message ? error.data.message : 'Failed to delete team ' + this.team.name); }); }); } /** * Get team display name. * * @param team * @returns {string} */ getTeamDisplayName(team): string { return this.codenvyTeam.getTeamDisplayName(team); } /** * Shows dialog to confirm the current team removal. * * @returns {angular.IPromise<any>} */ confirmRemoval(): ng.IPromise<any> { let promise = this.confirmDialogService.showConfirmDialog('Delete team', 'Would you like to delete team \'' + this.team.name + '\'?', 'Delete'); return promise; } }
redirectToTeamDetails
identifier_name
team-item.controller.ts
/* * Copyright (c) [2015] - [2017] Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ 'use strict'; import {CodenvyTeam} from '../../../../components/api/codenvy-team.factory'; /** * Controller for a team item. * * @author Ann Shumilova */ export class TeamItemController { /** * Service for displaying dialogs. */ private confirmDialogService: any; /** * Location service. */ private $location: ng.ILocationService; /** * Team API interaction. */ private codenvyTeam: CodenvyTeam; /** * Service for displaying notifications. */ private cheNotification: any; /** * Team details (the value is set in directive attributes). */ private team: any; /** * Callback needed to react on teams updation (the value is set in directive attributes). */ private onUpdate: Function; /** * Default constructor that is using resource injection * @ngInject for Dependency injection */ constructor($location: ng.ILocationService, codenvyTeam: CodenvyTeam, confirmDialogService: any, cheNotification: any) { this.$location = $location; this.confirmDialogService = confirmDialogService; this.codenvyTeam = codenvyTeam; this.cheNotification = cheNotification; } /** * Redirect to team details. */ redirectToTeamDetails(tab: string) {
* Removes team after confirmation. */ removeTeam(): void { this.confirmRemoval().then(() => { this.codenvyTeam.deleteTeam(this.team.id).then(() => { this.onUpdate(); }, (error: any) => { this.cheNotification.showError(error && error.data && error.data.message ? error.data.message : 'Failed to delete team ' + this.team.name); }); }); } /** * Get team display name. * * @param team * @returns {string} */ getTeamDisplayName(team): string { return this.codenvyTeam.getTeamDisplayName(team); } /** * Shows dialog to confirm the current team removal. * * @returns {angular.IPromise<any>} */ confirmRemoval(): ng.IPromise<any> { let promise = this.confirmDialogService.showConfirmDialog('Delete team', 'Would you like to delete team \'' + this.team.name + '\'?', 'Delete'); return promise; } }
this.$location.path('/team/' + this.team.qualifiedName).search(!tab ? {} : {tab: tab}); } /**
random_line_split
livestream.py
import logging import re from streamlink.plugin import Plugin, pluginmatcher from streamlink.plugin.api import validate from streamlink.stream import HLSStream from streamlink.utils.parse import parse_json log = logging.getLogger(__name__) @pluginmatcher(re.compile( r"https?://(?:www\.)?livestream\.com/" )) class Livestream(Plugin): _config_re = re.compile(r"window.config = ({.+})") _stream_config_schema = validate.Schema(validate.any({ "event": { "stream_info": validate.any({ "is_live": bool, "secure_m3u8_url": validate.url(scheme="https"), }, None), } }, {}), validate.get("event", {}), validate.get("stream_info", {})) def
(self): res = self.session.http.get(self.url) m = self._config_re.search(res.text) if not m: log.debug("Unable to find _config_re") return stream_info = parse_json(m.group(1), "config JSON", schema=self._stream_config_schema) log.trace("stream_info: {0!r}".format(stream_info)) if not (stream_info and stream_info["is_live"]): log.debug("Stream might be Off Air") return m3u8_url = stream_info.get("secure_m3u8_url") if m3u8_url: yield from HLSStream.parse_variant_playlist(self.session, m3u8_url).items() __plugin__ = Livestream
_get_streams
identifier_name
livestream.py
import logging import re from streamlink.plugin import Plugin, pluginmatcher from streamlink.plugin.api import validate from streamlink.stream import HLSStream from streamlink.utils.parse import parse_json log = logging.getLogger(__name__) @pluginmatcher(re.compile( r"https?://(?:www\.)?livestream\.com/" )) class Livestream(Plugin): _config_re = re.compile(r"window.config = ({.+})") _stream_config_schema = validate.Schema(validate.any({ "event": { "stream_info": validate.any({ "is_live": bool, "secure_m3u8_url": validate.url(scheme="https"), }, None), } }, {}), validate.get("event", {}), validate.get("stream_info", {})) def _get_streams(self): res = self.session.http.get(self.url) m = self._config_re.search(res.text) if not m: log.debug("Unable to find _config_re") return stream_info = parse_json(m.group(1), "config JSON", schema=self._stream_config_schema) log.trace("stream_info: {0!r}".format(stream_info)) if not (stream_info and stream_info["is_live"]):
m3u8_url = stream_info.get("secure_m3u8_url") if m3u8_url: yield from HLSStream.parse_variant_playlist(self.session, m3u8_url).items() __plugin__ = Livestream
log.debug("Stream might be Off Air") return
conditional_block
livestream.py
import logging import re from streamlink.plugin import Plugin, pluginmatcher from streamlink.plugin.api import validate from streamlink.stream import HLSStream from streamlink.utils.parse import parse_json log = logging.getLogger(__name__) @pluginmatcher(re.compile( r"https?://(?:www\.)?livestream\.com/" )) class Livestream(Plugin): _config_re = re.compile(r"window.config = ({.+})") _stream_config_schema = validate.Schema(validate.any({ "event": { "stream_info": validate.any({ "is_live": bool, "secure_m3u8_url": validate.url(scheme="https"), }, None), } }, {}), validate.get("event", {}), validate.get("stream_info", {})) def _get_streams(self):
__plugin__ = Livestream
res = self.session.http.get(self.url) m = self._config_re.search(res.text) if not m: log.debug("Unable to find _config_re") return stream_info = parse_json(m.group(1), "config JSON", schema=self._stream_config_schema) log.trace("stream_info: {0!r}".format(stream_info)) if not (stream_info and stream_info["is_live"]): log.debug("Stream might be Off Air") return m3u8_url = stream_info.get("secure_m3u8_url") if m3u8_url: yield from HLSStream.parse_variant_playlist(self.session, m3u8_url).items()
identifier_body
livestream.py
import logging import re from streamlink.plugin import Plugin, pluginmatcher from streamlink.plugin.api import validate from streamlink.stream import HLSStream from streamlink.utils.parse import parse_json log = logging.getLogger(__name__) @pluginmatcher(re.compile( r"https?://(?:www\.)?livestream\.com/" )) class Livestream(Plugin): _config_re = re.compile(r"window.config = ({.+})") _stream_config_schema = validate.Schema(validate.any({ "event": { "stream_info": validate.any({ "is_live": bool, "secure_m3u8_url": validate.url(scheme="https"), }, None), } }, {}), validate.get("event", {}), validate.get("stream_info", {})) def _get_streams(self): res = self.session.http.get(self.url) m = self._config_re.search(res.text) if not m: log.debug("Unable to find _config_re") return
if not (stream_info and stream_info["is_live"]): log.debug("Stream might be Off Air") return m3u8_url = stream_info.get("secure_m3u8_url") if m3u8_url: yield from HLSStream.parse_variant_playlist(self.session, m3u8_url).items() __plugin__ = Livestream
stream_info = parse_json(m.group(1), "config JSON", schema=self._stream_config_schema) log.trace("stream_info: {0!r}".format(stream_info))
random_line_split
productiontiles.component.ts
import {Component, ElementRef} from '@angular/core'; import { ProductionTileService } from '../../shared/services/productiontile.service'; import { Router } from '@angular/router'; import {Observable} from 'rxjs/Rx'; //import 'style-loader!./tiles.scss'; @Component({ selector: 'production-tiles', styleUrls: ['./tiles.scss'], templateUrl: './productiontiles.html' }) export class ProductionTiles { productions: Observable<Array<any>> sub_prod: Observable<Array<any>> summary:number=0; constructor(private router: Router, protected service: ProductionTileService) { } ngOnInit() { this.productions = this.service.getProductionTiles().map(response => response.json()["tiles"]);
this.router.navigate(['pages/productiontiles/details', id]); } summary_details(id): void { this.summary = 1; document.getElementsByClassName('widgets')['0'].style.display = 'none'; document.getElementById("summary").style.display = 'block'; } back_state():void{ this.summary = 0; document.getElementsByClassName('widgets')['0'].style.display = 'block'; document.getElementById("summary").style.display = 'none'; } }
this.sub_prod=this.productions; } button_details(id): void {
random_line_split
productiontiles.component.ts
import {Component, ElementRef} from '@angular/core'; import { ProductionTileService } from '../../shared/services/productiontile.service'; import { Router } from '@angular/router'; import {Observable} from 'rxjs/Rx'; //import 'style-loader!./tiles.scss'; @Component({ selector: 'production-tiles', styleUrls: ['./tiles.scss'], templateUrl: './productiontiles.html' }) export class ProductionTiles { productions: Observable<Array<any>> sub_prod: Observable<Array<any>> summary:number=0; constructor(private router: Router, protected service: ProductionTileService) { } ngOnInit() { this.productions = this.service.getProductionTiles().map(response => response.json()["tiles"]); this.sub_prod=this.productions; } button_details(id): void
summary_details(id): void { this.summary = 1; document.getElementsByClassName('widgets')['0'].style.display = 'none'; document.getElementById("summary").style.display = 'block'; } back_state():void{ this.summary = 0; document.getElementsByClassName('widgets')['0'].style.display = 'block'; document.getElementById("summary").style.display = 'none'; } }
{ this.router.navigate(['pages/productiontiles/details', id]); }
identifier_body
productiontiles.component.ts
import {Component, ElementRef} from '@angular/core'; import { ProductionTileService } from '../../shared/services/productiontile.service'; import { Router } from '@angular/router'; import {Observable} from 'rxjs/Rx'; //import 'style-loader!./tiles.scss'; @Component({ selector: 'production-tiles', styleUrls: ['./tiles.scss'], templateUrl: './productiontiles.html' }) export class ProductionTiles { productions: Observable<Array<any>> sub_prod: Observable<Array<any>> summary:number=0; constructor(private router: Router, protected service: ProductionTileService) { } ngOnInit() { this.productions = this.service.getProductionTiles().map(response => response.json()["tiles"]); this.sub_prod=this.productions; } button_details(id): void { this.router.navigate(['pages/productiontiles/details', id]); }
(id): void { this.summary = 1; document.getElementsByClassName('widgets')['0'].style.display = 'none'; document.getElementById("summary").style.display = 'block'; } back_state():void{ this.summary = 0; document.getElementsByClassName('widgets')['0'].style.display = 'block'; document.getElementById("summary").style.display = 'none'; } }
summary_details
identifier_name
sidebar.js
/** ***** BEGIN LICENSE BLOCK ***** * * Copyright (C) 2019 Marc Ruiz Altisent. All rights reserved. * * This file is part of FoxReplace. * * FoxReplace 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. * * FoxReplace 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 FoxReplace. If not, see <http://www.gnu.org/licenses/>. * * ***** END LICENSE BLOCK ***** */ function
() { document.removeEventListener("DOMContentLoaded", onLoad); document.getElementById("form").addEventListener("submit", onSubmit); } function onUnload() { document.removeEventListener("unload", onUnload); document.getElementById("form").removeEventListener("submit", onSubmit); } function onSubmit(event) { event.preventDefault(); // we just want to get the values, we don't want to submit anything let serialized = $('#form').serializeArray(); let formValues = {}; for (let item of serialized) { formValues[item.name] = item.value; } // Checkbox values are returned as 'on' when checked and missing (thus undefined) when unchecked. This works well when converted to Boolean. let substitutionList = [new SubstitutionGroup("", [], [new Substitution(formValues.input, formValues.output, formValues.caseSensitive, formValues.inputType)], formValues.html, true)]; browser.runtime.sendMessage({ key: "replace", list: substitutionListToJSON(substitutionList) }); } document.addEventListener("DOMContentLoaded", onLoad); document.addEventListener("unload", onUnload);
onLoad
identifier_name
sidebar.js
/** ***** BEGIN LICENSE BLOCK ***** * * Copyright (C) 2019 Marc Ruiz Altisent. All rights reserved. * * This file is part of FoxReplace. * * FoxReplace 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. * * FoxReplace 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 FoxReplace. If not, see <http://www.gnu.org/licenses/>. * * ***** END LICENSE BLOCK ***** */ function onLoad() { document.removeEventListener("DOMContentLoaded", onLoad); document.getElementById("form").addEventListener("submit", onSubmit); } function onUnload() { document.removeEventListener("unload", onUnload); document.getElementById("form").removeEventListener("submit", onSubmit); } function onSubmit(event) { event.preventDefault(); // we just want to get the values, we don't want to submit anything let serialized = $('#form').serializeArray(); let formValues = {}; for (let item of serialized) { formValues[item.name] = item.value; } // Checkbox values are returned as 'on' when checked and missing (thus undefined) when unchecked. This works well when converted to Boolean. let substitutionList = [new SubstitutionGroup("", [], [new Substitution(formValues.input, formValues.output, formValues.caseSensitive, formValues.inputType)], formValues.html, true)]; browser.runtime.sendMessage({ key: "replace", list: substitutionListToJSON(substitutionList) }); } document.addEventListener("DOMContentLoaded", onLoad);
document.addEventListener("unload", onUnload);
random_line_split
sidebar.js
/** ***** BEGIN LICENSE BLOCK ***** * * Copyright (C) 2019 Marc Ruiz Altisent. All rights reserved. * * This file is part of FoxReplace. * * FoxReplace 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. * * FoxReplace 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 FoxReplace. If not, see <http://www.gnu.org/licenses/>. * * ***** END LICENSE BLOCK ***** */ function onLoad() { document.removeEventListener("DOMContentLoaded", onLoad); document.getElementById("form").addEventListener("submit", onSubmit); } function onUnload()
function onSubmit(event) { event.preventDefault(); // we just want to get the values, we don't want to submit anything let serialized = $('#form').serializeArray(); let formValues = {}; for (let item of serialized) { formValues[item.name] = item.value; } // Checkbox values are returned as 'on' when checked and missing (thus undefined) when unchecked. This works well when converted to Boolean. let substitutionList = [new SubstitutionGroup("", [], [new Substitution(formValues.input, formValues.output, formValues.caseSensitive, formValues.inputType)], formValues.html, true)]; browser.runtime.sendMessage({ key: "replace", list: substitutionListToJSON(substitutionList) }); } document.addEventListener("DOMContentLoaded", onLoad); document.addEventListener("unload", onUnload);
{ document.removeEventListener("unload", onUnload); document.getElementById("form").removeEventListener("submit", onSubmit); }
identifier_body
sampler.py
# coding: utf-8 import random import json def
(tar_f=None, res_f=None, res_size=50, start_pos=0, end_pos=100): buff = [] if tar_f: with open(tar_f, 'r') as reader: cnt = 0 for line in reader: buff.append(json.dumps({'text': line, 'id': cnt})) if cnt > end_pos: break cnt += 1 target_field = buff[start_pos: end_pos] result_set = random.sample(target_field, res_size) if not res_f: res_f = '%d_sampled_%s_from_%d_to_%d' % (res_size, res_f, start_pos, end_pos) with open(res_f, 'w') as writer: writer.write('\n'.join(result_set)) else: print 'ERROR: no target file' if __name__ == '__main__': test_f = './template/title_template' full_sample(test_f, res_size=50, start_pos=0, end_pos=2000)
full_sample
identifier_name
sampler.py
# coding: utf-8 import random
import json def full_sample(tar_f=None, res_f=None, res_size=50, start_pos=0, end_pos=100): buff = [] if tar_f: with open(tar_f, 'r') as reader: cnt = 0 for line in reader: buff.append(json.dumps({'text': line, 'id': cnt})) if cnt > end_pos: break cnt += 1 target_field = buff[start_pos: end_pos] result_set = random.sample(target_field, res_size) if not res_f: res_f = '%d_sampled_%s_from_%d_to_%d' % (res_size, res_f, start_pos, end_pos) with open(res_f, 'w') as writer: writer.write('\n'.join(result_set)) else: print 'ERROR: no target file' if __name__ == '__main__': test_f = './template/title_template' full_sample(test_f, res_size=50, start_pos=0, end_pos=2000)
random_line_split
sampler.py
# coding: utf-8 import random import json def full_sample(tar_f=None, res_f=None, res_size=50, start_pos=0, end_pos=100):
if __name__ == '__main__': test_f = './template/title_template' full_sample(test_f, res_size=50, start_pos=0, end_pos=2000)
buff = [] if tar_f: with open(tar_f, 'r') as reader: cnt = 0 for line in reader: buff.append(json.dumps({'text': line, 'id': cnt})) if cnt > end_pos: break cnt += 1 target_field = buff[start_pos: end_pos] result_set = random.sample(target_field, res_size) if not res_f: res_f = '%d_sampled_%s_from_%d_to_%d' % (res_size, res_f, start_pos, end_pos) with open(res_f, 'w') as writer: writer.write('\n'.join(result_set)) else: print 'ERROR: no target file'
identifier_body
sampler.py
# coding: utf-8 import random import json def full_sample(tar_f=None, res_f=None, res_size=50, start_pos=0, end_pos=100): buff = [] if tar_f: with open(tar_f, 'r') as reader: cnt = 0 for line in reader: buff.append(json.dumps({'text': line, 'id': cnt})) if cnt > end_pos: break cnt += 1 target_field = buff[start_pos: end_pos] result_set = random.sample(target_field, res_size) if not res_f: res_f = '%d_sampled_%s_from_%d_to_%d' % (res_size, res_f, start_pos, end_pos) with open(res_f, 'w') as writer: writer.write('\n'.join(result_set)) else: print 'ERROR: no target file' if __name__ == '__main__':
test_f = './template/title_template' full_sample(test_f, res_size=50, start_pos=0, end_pos=2000)
conditional_block
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2013 Nicolas Wack <[email protected]> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # GuessIt 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 # Lesser GNU General Public License for more details. # # You should have received a copy of the Lesser GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from __future__ import absolute_import, division, print_function, unicode_literals import pkg_resources from .__version__ import __version__ __all__ = ['Guess', 'Language', 'guess_file_info', 'guess_video_info', 'guess_movie_info', 'guess_episode_info'] # Do python3 detection before importing any other module, to be sure that # it will then always be available # with code from http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/ import sys if sys.version_info[0] >= 3: # pragma: no cover PY2, PY3 = False, True unicode_text_type = str native_text_type = str base_text_type = str def u(x): return str(x) def s(x): return x class
(object): __str__ = lambda x: x.__unicode__() import binascii def to_hex(x): return binascii.hexlify(x).decode('utf-8') else: # pragma: no cover PY2, PY3 = True, False __all__ = [str(s) for s in __all__] # fix imports for python2 unicode_text_type = unicode native_text_type = str base_text_type = basestring def u(x): if isinstance(x, str): return x.decode('utf-8') if isinstance(x, list): return [u(s) for s in x] return unicode(x) def s(x): if isinstance(x, unicode): return x.encode('utf-8') if isinstance(x, list): return [s(y) for y in x] if isinstance(x, tuple): return tuple(s(y) for y in x) if isinstance(x, dict): return dict((s(key), s(value)) for key, value in x.items()) return x class UnicodeMixin(object): __str__ = lambda x: unicode(x).encode('utf-8') def to_hex(x): return x.encode('hex') range = xrange from guessit.guess import Guess, merge_all from guessit.language import Language from guessit.matcher import IterativeMatcher from guessit.textutils import clean_string, is_camel, from_camel import os.path import logging import json log = logging.getLogger(__name__) class NullHandler(logging.Handler): def emit(self, record): pass # let's be a nicely behaving library h = NullHandler() log.addHandler(h) def _guess_filename(filename, options=None, **kwargs): mtree = _build_filename_mtree(filename, options=options, **kwargs) _add_camel_properties(mtree, options=options) return mtree.matched() def _build_filename_mtree(filename, options=None, **kwargs): mtree = IterativeMatcher(filename, options=options, **kwargs) second_pass_options = mtree.second_pass_options if second_pass_options: log.info("Running 2nd pass") merged_options = dict(options) merged_options.update(second_pass_options) mtree = IterativeMatcher(filename, options=merged_options, **kwargs) return mtree def _add_camel_properties(mtree, options=None, **kwargs): prop = 'title' if mtree.matched().get('type') != 'episode' else 'series' value = mtree.matched().get(prop) _guess_camel_string(mtree, value, options=options, skip_title=False, **kwargs) for leaf in mtree.match_tree.unidentified_leaves(): value = leaf.value _guess_camel_string(mtree, value, options=options, skip_title=True, **kwargs) def _guess_camel_string(mtree, string, options=None, skip_title=False, **kwargs): if string and is_camel(string): log.info('"%s" is camel cased. Try to detect more properties.' % (string,)) uncameled_value = from_camel(string) camel_tree = _build_filename_mtree(uncameled_value, options=options, name_only=True, skip_title=skip_title, **kwargs) if len(camel_tree.matched()) > 0: # Title has changed. mtree.matched().update(camel_tree.matched()) return True return False def guess_file_info(filename, info=None, options=None, **kwargs): """info can contain the names of the various plugins, such as 'filename' to detect filename info, or 'hash_md5' to get the md5 hash of the file. >>> testfile = os.path.join(os.path.dirname(__file__), 'test/dummy.srt') >>> g = guess_file_info(testfile, info = ['hash_md5', 'hash_sha1']) >>> g['hash_md5'], g['hash_sha1'] ('64de6b5893cac24456c46a935ef9c359', 'a703fc0fa4518080505809bf562c6fc6f7b3c98c') """ info = info or 'filename' options = options or {} result = [] hashers = [] # Force unicode as soon as possible filename = u(filename) if isinstance(info, base_text_type): info = [info] for infotype in info: if infotype == 'filename': result.append(_guess_filename(filename, options, **kwargs)) elif infotype == 'hash_mpc': from guessit.hash_mpc import hash_file try: result.append(Guess({infotype: hash_file(filename)}, confidence=1.0)) except Exception as e: log.warning('Could not compute MPC-style hash because: %s' % e) elif infotype == 'hash_ed2k': from guessit.hash_ed2k import hash_file try: result.append(Guess({infotype: hash_file(filename)}, confidence=1.0)) except Exception as e: log.warning('Could not compute ed2k hash because: %s' % e) elif infotype.startswith('hash_'): import hashlib hashname = infotype[5:] try: hasher = getattr(hashlib, hashname)() hashers.append((infotype, hasher)) except AttributeError: log.warning('Could not compute %s hash because it is not available from python\'s hashlib module' % hashname) else: log.warning('Invalid infotype: %s' % infotype) # do all the hashes now, but on a single pass if hashers: try: blocksize = 8192 hasherobjs = dict(hashers).values() with open(filename, 'rb') as f: chunk = f.read(blocksize) while chunk: for hasher in hasherobjs: hasher.update(chunk) chunk = f.read(blocksize) for infotype, hasher in hashers: result.append(Guess({infotype: hasher.hexdigest()}, confidence=1.0)) except Exception as e: log.warning('Could not compute hash because: %s' % e) result = merge_all(result) return result def guess_video_info(filename, info=None, options=None, **kwargs): return guess_file_info(filename, info=info, options=options, type='video', **kwargs) def guess_movie_info(filename, info=None, options=None, **kwargs): return guess_file_info(filename, info=info, options=options, type='movie', **kwargs) def guess_episode_info(filename, info=None, options=None, **kwargs): return guess_file_info(filename, info=info, options=options, type='episode', **kwargs)
UnicodeMixin
identifier_name
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2013 Nicolas Wack <[email protected]> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # GuessIt 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 # Lesser GNU General Public License for more details. # # You should have received a copy of the Lesser GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from __future__ import absolute_import, division, print_function, unicode_literals import pkg_resources from .__version__ import __version__ __all__ = ['Guess', 'Language', 'guess_file_info', 'guess_video_info', 'guess_movie_info', 'guess_episode_info'] # Do python3 detection before importing any other module, to be sure that # it will then always be available # with code from http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/ import sys if sys.version_info[0] >= 3: # pragma: no cover PY2, PY3 = False, True unicode_text_type = str native_text_type = str base_text_type = str def u(x): return str(x) def s(x): return x class UnicodeMixin(object): __str__ = lambda x: x.__unicode__() import binascii def to_hex(x): return binascii.hexlify(x).decode('utf-8') else: # pragma: no cover PY2, PY3 = True, False __all__ = [str(s) for s in __all__] # fix imports for python2 unicode_text_type = unicode native_text_type = str base_text_type = basestring def u(x): if isinstance(x, str): return x.decode('utf-8') if isinstance(x, list): return [u(s) for s in x] return unicode(x) def s(x): if isinstance(x, unicode): return x.encode('utf-8') if isinstance(x, list): return [s(y) for y in x] if isinstance(x, tuple): return tuple(s(y) for y in x) if isinstance(x, dict): return dict((s(key), s(value)) for key, value in x.items()) return x class UnicodeMixin(object): __str__ = lambda x: unicode(x).encode('utf-8') def to_hex(x): return x.encode('hex') range = xrange from guessit.guess import Guess, merge_all from guessit.language import Language from guessit.matcher import IterativeMatcher from guessit.textutils import clean_string, is_camel, from_camel import os.path import logging import json log = logging.getLogger(__name__) class NullHandler(logging.Handler): def emit(self, record): pass # let's be a nicely behaving library h = NullHandler() log.addHandler(h) def _guess_filename(filename, options=None, **kwargs): mtree = _build_filename_mtree(filename, options=options, **kwargs) _add_camel_properties(mtree, options=options) return mtree.matched() def _build_filename_mtree(filename, options=None, **kwargs): mtree = IterativeMatcher(filename, options=options, **kwargs) second_pass_options = mtree.second_pass_options if second_pass_options: log.info("Running 2nd pass") merged_options = dict(options) merged_options.update(second_pass_options) mtree = IterativeMatcher(filename, options=merged_options, **kwargs) return mtree def _add_camel_properties(mtree, options=None, **kwargs): prop = 'title' if mtree.matched().get('type') != 'episode' else 'series' value = mtree.matched().get(prop) _guess_camel_string(mtree, value, options=options, skip_title=False, **kwargs) for leaf in mtree.match_tree.unidentified_leaves(): value = leaf.value _guess_camel_string(mtree, value, options=options, skip_title=True, **kwargs) def _guess_camel_string(mtree, string, options=None, skip_title=False, **kwargs): if string and is_camel(string): log.info('"%s" is camel cased. Try to detect more properties.' % (string,)) uncameled_value = from_camel(string) camel_tree = _build_filename_mtree(uncameled_value, options=options, name_only=True, skip_title=skip_title, **kwargs) if len(camel_tree.matched()) > 0: # Title has changed. mtree.matched().update(camel_tree.matched()) return True return False def guess_file_info(filename, info=None, options=None, **kwargs): """info can contain the names of the various plugins, such as 'filename' to detect filename info, or 'hash_md5' to get the md5 hash of the file. >>> testfile = os.path.join(os.path.dirname(__file__), 'test/dummy.srt') >>> g = guess_file_info(testfile, info = ['hash_md5', 'hash_sha1']) >>> g['hash_md5'], g['hash_sha1'] ('64de6b5893cac24456c46a935ef9c359', 'a703fc0fa4518080505809bf562c6fc6f7b3c98c') """ info = info or 'filename' options = options or {} result = [] hashers = [] # Force unicode as soon as possible filename = u(filename) if isinstance(info, base_text_type): info = [info] for infotype in info: if infotype == 'filename':
elif infotype == 'hash_mpc': from guessit.hash_mpc import hash_file try: result.append(Guess({infotype: hash_file(filename)}, confidence=1.0)) except Exception as e: log.warning('Could not compute MPC-style hash because: %s' % e) elif infotype == 'hash_ed2k': from guessit.hash_ed2k import hash_file try: result.append(Guess({infotype: hash_file(filename)}, confidence=1.0)) except Exception as e: log.warning('Could not compute ed2k hash because: %s' % e) elif infotype.startswith('hash_'): import hashlib hashname = infotype[5:] try: hasher = getattr(hashlib, hashname)() hashers.append((infotype, hasher)) except AttributeError: log.warning('Could not compute %s hash because it is not available from python\'s hashlib module' % hashname) else: log.warning('Invalid infotype: %s' % infotype) # do all the hashes now, but on a single pass if hashers: try: blocksize = 8192 hasherobjs = dict(hashers).values() with open(filename, 'rb') as f: chunk = f.read(blocksize) while chunk: for hasher in hasherobjs: hasher.update(chunk) chunk = f.read(blocksize) for infotype, hasher in hashers: result.append(Guess({infotype: hasher.hexdigest()}, confidence=1.0)) except Exception as e: log.warning('Could not compute hash because: %s' % e) result = merge_all(result) return result def guess_video_info(filename, info=None, options=None, **kwargs): return guess_file_info(filename, info=info, options=options, type='video', **kwargs) def guess_movie_info(filename, info=None, options=None, **kwargs): return guess_file_info(filename, info=info, options=options, type='movie', **kwargs) def guess_episode_info(filename, info=None, options=None, **kwargs): return guess_file_info(filename, info=info, options=options, type='episode', **kwargs)
result.append(_guess_filename(filename, options, **kwargs))
conditional_block
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2013 Nicolas Wack <[email protected]> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # GuessIt 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 # Lesser GNU General Public License for more details. # # You should have received a copy of the Lesser GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from __future__ import absolute_import, division, print_function, unicode_literals import pkg_resources from .__version__ import __version__ __all__ = ['Guess', 'Language', 'guess_file_info', 'guess_video_info', 'guess_movie_info', 'guess_episode_info'] # Do python3 detection before importing any other module, to be sure that # it will then always be available # with code from http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/ import sys if sys.version_info[0] >= 3: # pragma: no cover PY2, PY3 = False, True unicode_text_type = str native_text_type = str base_text_type = str def u(x): return str(x) def s(x): return x class UnicodeMixin(object): __str__ = lambda x: x.__unicode__() import binascii def to_hex(x): return binascii.hexlify(x).decode('utf-8') else: # pragma: no cover PY2, PY3 = True, False __all__ = [str(s) for s in __all__] # fix imports for python2 unicode_text_type = unicode native_text_type = str base_text_type = basestring def u(x): if isinstance(x, str): return x.decode('utf-8') if isinstance(x, list): return [u(s) for s in x] return unicode(x) def s(x):
class UnicodeMixin(object): __str__ = lambda x: unicode(x).encode('utf-8') def to_hex(x): return x.encode('hex') range = xrange from guessit.guess import Guess, merge_all from guessit.language import Language from guessit.matcher import IterativeMatcher from guessit.textutils import clean_string, is_camel, from_camel import os.path import logging import json log = logging.getLogger(__name__) class NullHandler(logging.Handler): def emit(self, record): pass # let's be a nicely behaving library h = NullHandler() log.addHandler(h) def _guess_filename(filename, options=None, **kwargs): mtree = _build_filename_mtree(filename, options=options, **kwargs) _add_camel_properties(mtree, options=options) return mtree.matched() def _build_filename_mtree(filename, options=None, **kwargs): mtree = IterativeMatcher(filename, options=options, **kwargs) second_pass_options = mtree.second_pass_options if second_pass_options: log.info("Running 2nd pass") merged_options = dict(options) merged_options.update(second_pass_options) mtree = IterativeMatcher(filename, options=merged_options, **kwargs) return mtree def _add_camel_properties(mtree, options=None, **kwargs): prop = 'title' if mtree.matched().get('type') != 'episode' else 'series' value = mtree.matched().get(prop) _guess_camel_string(mtree, value, options=options, skip_title=False, **kwargs) for leaf in mtree.match_tree.unidentified_leaves(): value = leaf.value _guess_camel_string(mtree, value, options=options, skip_title=True, **kwargs) def _guess_camel_string(mtree, string, options=None, skip_title=False, **kwargs): if string and is_camel(string): log.info('"%s" is camel cased. Try to detect more properties.' % (string,)) uncameled_value = from_camel(string) camel_tree = _build_filename_mtree(uncameled_value, options=options, name_only=True, skip_title=skip_title, **kwargs) if len(camel_tree.matched()) > 0: # Title has changed. mtree.matched().update(camel_tree.matched()) return True return False def guess_file_info(filename, info=None, options=None, **kwargs): """info can contain the names of the various plugins, such as 'filename' to detect filename info, or 'hash_md5' to get the md5 hash of the file. >>> testfile = os.path.join(os.path.dirname(__file__), 'test/dummy.srt') >>> g = guess_file_info(testfile, info = ['hash_md5', 'hash_sha1']) >>> g['hash_md5'], g['hash_sha1'] ('64de6b5893cac24456c46a935ef9c359', 'a703fc0fa4518080505809bf562c6fc6f7b3c98c') """ info = info or 'filename' options = options or {} result = [] hashers = [] # Force unicode as soon as possible filename = u(filename) if isinstance(info, base_text_type): info = [info] for infotype in info: if infotype == 'filename': result.append(_guess_filename(filename, options, **kwargs)) elif infotype == 'hash_mpc': from guessit.hash_mpc import hash_file try: result.append(Guess({infotype: hash_file(filename)}, confidence=1.0)) except Exception as e: log.warning('Could not compute MPC-style hash because: %s' % e) elif infotype == 'hash_ed2k': from guessit.hash_ed2k import hash_file try: result.append(Guess({infotype: hash_file(filename)}, confidence=1.0)) except Exception as e: log.warning('Could not compute ed2k hash because: %s' % e) elif infotype.startswith('hash_'): import hashlib hashname = infotype[5:] try: hasher = getattr(hashlib, hashname)() hashers.append((infotype, hasher)) except AttributeError: log.warning('Could not compute %s hash because it is not available from python\'s hashlib module' % hashname) else: log.warning('Invalid infotype: %s' % infotype) # do all the hashes now, but on a single pass if hashers: try: blocksize = 8192 hasherobjs = dict(hashers).values() with open(filename, 'rb') as f: chunk = f.read(blocksize) while chunk: for hasher in hasherobjs: hasher.update(chunk) chunk = f.read(blocksize) for infotype, hasher in hashers: result.append(Guess({infotype: hasher.hexdigest()}, confidence=1.0)) except Exception as e: log.warning('Could not compute hash because: %s' % e) result = merge_all(result) return result def guess_video_info(filename, info=None, options=None, **kwargs): return guess_file_info(filename, info=info, options=options, type='video', **kwargs) def guess_movie_info(filename, info=None, options=None, **kwargs): return guess_file_info(filename, info=info, options=options, type='movie', **kwargs) def guess_episode_info(filename, info=None, options=None, **kwargs): return guess_file_info(filename, info=info, options=options, type='episode', **kwargs)
if isinstance(x, unicode): return x.encode('utf-8') if isinstance(x, list): return [s(y) for y in x] if isinstance(x, tuple): return tuple(s(y) for y in x) if isinstance(x, dict): return dict((s(key), s(value)) for key, value in x.items()) return x
identifier_body
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2013 Nicolas Wack <[email protected]> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # GuessIt 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 # Lesser GNU General Public License for more details. # # You should have received a copy of the Lesser GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from __future__ import absolute_import, division, print_function, unicode_literals import pkg_resources from .__version__ import __version__ __all__ = ['Guess', 'Language', 'guess_file_info', 'guess_video_info', 'guess_movie_info', 'guess_episode_info'] # Do python3 detection before importing any other module, to be sure that # it will then always be available # with code from http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/ import sys if sys.version_info[0] >= 3: # pragma: no cover PY2, PY3 = False, True unicode_text_type = str native_text_type = str base_text_type = str def u(x): return str(x) def s(x): return x class UnicodeMixin(object): __str__ = lambda x: x.__unicode__() import binascii def to_hex(x): return binascii.hexlify(x).decode('utf-8') else: # pragma: no cover PY2, PY3 = True, False __all__ = [str(s) for s in __all__] # fix imports for python2 unicode_text_type = unicode native_text_type = str base_text_type = basestring def u(x): if isinstance(x, str): return x.decode('utf-8') if isinstance(x, list): return [u(s) for s in x] return unicode(x) def s(x): if isinstance(x, unicode): return x.encode('utf-8') if isinstance(x, list): return [s(y) for y in x] if isinstance(x, tuple): return tuple(s(y) for y in x) if isinstance(x, dict): return dict((s(key), s(value)) for key, value in x.items()) return x class UnicodeMixin(object): __str__ = lambda x: unicode(x).encode('utf-8') def to_hex(x): return x.encode('hex') range = xrange from guessit.guess import Guess, merge_all from guessit.language import Language from guessit.matcher import IterativeMatcher from guessit.textutils import clean_string, is_camel, from_camel import os.path import logging import json log = logging.getLogger(__name__) class NullHandler(logging.Handler): def emit(self, record): pass # let's be a nicely behaving library h = NullHandler() log.addHandler(h) def _guess_filename(filename, options=None, **kwargs): mtree = _build_filename_mtree(filename, options=options, **kwargs) _add_camel_properties(mtree, options=options) return mtree.matched() def _build_filename_mtree(filename, options=None, **kwargs): mtree = IterativeMatcher(filename, options=options, **kwargs) second_pass_options = mtree.second_pass_options if second_pass_options: log.info("Running 2nd pass") merged_options = dict(options) merged_options.update(second_pass_options) mtree = IterativeMatcher(filename, options=merged_options, **kwargs) return mtree def _add_camel_properties(mtree, options=None, **kwargs): prop = 'title' if mtree.matched().get('type') != 'episode' else 'series' value = mtree.matched().get(prop) _guess_camel_string(mtree, value, options=options, skip_title=False, **kwargs) for leaf in mtree.match_tree.unidentified_leaves(): value = leaf.value _guess_camel_string(mtree, value, options=options, skip_title=True, **kwargs) def _guess_camel_string(mtree, string, options=None, skip_title=False, **kwargs): if string and is_camel(string): log.info('"%s" is camel cased. Try to detect more properties.' % (string,)) uncameled_value = from_camel(string) camel_tree = _build_filename_mtree(uncameled_value, options=options, name_only=True, skip_title=skip_title, **kwargs) if len(camel_tree.matched()) > 0: # Title has changed. mtree.matched().update(camel_tree.matched()) return True return False def guess_file_info(filename, info=None, options=None, **kwargs): """info can contain the names of the various plugins, such as 'filename' to detect filename info, or 'hash_md5' to get the md5 hash of the file. >>> testfile = os.path.join(os.path.dirname(__file__), 'test/dummy.srt') >>> g = guess_file_info(testfile, info = ['hash_md5', 'hash_sha1']) >>> g['hash_md5'], g['hash_sha1'] ('64de6b5893cac24456c46a935ef9c359', 'a703fc0fa4518080505809bf562c6fc6f7b3c98c') """ info = info or 'filename' options = options or {} result = [] hashers = [] # Force unicode as soon as possible filename = u(filename) if isinstance(info, base_text_type): info = [info] for infotype in info: if infotype == 'filename':
from guessit.hash_mpc import hash_file try: result.append(Guess({infotype: hash_file(filename)}, confidence=1.0)) except Exception as e: log.warning('Could not compute MPC-style hash because: %s' % e) elif infotype == 'hash_ed2k': from guessit.hash_ed2k import hash_file try: result.append(Guess({infotype: hash_file(filename)}, confidence=1.0)) except Exception as e: log.warning('Could not compute ed2k hash because: %s' % e) elif infotype.startswith('hash_'): import hashlib hashname = infotype[5:] try: hasher = getattr(hashlib, hashname)() hashers.append((infotype, hasher)) except AttributeError: log.warning('Could not compute %s hash because it is not available from python\'s hashlib module' % hashname) else: log.warning('Invalid infotype: %s' % infotype) # do all the hashes now, but on a single pass if hashers: try: blocksize = 8192 hasherobjs = dict(hashers).values() with open(filename, 'rb') as f: chunk = f.read(blocksize) while chunk: for hasher in hasherobjs: hasher.update(chunk) chunk = f.read(blocksize) for infotype, hasher in hashers: result.append(Guess({infotype: hasher.hexdigest()}, confidence=1.0)) except Exception as e: log.warning('Could not compute hash because: %s' % e) result = merge_all(result) return result def guess_video_info(filename, info=None, options=None, **kwargs): return guess_file_info(filename, info=info, options=options, type='video', **kwargs) def guess_movie_info(filename, info=None, options=None, **kwargs): return guess_file_info(filename, info=info, options=options, type='movie', **kwargs) def guess_episode_info(filename, info=None, options=None, **kwargs): return guess_file_info(filename, info=info, options=options, type='episode', **kwargs)
result.append(_guess_filename(filename, options, **kwargs)) elif infotype == 'hash_mpc':
random_line_split
sha3.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Wrapper around tiny-keccak crate as well as common hash constants. extern crate sha3 as sha3_ext; use std::io; use tiny_keccak::Keccak; use hash::{H256, FixedHash}; use self::sha3_ext::*; /// Get the SHA3 (i.e. Keccak) hash of the empty bytes string. pub const SHA3_EMPTY: H256 = H256( [0xc5, 0xd2, 0x46, 0x01, 0x86, 0xf7, 0x23, 0x3c, 0x92, 0x7e, 0x7d, 0xb2, 0xdc, 0xc7, 0x03, 0xc0, 0xe5, 0x00, 0xb6, 0x53, 0xca, 0x82, 0x27, 0x3b, 0x7b, 0xfa, 0xd8, 0x04, 0x5d, 0x85, 0xa4, 0x70] ); /// The SHA3 of the RLP encoding of empty data. pub const SHA3_NULL_RLP: H256 = H256( [0x56, 0xe8, 0x1f, 0x17, 0x1b, 0xcc, 0x55, 0xa6, 0xff, 0x83, 0x45, 0xe6, 0x92, 0xc0, 0xf8, 0x6e, 0x5b, 0x48, 0xe0, 0x1b, 0x99, 0x6c, 0xad, 0xc0, 0x01, 0x62, 0x2f, 0xb5, 0xe3, 0x63, 0xb4, 0x21] ); /// The SHA3 of the RLP encoding of empty list. pub const SHA3_EMPTY_LIST_RLP: H256 = H256( [0x1d, 0xcc, 0x4d, 0xe8, 0xde, 0xc7, 0x5d, 0x7a, 0xab, 0x85, 0xb5, 0x67, 0xb6, 0xcc, 0xd4, 0x1a, 0xd3, 0x12, 0x45, 0x1b, 0x94, 0x8a, 0x74, 0x13, 0xf0, 0xa1, 0x42, 0xfd, 0x40, 0xd4, 0x93, 0x47] ); /// Types implementing this trait are sha3able. /// /// ``` /// extern crate ethcore_util as util; /// use std::str::FromStr; /// use util::sha3::*; /// use util::hash::*; /// /// fn main() { /// assert_eq!([0u8; 0].sha3(), H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap()); /// } /// ``` pub trait Hashable { /// Calculate SHA3 of this object. fn sha3(&self) -> H256; /// Calculate SHA3 of this object and place result into dest. fn sha3_into(&self, dest: &mut [u8]) { self.sha3().copy_to(dest); } } impl<T> Hashable for T where T: AsRef<[u8]> { fn sha3(&self) -> H256 { let mut ret: H256 = H256::zero(); self.sha3_into(&mut *ret); ret } fn sha3_into(&self, dest: &mut [u8]) { let input: &[u8] = self.as_ref(); unsafe { sha3_256(dest.as_mut_ptr(), dest.len(), input.as_ptr(), input.len()); } } } /// Calculate SHA3 of given stream. pub fn sha3(r: &mut io::BufRead) -> Result<H256, io::Error> { let mut output = [0u8; 32]; let mut input = [0u8; 1024]; let mut sha3 = Keccak::new_keccak256(); // read file loop { let some = try!(r.read(&mut input)); if some == 0 { break; } sha3.update(&input[0..some]); } sha3.finalize(&mut output); Ok(output.into()) } #[cfg(test)] mod tests { use std::fs; use std::io::{Write, BufReader}; use super::*; #[test] fn sha3_empty() { assert_eq!([0u8; 0].sha3(), SHA3_EMPTY); } #[test] fn sha3_as() { assert_eq!([0x41u8; 32].sha3(), From::from("59cad5948673622c1d64e2322488bf01619f7ff45789741b15a9f782ce9290a8")); } #[test] fn should_sha3_a_file() { // given use devtools::RandomTempPath; let path = RandomTempPath::new(); // Prepare file { let mut file = fs::File::create(&path).unwrap(); file.write_all(b"something").unwrap(); } let mut file = BufReader::new(fs::File::open(&path).unwrap());
// when let hash = sha3(&mut file).unwrap(); // then assert_eq!(format!("{:?}", hash), "68371d7e884c168ae2022c82bd837d51837718a7f7dfb7aa3f753074a35e1d87"); } }
random_line_split
sha3.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Wrapper around tiny-keccak crate as well as common hash constants. extern crate sha3 as sha3_ext; use std::io; use tiny_keccak::Keccak; use hash::{H256, FixedHash}; use self::sha3_ext::*; /// Get the SHA3 (i.e. Keccak) hash of the empty bytes string. pub const SHA3_EMPTY: H256 = H256( [0xc5, 0xd2, 0x46, 0x01, 0x86, 0xf7, 0x23, 0x3c, 0x92, 0x7e, 0x7d, 0xb2, 0xdc, 0xc7, 0x03, 0xc0, 0xe5, 0x00, 0xb6, 0x53, 0xca, 0x82, 0x27, 0x3b, 0x7b, 0xfa, 0xd8, 0x04, 0x5d, 0x85, 0xa4, 0x70] ); /// The SHA3 of the RLP encoding of empty data. pub const SHA3_NULL_RLP: H256 = H256( [0x56, 0xe8, 0x1f, 0x17, 0x1b, 0xcc, 0x55, 0xa6, 0xff, 0x83, 0x45, 0xe6, 0x92, 0xc0, 0xf8, 0x6e, 0x5b, 0x48, 0xe0, 0x1b, 0x99, 0x6c, 0xad, 0xc0, 0x01, 0x62, 0x2f, 0xb5, 0xe3, 0x63, 0xb4, 0x21] ); /// The SHA3 of the RLP encoding of empty list. pub const SHA3_EMPTY_LIST_RLP: H256 = H256( [0x1d, 0xcc, 0x4d, 0xe8, 0xde, 0xc7, 0x5d, 0x7a, 0xab, 0x85, 0xb5, 0x67, 0xb6, 0xcc, 0xd4, 0x1a, 0xd3, 0x12, 0x45, 0x1b, 0x94, 0x8a, 0x74, 0x13, 0xf0, 0xa1, 0x42, 0xfd, 0x40, 0xd4, 0x93, 0x47] ); /// Types implementing this trait are sha3able. /// /// ``` /// extern crate ethcore_util as util; /// use std::str::FromStr; /// use util::sha3::*; /// use util::hash::*; /// /// fn main() { /// assert_eq!([0u8; 0].sha3(), H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap()); /// } /// ``` pub trait Hashable { /// Calculate SHA3 of this object. fn sha3(&self) -> H256; /// Calculate SHA3 of this object and place result into dest. fn sha3_into(&self, dest: &mut [u8]) { self.sha3().copy_to(dest); } } impl<T> Hashable for T where T: AsRef<[u8]> { fn sha3(&self) -> H256 { let mut ret: H256 = H256::zero(); self.sha3_into(&mut *ret); ret } fn sha3_into(&self, dest: &mut [u8]) { let input: &[u8] = self.as_ref(); unsafe { sha3_256(dest.as_mut_ptr(), dest.len(), input.as_ptr(), input.len()); } } } /// Calculate SHA3 of given stream. pub fn sha3(r: &mut io::BufRead) -> Result<H256, io::Error> { let mut output = [0u8; 32]; let mut input = [0u8; 1024]; let mut sha3 = Keccak::new_keccak256(); // read file loop { let some = try!(r.read(&mut input)); if some == 0 { break; } sha3.update(&input[0..some]); } sha3.finalize(&mut output); Ok(output.into()) } #[cfg(test)] mod tests { use std::fs; use std::io::{Write, BufReader}; use super::*; #[test] fn sha3_empty() { assert_eq!([0u8; 0].sha3(), SHA3_EMPTY); } #[test] fn sha3_as() { assert_eq!([0x41u8; 32].sha3(), From::from("59cad5948673622c1d64e2322488bf01619f7ff45789741b15a9f782ce9290a8")); } #[test] fn
() { // given use devtools::RandomTempPath; let path = RandomTempPath::new(); // Prepare file { let mut file = fs::File::create(&path).unwrap(); file.write_all(b"something").unwrap(); } let mut file = BufReader::new(fs::File::open(&path).unwrap()); // when let hash = sha3(&mut file).unwrap(); // then assert_eq!(format!("{:?}", hash), "68371d7e884c168ae2022c82bd837d51837718a7f7dfb7aa3f753074a35e1d87"); } }
should_sha3_a_file
identifier_name
sha3.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Wrapper around tiny-keccak crate as well as common hash constants. extern crate sha3 as sha3_ext; use std::io; use tiny_keccak::Keccak; use hash::{H256, FixedHash}; use self::sha3_ext::*; /// Get the SHA3 (i.e. Keccak) hash of the empty bytes string. pub const SHA3_EMPTY: H256 = H256( [0xc5, 0xd2, 0x46, 0x01, 0x86, 0xf7, 0x23, 0x3c, 0x92, 0x7e, 0x7d, 0xb2, 0xdc, 0xc7, 0x03, 0xc0, 0xe5, 0x00, 0xb6, 0x53, 0xca, 0x82, 0x27, 0x3b, 0x7b, 0xfa, 0xd8, 0x04, 0x5d, 0x85, 0xa4, 0x70] ); /// The SHA3 of the RLP encoding of empty data. pub const SHA3_NULL_RLP: H256 = H256( [0x56, 0xe8, 0x1f, 0x17, 0x1b, 0xcc, 0x55, 0xa6, 0xff, 0x83, 0x45, 0xe6, 0x92, 0xc0, 0xf8, 0x6e, 0x5b, 0x48, 0xe0, 0x1b, 0x99, 0x6c, 0xad, 0xc0, 0x01, 0x62, 0x2f, 0xb5, 0xe3, 0x63, 0xb4, 0x21] ); /// The SHA3 of the RLP encoding of empty list. pub const SHA3_EMPTY_LIST_RLP: H256 = H256( [0x1d, 0xcc, 0x4d, 0xe8, 0xde, 0xc7, 0x5d, 0x7a, 0xab, 0x85, 0xb5, 0x67, 0xb6, 0xcc, 0xd4, 0x1a, 0xd3, 0x12, 0x45, 0x1b, 0x94, 0x8a, 0x74, 0x13, 0xf0, 0xa1, 0x42, 0xfd, 0x40, 0xd4, 0x93, 0x47] ); /// Types implementing this trait are sha3able. /// /// ``` /// extern crate ethcore_util as util; /// use std::str::FromStr; /// use util::sha3::*; /// use util::hash::*; /// /// fn main() { /// assert_eq!([0u8; 0].sha3(), H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap()); /// } /// ``` pub trait Hashable { /// Calculate SHA3 of this object. fn sha3(&self) -> H256; /// Calculate SHA3 of this object and place result into dest. fn sha3_into(&self, dest: &mut [u8]) { self.sha3().copy_to(dest); } } impl<T> Hashable for T where T: AsRef<[u8]> { fn sha3(&self) -> H256 { let mut ret: H256 = H256::zero(); self.sha3_into(&mut *ret); ret } fn sha3_into(&self, dest: &mut [u8]) { let input: &[u8] = self.as_ref(); unsafe { sha3_256(dest.as_mut_ptr(), dest.len(), input.as_ptr(), input.len()); } } } /// Calculate SHA3 of given stream. pub fn sha3(r: &mut io::BufRead) -> Result<H256, io::Error> { let mut output = [0u8; 32]; let mut input = [0u8; 1024]; let mut sha3 = Keccak::new_keccak256(); // read file loop { let some = try!(r.read(&mut input)); if some == 0
sha3.update(&input[0..some]); } sha3.finalize(&mut output); Ok(output.into()) } #[cfg(test)] mod tests { use std::fs; use std::io::{Write, BufReader}; use super::*; #[test] fn sha3_empty() { assert_eq!([0u8; 0].sha3(), SHA3_EMPTY); } #[test] fn sha3_as() { assert_eq!([0x41u8; 32].sha3(), From::from("59cad5948673622c1d64e2322488bf01619f7ff45789741b15a9f782ce9290a8")); } #[test] fn should_sha3_a_file() { // given use devtools::RandomTempPath; let path = RandomTempPath::new(); // Prepare file { let mut file = fs::File::create(&path).unwrap(); file.write_all(b"something").unwrap(); } let mut file = BufReader::new(fs::File::open(&path).unwrap()); // when let hash = sha3(&mut file).unwrap(); // then assert_eq!(format!("{:?}", hash), "68371d7e884c168ae2022c82bd837d51837718a7f7dfb7aa3f753074a35e1d87"); } }
{ break; }
conditional_block
sha3.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Wrapper around tiny-keccak crate as well as common hash constants. extern crate sha3 as sha3_ext; use std::io; use tiny_keccak::Keccak; use hash::{H256, FixedHash}; use self::sha3_ext::*; /// Get the SHA3 (i.e. Keccak) hash of the empty bytes string. pub const SHA3_EMPTY: H256 = H256( [0xc5, 0xd2, 0x46, 0x01, 0x86, 0xf7, 0x23, 0x3c, 0x92, 0x7e, 0x7d, 0xb2, 0xdc, 0xc7, 0x03, 0xc0, 0xe5, 0x00, 0xb6, 0x53, 0xca, 0x82, 0x27, 0x3b, 0x7b, 0xfa, 0xd8, 0x04, 0x5d, 0x85, 0xa4, 0x70] ); /// The SHA3 of the RLP encoding of empty data. pub const SHA3_NULL_RLP: H256 = H256( [0x56, 0xe8, 0x1f, 0x17, 0x1b, 0xcc, 0x55, 0xa6, 0xff, 0x83, 0x45, 0xe6, 0x92, 0xc0, 0xf8, 0x6e, 0x5b, 0x48, 0xe0, 0x1b, 0x99, 0x6c, 0xad, 0xc0, 0x01, 0x62, 0x2f, 0xb5, 0xe3, 0x63, 0xb4, 0x21] ); /// The SHA3 of the RLP encoding of empty list. pub const SHA3_EMPTY_LIST_RLP: H256 = H256( [0x1d, 0xcc, 0x4d, 0xe8, 0xde, 0xc7, 0x5d, 0x7a, 0xab, 0x85, 0xb5, 0x67, 0xb6, 0xcc, 0xd4, 0x1a, 0xd3, 0x12, 0x45, 0x1b, 0x94, 0x8a, 0x74, 0x13, 0xf0, 0xa1, 0x42, 0xfd, 0x40, 0xd4, 0x93, 0x47] ); /// Types implementing this trait are sha3able. /// /// ``` /// extern crate ethcore_util as util; /// use std::str::FromStr; /// use util::sha3::*; /// use util::hash::*; /// /// fn main() { /// assert_eq!([0u8; 0].sha3(), H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap()); /// } /// ``` pub trait Hashable { /// Calculate SHA3 of this object. fn sha3(&self) -> H256; /// Calculate SHA3 of this object and place result into dest. fn sha3_into(&self, dest: &mut [u8]) { self.sha3().copy_to(dest); } } impl<T> Hashable for T where T: AsRef<[u8]> { fn sha3(&self) -> H256
fn sha3_into(&self, dest: &mut [u8]) { let input: &[u8] = self.as_ref(); unsafe { sha3_256(dest.as_mut_ptr(), dest.len(), input.as_ptr(), input.len()); } } } /// Calculate SHA3 of given stream. pub fn sha3(r: &mut io::BufRead) -> Result<H256, io::Error> { let mut output = [0u8; 32]; let mut input = [0u8; 1024]; let mut sha3 = Keccak::new_keccak256(); // read file loop { let some = try!(r.read(&mut input)); if some == 0 { break; } sha3.update(&input[0..some]); } sha3.finalize(&mut output); Ok(output.into()) } #[cfg(test)] mod tests { use std::fs; use std::io::{Write, BufReader}; use super::*; #[test] fn sha3_empty() { assert_eq!([0u8; 0].sha3(), SHA3_EMPTY); } #[test] fn sha3_as() { assert_eq!([0x41u8; 32].sha3(), From::from("59cad5948673622c1d64e2322488bf01619f7ff45789741b15a9f782ce9290a8")); } #[test] fn should_sha3_a_file() { // given use devtools::RandomTempPath; let path = RandomTempPath::new(); // Prepare file { let mut file = fs::File::create(&path).unwrap(); file.write_all(b"something").unwrap(); } let mut file = BufReader::new(fs::File::open(&path).unwrap()); // when let hash = sha3(&mut file).unwrap(); // then assert_eq!(format!("{:?}", hash), "68371d7e884c168ae2022c82bd837d51837718a7f7dfb7aa3f753074a35e1d87"); } }
{ let mut ret: H256 = H256::zero(); self.sha3_into(&mut *ret); ret }
identifier_body
mod.rs
#[cfg(test)] use game; use ai; use ai::run_match; use constants::LINES; use std::sync::Arc;
fn match_mc() { let structure = Arc::new(game::Structure::new(&LINES)); let mut white_player = ai::mc::MonteCarloAI::new(1000); let mut black_player = ai::mc::MonteCarloAI::new(1000); run_match(structure, &mut white_player, &mut black_player); } #[test] fn match_mc_tree() { let structure = Arc::new(game::Structure::new(&LINES)); let mut white_player = ai::mc::MonteCarloAI::new(1000); let mut black_player = ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets); run_match(structure, &mut white_player, &mut black_player); } #[test] fn match_tree() { let structure = Arc::new(game::Structure::new(&LINES)); let mut white_player = ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets); let mut black_player = ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets); run_match(structure, &mut white_player, &mut black_player); } #[test] fn subset_coherence() { // This is a property based test, see QuickCheck for more information. use rand::{thread_rng, Rng}; let mut rng = thread_rng(); for _ in 0..10000 { // Ensure that all positions returned by the Subset iterator are // contained in the Subset. let subset = game::Subset(rng.next_u64()); for position in subset.iter() { println!("{:?}", position); assert!(subset.contains(position)); } } }
#[test]
random_line_split
mod.rs
#[cfg(test)] use game; use ai; use ai::run_match; use constants::LINES; use std::sync::Arc; #[test] fn match_mc() { let structure = Arc::new(game::Structure::new(&LINES)); let mut white_player = ai::mc::MonteCarloAI::new(1000); let mut black_player = ai::mc::MonteCarloAI::new(1000); run_match(structure, &mut white_player, &mut black_player); } #[test] fn match_mc_tree() { let structure = Arc::new(game::Structure::new(&LINES)); let mut white_player = ai::mc::MonteCarloAI::new(1000); let mut black_player = ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets); run_match(structure, &mut white_player, &mut black_player); } #[test] fn match_tree()
#[test] fn subset_coherence() { // This is a property based test, see QuickCheck for more information. use rand::{thread_rng, Rng}; let mut rng = thread_rng(); for _ in 0..10000 { // Ensure that all positions returned by the Subset iterator are // contained in the Subset. let subset = game::Subset(rng.next_u64()); for position in subset.iter() { println!("{:?}", position); assert!(subset.contains(position)); } } }
{ let structure = Arc::new(game::Structure::new(&LINES)); let mut white_player = ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets); let mut black_player = ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets); run_match(structure, &mut white_player, &mut black_player); }
identifier_body
mod.rs
#[cfg(test)] use game; use ai; use ai::run_match; use constants::LINES; use std::sync::Arc; #[test] fn match_mc() { let structure = Arc::new(game::Structure::new(&LINES)); let mut white_player = ai::mc::MonteCarloAI::new(1000); let mut black_player = ai::mc::MonteCarloAI::new(1000); run_match(structure, &mut white_player, &mut black_player); } #[test] fn match_mc_tree() { let structure = Arc::new(game::Structure::new(&LINES)); let mut white_player = ai::mc::MonteCarloAI::new(1000); let mut black_player = ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets); run_match(structure, &mut white_player, &mut black_player); } #[test] fn
() { let structure = Arc::new(game::Structure::new(&LINES)); let mut white_player = ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets); let mut black_player = ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets); run_match(structure, &mut white_player, &mut black_player); } #[test] fn subset_coherence() { // This is a property based test, see QuickCheck for more information. use rand::{thread_rng, Rng}; let mut rng = thread_rng(); for _ in 0..10000 { // Ensure that all positions returned by the Subset iterator are // contained in the Subset. let subset = game::Subset(rng.next_u64()); for position in subset.iter() { println!("{:?}", position); assert!(subset.contains(position)); } } }
match_tree
identifier_name
session.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 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 * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ use crate::log::*; use crate::kerberos::*; use crate::smb::smb::*; use crate::smb::smb1_session::*; use crate::smb::auth::*; #[derive(Debug)] pub struct SMBTransactionSessionSetup { pub request_host: Option<SessionSetupRequest>, pub response_host: Option<SessionSetupResponse>, pub ntlmssp: Option<NtlmsspData>, pub krb_ticket: Option<Kerberos5Ticket>, } impl SMBTransactionSessionSetup { pub fn
() -> SMBTransactionSessionSetup { return SMBTransactionSessionSetup { request_host: None, response_host: None, ntlmssp: None, krb_ticket: None, } } } impl SMBState { pub fn new_sessionsetup_tx(&mut self, hdr: SMBCommonHdr) -> &mut SMBTransaction { let mut tx = self.new_tx(); tx.hdr = hdr; tx.type_data = Some(SMBTransactionTypeData::SESSIONSETUP( SMBTransactionSessionSetup::new())); tx.request_done = true; tx.response_done = self.tc_trunc; // no response expected if tc is truncated SCLogDebug!("SMB: TX SESSIONSETUP created: ID {}", tx.id); self.transactions.push(tx); let tx_ref = self.transactions.last_mut(); return tx_ref.unwrap(); } pub fn get_sessionsetup_tx(&mut self, hdr: SMBCommonHdr) -> Option<&mut SMBTransaction> { for tx in &mut self.transactions { let hit = tx.hdr.compare(&hdr) && match tx.type_data { Some(SMBTransactionTypeData::SESSIONSETUP(_)) => { true }, _ => { false }, }; if hit { return Some(tx); } } return None; } }
new
identifier_name
session.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 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 * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ use crate::log::*; use crate::kerberos::*; use crate::smb::smb::*; use crate::smb::smb1_session::*; use crate::smb::auth::*; #[derive(Debug)] pub struct SMBTransactionSessionSetup { pub request_host: Option<SessionSetupRequest>, pub response_host: Option<SessionSetupResponse>, pub ntlmssp: Option<NtlmsspData>, pub krb_ticket: Option<Kerberos5Ticket>,
return SMBTransactionSessionSetup { request_host: None, response_host: None, ntlmssp: None, krb_ticket: None, } } } impl SMBState { pub fn new_sessionsetup_tx(&mut self, hdr: SMBCommonHdr) -> &mut SMBTransaction { let mut tx = self.new_tx(); tx.hdr = hdr; tx.type_data = Some(SMBTransactionTypeData::SESSIONSETUP( SMBTransactionSessionSetup::new())); tx.request_done = true; tx.response_done = self.tc_trunc; // no response expected if tc is truncated SCLogDebug!("SMB: TX SESSIONSETUP created: ID {}", tx.id); self.transactions.push(tx); let tx_ref = self.transactions.last_mut(); return tx_ref.unwrap(); } pub fn get_sessionsetup_tx(&mut self, hdr: SMBCommonHdr) -> Option<&mut SMBTransaction> { for tx in &mut self.transactions { let hit = tx.hdr.compare(&hdr) && match tx.type_data { Some(SMBTransactionTypeData::SESSIONSETUP(_)) => { true }, _ => { false }, }; if hit { return Some(tx); } } return None; } }
} impl SMBTransactionSessionSetup { pub fn new() -> SMBTransactionSessionSetup {
random_line_split
session.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 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 * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ use crate::log::*; use crate::kerberos::*; use crate::smb::smb::*; use crate::smb::smb1_session::*; use crate::smb::auth::*; #[derive(Debug)] pub struct SMBTransactionSessionSetup { pub request_host: Option<SessionSetupRequest>, pub response_host: Option<SessionSetupResponse>, pub ntlmssp: Option<NtlmsspData>, pub krb_ticket: Option<Kerberos5Ticket>, } impl SMBTransactionSessionSetup { pub fn new() -> SMBTransactionSessionSetup { return SMBTransactionSessionSetup { request_host: None, response_host: None, ntlmssp: None, krb_ticket: None, } } } impl SMBState { pub fn new_sessionsetup_tx(&mut self, hdr: SMBCommonHdr) -> &mut SMBTransaction { let mut tx = self.new_tx(); tx.hdr = hdr; tx.type_data = Some(SMBTransactionTypeData::SESSIONSETUP( SMBTransactionSessionSetup::new())); tx.request_done = true; tx.response_done = self.tc_trunc; // no response expected if tc is truncated SCLogDebug!("SMB: TX SESSIONSETUP created: ID {}", tx.id); self.transactions.push(tx); let tx_ref = self.transactions.last_mut(); return tx_ref.unwrap(); } pub fn get_sessionsetup_tx(&mut self, hdr: SMBCommonHdr) -> Option<&mut SMBTransaction>
}
{ for tx in &mut self.transactions { let hit = tx.hdr.compare(&hdr) && match tx.type_data { Some(SMBTransactionTypeData::SESSIONSETUP(_)) => { true }, _ => { false }, }; if hit { return Some(tx); } } return None; }
identifier_body
Config.js
/** * afterglow - An easy to integrate HTML5 video player with lightbox support. * @link http://afterglowplayer.com * @license MIT */ 'use strict'; import Util from '../lib/Util'; class Config { constructor(videoelement, skin = 'afterglow'){ return this.init(videoelement, skin); } init(videoelement, skin = 'afterglow'){ // Check for the video element if(videoelement == undefined){ console.error('Please provide a proper video element to afterglow'); } else{ // Set videoelement this.videoelement = videoelement; // Prepare the options container this.options = {}; // Set the skin this.skin = skin; // Prepare option variables this.setDefaultOptions(); this.setSkinControls(); let util = new Util; // Initialize youtube if the current player is a youtube player if(util.isYoutubePlayer(this.videoelement)){ this.setYoutubeOptions(); } // Initialize vimeo if the current player is a vimeo player if(util.isVimeoPlayer(this.videoelement)){ this.setVimeoOptions(); } } } /** * Sets some basic options based on the videoelement's attributes * @return {void} */ setDefaultOptions(){ // Controls needed for the player this.options.controls = true; // Default tech order this.options.techOrder = ["Html5"]; // Some default player parameters this.options.preload = this.getPlayerAttributeFromVideoElement('preload','auto'); this.options.autoplay = this.getPlayerAttributeFromVideoElement('autoplay'); this.options.poster = this.getPlayerAttributeFromVideoElement('poster'); } /** * Gets a configuration value that has been passed to the videoelement as HTML tag attribute * @param {string} attributename The name of the attribute to get * @param {mixed} fallback The expected fallback if the attribute was not set - false by default * @return {mixed} The attribute (with data-attributename being preferred) or the fallback if none. */ getPlayerAttributeFromVideoElement(attributename, fallback = false){ if(this.videoelement.getAttribute("data-"+attributename) !== null){ return this.videoelement.getAttribute("data-"+attributename); } else if(this.videoelement.getAttribute(attributename) !== null){ return this.videoelement.getAttribute(attributename); } else { return fallback; } } /** * Sets the controls which are needed for the player to work properly. */ setSkinControls(){ // For now, we just output the default 'afterglow' skin children, as there isn't any other skin defined yet let controlBar = { children: [ { name: "currentTimeDisplay" }, { name: "playToggle" }, { name: "durationDisplay" }, { name: "progressControl" }, { name: "ResolutionSwitchingButton" }, { name: "volumeMenuButton", inline:true }, { name: "subtitlesButton" }, { name: "captionsButton" } ] }; this.options.controlBar = controlBar; } /** * Sets options needed for youtube to work and replaces the sources with the correct youtube source */ setYoutubeOptions(){ this.options.showinfo = 0; this.options.techOrder = ["youtube"]; this.options.sources = [{ "type": "video/youtube", "src": "https://www.youtube.com/watch?v="+this.getPlayerAttributeFromVideoElement('youtube-id') }]; let util = new Util; if(util.ie().actualVersion >= 8 && util.ie().actualVersion <= 11){ this.options.youtube = { ytControls : 2, color : "white", modestbranding : 1 }; } else
} /** * Sets options needed for vimeo to work and replaces the sources with the correct vimeo source */ setVimeoOptions(){ this.options.techOrder = ["vimeo"]; this.options.sources = [{ "type": "video/vimeo", "src": "https://vimeo.com/"+this.getPlayerAttributeFromVideoElement('vimeo-id') }]; } /** * Returns the CSS class for the video element * @return {string} */ getSkinClass(){ var cssclass="vjs-afterglow-skin"; if(this.skin !== 'afterglow'){ cssclass += " afterglow-skin-"+this.skin; } // Fix for IE9. Somehow, this is necessary. Won't hurt anyone, so this hack is installed. let util = new Util; if(util.ie().actualVersion == 9){ cssclass += ' ie9-is-bad'; } return cssclass; } } export default Config;
{ this.options.youtube = { 'iv_load_policy' : 3, modestbranding: 1 }; }
conditional_block
Config.js
/** * afterglow - An easy to integrate HTML5 video player with lightbox support. * @link http://afterglowplayer.com * @license MIT */ 'use strict'; import Util from '../lib/Util'; class Config { constructor(videoelement, skin = 'afterglow'){ return this.init(videoelement, skin); } init(videoelement, skin = 'afterglow'){ // Check for the video element if(videoelement == undefined){ console.error('Please provide a proper video element to afterglow'); } else{ // Set videoelement this.videoelement = videoelement; // Prepare the options container this.options = {}; // Set the skin this.skin = skin; // Prepare option variables this.setDefaultOptions(); this.setSkinControls(); let util = new Util; // Initialize youtube if the current player is a youtube player if(util.isYoutubePlayer(this.videoelement)){ this.setYoutubeOptions(); } // Initialize vimeo if the current player is a vimeo player if(util.isVimeoPlayer(this.videoelement)){ this.setVimeoOptions(); } } } /** * Sets some basic options based on the videoelement's attributes * @return {void} */
// Default tech order this.options.techOrder = ["Html5"]; // Some default player parameters this.options.preload = this.getPlayerAttributeFromVideoElement('preload','auto'); this.options.autoplay = this.getPlayerAttributeFromVideoElement('autoplay'); this.options.poster = this.getPlayerAttributeFromVideoElement('poster'); } /** * Gets a configuration value that has been passed to the videoelement as HTML tag attribute * @param {string} attributename The name of the attribute to get * @param {mixed} fallback The expected fallback if the attribute was not set - false by default * @return {mixed} The attribute (with data-attributename being preferred) or the fallback if none. */ getPlayerAttributeFromVideoElement(attributename, fallback = false){ if(this.videoelement.getAttribute("data-"+attributename) !== null){ return this.videoelement.getAttribute("data-"+attributename); } else if(this.videoelement.getAttribute(attributename) !== null){ return this.videoelement.getAttribute(attributename); } else { return fallback; } } /** * Sets the controls which are needed for the player to work properly. */ setSkinControls(){ // For now, we just output the default 'afterglow' skin children, as there isn't any other skin defined yet let controlBar = { children: [ { name: "currentTimeDisplay" }, { name: "playToggle" }, { name: "durationDisplay" }, { name: "progressControl" }, { name: "ResolutionSwitchingButton" }, { name: "volumeMenuButton", inline:true }, { name: "subtitlesButton" }, { name: "captionsButton" } ] }; this.options.controlBar = controlBar; } /** * Sets options needed for youtube to work and replaces the sources with the correct youtube source */ setYoutubeOptions(){ this.options.showinfo = 0; this.options.techOrder = ["youtube"]; this.options.sources = [{ "type": "video/youtube", "src": "https://www.youtube.com/watch?v="+this.getPlayerAttributeFromVideoElement('youtube-id') }]; let util = new Util; if(util.ie().actualVersion >= 8 && util.ie().actualVersion <= 11){ this.options.youtube = { ytControls : 2, color : "white", modestbranding : 1 }; } else{ this.options.youtube = { 'iv_load_policy' : 3, modestbranding: 1 }; } } /** * Sets options needed for vimeo to work and replaces the sources with the correct vimeo source */ setVimeoOptions(){ this.options.techOrder = ["vimeo"]; this.options.sources = [{ "type": "video/vimeo", "src": "https://vimeo.com/"+this.getPlayerAttributeFromVideoElement('vimeo-id') }]; } /** * Returns the CSS class for the video element * @return {string} */ getSkinClass(){ var cssclass="vjs-afterglow-skin"; if(this.skin !== 'afterglow'){ cssclass += " afterglow-skin-"+this.skin; } // Fix for IE9. Somehow, this is necessary. Won't hurt anyone, so this hack is installed. let util = new Util; if(util.ie().actualVersion == 9){ cssclass += ' ie9-is-bad'; } return cssclass; } } export default Config;
setDefaultOptions(){ // Controls needed for the player this.options.controls = true;
random_line_split
Config.js
/** * afterglow - An easy to integrate HTML5 video player with lightbox support. * @link http://afterglowplayer.com * @license MIT */ 'use strict'; import Util from '../lib/Util'; class Config { constructor(videoelement, skin = 'afterglow'){ return this.init(videoelement, skin); } init(videoelement, skin = 'afterglow')
/** * Sets some basic options based on the videoelement's attributes * @return {void} */ setDefaultOptions(){ // Controls needed for the player this.options.controls = true; // Default tech order this.options.techOrder = ["Html5"]; // Some default player parameters this.options.preload = this.getPlayerAttributeFromVideoElement('preload','auto'); this.options.autoplay = this.getPlayerAttributeFromVideoElement('autoplay'); this.options.poster = this.getPlayerAttributeFromVideoElement('poster'); } /** * Gets a configuration value that has been passed to the videoelement as HTML tag attribute * @param {string} attributename The name of the attribute to get * @param {mixed} fallback The expected fallback if the attribute was not set - false by default * @return {mixed} The attribute (with data-attributename being preferred) or the fallback if none. */ getPlayerAttributeFromVideoElement(attributename, fallback = false){ if(this.videoelement.getAttribute("data-"+attributename) !== null){ return this.videoelement.getAttribute("data-"+attributename); } else if(this.videoelement.getAttribute(attributename) !== null){ return this.videoelement.getAttribute(attributename); } else { return fallback; } } /** * Sets the controls which are needed for the player to work properly. */ setSkinControls(){ // For now, we just output the default 'afterglow' skin children, as there isn't any other skin defined yet let controlBar = { children: [ { name: "currentTimeDisplay" }, { name: "playToggle" }, { name: "durationDisplay" }, { name: "progressControl" }, { name: "ResolutionSwitchingButton" }, { name: "volumeMenuButton", inline:true }, { name: "subtitlesButton" }, { name: "captionsButton" } ] }; this.options.controlBar = controlBar; } /** * Sets options needed for youtube to work and replaces the sources with the correct youtube source */ setYoutubeOptions(){ this.options.showinfo = 0; this.options.techOrder = ["youtube"]; this.options.sources = [{ "type": "video/youtube", "src": "https://www.youtube.com/watch?v="+this.getPlayerAttributeFromVideoElement('youtube-id') }]; let util = new Util; if(util.ie().actualVersion >= 8 && util.ie().actualVersion <= 11){ this.options.youtube = { ytControls : 2, color : "white", modestbranding : 1 }; } else{ this.options.youtube = { 'iv_load_policy' : 3, modestbranding: 1 }; } } /** * Sets options needed for vimeo to work and replaces the sources with the correct vimeo source */ setVimeoOptions(){ this.options.techOrder = ["vimeo"]; this.options.sources = [{ "type": "video/vimeo", "src": "https://vimeo.com/"+this.getPlayerAttributeFromVideoElement('vimeo-id') }]; } /** * Returns the CSS class for the video element * @return {string} */ getSkinClass(){ var cssclass="vjs-afterglow-skin"; if(this.skin !== 'afterglow'){ cssclass += " afterglow-skin-"+this.skin; } // Fix for IE9. Somehow, this is necessary. Won't hurt anyone, so this hack is installed. let util = new Util; if(util.ie().actualVersion == 9){ cssclass += ' ie9-is-bad'; } return cssclass; } } export default Config;
{ // Check for the video element if(videoelement == undefined){ console.error('Please provide a proper video element to afterglow'); } else{ // Set videoelement this.videoelement = videoelement; // Prepare the options container this.options = {}; // Set the skin this.skin = skin; // Prepare option variables this.setDefaultOptions(); this.setSkinControls(); let util = new Util; // Initialize youtube if the current player is a youtube player if(util.isYoutubePlayer(this.videoelement)){ this.setYoutubeOptions(); } // Initialize vimeo if the current player is a vimeo player if(util.isVimeoPlayer(this.videoelement)){ this.setVimeoOptions(); } } }
identifier_body
Config.js
/** * afterglow - An easy to integrate HTML5 video player with lightbox support. * @link http://afterglowplayer.com * @license MIT */ 'use strict'; import Util from '../lib/Util'; class Config {
(videoelement, skin = 'afterglow'){ return this.init(videoelement, skin); } init(videoelement, skin = 'afterglow'){ // Check for the video element if(videoelement == undefined){ console.error('Please provide a proper video element to afterglow'); } else{ // Set videoelement this.videoelement = videoelement; // Prepare the options container this.options = {}; // Set the skin this.skin = skin; // Prepare option variables this.setDefaultOptions(); this.setSkinControls(); let util = new Util; // Initialize youtube if the current player is a youtube player if(util.isYoutubePlayer(this.videoelement)){ this.setYoutubeOptions(); } // Initialize vimeo if the current player is a vimeo player if(util.isVimeoPlayer(this.videoelement)){ this.setVimeoOptions(); } } } /** * Sets some basic options based on the videoelement's attributes * @return {void} */ setDefaultOptions(){ // Controls needed for the player this.options.controls = true; // Default tech order this.options.techOrder = ["Html5"]; // Some default player parameters this.options.preload = this.getPlayerAttributeFromVideoElement('preload','auto'); this.options.autoplay = this.getPlayerAttributeFromVideoElement('autoplay'); this.options.poster = this.getPlayerAttributeFromVideoElement('poster'); } /** * Gets a configuration value that has been passed to the videoelement as HTML tag attribute * @param {string} attributename The name of the attribute to get * @param {mixed} fallback The expected fallback if the attribute was not set - false by default * @return {mixed} The attribute (with data-attributename being preferred) or the fallback if none. */ getPlayerAttributeFromVideoElement(attributename, fallback = false){ if(this.videoelement.getAttribute("data-"+attributename) !== null){ return this.videoelement.getAttribute("data-"+attributename); } else if(this.videoelement.getAttribute(attributename) !== null){ return this.videoelement.getAttribute(attributename); } else { return fallback; } } /** * Sets the controls which are needed for the player to work properly. */ setSkinControls(){ // For now, we just output the default 'afterglow' skin children, as there isn't any other skin defined yet let controlBar = { children: [ { name: "currentTimeDisplay" }, { name: "playToggle" }, { name: "durationDisplay" }, { name: "progressControl" }, { name: "ResolutionSwitchingButton" }, { name: "volumeMenuButton", inline:true }, { name: "subtitlesButton" }, { name: "captionsButton" } ] }; this.options.controlBar = controlBar; } /** * Sets options needed for youtube to work and replaces the sources with the correct youtube source */ setYoutubeOptions(){ this.options.showinfo = 0; this.options.techOrder = ["youtube"]; this.options.sources = [{ "type": "video/youtube", "src": "https://www.youtube.com/watch?v="+this.getPlayerAttributeFromVideoElement('youtube-id') }]; let util = new Util; if(util.ie().actualVersion >= 8 && util.ie().actualVersion <= 11){ this.options.youtube = { ytControls : 2, color : "white", modestbranding : 1 }; } else{ this.options.youtube = { 'iv_load_policy' : 3, modestbranding: 1 }; } } /** * Sets options needed for vimeo to work and replaces the sources with the correct vimeo source */ setVimeoOptions(){ this.options.techOrder = ["vimeo"]; this.options.sources = [{ "type": "video/vimeo", "src": "https://vimeo.com/"+this.getPlayerAttributeFromVideoElement('vimeo-id') }]; } /** * Returns the CSS class for the video element * @return {string} */ getSkinClass(){ var cssclass="vjs-afterglow-skin"; if(this.skin !== 'afterglow'){ cssclass += " afterglow-skin-"+this.skin; } // Fix for IE9. Somehow, this is necessary. Won't hurt anyone, so this hack is installed. let util = new Util; if(util.ie().actualVersion == 9){ cssclass += ' ie9-is-bad'; } return cssclass; } } export default Config;
constructor
identifier_name
AlertTab.tsx
import React, { useEffect, useState } from 'react'; import Styled, { css, Keyframes, keyframes } from 'styled-components'; import { IAlertMessage } from '../../store/modules/common'; import Transition, { ENTERED, ENTERING, EXITED, EXITING, TransitionStatus } from 'react-transition-group/Transition'; const ScrollDownKeyFrames = keyframes` from {height: 0;} to {height: 35px;} `; const ScrollUpKeyFrames = keyframes` from {height: 35px;} to {height: 0;} `; const animation = (keyFrame: Keyframes) => css` animation: ${keyFrame} 1s forwards; `; const AlertTabContainer = Styled.div<{ state: TransitionStatus }>` overflow: hidden; width: 100%; background-color: #ffc800; color: white; font-size: 10pt; position: relative; text-align: center; height: 0;
case ENTERING: case ENTERED: return animation(ScrollDownKeyFrames); case EXITING: case EXITED: return animation(ScrollUpKeyFrames); default: return 'height: 0'; } }} `; interface IProps extends IAlertMessage { } const AlertTab: React.FC<IProps> = (props) => { const [animate, setAnimate] = useState<boolean>(true); const { message, duration } = props; let clearAnimationTimeout: number; useEffect(() => { setAnimate(true); }, [message]); useEffect(() => { if (duration) { clearAnimationTimeout = window.setTimeout(() => { setAnimate(false); }, 3000); } return () => { clearAnimationTimeout && clearTimeout(clearAnimationTimeout); }; }, [duration]); return ( <Transition in={animate} timeout={500} unmountOnExit key={message}> {(state) => ( <AlertTabContainer state={state}>{message}</AlertTabContainer> )} </Transition> ); }; export default AlertTab;
line-height: 35px; ${({ state }) => { switch (state) {
random_line_split
0068_iaticheck.py
# -*- coding: utf-8 -*- import django.db.models.deletion from django.db import models, migrations import akvo.rsr.fields class
(migrations.Migration): dependencies = [ ('rsr', '0067_auto_20160412_1858'), ] operations = [ migrations.CreateModel( name='IatiCheck', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('status', models.PositiveSmallIntegerField(verbose_name='status')), ('description', akvo.rsr.fields.ValidXMLTextField(verbose_name='description')), ('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='iati_checks', verbose_name='project', to='rsr.Project')), ], options={ 'verbose_name': 'IATI check', 'verbose_name_plural': 'IATI checks', }, bases=(models.Model,), ), ]
Migration
identifier_name
0068_iaticheck.py
# -*- coding: utf-8 -*- import django.db.models.deletion from django.db import models, migrations import akvo.rsr.fields class Migration(migrations.Migration): dependencies = [ ('rsr', '0067_auto_20160412_1858'), ] operations = [ migrations.CreateModel( name='IatiCheck', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('status', models.PositiveSmallIntegerField(verbose_name='status')), ('description', akvo.rsr.fields.ValidXMLTextField(verbose_name='description')), ('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='iati_checks', verbose_name='project', to='rsr.Project')),
'verbose_name': 'IATI check', 'verbose_name_plural': 'IATI checks', }, bases=(models.Model,), ), ]
], options={
random_line_split
0068_iaticheck.py
# -*- coding: utf-8 -*- import django.db.models.deletion from django.db import models, migrations import akvo.rsr.fields class Migration(migrations.Migration):
dependencies = [ ('rsr', '0067_auto_20160412_1858'), ] operations = [ migrations.CreateModel( name='IatiCheck', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('status', models.PositiveSmallIntegerField(verbose_name='status')), ('description', akvo.rsr.fields.ValidXMLTextField(verbose_name='description')), ('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='iati_checks', verbose_name='project', to='rsr.Project')), ], options={ 'verbose_name': 'IATI check', 'verbose_name_plural': 'IATI checks', }, bases=(models.Model,), ), ]
identifier_body
bench_serialization.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::raft_cmdpb::{CmdType, RaftCmdRequest, Request}; use raft::eraftpb::Entry; use protobuf::{self, Message}; use rand::{thread_rng, RngCore}; use test::Bencher; use collections::HashMap; #[inline] fn gen_rand_str(len: usize) -> Vec<u8> { let mut rand_str = vec![0; len]; thread_rng().fill_bytes(&mut rand_str); rand_str } #[inline] fn generate_requests(map: &HashMap<&[u8], &[u8]>) -> Vec<Request> { let mut reqs = vec![]; for (key, value) in map { let mut r = Request::default(); r.set_cmd_type(CmdType::Put); r.mut_put().set_cf("tikv".to_owned()); r.mut_put().set_key(key.to_vec()); r.mut_put().set_value(value.to_vec()); reqs.push(r); } reqs } fn encode(map: &HashMap<&[u8], &[u8]>) -> Vec<u8> { let mut e = Entry::default(); let mut cmd = RaftCmdRequest::default(); let reqs = generate_requests(map); cmd.set_requests(reqs.into()); let cmd_msg = cmd.write_to_bytes().unwrap(); e.set_data(cmd_msg.into()); e.write_to_bytes().unwrap() } fn decode(data: &[u8]) { let mut entry = Entry::default(); entry.merge_from_bytes(data).unwrap(); let mut cmd = RaftCmdRequest::default(); cmd.merge_from_bytes(entry.get_data()).unwrap(); } #[bench] fn bench_encode_one(b: &mut Bencher) { let key = gen_rand_str(30); let value = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key, &value); b.iter(|| { encode(&map); }); } #[bench] fn bench_decode_one(b: &mut Bencher) { let key = gen_rand_str(30); let value = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key, &value); let data = encode(&map); b.iter(|| { decode(&data); }); } #[bench] fn bench_encode_two(b: &mut Bencher) { let key_for_lock = gen_rand_str(30); let value_for_lock = gen_rand_str(10); let key_for_data = gen_rand_str(30); let value_for_data = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key_for_lock, &value_for_lock);
b.iter(|| { encode(&map); }); } #[bench] fn bench_decode_two(b: &mut Bencher) { let key_for_lock = gen_rand_str(30); let value_for_lock = gen_rand_str(10); let key_for_data = gen_rand_str(30); let value_for_data = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key_for_lock, &value_for_lock); map.insert(&key_for_data, &value_for_data); let data = encode(&map); b.iter(|| { decode(&data); }); }
map.insert(&key_for_data, &value_for_data);
random_line_split
bench_serialization.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::raft_cmdpb::{CmdType, RaftCmdRequest, Request}; use raft::eraftpb::Entry; use protobuf::{self, Message}; use rand::{thread_rng, RngCore}; use test::Bencher; use collections::HashMap; #[inline] fn gen_rand_str(len: usize) -> Vec<u8> { let mut rand_str = vec![0; len]; thread_rng().fill_bytes(&mut rand_str); rand_str } #[inline] fn generate_requests(map: &HashMap<&[u8], &[u8]>) -> Vec<Request> { let mut reqs = vec![]; for (key, value) in map { let mut r = Request::default(); r.set_cmd_type(CmdType::Put); r.mut_put().set_cf("tikv".to_owned()); r.mut_put().set_key(key.to_vec()); r.mut_put().set_value(value.to_vec()); reqs.push(r); } reqs } fn encode(map: &HashMap<&[u8], &[u8]>) -> Vec<u8> { let mut e = Entry::default(); let mut cmd = RaftCmdRequest::default(); let reqs = generate_requests(map); cmd.set_requests(reqs.into()); let cmd_msg = cmd.write_to_bytes().unwrap(); e.set_data(cmd_msg.into()); e.write_to_bytes().unwrap() } fn decode(data: &[u8]) { let mut entry = Entry::default(); entry.merge_from_bytes(data).unwrap(); let mut cmd = RaftCmdRequest::default(); cmd.merge_from_bytes(entry.get_data()).unwrap(); } #[bench] fn bench_encode_one(b: &mut Bencher)
#[bench] fn bench_decode_one(b: &mut Bencher) { let key = gen_rand_str(30); let value = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key, &value); let data = encode(&map); b.iter(|| { decode(&data); }); } #[bench] fn bench_encode_two(b: &mut Bencher) { let key_for_lock = gen_rand_str(30); let value_for_lock = gen_rand_str(10); let key_for_data = gen_rand_str(30); let value_for_data = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key_for_lock, &value_for_lock); map.insert(&key_for_data, &value_for_data); b.iter(|| { encode(&map); }); } #[bench] fn bench_decode_two(b: &mut Bencher) { let key_for_lock = gen_rand_str(30); let value_for_lock = gen_rand_str(10); let key_for_data = gen_rand_str(30); let value_for_data = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key_for_lock, &value_for_lock); map.insert(&key_for_data, &value_for_data); let data = encode(&map); b.iter(|| { decode(&data); }); }
{ let key = gen_rand_str(30); let value = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key, &value); b.iter(|| { encode(&map); }); }
identifier_body
bench_serialization.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::raft_cmdpb::{CmdType, RaftCmdRequest, Request}; use raft::eraftpb::Entry; use protobuf::{self, Message}; use rand::{thread_rng, RngCore}; use test::Bencher; use collections::HashMap; #[inline] fn gen_rand_str(len: usize) -> Vec<u8> { let mut rand_str = vec![0; len]; thread_rng().fill_bytes(&mut rand_str); rand_str } #[inline] fn generate_requests(map: &HashMap<&[u8], &[u8]>) -> Vec<Request> { let mut reqs = vec![]; for (key, value) in map { let mut r = Request::default(); r.set_cmd_type(CmdType::Put); r.mut_put().set_cf("tikv".to_owned()); r.mut_put().set_key(key.to_vec()); r.mut_put().set_value(value.to_vec()); reqs.push(r); } reqs } fn encode(map: &HashMap<&[u8], &[u8]>) -> Vec<u8> { let mut e = Entry::default(); let mut cmd = RaftCmdRequest::default(); let reqs = generate_requests(map); cmd.set_requests(reqs.into()); let cmd_msg = cmd.write_to_bytes().unwrap(); e.set_data(cmd_msg.into()); e.write_to_bytes().unwrap() } fn decode(data: &[u8]) { let mut entry = Entry::default(); entry.merge_from_bytes(data).unwrap(); let mut cmd = RaftCmdRequest::default(); cmd.merge_from_bytes(entry.get_data()).unwrap(); } #[bench] fn bench_encode_one(b: &mut Bencher) { let key = gen_rand_str(30); let value = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key, &value); b.iter(|| { encode(&map); }); } #[bench] fn bench_decode_one(b: &mut Bencher) { let key = gen_rand_str(30); let value = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key, &value); let data = encode(&map); b.iter(|| { decode(&data); }); } #[bench] fn bench_encode_two(b: &mut Bencher) { let key_for_lock = gen_rand_str(30); let value_for_lock = gen_rand_str(10); let key_for_data = gen_rand_str(30); let value_for_data = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key_for_lock, &value_for_lock); map.insert(&key_for_data, &value_for_data); b.iter(|| { encode(&map); }); } #[bench] fn
(b: &mut Bencher) { let key_for_lock = gen_rand_str(30); let value_for_lock = gen_rand_str(10); let key_for_data = gen_rand_str(30); let value_for_data = gen_rand_str(256); let mut map: HashMap<&[u8], &[u8]> = HashMap::default(); map.insert(&key_for_lock, &value_for_lock); map.insert(&key_for_data, &value_for_data); let data = encode(&map); b.iter(|| { decode(&data); }); }
bench_decode_two
identifier_name
extensions.py
# # 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. from solum.api.controllers import common_types from solum.api.controllers.v1.datamodel import types as api_types #from solum.openstack.common import log as logging #LOG = logging.getLogger(__name__) class Extensions(api_types.Base): """extensions resource""" extension_links = [common_types.Link] """This attribute contains Links to extension resources that contain information about the extensions supported by this Platform.""" def
(self, **kwds): # LOG.debug("extensions constructor: %s" % kwds) super(Extensions, self).__init__(**kwds)
__init__
identifier_name
extensions.py
# # 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. from solum.api.controllers import common_types from solum.api.controllers.v1.datamodel import types as api_types #from solum.openstack.common import log as logging #LOG = logging.getLogger(__name__) class Extensions(api_types.Base):
"""extensions resource""" extension_links = [common_types.Link] """This attribute contains Links to extension resources that contain information about the extensions supported by this Platform.""" def __init__(self, **kwds): # LOG.debug("extensions constructor: %s" % kwds) super(Extensions, self).__init__(**kwds)
identifier_body
extensions.py
# # 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. from solum.api.controllers import common_types from solum.api.controllers.v1.datamodel import types as api_types #from solum.openstack.common import log as logging #LOG = logging.getLogger(__name__) class Extensions(api_types.Base): """extensions resource""" extension_links = [common_types.Link]
def __init__(self, **kwds): # LOG.debug("extensions constructor: %s" % kwds) super(Extensions, self).__init__(**kwds)
"""This attribute contains Links to extension resources that contain information about the extensions supported by this Platform."""
random_line_split
vi.js
/** * @Project NUKEVIET 4.x * @Author Mr.Thang ([email protected])
toolbar : 'Dán HTMl để tải ảnh về máy chủ', tooltip : 'Dán bài viết để tải hình ảnh về máy chủ', content_html: 'Nội dung cần tải hình ảnh', url_path_save: 'Đường dẫn lưu trữ hình ảnh', pasteMsg: 'Hãy dán nội dung vào trong khung bên dưới, sử dụng tổ hợp phím (<STRONG>Ctrl/Cmd+V</STRONG>) và nhấn vào nút <STRONG>Đồng ý</STRONG>.', info_action : 'Hãy dán nội dung vào trong khung bên dưới, sử dụng tổ hợp phím (Ctrl/Cmd+V) và nhấn vào nút Đồng ý.' });
* @License GNU/GPL version 2 or any later version * @Createdate 16-03-2015 12:55 */ CKEDITOR.plugins.setLang('tbvdownload', 'vi', {
random_line_split
profiling.py
from __future__ import absolute_import, division, unicode_literals from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from debug_toolbar.panels import Panel from debug_toolbar import settings as dt_settings import cProfile from pstats import Stats from colorsys import hsv_to_rgb import os class DjangoDebugToolbarStats(Stats): __root = None def get_root_func(self): if self.__root is None: for func, (cc, nc, tt, ct, callers) in self.stats.items(): if len(callers) == 0: self.__root = func break return self.__root class FunctionCall(object): def __init__(self, statobj, func, depth=0, stats=None, id=0, parent_ids=[], hsv=(0, 0.5, 1)): self.statobj = statobj self.func = func if stats: self.stats = stats else: self.stats = statobj.stats[func][:4] self.depth = depth self.id = id self.parent_ids = parent_ids self.hsv = hsv def parent_classes(self): return self.parent_classes def background(self): r, g, b = hsv_to_rgb(*self.hsv) return 'rgb(%f%%,%f%%,%f%%)' % (r * 100, g * 100, b * 100) def func_std_string(self): # match what old profile produced func_name = self.func if func_name[:2] == ('~', 0): # special case for built-in functions name = func_name[2] if name.startswith('<') and name.endswith('>'): return '{%s}' % name[1:-1] else: return name else: file_name, line_num, method = self.func idx = file_name.find('/site-packages/') if idx > -1: file_name = file_name[(idx + 14):] file_path, file_name = file_name.rsplit(os.sep, 1) return mark_safe( '<span class="path">{0}/</span>' '<span class="file">{1}</span>' ' in <span class="func">{3}</span>' '(<span class="lineno">{2}</span>)'.format( file_path, file_name, line_num, method)) def subfuncs(self): i = 0 h, s, v = self.hsv count = len(self.statobj.all_callees[self.func]) for func, stats in self.statobj.all_callees[self.func].items(): i += 1 h1 = h + (i / count) / (self.depth + 1) if stats[3] == 0: s1 = 0 else: s1 = s * (stats[3] / self.stats[3]) yield FunctionCall(self.statobj, func, self.depth + 1, stats=stats, id=str(self.id) + '_' + str(i), parent_ids=self.parent_ids + [self.id], hsv=(h1, s1, 1)) def count(self): return self.stats[1] def tottime(self): return self.stats[2] def
(self): cc, nc, tt, ct = self.stats return self.stats[3] def tottime_per_call(self): cc, nc, tt, ct = self.stats if nc == 0: return 0 return tt / nc def cumtime_per_call(self): cc, nc, tt, ct = self.stats if cc == 0: return 0 return ct / cc def indent(self): return 16 * self.depth class ProfilingPanel(Panel): """ Panel that displays profiling information. """ title = _("Profiling") template = 'debug_toolbar/panels/profiling.html' def process_view(self, request, view_func, view_args, view_kwargs): self.profiler = cProfile.Profile() args = (request,) + view_args return self.profiler.runcall(view_func, *args, **view_kwargs) def add_node(self, func_list, func, max_depth, cum_time=0.1): func_list.append(func) func.has_subfuncs = False if func.depth < max_depth: for subfunc in func.subfuncs(): if subfunc.stats[3] >= cum_time: func.has_subfuncs = True self.add_node(func_list, subfunc, max_depth, cum_time=cum_time) def process_response(self, request, response): if not hasattr(self, 'profiler'): return None # Could be delayed until the panel content is requested (perf. optim.) self.profiler.create_stats() self.stats = DjangoDebugToolbarStats(self.profiler) self.stats.calc_callees() root = FunctionCall(self.stats, self.stats.get_root_func(), depth=0) func_list = [] self.add_node(func_list, root, dt_settings.CONFIG['PROFILER_MAX_DEPTH'], root.stats[3] / 8) self.record_stats({'func_list': func_list})
cumtime
identifier_name
profiling.py
from __future__ import absolute_import, division, unicode_literals from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from debug_toolbar.panels import Panel from debug_toolbar import settings as dt_settings import cProfile from pstats import Stats from colorsys import hsv_to_rgb import os class DjangoDebugToolbarStats(Stats): __root = None def get_root_func(self): if self.__root is None: for func, (cc, nc, tt, ct, callers) in self.stats.items(): if len(callers) == 0: self.__root = func break return self.__root class FunctionCall(object): def __init__(self, statobj, func, depth=0, stats=None, id=0, parent_ids=[], hsv=(0, 0.5, 1)): self.statobj = statobj self.func = func if stats: self.stats = stats else: self.stats = statobj.stats[func][:4] self.depth = depth self.id = id self.parent_ids = parent_ids self.hsv = hsv def parent_classes(self): return self.parent_classes def background(self): r, g, b = hsv_to_rgb(*self.hsv) return 'rgb(%f%%,%f%%,%f%%)' % (r * 100, g * 100, b * 100) def func_std_string(self): # match what old profile produced func_name = self.func if func_name[:2] == ('~', 0): # special case for built-in functions name = func_name[2] if name.startswith('<') and name.endswith('>'): return '{%s}' % name[1:-1] else: return name else: file_name, line_num, method = self.func idx = file_name.find('/site-packages/') if idx > -1: file_name = file_name[(idx + 14):] file_path, file_name = file_name.rsplit(os.sep, 1) return mark_safe( '<span class="path">{0}/</span>' '<span class="file">{1}</span>' ' in <span class="func">{3}</span>' '(<span class="lineno">{2}</span>)'.format( file_path, file_name, line_num, method)) def subfuncs(self): i = 0 h, s, v = self.hsv count = len(self.statobj.all_callees[self.func]) for func, stats in self.statobj.all_callees[self.func].items(): i += 1 h1 = h + (i / count) / (self.depth + 1) if stats[3] == 0: s1 = 0 else: s1 = s * (stats[3] / self.stats[3]) yield FunctionCall(self.statobj, func, self.depth + 1, stats=stats, id=str(self.id) + '_' + str(i), parent_ids=self.parent_ids + [self.id], hsv=(h1, s1, 1)) def count(self): return self.stats[1] def tottime(self): return self.stats[2] def cumtime(self): cc, nc, tt, ct = self.stats return self.stats[3] def tottime_per_call(self): cc, nc, tt, ct = self.stats if nc == 0: return 0 return tt / nc def cumtime_per_call(self): cc, nc, tt, ct = self.stats if cc == 0: return 0 return ct / cc def indent(self): return 16 * self.depth class ProfilingPanel(Panel): """ Panel that displays profiling information. """ title = _("Profiling") template = 'debug_toolbar/panels/profiling.html' def process_view(self, request, view_func, view_args, view_kwargs): self.profiler = cProfile.Profile() args = (request,) + view_args return self.profiler.runcall(view_func, *args, **view_kwargs) def add_node(self, func_list, func, max_depth, cum_time=0.1): func_list.append(func) func.has_subfuncs = False if func.depth < max_depth: for subfunc in func.subfuncs(): if subfunc.stats[3] >= cum_time: func.has_subfuncs = True self.add_node(func_list, subfunc, max_depth, cum_time=cum_time) def process_response(self, request, response):
if not hasattr(self, 'profiler'): return None # Could be delayed until the panel content is requested (perf. optim.) self.profiler.create_stats() self.stats = DjangoDebugToolbarStats(self.profiler) self.stats.calc_callees() root = FunctionCall(self.stats, self.stats.get_root_func(), depth=0) func_list = [] self.add_node(func_list, root, dt_settings.CONFIG['PROFILER_MAX_DEPTH'], root.stats[3] / 8) self.record_stats({'func_list': func_list})
identifier_body
profiling.py
from __future__ import absolute_import, division, unicode_literals from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from debug_toolbar.panels import Panel from debug_toolbar import settings as dt_settings import cProfile from pstats import Stats from colorsys import hsv_to_rgb import os class DjangoDebugToolbarStats(Stats): __root = None def get_root_func(self): if self.__root is None: for func, (cc, nc, tt, ct, callers) in self.stats.items(): if len(callers) == 0: self.__root = func break return self.__root class FunctionCall(object): def __init__(self, statobj, func, depth=0, stats=None, id=0, parent_ids=[], hsv=(0, 0.5, 1)): self.statobj = statobj self.func = func if stats: self.stats = stats else: self.stats = statobj.stats[func][:4] self.depth = depth self.id = id self.parent_ids = parent_ids self.hsv = hsv def parent_classes(self): return self.parent_classes def background(self): r, g, b = hsv_to_rgb(*self.hsv) return 'rgb(%f%%,%f%%,%f%%)' % (r * 100, g * 100, b * 100) def func_std_string(self): # match what old profile produced func_name = self.func if func_name[:2] == ('~', 0): # special case for built-in functions name = func_name[2] if name.startswith('<') and name.endswith('>'): return '{%s}' % name[1:-1] else: return name else: file_name, line_num, method = self.func idx = file_name.find('/site-packages/') if idx > -1: file_name = file_name[(idx + 14):] file_path, file_name = file_name.rsplit(os.sep, 1) return mark_safe( '<span class="path">{0}/</span>' '<span class="file">{1}</span>' ' in <span class="func">{3}</span>' '(<span class="lineno">{2}</span>)'.format( file_path, file_name, line_num, method)) def subfuncs(self): i = 0 h, s, v = self.hsv count = len(self.statobj.all_callees[self.func]) for func, stats in self.statobj.all_callees[self.func].items(): i += 1 h1 = h + (i / count) / (self.depth + 1) if stats[3] == 0: s1 = 0 else: s1 = s * (stats[3] / self.stats[3]) yield FunctionCall(self.statobj, func, self.depth + 1, stats=stats, id=str(self.id) + '_' + str(i), parent_ids=self.parent_ids + [self.id], hsv=(h1, s1, 1)) def count(self): return self.stats[1] def tottime(self): return self.stats[2] def cumtime(self): cc, nc, tt, ct = self.stats return self.stats[3] def tottime_per_call(self): cc, nc, tt, ct = self.stats if nc == 0: return 0 return tt / nc def cumtime_per_call(self): cc, nc, tt, ct = self.stats if cc == 0: return 0 return ct / cc def indent(self): return 16 * self.depth class ProfilingPanel(Panel): """ Panel that displays profiling information. """ title = _("Profiling") template = 'debug_toolbar/panels/profiling.html' def process_view(self, request, view_func, view_args, view_kwargs): self.profiler = cProfile.Profile() args = (request,) + view_args return self.profiler.runcall(view_func, *args, **view_kwargs) def add_node(self, func_list, func, max_depth, cum_time=0.1): func_list.append(func) func.has_subfuncs = False if func.depth < max_depth: for subfunc in func.subfuncs(): if subfunc.stats[3] >= cum_time: func.has_subfuncs = True self.add_node(func_list, subfunc, max_depth, cum_time=cum_time) def process_response(self, request, response): if not hasattr(self, 'profiler'): return None
self.stats = DjangoDebugToolbarStats(self.profiler) self.stats.calc_callees() root = FunctionCall(self.stats, self.stats.get_root_func(), depth=0) func_list = [] self.add_node(func_list, root, dt_settings.CONFIG['PROFILER_MAX_DEPTH'], root.stats[3] / 8) self.record_stats({'func_list': func_list})
# Could be delayed until the panel content is requested (perf. optim.) self.profiler.create_stats()
random_line_split
profiling.py
from __future__ import absolute_import, division, unicode_literals from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from debug_toolbar.panels import Panel from debug_toolbar import settings as dt_settings import cProfile from pstats import Stats from colorsys import hsv_to_rgb import os class DjangoDebugToolbarStats(Stats): __root = None def get_root_func(self): if self.__root is None: for func, (cc, nc, tt, ct, callers) in self.stats.items(): if len(callers) == 0: self.__root = func break return self.__root class FunctionCall(object): def __init__(self, statobj, func, depth=0, stats=None, id=0, parent_ids=[], hsv=(0, 0.5, 1)): self.statobj = statobj self.func = func if stats: self.stats = stats else: self.stats = statobj.stats[func][:4] self.depth = depth self.id = id self.parent_ids = parent_ids self.hsv = hsv def parent_classes(self): return self.parent_classes def background(self): r, g, b = hsv_to_rgb(*self.hsv) return 'rgb(%f%%,%f%%,%f%%)' % (r * 100, g * 100, b * 100) def func_std_string(self): # match what old profile produced func_name = self.func if func_name[:2] == ('~', 0): # special case for built-in functions name = func_name[2] if name.startswith('<') and name.endswith('>'): return '{%s}' % name[1:-1] else: return name else:
def subfuncs(self): i = 0 h, s, v = self.hsv count = len(self.statobj.all_callees[self.func]) for func, stats in self.statobj.all_callees[self.func].items(): i += 1 h1 = h + (i / count) / (self.depth + 1) if stats[3] == 0: s1 = 0 else: s1 = s * (stats[3] / self.stats[3]) yield FunctionCall(self.statobj, func, self.depth + 1, stats=stats, id=str(self.id) + '_' + str(i), parent_ids=self.parent_ids + [self.id], hsv=(h1, s1, 1)) def count(self): return self.stats[1] def tottime(self): return self.stats[2] def cumtime(self): cc, nc, tt, ct = self.stats return self.stats[3] def tottime_per_call(self): cc, nc, tt, ct = self.stats if nc == 0: return 0 return tt / nc def cumtime_per_call(self): cc, nc, tt, ct = self.stats if cc == 0: return 0 return ct / cc def indent(self): return 16 * self.depth class ProfilingPanel(Panel): """ Panel that displays profiling information. """ title = _("Profiling") template = 'debug_toolbar/panels/profiling.html' def process_view(self, request, view_func, view_args, view_kwargs): self.profiler = cProfile.Profile() args = (request,) + view_args return self.profiler.runcall(view_func, *args, **view_kwargs) def add_node(self, func_list, func, max_depth, cum_time=0.1): func_list.append(func) func.has_subfuncs = False if func.depth < max_depth: for subfunc in func.subfuncs(): if subfunc.stats[3] >= cum_time: func.has_subfuncs = True self.add_node(func_list, subfunc, max_depth, cum_time=cum_time) def process_response(self, request, response): if not hasattr(self, 'profiler'): return None # Could be delayed until the panel content is requested (perf. optim.) self.profiler.create_stats() self.stats = DjangoDebugToolbarStats(self.profiler) self.stats.calc_callees() root = FunctionCall(self.stats, self.stats.get_root_func(), depth=0) func_list = [] self.add_node(func_list, root, dt_settings.CONFIG['PROFILER_MAX_DEPTH'], root.stats[3] / 8) self.record_stats({'func_list': func_list})
file_name, line_num, method = self.func idx = file_name.find('/site-packages/') if idx > -1: file_name = file_name[(idx + 14):] file_path, file_name = file_name.rsplit(os.sep, 1) return mark_safe( '<span class="path">{0}/</span>' '<span class="file">{1}</span>' ' in <span class="func">{3}</span>' '(<span class="lineno">{2}</span>)'.format( file_path, file_name, line_num, method))
conditional_block
WhoObserver.py
from FaustBot.Communication import Connection from FaustBot.Model.RemoteUser import RemoteUser from FaustBot.Modules.MagicNumberObserverPrototype import MagicNumberObserverPrototype from FaustBot.Modules.ModuleType import ModuleType from FaustBot.Modules.PingObserverPrototype import PingObserverPrototype from FaustBot.Modules.UserList import UserList class WhoObserver(MagicNumberObserverPrototype, PingObserverPrototype): @staticmethod def cmd(): return None @staticmethod def help(): return None def __init__(self, user_list: UserList): super().__init__() self.user_list = user_list self.pings_seen = 1 self.pending_whos = [] @staticmethod def get_module_types(): return [ModuleType.ON_MAGIC_NUMBER, ModuleType.ON_PING] def update_on_magic_number(self, data, connection): if data['number'] == '352': # RPL_WHOREPLY self.input_who(data, connection) elif data['number'] == '315': # RPL_ENDOFWHO self.end_who() def input_who(self, data, connection: Connection): # target #channel user host server nick status :0 gecos target, channel, user, host, server, nick, *ign = data['arguments'].split(' ') self.pending_whos.append(RemoteUser(nick, user, host)) def end_who(self): self.user_list.clear_list() for remuser in self.pending_whos:
self.pending_whos = [] def update_on_ping(self, data, connection: Connection): if self.pings_seen % 90 == 0: # 90 * 2 min = 3 Stunden connection.raw_send('WHO ' + connection.details.get_channel()) self.pings_seen += 1
self.user_list.add_user(remuser)
conditional_block
WhoObserver.py
from FaustBot.Communication import Connection from FaustBot.Model.RemoteUser import RemoteUser from FaustBot.Modules.MagicNumberObserverPrototype import MagicNumberObserverPrototype from FaustBot.Modules.ModuleType import ModuleType from FaustBot.Modules.PingObserverPrototype import PingObserverPrototype from FaustBot.Modules.UserList import UserList class WhoObserver(MagicNumberObserverPrototype, PingObserverPrototype): @staticmethod def cmd(): return None @staticmethod def help(): return None def __init__(self, user_list: UserList): super().__init__() self.user_list = user_list self.pings_seen = 1 self.pending_whos = [] @staticmethod def get_module_types():
def update_on_magic_number(self, data, connection): if data['number'] == '352': # RPL_WHOREPLY self.input_who(data, connection) elif data['number'] == '315': # RPL_ENDOFWHO self.end_who() def input_who(self, data, connection: Connection): # target #channel user host server nick status :0 gecos target, channel, user, host, server, nick, *ign = data['arguments'].split(' ') self.pending_whos.append(RemoteUser(nick, user, host)) def end_who(self): self.user_list.clear_list() for remuser in self.pending_whos: self.user_list.add_user(remuser) self.pending_whos = [] def update_on_ping(self, data, connection: Connection): if self.pings_seen % 90 == 0: # 90 * 2 min = 3 Stunden connection.raw_send('WHO ' + connection.details.get_channel()) self.pings_seen += 1
return [ModuleType.ON_MAGIC_NUMBER, ModuleType.ON_PING]
identifier_body
WhoObserver.py
from FaustBot.Communication import Connection from FaustBot.Model.RemoteUser import RemoteUser from FaustBot.Modules.MagicNumberObserverPrototype import MagicNumberObserverPrototype from FaustBot.Modules.ModuleType import ModuleType from FaustBot.Modules.PingObserverPrototype import PingObserverPrototype from FaustBot.Modules.UserList import UserList class WhoObserver(MagicNumberObserverPrototype, PingObserverPrototype): @staticmethod def cmd(): return None @staticmethod def
(): return None def __init__(self, user_list: UserList): super().__init__() self.user_list = user_list self.pings_seen = 1 self.pending_whos = [] @staticmethod def get_module_types(): return [ModuleType.ON_MAGIC_NUMBER, ModuleType.ON_PING] def update_on_magic_number(self, data, connection): if data['number'] == '352': # RPL_WHOREPLY self.input_who(data, connection) elif data['number'] == '315': # RPL_ENDOFWHO self.end_who() def input_who(self, data, connection: Connection): # target #channel user host server nick status :0 gecos target, channel, user, host, server, nick, *ign = data['arguments'].split(' ') self.pending_whos.append(RemoteUser(nick, user, host)) def end_who(self): self.user_list.clear_list() for remuser in self.pending_whos: self.user_list.add_user(remuser) self.pending_whos = [] def update_on_ping(self, data, connection: Connection): if self.pings_seen % 90 == 0: # 90 * 2 min = 3 Stunden connection.raw_send('WHO ' + connection.details.get_channel()) self.pings_seen += 1
help
identifier_name
WhoObserver.py
from FaustBot.Communication import Connection from FaustBot.Model.RemoteUser import RemoteUser from FaustBot.Modules.MagicNumberObserverPrototype import MagicNumberObserverPrototype
from FaustBot.Modules.PingObserverPrototype import PingObserverPrototype from FaustBot.Modules.UserList import UserList class WhoObserver(MagicNumberObserverPrototype, PingObserverPrototype): @staticmethod def cmd(): return None @staticmethod def help(): return None def __init__(self, user_list: UserList): super().__init__() self.user_list = user_list self.pings_seen = 1 self.pending_whos = [] @staticmethod def get_module_types(): return [ModuleType.ON_MAGIC_NUMBER, ModuleType.ON_PING] def update_on_magic_number(self, data, connection): if data['number'] == '352': # RPL_WHOREPLY self.input_who(data, connection) elif data['number'] == '315': # RPL_ENDOFWHO self.end_who() def input_who(self, data, connection: Connection): # target #channel user host server nick status :0 gecos target, channel, user, host, server, nick, *ign = data['arguments'].split(' ') self.pending_whos.append(RemoteUser(nick, user, host)) def end_who(self): self.user_list.clear_list() for remuser in self.pending_whos: self.user_list.add_user(remuser) self.pending_whos = [] def update_on_ping(self, data, connection: Connection): if self.pings_seen % 90 == 0: # 90 * 2 min = 3 Stunden connection.raw_send('WHO ' + connection.details.get_channel()) self.pings_seen += 1
from FaustBot.Modules.ModuleType import ModuleType
random_line_split
data_Error_Num__JOIN_5.js
var nodes = new vis.DataSet([ /* {id: a, label: b, ...}, */
var edges = new vis.DataSet([ /* {from: id_a, to: id_b}, */ {from: '5002', to: '5003'}, {from: '5001', to: '5003'}, {from: '5003', to: '5000'} ]);
{id: '5000', label: 'A1\n#NUM!', color: '#31b0d5', title: 'Name: A1<br>Alias: null<br>Value: #NUM!<br>Type: CELL_WITH_FORMULA<br>Id: 5000<br>Formula Expression: Formula String: COMBIN(VALUE, VALUE); Formula Values: COMBIN(8.0, 6.0); Formula Ptg: ; Ptgs: Index in Ptgs: 0 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@285b63eb'}, {id: '5001', label: 'VALUE\n6.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 6.0<br>Type: CONSTANT_VALUE<br>Id: 5001<br>Formula Expression: Formula String: VALUE; Formula Values: 6.0; Formula Ptg: 6.0; Ptgs: VALUE Index in Ptgs: 0 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@285b63eb'}, {id: '5002', label: 'VALUE\n8.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 8.0<br>Type: CONSTANT_VALUE<br>Id: 5002<br>Formula Expression: Formula String: VALUE; Formula Values: 8.0; Formula Ptg: 8.0; Ptgs: VALUE Index in Ptgs: 1 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@285b63eb'}, {id: '5003', label: 'COMBIN\n#NUM!', color: '#f0ad4e', title: 'Name: COMBIN<br>Alias: null<br>Value: #NUM!<br>Type: FUNCTION<br>Id: 5003<br>Formula Expression: Formula String: COMBIN(VALUE, VALUE); Formula Values: COMBIN(8.0, 6.0); Formula Ptg: ; Ptgs: Index in Ptgs: 2 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@285b63eb'} ]);
random_line_split
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn
() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is {}", secret_number); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("Failed to read line"); // シャドーイングにより、16行目で定義したguess変数を隠し、新しい変数定義を利用できる let guess: u32 = match guess.trim().parse() { // 入力には改行文字が含まれるため、 trim()で削除する Ok(num) => num, Err(_) => continue, // 数値以外が入ってきてもエラーにはせずループを続行させる }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { // Ordering は enum Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
main
identifier_name
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main()
{ println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is {}", secret_number); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("Failed to read line"); // シャドーイングにより、16行目で定義したguess変数を隠し、新しい変数定義を利用できる let guess: u32 = match guess.trim().parse() { // 入力には改行文字が含まれるため、 trim()で削除する Ok(num) => num, Err(_) => continue, // 数値以外が入ってきてもエラーにはせずループを続行させる }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { // Ordering は enum Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
identifier_body
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is {}", secret_number); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("Failed to read line"); // シャドーイングにより、16行目で定義したguess変数を隠し、新しい変数定義を利用できる let guess: u32 = match guess.trim().parse() { // 入力には改行文字が含まれるため、 trim()で削除する Ok(num) => num, Err(_) => continue, // 数値以外が入ってきてもエラーにはせずループを続行させる }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { // Ordering は enum Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
conditional_block
main.rs
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is {}", secret_number); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("Failed to read line"); // シャドーイングにより、16行目で定義したguess変数を隠し、新しい変数定義を利用できる let guess: u32 = match guess.trim().parse() { // 入力には改行文字が含まれるため、 trim()で削除する Ok(num) => num, Err(_) => continue, // 数値以外が入ってきてもエラーにはせずループを続行させる }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { // Ordering は enum Ordering::Less => println!("Too small!"),
break; } } } }
Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!");
random_line_split
_font.py
import _plotly_utils.basevalidators class FontValidator(_plotly_utils.basevalidators.CompoundValidator): def
(self, plotly_name="font", parent_name="box.hoverlabel", **kwargs): super(FontValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Font"), data_docs=kwargs.pop( "data_docs", """ color colorsrc Sets the source reference on Chart Studio Cloud for color . family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". familysrc Sets the source reference on Chart Studio Cloud for family . size sizesrc Sets the source reference on Chart Studio Cloud for size . """, ), **kwargs )
__init__
identifier_name
_font.py
import _plotly_utils.basevalidators class FontValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="font", parent_name="box.hoverlabel", **kwargs): super(FontValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Font"), data_docs=kwargs.pop( "data_docs", """ color colorsrc
for color . family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". familysrc Sets the source reference on Chart Studio Cloud for family . size sizesrc Sets the source reference on Chart Studio Cloud for size . """, ), **kwargs )
Sets the source reference on Chart Studio Cloud
random_line_split
_font.py
import _plotly_utils.basevalidators class FontValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="font", parent_name="box.hoverlabel", **kwargs):
super(FontValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Font"), data_docs=kwargs.pop( "data_docs", """ color colorsrc Sets the source reference on Chart Studio Cloud for color . family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". familysrc Sets the source reference on Chart Studio Cloud for family . size sizesrc Sets the source reference on Chart Studio Cloud for size . """, ), **kwargs )
identifier_body
sensor-threat-triage.module.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you 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 { NgModule } from '@angular/core'; import {SharedModule} from '../../shared/shared.module'; import {SensorThreatTriageComponent} from './sensor-threat-triage.component';
@NgModule ({ imports: [ SharedModule, SensorRuleEditorModule ], declarations: [ SensorThreatTriageComponent ], exports: [ SensorThreatTriageComponent ] }) export class SensorThreatTriageModule {}
import {SensorRuleEditorModule} from './rule-editor/sensor-rule-editor.module';
random_line_split
sensor-threat-triage.module.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you 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 { NgModule } from '@angular/core'; import {SharedModule} from '../../shared/shared.module'; import {SensorThreatTriageComponent} from './sensor-threat-triage.component'; import {SensorRuleEditorModule} from './rule-editor/sensor-rule-editor.module'; @NgModule ({ imports: [ SharedModule, SensorRuleEditorModule ], declarations: [ SensorThreatTriageComponent ], exports: [ SensorThreatTriageComponent ] }) export class
{}
SensorThreatTriageModule
identifier_name
connectToStore.tsx
import * as React from 'react' import {Component, ComponentClass, createElement} from 'react' import * as PropTypes from 'prop-types' import {connect} from 'react-redux'
function connectToStore<P>(component:ComponentClass<P>):ComponentClass<P> { type PS = P & {store:Store} const mapStateToProps = (state:ComputedState, ownProps:PS):P => ({ ...Object(ownProps), ...state }) const WrappedComponent = (props:P) => createElement(component, props) const ConnectedComponent = connect(mapStateToProps)(WrappedComponent) return class ConnectToStore extends Component<P, any> { static contextTypes = { rrnhStore: PropTypes.object.isRequired } render() { const {rrnhStore} = this.context return <ConnectedComponent store={rrnhStore} {...this.props} /> } } } export default connectToStore
import {Store} from '../store' import ComputedState from '../model/ComputedState'
random_line_split
connectToStore.tsx
import * as React from 'react' import {Component, ComponentClass, createElement} from 'react' import * as PropTypes from 'prop-types' import {connect} from 'react-redux' import {Store} from '../store' import ComputedState from '../model/ComputedState' function connectToStore<P>(component:ComponentClass<P>):ComponentClass<P>
export default connectToStore
{ type PS = P & {store:Store} const mapStateToProps = (state:ComputedState, ownProps:PS):P => ({ ...Object(ownProps), ...state }) const WrappedComponent = (props:P) => createElement(component, props) const ConnectedComponent = connect(mapStateToProps)(WrappedComponent) return class ConnectToStore extends Component<P, any> { static contextTypes = { rrnhStore: PropTypes.object.isRequired } render() { const {rrnhStore} = this.context return <ConnectedComponent store={rrnhStore} {...this.props} /> } } }
identifier_body
connectToStore.tsx
import * as React from 'react' import {Component, ComponentClass, createElement} from 'react' import * as PropTypes from 'prop-types' import {connect} from 'react-redux' import {Store} from '../store' import ComputedState from '../model/ComputedState' function connectToStore<P>(component:ComponentClass<P>):ComponentClass<P> { type PS = P & {store:Store} const mapStateToProps = (state:ComputedState, ownProps:PS):P => ({ ...Object(ownProps), ...state }) const WrappedComponent = (props:P) => createElement(component, props) const ConnectedComponent = connect(mapStateToProps)(WrappedComponent) return class ConnectToStore extends Component<P, any> { static contextTypes = { rrnhStore: PropTypes.object.isRequired }
() { const {rrnhStore} = this.context return <ConnectedComponent store={rrnhStore} {...this.props} /> } } } export default connectToStore
render
identifier_name
PRESUBMIT.py
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for changes affecting tools/perf/. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools. """ import os import re import sys def _CommonChecks(input_api, output_api):
def _CheckWprShaFiles(input_api, output_api): """Check whether the wpr sha files have matching URLs.""" from catapult_base import cloud_storage results = [] for affected_file in input_api.AffectedFiles(include_deletes=False): filename = affected_file.AbsoluteLocalPath() if not filename.endswith('wpr.sha1'): continue expected_hash = cloud_storage.ReadHash(filename) is_wpr_file_uploaded = any( cloud_storage.Exists(bucket, expected_hash) for bucket in cloud_storage.BUCKET_ALIASES.itervalues()) if not is_wpr_file_uploaded: wpr_filename = filename[:-5] results.append(output_api.PresubmitError( 'The file matching %s is not in Cloud Storage yet.\n' 'You can upload your new WPR archive file with the command:\n' 'depot_tools/upload_to_google_storage.py --bucket ' '<Your pageset\'s bucket> %s.\nFor more info: see ' 'http://www.chromium.org/developers/telemetry/' 'record_a_page_set#TOC-Upload-the-recording-to-Cloud-Storage' % (filename, wpr_filename))) return results def _CheckJson(input_api, output_api): """Checks whether JSON files in this change can be parsed.""" for affected_file in input_api.AffectedFiles(include_deletes=False): filename = affected_file.AbsoluteLocalPath() if os.path.splitext(filename)[1] != '.json': continue try: input_api.json.load(open(filename)) except ValueError: return [output_api.PresubmitError('Error parsing JSON in %s!' % filename)] return [] def CheckChangeOnUpload(input_api, output_api): report = [] report.extend(_CommonChecks(input_api, output_api)) return report def CheckChangeOnCommit(input_api, output_api): report = [] report.extend(_CommonChecks(input_api, output_api)) return report def _IsBenchmarksModified(change): """Checks whether CL contains any modification to Telemetry benchmarks.""" for affected_file in change.AffectedFiles(): affected_file_path = affected_file.LocalPath() file_path, _ = os.path.splitext(affected_file_path) if (os.path.join('tools', 'perf', 'benchmarks') in file_path or os.path.join('tools', 'perf', 'measurements') in file_path): return True return False def PostUploadHook(cl, change, output_api): """git cl upload will call this hook after the issue is created/modified. This hook adds extra try bots list to the CL description in order to run Telemetry benchmarks on Perf trybots in addtion to CQ trybots if the CL contains any changes to Telemetry benchmarks. """ benchmarks_modified = _IsBenchmarksModified(change) rietveld_obj = cl.RpcServer() issue = cl.issue original_description = rietveld_obj.get_description(issue) if not benchmarks_modified or re.search( r'^CQ_EXTRA_TRYBOTS=.*', original_description, re.M | re.I): return [] results = [] bots = [ 'linux_perf_bisect', 'mac_perf_bisect', 'win_perf_bisect', 'android_nexus5_perf_bisect' ] bots = ['tryserver.chromium.perf:%s' % s for s in bots] bots_string = ';'.join(bots) description = original_description description += '\nCQ_EXTRA_TRYBOTS=%s' % bots_string results.append(output_api.PresubmitNotifyResult( 'Automatically added Perf trybots to run Telemetry benchmarks on CQ.')) if description != original_description: rietveld_obj.update_description(issue, description) return results
"""Performs common checks, which includes running pylint.""" results = [] old_sys_path = sys.path try: # Modules in tools/perf depend on telemetry. sys.path = [os.path.join(os.pardir, 'telemetry')] + sys.path results.extend(input_api.canned_checks.RunPylint( input_api, output_api, black_list=[], pylintrc='pylintrc')) results.extend(_CheckJson(input_api, output_api)) results.extend(_CheckWprShaFiles(input_api, output_api)) finally: sys.path = old_sys_path return results
identifier_body
PRESUBMIT.py
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for changes affecting tools/perf/. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools. """ import os import re import sys def _CommonChecks(input_api, output_api): """Performs common checks, which includes running pylint.""" results = [] old_sys_path = sys.path try: # Modules in tools/perf depend on telemetry. sys.path = [os.path.join(os.pardir, 'telemetry')] + sys.path results.extend(input_api.canned_checks.RunPylint( input_api, output_api, black_list=[], pylintrc='pylintrc')) results.extend(_CheckJson(input_api, output_api)) results.extend(_CheckWprShaFiles(input_api, output_api)) finally: sys.path = old_sys_path return results def _CheckWprShaFiles(input_api, output_api): """Check whether the wpr sha files have matching URLs.""" from catapult_base import cloud_storage results = [] for affected_file in input_api.AffectedFiles(include_deletes=False): filename = affected_file.AbsoluteLocalPath() if not filename.endswith('wpr.sha1'):
expected_hash = cloud_storage.ReadHash(filename) is_wpr_file_uploaded = any( cloud_storage.Exists(bucket, expected_hash) for bucket in cloud_storage.BUCKET_ALIASES.itervalues()) if not is_wpr_file_uploaded: wpr_filename = filename[:-5] results.append(output_api.PresubmitError( 'The file matching %s is not in Cloud Storage yet.\n' 'You can upload your new WPR archive file with the command:\n' 'depot_tools/upload_to_google_storage.py --bucket ' '<Your pageset\'s bucket> %s.\nFor more info: see ' 'http://www.chromium.org/developers/telemetry/' 'record_a_page_set#TOC-Upload-the-recording-to-Cloud-Storage' % (filename, wpr_filename))) return results def _CheckJson(input_api, output_api): """Checks whether JSON files in this change can be parsed.""" for affected_file in input_api.AffectedFiles(include_deletes=False): filename = affected_file.AbsoluteLocalPath() if os.path.splitext(filename)[1] != '.json': continue try: input_api.json.load(open(filename)) except ValueError: return [output_api.PresubmitError('Error parsing JSON in %s!' % filename)] return [] def CheckChangeOnUpload(input_api, output_api): report = [] report.extend(_CommonChecks(input_api, output_api)) return report def CheckChangeOnCommit(input_api, output_api): report = [] report.extend(_CommonChecks(input_api, output_api)) return report def _IsBenchmarksModified(change): """Checks whether CL contains any modification to Telemetry benchmarks.""" for affected_file in change.AffectedFiles(): affected_file_path = affected_file.LocalPath() file_path, _ = os.path.splitext(affected_file_path) if (os.path.join('tools', 'perf', 'benchmarks') in file_path or os.path.join('tools', 'perf', 'measurements') in file_path): return True return False def PostUploadHook(cl, change, output_api): """git cl upload will call this hook after the issue is created/modified. This hook adds extra try bots list to the CL description in order to run Telemetry benchmarks on Perf trybots in addtion to CQ trybots if the CL contains any changes to Telemetry benchmarks. """ benchmarks_modified = _IsBenchmarksModified(change) rietveld_obj = cl.RpcServer() issue = cl.issue original_description = rietveld_obj.get_description(issue) if not benchmarks_modified or re.search( r'^CQ_EXTRA_TRYBOTS=.*', original_description, re.M | re.I): return [] results = [] bots = [ 'linux_perf_bisect', 'mac_perf_bisect', 'win_perf_bisect', 'android_nexus5_perf_bisect' ] bots = ['tryserver.chromium.perf:%s' % s for s in bots] bots_string = ';'.join(bots) description = original_description description += '\nCQ_EXTRA_TRYBOTS=%s' % bots_string results.append(output_api.PresubmitNotifyResult( 'Automatically added Perf trybots to run Telemetry benchmarks on CQ.')) if description != original_description: rietveld_obj.update_description(issue, description) return results
continue
conditional_block
PRESUBMIT.py
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for changes affecting tools/perf/. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools. """ import os import re import sys def _CommonChecks(input_api, output_api): """Performs common checks, which includes running pylint.""" results = [] old_sys_path = sys.path try: # Modules in tools/perf depend on telemetry. sys.path = [os.path.join(os.pardir, 'telemetry')] + sys.path results.extend(input_api.canned_checks.RunPylint( input_api, output_api, black_list=[], pylintrc='pylintrc')) results.extend(_CheckJson(input_api, output_api)) results.extend(_CheckWprShaFiles(input_api, output_api)) finally: sys.path = old_sys_path return results def _CheckWprShaFiles(input_api, output_api): """Check whether the wpr sha files have matching URLs.""" from catapult_base import cloud_storage results = [] for affected_file in input_api.AffectedFiles(include_deletes=False): filename = affected_file.AbsoluteLocalPath() if not filename.endswith('wpr.sha1'): continue expected_hash = cloud_storage.ReadHash(filename) is_wpr_file_uploaded = any( cloud_storage.Exists(bucket, expected_hash) for bucket in cloud_storage.BUCKET_ALIASES.itervalues()) if not is_wpr_file_uploaded: wpr_filename = filename[:-5] results.append(output_api.PresubmitError( 'The file matching %s is not in Cloud Storage yet.\n' 'You can upload your new WPR archive file with the command:\n' 'depot_tools/upload_to_google_storage.py --bucket ' '<Your pageset\'s bucket> %s.\nFor more info: see ' 'http://www.chromium.org/developers/telemetry/' 'record_a_page_set#TOC-Upload-the-recording-to-Cloud-Storage' % (filename, wpr_filename))) return results def _CheckJson(input_api, output_api): """Checks whether JSON files in this change can be parsed.""" for affected_file in input_api.AffectedFiles(include_deletes=False): filename = affected_file.AbsoluteLocalPath() if os.path.splitext(filename)[1] != '.json': continue try: input_api.json.load(open(filename)) except ValueError: return [output_api.PresubmitError('Error parsing JSON in %s!' % filename)] return [] def CheckChangeOnUpload(input_api, output_api): report = [] report.extend(_CommonChecks(input_api, output_api)) return report def CheckChangeOnCommit(input_api, output_api): report = [] report.extend(_CommonChecks(input_api, output_api)) return report def _IsBenchmarksModified(change): """Checks whether CL contains any modification to Telemetry benchmarks.""" for affected_file in change.AffectedFiles(): affected_file_path = affected_file.LocalPath() file_path, _ = os.path.splitext(affected_file_path) if (os.path.join('tools', 'perf', 'benchmarks') in file_path or os.path.join('tools', 'perf', 'measurements') in file_path): return True return False def PostUploadHook(cl, change, output_api): """git cl upload will call this hook after the issue is created/modified.
benchmarks_modified = _IsBenchmarksModified(change) rietveld_obj = cl.RpcServer() issue = cl.issue original_description = rietveld_obj.get_description(issue) if not benchmarks_modified or re.search( r'^CQ_EXTRA_TRYBOTS=.*', original_description, re.M | re.I): return [] results = [] bots = [ 'linux_perf_bisect', 'mac_perf_bisect', 'win_perf_bisect', 'android_nexus5_perf_bisect' ] bots = ['tryserver.chromium.perf:%s' % s for s in bots] bots_string = ';'.join(bots) description = original_description description += '\nCQ_EXTRA_TRYBOTS=%s' % bots_string results.append(output_api.PresubmitNotifyResult( 'Automatically added Perf trybots to run Telemetry benchmarks on CQ.')) if description != original_description: rietveld_obj.update_description(issue, description) return results
This hook adds extra try bots list to the CL description in order to run Telemetry benchmarks on Perf trybots in addtion to CQ trybots if the CL contains any changes to Telemetry benchmarks. """
random_line_split
PRESUBMIT.py
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for changes affecting tools/perf/. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools. """ import os import re import sys def _CommonChecks(input_api, output_api): """Performs common checks, which includes running pylint.""" results = [] old_sys_path = sys.path try: # Modules in tools/perf depend on telemetry. sys.path = [os.path.join(os.pardir, 'telemetry')] + sys.path results.extend(input_api.canned_checks.RunPylint( input_api, output_api, black_list=[], pylintrc='pylintrc')) results.extend(_CheckJson(input_api, output_api)) results.extend(_CheckWprShaFiles(input_api, output_api)) finally: sys.path = old_sys_path return results def _CheckWprShaFiles(input_api, output_api): """Check whether the wpr sha files have matching URLs.""" from catapult_base import cloud_storage results = [] for affected_file in input_api.AffectedFiles(include_deletes=False): filename = affected_file.AbsoluteLocalPath() if not filename.endswith('wpr.sha1'): continue expected_hash = cloud_storage.ReadHash(filename) is_wpr_file_uploaded = any( cloud_storage.Exists(bucket, expected_hash) for bucket in cloud_storage.BUCKET_ALIASES.itervalues()) if not is_wpr_file_uploaded: wpr_filename = filename[:-5] results.append(output_api.PresubmitError( 'The file matching %s is not in Cloud Storage yet.\n' 'You can upload your new WPR archive file with the command:\n' 'depot_tools/upload_to_google_storage.py --bucket ' '<Your pageset\'s bucket> %s.\nFor more info: see ' 'http://www.chromium.org/developers/telemetry/' 'record_a_page_set#TOC-Upload-the-recording-to-Cloud-Storage' % (filename, wpr_filename))) return results def _CheckJson(input_api, output_api): """Checks whether JSON files in this change can be parsed.""" for affected_file in input_api.AffectedFiles(include_deletes=False): filename = affected_file.AbsoluteLocalPath() if os.path.splitext(filename)[1] != '.json': continue try: input_api.json.load(open(filename)) except ValueError: return [output_api.PresubmitError('Error parsing JSON in %s!' % filename)] return [] def CheckChangeOnUpload(input_api, output_api): report = [] report.extend(_CommonChecks(input_api, output_api)) return report def
(input_api, output_api): report = [] report.extend(_CommonChecks(input_api, output_api)) return report def _IsBenchmarksModified(change): """Checks whether CL contains any modification to Telemetry benchmarks.""" for affected_file in change.AffectedFiles(): affected_file_path = affected_file.LocalPath() file_path, _ = os.path.splitext(affected_file_path) if (os.path.join('tools', 'perf', 'benchmarks') in file_path or os.path.join('tools', 'perf', 'measurements') in file_path): return True return False def PostUploadHook(cl, change, output_api): """git cl upload will call this hook after the issue is created/modified. This hook adds extra try bots list to the CL description in order to run Telemetry benchmarks on Perf trybots in addtion to CQ trybots if the CL contains any changes to Telemetry benchmarks. """ benchmarks_modified = _IsBenchmarksModified(change) rietveld_obj = cl.RpcServer() issue = cl.issue original_description = rietveld_obj.get_description(issue) if not benchmarks_modified or re.search( r'^CQ_EXTRA_TRYBOTS=.*', original_description, re.M | re.I): return [] results = [] bots = [ 'linux_perf_bisect', 'mac_perf_bisect', 'win_perf_bisect', 'android_nexus5_perf_bisect' ] bots = ['tryserver.chromium.perf:%s' % s for s in bots] bots_string = ';'.join(bots) description = original_description description += '\nCQ_EXTRA_TRYBOTS=%s' % bots_string results.append(output_api.PresubmitNotifyResult( 'Automatically added Perf trybots to run Telemetry benchmarks on CQ.')) if description != original_description: rietveld_obj.update_description(issue, description) return results
CheckChangeOnCommit
identifier_name
simpleDataTable.ts
/** * @module DataTable */ module DataTable { export class SimpleDataTable { public restrict = 'A'; public scope = { config: '=hawtioSimpleTable', target: '@', showFiles: '@' }; public link:(scope, element, attrs) => any; constructor(public $compile) { // necessary to ensure 'this' is this object <sigh> this.link = ($scope, $element, $attrs) => { return this.doLink($scope, $element, $attrs); } } private
($scope, $element, $attrs) { var defaultPrimaryKeyFn = (entity, idx) => { // default function to use id/_id/name as primary key, and fallback to use index return entity["id"] || entity["_id"] || entity["name"] || idx; }; var config = $scope.config; var dataName = config.data || "data"; // need to remember which rows has been selected as the config.data / config.selectedItems // so we can re-select them when data is changed/updated, and entity may be new instances // so we need a primary key function to generate a 'primary key' of the entity var primaryKeyFn = config.primaryKeyFn || defaultPrimaryKeyFn; $scope.rows = []; var scope = $scope.$parent || $scope; var listener = (otherValue) => { var value = Core.pathGet(scope, dataName); if (value && !angular.isArray(value)) { value = [value]; Core.pathSet(scope, dataName, value); } if (!('sortInfo' in config)) { // an optional defaultSort can be used to indicate a column // should not automatic be the default sort var ds = config.columnDefs.first()['defaultSort']; var sortField; if (angular.isUndefined(ds) || ds === true) { sortField = config.columnDefs.first()['field']; } else { sortField = config.columnDefs.slice(1).first()['field'] } config['sortInfo'] = { sortBy: sortField, ascending: true } } var sortInfo = $scope.config.sortInfo; // enrich the rows with information about their index var idx = -1; $scope.rows = (value || []).sortBy(sortInfo.sortBy, !sortInfo.ascending).map(entity => { idx++; return { entity: entity, index: idx, getProperty: (name) => { return entity[name]; } }; }); Core.pathSet(scope, ['hawtioSimpleTable', dataName, 'rows'], $scope.rows); // okay the data was changed/updated so we need to re-select previously selected items // and for that we need to evaluate the primary key function so we can match new data with old data. var reSelectedItems = []; $scope.rows.forEach((row, idx) => { var rpk = primaryKeyFn(row.entity, row.index); var selected = config.selectedItems.some(s => { var spk = primaryKeyFn(s, s.index); return angular.equals(rpk, spk); }); if (selected) { // need to enrich entity with index, as we push row.entity to the re-selected items row.entity.index = row.index; reSelectedItems.push(row.entity); log.debug("Data changed so keep selecting row at index " + row.index); } }); config.selectedItems = reSelectedItems; }; scope.$watch(dataName, listener); // lets add a separate event so we can force updates // if we find cases where the delta logic doesn't work // (such as for nested hawtioinput-input-table) scope.$on("hawtio.datatable." + dataName, listener); function getSelectionArray() { var selectionArray = config.selectedItems; if (!selectionArray) { selectionArray = []; config.selectedItems = selectionArray; } if (angular.isString(selectionArray)) { var name = selectionArray; selectionArray = Core.pathGet(scope, name); if (!selectionArray) { selectionArray = []; scope[name] = selectionArray; } } return selectionArray; } function isMultiSelect() { var multiSelect = $scope.config.multiSelect; if (angular.isUndefined(multiSelect)) { multiSelect = true; } return multiSelect; } $scope.toggleAllSelections = () => { var allRowsSelected = $scope.config.allRowsSelected; var newFlag = allRowsSelected; var selectionArray = getSelectionArray(); selectionArray.splice(0, selectionArray.length); angular.forEach($scope.rows, (row) => { row.selected = newFlag; if (allRowsSelected) { selectionArray.push(row.entity); } }); }; $scope.toggleRowSelection = (row) => { if (row) { var selectionArray = getSelectionArray(); if (!isMultiSelect()) { // lets clear all other selections selectionArray.splice(0, selectionArray.length); angular.forEach($scope.rows, (r) => { if (r !== row) { r.selected = false; } }); } var entity = row.entity; if (entity) { var idx = selectionArray.indexOf(entity); if (row.selected) { if (idx < 0) { selectionArray.push(entity); } } else { // clear the all selected checkbox $scope.config.allRowsSelected = false; if (idx >= 0) { selectionArray.splice(idx, 1); } } } } }; $scope.sortBy = (field) => { if ($scope.config.sortInfo.sortBy === field) { $scope.config.sortInfo.ascending = !$scope.config.sortInfo.ascending; } else { $scope.config.sortInfo.sortBy = field; $scope.config.sortInfo.ascending = true; } $scope.$emit("hawtio.datatable." + dataName); }; $scope.getClass = (field) => { if ('sortInfo' in $scope.config) { if ($scope.config.sortInfo.sortBy === field) { if ($scope.config.sortInfo.ascending) { return 'asc'; } else { return 'desc'; } } } return ''; }; $scope.showRow = (row) => { var filter = Core.pathGet($scope, ['config', 'filterOptions', 'filterText']); if (Core.isBlank(filter)) { return true; } var rowJson = angular.toJson(row); return rowJson.toLowerCase().has(filter.toLowerCase()); }; $scope.isSelected = (row) => { return config.selectedItems.some(row.entity); }; $scope.onRowSelected = (row) => { var idx = config.selectedItems.indexOf(row.entity); if (idx >= 0) { log.debug("De-selecting row at index " + row.index); config.selectedItems.splice(idx, 1); } else { if (!config.multiSelect) { config.selectedItems = []; } log.debug("Selecting row at index " + row.index); // need to enrich entity with index, as we push row.entity to the selected items row.entity.index = row.index; config.selectedItems.push(row.entity); } }; // lets add the header and row cells var rootElement = $element; rootElement.empty(); var showCheckBox = firstValueDefined(config, ["showSelectionCheckbox", "displaySelectionCheckbox"], true); var enableRowClickSelection = firstValueDefined(config, ["enableRowClickSelection"], false); var onMouseDown; if (enableRowClickSelection) { onMouseDown = "ng-mousedown='onRowSelected(row)' "; } else { onMouseDown = ""; } var headHtml = "<thead><tr>"; // use a function to check if a row is selected so the UI can be kept up to date asap var bodyHtml = "<tbody><tr ng-repeat='row in rows track by $index' ng-show='showRow(row)' " + onMouseDown + "ng-class=\"{'selected': isSelected(row)}\" >"; var idx = 0; if (showCheckBox) { var toggleAllHtml = isMultiSelect() ? "<input type='checkbox' ng-show='rows.length' ng-model='config.allRowsSelected' ng-change='toggleAllSelections()'>" : ""; headHtml += "\n<th>" + toggleAllHtml + "</th>" bodyHtml += "\n<td><input type='checkbox' ng-model='row.selected' ng-change='toggleRowSelection(row)'></td>" } angular.forEach(config.columnDefs, (colDef) => { var field = colDef.field; var cellTemplate = colDef.cellTemplate || '<div class="ngCellText" title="{{row.entity.' + field + '}}">{{row.entity.' + field + '}}</div>'; headHtml += "\n<th class='clickable no-fade table-header' ng-click=\"sortBy('" + field + "')\" ng-class=\"getClass('" + field + "')\">{{config.columnDefs[" + idx + "].displayName}}<span class='indicator'></span></th>" bodyHtml += "\n<td>" + cellTemplate + "</td>" idx += 1; }); var html = headHtml + "\n</tr></thead>\n" + bodyHtml + "\n</tr></tbody>"; var newContent = this.$compile(html)($scope); rootElement.html(newContent); } } /** * Returns the first property value defined in the given object or the default value if none are defined * * @param object the object to look for properties * @param names the array of property names to look for * @param defaultValue the value if no property values are defined * @return {*} the first defined property value or the defaultValue if none are defined */ function firstValueDefined(object, names, defaultValue) { var answer = defaultValue; var found = false; angular.forEach(names, (name) => { var value = object[name]; if (!found && angular.isDefined(value)) { answer = value; found = true; } }); return answer; } }
doLink
identifier_name
simpleDataTable.ts
/** * @module DataTable */ module DataTable { export class SimpleDataTable { public restrict = 'A'; public scope = { config: '=hawtioSimpleTable', target: '@', showFiles: '@' }; public link:(scope, element, attrs) => any; constructor(public $compile) { // necessary to ensure 'this' is this object <sigh> this.link = ($scope, $element, $attrs) => { return this.doLink($scope, $element, $attrs); } } private doLink($scope, $element, $attrs) { var defaultPrimaryKeyFn = (entity, idx) => { // default function to use id/_id/name as primary key, and fallback to use index return entity["id"] || entity["_id"] || entity["name"] || idx; }; var config = $scope.config; var dataName = config.data || "data"; // need to remember which rows has been selected as the config.data / config.selectedItems // so we can re-select them when data is changed/updated, and entity may be new instances // so we need a primary key function to generate a 'primary key' of the entity var primaryKeyFn = config.primaryKeyFn || defaultPrimaryKeyFn; $scope.rows = []; var scope = $scope.$parent || $scope; var listener = (otherValue) => { var value = Core.pathGet(scope, dataName); if (value && !angular.isArray(value)) { value = [value]; Core.pathSet(scope, dataName, value); } if (!('sortInfo' in config)) { // an optional defaultSort can be used to indicate a column // should not automatic be the default sort var ds = config.columnDefs.first()['defaultSort']; var sortField; if (angular.isUndefined(ds) || ds === true) { sortField = config.columnDefs.first()['field']; } else { sortField = config.columnDefs.slice(1).first()['field'] } config['sortInfo'] = { sortBy: sortField, ascending: true } } var sortInfo = $scope.config.sortInfo; // enrich the rows with information about their index var idx = -1; $scope.rows = (value || []).sortBy(sortInfo.sortBy, !sortInfo.ascending).map(entity => { idx++; return { entity: entity, index: idx, getProperty: (name) => { return entity[name]; } }; }); Core.pathSet(scope, ['hawtioSimpleTable', dataName, 'rows'], $scope.rows); // okay the data was changed/updated so we need to re-select previously selected items // and for that we need to evaluate the primary key function so we can match new data with old data. var reSelectedItems = []; $scope.rows.forEach((row, idx) => { var rpk = primaryKeyFn(row.entity, row.index);
var spk = primaryKeyFn(s, s.index); return angular.equals(rpk, spk); }); if (selected) { // need to enrich entity with index, as we push row.entity to the re-selected items row.entity.index = row.index; reSelectedItems.push(row.entity); log.debug("Data changed so keep selecting row at index " + row.index); } }); config.selectedItems = reSelectedItems; }; scope.$watch(dataName, listener); // lets add a separate event so we can force updates // if we find cases where the delta logic doesn't work // (such as for nested hawtioinput-input-table) scope.$on("hawtio.datatable." + dataName, listener); function getSelectionArray() { var selectionArray = config.selectedItems; if (!selectionArray) { selectionArray = []; config.selectedItems = selectionArray; } if (angular.isString(selectionArray)) { var name = selectionArray; selectionArray = Core.pathGet(scope, name); if (!selectionArray) { selectionArray = []; scope[name] = selectionArray; } } return selectionArray; } function isMultiSelect() { var multiSelect = $scope.config.multiSelect; if (angular.isUndefined(multiSelect)) { multiSelect = true; } return multiSelect; } $scope.toggleAllSelections = () => { var allRowsSelected = $scope.config.allRowsSelected; var newFlag = allRowsSelected; var selectionArray = getSelectionArray(); selectionArray.splice(0, selectionArray.length); angular.forEach($scope.rows, (row) => { row.selected = newFlag; if (allRowsSelected) { selectionArray.push(row.entity); } }); }; $scope.toggleRowSelection = (row) => { if (row) { var selectionArray = getSelectionArray(); if (!isMultiSelect()) { // lets clear all other selections selectionArray.splice(0, selectionArray.length); angular.forEach($scope.rows, (r) => { if (r !== row) { r.selected = false; } }); } var entity = row.entity; if (entity) { var idx = selectionArray.indexOf(entity); if (row.selected) { if (idx < 0) { selectionArray.push(entity); } } else { // clear the all selected checkbox $scope.config.allRowsSelected = false; if (idx >= 0) { selectionArray.splice(idx, 1); } } } } }; $scope.sortBy = (field) => { if ($scope.config.sortInfo.sortBy === field) { $scope.config.sortInfo.ascending = !$scope.config.sortInfo.ascending; } else { $scope.config.sortInfo.sortBy = field; $scope.config.sortInfo.ascending = true; } $scope.$emit("hawtio.datatable." + dataName); }; $scope.getClass = (field) => { if ('sortInfo' in $scope.config) { if ($scope.config.sortInfo.sortBy === field) { if ($scope.config.sortInfo.ascending) { return 'asc'; } else { return 'desc'; } } } return ''; }; $scope.showRow = (row) => { var filter = Core.pathGet($scope, ['config', 'filterOptions', 'filterText']); if (Core.isBlank(filter)) { return true; } var rowJson = angular.toJson(row); return rowJson.toLowerCase().has(filter.toLowerCase()); }; $scope.isSelected = (row) => { return config.selectedItems.some(row.entity); }; $scope.onRowSelected = (row) => { var idx = config.selectedItems.indexOf(row.entity); if (idx >= 0) { log.debug("De-selecting row at index " + row.index); config.selectedItems.splice(idx, 1); } else { if (!config.multiSelect) { config.selectedItems = []; } log.debug("Selecting row at index " + row.index); // need to enrich entity with index, as we push row.entity to the selected items row.entity.index = row.index; config.selectedItems.push(row.entity); } }; // lets add the header and row cells var rootElement = $element; rootElement.empty(); var showCheckBox = firstValueDefined(config, ["showSelectionCheckbox", "displaySelectionCheckbox"], true); var enableRowClickSelection = firstValueDefined(config, ["enableRowClickSelection"], false); var onMouseDown; if (enableRowClickSelection) { onMouseDown = "ng-mousedown='onRowSelected(row)' "; } else { onMouseDown = ""; } var headHtml = "<thead><tr>"; // use a function to check if a row is selected so the UI can be kept up to date asap var bodyHtml = "<tbody><tr ng-repeat='row in rows track by $index' ng-show='showRow(row)' " + onMouseDown + "ng-class=\"{'selected': isSelected(row)}\" >"; var idx = 0; if (showCheckBox) { var toggleAllHtml = isMultiSelect() ? "<input type='checkbox' ng-show='rows.length' ng-model='config.allRowsSelected' ng-change='toggleAllSelections()'>" : ""; headHtml += "\n<th>" + toggleAllHtml + "</th>" bodyHtml += "\n<td><input type='checkbox' ng-model='row.selected' ng-change='toggleRowSelection(row)'></td>" } angular.forEach(config.columnDefs, (colDef) => { var field = colDef.field; var cellTemplate = colDef.cellTemplate || '<div class="ngCellText" title="{{row.entity.' + field + '}}">{{row.entity.' + field + '}}</div>'; headHtml += "\n<th class='clickable no-fade table-header' ng-click=\"sortBy('" + field + "')\" ng-class=\"getClass('" + field + "')\">{{config.columnDefs[" + idx + "].displayName}}<span class='indicator'></span></th>" bodyHtml += "\n<td>" + cellTemplate + "</td>" idx += 1; }); var html = headHtml + "\n</tr></thead>\n" + bodyHtml + "\n</tr></tbody>"; var newContent = this.$compile(html)($scope); rootElement.html(newContent); } } /** * Returns the first property value defined in the given object or the default value if none are defined * * @param object the object to look for properties * @param names the array of property names to look for * @param defaultValue the value if no property values are defined * @return {*} the first defined property value or the defaultValue if none are defined */ function firstValueDefined(object, names, defaultValue) { var answer = defaultValue; var found = false; angular.forEach(names, (name) => { var value = object[name]; if (!found && angular.isDefined(value)) { answer = value; found = true; } }); return answer; } }
var selected = config.selectedItems.some(s => {
random_line_split
simpleDataTable.ts
/** * @module DataTable */ module DataTable { export class SimpleDataTable { public restrict = 'A'; public scope = { config: '=hawtioSimpleTable', target: '@', showFiles: '@' }; public link:(scope, element, attrs) => any; constructor(public $compile) { // necessary to ensure 'this' is this object <sigh> this.link = ($scope, $element, $attrs) => { return this.doLink($scope, $element, $attrs); } } private doLink($scope, $element, $attrs) { var defaultPrimaryKeyFn = (entity, idx) => { // default function to use id/_id/name as primary key, and fallback to use index return entity["id"] || entity["_id"] || entity["name"] || idx; }; var config = $scope.config; var dataName = config.data || "data"; // need to remember which rows has been selected as the config.data / config.selectedItems // so we can re-select them when data is changed/updated, and entity may be new instances // so we need a primary key function to generate a 'primary key' of the entity var primaryKeyFn = config.primaryKeyFn || defaultPrimaryKeyFn; $scope.rows = []; var scope = $scope.$parent || $scope; var listener = (otherValue) => { var value = Core.pathGet(scope, dataName); if (value && !angular.isArray(value)) { value = [value]; Core.pathSet(scope, dataName, value); } if (!('sortInfo' in config)) { // an optional defaultSort can be used to indicate a column // should not automatic be the default sort var ds = config.columnDefs.first()['defaultSort']; var sortField; if (angular.isUndefined(ds) || ds === true) { sortField = config.columnDefs.first()['field']; } else { sortField = config.columnDefs.slice(1).first()['field'] } config['sortInfo'] = { sortBy: sortField, ascending: true } } var sortInfo = $scope.config.sortInfo; // enrich the rows with information about their index var idx = -1; $scope.rows = (value || []).sortBy(sortInfo.sortBy, !sortInfo.ascending).map(entity => { idx++; return { entity: entity, index: idx, getProperty: (name) => { return entity[name]; } }; }); Core.pathSet(scope, ['hawtioSimpleTable', dataName, 'rows'], $scope.rows); // okay the data was changed/updated so we need to re-select previously selected items // and for that we need to evaluate the primary key function so we can match new data with old data. var reSelectedItems = []; $scope.rows.forEach((row, idx) => { var rpk = primaryKeyFn(row.entity, row.index); var selected = config.selectedItems.some(s => { var spk = primaryKeyFn(s, s.index); return angular.equals(rpk, spk); }); if (selected) { // need to enrich entity with index, as we push row.entity to the re-selected items row.entity.index = row.index; reSelectedItems.push(row.entity); log.debug("Data changed so keep selecting row at index " + row.index); } }); config.selectedItems = reSelectedItems; }; scope.$watch(dataName, listener); // lets add a separate event so we can force updates // if we find cases where the delta logic doesn't work // (such as for nested hawtioinput-input-table) scope.$on("hawtio.datatable." + dataName, listener); function getSelectionArray() { var selectionArray = config.selectedItems; if (!selectionArray) { selectionArray = []; config.selectedItems = selectionArray; } if (angular.isString(selectionArray)) { var name = selectionArray; selectionArray = Core.pathGet(scope, name); if (!selectionArray) { selectionArray = []; scope[name] = selectionArray; } } return selectionArray; } function isMultiSelect() { var multiSelect = $scope.config.multiSelect; if (angular.isUndefined(multiSelect)) { multiSelect = true; } return multiSelect; } $scope.toggleAllSelections = () => { var allRowsSelected = $scope.config.allRowsSelected; var newFlag = allRowsSelected; var selectionArray = getSelectionArray(); selectionArray.splice(0, selectionArray.length); angular.forEach($scope.rows, (row) => { row.selected = newFlag; if (allRowsSelected) { selectionArray.push(row.entity); } }); }; $scope.toggleRowSelection = (row) => { if (row) { var selectionArray = getSelectionArray(); if (!isMultiSelect()) { // lets clear all other selections selectionArray.splice(0, selectionArray.length); angular.forEach($scope.rows, (r) => { if (r !== row) { r.selected = false; } }); } var entity = row.entity; if (entity) { var idx = selectionArray.indexOf(entity); if (row.selected) { if (idx < 0) { selectionArray.push(entity); } } else { // clear the all selected checkbox $scope.config.allRowsSelected = false; if (idx >= 0) { selectionArray.splice(idx, 1); } } } } }; $scope.sortBy = (field) => { if ($scope.config.sortInfo.sortBy === field) { $scope.config.sortInfo.ascending = !$scope.config.sortInfo.ascending; } else
$scope.$emit("hawtio.datatable." + dataName); }; $scope.getClass = (field) => { if ('sortInfo' in $scope.config) { if ($scope.config.sortInfo.sortBy === field) { if ($scope.config.sortInfo.ascending) { return 'asc'; } else { return 'desc'; } } } return ''; }; $scope.showRow = (row) => { var filter = Core.pathGet($scope, ['config', 'filterOptions', 'filterText']); if (Core.isBlank(filter)) { return true; } var rowJson = angular.toJson(row); return rowJson.toLowerCase().has(filter.toLowerCase()); }; $scope.isSelected = (row) => { return config.selectedItems.some(row.entity); }; $scope.onRowSelected = (row) => { var idx = config.selectedItems.indexOf(row.entity); if (idx >= 0) { log.debug("De-selecting row at index " + row.index); config.selectedItems.splice(idx, 1); } else { if (!config.multiSelect) { config.selectedItems = []; } log.debug("Selecting row at index " + row.index); // need to enrich entity with index, as we push row.entity to the selected items row.entity.index = row.index; config.selectedItems.push(row.entity); } }; // lets add the header and row cells var rootElement = $element; rootElement.empty(); var showCheckBox = firstValueDefined(config, ["showSelectionCheckbox", "displaySelectionCheckbox"], true); var enableRowClickSelection = firstValueDefined(config, ["enableRowClickSelection"], false); var onMouseDown; if (enableRowClickSelection) { onMouseDown = "ng-mousedown='onRowSelected(row)' "; } else { onMouseDown = ""; } var headHtml = "<thead><tr>"; // use a function to check if a row is selected so the UI can be kept up to date asap var bodyHtml = "<tbody><tr ng-repeat='row in rows track by $index' ng-show='showRow(row)' " + onMouseDown + "ng-class=\"{'selected': isSelected(row)}\" >"; var idx = 0; if (showCheckBox) { var toggleAllHtml = isMultiSelect() ? "<input type='checkbox' ng-show='rows.length' ng-model='config.allRowsSelected' ng-change='toggleAllSelections()'>" : ""; headHtml += "\n<th>" + toggleAllHtml + "</th>" bodyHtml += "\n<td><input type='checkbox' ng-model='row.selected' ng-change='toggleRowSelection(row)'></td>" } angular.forEach(config.columnDefs, (colDef) => { var field = colDef.field; var cellTemplate = colDef.cellTemplate || '<div class="ngCellText" title="{{row.entity.' + field + '}}">{{row.entity.' + field + '}}</div>'; headHtml += "\n<th class='clickable no-fade table-header' ng-click=\"sortBy('" + field + "')\" ng-class=\"getClass('" + field + "')\">{{config.columnDefs[" + idx + "].displayName}}<span class='indicator'></span></th>" bodyHtml += "\n<td>" + cellTemplate + "</td>" idx += 1; }); var html = headHtml + "\n</tr></thead>\n" + bodyHtml + "\n</tr></tbody>"; var newContent = this.$compile(html)($scope); rootElement.html(newContent); } } /** * Returns the first property value defined in the given object or the default value if none are defined * * @param object the object to look for properties * @param names the array of property names to look for * @param defaultValue the value if no property values are defined * @return {*} the first defined property value or the defaultValue if none are defined */ function firstValueDefined(object, names, defaultValue) { var answer = defaultValue; var found = false; angular.forEach(names, (name) => { var value = object[name]; if (!found && angular.isDefined(value)) { answer = value; found = true; } }); return answer; } }
{ $scope.config.sortInfo.sortBy = field; $scope.config.sortInfo.ascending = true; }
conditional_block
redux.js
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["Redux"] = factory(); else root["Redux"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined; var _createStore = __webpack_require__(2); var _createStore2 = _interopRequireDefault(_createStore); var _combineReducers = __webpack_require__(7); var _combineReducers2 = _interopRequireDefault(_combineReducers); var _bindActionCreators = __webpack_require__(6); var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators); var _applyMiddleware = __webpack_require__(5); var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware); var _compose = __webpack_require__(1); var _compose2 = _interopRequireDefault(_compose); var _warning = __webpack_require__(3); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if (("development") !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') { (0, _warning2['default'])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.'); } exports.createStore = _createStore2['default']; exports.combineReducers = _combineReducers2['default']; exports.bindActionCreators = _bindActionCreators2['default']; exports.applyMiddleware = _applyMiddleware2['default']; exports.compose = _compose2['default']; /***/ }, /* 1 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = compose; /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } var last = funcs[funcs.length - 1]; var rest = funcs.slice(0, -1); return function () { return rest.reduceRight(function (composed, f) { return f(composed); }, last.apply(undefined, arguments)); }; } /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.ActionTypes = undefined; exports['default'] = createStore; var _isPlainObject = __webpack_require__(4); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _symbolObservable = __webpack_require__(12); var _symbolObservable2 = _interopRequireDefault(_symbolObservable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var ActionTypes = exports.ActionTypes = { INIT: '@@redux/INIT' }; /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [preloadedState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} enhancer The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ function createStore(reducer, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = preloadedState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.'); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!(0, _isPlainObject2['default'])(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { listeners[i](); } return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/zenparsing/es-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[_symbolObservable2['default']] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[_symbolObservable2['default']] = observable, _ref2; } /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = warning; /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var getPrototype = __webpack_require__(8), isHostObject = __webpack_require__(9), isObjectLike = __webpack_require__(11); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return (typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); } module.exports = isPlainObject; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports['default'] = applyMiddleware; var _compose = __webpack_require__(1); var _compose2 = _interopRequireDefault(_compose); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function (reducer, preloadedState, enhancer) { var store = createStore(reducer, preloadedState, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = _compose2['default'].apply(undefined, chain)(store.dispatch); return _extends({}, store, { dispatch: _dispatch }); }; }; } /***/ }, /* 6 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = bindActionCreators; function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(undefined, arguments)); }; } /** * Turns an object whose values are action creators, into an object with the * same keys, but with every function wrapped into a `dispatch` call so they * may be invoked directly. This is just a convenience method, as you can call * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. * * For convenience, you can also pass a single function as the first argument, * and get a function in return. * * @param {Function|Object} actionCreators An object whose values are action * creator functions. One handy way to obtain it is to use ES6 `import * as` * syntax. You may also pass a single function. * * @param {Function} dispatch The `dispatch` function available on your Redux * store. * * @returns {Function|Object} The object mimicking the original object, but with * every action creator wrapped into the `dispatch` call. If you passed a * function as `actionCreators`, the return value will also be a single * function. */ function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch); } if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'); } var keys = Object.keys(actionCreators); var boundActionCreators = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var actionCreator = actionCreators[key]; if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = combineReducers; var _createStore = __webpack_require__(2); var _isPlainObject = __webpack_require__(4); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _warning = __webpack_require__(3); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.'; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!(0, _isPlainObject2['default'])(inputState)) { return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]; }); unexpectedKeys.forEach(function (key) { unexpectedKeyCache[key] = true; }); if (unexpectedKeys.length > 0) { return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.'); } } function assertReducerSanity(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.'); } var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); if (typeof reducer(undefined, { type: type }) === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.'); } }); } /** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (true) { if (typeof reducers[key] === 'undefined') { (0, _warning2['default'])('No reducer provided for key "' + key + '"'); } } if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); if (true) { var unexpectedKeyCache = {}; } var sanityError; try { assertReducerSanity(finalReducers); } catch (e) { sanityError = e; } return function combination() { var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var action = arguments[1]; if (sanityError) { throw sanityError; } if (true) { var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache); if (warningMessage) { (0, _warning2['default'])(warningMessage); } } var hasChanged = false; var nextState = {}; for (var i = 0; i < finalReducerKeys.length; i++) { var key = finalReducerKeys[i]; var reducer = finalReducers[key]; var previousStateForKey = state[key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(key, action); throw new Error(errorMessage); } nextState[key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; } /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(10); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }, /* 9 */ /***/ function(module, exports) { /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } module.exports = isHostObject; /***/ }, /* 10 */ /***/ function(module, exports) { /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }, /* 11 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0
* * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(13); /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ponyfill = __webpack_require__(14); var _ponyfill2 = _interopRequireDefault(_ponyfill); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var root = undefined; /* global window */ if (typeof global !== 'undefined') { root = global; } else if (typeof window !== 'undefined') { root = window; } var result = (0, _ponyfill2['default'])(root); exports['default'] = result; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 14 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = symbolObservablePonyfill; function symbolObservablePonyfill(root) { var result; var _Symbol = root.Symbol; if (typeof _Symbol === 'function') { if (_Symbol.observable) { result = _Symbol.observable; } else { result = _Symbol('observable'); _Symbol.observable = result; } } else { result = '@@observable'; } return result; }; /***/ } /******/ ]) }); ;
* @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example
random_line_split
redux.js
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["Redux"] = factory(); else root["Redux"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined; var _createStore = __webpack_require__(2); var _createStore2 = _interopRequireDefault(_createStore); var _combineReducers = __webpack_require__(7); var _combineReducers2 = _interopRequireDefault(_combineReducers); var _bindActionCreators = __webpack_require__(6); var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators); var _applyMiddleware = __webpack_require__(5); var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware); var _compose = __webpack_require__(1); var _compose2 = _interopRequireDefault(_compose); var _warning = __webpack_require__(3); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if (("development") !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') { (0, _warning2['default'])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.'); } exports.createStore = _createStore2['default']; exports.combineReducers = _combineReducers2['default']; exports.bindActionCreators = _bindActionCreators2['default']; exports.applyMiddleware = _applyMiddleware2['default']; exports.compose = _compose2['default']; /***/ }, /* 1 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = compose; /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } var last = funcs[funcs.length - 1]; var rest = funcs.slice(0, -1); return function () { return rest.reduceRight(function (composed, f) { return f(composed); }, last.apply(undefined, arguments)); }; } /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.ActionTypes = undefined; exports['default'] = createStore; var _isPlainObject = __webpack_require__(4); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _symbolObservable = __webpack_require__(12); var _symbolObservable2 = _interopRequireDefault(_symbolObservable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var ActionTypes = exports.ActionTypes = { INIT: '@@redux/INIT' }; /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [preloadedState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} enhancer The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ function createStore(reducer, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = preloadedState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.'); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!(0, _isPlainObject2['default'])(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) {
return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/zenparsing/es-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[_symbolObservable2['default']] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[_symbolObservable2['default']] = observable, _ref2; } /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = warning; /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var getPrototype = __webpack_require__(8), isHostObject = __webpack_require__(9), isObjectLike = __webpack_require__(11); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return (typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); } module.exports = isPlainObject; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports['default'] = applyMiddleware; var _compose = __webpack_require__(1); var _compose2 = _interopRequireDefault(_compose); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function (reducer, preloadedState, enhancer) { var store = createStore(reducer, preloadedState, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = _compose2['default'].apply(undefined, chain)(store.dispatch); return _extends({}, store, { dispatch: _dispatch }); }; }; } /***/ }, /* 6 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = bindActionCreators; function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(undefined, arguments)); }; } /** * Turns an object whose values are action creators, into an object with the * same keys, but with every function wrapped into a `dispatch` call so they * may be invoked directly. This is just a convenience method, as you can call * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. * * For convenience, you can also pass a single function as the first argument, * and get a function in return. * * @param {Function|Object} actionCreators An object whose values are action * creator functions. One handy way to obtain it is to use ES6 `import * as` * syntax. You may also pass a single function. * * @param {Function} dispatch The `dispatch` function available on your Redux * store. * * @returns {Function|Object} The object mimicking the original object, but with * every action creator wrapped into the `dispatch` call. If you passed a * function as `actionCreators`, the return value will also be a single * function. */ function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch); } if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'); } var keys = Object.keys(actionCreators); var boundActionCreators = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var actionCreator = actionCreators[key]; if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = combineReducers; var _createStore = __webpack_require__(2); var _isPlainObject = __webpack_require__(4); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _warning = __webpack_require__(3); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.'; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!(0, _isPlainObject2['default'])(inputState)) { return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]; }); unexpectedKeys.forEach(function (key) { unexpectedKeyCache[key] = true; }); if (unexpectedKeys.length > 0) { return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.'); } } function assertReducerSanity(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.'); } var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); if (typeof reducer(undefined, { type: type }) === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.'); } }); } /** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (true) { if (typeof reducers[key] === 'undefined') { (0, _warning2['default'])('No reducer provided for key "' + key + '"'); } } if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); if (true) { var unexpectedKeyCache = {}; } var sanityError; try { assertReducerSanity(finalReducers); } catch (e) { sanityError = e; } return function combination() { var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var action = arguments[1]; if (sanityError) { throw sanityError; } if (true) { var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache); if (warningMessage) { (0, _warning2['default'])(warningMessage); } } var hasChanged = false; var nextState = {}; for (var i = 0; i < finalReducerKeys.length; i++) { var key = finalReducerKeys[i]; var reducer = finalReducers[key]; var previousStateForKey = state[key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(key, action); throw new Error(errorMessage); } nextState[key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; } /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(10); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }, /* 9 */ /***/ function(module, exports) { /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } module.exports = isHostObject; /***/ }, /* 10 */ /***/ function(module, exports) { /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }, /* 11 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(13); /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ponyfill = __webpack_require__(14); var _ponyfill2 = _interopRequireDefault(_ponyfill); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var root = undefined; /* global window */ if (typeof global !== 'undefined') { root = global; } else if (typeof window !== 'undefined') { root = window; } var result = (0, _ponyfill2['default'])(root); exports['default'] = result; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 14 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = symbolObservablePonyfill; function symbolObservablePonyfill(root) { var result; var _Symbol = root.Symbol; if (typeof _Symbol === 'function') { if (_Symbol.observable) { result = _Symbol.observable; } else { result = _Symbol('observable'); _Symbol.observable = result; } } else { result = '@@observable'; } return result; }; /***/ } /******/ ]) }); ;
listeners[i](); }
conditional_block
redux.js
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["Redux"] = factory(); else root["Redux"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined; var _createStore = __webpack_require__(2); var _createStore2 = _interopRequireDefault(_createStore); var _combineReducers = __webpack_require__(7); var _combineReducers2 = _interopRequireDefault(_combineReducers); var _bindActionCreators = __webpack_require__(6); var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators); var _applyMiddleware = __webpack_require__(5); var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware); var _compose = __webpack_require__(1); var _compose2 = _interopRequireDefault(_compose); var _warning = __webpack_require__(3); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if (("development") !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') { (0, _warning2['default'])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.'); } exports.createStore = _createStore2['default']; exports.combineReducers = _combineReducers2['default']; exports.bindActionCreators = _bindActionCreators2['default']; exports.applyMiddleware = _applyMiddleware2['default']; exports.compose = _compose2['default']; /***/ }, /* 1 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = compose; /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } var last = funcs[funcs.length - 1]; var rest = funcs.slice(0, -1); return function () { return rest.reduceRight(function (composed, f) { return f(composed); }, last.apply(undefined, arguments)); }; } /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.ActionTypes = undefined; exports['default'] = createStore; var _isPlainObject = __webpack_require__(4); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _symbolObservable = __webpack_require__(12); var _symbolObservable2 = _interopRequireDefault(_symbolObservable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var ActionTypes = exports.ActionTypes = { INIT: '@@redux/INIT' }; /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [preloadedState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} enhancer The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ function createStore(reducer, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = preloadedState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; function
() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.'); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!(0, _isPlainObject2['default'])(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { listeners[i](); } return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/zenparsing/es-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[_symbolObservable2['default']] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[_symbolObservable2['default']] = observable, _ref2; } /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = warning; /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var getPrototype = __webpack_require__(8), isHostObject = __webpack_require__(9), isObjectLike = __webpack_require__(11); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return (typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); } module.exports = isPlainObject; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports['default'] = applyMiddleware; var _compose = __webpack_require__(1); var _compose2 = _interopRequireDefault(_compose); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function (reducer, preloadedState, enhancer) { var store = createStore(reducer, preloadedState, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = _compose2['default'].apply(undefined, chain)(store.dispatch); return _extends({}, store, { dispatch: _dispatch }); }; }; } /***/ }, /* 6 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = bindActionCreators; function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(undefined, arguments)); }; } /** * Turns an object whose values are action creators, into an object with the * same keys, but with every function wrapped into a `dispatch` call so they * may be invoked directly. This is just a convenience method, as you can call * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. * * For convenience, you can also pass a single function as the first argument, * and get a function in return. * * @param {Function|Object} actionCreators An object whose values are action * creator functions. One handy way to obtain it is to use ES6 `import * as` * syntax. You may also pass a single function. * * @param {Function} dispatch The `dispatch` function available on your Redux * store. * * @returns {Function|Object} The object mimicking the original object, but with * every action creator wrapped into the `dispatch` call. If you passed a * function as `actionCreators`, the return value will also be a single * function. */ function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch); } if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'); } var keys = Object.keys(actionCreators); var boundActionCreators = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var actionCreator = actionCreators[key]; if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = combineReducers; var _createStore = __webpack_require__(2); var _isPlainObject = __webpack_require__(4); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _warning = __webpack_require__(3); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.'; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!(0, _isPlainObject2['default'])(inputState)) { return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]; }); unexpectedKeys.forEach(function (key) { unexpectedKeyCache[key] = true; }); if (unexpectedKeys.length > 0) { return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.'); } } function assertReducerSanity(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.'); } var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); if (typeof reducer(undefined, { type: type }) === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.'); } }); } /** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (true) { if (typeof reducers[key] === 'undefined') { (0, _warning2['default'])('No reducer provided for key "' + key + '"'); } } if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); if (true) { var unexpectedKeyCache = {}; } var sanityError; try { assertReducerSanity(finalReducers); } catch (e) { sanityError = e; } return function combination() { var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var action = arguments[1]; if (sanityError) { throw sanityError; } if (true) { var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache); if (warningMessage) { (0, _warning2['default'])(warningMessage); } } var hasChanged = false; var nextState = {}; for (var i = 0; i < finalReducerKeys.length; i++) { var key = finalReducerKeys[i]; var reducer = finalReducers[key]; var previousStateForKey = state[key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(key, action); throw new Error(errorMessage); } nextState[key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; } /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(10); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }, /* 9 */ /***/ function(module, exports) { /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } module.exports = isHostObject; /***/ }, /* 10 */ /***/ function(module, exports) { /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }, /* 11 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(13); /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ponyfill = __webpack_require__(14); var _ponyfill2 = _interopRequireDefault(_ponyfill); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var root = undefined; /* global window */ if (typeof global !== 'undefined') { root = global; } else if (typeof window !== 'undefined') { root = window; } var result = (0, _ponyfill2['default'])(root); exports['default'] = result; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 14 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = symbolObservablePonyfill; function symbolObservablePonyfill(root) { var result; var _Symbol = root.Symbol; if (typeof _Symbol === 'function') { if (_Symbol.observable) { result = _Symbol.observable; } else { result = _Symbol('observable'); _Symbol.observable = result; } } else { result = '@@observable'; } return result; }; /***/ } /******/ ]) }); ;
ensureCanMutateNextListeners
identifier_name
redux.js
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["Redux"] = factory(); else root["Redux"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined; var _createStore = __webpack_require__(2); var _createStore2 = _interopRequireDefault(_createStore); var _combineReducers = __webpack_require__(7); var _combineReducers2 = _interopRequireDefault(_combineReducers); var _bindActionCreators = __webpack_require__(6); var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators); var _applyMiddleware = __webpack_require__(5); var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware); var _compose = __webpack_require__(1); var _compose2 = _interopRequireDefault(_compose); var _warning = __webpack_require__(3); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if (("development") !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') { (0, _warning2['default'])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.'); } exports.createStore = _createStore2['default']; exports.combineReducers = _combineReducers2['default']; exports.bindActionCreators = _bindActionCreators2['default']; exports.applyMiddleware = _applyMiddleware2['default']; exports.compose = _compose2['default']; /***/ }, /* 1 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = compose; /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } var last = funcs[funcs.length - 1]; var rest = funcs.slice(0, -1); return function () { return rest.reduceRight(function (composed, f) { return f(composed); }, last.apply(undefined, arguments)); }; } /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.ActionTypes = undefined; exports['default'] = createStore; var _isPlainObject = __webpack_require__(4); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _symbolObservable = __webpack_require__(12); var _symbolObservable2 = _interopRequireDefault(_symbolObservable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var ActionTypes = exports.ActionTypes = { INIT: '@@redux/INIT' }; /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [preloadedState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} enhancer The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ function createStore(reducer, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = preloadedState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.'); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!(0, _isPlainObject2['default'])(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { listeners[i](); } return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/zenparsing/es-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[_symbolObservable2['default']] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[_symbolObservable2['default']] = observable, _ref2; } /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = warning; /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var getPrototype = __webpack_require__(8), isHostObject = __webpack_require__(9), isObjectLike = __webpack_require__(11); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return (typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); } module.exports = isPlainObject; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports['default'] = applyMiddleware; var _compose = __webpack_require__(1); var _compose2 = _interopRequireDefault(_compose); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function (reducer, preloadedState, enhancer) { var store = createStore(reducer, preloadedState, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = _compose2['default'].apply(undefined, chain)(store.dispatch); return _extends({}, store, { dispatch: _dispatch }); }; }; } /***/ }, /* 6 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = bindActionCreators; function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(undefined, arguments)); }; } /** * Turns an object whose values are action creators, into an object with the * same keys, but with every function wrapped into a `dispatch` call so they * may be invoked directly. This is just a convenience method, as you can call * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. * * For convenience, you can also pass a single function as the first argument, * and get a function in return. * * @param {Function|Object} actionCreators An object whose values are action * creator functions. One handy way to obtain it is to use ES6 `import * as` * syntax. You may also pass a single function. * * @param {Function} dispatch The `dispatch` function available on your Redux * store. * * @returns {Function|Object} The object mimicking the original object, but with * every action creator wrapped into the `dispatch` call. If you passed a * function as `actionCreators`, the return value will also be a single * function. */ function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch); } if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'); } var keys = Object.keys(actionCreators); var boundActionCreators = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var actionCreator = actionCreators[key]; if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = combineReducers; var _createStore = __webpack_require__(2); var _isPlainObject = __webpack_require__(4); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _warning = __webpack_require__(3); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.'; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!(0, _isPlainObject2['default'])(inputState)) { return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]; }); unexpectedKeys.forEach(function (key) { unexpectedKeyCache[key] = true; }); if (unexpectedKeys.length > 0) { return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.'); } } function assertReducerSanity(reducers) {
** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (true) { if (typeof reducers[key] === 'undefined') { (0, _warning2['default'])('No reducer provided for key "' + key + '"'); } } if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); if (true) { var unexpectedKeyCache = {}; } var sanityError; try { assertReducerSanity(finalReducers); } catch (e) { sanityError = e; } return function combination() { var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var action = arguments[1]; if (sanityError) { throw sanityError; } if (true) { var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache); if (warningMessage) { (0, _warning2['default'])(warningMessage); } } var hasChanged = false; var nextState = {}; for (var i = 0; i < finalReducerKeys.length; i++) { var key = finalReducerKeys[i]; var reducer = finalReducers[key]; var previousStateForKey = state[key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(key, action); throw new Error(errorMessage); } nextState[key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; } /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(10); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }, /* 9 */ /***/ function(module, exports) { /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } module.exports = isHostObject; /***/ }, /* 10 */ /***/ function(module, exports) { /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }, /* 11 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(13); /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ponyfill = __webpack_require__(14); var _ponyfill2 = _interopRequireDefault(_ponyfill); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var root = undefined; /* global window */ if (typeof global !== 'undefined') { root = global; } else if (typeof window !== 'undefined') { root = window; } var result = (0, _ponyfill2['default'])(root); exports['default'] = result; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 14 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = symbolObservablePonyfill; function symbolObservablePonyfill(root) { var result; var _Symbol = root.Symbol; if (typeof _Symbol === 'function') { if (_Symbol.observable) { result = _Symbol.observable; } else { result = _Symbol('observable'); _Symbol.observable = result; } } else { result = '@@observable'; } return result; }; /***/ } /******/ ]) }); ;
Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.'); } var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); if (typeof reducer(undefined, { type: type }) === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.'); } }); } /
identifier_body
event.rs
use devices::{HatSwitch, JoystickState}; /// State of a Key or Button #[derive(Eq, PartialEq, Clone, Debug)] pub enum State { Pressed, Released, } /// Key Identifier (UK Keyboard Layout) #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum KeyId { Escape, Return, Backspace, Left, Right, Up, Down, Space, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Shift, LeftCtrl, RightCtrl, LeftAlt, RightAlt, CapsLock, Pause, PageUp, PageDown, PrintScreen, Insert, End, Home, Delete, Add, Subtract, Multiply, Separator, Decimal, Divide, BackTick, BackSlash, ForwardSlash, Plus, Minus, FullStop, Comma, Tab, Numlock, LeftSquareBracket, RightSquareBracket, SemiColon, Apostrophe, Hash, } /// Mouse Buttons #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum MouseButton { Left, Right, Middle, Button4, Button5, } #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum Axis { X, Y, Z, RX, RY, RZ, SLIDER, } /// Event types /// /// The usize entry acts as a device ID unique to each DeviceType (Mouse, Keyboard, Hid). /// Keyboard press events repeat when a key is held down. #[derive(Clone, Debug)] pub enum RawEvent { MouseButtonEvent(usize, MouseButton, State), MouseMoveEvent(usize, i32, i32), MouseWheelEvent(usize, f32), KeyboardEvent(usize, KeyId, State), JoystickButtonEvent(usize, usize, State), JoystickAxisEvent(usize, Axis, f64), JoystickHatSwitchEvent(usize, HatSwitch), } impl JoystickState { pub fn compare_states(&self, other_state: JoystickState, id: usize) -> Vec<RawEvent> { let mut output: Vec<RawEvent> = Vec::new(); for (index, (&press_state, _)) in self .button_states .iter() .zip(other_state.button_states.iter()) .enumerate() .filter(|&(_, (&a, &b))| a != b) { output.push(RawEvent::JoystickButtonEvent( id, index, if press_state { State::Released } else { State::Pressed }, )); } if self.raw_axis_states.x != other_state.raw_axis_states.x { if let Some(value) = other_state.axis_states.x { output.push(RawEvent::JoystickAxisEvent(id, Axis::X, value)); } } if self.raw_axis_states.y != other_state.raw_axis_states.y { if let Some(value) = other_state.axis_states.y { output.push(RawEvent::JoystickAxisEvent(id, Axis::Y, value)); } } if self.raw_axis_states.z != other_state.raw_axis_states.z { if let Some(value) = other_state.axis_states.z { output.push(RawEvent::JoystickAxisEvent(id, Axis::Z, value)); } } if self.raw_axis_states.rx != other_state.raw_axis_states.rx { if let Some(value) = other_state.axis_states.rx { output.push(RawEvent::JoystickAxisEvent(id, Axis::RX, value)); } } if self.raw_axis_states.ry != other_state.raw_axis_states.ry { if let Some(value) = other_state.axis_states.ry { output.push(RawEvent::JoystickAxisEvent(id, Axis::RY, value)); } } if self.raw_axis_states.rz != other_state.raw_axis_states.rz { if let Some(value) = other_state.axis_states.rz { output.push(RawEvent::JoystickAxisEvent(id, Axis::RZ, value)); } } if self.raw_axis_states.slider != other_state.raw_axis_states.slider { if let Some(value) = other_state.axis_states.slider { output.push(RawEvent::JoystickAxisEvent(id, Axis::SLIDER, value)); } }
if let Some(value_self) = self.hatswitch.clone() { if value_self != value_other { output.push(RawEvent::JoystickHatSwitchEvent(id, value_other)); } } } output } }
if let Some(value_other) = other_state.hatswitch {
random_line_split
event.rs
use devices::{HatSwitch, JoystickState}; /// State of a Key or Button #[derive(Eq, PartialEq, Clone, Debug)] pub enum State { Pressed, Released, } /// Key Identifier (UK Keyboard Layout) #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum KeyId { Escape, Return, Backspace, Left, Right, Up, Down, Space, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Shift, LeftCtrl, RightCtrl, LeftAlt, RightAlt, CapsLock, Pause, PageUp, PageDown, PrintScreen, Insert, End, Home, Delete, Add, Subtract, Multiply, Separator, Decimal, Divide, BackTick, BackSlash, ForwardSlash, Plus, Minus, FullStop, Comma, Tab, Numlock, LeftSquareBracket, RightSquareBracket, SemiColon, Apostrophe, Hash, } /// Mouse Buttons #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum MouseButton { Left, Right, Middle, Button4, Button5, } #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum Axis { X, Y, Z, RX, RY, RZ, SLIDER, } /// Event types /// /// The usize entry acts as a device ID unique to each DeviceType (Mouse, Keyboard, Hid). /// Keyboard press events repeat when a key is held down. #[derive(Clone, Debug)] pub enum RawEvent { MouseButtonEvent(usize, MouseButton, State), MouseMoveEvent(usize, i32, i32), MouseWheelEvent(usize, f32), KeyboardEvent(usize, KeyId, State), JoystickButtonEvent(usize, usize, State), JoystickAxisEvent(usize, Axis, f64), JoystickHatSwitchEvent(usize, HatSwitch), } impl JoystickState { pub fn compare_states(&self, other_state: JoystickState, id: usize) -> Vec<RawEvent> { let mut output: Vec<RawEvent> = Vec::new(); for (index, (&press_state, _)) in self .button_states .iter() .zip(other_state.button_states.iter()) .enumerate() .filter(|&(_, (&a, &b))| a != b) { output.push(RawEvent::JoystickButtonEvent( id, index, if press_state { State::Released } else { State::Pressed }, )); } if self.raw_axis_states.x != other_state.raw_axis_states.x { if let Some(value) = other_state.axis_states.x { output.push(RawEvent::JoystickAxisEvent(id, Axis::X, value)); } } if self.raw_axis_states.y != other_state.raw_axis_states.y { if let Some(value) = other_state.axis_states.y { output.push(RawEvent::JoystickAxisEvent(id, Axis::Y, value)); } } if self.raw_axis_states.z != other_state.raw_axis_states.z { if let Some(value) = other_state.axis_states.z { output.push(RawEvent::JoystickAxisEvent(id, Axis::Z, value)); } } if self.raw_axis_states.rx != other_state.raw_axis_states.rx { if let Some(value) = other_state.axis_states.rx { output.push(RawEvent::JoystickAxisEvent(id, Axis::RX, value)); } } if self.raw_axis_states.ry != other_state.raw_axis_states.ry { if let Some(value) = other_state.axis_states.ry { output.push(RawEvent::JoystickAxisEvent(id, Axis::RY, value)); } } if self.raw_axis_states.rz != other_state.raw_axis_states.rz { if let Some(value) = other_state.axis_states.rz { output.push(RawEvent::JoystickAxisEvent(id, Axis::RZ, value)); } } if self.raw_axis_states.slider != other_state.raw_axis_states.slider { if let Some(value) = other_state.axis_states.slider
} if let Some(value_other) = other_state.hatswitch { if let Some(value_self) = self.hatswitch.clone() { if value_self != value_other { output.push(RawEvent::JoystickHatSwitchEvent(id, value_other)); } } } output } }
{ output.push(RawEvent::JoystickAxisEvent(id, Axis::SLIDER, value)); }
conditional_block
event.rs
use devices::{HatSwitch, JoystickState}; /// State of a Key or Button #[derive(Eq, PartialEq, Clone, Debug)] pub enum
{ Pressed, Released, } /// Key Identifier (UK Keyboard Layout) #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum KeyId { Escape, Return, Backspace, Left, Right, Up, Down, Space, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Shift, LeftCtrl, RightCtrl, LeftAlt, RightAlt, CapsLock, Pause, PageUp, PageDown, PrintScreen, Insert, End, Home, Delete, Add, Subtract, Multiply, Separator, Decimal, Divide, BackTick, BackSlash, ForwardSlash, Plus, Minus, FullStop, Comma, Tab, Numlock, LeftSquareBracket, RightSquareBracket, SemiColon, Apostrophe, Hash, } /// Mouse Buttons #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum MouseButton { Left, Right, Middle, Button4, Button5, } #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum Axis { X, Y, Z, RX, RY, RZ, SLIDER, } /// Event types /// /// The usize entry acts as a device ID unique to each DeviceType (Mouse, Keyboard, Hid). /// Keyboard press events repeat when a key is held down. #[derive(Clone, Debug)] pub enum RawEvent { MouseButtonEvent(usize, MouseButton, State), MouseMoveEvent(usize, i32, i32), MouseWheelEvent(usize, f32), KeyboardEvent(usize, KeyId, State), JoystickButtonEvent(usize, usize, State), JoystickAxisEvent(usize, Axis, f64), JoystickHatSwitchEvent(usize, HatSwitch), } impl JoystickState { pub fn compare_states(&self, other_state: JoystickState, id: usize) -> Vec<RawEvent> { let mut output: Vec<RawEvent> = Vec::new(); for (index, (&press_state, _)) in self .button_states .iter() .zip(other_state.button_states.iter()) .enumerate() .filter(|&(_, (&a, &b))| a != b) { output.push(RawEvent::JoystickButtonEvent( id, index, if press_state { State::Released } else { State::Pressed }, )); } if self.raw_axis_states.x != other_state.raw_axis_states.x { if let Some(value) = other_state.axis_states.x { output.push(RawEvent::JoystickAxisEvent(id, Axis::X, value)); } } if self.raw_axis_states.y != other_state.raw_axis_states.y { if let Some(value) = other_state.axis_states.y { output.push(RawEvent::JoystickAxisEvent(id, Axis::Y, value)); } } if self.raw_axis_states.z != other_state.raw_axis_states.z { if let Some(value) = other_state.axis_states.z { output.push(RawEvent::JoystickAxisEvent(id, Axis::Z, value)); } } if self.raw_axis_states.rx != other_state.raw_axis_states.rx { if let Some(value) = other_state.axis_states.rx { output.push(RawEvent::JoystickAxisEvent(id, Axis::RX, value)); } } if self.raw_axis_states.ry != other_state.raw_axis_states.ry { if let Some(value) = other_state.axis_states.ry { output.push(RawEvent::JoystickAxisEvent(id, Axis::RY, value)); } } if self.raw_axis_states.rz != other_state.raw_axis_states.rz { if let Some(value) = other_state.axis_states.rz { output.push(RawEvent::JoystickAxisEvent(id, Axis::RZ, value)); } } if self.raw_axis_states.slider != other_state.raw_axis_states.slider { if let Some(value) = other_state.axis_states.slider { output.push(RawEvent::JoystickAxisEvent(id, Axis::SLIDER, value)); } } if let Some(value_other) = other_state.hatswitch { if let Some(value_self) = self.hatswitch.clone() { if value_self != value_other { output.push(RawEvent::JoystickHatSwitchEvent(id, value_other)); } } } output } }
State
identifier_name
clv_medicament_template_history.py
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api from datetime import * class clv_medicament_template_history(models.Model): _name = 'clv_medicament.template.history' medicament_template_id = fields.Many2one('clv_medicament.template', 'Medicament Template', required=True) user_id = fields.Many2one ('res.users', 'User', required=True) date = fields.Datetime("Date", required=True) state = fields.Selection([('draft','Draft'), ('revised','Revised'), ('waiting','Waiting'), ('done','Done'), ('canceled','Canceled'), ], string='Status', default='draft', readonly=True, required=True, help="") notes = fields.Text(string='Notes') _order = "date desc" _defaults = { 'user_id': lambda obj,cr,uid,context: uid, 'date': lambda *a: datetime.now().strftime('%Y-%m-%d %H:%M:%S'), } class clv_medicament_template(models.Model): _inherit = 'clv_medicament.template' history_ids = fields.One2many('clv_medicament.template.history', 'medicament_template_id', 'Medicament Template History', readonly=True) active_history = fields.Boolean('Active History', help="If unchecked, it will allow you to disable the history without removing it.", default=True) @api.one def insert_clv_medicament_template_history(self, medicament_template_id, state, notes): if self.active_history:
@api.multi def write(self, values): if (not 'state' in values) and (not 'date' in values): notes = values.keys() self.insert_clv_medicament_template_history(self.id, self.state, notes) return super(clv_medicament_template, self).write(values) @api.one def button_draft(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'draft' self.insert_clv_medicament_template_history(self.id, 'draft', '') @api.one def button_revised(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'revised' self.insert_clv_medicament_template_history(self.id, 'revised', '') @api.one def button_waiting(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'waiting' self.insert_clv_medicament_template_history(self.id, 'waiting', '') @api.one def button_done(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'done' self.insert_clv_medicament_template_history(self.id, 'done', '') @api.one def button_cancel(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'canceled' self.insert_clv_medicament_template_history(self.id, 'canceled', '') @api.one def set_to_draft(self, *args): self.state = 'draft' self.create_workflow() return True
values = { 'medicament_template_id': medicament_template_id, 'state': state, 'notes': notes, } self.pool.get('clv_medicament.template.history').create(self._cr, self._uid, values)
conditional_block
clv_medicament_template_history.py
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api from datetime import * class clv_medicament_template_history(models.Model): _name = 'clv_medicament.template.history' medicament_template_id = fields.Many2one('clv_medicament.template', 'Medicament Template', required=True) user_id = fields.Many2one ('res.users', 'User', required=True) date = fields.Datetime("Date", required=True) state = fields.Selection([('draft','Draft'), ('revised','Revised'), ('waiting','Waiting'), ('done','Done'), ('canceled','Canceled'), ], string='Status', default='draft', readonly=True, required=True, help="") notes = fields.Text(string='Notes') _order = "date desc" _defaults = { 'user_id': lambda obj,cr,uid,context: uid, 'date': lambda *a: datetime.now().strftime('%Y-%m-%d %H:%M:%S'), } class clv_medicament_template(models.Model): _inherit = 'clv_medicament.template' history_ids = fields.One2many('clv_medicament.template.history', 'medicament_template_id', 'Medicament Template History', readonly=True) active_history = fields.Boolean('Active History', help="If unchecked, it will allow you to disable the history without removing it.", default=True) @api.one def insert_clv_medicament_template_history(self, medicament_template_id, state, notes): if self.active_history: values = { 'medicament_template_id': medicament_template_id, 'state': state, 'notes': notes, } self.pool.get('clv_medicament.template.history').create(self._cr, self._uid, values) @api.multi def write(self, values): if (not 'state' in values) and (not 'date' in values): notes = values.keys() self.insert_clv_medicament_template_history(self.id, self.state, notes) return super(clv_medicament_template, self).write(values) @api.one def button_draft(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'draft' self.insert_clv_medicament_template_history(self.id, 'draft', '') @api.one def button_revised(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'revised' self.insert_clv_medicament_template_history(self.id, 'revised', '') @api.one def button_waiting(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'waiting' self.insert_clv_medicament_template_history(self.id, 'waiting', '') @api.one def button_done(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'done' self.insert_clv_medicament_template_history(self.id, 'done', '') @api.one def button_cancel(self):
@api.one def set_to_draft(self, *args): self.state = 'draft' self.create_workflow() return True
self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'canceled' self.insert_clv_medicament_template_history(self.id, 'canceled', '')
identifier_body
clv_medicament_template_history.py
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # #
# You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api from datetime import * class clv_medicament_template_history(models.Model): _name = 'clv_medicament.template.history' medicament_template_id = fields.Many2one('clv_medicament.template', 'Medicament Template', required=True) user_id = fields.Many2one ('res.users', 'User', required=True) date = fields.Datetime("Date", required=True) state = fields.Selection([('draft','Draft'), ('revised','Revised'), ('waiting','Waiting'), ('done','Done'), ('canceled','Canceled'), ], string='Status', default='draft', readonly=True, required=True, help="") notes = fields.Text(string='Notes') _order = "date desc" _defaults = { 'user_id': lambda obj,cr,uid,context: uid, 'date': lambda *a: datetime.now().strftime('%Y-%m-%d %H:%M:%S'), } class clv_medicament_template(models.Model): _inherit = 'clv_medicament.template' history_ids = fields.One2many('clv_medicament.template.history', 'medicament_template_id', 'Medicament Template History', readonly=True) active_history = fields.Boolean('Active History', help="If unchecked, it will allow you to disable the history without removing it.", default=True) @api.one def insert_clv_medicament_template_history(self, medicament_template_id, state, notes): if self.active_history: values = { 'medicament_template_id': medicament_template_id, 'state': state, 'notes': notes, } self.pool.get('clv_medicament.template.history').create(self._cr, self._uid, values) @api.multi def write(self, values): if (not 'state' in values) and (not 'date' in values): notes = values.keys() self.insert_clv_medicament_template_history(self.id, self.state, notes) return super(clv_medicament_template, self).write(values) @api.one def button_draft(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'draft' self.insert_clv_medicament_template_history(self.id, 'draft', '') @api.one def button_revised(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'revised' self.insert_clv_medicament_template_history(self.id, 'revised', '') @api.one def button_waiting(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'waiting' self.insert_clv_medicament_template_history(self.id, 'waiting', '') @api.one def button_done(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'done' self.insert_clv_medicament_template_history(self.id, 'done', '') @api.one def button_cancel(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'canceled' self.insert_clv_medicament_template_history(self.id, 'canceled', '') @api.one def set_to_draft(self, *args): self.state = 'draft' self.create_workflow() return True
# 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 Affero General Public License for more details. # # #
random_line_split
clv_medicament_template_history.py
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api from datetime import * class clv_medicament_template_history(models.Model): _name = 'clv_medicament.template.history' medicament_template_id = fields.Many2one('clv_medicament.template', 'Medicament Template', required=True) user_id = fields.Many2one ('res.users', 'User', required=True) date = fields.Datetime("Date", required=True) state = fields.Selection([('draft','Draft'), ('revised','Revised'), ('waiting','Waiting'), ('done','Done'), ('canceled','Canceled'), ], string='Status', default='draft', readonly=True, required=True, help="") notes = fields.Text(string='Notes') _order = "date desc" _defaults = { 'user_id': lambda obj,cr,uid,context: uid, 'date': lambda *a: datetime.now().strftime('%Y-%m-%d %H:%M:%S'), } class clv_medicament_template(models.Model): _inherit = 'clv_medicament.template' history_ids = fields.One2many('clv_medicament.template.history', 'medicament_template_id', 'Medicament Template History', readonly=True) active_history = fields.Boolean('Active History', help="If unchecked, it will allow you to disable the history without removing it.", default=True) @api.one def insert_clv_medicament_template_history(self, medicament_template_id, state, notes): if self.active_history: values = { 'medicament_template_id': medicament_template_id, 'state': state, 'notes': notes, } self.pool.get('clv_medicament.template.history').create(self._cr, self._uid, values) @api.multi def write(self, values): if (not 'state' in values) and (not 'date' in values): notes = values.keys() self.insert_clv_medicament_template_history(self.id, self.state, notes) return super(clv_medicament_template, self).write(values) @api.one def button_draft(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'draft' self.insert_clv_medicament_template_history(self.id, 'draft', '') @api.one def
(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'revised' self.insert_clv_medicament_template_history(self.id, 'revised', '') @api.one def button_waiting(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'waiting' self.insert_clv_medicament_template_history(self.id, 'waiting', '') @api.one def button_done(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'done' self.insert_clv_medicament_template_history(self.id, 'done', '') @api.one def button_cancel(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.state = 'canceled' self.insert_clv_medicament_template_history(self.id, 'canceled', '') @api.one def set_to_draft(self, *args): self.state = 'draft' self.create_workflow() return True
button_revised
identifier_name
test.ts
const TestCommand = require('ember-cli/lib/commands/test'); import TestTask from '../tasks/test'; import {CliConfig} from '../models/config'; const NgCliTestCommand = TestCommand.extend({ availableOptions: [ { name: 'watch', type: Boolean, default: true, aliases: ['w'] }, { name: 'browsers', type: String }, { name: 'colors', type: Boolean }, { name: 'log-level', type: String }, { name: 'port', type: Number }, { name: 'reporters', type: String }, { name: 'build', type: Boolean, default: true } ], run: function(commandOptions: any) { this.project.ngConfig = this.project.ngConfig || CliConfig.fromProject(); const testTask = new TestTask({ ui: this.ui, analytics: this.analytics, project: this.project });
if (!commandOptions.watch) { // if not watching ensure karma is doing a single run commandOptions.singleRun = true; } return testTask.run(commandOptions); } }); NgCliTestCommand.overrideCore = true; export default NgCliTestCommand;
random_line_split
test.ts
const TestCommand = require('ember-cli/lib/commands/test'); import TestTask from '../tasks/test'; import {CliConfig} from '../models/config'; const NgCliTestCommand = TestCommand.extend({ availableOptions: [ { name: 'watch', type: Boolean, default: true, aliases: ['w'] }, { name: 'browsers', type: String }, { name: 'colors', type: Boolean }, { name: 'log-level', type: String }, { name: 'port', type: Number }, { name: 'reporters', type: String }, { name: 'build', type: Boolean, default: true } ], run: function(commandOptions: any) { this.project.ngConfig = this.project.ngConfig || CliConfig.fromProject(); const testTask = new TestTask({ ui: this.ui, analytics: this.analytics, project: this.project }); if (!commandOptions.watch)
return testTask.run(commandOptions); } }); NgCliTestCommand.overrideCore = true; export default NgCliTestCommand;
{ // if not watching ensure karma is doing a single run commandOptions.singleRun = true; }
conditional_block
client.rs
extern crate nanomsg; use std::thread; use std::time::Duration; use std::sync::mpsc::*; use super::media_player; use super::protocol; use self::nanomsg::{Socket, Protocol, Error}; pub fn run(rx_quit: Receiver<bool>, tx_state: Sender<media_player::State>)
{ let mut subscriber = match Socket::new(Protocol::Sub) { Ok(socket) => socket, Err(err) => panic!("{}", err) }; subscriber.subscribe(&String::from("").into_bytes()[..]); subscriber.set_receive_timeout(500).unwrap(); match subscriber.connect("tcp://*:5555") { Ok(_) => println!("Connected to server..."), Err(err) => panic!("Failed to bind socket: {}", err) } let mut msg_buffer: [u8; 9] = [0; 9]; while let Err(_) = rx_quit.try_recv() { match subscriber.nb_read(&mut msg_buffer) { Ok(_) => { let state = protocol::into_state(&msg_buffer[0..9]); println!("Received {:?}", state); // debug if let Err(_) = tx_state.send(state) { break; } }, Err(Error::TryAgain) => {}, Err(err) => panic!("Problem receiving msg: {}", err), } thread::sleep(Duration::from_millis(super::HOST_SYNC_INTERVAL_MS / 2)); } }
identifier_body
client.rs
extern crate nanomsg; use std::thread; use std::time::Duration; use std::sync::mpsc::*; use super::media_player; use super::protocol; use self::nanomsg::{Socket, Protocol, Error}; pub fn
(rx_quit: Receiver<bool>, tx_state: Sender<media_player::State>) { let mut subscriber = match Socket::new(Protocol::Sub) { Ok(socket) => socket, Err(err) => panic!("{}", err) }; subscriber.subscribe(&String::from("").into_bytes()[..]); subscriber.set_receive_timeout(500).unwrap(); match subscriber.connect("tcp://*:5555") { Ok(_) => println!("Connected to server..."), Err(err) => panic!("Failed to bind socket: {}", err) } let mut msg_buffer: [u8; 9] = [0; 9]; while let Err(_) = rx_quit.try_recv() { match subscriber.nb_read(&mut msg_buffer) { Ok(_) => { let state = protocol::into_state(&msg_buffer[0..9]); println!("Received {:?}", state); // debug if let Err(_) = tx_state.send(state) { break; } }, Err(Error::TryAgain) => {}, Err(err) => panic!("Problem receiving msg: {}", err), } thread::sleep(Duration::from_millis(super::HOST_SYNC_INTERVAL_MS / 2)); } }
run
identifier_name
client.rs
extern crate nanomsg; use std::thread; use std::time::Duration; use std::sync::mpsc::*; use super::media_player; use super::protocol;
pub fn run(rx_quit: Receiver<bool>, tx_state: Sender<media_player::State>) { let mut subscriber = match Socket::new(Protocol::Sub) { Ok(socket) => socket, Err(err) => panic!("{}", err) }; subscriber.subscribe(&String::from("").into_bytes()[..]); subscriber.set_receive_timeout(500).unwrap(); match subscriber.connect("tcp://*:5555") { Ok(_) => println!("Connected to server..."), Err(err) => panic!("Failed to bind socket: {}", err) } let mut msg_buffer: [u8; 9] = [0; 9]; while let Err(_) = rx_quit.try_recv() { match subscriber.nb_read(&mut msg_buffer) { Ok(_) => { let state = protocol::into_state(&msg_buffer[0..9]); println!("Received {:?}", state); // debug if let Err(_) = tx_state.send(state) { break; } }, Err(Error::TryAgain) => {}, Err(err) => panic!("Problem receiving msg: {}", err), } thread::sleep(Duration::from_millis(super::HOST_SYNC_INTERVAL_MS / 2)); } }
use self::nanomsg::{Socket, Protocol, Error};
random_line_split