idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
237,000 | def ned2geodetic ( n : float , e : float , d : float , lat0 : float , lon0 : float , h0 : float , ell : Ellipsoid = None , deg : bool = True ) -> Tuple [ float , float , float ] : x , y , z = enu2ecef ( e , n , - d , lat0 , lon0 , h0 , ell , deg = deg ) return ecef2geodetic ( x , y , z , ell , deg = deg ) | Converts North East Down to target latitude longitude altitude |
237,001 | def ned2ecef ( n : float , e : float , d : float , lat0 : float , lon0 : float , h0 : float , ell : Ellipsoid = None , deg : bool = True ) -> Tuple [ float , float , float ] : return enu2ecef ( e , n , - d , lat0 , lon0 , h0 , ell , deg = deg ) | North East Down to target ECEF coordinates |
237,002 | def ecef2ned ( x : float , y : float , z : float , lat0 : float , lon0 : float , h0 : float , ell : Ellipsoid = None , deg : bool = True ) -> Tuple [ float , float , float ] : e , n , u = ecef2enu ( x , y , z , lat0 , lon0 , h0 , ell , deg = deg ) return n , e , - u | Convert ECEF x y z to North East Down |
237,003 | def ecef2nedv ( x : float , y : float , z : float , lat0 : float , lon0 : float , deg : bool = True ) -> Tuple [ float , float , float ] : e , n , u = ecef2enuv ( x , y , z , lat0 , lon0 , deg = deg ) return n , e , - u | for VECTOR between two points |
237,004 | def azel2radec ( az_deg : float , el_deg : float , lat_deg : float , lon_deg : float , time : datetime ) -> Tuple [ float , float ] : az = atleast_1d ( az_deg ) el = atleast_1d ( el_deg ) lat = atleast_1d ( lat_deg ) lon = atleast_1d ( lon_deg ) if az . shape != el . shape : raise ValueError ( 'az and el must be same s... | converts azimuth elevation to right ascension declination |
237,005 | def radec2azel ( ra_deg : float , dec_deg : float , lat_deg : float , lon_deg : float , time : datetime ) -> Tuple [ float , float ] : ra = atleast_1d ( ra_deg ) dec = atleast_1d ( dec_deg ) lat = atleast_1d ( lat_deg ) lon = atleast_1d ( lon_deg ) if ra . shape != dec . shape : raise ValueError ( 'az and el must be sa... | converts right ascension declination to azimuth elevation |
237,006 | def ecef2aer ( x : float , y : float , z : float , lat0 : float , lon0 : float , h0 : float , ell = None , deg : bool = True ) -> Tuple [ float , float , float ] : xEast , yNorth , zUp = ecef2enu ( x , y , z , lat0 , lon0 , h0 , ell , deg = deg ) return enu2aer ( xEast , yNorth , zUp , deg = deg ) | gives azimuth elevation and slant range from an Observer to a Point with ECEF coordinates . |
237,007 | def geodetic2aer ( lat : float , lon : float , h : float , lat0 : float , lon0 : float , h0 : float , ell = None , deg : bool = True ) -> Tuple [ float , float , float ] : e , n , u = geodetic2enu ( lat , lon , h , lat0 , lon0 , h0 , ell , deg = deg ) return enu2aer ( e , n , u , deg = deg ) | gives azimuth elevation and slant range from an Observer to a Point with geodetic coordinates . |
237,008 | def aer2geodetic ( az : float , el : float , srange : float , lat0 : float , lon0 : float , h0 : float , ell = None , deg : bool = True ) -> Tuple [ float , float , float ] : x , y , z = aer2ecef ( az , el , srange , lat0 , lon0 , h0 , ell = ell , deg = deg ) return ecef2geodetic ( x , y , z , ell = ell , deg = deg ) | gives geodetic coordinates of a point with az el range from an observer at lat0 lon0 h0 |
237,009 | def eci2aer ( eci : Tuple [ float , float , float ] , lat0 : float , lon0 : float , h0 : float , t : datetime , useastropy : bool = True ) -> Tuple [ float , float , float ] : ecef = np . atleast_2d ( eci2ecef ( eci , t , useastropy ) ) return ecef2aer ( ecef [ : , 0 ] , ecef [ : , 1 ] , ecef [ : , 2 ] , lat0 , lon0 , ... | takes ECI coordinates of point and gives az el slant range from Observer |
237,010 | def aer2eci ( az : float , el : float , srange : float , lat0 : float , lon0 : float , h0 : float , t : datetime , ell = None , deg : bool = True , useastropy : bool = True ) -> np . ndarray : x , y , z = aer2ecef ( az , el , srange , lat0 , lon0 , h0 , ell , deg ) return ecef2eci ( np . column_stack ( ( x , y , z ) ) ... | gives ECI of a point from an observer at az el slant range |
237,011 | def aer2ecef ( az : float , el : float , srange : float , lat0 : float , lon0 : float , alt0 : float , ell = None , deg : bool = True ) -> Tuple [ float , float , float ] : x0 , y0 , z0 = geodetic2ecef ( lat0 , lon0 , alt0 , ell , deg = deg ) e1 , n1 , u1 = aer2enu ( az , el , srange , deg = deg ) dx , dy , dz = enu2uv... | converts target azimuth elevation range from observer at lat0 lon0 alt0 to ECEF coordinates . |
237,012 | def isometric ( lat : float , ell : Ellipsoid = None , deg : bool = True ) : if ell is None : ell = Ellipsoid ( ) f = ell . f if deg is True : lat = np . deg2rad ( lat ) e2 = f * ( 2 - f ) e = np . sqrt ( e2 ) x = e * np . sin ( lat ) y = ( 1 - x ) / ( 1 + x ) z = np . pi / 4 + lat / 2 isolat = np . log ( np . tan ( z ... | computes isometric latitude of a point on an ellipsoid |
237,013 | def loxodrome_inverse ( lat1 : float , lon1 : float , lat2 : float , lon2 : float , ell : Ellipsoid = None , deg : bool = True ) : if ell is None : ell = Ellipsoid ( ) if deg is True : lat1 , lon1 , lat2 , lon2 = np . radians ( [ lat1 , lon1 , lat2 , lon2 ] ) isolat1 = isometric ( lat1 , deg = False , ell = ell ) isola... | computes the arc length and azimuth of the loxodrome between two points on the surface of the reference ellipsoid |
237,014 | def eci2ecef ( eci : np . ndarray , time : datetime , useastropy : bool = True ) -> np . ndarray : useastropy = useastropy and Time if useastropy : gst = Time ( time ) . sidereal_time ( 'apparent' , 'greenwich' ) . radian else : gst = datetime2sidereal ( time , 0. ) gst = np . atleast_1d ( gst ) assert gst . ndim == 1 ... | Observer = > Point ECI = > ECEF |
237,015 | def describe_vpc ( record ) : account_id = record [ 'account' ] vpc_name = cloudwatch . filter_request_parameters ( 'vpcName' , record ) vpc_id = cloudwatch . filter_request_parameters ( 'vpcId' , record ) try : if vpc_id and vpc_name : return describe_vpcs ( account_number = account_id , assume_role = HISTORICAL_ROLE ... | Attempts to describe vpc ids . |
237,016 | def create_delete_model ( record ) : data = cloudwatch . get_historical_base_info ( record ) vpc_id = cloudwatch . filter_request_parameters ( 'vpcId' , record ) arn = get_arn ( vpc_id , cloudwatch . get_region ( record ) , record [ 'account' ] ) LOG . debug ( F'[-] Deleting Dynamodb Records. Hash Key: {arn}' ) data . ... | Create a vpc model from a record . |
237,017 | def handler ( event , context ) : records = deserialize_records ( event [ 'Records' ] ) update_records , delete_records = group_records_by_type ( records , UPDATE_EVENTS ) capture_delete_records ( delete_records ) update_records = [ e for e in update_records if not e [ 'detail' ] . get ( 'errorCode' ) ] LOG . debug ( f... | Historical vpc event collector . This collector is responsible for processing Cloudwatch events and polling events . |
237,018 | def default_diff ( latest_config , current_config ) : pop_no_diff_fields ( latest_config , current_config ) diff = DeepDiff ( latest_config , current_config , ignore_order = True ) return diff | Determine if two revisions have actually changed . |
237,019 | def pop_no_diff_fields ( latest_config , current_config ) : for field in [ 'userIdentity' , 'principalId' , 'userAgent' , 'sourceIpAddress' , 'requestParameters' , 'eventName' ] : latest_config . pop ( field , None ) current_config . pop ( field , None ) | Pops off fields that should not be included in the diff . |
237,020 | def modify_record ( durable_model , current_revision , arn , event_time , diff_func ) : items = list ( durable_model . query ( arn , ( durable_model . eventTime <= event_time ) , scan_index_forward = False , limit = 1 , consistent_read = True ) ) if items : latest_revision = items [ 0 ] latest_config = latest_revision ... | Handles a DynamoDB MODIFY event type . |
237,021 | def deserialize_current_record_to_durable_model ( record , current_model , durable_model ) : if record . get ( EVENT_TOO_BIG_FLAG ) : record = get_full_current_object ( record [ 'dynamodb' ] [ 'Keys' ] [ 'arn' ] [ 'S' ] , current_model ) if not record : return None serialized = record . _serialize ( ) record = { 'dynam... | Utility function that will take a dynamo event record and turn it into the proper pynamo object . |
237,022 | def deserialize_current_record_to_current_model ( record , current_model ) : if record . get ( EVENT_TOO_BIG_FLAG ) : return get_full_current_object ( record [ 'dynamodb' ] [ 'Keys' ] [ 'arn' ] [ 'S' ] , current_model ) new_image = remove_global_dynamo_specific_fields ( record [ 'dynamodb' ] [ 'NewImage' ] ) data = { }... | Utility function that will take a Dynamo event record and turn it into the proper Current Dynamo object . |
237,023 | def deserialize_durable_record_to_durable_model ( record , durable_model ) : if record . get ( EVENT_TOO_BIG_FLAG ) : return get_full_durable_object ( record [ 'dynamodb' ] [ 'Keys' ] [ 'arn' ] [ 'S' ] , record [ 'dynamodb' ] [ 'NewImage' ] [ 'eventTime' ] [ 'S' ] , durable_model ) new_image = remove_global_dynamo_spec... | Utility function that will take a Dynamo event record and turn it into the proper Durable Dynamo object . |
237,024 | def deserialize_durable_record_to_current_model ( record , current_model ) : if record . get ( EVENT_TOO_BIG_FLAG ) : return get_full_current_object ( record [ 'dynamodb' ] [ 'Keys' ] [ 'arn' ] [ 'S' ] , current_model ) new_image = remove_durable_specific_fields ( record [ 'dynamodb' ] [ 'NewImage' ] ) data = { } for i... | Utility function that will take a Durable Dynamo event record and turn it into the proper Current Dynamo object . |
237,025 | def serialize_me ( self , account_id , region , next_token = None ) : payload = { 'account_id' : account_id , 'region' : region } if next_token : payload [ 'next_token' ] = next_token return self . dumps ( payload ) . data | Dumps the proper JSON for the schema . |
237,026 | def serialize_me ( self , arn , event_time , tech , item = None ) : payload = { 'arn' : arn , 'event_time' : event_time , 'tech' : tech } if item : payload [ 'item' ] = item else : payload [ 'event_too_big' ] = True return self . dumps ( payload ) . data . replace ( '<empty>' , '' ) | Dumps the proper JSON for the schema . If the event is too big then don t include the item . |
237,027 | def fix_decimals ( obj ) : if isinstance ( obj , list ) : for i in range ( len ( obj ) ) : obj [ i ] = fix_decimals ( obj [ i ] ) return obj elif isinstance ( obj , dict ) : for key , value in obj . items ( ) : obj [ key ] = fix_decimals ( value ) return obj elif isinstance ( obj , decimal . Decimal ) : if obj % 1 == 0... | Removes the stupid Decimals |
237,028 | def serialize ( self , value ) : if isinstance ( value , str ) : return value return value . strftime ( DATETIME_FORMAT ) | Takes a datetime object and returns a string |
237,029 | def pull_tag_dict ( data ) : tags = data . pop ( 'Tags' , { } ) or { } if tags : proper_tags = { } for tag in tags : proper_tags [ tag [ 'Key' ] ] = tag [ 'Value' ] tags = proper_tags return tags | This will pull out a list of Tag Name - Value objects and return it as a dictionary . |
237,030 | def create_delete_model ( record ) : arn = f"arn:aws:s3:::{cloudwatch.filter_request_parameters('bucketName', record)}" LOG . debug ( f'[-] Deleting Dynamodb Records. Hash Key: {arn}' ) data = { 'arn' : arn , 'principalId' : cloudwatch . get_principal ( record ) , 'userIdentity' : cloudwatch . get_user_identity ( recor... | Create an S3 model from a record . |
237,031 | def process_delete_records ( delete_records ) : for rec in delete_records : arn = f"arn:aws:s3:::{rec['detail']['requestParameters']['bucketName']}" try : LOG . debug ( f'[-] Deleting bucket: {arn}' ) model = create_delete_model ( rec ) model . save ( condition = ( CurrentS3Model . eventTime <= rec [ 'detail' ] [ 'even... | Process the requests for S3 bucket deletions |
237,032 | def process_update_records ( update_records ) : events = sorted ( update_records , key = lambda x : x [ 'account' ] ) for account_id , events in groupby ( events , lambda x : x [ 'account' ] ) : events = list ( events ) buckets = { } for event in events : bucket_event = buckets . get ( event [ 'detail' ] [ 'requestPara... | Process the requests for S3 bucket update requests |
237,033 | def handler ( event , context ) : records = deserialize_records ( event [ 'Records' ] ) update_records , delete_records = group_records_by_type ( records , UPDATE_EVENTS ) LOG . debug ( '[@] Processing update records...' ) process_update_records ( update_records ) LOG . debug ( '[@] Completed processing of update recor... | Historical S3 event collector . |
237,034 | def get_historical_accounts ( ) : if os . environ . get ( 'SWAG_BUCKET' , False ) : swag_opts = { 'swag.type' : 's3' , 'swag.bucket_name' : os . environ [ 'SWAG_BUCKET' ] , 'swag.data_file' : os . environ . get ( 'SWAG_DATA_FILE' , 'accounts.json' ) , 'swag.region' : os . environ . get ( 'SWAG_REGION' , 'us-east-1' ) }... | Fetches valid accounts from SWAG if enabled or a list accounts . |
237,035 | def poller_processor_handler ( event , context ) : LOG . debug ( '[@] Running Poller...' ) queue_url = get_queue_url ( os . environ . get ( 'POLLER_QUEUE_NAME' , 'HistoricalS3Poller' ) ) records = deserialize_records ( event [ 'Records' ] ) for record in records : try : all_buckets = list_buckets ( account_number = rec... | Historical S3 Poller Processor . |
237,036 | def detect_global_table_updates ( record ) : if record [ 'eventName' ] == 'MODIFY' : old_image = remove_global_dynamo_specific_fields ( record [ 'dynamodb' ] [ 'OldImage' ] ) new_image = remove_global_dynamo_specific_fields ( record [ 'dynamodb' ] [ 'NewImage' ] ) if json . dumps ( old_image , sort_keys = True ) == jso... | This will detect DDB Global Table updates that are not relevant to application data updates . These need to be skipped over as they are pure noise . |
237,037 | def handler ( event , context ) : records = deserialize_records ( event [ 'Records' ] ) for record in records : process_dynamodb_differ_record ( record , CurrentS3Model , DurableS3Model ) | Historical S3 event differ . |
237,038 | def new ( ) : dir_path = os . path . dirname ( os . path . realpath ( __file__ ) ) cookiecutter ( os . path . join ( dir_path , 'historical-cookiecutter/' ) ) | Creates a new historical technology . |
237,039 | def poller_tasker_handler ( event , context ) : LOG . debug ( '[@] Running Poller Tasker...' ) queue_url = get_queue_url ( os . environ . get ( 'POLLER_TASKER_QUEUE_NAME' , 'HistoricalVPCPollerTasker' ) ) poller_task_schema = HistoricalPollerTaskEventModel ( ) events = [ ] for account in get_historical_accounts ( ) : f... | Historical VPC Poller Tasker . |
237,040 | def chunks ( event_list , chunk_size ) : for i in range ( 0 , len ( event_list ) , chunk_size ) : yield event_list [ i : i + chunk_size ] | Yield successive n - sized chunks from the event list . |
237,041 | def get_queue_url ( queue_name ) : client = boto3 . client ( "sqs" , CURRENT_REGION ) queue = client . get_queue_url ( QueueName = queue_name ) return queue [ "QueueUrl" ] | Get the URL of the SQS queue to send events to . |
237,042 | def produce_events ( events , queue_url , batch_size = 10 , randomize_delay = 0 ) : client = boto3 . client ( 'sqs' , region_name = CURRENT_REGION ) for chunk in chunks ( events , batch_size ) : records = [ make_sqs_record ( event , delay_seconds = get_random_delay ( randomize_delay ) ) for event in chunk ] client . se... | Efficiently sends events to the SQS event queue . |
237,043 | def describe_group ( record , region ) : account_id = record [ 'account' ] group_name = cloudwatch . filter_request_parameters ( 'groupName' , record ) vpc_id = cloudwatch . filter_request_parameters ( 'vpcId' , record ) group_id = cloudwatch . filter_request_parameters ( 'groupId' , record , look_in_response = True ) ... | Attempts to describe group ids . |
237,044 | def create_delete_model ( record ) : data = cloudwatch . get_historical_base_info ( record ) group_id = cloudwatch . filter_request_parameters ( 'groupId' , record ) arn = get_arn ( group_id , cloudwatch . get_region ( record ) , record [ 'account' ] ) LOG . debug ( f'[-] Deleting Dynamodb Records. Hash Key: {arn}' ) d... | Create a security group model from a record . |
237,045 | def extract_log_level_from_environment ( k , default ) : return LOG_LEVELS . get ( os . environ . get ( k ) ) or int ( os . environ . get ( k , default ) ) | Gets the log level from the environment variable . |
237,046 | def filter_request_parameters ( field_name , msg , look_in_response = False ) : val = msg [ 'detail' ] . get ( field_name , None ) try : if not val : val = msg [ 'detail' ] . get ( 'requestParameters' , { } ) . get ( field_name , None ) if not val and look_in_response : if msg [ 'detail' ] . get ( 'responseElements' ) ... | From an event extract the field name from the message . Different API calls put this information in different places so check a few places . |
237,047 | def get_historical_base_info ( event ) : data = { 'principalId' : get_principal ( event ) , 'userIdentity' : get_user_identity ( event ) , 'accountId' : event [ 'account' ] , 'userAgent' : event [ 'detail' ] . get ( 'userAgent' ) , 'sourceIpAddress' : event [ 'detail' ] . get ( 'sourceIPAddress' ) , 'requestParameters'... | Gets the base details from the CloudWatch Event . |
237,048 | def splitText ( text ) : segments = [ ] remaining_text = __class__ . cleanSpaces ( text ) while len ( remaining_text ) > __class__ . MAX_SEGMENT_SIZE : cur_text = remaining_text [ : __class__ . MAX_SEGMENT_SIZE ] split_idx = __class__ . findLastCharIndexMatching ( cur_text , lambda x : unicodedata . category ( x ) in (... | Split text into sub segments of size not bigger than MAX_SEGMENT_SIZE . |
237,049 | def play ( self , sox_effects = ( ) ) : preloader_threads = [ ] if self . text != "-" : segments = list ( self ) preloader_threads = [ PreloaderThread ( name = "PreloaderThread-%u" % ( i ) ) for i in range ( PRELOADER_THREAD_COUNT ) ] for preloader_thread in preloader_threads : preloader_thread . segments = segments pr... | Play a speech . |
237,050 | def isInCache ( self ) : url = self . buildUrl ( cache_friendly = True ) return url in __class__ . cache | Return True if audio data for this segment is present in cache False otherwise . |
237,051 | def preLoad ( self ) : logging . getLogger ( ) . debug ( "Preloading segment '%s'" % ( self ) ) real_url = self . buildUrl ( ) cache_url = self . buildUrl ( cache_friendly = True ) audio_data = self . download ( real_url ) assert ( audio_data ) __class__ . cache [ cache_url ] = audio_data | Store audio data in cache for fast playback . |
237,052 | def getAudioData ( self ) : with self . preload_mutex : cache_url = self . buildUrl ( cache_friendly = True ) if cache_url in __class__ . cache : logging . getLogger ( ) . debug ( "Got data for URL '%s' from cache" % ( cache_url ) ) audio_data = __class__ . cache [ cache_url ] assert ( audio_data ) else : real_url = se... | Fetch the audio data . |
237,053 | def play ( self , sox_effects = ( ) ) : audio_data = self . getAudioData ( ) logging . getLogger ( ) . info ( "Playing speech segment (%s): '%s'" % ( self . lang , self ) ) cmd = [ "sox" , "-q" , "-t" , "mp3" , "-" ] if sys . platform . startswith ( "win32" ) : cmd . extend ( ( "-t" , "waveaudio" ) ) cmd . extend ( ( "... | Play the segment . |
237,054 | def buildUrl ( self , cache_friendly = False ) : params = collections . OrderedDict ( ) params [ "client" ] = "tw-ob" params [ "ie" ] = "UTF-8" params [ "idx" ] = str ( self . segment_num ) if self . segment_count is not None : params [ "total" ] = str ( self . segment_count ) params [ "textlen" ] = str ( len ( self . ... | Construct the URL to get the sound from Goggle API . |
237,055 | def download ( self , url ) : logging . getLogger ( ) . debug ( "Downloading '%s'..." % ( url ) ) response = __class__ . session . get ( url , headers = { "User-Agent" : "Mozilla/5.0" } , timeout = 3.1 ) response . raise_for_status ( ) return response . content | Download a sound file . |
237,056 | def to_param_dict ( self ) : param_dict = { } for index , dictionary in enumerate ( self . value ) : for key , value in dictionary . items ( ) : param_name = '{param_name}[{index}][{key}]' . format ( param_name = self . param_name , index = index , key = key ) param_dict [ param_name ] = value return OrderedDict ( sort... | Sorts to ensure Order is consistent for Testing |
237,057 | def _get ( cls , kwarg_name ) : param_classes = cls . _discover_params ( ) try : param_class = param_classes [ kwarg_name ] except KeyError : raise ValueError ( 'invalid param keyword {}' . format ( kwarg_name ) ) else : return param_class | Returns a Param Class Instance by its kwarg or param name |
237,058 | def _process_params ( self , params ) : new_params = OrderedDict ( ) for param_name , param_value in sorted ( params . items ( ) ) : param_value = params [ param_name ] ParamClass = AirtableParams . _get ( param_name ) new_params . update ( ParamClass ( param_value ) . to_param_dict ( ) ) return new_params | Process params names or values as needed using filters |
237,059 | def _batch_request ( self , func , iterable ) : responses = [ ] for item in iterable : responses . append ( func ( item ) ) time . sleep ( self . API_LIMIT ) return responses | Internal Function to limit batch calls to API limit |
237,060 | def _add_members ( self , catmembers ) : members = [ x for x in catmembers if x [ 'ns' ] == 0 ] subcats = [ x for x in catmembers if x [ 'ns' ] == 14 ] if 'members' in self . data : self . data [ 'members' ] . extend ( members ) else : self . data . update ( { 'members' : members } ) if subcats : if 'subcategories' in ... | Adds category members and subcategories to data |
237,061 | def _query ( self , action , qobj ) : title = self . params . get ( 'title' ) pageid = self . params . get ( 'pageid' ) if action == 'random' : return qobj . random ( namespace = 14 ) elif action == 'category' : return qobj . category ( title , pageid , self . _continue_params ( ) ) | Form query to enumerate category |
237,062 | def _set_data ( self , action ) : data = self . _load_response ( action ) self . _handle_continuations ( data , 'category' ) if action == 'category' : members = data . get ( 'query' ) . get ( 'categorymembers' ) if members : self . _add_members ( members ) if action == 'random' : rand = data [ 'query' ] [ 'random' ] [ ... | Set category member data from API response |
237,063 | def _sitelist ( self , matrix ) : _list = [ ] for item in matrix : sites = [ ] if isinstance ( matrix [ item ] , list ) : sites = matrix [ item ] elif isinstance ( matrix [ item ] , dict ) : sites = matrix [ item ] [ 'site' ] for site in sites : if len ( site . keys ( ) ) > 4 : continue domain = self . params . get ( '... | Returns a list of sites from a SiteMatrix optionally filtered by domain param |
237,064 | def handle_wikidata_errors ( data , query ) : entities = data . get ( 'entities' ) if not entities : raise LookupError ( query ) elif '-1' in entities : raise LookupError ( query ) else : item = list ( entities . values ( ) ) [ 0 ] if 'missing' in item : errmsg = "wikidata item %s has been deleted" % item [ 'id' ] rais... | Raises LookupError if wikidata error found |
237,065 | def prettyprint ( datastr ) : maxwidth = WPToolsQuery . MAXWIDTH rpad = WPToolsQuery . RPAD extent = maxwidth - ( rpad + 2 ) for line in datastr : if len ( line ) >= maxwidth : line = line [ : extent ] + '...' utils . stderr ( line ) | Print page data strings to stderr |
237,066 | def _continue_params ( self ) : if not self . data . get ( 'continue' ) : return params = [ ] for item in self . data [ 'continue' ] : params . append ( "&%s=%s" % ( item , self . data [ 'continue' ] [ item ] ) ) return '' . join ( params ) | Returns query string fragment continue parameters |
237,067 | def _handle_continuations ( self , response , cache_key ) : rcontinue = response . get ( 'continue' ) listen = [ 'blcontinue' , 'cmcontinue' , 'plcontinue' ] cparams = { } if rcontinue : for flag in listen : if rcontinue . get ( flag ) : cparams [ flag ] = rcontinue . get ( flag ) if cparams : self . data [ 'continue' ... | Select continue params and clear cache or last continue params |
237,068 | def _get ( self , action , show , proxy , timeout ) : silent = self . flags [ 'silent' ] if action in self . cache : if action != 'imageinfo' and action != 'labels' : utils . stderr ( "+ %s results in cache" % action , silent ) return else : self . cache [ action ] = { } if self . flags . get ( 'skip' ) and action in s... | make HTTP request and cache response |
237,069 | def _load_response ( self , action ) : _query = self . cache [ action ] [ 'query' ] . replace ( '&format=json' , '' ) response = self . cache [ action ] [ 'response' ] if not response : raise ValueError ( "Empty response: %s" % self . params ) try : data = utils . json_loads ( response ) except ValueError : raise Value... | returns API reponse from cache or raises ValueError |
237,070 | def _request ( self , proxy , timeout ) : return request . WPToolsRequest ( self . flags [ 'silent' ] , self . flags [ 'verbose' ] , proxy , timeout ) | Returns WPToolsRequest object |
237,071 | def info ( self , action = None ) : if action in self . cache : return self . cache [ action ] [ 'info' ] return self . cache . keys ( ) or None | returns cached request info for given action or list of cached actions |
237,072 | def show ( self ) : if not self . data : return if self . data . get ( 'continue' ) : return ptitle = self . params . get ( 'title' ) dtitle = self . data . get ( 'title' ) pageid = self . params . get ( 'pageid' ) seed = dtitle or ptitle or pageid if utils . is_text ( seed ) : seed = seed . replace ( '_' , ' ' ) prett... | Pretty - print instance data |
237,073 | def _get_entity_prop ( self , entity , prop ) : variant = self . params . get ( 'variant' ) lang = self . params . get ( 'lang' ) if entity . get ( prop ) : ent = entity [ prop ] try : return ent [ variant or lang ] . get ( 'value' ) except AttributeError : return ent . get ( 'value' ) | returns Wikidata entity property value |
237,074 | def _marshal_claims ( self , query_claims ) : claims = reduce_claims ( query_claims ) self . data [ 'claims' ] = claims entities = set ( ) for eid in claims : if self . user_labels : if eid in self . user_labels or eid == 'P31' : entities . add ( eid ) else : continue else : entities . add ( eid ) for val in claims [ e... | set Wikidata entities from query claims |
237,075 | def _pop_entities ( self , limit = 50 ) : pop = self . data [ 'entities' ] [ : limit ] del self . data [ 'entities' ] [ : limit ] return pop | returns up to limit entities and pops them off the list |
237,076 | def _query ( self , action , qobj ) : if action == 'labels' : return qobj . labels ( self . _pop_entities ( ) ) elif action == 'wikidata' : return qobj . wikidata ( self . params . get ( 'title' ) , self . params . get ( 'wikibase' ) ) | returns wikidata query string |
237,077 | def _set_title ( self , item ) : title = None lang = self . params [ 'lang' ] label = self . data [ 'label' ] if item . get ( 'sitelinks' ) : for link in item [ 'sitelinks' ] : if link == "%swiki" % lang : title = item [ 'sitelinks' ] [ link ] [ 'title' ] self . data [ 'title' ] = title . replace ( ' ' , '_' ) if not s... | attempt to set title from wikidata |
237,078 | def _update_images ( self ) : wd_images = self . data [ 'claims' ] . get ( 'P18' ) if wd_images : if not isinstance ( wd_images , list ) : wd_images = [ wd_images ] if 'image' not in self . data : self . data [ 'image' ] = [ ] for img_file in wd_images : self . data [ 'image' ] . append ( { 'file' : img_file , 'kind' :... | add images from Wikidata |
237,079 | def _update_wikidata ( self ) : claims = self . data [ 'claims' ] for ent in claims : plabel = self . data [ 'labels' ] . get ( ent ) if plabel : plabel = "%s (%s)" % ( plabel , ent ) claim = [ ] for item in claims [ ent ] : ilabel = item if utils . is_text ( item ) and re . match ( r'^Q\d+$' , item ) : ilabel = self .... | set wikidata from claims and labels |
237,080 | def _html_image ( page ) : source = _image ( page ) if not source : return alt = page . data . get ( 'label' ) or page . data . get ( 'title' ) img = "<img src=\"%s\"" % source img += " alt=\"%s\" title=\"%s\" " % ( alt , alt ) img += "align=\"right\" width=\"240\">" return img | returns HTML img tag |
237,081 | def _html_title ( page ) : link = "<a href=\"%s\">%s</a>" % ( page . data . get ( 'url' ) , page . data . get ( 'title' ) ) desc = page . data . get ( 'description' ) if desc : link += "—<i>%s</i>" % desc else : link += "—<i>description</i>" if link : return "<p>%s</p>" % link | returns Wiki - linked HTML title |
237,082 | def _page_html ( page ) : out = [ ] out . append ( _html_title ( page ) ) out . append ( _html_image ( page ) ) out . append ( page . data . get ( 'extract' ) ) return "\n" . join ( [ x for x in out if x ] ) | returns assembled HTML output |
237,083 | def _page_text ( page , nowrap = False ) : title = page . data [ 'title' ] title = "%s\n%s" % ( title , "=" * len ( title ) ) desc = page . data . get ( 'description' ) if desc : desc = "_%s_" % desc img = _text_image ( page ) pars = page . data . get ( 'extext' ) if pars : pars = re . sub ( r'[ ]+\*[ ]+' , '* ' , pars... | returns assembled text output |
237,084 | def _safe_exit ( start , output ) : try : sys . stdout . write ( output ) sys . stdout . flush ( ) except TypeError : sys . stdout . write ( str ( output , 'utf-8' ) ) sys . stdout . flush ( ) except IOError : pass seconds = time . time ( ) - start print ( "\n\n%5.3f seconds" % ( seconds ) , file = sys . stderr ) | exit without breaking pipes |
237,085 | def _text_image ( page ) : img = None alt = page . data . get ( 'label' ) or page . data . get ( 'title' ) source = _image ( page ) if source : img = "" % ( alt , source ) return img | returns text image URL |
237,086 | def get ( args ) : html = args . H lang = args . l nowrap = args . n query = args . q silent = args . s title = args . t verbose = args . v wiki = args . w if query : qobj = WPToolsQuery ( lang = lang , wiki = wiki ) if title : return qobj . query ( title ) return qobj . random ( ) page = wptools . page ( title , lang ... | invoke wptools and assemble selected output |
237,087 | def main ( args ) : start = time . time ( ) output = get ( args ) _safe_exit ( start , output ) | invoke wptools and exit safely |
237,088 | def __insert_image_info ( self , title , _from , info ) : for img in self . data [ 'image' ] : if 'url' not in img : if title == img [ 'file' ] : img . update ( info ) elif _from == img [ 'file' ] : img . update ( info ) | Insert API image INFO into matching image dict |
237,089 | def __pull_image_info ( self , title , imageinfo , normalized ) : for info in imageinfo : info . update ( { 'title' : title } ) _from = None for norm in normalized : if title == norm [ 'to' ] : _from = norm [ 'from' ] info [ 'metadata' ] = { } extmetadata = info . get ( 'extmetadata' ) if extmetadata : info [ 'metadata... | Pull image INFO from API response and insert |
237,090 | def _extend_data ( self , datapoint , new_data ) : if new_data : try : self . data [ datapoint ] . extend ( new_data ) except KeyError : self . data [ datapoint ] = new_data | extend or assign new data to datapoint |
237,091 | def _missing_imageinfo ( self ) : if 'image' not in self . data : return missing = [ ] for img in self . data [ 'image' ] : if 'url' not in img : missing . append ( img [ 'file' ] ) return list ( set ( missing ) ) | returns list of image filenames that are missing info |
237,092 | def _query ( self , action , qobj ) : title = self . params . get ( 'title' ) pageid = self . params . get ( 'pageid' ) wikibase = self . params . get ( 'wikibase' ) qstr = None if action == 'random' : qstr = qobj . random ( ) elif action == 'query' : qstr = qobj . query ( title , pageid , self . _continue_params ( ) )... | returns WPToolsQuery string |
237,093 | def _set_data ( self , action ) : if 'query' in action : self . _set_query_data ( action ) elif action == 'imageinfo' : self . _set_imageinfo_data ( ) elif action == 'parse' : self . _set_parse_data ( ) elif action == 'random' : self . _set_random_data ( ) elif action == 'labels' : self . _set_labels ( ) elif action ==... | marshals response data into page data |
237,094 | def _set_parse_image ( self , infobox ) : image = infobox . get ( 'image' ) cover = infobox . get ( 'Cover' ) or infobox . get ( 'cover' ) if image or cover : if 'image' not in self . data : self . data [ 'image' ] = [ ] if image and utils . isfilename ( image ) : self . data [ 'image' ] . append ( { 'kind' : 'parse-im... | set image data from action = parse response |
237,095 | def _set_query_data_fast_1 ( self , page ) : self . data [ 'pageid' ] = page . get ( 'pageid' ) assessments = page . get ( 'pageassessments' ) if assessments : self . data [ 'assessments' ] = assessments extract = page . get ( 'extract' ) if extract : self . data [ 'extract' ] = extract extext = html2text . html2text (... | set less expensive action = query response data PART 1 |
237,096 | def _set_query_data_fast_2 ( self , page ) : self . data [ 'pageid' ] = page . get ( 'pageid' ) redirects = page . get ( 'redirects' ) if redirects : self . data [ 'redirects' ] = redirects terms = page . get ( 'terms' ) if terms : if terms . get ( 'alias' ) : self . data [ 'aliases' ] = terms [ 'alias' ] if terms . ge... | set less expensive action = query response data PART 2 |
237,097 | def _set_query_data_slow ( self , page ) : categories = page . get ( 'categories' ) if categories : self . data [ 'categories' ] = [ x [ 'title' ] for x in categories ] if page . get ( 'contributors' ) : contributors = page . get ( 'contributors' ) or 0 anoncontributors = page . get ( 'anoncontributors' ) or 0 if isins... | set more expensive action = query response data |
237,098 | def _set_query_image ( self , page ) : pageimage = page . get ( 'pageimage' ) thumbnail = page . get ( 'thumbnail' ) if pageimage or thumbnail : if 'image' not in self . data : self . data [ 'image' ] = [ ] if pageimage : self . data [ 'image' ] . append ( { 'kind' : 'query-pageimage' , 'file' : pageimage } ) if thumbn... | set image data from action = query response |
237,099 | def _set_random_data ( self ) : rdata = self . _load_response ( 'random' ) rdata = rdata [ 'query' ] [ 'random' ] [ 0 ] pageid = rdata . get ( 'id' ) title = rdata . get ( 'title' ) self . data . update ( { 'pageid' : pageid , 'title' : title } ) | sets page data from random request |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.