INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Run the interactive window until the user quits | def run(self):
"""
Run the interactive window until the user quits
"""
# pyglet.app.run() has issues like https://bitbucket.org/pyglet/pyglet/issues/199/attempting-to-resize-or-close-pyglet
# and also involves inverting your code to run inside the pyglet framework
# avoid... |
Return the path to a given game s directory | def get_file_path(game, file, inttype=Integrations.DEFAULT):
"""
Return the path to a given game's directory
"""
base = path()
for t in inttype.paths:
possible_path = os.path.join(base, t, game, file)
if os.path.exists(possible_path):
return possible_path
return None |
Return the path to a given game s romfile | def get_romfile_path(game, inttype=Integrations.DEFAULT):
"""
Return the path to a given game's romfile
"""
for extension in EMU_EXTENSIONS.keys():
possible_path = get_file_path(game, "rom" + extension, inttype)
if possible_path:
return possible_path
raise FileNotFoundEr... |
Create a Gym environment for the specified game | def make(game, state=State.DEFAULT, inttype=retro.data.Integrations.DEFAULT, **kwargs):
"""
Create a Gym environment for the specified game
"""
try:
retro.data.get_romfile_path(game, inttype)
except FileNotFoundError:
if not retro.data.get_file_path(game, "rom.sha", inttype):
... |
Select actions from the tree | def select_actions(root, action_space, max_episode_steps):
"""
Select actions from the tree
Normally we select the greedy action that has the highest reward
associated with that subtree. We have a small chance to select a
random action based on the exploration param and visit count of the
curr... |
Perform a rollout using a preset collection of actions | def rollout(env, acts):
"""
Perform a rollout using a preset collection of actions
"""
total_rew = 0
env.reset()
steps = 0
for act in acts:
_obs, rew, done, _info = env.step(act)
steps += 1
total_rew += rew
if done:
break
return steps, total_r... |
Given the tree a list of actions that were executed before the game ended and a reward update the tree so that the path formed by the executed actions are all updated to the new reward. | def update_tree(root, executed_acts, total_rew):
"""
Given the tree, a list of actions that were executed before the game ended, and a reward, update the tree
so that the path formed by the executed actions are all updated to the new reward.
"""
root.value = max(total_rew, root.value)
root.visit... |
Get the authorization URL to redirect the user | def get_authorization_url(self,
signin_with_twitter=False,
access_type=None):
"""Get the authorization URL to redirect the user"""
try:
if signin_with_twitter:
url = self._get_oauth_url('authenticate')
... |
After user has authorized the request token get access token with user supplied verifier. | def get_access_token(self, verifier=None):
"""
After user has authorized the request token, get access token
with user supplied verifier.
"""
try:
url = self._get_oauth_url('access_token')
self.oauth = OAuth1Session(self.consumer_key,
... |
Get an access token from an username and password combination. In order to get this working you need to create an app at http:// twitter. com/ apps after that send a mail to api | def get_xauth_access_token(self, username, password):
"""
Get an access token from an username and password combination.
In order to get this working you need to create an app at
http://twitter.com/apps, after that send a mail to api@twitter.com
and request activation of xAuth fo... |
Add new record to cache key: entry key value: data of entry | def store(self, key, value):
"""Add new record to cache
key: entry key
value: data of entry
"""
self.client.set(key, value, time=self.timeout) |
Store the key value pair in our redis server | def store(self, key, value):
"""Store the key, value pair in our redis server"""
# Prepend tweepy to our key,
# this makes it easier to identify tweepy keys in our redis server
key = self.pre_identifier + key
# Get a pipe (to execute several redis commands in one step)
pi... |
Given a key returns an element from the redis table | def get(self, key, timeout=None):
"""Given a key, returns an element from the redis table"""
key = self.pre_identifier + key
# Check to see if we have this key
unpickled_entry = self.client.get(key)
if not unpickled_entry:
# No hit, return nothing
return N... |
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. | 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 ) | 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 pages | def pages(self, limit=0):
"""Return iterator for pages"""
if limit > 0:
self.iterator.limit = limit
return self.iterator |
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 | 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 | 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 | 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 | 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 | 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. | 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 | 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 | 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 | 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 | 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 | 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 | 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. | 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 | 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 | 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. | 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. | 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 | 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 | 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 | 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 | 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 | 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 | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 | 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 | 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. | 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"... |
Start a websocket for user data | 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... |
Stop a websocket given the connection key | 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... |
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 ). | 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... |
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) |
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('}}"', '}}') |
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 | 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. | 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. | 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. | 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: | 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. | 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) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.