idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
35,100 | def publish ( self , topic , payload = None , qos = 0 , retain = False ) : if topic is None or len ( topic ) == 0 : raise ValueError ( 'Invalid topic.' ) if qos < 0 or qos > 2 : raise ValueError ( 'Invalid QoS level.' ) if isinstance ( payload , str ) or isinstance ( payload , bytearray ) : local_payload = payload elif... | Publish a message on a topic . |
35,101 | def username_pw_set ( self , username , password = None ) : self . _username = username . encode ( 'utf-8' ) self . _password = password | Set a username and optionally a password for broker authentication . |
35,102 | def disconnect ( self ) : self . _state_mutex . acquire ( ) self . _state = mqtt_cs_disconnecting self . _state_mutex . release ( ) self . _backoffCore . stopStableConnectionTimer ( ) if self . _sock is None and self . _ssl is None : return MQTT_ERR_NO_CONN return self . _send_disconnect ( ) | Disconnect a connected client from the broker . |
35,103 | def subscribe ( self , topic , qos = 0 ) : topic_qos_list = None if isinstance ( topic , str ) : if qos < 0 or qos > 2 : raise ValueError ( 'Invalid QoS level.' ) if topic is None or len ( topic ) == 0 : raise ValueError ( 'Invalid topic.' ) topic_qos_list = [ ( topic . encode ( 'utf-8' ) , qos ) ] elif isinstance ( to... | Subscribe the client to one or more topics . |
35,104 | def unsubscribe ( self , topic ) : topic_list = None if topic is None : raise ValueError ( 'Invalid topic.' ) if isinstance ( topic , str ) : if len ( topic ) == 0 : raise ValueError ( 'Invalid topic.' ) topic_list = [ topic . encode ( 'utf-8' ) ] elif isinstance ( topic , list ) : topic_list = [ ] for t in topic : if ... | Unsubscribe the client from one or more topics . |
35,105 | def will_set ( self , topic , payload = None , qos = 0 , retain = False ) : if topic is None or len ( topic ) == 0 : raise ValueError ( 'Invalid topic.' ) if qos < 0 or qos > 2 : raise ValueError ( 'Invalid QoS level.' ) if isinstance ( payload , str ) : self . _will_payload = payload . encode ( 'utf-8' ) elif isinstan... | Set a Will to be sent by the broker in case the client disconnects unexpectedly . |
35,106 | def socket ( self ) : if self . _ssl : if self . _useSecuredWebsocket : return self . _ssl . getSSLSocket ( ) else : return self . _ssl else : return self . _sock | Return the socket or ssl object for this client . |
35,107 | def createproject ( ) : os . chdir ( build_dir ) if windows_build : command = 'cmake -A {} -DPYTHON_EXECUTABLE:FILEPATH="{}" ../..' . format ( "win32" if bitness == 32 else "x64" , sys . executable ) os . system ( command ) if bitness == 64 : for line in fileinput . input ( "_rhino3dm.vcxproj" , inplace = 1 ) : print (... | compile for the platform we are running on |
35,108 | def add_passthru ( self , prefix ) : if _has_unicode ( prefix ) : prefix = _clean_unicode ( prefix ) self . passthru_prefixes += ( prefix , ) | Register a URL prefix to passthru any non - matching mock requests to . |
35,109 | def _install ( archive_filename , install_args = ( ) ) : with archive_context ( archive_filename ) : log . warn ( 'Installing Setuptools' ) if not _python_cmd ( 'setup.py' , 'install' , * install_args ) : log . warn ( 'Something went wrong during the installation.' ) log . warn ( 'See the error message above.' ) return... | Install Setuptools . |
35,110 | def _build_egg ( egg , archive_filename , to_dir ) : with archive_context ( archive_filename ) : log . warn ( 'Building a Setuptools egg in %s' , to_dir ) _python_cmd ( 'setup.py' , '-q' , 'bdist_egg' , '--dist-dir' , to_dir ) log . warn ( egg ) if not os . path . exists ( egg ) : raise IOError ( 'Could not build the e... | Build Setuptools egg . |
35,111 | def _do_download ( version , download_base , to_dir , download_delay ) : py_desig = 'py{sys.version_info[0]}.{sys.version_info[1]}' . format ( sys = sys ) tp = 'setuptools-{version}-{py_desig}.egg' egg = os . path . join ( to_dir , tp . format ( ** locals ( ) ) ) if not os . path . exists ( egg ) : archive = download_s... | Download Setuptools . |
35,112 | def use_setuptools ( version = DEFAULT_VERSION , download_base = DEFAULT_URL , to_dir = DEFAULT_SAVE_DIR , download_delay = 15 ) : to_dir = os . path . abspath ( to_dir ) rep_modules = 'pkg_resources' , 'setuptools' imported = set ( sys . modules ) . intersection ( rep_modules ) try : import pkg_resources pkg_resources... | Ensure that a setuptools version is installed . |
35,113 | def _conflict_bail ( VC_err , version ) : conflict_tmpl = textwrap . dedent ( ) msg = conflict_tmpl . format ( ** locals ( ) ) sys . stderr . write ( msg ) sys . exit ( 2 ) | Setuptools was imported prior to invocation so it is unsafe to unload it . Bail out . |
35,114 | def download_file_insecure ( url , target ) : src = urlopen ( url ) try : data = src . read ( ) finally : src . close ( ) with open ( target , "wb" ) as dst : dst . write ( data ) | Use Python to download the file without connection authentication . |
35,115 | def _download_args ( options ) : return dict ( version = options . version , download_base = options . download_base , downloader_factory = options . downloader_factory , to_dir = options . to_dir , ) | Return args for download_setuptools function from cmdline args . |
35,116 | def main ( ) : options = _parse_args ( ) archive = download_setuptools ( ** _download_args ( options ) ) return _install ( archive , _build_install_args ( options ) ) | Install or upgrade setuptools and EasyInstall . |
35,117 | def registerContract ( self , contract ) : if contract . m_exchange == "" : return if self . getConId ( contract ) == 0 : contract_tuple = self . contract_to_tuple ( contract ) self . createContract ( contract_tuple ) | used for when callback receives a contract that isn t found in local database |
35,118 | def handleErrorEvents ( self , msg ) : if msg . errorCode is not None and msg . errorCode != - 1 and msg . errorCode not in dataTypes [ "BENIGN_ERROR_CODES" ] : log = True if msg . errorCode in dataTypes [ "DISCONNECT_ERROR_CODES" ] : log = False if msg . errorCode not in self . connection_tracking [ "errors" ] : self ... | logs error messages |
35,119 | def handleServerEvents ( self , msg ) : self . log . debug ( 'MSG %s' , msg ) self . handleConnectionState ( msg ) if msg . typeName == "error" : self . handleErrorEvents ( msg ) elif msg . typeName == dataTypes [ "MSG_CURRENT_TIME" ] : if self . time < msg . time : self . time = msg . time elif ( msg . typeName == dat... | dispatch msg to the right handler |
35,120 | def handleContractDetails ( self , msg , end = False ) : if end : self . _contract_details [ msg . reqId ] [ 'downloaded' ] = True self . contract_details [ msg . reqId ] = self . _contract_details [ msg . reqId ] del self . _contract_details [ msg . reqId ] if len ( self . contract_details [ msg . reqId ] [ "contracts... | handles contractDetails and contractDetailsEnd |
35,121 | def handlePosition ( self , msg ) : self . log_msg ( "position" , msg ) contract_tuple = self . contract_to_tuple ( msg . contract ) contractString = self . contractString ( contract_tuple ) self . registerContract ( msg . contract ) if msg . account not in self . _positions . keys ( ) : self . _positions [ msg . accou... | handle positions changes |
35,122 | def handlePortfolio ( self , msg ) : self . log_msg ( "portfolio" , msg ) contract_tuple = self . contract_to_tuple ( msg . contract ) contractString = self . contractString ( contract_tuple ) self . registerContract ( msg . contract ) if msg . accountName not in self . _portfolios . keys ( ) : self . _portfolios [ msg... | handle portfolio updates |
35,123 | def handleOrders ( self , msg ) : self . log_msg ( "order" , msg ) self . getServerTime ( ) time . sleep ( 0.001 ) duplicateMessage = False if msg . typeName == dataTypes [ "MSG_TYPE_OPEN_ORDER" ] : contractString = self . contractString ( msg . contract ) order_account = "" if msg . orderId in self . orders and self .... | handle order open & status |
35,124 | def createTriggerableTrailingStop ( self , symbol , quantity = 1 , triggerPrice = 0 , trailPercent = 100. , trailAmount = 0. , parentId = 0 , stopOrderId = None , ** kwargs ) : ticksize = self . contractDetails ( symbol ) [ "m_minTick" ] self . triggerableTrailingStops [ symbol ] = { "parentId" : parentId , "stopOrderI... | adds order to triggerable list |
35,125 | def registerTrailingStop ( self , tickerId , orderId = 0 , quantity = 1 , lastPrice = 0 , trailPercent = 100. , trailAmount = 0. , parentId = 0 , ** kwargs ) : ticksize = self . contractDetails ( tickerId ) [ "m_minTick" ] trailingStop = self . trailingStops [ tickerId ] = { "orderId" : orderId , "parentId" : parentId ... | adds trailing stop to monitor list |
35,126 | def modifyStopOrder ( self , orderId , parentId , newStop , quantity , transmit = True , account = None ) : if orderId in self . orders . keys ( ) : order = self . createStopOrder ( quantity = quantity , parentId = parentId , stop = newStop , trail = False , transmit = transmit , account = account ) return self . place... | modify stop order |
35,127 | def handleTrailingStops ( self , tickerId ) : if tickerId not in self . trailingStops . keys ( ) : return None trailingStop = self . trailingStops [ tickerId ] price = self . marketData [ tickerId ] [ 'last' ] [ 0 ] symbol = self . tickerSymbol ( tickerId ) if ( self . _positions [ symbol ] == 0 ) | ( self . orders [ t... | software - based trailing stop |
35,128 | def triggerTrailingStops ( self , tickerId ) : symbol = self . tickerSymbol ( tickerId ) price = self . marketData [ tickerId ] [ 'last' ] [ 0 ] if symbol in self . triggerableTrailingStops . keys ( ) : pendingOrder = self . triggerableTrailingStops [ symbol ] parentId = pendingOrder [ "parentId" ] stopOrderId = pendin... | trigger waiting trailing stops |
35,129 | def tickerId ( self , contract_identifier ) : symbol = contract_identifier if isinstance ( symbol , Contract ) : symbol = self . contractString ( symbol ) for tickerId in self . tickerIds : if symbol == self . tickerIds [ tickerId ] : return tickerId else : tickerId = len ( self . tickerIds ) self . tickerIds [ tickerI... | returns the tickerId for the symbol or sets one if it doesn t exits |
35,130 | def createTargetOrder ( self , quantity , parentId = 0 , target = 0. , orderType = None , transmit = True , group = None , tif = "DAY" , rth = False , account = None ) : order = self . createOrder ( quantity , price = target , transmit = transmit , orderType = dataTypes [ "ORDER_TYPE_LIMIT" ] if orderType == None else ... | Creates TARGET order |
35,131 | def createStopOrder ( self , quantity , parentId = 0 , stop = 0. , trail = None , transmit = True , group = None , stop_limit = False , rth = False , tif = "DAY" , account = None ) : if trail : if trail == "percent" : order = self . createOrder ( quantity , trailingPercent = stop , transmit = transmit , orderType = dat... | Creates STOP order |
35,132 | def createTrailingStopOrder ( self , contract , quantity , parentId = 0 , trailPercent = 100. , group = None , triggerPrice = None , account = None ) : if parentId not in self . orders : raise ValueError ( "Order #" + str ( parentId ) + " doesn't exist or wasn't submitted" ) order = self . createStopOrder ( quantity , ... | convert hard stop order to trailing stop order |
35,133 | def placeOrder ( self , contract , order , orderId = None , account = None ) : self . requestOrderIds ( ) useOrderId = self . orderId if orderId == None else orderId if account : order . m_account = account self . ibConn . placeOrder ( useOrderId , contract , order ) account_key = order . m_account self . orders [ useO... | Place order on IB TWS |
35,134 | def cancelOrder ( self , orderId ) : self . ibConn . cancelOrder ( orderId ) self . requestOrderIds ( ) return orderId | cancel order on IB TWS |
35,135 | def requestOpenOrders ( self , all_clients = False ) : if all_clients : self . ibConn . reqAllOpenOrders ( ) self . ibConn . reqOpenOrders ( ) | Request open orders - loads up orders that wasn t created using this session |
35,136 | def cancelHistoricalData ( self , contracts = None ) : if contracts == None : contracts = list ( self . contracts . values ( ) ) elif not isinstance ( contracts , list ) : contracts = [ contracts ] for contract in contracts : tickerId = self . tickerId ( self . contractString ( contract ) ) self . ibConn . cancelHistor... | cancel historical data stream |
35,137 | def getConId ( self , contract_identifier ) : details = self . contractDetails ( contract_identifier ) if len ( details [ "contracts" ] ) > 1 : return details [ "m_underConId" ] return details [ "m_summary" ] [ "m_conId" ] | Get contracts conId |
35,138 | def createComboContract ( self , symbol , legs , currency = "USD" , exchange = None ) : exchange = legs [ 0 ] . m_exchange if exchange is None else exchange contract_tuple = ( symbol , "BAG" , exchange , currency , "" , 0.0 , "" ) contract = self . createContract ( contract_tuple , comboLegs = legs ) return contract | Used for ComboLegs . Expecting list of legs |
35,139 | def order_to_dict ( order ) : default = Order ( ) return { field : val for field , val in vars ( order ) . items ( ) if val != getattr ( default , field , None ) } | Convert an IBPy Order object to a dict containing any non - default values . |
35,140 | def contract_to_dict ( contract ) : default = Contract ( ) return { field : val for field , val in vars ( contract ) . items ( ) if val != getattr ( default , field , None ) } | Convert an IBPy Contract object to a dict containing any non - default values . |
35,141 | def _get_utm_code ( zone , direction ) : dir_dict = { _Direction . NORTH : '6' , _Direction . SOUTH : '7' } return '{}{}{}' . format ( '32' , dir_dict [ direction ] , str ( zone ) . zfill ( 2 ) ) | Get UTM code given a zone and direction |
35,142 | def _get_utm_name_value_pair ( zone , direction = _Direction . NORTH ) : name = 'UTM_{}{}' . format ( zone , direction . value ) epsg = _get_utm_code ( zone , direction ) return name , epsg | Get name and code for UTM coordinates |
35,143 | def _crs_parser ( cls , value ) : parsed_value = value if isinstance ( parsed_value , int ) : parsed_value = str ( parsed_value ) if isinstance ( parsed_value , str ) : parsed_value = parsed_value . strip ( 'epsgEPSG: ' ) return super ( _BaseCRS , cls ) . __new__ ( cls , parsed_value ) | Parses user input for class CRS |
35,144 | def get_wfs_typename ( cls , data_source ) : is_eocloud = SHConfig ( ) . is_eocloud_ogc_url ( ) return { cls . SENTINEL2_L1C : 'S2.TILE' , cls . SENTINEL2_L2A : 'SEN4CAP_S2L2A.TILE' if is_eocloud else 'DSS2' , cls . SENTINEL1_IW : 'S1.TILE' if is_eocloud else 'DSS3' , cls . SENTINEL1_EW : 'S1_EW.TILE' if is_eocloud els... | Maps data source to string identifier for WFS |
35,145 | def is_uswest_source ( self ) : return not SHConfig ( ) . is_eocloud_ogc_url ( ) and self . value [ 0 ] in [ _Source . LANDSAT8 , _Source . MODIS , _Source . DEM ] | Checks if data source via Sentinel Hub services is available at US West server |
35,146 | def get_available_sources ( cls ) : if SHConfig ( ) . is_eocloud_ogc_url ( ) : return [ cls . SENTINEL2_L1C , cls . SENTINEL2_L2A , cls . SENTINEL2_L3B , cls . SENTINEL1_IW , cls . SENTINEL1_EW , cls . SENTINEL1_EW_SH , cls . SENTINEL3 , cls . SENTINEL5P , cls . LANDSAT5 , cls . LANDSAT7 , cls . LANDSAT8 , cls . LANDSA... | Returns which data sources are available for configured Sentinel Hub OGC URL |
35,147 | def get_utm_from_wgs84 ( lng , lat ) : _ , _ , zone , _ = utm . from_latlon ( lat , lng ) direction = 'N' if lat >= 0 else 'S' return CRS [ 'UTM_{}{}' . format ( str ( zone ) , direction ) ] | Convert from WGS84 to UTM coordinate system |
35,148 | def has_value ( cls , value ) : return any ( value . lower ( ) == item . value . lower ( ) for item in cls ) | Tests whether CustomUrlParam contains a constant defined with a string value |
35,149 | def canonical_extension ( fmt_ext ) : if MimeType . has_value ( fmt_ext ) : return fmt_ext try : return { 'tif' : MimeType . TIFF . value , 'jpeg' : MimeType . JPG . value , 'hdf5' : MimeType . HDF . value , 'h5' : MimeType . HDF . value } [ fmt_ext ] except KeyError : raise ValueError ( 'Data format .{} is not support... | Canonical extension of file format extension |
35,150 | def is_image_format ( self ) : return self in frozenset ( [ MimeType . TIFF , MimeType . TIFF_d8 , MimeType . TIFF_d16 , MimeType . TIFF_d32f , MimeType . PNG , MimeType . JP2 , MimeType . JPG ] ) | Checks whether file format is an image format |
35,151 | def is_tiff_format ( self ) : return self in frozenset ( [ MimeType . TIFF , MimeType . TIFF_d8 , MimeType . TIFF_d16 , MimeType . TIFF_d32f ] ) | Checks whether file format is a TIFF image format |
35,152 | def get_string ( self ) : if self in [ MimeType . TIFF_d8 , MimeType . TIFF_d16 , MimeType . TIFF_d32f ] : return 'image/{}' . format ( self . value ) if self is MimeType . JP2 : return 'image/jpeg2000' if self in [ MimeType . RAW , MimeType . REQUESTS_RESPONSE ] : return self . value return mimetypes . types_map [ '.'... | Get file format as string |
35,153 | def get_expected_max_value ( self ) : try : return { MimeType . TIFF : 65535 , MimeType . TIFF_d8 : 255 , MimeType . TIFF_d16 : 65535 , MimeType . TIFF_d32f : 1.0 , MimeType . PNG : 255 , MimeType . JPG : 255 , MimeType . JP2 : 10000 } [ self ] except IndexError : raise ValueError ( 'Type {} is not supported by this me... | Returns max value of image MimeType format and raises an error if it is not an image format |
35,154 | def _filter_dates ( dates , time_difference ) : LOGGER . debug ( "dates=%s" , dates ) if len ( dates ) <= 1 : return dates sorted_dates = sorted ( dates ) separate_dates = [ sorted_dates [ 0 ] ] for curr_date in sorted_dates [ 1 : ] : if curr_date - separate_dates [ - 1 ] > time_difference : separate_dates . append ( c... | Filters out dates within time_difference preserving only the oldest date . |
35,155 | def _sentinel1_product_check ( product_id , data_source ) : props = product_id . split ( '_' ) acquisition , resolution , polarisation = props [ 1 ] , props [ 2 ] [ 3 ] , props [ 3 ] [ 2 : 4 ] if acquisition in [ 'IW' , 'EW' ] and resolution in [ 'M' , 'H' ] and polarisation in [ 'DV' , 'DH' , 'SV' , 'SH' ] : return ac... | Checks if Sentinel - 1 product ID matches Sentinel - 1 DataSource configuration |
35,156 | def get_url ( self , request , * , date = None , size_x = None , size_y = None , geometry = None ) : url = self . get_base_url ( request ) authority = self . instance_id if hasattr ( self , 'instance_id' ) else request . theme params = self . _get_common_url_parameters ( request ) if request . service_type in ( Service... | Returns url to Sentinel Hub s OGC service for the product specified by the OgcRequest and date . |
35,157 | def get_base_url ( self , request ) : url = self . base_url + request . service_type . value if hasattr ( request , 'data_source' ) and request . data_source . is_uswest_source ( ) : url = 'https://services-uswest2.sentinel-hub.com/ogc/{}' . format ( request . service_type . value ) if hasattr ( request , 'data_source'... | Creates base url string . |
35,158 | def _get_common_url_parameters ( request ) : params = { 'SERVICE' : request . service_type . value } if hasattr ( request , 'maxcc' ) : params [ 'MAXCC' ] = 100.0 * request . maxcc if hasattr ( request , 'custom_url_params' ) and request . custom_url_params is not None : params = { ** params , ** { k . value : str ( v ... | Returns parameters common dictionary for WMS WCS and FIS request . |
35,159 | def _get_wms_wcs_url_parameters ( request , date ) : params = { 'BBOX' : str ( request . bbox . reverse ( ) ) if request . bbox . crs is CRS . WGS84 else str ( request . bbox ) , 'FORMAT' : MimeType . get_string ( request . image_format ) , 'CRS' : CRS . ogc_string ( request . bbox . crs ) , } if date is not None : sta... | Returns parameters common dictionary for WMS and WCS request . |
35,160 | def _get_fis_parameters ( request , geometry ) : date_interval = parse_time_interval ( request . time ) params = { 'CRS' : CRS . ogc_string ( geometry . crs ) , 'LAYER' : request . layer , 'RESOLUTION' : request . resolution , 'TIME' : '{}/{}' . format ( date_interval [ 0 ] , date_interval [ 1 ] ) } if not isinstance (... | Returns parameters dictionary for FIS request . |
35,161 | def get_filename ( request , date , size_x , size_y ) : filename = '_' . join ( [ str ( request . service_type . value ) , request . layer , str ( request . bbox . crs ) , str ( request . bbox ) . replace ( ',' , '_' ) , '' if date is None else date . strftime ( "%Y-%m-%dT%H-%M-%S" ) , '{}X{}' . format ( size_x , size_... | Get filename location |
35,162 | def filename_add_custom_url_params ( filename , request ) : if hasattr ( request , 'custom_url_params' ) and request . custom_url_params is not None : for param , value in sorted ( request . custom_url_params . items ( ) , key = lambda parameter_item : parameter_item [ 0 ] . value ) : filename = '_' . join ( [ filename... | Adds custom url parameters to filename string |
35,163 | def finalize_filename ( filename , file_format = None ) : for char in [ ' ' , '/' , '\\' , '|' , ';' , ':' , '\n' , '\t' ] : filename = filename . replace ( char , '' ) if file_format : suffix = str ( file_format . value ) if file_format . is_tiff_format ( ) and file_format is not MimeType . TIFF : suffix = str ( MimeT... | Replaces invalid characters in filename string adds image extension and reduces filename length |
35,164 | def get_dates ( self , request ) : if DataSource . is_timeless ( request . data_source ) : return [ None ] date_interval = parse_time_interval ( request . time ) LOGGER . debug ( 'date_interval=%s' , date_interval ) if request . wfs_iterator is None : self . wfs_iterator = WebFeatureService ( request . bbox , date_inte... | Get available Sentinel - 2 acquisitions at least time_difference apart |
35,165 | def get_image_dimensions ( request ) : if request . service_type is ServiceType . WCS or ( isinstance ( request . size_x , int ) and isinstance ( request . size_y , int ) ) : return request . size_x , request . size_y if not isinstance ( request . size_x , int ) and not isinstance ( request . size_y , int ) : raise Val... | Verifies or calculates image dimensions . |
35,166 | def _fetch_features ( self ) : if self . feature_offset is None : return main_url = '{}{}/{}?' . format ( self . base_url , ServiceType . WFS . value , self . instance_id ) params = { 'SERVICE' : ServiceType . WFS . value , 'REQUEST' : 'GetFeature' , 'TYPENAMES' : DataSource . get_wfs_typename ( self . data_source ) , ... | Collects data from WFS service |
35,167 | def get_dates ( self ) : return [ datetime . datetime . strptime ( '{}T{}' . format ( tile_info [ 'properties' ] [ 'date' ] , tile_info [ 'properties' ] [ 'time' ] . split ( '.' ) [ 0 ] ) , '%Y-%m-%dT%H:%M:%S' ) for tile_info in self ] | Returns a list of acquisition times from tile info data |
35,168 | def _parse_tile_url ( tile_url ) : props = tile_url . rsplit ( '/' , 7 ) return '' . join ( props [ 1 : 4 ] ) , '-' . join ( props [ 4 : 7 ] ) , int ( props [ 7 ] ) | Extracts tile name data and AWS index from tile URL |
35,169 | def get_dates_in_range ( start_date , end_date ) : start_dt = iso_to_datetime ( start_date ) end_dt = iso_to_datetime ( end_date ) num_days = int ( ( end_dt - start_dt ) . days ) return [ datetime_to_iso ( start_dt + datetime . timedelta ( i ) ) for i in range ( num_days + 1 ) ] | Get all dates within input start and end date in ISO 8601 format |
35,170 | def iso_to_datetime ( date ) : chunks = list ( map ( int , date . split ( 'T' ) [ 0 ] . split ( '-' ) ) ) return datetime . datetime ( chunks [ 0 ] , chunks [ 1 ] , chunks [ 2 ] ) | Convert ISO 8601 time format to datetime format |
35,171 | def datetime_to_iso ( date , only_date = True ) : if only_date : return date . isoformat ( ) . split ( 'T' ) [ 0 ] return date . isoformat ( ) | Convert datetime format to ISO 8601 time format |
35,172 | def aws ( product , tile , folder , redownload , info , entire , bands , l2a ) : band_list = None if bands is None else bands . split ( ',' ) data_source = DataSource . SENTINEL2_L2A if l2a else DataSource . SENTINEL2_L1C if info : if product is None : click . echo ( get_safe_format ( tile = tile , entire_product = ent... | Download Sentinel - 2 data from Sentinel - 2 on AWS to ESA SAFE format . Download uses multiple threads . |
35,173 | def _config_options ( func ) : for param in SHConfig ( ) . get_params ( ) [ - 1 : : - 1 ] : func = click . option ( '--{}' . format ( param ) , param , help = 'Set new values to configuration parameter "{}"' . format ( param ) ) ( func ) return func | A helper function which joins click . option functions of each parameter from config . json |
35,174 | def config ( show , reset , ** params ) : sh_config = SHConfig ( ) if reset : sh_config . reset ( ) for param , value in params . items ( ) : if value is not None : try : value = int ( value ) except ValueError : if value . lower ( ) == 'true' : value = True elif value . lower ( ) == 'false' : value = False if getattr ... | Inspect and configure parameters in your local sentinelhub configuration file |
35,175 | def download ( url , filename , redownload ) : data_folder , filename = filename . rsplit ( '/' , 1 ) download_list = [ DownloadRequest ( url = url , data_folder = data_folder , filename = filename , save_response = True , return_data = False ) ] download_data ( download_list , redownload = redownload ) | Download from custom created URL into custom created file path |
35,176 | def save ( self ) : is_changed = False for prop in self . _instance . CONFIG_PARAMS : if getattr ( self , prop ) != getattr ( self . _instance , prop ) : is_changed = True setattr ( self . _instance , prop , getattr ( self , prop ) ) if is_changed : self . _instance . save_configuration ( ) | Method that saves configuration parameter changes from instance of SHConfig class to global config class and to config . json file . |
35,177 | def _reset_param ( self , param ) : if param not in self . _instance . CONFIG_PARAMS : raise ValueError ( "Cannot reset unknown parameter '{}'" . format ( param ) ) setattr ( self , param , self . _instance . CONFIG_PARAMS [ param ] ) | Resets a single parameter |
35,178 | def get_config_dict ( self ) : return OrderedDict ( ( prop , getattr ( self , prop ) ) for prop in self . _instance . CONFIG_PARAMS ) | Get a dictionary representation of SHConfig class |
35,179 | def bbox_to_resolution ( bbox , width , height ) : utm_bbox = to_utm_bbox ( bbox ) east1 , north1 = utm_bbox . lower_left east2 , north2 = utm_bbox . upper_right return abs ( east2 - east1 ) / width , abs ( north2 - north1 ) / height | Calculates pixel resolution in meters for a given bbox of a given width and height . |
35,180 | def get_image_dimension ( bbox , width = None , height = None ) : utm_bbox = to_utm_bbox ( bbox ) east1 , north1 = utm_bbox . lower_left east2 , north2 = utm_bbox . upper_right if isinstance ( width , int ) : return round ( width * abs ( north2 - north1 ) / abs ( east2 - east1 ) ) return round ( height * abs ( east2 - ... | Given bounding box and one of the parameters width or height it will return the other parameter that will best fit the bounding box dimensions |
35,181 | def to_utm_bbox ( bbox ) : if CRS . is_utm ( bbox . crs ) : return bbox lng , lat = bbox . middle utm_crs = get_utm_crs ( lng , lat , source_crs = bbox . crs ) return bbox . transform ( utm_crs ) | Transform bbox into UTM CRS |
35,182 | def get_utm_bbox ( img_bbox , transform ) : east1 , north1 = pixel_to_utm ( img_bbox [ 0 ] , img_bbox [ 1 ] , transform ) east2 , north2 = pixel_to_utm ( img_bbox [ 2 ] , img_bbox [ 3 ] , transform ) return [ east1 , north1 , east2 , north2 ] | Get UTM coordinates given a bounding box in pixels and a transform |
35,183 | def wgs84_to_utm ( lng , lat , utm_crs = None ) : if utm_crs is None : utm_crs = get_utm_crs ( lng , lat ) return transform_point ( ( lng , lat ) , CRS . WGS84 , utm_crs ) | Convert WGS84 coordinates to UTM . If UTM CRS is not set it will be calculated automatically . |
35,184 | def utm_to_pixel ( east , north , transform , truncate = True ) : column = ( east - transform [ 0 ] ) / transform [ 1 ] row = ( north - transform [ 3 ] ) / transform [ 5 ] if truncate : return int ( row + ERR ) , int ( column + ERR ) return row , column | Convert UTM coordinate to image coordinate given a transform |
35,185 | def pixel_to_utm ( row , column , transform ) : east = transform [ 0 ] + column * transform [ 1 ] north = transform [ 3 ] + row * transform [ 5 ] return east , north | Convert pixel coordinate to UTM coordinate given a transform |
35,186 | def wgs84_to_pixel ( lng , lat , transform , utm_epsg = None , truncate = True ) : east , north = wgs84_to_utm ( lng , lat , utm_epsg ) row , column = utm_to_pixel ( east , north , transform , truncate = truncate ) return row , column | Convert WGS84 coordinates to pixel image coordinates given transform and UTM CRS . If no CRS is given it will be calculated it automatically . |
35,187 | def transform_point ( point , source_crs , target_crs ) : if source_crs == target_crs : return point old_x , old_y = point new_x , new_y = pyproj . transform ( CRS . projection ( source_crs ) , CRS . projection ( target_crs ) , old_x , old_y ) return new_x , new_y | Maps point form src_crs to tgt_crs |
35,188 | def transform_bbox ( bbox , target_crs ) : warnings . warn ( "This function is deprecated, use BBox.transform method instead" , DeprecationWarning , stacklevel = 2 ) return bbox . transform ( target_crs ) | Maps bbox from current crs to target_crs |
35,189 | def get_safe_format ( product_id = None , tile = None , entire_product = False , bands = None , data_source = DataSource . SENTINEL2_L1C ) : entire_product = entire_product and product_id is None if tile is not None : safe_tile = SafeTile ( tile_name = tile [ 0 ] , time = tile [ 1 ] , bands = bands , data_source = data... | Returns . SAFE format structure in form of nested dictionaries . Either product_id or tile must be specified . |
35,190 | def download_safe_format ( product_id = None , tile = None , folder = '.' , redownload = False , entire_product = False , bands = None , data_source = DataSource . SENTINEL2_L1C ) : entire_product = entire_product and product_id is None if tile is not None : safe_request = AwsTileRequest ( tile = tile [ 0 ] , time = ti... | Downloads . SAFE format structure in form of nested dictionaries . Either product_id or tile must be specified . |
35,191 | def save_data ( self , * , data_filter = None , redownload = False , max_threads = None , raise_download_errors = False ) : self . _preprocess_request ( True , False ) self . _execute_data_download ( data_filter , redownload , max_threads , raise_download_errors ) | Saves data to disk . If redownload = True then the data is redownloaded using max_threads workers . |
35,192 | def _execute_data_download ( self , data_filter , redownload , max_threads , raise_download_errors ) : is_repeating_filter = False if data_filter is None : filtered_download_list = self . download_list elif isinstance ( data_filter , ( list , tuple ) ) : try : filtered_download_list = [ self . download_list [ index ] f... | Calls download module and executes the download process |
35,193 | def _filter_repeating_items ( download_list ) : unique_requests_map = { } mapping_list = [ ] unique_download_list = [ ] for download_request in download_list : if download_request not in unique_requests_map : unique_requests_map [ download_request ] = len ( unique_download_list ) unique_download_list . append ( downloa... | Because of data_filter some requests in download list might be the same . In order not to download them again this method will reduce the list of requests . It will also return a mapping list which can be used to reconstruct the previous list of download requests . |
35,194 | def _preprocess_request ( self , save_data , return_data ) : if not self . is_valid_request ( ) : raise ValueError ( 'Cannot obtain data because request is invalid' ) if save_data and self . data_folder is None : raise ValueError ( 'Request parameter `data_folder` is not specified. ' 'In order to save data please set `... | Prepares requests for download and creates empty folders |
35,195 | def _add_saved_data ( self , data_list , data_filter , raise_download_errors ) : filtered_download_list = self . download_list if data_filter is None else [ self . download_list [ index ] for index in data_filter ] for i , request in enumerate ( filtered_download_list ) : if request . return_data and data_list [ i ] is... | Adds already saved data that was not redownloaded to the requested data list . |
35,196 | def create_request ( self , reset_gpd_iterator = False ) : if reset_gpd_iterator : self . gpd_iterator = None gpd_service = GeopediaImageService ( ) self . download_list = gpd_service . get_request ( self ) self . gpd_iterator = gpd_service . get_gpd_iterator ( ) | Set a list of download requests |
35,197 | def provide_session ( self , start_new = False ) : if self . is_global : self . _session_info = self . _global_session_info self . _session_start = self . _global_session_start if self . _session_info is None or start_new or datetime . datetime . now ( ) > self . _session_start + self . SESSION_DURATION : self . _start... | Makes sure that session is still valid and provides session info |
35,198 | def _start_new_session ( self ) : self . _session_start = datetime . datetime . now ( ) session_id = self . _parse_session_id ( self . _session_info ) if self . _session_info else '' session_url = '{}data/v1/session/create?locale=en&sid={}' . format ( self . base_url , session_id ) self . _session_info = get_json ( ses... | Starts a new session and calculates when the new session will end . If username and password are provided it will also make login . |
35,199 | def _make_login ( self ) : login_url = '{}data/v1/session/login?user={}&pass={}&sid={}' . format ( self . base_url , self . username , self . password , self . _parse_session_id ( self . _session_info ) ) self . _session_info = get_json ( login_url ) | Private method that makes login |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.