idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
61,300 | def include ( self , target ) : if self . _clean . isDict ( ) : return self . _wrap ( target in self . obj . values ( ) ) else : return self . _wrap ( target in self . obj ) | Determine if a given value is included in the array or object using is . |
61,301 | def shuffle ( self ) : if ( self . _clean . isDict ( ) ) : return self . _wrap ( list ( ) ) cloned = self . obj [ : ] random . shuffle ( cloned ) return self . _wrap ( cloned ) | Shuffle an array . |
61,302 | def sortBy ( self , val = None ) : if val is not None : if _ ( val ) . isString ( ) : return self . _wrap ( sorted ( self . obj , key = lambda x , * args : x . get ( val ) ) ) else : return self . _wrap ( sorted ( self . obj , key = val ) ) else : return self . _wrap ( sorted ( self . obj ) ) | Sort the object s values by a criterion produced by an iterator . |
61,303 | def _lookupIterator ( self , val ) : if val is None : return lambda el , * args : el return val if _ . isCallable ( val ) else lambda obj , * args : obj [ val ] | An internal function to generate lookup iterators . |
61,304 | def _group ( self , obj , val , behavior ) : ns = self . Namespace ( ) ns . result = { } iterator = self . _lookupIterator ( val ) def e ( value , index , * args ) : key = iterator ( value , index ) behavior ( ns . result , key , value ) _ . each ( obj , e ) if len ( ns . result ) == 1 : try : return ns . result [ 0 ] except KeyError : return list ( ns . result . values ( ) ) [ 0 ] return ns . result | An internal function used for aggregate group by operations . |
61,305 | def groupBy ( self , val ) : def by ( result , key , value ) : if key not in result : result [ key ] = [ ] result [ key ] . append ( value ) res = self . _group ( self . obj , val , by ) return self . _wrap ( res ) | Groups the object s values by a criterion . Pass either a string attribute to group by or a function that returns the criterion . |
61,306 | def indexBy ( self , val = None ) : if val is None : val = lambda * args : args [ 0 ] def by ( result , key , value ) : result [ key ] = value res = self . _group ( self . obj , val , by ) return self . _wrap ( res ) | Indexes the object s values by a criterion similar to groupBy but for when you know that your index values will be unique . |
61,307 | def countBy ( self , val ) : def by ( result , key , value ) : if key not in result : result [ key ] = 0 result [ key ] += 1 res = self . _group ( self . obj , val , by ) return self . _wrap ( res ) | Counts instances of an object that group by a certain criterion . Pass either a string attribute to count by or a function that returns the criterion . |
61,308 | def sortedIndex ( self , obj , iterator = lambda x : x ) : array = self . obj value = iterator ( obj ) low = 0 high = len ( array ) while low < high : mid = ( low + high ) >> 1 if iterator ( array [ mid ] ) < value : low = mid + 1 else : high = mid return self . _wrap ( low ) | Use a comparator function to figure out the smallest index at which an object should be inserted so as to maintain order . Uses binary search . |
61,309 | def flatten ( self , shallow = None ) : return self . _wrap ( self . _flatten ( self . obj , shallow ) ) | Return a completely flattened version of an array . |
61,310 | def uniq ( self , isSorted = False , iterator = None ) : ns = self . Namespace ( ) ns . results = [ ] ns . array = self . obj initial = self . obj if iterator is not None : initial = _ ( ns . array ) . map ( iterator ) def by ( memo , value , index ) : if ( ( _ . last ( memo ) != value or not len ( memo ) ) if isSorted else not _ . include ( memo , value ) ) : memo . append ( value ) ns . results . append ( ns . array [ index ] ) return memo ret = _ . reduce ( initial , by ) return self . _wrap ( ret ) | Produce a duplicate - free version of the array . If the array has already been sorted you have the option of using a faster algorithm . Aliased as unique . |
61,311 | def intersection ( self , * args ) : if type ( self . obj [ 0 ] ) is int : a = self . obj else : a = tuple ( self . obj [ 0 ] ) setobj = set ( a ) for i , v in enumerate ( args ) : setobj = setobj & set ( args [ i ] ) return self . _wrap ( list ( setobj ) ) | Produce an array that contains every item shared between all the passed - in arrays . |
61,312 | def difference ( self , * args ) : setobj = set ( self . obj ) for i , v in enumerate ( args ) : setobj = setobj - set ( args [ i ] ) return self . _wrap ( self . _clean . _toOriginal ( setobj ) ) | Take the difference between one array and a number of other arrays . Only the elements present in just the first array will remain . |
61,313 | def indexOf ( self , item , isSorted = False ) : array = self . obj ret = - 1 if not ( self . _clean . isList ( ) or self . _clean . isTuple ( ) ) : return self . _wrap ( - 1 ) if isSorted : i = _ . sortedIndex ( array , item ) ret = i if array [ i ] is item else - 1 else : i = 0 l = len ( array ) while i < l : if array [ i ] is item : return self . _wrap ( i ) i += 1 return self . _wrap ( ret ) | Return the position of the first occurrence of an item in an array or - 1 if the item is not included in the array . |
61,314 | def lastIndexOf ( self , item ) : array = self . obj i = len ( array ) - 1 if not ( self . _clean . isList ( ) or self . _clean . isTuple ( ) ) : return self . _wrap ( - 1 ) while i > - 1 : if array [ i ] is item : return self . _wrap ( i ) i -= 1 return self . _wrap ( - 1 ) | Return the position of the last occurrence of an item in an array or - 1 if the item is not included in the array . |
61,315 | def range ( self , * args ) : args = list ( args ) args . insert ( 0 , self . obj ) return self . _wrap ( range ( * args ) ) | Generate an integer Array containing an arithmetic progression . |
61,316 | def partial ( self , * args ) : def part ( * args2 ) : args3 = args + args2 return self . obj ( * args3 ) return self . _wrap ( part ) | Partially apply a function by creating a version that has had some of its arguments pre - filled without changing its dynamic this context . |
61,317 | def memoize ( self , hasher = None ) : ns = self . Namespace ( ) ns . memo = { } if hasher is None : hasher = lambda x : x def memoized ( * args , ** kwargs ) : key = hasher ( * args ) if key not in ns . memo : ns . memo [ key ] = self . obj ( * args , ** kwargs ) return ns . memo [ key ] return self . _wrap ( memoized ) | Memoize an expensive function by storing its results . |
61,318 | def delay ( self , wait , * args ) : def call_it ( ) : self . obj ( * args ) t = Timer ( ( float ( wait ) / float ( 1000 ) ) , call_it ) t . start ( ) return self . _wrap ( self . obj ) | Delays a function for the given number of milliseconds and then calls it with the arguments supplied . |
61,319 | def throttle ( self , wait ) : ns = self . Namespace ( ) ns . timeout = None ns . throttling = None ns . more = None ns . result = None def done ( ) : ns . more = ns . throttling = False whenDone = _ . debounce ( done , wait ) wait = ( float ( wait ) / float ( 1000 ) ) def throttled ( * args , ** kwargs ) : def later ( ) : ns . timeout = None if ns . more : self . obj ( * args , ** kwargs ) whenDone ( ) if not ns . timeout : ns . timeout = Timer ( wait , later ) ns . timeout . start ( ) if ns . throttling : ns . more = True else : ns . throttling = True ns . result = self . obj ( * args , ** kwargs ) whenDone ( ) return ns . result return self . _wrap ( throttled ) | Returns a function that when invoked will only be triggered at most once during a given window of time . |
61,320 | def debounce ( self , wait , immediate = None ) : wait = ( float ( wait ) / float ( 1000 ) ) def debounced ( * args , ** kwargs ) : def call_it ( ) : self . obj ( * args , ** kwargs ) try : debounced . t . cancel ( ) except ( AttributeError ) : pass debounced . t = Timer ( wait , call_it ) debounced . t . start ( ) return self . _wrap ( debounced ) | Returns a function that as long as it continues to be invoked will not be triggered . The function will be called after it stops being called for N milliseconds . If immediate is passed trigger the function on the leading edge instead of the trailing . |
61,321 | def once ( self ) : ns = self . Namespace ( ) ns . memo = None ns . run = False def work_once ( * args , ** kwargs ) : if ns . run is False : ns . memo = self . obj ( * args , ** kwargs ) ns . run = True return ns . memo return self . _wrap ( work_once ) | Returns a function that will be executed at most one time no matter how often you call it . Useful for lazy initialization . |
61,322 | def wrap ( self , wrapper ) : def wrapped ( * args , ** kwargs ) : if kwargs : kwargs [ "object" ] = self . obj else : args = list ( args ) args . insert ( 0 , self . obj ) return wrapper ( * args , ** kwargs ) return self . _wrap ( wrapped ) | Returns the first function passed as an argument to the second allowing you to adjust arguments run code before and after and conditionally execute the original function . |
61,323 | def compose ( self , * args ) : args = list ( args ) def composed ( * ar , ** kwargs ) : lastRet = self . obj ( * ar , ** kwargs ) for i in args : lastRet = i ( lastRet ) return lastRet return self . _wrap ( composed ) | Returns a function that is the composition of a list of functions each consuming the return value of the function that follows . |
61,324 | def after ( self , func ) : ns = self . Namespace ( ) ns . times = self . obj if ns . times <= 0 : return func ( ) def work_after ( * args ) : if ns . times <= 1 : return func ( * args ) ns . times -= 1 return self . _wrap ( work_after ) | Returns a function that will only be executed after being called N times . |
61,325 | def invert ( self ) : keys = self . _clean . keys ( ) inverted = { } for key in keys : inverted [ self . obj [ key ] ] = key return self . _wrap ( inverted ) | Invert the keys and values of an object . The values must be serializable . |
61,326 | def functions ( self ) : names = [ ] for i , k in enumerate ( self . obj ) : if _ ( self . obj [ k ] ) . isCallable ( ) : names . append ( k ) return self . _wrap ( sorted ( names ) ) | Return a sorted list of the function names available on the object . |
61,327 | def pick ( self , * args ) : ns = self . Namespace ( ) ns . result = { } def by ( key , * args ) : if key in self . obj : ns . result [ key ] = self . obj [ key ] _ . each ( self . _flatten ( args , True , [ ] ) , by ) return self . _wrap ( ns . result ) | Return a copy of the object only containing the whitelisted properties . |
61,328 | def defaults ( self , * args ) : ns = self . Namespace ns . obj = self . obj def by ( source , * ar ) : for i , prop in enumerate ( source ) : if prop not in ns . obj : ns . obj [ prop ] = source [ prop ] _ . each ( args , by ) return self . _wrap ( ns . obj ) | Fill in a given object with default properties . |
61,329 | def tap ( self , interceptor ) : interceptor ( self . obj ) return self . _wrap ( self . obj ) | Invokes interceptor with the obj and then returns obj . The primary purpose of this method is to tap into a method chain in order to perform operations on intermediate results within the chain . |
61,330 | def isEmpty ( self ) : if self . obj is None : return True if self . _clean . isString ( ) : ret = self . obj . strip ( ) is "" elif self . _clean . isDict ( ) : ret = len ( self . obj . keys ( ) ) == 0 else : ret = len ( self . obj ) == 0 return self . _wrap ( ret ) | Is a given array string or object empty? An empty object has no enumerable own - properties . |
61,331 | def isFile ( self ) : try : filetype = file except NameError : filetype = io . IOBase return self . _wrap ( type ( self . obj ) is filetype ) | Check if the given object is a file |
61,332 | def join ( self , glue = " " ) : j = glue . join ( [ str ( x ) for x in self . obj ] ) return self . _wrap ( j ) | Javascript s join implementation |
61,333 | def result ( self , property , * args ) : if self . obj is None : return self . _wrap ( self . obj ) if ( hasattr ( self . obj , property ) ) : value = getattr ( self . obj , property ) else : value = self . obj . get ( property ) if _ . isCallable ( value ) : return self . _wrap ( value ( * args ) ) return self . _wrap ( value ) | If the value of the named property is a function then invoke it ; otherwise return it . |
61,334 | def mixin ( self ) : methods = self . obj for i , k in enumerate ( methods ) : setattr ( underscore , k , methods [ k ] ) self . makeStatic ( ) return self . _wrap ( self . obj ) | Add your own custom functions to the Underscore object ensuring that they re correctly added to the OOP wrapper as well . |
61,335 | def escape ( self ) : self . obj = self . obj . replace ( "&" , self . _html_escape_table [ "&" ] ) for i , k in enumerate ( self . _html_escape_table ) : v = self . _html_escape_table [ k ] if k is not "&" : self . obj = self . obj . replace ( k , v ) return self . _wrap ( self . obj ) | Escape a string for HTML interpolation . |
61,336 | def unescape ( self ) : for i , k in enumerate ( self . _html_escape_table ) : v = self . _html_escape_table [ k ] self . obj = self . obj . replace ( v , k ) return self . _wrap ( self . obj ) | Within an interpolation evaluation or escaping remove HTML escaping that had been previously added . |
61,337 | def value ( self ) : if self . _wrapped is not self . Null : return self . _wrapped else : return self . obj | returns the object instead of instance |
61,338 | def makeStatic ( ) : p = lambda value : inspect . ismethod ( value ) or inspect . isfunction ( value ) for eachMethod in inspect . getmembers ( underscore , predicate = p ) : m = eachMethod [ 0 ] if not hasattr ( _ , m ) : def caller ( a ) : def execute ( * args ) : if len ( args ) == 1 : r = getattr ( underscore ( args [ 0 ] ) , a ) ( ) elif len ( args ) > 1 : rargs = args [ 1 : ] r = getattr ( underscore ( args [ 0 ] ) , a ) ( * rargs ) else : r = getattr ( underscore ( [ ] ) , a ) ( ) return r return execute _ . __setattr__ ( m , caller ( m ) ) _ . __setattr__ ( "underscore" , underscore ) _ . templateSettings = { } | Provide static access to underscore class |
61,339 | def init ( ) : global _users , _names _configure_app ( app ) _users , _names = _init_login_manager ( app ) _configure_logger ( ) init_scheduler ( app . config . get ( 'SQLALCHEMY_DATABASE_URI' ) ) db . init ( app . config . get ( 'SQLALCHEMY_DATABASE_URI' ) ) | Initialise and configure the app database scheduler etc . |
61,340 | def _configure_app ( app_ ) : app_ . url_map . strict_slashes = False app_ . config . from_object ( default_settings ) app_ . config . from_envvar ( 'JOB_CONFIG' , silent = True ) db_url = app_ . config . get ( 'SQLALCHEMY_DATABASE_URI' ) if not db_url : raise Exception ( 'No db_url in config' ) app_ . wsgi_app = ProxyFix ( app_ . wsgi_app ) global SSL_VERIFY if app_ . config . get ( 'SSL_VERIFY' ) in [ 'False' , 'FALSE' , '0' , False , 0 ] : SSL_VERIFY = False else : SSL_VERIFY = True return app_ | Configure the Flask WSGI app . |
61,341 | def _init_login_manager ( app_ ) : login_manager = flogin . LoginManager ( ) login_manager . setup_app ( app_ ) login_manager . anonymous_user = Anonymous login_manager . login_view = "login" users = { app_ . config [ 'USERNAME' ] : User ( 'Admin' , 0 ) } names = dict ( ( int ( v . get_id ( ) ) , k ) for k , v in users . items ( ) ) @ login_manager . user_loader def load_user ( userid ) : userid = int ( userid ) name = names . get ( userid ) return users . get ( name ) return users , names | Initialise and configure the login manager . |
61,342 | def _configure_logger_for_production ( logger ) : stderr_handler = logging . StreamHandler ( sys . stderr ) stderr_handler . setLevel ( logging . INFO ) if 'STDERR' in app . config : logger . addHandler ( stderr_handler ) file_handler = logging . handlers . RotatingFileHandler ( app . config . get ( 'LOG_FILE' ) , maxBytes = 67108864 , backupCount = 5 ) file_handler . setLevel ( logging . INFO ) if 'LOG_FILE' in app . config : logger . addHandler ( file_handler ) mail_handler = logging . handlers . SMTPHandler ( '127.0.0.1' , app . config . get ( 'FROM_EMAIL' ) , app . config . get ( 'ADMINS' , [ ] ) , 'CKAN Service Error' ) mail_handler . setLevel ( logging . ERROR ) if 'FROM_EMAIL' in app . config : logger . addHandler ( mail_handler ) | Configure the given logger for production deployment . |
61,343 | def _configure_logger ( ) : if not app . debug : _configure_logger_for_production ( logging . getLogger ( ) ) elif not app . testing : _configure_logger_for_debugging ( logging . getLogger ( ) ) | Configure the logging module . |
61,344 | def init_scheduler ( db_uri ) : global scheduler scheduler = apscheduler . Scheduler ( ) scheduler . misfire_grace_time = 3600 scheduler . add_jobstore ( sqlalchemy_store . SQLAlchemyJobStore ( url = db_uri ) , 'default' ) scheduler . add_listener ( job_listener , events . EVENT_JOB_EXECUTED | events . EVENT_JOB_MISSED | events . EVENT_JOB_ERROR ) return scheduler | Initialise and configure the scheduler . |
61,345 | def job_listener ( event ) : job_id = event . job . args [ 0 ] if event . code == events . EVENT_JOB_MISSED : db . mark_job_as_missed ( job_id ) elif event . exception : if isinstance ( event . exception , util . JobError ) : error_object = event . exception . as_dict ( ) else : error_object = "\n" . join ( traceback . format_tb ( event . traceback ) + [ repr ( event . exception ) ] ) db . mark_job_as_errored ( job_id , error_object ) else : db . mark_job_as_completed ( job_id , event . retval ) api_key = db . get_job ( job_id ) [ "api_key" ] result_ok = send_result ( job_id , api_key ) if not result_ok : db . mark_job_as_failed_to_post_result ( job_id ) if "_TEST_CALLBACK_URL" in app . config : requests . get ( app . config [ "_TEST_CALLBACK_URL" ] ) | Listens to completed job |
61,346 | def status ( ) : job_types = async_types . keys ( ) + sync_types . keys ( ) counts = { } for job_status in job_statuses : counts [ job_status ] = db . ENGINE . execute ( db . JOBS_TABLE . count ( ) . where ( db . JOBS_TABLE . c . status == job_status ) ) . first ( ) [ 0 ] return flask . jsonify ( version = 0.1 , job_types = job_types , name = app . config . get ( 'NAME' , 'example' ) , stats = counts ) | Show version available job types and name of service . |
61,347 | def login ( ) : username = None password = None next = flask . request . args . get ( 'next' ) auth = flask . request . authorization if flask . request . method == 'POST' : username = flask . request . form [ 'username' ] password = flask . request . form [ 'password' ] if auth and auth . type == 'basic' : username = auth . username password = auth . password if not flogin . current_user . is_active : error = 'You have to login with proper credentials' if username and password : if check_auth ( username , password ) : user = _users . get ( username ) if user : if flogin . login_user ( user ) : return flask . redirect ( next or flask . url_for ( "user" ) ) error = 'Could not log in user.' else : error = 'User not found.' else : error = 'Wrong username or password.' else : error = 'No username or password.' return flask . Response ( 'Could not verify your access level for that URL.\n {}' . format ( error ) , 401 , { str ( 'WWW-Authenticate' ) : str ( 'Basic realm="Login Required"' ) } ) return flask . redirect ( next or flask . url_for ( "user" ) ) | Log in as administrator |
61,348 | def user ( ) : user = flogin . current_user return flask . jsonify ( { 'id' : user . get_id ( ) , 'name' : user . name , 'is_active' : user . is_active ( ) , 'is_anonymous' : user . is_anonymous } ) | Show information about the current user |
61,349 | def logout ( ) : flogin . logout_user ( ) next = flask . request . args . get ( 'next' ) return flask . redirect ( next or flask . url_for ( "user" ) ) | Log out the active user |
61,350 | def job_list ( ) : args = dict ( ( key , value ) for key , value in flask . request . args . items ( ) ) limit = args . pop ( '_limit' , 100 ) offset = args . pop ( '_offset' , 0 ) select = sql . select ( [ db . JOBS_TABLE . c . job_id ] , from_obj = [ db . JOBS_TABLE . outerjoin ( db . METADATA_TABLE , db . JOBS_TABLE . c . job_id == db . METADATA_TABLE . c . job_id ) ] ) . group_by ( db . JOBS_TABLE . c . job_id ) . order_by ( db . JOBS_TABLE . c . requested_timestamp . desc ( ) ) . limit ( limit ) . offset ( offset ) status = args . pop ( '_status' , None ) if status : select = select . where ( db . JOBS_TABLE . c . status == status ) ors = [ ] for key , value in args . iteritems ( ) : key = unicode ( key ) ors . append ( sql . and_ ( db . METADATA_TABLE . c . key == key , db . METADATA_TABLE . c . value == value ) ) if ors : select = select . where ( sql . or_ ( * ors ) ) select = select . having ( sql . func . count ( db . JOBS_TABLE . c . job_id ) == len ( ors ) ) result = db . ENGINE . execute ( select ) listing = [ ] for ( job_id , ) in result : listing . append ( flask . url_for ( 'job_status' , job_id = job_id ) ) return flask . jsonify ( list = listing ) | List all jobs . |
61,351 | def job_status ( job_id , show_job_key = False , ignore_auth = False ) : job_dict = db . get_job ( job_id ) if not job_dict : return json . dumps ( { 'error' : 'job_id not found' } ) , 404 , headers if not ignore_auth and not is_authorized ( job_dict ) : return json . dumps ( { 'error' : 'not authorized' } ) , 403 , headers job_dict . pop ( 'api_key' , None ) if not show_job_key : job_dict . pop ( 'job_key' , None ) return flask . Response ( json . dumps ( job_dict , cls = DatetimeJsonEncoder ) , mimetype = 'application/json' ) | Show a specific job . |
61,352 | def job_delete ( job_id ) : conn = db . ENGINE . connect ( ) job = db . get_job ( job_id ) if not job : return json . dumps ( { 'error' : 'job_id not found' } ) , 404 , headers if not is_authorized ( job ) : return json . dumps ( { 'error' : 'not authorized' } ) , 403 , headers trans = conn . begin ( ) try : conn . execute ( db . JOBS_TABLE . delete ( ) . where ( db . JOBS_TABLE . c . job_id == job_id ) ) trans . commit ( ) return json . dumps ( { 'success' : True } ) , 200 , headers except Exception , e : trans . rollback ( ) return json . dumps ( { 'error' : str ( e ) } ) , 409 , headers finally : conn . close ( ) | Deletes the job together with its logs and metadata . |
61,353 | def clear_jobs ( ) : if not is_authorized ( ) : return json . dumps ( { 'error' : 'not authorized' } ) , 403 , headers days = flask . request . args . get ( 'days' , None ) return _clear_jobs ( days ) | Clear old jobs |
61,354 | def job_data ( job_id ) : job_dict = db . get_job ( job_id ) if not job_dict : return json . dumps ( { 'error' : 'job_id not found' } ) , 404 , headers if not is_authorized ( job_dict ) : return json . dumps ( { 'error' : 'not authorized' } ) , 403 , headers if job_dict [ 'error' ] : return json . dumps ( { 'error' : job_dict [ 'error' ] } ) , 409 , headers content_type = job_dict [ 'metadata' ] . get ( 'mimetype' ) return flask . Response ( job_dict [ 'data' ] , mimetype = content_type ) | Get the raw data that the job returned . The mimetype will be the value provided in the metdata for the key mimetype . |
61,355 | def job ( job_id = None ) : if not job_id : job_id = str ( uuid . uuid4 ( ) ) job_key = str ( uuid . uuid4 ( ) ) try : input = flask . request . json except werkzeug . exceptions . BadRequest : return json . dumps ( { "error" : "Malformed json" } ) , 409 , headers if ( not input and 'application/json' in flask . request . content_type . lower ( ) ) : try : input = json . loads ( flask . request . data ) except ValueError : pass if not input : return json . dumps ( { "error" : ( 'Not recognised as json, make ' 'sure content type is application/' 'json' ) } ) , 409 , headers ACCEPTED_ARGUMENTS = set ( [ 'job_type' , 'data' , 'metadata' , 'result_url' , 'api_key' , 'metadata' ] ) extra_keys = set ( input . keys ( ) ) - ACCEPTED_ARGUMENTS if extra_keys : return json . dumps ( { "error" : ( 'Too many arguments. Extra keys are {}' . format ( ', ' . join ( extra_keys ) ) ) } ) , 409 , headers result_url = input . get ( 'result_url' ) if result_url and not result_url . startswith ( 'http' ) : return json . dumps ( { "error" : "result_url has to start with http" } ) , 409 , headers job_type = input . get ( 'job_type' ) if not job_type : return json . dumps ( { "error" : "Please specify a job type" } ) , 409 , headers job_types = async_types . keys ( ) + sync_types . keys ( ) if job_type not in job_types : error_string = ( 'Job type {} not available. Available job types are {}' ) . format ( job_type , ', ' . join ( job_types ) ) return json . dumps ( { "error" : error_string } ) , 409 , headers api_key = input . get ( 'api_key' ) if not api_key : return json . dumps ( { "error" : "Please provide your API key." } ) , 409 , headers metadata = input . get ( 'metadata' , { } ) if not isinstance ( metadata , dict ) : return json . dumps ( { "error" : "metadata has to be a json object" } ) , 409 , headers synchronous_job = sync_types . get ( job_type ) if synchronous_job : return run_synchronous_job ( synchronous_job , job_id , job_key , input ) else : asynchronous_job = async_types . get ( job_type ) return run_asynchronous_job ( asynchronous_job , job_id , job_key , input ) | Submit a job . If no id is provided a random id will be generated . |
61,356 | def is_authorized ( job = None ) : if flogin . current_user . is_authenticated : return True if job : job_key = flask . request . headers . get ( 'Authorization' ) if job_key == app . config . get ( 'SECRET_KEY' ) : return True return job [ 'job_key' ] == job_key return False | Returns true if the request is authorized for the job if provided . If no job is provided the user has to be admin to be authorized . |
61,357 | def send_result ( job_id , api_key = None ) : job_dict = db . get_job ( job_id ) result_url = job_dict . get ( 'result_url' ) if not result_url : db . delete_api_key ( job_id ) return True api_key_from_job = job_dict . pop ( 'api_key' , None ) if not api_key : api_key = api_key_from_job headers = { 'Content-Type' : 'application/json' } if api_key : if ':' in api_key : header , key = api_key . split ( ':' ) else : header , key = 'Authorization' , api_key headers [ header ] = key try : result = requests . post ( result_url , data = json . dumps ( job_dict , cls = DatetimeJsonEncoder ) , headers = headers , verify = SSL_VERIFY ) db . delete_api_key ( job_id ) except requests . ConnectionError : return False return result . status_code == requests . codes . ok | Send results to where requested . |
61,358 | def init ( uri , echo = False ) : global ENGINE , _METADATA , JOBS_TABLE , METADATA_TABLE , LOGS_TABLE ENGINE = sqlalchemy . create_engine ( uri , echo = echo , convert_unicode = True ) _METADATA = sqlalchemy . MetaData ( ENGINE ) JOBS_TABLE = _init_jobs_table ( ) METADATA_TABLE = _init_metadata_table ( ) LOGS_TABLE = _init_logs_table ( ) _METADATA . create_all ( ENGINE ) | Initialise the database . |
61,359 | def get_job ( job_id ) : if job_id : job_id = unicode ( job_id ) result = ENGINE . execute ( JOBS_TABLE . select ( ) . where ( JOBS_TABLE . c . job_id == job_id ) ) . first ( ) if not result : return None result_dict = { } for field in result . keys ( ) : value = getattr ( result , field ) if value is None : result_dict [ field ] = value elif field in ( 'sent_data' , 'data' , 'error' ) : result_dict [ field ] = json . loads ( value ) elif isinstance ( value , datetime . datetime ) : result_dict [ field ] = value . isoformat ( ) else : result_dict [ field ] = unicode ( value ) result_dict [ 'metadata' ] = _get_metadata ( job_id ) result_dict [ 'logs' ] = _get_logs ( job_id ) return result_dict | Return the job with the given job_id as a dict . |
61,360 | def add_pending_job ( job_id , job_key , job_type , api_key , data = None , metadata = None , result_url = None ) : if not data : data = { } data = json . dumps ( data ) if job_id : job_id = unicode ( job_id ) if job_type : job_type = unicode ( job_type ) if result_url : result_url = unicode ( result_url ) if api_key : api_key = unicode ( api_key ) if job_key : job_key = unicode ( job_key ) data = unicode ( data ) if not metadata : metadata = { } conn = ENGINE . connect ( ) trans = conn . begin ( ) try : conn . execute ( JOBS_TABLE . insert ( ) . values ( job_id = job_id , job_type = job_type , status = 'pending' , requested_timestamp = datetime . datetime . now ( ) , sent_data = data , result_url = result_url , api_key = api_key , job_key = job_key ) ) inserts = [ ] for key , value in metadata . items ( ) : type_ = 'string' if not isinstance ( value , basestring ) : value = json . dumps ( value ) type_ = 'json' key = unicode ( key ) value = unicode ( value ) inserts . append ( { "job_id" : job_id , "key" : key , "value" : value , "type" : type_ } ) if inserts : conn . execute ( METADATA_TABLE . insert ( ) , inserts ) trans . commit ( ) except Exception : trans . rollback ( ) raise finally : conn . close ( ) | Add a new job with status pending to the jobs table . |
61,361 | def _validate_error ( error ) : if error is None : return None elif isinstance ( error , basestring ) : return { "message" : error } else : try : message = error [ "message" ] if isinstance ( message , basestring ) : return error else : raise InvalidErrorObjectError ( "error['message'] must be a string" ) except ( TypeError , KeyError ) : raise InvalidErrorObjectError ( "error must be either a string or a dict with a message key" ) | Validate and return the given error object . |
61,362 | def _update_job ( job_id , job_dict ) : if job_id : job_id = unicode ( job_id ) if "error" in job_dict : job_dict [ "error" ] = _validate_error ( job_dict [ "error" ] ) job_dict [ "error" ] = json . dumps ( job_dict [ "error" ] ) job_dict [ "error" ] = unicode ( job_dict [ "error" ] ) if "data" in job_dict : job_dict [ "data" ] = unicode ( job_dict [ "data" ] ) ENGINE . execute ( JOBS_TABLE . update ( ) . where ( JOBS_TABLE . c . job_id == job_id ) . values ( ** job_dict ) ) | Update the database row for the given job_id with the given job_dict . |
61,363 | def mark_job_as_completed ( job_id , data = None ) : update_dict = { "status" : "complete" , "data" : json . dumps ( data ) , "finished_timestamp" : datetime . datetime . now ( ) , } _update_job ( job_id , update_dict ) | Mark a job as completed successfully . |
61,364 | def mark_job_as_errored ( job_id , error_object ) : update_dict = { "status" : "error" , "error" : error_object , "finished_timestamp" : datetime . datetime . now ( ) , } _update_job ( job_id , update_dict ) | Mark a job as failed with an error . |
61,365 | def _init_jobs_table ( ) : _jobs_table = sqlalchemy . Table ( 'jobs' , _METADATA , sqlalchemy . Column ( 'job_id' , sqlalchemy . UnicodeText , primary_key = True ) , sqlalchemy . Column ( 'job_type' , sqlalchemy . UnicodeText ) , sqlalchemy . Column ( 'status' , sqlalchemy . UnicodeText , index = True ) , sqlalchemy . Column ( 'data' , sqlalchemy . UnicodeText ) , sqlalchemy . Column ( 'error' , sqlalchemy . UnicodeText ) , sqlalchemy . Column ( 'requested_timestamp' , sqlalchemy . DateTime ) , sqlalchemy . Column ( 'finished_timestamp' , sqlalchemy . DateTime ) , sqlalchemy . Column ( 'sent_data' , sqlalchemy . UnicodeText ) , sqlalchemy . Column ( 'result_url' , sqlalchemy . UnicodeText ) , sqlalchemy . Column ( 'api_key' , sqlalchemy . UnicodeText ) , sqlalchemy . Column ( 'job_key' , sqlalchemy . UnicodeText ) , ) return _jobs_table | Initialise the jobs table in the db . |
61,366 | def _init_metadata_table ( ) : _metadata_table = sqlalchemy . Table ( 'metadata' , _METADATA , sqlalchemy . Column ( 'job_id' , sqlalchemy . ForeignKey ( "jobs.job_id" , ondelete = "CASCADE" ) , nullable = False , primary_key = True ) , sqlalchemy . Column ( 'key' , sqlalchemy . UnicodeText , primary_key = True ) , sqlalchemy . Column ( 'value' , sqlalchemy . UnicodeText , index = True ) , sqlalchemy . Column ( 'type' , sqlalchemy . UnicodeText ) , ) return _metadata_table | Initialise the metadata table in the db . |
61,367 | def _init_logs_table ( ) : _logs_table = sqlalchemy . Table ( 'logs' , _METADATA , sqlalchemy . Column ( 'job_id' , sqlalchemy . ForeignKey ( "jobs.job_id" , ondelete = "CASCADE" ) , nullable = False ) , sqlalchemy . Column ( 'timestamp' , sqlalchemy . DateTime ) , sqlalchemy . Column ( 'message' , sqlalchemy . UnicodeText ) , sqlalchemy . Column ( 'level' , sqlalchemy . UnicodeText ) , sqlalchemy . Column ( 'module' , sqlalchemy . UnicodeText ) , sqlalchemy . Column ( 'funcName' , sqlalchemy . UnicodeText ) , sqlalchemy . Column ( 'lineno' , sqlalchemy . Integer ) ) return _logs_table | Initialise the logs table in the db . |
61,368 | def _get_metadata ( job_id ) : job_id = unicode ( job_id ) results = ENGINE . execute ( METADATA_TABLE . select ( ) . where ( METADATA_TABLE . c . job_id == job_id ) ) . fetchall ( ) metadata = { } for row in results : value = row [ 'value' ] if row [ 'type' ] == 'json' : value = json . loads ( value ) metadata [ row [ 'key' ] ] = value return metadata | Return any metadata for the given job_id from the metadata table . |
61,369 | def _get_logs ( job_id ) : job_id = unicode ( job_id ) results = ENGINE . execute ( LOGS_TABLE . select ( ) . where ( LOGS_TABLE . c . job_id == job_id ) ) . fetchall ( ) results = [ dict ( result ) for result in results ] for result in results : result . pop ( "job_id" ) return results | Return any logs for the given job_id from the logs table . |
61,370 | def check_node_attributes ( pattern , node , * attributes ) : for attribute_name in attributes : attribute = node . get ( attribute_name ) if attribute is not None and pattern . search ( attribute ) : return True return False | Searches match in attributes against given pattern and if finds the match against any of them returns True . |
61,371 | def generate_hash_id ( node ) : try : content = tostring ( node ) except Exception : logger . exception ( "Generating of hash failed" ) content = to_bytes ( repr ( node ) ) hash_id = md5 ( content ) . hexdigest ( ) return hash_id [ : 8 ] | Generates a hash_id for the node in question . |
61,372 | def get_link_density ( node , node_text = None ) : if node_text is None : node_text = node . text_content ( ) node_text = normalize_whitespace ( node_text . strip ( ) ) text_length = len ( node_text ) if text_length == 0 : return 0.0 links_length = sum ( map ( _get_normalized_text_length , node . findall ( ".//a" ) ) ) img_bonuses = 50 * len ( node . findall ( ".//img" ) ) links_length = max ( 0 , links_length - img_bonuses ) return links_length / text_length | Computes the ratio for text in given node and text in links contained in the node . It is computed from number of characters in the texts . |
61,373 | def is_unlikely_node ( node ) : unlikely = check_node_attributes ( CLS_UNLIKELY , node , "class" , "id" ) maybe = check_node_attributes ( CLS_MAYBE , node , "class" , "id" ) return bool ( unlikely and not maybe and node . tag != "body" ) | Short helper for checking unlikely status . |
61,374 | def score_candidates ( nodes ) : MIN_HIT_LENTH = 25 candidates = { } for node in nodes : logger . debug ( "* Scoring candidate %s %r" , node . tag , node . attrib ) parent = node . getparent ( ) if parent is None : logger . debug ( "Skipping candidate - parent node is 'None'." ) continue grand = parent . getparent ( ) if grand is None : logger . debug ( "Skipping candidate - grand parent node is 'None'." ) continue inner_text = node . text_content ( ) . strip ( ) if len ( inner_text ) < MIN_HIT_LENTH : logger . debug ( "Skipping candidate - inner text < %d characters." , MIN_HIT_LENTH ) continue if parent not in candidates : candidates [ parent ] = ScoredNode ( parent ) if grand not in candidates : candidates [ grand ] = ScoredNode ( grand ) content_score = 1 if inner_text : commas_count = inner_text . count ( "," ) content_score += commas_count * 0.25 logger . debug ( "Bonus points for %d commas." , commas_count ) double_quotes_count = inner_text . count ( '"' ) content_score += double_quotes_count * - 0.5 logger . debug ( "Penalty points for %d double-quotes." , double_quotes_count ) length_points = len ( inner_text ) / 100 content_score += min ( length_points , 3.0 ) logger . debug ( "Bonus points for length of text: %f" , length_points ) logger . debug ( "Bonus points for parent %s %r with score %f: %f" , parent . tag , parent . attrib , candidates [ parent ] . content_score , content_score ) candidates [ parent ] . content_score += content_score logger . debug ( "Bonus points for grand %s %r with score %f: %f" , grand . tag , grand . attrib , candidates [ grand ] . content_score , content_score / 2.0 ) candidates [ grand ] . content_score += content_score / 2.0 if node not in candidates : candidates [ node ] = ScoredNode ( node ) candidates [ node ] . content_score += content_score for candidate in candidates . values ( ) : adjustment = 1.0 - get_link_density ( candidate . node ) candidate . content_score *= adjustment logger . debug ( "Link density adjustment for %s %r: %f" , candidate . node . tag , candidate . node . attrib , adjustment ) return candidates | Given a list of potential nodes find some initial scores to start |
61,375 | def getTime ( self ) : T = 1 / float ( self . samp [ self . nrates - 1 ] ) endtime = self . endsamp [ self . nrates - 1 ] * T t = numpy . linspace ( 0 , endtime , self . endsamp [ self . nrates - 1 ] ) return t | Actually this function creates a time stamp vector based on the number of samples and sample rate . |
61,376 | def getAnalogID ( self , num ) : listidx = self . An . index ( num ) return self . Ach_id [ listidx ] | Returns the COMTRADE ID of a given channel number . The number to be given is the same of the COMTRADE header . |
61,377 | def getDigitalID ( self , num ) : listidx = self . Dn . index ( num ) return self . Dch_id [ listidx ] | Reads the COMTRADE ID of a given channel number . The number to be given is the same of the COMTRADE header . |
61,378 | def getAnalogType ( self , num ) : listidx = self . An . index ( num ) unit = self . uu [ listidx ] if unit == 'kV' or unit == 'V' : return 'V' elif unit == 'A' or unit == 'kA' : return 'I' else : print 'Unknown channel type' return 0 | Returns the type of the channel num based on its unit stored in the Comtrade header file . Returns V for a voltage channel and I for a current channel . |
61,379 | def ReadDataFile ( self ) : if os . path . isfile ( self . filename [ 0 : - 4 ] + '.dat' ) : filename = self . filename [ 0 : - 4 ] + '.dat' elif os . path . isfile ( self . filename [ 0 : - 4 ] + '.DAT' ) : filename = self . filename [ 0 : - 4 ] + '.DAT' else : print "Data file File not found." return 0 self . filehandler = open ( filename , 'rb' ) self . DatFileContent = self . filehandler . read ( ) self . filehandler . close ( ) return 1 | Reads the contents of the Comtrade . dat file and store them in a private variable . For accessing a specific channel data see methods getAnalogData and getDigitalData . |
61,380 | def getAnalogChannelData ( self , ChNumber ) : if not self . DatFileContent : print "No data file content. Use the method ReadDataFile first" return 0 if ( ChNumber > self . A ) : print "Channel number greater than the total number of channels." return 0 str_struct = "ii%dh" % ( self . A + int ( numpy . ceil ( ( float ( self . D ) / float ( 16 ) ) ) ) ) NB = 4 + 4 + self . A * 2 + int ( numpy . ceil ( ( float ( self . D ) / float ( 16 ) ) ) ) * 2 N = self . getNumberOfSamples ( ) values = numpy . empty ( ( N , 1 ) ) ch_index = self . An . index ( ChNumber ) for i in range ( N ) : data = struct . unpack ( str_struct , self . DatFileContent [ i * NB : ( i * NB ) + NB ] ) values [ i ] = data [ ChNumber + 1 ] values = values * self . a [ ch_index ] values = values + self . b [ ch_index ] return values | Returns an array of numbers containing the data values of the channel number ChNumber . ChNumber is the number of the channal as in . cfg file . |
61,381 | def initLogger ( ) : global logger logger = logging . getLogger ( 'root' ) logger . setLevel ( logging . DEBUG ) ch = logging . StreamHandler ( sys . stdout ) ch . setLevel ( logging . INFO ) formatter = logging . Formatter ( "[%(asctime)s] %(levelname)s: %(message)s" , "%Y-%m-%d %H:%M:%S" ) ch . setFormatter ( formatter ) logger . addHandler ( ch ) | This code taken from Matt s Suspenders for initializing a logger |
61,382 | def writeSeqsToFiles ( seqArray , seqFNPrefix , offsetFN , uniformLength ) : if uniformLength : offsets = np . lib . format . open_memmap ( offsetFN , 'w+' , '<u8' , ( 1 , ) ) offsets [ 0 ] = uniformLength d = { '$' : 0 , 'A' : 1 , 'C' : 2 , 'G' : 3 , 'N' : 4 , 'T' : 5 } dArr = np . add ( np . zeros ( dtype = '<u1' , shape = ( 256 , ) ) , len ( d . keys ( ) ) ) for c in d . keys ( ) : dArr [ ord ( c ) ] = d [ c ] seqLen = uniformLength b = np . reshape ( seqArray , ( - 1 , seqLen ) ) numSeqs = b . shape [ 0 ] t = b . transpose ( ) for i in xrange ( 0 , seqLen ) : seqs = np . lib . format . open_memmap ( seqFNPrefix + '.' + str ( i ) + '.npy' , 'w+' , '<u1' , ( numSeqs , ) ) chunkSize = 1000000 j = 0 while chunkSize * j < numSeqs : seqs [ chunkSize * j : chunkSize * ( j + 1 ) ] = dArr [ t [ - i - 1 ] [ chunkSize * j : chunkSize * ( j + 1 ) ] ] j += 1 del seqs else : lenSums = np . add ( 1 , np . where ( seqArray == 36 ) [ 0 ] ) numSeqs = lenSums . shape [ 0 ] totalLen = lenSums [ - 1 ] seqFN = seqFNPrefix + '.npy' seqs = np . lib . format . open_memmap ( seqFN , 'w+' , '<u1' , ( totalLen , ) ) offsets = np . lib . format . open_memmap ( offsetFN , 'w+' , '<u8' , ( numSeqs + 1 , ) ) offsets [ 1 : ] = lenSums d = { '$' : 0 , 'A' : 1 , 'C' : 2 , 'G' : 3 , 'N' : 4 , 'T' : 5 } dArr = np . add ( np . zeros ( dtype = '<u1' , shape = ( 256 , ) ) , len ( d . keys ( ) ) ) for c in d . keys ( ) : dArr [ ord ( c ) ] = d [ c ] chunkSize = 1000000 i = 0 while chunkSize * i < seqArray . shape [ 0 ] : seqs [ chunkSize * i : chunkSize * ( i + 1 ) ] = dArr [ seqArray [ chunkSize * i : chunkSize * ( i + 1 ) ] ] i += 1 del lenSums del seqs del offsets return ( seqFNPrefix , offsetFN ) | This function takes a seqArray and saves the values to a memmap file that can be accessed for multi - processing . Additionally it saves some offset indices in a numpy file for quicker string access . |
61,383 | def decompressBWT ( inputDir , outputDir , numProcs , logger ) : msbwt = MultiStringBWT . CompressedMSBWT ( ) msbwt . loadMsbwt ( inputDir , logger ) outputFile = np . lib . format . open_memmap ( outputDir + '/msbwt.npy' , 'w+' , '<u1' , ( msbwt . getTotalSize ( ) , ) ) del outputFile worksize = 1000000 tups = [ None ] * ( msbwt . getTotalSize ( ) / worksize + 1 ) x = 0 if msbwt . getTotalSize ( ) > worksize : for x in xrange ( 0 , msbwt . getTotalSize ( ) / worksize ) : tups [ x ] = ( inputDir , outputDir , x * worksize , ( x + 1 ) * worksize ) tups [ - 1 ] = ( inputDir , outputDir , ( x + 1 ) * worksize , msbwt . getTotalSize ( ) ) else : tups [ 0 ] = ( inputDir , outputDir , 0 , msbwt . getTotalSize ( ) ) if numProcs > 1 : myPool = multiprocessing . Pool ( numProcs ) rets = myPool . map ( decompressBWTPoolProcess , tups ) else : rets = [ ] for tup in tups : rets . append ( decompressBWTPoolProcess ( tup ) ) | This is called for taking a BWT and decompressing it back out to it s original form . While unusual to do it s included in this package for completion purposes . |
61,384 | def decompressBWTPoolProcess ( tup ) : ( inputDir , outputDir , startIndex , endIndex ) = tup if startIndex == endIndex : return True msbwt = MultiStringBWT . CompressedMSBWT ( ) msbwt . loadMsbwt ( inputDir , None ) outputBwt = np . load ( outputDir + '/msbwt.npy' , 'r+' ) outputBwt [ startIndex : endIndex ] = msbwt . getBWTRange ( startIndex , endIndex ) return True | Individual process for decompression |
61,385 | def clearAuxiliaryData ( dirName ) : if dirName != None : if os . path . exists ( dirName + '/auxiliary.npy' ) : os . remove ( dirName + '/auxiliary.npy' ) if os . path . exists ( dirName + '/totalCounts.p' ) : os . remove ( dirName + '/totalCounts.p' ) if os . path . exists ( dirName + '/totalCounts.npy' ) : os . remove ( dirName + '/totalCounts.npy' ) if os . path . exists ( dirName + '/fmIndex.npy' ) : os . remove ( dirName + '/fmIndex.npy' ) if os . path . exists ( dirName + '/comp_refIndex.npy' ) : os . remove ( dirName + '/comp_refIndex.npy' ) if os . path . exists ( dirName + '/comp_fmIndex.npy' ) : os . remove ( dirName + '/comp_fmIndex.npy' ) if os . path . exists ( dirName + '/backrefs.npy' ) : os . remove ( dirName + '/backrefs.npy' ) | This function removes auxiliary files associated with a given filename |
61,386 | def build_base_document ( dom , return_fragment = True ) : body_element = dom . find ( ".//body" ) if body_element is None : fragment = fragment_fromstring ( '<div id="readabilityBody"/>' ) fragment . append ( dom ) else : body_element . tag = "div" body_element . set ( "id" , "readabilityBody" ) fragment = body_element return document_from_fragment ( fragment , return_fragment ) | Builds a base document with the body as root . |
61,387 | def check_siblings ( candidate_node , candidate_list ) : candidate_css = candidate_node . node . get ( "class" ) potential_target = candidate_node . content_score * 0.2 sibling_target_score = potential_target if potential_target > 10 else 10 parent = candidate_node . node . getparent ( ) siblings = parent . getchildren ( ) if parent is not None else [ ] for sibling in siblings : append = False content_bonus = 0 if sibling is candidate_node . node : append = True if candidate_css and sibling . get ( "class" ) == candidate_css : content_bonus += candidate_node . content_score * 0.2 if sibling in candidate_list : adjusted_score = candidate_list [ sibling ] . content_score + content_bonus if adjusted_score >= sibling_target_score : append = True if sibling . tag == "p" : link_density = get_link_density ( sibling ) content = sibling . text_content ( ) content_length = len ( content ) if content_length > 80 and link_density < 0.25 : append = True elif content_length < 80 and link_density == 0 : if ". " in content : append = True if append : logger . debug ( "Sibling appended: %s %r" , sibling . tag , sibling . attrib ) if sibling . tag not in ( "div" , "p" ) : sibling . tag = "div" if candidate_node . node != sibling : candidate_node . node . append ( sibling ) return candidate_node | Looks through siblings for content that might also be related . Things like preambles content split by ads that we removed etc . |
61,388 | def clean_document ( node ) : if node is None or len ( node ) == 0 : return None logger . debug ( "\n\n-------------- CLEANING DOCUMENT -----------------" ) to_drop = [ ] for n in node . iter ( ) : if "style" in n . attrib : n . set ( "style" , "" ) if n . tag in ( "object" , "embed" ) and not ok_embedded_video ( n ) : logger . debug ( "Dropping node %s %r" , n . tag , n . attrib ) to_drop . append ( n ) if n . tag in ( "h1" , "h2" , "h3" , "h4" ) and get_class_weight ( n ) < 0 : logger . debug ( "Dropping <%s>, it's insignificant" , n . tag ) to_drop . append ( n ) if n . tag in ( "h3" , "h4" ) and get_link_density ( n ) > 0.33 : logger . debug ( "Dropping <%s>, it's insignificant" , n . tag ) to_drop . append ( n ) if n . tag in ( "div" , "p" ) : text_content = shrink_text ( n . text_content ( ) ) if len ( text_content ) < 5 and not n . getchildren ( ) : logger . debug ( "Dropping %s %r without content." , n . tag , n . attrib ) to_drop . append ( n ) if clean_conditionally ( n ) : to_drop . append ( n ) drop_nodes_with_parents ( to_drop ) return node | Cleans up the final document we return as the readable article . |
61,389 | def clean_conditionally ( node ) : if node . tag not in ( 'form' , 'table' , 'ul' , 'div' , 'p' ) : return weight = get_class_weight ( node ) content_score = 0 if weight + content_score < 0 : logger . debug ( 'Dropping conditional node' ) logger . debug ( 'Weight + score < 0' ) return True commas_count = node . text_content ( ) . count ( ',' ) if commas_count < 10 : logger . debug ( "There are %d commas so we're processing more." , commas_count ) p = len ( node . findall ( './/p' ) ) img = len ( node . findall ( './/img' ) ) li = len ( node . findall ( './/li' ) ) - 100 inputs = len ( node . findall ( './/input' ) ) embed = 0 embeds = node . findall ( './/embed' ) for e in embeds : if ok_embedded_video ( e ) : embed += 1 link_density = get_link_density ( node ) content_length = len ( node . text_content ( ) ) remove_node = False if li > p and node . tag != 'ul' and node . tag != 'ol' : logger . debug ( 'Conditional drop: li > p and not ul/ol' ) remove_node = True elif inputs > p / 3.0 : logger . debug ( 'Conditional drop: inputs > p/3.0' ) remove_node = True elif content_length < 25 and ( img == 0 or img > 2 ) : logger . debug ( 'Conditional drop: len < 25 and 0/>2 images' ) remove_node = True elif weight < 25 and link_density > 0.2 : logger . debug ( 'Conditional drop: weight small (%f) and link is dense (%f)' , weight , link_density ) remove_node = True elif weight >= 25 and link_density > 0.5 : logger . debug ( 'Conditional drop: weight big but link heavy' ) remove_node = True elif ( embed == 1 and content_length < 75 ) or embed > 1 : logger . debug ( 'Conditional drop: embed w/o much content or many embed' ) remove_node = True if remove_node : logger . debug ( 'Node will be removed: %s %r %s' , node . tag , node . attrib , node . text_content ( ) [ : 30 ] ) return remove_node return False | Remove the clean_el if it looks like bad content based on rules . |
61,390 | def find_candidates ( document ) : nodes_to_score = set ( ) should_remove = set ( ) for node in document . iter ( ) : if is_unlikely_node ( node ) : logger . debug ( "We should drop unlikely: %s %r" , node . tag , node . attrib ) should_remove . add ( node ) elif is_bad_link ( node ) : logger . debug ( "We should drop bad link: %s %r" , node . tag , node . attrib ) should_remove . add ( node ) elif node . tag in SCORABLE_TAGS : nodes_to_score . add ( node ) return score_candidates ( nodes_to_score ) , should_remove | Finds cadidate nodes for the readable version of the article . |
61,391 | def is_bad_link ( node ) : if node . tag != "a" : return False name = node . get ( "name" ) href = node . get ( "href" ) if name and not href : return True if href : href_parts = href . split ( "#" ) if len ( href_parts ) == 2 and len ( href_parts [ 1 ] ) > 25 : return True return False | Helper to determine if the node is link that is useless . |
61,392 | def candidates ( self ) : dom = self . dom if dom is None or len ( dom ) == 0 : return None candidates , unlikely_candidates = find_candidates ( dom ) drop_nodes_with_parents ( unlikely_candidates ) return candidates | Generates list of candidates from the DOM . |
61,393 | def _readable ( self ) : if not self . candidates : logger . info ( "No candidates found in document." ) return self . _handle_no_candidates ( ) best_candidates = sorted ( ( c for c in self . candidates . values ( ) ) , key = attrgetter ( "content_score" ) , reverse = True ) printer = PrettyPrinter ( indent = 2 ) logger . debug ( printer . pformat ( best_candidates ) ) winner = best_candidates [ 0 ] updated_winner = check_siblings ( winner , self . candidates ) updated_winner . node = prep_article ( updated_winner . node ) if updated_winner . node is not None : dom = build_base_document ( updated_winner . node , self . _return_fragment ) else : logger . info ( 'Had candidates but failed to find a cleaned winning DOM.' ) dom = self . _handle_no_candidates ( ) return self . _remove_orphans ( dom . get_element_by_id ( "readabilityBody" ) ) | The readable parsed article |
61,394 | def _handle_no_candidates ( self ) : if self . dom is not None and len ( self . dom ) : dom = prep_article ( self . dom ) dom = build_base_document ( dom , self . _return_fragment ) return self . _remove_orphans ( dom . get_element_by_id ( "readabilityBody" ) ) else : logger . info ( "No document to use." ) return build_error_document ( self . _return_fragment ) | If we fail to find a good candidate we need to find something else . |
61,395 | def fastaIterator ( fastaFN ) : if fastaFN [ len ( fastaFN ) - 3 : ] == '.gz' : fp = gzip . open ( fastaFN , 'r' ) else : fp = open ( fastaFN , 'r' ) label = '' segments = [ ] line = '' for line in fp : if line [ 0 ] == '>' : if label != '' : yield ( label , '' . join ( segments ) ) label = ( line . strip ( '\n' ) [ 1 : ] ) . split ( ' ' ) [ 0 ] segments = [ ] else : segments . append ( line . strip ( '\n' ) ) if label != '' and len ( segments ) > 0 : yield ( label , '' . join ( segments ) ) fp . close ( ) | Iterator that yields tuples containing a sequence label and the sequence itself |
61,396 | def loadBWT ( bwtDir , logger = None ) : if os . path . exists ( bwtDir + '/msbwt.npy' ) : msbwt = MultiStringBWT ( ) msbwt . loadMsbwt ( bwtDir , logger ) return msbwt elif os . path . exists ( bwtDir + '/comp_msbwt.npy' ) : msbwt = CompressedMSBWT ( ) msbwt . loadMsbwt ( bwtDir , logger ) return msbwt else : logger . error ( 'Invalid BWT directory.' ) return None | Generic load function this is recommended for anyone wishing to use this code as it will automatically detect compression and assign the appropriate class preferring the decompressed version if both exist . |
61,397 | def createMSBWTFromSeqs ( seqArray , mergedDir , numProcs , areUniform , logger ) : MSBWTGen . clearAuxiliaryData ( mergedDir ) seqFN = mergedDir + '/seqs.npy' offsetFN = mergedDir + '/offsets.npy' seqCopy = sorted ( seqArray ) if areUniform : uniformLength = len ( seqArray [ 0 ] ) else : uniformLength = 0 seqCopy = '' . join ( seqCopy ) seqCopy = np . fromstring ( seqCopy , dtype = '<u1' ) MSBWTGen . writeSeqsToFiles ( seqCopy , seqFN , offsetFN , uniformLength ) MSBWTGen . createFromSeqs ( seqFN , offsetFN , mergedDir + '/msbwt.npy' , numProcs , areUniform , logger ) | This function takes a series of sequences and creates the BWT using the technique from Cox and Bauer |
61,398 | def createMSBWTFromFastq ( fastqFNs , outputDir , numProcs , areUniform , logger ) : logger . info ( 'Saving sorted sequences...' ) seqFN = outputDir + '/seqs.npy' offsetFN = outputDir + '/offsets.npy' abtFN = outputDir + '/about.npy' bwtFN = outputDir + '/msbwt.npy' MSBWTGen . clearAuxiliaryData ( outputDir ) preprocessFastqs ( fastqFNs , seqFN , offsetFN , abtFN , areUniform , logger ) MSBWTGen . createFromSeqs ( seqFN , offsetFN , bwtFN , numProcs , areUniform , logger ) | This function takes fasta filenames and creates the BWT using the technique from Cox and Bauer by simply loading all string prior to computation |
61,399 | def createMSBWTFromBam ( bamFNs , outputDir , numProcs , areUniform , logger ) : logger . info ( 'Saving sorted sequences...' ) seqFN = outputDir + '/seqs.npy' offsetFN = outputDir + '/offsets.npy' abtFN = outputDir + '/about.npy' bwtFN = outputDir + '/msbwt.npy' MSBWTGen . clearAuxiliaryData ( outputDir ) preprocessBams ( bamFNs , seqFN , offsetFN , abtFN , areUniform , logger ) MSBWTGen . createFromSeqs ( seqFN , offsetFN , bwtFN , numProcs , areUniform , logger ) | This function takes a fasta filename and creates the BWT using the technique from Cox and Bauer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.