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
lib.rs
#![feature(unboxed_closures)] extern crate libc; macro_rules! assert_enum { (@as_expr $e:expr) => {$e}; (@as_pat $p:pat) => {$p}; ($left:expr, $($right:tt)*) => ( { match &($left) { assert_enum!(@as_pat &$($right)*(..)) => {}, _ => { panic!("assertion failed: `(if let left = right(..))` \ (left: `{:?}`, right: `{:?}`)", $left, stringify!($($right)*) ) } } } ) } pub mod ffi; pub mod stack; pub mod collections; mod context; mod value; mod borrow; mod function; pub use context::*; pub use collections::*; pub use value::*; pub use borrow::*; pub use function::*; pub struct
; #[macro_export] macro_rules! push { ($cxt:expr, $($arg:expr),*) => ( $( $cxt.push($arg); )* ) }
nil
identifier_name
lib.rs
#![feature(unboxed_closures)] extern crate libc; macro_rules! assert_enum { (@as_expr $e:expr) => {$e}; (@as_pat $p:pat) => {$p}; ($left:expr, $($right:tt)*) => ( { match &($left) { assert_enum!(@as_pat &$($right)*(..)) => {}, _ => { panic!("assertion failed: `(if let left = right(..))` \ (left: `{:?}`, right: `{:?}`)", $left, stringify!($($right)*) ) } } } ) } pub mod ffi; pub mod stack; pub mod collections; mod context; mod value;
pub use context::*; pub use collections::*; pub use value::*; pub use borrow::*; pub use function::*; pub struct nil; #[macro_export] macro_rules! push { ($cxt:expr, $($arg:expr),*) => ( $( $cxt.push($arg); )* ) }
mod borrow; mod function;
random_line_split
issue-50706.rs
// Copyright 2018 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. // compile-pass pub struct Stats; #[derive(PartialEq, Eq)] pub struct StatVariant { pub id: u8, _priv: (), } #[derive(PartialEq, Eq)] pub struct Stat { pub variant: StatVariant, pub index: usize, _priv: (), } impl Stats { pub const TEST: StatVariant = StatVariant{id: 0, _priv: (),}; #[allow(non_upper_case_globals)] pub const A: Stat = Stat{ variant: Self::TEST, index: 0, _priv: (),}; } impl Stat { pub fn from_index(variant: StatVariant, index: usize) -> Option<Stat> { let stat = Stat{variant, index, _priv: (),};
match stat { Stats::A => Some(Stats::A), _ => None, } } } fn main() {}
random_line_split
issue-50706.rs
// Copyright 2018 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. // compile-pass pub struct
; #[derive(PartialEq, Eq)] pub struct StatVariant { pub id: u8, _priv: (), } #[derive(PartialEq, Eq)] pub struct Stat { pub variant: StatVariant, pub index: usize, _priv: (), } impl Stats { pub const TEST: StatVariant = StatVariant{id: 0, _priv: (),}; #[allow(non_upper_case_globals)] pub const A: Stat = Stat{ variant: Self::TEST, index: 0, _priv: (),}; } impl Stat { pub fn from_index(variant: StatVariant, index: usize) -> Option<Stat> { let stat = Stat{variant, index, _priv: (),}; match stat { Stats::A => Some(Stats::A), _ => None, } } } fn main() {}
Stats
identifier_name
hg-to-git.py
#!/usr/bin/env python """ hg-to-git.py - A Mercurial to GIT converter Copyright (C)2007 Stelian Pop <stelian@popies.net> 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 2, 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, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. """ import os, os.path, sys import tempfile, pickle, getopt import re if sys.hexversion < 0x02030000: # The behavior of the pickle module changed significantly in 2.3 sys.stderr.write("hg-to-git.py: requires Python 2.3 or later.\n") sys.exit(1) # Maps hg version -> git version hgvers = {} # List of children for each hg revision hgchildren = {} # List of parents for each hg revision hgparents = {} # Current branch for each hg revision hgbranch = {} # Number of new changesets converted from hg hgnewcsets = 0 #------------------------------------------------------------------------------ def usage():
#------------------------------------------------------------------------------ def getgitenv(user, date): env = '' elems = re.compile('(.*?)\s+<(.*)>').match(user) if elems: env += 'export GIT_AUTHOR_NAME="%s" ;' % elems.group(1) env += 'export GIT_COMMITTER_NAME="%s" ;' % elems.group(1) env += 'export GIT_AUTHOR_EMAIL="%s" ;' % elems.group(2) env += 'export GIT_COMMITTER_EMAIL="%s" ;' % elems.group(2) else: env += 'export GIT_AUTHOR_NAME="%s" ;' % user env += 'export GIT_COMMITTER_NAME="%s" ;' % user env += 'export GIT_AUTHOR_EMAIL= ;' env += 'export GIT_COMMITTER_EMAIL= ;' env += 'export GIT_AUTHOR_DATE="%s" ;' % date env += 'export GIT_COMMITTER_DATE="%s" ;' % date return env #------------------------------------------------------------------------------ state = '' opt_nrepack = 0 verbose = False try: opts, args = getopt.getopt(sys.argv[1:], 's:t:n:v', ['gitstate=', 'tempdir=', 'nrepack=', 'verbose']) for o, a in opts: if o in ('-s', '--gitstate'): state = a state = os.path.abspath(state) if o in ('-n', '--nrepack'): opt_nrepack = int(a) if o in ('-v', '--verbose'): verbose = True if len(args) != 1: raise Exception('params') except: usage() sys.exit(1) hgprj = args[0] os.chdir(hgprj) if state: if os.path.exists(state): if verbose: print 'State does exist, reading' f = open(state, 'r') hgvers = pickle.load(f) else: print 'State does not exist, first run' sock = os.popen('hg tip --template "{rev}"') tip = sock.read() if sock.close(): sys.exit(1) if verbose: print 'tip is', tip # Calculate the branches if verbose: print 'analysing the branches...' hgchildren["0"] = () hgparents["0"] = (None, None) hgbranch["0"] = "master" for cset in range(1, int(tip) + 1): hgchildren[str(cset)] = () prnts = os.popen('hg log -r %d --template "{parents}"' % cset).read().strip().split(' ') prnts = map(lambda x: x[:x.find(':')], prnts) if prnts[0] != '': parent = prnts[0].strip() else: parent = str(cset - 1) hgchildren[parent] += ( str(cset), ) if len(prnts) > 1: mparent = prnts[1].strip() hgchildren[mparent] += ( str(cset), ) else: mparent = None hgparents[str(cset)] = (parent, mparent) if mparent: # For merge changesets, take either one, preferably the 'master' branch if hgbranch[mparent] == 'master': hgbranch[str(cset)] = 'master' else: hgbranch[str(cset)] = hgbranch[parent] else: # Normal changesets # For first children, take the parent branch, for the others create a new branch if hgchildren[parent][0] == str(cset): hgbranch[str(cset)] = hgbranch[parent] else: hgbranch[str(cset)] = "branch-" + str(cset) if not hgvers.has_key("0"): print 'creating repository' os.system('git init') # loop through every hg changeset for cset in range(int(tip) + 1): # incremental, already seen if hgvers.has_key(str(cset)): continue hgnewcsets += 1 # get info log_data = os.popen('hg log -r %d --template "{tags}\n{date|date}\n{author}\n"' % cset).readlines() tag = log_data[0].strip() date = log_data[1].strip() user = log_data[2].strip() parent = hgparents[str(cset)][0] mparent = hgparents[str(cset)][1] #get comment (fdcomment, filecomment) = tempfile.mkstemp() csetcomment = os.popen('hg log -r %d --template "{desc}"' % cset).read().strip() os.write(fdcomment, csetcomment) os.close(fdcomment) print '-----------------------------------------' print 'cset:', cset print 'branch:', hgbranch[str(cset)] print 'user:', user print 'date:', date print 'comment:', csetcomment if parent: print 'parent:', parent if mparent: print 'mparent:', mparent if tag: print 'tag:', tag print '-----------------------------------------' # checkout the parent if necessary if cset != 0: if hgbranch[str(cset)] == "branch-" + str(cset): print 'creating new branch', hgbranch[str(cset)] os.system('git checkout -b %s %s' % (hgbranch[str(cset)], hgvers[parent])) else: print 'checking out branch', hgbranch[str(cset)] os.system('git checkout %s' % hgbranch[str(cset)]) # merge if mparent: if hgbranch[parent] == hgbranch[str(cset)]: otherbranch = hgbranch[mparent] else: otherbranch = hgbranch[parent] print 'merging', otherbranch, 'into', hgbranch[str(cset)] os.system(getgitenv(user, date) + 'git merge --no-commit -s ours "" %s %s' % (hgbranch[str(cset)], otherbranch)) # remove everything except .git and .hg directories os.system('find . \( -path "./.hg" -o -path "./.git" \) -prune -o ! -name "." -print | xargs rm -rf') # repopulate with checkouted files os.system('hg update -C %d' % cset) # add new files os.system('git ls-files -x .hg --others | git update-index --add --stdin') # delete removed files os.system('git ls-files -x .hg --deleted | git update-index --remove --stdin') # commit os.system(getgitenv(user, date) + 'git commit --allow-empty -a -F %s' % filecomment) os.unlink(filecomment) # tag if tag and tag != 'tip': os.system(getgitenv(user, date) + 'git tag %s' % tag) # delete branch if not used anymore... if mparent and len(hgchildren[str(cset)]): print "Deleting unused branch:", otherbranch os.system('git branch -d %s' % otherbranch) # retrieve and record the version vvv = os.popen('git show --quiet --pretty=format:%H').read() print 'record', cset, '->', vvv hgvers[str(cset)] = vvv if hgnewcsets >= opt_nrepack and opt_nrepack != -1: os.system('git repack -a -d') # write the state for incrementals if state: if verbose: print 'Writing state' f = open(state, 'w') pickle.dump(hgvers, f) # vim: et ts=8 sw=4 sts=4
print """\ %s: [OPTIONS] <hgprj> options: -s, --gitstate=FILE: name of the state to be saved/read for incrementals -n, --nrepack=INT: number of changesets that will trigger a repack (default=0, -1 to deactivate) -v, --verbose: be verbose required: hgprj: name of the HG project to import (directory) """ % sys.argv[0]
identifier_body
hg-to-git.py
#!/usr/bin/env python """ hg-to-git.py - A Mercurial to GIT converter Copyright (C)2007 Stelian Pop <stelian@popies.net> 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 2, 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, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. """ import os, os.path, sys import tempfile, pickle, getopt import re if sys.hexversion < 0x02030000: # The behavior of the pickle module changed significantly in 2.3 sys.stderr.write("hg-to-git.py: requires Python 2.3 or later.\n") sys.exit(1) # Maps hg version -> git version hgvers = {} # List of children for each hg revision hgchildren = {} # List of parents for each hg revision hgparents = {} # Current branch for each hg revision hgbranch = {} # Number of new changesets converted from hg hgnewcsets = 0 #------------------------------------------------------------------------------ def usage(): print """\ %s: [OPTIONS] <hgprj> options: -s, --gitstate=FILE: name of the state to be saved/read for incrementals -n, --nrepack=INT: number of changesets that will trigger a repack (default=0, -1 to deactivate) -v, --verbose: be verbose required: hgprj: name of the HG project to import (directory) """ % sys.argv[0] #------------------------------------------------------------------------------ def getgitenv(user, date): env = '' elems = re.compile('(.*?)\s+<(.*)>').match(user) if elems: env += 'export GIT_AUTHOR_NAME="%s" ;' % elems.group(1) env += 'export GIT_COMMITTER_NAME="%s" ;' % elems.group(1) env += 'export GIT_AUTHOR_EMAIL="%s" ;' % elems.group(2) env += 'export GIT_COMMITTER_EMAIL="%s" ;' % elems.group(2) else: env += 'export GIT_AUTHOR_NAME="%s" ;' % user env += 'export GIT_COMMITTER_NAME="%s" ;' % user env += 'export GIT_AUTHOR_EMAIL= ;' env += 'export GIT_COMMITTER_EMAIL= ;' env += 'export GIT_AUTHOR_DATE="%s" ;' % date env += 'export GIT_COMMITTER_DATE="%s" ;' % date return env #------------------------------------------------------------------------------ state = '' opt_nrepack = 0 verbose = False try: opts, args = getopt.getopt(sys.argv[1:], 's:t:n:v', ['gitstate=', 'tempdir=', 'nrepack=', 'verbose']) for o, a in opts: if o in ('-s', '--gitstate'): state = a state = os.path.abspath(state) if o in ('-n', '--nrepack'): opt_nrepack = int(a) if o in ('-v', '--verbose'): verbose = True if len(args) != 1: raise Exception('params') except: usage() sys.exit(1) hgprj = args[0] os.chdir(hgprj) if state: if os.path.exists(state): if verbose: print 'State does exist, reading' f = open(state, 'r') hgvers = pickle.load(f) else: print 'State does not exist, first run' sock = os.popen('hg tip --template "{rev}"') tip = sock.read() if sock.close(): sys.exit(1) if verbose: print 'tip is', tip # Calculate the branches if verbose: print 'analysing the branches...' hgchildren["0"] = () hgparents["0"] = (None, None) hgbranch["0"] = "master" for cset in range(1, int(tip) + 1): hgchildren[str(cset)] = () prnts = os.popen('hg log -r %d --template "{parents}"' % cset).read().strip().split(' ') prnts = map(lambda x: x[:x.find(':')], prnts) if prnts[0] != '': parent = prnts[0].strip() else: parent = str(cset - 1) hgchildren[parent] += ( str(cset), ) if len(prnts) > 1: mparent = prnts[1].strip() hgchildren[mparent] += ( str(cset), ) else: mparent = None hgparents[str(cset)] = (parent, mparent) if mparent: # For merge changesets, take either one, preferably the 'master' branch if hgbranch[mparent] == 'master': hgbranch[str(cset)] = 'master' else:
else: # Normal changesets # For first children, take the parent branch, for the others create a new branch if hgchildren[parent][0] == str(cset): hgbranch[str(cset)] = hgbranch[parent] else: hgbranch[str(cset)] = "branch-" + str(cset) if not hgvers.has_key("0"): print 'creating repository' os.system('git init') # loop through every hg changeset for cset in range(int(tip) + 1): # incremental, already seen if hgvers.has_key(str(cset)): continue hgnewcsets += 1 # get info log_data = os.popen('hg log -r %d --template "{tags}\n{date|date}\n{author}\n"' % cset).readlines() tag = log_data[0].strip() date = log_data[1].strip() user = log_data[2].strip() parent = hgparents[str(cset)][0] mparent = hgparents[str(cset)][1] #get comment (fdcomment, filecomment) = tempfile.mkstemp() csetcomment = os.popen('hg log -r %d --template "{desc}"' % cset).read().strip() os.write(fdcomment, csetcomment) os.close(fdcomment) print '-----------------------------------------' print 'cset:', cset print 'branch:', hgbranch[str(cset)] print 'user:', user print 'date:', date print 'comment:', csetcomment if parent: print 'parent:', parent if mparent: print 'mparent:', mparent if tag: print 'tag:', tag print '-----------------------------------------' # checkout the parent if necessary if cset != 0: if hgbranch[str(cset)] == "branch-" + str(cset): print 'creating new branch', hgbranch[str(cset)] os.system('git checkout -b %s %s' % (hgbranch[str(cset)], hgvers[parent])) else: print 'checking out branch', hgbranch[str(cset)] os.system('git checkout %s' % hgbranch[str(cset)]) # merge if mparent: if hgbranch[parent] == hgbranch[str(cset)]: otherbranch = hgbranch[mparent] else: otherbranch = hgbranch[parent] print 'merging', otherbranch, 'into', hgbranch[str(cset)] os.system(getgitenv(user, date) + 'git merge --no-commit -s ours "" %s %s' % (hgbranch[str(cset)], otherbranch)) # remove everything except .git and .hg directories os.system('find . \( -path "./.hg" -o -path "./.git" \) -prune -o ! -name "." -print | xargs rm -rf') # repopulate with checkouted files os.system('hg update -C %d' % cset) # add new files os.system('git ls-files -x .hg --others | git update-index --add --stdin') # delete removed files os.system('git ls-files -x .hg --deleted | git update-index --remove --stdin') # commit os.system(getgitenv(user, date) + 'git commit --allow-empty -a -F %s' % filecomment) os.unlink(filecomment) # tag if tag and tag != 'tip': os.system(getgitenv(user, date) + 'git tag %s' % tag) # delete branch if not used anymore... if mparent and len(hgchildren[str(cset)]): print "Deleting unused branch:", otherbranch os.system('git branch -d %s' % otherbranch) # retrieve and record the version vvv = os.popen('git show --quiet --pretty=format:%H').read() print 'record', cset, '->', vvv hgvers[str(cset)] = vvv if hgnewcsets >= opt_nrepack and opt_nrepack != -1: os.system('git repack -a -d') # write the state for incrementals if state: if verbose: print 'Writing state' f = open(state, 'w') pickle.dump(hgvers, f) # vim: et ts=8 sw=4 sts=4
hgbranch[str(cset)] = hgbranch[parent]
conditional_block
hg-to-git.py
#!/usr/bin/env python """ hg-to-git.py - A Mercurial to GIT converter Copyright (C)2007 Stelian Pop <stelian@popies.net> 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 2, 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, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. """ import os, os.path, sys import tempfile, pickle, getopt import re if sys.hexversion < 0x02030000: # The behavior of the pickle module changed significantly in 2.3 sys.stderr.write("hg-to-git.py: requires Python 2.3 or later.\n") sys.exit(1) # Maps hg version -> git version hgvers = {} # List of children for each hg revision hgchildren = {} # List of parents for each hg revision hgparents = {} # Current branch for each hg revision hgbranch = {} # Number of new changesets converted from hg hgnewcsets = 0 #------------------------------------------------------------------------------ def usage(): print """\ %s: [OPTIONS] <hgprj> options: -s, --gitstate=FILE: name of the state to be saved/read for incrementals -n, --nrepack=INT: number of changesets that will trigger a repack (default=0, -1 to deactivate) -v, --verbose: be verbose required: hgprj: name of the HG project to import (directory) """ % sys.argv[0] #------------------------------------------------------------------------------ def
(user, date): env = '' elems = re.compile('(.*?)\s+<(.*)>').match(user) if elems: env += 'export GIT_AUTHOR_NAME="%s" ;' % elems.group(1) env += 'export GIT_COMMITTER_NAME="%s" ;' % elems.group(1) env += 'export GIT_AUTHOR_EMAIL="%s" ;' % elems.group(2) env += 'export GIT_COMMITTER_EMAIL="%s" ;' % elems.group(2) else: env += 'export GIT_AUTHOR_NAME="%s" ;' % user env += 'export GIT_COMMITTER_NAME="%s" ;' % user env += 'export GIT_AUTHOR_EMAIL= ;' env += 'export GIT_COMMITTER_EMAIL= ;' env += 'export GIT_AUTHOR_DATE="%s" ;' % date env += 'export GIT_COMMITTER_DATE="%s" ;' % date return env #------------------------------------------------------------------------------ state = '' opt_nrepack = 0 verbose = False try: opts, args = getopt.getopt(sys.argv[1:], 's:t:n:v', ['gitstate=', 'tempdir=', 'nrepack=', 'verbose']) for o, a in opts: if o in ('-s', '--gitstate'): state = a state = os.path.abspath(state) if o in ('-n', '--nrepack'): opt_nrepack = int(a) if o in ('-v', '--verbose'): verbose = True if len(args) != 1: raise Exception('params') except: usage() sys.exit(1) hgprj = args[0] os.chdir(hgprj) if state: if os.path.exists(state): if verbose: print 'State does exist, reading' f = open(state, 'r') hgvers = pickle.load(f) else: print 'State does not exist, first run' sock = os.popen('hg tip --template "{rev}"') tip = sock.read() if sock.close(): sys.exit(1) if verbose: print 'tip is', tip # Calculate the branches if verbose: print 'analysing the branches...' hgchildren["0"] = () hgparents["0"] = (None, None) hgbranch["0"] = "master" for cset in range(1, int(tip) + 1): hgchildren[str(cset)] = () prnts = os.popen('hg log -r %d --template "{parents}"' % cset).read().strip().split(' ') prnts = map(lambda x: x[:x.find(':')], prnts) if prnts[0] != '': parent = prnts[0].strip() else: parent = str(cset - 1) hgchildren[parent] += ( str(cset), ) if len(prnts) > 1: mparent = prnts[1].strip() hgchildren[mparent] += ( str(cset), ) else: mparent = None hgparents[str(cset)] = (parent, mparent) if mparent: # For merge changesets, take either one, preferably the 'master' branch if hgbranch[mparent] == 'master': hgbranch[str(cset)] = 'master' else: hgbranch[str(cset)] = hgbranch[parent] else: # Normal changesets # For first children, take the parent branch, for the others create a new branch if hgchildren[parent][0] == str(cset): hgbranch[str(cset)] = hgbranch[parent] else: hgbranch[str(cset)] = "branch-" + str(cset) if not hgvers.has_key("0"): print 'creating repository' os.system('git init') # loop through every hg changeset for cset in range(int(tip) + 1): # incremental, already seen if hgvers.has_key(str(cset)): continue hgnewcsets += 1 # get info log_data = os.popen('hg log -r %d --template "{tags}\n{date|date}\n{author}\n"' % cset).readlines() tag = log_data[0].strip() date = log_data[1].strip() user = log_data[2].strip() parent = hgparents[str(cset)][0] mparent = hgparents[str(cset)][1] #get comment (fdcomment, filecomment) = tempfile.mkstemp() csetcomment = os.popen('hg log -r %d --template "{desc}"' % cset).read().strip() os.write(fdcomment, csetcomment) os.close(fdcomment) print '-----------------------------------------' print 'cset:', cset print 'branch:', hgbranch[str(cset)] print 'user:', user print 'date:', date print 'comment:', csetcomment if parent: print 'parent:', parent if mparent: print 'mparent:', mparent if tag: print 'tag:', tag print '-----------------------------------------' # checkout the parent if necessary if cset != 0: if hgbranch[str(cset)] == "branch-" + str(cset): print 'creating new branch', hgbranch[str(cset)] os.system('git checkout -b %s %s' % (hgbranch[str(cset)], hgvers[parent])) else: print 'checking out branch', hgbranch[str(cset)] os.system('git checkout %s' % hgbranch[str(cset)]) # merge if mparent: if hgbranch[parent] == hgbranch[str(cset)]: otherbranch = hgbranch[mparent] else: otherbranch = hgbranch[parent] print 'merging', otherbranch, 'into', hgbranch[str(cset)] os.system(getgitenv(user, date) + 'git merge --no-commit -s ours "" %s %s' % (hgbranch[str(cset)], otherbranch)) # remove everything except .git and .hg directories os.system('find . \( -path "./.hg" -o -path "./.git" \) -prune -o ! -name "." -print | xargs rm -rf') # repopulate with checkouted files os.system('hg update -C %d' % cset) # add new files os.system('git ls-files -x .hg --others | git update-index --add --stdin') # delete removed files os.system('git ls-files -x .hg --deleted | git update-index --remove --stdin') # commit os.system(getgitenv(user, date) + 'git commit --allow-empty -a -F %s' % filecomment) os.unlink(filecomment) # tag if tag and tag != 'tip': os.system(getgitenv(user, date) + 'git tag %s' % tag) # delete branch if not used anymore... if mparent and len(hgchildren[str(cset)]): print "Deleting unused branch:", otherbranch os.system('git branch -d %s' % otherbranch) # retrieve and record the version vvv = os.popen('git show --quiet --pretty=format:%H').read() print 'record', cset, '->', vvv hgvers[str(cset)] = vvv if hgnewcsets >= opt_nrepack and opt_nrepack != -1: os.system('git repack -a -d') # write the state for incrementals if state: if verbose: print 'Writing state' f = open(state, 'w') pickle.dump(hgvers, f) # vim: et ts=8 sw=4 sts=4
getgitenv
identifier_name
hg-to-git.py
#!/usr/bin/env python
""" hg-to-git.py - A Mercurial to GIT converter Copyright (C)2007 Stelian Pop <stelian@popies.net> 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 2, 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, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. """ import os, os.path, sys import tempfile, pickle, getopt import re if sys.hexversion < 0x02030000: # The behavior of the pickle module changed significantly in 2.3 sys.stderr.write("hg-to-git.py: requires Python 2.3 or later.\n") sys.exit(1) # Maps hg version -> git version hgvers = {} # List of children for each hg revision hgchildren = {} # List of parents for each hg revision hgparents = {} # Current branch for each hg revision hgbranch = {} # Number of new changesets converted from hg hgnewcsets = 0 #------------------------------------------------------------------------------ def usage(): print """\ %s: [OPTIONS] <hgprj> options: -s, --gitstate=FILE: name of the state to be saved/read for incrementals -n, --nrepack=INT: number of changesets that will trigger a repack (default=0, -1 to deactivate) -v, --verbose: be verbose required: hgprj: name of the HG project to import (directory) """ % sys.argv[0] #------------------------------------------------------------------------------ def getgitenv(user, date): env = '' elems = re.compile('(.*?)\s+<(.*)>').match(user) if elems: env += 'export GIT_AUTHOR_NAME="%s" ;' % elems.group(1) env += 'export GIT_COMMITTER_NAME="%s" ;' % elems.group(1) env += 'export GIT_AUTHOR_EMAIL="%s" ;' % elems.group(2) env += 'export GIT_COMMITTER_EMAIL="%s" ;' % elems.group(2) else: env += 'export GIT_AUTHOR_NAME="%s" ;' % user env += 'export GIT_COMMITTER_NAME="%s" ;' % user env += 'export GIT_AUTHOR_EMAIL= ;' env += 'export GIT_COMMITTER_EMAIL= ;' env += 'export GIT_AUTHOR_DATE="%s" ;' % date env += 'export GIT_COMMITTER_DATE="%s" ;' % date return env #------------------------------------------------------------------------------ state = '' opt_nrepack = 0 verbose = False try: opts, args = getopt.getopt(sys.argv[1:], 's:t:n:v', ['gitstate=', 'tempdir=', 'nrepack=', 'verbose']) for o, a in opts: if o in ('-s', '--gitstate'): state = a state = os.path.abspath(state) if o in ('-n', '--nrepack'): opt_nrepack = int(a) if o in ('-v', '--verbose'): verbose = True if len(args) != 1: raise Exception('params') except: usage() sys.exit(1) hgprj = args[0] os.chdir(hgprj) if state: if os.path.exists(state): if verbose: print 'State does exist, reading' f = open(state, 'r') hgvers = pickle.load(f) else: print 'State does not exist, first run' sock = os.popen('hg tip --template "{rev}"') tip = sock.read() if sock.close(): sys.exit(1) if verbose: print 'tip is', tip # Calculate the branches if verbose: print 'analysing the branches...' hgchildren["0"] = () hgparents["0"] = (None, None) hgbranch["0"] = "master" for cset in range(1, int(tip) + 1): hgchildren[str(cset)] = () prnts = os.popen('hg log -r %d --template "{parents}"' % cset).read().strip().split(' ') prnts = map(lambda x: x[:x.find(':')], prnts) if prnts[0] != '': parent = prnts[0].strip() else: parent = str(cset - 1) hgchildren[parent] += ( str(cset), ) if len(prnts) > 1: mparent = prnts[1].strip() hgchildren[mparent] += ( str(cset), ) else: mparent = None hgparents[str(cset)] = (parent, mparent) if mparent: # For merge changesets, take either one, preferably the 'master' branch if hgbranch[mparent] == 'master': hgbranch[str(cset)] = 'master' else: hgbranch[str(cset)] = hgbranch[parent] else: # Normal changesets # For first children, take the parent branch, for the others create a new branch if hgchildren[parent][0] == str(cset): hgbranch[str(cset)] = hgbranch[parent] else: hgbranch[str(cset)] = "branch-" + str(cset) if not hgvers.has_key("0"): print 'creating repository' os.system('git init') # loop through every hg changeset for cset in range(int(tip) + 1): # incremental, already seen if hgvers.has_key(str(cset)): continue hgnewcsets += 1 # get info log_data = os.popen('hg log -r %d --template "{tags}\n{date|date}\n{author}\n"' % cset).readlines() tag = log_data[0].strip() date = log_data[1].strip() user = log_data[2].strip() parent = hgparents[str(cset)][0] mparent = hgparents[str(cset)][1] #get comment (fdcomment, filecomment) = tempfile.mkstemp() csetcomment = os.popen('hg log -r %d --template "{desc}"' % cset).read().strip() os.write(fdcomment, csetcomment) os.close(fdcomment) print '-----------------------------------------' print 'cset:', cset print 'branch:', hgbranch[str(cset)] print 'user:', user print 'date:', date print 'comment:', csetcomment if parent: print 'parent:', parent if mparent: print 'mparent:', mparent if tag: print 'tag:', tag print '-----------------------------------------' # checkout the parent if necessary if cset != 0: if hgbranch[str(cset)] == "branch-" + str(cset): print 'creating new branch', hgbranch[str(cset)] os.system('git checkout -b %s %s' % (hgbranch[str(cset)], hgvers[parent])) else: print 'checking out branch', hgbranch[str(cset)] os.system('git checkout %s' % hgbranch[str(cset)]) # merge if mparent: if hgbranch[parent] == hgbranch[str(cset)]: otherbranch = hgbranch[mparent] else: otherbranch = hgbranch[parent] print 'merging', otherbranch, 'into', hgbranch[str(cset)] os.system(getgitenv(user, date) + 'git merge --no-commit -s ours "" %s %s' % (hgbranch[str(cset)], otherbranch)) # remove everything except .git and .hg directories os.system('find . \( -path "./.hg" -o -path "./.git" \) -prune -o ! -name "." -print | xargs rm -rf') # repopulate with checkouted files os.system('hg update -C %d' % cset) # add new files os.system('git ls-files -x .hg --others | git update-index --add --stdin') # delete removed files os.system('git ls-files -x .hg --deleted | git update-index --remove --stdin') # commit os.system(getgitenv(user, date) + 'git commit --allow-empty -a -F %s' % filecomment) os.unlink(filecomment) # tag if tag and tag != 'tip': os.system(getgitenv(user, date) + 'git tag %s' % tag) # delete branch if not used anymore... if mparent and len(hgchildren[str(cset)]): print "Deleting unused branch:", otherbranch os.system('git branch -d %s' % otherbranch) # retrieve and record the version vvv = os.popen('git show --quiet --pretty=format:%H').read() print 'record', cset, '->', vvv hgvers[str(cset)] = vvv if hgnewcsets >= opt_nrepack and opt_nrepack != -1: os.system('git repack -a -d') # write the state for incrementals if state: if verbose: print 'Writing state' f = open(state, 'w') pickle.dump(hgvers, f) # vim: et ts=8 sw=4 sts=4
random_line_split
webpack.base.babel.js
/** * COMMON WEBPACK CONFIGURATION */ const path = require('path'); const webpack = require('webpack'); module.exports = (options) => ({ entry: options.entry, output: Object.assign({ // Compile into js/build.js path: path.resolve(process.cwd(), 'build'), publicPath: '/', }, options.output), // Merge with env dependent settings module: { loaders: [{ test: /\.js$/, // Transform all .js files required somewhere with Babel loader: 'babel', exclude: /node_modules/, query: options.babelQuery, }, { // Do not transform vendor's CSS with CSS-modules // The point is that they remain in global scope. // Since we require these CSS files in our JS or CSS files, // they will be a part of our compilation either way. // So, no need for ExtractTextPlugin here. test: /\.css$/, include: /node_modules/, loaders: ['style-loader', 'css-loader'], }, { test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file-loader', }, { test: /\.(jpg|png|gif)$/, loaders: [ 'file-loader', { loader: 'image-webpack', query: { progressive: true, optimizationLevel: 7, interlaced: false, pngquant: { quality: '65-90', speed: 4, }, }, }, ], }, { test: /\.html$/, loader: 'html-loader', }, { test: /\.json$/, loader: 'json-loader', }, { test: /\.(mp4|webm)$/, loader: 'url-loader', query: { limit: 10000, }, }], }, plugins: options.plugins.concat([ new webpack.ProvidePlugin({ // make fetch available fetch: 'exports?self.fetch!whatwg-fetch', }), // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV` // inside your code for any environment checks; UglifyJS will automatically // drop any unreachable code. new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV), }, }),
modules: ['app', 'node_modules'], extensions: [ '.js', '.jsx', '.react.js', ], mainFields: [ 'browser', 'jsnext:main', 'main', ], }, devtool: options.devtool, target: 'web', // Make web variables accessible to webpack, e.g. window });
new webpack.NamedModulesPlugin(), ]), resolve: {
random_line_split
llms-form-checkout.js
/** * LifterLMS Checkout Screen related events and interactions * * @package LifterLMS/Scripts * * @since 3.0.0 * @version 3.34.5 */ ( function( $ ) { var llms_checkout = function() { /** * Array of validation functions to call on form submission * * @type array * @since 3.0.0 * @version 3.0.0 */ var before_submit = []; /** * Array of gateways to be automatically bound when needed * * @type array * @since 3.0.0 * @version 3.0.0 */ var gateways = []; this.$checkout_form = $( '#llms-product-purchase-form' ); this.$confirm_form = $( '#llms-product-purchase-confirm-form' ); this.$form_sections = false; this.form_action = false; /** * Initialize checkout JS & bind if on the checkout screen * * @since 3.0.0 * @since 3.34.5 Make sure we bind click events for the Show / Hide login area at the top of the checkout screen * even if there's no llms product purchase form. * * @return void */ this.init = function() { var self = this; if ( $( '.llms-checkout-wrapper' ).length ) { this.bind_login(); } if ( this.$checkout_form.length ) { this.form_action = 'checkout'; this.$form_sections = this.$checkout_form.find( '.llms-checkout-section' ); this.$checkout_form.on( 'submit', this, this.submit ); // add before submit event for password strength meter if one's found if ( $( '.llms-password-strength-meter' ).length ) { this.add_before_submit_event( { data: LLMS.PasswordStrength, handler: LLMS.PasswordStrength.checkout, } ); } this.bind_coupon(); this.bind_gateways(); } else if ( this.$confirm_form.length ) { this.form_action = 'confirm'; this.$form_sections = this.$confirm_form.find( '.llms-checkout-section' ); this.$confirm_form.on( 'submit', function() { self.processing( 'start' ); } ); } }; /** * Public function which allows other classes or extensions to add * before submit events to llms checkout private "before_submit" array * * @param object obj object of data to push to the array * requires at least a "handler" key which should pass a callable function * "data" can be anything, will be passed as the first parameter to the handler function * @since 3.0.0 * @version 3.0.0 */ this.add_before_submit_event = function( obj ) { if ( ! obj.handler || 'function' !== typeof obj.handler ) { return; } if ( ! obj.data ) { obj.data = null; } before_submit.push( obj ); }; /** * Add an error message * * @param string message error message string * @param mixed data optional error data to output on the console * @return void * @since 3.27.0 * @version 3.27.0 */ this.add_error = function( message, data ) { var id = 'llms-checkout-errors'; $err = $( '#' + id ); if ( ! $err.length ) { $err = $( '<ul class="llms-notice llms-error" id="' + id + '" />' ); $( '.llms-checkout-wrapper' ).prepend( $err ); } $err.append( '<li>' + message + '</li>' ); if ( data ) { console.error( data ); } }; /** * Public function which allows other classes or extensions to add * gateways classes that should be bound by this class * * @param obj gateway_class callable class object * @since 3.0.0 * @version 3.0.0 */ this.add_gateway = function( gateway_class ) { gateways.push( gateway_class ); }; /** * Bind coupon add & remove button events * * @return void * @since 3.0.0 * @version 3.0.0 */ this.bind_coupon = function() { var self = this; // show & hide the coupon field & button $( 'a[href="#llms-coupon-toggle"]' ).on( 'click', function( e ) { e.preventDefault(); $( '.llms-coupon-entry' ).slideToggle( 400 ); } ); // apply coupon click $( '#llms-apply-coupon' ).on( 'click', function( e ) { e.preventDefault(); self.coupon_apply( $( this ) ); } ); // remove coupon click $( '#llms-remove-coupon' ).on( 'click', function( e ) { e.preventDefault(); self.coupon_remove( $( this ) ); } ); }; /** * Bind gateway section events * * @return void * @since 3.0.0 * @version 3.0.0 */ this.bind_gateways = function() { this.load_gateways(); if ( ! $( 'input[name="llms_payment_gateway"]' ).length ) { $( '#llms_create_pending_order' ).removeAttr( 'disabled' ); } // add class and trigger watchable event when gateway selection changes $( 'input[name="llms_payment_gateway"]' ).on( 'change', function() { $( 'input[name="llms_payment_gateway"]' ).each( function() { var $el = $( this ), $parent = $el.closest( '.llms-payment-gateway' ), $fields = $parent.find( '.llms-gateway-fields' ).find( 'input, textarea, select' ), checked = $el.is( ':checked' ), display_func = ( checked ) ? 'addClass' : 'removeClass'; $parent[ display_func ]( 'is-selected' ); if ( checked ) { // enable fields $fields.removeAttr( 'disabled' ); // emit a watchable event for extensions to hook onto $( '.llms-payment-gateways' ).trigger( 'llms-gateway-selected', { id: $el.val(), $selector: $parent, } );
} } ); } ); // enable / disable buttons depending on field validation status $( '.llms-payment-gateways' ).on( 'llms-gateway-selected', function( e, data ) { var $submit = $( '#llms_create_pending_order' ); if ( data.$selector && data.$selector.find( '.llms-gateway-fields .invalid' ).length ) { $submit.attr( 'disabled', 'disabled' ); } else { $submit.removeAttr( 'disabled' ); } } ); }; /** * Bind click events for the Show / Hide login area at the top of the checkout screen * * @since 3.0.0 * @since 3.34.5 When showing the login form area make sure we slide up the `.llms-notice` link's parent too. * * @return void */ this.bind_login = function() { $( 'a[href="#llms-show-login"]' ).on( 'click', function( e ) { e.preventDefault(); $( this ).closest( '.llms-info,.llms-notice' ).slideUp( 400 ); $( 'form.llms-login' ).slideDown( 400 ); } ); }; /** * Clear error messages * * @return void * @since 3.27.0 * @version 3.27.0 */ this.clear_errors = function() { $( '#llms-checkout-errors' ).remove(); }; /** * Triggered by clicking the "Apply Coupon" Button * Validates the coupon via JS and adds error / success messages * On success it will replace partials on the checkout screen with updated * prices and a "remove coupon" button * * @param obj $btn jQuery selector of the Apply button * @return void * @since 3.0.0 * @version 3.0.0 */ this.coupon_apply = function ( $btn ) { var self = this, $code = $( '#llms_coupon_code' ), code = $code.val(), $messages = $( '.llms-coupon-messages' ), $errors = $messages.find( '.llms-error' ), $container = $( 'form.llms-checkout' ); LLMS.Spinner.start( $container ); window.LLMS.Ajax.call( { data: { action: 'validate_coupon_code', code: code, plan_id: $( '#llms-plan-id' ).val(), }, beforeSend: function() { $errors.hide(); }, success: function( r ) { LLMS.Spinner.stop( $container ); if ( 'error' === r.code ) { var $message = $( '<li>' + r.message + '</li>' ); if ( ! $errors.length ) { $errors = $( '<ul class="llms-notice llms-error" />' ); $messages.append( $errors ); } else { $errors.empty(); } $message.appendTo( $errors ); $errors.show(); } else if ( r.success ) { $( '.llms-coupon-wrapper' ).replaceWith( r.data.coupon_html ); self.bind_coupon(); $( '.llms-payment-gateways' ).replaceWith( r.data.gateways_html ); self.bind_gateways(); $( '.llms-order-summary' ).replaceWith( r.data.summary_html ); } } } ); }; /** * Called by clicking the "Remove Coupon" button * Removes the coupon via AJAX and unsets related session data * * @param obj $btn jQuery selector of the Remove button * @return void * @since 3.0.0 * @version 3.0.0 */ this.coupon_remove = function( $btn ) { var self = this, $container = $( 'form.llms-checkout' ); LLMS.Spinner.start( $container ); window.LLMS.Ajax.call( { data: { action: 'remove_coupon_code', plan_id: $( '#llms-plan-id' ).val(), }, success: function( r ) { LLMS.Spinner.stop( $container ); if ( r.success ) { $( '.llms-coupon-wrapper' ).replaceWith( r.data.coupon_html ); self.bind_coupon(); $( '.llms-order-summary' ).replaceWith( r.data.summary_html ); $( '.llms-payment-gateways' ).replaceWith( r.data.gateways_html ); self.bind_gateways(); } } } ); }; /** * Scroll error messages into view * * @return void * @since 3.27.0 * @version 3.27.0 */ this.focus_errors = function() { $( 'html, body' ).animate( { scrollTop: $( '#llms-checkout-errors' ).offset().top - 50, }, 200 ); }; /** * Bind external gateway JS * * @return void * @since 3.0.0 * @version 3.0.0 */ this.load_gateways = function() { for ( var i = 0; i <= gateways.length; i++ ) { var g = gateways[i]; if ( typeof g === 'object' && g !== null ) { if ( g.bind !== undefined && 'function' === typeof g.bind ) { g.bind(); } } } }; /** * Start or stop processing events on the checkout form * * @param string action whether to start or stop processing [start|stop] * @return void * @since 3.0.0 * @version 3.24.1 */ this.processing = function( action ) { var func, $form; switch ( action ) { case 'stop': func = 'removeClass'; break; case 'start': default: func = 'addClass'; break; } if ( 'checkout' === this.form_action ) { $form = this.$checkout_form; } else if ( 'confirm' === this.form_action ) { $form = this.$confirm_form; } $form[ func ]( 'llms-is-processing' ); LLMS.Spinner[ action ]( this.$form_sections ); }; /** * Handles form submission * Calls all validation events in `before_submit[]` * waits for call backs and either displays returned errors * or submits the form when all are successful * * @param obj e JS event object * @return void * @since 3.0.0 * @version 3.27.0 */ this.submit = function( e ) { var self = e.data, num = before_submit.length, checks = 0, max_checks = 60000, errors = [], finishes = 0, successes = 0, interval; e.preventDefault(); // add spinners self.processing( 'start' ); // remove errors to prevent duplicates self.clear_errors(); // start running all the events for ( var i = 0; i < before_submit.length; i++ ) { var obj = before_submit[ i ]; obj.handler( obj.data, function( r ) { finishes++; if ( true === r ) { successes++; } else if ( 'string' === typeof r ) { errors.push( r ); } } ); } // run an interval to wait for finishes interval = setInterval( function() { var clear = false, stop = false; // timeout... if ( checks >= max_checks ) { clear = true; stop = true; } else if ( num === finishes ) { // everything has finished // all were successful, submit the form if ( num === successes ) { clear = true; self.$checkout_form.off( 'submit', self.submit ); self.$checkout_form.trigger( 'submit' ); } else if ( errors.length ) { clear = true; stop = true; for ( var i = 0; i < errors.length; i++ ) { self.add_error( errors[ i ] ); } self.focus_errors(); } } if ( clear ) { clearInterval( interval ); } if ( stop ) { self.processing( 'stop' ); } checks++; }, 100 ); }; // initialize this.init(); return this; }; window.llms = window.llms || {}; window.llms.checkout = new llms_checkout(); } )( jQuery );
} else { // disable fields $fields.attr( 'disabled', 'disabled' );
random_line_split
llms-form-checkout.js
/** * LifterLMS Checkout Screen related events and interactions * * @package LifterLMS/Scripts * * @since 3.0.0 * @version 3.34.5 */ ( function( $ ) { var llms_checkout = function() { /** * Array of validation functions to call on form submission * * @type array * @since 3.0.0 * @version 3.0.0 */ var before_submit = []; /** * Array of gateways to be automatically bound when needed * * @type array * @since 3.0.0 * @version 3.0.0 */ var gateways = []; this.$checkout_form = $( '#llms-product-purchase-form' ); this.$confirm_form = $( '#llms-product-purchase-confirm-form' ); this.$form_sections = false; this.form_action = false; /** * Initialize checkout JS & bind if on the checkout screen * * @since 3.0.0 * @since 3.34.5 Make sure we bind click events for the Show / Hide login area at the top of the checkout screen * even if there's no llms product purchase form. * * @return void */ this.init = function() { var self = this; if ( $( '.llms-checkout-wrapper' ).length ) { this.bind_login(); } if ( this.$checkout_form.length ) { this.form_action = 'checkout'; this.$form_sections = this.$checkout_form.find( '.llms-checkout-section' ); this.$checkout_form.on( 'submit', this, this.submit ); // add before submit event for password strength meter if one's found if ( $( '.llms-password-strength-meter' ).length ) { this.add_before_submit_event( { data: LLMS.PasswordStrength, handler: LLMS.PasswordStrength.checkout, } ); } this.bind_coupon(); this.bind_gateways(); } else if ( this.$confirm_form.length ) { this.form_action = 'confirm'; this.$form_sections = this.$confirm_form.find( '.llms-checkout-section' ); this.$confirm_form.on( 'submit', function() { self.processing( 'start' ); } ); } }; /** * Public function which allows other classes or extensions to add * before submit events to llms checkout private "before_submit" array * * @param object obj object of data to push to the array * requires at least a "handler" key which should pass a callable function * "data" can be anything, will be passed as the first parameter to the handler function * @since 3.0.0 * @version 3.0.0 */ this.add_before_submit_event = function( obj ) { if ( ! obj.handler || 'function' !== typeof obj.handler ) { return; } if ( ! obj.data ) { obj.data = null; } before_submit.push( obj ); }; /** * Add an error message * * @param string message error message string * @param mixed data optional error data to output on the console * @return void * @since 3.27.0 * @version 3.27.0 */ this.add_error = function( message, data ) { var id = 'llms-checkout-errors'; $err = $( '#' + id ); if ( ! $err.length ) { $err = $( '<ul class="llms-notice llms-error" id="' + id + '" />' ); $( '.llms-checkout-wrapper' ).prepend( $err ); } $err.append( '<li>' + message + '</li>' ); if ( data ) { console.error( data ); } }; /** * Public function which allows other classes or extensions to add * gateways classes that should be bound by this class * * @param obj gateway_class callable class object * @since 3.0.0 * @version 3.0.0 */ this.add_gateway = function( gateway_class ) { gateways.push( gateway_class ); }; /** * Bind coupon add & remove button events * * @return void * @since 3.0.0 * @version 3.0.0 */ this.bind_coupon = function() { var self = this; // show & hide the coupon field & button $( 'a[href="#llms-coupon-toggle"]' ).on( 'click', function( e ) { e.preventDefault(); $( '.llms-coupon-entry' ).slideToggle( 400 ); } ); // apply coupon click $( '#llms-apply-coupon' ).on( 'click', function( e ) { e.preventDefault(); self.coupon_apply( $( this ) ); } ); // remove coupon click $( '#llms-remove-coupon' ).on( 'click', function( e ) { e.preventDefault(); self.coupon_remove( $( this ) ); } ); }; /** * Bind gateway section events * * @return void * @since 3.0.0 * @version 3.0.0 */ this.bind_gateways = function() { this.load_gateways(); if ( ! $( 'input[name="llms_payment_gateway"]' ).length ) { $( '#llms_create_pending_order' ).removeAttr( 'disabled' ); } // add class and trigger watchable event when gateway selection changes $( 'input[name="llms_payment_gateway"]' ).on( 'change', function() { $( 'input[name="llms_payment_gateway"]' ).each( function() { var $el = $( this ), $parent = $el.closest( '.llms-payment-gateway' ), $fields = $parent.find( '.llms-gateway-fields' ).find( 'input, textarea, select' ), checked = $el.is( ':checked' ), display_func = ( checked ) ? 'addClass' : 'removeClass'; $parent[ display_func ]( 'is-selected' ); if ( checked ) { // enable fields $fields.removeAttr( 'disabled' ); // emit a watchable event for extensions to hook onto $( '.llms-payment-gateways' ).trigger( 'llms-gateway-selected', { id: $el.val(), $selector: $parent, } ); } else { // disable fields $fields.attr( 'disabled', 'disabled' ); } } ); } ); // enable / disable buttons depending on field validation status $( '.llms-payment-gateways' ).on( 'llms-gateway-selected', function( e, data ) { var $submit = $( '#llms_create_pending_order' ); if ( data.$selector && data.$selector.find( '.llms-gateway-fields .invalid' ).length ) { $submit.attr( 'disabled', 'disabled' ); } else { $submit.removeAttr( 'disabled' ); } } ); }; /** * Bind click events for the Show / Hide login area at the top of the checkout screen * * @since 3.0.0 * @since 3.34.5 When showing the login form area make sure we slide up the `.llms-notice` link's parent too. * * @return void */ this.bind_login = function() { $( 'a[href="#llms-show-login"]' ).on( 'click', function( e ) { e.preventDefault(); $( this ).closest( '.llms-info,.llms-notice' ).slideUp( 400 ); $( 'form.llms-login' ).slideDown( 400 ); } ); }; /** * Clear error messages * * @return void * @since 3.27.0 * @version 3.27.0 */ this.clear_errors = function() { $( '#llms-checkout-errors' ).remove(); }; /** * Triggered by clicking the "Apply Coupon" Button * Validates the coupon via JS and adds error / success messages * On success it will replace partials on the checkout screen with updated * prices and a "remove coupon" button * * @param obj $btn jQuery selector of the Apply button * @return void * @since 3.0.0 * @version 3.0.0 */ this.coupon_apply = function ( $btn ) { var self = this, $code = $( '#llms_coupon_code' ), code = $code.val(), $messages = $( '.llms-coupon-messages' ), $errors = $messages.find( '.llms-error' ), $container = $( 'form.llms-checkout' ); LLMS.Spinner.start( $container ); window.LLMS.Ajax.call( { data: { action: 'validate_coupon_code', code: code, plan_id: $( '#llms-plan-id' ).val(), }, beforeSend: function() { $errors.hide(); }, success: function( r ) { LLMS.Spinner.stop( $container ); if ( 'error' === r.code ) { var $message = $( '<li>' + r.message + '</li>' ); if ( ! $errors.length ) { $errors = $( '<ul class="llms-notice llms-error" />' ); $messages.append( $errors ); } else { $errors.empty(); } $message.appendTo( $errors ); $errors.show(); } else if ( r.success ) { $( '.llms-coupon-wrapper' ).replaceWith( r.data.coupon_html ); self.bind_coupon(); $( '.llms-payment-gateways' ).replaceWith( r.data.gateways_html ); self.bind_gateways(); $( '.llms-order-summary' ).replaceWith( r.data.summary_html ); } } } ); }; /** * Called by clicking the "Remove Coupon" button * Removes the coupon via AJAX and unsets related session data * * @param obj $btn jQuery selector of the Remove button * @return void * @since 3.0.0 * @version 3.0.0 */ this.coupon_remove = function( $btn ) { var self = this, $container = $( 'form.llms-checkout' ); LLMS.Spinner.start( $container ); window.LLMS.Ajax.call( { data: { action: 'remove_coupon_code', plan_id: $( '#llms-plan-id' ).val(), }, success: function( r ) { LLMS.Spinner.stop( $container ); if ( r.success ) { $( '.llms-coupon-wrapper' ).replaceWith( r.data.coupon_html ); self.bind_coupon(); $( '.llms-order-summary' ).replaceWith( r.data.summary_html ); $( '.llms-payment-gateways' ).replaceWith( r.data.gateways_html ); self.bind_gateways(); } } } ); }; /** * Scroll error messages into view * * @return void * @since 3.27.0 * @version 3.27.0 */ this.focus_errors = function() { $( 'html, body' ).animate( { scrollTop: $( '#llms-checkout-errors' ).offset().top - 50, }, 200 ); }; /** * Bind external gateway JS * * @return void * @since 3.0.0 * @version 3.0.0 */ this.load_gateways = function() { for ( var i = 0; i <= gateways.length; i++ )
}; /** * Start or stop processing events on the checkout form * * @param string action whether to start or stop processing [start|stop] * @return void * @since 3.0.0 * @version 3.24.1 */ this.processing = function( action ) { var func, $form; switch ( action ) { case 'stop': func = 'removeClass'; break; case 'start': default: func = 'addClass'; break; } if ( 'checkout' === this.form_action ) { $form = this.$checkout_form; } else if ( 'confirm' === this.form_action ) { $form = this.$confirm_form; } $form[ func ]( 'llms-is-processing' ); LLMS.Spinner[ action ]( this.$form_sections ); }; /** * Handles form submission * Calls all validation events in `before_submit[]` * waits for call backs and either displays returned errors * or submits the form when all are successful * * @param obj e JS event object * @return void * @since 3.0.0 * @version 3.27.0 */ this.submit = function( e ) { var self = e.data, num = before_submit.length, checks = 0, max_checks = 60000, errors = [], finishes = 0, successes = 0, interval; e.preventDefault(); // add spinners self.processing( 'start' ); // remove errors to prevent duplicates self.clear_errors(); // start running all the events for ( var i = 0; i < before_submit.length; i++ ) { var obj = before_submit[ i ]; obj.handler( obj.data, function( r ) { finishes++; if ( true === r ) { successes++; } else if ( 'string' === typeof r ) { errors.push( r ); } } ); } // run an interval to wait for finishes interval = setInterval( function() { var clear = false, stop = false; // timeout... if ( checks >= max_checks ) { clear = true; stop = true; } else if ( num === finishes ) { // everything has finished // all were successful, submit the form if ( num === successes ) { clear = true; self.$checkout_form.off( 'submit', self.submit ); self.$checkout_form.trigger( 'submit' ); } else if ( errors.length ) { clear = true; stop = true; for ( var i = 0; i < errors.length; i++ ) { self.add_error( errors[ i ] ); } self.focus_errors(); } } if ( clear ) { clearInterval( interval ); } if ( stop ) { self.processing( 'stop' ); } checks++; }, 100 ); }; // initialize this.init(); return this; }; window.llms = window.llms || {}; window.llms.checkout = new llms_checkout(); } )( jQuery );
{ var g = gateways[i]; if ( typeof g === 'object' && g !== null ) { if ( g.bind !== undefined && 'function' === typeof g.bind ) { g.bind(); } } }
conditional_block
main.rs
#![cfg_attr(feature = "nightly-testing", feature(plugin))] #![cfg_attr(feature = "nightly-testing", plugin(clippy))] #[macro_use] extern crate clap; extern crate hoedown; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate toml; extern crate inflector; #[macro_use] extern crate lazy_static; extern crate regex; #[macro_use] extern crate log; extern crate env_logger; mod botocore; mod cargo; mod commands; mod config; mod service; mod util; mod doco; use std::path::Path; use clap::{Arg, App, SubCommand}; use service::Service; use config::ServiceConfig; use botocore::ServiceDefinition; fn main() { let matches = App::new("Rusoto Service Crate Generator") .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) .subcommand(SubCommand::with_name("check") .arg(Arg::with_name("services_config") .long("config") .short("c") .takes_value(true))) .subcommand(SubCommand::with_name("generate") .arg(Arg::with_name("services_config") .long("config") .short("c") .takes_value(true)) .arg(Arg::with_name("out_dir") .long("outdir") .short("o") .takes_value(true) .required(true))) .get_matches(); if let Some(matches) = matches.subcommand_matches("check")
if let Some(matches) = matches.subcommand_matches("generate") { let services_config_path = matches.value_of("services_config").unwrap(); let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file."); let out_dir = Path::new(matches.value_of("out_dir").unwrap()); commands::generate::generate_services(&service_configs, out_dir); } }
{ let services_config_path = matches.value_of("services_config").unwrap(); let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file."); commands::check::check(service_configs); }
conditional_block
main.rs
#![cfg_attr(feature = "nightly-testing", feature(plugin))] #![cfg_attr(feature = "nightly-testing", plugin(clippy))] #[macro_use] extern crate clap; extern crate hoedown; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate toml; extern crate inflector; #[macro_use] extern crate lazy_static; extern crate regex; #[macro_use] extern crate log; extern crate env_logger; mod botocore; mod cargo; mod commands; mod config; mod service;
use clap::{Arg, App, SubCommand}; use service::Service; use config::ServiceConfig; use botocore::ServiceDefinition; fn main() { let matches = App::new("Rusoto Service Crate Generator") .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) .subcommand(SubCommand::with_name("check") .arg(Arg::with_name("services_config") .long("config") .short("c") .takes_value(true))) .subcommand(SubCommand::with_name("generate") .arg(Arg::with_name("services_config") .long("config") .short("c") .takes_value(true)) .arg(Arg::with_name("out_dir") .long("outdir") .short("o") .takes_value(true) .required(true))) .get_matches(); if let Some(matches) = matches.subcommand_matches("check") { let services_config_path = matches.value_of("services_config").unwrap(); let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file."); commands::check::check(service_configs); } if let Some(matches) = matches.subcommand_matches("generate") { let services_config_path = matches.value_of("services_config").unwrap(); let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file."); let out_dir = Path::new(matches.value_of("out_dir").unwrap()); commands::generate::generate_services(&service_configs, out_dir); } }
mod util; mod doco; use std::path::Path;
random_line_split
main.rs
#![cfg_attr(feature = "nightly-testing", feature(plugin))] #![cfg_attr(feature = "nightly-testing", plugin(clippy))] #[macro_use] extern crate clap; extern crate hoedown; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate toml; extern crate inflector; #[macro_use] extern crate lazy_static; extern crate regex; #[macro_use] extern crate log; extern crate env_logger; mod botocore; mod cargo; mod commands; mod config; mod service; mod util; mod doco; use std::path::Path; use clap::{Arg, App, SubCommand}; use service::Service; use config::ServiceConfig; use botocore::ServiceDefinition; fn main()
{ let matches = App::new("Rusoto Service Crate Generator") .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) .subcommand(SubCommand::with_name("check") .arg(Arg::with_name("services_config") .long("config") .short("c") .takes_value(true))) .subcommand(SubCommand::with_name("generate") .arg(Arg::with_name("services_config") .long("config") .short("c") .takes_value(true)) .arg(Arg::with_name("out_dir") .long("outdir") .short("o") .takes_value(true) .required(true))) .get_matches(); if let Some(matches) = matches.subcommand_matches("check") { let services_config_path = matches.value_of("services_config").unwrap(); let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file."); commands::check::check(service_configs); } if let Some(matches) = matches.subcommand_matches("generate") { let services_config_path = matches.value_of("services_config").unwrap(); let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file."); let out_dir = Path::new(matches.value_of("out_dir").unwrap()); commands::generate::generate_services(&service_configs, out_dir); } }
identifier_body
main.rs
#![cfg_attr(feature = "nightly-testing", feature(plugin))] #![cfg_attr(feature = "nightly-testing", plugin(clippy))] #[macro_use] extern crate clap; extern crate hoedown; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate toml; extern crate inflector; #[macro_use] extern crate lazy_static; extern crate regex; #[macro_use] extern crate log; extern crate env_logger; mod botocore; mod cargo; mod commands; mod config; mod service; mod util; mod doco; use std::path::Path; use clap::{Arg, App, SubCommand}; use service::Service; use config::ServiceConfig; use botocore::ServiceDefinition; fn
() { let matches = App::new("Rusoto Service Crate Generator") .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) .subcommand(SubCommand::with_name("check") .arg(Arg::with_name("services_config") .long("config") .short("c") .takes_value(true))) .subcommand(SubCommand::with_name("generate") .arg(Arg::with_name("services_config") .long("config") .short("c") .takes_value(true)) .arg(Arg::with_name("out_dir") .long("outdir") .short("o") .takes_value(true) .required(true))) .get_matches(); if let Some(matches) = matches.subcommand_matches("check") { let services_config_path = matches.value_of("services_config").unwrap(); let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file."); commands::check::check(service_configs); } if let Some(matches) = matches.subcommand_matches("generate") { let services_config_path = matches.value_of("services_config").unwrap(); let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file."); let out_dir = Path::new(matches.value_of("out_dir").unwrap()); commands::generate::generate_services(&service_configs, out_dir); } }
main
identifier_name
ServicesPanel.spec.tsx
/// <reference types='jest' /> import * as React from 'react'; import ServicesPanel from '../ServicesPanel'; import Cases from './ServicesPanel.cases'; import { shallow, mount, render } from 'enzyme'; describe('ServicesPanel', () => { let servicesPanel:any; beforeEach(()=>{ servicesPanel = mount(<ServicesPanel {...Cases['Default']}/>) }); it('should render correctly', () => { expect(servicesPanel.find('Dropdown').length).toEqual(1); expect(servicesPanel.find('ServicesList').length).toEqual(1); expect(servicesPanel.find('Input').length).toEqual(1); }); it('should render the roles dropdown with the services prop roles as items', () => { // let roles: string[] = []; // servicesPanel.props().services.forEach((service:any) => { // if (roles.indexOf(service.roleId) === -1) { // roles.push(service.roleId); // } // }); // let dropDownItemsTexts = servicesPanel.find('DropdownItem .role').map((node:any) => { return node.text()}); // expect(JSON.stringify(roles.sort())).toEqual(JSON.stringify(dropDownItemsTexts.sort())); }); it('should render only services with the selected role', () => { // let activeRole = 'Mollis.'; // servicesPanel.setState({ // activeRole: activeRole // });
// return value === true; // }); // expect(allHaveActiveRole).toEqual(true); }); it('should render only services with the selected role when a search value is entered by user', () => { // let activeRole = 'Mollis.'; // servicesPanel.setState({ // activeRole: activeRole, // searhValue: 'test' // }); // let allHaveActiveRole = servicesPanel.find('ServiceCard').map((node:any) => { // return node.props().service.roles.indexOf(activeRole) > -1; // }).every((value:boolean) => { // return value === true; // }); // expect(allHaveActiveRole).toEqual(true); }); it('should render the Not found services message when search is performed an it returns no services', () => { // servicesPanel.setState({ // searchValue:'mycrazytestsearchcriteria', // activeRole:'Mollis.' // }); // expect(servicesPanel.find('h3').first().text()).toEqual('No services found'); }); it('should render the right search indicator in search bar depending on searching state', () => { // servicesPanel.setState({loadingSearch:false, searchValue:''}); // expect(servicesPanel.find('.rowHead').first().find('i').length).toEqual(0); // servicesPanel.setState({loadingSearch:false, searchValue:'mysearchcriteria'}); // expect(servicesPanel.find('.rowHead').first().find('i').length).toEqual(1); // expect(servicesPanel.find('.rowHead').first().find('i').html()).toContain('fa fa-times fa-lg'); // servicesPanel.setState({loadingSearch:true, searchValue:'mysearchcriteria'}); // expect(servicesPanel.find('.rowHead').first().find('i').length).toEqual(1); // expect(servicesPanel.find('.rowHead').first().find('i').html()).toContain('fa fa-pulse fa-spinner'); }); it(`should set the right searching state after a second depending on the searchOnChangeMethod actioned by user input`, (done) => { done(); // servicesPanel.instance().searchOnChange({target:{value:'mysearchcriteria'}, persist: () => {}}); // expect(servicesPanel.state().searchValue).toEqual('mysearchcriteria'); // expect(servicesPanel.state().loadingSearch).toEqual(true); // try { // setTimeout(()=>{ // expect(servicesPanel.state().loadingSearch).toEqual(false); // done(); // }, 2000); // }catch (e){ // done.fail(e); // } }); });
// let allHaveActiveRole = servicesPanel.find('ServiceCard').map((node:any) => { // return node.props().service.roles.indexOf(activeRole) > -1; // }).every((value:boolean) => {
random_line_split
DateArrayType.js
/*! * Module dependencies. */ var util = require('util'), moment = require('moment'), super_ = require('../Type'); /** * Date FieldType Constructor * @extends Field * @api public */ function datearray(list, path, options) { this._nativeType = [Date]; this._defaultSize = 'medium'; this._underscoreMethods = ['format']; this._properties = ['formatString']; this.parseFormatString = options.parseFormat || 'YYYY-MM-DD'; this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY'); if (this.formatString && 'string' !== typeof this.formatString) { throw new Error('FieldType.Date: options.format must be a string.'); } datearray.super_.call(this, list, path, options); } /*! * Inherit from Field */ util.inherits(datearray, super_); /** * Formats the field value * * @api public */ datearray.prototype.format = function(item, format) { if (format || this.formatString) { return item.get(this.path) ? moment(item.get(this.path)).format(format || this.formatString) : ''; } else { return item.get(this.path) || ''; } }; /** * Checks that a valid array of dates has been provided in a data object * * An empty value clears the stored value and is considered valid * * @api public */ datearray.prototype.inputIsValid = function(data, required, item) { var value = this.getValueFromData(data); var parseFormatString = this.parseFormatString; if ('string' === typeof value) { if (!moment(value, parseFormatString).isValid()) { return false; } value = [value]; } if (required) { if (value === undefined && item && item.get(this.path) && item.get(this.path).length) { return true; } if (value === undefined || !Array.isArray(value)) { return false; } if (Array.isArray(value) && !value.length) { return false; } } if (Array.isArray(value)) { // filter out empty fields value = value.filter(function(date) { return date.trim() !== ''; }); // if there are no values left, and requried is true, return false if (required && !value.length) { return false; } // if any date in the array is invalid, return false if (value.some(function (dateValue) { return !moment(dateValue, parseFormatString).isValid(); })) { return false; } } return (value === undefined || Array.isArray(value)); }; /** * Updates the value for this field in the item from a data object * * @api public */ datearray.prototype.updateItem = function(item, data, callback) { var value = this.getValueFromData(data); if (value !== undefined) {
if (Array.isArray(value)) { // Only save valid dates value = value.filter(function(date) { return moment(date).isValid(); }); } if (value === null) { value = []; } if ('string' === typeof value) { if (moment(value).isValid()) { value = [value]; } } if (Array.isArray(value)) { item.set(this.path, value); } } else item.set(this.path, []); process.nextTick(callback); }; /*! * Export class */ module.exports = datearray;
random_line_split
DateArrayType.js
/*! * Module dependencies. */ var util = require('util'), moment = require('moment'), super_ = require('../Type'); /** * Date FieldType Constructor * @extends Field * @api public */ function datearray(list, path, options) { this._nativeType = [Date]; this._defaultSize = 'medium'; this._underscoreMethods = ['format']; this._properties = ['formatString']; this.parseFormatString = options.parseFormat || 'YYYY-MM-DD'; this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY'); if (this.formatString && 'string' !== typeof this.formatString) { throw new Error('FieldType.Date: options.format must be a string.'); } datearray.super_.call(this, list, path, options); } /*! * Inherit from Field */ util.inherits(datearray, super_); /** * Formats the field value * * @api public */ datearray.prototype.format = function(item, format) { if (format || this.formatString) { return item.get(this.path) ? moment(item.get(this.path)).format(format || this.formatString) : ''; } else { return item.get(this.path) || ''; } }; /** * Checks that a valid array of dates has been provided in a data object * * An empty value clears the stored value and is considered valid * * @api public */ datearray.prototype.inputIsValid = function(data, required, item) { var value = this.getValueFromData(data); var parseFormatString = this.parseFormatString; if ('string' === typeof value) { if (!moment(value, parseFormatString).isValid()) { return false; } value = [value]; } if (required) { if (value === undefined && item && item.get(this.path) && item.get(this.path).length) { return true; } if (value === undefined || !Array.isArray(value)) { return false; } if (Array.isArray(value) && !value.length) { return false; } } if (Array.isArray(value)) { // filter out empty fields value = value.filter(function(date) { return date.trim() !== ''; }); // if there are no values left, and requried is true, return false if (required && !value.length) { return false; } // if any date in the array is invalid, return false if (value.some(function (dateValue) { return !moment(dateValue, parseFormatString).isValid(); })) { return false; } } return (value === undefined || Array.isArray(value)); }; /** * Updates the value for this field in the item from a data object * * @api public */ datearray.prototype.updateItem = function(item, data, callback) { var value = this.getValueFromData(data); if (value !== undefined) { if (Array.isArray(value)) { // Only save valid dates value = value.filter(function(date) { return moment(date).isValid(); }); } if (value === null) { value = []; } if ('string' === typeof value) { if (moment(value).isValid())
} if (Array.isArray(value)) { item.set(this.path, value); } } else item.set(this.path, []); process.nextTick(callback); }; /*! * Export class */ module.exports = datearray;
{ value = [value]; }
conditional_block
DateArrayType.js
/*! * Module dependencies. */ var util = require('util'), moment = require('moment'), super_ = require('../Type'); /** * Date FieldType Constructor * @extends Field * @api public */ function datearray(list, path, options)
/*! * Inherit from Field */ util.inherits(datearray, super_); /** * Formats the field value * * @api public */ datearray.prototype.format = function(item, format) { if (format || this.formatString) { return item.get(this.path) ? moment(item.get(this.path)).format(format || this.formatString) : ''; } else { return item.get(this.path) || ''; } }; /** * Checks that a valid array of dates has been provided in a data object * * An empty value clears the stored value and is considered valid * * @api public */ datearray.prototype.inputIsValid = function(data, required, item) { var value = this.getValueFromData(data); var parseFormatString = this.parseFormatString; if ('string' === typeof value) { if (!moment(value, parseFormatString).isValid()) { return false; } value = [value]; } if (required) { if (value === undefined && item && item.get(this.path) && item.get(this.path).length) { return true; } if (value === undefined || !Array.isArray(value)) { return false; } if (Array.isArray(value) && !value.length) { return false; } } if (Array.isArray(value)) { // filter out empty fields value = value.filter(function(date) { return date.trim() !== ''; }); // if there are no values left, and requried is true, return false if (required && !value.length) { return false; } // if any date in the array is invalid, return false if (value.some(function (dateValue) { return !moment(dateValue, parseFormatString).isValid(); })) { return false; } } return (value === undefined || Array.isArray(value)); }; /** * Updates the value for this field in the item from a data object * * @api public */ datearray.prototype.updateItem = function(item, data, callback) { var value = this.getValueFromData(data); if (value !== undefined) { if (Array.isArray(value)) { // Only save valid dates value = value.filter(function(date) { return moment(date).isValid(); }); } if (value === null) { value = []; } if ('string' === typeof value) { if (moment(value).isValid()) { value = [value]; } } if (Array.isArray(value)) { item.set(this.path, value); } } else item.set(this.path, []); process.nextTick(callback); }; /*! * Export class */ module.exports = datearray;
{ this._nativeType = [Date]; this._defaultSize = 'medium'; this._underscoreMethods = ['format']; this._properties = ['formatString']; this.parseFormatString = options.parseFormat || 'YYYY-MM-DD'; this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY'); if (this.formatString && 'string' !== typeof this.formatString) { throw new Error('FieldType.Date: options.format must be a string.'); } datearray.super_.call(this, list, path, options); }
identifier_body
DateArrayType.js
/*! * Module dependencies. */ var util = require('util'), moment = require('moment'), super_ = require('../Type'); /** * Date FieldType Constructor * @extends Field * @api public */ function
(list, path, options) { this._nativeType = [Date]; this._defaultSize = 'medium'; this._underscoreMethods = ['format']; this._properties = ['formatString']; this.parseFormatString = options.parseFormat || 'YYYY-MM-DD'; this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY'); if (this.formatString && 'string' !== typeof this.formatString) { throw new Error('FieldType.Date: options.format must be a string.'); } datearray.super_.call(this, list, path, options); } /*! * Inherit from Field */ util.inherits(datearray, super_); /** * Formats the field value * * @api public */ datearray.prototype.format = function(item, format) { if (format || this.formatString) { return item.get(this.path) ? moment(item.get(this.path)).format(format || this.formatString) : ''; } else { return item.get(this.path) || ''; } }; /** * Checks that a valid array of dates has been provided in a data object * * An empty value clears the stored value and is considered valid * * @api public */ datearray.prototype.inputIsValid = function(data, required, item) { var value = this.getValueFromData(data); var parseFormatString = this.parseFormatString; if ('string' === typeof value) { if (!moment(value, parseFormatString).isValid()) { return false; } value = [value]; } if (required) { if (value === undefined && item && item.get(this.path) && item.get(this.path).length) { return true; } if (value === undefined || !Array.isArray(value)) { return false; } if (Array.isArray(value) && !value.length) { return false; } } if (Array.isArray(value)) { // filter out empty fields value = value.filter(function(date) { return date.trim() !== ''; }); // if there are no values left, and requried is true, return false if (required && !value.length) { return false; } // if any date in the array is invalid, return false if (value.some(function (dateValue) { return !moment(dateValue, parseFormatString).isValid(); })) { return false; } } return (value === undefined || Array.isArray(value)); }; /** * Updates the value for this field in the item from a data object * * @api public */ datearray.prototype.updateItem = function(item, data, callback) { var value = this.getValueFromData(data); if (value !== undefined) { if (Array.isArray(value)) { // Only save valid dates value = value.filter(function(date) { return moment(date).isValid(); }); } if (value === null) { value = []; } if ('string' === typeof value) { if (moment(value).isValid()) { value = [value]; } } if (Array.isArray(value)) { item.set(this.path, value); } } else item.set(this.path, []); process.nextTick(callback); }; /*! * Export class */ module.exports = datearray;
datearray
identifier_name
TestClz.rs
/* * Copyright (C) 2016 The Android Open Source Project * * 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. */ // Don't edit this file! It is auto-generated by frameworks/rs/api/generate.sh. #pragma version(1) #pragma rs java_package_name(android.renderscript.cts) char __attribute__((kernel)) testClzCharChar(char inValue) { return clz(inValue); } char2 __attribute__((kernel)) testClzChar2Char2(char2 inValue) { return clz(inValue); } char3 __attribute__((kernel)) testClzChar3Char3(char3 inValue) { return clz(inValue); } char4 __attribute__((kernel)) testClzChar4Char4(char4 inValue) { return clz(inValue); } uchar __attribute__((kernel)) testClzUcharUchar(uchar inValue) { return clz(inValue); } uchar2 __attribute__((kernel)) testClzUchar2Uchar2(uchar2 inValue) { return clz(inValue); } uchar3 __attribute__((kernel)) testClzUchar3Uchar3(uchar3 inValue) { return clz(inValue); } uchar4 __attribute__((kernel)) testClzUchar4Uchar4(uchar4 inValue) { return clz(inValue); } short __attribute__((kernel)) testClzShortShort(short inValue) { return clz(inValue); } short2 __attribute__((kernel)) testClzShort2Short2(short2 inValue) { return clz(inValue); } short3 __attribute__((kernel)) testClzShort3Short3(short3 inValue) { return clz(inValue); } short4 __attribute__((kernel)) testClzShort4Short4(short4 inValue) { return clz(inValue); } ushort __attribute__((kernel)) testClzUshortUshort(ushort inValue) { return clz(inValue); } ushort2 __attribute__((kernel)) testClzUshort2Ushort2(ushort2 inValue) { return clz(inValue); } ushort3 __attribute__((kernel)) testClzUshort3Ushort3(ushort3 inValue) { return clz(inValue); } ushort4 __attribute__((kernel)) testClzUshort4Ushort4(ushort4 inValue) {
} int2 __attribute__((kernel)) testClzInt2Int2(int2 inValue) { return clz(inValue); } int3 __attribute__((kernel)) testClzInt3Int3(int3 inValue) { return clz(inValue); } int4 __attribute__((kernel)) testClzInt4Int4(int4 inValue) { return clz(inValue); } uint __attribute__((kernel)) testClzUintUint(uint inValue) { return clz(inValue); } uint2 __attribute__((kernel)) testClzUint2Uint2(uint2 inValue) { return clz(inValue); } uint3 __attribute__((kernel)) testClzUint3Uint3(uint3 inValue) { return clz(inValue); } uint4 __attribute__((kernel)) testClzUint4Uint4(uint4 inValue) { return clz(inValue); }
return clz(inValue); } int __attribute__((kernel)) testClzIntInt(int inValue) { return clz(inValue);
random_line_split
pagination.ts
import { Next, Request, Response } from "restify"; export interface PaginationMiddlewareConfig { perPage?: number; count: number; } export interface PaginatedResponse extends Response { sendPaginatedResponse(status?: any, body?: any, headers?: { [header: string]: string }): any; } export interface PaginatedRequest extends Request { per_page: number; page: number; } export class PaginationMiddleware { /** * Pagination Middleware Request handler * * @param config pagination options */ public handlePagination(config: PaginationMiddlewareConfig) { if (config.perPage === undefined) { config.perPage = 30; } return (req: PaginatedRequest, res: PaginatedResponse, next: Next) => { const page = (req.query.page !== undefined) ? Number(req.query.page) : 1; const perPage = (req.query.per_page !== undefined) ? Number(req.query.per_page) : config.perPage; res.sendPaginatedResponse = (code: number, object: any, headers?: { [header: string]: string }): any => { const link: string[] = []; const baseUrl: string = (req.isSecure() ? "https://" : "http://") + req.headers.host; const lastPage = config.count / perPage; // If we are not on the last page, display the last page and next if (page < lastPage) { link.push("<" + baseUrl + "?page=" + (page + 1) + "&per_page=" + perPage + '>; rel="next"'); link.push("<" + baseUrl + "?page=" + lastPage + "&per_page=" + perPage + '>; rel="last"'); } // If we are not on the first page, display the first page if (page > 1)
res.setHeader("link", link); res.send(code, object, headers); }; next(); }; } }
{ link.push("<" + baseUrl + "?page=1&per_page=" + perPage + '>; rel="first"'); link.push("<" + baseUrl + "?page=" + (page - 1) + "&per_page=" + perPage + '>; rel="prev"'); }
conditional_block
pagination.ts
import { Next, Request, Response } from "restify"; export interface PaginationMiddlewareConfig { perPage?: number; count: number; } export interface PaginatedResponse extends Response { sendPaginatedResponse(status?: any, body?: any, headers?: { [header: string]: string }): any; } export interface PaginatedRequest extends Request { per_page: number; page: number; } export class PaginationMiddleware { /** * Pagination Middleware Request handler * * @param config pagination options */ public handlePagination(config: PaginationMiddlewareConfig) { if (config.perPage === undefined) { config.perPage = 30; } return (req: PaginatedRequest, res: PaginatedResponse, next: Next) => { const page = (req.query.page !== undefined) ? Number(req.query.page) : 1; const perPage = (req.query.per_page !== undefined) ? Number(req.query.per_page) : config.perPage; res.sendPaginatedResponse = (code: number, object: any, headers?: { [header: string]: string }): any => { const link: string[] = []; const baseUrl: string = (req.isSecure() ? "https://" : "http://") + req.headers.host;
link.push("<" + baseUrl + "?page=" + (page + 1) + "&per_page=" + perPage + '>; rel="next"'); link.push("<" + baseUrl + "?page=" + lastPage + "&per_page=" + perPage + '>; rel="last"'); } // If we are not on the first page, display the first page if (page > 1) { link.push("<" + baseUrl + "?page=1&per_page=" + perPage + '>; rel="first"'); link.push("<" + baseUrl + "?page=" + (page - 1) + "&per_page=" + perPage + '>; rel="prev"'); } res.setHeader("link", link); res.send(code, object, headers); }; next(); }; } }
const lastPage = config.count / perPage; // If we are not on the last page, display the last page and next if (page < lastPage) {
random_line_split
pagination.ts
import { Next, Request, Response } from "restify"; export interface PaginationMiddlewareConfig { perPage?: number; count: number; } export interface PaginatedResponse extends Response { sendPaginatedResponse(status?: any, body?: any, headers?: { [header: string]: string }): any; } export interface PaginatedRequest extends Request { per_page: number; page: number; } export class PaginationMiddleware { /** * Pagination Middleware Request handler * * @param config pagination options */ public
(config: PaginationMiddlewareConfig) { if (config.perPage === undefined) { config.perPage = 30; } return (req: PaginatedRequest, res: PaginatedResponse, next: Next) => { const page = (req.query.page !== undefined) ? Number(req.query.page) : 1; const perPage = (req.query.per_page !== undefined) ? Number(req.query.per_page) : config.perPage; res.sendPaginatedResponse = (code: number, object: any, headers?: { [header: string]: string }): any => { const link: string[] = []; const baseUrl: string = (req.isSecure() ? "https://" : "http://") + req.headers.host; const lastPage = config.count / perPage; // If we are not on the last page, display the last page and next if (page < lastPage) { link.push("<" + baseUrl + "?page=" + (page + 1) + "&per_page=" + perPage + '>; rel="next"'); link.push("<" + baseUrl + "?page=" + lastPage + "&per_page=" + perPage + '>; rel="last"'); } // If we are not on the first page, display the first page if (page > 1) { link.push("<" + baseUrl + "?page=1&per_page=" + perPage + '>; rel="first"'); link.push("<" + baseUrl + "?page=" + (page - 1) + "&per_page=" + perPage + '>; rel="prev"'); } res.setHeader("link", link); res.send(code, object, headers); }; next(); }; } }
handlePagination
identifier_name
object-util.d.ts
/** * Sets the value of a field. * * @param {Object} obj The object * @param {string} field The path to a field. Can include dots (.) * @param {*} val The value to set the field * @return {Object} The modified object */ export function setFieldValue(obj: any, field: string, val: any): any; /** * Pick a subset of fields from an object * * @param {Object} obj The object * @param {string[]} fields The fields to pick. Can include dots (.) * @param {Object} [options] The options * @param {boolean} [options.excludeUndefinedValues=false] Whether undefined values should be included in returned object.
*/ export function pick(obj: any, fields: string[], options?: { excludeUndefinedValues: boolean; }): any; /** * Determines if embedded document. * * @param {Model} doc The Mongoose document * @return {boolean} True if embedded document, False otherwise. */ export function isEmbeddedDocument(doc: any): boolean;
* @return {Object} An object containing only those fields that have been picked
random_line_split
type_variable.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. pub use self::RelationDir::*; use self::TypeVariableValue::*; use self::UndoEntry::*; use middle::ty::{mod, Ty}; use std::mem; use util::snapshot_vec as sv; pub struct TypeVariableTable<'tcx> { values: sv::SnapshotVec<TypeVariableData<'tcx>,UndoEntry,Delegate>, } struct TypeVariableData<'tcx> { value: TypeVariableValue<'tcx>, diverging: bool } enum TypeVariableValue<'tcx> { Known(Ty<'tcx>), Bounded(Vec<Relation>), } pub struct Snapshot { snapshot: sv::Snapshot } enum UndoEntry { // The type of the var was specified. SpecifyVar(ty::TyVid, Vec<Relation>), Relate(ty::TyVid, ty::TyVid), } struct Delegate; type Relation = (RelationDir, ty::TyVid); #[deriving(PartialEq,Show)] pub enum RelationDir { SubtypeOf, SupertypeOf, EqTo } impl RelationDir { fn opposite(self) -> RelationDir { match self { SubtypeOf => SupertypeOf, SupertypeOf => SubtypeOf, EqTo => EqTo } } } impl<'tcx> TypeVariableTable<'tcx> { pub fn new() -> TypeVariableTable<'tcx> { TypeVariableTable { values: sv::SnapshotVec::new(Delegate) } } fn relations<'a>(&'a mut self, a: ty::TyVid) -> &'a mut Vec<Relation> { relations(self.values.get_mut(a.index)) } pub fn var_diverges<'a>(&'a self, vid: ty::TyVid) -> bool { self.values.get(vid.index).diverging } pub fn relate_vars(&mut self, a: ty::TyVid, dir: RelationDir, b: ty::TyVid) { /*! * Records that `a <: b`, `a :> b`, or `a == b`, depending on `dir`. * * Precondition: neither `a` nor `b` are known. */ if a != b { self.relations(a).push((dir, b)); self.relations(b).push((dir.opposite(), a)); self.values.record(Relate(a, b)); } } pub fn instantiate_and_push( &mut self, vid: ty::TyVid, ty: Ty<'tcx>, stack: &mut Vec<(Ty<'tcx>, RelationDir, ty::TyVid)>) { /*!
* dir, vid1)` where `vid1` is some other variable id. */ let old_value = { let value_ptr = &mut self.values.get_mut(vid.index).value; mem::replace(value_ptr, Known(ty)) }; let relations = match old_value { Bounded(b) => b, Known(_) => panic!("Asked to instantiate variable that is \ already instantiated") }; for &(dir, vid) in relations.iter() { stack.push((ty, dir, vid)); } self.values.record(SpecifyVar(vid, relations)); } pub fn new_var(&mut self, diverging: bool) -> ty::TyVid { let index = self.values.push(TypeVariableData { value: Bounded(vec![]), diverging: diverging }); ty::TyVid { index: index } } pub fn probe(&self, vid: ty::TyVid) -> Option<Ty<'tcx>> { match self.values.get(vid.index).value { Bounded(..) => None, Known(t) => Some(t) } } pub fn replace_if_possible(&self, t: Ty<'tcx>) -> Ty<'tcx> { match t.sty { ty::ty_infer(ty::TyVar(v)) => { match self.probe(v) { None => t, Some(u) => u } } _ => t, } } pub fn snapshot(&mut self) -> Snapshot { Snapshot { snapshot: self.values.start_snapshot() } } pub fn rollback_to(&mut self, s: Snapshot) { self.values.rollback_to(s.snapshot); } pub fn commit(&mut self, s: Snapshot) { self.values.commit(s.snapshot); } } impl<'tcx> sv::SnapshotVecDelegate<TypeVariableData<'tcx>,UndoEntry> for Delegate { fn reverse(&mut self, values: &mut Vec<TypeVariableData>, action: UndoEntry) { match action { SpecifyVar(vid, relations) => { values[vid.index].value = Bounded(relations); } Relate(a, b) => { relations(&mut (*values)[a.index]).pop(); relations(&mut (*values)[b.index]).pop(); } } } } fn relations<'a>(v: &'a mut TypeVariableData) -> &'a mut Vec<Relation> { match v.value { Known(_) => panic!("var_sub_var: variable is known"), Bounded(ref mut relations) => relations } }
* Instantiates `vid` with the type `ty` and then pushes an * entry onto `stack` for each of the relations of `vid` to * other variables. The relations will have the form `(ty,
random_line_split
type_variable.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. pub use self::RelationDir::*; use self::TypeVariableValue::*; use self::UndoEntry::*; use middle::ty::{mod, Ty}; use std::mem; use util::snapshot_vec as sv; pub struct TypeVariableTable<'tcx> { values: sv::SnapshotVec<TypeVariableData<'tcx>,UndoEntry,Delegate>, } struct TypeVariableData<'tcx> { value: TypeVariableValue<'tcx>, diverging: bool } enum TypeVariableValue<'tcx> { Known(Ty<'tcx>), Bounded(Vec<Relation>), } pub struct Snapshot { snapshot: sv::Snapshot } enum UndoEntry { // The type of the var was specified. SpecifyVar(ty::TyVid, Vec<Relation>), Relate(ty::TyVid, ty::TyVid), } struct Delegate; type Relation = (RelationDir, ty::TyVid); #[deriving(PartialEq,Show)] pub enum RelationDir { SubtypeOf, SupertypeOf, EqTo } impl RelationDir { fn opposite(self) -> RelationDir { match self { SubtypeOf => SupertypeOf, SupertypeOf => SubtypeOf, EqTo => EqTo } } } impl<'tcx> TypeVariableTable<'tcx> { pub fn new() -> TypeVariableTable<'tcx> { TypeVariableTable { values: sv::SnapshotVec::new(Delegate) } } fn relations<'a>(&'a mut self, a: ty::TyVid) -> &'a mut Vec<Relation> { relations(self.values.get_mut(a.index)) } pub fn var_diverges<'a>(&'a self, vid: ty::TyVid) -> bool { self.values.get(vid.index).diverging } pub fn relate_vars(&mut self, a: ty::TyVid, dir: RelationDir, b: ty::TyVid) { /*! * Records that `a <: b`, `a :> b`, or `a == b`, depending on `dir`. * * Precondition: neither `a` nor `b` are known. */ if a != b { self.relations(a).push((dir, b)); self.relations(b).push((dir.opposite(), a)); self.values.record(Relate(a, b)); } } pub fn instantiate_and_push( &mut self, vid: ty::TyVid, ty: Ty<'tcx>, stack: &mut Vec<(Ty<'tcx>, RelationDir, ty::TyVid)>) { /*! * Instantiates `vid` with the type `ty` and then pushes an * entry onto `stack` for each of the relations of `vid` to * other variables. The relations will have the form `(ty, * dir, vid1)` where `vid1` is some other variable id. */ let old_value = { let value_ptr = &mut self.values.get_mut(vid.index).value; mem::replace(value_ptr, Known(ty)) }; let relations = match old_value { Bounded(b) => b, Known(_) => panic!("Asked to instantiate variable that is \ already instantiated") }; for &(dir, vid) in relations.iter() { stack.push((ty, dir, vid)); } self.values.record(SpecifyVar(vid, relations)); } pub fn new_var(&mut self, diverging: bool) -> ty::TyVid { let index = self.values.push(TypeVariableData { value: Bounded(vec![]), diverging: diverging }); ty::TyVid { index: index } } pub fn probe(&self, vid: ty::TyVid) -> Option<Ty<'tcx>>
pub fn replace_if_possible(&self, t: Ty<'tcx>) -> Ty<'tcx> { match t.sty { ty::ty_infer(ty::TyVar(v)) => { match self.probe(v) { None => t, Some(u) => u } } _ => t, } } pub fn snapshot(&mut self) -> Snapshot { Snapshot { snapshot: self.values.start_snapshot() } } pub fn rollback_to(&mut self, s: Snapshot) { self.values.rollback_to(s.snapshot); } pub fn commit(&mut self, s: Snapshot) { self.values.commit(s.snapshot); } } impl<'tcx> sv::SnapshotVecDelegate<TypeVariableData<'tcx>,UndoEntry> for Delegate { fn reverse(&mut self, values: &mut Vec<TypeVariableData>, action: UndoEntry) { match action { SpecifyVar(vid, relations) => { values[vid.index].value = Bounded(relations); } Relate(a, b) => { relations(&mut (*values)[a.index]).pop(); relations(&mut (*values)[b.index]).pop(); } } } } fn relations<'a>(v: &'a mut TypeVariableData) -> &'a mut Vec<Relation> { match v.value { Known(_) => panic!("var_sub_var: variable is known"), Bounded(ref mut relations) => relations } }
{ match self.values.get(vid.index).value { Bounded(..) => None, Known(t) => Some(t) } }
identifier_body
type_variable.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. pub use self::RelationDir::*; use self::TypeVariableValue::*; use self::UndoEntry::*; use middle::ty::{mod, Ty}; use std::mem; use util::snapshot_vec as sv; pub struct TypeVariableTable<'tcx> { values: sv::SnapshotVec<TypeVariableData<'tcx>,UndoEntry,Delegate>, } struct TypeVariableData<'tcx> { value: TypeVariableValue<'tcx>, diverging: bool } enum TypeVariableValue<'tcx> { Known(Ty<'tcx>), Bounded(Vec<Relation>), } pub struct Snapshot { snapshot: sv::Snapshot } enum UndoEntry { // The type of the var was specified. SpecifyVar(ty::TyVid, Vec<Relation>), Relate(ty::TyVid, ty::TyVid), } struct Delegate; type Relation = (RelationDir, ty::TyVid); #[deriving(PartialEq,Show)] pub enum RelationDir { SubtypeOf, SupertypeOf, EqTo } impl RelationDir { fn opposite(self) -> RelationDir { match self { SubtypeOf => SupertypeOf, SupertypeOf => SubtypeOf, EqTo => EqTo } } } impl<'tcx> TypeVariableTable<'tcx> { pub fn new() -> TypeVariableTable<'tcx> { TypeVariableTable { values: sv::SnapshotVec::new(Delegate) } } fn relations<'a>(&'a mut self, a: ty::TyVid) -> &'a mut Vec<Relation> { relations(self.values.get_mut(a.index)) } pub fn var_diverges<'a>(&'a self, vid: ty::TyVid) -> bool { self.values.get(vid.index).diverging } pub fn relate_vars(&mut self, a: ty::TyVid, dir: RelationDir, b: ty::TyVid) { /*! * Records that `a <: b`, `a :> b`, or `a == b`, depending on `dir`. * * Precondition: neither `a` nor `b` are known. */ if a != b { self.relations(a).push((dir, b)); self.relations(b).push((dir.opposite(), a)); self.values.record(Relate(a, b)); } } pub fn instantiate_and_push( &mut self, vid: ty::TyVid, ty: Ty<'tcx>, stack: &mut Vec<(Ty<'tcx>, RelationDir, ty::TyVid)>) { /*! * Instantiates `vid` with the type `ty` and then pushes an * entry onto `stack` for each of the relations of `vid` to * other variables. The relations will have the form `(ty, * dir, vid1)` where `vid1` is some other variable id. */ let old_value = { let value_ptr = &mut self.values.get_mut(vid.index).value; mem::replace(value_ptr, Known(ty)) }; let relations = match old_value { Bounded(b) => b, Known(_) => panic!("Asked to instantiate variable that is \ already instantiated") }; for &(dir, vid) in relations.iter() { stack.push((ty, dir, vid)); } self.values.record(SpecifyVar(vid, relations)); } pub fn new_var(&mut self, diverging: bool) -> ty::TyVid { let index = self.values.push(TypeVariableData { value: Bounded(vec![]), diverging: diverging }); ty::TyVid { index: index } } pub fn probe(&self, vid: ty::TyVid) -> Option<Ty<'tcx>> { match self.values.get(vid.index).value { Bounded(..) => None, Known(t) => Some(t) } } pub fn replace_if_possible(&self, t: Ty<'tcx>) -> Ty<'tcx> { match t.sty { ty::ty_infer(ty::TyVar(v)) => { match self.probe(v) { None => t, Some(u) => u } } _ => t, } } pub fn
(&mut self) -> Snapshot { Snapshot { snapshot: self.values.start_snapshot() } } pub fn rollback_to(&mut self, s: Snapshot) { self.values.rollback_to(s.snapshot); } pub fn commit(&mut self, s: Snapshot) { self.values.commit(s.snapshot); } } impl<'tcx> sv::SnapshotVecDelegate<TypeVariableData<'tcx>,UndoEntry> for Delegate { fn reverse(&mut self, values: &mut Vec<TypeVariableData>, action: UndoEntry) { match action { SpecifyVar(vid, relations) => { values[vid.index].value = Bounded(relations); } Relate(a, b) => { relations(&mut (*values)[a.index]).pop(); relations(&mut (*values)[b.index]).pop(); } } } } fn relations<'a>(v: &'a mut TypeVariableData) -> &'a mut Vec<Relation> { match v.value { Known(_) => panic!("var_sub_var: variable is known"), Bounded(ref mut relations) => relations } }
snapshot
identifier_name
domparser.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::DOMParserBinding; use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{Text_html, Text_xml}; use dom::bindings::utils::{DOMString, Fallible, Reflector, Reflectable, reflect_dom_object}; use dom::document::{AbstractDocument, Document, XML}; use dom::element::HTMLHtmlElementTypeId; use dom::htmldocument::HTMLDocument; use dom::htmlelement::HTMLElement; use dom::htmlhtmlelement::HTMLHtmlElement; use dom::node::Node; use dom::window::Window; use js::jsapi::{JSContext, JSObject}; pub struct DOMParser { owner: @mut Window, //XXXjdm Document instead? reflector_: Reflector } impl DOMParser { pub fn new_inherited(owner: @mut Window) -> DOMParser { DOMParser { owner: owner, reflector_: Reflector::new() } } pub fn new(owner: @mut Window) -> @mut DOMParser { reflect_dom_object(@mut DOMParser::new_inherited(owner), owner, DOMParserBinding::Wrap) } pub fn Constructor(owner: @mut Window) -> Fallible<@mut DOMParser> { Ok(DOMParser::new(owner)) } pub fn ParseFromString(&self, _s: &DOMString, ty: DOMParserBinding::SupportedType) -> Fallible<AbstractDocument> { let cx = self.owner.get_cx(); let document = match ty { Text_html => { HTMLDocument::new(self.owner) } Text_xml => { AbstractDocument::as_abstract(cx, @mut Document::new(self.owner, XML)) } _ => { fail!("unsupported document type") } }; let root = @HTMLHtmlElement { htmlelement: HTMLElement::new(HTMLHtmlElementTypeId, ~"html", document) }; let root = unsafe { Node::as_abstract_node(cx, root) }; document.set_root(root); Ok(document) } } impl Reflectable for DOMParser { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector {
unreachable!(); } fn GetParentObject(&self, _cx: *JSContext) -> Option<@mut Reflectable> { Some(self.owner as @mut Reflectable) } }
&mut self.reflector_ } fn wrap_object_shared(@mut self, _cx: *JSContext, _scope: *JSObject) -> *JSObject {
random_line_split
domparser.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::DOMParserBinding; use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{Text_html, Text_xml}; use dom::bindings::utils::{DOMString, Fallible, Reflector, Reflectable, reflect_dom_object}; use dom::document::{AbstractDocument, Document, XML}; use dom::element::HTMLHtmlElementTypeId; use dom::htmldocument::HTMLDocument; use dom::htmlelement::HTMLElement; use dom::htmlhtmlelement::HTMLHtmlElement; use dom::node::Node; use dom::window::Window; use js::jsapi::{JSContext, JSObject}; pub struct DOMParser { owner: @mut Window, //XXXjdm Document instead? reflector_: Reflector } impl DOMParser { pub fn new_inherited(owner: @mut Window) -> DOMParser { DOMParser { owner: owner, reflector_: Reflector::new() } } pub fn new(owner: @mut Window) -> @mut DOMParser { reflect_dom_object(@mut DOMParser::new_inherited(owner), owner, DOMParserBinding::Wrap) } pub fn Constructor(owner: @mut Window) -> Fallible<@mut DOMParser> { Ok(DOMParser::new(owner)) } pub fn ParseFromString(&self, _s: &DOMString, ty: DOMParserBinding::SupportedType) -> Fallible<AbstractDocument> { let cx = self.owner.get_cx(); let document = match ty { Text_html =>
Text_xml => { AbstractDocument::as_abstract(cx, @mut Document::new(self.owner, XML)) } _ => { fail!("unsupported document type") } }; let root = @HTMLHtmlElement { htmlelement: HTMLElement::new(HTMLHtmlElementTypeId, ~"html", document) }; let root = unsafe { Node::as_abstract_node(cx, root) }; document.set_root(root); Ok(document) } } impl Reflectable for DOMParser { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector { &mut self.reflector_ } fn wrap_object_shared(@mut self, _cx: *JSContext, _scope: *JSObject) -> *JSObject { unreachable!(); } fn GetParentObject(&self, _cx: *JSContext) -> Option<@mut Reflectable> { Some(self.owner as @mut Reflectable) } }
{ HTMLDocument::new(self.owner) }
conditional_block
domparser.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::DOMParserBinding; use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{Text_html, Text_xml}; use dom::bindings::utils::{DOMString, Fallible, Reflector, Reflectable, reflect_dom_object}; use dom::document::{AbstractDocument, Document, XML}; use dom::element::HTMLHtmlElementTypeId; use dom::htmldocument::HTMLDocument; use dom::htmlelement::HTMLElement; use dom::htmlhtmlelement::HTMLHtmlElement; use dom::node::Node; use dom::window::Window; use js::jsapi::{JSContext, JSObject}; pub struct DOMParser { owner: @mut Window, //XXXjdm Document instead? reflector_: Reflector } impl DOMParser { pub fn new_inherited(owner: @mut Window) -> DOMParser
pub fn new(owner: @mut Window) -> @mut DOMParser { reflect_dom_object(@mut DOMParser::new_inherited(owner), owner, DOMParserBinding::Wrap) } pub fn Constructor(owner: @mut Window) -> Fallible<@mut DOMParser> { Ok(DOMParser::new(owner)) } pub fn ParseFromString(&self, _s: &DOMString, ty: DOMParserBinding::SupportedType) -> Fallible<AbstractDocument> { let cx = self.owner.get_cx(); let document = match ty { Text_html => { HTMLDocument::new(self.owner) } Text_xml => { AbstractDocument::as_abstract(cx, @mut Document::new(self.owner, XML)) } _ => { fail!("unsupported document type") } }; let root = @HTMLHtmlElement { htmlelement: HTMLElement::new(HTMLHtmlElementTypeId, ~"html", document) }; let root = unsafe { Node::as_abstract_node(cx, root) }; document.set_root(root); Ok(document) } } impl Reflectable for DOMParser { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector { &mut self.reflector_ } fn wrap_object_shared(@mut self, _cx: *JSContext, _scope: *JSObject) -> *JSObject { unreachable!(); } fn GetParentObject(&self, _cx: *JSContext) -> Option<@mut Reflectable> { Some(self.owner as @mut Reflectable) } }
{ DOMParser { owner: owner, reflector_: Reflector::new() } }
identifier_body
domparser.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::DOMParserBinding; use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{Text_html, Text_xml}; use dom::bindings::utils::{DOMString, Fallible, Reflector, Reflectable, reflect_dom_object}; use dom::document::{AbstractDocument, Document, XML}; use dom::element::HTMLHtmlElementTypeId; use dom::htmldocument::HTMLDocument; use dom::htmlelement::HTMLElement; use dom::htmlhtmlelement::HTMLHtmlElement; use dom::node::Node; use dom::window::Window; use js::jsapi::{JSContext, JSObject}; pub struct DOMParser { owner: @mut Window, //XXXjdm Document instead? reflector_: Reflector } impl DOMParser { pub fn new_inherited(owner: @mut Window) -> DOMParser { DOMParser { owner: owner, reflector_: Reflector::new() } } pub fn new(owner: @mut Window) -> @mut DOMParser { reflect_dom_object(@mut DOMParser::new_inherited(owner), owner, DOMParserBinding::Wrap) } pub fn Constructor(owner: @mut Window) -> Fallible<@mut DOMParser> { Ok(DOMParser::new(owner)) } pub fn ParseFromString(&self, _s: &DOMString, ty: DOMParserBinding::SupportedType) -> Fallible<AbstractDocument> { let cx = self.owner.get_cx(); let document = match ty { Text_html => { HTMLDocument::new(self.owner) } Text_xml => { AbstractDocument::as_abstract(cx, @mut Document::new(self.owner, XML)) } _ => { fail!("unsupported document type") } }; let root = @HTMLHtmlElement { htmlelement: HTMLElement::new(HTMLHtmlElementTypeId, ~"html", document) }; let root = unsafe { Node::as_abstract_node(cx, root) }; document.set_root(root); Ok(document) } } impl Reflectable for DOMParser { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector { &mut self.reflector_ } fn wrap_object_shared(@mut self, _cx: *JSContext, _scope: *JSObject) -> *JSObject { unreachable!(); } fn
(&self, _cx: *JSContext) -> Option<@mut Reflectable> { Some(self.owner as @mut Reflectable) } }
GetParentObject
identifier_name
validation.js
/** * External dependencies */
compact, inRange, isArray, isEmpty } from 'lodash'; import i18n from 'i18n-calypso'; function creditCardFieldRules() { return { name: { description: i18n.translate( 'Name on Card', { context: 'Upgrades: Card holder name label on credit card form', textOnly: true } ), rules: [ 'required' ] }, number: { description: i18n.translate( 'Card Number', { context: 'Upgrades: Card number label on credit card form', textOnly: true } ), rules: [ 'required', 'validCreditCardNumber' ] }, 'expiration-date': { description: i18n.translate( 'Credit Card Expiration Date' ), rules: [ 'required', 'validExpirationDate' ] }, cvv: { description: i18n.translate( 'Credit Card CVV Code' ), rules: [ 'required', 'validCvvNumber' ] }, country: { description: i18n.translate( 'Country' ), rules: [ 'required' ] }, 'postal-code': { description: i18n.translate( 'Postal Code', { context: 'Upgrades: Postal code on credit card form', textOnly: true } ), rules: [ 'required' ] } }; } const validators = {}; validators.required = { isValid: function( value ) { return ! isEmpty( value ); }, error: function( description ) { return i18n.translate( 'Missing required %(description)s field', { args: { description: description } } ); } }; validators.validCreditCardNumber = creditCardValidator( 'validCardNumber' ); validators.validCvvNumber = creditCardValidator( 'validCvc' ); validators.validExpirationDate = creditCardValidator( 'notExpired', 'validExpirationMonth', 'validExpirationYear', ); function validateCreditCard( cardDetails ) { const expirationDate = cardDetails[ 'expiration-date' ] || '/', expirationMonth = parseInt( expirationDate.split( '/' )[ 0 ], 10 ), expirationYear = 2000 + parseInt( expirationDate.split( '/' )[ 1 ], 10 ); return creditcards.validate( { number: cardDetails.number, expirationMonth: expirationMonth, expirationYear: expirationYear, cvc: cardDetails.cvv } ); } function creditCardValidator( ...validationProperties ) { return { isValid: function( value, cardDetails ) { if ( ! value ) { return false; } const validationResult = validateCreditCard( cardDetails ); return validationProperties.every( function( property ) { if ( property === 'notExpired' ) { return ! validationResult.expired; } return validationResult[ property ]; } ); }, error: function( description ) { return i18n.translate( '%(description)s is invalid', { args: { description: capitalize( description ) } } ); } }; } function validateCardDetails( cardDetails ) { const rules = creditCardFieldRules(), errors = Object.keys( rules ).reduce( function( allErrors, fieldName ) { const field = rules[ fieldName ], newErrors = getErrors( field, cardDetails[ fieldName ], cardDetails ); if ( newErrors.length ) { allErrors[ fieldName ] = newErrors; } return allErrors; }, {} ); return { errors: errors }; } /** * Retrieves the type of credit card from the specified number. * * @param {string} number - credit card number * @returns {string} the type of the credit card * @see {@link http://en.wikipedia.org/wiki/Bank_card_number} for more information */ function getCreditCardType( number ) { if ( number ) { number = number.replace( / /g, '' ); if ( number.match( /^3[47]\d{0,13}$/ ) ) { return 'amex'; } else if ( number.match( /^4\d{0,12}$/ ) || number.match( /^4\d{15}$/ ) ) { return 'visa'; } else if ( number.match( /^5[1-5]\d{0,14}$/ ) ) { return 'mastercard'; } else if ( number.match( /^6011\d{0,12}$/ ) || inRange( parseInt( number, 10 ), 622126, 622926 ) || // valid range is 622126-622925 number.match( /^64[4-9]\d{0,13}$/ ) || number.match( /^65\d{0,14}$/ ) ) { return 'discover'; } } return null; } function getErrors( field, value, cardDetails ) { return compact( field.rules.map( function( rule ) { const validator = getValidator( rule ); if ( ! validator.isValid( value, cardDetails ) ) { return validator.error( field.description ); } } ) ); } function getValidator( rule ) { if ( isArray( rule ) ) { return validators[ rule[ 0 ] ].apply( null, rule.slice( 1 ) ); } return validators[ rule ]; } module.exports = { getCreditCardType: getCreditCardType, validateCardDetails: validateCardDetails };
import creditcards from 'creditcards'; import { capitalize,
random_line_split
validation.js
/** * External dependencies */ import creditcards from 'creditcards'; import { capitalize, compact, inRange, isArray, isEmpty } from 'lodash'; import i18n from 'i18n-calypso'; function creditCardFieldRules() { return { name: { description: i18n.translate( 'Name on Card', { context: 'Upgrades: Card holder name label on credit card form', textOnly: true } ), rules: [ 'required' ] }, number: { description: i18n.translate( 'Card Number', { context: 'Upgrades: Card number label on credit card form', textOnly: true } ), rules: [ 'required', 'validCreditCardNumber' ] }, 'expiration-date': { description: i18n.translate( 'Credit Card Expiration Date' ), rules: [ 'required', 'validExpirationDate' ] }, cvv: { description: i18n.translate( 'Credit Card CVV Code' ), rules: [ 'required', 'validCvvNumber' ] }, country: { description: i18n.translate( 'Country' ), rules: [ 'required' ] }, 'postal-code': { description: i18n.translate( 'Postal Code', { context: 'Upgrades: Postal code on credit card form', textOnly: true } ), rules: [ 'required' ] } }; } const validators = {}; validators.required = { isValid: function( value ) { return ! isEmpty( value ); }, error: function( description ) { return i18n.translate( 'Missing required %(description)s field', { args: { description: description } } ); } }; validators.validCreditCardNumber = creditCardValidator( 'validCardNumber' ); validators.validCvvNumber = creditCardValidator( 'validCvc' ); validators.validExpirationDate = creditCardValidator( 'notExpired', 'validExpirationMonth', 'validExpirationYear', ); function validateCreditCard( cardDetails ) { const expirationDate = cardDetails[ 'expiration-date' ] || '/', expirationMonth = parseInt( expirationDate.split( '/' )[ 0 ], 10 ), expirationYear = 2000 + parseInt( expirationDate.split( '/' )[ 1 ], 10 ); return creditcards.validate( { number: cardDetails.number, expirationMonth: expirationMonth, expirationYear: expirationYear, cvc: cardDetails.cvv } ); } function creditCardValidator( ...validationProperties ) { return { isValid: function( value, cardDetails ) { if ( ! value ) { return false; } const validationResult = validateCreditCard( cardDetails ); return validationProperties.every( function( property ) { if ( property === 'notExpired' ) { return ! validationResult.expired; } return validationResult[ property ]; } ); }, error: function( description ) { return i18n.translate( '%(description)s is invalid', { args: { description: capitalize( description ) } } ); } }; } function
( cardDetails ) { const rules = creditCardFieldRules(), errors = Object.keys( rules ).reduce( function( allErrors, fieldName ) { const field = rules[ fieldName ], newErrors = getErrors( field, cardDetails[ fieldName ], cardDetails ); if ( newErrors.length ) { allErrors[ fieldName ] = newErrors; } return allErrors; }, {} ); return { errors: errors }; } /** * Retrieves the type of credit card from the specified number. * * @param {string} number - credit card number * @returns {string} the type of the credit card * @see {@link http://en.wikipedia.org/wiki/Bank_card_number} for more information */ function getCreditCardType( number ) { if ( number ) { number = number.replace( / /g, '' ); if ( number.match( /^3[47]\d{0,13}$/ ) ) { return 'amex'; } else if ( number.match( /^4\d{0,12}$/ ) || number.match( /^4\d{15}$/ ) ) { return 'visa'; } else if ( number.match( /^5[1-5]\d{0,14}$/ ) ) { return 'mastercard'; } else if ( number.match( /^6011\d{0,12}$/ ) || inRange( parseInt( number, 10 ), 622126, 622926 ) || // valid range is 622126-622925 number.match( /^64[4-9]\d{0,13}$/ ) || number.match( /^65\d{0,14}$/ ) ) { return 'discover'; } } return null; } function getErrors( field, value, cardDetails ) { return compact( field.rules.map( function( rule ) { const validator = getValidator( rule ); if ( ! validator.isValid( value, cardDetails ) ) { return validator.error( field.description ); } } ) ); } function getValidator( rule ) { if ( isArray( rule ) ) { return validators[ rule[ 0 ] ].apply( null, rule.slice( 1 ) ); } return validators[ rule ]; } module.exports = { getCreditCardType: getCreditCardType, validateCardDetails: validateCardDetails };
validateCardDetails
identifier_name
validation.js
/** * External dependencies */ import creditcards from 'creditcards'; import { capitalize, compact, inRange, isArray, isEmpty } from 'lodash'; import i18n from 'i18n-calypso'; function creditCardFieldRules() { return { name: { description: i18n.translate( 'Name on Card', { context: 'Upgrades: Card holder name label on credit card form', textOnly: true } ), rules: [ 'required' ] }, number: { description: i18n.translate( 'Card Number', { context: 'Upgrades: Card number label on credit card form', textOnly: true } ), rules: [ 'required', 'validCreditCardNumber' ] }, 'expiration-date': { description: i18n.translate( 'Credit Card Expiration Date' ), rules: [ 'required', 'validExpirationDate' ] }, cvv: { description: i18n.translate( 'Credit Card CVV Code' ), rules: [ 'required', 'validCvvNumber' ] }, country: { description: i18n.translate( 'Country' ), rules: [ 'required' ] }, 'postal-code': { description: i18n.translate( 'Postal Code', { context: 'Upgrades: Postal code on credit card form', textOnly: true } ), rules: [ 'required' ] } }; } const validators = {}; validators.required = { isValid: function( value ) { return ! isEmpty( value ); }, error: function( description ) { return i18n.translate( 'Missing required %(description)s field', { args: { description: description } } ); } }; validators.validCreditCardNumber = creditCardValidator( 'validCardNumber' ); validators.validCvvNumber = creditCardValidator( 'validCvc' ); validators.validExpirationDate = creditCardValidator( 'notExpired', 'validExpirationMonth', 'validExpirationYear', ); function validateCreditCard( cardDetails ) { const expirationDate = cardDetails[ 'expiration-date' ] || '/', expirationMonth = parseInt( expirationDate.split( '/' )[ 0 ], 10 ), expirationYear = 2000 + parseInt( expirationDate.split( '/' )[ 1 ], 10 ); return creditcards.validate( { number: cardDetails.number, expirationMonth: expirationMonth, expirationYear: expirationYear, cvc: cardDetails.cvv } ); } function creditCardValidator( ...validationProperties ) { return { isValid: function( value, cardDetails ) { if ( ! value ) { return false; } const validationResult = validateCreditCard( cardDetails ); return validationProperties.every( function( property ) { if ( property === 'notExpired' ) { return ! validationResult.expired; } return validationResult[ property ]; } ); }, error: function( description ) { return i18n.translate( '%(description)s is invalid', { args: { description: capitalize( description ) } } ); } }; } function validateCardDetails( cardDetails ) { const rules = creditCardFieldRules(), errors = Object.keys( rules ).reduce( function( allErrors, fieldName ) { const field = rules[ fieldName ], newErrors = getErrors( field, cardDetails[ fieldName ], cardDetails ); if ( newErrors.length ) { allErrors[ fieldName ] = newErrors; } return allErrors; }, {} ); return { errors: errors }; } /** * Retrieves the type of credit card from the specified number. * * @param {string} number - credit card number * @returns {string} the type of the credit card * @see {@link http://en.wikipedia.org/wiki/Bank_card_number} for more information */ function getCreditCardType( number )
function getErrors( field, value, cardDetails ) { return compact( field.rules.map( function( rule ) { const validator = getValidator( rule ); if ( ! validator.isValid( value, cardDetails ) ) { return validator.error( field.description ); } } ) ); } function getValidator( rule ) { if ( isArray( rule ) ) { return validators[ rule[ 0 ] ].apply( null, rule.slice( 1 ) ); } return validators[ rule ]; } module.exports = { getCreditCardType: getCreditCardType, validateCardDetails: validateCardDetails };
{ if ( number ) { number = number.replace( / /g, '' ); if ( number.match( /^3[47]\d{0,13}$/ ) ) { return 'amex'; } else if ( number.match( /^4\d{0,12}$/ ) || number.match( /^4\d{15}$/ ) ) { return 'visa'; } else if ( number.match( /^5[1-5]\d{0,14}$/ ) ) { return 'mastercard'; } else if ( number.match( /^6011\d{0,12}$/ ) || inRange( parseInt( number, 10 ), 622126, 622926 ) || // valid range is 622126-622925 number.match( /^64[4-9]\d{0,13}$/ ) || number.match( /^65\d{0,14}$/ ) ) { return 'discover'; } } return null; }
identifier_body
validation.js
/** * External dependencies */ import creditcards from 'creditcards'; import { capitalize, compact, inRange, isArray, isEmpty } from 'lodash'; import i18n from 'i18n-calypso'; function creditCardFieldRules() { return { name: { description: i18n.translate( 'Name on Card', { context: 'Upgrades: Card holder name label on credit card form', textOnly: true } ), rules: [ 'required' ] }, number: { description: i18n.translate( 'Card Number', { context: 'Upgrades: Card number label on credit card form', textOnly: true } ), rules: [ 'required', 'validCreditCardNumber' ] }, 'expiration-date': { description: i18n.translate( 'Credit Card Expiration Date' ), rules: [ 'required', 'validExpirationDate' ] }, cvv: { description: i18n.translate( 'Credit Card CVV Code' ), rules: [ 'required', 'validCvvNumber' ] }, country: { description: i18n.translate( 'Country' ), rules: [ 'required' ] }, 'postal-code': { description: i18n.translate( 'Postal Code', { context: 'Upgrades: Postal code on credit card form', textOnly: true } ), rules: [ 'required' ] } }; } const validators = {}; validators.required = { isValid: function( value ) { return ! isEmpty( value ); }, error: function( description ) { return i18n.translate( 'Missing required %(description)s field', { args: { description: description } } ); } }; validators.validCreditCardNumber = creditCardValidator( 'validCardNumber' ); validators.validCvvNumber = creditCardValidator( 'validCvc' ); validators.validExpirationDate = creditCardValidator( 'notExpired', 'validExpirationMonth', 'validExpirationYear', ); function validateCreditCard( cardDetails ) { const expirationDate = cardDetails[ 'expiration-date' ] || '/', expirationMonth = parseInt( expirationDate.split( '/' )[ 0 ], 10 ), expirationYear = 2000 + parseInt( expirationDate.split( '/' )[ 1 ], 10 ); return creditcards.validate( { number: cardDetails.number, expirationMonth: expirationMonth, expirationYear: expirationYear, cvc: cardDetails.cvv } ); } function creditCardValidator( ...validationProperties ) { return { isValid: function( value, cardDetails ) { if ( ! value ) { return false; } const validationResult = validateCreditCard( cardDetails ); return validationProperties.every( function( property ) { if ( property === 'notExpired' )
return validationResult[ property ]; } ); }, error: function( description ) { return i18n.translate( '%(description)s is invalid', { args: { description: capitalize( description ) } } ); } }; } function validateCardDetails( cardDetails ) { const rules = creditCardFieldRules(), errors = Object.keys( rules ).reduce( function( allErrors, fieldName ) { const field = rules[ fieldName ], newErrors = getErrors( field, cardDetails[ fieldName ], cardDetails ); if ( newErrors.length ) { allErrors[ fieldName ] = newErrors; } return allErrors; }, {} ); return { errors: errors }; } /** * Retrieves the type of credit card from the specified number. * * @param {string} number - credit card number * @returns {string} the type of the credit card * @see {@link http://en.wikipedia.org/wiki/Bank_card_number} for more information */ function getCreditCardType( number ) { if ( number ) { number = number.replace( / /g, '' ); if ( number.match( /^3[47]\d{0,13}$/ ) ) { return 'amex'; } else if ( number.match( /^4\d{0,12}$/ ) || number.match( /^4\d{15}$/ ) ) { return 'visa'; } else if ( number.match( /^5[1-5]\d{0,14}$/ ) ) { return 'mastercard'; } else if ( number.match( /^6011\d{0,12}$/ ) || inRange( parseInt( number, 10 ), 622126, 622926 ) || // valid range is 622126-622925 number.match( /^64[4-9]\d{0,13}$/ ) || number.match( /^65\d{0,14}$/ ) ) { return 'discover'; } } return null; } function getErrors( field, value, cardDetails ) { return compact( field.rules.map( function( rule ) { const validator = getValidator( rule ); if ( ! validator.isValid( value, cardDetails ) ) { return validator.error( field.description ); } } ) ); } function getValidator( rule ) { if ( isArray( rule ) ) { return validators[ rule[ 0 ] ].apply( null, rule.slice( 1 ) ); } return validators[ rule ]; } module.exports = { getCreditCardType: getCreditCardType, validateCardDetails: validateCardDetails };
{ return ! validationResult.expired; }
conditional_block
IDMappingGridContainer.js
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/on', 'dojo/topic', 'dijit/popup', 'dijit/TooltipDialog', './IDMappingGrid', './GridContainer' ], function ( declare, lang, on, Topic, popup, TooltipDialog, IDMappingGrid, GridContainer ) { return declare([GridContainer], { gridCtor: IDMappingGrid, containerType: 'feature_data', facetFields: [], enableFilterPanel: false, buildQuery: function () { // prevent further filtering. DO NOT DELETE }, _setQueryAttr: function (query) { // block default query handler for now. }, onSetState: function (state) { // block default behavior }, _setStateAttr: function (state) { this.inherited(arguments); if (!state)
if (this.grid) { this.grid.set('state', state); } else { // console.log("No Grid Yet (IDMappingGridContainer)"); } this._set('state', state); } }); });
{ return; }
conditional_block
IDMappingGridContainer.js
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/on', 'dojo/topic',
declare, lang, on, Topic, popup, TooltipDialog, IDMappingGrid, GridContainer ) { return declare([GridContainer], { gridCtor: IDMappingGrid, containerType: 'feature_data', facetFields: [], enableFilterPanel: false, buildQuery: function () { // prevent further filtering. DO NOT DELETE }, _setQueryAttr: function (query) { // block default query handler for now. }, onSetState: function (state) { // block default behavior }, _setStateAttr: function (state) { this.inherited(arguments); if (!state) { return; } if (this.grid) { this.grid.set('state', state); } else { // console.log("No Grid Yet (IDMappingGridContainer)"); } this._set('state', state); } }); });
'dijit/popup', 'dijit/TooltipDialog', './IDMappingGrid', './GridContainer' ], function (
random_line_split
coercion.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! # Type Coercion //! //! Under certain circumstances we will coerce from one type to another, //! for example by auto-borrowing. This occurs in situations where the //! compiler has a firm 'expected type' that was supplied from the user, //! and where the actual type is similar to that expected type in purpose //! but not in representation (so actual subtyping is inappropriate). //! //! ## Reborrowing //! //! Note that if we are expecting a reference, we will *reborrow* //! even if the argument provided was already a reference. This is //! useful for freezing mut/const things (that is, when the expected is &T //! but you have &const T or &mut T) and also for avoiding the linearity //! of mut things (when the expected is &mut T and you have &mut T). See //! the various `src/test/run-pass/coerce-reborrow-*.rs` tests for //! examples of where this is useful. //! //! ## Subtle note //! //! When deciding what type coercions to consider, we do not attempt to //! resolve any type variables we may encounter. This is because `b` //! represents the expected type "as the user wrote it", meaning that if //! the user defined a generic function like //! //! fn foo<A>(a: A, b: A) { ... } //! //! and then we wrote `foo(&1, @2)`, we will not auto-borrow //! either argument. In older code we went to some lengths to //! resolve the `b` variable, which could mean that we'd //! auto-borrow later arguments but not earlier ones, which //! seems very confusing. //! //! ## Subtler note //! //! However, right now, if the user manually specifies the //! values for the type variables, as so: //! //! foo::<&int>(@1, @2) //! //! then we *will* auto-borrow, because we can't distinguish this from a //! function that declared `&int`. This is inconsistent but it's easiest //! at the moment. The right thing to do, I think, is to consider the //! *unsubstituted* type when deciding whether to auto-borrow, but the //! *substituted* type when considering the bounds and so forth. But most //! of our methods don't give access to the unsubstituted type, and //! rightly so because they'd be error-prone. So maybe the thing to do is //! to actually determine the kind of coercions that should occur //! separately and pass them in. Or maybe it's ok as is. Anyway, it's //! sort of a minor point so I've opted to leave it for later---after all //! we may want to adjust precisely when coercions occur. use check::{autoderef, FnCtxt, NoPreference, PreferMutLvalue, UnresolvedTypeAction}; use middle::infer::{self, Coercion}; use middle::traits::{self, ObligationCause}; use middle::traits::{predicate_for_trait_def, report_selection_error}; use middle::ty::{AutoDerefRef, AdjustDerefRef}; use middle::ty::{self, mt, Ty}; use middle::ty_relate::RelateResult; use util::common::indent; use util::ppaux::Repr; use std::cell::RefCell; use std::collections::VecDeque; use syntax::ast; struct Coerce<'a, 'tcx: 'a> { fcx: &'a FnCtxt<'a, 'tcx>, origin: infer::TypeOrigin, unsizing_obligations: RefCell<Vec<traits::PredicateObligation<'tcx>>>, } type CoerceResult<'tcx> = RelateResult<'tcx, Option<ty::AutoAdjustment<'tcx>>>; impl<'f, 'tcx> Coerce<'f, 'tcx> { fn tcx(&self) -> &ty::ctxt<'tcx> { self.fcx.tcx() } fn subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { try!(self.fcx.infcx().sub_types(false, self.origin.clone(), a, b)); Ok(None) // No coercion required. } fn unpack_actual_value<T, F>(&self, a: Ty<'tcx>, f: F) -> T where F: FnOnce(Ty<'tcx>) -> T, { f(self.fcx.infcx().shallow_resolve(a)) } fn coerce(&self, expr_a: &ast::Expr, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { debug!("Coerce.tys({} => {})", a.repr(self.tcx()), b.repr(self.tcx())); // Consider coercing the subtype to a DST let unsize = self.unpack_actual_value(a, |a| { self.coerce_unsized(a, b) }); if unsize.is_ok() { return unsize; } // Examine the supertype and consider auto-borrowing. // // Note: does not attempt to resolve type variables we encounter. // See above for details. match b.sty { ty::ty_ptr(mt_b) => { return self.unpack_actual_value(a, |a| { self.coerce_unsafe_ptr(a, b, mt_b.mutbl) }); } ty::ty_rptr(_, mt_b) => { return self.unpack_actual_value(a, |a| { self.coerce_borrowed_pointer(expr_a, a, b, mt_b.mutbl) }); } _ => {} } self.unpack_actual_value(a, |a| { match a.sty { ty::ty_bare_fn(Some(_), a_f) => { // Function items are coercible to any closure // type; function pointers are not (that would // require double indirection). self.coerce_from_fn_item(a, a_f, b) } ty::ty_bare_fn(None, a_f) => { // We permit coercion of fn pointers to drop the // unsafe qualifier. self.coerce_from_fn_pointer(a, a_f, b) } _ => { // Otherwise, just use subtyping rules. self.subtype(a, b) } } }) } /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`. /// To match `A` with `B`, autoderef will be performed, /// calling `deref`/`deref_mut` where necessary. fn coerce_borrowed_pointer(&self, expr_a: &ast::Expr, a: Ty<'tcx>, b: Ty<'tcx>, mutbl_b: ast::Mutability) -> CoerceResult<'tcx> { debug!("coerce_borrowed_pointer(a={}, b={})", a.repr(self.tcx()), b.repr(self.tcx())); // If we have a parameter of type `&M T_a` and the value // provided is `expr`, we will be adding an implicit borrow, // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore, // to type check, we will construct the type that `&M*expr` would // yield. match a.sty { ty::ty_rptr(_, mt_a) => { try!(coerce_mutbls(mt_a.mutbl, mutbl_b)); } _ => return self.subtype(a, b) } let coercion = Coercion(self.origin.span()); let r_borrow = self.fcx.infcx().next_region_var(coercion); let r_borrow = self.tcx().mk_region(r_borrow); let autoref = Some(ty::AutoPtr(r_borrow, mutbl_b)); let lvalue_pref = match mutbl_b { ast::MutMutable => PreferMutLvalue, ast::MutImmutable => NoPreference }; let mut first_error = None; let (_, autoderefs, success) = autoderef(self.fcx, expr_a.span, a, Some(expr_a), UnresolvedTypeAction::Ignore, lvalue_pref, |inner_ty, autoderef| { if autoderef == 0 { // Don't let this pass, otherwise it would cause // &T to autoref to &&T. return None; } let ty = ty::mk_rptr(self.tcx(), r_borrow, mt {ty: inner_ty, mutbl: mutbl_b}); if let Err(err) = self.subtype(ty, b) { if first_error.is_none() { first_error = Some(err); } None } else { Some(()) } }); match success { Some(_) => { Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: autoderefs, autoref: autoref, unsize: None }))) } None => { // Return original error as if overloaded deref was never // attempted, to avoid irrelevant/confusing error messages. Err(first_error.expect("coerce_borrowed_pointer failed with no error?")) } } } // &[T, ..n] or &mut [T, ..n] -> &[T] // or &mut [T, ..n] -> &mut [T] // or &Concrete -> &Trait, etc. fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> { debug!("coerce_unsized(source={}, target={})", source.repr(self.tcx()), target.repr(self.tcx())); let traits = (self.tcx().lang_items.unsize_trait(), self.tcx().lang_items.coerce_unsized_trait()); let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits { (u, cu) } else { debug!("Missing Unsize or CoerceUnsized traits"); return Err(ty::terr_mismatch); }; // Note, we want to avoid unnecessary unsizing. We don't want to coerce to // a DST unless we have to. This currently comes out in the wash since // we can't unify [T] with U. But to properly support DST, we need to allow // that, at which point we will need extra checks on the target here. // Handle reborrows before selecting `Source: CoerceUnsized<Target>`. let (source, reborrow) = match (&source.sty, &target.sty) { (&ty::ty_rptr(_, mt_a), &ty::ty_rptr(_, mt_b)) => { try!(coerce_mutbls(mt_a.mutbl, mt_b.mutbl)); let coercion = Coercion(self.origin.span()); let r_borrow = self.fcx.infcx().next_region_var(coercion); let region = self.tcx().mk_region(r_borrow); (mt_a.ty, Some(ty::AutoPtr(region, mt_b.mutbl))) } (&ty::ty_rptr(_, mt_a), &ty::ty_ptr(mt_b)) => { try!(coerce_mutbls(mt_a.mutbl, mt_b.mutbl)); (mt_a.ty, Some(ty::AutoUnsafe(mt_b.mutbl))) } _ => (source, None) }; let source = ty::adjust_ty_for_autoref(self.tcx(), source, reborrow); let mut selcx = traits::SelectionContext::new(self.fcx.infcx(), self.fcx); // Use a FIFO queue for this custom fulfillment procedure. let mut queue = VecDeque::new(); let mut leftover_predicates = vec![]; // Create an obligation for `Source: CoerceUnsized<Target>`. let cause = ObligationCause::misc(self.origin.span(), self.fcx.body_id); queue.push_back(predicate_for_trait_def(self.tcx(), cause, coerce_unsized_did, 0, source, vec![target])); // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where // inference might unify those two inner type variables later. let traits = [coerce_unsized_did, unsize_did]; while let Some(obligation) = queue.pop_front() { debug!("coerce_unsized resolve step: {}", obligation.repr(self.tcx())); let trait_ref = match obligation.predicate { ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => { tr.clone() } _ => { leftover_predicates.push(obligation); continue; } }; match selcx.select(&obligation.with(trait_ref)) { // Uncertain or unimplemented. Ok(None) | Err(traits::Unimplemented) => { debug!("coerce_unsized: early return - can't prove obligation"); return Err(ty::terr_mismatch); } // Object safety violations or miscellaneous. Err(err) => { report_selection_error(self.fcx.infcx(), &obligation, &err); // Treat this like an obligation and follow through // with the unsizing - the lack of a coercion should // be silent, as it causes a type mismatch later. } Ok(Some(vtable)) => { vtable.map_move_nested(|o| queue.push_back(o)); } } } let mut obligations = self.unsizing_obligations.borrow_mut(); assert!(obligations.is_empty()); *obligations = leftover_predicates; let adjustment = AutoDerefRef { autoderefs: if reborrow.is_some() { 1 } else { 0 }, autoref: reborrow, unsize: Some(target) }; debug!("Success, coerced with {}", adjustment.repr(self.tcx())); Ok(Some(AdjustDerefRef(adjustment))) } fn coerce_from_fn_pointer(&self, a: Ty<'tcx>, fn_ty_a: &'tcx ty::BareFnTy<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { /*! * Attempts to coerce from the type of a Rust function item * into a closure or a `proc`. */ self.unpack_actual_value(b, |b| { debug!("coerce_from_fn_pointer(a={}, b={})", a.repr(self.tcx()), b.repr(self.tcx())); if let ty::ty_bare_fn(None, fn_ty_b) = b.sty { match (fn_ty_a.unsafety, fn_ty_b.unsafety) { (ast::Unsafety::Normal, ast::Unsafety::Unsafe) => { let unsafe_a = self.tcx().safe_to_unsafe_fn_ty(fn_ty_a); try!(self.subtype(unsafe_a, b)); return Ok(Some(ty::AdjustUnsafeFnPointer)); } _ => {} } } self.subtype(a, b) }) } fn coerce_from_fn_item(&self, a: Ty<'tcx>, fn_ty_a: &'tcx ty::BareFnTy<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { /*! * Attempts to coerce from the type of a Rust function item * into a closure or a `proc`. */ self.unpack_actual_value(b, |b| { debug!("coerce_from_fn_item(a={}, b={})", a.repr(self.tcx()), b.repr(self.tcx())); match b.sty { ty::ty_bare_fn(None, _) => { let a_fn_pointer = ty::mk_bare_fn(self.tcx(), None, fn_ty_a); try!(self.subtype(a_fn_pointer, b)); Ok(Some(ty::AdjustReifyFnPointer)) } _ => self.subtype(a, b) } }) } fn
(&self, a: Ty<'tcx>, b: Ty<'tcx>, mutbl_b: ast::Mutability) -> CoerceResult<'tcx> { debug!("coerce_unsafe_ptr(a={}, b={})", a.repr(self.tcx()), b.repr(self.tcx())); let mt_a = match a.sty { ty::ty_rptr(_, mt) | ty::ty_ptr(mt) => mt, _ => { return self.subtype(a, b); } }; // Check that the types which they point at are compatible. let a_unsafe = ty::mk_ptr(self.tcx(), ty::mt{ mutbl: mutbl_b, ty: mt_a.ty }); try!(self.subtype(a_unsafe, b)); try!(coerce_mutbls(mt_a.mutbl, mutbl_b)); // Although references and unsafe ptrs have the same // representation, we still register an AutoDerefRef so that // regionck knows that the region for `a` must be valid here. Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(ty::AutoUnsafe(mutbl_b)), unsize: None }))) } } pub fn mk_assignty<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, expr: &ast::Expr, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, ()> { debug!("mk_assignty({} -> {})", a.repr(fcx.tcx()), b.repr(fcx.tcx())); let mut unsizing_obligations = vec![]; let adjustment = try!(indent(|| { fcx.infcx().commit_if_ok(|_| { let coerce = Coerce { fcx: fcx, origin: infer::ExprAssignable(expr.span), unsizing_obligations: RefCell::new(vec![]) }; let adjustment = try!(coerce.coerce(expr, a, b)); unsizing_obligations = coerce.unsizing_obligations.into_inner(); Ok(adjustment) }) })); if let Some(AdjustDerefRef(auto)) = adjustment { if auto.unsize.is_some() { for obligation in unsizing_obligations { fcx.register_predicate(obligation); } } } if let Some(adjustment) = adjustment { debug!("Success, coerced with {}", adjustment.repr(fcx.tcx())); fcx.write_adjustment(expr.id, adjustment); } Ok(()) } fn coerce_mutbls<'tcx>(from_mutbl: ast::Mutability, to_mutbl: ast::Mutability) -> CoerceResult<'tcx> { match (from_mutbl, to_mutbl) { (ast::MutMutable, ast::MutMutable) | (ast::MutImmutable, ast::MutImmutable) | (ast::MutMutable, ast::MutImmutable) => Ok(None), (ast::MutImmutable, ast::MutMutable) => Err(ty::terr_mutability) } }
coerce_unsafe_ptr
identifier_name
coercion.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! # Type Coercion //! //! Under certain circumstances we will coerce from one type to another, //! for example by auto-borrowing. This occurs in situations where the //! compiler has a firm 'expected type' that was supplied from the user, //! and where the actual type is similar to that expected type in purpose //! but not in representation (so actual subtyping is inappropriate). //! //! ## Reborrowing //! //! Note that if we are expecting a reference, we will *reborrow* //! even if the argument provided was already a reference. This is //! useful for freezing mut/const things (that is, when the expected is &T //! but you have &const T or &mut T) and also for avoiding the linearity //! of mut things (when the expected is &mut T and you have &mut T). See //! the various `src/test/run-pass/coerce-reborrow-*.rs` tests for //! examples of where this is useful. //! //! ## Subtle note //! //! When deciding what type coercions to consider, we do not attempt to //! resolve any type variables we may encounter. This is because `b` //! represents the expected type "as the user wrote it", meaning that if //! the user defined a generic function like //! //! fn foo<A>(a: A, b: A) { ... } //! //! and then we wrote `foo(&1, @2)`, we will not auto-borrow //! either argument. In older code we went to some lengths to //! resolve the `b` variable, which could mean that we'd //! auto-borrow later arguments but not earlier ones, which //! seems very confusing. //! //! ## Subtler note //! //! However, right now, if the user manually specifies the //! values for the type variables, as so: //! //! foo::<&int>(@1, @2) //! //! then we *will* auto-borrow, because we can't distinguish this from a //! function that declared `&int`. This is inconsistent but it's easiest //! at the moment. The right thing to do, I think, is to consider the //! *unsubstituted* type when deciding whether to auto-borrow, but the //! *substituted* type when considering the bounds and so forth. But most //! of our methods don't give access to the unsubstituted type, and //! rightly so because they'd be error-prone. So maybe the thing to do is //! to actually determine the kind of coercions that should occur //! separately and pass them in. Or maybe it's ok as is. Anyway, it's //! sort of a minor point so I've opted to leave it for later---after all //! we may want to adjust precisely when coercions occur. use check::{autoderef, FnCtxt, NoPreference, PreferMutLvalue, UnresolvedTypeAction}; use middle::infer::{self, Coercion}; use middle::traits::{self, ObligationCause}; use middle::traits::{predicate_for_trait_def, report_selection_error}; use middle::ty::{AutoDerefRef, AdjustDerefRef}; use middle::ty::{self, mt, Ty}; use middle::ty_relate::RelateResult; use util::common::indent; use util::ppaux::Repr; use std::cell::RefCell; use std::collections::VecDeque; use syntax::ast; struct Coerce<'a, 'tcx: 'a> { fcx: &'a FnCtxt<'a, 'tcx>, origin: infer::TypeOrigin, unsizing_obligations: RefCell<Vec<traits::PredicateObligation<'tcx>>>, } type CoerceResult<'tcx> = RelateResult<'tcx, Option<ty::AutoAdjustment<'tcx>>>; impl<'f, 'tcx> Coerce<'f, 'tcx> { fn tcx(&self) -> &ty::ctxt<'tcx> { self.fcx.tcx() } fn subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { try!(self.fcx.infcx().sub_types(false, self.origin.clone(), a, b)); Ok(None) // No coercion required. } fn unpack_actual_value<T, F>(&self, a: Ty<'tcx>, f: F) -> T where F: FnOnce(Ty<'tcx>) -> T, { f(self.fcx.infcx().shallow_resolve(a)) } fn coerce(&self, expr_a: &ast::Expr, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { debug!("Coerce.tys({} => {})",
self.coerce_unsized(a, b) }); if unsize.is_ok() { return unsize; } // Examine the supertype and consider auto-borrowing. // // Note: does not attempt to resolve type variables we encounter. // See above for details. match b.sty { ty::ty_ptr(mt_b) => { return self.unpack_actual_value(a, |a| { self.coerce_unsafe_ptr(a, b, mt_b.mutbl) }); } ty::ty_rptr(_, mt_b) => { return self.unpack_actual_value(a, |a| { self.coerce_borrowed_pointer(expr_a, a, b, mt_b.mutbl) }); } _ => {} } self.unpack_actual_value(a, |a| { match a.sty { ty::ty_bare_fn(Some(_), a_f) => { // Function items are coercible to any closure // type; function pointers are not (that would // require double indirection). self.coerce_from_fn_item(a, a_f, b) } ty::ty_bare_fn(None, a_f) => { // We permit coercion of fn pointers to drop the // unsafe qualifier. self.coerce_from_fn_pointer(a, a_f, b) } _ => { // Otherwise, just use subtyping rules. self.subtype(a, b) } } }) } /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`. /// To match `A` with `B`, autoderef will be performed, /// calling `deref`/`deref_mut` where necessary. fn coerce_borrowed_pointer(&self, expr_a: &ast::Expr, a: Ty<'tcx>, b: Ty<'tcx>, mutbl_b: ast::Mutability) -> CoerceResult<'tcx> { debug!("coerce_borrowed_pointer(a={}, b={})", a.repr(self.tcx()), b.repr(self.tcx())); // If we have a parameter of type `&M T_a` and the value // provided is `expr`, we will be adding an implicit borrow, // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore, // to type check, we will construct the type that `&M*expr` would // yield. match a.sty { ty::ty_rptr(_, mt_a) => { try!(coerce_mutbls(mt_a.mutbl, mutbl_b)); } _ => return self.subtype(a, b) } let coercion = Coercion(self.origin.span()); let r_borrow = self.fcx.infcx().next_region_var(coercion); let r_borrow = self.tcx().mk_region(r_borrow); let autoref = Some(ty::AutoPtr(r_borrow, mutbl_b)); let lvalue_pref = match mutbl_b { ast::MutMutable => PreferMutLvalue, ast::MutImmutable => NoPreference }; let mut first_error = None; let (_, autoderefs, success) = autoderef(self.fcx, expr_a.span, a, Some(expr_a), UnresolvedTypeAction::Ignore, lvalue_pref, |inner_ty, autoderef| { if autoderef == 0 { // Don't let this pass, otherwise it would cause // &T to autoref to &&T. return None; } let ty = ty::mk_rptr(self.tcx(), r_borrow, mt {ty: inner_ty, mutbl: mutbl_b}); if let Err(err) = self.subtype(ty, b) { if first_error.is_none() { first_error = Some(err); } None } else { Some(()) } }); match success { Some(_) => { Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: autoderefs, autoref: autoref, unsize: None }))) } None => { // Return original error as if overloaded deref was never // attempted, to avoid irrelevant/confusing error messages. Err(first_error.expect("coerce_borrowed_pointer failed with no error?")) } } } // &[T, ..n] or &mut [T, ..n] -> &[T] // or &mut [T, ..n] -> &mut [T] // or &Concrete -> &Trait, etc. fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> { debug!("coerce_unsized(source={}, target={})", source.repr(self.tcx()), target.repr(self.tcx())); let traits = (self.tcx().lang_items.unsize_trait(), self.tcx().lang_items.coerce_unsized_trait()); let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits { (u, cu) } else { debug!("Missing Unsize or CoerceUnsized traits"); return Err(ty::terr_mismatch); }; // Note, we want to avoid unnecessary unsizing. We don't want to coerce to // a DST unless we have to. This currently comes out in the wash since // we can't unify [T] with U. But to properly support DST, we need to allow // that, at which point we will need extra checks on the target here. // Handle reborrows before selecting `Source: CoerceUnsized<Target>`. let (source, reborrow) = match (&source.sty, &target.sty) { (&ty::ty_rptr(_, mt_a), &ty::ty_rptr(_, mt_b)) => { try!(coerce_mutbls(mt_a.mutbl, mt_b.mutbl)); let coercion = Coercion(self.origin.span()); let r_borrow = self.fcx.infcx().next_region_var(coercion); let region = self.tcx().mk_region(r_borrow); (mt_a.ty, Some(ty::AutoPtr(region, mt_b.mutbl))) } (&ty::ty_rptr(_, mt_a), &ty::ty_ptr(mt_b)) => { try!(coerce_mutbls(mt_a.mutbl, mt_b.mutbl)); (mt_a.ty, Some(ty::AutoUnsafe(mt_b.mutbl))) } _ => (source, None) }; let source = ty::adjust_ty_for_autoref(self.tcx(), source, reborrow); let mut selcx = traits::SelectionContext::new(self.fcx.infcx(), self.fcx); // Use a FIFO queue for this custom fulfillment procedure. let mut queue = VecDeque::new(); let mut leftover_predicates = vec![]; // Create an obligation for `Source: CoerceUnsized<Target>`. let cause = ObligationCause::misc(self.origin.span(), self.fcx.body_id); queue.push_back(predicate_for_trait_def(self.tcx(), cause, coerce_unsized_did, 0, source, vec![target])); // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where // inference might unify those two inner type variables later. let traits = [coerce_unsized_did, unsize_did]; while let Some(obligation) = queue.pop_front() { debug!("coerce_unsized resolve step: {}", obligation.repr(self.tcx())); let trait_ref = match obligation.predicate { ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => { tr.clone() } _ => { leftover_predicates.push(obligation); continue; } }; match selcx.select(&obligation.with(trait_ref)) { // Uncertain or unimplemented. Ok(None) | Err(traits::Unimplemented) => { debug!("coerce_unsized: early return - can't prove obligation"); return Err(ty::terr_mismatch); } // Object safety violations or miscellaneous. Err(err) => { report_selection_error(self.fcx.infcx(), &obligation, &err); // Treat this like an obligation and follow through // with the unsizing - the lack of a coercion should // be silent, as it causes a type mismatch later. } Ok(Some(vtable)) => { vtable.map_move_nested(|o| queue.push_back(o)); } } } let mut obligations = self.unsizing_obligations.borrow_mut(); assert!(obligations.is_empty()); *obligations = leftover_predicates; let adjustment = AutoDerefRef { autoderefs: if reborrow.is_some() { 1 } else { 0 }, autoref: reborrow, unsize: Some(target) }; debug!("Success, coerced with {}", adjustment.repr(self.tcx())); Ok(Some(AdjustDerefRef(adjustment))) } fn coerce_from_fn_pointer(&self, a: Ty<'tcx>, fn_ty_a: &'tcx ty::BareFnTy<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { /*! * Attempts to coerce from the type of a Rust function item * into a closure or a `proc`. */ self.unpack_actual_value(b, |b| { debug!("coerce_from_fn_pointer(a={}, b={})", a.repr(self.tcx()), b.repr(self.tcx())); if let ty::ty_bare_fn(None, fn_ty_b) = b.sty { match (fn_ty_a.unsafety, fn_ty_b.unsafety) { (ast::Unsafety::Normal, ast::Unsafety::Unsafe) => { let unsafe_a = self.tcx().safe_to_unsafe_fn_ty(fn_ty_a); try!(self.subtype(unsafe_a, b)); return Ok(Some(ty::AdjustUnsafeFnPointer)); } _ => {} } } self.subtype(a, b) }) } fn coerce_from_fn_item(&self, a: Ty<'tcx>, fn_ty_a: &'tcx ty::BareFnTy<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { /*! * Attempts to coerce from the type of a Rust function item * into a closure or a `proc`. */ self.unpack_actual_value(b, |b| { debug!("coerce_from_fn_item(a={}, b={})", a.repr(self.tcx()), b.repr(self.tcx())); match b.sty { ty::ty_bare_fn(None, _) => { let a_fn_pointer = ty::mk_bare_fn(self.tcx(), None, fn_ty_a); try!(self.subtype(a_fn_pointer, b)); Ok(Some(ty::AdjustReifyFnPointer)) } _ => self.subtype(a, b) } }) } fn coerce_unsafe_ptr(&self, a: Ty<'tcx>, b: Ty<'tcx>, mutbl_b: ast::Mutability) -> CoerceResult<'tcx> { debug!("coerce_unsafe_ptr(a={}, b={})", a.repr(self.tcx()), b.repr(self.tcx())); let mt_a = match a.sty { ty::ty_rptr(_, mt) | ty::ty_ptr(mt) => mt, _ => { return self.subtype(a, b); } }; // Check that the types which they point at are compatible. let a_unsafe = ty::mk_ptr(self.tcx(), ty::mt{ mutbl: mutbl_b, ty: mt_a.ty }); try!(self.subtype(a_unsafe, b)); try!(coerce_mutbls(mt_a.mutbl, mutbl_b)); // Although references and unsafe ptrs have the same // representation, we still register an AutoDerefRef so that // regionck knows that the region for `a` must be valid here. Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(ty::AutoUnsafe(mutbl_b)), unsize: None }))) } } pub fn mk_assignty<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, expr: &ast::Expr, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, ()> { debug!("mk_assignty({} -> {})", a.repr(fcx.tcx()), b.repr(fcx.tcx())); let mut unsizing_obligations = vec![]; let adjustment = try!(indent(|| { fcx.infcx().commit_if_ok(|_| { let coerce = Coerce { fcx: fcx, origin: infer::ExprAssignable(expr.span), unsizing_obligations: RefCell::new(vec![]) }; let adjustment = try!(coerce.coerce(expr, a, b)); unsizing_obligations = coerce.unsizing_obligations.into_inner(); Ok(adjustment) }) })); if let Some(AdjustDerefRef(auto)) = adjustment { if auto.unsize.is_some() { for obligation in unsizing_obligations { fcx.register_predicate(obligation); } } } if let Some(adjustment) = adjustment { debug!("Success, coerced with {}", adjustment.repr(fcx.tcx())); fcx.write_adjustment(expr.id, adjustment); } Ok(()) } fn coerce_mutbls<'tcx>(from_mutbl: ast::Mutability, to_mutbl: ast::Mutability) -> CoerceResult<'tcx> { match (from_mutbl, to_mutbl) { (ast::MutMutable, ast::MutMutable) | (ast::MutImmutable, ast::MutImmutable) | (ast::MutMutable, ast::MutImmutable) => Ok(None), (ast::MutImmutable, ast::MutMutable) => Err(ty::terr_mutability) } }
a.repr(self.tcx()), b.repr(self.tcx())); // Consider coercing the subtype to a DST let unsize = self.unpack_actual_value(a, |a| {
random_line_split
coercion.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! # Type Coercion //! //! Under certain circumstances we will coerce from one type to another, //! for example by auto-borrowing. This occurs in situations where the //! compiler has a firm 'expected type' that was supplied from the user, //! and where the actual type is similar to that expected type in purpose //! but not in representation (so actual subtyping is inappropriate). //! //! ## Reborrowing //! //! Note that if we are expecting a reference, we will *reborrow* //! even if the argument provided was already a reference. This is //! useful for freezing mut/const things (that is, when the expected is &T //! but you have &const T or &mut T) and also for avoiding the linearity //! of mut things (when the expected is &mut T and you have &mut T). See //! the various `src/test/run-pass/coerce-reborrow-*.rs` tests for //! examples of where this is useful. //! //! ## Subtle note //! //! When deciding what type coercions to consider, we do not attempt to //! resolve any type variables we may encounter. This is because `b` //! represents the expected type "as the user wrote it", meaning that if //! the user defined a generic function like //! //! fn foo<A>(a: A, b: A) { ... } //! //! and then we wrote `foo(&1, @2)`, we will not auto-borrow //! either argument. In older code we went to some lengths to //! resolve the `b` variable, which could mean that we'd //! auto-borrow later arguments but not earlier ones, which //! seems very confusing. //! //! ## Subtler note //! //! However, right now, if the user manually specifies the //! values for the type variables, as so: //! //! foo::<&int>(@1, @2) //! //! then we *will* auto-borrow, because we can't distinguish this from a //! function that declared `&int`. This is inconsistent but it's easiest //! at the moment. The right thing to do, I think, is to consider the //! *unsubstituted* type when deciding whether to auto-borrow, but the //! *substituted* type when considering the bounds and so forth. But most //! of our methods don't give access to the unsubstituted type, and //! rightly so because they'd be error-prone. So maybe the thing to do is //! to actually determine the kind of coercions that should occur //! separately and pass them in. Or maybe it's ok as is. Anyway, it's //! sort of a minor point so I've opted to leave it for later---after all //! we may want to adjust precisely when coercions occur. use check::{autoderef, FnCtxt, NoPreference, PreferMutLvalue, UnresolvedTypeAction}; use middle::infer::{self, Coercion}; use middle::traits::{self, ObligationCause}; use middle::traits::{predicate_for_trait_def, report_selection_error}; use middle::ty::{AutoDerefRef, AdjustDerefRef}; use middle::ty::{self, mt, Ty}; use middle::ty_relate::RelateResult; use util::common::indent; use util::ppaux::Repr; use std::cell::RefCell; use std::collections::VecDeque; use syntax::ast; struct Coerce<'a, 'tcx: 'a> { fcx: &'a FnCtxt<'a, 'tcx>, origin: infer::TypeOrigin, unsizing_obligations: RefCell<Vec<traits::PredicateObligation<'tcx>>>, } type CoerceResult<'tcx> = RelateResult<'tcx, Option<ty::AutoAdjustment<'tcx>>>; impl<'f, 'tcx> Coerce<'f, 'tcx> { fn tcx(&self) -> &ty::ctxt<'tcx> { self.fcx.tcx() } fn subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { try!(self.fcx.infcx().sub_types(false, self.origin.clone(), a, b)); Ok(None) // No coercion required. } fn unpack_actual_value<T, F>(&self, a: Ty<'tcx>, f: F) -> T where F: FnOnce(Ty<'tcx>) -> T, { f(self.fcx.infcx().shallow_resolve(a)) } fn coerce(&self, expr_a: &ast::Expr, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { debug!("Coerce.tys({} => {})", a.repr(self.tcx()), b.repr(self.tcx())); // Consider coercing the subtype to a DST let unsize = self.unpack_actual_value(a, |a| { self.coerce_unsized(a, b) }); if unsize.is_ok() { return unsize; } // Examine the supertype and consider auto-borrowing. // // Note: does not attempt to resolve type variables we encounter. // See above for details. match b.sty { ty::ty_ptr(mt_b) => { return self.unpack_actual_value(a, |a| { self.coerce_unsafe_ptr(a, b, mt_b.mutbl) }); } ty::ty_rptr(_, mt_b) => { return self.unpack_actual_value(a, |a| { self.coerce_borrowed_pointer(expr_a, a, b, mt_b.mutbl) }); } _ => {} } self.unpack_actual_value(a, |a| { match a.sty { ty::ty_bare_fn(Some(_), a_f) => { // Function items are coercible to any closure // type; function pointers are not (that would // require double indirection). self.coerce_from_fn_item(a, a_f, b) } ty::ty_bare_fn(None, a_f) => { // We permit coercion of fn pointers to drop the // unsafe qualifier. self.coerce_from_fn_pointer(a, a_f, b) } _ => { // Otherwise, just use subtyping rules. self.subtype(a, b) } } }) } /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`. /// To match `A` with `B`, autoderef will be performed, /// calling `deref`/`deref_mut` where necessary. fn coerce_borrowed_pointer(&self, expr_a: &ast::Expr, a: Ty<'tcx>, b: Ty<'tcx>, mutbl_b: ast::Mutability) -> CoerceResult<'tcx> { debug!("coerce_borrowed_pointer(a={}, b={})", a.repr(self.tcx()), b.repr(self.tcx())); // If we have a parameter of type `&M T_a` and the value // provided is `expr`, we will be adding an implicit borrow, // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore, // to type check, we will construct the type that `&M*expr` would // yield. match a.sty { ty::ty_rptr(_, mt_a) => { try!(coerce_mutbls(mt_a.mutbl, mutbl_b)); } _ => return self.subtype(a, b) } let coercion = Coercion(self.origin.span()); let r_borrow = self.fcx.infcx().next_region_var(coercion); let r_borrow = self.tcx().mk_region(r_borrow); let autoref = Some(ty::AutoPtr(r_borrow, mutbl_b)); let lvalue_pref = match mutbl_b { ast::MutMutable => PreferMutLvalue, ast::MutImmutable => NoPreference }; let mut first_error = None; let (_, autoderefs, success) = autoderef(self.fcx, expr_a.span, a, Some(expr_a), UnresolvedTypeAction::Ignore, lvalue_pref, |inner_ty, autoderef| { if autoderef == 0 { // Don't let this pass, otherwise it would cause // &T to autoref to &&T. return None; } let ty = ty::mk_rptr(self.tcx(), r_borrow, mt {ty: inner_ty, mutbl: mutbl_b}); if let Err(err) = self.subtype(ty, b) { if first_error.is_none() { first_error = Some(err); } None } else { Some(()) } }); match success { Some(_) => { Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: autoderefs, autoref: autoref, unsize: None }))) } None => { // Return original error as if overloaded deref was never // attempted, to avoid irrelevant/confusing error messages. Err(first_error.expect("coerce_borrowed_pointer failed with no error?")) } } } // &[T, ..n] or &mut [T, ..n] -> &[T] // or &mut [T, ..n] -> &mut [T] // or &Concrete -> &Trait, etc. fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx>
fn coerce_from_fn_pointer(&self, a: Ty<'tcx>, fn_ty_a: &'tcx ty::BareFnTy<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { /*! * Attempts to coerce from the type of a Rust function item * into a closure or a `proc`. */ self.unpack_actual_value(b, |b| { debug!("coerce_from_fn_pointer(a={}, b={})", a.repr(self.tcx()), b.repr(self.tcx())); if let ty::ty_bare_fn(None, fn_ty_b) = b.sty { match (fn_ty_a.unsafety, fn_ty_b.unsafety) { (ast::Unsafety::Normal, ast::Unsafety::Unsafe) => { let unsafe_a = self.tcx().safe_to_unsafe_fn_ty(fn_ty_a); try!(self.subtype(unsafe_a, b)); return Ok(Some(ty::AdjustUnsafeFnPointer)); } _ => {} } } self.subtype(a, b) }) } fn coerce_from_fn_item(&self, a: Ty<'tcx>, fn_ty_a: &'tcx ty::BareFnTy<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { /*! * Attempts to coerce from the type of a Rust function item * into a closure or a `proc`. */ self.unpack_actual_value(b, |b| { debug!("coerce_from_fn_item(a={}, b={})", a.repr(self.tcx()), b.repr(self.tcx())); match b.sty { ty::ty_bare_fn(None, _) => { let a_fn_pointer = ty::mk_bare_fn(self.tcx(), None, fn_ty_a); try!(self.subtype(a_fn_pointer, b)); Ok(Some(ty::AdjustReifyFnPointer)) } _ => self.subtype(a, b) } }) } fn coerce_unsafe_ptr(&self, a: Ty<'tcx>, b: Ty<'tcx>, mutbl_b: ast::Mutability) -> CoerceResult<'tcx> { debug!("coerce_unsafe_ptr(a={}, b={})", a.repr(self.tcx()), b.repr(self.tcx())); let mt_a = match a.sty { ty::ty_rptr(_, mt) | ty::ty_ptr(mt) => mt, _ => { return self.subtype(a, b); } }; // Check that the types which they point at are compatible. let a_unsafe = ty::mk_ptr(self.tcx(), ty::mt{ mutbl: mutbl_b, ty: mt_a.ty }); try!(self.subtype(a_unsafe, b)); try!(coerce_mutbls(mt_a.mutbl, mutbl_b)); // Although references and unsafe ptrs have the same // representation, we still register an AutoDerefRef so that // regionck knows that the region for `a` must be valid here. Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(ty::AutoUnsafe(mutbl_b)), unsize: None }))) } } pub fn mk_assignty<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, expr: &ast::Expr, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, ()> { debug!("mk_assignty({} -> {})", a.repr(fcx.tcx()), b.repr(fcx.tcx())); let mut unsizing_obligations = vec![]; let adjustment = try!(indent(|| { fcx.infcx().commit_if_ok(|_| { let coerce = Coerce { fcx: fcx, origin: infer::ExprAssignable(expr.span), unsizing_obligations: RefCell::new(vec![]) }; let adjustment = try!(coerce.coerce(expr, a, b)); unsizing_obligations = coerce.unsizing_obligations.into_inner(); Ok(adjustment) }) })); if let Some(AdjustDerefRef(auto)) = adjustment { if auto.unsize.is_some() { for obligation in unsizing_obligations { fcx.register_predicate(obligation); } } } if let Some(adjustment) = adjustment { debug!("Success, coerced with {}", adjustment.repr(fcx.tcx())); fcx.write_adjustment(expr.id, adjustment); } Ok(()) } fn coerce_mutbls<'tcx>(from_mutbl: ast::Mutability, to_mutbl: ast::Mutability) -> CoerceResult<'tcx> { match (from_mutbl, to_mutbl) { (ast::MutMutable, ast::MutMutable) | (ast::MutImmutable, ast::MutImmutable) | (ast::MutMutable, ast::MutImmutable) => Ok(None), (ast::MutImmutable, ast::MutMutable) => Err(ty::terr_mutability) } }
{ debug!("coerce_unsized(source={}, target={})", source.repr(self.tcx()), target.repr(self.tcx())); let traits = (self.tcx().lang_items.unsize_trait(), self.tcx().lang_items.coerce_unsized_trait()); let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits { (u, cu) } else { debug!("Missing Unsize or CoerceUnsized traits"); return Err(ty::terr_mismatch); }; // Note, we want to avoid unnecessary unsizing. We don't want to coerce to // a DST unless we have to. This currently comes out in the wash since // we can't unify [T] with U. But to properly support DST, we need to allow // that, at which point we will need extra checks on the target here. // Handle reborrows before selecting `Source: CoerceUnsized<Target>`. let (source, reborrow) = match (&source.sty, &target.sty) { (&ty::ty_rptr(_, mt_a), &ty::ty_rptr(_, mt_b)) => { try!(coerce_mutbls(mt_a.mutbl, mt_b.mutbl)); let coercion = Coercion(self.origin.span()); let r_borrow = self.fcx.infcx().next_region_var(coercion); let region = self.tcx().mk_region(r_borrow); (mt_a.ty, Some(ty::AutoPtr(region, mt_b.mutbl))) } (&ty::ty_rptr(_, mt_a), &ty::ty_ptr(mt_b)) => { try!(coerce_mutbls(mt_a.mutbl, mt_b.mutbl)); (mt_a.ty, Some(ty::AutoUnsafe(mt_b.mutbl))) } _ => (source, None) }; let source = ty::adjust_ty_for_autoref(self.tcx(), source, reborrow); let mut selcx = traits::SelectionContext::new(self.fcx.infcx(), self.fcx); // Use a FIFO queue for this custom fulfillment procedure. let mut queue = VecDeque::new(); let mut leftover_predicates = vec![]; // Create an obligation for `Source: CoerceUnsized<Target>`. let cause = ObligationCause::misc(self.origin.span(), self.fcx.body_id); queue.push_back(predicate_for_trait_def(self.tcx(), cause, coerce_unsized_did, 0, source, vec![target])); // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where // inference might unify those two inner type variables later. let traits = [coerce_unsized_did, unsize_did]; while let Some(obligation) = queue.pop_front() { debug!("coerce_unsized resolve step: {}", obligation.repr(self.tcx())); let trait_ref = match obligation.predicate { ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => { tr.clone() } _ => { leftover_predicates.push(obligation); continue; } }; match selcx.select(&obligation.with(trait_ref)) { // Uncertain or unimplemented. Ok(None) | Err(traits::Unimplemented) => { debug!("coerce_unsized: early return - can't prove obligation"); return Err(ty::terr_mismatch); } // Object safety violations or miscellaneous. Err(err) => { report_selection_error(self.fcx.infcx(), &obligation, &err); // Treat this like an obligation and follow through // with the unsizing - the lack of a coercion should // be silent, as it causes a type mismatch later. } Ok(Some(vtable)) => { vtable.map_move_nested(|o| queue.push_back(o)); } } } let mut obligations = self.unsizing_obligations.borrow_mut(); assert!(obligations.is_empty()); *obligations = leftover_predicates; let adjustment = AutoDerefRef { autoderefs: if reborrow.is_some() { 1 } else { 0 }, autoref: reborrow, unsize: Some(target) }; debug!("Success, coerced with {}", adjustment.repr(self.tcx())); Ok(Some(AdjustDerefRef(adjustment))) }
identifier_body
main.py
from flask import Blueprint, render_template, redirect, url_for, current_app monitoring_main = Blueprint('monitoring_main', __name__, # pylint: disable=invalid-name template_folder='templates', static_url_path='/static',
def inject_data(): data = { 'dashboards': current_app.config['monitoring']['dashboards'], 'uchiwa_url': current_app.config['monitoring']['uchiwa_url'], } return data @monitoring_main.route('/') def index(): return redirect(url_for('monitoring_main.events')) @monitoring_main.route('/events') def events(): return render_template('events.html', title='Events') @monitoring_main.route('/checks') def checks(): return render_template('checks.html', title='Checks') @monitoring_main.route('/clients') def clients(): return render_template('clients.html', title='Clients') @monitoring_main.route('/clients/<zone>/<client_name>') def client(zone, client_name): return render_template('client_details.html', zone=zone, client=client_name, title='Client Details') @monitoring_main.route('/clients/<zone>/<client_name>/events/<check>') def client_event(zone, client_name, check): return render_template('client_event_details.html', zone=zone, client=client_name, check=check, title='Event Details')
static_folder='static') @monitoring_main.context_processor
random_line_split
main.py
from flask import Blueprint, render_template, redirect, url_for, current_app monitoring_main = Blueprint('monitoring_main', __name__, # pylint: disable=invalid-name template_folder='templates', static_url_path='/static', static_folder='static') @monitoring_main.context_processor def inject_data(): data = { 'dashboards': current_app.config['monitoring']['dashboards'], 'uchiwa_url': current_app.config['monitoring']['uchiwa_url'], } return data @monitoring_main.route('/') def index():
@monitoring_main.route('/events') def events(): return render_template('events.html', title='Events') @monitoring_main.route('/checks') def checks(): return render_template('checks.html', title='Checks') @monitoring_main.route('/clients') def clients(): return render_template('clients.html', title='Clients') @monitoring_main.route('/clients/<zone>/<client_name>') def client(zone, client_name): return render_template('client_details.html', zone=zone, client=client_name, title='Client Details') @monitoring_main.route('/clients/<zone>/<client_name>/events/<check>') def client_event(zone, client_name, check): return render_template('client_event_details.html', zone=zone, client=client_name, check=check, title='Event Details')
return redirect(url_for('monitoring_main.events'))
identifier_body
main.py
from flask import Blueprint, render_template, redirect, url_for, current_app monitoring_main = Blueprint('monitoring_main', __name__, # pylint: disable=invalid-name template_folder='templates', static_url_path='/static', static_folder='static') @monitoring_main.context_processor def inject_data(): data = { 'dashboards': current_app.config['monitoring']['dashboards'], 'uchiwa_url': current_app.config['monitoring']['uchiwa_url'], } return data @monitoring_main.route('/') def index(): return redirect(url_for('monitoring_main.events')) @monitoring_main.route('/events') def events(): return render_template('events.html', title='Events') @monitoring_main.route('/checks') def
(): return render_template('checks.html', title='Checks') @monitoring_main.route('/clients') def clients(): return render_template('clients.html', title='Clients') @monitoring_main.route('/clients/<zone>/<client_name>') def client(zone, client_name): return render_template('client_details.html', zone=zone, client=client_name, title='Client Details') @monitoring_main.route('/clients/<zone>/<client_name>/events/<check>') def client_event(zone, client_name, check): return render_template('client_event_details.html', zone=zone, client=client_name, check=check, title='Event Details')
checks
identifier_name
test_render.py
""" Tests for content rendering """
import ddt from discussion_api.render import render_body def _add_p_tags(raw_body): """Return raw_body surrounded by p tags""" return "<p>{raw_body}</p>".format(raw_body=raw_body) @ddt.ddt class RenderBodyTest(TestCase): """Tests for render_body""" def test_empty(self): self.assertEqual(render_body(""), "") @ddt.data( ("*", "em"), ("**", "strong"), ("`", "code"), ) @ddt.unpack def test_markdown_inline(self, delimiter, tag): self.assertEqual( render_body("{delimiter}some text{delimiter}".format(delimiter=delimiter)), "<p><{tag}>some text</{tag}></p>".format(tag=tag) ) @ddt.data( "b", "blockquote", "code", "del", "dd", "dl", "dt", "em", "h1", "h2", "h3", "i", "kbd", "li", "ol", "p", "pre", "s", "sup", "sub", "strong", "strike", "ul" ) def test_openclose_tag(self, tag): raw_body = "<{tag}>some text</{tag}>".format(tag=tag) is_inline_tag = tag in ["b", "code", "del", "em", "i", "kbd", "s", "sup", "sub", "strong", "strike"] rendered_body = _add_p_tags(raw_body) if is_inline_tag else raw_body self.assertEqual(render_body(raw_body), rendered_body) @ddt.data("br", "hr") def test_selfclosing_tag(self, tag): raw_body = "<{tag}>".format(tag=tag) is_inline_tag = tag == "br" rendered_body = _add_p_tags(raw_body) if is_inline_tag else raw_body self.assertEqual(render_body(raw_body), rendered_body) @ddt.data("http", "https", "ftp") def test_allowed_a_tag(self, protocol): raw_body = '<a href="{protocol}://foo" title="bar">baz</a>'.format(protocol=protocol) self.assertEqual(render_body(raw_body), _add_p_tags(raw_body)) def test_disallowed_a_tag(self): raw_body = '<a href="gopher://foo">link content</a>' self.assertEqual(render_body(raw_body), "<p>link content</p>") @ddt.data("http", "https") def test_allowed_img_tag(self, protocol): raw_body = '<img src="{protocol}://foo" width="111" height="222" alt="bar" title="baz">'.format( protocol=protocol ) self.assertEqual(render_body(raw_body), _add_p_tags(raw_body)) def test_disallowed_img_tag(self): raw_body = '<img src="gopher://foo">' self.assertEqual(render_body(raw_body), "<p></p>") def test_script_tag(self): raw_body = '<script type="text/javascript">alert("evil script");</script>' self.assertEqual(render_body(raw_body), 'alert("evil script");') @ddt.data("p", "br", "li", "hr") # img is tested above def test_allowed_unpaired_tags(self, tag): raw_body = "foo<{tag}>bar".format(tag=tag) self.assertEqual(render_body(raw_body), _add_p_tags(raw_body)) def test_unpaired_start_tag(self): self.assertEqual(render_body("foo<i>bar"), "<p>foobar</p>") def test_unpaired_end_tag(self): self.assertEqual(render_body("foo</i>bar"), "<p>foobar</p>") def test_interleaved_tags(self): self.assertEqual( render_body("foo<i>bar<b>baz</i>quux</b>greg"), "<p>foo<i>barbaz</i>quuxgreg</p>" )
from unittest import TestCase
random_line_split
test_render.py
""" Tests for content rendering """ from unittest import TestCase import ddt from discussion_api.render import render_body def _add_p_tags(raw_body): """Return raw_body surrounded by p tags""" return "<p>{raw_body}</p>".format(raw_body=raw_body) @ddt.ddt class RenderBodyTest(TestCase): """Tests for render_body""" def test_empty(self): self.assertEqual(render_body(""), "") @ddt.data( ("*", "em"), ("**", "strong"), ("`", "code"), ) @ddt.unpack def test_markdown_inline(self, delimiter, tag): self.assertEqual( render_body("{delimiter}some text{delimiter}".format(delimiter=delimiter)), "<p><{tag}>some text</{tag}></p>".format(tag=tag) ) @ddt.data( "b", "blockquote", "code", "del", "dd", "dl", "dt", "em", "h1", "h2", "h3", "i", "kbd", "li", "ol", "p", "pre", "s", "sup", "sub", "strong", "strike", "ul" ) def test_openclose_tag(self, tag): raw_body = "<{tag}>some text</{tag}>".format(tag=tag) is_inline_tag = tag in ["b", "code", "del", "em", "i", "kbd", "s", "sup", "sub", "strong", "strike"] rendered_body = _add_p_tags(raw_body) if is_inline_tag else raw_body self.assertEqual(render_body(raw_body), rendered_body) @ddt.data("br", "hr") def test_selfclosing_tag(self, tag): raw_body = "<{tag}>".format(tag=tag) is_inline_tag = tag == "br" rendered_body = _add_p_tags(raw_body) if is_inline_tag else raw_body self.assertEqual(render_body(raw_body), rendered_body) @ddt.data("http", "https", "ftp") def test_allowed_a_tag(self, protocol): raw_body = '<a href="{protocol}://foo" title="bar">baz</a>'.format(protocol=protocol) self.assertEqual(render_body(raw_body), _add_p_tags(raw_body)) def test_disallowed_a_tag(self): raw_body = '<a href="gopher://foo">link content</a>' self.assertEqual(render_body(raw_body), "<p>link content</p>") @ddt.data("http", "https") def test_allowed_img_tag(self, protocol): raw_body = '<img src="{protocol}://foo" width="111" height="222" alt="bar" title="baz">'.format( protocol=protocol ) self.assertEqual(render_body(raw_body), _add_p_tags(raw_body)) def
(self): raw_body = '<img src="gopher://foo">' self.assertEqual(render_body(raw_body), "<p></p>") def test_script_tag(self): raw_body = '<script type="text/javascript">alert("evil script");</script>' self.assertEqual(render_body(raw_body), 'alert("evil script");') @ddt.data("p", "br", "li", "hr") # img is tested above def test_allowed_unpaired_tags(self, tag): raw_body = "foo<{tag}>bar".format(tag=tag) self.assertEqual(render_body(raw_body), _add_p_tags(raw_body)) def test_unpaired_start_tag(self): self.assertEqual(render_body("foo<i>bar"), "<p>foobar</p>") def test_unpaired_end_tag(self): self.assertEqual(render_body("foo</i>bar"), "<p>foobar</p>") def test_interleaved_tags(self): self.assertEqual( render_body("foo<i>bar<b>baz</i>quux</b>greg"), "<p>foo<i>barbaz</i>quuxgreg</p>" )
test_disallowed_img_tag
identifier_name
test_render.py
""" Tests for content rendering """ from unittest import TestCase import ddt from discussion_api.render import render_body def _add_p_tags(raw_body): """Return raw_body surrounded by p tags""" return "<p>{raw_body}</p>".format(raw_body=raw_body) @ddt.ddt class RenderBodyTest(TestCase): """Tests for render_body""" def test_empty(self): self.assertEqual(render_body(""), "") @ddt.data( ("*", "em"), ("**", "strong"), ("`", "code"), ) @ddt.unpack def test_markdown_inline(self, delimiter, tag): self.assertEqual( render_body("{delimiter}some text{delimiter}".format(delimiter=delimiter)), "<p><{tag}>some text</{tag}></p>".format(tag=tag) ) @ddt.data( "b", "blockquote", "code", "del", "dd", "dl", "dt", "em", "h1", "h2", "h3", "i", "kbd", "li", "ol", "p", "pre", "s", "sup", "sub", "strong", "strike", "ul" ) def test_openclose_tag(self, tag): raw_body = "<{tag}>some text</{tag}>".format(tag=tag) is_inline_tag = tag in ["b", "code", "del", "em", "i", "kbd", "s", "sup", "sub", "strong", "strike"] rendered_body = _add_p_tags(raw_body) if is_inline_tag else raw_body self.assertEqual(render_body(raw_body), rendered_body) @ddt.data("br", "hr") def test_selfclosing_tag(self, tag): raw_body = "<{tag}>".format(tag=tag) is_inline_tag = tag == "br" rendered_body = _add_p_tags(raw_body) if is_inline_tag else raw_body self.assertEqual(render_body(raw_body), rendered_body) @ddt.data("http", "https", "ftp") def test_allowed_a_tag(self, protocol): raw_body = '<a href="{protocol}://foo" title="bar">baz</a>'.format(protocol=protocol) self.assertEqual(render_body(raw_body), _add_p_tags(raw_body)) def test_disallowed_a_tag(self):
@ddt.data("http", "https") def test_allowed_img_tag(self, protocol): raw_body = '<img src="{protocol}://foo" width="111" height="222" alt="bar" title="baz">'.format( protocol=protocol ) self.assertEqual(render_body(raw_body), _add_p_tags(raw_body)) def test_disallowed_img_tag(self): raw_body = '<img src="gopher://foo">' self.assertEqual(render_body(raw_body), "<p></p>") def test_script_tag(self): raw_body = '<script type="text/javascript">alert("evil script");</script>' self.assertEqual(render_body(raw_body), 'alert("evil script");') @ddt.data("p", "br", "li", "hr") # img is tested above def test_allowed_unpaired_tags(self, tag): raw_body = "foo<{tag}>bar".format(tag=tag) self.assertEqual(render_body(raw_body), _add_p_tags(raw_body)) def test_unpaired_start_tag(self): self.assertEqual(render_body("foo<i>bar"), "<p>foobar</p>") def test_unpaired_end_tag(self): self.assertEqual(render_body("foo</i>bar"), "<p>foobar</p>") def test_interleaved_tags(self): self.assertEqual( render_body("foo<i>bar<b>baz</i>quux</b>greg"), "<p>foo<i>barbaz</i>quuxgreg</p>" )
raw_body = '<a href="gopher://foo">link content</a>' self.assertEqual(render_body(raw_body), "<p>link content</p>")
identifier_body
resolve.rs
use std::collections::{HashMap, HashSet}; use core::{Package, PackageId, SourceId}; use core::registry::PackageRegistry; use core::resolver::{self, Resolve, Method}; use ops; use util::CargoResult; /// Resolve all dependencies for the specified `package` using the previous /// lockfile as a guide if present. /// /// This function will also write the result of resolution as a new /// lockfile. pub fn resolve_pkg(registry: &mut PackageRegistry, package: &Package) -> CargoResult<Resolve> { let prev = try!(ops::load_pkg_lockfile(package)); let resolve = try!(resolve_with_previous(registry, package, Method::Everything, prev.as_ref(), None)); if package.package_id().source_id().is_path() { try!(ops::write_pkg_lockfile(package, &resolve)); } Ok(resolve) } /// Resolve all dependencies for a package using an optional previous instance /// of resolve to guide the resolution process. /// /// This also takes an optional hash set, `to_avoid`, which is a list of package /// ids that should be avoided when consulting the previous instance of resolve /// (often used in pairings with updates). /// /// The previous resolve normally comes from a lockfile. This function does not /// read or write lockfiles from the filesystem. pub fn resolve_with_previous<'a>(registry: &mut PackageRegistry, package: &Package, method: Method, previous: Option<&'a Resolve>, to_avoid: Option<&HashSet<&'a PackageId>>) -> CargoResult<Resolve> { try!(registry.add_sources(&[package.package_id().source_id() .clone()])); // Here we place an artificial limitation that all non-registry sources // cannot be locked at more than one revision. This means that if a git // repository provides more than one package, they must all be updated in // step when any of them are updated. // // TODO: This seems like a hokey reason to single out the registry as being // different let mut to_avoid_sources = HashSet::new(); match to_avoid { Some(set) => { for package_id in set.iter() { let source = package_id.source_id(); if !source.is_registry() { to_avoid_sources.insert(source); } } } None => {} } let summary = package.summary().clone(); let summary = match previous { Some(r) => { // In the case where a previous instance of resolve is available, we // want to lock as many packages as possible to the previous version // without disturbing the graph structure. To this end we perform // two actions here: // // 1. We inform the package registry of all locked packages. This // involves informing it of both the locked package's id as well // as the versions of all locked dependencies. The registry will // then takes this information into account when it is queried. // // 2. The specified package's summary will have its dependencies // modified to their precise variants. This will instruct the // first step of the resolution process to not query for ranges // but rather for precise dependency versions. // // This process must handle altered dependencies, however, as // it's possible for a manifest to change over time to have // dependencies added, removed, or modified to different version // ranges. To deal with this, we only actually lock a dependency // to the previously resolved version if the dependency listed // still matches the locked version. for node in r.iter().filter(|p| keep(p, to_avoid, &to_avoid_sources)) { let deps = r.deps(node).into_iter().flat_map(|i| i) .filter(|p| keep(p, to_avoid, &to_avoid_sources)) .map(|p| p.clone()).collect(); registry.register_lock(node.clone(), deps); } let map = r.deps(r.root()).into_iter().flat_map(|i| i).filter(|p| { keep(p, to_avoid, &to_avoid_sources) }).map(|d| { (d.name(), d) }).collect::<HashMap<_, _>>(); summary.map_dependencies(|d| { match map.get(d.name()) { Some(&lock) if d.matches_id(lock) => d.lock_to(lock), _ => d, } }) } None => summary, };
let mut resolved = try!(resolver::resolve(&summary, &method, registry)); match previous { Some(r) => resolved.copy_metadata(r), None => {} } return Ok(resolved); fn keep<'a>(p: &&'a PackageId, to_avoid_packages: Option<&HashSet<&'a PackageId>>, to_avoid_sources: &HashSet<&'a SourceId>) -> bool { !to_avoid_sources.contains(&p.source_id()) && match to_avoid_packages { Some(set) => !set.contains(p), None => true, } } }
random_line_split
resolve.rs
use std::collections::{HashMap, HashSet}; use core::{Package, PackageId, SourceId}; use core::registry::PackageRegistry; use core::resolver::{self, Resolve, Method}; use ops; use util::CargoResult; /// Resolve all dependencies for the specified `package` using the previous /// lockfile as a guide if present. /// /// This function will also write the result of resolution as a new /// lockfile. pub fn resolve_pkg(registry: &mut PackageRegistry, package: &Package) -> CargoResult<Resolve> { let prev = try!(ops::load_pkg_lockfile(package)); let resolve = try!(resolve_with_previous(registry, package, Method::Everything, prev.as_ref(), None)); if package.package_id().source_id().is_path() { try!(ops::write_pkg_lockfile(package, &resolve)); } Ok(resolve) } /// Resolve all dependencies for a package using an optional previous instance /// of resolve to guide the resolution process. /// /// This also takes an optional hash set, `to_avoid`, which is a list of package /// ids that should be avoided when consulting the previous instance of resolve /// (often used in pairings with updates). /// /// The previous resolve normally comes from a lockfile. This function does not /// read or write lockfiles from the filesystem. pub fn resolve_with_previous<'a>(registry: &mut PackageRegistry, package: &Package, method: Method, previous: Option<&'a Resolve>, to_avoid: Option<&HashSet<&'a PackageId>>) -> CargoResult<Resolve>
{ try!(registry.add_sources(&[package.package_id().source_id() .clone()])); // Here we place an artificial limitation that all non-registry sources // cannot be locked at more than one revision. This means that if a git // repository provides more than one package, they must all be updated in // step when any of them are updated. // // TODO: This seems like a hokey reason to single out the registry as being // different let mut to_avoid_sources = HashSet::new(); match to_avoid { Some(set) => { for package_id in set.iter() { let source = package_id.source_id(); if !source.is_registry() { to_avoid_sources.insert(source); } } } None => {} } let summary = package.summary().clone(); let summary = match previous { Some(r) => { // In the case where a previous instance of resolve is available, we // want to lock as many packages as possible to the previous version // without disturbing the graph structure. To this end we perform // two actions here: // // 1. We inform the package registry of all locked packages. This // involves informing it of both the locked package's id as well // as the versions of all locked dependencies. The registry will // then takes this information into account when it is queried. // // 2. The specified package's summary will have its dependencies // modified to their precise variants. This will instruct the // first step of the resolution process to not query for ranges // but rather for precise dependency versions. // // This process must handle altered dependencies, however, as // it's possible for a manifest to change over time to have // dependencies added, removed, or modified to different version // ranges. To deal with this, we only actually lock a dependency // to the previously resolved version if the dependency listed // still matches the locked version. for node in r.iter().filter(|p| keep(p, to_avoid, &to_avoid_sources)) { let deps = r.deps(node).into_iter().flat_map(|i| i) .filter(|p| keep(p, to_avoid, &to_avoid_sources)) .map(|p| p.clone()).collect(); registry.register_lock(node.clone(), deps); } let map = r.deps(r.root()).into_iter().flat_map(|i| i).filter(|p| { keep(p, to_avoid, &to_avoid_sources) }).map(|d| { (d.name(), d) }).collect::<HashMap<_, _>>(); summary.map_dependencies(|d| { match map.get(d.name()) { Some(&lock) if d.matches_id(lock) => d.lock_to(lock), _ => d, } }) } None => summary, }; let mut resolved = try!(resolver::resolve(&summary, &method, registry)); match previous { Some(r) => resolved.copy_metadata(r), None => {} } return Ok(resolved); fn keep<'a>(p: &&'a PackageId, to_avoid_packages: Option<&HashSet<&'a PackageId>>, to_avoid_sources: &HashSet<&'a SourceId>) -> bool { !to_avoid_sources.contains(&p.source_id()) && match to_avoid_packages { Some(set) => !set.contains(p), None => true, } } }
identifier_body
resolve.rs
use std::collections::{HashMap, HashSet}; use core::{Package, PackageId, SourceId}; use core::registry::PackageRegistry; use core::resolver::{self, Resolve, Method}; use ops; use util::CargoResult; /// Resolve all dependencies for the specified `package` using the previous /// lockfile as a guide if present. /// /// This function will also write the result of resolution as a new /// lockfile. pub fn resolve_pkg(registry: &mut PackageRegistry, package: &Package) -> CargoResult<Resolve> { let prev = try!(ops::load_pkg_lockfile(package)); let resolve = try!(resolve_with_previous(registry, package, Method::Everything, prev.as_ref(), None)); if package.package_id().source_id().is_path() { try!(ops::write_pkg_lockfile(package, &resolve)); } Ok(resolve) } /// Resolve all dependencies for a package using an optional previous instance /// of resolve to guide the resolution process. /// /// This also takes an optional hash set, `to_avoid`, which is a list of package /// ids that should be avoided when consulting the previous instance of resolve /// (often used in pairings with updates). /// /// The previous resolve normally comes from a lockfile. This function does not /// read or write lockfiles from the filesystem. pub fn
<'a>(registry: &mut PackageRegistry, package: &Package, method: Method, previous: Option<&'a Resolve>, to_avoid: Option<&HashSet<&'a PackageId>>) -> CargoResult<Resolve> { try!(registry.add_sources(&[package.package_id().source_id() .clone()])); // Here we place an artificial limitation that all non-registry sources // cannot be locked at more than one revision. This means that if a git // repository provides more than one package, they must all be updated in // step when any of them are updated. // // TODO: This seems like a hokey reason to single out the registry as being // different let mut to_avoid_sources = HashSet::new(); match to_avoid { Some(set) => { for package_id in set.iter() { let source = package_id.source_id(); if !source.is_registry() { to_avoid_sources.insert(source); } } } None => {} } let summary = package.summary().clone(); let summary = match previous { Some(r) => { // In the case where a previous instance of resolve is available, we // want to lock as many packages as possible to the previous version // without disturbing the graph structure. To this end we perform // two actions here: // // 1. We inform the package registry of all locked packages. This // involves informing it of both the locked package's id as well // as the versions of all locked dependencies. The registry will // then takes this information into account when it is queried. // // 2. The specified package's summary will have its dependencies // modified to their precise variants. This will instruct the // first step of the resolution process to not query for ranges // but rather for precise dependency versions. // // This process must handle altered dependencies, however, as // it's possible for a manifest to change over time to have // dependencies added, removed, or modified to different version // ranges. To deal with this, we only actually lock a dependency // to the previously resolved version if the dependency listed // still matches the locked version. for node in r.iter().filter(|p| keep(p, to_avoid, &to_avoid_sources)) { let deps = r.deps(node).into_iter().flat_map(|i| i) .filter(|p| keep(p, to_avoid, &to_avoid_sources)) .map(|p| p.clone()).collect(); registry.register_lock(node.clone(), deps); } let map = r.deps(r.root()).into_iter().flat_map(|i| i).filter(|p| { keep(p, to_avoid, &to_avoid_sources) }).map(|d| { (d.name(), d) }).collect::<HashMap<_, _>>(); summary.map_dependencies(|d| { match map.get(d.name()) { Some(&lock) if d.matches_id(lock) => d.lock_to(lock), _ => d, } }) } None => summary, }; let mut resolved = try!(resolver::resolve(&summary, &method, registry)); match previous { Some(r) => resolved.copy_metadata(r), None => {} } return Ok(resolved); fn keep<'a>(p: &&'a PackageId, to_avoid_packages: Option<&HashSet<&'a PackageId>>, to_avoid_sources: &HashSet<&'a SourceId>) -> bool { !to_avoid_sources.contains(&p.source_id()) && match to_avoid_packages { Some(set) => !set.contains(p), None => true, } } }
resolve_with_previous
identifier_name
plugin.js
/** * plugin.js * * Copyright, Moxiecode Systems AB * Released under LGPL License. * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /*global tinymce:true */ tinymce.PluginManager.add('image', function(editor) { function getImageSize(url, callback) { var img = document.createElement('img'); function done(width, height) { if (img.parentNode) { img.parentNode.removeChild(img); } callback({width: width, height: height}); } img.onload = function() { done(img.clientWidth, img.clientHeight); }; img.onerror = function() { done(); }; var style = img.style; style.visibility = 'hidden'; style.position = 'fixed'; style.bottom = style.left = 0; style.width = style.height = 'auto'; document.body.appendChild(img); img.src = url; } function buildListItems(inputList, itemCallback, startItems) { function appendItems(values, output) { output = output || []; tinymce.each(values, function(item) { var menuItem = {text: item.text || item.title}; if (item.menu) { menuItem.menu = appendItems(item.menu); } else { menuItem.value = item.value; itemCallback(menuItem); } output.push(menuItem); }); return output; } return appendItems(inputList, startItems || []); } function createImageList(callback) { return function() { var imageList = editor.settings.image_list; if (typeof imageList == "string") { tinymce.util.XHR.send({ url: imageList, success: function(text) { callback(tinymce.util.JSON.parse(text)); } }); } else if (typeof imageList == "function") { imageList(callback); } else { callback(imageList); } }; } function showDialog(imageList) { var win, data = {}, dom = editor.dom, imgElm = editor.selection.getNode(); var width, height, imageListCtrl, classListCtrl, imageDimensions = editor.settings.image_dimensions !== false; function recalcSize() { var widthCtrl, heightCtrl, newWidth, newHeight; widthCtrl = win.find('#width')[0]; heightCtrl = win.find('#height')[0]; if (!widthCtrl || !heightCtrl) { return; } newWidth = widthCtrl.value(); newHeight = heightCtrl.value(); if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) { if (width != newWidth) { newHeight = Math.round((newWidth / width) * newHeight); if (!isNaN(newHeight)) { heightCtrl.value(newHeight); } } else { newWidth = Math.round((newHeight / height) * newWidth); if (!isNaN(newWidth)) { widthCtrl.value(newWidth); } } } width = newWidth; height = newHeight; } function onSubmitForm() { function waitLoad(imgElm) { function selectImage() { imgElm.onload = imgElm.onerror = null; if (editor.selection) { editor.selection.select(imgElm); editor.nodeChanged(); } } imgElm.onload = function() { if (!data.width && !data.height && imageDimensions) { dom.setAttribs(imgElm, { width: imgElm.clientWidth, height: imgElm.clientHeight }); //WP editor.fire( 'wpNewImageRefresh', { node: imgElm } ); } selectImage(); }; imgElm.onerror = selectImage; } updateStyle(); recalcSize(); data = tinymce.extend(data, win.toJSON()); var caption = data.caption; // WP if (!data.alt) { data.alt = ''; } if (!data.title) { data.title = ''; } if (data.width === '') { data.width = null; } if (data.height === '') { data.height = null; } if (!data.style) { data.style = null; } // Setup new data excluding style properties /*eslint dot-notation: 0*/ data = { src: data.src, alt: data.alt, title: data.title, width: data.width, height: data.height, style: data.style, "class": data["class"] }; editor.undoManager.transact(function() { // WP var eventData = { node: imgElm, data: data, caption: caption }; editor.fire( 'wpImageFormSubmit', { imgData: eventData } ); if ( eventData.cancel ) { waitLoad( eventData.node ); return; } // WP end if (!data.src) { if (imgElm) { dom.remove(imgElm); editor.focus(); editor.nodeChanged(); } return; } if (data.title === "") { data.title = null; } if (!imgElm) { data.id = '__mcenew'; editor.focus(); editor.selection.setContent(dom.createHTML('img', data)); imgElm = dom.get('__mcenew'); dom.setAttrib(imgElm, 'id', null); } else { dom.setAttribs(imgElm, data); } waitLoad(imgElm); }); } function removePixelSuffix(value) { if (value) { value = value.replace(/px$/, ''); } return value; } function srcChange(e)
width = dom.getAttrib(imgElm, 'width'); height = dom.getAttrib(imgElm, 'height'); if (imgElm.nodeName == 'IMG' && !imgElm.getAttribute('data-mce-object') && !imgElm.getAttribute('data-mce-placeholder')) { data = { src: dom.getAttrib(imgElm, 'src'), alt: dom.getAttrib(imgElm, 'alt'), title: dom.getAttrib(imgElm, 'title'), "class": dom.getAttrib(imgElm, 'class'), width: width, height: height }; // WP editor.fire( 'wpLoadImageData', { imgData: { data: data, node: imgElm } } ); } else { imgElm = null; } if (imageList) { imageListCtrl = { type: 'listbox', label: 'Image list', values: buildListItems( imageList, function(item) { item.value = editor.convertURL(item.value || item.url, 'src'); }, [{text: 'None', value: ''}] ), value: data.src && editor.convertURL(data.src, 'src'), onselect: function(e) { var altCtrl = win.find('#alt'); if (!altCtrl.value() || (e.lastControl && altCtrl.value() == e.lastControl.text())) { altCtrl.value(e.control.text()); } win.find('#src').value(e.control.value()).fire('change'); }, onPostRender: function() { imageListCtrl = this; } }; } if (editor.settings.image_class_list) { classListCtrl = { name: 'class', type: 'listbox', label: 'Class', values: buildListItems( editor.settings.image_class_list, function(item) { if (item.value) { item.textStyle = function() { return editor.formatter.getCssText({inline: 'img', classes: [item.value]}); }; } } ) }; } // General settings shared between simple and advanced dialogs var generalFormItems = [ { name: 'src', type: 'filepicker', filetype: 'image', label: 'Source', autofocus: true, onchange: srcChange }, imageListCtrl ]; if (editor.settings.image_description !== false) { generalFormItems.push({name: 'alt', type: 'textbox', label: 'Image description'}); } if (editor.settings.image_title) { generalFormItems.push({name: 'title', type: 'textbox', label: 'Image Title'}); } if (imageDimensions) { generalFormItems.push({ type: 'container', label: 'Dimensions', layout: 'flex', direction: 'row', align: 'center', spacing: 5, items: [ {name: 'width', type: 'textbox', maxLength: 5, size: 3, onchange: recalcSize, ariaLabel: 'Width'}, {type: 'label', text: 'x'}, {name: 'height', type: 'textbox', maxLength: 5, size: 3, onchange: recalcSize, ariaLabel: 'Height'}, {name: 'constrain', type: 'checkbox', checked: true, text: 'Constrain proportions'} ] }); } generalFormItems.push(classListCtrl); // WP editor.fire( 'wpLoadImageForm', { data: generalFormItems } ); function mergeMargins(css) { if (css.margin) { var splitMargin = css.margin.split(" "); switch (splitMargin.length) { case 1: //margin: toprightbottomleft; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[0]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[0]; css['margin-left'] = css['margin-left'] || splitMargin[0]; break; case 2: //margin: topbottom rightleft; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[0]; css['margin-left'] = css['margin-left'] || splitMargin[1]; break; case 3: //margin: top rightleft bottom; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[2]; css['margin-left'] = css['margin-left'] || splitMargin[1]; break; case 4: //margin: top right bottom left; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[2]; css['margin-left'] = css['margin-left'] || splitMargin[3]; } delete css.margin; } return css; } function updateStyle() { function addPixelSuffix(value) { if (value.length > 0 && /^[0-9]+$/.test(value)) { value += 'px'; } return value; } if (!editor.settings.image_advtab) { return; } var data = win.toJSON(), css = dom.parseStyle(data.style); css = mergeMargins(css); if (data.vspace) { css['margin-top'] = css['margin-bottom'] = addPixelSuffix(data.vspace); } if (data.hspace) { css['margin-left'] = css['margin-right'] = addPixelSuffix(data.hspace); } if (data.border) { css['border-width'] = addPixelSuffix(data.border); } win.find('#style').value(dom.serializeStyle(dom.parseStyle(dom.serializeStyle(css)))); } function updateVSpaceHSpaceBorder() { if (!editor.settings.image_advtab) { return; } var data = win.toJSON(), css = dom.parseStyle(data.style); win.find('#vspace').value(""); win.find('#hspace').value(""); css = mergeMargins(css); //Move opposite equal margins to vspace/hspace field if ((css['margin-top'] && css['margin-bottom']) || (css['margin-right'] && css['margin-left'])) { if (css['margin-top'] === css['margin-bottom']) { win.find('#vspace').value(removePixelSuffix(css['margin-top'])); } else { win.find('#vspace').value(''); } if (css['margin-right'] === css['margin-left']) { win.find('#hspace').value(removePixelSuffix(css['margin-right'])); } else { win.find('#hspace').value(''); } } //Move border-width if (css['border-width']) { win.find('#border').value(removePixelSuffix(css['border-width'])); } win.find('#style').value(dom.serializeStyle(dom.parseStyle(dom.serializeStyle(css)))); } if (editor.settings.image_advtab) { // Parse styles from img if (imgElm) { if (imgElm.style.marginLeft && imgElm.style.marginRight && imgElm.style.marginLeft === imgElm.style.marginRight) { data.hspace = removePixelSuffix(imgElm.style.marginLeft); } if (imgElm.style.marginTop && imgElm.style.marginBottom && imgElm.style.marginTop === imgElm.style.marginBottom) { data.vspace = removePixelSuffix(imgElm.style.marginTop); } if (imgElm.style.borderWidth) { data.border = removePixelSuffix(imgElm.style.borderWidth); } data.style = editor.dom.serializeStyle(editor.dom.parseStyle(editor.dom.getAttrib(imgElm, 'style'))); } // Advanced dialog shows general+advanced tabs win = editor.windowManager.open({ title: 'Insert/edit image', data: data, bodyType: 'tabpanel', body: [ { title: 'General', type: 'form', items: generalFormItems }, { title: 'Advanced', type: 'form', pack: 'start', items: [ { label: 'Style', name: 'style', type: 'textbox', onchange: updateVSpaceHSpaceBorder }, { type: 'form', layout: 'grid', packV: 'start', columns: 2, padding: 0, alignH: ['left', 'right'], defaults: { type: 'textbox', maxWidth: 50, onchange: updateStyle }, items: [ {label: 'Vertical space', name: 'vspace'}, {label: 'Horizontal space', name: 'hspace'}, {label: 'Border', name: 'border'} ] } ] } ], onSubmit: onSubmitForm }); } else { // Simple default dialog win = editor.windowManager.open({ title: 'Insert/edit image', data: data, body: generalFormItems, onSubmit: onSubmitForm }); } } editor.addButton('image', { icon: 'image', tooltip: 'Insert/edit image', onclick: createImageList(showDialog), stateSelector: 'img:not([data-mce-object],[data-mce-placeholder])' }); editor.addMenuItem('image', { icon: 'image', text: 'Insert/edit image', onclick: createImageList(showDialog), context: 'insert', prependToContext: true }); editor.addCommand('mceImage', createImageList(showDialog)); });
{ var srcURL, prependURL, absoluteURLPattern, meta = e.meta || {}; if (imageListCtrl) { imageListCtrl.value(editor.convertURL(this.value(), 'src')); } tinymce.each(meta, function(value, key) { win.find('#' + key).value(value); }); if (!meta.width && !meta.height) { srcURL = editor.convertURL(this.value(), 'src'); // Pattern test the src url and make sure we haven't already prepended the url prependURL = editor.settings.image_prepend_url; absoluteURLPattern = new RegExp('^(?:[a-z]+:)?//', 'i'); if (prependURL && !absoluteURLPattern.test(srcURL) && srcURL.substring(0, prependURL.length) !== prependURL) { srcURL = prependURL + srcURL; } this.value(srcURL); getImageSize(editor.documentBaseURI.toAbsolute(this.value()), function(data) { if (data.width && data.height && imageDimensions) { width = data.width; height = data.height; win.find('#width').value(width); win.find('#height').value(height); } }); } }
identifier_body
plugin.js
/** * plugin.js * * Copyright, Moxiecode Systems AB * Released under LGPL License. * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /*global tinymce:true */ tinymce.PluginManager.add('image', function(editor) { function getImageSize(url, callback) { var img = document.createElement('img'); function
(width, height) { if (img.parentNode) { img.parentNode.removeChild(img); } callback({width: width, height: height}); } img.onload = function() { done(img.clientWidth, img.clientHeight); }; img.onerror = function() { done(); }; var style = img.style; style.visibility = 'hidden'; style.position = 'fixed'; style.bottom = style.left = 0; style.width = style.height = 'auto'; document.body.appendChild(img); img.src = url; } function buildListItems(inputList, itemCallback, startItems) { function appendItems(values, output) { output = output || []; tinymce.each(values, function(item) { var menuItem = {text: item.text || item.title}; if (item.menu) { menuItem.menu = appendItems(item.menu); } else { menuItem.value = item.value; itemCallback(menuItem); } output.push(menuItem); }); return output; } return appendItems(inputList, startItems || []); } function createImageList(callback) { return function() { var imageList = editor.settings.image_list; if (typeof imageList == "string") { tinymce.util.XHR.send({ url: imageList, success: function(text) { callback(tinymce.util.JSON.parse(text)); } }); } else if (typeof imageList == "function") { imageList(callback); } else { callback(imageList); } }; } function showDialog(imageList) { var win, data = {}, dom = editor.dom, imgElm = editor.selection.getNode(); var width, height, imageListCtrl, classListCtrl, imageDimensions = editor.settings.image_dimensions !== false; function recalcSize() { var widthCtrl, heightCtrl, newWidth, newHeight; widthCtrl = win.find('#width')[0]; heightCtrl = win.find('#height')[0]; if (!widthCtrl || !heightCtrl) { return; } newWidth = widthCtrl.value(); newHeight = heightCtrl.value(); if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) { if (width != newWidth) { newHeight = Math.round((newWidth / width) * newHeight); if (!isNaN(newHeight)) { heightCtrl.value(newHeight); } } else { newWidth = Math.round((newHeight / height) * newWidth); if (!isNaN(newWidth)) { widthCtrl.value(newWidth); } } } width = newWidth; height = newHeight; } function onSubmitForm() { function waitLoad(imgElm) { function selectImage() { imgElm.onload = imgElm.onerror = null; if (editor.selection) { editor.selection.select(imgElm); editor.nodeChanged(); } } imgElm.onload = function() { if (!data.width && !data.height && imageDimensions) { dom.setAttribs(imgElm, { width: imgElm.clientWidth, height: imgElm.clientHeight }); //WP editor.fire( 'wpNewImageRefresh', { node: imgElm } ); } selectImage(); }; imgElm.onerror = selectImage; } updateStyle(); recalcSize(); data = tinymce.extend(data, win.toJSON()); var caption = data.caption; // WP if (!data.alt) { data.alt = ''; } if (!data.title) { data.title = ''; } if (data.width === '') { data.width = null; } if (data.height === '') { data.height = null; } if (!data.style) { data.style = null; } // Setup new data excluding style properties /*eslint dot-notation: 0*/ data = { src: data.src, alt: data.alt, title: data.title, width: data.width, height: data.height, style: data.style, "class": data["class"] }; editor.undoManager.transact(function() { // WP var eventData = { node: imgElm, data: data, caption: caption }; editor.fire( 'wpImageFormSubmit', { imgData: eventData } ); if ( eventData.cancel ) { waitLoad( eventData.node ); return; } // WP end if (!data.src) { if (imgElm) { dom.remove(imgElm); editor.focus(); editor.nodeChanged(); } return; } if (data.title === "") { data.title = null; } if (!imgElm) { data.id = '__mcenew'; editor.focus(); editor.selection.setContent(dom.createHTML('img', data)); imgElm = dom.get('__mcenew'); dom.setAttrib(imgElm, 'id', null); } else { dom.setAttribs(imgElm, data); } waitLoad(imgElm); }); } function removePixelSuffix(value) { if (value) { value = value.replace(/px$/, ''); } return value; } function srcChange(e) { var srcURL, prependURL, absoluteURLPattern, meta = e.meta || {}; if (imageListCtrl) { imageListCtrl.value(editor.convertURL(this.value(), 'src')); } tinymce.each(meta, function(value, key) { win.find('#' + key).value(value); }); if (!meta.width && !meta.height) { srcURL = editor.convertURL(this.value(), 'src'); // Pattern test the src url and make sure we haven't already prepended the url prependURL = editor.settings.image_prepend_url; absoluteURLPattern = new RegExp('^(?:[a-z]+:)?//', 'i'); if (prependURL && !absoluteURLPattern.test(srcURL) && srcURL.substring(0, prependURL.length) !== prependURL) { srcURL = prependURL + srcURL; } this.value(srcURL); getImageSize(editor.documentBaseURI.toAbsolute(this.value()), function(data) { if (data.width && data.height && imageDimensions) { width = data.width; height = data.height; win.find('#width').value(width); win.find('#height').value(height); } }); } } width = dom.getAttrib(imgElm, 'width'); height = dom.getAttrib(imgElm, 'height'); if (imgElm.nodeName == 'IMG' && !imgElm.getAttribute('data-mce-object') && !imgElm.getAttribute('data-mce-placeholder')) { data = { src: dom.getAttrib(imgElm, 'src'), alt: dom.getAttrib(imgElm, 'alt'), title: dom.getAttrib(imgElm, 'title'), "class": dom.getAttrib(imgElm, 'class'), width: width, height: height }; // WP editor.fire( 'wpLoadImageData', { imgData: { data: data, node: imgElm } } ); } else { imgElm = null; } if (imageList) { imageListCtrl = { type: 'listbox', label: 'Image list', values: buildListItems( imageList, function(item) { item.value = editor.convertURL(item.value || item.url, 'src'); }, [{text: 'None', value: ''}] ), value: data.src && editor.convertURL(data.src, 'src'), onselect: function(e) { var altCtrl = win.find('#alt'); if (!altCtrl.value() || (e.lastControl && altCtrl.value() == e.lastControl.text())) { altCtrl.value(e.control.text()); } win.find('#src').value(e.control.value()).fire('change'); }, onPostRender: function() { imageListCtrl = this; } }; } if (editor.settings.image_class_list) { classListCtrl = { name: 'class', type: 'listbox', label: 'Class', values: buildListItems( editor.settings.image_class_list, function(item) { if (item.value) { item.textStyle = function() { return editor.formatter.getCssText({inline: 'img', classes: [item.value]}); }; } } ) }; } // General settings shared between simple and advanced dialogs var generalFormItems = [ { name: 'src', type: 'filepicker', filetype: 'image', label: 'Source', autofocus: true, onchange: srcChange }, imageListCtrl ]; if (editor.settings.image_description !== false) { generalFormItems.push({name: 'alt', type: 'textbox', label: 'Image description'}); } if (editor.settings.image_title) { generalFormItems.push({name: 'title', type: 'textbox', label: 'Image Title'}); } if (imageDimensions) { generalFormItems.push({ type: 'container', label: 'Dimensions', layout: 'flex', direction: 'row', align: 'center', spacing: 5, items: [ {name: 'width', type: 'textbox', maxLength: 5, size: 3, onchange: recalcSize, ariaLabel: 'Width'}, {type: 'label', text: 'x'}, {name: 'height', type: 'textbox', maxLength: 5, size: 3, onchange: recalcSize, ariaLabel: 'Height'}, {name: 'constrain', type: 'checkbox', checked: true, text: 'Constrain proportions'} ] }); } generalFormItems.push(classListCtrl); // WP editor.fire( 'wpLoadImageForm', { data: generalFormItems } ); function mergeMargins(css) { if (css.margin) { var splitMargin = css.margin.split(" "); switch (splitMargin.length) { case 1: //margin: toprightbottomleft; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[0]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[0]; css['margin-left'] = css['margin-left'] || splitMargin[0]; break; case 2: //margin: topbottom rightleft; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[0]; css['margin-left'] = css['margin-left'] || splitMargin[1]; break; case 3: //margin: top rightleft bottom; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[2]; css['margin-left'] = css['margin-left'] || splitMargin[1]; break; case 4: //margin: top right bottom left; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[2]; css['margin-left'] = css['margin-left'] || splitMargin[3]; } delete css.margin; } return css; } function updateStyle() { function addPixelSuffix(value) { if (value.length > 0 && /^[0-9]+$/.test(value)) { value += 'px'; } return value; } if (!editor.settings.image_advtab) { return; } var data = win.toJSON(), css = dom.parseStyle(data.style); css = mergeMargins(css); if (data.vspace) { css['margin-top'] = css['margin-bottom'] = addPixelSuffix(data.vspace); } if (data.hspace) { css['margin-left'] = css['margin-right'] = addPixelSuffix(data.hspace); } if (data.border) { css['border-width'] = addPixelSuffix(data.border); } win.find('#style').value(dom.serializeStyle(dom.parseStyle(dom.serializeStyle(css)))); } function updateVSpaceHSpaceBorder() { if (!editor.settings.image_advtab) { return; } var data = win.toJSON(), css = dom.parseStyle(data.style); win.find('#vspace').value(""); win.find('#hspace').value(""); css = mergeMargins(css); //Move opposite equal margins to vspace/hspace field if ((css['margin-top'] && css['margin-bottom']) || (css['margin-right'] && css['margin-left'])) { if (css['margin-top'] === css['margin-bottom']) { win.find('#vspace').value(removePixelSuffix(css['margin-top'])); } else { win.find('#vspace').value(''); } if (css['margin-right'] === css['margin-left']) { win.find('#hspace').value(removePixelSuffix(css['margin-right'])); } else { win.find('#hspace').value(''); } } //Move border-width if (css['border-width']) { win.find('#border').value(removePixelSuffix(css['border-width'])); } win.find('#style').value(dom.serializeStyle(dom.parseStyle(dom.serializeStyle(css)))); } if (editor.settings.image_advtab) { // Parse styles from img if (imgElm) { if (imgElm.style.marginLeft && imgElm.style.marginRight && imgElm.style.marginLeft === imgElm.style.marginRight) { data.hspace = removePixelSuffix(imgElm.style.marginLeft); } if (imgElm.style.marginTop && imgElm.style.marginBottom && imgElm.style.marginTop === imgElm.style.marginBottom) { data.vspace = removePixelSuffix(imgElm.style.marginTop); } if (imgElm.style.borderWidth) { data.border = removePixelSuffix(imgElm.style.borderWidth); } data.style = editor.dom.serializeStyle(editor.dom.parseStyle(editor.dom.getAttrib(imgElm, 'style'))); } // Advanced dialog shows general+advanced tabs win = editor.windowManager.open({ title: 'Insert/edit image', data: data, bodyType: 'tabpanel', body: [ { title: 'General', type: 'form', items: generalFormItems }, { title: 'Advanced', type: 'form', pack: 'start', items: [ { label: 'Style', name: 'style', type: 'textbox', onchange: updateVSpaceHSpaceBorder }, { type: 'form', layout: 'grid', packV: 'start', columns: 2, padding: 0, alignH: ['left', 'right'], defaults: { type: 'textbox', maxWidth: 50, onchange: updateStyle }, items: [ {label: 'Vertical space', name: 'vspace'}, {label: 'Horizontal space', name: 'hspace'}, {label: 'Border', name: 'border'} ] } ] } ], onSubmit: onSubmitForm }); } else { // Simple default dialog win = editor.windowManager.open({ title: 'Insert/edit image', data: data, body: generalFormItems, onSubmit: onSubmitForm }); } } editor.addButton('image', { icon: 'image', tooltip: 'Insert/edit image', onclick: createImageList(showDialog), stateSelector: 'img:not([data-mce-object],[data-mce-placeholder])' }); editor.addMenuItem('image', { icon: 'image', text: 'Insert/edit image', onclick: createImageList(showDialog), context: 'insert', prependToContext: true }); editor.addCommand('mceImage', createImageList(showDialog)); });
done
identifier_name
plugin.js
/** * plugin.js * * Copyright, Moxiecode Systems AB * Released under LGPL License. * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /*global tinymce:true */ tinymce.PluginManager.add('image', function(editor) { function getImageSize(url, callback) { var img = document.createElement('img'); function done(width, height) { if (img.parentNode) { img.parentNode.removeChild(img); } callback({width: width, height: height}); } img.onload = function() { done(img.clientWidth, img.clientHeight); }; img.onerror = function() { done(); }; var style = img.style; style.visibility = 'hidden'; style.position = 'fixed'; style.bottom = style.left = 0; style.width = style.height = 'auto'; document.body.appendChild(img); img.src = url; } function buildListItems(inputList, itemCallback, startItems) { function appendItems(values, output) { output = output || []; tinymce.each(values, function(item) { var menuItem = {text: item.text || item.title}; if (item.menu) { menuItem.menu = appendItems(item.menu); } else { menuItem.value = item.value; itemCallback(menuItem); } output.push(menuItem); }); return output; } return appendItems(inputList, startItems || []); } function createImageList(callback) { return function() { var imageList = editor.settings.image_list; if (typeof imageList == "string") { tinymce.util.XHR.send({ url: imageList, success: function(text) { callback(tinymce.util.JSON.parse(text)); } }); } else if (typeof imageList == "function") { imageList(callback); } else { callback(imageList); } }; } function showDialog(imageList) { var win, data = {}, dom = editor.dom, imgElm = editor.selection.getNode(); var width, height, imageListCtrl, classListCtrl, imageDimensions = editor.settings.image_dimensions !== false; function recalcSize() { var widthCtrl, heightCtrl, newWidth, newHeight; widthCtrl = win.find('#width')[0]; heightCtrl = win.find('#height')[0]; if (!widthCtrl || !heightCtrl) { return; } newWidth = widthCtrl.value(); newHeight = heightCtrl.value(); if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) { if (width != newWidth) { newHeight = Math.round((newWidth / width) * newHeight); if (!isNaN(newHeight)) { heightCtrl.value(newHeight); } } else { newWidth = Math.round((newHeight / height) * newWidth); if (!isNaN(newWidth)) { widthCtrl.value(newWidth); } } } width = newWidth; height = newHeight; } function onSubmitForm() { function waitLoad(imgElm) { function selectImage() { imgElm.onload = imgElm.onerror = null; if (editor.selection) { editor.selection.select(imgElm); editor.nodeChanged(); } } imgElm.onload = function() { if (!data.width && !data.height && imageDimensions) { dom.setAttribs(imgElm, { width: imgElm.clientWidth, height: imgElm.clientHeight }); //WP editor.fire( 'wpNewImageRefresh', { node: imgElm } ); } selectImage(); }; imgElm.onerror = selectImage; } updateStyle(); recalcSize(); data = tinymce.extend(data, win.toJSON()); var caption = data.caption; // WP if (!data.alt) { data.alt = ''; } if (!data.title) { data.title = ''; } if (data.width === '') { data.width = null; } if (data.height === '') { data.height = null; } if (!data.style) { data.style = null; } // Setup new data excluding style properties /*eslint dot-notation: 0*/ data = { src: data.src, alt: data.alt, title: data.title, width: data.width, height: data.height, style: data.style, "class": data["class"] }; editor.undoManager.transact(function() { // WP var eventData = { node: imgElm, data: data, caption: caption }; editor.fire( 'wpImageFormSubmit', { imgData: eventData } ); if ( eventData.cancel ) { waitLoad( eventData.node ); return; } // WP end
editor.focus(); editor.nodeChanged(); } return; } if (data.title === "") { data.title = null; } if (!imgElm) { data.id = '__mcenew'; editor.focus(); editor.selection.setContent(dom.createHTML('img', data)); imgElm = dom.get('__mcenew'); dom.setAttrib(imgElm, 'id', null); } else { dom.setAttribs(imgElm, data); } waitLoad(imgElm); }); } function removePixelSuffix(value) { if (value) { value = value.replace(/px$/, ''); } return value; } function srcChange(e) { var srcURL, prependURL, absoluteURLPattern, meta = e.meta || {}; if (imageListCtrl) { imageListCtrl.value(editor.convertURL(this.value(), 'src')); } tinymce.each(meta, function(value, key) { win.find('#' + key).value(value); }); if (!meta.width && !meta.height) { srcURL = editor.convertURL(this.value(), 'src'); // Pattern test the src url and make sure we haven't already prepended the url prependURL = editor.settings.image_prepend_url; absoluteURLPattern = new RegExp('^(?:[a-z]+:)?//', 'i'); if (prependURL && !absoluteURLPattern.test(srcURL) && srcURL.substring(0, prependURL.length) !== prependURL) { srcURL = prependURL + srcURL; } this.value(srcURL); getImageSize(editor.documentBaseURI.toAbsolute(this.value()), function(data) { if (data.width && data.height && imageDimensions) { width = data.width; height = data.height; win.find('#width').value(width); win.find('#height').value(height); } }); } } width = dom.getAttrib(imgElm, 'width'); height = dom.getAttrib(imgElm, 'height'); if (imgElm.nodeName == 'IMG' && !imgElm.getAttribute('data-mce-object') && !imgElm.getAttribute('data-mce-placeholder')) { data = { src: dom.getAttrib(imgElm, 'src'), alt: dom.getAttrib(imgElm, 'alt'), title: dom.getAttrib(imgElm, 'title'), "class": dom.getAttrib(imgElm, 'class'), width: width, height: height }; // WP editor.fire( 'wpLoadImageData', { imgData: { data: data, node: imgElm } } ); } else { imgElm = null; } if (imageList) { imageListCtrl = { type: 'listbox', label: 'Image list', values: buildListItems( imageList, function(item) { item.value = editor.convertURL(item.value || item.url, 'src'); }, [{text: 'None', value: ''}] ), value: data.src && editor.convertURL(data.src, 'src'), onselect: function(e) { var altCtrl = win.find('#alt'); if (!altCtrl.value() || (e.lastControl && altCtrl.value() == e.lastControl.text())) { altCtrl.value(e.control.text()); } win.find('#src').value(e.control.value()).fire('change'); }, onPostRender: function() { imageListCtrl = this; } }; } if (editor.settings.image_class_list) { classListCtrl = { name: 'class', type: 'listbox', label: 'Class', values: buildListItems( editor.settings.image_class_list, function(item) { if (item.value) { item.textStyle = function() { return editor.formatter.getCssText({inline: 'img', classes: [item.value]}); }; } } ) }; } // General settings shared between simple and advanced dialogs var generalFormItems = [ { name: 'src', type: 'filepicker', filetype: 'image', label: 'Source', autofocus: true, onchange: srcChange }, imageListCtrl ]; if (editor.settings.image_description !== false) { generalFormItems.push({name: 'alt', type: 'textbox', label: 'Image description'}); } if (editor.settings.image_title) { generalFormItems.push({name: 'title', type: 'textbox', label: 'Image Title'}); } if (imageDimensions) { generalFormItems.push({ type: 'container', label: 'Dimensions', layout: 'flex', direction: 'row', align: 'center', spacing: 5, items: [ {name: 'width', type: 'textbox', maxLength: 5, size: 3, onchange: recalcSize, ariaLabel: 'Width'}, {type: 'label', text: 'x'}, {name: 'height', type: 'textbox', maxLength: 5, size: 3, onchange: recalcSize, ariaLabel: 'Height'}, {name: 'constrain', type: 'checkbox', checked: true, text: 'Constrain proportions'} ] }); } generalFormItems.push(classListCtrl); // WP editor.fire( 'wpLoadImageForm', { data: generalFormItems } ); function mergeMargins(css) { if (css.margin) { var splitMargin = css.margin.split(" "); switch (splitMargin.length) { case 1: //margin: toprightbottomleft; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[0]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[0]; css['margin-left'] = css['margin-left'] || splitMargin[0]; break; case 2: //margin: topbottom rightleft; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[0]; css['margin-left'] = css['margin-left'] || splitMargin[1]; break; case 3: //margin: top rightleft bottom; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[2]; css['margin-left'] = css['margin-left'] || splitMargin[1]; break; case 4: //margin: top right bottom left; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[2]; css['margin-left'] = css['margin-left'] || splitMargin[3]; } delete css.margin; } return css; } function updateStyle() { function addPixelSuffix(value) { if (value.length > 0 && /^[0-9]+$/.test(value)) { value += 'px'; } return value; } if (!editor.settings.image_advtab) { return; } var data = win.toJSON(), css = dom.parseStyle(data.style); css = mergeMargins(css); if (data.vspace) { css['margin-top'] = css['margin-bottom'] = addPixelSuffix(data.vspace); } if (data.hspace) { css['margin-left'] = css['margin-right'] = addPixelSuffix(data.hspace); } if (data.border) { css['border-width'] = addPixelSuffix(data.border); } win.find('#style').value(dom.serializeStyle(dom.parseStyle(dom.serializeStyle(css)))); } function updateVSpaceHSpaceBorder() { if (!editor.settings.image_advtab) { return; } var data = win.toJSON(), css = dom.parseStyle(data.style); win.find('#vspace').value(""); win.find('#hspace').value(""); css = mergeMargins(css); //Move opposite equal margins to vspace/hspace field if ((css['margin-top'] && css['margin-bottom']) || (css['margin-right'] && css['margin-left'])) { if (css['margin-top'] === css['margin-bottom']) { win.find('#vspace').value(removePixelSuffix(css['margin-top'])); } else { win.find('#vspace').value(''); } if (css['margin-right'] === css['margin-left']) { win.find('#hspace').value(removePixelSuffix(css['margin-right'])); } else { win.find('#hspace').value(''); } } //Move border-width if (css['border-width']) { win.find('#border').value(removePixelSuffix(css['border-width'])); } win.find('#style').value(dom.serializeStyle(dom.parseStyle(dom.serializeStyle(css)))); } if (editor.settings.image_advtab) { // Parse styles from img if (imgElm) { if (imgElm.style.marginLeft && imgElm.style.marginRight && imgElm.style.marginLeft === imgElm.style.marginRight) { data.hspace = removePixelSuffix(imgElm.style.marginLeft); } if (imgElm.style.marginTop && imgElm.style.marginBottom && imgElm.style.marginTop === imgElm.style.marginBottom) { data.vspace = removePixelSuffix(imgElm.style.marginTop); } if (imgElm.style.borderWidth) { data.border = removePixelSuffix(imgElm.style.borderWidth); } data.style = editor.dom.serializeStyle(editor.dom.parseStyle(editor.dom.getAttrib(imgElm, 'style'))); } // Advanced dialog shows general+advanced tabs win = editor.windowManager.open({ title: 'Insert/edit image', data: data, bodyType: 'tabpanel', body: [ { title: 'General', type: 'form', items: generalFormItems }, { title: 'Advanced', type: 'form', pack: 'start', items: [ { label: 'Style', name: 'style', type: 'textbox', onchange: updateVSpaceHSpaceBorder }, { type: 'form', layout: 'grid', packV: 'start', columns: 2, padding: 0, alignH: ['left', 'right'], defaults: { type: 'textbox', maxWidth: 50, onchange: updateStyle }, items: [ {label: 'Vertical space', name: 'vspace'}, {label: 'Horizontal space', name: 'hspace'}, {label: 'Border', name: 'border'} ] } ] } ], onSubmit: onSubmitForm }); } else { // Simple default dialog win = editor.windowManager.open({ title: 'Insert/edit image', data: data, body: generalFormItems, onSubmit: onSubmitForm }); } } editor.addButton('image', { icon: 'image', tooltip: 'Insert/edit image', onclick: createImageList(showDialog), stateSelector: 'img:not([data-mce-object],[data-mce-placeholder])' }); editor.addMenuItem('image', { icon: 'image', text: 'Insert/edit image', onclick: createImageList(showDialog), context: 'insert', prependToContext: true }); editor.addCommand('mceImage', createImageList(showDialog)); });
if (!data.src) { if (imgElm) { dom.remove(imgElm);
random_line_split
plugin.js
/** * plugin.js * * Copyright, Moxiecode Systems AB * Released under LGPL License. * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /*global tinymce:true */ tinymce.PluginManager.add('image', function(editor) { function getImageSize(url, callback) { var img = document.createElement('img'); function done(width, height) { if (img.parentNode) { img.parentNode.removeChild(img); } callback({width: width, height: height}); } img.onload = function() { done(img.clientWidth, img.clientHeight); }; img.onerror = function() { done(); }; var style = img.style; style.visibility = 'hidden'; style.position = 'fixed'; style.bottom = style.left = 0; style.width = style.height = 'auto'; document.body.appendChild(img); img.src = url; } function buildListItems(inputList, itemCallback, startItems) { function appendItems(values, output) { output = output || []; tinymce.each(values, function(item) { var menuItem = {text: item.text || item.title}; if (item.menu) { menuItem.menu = appendItems(item.menu); } else { menuItem.value = item.value; itemCallback(menuItem); } output.push(menuItem); }); return output; } return appendItems(inputList, startItems || []); } function createImageList(callback) { return function() { var imageList = editor.settings.image_list; if (typeof imageList == "string") { tinymce.util.XHR.send({ url: imageList, success: function(text) { callback(tinymce.util.JSON.parse(text)); } }); } else if (typeof imageList == "function") { imageList(callback); } else { callback(imageList); } }; } function showDialog(imageList) { var win, data = {}, dom = editor.dom, imgElm = editor.selection.getNode(); var width, height, imageListCtrl, classListCtrl, imageDimensions = editor.settings.image_dimensions !== false; function recalcSize() { var widthCtrl, heightCtrl, newWidth, newHeight; widthCtrl = win.find('#width')[0]; heightCtrl = win.find('#height')[0]; if (!widthCtrl || !heightCtrl) { return; } newWidth = widthCtrl.value(); newHeight = heightCtrl.value(); if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) { if (width != newWidth) { newHeight = Math.round((newWidth / width) * newHeight); if (!isNaN(newHeight)) { heightCtrl.value(newHeight); } } else { newWidth = Math.round((newHeight / height) * newWidth); if (!isNaN(newWidth)) { widthCtrl.value(newWidth); } } } width = newWidth; height = newHeight; } function onSubmitForm() { function waitLoad(imgElm) { function selectImage() { imgElm.onload = imgElm.onerror = null; if (editor.selection) { editor.selection.select(imgElm); editor.nodeChanged(); } } imgElm.onload = function() { if (!data.width && !data.height && imageDimensions) { dom.setAttribs(imgElm, { width: imgElm.clientWidth, height: imgElm.clientHeight }); //WP editor.fire( 'wpNewImageRefresh', { node: imgElm } ); } selectImage(); }; imgElm.onerror = selectImage; } updateStyle(); recalcSize(); data = tinymce.extend(data, win.toJSON()); var caption = data.caption; // WP if (!data.alt) { data.alt = ''; } if (!data.title) { data.title = ''; } if (data.width === '') { data.width = null; } if (data.height === '') { data.height = null; } if (!data.style) { data.style = null; } // Setup new data excluding style properties /*eslint dot-notation: 0*/ data = { src: data.src, alt: data.alt, title: data.title, width: data.width, height: data.height, style: data.style, "class": data["class"] }; editor.undoManager.transact(function() { // WP var eventData = { node: imgElm, data: data, caption: caption }; editor.fire( 'wpImageFormSubmit', { imgData: eventData } ); if ( eventData.cancel ) { waitLoad( eventData.node ); return; } // WP end if (!data.src) { if (imgElm) { dom.remove(imgElm); editor.focus(); editor.nodeChanged(); } return; } if (data.title === "") { data.title = null; } if (!imgElm) { data.id = '__mcenew'; editor.focus(); editor.selection.setContent(dom.createHTML('img', data)); imgElm = dom.get('__mcenew'); dom.setAttrib(imgElm, 'id', null); } else { dom.setAttribs(imgElm, data); } waitLoad(imgElm); }); } function removePixelSuffix(value) { if (value) { value = value.replace(/px$/, ''); } return value; } function srcChange(e) { var srcURL, prependURL, absoluteURLPattern, meta = e.meta || {}; if (imageListCtrl) { imageListCtrl.value(editor.convertURL(this.value(), 'src')); } tinymce.each(meta, function(value, key) { win.find('#' + key).value(value); }); if (!meta.width && !meta.height) { srcURL = editor.convertURL(this.value(), 'src'); // Pattern test the src url and make sure we haven't already prepended the url prependURL = editor.settings.image_prepend_url; absoluteURLPattern = new RegExp('^(?:[a-z]+:)?//', 'i'); if (prependURL && !absoluteURLPattern.test(srcURL) && srcURL.substring(0, prependURL.length) !== prependURL) { srcURL = prependURL + srcURL; } this.value(srcURL); getImageSize(editor.documentBaseURI.toAbsolute(this.value()), function(data) { if (data.width && data.height && imageDimensions) { width = data.width; height = data.height; win.find('#width').value(width); win.find('#height').value(height); } }); } } width = dom.getAttrib(imgElm, 'width'); height = dom.getAttrib(imgElm, 'height'); if (imgElm.nodeName == 'IMG' && !imgElm.getAttribute('data-mce-object') && !imgElm.getAttribute('data-mce-placeholder')) { data = { src: dom.getAttrib(imgElm, 'src'), alt: dom.getAttrib(imgElm, 'alt'), title: dom.getAttrib(imgElm, 'title'), "class": dom.getAttrib(imgElm, 'class'), width: width, height: height }; // WP editor.fire( 'wpLoadImageData', { imgData: { data: data, node: imgElm } } ); } else { imgElm = null; } if (imageList) { imageListCtrl = { type: 'listbox', label: 'Image list', values: buildListItems( imageList, function(item) { item.value = editor.convertURL(item.value || item.url, 'src'); }, [{text: 'None', value: ''}] ), value: data.src && editor.convertURL(data.src, 'src'), onselect: function(e) { var altCtrl = win.find('#alt'); if (!altCtrl.value() || (e.lastControl && altCtrl.value() == e.lastControl.text())) { altCtrl.value(e.control.text()); } win.find('#src').value(e.control.value()).fire('change'); }, onPostRender: function() { imageListCtrl = this; } }; } if (editor.settings.image_class_list) { classListCtrl = { name: 'class', type: 'listbox', label: 'Class', values: buildListItems( editor.settings.image_class_list, function(item) { if (item.value) { item.textStyle = function() { return editor.formatter.getCssText({inline: 'img', classes: [item.value]}); }; } } ) }; } // General settings shared between simple and advanced dialogs var generalFormItems = [ { name: 'src', type: 'filepicker', filetype: 'image', label: 'Source', autofocus: true, onchange: srcChange }, imageListCtrl ]; if (editor.settings.image_description !== false) { generalFormItems.push({name: 'alt', type: 'textbox', label: 'Image description'}); } if (editor.settings.image_title) { generalFormItems.push({name: 'title', type: 'textbox', label: 'Image Title'}); } if (imageDimensions) { generalFormItems.push({ type: 'container', label: 'Dimensions', layout: 'flex', direction: 'row', align: 'center', spacing: 5, items: [ {name: 'width', type: 'textbox', maxLength: 5, size: 3, onchange: recalcSize, ariaLabel: 'Width'}, {type: 'label', text: 'x'}, {name: 'height', type: 'textbox', maxLength: 5, size: 3, onchange: recalcSize, ariaLabel: 'Height'}, {name: 'constrain', type: 'checkbox', checked: true, text: 'Constrain proportions'} ] }); } generalFormItems.push(classListCtrl); // WP editor.fire( 'wpLoadImageForm', { data: generalFormItems } ); function mergeMargins(css) { if (css.margin) { var splitMargin = css.margin.split(" "); switch (splitMargin.length) { case 1: //margin: toprightbottomleft; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[0]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[0]; css['margin-left'] = css['margin-left'] || splitMargin[0]; break; case 2: //margin: topbottom rightleft; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[0]; css['margin-left'] = css['margin-left'] || splitMargin[1]; break; case 3: //margin: top rightleft bottom; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[2]; css['margin-left'] = css['margin-left'] || splitMargin[1]; break; case 4: //margin: top right bottom left; css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[2]; css['margin-left'] = css['margin-left'] || splitMargin[3]; } delete css.margin; } return css; } function updateStyle() { function addPixelSuffix(value) { if (value.length > 0 && /^[0-9]+$/.test(value)) { value += 'px'; } return value; } if (!editor.settings.image_advtab) { return; } var data = win.toJSON(), css = dom.parseStyle(data.style); css = mergeMargins(css); if (data.vspace) { css['margin-top'] = css['margin-bottom'] = addPixelSuffix(data.vspace); } if (data.hspace) { css['margin-left'] = css['margin-right'] = addPixelSuffix(data.hspace); } if (data.border)
win.find('#style').value(dom.serializeStyle(dom.parseStyle(dom.serializeStyle(css)))); } function updateVSpaceHSpaceBorder() { if (!editor.settings.image_advtab) { return; } var data = win.toJSON(), css = dom.parseStyle(data.style); win.find('#vspace').value(""); win.find('#hspace').value(""); css = mergeMargins(css); //Move opposite equal margins to vspace/hspace field if ((css['margin-top'] && css['margin-bottom']) || (css['margin-right'] && css['margin-left'])) { if (css['margin-top'] === css['margin-bottom']) { win.find('#vspace').value(removePixelSuffix(css['margin-top'])); } else { win.find('#vspace').value(''); } if (css['margin-right'] === css['margin-left']) { win.find('#hspace').value(removePixelSuffix(css['margin-right'])); } else { win.find('#hspace').value(''); } } //Move border-width if (css['border-width']) { win.find('#border').value(removePixelSuffix(css['border-width'])); } win.find('#style').value(dom.serializeStyle(dom.parseStyle(dom.serializeStyle(css)))); } if (editor.settings.image_advtab) { // Parse styles from img if (imgElm) { if (imgElm.style.marginLeft && imgElm.style.marginRight && imgElm.style.marginLeft === imgElm.style.marginRight) { data.hspace = removePixelSuffix(imgElm.style.marginLeft); } if (imgElm.style.marginTop && imgElm.style.marginBottom && imgElm.style.marginTop === imgElm.style.marginBottom) { data.vspace = removePixelSuffix(imgElm.style.marginTop); } if (imgElm.style.borderWidth) { data.border = removePixelSuffix(imgElm.style.borderWidth); } data.style = editor.dom.serializeStyle(editor.dom.parseStyle(editor.dom.getAttrib(imgElm, 'style'))); } // Advanced dialog shows general+advanced tabs win = editor.windowManager.open({ title: 'Insert/edit image', data: data, bodyType: 'tabpanel', body: [ { title: 'General', type: 'form', items: generalFormItems }, { title: 'Advanced', type: 'form', pack: 'start', items: [ { label: 'Style', name: 'style', type: 'textbox', onchange: updateVSpaceHSpaceBorder }, { type: 'form', layout: 'grid', packV: 'start', columns: 2, padding: 0, alignH: ['left', 'right'], defaults: { type: 'textbox', maxWidth: 50, onchange: updateStyle }, items: [ {label: 'Vertical space', name: 'vspace'}, {label: 'Horizontal space', name: 'hspace'}, {label: 'Border', name: 'border'} ] } ] } ], onSubmit: onSubmitForm }); } else { // Simple default dialog win = editor.windowManager.open({ title: 'Insert/edit image', data: data, body: generalFormItems, onSubmit: onSubmitForm }); } } editor.addButton('image', { icon: 'image', tooltip: 'Insert/edit image', onclick: createImageList(showDialog), stateSelector: 'img:not([data-mce-object],[data-mce-placeholder])' }); editor.addMenuItem('image', { icon: 'image', text: 'Insert/edit image', onclick: createImageList(showDialog), context: 'insert', prependToContext: true }); editor.addCommand('mceImage', createImageList(showDialog)); });
{ css['border-width'] = addPixelSuffix(data.border); }
conditional_block
transform.py
"""Helper functions for transforming results.""" import hashlib import logging import os import re import urllib.parse from typing import Optional from docutils.core import publish_parts from dump2polarion.exporters.verdicts import Verdicts # pylint: disable=invalid-name logger = logging.getLogger(__name__) TEST_PARAM_RE = re.compile(r"\[.*\]") def only_passed_and_wait(result): """Return PASS and WAIT results only, skips everything else.""" verdict = result.get("verdict", "").strip().lower() if verdict in Verdicts.PASS + Verdicts.WAIT: return result return None def insert_source_info(result): """Add info about source of test result if available.""" comment = result.get("comment") # don't change comment if it already exists if comment: return source = result.get("source") job_name = result.get("job_name") run = result.get("run") source_list = [source, job_name, run] if not all(source_list): return source_note = "/".join(source_list) source_note = "Source: {}".format(source_note) result["comment"] = source_note def setup_parametrization(result, parametrize): """Modify result's data according to the parametrization settings.""" if parametrize: # remove parameters from title title = result.get("title") if title: result["title"] = TEST_PARAM_RE.sub("", title) # remove parameters also from id if it's identical to title if title and result.get("id") == title: result["id"] = result["title"] else: # don't parametrize if not specifically configured if "params" in result: del result["params"] def
(result): """Make sure that test class is included in "title". Applies only to titles derived from test function names, e.g. "test_power_parent_service" -> "TestServiceRESTAPI.test_power_parent_service" >>> result = {"title": "test_foo", "id": "test_foo", "classname": "foo.bar.baz.TestFoo", ... "file": "foo/bar/baz.py"} >>> include_class_in_title(result) >>> str(result.get("title")) 'TestFoo.test_foo' >>> str(result.get("id")) 'TestFoo.test_foo' >>> result.get("classname") >>> result = {"title": "some title", "id": "test_foo", "classname": "foo.bar.baz.TestFoo", ... "file": "foo/bar/baz.py"} >>> include_class_in_title(result) >>> str(result.get("title")) 'some title' >>> str(result.get("id")) 'test_foo' """ classname = result.get("classname", "") if not classname: return filepath = result.get("file", "") title = result.get("title") if title and title.startswith("test_") and "/" in filepath and "." in classname: fname = filepath.split("/")[-1].replace(".py", "") last_classname = classname.split(".")[-1] # last part of classname is not file name if fname != last_classname and last_classname not in title: result["title"] = "{}.{}".format(last_classname, title) # update also the id if it is identical to original title if result.get("id") == title: result["id"] = result["title"] # we don't need to pass classnames? del result["classname"] def gen_unique_id(string): """Generate unique id out of a string. >>> gen_unique_id("vmaas_TestClass.test_name") '5acc5dc795a620c6b4491b681e5da39c' """ return hashlib.sha1(string.encode("utf-8")).hexdigest()[:32] def get_testcase_id(testcase, append_str): """Return new test case ID. >>> get_testcase_id({"title": "TestClass.test_name"}, "vmaas_") '5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "TestClass.test_name", "id": "TestClass.test_name"}, "vmaas_") '5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "TestClass.test_name", "id": "test_name"}, "vmaas_") '5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "some title", "id": "TestClass.test_name"}, "vmaas_") '2ea7695b73763331f8a0c4aec75362b8' >>> str(get_testcase_id({"title": "some title", "id": "some_id"}, "vmaas_")) 'some_id' """ testcase_title = testcase.get("title") testcase_id = testcase.get("id") if not testcase_id or testcase_id.lower().startswith("test"): testcase_id = gen_unique_id("{}{}".format(append_str, testcase_title)) return testcase_id def parse_rst_description(testcase): """Create an HTML version of the RST formatted description.""" description = testcase.get("description") if not description: return try: with open(os.devnull, "w") as devnull: testcase["description"] = publish_parts( description, writer_name="html", settings_overrides={"report_level": 2, "halt_level": 2, "warning_stream": devnull}, )["html_body"] # pylint: disable=broad-except except Exception as exp: testcase_id = testcase.get("nodeid") or testcase.get("id") or testcase.get("title") logger.error("%s: description: %s", str(exp), testcase_id) def preformat_plain_description(testcase): """Create a preformatted HTML version of the description.""" description = testcase.get("description") if not description: return # naive approach to removing indent from pytest docstrings nodeid = testcase.get("nodeid") or "" indent = None if "::Test" in nodeid: indent = 8 * " " elif "::test_" in nodeid: indent = 4 * " " if indent: orig_lines = description.split("\n") new_lines = [] for line in orig_lines: if line.startswith(indent): line = line.replace(indent, "", 1) new_lines.append(line) description = "\n".join(new_lines) testcase["description"] = "<pre>\n{}\n</pre>".format(description) def add_unique_runid(testcase, run_id=None): """Add run id to the test description. The `run_id` runs makes the descriptions unique between imports and force Polarion to update every testcase every time. """ testcase["description"] = '{visible}<br id="{invisible}"/>'.format( visible=testcase.get("description") or "empty-description-placeholder", invisible=run_id or id(add_unique_runid), ) def get_full_repo_address(repo_address: Optional[str]): """Make sure the repo address is complete path in repository. >>> get_full_repo_address("https://gitlab.com/somerepo") 'https://gitlab.com/somerepo/blob/master/' >>> get_full_repo_address("https://github.com/otherrepo/blob/branch/") 'https://github.com/otherrepo/blob/branch/' >>> get_full_repo_address(None) """ if not repo_address: return None if "/blob/" not in repo_address: # the master here should probably link the latest "commit" eventually repo_address = "{}/blob/master".format(repo_address) # make sure the / is present at the end of address repo_address = "{}/".format(repo_address.rstrip("/ ")) return repo_address def fill_automation_repo(repo_address: Optional[str], testcase: dict) -> dict: """Fill repo address to "automation_script" if missing.""" automation_script = testcase.get("automation_script") if not automation_script: return testcase if not repo_address: del testcase["automation_script"] return testcase if automation_script.startswith("http"): return testcase testcase["automation_script"] = urllib.parse.urljoin(repo_address, automation_script) return testcase def add_automation_link(testcase): """Append link to automation script to the test description.""" automation_script = testcase.get("automation_script") if not automation_script: return testcase automation_link = '<a href="{}">Test Source</a>'.format(automation_script) testcase["description"] = "{}<br/>{}".format(testcase.get("description") or "", automation_link) return testcase
include_class_in_title
identifier_name
transform.py
"""Helper functions for transforming results.""" import hashlib import logging import os import re import urllib.parse from typing import Optional from docutils.core import publish_parts from dump2polarion.exporters.verdicts import Verdicts # pylint: disable=invalid-name logger = logging.getLogger(__name__) TEST_PARAM_RE = re.compile(r"\[.*\]") def only_passed_and_wait(result): """Return PASS and WAIT results only, skips everything else.""" verdict = result.get("verdict", "").strip().lower() if verdict in Verdicts.PASS + Verdicts.WAIT: return result return None def insert_source_info(result): """Add info about source of test result if available.""" comment = result.get("comment") # don't change comment if it already exists if comment: return source = result.get("source") job_name = result.get("job_name") run = result.get("run") source_list = [source, job_name, run] if not all(source_list): return source_note = "/".join(source_list) source_note = "Source: {}".format(source_note) result["comment"] = source_note def setup_parametrization(result, parametrize): """Modify result's data according to the parametrization settings.""" if parametrize: # remove parameters from title title = result.get("title") if title: result["title"] = TEST_PARAM_RE.sub("", title) # remove parameters also from id if it's identical to title if title and result.get("id") == title: result["id"] = result["title"] else: # don't parametrize if not specifically configured if "params" in result: del result["params"] def include_class_in_title(result): """Make sure that test class is included in "title". Applies only to titles derived from test function names, e.g. "test_power_parent_service" -> "TestServiceRESTAPI.test_power_parent_service" >>> result = {"title": "test_foo", "id": "test_foo", "classname": "foo.bar.baz.TestFoo", ... "file": "foo/bar/baz.py"} >>> include_class_in_title(result) >>> str(result.get("title")) 'TestFoo.test_foo' >>> str(result.get("id")) 'TestFoo.test_foo' >>> result.get("classname") >>> result = {"title": "some title", "id": "test_foo", "classname": "foo.bar.baz.TestFoo", ... "file": "foo/bar/baz.py"} >>> include_class_in_title(result) >>> str(result.get("title")) 'some title' >>> str(result.get("id")) 'test_foo' """ classname = result.get("classname", "") if not classname: return filepath = result.get("file", "") title = result.get("title") if title and title.startswith("test_") and "/" in filepath and "." in classname: fname = filepath.split("/")[-1].replace(".py", "") last_classname = classname.split(".")[-1] # last part of classname is not file name if fname != last_classname and last_classname not in title: result["title"] = "{}.{}".format(last_classname, title) # update also the id if it is identical to original title if result.get("id") == title: result["id"] = result["title"] # we don't need to pass classnames? del result["classname"] def gen_unique_id(string): """Generate unique id out of a string. >>> gen_unique_id("vmaas_TestClass.test_name") '5acc5dc795a620c6b4491b681e5da39c' """ return hashlib.sha1(string.encode("utf-8")).hexdigest()[:32] def get_testcase_id(testcase, append_str): """Return new test case ID. >>> get_testcase_id({"title": "TestClass.test_name"}, "vmaas_") '5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "TestClass.test_name", "id": "TestClass.test_name"}, "vmaas_") '5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "TestClass.test_name", "id": "test_name"}, "vmaas_") '5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "some title", "id": "TestClass.test_name"}, "vmaas_") '2ea7695b73763331f8a0c4aec75362b8' >>> str(get_testcase_id({"title": "some title", "id": "some_id"}, "vmaas_")) 'some_id' """ testcase_title = testcase.get("title") testcase_id = testcase.get("id") if not testcase_id or testcase_id.lower().startswith("test"): testcase_id = gen_unique_id("{}{}".format(append_str, testcase_title)) return testcase_id def parse_rst_description(testcase): """Create an HTML version of the RST formatted description.""" description = testcase.get("description") if not description: return try: with open(os.devnull, "w") as devnull: testcase["description"] = publish_parts( description, writer_name="html", settings_overrides={"report_level": 2, "halt_level": 2, "warning_stream": devnull}, )["html_body"] # pylint: disable=broad-except except Exception as exp: testcase_id = testcase.get("nodeid") or testcase.get("id") or testcase.get("title") logger.error("%s: description: %s", str(exp), testcase_id) def preformat_plain_description(testcase): """Create a preformatted HTML version of the description.""" description = testcase.get("description") if not description: return # naive approach to removing indent from pytest docstrings nodeid = testcase.get("nodeid") or "" indent = None if "::Test" in nodeid: indent = 8 * " " elif "::test_" in nodeid: indent = 4 * " " if indent: orig_lines = description.split("\n") new_lines = [] for line in orig_lines: if line.startswith(indent): line = line.replace(indent, "", 1) new_lines.append(line) description = "\n".join(new_lines) testcase["description"] = "<pre>\n{}\n</pre>".format(description) def add_unique_runid(testcase, run_id=None): """Add run id to the test description. The `run_id` runs makes the descriptions unique between imports and force Polarion to update every testcase every time. """ testcase["description"] = '{visible}<br id="{invisible}"/>'.format( visible=testcase.get("description") or "empty-description-placeholder", invisible=run_id or id(add_unique_runid), ) def get_full_repo_address(repo_address: Optional[str]): """Make sure the repo address is complete path in repository. >>> get_full_repo_address("https://gitlab.com/somerepo") 'https://gitlab.com/somerepo/blob/master/' >>> get_full_repo_address("https://github.com/otherrepo/blob/branch/") 'https://github.com/otherrepo/blob/branch/' >>> get_full_repo_address(None) """ if not repo_address: return None if "/blob/" not in repo_address: # the master here should probably link the latest "commit" eventually repo_address = "{}/blob/master".format(repo_address) # make sure the / is present at the end of address repo_address = "{}/".format(repo_address.rstrip("/ ")) return repo_address def fill_automation_repo(repo_address: Optional[str], testcase: dict) -> dict: """Fill repo address to "automation_script" if missing.""" automation_script = testcase.get("automation_script") if not automation_script: return testcase if not repo_address: del testcase["automation_script"] return testcase if automation_script.startswith("http"): return testcase testcase["automation_script"] = urllib.parse.urljoin(repo_address, automation_script) return testcase def add_automation_link(testcase): """Append link to automation script to the test description.""" automation_script = testcase.get("automation_script") if not automation_script:
automation_link = '<a href="{}">Test Source</a>'.format(automation_script) testcase["description"] = "{}<br/>{}".format(testcase.get("description") or "", automation_link) return testcase
return testcase
conditional_block
transform.py
"""Helper functions for transforming results.""" import hashlib import logging import os import re import urllib.parse from typing import Optional from docutils.core import publish_parts from dump2polarion.exporters.verdicts import Verdicts # pylint: disable=invalid-name logger = logging.getLogger(__name__) TEST_PARAM_RE = re.compile(r"\[.*\]") def only_passed_and_wait(result): """Return PASS and WAIT results only, skips everything else.""" verdict = result.get("verdict", "").strip().lower() if verdict in Verdicts.PASS + Verdicts.WAIT: return result return None def insert_source_info(result): """Add info about source of test result if available.""" comment = result.get("comment") # don't change comment if it already exists if comment: return source = result.get("source") job_name = result.get("job_name") run = result.get("run") source_list = [source, job_name, run] if not all(source_list): return source_note = "/".join(source_list) source_note = "Source: {}".format(source_note) result["comment"] = source_note def setup_parametrization(result, parametrize): """Modify result's data according to the parametrization settings.""" if parametrize: # remove parameters from title title = result.get("title") if title: result["title"] = TEST_PARAM_RE.sub("", title) # remove parameters also from id if it's identical to title if title and result.get("id") == title: result["id"] = result["title"] else: # don't parametrize if not specifically configured if "params" in result: del result["params"] def include_class_in_title(result): """Make sure that test class is included in "title". Applies only to titles derived from test function names, e.g. "test_power_parent_service" -> "TestServiceRESTAPI.test_power_parent_service" >>> result = {"title": "test_foo", "id": "test_foo", "classname": "foo.bar.baz.TestFoo", ... "file": "foo/bar/baz.py"} >>> include_class_in_title(result) >>> str(result.get("title")) 'TestFoo.test_foo' >>> str(result.get("id")) 'TestFoo.test_foo' >>> result.get("classname") >>> result = {"title": "some title", "id": "test_foo", "classname": "foo.bar.baz.TestFoo", ... "file": "foo/bar/baz.py"} >>> include_class_in_title(result) >>> str(result.get("title")) 'some title' >>> str(result.get("id")) 'test_foo' """ classname = result.get("classname", "") if not classname: return filepath = result.get("file", "") title = result.get("title") if title and title.startswith("test_") and "/" in filepath and "." in classname: fname = filepath.split("/")[-1].replace(".py", "") last_classname = classname.split(".")[-1] # last part of classname is not file name if fname != last_classname and last_classname not in title: result["title"] = "{}.{}".format(last_classname, title) # update also the id if it is identical to original title if result.get("id") == title: result["id"] = result["title"] # we don't need to pass classnames? del result["classname"] def gen_unique_id(string): """Generate unique id out of a string. >>> gen_unique_id("vmaas_TestClass.test_name") '5acc5dc795a620c6b4491b681e5da39c' """ return hashlib.sha1(string.encode("utf-8")).hexdigest()[:32] def get_testcase_id(testcase, append_str): """Return new test case ID. >>> get_testcase_id({"title": "TestClass.test_name"}, "vmaas_") '5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "TestClass.test_name", "id": "TestClass.test_name"}, "vmaas_") '5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "TestClass.test_name", "id": "test_name"}, "vmaas_")
'some_id' """ testcase_title = testcase.get("title") testcase_id = testcase.get("id") if not testcase_id or testcase_id.lower().startswith("test"): testcase_id = gen_unique_id("{}{}".format(append_str, testcase_title)) return testcase_id def parse_rst_description(testcase): """Create an HTML version of the RST formatted description.""" description = testcase.get("description") if not description: return try: with open(os.devnull, "w") as devnull: testcase["description"] = publish_parts( description, writer_name="html", settings_overrides={"report_level": 2, "halt_level": 2, "warning_stream": devnull}, )["html_body"] # pylint: disable=broad-except except Exception as exp: testcase_id = testcase.get("nodeid") or testcase.get("id") or testcase.get("title") logger.error("%s: description: %s", str(exp), testcase_id) def preformat_plain_description(testcase): """Create a preformatted HTML version of the description.""" description = testcase.get("description") if not description: return # naive approach to removing indent from pytest docstrings nodeid = testcase.get("nodeid") or "" indent = None if "::Test" in nodeid: indent = 8 * " " elif "::test_" in nodeid: indent = 4 * " " if indent: orig_lines = description.split("\n") new_lines = [] for line in orig_lines: if line.startswith(indent): line = line.replace(indent, "", 1) new_lines.append(line) description = "\n".join(new_lines) testcase["description"] = "<pre>\n{}\n</pre>".format(description) def add_unique_runid(testcase, run_id=None): """Add run id to the test description. The `run_id` runs makes the descriptions unique between imports and force Polarion to update every testcase every time. """ testcase["description"] = '{visible}<br id="{invisible}"/>'.format( visible=testcase.get("description") or "empty-description-placeholder", invisible=run_id or id(add_unique_runid), ) def get_full_repo_address(repo_address: Optional[str]): """Make sure the repo address is complete path in repository. >>> get_full_repo_address("https://gitlab.com/somerepo") 'https://gitlab.com/somerepo/blob/master/' >>> get_full_repo_address("https://github.com/otherrepo/blob/branch/") 'https://github.com/otherrepo/blob/branch/' >>> get_full_repo_address(None) """ if not repo_address: return None if "/blob/" not in repo_address: # the master here should probably link the latest "commit" eventually repo_address = "{}/blob/master".format(repo_address) # make sure the / is present at the end of address repo_address = "{}/".format(repo_address.rstrip("/ ")) return repo_address def fill_automation_repo(repo_address: Optional[str], testcase: dict) -> dict: """Fill repo address to "automation_script" if missing.""" automation_script = testcase.get("automation_script") if not automation_script: return testcase if not repo_address: del testcase["automation_script"] return testcase if automation_script.startswith("http"): return testcase testcase["automation_script"] = urllib.parse.urljoin(repo_address, automation_script) return testcase def add_automation_link(testcase): """Append link to automation script to the test description.""" automation_script = testcase.get("automation_script") if not automation_script: return testcase automation_link = '<a href="{}">Test Source</a>'.format(automation_script) testcase["description"] = "{}<br/>{}".format(testcase.get("description") or "", automation_link) return testcase
'5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "some title", "id": "TestClass.test_name"}, "vmaas_") '2ea7695b73763331f8a0c4aec75362b8' >>> str(get_testcase_id({"title": "some title", "id": "some_id"}, "vmaas_"))
random_line_split
transform.py
"""Helper functions for transforming results.""" import hashlib import logging import os import re import urllib.parse from typing import Optional from docutils.core import publish_parts from dump2polarion.exporters.verdicts import Verdicts # pylint: disable=invalid-name logger = logging.getLogger(__name__) TEST_PARAM_RE = re.compile(r"\[.*\]") def only_passed_and_wait(result): """Return PASS and WAIT results only, skips everything else.""" verdict = result.get("verdict", "").strip().lower() if verdict in Verdicts.PASS + Verdicts.WAIT: return result return None def insert_source_info(result): """Add info about source of test result if available.""" comment = result.get("comment") # don't change comment if it already exists if comment: return source = result.get("source") job_name = result.get("job_name") run = result.get("run") source_list = [source, job_name, run] if not all(source_list): return source_note = "/".join(source_list) source_note = "Source: {}".format(source_note) result["comment"] = source_note def setup_parametrization(result, parametrize): """Modify result's data according to the parametrization settings.""" if parametrize: # remove parameters from title title = result.get("title") if title: result["title"] = TEST_PARAM_RE.sub("", title) # remove parameters also from id if it's identical to title if title and result.get("id") == title: result["id"] = result["title"] else: # don't parametrize if not specifically configured if "params" in result: del result["params"] def include_class_in_title(result): """Make sure that test class is included in "title". Applies only to titles derived from test function names, e.g. "test_power_parent_service" -> "TestServiceRESTAPI.test_power_parent_service" >>> result = {"title": "test_foo", "id": "test_foo", "classname": "foo.bar.baz.TestFoo", ... "file": "foo/bar/baz.py"} >>> include_class_in_title(result) >>> str(result.get("title")) 'TestFoo.test_foo' >>> str(result.get("id")) 'TestFoo.test_foo' >>> result.get("classname") >>> result = {"title": "some title", "id": "test_foo", "classname": "foo.bar.baz.TestFoo", ... "file": "foo/bar/baz.py"} >>> include_class_in_title(result) >>> str(result.get("title")) 'some title' >>> str(result.get("id")) 'test_foo' """ classname = result.get("classname", "") if not classname: return filepath = result.get("file", "") title = result.get("title") if title and title.startswith("test_") and "/" in filepath and "." in classname: fname = filepath.split("/")[-1].replace(".py", "") last_classname = classname.split(".")[-1] # last part of classname is not file name if fname != last_classname and last_classname not in title: result["title"] = "{}.{}".format(last_classname, title) # update also the id if it is identical to original title if result.get("id") == title: result["id"] = result["title"] # we don't need to pass classnames? del result["classname"] def gen_unique_id(string): """Generate unique id out of a string. >>> gen_unique_id("vmaas_TestClass.test_name") '5acc5dc795a620c6b4491b681e5da39c' """ return hashlib.sha1(string.encode("utf-8")).hexdigest()[:32] def get_testcase_id(testcase, append_str):
def parse_rst_description(testcase): """Create an HTML version of the RST formatted description.""" description = testcase.get("description") if not description: return try: with open(os.devnull, "w") as devnull: testcase["description"] = publish_parts( description, writer_name="html", settings_overrides={"report_level": 2, "halt_level": 2, "warning_stream": devnull}, )["html_body"] # pylint: disable=broad-except except Exception as exp: testcase_id = testcase.get("nodeid") or testcase.get("id") or testcase.get("title") logger.error("%s: description: %s", str(exp), testcase_id) def preformat_plain_description(testcase): """Create a preformatted HTML version of the description.""" description = testcase.get("description") if not description: return # naive approach to removing indent from pytest docstrings nodeid = testcase.get("nodeid") or "" indent = None if "::Test" in nodeid: indent = 8 * " " elif "::test_" in nodeid: indent = 4 * " " if indent: orig_lines = description.split("\n") new_lines = [] for line in orig_lines: if line.startswith(indent): line = line.replace(indent, "", 1) new_lines.append(line) description = "\n".join(new_lines) testcase["description"] = "<pre>\n{}\n</pre>".format(description) def add_unique_runid(testcase, run_id=None): """Add run id to the test description. The `run_id` runs makes the descriptions unique between imports and force Polarion to update every testcase every time. """ testcase["description"] = '{visible}<br id="{invisible}"/>'.format( visible=testcase.get("description") or "empty-description-placeholder", invisible=run_id or id(add_unique_runid), ) def get_full_repo_address(repo_address: Optional[str]): """Make sure the repo address is complete path in repository. >>> get_full_repo_address("https://gitlab.com/somerepo") 'https://gitlab.com/somerepo/blob/master/' >>> get_full_repo_address("https://github.com/otherrepo/blob/branch/") 'https://github.com/otherrepo/blob/branch/' >>> get_full_repo_address(None) """ if not repo_address: return None if "/blob/" not in repo_address: # the master here should probably link the latest "commit" eventually repo_address = "{}/blob/master".format(repo_address) # make sure the / is present at the end of address repo_address = "{}/".format(repo_address.rstrip("/ ")) return repo_address def fill_automation_repo(repo_address: Optional[str], testcase: dict) -> dict: """Fill repo address to "automation_script" if missing.""" automation_script = testcase.get("automation_script") if not automation_script: return testcase if not repo_address: del testcase["automation_script"] return testcase if automation_script.startswith("http"): return testcase testcase["automation_script"] = urllib.parse.urljoin(repo_address, automation_script) return testcase def add_automation_link(testcase): """Append link to automation script to the test description.""" automation_script = testcase.get("automation_script") if not automation_script: return testcase automation_link = '<a href="{}">Test Source</a>'.format(automation_script) testcase["description"] = "{}<br/>{}".format(testcase.get("description") or "", automation_link) return testcase
"""Return new test case ID. >>> get_testcase_id({"title": "TestClass.test_name"}, "vmaas_") '5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "TestClass.test_name", "id": "TestClass.test_name"}, "vmaas_") '5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "TestClass.test_name", "id": "test_name"}, "vmaas_") '5acc5dc795a620c6b4491b681e5da39c' >>> get_testcase_id({"title": "some title", "id": "TestClass.test_name"}, "vmaas_") '2ea7695b73763331f8a0c4aec75362b8' >>> str(get_testcase_id({"title": "some title", "id": "some_id"}, "vmaas_")) 'some_id' """ testcase_title = testcase.get("title") testcase_id = testcase.get("id") if not testcase_id or testcase_id.lower().startswith("test"): testcase_id = gen_unique_id("{}{}".format(append_str, testcase_title)) return testcase_id
identifier_body
assign-to-method.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct
{ meows : usize, how_hungry : isize, } impl cat { pub fn speak(&self) { self.meows += 1_usize; } } fn cat(in_x : usize, in_y : isize) -> cat { cat { meows: in_x, how_hungry: in_y } } fn main() { let nyan : cat = cat(52_usize, 99); nyan.speak = || println!("meow"); //~ ERROR attempted to take value of method }
cat
identifier_name
assign-to-method.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
meows : usize, how_hungry : isize, } impl cat { pub fn speak(&self) { self.meows += 1_usize; } } fn cat(in_x : usize, in_y : isize) -> cat { cat { meows: in_x, how_hungry: in_y } } fn main() { let nyan : cat = cat(52_usize, 99); nyan.speak = || println!("meow"); //~ ERROR attempted to take value of method }
struct cat {
random_line_split
assign-to-method.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct cat { meows : usize, how_hungry : isize, } impl cat { pub fn speak(&self) { self.meows += 1_usize; } } fn cat(in_x : usize, in_y : isize) -> cat { cat { meows: in_x, how_hungry: in_y } } fn main()
{ let nyan : cat = cat(52_usize, 99); nyan.speak = || println!("meow"); //~ ERROR attempted to take value of method }
identifier_body
tdbus_upower.py
# -*- coding: utf-8 -*- ''' This module presents a little code to deal with battery status using DBUS and UPower on Linux @author: pkremer ''' import sys import logging from six.moves import filter from functools import partial import six import tdbus # 'constants' UPOWER_NAME = 'org.freedesktop.UPower' UPOWER_DEVICE_IFACE = 'org.freedesktop.UPower.Device' UPOWER_PATH = '/org/freedesktop/UPower' UPOWER_IFACE = 'org.freedesktop.UPower' DBUS_PROP_NAME = 'org.freedesktop.DBus.Properties' log = logging.getLogger(__name__) def convert_DBUS_to_python(val): ''' quick hack to convert DBUS types to python types ''' if isinstance(val, (str, six.text_type,)): return str(val) elif isinstance(val, (int,)): return int(val) elif isinstance(val, (dict,)): return convert_DBUSDictionary_to_dict(val) elif isinstance(val, (list,)): return convert_DBUSArray_to_tuple(val) elif isinstance(val, (tuple,)): return val[1] elif isinstance(val, (float,)): return float(val) else: raise TypeError("Unknown type '%s': '%r'!" % (str(type(val)), repr(val))) def convert_DBUSArray_to_tuple(dbusarray): return ((convert_DBUS_to_python(val) for val in dbusarray),) def convert_DBUSDictionary_to_dict(dbusdict): return {convert_DBUS_to_python(k): convert_DBUS_to_python(dbusdict[k]) for k in dbusdict} def uPowerEnumerateDevices(conn): # list all UPower devices: for device in conn.call_method(UPOWER_PATH, member='EnumerateDevices', interface=UPOWER_IFACE, destination=UPOWER_NAME).get_args()[0]: yield device def uPowerDeviceGetAll(conn, device): ''' Utility method that uses the given DBUS connection to call the UPower.GetAll method on the UPower device specified and returns pure python data. :param conn: DBUS connection :param device: the device ''' log.debug("uPowerDeviceGetAll %s", device) return convert_DBUS_to_python(conn.call_method(device, member='GetAll', interface=DBUS_PROP_NAME, destination=UPOWER_NAME, format='s', args=(UPOWER_DEVICE_IFACE,) ).get_args()[0]) def uPowerDeviceGet(conn, device, attribute): log.debug("uPowerDeviceGet %s.%s", device, attribute) return convert_DBUS_to_python( conn.call_method(device, member='Get', interface=DBUS_PROP_NAME, destination=UPOWER_NAME, format='ss', args=(UPOWER_DEVICE_IFACE, attribute) ).get_args()[0] ) class UPowerDeviceHandler(tdbus.DBusHandler): def __init__(self, connect, devices): ''' A DBUS signal handler class for the org.freedesktop.UPower.Device 'Changed' event. To re-read the device data, a DBUS connection is required. This is established when an event is fired using the provided connect method. Essentially, this is a cluttered workaround for a bizarre object design and use of decorators in the tdbus library. :param connect: a DBUS system bus connection factory :param devices: the devices to watch ''' self.connect = connect self.device_paths = devices log.debug('Installing signal handler for devices: %r', devices) self._observers = {} super(UPowerDeviceHandler, self).__init__() def register_observer(self, observer, devices=None): """ register a listener function Parameters ----------- observer : external listener function events : tuple or list of relevant events (default=None) """ if devices is not None and type(devices) not in (tuple, list): devices = (devices,) if observer in self._observers: log.warning("Observer '%r' already registered, overwriting for " "devices %r", observer, devices) self._observers[observer] = devices def notify_observers(self, device=None, attributes=None): """notify observers """ log.debug("%s %r", device, attributes) for observer, devices in list(self._observers.items()): #log.debug("trying to notify the observer")
@tdbus.signal_handler(member='Changed', interface=UPOWER_DEVICE_IFACE) def Changed(self, message): device = message.get_path() if device in self.device_paths: log.debug('signal received: %s, args = %r', message.get_member(), message.get_args()) conn = self.connect() self.notify_observers(device, uPowerDeviceGetAll(conn, device)) conn.close() def connect_dbus_system(): ''' Factory for DBUS system bus connections ''' return tdbus.SimpleDBusConnection(tdbus.DBUS_BUS_SYSTEM) def upower_present(connect): conn = connect() result = conn.call_method(tdbus.DBUS_PATH_DBUS, 'ListNames', tdbus.DBUS_INTERFACE_DBUS, destination=tdbus.DBUS_SERVICE_DBUS) conn.close() # see if UPower is in the known services: return UPOWER_NAME in (name for name in result.get_args()[0] if not name.startswith(':')) def ibatteries(conn): ''' Utility that returns an generator for rechargeable power devices. :param conn: DBUS system bus connection ''' def is_rechargeable(conn, device): log.debug("testing IsRechargeable for '%s'", device) return uPowerDeviceGet(conn, device, 'IsRechargeable') return filter(partial(is_rechargeable, conn), uPowerEnumerateDevices(conn)) def main(): logging.basicConfig(level=logging.DEBUG) if not upower_present(connect_dbus_system): raise EnvironmentError("DBUS connection to UPower impossible") conn = connect_dbus_system() conn.add_handler(UPowerDeviceHandler(connect_dbus_system, set(ibatteries(conn)))) conn.subscribe_to_signals() # basic select() loop, i.e. we assume there is no event loop conn.dispatch() if __name__ == '__main__': sys.exit(main())
if devices is None or device is None or device in devices: try: observer(self, device, attributes) except (Exception,) as ex: # pylint: disable=W0703 self.unregister_observer(observer) errmsg = "Exception in message dispatch: Handler '{0}'" + \ " unregistered for device '{1}' ".format( observer.__class__.__name__, device) log.error(errmsg, exc_info=ex)
conditional_block
tdbus_upower.py
# -*- coding: utf-8 -*- ''' This module presents a little code to deal with battery status using DBUS and UPower on Linux @author: pkremer ''' import sys import logging from six.moves import filter from functools import partial import six import tdbus # 'constants' UPOWER_NAME = 'org.freedesktop.UPower' UPOWER_DEVICE_IFACE = 'org.freedesktop.UPower.Device' UPOWER_PATH = '/org/freedesktop/UPower' UPOWER_IFACE = 'org.freedesktop.UPower' DBUS_PROP_NAME = 'org.freedesktop.DBus.Properties' log = logging.getLogger(__name__) def convert_DBUS_to_python(val): ''' quick hack to convert DBUS types to python types ''' if isinstance(val, (str, six.text_type,)): return str(val) elif isinstance(val, (int,)): return int(val) elif isinstance(val, (dict,)): return convert_DBUSDictionary_to_dict(val) elif isinstance(val, (list,)): return convert_DBUSArray_to_tuple(val) elif isinstance(val, (tuple,)): return val[1] elif isinstance(val, (float,)): return float(val) else: raise TypeError("Unknown type '%s': '%r'!" % (str(type(val)), repr(val))) def convert_DBUSArray_to_tuple(dbusarray): return ((convert_DBUS_to_python(val) for val in dbusarray),) def convert_DBUSDictionary_to_dict(dbusdict): return {convert_DBUS_to_python(k): convert_DBUS_to_python(dbusdict[k]) for k in dbusdict} def uPowerEnumerateDevices(conn): # list all UPower devices: for device in conn.call_method(UPOWER_PATH, member='EnumerateDevices', interface=UPOWER_IFACE, destination=UPOWER_NAME).get_args()[0]: yield device def uPowerDeviceGetAll(conn, device): ''' Utility method that uses the given DBUS connection to call the UPower.GetAll method on the UPower device specified and returns pure python data. :param conn: DBUS connection :param device: the device ''' log.debug("uPowerDeviceGetAll %s", device) return convert_DBUS_to_python(conn.call_method(device, member='GetAll', interface=DBUS_PROP_NAME, destination=UPOWER_NAME, format='s', args=(UPOWER_DEVICE_IFACE,) ).get_args()[0]) def uPowerDeviceGet(conn, device, attribute): log.debug("uPowerDeviceGet %s.%s", device, attribute) return convert_DBUS_to_python( conn.call_method(device, member='Get', interface=DBUS_PROP_NAME, destination=UPOWER_NAME, format='ss', args=(UPOWER_DEVICE_IFACE, attribute) ).get_args()[0] ) class UPowerDeviceHandler(tdbus.DBusHandler): def __init__(self, connect, devices): ''' A DBUS signal handler class for the org.freedesktop.UPower.Device 'Changed' event. To re-read the device data, a DBUS connection is required. This is established when an event is fired using the provided connect method. Essentially, this is a cluttered workaround for a bizarre object design and use of decorators in the tdbus library. :param connect: a DBUS system bus connection factory :param devices: the devices to watch ''' self.connect = connect self.device_paths = devices log.debug('Installing signal handler for devices: %r', devices) self._observers = {} super(UPowerDeviceHandler, self).__init__() def
(self, observer, devices=None): """ register a listener function Parameters ----------- observer : external listener function events : tuple or list of relevant events (default=None) """ if devices is not None and type(devices) not in (tuple, list): devices = (devices,) if observer in self._observers: log.warning("Observer '%r' already registered, overwriting for " "devices %r", observer, devices) self._observers[observer] = devices def notify_observers(self, device=None, attributes=None): """notify observers """ log.debug("%s %r", device, attributes) for observer, devices in list(self._observers.items()): #log.debug("trying to notify the observer") if devices is None or device is None or device in devices: try: observer(self, device, attributes) except (Exception,) as ex: # pylint: disable=W0703 self.unregister_observer(observer) errmsg = "Exception in message dispatch: Handler '{0}'" + \ " unregistered for device '{1}' ".format( observer.__class__.__name__, device) log.error(errmsg, exc_info=ex) @tdbus.signal_handler(member='Changed', interface=UPOWER_DEVICE_IFACE) def Changed(self, message): device = message.get_path() if device in self.device_paths: log.debug('signal received: %s, args = %r', message.get_member(), message.get_args()) conn = self.connect() self.notify_observers(device, uPowerDeviceGetAll(conn, device)) conn.close() def connect_dbus_system(): ''' Factory for DBUS system bus connections ''' return tdbus.SimpleDBusConnection(tdbus.DBUS_BUS_SYSTEM) def upower_present(connect): conn = connect() result = conn.call_method(tdbus.DBUS_PATH_DBUS, 'ListNames', tdbus.DBUS_INTERFACE_DBUS, destination=tdbus.DBUS_SERVICE_DBUS) conn.close() # see if UPower is in the known services: return UPOWER_NAME in (name for name in result.get_args()[0] if not name.startswith(':')) def ibatteries(conn): ''' Utility that returns an generator for rechargeable power devices. :param conn: DBUS system bus connection ''' def is_rechargeable(conn, device): log.debug("testing IsRechargeable for '%s'", device) return uPowerDeviceGet(conn, device, 'IsRechargeable') return filter(partial(is_rechargeable, conn), uPowerEnumerateDevices(conn)) def main(): logging.basicConfig(level=logging.DEBUG) if not upower_present(connect_dbus_system): raise EnvironmentError("DBUS connection to UPower impossible") conn = connect_dbus_system() conn.add_handler(UPowerDeviceHandler(connect_dbus_system, set(ibatteries(conn)))) conn.subscribe_to_signals() # basic select() loop, i.e. we assume there is no event loop conn.dispatch() if __name__ == '__main__': sys.exit(main())
register_observer
identifier_name
tdbus_upower.py
# -*- coding: utf-8 -*- ''' This module presents a little code to deal with battery status using DBUS and UPower on Linux @author: pkremer ''' import sys import logging from six.moves import filter from functools import partial import six import tdbus # 'constants' UPOWER_NAME = 'org.freedesktop.UPower' UPOWER_DEVICE_IFACE = 'org.freedesktop.UPower.Device' UPOWER_PATH = '/org/freedesktop/UPower' UPOWER_IFACE = 'org.freedesktop.UPower' DBUS_PROP_NAME = 'org.freedesktop.DBus.Properties' log = logging.getLogger(__name__) def convert_DBUS_to_python(val): ''' quick hack to convert DBUS types to python types ''' if isinstance(val, (str, six.text_type,)): return str(val) elif isinstance(val, (int,)): return int(val) elif isinstance(val, (dict,)): return convert_DBUSDictionary_to_dict(val) elif isinstance(val, (list,)): return convert_DBUSArray_to_tuple(val) elif isinstance(val, (tuple,)): return val[1] elif isinstance(val, (float,)): return float(val) else: raise TypeError("Unknown type '%s': '%r'!" % (str(type(val)), repr(val))) def convert_DBUSArray_to_tuple(dbusarray): return ((convert_DBUS_to_python(val) for val in dbusarray),) def convert_DBUSDictionary_to_dict(dbusdict): return {convert_DBUS_to_python(k): convert_DBUS_to_python(dbusdict[k]) for k in dbusdict} def uPowerEnumerateDevices(conn): # list all UPower devices: for device in conn.call_method(UPOWER_PATH, member='EnumerateDevices', interface=UPOWER_IFACE, destination=UPOWER_NAME).get_args()[0]: yield device def uPowerDeviceGetAll(conn, device): ''' Utility method that uses the given DBUS connection to call the UPower.GetAll method on the UPower device specified and returns pure python data. :param conn: DBUS connection :param device: the device ''' log.debug("uPowerDeviceGetAll %s", device) return convert_DBUS_to_python(conn.call_method(device, member='GetAll', interface=DBUS_PROP_NAME, destination=UPOWER_NAME, format='s', args=(UPOWER_DEVICE_IFACE,) ).get_args()[0]) def uPowerDeviceGet(conn, device, attribute): log.debug("uPowerDeviceGet %s.%s", device, attribute) return convert_DBUS_to_python( conn.call_method(device, member='Get', interface=DBUS_PROP_NAME, destination=UPOWER_NAME, format='ss', args=(UPOWER_DEVICE_IFACE, attribute) ).get_args()[0] ) class UPowerDeviceHandler(tdbus.DBusHandler): def __init__(self, connect, devices): ''' A DBUS signal handler class for the org.freedesktop.UPower.Device 'Changed' event. To re-read the device data, a DBUS connection is required. This is established when an event is fired using the provided connect method. Essentially, this is a cluttered workaround for a bizarre object design and use of decorators in the tdbus library. :param connect: a DBUS system bus connection factory :param devices: the devices to watch ''' self.connect = connect self.device_paths = devices log.debug('Installing signal handler for devices: %r', devices) self._observers = {} super(UPowerDeviceHandler, self).__init__() def register_observer(self, observer, devices=None): """ register a listener function Parameters ----------- observer : external listener function events : tuple or list of relevant events (default=None) """ if devices is not None and type(devices) not in (tuple, list): devices = (devices,) if observer in self._observers: log.warning("Observer '%r' already registered, overwriting for " "devices %r", observer, devices) self._observers[observer] = devices def notify_observers(self, device=None, attributes=None): """notify observers """ log.debug("%s %r", device, attributes) for observer, devices in list(self._observers.items()): #log.debug("trying to notify the observer") if devices is None or device is None or device in devices: try: observer(self, device, attributes) except (Exception,) as ex: # pylint: disable=W0703 self.unregister_observer(observer) errmsg = "Exception in message dispatch: Handler '{0}'" + \ " unregistered for device '{1}' ".format( observer.__class__.__name__, device) log.error(errmsg, exc_info=ex) @tdbus.signal_handler(member='Changed', interface=UPOWER_DEVICE_IFACE) def Changed(self, message): device = message.get_path() if device in self.device_paths: log.debug('signal received: %s, args = %r', message.get_member(), message.get_args()) conn = self.connect() self.notify_observers(device, uPowerDeviceGetAll(conn, device)) conn.close() def connect_dbus_system(): ''' Factory for DBUS system bus connections ''' return tdbus.SimpleDBusConnection(tdbus.DBUS_BUS_SYSTEM) def upower_present(connect):
def ibatteries(conn): ''' Utility that returns an generator for rechargeable power devices. :param conn: DBUS system bus connection ''' def is_rechargeable(conn, device): log.debug("testing IsRechargeable for '%s'", device) return uPowerDeviceGet(conn, device, 'IsRechargeable') return filter(partial(is_rechargeable, conn), uPowerEnumerateDevices(conn)) def main(): logging.basicConfig(level=logging.DEBUG) if not upower_present(connect_dbus_system): raise EnvironmentError("DBUS connection to UPower impossible") conn = connect_dbus_system() conn.add_handler(UPowerDeviceHandler(connect_dbus_system, set(ibatteries(conn)))) conn.subscribe_to_signals() # basic select() loop, i.e. we assume there is no event loop conn.dispatch() if __name__ == '__main__': sys.exit(main())
conn = connect() result = conn.call_method(tdbus.DBUS_PATH_DBUS, 'ListNames', tdbus.DBUS_INTERFACE_DBUS, destination=tdbus.DBUS_SERVICE_DBUS) conn.close() # see if UPower is in the known services: return UPOWER_NAME in (name for name in result.get_args()[0] if not name.startswith(':'))
identifier_body
tdbus_upower.py
# -*- coding: utf-8 -*- ''' This module presents a little code to deal with battery status using DBUS and UPower on Linux @author: pkremer ''' import sys import logging from six.moves import filter from functools import partial import six import tdbus # 'constants' UPOWER_NAME = 'org.freedesktop.UPower' UPOWER_DEVICE_IFACE = 'org.freedesktop.UPower.Device' UPOWER_PATH = '/org/freedesktop/UPower' UPOWER_IFACE = 'org.freedesktop.UPower' DBUS_PROP_NAME = 'org.freedesktop.DBus.Properties' log = logging.getLogger(__name__) def convert_DBUS_to_python(val): ''' quick hack to convert DBUS types to python types ''' if isinstance(val, (str, six.text_type,)): return str(val) elif isinstance(val, (int,)): return int(val) elif isinstance(val, (dict,)): return convert_DBUSDictionary_to_dict(val) elif isinstance(val, (list,)): return convert_DBUSArray_to_tuple(val) elif isinstance(val, (tuple,)): return val[1] elif isinstance(val, (float,)): return float(val) else: raise TypeError("Unknown type '%s': '%r'!" % (str(type(val)), repr(val))) def convert_DBUSArray_to_tuple(dbusarray): return ((convert_DBUS_to_python(val) for val in dbusarray),) def convert_DBUSDictionary_to_dict(dbusdict): return {convert_DBUS_to_python(k): convert_DBUS_to_python(dbusdict[k]) for k in dbusdict} def uPowerEnumerateDevices(conn): # list all UPower devices: for device in conn.call_method(UPOWER_PATH, member='EnumerateDevices', interface=UPOWER_IFACE, destination=UPOWER_NAME).get_args()[0]: yield device def uPowerDeviceGetAll(conn, device): ''' Utility method that uses the given DBUS connection to call the UPower.GetAll method on the UPower device specified and returns pure python data. :param conn: DBUS connection :param device: the device ''' log.debug("uPowerDeviceGetAll %s", device) return convert_DBUS_to_python(conn.call_method(device, member='GetAll', interface=DBUS_PROP_NAME, destination=UPOWER_NAME, format='s', args=(UPOWER_DEVICE_IFACE,) ).get_args()[0]) def uPowerDeviceGet(conn, device, attribute): log.debug("uPowerDeviceGet %s.%s", device, attribute) return convert_DBUS_to_python( conn.call_method(device, member='Get', interface=DBUS_PROP_NAME, destination=UPOWER_NAME, format='ss', args=(UPOWER_DEVICE_IFACE, attribute) ).get_args()[0] ) class UPowerDeviceHandler(tdbus.DBusHandler): def __init__(self, connect, devices): ''' A DBUS signal handler class for the org.freedesktop.UPower.Device 'Changed' event. To re-read the device data, a DBUS connection is required. This is established when an event is fired using the provided connect method. Essentially, this is a cluttered workaround for a bizarre object design and use of decorators in the tdbus library. :param connect: a DBUS system bus connection factory :param devices: the devices to watch ''' self.connect = connect self.device_paths = devices log.debug('Installing signal handler for devices: %r', devices) self._observers = {} super(UPowerDeviceHandler, self).__init__() def register_observer(self, observer, devices=None): """ register a listener function Parameters ----------- observer : external listener function events : tuple or list of relevant events (default=None) """ if devices is not None and type(devices) not in (tuple, list): devices = (devices,) if observer in self._observers: log.warning("Observer '%r' already registered, overwriting for " "devices %r", observer, devices) self._observers[observer] = devices def notify_observers(self, device=None, attributes=None): """notify observers """ log.debug("%s %r", device, attributes) for observer, devices in list(self._observers.items()): #log.debug("trying to notify the observer") if devices is None or device is None or device in devices: try: observer(self, device, attributes) except (Exception,) as ex: # pylint: disable=W0703 self.unregister_observer(observer) errmsg = "Exception in message dispatch: Handler '{0}'" + \ " unregistered for device '{1}' ".format( observer.__class__.__name__, device) log.error(errmsg, exc_info=ex) @tdbus.signal_handler(member='Changed', interface=UPOWER_DEVICE_IFACE) def Changed(self, message): device = message.get_path() if device in self.device_paths: log.debug('signal received: %s, args = %r', message.get_member(), message.get_args()) conn = self.connect() self.notify_observers(device, uPowerDeviceGetAll(conn, device)) conn.close() def connect_dbus_system(): ''' Factory for DBUS system bus connections ''' return tdbus.SimpleDBusConnection(tdbus.DBUS_BUS_SYSTEM) def upower_present(connect): conn = connect() result = conn.call_method(tdbus.DBUS_PATH_DBUS, 'ListNames',
destination=tdbus.DBUS_SERVICE_DBUS) conn.close() # see if UPower is in the known services: return UPOWER_NAME in (name for name in result.get_args()[0] if not name.startswith(':')) def ibatteries(conn): ''' Utility that returns an generator for rechargeable power devices. :param conn: DBUS system bus connection ''' def is_rechargeable(conn, device): log.debug("testing IsRechargeable for '%s'", device) return uPowerDeviceGet(conn, device, 'IsRechargeable') return filter(partial(is_rechargeable, conn), uPowerEnumerateDevices(conn)) def main(): logging.basicConfig(level=logging.DEBUG) if not upower_present(connect_dbus_system): raise EnvironmentError("DBUS connection to UPower impossible") conn = connect_dbus_system() conn.add_handler(UPowerDeviceHandler(connect_dbus_system, set(ibatteries(conn)))) conn.subscribe_to_signals() # basic select() loop, i.e. we assume there is no event loop conn.dispatch() if __name__ == '__main__': sys.exit(main())
tdbus.DBUS_INTERFACE_DBUS,
random_line_split
acc_lib.py
# -*- coding: utf-8 -*- """ Acc Lib - Used by account contasis pre account line pre Created: 11 oct 2020 Last up: 29 mar 2021 """ import datetime class AccFuncs: @staticmethod def static_method(): # the static method gets passed nothing return "I am a static method" @classmethod def class_method(cls): # the class method gets passed the class (in this case ModCLass) return "I am a class method" def instance_method(self): # An instance method gets passed the instance of ModClass return "I am an instance method" #------------------------------------------------ Correct Time ----------------- # Used by Account Line # Correct Time # Format: 1876-10-10 00:00:00 @classmethod def correct_time(cls, date, delta): if date != False: year = int(date.split('-')[0]) if year >= 1900: DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" DATETIME_FORMAT_sp = "%d/%m/%Y %H:%M" date_field1 = datetime.datetime.strptime(date, DATETIME_FORMAT) date_corr = date_field1 + datetime.timedelta(hours=delta,minutes=0) date_corr_sp = date_corr.strftime(DATETIME_FORMAT_sp) return date_corr, date_corr_sp # correct_time # ----------------------------------------------------- Get Orders Filter ------ # Provides sales between begin date and end date. # Sales and Cancelled also. @classmethod def get_orders_filter(cls, obj, date_bx, date_ex): # Dates #DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" DATETIME_FORMAT = "%Y-%m-%d" date_begin = date_bx + ' 05:00:00'
# Search Orders orders = obj.env['sale.order'].search([ ('state', 'in', ['sale', 'cancel']), ('date_order', '>=', date_begin), ('date_order', '<', date_end), ], order='x_serial_nr asc', #limit=1, ) # Count count = obj.env['sale.order'].search_count([ ('state', 'in', ['sale', 'cancel']), ('date_order', '>=', date_begin), ('date_order', '<', date_end), ], #order='x_serial_nr asc', #limit=1, ) return orders, count # get_orders_filter # ------------------------------------------------------ Get Net and Tax ------- # Get Net and Tax @classmethod def get_net_tax(cls, amount): # Net x = amount / 1.18 net = float("{0:.2f}".format(x)) # Tax x = amount * 0.18 tax = float("{0:.2f}".format(x)) return net, tax # get_net_tax
date_end_dt = datetime.datetime.strptime(date_ex, DATETIME_FORMAT) + datetime.timedelta(hours=24) + datetime.timedelta(hours=5, minutes=0) date_end = date_end_dt.strftime('%Y-%m-%d %H:%M') #print date_end_dt
random_line_split
acc_lib.py
# -*- coding: utf-8 -*- """ Acc Lib - Used by account contasis pre account line pre Created: 11 oct 2020 Last up: 29 mar 2021 """ import datetime class AccFuncs: @staticmethod def static_method(): # the static method gets passed nothing return "I am a static method" @classmethod def class_method(cls): # the class method gets passed the class (in this case ModCLass) return "I am a class method" def instance_method(self): # An instance method gets passed the instance of ModClass return "I am an instance method" #------------------------------------------------ Correct Time ----------------- # Used by Account Line # Correct Time # Format: 1876-10-10 00:00:00 @classmethod def correct_time(cls, date, delta): if date != False: year = int(date.split('-')[0]) if year >= 1900: DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" DATETIME_FORMAT_sp = "%d/%m/%Y %H:%M" date_field1 = datetime.datetime.strptime(date, DATETIME_FORMAT) date_corr = date_field1 + datetime.timedelta(hours=delta,minutes=0) date_corr_sp = date_corr.strftime(DATETIME_FORMAT_sp) return date_corr, date_corr_sp # correct_time # ----------------------------------------------------- Get Orders Filter ------ # Provides sales between begin date and end date. # Sales and Cancelled also. @classmethod def get_orders_filter(cls, obj, date_bx, date_ex): # Dates #DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" DATETIME_FORMAT = "%Y-%m-%d" date_begin = date_bx + ' 05:00:00' date_end_dt = datetime.datetime.strptime(date_ex, DATETIME_FORMAT) + datetime.timedelta(hours=24) + datetime.timedelta(hours=5, minutes=0) date_end = date_end_dt.strftime('%Y-%m-%d %H:%M') #print date_end_dt # Search Orders orders = obj.env['sale.order'].search([ ('state', 'in', ['sale', 'cancel']), ('date_order', '>=', date_begin), ('date_order', '<', date_end), ], order='x_serial_nr asc', #limit=1, ) # Count count = obj.env['sale.order'].search_count([ ('state', 'in', ['sale', 'cancel']), ('date_order', '>=', date_begin), ('date_order', '<', date_end), ], #order='x_serial_nr asc', #limit=1, ) return orders, count # get_orders_filter # ------------------------------------------------------ Get Net and Tax ------- # Get Net and Tax @classmethod def get_net_tax(cls, amount): # Net
# get_net_tax
x = amount / 1.18 net = float("{0:.2f}".format(x)) # Tax x = amount * 0.18 tax = float("{0:.2f}".format(x)) return net, tax
identifier_body
acc_lib.py
# -*- coding: utf-8 -*- """ Acc Lib - Used by account contasis pre account line pre Created: 11 oct 2020 Last up: 29 mar 2021 """ import datetime class AccFuncs: @staticmethod def static_method(): # the static method gets passed nothing return "I am a static method" @classmethod def class_method(cls): # the class method gets passed the class (in this case ModCLass) return "I am a class method" def instance_method(self): # An instance method gets passed the instance of ModClass return "I am an instance method" #------------------------------------------------ Correct Time ----------------- # Used by Account Line # Correct Time # Format: 1876-10-10 00:00:00 @classmethod def
(cls, date, delta): if date != False: year = int(date.split('-')[0]) if year >= 1900: DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" DATETIME_FORMAT_sp = "%d/%m/%Y %H:%M" date_field1 = datetime.datetime.strptime(date, DATETIME_FORMAT) date_corr = date_field1 + datetime.timedelta(hours=delta,minutes=0) date_corr_sp = date_corr.strftime(DATETIME_FORMAT_sp) return date_corr, date_corr_sp # correct_time # ----------------------------------------------------- Get Orders Filter ------ # Provides sales between begin date and end date. # Sales and Cancelled also. @classmethod def get_orders_filter(cls, obj, date_bx, date_ex): # Dates #DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" DATETIME_FORMAT = "%Y-%m-%d" date_begin = date_bx + ' 05:00:00' date_end_dt = datetime.datetime.strptime(date_ex, DATETIME_FORMAT) + datetime.timedelta(hours=24) + datetime.timedelta(hours=5, minutes=0) date_end = date_end_dt.strftime('%Y-%m-%d %H:%M') #print date_end_dt # Search Orders orders = obj.env['sale.order'].search([ ('state', 'in', ['sale', 'cancel']), ('date_order', '>=', date_begin), ('date_order', '<', date_end), ], order='x_serial_nr asc', #limit=1, ) # Count count = obj.env['sale.order'].search_count([ ('state', 'in', ['sale', 'cancel']), ('date_order', '>=', date_begin), ('date_order', '<', date_end), ], #order='x_serial_nr asc', #limit=1, ) return orders, count # get_orders_filter # ------------------------------------------------------ Get Net and Tax ------- # Get Net and Tax @classmethod def get_net_tax(cls, amount): # Net x = amount / 1.18 net = float("{0:.2f}".format(x)) # Tax x = amount * 0.18 tax = float("{0:.2f}".format(x)) return net, tax # get_net_tax
correct_time
identifier_name
acc_lib.py
# -*- coding: utf-8 -*- """ Acc Lib - Used by account contasis pre account line pre Created: 11 oct 2020 Last up: 29 mar 2021 """ import datetime class AccFuncs: @staticmethod def static_method(): # the static method gets passed nothing return "I am a static method" @classmethod def class_method(cls): # the class method gets passed the class (in this case ModCLass) return "I am a class method" def instance_method(self): # An instance method gets passed the instance of ModClass return "I am an instance method" #------------------------------------------------ Correct Time ----------------- # Used by Account Line # Correct Time # Format: 1876-10-10 00:00:00 @classmethod def correct_time(cls, date, delta): if date != False:
# correct_time # ----------------------------------------------------- Get Orders Filter ------ # Provides sales between begin date and end date. # Sales and Cancelled also. @classmethod def get_orders_filter(cls, obj, date_bx, date_ex): # Dates #DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" DATETIME_FORMAT = "%Y-%m-%d" date_begin = date_bx + ' 05:00:00' date_end_dt = datetime.datetime.strptime(date_ex, DATETIME_FORMAT) + datetime.timedelta(hours=24) + datetime.timedelta(hours=5, minutes=0) date_end = date_end_dt.strftime('%Y-%m-%d %H:%M') #print date_end_dt # Search Orders orders = obj.env['sale.order'].search([ ('state', 'in', ['sale', 'cancel']), ('date_order', '>=', date_begin), ('date_order', '<', date_end), ], order='x_serial_nr asc', #limit=1, ) # Count count = obj.env['sale.order'].search_count([ ('state', 'in', ['sale', 'cancel']), ('date_order', '>=', date_begin), ('date_order', '<', date_end), ], #order='x_serial_nr asc', #limit=1, ) return orders, count # get_orders_filter # ------------------------------------------------------ Get Net and Tax ------- # Get Net and Tax @classmethod def get_net_tax(cls, amount): # Net x = amount / 1.18 net = float("{0:.2f}".format(x)) # Tax x = amount * 0.18 tax = float("{0:.2f}".format(x)) return net, tax # get_net_tax
year = int(date.split('-')[0]) if year >= 1900: DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" DATETIME_FORMAT_sp = "%d/%m/%Y %H:%M" date_field1 = datetime.datetime.strptime(date, DATETIME_FORMAT) date_corr = date_field1 + datetime.timedelta(hours=delta,minutes=0) date_corr_sp = date_corr.strftime(DATETIME_FORMAT_sp) return date_corr, date_corr_sp
conditional_block
PIXISpriteScreen.tsx
import './BeforePIXI'; import { Asset } from 'expo-asset'; import { Platform } from 'expo-modules-core'; import * as PIXI from 'pixi.js'; import { Dimensions } from 'react-native'; import GLWrap from './GLWrap'; export default GLWrap('pixi.js sprite rendering', async (gl) => { const { scale: resolution } = Dimensions.get('window'); const width = gl.drawingBufferWidth / resolution; const height = gl.drawingBufferHeight / resolution; const app = new PIXI.Application({ context: gl, width, height, resolution, backgroundColor: 0xffffff, }); app.ticker.add(() => gl.endFrameEXP()); const asset = Asset.fromModule(require('../../../assets/images/nikki.png')); await asset.downloadAsync(); let image; if (Platform.OS === 'web') { image = new Image(); image.src = asset.localUri!; } else
const sprite = PIXI.Sprite.from(image); app.stage.addChild(sprite); });
{ image = new Image(asset as any); }
conditional_block
PIXISpriteScreen.tsx
import './BeforePIXI'; import { Asset } from 'expo-asset'; import { Platform } from 'expo-modules-core'; import * as PIXI from 'pixi.js'; import { Dimensions } from 'react-native';
export default GLWrap('pixi.js sprite rendering', async (gl) => { const { scale: resolution } = Dimensions.get('window'); const width = gl.drawingBufferWidth / resolution; const height = gl.drawingBufferHeight / resolution; const app = new PIXI.Application({ context: gl, width, height, resolution, backgroundColor: 0xffffff, }); app.ticker.add(() => gl.endFrameEXP()); const asset = Asset.fromModule(require('../../../assets/images/nikki.png')); await asset.downloadAsync(); let image; if (Platform.OS === 'web') { image = new Image(); image.src = asset.localUri!; } else { image = new Image(asset as any); } const sprite = PIXI.Sprite.from(image); app.stage.addChild(sprite); });
import GLWrap from './GLWrap';
random_line_split
scan_threshold.py
import logging from pybar.analysis.analyze_raw_data import AnalyzeRawData from pybar.fei4.register_utils import invert_pixel_mask from pybar.fei4_run_base import Fei4RunBase from pybar.fei4.register_utils import scan_loop from pybar.run_manager import RunManager class ThresholdScan(Fei4RunBase): '''Standard Threshold Scan Implementation of a standard threshold scan. ''' _default_run_conf = { "broadcast_commands": True, "threaded_scan": True, "mask_steps": 3, # mask steps, be carefull PlsrDAC injects different charge for different mask steps "n_injections": 100, # number of injections per PlsrDAC step "scan_parameters": [('PlsrDAC', [None, 100])], # the PlsrDAC range "step_size": 1, # step size of the PlsrDAC during scan "use_enable_mask": False, # if True, use Enable mask during scan, if False, all pixels will be enabled "enable_shift_masks": ["Enable", "C_High", "C_Low"], # enable masks shifted during scan "disable_shift_masks": [], # disable masks shifted during scan "pulser_dac_correction": False # PlsrDAC correction for each double column } def configure(self): commands = [] commands.extend(self.register.get_commands("ConfMode")) # C_Low if "C_Low".lower() in map(lambda x: x.lower(), self.enable_shift_masks): self.register.set_pixel_register_value('C_Low', 1) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_Low')) else: self.register.set_pixel_register_value('C_Low', 0) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_Low')) # C_High if "C_High".lower() in map(lambda x: x.lower(), self.enable_shift_masks): self.register.set_pixel_register_value('C_High', 1) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_High')) else:
commands.extend(self.register.get_commands("RunMode")) self.register_utils.send_commands(commands) def scan(self): scan_parameter_range = [0, (2 ** self.register.global_registers['PlsrDAC']['bitlength'])] if self.scan_parameters.PlsrDAC[0]: scan_parameter_range[0] = self.scan_parameters.PlsrDAC[0] if self.scan_parameters.PlsrDAC[1]: scan_parameter_range[1] = self.scan_parameters.PlsrDAC[1] scan_parameter_range = range(scan_parameter_range[0], scan_parameter_range[1] + 1, self.step_size) logging.info("Scanning %s from %d to %d", 'PlsrDAC', scan_parameter_range[0], scan_parameter_range[-1]) for scan_parameter_value in scan_parameter_range: if self.stop_run.is_set(): break commands = [] commands.extend(self.register.get_commands("ConfMode")) self.register.set_global_register_value('PlsrDAC', scan_parameter_value) commands.extend(self.register.get_commands("WrRegister", name=['PlsrDAC'])) self.register_utils.send_commands(commands) with self.readout(PlsrDAC=scan_parameter_value): cal_lvl1_command = self.register.get_commands("CAL")[0] + self.register.get_commands("zeros", length=40)[0] + self.register.get_commands("LV1")[0] scan_loop(self, cal_lvl1_command, repeat_command=self.n_injections, use_delay=True, mask_steps=self.mask_steps, enable_mask_steps=None, enable_double_columns=None, same_mask_for_all_dc=True, fast_dc_loop=True, bol_function=None, eol_function=None, digital_injection=False, enable_shift_masks=self.enable_shift_masks, disable_shift_masks=self.disable_shift_masks, restore_shift_masks=False, mask=invert_pixel_mask(self.register.get_pixel_register_value('Enable')) if self.use_enable_mask else None, double_column_correction=self.pulser_dac_correction) def analyze(self): with AnalyzeRawData(raw_data_file=self.output_filename, create_pdf=True) as analyze_raw_data: analyze_raw_data.create_tot_hist = False analyze_raw_data.create_fitted_threshold_hists = True analyze_raw_data.create_threshold_mask = True analyze_raw_data.n_injections = 100 analyze_raw_data.interpreter.set_warning_output(False) # so far the data structure in a threshold scan was always bad, too many warnings given analyze_raw_data.interpret_word_table() analyze_raw_data.interpreter.print_summary() analyze_raw_data.plot_histograms() if __name__ == "__main__": with RunManager('configuration.yaml') as runmngr: runmngr.run_run(ThresholdScan)
self.register.set_pixel_register_value('C_High', 0) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_High'))
conditional_block
scan_threshold.py
import logging from pybar.analysis.analyze_raw_data import AnalyzeRawData from pybar.fei4.register_utils import invert_pixel_mask from pybar.fei4_run_base import Fei4RunBase from pybar.fei4.register_utils import scan_loop from pybar.run_manager import RunManager class ThresholdScan(Fei4RunBase): '''Standard Threshold Scan Implementation of a standard threshold scan. ''' _default_run_conf = { "broadcast_commands": True, "threaded_scan": True, "mask_steps": 3, # mask steps, be carefull PlsrDAC injects different charge for different mask steps "n_injections": 100, # number of injections per PlsrDAC step "scan_parameters": [('PlsrDAC', [None, 100])], # the PlsrDAC range "step_size": 1, # step size of the PlsrDAC during scan "use_enable_mask": False, # if True, use Enable mask during scan, if False, all pixels will be enabled "enable_shift_masks": ["Enable", "C_High", "C_Low"], # enable masks shifted during scan "disable_shift_masks": [], # disable masks shifted during scan "pulser_dac_correction": False # PlsrDAC correction for each double column } def configure(self): commands = [] commands.extend(self.register.get_commands("ConfMode")) # C_Low if "C_Low".lower() in map(lambda x: x.lower(), self.enable_shift_masks): self.register.set_pixel_register_value('C_Low', 1) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_Low')) else: self.register.set_pixel_register_value('C_Low', 0) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_Low')) # C_High if "C_High".lower() in map(lambda x: x.lower(), self.enable_shift_masks): self.register.set_pixel_register_value('C_High', 1) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_High')) else: self.register.set_pixel_register_value('C_High', 0) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_High')) commands.extend(self.register.get_commands("RunMode")) self.register_utils.send_commands(commands) def scan(self):
def analyze(self): with AnalyzeRawData(raw_data_file=self.output_filename, create_pdf=True) as analyze_raw_data: analyze_raw_data.create_tot_hist = False analyze_raw_data.create_fitted_threshold_hists = True analyze_raw_data.create_threshold_mask = True analyze_raw_data.n_injections = 100 analyze_raw_data.interpreter.set_warning_output(False) # so far the data structure in a threshold scan was always bad, too many warnings given analyze_raw_data.interpret_word_table() analyze_raw_data.interpreter.print_summary() analyze_raw_data.plot_histograms() if __name__ == "__main__": with RunManager('configuration.yaml') as runmngr: runmngr.run_run(ThresholdScan)
scan_parameter_range = [0, (2 ** self.register.global_registers['PlsrDAC']['bitlength'])] if self.scan_parameters.PlsrDAC[0]: scan_parameter_range[0] = self.scan_parameters.PlsrDAC[0] if self.scan_parameters.PlsrDAC[1]: scan_parameter_range[1] = self.scan_parameters.PlsrDAC[1] scan_parameter_range = range(scan_parameter_range[0], scan_parameter_range[1] + 1, self.step_size) logging.info("Scanning %s from %d to %d", 'PlsrDAC', scan_parameter_range[0], scan_parameter_range[-1]) for scan_parameter_value in scan_parameter_range: if self.stop_run.is_set(): break commands = [] commands.extend(self.register.get_commands("ConfMode")) self.register.set_global_register_value('PlsrDAC', scan_parameter_value) commands.extend(self.register.get_commands("WrRegister", name=['PlsrDAC'])) self.register_utils.send_commands(commands) with self.readout(PlsrDAC=scan_parameter_value): cal_lvl1_command = self.register.get_commands("CAL")[0] + self.register.get_commands("zeros", length=40)[0] + self.register.get_commands("LV1")[0] scan_loop(self, cal_lvl1_command, repeat_command=self.n_injections, use_delay=True, mask_steps=self.mask_steps, enable_mask_steps=None, enable_double_columns=None, same_mask_for_all_dc=True, fast_dc_loop=True, bol_function=None, eol_function=None, digital_injection=False, enable_shift_masks=self.enable_shift_masks, disable_shift_masks=self.disable_shift_masks, restore_shift_masks=False, mask=invert_pixel_mask(self.register.get_pixel_register_value('Enable')) if self.use_enable_mask else None, double_column_correction=self.pulser_dac_correction)
identifier_body
scan_threshold.py
import logging from pybar.analysis.analyze_raw_data import AnalyzeRawData from pybar.fei4.register_utils import invert_pixel_mask from pybar.fei4_run_base import Fei4RunBase from pybar.fei4.register_utils import scan_loop from pybar.run_manager import RunManager class ThresholdScan(Fei4RunBase): '''Standard Threshold Scan Implementation of a standard threshold scan. ''' _default_run_conf = { "broadcast_commands": True, "threaded_scan": True, "mask_steps": 3, # mask steps, be carefull PlsrDAC injects different charge for different mask steps "n_injections": 100, # number of injections per PlsrDAC step "scan_parameters": [('PlsrDAC', [None, 100])], # the PlsrDAC range "step_size": 1, # step size of the PlsrDAC during scan "use_enable_mask": False, # if True, use Enable mask during scan, if False, all pixels will be enabled "enable_shift_masks": ["Enable", "C_High", "C_Low"], # enable masks shifted during scan "disable_shift_masks": [], # disable masks shifted during scan "pulser_dac_correction": False # PlsrDAC correction for each double column } def configure(self): commands = [] commands.extend(self.register.get_commands("ConfMode")) # C_Low if "C_Low".lower() in map(lambda x: x.lower(), self.enable_shift_masks): self.register.set_pixel_register_value('C_Low', 1) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_Low')) else: self.register.set_pixel_register_value('C_Low', 0) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_Low')) # C_High if "C_High".lower() in map(lambda x: x.lower(), self.enable_shift_masks): self.register.set_pixel_register_value('C_High', 1) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_High')) else: self.register.set_pixel_register_value('C_High', 0) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_High')) commands.extend(self.register.get_commands("RunMode")) self.register_utils.send_commands(commands) def scan(self): scan_parameter_range = [0, (2 ** self.register.global_registers['PlsrDAC']['bitlength'])] if self.scan_parameters.PlsrDAC[0]: scan_parameter_range[0] = self.scan_parameters.PlsrDAC[0] if self.scan_parameters.PlsrDAC[1]: scan_parameter_range[1] = self.scan_parameters.PlsrDAC[1] scan_parameter_range = range(scan_parameter_range[0], scan_parameter_range[1] + 1, self.step_size) logging.info("Scanning %s from %d to %d", 'PlsrDAC', scan_parameter_range[0], scan_parameter_range[-1]) for scan_parameter_value in scan_parameter_range: if self.stop_run.is_set(): break commands = [] commands.extend(self.register.get_commands("ConfMode")) self.register.set_global_register_value('PlsrDAC', scan_parameter_value) commands.extend(self.register.get_commands("WrRegister", name=['PlsrDAC'])) self.register_utils.send_commands(commands) with self.readout(PlsrDAC=scan_parameter_value): cal_lvl1_command = self.register.get_commands("CAL")[0] + self.register.get_commands("zeros", length=40)[0] + self.register.get_commands("LV1")[0] scan_loop(self, cal_lvl1_command, repeat_command=self.n_injections, use_delay=True, mask_steps=self.mask_steps, enable_mask_steps=None, enable_double_columns=None, same_mask_for_all_dc=True, fast_dc_loop=True, bol_function=None, eol_function=None, digital_injection=False, enable_shift_masks=self.enable_shift_masks, disable_shift_masks=self.disable_shift_masks, restore_shift_masks=False, mask=invert_pixel_mask(self.register.get_pixel_register_value('Enable')) if self.use_enable_mask else None, double_column_correction=self.pulser_dac_correction) def
(self): with AnalyzeRawData(raw_data_file=self.output_filename, create_pdf=True) as analyze_raw_data: analyze_raw_data.create_tot_hist = False analyze_raw_data.create_fitted_threshold_hists = True analyze_raw_data.create_threshold_mask = True analyze_raw_data.n_injections = 100 analyze_raw_data.interpreter.set_warning_output(False) # so far the data structure in a threshold scan was always bad, too many warnings given analyze_raw_data.interpret_word_table() analyze_raw_data.interpreter.print_summary() analyze_raw_data.plot_histograms() if __name__ == "__main__": with RunManager('configuration.yaml') as runmngr: runmngr.run_run(ThresholdScan)
analyze
identifier_name
scan_threshold.py
import logging from pybar.analysis.analyze_raw_data import AnalyzeRawData from pybar.fei4.register_utils import invert_pixel_mask from pybar.fei4_run_base import Fei4RunBase from pybar.fei4.register_utils import scan_loop from pybar.run_manager import RunManager class ThresholdScan(Fei4RunBase): '''Standard Threshold Scan Implementation of a standard threshold scan. ''' _default_run_conf = { "broadcast_commands": True, "threaded_scan": True, "mask_steps": 3, # mask steps, be carefull PlsrDAC injects different charge for different mask steps "n_injections": 100, # number of injections per PlsrDAC step "scan_parameters": [('PlsrDAC', [None, 100])], # the PlsrDAC range "step_size": 1, # step size of the PlsrDAC during scan "use_enable_mask": False, # if True, use Enable mask during scan, if False, all pixels will be enabled "enable_shift_masks": ["Enable", "C_High", "C_Low"], # enable masks shifted during scan "disable_shift_masks": [], # disable masks shifted during scan "pulser_dac_correction": False # PlsrDAC correction for each double column } def configure(self): commands = [] commands.extend(self.register.get_commands("ConfMode")) # C_Low if "C_Low".lower() in map(lambda x: x.lower(), self.enable_shift_masks): self.register.set_pixel_register_value('C_Low', 1) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_Low')) else: self.register.set_pixel_register_value('C_Low', 0) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_Low')) # C_High if "C_High".lower() in map(lambda x: x.lower(), self.enable_shift_masks): self.register.set_pixel_register_value('C_High', 1) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_High')) else: self.register.set_pixel_register_value('C_High', 0) commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_High')) commands.extend(self.register.get_commands("RunMode")) self.register_utils.send_commands(commands) def scan(self): scan_parameter_range = [0, (2 ** self.register.global_registers['PlsrDAC']['bitlength'])] if self.scan_parameters.PlsrDAC[0]: scan_parameter_range[0] = self.scan_parameters.PlsrDAC[0] if self.scan_parameters.PlsrDAC[1]: scan_parameter_range[1] = self.scan_parameters.PlsrDAC[1] scan_parameter_range = range(scan_parameter_range[0], scan_parameter_range[1] + 1, self.step_size) logging.info("Scanning %s from %d to %d", 'PlsrDAC', scan_parameter_range[0], scan_parameter_range[-1]) for scan_parameter_value in scan_parameter_range: if self.stop_run.is_set(): break commands = [] commands.extend(self.register.get_commands("ConfMode")) self.register.set_global_register_value('PlsrDAC', scan_parameter_value) commands.extend(self.register.get_commands("WrRegister", name=['PlsrDAC'])) self.register_utils.send_commands(commands) with self.readout(PlsrDAC=scan_parameter_value): cal_lvl1_command = self.register.get_commands("CAL")[0] + self.register.get_commands("zeros", length=40)[0] + self.register.get_commands("LV1")[0] scan_loop(self, cal_lvl1_command, repeat_command=self.n_injections, use_delay=True, mask_steps=self.mask_steps, enable_mask_steps=None, enable_double_columns=None, same_mask_for_all_dc=True, fast_dc_loop=True, bol_function=None, eol_function=None, digital_injection=False, enable_shift_masks=self.enable_shift_masks, disable_shift_masks=self.disable_shift_masks, restore_shift_masks=False, mask=invert_pixel_mask(self.register.get_pixel_register_value('Enable')) if self.use_enable_mask else None, double_column_correction=self.pulser_dac_correction) def analyze(self):
analyze_raw_data.create_tot_hist = False analyze_raw_data.create_fitted_threshold_hists = True analyze_raw_data.create_threshold_mask = True analyze_raw_data.n_injections = 100 analyze_raw_data.interpreter.set_warning_output(False) # so far the data structure in a threshold scan was always bad, too many warnings given analyze_raw_data.interpret_word_table() analyze_raw_data.interpreter.print_summary() analyze_raw_data.plot_histograms() if __name__ == "__main__": with RunManager('configuration.yaml') as runmngr: runmngr.run_run(ThresholdScan)
with AnalyzeRawData(raw_data_file=self.output_filename, create_pdf=True) as analyze_raw_data:
random_line_split
usrp_transmit_path.py
# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr import usrp_options import transmit_path from pick_bitrate import pick_tx_bitrate from gnuradio import eng_notation def add_freq_option(parser): """ Hackery that has the -f / --freq option set both tx_freq and rx_freq """ def freq_callback(option, opt_str, value, parser): parser.values.rx_freq = value parser.values.tx_freq = value if not parser.has_option('--freq'):
def add_options(parser, expert): add_freq_option(parser) usrp_options.add_tx_options(parser) transmit_path.transmit_path.add_options(parser, expert) expert.add_option("", "--tx-freq", type="eng_float", default=None, help="set transmit frequency to FREQ [default=%default]", metavar="FREQ") parser.add_option("-v", "--verbose", action="store_true", default=False) class usrp_transmit_path(gr.hier_block2): def __init__(self, modulator_class, options): ''' See below for what options should hold ''' gr.hier_block2.__init__(self, "usrp_transmit_path", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(0, 0, 0)) # Output signature if options.tx_freq is None: sys.stderr.write("-f FREQ or --freq FREQ or --tx-freq FREQ must be specified\n") raise SystemExit tx_path = transmit_path.transmit_path(modulator_class, options) for attr in dir(tx_path): #forward the methods if not attr.startswith('_') and not hasattr(self, attr): setattr(self, attr, getattr(tx_path, attr)) #setup usrp self._modulator_class = modulator_class self._setup_usrp_sink(options) #connect self.connect(tx_path, self.u) def _setup_usrp_sink(self, options): """ Creates a USRP sink, determines the settings for best bitrate, and attaches to the transmitter's subdevice. """ self.u = usrp_options.create_usrp_sink(options) dac_rate = self.u.dac_rate() if options.verbose: print 'USRP Sink:', self.u (self._bitrate, self._samples_per_symbol, self._interp) = \ pick_tx_bitrate(options.bitrate, self._modulator_class.bits_per_symbol(), \ options.samples_per_symbol, options.interp, dac_rate, \ self.u.get_interp_rates()) self.u.set_interp(self._interp) self.u.set_auto_tr(True) if not self.u.set_center_freq(options.tx_freq): print "Failed to set Rx frequency to %s" % (eng_notation.num_to_str(options.tx_freq)) raise ValueError, eng_notation.num_to_str(options.tx_freq)
parser.add_option('-f', '--freq', type="eng_float", action="callback", callback=freq_callback, help="set Tx and/or Rx frequency to FREQ [default=%default]", metavar="FREQ")
conditional_block
usrp_transmit_path.py
# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr import usrp_options import transmit_path from pick_bitrate import pick_tx_bitrate from gnuradio import eng_notation def add_freq_option(parser): """ Hackery that has the -f / --freq option set both tx_freq and rx_freq """ def freq_callback(option, opt_str, value, parser):
if not parser.has_option('--freq'): parser.add_option('-f', '--freq', type="eng_float", action="callback", callback=freq_callback, help="set Tx and/or Rx frequency to FREQ [default=%default]", metavar="FREQ") def add_options(parser, expert): add_freq_option(parser) usrp_options.add_tx_options(parser) transmit_path.transmit_path.add_options(parser, expert) expert.add_option("", "--tx-freq", type="eng_float", default=None, help="set transmit frequency to FREQ [default=%default]", metavar="FREQ") parser.add_option("-v", "--verbose", action="store_true", default=False) class usrp_transmit_path(gr.hier_block2): def __init__(self, modulator_class, options): ''' See below for what options should hold ''' gr.hier_block2.__init__(self, "usrp_transmit_path", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(0, 0, 0)) # Output signature if options.tx_freq is None: sys.stderr.write("-f FREQ or --freq FREQ or --tx-freq FREQ must be specified\n") raise SystemExit tx_path = transmit_path.transmit_path(modulator_class, options) for attr in dir(tx_path): #forward the methods if not attr.startswith('_') and not hasattr(self, attr): setattr(self, attr, getattr(tx_path, attr)) #setup usrp self._modulator_class = modulator_class self._setup_usrp_sink(options) #connect self.connect(tx_path, self.u) def _setup_usrp_sink(self, options): """ Creates a USRP sink, determines the settings for best bitrate, and attaches to the transmitter's subdevice. """ self.u = usrp_options.create_usrp_sink(options) dac_rate = self.u.dac_rate() if options.verbose: print 'USRP Sink:', self.u (self._bitrate, self._samples_per_symbol, self._interp) = \ pick_tx_bitrate(options.bitrate, self._modulator_class.bits_per_symbol(), \ options.samples_per_symbol, options.interp, dac_rate, \ self.u.get_interp_rates()) self.u.set_interp(self._interp) self.u.set_auto_tr(True) if not self.u.set_center_freq(options.tx_freq): print "Failed to set Rx frequency to %s" % (eng_notation.num_to_str(options.tx_freq)) raise ValueError, eng_notation.num_to_str(options.tx_freq)
parser.values.rx_freq = value parser.values.tx_freq = value
identifier_body
usrp_transmit_path.py
# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr import usrp_options import transmit_path from pick_bitrate import pick_tx_bitrate from gnuradio import eng_notation def add_freq_option(parser): """ Hackery that has the -f / --freq option set both tx_freq and rx_freq """ def freq_callback(option, opt_str, value, parser): parser.values.rx_freq = value parser.values.tx_freq = value if not parser.has_option('--freq'): parser.add_option('-f', '--freq', type="eng_float", action="callback", callback=freq_callback, help="set Tx and/or Rx frequency to FREQ [default=%default]", metavar="FREQ")
def add_options(parser, expert): add_freq_option(parser) usrp_options.add_tx_options(parser) transmit_path.transmit_path.add_options(parser, expert) expert.add_option("", "--tx-freq", type="eng_float", default=None, help="set transmit frequency to FREQ [default=%default]", metavar="FREQ") parser.add_option("-v", "--verbose", action="store_true", default=False) class usrp_transmit_path(gr.hier_block2): def __init__(self, modulator_class, options): ''' See below for what options should hold ''' gr.hier_block2.__init__(self, "usrp_transmit_path", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(0, 0, 0)) # Output signature if options.tx_freq is None: sys.stderr.write("-f FREQ or --freq FREQ or --tx-freq FREQ must be specified\n") raise SystemExit tx_path = transmit_path.transmit_path(modulator_class, options) for attr in dir(tx_path): #forward the methods if not attr.startswith('_') and not hasattr(self, attr): setattr(self, attr, getattr(tx_path, attr)) #setup usrp self._modulator_class = modulator_class self._setup_usrp_sink(options) #connect self.connect(tx_path, self.u) def _setup_usrp_sink(self, options): """ Creates a USRP sink, determines the settings for best bitrate, and attaches to the transmitter's subdevice. """ self.u = usrp_options.create_usrp_sink(options) dac_rate = self.u.dac_rate() if options.verbose: print 'USRP Sink:', self.u (self._bitrate, self._samples_per_symbol, self._interp) = \ pick_tx_bitrate(options.bitrate, self._modulator_class.bits_per_symbol(), \ options.samples_per_symbol, options.interp, dac_rate, \ self.u.get_interp_rates()) self.u.set_interp(self._interp) self.u.set_auto_tr(True) if not self.u.set_center_freq(options.tx_freq): print "Failed to set Rx frequency to %s" % (eng_notation.num_to_str(options.tx_freq)) raise ValueError, eng_notation.num_to_str(options.tx_freq)
random_line_split
usrp_transmit_path.py
# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr import usrp_options import transmit_path from pick_bitrate import pick_tx_bitrate from gnuradio import eng_notation def add_freq_option(parser): """ Hackery that has the -f / --freq option set both tx_freq and rx_freq """ def freq_callback(option, opt_str, value, parser): parser.values.rx_freq = value parser.values.tx_freq = value if not parser.has_option('--freq'): parser.add_option('-f', '--freq', type="eng_float", action="callback", callback=freq_callback, help="set Tx and/or Rx frequency to FREQ [default=%default]", metavar="FREQ") def add_options(parser, expert): add_freq_option(parser) usrp_options.add_tx_options(parser) transmit_path.transmit_path.add_options(parser, expert) expert.add_option("", "--tx-freq", type="eng_float", default=None, help="set transmit frequency to FREQ [default=%default]", metavar="FREQ") parser.add_option("-v", "--verbose", action="store_true", default=False) class usrp_transmit_path(gr.hier_block2): def
(self, modulator_class, options): ''' See below for what options should hold ''' gr.hier_block2.__init__(self, "usrp_transmit_path", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(0, 0, 0)) # Output signature if options.tx_freq is None: sys.stderr.write("-f FREQ or --freq FREQ or --tx-freq FREQ must be specified\n") raise SystemExit tx_path = transmit_path.transmit_path(modulator_class, options) for attr in dir(tx_path): #forward the methods if not attr.startswith('_') and not hasattr(self, attr): setattr(self, attr, getattr(tx_path, attr)) #setup usrp self._modulator_class = modulator_class self._setup_usrp_sink(options) #connect self.connect(tx_path, self.u) def _setup_usrp_sink(self, options): """ Creates a USRP sink, determines the settings for best bitrate, and attaches to the transmitter's subdevice. """ self.u = usrp_options.create_usrp_sink(options) dac_rate = self.u.dac_rate() if options.verbose: print 'USRP Sink:', self.u (self._bitrate, self._samples_per_symbol, self._interp) = \ pick_tx_bitrate(options.bitrate, self._modulator_class.bits_per_symbol(), \ options.samples_per_symbol, options.interp, dac_rate, \ self.u.get_interp_rates()) self.u.set_interp(self._interp) self.u.set_auto_tr(True) if not self.u.set_center_freq(options.tx_freq): print "Failed to set Rx frequency to %s" % (eng_notation.num_to_str(options.tx_freq)) raise ValueError, eng_notation.num_to_str(options.tx_freq)
__init__
identifier_name
network_usage.rs
use futures::{Future, Stream}; use std::sync::Arc; use tokio_timer::Timer; use tokio_core::reactor::Handle; use component::Component; use error::{Error, Result}; use std::time::Duration; use utils; #[derive(Clone, PartialEq, Copy)] pub enum Scale { Binary, Decimal, } impl Scale { fn base(&self) -> u16 { match *self { Scale::Decimal => 1000,
Scale::Binary => 1024, } } } #[derive(Clone, Copy)] pub enum Direction { Incoming, Outgoing, } pub struct NetworkUsage { pub interface: String, pub direction: Direction, pub scale: Scale, pub percision: u8, pub refresh_frequency: Duration, pub sample_duration: Duration, } impl Default for NetworkUsage { fn default() -> NetworkUsage { NetworkUsage { interface: "eth0".to_string(), direction: Direction::Incoming, scale: Scale::Binary, percision: 3, refresh_frequency: Duration::from_secs(10), sample_duration: Duration::from_secs(1), } } } fn get_prefix(scale: Scale, power: u8) -> &'static str { match (scale, power) { (Scale::Decimal, 0) | (Scale::Binary, 0) => "B/s", (Scale::Decimal, 1) => "kb/s", (Scale::Decimal, 2) => "Mb/s", (Scale::Decimal, 3) => "Gb/s", (Scale::Decimal, 4) => "Tb/s", (Scale::Binary, 1) => "KiB/s", (Scale::Binary, 2) => "MiB/s", (Scale::Binary, 3) => "GiB/s", (Scale::Binary, 4) => "TiB/s", _ => "X/s", } } fn get_number_scale(number: u64, scale: Scale) -> (f64, u8) { let log = (number as f64).log(scale.base() as f64); let wholes = log.floor(); let over = (scale.base() as f64).powf(log - wholes); (over, wholes as u8) } fn get_bytes(interface: &str, dir: Direction) -> ::std::io::Result<Option<u64>> { let dev = ::procinfo::net::dev::dev()? .into_iter() .find(|dev| dev.interface == interface); let dev = match dev { Some(dev) => dev, None => return Ok(None), }; match dir { Direction::Incoming => Ok(Some(dev.receive_bytes)), Direction::Outgoing => Ok(Some(dev.transmit_bytes)), } } impl Component for NetworkUsage { type Error = Error; type Stream = Box<Stream<Item = String, Error = Error>>; fn init(&mut self) -> Result<()> { ::procinfo::net::dev::dev()? .into_iter() .find(|dev| dev.interface == self.interface) .ok_or_else(|| Error::from("No such network interface"))?; Ok(()) } fn stream(self, _: Handle) -> Self::Stream { let conf = Arc::new(self); utils::LoopFn::new(move || { let timer = Timer::default(); let conf = conf.clone(); timer.sleep(conf.refresh_frequency) .and_then(move |()| { let conf = conf.clone(); let conf2 = conf.clone(); let first = get_bytes(conf.interface.as_str(), conf.direction) .unwrap().unwrap(); timer.sleep(conf.sample_duration) .and_then(move |()| { let second = get_bytes(conf.interface.as_str(), conf.direction) .unwrap().unwrap(); let per_second = (second-first)/conf.sample_duration.as_secs(); Ok(per_second) }) .map(move |speed| { let (num, power) = get_number_scale(speed, conf2.scale); let x = 10f64.powi((conf2.percision-1) as i32); let num = (num*x).round() / x; format!("{} {}", num, get_prefix(conf2.scale, power)) }) }) }).map_err(|_| "timer error".into()) .boxed() } }
random_line_split
network_usage.rs
use futures::{Future, Stream}; use std::sync::Arc; use tokio_timer::Timer; use tokio_core::reactor::Handle; use component::Component; use error::{Error, Result}; use std::time::Duration; use utils; #[derive(Clone, PartialEq, Copy)] pub enum Scale { Binary, Decimal, } impl Scale { fn base(&self) -> u16 { match *self { Scale::Decimal => 1000, Scale::Binary => 1024, } } } #[derive(Clone, Copy)] pub enum Direction { Incoming, Outgoing, } pub struct
{ pub interface: String, pub direction: Direction, pub scale: Scale, pub percision: u8, pub refresh_frequency: Duration, pub sample_duration: Duration, } impl Default for NetworkUsage { fn default() -> NetworkUsage { NetworkUsage { interface: "eth0".to_string(), direction: Direction::Incoming, scale: Scale::Binary, percision: 3, refresh_frequency: Duration::from_secs(10), sample_duration: Duration::from_secs(1), } } } fn get_prefix(scale: Scale, power: u8) -> &'static str { match (scale, power) { (Scale::Decimal, 0) | (Scale::Binary, 0) => "B/s", (Scale::Decimal, 1) => "kb/s", (Scale::Decimal, 2) => "Mb/s", (Scale::Decimal, 3) => "Gb/s", (Scale::Decimal, 4) => "Tb/s", (Scale::Binary, 1) => "KiB/s", (Scale::Binary, 2) => "MiB/s", (Scale::Binary, 3) => "GiB/s", (Scale::Binary, 4) => "TiB/s", _ => "X/s", } } fn get_number_scale(number: u64, scale: Scale) -> (f64, u8) { let log = (number as f64).log(scale.base() as f64); let wholes = log.floor(); let over = (scale.base() as f64).powf(log - wholes); (over, wholes as u8) } fn get_bytes(interface: &str, dir: Direction) -> ::std::io::Result<Option<u64>> { let dev = ::procinfo::net::dev::dev()? .into_iter() .find(|dev| dev.interface == interface); let dev = match dev { Some(dev) => dev, None => return Ok(None), }; match dir { Direction::Incoming => Ok(Some(dev.receive_bytes)), Direction::Outgoing => Ok(Some(dev.transmit_bytes)), } } impl Component for NetworkUsage { type Error = Error; type Stream = Box<Stream<Item = String, Error = Error>>; fn init(&mut self) -> Result<()> { ::procinfo::net::dev::dev()? .into_iter() .find(|dev| dev.interface == self.interface) .ok_or_else(|| Error::from("No such network interface"))?; Ok(()) } fn stream(self, _: Handle) -> Self::Stream { let conf = Arc::new(self); utils::LoopFn::new(move || { let timer = Timer::default(); let conf = conf.clone(); timer.sleep(conf.refresh_frequency) .and_then(move |()| { let conf = conf.clone(); let conf2 = conf.clone(); let first = get_bytes(conf.interface.as_str(), conf.direction) .unwrap().unwrap(); timer.sleep(conf.sample_duration) .and_then(move |()| { let second = get_bytes(conf.interface.as_str(), conf.direction) .unwrap().unwrap(); let per_second = (second-first)/conf.sample_duration.as_secs(); Ok(per_second) }) .map(move |speed| { let (num, power) = get_number_scale(speed, conf2.scale); let x = 10f64.powi((conf2.percision-1) as i32); let num = (num*x).round() / x; format!("{} {}", num, get_prefix(conf2.scale, power)) }) }) }).map_err(|_| "timer error".into()) .boxed() } }
NetworkUsage
identifier_name
network_usage.rs
use futures::{Future, Stream}; use std::sync::Arc; use tokio_timer::Timer; use tokio_core::reactor::Handle; use component::Component; use error::{Error, Result}; use std::time::Duration; use utils; #[derive(Clone, PartialEq, Copy)] pub enum Scale { Binary, Decimal, } impl Scale { fn base(&self) -> u16 { match *self { Scale::Decimal => 1000, Scale::Binary => 1024, } } } #[derive(Clone, Copy)] pub enum Direction { Incoming, Outgoing, } pub struct NetworkUsage { pub interface: String, pub direction: Direction, pub scale: Scale, pub percision: u8, pub refresh_frequency: Duration, pub sample_duration: Duration, } impl Default for NetworkUsage { fn default() -> NetworkUsage
} fn get_prefix(scale: Scale, power: u8) -> &'static str { match (scale, power) { (Scale::Decimal, 0) | (Scale::Binary, 0) => "B/s", (Scale::Decimal, 1) => "kb/s", (Scale::Decimal, 2) => "Mb/s", (Scale::Decimal, 3) => "Gb/s", (Scale::Decimal, 4) => "Tb/s", (Scale::Binary, 1) => "KiB/s", (Scale::Binary, 2) => "MiB/s", (Scale::Binary, 3) => "GiB/s", (Scale::Binary, 4) => "TiB/s", _ => "X/s", } } fn get_number_scale(number: u64, scale: Scale) -> (f64, u8) { let log = (number as f64).log(scale.base() as f64); let wholes = log.floor(); let over = (scale.base() as f64).powf(log - wholes); (over, wholes as u8) } fn get_bytes(interface: &str, dir: Direction) -> ::std::io::Result<Option<u64>> { let dev = ::procinfo::net::dev::dev()? .into_iter() .find(|dev| dev.interface == interface); let dev = match dev { Some(dev) => dev, None => return Ok(None), }; match dir { Direction::Incoming => Ok(Some(dev.receive_bytes)), Direction::Outgoing => Ok(Some(dev.transmit_bytes)), } } impl Component for NetworkUsage { type Error = Error; type Stream = Box<Stream<Item = String, Error = Error>>; fn init(&mut self) -> Result<()> { ::procinfo::net::dev::dev()? .into_iter() .find(|dev| dev.interface == self.interface) .ok_or_else(|| Error::from("No such network interface"))?; Ok(()) } fn stream(self, _: Handle) -> Self::Stream { let conf = Arc::new(self); utils::LoopFn::new(move || { let timer = Timer::default(); let conf = conf.clone(); timer.sleep(conf.refresh_frequency) .and_then(move |()| { let conf = conf.clone(); let conf2 = conf.clone(); let first = get_bytes(conf.interface.as_str(), conf.direction) .unwrap().unwrap(); timer.sleep(conf.sample_duration) .and_then(move |()| { let second = get_bytes(conf.interface.as_str(), conf.direction) .unwrap().unwrap(); let per_second = (second-first)/conf.sample_duration.as_secs(); Ok(per_second) }) .map(move |speed| { let (num, power) = get_number_scale(speed, conf2.scale); let x = 10f64.powi((conf2.percision-1) as i32); let num = (num*x).round() / x; format!("{} {}", num, get_prefix(conf2.scale, power)) }) }) }).map_err(|_| "timer error".into()) .boxed() } }
{ NetworkUsage { interface: "eth0".to_string(), direction: Direction::Incoming, scale: Scale::Binary, percision: 3, refresh_frequency: Duration::from_secs(10), sample_duration: Duration::from_secs(1), } }
identifier_body
index.js
/* global location */ /* Centralized place to reference utilities since utils is exposed to the user. */ var debug = require('./debug'); var deepAssign = require('deep-assign'); var device = require('./device'); var objectAssign = require('object-assign'); var objectPool = require('./object-pool'); var warn = debug('utils:warn'); module.exports.bind = require('./bind'); module.exports.coordinates = require('./coordinates'); module.exports.debug = debug; module.exports.device = device; module.exports.entity = require('./entity'); module.exports.forceCanvasResizeSafariMobile = require('./forceCanvasResizeSafariMobile'); module.exports.material = require('./material'); module.exports.objectPool = objectPool; module.exports.styleParser = require('./styleParser'); module.exports.trackedControls = require('./tracked-controls'); module.exports.checkHeadsetConnected = function () { warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`'); return device.checkHeadsetConnected(arguments); }; module.exports.isGearVR = function () { warn('`utils.isGearVR` has moved to `utils.device.isGearVR`'); return device.isGearVR(arguments); }; module.exports.isIOS = function () { warn('`utils.isIOS` has moved to `utils.device.isIOS`'); return device.isIOS(arguments); }; module.exports.isMobile = function () { warn('`utils.isMobile has moved to `utils.device.isMobile`'); return device.isMobile(arguments); }; /** * Returns throttle function that gets called at most once every interval. * * @param {function} functionToThrottle * @param {number} minimumInterval - Minimal interval between calls (milliseconds). * @param {object} optionalContext - If given, bind function to throttle to this context. * @returns {function} Throttled function. */ module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) { var lastTime; if (optionalContext) { functionToThrottle = module.exports.bind(functionToThrottle, optionalContext); } return function () { var time = Date.now(); var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime; if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) { lastTime = time; functionToThrottle.apply(null, arguments); } }; }; /** * Returns throttle function that gets called at most once every interval. * Uses the time/timeDelta timestamps provided by the global render loop for better perf. * * @param {function} functionToThrottle * @param {number} minimumInterval - Minimal interval between calls (milliseconds). * @param {object} optionalContext - If given, bind function to throttle to this context. * @returns {function} Throttled function. */ module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) { var lastTime; if (optionalContext) { functionToThrottle = module.exports.bind(functionToThrottle, optionalContext); } return function (time, delta) { var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime; if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) { lastTime = time; functionToThrottle(time, sinceLastTime); } }; }; /** * Returns debounce function that gets called only once after a set of repeated calls. * * @param {function} functionToDebounce * @param {number} wait - Time to wait for repeated function calls (milliseconds). * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting. * @returns {function} Debounced function. */ module.exports.debounce = function (func, wait, immediate) { var timeout; return function () { var context = this; var args = arguments; var later = function () { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; /** * Mix the properties of source object(s) into a destination object. * * @param {object} dest - The object to which properties will be copied. * @param {...object} source - The object(s) from which properties will be copied. */ module.exports.extend = objectAssign; module.exports.extendDeep = deepAssign; module.exports.clone = function (obj) { return JSON.parse(JSON.stringify(obj)); }; /** * Checks if two values are equal. * Includes objects and arrays and nested objects and arrays. * Try to keep this function performant as it will be called often to see if a component * should be updated. * * @param {object} a - First object. * @param {object} b - Second object. * @returns {boolean} Whether two objects are deeply equal. */ var deepEqual = (function () { var arrayPool = objectPool.createPool(function () { return []; }); return function (a, b) { var key; var keysA; var keysB; var i; var valA; var valB; // If not objects or arrays, compare as values. if (a === undefined || b === undefined || a === null || b === null || !(a && b && (a.constructor === Object && b.constructor === Object) || (a.constructor === Array && b.constructor === Array))) { return a === b; } // Different number of keys, not equal. keysA = arrayPool.use(); keysB = arrayPool.use(); keysA.length = 0; keysB.length = 0; for (key in a) { keysA.push(key); } for (key in b) { keysB.push(key); } if (keysA.length !== keysB.length) { arrayPool.recycle(keysA); arrayPool.recycle(keysB); return false; } // Return `false` at the first sign of inequality. for (i = 0; i < keysA.length; ++i) { valA = a[keysA[i]]; valB = b[keysA[i]]; // Check nested array and object. if ((typeof valA === 'object' || typeof valB === 'object') || (Array.isArray(valA) && Array.isArray(valB))) { if (valA === valB) { continue; } if (!deepEqual(valA, valB)) { arrayPool.recycle(keysA); arrayPool.recycle(keysB); return false; } } else if (valA !== valB) { arrayPool.recycle(keysA); arrayPool.recycle(keysB); return false; } } arrayPool.recycle(keysA); arrayPool.recycle(keysB); return true; }; })(); module.exports.deepEqual = deepEqual; /** * Computes the difference between two objects. * * @param {object} a - First object to compare (e.g., oldData). * @param {object} b - Second object to compare (e.g., newData). * @returns {object} * Difference object where set of keys note which values were not equal, and values are * `b`'s values. */ module.exports.diff = (function () { var keys = []; return function (a, b, targetObject) { var aVal; var bVal; var bKey; var diff; var key; var i; var isComparingObjects; diff = targetObject || {}; // Collect A keys. keys.length = 0; for (key in a) { keys.push(key); } if (!b) { return diff; } // Collect B keys. for (bKey in b) { if (keys.indexOf(bKey) === -1) { keys.push(bKey); } } for (i = 0; i < keys.length; i++) { key = keys[i]; aVal = a[key]; bVal = b[key]; isComparingObjects = aVal && bVal && aVal.constructor === Object && bVal.constructor === Object; if ((isComparingObjects && !deepEqual(aVal, bVal)) || (!isComparingObjects && aVal !== bVal)) { diff[key] = bVal; } } return diff; }; })(); /** * Returns whether we should capture this keyboard event for keyboard shortcuts. * @param {Event} event Event object. * @returns {Boolean} Whether the key event should be captured. */ module.exports.shouldCaptureKeyEvent = function (event) { if (event.metaKey) { return false; } return document.activeElement === document.body; }; /** * Splits a string into an array based on a delimiter. * * @param {string=} [str=''] Source string * @param {string=} [delimiter=' '] Delimiter to use * @returns {array} Array of delimited strings */ module.exports.splitString = function (str, delimiter) { if (typeof delimiter === 'undefined') { delimiter = ' '; } // First collapse the whitespace (or whatever the delimiter is). var regex = new RegExp(delimiter, 'g'); str = (str || '').replace(regex, delimiter); // Then split. return str.split(delimiter); }; /** * Extracts data from the element given an object that contains expected keys. * * @param {Element} Source element. * @param {Object} [defaults={}] Object of default key-value pairs. * @returns {Object} */ module.exports.getElData = function (el, defaults) { defaults = defaults || {}; var data = {}; Object.keys(defaults).forEach(copyAttribute); function copyAttribute (key)
return data; }; /** * Retrieves querystring value. * @param {String} name Name of querystring key. * @return {String} Value */ module.exports.getUrlParameter = function (name) { // eslint-disable-next-line no-useless-escape name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'); var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'); var results = regex.exec(location.search); return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' ')); }; /** * Detects whether context is within iframe. */ module.exports.isIframed = function () { return window.top !== window.self; }; /** * Finds all elements under the element that have the isScene * property set to true */ module.exports.findAllScenes = function (el) { var matchingElements = []; var allElements = el.getElementsByTagName('*'); for (var i = 0, n = allElements.length; i < n; i++) { if (allElements[i].isScene) { // Element exists with isScene set. matchingElements.push(allElements[i]); } } return matchingElements; }; // Must be at bottom to avoid circular dependency. module.exports.srcLoader = require('./src-loader'); /** * String split with cached result. */ module.exports.split = (function () { var splitCache = {}; return function (str, delimiter) { if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; } if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; } splitCache[delimiter][str] = str.split(delimiter); return splitCache[delimiter][str]; }; })();
{ if (el.hasAttribute(key)) { data[key] = el.getAttribute(key); } }
identifier_body
index.js
/* global location */ /* Centralized place to reference utilities since utils is exposed to the user. */ var debug = require('./debug'); var deepAssign = require('deep-assign'); var device = require('./device'); var objectAssign = require('object-assign'); var objectPool = require('./object-pool'); var warn = debug('utils:warn'); module.exports.bind = require('./bind'); module.exports.coordinates = require('./coordinates'); module.exports.debug = debug; module.exports.device = device; module.exports.entity = require('./entity'); module.exports.forceCanvasResizeSafariMobile = require('./forceCanvasResizeSafariMobile'); module.exports.material = require('./material'); module.exports.objectPool = objectPool; module.exports.styleParser = require('./styleParser'); module.exports.trackedControls = require('./tracked-controls'); module.exports.checkHeadsetConnected = function () { warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`'); return device.checkHeadsetConnected(arguments); }; module.exports.isGearVR = function () { warn('`utils.isGearVR` has moved to `utils.device.isGearVR`'); return device.isGearVR(arguments); }; module.exports.isIOS = function () { warn('`utils.isIOS` has moved to `utils.device.isIOS`'); return device.isIOS(arguments); }; module.exports.isMobile = function () { warn('`utils.isMobile has moved to `utils.device.isMobile`'); return device.isMobile(arguments); }; /** * Returns throttle function that gets called at most once every interval. * * @param {function} functionToThrottle * @param {number} minimumInterval - Minimal interval between calls (milliseconds). * @param {object} optionalContext - If given, bind function to throttle to this context. * @returns {function} Throttled function. */ module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) { var lastTime; if (optionalContext) { functionToThrottle = module.exports.bind(functionToThrottle, optionalContext); } return function () { var time = Date.now(); var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime; if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) { lastTime = time; functionToThrottle.apply(null, arguments); } }; }; /** * Returns throttle function that gets called at most once every interval. * Uses the time/timeDelta timestamps provided by the global render loop for better perf. * * @param {function} functionToThrottle * @param {number} minimumInterval - Minimal interval between calls (milliseconds). * @param {object} optionalContext - If given, bind function to throttle to this context. * @returns {function} Throttled function. */ module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) { var lastTime; if (optionalContext) { functionToThrottle = module.exports.bind(functionToThrottle, optionalContext); } return function (time, delta) { var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime; if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) { lastTime = time; functionToThrottle(time, sinceLastTime); } }; }; /** * Returns debounce function that gets called only once after a set of repeated calls. * * @param {function} functionToDebounce * @param {number} wait - Time to wait for repeated function calls (milliseconds). * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting. * @returns {function} Debounced function. */ module.exports.debounce = function (func, wait, immediate) { var timeout; return function () { var context = this; var args = arguments; var later = function () { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; /** * Mix the properties of source object(s) into a destination object. * * @param {object} dest - The object to which properties will be copied. * @param {...object} source - The object(s) from which properties will be copied. */ module.exports.extend = objectAssign; module.exports.extendDeep = deepAssign; module.exports.clone = function (obj) { return JSON.parse(JSON.stringify(obj)); }; /** * Checks if two values are equal. * Includes objects and arrays and nested objects and arrays. * Try to keep this function performant as it will be called often to see if a component * should be updated. * * @param {object} a - First object. * @param {object} b - Second object. * @returns {boolean} Whether two objects are deeply equal. */ var deepEqual = (function () { var arrayPool = objectPool.createPool(function () { return []; }); return function (a, b) { var key; var keysA; var keysB; var i; var valA; var valB; // If not objects or arrays, compare as values. if (a === undefined || b === undefined || a === null || b === null || !(a && b && (a.constructor === Object && b.constructor === Object) || (a.constructor === Array && b.constructor === Array))) { return a === b; } // Different number of keys, not equal. keysA = arrayPool.use(); keysB = arrayPool.use(); keysA.length = 0; keysB.length = 0; for (key in a) { keysA.push(key); } for (key in b) { keysB.push(key); } if (keysA.length !== keysB.length) { arrayPool.recycle(keysA); arrayPool.recycle(keysB); return false; } // Return `false` at the first sign of inequality. for (i = 0; i < keysA.length; ++i) { valA = a[keysA[i]]; valB = b[keysA[i]]; // Check nested array and object. if ((typeof valA === 'object' || typeof valB === 'object') || (Array.isArray(valA) && Array.isArray(valB))) { if (valA === valB) { continue; } if (!deepEqual(valA, valB)) { arrayPool.recycle(keysA); arrayPool.recycle(keysB); return false; } } else if (valA !== valB) { arrayPool.recycle(keysA); arrayPool.recycle(keysB); return false; } } arrayPool.recycle(keysA); arrayPool.recycle(keysB); return true; }; })(); module.exports.deepEqual = deepEqual; /** * Computes the difference between two objects. * * @param {object} a - First object to compare (e.g., oldData). * @param {object} b - Second object to compare (e.g., newData). * @returns {object} * Difference object where set of keys note which values were not equal, and values are * `b`'s values. */ module.exports.diff = (function () { var keys = []; return function (a, b, targetObject) { var aVal; var bVal; var bKey; var diff; var key; var i; var isComparingObjects; diff = targetObject || {}; // Collect A keys. keys.length = 0; for (key in a) { keys.push(key); } if (!b) { return diff; } // Collect B keys. for (bKey in b) { if (keys.indexOf(bKey) === -1) { keys.push(bKey); } } for (i = 0; i < keys.length; i++) { key = keys[i]; aVal = a[key]; bVal = b[key]; isComparingObjects = aVal && bVal && aVal.constructor === Object && bVal.constructor === Object; if ((isComparingObjects && !deepEqual(aVal, bVal)) || (!isComparingObjects && aVal !== bVal)) { diff[key] = bVal; } } return diff; }; })(); /** * Returns whether we should capture this keyboard event for keyboard shortcuts. * @param {Event} event Event object. * @returns {Boolean} Whether the key event should be captured. */ module.exports.shouldCaptureKeyEvent = function (event) { if (event.metaKey) { return false; } return document.activeElement === document.body; }; /** * Splits a string into an array based on a delimiter. * * @param {string=} [str=''] Source string * @param {string=} [delimiter=' '] Delimiter to use * @returns {array} Array of delimited strings */ module.exports.splitString = function (str, delimiter) { if (typeof delimiter === 'undefined') { delimiter = ' '; } // First collapse the whitespace (or whatever the delimiter is). var regex = new RegExp(delimiter, 'g'); str = (str || '').replace(regex, delimiter); // Then split. return str.split(delimiter); }; /** * Extracts data from the element given an object that contains expected keys. * * @param {Element} Source element. * @param {Object} [defaults={}] Object of default key-value pairs. * @returns {Object} */ module.exports.getElData = function (el, defaults) { defaults = defaults || {}; var data = {}; Object.keys(defaults).forEach(copyAttribute); function
(key) { if (el.hasAttribute(key)) { data[key] = el.getAttribute(key); } } return data; }; /** * Retrieves querystring value. * @param {String} name Name of querystring key. * @return {String} Value */ module.exports.getUrlParameter = function (name) { // eslint-disable-next-line no-useless-escape name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'); var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'); var results = regex.exec(location.search); return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' ')); }; /** * Detects whether context is within iframe. */ module.exports.isIframed = function () { return window.top !== window.self; }; /** * Finds all elements under the element that have the isScene * property set to true */ module.exports.findAllScenes = function (el) { var matchingElements = []; var allElements = el.getElementsByTagName('*'); for (var i = 0, n = allElements.length; i < n; i++) { if (allElements[i].isScene) { // Element exists with isScene set. matchingElements.push(allElements[i]); } } return matchingElements; }; // Must be at bottom to avoid circular dependency. module.exports.srcLoader = require('./src-loader'); /** * String split with cached result. */ module.exports.split = (function () { var splitCache = {}; return function (str, delimiter) { if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; } if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; } splitCache[delimiter][str] = str.split(delimiter); return splitCache[delimiter][str]; }; })();
copyAttribute
identifier_name
index.js
/* global location */ /* Centralized place to reference utilities since utils is exposed to the user. */ var debug = require('./debug'); var deepAssign = require('deep-assign'); var device = require('./device'); var objectAssign = require('object-assign'); var objectPool = require('./object-pool'); var warn = debug('utils:warn'); module.exports.bind = require('./bind'); module.exports.coordinates = require('./coordinates'); module.exports.debug = debug; module.exports.device = device; module.exports.entity = require('./entity'); module.exports.forceCanvasResizeSafariMobile = require('./forceCanvasResizeSafariMobile'); module.exports.material = require('./material'); module.exports.objectPool = objectPool; module.exports.styleParser = require('./styleParser'); module.exports.trackedControls = require('./tracked-controls'); module.exports.checkHeadsetConnected = function () { warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`'); return device.checkHeadsetConnected(arguments); }; module.exports.isGearVR = function () { warn('`utils.isGearVR` has moved to `utils.device.isGearVR`'); return device.isGearVR(arguments); }; module.exports.isIOS = function () { warn('`utils.isIOS` has moved to `utils.device.isIOS`'); return device.isIOS(arguments); }; module.exports.isMobile = function () { warn('`utils.isMobile has moved to `utils.device.isMobile`'); return device.isMobile(arguments); }; /** * Returns throttle function that gets called at most once every interval. * * @param {function} functionToThrottle * @param {number} minimumInterval - Minimal interval between calls (milliseconds). * @param {object} optionalContext - If given, bind function to throttle to this context. * @returns {function} Throttled function. */ module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) { var lastTime; if (optionalContext) { functionToThrottle = module.exports.bind(functionToThrottle, optionalContext); } return function () { var time = Date.now(); var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime; if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) { lastTime = time; functionToThrottle.apply(null, arguments); } }; }; /** * Returns throttle function that gets called at most once every interval. * Uses the time/timeDelta timestamps provided by the global render loop for better perf. * * @param {function} functionToThrottle * @param {number} minimumInterval - Minimal interval between calls (milliseconds). * @param {object} optionalContext - If given, bind function to throttle to this context. * @returns {function} Throttled function. */ module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) { var lastTime; if (optionalContext) { functionToThrottle = module.exports.bind(functionToThrottle, optionalContext); } return function (time, delta) { var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime; if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) { lastTime = time; functionToThrottle(time, sinceLastTime); } }; }; /** * Returns debounce function that gets called only once after a set of repeated calls. * * @param {function} functionToDebounce * @param {number} wait - Time to wait for repeated function calls (milliseconds). * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting. * @returns {function} Debounced function. */ module.exports.debounce = function (func, wait, immediate) { var timeout; return function () { var context = this; var args = arguments; var later = function () { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; /** * Mix the properties of source object(s) into a destination object. * * @param {object} dest - The object to which properties will be copied. * @param {...object} source - The object(s) from which properties will be copied. */ module.exports.extend = objectAssign; module.exports.extendDeep = deepAssign; module.exports.clone = function (obj) { return JSON.parse(JSON.stringify(obj)); }; /** * Checks if two values are equal. * Includes objects and arrays and nested objects and arrays. * Try to keep this function performant as it will be called often to see if a component * should be updated. * * @param {object} a - First object. * @param {object} b - Second object. * @returns {boolean} Whether two objects are deeply equal. */ var deepEqual = (function () { var arrayPool = objectPool.createPool(function () { return []; }); return function (a, b) { var key; var keysA; var keysB; var i; var valA; var valB; // If not objects or arrays, compare as values. if (a === undefined || b === undefined || a === null || b === null || !(a && b && (a.constructor === Object && b.constructor === Object) || (a.constructor === Array && b.constructor === Array))) { return a === b; } // Different number of keys, not equal. keysA = arrayPool.use(); keysB = arrayPool.use(); keysA.length = 0; keysB.length = 0; for (key in a) { keysA.push(key); } for (key in b) { keysB.push(key); } if (keysA.length !== keysB.length) { arrayPool.recycle(keysA); arrayPool.recycle(keysB); return false; } // Return `false` at the first sign of inequality. for (i = 0; i < keysA.length; ++i) { valA = a[keysA[i]]; valB = b[keysA[i]]; // Check nested array and object. if ((typeof valA === 'object' || typeof valB === 'object') || (Array.isArray(valA) && Array.isArray(valB))) { if (valA === valB) { continue; } if (!deepEqual(valA, valB)) { arrayPool.recycle(keysA); arrayPool.recycle(keysB); return false; } } else if (valA !== valB) { arrayPool.recycle(keysA); arrayPool.recycle(keysB); return false; } } arrayPool.recycle(keysA); arrayPool.recycle(keysB); return true; }; })(); module.exports.deepEqual = deepEqual; /** * Computes the difference between two objects. * * @param {object} a - First object to compare (e.g., oldData). * @param {object} b - Second object to compare (e.g., newData). * @returns {object} * Difference object where set of keys note which values were not equal, and values are * `b`'s values. */ module.exports.diff = (function () { var keys = []; return function (a, b, targetObject) { var aVal; var bVal; var bKey; var diff; var key; var i; var isComparingObjects; diff = targetObject || {}; // Collect A keys. keys.length = 0; for (key in a) { keys.push(key); } if (!b) { return diff; } // Collect B keys. for (bKey in b) { if (keys.indexOf(bKey) === -1) { keys.push(bKey); } } for (i = 0; i < keys.length; i++) { key = keys[i]; aVal = a[key]; bVal = b[key]; isComparingObjects = aVal && bVal && aVal.constructor === Object && bVal.constructor === Object; if ((isComparingObjects && !deepEqual(aVal, bVal)) || (!isComparingObjects && aVal !== bVal)) { diff[key] = bVal; } } return diff; }; })(); /** * Returns whether we should capture this keyboard event for keyboard shortcuts. * @param {Event} event Event object. * @returns {Boolean} Whether the key event should be captured. */ module.exports.shouldCaptureKeyEvent = function (event) { if (event.metaKey) { return false; } return document.activeElement === document.body;
/** * Splits a string into an array based on a delimiter. * * @param {string=} [str=''] Source string * @param {string=} [delimiter=' '] Delimiter to use * @returns {array} Array of delimited strings */ module.exports.splitString = function (str, delimiter) { if (typeof delimiter === 'undefined') { delimiter = ' '; } // First collapse the whitespace (or whatever the delimiter is). var regex = new RegExp(delimiter, 'g'); str = (str || '').replace(regex, delimiter); // Then split. return str.split(delimiter); }; /** * Extracts data from the element given an object that contains expected keys. * * @param {Element} Source element. * @param {Object} [defaults={}] Object of default key-value pairs. * @returns {Object} */ module.exports.getElData = function (el, defaults) { defaults = defaults || {}; var data = {}; Object.keys(defaults).forEach(copyAttribute); function copyAttribute (key) { if (el.hasAttribute(key)) { data[key] = el.getAttribute(key); } } return data; }; /** * Retrieves querystring value. * @param {String} name Name of querystring key. * @return {String} Value */ module.exports.getUrlParameter = function (name) { // eslint-disable-next-line no-useless-escape name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'); var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'); var results = regex.exec(location.search); return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' ')); }; /** * Detects whether context is within iframe. */ module.exports.isIframed = function () { return window.top !== window.self; }; /** * Finds all elements under the element that have the isScene * property set to true */ module.exports.findAllScenes = function (el) { var matchingElements = []; var allElements = el.getElementsByTagName('*'); for (var i = 0, n = allElements.length; i < n; i++) { if (allElements[i].isScene) { // Element exists with isScene set. matchingElements.push(allElements[i]); } } return matchingElements; }; // Must be at bottom to avoid circular dependency. module.exports.srcLoader = require('./src-loader'); /** * String split with cached result. */ module.exports.split = (function () { var splitCache = {}; return function (str, delimiter) { if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; } if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; } splitCache[delimiter][str] = str.split(delimiter); return splitCache[delimiter][str]; }; })();
};
random_line_split
time-scons.py
#!/usr/bin/env python # # time-scons.py: a wrapper script for running SCons timings # # This script exists to: # # 1) Wrap the invocation of runtest.py to run the actual TimeSCons # timings consistently. It does this specifically by building # SCons first, so .pyc compilation is not part of the timing. # # 2) Provide an interface for running TimeSCons timings against # earlier revisions, before the whole TimeSCons infrastructure # was "frozen" to provide consistent timings. This is done # by updating the specific pieces containing the TimeSCons # infrastructure to the earliest revision at which those pieces # were "stable enough." # # By encapsulating all the logic in this script, our Buildbot # infrastructure only needs to call this script, and we should be able # to change what we need to in this script and have it affect the build # automatically when the source code is updated, without having to # restart either master or slave. import optparse import os import shutil import subprocess import sys import tempfile import xml.sax.handler SubversionURL = 'http://scons.tigris.org/svn/scons' # This is the baseline revision when the TimeSCons scripts first # stabilized and collected "real," consistent timings. If we're timing # a revision prior to this, we'll forcibly update the TimeSCons pieces # of the tree to this revision to collect consistent timings for earlier # revisions. TimeSCons_revision = 4569 # The pieces of the TimeSCons infrastructure that are necessary to # produce consistent timings, even when the rest of the tree is from # an earlier revision that doesn't have these pieces. TimeSCons_pieces = ['QMTest', 'timings', 'runtest.py'] class CommandRunner(object): """ Executor class for commands, including "commands" implemented by Python functions. """ verbose = True active = True def __init__(self, dictionary={}): self.subst_dictionary(dictionary) def subst_dictionary(self, dictionary): self._subst_dictionary = dictionary def subst(self, string, dictionary=None): """ Substitutes (via the format operator) the values in the specified dictionary into the specified command. The command can be an (action, string) tuple. In all cases, we perform substitution on strings and don't worry if something isn't a string. (It's probably a Python function to be executed.) """ if dictionary is None: dictionary = self._subst_dictionary if dictionary: try: string = string % dictionary except TypeError: pass return string def display(self, command, stdout=None, stderr=None): if not self.verbose: return if isinstance(command, tuple): func = command[0] args = command[1:] s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args))) if isinstance(command, list): # TODO: quote arguments containing spaces # TODO: handle meta characters? s = ' '.join(command) else: s = self.subst(command) if not s.endswith('\n'): s += '\n' sys.stdout.write(s) sys.stdout.flush() def execute(self, command, stdout=None, stderr=None): """ Executes a single command. """ if not self.active: return 0 if isinstance(command, str): command = self.subst(command) cmdargs = shlex.split(command) if cmdargs[0] == 'cd': command = (os.chdir,) + tuple(cmdargs[1:]) if isinstance(command, tuple): func = command[0] args = command[1:] return func(*args) else: if stdout is sys.stdout: # Same as passing sys.stdout, except works with python2.4. subout = None elif stdout is None: # Open pipe for anything else so Popen works on python2.4. subout = subprocess.PIPE else: subout = stdout if stderr is sys.stderr: # Same as passing sys.stdout, except works with python2.4. suberr = None elif stderr is None: # Merge with stdout if stderr isn't specified. suberr = subprocess.STDOUT else: suberr = stderr p = subprocess.Popen(command, shell=(sys.platform == 'win32'), stdout=subout, stderr=suberr) p.wait() return p.returncode def run(self, command, display=None, stdout=None, stderr=None): """ Runs a single command, displaying it first. """ if display is None: display = command self.display(display) return self.execute(command, stdout, stderr) def run_list(self, command_list, **kw): """ Runs a list of commands, stopping with the first error.
""" status = 0 for command in command_list: s = self.run(command, **kw) if s and status == 0: status = s return 0 def get_svn_revisions(branch, revisions=None): """ Fetch the actual SVN revisions for the given branch querying "svn log." A string specifying a range of revisions can be supplied to restrict the output to a subset of the entire log. """ command = ['svn', 'log', '--xml'] if revisions: command.extend(['-r', revisions]) command.append(branch) p = subprocess.Popen(command, stdout=subprocess.PIPE) class SVNLogHandler(xml.sax.handler.ContentHandler): def __init__(self): self.revisions = [] def startElement(self, name, attributes): if name == 'logentry': self.revisions.append(int(attributes['revision'])) parser = xml.sax.make_parser() handler = SVNLogHandler() parser.setContentHandler(handler) parser.parse(p.stdout) return sorted(handler.revisions) def prepare_commands(): """ Returns a list of the commands to be executed to prepare the tree for testing. This involves building SCons, specifically the build/scons subdirectory where our packaging build is staged, and then running setup.py to create a local installed copy with compiled *.pyc files. The build directory gets removed first. """ commands = [] if os.path.exists('build'): commands.extend([ ['mv', 'build', 'build.OLD'], ['rm', '-rf', 'build.OLD'], ]) commands.append([sys.executable, 'bootstrap.py', 'build/scons']) commands.append([sys.executable, 'build/scons/setup.py', 'install', '--prefix=' + os.path.abspath('build/usr')]) return commands def script_command(script): """Returns the command to actually invoke the specified timing script using our "built" scons.""" return [sys.executable, 'runtest.py', '-x', 'build/usr/bin/scons', script] def do_revisions(cr, opts, branch, revisions, scripts): """ Time the SCons branch specified scripts through a list of revisions. We assume we're in a (temporary) directory in which we can check out the source for the specified revisions. """ stdout = sys.stdout stderr = sys.stderr status = 0 if opts.logsdir and not opts.no_exec and len(scripts) > 1: for script in scripts: subdir = os.path.basename(os.path.dirname(script)) logsubdir = os.path.join(opts.origin, opts.logsdir, subdir) if not os.path.exists(logsubdir): os.makedirs(logsubdir) for this_revision in revisions: if opts.logsdir and not opts.no_exec: log_name = '%s.log' % this_revision log_file = os.path.join(opts.origin, opts.logsdir, log_name) stdout = open(log_file, 'w') stderr = None commands = [ ['svn', 'co', '-q', '-r', str(this_revision), branch, '.'], ] if int(this_revision) < int(TimeSCons_revision): commands.append(['svn', 'up', '-q', '-r', str(TimeSCons_revision)] + TimeSCons_pieces) commands.extend(prepare_commands()) s = cr.run_list(commands, stdout=stdout, stderr=stderr) if s: if status == 0: status = s continue for script in scripts: if opts.logsdir and not opts.no_exec and len(scripts) > 1: subdir = os.path.basename(os.path.dirname(script)) lf = os.path.join(opts.origin, opts.logsdir, subdir, log_name) out = open(lf, 'w') err = None close_out = True else: out = stdout err = stderr close_out = False s = cr.run(script_command(script), stdout=out, stderr=err) if s and status == 0: status = s if close_out: out.close() out = None if int(this_revision) < int(TimeSCons_revision): # "Revert" the pieces that we previously updated to the # TimeSCons_revision, so the update to the next revision # works cleanly. command = (['svn', 'up', '-q', '-r', str(this_revision)] + TimeSCons_pieces) s = cr.run(command, stdout=stdout, stderr=stderr) if s: if status == 0: status = s continue if stdout not in (sys.stdout, None): stdout.close() stdout = None return status Usage = """\ time-scons.py [-hnq] [-r REVISION ...] [--branch BRANCH] [--logsdir DIR] [--svn] SCRIPT ...""" def main(argv=None): if argv is None: argv = sys.argv parser = optparse.OptionParser(usage=Usage) parser.add_option("--branch", metavar="BRANCH", default="trunk", help="time revision on BRANCH") parser.add_option("--logsdir", metavar="DIR", default='.', help="generate separate log files for each revision") parser.add_option("-n", "--no-exec", action="store_true", help="no execute, just print the command line") parser.add_option("-q", "--quiet", action="store_true", help="quiet, don't print the command line") parser.add_option("-r", "--revision", metavar="REVISION", help="time specified revisions") parser.add_option("--svn", action="store_true", help="fetch actual revisions for BRANCH") opts, scripts = parser.parse_args(argv[1:]) if not scripts: sys.stderr.write('No scripts specified.\n') sys.exit(1) CommandRunner.verbose = not opts.quiet CommandRunner.active = not opts.no_exec cr = CommandRunner() os.environ['TESTSCONS_SCONSFLAGS'] = '' branch = SubversionURL + '/' + opts.branch if opts.svn: revisions = get_svn_revisions(branch, opts.revision) elif opts.revision: # TODO(sgk): parse this for SVN-style revision strings revisions = [opts.revision] else: revisions = None if opts.logsdir and not os.path.exists(opts.logsdir): os.makedirs(opts.logsdir) if revisions: opts.origin = os.getcwd() tempdir = tempfile.mkdtemp(prefix='time-scons-') try: os.chdir(tempdir) status = do_revisions(cr, opts, branch, revisions, scripts) finally: os.chdir(opts.origin) shutil.rmtree(tempdir) else: commands = prepare_commands() commands.extend([ script_command(script) for script in scripts ]) status = cr.run_list(commands, stdout=sys.stdout, stderr=sys.stderr) return status if __name__ == "__main__": sys.exit(main())
Returns the exit status of the first failed command, or 0 on success.
random_line_split
time-scons.py
#!/usr/bin/env python # # time-scons.py: a wrapper script for running SCons timings # # This script exists to: # # 1) Wrap the invocation of runtest.py to run the actual TimeSCons # timings consistently. It does this specifically by building # SCons first, so .pyc compilation is not part of the timing. # # 2) Provide an interface for running TimeSCons timings against # earlier revisions, before the whole TimeSCons infrastructure # was "frozen" to provide consistent timings. This is done # by updating the specific pieces containing the TimeSCons # infrastructure to the earliest revision at which those pieces # were "stable enough." # # By encapsulating all the logic in this script, our Buildbot # infrastructure only needs to call this script, and we should be able # to change what we need to in this script and have it affect the build # automatically when the source code is updated, without having to # restart either master or slave. import optparse import os import shutil import subprocess import sys import tempfile import xml.sax.handler SubversionURL = 'http://scons.tigris.org/svn/scons' # This is the baseline revision when the TimeSCons scripts first # stabilized and collected "real," consistent timings. If we're timing # a revision prior to this, we'll forcibly update the TimeSCons pieces # of the tree to this revision to collect consistent timings for earlier # revisions. TimeSCons_revision = 4569 # The pieces of the TimeSCons infrastructure that are necessary to # produce consistent timings, even when the rest of the tree is from # an earlier revision that doesn't have these pieces. TimeSCons_pieces = ['QMTest', 'timings', 'runtest.py'] class CommandRunner(object): """ Executor class for commands, including "commands" implemented by Python functions. """ verbose = True active = True def
(self, dictionary={}): self.subst_dictionary(dictionary) def subst_dictionary(self, dictionary): self._subst_dictionary = dictionary def subst(self, string, dictionary=None): """ Substitutes (via the format operator) the values in the specified dictionary into the specified command. The command can be an (action, string) tuple. In all cases, we perform substitution on strings and don't worry if something isn't a string. (It's probably a Python function to be executed.) """ if dictionary is None: dictionary = self._subst_dictionary if dictionary: try: string = string % dictionary except TypeError: pass return string def display(self, command, stdout=None, stderr=None): if not self.verbose: return if isinstance(command, tuple): func = command[0] args = command[1:] s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args))) if isinstance(command, list): # TODO: quote arguments containing spaces # TODO: handle meta characters? s = ' '.join(command) else: s = self.subst(command) if not s.endswith('\n'): s += '\n' sys.stdout.write(s) sys.stdout.flush() def execute(self, command, stdout=None, stderr=None): """ Executes a single command. """ if not self.active: return 0 if isinstance(command, str): command = self.subst(command) cmdargs = shlex.split(command) if cmdargs[0] == 'cd': command = (os.chdir,) + tuple(cmdargs[1:]) if isinstance(command, tuple): func = command[0] args = command[1:] return func(*args) else: if stdout is sys.stdout: # Same as passing sys.stdout, except works with python2.4. subout = None elif stdout is None: # Open pipe for anything else so Popen works on python2.4. subout = subprocess.PIPE else: subout = stdout if stderr is sys.stderr: # Same as passing sys.stdout, except works with python2.4. suberr = None elif stderr is None: # Merge with stdout if stderr isn't specified. suberr = subprocess.STDOUT else: suberr = stderr p = subprocess.Popen(command, shell=(sys.platform == 'win32'), stdout=subout, stderr=suberr) p.wait() return p.returncode def run(self, command, display=None, stdout=None, stderr=None): """ Runs a single command, displaying it first. """ if display is None: display = command self.display(display) return self.execute(command, stdout, stderr) def run_list(self, command_list, **kw): """ Runs a list of commands, stopping with the first error. Returns the exit status of the first failed command, or 0 on success. """ status = 0 for command in command_list: s = self.run(command, **kw) if s and status == 0: status = s return 0 def get_svn_revisions(branch, revisions=None): """ Fetch the actual SVN revisions for the given branch querying "svn log." A string specifying a range of revisions can be supplied to restrict the output to a subset of the entire log. """ command = ['svn', 'log', '--xml'] if revisions: command.extend(['-r', revisions]) command.append(branch) p = subprocess.Popen(command, stdout=subprocess.PIPE) class SVNLogHandler(xml.sax.handler.ContentHandler): def __init__(self): self.revisions = [] def startElement(self, name, attributes): if name == 'logentry': self.revisions.append(int(attributes['revision'])) parser = xml.sax.make_parser() handler = SVNLogHandler() parser.setContentHandler(handler) parser.parse(p.stdout) return sorted(handler.revisions) def prepare_commands(): """ Returns a list of the commands to be executed to prepare the tree for testing. This involves building SCons, specifically the build/scons subdirectory where our packaging build is staged, and then running setup.py to create a local installed copy with compiled *.pyc files. The build directory gets removed first. """ commands = [] if os.path.exists('build'): commands.extend([ ['mv', 'build', 'build.OLD'], ['rm', '-rf', 'build.OLD'], ]) commands.append([sys.executable, 'bootstrap.py', 'build/scons']) commands.append([sys.executable, 'build/scons/setup.py', 'install', '--prefix=' + os.path.abspath('build/usr')]) return commands def script_command(script): """Returns the command to actually invoke the specified timing script using our "built" scons.""" return [sys.executable, 'runtest.py', '-x', 'build/usr/bin/scons', script] def do_revisions(cr, opts, branch, revisions, scripts): """ Time the SCons branch specified scripts through a list of revisions. We assume we're in a (temporary) directory in which we can check out the source for the specified revisions. """ stdout = sys.stdout stderr = sys.stderr status = 0 if opts.logsdir and not opts.no_exec and len(scripts) > 1: for script in scripts: subdir = os.path.basename(os.path.dirname(script)) logsubdir = os.path.join(opts.origin, opts.logsdir, subdir) if not os.path.exists(logsubdir): os.makedirs(logsubdir) for this_revision in revisions: if opts.logsdir and not opts.no_exec: log_name = '%s.log' % this_revision log_file = os.path.join(opts.origin, opts.logsdir, log_name) stdout = open(log_file, 'w') stderr = None commands = [ ['svn', 'co', '-q', '-r', str(this_revision), branch, '.'], ] if int(this_revision) < int(TimeSCons_revision): commands.append(['svn', 'up', '-q', '-r', str(TimeSCons_revision)] + TimeSCons_pieces) commands.extend(prepare_commands()) s = cr.run_list(commands, stdout=stdout, stderr=stderr) if s: if status == 0: status = s continue for script in scripts: if opts.logsdir and not opts.no_exec and len(scripts) > 1: subdir = os.path.basename(os.path.dirname(script)) lf = os.path.join(opts.origin, opts.logsdir, subdir, log_name) out = open(lf, 'w') err = None close_out = True else: out = stdout err = stderr close_out = False s = cr.run(script_command(script), stdout=out, stderr=err) if s and status == 0: status = s if close_out: out.close() out = None if int(this_revision) < int(TimeSCons_revision): # "Revert" the pieces that we previously updated to the # TimeSCons_revision, so the update to the next revision # works cleanly. command = (['svn', 'up', '-q', '-r', str(this_revision)] + TimeSCons_pieces) s = cr.run(command, stdout=stdout, stderr=stderr) if s: if status == 0: status = s continue if stdout not in (sys.stdout, None): stdout.close() stdout = None return status Usage = """\ time-scons.py [-hnq] [-r REVISION ...] [--branch BRANCH] [--logsdir DIR] [--svn] SCRIPT ...""" def main(argv=None): if argv is None: argv = sys.argv parser = optparse.OptionParser(usage=Usage) parser.add_option("--branch", metavar="BRANCH", default="trunk", help="time revision on BRANCH") parser.add_option("--logsdir", metavar="DIR", default='.', help="generate separate log files for each revision") parser.add_option("-n", "--no-exec", action="store_true", help="no execute, just print the command line") parser.add_option("-q", "--quiet", action="store_true", help="quiet, don't print the command line") parser.add_option("-r", "--revision", metavar="REVISION", help="time specified revisions") parser.add_option("--svn", action="store_true", help="fetch actual revisions for BRANCH") opts, scripts = parser.parse_args(argv[1:]) if not scripts: sys.stderr.write('No scripts specified.\n') sys.exit(1) CommandRunner.verbose = not opts.quiet CommandRunner.active = not opts.no_exec cr = CommandRunner() os.environ['TESTSCONS_SCONSFLAGS'] = '' branch = SubversionURL + '/' + opts.branch if opts.svn: revisions = get_svn_revisions(branch, opts.revision) elif opts.revision: # TODO(sgk): parse this for SVN-style revision strings revisions = [opts.revision] else: revisions = None if opts.logsdir and not os.path.exists(opts.logsdir): os.makedirs(opts.logsdir) if revisions: opts.origin = os.getcwd() tempdir = tempfile.mkdtemp(prefix='time-scons-') try: os.chdir(tempdir) status = do_revisions(cr, opts, branch, revisions, scripts) finally: os.chdir(opts.origin) shutil.rmtree(tempdir) else: commands = prepare_commands() commands.extend([ script_command(script) for script in scripts ]) status = cr.run_list(commands, stdout=sys.stdout, stderr=sys.stderr) return status if __name__ == "__main__": sys.exit(main())
__init__
identifier_name
time-scons.py
#!/usr/bin/env python # # time-scons.py: a wrapper script for running SCons timings # # This script exists to: # # 1) Wrap the invocation of runtest.py to run the actual TimeSCons # timings consistently. It does this specifically by building # SCons first, so .pyc compilation is not part of the timing. # # 2) Provide an interface for running TimeSCons timings against # earlier revisions, before the whole TimeSCons infrastructure # was "frozen" to provide consistent timings. This is done # by updating the specific pieces containing the TimeSCons # infrastructure to the earliest revision at which those pieces # were "stable enough." # # By encapsulating all the logic in this script, our Buildbot # infrastructure only needs to call this script, and we should be able # to change what we need to in this script and have it affect the build # automatically when the source code is updated, without having to # restart either master or slave. import optparse import os import shutil import subprocess import sys import tempfile import xml.sax.handler SubversionURL = 'http://scons.tigris.org/svn/scons' # This is the baseline revision when the TimeSCons scripts first # stabilized and collected "real," consistent timings. If we're timing # a revision prior to this, we'll forcibly update the TimeSCons pieces # of the tree to this revision to collect consistent timings for earlier # revisions. TimeSCons_revision = 4569 # The pieces of the TimeSCons infrastructure that are necessary to # produce consistent timings, even when the rest of the tree is from # an earlier revision that doesn't have these pieces. TimeSCons_pieces = ['QMTest', 'timings', 'runtest.py'] class CommandRunner(object): """ Executor class for commands, including "commands" implemented by Python functions. """ verbose = True active = True def __init__(self, dictionary={}): self.subst_dictionary(dictionary) def subst_dictionary(self, dictionary): self._subst_dictionary = dictionary def subst(self, string, dictionary=None): """ Substitutes (via the format operator) the values in the specified dictionary into the specified command. The command can be an (action, string) tuple. In all cases, we perform substitution on strings and don't worry if something isn't a string. (It's probably a Python function to be executed.) """ if dictionary is None: dictionary = self._subst_dictionary if dictionary: try: string = string % dictionary except TypeError: pass return string def display(self, command, stdout=None, stderr=None): if not self.verbose: return if isinstance(command, tuple): func = command[0] args = command[1:] s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args))) if isinstance(command, list): # TODO: quote arguments containing spaces # TODO: handle meta characters? s = ' '.join(command) else: s = self.subst(command) if not s.endswith('\n'): s += '\n' sys.stdout.write(s) sys.stdout.flush() def execute(self, command, stdout=None, stderr=None): """ Executes a single command. """ if not self.active: return 0 if isinstance(command, str): command = self.subst(command) cmdargs = shlex.split(command) if cmdargs[0] == 'cd': command = (os.chdir,) + tuple(cmdargs[1:]) if isinstance(command, tuple): func = command[0] args = command[1:] return func(*args) else: if stdout is sys.stdout: # Same as passing sys.stdout, except works with python2.4. subout = None elif stdout is None: # Open pipe for anything else so Popen works on python2.4. subout = subprocess.PIPE else: subout = stdout if stderr is sys.stderr: # Same as passing sys.stdout, except works with python2.4. suberr = None elif stderr is None: # Merge with stdout if stderr isn't specified. suberr = subprocess.STDOUT else: suberr = stderr p = subprocess.Popen(command, shell=(sys.platform == 'win32'), stdout=subout, stderr=suberr) p.wait() return p.returncode def run(self, command, display=None, stdout=None, stderr=None): """ Runs a single command, displaying it first. """ if display is None: display = command self.display(display) return self.execute(command, stdout, stderr) def run_list(self, command_list, **kw): """ Runs a list of commands, stopping with the first error. Returns the exit status of the first failed command, or 0 on success. """ status = 0 for command in command_list: s = self.run(command, **kw) if s and status == 0: status = s return 0 def get_svn_revisions(branch, revisions=None): """ Fetch the actual SVN revisions for the given branch querying "svn log." A string specifying a range of revisions can be supplied to restrict the output to a subset of the entire log. """ command = ['svn', 'log', '--xml'] if revisions:
command.append(branch) p = subprocess.Popen(command, stdout=subprocess.PIPE) class SVNLogHandler(xml.sax.handler.ContentHandler): def __init__(self): self.revisions = [] def startElement(self, name, attributes): if name == 'logentry': self.revisions.append(int(attributes['revision'])) parser = xml.sax.make_parser() handler = SVNLogHandler() parser.setContentHandler(handler) parser.parse(p.stdout) return sorted(handler.revisions) def prepare_commands(): """ Returns a list of the commands to be executed to prepare the tree for testing. This involves building SCons, specifically the build/scons subdirectory where our packaging build is staged, and then running setup.py to create a local installed copy with compiled *.pyc files. The build directory gets removed first. """ commands = [] if os.path.exists('build'): commands.extend([ ['mv', 'build', 'build.OLD'], ['rm', '-rf', 'build.OLD'], ]) commands.append([sys.executable, 'bootstrap.py', 'build/scons']) commands.append([sys.executable, 'build/scons/setup.py', 'install', '--prefix=' + os.path.abspath('build/usr')]) return commands def script_command(script): """Returns the command to actually invoke the specified timing script using our "built" scons.""" return [sys.executable, 'runtest.py', '-x', 'build/usr/bin/scons', script] def do_revisions(cr, opts, branch, revisions, scripts): """ Time the SCons branch specified scripts through a list of revisions. We assume we're in a (temporary) directory in which we can check out the source for the specified revisions. """ stdout = sys.stdout stderr = sys.stderr status = 0 if opts.logsdir and not opts.no_exec and len(scripts) > 1: for script in scripts: subdir = os.path.basename(os.path.dirname(script)) logsubdir = os.path.join(opts.origin, opts.logsdir, subdir) if not os.path.exists(logsubdir): os.makedirs(logsubdir) for this_revision in revisions: if opts.logsdir and not opts.no_exec: log_name = '%s.log' % this_revision log_file = os.path.join(opts.origin, opts.logsdir, log_name) stdout = open(log_file, 'w') stderr = None commands = [ ['svn', 'co', '-q', '-r', str(this_revision), branch, '.'], ] if int(this_revision) < int(TimeSCons_revision): commands.append(['svn', 'up', '-q', '-r', str(TimeSCons_revision)] + TimeSCons_pieces) commands.extend(prepare_commands()) s = cr.run_list(commands, stdout=stdout, stderr=stderr) if s: if status == 0: status = s continue for script in scripts: if opts.logsdir and not opts.no_exec and len(scripts) > 1: subdir = os.path.basename(os.path.dirname(script)) lf = os.path.join(opts.origin, opts.logsdir, subdir, log_name) out = open(lf, 'w') err = None close_out = True else: out = stdout err = stderr close_out = False s = cr.run(script_command(script), stdout=out, stderr=err) if s and status == 0: status = s if close_out: out.close() out = None if int(this_revision) < int(TimeSCons_revision): # "Revert" the pieces that we previously updated to the # TimeSCons_revision, so the update to the next revision # works cleanly. command = (['svn', 'up', '-q', '-r', str(this_revision)] + TimeSCons_pieces) s = cr.run(command, stdout=stdout, stderr=stderr) if s: if status == 0: status = s continue if stdout not in (sys.stdout, None): stdout.close() stdout = None return status Usage = """\ time-scons.py [-hnq] [-r REVISION ...] [--branch BRANCH] [--logsdir DIR] [--svn] SCRIPT ...""" def main(argv=None): if argv is None: argv = sys.argv parser = optparse.OptionParser(usage=Usage) parser.add_option("--branch", metavar="BRANCH", default="trunk", help="time revision on BRANCH") parser.add_option("--logsdir", metavar="DIR", default='.', help="generate separate log files for each revision") parser.add_option("-n", "--no-exec", action="store_true", help="no execute, just print the command line") parser.add_option("-q", "--quiet", action="store_true", help="quiet, don't print the command line") parser.add_option("-r", "--revision", metavar="REVISION", help="time specified revisions") parser.add_option("--svn", action="store_true", help="fetch actual revisions for BRANCH") opts, scripts = parser.parse_args(argv[1:]) if not scripts: sys.stderr.write('No scripts specified.\n') sys.exit(1) CommandRunner.verbose = not opts.quiet CommandRunner.active = not opts.no_exec cr = CommandRunner() os.environ['TESTSCONS_SCONSFLAGS'] = '' branch = SubversionURL + '/' + opts.branch if opts.svn: revisions = get_svn_revisions(branch, opts.revision) elif opts.revision: # TODO(sgk): parse this for SVN-style revision strings revisions = [opts.revision] else: revisions = None if opts.logsdir and not os.path.exists(opts.logsdir): os.makedirs(opts.logsdir) if revisions: opts.origin = os.getcwd() tempdir = tempfile.mkdtemp(prefix='time-scons-') try: os.chdir(tempdir) status = do_revisions(cr, opts, branch, revisions, scripts) finally: os.chdir(opts.origin) shutil.rmtree(tempdir) else: commands = prepare_commands() commands.extend([ script_command(script) for script in scripts ]) status = cr.run_list(commands, stdout=sys.stdout, stderr=sys.stderr) return status if __name__ == "__main__": sys.exit(main())
command.extend(['-r', revisions])
conditional_block
time-scons.py
#!/usr/bin/env python # # time-scons.py: a wrapper script for running SCons timings # # This script exists to: # # 1) Wrap the invocation of runtest.py to run the actual TimeSCons # timings consistently. It does this specifically by building # SCons first, so .pyc compilation is not part of the timing. # # 2) Provide an interface for running TimeSCons timings against # earlier revisions, before the whole TimeSCons infrastructure # was "frozen" to provide consistent timings. This is done # by updating the specific pieces containing the TimeSCons # infrastructure to the earliest revision at which those pieces # were "stable enough." # # By encapsulating all the logic in this script, our Buildbot # infrastructure only needs to call this script, and we should be able # to change what we need to in this script and have it affect the build # automatically when the source code is updated, without having to # restart either master or slave. import optparse import os import shutil import subprocess import sys import tempfile import xml.sax.handler SubversionURL = 'http://scons.tigris.org/svn/scons' # This is the baseline revision when the TimeSCons scripts first # stabilized and collected "real," consistent timings. If we're timing # a revision prior to this, we'll forcibly update the TimeSCons pieces # of the tree to this revision to collect consistent timings for earlier # revisions. TimeSCons_revision = 4569 # The pieces of the TimeSCons infrastructure that are necessary to # produce consistent timings, even when the rest of the tree is from # an earlier revision that doesn't have these pieces. TimeSCons_pieces = ['QMTest', 'timings', 'runtest.py'] class CommandRunner(object): """ Executor class for commands, including "commands" implemented by Python functions. """ verbose = True active = True def __init__(self, dictionary={}): self.subst_dictionary(dictionary) def subst_dictionary(self, dictionary): self._subst_dictionary = dictionary def subst(self, string, dictionary=None): """ Substitutes (via the format operator) the values in the specified dictionary into the specified command. The command can be an (action, string) tuple. In all cases, we perform substitution on strings and don't worry if something isn't a string. (It's probably a Python function to be executed.) """ if dictionary is None: dictionary = self._subst_dictionary if dictionary: try: string = string % dictionary except TypeError: pass return string def display(self, command, stdout=None, stderr=None): if not self.verbose: return if isinstance(command, tuple): func = command[0] args = command[1:] s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args))) if isinstance(command, list): # TODO: quote arguments containing spaces # TODO: handle meta characters? s = ' '.join(command) else: s = self.subst(command) if not s.endswith('\n'): s += '\n' sys.stdout.write(s) sys.stdout.flush() def execute(self, command, stdout=None, stderr=None): """ Executes a single command. """ if not self.active: return 0 if isinstance(command, str): command = self.subst(command) cmdargs = shlex.split(command) if cmdargs[0] == 'cd': command = (os.chdir,) + tuple(cmdargs[1:]) if isinstance(command, tuple): func = command[0] args = command[1:] return func(*args) else: if stdout is sys.stdout: # Same as passing sys.stdout, except works with python2.4. subout = None elif stdout is None: # Open pipe for anything else so Popen works on python2.4. subout = subprocess.PIPE else: subout = stdout if stderr is sys.stderr: # Same as passing sys.stdout, except works with python2.4. suberr = None elif stderr is None: # Merge with stdout if stderr isn't specified. suberr = subprocess.STDOUT else: suberr = stderr p = subprocess.Popen(command, shell=(sys.platform == 'win32'), stdout=subout, stderr=suberr) p.wait() return p.returncode def run(self, command, display=None, stdout=None, stderr=None): """ Runs a single command, displaying it first. """ if display is None: display = command self.display(display) return self.execute(command, stdout, stderr) def run_list(self, command_list, **kw): """ Runs a list of commands, stopping with the first error. Returns the exit status of the first failed command, or 0 on success. """ status = 0 for command in command_list: s = self.run(command, **kw) if s and status == 0: status = s return 0 def get_svn_revisions(branch, revisions=None): """ Fetch the actual SVN revisions for the given branch querying "svn log." A string specifying a range of revisions can be supplied to restrict the output to a subset of the entire log. """ command = ['svn', 'log', '--xml'] if revisions: command.extend(['-r', revisions]) command.append(branch) p = subprocess.Popen(command, stdout=subprocess.PIPE) class SVNLogHandler(xml.sax.handler.ContentHandler): def __init__(self): self.revisions = [] def startElement(self, name, attributes): if name == 'logentry': self.revisions.append(int(attributes['revision'])) parser = xml.sax.make_parser() handler = SVNLogHandler() parser.setContentHandler(handler) parser.parse(p.stdout) return sorted(handler.revisions) def prepare_commands(): """ Returns a list of the commands to be executed to prepare the tree for testing. This involves building SCons, specifically the build/scons subdirectory where our packaging build is staged, and then running setup.py to create a local installed copy with compiled *.pyc files. The build directory gets removed first. """ commands = [] if os.path.exists('build'): commands.extend([ ['mv', 'build', 'build.OLD'], ['rm', '-rf', 'build.OLD'], ]) commands.append([sys.executable, 'bootstrap.py', 'build/scons']) commands.append([sys.executable, 'build/scons/setup.py', 'install', '--prefix=' + os.path.abspath('build/usr')]) return commands def script_command(script): """Returns the command to actually invoke the specified timing script using our "built" scons.""" return [sys.executable, 'runtest.py', '-x', 'build/usr/bin/scons', script] def do_revisions(cr, opts, branch, revisions, scripts): """ Time the SCons branch specified scripts through a list of revisions. We assume we're in a (temporary) directory in which we can check out the source for the specified revisions. """ stdout = sys.stdout stderr = sys.stderr status = 0 if opts.logsdir and not opts.no_exec and len(scripts) > 1: for script in scripts: subdir = os.path.basename(os.path.dirname(script)) logsubdir = os.path.join(opts.origin, opts.logsdir, subdir) if not os.path.exists(logsubdir): os.makedirs(logsubdir) for this_revision in revisions: if opts.logsdir and not opts.no_exec: log_name = '%s.log' % this_revision log_file = os.path.join(opts.origin, opts.logsdir, log_name) stdout = open(log_file, 'w') stderr = None commands = [ ['svn', 'co', '-q', '-r', str(this_revision), branch, '.'], ] if int(this_revision) < int(TimeSCons_revision): commands.append(['svn', 'up', '-q', '-r', str(TimeSCons_revision)] + TimeSCons_pieces) commands.extend(prepare_commands()) s = cr.run_list(commands, stdout=stdout, stderr=stderr) if s: if status == 0: status = s continue for script in scripts: if opts.logsdir and not opts.no_exec and len(scripts) > 1: subdir = os.path.basename(os.path.dirname(script)) lf = os.path.join(opts.origin, opts.logsdir, subdir, log_name) out = open(lf, 'w') err = None close_out = True else: out = stdout err = stderr close_out = False s = cr.run(script_command(script), stdout=out, stderr=err) if s and status == 0: status = s if close_out: out.close() out = None if int(this_revision) < int(TimeSCons_revision): # "Revert" the pieces that we previously updated to the # TimeSCons_revision, so the update to the next revision # works cleanly. command = (['svn', 'up', '-q', '-r', str(this_revision)] + TimeSCons_pieces) s = cr.run(command, stdout=stdout, stderr=stderr) if s: if status == 0: status = s continue if stdout not in (sys.stdout, None): stdout.close() stdout = None return status Usage = """\ time-scons.py [-hnq] [-r REVISION ...] [--branch BRANCH] [--logsdir DIR] [--svn] SCRIPT ...""" def main(argv=None):
if __name__ == "__main__": sys.exit(main())
if argv is None: argv = sys.argv parser = optparse.OptionParser(usage=Usage) parser.add_option("--branch", metavar="BRANCH", default="trunk", help="time revision on BRANCH") parser.add_option("--logsdir", metavar="DIR", default='.', help="generate separate log files for each revision") parser.add_option("-n", "--no-exec", action="store_true", help="no execute, just print the command line") parser.add_option("-q", "--quiet", action="store_true", help="quiet, don't print the command line") parser.add_option("-r", "--revision", metavar="REVISION", help="time specified revisions") parser.add_option("--svn", action="store_true", help="fetch actual revisions for BRANCH") opts, scripts = parser.parse_args(argv[1:]) if not scripts: sys.stderr.write('No scripts specified.\n') sys.exit(1) CommandRunner.verbose = not opts.quiet CommandRunner.active = not opts.no_exec cr = CommandRunner() os.environ['TESTSCONS_SCONSFLAGS'] = '' branch = SubversionURL + '/' + opts.branch if opts.svn: revisions = get_svn_revisions(branch, opts.revision) elif opts.revision: # TODO(sgk): parse this for SVN-style revision strings revisions = [opts.revision] else: revisions = None if opts.logsdir and not os.path.exists(opts.logsdir): os.makedirs(opts.logsdir) if revisions: opts.origin = os.getcwd() tempdir = tempfile.mkdtemp(prefix='time-scons-') try: os.chdir(tempdir) status = do_revisions(cr, opts, branch, revisions, scripts) finally: os.chdir(opts.origin) shutil.rmtree(tempdir) else: commands = prepare_commands() commands.extend([ script_command(script) for script in scripts ]) status = cr.run_list(commands, stdout=sys.stdout, stderr=sys.stderr) return status
identifier_body
float_context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use geom::point::Point2D; use geom::size::Size2D; use geom::rect::Rect; use gfx::geometry::{Au, max, min}; use std::util::replace; use std::vec; use std::i32::max_value; #[deriving(Clone)] pub enum FloatType{ FloatLeft, FloatRight } pub enum ClearType { ClearLeft, ClearRight, ClearBoth } struct FloatContextBase{ float_data: ~[Option<FloatData>], floats_used: uint, max_y : Au, offset: Point2D<Au> } #[deriving(Clone)] struct FloatData{ bounds: Rect<Au>, f_type: FloatType } /// All information necessary to place a float pub struct PlacementInfo{ width: Au, // The dimensions of the float height: Au, ceiling: Au, // The minimum top of the float, as determined by earlier elements max_width: Au, // The maximum right of the float, generally determined by the contining block f_type: FloatType // left or right } /// Wrappers around float methods. To avoid allocating data we'll never use, /// destroy the context on modification. pub enum FloatContext { Invalid, Valid(~FloatContextBase) } impl FloatContext { pub fn new(num_floats: uint) -> FloatContext { Valid(~FloatContextBase::new(num_floats)) } #[inline(always)] pub fn clone(&mut self) -> FloatContext { match *self { Invalid => fail!("Can't clone an invalid float context"), Valid(_) => replace(self, Invalid) } } #[inline(always)] fn with_mut_base<R>(&mut self, callback: &fn(&mut FloatContextBase) -> R) -> R { match *self { Invalid => fail!("Float context no longer available"), Valid(ref mut base) => callback(&mut **base) } } #[inline(always)] pub fn with_base<R>(&self, callback: &fn(&FloatContextBase) -> R) -> R { match *self { Invalid => fail!("Float context no longer available"), Valid(ref base) => callback(& **base) } } #[inline(always)] pub fn translate(&mut self, trans: Point2D<Au>) -> FloatContext { do self.with_mut_base |base| { base.translate(trans); } replace(self, Invalid) } #[inline(always)] pub fn available_rect(&mut self, top: Au, height: Au, max_x: Au) -> Option<Rect<Au>> { do self.with_base |base| { base.available_rect(top, height, max_x) } } #[inline(always)] pub fn add_float(&mut self, info: &PlacementInfo) -> FloatContext{ do self.with_mut_base |base| { base.add_float(info); } replace(self, Invalid) } #[inline(always)] pub fn place_between_floats(&self, info: &PlacementInfo) -> Rect<Au>
#[inline(always)] pub fn last_float_pos(&mut self) -> Point2D<Au> { do self.with_base |base| { base.last_float_pos() } } #[inline(always)] pub fn clearance(&self, clear: ClearType) -> Au { do self.with_base |base| { base.clearance(clear) } } } impl FloatContextBase{ fn new(num_floats: uint) -> FloatContextBase { debug!("Creating float context of size %?", num_floats); let new_data = vec::from_elem(num_floats, None); FloatContextBase { float_data: new_data, floats_used: 0, max_y: Au(0), offset: Point2D(Au(0), Au(0)) } } fn translate(&mut self, trans: Point2D<Au>) { self.offset = self.offset + trans; } fn last_float_pos(&self) -> Point2D<Au> { assert!(self.floats_used > 0, "Error: tried to access FloatContext with no floats in it"); match self.float_data[self.floats_used - 1] { None => fail!("FloatContext error: floats should never be None here"), Some(float) => { debug!("Returning float position: %?", float.bounds.origin + self.offset); float.bounds.origin + self.offset } } } /// Returns a rectangle that encloses the region from top to top + height, /// with width small enough that it doesn't collide with any floats. max_x /// is the x-coordinate beyond which floats have no effect (generally /// this is the containing block width). fn available_rect(&self, top: Au, height: Au, max_x: Au) -> Option<Rect<Au>> { fn range_intersect(top_1: Au, bottom_1: Au, top_2: Au, bottom_2: Au) -> (Au, Au) { (max(top_1, top_2), min(bottom_1, bottom_2)) } let top = top - self.offset.y; debug!("available_rect: trying to find space at %?", top); // Relevant dimensions for the right-most left float let mut max_left = Au(0) - self.offset.x; let mut l_top = None; let mut l_bottom = None; // Relevant dimensions for the left-most right float let mut min_right = max_x - self.offset.x; let mut r_top = None; let mut r_bottom = None; // Find the float collisions for the given vertical range. for float in self.float_data.iter() { debug!("available_rect: Checking for collision against float"); match *float{ None => (), Some(data) => { let float_pos = data.bounds.origin; let float_size = data.bounds.size; debug!("float_pos: %?, float_size: %?", float_pos, float_size); match data.f_type { FloatLeft => { if(float_pos.x + float_size.width > max_left && float_pos.y + float_size.height > top && float_pos.y < top + height) { max_left = float_pos.x + float_size.width; l_top = Some(float_pos.y); l_bottom = Some(float_pos.y + float_size.height); debug!("available_rect: collision with left float: new max_left is %?", max_left); } } FloatRight => { if(float_pos.x < min_right && float_pos.y + float_size.height > top && float_pos.y < top + height) { min_right = float_pos.x; r_top = Some(float_pos.y); r_bottom = Some(float_pos.y + float_size.height); debug!("available_rect: collision with right float: new min_right is %?", min_right); } } } } }; } // Extend the vertical range of the rectangle to the closest floats. // If there are floats on both sides, take the intersection of the // two areas. Also make sure we never return a top smaller than the // given upper bound. let (top, bottom) = match (r_top, r_bottom, l_top, l_bottom) { (Some(r_top), Some(r_bottom), Some(l_top), Some(l_bottom)) => range_intersect(max(top, r_top), r_bottom, max(top, l_top), l_bottom), (None, None, Some(l_top), Some(l_bottom)) => (max(top, l_top), l_bottom), (Some(r_top), Some(r_bottom), None, None) => (max(top, r_top), r_bottom), (None, None, None, None) => return None, _ => fail!("Reached unreachable state when computing float area") }; // This assertion is too strong and fails in some cases. It is OK to // return negative widths since we check against that right away, but // we should still undersrtand why they occur and add a stronger // assertion here. //assert!(max_left < min_right); assert!(top <= bottom, "Float position error"); Some(Rect{ origin: Point2D(max_left, top) + self.offset, size: Size2D(min_right - max_left, bottom - top) }) } fn add_float(&mut self, info: &PlacementInfo) { debug!("Floats_used: %?, Floats available: %?", self.floats_used, self.float_data.len()); assert!(self.floats_used < self.float_data.len() && self.float_data[self.floats_used].is_none()); let new_info = PlacementInfo { width: info.width, height: info.height, ceiling: max(info.ceiling, self.max_y + self.offset.y), max_width: info.max_width, f_type: info.f_type }; debug!("add_float: added float with info %?", new_info); let new_float = FloatData { bounds: Rect { origin: self.place_between_floats(&new_info).origin - self.offset, size: Size2D(info.width, info.height) }, f_type: info.f_type }; self.float_data[self.floats_used] = Some(new_float); self.max_y = max(self.max_y, new_float.bounds.origin.y); self.floats_used += 1; } /// Returns true if the given rect overlaps with any floats. fn collides_with_float(&self, bounds: &Rect<Au>) -> bool { for float in self.float_data.iter() { match *float{ None => (), Some(data) => { if data.bounds.translate(&self.offset).intersects(bounds) { return true; } } }; } return false; } /// Given the top 3 sides of the rectange, finds the largest height that /// will result in the rectange not colliding with any floats. Returns /// None if that height is infinite. fn max_height_for_bounds(&self, left: Au, top: Au, width: Au) -> Option<Au> { let top = top - self.offset.y; let left = left - self.offset.x; let mut max_height = None; for float in self.float_data.iter() { match *float { None => (), Some(f_data) => { if f_data.bounds.origin.y + f_data.bounds.size.height > top && f_data.bounds.origin.x + f_data.bounds.size.width > left && f_data.bounds.origin.x < left + width { let new_y = f_data.bounds.origin.y; max_height = Some(min(max_height.unwrap_or_default(new_y), new_y)); } } } } max_height.map(|h| h + self.offset.y) } /// Given necessary info, finds the closest place a box can be positioned /// without colliding with any floats. fn place_between_floats(&self, info: &PlacementInfo) -> Rect<Au>{ debug!("place_float: Placing float with width %? and height %?", info.width, info.height); // Can't go any higher than previous floats or // previous elements in the document. let mut float_y = info.ceiling; loop { let maybe_location = self.available_rect(float_y, info.height, info.max_width); debug!("place_float: Got available rect: %? for y-pos: %?", maybe_location, float_y); match maybe_location { // If there are no floats blocking us, return the current location // TODO(eatknson): integrate with overflow None => return match info.f_type { FloatLeft => Rect(Point2D(Au(0), float_y), Size2D(info.max_width, Au(max_value))), FloatRight => Rect(Point2D(info.max_width - info.width, float_y), Size2D(info.max_width, Au(max_value))) }, Some(rect) => { assert!(rect.origin.y + rect.size.height != float_y, "Non-terminating float placement"); // Place here if there is enough room if (rect.size.width >= info.width) { let height = self.max_height_for_bounds(rect.origin.x, rect.origin.y, rect.size.width); let height = height.unwrap_or_default(Au(max_value)); return match info.f_type { FloatLeft => Rect(Point2D(rect.origin.x, float_y), Size2D(rect.size.width, height)), FloatRight => { Rect(Point2D(rect.origin.x + rect.size.width - info.width, float_y), Size2D(rect.size.width, height)) } }; } // Try to place at the next-lowest location. // Need to be careful of fencepost errors. float_y = rect.origin.y + rect.size.height; } } } } fn clearance(&self, clear: ClearType) -> Au { let mut clearance = Au(0); for float in self.float_data.iter() { match *float { None => (), Some(f_data) => { match (clear, f_data.f_type) { (ClearLeft, FloatLeft) | (ClearRight, FloatRight) | (ClearBoth, _) => { clearance = max( clearance, self.offset.y + f_data.bounds.origin.y + f_data.bounds.size.height); } _ => () } } } } clearance } }
{ do self.with_base |base| { base.place_between_floats(info) } }
identifier_body
float_context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use geom::point::Point2D; use geom::size::Size2D; use geom::rect::Rect; use gfx::geometry::{Au, max, min}; use std::util::replace; use std::vec; use std::i32::max_value; #[deriving(Clone)] pub enum FloatType{ FloatLeft, FloatRight } pub enum ClearType { ClearLeft, ClearRight, ClearBoth } struct FloatContextBase{ float_data: ~[Option<FloatData>], floats_used: uint, max_y : Au, offset: Point2D<Au> } #[deriving(Clone)] struct FloatData{ bounds: Rect<Au>, f_type: FloatType } /// All information necessary to place a float pub struct PlacementInfo{ width: Au, // The dimensions of the float height: Au, ceiling: Au, // The minimum top of the float, as determined by earlier elements max_width: Au, // The maximum right of the float, generally determined by the contining block f_type: FloatType // left or right } /// Wrappers around float methods. To avoid allocating data we'll never use, /// destroy the context on modification. pub enum FloatContext { Invalid, Valid(~FloatContextBase) } impl FloatContext { pub fn new(num_floats: uint) -> FloatContext { Valid(~FloatContextBase::new(num_floats)) } #[inline(always)] pub fn clone(&mut self) -> FloatContext { match *self { Invalid => fail!("Can't clone an invalid float context"), Valid(_) => replace(self, Invalid) } } #[inline(always)] fn with_mut_base<R>(&mut self, callback: &fn(&mut FloatContextBase) -> R) -> R { match *self { Invalid => fail!("Float context no longer available"), Valid(ref mut base) => callback(&mut **base) } } #[inline(always)] pub fn with_base<R>(&self, callback: &fn(&FloatContextBase) -> R) -> R { match *self { Invalid => fail!("Float context no longer available"), Valid(ref base) => callback(& **base) } } #[inline(always)] pub fn translate(&mut self, trans: Point2D<Au>) -> FloatContext { do self.with_mut_base |base| { base.translate(trans); } replace(self, Invalid) } #[inline(always)] pub fn available_rect(&mut self, top: Au, height: Au, max_x: Au) -> Option<Rect<Au>> { do self.with_base |base| { base.available_rect(top, height, max_x) } } #[inline(always)] pub fn add_float(&mut self, info: &PlacementInfo) -> FloatContext{ do self.with_mut_base |base| { base.add_float(info); } replace(self, Invalid) } #[inline(always)] pub fn place_between_floats(&self, info: &PlacementInfo) -> Rect<Au> { do self.with_base |base| { base.place_between_floats(info) } } #[inline(always)] pub fn last_float_pos(&mut self) -> Point2D<Au> { do self.with_base |base| { base.last_float_pos() } } #[inline(always)] pub fn clearance(&self, clear: ClearType) -> Au { do self.with_base |base| { base.clearance(clear) } } } impl FloatContextBase{ fn new(num_floats: uint) -> FloatContextBase { debug!("Creating float context of size %?", num_floats); let new_data = vec::from_elem(num_floats, None); FloatContextBase { float_data: new_data, floats_used: 0, max_y: Au(0), offset: Point2D(Au(0), Au(0)) } } fn translate(&mut self, trans: Point2D<Au>) { self.offset = self.offset + trans; } fn last_float_pos(&self) -> Point2D<Au> { assert!(self.floats_used > 0, "Error: tried to access FloatContext with no floats in it"); match self.float_data[self.floats_used - 1] { None => fail!("FloatContext error: floats should never be None here"), Some(float) => { debug!("Returning float position: %?", float.bounds.origin + self.offset); float.bounds.origin + self.offset } } } /// Returns a rectangle that encloses the region from top to top + height, /// with width small enough that it doesn't collide with any floats. max_x /// is the x-coordinate beyond which floats have no effect (generally /// this is the containing block width). fn available_rect(&self, top: Au, height: Au, max_x: Au) -> Option<Rect<Au>> { fn range_intersect(top_1: Au, bottom_1: Au, top_2: Au, bottom_2: Au) -> (Au, Au) { (max(top_1, top_2), min(bottom_1, bottom_2)) } let top = top - self.offset.y; debug!("available_rect: trying to find space at %?", top); // Relevant dimensions for the right-most left float let mut max_left = Au(0) - self.offset.x; let mut l_top = None; let mut l_bottom = None; // Relevant dimensions for the left-most right float let mut min_right = max_x - self.offset.x; let mut r_top = None; let mut r_bottom = None; // Find the float collisions for the given vertical range. for float in self.float_data.iter() { debug!("available_rect: Checking for collision against float"); match *float{ None => (), Some(data) => { let float_pos = data.bounds.origin; let float_size = data.bounds.size; debug!("float_pos: %?, float_size: %?", float_pos, float_size); match data.f_type { FloatLeft => { if(float_pos.x + float_size.width > max_left && float_pos.y + float_size.height > top && float_pos.y < top + height) { max_left = float_pos.x + float_size.width; l_top = Some(float_pos.y); l_bottom = Some(float_pos.y + float_size.height); debug!("available_rect: collision with left float: new max_left is %?", max_left); } } FloatRight => { if(float_pos.x < min_right && float_pos.y + float_size.height > top && float_pos.y < top + height) { min_right = float_pos.x; r_top = Some(float_pos.y); r_bottom = Some(float_pos.y + float_size.height); debug!("available_rect: collision with right float: new min_right is %?", min_right); } } } } }; } // Extend the vertical range of the rectangle to the closest floats. // If there are floats on both sides, take the intersection of the // two areas. Also make sure we never return a top smaller than the // given upper bound. let (top, bottom) = match (r_top, r_bottom, l_top, l_bottom) { (Some(r_top), Some(r_bottom), Some(l_top), Some(l_bottom)) => range_intersect(max(top, r_top), r_bottom, max(top, l_top), l_bottom), (None, None, Some(l_top), Some(l_bottom)) => (max(top, l_top), l_bottom), (Some(r_top), Some(r_bottom), None, None) => (max(top, r_top), r_bottom), (None, None, None, None) => return None, _ => fail!("Reached unreachable state when computing float area") }; // This assertion is too strong and fails in some cases. It is OK to // return negative widths since we check against that right away, but // we should still undersrtand why they occur and add a stronger // assertion here. //assert!(max_left < min_right); assert!(top <= bottom, "Float position error"); Some(Rect{ origin: Point2D(max_left, top) + self.offset, size: Size2D(min_right - max_left, bottom - top) }) } fn add_float(&mut self, info: &PlacementInfo) { debug!("Floats_used: %?, Floats available: %?", self.floats_used, self.float_data.len()); assert!(self.floats_used < self.float_data.len() && self.float_data[self.floats_used].is_none()); let new_info = PlacementInfo { width: info.width, height: info.height, ceiling: max(info.ceiling, self.max_y + self.offset.y), max_width: info.max_width, f_type: info.f_type }; debug!("add_float: added float with info %?", new_info); let new_float = FloatData { bounds: Rect { origin: self.place_between_floats(&new_info).origin - self.offset, size: Size2D(info.width, info.height) }, f_type: info.f_type }; self.float_data[self.floats_used] = Some(new_float); self.max_y = max(self.max_y, new_float.bounds.origin.y); self.floats_used += 1; } /// Returns true if the given rect overlaps with any floats. fn
(&self, bounds: &Rect<Au>) -> bool { for float in self.float_data.iter() { match *float{ None => (), Some(data) => { if data.bounds.translate(&self.offset).intersects(bounds) { return true; } } }; } return false; } /// Given the top 3 sides of the rectange, finds the largest height that /// will result in the rectange not colliding with any floats. Returns /// None if that height is infinite. fn max_height_for_bounds(&self, left: Au, top: Au, width: Au) -> Option<Au> { let top = top - self.offset.y; let left = left - self.offset.x; let mut max_height = None; for float in self.float_data.iter() { match *float { None => (), Some(f_data) => { if f_data.bounds.origin.y + f_data.bounds.size.height > top && f_data.bounds.origin.x + f_data.bounds.size.width > left && f_data.bounds.origin.x < left + width { let new_y = f_data.bounds.origin.y; max_height = Some(min(max_height.unwrap_or_default(new_y), new_y)); } } } } max_height.map(|h| h + self.offset.y) } /// Given necessary info, finds the closest place a box can be positioned /// without colliding with any floats. fn place_between_floats(&self, info: &PlacementInfo) -> Rect<Au>{ debug!("place_float: Placing float with width %? and height %?", info.width, info.height); // Can't go any higher than previous floats or // previous elements in the document. let mut float_y = info.ceiling; loop { let maybe_location = self.available_rect(float_y, info.height, info.max_width); debug!("place_float: Got available rect: %? for y-pos: %?", maybe_location, float_y); match maybe_location { // If there are no floats blocking us, return the current location // TODO(eatknson): integrate with overflow None => return match info.f_type { FloatLeft => Rect(Point2D(Au(0), float_y), Size2D(info.max_width, Au(max_value))), FloatRight => Rect(Point2D(info.max_width - info.width, float_y), Size2D(info.max_width, Au(max_value))) }, Some(rect) => { assert!(rect.origin.y + rect.size.height != float_y, "Non-terminating float placement"); // Place here if there is enough room if (rect.size.width >= info.width) { let height = self.max_height_for_bounds(rect.origin.x, rect.origin.y, rect.size.width); let height = height.unwrap_or_default(Au(max_value)); return match info.f_type { FloatLeft => Rect(Point2D(rect.origin.x, float_y), Size2D(rect.size.width, height)), FloatRight => { Rect(Point2D(rect.origin.x + rect.size.width - info.width, float_y), Size2D(rect.size.width, height)) } }; } // Try to place at the next-lowest location. // Need to be careful of fencepost errors. float_y = rect.origin.y + rect.size.height; } } } } fn clearance(&self, clear: ClearType) -> Au { let mut clearance = Au(0); for float in self.float_data.iter() { match *float { None => (), Some(f_data) => { match (clear, f_data.f_type) { (ClearLeft, FloatLeft) | (ClearRight, FloatRight) | (ClearBoth, _) => { clearance = max( clearance, self.offset.y + f_data.bounds.origin.y + f_data.bounds.size.height); } _ => () } } } } clearance } }
collides_with_float
identifier_name
float_context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use geom::point::Point2D; use geom::size::Size2D; use geom::rect::Rect; use gfx::geometry::{Au, max, min}; use std::util::replace; use std::vec; use std::i32::max_value; #[deriving(Clone)] pub enum FloatType{ FloatLeft, FloatRight } pub enum ClearType { ClearLeft, ClearRight, ClearBoth } struct FloatContextBase{ float_data: ~[Option<FloatData>], floats_used: uint, max_y : Au, offset: Point2D<Au> } #[deriving(Clone)] struct FloatData{ bounds: Rect<Au>, f_type: FloatType } /// All information necessary to place a float pub struct PlacementInfo{ width: Au, // The dimensions of the float height: Au, ceiling: Au, // The minimum top of the float, as determined by earlier elements max_width: Au, // The maximum right of the float, generally determined by the contining block f_type: FloatType // left or right } /// Wrappers around float methods. To avoid allocating data we'll never use, /// destroy the context on modification. pub enum FloatContext { Invalid, Valid(~FloatContextBase) } impl FloatContext { pub fn new(num_floats: uint) -> FloatContext { Valid(~FloatContextBase::new(num_floats)) } #[inline(always)] pub fn clone(&mut self) -> FloatContext { match *self { Invalid => fail!("Can't clone an invalid float context"), Valid(_) => replace(self, Invalid) } } #[inline(always)] fn with_mut_base<R>(&mut self, callback: &fn(&mut FloatContextBase) -> R) -> R { match *self { Invalid => fail!("Float context no longer available"), Valid(ref mut base) => callback(&mut **base) } } #[inline(always)] pub fn with_base<R>(&self, callback: &fn(&FloatContextBase) -> R) -> R { match *self { Invalid => fail!("Float context no longer available"), Valid(ref base) => callback(& **base) } } #[inline(always)] pub fn translate(&mut self, trans: Point2D<Au>) -> FloatContext { do self.with_mut_base |base| { base.translate(trans); } replace(self, Invalid) } #[inline(always)] pub fn available_rect(&mut self, top: Au, height: Au, max_x: Au) -> Option<Rect<Au>> { do self.with_base |base| { base.available_rect(top, height, max_x) } } #[inline(always)] pub fn add_float(&mut self, info: &PlacementInfo) -> FloatContext{ do self.with_mut_base |base| { base.add_float(info); } replace(self, Invalid) } #[inline(always)] pub fn place_between_floats(&self, info: &PlacementInfo) -> Rect<Au> { do self.with_base |base| { base.place_between_floats(info) } } #[inline(always)] pub fn last_float_pos(&mut self) -> Point2D<Au> { do self.with_base |base| { base.last_float_pos() } } #[inline(always)] pub fn clearance(&self, clear: ClearType) -> Au { do self.with_base |base| { base.clearance(clear) } } } impl FloatContextBase{ fn new(num_floats: uint) -> FloatContextBase { debug!("Creating float context of size %?", num_floats); let new_data = vec::from_elem(num_floats, None); FloatContextBase { float_data: new_data, floats_used: 0, max_y: Au(0), offset: Point2D(Au(0), Au(0)) } } fn translate(&mut self, trans: Point2D<Au>) { self.offset = self.offset + trans; } fn last_float_pos(&self) -> Point2D<Au> { assert!(self.floats_used > 0, "Error: tried to access FloatContext with no floats in it"); match self.float_data[self.floats_used - 1] { None => fail!("FloatContext error: floats should never be None here"), Some(float) => { debug!("Returning float position: %?", float.bounds.origin + self.offset); float.bounds.origin + self.offset } } } /// Returns a rectangle that encloses the region from top to top + height, /// with width small enough that it doesn't collide with any floats. max_x /// is the x-coordinate beyond which floats have no effect (generally /// this is the containing block width). fn available_rect(&self, top: Au, height: Au, max_x: Au) -> Option<Rect<Au>> { fn range_intersect(top_1: Au, bottom_1: Au, top_2: Au, bottom_2: Au) -> (Au, Au) { (max(top_1, top_2), min(bottom_1, bottom_2)) } let top = top - self.offset.y; debug!("available_rect: trying to find space at %?", top); // Relevant dimensions for the right-most left float let mut max_left = Au(0) - self.offset.x; let mut l_top = None; let mut l_bottom = None; // Relevant dimensions for the left-most right float let mut min_right = max_x - self.offset.x; let mut r_top = None; let mut r_bottom = None; // Find the float collisions for the given vertical range. for float in self.float_data.iter() { debug!("available_rect: Checking for collision against float"); match *float{ None => (), Some(data) => { let float_pos = data.bounds.origin; let float_size = data.bounds.size; debug!("float_pos: %?, float_size: %?", float_pos, float_size); match data.f_type { FloatLeft => { if(float_pos.x + float_size.width > max_left && float_pos.y + float_size.height > top && float_pos.y < top + height) { max_left = float_pos.x + float_size.width; l_top = Some(float_pos.y); l_bottom = Some(float_pos.y + float_size.height); debug!("available_rect: collision with left float: new max_left is %?", max_left); } } FloatRight => { if(float_pos.x < min_right && float_pos.y + float_size.height > top && float_pos.y < top + height) { min_right = float_pos.x; r_top = Some(float_pos.y); r_bottom = Some(float_pos.y + float_size.height); debug!("available_rect: collision with right float: new min_right is %?", min_right); } } } } }; } // Extend the vertical range of the rectangle to the closest floats. // If there are floats on both sides, take the intersection of the // two areas. Also make sure we never return a top smaller than the // given upper bound. let (top, bottom) = match (r_top, r_bottom, l_top, l_bottom) { (Some(r_top), Some(r_bottom), Some(l_top), Some(l_bottom)) => range_intersect(max(top, r_top), r_bottom, max(top, l_top), l_bottom), (None, None, Some(l_top), Some(l_bottom)) => (max(top, l_top), l_bottom), (Some(r_top), Some(r_bottom), None, None) => (max(top, r_top), r_bottom), (None, None, None, None) => return None, _ => fail!("Reached unreachable state when computing float area") }; // This assertion is too strong and fails in some cases. It is OK to // return negative widths since we check against that right away, but // we should still undersrtand why they occur and add a stronger // assertion here. //assert!(max_left < min_right); assert!(top <= bottom, "Float position error"); Some(Rect{ origin: Point2D(max_left, top) + self.offset, size: Size2D(min_right - max_left, bottom - top) }) } fn add_float(&mut self, info: &PlacementInfo) { debug!("Floats_used: %?, Floats available: %?", self.floats_used, self.float_data.len()); assert!(self.floats_used < self.float_data.len() && self.float_data[self.floats_used].is_none()); let new_info = PlacementInfo { width: info.width, height: info.height, ceiling: max(info.ceiling, self.max_y + self.offset.y), max_width: info.max_width, f_type: info.f_type }; debug!("add_float: added float with info %?", new_info); let new_float = FloatData { bounds: Rect { origin: self.place_between_floats(&new_info).origin - self.offset, size: Size2D(info.width, info.height) }, f_type: info.f_type }; self.float_data[self.floats_used] = Some(new_float); self.max_y = max(self.max_y, new_float.bounds.origin.y); self.floats_used += 1; } /// Returns true if the given rect overlaps with any floats. fn collides_with_float(&self, bounds: &Rect<Au>) -> bool { for float in self.float_data.iter() { match *float{ None => (), Some(data) => { if data.bounds.translate(&self.offset).intersects(bounds) { return true; } } }; } return false; } /// Given the top 3 sides of the rectange, finds the largest height that /// will result in the rectange not colliding with any floats. Returns /// None if that height is infinite. fn max_height_for_bounds(&self, left: Au, top: Au, width: Au) -> Option<Au> { let top = top - self.offset.y; let left = left - self.offset.x; let mut max_height = None; for float in self.float_data.iter() { match *float { None => (), Some(f_data) => { if f_data.bounds.origin.y + f_data.bounds.size.height > top && f_data.bounds.origin.x + f_data.bounds.size.width > left && f_data.bounds.origin.x < left + width { let new_y = f_data.bounds.origin.y; max_height = Some(min(max_height.unwrap_or_default(new_y), new_y)); } } } } max_height.map(|h| h + self.offset.y) } /// Given necessary info, finds the closest place a box can be positioned /// without colliding with any floats. fn place_between_floats(&self, info: &PlacementInfo) -> Rect<Au>{ debug!("place_float: Placing float with width %? and height %?", info.width, info.height); // Can't go any higher than previous floats or // previous elements in the document. let mut float_y = info.ceiling; loop { let maybe_location = self.available_rect(float_y, info.height, info.max_width); debug!("place_float: Got available rect: %? for y-pos: %?", maybe_location, float_y); match maybe_location { // If there are no floats blocking us, return the current location // TODO(eatknson): integrate with overflow None => return match info.f_type { FloatLeft => Rect(Point2D(Au(0), float_y), Size2D(info.max_width, Au(max_value))), FloatRight => Rect(Point2D(info.max_width - info.width, float_y),
"Non-terminating float placement"); // Place here if there is enough room if (rect.size.width >= info.width) { let height = self.max_height_for_bounds(rect.origin.x, rect.origin.y, rect.size.width); let height = height.unwrap_or_default(Au(max_value)); return match info.f_type { FloatLeft => Rect(Point2D(rect.origin.x, float_y), Size2D(rect.size.width, height)), FloatRight => { Rect(Point2D(rect.origin.x + rect.size.width - info.width, float_y), Size2D(rect.size.width, height)) } }; } // Try to place at the next-lowest location. // Need to be careful of fencepost errors. float_y = rect.origin.y + rect.size.height; } } } } fn clearance(&self, clear: ClearType) -> Au { let mut clearance = Au(0); for float in self.float_data.iter() { match *float { None => (), Some(f_data) => { match (clear, f_data.f_type) { (ClearLeft, FloatLeft) | (ClearRight, FloatRight) | (ClearBoth, _) => { clearance = max( clearance, self.offset.y + f_data.bounds.origin.y + f_data.bounds.size.height); } _ => () } } } } clearance } }
Size2D(info.max_width, Au(max_value))) }, Some(rect) => { assert!(rect.origin.y + rect.size.height != float_y,
random_line_split
b_lanterns.py
import fileinput def
(s): return([ int(x) for x in s.split() ]) # args = [ 'line 1', 'line 2', ... ] def proc_input(args): (n, l) = str_to_int(args[0]) a = tuple(str_to_int(args[1])) return(l, a) def solve(args, verbose=False): (l, a) = proc_input(args) list_a = list(a) list_a.sort() max_dist = max(list_a[0] * 2, (l - list_a[-1]) * 2) for x in xrange(len(a) - 1): max_dist = max(max_dist, list_a[x + 1] - list_a[x]) if verbose: print max_dist / float(2) return max_dist / float(2) def test(): assert(str_to_int('1 2 3') == [ 1, 2, 3 ]) assert(proc_input([ '2 5', '2 5' ]) == (5, (2, 5))) assert(solve([ '2 5', '2 5' ]) == 2.0) assert(solve([ '4 5', '0 1 2 3' ]) == 2.0) assert(solve([ '7 15', '15 5 3 7 9 14 0' ]) == 2.5) if __name__ == '__main__': from sys import argv if argv.pop() == 'test': test() else: solve(list(fileinput.input()), verbose=True)
str_to_int
identifier_name
b_lanterns.py
import fileinput def str_to_int(s): return([ int(x) for x in s.split() ]) # args = [ 'line 1', 'line 2', ... ] def proc_input(args):
def solve(args, verbose=False): (l, a) = proc_input(args) list_a = list(a) list_a.sort() max_dist = max(list_a[0] * 2, (l - list_a[-1]) * 2) for x in xrange(len(a) - 1): max_dist = max(max_dist, list_a[x + 1] - list_a[x]) if verbose: print max_dist / float(2) return max_dist / float(2) def test(): assert(str_to_int('1 2 3') == [ 1, 2, 3 ]) assert(proc_input([ '2 5', '2 5' ]) == (5, (2, 5))) assert(solve([ '2 5', '2 5' ]) == 2.0) assert(solve([ '4 5', '0 1 2 3' ]) == 2.0) assert(solve([ '7 15', '15 5 3 7 9 14 0' ]) == 2.5) if __name__ == '__main__': from sys import argv if argv.pop() == 'test': test() else: solve(list(fileinput.input()), verbose=True)
(n, l) = str_to_int(args[0]) a = tuple(str_to_int(args[1])) return(l, a)
identifier_body
b_lanterns.py
import fileinput def str_to_int(s): return([ int(x) for x in s.split() ]) # args = [ 'line 1', 'line 2', ... ] def proc_input(args): (n, l) = str_to_int(args[0]) a = tuple(str_to_int(args[1])) return(l, a) def solve(args, verbose=False): (l, a) = proc_input(args) list_a = list(a) list_a.sort() max_dist = max(list_a[0] * 2, (l - list_a[-1]) * 2) for x in xrange(len(a) - 1): max_dist = max(max_dist, list_a[x + 1] - list_a[x]) if verbose: print max_dist / float(2) return max_dist / float(2) def test(): assert(str_to_int('1 2 3') == [ 1, 2, 3 ]) assert(proc_input([ '2 5', '2 5' ]) == (5, (2, 5))) assert(solve([ '2 5', '2 5' ]) == 2.0)
assert(solve([ '4 5', '0 1 2 3' ]) == 2.0) assert(solve([ '7 15', '15 5 3 7 9 14 0' ]) == 2.5) if __name__ == '__main__': from sys import argv if argv.pop() == 'test': test() else: solve(list(fileinput.input()), verbose=True)
random_line_split
b_lanterns.py
import fileinput def str_to_int(s): return([ int(x) for x in s.split() ]) # args = [ 'line 1', 'line 2', ... ] def proc_input(args): (n, l) = str_to_int(args[0]) a = tuple(str_to_int(args[1])) return(l, a) def solve(args, verbose=False): (l, a) = proc_input(args) list_a = list(a) list_a.sort() max_dist = max(list_a[0] * 2, (l - list_a[-1]) * 2) for x in xrange(len(a) - 1): max_dist = max(max_dist, list_a[x + 1] - list_a[x]) if verbose: print max_dist / float(2) return max_dist / float(2) def test(): assert(str_to_int('1 2 3') == [ 1, 2, 3 ]) assert(proc_input([ '2 5', '2 5' ]) == (5, (2, 5))) assert(solve([ '2 5', '2 5' ]) == 2.0) assert(solve([ '4 5', '0 1 2 3' ]) == 2.0) assert(solve([ '7 15', '15 5 3 7 9 14 0' ]) == 2.5) if __name__ == '__main__': from sys import argv if argv.pop() == 'test': test() else:
solve(list(fileinput.input()), verbose=True)
conditional_block
concurrency.py
import functools import threading from concurrent.futures import ThreadPoolExecutor import traceback NUMBER_OF_THREADS = 100 def unique_step(parallel, numer_of_threads=NUMBER_OF_THREADS): """Shorten the call for calling a function after the other is completed. @serial_step def get(self, url): return parallel thing @get(url): def next_step(): pass When the arguments to the function are the same, the call can not be done in parallel. It gets executed once and the result is passed two both results. `next_step` will get executed in parallel to where it was defined in all cases. """ executor = ThreadPoolExecutor(numer_of_threads) lock = threading.RLock() requesting = {} @functools.wraps(parallel) def record_call(*args):
return record_call
def call_function_when_done(function): assert callable(function), "{} must be callable. In {}".format(function, parallel) with lock: future = requesting.get(args) if not future: future = executor.submit(parallel, *args) requesting[args] = future @future.add_done_callback def end_with_result(future): with lock: requesting.pop(args) @future.add_done_callback def call_with_result(future): def call_function(): try: function(future.result()) except: traceback.print_exc() executor.submit(call_function) return function return call_function_when_done
identifier_body
concurrency.py
import functools import threading from concurrent.futures import ThreadPoolExecutor import traceback NUMBER_OF_THREADS = 100 def unique_step(parallel, numer_of_threads=NUMBER_OF_THREADS): """Shorten the call for calling a function after the other is completed. @serial_step def get(self, url): return parallel thing @get(url): def next_step(): pass When the arguments to the function are the same, the call can not be done in parallel. It gets executed once and the result is passed two both results. `next_step` will get executed in parallel to where it was defined in all cases. """ executor = ThreadPoolExecutor(numer_of_threads) lock = threading.RLock() requesting = {} @functools.wraps(parallel) def record_call(*args): def call_function_when_done(function): assert callable(function), "{} must be callable. In {}".format(function, parallel) with lock: future = requesting.get(args) if not future:
@future.add_done_callback def call_with_result(future): def call_function(): try: function(future.result()) except: traceback.print_exc() executor.submit(call_function) return function return call_function_when_done return record_call
future = executor.submit(parallel, *args) requesting[args] = future @future.add_done_callback def end_with_result(future): with lock: requesting.pop(args)
conditional_block
concurrency.py
import functools import threading from concurrent.futures import ThreadPoolExecutor import traceback NUMBER_OF_THREADS = 100 def unique_step(parallel, numer_of_threads=NUMBER_OF_THREADS): """Shorten the call for calling a function after the other is completed. @serial_step def get(self, url): return parallel thing @get(url): def next_step(): pass When the arguments to the function are the same, the call can not be done in parallel. It gets executed once and the result is passed two both results. `next_step` will get executed in parallel to where it was defined in all cases. """ executor = ThreadPoolExecutor(numer_of_threads) lock = threading.RLock() requesting = {} @functools.wraps(parallel) def record_call(*args): def call_function_when_done(function): assert callable(function), "{} must be callable. In {}".format(function, parallel) with lock: future = requesting.get(args) if not future: future = executor.submit(parallel, *args) requesting[args] = future @future.add_done_callback def end_with_result(future): with lock: requesting.pop(args) @future.add_done_callback def call_with_result(future): def
(): try: function(future.result()) except: traceback.print_exc() executor.submit(call_function) return function return call_function_when_done return record_call
call_function
identifier_name
concurrency.py
NUMBER_OF_THREADS = 100 def unique_step(parallel, numer_of_threads=NUMBER_OF_THREADS): """Shorten the call for calling a function after the other is completed. @serial_step def get(self, url): return parallel thing @get(url): def next_step(): pass When the arguments to the function are the same, the call can not be done in parallel. It gets executed once and the result is passed two both results. `next_step` will get executed in parallel to where it was defined in all cases. """ executor = ThreadPoolExecutor(numer_of_threads) lock = threading.RLock() requesting = {} @functools.wraps(parallel) def record_call(*args): def call_function_when_done(function): assert callable(function), "{} must be callable. In {}".format(function, parallel) with lock: future = requesting.get(args) if not future: future = executor.submit(parallel, *args) requesting[args] = future @future.add_done_callback def end_with_result(future): with lock: requesting.pop(args) @future.add_done_callback def call_with_result(future): def call_function(): try: function(future.result()) except: traceback.print_exc() executor.submit(call_function) return function return call_function_when_done return record_call
import functools import threading from concurrent.futures import ThreadPoolExecutor import traceback
random_line_split