INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Delete an object from the redis table
def delete_entry(self, key): """Delete an object from the redis table""" pipe = self.client.pipeline() pipe.srem(self.keys_container, key) pipe.delete(key) pipe.execute()
Cleanup all the expired keys
def cleanup(self): """Cleanup all the expired keys""" keys = self.client.smembers(self.keys_container) for key in keys: entry = self.client.get(key) if entry: entry = pickle.loads(entry) if self._is_expired(entry, self.timeout): ...
Delete all entries from the cache
def flush(self): """Delete all entries from the cache""" keys = self.client.smembers(self.keys_container) for key in keys: self.delete_entry(key)
:reference: https://dev.twitter.com/docs/api/1.1/get/related_results/show/%3id.format :allowed_param:'id'
def related_results(self): """ :reference: https://dev.twitter.com/docs/api/1.1/get/related_results/show/%3id.format :allowed_param:'id' """ return bind_api( api=self, path='/related_results/show/{id}.json', payload_type='relation', payload_list=Tr...
:reference: https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload :allowed_param:
def media_upload(self, filename, *args, **kwargs): """ :reference: https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload :allowed_param: """ f = kwargs.pop('file', None) headers, post_data = API._pack_image(filename, 4883, form_field='media'...
:reference: https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id :allowed_param:'id'
def destroy_status(self): """ :reference: https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id :allowed_param:'id' """ return bind_api( api=self, path='/statuses/destroy/{id}.json', method='POST', ...
Perform bulk look up of users from user ID or screen_name
def lookup_users(self, user_ids=None, screen_names=None, include_entities=None, tweet_mode=None): """ Perform bulk look up of users from user ID or screen_name """ post_data = {} if include_entities is not None: include_entities = 'true' if include_entities else 'false' p...
:reference: https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup allowed_param='user_id', 'screen_name', 'include_entities', 'tweet_mode'
def _lookup_users(self): """ :reference: https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup allowed_param='user_id', 'screen_name', 'include_entities', 'tweet_mode' """ return bind_api( api=self, pat...
:reference: https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search :allowed_param:'q', 'count', 'page'
def search_users(self): """ :reference: https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search :allowed_param:'q', 'count', 'page' """ return bind_api( api=self, path='/users/search.json', pa...
:reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-message :allowed_param:'id', 'full_text'
def get_direct_message(self): """ :reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-message :allowed_param:'id', 'full_text' """ return bind_api( api=self, path='/direct_messages/show/{id}.json', ...
Perform bulk look up of friendships from user ID or screenname
def lookup_friendships(self, user_ids=None, screen_names=None): """ Perform bulk look up of friendships from user ID or screenname """ return self._lookup_friendships(list_to_csv(user_ids), list_to_csv(screen_names))
:reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-settings :allowed_param:'sleep_time_enabled', 'start_sleep_time', 'end_sleep_time', 'time_zone', 'trend_location_woeid', 'allow_contributor_request', 'lang'
def set_settings(self): """ :reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-settings :allowed_param:'sleep_time_enabled', 'start_sleep_time', 'end_sleep_time', 'time_zone', 'trend_location_woeid', 'allow_...
:reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials :allowed_param:'include_entities', 'skip_status', 'include_email'
def verify_credentials(self, **kargs): """ :reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials :allowed_param:'include_entities', 'skip_status', 'include_email' """ try: return bind_api(...
:reference: https://developer.twitter.com/en/docs/developer-utilities/rate-limit-status/api-reference/get-application-rate_limit_status :allowed_param:'resources'
def rate_limit_status(self): """ :reference: https://developer.twitter.com/en/docs/developer-utilities/rate-limit-status/api-reference/get-application-rate_limit_status :allowed_param:'resources' """ return bind_api( api=self, path='/application/rate_limit_sta...
:reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image :allowed_param:'include_entities', 'skip_status'
def update_profile_image(self, filename, file_=None): """ :reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image :allowed_param:'include_entities', 'skip_status' """ headers, post_data = API._pack_i...
:reference: https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-favorites-list :allowed_param:'screen_name', 'user_id', 'max_id', 'count', 'since_id', 'max_id'
def favorites(self): """ :reference: https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-favorites-list :allowed_param:'screen_name', 'user_id', 'max_id', 'count', 'since_id', 'max_id' """ return bind_api( api=self, path='/favorites/...
:reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
def saved_searches(self): """ :reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list """ return bind_api( api=self, path='/saved_searches/list.json', payload_type='saved_search', payload_list=...
Perform bulk add of list members from user ID or screenname
def add_list_members(self, screen_name=None, user_id=None, slug=None, list_id=None, owner_id=None, owner_screen_name=None): """ Perform bulk add of list members from user ID or screenname """ return self._add_list_members(list_to_csv(screen_name), ...
Perform bulk remove of list members from user ID or screenname
def remove_list_members(self, screen_name=None, user_id=None, slug=None, list_id=None, owner_id=None, owner_screen_name=None): """ Perform bulk remove of list members from user ID or screenname """ return self._remove_list_members(list_to_csv(screen_name), ...
Called when raw data is received from connection. Override this method if you wish to manually handle the stream data. Return False to stop stream and close connection.
def on_data(self, raw_data): """Called when raw data is received from connection. Override this method if you wish to manually handle the stream data. Return False to stop stream and close connection. """ data = json.loads(raw_data) if 'in_reply_to_status_id' in data: ...
Read the data stream until a given separator is found (default \n) :param sep: Separator to read until. Must by of the bytes type (str in python 2, bytes in python 3) :return: The str of the data read until sep
def read_line(self, sep=six.b('\n')): """Read the data stream until a given separator is found (default \n) :param sep: Separator to read until. Must by of the bytes type (str in python 2, bytes in python 3) :return: The str of the data read until sep """ start = 0 ...
Return iterator for items in each page
def items(self, limit=0): """Return iterator for items in each page""" i = ItemIterator(self.iterator) i.limit = limit return i
Fetch a set of items with IDs less than current set.
def next(self): """Fetch a set of items with IDs less than current set.""" if self.limit and self.limit == self.num_tweets: raise StopIteration if self.index >= len(self.results) - 1: data = self.method(max_id=self.max_id, parser=RawParser(), *self.args, **self.kargs) ...
Fetch a set of items with IDs greater than current set.
def prev(self): """Fetch a set of items with IDs greater than current set.""" if self.limit and self.limit == self.num_tweets: raise StopIteration self.index -= 1 if self.index < 0: # There's no way to fetch a set of tweets directly 'above' the # curr...
Add a bid to the cache :param bid: :return:
def add_bid(self, bid): """Add a bid to the cache :param bid: :return: """ self._bids[bid[0]] = float(bid[1]) if bid[1] == "0.00000000": del self._bids[bid[0]]
Add an ask to the cache :param ask: :return:
def add_ask(self, ask): """Add an ask to the cache :param ask: :return: """ self._asks[ask[0]] = float(ask[1]) if ask[1] == "0.00000000": del self._asks[ask[0]]
Sort bids or asks by price
def sort_depth(vals, reverse=False): """Sort bids or asks by price """ lst = [[float(price), quantity] for price, quantity in vals.items()] lst = sorted(lst, key=itemgetter(0), reverse=reverse) return lst
Initialise the depth cache calling REST endpoint :return:
def _init_cache(self): """Initialise the depth cache calling REST endpoint :return: """ self._last_update_id = None self._depth_message_buffer = [] res = self._client.get_order_book(symbol=self._symbol, limit=self._limit) # process bid and asks from the order b...
Start the depth cache socket :return:
def _start_socket(self): """Start the depth cache socket :return: """ if self._bm is None: self._bm = BinanceSocketManager(self._client) self._conn_key = self._bm.start_depth_socket(self._symbol, self._depth_event) if not self._bm.is_alive(): sel...
Handle a depth event :param msg: :return:
def _depth_event(self, msg): """Handle a depth event :param msg: :return: """ if 'e' in msg and msg['e'] == 'error': # close the socket self.close() # notify the user by returning a None value if self._callback: ...
Process a depth event message. :param msg: Depth event message. :return:
def _process_depth_message(self, msg, buffer=False): """Process a depth event message. :param msg: Depth event message. :return: """ if buffer and msg['u'] <= self._last_update_id: # ignore any updates before the initial update id return elif ms...
Close the open socket for this manager :return:
def close(self, close_socket=False): """Close the open socket for this manager :return: """ self._bm.stop_socket(self._conn_key) if close_socket: self._bm.close() time.sleep(1) self._depth_cache = None
Convert UTC date to milliseconds If using offset strings add "UTC" to date string e.g. "now UTC", "11 hours ago UTC" See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/ :param date_str: date in readable format, i.e. "January 01, 2018", "11 hours ago UTC", "now UTC" :type date_s...
def date_to_milliseconds(date_str): """Convert UTC date to milliseconds If using offset strings add "UTC" to date string e.g. "now UTC", "11 hours ago UTC" See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/ :param date_str: date in readable format, i.e. "January 01, 2018", "11...
Convert a Binance interval string to milliseconds :param interval: Binance interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w :type interval: str :return: None if unit not one of m, h, d or w None if string not in correct format int value of interval in mi...
def interval_to_milliseconds(interval): """Convert a Binance interval string to milliseconds :param interval: Binance interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w :type interval: str :return: None if unit not one of m, h, d or w None if string not in corr...
Get Historical Klines from Binance See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/ If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC" :param symbol: Name of symbol pair e.g BNBBTC :type symbol: str :p...
def get_historical_klines(symbol, interval, start_str, end_str=None): """Get Historical Klines from Binance See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/ If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC" ...
Convert params to list with signature as last element :param data: :return:
def _order_params(self, data): """Convert params to list with signature as last element :param data: :return: """ has_signature = False params = [] for key, value in data.items(): if key == 'signature': has_signature = True ...
Internal helper for handling API responses from the Binance server. Raises the appropriate exceptions when necessary; otherwise, returns the response.
def _handle_response(self, response): """Internal helper for handling API responses from the Binance server. Raises the appropriate exceptions when necessary; otherwise, returns the response. """ if not str(response.status_code).startswith('2'): raise BinanceAPIExcept...
Return information about a symbol :param symbol: required e.g BNBBTC :type symbol: str :returns: Dict if found, None if not .. code-block:: python { "symbol": "ETHBTC", "status": "TRADING", "baseAsset": "ETH", ...
def get_symbol_info(self, symbol): """Return information about a symbol :param symbol: required e.g BNBBTC :type symbol: str :returns: Dict if found, None if not .. code-block:: python { "symbol": "ETHBTC", "status": "TRADING", ...
Iterate over aggregate trade data from (start_time or last_id) to the end of the history so far. If start_time is specified, start with the first trade after start_time. Meant to initialise a local cache of trade data. If last_id is specified, start with the trade after it. This is mea...
def aggregate_trade_iter(self, symbol, start_str=None, last_id=None): """Iterate over aggregate trade data from (start_time or last_id) to the end of the history so far. If start_time is specified, start with the first trade after start_time. Meant to initialise a local cache of trade d...
Get earliest valid open timestamp from Binance :param symbol: Name of symbol pair e.g BNBBTC :type symbol: str :param interval: Binance Kline interval :type interval: str :return: first valid timestamp
def _get_earliest_valid_timestamp(self, symbol, interval): """Get earliest valid open timestamp from Binance :param symbol: Name of symbol pair e.g BNBBTC :type symbol: str :param interval: Binance Kline interval :type interval: str :return: first valid timestamp ...
Get Historical Klines from Binance See dateparser docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/ If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC" :param symbol: Name of symbol pair e.g BNBBTC :type s...
def get_historical_klines(self, symbol, interval, start_str, end_str=None, limit=500): """Get Historical Klines from Binance See dateparser docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/ If using offset strings for dates ad...
Latest price for a symbol or symbols. https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#24hr-ticker-price-change-statistics :param symbol: :type symbol: str :returns: API response .. code-block:: python { "symbo...
def get_symbol_ticker(self, **params): """Latest price for a symbol or symbols. https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#24hr-ticker-price-change-statistics :param symbol: :type symbol: str :returns: API response .. code-bl...
Latest price for a symbol or symbols. https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#symbol-order-book-ticker :param symbol: :type symbol: str :returns: API response .. code-block:: python { "symbol": "LTCBTC...
def get_orderbook_ticker(self, **params): """Latest price for a symbol or symbols. https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#symbol-order-book-ticker :param symbol: :type symbol: str :returns: API response .. code-block:: py...
Send in a new limit order Any order with an icebergQty MUST have timeInForce set to GTC. :param symbol: required :type symbol: str :param side: required :type side: str :param quantity: required :type quantity: decimal :param price: required :typ...
def order_limit(self, timeInForce=TIME_IN_FORCE_GTC, **params): """Send in a new limit order Any order with an icebergQty MUST have timeInForce set to GTC. :param symbol: required :type symbol: str :param side: required :type side: str :param quantity: required ...
Send in a new limit buy order Any order with an icebergQty MUST have timeInForce set to GTC. :param symbol: required :type symbol: str :param quantity: required :type quantity: decimal :param price: required :type price: str :param timeInForce: default G...
def order_limit_buy(self, timeInForce=TIME_IN_FORCE_GTC, **params): """Send in a new limit buy order Any order with an icebergQty MUST have timeInForce set to GTC. :param symbol: required :type symbol: str :param quantity: required :type quantity: decimal :param...
Send in a new limit sell order :param symbol: required :type symbol: str :param quantity: required :type quantity: decimal :param price: required :type price: str :param timeInForce: default Good till cancelled :type timeInForce: str :param newCli...
def order_limit_sell(self, timeInForce=TIME_IN_FORCE_GTC, **params): """Send in a new limit sell order :param symbol: required :type symbol: str :param quantity: required :type quantity: decimal :param price: required :type price: str :param timeInForce: ...
Send in a new market order :param symbol: required :type symbol: str :param side: required :type side: str :param quantity: required :type quantity: decimal :param newClientOrderId: A unique id for the order. Automatically generated if not sent. :type new...
def order_market(self, **params): """Send in a new market order :param symbol: required :type symbol: str :param side: required :type side: str :param quantity: required :type quantity: decimal :param newClientOrderId: A unique id for the order. Automatic...
Send in a new market buy order :param symbol: required :type symbol: str :param quantity: required :type quantity: decimal :param newClientOrderId: A unique id for the order. Automatically generated if not sent. :type newClientOrderId: str :param newOrderRespType...
def order_market_buy(self, **params): """Send in a new market buy order :param symbol: required :type symbol: str :param quantity: required :type quantity: decimal :param newClientOrderId: A unique id for the order. Automatically generated if not sent. :type newC...
Send in a new market sell order :param symbol: required :type symbol: str :param quantity: required :type quantity: decimal :param newClientOrderId: A unique id for the order. Automatically generated if not sent. :type newClientOrderId: str :param newOrderRespTyp...
def order_market_sell(self, **params): """Send in a new market sell order :param symbol: required :type symbol: str :param quantity: required :type quantity: decimal :param newClientOrderId: A unique id for the order. Automatically generated if not sent. :type ne...
Get current asset balance. https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#account-information-user_data :param asset: required :type asset: str :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int ...
def get_asset_balance(self, asset, **params): """Get current asset balance. https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#account-information-user_data :param asset: required :type asset: str :param recvWindow: the number of milliseconds ...
Get account status detail. https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#account-status-user_data :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int :returns: API response .. code-block:: python...
def get_account_status(self, **params): """Get account status detail. https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#account-status-user_data :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int :re...
Get log of small amounts exchanged for BNB. https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#dustlog-user_data :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int :returns: API response .. code-bloc...
def get_dust_log(self, **params): """Get log of small amounts exchanged for BNB. https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#dustlog-user_data :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int ...
Get trade fee. https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#trade-fee-user_data :param symbol: optional :type symbol: str :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int :returns: API...
def get_trade_fee(self, **params): """Get trade fee. https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#trade-fee-user_data :param symbol: optional :type symbol: str :param recvWindow: the number of milliseconds the request is valid for ...
Fetch details on assets. https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#asset-detail-user_data :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int :returns: API response .. code-block:: python ...
def get_asset_details(self, **params): """Fetch details on assets. https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#asset-detail-user_data :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int :returns...
Submit a withdraw request. https://www.binance.com/restapipub.html Assumptions: - You must have Withdraw permissions enabled on your API key - You must have withdrawn to the address specified through the website and approved the transaction via email :param asset: required ...
def withdraw(self, **params): """Submit a withdraw request. https://www.binance.com/restapipub.html Assumptions: - You must have Withdraw permissions enabled on your API key - You must have withdrawn to the address specified through the website and approved the transaction via...
PING a user data stream to prevent a time out. https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#keepalive-user-data-stream-user_stream :param listenKey: required :type listenKey: str :returns: API response .. code-block:: python ...
def stream_keepalive(self, listenKey): """PING a user data stream to prevent a time out. https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#keepalive-user-data-stream-user_stream :param listenKey: required :type listenKey: str :returns: API r...
Close out a user data stream. https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#close-user-data-stream-user_stream :param listenKey: required :type listenKey: str :returns: API response .. code-block:: python {} :raise...
def stream_close(self, listenKey): """Close out a user data stream. https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#close-user-data-stream-user_stream :param listenKey: required :type listenKey: str :returns: API response .. code-...
Start a websocket for symbol market depth returning either a diff or a partial book https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#partial-book-depth-streams :param symbol: required :type symbol: str :param callback: callback function to...
def start_depth_socket(self, symbol, callback, depth=None): """Start a websocket for symbol market depth returning either a diff or a partial book https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#partial-book-depth-streams :param symbol: required ...
Start a websocket for symbol kline data https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams :param symbol: required :type symbol: str :param callback: callback function to handle messages :type callback: funct...
def start_kline_socket(self, symbol, callback, interval=Client.KLINE_INTERVAL_1MINUTE): """Start a websocket for symbol kline data https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams :param symbol: required :type symb...
Start a multiplexed socket using a list of socket names. User stream sockets can not be included. Symbols in socket name must be lowercase i.e bnbbtc@aggTrade, neobtc@ticker Combined stream events are wrapped as follows: {"stream":"<streamName>","data":<rawPayload>} https://github.com...
def start_multiplex_socket(self, streams, callback): """Start a multiplexed socket using a list of socket names. User stream sockets can not be included. Symbols in socket name must be lowercase i.e bnbbtc@aggTrade, neobtc@ticker Combined stream events are wrapped as follows: {"stream"...
Stop a websocket given the connection key :param conn_key: Socket connection key :type conn_key: string :returns: connection key string if successful, False otherwise
def stop_socket(self, conn_key): """Stop a websocket given the connection key :param conn_key: Socket connection key :type conn_key: string :returns: connection key string if successful, False otherwise """ if conn_key not in self._conns: return # d...
Start a websocket for user data https://github.com/binance-exchange/binance-official-api-docs/blob/master/user-data-stream.md :param callback: callback function to handle messages :type callback: function :returns: connection key string if successful, False otherwise Message ...
def start_user_socket(self, callback): """Start a websocket for user data https://github.com/binance-exchange/binance-official-api-docs/blob/master/user-data-stream.md :param callback: callback function to handle messages :type callback: function :returns: connection key strin...
Close all connections
def close(self): """Close all connections """ keys = set(self._conns.keys()) for key in keys: self.stop_socket(key) self._conns = {}
Computes the bounds of the object itself (not including it's children) in the form [[lat_min, lon_min], [lat_max, lon_max]].
def _get_self_bounds(self): """ Computes the bounds of the object itself (not including it's children) in the form [[lat_min, lon_min], [lat_max, lon_max]]. """ bounds = [[None, None], [None, None]] for point in self.data: bounds = [ [ ...
Contains options and constants shared between vector overlays (Polygon, Polyline, Circle, CircleMarker, and Rectangle). Parameters ---------- stroke: Bool, True Whether to draw stroke along the path. Set it to false to disable borders on polygons or circles. color: str, '#3388ff' ...
def path_options(line=False, radius=False, **kwargs): """ Contains options and constants shared between vector overlays (Polygon, Polyline, Circle, CircleMarker, and Rectangle). Parameters ---------- stroke: Bool, True Whether to draw stroke along the path. Set it to false to di...
Renders the HTML representation of the element.
def render(self, **kwargs): """Renders the HTML representation of the element.""" self.json = json.dumps(self.data) self._parent.html.add_child(Element(Template(""" <div id="{{this.get_name()}}"></div> """).render(this=self, kwargs=kwargs)), name=self.get_name()) ...
Renders the HTML representation of the element.
def render(self, **kwargs): """Renders the HTML representation of the element.""" vegalite_major_version = self._get_vegalite_major_versions(self.data) self._parent.html.add_child(Element(Template(""" <div id="{{this.get_name()}}"></div> """).render(this=self, kwargs=kwa...
Convert an unknown data input into a geojson dictionary.
def process_data(self, data): """Convert an unknown data input into a geojson dictionary.""" if isinstance(data, dict): self.embed = True return data elif isinstance(data, str): if data.lower().startswith(('http:', 'ftp:', 'https:')): if not se...
Convert data into a FeatureCollection if it is not already.
def convert_to_feature_collection(self): """Convert data into a FeatureCollection if it is not already.""" if self.data['type'] == 'FeatureCollection': return if not self.embed: raise ValueError( 'Data is not a FeatureCollection, but it should be to apply ...
Tests `self.style_function` and `self.highlight_function` to ensure they are functions returning dictionaries.
def _validate_function(self, func, name): """ Tests `self.style_function` and `self.highlight_function` to ensure they are functions returning dictionaries. """ test_feature = self.data['features'][0] if not callable(func) or not isinstance(func(test_feature), dict): ...
Find a unique identifier for each feature, create it if needed.
def find_identifier(self): """Find a unique identifier for each feature, create it if needed.""" features = self.data['features'] n = len(features) feature = features[0] if 'id' in feature and len(set(feat['id'] for feat in features)) == n: return 'feature.id' ...
Internal function to create the mapping.
def _create_mapping(self, func, switch): """Internal function to create the mapping.""" mapping = {} for feature in self.data['features']: content = func(feature) if switch == 'style': for key, value in content.items(): if isinstance(va...
Convert dict to str and enable Jinja2 template syntax.
def _to_key(d): """Convert dict to str and enable Jinja2 template syntax.""" as_str = json.dumps(d, sort_keys=True) return as_str.replace('"{{', '{{').replace('}}"', '}}')
Return a value identifying the feature.
def get_feature_id(self, feature): """Return a value identifying the feature.""" fields = self.feature_identifier.split('.')[1:] return functools.reduce(operator.getitem, fields, feature)
Replace the field with the most features with a 'default' field.
def _set_default_key(mapping): """Replace the field with the most features with a 'default' field.""" key_longest = sorted([(len(v), k) for k, v in mapping.items()], reverse=True)[0][1] mapping['default'] = key_longest del (mapping[key_longest])
Applies self.style_function to each feature of self.data.
def style_data(self): """Applies self.style_function to each feature of self.data.""" def recursive_get(data, keys): if len(keys): return recursive_get(data.get(keys[0]), keys[1:]) else: return data geometries = recursive_get(self.data, s...
Computes the bounds of the object itself (not including it's children) in the form [[lat_min, lon_min], [lat_max, lon_max]]
def get_bounds(self): """ Computes the bounds of the object itself (not including it's children) in the form [[lat_min, lon_min], [lat_max, lon_max]] """ if not self.embed: raise ValueError('Cannot compute bounds of non-embedded TopoJSON.') xmin, xmax, ymin,...
Checks for GeoJson GeometryCollection features to warn user about incompatibility.
def warn_for_geometry_collections(self): """Checks for GeoJson GeometryCollection features to warn user about incompatibility.""" geom_collections = [ feature.get('properties') if feature.get('properties') is not None else key for key, feature in enumerate(self._parent.data['feat...
Renders the HTML representation of the element.
def render(self, **kwargs): """Renders the HTML representation of the element.""" if isinstance(self._parent, GeoJson): keys = tuple(self._parent.data['features'][0]['properties'].keys()) self.warn_for_geometry_collections() elif isinstance(self._parent, TopoJson): ...
Render the GeoJson/TopoJson and color scale objects.
def render(self, **kwargs): """Render the GeoJson/TopoJson and color scale objects.""" if self.color_scale: # ColorMap needs Map as its parent assert isinstance(self._parent, Map), ('Choropleth must be added' ' to a Map object.')...
Validate a single lat/lon coordinate pair and convert to a list Validate that location: * is a sized variable * with size 2 * allows indexing (i.e. has an ordering) * where both values are floats (or convertible to float) * and both values are not NaN Returns ------- list[float, fl...
def validate_location(location): # noqa: C901 """Validate a single lat/lon coordinate pair and convert to a list Validate that location: * is a sized variable * with size 2 * allows indexing (i.e. has an ordering) * where both values are floats (or convertible to float) * and both values a...
Validate an iterable with multiple lat/lon coordinate pairs. Returns ------- list[list[float, float]] or list[list[list[float, float]]]
def validate_locations(locations): """Validate an iterable with multiple lat/lon coordinate pairs. Returns ------- list[list[float, float]] or list[list[list[float, float]]] """ locations = if_pandas_df_convert_to_numpy(locations) try: iter(locations) except TypeError: ...
Return a Numpy array from a Pandas dataframe. Iterating over a DataFrame has weird side effects, such as the first row being the column names. Converting to Numpy is more safe.
def if_pandas_df_convert_to_numpy(obj): """Return a Numpy array from a Pandas dataframe. Iterating over a DataFrame has weird side effects, such as the first row being the column names. Converting to Numpy is more safe. """ if pd is not None and isinstance(obj, pd.DataFrame): return obj.val...
Infers the type of an image argument and transforms it into a URL. Parameters ---------- image: string, file or array-like object * If string, it will be written directly in the output file. * If file, it's content will be converted as embedded in the output file. * If arr...
def image_to_url(image, colormap=None, origin='upper'): """ Infers the type of an image argument and transforms it into a URL. Parameters ---------- image: string, file or array-like object * If string, it will be written directly in the output file. * If file, it's content will be ...
Transform an array of data into a PNG string. This can be written to disk using binary I/O, or encoded using base64 for an inline PNG like this: >>> png_str = write_png(array) >>> "data:image/png;base64,"+png_str.encode('base64') Inspired from https://stackoverflow.com/questions/902761/saving-...
def write_png(data, origin='upper', colormap=None): """ Transform an array of data into a PNG string. This can be written to disk using binary I/O, or encoded using base64 for an inline PNG like this: >>> png_str = write_png(array) >>> "data:image/png;base64,"+png_str.encode('base64') Insp...
Transforms an image computed in (longitude,latitude) coordinates into the a Mercator projection image. Parameters ---------- data: numpy array or equivalent list-like object. Must be NxM (mono), NxMx3 (RGB) or NxMx4 (RGBA) lat_bounds : length 2 tuple Minimal and maximal value of t...
def mercator_transform(data, lat_bounds, origin='upper', height_out=None): """ Transforms an image computed in (longitude,latitude) coordinates into the a Mercator projection image. Parameters ---------- data: numpy array or equivalent list-like object. Must be NxM (mono), NxMx3 (RGB) ...
Returns all the coordinate tuples from a geometry or feature.
def iter_coords(obj): """ Returns all the coordinate tuples from a geometry or feature. """ if isinstance(obj, (tuple, list)): coords = obj elif 'features' in obj: coords = [geom['geometry']['coordinates'] for geom in obj['features']] elif 'geometry' in obj: coords = obj...
Mirrors the points in a list-of-list-of-...-of-list-of-points. For example: >>> _locations_mirror([[[1, 2], [3, 4]], [5, 6], [7, 8]]) [[[2, 1], [4, 3]], [6, 5], [8, 7]]
def _locations_mirror(x): """ Mirrors the points in a list-of-list-of-...-of-list-of-points. For example: >>> _locations_mirror([[[1, 2], [3, 4]], [5, 6], [7, 8]]) [[[2, 1], [4, 3]], [6, 5], [8, 7]] """ if hasattr(x, '__iter__'): if hasattr(x[0], '__iter__'): return list...
Computes the bounds of the object in the form [[lat_min, lon_min], [lat_max, lon_max]]
def get_bounds(locations, lonlat=False): """ Computes the bounds of the object in the form [[lat_min, lon_min], [lat_max, lon_max]] """ bounds = [[None, None], [None, None]] for point in iter_coords(locations): bounds = [ [ none_min(bounds[0][0], point[0]), ...
Convert a python_style_variable_name to lowerCamelCase. Examples -------- >>> camelize('variable_name') 'variableName' >>> camelize('variableName') 'variableName'
def camelize(key): """Convert a python_style_variable_name to lowerCamelCase. Examples -------- >>> camelize('variable_name') 'variableName' >>> camelize('variableName') 'variableName' """ return ''.join(x.capitalize() if i > 0 else x for i, x in enumerate(key.spl...
Return the input string without non-functional spaces or newlines.
def normalize(rendered): """Return the input string without non-functional spaces or newlines.""" out = ''.join([line.strip() for line in rendered.splitlines() if line.strip()]) out = out.replace(', ', ',') return out
Yields the path of a temporary HTML file containing data.
def _tmp_html(data): """Yields the path of a temporary HTML file containing data.""" filepath = '' try: fid, filepath = tempfile.mkstemp(suffix='.html', prefix='folium_') os.write(fid, data.encode('utf8')) os.close(fid) yield filepath finally: if os.path.isfile(fi...
Return a recursive deep-copy of item where each copy has a new ID.
def deep_copy(item_original): """Return a recursive deep-copy of item where each copy has a new ID.""" item = copy.copy(item_original) item._id = uuid.uuid4().hex if hasattr(item, '_children') and len(item._children) > 0: children_new = collections.OrderedDict() for subitem_original in i...
Return the first object in the parent tree of class `cls`.
def get_obj_in_upper_tree(element, cls): """Return the first object in the parent tree of class `cls`.""" if not hasattr(element, '_parent'): raise ValueError('The top of the tree was reached without finding a {}' .format(cls)) parent = element._parent if not isinstance(...
Return a dict with lower-camelcase keys and non-None values..
def parse_options(**kwargs): """Return a dict with lower-camelcase keys and non-None values..""" return {camelize(key): value for key, value in kwargs.items() if value is not None}
Renders the HTML representation of the element.
def render(self, **kwargs): """Renders the HTML representation of the element.""" for item in self._parent._children.values(): if not isinstance(item, Layer) or not item.control: continue key = item.layer_name if not item.overlay: self....
Renders the HTML representation of the element.
def render(self, **kwargs): """Renders the HTML representation of the element.""" for name, child in self._children.items(): child.render(**kwargs) figure = self.get_root() assert isinstance(figure, Figure), ('You cannot render this Element ' ...
Validate the provided kwargs and return options as json string.
def parse_options(self, kwargs): """Validate the provided kwargs and return options as json string.""" kwargs = {camelize(key): value for key, value in kwargs.items()} for key in kwargs.keys(): assert key in self.valid_options, ( 'The option {} is not in the available...
Displays the HTML Map in a Jupyter notebook.
def _repr_html_(self, **kwargs): """Displays the HTML Map in a Jupyter notebook.""" if self._parent is None: self.add_to(Figure()) out = self._parent._repr_html_(**kwargs) self._parent = None else: out = self._parent._repr_html_(**kwargs) r...
Export the HTML to byte representation of a PNG image. Uses selenium to render the HTML and record a PNG. You may need to adjust the `delay` time keyword argument if maps render without data or tiles. Examples -------- >>> m._to_png() >>> m._to_png(time=10) # Wait 10 s...
def _to_png(self, delay=3): """Export the HTML to byte representation of a PNG image. Uses selenium to render the HTML and record a PNG. You may need to adjust the `delay` time keyword argument if maps render without data or tiles. Examples -------- >>> m._to_png() ...