idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
10,000 | def calcDrawingProbs ( self ) : wmg = self . wmg phi = self . phi # We say the weight of the candidate in position i is phi^i. weights = [ ] for i in range ( 0 , len ( wmg . keys ( ) ) ) : weights . append ( phi ** i ) # Calculate the probabilty that an item at each weight is drawn. totalWeight = sum ( weights ) for i ... | Returns a vector that contains the probabily of an item being from each position . We say that every item in a order vector is drawn with weight phi^i where i is its position . | 127 | 40 |
10,001 | def drawRankingPlakettLuce ( self , rankList ) : probs = self . plakettLuceProbs numCands = len ( rankList ) newRanking = [ ] remainingCands = copy . deepcopy ( rankList ) probsCopy = copy . deepcopy ( self . plakettLuceProbs ) totalProb = sum ( probs ) # We will use prob to iteratively calculate the probabilty that we... | Given an order vector over the candidates draw candidates to generate a new order vector . | 257 | 16 |
10,002 | def calcProbOfVFromW ( self , V , W ) : weights = range ( 0 , len ( V ) ) i = 0 for alt in W : weights [ alt - 1 ] = self . phi ** i i = i + 1 # Calculate the probability that we draw V[0], V[1], and so on from W. prob = 1.0 totalWeight = sum ( weights ) for alt in V : prob = prob * weights [ alt - 1 ] / totalWeight to... | Given a order vector V and an order vector W calculate the probability that we generate V as our next sample if our current sample was W . | 119 | 28 |
10,003 | def get_hist ( rfile , histname , get_overflow = False ) : import root_numpy as rnp rfile = open_rfile ( rfile ) hist = rfile [ histname ] xlims = np . array ( list ( hist . xedges ( ) ) ) bin_values = rnp . hist2array ( hist , include_overflow = get_overflow ) rfile . close ( ) return bin_values , xlims | Read a 1D Histogram . | 102 | 7 |
10,004 | def interpol_hist2d ( h2d , oversamp_factor = 10 ) : from rootpy import ROOTError xlim = h2d . bins ( axis = 0 ) ylim = h2d . bins ( axis = 1 ) xn = h2d . nbins ( 0 ) yn = h2d . nbins ( 1 ) x = np . linspace ( xlim [ 0 ] , xlim [ 1 ] , xn * oversamp_factor ) y = np . linspace ( ylim [ 0 ] , ylim [ 1 ] , yn * oversamp_f... | Sample the interpolator of a root 2d hist . | 211 | 11 |
10,005 | def create_window ( size = None , samples = 16 , * , fullscreen = False , title = None , threaded = True ) -> Window : if size is None : width , height = 1280 , 720 else : width , height = size if samples < 0 or ( samples & ( samples - 1 ) ) != 0 : raise Exception ( 'Invalid number of samples: %d' % samples ) window = ... | Create the main window . | 120 | 5 |
10,006 | def clear ( self , red = 0.0 , green = 0.0 , blue = 0.0 , alpha = 0.0 ) -> None : self . wnd . clear ( red , green , blue , alpha ) | Clear the window . | 47 | 4 |
10,007 | def windowed ( self , size ) -> None : width , height = size self . wnd . windowed ( width , height ) | Set the window to windowed mode . | 28 | 8 |
10,008 | def product_metadata ( product , dst_folder , counter = None , writers = [ file_writer ] , geometry_check = None ) : if not counter : counter = { 'products' : 0 , 'saved_tiles' : 0 , 'skipped_tiles' : 0 , 'skipped_tiles_paths' : [ ] } s3_url = 'http://sentinel-s2-l1c.s3.amazonaws.com' product_meta_link = '{0}/{1}' . fo... | Extract metadata for a specific product | 363 | 7 |
10,009 | def daily_metadata ( year , month , day , dst_folder , writers = [ file_writer ] , geometry_check = None , num_worker_threads = 1 ) : threaded = False counter = { 'products' : 0 , 'saved_tiles' : 0 , 'skipped_tiles' : 0 , 'skipped_tiles_paths' : [ ] } if num_worker_threads > 1 : threaded = True queue = Queue ( ) # crea... | Extra metadata for all products in a specific date | 452 | 9 |
10,010 | def range_metadata ( start , end , dst_folder , num_worker_threads = 0 , writers = [ file_writer ] , geometry_check = None ) : assert isinstance ( start , date ) assert isinstance ( end , date ) delta = end - start dates = [ ] for i in range ( delta . days + 1 ) : dates . append ( start + timedelta ( days = i ) ) days ... | Extra metadata for all products in a date range | 263 | 9 |
10,011 | def get_on_tmdb ( uri , * * kwargs ) : kwargs [ 'api_key' ] = app . config [ 'TMDB_API_KEY' ] response = requests_session . get ( ( TMDB_API_URL + uri ) . encode ( 'utf8' ) , params = kwargs ) response . raise_for_status ( ) return json . loads ( response . text ) | Get a resource on TMDB . | 95 | 7 |
10,012 | def search ( ) : redis_key = 's_%s' % request . args [ 'query' ] . lower ( ) cached = redis_ro_conn . get ( redis_key ) if cached : return Response ( cached ) else : try : found = get_on_tmdb ( u'/search/movie' , query = request . args [ 'query' ] ) movies = [ ] for movie in found [ 'results' ] : cast = get_on_tmdb ( u... | Search a movie on TMDB . | 347 | 7 |
10,013 | def get_movie ( tmdb_id ) : redis_key = 'm_%s' % tmdb_id cached = redis_ro_conn . get ( redis_key ) if cached : return Response ( cached ) else : try : details = get_on_tmdb ( u'/movie/%d' % tmdb_id ) cast = get_on_tmdb ( u'/movie/%d/casts' % tmdb_id ) alternative = get_on_tmdb ( u'/movie/%d/alternative_titles' % tmdb_... | Get informations about a movie using its tmdb id . | 583 | 13 |
10,014 | def _handle_response_error ( self , response , retries , * * kwargs ) : error = self . _convert_response_to_error ( response ) if error is None : return response max_retries = self . _max_retries_for_error ( error ) if max_retries is None or retries >= max_retries : return response backoff = min ( 0.0625 * 2 ** retries... | r Provides a way for each connection wrapper to handle error responses . | 180 | 13 |
10,015 | def _convert_response_to_error ( self , response ) : content_type = response . headers . get ( "content-type" , "" ) if "application/x-protobuf" in content_type : self . logger . debug ( "Decoding protobuf response." ) data = status_pb2 . Status . FromString ( response . content ) status = self . _PB_ERROR_CODES . get ... | Subclasses may override this method in order to influence how errors are parsed from the response . | 208 | 18 |
10,016 | def parse_pattern ( format_string , env , wrapper = lambda x , y : y ) : formatter = Formatter ( ) fields = [ x [ 1 ] for x in formatter . parse ( format_string ) if x [ 1 ] is not None ] prepared_env = { } # Create a prepared environment with only used fields, all as list: for field in fields : # Search for a movie at... | Parse the format_string and return prepared data according to the env . | 244 | 15 |
10,017 | def perc ( arr , p = 95 , * * kwargs ) : offset = ( 100 - p ) / 2 return np . percentile ( arr , ( offset , 100 - offset ) , * * kwargs ) | Create symmetric percentiles with p coverage . | 47 | 9 |
10,018 | def resample_1d ( arr , n_out = None , random_state = None ) : if random_state is None : random_state = np . random . RandomState ( ) arr = np . atleast_1d ( arr ) n = len ( arr ) if n_out is None : n_out = n idx = random_state . randint ( 0 , n , size = n ) return arr [ idx ] | Resample an array with replacement . | 96 | 7 |
10,019 | def bootstrap_params ( rv_cont , data , n_iter = 5 , * * kwargs ) : fit_res = [ ] for _ in range ( n_iter ) : params = rv_cont . fit ( resample_1d ( data , * * kwargs ) ) fit_res . append ( params ) fit_res = np . array ( fit_res ) return fit_res | Bootstrap the fit params of a distribution . | 90 | 9 |
10,020 | def param_describe ( params , quant = 95 , axis = 0 ) : par = np . mean ( params , axis = axis ) lo , up = perc ( quant ) p_up = np . percentile ( params , up , axis = axis ) p_lo = np . percentile ( params , lo , axis = axis ) return par , p_lo , p_up | Get mean + quantile range from bootstrapped params . | 80 | 12 |
10,021 | def bootstrap_fit ( rv_cont , data , n_iter = 10 , quant = 95 , print_params = True , * * kwargs ) : fit_params = bootstrap_params ( rv_cont , data , n_iter ) par , lo , up = param_describe ( fit_params , quant = quant ) names = param_names ( rv_cont ) maxlen = max ( [ len ( s ) for s in names ] ) print ( "------------... | Bootstrap a distribution fit + get confidence intervals for the params . | 240 | 13 |
10,022 | def rvs ( self , * args , * * kwargs ) : # TODO REVERSE THIS FUCK PYTHON2 size = kwargs . pop ( 'size' , 1 ) random_state = kwargs . pop ( 'size' , None ) # don't ask me why it uses `self._size` return self . _kde . sample ( n_samples = size , random_state = random_state ) | Draw Random Variates . | 96 | 5 |
10,023 | def main ( ) : from docopt import docopt args = docopt ( __doc__ ) infile = args [ 'INFILE' ] outfile = args [ 'OUTFILE' ] i3extract ( infile , outfile ) | Entry point when running as script from commandline . | 52 | 10 |
10,024 | def connect ( self , server_config ) : if 'connection_string' in server_config : self . client = pymongo . MongoClient ( server_config [ 'connection_string' ] ) self . db = self . client [ server_config [ 'db' ] ] else : self . client = pymongo . MongoClient ( server_config [ 'host' ] , server_config [ 'port' ] , tz_aw... | Connect using the configuration given | 437 | 5 |
10,025 | def ptconcat ( output_file , input_files , overwrite = False ) : filt = tb . Filters ( complevel = 5 , shuffle = True , fletcher32 = True , complib = 'zlib' ) out_tabs = { } dt_file = input_files [ 0 ] log . info ( "Reading data struct '%s'..." % dt_file ) h5struc = tb . open_file ( dt_file , 'r' ) log . info ( "Openin... | Concatenate HDF5 Files | 344 | 8 |
10,026 | def load_k40_coincidences_from_hdf5 ( filename , dom_id ) : with h5py . File ( filename , 'r' ) as h5f : data = h5f [ '/k40counts/{0}' . format ( dom_id ) ] livetime = data . attrs [ 'livetime' ] data = np . array ( data ) return data , livetime | Load k40 coincidences from hdf5 file | 91 | 10 |
10,027 | def load_k40_coincidences_from_rootfile ( filename , dom_id ) : from ROOT import TFile root_file_monitor = TFile ( filename , "READ" ) dom_name = str ( dom_id ) + ".2S" histo_2d_monitor = root_file_monitor . Get ( dom_name ) data = [ ] for c in range ( 1 , histo_2d_monitor . GetNbinsX ( ) + 1 ) : combination = [ ] for ... | Load k40 coincidences from JMonitorK40 ROOT file | 323 | 13 |
10,028 | def calculate_angles ( detector , combs ) : angles = [ ] pmt_angles = detector . pmt_angles for first , second in combs : angles . append ( kp . math . angle_between ( np . array ( pmt_angles [ first ] ) , np . array ( pmt_angles [ second ] ) ) ) return np . array ( angles ) | Calculates angles between PMT combinations according to positions in detector_file | 81 | 15 |
10,029 | def fit_angular_distribution ( angles , rates , rate_errors , shape = 'pexp' ) : if shape == 'exp' : fit_function = exponential # p0 = [-0.91871169, 2.72224241, -1.19065965, 1.48054122] if shape == 'pexp' : fit_function = exponential_polinomial # p0 = [0.34921202, 2.8629577] cos_angles = np . cos ( angles ) popt , pcov... | Fits angular distribution of rates . | 161 | 7 |
10,030 | def minimize_t0s ( means , weights , combs ) : def make_quality_function ( means , weights , combs ) : def quality_function ( t0s ) : sq_sum = 0 for mean , comb , weight in zip ( means , combs , weights ) : sq_sum += ( ( mean - ( t0s [ comb [ 1 ] ] - t0s [ comb [ 0 ] ] ) ) * weight ) ** 2 return sq_sum return quality_f... | Varies t0s to minimize the deviation of the gaussian means from zero . | 194 | 17 |
10,031 | def minimize_qes ( fitted_rates , rates , weights , combs ) : def make_quality_function ( fitted_rates , rates , weights , combs ) : def quality_function ( qes ) : sq_sum = 0 for fitted_rate , comb , rate , weight in zip ( fitted_rates , combs , rates , weights ) : sq_sum += ( ( rate / qes [ comb [ 0 ] ] / qes [ comb [... | Varies QEs to minimize the deviation of the rates from the fitted_rates . | 186 | 17 |
10,032 | def correct_means ( means , opt_t0s , combs ) : corrected_means = np . array ( [ ( opt_t0s [ comb [ 1 ] ] - opt_t0s [ comb [ 0 ] ] ) - mean for mean , comb in zip ( means , combs ) ] ) return corrected_means | Applies optimal t0s to gaussians means . | 74 | 12 |
10,033 | def correct_rates ( rates , opt_qes , combs ) : corrected_rates = np . array ( [ rate / opt_qes [ comb [ 0 ] ] / opt_qes [ comb [ 1 ] ] for rate , comb in zip ( rates , combs ) ] ) return corrected_rates | Applies optimal qes to rates . | 66 | 8 |
10,034 | def calculate_rms_means ( means , corrected_means ) : rms_means = np . sqrt ( np . mean ( ( means - 0 ) ** 2 ) ) rms_corrected_means = np . sqrt ( np . mean ( ( corrected_means - 0 ) ** 2 ) ) return rms_means , rms_corrected_means | Calculates RMS of means from zero before and after correction | 86 | 13 |
10,035 | def calculate_rms_rates ( rates , fitted_rates , corrected_rates ) : rms_rates = np . sqrt ( np . mean ( ( rates - fitted_rates ) ** 2 ) ) rms_corrected_rates = np . sqrt ( np . mean ( ( corrected_rates - fitted_rates ) ** 2 ) ) return rms_rates , rms_corrected_rates | Calculates RMS of rates from fitted_rates before and after correction | 87 | 15 |
10,036 | def add_to_twofold_matrix ( times , tdcs , mat , tmax = 10 ) : h_idx = 0 # index of initial hit c_idx = 0 # index of coincident candidate hit n_hits = len ( times ) multiplicity = 0 while h_idx <= n_hits : c_idx = h_idx + 1 if ( c_idx < n_hits ) and ( times [ c_idx ] - times [ h_idx ] <= tmax ) : multiplicity = 2 c_idx... | Add counts to twofold coincidences for a given tmax . | 343 | 13 |
10,037 | def reset ( self ) : self . counts = defaultdict ( partial ( np . zeros , ( 465 , self . tmax * 2 + 1 ) ) ) self . n_timeslices = defaultdict ( int ) | Reset coincidence counter | 47 | 4 |
10,038 | def dump ( self ) : self . print ( "Dumping data to {}" . format ( self . dump_filename ) ) pickle . dump ( { 'data' : self . counts , 'livetime' : self . get_livetime ( ) } , open ( self . dump_filename , "wb" ) ) | Write coincidence counts into a Python pickle | 69 | 8 |
10,039 | def get_named_by_definition ( cls , element_list , string_def ) : try : return next ( ( st . value for st in element_list if st . definition == string_def ) ) except Exception : return None | Attempts to get an IOOS definition from a list of xml elements | 51 | 13 |
10,040 | def get_ioos_def ( self , ident , elem_type , ont ) : if elem_type == "identifier" : getter_fn = self . system . get_identifiers_by_name elif elem_type == "classifier" : getter_fn = self . system . get_classifiers_by_name else : raise ValueError ( "Unknown element type '{}'" . format ( elem_type ) ) return DescribeSens... | Gets a definition given an identifier and where to search for it | 129 | 13 |
10,041 | def get_sentence ( start = None , depth = 7 ) : if not GRAMMAR : return 'Please set a GRAMMAR file' start = start if start else GRAMMAR . start ( ) if isinstance ( start , Nonterminal ) : productions = GRAMMAR . productions ( start ) if not depth : # time to break the cycle terminals = [ p for p in productions if not i... | follow the grammatical patterns to generate a random sentence | 151 | 10 |
10,042 | def format_sentence ( sentence ) : for index , word in enumerate ( sentence ) : if word == 'a' and index + 1 < len ( sentence ) and re . match ( r'^[aeiou]' , sentence [ index + 1 ] ) and not re . match ( r'^uni' , sentence [ index + 1 ] ) : sentence [ index ] = 'an' text = ' ' . join ( sentence ) text = '%s%s' % ( tex... | fix display formatting of a sentence array | 138 | 7 |
10,043 | def new_station ( self , _id , callSign , name , affiliate , fccChannelNumber ) : if self . __v_station : # [Station: 11440, WFLX, WFLX, Fox Affiliate, 29] # [Station: 11836, WSCV, WSCV, TELEMUNDO (HBC) Affiliate, 51] # [Station: 11867, TBS, Turner Broadcasting System, Satellite, None] # [Station: 11869, WTCE, WTCE, In... | Callback run for each new station | 295 | 6 |
10,044 | def new_lineup ( self , name , location , device , _type , postalCode , _id ) : if self . __v_lineup : # [Lineup: Comcast West Palm Beach /Palm Beach Co., West Palm Beach, Digital, CableDigital, 33436, FL09567:X] print ( "[Lineup: %s, %s, %s, %s, %s, %s]" % ( name , location , device , _type , postalCode , _id ) ) | Callback run for each new lineup | 109 | 6 |
10,045 | def new_genre ( self , program , genre , relevance ) : if self . __v_genre : # [Genre: SP002709210000, Sports event, 0] # [Genre: SP002709210000, Basketball, 1] # [Genre: SP002737310000, Sports event, 0] # [Genre: SP002737310000, Basketball, 1] # [Genre: SH016761790000, News, 0] # [Genre: SH016761790000, Talk, 1] # [Ge... | Callback run for each new program genre entry | 172 | 8 |
10,046 | def qsub ( script , job_name , dryrun = False , * args , * * kwargs ) : print ( "Preparing job script..." ) job_string = gen_job ( script = script , job_name = job_name , * args , * * kwargs ) env = os . environ . copy ( ) if dryrun : print ( "This is a dry run! Here is the generated job file, which will " "not be subm... | Submit a job via qsub . | 178 | 7 |
10,047 | def gen_job ( script , job_name , log_path = 'qlogs' , group = 'km3net' , platform = 'cl7' , walltime = '00:10:00' , vmem = '8G' , fsize = '8G' , shell = None , email = None , send_mail = 'n' , job_array_start = 1 , job_array_stop = None , job_array_step = 1 , irods = False , sps = True , hpss = False , xrootd = False ... | Generate a job script . | 449 | 6 |
10,048 | def get_jpp_env ( jpp_dir ) : env = { v [ 0 ] : '' . join ( v [ 1 : ] ) for v in [ l . split ( '=' ) for l in os . popen ( "source {0}/setenv.sh {0} && env" . format ( jpp_dir ) ) . read ( ) . split ( '\n' ) if '=' in l ] } return env | Return the environment dict of a loaded Jpp env . | 97 | 11 |
10,049 | def iget ( self , irods_path , attempts = 1 , pause = 15 ) : if attempts > 1 : cmd = """ for i in {{1..{0}}}; do ret=$(iget -v {1} 2>&1) echo $ret if [[ $ret == *"ERROR"* ]]; then echo "Attempt $i failed" else break fi sleep {2}s done """ cmd = lstrip ( cmd ) cmd = cmd . format ( attempts , irods_path , pause ) self . ... | Add an iget command to retrieve a file from iRODS . | 141 | 15 |
10,050 | def _add_two_argument_command ( self , command , arg1 , arg2 ) : self . lines . append ( "{} {} {}" . format ( command , arg1 , arg2 ) ) | Helper function for two - argument commands | 44 | 7 |
10,051 | def get_devices ( self ) : devices = self . make_request ( '["{username}","{password}","info","",""]' . format ( username = self . username , password = self . password ) ) if devices != False : garage_doors = [ ] try : self . apicode = devices . find ( 'apicode' ) . text self . _device_states = { } for doorNum in rang... | List all garage door devices . | 299 | 6 |
10,052 | def get_status ( self , device_id ) : devices = self . get_devices ( ) if devices != False : for device in devices : if device [ 'door' ] == device_id : return device [ 'status' ] return False | List only MyQ garage door devices . | 52 | 8 |
10,053 | def analyze ( segments , analysis , lookup = dict ( bipa = { } , dolgo = { } ) ) : # raise a ValueError in case of empty segments/strings if not segments : raise ValueError ( 'Empty sequence.' ) # test if at least one element in `segments` has information # (helps to catch really badly formed input, such as ['\n'] if n... | Test a sequence for compatibility with CLPA and LingPy . | 542 | 12 |
10,054 | def most_energetic ( df ) : idx = df . groupby ( [ 'event_id' ] ) [ 'energy' ] . transform ( max ) == df [ 'energy' ] return df [ idx ] . reindex ( ) | Grab most energetic particle from mc_tracks dataframe . | 53 | 11 |
10,055 | def _connect ( self ) : log . debug ( "Connecting to JLigier" ) self . socket = socket . socket ( ) self . socket . connect ( ( self . host , self . port ) ) | Connect to JLigier | 46 | 6 |
10,056 | def _reconnect ( self ) : log . debug ( "Reconnecting to JLigier..." ) self . _disconnect ( ) self . _connect ( ) self . _update_subscriptions ( ) | Reconnect to JLigier and subscribe to the tags . | 47 | 14 |
10,057 | def data ( self , value ) : if not value : value = b'' if len ( value ) > self . SIZE : raise ValueError ( "The maximum tag size is {0}" . format ( self . SIZE ) ) self . _data = value while len ( self . _data ) < self . SIZE : self . _data += b'\x00' | Set the byte data and fill up the bytes to fit the size . | 80 | 14 |
10,058 | def add ( self , name , attr = None , value = None ) : if isinstance ( name , tuple ) or isinstance ( name , list ) : name , attr , value = self . __set_iter_value ( name ) if attr is None : attr = name if value is None : value = attr self . __data += ( self . get_const_string ( name = name , value = value ) , ) # set ... | Set values in constant | 125 | 4 |
10,059 | def start ( self ) : assert self . _thread is None , 'thread already started' # configure thread self . _thread = Thread ( target = self . _start_io_loop ) self . _thread . daemon = True # begin thread and block until ready self . _thread . start ( ) self . _ready . wait ( ) | Start IOLoop in daemonized thread . | 71 | 9 |
10,060 | def _start_io_loop ( self ) : def mark_as_ready ( ) : self . _ready . set ( ) if not self . _io_loop : self . _io_loop = ioloop . IOLoop ( ) self . _io_loop . add_callback ( mark_as_ready ) self . _io_loop . start ( ) | Start IOLoop then set ready threading . Event . | 80 | 12 |
10,061 | def is_ready ( self ) : if not self . _thread : return False if not self . _ready . is_set ( ) : return False return True | Is thread & ioloop ready . | 34 | 8 |
10,062 | def submit ( self , fn , * args , * * kwargs ) : if not self . is_ready ( ) : raise ThreadNotStartedError ( "The thread has not been started yet, " "make sure you call start() first" ) future = Future ( ) def execute ( ) : """Executes fn on the IOLoop.""" try : result = gen . maybe_future ( fn ( * args , * * kwargs ) )... | Submit Tornado Coroutine to IOLoop in daemonized thread . | 409 | 13 |
10,063 | def peak_memory_usage ( ) : if sys . platform . startswith ( 'win' ) : p = psutil . Process ( ) return p . memory_info ( ) . peak_wset / 1024 / 1024 mem = resource . getrusage ( resource . RUSAGE_SELF ) . ru_maxrss factor_mb = 1 / 1024 if sys . platform == 'darwin' : factor_mb = 1 / ( 1024 * 1024 ) return mem * factor_... | Return peak memory usage in MB | 104 | 6 |
10,064 | def getPreferenceCounts ( self ) : preferenceCounts = [ ] for preference in self . preferences : preferenceCounts . append ( preference . count ) return preferenceCounts | Returns a list of the number of times each preference is given . | 37 | 13 |
10,065 | def getRankMaps ( self ) : rankMaps = [ ] for preference in self . preferences : rankMaps . append ( preference . getRankMap ( ) ) return rankMaps | Returns a list of dictionaries one for each preference that associates the integer representation of each candidate with its position in the ranking starting from 1 and returns a list of the number of times each preference is given . | 36 | 41 |
10,066 | def getReverseRankMaps ( self ) : reverseRankMaps = [ ] for preference in self . preferences : reverseRankMaps . append ( preference . getReverseRankMap ( ) ) return reverseRankMaps | Returns a list of dictionaries one for each preference that associates each position in the ranking with a list of integer representations of the candidates ranked at that position and returns a list of the number of times each preference is given . | 45 | 44 |
10,067 | def exportPreflibFile ( self , fileName ) : elecType = self . getElecType ( ) if elecType != "soc" and elecType != "toc" and elecType != "soi" and elecType != "toi" : print ( "ERROR: printing current type to preflib format is not supported" ) exit ( ) # Generate a list of reverse rankMaps, one for each vote. This will ... | Exports a preflib format file that contains all the information of the current Profile . | 542 | 18 |
10,068 | def importPreflibFile ( self , fileName ) : # Use the functionality found in io to read the file. elecFileObj = open ( fileName , 'r' ) self . candMap , rankMaps , wmgMapsCounts , self . numVoters = prefpy_io . read_election_file ( elecFileObj ) elecFileObj . close ( ) self . numCands = len ( self . candMap . keys ( ) ... | Imports a preflib format file that contains all the information of a Profile . This function will completely override all members of the current Profile object . Currently we assume that in an election where incomplete ordering are allowed if a voter ranks only one candidate then the voter did not prefer any candidates... | 192 | 88 |
10,069 | def exportJsonFile ( self , fileName ) : # Because our Profile class is not directly JSON serializable, we exporrt the underlying # dictionary. data = dict ( ) for key in self . __dict__ . keys ( ) : if key != "preferences" : data [ key ] = self . __dict__ [ key ] # The Preference class is also not directly JSON serial... | Exports a json file that contains all the information of the current Profile . | 196 | 15 |
10,070 | def importJsonFile ( self , fileName ) : infile = open ( fileName ) data = json . load ( infile ) infile . close ( ) self . numCands = int ( data [ "numCands" ] ) self . numVoters = int ( data [ "numVoters" ] ) # Because the json.load function imports everything as unicode strings, we will go through # the candMap dict... | Imports a json file that contains all the information of a Profile . This function will completely override all members of the current Profile object . | 382 | 27 |
10,071 | def main ( ) : # test example below taken from GMMRA by Azari, Chen, Parkes, & Xia cand_set = [ 0 , 1 , 2 ] votes = [ [ 0 , 1 , 2 ] , [ 1 , 2 , 0 ] ] mmagg = MMPLAggregator ( cand_set ) gamma = mmagg . aggregate ( votes , epsilon = 1e-7 , max_iters = 20 ) print ( mmagg . alts_to_ranks , mmagg . ranks_to_alts ) assert (... | Driver function for the computation of the MM algorithm | 148 | 9 |
10,072 | def get_login_url ( self , state = None ) : payload = { 'response_type' : 'code' , 'client_id' : self . _client_id , 'redirect_uri' : self . _redirect_uri , } if state is not None : payload [ 'state' ] = state return "%s?%s" % ( settings . API_AUTHORIZATION_URL , urllib . urlencode ( payload ) ) | Generates and returns URL for redirecting to Login Page of RunKeeper which is the Authorization Endpoint of Health Graph API . | 102 | 26 |
10,073 | def get_login_button_url ( self , button_color = None , caption_color = None , button_size = None ) : if not button_color in settings . LOGIN_BUTTON_COLORS : button_color = settings . LOGIN_BUTTON_COLORS [ 0 ] if not caption_color in settings . LOGIN_BUTTON_CAPTION_COLORS : caption_color = settings . LOGIN_BUTTON_CAPTI... | Return URL for image used for RunKeeper Login button . | 192 | 12 |
10,074 | def get_access_token ( self , code ) : payload = { 'grant_type' : 'authorization_code' , 'code' : code , 'client_id' : self . _client_id , 'client_secret' : self . _client_secret , 'redirect_uri' : self . _redirect_uri , } req = requests . post ( settings . API_ACCESS_TOKEN_URL , data = payload ) data = req . json ( ) ... | Returns Access Token retrieved from the Health Graph API Token Endpoint following the login to RunKeeper . to RunKeeper . | 117 | 25 |
10,075 | def revoke_access_token ( self , access_token ) : payload = { 'access_token' : access_token , } req = requests . post ( settings . API_DEAUTHORIZATION_URL , data = payload ) | Revokes the Access Token by accessing the De - authorization Endpoint of Health Graph API . | 51 | 18 |
10,076 | def split ( self , points ) : for p in points : for i in range ( len ( self . intervals ) ) : if ( self . intervals [ i ] . start < p ) and ( self . intervals [ i ] . end > p ) : self . intervals = ( self . intervals [ : i ] + [ TimeInterval ( self . intervals [ i ] . start , p ) , TimeInterval ( p , self . intervals [... | Splits the list of time intervals in the specified points | 113 | 11 |
10,077 | def create ( cls , data , * * kwargs ) : with db . session . begin_nested ( ) : model = cls . dbmodel ( * * kwargs ) model . data = data obj = cls ( model ) db . session . add ( obj . model ) return obj | Create a new Workflow Object with given content . | 65 | 10 |
10,078 | def get ( cls , id_ ) : with db . session . no_autoflush : query = cls . dbmodel . query . filter_by ( id = id_ ) try : model = query . one ( ) except NoResultFound : raise WorkflowsMissingObject ( "No object for for id {0}" . format ( id_ ) ) return cls ( model ) | Return a workflow object from id . | 83 | 7 |
10,079 | def query ( cls , * criteria , * * filters ) : query = cls . dbmodel . query . filter ( * criteria ) . filter_by ( * * filters ) return [ cls ( obj ) for obj in query . all ( ) ] | Wrap sqlalchemy query methods . | 54 | 8 |
10,080 | def delete ( self , force = False ) : if self . model is None : raise WorkflowsMissingModel ( ) with db . session . begin_nested ( ) : db . session . delete ( self . model ) return self | Delete a workflow object . | 48 | 5 |
10,081 | def set_action ( self , action , message ) : self . extra_data [ "_action" ] = action self . extra_data [ "_message" ] = message | Set the action to be taken for this object . | 36 | 10 |
10,082 | def start_workflow ( self , workflow_name , delayed = False , * * kwargs ) : from . tasks import start if delayed : self . save ( ) db . session . commit ( ) return start . delay ( workflow_name , object_id = self . id , * * kwargs ) else : return start ( workflow_name , data = [ self ] , * * kwargs ) | Run the workflow specified on the object . | 87 | 8 |
10,083 | def continue_workflow ( self , start_point = "continue_next" , delayed = False , * * kwargs ) : from . tasks import resume self . save ( ) if not self . id_workflow : raise WorkflowAPIError ( "No workflow associated with object: %r" % ( repr ( self ) , ) ) if delayed : db . session . commit ( ) return resume . delay ( ... | Continue the workflow for this object . | 121 | 7 |
10,084 | def get_current_task_info ( self ) : name = self . model . workflow . name if not name : return current_task = workflows [ name ] . workflow for step in self . callback_pos : current_task = current_task [ step ] if callable ( current_task ) : return get_func_info ( current_task ) | Return dictionary of current task function info for this object . | 76 | 11 |
10,085 | def canned_handlers ( self , environ , start_response , code = '200' , headers = [ ] ) : headerbase = [ ( 'Content-Type' , 'text/plain' ) ] if headers : hObj = Headers ( headerbase ) for header in headers : hObj [ header [ 0 ] ] = '; ' . join ( header [ 1 : ] ) start_response ( self . canned_collection [ code ] , heade... | We convert an error code into certain action over start_response and return a WSGI - compliant payload . | 103 | 21 |
10,086 | def info_shell_scope ( self ) : Console . ok ( "{:>20} = {:}" . format ( "ECHO" , self . echo ) ) Console . ok ( "{:>20} = {:}" . format ( "DEBUG" , self . debug ) ) Console . ok ( "{:>20} = {:}" . format ( "LOGLEVEL" , self . loglevel ) ) Console . ok ( "{:>20} = {:}" . format ( "SCOPE" , self . active_scope ) ) Conso... | prints some information about the shell scope | 244 | 7 |
10,087 | def activate_shell_scope ( self ) : self . variables = { } self . prompt = 'cm> ' self . active_scope = "" self . scopes = [ ] self . scopeless = [ 'load' , 'info' , 'var' , 'use' , 'quit' , 'q' , 'help' ] | activates the shell scope | 73 | 5 |
10,088 | def _build_stack ( self ) -> List [ Callable ] : stack = [ ] for m in self . manager . middlewares : try : stack . append ( getattr ( m ( self ) , self . name ) ) except AttributeError : pass return stack | Generates the stack of functions to call . It looks at the ordered list of all middlewares and only keeps those which have the method we re trying to call . | 57 | 34 |
10,089 | def instance ( cls ) -> 'MiddlewareManager' : if cls . _instance is None : cls . _instance = cls ( ) cls . _instance . init ( ) return cls . _instance | Creates initializes and returns a unique MiddlewareManager instance . | 47 | 13 |
10,090 | def health_check ( cls ) : try : assert isinstance ( settings . MIDDLEWARES , list ) except AssertionError : yield HealthCheckFail ( '00005' , 'The "MIDDLEWARES" configuration key should be assigned ' 'to a list' , ) return for m in settings . MIDDLEWARES : try : c = import_class ( m ) except ( TypeError , ValueError ,... | Checks that the configuration makes sense . | 169 | 8 |
10,091 | def get ( self , name : Text , final : C ) -> C : # noinspection PyTypeChecker return Caller ( self , name , final ) | Get the function to call which will run all middlewares . | 33 | 13 |
10,092 | def load_from_args ( args ) : if not args . locus : return None loci_iterator = ( Locus . parse ( locus ) for locus in args . locus ) # if args.neighbor_offsets: # loci_iterator = expand_with_neighbors( # loci_iterator, args.neighbor_offsets) return Loci ( loci_iterator ) | Return a Loci object giving the loci specified on the command line . | 91 | 15 |
10,093 | def format_date ( cls , timestamp ) : if not timestamp : raise DateTimeFormatterException ( 'timestamp must a valid string {}' . format ( timestamp ) ) return timestamp . strftime ( cls . DATE_FORMAT ) | Creates a string representing the date information provided by the given timestamp object . | 52 | 15 |
10,094 | def format_datetime ( cls , timestamp ) : if not timestamp : raise DateTimeFormatterException ( 'timestamp must a valid string {}' . format ( timestamp ) ) return timestamp . strftime ( cls . DATETIME_FORMAT ) | Creates a string representing the date and time information provided by the given timestamp object . | 55 | 17 |
10,095 | def extract_date ( cls , date_str ) : if not date_str : raise DateTimeFormatterException ( 'date_str must a valid string {}.' . format ( date_str ) ) try : return cls . _extract_timestamp ( date_str , cls . DATE_FORMAT ) except ( TypeError , ValueError ) : raise DateTimeFormatterException ( 'Invalid date string {}.' . ... | Tries to extract a datetime object from the given string expecting date information only . | 100 | 17 |
10,096 | def extract_datetime ( cls , datetime_str ) : if not datetime_str : raise DateTimeFormatterException ( 'datetime_str must a valid string' ) try : return cls . _extract_timestamp ( datetime_str , cls . DATETIME_FORMAT ) except ( TypeError , ValueError ) : raise DateTimeFormatterException ( 'Invalid datetime string {}.' ... | Tries to extract a datetime object from the given string including time information . | 101 | 16 |
10,097 | def extract_datetime_hour ( cls , datetime_str ) : if not datetime_str : raise DateTimeFormatterException ( 'datetime_str must a valid string' ) try : return cls . _extract_timestamp ( datetime_str , cls . DATETIME_HOUR_FORMAT ) except ( TypeError , ValueError ) : raise DateTimeFormatterException ( 'Invalid datetime st... | Tries to extract a datetime object from the given string including only hours . | 106 | 16 |
10,098 | def extract ( cls , timestamp_str ) : if not timestamp_str : raise DateTimeFormatterException ( 'timestamp_str must a valid string {}' . format ( timestamp_str ) ) if isinstance ( timestamp_str , ( date , datetime ) ) : return timestamp_str try : return cls . extract_datetime ( timestamp_str ) except DateTimeFormatterE... | Tries to extract a datetime object from the given string . First the datetime format is tried if it fails the date format is used for extraction . | 143 | 31 |
10,099 | def restart ( uuid , * * kwargs ) : from . worker_engine import restart_worker return text_type ( restart_worker ( uuid , * * kwargs ) . uuid ) | Restart the workflow from a given workflow engine UUID . | 44 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.