idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
41,000 | def from_str ( cls , s ) : ast_obj = ast . parse ( s ) . body [ 0 ] if not isinstance ( ast_obj , cls . _expected_ast_type ) : raise AssertionError ( 'Expected ast of type {!r} but got {!r}' . format ( cls . _expected_ast_type , ast_obj ) ) return cls ( ast_obj ) | Construct an import object from a string . |
41,001 | def sort ( imports , separate = True , import_before_from = True , ** classify_kwargs ) : if separate : def classify_func ( obj ) : return classify_import ( obj . import_statement . module , ** classify_kwargs ) types = ImportType . __all__ else : def classify_func ( obj ) : return classify_import ( obj . import_statement . module , ** classify_kwargs ) == ImportType . FUTURE types = [ True , False ] if import_before_from : def sort_within ( obj ) : return ( CLS_TO_INDEX [ type ( obj ) ] , ) + obj . sort_key else : def sort_within ( obj ) : return tuple ( obj . sort_key ) imports_partitioned = collections . defaultdict ( list ) for import_obj in imports : imports_partitioned [ classify_func ( import_obj ) ] . append ( import_obj ) for segment_key , val in imports_partitioned . items ( ) : imports_partitioned [ segment_key ] = sorted ( val , key = sort_within ) return tuple ( tuple ( imports_partitioned [ key ] ) for key in types if key in imports_partitioned ) | Sort import objects into groups . |
41,002 | def classify_import ( module_name , application_directories = ( '.' , ) ) : base , _ , _ = module_name . partition ( '.' ) found , module_path , is_builtin = _get_module_info ( base , application_directories , ) if base == '__future__' : return ImportType . FUTURE elif base == '' : return ImportType . APPLICATION elif is_builtin : return ImportType . BUILTIN elif _module_path_is_local_and_is_not_symlinked ( module_path , application_directories , ) : return ImportType . APPLICATION elif ( found and PACKAGES_PATH not in module_path and not _due_to_pythonpath ( module_path ) ) : return ImportType . BUILTIN else : return ImportType . THIRD_PARTY | Classifies an import by its package . |
41,003 | def _arg_parser ( ) : parser = argparse . ArgumentParser ( description = __doc__ ) parser . add_argument ( 'xml' , nargs = '*' ) return parser | Factory for creating the argument parser |
41,004 | def validate_cnxml ( * content_filepaths ) : content_filepaths = [ Path ( path ) . resolve ( ) for path in content_filepaths ] return jing ( CNXML_JING_RNG , * content_filepaths ) | Validates the given CNXML file against the cnxml - jing . rng RNG . |
41,005 | def validate_collxml ( * content_filepaths ) : content_filepaths = [ Path ( path ) . resolve ( ) for path in content_filepaths ] return jing ( COLLXML_JING_RNG , * content_filepaths ) | Validates the given COLLXML file against the collxml - jing . rng RNG . |
41,006 | def action ( args ) : log . info ( 'loading reference package' ) r = refpkg . Refpkg ( args . refpkg , create = False ) q = r . contents for i in range ( args . n ) : if q [ 'rollback' ] is None : log . error ( 'Cannot rollback {} changes; ' 'refpkg only records {} changes.' . format ( args . n , i ) ) return 1 else : q = q [ 'rollback' ] for i in range ( args . n ) : r . rollback ( ) return 0 | Roll back commands on a refpkg . |
41,007 | def set_targets ( x , delta = 10 ) : data = [ ] for row , _ in x . iterrows ( ) : if row == x . shape [ 0 ] - 1 : break curr_close = x . close [ row ] next_close = x . close [ row + 1 ] high_close = next_close + ( delta / 2 ) low_close = next_close - ( delta / 2 ) if curr_close < low_close : target = TARGET_CODES [ 'bearish' ] elif curr_close > high_close : target = TARGET_CODES [ 'bullish' ] else : target = TARGET_CODES [ 'neutral' ] data . append ( target ) return pd . Series ( data = data , dtype = np . int32 , name = 'target' ) | Sets target market trend for a date |
41,008 | def eval_features ( json ) : return { 'close' : json [ - 1 ] [ 'close' ] , 'sma' : SMA . eval_from_json ( json ) , 'rsi' : RSI . eval_from_json ( json ) , 'so' : SO . eval_from_json ( json ) , 'obv' : OBV . eval_from_json ( json ) } | Gets technical analysis features from market data JSONs |
41,009 | def target_code_to_name ( code ) : TARGET_NAMES = { v : k for k , v in TARGET_CODES . items ( ) } return TARGET_NAMES [ code ] | Converts an int target code to a target name |
41,010 | def setup_model ( x , y , model_type = 'random_forest' , seed = None , ** kwargs ) : assert len ( x ) > 1 and len ( y ) > 1 , 'Not enough data objects to train on (minimum is at least two, you have (x: {0}) and (y: {1}))' . format ( len ( x ) , len ( y ) ) sets = namedtuple ( 'Datasets' , [ 'train' , 'test' ] ) x_train , x_test , y_train , y_test = train_test_split ( x , y , random_state = seed , shuffle = False ) x = sets ( x_train , x_test ) y = sets ( y_train , y_test ) if model_type == 'random_forest' or model_type == 'rf' : model = rf . RandomForest ( x , y , random_state = seed , ** kwargs ) elif model_type == 'deep_neural_network' or model_type == 'dnn' : model = dnn . DeepNeuralNetwork ( x , y , ** kwargs ) else : raise ValueError ( 'Invalid model type kwarg' ) return model | Initializes a machine learning model |
41,011 | def get_json ( self ) : today = dt . now ( ) DIRECTION = 'last' epochs = date . get_end_start_epochs ( today . year , today . month , today . day , DIRECTION , self . unit , self . count ) return poloniex . chart_json ( epochs [ 'shifted' ] , epochs [ 'initial' ] , self . period , self . symbol ) [ 0 ] | Gets market chart data from today to a previous date |
41,012 | def set_features ( self , partition = 1 ) : if len ( self . json ) < partition + 1 : raise ValueError ( 'Not enough dates for the specified partition size: {0}. Try a smaller partition.' . format ( partition ) ) data = [ ] for offset in range ( len ( self . json ) - partition ) : json = self . json [ offset : offset + partition ] data . append ( eval_features ( json ) ) return pd . DataFrame ( data = data , dtype = np . float32 ) | Parses market data JSON for technical analysis indicators |
41,013 | def set_long_features ( self , features , columns_to_set = [ ] , partition = 2 ) : features_long = self . set_features ( partition = 2 * partition ) unwanted_features = [ f for f in features . columns if f not in columns_to_set ] features_long = features_long . drop ( unwanted_features , axis = 1 ) features_long . columns = [ 'long_{0}' . format ( f ) for f in features_long . columns ] skip = partition return pd . concat ( [ features [ skip : ] . reset_index ( drop = True ) , features_long ] , axis = 1 ) | Sets features of double the duration |
41,014 | def feature_importances ( self ) : feature_names = [ feature for feature in self . features . train ] return list ( zip ( feature_names , self . feature_importances_ ) ) | Return list of features and their importance in classification |
41,015 | def stop ( self ) : if self . _http_server is not None : self . _http_server . stop ( ) tornado . ioloop . IOLoop . instance ( ) . add_callback ( tornado . ioloop . IOLoop . instance ( ) . stop ) | Stop the worker . |
41,016 | def run ( self ) : setproctitle . setproctitle ( "{:s}: worker {:s}" . format ( self . context . config . name , self . _tornado_app . settings [ 'interface' ] . name ) ) self . logger . info ( "Worker '%s' has been started with pid %d" , self . _tornado_app . settings [ 'interface' ] . name , os . getpid ( ) ) self . context . config . configure_logging ( ) self . http_server = tornado . httpserver . HTTPServer ( self . _tornado_app ) self . context . initialize_child ( TORNADO_WORKER , process = self ) def sigint_handler ( unused_signum , unused_frame ) : io_loop = tornado . ioloop . IOLoop . instance ( ) io_loop . add_callback_from_signal ( self . stop ) signal . signal ( signal . SIGINT , sigint_handler ) def run_ioloop_callback ( ) : self . _ready . value = True tornado . ioloop . IOLoop . instance ( ) . add_callback ( run_ioloop_callback ) def check_parent_callback ( ) : if os . getppid ( ) != self . _parent_pid : self . stop ( ) stop_callback = tornado . ioloop . PeriodicCallback ( check_parent_callback , 250 ) stop_callback . start ( ) self . http_server . add_sockets ( self . _sockets ) tornado . ioloop . IOLoop . instance ( ) . start ( ) | Tornado worker which handles HTTP requests . |
41,017 | def initialize ( self ) : self . main_pid = os . getpid ( ) self . processes . extend ( self . init_service_processes ( ) ) self . processes . extend ( self . init_tornado_workers ( ) ) | Initialize instance attributes . You can override this method in the subclasses . |
41,018 | def scratch_file ( unlink = True , ** kwargs ) : kwargs [ 'delete' ] = False tf = tempfile . NamedTemporaryFile ( ** kwargs ) tf . close ( ) try : yield tf . name finally : if unlink : os . unlink ( tf . name ) | Create a temporary file and return its name . |
41,019 | def open ( self , name , * mode ) : return self . file_factory ( self . file_path ( name ) , * mode ) | Return an open file object for a file in the reference package . |
41,020 | def open_resource ( self , resource , * mode ) : return self . open ( self . resource_name ( resource ) , * mode ) | Return an open file object for a particular named resource in this reference package . |
41,021 | def resource_name ( self , resource ) : if not ( resource in self . contents [ 'files' ] ) : raise ValueError ( "No such resource %r in refpkg" % ( resource , ) ) return self . contents [ 'files' ] [ resource ] | Return the name of the file within the reference package for a particular named resource . |
41,022 | def resource_md5 ( self , resource ) : if not ( resource in self . contents [ 'md5' ] ) : raise ValueError ( "No such resource %r in refpkg" % ( resource , ) ) return self . contents [ 'md5' ] [ resource ] | Return the stored MD5 sum for a particular named resource . |
41,023 | def _set_defaults ( self ) : self . contents . setdefault ( 'log' , [ ] ) self . contents . setdefault ( 'rollback' , None ) self . contents . setdefault ( 'rollforward' , None ) | Set some default values in the manifest . |
41,024 | def _sync_to_disk ( self ) : with self . open_manifest ( 'w' ) as h : json . dump ( self . contents , h , indent = 4 ) h . write ( '\n' ) | Write any changes made on Refpkg to disk . |
41,025 | def _sync_from_disk ( self ) : try : fobj = self . open_manifest ( 'r' ) except IOError as e : if e . errno == errno . ENOENT : raise ValueError ( "couldn't find manifest file in %s" % ( self . path , ) ) elif e . errno == errno . ENOTDIR : raise ValueError ( "%s is not a directory" % ( self . path , ) ) else : raise with fobj : self . contents = json . load ( fobj ) self . _set_defaults ( ) self . _check_refpkg ( ) | Read any changes made on disk to this Refpkg . |
41,026 | def _add_file ( self , key , path ) : filename = os . path . basename ( path ) base , ext = os . path . splitext ( filename ) if os . path . exists ( self . file_path ( filename ) ) : with tempfile . NamedTemporaryFile ( dir = self . path , prefix = base , suffix = ext ) as tf : filename = os . path . basename ( tf . name ) shutil . copyfile ( path , self . file_path ( filename ) ) self . contents [ 'files' ] [ key ] = filename | Copy a file into the reference package . |
41,027 | def is_invalid ( self ) : for k in [ 'metadata' , 'files' , 'md5' ] : if not ( k in self . contents ) : return "Manifest file missing key %s" % k if not ( isinstance ( self . contents [ k ] , dict ) ) : return "Key %s in manifest did not refer to a dictionary" % k if not ( 'rollback' in self . contents ) : return "Manifest file missing key rollback" if not ( isinstance ( self . contents [ 'rollback' ] , dict ) ) and self . contents [ "rollback" ] is not None : return ( "Key rollback in manifest did not refer to a " "dictionary or None, found %s" ) % str ( self . contents [ 'rollback' ] ) if not ( 'rollforward' in self . contents ) : return "Manifest file missing key rollforward" if self . contents [ 'rollforward' ] is not None : if not ( isinstance ( self . contents [ 'rollforward' ] , list ) ) : return "Key rollforward was not a list, found %s" % str ( self . contents [ 'rollforward' ] ) elif len ( self . contents [ 'rollforward' ] ) != 2 : return "Key rollforward had wrong length, found %d" % len ( self . contents [ 'rollforward' ] ) elif not is_string ( self . contents [ 'rollforward' ] [ 0 ] ) : print ( type ( self . contents [ 'rollforward' ] [ 0 ] ) ) return "Key rollforward's first entry was not a string, found %s" % str ( self . contents [ 'rollforward' ] [ 0 ] ) elif not ( isinstance ( self . contents [ 'rollforward' ] [ 1 ] , dict ) ) : return "Key rollforward's second entry was not a dict, found %s" % str ( self . contents [ 'rollforward' ] [ 1 ] ) if not ( "log" in self . contents ) : return "Manifest file missing key 'log'" if not ( isinstance ( self . contents [ 'log' ] , list ) ) : return "Key 'log' in manifest did not refer to a list" if self . contents [ 'files' ] . keys ( ) != self . contents [ 'md5' ] . keys ( ) : return ( "Files and MD5 sums in manifest do not " "match (files: %s, MD5 sums: %s)" ) % ( list ( self . contents [ 'files' ] . keys ( ) ) , list ( self . contents [ 'md5' ] . keys ( ) ) ) for key , filename in self . contents [ 'files' ] . items ( ) : expected_md5 = self . resource_md5 ( key ) found_md5 = self . calculate_resource_md5 ( key ) if found_md5 != expected_md5 : return ( "File %s referred to by key %s did " "not match its MD5 sum (found: %s, expected %s)" ) % ( filename , key , found_md5 , expected_md5 ) return False | Check if this RefPkg is invalid . |
41,028 | def reroot ( self , rppr = None , pretend = False ) : with scratch_file ( prefix = 'tree' , suffix = '.tre' ) as name : subprocess . check_call ( [ rppr or 'rppr' , 'reroot' , '-c' , self . path , '-o' , name ] ) if not ( pretend ) : self . update_file ( 'tree' , name ) self . _log ( 'Rerooting refpkg' ) | Reroot the phylogenetic tree . |
41,029 | def update_phylo_model ( self , stats_type , stats_file , frequency_type = None ) : if frequency_type not in ( None , 'model' , 'empirical' ) : raise ValueError ( 'Unknown frequency type: "{0}"' . format ( frequency_type ) ) if frequency_type and stats_type not in ( None , 'PhyML' ) : raise ValueError ( 'Frequency type should only be specified for ' 'PhyML alignments.' ) if stats_type is None : with open ( stats_file ) as fobj : for line in fobj : if line . startswith ( 'FastTree' ) : stats_type = 'FastTree' break elif ( line . startswith ( 'This is RAxML' ) or line . startswith ( 'You are using RAxML' ) ) : stats_type = 'RAxML' break elif 'PhyML' in line : stats_type = 'PhyML' break else : raise ValueError ( "couldn't guess log type for %r" % ( stats_file , ) ) if stats_type == 'RAxML' : parser = utils . parse_raxml elif stats_type == 'FastTree' : parser = utils . parse_fasttree elif stats_type == 'PhyML' : parser = functools . partial ( utils . parse_phyml , frequency_type = frequency_type ) else : raise ValueError ( 'invalid log type: %r' % ( stats_type , ) ) with scratch_file ( prefix = 'phylo_model' , suffix = '.json' ) as name : with open ( name , 'w' ) as phylo_model , open ( stats_file ) as h : json . dump ( parser ( h ) , phylo_model , indent = 4 ) self . update_file ( 'phylo_model' , name ) | Parse a stats log and use it to update phylo_model . |
41,030 | def rollback ( self ) : if self . contents [ 'rollback' ] is None : raise ValueError ( "No operation to roll back on refpkg" ) future_msg = self . contents [ 'log' ] [ 0 ] rolledback_log = self . contents [ 'log' ] [ 1 : ] rollforward = copy . deepcopy ( self . contents ) rollforward . pop ( 'rollback' ) self . contents = self . contents [ 'rollback' ] self . contents [ 'log' ] = rolledback_log self . contents [ 'rollforward' ] = [ future_msg , rollforward ] self . _sync_to_disk ( ) | Revert the previous modification to the refpkg . |
41,031 | def rollforward ( self ) : if self . contents [ 'rollforward' ] is None : raise ValueError ( "No operation to roll forward on refpkg" ) new_log_message = self . contents [ 'rollforward' ] [ 0 ] new_contents = self . contents [ 'rollforward' ] [ 1 ] new_contents [ 'log' ] = [ new_log_message ] + self . contents . pop ( 'log' ) self . contents [ 'rollforward' ] = None new_contents [ 'rollback' ] = copy . deepcopy ( self . contents ) new_contents [ 'rollback' ] . pop ( 'rollforward' ) self . contents = new_contents self . _sync_to_disk ( ) | Restore a reverted modification to the refpkg . |
41,032 | def strip ( self ) : self . _sync_from_disk ( ) current_filenames = set ( self . contents [ 'files' ] . values ( ) ) all_filenames = set ( os . listdir ( self . path ) ) to_delete = all_filenames . difference ( current_filenames ) to_delete . discard ( 'CONTENTS.json' ) for f in to_delete : self . _delete_file ( f ) self . contents [ 'rollback' ] = None self . contents [ 'rollforward' ] = None self . contents [ 'log' ] . insert ( 0 , 'Stripped refpkg (removed %d files)' % len ( to_delete ) ) self . _sync_to_disk ( ) | Remove rollbacks rollforwards and all non - current files . |
41,033 | def start_transaction ( self ) : if self . current_transaction : raise ValueError ( "There is already a transaction going" ) else : initial_state = copy . deepcopy ( self . contents ) self . current_transaction = { 'rollback' : initial_state , 'log' : '(Transaction left no log message)' } | Begin a transaction to group operations on the refpkg . |
41,034 | def is_ill_formed ( self ) : m = self . is_invalid ( ) if m : return m required_keys = ( 'aln_fasta' , 'aln_sto' , 'seq_info' , 'tree' , 'taxonomy' , 'phylo_model' ) for k in required_keys : if k not in self . contents [ 'files' ] : return "RefPkg has no key " + k with self . open_resource ( 'aln_fasta' ) as f : firstline = f . readline ( ) if firstline . startswith ( '>' ) : f . seek ( 0 ) else : return 'aln_fasta file is not valid FASTA.' fasta_names = { seq . id for seq in fastalite ( f ) } with self . open_resource ( 'seq_info' ) as f : lines = list ( csv . reader ( f ) ) headers = set ( lines [ 0 ] ) for req_header in 'seqname' , 'tax_id' : if req_header not in headers : return "seq_info is missing {0}" . format ( req_header ) lengths = { len ( line ) for line in lines } if len ( lengths ) > 1 : return "some lines in seq_info differ in field cout" csv_names = { line [ 0 ] for line in lines [ 1 : ] } with self . open_resource ( 'aln_sto' ) as f : try : sto_names = set ( utils . parse_stockholm ( f ) ) except ValueError : return 'aln_sto file is not valid Stockholm.' try : tree = dendropy . Tree . get ( path = self . resource_path ( 'tree' ) , schema = 'newick' , case_sensitive_taxon_labels = True , preserve_underscores = True ) tree_names = set ( tree . taxon_namespace . labels ( ) ) except Exception : return 'tree file is not valid Newick.' d = fasta_names . symmetric_difference ( sto_names ) if len ( d ) != 0 : return "Names in aln_fasta did not match aln_sto. Mismatches: " + ', ' . join ( [ str ( x ) for x in d ] ) d = fasta_names . symmetric_difference ( csv_names ) if len ( d ) != 0 : return "Names in aln_fasta did not match seq_info. Mismatches: " + ', ' . join ( [ str ( x ) for x in d ] ) d = fasta_names . symmetric_difference ( tree_names ) if len ( d ) != 0 : return "Names in aln_fasta did not match nodes in tree. Mismatches: " + ', ' . join ( [ str ( x ) for x in d ] ) with self . open_resource ( 'taxonomy' ) as f : lines = list ( csv . reader ( f ) ) lengths = { len ( line ) for line in lines } if len ( lengths ) > 1 : return ( "Taxonomy is invalid: not all lines had " "the same number of fields." ) with self . open_resource ( 'phylo_model' ) as f : try : json . load ( f ) except ValueError : return "phylo_model is not valid JSON." return False | Stronger set of checks than is_invalid for Refpkg . |
41,035 | def load_db ( self ) : db = taxdb . Taxdb ( ) db . create_tables ( ) reader = csv . DictReader ( self . open_resource ( 'taxonomy' , 'rU' ) ) db . insert_from_taxtable ( lambda : reader . _fieldnames , reader ) curs = db . cursor ( ) reader = csv . DictReader ( self . open_resource ( 'seq_info' , 'rU' ) ) curs . executemany ( "INSERT INTO sequences VALUES (?, ?)" , ( ( row [ 'seqname' ] , row [ 'tax_id' ] ) for row in reader ) ) db . commit ( ) self . db = db | Load the taxonomy into a sqlite3 database . |
41,036 | def most_recent_common_ancestor ( self , * ts ) : if len ( ts ) > 200 : res = self . _large_mrca ( ts ) else : res = self . _small_mrca ( ts ) if res : ( res , ) , = res else : raise NoAncestor ( ) return res | Find the MRCA of some tax_ids . |
41,037 | def main ( args = None ) : parser = ArgumentParser ( add_help = False ) parser . add_argument ( '-s' , '--settings' , dest = 'settings' , action = 'store' , type = str , default = None , help = _ ( 'application settings module' ) ) try : settings = get_app_settings ( parser , args ) except ImportError as exc : parser . error ( _ ( "Invalid application settings module: {}" ) . format ( exc ) ) commands = get_management_commands ( settings ) subparsers = parser . add_subparsers ( dest = 'action' , help = _ ( 'specify action' ) ) for command_cls in six . itervalues ( commands ) : subparser = subparsers . add_parser ( command_cls . name , help = command_cls . help ) for command_args , kwargs in command_cls . arguments : subparser . add_argument ( * command_args , ** kwargs ) if settings : config_cls = get_config_class ( settings ) if not issubclass ( config_cls , Config ) : raise TypeError ( "Config class must be subclass of the " "shelter.core.config.Config" ) for config_args , kwargs in config_cls . arguments : parser . add_argument ( * config_args , ** kwargs ) else : config_cls = Config parser . add_argument ( '-h' , '--help' , action = 'help' , help = _ ( 'show this help message and exit' ) ) cmdline_args = parser . parse_args ( args ) if not cmdline_args . action : parser . error ( _ ( 'No action' ) ) command_cls = commands [ cmdline_args . action ] if command_cls . settings_required and not settings : parser . error ( _ ( "Settings module is not defined. You must either set " "'SHELTER_SETTINGS_MODULE' environment variable or " "'-s/--settings' command line argument." ) ) try : config = config_cls ( settings , cmdline_args ) except ImproperlyConfiguredError as exc : parser . error ( str ( exc ) ) command = command_cls ( config ) try : command ( ) except Exception : traceback . print_exc ( file = sys . stderr ) sys . stderr . flush ( ) if multiprocessing . active_children ( ) : os . _exit ( 1 ) sys . exit ( 1 ) sys . exit ( 0 ) | Run management command handled from command line . |
41,038 | def as_length ( self , value ) : new_vec = self . copy ( ) new_vec . length = value return new_vec | Return a new vector scaled to given length |
41,039 | def as_percent ( self , value ) : new_vec = self . copy ( ) new_vec . length = value * self . length return new_vec | Return a new vector scaled by given decimal percent |
41,040 | def angle ( self , vec , unit = 'rad' ) : if not isinstance ( vec , self . __class__ ) : raise TypeError ( 'Angle operand must be of class {}' . format ( self . __class__ . __name__ ) ) if unit not in [ 'deg' , 'rad' ] : raise ValueError ( 'Only units of rad or deg are supported' ) denom = self . length * vec . length if denom == 0 : raise ZeroDivisionError ( 'Cannot calculate angle between ' 'zero-length vector(s)' ) ang = np . arccos ( self . dot ( vec ) / denom ) if unit == 'deg' : ang = ang * 180 / np . pi return ang | Calculate the angle between two Vectors |
41,041 | def length ( self ) : return np . sqrt ( np . sum ( self ** 2 , axis = 1 ) ) . view ( np . ndarray ) | Array of vector lengths |
41,042 | def cross ( self , vec ) : if not isinstance ( vec , Vector3Array ) : raise TypeError ( 'Cross product operand must be a Vector3Array' ) if self . nV != 1 and vec . nV != 1 and self . nV != vec . nV : raise ValueError ( 'Cross product operands must have the same ' 'number of elements.' ) return Vector3Array ( np . cross ( self , vec ) ) | Cross product with another Vector3Array |
41,043 | def eval_rs ( gains , losses ) : count = len ( gains ) + len ( losses ) avg_gains = stats . avg ( gains , count = count ) if gains else 1 avg_losses = stats . avg ( losses , count = count ) if losses else 1 if avg_losses == 0 : return avg_gains else : return avg_gains / avg_losses | Evaluates the RS variable in RSI algorithm |
41,044 | def action ( args ) : log . info ( 'loading reference package' ) pkg = refpkg . Refpkg ( args . refpkg , create = False ) with open ( pkg . file_abspath ( 'seq_info' ) , 'rU' ) as seq_info : seqinfo = list ( csv . DictReader ( seq_info ) ) snames = [ row [ 'seqname' ] for row in seqinfo ] if args . seq_names : print ( '\n' . join ( snames ) ) elif args . tally : tally_taxa ( pkg ) elif args . lengths : print_lengths ( pkg ) else : print ( 'number of sequences:' , len ( snames ) ) print ( 'package components\n' , '\n' . join ( sorted ( pkg . file_keys ( ) ) ) ) | Show information about reference packages . |
41,045 | def json_to_url ( json , symbol ) : start = json [ 0 ] [ 'date' ] end = json [ - 1 ] [ 'date' ] diff = end - start periods = [ 300 , 900 , 1800 , 7200 , 14400 , 86400 ] diffs = { } for p in periods : diffs [ p ] = abs ( 1 - ( p / ( diff / len ( json ) ) ) ) period = min ( diffs , key = diffs . get ) url = ( 'https://poloniex.com/public?command' '=returnChartData¤cyPair={0}&start={1}' '&end={2}&period={3}' ) . format ( symbol , start , end , period ) return url | Converts a JSON to a URL by the Poloniex API |
41,046 | def parse_changes ( json ) : changes = [ ] dates = len ( json ) for date in range ( 1 , dates ) : last_close = json [ date - 1 ] [ 'close' ] now_close = json [ date ] [ 'close' ] changes . append ( now_close - last_close ) logger . debug ( 'Market Changes (from JSON):\n{0}' . format ( changes ) ) return changes | Gets price changes from JSON |
41,047 | def get_gains_losses ( changes ) : res = { 'gains' : [ ] , 'losses' : [ ] } for change in changes : if change > 0 : res [ 'gains' ] . append ( change ) else : res [ 'losses' ] . append ( change * - 1 ) logger . debug ( 'Gains: {0}' . format ( res [ 'gains' ] ) ) logger . debug ( 'Losses: {0}' . format ( res [ 'losses' ] ) ) return res | Categorizes changes into gains and losses |
41,048 | def get_attribute ( json , attr ) : res = [ json [ entry ] [ attr ] for entry , _ in enumerate ( json ) ] logger . debug ( '{0}s (from JSON):\n{1}' . format ( attr , res ) ) return res | Gets the values of an attribute from JSON |
41,049 | def get_json_shift ( year , month , day , unit , count , period , symbol ) : epochs = date . get_end_start_epochs ( year , month , day , 'last' , unit , count ) return chart_json ( epochs [ 'shifted' ] , epochs [ 'initial' ] , period , symbol ) [ 0 ] | Gets JSON from shifted date by the Poloniex API |
41,050 | def filter_ranks ( results ) : for _ , group in itertools . groupby ( results , operator . itemgetter ( 0 ) ) : yield next ( group ) | Find just the first rank for all the results for a given tax_id . |
41,051 | def eval_algorithm ( closing , low , high ) : if high - low == 0 : return 100 * ( closing - low ) else : return 100 * ( closing - low ) / ( high - low ) | Evaluates the SO algorithm |
41,052 | def avg ( vals , count = None ) : sum = 0 for v in vals : sum += v if count is None : count = len ( vals ) return float ( sum ) / count | Returns the average value |
41,053 | def db_connect ( engine , schema = None , clobber = False ) : if schema is None : base = declarative_base ( ) else : try : engine . execute ( sqlalchemy . schema . CreateSchema ( schema ) ) except sqlalchemy . exc . ProgrammingError as err : logging . warn ( err ) base = declarative_base ( metadata = MetaData ( schema = schema ) ) define_schema ( base ) if clobber : logging . info ( 'Clobbering database tables' ) base . metadata . drop_all ( bind = engine ) logging . info ( 'Creating database tables' ) base . metadata . create_all ( bind = engine ) return base | Create a connection object to a database . Attempt to establish a schema . If there are existing tables delete them if clobber is True and return otherwise . Returns a sqlalchemy engine object . |
41,054 | def read_nodes ( rows , source_id = 1 ) : ncbi_keys = [ 'tax_id' , 'parent_id' , 'rank' , 'embl_code' , 'division_id' ] extra_keys = [ 'source_id' , 'is_valid' ] is_valid = True ncbi_cols = len ( ncbi_keys ) rank = ncbi_keys . index ( 'rank' ) parent_id = ncbi_keys . index ( 'parent_id' ) row = next ( rows ) row [ rank ] = 'root' row [ parent_id ] = None rows = itertools . chain ( [ row ] , rows ) yield ncbi_keys + extra_keys for row in rows : row [ rank ] = '_' . join ( row [ rank ] . split ( ) ) yield row [ : ncbi_cols ] + [ source_id , is_valid ] | Return an iterator of rows ready to insert into table nodes . |
41,055 | def fetch_data ( dest_dir = '.' , clobber = False , url = DATA_URL ) : dest_dir = os . path . abspath ( dest_dir ) try : os . mkdir ( dest_dir ) except OSError : pass fout = os . path . join ( dest_dir , os . path . split ( url ) [ - 1 ] ) if os . access ( fout , os . F_OK ) and not clobber : downloaded = False logging . info ( fout + ' exists; not downloading' ) else : downloaded = True logging . info ( 'downloading {} to {}' . format ( url , fout ) ) request . urlretrieve ( url , fout ) return ( fout , downloaded ) | Download data from NCBI required to generate local taxonomy database . Default url is ncbi . DATA_URL |
41,056 | def read_archive ( archive , fname ) : zfile = zipfile . ZipFile ( archive ) contents = zfile . open ( fname , 'r' ) fobj = io . TextIOWrapper ( contents ) seen = set ( ) for line in fobj : line = line . rstrip ( '\t|\n' ) if line not in seen : yield line . split ( '\t|\t' ) seen . add ( line ) | Return an iterator of unique rows from a zip archive . |
41,057 | def prepend_schema ( self , name ) : return '.' . join ( [ self . schema , name ] ) if self . schema else name | Prepend schema name to name when a schema is specified |
41,058 | def load_table ( self , table , rows , colnames = None , limit = None ) : conn = self . engine . raw_connection ( ) cur = conn . cursor ( ) colnames = colnames or next ( rows ) cmd = 'INSERT INTO {table} ({colnames}) VALUES ({placeholders})' . format ( table = self . tables [ table ] , colnames = ', ' . join ( colnames ) , placeholders = ', ' . join ( [ self . placeholder ] * len ( colnames ) ) ) cur . executemany ( cmd , itertools . islice ( rows , limit ) ) conn . commit ( ) | Load rows into table table . If colnames is not provided the first element of rows must provide column names . |
41,059 | def load_archive ( self , archive ) : self . load_table ( 'source' , rows = [ ( 'ncbi' , DATA_URL ) ] , colnames = [ 'name' , 'description' ] , ) conn = self . engine . raw_connection ( ) cur = conn . cursor ( ) cmd = "select id from {source} where name = 'ncbi'" . format ( ** self . tables ) cur . execute ( cmd ) source_id = cur . fetchone ( ) [ 0 ] log . info ( 'loading ranks' ) self . load_table ( 'ranks' , rows = ( ( rank , i ) for i , rank in enumerate ( RANKS ) ) , colnames = [ 'rank' , 'height' ] , ) logging . info ( 'loading nodes' ) nodes_rows = read_nodes ( read_archive ( archive , 'nodes.dmp' ) , source_id = source_id ) self . load_table ( 'nodes' , rows = nodes_rows ) logging . info ( 'loading names' ) names_rows = read_names ( read_archive ( archive , 'names.dmp' ) , source_id = source_id ) self . load_table ( 'names' , rows = names_rows ) logging . info ( 'loading merged' ) merged_rows = read_merged ( read_archive ( archive , 'merged.dmp' ) ) self . load_table ( 'merged' , rows = merged_rows ) | Load data from the zip archive of the NCBI taxonomy . |
41,060 | def date_to_epoch ( year , month , day ) : return int ( date_to_delorean ( year , month , day ) . epoch ) | Converts a date to epoch in UTC |
41,061 | def get_end_start_epochs ( year , month , day , direction , unit , count ) : if year or month or day : if not year : year = 2017 if not month : month = 1 if not day : day = 1 initial_delorean = date_to_delorean ( year , month , day ) else : count += 1 initial_delorean = now_delorean ( ) initial_epoch = int ( initial_delorean . epoch ) shifted_epoch = shift_epoch ( initial_delorean , direction , unit , count ) return { 'initial' : initial_epoch , 'shifted' : shifted_epoch } | Gets epoch from a start date and epoch from a shifted date |
41,062 | def add_child ( self , child ) : assert child != self child . parent = self child . ranks = self . ranks child . index = self . index assert child . tax_id not in self . index self . index [ child . tax_id ] = child self . children . add ( child ) | Add a child to this node . |
41,063 | def remove_child ( self , child ) : assert child in self . children self . children . remove ( child ) self . index . pop ( child . tax_id ) if child . parent is self : child . parent = None if child . index is self . index : child . index = None for n in child : if n is child : continue self . index . pop ( n . tax_id ) if n . index is self . index : n . index = None | Remove a child from this node . |
41,064 | def drop ( self ) : if self . is_root : raise ValueError ( "Cannot drop root node!" ) parent = self . parent for child in self . children : child . parent = parent parent . children . add ( child ) self . children = set ( ) parent . sequence_ids . update ( self . sequence_ids ) self . sequence_ids = set ( ) parent . remove_child ( self ) | Remove this node from the taxonomy maintaining child subtrees by adding them to the node s parent and moving sequences at this node to the parent . |
41,065 | def prune_unrepresented ( self ) : for node in self . depth_first_iter ( self_first = False ) : if ( not node . children and not node . sequence_ids and node is not self ) : node . parent . remove_child ( node ) | Remove nodes without sequences or children below this node . |
41,066 | def at_rank ( self , rank ) : s = self while s : if s . rank == rank : return s s = s . parent raise ValueError ( "No node at rank {0} for {1}" . format ( rank , self . tax_id ) ) | Find the node above this node at rank rank |
41,067 | def depth_first_iter ( self , self_first = True ) : if self_first : yield self for child in list ( self . children ) : for i in child . depth_first_iter ( self_first ) : yield i if not self_first : yield self | Iterate over nodes below this node optionally yielding children before self . |
41,068 | def path ( self , tax_ids ) : assert tax_ids [ 0 ] == self . tax_id if len ( tax_ids ) == 1 : return self n = tax_ids [ 1 ] try : child = next ( i for i in self . children if i . tax_id == n ) except StopIteration : raise ValueError ( n ) return child . path ( tax_ids [ 1 : ] ) | Get the node at the end of the path described by tax_ids . |
41,069 | def lineage ( self ) : if not self . parent : return [ self ] else : L = self . parent . lineage ( ) L . append ( self ) return L | Return all nodes between this node and the root including this one . |
41,070 | def write_taxtable ( self , out_fp , ** kwargs ) : ranks_represented = frozenset ( i . rank for i in self ) | frozenset ( i . rank for i in self . lineage ( ) ) ranks = [ i for i in self . ranks if i in ranks_represented ] assert len ( ranks_represented ) == len ( ranks ) def node_record ( node ) : parent_id = node . parent . tax_id if node . parent else node . tax_id d = { 'tax_id' : node . tax_id , 'tax_name' : node . name , 'parent_id' : parent_id , 'rank' : node . rank } L = { i . rank : i . tax_id for i in node . lineage ( ) } d . update ( L ) return d header = [ 'tax_id' , 'parent_id' , 'rank' , 'tax_name' ] + ranks w = csv . DictWriter ( out_fp , header , quoting = csv . QUOTE_NONNUMERIC , lineterminator = '\n' ) w . writeheader ( ) for i in self . lineage ( ) [ : - 1 ] : w . writerow ( node_record ( i ) ) w . writerows ( node_record ( i ) for i in self ) | Write a taxtable for this node and all descendants including the lineage leading to this node . |
41,071 | def populate_from_seqinfo ( self , seqinfo ) : for row in csv . DictReader ( seqinfo ) : node = self . index . get ( row [ 'tax_id' ] ) if node : node . sequence_ids . add ( row [ 'seqname' ] ) | Populate sequence_ids below this node from a seqinfo file object . |
41,072 | def collapse ( self , remove = False ) : descendants = iter ( self ) assert next ( descendants ) is self for descendant in descendants : self . sequence_ids . update ( descendant . sequence_ids ) descendant . sequence_ids . clear ( ) if remove : for node in self . children : self . remove_child ( node ) | Move all sequence_ids in the subtree below this node to this node . |
41,073 | def write_seqinfo ( self , out_fp , include_name = True ) : header = [ 'seqname' , 'tax_id' ] if include_name : header . append ( 'tax_name' ) w = csv . DictWriter ( out_fp , header , quoting = csv . QUOTE_NONNUMERIC , lineterminator = '\n' , extrasaction = 'ignore' ) w . writeheader ( ) rows = ( { 'seqname' : seq_id , 'tax_id' : node . tax_id , 'tax_name' : node . name } for node in self for seq_id in node . sequence_ids ) w . writerows ( rows ) | Write a simple seq_info file suitable for use in taxtastic . Useful for printing out the results of collapsing tax nodes - super bare bones just tax_id and seqname . |
41,074 | def from_taxtable ( cls , taxtable_fp ) : r = csv . reader ( taxtable_fp ) headers = next ( r ) rows = ( collections . OrderedDict ( list ( zip ( headers , i ) ) ) for i in r ) row = next ( rows ) root = cls ( rank = row [ 'rank' ] , tax_id = row [ 'tax_id' ] , name = row [ 'tax_name' ] ) path_root = headers . index ( 'root' ) root . ranks = headers [ path_root : ] for row in rows : rank , tax_id , name = [ row [ i ] for i in ( 'rank' , 'tax_id' , 'tax_name' ) ] path = [ _f for _f in list ( row . values ( ) ) [ path_root : ] if _f ] parent = root . path ( path [ : - 1 ] ) parent . add_child ( cls ( rank , tax_id , name = name ) ) return root | Generate a node from an open handle to a taxtable as generated by taxit taxtable |
41,075 | def get_children ( engine , parent_ids , rank = 'species' , schema = None ) : if not parent_ids : return [ ] nodes = schema + '.nodes' if schema else 'nodes' names = schema + '.names' if schema else 'names' cmd = ( 'select tax_id, tax_name, rank ' 'from {} join {} using (tax_id) ' 'where parent_id = :tax_id and is_primary' ) . format ( nodes , names ) species = [ ] for parent_id in parent_ids : result = engine . execute ( sqlalchemy . sql . text ( cmd ) , tax_id = parent_id ) keys = list ( result . keys ( ) ) rows = [ dict ( list ( zip ( keys , row ) ) ) for row in result . fetchall ( ) ] for r in rows : if r [ 'rank' ] == rank and 'sp.' not in r [ 'tax_name' ] : species . append ( r ) others = [ r for r in rows if r [ 'rank' ] not in ( rank , 'no_rank' ) ] if others : _ , s = get_children ( engine , [ r [ 'tax_id' ] for r in others ] ) species . extend ( s ) return keys , species | Recursively fetch children of tax_ids in parent_ids until the rank of rank |
41,076 | def action ( args ) : log . info ( 'loading reference package' ) pairs = [ p . split ( '=' , 1 ) for p in args . changes ] if args . metadata : rp = refpkg . Refpkg ( args . refpkg , create = False ) rp . start_transaction ( ) for key , value in pairs : rp . update_metadata ( key , value ) rp . commit_transaction ( 'Updated metadata: ' + ', ' . join ( [ '%s=%s' % ( a , b ) for a , b in pairs ] ) ) else : for key , filename in pairs : if not ( os . path . exists ( filename ) ) : print ( "No such file: %s" % filename ) exit ( 1 ) rp = refpkg . Refpkg ( args . refpkg , create = False ) rp . start_transaction ( ) for key , filename in pairs : if key == 'tree_stats' : with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" , refpkg . DerivedFileNotUpdatedWarning ) rp . update_file ( key , os . path . abspath ( filename ) ) log . info ( 'Updating phylo_model to match tree_stats' ) rp . update_phylo_model ( args . stats_type , filename , args . frequency_type ) else : rp . update_file ( key , os . path . abspath ( filename ) ) rp . commit_transaction ( 'Updates files: ' + ', ' . join ( [ '%s=%s' % ( a , b ) for a , b in pairs ] ) ) return 0 | Updates a Refpkg with new files . |
41,077 | def parse_arguments ( argv ) : parser = argparse . ArgumentParser ( description = DESCRIPTION ) base_parser = argparse . ArgumentParser ( add_help = False ) parser . add_argument ( '-V' , '--version' , action = 'version' , version = 'taxit v' + version , help = 'Print the version number and exit' ) parser . add_argument ( '-v' , '--verbose' , action = 'count' , dest = 'verbosity' , default = 1 , help = 'Increase verbosity of screen output (eg, -v is verbose, ' '-vv more so)' ) parser . add_argument ( '-q' , '--quiet' , action = 'store_const' , dest = 'verbosity' , const = 0 , help = 'Suppress output' ) subparsers = parser . add_subparsers ( dest = 'subparser_name' ) parser_help = subparsers . add_parser ( 'help' , help = 'Detailed help for actions using `help <action>`' ) parser_help . add_argument ( 'action' , nargs = 1 ) actions = { } for name , mod in subcommands . itermodules ( os . path . split ( subcommands . __file__ ) [ 0 ] ) : subparser = subparsers . add_parser ( name , prog = 'taxit {}' . format ( name ) , help = mod . __doc__ . lstrip ( ) . split ( '\n' , 1 ) [ 0 ] , description = mod . __doc__ , formatter_class = RawDescriptionHelpFormatter , parents = [ base_parser ] ) mod . build_parser ( subparser ) actions [ name ] = mod . action arguments = parser . parse_args ( argv ) action = arguments . subparser_name if action == 'help' : return parse_arguments ( [ str ( arguments . action [ 0 ] ) , '-h' ] ) return actions [ action ] , arguments | Create the argument parser |
41,078 | def execute ( self , statements , exc = IntegrityError , rasie_as = ValueError ) : Session = sessionmaker ( bind = self . engine ) session = Session ( ) try : for statement in statements : session . execute ( statement ) except exc as err : session . rollback ( ) raise rasie_as ( str ( err ) ) else : session . commit ( ) finally : session . close ( ) | Execute statements in a session and perform a rollback on error . exc is a single exception object or a tuple of objects to be used in the except clause . The error message is re - raised as the exception specified by raise_as . |
41,079 | def _node ( self , tax_id ) : s = select ( [ self . nodes . c . parent_id , self . nodes . c . rank ] , self . nodes . c . tax_id == tax_id ) res = s . execute ( ) output = res . fetchone ( ) if not output : msg = 'value "{}" not found in nodes.tax_id' . format ( tax_id ) raise ValueError ( msg ) else : return output | Returns parent_id rank |
41,080 | def primary_from_id ( self , tax_id ) : s = select ( [ self . names . c . tax_name ] , and_ ( self . names . c . tax_id == tax_id , self . names . c . is_primary ) ) res = s . execute ( ) output = res . fetchone ( ) if not output : msg = 'value "{}" not found in names.tax_id' . format ( tax_id ) raise ValueError ( msg ) else : return output [ 0 ] | Returns primary taxonomic name associated with tax_id |
41,081 | def primary_from_name ( self , tax_name ) : names = self . names s1 = select ( [ names . c . tax_id , names . c . is_primary ] , names . c . tax_name == tax_name ) log . debug ( str ( s1 ) ) res = s1 . execute ( ) . fetchone ( ) if res : tax_id , is_primary = res else : msg = '"{}" not found in names.tax_names' . format ( tax_name ) raise ValueError ( msg ) if not is_primary : s2 = select ( [ names . c . tax_name ] , and_ ( names . c . tax_id == tax_id , names . c . is_primary ) ) tax_name = s2 . execute ( ) . fetchone ( ) [ 0 ] return tax_id , tax_name , bool ( is_primary ) | Return tax_id and primary tax_name corresponding to tax_name . |
41,082 | def lineage ( self , tax_id = None , tax_name = None ) : if not bool ( tax_id ) ^ bool ( tax_name ) : msg = 'Exactly one of tax_id and tax_name may be provided.' raise ValueError ( msg ) if tax_name : tax_id , primary_name , is_primary = self . primary_from_name ( tax_name ) else : primary_name = None lintups = self . _get_lineage ( tax_id ) ldict = dict ( lintups ) ldict [ 'tax_id' ] = tax_id try : __ , ldict [ 'parent_id' ] = lintups [ - 2 ] except IndexError : ldict [ 'parent_id' ] = None ldict [ 'rank' ] , __ = lintups [ - 1 ] ldict [ 'tax_name' ] = primary_name or self . primary_from_id ( tax_id ) return ldict | Public method for returning a lineage ; includes tax_name and rank |
41,083 | def verify_rank_integrity ( self , tax_id , rank , parent_id , children ) : def _lower ( n1 , n2 ) : return self . ranks . index ( n1 ) < self . ranks . index ( n2 ) if rank not in self . ranks : raise TaxonIntegrityError ( 'rank "{}" is undefined' . format ( rank ) ) parent_rank = self . rank ( parent_id ) if not _lower ( rank , parent_rank ) and rank != self . NO_RANK : msg = ( 'New node "{}", rank "{}" has same or ' 'higher rank than parent node "{}", rank "{}"' ) msg = msg . format ( tax_id , rank , parent_id , parent_rank ) raise TaxonIntegrityError ( msg ) for child in children : if not _lower ( self . rank ( child ) , rank ) : msg = 'Child node {} has same or lower rank as new node {}' msg = msg . format ( tax_id , child ) raise TaxonIntegrityError ( msg ) return True | Confirm that for each node the parent ranks and children ranks are coherent |
41,084 | def add_node ( self , tax_id , parent_id , rank , names , source_name , children = None , is_valid = True , execute = True , ** ignored ) : if ignored : log . info ( 'some arguments were ignored: {} ' . format ( str ( ignored ) ) ) children = children or [ ] self . verify_rank_integrity ( tax_id , rank , parent_id , children ) source_id , __ = self . add_source ( source_name ) assert isinstance ( is_valid , bool ) statements = [ ] statements . append ( self . nodes . insert ( ) . values ( tax_id = tax_id , parent_id = parent_id , rank = rank , source_id = source_id ) ) if len ( names ) == 1 : names [ 0 ] [ 'is_primary' ] = True else : primary_names = [ n [ 'tax_name' ] for n in names if n . get ( 'is_primary' ) ] if len ( primary_names ) != 1 : raise ValueError ( '`is_primary` must be True for exactly one name in `names`' ) for namedict in names : namedict [ 'source_id' ] = source_id if 'source_name' in namedict : del namedict [ 'source_name' ] statements . extend ( self . add_names ( tax_id , names , execute = False ) ) for child in children : statements . append ( self . nodes . update ( whereclause = self . nodes . c . tax_id == child , values = { 'parent_id' : tax_id , 'source_id' : source_id } ) ) if execute : self . execute ( statements ) else : return statements | Add a node to the taxonomy . |
41,085 | def add_names ( self , tax_id , names , execute = True ) : primary_names = [ n [ 'tax_name' ] for n in names if n . get ( 'is_primary' ) ] if len ( primary_names ) > 1 : raise ValueError ( '`is_primary` may be True for no more than one name in `names`' ) statements = [ ] for namevals in names : if 'tax_id' in namevals : del namevals [ 'tax_id' ] statements . extend ( self . add_name ( tax_id = tax_id , execute = False , ** namevals ) ) if execute : self . execute ( statements ) else : return statements | Associate one or more names with tax_id . |
41,086 | def tax_ids ( self ) : fetch = select ( [ self . nodes . c . tax_id ] ) . execute ( ) . fetchall ( ) ids = [ t [ 0 ] for t in fetch ] return ids | Return all tax_ids in node table |
41,087 | def validate_db ( sqlalchemy_bind , is_enabled = ENABLE_DB ) : def decorator ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : def is_db_responsive ( ) : try : sqlalchemy_bind . session . query ( '1' ) . first_or_404 ( ) except : return False else : return True if is_enabled and is_db_responsive ( ) : return func ( * args , ** kwargs ) else : abort ( HTTP_CODES . UNAUTHORIZED ) return wrapper return decorator | Checks if a DB is authorized and responding before executing the function |
41,088 | def get_new_nodes ( fname ) : with open ( fname , 'rU' ) as infile : infile = ( line for line in infile if not line . startswith ( '#' ) ) reader = list ( csv . DictReader ( infile ) ) rows = ( d for d in reader if d [ 'tax_id' ] ) for d in rows : if 'children' in d : if d [ 'children' ] : d [ 'children' ] = [ x . strip ( ) for x in d [ 'children' ] . split ( ';' ) ] else : del d [ 'children' ] yield d | Return an iterator of dicts given a . csv - format file . |
41,089 | def parse_raxml ( handle ) : s = '' . join ( handle . readlines ( ) ) result = { } try_set_fields ( result , r'(?P<program>RAxML version [0-9.]+)' , s ) try_set_fields ( result , r'(?P<datatype>DNA|RNA|AA)' , s ) result [ 'empirical_frequencies' ] = ( result [ 'datatype' ] != 'AA' or re . search ( 'empirical base frequencies' , s , re . IGNORECASE ) is not None ) try_set_fields ( result , r'Substitution Matrix: (?P<subs_model>\w+)' , s ) rates = { } if result [ 'datatype' ] != 'AA' : try_set_fields ( rates , ( r"rates\[0\] ac ag at cg ct gt: " r"(?P<ac>[0-9.]+) (?P<ag>[0-9.]+) (?P<at>[0-9.]+) " r"(?P<cg>[0-9.]+) (?P<ct>[0-9.]+) (?P<gt>[0-9.]+)" ) , s , hook = float ) try_set_fields ( rates , r'rate A <-> C: (?P<ac>[0-9.]+)' , s , hook = float ) try_set_fields ( rates , r'rate A <-> G: (?P<ag>[0-9.]+)' , s , hook = float ) try_set_fields ( rates , r'rate A <-> T: (?P<at>[0-9.]+)' , s , hook = float ) try_set_fields ( rates , r'rate C <-> G: (?P<cg>[0-9.]+)' , s , hook = float ) try_set_fields ( rates , r'rate C <-> T: (?P<ct>[0-9.]+)' , s , hook = float ) try_set_fields ( rates , r'rate G <-> T: (?P<gt>[0-9.]+)' , s , hook = float ) if len ( rates ) > 0 : result [ 'subs_rates' ] = rates result [ 'gamma' ] = { 'n_cats' : 4 } try_set_fields ( result [ 'gamma' ] , r"alpha[\[\]0-9]*: (?P<alpha>[0-9.]+)" , s , hook = float ) result [ 'ras_model' ] = 'gamma' return result | Parse RAxML s summary output . |
41,090 | def parse_stockholm ( fobj ) : names = OrderedDict ( ) found_eof = False for line in fobj : line = line . strip ( ) if line == '//' : found_eof = True elif line . startswith ( '#' ) or not line . strip ( ) : continue else : name , __ = line . split ( None , 1 ) names [ name ] = None if not found_eof : raise ValueError ( 'Invalid Stockholm format: no file terminator' ) return list ( names . keys ( ) ) | Return a list of names from an Stockholm - format sequence alignment file . fobj is an open file or another object representing a sequence of lines . |
41,091 | def has_rppr ( rppr_name = 'rppr' ) : with open ( os . devnull ) as dn : try : subprocess . check_call ( [ rppr_name ] , stdout = dn , stderr = dn ) except OSError as e : if e . errno == os . errno . ENOENT : return False else : raise except subprocess . CalledProcessError as e : pass return True | Check for rppr binary in path |
41,092 | def add_database_args ( parser ) : parser . add_argument ( 'url' , nargs = '?' , default = 'sqlite:///ncbi_taxonomy.db' , type = sqlite_default ( ) , help = ( 'Database string URI or filename. If no database scheme ' 'specified \"sqlite:///\" will be prepended. [%(default)s]' ) ) db_parser = parser . add_argument_group ( title = 'database options' ) db_parser . add_argument ( '--schema' , help = ( 'Name of SQL schema in database to query ' '(if database flavor supports this).' ) ) return parser | Add a standard set of database arguments for argparse |
41,093 | def sqlite_default ( ) : def parse_url ( url ) : if url . endswith ( '.db' ) or url . endswith ( '.sqlite' ) : if not url . startswith ( 'sqlite:///' ) : url = 'sqlite:///' + url elif url . endswith ( '.cfg' ) or url . endswith ( '.conf' ) : conf = configparser . SafeConfigParser ( allow_no_value = True ) conf . optionxform = str conf . read ( url ) url = conf . get ( 'sqlalchemy' , 'url' ) return url return parse_url | Prepend default scheme if none is specified . This helps provides backwards compatibility with old versions of taxtastic where sqlite was the automatic default database . |
41,094 | def action ( args ) : log . info ( 'loading reference package' ) refpkg . Refpkg ( args . refpkg , create = False ) . strip ( ) | Strips non - current files and rollback information from a refpkg . |
41,095 | def name ( self ) : try : return self . config_parser . get ( 'application' , 'name' ) except CONFIGPARSER_EXC : return super ( IniConfig , self ) . name | Application name . It s used as a process name . |
41,096 | def tz_file ( name ) : try : filepath = tz_path ( name ) return open ( filepath , 'rb' ) except TimezoneNotFound : try : from pkg_resources import resource_stream except ImportError : resource_stream = None if resource_stream is not None : try : return resource_stream ( __name__ , 'zoneinfo/' + name ) except FileNotFoundError : return tz_path ( name ) raise | Open a timezone file from the zoneinfo subdir for reading . |
41,097 | def tz_path ( name ) : if not name : raise ValueError ( 'Invalid timezone' ) name_parts = name . lstrip ( '/' ) . split ( '/' ) for part in name_parts : if part == os . path . pardir or os . path . sep in part : raise ValueError ( 'Bad path segment: %r' % part ) filepath = os . path . join ( _DIRECTORY , * name_parts ) if not os . path . exists ( filepath ) : raise TimezoneNotFound ( 'Timezone {} not found at {}' . format ( name , filepath ) ) return filepath | Return the path to a timezone file . |
41,098 | def get_timezones ( ) : base_dir = _DIRECTORY zones = ( ) for root , dirs , files in os . walk ( base_dir ) : for basename in files : zone = os . path . join ( root , basename ) if os . path . isdir ( zone ) : continue zone = os . path . relpath ( zone , base_dir ) with open ( os . path . join ( root , basename ) , 'rb' ) as fd : if fd . read ( 4 ) == b'TZif' and zone not in INVALID_ZONES : zones = zones + ( zone , ) return tuple ( sorted ( zones ) ) | Get the supported timezones . |
41,099 | def award_points ( target , key , reason = "" , source = None ) : point_value , points = get_points ( key ) if not ALLOW_NEGATIVE_TOTALS : total = points_awarded ( target ) if total + points < 0 : reason = reason + "(floored from {0} to 0)" . format ( points ) points = - total apv = AwardedPointValue ( points = points , value = point_value , reason = reason ) if isinstance ( target , get_user_model ( ) ) : apv . target_user = target lookup_params = { "target_user" : target } else : apv . target_object = target lookup_params = { "target_content_type" : apv . target_content_type , "target_object_id" : apv . target_object_id , } if source is not None : if isinstance ( source , get_user_model ( ) ) : apv . source_user = source else : apv . source_object = source apv . save ( ) if not TargetStat . update_points ( points , lookup_params ) : try : sid = transaction . savepoint ( ) TargetStat . _default_manager . create ( ** dict ( lookup_params , points = points ) ) transaction . savepoint_commit ( sid ) except IntegrityError : transaction . savepoint_rollback ( sid ) TargetStat . update_points ( points , lookup_params ) signals . points_awarded . send ( sender = target . __class__ , target = target , key = key , points = points , source = source ) new_points = points_awarded ( target ) old_points = new_points - points TargetStat . update_positions ( ( old_points , new_points ) ) return apv | Awards target the point value for key . If key is an integer then it s a one off assignment and should be interpreted as the actual point value . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.