idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
13,300 | def get_process_fingerprint ( ) : pid = os . getpid ( ) hostname = socket . gethostname ( ) padded_pid = _pad ( _to_base36 ( pid ) , 2 ) hostname_hash = sum ( [ ord ( x ) for x in hostname ] ) + len ( hostname ) + 36 padded_hostname = _pad ( _to_base36 ( hostname_hash ) , 2 ) return padded_pid + padded_hostname | Extract a unique fingerprint for the current process using a combination of the process PID and the system s hostname . | 104 | 23 |
13,301 | def counter ( self ) : self . _counter += 1 if self . _counter >= DISCRETE_VALUES : self . _counter = 0 return self . _counter | Rolling counter that ensures same - machine and same - time cuids don t collide . | 36 | 18 |
13,302 | def cuid ( self ) : # start with a hardcoded lowercase c identifier = "c" # add a timestamp in milliseconds since the epoch, in base 36 millis = int ( time . time ( ) * 1000 ) identifier += _to_base36 ( millis ) # use a counter to ensure no collisions on the same machine # in the same millisecond count = _pad ( _to_base36 ( self . counter ) , BLOCK_SIZE ) identifier += count # add the process fingerprint identifier += self . fingerprint # add a couple of random blocks identifier += _random_block ( ) identifier += _random_block ( ) return identifier | Generate a full - length cuid as a string . | 135 | 12 |
13,303 | def read_excel_file ( inputfile , sheet_name ) : workbook = xlrd . open_workbook ( inputfile ) output = [ ] found = False for sheet in workbook . sheets ( ) : if sheet . name == sheet_name : found = True for row in range ( sheet . nrows ) : values = [ ] for col in range ( sheet . ncols ) : values . append ( sheet . cell ( row , col ) . value ) output . append ( values ) if not found : # pragma: no cover raise MQ2Exception ( 'Invalid session identifier provided' ) return output | Return a matrix containing all the information present in the excel sheet of the specified excel document . | 133 | 18 |
13,304 | def get_session_identifiers ( cls , folder = None , inputfile = None ) : sessions = [ ] if inputfile and folder : raise MQ2Exception ( 'You should specify either a folder or a file' ) if folder : if not os . path . isdir ( folder ) : return sessions for root , dirs , files in os . walk ( folder ) : for filename in files : filename = os . path . join ( root , filename ) for ext in SUPPORTED_FILES : if filename . endswith ( ext ) : wbook = xlrd . open_workbook ( filename ) for sheet in wbook . sheets ( ) : if sheet . name not in sessions : sessions . append ( sheet . name ) elif inputfile : if os . path . isdir ( inputfile ) : return sessions for ext in SUPPORTED_FILES : if inputfile . endswith ( ext ) : wbook = xlrd . open_workbook ( inputfile ) for sheet in wbook . sheets ( ) : if sheet . name not in sessions : sessions . append ( sheet . name ) return sessions | Retrieve the list of session identifiers contained in the data on the folder or the inputfile . For this plugin it returns the list of excel sheet available . | 239 | 31 |
13,305 | def file_rights ( filepath , mode = None , uid = None , gid = None ) : file_handle = os . open ( filepath , os . O_RDONLY ) if mode : os . fchmod ( file_handle , mode ) if uid : if not gid : gid = 0 os . fchown ( file_handle , uid , gid ) os . close ( file_handle ) | Change file rights | 94 | 3 |
13,306 | def init_from_wave_file ( wavpath ) : try : samplerate , data = SW . read ( wavpath ) nframes = data . shape [ 0 ] except : # scipy cannot handle 24 bit wav files # and wave cannot handle 32 bit wav files try : w = wave . open ( wavpath ) samplerate = w . getframerate ( ) nframes = w . getnframes ( ) except : raise Exception ( 'Cannot decode wavefile ' + wavpath ) return SVEnv ( samplerate , nframes , wavpath ) | Init a sonic visualiser environment structure based the analysis of the main audio file . The audio file have to be encoded in wave | 128 | 25 |
13,307 | def add_continuous_annotations ( self , x , y , colourName = 'Purple' , colour = '#c832ff' , name = '' , view = None , vscale = None , presentationName = None ) : model = self . data . appendChild ( self . doc . createElement ( 'model' ) ) imodel = self . nbdata for atname , atval in [ ( 'id' , imodel + 1 ) , ( 'dataset' , imodel ) , ( 'name' , name ) , ( 'sampleRate' , self . samplerate ) , ( 'start' , int ( min ( x ) * self . samplerate ) ) , ( 'end' , int ( max ( x ) * self . samplerate ) ) , ( 'type' , 'sparse' ) , ( 'dimensions' , '2' ) , ( 'resolution' , '1' ) , ( 'notifyOnAdd' , 'true' ) , ( 'minimum' , min ( y ) ) , ( 'maximum' , max ( y ) ) , ( 'units' , '' ) ] : model . setAttribute ( atname , str ( atval ) ) # dataset = self.data.appendChild(self.doc.createElement('dataset')) # dataset.setAttribute('id', str(imodel)) # dataset.setAttribute('dimensions', '2') # self.nbdata += 2 # datasetnode = SVDataset2D(self.doc, str(imodel), self.samplerate) # datasetnode.set_data_from_iterable(map(int, np.array(x) * self.samplerate), y) # data = dataset.appendChild(datasetnode) dataset = self . data . appendChild ( SVDataset2D ( self . doc , str ( imodel ) , self . samplerate ) ) dataset . set_data_from_iterable ( map ( int , np . array ( x ) * self . samplerate ) , y ) self . nbdata += 2 ###### add layers valruler = self . __add_time_ruler ( ) vallayer = self . __add_val_layer ( imodel + 1 ) vallayer . setAttribute ( 'colourName' , colourName ) vallayer . setAttribute ( 'colour' , colour ) if presentationName : vallayer . setAttribute ( 'presentationName' , presentationName ) if vscale is None : vallayer . setAttribute ( 'verticalScale' , '0' ) vallayer . setAttribute ( 'scaleMinimum' , str ( min ( y ) ) ) vallayer . setAttribute ( 'scaleMaximum' , str ( max ( y ) ) ) else : vallayer . setAttribute ( 'verticalScale' , '0' ) vallayer . setAttribute ( 'scaleMinimum' , str ( vscale [ 0 ] ) ) vallayer . setAttribute ( 'scaleMaximum' , str ( vscale [ 1 ] ) ) if view is None : view = self . __add_view ( ) self . __add_layer_reference ( view , valruler ) self . __add_layer_reference ( view , vallayer ) return view | add a continous annotation layer | 723 | 6 |
13,308 | def add_interval_annotations ( self , temp_idx , durations , labels , values = None , colourName = 'Purple' , colour = '#c832ff' , name = '' , view = None , presentationName = None ) : model = self . data . appendChild ( self . doc . createElement ( 'model' ) ) imodel = self . nbdata for atname , atval in [ ( 'id' , imodel + 1 ) , ( 'dataset' , imodel ) , ( 'name' , name ) , ( 'sampleRate' , self . samplerate ) , ( 'type' , 'sparse' ) , ( 'dimensions' , '3' ) , ( 'subtype' , 'region' ) , ( 'resolution' , '1' ) , ( 'notifyOnAdd' , 'true' ) , ( 'units' , '' ) , ( 'valueQuantization' , '0' ) ] : model . setAttribute ( atname , str ( atval ) ) dataset = self . data . appendChild ( SVDataset3D ( self . doc , str ( imodel ) , self . samplerate ) ) if values is None : values = ( [ 0 ] * len ( temp_idx ) ) dataset . set_data_from_iterable ( map ( int , np . array ( temp_idx ) * self . samplerate ) , values , map ( int , np . array ( durations ) * self . samplerate ) , labels ) # dataset = self.data.appendChild(self.doc.createElement('dataset')) # dataset.setAttribute('id', str(imodel)) # dataset.setAttribute('dimensions', '3') self . nbdata += 2 valruler = self . __add_time_ruler ( ) vallayer = self . __add_region_layer ( imodel + 1 , name ) vallayer . setAttribute ( 'colourName' , colourName ) vallayer . setAttribute ( 'colour' , colour ) if presentationName : vallayer . setAttribute ( 'presentationName' , presentationName ) if view is None : view = self . __add_view ( ) self . __add_layer_reference ( view , valruler ) self . __add_layer_reference ( view , vallayer ) # if values is None: # values = ([0] * len(temp_idx)) # for t, d, l, v in zip(temp_idx, durations, labels, values): # point = dataset.appendChild(self.doc.createElement('point')) # point.setAttribute('label', l) # point.setAttribute('frame', str(int(t * self.samplerate))) # point.setAttribute('duration', str(int(d * self.samplerate))) # point.setAttribute('value', str(v)) return view | add a labelled interval annotation layer | 651 | 6 |
13,309 | def load_initial ( self , streams ) : d = { } for stream in streams : s = io . load ( stream ) if 'BLOCK' not in s : raise ValueError ( "No BLOCK found" ) d . update ( s [ 'BLOCK' ] ) d = { 'BLOCK' : d } C = io . wc_lha2dict ( d ) sm = io . sm_lha2dict ( d ) C . update ( sm ) C = definitions . symmetrize ( C ) self . C_in = C | Load the initial values for parameters and Wilson coefficients from one or several files . | 120 | 15 |
13,310 | def load_wcxf ( self , stream , get_smpar = True ) : import wcxf wc = wcxf . WC . load ( stream ) self . set_initial_wcxf ( wc , get_smpar = get_smpar ) | Load the initial values for Wilson coefficients from a file - like object or a string in WCxf format . | 59 | 21 |
13,311 | def dump_wcxf ( self , C_out , scale_out , fmt = 'yaml' , stream = None , * * kwargs ) : wc = self . get_wcxf ( C_out , scale_out ) return wc . dump ( fmt = fmt , stream = stream , * * kwargs ) | Return a string representation of the Wilson coefficients C_out in WCxf format . If stream is specified export it to a file . fmt defaults to yaml but can also be json . | 74 | 37 |
13,312 | def rgevolve_leadinglog ( self , scale_out ) : self . _check_initial ( ) return rge . smeft_evolve_leadinglog ( C_in = self . C_in , scale_high = self . scale_high , scale_in = self . scale_in , scale_out = scale_out ) | Compute the leading logarithmix approximation to the solution of the SMEFT RGEs from the initial scale to scale_out . Returns a dictionary with parameters and Wilson coefficients . Much faster but less precise that rgevolve . | 76 | 49 |
13,313 | def _check_initial ( self ) : if self . C_in is None : raise Exception ( "You have to specify the initial conditions first." ) if self . scale_in is None : raise Exception ( "You have to specify the initial scale first." ) if self . scale_high is None : raise Exception ( "You have to specify the high scale first." ) | Check if initial values and scale as well as the new physics scale have been set . | 78 | 17 |
13,314 | def rotate_defaultbasis ( self , C ) : v = sqrt ( 2 * C [ 'm2' ] . real / C [ 'Lambda' ] . real ) Mep = v / sqrt ( 2 ) * ( C [ 'Ge' ] - C [ 'ephi' ] * v ** 2 / self . scale_high ** 2 / 2 ) Mup = v / sqrt ( 2 ) * ( C [ 'Gu' ] - C [ 'uphi' ] * v ** 2 / self . scale_high ** 2 / 2 ) Mdp = v / sqrt ( 2 ) * ( C [ 'Gd' ] - C [ 'dphi' ] * v ** 2 / self . scale_high ** 2 / 2 ) Mnup = - v ** 2 * C [ 'llphiphi' ] UeL , Me , UeR = ckmutil . diag . msvd ( Mep ) UuL , Mu , UuR = ckmutil . diag . msvd ( Mup ) UdL , Md , UdR = ckmutil . diag . msvd ( Mdp ) Unu , Mnu = ckmutil . diag . mtakfac ( Mnup ) UuL , UdL , UuR , UdR = ckmutil . phases . rephase_standard ( UuL , UdL , UuR , UdR ) Unu , UeL , UeR = ckmutil . phases . rephase_pmns_standard ( Unu , UeL , UeR ) return definitions . flavor_rotation ( C , Uq = UdL , Uu = UuR , Ud = UdR , Ul = UeL , Ue = UeR ) | Rotate all parameters to the basis where the running down - type quark and charged lepton mass matrices are diagonal and where the running up - type quark mass matrix has the form V . S with V unitary and S real diagonal and where the CKM and PMNS matrices have the standard phase convention . | 384 | 65 |
13,315 | def set_database ( db_url , proxy , config ) : db_config = config . get ( 'results_database' , { } ) . get ( 'params' , { } ) if 'testing' in config and config [ 'testing' ] is True : database = connect ( 'sqlite:////tmp/results.sqlite' , check_same_thread = False , threadlocals = True ) else : if os . path . isfile ( db_url ) or os . path . isdir ( os . path . dirname ( db_url ) ) : db_url = "sqlite:///" + db_url db_config . update ( check_same_thread = False , threadlocals = True ) database = connect ( db_url , * * db_config ) proxy . initialize ( database ) | Initialize the peewee database with the given configuration | 176 | 11 |
13,316 | def sh ( cmd ) : # Figure out what local variables are defined in the calling scope. import inspect frame = inspect . currentframe ( ) try : locals = frame . f_back . f_locals finally : del frame # Run the given command in a shell. Return everything written to stdout if # the command returns an error code of 0, otherwise raise an exception. from subprocess import Popen , PIPE , CalledProcessError process = Popen ( cmd . format ( * * locals ) , shell = True , stdout = PIPE ) stdout , unused_stderr = process . communicate ( ) retcode = process . poll ( ) if retcode : error = subprocess . CalledProcessError ( retcode , cmd ) error . output = stdout raise error return stdout . strip ( ) | Run the given command in a shell . | 172 | 8 |
13,317 | def get_curricula_by_department ( department , future_terms = 0 , view_unpublished = False ) : if not isinstance ( future_terms , int ) : raise ValueError ( future_terms ) if future_terms < 0 or future_terms > 2 : raise ValueError ( future_terms ) view_unpublished = "true" if view_unpublished else "false" url = "{}?{}" . format ( curriculum_search_url_prefix , urlencode ( [ ( "department_abbreviation" , department . label , ) , ( "future_terms" , future_terms , ) , ( "view_unpublished" , view_unpublished , ) ] ) ) return _json_to_curricula ( get_resource ( url ) ) | Returns a list of restclients . Curriculum models for the passed Department model . | 172 | 18 |
13,318 | def get_curricula_by_term ( term , view_unpublished = False ) : view_unpublished = "true" if view_unpublished else "false" url = "{}?{}" . format ( curriculum_search_url_prefix , urlencode ( [ ( "quarter" , term . quarter . lower ( ) , ) , ( "year" , term . year , ) , ( "view_unpublished" , view_unpublished , ) ] ) ) return _json_to_curricula ( get_resource ( url ) ) | Returns a list of restclients . Curriculum models for the passed Term model . | 121 | 18 |
13,319 | def BP ( candidate , references ) : c = len ( candidate ) ref_lens = ( len ( reference ) for reference in references ) r = min ( ref_lens , key = lambda ref_len : ( abs ( ref_len - c ) , ref_len ) ) if c > r : return 1 else : return math . exp ( 1 - r / c ) | calculate brevity penalty | 80 | 6 |
13,320 | def MP ( candidate , references , n ) : counts = Counter ( ngrams ( candidate , n ) ) if not counts : return 0 max_counts = { } for reference in references : reference_counts = Counter ( ngrams ( reference , n ) ) for ngram in counts : max_counts [ ngram ] = max ( max_counts . get ( ngram , 0 ) , reference_counts [ ngram ] ) clipped_counts = dict ( ( ngram , min ( count , max_counts [ ngram ] ) ) for ngram , count in counts . items ( ) ) return sum ( clipped_counts . values ( ) ) / sum ( counts . values ( ) ) | calculate modified precision | 154 | 5 |
13,321 | def template2regex ( template , ranges = None ) : if len ( template ) and - 1 < template . find ( '|' ) < len ( template ) - 1 : raise InvalidTemplateError ( "'|' may only appear at the end, found at position %d in %s" % ( template . find ( '|' ) , template ) ) if ranges is None : ranges = DEFAULT_RANGES anchor = True state = S_PATH if len ( template ) and template [ - 1 ] == '|' : anchor = False params = [ ] bracketdepth = 0 result = [ '^' ] name = "" pattern = "[^/]+" rangename = None for c in template_splitter . split ( template ) : if state == S_PATH : if len ( c ) > 1 : result . append ( re . escape ( c ) ) elif c == '[' : result . append ( "(" ) bracketdepth += 1 elif c == ']' : bracketdepth -= 1 if bracketdepth < 0 : raise InvalidTemplateError ( "Mismatched brackets in %s" % template ) result . append ( ")?" ) elif c == '{' : name = "" state = S_TEMPLATE elif c == '}' : raise InvalidTemplateError ( "Mismatched braces in %s" % template ) elif c == '|' : pass else : result . append ( re . escape ( c ) ) else : if c == '}' : if rangename and rangename in ranges : result . append ( "(?P<%s>%s)" % ( name , ranges [ rangename ] ) ) else : result . append ( "(?P<%s>%s)" % ( name , pattern ) ) params . append ( name ) state = S_PATH rangename = None else : name = c if name . find ( ":" ) > - 1 : name , rangename = name . split ( ":" ) if bracketdepth != 0 : raise InvalidTemplateError ( "Mismatched brackets in %s" % template ) if state == S_TEMPLATE : raise InvalidTemplateError ( "Mismatched braces in %s" % template ) if anchor : result . append ( '$' ) return "" . join ( result ) , params | Convert a URL template to a regular expression . | 490 | 10 |
13,322 | def add_callback ( self , phase , fn ) : try : self . __callbacks [ phase ] . append ( fn ) except KeyError : raise KeyError ( "Invalid callback phase '%s'. Must be one of %s" % ( phase , _callback_phases ) ) | Adds a callback to the context . | 61 | 7 |
13,323 | def add_property ( self , name , fn , cached = True ) : if name in self . __properties : raise KeyError ( "Trying to add a property '%s' that already exists on this %s object." % ( name , self . __class__ . __name__ ) ) self . __properties [ name ] = ( fn , cached ) | Adds a property to the Context . | 76 | 7 |
13,324 | def path ( self , args , kw ) : params = self . _pop_params ( args , kw ) if args or kw : raise InvalidArgumentError ( "Extra parameters (%s, %s) when building path for %s" % ( args , kw , self . template ) ) return self . build_url ( * * params ) | Builds the URL path fragment for this route . | 76 | 10 |
13,325 | def add ( self , template , resource , name = None ) : # Special case for standalone handler functions if hasattr ( resource , '_rhino_meta' ) : route = Route ( template , Resource ( resource ) , name = name , ranges = self . ranges ) else : route = Route ( template , resource , name = name , ranges = self . ranges ) obj_id = id ( resource ) if obj_id not in self . _lookup : # It's ok to have multiple routes for the same object id, the # lookup will return the first one. self . _lookup [ obj_id ] = route if name is not None : if name in self . named_routes : raise InvalidArgumentError ( "A route named '%s' already exists in this %s object." % ( name , self . __class__ . __name__ ) ) self . named_routes [ name ] = route self . routes . append ( route ) | Add a route to a resource . | 206 | 7 |
13,326 | def add_ctx_property ( self , name , fn , cached = True ) : if name in [ item [ 0 ] for item in self . _ctx_properties ] : raise InvalidArgumentError ( "A context property name '%s' already exists." % name ) self . _ctx_properties . append ( [ name , ( fn , cached ) ] ) | Install a context property . | 77 | 5 |
13,327 | def path ( self , target , args , kw ) : if type ( target ) in string_types : if ':' in target : # Build path a nested route name prefix , rest = target . split ( ':' , 1 ) route = self . named_routes [ prefix ] prefix_params = route . _pop_params ( args , kw ) prefix_path = route . path ( [ ] , prefix_params ) next_mapper = route . resource return prefix_path + next_mapper . path ( rest , args , kw ) else : # Build path for a named route return self . named_routes [ target ] . path ( args , kw ) elif isinstance ( target , Route ) : # Build path for a route instance, used by build_url('.') for route in self . routes : if route is target : return route . path ( args , kw ) raise InvalidArgumentError ( "Route '%s' not found in this %s object." % ( target , self . __class__ . __name__ ) ) else : # Build path for resource by object id target_id = id ( target ) if target_id in self . _lookup : return self . _lookup [ target_id ] . path ( args , kw ) raise InvalidArgumentError ( "No Route found for target '%s' in this %s object." % ( target , self . __class__ . __name__ ) ) | Build a URL path fragment for a resource or route . | 315 | 11 |
13,328 | def wsgi ( self , environ , start_response ) : request = Request ( environ ) ctx = Context ( request ) try : try : response = self ( request , ctx ) ctx . _run_callbacks ( 'finalize' , ( request , response ) ) response = response . conditional_to ( request ) except HTTPException as e : response = e . response except Exception : self . handle_error ( request , ctx ) response = InternalServerError ( ) . response response . add_callback ( lambda : ctx . _run_callbacks ( 'close' ) ) return response ( environ , start_response ) finally : ctx . _run_callbacks ( 'teardown' , log_errors = True ) | Implements the mapper s WSGI interface . | 161 | 11 |
13,329 | def start_server ( self , host = 'localhost' , port = 9000 , app = None ) : from wsgiref . simple_server import make_server if app is None : app = self . wsgi server = make_server ( host , port , app ) server_addr = "%s:%s" % ( server . server_name , server . server_port ) print "Server listening at http://%s/" % server_addr server . serve_forever ( ) | Start a wsgiref . simple_server based server to run this mapper . | 105 | 18 |
13,330 | def generate_docs ( app ) : config = app . config config_dir = app . env . srcdir source_root = os . path . join ( config_dir , config . apidoc_source_root ) output_root = os . path . join ( config_dir , config . apidoc_output_root ) execution_dir = os . path . join ( config_dir , '..' ) # Remove any files generated by earlier builds cleanup ( output_root ) command = [ 'sphinx-apidoc' , '-f' , '-o' , output_root , source_root ] # Exclude anything else we were specifically asked to for exclude in config . apidoc_exclude : command . append ( os . path . join ( source_root , exclude ) ) process = Popen ( command , cwd = execution_dir ) process . wait ( ) | Run sphinx - apidoc to generate Python API documentation for the project . | 192 | 17 |
13,331 | def cleanup ( output_root ) : if os . path . exists ( output_root ) : if os . path . isdir ( output_root ) : rmtree ( output_root ) else : os . remove ( output_root ) | Remove any reST files which were generated by this extension | 51 | 11 |
13,332 | def build ( cls : Type [ T ] , data : Generic ) -> T : fields = fields_dict ( cls ) kwargs : Dict [ str , Any ] = { } for key , value in data . items ( ) : if key in fields : if isinstance ( value , Mapping ) : t = fields [ key ] . type if issubclass ( t , Auto ) : value = t . build ( value ) else : value = Auto . generate ( value , name = key . title ( ) ) kwargs [ key ] = value else : log . debug ( f"got unknown attribute {key} for {cls.__name__}" ) return cls ( * * kwargs ) | Build objects from dictionaries recursively . | 153 | 9 |
13,333 | def generate ( cls : Type [ T ] , data : Generic , name : str = None , * , recursive : bool = True ) -> T : if name is None : name = cls . __name__ kls = make_class ( name , { k : ib ( default = None ) for k in data } , bases = ( cls , ) ) data = { k : ( cls . generate ( v , k . title ( ) ) if recursive and isinstance ( v , Mapping ) else v ) for k , v in data . items ( ) } return kls ( * * data ) | Build dataclasses and objects from dictionaries recursively . | 129 | 13 |
13,334 | def emit_answer_event ( sender , instance , * * kwargs ) : if not issubclass ( sender , Answer ) or not kwargs [ 'created' ] : return logger = get_events_logger ( ) logger . emit ( 'answer' , { "user_id" : instance . user_id , "is_correct" : instance . item_asked_id == instance . item_answered_id , "context_id" : [ instance . context_id ] if instance . context_id else [ ] , "item_id" : instance . item_id , "response_time_ms" : instance . response_time , "params" : { "session_id" : instance . session_id , "guess" : instance . guess , "practice_set_id" : instance . practice_set_id , "config_id" : instance . config_id , } } ) | Save answer event to log file . | 200 | 7 |
13,335 | def get_all_available_leaves ( self , language = None , forbidden_item_ids = None ) : return self . get_all_leaves ( language = language , forbidden_item_ids = forbidden_item_ids ) | Get all available leaves . | 51 | 5 |
13,336 | def get_children_graph ( self , item_ids = None , language = None , forbidden_item_ids = None ) : if forbidden_item_ids is None : forbidden_item_ids = set ( ) def _children ( item_ids ) : if item_ids is None : items = Item . objects . filter ( active = True ) . prefetch_related ( 'children' ) else : item_ids = [ ii for iis in item_ids . values ( ) for ii in iis ] items = Item . objects . filter ( id__in = item_ids , active = True ) . prefetch_related ( 'children' ) return { item . id : sorted ( [ _item . id for _item in item . children . all ( ) if _item . active and _item . id not in forbidden_item_ids ] ) for item in items if item . id not in forbidden_item_ids } if item_ids is None : return self . _reachable_graph ( None , _children , language = language ) else : graph = self . get_children_graph ( None , language , forbidden_item_ids = forbidden_item_ids ) return self . _subset_graph ( graph , set ( item_ids ) - set ( forbidden_item_ids ) ) | Get a subgraph of items reachable from the given set of items through the child relation . | 278 | 19 |
13,337 | def get_parents_graph ( self , item_ids , language = None ) : def _parents ( item_ids ) : if item_ids is None : items = Item . objects . filter ( active = True ) . prefetch_related ( 'parents' ) else : item_ids = [ ii for iis in item_ids . values ( ) for ii in iis ] items = Item . objects . filter ( id__in = item_ids , active = True ) . prefetch_related ( 'parents' ) return { item . id : sorted ( [ _item . id for _item in item . parents . all ( ) ] ) for item in items } return self . _reachable_graph ( item_ids , _parents , language = language ) if item_ids is None : return self . _reachable_graph ( None , _parents , language = language ) else : graph = self . get_parents_graph ( None , language ) return self . _subset_graph ( graph , item_ids ) | Get a subgraph of items reachable from the given set of items through the parent relation . | 218 | 19 |
13,338 | def get_graph ( self , item_ids , language = None ) : def _related ( item_ids ) : if item_ids is None : items = Item . objects . filter ( active = True ) . prefetch_related ( 'parents' , 'children' ) else : item_ids = [ ii for iis in item_ids . values ( ) for ii in iis ] items = Item . objects . filter ( id__in = item_ids , active = True ) . prefetch_related ( 'parents' , 'children' ) return { item . id : sorted ( [ _item . id for rel in [ item . parents . all ( ) , item . children . all ( ) ] for _item in rel ] ) for item in items } if item_ids is None : return self . _reachable_graph ( None , _related , language = language ) else : graph = self . get_graph ( None , language ) return self . _subset_graph ( graph , item_ids ) | Get a subgraph of items reachable from the given set of items through any relation . | 216 | 18 |
13,339 | def translate_item_ids ( self , item_ids , language , is_nested = None ) : if is_nested is None : def is_nested_fun ( x ) : return True elif isinstance ( is_nested , bool ) : def is_nested_fun ( x ) : return is_nested else : is_nested_fun = is_nested all_item_type_ids = ItemType . objects . get_all_item_type_ids ( ) groupped = proso . list . group_by ( item_ids , by = lambda item_id : all_item_type_ids [ item_id ] ) result = { } for item_type_id , items in groupped . items ( ) : with timeit ( 'translating item type {}' . format ( item_type_id ) ) : item_type = ItemType . objects . get_all_types ( ) [ item_type_id ] model = ItemType . objects . get_model ( item_type_id ) kwargs = { '{}__in' . format ( item_type [ 'foreign_key' ] ) : items } if 'language' in item_type : kwargs [ item_type [ 'language' ] ] = language if any ( [ not is_nested_fun ( item_id ) for item_id in items ] ) and hasattr ( model . objects , 'prepare_related' ) : objs = model . objects . prepare_related ( ) elif hasattr ( model . objects , 'prepare' ) : objs = model . objects . prepare ( ) else : objs = model . objects for obj in objs . filter ( * * kwargs ) : item_id = getattr ( obj , item_type [ 'foreign_key' ] ) result [ item_id ] = obj . to_json ( nested = is_nested_fun ( item_id ) ) return result | Translate a list of item ids to JSON objects which reference them . | 430 | 15 |
13,340 | def get_leaves ( self , item_ids = None , language = None , forbidden_item_ids = None ) : forbidden_item_ids = set ( ) if forbidden_item_ids is None else set ( forbidden_item_ids ) children = self . get_children_graph ( item_ids , language = language , forbidden_item_ids = forbidden_item_ids ) counts = self . get_children_counts ( active = None ) if item_ids is None : # not leaves item_ids = set ( children . keys ( ) ) def _get_leaves ( item_id ) : leaves = set ( ) def __search ( item_ids ) : result = set ( flatten ( [ children . get ( item_id , [ ] ) for item_id in item_ids ] ) ) new_leaves = { item_id for item_id in result if item_id not in children . keys ( ) } leaves . update ( new_leaves ) return result - new_leaves fixed_point ( is_zero = lambda to_visit : len ( to_visit ) == 0 , minus = lambda to_visit , visited : to_visit - visited , plus = lambda visited_x , visited_y : visited_x | visited_y , f = __search , x = { item_id } ) leaves = { leaf for leaf in leaves if counts [ leaf ] == 0 } if len ( leaves ) > 0 : return leaves if counts [ item_id ] == 0 and item_id not in forbidden_item_ids : return { item_id } return set ( ) return { item_id : _get_leaves ( item_id ) for item_id in item_ids } | Get mapping of items to their reachable leaves . Leaves having inactive relations to other items are omitted . | 374 | 20 |
13,341 | def get_all_leaves ( self , item_ids = None , language = None , forbidden_item_ids = None ) : return sorted ( set ( flatten ( self . get_leaves ( item_ids , language = language , forbidden_item_ids = forbidden_item_ids ) . values ( ) ) ) ) | Get all leaves reachable from the given set of items . Leaves having inactive relations to other items are omitted . | 71 | 22 |
13,342 | def get_reference_fields ( self , exclude_models = None ) : if exclude_models is None : exclude_models = [ ] result = [ ] for django_model in django . apps . apps . get_models ( ) : if any ( [ issubclass ( django_model , m ) for m in exclude_models ] ) : continue for django_field in django_model . _meta . fields : if isinstance ( django_field , models . ForeignKey ) and django_field . related . to == Item : result = [ ( m , f ) for ( m , f ) in result if not issubclass ( django_model , m ) ] result . append ( ( django_model , django_field ) ) return result | Get all Django model fields which reference the Item model . | 167 | 11 |
13,343 | def override_parent_subgraph ( self , parent_subgraph , invisible_edges = None ) : with transaction . atomic ( ) : if invisible_edges is None : invisible_edges = set ( ) children = list ( parent_subgraph . keys ( ) ) all_old_relations = dict ( proso . list . group_by ( list ( ItemRelation . objects . filter ( child_id__in = children ) ) , by = lambda relation : relation . child_id ) ) to_delete = set ( ) for child_id , parents in parent_subgraph . items ( ) : old_relations = { relation . parent_id : relation for relation in all_old_relations . get ( child_id , [ ] ) } for parent_id in parents : if parent_id not in old_relations : ItemRelation . objects . create ( parent_id = parent_id , child_id = child_id , visible = ( child_id , parent_id ) not in invisible_edges ) elif old_relations [ parent_id ] . visible != ( ( child_id , parent_id ) not in invisible_edges ) : old_relations [ parent_id ] . visible = ( child_id , parent_id ) not in invisible_edges old_relations [ parent_id ] . save ( ) to_delete |= { old_relations [ parent_id ] . pk for parent_id in set ( old_relations . keys ( ) ) - set ( parents ) } ItemRelation . objects . filter ( pk__in = to_delete ) . delete ( ) | Get all items with outcoming edges from the given subgraph drop all their parent relations and then add parents according to the given subgraph . | 349 | 28 |
13,344 | def query_api ( self , data = None , endpoint = 'SMS' ) : url = self . api_url % endpoint if data : response = requests . post ( url , data = data , auth = self . auth ) else : response = requests . get ( url , auth = self . auth ) try : response . raise_for_status ( ) except HTTPError as e : raise HTTPError ( 'HTTP %s\n%s' % ( response . status_code , response . text ) ) return response . text | Send a request to the 46elks API . Fetches SMS history as JSON by default sends a HTTP POST request with the incoming data dictionary as a urlencoded query if data is provided otherwise HTTP GET | 112 | 41 |
13,345 | def validate_number ( self , number ) : if not isinstance ( number , str ) : raise ElksException ( 'Recipient phone number may not be empty' ) if number [ 0 ] == '+' and len ( number ) > 2 and len ( number ) < 16 : return True else : raise ElksException ( "Phone number must be of format +CCCXXX..." ) | Checks if a number looks somewhat like a E . 164 number . Not an exhaustive check as the API takes care of that | 81 | 25 |
13,346 | def format_sms_payload ( self , message , to , sender = 'elkme' , options = [ ] ) : self . validate_number ( to ) if not isinstance ( message , str ) : message = " " . join ( message ) message = message . rstrip ( ) sms = { 'from' : sender , 'to' : to , 'message' : message } for option in options : if option not in [ 'dontlog' , 'dryrun' , 'flashsms' ] : raise ElksException ( 'Option %s not supported' % option ) sms [ option ] = 'yes' return sms | Helper function to create a SMS payload with little effort | 141 | 10 |
13,347 | def send_sms ( self , message , to , sender = 'elkme' , options = [ ] ) : sms = self . format_sms_payload ( message = message , to = to , sender = sender , options = options ) return self . query_api ( sms ) | Sends a text message to a configuration conf containing the message in the message paramter | 65 | 17 |
13,348 | async def get_types ( self ) : async with aiohttp . ClientSession ( ) as session : async with session . get ( 'https://api.weeb.sh/images/types' , headers = self . __headers ) as resp : if resp . status == 200 : return ( await resp . json ( ) ) [ 'types' ] else : raise Exception ( ( await resp . json ( ) ) [ 'message' ] ) | Gets all available types . | 94 | 6 |
13,349 | async def get_image ( self , imgtype = None , tags = None , nsfw = None , hidden = None , filetype = None ) : if not imgtype and not tags : raise MissingTypeOrTags ( "'get_image' requires at least one of either type or tags." ) if imgtype and not isinstance ( imgtype , str ) : raise TypeError ( "type of 'imgtype' must be str." ) if tags and not isinstance ( tags , list ) : raise TypeError ( "type of 'tags' must be list or None." ) if hidden and not isinstance ( hidden , bool ) : raise TypeError ( "type of 'hidden' must be bool or None." ) if nsfw and not isinstance ( nsfw , bool ) and ( isinstance ( nsfw , str ) and nsfw == 'only' ) : raise TypeError ( "type of 'nsfw' must be str, bool or None." ) if filetype and not isinstance ( filetype , str ) : raise TypeError ( "type of 'filetype' must be str." ) url = 'https://api.weeb.sh/images/random' + ( f'?type={imgtype}' if imgtype else '' ) + ( f'{"?" if not imgtype else "&"}tags={",".join(tags)}' if tags else '' ) + ( f'&nsfw={nsfw.lower()}' if nsfw else '' ) + ( f'&hidden={hidden}' if hidden else '' ) + ( f'&filetype={filetype}' if filetype else '' ) async with aiohttp . ClientSession ( ) as session : async with session . get ( url , headers = self . __headers ) as resp : if resp . status == 200 : js = await resp . json ( ) return [ js [ 'url' ] , js [ 'id' ] , js [ 'fileType' ] ] else : raise Exception ( ( await resp . json ( ) ) [ 'message' ] ) | Request an image from weeb . sh . | 442 | 9 |
13,350 | async def generate_image ( self , imgtype , face = None , hair = None ) : if not isinstance ( imgtype , str ) : raise TypeError ( "type of 'imgtype' must be str." ) if face and not isinstance ( face , str ) : raise TypeError ( "type of 'face' must be str." ) if hair and not isinstance ( hair , str ) : raise TypeError ( "type of 'hair' must be str." ) if ( face or hair ) and imgtype != 'awooo' : raise InvalidArguments ( '\'face\' and \'hair\' are arguments only available on the \'awoo\' image type' ) url = f'https://api.weeb.sh/auto-image/generate?type={imgtype}' + ( "&face=" + face if face else "" ) + ( "&hair=" + hair if hair else "" ) async with aiohttp . ClientSession ( ) as session : async with session . get ( url , headers = self . __headers ) as resp : if resp . status == 200 : return await resp . read ( ) else : raise Exception ( ( await resp . json ( ) ) [ 'message' ] ) | Generate a basic image using the auto - image endpoint of weeb . sh . | 260 | 17 |
13,351 | async def generate_status ( self , status , avatar = None ) : if not isinstance ( status , str ) : raise TypeError ( "type of 'status' must be str." ) if avatar and not isinstance ( avatar , str ) : raise TypeError ( "type of 'avatar' must be str." ) url = f'https://api.weeb.sh/auto-image/discord-status?status={status}' + ( f'&avatar={urllib.parse.quote(avatar, safe="")}' if avatar else '' ) async with aiohttp . ClientSession ( ) as session : async with session . get ( url , headers = self . __headers ) as resp : if resp . status == 200 : return await resp . read ( ) else : raise Exception ( ( await resp . json ( ) ) [ 'message' ] ) | Generate a discord status icon below the image provided . | 189 | 11 |
13,352 | async def generate_waifu_insult ( self , avatar ) : if not isinstance ( avatar , str ) : raise TypeError ( "type of 'avatar' must be str." ) async with aiohttp . ClientSession ( ) as session : async with session . post ( "https://api.weeb.sh/auto-image/waifu-insult" , headers = self . __headers , data = { "avatar" : avatar } ) as resp : if resp . status == 200 : return await resp . read ( ) else : raise Exception ( ( await resp . json ( ) ) [ 'message' ] ) | Generate a waifu insult image . | 138 | 9 |
13,353 | async def generate_license ( self , title , avatar , badges = None , widgets = None ) : if not isinstance ( title , str ) : raise TypeError ( "type of 'title' must be str." ) if not isinstance ( avatar , str ) : raise TypeError ( "type of 'avatar' must be str." ) if badges and not isinstance ( badges , list ) : raise TypeError ( "type of 'badges' must be list." ) if widgets and not isinstance ( widgets , list ) : raise TypeError ( "type of 'widgets' must be list." ) data = { "title" : title , "avatar" : avatar } if badges and len ( badges ) <= 3 : data [ 'badges' ] = badges if widgets and len ( widgets ) <= 3 : data [ 'widgets' ] = widgets async with aiohttp . ClientSession ( ) as session : async with session . post ( "https://api.weeb.sh/auto-image/license" , headers = self . __headers , data = data ) as resp : if resp . status == 200 : return await resp . read ( ) else : raise Exception ( ( await resp . json ( ) ) [ 'message' ] ) | Generate a license . | 266 | 5 |
13,354 | async def generate_love_ship ( self , target_one , target_two ) : if not isinstance ( target_one , str ) : raise TypeError ( "type of 'target_one' must be str." ) if not isinstance ( target_two , str ) : raise TypeError ( "type of 'target_two' must be str." ) data = { "targetOne" : target_one , "targetTwo" : target_two } async with aiohttp . ClientSession ( ) as session : async with session . post ( "https://api.weeb.sh/auto-image/love-ship" , headers = self . __headers , data = data ) as resp : if resp . status == 200 : return await resp . read ( ) else : raise Exception ( ( await resp . json ( ) ) [ 'message' ] ) | Generate a love ship . | 184 | 6 |
13,355 | def launch_command ( command , parameter = '' ) : result = '' # Transform into an array if it not one if not isinstance ( parameter , list ) : parameter = [ parameter ] # Iterate on all parameter with action & put them in result string for name in parameter : result += subprocess . Popen ( 'cozy-monitor {} {}' . format ( command , name ) , shell = True , stdout = subprocess . PIPE ) . stdout . read ( ) return result | Can launch a cozy - monitor command | 105 | 7 |
13,356 | def status ( app_name = None , only_cozy = False , as_boolean = False ) : apps = { } # Get all apps status & slip them apps_status = subprocess . Popen ( 'cozy-monitor status' , shell = True , stdout = subprocess . PIPE ) . stdout . read ( ) apps_status = apps_status . split ( '\n' ) # Parse result to store them in apps dictionary for app_status in apps_status : if app_status : app_status = ANSI_ESCAPE . sub ( '' , app_status ) . split ( ': ' ) if len ( app_status ) == 2 : current_status = app_status [ 1 ] if as_boolean : if app_status [ 1 ] == 'up' : current_status = True else : current_status = False if only_cozy and app_status [ 0 ] not in SYSTEM_APPS : apps [ app_status [ 0 ] ] = current_status else : apps [ app_status [ 0 ] ] = current_status # Return app status if get as param or return all apps status if app_name : return apps . get ( app_name , None ) else : return apps | Get apps status | 270 | 3 |
13,357 | def transitive_closure ( m , orig , rel ) : #FIXME: Broken for now links = list ( m . match ( orig , rel ) ) for link in links : yield link [ 0 ] [ TARGET ] yield from transitive_closure ( m , target , rel ) | Generate the closure over a transitive relationship in depth - first fashion | 60 | 14 |
13,358 | def all_origins ( m ) : seen = set ( ) for link in m . match ( ) : origin = link [ ORIGIN ] if origin not in seen : seen . add ( origin ) yield origin | Generate all unique statement origins in the given model | 44 | 10 |
13,359 | def column ( m , linkpart ) : assert linkpart in ( 0 , 1 , 2 , 3 ) seen = set ( ) for link in m . match ( ) : val = link [ linkpart ] if val not in seen : seen . add ( val ) yield val | Generate all parts of links according to the parameter | 57 | 10 |
13,360 | def resourcetypes ( rid , model ) : types = [ ] for o , r , t , a in model . match ( rid , VTYPE_REL ) : types . append ( t ) return types | Return a list of Versa types for a resource | 45 | 10 |
13,361 | def replace_values ( in_m , out_m , map_from = ( ) , map_to = ( ) ) : for link in in_m . match ( ) : new_link = list ( link ) if map_from : if link [ ORIGIN ] in map_from : new_link [ ORIGIN ] = map_to [ map_from . index ( link [ ORIGIN ] ) ] new_link [ ATTRIBUTES ] = link [ ATTRIBUTES ] . copy ( ) out_m . add ( * new_link ) return | Make a copy of a model with one value replaced with another | 123 | 12 |
13,362 | def replace_entity_resource ( model , oldres , newres ) : oldrids = set ( ) for rid , link in model : if link [ ORIGIN ] == oldres or link [ TARGET ] == oldres or oldres in link [ ATTRIBUTES ] . values ( ) : oldrids . add ( rid ) new_link = ( newres if o == oldres else o , r , newres if t == oldres else t , dict ( ( k , newres if v == oldres else v ) for k , v in a . items ( ) ) ) model . add ( * new_link ) model . delete ( oldrids ) return | Replace one entity in the model with another with the same links | 145 | 13 |
13,363 | def duplicate_statements ( model , oldorigin , neworigin , rfilter = None ) : for o , r , t , a in model . match ( oldorigin ) : if rfilter is None or rfilter ( o , r , t , a ) : model . add ( I ( neworigin ) , r , t , a ) return | Take links with a given origin and create duplicate links with the same information but a new origin | 72 | 18 |
13,364 | def uniquify ( model ) : seen = set ( ) to_remove = set ( ) for ix , ( o , r , t , a ) in model : hashable_link = ( o , r , t ) + tuple ( sorted ( a . items ( ) ) ) #print(hashable_link) if hashable_link in seen : to_remove . add ( ix ) seen . add ( hashable_link ) model . remove ( to_remove ) return | Remove all duplicate relationships | 103 | 4 |
13,365 | def jsonload ( model , fp ) : dumped_list = json . load ( fp ) for link in dumped_list : if len ( link ) == 2 : sid , ( s , p , o , a ) = link elif len ( link ) == 4 : #canonical ( s , p , o , a ) = link tt = a . get ( '@target-type' ) if tt == '@iri-ref' : o = I ( o ) a . pop ( '@target-type' , None ) else : continue model . add ( s , p , o , a ) return | Load Versa model dumped into JSON form either raw or canonical | 132 | 12 |
13,366 | def jsondump ( model , fp ) : fp . write ( '[' ) links_ser = [ ] for link in model : links_ser . append ( json . dumps ( link ) ) fp . write ( ',\n' . join ( links_ser ) ) fp . write ( ']' ) | Dump Versa model into JSON form | 68 | 8 |
13,367 | def set_statics ( self ) : if not os . path . exists ( self . results_dir ) : return None try : shutil . copytree ( os . path . join ( self . templates_dir , 'css' ) , os . path . join ( self . results_dir , 'css' ) ) shutil . copytree ( os . path . join ( self . templates_dir , 'scripts' ) , os . path . join ( self . results_dir , 'scripts' ) ) shutil . copytree ( os . path . join ( self . templates_dir , 'fonts' ) , os . path . join ( self . results_dir , 'fonts' ) ) except OSError as e : if e . errno == 17 : # File exists print ( "WARNING : existing output directory for static files, will not replace them" ) else : # in all other cases, re-raise exceptions raise try : shutil . copytree ( os . path . join ( self . templates_dir , 'img' ) , os . path . join ( self . results_dir , 'img' ) ) except OSError as e : pass | Create statics directory and copy files in it | 251 | 9 |
13,368 | def write_report ( self , template ) : with open ( self . fn , 'w' ) as f : f . write ( template ) | Write the compiled jinja template to the results file | 30 | 11 |
13,369 | def set_raw_holding_register ( self , name , value ) : self . _conn . write_register ( unit = self . _slave , address = ( self . _holding_regs [ name ] [ 'addr' ] ) , value = value ) | Write to register by name . | 56 | 6 |
13,370 | def unzip ( filepath , output_path ) : filename = os . path . split ( filepath ) [ 1 ] ( name , extension ) = os . path . splitext ( filename ) extension = extension [ 1 : ] . lower ( ) extension2 = os . path . splitext ( name ) [ 1 ] [ 1 : ] . lower ( ) if extension not in ZIP_EXTENSIONS : raise Exception ( "Impossible to extract archive file %s" % filepath ) extract_command = "unzip" output_args = "-d" if extension == 'bz2' and extension2 == 'tar' : extract_command = "tar -xjf" output_args = "-C" elif extension == 'gz' and extension2 == 'tar' : extract_command = "tar -xzf" output_args = "-C" elif extension == 'xz' and extension2 == 'tar' : extract_command = "tar -xJf" output_args = "-C" elif extension == 'bz2' : extract_command = "bunzip2 -dc " output_args = ">" output_path = os . path . join ( output_path , name ) elif extension == 'rar' : extract_command = "unrar x" output_args = "" elif extension == 'gz' : extract_command = "gunzip" output_args = "" elif extension == 'tar' : extract_command = "tar -xf" output_args = "-C" elif extension == 'tbz2' : extract_command = "tar -xjf" output_args = "-C" elif extension == 'tgz' : extract_command = "tar -xzf" output_args = "-C" elif extension == 'zip' : extract_command = "unzip" output_args = "-d" elif extension == 'Z' : extract_command = "uncompress" output_args = "" elif extension == '7z' : extract_command = "7z x" output_args = "" elif extension == 'xz' : extract_command = "unxz" output_args = "" elif extension == 'ace' : extract_command = "unace" output_args = "" elif extension == 'iso' : extract_command = "7z x" output_args = "" elif extension == 'arj' : extract_command = "7z x" output_args = "" command = """%(extract_command)s "%(filepath)s" %(output_args)s "%(output_folder)s" """ params = { 'extract_command' : extract_command , 'filepath' : filepath , 'output_folder' : output_path , 'output_args' : output_args , } result = os . system ( command % params ) return result | Unzip an archive file | 633 | 5 |
13,371 | def _configure_sockets ( self , config , with_streamer = False , with_forwarder = False ) : rc_port = config . get ( 'rc_port' , 5001 ) self . result_collector . set_hwm ( 0 ) self . result_collector . bind ( "tcp://*:{}" . format ( rc_port ) ) self . poller . register ( self . result_collector , zmq . POLLIN ) | Configure sockets for HQ | 104 | 5 |
13,372 | def wait_turrets ( self , wait_for ) : print ( "Waiting for %d turrets" % ( wait_for - len ( self . turrets_manager . turrets ) ) ) while len ( self . turrets_manager . turrets ) < wait_for : self . turrets_manager . status_request ( ) socks = dict ( self . poller . poll ( 2000 ) ) if self . result_collector in socks : data = self . result_collector . recv_json ( ) self . turrets_manager . process_message ( data ) print ( "Waiting for %d turrets" % ( wait_for - len ( self . turrets_manager . turrets ) ) ) | Wait until wait_for turrets are connected and ready | 147 | 10 |
13,373 | def run ( self ) : elapsed = 0 run_time = self . config [ 'run_time' ] start_time = time . time ( ) t = time . time self . turrets_manager . start ( self . transaction_context ) self . started = True while elapsed <= run_time : try : self . _run_loop_action ( ) self . _print_status ( elapsed ) elapsed = t ( ) - start_time except ( Exception , KeyboardInterrupt ) : print ( "\nStopping test, sending stop command to turrets" ) self . turrets_manager . stop ( ) self . stats_handler . write_remaining ( ) traceback . print_exc ( ) break self . turrets_manager . stop ( ) print ( "\n\nProcessing all remaining messages... This could take time depending on message volume" ) t = time . time ( ) self . result_collector . unbind ( self . result_collector . LAST_ENDPOINT ) self . _clean_queue ( ) print ( "took %s" % ( time . time ( ) - t ) ) | Run the hight quarter lunch the turrets and wait for results | 236 | 12 |
13,374 | def query ( logfile , jobID = None ) : joblist = logfile . readFromLogfile ( ) if jobID and type ( jobID ) == type ( 1 ) : command = [ 'qstat' , '-j' , str ( jobID ) ] else : command = [ 'qstat' ] processoutput = subprocess . Popen ( command , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) . communicate ( ) output = processoutput [ 0 ] serror = processoutput [ 1 ] # Form command jobs = { } if type ( jobID ) == type ( 1 ) : if serror . find ( "Following jobs do not exist" ) != - 1 : return False else : return True if not output . strip ( ) : colorprinter . message ( "No jobs running at present." ) output = output . strip ( ) . split ( "\n" ) if len ( output ) > 2 : for line in output [ 2 : ] : # We assume that our script names contain no spaces for the parsing below to work tokens = line . split ( ) jid = int ( tokens [ 0 ] ) jobstate = tokens [ 4 ] details = { "jobid" : jid , "prior" : tokens [ 1 ] , "name" : tokens [ 2 ] , "user" : tokens [ 3 ] , "state" : jobstate , "submit/start at" : "%s %s" % ( tokens [ 5 ] , tokens [ 6 ] ) } jataskID = 0 if jobstate == "r" : details [ "queue" ] = tokens [ 7 ] details [ "slots" ] = tokens [ 8 ] elif jobstate == "qw" : details [ "slots" ] = tokens [ 7 ] if len ( tokens ) >= 9 : jataskID = tokens [ 8 ] details [ "ja-task-ID" ] = jataskID if len ( tokens ) > 9 : jataskID = tokens [ 9 ] details [ "ja-task-ID" ] = jataskID jobs [ jid ] = jobs . get ( jid ) or { } jobs [ jid ] [ jataskID ] = details if joblist . get ( jid ) : jobdir = joblist [ jid ] [ "Directory" ] jobtime = joblist [ jid ] [ "TimeInSeconds" ] colorprinter . message ( "Job %d submitted %d minutes ago. Status: '%s'. Destination directory: %s." % ( jid , jobtime / 60 , jobstate , jobdir ) ) else : colorprinter . message ( "Job %d submitted at %s %s. Status: '%s'. Destination directory unknown." % ( jid , tokens [ 5 ] , tokens [ 6 ] , jobstate ) ) return True | If jobID is an integer then return False if the job has finished and True if it is still running . Otherwise returns a table of jobs run by the user . | 614 | 33 |
13,375 | def set_tmp_folder ( ) : output = "%s" % datetime . datetime . now ( ) for char in [ ' ' , ':' , '.' , '-' ] : output = output . replace ( char , '' ) output . strip ( ) tmp_folder = os . path . join ( tempfile . gettempdir ( ) , output ) return tmp_folder | Create a temporary folder using the current time in which the zip can be extracted and which should be destroyed afterward . | 81 | 22 |
13,376 | def file_logger ( app , level = None ) : path = os . path . join ( os . getcwd ( ) , 'var' , 'logs' , 'app.log' ) max_bytes = 1024 * 1024 * 2 file_handler = RotatingFileHandler ( filename = path , mode = 'a' , maxBytes = max_bytes , backupCount = 10 ) if level is None : level = logging . INFO file_handler . setLevel ( level ) log_format = '%(asctime)s %(levelname)s: %(message)s' log_format += ' [in %(pathname)s:%(lineno)d]' file_handler . setFormatter ( logging . Formatter ( log_format ) ) return file_handler | Get file logger Returns configured fire logger ready to be attached to app | 171 | 13 |
13,377 | def tag ( self , repository_tag , tags = [ ] ) : if not isinstance ( repository_tag , six . string_types ) : raise TypeError ( 'repository_tag must be a string' ) if not isinstance ( tags , list ) : raise TypeError ( 'tags must be a list.' ) if ':' in repository_tag : repository , tag = repository_tag . split ( ':' ) tags . append ( tag ) else : repository = repository_tag if not tags : tags . append ( 'latest' ) for tag in tags : repo_tag = "{0}:{1}" . format ( repository , tag ) if repo_tag not in self . repo_tags : logger . info ( "Tagging Image: {0} Repo Tag: {1}" . format ( self . identifier , repo_tag ) ) self . repo_tags = self . repo_tags + ( repo_tag , ) # always going to force tags until a feature is added to allow users to specify. try : self . client . tag ( self . id , repository , tag ) except : self . client . tag ( self . id , repository , tag , force = True ) | Tags image with one or more tags . | 251 | 8 |
13,378 | def build ( client , repository_tag , docker_file , tag = None , use_cache = False ) : if not isinstance ( client , docker . Client ) : raise TypeError ( "client needs to be of type docker.Client." ) if not isinstance ( docker_file , six . string_types ) or not os . path . exists ( docker_file ) : # TODO: need to add path stuff for git and http etc. raise Exception ( "docker file path doesn't exist: {0}" . format ( docker_file ) ) if not isinstance ( repository_tag , six . string_types ) : raise TypeError ( 'repository must be a string' ) if not tag : tag = 'latest' if not isinstance ( use_cache , bool ) : raise TypeError ( "use_cache must be a bool. {0} was passed." . format ( use_cache ) ) no_cache = not use_cache if ':' not in repository_tag : repository_tag = "{0}:{1}" . format ( repository_tag , tag ) file_obj = None try : if os . path . isfile ( docker_file ) : path = os . getcwd ( ) docker_file = "./{0}" . format ( os . path . relpath ( docker_file ) ) # TODO: support using file_obj in the future. Needed for post pre hooks and the injector. # with open(docker_file) as Dockerfile: # testing = Dockerfile.read() # file_obj = BytesIO(testing.encode('utf-8')) response = client . build ( path = path , nocache = no_cache , # custom_context=True, dockerfile = docker_file , # fileobj=file_obj, tag = repository_tag , rm = True , stream = True ) else : response = client . build ( path = docker_file , tag = repository_tag , rm = True , nocache = no_cache , stream = True ) except Exception as e : raise e finally : if file_obj : file_obj . close ( ) parse_stream ( response ) client . close ( ) return Image ( client , repository_tag ) | Build a docker image | 478 | 4 |
13,379 | def get_grades_by_regid_and_term ( regid , term ) : url = "{}/{},{},{}.json" . format ( enrollment_res_url_prefix , term . year , term . quarter , regid ) return _json_to_grades ( get_resource ( url ) , regid , term ) | Returns a StudentGrades model for the regid and term . | 75 | 13 |
13,380 | def _requires_refresh_token ( self ) : expires_on = datetime . datetime . strptime ( self . login_data [ 'token' ] [ 'expiresOn' ] , '%Y-%m-%dT%H:%M:%SZ' ) refresh = datetime . datetime . utcnow ( ) + datetime . timedelta ( seconds = 30 ) return expires_on < refresh | Check if a refresh of the token is needed | 95 | 9 |
13,381 | def _request_token ( self , force = False ) : if self . login_data is None : raise RuntimeError ( "Don't have a token to refresh" ) if not force : if not self . _requires_refresh_token ( ) : # no need to refresh as token is valid return True headers = { "Accept" : "application/json" , 'Authorization' : 'Bearer ' + self . login_data [ 'token' ] [ 'accessToken' ] } url = self . api_base_url + "account/RefreshToken" response = requests . get ( url , headers = headers , timeout = 10 ) if response . status_code != 200 : return False refresh_data = response . json ( ) if 'token' not in refresh_data : return False self . login_data [ 'token' ] [ 'accessToken' ] = refresh_data [ 'accessToken' ] self . login_data [ 'token' ] [ 'issuedOn' ] = refresh_data [ 'issuedOn' ] self . login_data [ 'token' ] [ 'expiresOn' ] = refresh_data [ 'expiresOn' ] return True | Request a new auth token | 252 | 5 |
13,382 | def get_home ( self , home_id = None ) : now = datetime . datetime . utcnow ( ) if self . home and now < self . home_refresh_at : return self . home if not self . _do_auth ( ) : raise RuntimeError ( "Unable to login" ) if home_id is None : home_id = self . home_id url = self . api_base_url + "Home/GetHomeById" params = { "homeId" : home_id } headers = { "Accept" : "application/json" , 'Authorization' : 'bearer ' + self . login_data [ 'token' ] [ 'accessToken' ] } response = requests . get ( url , params = params , headers = headers , timeout = 10 ) if response . status_code != 200 : raise RuntimeError ( "{} response code when getting home" . format ( response . status_code ) ) home = response . json ( ) if self . cache_home : self . home = home self . home_refresh_at = ( datetime . datetime . utcnow ( ) + datetime . timedelta ( minutes = 5 ) ) return home | Get the data about a home | 259 | 6 |
13,383 | def get_zones ( self ) : home_data = self . get_home ( ) if not home_data [ 'isSuccess' ] : return [ ] zones = [ ] for receiver in home_data [ 'data' ] [ 'receivers' ] : for zone in receiver [ 'zones' ] : zones . append ( zone ) return zones | Get all zones | 77 | 3 |
13,384 | def get_zone_names ( self ) : zone_names = [ ] for zone in self . get_zones ( ) : zone_names . append ( zone [ 'name' ] ) return zone_names | Get the name of all zones | 45 | 6 |
13,385 | def get_zone ( self , zone_name ) : for zone in self . get_zones ( ) : if zone_name == zone [ 'name' ] : return zone raise RuntimeError ( "Unknown zone" ) | Get the information about a particular zone | 47 | 7 |
13,386 | def get_zone_temperature ( self , zone_name ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return zone [ 'currentTemperature' ] | Get the temperature for a zone | 49 | 6 |
13,387 | def set_target_temperature_by_id ( self , zone_id , target_temperature ) : if not self . _do_auth ( ) : raise RuntimeError ( "Unable to login" ) data = { "ZoneId" : zone_id , "TargetTemperature" : target_temperature } headers = { "Accept" : "application/json" , "Content-Type" : "application/json" , 'Authorization' : 'Bearer ' + self . login_data [ 'token' ] [ 'accessToken' ] } url = self . api_base_url + "Home/ZoneTargetTemperature" response = requests . post ( url , data = json . dumps ( data ) , headers = headers , timeout = 10 ) if response . status_code != 200 : return False zone_change_data = response . json ( ) return zone_change_data . get ( "isSuccess" , False ) | Set the target temperature for a zone by id | 200 | 9 |
13,388 | def set_target_temperture_by_name ( self , zone_name , target_temperature ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return self . set_target_temperature_by_id ( zone [ "zoneId" ] , target_temperature ) | Set the target temperature for a zone by name | 77 | 9 |
13,389 | def activate_boost_by_id ( self , zone_id , target_temperature , num_hours = 1 ) : if not self . _do_auth ( ) : raise RuntimeError ( "Unable to login" ) zones = [ zone_id ] data = { "ZoneIds" : zones , "NumberOfHours" : num_hours , "TargetTemperature" : target_temperature } headers = { "Accept" : "application/json" , "Content-Type" : "application/json" , 'Authorization' : 'Bearer ' + self . login_data [ 'token' ] [ 'accessToken' ] } url = self . api_base_url + "Home/ActivateZoneBoost" response = requests . post ( url , data = json . dumps ( data ) , headers = headers , timeout = 10 ) if response . status_code != 200 : return False boost_data = response . json ( ) return boost_data . get ( "isSuccess" , False ) | Activate boost for a zone based on the numeric id | 216 | 11 |
13,390 | def activate_boost_by_name ( self , zone_name , target_temperature , num_hours = 1 ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return self . activate_boost_by_id ( zone [ "zoneId" ] , target_temperature , num_hours ) | Activate boost by the name of the zone | 81 | 9 |
13,391 | def deactivate_boost_by_name ( self , zone_name ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return self . deactivate_boost_by_id ( zone [ "zoneId" ] ) | Deactivate boost by the name of the zone | 63 | 9 |
13,392 | def set_mode_by_id ( self , zone_id , mode ) : if not self . _do_auth ( ) : raise RuntimeError ( "Unable to login" ) data = { "ZoneId" : zone_id , "mode" : mode . value } headers = { "Accept" : "application/json" , "Content-Type" : "application/json" , 'Authorization' : 'Bearer ' + self . login_data [ 'token' ] [ 'accessToken' ] } url = self . api_base_url + "Home/SetZoneMode" response = requests . post ( url , data = json . dumps ( data ) , headers = headers , timeout = 10 ) if response . status_code != 200 : return False mode_data = response . json ( ) return mode_data . get ( "isSuccess" , False ) | Set the mode by using the zone id Supported zones are available in the enum Mode | 188 | 16 |
13,393 | def set_mode_by_name ( self , zone_name , mode ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return self . set_mode_by_id ( zone [ "zoneId" ] , mode ) | Set the mode by using the name of the zone | 65 | 10 |
13,394 | def get_zone_mode ( self , zone_name ) : zone = self . get_zone ( zone_name ) if zone is None : raise RuntimeError ( "Unknown zone" ) return ZoneMode ( zone [ 'mode' ] ) | Get the mode for a zone | 51 | 6 |
13,395 | def _convertToElementList ( elements_list ) : elements = [ ] current_element = [ ] for node_index in elements_list : if node_index == - 1 : elements . append ( current_element ) current_element = [ ] else : current_element . append ( node_index ) return elements | Take a list of element node indexes deliminated by - 1 and convert it into a list element node indexes list . | 68 | 23 |
13,396 | def get_locale ( self ) : if not self . locale : try : import flask_babel as babel self . locale = str ( babel . get_locale ( ) ) . lower ( ) except ImportError : from flask import current_app self . locale = current_app . config [ 'DEFAULT_LOCALE' ] . lower return self . locale | Get locale Will extract locale from application trying to get one from babel first then if not available will get one from app config | 79 | 25 |
13,397 | def get_language ( self ) : locale = self . get_locale ( ) language = locale if '_' in locale : language = locale [ 0 : locale . index ( '_' ) ] return language | Get language If locale contains region will cut that off . Returns just the language code | 45 | 16 |
13,398 | def localize_humanize ( self ) : import humanize language = self . get_language ( ) if language != 'en' : humanize . i18n . activate ( language ) | Setts current language to humanize | 40 | 7 |
13,399 | def get_filters ( self ) : filters = dict ( ) for filter in self . get_filter_names ( ) : filters [ filter ] = getattr ( self , filter ) return filters | Returns a dictionary of filters | 41 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.