idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
1,000
def si_format ( value , precision = 1 , format_str = u'{value} {prefix}' , exp_format_str = u'{value}e{expof10}' ) : svalue , expof10 = split ( value , precision ) value_format = u'%%.%df' % precision value_str = value_format % svalue try : return format_str . format ( value = value_str , prefix = prefix ( expof10 ) . ...
Format value to string with SI prefix using the specified precision .
1,001
def si_parse ( value ) : CRE_10E_NUMBER = re . compile ( r'^\s*(?P<integer>[\+\-]?\d+)?' r'(?P<fraction>.\d+)?\s*([eE]\s*' r'(?P<expof10>[\+\-]?\d+))?$' ) CRE_SI_NUMBER = re . compile ( r'^\s*(?P<number>(?P<integer>[\+\-]?\d+)?' r'(?P<fraction>.\d+)?)\s*' u'(?P<si_unit>[%s])?\s*$' % SI_PREFIX_UNITS ) match = CRE_10E_NU...
Parse a value expressed using SI prefix units to a floating point number .
1,002
def set_status ( self , name , status ) : getattr ( self . system , name ) . status = status return True
Set sensor name status to status .
1,003
def toggle_object_status ( self , objname ) : o = getattr ( self . system , objname ) o . status = not o . status self . system . flush ( ) return o . status
Toggle boolean - valued sensor status between True and False .
1,004
def log ( self ) : logserv = self . system . request_service ( 'LogStoreService' ) return logserv . lastlog ( html = False )
Return recent log entries as a string .
1,005
def load_or_create ( cls , filename = None , no_input = False , create_new = False , ** kwargs ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( '--no_input' , action = 'store_true' ) parser . add_argument ( '--create_new' , action = 'store_true' ) args = parser . parse_args ( ) if args . no_input : pr...
Load system from a dump if dump file exists or create a new system if it does not exist .
1,006
def cmd_namespace ( self ) : import automate ns = dict ( list ( automate . __dict__ . items ( ) ) + list ( self . namespace . items ( ) ) ) return ns
A read - only property that gives the namespace of the system for evaluating commands .
1,007
def services_by_name ( self ) : srvs = defaultdict ( list ) for i in self . services : srvs [ i . __class__ . __name__ ] . append ( i ) return srvs
A property that gives a dictionary that contains services as values and their names as keys .
1,008
def name_to_system_object ( self , name ) : if isinstance ( name , str ) : if self . allow_name_referencing : name = name else : raise NameError ( 'System.allow_name_referencing is set to False, cannot convert string to name' ) elif isinstance ( name , Object ) : name = str ( name ) return self . namespace . get ( name...
Give SystemObject instance corresponding to the name
1,009
def register_service_functions ( self , * funcs ) : for func in funcs : self . namespace [ func . __name__ ] = func
Register function in the system namespace . Called by Services .
1,010
def register_service ( self , service ) : if service not in self . services : self . services . append ( service )
Register service into the system . Called by Services .
1,011
def cleanup ( self ) : self . pre_exit_trigger = True self . logger . info ( "Shutting down %s, please wait a moment." , self . name ) for t in threading . enumerate ( ) : if isinstance ( t , TimerClass ) : t . cancel ( ) self . logger . debug ( 'Timers cancelled' ) for i in self . objects : i . cleanup ( ) self . logg...
Clean up before quitting
1,012
def cmd_exec ( self , cmd ) : if not cmd : return ns = self . cmd_namespace import copy rval = True nscopy = copy . copy ( ns ) try : r = eval ( cmd , ns ) if isinstance ( r , SystemObject ) and not r . system : r . setup_system ( self ) if callable ( r ) : r = r ( ) cmd += "()" self . logger . info ( "Eval: %s" , cmd ...
Execute commands in automate namespace
1,013
def write_puml ( self , filename = '' ) : def get_type ( o ) : type = 'program' if isinstance ( o , AbstractSensor ) : type = 'sensor' elif isinstance ( o , AbstractActuator ) : type = 'actuator' return type if filename : s = open ( filename , 'w' ) else : s = io . StringIO ( ) s . write ( '@startuml\n' ) s . write ( '...
Writes PUML from the system . If filename is given stores result in the file . Otherwise returns result as a string .
1,014
def write_svg ( self ) : import plantuml puml = self . write_puml ( ) server = plantuml . PlantUML ( url = self . url ) svg = server . processes ( puml ) return svg
Returns PUML from the system as a SVG image . Requires plantuml library .
1,015
def median_kneighbour_distance ( X , k = 5 ) : N_all = X . shape [ 0 ] k = min ( k , N_all ) N_subset = min ( N_all , 2000 ) sample_idx_train = np . random . permutation ( N_all ) [ : N_subset ] nn = neighbors . NearestNeighbors ( k ) nn . fit ( X [ sample_idx_train , : ] ) d , idx = nn . kneighbors ( X [ sample_idx_tr...
Calculate the median kneighbor distance .
1,016
def pair_distance_centile ( X , centile , max_pairs = 5000 ) : N = X . shape [ 0 ] n_pairs = min ( max_pairs , N ** 2 ) dists = np . zeros ( n_pairs ) for i in range ( n_pairs ) : pair = np . random . randint ( 0 , N , 2 ) pairdiff = X [ pair [ 0 ] , : ] - X [ pair [ 1 ] , : ] dists [ i ] = np . dot ( pairdiff , pairdi...
Calculate centiles of distances between random pairs in a dataset .
1,017
def fit ( self , X , y = None ) : N = X . shape [ 0 ] if y is None : y = np . zeros ( N ) self . classes = list ( set ( y ) ) self . classes . sort ( ) self . n_classes = len ( self . classes ) if not self . sigma : self . sigma = median_kneighbour_distance ( X ) self . gamma = self . sigma ** - 2 if not self . gamma :...
Fit the inlier model given training data .
1,018
def predict ( self , X ) : predictions_proba = self . predict_proba ( X ) predictions = [ ] allclasses = copy . copy ( self . classes ) allclasses . append ( 'anomaly' ) for i in range ( X . shape [ 0 ] ) : predictions . append ( allclasses [ predictions_proba [ i , : ] . argmax ( ) ] ) return predictions
Assign classes to test data .
1,019
def predict_proba ( self , X ) : Phi = metrics . pairwise . rbf_kernel ( X , self . kernel_pos , self . gamma ) N = X . shape [ 0 ] predictions = np . zeros ( ( N , self . n_classes + 1 ) ) for i in range ( N ) : post = np . zeros ( self . n_classes ) for c in range ( self . n_classes ) : post [ c ] = max ( 0 , np . do...
Calculate posterior probabilities of test data .
1,020
def decision_function ( self , X ) : predictions = self . predict_proba ( X ) out = np . zeros ( ( predictions . shape [ 0 ] , 1 ) ) out [ : , 0 ] = 1 - predictions [ : , - 1 ] return out
Generate an inlier score for each test data example .
1,021
def score ( self , X , y ) : predictions = self . predict ( X ) true = 0.0 total = 0.0 for i in range ( len ( predictions ) ) : total += 1 if predictions [ i ] == y [ i ] : true += 1 return true / total
Calculate accuracy score .
1,022
def predict_sequence ( self , X , A , pi , inference = 'smoothing' ) : obsll = self . predict_proba ( X ) T , S = obsll . shape alpha = np . zeros ( ( T , S ) ) alpha [ 0 , : ] = pi for t in range ( 1 , T ) : alpha [ t , : ] = np . dot ( alpha [ t - 1 , : ] , A ) for s in range ( S ) : alpha [ t , s ] *= obsll [ t , s ...
Calculate class probabilities for a sequence of data .
1,023
def toggle_sensor ( request , sensorname ) : if service . read_only : service . logger . warning ( "Could not perform operation: read only mode enabled" ) raise Http404 source = request . GET . get ( 'source' , 'main' ) sensor = service . system . namespace [ sensorname ] sensor . status = not sensor . status service ....
This is used only if websocket fails
1,024
def toggle_value ( request , name ) : obj = service . system . namespace . get ( name , None ) if not obj or service . read_only : raise Http404 new_status = obj . status = not obj . status if service . redirect_from_setters : return HttpResponseRedirect ( reverse ( 'set_ready' , args = ( name , new_status ) ) ) else :...
For manual shortcut links to perform toggle actions
1,025
def set_value ( request , name , value ) : obj = service . system . namespace . get ( name , None ) if not obj or service . read_only : raise Http404 obj . status = value if service . redirect_from_setters : return HttpResponseRedirect ( reverse ( 'set_ready' , args = ( name , value ) ) ) else : return set_ready ( requ...
For manual shortcut links to perform set value actions
1,026
def object_type ( self ) : from . statusobject import AbstractSensor , AbstractActuator from . program import Program if isinstance ( self , AbstractSensor ) : return 'sensor' elif isinstance ( self , AbstractActuator ) : return 'actuator' elif isinstance ( self , Program ) : return 'program' else : return 'other'
A read - only property that gives the object type as string ; sensor actuator program other . Used by WEB interface templates .
1,027
def get_as_datadict ( self ) : return dict ( type = self . __class__ . __name__ , tags = list ( self . tags ) )
Get information about this object as a dictionary . Used by WebSocket interface to pass some relevant information to client applications .
1,028
def setup_system ( self , system , name_from_system = '' , ** kwargs ) : if not self . system : self . system = system name , traits = self . _passed_arguments new_name = self . system . get_unique_name ( self , name , name_from_system ) if not self in self . system . reverse : self . name = new_name self . logger = se...
Set system attribute and do some initialization . Used by System .
1,029
def setup_callables ( self ) : defaults = self . get_default_callables ( ) for key , value in list ( defaults . items ( ) ) : self . _postponed_callables . setdefault ( key , value ) for key in self . callables : value = self . _postponed_callables . pop ( key ) value . setup_callable_system ( self . system , init = Tr...
Setup Callable attributes that belong to this object .
1,030
def grab_keyfile ( cert_url ) : key_cache = caches [ getattr ( settings , 'BOUNCY_KEY_CACHE' , 'default' ) ] pemfile = key_cache . get ( cert_url ) if not pemfile : response = urlopen ( cert_url ) pemfile = response . read ( ) certificates = pem . parse ( smart_bytes ( pemfile ) ) if len ( certificates ) != 1 : logger ...
Function to acqure the keyfile
1,031
def verify_notification ( data ) : pemfile = grab_keyfile ( data [ 'SigningCertURL' ] ) cert = crypto . load_certificate ( crypto . FILETYPE_PEM , pemfile ) signature = base64 . decodestring ( six . b ( data [ 'Signature' ] ) ) if data [ 'Type' ] == "Notification" : hash_format = NOTIFICATION_HASH_FORMAT else : hash_fo...
Function to verify notification came from a trusted source
1,032
def approve_subscription ( data ) : url = data [ 'SubscribeURL' ] domain = urlparse ( url ) . netloc pattern = getattr ( settings , 'BOUNCY_SUBSCRIBE_DOMAIN_REGEX' , r"sns.[a-z0-9\-]+.amazonaws.com$" ) if not re . search ( pattern , domain ) : logger . error ( 'Invalid Subscription Domain %s' , url ) return HttpRespons...
Function to approve a SNS subscription with Amazon
1,033
def clean_time ( time_string ) : time = dateutil . parser . parse ( time_string ) if not settings . USE_TZ : time = time . astimezone ( timezone . utc ) . replace ( tzinfo = None ) return time
Return a datetime from the Amazon - provided datetime string
1,034
def parse_selectors ( model , fields = None , exclude = None , key_map = None , ** options ) : fields = fields or DEFAULT_SELECTORS exclude = exclude or ( ) key_map = key_map or { } validated = [ ] for alias in fields : actual = key_map . get ( alias , alias ) cleaned = resolver . get_field ( model , actual ) if cleane...
Validates fields are valid and maps pseudo - fields to actual fields for a given model class .
1,035
def _get_local_fields ( self , model ) : "Return the names of all locally defined fields on the model class." local = [ f for f in model . _meta . fields ] m2m = [ f for f in model . _meta . many_to_many ] fields = local + m2m names = tuple ( [ x . name for x in fields ] ) return { ':local' : dict ( list ( zip ( names ...
Return the names of all locally defined fields on the model class .
1,036
def _get_related_fields ( self , model ) : "Returns the names of all related fields for model class." reverse_fk = self . _get_all_related_objects ( model ) reverse_m2m = self . _get_all_related_many_to_many_objects ( model ) fields = tuple ( reverse_fk + reverse_m2m ) names = tuple ( [ x . get_accessor_name ( ) for x ...
Returns the names of all related fields for model class .
1,037
def to_html ( self , index = False , escape = False , header = True , collapse_table = True , class_outer = "table_outer" , ** kargs ) : _buffer = { } for k , v in self . pd_options . items ( ) : _buffer [ k ] = pd . get_option ( k ) pd . set_option ( k , v ) table = self . df . to_html ( escape = escape , header = hea...
Return HTML version of the table
1,038
def add_bgcolor ( self , colname , cmap = 'copper' , mode = 'absmax' , threshold = 2 ) : try : cmap = cmap_builder ( cmap ) except : pass data = self . df [ colname ] . values if len ( data ) == 0 : return if mode == 'clip' : data = [ min ( x , threshold ) / float ( threshold ) for x in data ] elif mode == 'absmax' : m...
Change column content into HTML paragraph with background color
1,039
def changelist_view ( self , request , extra_context = None ) : extra_context = extra_context or { } if 'object' in request . GET . keys ( ) : value = request . GET [ 'object' ] . split ( ':' ) content_type = get_object_or_404 ( ContentType , id = value [ 0 ] , ) tracked_object = get_object_or_404 ( content_type . mode...
Get object currently tracked and add a button to get back to it
1,040
def list ( self , filter = None , type = None , sort = None , limit = None , page = None ) : schema = self . LIST_SCHEMA resp = self . service . list ( self . base , filter , type , sort , limit , page ) cs , l = self . service . decode ( schema , resp , many = True , links = True ) return Page ( cs , l )
Get a list of configs .
1,041
def iter_list ( self , * args , ** kwargs ) : return self . service . iter_list ( self . list , * args , ** kwargs )
Get a list of configs . Whereas list fetches a single page of configs according to its limit and page arguments iter_list returns all configs by internally making successive calls to list .
1,042
def get_plaintext ( self , id ) : return self . service . get_id ( self . base , id , params = { 'format' : 'text' } ) . text
Get a config as plaintext .
1,043
def create ( self , resource ) : schema = self . CREATE_SCHEMA json = self . service . encode ( schema , resource ) schema = self . GET_SCHEMA resp = self . service . create ( self . base , json ) return self . service . decode ( schema , resp )
Create a new config .
1,044
def edit ( self , resource ) : schema = self . EDIT_SCHEMA json = self . service . encode ( schema , resource ) schema = self . GET_SCHEMA resp = self . service . edit ( self . base , resource . id , json ) return self . service . decode ( schema , resp )
Edit a config .
1,045
def edit_shares ( self , id , user_ids ) : return self . service . edit_shares ( self . base , id , user_ids )
Edit shares for a config .
1,046
def check_config ( self , contents ) : schema = CheckConfigSchema ( ) resp = self . service . post ( self . base , params = { 'process' : 'check' } , json = { 'contents' : contents } ) return self . service . decode ( schema , resp )
Process config contents with cdrouter - cli - check - config .
1,047
def upgrade_config ( self , contents ) : schema = UpgradeConfigSchema ( ) resp = self . service . post ( self . base , params = { 'process' : 'upgrade' } , json = { 'contents' : contents } ) return self . service . decode ( schema , resp )
Process config contents with cdrouter - cli - upgrade - config .
1,048
def get_networks ( self , contents ) : schema = NetworksSchema ( ) resp = self . service . post ( self . base , params = { 'process' : 'networks' } , json = { 'contents' : contents } ) return self . service . decode ( schema , resp )
Process config contents with cdrouter - cli - print - networks - json .
1,049
def bulk_copy ( self , ids ) : schema = self . GET_SCHEMA return self . service . bulk_copy ( self . base , self . RESOURCE , ids , schema )
Bulk copy a set of configs .
1,050
def bulk_edit ( self , _fields , ids = None , filter = None , type = None , all = False , testvars = None ) : schema = self . EDIT_SCHEMA _fields = self . service . encode ( schema , _fields , skip_none = True ) return self . service . bulk_edit ( self . base , self . RESOURCE , _fields , ids = ids , filter = filter , ...
Bulk edit a set of configs .
1,051
def bulk_delete ( self , ids = None , filter = None , type = None , all = False ) : return self . service . bulk_delete ( self . base , self . RESOURCE , ids = ids , filter = filter , type = type , all = all )
Bulk delete a set of configs .
1,052
def response_token_setter ( remote , resp ) : if resp is None : raise OAuthRejectedRequestError ( 'User rejected request.' , remote , resp ) else : if 'access_token' in resp : return oauth2_token_setter ( remote , resp ) elif 'oauth_token' in resp and 'oauth_token_secret' in resp : return oauth1_token_setter ( remote ,...
Extract token from response and set it for the user .
1,053
def oauth1_token_setter ( remote , resp , token_type = '' , extra_data = None ) : return token_setter ( remote , resp [ 'oauth_token' ] , secret = resp [ 'oauth_token_secret' ] , extra_data = extra_data , token_type = token_type , )
Set an OAuth1 token .
1,054
def oauth2_token_setter ( remote , resp , token_type = '' , extra_data = None ) : return token_setter ( remote , resp [ 'access_token' ] , secret = '' , token_type = token_type , extra_data = extra_data , )
Set an OAuth2 token .
1,055
def token_setter ( remote , token , secret = '' , token_type = '' , extra_data = None , user = None ) : session [ token_session_key ( remote . name ) ] = ( token , secret ) user = user or current_user if not user . is_anonymous : uid = user . id cid = remote . consumer_key t = RemoteToken . get ( uid , cid , token_type...
Set token for user .
1,056
def token_getter ( remote , token = '' ) : session_key = token_session_key ( remote . name ) if session_key not in session and current_user . is_authenticated : remote_token = RemoteToken . get ( current_user . get_id ( ) , remote . consumer_key , token_type = token , ) if remote_token is None : return None session [ s...
Retrieve OAuth access token .
1,057
def token_delete ( remote , token = '' ) : session_key = token_session_key ( remote . name ) return session . pop ( session_key , None )
Remove OAuth access tokens from session .
1,058
def oauth_error_handler ( f ) : @ wraps ( f ) def inner ( * args , ** kwargs ) : try : return f ( * args , ** kwargs ) except OAuthClientError as e : current_app . logger . warning ( e . message , exc_info = True ) return oauth2_handle_error ( e . remote , e . response , e . code , e . uri , e . description ) except OA...
Decorator to handle exceptions .
1,059
def authorized_default_handler ( resp , remote , * args , ** kwargs ) : response_token_setter ( remote , resp ) db . session . commit ( ) return redirect ( url_for ( 'invenio_oauthclient_settings.index' ) )
Store access token in session .
1,060
def signup_handler ( remote , * args , ** kwargs ) : if current_user . is_authenticated : return redirect ( '/' ) oauth_token = token_getter ( remote ) if not oauth_token : return redirect ( '/' ) session_prefix = token_session_key ( remote . name ) if not session . get ( session_prefix + '_autoregister' , False ) : re...
Handle extra signup information .
1,061
def oauth_logout_handler ( sender_app , user = None ) : oauth = current_app . extensions [ 'oauthlib.client' ] for remote in oauth . remote_apps . values ( ) : token_delete ( remote ) db . session . commit ( )
Remove all access tokens from session on logout .
1,062
def make_handler ( f , remote , with_response = True ) : if isinstance ( f , six . string_types ) : f = import_string ( f ) @ wraps ( f ) def inner ( * args , ** kwargs ) : if with_response : return f ( args [ 0 ] , remote , * args [ 1 : ] , ** kwargs ) else : return f ( remote , * args , ** kwargs ) return inner
Make a handler for authorized and disconnect callbacks .
1,063
def _enable_lock ( func ) : @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : self = args [ 0 ] if self . is_concurrent : only_read = kwargs . get ( 'only_read' ) if only_read is None or only_read : with self . _rwlock : return func ( * args , ** kwargs ) else : self . _rwlock . acquire_writer ( ) try :...
The decorator for ensuring thread - safe when current cache instance is concurrent status .
1,064
def _enable_cleanup ( func ) : @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : self = args [ 0 ] result = func ( * args , ** kwargs ) self . cleanup ( self ) return result return wrapper
Execute cleanup operation when the decorated function completed .
1,065
def _enable_thread_pool ( func ) : @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : self = args [ 0 ] if self . enable_thread_pool and hasattr ( self , 'thread_pool' ) : future = self . thread_pool . submit ( func , * args , ** kwargs ) is_async = kwargs . get ( 'is_async' ) if is_async is None or not ...
Use thread pool for executing a task if self . enable_thread_pool is True .
1,066
def statistic_record ( self , desc = True , timeout = 3 , is_async = False , only_read = True , * keys ) : if len ( keys ) == 0 : records = self . _generate_statistic_records ( ) else : records = self . _generate_statistic_records_by_keys ( keys ) return sorted ( records , key = lambda t : t [ 'hit_counts' ] , reverse ...
Returns a list that each element is a dictionary of the statistic info of the cache item .
1,067
def signature_unsafe ( m , sk , pk , hash_func = H ) : h = hash_func ( sk ) a = 2 ** ( b - 2 ) + sum ( 2 ** i * bit ( h , i ) for i in range ( 3 , b - 2 ) ) r = Hint ( bytearray ( [ h [ j ] for j in range ( b // 8 , b // 4 ) ] ) + m ) R = scalarmult_B ( r ) S = ( r + Hint ( encodepoint ( R ) + pk + m ) * a ) % l return...
Not safe to use with secret keys or secret data . See module docstring . This function should be used for testing only .
1,068
def checkvalid ( s , m , pk ) : if len ( s ) != b // 4 : raise ValueError ( "signature length is wrong" ) if len ( pk ) != b // 8 : raise ValueError ( "public-key length is wrong" ) s = bytearray ( s ) m = bytearray ( m ) pk = bytearray ( pk ) R = decodepoint ( s [ : b // 8 ] ) A = decodepoint ( pk ) S = decodeint ( s ...
Not safe to use when any argument is secret . See module docstring . This function should be used only for verifying public signatures of public messages .
1,069
def dict ( ) : default = defaultdict ( list ) for key , value in entries ( ) : default [ key ] . append ( value ) return default
Compatibility with NLTK . Returns the cmudict lexicon as a dictionary whose keys are lowercase words and whose values are lists of pronunciations .
1,070
def symbols ( ) : symbols = [ ] for line in symbols_stream ( ) : symbols . append ( line . decode ( 'utf-8' ) . strip ( ) ) return symbols
Return a list of symbols .
1,071
def connect_inputs ( self , datas ) : start_pipers = self . get_inputs ( ) self . log . debug ( '%s trying to connect inputs in the order %s' % ( repr ( self ) , repr ( start_pipers ) ) ) for piper , data in izip ( start_pipers , datas ) : piper . connect ( [ data ] ) self . log . debug ( '%s succesfuly connected input...
Connects input Pipers to datas input data in the correct order determined by the Piper . ornament attribute and the Dagger . _cmp function .
1,072
def start ( self ) : pipers = self . postorder ( ) for piper in pipers : piper . start ( stages = ( 0 , 1 ) ) for piper in pipers : piper . start ( stages = ( 2 , ) )
Given the pipeline topology starts Pipers in the order input - > output . See Piper . start . Pipers instances are started in two stages which allows them to share NuMaps .
1,073
def stop ( self ) : self . log . debug ( '%s begins stopping routine' % repr ( self ) ) self . log . debug ( '%s triggers stopping in input pipers' % repr ( self ) ) inputs = self . get_inputs ( ) for piper in inputs : piper . stop ( forced = True ) self . log . debug ( '%s pulls output pipers until stop' % repr ( self...
Stops the Pipers according to pipeline topology .
1,074
def del_piper ( self , piper , forced = False ) : self . log . debug ( '%s trying to delete piper %s' % ( repr ( self ) , repr ( piper ) ) ) try : piper = self . resolve ( piper , forgive = False ) except DaggerError : self . log . error ( '%s cannot resolve piper from %s' % ( repr ( self ) , repr ( piper ) ) ) raise D...
Removes a Piper from the Dagger instance .
1,075
def start ( self , datas ) : if not self . _started . isSet ( ) and not self . _running . isSet ( ) and not self . _pausing . isSet ( ) : self . stats = { } self . stats [ 'start_time' ] = None self . stats [ 'run_time' ] = None self . connect_inputs ( datas ) self . connect ( ) self . stats [ 'pipers_tracked' ] = { } ...
Starts the pipeline by connecting the input Pipers of the pipeline to the input data connecting the pipeline and starting the NuMap instances . The order of items in the datas argument sequence should correspond to the order of the input Pipers defined by Dagger . _cmp and Piper . ornament .
1,076
def pause ( self ) : if self . _started . isSet ( ) and self . _running . isSet ( ) and not self . _pausing . isSet ( ) : self . _pausing . set ( ) self . _plunger . join ( ) del self . _plunger self . _pausing . clear ( ) self . _running . clear ( ) else : raise PlumberError
Pauses a running pipeline . This will stop retrieving results from the pipeline . Parallel parts of the pipeline will stop after the NuMap buffer is has been filled . A paused pipeline can be run or stopped .
1,077
def stop ( self ) : if self . _started . isSet ( ) and not self . _running . isSet ( ) and not self . _pausing . isSet ( ) : super ( Plumber , self ) . stop ( ) self . disconnect ( ) self . stats [ 'run_time' ] = time ( ) - self . stats [ 'start_time' ] self . _started . clear ( ) else : raise PlumberError
Stops a paused pipeline . This will a trigger a StopIteration in the inputs of the pipeline . And retrieve the buffered results . This will stop all Pipers and NuMaps . Python will not terminate cleanly if a pipeline is running or paused .
1,078
def next ( self ) : try : results = self . _stride_buffer . pop ( ) except ( IndexError , AttributeError ) : self . _rebuffer ( ) results = self . _stride_buffer . pop ( ) if not results : raise StopIteration return results
Returns the next sequence of results given stride and n .
1,079
def next ( self ) : if self . s : self . s -= 1 else : self . s = self . stride - 1 self . i = ( self . i + 1 ) % self . l return self . iterables [ self . i ] . next ( )
Returns the next result from the chained iterables given stride .
1,080
def list_csv ( self , filter = None , type = None , sort = None , limit = None , page = None ) : return self . service . list ( self . base , filter , type , sort , limit , page , format = 'csv' ) . text
Get a list of results as CSV .
1,081
def updates ( self , id , update_id = None ) : if update_id is None : update_id = - 1 schema = UpdateSchema ( ) resp = self . service . get_id ( self . base , id , params = { 'updates' : update_id } ) return self . service . decode ( schema , resp )
Get updates of a running result via long - polling . If no updates are available CDRouter waits up to 10 seconds before sending an empty response .
1,082
def pause ( self , id , when = None ) : return self . service . post ( self . base + str ( id ) + '/pause/' , params = { 'when' : when } )
Pause a running result .
1,083
def unpause ( self , id ) : return self . service . post ( self . base + str ( id ) + '/unpause/' )
Unpause a running result .
1,084
def export ( self , id , exclude_captures = False ) : return self . service . export ( self . base , id , params = { 'exclude_captures' : exclude_captures } )
Export a result .
1,085
def bulk_export ( self , ids , exclude_captures = False ) : return self . service . bulk_export ( self . base , ids , params = { 'exclude_captures' : exclude_captures } )
Bulk export a set of results .
1,086
def bulk_copy ( self , ids ) : schema = ResultSchema ( ) return self . service . bulk_copy ( self . base , self . RESOURCE , ids , schema )
Bulk copy a set of results .
1,087
def all_stats ( self ) : schema = AllStatsSchema ( ) resp = self . service . post ( self . base , params = { 'stats' : 'all' } ) return self . service . decode ( schema , resp )
Compute stats for all results .
1,088
def set_stats ( self , ids ) : schema = SetStatsSchema ( ) resp = self . service . post ( self . base , params = { 'stats' : 'set' } , json = [ { 'id' : str ( x ) } for x in ids ] ) return self . service . decode ( schema , resp )
Compute stats for a set of results .
1,089
def diff_stats ( self , ids ) : schema = DiffStatsSchema ( ) resp = self . service . post ( self . base , params = { 'stats' : 'diff' } , json = [ { 'id' : str ( x ) } for x in ids ] ) return self . service . decode ( schema , resp )
Compute diff stats for a set of results .
1,090
def single_stats ( self , id ) : schema = SingleStatsSchema ( ) resp = self . service . get ( self . base + str ( id ) + '/' , params = { 'stats' : 'all' } ) return self . service . decode ( schema , resp )
Compute stats for a result .
1,091
def progress_stats ( self , id ) : schema = ProgressSchema ( ) resp = self . service . get ( self . base + str ( id ) + '/' , params = { 'stats' : 'progress' } ) return self . service . decode ( schema , resp )
Compute progress stats for a result .
1,092
def summary_stats ( self , id ) : schema = SummaryStatsSchema ( ) resp = self . service . get ( self . base + str ( id ) + '/' , params = { 'stats' : 'summary' } ) return self . service . decode ( schema , resp )
Compute summary stats for a result .
1,093
def list_logdir ( self , id , filter = None , sort = None ) : schema = LogDirFileSchema ( ) resp = self . service . list ( self . base + str ( id ) + '/logdir/' , filter , sort ) return self . service . decode ( schema , resp , many = True )
Get a list of logdir files .
1,094
def get_logdir_file ( self , id , filename ) : resp = self . service . get ( self . base + str ( id ) + '/logdir/' + filename + '/' , stream = True ) b = io . BytesIO ( ) stream . stream_response_to_file ( resp , path = b ) resp . close ( ) b . seek ( 0 ) return ( b , self . service . filename ( resp ) )
Download a logdir file .
1,095
def download_logdir_archive ( self , id , format = 'zip' , exclude_captures = False ) : resp = self . service . get ( self . base + str ( id ) + '/logdir/' , params = { 'format' : format , 'exclude_captures' : exclude_captures } , stream = True ) b = io . BytesIO ( ) stream . stream_response_to_file ( resp , path = b )...
Download logdir archive in tgz or zip format .
1,096
def logout ( ) : logout_url = REMOTE_APP [ 'logout_url' ] apps = current_app . config . get ( 'OAUTHCLIENT_REMOTE_APPS' ) if apps : cern_app = apps . get ( 'cern' , REMOTE_APP ) logout_url = cern_app [ 'logout_url' ] return redirect ( logout_url , code = 302 )
CERN logout view .
1,097
def find_remote_by_client_id ( client_id ) : for remote in current_oauthclient . oauth . remote_apps . values ( ) : if remote . name == 'cern' and remote . consumer_key == client_id : return remote
Return a remote application based with given client ID .
1,098
def fetch_groups ( groups ) : hidden_groups = current_app . config . get ( 'OAUTHCLIENT_CERN_HIDDEN_GROUPS' , OAUTHCLIENT_CERN_HIDDEN_GROUPS ) hidden_groups_re = current_app . config . get ( 'OAUTHCLIENT_CERN_HIDDEN_GROUPS_RE' , OAUTHCLIENT_CERN_HIDDEN_GROUPS_RE ) groups = [ group for group in groups if group not in hi...
Prepare list of allowed group names .
1,099
def fetch_extra_data ( resource ) : person_id = resource . get ( 'PersonID' , [ None ] ) [ 0 ] identity_class = resource . get ( 'IdentityClass' , [ None ] ) [ 0 ] department = resource . get ( 'Department' , [ None ] ) [ 0 ] return dict ( person_id = person_id , identity_class = identity_class , department = departmen...
Return a dict with extra data retrieved from cern oauth .