Logistics management is the part of supply chain management and supply chain engineering that plans, implements, and controls the efficient, effective forward, and reverse flow and storage of goods, services, and related information between the point of origin and point of consumption to meet customer's requirements. The complexity of logistics can be modeled, analyzed, visualized, and optimized by dedicated simulation software. The resources managed in logistics may include tangible goods such as materials, equipment, and supplies, as well as food and other consumable items.
These software components cover functions across Courier, Delivery, Distribution, Postal, RFID, Supply Chain, Traceability, Warehouse Management areas.
Popular New Releases in Logistics
joplin
v2.8.2
lossless-cut
3.44.0
Vue-Socket.io
Vue-Socket.io 3.0.10
afwall
F-Droid Patch Release
trimesh
Release 3.10.8
Popular Libraries in Logistics
by laurent22 typescript
29233 NOASSERTION
Joplin - an open source note taking and to-do application with synchronization capabilities for Windows, macOS, Linux, Android and iOS.
by postalhq ruby
10570 MIT
📨 A fully featured open source mail delivery platform for incoming & outgoing e-mail
by mifi javascript
9993 GPL-2.0
The swiss army knife of lossless video/audio editing
by awslabs javascript
3733 Apache-2.0
Run serverless applications and REST APIs using your existing Node.js application framework, on top of AWS Lambda and Amazon API Gateway
by MetinSeylan javascript
3601 MIT
😻 Socket.io implementation for Vuejs and Vuex
by davidroyer javascript
2337 MIT
A text editor using Vue.js and Quill
by atulmy javascript
2216 MIT
👕 👖 📦 A sample web and mobile application built with Node, Express, React, React Native, Redux and GraphQL. Very basic replica of stitchfix.com / krate.in (allows users to get monthly subscription of trendy clothes and accessories).
by lirantal javascript
1899
Awesome Node.js Security resources
by ukanth java
1891 GPL-3.0
AFWall+ (Android Firewall +) - iptables based firewall for Android
Trending New libraries in Logistics
by MinaSamir11 javascript
409 MIT
The Google Play In-App Review API, App store rating API lets you prompt users to submit Play Store or App store ratings and reviews without the inconvenience of leaving your app or game.
by calvintwr javascript
93
A simple and fast module to automatically require all your express routes without bloating your code with `app.use('i/will/repeat/this', require('./i/will/repeat/this')`. 把 Express 路由图给自动化。
by SAP-samples css
65
Learn how to build a developer-centric SAP HANA command line tool, particularly designed to be used when performing SAP HANA development in non-SAP tooling (for example from VS Code).
by soerenmartius javascript
53 MIT
📋 clipboard.js bindings for Vue 3
by GoogleCloudPlatform java
52 Apache-2.0
Reference implementation for real-time Data Lineage tracking for BigQuery using Audit Logs, ZetaSQL and Dataflow.
by toomuchdesign javascript
46 MIT
Generate contextual routing / modal routes paths for Next.js
by build-security javascript
35 MIT
Node.JS Express middleware for working with the Open Policy Agent
by tobiasbernet javascript
33
by elit-altum javascript
32
A full stack webapp built using MongoDB, Express, ReactJS and Node to clone the social networking giant, Instagram! 📸
Top Authors in Logistics
1
4 Libraries
41
2
3 Libraries
44
3
3 Libraries
20
4
3 Libraries
20
5
3 Libraries
24
6
2 Libraries
37
7
2 Libraries
41
8
2 Libraries
115
9
2 Libraries
8
10
2 Libraries
12
1
4 Libraries
41
2
3 Libraries
44
3
3 Libraries
20
4
3 Libraries
20
5
3 Libraries
24
6
2 Libraries
37
7
2 Libraries
41
8
2 Libraries
115
9
2 Libraries
8
10
2 Libraries
12
Trending Kits in Logistics
Supply Chains have always been a critical differentiation to businesses. With the digital speed and pandemic situation, supply chain technologies have become more critical. This reflects in PanasonicÆs proposed acquisition of U.S. supply-chain software firm Blue Yonder (formerly JDA Software) for $7.1 Billion.
Manufacturers and retailers have to manage global supply chains with significant agility given the pandemic disruptions, geo-political dynamics, digital speed of innovation, consumer choices, and varying demand. Edge, AI, and Blockchain, in addition to traditional planning, forecasting, visibility, and transactional systems, are driving innovation in supply chain technologies.
kandi algorithms analyzed all public libraries available across Supply chain planning, Warehouse Management, and Transportation Management systems and found over a thousand libraries that you can reuse to enhance your supply chain technologies. We have picked nine unique and popular samples across the supply chain technology spectrum from this long list. The large-scale solutions on demand planning, inventory management, WMS, eCommerce, and blockchain are covered in the respective implementation collections.
Supply Chain for Good
Starting with the 'supply chain for good' use cases, pantry-for-good by freeCodeCamp provides food bank capability, while AgroChain by freeCodeCamp brings in microfinance to small vendors in the agricultural supply chain, and Responsible Supply Chain Management by CSRware helps monitor working conditions in the supply chain.
Inventory and WMS
openboxes by openboxes provides inventory management in health care, and waresys by kohlicekjan is a nifty warehouse management solution based on RFID and Raspberry Pi.
Transport Optimization
maro by microsoft, multimodal-transportation-optimization by hzjken, and IoT-AssetTracking-Perishable-Network-Blockchain by johnwalicki help optimize transportation operations.
Foundational Frameworks
If you need a foundation to build your use cases try ofbiz-framework by apache.
Trending Discussions on Logistics
Unable to bind Django application with Gunicorn
Loop through pattern matching schemas and tables in PostgreSQL
CODEIGNITER4: how to link value from table_1 to table_2 that I insert using SELECT OPTION tag
Calculate total difference of values between two timestamps
Query Search Algorithm using priority array and ignoring conditions
Python Pandas and Slack Webhooks Requests.post
Depth First Search in Directed Graph?
image as circle background (d3.js svg)
Select values that have a minus difference between two timestamps and show their complete history in the table
SpringBoot profiles with Gradle vs cloud
QUESTION
Unable to bind Django application with Gunicorn
Asked 2022-Mar-14 at 14:49It has been very difficult for me trying to deploy to aws EC2 ubuntu server SINCE I'm coming from windows background. I encounter an error while trying to bind django application to gunicorn. The command I'm running is sudo gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
And the error log is show below:
1(venv) ubuntu@ip-172-31-18-196:/var/www/html$ sudo gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
2[2021-09-08 11:21:00 +0000] [29379] [INFO] Starting gunicorn 20.1.0
3[2021-09-08 11:21:00 +0000] [29379] [INFO] Listening at: http://0.0.0.0:8000 (29379)
4[2021-09-08 11:21:00 +0000] [29379] [INFO] Using worker: sync
5[2021-09-08 11:21:00 +0000] [29382] [INFO] Booting worker with pid: 29382
6[2021-09-08 11:21:00 +0000] [29382] [ERROR] Exception in worker process
7Traceback (most recent call last):
8 File "/usr/local/lib/python3.5/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker
9 worker.init_process()
10 File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 134, in init_process
11 self.load_wsgi()
12 File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi
13 self.wsgi = self.app.wsgi()
14 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/base.py", line 67, in wsgi
15 self.callable = self.load()
16 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load
17 return self.load_wsgiapp()
18 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
19 return util.import_app(self.app_uri)
20 File "/usr/local/lib/python3.5/dist-packages/gunicorn/util.py", line 359, in import_app
21 mod = importlib.import_module(module)
22 File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
23 return _bootstrap._gcd_import(name[level:], package, level)
24 File "<frozen importlib._bootstrap>", line 986, in _gcd_import
25 File "<frozen importlib._bootstrap>", line 969, in _find_and_load
26 File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
27 File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
28 File "<frozen importlib._bootstrap_external>", line 665, in exec_module
29 File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
30 File "/var/www/html/logistics/wsgi.py", line 12, in <module>
31 from django.core.wsgi import get_wsgi_application
32 File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 2, in <module>
33 from django.core.handlers.wsgi import WSGIHandler
34 File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/wsgi.py", line 3, in <module>
35 from django.conf import settings
36 File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 19, in <module>
37 from django.utils.deprecation import RemovedInDjango40Warning
38 File "/usr/local/lib/python3.5/dist-packages/django/utils/deprecation.py", line 5, in <module>
39 from asgiref.sync import sync_to_async
40 File "/usr/local/lib/python3.5/dist-packages/asgiref/sync.py", line 115
41 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {}
42 ^
43SyntaxError: invalid syntax
44[2021-09-08 11:21:00 +0000] [29382] [INFO] Worker exiting (pid: 29382)
45[2021-09-08 11:21:00 +0000] [29379] [INFO] Shutting down: Master
46[2021-09-08 11:21:00 +0000] [29379] [INFO] Reason: Worker failed to boot.
47
When I run gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
, (that is, without sudo
) I get another error:
1(venv) ubuntu@ip-172-31-18-196:/var/www/html$ sudo gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
2[2021-09-08 11:21:00 +0000] [29379] [INFO] Starting gunicorn 20.1.0
3[2021-09-08 11:21:00 +0000] [29379] [INFO] Listening at: http://0.0.0.0:8000 (29379)
4[2021-09-08 11:21:00 +0000] [29379] [INFO] Using worker: sync
5[2021-09-08 11:21:00 +0000] [29382] [INFO] Booting worker with pid: 29382
6[2021-09-08 11:21:00 +0000] [29382] [ERROR] Exception in worker process
7Traceback (most recent call last):
8 File "/usr/local/lib/python3.5/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker
9 worker.init_process()
10 File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 134, in init_process
11 self.load_wsgi()
12 File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi
13 self.wsgi = self.app.wsgi()
14 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/base.py", line 67, in wsgi
15 self.callable = self.load()
16 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load
17 return self.load_wsgiapp()
18 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
19 return util.import_app(self.app_uri)
20 File "/usr/local/lib/python3.5/dist-packages/gunicorn/util.py", line 359, in import_app
21 mod = importlib.import_module(module)
22 File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
23 return _bootstrap._gcd_import(name[level:], package, level)
24 File "<frozen importlib._bootstrap>", line 986, in _gcd_import
25 File "<frozen importlib._bootstrap>", line 969, in _find_and_load
26 File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
27 File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
28 File "<frozen importlib._bootstrap_external>", line 665, in exec_module
29 File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
30 File "/var/www/html/logistics/wsgi.py", line 12, in <module>
31 from django.core.wsgi import get_wsgi_application
32 File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 2, in <module>
33 from django.core.handlers.wsgi import WSGIHandler
34 File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/wsgi.py", line 3, in <module>
35 from django.conf import settings
36 File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 19, in <module>
37 from django.utils.deprecation import RemovedInDjango40Warning
38 File "/usr/local/lib/python3.5/dist-packages/django/utils/deprecation.py", line 5, in <module>
39 from asgiref.sync import sync_to_async
40 File "/usr/local/lib/python3.5/dist-packages/asgiref/sync.py", line 115
41 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {}
42 ^
43SyntaxError: invalid syntax
44[2021-09-08 11:21:00 +0000] [29382] [INFO] Worker exiting (pid: 29382)
45[2021-09-08 11:21:00 +0000] [29379] [INFO] Shutting down: Master
46[2021-09-08 11:21:00 +0000] [29379] [INFO] Reason: Worker failed to boot.
47(venv) ubuntu@ip-172-31-18-196:/var/www/html$ gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
48Traceback (most recent call last):
49 File "/home/ubuntu/.local/bin/gunicorn", line 7, in <module>
50 from gunicorn.app.wsgiapp import run
51ModuleNotFoundError: No module named 'gunicorn'
52
But I have already install gunicorn with the command pip3 install gunicorn --user
. The reason why I added --user
at the end is that running pip3 install gunicorn
within the activated virtual enviroment is throwing back permission error as shown below:
1(venv) ubuntu@ip-172-31-18-196:/var/www/html$ sudo gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
2[2021-09-08 11:21:00 +0000] [29379] [INFO] Starting gunicorn 20.1.0
3[2021-09-08 11:21:00 +0000] [29379] [INFO] Listening at: http://0.0.0.0:8000 (29379)
4[2021-09-08 11:21:00 +0000] [29379] [INFO] Using worker: sync
5[2021-09-08 11:21:00 +0000] [29382] [INFO] Booting worker with pid: 29382
6[2021-09-08 11:21:00 +0000] [29382] [ERROR] Exception in worker process
7Traceback (most recent call last):
8 File "/usr/local/lib/python3.5/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker
9 worker.init_process()
10 File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 134, in init_process
11 self.load_wsgi()
12 File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi
13 self.wsgi = self.app.wsgi()
14 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/base.py", line 67, in wsgi
15 self.callable = self.load()
16 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load
17 return self.load_wsgiapp()
18 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
19 return util.import_app(self.app_uri)
20 File "/usr/local/lib/python3.5/dist-packages/gunicorn/util.py", line 359, in import_app
21 mod = importlib.import_module(module)
22 File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
23 return _bootstrap._gcd_import(name[level:], package, level)
24 File "<frozen importlib._bootstrap>", line 986, in _gcd_import
25 File "<frozen importlib._bootstrap>", line 969, in _find_and_load
26 File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
27 File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
28 File "<frozen importlib._bootstrap_external>", line 665, in exec_module
29 File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
30 File "/var/www/html/logistics/wsgi.py", line 12, in <module>
31 from django.core.wsgi import get_wsgi_application
32 File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 2, in <module>
33 from django.core.handlers.wsgi import WSGIHandler
34 File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/wsgi.py", line 3, in <module>
35 from django.conf import settings
36 File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 19, in <module>
37 from django.utils.deprecation import RemovedInDjango40Warning
38 File "/usr/local/lib/python3.5/dist-packages/django/utils/deprecation.py", line 5, in <module>
39 from asgiref.sync import sync_to_async
40 File "/usr/local/lib/python3.5/dist-packages/asgiref/sync.py", line 115
41 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {}
42 ^
43SyntaxError: invalid syntax
44[2021-09-08 11:21:00 +0000] [29382] [INFO] Worker exiting (pid: 29382)
45[2021-09-08 11:21:00 +0000] [29379] [INFO] Shutting down: Master
46[2021-09-08 11:21:00 +0000] [29379] [INFO] Reason: Worker failed to boot.
47(venv) ubuntu@ip-172-31-18-196:/var/www/html$ gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
48Traceback (most recent call last):
49 File "/home/ubuntu/.local/bin/gunicorn", line 7, in <module>
50 from gunicorn.app.wsgiapp import run
51ModuleNotFoundError: No module named 'gunicorn'
52(venv) ubuntu@ip-172-31-18-196:/var/www/html$ pip3 install gunicorn
53Collecting gunicorn
54 Using cached https://files.pythonhosted.org/packages/e4/dd/5b190393e6066286773a67dfcc2f9492058e9b57c4867a95f1ba5caf0a83/gunicorn-20.1.0-py3-none-any.whl
55Requirement already satisfied: setuptools>=3.0 in ./venv/lib/python3.6/site-packages (from gunicorn) (40.6.2)
56Installing collected packages: gunicorn
57Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/var/www/html/venv/lib/python3.6/site-packages/gunicorn-20.1.0.dist-info'
58Consider using the `--user` option or check the permissions.
59
60You are using pip version 18.1, however version 21.2.4 is available.
61You should consider upgrading via the 'pip install --upgrade pip' command.
62
Again, I have already upgraded from python3.5
to python3.6
such that when I run python3 on the terminal I get the following output
1(venv) ubuntu@ip-172-31-18-196:/var/www/html$ sudo gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
2[2021-09-08 11:21:00 +0000] [29379] [INFO] Starting gunicorn 20.1.0
3[2021-09-08 11:21:00 +0000] [29379] [INFO] Listening at: http://0.0.0.0:8000 (29379)
4[2021-09-08 11:21:00 +0000] [29379] [INFO] Using worker: sync
5[2021-09-08 11:21:00 +0000] [29382] [INFO] Booting worker with pid: 29382
6[2021-09-08 11:21:00 +0000] [29382] [ERROR] Exception in worker process
7Traceback (most recent call last):
8 File "/usr/local/lib/python3.5/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker
9 worker.init_process()
10 File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 134, in init_process
11 self.load_wsgi()
12 File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi
13 self.wsgi = self.app.wsgi()
14 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/base.py", line 67, in wsgi
15 self.callable = self.load()
16 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load
17 return self.load_wsgiapp()
18 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
19 return util.import_app(self.app_uri)
20 File "/usr/local/lib/python3.5/dist-packages/gunicorn/util.py", line 359, in import_app
21 mod = importlib.import_module(module)
22 File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
23 return _bootstrap._gcd_import(name[level:], package, level)
24 File "<frozen importlib._bootstrap>", line 986, in _gcd_import
25 File "<frozen importlib._bootstrap>", line 969, in _find_and_load
26 File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
27 File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
28 File "<frozen importlib._bootstrap_external>", line 665, in exec_module
29 File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
30 File "/var/www/html/logistics/wsgi.py", line 12, in <module>
31 from django.core.wsgi import get_wsgi_application
32 File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 2, in <module>
33 from django.core.handlers.wsgi import WSGIHandler
34 File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/wsgi.py", line 3, in <module>
35 from django.conf import settings
36 File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 19, in <module>
37 from django.utils.deprecation import RemovedInDjango40Warning
38 File "/usr/local/lib/python3.5/dist-packages/django/utils/deprecation.py", line 5, in <module>
39 from asgiref.sync import sync_to_async
40 File "/usr/local/lib/python3.5/dist-packages/asgiref/sync.py", line 115
41 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {}
42 ^
43SyntaxError: invalid syntax
44[2021-09-08 11:21:00 +0000] [29382] [INFO] Worker exiting (pid: 29382)
45[2021-09-08 11:21:00 +0000] [29379] [INFO] Shutting down: Master
46[2021-09-08 11:21:00 +0000] [29379] [INFO] Reason: Worker failed to boot.
47(venv) ubuntu@ip-172-31-18-196:/var/www/html$ gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
48Traceback (most recent call last):
49 File "/home/ubuntu/.local/bin/gunicorn", line 7, in <module>
50 from gunicorn.app.wsgiapp import run
51ModuleNotFoundError: No module named 'gunicorn'
52(venv) ubuntu@ip-172-31-18-196:/var/www/html$ pip3 install gunicorn
53Collecting gunicorn
54 Using cached https://files.pythonhosted.org/packages/e4/dd/5b190393e6066286773a67dfcc2f9492058e9b57c4867a95f1ba5caf0a83/gunicorn-20.1.0-py3-none-any.whl
55Requirement already satisfied: setuptools>=3.0 in ./venv/lib/python3.6/site-packages (from gunicorn) (40.6.2)
56Installing collected packages: gunicorn
57Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/var/www/html/venv/lib/python3.6/site-packages/gunicorn-20.1.0.dist-info'
58Consider using the `--user` option or check the permissions.
59
60You are using pip version 18.1, however version 21.2.4 is available.
61You should consider upgrading via the 'pip install --upgrade pip' command.
62(venv) ubuntu@ip-172-31-18-196:/var/www/html$ python3 --version
63Python 3.6.13
64
Yet, I don't know why the error log is making reference to python3.5 instead of python3.6 as shown here: File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py"
whenever I run sudo gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
Please I want to know why I'm getting that error
ANSWER
Answered 2022-Mar-14 at 14:49You have to login as Ubuntu
user and NOT sudo su/root
Stage 1: Binding your Gunicorn to your Django app and checking if the upstream gunicorn is working fine. Please note the deployment is incomplete without other stages
sudo apt-get update
sudo apt-get upgrade
Optional - If it shows a popup/options then just select the pkg maintainer version.
python3 -m venv env
sudo apt-get install python3-venv
source env/bin/activate
pip3 install django
git clone <your-repo-url>
pip3 install gunicorn
sudo apt-get install -y nginx
cd
to your project directory wheresettings.py
,db.sqlite3
and all those files of your project is stored.pip3 install -r requirements.txt
gunicorn --bind 0.0.0.0:8000 <project_name>.wsgi:application
Note: your project name is the main app name which you created in the beginning withdjango-admin startproject <project_name>
commandYou will see
1(venv) ubuntu@ip-172-31-18-196:/var/www/html$ sudo gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
2[2021-09-08 11:21:00 +0000] [29379] [INFO] Starting gunicorn 20.1.0
3[2021-09-08 11:21:00 +0000] [29379] [INFO] Listening at: http://0.0.0.0:8000 (29379)
4[2021-09-08 11:21:00 +0000] [29379] [INFO] Using worker: sync
5[2021-09-08 11:21:00 +0000] [29382] [INFO] Booting worker with pid: 29382
6[2021-09-08 11:21:00 +0000] [29382] [ERROR] Exception in worker process
7Traceback (most recent call last):
8 File "/usr/local/lib/python3.5/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker
9 worker.init_process()
10 File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 134, in init_process
11 self.load_wsgi()
12 File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi
13 self.wsgi = self.app.wsgi()
14 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/base.py", line 67, in wsgi
15 self.callable = self.load()
16 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load
17 return self.load_wsgiapp()
18 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
19 return util.import_app(self.app_uri)
20 File "/usr/local/lib/python3.5/dist-packages/gunicorn/util.py", line 359, in import_app
21 mod = importlib.import_module(module)
22 File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
23 return _bootstrap._gcd_import(name[level:], package, level)
24 File "<frozen importlib._bootstrap>", line 986, in _gcd_import
25 File "<frozen importlib._bootstrap>", line 969, in _find_and_load
26 File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
27 File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
28 File "<frozen importlib._bootstrap_external>", line 665, in exec_module
29 File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
30 File "/var/www/html/logistics/wsgi.py", line 12, in <module>
31 from django.core.wsgi import get_wsgi_application
32 File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 2, in <module>
33 from django.core.handlers.wsgi import WSGIHandler
34 File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/wsgi.py", line 3, in <module>
35 from django.conf import settings
36 File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 19, in <module>
37 from django.utils.deprecation import RemovedInDjango40Warning
38 File "/usr/local/lib/python3.5/dist-packages/django/utils/deprecation.py", line 5, in <module>
39 from asgiref.sync import sync_to_async
40 File "/usr/local/lib/python3.5/dist-packages/asgiref/sync.py", line 115
41 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {}
42 ^
43SyntaxError: invalid syntax
44[2021-09-08 11:21:00 +0000] [29382] [INFO] Worker exiting (pid: 29382)
45[2021-09-08 11:21:00 +0000] [29379] [INFO] Shutting down: Master
46[2021-09-08 11:21:00 +0000] [29379] [INFO] Reason: Worker failed to boot.
47(venv) ubuntu@ip-172-31-18-196:/var/www/html$ gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
48Traceback (most recent call last):
49 File "/home/ubuntu/.local/bin/gunicorn", line 7, in <module>
50 from gunicorn.app.wsgiapp import run
51ModuleNotFoundError: No module named 'gunicorn'
52(venv) ubuntu@ip-172-31-18-196:/var/www/html$ pip3 install gunicorn
53Collecting gunicorn
54 Using cached https://files.pythonhosted.org/packages/e4/dd/5b190393e6066286773a67dfcc2f9492058e9b57c4867a95f1ba5caf0a83/gunicorn-20.1.0-py3-none-any.whl
55Requirement already satisfied: setuptools>=3.0 in ./venv/lib/python3.6/site-packages (from gunicorn) (40.6.2)
56Installing collected packages: gunicorn
57Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/var/www/html/venv/lib/python3.6/site-packages/gunicorn-20.1.0.dist-info'
58Consider using the `--user` option or check the permissions.
59
60You are using pip version 18.1, however version 21.2.4 is available.
61You should consider upgrading via the 'pip install --upgrade pip' command.
62(venv) ubuntu@ip-172-31-18-196:/var/www/html$ python3 --version
63Python 3.6.13
64[2021-09-08 15:20:17 +0000] [12789] [INFO] Starting gunicorn 20.1.0
65[2021-09-08 15:20:17 +0000] [12789] [INFO] Listening at: http://0.0.0.0:8000 (12789)
66[2021-09-08 15:20:17 +0000] [12789] [INFO] Using worker: sync
67[2021-09-08 15:20:17 +0000] [12791] [INFO] Booting worker with pid: 12791
68
which means you have successfully bonded your gunicorn to run your Django app and your Django app is now ready to get linked with a webserver (NGINX in our case). This marks the completion of Stage 1.
To test out Stage 1 success you can type in your IP with port :8000
and see your application run (make sure your aws security is allowing port 8000 else you will see a 404) but the above Booting worker with pid confirms that it's working.
Stage 2: Setting up supervisor
so that your Gunicors autostarts your Django app on reboot and after first boot.
sudo apt-get install -y supervisor
cd /etc/supervisor/conf.d/
sudo touch gunicorn.conf
sudo nano gunicorn.conf
This will open up an editor where you have to type in the script for gunicorn (The bind which we did in Stage 1 but now we are telling supervisor to bind gunicorn every time the server/instance start)
1(venv) ubuntu@ip-172-31-18-196:/var/www/html$ sudo gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
2[2021-09-08 11:21:00 +0000] [29379] [INFO] Starting gunicorn 20.1.0
3[2021-09-08 11:21:00 +0000] [29379] [INFO] Listening at: http://0.0.0.0:8000 (29379)
4[2021-09-08 11:21:00 +0000] [29379] [INFO] Using worker: sync
5[2021-09-08 11:21:00 +0000] [29382] [INFO] Booting worker with pid: 29382
6[2021-09-08 11:21:00 +0000] [29382] [ERROR] Exception in worker process
7Traceback (most recent call last):
8 File "/usr/local/lib/python3.5/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker
9 worker.init_process()
10 File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 134, in init_process
11 self.load_wsgi()
12 File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi
13 self.wsgi = self.app.wsgi()
14 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/base.py", line 67, in wsgi
15 self.callable = self.load()
16 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load
17 return self.load_wsgiapp()
18 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
19 return util.import_app(self.app_uri)
20 File "/usr/local/lib/python3.5/dist-packages/gunicorn/util.py", line 359, in import_app
21 mod = importlib.import_module(module)
22 File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
23 return _bootstrap._gcd_import(name[level:], package, level)
24 File "<frozen importlib._bootstrap>", line 986, in _gcd_import
25 File "<frozen importlib._bootstrap>", line 969, in _find_and_load
26 File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
27 File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
28 File "<frozen importlib._bootstrap_external>", line 665, in exec_module
29 File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
30 File "/var/www/html/logistics/wsgi.py", line 12, in <module>
31 from django.core.wsgi import get_wsgi_application
32 File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 2, in <module>
33 from django.core.handlers.wsgi import WSGIHandler
34 File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/wsgi.py", line 3, in <module>
35 from django.conf import settings
36 File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 19, in <module>
37 from django.utils.deprecation import RemovedInDjango40Warning
38 File "/usr/local/lib/python3.5/dist-packages/django/utils/deprecation.py", line 5, in <module>
39 from asgiref.sync import sync_to_async
40 File "/usr/local/lib/python3.5/dist-packages/asgiref/sync.py", line 115
41 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {}
42 ^
43SyntaxError: invalid syntax
44[2021-09-08 11:21:00 +0000] [29382] [INFO] Worker exiting (pid: 29382)
45[2021-09-08 11:21:00 +0000] [29379] [INFO] Shutting down: Master
46[2021-09-08 11:21:00 +0000] [29379] [INFO] Reason: Worker failed to boot.
47(venv) ubuntu@ip-172-31-18-196:/var/www/html$ gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
48Traceback (most recent call last):
49 File "/home/ubuntu/.local/bin/gunicorn", line 7, in <module>
50 from gunicorn.app.wsgiapp import run
51ModuleNotFoundError: No module named 'gunicorn'
52(venv) ubuntu@ip-172-31-18-196:/var/www/html$ pip3 install gunicorn
53Collecting gunicorn
54 Using cached https://files.pythonhosted.org/packages/e4/dd/5b190393e6066286773a67dfcc2f9492058e9b57c4867a95f1ba5caf0a83/gunicorn-20.1.0-py3-none-any.whl
55Requirement already satisfied: setuptools>=3.0 in ./venv/lib/python3.6/site-packages (from gunicorn) (40.6.2)
56Installing collected packages: gunicorn
57Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/var/www/html/venv/lib/python3.6/site-packages/gunicorn-20.1.0.dist-info'
58Consider using the `--user` option or check the permissions.
59
60You are using pip version 18.1, however version 21.2.4 is available.
61You should consider upgrading via the 'pip install --upgrade pip' command.
62(venv) ubuntu@ip-172-31-18-196:/var/www/html$ python3 --version
63Python 3.6.13
64[2021-09-08 15:20:17 +0000] [12789] [INFO] Starting gunicorn 20.1.0
65[2021-09-08 15:20:17 +0000] [12789] [INFO] Listening at: http://0.0.0.0:8000 (12789)
66[2021-09-08 15:20:17 +0000] [12789] [INFO] Using worker: sync
67[2021-09-08 15:20:17 +0000] [12791] [INFO] Booting worker with pid: 12791
68 [program:gunicorn]
69 directory = /home/ubuntu/<path to manage.py>
70 command = /home/ubuntu/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/<App Directory>/app.sock <App Name>.wsgi:application
71 autostart = true
72 autorestart = true
73 stderr_logfile = /var/log/gunicorn/gunicorn.err.log
74 stdout_logfile = /var/log/gunicorn/gunicorn.out.log
75
76 [group:guni]
77 programs:gunicorn
78
sudo mkdir /var/log/gunicorn
, here we are creating the log folder for our gunicorn out and error logs.
sudo supervisorctl reread
If you see guni:available
here it means your supervisor is all set and you have properly done everything till now.
sudo supervisorctl update
if you see guni: added process group
this is another marker that you have properly done the steps.
sudo supervisorctl status
If you see guni:gunicorn RUNNING
this is the third and final indicator that your gunicorn is now properly set up.
After all these steps it is confirmed that your gunicorn is now bi-directionally communicating to an app.sock
file which is automatically created inside your project directory.
Stage 3: Final step to link your Gunicorn upstream server to your NGINX
cd /etc/nginx/sites-available
sudo touch django.conf
sudo nano django.conf
This will open up your nano editor where you have to type in these exact server settings.
1(venv) ubuntu@ip-172-31-18-196:/var/www/html$ sudo gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
2[2021-09-08 11:21:00 +0000] [29379] [INFO] Starting gunicorn 20.1.0
3[2021-09-08 11:21:00 +0000] [29379] [INFO] Listening at: http://0.0.0.0:8000 (29379)
4[2021-09-08 11:21:00 +0000] [29379] [INFO] Using worker: sync
5[2021-09-08 11:21:00 +0000] [29382] [INFO] Booting worker with pid: 29382
6[2021-09-08 11:21:00 +0000] [29382] [ERROR] Exception in worker process
7Traceback (most recent call last):
8 File "/usr/local/lib/python3.5/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker
9 worker.init_process()
10 File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 134, in init_process
11 self.load_wsgi()
12 File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi
13 self.wsgi = self.app.wsgi()
14 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/base.py", line 67, in wsgi
15 self.callable = self.load()
16 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load
17 return self.load_wsgiapp()
18 File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
19 return util.import_app(self.app_uri)
20 File "/usr/local/lib/python3.5/dist-packages/gunicorn/util.py", line 359, in import_app
21 mod = importlib.import_module(module)
22 File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
23 return _bootstrap._gcd_import(name[level:], package, level)
24 File "<frozen importlib._bootstrap>", line 986, in _gcd_import
25 File "<frozen importlib._bootstrap>", line 969, in _find_and_load
26 File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
27 File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
28 File "<frozen importlib._bootstrap_external>", line 665, in exec_module
29 File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
30 File "/var/www/html/logistics/wsgi.py", line 12, in <module>
31 from django.core.wsgi import get_wsgi_application
32 File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 2, in <module>
33 from django.core.handlers.wsgi import WSGIHandler
34 File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/wsgi.py", line 3, in <module>
35 from django.conf import settings
36 File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 19, in <module>
37 from django.utils.deprecation import RemovedInDjango40Warning
38 File "/usr/local/lib/python3.5/dist-packages/django/utils/deprecation.py", line 5, in <module>
39 from asgiref.sync import sync_to_async
40 File "/usr/local/lib/python3.5/dist-packages/asgiref/sync.py", line 115
41 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {}
42 ^
43SyntaxError: invalid syntax
44[2021-09-08 11:21:00 +0000] [29382] [INFO] Worker exiting (pid: 29382)
45[2021-09-08 11:21:00 +0000] [29379] [INFO] Shutting down: Master
46[2021-09-08 11:21:00 +0000] [29379] [INFO] Reason: Worker failed to boot.
47(venv) ubuntu@ip-172-31-18-196:/var/www/html$ gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application
48Traceback (most recent call last):
49 File "/home/ubuntu/.local/bin/gunicorn", line 7, in <module>
50 from gunicorn.app.wsgiapp import run
51ModuleNotFoundError: No module named 'gunicorn'
52(venv) ubuntu@ip-172-31-18-196:/var/www/html$ pip3 install gunicorn
53Collecting gunicorn
54 Using cached https://files.pythonhosted.org/packages/e4/dd/5b190393e6066286773a67dfcc2f9492058e9b57c4867a95f1ba5caf0a83/gunicorn-20.1.0-py3-none-any.whl
55Requirement already satisfied: setuptools>=3.0 in ./venv/lib/python3.6/site-packages (from gunicorn) (40.6.2)
56Installing collected packages: gunicorn
57Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/var/www/html/venv/lib/python3.6/site-packages/gunicorn-20.1.0.dist-info'
58Consider using the `--user` option or check the permissions.
59
60You are using pip version 18.1, however version 21.2.4 is available.
61You should consider upgrading via the 'pip install --upgrade pip' command.
62(venv) ubuntu@ip-172-31-18-196:/var/www/html$ python3 --version
63Python 3.6.13
64[2021-09-08 15:20:17 +0000] [12789] [INFO] Starting gunicorn 20.1.0
65[2021-09-08 15:20:17 +0000] [12789] [INFO] Listening at: http://0.0.0.0:8000 (12789)
66[2021-09-08 15:20:17 +0000] [12789] [INFO] Using worker: sync
67[2021-09-08 15:20:17 +0000] [12791] [INFO] Booting worker with pid: 12791
68 [program:gunicorn]
69 directory = /home/ubuntu/<path to manage.py>
70 command = /home/ubuntu/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/<App Directory>/app.sock <App Name>.wsgi:application
71 autostart = true
72 autorestart = true
73 stderr_logfile = /var/log/gunicorn/gunicorn.err.log
74 stdout_logfile = /var/log/gunicorn/gunicorn.out.log
75
76 [group:guni]
77 programs:gunicorn
78server {
79 listen 80;
80 server_name <ipaddress or domain name> ;
81 #server_name 192.168.0.1 yourdomain.com your_alternate_domain.com; this is how you can add multiple hosts. Do not add any comma just separate it with spaces
82
83 location / {
84 include proxy_params;
85 proxy_pass http://unix:/home/ubuntu/Appdir/app.sock;
86 }
87}
88
sudo nginx -t
(This will test the syntax of your config file)
sudo ln django.conf /etc/nginx/sites-enabled/
<---- this is a very crucial step make sure there is not typing mistake here, it creates a symlink
sudo nginx -t
sudo service nginx restart
With this you now have linked your Nginx to your gunicorn upstream on app.sock so head on to your browser and type in the IP address of your instance and you will see your app live.
If you can see your website without any CSS then you have followed everything properly, I will re-edit my answer on how to serve static files of your Django app in Nginx once you confirm that everything works.
QUESTION
Loop through pattern matching schemas and tables in PostgreSQL
Asked 2022-Feb-21 at 03:22I have 20 schemas that follow an ending pattern depending on the office, that is the name of the office followed by '_finance', '_security' etc and it would something like this:
- new_york_office_finance
- boston_office_finance
- new_york_office_security
- boston_office_security
- etc
In addition, all the tables inside the schemas have the same table names.
- staff
- logistics
- Etc
How can I select only the schemas that end in '_finance' and the tables 'logistics' from all those schemas?
ANSWER
Answered 2022-Feb-21 at 03:22You can create sql's by querying information_schema.table like this:
1select 'select <column_list> from '||table_name||' where ... <conditions> ;' from information_schema.tables where table_name='logistics' and table_schema like '%\_finance';
2
Example: To query a table tbl in a schema having name starting with demo
1select 'select <column_list> from '||table_name||' where ... <conditions> ;' from information_schema.tables where table_name='logistics' and table_schema like '%\_finance';
2postgres=# select table_schema, 'select <column_list> from '||table_name||' where ... <conditions> ;' from information_schema.tables where table_name ='tbl' and table_schema like 'demo\_%';
3 table_schema | ?column?
4--------------+--------------------------------------------------------
5 demo_schema | select <column_list> from tbl where ... <conditions> ;
6(1 row)
7
8
QUESTION
CODEIGNITER4: how to link value from table_1 to table_2 that I insert using SELECT OPTION tag
Asked 2022-Feb-10 at 14:21See I have 2 tables tbl_office and tbl_result
1| id | office_name | | id | office | rating | comment |
2|----|-------------| |----|-------------|-----------|---------|
3| 1 | Records | | 1 | Records | Satisfied | |
4| 2 | Logistics | | 2 | Logistics | Satisfied | |
5| 3 | HR | | 3 | HR | Neutral | |
6
i used a SELECT OPTION tag on my form to get the row value of office_name from tbl_office
CONTROLLER
1| id | office_name | | id | office | rating | comment |
2|----|-------------| |----|-------------|-----------|---------|
3| 1 | Records | | 1 | Records | Satisfied | |
4| 2 | Logistics | | 2 | Logistics | Satisfied | |
5| 3 | HR | | 3 | HR | Neutral | |
6namespace App\Controllers;
7use App\Models\SurveyModel;
8use App\Models\OfficeMOdel;
9
10class Survey extends BaseController
11{
12 public function index()
13 {
14 $data = [];
15 helper(['form','url']);
16
17 $office = new OfficeMOdel();
18 $data['office'] = $office->findAll();
19
20
21 if($this->request->getMethod() == 'post'){
22
23 $rules = [
24 'office' => ['label' => 'Office', 'rules' => 'required'],
25 'rating' => ['label' => 'Rating', 'rules' => 'required']
26 ];
27
28 if (!$this->validate($rules)){
29 $data['validation'] = $this->validator;
30 }else{
31 $model = new SurveyModel();
32
33 $newData = [
34 'office' => $this->request->getVar('office'),
35 'rating' => $this->request->getVar('rating'),
36 'comment' => $this->request->getVar('comment'),
37 ];
38
39 $model->save($newData);
40 $session = session();
41 $session->setFlashdata('success','Your Feedback has been successfully added to our system!',);
42
43 return redirect()->to('survey/confirmation');
44 }
45 }
46
47 echo view ('templates/header_form', $data);
48 echo view ('surveyform');
49 echo view ('templates/footer_form');
50 }
51
PHP/HTML for displaying the values of office_name
1| id | office_name | | id | office | rating | comment |
2|----|-------------| |----|-------------|-----------|---------|
3| 1 | Records | | 1 | Records | Satisfied | |
4| 2 | Logistics | | 2 | Logistics | Satisfied | |
5| 3 | HR | | 3 | HR | Neutral | |
6namespace App\Controllers;
7use App\Models\SurveyModel;
8use App\Models\OfficeMOdel;
9
10class Survey extends BaseController
11{
12 public function index()
13 {
14 $data = [];
15 helper(['form','url']);
16
17 $office = new OfficeMOdel();
18 $data['office'] = $office->findAll();
19
20
21 if($this->request->getMethod() == 'post'){
22
23 $rules = [
24 'office' => ['label' => 'Office', 'rules' => 'required'],
25 'rating' => ['label' => 'Rating', 'rules' => 'required']
26 ];
27
28 if (!$this->validate($rules)){
29 $data['validation'] = $this->validator;
30 }else{
31 $model = new SurveyModel();
32
33 $newData = [
34 'office' => $this->request->getVar('office'),
35 'rating' => $this->request->getVar('rating'),
36 'comment' => $this->request->getVar('comment'),
37 ];
38
39 $model->save($newData);
40 $session = session();
41 $session->setFlashdata('success','Your Feedback has been successfully added to our system!',);
42
43 return redirect()->to('survey/confirmation');
44 }
45 }
46
47 echo view ('templates/header_form', $data);
48 echo view ('surveyform');
49 echo view ('templates/footer_form');
50 }
51<select name="office">
52
53 <?php foreach($office as $row) :?>
54 <option><?php echo $row['office_name'] ?></option>
55 <?php endforeach; ?>
56
57</select>
58
IT WORKS, but when I update the value from office_name from tbl_office, the value on the tbl_result does not change. Is there a way to link those value instead of just getting the value of the option when i insert it to the other table?
Thank you so much for answering. Beginner here.
ANSWER
Answered 2022-Feb-10 at 14:21You should not store office
name in your tbl_result
. Instead this you should to store office_id:
1| id | office_name | | id | office | rating | comment |
2|----|-------------| |----|-------------|-----------|---------|
3| 1 | Records | | 1 | Records | Satisfied | |
4| 2 | Logistics | | 2 | Logistics | Satisfied | |
5| 3 | HR | | 3 | HR | Neutral | |
6namespace App\Controllers;
7use App\Models\SurveyModel;
8use App\Models\OfficeMOdel;
9
10class Survey extends BaseController
11{
12 public function index()
13 {
14 $data = [];
15 helper(['form','url']);
16
17 $office = new OfficeMOdel();
18 $data['office'] = $office->findAll();
19
20
21 if($this->request->getMethod() == 'post'){
22
23 $rules = [
24 'office' => ['label' => 'Office', 'rules' => 'required'],
25 'rating' => ['label' => 'Rating', 'rules' => 'required']
26 ];
27
28 if (!$this->validate($rules)){
29 $data['validation'] = $this->validator;
30 }else{
31 $model = new SurveyModel();
32
33 $newData = [
34 'office' => $this->request->getVar('office'),
35 'rating' => $this->request->getVar('rating'),
36 'comment' => $this->request->getVar('comment'),
37 ];
38
39 $model->save($newData);
40 $session = session();
41 $session->setFlashdata('success','Your Feedback has been successfully added to our system!',);
42
43 return redirect()->to('survey/confirmation');
44 }
45 }
46
47 echo view ('templates/header_form', $data);
48 echo view ('surveyform');
49 echo view ('templates/footer_form');
50 }
51<select name="office">
52
53 <?php foreach($office as $row) :?>
54 <option><?php echo $row['office_name'] ?></option>
55 <?php endforeach; ?>
56
57</select>
58CREATE TABLE `tbl_office` (
59 id int primary key auto_increment,
60 name varchar(64)
61);
62
63CREATE TABLE `tbl_rating` (
64 id int primary key auto_increment,
65 name varchar(64)
66);
67
68CREATE TABLE `tbl_result` (
69 id int primary key auto_increment,
70 office_id int,
71 rating_id int,
72 comment text
73);
74
75SELECT `res`.`id`, `o`.`name` AS `office`, `r`.`name` AS `rating`, `comment`
76FROM `tbl_result` `res`
77JOIN `tbl_office` `o` ON `o`.`id` = `res`.`office_id`
78JOIN `tbl_rating` `r` ON `r`.`id` = `res`.`rating_id`
79
1| id | office_name | | id | office | rating | comment |
2|----|-------------| |----|-------------|-----------|---------|
3| 1 | Records | | 1 | Records | Satisfied | |
4| 2 | Logistics | | 2 | Logistics | Satisfied | |
5| 3 | HR | | 3 | HR | Neutral | |
6namespace App\Controllers;
7use App\Models\SurveyModel;
8use App\Models\OfficeMOdel;
9
10class Survey extends BaseController
11{
12 public function index()
13 {
14 $data = [];
15 helper(['form','url']);
16
17 $office = new OfficeMOdel();
18 $data['office'] = $office->findAll();
19
20
21 if($this->request->getMethod() == 'post'){
22
23 $rules = [
24 'office' => ['label' => 'Office', 'rules' => 'required'],
25 'rating' => ['label' => 'Rating', 'rules' => 'required']
26 ];
27
28 if (!$this->validate($rules)){
29 $data['validation'] = $this->validator;
30 }else{
31 $model = new SurveyModel();
32
33 $newData = [
34 'office' => $this->request->getVar('office'),
35 'rating' => $this->request->getVar('rating'),
36 'comment' => $this->request->getVar('comment'),
37 ];
38
39 $model->save($newData);
40 $session = session();
41 $session->setFlashdata('success','Your Feedback has been successfully added to our system!',);
42
43 return redirect()->to('survey/confirmation');
44 }
45 }
46
47 echo view ('templates/header_form', $data);
48 echo view ('surveyform');
49 echo view ('templates/footer_form');
50 }
51<select name="office">
52
53 <?php foreach($office as $row) :?>
54 <option><?php echo $row['office_name'] ?></option>
55 <?php endforeach; ?>
56
57</select>
58CREATE TABLE `tbl_office` (
59 id int primary key auto_increment,
60 name varchar(64)
61);
62
63CREATE TABLE `tbl_rating` (
64 id int primary key auto_increment,
65 name varchar(64)
66);
67
68CREATE TABLE `tbl_result` (
69 id int primary key auto_increment,
70 office_id int,
71 rating_id int,
72 comment text
73);
74
75SELECT `res`.`id`, `o`.`name` AS `office`, `r`.`name` AS `rating`, `comment`
76FROM `tbl_result` `res`
77JOIN `tbl_office` `o` ON `o`.`id` = `res`.`office_id`
78JOIN `tbl_rating` `r` ON `r`.`id` = `res`.`rating_id`
79+====+===========+===========+=========+
80| id | office | rating | comment |
81+====+===========+===========+=========+
82| 1 | Records | Satisfied | (null) |
83+----+-----------+-----------+---------+
84| 2 | Logistics | Satisfied | (null) |
85+----+-----------+-----------+---------+
86| 3 | HR | Neutral | (null) |
87+----+-----------+-----------+---------+
88
QUESTION
Calculate total difference of values between two timestamps
Asked 2022-Jan-19 at 09:081CREATE TABLE logistics (
2 id SERIAL PRIMARY KEY,
3 time_stamp DATE,
4 product VARCHAR(255),
5 quantity INT
6);
7
8INSERT INTO logistics
9(time_stamp, product, quantity)
10VALUES
11('2020-01-14', 'Product_A', '100'),
12('2020-01-14', 'Product_B', '300'),
13
14('2020-01-15', 'Product_B', '400'),
15('2020-01-15', 'Product_C', '350'),
16
17('2020-01-16', 'Product_B', '530'),
18('2020-01-16', 'Product_C', '350'),
19('2020-01-16', 'Product_D', '670'),
20
21('2020-01-17', 'Product_C', '500'),
22('2020-01-17', 'Product_D', '980'),
23('2020-01-17', 'Product_E', '700'),
24('2020-01-17', 'Product_F', '450');
25
Expected Result:
1CREATE TABLE logistics (
2 id SERIAL PRIMARY KEY,
3 time_stamp DATE,
4 product VARCHAR(255),
5 quantity INT
6);
7
8INSERT INTO logistics
9(time_stamp, product, quantity)
10VALUES
11('2020-01-14', 'Product_A', '100'),
12('2020-01-14', 'Product_B', '300'),
13
14('2020-01-15', 'Product_B', '400'),
15('2020-01-15', 'Product_C', '350'),
16
17('2020-01-16', 'Product_B', '530'),
18('2020-01-16', 'Product_C', '350'),
19('2020-01-16', 'Product_D', '670'),
20
21('2020-01-17', 'Product_C', '500'),
22('2020-01-17', 'Product_D', '980'),
23('2020-01-17', 'Product_E', '700'),
24('2020-01-17', 'Product_F', '450');
25time_stamp | difference | info
26------------|----------------|--------------------------------------
272020-01-14 | 400 | =(100+300)
282020-01-15 | 350 | =(400+350)-(300+100)
292020-01-16 | 800 | =(530+350+670)-(400+350)
302020-01-17 | 1080 | =(500+980+700+450)-(530+350+670)
31
I want to calculate the total difference of the quantity
between two timestamps
.
Therefore, I tried to use the query from this question:
1CREATE TABLE logistics (
2 id SERIAL PRIMARY KEY,
3 time_stamp DATE,
4 product VARCHAR(255),
5 quantity INT
6);
7
8INSERT INTO logistics
9(time_stamp, product, quantity)
10VALUES
11('2020-01-14', 'Product_A', '100'),
12('2020-01-14', 'Product_B', '300'),
13
14('2020-01-15', 'Product_B', '400'),
15('2020-01-15', 'Product_C', '350'),
16
17('2020-01-16', 'Product_B', '530'),
18('2020-01-16', 'Product_C', '350'),
19('2020-01-16', 'Product_D', '670'),
20
21('2020-01-17', 'Product_C', '500'),
22('2020-01-17', 'Product_D', '980'),
23('2020-01-17', 'Product_E', '700'),
24('2020-01-17', 'Product_F', '450');
25time_stamp | difference | info
26------------|----------------|--------------------------------------
272020-01-14 | 400 | =(100+300)
282020-01-15 | 350 | =(400+350)-(300+100)
292020-01-16 | 800 | =(530+350+670)-(400+350)
302020-01-17 | 1080 | =(500+980+700+450)-(530+350+670)
31SELECT
32t1.time_stamp AS time_stamp,
33t1.quantity AS quantity,
34COALESCE(t1.quantity-LAG(t1.quantity) OVER (PARTITION BY t1.time_stamp ORDER BY t1.time_stamp), t1.quantity) AS difference
35FROM
36
37 (SELECT
38 l.time_stamp AS time_stamp,
39 SUM(l.quantity) AS quantity
40 FROM logistics l
41 GROUP BY 1
42 ORDER BY 1) t1
43
44GROUP BY 1,2
45ORDER BY 1,2;
46
However, I am not able to get the expected result.
What do I need to change to make it work?
ANSWER
Answered 2022-Jan-18 at 10:22You can remove the PARTITION BY
in the LAG
function.
If the "product" column was part of the result.
Then PARTITION BY product
would make sense.
But since that's not the case, the ORDER BY t1.time_stamp
is sufficient.
1CREATE TABLE logistics (
2 id SERIAL PRIMARY KEY,
3 time_stamp DATE,
4 product VARCHAR(255),
5 quantity INT
6);
7
8INSERT INTO logistics
9(time_stamp, product, quantity)
10VALUES
11('2020-01-14', 'Product_A', '100'),
12('2020-01-14', 'Product_B', '300'),
13
14('2020-01-15', 'Product_B', '400'),
15('2020-01-15', 'Product_C', '350'),
16
17('2020-01-16', 'Product_B', '530'),
18('2020-01-16', 'Product_C', '350'),
19('2020-01-16', 'Product_D', '670'),
20
21('2020-01-17', 'Product_C', '500'),
22('2020-01-17', 'Product_D', '980'),
23('2020-01-17', 'Product_E', '700'),
24('2020-01-17', 'Product_F', '450');
25time_stamp | difference | info
26------------|----------------|--------------------------------------
272020-01-14 | 400 | =(100+300)
282020-01-15 | 350 | =(400+350)-(300+100)
292020-01-16 | 800 | =(530+350+670)-(400+350)
302020-01-17 | 1080 | =(500+980+700+450)-(530+350+670)
31SELECT
32t1.time_stamp AS time_stamp,
33t1.quantity AS quantity,
34COALESCE(t1.quantity-LAG(t1.quantity) OVER (PARTITION BY t1.time_stamp ORDER BY t1.time_stamp), t1.quantity) AS difference
35FROM
36
37 (SELECT
38 l.time_stamp AS time_stamp,
39 SUM(l.quantity) AS quantity
40 FROM logistics l
41 GROUP BY 1
42 ORDER BY 1) t1
43
44GROUP BY 1,2
45ORDER BY 1,2;
46SELECT
47t1.time_stamp AS time_stamp,
48t1.quantity AS quantity,
49COALESCE(t1.quantity-LAG(t1.quantity) OVER (ORDER BY t1.time_stamp), t1.quantity)
50AS difference
51FROM
52
53 (SELECT
54 l.time_stamp AS time_stamp,
55 SUM(l.quantity) AS quantity
56 FROM logistics l
57 GROUP BY 1
58 ORDER BY 1) t1
59
60GROUP BY 1,2
61ORDER BY 1,2;
62
1CREATE TABLE logistics (
2 id SERIAL PRIMARY KEY,
3 time_stamp DATE,
4 product VARCHAR(255),
5 quantity INT
6);
7
8INSERT INTO logistics
9(time_stamp, product, quantity)
10VALUES
11('2020-01-14', 'Product_A', '100'),
12('2020-01-14', 'Product_B', '300'),
13
14('2020-01-15', 'Product_B', '400'),
15('2020-01-15', 'Product_C', '350'),
16
17('2020-01-16', 'Product_B', '530'),
18('2020-01-16', 'Product_C', '350'),
19('2020-01-16', 'Product_D', '670'),
20
21('2020-01-17', 'Product_C', '500'),
22('2020-01-17', 'Product_D', '980'),
23('2020-01-17', 'Product_E', '700'),
24('2020-01-17', 'Product_F', '450');
25time_stamp | difference | info
26------------|----------------|--------------------------------------
272020-01-14 | 400 | =(100+300)
282020-01-15 | 350 | =(400+350)-(300+100)
292020-01-16 | 800 | =(530+350+670)-(400+350)
302020-01-17 | 1080 | =(500+980+700+450)-(530+350+670)
31SELECT
32t1.time_stamp AS time_stamp,
33t1.quantity AS quantity,
34COALESCE(t1.quantity-LAG(t1.quantity) OVER (PARTITION BY t1.time_stamp ORDER BY t1.time_stamp), t1.quantity) AS difference
35FROM
36
37 (SELECT
38 l.time_stamp AS time_stamp,
39 SUM(l.quantity) AS quantity
40 FROM logistics l
41 GROUP BY 1
42 ORDER BY 1) t1
43
44GROUP BY 1,2
45ORDER BY 1,2;
46SELECT
47t1.time_stamp AS time_stamp,
48t1.quantity AS quantity,
49COALESCE(t1.quantity-LAG(t1.quantity) OVER (ORDER BY t1.time_stamp), t1.quantity)
50AS difference
51FROM
52
53 (SELECT
54 l.time_stamp AS time_stamp,
55 SUM(l.quantity) AS quantity
56 FROM logistics l
57 GROUP BY 1
58 ORDER BY 1) t1
59
60GROUP BY 1,2
61ORDER BY 1,2;
62
db<>fiddle here
QUESTION
Query Search Algorithm using priority array and ignoring conditions
Asked 2022-Jan-04 at 13:26I am facing this problem at my companies logistics:
Given array of mixed values
1arr = [
2 v1 => a,
3 v2 => b,
4 v3 => c,
5 v4 => d
6]
7
ordered by priority ASC (v1 is more important than v2, ... etc)
I need to search values in a table t like this:
1arr = [
2 v1 => a,
3 v2 => b,
4 v3 => c,
5 v4 => d
6]
7select * from t where
8 ... And
9 t.v1 = a And
10 t.v2 = b And
11 t.v3 = c And
12 t.v4 = d
13
The 3 dots in query are the fixed conditions
If I cant find any value from query, perform same query ignoring the least important value from array
1arr = [
2 v1 => a,
3 v2 => b,
4 v3 => c,
5 v4 => d
6]
7select * from t where
8 ... And
9 t.v1 = a And
10 t.v2 = b And
11 t.v3 = c And
12 t.v4 = d
13select * from t where
14 ... And
15 t.v1 = a And
16 t.v2 = b And
17 t.v3 = c
18
Again if value was not found. perform a query ignoring the next least important value
1arr = [
2 v1 => a,
3 v2 => b,
4 v3 => c,
5 v4 => d
6]
7select * from t where
8 ... And
9 t.v1 = a And
10 t.v2 = b And
11 t.v3 = c And
12 t.v4 = d
13select * from t where
14 ... And
15 t.v1 = a And
16 t.v2 = b And
17 t.v3 = c
18select * from t where
19 ... And
20 t.v1 = a And
21 t.v2 = b And
22 t.v4 = d
23
The query can ignore all elements from array as last query
1arr = [
2 v1 => a,
3 v2 => b,
4 v3 => c,
5 v4 => d
6]
7select * from t where
8 ... And
9 t.v1 = a And
10 t.v2 = b And
11 t.v3 = c And
12 t.v4 = d
13select * from t where
14 ... And
15 t.v1 = a And
16 t.v2 = b And
17 t.v3 = c
18select * from t where
19 ... And
20 t.v1 = a And
21 t.v2 = b And
22 t.v4 = d
23select * from t where ...
24
Repeat that until find at least 1 query result or all elements in array are nulled and no result were found. (return false)
I did my search algorithm using binary numbers to find the value which works like this
1arr = [
2 v1 => a,
3 v2 => b,
4 v3 => c,
5 v4 => d
6]
7select * from t where
8 ... And
9 t.v1 = a And
10 t.v2 = b And
11 t.v3 = c And
12 t.v4 = d
13select * from t where
14 ... And
15 t.v1 = a And
16 t.v2 = b And
17 t.v3 = c
18select * from t where
19 ... And
20 t.v1 = a And
21 t.v2 = b And
22 t.v4 = d
23select * from t where ...
24binaryValue = (2 ^ arr.lenght) - 1 //(In this case: 2^4-1 = 15)
25
transform binary 15 in array of boolean exploded = [1, 1, 1, 1] (15 in binary is 1111)
Than make the query considering position 0 of booleanArray exploded if true then Consider value in arr of mixed values and so on
loop from 15 to 0 (the 0 iteration is when the boolean array is [0,0,0,0] and ignores all cases The sequence will be like this with this logic:
1arr = [
2 v1 => a,
3 v2 => b,
4 v3 => c,
5 v4 => d
6]
7select * from t where
8 ... And
9 t.v1 = a And
10 t.v2 = b And
11 t.v3 = c And
12 t.v4 = d
13select * from t where
14 ... And
15 t.v1 = a And
16 t.v2 = b And
17 t.v3 = c
18select * from t where
19 ... And
20 t.v1 = a And
21 t.v2 = b And
22 t.v4 = d
23select * from t where ...
24binaryValue = (2 ^ arr.lenght) - 1 //(In this case: 2^4-1 = 15)
25[a, b, c, d] // [1,1,1,1] = 15 (select * from t where ... and v1=a and v2=b and v3=c and v4=d)
26[a, b, c] // [1,1,1,0] = 14 (select * from t where ... and v1=a and v2=b and v3=c)
27[a, b, d] // [1,1,0,1] = 13 (select * from t where ... and v1=a and v2=b and v4=d)
28...
29[] // [0,0,0,0] = 0 (select * from t where ...)
30
The search algorithm works fine but I have a huge problem to performance.
The number of queries performed in this search is arr.length! (fatorial) So when the array is length 4, the worst case scenario performs 24 queries. if the arr.length is 6 (what is the length I am dealing now in my code in production) the worst case performs 720 queries which is unacceptable.
I need a way to Improve this search. Can someone help me?
Thanks in advance.
ANSWER
Answered 2022-Jan-04 at 13:26I came up to the solution using the concept of row's desirability suggested by @RBarryYoung
Instead of performing multiple queries, I fetch all relevant rows into a datatable (1 query) and for each rows I applied a score based in desirability. (Code side)
1arr = [
2 v1 => a,
3 v2 => b,
4 v3 => c,
5 v4 => d
6]
7select * from t where
8 ... And
9 t.v1 = a And
10 t.v2 = b And
11 t.v3 = c And
12 t.v4 = d
13select * from t where
14 ... And
15 t.v1 = a And
16 t.v2 = b And
17 t.v3 = c
18select * from t where
19 ... And
20 t.v1 = a And
21 t.v2 = b And
22 t.v4 = d
23select * from t where ...
24binaryValue = (2 ^ arr.lenght) - 1 //(In this case: 2^4-1 = 15)
25[a, b, c, d] // [1,1,1,1] = 15 (select * from t where ... and v1=a and v2=b and v3=c and v4=d)
26[a, b, c] // [1,1,1,0] = 14 (select * from t where ... and v1=a and v2=b and v3=c)
27[a, b, d] // [1,1,0,1] = 13 (select * from t where ... and v1=a and v2=b and v4=d)
28...
29[] // [0,0,0,0] = 0 (select * from t where ...)
30 Dim dicFields As New Dictionary(Of String, String) From { _
31 {"v1", a}, _
32 {"v2", b}, _
33 {"v3", c}, _
34 {"v4", d}
35 }
36
37 Dim intScore As Integer = dicFields.Keys.Count
38
39 For Each pair As KeyValuePair(Of String, String) In dicFields
40 lstRow _
41 .Where(Function(p) p.Item(pair.Key) = pair.Value) _
42 .ToList() _
43 .ForEach(Sub(p) p.Item("__Score") += intScore)
44
45 intScore -= 1
46 Next
47
48 return lstRow _
49 .OrderByDescending(Function(p) p.Item("__Score")) _
50 .FirstOrDefault()
51
It reduced the complexity of n! to just 1 query and n filters. System are up and running smoothly. Thanks for the help @RBarryYoung
QUESTION
Python Pandas and Slack Webhooks Requests.post
Asked 2021-Dec-31 at 15:58What im looking to achieve is pulling a csv file from a workorder app that we use. Then convert it using pandas and remove unnecessary columns. Then post this info into slack using a webhook. I dont have access to the slack API. So far this is what i came up with but am finding it hard to get the data into a format that i can send.
1from time import sleep
2from requests.models import Response
3from selenium import webdriver
4import os
5import pandas as pd
6
7import json
8import requests
9
10
11def WOPULLER_CSV():
12 options = webdriver.ChromeOptions()
13 prefs = {'download.default_directory' : 'C:\\WO_CSV'}
14 options.add_experimental_option('prefs', prefs)
15 driver = webdriver.Chrome(options=options)
16 driver.get('https://portal.ez.na.rme.logistics.a2z.com/work-orders?preset=allCSS&customPreset=allCSS&scheduledStartDate=nextOneWeek&status=RS,S')
17 SignInASButton = driver.execute_script("return document.querySelector('ez-rme-app').shadowRoot.querySelector('ez-login-page').shadowRoot.querySelector('ez-login').shadowRoot.querySelector('mwc-button:nth-child(4)').shadowRoot.querySelector('#button')")
18 SignInASButton.click()
19 sleep(1)
20 SingleSignOnButton = driver.execute_script("return document.querySelector('ez-rme-app').shadowRoot.querySelector('ez-login-page').shadowRoot.querySelector('ez-login').shadowRoot.querySelector('#sso-login').shadowRoot.querySelector('#button')")
21 SingleSignOnButton.click()
22 sleep(8)
23 if os.path.exists("C:\\WO_CSV\\WorkOrderExport.csv"):
24 os.remove("C:\\WO_CSV\\WorkOrderExport.csv")
25 CSVButton = driver.execute_script("return document.querySelector('body > ez-rme-app').shadowRoot.querySelector('#content > main > ez-work-order-list-page').shadowRoot.querySelector('div > mwc-button:nth-child(1)').shadowRoot.querySelector('#button')")
26 CSVButton.click()
27 sleep(1)
28
29def WEBHOOK():
30
31 #value = pd.read_json('C:\WO_CSV\WorkOrderExport.json')
32
33 value = wo
34 web_hook_link = 'WEBHOOK LINK'
35 headers = {
36 'Content-Type': 'application/json',
37 }
38 data = json.dumps({"name": value})
39 response = requests.post(web_hook_link, headers=headers, data=data)
40 print (response)
41
42#WOPULLER_CSV()
43
44df = pd.read_csv (r'C:\WO_CSV\WorkOrderExport.csv')
45df = df.sort_values(by='Scheduled Start Date', ascending=False)
46df = df.drop(columns=['Organization', 'Original PM due date', 'PM Compliance Max Date', 'PM Compliance Min Date', 'Scheduled End Date', 'Priority', 'Equipment Criticality', 'Equipment Alias', 'Type', 'Index', 'Equipment Description' ])
47
48if os.path.exists("C:\WO_CSV\WorkOrderExport.json"):
49 os.remove("C:\WO_CSV\WorkOrderExport.json")
50
51df.to_json('C:\WO_CSV\WorkOrderExport.json')
52wo = pd.read_json (r'C:\WO_CSV\WorkOrderExport.json')
53
54WEBHOOK()
55print (wo)
56
Information that is in the CSV file : CSV After Colum Drop
What im trying to achieve in slack is similar to if i just copy and pasted from excel xlsx file. There is no MD formatting in slack so this is the best option. Format in slack
ANSWER
Answered 2021-Dec-31 at 15:58OK i found my answer . In order to post to slack you need to tabulate the csv file then use the json.dump. Referenced these other stack posts :
what-are-some-ways-to-post-python-pandas-dataframes-to-slack
1from time import sleep
2from requests.models import Response
3from selenium import webdriver
4import os
5import pandas as pd
6
7import json
8import requests
9
10
11def WOPULLER_CSV():
12 options = webdriver.ChromeOptions()
13 prefs = {'download.default_directory' : 'C:\\WO_CSV'}
14 options.add_experimental_option('prefs', prefs)
15 driver = webdriver.Chrome(options=options)
16 driver.get('https://portal.ez.na.rme.logistics.a2z.com/work-orders?preset=allCSS&customPreset=allCSS&scheduledStartDate=nextOneWeek&status=RS,S')
17 SignInASButton = driver.execute_script("return document.querySelector('ez-rme-app').shadowRoot.querySelector('ez-login-page').shadowRoot.querySelector('ez-login').shadowRoot.querySelector('mwc-button:nth-child(4)').shadowRoot.querySelector('#button')")
18 SignInASButton.click()
19 sleep(1)
20 SingleSignOnButton = driver.execute_script("return document.querySelector('ez-rme-app').shadowRoot.querySelector('ez-login-page').shadowRoot.querySelector('ez-login').shadowRoot.querySelector('#sso-login').shadowRoot.querySelector('#button')")
21 SingleSignOnButton.click()
22 sleep(8)
23 if os.path.exists("C:\\WO_CSV\\WorkOrderExport.csv"):
24 os.remove("C:\\WO_CSV\\WorkOrderExport.csv")
25 CSVButton = driver.execute_script("return document.querySelector('body > ez-rme-app').shadowRoot.querySelector('#content > main > ez-work-order-list-page').shadowRoot.querySelector('div > mwc-button:nth-child(1)').shadowRoot.querySelector('#button')")
26 CSVButton.click()
27 sleep(1)
28
29def WEBHOOK():
30
31 #value = pd.read_json('C:\WO_CSV\WorkOrderExport.json')
32
33 value = wo
34 web_hook_link = 'WEBHOOK LINK'
35 headers = {
36 'Content-Type': 'application/json',
37 }
38 data = json.dumps({"name": value})
39 response = requests.post(web_hook_link, headers=headers, data=data)
40 print (response)
41
42#WOPULLER_CSV()
43
44df = pd.read_csv (r'C:\WO_CSV\WorkOrderExport.csv')
45df = df.sort_values(by='Scheduled Start Date', ascending=False)
46df = df.drop(columns=['Organization', 'Original PM due date', 'PM Compliance Max Date', 'PM Compliance Min Date', 'Scheduled End Date', 'Priority', 'Equipment Criticality', 'Equipment Alias', 'Type', 'Index', 'Equipment Description' ])
47
48if os.path.exists("C:\WO_CSV\WorkOrderExport.json"):
49 os.remove("C:\WO_CSV\WorkOrderExport.json")
50
51df.to_json('C:\WO_CSV\WorkOrderExport.json')
52wo = pd.read_json (r'C:\WO_CSV\WorkOrderExport.json')
53
54WEBHOOK()
55print (wo)
56def WEBHOOK():
57
58 #value = pd.read_json('C:\WO_CSV\WorkOrderExport.json')
59
60 value = tab
61 web_hook_link = 'https://hooks.slack.com/workflows/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'
62 headers = {
63 'Content-Type': 'application/json',
64 }
65 data = json.dumps({"name": value})
66 response = requests.post(web_hook_link, headers=headers, data=data)
67 print (response)
68
69 #WOPULLER_CSV()
70
71 df = pd.read_csv (r'C:\WO_CSV\WorkOrderExport.csv')
72 df = df.sort_values(by='Scheduled Start Date', ascending=False)
73 df = df.drop(columns=['Organization', 'Original PM due date', 'PM Compliance Max Date', 'PM Compliance Min Date', 'Scheduled End Date', 'Priority', 'Equipment Criticality', 'Equipment Alias', 'Type', 'Index', 'Equipment Description' ])
74
75 **tab = (tabulate(df, tablefmt="grid"))**
76
77 WEBHOOK()
78 print (tab)
79
QUESTION
Depth First Search in Directed Graph?
Asked 2021-Dec-09 at 10:07I have a small array of numbers. [4, 1, 2, 5, 3, 6, 8, 7]
The way my graph is set up is that each number in the array is pointing to all numbers larger than it later on in the array. (4 is pointing to 5, 6, 8, and 7. 3 is pointing to 6, 8, 7. Etc.) I input these numbers into the graph, using an adjacency list to map out all the edges. I'm trying to use some sort of Depth First Search method to find the length of the longest path from any starting point in the graph. I'm just having some troubles getting the traversal started and set up, especially since later on I want to use this same graph for a much larger array of random numbers.
Here is my code for my Graph (also the count variable in my DFSUtil is supposed to be used to count the edges on each path, and then I was going to put those into an array or something to keep track of which path had the most edges (longest path)):
1import java.util.NoSuchElementException;
2
3public class Graph {
4 private static final String NEWLINE = System.getProperty("line.separator");
5
6 public final int V; // initializing variables and data structures
7 private int E = 0;
8 public Bag<Integer>[] adj;
9
10 public Graph(int[] numbers) {
11
12 try {
13 this.V = numbers.length;
14 adj = (Bag<Integer>[]) new Bag[V]; // bag initialized
15 for (int v = 0; v < V; v++) {
16 adj[v] = new Bag<Integer>(); // indices are initialized
17 }
18 for (int i = 0; i < V; i++) {
19 adj[i].label = numbers[i];
20 int j = (i + 1);
21 while (j < numbers.length) {
22 if (numbers[i] < numbers[j]) {
23 addEdge(i, numbers[j]);
24 }
25 j++;
26 }
27 }
28 }
29 catch (NoSuchElementException e) {
30 throw new IllegalArgumentException("invalid input format in Graph constructor", e);
31 }
32 }
33
34 public void addEdge(int index, int num) {
35 E++; // number of edges increases
36 adj[index].add(num); // indexes into bag
37 }
38
39 public void print() {
40 for (int i = 0; i < adj.length; i++) {
41 System.out.print(adj[i].label + ": ");
42 for (int w : adj[i]) {
43 System.out.print(w + " ");
44 }
45 System.out.println("");
46 }
47 }
48
49
50 public int getIndex(int num) {
51 for (int i = 0; i < adj.length; i++) {
52 if (adj[i].label == num) {
53 return num;
54 }
55 }
56 return -1;
57
58 }
59
60 void DFSUtil(int start)
61 {
62 while (start < adj.length) {
63 System.out.print(start + " ");
64 int a = 0;
65 int count = 0;
66
67 for (int i = 0; i < adj[start].edges; i++) //iterate through the linked list and then propagate to the next few nodes
68 {
69 int j = 0;
70 for (int num : adj[start]) {
71 if (j == i) {
72 a = getIndex(num);
73 }
74 j++;
75 }
76 count++;
77 DFSUtil(a);
78 }
79 start++;
80 }
81 }
82
83 void DFS()
84 {
85 DFSUtil(0);
86 }
87
88}
89
And here is the code for my Bag method:
1import java.util.NoSuchElementException;
2
3public class Graph {
4 private static final String NEWLINE = System.getProperty("line.separator");
5
6 public final int V; // initializing variables and data structures
7 private int E = 0;
8 public Bag<Integer>[] adj;
9
10 public Graph(int[] numbers) {
11
12 try {
13 this.V = numbers.length;
14 adj = (Bag<Integer>[]) new Bag[V]; // bag initialized
15 for (int v = 0; v < V; v++) {
16 adj[v] = new Bag<Integer>(); // indices are initialized
17 }
18 for (int i = 0; i < V; i++) {
19 adj[i].label = numbers[i];
20 int j = (i + 1);
21 while (j < numbers.length) {
22 if (numbers[i] < numbers[j]) {
23 addEdge(i, numbers[j]);
24 }
25 j++;
26 }
27 }
28 }
29 catch (NoSuchElementException e) {
30 throw new IllegalArgumentException("invalid input format in Graph constructor", e);
31 }
32 }
33
34 public void addEdge(int index, int num) {
35 E++; // number of edges increases
36 adj[index].add(num); // indexes into bag
37 }
38
39 public void print() {
40 for (int i = 0; i < adj.length; i++) {
41 System.out.print(adj[i].label + ": ");
42 for (int w : adj[i]) {
43 System.out.print(w + " ");
44 }
45 System.out.println("");
46 }
47 }
48
49
50 public int getIndex(int num) {
51 for (int i = 0; i < adj.length; i++) {
52 if (adj[i].label == num) {
53 return num;
54 }
55 }
56 return -1;
57
58 }
59
60 void DFSUtil(int start)
61 {
62 while (start < adj.length) {
63 System.out.print(start + " ");
64 int a = 0;
65 int count = 0;
66
67 for (int i = 0; i < adj[start].edges; i++) //iterate through the linked list and then propagate to the next few nodes
68 {
69 int j = 0;
70 for (int num : adj[start]) {
71 if (j == i) {
72 a = getIndex(num);
73 }
74 j++;
75 }
76 count++;
77 DFSUtil(a);
78 }
79 start++;
80 }
81 }
82
83 void DFS()
84 {
85 DFSUtil(0);
86 }
87
88}
89import java.util.Iterator;
90import java.util.NoSuchElementException;
91
92public class Bag<Item> implements Iterable<Item> {
93 private Node<Item> first; // beginning of bag
94 private Node<Item> end;
95 private int n; // number of elements in bag
96 public int label;
97 public int edges;
98
99 public static class Node<Item> {
100 private Item item;
101 private Node<Item> next;
102 public int label;
103 public int edges;
104 }
105
106 public Bag() {
107 first = null; // empty bag initialized
108 end = null;
109 n = 0;
110 }
111
112 public void add(Item item) {
113 if (n==0) {
114 Node<Item> head = new Node<Item>(); // if bag is empty
115 first = head;
116 end = head;
117 head.item = item; // new node both first and end of bag
118 edges++;
119 n++;
120 }
121 else {
122 Node<Item> oldlast = end; // old last assigned to end of node
123 Node<Item> last = new Node<Item>();
124 last.item = item;
125 oldlast.next = last; // new node added after old last
126 end = last;
127 n++; // size increased
128 edges++;
129 }
130 }
131
132 public int size() {
133 return n;
134 }
135
136 public void print() {
137 Node<Item> current = first;
138 for (int i = 0; i < n; i++) { // starting at front of bag
139 System.out.println(current.item); // prints item, moves to next
140 current = current.next;
141 }
142 }
143
144
145 public Iterator<Item> iterator() {
146 return new LinkedIterator(first); // returns an iterator that iterates over the items in this bag in arbitrary order
147 }
148
149
150 public class LinkedIterator implements Iterator<Item> {
151 private Node<Item> current;
152
153 public LinkedIterator(Node<Item> first) {
154 current = first; // iterator starts at head of bag
155 }
156
157 public boolean hasNext() { return current != null; }
158 public void remove() { throw new UnsupportedOperationException(); }
159
160 public Item next() {
161 if (!hasNext()) throw new NoSuchElementException(); // if there is next item, current is moved to next
162 Item item = current.item;
163 current = current.next;
164 return item; // item is returned
165 }
166 }
167
168}
169
And then this is all I have in my main function:
1import java.util.NoSuchElementException;
2
3public class Graph {
4 private static final String NEWLINE = System.getProperty("line.separator");
5
6 public final int V; // initializing variables and data structures
7 private int E = 0;
8 public Bag<Integer>[] adj;
9
10 public Graph(int[] numbers) {
11
12 try {
13 this.V = numbers.length;
14 adj = (Bag<Integer>[]) new Bag[V]; // bag initialized
15 for (int v = 0; v < V; v++) {
16 adj[v] = new Bag<Integer>(); // indices are initialized
17 }
18 for (int i = 0; i < V; i++) {
19 adj[i].label = numbers[i];
20 int j = (i + 1);
21 while (j < numbers.length) {
22 if (numbers[i] < numbers[j]) {
23 addEdge(i, numbers[j]);
24 }
25 j++;
26 }
27 }
28 }
29 catch (NoSuchElementException e) {
30 throw new IllegalArgumentException("invalid input format in Graph constructor", e);
31 }
32 }
33
34 public void addEdge(int index, int num) {
35 E++; // number of edges increases
36 adj[index].add(num); // indexes into bag
37 }
38
39 public void print() {
40 for (int i = 0; i < adj.length; i++) {
41 System.out.print(adj[i].label + ": ");
42 for (int w : adj[i]) {
43 System.out.print(w + " ");
44 }
45 System.out.println("");
46 }
47 }
48
49
50 public int getIndex(int num) {
51 for (int i = 0; i < adj.length; i++) {
52 if (adj[i].label == num) {
53 return num;
54 }
55 }
56 return -1;
57
58 }
59
60 void DFSUtil(int start)
61 {
62 while (start < adj.length) {
63 System.out.print(start + " ");
64 int a = 0;
65 int count = 0;
66
67 for (int i = 0; i < adj[start].edges; i++) //iterate through the linked list and then propagate to the next few nodes
68 {
69 int j = 0;
70 for (int num : adj[start]) {
71 if (j == i) {
72 a = getIndex(num);
73 }
74 j++;
75 }
76 count++;
77 DFSUtil(a);
78 }
79 start++;
80 }
81 }
82
83 void DFS()
84 {
85 DFSUtil(0);
86 }
87
88}
89import java.util.Iterator;
90import java.util.NoSuchElementException;
91
92public class Bag<Item> implements Iterable<Item> {
93 private Node<Item> first; // beginning of bag
94 private Node<Item> end;
95 private int n; // number of elements in bag
96 public int label;
97 public int edges;
98
99 public static class Node<Item> {
100 private Item item;
101 private Node<Item> next;
102 public int label;
103 public int edges;
104 }
105
106 public Bag() {
107 first = null; // empty bag initialized
108 end = null;
109 n = 0;
110 }
111
112 public void add(Item item) {
113 if (n==0) {
114 Node<Item> head = new Node<Item>(); // if bag is empty
115 first = head;
116 end = head;
117 head.item = item; // new node both first and end of bag
118 edges++;
119 n++;
120 }
121 else {
122 Node<Item> oldlast = end; // old last assigned to end of node
123 Node<Item> last = new Node<Item>();
124 last.item = item;
125 oldlast.next = last; // new node added after old last
126 end = last;
127 n++; // size increased
128 edges++;
129 }
130 }
131
132 public int size() {
133 return n;
134 }
135
136 public void print() {
137 Node<Item> current = first;
138 for (int i = 0; i < n; i++) { // starting at front of bag
139 System.out.println(current.item); // prints item, moves to next
140 current = current.next;
141 }
142 }
143
144
145 public Iterator<Item> iterator() {
146 return new LinkedIterator(first); // returns an iterator that iterates over the items in this bag in arbitrary order
147 }
148
149
150 public class LinkedIterator implements Iterator<Item> {
151 private Node<Item> current;
152
153 public LinkedIterator(Node<Item> first) {
154 current = first; // iterator starts at head of bag
155 }
156
157 public boolean hasNext() { return current != null; }
158 public void remove() { throw new UnsupportedOperationException(); }
159
160 public Item next() {
161 if (!hasNext()) throw new NoSuchElementException(); // if there is next item, current is moved to next
162 Item item = current.item;
163 current = current.next;
164 return item; // item is returned
165 }
166 }
167
168}
169 public static void main(String[] args) {
170 int[] num = {4, 1, 2, 5, 3, 6, 8, 7};
171 Graph G = new Graph(num);
172 G.print();
173 G.DFS();
174
175 }
176
I've been trying to get some sort of recursive method going for my search, but I'm having troubles getting the logistics down. Any help would be appreciated!
ANSWER
Answered 2021-Dec-07 at 06:54The problem with your void DFSUtil(int start)
is that start
is not a node of your graph, it's just an index to access your adjacency list and cannot be used to access its neighbors. In your case, you need to use the label
to access the neighbor list.
1import java.util.NoSuchElementException;
2
3public class Graph {
4 private static final String NEWLINE = System.getProperty("line.separator");
5
6 public final int V; // initializing variables and data structures
7 private int E = 0;
8 public Bag<Integer>[] adj;
9
10 public Graph(int[] numbers) {
11
12 try {
13 this.V = numbers.length;
14 adj = (Bag<Integer>[]) new Bag[V]; // bag initialized
15 for (int v = 0; v < V; v++) {
16 adj[v] = new Bag<Integer>(); // indices are initialized
17 }
18 for (int i = 0; i < V; i++) {
19 adj[i].label = numbers[i];
20 int j = (i + 1);
21 while (j < numbers.length) {
22 if (numbers[i] < numbers[j]) {
23 addEdge(i, numbers[j]);
24 }
25 j++;
26 }
27 }
28 }
29 catch (NoSuchElementException e) {
30 throw new IllegalArgumentException("invalid input format in Graph constructor", e);
31 }
32 }
33
34 public void addEdge(int index, int num) {
35 E++; // number of edges increases
36 adj[index].add(num); // indexes into bag
37 }
38
39 public void print() {
40 for (int i = 0; i < adj.length; i++) {
41 System.out.print(adj[i].label + ": ");
42 for (int w : adj[i]) {
43 System.out.print(w + " ");
44 }
45 System.out.println("");
46 }
47 }
48
49
50 public int getIndex(int num) {
51 for (int i = 0; i < adj.length; i++) {
52 if (adj[i].label == num) {
53 return num;
54 }
55 }
56 return -1;
57
58 }
59
60 void DFSUtil(int start)
61 {
62 while (start < adj.length) {
63 System.out.print(start + " ");
64 int a = 0;
65 int count = 0;
66
67 for (int i = 0; i < adj[start].edges; i++) //iterate through the linked list and then propagate to the next few nodes
68 {
69 int j = 0;
70 for (int num : adj[start]) {
71 if (j == i) {
72 a = getIndex(num);
73 }
74 j++;
75 }
76 count++;
77 DFSUtil(a);
78 }
79 start++;
80 }
81 }
82
83 void DFS()
84 {
85 DFSUtil(0);
86 }
87
88}
89import java.util.Iterator;
90import java.util.NoSuchElementException;
91
92public class Bag<Item> implements Iterable<Item> {
93 private Node<Item> first; // beginning of bag
94 private Node<Item> end;
95 private int n; // number of elements in bag
96 public int label;
97 public int edges;
98
99 public static class Node<Item> {
100 private Item item;
101 private Node<Item> next;
102 public int label;
103 public int edges;
104 }
105
106 public Bag() {
107 first = null; // empty bag initialized
108 end = null;
109 n = 0;
110 }
111
112 public void add(Item item) {
113 if (n==0) {
114 Node<Item> head = new Node<Item>(); // if bag is empty
115 first = head;
116 end = head;
117 head.item = item; // new node both first and end of bag
118 edges++;
119 n++;
120 }
121 else {
122 Node<Item> oldlast = end; // old last assigned to end of node
123 Node<Item> last = new Node<Item>();
124 last.item = item;
125 oldlast.next = last; // new node added after old last
126 end = last;
127 n++; // size increased
128 edges++;
129 }
130 }
131
132 public int size() {
133 return n;
134 }
135
136 public void print() {
137 Node<Item> current = first;
138 for (int i = 0; i < n; i++) { // starting at front of bag
139 System.out.println(current.item); // prints item, moves to next
140 current = current.next;
141 }
142 }
143
144
145 public Iterator<Item> iterator() {
146 return new LinkedIterator(first); // returns an iterator that iterates over the items in this bag in arbitrary order
147 }
148
149
150 public class LinkedIterator implements Iterator<Item> {
151 private Node<Item> current;
152
153 public LinkedIterator(Node<Item> first) {
154 current = first; // iterator starts at head of bag
155 }
156
157 public boolean hasNext() { return current != null; }
158 public void remove() { throw new UnsupportedOperationException(); }
159
160 public Item next() {
161 if (!hasNext()) throw new NoSuchElementException(); // if there is next item, current is moved to next
162 Item item = current.item;
163 current = current.next;
164 return item; // item is returned
165 }
166 }
167
168}
169 public static void main(String[] args) {
170 int[] num = {4, 1, 2, 5, 3, 6, 8, 7};
171 Graph G = new Graph(num);
172 G.print();
173 G.DFS();
174
175 }
176public Bag<Integer> getAdjList(int src) {
177 Bag<Integer> adjList = null;
178 for (Bag<Integer> list : adj) {
179 if (list.label == src) {
180 adjList = list;
181 break;
182 }
183 }
184 return adjList;
185}
186
And this adjacency list should be used to access current node neighbors. To get all the paths from a current node
start dfs
from the current node
and backtrack when there are no nodes
left to visit. Create an empty list
to track the current path, when visiting a node
add it to the list
and remove it from the list
when backtracking.
1import java.util.NoSuchElementException;
2
3public class Graph {
4 private static final String NEWLINE = System.getProperty("line.separator");
5
6 public final int V; // initializing variables and data structures
7 private int E = 0;
8 public Bag<Integer>[] adj;
9
10 public Graph(int[] numbers) {
11
12 try {
13 this.V = numbers.length;
14 adj = (Bag<Integer>[]) new Bag[V]; // bag initialized
15 for (int v = 0; v < V; v++) {
16 adj[v] = new Bag<Integer>(); // indices are initialized
17 }
18 for (int i = 0; i < V; i++) {
19 adj[i].label = numbers[i];
20 int j = (i + 1);
21 while (j < numbers.length) {
22 if (numbers[i] < numbers[j]) {
23 addEdge(i, numbers[j]);
24 }
25 j++;
26 }
27 }
28 }
29 catch (NoSuchElementException e) {
30 throw new IllegalArgumentException("invalid input format in Graph constructor", e);
31 }
32 }
33
34 public void addEdge(int index, int num) {
35 E++; // number of edges increases
36 adj[index].add(num); // indexes into bag
37 }
38
39 public void print() {
40 for (int i = 0; i < adj.length; i++) {
41 System.out.print(adj[i].label + ": ");
42 for (int w : adj[i]) {
43 System.out.print(w + " ");
44 }
45 System.out.println("");
46 }
47 }
48
49
50 public int getIndex(int num) {
51 for (int i = 0; i < adj.length; i++) {
52 if (adj[i].label == num) {
53 return num;
54 }
55 }
56 return -1;
57
58 }
59
60 void DFSUtil(int start)
61 {
62 while (start < adj.length) {
63 System.out.print(start + " ");
64 int a = 0;
65 int count = 0;
66
67 for (int i = 0; i < adj[start].edges; i++) //iterate through the linked list and then propagate to the next few nodes
68 {
69 int j = 0;
70 for (int num : adj[start]) {
71 if (j == i) {
72 a = getIndex(num);
73 }
74 j++;
75 }
76 count++;
77 DFSUtil(a);
78 }
79 start++;
80 }
81 }
82
83 void DFS()
84 {
85 DFSUtil(0);
86 }
87
88}
89import java.util.Iterator;
90import java.util.NoSuchElementException;
91
92public class Bag<Item> implements Iterable<Item> {
93 private Node<Item> first; // beginning of bag
94 private Node<Item> end;
95 private int n; // number of elements in bag
96 public int label;
97 public int edges;
98
99 public static class Node<Item> {
100 private Item item;
101 private Node<Item> next;
102 public int label;
103 public int edges;
104 }
105
106 public Bag() {
107 first = null; // empty bag initialized
108 end = null;
109 n = 0;
110 }
111
112 public void add(Item item) {
113 if (n==0) {
114 Node<Item> head = new Node<Item>(); // if bag is empty
115 first = head;
116 end = head;
117 head.item = item; // new node both first and end of bag
118 edges++;
119 n++;
120 }
121 else {
122 Node<Item> oldlast = end; // old last assigned to end of node
123 Node<Item> last = new Node<Item>();
124 last.item = item;
125 oldlast.next = last; // new node added after old last
126 end = last;
127 n++; // size increased
128 edges++;
129 }
130 }
131
132 public int size() {
133 return n;
134 }
135
136 public void print() {
137 Node<Item> current = first;
138 for (int i = 0; i < n; i++) { // starting at front of bag
139 System.out.println(current.item); // prints item, moves to next
140 current = current.next;
141 }
142 }
143
144
145 public Iterator<Item> iterator() {
146 return new LinkedIterator(first); // returns an iterator that iterates over the items in this bag in arbitrary order
147 }
148
149
150 public class LinkedIterator implements Iterator<Item> {
151 private Node<Item> current;
152
153 public LinkedIterator(Node<Item> first) {
154 current = first; // iterator starts at head of bag
155 }
156
157 public boolean hasNext() { return current != null; }
158 public void remove() { throw new UnsupportedOperationException(); }
159
160 public Item next() {
161 if (!hasNext()) throw new NoSuchElementException(); // if there is next item, current is moved to next
162 Item item = current.item;
163 current = current.next;
164 return item; // item is returned
165 }
166 }
167
168}
169 public static void main(String[] args) {
170 int[] num = {4, 1, 2, 5, 3, 6, 8, 7};
171 Graph G = new Graph(num);
172 G.print();
173 G.DFS();
174
175 }
176public Bag<Integer> getAdjList(int src) {
177 Bag<Integer> adjList = null;
178 for (Bag<Integer> list : adj) {
179 if (list.label == src) {
180 adjList = list;
181 break;
182 }
183 }
184 return adjList;
185}
186public void dfs(int src, ArrayList<Integer> curr) {
187 curr.add(src);
188 Bag<Integer> srcAdj = getAdjList(src);
189 if (srcAdj.size() == 0) {
190 // Leaf node
191 // Print this path
192 System.out.println(curr.toString());
193 }
194 for (int neighbor : srcAdj) {
195 dfs(neighbor, curr);
196 }
197 curr.remove(curr.size()-1);
198}
199
To get all the paths from all nodes in your graph, start dfs
for all the nodes in your graph.
1import java.util.NoSuchElementException;
2
3public class Graph {
4 private static final String NEWLINE = System.getProperty("line.separator");
5
6 public final int V; // initializing variables and data structures
7 private int E = 0;
8 public Bag<Integer>[] adj;
9
10 public Graph(int[] numbers) {
11
12 try {
13 this.V = numbers.length;
14 adj = (Bag<Integer>[]) new Bag[V]; // bag initialized
15 for (int v = 0; v < V; v++) {
16 adj[v] = new Bag<Integer>(); // indices are initialized
17 }
18 for (int i = 0; i < V; i++) {
19 adj[i].label = numbers[i];
20 int j = (i + 1);
21 while (j < numbers.length) {
22 if (numbers[i] < numbers[j]) {
23 addEdge(i, numbers[j]);
24 }
25 j++;
26 }
27 }
28 }
29 catch (NoSuchElementException e) {
30 throw new IllegalArgumentException("invalid input format in Graph constructor", e);
31 }
32 }
33
34 public void addEdge(int index, int num) {
35 E++; // number of edges increases
36 adj[index].add(num); // indexes into bag
37 }
38
39 public void print() {
40 for (int i = 0; i < adj.length; i++) {
41 System.out.print(adj[i].label + ": ");
42 for (int w : adj[i]) {
43 System.out.print(w + " ");
44 }
45 System.out.println("");
46 }
47 }
48
49
50 public int getIndex(int num) {
51 for (int i = 0; i < adj.length; i++) {
52 if (adj[i].label == num) {
53 return num;
54 }
55 }
56 return -1;
57
58 }
59
60 void DFSUtil(int start)
61 {
62 while (start < adj.length) {
63 System.out.print(start + " ");
64 int a = 0;
65 int count = 0;
66
67 for (int i = 0; i < adj[start].edges; i++) //iterate through the linked list and then propagate to the next few nodes
68 {
69 int j = 0;
70 for (int num : adj[start]) {
71 if (j == i) {
72 a = getIndex(num);
73 }
74 j++;
75 }
76 count++;
77 DFSUtil(a);
78 }
79 start++;
80 }
81 }
82
83 void DFS()
84 {
85 DFSUtil(0);
86 }
87
88}
89import java.util.Iterator;
90import java.util.NoSuchElementException;
91
92public class Bag<Item> implements Iterable<Item> {
93 private Node<Item> first; // beginning of bag
94 private Node<Item> end;
95 private int n; // number of elements in bag
96 public int label;
97 public int edges;
98
99 public static class Node<Item> {
100 private Item item;
101 private Node<Item> next;
102 public int label;
103 public int edges;
104 }
105
106 public Bag() {
107 first = null; // empty bag initialized
108 end = null;
109 n = 0;
110 }
111
112 public void add(Item item) {
113 if (n==0) {
114 Node<Item> head = new Node<Item>(); // if bag is empty
115 first = head;
116 end = head;
117 head.item = item; // new node both first and end of bag
118 edges++;
119 n++;
120 }
121 else {
122 Node<Item> oldlast = end; // old last assigned to end of node
123 Node<Item> last = new Node<Item>();
124 last.item = item;
125 oldlast.next = last; // new node added after old last
126 end = last;
127 n++; // size increased
128 edges++;
129 }
130 }
131
132 public int size() {
133 return n;
134 }
135
136 public void print() {
137 Node<Item> current = first;
138 for (int i = 0; i < n; i++) { // starting at front of bag
139 System.out.println(current.item); // prints item, moves to next
140 current = current.next;
141 }
142 }
143
144
145 public Iterator<Item> iterator() {
146 return new LinkedIterator(first); // returns an iterator that iterates over the items in this bag in arbitrary order
147 }
148
149
150 public class LinkedIterator implements Iterator<Item> {
151 private Node<Item> current;
152
153 public LinkedIterator(Node<Item> first) {
154 current = first; // iterator starts at head of bag
155 }
156
157 public boolean hasNext() { return current != null; }
158 public void remove() { throw new UnsupportedOperationException(); }
159
160 public Item next() {
161 if (!hasNext()) throw new NoSuchElementException(); // if there is next item, current is moved to next
162 Item item = current.item;
163 current = current.next;
164 return item; // item is returned
165 }
166 }
167
168}
169 public static void main(String[] args) {
170 int[] num = {4, 1, 2, 5, 3, 6, 8, 7};
171 Graph G = new Graph(num);
172 G.print();
173 G.DFS();
174
175 }
176public Bag<Integer> getAdjList(int src) {
177 Bag<Integer> adjList = null;
178 for (Bag<Integer> list : adj) {
179 if (list.label == src) {
180 adjList = list;
181 break;
182 }
183 }
184 return adjList;
185}
186public void dfs(int src, ArrayList<Integer> curr) {
187 curr.add(src);
188 Bag<Integer> srcAdj = getAdjList(src);
189 if (srcAdj.size() == 0) {
190 // Leaf node
191 // Print this path
192 System.out.println(curr.toString());
193 }
194 for (int neighbor : srcAdj) {
195 dfs(neighbor, curr);
196 }
197 curr.remove(curr.size()-1);
198}
199int[] num = {4, 1, 2, 5, 3, 6, 8, 7};
200Graph G = new Graph(num);
201G.print();
202for (int i=0;i<num.length;i++) {
203 // Print all paths from current node
204 G.dfs(num[i],new ArrayList<>());
205}
206
QUESTION
image as circle background (d3.js svg)
Asked 2021-Dec-08 at 15:40UPDATED I have made a force directed graph using D3.js. Each node corresponds to a company, and each link corresponds how they are related to each other according to the link color. What I would like to achieve is to use the image URLs within "nodes" data and show a different image for each bubble. Currently I was able to set a fixed static/identical image for all of my bubbles. I tried to connect the pattern to my "nodes" data, but unsuccessfully which ended up in an infinite loop.
Simple HTML canvas for my svg and two buttons for the zoom in and zoom out by click.
1 <div class="main-map-container" style="overflow: hidden">
2 <div class="canvas">
3 <div>
4 <button id="zoom_in">+</button>
5 <button id="zoom_out">-</button>
6 </div>
7 </div>
8 </div>
9
My datasets (links and nodes), note the image attribute on nodes. it refers to the image I wish to set as node background
1 <div class="main-map-container" style="overflow: hidden">
2 <div class="canvas">
3 <div>
4 <button id="zoom_in">+</button>
5 <button id="zoom_out">-</button>
6 </div>
7 </div>
8 </div>
9
10 const links = [
11 {src:"Amazon",target:"Aurora",link:"Investment",market:"Semi_Truck",tags:"AD_L3-4|AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US",date:"2019-02-01",description:"Amazon Investing in Aurora in an $530 million Financing Round",source:"https://drive.google.com/open?id=1aLuuUqXKSQcGzivH21CSuO7204pdyP7K",years:"2019"},
12 {src:"Amazon",target:"Aurora",link:"Investment",market:"Robotaxi | Semi_Truck",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$530",region:"EU| US",date:"2019-02-01",description:"Aurora announced that they have secured over $530 million in Series B financing led by Sequoia. This funding and partnership will accelerate their mission of delivering the benefits of self-driving technology safely, quickly, and broadly.\r\n\r\nIn addition to Sequoia, Amazon, and funds and accounts advised by T. Rowe Price Associates, Inc. are making significant investments in Aurora. Amazon’s unique expertise, capabilities, and perspectives will be valuable for us as we drive towards our mission.",source:"https://drive.google.com/open?id=1aLuuUqXKSQcGzivH21CSuO7204pdyP7K",years:"2019"},
13 {src:"Amazon",target:"Zoox",link:"Acquisition",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$1,200",region:"US",date:"2020-06-01",description:"Amazon acquires Zoox to help bring their vision of autonomous ride-hailing to reality. [The Financial Times reports that Amazon spends $1.2bn on the acquisition.]",source:"https://drive.google.com/open?id=18-zXDSHy9_o0OrIwYFfb5FdyMxMzgtHH",years:"2020"},
14 {src:"Amazon",target:"Rivian",link:"Investment",market:"Light_CV",tags:"Other",technology:"",aces:"Automated",amount:"",region:"US",date:"2020-10-01",description:"Amazon unveils its new electric delivery vans built by Rivian\nThe delivery giant aims to have 10,000 vehicles on the road by 2022, 100,000 vehicles expected by 2030.",source:"https://www.theverge.com/2020/10/8/21507495/amazon-electric-delivery-van-rivian-date-specs",years:"2020"},
15 {src:"Amazon",target:"Torc",link:"Partnership",market:"Semi_Truck",tags:"AD_L3-4| Edge/Cloud_computing",technology:"",aces:"Automated| Connected",amount:"",region:"US",date:"2021-02-17",description:"Torc selects AWS as preferred cloud provider for self-driving truck fleet",source:"https://drive.google.com/open?id=1QDHZIyUHpAY4oKEqmeM9cngPIWZWV2doE0r1emQZuNY",years:"2021"},
16 {src:"Amazon",target:"Intel",link:"Partnership",market:"PoV",tags:"Edge/Cloud_computing",technology:"",aces:"Connected",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-03-01",description:"Intel Achieves AWS High Performance Computing Competency Status",source:"https://drive.google.com/open?id=1MvhLikyzwbu-Mz_OuXUvytAuqXNEnUjHdSxMGXcKLok",years:"2021"},
17 {src:"Aurora",target:"Blackmore",link:"Acquisition",market:"Semi_Truck | Robotaxi",tags:"AD_Driverless",technology:"LiDAR",aces:"Automated",amount:"",region:"US",date:"2019-01-09",description:"Yesterday announce that they plan to acquire the industry-leading lidar company Blackmore, located in Bozeman, Montana.\r\n\r\nThe Bozeman, Montana–based outfit, which started up a decade ago to do work for the defense industry, uses a “frequency modulated continuous wave” system, also known as a Doppler lidar. When the infrared light hits an object and bounces back, the system determines both how far away it is and its velocity. Knowing where something is headed and how fast is prized data. Blackmore has at least one Doppler lidar competitor in Aeva, founded in early 2017 by a pair of former Apple engineers. [...]",source:"https://drive.google.com/open?id=1UkF-sxgA1AgpgWoRCd2qgWjovLQULoAP",years:"2019"},
18 {src:"Aurora",target:"Uber ATG",link:"Acquisition",market:"Robotaxi | Semi_Truck",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$4,000",region:"US",date:"2020-12-01",description:"Aurora is acquiring Uber's self-driving unit, ATG, accelerating the first Aurora Driver applications for heavy-duty trucks while allowing us to continue and accelerate our work on light-vehicle products. \"Simply put, Aurora will be the company best positioned to deliver the self-driving products necessary to make transportation and logistics safer, more accessible, and less expensive,\" said Chris Urmson, co-founder and CEO of Aurora.",source:"https://drive.google.com/open?id=1rc-_3VLlITe2bdxBgws3Bvb2rPvCluMfsMkFXiwbg98",years:"2020"},
19 {src:"Aurora",target:"Paccar",link:"Partnership",market:"Semi_Truck",tags:"AD_L3-4",technology:"",aces:"Automated",amount:"",region:"US",date:"2021-01-19",description:"Aurora teams up with PACCAR to build and deploy self-driving trucks",source:"https://drive.google.com/open?id=1TfA9U81CbyNwQc4Xfg2iJ9wqmka7RLqVEIsES2-62Ww",years:"2021"},
20 {src:"Aurora",target:"Denso",link:"Partnership",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-02-09",description:"Aurora enters into long-term, global, and strategic collaboration with Toyota and Denso",source:"https://drive.google.com/open?id=1QnlNnMMxbcPdnbi4AcBo36_UWM9TuMrNqItZHfPDUos",years:"2021"},
21 {src:"Aurora",target:"Toyota",link:"Partnership",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-02-09",description:"Aurora enters into long-term, global, and strategic collaboration with Toyota and Denso",source:"https://drive.google.com/open?id=1QnlNnMMxbcPdnbi4AcBo36_UWM9TuMrNqItZHfPDUos",years:"2021"},
22 {src:"Aurora",target:"OURS-Tech",link:"Acquisition",market:"Semi_Truck| Robotaxi",tags:"",technology:"LiDAR",aces:"Automated",amount:"",region:"US",date:"2021-02-26",description:"Aurora acquires OURS lidar (FMCW), unlocking the commercialization of its Aurora Driver",source:"https://drive.google.com/open?id=1TWEII1c0jQk26DcCC2WXw3plT0XTnfDzmD-e551VWSQ",years:"2021"},
23 {src:"Zoox",target:"ZadarLabs",link:"Investment",market:"PoV| Robotaxi",tags:"AD_L3-4| AD_Driverless",technology:"Radar",aces:"Automated",amount:"",region:"US",date:"2021-01-26",description:"Zadar Labs, Developing Next Generation Imaging Radar, Closes $5.6M in Seed Funding",source:"https://drive.google.com/open?id=1fz3MhS4P_Cmq2VmT9crQztUBd9W5Pj-IWEL9ABq3ySg",years:"2021"},
24 {src:"Intel",target:"Mobileye",link:"Acquisition",market:"PoV",tags:"AD_L3-4",technology:"",aces:"Automated",amount:"$15,000",region:"Worldwide",date:"2017-01-14",description:"Instead of Mobileye being integrated into Intel, Intel’s AD Group (ADG) will be integrated into Mobileye.",source:"https://www.engadget.com/2017-08-08-intel-acquisition-Mobileye-complete.html",years:"<2017"},
25 {src:"Intel",target:"Infineon",link:"Acquisition",market:"",tags:"",technology:"",aces:"Automated|Experience",amount:"1400",region:"US|EU",date:"2010-01-01",description:"Intel to Acquire Infineon’s Wireless Solutions Business",source:"https://www.infineon.com/cms/en/about-infineon/press/press-releases/2010/INFXX201008-069.html",years:"<2017"},
26 ]
27
28 const nodes = [
29 {id:"Amazon",type:"Tech",tags:"",technology:"",market:"Droid_Goods|Robotaxi",valuation:"",description:"Amazon is an international e-commerce website for consumers, sellers, and content creators.",country:"US",region:"North America",image:"https://images-eu.ssl-images-amazon.com/images/G/02/gc/designs/livepreview/a_generic_10_uk_noto_email_v2016_uk-main._CB485921599_.png"},
30 {id:"Aurora",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi|Semi_Truck",valuation:"1100",description:"Aurora is delivering the benefits of self-driving technology safely, quickly, and broadly.",country:"US",region:"North America",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/oeagjbu7wau6o16zdhb1"},
31 {id:"Zoox",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi",valuation:"",description:"Zoox is an AI robotics company that provides mobility as-a-service and self-driving car services.",country:"US",region:"North America",image:"https://res-4.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/kpc7mmk886nbbipbeqau"},
32 {id:"Rivian",type:"OEM",tags:"",technology:"",market:"PoV",valuation:"8200",description:"Rivian is an electric vehicle manufacturer that develops products and services to advance the shift to sustainable mobility.",country:"US",region:"North America",image:"https://res-4.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/sdz7aspakybuxp7oojvh"},
33 {id:"Torc",type:"Tier1",tags:"AD_Driverless|AD_L3-4",technology:"",market:"Semi_Truck|Mining",valuation:"",description:"Torc provides L4 end-to-end self-driving software for mobility, trucking, mining, and defense markets through strategic partnerships",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/smfgyxvfot1dwq4vqvo7"},
34 {id:"Intel",type:"Tech",tags:"",technology:"",market:"PoV | Robotaxi",valuation:"",description:"Intel designs, manufactures, and sells integrated digital technology platforms worldwide.",country:"US",region:"North America",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1505768454/wrhwa2ogipbd1o6tgggi.png"},
35 {id:"Blackmore",type:"Tier2",tags:"",technology:"LiDAR",market:"PoV|Other",valuation:"21.5",description:"Blackmore Sensors and Analytics develops frequency-modulated continuous wave lidar imaging and its supporting analytic tools software.",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1497015437/tqor2yimyfapcsn5uyaj.png"},
36 {id:"Uber ATG",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi",valuation:"1000",description:"Uber Advanced Technologies Group focuses on autonomous vehicles and the self-driving car business.",country:"US",region:"North America",image:"https://res-5.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/dlzugstswtlgq9wejmfi"},
37 {id:"Paccar",type:"OEM",tags:"",technology:"",market:"Semi_Truck",valuation:"",description:"Global technology leader in the design, manufacture and customer support of high-quality premium trucks.",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1404996232/nmvcucjqpgpnhrolbnnk.png"},
38 {id:"Denso",type:"Tier1",tags:"",technology:"",market:"PoV",valuation:"",description:"Supplier of advanced automotive technology",country:"Japan",region:"Japan",image:"https://res-5.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1398234958/fnjwkbbov8sivhs79wta.png"},
39 {id:"Toyota",type:"OEM",tags:"",technology:"",market:"PoV",valuation:"",description:"Toyota is a Japanese automotive company that manufactures and markets vehicles to over 170 countries and regions.",country:"Japan",region:"Japan",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1425366959/cleoo1wmofcfxxspobul.jpg"},
40 {id:"OURS-Tech",type:"Tier2",tags:"",technology:"LiDAR",market:"Semi_Truck| Robotaxi",valuation:"",description:"Enabling mass-production 5D LiDAR for the autonomous future",country:"US",region:"North America",image:"https://static.wixstatic.com/media/c668c3_f1f58317e99d41deac4152d212fcdbc2~mv2.gif"},
41 {id:"ZadarLabs",type:"Tier2",tags:"",technology:"Radar",market:"PoV| Robotaxi",valuation:"",description:"Zadar Labs brings radar intelligence to autonomous systems",country:"US",region:"North America",image:"https://res-1.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/g3kgj9vsfjzlpbichdml"},
42 {id:"Mobileye",type:"Tech",tags:"AS_NCAP|ADAS_uptoL2+|AD_Driverless",technology:"ECU_ADAS",market:"PoV|Robotaxi|Semi_Truck",valuation:"515",description:"Mobileye is a technology company developing vision-based advanced driver assistance systems that help prevent and mitigate collisions.",country:"Israel",region:"Others",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/bcuhhoflftvvdbpeaarx"},
43 {id:"Infineon",type:"Tier2",tags:"Interior_cocoon",technology:"",market:"PoV",valuation:"",description:"Infineon Technologies offers semiconductor solutions, microcontrollers, LED drivers, sensors and Automotive & Power Management ICs.",country:"Germany",region:"EU",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1397183702/79bc5b009247cfd1a274f2a328ff17bf.png"},
44
45 ]
46
As for my D3 javascript code here is a section with the most relevant :
1 <div class="main-map-container" style="overflow: hidden">
2 <div class="canvas">
3 <div>
4 <button id="zoom_in">+</button>
5 <button id="zoom_out">-</button>
6 </div>
7 </div>
8 </div>
9
10 const links = [
11 {src:"Amazon",target:"Aurora",link:"Investment",market:"Semi_Truck",tags:"AD_L3-4|AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US",date:"2019-02-01",description:"Amazon Investing in Aurora in an $530 million Financing Round",source:"https://drive.google.com/open?id=1aLuuUqXKSQcGzivH21CSuO7204pdyP7K",years:"2019"},
12 {src:"Amazon",target:"Aurora",link:"Investment",market:"Robotaxi | Semi_Truck",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$530",region:"EU| US",date:"2019-02-01",description:"Aurora announced that they have secured over $530 million in Series B financing led by Sequoia. This funding and partnership will accelerate their mission of delivering the benefits of self-driving technology safely, quickly, and broadly.\r\n\r\nIn addition to Sequoia, Amazon, and funds and accounts advised by T. Rowe Price Associates, Inc. are making significant investments in Aurora. Amazon’s unique expertise, capabilities, and perspectives will be valuable for us as we drive towards our mission.",source:"https://drive.google.com/open?id=1aLuuUqXKSQcGzivH21CSuO7204pdyP7K",years:"2019"},
13 {src:"Amazon",target:"Zoox",link:"Acquisition",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$1,200",region:"US",date:"2020-06-01",description:"Amazon acquires Zoox to help bring their vision of autonomous ride-hailing to reality. [The Financial Times reports that Amazon spends $1.2bn on the acquisition.]",source:"https://drive.google.com/open?id=18-zXDSHy9_o0OrIwYFfb5FdyMxMzgtHH",years:"2020"},
14 {src:"Amazon",target:"Rivian",link:"Investment",market:"Light_CV",tags:"Other",technology:"",aces:"Automated",amount:"",region:"US",date:"2020-10-01",description:"Amazon unveils its new electric delivery vans built by Rivian\nThe delivery giant aims to have 10,000 vehicles on the road by 2022, 100,000 vehicles expected by 2030.",source:"https://www.theverge.com/2020/10/8/21507495/amazon-electric-delivery-van-rivian-date-specs",years:"2020"},
15 {src:"Amazon",target:"Torc",link:"Partnership",market:"Semi_Truck",tags:"AD_L3-4| Edge/Cloud_computing",technology:"",aces:"Automated| Connected",amount:"",region:"US",date:"2021-02-17",description:"Torc selects AWS as preferred cloud provider for self-driving truck fleet",source:"https://drive.google.com/open?id=1QDHZIyUHpAY4oKEqmeM9cngPIWZWV2doE0r1emQZuNY",years:"2021"},
16 {src:"Amazon",target:"Intel",link:"Partnership",market:"PoV",tags:"Edge/Cloud_computing",technology:"",aces:"Connected",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-03-01",description:"Intel Achieves AWS High Performance Computing Competency Status",source:"https://drive.google.com/open?id=1MvhLikyzwbu-Mz_OuXUvytAuqXNEnUjHdSxMGXcKLok",years:"2021"},
17 {src:"Aurora",target:"Blackmore",link:"Acquisition",market:"Semi_Truck | Robotaxi",tags:"AD_Driverless",technology:"LiDAR",aces:"Automated",amount:"",region:"US",date:"2019-01-09",description:"Yesterday announce that they plan to acquire the industry-leading lidar company Blackmore, located in Bozeman, Montana.\r\n\r\nThe Bozeman, Montana–based outfit, which started up a decade ago to do work for the defense industry, uses a “frequency modulated continuous wave” system, also known as a Doppler lidar. When the infrared light hits an object and bounces back, the system determines both how far away it is and its velocity. Knowing where something is headed and how fast is prized data. Blackmore has at least one Doppler lidar competitor in Aeva, founded in early 2017 by a pair of former Apple engineers. [...]",source:"https://drive.google.com/open?id=1UkF-sxgA1AgpgWoRCd2qgWjovLQULoAP",years:"2019"},
18 {src:"Aurora",target:"Uber ATG",link:"Acquisition",market:"Robotaxi | Semi_Truck",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$4,000",region:"US",date:"2020-12-01",description:"Aurora is acquiring Uber's self-driving unit, ATG, accelerating the first Aurora Driver applications for heavy-duty trucks while allowing us to continue and accelerate our work on light-vehicle products. \"Simply put, Aurora will be the company best positioned to deliver the self-driving products necessary to make transportation and logistics safer, more accessible, and less expensive,\" said Chris Urmson, co-founder and CEO of Aurora.",source:"https://drive.google.com/open?id=1rc-_3VLlITe2bdxBgws3Bvb2rPvCluMfsMkFXiwbg98",years:"2020"},
19 {src:"Aurora",target:"Paccar",link:"Partnership",market:"Semi_Truck",tags:"AD_L3-4",technology:"",aces:"Automated",amount:"",region:"US",date:"2021-01-19",description:"Aurora teams up with PACCAR to build and deploy self-driving trucks",source:"https://drive.google.com/open?id=1TfA9U81CbyNwQc4Xfg2iJ9wqmka7RLqVEIsES2-62Ww",years:"2021"},
20 {src:"Aurora",target:"Denso",link:"Partnership",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-02-09",description:"Aurora enters into long-term, global, and strategic collaboration with Toyota and Denso",source:"https://drive.google.com/open?id=1QnlNnMMxbcPdnbi4AcBo36_UWM9TuMrNqItZHfPDUos",years:"2021"},
21 {src:"Aurora",target:"Toyota",link:"Partnership",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-02-09",description:"Aurora enters into long-term, global, and strategic collaboration with Toyota and Denso",source:"https://drive.google.com/open?id=1QnlNnMMxbcPdnbi4AcBo36_UWM9TuMrNqItZHfPDUos",years:"2021"},
22 {src:"Aurora",target:"OURS-Tech",link:"Acquisition",market:"Semi_Truck| Robotaxi",tags:"",technology:"LiDAR",aces:"Automated",amount:"",region:"US",date:"2021-02-26",description:"Aurora acquires OURS lidar (FMCW), unlocking the commercialization of its Aurora Driver",source:"https://drive.google.com/open?id=1TWEII1c0jQk26DcCC2WXw3plT0XTnfDzmD-e551VWSQ",years:"2021"},
23 {src:"Zoox",target:"ZadarLabs",link:"Investment",market:"PoV| Robotaxi",tags:"AD_L3-4| AD_Driverless",technology:"Radar",aces:"Automated",amount:"",region:"US",date:"2021-01-26",description:"Zadar Labs, Developing Next Generation Imaging Radar, Closes $5.6M in Seed Funding",source:"https://drive.google.com/open?id=1fz3MhS4P_Cmq2VmT9crQztUBd9W5Pj-IWEL9ABq3ySg",years:"2021"},
24 {src:"Intel",target:"Mobileye",link:"Acquisition",market:"PoV",tags:"AD_L3-4",technology:"",aces:"Automated",amount:"$15,000",region:"Worldwide",date:"2017-01-14",description:"Instead of Mobileye being integrated into Intel, Intel’s AD Group (ADG) will be integrated into Mobileye.",source:"https://www.engadget.com/2017-08-08-intel-acquisition-Mobileye-complete.html",years:"<2017"},
25 {src:"Intel",target:"Infineon",link:"Acquisition",market:"",tags:"",technology:"",aces:"Automated|Experience",amount:"1400",region:"US|EU",date:"2010-01-01",description:"Intel to Acquire Infineon’s Wireless Solutions Business",source:"https://www.infineon.com/cms/en/about-infineon/press/press-releases/2010/INFXX201008-069.html",years:"<2017"},
26 ]
27
28 const nodes = [
29 {id:"Amazon",type:"Tech",tags:"",technology:"",market:"Droid_Goods|Robotaxi",valuation:"",description:"Amazon is an international e-commerce website for consumers, sellers, and content creators.",country:"US",region:"North America",image:"https://images-eu.ssl-images-amazon.com/images/G/02/gc/designs/livepreview/a_generic_10_uk_noto_email_v2016_uk-main._CB485921599_.png"},
30 {id:"Aurora",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi|Semi_Truck",valuation:"1100",description:"Aurora is delivering the benefits of self-driving technology safely, quickly, and broadly.",country:"US",region:"North America",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/oeagjbu7wau6o16zdhb1"},
31 {id:"Zoox",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi",valuation:"",description:"Zoox is an AI robotics company that provides mobility as-a-service and self-driving car services.",country:"US",region:"North America",image:"https://res-4.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/kpc7mmk886nbbipbeqau"},
32 {id:"Rivian",type:"OEM",tags:"",technology:"",market:"PoV",valuation:"8200",description:"Rivian is an electric vehicle manufacturer that develops products and services to advance the shift to sustainable mobility.",country:"US",region:"North America",image:"https://res-4.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/sdz7aspakybuxp7oojvh"},
33 {id:"Torc",type:"Tier1",tags:"AD_Driverless|AD_L3-4",technology:"",market:"Semi_Truck|Mining",valuation:"",description:"Torc provides L4 end-to-end self-driving software for mobility, trucking, mining, and defense markets through strategic partnerships",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/smfgyxvfot1dwq4vqvo7"},
34 {id:"Intel",type:"Tech",tags:"",technology:"",market:"PoV | Robotaxi",valuation:"",description:"Intel designs, manufactures, and sells integrated digital technology platforms worldwide.",country:"US",region:"North America",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1505768454/wrhwa2ogipbd1o6tgggi.png"},
35 {id:"Blackmore",type:"Tier2",tags:"",technology:"LiDAR",market:"PoV|Other",valuation:"21.5",description:"Blackmore Sensors and Analytics develops frequency-modulated continuous wave lidar imaging and its supporting analytic tools software.",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1497015437/tqor2yimyfapcsn5uyaj.png"},
36 {id:"Uber ATG",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi",valuation:"1000",description:"Uber Advanced Technologies Group focuses on autonomous vehicles and the self-driving car business.",country:"US",region:"North America",image:"https://res-5.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/dlzugstswtlgq9wejmfi"},
37 {id:"Paccar",type:"OEM",tags:"",technology:"",market:"Semi_Truck",valuation:"",description:"Global technology leader in the design, manufacture and customer support of high-quality premium trucks.",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1404996232/nmvcucjqpgpnhrolbnnk.png"},
38 {id:"Denso",type:"Tier1",tags:"",technology:"",market:"PoV",valuation:"",description:"Supplier of advanced automotive technology",country:"Japan",region:"Japan",image:"https://res-5.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1398234958/fnjwkbbov8sivhs79wta.png"},
39 {id:"Toyota",type:"OEM",tags:"",technology:"",market:"PoV",valuation:"",description:"Toyota is a Japanese automotive company that manufactures and markets vehicles to over 170 countries and regions.",country:"Japan",region:"Japan",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1425366959/cleoo1wmofcfxxspobul.jpg"},
40 {id:"OURS-Tech",type:"Tier2",tags:"",technology:"LiDAR",market:"Semi_Truck| Robotaxi",valuation:"",description:"Enabling mass-production 5D LiDAR for the autonomous future",country:"US",region:"North America",image:"https://static.wixstatic.com/media/c668c3_f1f58317e99d41deac4152d212fcdbc2~mv2.gif"},
41 {id:"ZadarLabs",type:"Tier2",tags:"",technology:"Radar",market:"PoV| Robotaxi",valuation:"",description:"Zadar Labs brings radar intelligence to autonomous systems",country:"US",region:"North America",image:"https://res-1.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/g3kgj9vsfjzlpbichdml"},
42 {id:"Mobileye",type:"Tech",tags:"AS_NCAP|ADAS_uptoL2+|AD_Driverless",technology:"ECU_ADAS",market:"PoV|Robotaxi|Semi_Truck",valuation:"515",description:"Mobileye is a technology company developing vision-based advanced driver assistance systems that help prevent and mitigate collisions.",country:"Israel",region:"Others",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/bcuhhoflftvvdbpeaarx"},
43 {id:"Infineon",type:"Tier2",tags:"Interior_cocoon",technology:"",market:"PoV",valuation:"",description:"Infineon Technologies offers semiconductor solutions, microcontrollers, LED drivers, sensors and Automotive & Power Management ICs.",country:"Germany",region:"EU",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1397183702/79bc5b009247cfd1a274f2a328ff17bf.png"},
44
45 ]
46 const svg = d3.create("svg")
47 .attr("preserveAspectRatio", "xMinYMin meet")
48 .attr("viewBox", [-width/2,-height/2, width,height])
49 .classed("svg-content-responsive", true)
50
51 const defs = svg.append('svg:defs');
52
53
54 defs.append("svg:pattern")
55 .attr("id", "grump_avatar")
56 .attr("width", 1)
57 .attr("height", 1)
58 //.attr("patternUnits", "userSpaceOnUse")
59 .append("svg:image")
60 .attr("xlink:href", 'http://placekitten.com/g/48/48')
61 .attr("width",40)
62 .attr("height",40)
63 .attr("x",0)
64 .attr("y",0)
65
66
67 const link = svg.append("g")
68 .attr("stroke-opacity", 0.6)
69 .attr("stroke-width", 7)
70 .attr("stroke-linecap", "round")
71 .selectAll("line")
72 .data(links)
73 .join("line")
74
75 if (l) link.attr("stroke", ({index: i}) => setLinkColor(l[i])); // set conditional link color
76
77
78 const node = svg.append("g")
79 .attr("stroke", "teal")
80 .attr("stroke-opacity", 1)
81 .attr("stroke-width", 2)
82 .selectAll("circle")
83 .data(nodes)
84 .join("circle")
85 .style("fill", "#fff")
86 .style("fill", "url(#grump_avatar)")
87 .attr("r", 20)
88 .call(drag(simulation))
89
90
91
ANSWER
Answered 2021-Dec-08 at 12:15I've used your code to assemble a small example, which you can see below.
- Inside
svg > defs
, create onepattern
per node and use thatpattern
(with the ID of the company) to fetch the logo of that company; - Reference the
pattern
for the node using the information you already have.
Some pointers on your code:
- You already use ES6 logic, so you can also use
Array.prototype.map
and other functions. They're generally much more readable (and natively implemented!) thand3.map
; - There is no need to keep so many arrays of values, generally having fewer sources of truth for your data will make the code simpler to maintain and update in the future;
- Use clear variable names! LS and LT are logical when you know the context, but when you revisit this code in 6 months you might not instantly know what you were talking about when you wrote it.
1 <div class="main-map-container" style="overflow: hidden">
2 <div class="canvas">
3 <div>
4 <button id="zoom_in">+</button>
5 <button id="zoom_out">-</button>
6 </div>
7 </div>
8 </div>
9
10 const links = [
11 {src:"Amazon",target:"Aurora",link:"Investment",market:"Semi_Truck",tags:"AD_L3-4|AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US",date:"2019-02-01",description:"Amazon Investing in Aurora in an $530 million Financing Round",source:"https://drive.google.com/open?id=1aLuuUqXKSQcGzivH21CSuO7204pdyP7K",years:"2019"},
12 {src:"Amazon",target:"Aurora",link:"Investment",market:"Robotaxi | Semi_Truck",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$530",region:"EU| US",date:"2019-02-01",description:"Aurora announced that they have secured over $530 million in Series B financing led by Sequoia. This funding and partnership will accelerate their mission of delivering the benefits of self-driving technology safely, quickly, and broadly.\r\n\r\nIn addition to Sequoia, Amazon, and funds and accounts advised by T. Rowe Price Associates, Inc. are making significant investments in Aurora. Amazon’s unique expertise, capabilities, and perspectives will be valuable for us as we drive towards our mission.",source:"https://drive.google.com/open?id=1aLuuUqXKSQcGzivH21CSuO7204pdyP7K",years:"2019"},
13 {src:"Amazon",target:"Zoox",link:"Acquisition",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$1,200",region:"US",date:"2020-06-01",description:"Amazon acquires Zoox to help bring their vision of autonomous ride-hailing to reality. [The Financial Times reports that Amazon spends $1.2bn on the acquisition.]",source:"https://drive.google.com/open?id=18-zXDSHy9_o0OrIwYFfb5FdyMxMzgtHH",years:"2020"},
14 {src:"Amazon",target:"Rivian",link:"Investment",market:"Light_CV",tags:"Other",technology:"",aces:"Automated",amount:"",region:"US",date:"2020-10-01",description:"Amazon unveils its new electric delivery vans built by Rivian\nThe delivery giant aims to have 10,000 vehicles on the road by 2022, 100,000 vehicles expected by 2030.",source:"https://www.theverge.com/2020/10/8/21507495/amazon-electric-delivery-van-rivian-date-specs",years:"2020"},
15 {src:"Amazon",target:"Torc",link:"Partnership",market:"Semi_Truck",tags:"AD_L3-4| Edge/Cloud_computing",technology:"",aces:"Automated| Connected",amount:"",region:"US",date:"2021-02-17",description:"Torc selects AWS as preferred cloud provider for self-driving truck fleet",source:"https://drive.google.com/open?id=1QDHZIyUHpAY4oKEqmeM9cngPIWZWV2doE0r1emQZuNY",years:"2021"},
16 {src:"Amazon",target:"Intel",link:"Partnership",market:"PoV",tags:"Edge/Cloud_computing",technology:"",aces:"Connected",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-03-01",description:"Intel Achieves AWS High Performance Computing Competency Status",source:"https://drive.google.com/open?id=1MvhLikyzwbu-Mz_OuXUvytAuqXNEnUjHdSxMGXcKLok",years:"2021"},
17 {src:"Aurora",target:"Blackmore",link:"Acquisition",market:"Semi_Truck | Robotaxi",tags:"AD_Driverless",technology:"LiDAR",aces:"Automated",amount:"",region:"US",date:"2019-01-09",description:"Yesterday announce that they plan to acquire the industry-leading lidar company Blackmore, located in Bozeman, Montana.\r\n\r\nThe Bozeman, Montana–based outfit, which started up a decade ago to do work for the defense industry, uses a “frequency modulated continuous wave” system, also known as a Doppler lidar. When the infrared light hits an object and bounces back, the system determines both how far away it is and its velocity. Knowing where something is headed and how fast is prized data. Blackmore has at least one Doppler lidar competitor in Aeva, founded in early 2017 by a pair of former Apple engineers. [...]",source:"https://drive.google.com/open?id=1UkF-sxgA1AgpgWoRCd2qgWjovLQULoAP",years:"2019"},
18 {src:"Aurora",target:"Uber ATG",link:"Acquisition",market:"Robotaxi | Semi_Truck",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$4,000",region:"US",date:"2020-12-01",description:"Aurora is acquiring Uber's self-driving unit, ATG, accelerating the first Aurora Driver applications for heavy-duty trucks while allowing us to continue and accelerate our work on light-vehicle products. \"Simply put, Aurora will be the company best positioned to deliver the self-driving products necessary to make transportation and logistics safer, more accessible, and less expensive,\" said Chris Urmson, co-founder and CEO of Aurora.",source:"https://drive.google.com/open?id=1rc-_3VLlITe2bdxBgws3Bvb2rPvCluMfsMkFXiwbg98",years:"2020"},
19 {src:"Aurora",target:"Paccar",link:"Partnership",market:"Semi_Truck",tags:"AD_L3-4",technology:"",aces:"Automated",amount:"",region:"US",date:"2021-01-19",description:"Aurora teams up with PACCAR to build and deploy self-driving trucks",source:"https://drive.google.com/open?id=1TfA9U81CbyNwQc4Xfg2iJ9wqmka7RLqVEIsES2-62Ww",years:"2021"},
20 {src:"Aurora",target:"Denso",link:"Partnership",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-02-09",description:"Aurora enters into long-term, global, and strategic collaboration with Toyota and Denso",source:"https://drive.google.com/open?id=1QnlNnMMxbcPdnbi4AcBo36_UWM9TuMrNqItZHfPDUos",years:"2021"},
21 {src:"Aurora",target:"Toyota",link:"Partnership",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-02-09",description:"Aurora enters into long-term, global, and strategic collaboration with Toyota and Denso",source:"https://drive.google.com/open?id=1QnlNnMMxbcPdnbi4AcBo36_UWM9TuMrNqItZHfPDUos",years:"2021"},
22 {src:"Aurora",target:"OURS-Tech",link:"Acquisition",market:"Semi_Truck| Robotaxi",tags:"",technology:"LiDAR",aces:"Automated",amount:"",region:"US",date:"2021-02-26",description:"Aurora acquires OURS lidar (FMCW), unlocking the commercialization of its Aurora Driver",source:"https://drive.google.com/open?id=1TWEII1c0jQk26DcCC2WXw3plT0XTnfDzmD-e551VWSQ",years:"2021"},
23 {src:"Zoox",target:"ZadarLabs",link:"Investment",market:"PoV| Robotaxi",tags:"AD_L3-4| AD_Driverless",technology:"Radar",aces:"Automated",amount:"",region:"US",date:"2021-01-26",description:"Zadar Labs, Developing Next Generation Imaging Radar, Closes $5.6M in Seed Funding",source:"https://drive.google.com/open?id=1fz3MhS4P_Cmq2VmT9crQztUBd9W5Pj-IWEL9ABq3ySg",years:"2021"},
24 {src:"Intel",target:"Mobileye",link:"Acquisition",market:"PoV",tags:"AD_L3-4",technology:"",aces:"Automated",amount:"$15,000",region:"Worldwide",date:"2017-01-14",description:"Instead of Mobileye being integrated into Intel, Intel’s AD Group (ADG) will be integrated into Mobileye.",source:"https://www.engadget.com/2017-08-08-intel-acquisition-Mobileye-complete.html",years:"<2017"},
25 {src:"Intel",target:"Infineon",link:"Acquisition",market:"",tags:"",technology:"",aces:"Automated|Experience",amount:"1400",region:"US|EU",date:"2010-01-01",description:"Intel to Acquire Infineon’s Wireless Solutions Business",source:"https://www.infineon.com/cms/en/about-infineon/press/press-releases/2010/INFXX201008-069.html",years:"<2017"},
26 ]
27
28 const nodes = [
29 {id:"Amazon",type:"Tech",tags:"",technology:"",market:"Droid_Goods|Robotaxi",valuation:"",description:"Amazon is an international e-commerce website for consumers, sellers, and content creators.",country:"US",region:"North America",image:"https://images-eu.ssl-images-amazon.com/images/G/02/gc/designs/livepreview/a_generic_10_uk_noto_email_v2016_uk-main._CB485921599_.png"},
30 {id:"Aurora",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi|Semi_Truck",valuation:"1100",description:"Aurora is delivering the benefits of self-driving technology safely, quickly, and broadly.",country:"US",region:"North America",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/oeagjbu7wau6o16zdhb1"},
31 {id:"Zoox",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi",valuation:"",description:"Zoox is an AI robotics company that provides mobility as-a-service and self-driving car services.",country:"US",region:"North America",image:"https://res-4.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/kpc7mmk886nbbipbeqau"},
32 {id:"Rivian",type:"OEM",tags:"",technology:"",market:"PoV",valuation:"8200",description:"Rivian is an electric vehicle manufacturer that develops products and services to advance the shift to sustainable mobility.",country:"US",region:"North America",image:"https://res-4.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/sdz7aspakybuxp7oojvh"},
33 {id:"Torc",type:"Tier1",tags:"AD_Driverless|AD_L3-4",technology:"",market:"Semi_Truck|Mining",valuation:"",description:"Torc provides L4 end-to-end self-driving software for mobility, trucking, mining, and defense markets through strategic partnerships",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/smfgyxvfot1dwq4vqvo7"},
34 {id:"Intel",type:"Tech",tags:"",technology:"",market:"PoV | Robotaxi",valuation:"",description:"Intel designs, manufactures, and sells integrated digital technology platforms worldwide.",country:"US",region:"North America",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1505768454/wrhwa2ogipbd1o6tgggi.png"},
35 {id:"Blackmore",type:"Tier2",tags:"",technology:"LiDAR",market:"PoV|Other",valuation:"21.5",description:"Blackmore Sensors and Analytics develops frequency-modulated continuous wave lidar imaging and its supporting analytic tools software.",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1497015437/tqor2yimyfapcsn5uyaj.png"},
36 {id:"Uber ATG",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi",valuation:"1000",description:"Uber Advanced Technologies Group focuses on autonomous vehicles and the self-driving car business.",country:"US",region:"North America",image:"https://res-5.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/dlzugstswtlgq9wejmfi"},
37 {id:"Paccar",type:"OEM",tags:"",technology:"",market:"Semi_Truck",valuation:"",description:"Global technology leader in the design, manufacture and customer support of high-quality premium trucks.",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1404996232/nmvcucjqpgpnhrolbnnk.png"},
38 {id:"Denso",type:"Tier1",tags:"",technology:"",market:"PoV",valuation:"",description:"Supplier of advanced automotive technology",country:"Japan",region:"Japan",image:"https://res-5.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1398234958/fnjwkbbov8sivhs79wta.png"},
39 {id:"Toyota",type:"OEM",tags:"",technology:"",market:"PoV",valuation:"",description:"Toyota is a Japanese automotive company that manufactures and markets vehicles to over 170 countries and regions.",country:"Japan",region:"Japan",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1425366959/cleoo1wmofcfxxspobul.jpg"},
40 {id:"OURS-Tech",type:"Tier2",tags:"",technology:"LiDAR",market:"Semi_Truck| Robotaxi",valuation:"",description:"Enabling mass-production 5D LiDAR for the autonomous future",country:"US",region:"North America",image:"https://static.wixstatic.com/media/c668c3_f1f58317e99d41deac4152d212fcdbc2~mv2.gif"},
41 {id:"ZadarLabs",type:"Tier2",tags:"",technology:"Radar",market:"PoV| Robotaxi",valuation:"",description:"Zadar Labs brings radar intelligence to autonomous systems",country:"US",region:"North America",image:"https://res-1.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/g3kgj9vsfjzlpbichdml"},
42 {id:"Mobileye",type:"Tech",tags:"AS_NCAP|ADAS_uptoL2+|AD_Driverless",technology:"ECU_ADAS",market:"PoV|Robotaxi|Semi_Truck",valuation:"515",description:"Mobileye is a technology company developing vision-based advanced driver assistance systems that help prevent and mitigate collisions.",country:"Israel",region:"Others",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/bcuhhoflftvvdbpeaarx"},
43 {id:"Infineon",type:"Tier2",tags:"Interior_cocoon",technology:"",market:"PoV",valuation:"",description:"Infineon Technologies offers semiconductor solutions, microcontrollers, LED drivers, sensors and Automotive & Power Management ICs.",country:"Germany",region:"EU",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1397183702/79bc5b009247cfd1a274f2a328ff17bf.png"},
44
45 ]
46 const svg = d3.create("svg")
47 .attr("preserveAspectRatio", "xMinYMin meet")
48 .attr("viewBox", [-width/2,-height/2, width,height])
49 .classed("svg-content-responsive", true)
50
51 const defs = svg.append('svg:defs');
52
53
54 defs.append("svg:pattern")
55 .attr("id", "grump_avatar")
56 .attr("width", 1)
57 .attr("height", 1)
58 //.attr("patternUnits", "userSpaceOnUse")
59 .append("svg:image")
60 .attr("xlink:href", 'http://placekitten.com/g/48/48')
61 .attr("width",40)
62 .attr("height",40)
63 .attr("x",0)
64 .attr("y",0)
65
66
67 const link = svg.append("g")
68 .attr("stroke-opacity", 0.6)
69 .attr("stroke-width", 7)
70 .attr("stroke-linecap", "round")
71 .selectAll("line")
72 .data(links)
73 .join("line")
74
75 if (l) link.attr("stroke", ({index: i}) => setLinkColor(l[i])); // set conditional link color
76
77
78 const node = svg.append("g")
79 .attr("stroke", "teal")
80 .attr("stroke-opacity", 1)
81 .attr("stroke-width", 2)
82 .selectAll("circle")
83 .data(nodes)
84 .join("circle")
85 .style("fill", "#fff")
86 .style("fill", "url(#grump_avatar)")
87 .attr("r", 20)
88 .call(drag(simulation))
89
90
91const nodes = [{
92 id: "Amazon",
93 image: "https://images-eu.ssl-images-amazon.com/images/G/02/gc/designs/livepreview/a_generic_10_uk_noto_email_v2016_uk-main._CB485921599_.png"
94 },
95 {
96 id: "Aurora",
97 image: "https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/oeagjbu7wau6o16zdhb1"
98 },
99 {
100 id: "Zoox",
101 image: "https://res-4.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/kpc7mmk886nbbipbeqau"
102 }
103];
104
105const links = [{
106 src: 'Amazon',
107 target: 'Aurora'
108 },
109 {
110 src: 'Amazon',
111 target: 'Zoox'
112 },
113 {
114 src: 'Aurora',
115 target: 'Zoox'
116 }
117];
118
119const width = 500,
120 height = 500;
121
122function ForceGraph({
123 nodes, // an iterable of node objects (typically [{id}, …])
124 links // an iterable of link objects (typically [{src, target}, …])
125}, {
126 nodeId = d => d.id, // given d in nodes, returns a unique identifier (string)
127 nodeTitle, // given d in nodes, a title string
128 nodeStroke = "teal", // node stroke color
129 nodeStrokeWidth = 2, // node stroke width, in pixels
130 nodeStrokeOpacity = 1, // node stroke opacity
131 nodeRadius = 20, // node radius, in pixels
132 nodeStrength = -750,
133 linkDistance = 100,
134 linkStrokeOpacity = 0.6, // link stroke opacity
135 linkStrokeWidth = 7, // given d in links, returns a stroke width in pixels
136 linkStrokeLinecap = "round", // link stroke linecap
137 linkStrength,
138 container
139} = {}) {
140
141 // Compute values.
142 const N = d3.map(nodes, nodeId);
143
144 // HERE: Don't replace the input nodes using this complex method,
145 // just Object.assign({}, n) to essentially perform a deep copy of a node.
146
147 // Replace the input nodes and links with mutable objects for the simulation.
148 nodes = nodes.map(n => Object.assign({}, n));
149 links = links.map(l => ({
150 source: l.src,
151 target: l.target
152 }));
153
154 const svg = d3.select('body')
155 .append("svg")
156 .attr("preserveAspectRatio", "xMinYMin meet")
157 .attr("viewBox", [-width / 2, -height / 2, width, height])
158 .classed("svg-content-responsive", true)
159
160 const defs = svg.append('svg:defs');
161
162 // HERE: See we add one image per node
163 defs.selectAll("pattern")
164 .data(nodes)
165 .join(
166 enter => {
167 // For every new <pattern>, set the constants and append an <image> tag
168 const patterns = enter
169 .append("pattern")
170 .attr("width", 48)
171 .attr("height", 48);
172 patterns
173 .append("image")
174 .attr("width", 48)
175 .attr("height", 48)
176 .attr("x", 0)
177 .attr("y", 0);
178 return patterns;
179 }
180 )
181 // For every <pattern>, set it to point to the correct
182 // URL and have the correct (company) ID
183 .attr("id", d => d.id)
184 .select("image")
185 .datum(d => {
186 debugger;
187 return d;
188 })
189 .attr("xlink:href", d => {
190 debugger;
191 return d.image;
192 })
193
194 const link = svg.append("g")
195 .attr("stroke-opacity", linkStrokeOpacity)
196 .attr("stroke-width", linkStrokeWidth)
197 .attr("stroke-linecap", linkStrokeLinecap)
198 .selectAll("line")
199 .data(links)
200 .join("line");
201
202 // Construct the forces.
203 const forceNode = d3.forceManyBody();
204 const forceLink = d3.forceLink(links).id(({
205 index: i
206 }) => N[i]);
207 if (nodeStrength !== undefined) forceNode.strength(nodeStrength);
208 if (linkStrength !== undefined) forceLink.strength(linkStrength);
209 forceLink.distance(linkDistance)
210 const simulation = d3.forceSimulation(nodes)
211 .force(link, forceLink)
212 .force("charge", forceNode)
213 .force("x", d3.forceX())
214 .force("y", d3.forceY())
215 .on("tick", ticked);
216
217 const node = svg.append("g")
218 .attr("stroke", nodeStroke)
219 .attr("stroke-opacity", nodeStrokeOpacity)
220 .attr("stroke-width", nodeStrokeWidth)
221 .selectAll("circle")
222 .data(nodes)
223 .join("circle")
224 .style("fill", "#fff")
225 .style("fill", d => `url(#${d.id})`)
226 .attr("r", nodeRadius);
227
228 function ticked() {
229 link
230 .attr("x1", d => d.source.x)
231 .attr("y1", d => d.source.y)
232 .attr("x2", d => d.target.x)
233 .attr("y2", d => d.target.y);
234 node
235 .attr("cx", d => d.x)
236 .attr("cy", d => d.y);
237 }
238} // ForceGraph
239
240ForceGraph({
241 nodes,
242 links
243});
1 <div class="main-map-container" style="overflow: hidden">
2 <div class="canvas">
3 <div>
4 <button id="zoom_in">+</button>
5 <button id="zoom_out">-</button>
6 </div>
7 </div>
8 </div>
9
10 const links = [
11 {src:"Amazon",target:"Aurora",link:"Investment",market:"Semi_Truck",tags:"AD_L3-4|AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US",date:"2019-02-01",description:"Amazon Investing in Aurora in an $530 million Financing Round",source:"https://drive.google.com/open?id=1aLuuUqXKSQcGzivH21CSuO7204pdyP7K",years:"2019"},
12 {src:"Amazon",target:"Aurora",link:"Investment",market:"Robotaxi | Semi_Truck",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$530",region:"EU| US",date:"2019-02-01",description:"Aurora announced that they have secured over $530 million in Series B financing led by Sequoia. This funding and partnership will accelerate their mission of delivering the benefits of self-driving technology safely, quickly, and broadly.\r\n\r\nIn addition to Sequoia, Amazon, and funds and accounts advised by T. Rowe Price Associates, Inc. are making significant investments in Aurora. Amazon’s unique expertise, capabilities, and perspectives will be valuable for us as we drive towards our mission.",source:"https://drive.google.com/open?id=1aLuuUqXKSQcGzivH21CSuO7204pdyP7K",years:"2019"},
13 {src:"Amazon",target:"Zoox",link:"Acquisition",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$1,200",region:"US",date:"2020-06-01",description:"Amazon acquires Zoox to help bring their vision of autonomous ride-hailing to reality. [The Financial Times reports that Amazon spends $1.2bn on the acquisition.]",source:"https://drive.google.com/open?id=18-zXDSHy9_o0OrIwYFfb5FdyMxMzgtHH",years:"2020"},
14 {src:"Amazon",target:"Rivian",link:"Investment",market:"Light_CV",tags:"Other",technology:"",aces:"Automated",amount:"",region:"US",date:"2020-10-01",description:"Amazon unveils its new electric delivery vans built by Rivian\nThe delivery giant aims to have 10,000 vehicles on the road by 2022, 100,000 vehicles expected by 2030.",source:"https://www.theverge.com/2020/10/8/21507495/amazon-electric-delivery-van-rivian-date-specs",years:"2020"},
15 {src:"Amazon",target:"Torc",link:"Partnership",market:"Semi_Truck",tags:"AD_L3-4| Edge/Cloud_computing",technology:"",aces:"Automated| Connected",amount:"",region:"US",date:"2021-02-17",description:"Torc selects AWS as preferred cloud provider for self-driving truck fleet",source:"https://drive.google.com/open?id=1QDHZIyUHpAY4oKEqmeM9cngPIWZWV2doE0r1emQZuNY",years:"2021"},
16 {src:"Amazon",target:"Intel",link:"Partnership",market:"PoV",tags:"Edge/Cloud_computing",technology:"",aces:"Connected",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-03-01",description:"Intel Achieves AWS High Performance Computing Competency Status",source:"https://drive.google.com/open?id=1MvhLikyzwbu-Mz_OuXUvytAuqXNEnUjHdSxMGXcKLok",years:"2021"},
17 {src:"Aurora",target:"Blackmore",link:"Acquisition",market:"Semi_Truck | Robotaxi",tags:"AD_Driverless",technology:"LiDAR",aces:"Automated",amount:"",region:"US",date:"2019-01-09",description:"Yesterday announce that they plan to acquire the industry-leading lidar company Blackmore, located in Bozeman, Montana.\r\n\r\nThe Bozeman, Montana–based outfit, which started up a decade ago to do work for the defense industry, uses a “frequency modulated continuous wave” system, also known as a Doppler lidar. When the infrared light hits an object and bounces back, the system determines both how far away it is and its velocity. Knowing where something is headed and how fast is prized data. Blackmore has at least one Doppler lidar competitor in Aeva, founded in early 2017 by a pair of former Apple engineers. [...]",source:"https://drive.google.com/open?id=1UkF-sxgA1AgpgWoRCd2qgWjovLQULoAP",years:"2019"},
18 {src:"Aurora",target:"Uber ATG",link:"Acquisition",market:"Robotaxi | Semi_Truck",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$4,000",region:"US",date:"2020-12-01",description:"Aurora is acquiring Uber's self-driving unit, ATG, accelerating the first Aurora Driver applications for heavy-duty trucks while allowing us to continue and accelerate our work on light-vehicle products. \"Simply put, Aurora will be the company best positioned to deliver the self-driving products necessary to make transportation and logistics safer, more accessible, and less expensive,\" said Chris Urmson, co-founder and CEO of Aurora.",source:"https://drive.google.com/open?id=1rc-_3VLlITe2bdxBgws3Bvb2rPvCluMfsMkFXiwbg98",years:"2020"},
19 {src:"Aurora",target:"Paccar",link:"Partnership",market:"Semi_Truck",tags:"AD_L3-4",technology:"",aces:"Automated",amount:"",region:"US",date:"2021-01-19",description:"Aurora teams up with PACCAR to build and deploy self-driving trucks",source:"https://drive.google.com/open?id=1TfA9U81CbyNwQc4Xfg2iJ9wqmka7RLqVEIsES2-62Ww",years:"2021"},
20 {src:"Aurora",target:"Denso",link:"Partnership",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-02-09",description:"Aurora enters into long-term, global, and strategic collaboration with Toyota and Denso",source:"https://drive.google.com/open?id=1QnlNnMMxbcPdnbi4AcBo36_UWM9TuMrNqItZHfPDUos",years:"2021"},
21 {src:"Aurora",target:"Toyota",link:"Partnership",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-02-09",description:"Aurora enters into long-term, global, and strategic collaboration with Toyota and Denso",source:"https://drive.google.com/open?id=1QnlNnMMxbcPdnbi4AcBo36_UWM9TuMrNqItZHfPDUos",years:"2021"},
22 {src:"Aurora",target:"OURS-Tech",link:"Acquisition",market:"Semi_Truck| Robotaxi",tags:"",technology:"LiDAR",aces:"Automated",amount:"",region:"US",date:"2021-02-26",description:"Aurora acquires OURS lidar (FMCW), unlocking the commercialization of its Aurora Driver",source:"https://drive.google.com/open?id=1TWEII1c0jQk26DcCC2WXw3plT0XTnfDzmD-e551VWSQ",years:"2021"},
23 {src:"Zoox",target:"ZadarLabs",link:"Investment",market:"PoV| Robotaxi",tags:"AD_L3-4| AD_Driverless",technology:"Radar",aces:"Automated",amount:"",region:"US",date:"2021-01-26",description:"Zadar Labs, Developing Next Generation Imaging Radar, Closes $5.6M in Seed Funding",source:"https://drive.google.com/open?id=1fz3MhS4P_Cmq2VmT9crQztUBd9W5Pj-IWEL9ABq3ySg",years:"2021"},
24 {src:"Intel",target:"Mobileye",link:"Acquisition",market:"PoV",tags:"AD_L3-4",technology:"",aces:"Automated",amount:"$15,000",region:"Worldwide",date:"2017-01-14",description:"Instead of Mobileye being integrated into Intel, Intel’s AD Group (ADG) will be integrated into Mobileye.",source:"https://www.engadget.com/2017-08-08-intel-acquisition-Mobileye-complete.html",years:"<2017"},
25 {src:"Intel",target:"Infineon",link:"Acquisition",market:"",tags:"",technology:"",aces:"Automated|Experience",amount:"1400",region:"US|EU",date:"2010-01-01",description:"Intel to Acquire Infineon’s Wireless Solutions Business",source:"https://www.infineon.com/cms/en/about-infineon/press/press-releases/2010/INFXX201008-069.html",years:"<2017"},
26 ]
27
28 const nodes = [
29 {id:"Amazon",type:"Tech",tags:"",technology:"",market:"Droid_Goods|Robotaxi",valuation:"",description:"Amazon is an international e-commerce website for consumers, sellers, and content creators.",country:"US",region:"North America",image:"https://images-eu.ssl-images-amazon.com/images/G/02/gc/designs/livepreview/a_generic_10_uk_noto_email_v2016_uk-main._CB485921599_.png"},
30 {id:"Aurora",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi|Semi_Truck",valuation:"1100",description:"Aurora is delivering the benefits of self-driving technology safely, quickly, and broadly.",country:"US",region:"North America",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/oeagjbu7wau6o16zdhb1"},
31 {id:"Zoox",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi",valuation:"",description:"Zoox is an AI robotics company that provides mobility as-a-service and self-driving car services.",country:"US",region:"North America",image:"https://res-4.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/kpc7mmk886nbbipbeqau"},
32 {id:"Rivian",type:"OEM",tags:"",technology:"",market:"PoV",valuation:"8200",description:"Rivian is an electric vehicle manufacturer that develops products and services to advance the shift to sustainable mobility.",country:"US",region:"North America",image:"https://res-4.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/sdz7aspakybuxp7oojvh"},
33 {id:"Torc",type:"Tier1",tags:"AD_Driverless|AD_L3-4",technology:"",market:"Semi_Truck|Mining",valuation:"",description:"Torc provides L4 end-to-end self-driving software for mobility, trucking, mining, and defense markets through strategic partnerships",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/smfgyxvfot1dwq4vqvo7"},
34 {id:"Intel",type:"Tech",tags:"",technology:"",market:"PoV | Robotaxi",valuation:"",description:"Intel designs, manufactures, and sells integrated digital technology platforms worldwide.",country:"US",region:"North America",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1505768454/wrhwa2ogipbd1o6tgggi.png"},
35 {id:"Blackmore",type:"Tier2",tags:"",technology:"LiDAR",market:"PoV|Other",valuation:"21.5",description:"Blackmore Sensors and Analytics develops frequency-modulated continuous wave lidar imaging and its supporting analytic tools software.",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1497015437/tqor2yimyfapcsn5uyaj.png"},
36 {id:"Uber ATG",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi",valuation:"1000",description:"Uber Advanced Technologies Group focuses on autonomous vehicles and the self-driving car business.",country:"US",region:"North America",image:"https://res-5.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/dlzugstswtlgq9wejmfi"},
37 {id:"Paccar",type:"OEM",tags:"",technology:"",market:"Semi_Truck",valuation:"",description:"Global technology leader in the design, manufacture and customer support of high-quality premium trucks.",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1404996232/nmvcucjqpgpnhrolbnnk.png"},
38 {id:"Denso",type:"Tier1",tags:"",technology:"",market:"PoV",valuation:"",description:"Supplier of advanced automotive technology",country:"Japan",region:"Japan",image:"https://res-5.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1398234958/fnjwkbbov8sivhs79wta.png"},
39 {id:"Toyota",type:"OEM",tags:"",technology:"",market:"PoV",valuation:"",description:"Toyota is a Japanese automotive company that manufactures and markets vehicles to over 170 countries and regions.",country:"Japan",region:"Japan",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1425366959/cleoo1wmofcfxxspobul.jpg"},
40 {id:"OURS-Tech",type:"Tier2",tags:"",technology:"LiDAR",market:"Semi_Truck| Robotaxi",valuation:"",description:"Enabling mass-production 5D LiDAR for the autonomous future",country:"US",region:"North America",image:"https://static.wixstatic.com/media/c668c3_f1f58317e99d41deac4152d212fcdbc2~mv2.gif"},
41 {id:"ZadarLabs",type:"Tier2",tags:"",technology:"Radar",market:"PoV| Robotaxi",valuation:"",description:"Zadar Labs brings radar intelligence to autonomous systems",country:"US",region:"North America",image:"https://res-1.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/g3kgj9vsfjzlpbichdml"},
42 {id:"Mobileye",type:"Tech",tags:"AS_NCAP|ADAS_uptoL2+|AD_Driverless",technology:"ECU_ADAS",market:"PoV|Robotaxi|Semi_Truck",valuation:"515",description:"Mobileye is a technology company developing vision-based advanced driver assistance systems that help prevent and mitigate collisions.",country:"Israel",region:"Others",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/bcuhhoflftvvdbpeaarx"},
43 {id:"Infineon",type:"Tier2",tags:"Interior_cocoon",technology:"",market:"PoV",valuation:"",description:"Infineon Technologies offers semiconductor solutions, microcontrollers, LED drivers, sensors and Automotive & Power Management ICs.",country:"Germany",region:"EU",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1397183702/79bc5b009247cfd1a274f2a328ff17bf.png"},
44
45 ]
46 const svg = d3.create("svg")
47 .attr("preserveAspectRatio", "xMinYMin meet")
48 .attr("viewBox", [-width/2,-height/2, width,height])
49 .classed("svg-content-responsive", true)
50
51 const defs = svg.append('svg:defs');
52
53
54 defs.append("svg:pattern")
55 .attr("id", "grump_avatar")
56 .attr("width", 1)
57 .attr("height", 1)
58 //.attr("patternUnits", "userSpaceOnUse")
59 .append("svg:image")
60 .attr("xlink:href", 'http://placekitten.com/g/48/48')
61 .attr("width",40)
62 .attr("height",40)
63 .attr("x",0)
64 .attr("y",0)
65
66
67 const link = svg.append("g")
68 .attr("stroke-opacity", 0.6)
69 .attr("stroke-width", 7)
70 .attr("stroke-linecap", "round")
71 .selectAll("line")
72 .data(links)
73 .join("line")
74
75 if (l) link.attr("stroke", ({index: i}) => setLinkColor(l[i])); // set conditional link color
76
77
78 const node = svg.append("g")
79 .attr("stroke", "teal")
80 .attr("stroke-opacity", 1)
81 .attr("stroke-width", 2)
82 .selectAll("circle")
83 .data(nodes)
84 .join("circle")
85 .style("fill", "#fff")
86 .style("fill", "url(#grump_avatar)")
87 .attr("r", 20)
88 .call(drag(simulation))
89
90
91const nodes = [{
92 id: "Amazon",
93 image: "https://images-eu.ssl-images-amazon.com/images/G/02/gc/designs/livepreview/a_generic_10_uk_noto_email_v2016_uk-main._CB485921599_.png"
94 },
95 {
96 id: "Aurora",
97 image: "https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/oeagjbu7wau6o16zdhb1"
98 },
99 {
100 id: "Zoox",
101 image: "https://res-4.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/kpc7mmk886nbbipbeqau"
102 }
103];
104
105const links = [{
106 src: 'Amazon',
107 target: 'Aurora'
108 },
109 {
110 src: 'Amazon',
111 target: 'Zoox'
112 },
113 {
114 src: 'Aurora',
115 target: 'Zoox'
116 }
117];
118
119const width = 500,
120 height = 500;
121
122function ForceGraph({
123 nodes, // an iterable of node objects (typically [{id}, …])
124 links // an iterable of link objects (typically [{src, target}, …])
125}, {
126 nodeId = d => d.id, // given d in nodes, returns a unique identifier (string)
127 nodeTitle, // given d in nodes, a title string
128 nodeStroke = "teal", // node stroke color
129 nodeStrokeWidth = 2, // node stroke width, in pixels
130 nodeStrokeOpacity = 1, // node stroke opacity
131 nodeRadius = 20, // node radius, in pixels
132 nodeStrength = -750,
133 linkDistance = 100,
134 linkStrokeOpacity = 0.6, // link stroke opacity
135 linkStrokeWidth = 7, // given d in links, returns a stroke width in pixels
136 linkStrokeLinecap = "round", // link stroke linecap
137 linkStrength,
138 container
139} = {}) {
140
141 // Compute values.
142 const N = d3.map(nodes, nodeId);
143
144 // HERE: Don't replace the input nodes using this complex method,
145 // just Object.assign({}, n) to essentially perform a deep copy of a node.
146
147 // Replace the input nodes and links with mutable objects for the simulation.
148 nodes = nodes.map(n => Object.assign({}, n));
149 links = links.map(l => ({
150 source: l.src,
151 target: l.target
152 }));
153
154 const svg = d3.select('body')
155 .append("svg")
156 .attr("preserveAspectRatio", "xMinYMin meet")
157 .attr("viewBox", [-width / 2, -height / 2, width, height])
158 .classed("svg-content-responsive", true)
159
160 const defs = svg.append('svg:defs');
161
162 // HERE: See we add one image per node
163 defs.selectAll("pattern")
164 .data(nodes)
165 .join(
166 enter => {
167 // For every new <pattern>, set the constants and append an <image> tag
168 const patterns = enter
169 .append("pattern")
170 .attr("width", 48)
171 .attr("height", 48);
172 patterns
173 .append("image")
174 .attr("width", 48)
175 .attr("height", 48)
176 .attr("x", 0)
177 .attr("y", 0);
178 return patterns;
179 }
180 )
181 // For every <pattern>, set it to point to the correct
182 // URL and have the correct (company) ID
183 .attr("id", d => d.id)
184 .select("image")
185 .datum(d => {
186 debugger;
187 return d;
188 })
189 .attr("xlink:href", d => {
190 debugger;
191 return d.image;
192 })
193
194 const link = svg.append("g")
195 .attr("stroke-opacity", linkStrokeOpacity)
196 .attr("stroke-width", linkStrokeWidth)
197 .attr("stroke-linecap", linkStrokeLinecap)
198 .selectAll("line")
199 .data(links)
200 .join("line");
201
202 // Construct the forces.
203 const forceNode = d3.forceManyBody();
204 const forceLink = d3.forceLink(links).id(({
205 index: i
206 }) => N[i]);
207 if (nodeStrength !== undefined) forceNode.strength(nodeStrength);
208 if (linkStrength !== undefined) forceLink.strength(linkStrength);
209 forceLink.distance(linkDistance)
210 const simulation = d3.forceSimulation(nodes)
211 .force(link, forceLink)
212 .force("charge", forceNode)
213 .force("x", d3.forceX())
214 .force("y", d3.forceY())
215 .on("tick", ticked);
216
217 const node = svg.append("g")
218 .attr("stroke", nodeStroke)
219 .attr("stroke-opacity", nodeStrokeOpacity)
220 .attr("stroke-width", nodeStrokeWidth)
221 .selectAll("circle")
222 .data(nodes)
223 .join("circle")
224 .style("fill", "#fff")
225 .style("fill", d => `url(#${d.id})`)
226 .attr("r", nodeRadius);
227
228 function ticked() {
229 link
230 .attr("x1", d => d.source.x)
231 .attr("y1", d => d.source.y)
232 .attr("x2", d => d.target.x)
233 .attr("y2", d => d.target.y);
234 node
235 .attr("cx", d => d.x)
236 .attr("cy", d => d.y);
237 }
238} // ForceGraph
239
240ForceGraph({
241 nodes,
242 links
243});line {
244 stroke: red;
245}
1 <div class="main-map-container" style="overflow: hidden">
2 <div class="canvas">
3 <div>
4 <button id="zoom_in">+</button>
5 <button id="zoom_out">-</button>
6 </div>
7 </div>
8 </div>
9
10 const links = [
11 {src:"Amazon",target:"Aurora",link:"Investment",market:"Semi_Truck",tags:"AD_L3-4|AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US",date:"2019-02-01",description:"Amazon Investing in Aurora in an $530 million Financing Round",source:"https://drive.google.com/open?id=1aLuuUqXKSQcGzivH21CSuO7204pdyP7K",years:"2019"},
12 {src:"Amazon",target:"Aurora",link:"Investment",market:"Robotaxi | Semi_Truck",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$530",region:"EU| US",date:"2019-02-01",description:"Aurora announced that they have secured over $530 million in Series B financing led by Sequoia. This funding and partnership will accelerate their mission of delivering the benefits of self-driving technology safely, quickly, and broadly.\r\n\r\nIn addition to Sequoia, Amazon, and funds and accounts advised by T. Rowe Price Associates, Inc. are making significant investments in Aurora. Amazon’s unique expertise, capabilities, and perspectives will be valuable for us as we drive towards our mission.",source:"https://drive.google.com/open?id=1aLuuUqXKSQcGzivH21CSuO7204pdyP7K",years:"2019"},
13 {src:"Amazon",target:"Zoox",link:"Acquisition",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$1,200",region:"US",date:"2020-06-01",description:"Amazon acquires Zoox to help bring their vision of autonomous ride-hailing to reality. [The Financial Times reports that Amazon spends $1.2bn on the acquisition.]",source:"https://drive.google.com/open?id=18-zXDSHy9_o0OrIwYFfb5FdyMxMzgtHH",years:"2020"},
14 {src:"Amazon",target:"Rivian",link:"Investment",market:"Light_CV",tags:"Other",technology:"",aces:"Automated",amount:"",region:"US",date:"2020-10-01",description:"Amazon unveils its new electric delivery vans built by Rivian\nThe delivery giant aims to have 10,000 vehicles on the road by 2022, 100,000 vehicles expected by 2030.",source:"https://www.theverge.com/2020/10/8/21507495/amazon-electric-delivery-van-rivian-date-specs",years:"2020"},
15 {src:"Amazon",target:"Torc",link:"Partnership",market:"Semi_Truck",tags:"AD_L3-4| Edge/Cloud_computing",technology:"",aces:"Automated| Connected",amount:"",region:"US",date:"2021-02-17",description:"Torc selects AWS as preferred cloud provider for self-driving truck fleet",source:"https://drive.google.com/open?id=1QDHZIyUHpAY4oKEqmeM9cngPIWZWV2doE0r1emQZuNY",years:"2021"},
16 {src:"Amazon",target:"Intel",link:"Partnership",market:"PoV",tags:"Edge/Cloud_computing",technology:"",aces:"Connected",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-03-01",description:"Intel Achieves AWS High Performance Computing Competency Status",source:"https://drive.google.com/open?id=1MvhLikyzwbu-Mz_OuXUvytAuqXNEnUjHdSxMGXcKLok",years:"2021"},
17 {src:"Aurora",target:"Blackmore",link:"Acquisition",market:"Semi_Truck | Robotaxi",tags:"AD_Driverless",technology:"LiDAR",aces:"Automated",amount:"",region:"US",date:"2019-01-09",description:"Yesterday announce that they plan to acquire the industry-leading lidar company Blackmore, located in Bozeman, Montana.\r\n\r\nThe Bozeman, Montana–based outfit, which started up a decade ago to do work for the defense industry, uses a “frequency modulated continuous wave” system, also known as a Doppler lidar. When the infrared light hits an object and bounces back, the system determines both how far away it is and its velocity. Knowing where something is headed and how fast is prized data. Blackmore has at least one Doppler lidar competitor in Aeva, founded in early 2017 by a pair of former Apple engineers. [...]",source:"https://drive.google.com/open?id=1UkF-sxgA1AgpgWoRCd2qgWjovLQULoAP",years:"2019"},
18 {src:"Aurora",target:"Uber ATG",link:"Acquisition",market:"Robotaxi | Semi_Truck",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"$4,000",region:"US",date:"2020-12-01",description:"Aurora is acquiring Uber's self-driving unit, ATG, accelerating the first Aurora Driver applications for heavy-duty trucks while allowing us to continue and accelerate our work on light-vehicle products. \"Simply put, Aurora will be the company best positioned to deliver the self-driving products necessary to make transportation and logistics safer, more accessible, and less expensive,\" said Chris Urmson, co-founder and CEO of Aurora.",source:"https://drive.google.com/open?id=1rc-_3VLlITe2bdxBgws3Bvb2rPvCluMfsMkFXiwbg98",years:"2020"},
19 {src:"Aurora",target:"Paccar",link:"Partnership",market:"Semi_Truck",tags:"AD_L3-4",technology:"",aces:"Automated",amount:"",region:"US",date:"2021-01-19",description:"Aurora teams up with PACCAR to build and deploy self-driving trucks",source:"https://drive.google.com/open?id=1TfA9U81CbyNwQc4Xfg2iJ9wqmka7RLqVEIsES2-62Ww",years:"2021"},
20 {src:"Aurora",target:"Denso",link:"Partnership",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-02-09",description:"Aurora enters into long-term, global, and strategic collaboration with Toyota and Denso",source:"https://drive.google.com/open?id=1QnlNnMMxbcPdnbi4AcBo36_UWM9TuMrNqItZHfPDUos",years:"2021"},
21 {src:"Aurora",target:"Toyota",link:"Partnership",market:"Robotaxi",tags:"AD_Driverless",technology:"",aces:"Automated",amount:"",region:"EU| US| China| Korea| Japan| Others",date:"2021-02-09",description:"Aurora enters into long-term, global, and strategic collaboration with Toyota and Denso",source:"https://drive.google.com/open?id=1QnlNnMMxbcPdnbi4AcBo36_UWM9TuMrNqItZHfPDUos",years:"2021"},
22 {src:"Aurora",target:"OURS-Tech",link:"Acquisition",market:"Semi_Truck| Robotaxi",tags:"",technology:"LiDAR",aces:"Automated",amount:"",region:"US",date:"2021-02-26",description:"Aurora acquires OURS lidar (FMCW), unlocking the commercialization of its Aurora Driver",source:"https://drive.google.com/open?id=1TWEII1c0jQk26DcCC2WXw3plT0XTnfDzmD-e551VWSQ",years:"2021"},
23 {src:"Zoox",target:"ZadarLabs",link:"Investment",market:"PoV| Robotaxi",tags:"AD_L3-4| AD_Driverless",technology:"Radar",aces:"Automated",amount:"",region:"US",date:"2021-01-26",description:"Zadar Labs, Developing Next Generation Imaging Radar, Closes $5.6M in Seed Funding",source:"https://drive.google.com/open?id=1fz3MhS4P_Cmq2VmT9crQztUBd9W5Pj-IWEL9ABq3ySg",years:"2021"},
24 {src:"Intel",target:"Mobileye",link:"Acquisition",market:"PoV",tags:"AD_L3-4",technology:"",aces:"Automated",amount:"$15,000",region:"Worldwide",date:"2017-01-14",description:"Instead of Mobileye being integrated into Intel, Intel’s AD Group (ADG) will be integrated into Mobileye.",source:"https://www.engadget.com/2017-08-08-intel-acquisition-Mobileye-complete.html",years:"<2017"},
25 {src:"Intel",target:"Infineon",link:"Acquisition",market:"",tags:"",technology:"",aces:"Automated|Experience",amount:"1400",region:"US|EU",date:"2010-01-01",description:"Intel to Acquire Infineon’s Wireless Solutions Business",source:"https://www.infineon.com/cms/en/about-infineon/press/press-releases/2010/INFXX201008-069.html",years:"<2017"},
26 ]
27
28 const nodes = [
29 {id:"Amazon",type:"Tech",tags:"",technology:"",market:"Droid_Goods|Robotaxi",valuation:"",description:"Amazon is an international e-commerce website for consumers, sellers, and content creators.",country:"US",region:"North America",image:"https://images-eu.ssl-images-amazon.com/images/G/02/gc/designs/livepreview/a_generic_10_uk_noto_email_v2016_uk-main._CB485921599_.png"},
30 {id:"Aurora",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi|Semi_Truck",valuation:"1100",description:"Aurora is delivering the benefits of self-driving technology safely, quickly, and broadly.",country:"US",region:"North America",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/oeagjbu7wau6o16zdhb1"},
31 {id:"Zoox",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi",valuation:"",description:"Zoox is an AI robotics company that provides mobility as-a-service and self-driving car services.",country:"US",region:"North America",image:"https://res-4.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/kpc7mmk886nbbipbeqau"},
32 {id:"Rivian",type:"OEM",tags:"",technology:"",market:"PoV",valuation:"8200",description:"Rivian is an electric vehicle manufacturer that develops products and services to advance the shift to sustainable mobility.",country:"US",region:"North America",image:"https://res-4.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/sdz7aspakybuxp7oojvh"},
33 {id:"Torc",type:"Tier1",tags:"AD_Driverless|AD_L3-4",technology:"",market:"Semi_Truck|Mining",valuation:"",description:"Torc provides L4 end-to-end self-driving software for mobility, trucking, mining, and defense markets through strategic partnerships",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/smfgyxvfot1dwq4vqvo7"},
34 {id:"Intel",type:"Tech",tags:"",technology:"",market:"PoV | Robotaxi",valuation:"",description:"Intel designs, manufactures, and sells integrated digital technology platforms worldwide.",country:"US",region:"North America",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1505768454/wrhwa2ogipbd1o6tgggi.png"},
35 {id:"Blackmore",type:"Tier2",tags:"",technology:"LiDAR",market:"PoV|Other",valuation:"21.5",description:"Blackmore Sensors and Analytics develops frequency-modulated continuous wave lidar imaging and its supporting analytic tools software.",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1497015437/tqor2yimyfapcsn5uyaj.png"},
36 {id:"Uber ATG",type:"Tier1",tags:"AD_Driverless",technology:"",market:"Robotaxi",valuation:"1000",description:"Uber Advanced Technologies Group focuses on autonomous vehicles and the self-driving car business.",country:"US",region:"North America",image:"https://res-5.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/dlzugstswtlgq9wejmfi"},
37 {id:"Paccar",type:"OEM",tags:"",technology:"",market:"Semi_Truck",valuation:"",description:"Global technology leader in the design, manufacture and customer support of high-quality premium trucks.",country:"US",region:"North America",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1404996232/nmvcucjqpgpnhrolbnnk.png"},
38 {id:"Denso",type:"Tier1",tags:"",technology:"",market:"PoV",valuation:"",description:"Supplier of advanced automotive technology",country:"Japan",region:"Japan",image:"https://res-5.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1398234958/fnjwkbbov8sivhs79wta.png"},
39 {id:"Toyota",type:"OEM",tags:"",technology:"",market:"PoV",valuation:"",description:"Toyota is a Japanese automotive company that manufactures and markets vehicles to over 170 countries and regions.",country:"Japan",region:"Japan",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1425366959/cleoo1wmofcfxxspobul.jpg"},
40 {id:"OURS-Tech",type:"Tier2",tags:"",technology:"LiDAR",market:"Semi_Truck| Robotaxi",valuation:"",description:"Enabling mass-production 5D LiDAR for the autonomous future",country:"US",region:"North America",image:"https://static.wixstatic.com/media/c668c3_f1f58317e99d41deac4152d212fcdbc2~mv2.gif"},
41 {id:"ZadarLabs",type:"Tier2",tags:"",technology:"Radar",market:"PoV| Robotaxi",valuation:"",description:"Zadar Labs brings radar intelligence to autonomous systems",country:"US",region:"North America",image:"https://res-1.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/g3kgj9vsfjzlpbichdml"},
42 {id:"Mobileye",type:"Tech",tags:"AS_NCAP|ADAS_uptoL2+|AD_Driverless",technology:"ECU_ADAS",market:"PoV|Robotaxi|Semi_Truck",valuation:"515",description:"Mobileye is a technology company developing vision-based advanced driver assistance systems that help prevent and mitigate collisions.",country:"Israel",region:"Others",image:"https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/bcuhhoflftvvdbpeaarx"},
43 {id:"Infineon",type:"Tier2",tags:"Interior_cocoon",technology:"",market:"PoV",valuation:"",description:"Infineon Technologies offers semiconductor solutions, microcontrollers, LED drivers, sensors and Automotive & Power Management ICs.",country:"Germany",region:"EU",image:"https://res-2.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/v1397183702/79bc5b009247cfd1a274f2a328ff17bf.png"},
44
45 ]
46 const svg = d3.create("svg")
47 .attr("preserveAspectRatio", "xMinYMin meet")
48 .attr("viewBox", [-width/2,-height/2, width,height])
49 .classed("svg-content-responsive", true)
50
51 const defs = svg.append('svg:defs');
52
53
54 defs.append("svg:pattern")
55 .attr("id", "grump_avatar")
56 .attr("width", 1)
57 .attr("height", 1)
58 //.attr("patternUnits", "userSpaceOnUse")
59 .append("svg:image")
60 .attr("xlink:href", 'http://placekitten.com/g/48/48')
61 .attr("width",40)
62 .attr("height",40)
63 .attr("x",0)
64 .attr("y",0)
65
66
67 const link = svg.append("g")
68 .attr("stroke-opacity", 0.6)
69 .attr("stroke-width", 7)
70 .attr("stroke-linecap", "round")
71 .selectAll("line")
72 .data(links)
73 .join("line")
74
75 if (l) link.attr("stroke", ({index: i}) => setLinkColor(l[i])); // set conditional link color
76
77
78 const node = svg.append("g")
79 .attr("stroke", "teal")
80 .attr("stroke-opacity", 1)
81 .attr("stroke-width", 2)
82 .selectAll("circle")
83 .data(nodes)
84 .join("circle")
85 .style("fill", "#fff")
86 .style("fill", "url(#grump_avatar)")
87 .attr("r", 20)
88 .call(drag(simulation))
89
90
91const nodes = [{
92 id: "Amazon",
93 image: "https://images-eu.ssl-images-amazon.com/images/G/02/gc/designs/livepreview/a_generic_10_uk_noto_email_v2016_uk-main._CB485921599_.png"
94 },
95 {
96 id: "Aurora",
97 image: "https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/oeagjbu7wau6o16zdhb1"
98 },
99 {
100 id: "Zoox",
101 image: "https://res-4.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco/kpc7mmk886nbbipbeqau"
102 }
103];
104
105const links = [{
106 src: 'Amazon',
107 target: 'Aurora'
108 },
109 {
110 src: 'Amazon',
111 target: 'Zoox'
112 },
113 {
114 src: 'Aurora',
115 target: 'Zoox'
116 }
117];
118
119const width = 500,
120 height = 500;
121
122function ForceGraph({
123 nodes, // an iterable of node objects (typically [{id}, …])
124 links // an iterable of link objects (typically [{src, target}, …])
125}, {
126 nodeId = d => d.id, // given d in nodes, returns a unique identifier (string)
127 nodeTitle, // given d in nodes, a title string
128 nodeStroke = "teal", // node stroke color
129 nodeStrokeWidth = 2, // node stroke width, in pixels
130 nodeStrokeOpacity = 1, // node stroke opacity
131 nodeRadius = 20, // node radius, in pixels
132 nodeStrength = -750,
133 linkDistance = 100,
134 linkStrokeOpacity = 0.6, // link stroke opacity
135 linkStrokeWidth = 7, // given d in links, returns a stroke width in pixels
136 linkStrokeLinecap = "round", // link stroke linecap
137 linkStrength,
138 container
139} = {}) {
140
141 // Compute values.
142 const N = d3.map(nodes, nodeId);
143
144 // HERE: Don't replace the input nodes using this complex method,
145 // just Object.assign({}, n) to essentially perform a deep copy of a node.
146
147 // Replace the input nodes and links with mutable objects for the simulation.
148 nodes = nodes.map(n => Object.assign({}, n));
149 links = links.map(l => ({
150 source: l.src,
151 target: l.target
152 }));
153
154 const svg = d3.select('body')
155 .append("svg")
156 .attr("preserveAspectRatio", "xMinYMin meet")
157 .attr("viewBox", [-width / 2, -height / 2, width, height])
158 .classed("svg-content-responsive", true)
159
160 const defs = svg.append('svg:defs');
161
162 // HERE: See we add one image per node
163 defs.selectAll("pattern")
164 .data(nodes)
165 .join(
166 enter => {
167 // For every new <pattern>, set the constants and append an <image> tag
168 const patterns = enter
169 .append("pattern")
170 .attr("width", 48)
171 .attr("height", 48);
172 patterns
173 .append("image")
174 .attr("width", 48)
175 .attr("height", 48)
176 .attr("x", 0)
177 .attr("y", 0);
178 return patterns;
179 }
180 )
181 // For every <pattern>, set it to point to the correct
182 // URL and have the correct (company) ID
183 .attr("id", d => d.id)
184 .select("image")
185 .datum(d => {
186 debugger;
187 return d;
188 })
189 .attr("xlink:href", d => {
190 debugger;
191 return d.image;
192 })
193
194 const link = svg.append("g")
195 .attr("stroke-opacity", linkStrokeOpacity)
196 .attr("stroke-width", linkStrokeWidth)
197 .attr("stroke-linecap", linkStrokeLinecap)
198 .selectAll("line")
199 .data(links)
200 .join("line");
201
202 // Construct the forces.
203 const forceNode = d3.forceManyBody();
204 const forceLink = d3.forceLink(links).id(({
205 index: i
206 }) => N[i]);
207 if (nodeStrength !== undefined) forceNode.strength(nodeStrength);
208 if (linkStrength !== undefined) forceLink.strength(linkStrength);
209 forceLink.distance(linkDistance)
210 const simulation = d3.forceSimulation(nodes)
211 .force(link, forceLink)
212 .force("charge", forceNode)
213 .force("x", d3.forceX())
214 .force("y", d3.forceY())
215 .on("tick", ticked);
216
217 const node = svg.append("g")
218 .attr("stroke", nodeStroke)
219 .attr("stroke-opacity", nodeStrokeOpacity)
220 .attr("stroke-width", nodeStrokeWidth)
221 .selectAll("circle")
222 .data(nodes)
223 .join("circle")
224 .style("fill", "#fff")
225 .style("fill", d => `url(#${d.id})`)
226 .attr("r", nodeRadius);
227
228 function ticked() {
229 link
230 .attr("x1", d => d.source.x)
231 .attr("y1", d => d.source.y)
232 .attr("x2", d => d.target.x)
233 .attr("y2", d => d.target.y);
234 node
235 .attr("cx", d => d.x)
236 .attr("cy", d => d.y);
237 }
238} // ForceGraph
239
240ForceGraph({
241 nodes,
242 links
243});line {
244 stroke: red;
245}<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.js"></script>
QUESTION
Select values that have a minus difference between two timestamps and show their complete history in the table
Asked 2021-Nov-18 at 13:191CREATE TABLE logistics (
2 id SERIAL PRIMARY KEY,
3 time_stamp DATE,
4 product VARCHAR(255),
5 quantity INT
6);
7
8INSERT INTO logistics
9(time_stamp, product, quantity)
10VALUES
11('2020-01-14', 'Product_A', '100'),
12('2020-01-14', 'Product_B', '300'),
13
14('2020-01-15', 'Product_B', '400'),
15('2020-01-15', 'Product_C', '350'),
16
17('2020-01-16', 'Product_B', '530'),
18('2020-01-16', 'Product_C', '250'),
19('2020-01-16', 'Product_D', '670'),
20
21('2020-01-17', 'Product_C', '380'),
22('2020-01-17', 'Product_D', '980'),
23('2020-01-17', 'Product_E', '700'),
24('2020-01-17', 'Product_F', '450');
25
Expected Result
1CREATE TABLE logistics (
2 id SERIAL PRIMARY KEY,
3 time_stamp DATE,
4 product VARCHAR(255),
5 quantity INT
6);
7
8INSERT INTO logistics
9(time_stamp, product, quantity)
10VALUES
11('2020-01-14', 'Product_A', '100'),
12('2020-01-14', 'Product_B', '300'),
13
14('2020-01-15', 'Product_B', '400'),
15('2020-01-15', 'Product_C', '350'),
16
17('2020-01-16', 'Product_B', '530'),
18('2020-01-16', 'Product_C', '250'),
19('2020-01-16', 'Product_D', '670'),
20
21('2020-01-17', 'Product_C', '380'),
22('2020-01-17', 'Product_D', '980'),
23('2020-01-17', 'Product_E', '700'),
24('2020-01-17', 'Product_F', '450');
25time_stamp | product | difference |
26------------|-----------------|-----------------|---------
272020-01-15 | Product_C | 350 |
282020-01-16 | Product_C | -100 |
292020-01-17 | Product_C | 130 |
30
I want to do the following two things:
- Extract the products from the table which have decreased their quantity from timestamp to timestamp
- Display the history of those products over all timestamps.
With the below query I am able to do Step 1 but I am wondering how I need to modify it to also include the history of the selected products.
1CREATE TABLE logistics (
2 id SERIAL PRIMARY KEY,
3 time_stamp DATE,
4 product VARCHAR(255),
5 quantity INT
6);
7
8INSERT INTO logistics
9(time_stamp, product, quantity)
10VALUES
11('2020-01-14', 'Product_A', '100'),
12('2020-01-14', 'Product_B', '300'),
13
14('2020-01-15', 'Product_B', '400'),
15('2020-01-15', 'Product_C', '350'),
16
17('2020-01-16', 'Product_B', '530'),
18('2020-01-16', 'Product_C', '250'),
19('2020-01-16', 'Product_D', '670'),
20
21('2020-01-17', 'Product_C', '380'),
22('2020-01-17', 'Product_D', '980'),
23('2020-01-17', 'Product_E', '700'),
24('2020-01-17', 'Product_F', '450');
25time_stamp | product | difference |
26------------|-----------------|-----------------|---------
272020-01-15 | Product_C | 350 |
282020-01-16 | Product_C | -100 |
292020-01-17 | Product_C | 130 |
30SELECT
31t1.time_stamp AS time_stamp,
32t1.product AS product,
33SUM(t1.difference) AS difference
34FROM
35
36 (SELECT
37 l.time_stamp AS time_stamp,
38 l.product AS product,
39 Coalesce(l.quantity-LAG(l.quantity) OVER (Partition by l.product ORDER BY l.product, l.time_stamp), l.quantity) AS difference
40 FROM logistics l
41 ORDER BY 1,2) t1
42
43WHERE t1.difference < 0
44GROUP BY 1,2
45ORDER BY 1,2;
46
Do you have any idea?
ANSWER
Answered 2021-Nov-17 at 14:10Use EXISTS
:
1CREATE TABLE logistics (
2 id SERIAL PRIMARY KEY,
3 time_stamp DATE,
4 product VARCHAR(255),
5 quantity INT
6);
7
8INSERT INTO logistics
9(time_stamp, product, quantity)
10VALUES
11('2020-01-14', 'Product_A', '100'),
12('2020-01-14', 'Product_B', '300'),
13
14('2020-01-15', 'Product_B', '400'),
15('2020-01-15', 'Product_C', '350'),
16
17('2020-01-16', 'Product_B', '530'),
18('2020-01-16', 'Product_C', '250'),
19('2020-01-16', 'Product_D', '670'),
20
21('2020-01-17', 'Product_C', '380'),
22('2020-01-17', 'Product_D', '980'),
23('2020-01-17', 'Product_E', '700'),
24('2020-01-17', 'Product_F', '450');
25time_stamp | product | difference |
26------------|-----------------|-----------------|---------
272020-01-15 | Product_C | 350 |
282020-01-16 | Product_C | -100 |
292020-01-17 | Product_C | 130 |
30SELECT
31t1.time_stamp AS time_stamp,
32t1.product AS product,
33SUM(t1.difference) AS difference
34FROM
35
36 (SELECT
37 l.time_stamp AS time_stamp,
38 l.product AS product,
39 Coalesce(l.quantity-LAG(l.quantity) OVER (Partition by l.product ORDER BY l.product, l.time_stamp), l.quantity) AS difference
40 FROM logistics l
41 ORDER BY 1,2) t1
42
43WHERE t1.difference < 0
44GROUP BY 1,2
45ORDER BY 1,2;
46WITH cte AS (
47 SELECT time_stamp, product,
48 quantity - LAG(quantity, 1, 0) OVER (PARTITION BY product ORDER BY time_stamp) difference
49 FROM logistics
50)
51SELECT c1.*
52FROM cte c1
53WHERE EXISTS (
54 SELECT 1
55 FROM cte c2
56 WHERE c2.product = c1.product AND c2.difference < 0
57)
58ORDER BY c1.product, c1.time_stamp;
59
See the demo.
QUESTION
SpringBoot profiles with Gradle vs cloud
Asked 2021-Nov-17 at 20:17I have some problem with starting microservice with cloud config on local machine: In application.yml:
1spring:
2 application:
3 name: my_servie
4 config:
5 import: 'configserver:'
6 profiles:
7 group:
8 env-prod-pg: postgres,log
9
I create application-local.yml, where add:
1spring:
2 application:
3 name: my_servie
4 config:
5 import: 'configserver:'
6 profiles:
7 group:
8 env-prod-pg: postgres,log
9spring:
10 application:
11 name: mc-service-logistics-v2
12 config:
13 import: 'optional:configserver:'
14
and some other config updates, in build.gradle I add:
1spring:
2 application:
3 name: my_servie
4 config:
5 import: 'configserver:'
6 profiles:
7 group:
8 env-prod-pg: postgres,log
9spring:
10 application:
11 name: mc-service-logistics-v2
12 config:
13 import: 'optional:configserver:'
14tasks.register("bootRunLocal") {
15 group = "application"
16 description = "Runs the Spring Boot application with the local profile"
17 doFirst {
18 tasks.bootRun.configure {
19 systemProperty("spring.profiles.active", "local")
20 }
21 }
22 finalizedBy("bootRun")
23}
24
but when I try to start app with gradle bootRunLocal I caught error: Caused by: org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:8888/my-service/local": Connection refused; nested exception is java.net.ConnectException: Connection refused
If I understand- application still want to use cloud config and can't start. If I comment spring.config.import in application.yml- aplication started without any problem.
How to solve this problem? I don't want to push to repo my local config again)
ANSWER
Answered 2021-Nov-17 at 20:17Well, I create to application-.yml and application.yml ,where store current profile:
1spring:
2 application:
3 name: my_servie
4 config:
5 import: 'configserver:'
6 profiles:
7 group:
8 env-prod-pg: postgres,log
9spring:
10 application:
11 name: mc-service-logistics-v2
12 config:
13 import: 'optional:configserver:'
14tasks.register("bootRunLocal") {
15 group = "application"
16 description = "Runs the Spring Boot application with the local profile"
17 doFirst {
18 tasks.bootRun.configure {
19 systemProperty("spring.profiles.active", "local")
20 }
21 }
22 finalizedBy("bootRun")
23}
24spring:
25 profiles:
26 active: prod
27
Community Discussions contain sources that include Stack Exchange Network
Tutorials and Learning Resources in Logistics
Tutorials and Learning Resources are not available at this moment for Logistics