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
Presence.ts
export interface Presence { subscribe(topic: string, callback: Function); unsubscribe(topic: string, callback?: Function); publish(topic: string, data: any); exists(roomId: string): Promise<boolean>; setex(key: string, value: string, seconds: number); get(key: string); del(key: string): void; sadd(key: string, value: any); smembers(key: string): Promise<string[]>; sismember(key: string, field: string);
srem(key: string, value: any); scard(key: string); sinter(...keys: string[]): Promise<string[]>; hset(key: string, field: string, value: string); hincrby(key: string, field: string, value: number); hget(key: string, field: string): Promise<string>; hgetall(key: string): Promise<{ [key: string]: string }>; hdel(key: string, field: string); hlen(key: string): Promise<number>; incr(key: string); decr(key: string); }
random_line_split
setup.py
#!/usr/bin/env python # coding=utf-8 from setuptools import setup, find_packages setup(name='french_dates_to_ical', version='0.0.1', author='Michaël Launay', author_email='michaellaunay@ecreall.com', url='http://www.ecreall.com/ressources/french_dates_to_ical', download_url='https://github.com/michaellaunay/french_dates_to_ical', description='Parse a string of french dates to generate the ical rules (RFC 5545)', long_description='french_dates_to_ical can be use as a standalone tool or like a library. In both cases, you provide a string of french dates like "Tous les jeudis", and the program returns the ical rules.', packages = find_packages(), include_package_data = True, package_data = { '': ['*.txt', '*.rst'], #'french_dates_to_ical': ['data/*'], }, exclude_package_data = { '': ['README.txt'] }, scripts = ['bin/fr2ical.py'], entry_points = """ [console_scripts] fr2ical = french_dates_to_ical.main:main """, keywords='python tools utils ical', license='GPL', classifiers=['Development Status :: 2 - Planning', 'Natural Language :: French', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Topic :: Text Processing :: Dates',
#setup_requires = ['python-stdeb', 'fakeroot', 'python-all'], install_requires = ['setuptools', 'docutils>=0.3', 'parsimonious', 'pytest'], )
],
random_line_split
unreachable_rule.rs
// Copyright 2018 Chao Lin & William Sergeant (Sorbonne University) // 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. #![macro_use] use std::char::*; use middle::analysis::ast::*; use self::Pattern::*; use self::Character::*; #[derive(Copy, Clone)] enum Pattern { // OneOrMore, // + // ZeroOrMore, // * // ZeroOrOne, // ? One, // And, // & // Not, // ! } #[derive(Copy, Clone)] enum Character{ Char(char), Any // . } struct Occurence { choice: Vec<Vec<(Character,Pattern)>> } impl Occurence { fn push_sequence(&self, other: Occurence) -> Occurence{ let mut res = vec![]; for choice1 in other.choice.clone(){ for choice2 in self.choice.clone(){ let mut tmp = choice2.clone(); for couple in choice1.clone(){ tmp.push(couple) } res.push(tmp) } } Occurence{ choice: res } } fn merge_choice(&self, other: Occurence) -> Occurence { let mut res = self.choice.clone(); for choice in other.choice.clone(){ res.push(choice) } Occurence{ choice: res } } fn copy(&self) -> Occurence{ Occurence{ choice: self.choice.to_vec() } } fn is_unreachable_with(&self, target: Occurence) -> bool { let mut res = true; for seq in self.choice.clone(){ if !(target.success_with(seq)) { res = false; break; } } res } fn success_with(&self, seq2: Vec<(Character, Pattern)>) -> bool { let mut res = false; for seq1 in self.choice.clone(){ if self.succeed_before(seq1,seq2.to_vec()) { res = true; } } res } fn succeed_before(&self, seq1: Vec<(Character, Pattern)>, seq2: Vec<(Character, Pattern)>) -> bool{ let mut res = true; if seq2.len()<seq1.len() { res=false; } else{ for (i,character_pattern1) in seq1.iter().enumerate(){ if let Some(character_pattern2) = seq2.get(i) { let &(c1,_p1) = character_pattern1; let &(c2,_p2) = character_pattern2; match c1 { Char(character1) => { match c2 { Char(character2) => { if character1!=character2 { res=false; break; } } Any => { res=false; break; } } } Any => { continue; } } } } } res } } pub struct UnreachableRule<'a: 'c, 'b: 'a, 'c> { grammar: &'c AGrammar<'a, 'b> } impl <'a, 'b, 'c> UnreachableRule<'a, 'b, 'c> { pub fn analyse(grammar: AGrammar<'a, 'b>) -> Partial<AGrammar<'a, 'b>> { UnreachableRule::check_unreachable_rule(&grammar); Partial::Value(grammar) } fn check_unreachable_rule(grammar: &'c AGrammar<'a, 'b>){ let mut analyser = UnreachableRule{ grammar: grammar }; for rule in &grammar.rules { analyser.visit_expr(rule.expr_idx); } } } impl<'a, 'b, 'c> ExprByIndex for UnreachableRule<'a, 'b, 'c> { fn expr_by_index(&self, index: usize) -> Expression { self.grammar.expr_by_index(index).clone() } } impl<'a, 'b, 'c> Visitor<Occurence> for UnreachableRule<'a, 'b, 'c> { fn visit_choice(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut occurences_of_children = vec![]; for child in children.clone(){ let occ = self.visit_expr(child); if !occ.choice.is_empty() { occurences_of_children.push((occ,child)); } } for (i, cp1) in occurences_of_children.iter().enumerate(){ let (_left, right) = occurences_of_children.split_at(i+1); let &(ref occ1, child1) = cp1; for cp2 in right{ let &(ref occ2, child2) = cp2; if occ2.is_unreachable_with(occ1.copy()) { self.grammar.span_warn( self.grammar[child2].span(), format!("This alternative will nerver succeed.") ); self.grammar.span_note( self.grammar[child1].span(), format!("Because this alternative succeeded before reaching the previous one.") ); } } } let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.merge_choice(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_sequence(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.push_sequence(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_atom(&mut self, _this: usize) -> Occurence
fn visit_str_literal(&mut self, _this: usize, lit: String) -> Occurence{ let mut seq = vec![]; for c in lit.chars(){ seq.push((Char(c),One)) } let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_any_single_char(&mut self, _this: usize) -> Occurence{ let mut seq = vec![]; seq.push((Any,One)); let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_character_class(&mut self, _this: usize, char_class: CharacterClassExpr) -> Occurence{ let mut res = vec![]; for intervals in char_class.intervals{ for i in intervals.lo as u32 .. intervals.hi as u32 +1 { if let Some(c) = from_u32(i) { res.push(vec![(Char(c),One)]) } } } Occurence{ choice: res } } fn visit_non_terminal_symbol(&mut self, _this: usize, _rule: Ident) -> Occurence{ Occurence{ choice: vec![] } } fn visit_zero_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_one_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_optional(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_not_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_and_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } }
{ Occurence{ choice: vec![] } }
identifier_body
unreachable_rule.rs
// Copyright 2018 Chao Lin & William Sergeant (Sorbonne University) // 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. #![macro_use] use std::char::*; use middle::analysis::ast::*; use self::Pattern::*; use self::Character::*; #[derive(Copy, Clone)] enum Pattern { // OneOrMore, // + // ZeroOrMore, // * // ZeroOrOne, // ? One, // And, // & // Not, // ! } #[derive(Copy, Clone)] enum Character{ Char(char), Any // . } struct Occurence { choice: Vec<Vec<(Character,Pattern)>> } impl Occurence { fn push_sequence(&self, other: Occurence) -> Occurence{ let mut res = vec![]; for choice1 in other.choice.clone(){ for choice2 in self.choice.clone(){ let mut tmp = choice2.clone(); for couple in choice1.clone(){ tmp.push(couple) } res.push(tmp) } } Occurence{ choice: res } } fn merge_choice(&self, other: Occurence) -> Occurence { let mut res = self.choice.clone(); for choice in other.choice.clone(){ res.push(choice) } Occurence{ choice: res } } fn copy(&self) -> Occurence{ Occurence{ choice: self.choice.to_vec() } } fn is_unreachable_with(&self, target: Occurence) -> bool { let mut res = true; for seq in self.choice.clone(){ if !(target.success_with(seq)) { res = false; break; } } res } fn success_with(&self, seq2: Vec<(Character, Pattern)>) -> bool { let mut res = false; for seq1 in self.choice.clone(){ if self.succeed_before(seq1,seq2.to_vec()) { res = true; } } res } fn succeed_before(&self, seq1: Vec<(Character, Pattern)>, seq2: Vec<(Character, Pattern)>) -> bool{ let mut res = true; if seq2.len()<seq1.len() { res=false; } else{ for (i,character_pattern1) in seq1.iter().enumerate(){ if let Some(character_pattern2) = seq2.get(i) { let &(c1,_p1) = character_pattern1; let &(c2,_p2) = character_pattern2; match c1 { Char(character1) => { match c2 { Char(character2) => { if character1!=character2 { res=false; break; } } Any => { res=false; break; } } } Any => { continue; } } } } } res } } pub struct UnreachableRule<'a: 'c, 'b: 'a, 'c> { grammar: &'c AGrammar<'a, 'b> } impl <'a, 'b, 'c> UnreachableRule<'a, 'b, 'c> { pub fn analyse(grammar: AGrammar<'a, 'b>) -> Partial<AGrammar<'a, 'b>> { UnreachableRule::check_unreachable_rule(&grammar); Partial::Value(grammar) } fn check_unreachable_rule(grammar: &'c AGrammar<'a, 'b>){ let mut analyser = UnreachableRule{ grammar: grammar }; for rule in &grammar.rules { analyser.visit_expr(rule.expr_idx); } } } impl<'a, 'b, 'c> ExprByIndex for UnreachableRule<'a, 'b, 'c> { fn expr_by_index(&self, index: usize) -> Expression { self.grammar.expr_by_index(index).clone() } } impl<'a, 'b, 'c> Visitor<Occurence> for UnreachableRule<'a, 'b, 'c> { fn visit_choice(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut occurences_of_children = vec![]; for child in children.clone(){ let occ = self.visit_expr(child); if !occ.choice.is_empty() { occurences_of_children.push((occ,child)); } } for (i, cp1) in occurences_of_children.iter().enumerate(){ let (_left, right) = occurences_of_children.split_at(i+1); let &(ref occ1, child1) = cp1; for cp2 in right{ let &(ref occ2, child2) = cp2; if occ2.is_unreachable_with(occ1.copy()) { self.grammar.span_warn( self.grammar[child2].span(), format!("This alternative will nerver succeed.") ); self.grammar.span_note( self.grammar[child1].span(), format!("Because this alternative succeeded before reaching the previous one.") ); } } } let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.merge_choice(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_sequence(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.push_sequence(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_atom(&mut self, _this: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_str_literal(&mut self, _this: usize, lit: String) -> Occurence{ let mut seq = vec![]; for c in lit.chars(){ seq.push((Char(c),One)) } let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_any_single_char(&mut self, _this: usize) -> Occurence{ let mut seq = vec![]; seq.push((Any,One)); let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_character_class(&mut self, _this: usize, char_class: CharacterClassExpr) -> Occurence{ let mut res = vec![]; for intervals in char_class.intervals{ for i in intervals.lo as u32 .. intervals.hi as u32 +1 { if let Some(c) = from_u32(i) { res.push(vec![(Char(c),One)]) } } } Occurence{ choice: res } } fn visit_non_terminal_symbol(&mut self, _this: usize, _rule: Ident) -> Occurence{ Occurence{ choice: vec![] }
Occurence{ choice: vec![] } } fn visit_one_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_optional(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_not_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_and_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } }
} fn visit_zero_or_more(&mut self, _this: usize, _child: usize) -> Occurence{
random_line_split
unreachable_rule.rs
// Copyright 2018 Chao Lin & William Sergeant (Sorbonne University) // 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. #![macro_use] use std::char::*; use middle::analysis::ast::*; use self::Pattern::*; use self::Character::*; #[derive(Copy, Clone)] enum Pattern { // OneOrMore, // + // ZeroOrMore, // * // ZeroOrOne, // ? One, // And, // & // Not, // ! } #[derive(Copy, Clone)] enum Character{ Char(char), Any // . } struct Occurence { choice: Vec<Vec<(Character,Pattern)>> } impl Occurence { fn push_sequence(&self, other: Occurence) -> Occurence{ let mut res = vec![]; for choice1 in other.choice.clone(){ for choice2 in self.choice.clone(){ let mut tmp = choice2.clone(); for couple in choice1.clone(){ tmp.push(couple) } res.push(tmp) } } Occurence{ choice: res } } fn merge_choice(&self, other: Occurence) -> Occurence { let mut res = self.choice.clone(); for choice in other.choice.clone(){ res.push(choice) } Occurence{ choice: res } } fn copy(&self) -> Occurence{ Occurence{ choice: self.choice.to_vec() } } fn is_unreachable_with(&self, target: Occurence) -> bool { let mut res = true; for seq in self.choice.clone(){ if !(target.success_with(seq))
} res } fn success_with(&self, seq2: Vec<(Character, Pattern)>) -> bool { let mut res = false; for seq1 in self.choice.clone(){ if self.succeed_before(seq1,seq2.to_vec()) { res = true; } } res } fn succeed_before(&self, seq1: Vec<(Character, Pattern)>, seq2: Vec<(Character, Pattern)>) -> bool{ let mut res = true; if seq2.len()<seq1.len() { res=false; } else{ for (i,character_pattern1) in seq1.iter().enumerate(){ if let Some(character_pattern2) = seq2.get(i) { let &(c1,_p1) = character_pattern1; let &(c2,_p2) = character_pattern2; match c1 { Char(character1) => { match c2 { Char(character2) => { if character1!=character2 { res=false; break; } } Any => { res=false; break; } } } Any => { continue; } } } } } res } } pub struct UnreachableRule<'a: 'c, 'b: 'a, 'c> { grammar: &'c AGrammar<'a, 'b> } impl <'a, 'b, 'c> UnreachableRule<'a, 'b, 'c> { pub fn analyse(grammar: AGrammar<'a, 'b>) -> Partial<AGrammar<'a, 'b>> { UnreachableRule::check_unreachable_rule(&grammar); Partial::Value(grammar) } fn check_unreachable_rule(grammar: &'c AGrammar<'a, 'b>){ let mut analyser = UnreachableRule{ grammar: grammar }; for rule in &grammar.rules { analyser.visit_expr(rule.expr_idx); } } } impl<'a, 'b, 'c> ExprByIndex for UnreachableRule<'a, 'b, 'c> { fn expr_by_index(&self, index: usize) -> Expression { self.grammar.expr_by_index(index).clone() } } impl<'a, 'b, 'c> Visitor<Occurence> for UnreachableRule<'a, 'b, 'c> { fn visit_choice(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut occurences_of_children = vec![]; for child in children.clone(){ let occ = self.visit_expr(child); if !occ.choice.is_empty() { occurences_of_children.push((occ,child)); } } for (i, cp1) in occurences_of_children.iter().enumerate(){ let (_left, right) = occurences_of_children.split_at(i+1); let &(ref occ1, child1) = cp1; for cp2 in right{ let &(ref occ2, child2) = cp2; if occ2.is_unreachable_with(occ1.copy()) { self.grammar.span_warn( self.grammar[child2].span(), format!("This alternative will nerver succeed.") ); self.grammar.span_note( self.grammar[child1].span(), format!("Because this alternative succeeded before reaching the previous one.") ); } } } let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.merge_choice(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_sequence(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.push_sequence(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_atom(&mut self, _this: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_str_literal(&mut self, _this: usize, lit: String) -> Occurence{ let mut seq = vec![]; for c in lit.chars(){ seq.push((Char(c),One)) } let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_any_single_char(&mut self, _this: usize) -> Occurence{ let mut seq = vec![]; seq.push((Any,One)); let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_character_class(&mut self, _this: usize, char_class: CharacterClassExpr) -> Occurence{ let mut res = vec![]; for intervals in char_class.intervals{ for i in intervals.lo as u32 .. intervals.hi as u32 +1 { if let Some(c) = from_u32(i) { res.push(vec![(Char(c),One)]) } } } Occurence{ choice: res } } fn visit_non_terminal_symbol(&mut self, _this: usize, _rule: Ident) -> Occurence{ Occurence{ choice: vec![] } } fn visit_zero_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_one_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_optional(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_not_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_and_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } }
{ res = false; break; }
conditional_block
unreachable_rule.rs
// Copyright 2018 Chao Lin & William Sergeant (Sorbonne University) // 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. #![macro_use] use std::char::*; use middle::analysis::ast::*; use self::Pattern::*; use self::Character::*; #[derive(Copy, Clone)] enum Pattern { // OneOrMore, // + // ZeroOrMore, // * // ZeroOrOne, // ? One, // And, // & // Not, // ! } #[derive(Copy, Clone)] enum Character{ Char(char), Any // . } struct Occurence { choice: Vec<Vec<(Character,Pattern)>> } impl Occurence { fn push_sequence(&self, other: Occurence) -> Occurence{ let mut res = vec![]; for choice1 in other.choice.clone(){ for choice2 in self.choice.clone(){ let mut tmp = choice2.clone(); for couple in choice1.clone(){ tmp.push(couple) } res.push(tmp) } } Occurence{ choice: res } } fn merge_choice(&self, other: Occurence) -> Occurence { let mut res = self.choice.clone(); for choice in other.choice.clone(){ res.push(choice) } Occurence{ choice: res } } fn copy(&self) -> Occurence{ Occurence{ choice: self.choice.to_vec() } } fn is_unreachable_with(&self, target: Occurence) -> bool { let mut res = true; for seq in self.choice.clone(){ if !(target.success_with(seq)) { res = false; break; } } res } fn success_with(&self, seq2: Vec<(Character, Pattern)>) -> bool { let mut res = false; for seq1 in self.choice.clone(){ if self.succeed_before(seq1,seq2.to_vec()) { res = true; } } res } fn succeed_before(&self, seq1: Vec<(Character, Pattern)>, seq2: Vec<(Character, Pattern)>) -> bool{ let mut res = true; if seq2.len()<seq1.len() { res=false; } else{ for (i,character_pattern1) in seq1.iter().enumerate(){ if let Some(character_pattern2) = seq2.get(i) { let &(c1,_p1) = character_pattern1; let &(c2,_p2) = character_pattern2; match c1 { Char(character1) => { match c2 { Char(character2) => { if character1!=character2 { res=false; break; } } Any => { res=false; break; } } } Any => { continue; } } } } } res } } pub struct UnreachableRule<'a: 'c, 'b: 'a, 'c> { grammar: &'c AGrammar<'a, 'b> } impl <'a, 'b, 'c> UnreachableRule<'a, 'b, 'c> { pub fn analyse(grammar: AGrammar<'a, 'b>) -> Partial<AGrammar<'a, 'b>> { UnreachableRule::check_unreachable_rule(&grammar); Partial::Value(grammar) } fn check_unreachable_rule(grammar: &'c AGrammar<'a, 'b>){ let mut analyser = UnreachableRule{ grammar: grammar }; for rule in &grammar.rules { analyser.visit_expr(rule.expr_idx); } } } impl<'a, 'b, 'c> ExprByIndex for UnreachableRule<'a, 'b, 'c> { fn expr_by_index(&self, index: usize) -> Expression { self.grammar.expr_by_index(index).clone() } } impl<'a, 'b, 'c> Visitor<Occurence> for UnreachableRule<'a, 'b, 'c> { fn visit_choice(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut occurences_of_children = vec![]; for child in children.clone(){ let occ = self.visit_expr(child); if !occ.choice.is_empty() { occurences_of_children.push((occ,child)); } } for (i, cp1) in occurences_of_children.iter().enumerate(){ let (_left, right) = occurences_of_children.split_at(i+1); let &(ref occ1, child1) = cp1; for cp2 in right{ let &(ref occ2, child2) = cp2; if occ2.is_unreachable_with(occ1.copy()) { self.grammar.span_warn( self.grammar[child2].span(), format!("This alternative will nerver succeed.") ); self.grammar.span_note( self.grammar[child1].span(), format!("Because this alternative succeeded before reaching the previous one.") ); } } } let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.merge_choice(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_sequence(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.push_sequence(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_atom(&mut self, _this: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_str_literal(&mut self, _this: usize, lit: String) -> Occurence{ let mut seq = vec![]; for c in lit.chars(){ seq.push((Char(c),One)) } let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_any_single_char(&mut self, _this: usize) -> Occurence{ let mut seq = vec![]; seq.push((Any,One)); let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_character_class(&mut self, _this: usize, char_class: CharacterClassExpr) -> Occurence{ let mut res = vec![]; for intervals in char_class.intervals{ for i in intervals.lo as u32 .. intervals.hi as u32 +1 { if let Some(c) = from_u32(i) { res.push(vec![(Char(c),One)]) } } } Occurence{ choice: res } } fn
(&mut self, _this: usize, _rule: Ident) -> Occurence{ Occurence{ choice: vec![] } } fn visit_zero_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_one_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_optional(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_not_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_and_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } }
visit_non_terminal_symbol
identifier_name
wrapped_mesh.py
# Copyright (C) 2011-2015 Claas Abert # # This file is part of magnum.fe. # # magnum.fe is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # magnum.fe 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with magnum.fe. If not, see <http://www.gnu.org/licenses/>. # # Last modified by Claas Abert, 2015-06-29 from __future__ import absolute_import from dolfin import Function, MeshFunction, Mesh, SubMesh, CellFunction, FunctionSpaceBase, interpolate import numpy as np __all__ = ["WrappedMesh"] class WrappedMesh(Mesh): def __init__(self, *args, **kwargs): """ This class represents a mesh with a certain submesh and defines methods for the fast interpolation between the two meshes. """ super(WrappedMesh, self).__init__(*args, **kwargs) def _init(self, mesh_with_shell): """ Initialize the mesh instance. *Arguments* mesh_with_shell (:class:`dolfin.Mesh`) The super mesh """ self.with_shell = mesh_with_shell # Cache DOF mappings # The signature of the element is used as key self._mappings = {} def cut(self, f, **kwargs): """ Takes a function defined on the super mesh and returns a truncated function defined on the sub mesh. *Arguments* f (:class:`dolfin.Function`) The function on the super mesh. *Returns* :class:`dolfin.Function` The function on the sub mesh. """ mapping = self._get_mapping(f.function_space()) result = Function(mapping['Vsub']) result.vector()[:] = f.vector().array()[mapping['map']] result.rename(f.name(), f.label()) return result def expand(self, f, target = None): """ Takes a function defined on the sub mesh and returns a function defined on the super mesh with unknown values set to zero. *Arguments* f (:class:`dolfin.Function`) The function on the sub mesh. *Returns* The function on the super mesh. """ mapping = self._get_mapping(f.function_space()) if target is None: target = Function(mapping['Vsuper']) target.rename(f.name(), f.label()) target.vector()[mapping['map']] = f.vector().array() return target def _get_mapping(self, V): element = V.ufl_element() key = V.element().signature() if not self._mappings.has_key(key): Vsub = FunctionSpaceBase(self, element) Vsuper = FunctionSpaceBase(self.with_shell, element) fsuper = Function(Vsuper) fsuper.vector()[:] = np.arange(fsuper.vector().size(), dtype=float) fsub = interpolate(fsuper, Vsub) self._mappings[key] = { 'map': np.round(fsub.vector().array()).astype(np.uint64), 'Vsub': Vsub, 'Vsuper': Vsuper } return self._mappings[key] @staticmethod def create(mesh, domain_ids, invert=False): """ Creates a wrapped mesh from a super mesh for a given collection of domain IDs. *Arguments* mesh (:class:`dolfin.Mesh`) The mesh. domain_ids (:class:`[int]`) List of domain IDs invert (:class:`bool`) Invert list of domain IDs *Returns* :class:`WrappedMesh` The wrapped mesh """ if invert or isinstance(domain_ids, list) or isinstance(domain_ids, tuple): if isinstance(domain_ids, int): domain_ids = (domain_ids,) subdomains = MeshFunction('size_t', mesh, 3, mesh.domains()) combined_subdomains = CellFunction("size_t", mesh, 0) for domain_id in domain_ids: combined_subdomains.array()[subdomains.array() == domain_id] = 1 submesh = SubMesh(mesh, combined_subdomains, 0 if invert else 1) else:
submesh.__class__ = WrappedMesh submesh._init(mesh) return submesh
submesh = SubMesh(mesh, domain_ids)
conditional_block
wrapped_mesh.py
# Copyright (C) 2011-2015 Claas Abert # # This file is part of magnum.fe. # # magnum.fe is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # magnum.fe 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with magnum.fe. If not, see <http://www.gnu.org/licenses/>. # # Last modified by Claas Abert, 2015-06-29 from __future__ import absolute_import from dolfin import Function, MeshFunction, Mesh, SubMesh, CellFunction, FunctionSpaceBase, interpolate import numpy as np __all__ = ["WrappedMesh"] class WrappedMesh(Mesh): def __init__(self, *args, **kwargs): """ This class represents a mesh with a certain submesh and defines methods for the fast interpolation between the two meshes. """ super(WrappedMesh, self).__init__(*args, **kwargs) def _init(self, mesh_with_shell): """ Initialize the mesh instance. *Arguments* mesh_with_shell (:class:`dolfin.Mesh`) The super mesh """ self.with_shell = mesh_with_shell # Cache DOF mappings # The signature of the element is used as key self._mappings = {} def
(self, f, **kwargs): """ Takes a function defined on the super mesh and returns a truncated function defined on the sub mesh. *Arguments* f (:class:`dolfin.Function`) The function on the super mesh. *Returns* :class:`dolfin.Function` The function on the sub mesh. """ mapping = self._get_mapping(f.function_space()) result = Function(mapping['Vsub']) result.vector()[:] = f.vector().array()[mapping['map']] result.rename(f.name(), f.label()) return result def expand(self, f, target = None): """ Takes a function defined on the sub mesh and returns a function defined on the super mesh with unknown values set to zero. *Arguments* f (:class:`dolfin.Function`) The function on the sub mesh. *Returns* The function on the super mesh. """ mapping = self._get_mapping(f.function_space()) if target is None: target = Function(mapping['Vsuper']) target.rename(f.name(), f.label()) target.vector()[mapping['map']] = f.vector().array() return target def _get_mapping(self, V): element = V.ufl_element() key = V.element().signature() if not self._mappings.has_key(key): Vsub = FunctionSpaceBase(self, element) Vsuper = FunctionSpaceBase(self.with_shell, element) fsuper = Function(Vsuper) fsuper.vector()[:] = np.arange(fsuper.vector().size(), dtype=float) fsub = interpolate(fsuper, Vsub) self._mappings[key] = { 'map': np.round(fsub.vector().array()).astype(np.uint64), 'Vsub': Vsub, 'Vsuper': Vsuper } return self._mappings[key] @staticmethod def create(mesh, domain_ids, invert=False): """ Creates a wrapped mesh from a super mesh for a given collection of domain IDs. *Arguments* mesh (:class:`dolfin.Mesh`) The mesh. domain_ids (:class:`[int]`) List of domain IDs invert (:class:`bool`) Invert list of domain IDs *Returns* :class:`WrappedMesh` The wrapped mesh """ if invert or isinstance(domain_ids, list) or isinstance(domain_ids, tuple): if isinstance(domain_ids, int): domain_ids = (domain_ids,) subdomains = MeshFunction('size_t', mesh, 3, mesh.domains()) combined_subdomains = CellFunction("size_t", mesh, 0) for domain_id in domain_ids: combined_subdomains.array()[subdomains.array() == domain_id] = 1 submesh = SubMesh(mesh, combined_subdomains, 0 if invert else 1) else: submesh = SubMesh(mesh, domain_ids) submesh.__class__ = WrappedMesh submesh._init(mesh) return submesh
cut
identifier_name
wrapped_mesh.py
# Copyright (C) 2011-2015 Claas Abert # # This file is part of magnum.fe. # # magnum.fe is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # magnum.fe 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with magnum.fe. If not, see <http://www.gnu.org/licenses/>. # # Last modified by Claas Abert, 2015-06-29 from __future__ import absolute_import from dolfin import Function, MeshFunction, Mesh, SubMesh, CellFunction, FunctionSpaceBase, interpolate import numpy as np __all__ = ["WrappedMesh"] class WrappedMesh(Mesh): def __init__(self, *args, **kwargs): """ This class represents a mesh with a certain submesh and defines methods for the fast interpolation between the two meshes. """ super(WrappedMesh, self).__init__(*args, **kwargs) def _init(self, mesh_with_shell): """ Initialize the mesh instance. *Arguments* mesh_with_shell (:class:`dolfin.Mesh`) The super mesh """ self.with_shell = mesh_with_shell # Cache DOF mappings # The signature of the element is used as key self._mappings = {} def cut(self, f, **kwargs): """ Takes a function defined on the super mesh and returns a truncated function defined on the sub mesh. *Arguments* f (:class:`dolfin.Function`) The function on the super mesh. *Returns* :class:`dolfin.Function` The function on the sub mesh. """ mapping = self._get_mapping(f.function_space()) result = Function(mapping['Vsub']) result.vector()[:] = f.vector().array()[mapping['map']] result.rename(f.name(), f.label()) return result def expand(self, f, target = None): """ Takes a function defined on the sub mesh and returns a function defined on the super mesh with unknown values set to zero. *Arguments* f (:class:`dolfin.Function`) The function on the sub mesh. *Returns* The function on the super mesh. """ mapping = self._get_mapping(f.function_space()) if target is None: target = Function(mapping['Vsuper']) target.rename(f.name(), f.label()) target.vector()[mapping['map']] = f.vector().array() return target def _get_mapping(self, V): element = V.ufl_element() key = V.element().signature() if not self._mappings.has_key(key): Vsub = FunctionSpaceBase(self, element) Vsuper = FunctionSpaceBase(self.with_shell, element) fsuper = Function(Vsuper) fsuper.vector()[:] = np.arange(fsuper.vector().size(), dtype=float) fsub = interpolate(fsuper, Vsub) self._mappings[key] = { 'map': np.round(fsub.vector().array()).astype(np.uint64), 'Vsub': Vsub, 'Vsuper': Vsuper } return self._mappings[key] @staticmethod def create(mesh, domain_ids, invert=False): """ Creates a wrapped mesh from a super mesh for a given collection of domain IDs. *Arguments* mesh (:class:`dolfin.Mesh`) The mesh. domain_ids (:class:`[int]`) List of domain IDs invert (:class:`bool`)
Invert list of domain IDs *Returns* :class:`WrappedMesh` The wrapped mesh """ if invert or isinstance(domain_ids, list) or isinstance(domain_ids, tuple): if isinstance(domain_ids, int): domain_ids = (domain_ids,) subdomains = MeshFunction('size_t', mesh, 3, mesh.domains()) combined_subdomains = CellFunction("size_t", mesh, 0) for domain_id in domain_ids: combined_subdomains.array()[subdomains.array() == domain_id] = 1 submesh = SubMesh(mesh, combined_subdomains, 0 if invert else 1) else: submesh = SubMesh(mesh, domain_ids) submesh.__class__ = WrappedMesh submesh._init(mesh) return submesh
random_line_split
wrapped_mesh.py
# Copyright (C) 2011-2015 Claas Abert # # This file is part of magnum.fe. # # magnum.fe is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # magnum.fe 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with magnum.fe. If not, see <http://www.gnu.org/licenses/>. # # Last modified by Claas Abert, 2015-06-29 from __future__ import absolute_import from dolfin import Function, MeshFunction, Mesh, SubMesh, CellFunction, FunctionSpaceBase, interpolate import numpy as np __all__ = ["WrappedMesh"] class WrappedMesh(Mesh): def __init__(self, *args, **kwargs): """ This class represents a mesh with a certain submesh and defines methods for the fast interpolation between the two meshes. """ super(WrappedMesh, self).__init__(*args, **kwargs) def _init(self, mesh_with_shell): """ Initialize the mesh instance. *Arguments* mesh_with_shell (:class:`dolfin.Mesh`) The super mesh """ self.with_shell = mesh_with_shell # Cache DOF mappings # The signature of the element is used as key self._mappings = {} def cut(self, f, **kwargs): """ Takes a function defined on the super mesh and returns a truncated function defined on the sub mesh. *Arguments* f (:class:`dolfin.Function`) The function on the super mesh. *Returns* :class:`dolfin.Function` The function on the sub mesh. """ mapping = self._get_mapping(f.function_space()) result = Function(mapping['Vsub']) result.vector()[:] = f.vector().array()[mapping['map']] result.rename(f.name(), f.label()) return result def expand(self, f, target = None): """ Takes a function defined on the sub mesh and returns a function defined on the super mesh with unknown values set to zero. *Arguments* f (:class:`dolfin.Function`) The function on the sub mesh. *Returns* The function on the super mesh. """ mapping = self._get_mapping(f.function_space()) if target is None: target = Function(mapping['Vsuper']) target.rename(f.name(), f.label()) target.vector()[mapping['map']] = f.vector().array() return target def _get_mapping(self, V): element = V.ufl_element() key = V.element().signature() if not self._mappings.has_key(key): Vsub = FunctionSpaceBase(self, element) Vsuper = FunctionSpaceBase(self.with_shell, element) fsuper = Function(Vsuper) fsuper.vector()[:] = np.arange(fsuper.vector().size(), dtype=float) fsub = interpolate(fsuper, Vsub) self._mappings[key] = { 'map': np.round(fsub.vector().array()).astype(np.uint64), 'Vsub': Vsub, 'Vsuper': Vsuper } return self._mappings[key] @staticmethod def create(mesh, domain_ids, invert=False):
""" Creates a wrapped mesh from a super mesh for a given collection of domain IDs. *Arguments* mesh (:class:`dolfin.Mesh`) The mesh. domain_ids (:class:`[int]`) List of domain IDs invert (:class:`bool`) Invert list of domain IDs *Returns* :class:`WrappedMesh` The wrapped mesh """ if invert or isinstance(domain_ids, list) or isinstance(domain_ids, tuple): if isinstance(domain_ids, int): domain_ids = (domain_ids,) subdomains = MeshFunction('size_t', mesh, 3, mesh.domains()) combined_subdomains = CellFunction("size_t", mesh, 0) for domain_id in domain_ids: combined_subdomains.array()[subdomains.array() == domain_id] = 1 submesh = SubMesh(mesh, combined_subdomains, 0 if invert else 1) else: submesh = SubMesh(mesh, domain_ids) submesh.__class__ = WrappedMesh submesh._init(mesh) return submesh
identifier_body
stenciledsum.py
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np def subarray_multislice(array_ndim, fixed_axes, indices): ''' Return tuple of slices that if indexed into an array with given dimensions will return subarray with the axes in axes fixed at given indices ''' indices = np.array(indices) colon = slice(None, None, None) multislice = () for i in range(array_ndim): if i in fixed_axes: multislice = multislice + \ (indices[np.where(fixed_axes == i)[0][0]],) else: multislice = multislice + (colon,) return multislice def subarray_view(array, fixed_axes, indices, checks=True):
# Coerce the inputs into flat numpy arrays to allow for easy handling # of a variety of input types fixed_axes = np.atleast_1d(np.array(fixed_axes)).flatten() indices = np.atleast_1d(np.array(indices)).flatten() check_axes_access(fixed_axes, array.ndim) convert_axes_to_positive(fixed_axes, array.ndim) if fixed_axes.shape != indices.shape: raise ValueError('axes and indices must have matching shapes or' ' both be integers') return array[subarray_multislice(array.ndim, fixed_axes, indices)] def subrange_view(array, starts, ends, steps=None, checks=True): ''' Return view of array with each axes indexed between starts and ends. ''' if checks: # Coerce the inputs into flat numpy arrays to allow for easy handling # of a variety of input types starts = np.atleast_1d(np.array(starts)).flatten() ends = np.atleast_1d(np.array(ends)).flatten() if steps is not None: steps = np.atleast_1d(np.array(steps)).flatten() # Check number of array axes matches up with starts and ends if (array.ndim != starts.size) or (array.ndim != ends.size): raise ValueError('the size of starts and ends must equal the ' 'number of array dimensions') multislice = () # If steps is None, default to step size of 1 if steps is None: for i in range(array.ndim): multislice = multislice + (slice(starts[i], ends[i], 1),) else: for i in range(array.ndim): multislice = multislice + (slice(starts[i], ends[i], steps[i]),) return array[multislice] def check_axes_access(axes, array_ndim): if np.max(axes) >= array_ndim or np.min(axes) < -array_ndim: raise IndexError('too many indices for array') # regular numpy scheme for which positive index a negative index corresponds to def convert_axes_to_positive(axes, array_ndim): for index, element in enumerate(axes): if element < 0: axes[index] = element + array_ndim def correct_stencil_shape(array_ndim, axes, summed_axes_shape): return np.hstack([np.array(summed_axes_shape), np.array(array_ndim - len(axes))]) def check_stencil_shape(array_ndim, axes, summed_axes_shape, stencil): if not np.all(np.array(stencil.shape) == correct_stencil_shape(array_ndim, axes, summed_axes_shape)): raise ValueError('The shape of the stencil must match the big' ' array and axes appropriately') def stenciled_sum(array, summed_axes, stencil): summed_axes = np.atleast_1d(np.array(summed_axes)) summed_axes_shape = np.array(array.shape)[summed_axes] fixed_stencil_summer = fixedStencilSum(array.ndim, summed_axes, summed_axes_shape, stencil) return fixed_stencil_summer.stenciled_sum(array) class fixedStencilSum(object): def __init__(self, array_ndim, axes_summed_over, summed_axes_shape, stencil): axes = np.atleast_1d(np.array(axes_summed_over)).flatten() # check that inputs are compatible check_axes_access(axes, array_ndim) convert_axes_to_positive(axes, array_ndim) check_stencil_shape(array_ndim, axes, summed_axes_shape, stencil) # handle a trivial case where we sum the entire array into one number if array_ndim == len(axes): self.stenciled_sum = np.sum self.array_ndim = array_ndim self.axes = axes self.not_axes = [i for i in range(array_ndim) if i not in axes] self.summed_axes_shape = summed_axes_shape # left zero the stencil, ablsa is a tuple of indices into # "all but last stencil axis" ablsa = tuple(range(stencil.ndim-1)) stencil = stencil - np.amin(stencil, axis=ablsa) self.stencil = stencil self.input_expand = np.amax(stencil, axis=ablsa) - \ np.amin(stencil, axis=ablsa) self.stencil_loop_indices = [i for i in np.ndindex(stencil.shape[:-1])] self.multislices = [subarray_multislice(self.array_ndim, self.axes, indices) for indices in self.stencil_loop_indices] def stenciled_sum(self, big_array): subarray_shape = np.array(big_array.shape)[self.not_axes] return_array_shape = subarray_shape + self.input_expand return_array = np.zeros(return_array_shape, dtype=big_array.dtype) for indices, multislice in zip(self.stencil_loop_indices, self.multislices): starts = self.stencil[indices] ends = self.stencil[indices] + subarray_shape chunk_to_increase = subrange_view(return_array, starts, ends, checks=False) chunk_to_increase[:] += big_array[multislice] return return_array def __eq__(self, other): if isinstance(other, fixedStencilSum): is_equal = True for attribute in self.__dict__: is_equal = (np.all(np.equal(getattr(self, attribute), getattr(other, attribute)))) and is_equal return is_equal else: return NotImplemented
''' Return view of subarray of input array with fixed_axes at corresponding indices.''' if checks:
random_line_split
stenciledsum.py
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np def subarray_multislice(array_ndim, fixed_axes, indices): ''' Return tuple of slices that if indexed into an array with given dimensions will return subarray with the axes in axes fixed at given indices ''' indices = np.array(indices) colon = slice(None, None, None) multislice = () for i in range(array_ndim): if i in fixed_axes: multislice = multislice + \ (indices[np.where(fixed_axes == i)[0][0]],) else: multislice = multislice + (colon,) return multislice def subarray_view(array, fixed_axes, indices, checks=True): ''' Return view of subarray of input array with fixed_axes at corresponding indices.''' if checks: # Coerce the inputs into flat numpy arrays to allow for easy handling # of a variety of input types fixed_axes = np.atleast_1d(np.array(fixed_axes)).flatten() indices = np.atleast_1d(np.array(indices)).flatten() check_axes_access(fixed_axes, array.ndim) convert_axes_to_positive(fixed_axes, array.ndim) if fixed_axes.shape != indices.shape: raise ValueError('axes and indices must have matching shapes or' ' both be integers') return array[subarray_multislice(array.ndim, fixed_axes, indices)] def subrange_view(array, starts, ends, steps=None, checks=True):
def check_axes_access(axes, array_ndim): if np.max(axes) >= array_ndim or np.min(axes) < -array_ndim: raise IndexError('too many indices for array') # regular numpy scheme for which positive index a negative index corresponds to def convert_axes_to_positive(axes, array_ndim): for index, element in enumerate(axes): if element < 0: axes[index] = element + array_ndim def correct_stencil_shape(array_ndim, axes, summed_axes_shape): return np.hstack([np.array(summed_axes_shape), np.array(array_ndim - len(axes))]) def check_stencil_shape(array_ndim, axes, summed_axes_shape, stencil): if not np.all(np.array(stencil.shape) == correct_stencil_shape(array_ndim, axes, summed_axes_shape)): raise ValueError('The shape of the stencil must match the big' ' array and axes appropriately') def stenciled_sum(array, summed_axes, stencil): summed_axes = np.atleast_1d(np.array(summed_axes)) summed_axes_shape = np.array(array.shape)[summed_axes] fixed_stencil_summer = fixedStencilSum(array.ndim, summed_axes, summed_axes_shape, stencil) return fixed_stencil_summer.stenciled_sum(array) class fixedStencilSum(object): def __init__(self, array_ndim, axes_summed_over, summed_axes_shape, stencil): axes = np.atleast_1d(np.array(axes_summed_over)).flatten() # check that inputs are compatible check_axes_access(axes, array_ndim) convert_axes_to_positive(axes, array_ndim) check_stencil_shape(array_ndim, axes, summed_axes_shape, stencil) # handle a trivial case where we sum the entire array into one number if array_ndim == len(axes): self.stenciled_sum = np.sum self.array_ndim = array_ndim self.axes = axes self.not_axes = [i for i in range(array_ndim) if i not in axes] self.summed_axes_shape = summed_axes_shape # left zero the stencil, ablsa is a tuple of indices into # "all but last stencil axis" ablsa = tuple(range(stencil.ndim-1)) stencil = stencil - np.amin(stencil, axis=ablsa) self.stencil = stencil self.input_expand = np.amax(stencil, axis=ablsa) - \ np.amin(stencil, axis=ablsa) self.stencil_loop_indices = [i for i in np.ndindex(stencil.shape[:-1])] self.multislices = [subarray_multislice(self.array_ndim, self.axes, indices) for indices in self.stencil_loop_indices] def stenciled_sum(self, big_array): subarray_shape = np.array(big_array.shape)[self.not_axes] return_array_shape = subarray_shape + self.input_expand return_array = np.zeros(return_array_shape, dtype=big_array.dtype) for indices, multislice in zip(self.stencil_loop_indices, self.multislices): starts = self.stencil[indices] ends = self.stencil[indices] + subarray_shape chunk_to_increase = subrange_view(return_array, starts, ends, checks=False) chunk_to_increase[:] += big_array[multislice] return return_array def __eq__(self, other): if isinstance(other, fixedStencilSum): is_equal = True for attribute in self.__dict__: is_equal = (np.all(np.equal(getattr(self, attribute), getattr(other, attribute)))) and is_equal return is_equal else: return NotImplemented
''' Return view of array with each axes indexed between starts and ends. ''' if checks: # Coerce the inputs into flat numpy arrays to allow for easy handling # of a variety of input types starts = np.atleast_1d(np.array(starts)).flatten() ends = np.atleast_1d(np.array(ends)).flatten() if steps is not None: steps = np.atleast_1d(np.array(steps)).flatten() # Check number of array axes matches up with starts and ends if (array.ndim != starts.size) or (array.ndim != ends.size): raise ValueError('the size of starts and ends must equal the ' 'number of array dimensions') multislice = () # If steps is None, default to step size of 1 if steps is None: for i in range(array.ndim): multislice = multislice + (slice(starts[i], ends[i], 1),) else: for i in range(array.ndim): multislice = multislice + (slice(starts[i], ends[i], steps[i]),) return array[multislice]
identifier_body
stenciledsum.py
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np def subarray_multislice(array_ndim, fixed_axes, indices): ''' Return tuple of slices that if indexed into an array with given dimensions will return subarray with the axes in axes fixed at given indices ''' indices = np.array(indices) colon = slice(None, None, None) multislice = () for i in range(array_ndim): if i in fixed_axes: multislice = multislice + \ (indices[np.where(fixed_axes == i)[0][0]],) else: multislice = multislice + (colon,) return multislice def subarray_view(array, fixed_axes, indices, checks=True): ''' Return view of subarray of input array with fixed_axes at corresponding indices.''' if checks: # Coerce the inputs into flat numpy arrays to allow for easy handling # of a variety of input types fixed_axes = np.atleast_1d(np.array(fixed_axes)).flatten() indices = np.atleast_1d(np.array(indices)).flatten() check_axes_access(fixed_axes, array.ndim) convert_axes_to_positive(fixed_axes, array.ndim) if fixed_axes.shape != indices.shape: raise ValueError('axes and indices must have matching shapes or' ' both be integers') return array[subarray_multislice(array.ndim, fixed_axes, indices)] def subrange_view(array, starts, ends, steps=None, checks=True): ''' Return view of array with each axes indexed between starts and ends. ''' if checks: # Coerce the inputs into flat numpy arrays to allow for easy handling # of a variety of input types starts = np.atleast_1d(np.array(starts)).flatten() ends = np.atleast_1d(np.array(ends)).flatten() if steps is not None: steps = np.atleast_1d(np.array(steps)).flatten() # Check number of array axes matches up with starts and ends if (array.ndim != starts.size) or (array.ndim != ends.size): raise ValueError('the size of starts and ends must equal the ' 'number of array dimensions') multislice = () # If steps is None, default to step size of 1 if steps is None: for i in range(array.ndim): multislice = multislice + (slice(starts[i], ends[i], 1),) else: for i in range(array.ndim): multislice = multislice + (slice(starts[i], ends[i], steps[i]),) return array[multislice] def check_axes_access(axes, array_ndim): if np.max(axes) >= array_ndim or np.min(axes) < -array_ndim: raise IndexError('too many indices for array') # regular numpy scheme for which positive index a negative index corresponds to def convert_axes_to_positive(axes, array_ndim): for index, element in enumerate(axes): if element < 0:
def correct_stencil_shape(array_ndim, axes, summed_axes_shape): return np.hstack([np.array(summed_axes_shape), np.array(array_ndim - len(axes))]) def check_stencil_shape(array_ndim, axes, summed_axes_shape, stencil): if not np.all(np.array(stencil.shape) == correct_stencil_shape(array_ndim, axes, summed_axes_shape)): raise ValueError('The shape of the stencil must match the big' ' array and axes appropriately') def stenciled_sum(array, summed_axes, stencil): summed_axes = np.atleast_1d(np.array(summed_axes)) summed_axes_shape = np.array(array.shape)[summed_axes] fixed_stencil_summer = fixedStencilSum(array.ndim, summed_axes, summed_axes_shape, stencil) return fixed_stencil_summer.stenciled_sum(array) class fixedStencilSum(object): def __init__(self, array_ndim, axes_summed_over, summed_axes_shape, stencil): axes = np.atleast_1d(np.array(axes_summed_over)).flatten() # check that inputs are compatible check_axes_access(axes, array_ndim) convert_axes_to_positive(axes, array_ndim) check_stencil_shape(array_ndim, axes, summed_axes_shape, stencil) # handle a trivial case where we sum the entire array into one number if array_ndim == len(axes): self.stenciled_sum = np.sum self.array_ndim = array_ndim self.axes = axes self.not_axes = [i for i in range(array_ndim) if i not in axes] self.summed_axes_shape = summed_axes_shape # left zero the stencil, ablsa is a tuple of indices into # "all but last stencil axis" ablsa = tuple(range(stencil.ndim-1)) stencil = stencil - np.amin(stencil, axis=ablsa) self.stencil = stencil self.input_expand = np.amax(stencil, axis=ablsa) - \ np.amin(stencil, axis=ablsa) self.stencil_loop_indices = [i for i in np.ndindex(stencil.shape[:-1])] self.multislices = [subarray_multislice(self.array_ndim, self.axes, indices) for indices in self.stencil_loop_indices] def stenciled_sum(self, big_array): subarray_shape = np.array(big_array.shape)[self.not_axes] return_array_shape = subarray_shape + self.input_expand return_array = np.zeros(return_array_shape, dtype=big_array.dtype) for indices, multislice in zip(self.stencil_loop_indices, self.multislices): starts = self.stencil[indices] ends = self.stencil[indices] + subarray_shape chunk_to_increase = subrange_view(return_array, starts, ends, checks=False) chunk_to_increase[:] += big_array[multislice] return return_array def __eq__(self, other): if isinstance(other, fixedStencilSum): is_equal = True for attribute in self.__dict__: is_equal = (np.all(np.equal(getattr(self, attribute), getattr(other, attribute)))) and is_equal return is_equal else: return NotImplemented
axes[index] = element + array_ndim
conditional_block
stenciledsum.py
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np def subarray_multislice(array_ndim, fixed_axes, indices): ''' Return tuple of slices that if indexed into an array with given dimensions will return subarray with the axes in axes fixed at given indices ''' indices = np.array(indices) colon = slice(None, None, None) multislice = () for i in range(array_ndim): if i in fixed_axes: multislice = multislice + \ (indices[np.where(fixed_axes == i)[0][0]],) else: multislice = multislice + (colon,) return multislice def subarray_view(array, fixed_axes, indices, checks=True): ''' Return view of subarray of input array with fixed_axes at corresponding indices.''' if checks: # Coerce the inputs into flat numpy arrays to allow for easy handling # of a variety of input types fixed_axes = np.atleast_1d(np.array(fixed_axes)).flatten() indices = np.atleast_1d(np.array(indices)).flatten() check_axes_access(fixed_axes, array.ndim) convert_axes_to_positive(fixed_axes, array.ndim) if fixed_axes.shape != indices.shape: raise ValueError('axes and indices must have matching shapes or' ' both be integers') return array[subarray_multislice(array.ndim, fixed_axes, indices)] def subrange_view(array, starts, ends, steps=None, checks=True): ''' Return view of array with each axes indexed between starts and ends. ''' if checks: # Coerce the inputs into flat numpy arrays to allow for easy handling # of a variety of input types starts = np.atleast_1d(np.array(starts)).flatten() ends = np.atleast_1d(np.array(ends)).flatten() if steps is not None: steps = np.atleast_1d(np.array(steps)).flatten() # Check number of array axes matches up with starts and ends if (array.ndim != starts.size) or (array.ndim != ends.size): raise ValueError('the size of starts and ends must equal the ' 'number of array dimensions') multislice = () # If steps is None, default to step size of 1 if steps is None: for i in range(array.ndim): multislice = multislice + (slice(starts[i], ends[i], 1),) else: for i in range(array.ndim): multislice = multislice + (slice(starts[i], ends[i], steps[i]),) return array[multislice] def check_axes_access(axes, array_ndim): if np.max(axes) >= array_ndim or np.min(axes) < -array_ndim: raise IndexError('too many indices for array') # regular numpy scheme for which positive index a negative index corresponds to def convert_axes_to_positive(axes, array_ndim): for index, element in enumerate(axes): if element < 0: axes[index] = element + array_ndim def correct_stencil_shape(array_ndim, axes, summed_axes_shape): return np.hstack([np.array(summed_axes_shape), np.array(array_ndim - len(axes))]) def check_stencil_shape(array_ndim, axes, summed_axes_shape, stencil): if not np.all(np.array(stencil.shape) == correct_stencil_shape(array_ndim, axes, summed_axes_shape)): raise ValueError('The shape of the stencil must match the big' ' array and axes appropriately') def stenciled_sum(array, summed_axes, stencil): summed_axes = np.atleast_1d(np.array(summed_axes)) summed_axes_shape = np.array(array.shape)[summed_axes] fixed_stencil_summer = fixedStencilSum(array.ndim, summed_axes, summed_axes_shape, stencil) return fixed_stencil_summer.stenciled_sum(array) class fixedStencilSum(object): def
(self, array_ndim, axes_summed_over, summed_axes_shape, stencil): axes = np.atleast_1d(np.array(axes_summed_over)).flatten() # check that inputs are compatible check_axes_access(axes, array_ndim) convert_axes_to_positive(axes, array_ndim) check_stencil_shape(array_ndim, axes, summed_axes_shape, stencil) # handle a trivial case where we sum the entire array into one number if array_ndim == len(axes): self.stenciled_sum = np.sum self.array_ndim = array_ndim self.axes = axes self.not_axes = [i for i in range(array_ndim) if i not in axes] self.summed_axes_shape = summed_axes_shape # left zero the stencil, ablsa is a tuple of indices into # "all but last stencil axis" ablsa = tuple(range(stencil.ndim-1)) stencil = stencil - np.amin(stencil, axis=ablsa) self.stencil = stencil self.input_expand = np.amax(stencil, axis=ablsa) - \ np.amin(stencil, axis=ablsa) self.stencil_loop_indices = [i for i in np.ndindex(stencil.shape[:-1])] self.multislices = [subarray_multislice(self.array_ndim, self.axes, indices) for indices in self.stencil_loop_indices] def stenciled_sum(self, big_array): subarray_shape = np.array(big_array.shape)[self.not_axes] return_array_shape = subarray_shape + self.input_expand return_array = np.zeros(return_array_shape, dtype=big_array.dtype) for indices, multislice in zip(self.stencil_loop_indices, self.multislices): starts = self.stencil[indices] ends = self.stencil[indices] + subarray_shape chunk_to_increase = subrange_view(return_array, starts, ends, checks=False) chunk_to_increase[:] += big_array[multislice] return return_array def __eq__(self, other): if isinstance(other, fixedStencilSum): is_equal = True for attribute in self.__dict__: is_equal = (np.all(np.equal(getattr(self, attribute), getattr(other, attribute)))) and is_equal return is_equal else: return NotImplemented
__init__
identifier_name
parent-hoc.tsx
import * as React from 'react' import {isMobile, hoistNonReactStatic} from '../../util/container' export type OverlayParentProps = { getAttachmentRef?: () => React.Component<any> | null showingMenu: boolean setAttachmentRef: (arg0: React.Component<any> | null) => void setShowingMenu: (arg0: boolean) => void toggleShowingMenu: () => void } export type PropsWithOverlay<Props> = Props & OverlayParentProps export type PropsWithoutOverlay<Props> = Exclude<Props, OverlayParentProps> type OverlayParentState = { showingMenu: boolean } // This is deprecated. Use `Kb.usePopup instead.` const OverlayParentHOC = <Props extends {}>( ComposedComponent: React.ComponentType<PropsWithOverlay<Props>> ): React.ComponentType<PropsWithoutOverlay<Props>> => { class _OverlayParent extends React.Component<PropsWithoutOverlay<Props>, OverlayParentState> { state = {showingMenu: false} _ref: React.Component<any> | null = null setShowingMenu = (showingMenu: boolean) => this.setState(oldState => (oldState.showingMenu === showingMenu ? null : {showingMenu})) toggleShowingMenu = () => this.setState(oldState => ({showingMenu: !oldState.showingMenu})) setAttachmentRef = isMobile ? () => {} : (attachmentRef: React.Component<any> | null) => { this._ref = attachmentRef } getAttachmentRef = () => this._ref render()
} const OverlayParent: React.ComponentClass<PropsWithoutOverlay<Props>, OverlayParentState> = _OverlayParent OverlayParent.displayName = ComposedComponent.displayName || 'OverlayParent' hoistNonReactStatic(OverlayParent, ComposedComponent) return OverlayParent } export default OverlayParentHOC
{ return ( <ComposedComponent {...this.props} setShowingMenu={this.setShowingMenu} toggleShowingMenu={this.toggleShowingMenu} setAttachmentRef={this.setAttachmentRef} getAttachmentRef={this.getAttachmentRef} showingMenu={this.state.showingMenu} /> ) }
identifier_body
parent-hoc.tsx
import * as React from 'react' import {isMobile, hoistNonReactStatic} from '../../util/container' export type OverlayParentProps = { getAttachmentRef?: () => React.Component<any> | null showingMenu: boolean setAttachmentRef: (arg0: React.Component<any> | null) => void setShowingMenu: (arg0: boolean) => void toggleShowingMenu: () => void } export type PropsWithOverlay<Props> = Props & OverlayParentProps export type PropsWithoutOverlay<Props> = Exclude<Props, OverlayParentProps> type OverlayParentState = { showingMenu: boolean } // This is deprecated. Use `Kb.usePopup instead.` const OverlayParentHOC = <Props extends {}>( ComposedComponent: React.ComponentType<PropsWithOverlay<Props>> ): React.ComponentType<PropsWithoutOverlay<Props>> => { class _OverlayParent extends React.Component<PropsWithoutOverlay<Props>, OverlayParentState> { state = {showingMenu: false} _ref: React.Component<any> | null = null setShowingMenu = (showingMenu: boolean) => this.setState(oldState => (oldState.showingMenu === showingMenu ? null : {showingMenu}))
this._ref = attachmentRef } getAttachmentRef = () => this._ref render() { return ( <ComposedComponent {...this.props} setShowingMenu={this.setShowingMenu} toggleShowingMenu={this.toggleShowingMenu} setAttachmentRef={this.setAttachmentRef} getAttachmentRef={this.getAttachmentRef} showingMenu={this.state.showingMenu} /> ) } } const OverlayParent: React.ComponentClass<PropsWithoutOverlay<Props>, OverlayParentState> = _OverlayParent OverlayParent.displayName = ComposedComponent.displayName || 'OverlayParent' hoistNonReactStatic(OverlayParent, ComposedComponent) return OverlayParent } export default OverlayParentHOC
toggleShowingMenu = () => this.setState(oldState => ({showingMenu: !oldState.showingMenu})) setAttachmentRef = isMobile ? () => {} : (attachmentRef: React.Component<any> | null) => {
random_line_split
parent-hoc.tsx
import * as React from 'react' import {isMobile, hoistNonReactStatic} from '../../util/container' export type OverlayParentProps = { getAttachmentRef?: () => React.Component<any> | null showingMenu: boolean setAttachmentRef: (arg0: React.Component<any> | null) => void setShowingMenu: (arg0: boolean) => void toggleShowingMenu: () => void } export type PropsWithOverlay<Props> = Props & OverlayParentProps export type PropsWithoutOverlay<Props> = Exclude<Props, OverlayParentProps> type OverlayParentState = { showingMenu: boolean } // This is deprecated. Use `Kb.usePopup instead.` const OverlayParentHOC = <Props extends {}>( ComposedComponent: React.ComponentType<PropsWithOverlay<Props>> ): React.ComponentType<PropsWithoutOverlay<Props>> => { class
extends React.Component<PropsWithoutOverlay<Props>, OverlayParentState> { state = {showingMenu: false} _ref: React.Component<any> | null = null setShowingMenu = (showingMenu: boolean) => this.setState(oldState => (oldState.showingMenu === showingMenu ? null : {showingMenu})) toggleShowingMenu = () => this.setState(oldState => ({showingMenu: !oldState.showingMenu})) setAttachmentRef = isMobile ? () => {} : (attachmentRef: React.Component<any> | null) => { this._ref = attachmentRef } getAttachmentRef = () => this._ref render() { return ( <ComposedComponent {...this.props} setShowingMenu={this.setShowingMenu} toggleShowingMenu={this.toggleShowingMenu} setAttachmentRef={this.setAttachmentRef} getAttachmentRef={this.getAttachmentRef} showingMenu={this.state.showingMenu} /> ) } } const OverlayParent: React.ComponentClass<PropsWithoutOverlay<Props>, OverlayParentState> = _OverlayParent OverlayParent.displayName = ComposedComponent.displayName || 'OverlayParent' hoistNonReactStatic(OverlayParent, ComposedComponent) return OverlayParent } export default OverlayParentHOC
_OverlayParent
identifier_name
process.rs
//! System calls related to process managment. use arch::context::{context_clone, context_switch, ContextFile}; use arch::regs::Regs; use collections::{BTreeMap, Vec}; use collections::string::ToString; use core::mem; use core::ops::DerefMut; use system::{c_array_to_slice, c_string_to_str}; use system::error::{Error, Result, ECHILD, EINVAL, EACCES}; use super::execute::execute; use fs::SupervisorResource; pub fn clone(regs: &Regs) -> Result<usize> { unsafe { context_clone(regs) } } pub fn execve(path: *const u8, args: *const *const u8) -> Result<usize> { let mut args_vec = Vec::new(); args_vec.push(c_string_to_str(path).to_string()); for arg in c_array_to_slice(args) { args_vec.push(c_string_to_str(*arg).to_string()); } execute(args_vec) } /// Exit context pub fn exit(status: usize) -> ! { { let contexts = unsafe { &mut *::env().contexts.get() }; let mut statuses = BTreeMap::new(); let (pid, ppid) = { if let Ok(mut current) = contexts.current_mut() { mem::swap(&mut statuses, &mut unsafe { current.statuses.inner() }.deref_mut()); current.exit(); (current.pid, current.ppid) } else { (0, 0) } }; for mut context in contexts.iter_mut() { // Add exit status to parent if context.pid == ppid { context.statuses.send(pid, status, "exit parent status"); for (pid, status) in statuses.iter() { context.statuses.send(*pid, *status, "exit child status"); } } // Move children to parent if context.ppid == pid { context.ppid = ppid; } } } loop { unsafe { context_switch() }; } } pub fn getpid() -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); Ok(current.pid) } #[cfg(target_arch = "x86")] pub fn iopl(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) } else { Err(Error::new(EINVAL)) } } #[cfg(target_arch = "x86_64")] pub fn iopl(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3
else { Err(Error::new(EINVAL)) } } //TODO: Finish implementation, add more functions to WaitMap so that matching any or using WNOHANG works pub fn waitpid(pid: isize, status_ptr: *mut usize, _options: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let current = try!(contexts.current_mut()); if pid > 0 { let status = current.statuses.receive(&(pid as usize), "waitpid status"); if let Ok(status_safe) = current.get_ref_mut(status_ptr) { *status_safe = status; } Ok(pid as usize) } else { Err(Error::new(ECHILD)) } } pub fn sched_yield() -> Result<usize> { unsafe { context_switch(); } Ok(0) } /// Supervise a child process of the current context. /// /// This will make all syscalls the given process makes mark the process as blocked, until it is /// handled by the supervisor (parrent process) through the returned handle (for details, see the /// docs in the `system` crate). /// /// This routine is done by having a field defining whether the process is blocked by a syscall. /// When the syscall is read from the file handle, this field is set to false, but the process is /// still stopped (because it is marked as `blocked`), until the new value of the EAX register is /// written to the file handle. pub fn supervise(pid: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let cur_pid = try!(contexts.current_mut()).pid; let procc; { let jailed = try!(contexts.find_mut(pid)); // Make sure that this is actually a child process of the invoker. if jailed.ppid != cur_pid { return Err(Error::new(EACCES)); } jailed.supervised = true; procc = &mut **jailed as *mut _; } let current = try!(contexts.current_mut()); let fd = current.next_fd(); unsafe { (*current.files.get()).push(ContextFile { fd: fd, resource: box try!(SupervisorResource::new(procc)), }); } Ok(fd) }
{ let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFFFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) }
conditional_block
process.rs
//! System calls related to process managment. use arch::context::{context_clone, context_switch, ContextFile}; use arch::regs::Regs; use collections::{BTreeMap, Vec}; use collections::string::ToString; use core::mem; use core::ops::DerefMut; use system::{c_array_to_slice, c_string_to_str}; use system::error::{Error, Result, ECHILD, EINVAL, EACCES}; use super::execute::execute; use fs::SupervisorResource; pub fn clone(regs: &Regs) -> Result<usize> { unsafe { context_clone(regs) } } pub fn execve(path: *const u8, args: *const *const u8) -> Result<usize> { let mut args_vec = Vec::new(); args_vec.push(c_string_to_str(path).to_string()); for arg in c_array_to_slice(args) { args_vec.push(c_string_to_str(*arg).to_string()); } execute(args_vec) } /// Exit context pub fn exit(status: usize) -> ! { { let contexts = unsafe { &mut *::env().contexts.get() }; let mut statuses = BTreeMap::new(); let (pid, ppid) = { if let Ok(mut current) = contexts.current_mut() { mem::swap(&mut statuses, &mut unsafe { current.statuses.inner() }.deref_mut()); current.exit(); (current.pid, current.ppid) } else { (0, 0) } }; for mut context in contexts.iter_mut() { // Add exit status to parent if context.pid == ppid { context.statuses.send(pid, status, "exit parent status"); for (pid, status) in statuses.iter() { context.statuses.send(*pid, *status, "exit child status"); } } // Move children to parent if context.ppid == pid { context.ppid = ppid; } } } loop { unsafe { context_switch() }; } } pub fn getpid() -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); Ok(current.pid) } #[cfg(target_arch = "x86")] pub fn iopl(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) } else { Err(Error::new(EINVAL)) } } #[cfg(target_arch = "x86_64")] pub fn iopl(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFFFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) } else {
//TODO: Finish implementation, add more functions to WaitMap so that matching any or using WNOHANG works pub fn waitpid(pid: isize, status_ptr: *mut usize, _options: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let current = try!(contexts.current_mut()); if pid > 0 { let status = current.statuses.receive(&(pid as usize), "waitpid status"); if let Ok(status_safe) = current.get_ref_mut(status_ptr) { *status_safe = status; } Ok(pid as usize) } else { Err(Error::new(ECHILD)) } } pub fn sched_yield() -> Result<usize> { unsafe { context_switch(); } Ok(0) } /// Supervise a child process of the current context. /// /// This will make all syscalls the given process makes mark the process as blocked, until it is /// handled by the supervisor (parrent process) through the returned handle (for details, see the /// docs in the `system` crate). /// /// This routine is done by having a field defining whether the process is blocked by a syscall. /// When the syscall is read from the file handle, this field is set to false, but the process is /// still stopped (because it is marked as `blocked`), until the new value of the EAX register is /// written to the file handle. pub fn supervise(pid: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let cur_pid = try!(contexts.current_mut()).pid; let procc; { let jailed = try!(contexts.find_mut(pid)); // Make sure that this is actually a child process of the invoker. if jailed.ppid != cur_pid { return Err(Error::new(EACCES)); } jailed.supervised = true; procc = &mut **jailed as *mut _; } let current = try!(contexts.current_mut()); let fd = current.next_fd(); unsafe { (*current.files.get()).push(ContextFile { fd: fd, resource: box try!(SupervisorResource::new(procc)), }); } Ok(fd) }
Err(Error::new(EINVAL)) } }
random_line_split
process.rs
//! System calls related to process managment. use arch::context::{context_clone, context_switch, ContextFile}; use arch::regs::Regs; use collections::{BTreeMap, Vec}; use collections::string::ToString; use core::mem; use core::ops::DerefMut; use system::{c_array_to_slice, c_string_to_str}; use system::error::{Error, Result, ECHILD, EINVAL, EACCES}; use super::execute::execute; use fs::SupervisorResource; pub fn clone(regs: &Regs) -> Result<usize> { unsafe { context_clone(regs) } } pub fn execve(path: *const u8, args: *const *const u8) -> Result<usize> { let mut args_vec = Vec::new(); args_vec.push(c_string_to_str(path).to_string()); for arg in c_array_to_slice(args) { args_vec.push(c_string_to_str(*arg).to_string()); } execute(args_vec) } /// Exit context pub fn exit(status: usize) -> ! { { let contexts = unsafe { &mut *::env().contexts.get() }; let mut statuses = BTreeMap::new(); let (pid, ppid) = { if let Ok(mut current) = contexts.current_mut() { mem::swap(&mut statuses, &mut unsafe { current.statuses.inner() }.deref_mut()); current.exit(); (current.pid, current.ppid) } else { (0, 0) } }; for mut context in contexts.iter_mut() { // Add exit status to parent if context.pid == ppid { context.statuses.send(pid, status, "exit parent status"); for (pid, status) in statuses.iter() { context.statuses.send(*pid, *status, "exit child status"); } } // Move children to parent if context.ppid == pid { context.ppid = ppid; } } } loop { unsafe { context_switch() }; } } pub fn getpid() -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); Ok(current.pid) } #[cfg(target_arch = "x86")] pub fn iopl(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) } else { Err(Error::new(EINVAL)) } } #[cfg(target_arch = "x86_64")] pub fn iopl(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFFFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) } else { Err(Error::new(EINVAL)) } } //TODO: Finish implementation, add more functions to WaitMap so that matching any or using WNOHANG works pub fn waitpid(pid: isize, status_ptr: *mut usize, _options: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let current = try!(contexts.current_mut()); if pid > 0 { let status = current.statuses.receive(&(pid as usize), "waitpid status"); if let Ok(status_safe) = current.get_ref_mut(status_ptr) { *status_safe = status; } Ok(pid as usize) } else { Err(Error::new(ECHILD)) } } pub fn sched_yield() -> Result<usize>
/// Supervise a child process of the current context. /// /// This will make all syscalls the given process makes mark the process as blocked, until it is /// handled by the supervisor (parrent process) through the returned handle (for details, see the /// docs in the `system` crate). /// /// This routine is done by having a field defining whether the process is blocked by a syscall. /// When the syscall is read from the file handle, this field is set to false, but the process is /// still stopped (because it is marked as `blocked`), until the new value of the EAX register is /// written to the file handle. pub fn supervise(pid: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let cur_pid = try!(contexts.current_mut()).pid; let procc; { let jailed = try!(contexts.find_mut(pid)); // Make sure that this is actually a child process of the invoker. if jailed.ppid != cur_pid { return Err(Error::new(EACCES)); } jailed.supervised = true; procc = &mut **jailed as *mut _; } let current = try!(contexts.current_mut()); let fd = current.next_fd(); unsafe { (*current.files.get()).push(ContextFile { fd: fd, resource: box try!(SupervisorResource::new(procc)), }); } Ok(fd) }
{ unsafe { context_switch(); } Ok(0) }
identifier_body
process.rs
//! System calls related to process managment. use arch::context::{context_clone, context_switch, ContextFile}; use arch::regs::Regs; use collections::{BTreeMap, Vec}; use collections::string::ToString; use core::mem; use core::ops::DerefMut; use system::{c_array_to_slice, c_string_to_str}; use system::error::{Error, Result, ECHILD, EINVAL, EACCES}; use super::execute::execute; use fs::SupervisorResource; pub fn clone(regs: &Regs) -> Result<usize> { unsafe { context_clone(regs) } } pub fn execve(path: *const u8, args: *const *const u8) -> Result<usize> { let mut args_vec = Vec::new(); args_vec.push(c_string_to_str(path).to_string()); for arg in c_array_to_slice(args) { args_vec.push(c_string_to_str(*arg).to_string()); } execute(args_vec) } /// Exit context pub fn exit(status: usize) -> ! { { let contexts = unsafe { &mut *::env().contexts.get() }; let mut statuses = BTreeMap::new(); let (pid, ppid) = { if let Ok(mut current) = contexts.current_mut() { mem::swap(&mut statuses, &mut unsafe { current.statuses.inner() }.deref_mut()); current.exit(); (current.pid, current.ppid) } else { (0, 0) } }; for mut context in contexts.iter_mut() { // Add exit status to parent if context.pid == ppid { context.statuses.send(pid, status, "exit parent status"); for (pid, status) in statuses.iter() { context.statuses.send(*pid, *status, "exit child status"); } } // Move children to parent if context.ppid == pid { context.ppid = ppid; } } } loop { unsafe { context_switch() }; } } pub fn getpid() -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); Ok(current.pid) } #[cfg(target_arch = "x86")] pub fn
(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) } else { Err(Error::new(EINVAL)) } } #[cfg(target_arch = "x86_64")] pub fn iopl(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFFFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) } else { Err(Error::new(EINVAL)) } } //TODO: Finish implementation, add more functions to WaitMap so that matching any or using WNOHANG works pub fn waitpid(pid: isize, status_ptr: *mut usize, _options: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let current = try!(contexts.current_mut()); if pid > 0 { let status = current.statuses.receive(&(pid as usize), "waitpid status"); if let Ok(status_safe) = current.get_ref_mut(status_ptr) { *status_safe = status; } Ok(pid as usize) } else { Err(Error::new(ECHILD)) } } pub fn sched_yield() -> Result<usize> { unsafe { context_switch(); } Ok(0) } /// Supervise a child process of the current context. /// /// This will make all syscalls the given process makes mark the process as blocked, until it is /// handled by the supervisor (parrent process) through the returned handle (for details, see the /// docs in the `system` crate). /// /// This routine is done by having a field defining whether the process is blocked by a syscall. /// When the syscall is read from the file handle, this field is set to false, but the process is /// still stopped (because it is marked as `blocked`), until the new value of the EAX register is /// written to the file handle. pub fn supervise(pid: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let cur_pid = try!(contexts.current_mut()).pid; let procc; { let jailed = try!(contexts.find_mut(pid)); // Make sure that this is actually a child process of the invoker. if jailed.ppid != cur_pid { return Err(Error::new(EACCES)); } jailed.supervised = true; procc = &mut **jailed as *mut _; } let current = try!(contexts.current_mut()); let fd = current.next_fd(); unsafe { (*current.files.get()).push(ContextFile { fd: fd, resource: box try!(SupervisorResource::new(procc)), }); } Ok(fd) }
iopl
identifier_name
enrichment.rs
use serde_json::Value; use {PassiveTotal, Result}; const URL_DATA: &str = "/enrichment"; const URL_OSINT: &str = "/enrichment/osint"; const URL_MALWARE: &str = "/enrichment/malware"; const URL_SUBDOMAINS: &str = "/enrichment/subdomains"; pub struct EnrichmentRequest<'a> { pt: &'a PassiveTotal, } request_struct!(EnrichmentData { query: String }); request_struct!(EnrichmentOsint { query: String }); request_struct!(EnrichmentMalware { query: String }); request_struct!(EnrichmentSubdomains { query: String }); impl<'a> EnrichmentRequest<'a> { pub fn data<S>(self, query: S) -> EnrichmentData<'a> where S: Into<String>, { EnrichmentData { pt: self.pt, url: URL_DATA, query: query.into(), } } pub fn osint<S>(self, query: S) -> EnrichmentOsint<'a> where S: Into<String>, { EnrichmentOsint { pt: self.pt, url: URL_OSINT, query: query.into(), } } pub fn malware<S>(self, query: S) -> EnrichmentMalware<'a> where S: Into<String>, { EnrichmentMalware { pt: self.pt, url: URL_MALWARE, query: query.into(), } } pub fn subdomains<S>(self, query: S) -> EnrichmentSubdomains<'a> where S: Into<String>, { EnrichmentSubdomains { pt: self.pt, url: URL_SUBDOMAINS, query: query.into(), } } } impl_send!(EnrichmentData); impl_send!(EnrichmentOsint); impl_send!(EnrichmentMalware); impl_send!(EnrichmentSubdomains); impl PassiveTotal { pub fn
(&self) -> EnrichmentRequest { EnrichmentRequest { pt: self } } }
enrichment
identifier_name
enrichment.rs
use serde_json::Value; use {PassiveTotal, Result}; const URL_DATA: &str = "/enrichment"; const URL_OSINT: &str = "/enrichment/osint"; const URL_MALWARE: &str = "/enrichment/malware"; const URL_SUBDOMAINS: &str = "/enrichment/subdomains"; pub struct EnrichmentRequest<'a> { pt: &'a PassiveTotal, } request_struct!(EnrichmentData { query: String }); request_struct!(EnrichmentOsint { query: String }); request_struct!(EnrichmentMalware { query: String }); request_struct!(EnrichmentSubdomains { query: String }); impl<'a> EnrichmentRequest<'a> { pub fn data<S>(self, query: S) -> EnrichmentData<'a> where S: Into<String>, { EnrichmentData { pt: self.pt, url: URL_DATA, query: query.into(), } } pub fn osint<S>(self, query: S) -> EnrichmentOsint<'a> where S: Into<String>, { EnrichmentOsint { pt: self.pt, url: URL_OSINT, query: query.into(), } } pub fn malware<S>(self, query: S) -> EnrichmentMalware<'a> where S: Into<String>, { EnrichmentMalware { pt: self.pt, url: URL_MALWARE, query: query.into(), } }
S: Into<String>, { EnrichmentSubdomains { pt: self.pt, url: URL_SUBDOMAINS, query: query.into(), } } } impl_send!(EnrichmentData); impl_send!(EnrichmentOsint); impl_send!(EnrichmentMalware); impl_send!(EnrichmentSubdomains); impl PassiveTotal { pub fn enrichment(&self) -> EnrichmentRequest { EnrichmentRequest { pt: self } } }
pub fn subdomains<S>(self, query: S) -> EnrichmentSubdomains<'a> where
random_line_split
enrichment.rs
use serde_json::Value; use {PassiveTotal, Result}; const URL_DATA: &str = "/enrichment"; const URL_OSINT: &str = "/enrichment/osint"; const URL_MALWARE: &str = "/enrichment/malware"; const URL_SUBDOMAINS: &str = "/enrichment/subdomains"; pub struct EnrichmentRequest<'a> { pt: &'a PassiveTotal, } request_struct!(EnrichmentData { query: String }); request_struct!(EnrichmentOsint { query: String }); request_struct!(EnrichmentMalware { query: String }); request_struct!(EnrichmentSubdomains { query: String }); impl<'a> EnrichmentRequest<'a> { pub fn data<S>(self, query: S) -> EnrichmentData<'a> where S: Into<String>,
pub fn osint<S>(self, query: S) -> EnrichmentOsint<'a> where S: Into<String>, { EnrichmentOsint { pt: self.pt, url: URL_OSINT, query: query.into(), } } pub fn malware<S>(self, query: S) -> EnrichmentMalware<'a> where S: Into<String>, { EnrichmentMalware { pt: self.pt, url: URL_MALWARE, query: query.into(), } } pub fn subdomains<S>(self, query: S) -> EnrichmentSubdomains<'a> where S: Into<String>, { EnrichmentSubdomains { pt: self.pt, url: URL_SUBDOMAINS, query: query.into(), } } } impl_send!(EnrichmentData); impl_send!(EnrichmentOsint); impl_send!(EnrichmentMalware); impl_send!(EnrichmentSubdomains); impl PassiveTotal { pub fn enrichment(&self) -> EnrichmentRequest { EnrichmentRequest { pt: self } } }
{ EnrichmentData { pt: self.pt, url: URL_DATA, query: query.into(), } }
identifier_body
fashion_compatibility.py
# Copyright 2017 Xintong Han. All Rights Reserved. # # 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. # ============================================================================== """Predict the fashion compatibility of a given image sequence.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import json import tensorflow as tf import numpy as np import pickle as pkl from sklearn import metrics import configuration import polyvore_model_bi as polyvore_model FLAGS = tf.flags.FLAGS tf.flags.DEFINE_string("checkpoint_path", "", "Model checkpoint file or directory containing a " "model checkpoint file.") tf.flags.DEFINE_string("label_file", "", "Txt file containing test outfits.") tf.flags.DEFINE_string("feature_file", "", "Files containing image features") tf.flags.DEFINE_string("rnn_type", "", "Type of RNN.") tf.flags.DEFINE_string("result_file", "", "File to store the results.") tf.flags.DEFINE_integer("direction", 2, "2: bidirectional; 1: forward only;" "-1: backward only.") def run_compatibility_inference(sess, image_seqs, test_feat, num_lstm_units, model): emb_seqs = test_feat[image_seqs,:] num_images = float(len(image_seqs)) if FLAGS.rnn_type == "lstm": zero_state = np.zeros([1, 2 * num_lstm_units]) else: zero_state = np.zeros([1, num_lstm_units]) f_score = 0 b_score = 0 if FLAGS.direction != -1: # Forward RNN. outputs = [] input_feed = np.reshape(emb_seqs[0], [1,-1]) # Run first step with all zeros initial state. [lstm_state, lstm_output] = sess.run( fetches=["lstm/f_state:0","f_logits/f_logits/BiasAdd:0"], feed_dict={"lstm/f_input_feed:0":input_feed, "lstm/f_state_feed:0":zero_state}) outputs.append(lstm_output) # Run remaining steps. for step in range(int(num_images)-1): input_feed = np.reshape(emb_seqs[step+1], [1,-1]) [lstm_state, lstm_output] = sess.run( fetches=["lstm/f_state:0","f_logits/f_logits/BiasAdd:0"], feed_dict={"lstm/f_input_feed:0":input_feed, "lstm/f_state_feed:0":lstm_state}) outputs.append(lstm_output) # Calculate the loss. # Different from the training process where the loss is calculated in each # mini batch, during testing, we get the loss againist the whole test set. # This is pretty slow, maybe a better method could be used. s = np.squeeze(np.dot(np.asarray(outputs), np.transpose(test_feat))) f_score = sess.run(model.lstm_xent_loss, feed_dict={"lstm/pred_feed:0":s, "lstm/next_index_feed:0":image_seqs[1:] + [test_feat.shape[0]-1]}) f_score = - np.mean(f_score) if FLAGS.direction != 1: # Backward RNN. outputs = [] input_feed = np.reshape(emb_seqs[-1], [1,-1]) [lstm_state, lstm_output] = sess.run( fetches=["lstm/b_state:0","b_logits/b_logits/BiasAdd:0"], feed_dict={"lstm/b_input_feed:0":input_feed, "lstm/b_state_feed:0":zero_state}) outputs.append(lstm_output) for step in range(int(num_images)-1): input_feed = np.reshape(emb_seqs[int(num_images)-2-step], [1,-1]) [lstm_state, lstm_output] = sess.run( fetches=["lstm/b_state:0","b_logits/b_logits/BiasAdd:0"], feed_dict={"lstm/b_input_feed:0":input_feed, "lstm/b_state_feed:0":lstm_state}) outputs.append(lstm_output) # Calculate the loss. s = np.squeeze(np.dot(np.asarray(outputs), np.transpose(test_feat))) b_score = sess.run(model.lstm_xent_loss, feed_dict={"lstm/pred_feed:0":s, "lstm/next_index_feed:0": image_seqs[-2::-1] + [test_feat.shape[0]-1]}) b_score = - np.mean(b_score) return [f_score, b_score] def main(_): # Build the inference graph.
if __name__ == "__main__": tf.app.run()
g = tf.Graph() with g.as_default(): model_config = configuration.ModelConfig() model_config.rnn_type = FLAGS.rnn_type model = polyvore_model.PolyvoreModel(model_config, mode="inference") model.build() saver = tf.train.Saver() # Load pre-computed image features. with open(FLAGS.feature_file, "rb") as f: test_data = pkl.load(f) test_ids = test_data.keys() test_feat = np.zeros((len(test_ids) + 1, len(test_data[test_ids[0]]["image_rnn_feat"]))) # test_feat has one more zero vector as the representation of END of # RNN prediction. for i, test_id in enumerate(test_ids): # Image feature in the RNN space. test_feat[i] = test_data[test_id]["image_rnn_feat"] g.finalize() with tf.Session() as sess: saver.restore(sess, FLAGS.checkpoint_path) all_f_scores = [] all_b_scores = [] all_scores = [] all_labels = [] testset = open(FLAGS.label_file).read().splitlines() k = 0 for test_outfit in testset: k += 1 if k % 100 == 0: print("Finish %d outfits." % k) image_seqs = [] for test_image in test_outfit.split()[1:]: image_seqs.append(test_ids.index(test_image)) [f_score, b_score] = run_compatibility_inference(sess, image_seqs, test_feat, model_config.num_lstm_units, model) all_f_scores.append(f_score) all_b_scores.append(b_score) all_scores.append(f_score + b_score) all_labels.append(int(test_outfit[0])) # calculate AUC and AP fpr, tpr, thresholds = metrics.roc_curve(all_labels, all_scores, pos_label=1) print("Compatibility AUC: %f for %d outfits" % (metrics.auc(fpr, tpr), len(all_labels))) with open(FLAGS.result_file, "wb") as f: pkl.dump({"all_labels": all_labels, "all_f_scores": all_f_scores, "all_b_scores": all_b_scores}, f)
identifier_body
fashion_compatibility.py
# Copyright 2017 Xintong Han. All Rights Reserved. # # 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 #
# See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Predict the fashion compatibility of a given image sequence.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import json import tensorflow as tf import numpy as np import pickle as pkl from sklearn import metrics import configuration import polyvore_model_bi as polyvore_model FLAGS = tf.flags.FLAGS tf.flags.DEFINE_string("checkpoint_path", "", "Model checkpoint file or directory containing a " "model checkpoint file.") tf.flags.DEFINE_string("label_file", "", "Txt file containing test outfits.") tf.flags.DEFINE_string("feature_file", "", "Files containing image features") tf.flags.DEFINE_string("rnn_type", "", "Type of RNN.") tf.flags.DEFINE_string("result_file", "", "File to store the results.") tf.flags.DEFINE_integer("direction", 2, "2: bidirectional; 1: forward only;" "-1: backward only.") def run_compatibility_inference(sess, image_seqs, test_feat, num_lstm_units, model): emb_seqs = test_feat[image_seqs,:] num_images = float(len(image_seqs)) if FLAGS.rnn_type == "lstm": zero_state = np.zeros([1, 2 * num_lstm_units]) else: zero_state = np.zeros([1, num_lstm_units]) f_score = 0 b_score = 0 if FLAGS.direction != -1: # Forward RNN. outputs = [] input_feed = np.reshape(emb_seqs[0], [1,-1]) # Run first step with all zeros initial state. [lstm_state, lstm_output] = sess.run( fetches=["lstm/f_state:0","f_logits/f_logits/BiasAdd:0"], feed_dict={"lstm/f_input_feed:0":input_feed, "lstm/f_state_feed:0":zero_state}) outputs.append(lstm_output) # Run remaining steps. for step in range(int(num_images)-1): input_feed = np.reshape(emb_seqs[step+1], [1,-1]) [lstm_state, lstm_output] = sess.run( fetches=["lstm/f_state:0","f_logits/f_logits/BiasAdd:0"], feed_dict={"lstm/f_input_feed:0":input_feed, "lstm/f_state_feed:0":lstm_state}) outputs.append(lstm_output) # Calculate the loss. # Different from the training process where the loss is calculated in each # mini batch, during testing, we get the loss againist the whole test set. # This is pretty slow, maybe a better method could be used. s = np.squeeze(np.dot(np.asarray(outputs), np.transpose(test_feat))) f_score = sess.run(model.lstm_xent_loss, feed_dict={"lstm/pred_feed:0":s, "lstm/next_index_feed:0":image_seqs[1:] + [test_feat.shape[0]-1]}) f_score = - np.mean(f_score) if FLAGS.direction != 1: # Backward RNN. outputs = [] input_feed = np.reshape(emb_seqs[-1], [1,-1]) [lstm_state, lstm_output] = sess.run( fetches=["lstm/b_state:0","b_logits/b_logits/BiasAdd:0"], feed_dict={"lstm/b_input_feed:0":input_feed, "lstm/b_state_feed:0":zero_state}) outputs.append(lstm_output) for step in range(int(num_images)-1): input_feed = np.reshape(emb_seqs[int(num_images)-2-step], [1,-1]) [lstm_state, lstm_output] = sess.run( fetches=["lstm/b_state:0","b_logits/b_logits/BiasAdd:0"], feed_dict={"lstm/b_input_feed:0":input_feed, "lstm/b_state_feed:0":lstm_state}) outputs.append(lstm_output) # Calculate the loss. s = np.squeeze(np.dot(np.asarray(outputs), np.transpose(test_feat))) b_score = sess.run(model.lstm_xent_loss, feed_dict={"lstm/pred_feed:0":s, "lstm/next_index_feed:0": image_seqs[-2::-1] + [test_feat.shape[0]-1]}) b_score = - np.mean(b_score) return [f_score, b_score] def main(_): # Build the inference graph. g = tf.Graph() with g.as_default(): model_config = configuration.ModelConfig() model_config.rnn_type = FLAGS.rnn_type model = polyvore_model.PolyvoreModel(model_config, mode="inference") model.build() saver = tf.train.Saver() # Load pre-computed image features. with open(FLAGS.feature_file, "rb") as f: test_data = pkl.load(f) test_ids = test_data.keys() test_feat = np.zeros((len(test_ids) + 1, len(test_data[test_ids[0]]["image_rnn_feat"]))) # test_feat has one more zero vector as the representation of END of # RNN prediction. for i, test_id in enumerate(test_ids): # Image feature in the RNN space. test_feat[i] = test_data[test_id]["image_rnn_feat"] g.finalize() with tf.Session() as sess: saver.restore(sess, FLAGS.checkpoint_path) all_f_scores = [] all_b_scores = [] all_scores = [] all_labels = [] testset = open(FLAGS.label_file).read().splitlines() k = 0 for test_outfit in testset: k += 1 if k % 100 == 0: print("Finish %d outfits." % k) image_seqs = [] for test_image in test_outfit.split()[1:]: image_seqs.append(test_ids.index(test_image)) [f_score, b_score] = run_compatibility_inference(sess, image_seqs, test_feat, model_config.num_lstm_units, model) all_f_scores.append(f_score) all_b_scores.append(b_score) all_scores.append(f_score + b_score) all_labels.append(int(test_outfit[0])) # calculate AUC and AP fpr, tpr, thresholds = metrics.roc_curve(all_labels, all_scores, pos_label=1) print("Compatibility AUC: %f for %d outfits" % (metrics.auc(fpr, tpr), len(all_labels))) with open(FLAGS.result_file, "wb") as f: pkl.dump({"all_labels": all_labels, "all_f_scores": all_f_scores, "all_b_scores": all_b_scores}, f) if __name__ == "__main__": tf.app.run()
# 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.
random_line_split
fashion_compatibility.py
# Copyright 2017 Xintong Han. All Rights Reserved. # # 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. # ============================================================================== """Predict the fashion compatibility of a given image sequence.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import json import tensorflow as tf import numpy as np import pickle as pkl from sklearn import metrics import configuration import polyvore_model_bi as polyvore_model FLAGS = tf.flags.FLAGS tf.flags.DEFINE_string("checkpoint_path", "", "Model checkpoint file or directory containing a " "model checkpoint file.") tf.flags.DEFINE_string("label_file", "", "Txt file containing test outfits.") tf.flags.DEFINE_string("feature_file", "", "Files containing image features") tf.flags.DEFINE_string("rnn_type", "", "Type of RNN.") tf.flags.DEFINE_string("result_file", "", "File to store the results.") tf.flags.DEFINE_integer("direction", 2, "2: bidirectional; 1: forward only;" "-1: backward only.") def
(sess, image_seqs, test_feat, num_lstm_units, model): emb_seqs = test_feat[image_seqs,:] num_images = float(len(image_seqs)) if FLAGS.rnn_type == "lstm": zero_state = np.zeros([1, 2 * num_lstm_units]) else: zero_state = np.zeros([1, num_lstm_units]) f_score = 0 b_score = 0 if FLAGS.direction != -1: # Forward RNN. outputs = [] input_feed = np.reshape(emb_seqs[0], [1,-1]) # Run first step with all zeros initial state. [lstm_state, lstm_output] = sess.run( fetches=["lstm/f_state:0","f_logits/f_logits/BiasAdd:0"], feed_dict={"lstm/f_input_feed:0":input_feed, "lstm/f_state_feed:0":zero_state}) outputs.append(lstm_output) # Run remaining steps. for step in range(int(num_images)-1): input_feed = np.reshape(emb_seqs[step+1], [1,-1]) [lstm_state, lstm_output] = sess.run( fetches=["lstm/f_state:0","f_logits/f_logits/BiasAdd:0"], feed_dict={"lstm/f_input_feed:0":input_feed, "lstm/f_state_feed:0":lstm_state}) outputs.append(lstm_output) # Calculate the loss. # Different from the training process where the loss is calculated in each # mini batch, during testing, we get the loss againist the whole test set. # This is pretty slow, maybe a better method could be used. s = np.squeeze(np.dot(np.asarray(outputs), np.transpose(test_feat))) f_score = sess.run(model.lstm_xent_loss, feed_dict={"lstm/pred_feed:0":s, "lstm/next_index_feed:0":image_seqs[1:] + [test_feat.shape[0]-1]}) f_score = - np.mean(f_score) if FLAGS.direction != 1: # Backward RNN. outputs = [] input_feed = np.reshape(emb_seqs[-1], [1,-1]) [lstm_state, lstm_output] = sess.run( fetches=["lstm/b_state:0","b_logits/b_logits/BiasAdd:0"], feed_dict={"lstm/b_input_feed:0":input_feed, "lstm/b_state_feed:0":zero_state}) outputs.append(lstm_output) for step in range(int(num_images)-1): input_feed = np.reshape(emb_seqs[int(num_images)-2-step], [1,-1]) [lstm_state, lstm_output] = sess.run( fetches=["lstm/b_state:0","b_logits/b_logits/BiasAdd:0"], feed_dict={"lstm/b_input_feed:0":input_feed, "lstm/b_state_feed:0":lstm_state}) outputs.append(lstm_output) # Calculate the loss. s = np.squeeze(np.dot(np.asarray(outputs), np.transpose(test_feat))) b_score = sess.run(model.lstm_xent_loss, feed_dict={"lstm/pred_feed:0":s, "lstm/next_index_feed:0": image_seqs[-2::-1] + [test_feat.shape[0]-1]}) b_score = - np.mean(b_score) return [f_score, b_score] def main(_): # Build the inference graph. g = tf.Graph() with g.as_default(): model_config = configuration.ModelConfig() model_config.rnn_type = FLAGS.rnn_type model = polyvore_model.PolyvoreModel(model_config, mode="inference") model.build() saver = tf.train.Saver() # Load pre-computed image features. with open(FLAGS.feature_file, "rb") as f: test_data = pkl.load(f) test_ids = test_data.keys() test_feat = np.zeros((len(test_ids) + 1, len(test_data[test_ids[0]]["image_rnn_feat"]))) # test_feat has one more zero vector as the representation of END of # RNN prediction. for i, test_id in enumerate(test_ids): # Image feature in the RNN space. test_feat[i] = test_data[test_id]["image_rnn_feat"] g.finalize() with tf.Session() as sess: saver.restore(sess, FLAGS.checkpoint_path) all_f_scores = [] all_b_scores = [] all_scores = [] all_labels = [] testset = open(FLAGS.label_file).read().splitlines() k = 0 for test_outfit in testset: k += 1 if k % 100 == 0: print("Finish %d outfits." % k) image_seqs = [] for test_image in test_outfit.split()[1:]: image_seqs.append(test_ids.index(test_image)) [f_score, b_score] = run_compatibility_inference(sess, image_seqs, test_feat, model_config.num_lstm_units, model) all_f_scores.append(f_score) all_b_scores.append(b_score) all_scores.append(f_score + b_score) all_labels.append(int(test_outfit[0])) # calculate AUC and AP fpr, tpr, thresholds = metrics.roc_curve(all_labels, all_scores, pos_label=1) print("Compatibility AUC: %f for %d outfits" % (metrics.auc(fpr, tpr), len(all_labels))) with open(FLAGS.result_file, "wb") as f: pkl.dump({"all_labels": all_labels, "all_f_scores": all_f_scores, "all_b_scores": all_b_scores}, f) if __name__ == "__main__": tf.app.run()
run_compatibility_inference
identifier_name
fashion_compatibility.py
# Copyright 2017 Xintong Han. All Rights Reserved. # # 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. # ============================================================================== """Predict the fashion compatibility of a given image sequence.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import json import tensorflow as tf import numpy as np import pickle as pkl from sklearn import metrics import configuration import polyvore_model_bi as polyvore_model FLAGS = tf.flags.FLAGS tf.flags.DEFINE_string("checkpoint_path", "", "Model checkpoint file or directory containing a " "model checkpoint file.") tf.flags.DEFINE_string("label_file", "", "Txt file containing test outfits.") tf.flags.DEFINE_string("feature_file", "", "Files containing image features") tf.flags.DEFINE_string("rnn_type", "", "Type of RNN.") tf.flags.DEFINE_string("result_file", "", "File to store the results.") tf.flags.DEFINE_integer("direction", 2, "2: bidirectional; 1: forward only;" "-1: backward only.") def run_compatibility_inference(sess, image_seqs, test_feat, num_lstm_units, model): emb_seqs = test_feat[image_seqs,:] num_images = float(len(image_seqs)) if FLAGS.rnn_type == "lstm": zero_state = np.zeros([1, 2 * num_lstm_units]) else: zero_state = np.zeros([1, num_lstm_units]) f_score = 0 b_score = 0 if FLAGS.direction != -1: # Forward RNN. outputs = [] input_feed = np.reshape(emb_seqs[0], [1,-1]) # Run first step with all zeros initial state. [lstm_state, lstm_output] = sess.run( fetches=["lstm/f_state:0","f_logits/f_logits/BiasAdd:0"], feed_dict={"lstm/f_input_feed:0":input_feed, "lstm/f_state_feed:0":zero_state}) outputs.append(lstm_output) # Run remaining steps. for step in range(int(num_images)-1): input_feed = np.reshape(emb_seqs[step+1], [1,-1]) [lstm_state, lstm_output] = sess.run( fetches=["lstm/f_state:0","f_logits/f_logits/BiasAdd:0"], feed_dict={"lstm/f_input_feed:0":input_feed, "lstm/f_state_feed:0":lstm_state}) outputs.append(lstm_output) # Calculate the loss. # Different from the training process where the loss is calculated in each # mini batch, during testing, we get the loss againist the whole test set. # This is pretty slow, maybe a better method could be used. s = np.squeeze(np.dot(np.asarray(outputs), np.transpose(test_feat))) f_score = sess.run(model.lstm_xent_loss, feed_dict={"lstm/pred_feed:0":s, "lstm/next_index_feed:0":image_seqs[1:] + [test_feat.shape[0]-1]}) f_score = - np.mean(f_score) if FLAGS.direction != 1: # Backward RNN. outputs = [] input_feed = np.reshape(emb_seqs[-1], [1,-1]) [lstm_state, lstm_output] = sess.run( fetches=["lstm/b_state:0","b_logits/b_logits/BiasAdd:0"], feed_dict={"lstm/b_input_feed:0":input_feed, "lstm/b_state_feed:0":zero_state}) outputs.append(lstm_output) for step in range(int(num_images)-1): input_feed = np.reshape(emb_seqs[int(num_images)-2-step], [1,-1]) [lstm_state, lstm_output] = sess.run( fetches=["lstm/b_state:0","b_logits/b_logits/BiasAdd:0"], feed_dict={"lstm/b_input_feed:0":input_feed, "lstm/b_state_feed:0":lstm_state}) outputs.append(lstm_output) # Calculate the loss. s = np.squeeze(np.dot(np.asarray(outputs), np.transpose(test_feat))) b_score = sess.run(model.lstm_xent_loss, feed_dict={"lstm/pred_feed:0":s, "lstm/next_index_feed:0": image_seqs[-2::-1] + [test_feat.shape[0]-1]}) b_score = - np.mean(b_score) return [f_score, b_score] def main(_): # Build the inference graph. g = tf.Graph() with g.as_default(): model_config = configuration.ModelConfig() model_config.rnn_type = FLAGS.rnn_type model = polyvore_model.PolyvoreModel(model_config, mode="inference") model.build() saver = tf.train.Saver() # Load pre-computed image features. with open(FLAGS.feature_file, "rb") as f: test_data = pkl.load(f) test_ids = test_data.keys() test_feat = np.zeros((len(test_ids) + 1, len(test_data[test_ids[0]]["image_rnn_feat"]))) # test_feat has one more zero vector as the representation of END of # RNN prediction. for i, test_id in enumerate(test_ids): # Image feature in the RNN space. test_feat[i] = test_data[test_id]["image_rnn_feat"] g.finalize() with tf.Session() as sess: saver.restore(sess, FLAGS.checkpoint_path) all_f_scores = [] all_b_scores = [] all_scores = [] all_labels = [] testset = open(FLAGS.label_file).read().splitlines() k = 0 for test_outfit in testset: k += 1 if k % 100 == 0: print("Finish %d outfits." % k) image_seqs = [] for test_image in test_outfit.split()[1:]:
[f_score, b_score] = run_compatibility_inference(sess, image_seqs, test_feat, model_config.num_lstm_units, model) all_f_scores.append(f_score) all_b_scores.append(b_score) all_scores.append(f_score + b_score) all_labels.append(int(test_outfit[0])) # calculate AUC and AP fpr, tpr, thresholds = metrics.roc_curve(all_labels, all_scores, pos_label=1) print("Compatibility AUC: %f for %d outfits" % (metrics.auc(fpr, tpr), len(all_labels))) with open(FLAGS.result_file, "wb") as f: pkl.dump({"all_labels": all_labels, "all_f_scores": all_f_scores, "all_b_scores": all_b_scores}, f) if __name__ == "__main__": tf.app.run()
image_seqs.append(test_ids.index(test_image))
conditional_block
mocha.d.ts
// Type definitions for mocha 1.9.0 // Project: http://visionmedia.github.io/mocha/ // Definitions by: Kazi Manzur Rashid <https://github.com/kazimanzurrashid/> // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped interface Mocha { // Setup mocha with the given setting options. setup(options: MochaSetupOptions): Mocha; //Run tests and invoke `fn()` when complete. run(callback?: () => void): void;
// Set reporter, defaults to "dot" reporter(reporter: string): Mocha; // Enable growl support. growl(): Mocha } interface MochaSetupOptions { //milliseconds to wait before considering a test slow slow?: number; // timeout in milliseconds timeout?: number; // ui name "bdd", "tdd", "exports" etc ui?: string; //array of accepted globals globals?: any[]; // reporter instance (function or string), defaults to `mocha.reporters.Dot` reporter?: any; // bail on the first test failure bail?: Boolean; // ignore global leaks ignoreLeaks?: Boolean; // grep string or regexp to filter tests with grep?: any; } declare module mocha { interface Done { (error?: Error): void; } } declare var describe : { (description: string, spec: () => void): void; only(description: string, spec: () => void): void; skip(description: string, spec: () => void): void; timeout(ms: number): void; } declare var it: { (expectation: string, assertion?: () => void): void; (expectation: string, assertion?: (done: mocha.Done) => void): void; only(expectation: string, assertion?: () => void): void; only(expectation: string, assertion?: (done: mocha.Done) => void): void; skip(expectation: string, assertion?: () => void): void; skip(expectation: string, assertion?: (done: mocha.Done) => void): void; timeout(ms: number): void; }; declare function before(action: () => void): void; declare function before(action: (done: mocha.Done) => void): void; declare function after(action: () => void): void; declare function after(action: (done: mocha.Done) => void): void; declare function beforeEach(action: () => void): void; declare function beforeEach(action: (done: mocha.Done) => void): void; declare function afterEach(action: () => void): void; declare function afterEach(action: (done: mocha.Done) => void): void;
// Set reporter as function reporter(reporter: () => void): Mocha;
random_line_split
Debug.js
/////////////////////////////////////////////////////////////////////////////// // Debug Extensions ss.Debug = global.Debug || function() {}; ss.Debug.__typeName = 'Debug'; if (!ss.Debug.writeln) { ss.Debug.writeln = function#? DEBUG Debug$writeln##(text) { if (global.console) { if (global.console.debug)
else if (global.console.log) { global.console.log(text); return; } } else if (global.opera && global.opera.postError) { global.opera.postError(text); return; } } }; ss.Debug._fail = function#? DEBUG Debug$_fail##(message) { ss.Debug.writeln(message); debugger; }; ss.Debug.assert = function#? DEBUG Debug$assert##(condition, message) { if (!condition) { message = 'Assert failed: ' + message; if (confirm(message + '\r\n\r\nBreak into debugger?')) { ss.Debug._fail(message); } } }; ss.Debug.fail = function#? DEBUG Debug$fail##(message) { ss.Debug._fail(message); };
{ global.console.debug(text); return; }
conditional_block
Debug.js
/////////////////////////////////////////////////////////////////////////////// // Debug Extensions ss.Debug = global.Debug || function() {}; ss.Debug.__typeName = 'Debug'; if (!ss.Debug.writeln) { ss.Debug.writeln = function#? DEBUG Debug$writeln##(text) { if (global.console) { if (global.console.debug) { global.console.debug(text); return; } else if (global.console.log) { global.console.log(text); return; } } else if (global.opera && global.opera.postError) { global.opera.postError(text); return; } }
debugger; }; ss.Debug.assert = function#? DEBUG Debug$assert##(condition, message) { if (!condition) { message = 'Assert failed: ' + message; if (confirm(message + '\r\n\r\nBreak into debugger?')) { ss.Debug._fail(message); } } }; ss.Debug.fail = function#? DEBUG Debug$fail##(message) { ss.Debug._fail(message); };
}; ss.Debug._fail = function#? DEBUG Debug$_fail##(message) { ss.Debug.writeln(message);
random_line_split
action-constraint-form-control.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ export enum ActionConstraintFormControl { Title = 'title', Icon = 'icon', TitleUser = 'titleUser', Background = 'background', Rule = 'rule',
RequiresConfirmation = 'requiresConfirmation', ConfirmationTitle = 'confirmationTitle', }
random_line_split
jquery.ui.datepicker-ja.min.js
/*! jQuery UI - v1.9.2 - 2015-05-24 * http://jqueryui.com * Copyright 2015 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.ja={closeText:"閉じる",prevText:"&#x3C;前",nextText:"次&#x3E;",currentText:"今日",monthNames:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],monthNamesShort:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],dayNames:["日曜日","月曜日","火曜日","水曜日","木曜日","金曜日","土曜日"],dayNamesShort:["日","月","火","水","木","金","土"],dayNamesMin:["日","月","火","水","木","金","土"],weekHeader:"週",dateFormat:"yy/mm/dd",firstDay:0,isRTL:!1,showMonthAfterYear:!0,yearSuffix:"年"},e.datepicker.setDefaults(e.datepicker.regional.ja)});
random_line_split
anmr_platform_win.py
#from matplotlib.backends.backend_gtk import NavigationToolbar2GTK as NavigationToolbar2 from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar2 import subprocess import shlex import re import posixpath from anmr_common import * # use hub4com ? USE_SERIAL_PIPE=False #external helper programs: #hub4com is quoted differently than sox because its arguments are tricky. HUB4COM='C:\\Program Files\\hub4com\\hub4com.exe' SOX_EXEC='"c:\\Program Files\\sox-14-4-0\\sox.exe"' AVRDUDE='c:\\Anmr\\avrdude\\avrdude.exe' AVRDUDE_CONF='C:\\Anmr\\avrdude\\avrdude.conf' #standard windows install: IMAGE_VIEWER = 'rundll32.exe "c:\\WINDOWS\\System32\\shimgvw.dll,ImageView_Fullscreen"' #Anmr installs: #this one is also in Shim.py ICON_PATH='c:\\Anmr\\Icons' #our firmware #ARDUINO_CODE = 'c:\\Anmr\\arduinoCode' FIRMWARE='c:\\Anmr\\arduinoCode\\arduinoCode.hex' #pulse programs: PROG_DIR = 'c:\\Anmr\\PulsePrograms' #pulse program header file: HEADER_NAME = 'defaults.include' #hardware config # board : atmega328 for duemilanove # board is uno for uno # if ARDUINO_DEV is None, we'll guess # otherwise all of these must be set. ARDUINO_DEV = 'auto' ARDUINO_BOARD = 'auto' #these are com0com fake ports used for a serial pipe. HUB1 = None #autodetect HUB2 = None ################ End of configuration variables. TMPDIR is in anmr_common #To force DEV and BOARD settings: #ARDUINO_DEV is something like: 'COM3' #ARDUINO_BOARD is 'uno' or 'atmega328' #it's used by scons -> avrdude to program it. #eg ARDUINO_DEV='COM6' HUB1='COM7' HUB2='COM8' ICON_EXTENSION="24.xpm" # used to find serial ports: try: import winreg as winreg except: import _winreg as winreg import itertools #used to list processes import win32com.client import ctypes class MyToolbar(NavigationToolbar2): #idea borrowed from: http://dalelane.co.uk/blog/?p=778 # but redone a bit differently. # we inhereit the navigation toolbar, but redefine the toolitems # list of toolitems to add to the toolbar, format is: # text, tooltip_text, image_file, callback(str) toolitems = ( ('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous view','back', 'back'), ('Forward', 'Forward to next view','forward', 'forward'), ('Pan', 'Pan axes with left mouse, zoom with right', 'move','pan'), ('Zoom', 'Zoom to rectangle','zoom_to_rect', 'zoom'), (None, None, None, None), # ('Subplots', 'Configure subplots','subplots.png', 'configure_subplots'), ('Save', 'Save the figure','filesave', 'save_figure'), ) #windows specific count serial ports: def enumerate_serial_ports(): """ Uses the Win32 registry to return an iterator of serial (COM) ports existing on this computer. """ path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise IterationError for i in itertools.count(): try: val = winreg.EnumValue(key, i) yield (str(val[1]), str(val[0])) except EnvironmentError: break def pipeRunning(tempDir): #tempDir is ignored here, is used in linux version # this is simplified from: # http://www.blog.pythonlibrary.org/2010/10/03/how-to-find-and-list-all-running-processes-with-python/ head,tail = os.path.split(HUB4COM) wmi=win32com.client.GetObject('winmgmts:') for p in wmi.InstancesOf('win32_process'): # if p.Name == 'hub4com.exe': if p.Name == tail: return True return False def detectArduino(tempDir): #tempDir is ignored here, used in linux version global ARDUINO_DEV,ARDUINO_BOARD,HUB1,HUB2 myArduinoDev = ARDUINO_DEV if myArduinoDev == 'auto': ARDUINO_BOARD = 'auto' HUB1 = None HUB2 = None for port, desc in enumerate_serial_ports(): print("port: ",port," desc: ",desc) if desc[8:15] == 'com0com': if HUB1 is None: HUB1 = port print('first pseudo port is: ',HUB1) elif HUB2 is None: HUB2 = port print('second pseudo port is: ',HUB2) if desc[8:11] == 'VCP': print('deumilanove at: ',port) myArduinoDev = port ARDUINO_BOARD='atmega328' if desc[8:14] == 'USBSER': print('found Uno at:',port) myArduinoDev = port ARDUINO_BOARD = 'uno' if myArduinoDev == 'auto' or (USE_SERIAL_PIPE == True and (HUB1 is None or HUB2 is None)): print("have a missing device?") print("ARDUINO_DEV: ", myArduinoDev) print("HUB1: ",HUB1) print("HUB2: ",HUB2) #popup_msg("Couldn't find a serial device?") return None,None,None,None if USE_SERIAL_PIPE: return myArduinoDev,HUB2,ARDUINO_BOARD,'software' else: return myArduinoDev,myArduinoDev,ARDUINO_BOARD,'hardware' def startSerialPipe(hardwareDev,arduinoDev): #in here arduinoDev is ignored, used in linux version. We link the #hardwareDev to HUM1, then HUB2 is what's talked to. args = [HUB4COM,'--route=All:All','--octs=off','--baud=1000000','\\\\.\\'+hardwareDev,'--baud=1000000','\\\\.\\'+HUB1] print('args are:',args) try: proc = subprocess.Popen(args) #should do a better job of checking this? return True except: return False def
(tempDir): head,tail = os.path.split(HUB4COM) wmi=win32com.client.GetObject('winmgmts:') for p in wmi.InstancesOf('win32_process'): # if p.Name == 'hub4com.exe': if p.Name == tail: pid = int(p.Properties_('ProcessId')) print('Found: ',p.Name, 'pid: ',pid, ' Killing.') kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(1,0,pid) kernel32.TerminateProcess(handle,0) #it still gets detected unless we wait a moment: time.sleep(0.1) if pipeRunning(None) == False: print('successfully killed hub4com') return True print('tried to kill hub4com, but seems to still be running') return False
killSerialPipe
identifier_name
anmr_platform_win.py
#from matplotlib.backends.backend_gtk import NavigationToolbar2GTK as NavigationToolbar2 from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar2 import subprocess import shlex import re import posixpath from anmr_common import * # use hub4com ? USE_SERIAL_PIPE=False #external helper programs: #hub4com is quoted differently than sox because its arguments are tricky. HUB4COM='C:\\Program Files\\hub4com\\hub4com.exe' SOX_EXEC='"c:\\Program Files\\sox-14-4-0\\sox.exe"' AVRDUDE='c:\\Anmr\\avrdude\\avrdude.exe' AVRDUDE_CONF='C:\\Anmr\\avrdude\\avrdude.conf' #standard windows install: IMAGE_VIEWER = 'rundll32.exe "c:\\WINDOWS\\System32\\shimgvw.dll,ImageView_Fullscreen"' #Anmr installs: #this one is also in Shim.py ICON_PATH='c:\\Anmr\\Icons' #our firmware #ARDUINO_CODE = 'c:\\Anmr\\arduinoCode' FIRMWARE='c:\\Anmr\\arduinoCode\\arduinoCode.hex' #pulse programs: PROG_DIR = 'c:\\Anmr\\PulsePrograms' #pulse program header file: HEADER_NAME = 'defaults.include' #hardware config # board : atmega328 for duemilanove # board is uno for uno # if ARDUINO_DEV is None, we'll guess # otherwise all of these must be set. ARDUINO_DEV = 'auto' ARDUINO_BOARD = 'auto' #these are com0com fake ports used for a serial pipe. HUB1 = None #autodetect HUB2 = None ################ End of configuration variables. TMPDIR is in anmr_common #To force DEV and BOARD settings: #ARDUINO_DEV is something like: 'COM3' #ARDUINO_BOARD is 'uno' or 'atmega328' #it's used by scons -> avrdude to program it. #eg ARDUINO_DEV='COM6' HUB1='COM7' HUB2='COM8' ICON_EXTENSION="24.xpm" # used to find serial ports: try: import winreg as winreg except: import _winreg as winreg import itertools #used to list processes import win32com.client import ctypes class MyToolbar(NavigationToolbar2): #idea borrowed from: http://dalelane.co.uk/blog/?p=778 # but redone a bit differently. # we inhereit the navigation toolbar, but redefine the toolitems # list of toolitems to add to the toolbar, format is: # text, tooltip_text, image_file, callback(str) toolitems = ( ('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous view','back', 'back'), ('Forward', 'Forward to next view','forward', 'forward'), ('Pan', 'Pan axes with left mouse, zoom with right', 'move','pan'), ('Zoom', 'Zoom to rectangle','zoom_to_rect', 'zoom'), (None, None, None, None), # ('Subplots', 'Configure subplots','subplots.png', 'configure_subplots'), ('Save', 'Save the figure','filesave', 'save_figure'), ) #windows specific count serial ports: def enumerate_serial_ports(): """ Uses the Win32 registry to return an iterator of serial (COM) ports existing on this computer. """ path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise IterationError for i in itertools.count(): try: val = winreg.EnumValue(key, i) yield (str(val[1]), str(val[0])) except EnvironmentError: break def pipeRunning(tempDir): #tempDir is ignored here, is used in linux version # this is simplified from: # http://www.blog.pythonlibrary.org/2010/10/03/how-to-find-and-list-all-running-processes-with-python/
def detectArduino(tempDir): #tempDir is ignored here, used in linux version global ARDUINO_DEV,ARDUINO_BOARD,HUB1,HUB2 myArduinoDev = ARDUINO_DEV if myArduinoDev == 'auto': ARDUINO_BOARD = 'auto' HUB1 = None HUB2 = None for port, desc in enumerate_serial_ports(): print("port: ",port," desc: ",desc) if desc[8:15] == 'com0com': if HUB1 is None: HUB1 = port print('first pseudo port is: ',HUB1) elif HUB2 is None: HUB2 = port print('second pseudo port is: ',HUB2) if desc[8:11] == 'VCP': print('deumilanove at: ',port) myArduinoDev = port ARDUINO_BOARD='atmega328' if desc[8:14] == 'USBSER': print('found Uno at:',port) myArduinoDev = port ARDUINO_BOARD = 'uno' if myArduinoDev == 'auto' or (USE_SERIAL_PIPE == True and (HUB1 is None or HUB2 is None)): print("have a missing device?") print("ARDUINO_DEV: ", myArduinoDev) print("HUB1: ",HUB1) print("HUB2: ",HUB2) #popup_msg("Couldn't find a serial device?") return None,None,None,None if USE_SERIAL_PIPE: return myArduinoDev,HUB2,ARDUINO_BOARD,'software' else: return myArduinoDev,myArduinoDev,ARDUINO_BOARD,'hardware' def startSerialPipe(hardwareDev,arduinoDev): #in here arduinoDev is ignored, used in linux version. We link the #hardwareDev to HUM1, then HUB2 is what's talked to. args = [HUB4COM,'--route=All:All','--octs=off','--baud=1000000','\\\\.\\'+hardwareDev,'--baud=1000000','\\\\.\\'+HUB1] print('args are:',args) try: proc = subprocess.Popen(args) #should do a better job of checking this? return True except: return False def killSerialPipe(tempDir): head,tail = os.path.split(HUB4COM) wmi=win32com.client.GetObject('winmgmts:') for p in wmi.InstancesOf('win32_process'): # if p.Name == 'hub4com.exe': if p.Name == tail: pid = int(p.Properties_('ProcessId')) print('Found: ',p.Name, 'pid: ',pid, ' Killing.') kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(1,0,pid) kernel32.TerminateProcess(handle,0) #it still gets detected unless we wait a moment: time.sleep(0.1) if pipeRunning(None) == False: print('successfully killed hub4com') return True print('tried to kill hub4com, but seems to still be running') return False
head,tail = os.path.split(HUB4COM) wmi=win32com.client.GetObject('winmgmts:') for p in wmi.InstancesOf('win32_process'): # if p.Name == 'hub4com.exe': if p.Name == tail: return True return False
identifier_body
anmr_platform_win.py
#from matplotlib.backends.backend_gtk import NavigationToolbar2GTK as NavigationToolbar2 from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar2 import subprocess import shlex import re import posixpath from anmr_common import * # use hub4com ? USE_SERIAL_PIPE=False #external helper programs: #hub4com is quoted differently than sox because its arguments are tricky. HUB4COM='C:\\Program Files\\hub4com\\hub4com.exe' SOX_EXEC='"c:\\Program Files\\sox-14-4-0\\sox.exe"' AVRDUDE='c:\\Anmr\\avrdude\\avrdude.exe' AVRDUDE_CONF='C:\\Anmr\\avrdude\\avrdude.conf' #standard windows install: IMAGE_VIEWER = 'rundll32.exe "c:\\WINDOWS\\System32\\shimgvw.dll,ImageView_Fullscreen"' #Anmr installs: #this one is also in Shim.py ICON_PATH='c:\\Anmr\\Icons' #our firmware #ARDUINO_CODE = 'c:\\Anmr\\arduinoCode' FIRMWARE='c:\\Anmr\\arduinoCode\\arduinoCode.hex' #pulse programs: PROG_DIR = 'c:\\Anmr\\PulsePrograms' #pulse program header file: HEADER_NAME = 'defaults.include' #hardware config # board : atmega328 for duemilanove # board is uno for uno # if ARDUINO_DEV is None, we'll guess # otherwise all of these must be set. ARDUINO_DEV = 'auto' ARDUINO_BOARD = 'auto' #these are com0com fake ports used for a serial pipe. HUB1 = None #autodetect HUB2 = None ################ End of configuration variables. TMPDIR is in anmr_common #To force DEV and BOARD settings: #ARDUINO_DEV is something like: 'COM3' #ARDUINO_BOARD is 'uno' or 'atmega328' #it's used by scons -> avrdude to program it. #eg ARDUINO_DEV='COM6' HUB1='COM7' HUB2='COM8' ICON_EXTENSION="24.xpm" # used to find serial ports: try: import winreg as winreg except: import _winreg as winreg import itertools #used to list processes import win32com.client import ctypes class MyToolbar(NavigationToolbar2): #idea borrowed from: http://dalelane.co.uk/blog/?p=778 # but redone a bit differently. # we inhereit the navigation toolbar, but redefine the toolitems # list of toolitems to add to the toolbar, format is: # text, tooltip_text, image_file, callback(str) toolitems = ( ('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous view','back', 'back'), ('Forward', 'Forward to next view','forward', 'forward'), ('Pan', 'Pan axes with left mouse, zoom with right', 'move','pan'), ('Zoom', 'Zoom to rectangle','zoom_to_rect', 'zoom'), (None, None, None, None), # ('Subplots', 'Configure subplots','subplots.png', 'configure_subplots'), ('Save', 'Save the figure','filesave', 'save_figure'), ) #windows specific count serial ports: def enumerate_serial_ports(): """ Uses the Win32 registry to return an iterator of serial (COM) ports existing on this computer. """ path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise IterationError for i in itertools.count(): try: val = winreg.EnumValue(key, i) yield (str(val[1]), str(val[0])) except EnvironmentError: break def pipeRunning(tempDir): #tempDir is ignored here, is used in linux version # this is simplified from: # http://www.blog.pythonlibrary.org/2010/10/03/how-to-find-and-list-all-running-processes-with-python/ head,tail = os.path.split(HUB4COM) wmi=win32com.client.GetObject('winmgmts:') for p in wmi.InstancesOf('win32_process'): # if p.Name == 'hub4com.exe': if p.Name == tail: return True return False def detectArduino(tempDir): #tempDir is ignored here, used in linux version global ARDUINO_DEV,ARDUINO_BOARD,HUB1,HUB2 myArduinoDev = ARDUINO_DEV if myArduinoDev == 'auto': ARDUINO_BOARD = 'auto' HUB1 = None HUB2 = None for port, desc in enumerate_serial_ports(): print("port: ",port," desc: ",desc) if desc[8:15] == 'com0com': if HUB1 is None: HUB1 = port print('first pseudo port is: ',HUB1) elif HUB2 is None: HUB2 = port print('second pseudo port is: ',HUB2) if desc[8:11] == 'VCP': print('deumilanove at: ',port) myArduinoDev = port ARDUINO_BOARD='atmega328' if desc[8:14] == 'USBSER': print('found Uno at:',port) myArduinoDev = port ARDUINO_BOARD = 'uno' if myArduinoDev == 'auto' or (USE_SERIAL_PIPE == True and (HUB1 is None or HUB2 is None)): print("have a missing device?") print("ARDUINO_DEV: ", myArduinoDev) print("HUB1: ",HUB1) print("HUB2: ",HUB2) #popup_msg("Couldn't find a serial device?") return None,None,None,None if USE_SERIAL_PIPE: return myArduinoDev,HUB2,ARDUINO_BOARD,'software' else: return myArduinoDev,myArduinoDev,ARDUINO_BOARD,'hardware' def startSerialPipe(hardwareDev,arduinoDev): #in here arduinoDev is ignored, used in linux version. We link the #hardwareDev to HUM1, then HUB2 is what's talked to. args = [HUB4COM,'--route=All:All','--octs=off','--baud=1000000','\\\\.\\'+hardwareDev,'--baud=1000000','\\\\.\\'+HUB1] print('args are:',args) try: proc = subprocess.Popen(args) #should do a better job of checking this? return True except: return False def killSerialPipe(tempDir): head,tail = os.path.split(HUB4COM) wmi=win32com.client.GetObject('winmgmts:') for p in wmi.InstancesOf('win32_process'): # if p.Name == 'hub4com.exe': if p.Name == tail:
#it still gets detected unless we wait a moment: time.sleep(0.1) if pipeRunning(None) == False: print('successfully killed hub4com') return True print('tried to kill hub4com, but seems to still be running') return False
pid = int(p.Properties_('ProcessId')) print('Found: ',p.Name, 'pid: ',pid, ' Killing.') kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(1,0,pid) kernel32.TerminateProcess(handle,0)
conditional_block
anmr_platform_win.py
#from matplotlib.backends.backend_gtk import NavigationToolbar2GTK as NavigationToolbar2 from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar2 import subprocess import shlex import re import posixpath from anmr_common import * # use hub4com ? USE_SERIAL_PIPE=False #external helper programs: #hub4com is quoted differently than sox because its arguments are tricky. HUB4COM='C:\\Program Files\\hub4com\\hub4com.exe' SOX_EXEC='"c:\\Program Files\\sox-14-4-0\\sox.exe"' AVRDUDE='c:\\Anmr\\avrdude\\avrdude.exe' AVRDUDE_CONF='C:\\Anmr\\avrdude\\avrdude.conf' #standard windows install: IMAGE_VIEWER = 'rundll32.exe "c:\\WINDOWS\\System32\\shimgvw.dll,ImageView_Fullscreen"' #Anmr installs: #this one is also in Shim.py ICON_PATH='c:\\Anmr\\Icons' #our firmware #ARDUINO_CODE = 'c:\\Anmr\\arduinoCode' FIRMWARE='c:\\Anmr\\arduinoCode\\arduinoCode.hex' #pulse programs: PROG_DIR = 'c:\\Anmr\\PulsePrograms' #pulse program header file: HEADER_NAME = 'defaults.include' #hardware config # board : atmega328 for duemilanove # board is uno for uno # if ARDUINO_DEV is None, we'll guess # otherwise all of these must be set. ARDUINO_DEV = 'auto' ARDUINO_BOARD = 'auto' #these are com0com fake ports used for a serial pipe. HUB1 = None #autodetect HUB2 = None ################ End of configuration variables. TMPDIR is in anmr_common #To force DEV and BOARD settings: #ARDUINO_DEV is something like: 'COM3' #ARDUINO_BOARD is 'uno' or 'atmega328' #it's used by scons -> avrdude to program it. #eg ARDUINO_DEV='COM6' HUB1='COM7' HUB2='COM8' ICON_EXTENSION="24.xpm" # used to find serial ports: try: import winreg as winreg except: import _winreg as winreg import itertools #used to list processes import win32com.client import ctypes class MyToolbar(NavigationToolbar2): #idea borrowed from: http://dalelane.co.uk/blog/?p=778 # but redone a bit differently. # we inhereit the navigation toolbar, but redefine the toolitems # list of toolitems to add to the toolbar, format is: # text, tooltip_text, image_file, callback(str) toolitems = ( ('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous view','back', 'back'), ('Forward', 'Forward to next view','forward', 'forward'), ('Pan', 'Pan axes with left mouse, zoom with right', 'move','pan'), ('Zoom', 'Zoom to rectangle','zoom_to_rect', 'zoom'), (None, None, None, None), # ('Subplots', 'Configure subplots','subplots.png', 'configure_subplots'), ('Save', 'Save the figure','filesave', 'save_figure'), ) #windows specific count serial ports: def enumerate_serial_ports(): """ Uses the Win32 registry to return an iterator of serial (COM) ports existing on this computer. """ path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise IterationError for i in itertools.count(): try: val = winreg.EnumValue(key, i) yield (str(val[1]), str(val[0])) except EnvironmentError: break def pipeRunning(tempDir): #tempDir is ignored here, is used in linux version # this is simplified from: # http://www.blog.pythonlibrary.org/2010/10/03/how-to-find-and-list-all-running-processes-with-python/ head,tail = os.path.split(HUB4COM) wmi=win32com.client.GetObject('winmgmts:') for p in wmi.InstancesOf('win32_process'): # if p.Name == 'hub4com.exe': if p.Name == tail: return True return False def detectArduino(tempDir): #tempDir is ignored here, used in linux version global ARDUINO_DEV,ARDUINO_BOARD,HUB1,HUB2 myArduinoDev = ARDUINO_DEV if myArduinoDev == 'auto': ARDUINO_BOARD = 'auto' HUB1 = None HUB2 = None for port, desc in enumerate_serial_ports(): print("port: ",port," desc: ",desc) if desc[8:15] == 'com0com': if HUB1 is None: HUB1 = port print('first pseudo port is: ',HUB1) elif HUB2 is None: HUB2 = port print('second pseudo port is: ',HUB2) if desc[8:11] == 'VCP': print('deumilanove at: ',port) myArduinoDev = port ARDUINO_BOARD='atmega328' if desc[8:14] == 'USBSER': print('found Uno at:',port) myArduinoDev = port ARDUINO_BOARD = 'uno' if myArduinoDev == 'auto' or (USE_SERIAL_PIPE == True and (HUB1 is None or HUB2 is None)): print("have a missing device?") print("ARDUINO_DEV: ", myArduinoDev) print("HUB1: ",HUB1) print("HUB2: ",HUB2) #popup_msg("Couldn't find a serial device?") return None,None,None,None if USE_SERIAL_PIPE: return myArduinoDev,HUB2,ARDUINO_BOARD,'software' else: return myArduinoDev,myArduinoDev,ARDUINO_BOARD,'hardware' def startSerialPipe(hardwareDev,arduinoDev):
#in here arduinoDev is ignored, used in linux version. We link the #hardwareDev to HUM1, then HUB2 is what's talked to. args = [HUB4COM,'--route=All:All','--octs=off','--baud=1000000','\\\\.\\'+hardwareDev,'--baud=1000000','\\\\.\\'+HUB1] print('args are:',args) try: proc = subprocess.Popen(args) #should do a better job of checking this? return True except: return False def killSerialPipe(tempDir): head,tail = os.path.split(HUB4COM) wmi=win32com.client.GetObject('winmgmts:') for p in wmi.InstancesOf('win32_process'): # if p.Name == 'hub4com.exe': if p.Name == tail: pid = int(p.Properties_('ProcessId')) print('Found: ',p.Name, 'pid: ',pid, ' Killing.') kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(1,0,pid) kernel32.TerminateProcess(handle,0) #it still gets detected unless we wait a moment: time.sleep(0.1) if pipeRunning(None) == False: print('successfully killed hub4com') return True print('tried to kill hub4com, but seems to still be running') return False
random_line_split
BaristaCardView.js
/** * card_view = new BaristaCardView({el: $("target_selector", url:"", title:"", subtitle:"", fg_color: "#1b9e77", image:"", span_class: "col-lg-12"}); * * A Backbone View that displays a card of information wrapped in link * The view is meant to be a top level entry point to other pages * basic use: card_view = new BaristaCardView(); * optional arguments: * @param {string} url the link to navigate to if the card is clicked, defaults to "" * @param {string} title the title of the card. defaults to "title" * @param {string} subtitle the subtitle of the card. defaults to "subtitle" * @param {string} image the link to an image to show as the cards main content. defaults to ""
* #1b9e77 * @param {string} span_class a bootstrap span class to size the width of the view, defaults to * "col-lg-12" */ Barista.Views.BaristaCardView = Backbone.View.extend({ /** * give the view a name to be used throughout the View's functions when it needs to know what its class * name is * @type {String} */ name: "BaristaCardView", /** * supply a base model for the view * Overide this if you need to use it for dynamic content * @type {Backbone} */ model: new Backbone.Model(), /** * overide the view's default initialize method in order to catch options and render a custom template */ initialize: function(){ // set up color options. default if not specified this.fg_color = (this.options.fg_color !== undefined) ? this.options.fg_color : "#1b9e77"; // set up the span size this.span_class = (this.options.span_class !== undefined) ? this.options.span_class : "col-lg-12"; // set up the url this.url = (this.options.url !== undefined) ? this.options.url : ""; // set up the title this.title = (this.options.title !== undefined) ? this.options.title : "Title"; // set up the subtitle this.subtitle = (this.options.subtitle !== undefined) ? this.options.subtitle : "subtitle"; // set up the image this.image = (this.options.image !== undefined) ? this.options.image : ""; // bind render to model changes this.listenTo(this.model,'change', this.update); // compile the default template for the view this.compile_template(); }, /** * use Handlebars to compile the template for the view */ compile_template: function(){ var self = this; this.div_string = 'barista_view' + new Date().getTime();; this.$el.append(BaristaTemplates.CMapCard({div_string: this.div_string, span_class: this.span_class, url: this.url, title: this.title, subtitle: this.subtitle, image: this.image, fg_color: this.fg_color})); } });
* @param {string} fg_color the hex color code to use as the foreground color of the view, defaults to
random_line_split
stability_summary.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module crawls a `clean::Crate` and produces a summarization of the //! stability levels within the crate. The summary contains the module //! hierarchy, with item counts for every stability level per module. A parent //! module's count includes its children's. use std::ops::Add; use std::num::Zero; use syntax::attr::{Deprecated, Experimental, Unstable, Stable, Frozen, Locked}; use syntax::ast::Public; use clean::{Crate, Item, ModuleItem, Module, EnumItem, Enum}; use clean::{ImplItem, Impl, Trait, TraitItem, TraitMethod, ProvidedMethod, RequiredMethod}; use clean::{TypeTraitItem, ViewItemItem, PrimitiveItem, Stability}; use html::render::cache; #[deriving(Zero, Encodable, Decodable, PartialEq, Eq)] /// The counts for each stability level. pub struct Counts { pub deprecated: uint, pub experimental: uint, pub unstable: uint, pub stable: uint, pub frozen: uint, pub locked: uint, /// No stability level, inherited or otherwise. pub unmarked: uint, } impl Copy for Counts {} impl Add<Counts, Counts> for Counts { fn add(&self, other: &Counts) -> Counts { Counts { deprecated: self.deprecated + other.deprecated, experimental: self.experimental + other.experimental, unstable: self.unstable + other.unstable, stable: self.stable + other.stable, frozen: self.frozen + other.frozen, locked: self.locked + other.locked, unmarked: self.unmarked + other.unmarked, } } } impl Counts { fn zero() -> Counts { Counts { deprecated: 0, experimental: 0, unstable: 0, stable: 0, frozen: 0, locked: 0, unmarked: 0, } } pub fn total(&self) -> uint { self.deprecated + self.experimental + self.unstable + self.stable + self.frozen + self.locked + self.unmarked } } #[deriving(Encodable, Decodable, PartialEq, Eq)] /// A summarized module, which includes total counts and summarized children /// modules. pub struct ModuleSummary { pub name: String, pub counts: Counts, pub submodules: Vec<ModuleSummary>, } impl PartialOrd for ModuleSummary { fn partial_cmp(&self, other: &ModuleSummary) -> Option<Ordering> { self.name.partial_cmp(&other.name) } } impl Ord for ModuleSummary { fn cmp(&self, other: &ModuleSummary) -> Ordering { self.name.cmp(&other.name) } } // is the item considered publically visible? fn visible(item: &Item) -> bool { match item.inner { ImplItem(_) => true, _ => item.visibility == Some(Public) } } fn count_stability(stab: Option<&Stability>) -> Counts { match stab { None => Counts { unmarked: 1, .. Counts::zero() }, Some(ref stab) => match stab.level { Deprecated => Counts { deprecated: 1, .. Counts::zero() }, Experimental => Counts { experimental: 1, .. Counts::zero() }, Unstable => Counts { unstable: 1, .. Counts::zero() }, Stable => Counts { stable: 1, .. Counts::zero() }, Frozen => Counts { frozen: 1, .. Counts::zero() }, Locked => Counts { locked: 1, .. Counts::zero() }, } } } fn summarize_methods(item: &Item) -> Counts { match cache().impls.get(&item.def_id) { Some(v) => { v.iter().map(|i| { let count = count_stability(i.stability.as_ref()); if i.impl_.trait_.is_none() { count + i.impl_.items.iter() .map(|ti| summarize_item(ti).0) .fold(Counts::zero(), |acc, c| acc + c) } else { count } }).fold(Counts::zero(), |acc, c| acc + c) }, None =>
, } } // Produce the summary for an arbitrary item. If the item is a module, include a // module summary. The counts for items with nested items (e.g. modules, traits, // impls) include all children counts. fn summarize_item(item: &Item) -> (Counts, Option<ModuleSummary>) { let item_counts = count_stability(item.stability.as_ref()) + summarize_methods(item); // Count this item's children, if any. Note that a trait impl is // considered to have no children. match item.inner { // Require explicit `pub` to be visible ImplItem(Impl { items: ref subitems, trait_: None, .. }) => { let subcounts = subitems.iter().filter(|i| visible(*i)) .map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (subcounts, None) } // `pub` automatically EnumItem(Enum { variants: ref subitems, .. }) => { let subcounts = subitems.iter().map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (item_counts + subcounts, None) } TraitItem(Trait { items: ref trait_items, .. }) => { fn extract_item<'a>(trait_item: &'a TraitMethod) -> &'a Item { match *trait_item { ProvidedMethod(ref item) | RequiredMethod(ref item) | TypeTraitItem(ref item) => item } } let subcounts = trait_items.iter() .map(extract_item) .map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (item_counts + subcounts, None) } ModuleItem(Module { ref items, .. }) => { let mut counts = item_counts; let mut submodules = Vec::new(); for (subcounts, submodule) in items.iter().filter(|i| visible(*i)) .map(summarize_item) { counts = counts + subcounts; submodule.map(|m| submodules.push(m)); } submodules.sort(); (counts, Some(ModuleSummary { name: item.name.as_ref().map_or("".to_string(), |n| n.clone()), counts: counts, submodules: submodules, })) } // no stability information for the following items: ViewItemItem(_) | PrimitiveItem(_) => (Counts::zero(), None), _ => (item_counts, None) } } /// Summarizes the stability levels in a crate. pub fn build(krate: &Crate) -> ModuleSummary { match krate.module { None => ModuleSummary { name: krate.name.clone(), counts: Counts::zero(), submodules: Vec::new(), }, Some(ref item) => ModuleSummary { name: krate.name.clone(), .. summarize_item(item).val1().unwrap() } } }
{ Counts::zero() }
conditional_block
stability_summary.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module crawls a `clean::Crate` and produces a summarization of the //! stability levels within the crate. The summary contains the module //! hierarchy, with item counts for every stability level per module. A parent //! module's count includes its children's. use std::ops::Add; use std::num::Zero; use syntax::attr::{Deprecated, Experimental, Unstable, Stable, Frozen, Locked}; use syntax::ast::Public; use clean::{Crate, Item, ModuleItem, Module, EnumItem, Enum}; use clean::{ImplItem, Impl, Trait, TraitItem, TraitMethod, ProvidedMethod, RequiredMethod}; use clean::{TypeTraitItem, ViewItemItem, PrimitiveItem, Stability}; use html::render::cache; #[deriving(Zero, Encodable, Decodable, PartialEq, Eq)] /// The counts for each stability level. pub struct Counts { pub deprecated: uint, pub experimental: uint, pub unstable: uint, pub stable: uint, pub frozen: uint, pub locked: uint, /// No stability level, inherited or otherwise. pub unmarked: uint, } impl Copy for Counts {} impl Add<Counts, Counts> for Counts { fn add(&self, other: &Counts) -> Counts { Counts { deprecated: self.deprecated + other.deprecated, experimental: self.experimental + other.experimental, unstable: self.unstable + other.unstable, stable: self.stable + other.stable, frozen: self.frozen + other.frozen, locked: self.locked + other.locked, unmarked: self.unmarked + other.unmarked, } } } impl Counts { fn zero() -> Counts { Counts { deprecated: 0, experimental: 0, unstable: 0, stable: 0, frozen: 0, locked: 0, unmarked: 0, } } pub fn total(&self) -> uint { self.deprecated + self.experimental + self.unstable + self.stable + self.frozen + self.locked + self.unmarked } } #[deriving(Encodable, Decodable, PartialEq, Eq)] /// A summarized module, which includes total counts and summarized children /// modules. pub struct ModuleSummary { pub name: String, pub counts: Counts, pub submodules: Vec<ModuleSummary>, } impl PartialOrd for ModuleSummary { fn partial_cmp(&self, other: &ModuleSummary) -> Option<Ordering>
} impl Ord for ModuleSummary { fn cmp(&self, other: &ModuleSummary) -> Ordering { self.name.cmp(&other.name) } } // is the item considered publically visible? fn visible(item: &Item) -> bool { match item.inner { ImplItem(_) => true, _ => item.visibility == Some(Public) } } fn count_stability(stab: Option<&Stability>) -> Counts { match stab { None => Counts { unmarked: 1, .. Counts::zero() }, Some(ref stab) => match stab.level { Deprecated => Counts { deprecated: 1, .. Counts::zero() }, Experimental => Counts { experimental: 1, .. Counts::zero() }, Unstable => Counts { unstable: 1, .. Counts::zero() }, Stable => Counts { stable: 1, .. Counts::zero() }, Frozen => Counts { frozen: 1, .. Counts::zero() }, Locked => Counts { locked: 1, .. Counts::zero() }, } } } fn summarize_methods(item: &Item) -> Counts { match cache().impls.get(&item.def_id) { Some(v) => { v.iter().map(|i| { let count = count_stability(i.stability.as_ref()); if i.impl_.trait_.is_none() { count + i.impl_.items.iter() .map(|ti| summarize_item(ti).0) .fold(Counts::zero(), |acc, c| acc + c) } else { count } }).fold(Counts::zero(), |acc, c| acc + c) }, None => { Counts::zero() }, } } // Produce the summary for an arbitrary item. If the item is a module, include a // module summary. The counts for items with nested items (e.g. modules, traits, // impls) include all children counts. fn summarize_item(item: &Item) -> (Counts, Option<ModuleSummary>) { let item_counts = count_stability(item.stability.as_ref()) + summarize_methods(item); // Count this item's children, if any. Note that a trait impl is // considered to have no children. match item.inner { // Require explicit `pub` to be visible ImplItem(Impl { items: ref subitems, trait_: None, .. }) => { let subcounts = subitems.iter().filter(|i| visible(*i)) .map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (subcounts, None) } // `pub` automatically EnumItem(Enum { variants: ref subitems, .. }) => { let subcounts = subitems.iter().map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (item_counts + subcounts, None) } TraitItem(Trait { items: ref trait_items, .. }) => { fn extract_item<'a>(trait_item: &'a TraitMethod) -> &'a Item { match *trait_item { ProvidedMethod(ref item) | RequiredMethod(ref item) | TypeTraitItem(ref item) => item } } let subcounts = trait_items.iter() .map(extract_item) .map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (item_counts + subcounts, None) } ModuleItem(Module { ref items, .. }) => { let mut counts = item_counts; let mut submodules = Vec::new(); for (subcounts, submodule) in items.iter().filter(|i| visible(*i)) .map(summarize_item) { counts = counts + subcounts; submodule.map(|m| submodules.push(m)); } submodules.sort(); (counts, Some(ModuleSummary { name: item.name.as_ref().map_or("".to_string(), |n| n.clone()), counts: counts, submodules: submodules, })) } // no stability information for the following items: ViewItemItem(_) | PrimitiveItem(_) => (Counts::zero(), None), _ => (item_counts, None) } } /// Summarizes the stability levels in a crate. pub fn build(krate: &Crate) -> ModuleSummary { match krate.module { None => ModuleSummary { name: krate.name.clone(), counts: Counts::zero(), submodules: Vec::new(), }, Some(ref item) => ModuleSummary { name: krate.name.clone(), .. summarize_item(item).val1().unwrap() } } }
{ self.name.partial_cmp(&other.name) }
identifier_body
stability_summary.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module crawls a `clean::Crate` and produces a summarization of the //! stability levels within the crate. The summary contains the module //! hierarchy, with item counts for every stability level per module. A parent //! module's count includes its children's. use std::ops::Add; use std::num::Zero; use syntax::attr::{Deprecated, Experimental, Unstable, Stable, Frozen, Locked}; use syntax::ast::Public; use clean::{Crate, Item, ModuleItem, Module, EnumItem, Enum}; use clean::{ImplItem, Impl, Trait, TraitItem, TraitMethod, ProvidedMethod, RequiredMethod}; use clean::{TypeTraitItem, ViewItemItem, PrimitiveItem, Stability}; use html::render::cache; #[deriving(Zero, Encodable, Decodable, PartialEq, Eq)] /// The counts for each stability level. pub struct Counts { pub deprecated: uint, pub experimental: uint, pub unstable: uint, pub stable: uint, pub frozen: uint, pub locked: uint, /// No stability level, inherited or otherwise. pub unmarked: uint, } impl Copy for Counts {} impl Add<Counts, Counts> for Counts { fn add(&self, other: &Counts) -> Counts { Counts { deprecated: self.deprecated + other.deprecated, experimental: self.experimental + other.experimental, unstable: self.unstable + other.unstable, stable: self.stable + other.stable, frozen: self.frozen + other.frozen, locked: self.locked + other.locked, unmarked: self.unmarked + other.unmarked, } } } impl Counts { fn
() -> Counts { Counts { deprecated: 0, experimental: 0, unstable: 0, stable: 0, frozen: 0, locked: 0, unmarked: 0, } } pub fn total(&self) -> uint { self.deprecated + self.experimental + self.unstable + self.stable + self.frozen + self.locked + self.unmarked } } #[deriving(Encodable, Decodable, PartialEq, Eq)] /// A summarized module, which includes total counts and summarized children /// modules. pub struct ModuleSummary { pub name: String, pub counts: Counts, pub submodules: Vec<ModuleSummary>, } impl PartialOrd for ModuleSummary { fn partial_cmp(&self, other: &ModuleSummary) -> Option<Ordering> { self.name.partial_cmp(&other.name) } } impl Ord for ModuleSummary { fn cmp(&self, other: &ModuleSummary) -> Ordering { self.name.cmp(&other.name) } } // is the item considered publically visible? fn visible(item: &Item) -> bool { match item.inner { ImplItem(_) => true, _ => item.visibility == Some(Public) } } fn count_stability(stab: Option<&Stability>) -> Counts { match stab { None => Counts { unmarked: 1, .. Counts::zero() }, Some(ref stab) => match stab.level { Deprecated => Counts { deprecated: 1, .. Counts::zero() }, Experimental => Counts { experimental: 1, .. Counts::zero() }, Unstable => Counts { unstable: 1, .. Counts::zero() }, Stable => Counts { stable: 1, .. Counts::zero() }, Frozen => Counts { frozen: 1, .. Counts::zero() }, Locked => Counts { locked: 1, .. Counts::zero() }, } } } fn summarize_methods(item: &Item) -> Counts { match cache().impls.get(&item.def_id) { Some(v) => { v.iter().map(|i| { let count = count_stability(i.stability.as_ref()); if i.impl_.trait_.is_none() { count + i.impl_.items.iter() .map(|ti| summarize_item(ti).0) .fold(Counts::zero(), |acc, c| acc + c) } else { count } }).fold(Counts::zero(), |acc, c| acc + c) }, None => { Counts::zero() }, } } // Produce the summary for an arbitrary item. If the item is a module, include a // module summary. The counts for items with nested items (e.g. modules, traits, // impls) include all children counts. fn summarize_item(item: &Item) -> (Counts, Option<ModuleSummary>) { let item_counts = count_stability(item.stability.as_ref()) + summarize_methods(item); // Count this item's children, if any. Note that a trait impl is // considered to have no children. match item.inner { // Require explicit `pub` to be visible ImplItem(Impl { items: ref subitems, trait_: None, .. }) => { let subcounts = subitems.iter().filter(|i| visible(*i)) .map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (subcounts, None) } // `pub` automatically EnumItem(Enum { variants: ref subitems, .. }) => { let subcounts = subitems.iter().map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (item_counts + subcounts, None) } TraitItem(Trait { items: ref trait_items, .. }) => { fn extract_item<'a>(trait_item: &'a TraitMethod) -> &'a Item { match *trait_item { ProvidedMethod(ref item) | RequiredMethod(ref item) | TypeTraitItem(ref item) => item } } let subcounts = trait_items.iter() .map(extract_item) .map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (item_counts + subcounts, None) } ModuleItem(Module { ref items, .. }) => { let mut counts = item_counts; let mut submodules = Vec::new(); for (subcounts, submodule) in items.iter().filter(|i| visible(*i)) .map(summarize_item) { counts = counts + subcounts; submodule.map(|m| submodules.push(m)); } submodules.sort(); (counts, Some(ModuleSummary { name: item.name.as_ref().map_or("".to_string(), |n| n.clone()), counts: counts, submodules: submodules, })) } // no stability information for the following items: ViewItemItem(_) | PrimitiveItem(_) => (Counts::zero(), None), _ => (item_counts, None) } } /// Summarizes the stability levels in a crate. pub fn build(krate: &Crate) -> ModuleSummary { match krate.module { None => ModuleSummary { name: krate.name.clone(), counts: Counts::zero(), submodules: Vec::new(), }, Some(ref item) => ModuleSummary { name: krate.name.clone(), .. summarize_item(item).val1().unwrap() } } }
zero
identifier_name
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Samrai(AutotoolsPackage):
"""SAMRAI (Structured Adaptive Mesh Refinement Application Infrastructure) is an object-oriented C++ software library enables exploration of numerical, algorithmic, parallel computing, and software issues associated with applying structured adaptive mesh refinement (SAMR) technology in large-scale parallel application development. """ homepage = "https://computing.llnl.gov/projects/samrai" url = "https://computing.llnl.gov/projects/samrai/download/SAMRAI-v3.11.2.tar.gz" list_url = homepage tags = ['radiuss'] version('3.12.0', sha256='b8334aa22330a7c858e09e000dfc62abbfa3c449212b4993ec3c4035bed6b832') version('3.11.5', sha256='6ec1f4cf2735284fe41f74073c4f1be87d92184d79401011411be3c0671bd84c') version('3.11.4', sha256='fa87f6cc1cb3b3c4856bc3f4d7162b1f9705a200b68a5dc173484f7a71c7ea0a') # Version 3.11.3 permissions don't allow downloading version('3.11.2', sha256='fd9518cc9fd8c8f6cdd681484c6eb42114aebf2a6ba4c8e1f12b34a148dfdefb') version('3.11.1', sha256='14317938e55cb7dc3eca21d9b7667a256a08661c6da988334f7af566a015b327') version('3.10.0', sha256='8d6958867f7165396459f4556e439065bc2cd2464bcfe16195a2a68345d56ea7') version('3.9.1', sha256='ce0aa9bcb3accbd39c09dd32cbc9884dc00e7a8d53782ba46b8fe7d7d60fc03f') version('3.8.0', sha256='0fc811ca83bd72d238f0efb172d466e80e5091db0b78ad00ab6b93331a1fe489') version('3.7.3', sha256='19eada4f351a821abccac0779fde85e2ad18b931b6a8110510a4c21707c2f5ce') version('3.7.2', sha256='c20c5b12576b73a1a095d8ef54536c4424517adaf472d55d48e57455eda74f2d') version('3.6.3-beta', sha256='7d9202355a66b8850333484862627f73ea3d7620ca84cde757dee629ebcb61bb') version('3.5.2-beta', sha256='9a591fc962edd56ea073abd13d03027bd530f1e61df595fae42dd9a7f8b9cc3a') version('3.5.0-beta', sha256='3e10c55d7b652b6feca902ce782751d4b16c8ad9d4dd8b9e2e9ec74dd64f30da') version('3.4.1-beta', sha256='5aadc813b75b65485f221372e174a2691e184e380f569129e7aa4484ca4047f8') version('3.3.3-beta', sha256='c07b5dc8d56a8f310239d1ec6be31182a6463fea787a0e10b54a3df479979cac') version('3.3.2-beta', sha256='430ea1a77083c8990a3c996572ed15663d9b31c0f8b614537bd7065abd6f375f') version('2.4.4', sha256='33242e38e6f4d35bd52f4194bd99a014485b0f3458b268902f69f6c02b35ee5c') # Debug mode reduces optimization, includes assertions, debug symbols # and more print statements variant('debug', default=False, description='Compile with reduced optimization and debugging on') variant('silo', default=False, description='Compile with support for silo') depends_on('mpi') depends_on('zlib') depends_on('hdf5+mpi') depends_on('m4', type='build') depends_on('boost@:1.64.0', when='@3.0.0:3.11', type='build') depends_on('silo+mpi', when='+silo') # don't build SAMRAI 3+ with tools with gcc patch('no-tool-build.patch', when='@3.0.0:%gcc') # 2.4.4 needs a lot of patches to fix ADL and performance problems patch('https://github.com/IBAMR/IBAMR/releases/download/v0.3.0/ibamr-samrai-fixes.patch', sha256='1d088b6cca41377747fa0ae8970440c20cb68988bbc34f9032d5a4e6aceede47', when='@2.4.4') def configure_args(self): options = [] options.extend([ '--with-CXX=%s' % self.spec['mpi'].mpicxx, '--with-CC=%s' % self.spec['mpi'].mpicc, '--with-F77=%s' % self.spec['mpi'].mpifc, '--with-M4=%s' % self.spec['m4'].prefix, '--with-hdf5=%s' % self.spec['hdf5'].prefix, '--with-zlib=%s' % self.spec['zlib'].prefix, '--without-blas', '--without-lapack', '--with-hypre=no', '--with-petsc=no']) # SAMRAI 2 used templates; enable implicit instantiation if self.spec.satisfies('@:3'): options.append('--enable-implicit-template-instantiation') if '+debug' in self.spec: options.extend([ '--disable-opt', '--enable-debug']) else: options.extend([ '--enable-opt', '--disable-debug']) if '+silo' in self.spec: options.append('--with-silo=%s' % self.spec['silo'].prefix) if self.spec.satisfies('@3.0:3.11'): options.append('--with-boost=%s' % self.spec['boost'].prefix) return options def setup_dependent_build_environment(self, env, dependent_spec): if self.spec.satisfies('@3.12:'): env.append_flags('CXXFLAGS', self.compiler.cxx11_flag)
identifier_body
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Samrai(AutotoolsPackage): """SAMRAI (Structured Adaptive Mesh Refinement Application Infrastructure) is an object-oriented C++ software library enables exploration of numerical, algorithmic, parallel computing, and software issues associated with applying structured adaptive mesh refinement (SAMR) technology in large-scale parallel application development. """ homepage = "https://computing.llnl.gov/projects/samrai" url = "https://computing.llnl.gov/projects/samrai/download/SAMRAI-v3.11.2.tar.gz" list_url = homepage tags = ['radiuss'] version('3.12.0', sha256='b8334aa22330a7c858e09e000dfc62abbfa3c449212b4993ec3c4035bed6b832') version('3.11.5', sha256='6ec1f4cf2735284fe41f74073c4f1be87d92184d79401011411be3c0671bd84c') version('3.11.4', sha256='fa87f6cc1cb3b3c4856bc3f4d7162b1f9705a200b68a5dc173484f7a71c7ea0a') # Version 3.11.3 permissions don't allow downloading version('3.11.2', sha256='fd9518cc9fd8c8f6cdd681484c6eb42114aebf2a6ba4c8e1f12b34a148dfdefb') version('3.11.1', sha256='14317938e55cb7dc3eca21d9b7667a256a08661c6da988334f7af566a015b327') version('3.10.0', sha256='8d6958867f7165396459f4556e439065bc2cd2464bcfe16195a2a68345d56ea7') version('3.9.1', sha256='ce0aa9bcb3accbd39c09dd32cbc9884dc00e7a8d53782ba46b8fe7d7d60fc03f') version('3.8.0', sha256='0fc811ca83bd72d238f0efb172d466e80e5091db0b78ad00ab6b93331a1fe489') version('3.7.3', sha256='19eada4f351a821abccac0779fde85e2ad18b931b6a8110510a4c21707c2f5ce') version('3.7.2', sha256='c20c5b12576b73a1a095d8ef54536c4424517adaf472d55d48e57455eda74f2d') version('3.6.3-beta', sha256='7d9202355a66b8850333484862627f73ea3d7620ca84cde757dee629ebcb61bb') version('3.5.2-beta', sha256='9a591fc962edd56ea073abd13d03027bd530f1e61df595fae42dd9a7f8b9cc3a') version('3.5.0-beta', sha256='3e10c55d7b652b6feca902ce782751d4b16c8ad9d4dd8b9e2e9ec74dd64f30da') version('3.4.1-beta', sha256='5aadc813b75b65485f221372e174a2691e184e380f569129e7aa4484ca4047f8') version('3.3.3-beta', sha256='c07b5dc8d56a8f310239d1ec6be31182a6463fea787a0e10b54a3df479979cac') version('3.3.2-beta', sha256='430ea1a77083c8990a3c996572ed15663d9b31c0f8b614537bd7065abd6f375f') version('2.4.4', sha256='33242e38e6f4d35bd52f4194bd99a014485b0f3458b268902f69f6c02b35ee5c') # Debug mode reduces optimization, includes assertions, debug symbols
depends_on('mpi') depends_on('zlib') depends_on('hdf5+mpi') depends_on('m4', type='build') depends_on('boost@:1.64.0', when='@3.0.0:3.11', type='build') depends_on('silo+mpi', when='+silo') # don't build SAMRAI 3+ with tools with gcc patch('no-tool-build.patch', when='@3.0.0:%gcc') # 2.4.4 needs a lot of patches to fix ADL and performance problems patch('https://github.com/IBAMR/IBAMR/releases/download/v0.3.0/ibamr-samrai-fixes.patch', sha256='1d088b6cca41377747fa0ae8970440c20cb68988bbc34f9032d5a4e6aceede47', when='@2.4.4') def configure_args(self): options = [] options.extend([ '--with-CXX=%s' % self.spec['mpi'].mpicxx, '--with-CC=%s' % self.spec['mpi'].mpicc, '--with-F77=%s' % self.spec['mpi'].mpifc, '--with-M4=%s' % self.spec['m4'].prefix, '--with-hdf5=%s' % self.spec['hdf5'].prefix, '--with-zlib=%s' % self.spec['zlib'].prefix, '--without-blas', '--without-lapack', '--with-hypre=no', '--with-petsc=no']) # SAMRAI 2 used templates; enable implicit instantiation if self.spec.satisfies('@:3'): options.append('--enable-implicit-template-instantiation') if '+debug' in self.spec: options.extend([ '--disable-opt', '--enable-debug']) else: options.extend([ '--enable-opt', '--disable-debug']) if '+silo' in self.spec: options.append('--with-silo=%s' % self.spec['silo'].prefix) if self.spec.satisfies('@3.0:3.11'): options.append('--with-boost=%s' % self.spec['boost'].prefix) return options def setup_dependent_build_environment(self, env, dependent_spec): if self.spec.satisfies('@3.12:'): env.append_flags('CXXFLAGS', self.compiler.cxx11_flag)
# and more print statements variant('debug', default=False, description='Compile with reduced optimization and debugging on') variant('silo', default=False, description='Compile with support for silo')
random_line_split
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Samrai(AutotoolsPackage): """SAMRAI (Structured Adaptive Mesh Refinement Application Infrastructure) is an object-oriented C++ software library enables exploration of numerical, algorithmic, parallel computing, and software issues associated with applying structured adaptive mesh refinement (SAMR) technology in large-scale parallel application development. """ homepage = "https://computing.llnl.gov/projects/samrai" url = "https://computing.llnl.gov/projects/samrai/download/SAMRAI-v3.11.2.tar.gz" list_url = homepage tags = ['radiuss'] version('3.12.0', sha256='b8334aa22330a7c858e09e000dfc62abbfa3c449212b4993ec3c4035bed6b832') version('3.11.5', sha256='6ec1f4cf2735284fe41f74073c4f1be87d92184d79401011411be3c0671bd84c') version('3.11.4', sha256='fa87f6cc1cb3b3c4856bc3f4d7162b1f9705a200b68a5dc173484f7a71c7ea0a') # Version 3.11.3 permissions don't allow downloading version('3.11.2', sha256='fd9518cc9fd8c8f6cdd681484c6eb42114aebf2a6ba4c8e1f12b34a148dfdefb') version('3.11.1', sha256='14317938e55cb7dc3eca21d9b7667a256a08661c6da988334f7af566a015b327') version('3.10.0', sha256='8d6958867f7165396459f4556e439065bc2cd2464bcfe16195a2a68345d56ea7') version('3.9.1', sha256='ce0aa9bcb3accbd39c09dd32cbc9884dc00e7a8d53782ba46b8fe7d7d60fc03f') version('3.8.0', sha256='0fc811ca83bd72d238f0efb172d466e80e5091db0b78ad00ab6b93331a1fe489') version('3.7.3', sha256='19eada4f351a821abccac0779fde85e2ad18b931b6a8110510a4c21707c2f5ce') version('3.7.2', sha256='c20c5b12576b73a1a095d8ef54536c4424517adaf472d55d48e57455eda74f2d') version('3.6.3-beta', sha256='7d9202355a66b8850333484862627f73ea3d7620ca84cde757dee629ebcb61bb') version('3.5.2-beta', sha256='9a591fc962edd56ea073abd13d03027bd530f1e61df595fae42dd9a7f8b9cc3a') version('3.5.0-beta', sha256='3e10c55d7b652b6feca902ce782751d4b16c8ad9d4dd8b9e2e9ec74dd64f30da') version('3.4.1-beta', sha256='5aadc813b75b65485f221372e174a2691e184e380f569129e7aa4484ca4047f8') version('3.3.3-beta', sha256='c07b5dc8d56a8f310239d1ec6be31182a6463fea787a0e10b54a3df479979cac') version('3.3.2-beta', sha256='430ea1a77083c8990a3c996572ed15663d9b31c0f8b614537bd7065abd6f375f') version('2.4.4', sha256='33242e38e6f4d35bd52f4194bd99a014485b0f3458b268902f69f6c02b35ee5c') # Debug mode reduces optimization, includes assertions, debug symbols # and more print statements variant('debug', default=False, description='Compile with reduced optimization and debugging on') variant('silo', default=False, description='Compile with support for silo') depends_on('mpi') depends_on('zlib') depends_on('hdf5+mpi') depends_on('m4', type='build') depends_on('boost@:1.64.0', when='@3.0.0:3.11', type='build') depends_on('silo+mpi', when='+silo') # don't build SAMRAI 3+ with tools with gcc patch('no-tool-build.patch', when='@3.0.0:%gcc') # 2.4.4 needs a lot of patches to fix ADL and performance problems patch('https://github.com/IBAMR/IBAMR/releases/download/v0.3.0/ibamr-samrai-fixes.patch', sha256='1d088b6cca41377747fa0ae8970440c20cb68988bbc34f9032d5a4e6aceede47', when='@2.4.4') def
(self): options = [] options.extend([ '--with-CXX=%s' % self.spec['mpi'].mpicxx, '--with-CC=%s' % self.spec['mpi'].mpicc, '--with-F77=%s' % self.spec['mpi'].mpifc, '--with-M4=%s' % self.spec['m4'].prefix, '--with-hdf5=%s' % self.spec['hdf5'].prefix, '--with-zlib=%s' % self.spec['zlib'].prefix, '--without-blas', '--without-lapack', '--with-hypre=no', '--with-petsc=no']) # SAMRAI 2 used templates; enable implicit instantiation if self.spec.satisfies('@:3'): options.append('--enable-implicit-template-instantiation') if '+debug' in self.spec: options.extend([ '--disable-opt', '--enable-debug']) else: options.extend([ '--enable-opt', '--disable-debug']) if '+silo' in self.spec: options.append('--with-silo=%s' % self.spec['silo'].prefix) if self.spec.satisfies('@3.0:3.11'): options.append('--with-boost=%s' % self.spec['boost'].prefix) return options def setup_dependent_build_environment(self, env, dependent_spec): if self.spec.satisfies('@3.12:'): env.append_flags('CXXFLAGS', self.compiler.cxx11_flag)
configure_args
identifier_name
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Samrai(AutotoolsPackage): """SAMRAI (Structured Adaptive Mesh Refinement Application Infrastructure) is an object-oriented C++ software library enables exploration of numerical, algorithmic, parallel computing, and software issues associated with applying structured adaptive mesh refinement (SAMR) technology in large-scale parallel application development. """ homepage = "https://computing.llnl.gov/projects/samrai" url = "https://computing.llnl.gov/projects/samrai/download/SAMRAI-v3.11.2.tar.gz" list_url = homepage tags = ['radiuss'] version('3.12.0', sha256='b8334aa22330a7c858e09e000dfc62abbfa3c449212b4993ec3c4035bed6b832') version('3.11.5', sha256='6ec1f4cf2735284fe41f74073c4f1be87d92184d79401011411be3c0671bd84c') version('3.11.4', sha256='fa87f6cc1cb3b3c4856bc3f4d7162b1f9705a200b68a5dc173484f7a71c7ea0a') # Version 3.11.3 permissions don't allow downloading version('3.11.2', sha256='fd9518cc9fd8c8f6cdd681484c6eb42114aebf2a6ba4c8e1f12b34a148dfdefb') version('3.11.1', sha256='14317938e55cb7dc3eca21d9b7667a256a08661c6da988334f7af566a015b327') version('3.10.0', sha256='8d6958867f7165396459f4556e439065bc2cd2464bcfe16195a2a68345d56ea7') version('3.9.1', sha256='ce0aa9bcb3accbd39c09dd32cbc9884dc00e7a8d53782ba46b8fe7d7d60fc03f') version('3.8.0', sha256='0fc811ca83bd72d238f0efb172d466e80e5091db0b78ad00ab6b93331a1fe489') version('3.7.3', sha256='19eada4f351a821abccac0779fde85e2ad18b931b6a8110510a4c21707c2f5ce') version('3.7.2', sha256='c20c5b12576b73a1a095d8ef54536c4424517adaf472d55d48e57455eda74f2d') version('3.6.3-beta', sha256='7d9202355a66b8850333484862627f73ea3d7620ca84cde757dee629ebcb61bb') version('3.5.2-beta', sha256='9a591fc962edd56ea073abd13d03027bd530f1e61df595fae42dd9a7f8b9cc3a') version('3.5.0-beta', sha256='3e10c55d7b652b6feca902ce782751d4b16c8ad9d4dd8b9e2e9ec74dd64f30da') version('3.4.1-beta', sha256='5aadc813b75b65485f221372e174a2691e184e380f569129e7aa4484ca4047f8') version('3.3.3-beta', sha256='c07b5dc8d56a8f310239d1ec6be31182a6463fea787a0e10b54a3df479979cac') version('3.3.2-beta', sha256='430ea1a77083c8990a3c996572ed15663d9b31c0f8b614537bd7065abd6f375f') version('2.4.4', sha256='33242e38e6f4d35bd52f4194bd99a014485b0f3458b268902f69f6c02b35ee5c') # Debug mode reduces optimization, includes assertions, debug symbols # and more print statements variant('debug', default=False, description='Compile with reduced optimization and debugging on') variant('silo', default=False, description='Compile with support for silo') depends_on('mpi') depends_on('zlib') depends_on('hdf5+mpi') depends_on('m4', type='build') depends_on('boost@:1.64.0', when='@3.0.0:3.11', type='build') depends_on('silo+mpi', when='+silo') # don't build SAMRAI 3+ with tools with gcc patch('no-tool-build.patch', when='@3.0.0:%gcc') # 2.4.4 needs a lot of patches to fix ADL and performance problems patch('https://github.com/IBAMR/IBAMR/releases/download/v0.3.0/ibamr-samrai-fixes.patch', sha256='1d088b6cca41377747fa0ae8970440c20cb68988bbc34f9032d5a4e6aceede47', when='@2.4.4') def configure_args(self): options = [] options.extend([ '--with-CXX=%s' % self.spec['mpi'].mpicxx, '--with-CC=%s' % self.spec['mpi'].mpicc, '--with-F77=%s' % self.spec['mpi'].mpifc, '--with-M4=%s' % self.spec['m4'].prefix, '--with-hdf5=%s' % self.spec['hdf5'].prefix, '--with-zlib=%s' % self.spec['zlib'].prefix, '--without-blas', '--without-lapack', '--with-hypre=no', '--with-petsc=no']) # SAMRAI 2 used templates; enable implicit instantiation if self.spec.satisfies('@:3'): options.append('--enable-implicit-template-instantiation') if '+debug' in self.spec: options.extend([ '--disable-opt', '--enable-debug']) else: options.extend([ '--enable-opt', '--disable-debug']) if '+silo' in self.spec: options.append('--with-silo=%s' % self.spec['silo'].prefix) if self.spec.satisfies('@3.0:3.11'):
return options def setup_dependent_build_environment(self, env, dependent_spec): if self.spec.satisfies('@3.12:'): env.append_flags('CXXFLAGS', self.compiler.cxx11_flag)
options.append('--with-boost=%s' % self.spec['boost'].prefix)
conditional_block
test.ts
/* * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * 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. */ /// <reference types="@stdlib/types"/> import { ndarray } from '@stdlib/types/ndarray'; import sdot = require( './index' ); /** * Returns an ndarray object. * * @returns ndarray object */ function
(): ndarray { const arr: ndarray = { 'byteLength': null, 'BYTES_PER_ELEMENT': null, 'data': new Float64Array( [ 1, 2, 3 ] ), 'dtype': 'float64', 'flags': { 'ROW_MAJOR_CONTIGUOUS': true, 'COLUMN_MAJOR_CONTIGUOUS': false }, 'length': 3, 'ndims': 1, 'offset': 0, 'order': 'row-major', 'shape': [ 3 ], 'strides': [ 1 ], 'get': ( i: number ): any => { return arr.data[ i ]; }, 'set': ( i: number, v: any ): ndarray => { arr.data[ i ] = v; return arr; } }; return arr; } // TESTS // // The function returns a number... { sdot( createArray(), createArray() ); // $ExpectType number } // The compiler throws an error if the function is provided a first argument which is not an ndarray... { const y: ndarray = createArray(); sdot( 10, y ); // $ExpectError sdot( '10', y ); // $ExpectError sdot( true, y ); // $ExpectError sdot( false, y ); // $ExpectError sdot( null, y ); // $ExpectError sdot( undefined, y ); // $ExpectError sdot( {}, y ); // $ExpectError sdot( [], y ); // $ExpectError sdot( ( x: number ): number => x, y ); // $ExpectError } // The compiler throws an error if the function is provided a second argument which is not an ndarray... { const x: ndarray = createArray(); sdot( x, 10 ); // $ExpectError sdot( x, '10' ); // $ExpectError sdot( x, true ); // $ExpectError sdot( x, false ); // $ExpectError sdot( x, null ); // $ExpectError sdot( x, undefined ); // $ExpectError sdot( x, {} ); // $ExpectError sdot( x, [] ); // $ExpectError sdot( x, ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the function is provided an unsupported number of arguments... { const x: ndarray = createArray(); const y: ndarray = createArray(); sdot(); // $ExpectError sdot( x ); // $ExpectError sdot( x, y, {} ); // $ExpectError }
createArray
identifier_name
test.ts
/* * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * 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. */ /// <reference types="@stdlib/types"/> import { ndarray } from '@stdlib/types/ndarray'; import sdot = require( './index' ); /** * Returns an ndarray object. * * @returns ndarray object */ function createArray(): ndarray { const arr: ndarray = { 'byteLength': null, 'BYTES_PER_ELEMENT': null, 'data': new Float64Array( [ 1, 2, 3 ] ), 'dtype': 'float64', 'flags': { 'ROW_MAJOR_CONTIGUOUS': true, 'COLUMN_MAJOR_CONTIGUOUS': false }, 'length': 3, 'ndims': 1, 'offset': 0, 'order': 'row-major', 'shape': [ 3 ], 'strides': [ 1 ], 'get': ( i: number ): any => { return arr.data[ i ]; }, 'set': ( i: number, v: any ): ndarray => { arr.data[ i ] = v; return arr; } }; return arr; } // TESTS // // The function returns a number... { sdot( createArray(), createArray() ); // $ExpectType number } // The compiler throws an error if the function is provided a first argument which is not an ndarray... { const y: ndarray = createArray(); sdot( 10, y ); // $ExpectError sdot( '10', y ); // $ExpectError sdot( true, y ); // $ExpectError sdot( false, y ); // $ExpectError
sdot( [], y ); // $ExpectError sdot( ( x: number ): number => x, y ); // $ExpectError } // The compiler throws an error if the function is provided a second argument which is not an ndarray... { const x: ndarray = createArray(); sdot( x, 10 ); // $ExpectError sdot( x, '10' ); // $ExpectError sdot( x, true ); // $ExpectError sdot( x, false ); // $ExpectError sdot( x, null ); // $ExpectError sdot( x, undefined ); // $ExpectError sdot( x, {} ); // $ExpectError sdot( x, [] ); // $ExpectError sdot( x, ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the function is provided an unsupported number of arguments... { const x: ndarray = createArray(); const y: ndarray = createArray(); sdot(); // $ExpectError sdot( x ); // $ExpectError sdot( x, y, {} ); // $ExpectError }
sdot( null, y ); // $ExpectError sdot( undefined, y ); // $ExpectError sdot( {}, y ); // $ExpectError
random_line_split
test.ts
/* * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * 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. */ /// <reference types="@stdlib/types"/> import { ndarray } from '@stdlib/types/ndarray'; import sdot = require( './index' ); /** * Returns an ndarray object. * * @returns ndarray object */ function createArray(): ndarray
// TESTS // // The function returns a number... { sdot( createArray(), createArray() ); // $ExpectType number } // The compiler throws an error if the function is provided a first argument which is not an ndarray... { const y: ndarray = createArray(); sdot( 10, y ); // $ExpectError sdot( '10', y ); // $ExpectError sdot( true, y ); // $ExpectError sdot( false, y ); // $ExpectError sdot( null, y ); // $ExpectError sdot( undefined, y ); // $ExpectError sdot( {}, y ); // $ExpectError sdot( [], y ); // $ExpectError sdot( ( x: number ): number => x, y ); // $ExpectError } // The compiler throws an error if the function is provided a second argument which is not an ndarray... { const x: ndarray = createArray(); sdot( x, 10 ); // $ExpectError sdot( x, '10' ); // $ExpectError sdot( x, true ); // $ExpectError sdot( x, false ); // $ExpectError sdot( x, null ); // $ExpectError sdot( x, undefined ); // $ExpectError sdot( x, {} ); // $ExpectError sdot( x, [] ); // $ExpectError sdot( x, ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the function is provided an unsupported number of arguments... { const x: ndarray = createArray(); const y: ndarray = createArray(); sdot(); // $ExpectError sdot( x ); // $ExpectError sdot( x, y, {} ); // $ExpectError }
{ const arr: ndarray = { 'byteLength': null, 'BYTES_PER_ELEMENT': null, 'data': new Float64Array( [ 1, 2, 3 ] ), 'dtype': 'float64', 'flags': { 'ROW_MAJOR_CONTIGUOUS': true, 'COLUMN_MAJOR_CONTIGUOUS': false }, 'length': 3, 'ndims': 1, 'offset': 0, 'order': 'row-major', 'shape': [ 3 ], 'strides': [ 1 ], 'get': ( i: number ): any => { return arr.data[ i ]; }, 'set': ( i: number, v: any ): ndarray => { arr.data[ i ] = v; return arr; } }; return arr; }
identifier_body
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class
(CMakePackage): """SIMD Library for Evaluating Elementary Functions, vectorized libm and DFT.""" homepage = "http://sleef.org" url = "https://github.com/shibatch/sleef/archive/3.2.tar.gz" version('3.2', '459215058f2c8d55cd2b644d56c8c4f0')
Sleef
identifier_name
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. #
# # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Sleef(CMakePackage): """SIMD Library for Evaluating Elementary Functions, vectorized libm and DFT.""" homepage = "http://sleef.org" url = "https://github.com/shibatch/sleef/archive/3.2.tar.gz" version('3.2', '459215058f2c8d55cd2b644d56c8c4f0')
# 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 terms and # conditions of the GNU Lesser General Public License for more details.
random_line_split
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Sleef(CMakePackage):
"""SIMD Library for Evaluating Elementary Functions, vectorized libm and DFT.""" homepage = "http://sleef.org" url = "https://github.com/shibatch/sleef/archive/3.2.tar.gz" version('3.2', '459215058f2c8d55cd2b644d56c8c4f0')
identifier_body
into_iterator.rs
#![allow(dead_code, unused_imports)] #[macro_use] extern crate derive_more; #[derive(IntoIterator)] #[into_iterator(owned, ref, ref_mut)] struct MyVec(Vec<i32>); #[derive(IntoIterator)] #[into_iterator(owned, ref, ref_mut)] struct Numbers { numbers: Vec<i32>, } #[derive(IntoIterator)] struct
{ #[into_iterator(owned, ref, ref_mut)] numbers: Vec<i32>, useless: bool, useless2: bool, } #[derive(IntoIterator)] struct Numbers3 { #[into_iterator(ref, ref_mut)] numbers: Vec<i32>, useless: bool, useless2: bool, } // Test that owned is not enabled when ref/ref_mut are enabled without owned impl ::core::iter::IntoIterator for Numbers3 { type Item = <Vec<i32> as ::core::iter::IntoIterator>::Item; type IntoIter = <Vec<i32> as ::core::iter::IntoIterator>::IntoIter; #[inline] fn into_iter(self) -> Self::IntoIter { <Vec<i32> as ::core::iter::IntoIterator>::into_iter(self.numbers) } }
Numbers2
identifier_name
into_iterator.rs
#![allow(dead_code, unused_imports)]
#[derive(IntoIterator)] #[into_iterator(owned, ref, ref_mut)] struct MyVec(Vec<i32>); #[derive(IntoIterator)] #[into_iterator(owned, ref, ref_mut)] struct Numbers { numbers: Vec<i32>, } #[derive(IntoIterator)] struct Numbers2 { #[into_iterator(owned, ref, ref_mut)] numbers: Vec<i32>, useless: bool, useless2: bool, } #[derive(IntoIterator)] struct Numbers3 { #[into_iterator(ref, ref_mut)] numbers: Vec<i32>, useless: bool, useless2: bool, } // Test that owned is not enabled when ref/ref_mut are enabled without owned impl ::core::iter::IntoIterator for Numbers3 { type Item = <Vec<i32> as ::core::iter::IntoIterator>::Item; type IntoIter = <Vec<i32> as ::core::iter::IntoIterator>::IntoIter; #[inline] fn into_iter(self) -> Self::IntoIter { <Vec<i32> as ::core::iter::IntoIterator>::into_iter(self.numbers) } }
#[macro_use] extern crate derive_more;
random_line_split
common.js
/* * Copyright © Enable Software Pty Ltd 2013 - All rights reserved */ var common = {}; common.unique = function (array) { var results = []; var dict = {}; for (var i in array) { dict[array[i]] = true; } for (var y in dict) { results.push(y); } return results; }; common.map = function (list, functor) { var l = []; if (list.each !== undefined) { list.each(function () { l.push(functor($(this))); }); } else if (list.forEach !== undefined) { list.forEach(function (e) { l.push(functor(e)); }); } else { for (var k in list) { l.push(functor(k, list[k])); } } return l; }; common.reduce = function (array, functor) { var results = []; for (var a in array) { if (functor(array[a])) { results.push(array[a]); } } return results; }; $.fn.datalist = function (data) { return common.map(this, function (x) { return x.data(data); }); }; $.fn.attrlist = function (attr) { return rms.map(this, function (x) { return x.attr(attr); }); }; String.prototype.replaceAll = function (find, replace) { var str = this; return str.replace(new RegExp(find, 'g'), replace); }; common.toString = function (buf) { var deferred = $.Deferred(); var b = new Blob([buf]); var f = new FileReader(); f.onload = function(e) { deferred.resolve(e.target.result); } f.onerror = function(e) { deferred.reject(e); } f.readAsText(b); return deferred.promise(); }; common.multiDeferred = function(items, functor) { var main = $.Deferred(); var deferredList = []; for (var x in items) { var deferred = $.Deferred(); deferred.done(function() { if (common.reduce(deferredList, function(f) { return f.state() != "resolved"}).length === 0) { main.resolve(); } }); deferredList.push(deferred); } for (var x in items) { (function (x) { functor(items[x]).done(function() { deferredList[x].resolve()}); })(x); } return main.promise(); } function CreateArray(length) { var arr = new Array(length || 0), i = length; if (arguments.length > 1) { var args = Array.prototype.slice.call(arguments, 1); while (i--) arr[length - 1 - i] = CreateArray.apply(this, args); } return arr; } function FromHex(hex) { return parseInt(hex, 16); } function ToHex(num) { return num.toString(16); } function FullHex(num) { return "0x" + ("00000000" + ToHex(num)).substr(-8) } function SetBit(mask, bit) { return mask |= (1 << bit); } function ClearBit(mask, bit) { return mask &= ~(1 << bit); } function BitSet(mask, bit) { return (mask & (1 << bit)) ? 1 : 0; } /*function copy(buffer) { var bytes = new Uint8Array(buffer); var output = new ArrayBuffer(buffer.byteLength); var outputBytes = new Uint8Array(output); for (var i = 0; i < bytes.length; i++) outputBytes[i] = bytes[i]; return output; }*/ function clone(obj) { // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { var copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) {
// Handle Object if (obj instanceof Object) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); }
var copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = clone(obj[i]); } return copy; }
conditional_block
common.js
/* * Copyright © Enable Software Pty Ltd 2013 - All rights reserved */ var common = {}; common.unique = function (array) { var results = []; var dict = {}; for (var i in array) { dict[array[i]] = true; } for (var y in dict) { results.push(y); } return results; }; common.map = function (list, functor) { var l = []; if (list.each !== undefined) { list.each(function () { l.push(functor($(this))); }); } else if (list.forEach !== undefined) { list.forEach(function (e) { l.push(functor(e)); }); } else { for (var k in list) { l.push(functor(k, list[k])); } } return l; }; common.reduce = function (array, functor) { var results = []; for (var a in array) { if (functor(array[a])) { results.push(array[a]); } } return results; }; $.fn.datalist = function (data) { return common.map(this, function (x) { return x.data(data); }); }; $.fn.attrlist = function (attr) { return rms.map(this, function (x) { return x.attr(attr); }); }; String.prototype.replaceAll = function (find, replace) { var str = this; return str.replace(new RegExp(find, 'g'), replace); }; common.toString = function (buf) { var deferred = $.Deferred(); var b = new Blob([buf]); var f = new FileReader(); f.onload = function(e) { deferred.resolve(e.target.result); } f.onerror = function(e) { deferred.reject(e); } f.readAsText(b); return deferred.promise(); }; common.multiDeferred = function(items, functor) { var main = $.Deferred(); var deferredList = []; for (var x in items) { var deferred = $.Deferred(); deferred.done(function() { if (common.reduce(deferredList, function(f) { return f.state() != "resolved"}).length === 0) { main.resolve(); } }); deferredList.push(deferred); } for (var x in items) { (function (x) { functor(items[x]).done(function() { deferredList[x].resolve()}); })(x); } return main.promise(); } function CreateArray(length) { var arr = new Array(length || 0), i = length; if (arguments.length > 1) { var args = Array.prototype.slice.call(arguments, 1); while (i--) arr[length - 1 - i] = CreateArray.apply(this, args); } return arr; } function FromHex(hex) { return parseInt(hex, 16); } function ToHex(num) { return num.toString(16); } function FullHex(num) { return "0x" + ("00000000" + ToHex(num)).substr(-8) } function SetBit(mask, bit) { return mask |= (1 << bit); } function ClearBit(mask, bit) { return mask &= ~(1 << bit); } function BitSet(mask, bit) { return (mask & (1 << bit)) ? 1 : 0; } /*function copy(buffer) { var bytes = new Uint8Array(buffer); var output = new ArrayBuffer(buffer.byteLength); var outputBytes = new Uint8Array(output); for (var i = 0; i < bytes.length; i++) outputBytes[i] = bytes[i]; return output; }*/ function clone(obj) { // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { var copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { var copy = []; for (var i = 0, len = obj.length; i < len; i++) {
} // Handle Object if (obj instanceof Object) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); }
copy[i] = clone(obj[i]); } return copy;
random_line_split
common.js
/* * Copyright © Enable Software Pty Ltd 2013 - All rights reserved */ var common = {}; common.unique = function (array) { var results = []; var dict = {}; for (var i in array) { dict[array[i]] = true; } for (var y in dict) { results.push(y); } return results; }; common.map = function (list, functor) { var l = []; if (list.each !== undefined) { list.each(function () { l.push(functor($(this))); }); } else if (list.forEach !== undefined) { list.forEach(function (e) { l.push(functor(e)); }); } else { for (var k in list) { l.push(functor(k, list[k])); } } return l; }; common.reduce = function (array, functor) { var results = []; for (var a in array) { if (functor(array[a])) { results.push(array[a]); } } return results; }; $.fn.datalist = function (data) { return common.map(this, function (x) { return x.data(data); }); }; $.fn.attrlist = function (attr) { return rms.map(this, function (x) { return x.attr(attr); }); }; String.prototype.replaceAll = function (find, replace) { var str = this; return str.replace(new RegExp(find, 'g'), replace); }; common.toString = function (buf) { var deferred = $.Deferred(); var b = new Blob([buf]); var f = new FileReader(); f.onload = function(e) { deferred.resolve(e.target.result); } f.onerror = function(e) { deferred.reject(e); } f.readAsText(b); return deferred.promise(); }; common.multiDeferred = function(items, functor) { var main = $.Deferred(); var deferredList = []; for (var x in items) { var deferred = $.Deferred(); deferred.done(function() { if (common.reduce(deferredList, function(f) { return f.state() != "resolved"}).length === 0) { main.resolve(); } }); deferredList.push(deferred); } for (var x in items) { (function (x) { functor(items[x]).done(function() { deferredList[x].resolve()}); })(x); } return main.promise(); } function CreateArray(length) { var arr = new Array(length || 0), i = length; if (arguments.length > 1) { var args = Array.prototype.slice.call(arguments, 1); while (i--) arr[length - 1 - i] = CreateArray.apply(this, args); } return arr; } function FromHex(hex) { return parseInt(hex, 16); } function ToHex(num) { return num.toString(16); } function FullHex(num) { return "0x" + ("00000000" + ToHex(num)).substr(-8) } function SetBit(mask, bit) { return mask |= (1 << bit); } function C
mask, bit) { return mask &= ~(1 << bit); } function BitSet(mask, bit) { return (mask & (1 << bit)) ? 1 : 0; } /*function copy(buffer) { var bytes = new Uint8Array(buffer); var output = new ArrayBuffer(buffer.byteLength); var outputBytes = new Uint8Array(output); for (var i = 0; i < bytes.length; i++) outputBytes[i] = bytes[i]; return output; }*/ function clone(obj) { // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { var copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { var copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = clone(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); }
learBit(
identifier_name
common.js
/* * Copyright © Enable Software Pty Ltd 2013 - All rights reserved */ var common = {}; common.unique = function (array) { var results = []; var dict = {}; for (var i in array) { dict[array[i]] = true; } for (var y in dict) { results.push(y); } return results; }; common.map = function (list, functor) { var l = []; if (list.each !== undefined) { list.each(function () { l.push(functor($(this))); }); } else if (list.forEach !== undefined) { list.forEach(function (e) { l.push(functor(e)); }); } else { for (var k in list) { l.push(functor(k, list[k])); } } return l; }; common.reduce = function (array, functor) { var results = []; for (var a in array) { if (functor(array[a])) { results.push(array[a]); } } return results; }; $.fn.datalist = function (data) { return common.map(this, function (x) { return x.data(data); }); }; $.fn.attrlist = function (attr) { return rms.map(this, function (x) { return x.attr(attr); }); }; String.prototype.replaceAll = function (find, replace) { var str = this; return str.replace(new RegExp(find, 'g'), replace); }; common.toString = function (buf) { var deferred = $.Deferred(); var b = new Blob([buf]); var f = new FileReader(); f.onload = function(e) { deferred.resolve(e.target.result); } f.onerror = function(e) { deferred.reject(e); } f.readAsText(b); return deferred.promise(); }; common.multiDeferred = function(items, functor) { var main = $.Deferred(); var deferredList = []; for (var x in items) { var deferred = $.Deferred(); deferred.done(function() { if (common.reduce(deferredList, function(f) { return f.state() != "resolved"}).length === 0) { main.resolve(); } }); deferredList.push(deferred); } for (var x in items) { (function (x) { functor(items[x]).done(function() { deferredList[x].resolve()}); })(x); } return main.promise(); } function CreateArray(length) { var arr = new Array(length || 0), i = length; if (arguments.length > 1) { var args = Array.prototype.slice.call(arguments, 1); while (i--) arr[length - 1 - i] = CreateArray.apply(this, args); } return arr; } function FromHex(hex) { return parseInt(hex, 16); } function ToHex(num) { return num.toString(16); } function FullHex(num) { return "0x" + ("00000000" + ToHex(num)).substr(-8) } function SetBit(mask, bit) { return mask |= (1 << bit); } function ClearBit(mask, bit) { return mask &= ~(1 << bit); } function BitSet(mask, bit) {
/*function copy(buffer) { var bytes = new Uint8Array(buffer); var output = new ArrayBuffer(buffer.byteLength); var outputBytes = new Uint8Array(output); for (var i = 0; i < bytes.length; i++) outputBytes[i] = bytes[i]; return output; }*/ function clone(obj) { // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { var copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { var copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = clone(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); }
return (mask & (1 << bit)) ? 1 : 0; }
identifier_body
WolframAlphaLookup.py
import sublime, sublime_plugin, requests from xml.etree import ElementTree as ET class WolframAlphaLookupCommand(sublime_plugin.WindowCommand): def run(self): settings = sublime.load_settings("Preferences.sublime-settings") if settings.has("wolfram_api_key"): API_KEY = settings.get("wolfram_api_key") for region in self.window.active_view().sel(): if not region.empty(): query = self.window.active_view().substr(region) else: query = self.window.active_view().substr(self.window.active_view().line(region)) query = query.strip() r = requests.get("http://api.wolframalpha.com/v2/query", params={ "input": query, "appid": API_KEY }) root = ET.fromstring(r.text) if root.get('success') == 'true': items = list() for pod in root.iter('pod'): title = pod.attrib.get('title') plaintext = pod.find('./subpod/plaintext').text if title and plaintext: items.append([title, plaintext]) def on_select(index): if index > -1: print(items[index]) print(region) self.window.active_view().run_command("insert_result", {"data": items[index][1]}) self.window.show_quick_panel(items, on_select) else: sublime.error_message("Wolfram|Alpha could not understand your query!") break else: sublime.error_message("Please add a \"wolfram_api_key\" to the settings!") class InsertResultCommand(sublime_plugin.TextCommand): def
(self, edit, data): for region in self.view.sel(): if region.empty(): line = self.view.line(region) self.view.insert(edit, line.end(), '\n' + (data[:-1] if data[-1] == '\n' else data)) else: self.view.insert(edit, region.end(), data) break
run
identifier_name
WolframAlphaLookup.py
import sublime, sublime_plugin, requests from xml.etree import ElementTree as ET class WolframAlphaLookupCommand(sublime_plugin.WindowCommand): def run(self): settings = sublime.load_settings("Preferences.sublime-settings") if settings.has("wolfram_api_key"): API_KEY = settings.get("wolfram_api_key") for region in self.window.active_view().sel(): if not region.empty(): query = self.window.active_view().substr(region) else: query = self.window.active_view().substr(self.window.active_view().line(region)) query = query.strip() r = requests.get("http://api.wolframalpha.com/v2/query", params={ "input": query, "appid": API_KEY }) root = ET.fromstring(r.text) if root.get('success') == 'true': items = list() for pod in root.iter('pod'): title = pod.attrib.get('title') plaintext = pod.find('./subpod/plaintext').text if title and plaintext: items.append([title, plaintext]) def on_select(index): if index > -1: print(items[index]) print(region) self.window.active_view().run_command("insert_result", {"data": items[index][1]}) self.window.show_quick_panel(items, on_select) else:
break else: sublime.error_message("Please add a \"wolfram_api_key\" to the settings!") class InsertResultCommand(sublime_plugin.TextCommand): def run(self, edit, data): for region in self.view.sel(): if region.empty(): line = self.view.line(region) self.view.insert(edit, line.end(), '\n' + (data[:-1] if data[-1] == '\n' else data)) else: self.view.insert(edit, region.end(), data) break
sublime.error_message("Wolfram|Alpha could not understand your query!")
conditional_block
WolframAlphaLookup.py
import sublime, sublime_plugin, requests from xml.etree import ElementTree as ET class WolframAlphaLookupCommand(sublime_plugin.WindowCommand): def run(self): settings = sublime.load_settings("Preferences.sublime-settings") if settings.has("wolfram_api_key"): API_KEY = settings.get("wolfram_api_key") for region in self.window.active_view().sel(): if not region.empty(): query = self.window.active_view().substr(region) else: query = self.window.active_view().substr(self.window.active_view().line(region)) query = query.strip() r = requests.get("http://api.wolframalpha.com/v2/query", params={ "input": query, "appid": API_KEY }) root = ET.fromstring(r.text) if root.get('success') == 'true': items = list() for pod in root.iter('pod'): title = pod.attrib.get('title') plaintext = pod.find('./subpod/plaintext').text if title and plaintext: items.append([title, plaintext]) def on_select(index):
self.window.show_quick_panel(items, on_select) else: sublime.error_message("Wolfram|Alpha could not understand your query!") break else: sublime.error_message("Please add a \"wolfram_api_key\" to the settings!") class InsertResultCommand(sublime_plugin.TextCommand): def run(self, edit, data): for region in self.view.sel(): if region.empty(): line = self.view.line(region) self.view.insert(edit, line.end(), '\n' + (data[:-1] if data[-1] == '\n' else data)) else: self.view.insert(edit, region.end(), data) break
if index > -1: print(items[index]) print(region) self.window.active_view().run_command("insert_result", {"data": items[index][1]})
identifier_body
WolframAlphaLookup.py
import sublime, sublime_plugin, requests from xml.etree import ElementTree as ET class WolframAlphaLookupCommand(sublime_plugin.WindowCommand): def run(self): settings = sublime.load_settings("Preferences.sublime-settings") if settings.has("wolfram_api_key"): API_KEY = settings.get("wolfram_api_key")
else: query = self.window.active_view().substr(self.window.active_view().line(region)) query = query.strip() r = requests.get("http://api.wolframalpha.com/v2/query", params={ "input": query, "appid": API_KEY }) root = ET.fromstring(r.text) if root.get('success') == 'true': items = list() for pod in root.iter('pod'): title = pod.attrib.get('title') plaintext = pod.find('./subpod/plaintext').text if title and plaintext: items.append([title, plaintext]) def on_select(index): if index > -1: print(items[index]) print(region) self.window.active_view().run_command("insert_result", {"data": items[index][1]}) self.window.show_quick_panel(items, on_select) else: sublime.error_message("Wolfram|Alpha could not understand your query!") break else: sublime.error_message("Please add a \"wolfram_api_key\" to the settings!") class InsertResultCommand(sublime_plugin.TextCommand): def run(self, edit, data): for region in self.view.sel(): if region.empty(): line = self.view.line(region) self.view.insert(edit, line.end(), '\n' + (data[:-1] if data[-1] == '\n' else data)) else: self.view.insert(edit, region.end(), data) break
for region in self.window.active_view().sel(): if not region.empty(): query = self.window.active_view().substr(region)
random_line_split
util.py
from django.utils.encoding import smart_unicode def ssn_check_digit(value):
def vat_number_check_digit(vat_number): "Calculate Italian VAT number check digit." normalized_vat_number = smart_unicode(vat_number).zfill(10) total = 0 for i in range(0, 10, 2): total += int(normalized_vat_number[i]) for i in range(1, 11, 2): quotient , remainder = divmod(int(normalized_vat_number[i]) * 2, 10) total += quotient + remainder return smart_unicode((10 - total % 10) % 10)
"Calculate Italian social security number check digit." ssn_even_chars = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25 } ssn_odd_chars = { '0': 1, '1': 0, '2': 5, '3': 7, '4': 9, '5': 13, '6': 15, '7': 17, '8': 19, '9': 21, 'A': 1, 'B': 0, 'C': 5, 'D': 7, 'E': 9, 'F': 13, 'G': 15, 'H': 17, 'I': 19, 'J': 21, 'K': 2, 'L': 4, 'M': 18, 'N': 20, 'O': 11, 'P': 3, 'Q': 6, 'R': 8, 'S': 12, 'T': 14, 'U': 16, 'V': 10, 'W': 22, 'X': 25, 'Y': 24, 'Z': 23 } # Chars from 'A' to 'Z' ssn_check_digits = [chr(x) for x in range(65, 91)] ssn = value.upper() total = 0 for i in range(0, 15): try: if i % 2 == 0: total += ssn_odd_chars[ssn[i]] else: total += ssn_even_chars[ssn[i]] except KeyError: msg = "Character '%(char)s' is not allowed." % {'char': ssn[i]} raise ValueError(msg) return ssn_check_digits[total % 26]
identifier_body
util.py
from django.utils.encoding import smart_unicode def ssn_check_digit(value): "Calculate Italian social security number check digit." ssn_even_chars = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25 } ssn_odd_chars = { '0': 1, '1': 0, '2': 5, '3': 7, '4': 9, '5': 13, '6': 15, '7': 17, '8': 19, '9': 21, 'A': 1, 'B': 0, 'C': 5, 'D': 7, 'E': 9, 'F': 13, 'G': 15, 'H': 17, 'I': 19, 'J': 21, 'K': 2, 'L': 4, 'M': 18, 'N': 20, 'O': 11, 'P': 3, 'Q': 6, 'R': 8, 'S': 12, 'T': 14, 'U': 16, 'V': 10, 'W': 22, 'X': 25, 'Y': 24, 'Z': 23 } # Chars from 'A' to 'Z' ssn_check_digits = [chr(x) for x in range(65, 91)] ssn = value.upper() total = 0 for i in range(0, 15): try: if i % 2 == 0: total += ssn_odd_chars[ssn[i]] else: total += ssn_even_chars[ssn[i]] except KeyError: msg = "Character '%(char)s' is not allowed." % {'char': ssn[i]} raise ValueError(msg) return ssn_check_digits[total % 26] def vat_number_check_digit(vat_number): "Calculate Italian VAT number check digit." normalized_vat_number = smart_unicode(vat_number).zfill(10) total = 0 for i in range(0, 10, 2):
for i in range(1, 11, 2): quotient , remainder = divmod(int(normalized_vat_number[i]) * 2, 10) total += quotient + remainder return smart_unicode((10 - total % 10) % 10)
total += int(normalized_vat_number[i])
conditional_block
util.py
from django.utils.encoding import smart_unicode def ssn_check_digit(value): "Calculate Italian social security number check digit." ssn_even_chars = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25 } ssn_odd_chars = { '0': 1, '1': 0, '2': 5, '3': 7, '4': 9, '5': 13, '6': 15, '7': 17, '8': 19, '9': 21, 'A': 1, 'B': 0, 'C': 5, 'D': 7, 'E': 9, 'F': 13, 'G': 15, 'H': 17, 'I': 19, 'J': 21, 'K': 2, 'L': 4, 'M': 18, 'N': 20, 'O': 11, 'P': 3, 'Q': 6, 'R': 8, 'S': 12, 'T': 14, 'U': 16, 'V': 10, 'W': 22, 'X': 25, 'Y': 24, 'Z': 23 } # Chars from 'A' to 'Z' ssn_check_digits = [chr(x) for x in range(65, 91)] ssn = value.upper() total = 0 for i in range(0, 15): try: if i % 2 == 0: total += ssn_odd_chars[ssn[i]] else: total += ssn_even_chars[ssn[i]] except KeyError: msg = "Character '%(char)s' is not allowed." % {'char': ssn[i]} raise ValueError(msg) return ssn_check_digits[total % 26] def
(vat_number): "Calculate Italian VAT number check digit." normalized_vat_number = smart_unicode(vat_number).zfill(10) total = 0 for i in range(0, 10, 2): total += int(normalized_vat_number[i]) for i in range(1, 11, 2): quotient , remainder = divmod(int(normalized_vat_number[i]) * 2, 10) total += quotient + remainder return smart_unicode((10 - total % 10) % 10)
vat_number_check_digit
identifier_name
util.py
from django.utils.encoding import smart_unicode def ssn_check_digit(value): "Calculate Italian social security number check digit." ssn_even_chars = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25 } ssn_odd_chars = { '0': 1, '1': 0, '2': 5, '3': 7, '4': 9, '5': 13, '6': 15, '7': 17, '8': 19, '9': 21, 'A': 1, 'B': 0, 'C': 5, 'D': 7, 'E': 9, 'F': 13, 'G': 15, 'H': 17, 'I': 19, 'J': 21, 'K': 2, 'L': 4, 'M': 18, 'N': 20, 'O': 11, 'P': 3, 'Q': 6, 'R': 8, 'S': 12, 'T': 14, 'U': 16, 'V': 10, 'W': 22, 'X': 25, 'Y': 24, 'Z': 23 } # Chars from 'A' to 'Z' ssn_check_digits = [chr(x) for x in range(65, 91)] ssn = value.upper() total = 0 for i in range(0, 15): try: if i % 2 == 0: total += ssn_odd_chars[ssn[i]] else:
raise ValueError(msg) return ssn_check_digits[total % 26] def vat_number_check_digit(vat_number): "Calculate Italian VAT number check digit." normalized_vat_number = smart_unicode(vat_number).zfill(10) total = 0 for i in range(0, 10, 2): total += int(normalized_vat_number[i]) for i in range(1, 11, 2): quotient , remainder = divmod(int(normalized_vat_number[i]) * 2, 10) total += quotient + remainder return smart_unicode((10 - total % 10) % 10)
total += ssn_even_chars[ssn[i]] except KeyError: msg = "Character '%(char)s' is not allowed." % {'char': ssn[i]}
random_line_split
check_field_existence.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011, 2013 CERN. # # Invenio 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 2 of the # License, or (at your option) any later version. # # Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. def check_field_existence(record, field, min_value, max_value=None, subfield=None, continuable=True): """ Checks field.subfield existence inside the record according to max and min values @param record: BibFieldDict where the record is stored @param field: Main json ID or field name to make test on @param min_value: Minimum number of occurrences of field. If max_value is not present then min_value represents the fix number of times that field should be present. @param max_value: Maximum number of occurrences of a field, this might be a fix number or "n". @param subfield: If this parameter is present, instead of applying the checker to the field, it is applied to record['field.subfield'] @note: This checker also modify the record if the field is not repeatable, meaning that min_value=1 or min_value=0,max_value=1 """ from invenio.bibfield_utils import InvenioBibFieldContinuableError, \ InvenioBibFieldError error = continuable and InvenioBibFieldContinuableError or InvenioBibFieldError field = '[n]' in field and field[:-3] or field key = subfield and "%s.%s" % (field, subfield) or field if min_value == 0: # (0,1), (0,'n'), (0,n) if not max_value: raise error("Minimun value = 0 and no max value for '%s'" % (key,)) if key in record: value = record[key] if max_value == 1 and isinstance(value, list) and len(value) != 1: raise error("Field '%s' is not repeatable" % (key,)) elif max_value != 'n': if isinstance(value, list) and len(value) > max_value: raise error("Field '%s' is repeatable only %s times" % (key, max_value)) elif min_value == 1: # (1,-) (1,'n'), (1, n) if not key in record: raise error("Field '%s' is mandatory" % (key,)) value = record[key] if not value:
if isinstance(value, list) and len(value) != 1: raise error("Field '%s' is mandatory and not repeatable" % (key,)) elif max_value != 'n': if isinstance(value, list) and len(value) > max_value: raise error("Field '%s' is mandatory and repeatable only %s times" % (key, max_value)) else: if not key in record: raise error("Field '%s' must be present inside the record %s times" % (key, min_value)) value = record[key] if not value: raise error("Field '%s' must be present inside the record %s times" % (key, min_value)) if not max_value: if not isinstance(value, list) or len(value) != min_value: raise error("Field '%s' must be present inside the record %s times" % (key, min_value)) else: if max_value != 'n' and (not isinstance(value, list) or len(value) < min_value or len(value) > max_value): raise error("Field '%s' must be present inside the record between %s and %s times" % (key, min_value, max_value)) elif not isinstance(value, list) or len(value) < min_value: raise error("Field '%s' must be present inside the record between %s and 'n' times" % (key, min_value))
raise error("Field '%s' is mandatory" % (key,)) if not max_value:
random_line_split
check_field_existence.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011, 2013 CERN. # # Invenio 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 2 of the # License, or (at your option) any later version. # # Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. def check_field_existence(record, field, min_value, max_value=None, subfield=None, continuable=True):
""" Checks field.subfield existence inside the record according to max and min values @param record: BibFieldDict where the record is stored @param field: Main json ID or field name to make test on @param min_value: Minimum number of occurrences of field. If max_value is not present then min_value represents the fix number of times that field should be present. @param max_value: Maximum number of occurrences of a field, this might be a fix number or "n". @param subfield: If this parameter is present, instead of applying the checker to the field, it is applied to record['field.subfield'] @note: This checker also modify the record if the field is not repeatable, meaning that min_value=1 or min_value=0,max_value=1 """ from invenio.bibfield_utils import InvenioBibFieldContinuableError, \ InvenioBibFieldError error = continuable and InvenioBibFieldContinuableError or InvenioBibFieldError field = '[n]' in field and field[:-3] or field key = subfield and "%s.%s" % (field, subfield) or field if min_value == 0: # (0,1), (0,'n'), (0,n) if not max_value: raise error("Minimun value = 0 and no max value for '%s'" % (key,)) if key in record: value = record[key] if max_value == 1 and isinstance(value, list) and len(value) != 1: raise error("Field '%s' is not repeatable" % (key,)) elif max_value != 'n': if isinstance(value, list) and len(value) > max_value: raise error("Field '%s' is repeatable only %s times" % (key, max_value)) elif min_value == 1: # (1,-) (1,'n'), (1, n) if not key in record: raise error("Field '%s' is mandatory" % (key,)) value = record[key] if not value: raise error("Field '%s' is mandatory" % (key,)) if not max_value: if isinstance(value, list) and len(value) != 1: raise error("Field '%s' is mandatory and not repeatable" % (key,)) elif max_value != 'n': if isinstance(value, list) and len(value) > max_value: raise error("Field '%s' is mandatory and repeatable only %s times" % (key, max_value)) else: if not key in record: raise error("Field '%s' must be present inside the record %s times" % (key, min_value)) value = record[key] if not value: raise error("Field '%s' must be present inside the record %s times" % (key, min_value)) if not max_value: if not isinstance(value, list) or len(value) != min_value: raise error("Field '%s' must be present inside the record %s times" % (key, min_value)) else: if max_value != 'n' and (not isinstance(value, list) or len(value) < min_value or len(value) > max_value): raise error("Field '%s' must be present inside the record between %s and %s times" % (key, min_value, max_value)) elif not isinstance(value, list) or len(value) < min_value: raise error("Field '%s' must be present inside the record between %s and 'n' times" % (key, min_value))
identifier_body
check_field_existence.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011, 2013 CERN. # # Invenio 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 2 of the # License, or (at your option) any later version. # # Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. def check_field_existence(record, field, min_value, max_value=None, subfield=None, continuable=True): """ Checks field.subfield existence inside the record according to max and min values @param record: BibFieldDict where the record is stored @param field: Main json ID or field name to make test on @param min_value: Minimum number of occurrences of field. If max_value is not present then min_value represents the fix number of times that field should be present. @param max_value: Maximum number of occurrences of a field, this might be a fix number or "n". @param subfield: If this parameter is present, instead of applying the checker to the field, it is applied to record['field.subfield'] @note: This checker also modify the record if the field is not repeatable, meaning that min_value=1 or min_value=0,max_value=1 """ from invenio.bibfield_utils import InvenioBibFieldContinuableError, \ InvenioBibFieldError error = continuable and InvenioBibFieldContinuableError or InvenioBibFieldError field = '[n]' in field and field[:-3] or field key = subfield and "%s.%s" % (field, subfield) or field if min_value == 0: # (0,1), (0,'n'), (0,n) if not max_value: raise error("Minimun value = 0 and no max value for '%s'" % (key,)) if key in record: value = record[key] if max_value == 1 and isinstance(value, list) and len(value) != 1: raise error("Field '%s' is not repeatable" % (key,)) elif max_value != 'n': if isinstance(value, list) and len(value) > max_value: raise error("Field '%s' is repeatable only %s times" % (key, max_value)) elif min_value == 1: # (1,-) (1,'n'), (1, n) if not key in record: raise error("Field '%s' is mandatory" % (key,)) value = record[key] if not value: raise error("Field '%s' is mandatory" % (key,)) if not max_value: if isinstance(value, list) and len(value) != 1: raise error("Field '%s' is mandatory and not repeatable" % (key,)) elif max_value != 'n':
else: if not key in record: raise error("Field '%s' must be present inside the record %s times" % (key, min_value)) value = record[key] if not value: raise error("Field '%s' must be present inside the record %s times" % (key, min_value)) if not max_value: if not isinstance(value, list) or len(value) != min_value: raise error("Field '%s' must be present inside the record %s times" % (key, min_value)) else: if max_value != 'n' and (not isinstance(value, list) or len(value) < min_value or len(value) > max_value): raise error("Field '%s' must be present inside the record between %s and %s times" % (key, min_value, max_value)) elif not isinstance(value, list) or len(value) < min_value: raise error("Field '%s' must be present inside the record between %s and 'n' times" % (key, min_value))
if isinstance(value, list) and len(value) > max_value: raise error("Field '%s' is mandatory and repeatable only %s times" % (key, max_value))
conditional_block
check_field_existence.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011, 2013 CERN. # # Invenio 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 2 of the # License, or (at your option) any later version. # # Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. def
(record, field, min_value, max_value=None, subfield=None, continuable=True): """ Checks field.subfield existence inside the record according to max and min values @param record: BibFieldDict where the record is stored @param field: Main json ID or field name to make test on @param min_value: Minimum number of occurrences of field. If max_value is not present then min_value represents the fix number of times that field should be present. @param max_value: Maximum number of occurrences of a field, this might be a fix number or "n". @param subfield: If this parameter is present, instead of applying the checker to the field, it is applied to record['field.subfield'] @note: This checker also modify the record if the field is not repeatable, meaning that min_value=1 or min_value=0,max_value=1 """ from invenio.bibfield_utils import InvenioBibFieldContinuableError, \ InvenioBibFieldError error = continuable and InvenioBibFieldContinuableError or InvenioBibFieldError field = '[n]' in field and field[:-3] or field key = subfield and "%s.%s" % (field, subfield) or field if min_value == 0: # (0,1), (0,'n'), (0,n) if not max_value: raise error("Minimun value = 0 and no max value for '%s'" % (key,)) if key in record: value = record[key] if max_value == 1 and isinstance(value, list) and len(value) != 1: raise error("Field '%s' is not repeatable" % (key,)) elif max_value != 'n': if isinstance(value, list) and len(value) > max_value: raise error("Field '%s' is repeatable only %s times" % (key, max_value)) elif min_value == 1: # (1,-) (1,'n'), (1, n) if not key in record: raise error("Field '%s' is mandatory" % (key,)) value = record[key] if not value: raise error("Field '%s' is mandatory" % (key,)) if not max_value: if isinstance(value, list) and len(value) != 1: raise error("Field '%s' is mandatory and not repeatable" % (key,)) elif max_value != 'n': if isinstance(value, list) and len(value) > max_value: raise error("Field '%s' is mandatory and repeatable only %s times" % (key, max_value)) else: if not key in record: raise error("Field '%s' must be present inside the record %s times" % (key, min_value)) value = record[key] if not value: raise error("Field '%s' must be present inside the record %s times" % (key, min_value)) if not max_value: if not isinstance(value, list) or len(value) != min_value: raise error("Field '%s' must be present inside the record %s times" % (key, min_value)) else: if max_value != 'n' and (not isinstance(value, list) or len(value) < min_value or len(value) > max_value): raise error("Field '%s' must be present inside the record between %s and %s times" % (key, min_value, max_value)) elif not isinstance(value, list) or len(value) < min_value: raise error("Field '%s' must be present inside the record between %s and 'n' times" % (key, min_value))
check_field_existence
identifier_name
odin.js
module.exports.odin = { baseUrl: 'http://localhost:3000', kongHost: '0.0.0.0', kongAdmin: '0.0.0.0:8001', recaptchaSecret: '6LcBhAkUAAAAABqD6jm_Cd3uFALNoXRr6ZXqvyBG', uploadFolder: 'files', datasetZipFolder: 'datasets', logFolder: 'logs', logFile: 'sailsApp.log',
defaultEncoding: 'utf8', dataStorage: { host: 'localhost', port: '27017' }, logLevel: 'error' }; module.exports.email = { service: 'Gmail', auth: {user: 'examplemail@gmail.com', pass: 'onepass'}, alwaysSendTo: 'examplemail@gmail.com', testMode: false, templateDir: 'api/views' }; module.exports.connections = { postgres: { adapter: 'sails-postgresql', database: 'odin', host: 'localhost', user: 'postgres', password: 'postgres', port: 5432, pool: false, ssl: false } };
statisticsPath: 'stats', backupFolder: 'backups',
random_line_split
ch15-closures.rs
/*Named functions, like those we've seen so far, may not refer to local variables declared outside the function: they do not close over their environment (sometimes referred to as "capturing" variables in their environment). A closure does support accessing the enclosing scope */ let x = 3; // `fun` is an invalid definition fn fun () -> () { println!("{}", x) } // cannot capture from enclosing scope let closure = || -> () { println!("{}", x) }; // can capture from enclosing scope // `fun_arg` is an invalid definition fn fun_arg (arg: int) -> () { println!("{}", arg + x) } // cannot capture let closure_arg = |arg: int| -> () { println!("{}", arg + x) }; // can capture // ^ // Requires a type because the implementation needs to know which `+` to use. // In the future, the implementation may not need the help. fun(); // Still won't work closure(); // Prints: 3 fun_arg(7); // Still won't work closure_arg(7); // Prints: 10 /*Closures begin with the argument list between vertical bars and are followed by a single expression. Remember that a block, { <expr1>; <expr2>; ... }, is considered a single expression: it evaluates to the result of the last expression it contains if that expression is not followed by a semicolon, otherwise the block evaluates to (), the unit value. In general, return types and all argument types must be specified explicitly for function definitions.*/ fn fun (x: int) { println!("{}", x) } // this is same as saying `-> ()` fn square(x: int) -> uint { (x * x) as uint } // other return types are explicit // Error: mismatched types: expected `()` but found `uint` fn badfun(x: int) { (x * x) as uint } /*On the other hand, the compiler can usually infer both the argument and return types for a closure expression; therefore they are often omitted, since both a human reader and the compiler can deduce the types from the immediate context. This is in contrast to function declarations, which require types to be specified and are not subject to type inference.*/ // `fun` as a function declaration cannot infer the type of `x`, so it must be provided fn fun (x: int) { println!("{}", x) } let closure = |x | { println!("{}", x) }; // infers `x: int`, return type `()` // For closures, omitting a return type is *not* synonymous with `-> ()` let add_3 = |y | { 3i + y }; // infers `y: int`, return type `int`. fun(10); // Prints 10 closure(20); // Prints 20 closure(add_3(30)); // Prints 33 fun("String"); // Error: mismatched types // Error: mismatched types // inference already assigned `closure` the type `|int| -> ()` closure("String"); /*In cases where the compiler needs assistance, the arguments and return types may be annotated on closures, using the same notation as shown earlier. In the example below, since different types provide an implementation for the operator *, the argument type for the x parameter must be explicitly provided.*/ // Error: the type of `x` must be known to be used with `x * x` let square = |x | -> uint { (x * x) as uint }; let square_explicit = |x: int| -> uint { (x * x) as uint }; let square_infer = |x: int| { (x * x) as uint }; println!("{}", square_explicit(20)); // 400
has type || and can directly access local variables in the enclosing scope.*/ let mut max = 0; let f = |x: int| if x > max { max = x }; for x in [1, 2, 3].iter() { f(*x); } /*Stack closures are very efficient because their environment is allocated on the call stack and refers by pointer to captured locals. To ensure that stack closures never outlive the local variables to which they refer, stack closures are not first-class. That is, they can only be used in argument position; they cannot be stored in data structures or returned from functions. Despite these limitations, stack closures are used pervasively in Rust code.*/ // -- Owned closures /*Owned closures, written proc, hold on to things that can safely be sent between processes. They copy the values they close over, but they also own them: that is, no other code can access them. Owned closures are used in concurrent code, particularly for spawning tasks. Closures can be used to spawn tasks. A practical example of this pattern is found when using the spawn function, which starts a new task.*/ use std::task::spawn; // proc is the closure which will be spawned. spawn(proc() { println!("I'm a new task") }); // -- Closure compatibility /*Rust closures have a convenient subtyping property: you can pass any kind of closure (as long as the arguments and return types match) to functions that expect a ||. Thus, when writing a higher-order function that only calls its function argument, and does nothing else with it, you should almost always declare the type of that argument as ||. That way, callers may pass any kind of closure.*/ fn call_twice(f: ||) { f(); f(); } let closure = || { "I'm a closure, and it doesn't matter what type I am"; }; fn function() { "I'm a normal function"; } call_twice(closure); call_twice(function);
println!("{}", square_infer(-20)); // 400 /*There are several forms of closure, each with its own role. The most common, called a stack closure,
random_line_split
ch15-closures.rs
/*Named functions, like those we've seen so far, may not refer to local variables declared outside the function: they do not close over their environment (sometimes referred to as "capturing" variables in their environment). A closure does support accessing the enclosing scope */ let x = 3; // `fun` is an invalid definition fn fun () -> () { println!("{}", x) } // cannot capture from enclosing scope let closure = || -> () { println!("{}", x) }; // can capture from enclosing scope // `fun_arg` is an invalid definition fn fun_arg (arg: int) -> () { println!("{}", arg + x) } // cannot capture let closure_arg = |arg: int| -> () { println!("{}", arg + x) }; // can capture // ^ // Requires a type because the implementation needs to know which `+` to use. // In the future, the implementation may not need the help. fun(); // Still won't work closure(); // Prints: 3 fun_arg(7); // Still won't work closure_arg(7); // Prints: 10 /*Closures begin with the argument list between vertical bars and are followed by a single expression. Remember that a block, { <expr1>; <expr2>; ... }, is considered a single expression: it evaluates to the result of the last expression it contains if that expression is not followed by a semicolon, otherwise the block evaluates to (), the unit value. In general, return types and all argument types must be specified explicitly for function definitions.*/ fn
(x: int) { println!("{}", x) } // this is same as saying `-> ()` fn square(x: int) -> uint { (x * x) as uint } // other return types are explicit // Error: mismatched types: expected `()` but found `uint` fn badfun(x: int) { (x * x) as uint } /*On the other hand, the compiler can usually infer both the argument and return types for a closure expression; therefore they are often omitted, since both a human reader and the compiler can deduce the types from the immediate context. This is in contrast to function declarations, which require types to be specified and are not subject to type inference.*/ // `fun` as a function declaration cannot infer the type of `x`, so it must be provided fn fun (x: int) { println!("{}", x) } let closure = |x | { println!("{}", x) }; // infers `x: int`, return type `()` // For closures, omitting a return type is *not* synonymous with `-> ()` let add_3 = |y | { 3i + y }; // infers `y: int`, return type `int`. fun(10); // Prints 10 closure(20); // Prints 20 closure(add_3(30)); // Prints 33 fun("String"); // Error: mismatched types // Error: mismatched types // inference already assigned `closure` the type `|int| -> ()` closure("String"); /*In cases where the compiler needs assistance, the arguments and return types may be annotated on closures, using the same notation as shown earlier. In the example below, since different types provide an implementation for the operator *, the argument type for the x parameter must be explicitly provided.*/ // Error: the type of `x` must be known to be used with `x * x` let square = |x | -> uint { (x * x) as uint }; let square_explicit = |x: int| -> uint { (x * x) as uint }; let square_infer = |x: int| { (x * x) as uint }; println!("{}", square_explicit(20)); // 400 println!("{}", square_infer(-20)); // 400 /*There are several forms of closure, each with its own role. The most common, called a stack closure, has type || and can directly access local variables in the enclosing scope.*/ let mut max = 0; let f = |x: int| if x > max { max = x }; for x in [1, 2, 3].iter() { f(*x); } /*Stack closures are very efficient because their environment is allocated on the call stack and refers by pointer to captured locals. To ensure that stack closures never outlive the local variables to which they refer, stack closures are not first-class. That is, they can only be used in argument position; they cannot be stored in data structures or returned from functions. Despite these limitations, stack closures are used pervasively in Rust code.*/ // -- Owned closures /*Owned closures, written proc, hold on to things that can safely be sent between processes. They copy the values they close over, but they also own them: that is, no other code can access them. Owned closures are used in concurrent code, particularly for spawning tasks. Closures can be used to spawn tasks. A practical example of this pattern is found when using the spawn function, which starts a new task.*/ use std::task::spawn; // proc is the closure which will be spawned. spawn(proc() { println!("I'm a new task") }); // -- Closure compatibility /*Rust closures have a convenient subtyping property: you can pass any kind of closure (as long as the arguments and return types match) to functions that expect a ||. Thus, when writing a higher-order function that only calls its function argument, and does nothing else with it, you should almost always declare the type of that argument as ||. That way, callers may pass any kind of closure.*/ fn call_twice(f: ||) { f(); f(); } let closure = || { "I'm a closure, and it doesn't matter what type I am"; }; fn function() { "I'm a normal function"; } call_twice(closure); call_twice(function);
fun
identifier_name
ch15-closures.rs
/*Named functions, like those we've seen so far, may not refer to local variables declared outside the function: they do not close over their environment (sometimes referred to as "capturing" variables in their environment). A closure does support accessing the enclosing scope */ let x = 3; // `fun` is an invalid definition fn fun () -> () { println!("{}", x) } // cannot capture from enclosing scope let closure = || -> () { println!("{}", x) }; // can capture from enclosing scope // `fun_arg` is an invalid definition fn fun_arg (arg: int) -> () { println!("{}", arg + x) } // cannot capture let closure_arg = |arg: int| -> () { println!("{}", arg + x) }; // can capture // ^ // Requires a type because the implementation needs to know which `+` to use. // In the future, the implementation may not need the help. fun(); // Still won't work closure(); // Prints: 3 fun_arg(7); // Still won't work closure_arg(7); // Prints: 10 /*Closures begin with the argument list between vertical bars and are followed by a single expression. Remember that a block, { <expr1>; <expr2>; ... }, is considered a single expression: it evaluates to the result of the last expression it contains if that expression is not followed by a semicolon, otherwise the block evaluates to (), the unit value. In general, return types and all argument types must be specified explicitly for function definitions.*/ fn fun (x: int) { println!("{}", x) } // this is same as saying `-> ()` fn square(x: int) -> uint { (x * x) as uint } // other return types are explicit // Error: mismatched types: expected `()` but found `uint` fn badfun(x: int) { (x * x) as uint } /*On the other hand, the compiler can usually infer both the argument and return types for a closure expression; therefore they are often omitted, since both a human reader and the compiler can deduce the types from the immediate context. This is in contrast to function declarations, which require types to be specified and are not subject to type inference.*/ // `fun` as a function declaration cannot infer the type of `x`, so it must be provided fn fun (x: int) { println!("{}", x) } let closure = |x | { println!("{}", x) }; // infers `x: int`, return type `()` // For closures, omitting a return type is *not* synonymous with `-> ()` let add_3 = |y | { 3i + y }; // infers `y: int`, return type `int`. fun(10); // Prints 10 closure(20); // Prints 20 closure(add_3(30)); // Prints 33 fun("String"); // Error: mismatched types // Error: mismatched types // inference already assigned `closure` the type `|int| -> ()` closure("String"); /*In cases where the compiler needs assistance, the arguments and return types may be annotated on closures, using the same notation as shown earlier. In the example below, since different types provide an implementation for the operator *, the argument type for the x parameter must be explicitly provided.*/ // Error: the type of `x` must be known to be used with `x * x` let square = |x | -> uint { (x * x) as uint }; let square_explicit = |x: int| -> uint { (x * x) as uint }; let square_infer = |x: int| { (x * x) as uint }; println!("{}", square_explicit(20)); // 400 println!("{}", square_infer(-20)); // 400 /*There are several forms of closure, each with its own role. The most common, called a stack closure, has type || and can directly access local variables in the enclosing scope.*/ let mut max = 0; let f = |x: int| if x > max
; for x in [1, 2, 3].iter() { f(*x); } /*Stack closures are very efficient because their environment is allocated on the call stack and refers by pointer to captured locals. To ensure that stack closures never outlive the local variables to which they refer, stack closures are not first-class. That is, they can only be used in argument position; they cannot be stored in data structures or returned from functions. Despite these limitations, stack closures are used pervasively in Rust code.*/ // -- Owned closures /*Owned closures, written proc, hold on to things that can safely be sent between processes. They copy the values they close over, but they also own them: that is, no other code can access them. Owned closures are used in concurrent code, particularly for spawning tasks. Closures can be used to spawn tasks. A practical example of this pattern is found when using the spawn function, which starts a new task.*/ use std::task::spawn; // proc is the closure which will be spawned. spawn(proc() { println!("I'm a new task") }); // -- Closure compatibility /*Rust closures have a convenient subtyping property: you can pass any kind of closure (as long as the arguments and return types match) to functions that expect a ||. Thus, when writing a higher-order function that only calls its function argument, and does nothing else with it, you should almost always declare the type of that argument as ||. That way, callers may pass any kind of closure.*/ fn call_twice(f: ||) { f(); f(); } let closure = || { "I'm a closure, and it doesn't matter what type I am"; }; fn function() { "I'm a normal function"; } call_twice(closure); call_twice(function);
{ max = x }
conditional_block
ch15-closures.rs
/*Named functions, like those we've seen so far, may not refer to local variables declared outside the function: they do not close over their environment (sometimes referred to as "capturing" variables in their environment). A closure does support accessing the enclosing scope */ let x = 3; // `fun` is an invalid definition fn fun () -> () { println!("{}", x) } // cannot capture from enclosing scope let closure = || -> () { println!("{}", x) }; // can capture from enclosing scope // `fun_arg` is an invalid definition fn fun_arg (arg: int) -> () { println!("{}", arg + x) } // cannot capture let closure_arg = |arg: int| -> () { println!("{}", arg + x) }; // can capture // ^ // Requires a type because the implementation needs to know which `+` to use. // In the future, the implementation may not need the help. fun(); // Still won't work closure(); // Prints: 3 fun_arg(7); // Still won't work closure_arg(7); // Prints: 10 /*Closures begin with the argument list between vertical bars and are followed by a single expression. Remember that a block, { <expr1>; <expr2>; ... }, is considered a single expression: it evaluates to the result of the last expression it contains if that expression is not followed by a semicolon, otherwise the block evaluates to (), the unit value. In general, return types and all argument types must be specified explicitly for function definitions.*/ fn fun (x: int) { println!("{}", x) } // this is same as saying `-> ()` fn square(x: int) -> uint { (x * x) as uint } // other return types are explicit // Error: mismatched types: expected `()` but found `uint` fn badfun(x: int) { (x * x) as uint } /*On the other hand, the compiler can usually infer both the argument and return types for a closure expression; therefore they are often omitted, since both a human reader and the compiler can deduce the types from the immediate context. This is in contrast to function declarations, which require types to be specified and are not subject to type inference.*/ // `fun` as a function declaration cannot infer the type of `x`, so it must be provided fn fun (x: int)
let closure = |x | { println!("{}", x) }; // infers `x: int`, return type `()` // For closures, omitting a return type is *not* synonymous with `-> ()` let add_3 = |y | { 3i + y }; // infers `y: int`, return type `int`. fun(10); // Prints 10 closure(20); // Prints 20 closure(add_3(30)); // Prints 33 fun("String"); // Error: mismatched types // Error: mismatched types // inference already assigned `closure` the type `|int| -> ()` closure("String"); /*In cases where the compiler needs assistance, the arguments and return types may be annotated on closures, using the same notation as shown earlier. In the example below, since different types provide an implementation for the operator *, the argument type for the x parameter must be explicitly provided.*/ // Error: the type of `x` must be known to be used with `x * x` let square = |x | -> uint { (x * x) as uint }; let square_explicit = |x: int| -> uint { (x * x) as uint }; let square_infer = |x: int| { (x * x) as uint }; println!("{}", square_explicit(20)); // 400 println!("{}", square_infer(-20)); // 400 /*There are several forms of closure, each with its own role. The most common, called a stack closure, has type || and can directly access local variables in the enclosing scope.*/ let mut max = 0; let f = |x: int| if x > max { max = x }; for x in [1, 2, 3].iter() { f(*x); } /*Stack closures are very efficient because their environment is allocated on the call stack and refers by pointer to captured locals. To ensure that stack closures never outlive the local variables to which they refer, stack closures are not first-class. That is, they can only be used in argument position; they cannot be stored in data structures or returned from functions. Despite these limitations, stack closures are used pervasively in Rust code.*/ // -- Owned closures /*Owned closures, written proc, hold on to things that can safely be sent between processes. They copy the values they close over, but they also own them: that is, no other code can access them. Owned closures are used in concurrent code, particularly for spawning tasks. Closures can be used to spawn tasks. A practical example of this pattern is found when using the spawn function, which starts a new task.*/ use std::task::spawn; // proc is the closure which will be spawned. spawn(proc() { println!("I'm a new task") }); // -- Closure compatibility /*Rust closures have a convenient subtyping property: you can pass any kind of closure (as long as the arguments and return types match) to functions that expect a ||. Thus, when writing a higher-order function that only calls its function argument, and does nothing else with it, you should almost always declare the type of that argument as ||. That way, callers may pass any kind of closure.*/ fn call_twice(f: ||) { f(); f(); } let closure = || { "I'm a closure, and it doesn't matter what type I am"; }; fn function() { "I'm a normal function"; } call_twice(closure); call_twice(function);
{ println!("{}", x) }
identifier_body
base.py
""" File: base.py Author: Me Email: yourname@email.com Github: https://github.com/yourname Description:
from django.test import TestCase from django.urls import reverse from django.utils import timezone from django.utils.crypto import get_random_string from rest_framework.test import APITestCase # from oauth2_provider.tests.test_utils import TestCaseUtils from oauth2_provider.models import get_application_model, AccessToken from rest_framework import status import json import pytest from mixer.backend.django import mixer Application = get_application_model() pytestmark = pytest.mark.django_db class PostsBaseTest(APITestCase): def test_create_user_model(self): User.objects.create( username='Hello_World' ) assert User.objects.count() == 1, "Should be equal" def set_oauth2_app_by_admin(self, user): app = Application.objects.create( name='SuperAPI OAUTH2 APP', user=user, client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_PASSWORD, ) return app def get_token(self, access_user, app): random = get_random_string(length=1024) access_token = AccessToken.objects.create( user=access_user, scope='read write', expires=timezone.now() + timedelta(minutes=5), token=f'{random}---{access_user.username}', application=app ) return access_token.token
""" from datetime import timedelta from django.contrib.auth.models import User
random_line_split
base.py
""" File: base.py Author: Me Email: yourname@email.com Github: https://github.com/yourname Description: """ from datetime import timedelta from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from django.utils import timezone from django.utils.crypto import get_random_string from rest_framework.test import APITestCase # from oauth2_provider.tests.test_utils import TestCaseUtils from oauth2_provider.models import get_application_model, AccessToken from rest_framework import status import json import pytest from mixer.backend.django import mixer Application = get_application_model() pytestmark = pytest.mark.django_db class PostsBaseTest(APITestCase): def
(self): User.objects.create( username='Hello_World' ) assert User.objects.count() == 1, "Should be equal" def set_oauth2_app_by_admin(self, user): app = Application.objects.create( name='SuperAPI OAUTH2 APP', user=user, client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_PASSWORD, ) return app def get_token(self, access_user, app): random = get_random_string(length=1024) access_token = AccessToken.objects.create( user=access_user, scope='read write', expires=timezone.now() + timedelta(minutes=5), token=f'{random}---{access_user.username}', application=app ) return access_token.token
test_create_user_model
identifier_name
base.py
""" File: base.py Author: Me Email: yourname@email.com Github: https://github.com/yourname Description: """ from datetime import timedelta from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from django.utils import timezone from django.utils.crypto import get_random_string from rest_framework.test import APITestCase # from oauth2_provider.tests.test_utils import TestCaseUtils from oauth2_provider.models import get_application_model, AccessToken from rest_framework import status import json import pytest from mixer.backend.django import mixer Application = get_application_model() pytestmark = pytest.mark.django_db class PostsBaseTest(APITestCase): def test_create_user_model(self): User.objects.create( username='Hello_World' ) assert User.objects.count() == 1, "Should be equal" def set_oauth2_app_by_admin(self, user): app = Application.objects.create( name='SuperAPI OAUTH2 APP', user=user, client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_PASSWORD, ) return app def get_token(self, access_user, app):
random = get_random_string(length=1024) access_token = AccessToken.objects.create( user=access_user, scope='read write', expires=timezone.now() + timedelta(minutes=5), token=f'{random}---{access_user.username}', application=app ) return access_token.token
identifier_body
danmaku.dom.js
var transform = (function() { var properties = [ 'oTransform', // Opera 11.5 'msTransform', // IE 9 'mozTransform', 'webkitTransform', 'transform' ]; var style = document.createElement('div').style; for (var i = 0; i < properties.length; i++) { /* istanbul ignore else */ if (properties[i] in style) { return properties[i]; } } /* istanbul ignore next */ return 'transform'; }()); function createCommentNode(cmt) { var node = document.createElement('div'); node.style.cssText = 'position:absolute;'; if (typeof cmt.render === 'function') { var $el = cmt.render(); if ($el instanceof HTMLElement) { node.appendChild($el); return node; } } node.textContent = cmt.text; if (cmt.style) { for (var key in cmt.style) { node.style[key] = cmt.style[key]; } } return node; } function init() { var stage = document.createElement('div'); stage.style.cssText = 'overflow:hidden;white-space:nowrap;transform:translateZ(0);'; return stage; } function clear(stage) { var lc = stage.lastChild; while (lc) { stage.removeChild(lc); lc = stage.lastChild; } } function resize(stage) { stage.style.width = stage.width + 'px'; stage.style.height = stage.height + 'px'; } function framing() { // } function setup(stage, comments) { var df = document.createDocumentFragment(); var i = 0; var cmt = null; for (i = 0; i < comments.length; i++) { cmt = comments[i]; cmt.node = cmt.node || createCommentNode(cmt); df.appendChild(cmt.node); } if (comments.length) { stage.appendChild(df); } for (i = 0; i < comments.length; i++) { cmt = comments[i]; cmt.width = cmt.width || cmt.node.offsetWidth; cmt.height = cmt.height || cmt.node.offsetHeight; } } function render(stage, cmt) { cmt.node.style[transform] = 'translate(' + cmt.x + 'px,' + cmt.y + 'px)'; } /* eslint no-invalid-this: 0 */ function remove(stage, cmt) { stage.removeChild(cmt.node); /* istanbul ignore else */ if (!this.media) { cmt.node = null; } } var domEngine = { name: 'dom', init: init, clear: clear, resize: resize, framing: framing, setup: setup, render: render, remove: remove, }; /* eslint no-invalid-this: 0 */ function allocate(cmt) { var that = this; var ct = this.media ? this.media.currentTime : Date.now() / 1000; var pbr = this.media ? this.media.playbackRate : 1; function willCollide(cr, cmt) { if (cmt.mode === 'top' || cmt.mode === 'bottom') { return ct - cr.time < that._.duration; } var crTotalWidth = that._.stage.width + cr.width; var crElapsed = crTotalWidth * (ct - cr.time) * pbr / that._.duration; if (cr.width > crElapsed) { return true; } // (rtl mode) the right end of `cr` move out of left side of stage var crLeftTime = that._.duration + cr.time - ct; var cmtTotalWidth = that._.stage.width + cmt.width; var cmtTime = that.media ? cmt.time : cmt._utc; var cmtElapsed = cmtTotalWidth * (ct - cmtTime) * pbr / that._.duration; var cmtArrival = that._.stage.width - cmtElapsed; // (rtl mode) the left end of `cmt` reach the left side of stage var cmtArrivalTime = that._.duration * cmtArrival / (that._.stage.width + cmt.width); return crLeftTime > cmtArrivalTime; } var crs = this._.space[cmt.mode]; var last = 0; var curr = 0; for (var i = 1; i < crs.length; i++) { var cr = crs[i]; var requiredRange = cmt.height; if (cmt.mode === 'top' || cmt.mode === 'bottom') { requiredRange += cr.height; } if (cr.range - cr.height - crs[last].range >= requiredRange) { curr = i; break; } if (willCollide(cr, cmt)) { last = i; } } var channel = crs[last].range; var crObj = { range: channel + cmt.height, time: this.media ? cmt.time : cmt._utc, width: cmt.width, height: cmt.height }; crs.splice(last + 1, curr - last - 1, crObj); if (cmt.mode === 'bottom') { return this._.stage.height - cmt.height - channel % this._.stage.height; } return channel % (this._.stage.height - cmt.height); } /* eslint no-invalid-this: 0 */ function createEngine(framing, setup, render, remove) { return function() { framing(this._.stage); var dn = Date.now() / 1000; var ct = this.media ? this.media.currentTime : dn; var pbr = this.media ? this.media.playbackRate : 1; var cmt = null; var cmtt = 0; var i = 0; for (i = this._.runningList.length - 1; i >= 0; i--) { cmt = this._.runningList[i]; cmtt = this.media ? cmt.time : cmt._utc; if (ct - cmtt > this._.duration) { remove(this._.stage, cmt); this._.runningList.splice(i, 1); } } var pendingList = []; while (this._.position < this.comments.length) { cmt = this.comments[this._.position]; cmtt = this.media ? cmt.time : cmt._utc; if (cmtt >= ct) { break; } // when clicking controls to seek, media.currentTime may changed before // `pause` event is fired, so here skips comments out of duration, // see https://github.com/weizhenye/Danmaku/pull/30 for details. if (ct - cmtt > this._.duration) { ++this._.position; continue; } if (this.media) { cmt._utc = dn - (this.media.currentTime - cmt.time); } pendingList.push(cmt); ++this._.position; } setup(this._.stage, pendingList); for (i = 0; i < pendingList.length; i++) { cmt = pendingList[i]; cmt.y = allocate.call(this, cmt); if (cmt.mode === 'top' || cmt.mode === 'bottom') { cmt.x = (this._.stage.width - cmt.width) >> 1; } this._.runningList.push(cmt); } for (i = 0; i < this._.runningList.length; i++) { cmt = this._.runningList[i]; var totalWidth = this._.stage.width + cmt.width; var elapsed = totalWidth * (dn - cmt._utc) * pbr / this._.duration; if (cmt.mode === 'ltr') cmt.x = (elapsed - cmt.width + .5) | 0; if (cmt.mode === 'rtl') cmt.x = (this._.stage.width - elapsed + .5) | 0; render(this._.stage, cmt); } }; } var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function(cb) { return setTimeout(cb, 50 / 3); };
var caf = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || clearTimeout; function binsearch(arr, prop, key) { var mid = 0; var left = 0; var right = arr.length; while (left < right - 1) { mid = (left + right) >> 1; if (key >= arr[mid][prop]) { left = mid; } else { right = mid; } } if (arr[left] && key < arr[left][prop]) { return left; } return right; } function formatMode(mode) { if (!/^(ltr|top|bottom)$/i.test(mode)) { return 'rtl'; } return mode.toLowerCase(); } function collidableRange() { var max = 9007199254740991; return [ { range: 0, time: -max, width: max, height: 0 }, { range: max, time: max, width: 0, height: 0 } ]; } function resetSpace(space) { space.ltr = collidableRange(); space.rtl = collidableRange(); space.top = collidableRange(); space.bottom = collidableRange(); } /* eslint no-invalid-this: 0 */ function play() { if (!this._.visible || !this._.paused) { return this; } this._.paused = false; if (this.media) { for (var i = 0; i < this._.runningList.length; i++) { var cmt = this._.runningList[i]; cmt._utc = Date.now() / 1000 - (this.media.currentTime - cmt.time); } } var that = this; var engine = createEngine( this._.engine.framing.bind(this), this._.engine.setup.bind(this), this._.engine.render.bind(this), this._.engine.remove.bind(this) ); function frame() { engine.call(that); that._.requestID = raf(frame); } this._.requestID = raf(frame); return this; } /* eslint no-invalid-this: 0 */ function pause() { if (!this._.visible || this._.paused) { return this; } this._.paused = true; caf(this._.requestID); this._.requestID = 0; return this; } /* eslint no-invalid-this: 0 */ function seek() { if (!this.media) { return this; } this.clear(); resetSpace(this._.space); var position = binsearch(this.comments, 'time', this.media.currentTime); this._.position = Math.max(0, position - 1); return this; } /* eslint no-invalid-this: 0 */ function bindEvents(_) { _.play = play.bind(this); _.pause = pause.bind(this); _.seeking = seek.bind(this); this.media.addEventListener('play', _.play); this.media.addEventListener('pause', _.pause); this.media.addEventListener('playing', _.play); this.media.addEventListener('waiting', _.pause); this.media.addEventListener('seeking', _.seeking); } /* eslint no-invalid-this: 0 */ function unbindEvents(_) { this.media.removeEventListener('play', _.play); this.media.removeEventListener('pause', _.pause); this.media.removeEventListener('playing', _.play); this.media.removeEventListener('waiting', _.pause); this.media.removeEventListener('seeking', _.seeking); _.play = null; _.pause = null; _.seeking = null; } /* eslint-disable no-invalid-this */ function init$1(opt) { this._ = {}; this.container = opt.container || document.createElement('div'); this.media = opt.media; this._.visible = true; /* eslint-disable no-undef */ /* istanbul ignore next */ { this.engine = 'dom'; this._.engine = domEngine; } /* eslint-enable no-undef */ this._.requestID = 0; this._.speed = Math.max(0, opt.speed) || 144; this._.duration = 4; this.comments = opt.comments || []; this.comments.sort(function(a, b) { return a.time - b.time; }); for (var i = 0; i < this.comments.length; i++) { this.comments[i].mode = formatMode(this.comments[i].mode); } this._.runningList = []; this._.position = 0; this._.paused = true; if (this.media) { this._.listener = {}; bindEvents.call(this, this._.listener); } this._.stage = this._.engine.init(this.container); this._.stage.style.cssText += 'position:relative;pointer-events:none;'; this.resize(); this.container.appendChild(this._.stage); this._.space = {}; resetSpace(this._.space); if (!this.media || !this.media.paused) { seek.call(this); play.call(this); } return this; } /* eslint-disable no-invalid-this */ function destroy() { if (!this.container) { return this; } pause.call(this); this.clear(); this.container.removeChild(this._.stage); if (this.media) { unbindEvents.call(this, this._.listener); } for (var key in this) { /* istanbul ignore else */ if (Object.prototype.hasOwnProperty.call(this, key)) { this[key] = null; } } return this; } var properties = ['mode', 'time', 'text', 'render', 'style']; /* eslint-disable no-invalid-this */ function emit(obj) { if (!obj || Object.prototype.toString.call(obj) !== '[object Object]') { return this; } var cmt = {}; for (var i = 0; i < properties.length; i++) { if (obj[properties[i]] !== undefined) { cmt[properties[i]] = obj[properties[i]]; } } cmt.text = (cmt.text || '').toString(); cmt.mode = formatMode(cmt.mode); cmt._utc = Date.now() / 1000; if (this.media) { var position = 0; if (cmt.time === undefined) { cmt.time = this.media.currentTime; position = this._.position; } else { position = binsearch(this.comments, 'time', cmt.time); if (position < this._.position) { this._.position += 1; } } this.comments.splice(position, 0, cmt); } else { this.comments.push(cmt); } return this; } /* eslint-disable no-invalid-this */ function show() { if (this._.visible) { return this; } this._.visible = true; if (this.media && this.media.paused) { return this; } seek.call(this); play.call(this); return this; } /* eslint-disable no-invalid-this */ function hide() { if (!this._.visible) { return this; } pause.call(this); this.clear(); this._.visible = false; return this; } /* eslint-disable no-invalid-this */ function clear$1() { this._.engine.clear(this._.stage, this._.runningList); this._.runningList = []; return this; } /* eslint-disable no-invalid-this */ function resize$1() { this._.stage.width = this.container.offsetWidth; this._.stage.height = this.container.offsetHeight; this._.engine.resize(this._.stage); this._.duration = this._.stage.width / this._.speed; return this; } var speed = { get: function() { return this._.speed; }, set: function(s) { if (typeof s !== 'number' || isNaN(s) || !isFinite(s) || s <= 0) { return this._.speed; } this._.speed = s; if (this._.stage.width) { this._.duration = this._.stage.width / s; } return s; } }; function Danmaku(opt) { opt && init$1.call(this, opt); } Danmaku.prototype.destroy = function() { return destroy.call(this); }; Danmaku.prototype.emit = function(cmt) { return emit.call(this, cmt); }; Danmaku.prototype.show = function() { return show.call(this); }; Danmaku.prototype.hide = function() { return hide.call(this); }; Danmaku.prototype.clear = function() { return clear$1.call(this); }; Danmaku.prototype.resize = function() { return resize$1.call(this); }; Object.defineProperty(Danmaku.prototype, 'speed', speed); export default Danmaku;
random_line_split
danmaku.dom.js
var transform = (function() { var properties = [ 'oTransform', // Opera 11.5 'msTransform', // IE 9 'mozTransform', 'webkitTransform', 'transform' ]; var style = document.createElement('div').style; for (var i = 0; i < properties.length; i++) { /* istanbul ignore else */ if (properties[i] in style) { return properties[i]; } } /* istanbul ignore next */ return 'transform'; }()); function createCommentNode(cmt) { var node = document.createElement('div'); node.style.cssText = 'position:absolute;'; if (typeof cmt.render === 'function') { var $el = cmt.render(); if ($el instanceof HTMLElement) { node.appendChild($el); return node; } } node.textContent = cmt.text; if (cmt.style) { for (var key in cmt.style) { node.style[key] = cmt.style[key]; } } return node; } function init() { var stage = document.createElement('div'); stage.style.cssText = 'overflow:hidden;white-space:nowrap;transform:translateZ(0);'; return stage; } function clear(stage) { var lc = stage.lastChild; while (lc) { stage.removeChild(lc); lc = stage.lastChild; } } function resize(stage) { stage.style.width = stage.width + 'px'; stage.style.height = stage.height + 'px'; } function framing() { // } function setup(stage, comments) { var df = document.createDocumentFragment(); var i = 0; var cmt = null; for (i = 0; i < comments.length; i++) { cmt = comments[i]; cmt.node = cmt.node || createCommentNode(cmt); df.appendChild(cmt.node); } if (comments.length) { stage.appendChild(df); } for (i = 0; i < comments.length; i++) { cmt = comments[i]; cmt.width = cmt.width || cmt.node.offsetWidth; cmt.height = cmt.height || cmt.node.offsetHeight; } } function render(stage, cmt) { cmt.node.style[transform] = 'translate(' + cmt.x + 'px,' + cmt.y + 'px)'; } /* eslint no-invalid-this: 0 */ function remove(stage, cmt) { stage.removeChild(cmt.node); /* istanbul ignore else */ if (!this.media) { cmt.node = null; } } var domEngine = { name: 'dom', init: init, clear: clear, resize: resize, framing: framing, setup: setup, render: render, remove: remove, }; /* eslint no-invalid-this: 0 */ function allocate(cmt) { var that = this; var ct = this.media ? this.media.currentTime : Date.now() / 1000; var pbr = this.media ? this.media.playbackRate : 1; function willCollide(cr, cmt) { if (cmt.mode === 'top' || cmt.mode === 'bottom') { return ct - cr.time < that._.duration; } var crTotalWidth = that._.stage.width + cr.width; var crElapsed = crTotalWidth * (ct - cr.time) * pbr / that._.duration; if (cr.width > crElapsed) { return true; } // (rtl mode) the right end of `cr` move out of left side of stage var crLeftTime = that._.duration + cr.time - ct; var cmtTotalWidth = that._.stage.width + cmt.width; var cmtTime = that.media ? cmt.time : cmt._utc; var cmtElapsed = cmtTotalWidth * (ct - cmtTime) * pbr / that._.duration; var cmtArrival = that._.stage.width - cmtElapsed; // (rtl mode) the left end of `cmt` reach the left side of stage var cmtArrivalTime = that._.duration * cmtArrival / (that._.stage.width + cmt.width); return crLeftTime > cmtArrivalTime; } var crs = this._.space[cmt.mode]; var last = 0; var curr = 0; for (var i = 1; i < crs.length; i++) { var cr = crs[i]; var requiredRange = cmt.height; if (cmt.mode === 'top' || cmt.mode === 'bottom') { requiredRange += cr.height; } if (cr.range - cr.height - crs[last].range >= requiredRange) { curr = i; break; } if (willCollide(cr, cmt)) { last = i; } } var channel = crs[last].range; var crObj = { range: channel + cmt.height, time: this.media ? cmt.time : cmt._utc, width: cmt.width, height: cmt.height }; crs.splice(last + 1, curr - last - 1, crObj); if (cmt.mode === 'bottom') { return this._.stage.height - cmt.height - channel % this._.stage.height; } return channel % (this._.stage.height - cmt.height); } /* eslint no-invalid-this: 0 */ function createEngine(framing, setup, render, remove) { return function() { framing(this._.stage); var dn = Date.now() / 1000; var ct = this.media ? this.media.currentTime : dn; var pbr = this.media ? this.media.playbackRate : 1; var cmt = null; var cmtt = 0; var i = 0; for (i = this._.runningList.length - 1; i >= 0; i--) { cmt = this._.runningList[i]; cmtt = this.media ? cmt.time : cmt._utc; if (ct - cmtt > this._.duration) { remove(this._.stage, cmt); this._.runningList.splice(i, 1); } } var pendingList = []; while (this._.position < this.comments.length) { cmt = this.comments[this._.position]; cmtt = this.media ? cmt.time : cmt._utc; if (cmtt >= ct) { break; } // when clicking controls to seek, media.currentTime may changed before // `pause` event is fired, so here skips comments out of duration, // see https://github.com/weizhenye/Danmaku/pull/30 for details. if (ct - cmtt > this._.duration) { ++this._.position; continue; } if (this.media) { cmt._utc = dn - (this.media.currentTime - cmt.time); } pendingList.push(cmt); ++this._.position; } setup(this._.stage, pendingList); for (i = 0; i < pendingList.length; i++) { cmt = pendingList[i]; cmt.y = allocate.call(this, cmt); if (cmt.mode === 'top' || cmt.mode === 'bottom') { cmt.x = (this._.stage.width - cmt.width) >> 1; } this._.runningList.push(cmt); } for (i = 0; i < this._.runningList.length; i++) { cmt = this._.runningList[i]; var totalWidth = this._.stage.width + cmt.width; var elapsed = totalWidth * (dn - cmt._utc) * pbr / this._.duration; if (cmt.mode === 'ltr') cmt.x = (elapsed - cmt.width + .5) | 0; if (cmt.mode === 'rtl') cmt.x = (this._.stage.width - elapsed + .5) | 0; render(this._.stage, cmt); } }; } var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function(cb) { return setTimeout(cb, 50 / 3); }; var caf = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || clearTimeout; function binsearch(arr, prop, key) { var mid = 0; var left = 0; var right = arr.length; while (left < right - 1) { mid = (left + right) >> 1; if (key >= arr[mid][prop]) { left = mid; } else { right = mid; } } if (arr[left] && key < arr[left][prop]) { return left; } return right; } function formatMode(mode) { if (!/^(ltr|top|bottom)$/i.test(mode)) { return 'rtl'; } return mode.toLowerCase(); } function collidableRange() { var max = 9007199254740991; return [ { range: 0, time: -max, width: max, height: 0 }, { range: max, time: max, width: 0, height: 0 } ]; } function resetSpace(space) { space.ltr = collidableRange(); space.rtl = collidableRange(); space.top = collidableRange(); space.bottom = collidableRange(); } /* eslint no-invalid-this: 0 */ function play() { if (!this._.visible || !this._.paused) { return this; } this._.paused = false; if (this.media) { for (var i = 0; i < this._.runningList.length; i++) { var cmt = this._.runningList[i]; cmt._utc = Date.now() / 1000 - (this.media.currentTime - cmt.time); } } var that = this; var engine = createEngine( this._.engine.framing.bind(this), this._.engine.setup.bind(this), this._.engine.render.bind(this), this._.engine.remove.bind(this) ); function frame() { engine.call(that); that._.requestID = raf(frame); } this._.requestID = raf(frame); return this; } /* eslint no-invalid-this: 0 */ function pause() { if (!this._.visible || this._.paused) { return this; } this._.paused = true; caf(this._.requestID); this._.requestID = 0; return this; } /* eslint no-invalid-this: 0 */ function seek() { if (!this.media) { return this; } this.clear(); resetSpace(this._.space); var position = binsearch(this.comments, 'time', this.media.currentTime); this._.position = Math.max(0, position - 1); return this; } /* eslint no-invalid-this: 0 */ function bindEvents(_) { _.play = play.bind(this); _.pause = pause.bind(this); _.seeking = seek.bind(this); this.media.addEventListener('play', _.play); this.media.addEventListener('pause', _.pause); this.media.addEventListener('playing', _.play); this.media.addEventListener('waiting', _.pause); this.media.addEventListener('seeking', _.seeking); } /* eslint no-invalid-this: 0 */ function unbindEvents(_) { this.media.removeEventListener('play', _.play); this.media.removeEventListener('pause', _.pause); this.media.removeEventListener('playing', _.play); this.media.removeEventListener('waiting', _.pause); this.media.removeEventListener('seeking', _.seeking); _.play = null; _.pause = null; _.seeking = null; } /* eslint-disable no-invalid-this */ function init$1(opt) { this._ = {}; this.container = opt.container || document.createElement('div'); this.media = opt.media; this._.visible = true; /* eslint-disable no-undef */ /* istanbul ignore next */ { this.engine = 'dom'; this._.engine = domEngine; } /* eslint-enable no-undef */ this._.requestID = 0; this._.speed = Math.max(0, opt.speed) || 144; this._.duration = 4; this.comments = opt.comments || []; this.comments.sort(function(a, b) { return a.time - b.time; }); for (var i = 0; i < this.comments.length; i++) { this.comments[i].mode = formatMode(this.comments[i].mode); } this._.runningList = []; this._.position = 0; this._.paused = true; if (this.media) { this._.listener = {}; bindEvents.call(this, this._.listener); } this._.stage = this._.engine.init(this.container); this._.stage.style.cssText += 'position:relative;pointer-events:none;'; this.resize(); this.container.appendChild(this._.stage); this._.space = {}; resetSpace(this._.space); if (!this.media || !this.media.paused) { seek.call(this); play.call(this); } return this; } /* eslint-disable no-invalid-this */ function
() { if (!this.container) { return this; } pause.call(this); this.clear(); this.container.removeChild(this._.stage); if (this.media) { unbindEvents.call(this, this._.listener); } for (var key in this) { /* istanbul ignore else */ if (Object.prototype.hasOwnProperty.call(this, key)) { this[key] = null; } } return this; } var properties = ['mode', 'time', 'text', 'render', 'style']; /* eslint-disable no-invalid-this */ function emit(obj) { if (!obj || Object.prototype.toString.call(obj) !== '[object Object]') { return this; } var cmt = {}; for (var i = 0; i < properties.length; i++) { if (obj[properties[i]] !== undefined) { cmt[properties[i]] = obj[properties[i]]; } } cmt.text = (cmt.text || '').toString(); cmt.mode = formatMode(cmt.mode); cmt._utc = Date.now() / 1000; if (this.media) { var position = 0; if (cmt.time === undefined) { cmt.time = this.media.currentTime; position = this._.position; } else { position = binsearch(this.comments, 'time', cmt.time); if (position < this._.position) { this._.position += 1; } } this.comments.splice(position, 0, cmt); } else { this.comments.push(cmt); } return this; } /* eslint-disable no-invalid-this */ function show() { if (this._.visible) { return this; } this._.visible = true; if (this.media && this.media.paused) { return this; } seek.call(this); play.call(this); return this; } /* eslint-disable no-invalid-this */ function hide() { if (!this._.visible) { return this; } pause.call(this); this.clear(); this._.visible = false; return this; } /* eslint-disable no-invalid-this */ function clear$1() { this._.engine.clear(this._.stage, this._.runningList); this._.runningList = []; return this; } /* eslint-disable no-invalid-this */ function resize$1() { this._.stage.width = this.container.offsetWidth; this._.stage.height = this.container.offsetHeight; this._.engine.resize(this._.stage); this._.duration = this._.stage.width / this._.speed; return this; } var speed = { get: function() { return this._.speed; }, set: function(s) { if (typeof s !== 'number' || isNaN(s) || !isFinite(s) || s <= 0) { return this._.speed; } this._.speed = s; if (this._.stage.width) { this._.duration = this._.stage.width / s; } return s; } }; function Danmaku(opt) { opt && init$1.call(this, opt); } Danmaku.prototype.destroy = function() { return destroy.call(this); }; Danmaku.prototype.emit = function(cmt) { return emit.call(this, cmt); }; Danmaku.prototype.show = function() { return show.call(this); }; Danmaku.prototype.hide = function() { return hide.call(this); }; Danmaku.prototype.clear = function() { return clear$1.call(this); }; Danmaku.prototype.resize = function() { return resize$1.call(this); }; Object.defineProperty(Danmaku.prototype, 'speed', speed); export default Danmaku;
destroy
identifier_name
danmaku.dom.js
var transform = (function() { var properties = [ 'oTransform', // Opera 11.5 'msTransform', // IE 9 'mozTransform', 'webkitTransform', 'transform' ]; var style = document.createElement('div').style; for (var i = 0; i < properties.length; i++) { /* istanbul ignore else */ if (properties[i] in style) { return properties[i]; } } /* istanbul ignore next */ return 'transform'; }()); function createCommentNode(cmt) { var node = document.createElement('div'); node.style.cssText = 'position:absolute;'; if (typeof cmt.render === 'function') { var $el = cmt.render(); if ($el instanceof HTMLElement) { node.appendChild($el); return node; } } node.textContent = cmt.text; if (cmt.style) { for (var key in cmt.style) { node.style[key] = cmt.style[key]; } } return node; } function init() { var stage = document.createElement('div'); stage.style.cssText = 'overflow:hidden;white-space:nowrap;transform:translateZ(0);'; return stage; } function clear(stage) { var lc = stage.lastChild; while (lc) { stage.removeChild(lc); lc = stage.lastChild; } } function resize(stage) { stage.style.width = stage.width + 'px'; stage.style.height = stage.height + 'px'; } function framing() { // } function setup(stage, comments) { var df = document.createDocumentFragment(); var i = 0; var cmt = null; for (i = 0; i < comments.length; i++) { cmt = comments[i]; cmt.node = cmt.node || createCommentNode(cmt); df.appendChild(cmt.node); } if (comments.length) { stage.appendChild(df); } for (i = 0; i < comments.length; i++) { cmt = comments[i]; cmt.width = cmt.width || cmt.node.offsetWidth; cmt.height = cmt.height || cmt.node.offsetHeight; } } function render(stage, cmt) { cmt.node.style[transform] = 'translate(' + cmt.x + 'px,' + cmt.y + 'px)'; } /* eslint no-invalid-this: 0 */ function remove(stage, cmt) { stage.removeChild(cmt.node); /* istanbul ignore else */ if (!this.media) { cmt.node = null; } } var domEngine = { name: 'dom', init: init, clear: clear, resize: resize, framing: framing, setup: setup, render: render, remove: remove, }; /* eslint no-invalid-this: 0 */ function allocate(cmt) { var that = this; var ct = this.media ? this.media.currentTime : Date.now() / 1000; var pbr = this.media ? this.media.playbackRate : 1; function willCollide(cr, cmt) { if (cmt.mode === 'top' || cmt.mode === 'bottom') { return ct - cr.time < that._.duration; } var crTotalWidth = that._.stage.width + cr.width; var crElapsed = crTotalWidth * (ct - cr.time) * pbr / that._.duration; if (cr.width > crElapsed) { return true; } // (rtl mode) the right end of `cr` move out of left side of stage var crLeftTime = that._.duration + cr.time - ct; var cmtTotalWidth = that._.stage.width + cmt.width; var cmtTime = that.media ? cmt.time : cmt._utc; var cmtElapsed = cmtTotalWidth * (ct - cmtTime) * pbr / that._.duration; var cmtArrival = that._.stage.width - cmtElapsed; // (rtl mode) the left end of `cmt` reach the left side of stage var cmtArrivalTime = that._.duration * cmtArrival / (that._.stage.width + cmt.width); return crLeftTime > cmtArrivalTime; } var crs = this._.space[cmt.mode]; var last = 0; var curr = 0; for (var i = 1; i < crs.length; i++) { var cr = crs[i]; var requiredRange = cmt.height; if (cmt.mode === 'top' || cmt.mode === 'bottom') { requiredRange += cr.height; } if (cr.range - cr.height - crs[last].range >= requiredRange) { curr = i; break; } if (willCollide(cr, cmt)) { last = i; } } var channel = crs[last].range; var crObj = { range: channel + cmt.height, time: this.media ? cmt.time : cmt._utc, width: cmt.width, height: cmt.height }; crs.splice(last + 1, curr - last - 1, crObj); if (cmt.mode === 'bottom') { return this._.stage.height - cmt.height - channel % this._.stage.height; } return channel % (this._.stage.height - cmt.height); } /* eslint no-invalid-this: 0 */ function createEngine(framing, setup, render, remove) { return function() { framing(this._.stage); var dn = Date.now() / 1000; var ct = this.media ? this.media.currentTime : dn; var pbr = this.media ? this.media.playbackRate : 1; var cmt = null; var cmtt = 0; var i = 0; for (i = this._.runningList.length - 1; i >= 0; i--) { cmt = this._.runningList[i]; cmtt = this.media ? cmt.time : cmt._utc; if (ct - cmtt > this._.duration) { remove(this._.stage, cmt); this._.runningList.splice(i, 1); } } var pendingList = []; while (this._.position < this.comments.length) { cmt = this.comments[this._.position]; cmtt = this.media ? cmt.time : cmt._utc; if (cmtt >= ct) { break; } // when clicking controls to seek, media.currentTime may changed before // `pause` event is fired, so here skips comments out of duration, // see https://github.com/weizhenye/Danmaku/pull/30 for details. if (ct - cmtt > this._.duration) { ++this._.position; continue; } if (this.media) { cmt._utc = dn - (this.media.currentTime - cmt.time); } pendingList.push(cmt); ++this._.position; } setup(this._.stage, pendingList); for (i = 0; i < pendingList.length; i++) { cmt = pendingList[i]; cmt.y = allocate.call(this, cmt); if (cmt.mode === 'top' || cmt.mode === 'bottom') { cmt.x = (this._.stage.width - cmt.width) >> 1; } this._.runningList.push(cmt); } for (i = 0; i < this._.runningList.length; i++) { cmt = this._.runningList[i]; var totalWidth = this._.stage.width + cmt.width; var elapsed = totalWidth * (dn - cmt._utc) * pbr / this._.duration; if (cmt.mode === 'ltr') cmt.x = (elapsed - cmt.width + .5) | 0; if (cmt.mode === 'rtl') cmt.x = (this._.stage.width - elapsed + .5) | 0; render(this._.stage, cmt); } }; } var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function(cb) { return setTimeout(cb, 50 / 3); }; var caf = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || clearTimeout; function binsearch(arr, prop, key) { var mid = 0; var left = 0; var right = arr.length; while (left < right - 1) { mid = (left + right) >> 1; if (key >= arr[mid][prop]) { left = mid; } else { right = mid; } } if (arr[left] && key < arr[left][prop]) { return left; } return right; } function formatMode(mode) { if (!/^(ltr|top|bottom)$/i.test(mode)) { return 'rtl'; } return mode.toLowerCase(); } function collidableRange() { var max = 9007199254740991; return [ { range: 0, time: -max, width: max, height: 0 }, { range: max, time: max, width: 0, height: 0 } ]; } function resetSpace(space) { space.ltr = collidableRange(); space.rtl = collidableRange(); space.top = collidableRange(); space.bottom = collidableRange(); } /* eslint no-invalid-this: 0 */ function play() { if (!this._.visible || !this._.paused) { return this; } this._.paused = false; if (this.media)
var that = this; var engine = createEngine( this._.engine.framing.bind(this), this._.engine.setup.bind(this), this._.engine.render.bind(this), this._.engine.remove.bind(this) ); function frame() { engine.call(that); that._.requestID = raf(frame); } this._.requestID = raf(frame); return this; } /* eslint no-invalid-this: 0 */ function pause() { if (!this._.visible || this._.paused) { return this; } this._.paused = true; caf(this._.requestID); this._.requestID = 0; return this; } /* eslint no-invalid-this: 0 */ function seek() { if (!this.media) { return this; } this.clear(); resetSpace(this._.space); var position = binsearch(this.comments, 'time', this.media.currentTime); this._.position = Math.max(0, position - 1); return this; } /* eslint no-invalid-this: 0 */ function bindEvents(_) { _.play = play.bind(this); _.pause = pause.bind(this); _.seeking = seek.bind(this); this.media.addEventListener('play', _.play); this.media.addEventListener('pause', _.pause); this.media.addEventListener('playing', _.play); this.media.addEventListener('waiting', _.pause); this.media.addEventListener('seeking', _.seeking); } /* eslint no-invalid-this: 0 */ function unbindEvents(_) { this.media.removeEventListener('play', _.play); this.media.removeEventListener('pause', _.pause); this.media.removeEventListener('playing', _.play); this.media.removeEventListener('waiting', _.pause); this.media.removeEventListener('seeking', _.seeking); _.play = null; _.pause = null; _.seeking = null; } /* eslint-disable no-invalid-this */ function init$1(opt) { this._ = {}; this.container = opt.container || document.createElement('div'); this.media = opt.media; this._.visible = true; /* eslint-disable no-undef */ /* istanbul ignore next */ { this.engine = 'dom'; this._.engine = domEngine; } /* eslint-enable no-undef */ this._.requestID = 0; this._.speed = Math.max(0, opt.speed) || 144; this._.duration = 4; this.comments = opt.comments || []; this.comments.sort(function(a, b) { return a.time - b.time; }); for (var i = 0; i < this.comments.length; i++) { this.comments[i].mode = formatMode(this.comments[i].mode); } this._.runningList = []; this._.position = 0; this._.paused = true; if (this.media) { this._.listener = {}; bindEvents.call(this, this._.listener); } this._.stage = this._.engine.init(this.container); this._.stage.style.cssText += 'position:relative;pointer-events:none;'; this.resize(); this.container.appendChild(this._.stage); this._.space = {}; resetSpace(this._.space); if (!this.media || !this.media.paused) { seek.call(this); play.call(this); } return this; } /* eslint-disable no-invalid-this */ function destroy() { if (!this.container) { return this; } pause.call(this); this.clear(); this.container.removeChild(this._.stage); if (this.media) { unbindEvents.call(this, this._.listener); } for (var key in this) { /* istanbul ignore else */ if (Object.prototype.hasOwnProperty.call(this, key)) { this[key] = null; } } return this; } var properties = ['mode', 'time', 'text', 'render', 'style']; /* eslint-disable no-invalid-this */ function emit(obj) { if (!obj || Object.prototype.toString.call(obj) !== '[object Object]') { return this; } var cmt = {}; for (var i = 0; i < properties.length; i++) { if (obj[properties[i]] !== undefined) { cmt[properties[i]] = obj[properties[i]]; } } cmt.text = (cmt.text || '').toString(); cmt.mode = formatMode(cmt.mode); cmt._utc = Date.now() / 1000; if (this.media) { var position = 0; if (cmt.time === undefined) { cmt.time = this.media.currentTime; position = this._.position; } else { position = binsearch(this.comments, 'time', cmt.time); if (position < this._.position) { this._.position += 1; } } this.comments.splice(position, 0, cmt); } else { this.comments.push(cmt); } return this; } /* eslint-disable no-invalid-this */ function show() { if (this._.visible) { return this; } this._.visible = true; if (this.media && this.media.paused) { return this; } seek.call(this); play.call(this); return this; } /* eslint-disable no-invalid-this */ function hide() { if (!this._.visible) { return this; } pause.call(this); this.clear(); this._.visible = false; return this; } /* eslint-disable no-invalid-this */ function clear$1() { this._.engine.clear(this._.stage, this._.runningList); this._.runningList = []; return this; } /* eslint-disable no-invalid-this */ function resize$1() { this._.stage.width = this.container.offsetWidth; this._.stage.height = this.container.offsetHeight; this._.engine.resize(this._.stage); this._.duration = this._.stage.width / this._.speed; return this; } var speed = { get: function() { return this._.speed; }, set: function(s) { if (typeof s !== 'number' || isNaN(s) || !isFinite(s) || s <= 0) { return this._.speed; } this._.speed = s; if (this._.stage.width) { this._.duration = this._.stage.width / s; } return s; } }; function Danmaku(opt) { opt && init$1.call(this, opt); } Danmaku.prototype.destroy = function() { return destroy.call(this); }; Danmaku.prototype.emit = function(cmt) { return emit.call(this, cmt); }; Danmaku.prototype.show = function() { return show.call(this); }; Danmaku.prototype.hide = function() { return hide.call(this); }; Danmaku.prototype.clear = function() { return clear$1.call(this); }; Danmaku.prototype.resize = function() { return resize$1.call(this); }; Object.defineProperty(Danmaku.prototype, 'speed', speed); export default Danmaku;
{ for (var i = 0; i < this._.runningList.length; i++) { var cmt = this._.runningList[i]; cmt._utc = Date.now() / 1000 - (this.media.currentTime - cmt.time); } }
conditional_block
danmaku.dom.js
var transform = (function() { var properties = [ 'oTransform', // Opera 11.5 'msTransform', // IE 9 'mozTransform', 'webkitTransform', 'transform' ]; var style = document.createElement('div').style; for (var i = 0; i < properties.length; i++) { /* istanbul ignore else */ if (properties[i] in style) { return properties[i]; } } /* istanbul ignore next */ return 'transform'; }()); function createCommentNode(cmt) { var node = document.createElement('div'); node.style.cssText = 'position:absolute;'; if (typeof cmt.render === 'function') { var $el = cmt.render(); if ($el instanceof HTMLElement) { node.appendChild($el); return node; } } node.textContent = cmt.text; if (cmt.style) { for (var key in cmt.style) { node.style[key] = cmt.style[key]; } } return node; } function init() { var stage = document.createElement('div'); stage.style.cssText = 'overflow:hidden;white-space:nowrap;transform:translateZ(0);'; return stage; } function clear(stage) { var lc = stage.lastChild; while (lc) { stage.removeChild(lc); lc = stage.lastChild; } } function resize(stage) { stage.style.width = stage.width + 'px'; stage.style.height = stage.height + 'px'; } function framing() { // } function setup(stage, comments) { var df = document.createDocumentFragment(); var i = 0; var cmt = null; for (i = 0; i < comments.length; i++) { cmt = comments[i]; cmt.node = cmt.node || createCommentNode(cmt); df.appendChild(cmt.node); } if (comments.length) { stage.appendChild(df); } for (i = 0; i < comments.length; i++) { cmt = comments[i]; cmt.width = cmt.width || cmt.node.offsetWidth; cmt.height = cmt.height || cmt.node.offsetHeight; } } function render(stage, cmt) { cmt.node.style[transform] = 'translate(' + cmt.x + 'px,' + cmt.y + 'px)'; } /* eslint no-invalid-this: 0 */ function remove(stage, cmt) { stage.removeChild(cmt.node); /* istanbul ignore else */ if (!this.media) { cmt.node = null; } } var domEngine = { name: 'dom', init: init, clear: clear, resize: resize, framing: framing, setup: setup, render: render, remove: remove, }; /* eslint no-invalid-this: 0 */ function allocate(cmt) { var that = this; var ct = this.media ? this.media.currentTime : Date.now() / 1000; var pbr = this.media ? this.media.playbackRate : 1; function willCollide(cr, cmt) { if (cmt.mode === 'top' || cmt.mode === 'bottom') { return ct - cr.time < that._.duration; } var crTotalWidth = that._.stage.width + cr.width; var crElapsed = crTotalWidth * (ct - cr.time) * pbr / that._.duration; if (cr.width > crElapsed) { return true; } // (rtl mode) the right end of `cr` move out of left side of stage var crLeftTime = that._.duration + cr.time - ct; var cmtTotalWidth = that._.stage.width + cmt.width; var cmtTime = that.media ? cmt.time : cmt._utc; var cmtElapsed = cmtTotalWidth * (ct - cmtTime) * pbr / that._.duration; var cmtArrival = that._.stage.width - cmtElapsed; // (rtl mode) the left end of `cmt` reach the left side of stage var cmtArrivalTime = that._.duration * cmtArrival / (that._.stage.width + cmt.width); return crLeftTime > cmtArrivalTime; } var crs = this._.space[cmt.mode]; var last = 0; var curr = 0; for (var i = 1; i < crs.length; i++) { var cr = crs[i]; var requiredRange = cmt.height; if (cmt.mode === 'top' || cmt.mode === 'bottom') { requiredRange += cr.height; } if (cr.range - cr.height - crs[last].range >= requiredRange) { curr = i; break; } if (willCollide(cr, cmt)) { last = i; } } var channel = crs[last].range; var crObj = { range: channel + cmt.height, time: this.media ? cmt.time : cmt._utc, width: cmt.width, height: cmt.height }; crs.splice(last + 1, curr - last - 1, crObj); if (cmt.mode === 'bottom') { return this._.stage.height - cmt.height - channel % this._.stage.height; } return channel % (this._.stage.height - cmt.height); } /* eslint no-invalid-this: 0 */ function createEngine(framing, setup, render, remove) { return function() { framing(this._.stage); var dn = Date.now() / 1000; var ct = this.media ? this.media.currentTime : dn; var pbr = this.media ? this.media.playbackRate : 1; var cmt = null; var cmtt = 0; var i = 0; for (i = this._.runningList.length - 1; i >= 0; i--) { cmt = this._.runningList[i]; cmtt = this.media ? cmt.time : cmt._utc; if (ct - cmtt > this._.duration) { remove(this._.stage, cmt); this._.runningList.splice(i, 1); } } var pendingList = []; while (this._.position < this.comments.length) { cmt = this.comments[this._.position]; cmtt = this.media ? cmt.time : cmt._utc; if (cmtt >= ct) { break; } // when clicking controls to seek, media.currentTime may changed before // `pause` event is fired, so here skips comments out of duration, // see https://github.com/weizhenye/Danmaku/pull/30 for details. if (ct - cmtt > this._.duration) { ++this._.position; continue; } if (this.media) { cmt._utc = dn - (this.media.currentTime - cmt.time); } pendingList.push(cmt); ++this._.position; } setup(this._.stage, pendingList); for (i = 0; i < pendingList.length; i++) { cmt = pendingList[i]; cmt.y = allocate.call(this, cmt); if (cmt.mode === 'top' || cmt.mode === 'bottom') { cmt.x = (this._.stage.width - cmt.width) >> 1; } this._.runningList.push(cmt); } for (i = 0; i < this._.runningList.length; i++) { cmt = this._.runningList[i]; var totalWidth = this._.stage.width + cmt.width; var elapsed = totalWidth * (dn - cmt._utc) * pbr / this._.duration; if (cmt.mode === 'ltr') cmt.x = (elapsed - cmt.width + .5) | 0; if (cmt.mode === 'rtl') cmt.x = (this._.stage.width - elapsed + .5) | 0; render(this._.stage, cmt); } }; } var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function(cb) { return setTimeout(cb, 50 / 3); }; var caf = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || clearTimeout; function binsearch(arr, prop, key) { var mid = 0; var left = 0; var right = arr.length; while (left < right - 1) { mid = (left + right) >> 1; if (key >= arr[mid][prop]) { left = mid; } else { right = mid; } } if (arr[left] && key < arr[left][prop]) { return left; } return right; } function formatMode(mode) { if (!/^(ltr|top|bottom)$/i.test(mode)) { return 'rtl'; } return mode.toLowerCase(); } function collidableRange() { var max = 9007199254740991; return [ { range: 0, time: -max, width: max, height: 0 }, { range: max, time: max, width: 0, height: 0 } ]; } function resetSpace(space) { space.ltr = collidableRange(); space.rtl = collidableRange(); space.top = collidableRange(); space.bottom = collidableRange(); } /* eslint no-invalid-this: 0 */ function play() { if (!this._.visible || !this._.paused) { return this; } this._.paused = false; if (this.media) { for (var i = 0; i < this._.runningList.length; i++) { var cmt = this._.runningList[i]; cmt._utc = Date.now() / 1000 - (this.media.currentTime - cmt.time); } } var that = this; var engine = createEngine( this._.engine.framing.bind(this), this._.engine.setup.bind(this), this._.engine.render.bind(this), this._.engine.remove.bind(this) ); function frame() { engine.call(that); that._.requestID = raf(frame); } this._.requestID = raf(frame); return this; } /* eslint no-invalid-this: 0 */ function pause() { if (!this._.visible || this._.paused) { return this; } this._.paused = true; caf(this._.requestID); this._.requestID = 0; return this; } /* eslint no-invalid-this: 0 */ function seek() { if (!this.media) { return this; } this.clear(); resetSpace(this._.space); var position = binsearch(this.comments, 'time', this.media.currentTime); this._.position = Math.max(0, position - 1); return this; } /* eslint no-invalid-this: 0 */ function bindEvents(_) { _.play = play.bind(this); _.pause = pause.bind(this); _.seeking = seek.bind(this); this.media.addEventListener('play', _.play); this.media.addEventListener('pause', _.pause); this.media.addEventListener('playing', _.play); this.media.addEventListener('waiting', _.pause); this.media.addEventListener('seeking', _.seeking); } /* eslint no-invalid-this: 0 */ function unbindEvents(_) { this.media.removeEventListener('play', _.play); this.media.removeEventListener('pause', _.pause); this.media.removeEventListener('playing', _.play); this.media.removeEventListener('waiting', _.pause); this.media.removeEventListener('seeking', _.seeking); _.play = null; _.pause = null; _.seeking = null; } /* eslint-disable no-invalid-this */ function init$1(opt) { this._ = {}; this.container = opt.container || document.createElement('div'); this.media = opt.media; this._.visible = true; /* eslint-disable no-undef */ /* istanbul ignore next */ { this.engine = 'dom'; this._.engine = domEngine; } /* eslint-enable no-undef */ this._.requestID = 0; this._.speed = Math.max(0, opt.speed) || 144; this._.duration = 4; this.comments = opt.comments || []; this.comments.sort(function(a, b) { return a.time - b.time; }); for (var i = 0; i < this.comments.length; i++) { this.comments[i].mode = formatMode(this.comments[i].mode); } this._.runningList = []; this._.position = 0; this._.paused = true; if (this.media) { this._.listener = {}; bindEvents.call(this, this._.listener); } this._.stage = this._.engine.init(this.container); this._.stage.style.cssText += 'position:relative;pointer-events:none;'; this.resize(); this.container.appendChild(this._.stage); this._.space = {}; resetSpace(this._.space); if (!this.media || !this.media.paused) { seek.call(this); play.call(this); } return this; } /* eslint-disable no-invalid-this */ function destroy() { if (!this.container) { return this; } pause.call(this); this.clear(); this.container.removeChild(this._.stage); if (this.media) { unbindEvents.call(this, this._.listener); } for (var key in this) { /* istanbul ignore else */ if (Object.prototype.hasOwnProperty.call(this, key)) { this[key] = null; } } return this; } var properties = ['mode', 'time', 'text', 'render', 'style']; /* eslint-disable no-invalid-this */ function emit(obj) { if (!obj || Object.prototype.toString.call(obj) !== '[object Object]') { return this; } var cmt = {}; for (var i = 0; i < properties.length; i++) { if (obj[properties[i]] !== undefined) { cmt[properties[i]] = obj[properties[i]]; } } cmt.text = (cmt.text || '').toString(); cmt.mode = formatMode(cmt.mode); cmt._utc = Date.now() / 1000; if (this.media) { var position = 0; if (cmt.time === undefined) { cmt.time = this.media.currentTime; position = this._.position; } else { position = binsearch(this.comments, 'time', cmt.time); if (position < this._.position) { this._.position += 1; } } this.comments.splice(position, 0, cmt); } else { this.comments.push(cmt); } return this; } /* eslint-disable no-invalid-this */ function show() { if (this._.visible) { return this; } this._.visible = true; if (this.media && this.media.paused) { return this; } seek.call(this); play.call(this); return this; } /* eslint-disable no-invalid-this */ function hide() { if (!this._.visible) { return this; } pause.call(this); this.clear(); this._.visible = false; return this; } /* eslint-disable no-invalid-this */ function clear$1()
/* eslint-disable no-invalid-this */ function resize$1() { this._.stage.width = this.container.offsetWidth; this._.stage.height = this.container.offsetHeight; this._.engine.resize(this._.stage); this._.duration = this._.stage.width / this._.speed; return this; } var speed = { get: function() { return this._.speed; }, set: function(s) { if (typeof s !== 'number' || isNaN(s) || !isFinite(s) || s <= 0) { return this._.speed; } this._.speed = s; if (this._.stage.width) { this._.duration = this._.stage.width / s; } return s; } }; function Danmaku(opt) { opt && init$1.call(this, opt); } Danmaku.prototype.destroy = function() { return destroy.call(this); }; Danmaku.prototype.emit = function(cmt) { return emit.call(this, cmt); }; Danmaku.prototype.show = function() { return show.call(this); }; Danmaku.prototype.hide = function() { return hide.call(this); }; Danmaku.prototype.clear = function() { return clear$1.call(this); }; Danmaku.prototype.resize = function() { return resize$1.call(this); }; Object.defineProperty(Danmaku.prototype, 'speed', speed); export default Danmaku;
{ this._.engine.clear(this._.stage, this._.runningList); this._.runningList = []; return this; }
identifier_body
navigation.component.ts
import { Component, AfterViewInit, Input } from '@angular/core'; import { User } from '../../models'; import { AuthenticationService, AlertService } from '../../services'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'nav-menu', template: require('./navigation.component.html') }) export class NavigationComponent { @Input() isActive: boolean = false; showMenu: boolean = false; showForgotPassword: boolean = false; showSignIn: boolean = false; showLogIn: boolean = false; user: User = null; constructor(private authService: AuthenticationService, private route: ActivatedRoute) { this.user = this.authService.getLoggedInUser(); this.route.queryParams.subscribe( (queryParam: any) => { if(queryParam['showLogin']){ this.showLogIn = true; } }); // this.route.queryParams.subscribe(x=>) } toggleMenu(){ if(this.showSignIn){ this.showSignIn = !this.showSignIn; } else if(this.showLogIn){ this.showLogIn = !this.showLogIn; } else if(this.showForgotPassword){ this.showForgotPassword = !this.showForgotPassword; } else { this.showMenu = !this.showMenu; } } toggleSignIn(){ this.showSignIn = !this.showSignIn; } toggleLogIn(){ this.showLogIn = !this.showLogIn;
this.showForgotPassword = true; this.showLogIn = false; this.showSignIn = false; } showSignUp(){ this.showSignIn = true; this.showForgotPassword = false; this.showLogIn = false; } closeForgot(){ this.showForgotPassword = false; } closeLogin(){ this.showLogIn = false; } closeSignup(){ this.user = this.authService.getLoggedInUser(); this.showSignIn = false; } }
} showForgot(){
random_line_split
navigation.component.ts
import { Component, AfterViewInit, Input } from '@angular/core'; import { User } from '../../models'; import { AuthenticationService, AlertService } from '../../services'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'nav-menu', template: require('./navigation.component.html') }) export class NavigationComponent { @Input() isActive: boolean = false; showMenu: boolean = false; showForgotPassword: boolean = false; showSignIn: boolean = false; showLogIn: boolean = false; user: User = null; constructor(private authService: AuthenticationService, private route: ActivatedRoute) { this.user = this.authService.getLoggedInUser(); this.route.queryParams.subscribe( (queryParam: any) => { if(queryParam['showLogin']){ this.showLogIn = true; } }); // this.route.queryParams.subscribe(x=>) } toggleMenu(){ if(this.showSignIn){ this.showSignIn = !this.showSignIn; } else if(this.showLogIn){ this.showLogIn = !this.showLogIn; } else if(this.showForgotPassword){ this.showForgotPassword = !this.showForgotPassword; } else { this.showMenu = !this.showMenu; } } toggleSignIn(){ this.showSignIn = !this.showSignIn; } toggleLogIn(){ this.showLogIn = !this.showLogIn; }
(){ this.showForgotPassword = true; this.showLogIn = false; this.showSignIn = false; } showSignUp(){ this.showSignIn = true; this.showForgotPassword = false; this.showLogIn = false; } closeForgot(){ this.showForgotPassword = false; } closeLogin(){ this.showLogIn = false; } closeSignup(){ this.user = this.authService.getLoggedInUser(); this.showSignIn = false; } }
showForgot
identifier_name
navigation.component.ts
import { Component, AfterViewInit, Input } from '@angular/core'; import { User } from '../../models'; import { AuthenticationService, AlertService } from '../../services'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'nav-menu', template: require('./navigation.component.html') }) export class NavigationComponent { @Input() isActive: boolean = false; showMenu: boolean = false; showForgotPassword: boolean = false; showSignIn: boolean = false; showLogIn: boolean = false; user: User = null; constructor(private authService: AuthenticationService, private route: ActivatedRoute) { this.user = this.authService.getLoggedInUser(); this.route.queryParams.subscribe( (queryParam: any) => { if(queryParam['showLogin']){ this.showLogIn = true; } }); // this.route.queryParams.subscribe(x=>) } toggleMenu(){ if(this.showSignIn){ this.showSignIn = !this.showSignIn; } else if(this.showLogIn){ this.showLogIn = !this.showLogIn; } else if(this.showForgotPassword){ this.showForgotPassword = !this.showForgotPassword; } else { this.showMenu = !this.showMenu; } } toggleSignIn(){ this.showSignIn = !this.showSignIn; } toggleLogIn(){ this.showLogIn = !this.showLogIn; } showForgot()
showSignUp(){ this.showSignIn = true; this.showForgotPassword = false; this.showLogIn = false; } closeForgot(){ this.showForgotPassword = false; } closeLogin(){ this.showLogIn = false; } closeSignup(){ this.user = this.authService.getLoggedInUser(); this.showSignIn = false; } }
{ this.showForgotPassword = true; this.showLogIn = false; this.showSignIn = false; }
identifier_body
account_config.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 Andrea Cometa. # Email: info@andreacometa.it # Web site: http://www.andreacometa.it # Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>) # Copyright (C) 2012 Domsense srl (<http://www.domsense.com>) # Copyright (C) 2012 Associazione OpenERP Italia # (<http://www.odoo-italia.org>). # # 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 class AccountConfigSettings(models.TransientModel): _inherit = 'account.config.settings' due_cost_service_id = fields.Many2one( related='company_id.due_cost_service_id', help='Default Service for RiBa Due Cost (collection fees) on invoice', domain=[('type', '=', 'service')]) def default_get(self, cr, uid, fields, context=None):
class ResCompany(models.Model): _inherit = 'res.company' due_cost_service_id = fields.Many2one('product.product')
res = super(AccountConfigSettings, self).default_get( cr, uid, fields, context) if res: user = self.pool['res.users'].browse(cr, uid, uid, context) res['due_cost_service_id'] = user.company_id.due_cost_service_id.id return res
identifier_body
account_config.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 Andrea Cometa. # Email: info@andreacometa.it # Web site: http://www.andreacometa.it # Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>) # Copyright (C) 2012 Domsense srl (<http://www.domsense.com>) # Copyright (C) 2012 Associazione OpenERP Italia # (<http://www.odoo-italia.org>). # # 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 class AccountConfigSettings(models.TransientModel): _inherit = 'account.config.settings' due_cost_service_id = fields.Many2one( related='company_id.due_cost_service_id', help='Default Service for RiBa Due Cost (collection fees) on invoice', domain=[('type', '=', 'service')]) def default_get(self, cr, uid, fields, context=None): res = super(AccountConfigSettings, self).default_get( cr, uid, fields, context) if res:
return res class ResCompany(models.Model): _inherit = 'res.company' due_cost_service_id = fields.Many2one('product.product')
user = self.pool['res.users'].browse(cr, uid, uid, context) res['due_cost_service_id'] = user.company_id.due_cost_service_id.id
conditional_block
account_config.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 Andrea Cometa. # Email: info@andreacometa.it # Web site: http://www.andreacometa.it # Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>) # Copyright (C) 2012 Domsense srl (<http://www.domsense.com>) # Copyright (C) 2012 Associazione OpenERP Italia # (<http://www.odoo-italia.org>). # # 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 class
(models.TransientModel): _inherit = 'account.config.settings' due_cost_service_id = fields.Many2one( related='company_id.due_cost_service_id', help='Default Service for RiBa Due Cost (collection fees) on invoice', domain=[('type', '=', 'service')]) def default_get(self, cr, uid, fields, context=None): res = super(AccountConfigSettings, self).default_get( cr, uid, fields, context) if res: user = self.pool['res.users'].browse(cr, uid, uid, context) res['due_cost_service_id'] = user.company_id.due_cost_service_id.id return res class ResCompany(models.Model): _inherit = 'res.company' due_cost_service_id = fields.Many2one('product.product')
AccountConfigSettings
identifier_name
account_config.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 Andrea Cometa. # Email: info@andreacometa.it # Web site: http://www.andreacometa.it # Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>) # Copyright (C) 2012 Domsense srl (<http://www.domsense.com>) # Copyright (C) 2012 Associazione OpenERP Italia # (<http://www.odoo-italia.org>). # # This program is free software: you can redistribute it and/or modify
# (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 class AccountConfigSettings(models.TransientModel): _inherit = 'account.config.settings' due_cost_service_id = fields.Many2one( related='company_id.due_cost_service_id', help='Default Service for RiBa Due Cost (collection fees) on invoice', domain=[('type', '=', 'service')]) def default_get(self, cr, uid, fields, context=None): res = super(AccountConfigSettings, self).default_get( cr, uid, fields, context) if res: user = self.pool['res.users'].browse(cr, uid, uid, context) res['due_cost_service_id'] = user.company_id.due_cost_service_id.id return res class ResCompany(models.Model): _inherit = 'res.company' due_cost_service_id = fields.Many2one('product.product')
# 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
random_line_split
Reflector.js
console.warn( "THREE.Reflector: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/index.html#manual/en/introduction/Import-via-modules." ); /** * @author Slayvin / http://slayvin.net */ THREE.Reflector = function ( geometry, options ) { THREE.Mesh.call( this, geometry ); this.type = 'Reflector'; var scope = this; options = options || {}; var color = ( options.color !== undefined ) ? new THREE.Color( options.color ) : new THREE.Color( 0x7F7F7F ); var textureWidth = options.textureWidth || 512; var textureHeight = options.textureHeight || 512; var clipBias = options.clipBias || 0; var shader = options.shader || THREE.Reflector.ReflectorShader; // var reflectorPlane = new THREE.Plane(); var normal = new THREE.Vector3(); var reflectorWorldPosition = new THREE.Vector3(); var cameraWorldPosition = new THREE.Vector3(); var rotationMatrix = new THREE.Matrix4(); var lookAtPosition = new THREE.Vector3( 0, 0, - 1 ); var clipPlane = new THREE.Vector4(); var view = new THREE.Vector3(); var target = new THREE.Vector3(); var q = new THREE.Vector4(); var textureMatrix = new THREE.Matrix4(); var virtualCamera = new THREE.PerspectiveCamera(); var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false }; var renderTarget = new THREE.WebGLRenderTarget( textureWidth, textureHeight, parameters ); if ( ! THREE.MathUtils.isPowerOfTwo( textureWidth ) || ! THREE.MathUtils.isPowerOfTwo( textureHeight ) )
var material = new THREE.ShaderMaterial( { uniforms: THREE.UniformsUtils.clone( shader.uniforms ), fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader } ); material.uniforms[ "tDiffuse" ].value = renderTarget.texture; material.uniforms[ "color" ].value = color; material.uniforms[ "textureMatrix" ].value = textureMatrix; this.material = material; this.onBeforeRender = function ( renderer, scene, camera ) { reflectorWorldPosition.setFromMatrixPosition( scope.matrixWorld ); cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld ); rotationMatrix.extractRotation( scope.matrixWorld ); normal.set( 0, 0, 1 ); normal.applyMatrix4( rotationMatrix ); view.subVectors( reflectorWorldPosition, cameraWorldPosition ); // Avoid rendering when reflector is facing away if ( view.dot( normal ) > 0 ) return; view.reflect( normal ).negate(); view.add( reflectorWorldPosition ); rotationMatrix.extractRotation( camera.matrixWorld ); lookAtPosition.set( 0, 0, - 1 ); lookAtPosition.applyMatrix4( rotationMatrix ); lookAtPosition.add( cameraWorldPosition ); target.subVectors( reflectorWorldPosition, lookAtPosition ); target.reflect( normal ).negate(); target.add( reflectorWorldPosition ); virtualCamera.position.copy( view ); virtualCamera.up.set( 0, 1, 0 ); virtualCamera.up.applyMatrix4( rotationMatrix ); virtualCamera.up.reflect( normal ); virtualCamera.lookAt( target ); virtualCamera.far = camera.far; // Used in WebGLBackground virtualCamera.updateMatrixWorld(); virtualCamera.projectionMatrix.copy( camera.projectionMatrix ); // Update the texture matrix textureMatrix.set( 0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0 ); textureMatrix.multiply( virtualCamera.projectionMatrix ); textureMatrix.multiply( virtualCamera.matrixWorldInverse ); textureMatrix.multiply( scope.matrixWorld ); // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf reflectorPlane.setFromNormalAndCoplanarPoint( normal, reflectorWorldPosition ); reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse ); clipPlane.set( reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant ); var projectionMatrix = virtualCamera.projectionMatrix; q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ]; q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ]; q.z = - 1.0; q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ]; // Calculate the scaled plane vector clipPlane.multiplyScalar( 2.0 / clipPlane.dot( q ) ); // Replacing the third row of the projection matrix projectionMatrix.elements[ 2 ] = clipPlane.x; projectionMatrix.elements[ 6 ] = clipPlane.y; projectionMatrix.elements[ 10 ] = clipPlane.z + 1.0 - clipBias; projectionMatrix.elements[ 14 ] = clipPlane.w; // Render renderTarget.texture.encoding = renderer.outputEncoding; scope.visible = false; var currentRenderTarget = renderer.getRenderTarget(); var currentXrEnabled = renderer.xr.enabled; var currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; renderer.xr.enabled = false; // Avoid camera modification renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows renderer.setRenderTarget( renderTarget ); renderer.state.buffers.depth.setMask( true ); // make sure the depth buffer is writable so it can be properly cleared, see #18897 if ( renderer.autoClear === false ) renderer.clear(); renderer.render( scene, virtualCamera ); renderer.xr.enabled = currentXrEnabled; renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; renderer.setRenderTarget( currentRenderTarget ); // Restore viewport var viewport = camera.viewport; if ( viewport !== undefined ) { renderer.state.viewport( viewport ); } scope.visible = true; }; this.getRenderTarget = function () { return renderTarget; }; }; THREE.Reflector.prototype = Object.create( THREE.Mesh.prototype ); THREE.Reflector.prototype.constructor = THREE.Reflector; THREE.Reflector.ReflectorShader = { uniforms: { 'color': { value: null }, 'tDiffuse': { value: null }, 'textureMatrix': { value: null } }, vertexShader: [ 'uniform mat4 textureMatrix;', 'varying vec4 vUv;', 'void main() {', ' vUv = textureMatrix * vec4( position, 1.0 );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}' ].join( '\n' ), fragmentShader: [ 'uniform vec3 color;', 'uniform sampler2D tDiffuse;', 'varying vec4 vUv;', 'float blendOverlay( float base, float blend ) {', ' return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );', '}', 'vec3 blendOverlay( vec3 base, vec3 blend ) {', ' return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );', '}', 'void main() {', ' vec4 base = texture2DProj( tDiffuse, vUv );', ' gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );', '}' ].join( '\n' ) };
{ renderTarget.texture.generateMipmaps = false; }
conditional_block
Reflector.js
console.warn( "THREE.Reflector: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/index.html#manual/en/introduction/Import-via-modules." ); /** * @author Slayvin / http://slayvin.net */ THREE.Reflector = function ( geometry, options ) { THREE.Mesh.call( this, geometry ); this.type = 'Reflector'; var scope = this; options = options || {}; var color = ( options.color !== undefined ) ? new THREE.Color( options.color ) : new THREE.Color( 0x7F7F7F ); var textureWidth = options.textureWidth || 512; var textureHeight = options.textureHeight || 512; var clipBias = options.clipBias || 0; var shader = options.shader || THREE.Reflector.ReflectorShader; // var reflectorPlane = new THREE.Plane(); var normal = new THREE.Vector3(); var reflectorWorldPosition = new THREE.Vector3(); var cameraWorldPosition = new THREE.Vector3(); var rotationMatrix = new THREE.Matrix4(); var lookAtPosition = new THREE.Vector3( 0, 0, - 1 ); var clipPlane = new THREE.Vector4(); var view = new THREE.Vector3(); var target = new THREE.Vector3(); var q = new THREE.Vector4(); var textureMatrix = new THREE.Matrix4(); var virtualCamera = new THREE.PerspectiveCamera(); var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false }; var renderTarget = new THREE.WebGLRenderTarget( textureWidth, textureHeight, parameters ); if ( ! THREE.MathUtils.isPowerOfTwo( textureWidth ) || ! THREE.MathUtils.isPowerOfTwo( textureHeight ) ) { renderTarget.texture.generateMipmaps = false; } var material = new THREE.ShaderMaterial( { uniforms: THREE.UniformsUtils.clone( shader.uniforms ), fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader } ); material.uniforms[ "tDiffuse" ].value = renderTarget.texture; material.uniforms[ "color" ].value = color; material.uniforms[ "textureMatrix" ].value = textureMatrix; this.material = material; this.onBeforeRender = function ( renderer, scene, camera ) { reflectorWorldPosition.setFromMatrixPosition( scope.matrixWorld ); cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld ); rotationMatrix.extractRotation( scope.matrixWorld ); normal.set( 0, 0, 1 ); normal.applyMatrix4( rotationMatrix ); view.subVectors( reflectorWorldPosition, cameraWorldPosition ); // Avoid rendering when reflector is facing away
view.reflect( normal ).negate(); view.add( reflectorWorldPosition ); rotationMatrix.extractRotation( camera.matrixWorld ); lookAtPosition.set( 0, 0, - 1 ); lookAtPosition.applyMatrix4( rotationMatrix ); lookAtPosition.add( cameraWorldPosition ); target.subVectors( reflectorWorldPosition, lookAtPosition ); target.reflect( normal ).negate(); target.add( reflectorWorldPosition ); virtualCamera.position.copy( view ); virtualCamera.up.set( 0, 1, 0 ); virtualCamera.up.applyMatrix4( rotationMatrix ); virtualCamera.up.reflect( normal ); virtualCamera.lookAt( target ); virtualCamera.far = camera.far; // Used in WebGLBackground virtualCamera.updateMatrixWorld(); virtualCamera.projectionMatrix.copy( camera.projectionMatrix ); // Update the texture matrix textureMatrix.set( 0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0 ); textureMatrix.multiply( virtualCamera.projectionMatrix ); textureMatrix.multiply( virtualCamera.matrixWorldInverse ); textureMatrix.multiply( scope.matrixWorld ); // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf reflectorPlane.setFromNormalAndCoplanarPoint( normal, reflectorWorldPosition ); reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse ); clipPlane.set( reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant ); var projectionMatrix = virtualCamera.projectionMatrix; q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ]; q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ]; q.z = - 1.0; q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ]; // Calculate the scaled plane vector clipPlane.multiplyScalar( 2.0 / clipPlane.dot( q ) ); // Replacing the third row of the projection matrix projectionMatrix.elements[ 2 ] = clipPlane.x; projectionMatrix.elements[ 6 ] = clipPlane.y; projectionMatrix.elements[ 10 ] = clipPlane.z + 1.0 - clipBias; projectionMatrix.elements[ 14 ] = clipPlane.w; // Render renderTarget.texture.encoding = renderer.outputEncoding; scope.visible = false; var currentRenderTarget = renderer.getRenderTarget(); var currentXrEnabled = renderer.xr.enabled; var currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; renderer.xr.enabled = false; // Avoid camera modification renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows renderer.setRenderTarget( renderTarget ); renderer.state.buffers.depth.setMask( true ); // make sure the depth buffer is writable so it can be properly cleared, see #18897 if ( renderer.autoClear === false ) renderer.clear(); renderer.render( scene, virtualCamera ); renderer.xr.enabled = currentXrEnabled; renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; renderer.setRenderTarget( currentRenderTarget ); // Restore viewport var viewport = camera.viewport; if ( viewport !== undefined ) { renderer.state.viewport( viewport ); } scope.visible = true; }; this.getRenderTarget = function () { return renderTarget; }; }; THREE.Reflector.prototype = Object.create( THREE.Mesh.prototype ); THREE.Reflector.prototype.constructor = THREE.Reflector; THREE.Reflector.ReflectorShader = { uniforms: { 'color': { value: null }, 'tDiffuse': { value: null }, 'textureMatrix': { value: null } }, vertexShader: [ 'uniform mat4 textureMatrix;', 'varying vec4 vUv;', 'void main() {', ' vUv = textureMatrix * vec4( position, 1.0 );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}' ].join( '\n' ), fragmentShader: [ 'uniform vec3 color;', 'uniform sampler2D tDiffuse;', 'varying vec4 vUv;', 'float blendOverlay( float base, float blend ) {', ' return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );', '}', 'vec3 blendOverlay( vec3 base, vec3 blend ) {', ' return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );', '}', 'void main() {', ' vec4 base = texture2DProj( tDiffuse, vUv );', ' gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );', '}' ].join( '\n' ) };
if ( view.dot( normal ) > 0 ) return;
random_line_split
pragma.rs
use std::fmt; use std::ascii::AsciiExt; use header::{Header, Raw, parsing}; /// The `Pragma` header defined by HTTP/1.0. /// /// > The "Pragma" header field allows backwards compatibility with /// > HTTP/1.0 caches, so that clients can specify a "no-cache" request /// > that they will understand (as Cache-Control was not defined until /// > HTTP/1.1). When the Cache-Control header field is also present and /// > understood in a request, Pragma is ignored. /// > In HTTP/1.0, Pragma was defined as an extensible field for /// > implementation-specified directives for recipients. This /// > specification deprecates such extensions to improve interoperability. /// /// Spec: https://tools.ietf.org/html/rfc7234#section-5.4 /// /// # Examples /// ``` /// use hyper::header::{Headers, Pragma}; /// /// let mut headers = Headers::new(); /// headers.set(Pragma::NoCache); /// ``` /// ``` /// use hyper::header::{Headers, Pragma}; /// /// let mut headers = Headers::new(); /// headers.set(Pragma::Ext("foobar".to_owned())); /// ``` #[derive(Clone, PartialEq, Debug)] pub enum Pragma { /// Corresponds to the `no-cache` value. NoCache, /// Every value other than `no-cache`. Ext(String), } impl Header for Pragma { fn header_name() -> &'static str { static NAME: &'static str = "Pragma"; NAME } fn parse_header(raw: &Raw) -> ::Result<Pragma> { parsing::from_one_raw_str(raw).and_then(|s: String| { let slice = &s.to_ascii_lowercase()[..]; match slice { "no-cache" => Ok(Pragma::NoCache), _ => Ok(Pragma::Ext(s)), } }) }
}) } } #[test] fn test_parse_header() { let a: Pragma = Header::parse_header(&"no-cache".into()).unwrap(); let b = Pragma::NoCache; assert_eq!(a, b); let c: Pragma = Header::parse_header(&"FoObar".into()).unwrap(); let d = Pragma::Ext("FoObar".to_owned()); assert_eq!(c, d); let e: ::Result<Pragma> = Header::parse_header(&"".into()); assert_eq!(e.ok(), None); }
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { Pragma::NoCache => "no-cache", Pragma::Ext(ref string) => &string[..],
random_line_split
pragma.rs
use std::fmt; use std::ascii::AsciiExt; use header::{Header, Raw, parsing}; /// The `Pragma` header defined by HTTP/1.0. /// /// > The "Pragma" header field allows backwards compatibility with /// > HTTP/1.0 caches, so that clients can specify a "no-cache" request /// > that they will understand (as Cache-Control was not defined until /// > HTTP/1.1). When the Cache-Control header field is also present and /// > understood in a request, Pragma is ignored. /// > In HTTP/1.0, Pragma was defined as an extensible field for /// > implementation-specified directives for recipients. This /// > specification deprecates such extensions to improve interoperability. /// /// Spec: https://tools.ietf.org/html/rfc7234#section-5.4 /// /// # Examples /// ``` /// use hyper::header::{Headers, Pragma}; /// /// let mut headers = Headers::new(); /// headers.set(Pragma::NoCache); /// ``` /// ``` /// use hyper::header::{Headers, Pragma}; /// /// let mut headers = Headers::new(); /// headers.set(Pragma::Ext("foobar".to_owned())); /// ``` #[derive(Clone, PartialEq, Debug)] pub enum Pragma { /// Corresponds to the `no-cache` value. NoCache, /// Every value other than `no-cache`. Ext(String), } impl Header for Pragma { fn header_name() -> &'static str { static NAME: &'static str = "Pragma"; NAME } fn parse_header(raw: &Raw) -> ::Result<Pragma> { parsing::from_one_raw_str(raw).and_then(|s: String| { let slice = &s.to_ascii_lowercase()[..]; match slice { "no-cache" => Ok(Pragma::NoCache), _ => Ok(Pragma::Ext(s)), } }) } fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result
} #[test] fn test_parse_header() { let a: Pragma = Header::parse_header(&"no-cache".into()).unwrap(); let b = Pragma::NoCache; assert_eq!(a, b); let c: Pragma = Header::parse_header(&"FoObar".into()).unwrap(); let d = Pragma::Ext("FoObar".to_owned()); assert_eq!(c, d); let e: ::Result<Pragma> = Header::parse_header(&"".into()); assert_eq!(e.ok(), None); }
{ f.write_str(match *self { Pragma::NoCache => "no-cache", Pragma::Ext(ref string) => &string[..], }) }
identifier_body
pragma.rs
use std::fmt; use std::ascii::AsciiExt; use header::{Header, Raw, parsing}; /// The `Pragma` header defined by HTTP/1.0. /// /// > The "Pragma" header field allows backwards compatibility with /// > HTTP/1.0 caches, so that clients can specify a "no-cache" request /// > that they will understand (as Cache-Control was not defined until /// > HTTP/1.1). When the Cache-Control header field is also present and /// > understood in a request, Pragma is ignored. /// > In HTTP/1.0, Pragma was defined as an extensible field for /// > implementation-specified directives for recipients. This /// > specification deprecates such extensions to improve interoperability. /// /// Spec: https://tools.ietf.org/html/rfc7234#section-5.4 /// /// # Examples /// ``` /// use hyper::header::{Headers, Pragma}; /// /// let mut headers = Headers::new(); /// headers.set(Pragma::NoCache); /// ``` /// ``` /// use hyper::header::{Headers, Pragma}; /// /// let mut headers = Headers::new(); /// headers.set(Pragma::Ext("foobar".to_owned())); /// ``` #[derive(Clone, PartialEq, Debug)] pub enum Pragma { /// Corresponds to the `no-cache` value. NoCache, /// Every value other than `no-cache`. Ext(String), } impl Header for Pragma { fn header_name() -> &'static str { static NAME: &'static str = "Pragma"; NAME } fn parse_header(raw: &Raw) -> ::Result<Pragma> { parsing::from_one_raw_str(raw).and_then(|s: String| { let slice = &s.to_ascii_lowercase()[..]; match slice { "no-cache" => Ok(Pragma::NoCache), _ => Ok(Pragma::Ext(s)), } }) } fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { Pragma::NoCache => "no-cache", Pragma::Ext(ref string) => &string[..], }) } } #[test] fn
() { let a: Pragma = Header::parse_header(&"no-cache".into()).unwrap(); let b = Pragma::NoCache; assert_eq!(a, b); let c: Pragma = Header::parse_header(&"FoObar".into()).unwrap(); let d = Pragma::Ext("FoObar".to_owned()); assert_eq!(c, d); let e: ::Result<Pragma> = Header::parse_header(&"".into()); assert_eq!(e.ok(), None); }
test_parse_header
identifier_name
message_dialog.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::c_char; use ffi; use glib::translate::*; use glib::object::{Cast, IsA}; use std::ptr; use ButtonsType; use DialogFlags; use MessageDialog; use MessageType; use Widget; use Window; impl MessageDialog { pub fn new<T: IsA<Window>>(parent: Option<&T>, flags: DialogFlags, type_: MessageType, buttons: ButtonsType, message: &str) -> MessageDialog { assert_initialized_main_thread!(); unsafe { let message: Stash<*const c_char, _> = message.to_glib_none(); Widget::from_glib_none( ffi::gtk_message_dialog_new(parent.map(|p| p.as_ref()).to_glib_none().0, flags.to_glib(), type_.to_glib(), buttons.to_glib(), b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>())) .unsafe_cast() } } } pub trait MessageDialogExt: 'static { fn set_secondary_markup<'a, I: Into<Option<&'a str>>>(&self, message: I); fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I); } impl<O: IsA<MessageDialog>> MessageDialogExt for O { fn set_secondary_markup<'a, I: Into<Option<&'a str>>>(&self, message: I) { let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>()) }, None => unsafe { ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to_glib_none().0, ptr::null::<c_char>()) }, } } fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I) { let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_text( self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>()) }, None => unsafe { ffi::gtk_message_dialog_format_secondary_text( self.as_ref().to_glib_none().0, ptr::null::<c_char>()) }, } }
}
random_line_split
message_dialog.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::c_char; use ffi; use glib::translate::*; use glib::object::{Cast, IsA}; use std::ptr; use ButtonsType; use DialogFlags; use MessageDialog; use MessageType; use Widget; use Window; impl MessageDialog { pub fn new<T: IsA<Window>>(parent: Option<&T>, flags: DialogFlags, type_: MessageType, buttons: ButtonsType, message: &str) -> MessageDialog { assert_initialized_main_thread!(); unsafe { let message: Stash<*const c_char, _> = message.to_glib_none(); Widget::from_glib_none( ffi::gtk_message_dialog_new(parent.map(|p| p.as_ref()).to_glib_none().0, flags.to_glib(), type_.to_glib(), buttons.to_glib(), b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>())) .unsafe_cast() } } } pub trait MessageDialogExt: 'static { fn set_secondary_markup<'a, I: Into<Option<&'a str>>>(&self, message: I); fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I); } impl<O: IsA<MessageDialog>> MessageDialogExt for O { fn
<'a, I: Into<Option<&'a str>>>(&self, message: I) { let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>()) }, None => unsafe { ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to_glib_none().0, ptr::null::<c_char>()) }, } } fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I) { let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_text( self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>()) }, None => unsafe { ffi::gtk_message_dialog_format_secondary_text( self.as_ref().to_glib_none().0, ptr::null::<c_char>()) }, } } }
set_secondary_markup
identifier_name
message_dialog.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::c_char; use ffi; use glib::translate::*; use glib::object::{Cast, IsA}; use std::ptr; use ButtonsType; use DialogFlags; use MessageDialog; use MessageType; use Widget; use Window; impl MessageDialog { pub fn new<T: IsA<Window>>(parent: Option<&T>, flags: DialogFlags, type_: MessageType, buttons: ButtonsType, message: &str) -> MessageDialog { assert_initialized_main_thread!(); unsafe { let message: Stash<*const c_char, _> = message.to_glib_none(); Widget::from_glib_none( ffi::gtk_message_dialog_new(parent.map(|p| p.as_ref()).to_glib_none().0, flags.to_glib(), type_.to_glib(), buttons.to_glib(), b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>())) .unsafe_cast() } } } pub trait MessageDialogExt: 'static { fn set_secondary_markup<'a, I: Into<Option<&'a str>>>(&self, message: I); fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I); } impl<O: IsA<MessageDialog>> MessageDialogExt for O { fn set_secondary_markup<'a, I: Into<Option<&'a str>>>(&self, message: I)
fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I) { let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_text( self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>()) }, None => unsafe { ffi::gtk_message_dialog_format_secondary_text( self.as_ref().to_glib_none().0, ptr::null::<c_char>()) }, } } }
{ let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>()) }, None => unsafe { ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to_glib_none().0, ptr::null::<c_char>()) }, } }
identifier_body
HeroBusiness.ts
/** * Created by Moiz.Kachwala on 15-06-2016. */ import HeroRepository = require("./../repository/HeroRepository"); import IHeroBusiness = require("./interfaces/HeroBusiness"); import IHeroModel = require("./../model/interfaces/HeroModel"); import HeroModel = require("./../model/HeroModel"); class
implements IHeroBusiness { private _heroRepository: HeroRepository; constructor () { this._heroRepository = new HeroRepository(); } create (item: IHeroModel, callback: (error: any, result: any) => void) { console.log(JSON.stringify(item)); this._heroRepository.create(item, callback); } retrieve (callback: (error: any, result: any) => void) { this._heroRepository.retrieve(callback); } update (_id: string, item: IHeroModel, callback: (error: any, result: any) => void) { this._heroRepository.findById(_id, (err, res) => { if(err) callback(err, res); else { this._heroRepository.update(res._id, item, callback); } }); } delete (_id: string, callback:(error: any, result: any) => void) { this._heroRepository.delete(_id , callback); } findById (_id: string, callback: (error: any, result: IHeroModel) => void) { this._heroRepository.findById(_id, callback); } getTree (_id: string, callback: (error: any, result: IHeroModel) => void) { this._heroRepository.getTree(_id, callback); } getFamily (_id: string, callback: (error: any, result: IHeroModel) => void) { this._heroRepository.getFamily(_id, callback); } } Object.seal(HeroBusiness); export = HeroBusiness;
HeroBusiness
identifier_name
HeroBusiness.ts
/** * Created by Moiz.Kachwala on 15-06-2016. */ import HeroRepository = require("./../repository/HeroRepository"); import IHeroBusiness = require("./interfaces/HeroBusiness"); import IHeroModel = require("./../model/interfaces/HeroModel"); import HeroModel = require("./../model/HeroModel"); class HeroBusiness implements IHeroBusiness { private _heroRepository: HeroRepository; constructor () { this._heroRepository = new HeroRepository(); } create (item: IHeroModel, callback: (error: any, result: any) => void)
retrieve (callback: (error: any, result: any) => void) { this._heroRepository.retrieve(callback); } update (_id: string, item: IHeroModel, callback: (error: any, result: any) => void) { this._heroRepository.findById(_id, (err, res) => { if(err) callback(err, res); else { this._heroRepository.update(res._id, item, callback); } }); } delete (_id: string, callback:(error: any, result: any) => void) { this._heroRepository.delete(_id , callback); } findById (_id: string, callback: (error: any, result: IHeroModel) => void) { this._heroRepository.findById(_id, callback); } getTree (_id: string, callback: (error: any, result: IHeroModel) => void) { this._heroRepository.getTree(_id, callback); } getFamily (_id: string, callback: (error: any, result: IHeroModel) => void) { this._heroRepository.getFamily(_id, callback); } } Object.seal(HeroBusiness); export = HeroBusiness;
{ console.log(JSON.stringify(item)); this._heroRepository.create(item, callback); }
identifier_body
HeroBusiness.ts
/** * Created by Moiz.Kachwala on 15-06-2016. */ import HeroRepository = require("./../repository/HeroRepository"); import IHeroBusiness = require("./interfaces/HeroBusiness"); import IHeroModel = require("./../model/interfaces/HeroModel"); import HeroModel = require("./../model/HeroModel"); class HeroBusiness implements IHeroBusiness { private _heroRepository: HeroRepository; constructor () { this._heroRepository = new HeroRepository(); } create (item: IHeroModel, callback: (error: any, result: any) => void) { console.log(JSON.stringify(item)); this._heroRepository.create(item, callback);
retrieve (callback: (error: any, result: any) => void) { this._heroRepository.retrieve(callback); } update (_id: string, item: IHeroModel, callback: (error: any, result: any) => void) { this._heroRepository.findById(_id, (err, res) => { if(err) callback(err, res); else { this._heroRepository.update(res._id, item, callback); } }); } delete (_id: string, callback:(error: any, result: any) => void) { this._heroRepository.delete(_id , callback); } findById (_id: string, callback: (error: any, result: IHeroModel) => void) { this._heroRepository.findById(_id, callback); } getTree (_id: string, callback: (error: any, result: IHeroModel) => void) { this._heroRepository.getTree(_id, callback); } getFamily (_id: string, callback: (error: any, result: IHeroModel) => void) { this._heroRepository.getFamily(_id, callback); } } Object.seal(HeroBusiness); export = HeroBusiness;
}
random_line_split
solarAdd.py
from omf import feeder import omf.solvers.gridlabd feed = feeder.parse('GC-12.47-1.glm') maxKey = feeder.getMaxKey(feed) print(feed[1]) feed[maxKey + 1] = { 'object': 'node', 'name': 'test_solar_node', 'phases': 'ABCN', 'nominal_voltage': '7200' } feed[maxKey + 2] = { 'object': 'underground_line', 'name': 'test_solar_line', 'phases': 'ABCN', 'from': 'test_solar_node', 'to': 'GC-12-47-1_node_26', 'length': '100', 'configuration': 'line_configuration:6' }
'object': 'meter', 'name': 'test_solar_meter', 'parent': 'test_solar_node', 'phases': 'ABCN', 'nominal_voltage': '480' } feed[maxKey + 4] = { 'object': 'inverter', 'name': 'test_solar_inverter', 'parent': 'test_solar_meter', 'phases': 'AS', 'inverter_type': 'PWM', 'power_factor': '1.0', 'generator_status': 'ONLINE', 'generator_mode': 'CONSTANT_PF' } feed[maxKey + 5] = { 'object': 'solar', 'name': 'test_solar', 'parent': 'test_solar_inverter', 'area': '1000000 sf', 'generator_status': 'ONLINE', 'efficiency': '0.2', 'generator_mode': 'SUPPLY_DRIVEN', 'panel_type': 'SINGLE_CRYSTAL_SILICON' } feed[maxKey + 6] = { 'object': 'recorder', 'parent': 'test_solar_meter', 'property': 'voltage_A.real,voltage_A.imag,voltage_B.real,voltage_B.imag,voltage_C.real,voltage_C.imag', 'file': 'GC-addSolar-voltages.csv', 'interval': '60', 'limit': '1440' } omf.solvers.gridlabd.runInFilesystem(feed, keepFiles = True, workDir = '.', glmName = 'GC-solarAdd.glm') ''' output = open('GC-solarAdd.glm', 'w') output.write(feeder.write(feed)) output.close() '''
feed[maxKey + 3] = {
random_line_split