idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
1,000 | 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_NUMBER . match ( value ) if match : # Can be parse using `float`. assert ( match . group ( 'integer' ) is not None or match . group ( 'fraction' ) is not None ) return float ( value ) match = CRE_SI_NUMBER . match ( value ) assert ( match . group ( 'integer' ) is not None or match . group ( 'fraction' ) is not None ) d = match . groupdict ( ) si_unit = d [ 'si_unit' ] if d [ 'si_unit' ] else ' ' prefix_levels = ( len ( SI_PREFIX_UNITS ) - 1 ) // 2 scale = 10 ** ( 3 * ( SI_PREFIX_UNITS . index ( si_unit ) - prefix_levels ) ) return float ( d [ 'number' ] ) * scale | Parse a value expressed using SI prefix units to a floating point number . | 362 | 15 |
1,001 | def set_status ( self , name , status ) : getattr ( self . system , name ) . status = status return True | Set sensor name status to status . | 27 | 7 |
1,002 | 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 . | 44 | 12 |
1,003 | def log ( self ) : logserv = self . system . request_service ( 'LogStoreService' ) return logserv . lastlog ( html = False ) | Return recent log entries as a string . | 34 | 8 |
1,004 | 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 : print ( 'Parameter --no_input was given' ) no_input = True if args . create_new : print ( 'Parameter --create_new was given' ) create_new = True no_input = True def savefile_more_recent ( ) : time_savefile = os . path . getmtime ( filename ) time_program = os . path . getmtime ( sys . argv [ 0 ] ) return time_savefile > time_program def load_pickle ( ) : with open ( filename , 'rb' ) as of : statefile_version , data = pickle . load ( of ) if statefile_version != STATEFILE_VERSION : raise RuntimeError ( f'Wrong statefile version, please remove state file {filename}' ) return data def load ( ) : print ( 'Loading %s' % filename ) obj_list , config = load_pickle ( ) system = System ( load_state = obj_list , filename = filename , * * kwargs ) return system def create ( ) : print ( 'Creating new system' ) config = None if filename : try : obj_list , config = load_pickle ( ) except FileNotFoundError : config = None return cls ( filename = filename , load_config = config , * * kwargs ) if filename and os . path . isfile ( filename ) : if savefile_more_recent ( ) and not create_new : return load ( ) else : if no_input : print ( 'Program file more recent. Loading that instead.' ) return create ( ) while True : answer = input ( 'Program file more recent. Do you want to load it? (y/n) ' ) if answer == 'y' : return create ( ) elif answer == 'n' : return load ( ) else : return create ( ) | Load system from a dump if dump file exists or create a new system if it does not exist . | 493 | 20 |
1,005 | 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 . | 41 | 16 |
1,006 | 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 . | 46 | 17 |
1,007 | 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 , None ) | Give SystemObject instance corresponding to the name | 92 | 8 |
1,008 | def register_service_functions ( self , * funcs ) : for func in funcs : self . namespace [ func . __name__ ] = func | Register function in the system namespace . Called by Services . | 33 | 11 |
1,009 | def register_service ( self , service ) : if service not in self . services : self . services . append ( service ) | Register service into the system . Called by Services . | 26 | 10 |
1,010 | 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 . logger . debug ( 'Sensors etc cleanups done' ) for ser in ( i for i in self . services if isinstance ( i , AbstractUserService ) ) : ser . cleanup_system ( ) self . logger . debug ( 'User services cleaned up' ) if self . worker_thread . is_alive ( ) : self . worker_thread . stop ( ) self . logger . debug ( 'Worker thread really stopped' ) for ser in ( i for i in self . services if isinstance ( i , AbstractSystemService ) ) : ser . cleanup_system ( ) self . logger . debug ( 'System services cleaned up' ) threads = list ( t . name for t in threading . enumerate ( ) if t . is_alive ( ) and not t . daemon ) if threads : self . logger . info ( 'After cleanup, we have still the following threads ' 'running: %s' , ', ' . join ( threads ) ) | Clean up before quitting | 295 | 4 |
1,011 | 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 ) self . logger . info ( "Result: %s" , r ) except SyntaxError : r = { } try : exec ( cmd , ns ) self . logger . info ( "Exec: %s" , cmd ) except ExitException : raise except Exception as e : self . logger . info ( "Failed to exec cmd %s: %s." , cmd , e ) rval = False for key , value in list ( ns . items ( ) ) : if key not in nscopy or not value is nscopy [ key ] : if key in self . namespace : del self . namespace [ key ] self . namespace [ key ] = value r [ key ] = value self . logger . info ( "Set items in namespace: %s" , r ) except ExitException : raise except Exception as e : self . logger . info ( "Failed to eval cmd %s: %s" , cmd , e ) return False return rval | Execute commands in automate namespace | 305 | 6 |
1,012 | 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 ( 'skinparam state {\n' ) for k , v in list ( self . background_colors . items ( ) ) : s . write ( 'BackGroundColor<<%s>> %s\n' % ( k , v ) ) s . write ( '}\n' ) for o in self . system . objects : if isinstance ( o , DefaultProgram ) or o . hide_in_uml : continue if isinstance ( o , ProgrammableSystemObject ) : s . write ( 'state "%s" as %s <<%s>>\n' % ( o , o , get_type ( o ) ) ) s . write ( '%s: %s\n' % ( o , o . class_name ) ) if isinstance ( o , AbstractActuator ) : for p in reversed ( o . program_stack ) : s . write ( '%s: %s :: %s\n' % ( o , p , o . program_status . get ( p , '-' ) ) ) elif hasattr ( o , 'status' ) : s . write ( '%s: Status: %s\n' % ( o , o . status ) ) if getattr ( o , 'is_program' , False ) : s . write ( '%s: Priority: %s\n' % ( o , o . priority ) ) for t in o . actual_triggers : if isinstance ( t , DefaultProgram ) or t . hide_in_uml : continue s . write ( '%s -[%s]-> %s\n' % ( t , self . arrow_colors [ 'trigger' ] , o ) ) for t in o . actual_targets : if t . hide_in_uml : continue if o . active : color = 'active_target' else : color = 'inactive_target' if getattr ( t , 'program' , None ) == o : color = 'controlled_target' s . write ( '%s -[%s]-> %s\n' % ( o , self . arrow_colors [ color ] , t ) ) s . write ( '@enduml\n' ) if filename : s . close ( ) else : return s . getvalue ( ) | Writes PUML from the system . If filename is given stores result in the file . Otherwise returns result as a string . | 596 | 25 |
1,013 | 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 . | 56 | 17 |
1,014 | 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_train , : ] ) return np . median ( d [ : , - 1 ] ) | Calculate the median kneighbor distance . | 141 | 10 |
1,015 | def pair_distance_centile ( X , centile , max_pairs = 5000 ) : N = X . shape [ 0 ] n_pairs = min ( max_pairs , N ** 2 ) # randorder1 = np.random.permutation(N) # randorder2 = np.random.permutation(N) 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 , pairdiff . T ) dists . sort ( ) out = dists [ int ( n_pairs * centile / 100. ) ] return np . sqrt ( out ) | Calculate centiles of distances between random pairs in a dataset . | 185 | 14 |
1,016 | 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 no kernel parameters specified, try to choose some defaults if not self . sigma : self . sigma = median_kneighbour_distance ( X ) self . gamma = self . sigma ** - 2 if not self . gamma : self . gamma = self . sigma ** - 2 if not self . rho : self . rho = 0.1 # choose kernel basis centres if self . kernel_pos is None : B = min ( self . n_kernels_max , N ) kernel_idx = np . random . permutation ( N ) self . kernel_pos = X [ kernel_idx [ : B ] ] else : B = self . kernel_pos . shape [ 0 ] # fit coefficients Phi = metrics . pairwise . rbf_kernel ( X , self . kernel_pos , self . gamma ) theta = { } Phi_PhiT = np . dot ( Phi . T , Phi ) inverse_term = np . linalg . inv ( Phi_PhiT + self . rho * np . eye ( B ) ) for c in self . classes : m = ( y == c ) . astype ( int ) theta [ c ] = np . dot ( inverse_term , np . dot ( Phi . T , m ) ) self . theta = theta | Fit the inlier model given training data . | 346 | 9 |
1,017 | 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 . | 85 | 7 |
1,018 | 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 . dot ( self . theta [ self . classes [ c ] ] . T , Phi [ i , : ] ) ) post [ c ] = min ( post [ c ] , 1. ) predictions [ i , : - 1 ] = post predictions [ i , - 1 ] = max ( 0 , 1 - sum ( post ) ) return predictions | Calculate posterior probabilities of test data . | 177 | 9 |
1,019 | 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 . | 57 | 12 |
1,020 | 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 . | 60 | 6 |
1,021 | 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 ] alpha [ t , : ] = alpha [ t , : ] / sum ( alpha [ t , : ] ) if inference == 'filtering' : return alpha else : beta = np . zeros ( ( T , S ) ) gamma = np . zeros ( ( T , S ) ) beta [ T - 1 , : ] = np . ones ( S ) for t in range ( T - 2 , - 1 , - 1 ) : for i in range ( S ) : for j in range ( S ) : beta [ t , i ] += A [ i , j ] * obsll [ t + 1 , j ] * beta [ t + 1 , j ] beta [ t , : ] = beta [ t , : ] / sum ( beta [ t , : ] ) for t in range ( T ) : gamma [ t , : ] = alpha [ t , : ] * beta [ t , : ] gamma [ t , : ] = gamma [ t , : ] / sum ( gamma [ t , : ] ) return gamma | Calculate class probabilities for a sequence of data . | 334 | 11 |
1,022 | 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 . system . flush ( ) return HttpResponseRedirect ( reverse ( source ) ) | This is used only if websocket fails | 97 | 8 |
1,023 | 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 : return set_ready ( request , name , new_status ) | For manual shortcut links to perform toggle actions | 101 | 8 |
1,024 | 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 ( request , name , value ) | For manual shortcut links to perform set value actions | 92 | 9 |
1,025 | 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 . | 79 | 26 |
1,026 | 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 . | 36 | 23 |
1,027 | 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 = self . system . logger . getChild ( '%s.%s' % ( self . __class__ . __name__ , self . name ) ) self . logger . setLevel ( self . log_level ) if name is None and 'name' in traits : # Only __setstate__ sets name to None. Default is ''. del traits [ 'name' ] for cname in self . callables : if cname in traits : c = self . _postponed_callables [ cname ] = traits . pop ( cname ) c . setup_callable_system ( self . system ) getattr ( self , cname ) . setup_callable_system ( self . system ) if not self . traits_inited ( ) : super ( ) . __init__ ( * * traits ) self . name_changed_event = True self . setup ( ) | Set system attribute and do some initialization . Used by System . | 279 | 12 |
1,028 | 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 = True ) setattr ( self , key , value ) | Setup Callable attributes that belong to this object . | 102 | 10 |
1,029 | 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 ( ) # Extract the first certificate in the file and confirm it's a valid # PEM certificate certificates = pem . parse ( smart_bytes ( pemfile ) ) # A proper certificate file will contain 1 certificate if len ( certificates ) != 1 : logger . error ( 'Invalid Certificate File: URL %s' , cert_url ) raise ValueError ( 'Invalid Certificate File' ) key_cache . set ( cert_url , pemfile ) return pemfile | Function to acqure the keyfile | 175 | 7 |
1,030 | 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_format = SUBSCRIPTION_HASH_FORMAT try : crypto . verify ( cert , signature , six . b ( hash_format . format ( * * data ) ) , 'sha1' ) except crypto . Error : return False return True | Function to verify notification came from a trusted source | 153 | 9 |
1,031 | 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 HttpResponseBadRequest ( 'Improper Subscription Domain' ) try : result = urlopen ( url ) . read ( ) logger . info ( 'Subscription Request Sent %s' , url ) except urllib . HTTPError as error : result = error . read ( ) logger . warning ( 'HTTP Error Creating Subscription %s' , str ( result ) ) signals . subscription . send ( sender = 'bouncy_approve_subscription' , result = result , notification = data ) # Return a 200 Status Code return HttpResponse ( six . u ( result ) ) | Function to approve a SNS subscription with Amazon | 226 | 9 |
1,032 | def clean_time ( time_string ) : # Get a timezone-aware datetime object from the string time = dateutil . parser . parse ( time_string ) if not settings . USE_TZ : # If timezone support is not active, convert the time to UTC and # remove the timezone field time = time . astimezone ( timezone . utc ) . replace ( tzinfo = None ) return time | Return a datetime from the Amazon - provided datetime string | 91 | 12 |
1,033 | 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 : # Map the output key name to the actual field/accessor name for # the model actual = key_map . get ( alias , alias ) # Validate the field exists cleaned = resolver . get_field ( model , actual ) if cleaned is None : raise AttributeError ( 'The "{0}" attribute could not be found ' 'on the model "{1}"' . format ( actual , model ) ) # Mapped value, so use the original name listed in `fields` if type ( cleaned ) is list : validated . extend ( cleaned ) elif alias != actual : validated . append ( alias ) else : validated . append ( cleaned ) return tuple ( [ x for x in validated if x not in exclude ] ) | Validates fields are valid and maps pseudo - fields to actual fields for a given model class . | 212 | 19 |
1,034 | def _get_local_fields ( self , model ) : 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 , fields ) ) ) , } | Return the names of all locally defined fields on the model class . | 89 | 13 |
1,035 | def _get_related_fields ( self , model ) : 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 in fields ] ) return { ':related' : dict ( list ( zip ( names , fields ) ) ) , } | Returns the names of all related fields for model class . | 113 | 11 |
1,036 | 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 ( ) : # save the current option _buffer [ k ] = pd . get_option ( k ) # set with user value pd . set_option ( k , v ) # class sortable is to use the sorttable javascript # note that the class has one t and the javascript library has 2 # as in the original version of sorttable.js table = self . df . to_html ( escape = escape , header = header , index = index , classes = 'sortable' , * * kargs ) # get back to default options for k , v in _buffer . items ( ) : pd . set_option ( k , v ) # We wrap the table in a dedicated class/div nammed table_scroller # that users must define. return '<div class="%s">' % class_outer + table + "</div>" | Return HTML version of the table | 241 | 6 |
1,037 | def add_bgcolor ( self , colname , cmap = 'copper' , mode = 'absmax' , threshold = 2 ) : try : # if a cmap is provided, it may be just a known cmap name 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 = abs ( data . min ( ) ) M = abs ( data . max ( ) ) M = max ( [ m , M ] ) if M != 0 : data = ( data / M + 1 ) / 2. elif mode == 'max' : if data . max ( ) != 0 : data = data / float ( data . max ( ) ) # the expected RGB values for a given data point rgbcolors = [ cmap ( x ) [ 0 : 3 ] for x in data ] hexcolors = [ rgb2hex ( * x , normalised = True ) for x in rgbcolors ] # need to read original data again data = self . df [ colname ] . values # need to set precision since this is going to be a text not a number # so pandas will not use the precision for those cases: def prec ( x ) : try : # this may fail if for instance x is nan or inf x = easydev . precision ( x , self . pd_options [ 'precision' ] ) return x except : return x data = [ prec ( x ) for x in data ] html_formatter = '<p style="background-color:{0}">{1}</p>' self . df [ colname ] = [ html_formatter . format ( x , y ) for x , y in zip ( hexcolors , data ) ] | Change column content into HTML paragraph with background color | 416 | 9 |
1,038 | 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 . model_class ( ) , id = value [ 1 ] , ) extra_context [ 'tracked_object' ] = tracked_object extra_context [ 'tracked_object_opts' ] = tracked_object . _meta return super ( TrackingEventAdmin , self ) . changelist_view ( request , extra_context ) | Get object currently tracked and add a button to get back to it | 166 | 13 |
1,039 | def list ( self , filter = None , type = None , sort = None , limit = None , page = None ) : # pylint: disable=redefined-builtin 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 . | 98 | 7 |
1,040 | 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 . | 39 | 39 |
1,041 | def get_plaintext ( self , id ) : # pylint: disable=invalid-name,redefined-builtin return self . service . get_id ( self . base , id , params = { 'format' : 'text' } ) . text | Get a config as plaintext . | 57 | 7 |
1,042 | 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 . | 64 | 5 |
1,043 | 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 . | 67 | 4 |
1,044 | def edit_shares ( self , id , user_ids ) : # pylint: disable=invalid-name,redefined-builtin return self . service . edit_shares ( self . base , id , user_ids ) | Edit shares for a config . | 52 | 6 |
1,045 | 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 . | 64 | 15 |
1,046 | 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 . | 65 | 15 |
1,047 | 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 . | 65 | 17 |
1,048 | 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 . | 43 | 9 |
1,049 | def bulk_edit ( self , _fields , ids = None , filter = None , type = None , all = False , testvars = None ) : # pylint: disable=redefined-builtin 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 , type = type , all = all , testvars = testvars ) | Bulk edit a set of configs . | 122 | 9 |
1,050 | def bulk_delete ( self , ids = None , filter = None , type = None , all = False ) : # pylint: disable=redefined-builtin return self . service . bulk_delete ( self . base , self . RESOURCE , ids = ids , filter = filter , type = type , all = all ) | Bulk delete a set of configs . | 73 | 9 |
1,051 | 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 , resp ) elif 'error' in resp : # Only OAuth2 specifies how to send error messages raise OAuthClientError ( 'Authorization with remote service failed.' , remote , resp , ) raise OAuthResponseError ( 'Bad OAuth authorized request' , remote , resp ) | Extract token from response and set it for the user . | 154 | 12 |
1,052 | 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 . | 76 | 7 |
1,053 | 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 . | 65 | 7 |
1,054 | 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 # Save token if user is not anonymous (user exists but can be not active at # this moment) if not user . is_anonymous : uid = user . id cid = remote . consumer_key # Check for already existing token t = RemoteToken . get ( uid , cid , token_type = token_type ) if t : t . update_token ( token , secret ) else : t = RemoteToken . create ( uid , cid , token , secret , token_type = token_type , extra_data = extra_data ) return t return None | Set token for user . | 180 | 5 |
1,055 | def token_getter ( remote , token = '' ) : session_key = token_session_key ( remote . name ) if session_key not in session and current_user . is_authenticated : # Fetch key from token store if user is authenticated, and the key # isn't already cached in the session. remote_token = RemoteToken . get ( current_user . get_id ( ) , remote . consumer_key , token_type = token , ) if remote_token is None : return None # Store token and secret in session session [ session_key ] = remote_token . token ( ) return session . get ( session_key , None ) | Retrieve OAuth access token . | 141 | 7 |
1,056 | def token_delete ( remote , token = '' ) : session_key = token_session_key ( remote . name ) return session . pop ( session_key , None ) | Remove OAuth access tokens from session . | 37 | 8 |
1,057 | def oauth_error_handler ( f ) : @ wraps ( f ) def inner ( * args , * * kwargs ) : # OAuthErrors should not happen, so they are not caught here. Hence # they will result in a 500 Internal Server Error which is what we # are interested in. 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 OAuthCERNRejectedAccountError as e : current_app . logger . warning ( e . message , exc_info = True ) flash ( _ ( 'CERN account not allowed.' ) , category = 'danger' ) return redirect ( '/' ) except OAuthRejectedRequestError : flash ( _ ( 'You rejected the authentication request.' ) , category = 'info' ) return redirect ( '/' ) except AlreadyLinkedError : flash ( _ ( 'External service is already linked to another account.' ) , category = 'danger' ) return redirect ( url_for ( 'invenio_oauthclient_settings.index' ) ) return inner | Decorator to handle exceptions . | 275 | 7 |
1,058 | 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 . | 61 | 6 |
1,059 | def signup_handler ( remote , * args , * * kwargs ) : # User already authenticated so move on if current_user . is_authenticated : return redirect ( '/' ) # Retrieve token from session oauth_token = token_getter ( remote ) if not oauth_token : return redirect ( '/' ) session_prefix = token_session_key ( remote . name ) # Test to see if this is coming from on authorized request if not session . get ( session_prefix + '_autoregister' , False ) : return redirect ( url_for ( '.login' , remote_app = remote . name ) ) form = create_registrationform ( request . form ) if form . validate_on_submit ( ) : account_info = session . get ( session_prefix + '_account_info' ) response = session . get ( session_prefix + '_response' ) # Register user user = oauth_register ( form ) if user is None : raise OAuthError ( 'Could not create user.' , remote ) # Remove session key session . pop ( session_prefix + '_autoregister' , None ) # Link account and set session data token = token_setter ( remote , oauth_token [ 0 ] , secret = oauth_token [ 1 ] , user = user ) handlers = current_oauthclient . signup_handlers [ remote . name ] if token is None : raise OAuthError ( 'Could not create token for user.' , remote ) if not token . remote_account . extra_data : account_setup = handlers [ 'setup' ] ( token , response ) account_setup_received . send ( remote , token = token , response = response , account_setup = account_setup ) # Registration has been finished db . session . commit ( ) account_setup_committed . send ( remote , token = token ) else : # Registration has been finished db . session . commit ( ) # Authenticate the user if not oauth_authenticate ( remote . consumer_key , user , require_existing_link = False ) : # Redirect the user after registration (which doesn't include the # activation), waiting for user to confirm his email. return redirect ( url_for ( 'security.login' ) ) # Remove account info from session session . pop ( session_prefix + '_account_info' , None ) session . pop ( session_prefix + '_response' , None ) # Redirect to next next_url = get_session_next_url ( remote . name ) if next_url : return redirect ( next_url ) else : return redirect ( '/' ) # Pre-fill form account_info = session . get ( session_prefix + '_account_info' ) if not form . is_submitted ( ) : form = fill_form ( form , account_info [ 'user' ] ) return render_template ( current_app . config [ 'OAUTHCLIENT_SIGNUP_TEMPLATE' ] , form = form , remote = remote , app_title = current_app . config [ 'OAUTHCLIENT_REMOTE_APPS' ] [ remote . name ] . get ( 'title' , '' ) , app_description = current_app . config [ 'OAUTHCLIENT_REMOTE_APPS' ] [ remote . name ] . get ( 'description' , '' ) , app_icon = current_app . config [ 'OAUTHCLIENT_REMOTE_APPS' ] [ remote . name ] . get ( 'icon' , None ) , ) | Handle extra signup information . | 769 | 6 |
1,060 | 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 . | 62 | 10 |
1,061 | 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 . | 101 | 10 |
1,062 | 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 : return func ( * args , * * kwargs ) finally : self . _rwlock . release ( ) else : return func ( * args , * * kwargs ) return wrapper | The decorator for ensuring thread - safe when current cache instance is concurrent status . | 145 | 16 |
1,063 | 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 . | 61 | 10 |
1,064 | 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 is_async : timeout = kwargs . get ( 'timeout' ) if timeout is None : timeout = 2 try : result = future . result ( timeout = timeout ) except TimeoutError as e : self . logger . exception ( e ) result = None return result return future else : return func ( * args , * * kwargs ) return wrapper | Use thread pool for executing a task if self . enable_thread_pool is True . | 183 | 18 |
1,065 | 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 = desc ) | Returns a list that each element is a dictionary of the statistic info of the cache item . | 101 | 18 |
1,066 | 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 bytes ( encodepoint ( R ) + encodeint ( S ) ) | Not safe to use with secret keys or secret data . See module docstring . This function should be used for testing only . | 148 | 25 |
1,067 | 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 [ b // 8 : b // 4 ] ) h = Hint ( encodepoint ( R ) + pk + m ) ( x1 , y1 , z1 , t1 ) = P = scalarmult_B ( S ) ( x2 , y2 , z2 , t2 ) = Q = edwards_add ( R , scalarmult ( A , h ) ) if ( not isoncurve ( P ) or not isoncurve ( Q ) or ( x1 * z2 - x2 * z1 ) % q != 0 or ( y1 * z2 - y2 * z1 ) % q != 0 ) : raise SignatureMismatch ( "signature does not pass verification" ) | 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 . | 274 | 29 |
1,068 | 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 . | 32 | 33 |
1,069 | def symbols ( ) : symbols = [ ] for line in symbols_stream ( ) : symbols . append ( line . decode ( 'utf-8' ) . strip ( ) ) return symbols | Return a list of symbols . | 39 | 6 |
1,070 | 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 inputs' % repr ( self ) ) | Connects input Pipers to datas input data in the correct order determined by the Piper . ornament attribute and the Dagger . _cmp function . | 108 | 28 |
1,071 | def start ( self ) : # top - > bottom of pipeline 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 . | 62 | 37 |
1,072 | 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 ) ) outputs = self . get_outputs ( ) while outputs : for piper in outputs : try : # for i in xrange(stride)? piper . next ( ) except StopIteration : outputs . remove ( piper ) self . log . debug ( "%s stopped output piper: %s" % ( repr ( self ) , repr ( piper ) ) ) continue except Exception , excp : self . log . debug ( "%s %s raised an exception: %s" % ( repr ( self ) , piper , excp ) ) self . log . debug ( "%s stops the remaining pipers" % repr ( self ) ) postorder = self . postorder ( ) for piper in postorder : if piper not in inputs : piper . stop ( ends = [ 0 ] ) self . log . debug ( "%s finishes stopping of input pipers" % repr ( self ) ) for piper in inputs : if hasattr ( piper . imap , 'stop' ) : piper . imap . stop ( ends = [ 0 ] ) self . log . debug ( '%s finishes stopping routine' % repr ( self ) ) | Stops the Pipers according to pipeline topology . | 340 | 11 |
1,073 | 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 DaggerError ( '%s cannot resolve piper from %s' % ( repr ( self ) , repr ( piper ) ) ) if self . incoming_edges ( piper ) and not forced : self . log . error ( '%s piper %s has down-stream pipers (use forced =True to override)' % ( repr ( self ) , piper ) ) raise DaggerError ( '%s piper %s has down-stream pipers (use forced =True to override)' % ( repr ( self ) , piper ) ) self . del_node ( piper ) self . log . debug ( '%s deleted piper %s' % ( repr ( self ) , piper ) ) | Removes a Piper from the Dagger instance . | 251 | 9 |
1,074 | def start ( self , datas ) : if not self . _started . isSet ( ) and not self . _running . isSet ( ) and not self . _pausing . isSet ( ) : # Plumber statistics self . stats = { } self . stats [ 'start_time' ] = None self . stats [ 'run_time' ] = None # connects input pipers to external data self . connect_inputs ( datas ) # connects pipers within the pipeline self . connect ( ) # make pointers to results collected for pipers by imaps self . stats [ 'pipers_tracked' ] = { } for piper in self . postorder ( ) : if hasattr ( piper . imap , '_tasks_tracked' ) and piper . track : self . stats [ 'pipers_tracked' ] [ piper ] = [ piper . imap . _tasks_tracked [ t . task ] for t in piper . imap_tasks ] self . stats [ 'start_time' ] = time ( ) # starts the Dagger # this starts Pipers and NuMaps super ( Plumber , self ) . start ( ) # transitioning to started state self . _started . set ( ) self . _finished . clear ( ) else : raise PlumberError | 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 . | 280 | 57 |
1,075 | def pause ( self ) : # 1. stop the plumbing thread by raising a StopIteration on a stride # boundary 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 . | 106 | 41 |
1,076 | def stop ( self ) : if self . _started . isSet ( ) and not self . _running . isSet ( ) and not self . _pausing . isSet ( ) : # stops the dagger super ( Plumber , self ) . stop ( ) # disconnects all pipers 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 . | 105 | 52 |
1,077 | 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 . | 61 | 11 |
1,078 | def next ( self ) : if self . s : self . s -= 1 else : self . s = self . stride - 1 self . i = ( self . i + 1 ) % self . l # new iterable return self . iterables [ self . i ] . next ( ) | Returns the next result from the chained iterables given stride . | 60 | 12 |
1,079 | def list_csv ( self , filter = None , type = None , sort = None , limit = None , page = None ) : # pylint: disable=redefined-builtin return self . service . list ( self . base , filter , type , sort , limit , page , format = 'csv' ) . text | Get a list of results as CSV . | 69 | 8 |
1,080 | def updates ( self , id , update_id = None ) : # pylint: disable=invalid-name,redefined-builtin 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 . | 91 | 30 |
1,081 | def pause ( self , id , when = None ) : # pylint: disable=invalid-name,redefined-builtin return self . service . post ( self . base + str ( id ) + '/pause/' , params = { 'when' : when } ) | Pause a running result . | 60 | 5 |
1,082 | def unpause ( self , id ) : # pylint: disable=invalid-name,redefined-builtin return self . service . post ( self . base + str ( id ) + '/unpause/' ) | Unpause a running result . | 48 | 6 |
1,083 | def export ( self , id , exclude_captures = False ) : # pylint: disable=invalid-name,redefined-builtin return self . service . export ( self . base , id , params = { 'exclude_captures' : exclude_captures } ) | Export a result . | 62 | 4 |
1,084 | 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 . | 51 | 8 |
1,085 | def bulk_copy ( self , ids ) : schema = ResultSchema ( ) return self . service . bulk_copy ( self . base , self . RESOURCE , ids , schema ) | Bulk copy a set of results . | 41 | 8 |
1,086 | 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 . | 51 | 7 |
1,087 | 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 . | 74 | 9 |
1,088 | 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 . | 74 | 10 |
1,089 | def single_stats ( self , id ) : # pylint: disable=invalid-name,redefined-builtin schema = SingleStatsSchema ( ) resp = self . service . get ( self . base + str ( id ) + '/' , params = { 'stats' : 'all' } ) return self . service . decode ( schema , resp ) | Compute stats for a result . | 78 | 7 |
1,090 | def progress_stats ( self , id ) : # pylint: disable=invalid-name,redefined-builtin 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 . | 77 | 8 |
1,091 | def summary_stats ( self , id ) : # pylint: disable=invalid-name,redefined-builtin 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 . | 78 | 8 |
1,092 | def list_logdir ( self , id , filter = None , sort = None ) : # pylint: disable=invalid-name,redefined-builtin 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 . | 87 | 8 |
1,093 | def get_logdir_file ( self , id , filename ) : # pylint: disable=invalid-name,redefined-builtin 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 . | 113 | 6 |
1,094 | def download_logdir_archive ( self , id , format = 'zip' , exclude_captures = False ) : # pylint: disable=invalid-name,redefined-builtin 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 ) resp . close ( ) b . seek ( 0 ) return ( b , self . service . filename ( resp ) ) | Download logdir archive in tgz or zip format . | 142 | 11 |
1,095 | 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 . | 96 | 6 |
1,096 | 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 . | 57 | 10 |
1,097 | 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 hidden_groups ] filter_groups = [ ] for regexp in hidden_groups_re : for group in groups : if regexp . match ( group ) : filter_groups . append ( group ) groups = [ group for group in groups if group not in filter_groups ] return groups | Prepare list of allowed group names . | 180 | 8 |
1,098 | 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 = department ) | Return a dict with extra data retrieved from cern oauth . | 91 | 13 |
1,099 | def account_groups_and_extra_data ( account , resource , refresh_timedelta = None ) : updated = datetime . utcnow ( ) modified_since = updated if refresh_timedelta is not None : modified_since += refresh_timedelta modified_since = modified_since . isoformat ( ) last_update = account . extra_data . get ( 'updated' , modified_since ) if last_update > modified_since : return account . extra_data . get ( 'groups' , [ ] ) groups = fetch_groups ( resource [ 'Group' ] ) extra_data = current_app . config . get ( 'OAUTHCLIENT_CERN_EXTRA_DATA_SERIALIZER' , fetch_extra_data ) ( resource ) account . extra_data . update ( groups = groups , updated = updated . isoformat ( ) , * * extra_data ) return groups | Fetch account groups and extra data from resource if necessary . | 198 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.