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 in range ( 0 , len ( wmg . keys ( ) ) ) : weights [ i ] = weights [ i ] / totalWeight return weights | 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 draw the order vector # that we end up drawing. prob = 1.0 while ( len ( newRanking ) < numCands ) : # We generate a random number from 0 to 1, and use it to select a candidate. rand = random . random ( ) threshold = 0.0 for i in range ( 0 , len ( probsCopy ) ) : threshold = threshold + probsCopy [ i ] / totalProb if rand <= threshold : prob = prob * probsCopy [ i ] / totalProb newRanking . append ( remainingCands [ i ] ) remainingCands . pop ( i ) totalProb = totalProb - probsCopy [ i ] probsCopy . pop ( i ) break return newRanking , prob | 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 totalWeight = totalWeight - weights [ alt - 1 ] return prob | 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_factor ) mat = np . zeros ( ( xn , yn ) ) for xi in range ( xn ) : for yi in range ( yn ) : try : mat [ xi , yi ] = h2d . interpolate ( x [ xi ] , y [ yi ] ) except ROOTError : continue return mat , x , y | 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 = Window . __new__ ( Window ) window . wnd = glwnd . create_window ( width , height , samples , fullscreen , title , threaded ) return 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}' . format ( s3_url , product [ 'metadata' ] ) product_info = requests . get ( product_meta_link , stream = True ) product_metadata = metadata_to_dict ( product_info . raw ) product_metadata [ 'product_meta_link' ] = product_meta_link counter [ 'products' ] += 1 for tile in product [ 'tiles' ] : tile_info = requests . get ( '{0}/{1}' . format ( s3_url , tile ) ) try : metadata = tile_metadata ( tile_info . json ( ) , copy ( product_metadata ) , geometry_check ) for w in writers : w ( dst_folder , metadata ) logger . info ( 'Saving to disk: %s' % metadata [ 'tile_name' ] ) counter [ 'saved_tiles' ] += 1 except JSONDecodeError : logger . warning ( 'Tile: %s was not found and skipped' % tile ) counter [ 'skipped_tiles' ] += 1 counter [ 'skipped_tiles_paths' ] . append ( tile ) return counter | 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 ( ) # create folders year_dir = os . path . join ( dst_folder , str ( year ) ) month_dir = os . path . join ( year_dir , str ( month ) ) day_dir = os . path . join ( month_dir , str ( day ) ) product_list = get_products_metadata_path ( year , month , day ) logger . info ( 'There are %s products in %s-%s-%s' % ( len ( list ( iterkeys ( product_list ) ) ) , year , month , day ) ) for name , product in iteritems ( product_list ) : product_dir = os . path . join ( day_dir , name ) if threaded : queue . put ( [ product , product_dir , counter , writers , geometry_check ] ) else : counter = product_metadata ( product , product_dir , counter , writers , geometry_check ) if threaded : def worker ( ) : while not queue . empty ( ) : args = queue . get ( ) try : product_metadata ( * args ) except Exception : exc = sys . exc_info ( ) logger . error ( '%s tile skipped due to error: %s' % ( threading . current_thread ( ) . name , exc [ 1 ] . __str__ ( ) ) ) args [ 2 ] [ 'skipped_tiles' ] += 1 queue . task_done ( ) threads = [ ] for i in range ( num_worker_threads ) : t = threading . Thread ( target = worker ) t . start ( ) threads . append ( t ) queue . join ( ) return counter | 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 = len ( dates ) total_counter = { 'days' : days , 'products' : 0 , 'saved_tiles' : 0 , 'skipped_tiles' : 0 , 'skipped_tiles_paths' : [ ] } def update_counter ( counter ) : for key in iterkeys ( total_counter ) : if key in counter : total_counter [ key ] += counter [ key ] for d in dates : logger . info ( 'Getting metadata of {0}-{1}-{2}' . format ( d . year , d . month , d . day ) ) update_counter ( daily_metadata ( d . year , d . month , d . day , dst_folder , writers , geometry_check , num_worker_threads ) ) return total_counter | 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'/movie/%s/casts' % movie [ 'id' ] ) year = datetime . strptime ( movie [ 'release_date' ] , '%Y-%m-%d' ) . year if movie [ 'release_date' ] else None movies . append ( { 'title' : movie [ 'original_title' ] , 'directors' : [ x [ 'name' ] for x in cast [ 'crew' ] if x [ 'department' ] == 'Directing' and x [ 'job' ] == 'Director' ] , 'year' : year , '_tmdb_id' : movie [ 'id' ] } ) except requests . HTTPError as err : return Response ( 'TMDB API error: %s' % str ( err ) , status = err . response . status_code ) json_response = json . dumps ( { 'movies' : movies } ) redis_conn . setex ( redis_key , app . config [ 'CACHE_TTL' ] , json_response ) return Response ( json_response ) | 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_id ) except requests . HTTPError as err : return Response ( 'TMDB API error: %s' % str ( err ) , status = err . response . status_code ) movie = { 'title' : details [ 'original_title' ] , 'score' : details [ 'popularity' ] , 'directors' : [ x [ 'name' ] for x in cast [ 'crew' ] if x [ 'department' ] == 'Directing' and x [ 'job' ] == 'Director' ] , 'writers' : [ x [ 'name' ] for x in cast [ 'crew' ] if x [ 'department' ] == 'Writing' ] , 'cast' : [ x [ 'name' ] for x in cast [ 'cast' ] ] , 'genres' : [ x [ 'name' ] for x in details [ 'genres' ] ] , 'countries' : [ x [ 'name' ] for x in details [ 'production_countries' ] ] , 'tmdb_votes' : int ( round ( details . get ( 'vote_average' , 0 ) * 0.5 ) ) , '_tmdb_id' : tmdb_id } if details . get ( 'release_date' ) : movie [ 'year' ] = datetime . strptime ( details [ 'release_date' ] , '%Y-%m-%d' ) . year if details . get ( 'belongs_to_collection' ) : movie [ 'collection' ] = details [ 'belongs_to_collection' ] [ 'name' ] for alt in alternative [ 'titles' ] : movie [ 'title_%s' % alt [ 'iso_3166_1' ] . lower ( ) ] = alt [ 'title' ] json_response = json . dumps ( { 'movie' : movie } ) redis_conn . setex ( redis_key , app . config [ 'CACHE_TTL' ] , json_response ) return Response ( json_response ) | 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 , 1.0 ) self . logger . warning ( "Sleeping for %r before retrying failed request..." , backoff ) time . sleep ( backoff ) retries += 1 self . logger . warning ( "Retrying failed request. Attempt %d/%d." , retries , max_retries ) return self . request ( retries = retries , * * kwargs ) | 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 ( data . code ) error = { "status" : status } return error elif "application/json" in content_type : self . logger . debug ( "Decoding json response." ) data = response . json ( ) error = data . get ( "error" ) if not error or not isinstance ( error , dict ) : self . logger . warning ( "Unexpected error response: %r" , data ) return None return error self . logger . warning ( "Unexpected response: %r" , response . text ) return None | 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 attribute for each alternative field separated # by a pipe sign: for field_alt in ( x . strip ( ) for x in field . split ( '|' ) ) : # Handle default values (enclosed by quotes): if field_alt [ 0 ] in '\'"' and field_alt [ - 1 ] in '\'"' : field_values = field_alt [ 1 : - 1 ] else : field_values = env . get ( field_alt ) if field_values is not None : break else : field_values = [ ] if not isinstance ( field_values , list ) : field_values = [ field_values ] prepared_env [ field ] = wrapper ( field_alt , field_values ) return prepared_env | 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 ( "--------------" ) print ( rv_cont . name ) print ( "--------------" ) for i , name in enumerate ( names ) : print ( "{nam:>{fill}}: {mean:+.3f} ∈ " "[{lo:+.3f}, {up:+.3f}] ({q}%)" . format ( nam = name , fill = maxlen , mean = par [ i ] , lo = lo [ i ] , up = up [ i ] , q = quant ) ) out = { 'mean' : par , 'lower limit' : lo , 'upper limit' : up , } return out | 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_aware = self . get_config_value ( 'tz_aware' , True ) ) self . db = self . client [ server_config [ 'db' ] ] if ( 'authentication_database' in server_config and server_config [ 'authentication_database' ] ) : self . db . authenticate ( server_config [ 'username' ] , server_config [ 'password' ] , source = server_config [ 'authentication_database' ] ) else : if 'username' in server_config : if 'password' in server_config : self . db . authenticate ( server_config [ 'username' ] , server_config [ 'password' ] ) else : self . db . authenticate ( server_config [ 'username' ] ) # Mongo Engine connection d = dict ( ( k , v ) for k , v in server_config . items ( ) if k not in [ 'modalities' , 'summaries' ] ) if 'authentication_database' in d : d [ 'authentication_source' ] = d [ 'authentication_database' ] del d [ 'authentication_database' ] self . session = connect ( alias = "hyperstream" , * * d ) # TODO: This sets the default connection of mongoengine, but seems to be a bit of a hack if "default" not in connection . _connections : connection . _connections [ "default" ] = connection . _connections [ "hyperstream" ] connection . _connection_settings [ "default" ] = connection . _connection_settings [ "hyperstream" ] | 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 ( "Opening output file '%s'..." % output_file ) if overwrite : outmode = 'w' else : outmode = 'a' h5out = tb . open_file ( output_file , outmode ) for node in h5struc . walk_nodes ( '/' , classname = 'Table' ) : path = node . _v_pathname log . debug ( path ) dtype = node . dtype p , n = os . path . split ( path ) out_tabs [ path ] = h5out . create_table ( p , n , description = dtype , filters = filt , createparents = True ) h5struc . close ( ) for fname in input_files : log . info ( 'Reading %s...' % fname ) h5 = tb . open_file ( fname ) for path , out in out_tabs . items ( ) : tab = h5 . get_node ( path ) out . append ( tab [ : ] ) h5 . close ( ) h5out . close ( ) | 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 b in range ( 1 , histo_2d_monitor . GetNbinsY ( ) + 1 ) : combination . append ( histo_2d_monitor . GetBinContent ( c , b ) ) data . append ( combination ) weights = { } weights_histo = root_file_monitor . Get ( 'weights_hist' ) try : for i in range ( 1 , weights_histo . GetNbinsX ( ) + 1 ) : # we have to read all the entries, unfortunately weight = weights_histo . GetBinContent ( i ) label = weights_histo . GetXaxis ( ) . GetBinLabel ( i ) weights [ label [ 3 : ] ] = weight dom_weight = weights [ str ( dom_id ) ] except AttributeError : log . info ( "Weights histogram broken or not found, setting weight to 1." ) dom_weight = 1. return np . array ( data ) , dom_weight | 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 = optimize . curve_fit ( fit_function , cos_angles , rates ) fitted_rates = fit_function ( cos_angles , * popt ) return fitted_rates , 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_function qfunc = make_quality_function ( means , weights , combs ) # t0s = np.zeros(31) t0s = np . random . rand ( 31 ) bounds = [ ( 0 , 0 ) ] + [ ( - 10. , 10. ) ] * 30 opt_t0s = optimize . minimize ( qfunc , t0s , bounds = bounds ) return opt_t0s | 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 [ 1 ] ] - fitted_rate ) * weight ) ** 2 return sq_sum return quality_function qfunc = make_quality_function ( fitted_rates , rates , weights , combs ) qes = np . ones ( 31 ) bounds = [ ( 0.1 , 2. ) ] * 31 opt_qes = optimize . minimize ( qfunc , qes , bounds = bounds ) return opt_qes | 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 += 1 while ( c_idx < n_hits ) and ( times [ c_idx ] - times [ h_idx ] <= tmax ) : c_idx += 1 multiplicity += 1 if multiplicity != 2 : h_idx = c_idx continue c_idx -= 1 h_tdc = tdcs [ h_idx ] c_tdc = tdcs [ c_idx ] h_time = times [ h_idx ] c_time = times [ c_idx ] if h_tdc != c_tdc : dt = int ( c_time - h_time ) if h_tdc > c_tdc : mat [ get_comb_index ( c_tdc , h_tdc ) , - dt + tmax ] += 1 else : mat [ get_comb_index ( h_tdc , c_tdc ) , dt + tmax ] += 1 h_idx = 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 DescribeSensor . get_named_by_definition ( getter_fn ( ident ) , urljoin ( ont , ident ) ) | 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 isinstance ( start , Nonterminal ) ] if len ( terminals ) : production = terminals production = random . choice ( productions ) sentence = [ ] for piece in production . rhs ( ) : sentence += get_sentence ( start = piece , depth = depth - 1 ) return sentence else : return [ start ] | 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' % ( text [ 0 ] . upper ( ) , text [ 1 : ] ) text = text . replace ( ' ,' , ',' ) return '%s.' % text | 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, Independent, 21] # [Station: 11924, WTVX, WTVX, CW Affiliate, 34] # [Station: 11991, WXEL, WXEL, PBS Affiliate, 42] # [Station: 12131, TOON, Cartoon Network, Satellite, None] # [Station: 12444, ESPN2, ESPN2, Sports Satellite, None] # [Station: 12471, WFGC, WFGC, Independent, 61] # [Station: 16046, TVNI, TV Chile Internacional, Latin American Satellite, None] # [Station: 22233, GOAC020, Government Access - GOAC020, Cablecast, None] print ( "[Station: %s, %s, %s, %s, %s]" % ( _id , callSign , name , affiliate , fccChannelNumber ) ) | 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] # [Genre: SH016761790000, Interview, 2] # [Genre: SH016761790000, Politics, 3] print ( "[Genre: %s, %s, %s]" % ( program , genre , relevance ) ) | 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 submitted:" ) print ( job_string ) else : print ( "Calling qsub with the generated job script." ) p = subprocess . Popen ( 'qsub -V' , stdin = subprocess . PIPE , env = env , shell = True ) p . communicate ( input = bytes ( job_string . encode ( 'ascii' ) ) ) | 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 , dcache = False , oracle = False , split_array_logs = False ) : if shell is None : shell = os . environ [ 'SHELL' ] if email is None : email = os . environ [ 'USER' ] + '@km3net.de' if isinstance ( script , Script ) : script = str ( script ) log_path = os . path . join ( os . getcwd ( ) , log_path ) if job_array_stop is not None : job_array_option = "#$ -t {}-{}:{}" . format ( job_array_start , job_array_stop , job_array_step ) else : job_array_option = "#" if split_array_logs : task_name = '_$TASK_ID' else : task_name = '' job_string = JOB_TEMPLATE . format ( script = script , email = email , send_mail = send_mail , log_path = log_path , job_name = job_name , group = group , walltime = walltime , vmem = vmem , fsize = fsize , irods = irods , sps = sps , hpss = hpss , xrootd = xrootd , dcache = dcache , oracle = oracle , shell = shell , platform = platform , job_array_option = job_array_option , task_name = task_name ) return job_string | 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 ( cmd ) else : self . add ( 'iget -v "{}"' . format ( irods_path ) ) | 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 range ( 1 , 4 ) : door = devices . find ( 'door' + str ( doorNum ) ) doorName = door . find ( 'name' ) . text if doorName : dev = { 'door' : doorNum , 'name' : doorName } for id in [ 'mode' , 'sensor' , 'status' , 'sensorid' , 'temperature' , 'voltage' , 'camera' , 'events' , 'permission' ] : item = door . find ( id ) if item is not None : dev [ id ] = item . text garage_state = door . find ( 'status' ) . text dev [ 'status' ] = self . DOOR_STATE [ garage_state ] self . _device_states [ doorNum ] = self . DOOR_STATE [ garage_state ] garage_doors . append ( dev ) return garage_doors except TypeError as ex : print ( ex ) return False else : return False | 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 not [ segment for segment in segments if segment . strip ( ) ] : raise ValueError ( 'No information in the sequence.' ) # build the phonologic and sound class analyses try : bipa_analysis , sc_analysis = [ ] , [ ] for s in segments : a = lookup [ 'bipa' ] . get ( s ) if a is None : a = lookup [ 'bipa' ] . setdefault ( s , BIPA [ s ] ) bipa_analysis . append ( a ) sc = lookup [ 'dolgo' ] . get ( s ) if sc is None : sc = lookup [ 'dolgo' ] . setdefault ( s , BIPA . translate ( s , DOLGO ) ) sc_analysis . append ( sc ) except : # noqa print ( segments ) raise # compute general errors; this loop must take place outside the # following one because the code for computing single errors (either # in `bipa_analysis` or in `soundclass_analysis`) is unnecessary # complicated for sound_bipa , sound_class in zip ( bipa_analysis , sc_analysis ) : if isinstance ( sound_bipa , pyclts . models . UnknownSound ) or sound_class == '?' : analysis . general_errors += 1 # iterate over the segments and analyses, updating counts of occurrences # and specific errors for segment , sound_bipa , sound_class in zip ( segments , bipa_analysis , sc_analysis ) : # update the segment count analysis . segments . update ( [ segment ] ) # add an error if we got an unknown sound, otherwise just append # the `replacements` dictionary if isinstance ( sound_bipa , pyclts . models . UnknownSound ) : analysis . bipa_errors . add ( segment ) else : analysis . replacements [ sound_bipa . source ] . add ( sound_bipa . __unicode__ ( ) ) # update sound class errors, if any if sound_class == '?' : analysis . sclass_errors . add ( segment ) return segments , bipa_analysis , sc_analysis , analysis | 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 attribute as slugfiy self . __dict__ [ s_attr ( attr ) ] = self . __data [ - 1 ] | 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 ) ) except Exception : # The function we ran didn't return a future and instead raised # an exception. Let's pretend that it returned this dummy # future with our stack trace. f = gen . Future ( ) f . set_exc_info ( sys . exc_info ( ) ) on_done ( f ) else : result . add_done_callback ( on_done ) def on_done ( f ) : """Sets tornado.Future results to the concurrent.Future.""" if not f . exception ( ) : future . set_result ( f . result ( ) ) return # if f is a tornado future, then it has exc_info() if hasattr ( f , 'exc_info' ) : exception , traceback = f . exc_info ( ) [ 1 : ] # else it's a concurrent.future else : # python2's concurrent.future has exception_info() if hasattr ( f , 'exception_info' ) : exception , traceback = f . exception_info ( ) # python3's concurrent.future just has exception() else : exception = f . exception ( ) traceback = None # python2 needs exc_info set explicitly if _FUTURE_HAS_EXC_INFO : future . set_exception_info ( exception , traceback ) return # python3 just needs the exception, exc_info works fine future . set_exception ( exception ) self . _io_loop . add_callback ( execute ) return future | 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_mb | 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 allow us to easiliy # identify ties. reverseRankMaps = self . getReverseRankMaps ( ) outfileObj = open ( fileName , 'w' ) # Print the number of candidates and the integer representation and name of each candidate. outfileObj . write ( str ( self . numCands ) ) for candInt , cand in self . candMap . items ( ) : outfileObj . write ( "\n" + str ( candInt ) + "," + cand ) # Sum up the number of preferences that are represented. preferenceCount = 0 for preference in self . preferences : preferenceCount += preference . count # Print the number of voters, the sum of vote count, and the number of unique orders. outfileObj . write ( "\n" + str ( self . numVoters ) + "," + str ( preferenceCount ) + "," + str ( len ( self . preferences ) ) ) for i in range ( 0 , len ( reverseRankMaps ) ) : # First, print the number of times the preference appears. outfileObj . write ( "\n" + str ( self . preferences [ i ] . count ) ) reverseRankMap = reverseRankMaps [ i ] # We sort the positions in increasing order and print the candidates at each position # in order. sortedKeys = sorted ( reverseRankMap . keys ( ) ) for key in sortedKeys : cands = reverseRankMap [ key ] # If only one candidate is in a particular position, we assume there is no tie. if len ( cands ) == 1 : outfileObj . write ( "," + str ( cands [ 0 ] ) ) # If more than one candidate is in a particular position, they are tied. We print # brackets around the candidates. elif len ( cands ) > 1 : outfileObj . write ( ",{" + str ( cands [ 0 ] ) ) for j in range ( 1 , len ( cands ) ) : outfileObj . write ( "," + str ( cands [ j ] ) ) outfileObj . write ( "}" ) outfileObj . close ( ) | 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 ( ) ) # Go through the rankMaps and generate a wmgMap for each vote. Use the wmgMap to create a # Preference object. self . preferences = [ ] for i in range ( 0 , len ( rankMaps ) ) : wmgMap = self . genWmgMapFromRankMap ( rankMaps [ i ] ) self . preferences . append ( Preference ( wmgMap , wmgMapsCounts [ i ] ) ) | 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 over another . This may lead to some discrepancies when importing and exporting a . toi preflib file or a . soi preflib file . | 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 serializable, so we export the underlying # dictionary for each Preference object. preferenceDicts = [ ] for preference in self . preferences : preferenceDict = dict ( ) for key in preference . __dict__ . keys ( ) : preferenceDict [ key ] = preference . __dict__ [ key ] preferenceDicts . append ( preferenceDict ) data [ "preferences" ] = preferenceDicts outfile = open ( fileName , 'w' ) json . dump ( data , outfile ) outfile . close ( ) | 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 dictionary and convert all the keys to integers and convert all the values to # ascii strings. candMap = dict ( ) for key in data [ "candMap" ] . keys ( ) : candMap [ int ( key ) ] = data [ "candMap" ] [ key ] . encode ( "ascii" ) self . candMap = candMap # The Preference class is also not directly JSON serializable, so we exported the # underlying dictionary for each Preference object. When we import, we will create a # Preference object from these dictionaries. self . preferences = [ ] for preferenceMap in data [ "preferences" ] : count = int ( preferenceMap [ "count" ] ) # Because json.load imports all the items in the wmgMap as unicode strings, we need to # convert all the keys and values into integers. preferenceWmgMap = preferenceMap [ "wmgMap" ] wmgMap = dict ( ) for key in preferenceWmgMap . keys ( ) : wmgMap [ int ( key ) ] = dict ( ) for key2 in preferenceWmgMap [ key ] . keys ( ) : wmgMap [ int ( key ) ] [ int ( key2 ) ] = int ( preferenceWmgMap [ key ] [ key2 ] ) self . preferences . append ( Preference ( wmgMap , count ) ) | 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 ( [ mmagg . get_ranking ( i ) for i in cand_set ] == [ 1 , 0 , 2 ] ) print ( gamma ) | 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_CAPTION_COLORS [ 0 ] if settings . LOGIN_BUTTON_SIZES . has_key ( button_size ) : button_size = settings . LOGIN_BUTTON_SIZES [ button_size ] else : button_size = settings . LOGIN_BUTTON_SIZES [ 'None' ] return settings . LOGIN_BUTTON_URL % ( button_color , caption_color , button_size ) | 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 ( ) return data . get ( 'access_token' ) | 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 [ i ] . end ) ] + self . intervals [ ( i + 1 ) : ] ) break | 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 ( self . id , start_point , * * kwargs ) else : return resume ( self . id , start_point , * * kwargs ) | 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 ] , headerbase ) return [ '' ] | 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 ) ) Console . ok ( "{:>20} = {:}" . format ( "SCOPES" , self . scopes ) ) Console . ok ( "{:>20} = {:}" . format ( "SCOPELESS" , self . scopeless ) ) Console . ok ( "{:>20} = {:}" . format ( "prompt" , self . prompt ) ) Console . ok ( "{:>20} = {:}" . format ( "scripts" , self . scripts ) ) Console . ok ( "{:>20} = {:}" . format ( "variables" , self . variables ) ) | 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 , AttributeError , ImportError ) : yield HealthCheckFail ( '00005' , f'Cannot import middleware "{m}"' , ) else : if not issubclass ( c , BaseMiddleware ) : yield HealthCheckFail ( '00005' , f'Middleware "{m}" does not implement ' f'"BaseMiddleware"' , ) | 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 {}.' . format ( date_str ) ) | 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 {}.' . format ( datetime_str ) ) | 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 string {}.' . format ( datetime_str ) ) | 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 DateTimeFormatterException : pass try : return cls . extract_datetime_hour ( timestamp_str ) except DateTimeFormatterException : pass try : return cls . extract_date ( timestamp_str ) except DateTimeFormatterException as e : raise DateTimeFormatterException ( e ) | 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.