Compare commits

..

No commits in common. "master" and "data-downloads" have entirely different histories.

38 changed files with 173 additions and 928 deletions

2
.gitignore vendored
View File

@ -2,6 +2,4 @@
*.old
.hugo_build.lock
*.json
/data
backend/api_logs.txt
*__pycache__*

View File

@ -1,428 +0,0 @@
Attribution-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-ShareAlike 4.0 International Public
License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-ShareAlike 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and
conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. BY-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
e. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution and ShareAlike.
h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
i. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
k. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
l. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
m. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. Additional offer from the Licensor -- Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
in any reasonable manner based on the medium, means, and
context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.

View File

@ -1,3 +1,3 @@
# My personal website ([https://baseddata.io](https://baseddata.io))
# My personal website ([https://bitlab21.com](https://bitlab21.com))
This site is made using [Hugo](https://gohugo.io/), a static website generator. The backend (which powers the api for getting data for the charts) is build in python and served using gunicorn.

View File

@ -1,172 +1,63 @@
from flask import Flask, g, jsonify, request, json, Response, send_from_directory, abort
from flask import Flask, jsonify, request, json, Response, send_from_directory, abort
from flask_cors import CORS
import orjson, os
import datetime
import time
app = Flask(__name__)
CORS(app)
FILES_DIRECTORY = "../data/"
FILES_DIRECTORY = '../data/'
@app.before_request
def start_timer():
g.start = time.time()
@app.after_request
def log(response):
now = time.time()
duration = round(now - g.start, 4)
dt = datetime.datetime.fromtimestamp(now).strftime("%Y-%m-%d %H:%M:%S")
log_entry = {
"timestamp": dt,
"duration": duration,
"method": request.method,
"url": request.url,
"status": response.status_code,
"remote_addr": request.access_route[-1],
"user_agent": request.user_agent.string,
}
log_line = ",".join(f"{key}={value}" for key, value in log_entry.items())
with open("api_logs.txt", "a") as f:
f.write(log_line + "\n")
return response
@app.route("/bitcoin_business_growth_by_country", methods=["GET"])
@app.route('/bitcoin_business_growth_by_country', methods=['GET'])
def business_growth():
today = datetime.datetime.today()
# Parse args from request
latest_date = request.args.get("latest_date")
country_names = request.args.get("countries") # change this line
cumulative_period_type = request.args.get("cumulative_period_type")
latest_date = request.args.get('latest_date')
country_names = request.args.get('countries') # change this line
cumulative_period_type = request.args.get('cumulative_period_type')
# Open json locally
with open("../data/final__bitcoin_business_growth_by_country.json", "rb") as f:
with open('../data/final__bitcoin_business_growth_by_country.json', 'rb') as f:
data = orjson.loads(f.read())
# Filter based on args
if latest_date:
latest_date_bool = latest_date == "true"
filtered_data = [
item for item in data if item["latest_date"] == latest_date_bool
]
latest_date_bool = latest_date == 'true'
filtered_data = [item for item in data if item['latest_date'] == latest_date_bool]
else:
filtered_data = data
if country_names:
countries = [name.strip() for name in country_names.split(",")]
filtered_data = [
item for item in filtered_data if item["country_name"] in countries
]
if cumulative_period_type == "1 day":
delta = today - datetime.timedelta(days=2)
filtered_data = [
item
for item in filtered_data
if item["cumulative_period_type"] == cumulative_period_type
and delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d")
]
elif cumulative_period_type == "7 day":
delta = today - datetime.timedelta(days=8)
filtered_data = [
item
for item in filtered_data
if item["cumulative_period_type"] == cumulative_period_type
and delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d")
]
elif cumulative_period_type == "28 day":
delta = today - datetime.timedelta(days=29)
filtered_data = [
item
for item in filtered_data
if item["cumulative_period_type"] == cumulative_period_type
and delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d")
]
elif cumulative_period_type == "365 day":
delta = today - datetime.timedelta(days=366)
filtered_data = [
item
for item in filtered_data
if item["cumulative_period_type"] == cumulative_period_type
and delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d")
]
filtered_data = [item for item in filtered_data if item['country_name'] in countries]
if cumulative_period_type:
filtered_data = [item for item in filtered_data if item['cumulative_period_type'] == cumulative_period_type]
# Sort by date
sorted_data = sorted(filtered_data, key=lambda x: x["date"], reverse=False)
sorted_data = sorted(filtered_data, key=lambda x: x['date'], reverse=True)
# Return json
return Response(json.dumps(sorted_data), mimetype="application/json")
return Response(json.dumps(sorted_data), mimetype='application/json')
@app.route("/get_json/<filename>", methods=["GET"])
@app.route('/get_json/<filename>', methods=['GET'])
def get_json(filename):
period = request.args.get("period")
today = datetime.datetime.today()
file_path = os.path.join(FILES_DIRECTORY, filename)
if not os.path.isfile(file_path):
abort(404)
with open(file_path, "r") as f:
data = orjson.loads(f.read())
with open(file_path, 'r') as file:
data = json.load(file)
if period == "last 7 days":
delta = today - datetime.timedelta(days=7)
filtered_data = [
item
for item in data
if delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d") <= today
]
sorted_data = sorted(filtered_data, key=lambda x: x["date"])
elif period == "last 28 days":
delta = today - datetime.timedelta(days=28)
filtered_data = [
item
for item in data
if delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d") <= today
]
sorted_data = sorted(filtered_data, key=lambda x: x["date"])
elif period == "last 365 days":
delta = today - datetime.timedelta(days=365)
filtered_data = [
item
for item in data
if delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d") <= today
]
sorted_data = sorted(filtered_data, key=lambda x: x["date"])
elif period == "last 2 years":
delta = today - datetime.timedelta(days=730)
filtered_data = [
item
for item in data
if delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d") <= today
]
sorted_data = sorted(filtered_data, key=lambda x: x["date"])
else:
sorted_data = sorted(data, key=lambda x: x["date"])
return jsonify(data)
return jsonify(sorted_data)
@app.route("/download/<filename>", methods=["GET"])
@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
try:
return send_from_directory(FILES_DIRECTORY, filename, as_attachment=True)
except FileNotFoundError:
abort(404)
if __name__ == '__main__':
app.run(debug=True)
if __name__ == "__main__":
if __name__ == '__main__':
app.run()

View File

@ -1,13 +0,0 @@
[Unit]
Description=Gunicorn instance to serve baseddata.io
After=network.target
[Service]
User=admin
Group=www-data
WorkingDirectory=/var/www/baseddata.io/backend
Environment="PATH=/var/www/baseddata.io/.venv/bin"
ExecStart=/var/www/baseddata.io/.venv/bin/gunicorn --workers 4 --bind unix:baseddata.sock -m 007 app:app
[Install]
WantedBy=multi-user.target

13
backend/bitlab21.service Normal file
View File

@ -0,0 +1,13 @@
[Unit]
Description=Gunicorn instance to serve bitlab21.com
After=network.target
[Service]
User=admin
Group=www-data
WorkingDirectory=/var/www/bitlab21.com/backend
Environment="PATH=/var/www/bitlab21.com/.venv/bin"
ExecStart=/var/www/bitlab21.com/.venv/bin/gunicorn --workers 4 --bind unix:bitlab21.sock -m 007 app:app
[Install]
WantedBy=multi-user.target

View File

@ -1,5 +0,0 @@
flask
flask_cors
orjson
gunicorn

View File

@ -4,11 +4,11 @@ toc: False
# Grounded Insights from Open Data
**This site is currently under construction**.
This site is currently under construction. The direction I intend for this site to take is as a place to publish analytical insights derived from open data. I have a page called [Data Lab](/data-lab) where I publish interactive analytical dashboards, a blog to publish tutorials and thoughts on various related topics, and a [data downloads](/data-download) page for data access.
I intend for this to be a place to publish my personal work to share with others. I have a page called [Data Lab](/data-lab) where I publish interactive analytical dashboards based on open data, a blog to publish tutorials and thoughts I have on various topics, and a [data downloads](/data-downloads) page for data access.
I'm interested in a broad set of topics such as Linux, analytics and data engineering, GIS and bitcoin. So expect to see content related to these topics published on this site.
I'm interested in a broad set of topics such as Linux, analytics and data engineering, Geographic Information Systems (GIS) and bitcoin. So expect to see content related to these topics published on this site.
I strongly believe in the philosophy of [Free Software](https://www.gnu.org/philosophy/free-sw.html) and [Open Data](https://en.wikipedia.org/wiki/Open_data). Therefore, all material on this site is released into the public domain unless otherwise specified. For more information, see [here](/license).
### Explore Based Data

View File

@ -9,13 +9,16 @@ toc: false
My name is Sam Chance, and this is my personal site.
I'm a professional Analytics Engineer with a passion for working with data. I built this website as a place to publish my personal work.
I'm an independent Analytics Engineer with a passion for working with data. I built this website as a place to publish my personal work.
If you wish to work with me, then please email me on *contact@sjplab.com*.
More about my professional life [here](/cv).
### Shortcuts to some of my work:
- [Data Lab](/data-lab) A selection of charts and metrics obtained from public data
- [Based Data Lab](/data-lab) A selection of charts and metrics obtained from public data
- [Map Printing Service](https://semitamaps.com) A free map printing service based on Openstreetmaps
@ -25,7 +28,7 @@ If you wish to work with me, then please email me on *contact@sjplab.com*.
### Software I use:
- [**Neovim**](https://neovim.io/) for text editing (my neovim config is part of my [nixos](https://git.bitlab21.com/sam/nixos/src/branch/master/home/common/core/nixvim) configuration)
- [**Neovim**](https://neovim.io/) for text editing (my neovim config is part of my [nixos](https://git.bitlab21.com/sam/nixos) configuration)
- I use **Linux** on all my machines

View File

@ -51,7 +51,7 @@ Next we can run the following command to download the rasters. This will take so
aws s3 cp s3://raster/SRTM_GL1/ . --recursive --endpoint-url https://opentopography.s3.sdsc.edu --no-sign-request
{{</ highlight >}}
If you'd prefer to download specific rasters or rasters for a region instead of downloading them all, you can select regions for download from the OpenTopography [website](https://portal.opentopography.org/raster?opentopoID=OTSRTM.082015.4326.1) using the interactive map.
If you'd prefer to download specific rasters or rasters for a region instead, you can checkout this [website](https://dwtkns.com/srtm30m/).
## Using raster2pgsql to import raster tiles into PostGIS
Now we have the data downloaded on our system, we can import it into our database.
@ -98,9 +98,9 @@ So we have just over 12 million 128x128 tiles in the database.
## Raster Clipping
Now we have global SRTM data loaded in our local database, we can extract the tiles we want for further analysis.
Now we have global SRTM data loaded in our local database, we can extract any of the tiles for further analysis and access this using any application.
Here we'll create a digital elevation raster for Singapore to demonstrate using the following PostGIS commands: `st_clip`, `st_intersects` and `st_union`, then import this into QGIS to style and visualise the results.
Here I'll demonstrate using the following PostGIS commands: `st_clip`, `st_intersects` and `st_union` to create a digital elevation table for singapore and access this from from within QGIS.
I already have countries vector data in my Postgres database that I extracted from OpenStreetMaps. You can download a pg_dump of this [here](/data/countries.sql) to insert into your database. Alternatively, I have a post [here](/blogs/import-osm-countries-data) that explains the process to do this manually.
@ -224,6 +224,3 @@ This DEM raster of Singapore is available for download from the downloads page [
#### Citations
NASA Shuttle Radar Topography Mission (SRTM)(2013). Shuttle Radar Topography Mission (SRTM) Global. Distributed by OpenTopography. https://doi.org/10.5069/G9445JDF. Accessed: 2024-08-06
#### Attribution and License
© [OpenStreetMap](https://www.openstreetmap.org/copyright)

View File

@ -1,42 +1,28 @@
## Sam Chance | Analytics Engineer | Cornwall, UK
***contact@sjplab.com***
# Sam Chance
## Analytics Engineer
4 years experience working in the tech industry as a Data Analyst and Analytics Engineer. Experienced at providing high quality consulting services to company stakeholders. Demonstrable proficiency in various programming languages. Strong educational background in a STEM field with Master's and Bachelor's degree. Excellent communication skills with competence at articulating complex ideas to non-technical people. Broad set of technical skills and talented at crafting creative solutions for novel problems.
Analytics Engineer with over 4 years experience in designing and implementing data models, pipelines, and analytics solutions. Proficient in SQL, data warehousing, dbt and building dashboards for company metrics.
## Skills
- **Database Management**: BigQuery | Postgres | MongoDB (learning)
- **Analytics**: Data Engineering | Data Analysis (R, Pandas, Numpy, SPSS) | Data Modelling (DBT, Python, SQL) | Data Visualization | Dashboarding (Looker Studio, Apache ECharts)
- **Programming Languages**: proficient: SQL, Python, Bash | capable: R, Lua | learning: JavaScript, Nix
- **Code Collaboration & Version Control**: Git, Github, Self Hosted Gitea
- **Workflow Orchestration**: Apache Airflow | Prefect (learning)
- **CLI wizard**: Scripting (Bash, Python) | GNU Coreutils | Neovim
- **Geographic Information Systems**: QGIS | PostGIS | GDAL
- **Sysadmin**: Linux | Networking | SSH | Reverse Proxy (Nginx) | API Management | Containerization (Docker, LXC) | Nixos
- **Computers**: Cloud Computing (GCP) | Infrastructure Engineering (Homelab, Hypervisors, KVM) | x86 Architecture
- **AI Tooling**: Self Hosted LLMs | Ollama | Langchain | Open Interpreter
- **Web Development**: Hugo | JavaScript/HTML/CSS | Apache ECharts
- **Personal**: Full UK Driving License | Flexible Working | Autonomous Worker
- SQL
- Python
- Scripting/Programming
- Data Warehousing
- Data Modelling
- DBT
- Data and Statistical Analysis
- System Administration
## Experience
### Growth Analyst / Analytics Engineer | What3Words | May 2020 to Apr 2024
- Designed and implemented successful bespoke alerting system from scratch to detect anomalous behaviour in partner API usage (using python)
- General consultant to company stakeholders for resolving technical data related problems
- Built company KPI dashboard in Looker Studio along with underlying data pipelines and data models
- Built QA tool for Product Team to assess and monitor data quality
- Assisted with several large data migration projects in the Data Team
- Researched and implemented data mining techniques for Product and BD Teams
- Started as a Growth Analyst, then promoted to Analytics Engineer
## Work Experience
### Growth Analyst
What3Words - May 2020 to Feb 2022
### Analytics Engineer
What3Words - Feb 2022 to Apr 2024
## Education
### MSc Marine Biology | Bangor University | 1 year
- Delivering technical presentations
- Programmatic statistical analysis of data
- **Thesis**: "Quantifying the Effectiveness of Indonesia's Protected Areas at Preventing Mangrove Deforestation"
* A GIS project that involved statistical modelling of satellite data using ArcGIS and R
### MSc Marine Biology
Bangor University - 2017 to 2018
### BSc Marine Biology & Zoology | Bangor University | 3 years
- **Thesis**: "Biodiversity of Seamounts"
## Personal Websites
- https://baseddata.io: A site where I publish analytical content based on open data. Still a work in progress.
- https://semitamaps.com: A free high-quality map printing service based on OpenStreetMaps.
### BSc Marine Biology & Zoology
Bangor University - 2008 to 2011

View File

@ -11,10 +11,7 @@ tags: ["QGIS", "SRTM", "DEM", "Raster", "download"]
{{< figure src="/pics/blog/batch-import-postgis-rasters/singapore-final.webp" width="300">}}
Download the Digital Elevation Model featured in [this](/blog/batch-import-postgis-rasters/) blog.
{{< download-data src="/singapore-srtm-dem.tif" name="singapore-srtm-dem.tif" >}} (9.6MB)
{{< download-data src="http://localhost:5000/download/singapore-srtm-dem.tif" name="singapore-srtm-dem.tif" >}}
#### Citations
NASA Shuttle Radar Topography Mission (SRTM)(2013). Shuttle Radar Topography Mission (SRTM) Global. Distributed by OpenTopography. https://doi.org/10.5069/G9445JDF. Accessed: 2024-08-06
#### Attribution and License
© [OpenStreetMap](https://www.openstreetmap.org/copyright)

View File

@ -10,5 +10,7 @@ tags: ["Bitcoin", "Stats"]
---
This chart shows historical median daily feerate percentiles for the Bitcoin
protocol.
protocol. The data represents a daily aggregation of all blocks. This data was
extracted from the blockchain using the `bitcoin-cli getblockstats` command.
{{< chart src="/js/feerate-percentile.js" >}}

View File

@ -8,19 +8,13 @@ summary: "This analysis uses OpenStreetMaps data to chart the yearly growth of b
tags: ["Bitcoin", "Stats", "OpenStreetMaps"]
---
The table below illustrates growth of businesses worldwide that accept bitcoin as payment for products or services. The accompanying chart displays the cumulative number of bitcoin-accepting businesses for the countries selected in the table. The data is sourced from OpenStreetMaps and is updated approximately every 2 hours.
The table below illustrates growth of businesses worldwide that accept bitcoin as payment for products or services. The accompanying chart displays the yearly cumulative number of bitcoin-accepting businesses for the countries selected in the table. The data is sourced from OpenStreetMaps and is updated approximately every 2 hours.
You can select the growth period of interest from the drop-down, which updates the values in the table. The table shows the ***Previous*** value, which was the number of businesses *n* days ago specified in the drop-down. The ***Current*** value is the number of businesses as of the latest update. The table also shows the ***Absolute Difference***, and the ***Percent Difference*** between this period.
The chart always reflects the countries selected in the table.
The chart always reflects the countries selected in the table. There is a zoom feature on the chart to focus in on a period of interest.
<br/>
Select growth period: {{< dropdown-filter id=cumulative_period_type select="365 day,28 day,7 day,1 day" >}}
{{< chart src="/js/bitcoin-business-growth-chart.js" >}}
{{< table src="/js/bitcoin-business-growth-table.js" >}}
#### Attribution and License
Data obtained from © [OpenStreetMap](https://www.openstreetmap.org/copyright)
Licensed under the [ODbl](https://opendatacommons.org/licenses/odbl/)

View File

@ -8,6 +8,6 @@ summary: "Timeseries chart showing the Bitcoin network hashrate and difficulty."
tags: ["Bitcoin", "Stats", "Hashrate"]
---
This chart shows the estimated hashrate and difficulty of the Bitcoin network, accompanied by the 28-day moving average. This information is extracted from a bitcoin node using the `bitcoin-cli getnetworkhashps` command.
The estimated hashrate and difficulty of the Bitcoin network, accompanied by the 28-day moving average.
{{< chart src="/js/hashrate.js" >}}

View File

@ -9,6 +9,6 @@ draft: false
tags: ["Bitcoin", "Stats"]
---
The following chart shows daily miner revenue in USD for the period selected in the dropdown. This information is based on the sum of bitcoin mined each day (i.e. the block-subsidy) plus the transaction fees. Price data is obtained from [CoinGecko](https://www.coingecko.com/).
Total daily aggregated miner income denominated in USD for that day.
{{< chart src="/js/miner-rewards.js" >}}

View File

@ -8,7 +8,7 @@ summary: "Daily bitcoin price. Data is obtained from CoinGecko using their publi
tags: ["Bitcoin", "Stats"]
---
Daily bitcoin price. Data is obtained from [CoinGecko](https://www.coingecko.com/) using their
Daily bitcoin price. Data is obtained from CoinGecko using their
public API.
{{< bitcoin-price >}}

View File

@ -1,21 +1,3 @@
# License
Where possible, all original work on this site that has been created and published by me is licensed using [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/).
You are free to:
- Share — copy and redistribute the material in any medium or format for any purpose, even commercially.
- Adapt — remix, transform, and build upon the material for any purpose, even commercially.
The licensor cannot revoke these freedoms as long as you follow the license terms.
Under the following terms:
- Attribution — You must give appropriate credit , provide a link to the license, and indicate if changes were made . You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
- ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.
- No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits.
Notices:
You do not have to comply with the license for elements of the material in the public domain or where your use is permitted by an applicable exception or limitation .
No warranties are given. The license may not give you all of the permissions necessary for your intended use. For example, other rights such as publicity, privacy, or moral rights may limit how you use the material.
All work on this site is licensed using [unlicense](https://unlicense.org/). This effectively means all of the content hosted on https://bitlab21.com and in the bitlab21.com repository at https://git.bitlab21.com/sam/bitlab21.com is in the public domain. You can use this material as you wish. Attribution is appreciated, but not required.

View File

@ -1,9 +1,6 @@
baseURL = 'https://baseddata.io'
baseURL = 'https://baseddate.io/'
languageCode = 'en-gb'
title = 'Based Data'
[params]
apiURL = 'https://api.baseddata.io'
title = 'baseddata.io'
[markup.highlight]
pygmentsUseClasses = false

View File

@ -1,7 +1,7 @@
<script src="https://cdn.jsdelivr.net/npm/echarts@5.5.1/dist/echarts.min.js"></script>
<section class="chart-container">
<div id="chart-modifiers"></div>
<div id="chart">
<canvas id="{{ .id }}"></canvas>
<script src="{{ .src }}"></script>
</div>
</section>

View File

@ -1,9 +1,8 @@
<footer>
<div id="footer">
<p>
baseddata.io by Sam Chance. | Built with
<a href="https://gohugo.io/">Hugo</a>
| <a href="/license">License</a>
Bitlab21.com by Sam Chance.
<a href="/license">Uncopywrited.</a>
</p>
</div>
</footer>

View File

@ -1,7 +1,7 @@
<header>
<nav class="navbar" role="navigation">
<div class="navbar__left">
<a href="/"><strong>BASED DATA</strong></a>
<a href="/"><strong>Based Data</strong></a>
</div>
<div class="navbar__right">
<div class="navbar-links">{{ partial "navbarlinks.html" . }}</div>

View File

@ -4,7 +4,7 @@
<p id="price"></p>
<script>
fetch(`${"{{ .Site.Params.apiURL }}"}/get_json/final__price.json`)
fetch("https://api.bitlab21.com/price")
.then((response) => response.json())
.then((data) => {
var lastElement = data[data.length - 1];

View File

@ -1,5 +1,2 @@
<script>
const apiURL = "{{ .Site.Params.apiURL }}";
</script>
{{ $id := .Get "src" | md5 }} {{ partial "chart.html" (dict "src" (.Get "src")
"id" $id) }}
{{ $id := .Get "src" | md5 }}
{{ partial "chart.html" (dict "src" (.Get "src") "id" $id) }}

View File

@ -5,10 +5,7 @@
<script>
async function downloadFile(url, name) {
try {
const response = await fetch(`${"{{ .Site.Params.apiURL }}"}/download${url}`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const response = await fetch(url);
const blob = await response.blob();
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
@ -16,7 +13,6 @@
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href); // Clean up the object URL
} catch (error) {
console.error('Error downloading the file:', error);
}

View File

@ -0,0 +1,7 @@
<select id={{ .Get "id" }} class="dropdownFilter">
{{ with .Get "select" }}
{{ range $index, $element := split . "," }}
<option value="{{ $element }}">{{ $element }}</option>
{{ end }}
</select>
{{ end }}

View File

@ -6,39 +6,24 @@
</div>
<div class="article-card-container">
{{ range.Pages }}
<div class="article-card">
<a class="article-card" href="{{ .RelPermalink }}">
<div class="article-card-info">
<div class="article-card-thumb">
<a href="{{ .RelPermalink }}">
<img
class="article-card-thumbnail"
src="{{ .Params.header_image }}"
/>
</a>
<img
class="article-card-thumbnail"
src="{{ .Params.header_image }}"
/>
</div>
<div class="article-card-summary">
{{ template "partials/get-tags.html" . }}
<a href="{{ .RelPermalink }}">
<h3><strong>{{ .Title | safeHTML }}</strong></h3>
</a>
<p>
{{ .Summary | safeHTML }}
<i class="reading-time"
>({{ .ReadingTime }} minute{{ if (ne .ReadingTime 1) }}s{{ end
}})</i
>
</p>
<h3><strong>{{ .Title | safeHTML }}</strong></h3>
<p>{{ .Summary | safeHTML }}</p>
<br />
<div class="article-card-author-row">
{{ with .Params.author }}
<strong><p class="author-name">{{ .name }}</p></strong>
{{ end }}
<time>{{ .Date.Format "January 2, 2006" }}</time>
</div>
</div>
</div>
</div>
</a>
{{ end }}
</div>
</div>

View File

@ -9,22 +9,10 @@ pkgs.mkShell
python312Packages.pandas
python312Packages.orjson
hugo
tmux
];
shellHook = ''
${pkgs.cowsay}/bin/cowsay "Welcome to the baseddata.io development environment!" | ${pkgs.lolcat}/bin/lolcat
get_session=$(tmux list-session | grep "baseddata")
if [ -z "$get_session" ];
then
tmux new-session -d -s baseddata
tmux split-window -h
tmux send-keys -t 0 "hugo server" C-m
tmux send-keys -t 1 "cd backend && python app.py" C-m
echo "Baseddata running in dev tmux shell"
fi
${pkgs.cowsay}/bin/cowsay "Welcome to the bitlab development environment!" | ${pkgs.lolcat}/bin/lolcat
'';
}

View File

@ -16,9 +16,4 @@
margin-top: 20px;
display: flex;
justify-content: center;
flex-direction: column;
}
#chart-modifiers {
display: flex;
}

View File

@ -52,7 +52,6 @@
.navbar__left a {
text-decoration: none !important;
font-weight: 540;
color: var(--text-color) !important;
font-size: 22px;
}

View File

@ -133,10 +133,7 @@ footer {
color: var(--text-color);
padding: 20px;
height: 10vh;
display: flex;
justify-content: space-between;
border-top: var(--border-width) var(--border-style) var(--border-color);
}
#footer {
display: flex;
justify-content: center;
}

View File

@ -1,14 +1,9 @@
let chartData = [];
let myChart;
let periodIndex = 3;
const periods = ["1 day", "7 day", "28 day", "365 day"];
async function fetchDataForChart(str, period) {
async function fetchDataForChart(str) {
try {
const apiEndpoint = `${apiURL}/bitcoin_business_growth_by_country?cumulative_period_type=${period}&countries=${str}`;
console.log("Fetching from " + apiEndpoint);
const apiEndpoint = `https://api.bitlab21.com/bitcoin_business_growth_by_country?cumulative_period_type=365 day&countries=${str}`;
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
@ -43,11 +38,10 @@ function updateChart() {
axisTick: axisTick,
axisLabel: axisLabel,
axisLine: axisLine,
type: "category",
type: "time",
},
yAxis: {
axisTick: axisTick,
scale: true,
splitLine: {
show: false,
},
@ -75,35 +69,30 @@ function handleCheckboxChange(event) {
if (event.target.type === "checkbox") {
const boxChecked = event.target.checked;
const boxId = event.target.id;
let selectedPeriod = getPeriodFromDropdown();
// Remove unchecked boxes
if (boxChecked === false) {
delete chartData[boxId];
updateChart();
// Add checked boxes
} else {
fetchDataForChart(boxId, selectedPeriod);
fetchDataForChart(boxId);
}
}
}
document.addEventListener("DOMContentLoaded", function () {
periodDropdown(periods, periodIndex);
document.addEventListener("reloadTable", () => {
myChart = echarts.init(document.getElementById("chart"));
jsonTableCheckedBoxes = document.querySelectorAll(
'#jsonTableContainer input[type="checkbox"]:checked',
);
const checkedBoxes = Array.from(jsonTableCheckedBoxes).map(
(checkbox) => checkbox.id,
);
const str = checkedBoxes.join(",");
let selectedPeriod = getPeriodFromDropdown();
chartData = [];
fetchDataForChart(str, selectedPeriod);
document.addEventListener("reloadTable", () => {
myChart = echarts.init(document.getElementById("chart"));
jsonTableCheckedBoxes = document.querySelectorAll(
'#jsonTableContainer input[type="checkbox"]:checked',
);
const checkedBoxes = Array.from(jsonTableCheckedBoxes).map(
(checkbox) => checkbox.id,
);
const str = checkedBoxes.join(",");
chartData = [];
fetchDataForChart(str);
jsonTable = document.getElementById("jsonTableContainer");
jsonTable.removeEventListener("change", handleCheckboxChange);
jsonTable.addEventListener("change", handleCheckboxChange);
});
jsonTable = document.getElementById("jsonTableContainer");
jsonTable.removeEventListener("change", handleCheckboxChange);
jsonTable.addEventListener("change", handleCheckboxChange);
});

View File

@ -1,9 +1,12 @@
async function fetchDataForTable() {
try {
selectedPeriod = getPeriodFromDropdown();
const apiEndpoint = `${apiURL}/bitcoin_business_growth_by_country?latest_date=true`;
const dropdown = document.querySelector(".dropdownFilter");
let selectedIndex = dropdown.selectedIndex;
let selectedValue = dropdown.options[selectedIndex].value;
const apiEndpoint =
"https://api.bitlab21.com/bitcoin_business_growth_by_country?latest_date=true";
const response = await fetch(
apiEndpoint + `&cumulative_period_type=${selectedPeriod}`,
apiEndpoint + `&cumulative_period_type=${selectedValue}`,
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
@ -86,10 +89,10 @@ function createTable(data) {
);
}
document.addEventListener("DOMContentLoaded", function () {
const dropdown = document.getElementById("select-period-dropdown");
window.onload = () => {
const dropdown = document.querySelector(".dropdownFilter");
fetchDataForTable();
dropdown.addEventListener("change", () => {
fetchDataForTable();
});
});
};

View File

@ -1,18 +1,9 @@
let dataArr = [];
const myChart = echarts.init(document.getElementById("chart"));
const filename = "final__price.json";
const periods = [
"all time",
"last 7 days",
"last 28 days",
"last 365 days",
"last 2 years",
];
async function fetchDataForChart(selectedValue) {
async function fetchDataForChart() {
try {
const apiEndpoint = `${apiURL}/get_json/${filename}?period=${selectedValue}`;
const apiEndpoint = "https://api.bitlab21.com/get_json/final__price.json";
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
@ -36,7 +27,7 @@ function initEchart(dataArr) {
axisLine: axisLine,
},
grid: grid,
dataZoom: dataZoom(0),
dataZoom: dataZoom(),
yAxis: [
{
type: "value",
@ -71,14 +62,4 @@ function initEchart(dataArr) {
myChart.setOption(option);
}
document.addEventListener("DOMContentLoaded", function () {
let periodIndex = 2;
periodDropdown(periods, periodIndex);
fetchDataForChart(periods[periodIndex]);
const selectElement = document.getElementById("select-period-dropdown");
selectElement.addEventListener("change", function (event) {
const selectedValue = event.target.value;
fetchDataForChart(selectedValue);
});
});
fetchDataForChart();

View File

@ -31,7 +31,7 @@ const toolboxParams = {
dataZoom: {
yAxisIndex: "none",
},
dataView: {},
restore: {},
saveAsImage: {
pixelRatio: 2,
},
@ -73,10 +73,13 @@ const yaxisTextStyle2 = {
color: textColor,
};
function dataZoom() {
function dataZoom(start = 90, end = 100, bottom = 15, height = 15) {
const dataZoom = [
{
type: "inside",
start: start,
end: end,
bottom: bottom,
height: height,
},
];
@ -103,35 +106,6 @@ function nFormatter(value, digits) {
: "0";
}
function periodDropdown(periods, defaultIndex = 0) {
const modifiers = document.getElementById("chart-modifiers");
const dropdownContainer = document.createElement("div");
const dropdown = document.createElement("select");
const textNode = document.createTextNode("Select period: ");
dropdownContainer.id = "dropdown-container";
dropdown.id = "select-period-dropdown";
dropdownContainer.appendChild(textNode);
dropdownContainer.appendChild(dropdown);
modifiers.appendChild(dropdownContainer);
periods.forEach((period, index) => {
const option = document.createElement("option");
if (index === defaultIndex) {
option.selected = true;
}
option.value = period;
option.textContent = period;
dropdown.appendChild(option);
});
}
function getPeriodFromDropdown() {
let dropdown = document.getElementById("select-period-dropdown");
let selectedIndex = dropdown.selectedIndex;
return dropdown.options[selectedIndex].value;
}
window.addEventListener("resize", function () {
if (myChart != null && myChart != undefined) {
myChart.resize();

View File

@ -1,18 +1,10 @@
let dataArr = [];
const myChart = echarts.init(document.getElementById("chart"));
const filename = "final__feerate_percentiles.json";
const periods = [
"all time",
"last 7 days",
"last 28 days",
"last 365 days",
"last 2 years",
];
async function fetchDataForChart(selectedValue) {
async function fetchDataForChart() {
try {
const apiEndpoint = `${apiURL}/get_json/${filename}?period=${selectedValue}`;
const apiEndpoint =
"https://api.bitlab21.com/get_json/final__feerate_percentiles.json";
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
@ -47,7 +39,7 @@ function initEchart(dataArr) {
axisLine: axisLine,
},
grid: grid,
dataZoom: dataZoom(0),
dataZoom: dataZoom((start = 98)),
series: [
{
type: "line",
@ -113,15 +105,4 @@ function initEchart(dataArr) {
myChart.setOption(option);
}
document.addEventListener("DOMContentLoaded", function () {
let periodIndex = 2;
periodDropdown(periods, periodIndex);
fetchDataForChart(periods[periodIndex]);
const selectElement = document.getElementById("select-period-dropdown");
selectElement.addEventListener("change", function (event) {
const selectedValue = event.target.value;
fetchDataForChart(selectedValue);
});
});
fetchDataForChart();

View File

@ -1,17 +1,10 @@
let dataArr = [];
const myChart = echarts.init(document.getElementById("chart"));
const filename = "final__hashrate.json";
const periods = [
"all time",
"last 7 days",
"last 28 days",
"last 365 days",
"last 2 years",
];
async function fetchDataForChart(selectedValue) {
async function fetchDataForChart() {
try {
const apiEndpoint = `${apiURL}/get_json/${filename}?period=${selectedValue}`;
const apiEndpoint =
"https://api.bitlab21.com/get_json/final__hashrate.json";
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
@ -40,7 +33,7 @@ function initEchart(dataArr) {
axisLine: axisLine,
},
grid: grid,
dataZoom: dataZoom(0),
dataZoom: dataZoom(),
yAxis: [
{
type: "value",
@ -113,15 +106,4 @@ function initEchart(dataArr) {
myChart.setOption(option);
}
document.addEventListener("DOMContentLoaded", function () {
let periodIndex = 2;
periodDropdown(periods, periodIndex);
fetchDataForChart(periods[periodIndex]);
const selectElement = document.getElementById("select-period-dropdown");
selectElement.addEventListener("change", function (event) {
const selectedValue = event.target.value;
fetchDataForChart(selectedValue);
});
});
fetchDataForChart();

View File

@ -1,17 +1,10 @@
let dataArr = [];
const myChart = echarts.init(document.getElementById("chart"));
const filename = "final__miner_rewards.json";
const periods = [
"all time",
"last 7 days",
"last 28 days",
"last 365 days",
"last 2 years",
];
async function fetchDataForChart(selectedValue) {
async function fetchDataForChart() {
try {
const apiEndpoint = `${apiURL}/get_json/${filename}?period=${selectedValue}`;
const apiEndpoint =
"https://api.bitlab21.com/get_json/final__miner_rewards.json";
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
@ -24,37 +17,9 @@ async function fetchDataForChart(selectedValue) {
}
function initEchart(dataArr) {
console.log(dataArr);
const option = {
backgroundColor: backgroundColor,
tooltip: {
...tooltip,
formatter: function (params) {
let colors = ["#ee6666", "#000000", "#b0da9d", "#8699d5"];
let colorSpan = (color) =>
'<span style="display:inline-block;margin-right:1px;border-radius:5px;width:9px;height:9px;background-color:' +
color +
'"></span>';
let tooltip = "<p>" + params[0].axisValue + "</p>";
params.reverse().forEach((item, index) => {
let color = colors[index % colors.length];
let labels =
"<p>" +
colorSpan(color) +
" " +
item.seriesName +
": " +
nFormatter(item.data, 3);
("</p>");
tooltip += labels;
});
return tooltip;
},
valueFormatter(value, index) {
return nFormatter(value, 3);
},
},
tooltip: tooltip,
toolbox: toolboxParams,
xAxis: {
data: dataArr.map((row) => row.date),
@ -63,13 +28,13 @@ function initEchart(dataArr) {
axisLine: axisLine,
},
grid: grid,
dataZoom: dataZoom(0),
dataZoom: dataZoom(97),
yAxis: [
{
type: "value",
name: "Rewards (USD)",
nameLocation: "middle",
nameGap: 30,
nameGap: 35,
nameTextStyle: textStyleMain,
position: "left",
alignTicks: true,
@ -87,7 +52,7 @@ function initEchart(dataArr) {
},
{
type: "value",
name: "Subsidy (BTC)",
name: "Block Subsidy (BTC)",
nameLocation: "middle",
nameGap: 20,
nameTextStyle: {
@ -110,7 +75,8 @@ function initEchart(dataArr) {
series: [
{
type: "line",
name: "Subsidy (USD)",
name: "Daily Subsidy (USD)",
smooth: true,
stack: "Total",
areaStyle: {},
symbol: "none",
@ -121,7 +87,8 @@ function initEchart(dataArr) {
},
{
type: "line",
name: "Fees (USD)",
name: "Daily Fees (USD)",
smooth: true,
stack: "Total",
areaStyle: {},
symbol: "none",
@ -132,7 +99,8 @@ function initEchart(dataArr) {
},
{
type: "line",
name: "Total (USD)",
name: "Daily Total Reward (USD)",
smooth: true,
symbol: "none",
lineStyle: {
width: 1,
@ -156,14 +124,4 @@ function initEchart(dataArr) {
myChart.setOption(option);
}
document.addEventListener("DOMContentLoaded", function () {
let periodIndex = 2;
periodDropdown(periods, periodIndex);
fetchDataForChart(periods[periodIndex]);
const selectElement = document.getElementById("select-period-dropdown");
selectElement.addEventListener("change", function (event) {
const selectedValue = event.target.value;
fetchDataForChart(selectedValue);
});
});
fetchDataForChart();