idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
9,900 | def _gather_field_values ( item , * , fields = None , field_map = FIELD_MAP , normalize_values = False , normalize_func = normalize_value ) : it = get_item_tags ( item ) if fields is None : fields = list ( it . keys ( ) ) normalize = normalize_func if normalize_values else lambda x : str ( x ) field_values = [ ] for fi... | Create a tuple of normalized metadata field values . | 143 | 9 |
9,901 | def find_existing_items ( src , dst , * , fields = None , field_map = None , normalize_values = False , normalize_func = normalize_value ) : if field_map is None : field_map = FIELD_MAP dst_keys = { _gather_field_values ( dst_item , fields = fields , field_map = field_map , normalize_values = normalize_values , normali... | Find items from an item collection that are in another item collection . | 173 | 13 |
9,902 | def monitor ( self , message , * args , * * kws ) : if self . isEnabledFor ( MON ) : # Yes, logger takes its '*args' as 'args'. self . _log ( MON , message , args , * * kws ) | Define a monitoring logger that will be added to Logger | 55 | 12 |
9,903 | def monitor ( msg , * args , * * kwargs ) : if len ( logging . root . handlers ) == 0 : logging . basicConfig ( ) logging . root . monitor ( msg , * args , * * kwargs ) | Log a message with severity MON on the root logger . | 50 | 11 |
9,904 | def format ( self , record ) : try : n = record . n except AttributeError : n = 'default' try : message = record . message except AttributeError : message = record . msg senml = OrderedDict ( uid = "hyperstream" , bt = datetime . utcfromtimestamp ( record . created ) . isoformat ( ) [ : - 3 ] + 'Z' , e = [ OrderedDict ... | The formatting function | 122 | 3 |
9,905 | def teardown ( self ) : with self . _teardown_lock : if not self . _teardown_called : self . _teardown_called = True if len ( self . _acquiring_session_ids ) > 0 : logger . info ( f"Destroying all sessions that have not acquired keys: {self._acquiring_session_ids}..." ) for session_id in self . _acquiring_session_ids :... | Tears down the instance removing any remaining sessions that this instance has created . | 190 | 15 |
9,906 | def we_are_in_lyon ( ) : import socket try : hostname = socket . gethostname ( ) ip = socket . gethostbyname ( hostname ) except socket . gaierror : return False return ip . startswith ( "134.158." ) | Check if we are on a Lyon machine | 60 | 8 |
9,907 | def read_csv ( text , sep = "\t" ) : import pandas as pd # no top level load to make a faster import of db return pd . read_csv ( StringIO ( text ) , sep = "\t" ) | Create a DataFrame from CSV text | 52 | 7 |
9,908 | def add_datetime ( dataframe , timestamp_key = 'UNIXTIME' ) : def convert_data ( timestamp ) : return datetime . fromtimestamp ( float ( timestamp ) / 1e3 , UTC_TZ ) try : log . debug ( "Adding DATETIME column to the data" ) converted = dataframe [ timestamp_key ] . apply ( convert_data ) dataframe [ 'DATETIME' ] = con... | Add an additional DATETIME column with standar datetime format . | 115 | 15 |
9,909 | def show_ahrs_calibration ( clb_upi , version = '3' ) : db = DBManager ( ) ahrs_upi = clbupi2ahrsupi ( clb_upi ) print ( "AHRS UPI: {}" . format ( ahrs_upi ) ) content = db . _get_content ( "show_product_test.htm?upi={0}&" "testtype=AHRS-CALIBRATION-v{1}&n=1&out=xml" . format ( ahrs_upi , version ) ) . replace ( '\n' ,... | Show AHRS calibration data for given clb_upi . | 288 | 13 |
9,910 | def _datalog ( self , parameter , run , maxrun , det_id ) : values = { 'parameter_name' : parameter , 'minrun' : run , 'maxrun' : maxrun , 'detid' : det_id , } data = urlencode ( values ) content = self . _get_content ( 'streamds/datalognumbers.txt?' + data ) if content . startswith ( 'ERROR' ) : log . error ( content ... | Extract data from database | 204 | 5 |
9,911 | def _add_converted_units ( self , dataframe , parameter , key = 'VALUE' ) : convert_unit = self . parameters . get_converter ( parameter ) try : log . debug ( "Adding unit converted DATA_VALUE to the data" ) dataframe [ key ] = dataframe [ 'DATA_VALUE' ] . apply ( convert_unit ) except KeyError : log . warning ( "Missi... | Add an additional DATA_VALUE column with converted VALUEs | 112 | 12 |
9,912 | def to_det_id ( self , det_id_or_det_oid ) : try : int ( det_id_or_det_oid ) except ValueError : return self . get_det_id ( det_id_or_det_oid ) else : return det_id_or_det_oid | Convert det ID or OID to det ID | 69 | 10 |
9,913 | def to_det_oid ( self , det_id_or_det_oid ) : try : int ( det_id_or_det_oid ) except ValueError : return det_id_or_det_oid else : return self . get_det_oid ( det_id_or_det_oid ) | Convert det OID or ID to det OID | 69 | 11 |
9,914 | def _load_parameters ( self ) : parameters = self . _get_json ( 'allparam/s' ) data = { } for parameter in parameters : # There is a case-chaos in the DB data [ parameter [ 'Name' ] . lower ( ) ] = parameter self . _parameters = ParametersContainer ( data ) | Retrieve a list of available parameters from the database | 72 | 10 |
9,915 | def trigger_setup ( self , runsetup_oid ) : r = self . _get_content ( "jsonds/rslite/s?rs_oid={}&upifilter=1.1.2.2.3/*" . format ( runsetup_oid ) ) data = json . loads ( r ) [ 'Data' ] if not data : log . error ( "Empty dataset." ) return raw_setup = data [ 0 ] det_id = raw_setup [ 'DetID' ] name = raw_setup [ 'Name' ]... | Retrieve the trigger setup for a given runsetup OID | 455 | 12 |
9,916 | def detx ( self , det_id , t0set = None , calibration = None ) : url = 'detx/{0}?' . format ( det_id ) # '?' since it's ignored if no args if t0set is not None : url += '&t0set=' + t0set if calibration is not None : url += '&calibrid=' + calibration detx = self . _get_content ( url ) return detx | Retrieve the detector file for given detector id | 99 | 9 |
9,917 | def _get_json ( self , url ) : content = self . _get_content ( 'jsonds/' + url ) try : json_content = json . loads ( content . decode ( ) ) except AttributeError : json_content = json . loads ( content ) if json_content [ 'Comment' ] : log . warning ( json_content [ 'Comment' ] ) if json_content [ 'Result' ] != 'OK' : ... | Get JSON - type content | 118 | 5 |
9,918 | def _get_content ( self , url ) : target_url = self . _db_url + '/' + unquote ( url ) # .encode('utf-8')) log . debug ( "Opening '{0}'" . format ( target_url ) ) try : f = self . opener . open ( target_url ) except HTTPError as e : log . error ( "HTTP error, your session may be expired." ) log . error ( e ) if input ( ... | Get HTML content | 247 | 3 |
9,919 | def opener ( self ) : if self . _opener is None : log . debug ( "Creating connection handler" ) opener = build_opener ( ) if self . _cookies : log . debug ( "Appending cookies" ) else : log . debug ( "No cookies to append" ) for cookie in self . _cookies : cookie_str = cookie . name + '=' + cookie . value opener . addh... | A reusable connection manager | 130 | 4 |
9,920 | def request_sid_cookie ( self , username , password ) : log . debug ( "Requesting SID cookie" ) target_url = self . _login_url + '?usr={0}&pwd={1}&persist=y' . format ( username , password ) cookie = urlopen ( target_url ) . read ( ) return cookie | Request cookie for permanent session token . | 77 | 7 |
9,921 | def restore_session ( self , cookie ) : log . debug ( "Restoring session from cookie: {}" . format ( cookie ) ) opener = build_opener ( ) opener . addheaders . append ( ( 'Cookie' , cookie ) ) self . _opener = opener | Establish databse connection using permanent session cookie | 60 | 10 |
9,922 | def login ( self , username , password ) : log . debug ( "Logging in to the DB" ) opener = self . _build_opener ( ) values = { 'usr' : username , 'pwd' : password } req = self . _make_request ( self . _login_url , values ) try : log . debug ( "Sending login request" ) f = opener . open ( req ) except URLError as e : lo... | Login to the database and store cookies for upcoming requests . | 181 | 11 |
9,923 | def _update_streams ( self ) : content = self . _db . _get_content ( "streamds" ) self . _stream_df = read_csv ( content ) . sort_values ( "STREAM" ) self . _streams = None for stream in self . streams : setattr ( self , stream , self . __getattr__ ( stream ) ) | Update the list of available straems | 81 | 7 |
9,924 | def streams ( self ) : if self . _streams is None : self . _streams = list ( self . _stream_df [ "STREAM" ] . values ) return self . _streams | A list of available streams | 44 | 5 |
9,925 | def help ( self , stream ) : if stream not in self . streams : log . error ( "Stream '{}' not found in the database." . format ( stream ) ) params = self . _stream_df [ self . _stream_df [ 'STREAM' ] == stream ] . values [ 0 ] self . _print_stream_parameters ( params ) | Show the help for a given stream . | 79 | 8 |
9,926 | def _print_stream_parameters ( self , values ) : cprint ( "{0}" . format ( * values ) , "magenta" , attrs = [ "bold" ] ) print ( "{4}" . format ( * values ) ) cprint ( " available formats: {1}" . format ( * values ) , "blue" ) cprint ( " mandatory selectors: {2}" . format ( * values ) , "red" ) cprint ( " optional sele... | Print a coloured help for a given tuple of stream parameters . | 121 | 12 |
9,927 | def get ( self , stream , fmt = 'txt' , * * kwargs ) : sel = '' . join ( [ "&{0}={1}" . format ( k , v ) for ( k , v ) in kwargs . items ( ) ] ) url = "streamds/{0}.{1}?{2}" . format ( stream , fmt , sel [ 1 : ] ) data = self . _db . _get_content ( url ) if not data : log . error ( "No data found at URL '%s'." % url ) ... | Get the data for a given stream manually | 162 | 8 |
9,928 | def get_parameter ( self , parameter ) : parameter = self . _get_parameter_name ( parameter ) return self . _parameters [ parameter ] | Return a dict for given parameter | 34 | 6 |
9,929 | def get_converter ( self , parameter ) : if parameter not in self . _converters : param = self . get_parameter ( parameter ) try : scale = float ( param [ 'Scale' ] ) except KeyError : scale = 1 def convert ( value ) : # easy_scale = float(param['EasyScale']) # easy_scale_multiplier = float(param['EasyScaleMultiplier']... | Generate unit conversion function for given parameter | 98 | 8 |
9,930 | def unit ( self , parameter ) : parameter = self . _get_parameter_name ( parameter ) . lower ( ) return self . _parameters [ parameter ] [ 'Unit' ] | Get the unit for given parameter | 40 | 6 |
9,931 | def oid2name ( self , oid ) : if not self . _oid_lookup : for name , data in self . _parameters . items ( ) : self . _oid_lookup [ data [ 'OID' ] ] = data [ 'Name' ] return self . _oid_lookup [ oid ] | Look up the parameter name for a given OID | 72 | 10 |
9,932 | def via_dom_id ( self , dom_id , det_id ) : try : return DOM . from_json ( [ d for d in self . _json if d [ "DOMId" ] == dom_id and d [ "DetOID" ] == det_id ] [ 0 ] ) except IndexError : log . critical ( "No DOM found for DOM ID '{0}'" . format ( dom_id ) ) | Return DOM for given dom_id | 94 | 7 |
9,933 | def via_clb_upi ( self , clb_upi , det_id ) : try : return DOM . from_json ( [ d for d in self . _json if d [ "CLBUPI" ] == clb_upi and d [ "DetOID" ] == det_id ] [ 0 ] ) except IndexError : log . critical ( "No DOM found for CLB UPI '{0}'" . format ( clb_upi ) ) | return DOM for given CLB UPI | 106 | 8 |
9,934 | def upi ( self ) : parameter = 'UPI' if parameter not in self . _by : self . _populate ( by = parameter ) return self . _by [ parameter ] | A dict of CLBs with UPI as key | 40 | 10 |
9,935 | def dom_id ( self ) : parameter = 'DOMID' if parameter not in self . _by : self . _populate ( by = parameter ) return self . _by [ parameter ] | A dict of CLBs with DOM ID as key | 41 | 10 |
9,936 | def base ( self , du ) : parameter = 'base' if parameter not in self . _by : self . _by [ parameter ] = { } for clb in self . upi . values ( ) : if clb . floor == 0 : self . _by [ parameter ] [ clb . du ] = clb return self . _by [ parameter ] [ du ] | Return the base CLB for a given DU | 80 | 9 |
9,937 | def get_results ( self , stream , time_interval ) : query = stream . stream_id . as_raw ( ) query [ 'datetime' ] = { '$gt' : time_interval . start , '$lte' : time_interval . end } with switch_db ( StreamInstanceModel , 'hyperstream' ) : for instance in StreamInstanceModel . objects ( __raw__ = query ) : yield StreamIns... | Get the results for a given stream | 110 | 7 |
9,938 | def seek_to_packet ( self , index ) : pointer_position = self . packet_positions [ index ] self . blob_file . seek ( pointer_position , 0 ) | Move file pointer to the packet with given index . | 40 | 10 |
9,939 | def next_blob ( self ) : try : length = struct . unpack ( '<i' , self . blob_file . read ( 4 ) ) [ 0 ] except struct . error : raise StopIteration header = CLBHeader ( file_obj = self . blob_file ) blob = { 'CLBHeader' : header } remaining_length = length - header . size pmt_data = [ ] pmt_raw_data = self . blob_file .... | Generate next blob in file | 233 | 6 |
9,940 | def getKendallTauScore ( myResponse , otherResponse ) : # variables kt = 0 list1 = myResponse . values ( ) list2 = otherResponse . values ( ) if len ( list1 ) <= 1 : return kt # runs through list1 for itr1 in range ( 0 , len ( list1 ) - 1 ) : # runs through list2 for itr2 in range ( itr1 + 1 , len ( list2 ) ) : # check... | Returns the Kendall Tau Score | 228 | 5 |
9,941 | def getCandScoresMap ( self , profile ) : # Currently, we expect the profile to contain complete ordering over candidates. elecType = profile . getElecType ( ) if elecType != "soc" and elecType != "toc" : print ( "ERROR: unsupported election type" ) exit ( ) # Initialize our dictionary so that all candidates have a sco... | Returns a dictonary that associates the integer representation of each candidate with the score they recieved in the profile . | 251 | 23 |
9,942 | def getMov ( self , profile ) : # from . import mov import mov return mov . MoVScoring ( profile , self . getScoringVector ( profile ) ) | Returns an integer that is equal to the margin of victory of the election profile . | 37 | 16 |
9,943 | def getCandScoresMap ( self , profile ) : # Currently, we expect the profile to contain complete ordering over candidates. elecType = profile . getElecType ( ) if elecType != "soc" and elecType != "toc" : print ( "ERROR: unsupported profile type" ) exit ( ) bucklinScores = dict ( ) rankMaps = profile . getRankMaps ( ) ... | Returns a dictionary that associates integer representations of each candidate with their Bucklin score . | 257 | 16 |
9,944 | def getCandScoresMap ( self , profile ) : # Currently, we expect the profile to contain complete ordering over candidates. Ties are # allowed however. elecType = profile . getElecType ( ) if elecType != "soc" and elecType != "toc" : print ( "ERROR: unsupported election type" ) exit ( ) wmg = profile . getWmg ( ) # Init... | Returns a dictionary that associates integer representations of each candidate with their maximin score . | 252 | 16 |
9,945 | def computeStrongestPaths ( self , profile , pairwisePreferences ) : cands = profile . candMap . keys ( ) numCands = len ( cands ) # Initialize the two-dimensional dictionary that will hold our strongest paths. strongestPaths = dict ( ) for cand in cands : strongestPaths [ cand ] = dict ( ) for i in range ( 1 , numCand... | Returns a two - dimensional dictionary that associates every pair of candidates cand1 and cand2 with the strongest path from cand1 to cand2 . | 278 | 28 |
9,946 | def computePairwisePreferences ( self , profile ) : cands = profile . candMap . keys ( ) # Initialize the two-dimensional dictionary that will hold our pairwise preferences. pairwisePreferences = dict ( ) for cand in cands : pairwisePreferences [ cand ] = dict ( ) for cand1 in cands : for cand2 in cands : if cand1 != c... | Returns a two - dimensional dictionary that associates every pair of candidates cand1 and cand2 with number of voters who prefer cand1 to cand2 . | 317 | 29 |
9,947 | def getCandScoresMap ( self , profile ) : cands = profile . candMap . keys ( ) pairwisePreferences = self . computePairwisePreferences ( profile ) strongestPaths = self . computeStrongestPaths ( profile , pairwisePreferences ) # For each candidate, determine how many times p[E,X] >= p[X,E] using a variant of the # Floy... | Returns a dictionary that associates integer representations of each candidate with the number of other candidates for which her strongest path to the other candidate is greater than the other candidate s stronget path to her . | 170 | 38 |
9,948 | def STVsocwinners ( self , profile ) : ordering = profile . getOrderVectors ( ) prefcounts = profile . getPreferenceCounts ( ) m = profile . numCands if min ( ordering [ 0 ] ) == 0 : startstate = set ( range ( m ) ) else : startstate = set ( range ( 1 , m + 1 ) ) ordering , startstate = self . preprocessing ( ordering ... | Returns an integer list that represents all possible winners of a profile under STV rule . | 461 | 17 |
9,949 | def baldwinsoc_winners ( self , profile ) : ordering = profile . getOrderVectors ( ) m = profile . numCands prefcounts = profile . getPreferenceCounts ( ) if min ( ordering [ 0 ] ) == 0 : startstate = set ( range ( m ) ) else : startstate = set ( range ( 1 , m + 1 ) ) wmg = self . getWmg2 ( prefcounts , ordering , star... | Returns an integer list that represents all possible winners of a profile under baldwin rule . | 536 | 17 |
9,950 | def getWmg2 ( self , prefcounts , ordering , state , normalize = False ) : # Initialize a new dictionary for our final weighted majority graph. wmgMap = dict ( ) for cand in state : wmgMap [ cand ] = dict ( ) for cand1 , cand2 in itertools . combinations ( state , 2 ) : wmgMap [ cand1 ] [ cand2 ] = 0 wmgMap [ cand2 ] [... | Generate a weighted majority graph that represents the whole profile . The function will return a two - dimensional dictionary that associates integer representations of each pair of candidates cand1 and cand2 with the number of times cand1 is ranked above cand2 minus the number of times cand2 is ranked above cand1 . | 349 | 60 |
9,951 | def PluRunOff_single_winner ( self , profile ) : # Currently, we expect the profile to contain complete ordering over candidates. Ties are # allowed however. elecType = profile . getElecType ( ) if elecType != "soc" and elecType != "toc" and elecType != "csv" : print ( "ERROR: unsupported election type" ) exit ( ) # In... | Returns a number that associates the winner of a profile under Plurality with Runoff rule . | 447 | 19 |
9,952 | def PluRunOff_cowinners ( self , profile ) : # Currently, we expect the profile to contain complete ordering over candidates. Ties are # allowed however. elecType = profile . getElecType ( ) if elecType != "soc" and elecType != "toc" and elecType != "csv" : print ( "ERROR: unsupported election type" ) exit ( ) # Initia... | Returns a list that associates all the winners of a profile under Plurality with Runoff rule . | 549 | 20 |
9,953 | def SNTV_winners ( self , profile , K ) : # Currently, we expect the profile to contain complete ordering over candidates. Ties are # allowed however. elecType = profile . getElecType ( ) if elecType != "soc" and elecType != "toc" and elecType != "csv" : print ( "ERROR: unsupported election type" ) exit ( ) m = profile... | Returns a list that associates all the winners of a profile under Single non - transferable vote rule . | 203 | 20 |
9,954 | def Borda_mean_winners ( self , profile ) : n_candidates = profile . numCands prefcounts = profile . getPreferenceCounts ( ) len_prefcounts = len ( prefcounts ) rankmaps = profile . getRankMaps ( ) values = zeros ( [ len_prefcounts , n_candidates ] , dtype = int ) if min ( list ( rankmaps [ 0 ] . keys ( ) ) ) == 0 : de... | Returns a list that associates all the winners of a profile under The Borda - mean rule . | 296 | 19 |
9,955 | def apply_t0 ( self , hits ) : if HAVE_NUMBA : apply_t0_nb ( hits . time , hits . dom_id , hits . channel_id , self . _lookup_tables ) else : n = len ( hits ) cal = np . empty ( n ) lookup = self . _calib_by_dom_and_channel for i in range ( n ) : calib = lookup [ hits [ 'dom_id' ] [ i ] ] [ hits [ 'channel_id' ] [ i ] ... | Apply only t0s | 133 | 5 |
9,956 | def _get_file_index_str ( self ) : file_index = str ( self . file_index ) if self . n_digits is not None : file_index = file_index . zfill ( self . n_digits ) return file_index | Create a string out of the current file_index | 58 | 10 |
9,957 | def prepare_blobs ( self ) : self . raw_header = self . extract_header ( ) if self . cache_enabled : self . _cache_offsets ( ) | Populate the blobs | 38 | 5 |
9,958 | def extract_header ( self ) : self . log . info ( "Extracting the header" ) raw_header = self . raw_header = defaultdict ( list ) first_line = self . blob_file . readline ( ) first_line = try_decode_string ( first_line ) self . blob_file . seek ( 0 , 0 ) if not first_line . startswith ( str ( 'start_run' ) ) : self . l... | Create a dictionary with the EVT header information | 290 | 9 |
9,959 | def get_blob ( self , index ) : self . log . info ( "Retrieving blob #{}" . format ( index ) ) if index > len ( self . event_offsets ) - 1 : self . log . info ( "Index not in cache, caching offsets" ) self . _cache_offsets ( index , verbose = False ) self . blob_file . seek ( self . event_offsets [ index ] , 0 ) blob =... | Return a blob with the event at the given index | 169 | 10 |
9,960 | def process ( self , blob = None ) : try : blob = self . get_blob ( self . index ) except IndexError : self . log . info ( "Got an IndexError, trying the next file" ) if ( self . basename or self . filenames ) and self . file_index < self . index_stop : self . file_index += 1 self . log . info ( "Now at file_index={}" ... | Pump the next blob to the modules | 341 | 8 |
9,961 | def _cache_offsets ( self , up_to_index = None , verbose = True ) : if not up_to_index : if verbose : self . print ( "Caching event file offsets, this may take a bit." ) self . blob_file . seek ( 0 , 0 ) self . event_offsets = [ ] if not self . raw_header : self . event_offsets . append ( 0 ) else : self . blob_file . ... | Cache all event offsets . | 289 | 5 |
9,962 | def _record_offset ( self ) : offset = self . blob_file . tell ( ) self . event_offsets . append ( offset ) | Stores the current file pointer position | 31 | 7 |
9,963 | def _create_blob ( self ) : blob = None for line in self . blob_file : line = try_decode_string ( line ) line = line . strip ( ) if line == '' : self . log . info ( "Ignoring empty line..." ) continue if line . startswith ( 'end_event:' ) and blob : blob [ 'raw_header' ] = self . raw_header return blob try : tag , valu... | Parse the next event from the current file position | 229 | 10 |
9,964 | def runserver ( project_name ) : DIR = os . listdir ( project_name ) if 'settings.py' not in DIR : raise NotImplementedError ( 'No file called: settings.py found in %s' % project_name ) CGI_BIN_FOLDER = os . path . join ( project_name , 'cgi' , 'cgi-bin' ) CGI_FOLDER = os . path . join ( project_name , 'cgi' ) if not o... | Runs a python cgi server in a subprocess . | 168 | 12 |
9,965 | def getUtility ( self , decision , sample , aggregationMode = "avg" ) : utilities = self . getUtilities ( decision , sample ) if aggregationMode == "avg" : utility = numpy . mean ( utilities ) elif aggregationMode == "min" : utility = min ( utilities ) elif aggregationMode == "max" : utility = max ( utilities ) else : ... | Get the utility of a given decision given a preference . | 98 | 11 |
9,966 | def getUtilities ( self , decision , orderVector ) : scoringVector = self . getScoringVector ( orderVector ) utilities = [ ] for alt in decision : altPosition = orderVector . index ( alt ) utility = float ( scoringVector [ altPosition ] ) if self . isLoss == True : utility = - 1 * utility utilities . append ( utility )... | Returns a floats that contains the utilities of every candidate in the decision . | 79 | 14 |
9,967 | def getUtilities ( self , decision , binaryRelations ) : m = len ( binaryRelations ) utilities = [ ] for cand in decision : tops = [ cand - 1 ] index = 0 while index < len ( tops ) : s = tops [ index ] for j in range ( m ) : if j == s : continue if binaryRelations [ j ] [ s ] > 0 : if j not in tops : tops . append ( j ... | Returns a floats that contains the utilities of every candidate in the decision . This was adapted from code written by Lirong Xia . | 152 | 26 |
9,968 | def db_credentials ( self ) : try : username = self . config . get ( 'DB' , 'username' ) password = self . config . get ( 'DB' , 'password' ) except Error : username = input ( "Please enter your KM3NeT DB username: " ) password = getpass . getpass ( "Password: " ) return username , password | Return username and password for the KM3NeT WebDB . | 81 | 13 |
9,969 | def get_path ( src ) : # pragma: no cover res = None while not res : if res is False : print ( colored ( 'You must provide a path to an existing directory!' , 'red' ) ) print ( 'You need a local clone or release of (a fork of) ' 'https://github.com/{0}' . format ( src ) ) res = input ( colored ( 'Local path to {0}: ' .... | Prompts the user to input a local path . | 140 | 11 |
9,970 | def execute_all ( self ) : for workflow_id in self . workflows : if self . workflows [ workflow_id ] . online : for interval in self . workflows [ workflow_id ] . requested_intervals : logging . info ( "Executing workflow {} over interval {}" . format ( workflow_id , interval ) ) self . workflows [ workflow_id ] . exec... | Execute all workflows | 86 | 5 |
9,971 | def execute ( self , sources , sink , interval , alignment_stream = None ) : if not isinstance ( interval , TimeInterval ) : raise TypeError ( 'Expected TimeInterval, got {}' . format ( type ( interval ) ) ) # logging.info(self.message(interval)) if interval . end > sink . channel . up_to_timestamp : raise StreamNotAva... | Execute the tool over the given time interval . If an alignment stream is given the output instances will be aligned to this stream | 324 | 25 |
9,972 | def create_stream ( self , stream_id , sandbox = None ) : if stream_id in self . streams : raise StreamAlreadyExistsError ( "Stream with id '{}' already exists" . format ( stream_id ) ) if sandbox is not None : raise ValueError ( "Cannot use sandboxes with memory streams" ) stream = Stream ( channel = self , stream_id ... | Must be overridden by deriving classes must create the stream according to the tool and return its unique identifier stream_id | 125 | 24 |
9,973 | def purge_all ( self , remove_definitions = False ) : for stream_id in list ( self . streams . keys ( ) ) : self . purge_stream ( stream_id , remove_definition = remove_definitions ) | Clears all streams in the channel - use with caution! | 50 | 12 |
9,974 | def update_state ( self , up_to_timestamp ) : for stream_id in self . streams : self . streams [ stream_id ] . calculated_intervals = TimeIntervals ( [ ( MIN_DATE , up_to_timestamp ) ] ) self . up_to_timestamp = up_to_timestamp | Call this function to ensure that the channel is up to date at the time of timestamp . I . e . all the streams that have been created before or at that timestamp are calculated exactly until up_to_timestamp . | 73 | 45 |
9,975 | def compile_regex ( self , pattern , flags = 0 ) : pattern_re = regex . compile ( '(?P<substr>%\{(?P<fullname>(?P<patname>\w+)(?::(?P<subname>\w+))?)\})' ) while 1 : matches = [ md . groupdict ( ) for md in pattern_re . finditer ( pattern ) ] if len ( matches ) == 0 : break for md in matches : if md [ 'patname' ] in se... | Compile regex from pattern and pattern_dict | 380 | 9 |
9,976 | def _load_patterns ( self , folders , pattern_dict = None ) : if pattern_dict is None : pattern_dict = { } for folder in folders : for file in os . listdir ( folder ) : if regex . match ( '^[\w-]+$' , file ) : self . _load_pattern_file ( os . path . join ( folder , file ) , pattern_dict ) return pattern_dict | Load all pattern from all the files in folders | 93 | 9 |
9,977 | def load_pkl ( filenames ) : if not isinstance ( filenames , ( list , tuple ) ) : filenames = [ filenames ] times = [ ] for name in filenames : name = str ( name ) with open ( name , 'rb' ) as file : loaded_obj = pickle . load ( file ) if not isinstance ( loaded_obj , Times ) : raise TypeError ( "At least one loaded ob... | Unpickle file contents . | 128 | 6 |
9,978 | async def retrieve ( self , url , * * kwargs ) : try : async with self . websession . request ( 'GET' , url , * * kwargs ) as res : if res . status != 200 : raise Exception ( "Could not retrieve information from API" ) if res . content_type == 'application/json' : return await res . json ( ) return await res . text ( )... | Issue API requests . | 104 | 4 |
9,979 | def _to_number ( cls , string ) : try : if float ( string ) - int ( string ) == 0 : return int ( string ) return float ( string ) except ValueError : try : return float ( string ) except ValueError : return string | Convert string to int or float . | 54 | 8 |
9,980 | async def stations ( self ) : data = await self . retrieve ( API_DISTRITS ) Station = namedtuple ( 'Station' , [ 'latitude' , 'longitude' , 'idAreaAviso' , 'idConselho' , 'idDistrito' , 'idRegiao' , 'globalIdLocal' , 'local' ] ) _stations = [ ] for station in data [ 'data' ] : _station = Station ( self . _to_number ( s... | Retrieve stations . | 206 | 4 |
9,981 | async def weather_type_classe ( self ) : data = await self . retrieve ( url = API_WEATHER_TYPE ) self . weather_type = dict ( ) for _type in data [ 'data' ] : self . weather_type [ _type [ 'idWeatherType' ] ] = _type [ 'descIdWeatherTypePT' ] return self . weather_type | Retrieve translation for weather type . | 83 | 7 |
9,982 | async def wind_type_classe ( self ) : data = await self . retrieve ( url = API_WIND_TYPE ) self . wind_type = dict ( ) for _type in data [ 'data' ] : self . wind_type [ int ( _type [ 'classWindSpeed' ] ) ] = _type [ 'descClassWindSpeedDailyPT' ] return self . wind_type | Retrieve translation for wind type . | 86 | 7 |
9,983 | def register ( self , plugin ) : for listener in plugin . listeners : self . listeners [ listener ] . add ( plugin ) self . plugins . add ( plugin ) plugin . messenger = self . messages plugin . start ( ) | Add the plugin to our set of listeners for each message that it listens to tell it to use our messages Queue for communication and start it up . | 46 | 30 |
9,984 | def start ( self ) : self . recieve ( 'APP_START' ) self . alive = True while self . alive : message , payload = self . messages . get ( ) if message == 'APP_STOP' : for plugin in self . plugins : plugin . recieve ( 'SHUTDOWN' ) self . alive = False else : self . recieve ( message , payload ) | Send APP_START to any plugins that listen for it and loop around waiting for messages and sending them to their listening plugins until it s time to shutdown . | 83 | 32 |
9,985 | def choose ( self , palette ) : try : self . _cycler = cycle ( self . colours [ palette ] ) except KeyError : raise KeyError ( "Chose one of the following colour palettes: {0}" . format ( self . available ) ) | Pick a palette | 55 | 3 |
9,986 | def refresh_styles ( self ) : import matplotlib . pyplot as plt self . colours = { } for style in plt . style . available : try : style_colours = plt . style . library [ style ] [ 'axes.prop_cycle' ] self . colours [ style ] = [ c [ 'color' ] for c in list ( style_colours ) ] except KeyError : continue self . colours [... | Load all available styles | 159 | 4 |
9,987 | def get_file_object ( username , password , utc_start = None , utc_stop = None ) : if not utc_start : utc_start = datetime . now ( ) if not utc_stop : utc_stop = utc_start + timedelta ( days = 1 ) logging . info ( "Downloading schedules for username [%s] in range [%s] to " "[%s]." % ( username , utc_start , utc_stop ) ... | Make the connection . Return a file - like object . | 322 | 11 |
9,988 | def process_file_object ( file_obj , importer , progress ) : logging . info ( "Processing schedule data." ) try : handler = XmlCallbacks ( importer , progress ) parser = sax . make_parser ( ) parser . setContentHandler ( handler ) parser . setErrorHandler ( handler ) parser . parse ( file_obj ) except : logging . excep... | Parse the data using the connected file - like object . | 99 | 12 |
9,989 | def parse_schedules ( username , password , importer , progress , utc_start = None , utc_stop = None ) : file_obj = get_file_object ( username , password , utc_start , utc_stop ) process_file_object ( file_obj , importer , progress ) | A utility function to marry the connecting and reading functions . | 70 | 11 |
9,990 | def km3h5concat ( input_files , output_file , n_events = None , * * kwargs ) : from km3pipe import Pipeline # noqa from km3pipe . io import HDF5Pump , HDF5Sink # noqa pipe = Pipeline ( ) pipe . attach ( HDF5Pump , filenames = input_files , * * kwargs ) pipe . attach ( StatusBar , every = 250 ) pipe . attach ( HDF5Sink ... | Concatenate KM3HDF5 files via pipeline . | 129 | 13 |
9,991 | def get_data ( stream , parameters , fmt ) : sds = kp . db . StreamDS ( ) if stream not in sds . streams : log . error ( "Stream '{}' not found in the database." . format ( stream ) ) return params = { } if parameters : for parameter in parameters : if '=' not in parameter : log . error ( "Invalid parameter syntax '{}'... | Retrieve data for given stream and parameters or None if not found | 189 | 13 |
9,992 | def available_streams ( ) : sds = kp . db . StreamDS ( ) print ( "Available streams: " ) print ( ', ' . join ( sorted ( sds . streams ) ) ) | Show a short list of available streams . | 44 | 8 |
9,993 | def upload_runsummary ( csv_filename , dryrun = False ) : print ( "Checking '{}' for consistency." . format ( csv_filename ) ) if not os . path . exists ( csv_filename ) : log . critical ( "{} -> file not found." . format ( csv_filename ) ) return try : df = pd . read_csv ( csv_filename , sep = '\t' ) except pd . error... | Reads the CSV file and uploads its contents to the runsummary table | 704 | 16 |
9,994 | def convert_runsummary_to_json ( df , comment = 'Uploaded via km3pipe.StreamDS' , prefix = 'TEST_' ) : data_field = [ ] comment += ", by {}" . format ( getpass . getuser ( ) ) for det_id , det_data in df . groupby ( 'det_id' ) : runs_field = [ ] data_field . append ( { "DetectorId" : det_id , "Runs" : runs_field } ) fo... | Convert a Pandas DataFrame with runsummary to JSON for DB upload | 413 | 16 |
9,995 | def calcAcceptanceRatio ( self , V , W ) : acceptanceRatio = 1.0 for comb in itertools . combinations ( V , 2 ) : #Check if comb[0] is ranked before comb[1] in V and W vIOverJ = 1 wIOverJ = 1 if V . index ( comb [ 0 ] ) > V . index ( comb [ 1 ] ) : vIOverJ = 0 if W . index ( comb [ 0 ] ) > W . index ( comb [ 1 ] ) : wI... | Given a order vector V and a proposed order vector W calculate the acceptance ratio for changing to W when using MCMC . | 166 | 24 |
9,996 | def getNextSample ( self , V ) : # Select a random alternative in V to switch with its adacent alternatives. randPos = random . randint ( 0 , len ( V ) - 2 ) W = copy . deepcopy ( V ) d = V [ randPos ] c = V [ randPos + 1 ] W [ randPos ] = c W [ randPos + 1 ] = d # Check whether we should change to the new ranking. prM... | Generate the next sample by randomly flipping two adjacent candidates . | 155 | 12 |
9,997 | def getNextSample ( self , V ) : positions = range ( 0 , len ( self . wmg ) ) randPoss = random . sample ( positions , self . shuffleSize ) flipSet = copy . deepcopy ( randPoss ) randPoss . sort ( ) W = copy . deepcopy ( V ) for j in range ( 0 , self . shuffleSize ) : W [ randPoss [ j ] ] = V [ flipSet [ j ] ] # Check ... | Generate the next sample by randomly shuffling candidates . | 173 | 11 |
9,998 | def getNextSample ( self , V ) : phi = self . phi wmg = self . wmg W = [ ] W . append ( V [ 0 ] ) for j in range ( 2 , len ( V ) + 1 ) : randomSelect = random . random ( ) threshold = 0.0 denom = 1.0 for k in range ( 1 , j ) : denom = denom + phi ** k for k in range ( 1 , j + 1 ) : numerator = phi ** ( j - k ) threshol... | We generate a new ranking based on a Mallows - based jumping distribution . The algorithm is described in Bayesian Ordinal Peer Grading by Raman and Joachims . | 198 | 35 |
9,999 | def getNextSample ( self , V ) : W , WProb = self . drawRankingPlakettLuce ( V ) VProb = self . calcProbOfVFromW ( V , W ) acceptanceRatio = self . calcAcceptanceRatio ( V , W ) prob = min ( 1.0 , acceptanceRatio * ( VProb / WProb ) ) if random . random ( ) <= prob : V = W return V | Given a ranking over the candidates generate a new ranking by assigning each candidate at position i a Plakett - Luce weight of phi^i and draw a new ranking . | 99 | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.