idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
10,900 | def calc_downsample ( w , h , target = 400 ) : if w > h : return h / target elif h >= w : return w / target | Calculate downsampling value . |
10,901 | def move ( self ) : k = random . choice ( self . keys ) multiplier = random . choice ( ( 0.95 , 1.05 ) ) invalid_key = True while invalid_key : if k == "bias" : if self . state [ k ] > 0.909 : k = random . choice ( self . keys ) continue invalid_key = False newval = self . state [ k ] * multiplier self . state [ k ] = newval | Create a state change . |
10,902 | def apply_color ( self , arr , state ) : ops = self . cmd ( state ) for func in parse_operations ( ops ) : arr = func ( arr ) return arr | Apply color formula to an array . |
10,903 | def energy ( self ) : arr = self . src . copy ( ) arr = self . apply_color ( arr , self . state ) scores = [ histogram_distance ( self . ref [ i ] , arr [ i ] ) for i in range ( 3 ) ] return sum ( scores ) * 100 | Calculate state s energy . |
10,904 | def update ( self , step , T , E , acceptance , improvement ) : if acceptance is None : acceptance = 0 if improvement is None : improvement = 0 if step > 0 : elapsed = time . time ( ) - self . start remain = ( self . steps - step ) * ( elapsed / step ) else : elapsed = 0 remain = 0 curr = self . cmd ( self . state ) curr_score = float ( E ) best = self . cmd ( self . best_state ) best_score = self . best_energy report = progress_report ( curr , best , curr_score , best_score , step , self . steps , acceptance * 100 , improvement * 100 , time_string ( elapsed ) , time_string ( remain ) , ) print ( report ) if fig : imgs [ 1 ] . set_data ( reshape_as_image ( self . apply_color ( self . src . copy ( ) , self . state ) ) ) imgs [ 2 ] . set_data ( reshape_as_image ( self . apply_color ( self . src . copy ( ) , self . best_state ) ) ) if txt : txt . set_text ( report ) fig . canvas . draw ( ) | Print progress . |
10,905 | def atmos_worker ( srcs , window , ij , args ) : src = srcs [ 0 ] rgb = src . read ( window = window ) rgb = to_math_type ( rgb ) atmos = simple_atmo ( rgb , args [ "atmo" ] , args [ "contrast" ] , args [ "bias" ] ) return scale_dtype ( atmos , args [ "out_dtype" ] ) | A simple atmospheric correction user function . |
10,906 | def color_worker ( srcs , window , ij , args ) : src = srcs [ 0 ] arr = src . read ( window = window ) arr = to_math_type ( arr ) for func in parse_operations ( args [ "ops_string" ] ) : arr = func ( arr ) return scale_dtype ( arr , args [ "out_dtype" ] ) | A user function . |
10,907 | def add_raw_code ( self , string_or_list ) : if _is_string ( string_or_list ) : self . _GMSH_CODE . append ( string_or_list ) else : assert isinstance ( string_or_list , list ) for string in string_or_list : self . _GMSH_CODE . append ( string ) return | Add raw Gmsh code . |
10,908 | def _add_torus_extrude_lines ( self , irad , orad , lcar = None , R = numpy . eye ( 3 ) , x0 = numpy . array ( [ 0.0 , 0.0 , 0.0 ] ) ) : self . add_comment ( "Torus" ) x0t = numpy . dot ( R , numpy . array ( [ 0.0 , orad , 0.0 ] ) ) Rc = numpy . array ( [ [ 0.0 , 0.0 , 1.0 ] , [ 0.0 , 1.0 , 0.0 ] , [ 1.0 , 0.0 , 0.0 ] ] ) c = self . add_circle ( x0 + x0t , irad , lcar = lcar , R = numpy . dot ( R , Rc ) ) rot_axis = [ 0.0 , 0.0 , 1.0 ] rot_axis = numpy . dot ( R , rot_axis ) point_on_rot_axis = [ 0.0 , 0.0 , 0.0 ] point_on_rot_axis = numpy . dot ( R , point_on_rot_axis ) + x0 previous = c . line_loop . lines angle = "2*Pi/3" all_surfaces = [ ] for i in range ( 3 ) : self . add_comment ( "Round no. {}" . format ( i + 1 ) ) for k , p in enumerate ( previous ) : top , surf , _ = self . extrude ( p , rotation_axis = rot_axis , point_on_axis = point_on_rot_axis , angle = angle , ) all_surfaces . append ( surf ) previous [ k ] = top surface_loop = self . add_surface_loop ( all_surfaces ) vol = self . add_volume ( surface_loop ) self . add_comment ( "\n" ) return vol | Create Gmsh code for the torus in the x - y plane under the coordinate transformation |
10,909 | def _add_torus_extrude_circle ( self , irad , orad , lcar = None , R = numpy . eye ( 3 ) , x0 = numpy . array ( [ 0.0 , 0.0 , 0.0 ] ) ) : self . add_comment ( 76 * "-" ) self . add_comment ( "Torus" ) x0t = numpy . dot ( R , numpy . array ( [ 0.0 , orad , 0.0 ] ) ) Rc = numpy . array ( [ [ 0.0 , 0.0 , 1.0 ] , [ 1.0 , 0.0 , 0.0 ] , [ 0.0 , 1.0 , 0.0 ] ] ) c = self . add_circle ( x0 + x0t , irad , lcar = lcar , R = numpy . dot ( R , Rc ) ) rot_axis = [ 0.0 , 0.0 , 1.0 ] rot_axis = numpy . dot ( R , rot_axis ) point_on_rot_axis = [ 0.0 , 0.0 , 0.0 ] point_on_rot_axis = numpy . dot ( R , point_on_rot_axis ) + x0 previous = c . plane_surface all_volumes = [ ] num_steps = 3 for _ in range ( num_steps ) : top , vol , _ = self . extrude ( previous , rotation_axis = rot_axis , point_on_axis = point_on_rot_axis , angle = "2*Pi/{}" . format ( num_steps ) , ) previous = top all_volumes . append ( vol ) if self . _gmsh_major ( ) == 3 : self . add_compound_volume ( all_volumes ) else : assert self . _gmsh_major ( ) == 4 self . add_raw_code ( "Compound Volume{{{}}};" . format ( "," . join ( v . id for v in all_volumes ) ) ) self . add_comment ( 76 * "-" + "\n" ) return | Create Gmsh code for the torus under the coordinate transformation |
10,910 | def _add_pipe_by_rectangle_rotation ( self , outer_radius , inner_radius , length , R = numpy . eye ( 3 ) , x0 = numpy . array ( [ 0.0 , 0.0 , 0.0 ] ) , lcar = None , ) : self . add_comment ( "Define rectangle." ) X = numpy . array ( [ [ 0.0 , outer_radius , - 0.5 * length ] , [ 0.0 , outer_radius , + 0.5 * length ] , [ 0.0 , inner_radius , + 0.5 * length ] , [ 0.0 , inner_radius , - 0.5 * length ] , ] ) X = [ numpy . dot ( R , x ) + x0 for x in X ] p = [ self . add_point ( x , lcar = lcar ) for x in X ] e = [ self . add_line ( p [ 0 ] , p [ 1 ] ) , self . add_line ( p [ 1 ] , p [ 2 ] ) , self . add_line ( p [ 2 ] , p [ 3 ] ) , self . add_line ( p [ 3 ] , p [ 0 ] ) , ] rot_axis = [ 0.0 , 0.0 , 1.0 ] rot_axis = numpy . dot ( R , rot_axis ) point_on_rot_axis = [ 0.0 , 0.0 , 0.0 ] point_on_rot_axis = numpy . dot ( R , point_on_rot_axis ) + x0 previous = e angle = "2*Pi/3" all_surfaces = [ ] self . add_comment ( "Extrude in 3 steps." ) for i in range ( 3 ) : self . add_comment ( "Step {}" . format ( i + 1 ) ) for k , p in enumerate ( previous ) : top , surf , _ = self . extrude ( p , rotation_axis = rot_axis , point_on_axis = point_on_rot_axis , angle = angle , ) all_surfaces . append ( surf ) previous [ k ] = top surface_loop = self . add_surface_loop ( all_surfaces ) vol = self . add_volume ( surface_loop ) return vol | Hollow cylinder . Define a rectangle extrude it by rotation . |
10,911 | def _add_pipe_by_circle_extrusion ( self , outer_radius , inner_radius , length , R = numpy . eye ( 3 ) , x0 = numpy . array ( [ 0.0 , 0.0 , 0.0 ] ) , lcar = None , ) : Rc = numpy . array ( [ [ 0.0 , 0.0 , 1.0 ] , [ 1.0 , 0.0 , 0.0 ] , [ 0.0 , 1.0 , 0.0 ] ] ) c_inner = self . add_circle ( x0 , inner_radius , lcar = lcar , R = numpy . dot ( R , Rc ) , make_surface = False ) circ = self . add_circle ( x0 , outer_radius , lcar = lcar , R = numpy . dot ( R , Rc ) , holes = [ c_inner . line_loop ] ) _ , vol , _ = self . extrude ( circ . plane_surface , translation_axis = numpy . dot ( R , [ length , 0 , 0 ] ) ) return vol | Hollow cylinder . Define a ring extrude it by translation . |
10,912 | def translate ( self , input_entity , vector ) : d = { 1 : "Line" , 2 : "Surface" , 3 : "Volume" } self . _GMSH_CODE . append ( "Translate {{{}}} {{ {}{{{}}}; }}" . format ( ", " . join ( [ str ( co ) for co in vector ] ) , d [ input_entity . dimension ] , input_entity . id , ) ) return | Translates input_entity itself by vector . |
10,913 | def symmetry ( self , input_entity , coefficients , duplicate = True ) : d = { 1 : "Line" , 2 : "Surface" , 3 : "Volume" } entity = "{}{{{}}};" . format ( d [ input_entity . dimension ] , input_entity . id ) if duplicate : entity = "Duplicata{{{}}}" . format ( entity ) self . _GMSH_CODE . append ( "Symmetry {{{}}} {{{}}}" . format ( ", " . join ( [ str ( co ) for co in coefficients ] ) , entity ) ) return | Transforms all elementary entities symmetrically to a plane . The vector should contain four expressions giving the coefficients of the plane s equation . |
10,914 | def patch_qcombobox ( QComboBox ) : from . . QtGui import QIcon from . . QtCore import Qt , QObject class userDataWrapper ( ) : def __init__ ( self , data ) : self . data = data _addItem = QComboBox . addItem def addItem ( self , * args , ** kwargs ) : if len ( args ) == 3 or ( not isinstance ( args [ 0 ] , QIcon ) and len ( args ) == 2 ) : args , kwargs [ 'userData' ] = args [ : - 1 ] , args [ - 1 ] if 'userData' in kwargs : kwargs [ 'userData' ] = userDataWrapper ( kwargs [ 'userData' ] ) _addItem ( self , * args , ** kwargs ) _insertItem = QComboBox . insertItem def insertItem ( self , * args , ** kwargs ) : if len ( args ) == 4 or ( not isinstance ( args [ 1 ] , QIcon ) and len ( args ) == 3 ) : args , kwargs [ 'userData' ] = args [ : - 1 ] , args [ - 1 ] if 'userData' in kwargs : kwargs [ 'userData' ] = userDataWrapper ( kwargs [ 'userData' ] ) _insertItem ( self , * args , ** kwargs ) _setItemData = QComboBox . setItemData def setItemData ( self , index , value , role = Qt . UserRole ) : value = userDataWrapper ( value ) _setItemData ( self , index , value , role = role ) _itemData = QComboBox . itemData def itemData ( self , index , role = Qt . UserRole ) : userData = _itemData ( self , index , role = role ) if isinstance ( userData , userDataWrapper ) : userData = userData . data return userData def findData ( self , value ) : for i in range ( self . count ( ) ) : if self . itemData ( i ) == value : return i return - 1 QComboBox . addItem = addItem QComboBox . insertItem = insertItem QComboBox . setItemData = setItemData QComboBox . itemData = itemData QComboBox . findData = findData | In PySide using Python objects as userData in QComboBox causes Segmentation faults under certain conditions . Even in cases where it doesn t findData does not work correctly . Likewise findData also does not work correctly with Python objects when using PyQt4 . On the other hand PyQt5 deals with this case correctly . We therefore patch QComboBox when using PyQt4 and PySide to avoid issues . |
10,915 | def to_czml ( traffic : Union [ Traffic , SO6 ] , filename : Union [ str , Path ] , minimum_time : Optional [ timelike ] = None , ) -> None : if isinstance ( traffic , Traffic ) : if "baro_altitude" in traffic . data . columns : traffic = traffic . query ( "baro_altitude == baro_altitude" ) elif "altitude" in traffic . data . columns : traffic = traffic . query ( "altitude == altitude" ) if minimum_time is not None : minimum_time = to_datetime ( minimum_time ) traffic = cast ( Traffic , traffic . query ( f"timestamp >= '{minimum_time}'" ) ) if isinstance ( filename , str ) : filename = Path ( filename ) if not filename . parent . exists ( ) : filename . parent . mkdir ( parents = True ) start = format_ts ( traffic . start_time ) availability = f"{start}/{format_ts(traffic.end_time)}" export = [ { "id" : "document" , "name" : f"Traffic_{start}" , "version" : "1.0" , "author" : getpass . getuser ( ) , "clock" : { "interval" : availability , "currentTime" : start , "multiplier" : _CZML_Params . default_time_multiplier , } , } ] for flight in traffic : for elt in export_flight ( flight ) : export . append ( elt ) with filename . open ( "w" ) as fh : json . dump ( export , fh , indent = 2 ) logging . info ( f"Scenario file {filename} written" ) | Generates a CesiumJS scenario file . |
10,916 | def plot ( self , ax : GeoAxesSubplot , ** kwargs ) -> Artist : if "facecolor" not in kwargs : kwargs [ "facecolor" ] = "None" if "edgecolor" not in kwargs : kwargs [ "edgecolor" ] = ax . _get_lines . get_next_color ( ) if "projection" in ax . __dict__ : return ax . add_geometries ( [ self . shape ] , crs = PlateCarree ( ) , ** kwargs ) else : return ax . add_patch ( MplPolygon ( list ( self . shape . exterior . coords ) , ** kwargs ) ) | Plotting function . All arguments are passed to the geometry |
10,917 | def api_states ( self , own : bool = False , bounds : Union [ BaseGeometry , Tuple [ float , float , float , float ] , None ] = None , ) -> StateVectors : what = "own" if ( own and self . auth is not None ) else "all" if bounds is not None : try : west , south , east , north = bounds . bounds except AttributeError : west , south , east , north = bounds what += f"?lamin={south}&lamax={north}&lomin={west}&lomax={east}" c = requests . get ( f"https://opensky-network.org/api/states/{what}" , auth = self . auth ) if c . status_code != 200 : raise ValueError ( c . content . decode ( ) ) r = pd . DataFrame . from_records ( c . json ( ) [ "states" ] , columns = self . _json_columns ) r = r . drop ( [ "origin_country" , "spi" , "sensors" ] , axis = 1 ) r = r . dropna ( ) return StateVectors ( self . _format_dataframe ( r , nautical_units = True ) , self ) | Returns the current state vectors from OpenSky REST API . |
10,918 | def api_tracks ( self , icao24 : str ) -> Flight : c = requests . get ( f"https://opensky-network.org/api/tracks/?icao24={icao24}" ) if c . status_code != 200 : raise ValueError ( c . content . decode ( ) ) json = c . json ( ) df = pd . DataFrame . from_records ( json [ "path" ] , columns = [ "timestamp" , "latitude" , "longitude" , "altitude" , "track" , "onground" , ] , ) . assign ( icao24 = json [ "icao24" ] , callsign = json [ "callsign" ] ) return Flight ( self . _format_dataframe ( df , nautical_units = True ) ) | Returns a Flight corresponding to a given aircraft . |
10,919 | def api_routes ( self , callsign : str ) -> Tuple [ Airport , ... ] : from . . import airports c = requests . get ( f"https://opensky-network.org/api/routes?callsign={callsign}" ) if c . status_code == 404 : raise ValueError ( "Unknown callsign" ) if c . status_code != 200 : raise ValueError ( c . content . decode ( ) ) json = c . json ( ) return tuple ( airports [ a ] for a in json [ "route" ] ) | Returns the route associated to a callsign . |
10,920 | def api_aircraft ( self , icao24 : str , begin : Optional [ timelike ] = None , end : Optional [ timelike ] = None , ) -> pd . DataFrame : if begin is None : begin = round_time ( datetime . now ( timezone . utc ) , by = timedelta ( days = 1 ) ) begin = to_datetime ( begin ) if end is None : end = begin + timedelta ( days = 1 ) else : end = to_datetime ( end ) begin = int ( begin . timestamp ( ) ) end = int ( end . timestamp ( ) ) c = requests . get ( f"https://opensky-network.org/api/flights/aircraft" f"?icao24={icao24}&begin={begin}&end={end}" ) if c . status_code != 200 : raise ValueError ( c . content . decode ( ) ) return ( pd . DataFrame . from_records ( c . json ( ) ) [ [ "firstSeen" , "lastSeen" , "icao24" , "callsign" , "estDepartureAirport" , "estArrivalAirport" , ] ] . assign ( firstSeen = lambda df : pd . to_datetime ( df . firstSeen * 1e9 ) . dt . tz_localize ( "utc" ) , lastSeen = lambda df : pd . to_datetime ( df . lastSeen * 1e9 ) . dt . tz_localize ( "utc" ) , ) . sort_values ( "lastSeen" ) ) | Returns a flight table associated to an aircraft . |
10,921 | def api_range ( self , serial : str , date : Optional [ timelike ] = None ) -> SensorRange : if date is None : date = round_time ( datetime . now ( timezone . utc ) , by = timedelta ( days = 1 ) ) else : date = to_datetime ( date ) date = int ( date . timestamp ( ) ) c = requests . get ( f"https://opensky-network.org/api/range/days" f"?days={date}&serials={serial}" ) if c . status_code != 200 : raise ValueError ( c . content . decode ( ) ) return SensorRange ( c . json ( ) ) | Wraps a polygon representing a sensor s range . |
10,922 | def api_arrival ( self , airport : Union [ str , Airport ] , begin : Optional [ timelike ] = None , end : Optional [ timelike ] = None , ) -> pd . DataFrame : if isinstance ( airport , str ) : from . . import airports airport_code = airports [ airport ] . icao else : airport_code = airport . icao if begin is None : begin = round_time ( datetime . now ( timezone . utc ) , by = timedelta ( days = 1 ) ) begin = to_datetime ( begin ) if end is None : end = begin + timedelta ( days = 1 ) else : end = to_datetime ( end ) begin = int ( begin . timestamp ( ) ) end = int ( end . timestamp ( ) ) c = requests . get ( f"https://opensky-network.org/api/flights/arrival" f"?begin={begin}&airport={airport_code}&end={end}" ) if c . status_code != 200 : raise ValueError ( c . content . decode ( ) ) return ( pd . DataFrame . from_records ( c . json ( ) ) [ [ "firstSeen" , "lastSeen" , "icao24" , "callsign" , "estDepartureAirport" , "estArrivalAirport" , ] ] . assign ( firstSeen = lambda df : pd . to_datetime ( df . firstSeen * 1e9 ) . dt . tz_localize ( "utc" ) , lastSeen = lambda df : pd . to_datetime ( df . lastSeen * 1e9 ) . dt . tz_localize ( "utc" ) , ) . sort_values ( "lastSeen" ) ) | Returns a flight table associated to an airport . |
10,923 | def start ( self ) -> pd . Timestamp : start = self . data . timestamp . min ( ) self . data = self . data . assign ( start = start ) return start | Returns the minimum timestamp value of the DataFrame . |
10,924 | def squawk ( self ) -> Set [ str ] : return set ( self . data . squawk . ffill ( ) . bfill ( ) ) | Returns all the unique squawk values in the trajectory . |
10,925 | def query_opensky ( self ) -> Optional [ "Flight" ] : from . . data import opensky query_params = { "start" : self . start , "stop" : self . stop , "callsign" : self . callsign , "icao24" : self . icao24 , } return opensky . history ( ** query_params ) | Return the equivalent Flight from OpenSky History . |
10,926 | def coords ( self ) -> Iterator [ Tuple [ float , float , float ] ] : data = self . data [ self . data . longitude . notnull ( ) ] yield from zip ( data [ "longitude" ] , data [ "latitude" ] , data [ "altitude" ] ) | Iterates on longitudes latitudes and altitudes . |
10,927 | def xy_time ( self ) -> Iterator [ Tuple [ float , float , float ] ] : iterator = iter ( zip ( self . coords , self . timestamp ) ) while True : next_ = next ( iterator , None ) if next_ is None : return coords , time = next_ yield ( coords [ 0 ] , coords [ 1 ] , time . to_pydatetime ( ) . timestamp ( ) ) | Iterates on longitudes latitudes and timestamps . |
10,928 | def split ( self , value = 10 , unit = None ) : if type ( value ) == int and unit is None : unit = "m" for data in _split ( self . data , value , unit ) : yield self . __class__ ( data ) | Splits Flights in several legs . |
10,929 | def resample ( self , rule : Union [ str , int ] = "1s" ) -> "Flight" : if isinstance ( rule , str ) : data = ( self . _handle_last_position ( ) . data . assign ( start = self . start , stop = self . stop ) . set_index ( "timestamp" ) . resample ( rule ) . first ( ) . interpolate ( ) . reset_index ( ) . fillna ( method = "pad" ) ) elif isinstance ( rule , int ) : data = ( self . _handle_last_position ( ) . data . set_index ( "timestamp" ) . asfreq ( ( self . stop - self . start ) / ( rule - 1 ) , method = "nearest" , ) . reset_index ( ) ) else : raise TypeError ( "rule must be a str or an int" ) return self . __class__ ( data ) | Resamples a Flight at a one point per second rate . |
10,930 | def simplify ( self , tolerance : float , altitude : Optional [ str ] = None , z_factor : float = 3.048 , return_type : Type [ Mask ] = Type [ "Flight" ] , ) -> Mask : mask = douglas_peucker ( df = self . data , tolerance = tolerance , lat = "latitude" , lon = "longitude" , z = altitude , z_factor = z_factor , ) if return_type == Type [ "Flight" ] : return self . __class__ ( self . data . loc [ mask ] ) else : return mask | Simplifies a trajectory with Douglas - Peucker algorithm . |
10,931 | def project_shape ( self , projection : Union [ pyproj . Proj , crs . Projection , None ] = None ) -> base . BaseGeometry : if self . shape is None : return None if isinstance ( projection , crs . Projection ) : projection = pyproj . Proj ( projection . proj4_init ) if projection is None : bounds = self . bounds projection = pyproj . Proj ( proj = "aea" , lat_1 = bounds [ 1 ] , lat_2 = bounds [ 3 ] , lat_0 = ( bounds [ 1 ] + bounds [ 3 ] ) / 2 , lon_0 = ( bounds [ 0 ] + bounds [ 2 ] ) / 2 , ) projected_shape = transform ( partial ( pyproj . transform , pyproj . Proj ( init = "EPSG:4326" ) , projection ) , self . shape , ) if not projected_shape . is_valid : warnings . warn ( "The chosen projection is invalid for current shape" ) return projected_shape | Projection for a decent representation of the structure . |
10,932 | def compute_xy ( self , projection : Union [ pyproj . Proj , crs . Projection , None ] = None ) : if isinstance ( projection , crs . Projection ) : projection = pyproj . Proj ( projection . proj4_init ) if projection is None : projection = pyproj . Proj ( proj = "lcc" , lat_1 = self . data . latitude . min ( ) , lat_2 = self . data . latitude . max ( ) , lat_0 = self . data . latitude . mean ( ) , lon_0 = self . data . longitude . mean ( ) , ) x , y = pyproj . transform ( pyproj . Proj ( init = "EPSG:4326" ) , projection , self . data . longitude . values , self . data . latitude . values , ) return self . __class__ ( self . data . assign ( x = x , y = y ) ) | Computes x and y columns from latitudes and longitudes . |
10,933 | def callsigns ( self ) -> Set [ str ] : sub = self . data . query ( "callsign == callsign" ) return set ( cs for cs in sub . callsign if len ( cs ) > 3 and " " not in cs ) | Return only the most relevant callsigns |
10,934 | def resample ( self , rule : Union [ str , int ] = "1s" , max_workers : int = 4 , ) -> "Traffic" : with ProcessPoolExecutor ( max_workers = max_workers ) as executor : cumul = [ ] tasks = { executor . submit ( flight . resample , rule ) : flight for flight in self } for future in tqdm ( as_completed ( tasks ) , total = len ( tasks ) ) : cumul . append ( future . result ( ) ) return self . __class__ . from_flights ( cumul ) | Resamples all trajectories flight by flight . |
10,935 | def vcas2mach ( cas , h ) : tas = vcas2tas ( cas , h ) M = vtas2mach ( tas , h ) return M | CAS to Mach conversion |
10,936 | def cas2mach ( cas , h ) : tas = cas2tas ( cas , h ) M = tas2mach ( tas , h ) return M | CAS Mach conversion |
10,937 | def to_bluesky ( traffic : Traffic , filename : Union [ str , Path ] , minimum_time : Optional [ timelike ] = None , ) -> None : if minimum_time is not None : minimum_time = to_datetime ( minimum_time ) traffic = traffic . query ( f"timestamp >= '{minimum_time}'" ) if isinstance ( filename , str ) : filename = Path ( filename ) if not filename . parent . exists ( ) : filename . parent . mkdir ( parents = True ) altitude = ( "baro_altitude" if "baro_altitude" in traffic . data . columns else "altitude" ) if "mdl" not in traffic . data . columns : traffic = aircraft . merge ( traffic ) if "cas" not in traffic . data . columns : traffic = Traffic ( traffic . data . assign ( cas = vtas2cas ( traffic . data . ground_speed , traffic . data [ altitude ] ) ) ) with filename . open ( "w" ) as fh : t_delta = traffic . data . timestamp - traffic . start_time data = ( traffic . assign_id ( ) . data . groupby ( "flight_id" ) . filter ( lambda x : x . shape [ 0 ] > 3 ) . assign ( timedelta = t_delta . apply ( fmt_timedelta ) ) . sort_values ( by = "timestamp" ) ) for column in data . columns : data [ column ] = data [ column ] . astype ( np . str ) is_created : List [ str ] = [ ] is_deleted : List [ str ] = [ ] start_time = cast ( pd . Timestamp , traffic . start_time ) . time ( ) fh . write ( f"00:00:00> TIME {start_time}\n" ) buff = data . groupby ( "flight_id" ) . timestamp . max ( ) dd = pd . DataFrame ( columns = [ "timestamp" ] , data = buff . values , index = buff . index . values ) map_icao24_last_point = { } for i , v in dd . iterrows ( ) : map_icao24_last_point [ i ] = v [ 0 ] for _ , v in data . iterrows ( ) : if v . flight_id not in is_created : is_created . append ( v . flight_id ) fh . write ( f"{v.timedelta}> CRE {v.callsign} {v.mdl} " f"{v.latitude} {v.longitude} {v.track} " f"{v[altitude]} {v.cas}\n" ) elif v . timestamp == map_icao24_last_point [ v . flight_id ] : if v . flight_id not in is_deleted : is_deleted . append ( v . flight_id ) fh . write ( f"{v.timedelta}> DEL {v.callsign}\n" ) elif v . flight_id not in is_deleted : fh . write ( f"{v.timedelta}> MOVE {v.callsign} " f"{v.latitude} {v.longitude} {v[altitude]} " f"{v.track} {v.cas} {v.vertical_rate}\n" ) logging . info ( f"Scenario file {filename} written" ) | Generates a Bluesky scenario file . |
10,938 | def import_submodules ( package , recursive = True ) : if isinstance ( package , str ) : package = importlib . import_module ( package ) results = { } for loader , name , is_pkg in pkgutil . walk_packages ( package . __path__ ) : full_name = package . __name__ + "." + name results [ name ] = importlib . import_module ( full_name ) if recursive and is_pkg : results . update ( import_submodules ( full_name ) ) return results | Import all submodules of a module recursively including subpackages |
10,939 | def interpolate ( self , times , proj = PlateCarree ( ) ) -> np . ndarray : if proj not in self . interpolator : self . interpolator [ proj ] = interp1d ( np . stack ( t . to_pydatetime ( ) . timestamp ( ) for t in self . timestamp ) , proj . transform_points ( PlateCarree ( ) , * np . stack ( self . coords ) . T ) . T , ) return PlateCarree ( ) . transform_points ( proj , * self . interpolator [ proj ] ( times ) ) | Interpolates a trajectory in time . |
10,940 | def _set_default_extent ( self ) : west , south , east , north = self . projection . boundary . bounds self . set_extent ( ( west , east , south , north ) , crs = self . projection ) | Helper for a default extent limited to the projection boundaries . |
10,941 | def _format_dataframe ( df : pd . DataFrame , nautical_units = True ) -> pd . DataFrame : if "callsign" in df . columns and df . callsign . dtype == object : df . callsign = df . callsign . str . strip ( ) if nautical_units : df . altitude = df . altitude / 0.3048 if "geoaltitude" in df . columns : df . geoaltitude = df . geoaltitude / 0.3048 if "groundspeed" in df . columns : df . groundspeed = df . groundspeed / 1852 * 3600 if "vertical_rate" in df . columns : df . vertical_rate = df . vertical_rate / 0.3048 * 60 df . timestamp = pd . to_datetime ( df . timestamp * 1e9 ) . dt . tz_localize ( "utc" ) if "last_position" in df . columns : df = df . query ( "last_position == last_position" ) . assign ( last_position = pd . to_datetime ( df . last_position * 1e9 ) . dt . tz_localize ( "utc" ) ) return df . sort_values ( "timestamp" ) | This function converts types strips spaces after callsigns and sorts the DataFrame by timestamp . |
10,942 | def filter ( self , info , releases ) : removed = 0 versions = list ( releases . keys ( ) ) for version in versions : new_files = [ ] for file_desc in releases [ version ] : if self . _check_match ( file_desc ) : removed += 1 else : new_files . append ( file_desc ) if len ( new_files ) == 0 : del releases [ version ] else : releases [ version ] = new_files logger . debug ( f"{self.name}: filenames removed: {removed}" ) | Remove files from releases that match any pattern . |
10,943 | def load_filter_plugins ( entrypoint_group : str ) -> Iterable [ Filter ] : global loaded_filter_plugins enabled_plugins : List [ str ] = [ ] config = BandersnatchConfig ( ) . config try : config_blacklist_plugins = config [ "blacklist" ] [ "plugins" ] split_plugins = config_blacklist_plugins . split ( "\n" ) if "all" in split_plugins : enabled_plugins = [ "all" ] else : for plugin in split_plugins : if not plugin : continue enabled_plugins . append ( plugin ) except KeyError : pass cached_plugins = loaded_filter_plugins . get ( entrypoint_group ) if cached_plugins : return cached_plugins plugins = set ( ) for entry_point in pkg_resources . iter_entry_points ( group = entrypoint_group ) : plugin_class = entry_point . load ( ) plugin_instance = plugin_class ( ) if "all" in enabled_plugins or plugin_instance . name in enabled_plugins : plugins . add ( plugin_instance ) loaded_filter_plugins [ entrypoint_group ] = list ( plugins ) return plugins | Load all blacklist plugins that are registered with pkg_resources |
10,944 | def filter ( self , info , releases ) : for version in list ( releases . keys ( ) ) : if any ( pattern . match ( version ) for pattern in self . patterns ) : del releases [ version ] | Remove all release versions that match any of the specificed patterns . |
10,945 | def _check_match ( self , name , version_string ) -> bool : if not name or not version_string : return False try : version = Version ( version_string ) except InvalidVersion : logger . debug ( f"Package {name}=={version_string} has an invalid version" ) return False for requirement in self . blacklist_release_requirements : if name != requirement . name : continue if version in requirement . specifier : logger . debug ( f"MATCH: Release {name}=={version} matches specifier " f"{requirement.specifier}" ) return True return False | Check if the package name and version matches against a blacklisted package version specifier . |
10,946 | def find ( root : Union [ Path , str ] , dirs : bool = True ) -> str : if isinstance ( root , str ) : root = Path ( root ) results : List [ Path ] = [ ] for dirpath , dirnames , filenames in os . walk ( root ) : names = filenames if dirs : names += dirnames for name in names : results . append ( Path ( dirpath ) / name ) results . sort ( ) return "\n" . join ( str ( result . relative_to ( root ) ) for result in results ) | A test helper simulating find . |
10,947 | def rewrite ( filepath : Union [ str , Path ] , mode : str = "w" , ** kw : Any ) -> Generator [ IO , None , None ] : if isinstance ( filepath , str ) : base_dir = os . path . dirname ( filepath ) filename = os . path . basename ( filepath ) else : base_dir = str ( filepath . parent ) filename = filepath . name with tempfile . NamedTemporaryFile ( mode = mode , prefix = f".{filename}." , delete = False , dir = base_dir , ** kw ) as f : filepath_tmp = f . name yield f if not os . path . exists ( filepath_tmp ) : return os . chmod ( filepath_tmp , 0o100644 ) os . rename ( filepath_tmp , filepath ) | Rewrite an existing file atomically to avoid programs running in parallel to have race conditions while reading . |
10,948 | def unlink_parent_dir ( path : Path ) -> None : logger . info ( f"unlink {str(path)}" ) path . unlink ( ) parent_path = path . parent try : parent_path . rmdir ( ) logger . info ( f"rmdir {str(parent_path)}" ) except OSError as oe : logger . debug ( f"Did not remove {str(parent_path)}: {str(oe)}" ) | Remove a file and if the dir is empty remove it |
10,949 | def update_safe ( filename : str , ** kw : Any ) -> Generator [ IO , None , None ] : with tempfile . NamedTemporaryFile ( dir = os . path . dirname ( filename ) , delete = False , prefix = f"{os.path.basename(filename)}." , ** kw , ) as tf : if os . path . exists ( filename ) : os . chmod ( tf . name , os . stat ( filename ) . st_mode & 0o7777 ) tf . has_changed = False yield tf if not os . path . exists ( tf . name ) : return filename_tmp = tf . name if os . path . exists ( filename ) and filecmp . cmp ( filename , filename_tmp , shallow = False ) : os . unlink ( filename_tmp ) else : os . rename ( filename_tmp , filename ) tf . has_changed = True | Rewrite a file atomically . |
10,950 | def save_json_metadata ( self , package_info : Dict ) -> bool : try : with utils . rewrite ( self . json_file ) as jf : dump ( package_info , jf , indent = 4 , sort_keys = True ) except Exception as e : logger . error ( "Unable to write json to {}: {}" . format ( self . json_file , str ( e ) ) ) return False symlink_dir = self . json_pypi_symlink . parent if not symlink_dir . exists ( ) : symlink_dir . mkdir ( ) try : self . json_pypi_symlink . symlink_to ( self . json_file ) except FileExistsError : pass return True | Take the JSON metadata we just fetched and save to disk |
10,951 | def _filter_releases ( self ) : global display_filter_log filter_plugins = filter_release_plugins ( ) if not filter_plugins : if display_filter_log : logger . info ( "No release filters are enabled. Skipping filtering" ) display_filter_log = False else : for plugin in filter_plugins : plugin . filter ( self . info , self . releases ) | Run the release filtering plugins |
10,952 | def sync_release_files ( self ) : release_files = [ ] for release in self . releases . values ( ) : release_files . extend ( release ) downloaded_files = set ( ) deferred_exception = None for release_file in release_files : try : downloaded_file = self . download_file ( release_file [ "url" ] , release_file [ "digests" ] [ "sha256" ] ) if downloaded_file : downloaded_files . add ( str ( downloaded_file . relative_to ( self . mirror . homedir ) ) ) except Exception as e : logger . exception ( f"Continuing to next file after error downloading: " f"{release_file['url']}" ) if not deferred_exception : deferred_exception = e if deferred_exception : raise deferred_exception self . mirror . altered_packages [ self . name ] = downloaded_files | Purge + download files returning files removed + added |
10,953 | def _cleanup ( self ) : if self . todolist . exists ( ) : try : saved_todo = iter ( open ( self . todolist , encoding = "utf-8" ) ) int ( next ( saved_todo ) . strip ( ) ) for line in saved_todo : _ , serial = line . strip ( ) . split ( ) int ( serial ) except ( StopIteration , ValueError ) : logger . info ( "Removing inconsistent todo list." ) self . todolist . unlink ( ) | Does a couple of cleanup tasks to ensure consistent data for later processing . |
10,954 | def _filter_packages ( self ) : global LOG_PLUGINS filter_plugins = filter_project_plugins ( ) if not filter_plugins : if LOG_PLUGINS : logger . info ( "No project filters are enabled. Skipping filtering" ) LOG_PLUGINS = False return packages = list ( self . packages_to_sync . keys ( ) ) for package_name in packages : for plugin in filter_plugins : if plugin . check_match ( name = package_name ) : if package_name not in self . packages_to_sync : logger . debug ( f"{package_name} not found in packages to sync - " + f"{plugin.name} has no effect here ..." ) else : del self . packages_to_sync [ package_name ] | Run the package filtering plugins and remove any packages from the packages_to_sync that match any filters . - Logging of action will be done within the check_match methods |
10,955 | def determine_packages_to_sync ( self ) : self . target_serial = self . synced_serial self . packages_to_sync = { } logger . info ( f"Current mirror serial: {self.synced_serial}" ) if self . todolist . exists ( ) : logger . info ( "Resuming interrupted sync from local todo list." ) saved_todo = iter ( open ( self . todolist , encoding = "utf-8" ) ) self . target_serial = int ( next ( saved_todo ) . strip ( ) ) for line in saved_todo : package , serial = line . strip ( ) . split ( ) self . packages_to_sync [ package ] = int ( serial ) elif not self . synced_serial : logger . info ( "Syncing all packages." ) self . packages_to_sync . update ( self . master . all_packages ( ) ) self . target_serial = max ( [ self . synced_serial ] + list ( self . packages_to_sync . values ( ) ) ) else : logger . info ( "Syncing based on changelog." ) self . packages_to_sync . update ( self . master . changed_packages ( self . synced_serial ) ) self . target_serial = max ( [ self . synced_serial ] + list ( self . packages_to_sync . values ( ) ) ) self . need_index_sync = bool ( self . packages_to_sync ) self . _filter_packages ( ) logger . info ( f"Trying to reach serial: {self.target_serial}" ) pkg_count = len ( self . packages_to_sync ) logger . info ( f"{pkg_count} packages to sync." ) | Update the self . packages_to_sync to contain packages that need to be synced . |
10,956 | def get_simple_dirs ( self , simple_dir : Path ) -> List [ Path ] : if self . hash_index : subdirs = [ simple_dir / x for x in simple_dir . iterdir ( ) if x . is_dir ( ) ] else : subdirs = [ simple_dir ] return subdirs | Return a list of simple index directories that should be searched for package indexes when compiling the main index page . |
10,957 | def find_package_indexes_in_dir ( self , simple_dir ) : packages = sorted ( { canonicalize_name ( x ) for x in os . listdir ( simple_dir ) } ) packages = [ x for x in packages if os . path . isdir ( os . path . join ( simple_dir , x ) ) ] return packages | Given a directory that contains simple packages indexes return a sorted list of normalized package names . This presumes every directory within is a simple package index directory . |
10,958 | def load_configuration ( self ) -> None : config_file = self . default_config_file if self . config_file : config_file = self . config_file self . config = ConfigParser ( ) self . config . read ( config_file ) | Read the configuration from a configuration file |
10,959 | async def metadata_verify ( config , args ) -> int : all_package_files = [ ] loop = asyncio . get_event_loop ( ) mirror_base = config . get ( "mirror" , "directory" ) json_base = Path ( mirror_base ) / "web" / "json" workers = args . workers or config . getint ( "mirror" , "workers" ) executor = concurrent . futures . ThreadPoolExecutor ( max_workers = workers ) logger . info ( f"Starting verify for {mirror_base} with {workers} workers" ) try : json_files = await loop . run_in_executor ( executor , os . listdir , json_base ) except FileExistsError as fee : logger . error ( f"Metadata base dir {json_base} does not exist: {fee}" ) return 2 if not json_files : logger . error ( "No JSON metadata files found. Can not verify" ) return 3 logger . debug ( f"Found {len(json_files)} objects in {json_base}" ) logger . debug ( f"Using a {workers} thread ThreadPoolExecutor" ) await async_verify ( config , all_package_files , mirror_base , json_files , args , executor ) if not args . delete : return 0 return await delete_files ( mirror_base , executor , all_package_files , args . dry_run ) | Crawl all saved JSON metadata or online to check we have all packages if delete - generate a diff of unowned files |
10,960 | def _der_to_pem ( der_key , marker ) : pem_key_chunks = [ ( '-----BEGIN %s-----' % marker ) . encode ( 'utf-8' ) ] for chunk_start in range ( 0 , len ( der_key ) , 48 ) : pem_key_chunks . append ( b64encode ( der_key [ chunk_start : chunk_start + 48 ] ) ) pem_key_chunks . append ( ( '-----END %s-----' % marker ) . encode ( 'utf-8' ) ) return b'\n' . join ( pem_key_chunks ) | Perform a simple DER to PEM conversion . |
10,961 | def _der_to_raw ( self , der_signature ) : r , s = decode_dss_signature ( der_signature ) component_length = self . _sig_component_length ( ) return int_to_bytes ( r , component_length ) + int_to_bytes ( s , component_length ) | Convert signature from DER encoding to RAW encoding . |
10,962 | def _raw_to_der ( self , raw_signature ) : component_length = self . _sig_component_length ( ) if len ( raw_signature ) != int ( 2 * component_length ) : raise ValueError ( "Invalid signature" ) r_bytes = raw_signature [ : component_length ] s_bytes = raw_signature [ component_length : ] r = int_from_bytes ( r_bytes , "big" ) s = int_from_bytes ( s_bytes , "big" ) return encode_dss_signature ( r , s ) | Convert signature from RAW encoding to DER encoding . |
10,963 | def encode ( claims , key , algorithm = ALGORITHMS . HS256 , headers = None , access_token = None ) : for time_claim in [ 'exp' , 'iat' , 'nbf' ] : if isinstance ( claims . get ( time_claim ) , datetime ) : claims [ time_claim ] = timegm ( claims [ time_claim ] . utctimetuple ( ) ) if access_token : claims [ 'at_hash' ] = calculate_at_hash ( access_token , ALGORITHMS . HASHES [ algorithm ] ) return jws . sign ( claims , key , headers = headers , algorithm = algorithm ) | Encodes a claims set and returns a JWT string . |
10,964 | def decode ( token , key , algorithms = None , options = None , audience = None , issuer = None , subject = None , access_token = None ) : defaults = { 'verify_signature' : True , 'verify_aud' : True , 'verify_iat' : True , 'verify_exp' : True , 'verify_nbf' : True , 'verify_iss' : True , 'verify_sub' : True , 'verify_jti' : True , 'verify_at_hash' : True , 'require_aud' : False , 'require_iat' : False , 'require_exp' : False , 'require_nbf' : False , 'require_iss' : False , 'require_sub' : False , 'require_jti' : False , 'require_at_hash' : False , 'leeway' : 0 , } if options : defaults . update ( options ) verify_signature = defaults . get ( 'verify_signature' , True ) try : payload = jws . verify ( token , key , algorithms , verify = verify_signature ) except JWSError as e : raise JWTError ( e ) algorithm = jws . get_unverified_header ( token ) [ 'alg' ] try : claims = json . loads ( payload . decode ( 'utf-8' ) ) except ValueError as e : raise JWTError ( 'Invalid payload string: %s' % e ) if not isinstance ( claims , Mapping ) : raise JWTError ( 'Invalid payload string: must be a json object' ) _validate_claims ( claims , audience = audience , issuer = issuer , subject = subject , algorithm = algorithm , access_token = access_token , options = defaults ) return claims | Verifies a JWT string s signature and validates reserved claims . |
10,965 | def _validate_nbf ( claims , leeway = 0 ) : if 'nbf' not in claims : return try : nbf = int ( claims [ 'nbf' ] ) except ValueError : raise JWTClaimsError ( 'Not Before claim (nbf) must be an integer.' ) now = timegm ( datetime . utcnow ( ) . utctimetuple ( ) ) if nbf > ( now + leeway ) : raise JWTClaimsError ( 'The token is not yet valid (nbf)' ) | Validates that the nbf claim is valid . |
10,966 | def _validate_exp ( claims , leeway = 0 ) : if 'exp' not in claims : return try : exp = int ( claims [ 'exp' ] ) except ValueError : raise JWTClaimsError ( 'Expiration Time claim (exp) must be an integer.' ) now = timegm ( datetime . utcnow ( ) . utctimetuple ( ) ) if exp < ( now - leeway ) : raise ExpiredSignatureError ( 'Signature has expired.' ) | Validates that the exp claim is valid . |
10,967 | def _validate_aud ( claims , audience = None ) : if 'aud' not in claims : return audience_claims = claims [ 'aud' ] if isinstance ( audience_claims , string_types ) : audience_claims = [ audience_claims ] if not isinstance ( audience_claims , list ) : raise JWTClaimsError ( 'Invalid claim format in token' ) if any ( not isinstance ( c , string_types ) for c in audience_claims ) : raise JWTClaimsError ( 'Invalid claim format in token' ) if audience not in audience_claims : raise JWTClaimsError ( 'Invalid audience' ) | Validates that the aud claim is valid . |
10,968 | def _validate_iss ( claims , issuer = None ) : if issuer is not None : if isinstance ( issuer , string_types ) : issuer = ( issuer , ) if claims . get ( 'iss' ) not in issuer : raise JWTClaimsError ( 'Invalid issuer' ) | Validates that the iss claim is valid . |
10,969 | def _validate_sub ( claims , subject = None ) : if 'sub' not in claims : return if not isinstance ( claims [ 'sub' ] , string_types ) : raise JWTClaimsError ( 'Subject must be a string.' ) if subject is not None : if claims . get ( 'sub' ) != subject : raise JWTClaimsError ( 'Invalid subject' ) | Validates that the sub claim is valid . |
10,970 | def _gcd ( a , b ) : while b : a , b = b , ( a % b ) return a | Calculate the Greatest Common Divisor of a and b . |
10,971 | def _rsa_recover_prime_factors ( n , e , d ) : ktot = d * e - 1 t = ktot while t % 2 == 0 : t = t // 2 spotted = False a = 2 while not spotted and a < _MAX_RECOVERY_ATTEMPTS : k = t while k < ktot : cand = pow ( a , k , n ) if cand != 1 and cand != ( n - 1 ) and pow ( cand , 2 , n ) == 1 : p = _gcd ( cand + 1 , n ) spotted = True break k *= 2 a += 2 if not spotted : raise ValueError ( "Unable to compute factors p and q from exponent d." ) q , r = divmod ( n , p ) assert r == 0 p , q = sorted ( ( p , q ) , reverse = True ) return ( p , q ) | Compute factors p and q from the private exponent d . We assume that n has no more than two factors . This function is adapted from code in PyCrypto . |
10,972 | def _legacy_private_key_pkcs8_to_pkcs1 ( pkcs8_key ) : if not pkcs8_key . startswith ( LEGACY_INVALID_PKCS8_RSA_HEADER + ASN1_SEQUENCE_ID ) : raise ValueError ( "Invalid private key encoding" ) return pkcs8_key [ len ( LEGACY_INVALID_PKCS8_RSA_HEADER ) : ] | Legacy RSA private key PKCS8 - to - PKCS1 conversion . |
10,973 | def base64url_decode ( input ) : rem = len ( input ) % 4 if rem > 0 : input += b'=' * ( 4 - rem ) return base64 . urlsafe_b64decode ( input ) | Helper method to base64url_decode a string . |
10,974 | def constant_time_string_compare ( a , b ) : try : return hmac . compare_digest ( a , b ) except AttributeError : if len ( a ) != len ( b ) : return False result = 0 for x , y in zip ( a , b ) : result |= ord ( x ) ^ ord ( y ) return result == 0 | Helper for comparing string in constant time independent of the python version being used . |
10,975 | def sign ( payload , key , headers = None , algorithm = ALGORITHMS . HS256 ) : if algorithm not in ALGORITHMS . SUPPORTED : raise JWSError ( 'Algorithm %s not supported.' % algorithm ) encoded_header = _encode_header ( algorithm , additional_headers = headers ) encoded_payload = _encode_payload ( payload ) signed_output = _sign_header_and_claims ( encoded_header , encoded_payload , algorithm , key ) return signed_output | Signs a claims set and returns a JWS string . |
10,976 | def verify ( token , key , algorithms , verify = True ) : header , payload , signing_input , signature = _load ( token ) if verify : _verify_signature ( signing_input , header , signature , key , algorithms ) return payload | Verifies a JWS string s signature . |
10,977 | def construct ( key_data , algorithm = None ) : if not algorithm and isinstance ( key_data , dict ) : algorithm = key_data . get ( 'alg' , None ) if not algorithm : raise JWKError ( 'Unable to find a algorithm for key: %s' % key_data ) key_class = get_key ( algorithm ) if not key_class : raise JWKError ( 'Unable to find a algorithm for key: %s' % key_data ) return key_class ( key_data , algorithm ) | Construct a Key object for the given algorithm with the given key_data . |
10,978 | def train ( self , dataset ) : r X , Y = dataset . format_sklearn ( ) X = np . array ( X ) Y = np . array ( Y ) self . n_labels_ = np . shape ( Y ) [ 1 ] self . n_features_ = np . shape ( X ) [ 1 ] self . clfs_ = [ ] for i in range ( self . n_labels_ ) : if len ( np . unique ( Y [ : , i ] ) ) == 1 : clf = DummyClf ( ) else : clf = copy . deepcopy ( self . base_clf ) self . clfs_ . append ( clf ) Parallel ( n_jobs = self . n_jobs , backend = 'threading' ) ( delayed ( _fit_model ) ( self . clfs_ [ i ] , X , Y [ : , i ] ) for i in range ( self . n_labels_ ) ) return self | r Train model with given feature . |
10,979 | def predict ( self , X ) : r X = np . asarray ( X ) if self . clfs_ is None : raise ValueError ( "Train before prediction" ) if X . shape [ 1 ] != self . n_features_ : raise ValueError ( 'Given feature size does not match' ) pred = np . zeros ( ( X . shape [ 0 ] , self . n_labels_ ) ) for i in range ( self . n_labels_ ) : pred [ : , i ] = self . clfs_ [ i ] . predict ( X ) return pred . astype ( int ) | r Predict labels . |
10,980 | def predict_real ( self , X ) : r X = np . asarray ( X ) if self . clfs_ is None : raise ValueError ( "Train before prediction" ) if X . shape [ 1 ] != self . n_features_ : raise ValueError ( 'given feature size does not match' ) pred = np . zeros ( ( X . shape [ 0 ] , self . n_labels_ ) ) for i in range ( self . n_labels_ ) : pred [ : , i ] = self . clfs_ [ i ] . predict_real ( X ) [ : , 1 ] return pred | r Predict the probability of being 1 for each label . |
10,981 | def score ( self , testing_dataset , criterion = 'hamming' ) : X , Y = testing_dataset . format_sklearn ( ) if criterion == 'hamming' : return np . mean ( np . abs ( self . predict ( X ) - Y ) . mean ( axis = 1 ) ) elif criterion == 'f1' : Z = self . predict ( X ) Z = Z . astype ( int ) Y = Y . astype ( int ) up = 2 * np . sum ( Z & Y , axis = 1 ) . astype ( float ) down1 = np . sum ( Z , axis = 1 ) down2 = np . sum ( Y , axis = 1 ) down = ( down1 + down2 ) down [ down == 0 ] = 1. up [ down == 0 ] = 1. return np . mean ( up / down ) else : raise NotImplementedError ( "criterion '%s' not implemented" % criterion ) | Return the mean accuracy on the test dataset |
10,982 | def seed_random_state ( seed ) : if ( seed is None ) or ( isinstance ( seed , int ) ) : return np . random . RandomState ( seed ) elif isinstance ( seed , np . random . RandomState ) : return seed raise ValueError ( "%r can not be used to generate numpy.random.RandomState" " instance" % seed ) | Turn seed into np . random . RandomState instance |
10,983 | def calc_cost ( y , yhat , cost_matrix ) : return np . mean ( cost_matrix [ list ( y ) , list ( yhat ) ] ) | Calculate the cost with given cost matrix |
10,984 | def make_query ( self , return_score = False ) : dataset = self . dataset self . model . train ( dataset ) unlabeled_entry_ids , X_pool = zip ( * dataset . get_unlabeled_entries ( ) ) if isinstance ( self . model , ProbabilisticModel ) : dvalue = self . model . predict_proba ( X_pool ) elif isinstance ( self . model , ContinuousModel ) : dvalue = self . model . predict_real ( X_pool ) if self . method == 'lc' : score = - np . max ( dvalue , axis = 1 ) elif self . method == 'sm' : if np . shape ( dvalue ) [ 1 ] > 2 : dvalue = - ( np . partition ( - dvalue , 2 , axis = 1 ) [ : , : 2 ] ) score = - np . abs ( dvalue [ : , 0 ] - dvalue [ : , 1 ] ) elif self . method == 'entropy' : score = np . sum ( - dvalue * np . log ( dvalue ) , axis = 1 ) ask_id = np . argmax ( score ) if return_score : return unlabeled_entry_ids [ ask_id ] , list ( zip ( unlabeled_entry_ids , score ) ) else : return unlabeled_entry_ids [ ask_id ] | Return the index of the sample to be queried and labeled and selection score of each sample . Read - only . |
10,985 | def _vote_disagreement ( self , votes ) : ret = [ ] for candidate in votes : ret . append ( 0.0 ) lab_count = { } for lab in candidate : lab_count [ lab ] = lab_count . setdefault ( lab , 0 ) + 1 for lab in lab_count . keys ( ) : ret [ - 1 ] -= lab_count [ lab ] / self . n_students * math . log ( float ( lab_count [ lab ] ) / self . n_students ) return ret | Return the disagreement measurement of the given number of votes . It uses the vote vote to measure the disagreement . |
10,986 | def _labeled_uniform_sample ( self , sample_size ) : labeled_entries = self . dataset . get_labeled_entries ( ) samples = [ labeled_entries [ self . random_state_ . randint ( 0 , len ( labeled_entries ) ) ] for _ in range ( sample_size ) ] return Dataset ( * zip ( * samples ) ) | sample labeled entries uniformly |
10,987 | def calc_reward_fn ( self ) : model = copy . copy ( self . model ) model . train ( self . dataset ) reward = 0. for i in range ( len ( self . queried_hist_ ) ) : reward += self . W [ i ] * ( model . predict ( self . dataset . data [ self . queried_hist_ [ i ] ] [ 0 ] . reshape ( 1 , - 1 ) ) [ 0 ] == self . dataset . data [ self . queried_hist_ [ i ] ] [ 1 ] ) reward /= ( self . dataset . len_labeled ( ) + self . dataset . len_unlabeled ( ) ) reward /= self . T return reward | Calculate the reward value |
10,988 | def calc_query ( self ) : if self . query_dist is None : self . query_dist = self . exp4p_ . next ( - 1 , None , None ) else : self . query_dist = self . exp4p_ . next ( self . calc_reward_fn ( ) , self . queried_hist_ [ - 1 ] , self . dataset . data [ self . queried_hist_ [ - 1 ] ] [ 1 ] ) return | Calculate the sampling query distribution |
10,989 | def next ( self , reward , ask_id , lbl ) : if reward == - 1 : return next ( self . exp4p_gen ) else : return self . exp4p_gen . send ( ( reward , ask_id , lbl ) ) | Taking the label and the reward value of last question and returns the next question to ask . |
10,990 | def exp4p ( self ) : while True : query = np . zeros ( ( self . N , len ( self . unlabeled_invert_id_idx ) ) ) if self . uniform_sampler : query [ - 1 , : ] = 1. / len ( self . unlabeled_invert_id_idx ) for i , model in enumerate ( self . query_strategies_ ) : query [ i ] [ self . unlabeled_invert_id_idx [ model . make_query ( ) ] ] = 1 W = np . sum ( self . w ) p = ( 1 - self . K * self . pmin ) * self . w / W + self . pmin query_vector = np . dot ( p , query ) reward , ask_id , _ = yield query_vector ask_idx = self . unlabeled_invert_id_idx [ ask_id ] rhat = reward * query [ : , ask_idx ] / query_vector [ ask_idx ] yhat = rhat vhat = 1 / p self . w = self . w * np . exp ( self . pmin / 2 * ( yhat + vhat * np . sqrt ( np . log ( self . N / self . delta ) / self . K / self . T ) ) ) raise StopIteration | The generator which implements the main part of Exp4 . P . |
10,991 | def import_libsvm_sparse ( filename ) : from sklearn . datasets import load_svmlight_file X , y = load_svmlight_file ( filename ) return Dataset ( X . toarray ( ) . tolist ( ) , y . tolist ( ) ) | Imports dataset file in libsvm sparse format |
10,992 | def update ( self , entry_id , new_label ) : self . data [ entry_id ] = ( self . data [ entry_id ] [ 0 ] , new_label ) self . modified = True for callback in self . _update_callback : callback ( entry_id , new_label ) | Updates an entry with entry_id with the given label |
10,993 | def get_unlabeled_entries ( self ) : return [ ( idx , entry [ 0 ] ) for idx , entry in enumerate ( self . data ) if entry [ 1 ] is None ] | Returns list of unlabeled features along with their entry_ids |
10,994 | def labeled_uniform_sample ( self , sample_size , replace = True ) : if replace : samples = [ random . choice ( self . get_labeled_entries ( ) ) for _ in range ( sample_size ) ] else : samples = random . sample ( self . get_labeled_entries ( ) , sample_size ) return Dataset ( * zip ( * samples ) ) | Returns a Dataset object with labeled data only which is resampled uniformly with given sample size . Parameter replace decides whether sampling with replacement or not . |
10,995 | def push_token ( self , tok ) : "Push a token onto the stack popped by the get_token method" if self . debug >= 1 : print ( "shlex: pushing token " + repr ( tok ) ) self . pushback . appendleft ( tok ) | Push a token onto the stack popped by the get_token method |
10,996 | def _get_next_positional ( self ) : active_parser = self . active_parsers [ - 1 ] last_positional = self . visited_positionals [ - 1 ] all_positionals = active_parser . _get_positional_actions ( ) if not all_positionals : return None if active_parser == last_positional : return all_positionals [ 0 ] i = 0 for i in range ( len ( all_positionals ) ) : if all_positionals [ i ] == last_positional : break if i + 1 < len ( all_positionals ) : return all_positionals [ i + 1 ] return None | Get the next positional action if it exists . |
10,997 | def shellcode ( executables , use_defaults = True , shell = 'bash' , complete_arguments = None ) : if complete_arguments is None : complete_options = '-o nospace -o default' if use_defaults else '-o nospace' else : complete_options = " " . join ( complete_arguments ) if shell == 'bash' : quoted_executables = [ quote ( i ) for i in executables ] executables_list = " " . join ( quoted_executables ) code = bashcode % dict ( complete_opts = complete_options , executables = executables_list ) else : code = "" for executable in executables : code += tcshcode % dict ( executable = executable ) return code | Provide the shell code required to register a python executable for use with the argcomplete module . |
10,998 | def _send ( self , message ) : params = { 'V' : SMSPUBLI_API_VERSION , 'UN' : SMSPUBLI_USERNAME , 'PWD' : SMSPUBLI_PASSWORD , 'R' : SMSPUBLI_ROUTE , 'SA' : message . from_phone , 'DA' : ',' . join ( message . to ) , 'M' : message . body . encode ( 'latin-1' ) , 'DC' : SMSPUBLI_DC , 'DR' : SMSPUBLI_DR , 'UR' : message . from_phone } if SMSPUBLI_ALLOW_LONG_SMS : params [ 'LM' ] = '1' response = requests . post ( SMSPUBLI_API_URL , params ) if response . status_code != 200 : if not self . fail_silently : raise else : return False response_msg , response_code = response . content . split ( ':' ) if response_msg == 'OK' : try : if "," in response_code : codes = map ( int , response_code . split ( "," ) ) else : codes = [ int ( response_code ) ] for code in codes : if code == - 5 : pass elif code == - 3 : pass return True except ( ValueError , TypeError ) : if not self . fail_silently : raise return False return False | Private method for send one message . |
10,999 | def _get_filename ( self ) : if self . _fname is None : timestamp = datetime . datetime . now ( ) . strftime ( "%Y%m%d-%H%M%S" ) fname = "%s-%s.log" % ( timestamp , abs ( id ( self ) ) ) self . _fname = os . path . join ( self . file_path , fname ) return self . _fname | Return a unique file name . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.