Showing posts with label docker. Show all posts
Showing posts with label docker. Show all posts

Wednesday, May 12, 2021

How to install docker client and connect to docker desktop engine on another machine macOS or Windows.

Use Docker Desktop for Windows 10 / macOS as engine and docker client for linux/macos/Android to connect.
Why use docker client ? Because don't want to / cannot install docker engine in the client environment and just want to connect to the docker engine on local LAN.
(1) For Windows 10 Host, after installation of docker desktop
# C:\ProgramData\Docker\config\daemon.json and add
"hosts" : ["tcp://0.0.0.0:2375"],
# change port forwarding to docker wsl backend, run this in powershell admin mode
netsh interface portproxy add v4tov4 listenport=2375 listenaddress=192.168.64.1 connectaddress=127.0.0.1 connectport=2375
# change Windows defender firewall and add incoming rule to enable port 2375 # Refer to this for setting openssh server authorized_keys, with proper file permission https://superuser.com/questions/1445976/windows-ssh-server-refuses-key-based-authentication-from-client

(2) For macOS Host, after installation of docker desktop
# ssh-keygen in client and ssh-copy-id to host, e.g. remote host username with ip address of 192.168.64.1
ssh-keygen -t rsa
ssh-copy-id username@192.168.64.1
# edit sshd_config
sudo vi /private/etc/ssh/sshd_config
# and add
PermitUserEnvironment PATH,LANG
# edit ~/.docker/daemon.json and add
"hosts" : ["tcp://0.0.0.0:2375"],
# add .ssh/environment
PATH=$PATH:/usr/local/bin
# restarting sshd using macOS System Preferences -> Sharing -> File Sharing

(3) To install docker client for Linux using tcp
cd ~/
wget https://download.docker.com/linux/static/stable/x86_64/docker-20.10.6.tgz
tar -xzvf docker-20.10.6.tgz
cd docker
./docker -H tcp://<remote host ip address>:2375 images


(3.1) To install docker client for Termux app of Android and using tcp
wget https://download.docker.com/linux/static/stable/aarch64/docker-20.10.6.tgz

tar xzvf docker-20.10.6.tgz
mv docker/docker /data/data/com.termux/files/usr/bin/
./docker -H tcp://<remote host ip address>:2375 images


(4) To install docker client for macOS using ssh
cd ~/
wget https://download.docker.com/mac/static/stable/x86_64/docker-20.10.6.tgz
#or curl -OL https://download.docker.com/mac/static/stable/x86_64/docker-20.10.6.tgz
#or curl -OL https://download.docker.com/mac/static/stable/aarch64/docker-20.10.6.tgz
tar xzvf docker-20.10.6.tgz
xattr -rc docker
cd docker
sudo mkdir -p /usr/local/bin
sudo mv * /usr/local/bin/
docker -H ssh://username@<remote host ip address> images


(5) Or simply add the corresponding variables to ~/.bashrc
unset DOCKER_HOST
# for tcp connection to Windows 10 host
export DOCKER_HOST=tcp://192.168.64.1:2375

# for ssh connection to macOS host using SSH
export DOCKER_HOST=ssh://user@192.168.64.1


Sunday, February 28, 2021

How to cross compile using Docker Desktop experimental feature buildx

Another demo to show the building of packages using experiemtal feature of Docker desktop. Have to enable the experimental feature to cross compile in other architetcures different from the host machine. E.g. cross compile armv7 packages in amd64 or arm64 host of Mac or PC.
Shell script   Select all
cd $HOME mkdir -p my-quantlib cd my-quantlib # get helloworld.ipynb wget https://raw.githubusercontent.com/lballabio/dockerfiles/master/quantlib-jupyter/Hello%20world.ipynb cat >$HOME/my-quantlib/Dockerfile_ql_armv7_1.21 <<'HEREEOF' # Dockerfile_ql_armv7_1.21 # docker buildx build --platform linux/arm/v7 -f Dockerfile_ql_armv7_1.21 -t armv7/quantlib:1.21 . # Build Quantlib libraries for armv7 in arm64/amd64 host ARG tag=latest FROM arm32v7/ubuntu:18.04 LABEL Description="Provide a building environment where the QuantLib Python jupyter-notebook" RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential wget libbz2-dev vim git ENV boost_version=1.67.0 ENV boost_dir=boost_1_67_0 # Build boost RUN echo 'Building boost ...' RUN wget --no-check-certificate https://boostorg.jfrog.i o/artifactory/main/release/${boost_version}/source/${boo st_dir}.tar.gz \ && tar xfz ${boost_dir}.tar.gz \ && rm ${boost_dir}.tar.gz \ && cd ${boost_dir} \ && ./bootstrap.sh \ && ./b2 --without-python --prefix=/usr -j 4 link=shared runtime-link=shared install \ && ./b2 --prefix=/Staging/usr install \ && cd .. && rm -rf ${boost_dir} && ldconfig # Build Quantlib C++ RUN echo 'Building Quantlib C++ ...' ENV quantlib_version=1.21 RUN wget https://github.com/lballabio/QuantLib/releases/download/QuantLib-v${quantlib_version}/QuantLib-${quantlib_version}.tar.gz \ && tar xfz QuantLib-${quantlib_version}.tar.gz \ && rm QuantLib-${quantlib_version}.tar.gz \ && cd QuantLib-${quantlib_version} \ && ./configure --prefix=/usr --disable-static CXXFLAGS=-O3 \ && make -j 4 && make install \ && make DESTDIR=/Staging install \ && make clean \ && cd .. && ldconfig # && cd .. && rm -rf QuantLib-${quantlib_version} && ldconfig # Build Quantlib-Python RUN echo 'Build Quantlib-Python ...' RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y swig python3 python3-pip python-dev libgomp1 # Build Quantlib for Python3 RUN echo 'Install Quantlib Python' ENV quantlib_swig_version=1.21 RUN wget https://github.com/lballabio/QuantLib-SWIG/releases/download/QuantLib-SWIG-v${quantlib_swig_version}/QuantLib-SWIG-${quantlib_swig_version}.tar.gz \ && tar xfz QuantLib-SWIG-${quantlib_swig_version}.tar.gz \ && rm QuantLib-SWIG-${quantlib_swig_version}.tar.gz \ && cd QuantLib-SWIG-${quantlib_swig_version} \ && ./configure CXXFLAGS="--param ggc-min-expand=1 --param ggc-min-heapsize=32768" PYTHON=/usr/bin/python3 \ && make -C Python && make -C Python check && make -C Python install \ && cd .. && rm -rf QuantLib-SWIG-${quantlib_swig_version} && ldconfig # Build jupyter-notebook server RUN python3 -c "print('\033[91m Building jupyter-notebook server ... \033[0m')" RUN pip3 install --no-cache-dir jupyter jupyterlab matplotlib numpy scipy pandas ipywidgets RISE RUN jupyter-nbextension install rise --py --sys-prefix RUN jupyter-nbextension install widgetsnbextension --py --sys-prefix \ && jupyter-nbextension enable widgetsnbextension --py --sys-prefix # Build Quantlib for Python2 RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y python \ && apt-get clean RUN wget https://bootstrap.pypa.io/2.7/get-pip.py \ && python2 get-pip.py \ && rm get-pip.py RUN wget https://dl.bintray.com/quantlib/releases/QuantLib-SWIG-${quantlib_swig_version}.tar.gz \ && tar xfz QuantLib-SWIG-${quantlib_swig_version}.tar.gz \ && rm QuantLib-SWIG-${quantlib_swig_version}.tar.gz \ && cd QuantLib-SWIG-${quantlib_swig_version} \ && ./configure CXXFLAGS="--param ggc-min-expand=1 --param ggc-min-heapsize=32768" \ && make -C Python && make -C Python check && make -C Python install \ && cd .. && rm -rf QuantLib-SWIG-${quantlib_swig_version} && ldconfig RUN pip2 install --no-cache-dir numpy EXPOSE 8888 RUN mkdir /notebooks VOLUME /notebooks COPY *.ipynb /notebooks/ # Starting jupyter-notebook server RUN python3 -c "print('\033[92m Starting jupyter-notebook server at port 8888 \033[0m')" CMD jupyter notebook --no-browser --allow-root --ip=0.0.0.0 --port=8888 --notebook-dir=/notebooks HEREEOF # build and load image (after experimental feature of Docker Desktop is enabled docker buildx build --platform linux/arm/v7 --memory="8g" --output "type=docker,push=false,dest=armv7_ql.tar" -f Dockerfile_ql_armv7_1.21 -t armv7/quantlib:1.21 . docker load < armv7_ql.tar # run image docker run --platform linux/arm/v7 -d -p 8888:8888 --name myquantlibarmv7testing armv7/quantlib:1.21 # list the token of the jupyter-notebook server docker container exec -it myquantlibarmv7testing jupyter notebook list


If using WSL2 docker CLI in Linux, should enable the experimental feature first.
export DOCKER_CLI_EXPERIMENTAL=enabled
docker buildx create --name mybuilder
docker buildx use mybuilder
docker buildx inspect --bootstrap
docker buildx build --platform linux/arm/v7 --memory="8g" --output "type=docker,push=false,dest=armv7_ql.tar" -f Dockerfile_ql_armv7_1.21 -t armv7/quantlib:1.21 .


Thursday, February 25, 2021

How to cross compile QuantLib in docker

This example demo using dockcross to build Quantlib armv7 library packages and cross compile in host X86_64 machine
Shell script   Select all
cd $HOME mkdir -p dockcross cd dockcross cat >$HOME/dockcross/dockcross_ql_1.21 <<'HEREEOF' # dockcross_ql_1.21 # docker build -f dockcross_ql_1.21 -t dockcross/linux-armv7/quantlib:1.21 . # Build Quantlib libraries for armv7 ARG tag=latest FROM dockcross/linux-armv7 ENV DEFAULT_DOCKCROSS_IMAGE dockcross/linux-armv7/quantlib:1.21 ENV CROSS_PREFIX /usr/xcc/armv7-unknown-linux-gnueabi/armv7-unknown-linux-gnueabi/sysroot/usr LABEL Description="Provide a building environment dockcross/linux/armv7 for the QuantLib" RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential wget vim git ENV boost_version=1.67.0 ENV boost_dir=boost_1_67_0 # Install boost dependencies RUN echo 'Building boost and required packages ...' RUN dpkg --add-architecture armhf \ && apt-get update \ && apt-get download libbz2-1.0:armhf libbz2-dev:armhf liblzma-dev:armhf \ && dpkg-deb -x libbz2-1*armhf.deb ./x \ && dpkg-deb -x libbz2-dev_*armhf.deb ./x \ && dpkg-deb -x liblzma-dev_*armhf.deb ./x \ && mv ./x/usr/lib/arm-linux-gnueabihf/* ${CROSS_PREFIX}/lib/ \ && mv ./x/usr/bin/* ${CROSS_PREFIX}/bin/ \ && mv ./x/usr/include/* ${CROSS_PREFIX}/include/ \ && mv ./x/usr/share/* ${CROSS_PREFIX}/share/ \ && mv ./x/lib/arm-linux-gnueabihf/* ${CROSS_PREFIX}/lib/ \ && rm -fr ./x *.deb && ldconfig RUN wget https://sourceforge.net/projects/libpng/files/zlib/1.2.11/zlib-1.2.11.tar.gz/download -O zlib-1.2.11.tar.gz \ && tar xfz zlib-1.2.11.tar.gz \ && rm zlib-1.2.11.tar.gz \ && cd zlib-1.2.11 \ && ./configure --prefix=${CROSS_PREFIX} && make && make install \ && cd .. && rm -rf zlib-1.2.11 && ldconfig # Build boost RUN wget https://dl.bintray.com/boostorg/release/${boost_version}/source/${boost_dir}.tar.gz \ && tar xfz ${boost_dir}.tar.gz \ && rm ${boost_dir}.tar.gz \ && cd ${boost_dir} \ && ./bootstrap.sh --with-toolset=gcc --prefix=${CROSS_PREFIX} \ && touch user-config.jam \ && echo "using gcc : armv7 : ${CXX} ;" > user-config.jam \ && echo "using mpi ;" >> user-config.jam \ && ./b2 --toolset=gcc-armv7 --address-model=32 --architecture=arm --user-config=./user-config.jam --without-python --prefix=${CROSS_PREFIX} -j 4 link=shared runtime-link=shared install \ && cd .. && rm -rf ${boost_dir} && ldconfig # Build Quantlib C++ RUN echo 'Building Quantlib C++ ...' ENV quantlib_version=1.21 RUN wget https://dl.bintray.com/quantlib/releases/QuantLib-${quantlib_version}.tar.gz \ && tar xfz QuantLib-${quantlib_version}.tar.gz \ && rm QuantLib-${quantlib_version}.tar.gz \ && cd QuantLib-${quantlib_version} \ && ./configure --host=x86_64-linux-gnu --target=armv7-unknown-linux-gnueabi --with-boost-include=${CROSS_PREFIX}/include/boost --with-boost-lib=${CROSS_PREFIX}/lib --prefix=${CROSS_PREFIX} --disable-static CXXFLAGS=-O3 \ && make -j 4 && make install \ && make clean \ && cd .. && ldconfig HEREEOF # build image docker build -f dockcross_ql_1.21 -t dockcross/linux-armv7/quantlib:1.21 . # Test dockcross compile docker run --rm dockcross/linux-armv7/quantlib:1.21 > dockcross-quantlib-armv7 chmod +x dockcross-quantlib-armv7 ./dockcross-quantlib-armv7 bash -c '$CXX -v' # Copy example cpp file from image docker run -v $PWD:/opt/mount --rm --entrypoint cp dockcross/linux-armv7/quantlib:1.21 /work/QuantLib-1.21/Examples/Bonds/Bonds.cpp /opt/mount/Bonds.cpp # Use this command to copy whole directory recursively # docker run -v $PWD:/opt/mount --rm --entrypoint cp dockcross/linux-armv7/quantlib:1.21 -r /work/QuantLib-1.21/Examples /opt/mount/QLExamples # Compile and check binary ./dockcross-quantlib-armv7 bash -c '$CXX Bonds.cpp -lQuantLib -o Bonds -static' file Bonds


# install qemu and run in host
sudo apt update
sudo apt install -y qemu-user
qemu-arm Bonds

# Or test run it in armv7 machine e.g. RaspberryPi 3B+
scp Bonds mypi3b:~/.
ssh mypi3b '~/Bonds'

Sunday, February 14, 2021

How to install Windows Subsystem for Linux 2 and docker on Windows 10

Required Windows 10 update 1903 or 1909 or above
(1) Use Windows Power Shell (run as Administrator) to install WSL2
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
# for Windows update 2004 or later
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
# for Windows update 1903 or 1909
Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform -NoRestart
# Restart Windows after enable Enable-WindowsOptionalFeature curl -o $env:userprofile\Desktop\wsl_update_x64.msi https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi
msiexec.exe /I $env:userprofile\Desktop\wsl_update_x64.msi /quiet
wsl --set-default-version 2


(2) Install Ubuntu 20.04 from Windows Store

(3) Install docker (Reference : https://docs.docker.com/engine/install/ubuntu/)
sudo apt update
sudo apt install -y apt-transport-https ca-certificates curl gnupg-agent software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io
sudo usermod -aG docker $USER

# Test docker
sudo /etc/init.d/docker start
docker run -e MYSQL_ROOT_PASSWORD=rootpassword -e MYSQL_USER=wpuser -e MYSQL_PASSWORD=wpuserpassword -e MYSQL_DATABASE=wordpressdb --name wordpressdb -d mariadb ; sudo docker run -e WORDPRESS_DB_USER=wpuser -e WORDPRESS_DB_PASSWORD=wpuserpassword -e WORDPRESS_DB_NAME=wordpressdb -p 8080:80 --link wordpressdb:mysql --name wordpress -d wordpress
# browser test enter address http://127.0.0.1:8080/


Test (4) Install docker-compose
sudo apt install python3.8 python3-pip
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10
sudo update-alternatives --install /usr/bin/pip pip /usr/bin/pip3 10
sudo pip3 -v install docker-compose


(5) For example, the creation Dockerfile to build for Quantlib juypter notebook server is as below.
P.S. You need 8G RAM to build thia dockerfile using gcc

Shell script   Select all
cd $HOME mkdir -p my-quantlib cd my-quantlib # get helloworld.ipynb wget https://raw.githubusercontent.com/lballabio/dockerfiles/master/quantlib-jupyter/Hello%20world.ipynb cat >$HOME/my-quantlib/Dockerfile_ql_1.21 <<'HEREEOF' # Dockerfile_ql_1.21 # docker build -f Dockerfile_ql_1.21 -t quantlib:1.21 . # Build Quantlib libraries for amd64 ARG tag=latest FROM ubuntu:20.04 MAINTAINER Luigi Ballabio LABEL Description="Provide a building environment where the QuantLib Python jupyter-notebook" RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential wget libbz2-dev vim git ENV boost_version=1.67.0 ENV boost_dir=boost_1_67_0 # Build boost RUN echo 'Building boost ...' RUN wget https://dl.bintray.com/boostorg/release/${boost_version}/source/${boost_dir}.tar.gz \ && tar xfz ${boost_dir}.tar.gz \ && rm ${boost_dir}.tar.gz \ && cd ${boost_dir} \ && ./bootstrap.sh \ && ./b2 --without-python --prefix=/usr -j 4 link=shared runtime-link=shared install \ && cd .. && rm -rf ${boost_dir} && ldconfig # Build Quantlib C++ RUN echo 'Building Quantlib C++ ...' ENV quantlib_version=1.21 RUN wget https://dl.bintray.com/quantlib/releases/QuantLib-${quantlib_version}.tar.gz \ && tar xfz QuantLib-${quantlib_version}.tar.gz \ && rm QuantLib-${quantlib_version}.tar.gz \ && cd QuantLib-${quantlib_version} \ && ./configure --prefix=/usr --disable-static CXXFLAGS=-O3 \ && make -j 4 && make check && make install \ && make clean \ && cd .. && ldconfig # && cd .. && rm -rf QuantLib-${quantlib_version} && ldconfig # Build Quantlib-Python RUN echo 'Build Quantlib-Python ...' RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y swig python3 python3-pip python-dev libgomp1 # Build Quantlib for Python3 RUN echo 'Install Quantlib Python' ENV quantlib_swig_version=1.21 RUN wget https://dl.bintray.com/quantlib/releases/QuantLib-SWIG-${quantlib_swig_version}.tar.gz \ && tar xfz QuantLib-SWIG-${quantlib_swig_version}.tar.gz \ && rm QuantLib-SWIG-${quantlib_swig_version}.tar.gz \ && cd QuantLib-SWIG-${quantlib_swig_version} \ && ./configure CXXFLAGS="--param ggc-min-expand=1 --param ggc-min-heapsize=32768" PYTHON=/usr/bin/python3 \ && make -C Python && make -C Python check && make -C Python install \ && cd .. && rm -rf QuantLib-SWIG-${quantlib_swig_version} && ldconfig # Build jupyter-notebook server RUN python3 -c "print('\033[91m Building jupyter-notebook server ... \033[0m')" RUN pip3 install --no-cache-dir jupyter jupyterlab matplotlib numpy scipy pandas ipywidgets RISE RUN jupyter-nbextension install rise --py --sys-prefix RUN jupyter-nbextension install widgetsnbextension --py --sys-prefix \ && jupyter-nbextension enable widgetsnbextension --py --sys-prefix # Build Quantlib for Python2 RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y python2 \ && apt-get clean RUN wget https://bootstrap.pypa.io/2.7/get-pip.py \ && python2 get-pip.py \ && rm get-pip.py RUN wget https://dl.bintray.com/quantlib/releases/QuantLib-SWIG-${quantlib_swig_version}.tar.gz \ && tar xfz QuantLib-SWIG-${quantlib_swig_version}.tar.gz \ && rm QuantLib-SWIG-${quantlib_swig_version}.tar.gz \ && cd QuantLib-SWIG-${quantlib_swig_version} \ && ./configure CXXFLAGS="--param ggc-min-expand=1 --param ggc-min-heapsize=32768" \ && make -C Python && make -C Python check && make -C Python install \ && cd .. && rm -rf QuantLib-SWIG-${quantlib_swig_version} && ldconfig RUN pip2 install --no-cache-dir numpy EXPOSE 8888 RUN mkdir /notebooks VOLUME /notebooks COPY *.ipynb /notebooks/ # Starting jupyter-notebook server RUN python3 -c "print('\033[92m Starting jupyter-notebook server at port 8888 \033[0m')" CMD jupyter notebook --no-browser --allow-root --ip=0.0.0.0 --port=8888 --notebook-dir=/notebooks HEREEOF # build image docker build -f Dockerfile_ql_1.21 -t quantlib:1.21 . # run image docker run -d -p 8888:8888 --name myquantlibtesting quantlib:1.21 # list the token of the jupyter-notebook server docker container exec -it myquantlibtesting jupyter notebook list


(6) Install youtube-dl for WSL2
wget https://github.com/ytdl-org/youtube-dl/releases/download/2021.12.17/youtube-dl
sudo chmod +x youtube-dl sudo mv youtube-dl /usr/local/bin/ sudo apt install -y openssl ffmpeg
sudo apt install python-is-python3
youtube-dl -U
youtube-dl -i -f m4a https://youtu.be/e0npW4WoGmc
# use ffmpeg to resize videp https://ottverse.com/change-resolution-resize-scale-video-using-ffmpeg/ # use ffmpeg to resize image https://stackoverflow.com/questions/28806816/use-ffmpeg-to-resize-image


(7) Install X Display Server for WSL gui app
https://techcommunity.microsoft.com/t5/windows-dev-appconsult/running-wsl-gui-apps-on-windows-10/ba-p/1493242

Run wsl app batch file
https://gist.githubusercontent.com/zarinfam/eb671a82340eadb5af9026ba6e0b666b/raw/c2d0d947a488e54eeb7fdaafae5464afc778de71/wsl-app-runner.bat

vbscript to start the batch file
https://gist.github.com/zarinfam/5dbc0e10662b79468a3da9a67c107217/raw/cf4d2d3b6095cb3c42fca0df9e86e4d3b2703671/linux-gui-app-runner.vbs



To install OpenSSH Server on Windows 10 https://virtualizationreview.com/articles/2020/05/21/ssh-server-on-windows-10.aspx

To enable ssh login default to wsl ubuntu. Should use powershell with admin authority yo rmable features. https://www.hanselman.com/blog/the-easy-way-how-to-ssh-into-bash-and-wsl2-on-windows-10-from-an-external-machine

In order not to interrupt the ssh server service, should consider to disable sleep when on power adapter. And disable automatic windows update and restart.



Wednesday, April 8, 2020

Swift 5.2 on Ubuntu for Windows 10 bash shell

Prerequisite:
Windows 10 64 bits Home or Pro Edition
Enable WSL via powershell as Administrator
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform


Install Ubuntu App from Microsoft Store

Swift 5.2 on Ubuntu (18.04 LTS) for Windows 10 bash shell

You need to download and extract the Release (Ubuntu 18.04) from swift.org and do these under bash shell of Ubuntu App.
shell script    Select all
# Show Ubuntu Version lsb_release -a # download and extract swift 5.2 Release cd ~/ wget https://swift.org/builds/swift-5.2-release/ubuntu1804/swift-5.2-RELEASE/swift-5.2-RELEASE-ubuntu18.04.tar.gz tar xzvf swift-5.2-RELEASE-ubuntu18.04.tar.gz sudo mv ~/swift-5.2-RELEASE-ubuntu18.04 /usr/share/swift-5.2 # install packages and development tools sudo apt-get update sudo apt-get install -y clang sudo apt-get install -y libcurl3 libpython2.7 libpython2.7-dev sudo apt-get install -y libcurl4-openssl-dev sudo apt-get install -y git build-essential # add path in ~/.bashrc echo "export PATH=/usr/share/swift-5.2/usr/bin:\$PATH" >> ~/.bashrc # disable color in ~/.bashrc echo 'export TERM=xterm-mono' >> ~/.bashrc #reload ~/.bashrc source ~/.bashrc Check the Swift version swift --version # test Foundation, libdispatch and swiftc compile cd $HOME cat > hello.swift <<EOF import Foundation let device = "WIN10" print("Hello from Swift on \(device)") print("\(NSTimeZone.default.abbreviation()!) \(NSDate())") // Test libdispatch import Dispatch var my_dispatch_group = DispatchGroup() let concurrentQueue = DispatchQueue(label: "myqueuename", attributes: DispatchQueue.Attributes.concurrent) for a in 1...20 { my_dispatch_group.enter() let block = DispatchWorkItem { print("do something at \(a)") } my_dispatch_group.leave() my_dispatch_group.notify(queue: concurrentQueue, work:block) } let item = DispatchWorkItem { print("PROGRAM ENDED \(NSTimeZone.default.abbreviation()!) \(NSDate())") } my_dispatch_group.notify(queue: DispatchQueue.global(qos:.userInitiated), work:item) print("press enter to exit") let _ = readLine(strippingNewline: true) EOF swiftc hello.swift ./hello # test Swift Package Manager mkdir -p $HOME/test1 cd $HOME/test1 swift package init swift test


Follow this guide to install docker on Ubuntu 16.0.4 LTS. Currently 18.0.4 is not working for docker CE on WSL.
https://medium.com/faun/docker-running-seamlessly-in-windows-subsystem-linux-6ef8412377aa


To get Swift 5.2 on Ubuntu 16.0.4
wget https://swift.org/builds/swift-5.2-release/ubuntu1604/swift-5.2-RELEASE/swift-5.2-RELEASE-ubuntu16.04.tar.gz
tar xzvf swift-5.2-RELEASE-ubuntu16.04.tar.gz
sudo mv ~/swift-5.2-RELEASE-ubuntu16.04 /usr/share/swift-5.2




For docker on WSL, you might encounter error on apt-get update with Error in GPG signature. The temporary solution is to change storage driver to vfs as the default overlay2 driver does not work under wsl. But the performance of vfs is really poor.
shell script    Select all
# create the following file in /etc/docker/daemon.json and restart the machine and docker daemon echo '{"storage-driver": "vfs"}' | sudo tee /etc/docker/daemon.json


Click on the docker label below to see some previous examples on using docker.



For example using the quantlib-python3 docker image
docker run -t -i lballabio/quantlib-python3:latest bash

To test the quantlib-python3 docker image
shell script    Select all
# Display unbuntu version apt-get update apt install lsb-release lsb_release -a # Test python 3 QuantLib apt-get install python3 python3-pip -y pip3 install numpy QuantLib-Python==1.18 pip3 freeze cd $HOME cat > $HOME/swap.py <<EOF from __future__ import print_function import numpy as np import QuantLib as ql print("QuantLib version is", ql.__version__) # Set Evaluation Date today = ql.Date(31,3,2015) ql.Settings.instance().setEvaluationDate(today) # Setup the yield termstructure rate = ql.SimpleQuote(0.03) rate_handle = ql.QuoteHandle(rate) dc = ql.Actual365Fixed() disc_curve = ql.FlatForward(today, rate_handle, dc) disc_curve.enableExtrapolation() hyts = ql.YieldTermStructureHandle(disc_curve) discount = np.vectorize(hyts.discount) start = ql.TARGET().advance(today, ql.Period('2D')) end = ql.TARGET().advance(start, ql.Period('10Y')) nominal = 1e7 typ = ql.VanillaSwap.Payer fixRate = 0.03 fixedLegTenor = ql.Period('1y') fixedLegBDC = ql.ModifiedFollowing fixedLegDC = ql.Thirty360(ql.Thirty360.BondBasis) index = ql.Euribor6M(ql.YieldTermStructureHandle(disc_curve)) spread = 0.0 fixedSchedule = ql.Schedule(start, end, fixedLegTenor, index.fixingCalendar(), fixedLegBDC, fixedLegBDC, ql.DateGeneration.Backward, False) floatSchedule = ql.Schedule(start, end, index.tenor(), index.fixingCalendar(), index.businessDayConvention(), index.businessDayConvention(), ql.DateGeneration.Backward, False) swap = ql.VanillaSwap(typ, nominal, fixedSchedule, fixRate, fixedLegDC, floatSchedule, index, spread, index.dayCounter()) engine = ql.DiscountingSwapEngine(ql.YieldTermStructureHandle(disc_curve)) swap.setPricingEngine(engine) print(swap.NPV()) print(swap.fairRate()) EOF # Test python3 cd $HOME python3 swap.py # Install boost 1.71 apt-get install build-essential export boost_version=1.71.0; export boost_dir=boost_1_71_0; cd $HOME; wget https://dl.bintray.com/boostorg/release/${boost_version}/source/${boost_dir}.tar.gz export boost_version=1.71.0; export boost_dir=boost_1_71_0; cd $HOME; tar xfz ${boost_dir}.tar.gz && cd ${boost_dir} && ./bootstrap.sh && ./b2 --without-python --prefix=/usr -j 4 link=shared runtime-link=shared install && cd .. && rm -rf ${boost_dir} && ldconfig # Install quantlib 1.17 export quantlib_version=1.17; cd $HOME; wget https://dl.bintray.com/quantlib/releases/QuantLib-${quantlib_version}.tar.gz export quantlib_version=1.17; cd $HOME; tar xfz QuantLib-${quantlib_version}.tar.gz && cd QuantLib-${quantlib_version} && ./configure --prefix=/usr --disable-static CXXFLAGS=-O3 && make -j 4 && make install && cd .. && ldconfig # Test quantlib 1.17 #Create testql.cpp cd $HOME cat > testql.cpp << 'testqlEOF' #include <ql/quantlib.hpp> int main() { std::cout << "BOOST version is " << BOOST_VERSION << std::endl; std::cout << "QL version is " << QL_VERSION << std::endl; #if __x86_64__ || __WORDSIZE == 64 std::cout << "This is 64 bits" << std::endl; #elif __i386__ || __WORDSIZE == 32 std::cout << "This is 32 bits" << std::endl; #else std::cout << "This is something else" << std::endl; #endif return 0; } testqlEOF g++ testql.cpp -lQuantLib -o testql ./testql # Test QuantLib Examples cd $HOME g++ QuantLib-*/Examples/Bonds/Bonds.cpp -lQuantLib -o testBonds ./testBonds cd $HOME g++ QuantLib-*/Examples/FRA/FRA.cpp -lQuantLib -o testFRA ./testFRA # Python 2 installation apt-get install python python-pip -y pip2 install numpy QuantLib-Python==1.17 pip2 freeze apt-get install git -y # Test python2 cd $HOME git clone git://github.com/mmport80/QuantLib-with-Python-Blog-Examples.git cd QuantLib-with-Python-Blog-Examples/ python2 blog_frn_example.py cd $HOME python2 swap.py



Export and Import of container
docker export CONTAINER_NAME | gzip > NAME.gz
zcat NAME.gz | docker import - IMAGE-NAME



Wednesday, August 3, 2016

Bash Shell Built Into Windows 10 Anniversary Update 1607 Build 14393.10

After Windows 10 Anniversary Update, you have to enable "Developer mode" on the "Update & Security" page.
Then go to Control Panel -> Program and Features -> Turn Windows Features on or off -> Windows SubSystem for Linux (Beta), and click OK.

Bash Shell is only for 64-bit versions of Windows 10.

Bash Shortcut Keys
There are a number of very useful shortcut keys you can use in the bash shell:

Ctrl + U: Clears the line from the cursor point back to the beginning.
Ctrl + A: Moves the cursor to the beginning of the line.
Ctrl + E: Moves the cursor to the end of the line.
Ctrl + Left / Right: Moves the cursor to one word Left / Right.
Ctrl + R: Allows you to search through the previous commands.

Batch Rename Files
rename –v 's/foo/bar/g' *

Customize command line prompt
function prompt
{
local WHITE="\[\033[1;37m\]"
local GREEN="\[\033[0;32m\]"
local CYAN="\[\033[0;36m\]"
local GRAY="\[\033[0;37m\]"
local BLUE="\[\033[0;34m\]"
export PS1="${GREEN}\u${CYAN}@${BLUE}\h ${CYAN}\w${GRAY}$ "
}
prompt


where
\u refers to the current username
\h refers to the host name
\w refers to the current file path.

or simply uncomment the line force_color_prompt=yes in ~/.bashrc

You can use Docker for Windows as engine and docker client for linux in bash. "Docker for Windows" requires Windows 10 Pro 64-bit and Hyper-V Package.

To install docker client for Linux under bash shell
cd ~/
wget https://get.docker.com/builds/Linux/x86_64/docker-1.12.0.tgz
tar -xzvf docker-1.12.0.tgz
cd docker
./docker -H tcp://0.0.0.0:2375 ps


Or simply add the corresponding variables to ~/.bashrc
export DOCKER_HOST=tcp://0.0.0.0:2375
export PATH=$PATH:~/docker

To detach the docker tty without exiting the shell, use the escape sequence Ctrl-p + Ctrl-q


Install docker-compose and try docker-compose example as per https://docs.docker.com/compose/wordpress/
shell script    Select all
# install dcoker-compose curl -L https://github.com/docker/compose/releases/download/1.8.0/docker-compose-`uname -s`-`uname -m` > ~/docker/docker-compose chmod +x ~/docker/docker-compose docker-compose --version # try docker-compose example on wordpress and mysql images cd $HOME mkdir my-wordpress cd my-wordpress cat > docker-compose.yaml <<EOF version: '2' services: db: image: mysql:5.7 volumes: - "./.data/db:/var/lib/mysql" restart: always environment: MYSQL_ROOT_PASSWORD: wordpress MYSQL_DATABASE: wordpress MYSQL_USER: wordpress MYSQL_PASSWORD: wordpress wordpress: depends_on: - db image: wordpress:latest links: - db ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_PASSWORD: wordpress EOF # start the docker-compose example docker-compose up -d # then try browser http://localhost:8000/ # stop the docker-compose example docker-compose down


Swift 3 on Ubuntu (14.04 LTS trusty) for Windows 10 bash shell

You need to download and extract the development snapshot (Ubuntu 14.04) from swift.org and do these under bash shell.
shell script    Select all
# download and extract swift 3 snapshot cd ~/ wget https://swift.org/builds/development/ubuntu1404/swift-DEVELOPMENT-SNAPSHOT-2016-08-04-a/swift-DEVELOPMENT-SNAPSHOT-2016-08-04-a-ubuntu14.04.tar.gz tar xzvf swift-DEVELOPMENT-SNAPSHOT-2016-08-04-a-ubuntu14.04.tar.gz # the latest snapshot 2016-08-23 has libdispatch cd ~/ wget https://swift.org/builds/development/ubuntu1404/swift-DEVELOPMENT-SNAPSHOT-2016-08-23-a/swift-DEVELOPMENT-SNAPSHOT-2016-08-23-a-ubuntu14.04.tar.gz tar xzvf swift-DEVELOPMENT-SNAPSHOT-2016-08-23-a-ubuntu14.04.tar.gz # Swift 3.0 GM Candidate cd ~/ wget https://swift.org/builds/swift-3.0-GM-CANDIDATE/ubuntu1404/swift-3.0-GM-CANDIDATE/swift-3.0-GM-CANDIDATE-ubuntu14.04.tar.gz tar xzvf swift-3.0-GM-CANDIDATE-ubuntu14.04.tar.gz # Swift 3.0.2 Release cd ~/ wget https://swift.org/builds/swift-3.0.2-release/ubuntu1404/swift-3.0.2-RELEASE/swift-3.0.2-RELEASE-ubuntu14.04.tar.gz tar xzvf swift-3.0.2-RELEASE-ubuntu14.04.tar.gz # install and configure clang plus other tools sudo apt-get update sudo apt-get install -y libicu-dev uuid-dev clang-3.6 sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-3.6 100 sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.6 100 sudo apt-get install -y git build-essential # clears the executable stack flag of shared library sudo apt-get install -y execstack sudo execstack -c ~/swift-DEVELOPMENT-SNAPSHOT-2016-08-04-a-ubuntu14.04/usr/lib/swift/linux/libFoundation.so sudo execstack -c ~/swift-DEVELOPMENT-SNAPSHOT-2016-08-23-a-ubuntu14.04/usr/lib/swift/linux/libFoundation.so sudo execstack -c ~/swift-3.0-GM-CANDIDATE-ubuntu14.04/usr/lib/swift/linux/libFoundation.so sudo execstack -c ~/swift-3.0.2-RELEASE-ubuntu14.04/usr/lib/swift/linux/libFoundation.so # add path in ~/.bashrc export PATH=$PATH:~/swift-DEVELOPMENT-SNAPSHOT-2016-08-04-a-ubuntu14.04/usr/bin export PATH=$PATH:~/swift-DEVELOPMENT-SNAPSHOT-2016-08-23-a-ubuntu14.04/usr/bin export PATH=$PATH:~/swift-3.0-GM-CANDIDATE-ubuntu14.04/usr/bin export PATH=$PATH:~/swift-3.0.2-RELEASE-ubuntu14.04/usr/bin # test Foundation, libdispatch and swiftc compile cat > hello.swift <<EOF import Foundation let device = "WIN10" print("Hello from Swift on \(device)") //print("\(TimeZone.defaultTimeZone().name) \(NSDate())") // for old snapshot 2016-08-04 //print("\(NSTimeZone.defaultTimeZone().abbreviation()!) \(NSDate())") // for old snapshot 2016-08-23 print("\(NSTimeZone.default.abbreviation()!) \(NSDate())") // for Swift 3.0 GM Candidate // Test libdispatch import Dispatch var my_dispatch_group = DispatchGroup() let concurrentQueue = DispatchQueue(label: "myqueuename", attributes: DispatchQueue.Attributes.concurrent) for a in 1...20 { my_dispatch_group.enter() let block = DispatchWorkItem { print("do something at \(a)") } my_dispatch_group.leave() my_dispatch_group.notify(queue: concurrentQueue, work:block) } let item = DispatchWorkItem { print("PROGRAM ENDED \(NSTimeZone.default.abbreviation()!) \(NSDate())") } my_dispatch_group.notify(queue: DispatchQueue.global(qos:.userInitiated), work:item) print("press enter to exit") let _ = readLine(strippingNewline: true) EOF swiftc hello.swift ./hello # test Swift Package Manager mkdir -p $HOME/test1 cd $HOME/test1 swift package init swift test


Install node.js and mongo shell for Ubuntu
shell script    Select all
# download and extract node.js cd ~/ wget https://nodejs.org/dist/v4.4.7/node-v4.4.7-linux-x64.tar.xz tar xpvf node-v4.4.7-linux-x64.tar.xz # add path in ~/.bashrc export PATH=$PATH:~/node-v4.4.7-linux-x64/bin node --version npm --version # install mongo shell for version 3.2.8 # please refer to instructions here https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927 echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list sudo apt-get update sudo apt-get install -y mongodb-org-shell=3.2.8 # if you follow the previous post on nodeapi.zip example # you need to install mongodb server on the Windows platform # in order to test that example.


File System Access

Ubuntu filesystem from Windows Explorer
C:\Users\%USERNAME%\AppData\Local\Lxss\rootfs
Ubuntu 16.04 filesystem from Windows Explorer, Fall Creators Update (2017 Oct)
C:\Users\%USERNAME%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs\

Windows filesystem from Ubuntu bash
/mnt/c/
/mnt/d/

#edit ~/.bashrc
#add export LS_COLORS=$LS_COLORS:'di=1;44:' ; # dir white on blue background


To upgrade to Ubuntu 16.04 after Windows 10's Creators Update (2017 April)
open the Bash shell and run the following command:


sudo do-release-upgrade

lsb_release -a

However, lxrun /uninstall then lxrun /install is faster.


The lastest installtion of WSL is documented at https://docs.microsoft.com/en-us/windows/wsl/install-win10
where different and multiple distros can be installed via Microsoft Store since Fall Creators Update (2017 Oct).


Installation of Swift 3.1.1 in Ubuntu 16.04
shell script    Select all
# Install related packages and set LLVM 3.8 as the compiler sudo apt-get -q update && sudo apt-get -q install -y make libc6-dev clang-3.8 curl libedit-dev libicu-dev libssl-dev libxml2 git libcurl4-openssl-dev pkg-config sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-3.8 100 sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.8 100 curl -fSLO https://swift.org/builds/swift-3.1.1-release/ubuntu1604/swift-3.1.1-RELEASE/swift-3.1.1-RELEASE-ubuntu16.04.tar.gz # Swift 4.0 # https://swift.org/builds/swift-4.0-release/ubuntu1604/swift-4.0-RELEASE/swift-4.0-RELEASE-ubuntu16.04.tar.gz tar xzvf swift-3.1.1-RELEASE-ubuntu16.04.tar.gz export PATH=$PATH:$HOME/swift-3.1.1-RELEASE-ubuntu16.04/usr/bin #test Hello mkdir Hello cd Hello/ swiftc --version swift package init --type=executable swift build ./.build/debug/Hello # test Swift Package Manager mkdir -p $HOME/SessionState cd $HOME/SessionState swift package init --type library cat > $HOME/SessionState/Sources/SessionState.swift <<EOF // SessionState.swift import Foundation import Dispatch public class SessionState { private var storage = [String:Any]() // serial access to internal dictionary // private let syncQueue = DispatchQueue(label:"serializationQueue") // change to concurrent queue private let asyncQueue = DispatchQueue(label:"asyncQueue", attributes:.concurrent, target:nil) private init() {} public static let shared:SessionState = { let instance = SessionState() return instance } () public func set( _ value: Any, forKey key: String) { asyncQueue.sync(flags: .barrier) { // change to barrier queue to have serial write access // syncQueue.sync { storage[key] = value } } public func object (forKey key: String) -> Any? { var result: Any? asyncQueue.sync { result = storage[key] ?? nil } return result } } EOF cat > $HOME/SessionState/Tests/SessionStateTests/SessionStateTests.swift <<EOF //SessionStateTests.swift import XCTest import Dispatch @testable import SessionState class SessionStateTests:XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testConcurrentAccess() { let asyncQueue = DispatchQueue( label: "asyncQueue", attributes: .concurrent, target: nil ) let expect = expectation(description: "Storing value in SessionState shall succeed") let MaxIndex = 2000 for index in 0...MaxIndex { asyncQueue.async { SessionState.shared.set ( index, forKey: String(index) ) } } while SessionState.shared.object(forKey: String(MaxIndex)) as? Int != MaxIndex { //nop } expect.fulfill() waitForExpectations(timeout:10) { (error) in XCTAssertNil(error, "Test expectation failed") } } static var allTests = [ ("testConcurrentAccess", testConcurrentAccess), ] } EOF # build and test swift test # Compile and install Boost sudo apt-get -q install -y build-essential cd $HOME curl -O https://nchc.dl.sourceforge.net/project/boost/boost/1.62.0/boost_1_62_0.tar.bz2 tar xjvf boost_1_62_0.tar.bz2 cd boost_1_62_0/ ./bootstrap.sh --with-libraries=atomic,chrono,date_time,exception,filesystem,graph,iostreams,math,program_options,random,regex,serialization,signals,system,test,thread,wave --prefix=/usr ./b2 -j6 toolset=gcc address-model=64 threading=multi link=static sudo ./b2 install # Compile and install QuantLib cd $HOME curl -O https://jaist.dl.sourceforge.net/project/quantlib/QuantLib/1.10/QuantLib-1.10.tar.gz tar xzvf QuantLib-1.10.tar.gz # QuantLib 1.11 download link # https://jaist.dl.sourceforge.net/project/quantlib/QuantLib/1.11/QuantLib-1.11.tar.gz cd QuantLib-1.10/ ./configure --prefix=/usr --enable-static --disable-examples make -j6 sudo make install # to remove -> sudo make uninstall # test QuantLib cd $HOME cat > $HOME/qlversion.cpp <<EOF #include <iostream> #include <ql/version.hpp> int main() { std::cout << "Current QL Version:" << QL_LIB_VERSION << std::endl; return 0; } EOF g++ qlversion.cpp -o qlversion ./qlversion # Following this instruction to install QuantLib Python # http://quantlib.org/install/linux-python.shtml



Installation of Swift 4 for Cygwin64
shell script    Select all
# first install Cygwin64 in Windows # In Cygwin64 Terminal prompt wget -q https://github.com/tinysun212/swift-windows/releases/download/swift-4.0.3%2Bcygwin.20180212/swift-4.0.3.cygwin.20180212-bin.tar.gz tar zxf swift-4.0.3.cygwin.20180212-bin.tar.gz export PATH=$PATH:$(pwd)/usr/bin swift --version # test git clone https://github.com/apple/example-package-dealer.git cd example-package-dealer swift run Dealer



Tuesday, June 21, 2016

How to run Docker for macOS

1) Download from here -> https://docs.docker.com/docker-for-mac/

2) Drag to Application Folder and double click to start and then check version in Terminal
docker --version
docker info


3) Search and Pull Docker image
E.g.
docker search kitura
docker pull ibmcom/kitura-ubuntu:latest


4) Run image with port forwarding <local port : container port>
E.g.
docker run --cap-add sys_ptrace -p 8095:8095 -t -i ibmcom/kitura-ubuntu:latest /bin/bash

5) Run / Download (if none) additional images and run as daemon
docker run -d -p 8080:8080 --name nodejs node
docker run -d -p 80:80 --name webserver nginx


6) List all downloaded or committed images
docker images

Download old images from
http://mirror.yandex.ru/mirrors/download.openvz.org/template/precreated/
and using import
cat ~/Downloads/ubuntu-10.04-x86.tar.gz | docker import - ubuntu-x86:10.04
or
docker import ubuntu-10.04-x86.tar.gz ubuntu-x86:10.04

docker run -t -i ubuntu-x86:10.04 bash


7) Run image with port forwarding <local port : container port> and bash shell
docker run -p 8095:8095 -t -i ibmcom/kitura-ubuntu:latest bash
docker run -p 80:80 -t -i nginx:latest bash
docker run -p 3000:3000 -t -i node:latest bash
docker run -t -i lballabio/quantlib:latest bash
docker run -t -i lballabio/quantlib-python:latest bash


8) List all containers with <CONTAINER ID>
docker ps -a
#export container
docker export <CONTAINER ID> > ubuntu.tar


Execute container with bash shell
docker exec -t -i <CONTAINER ID> bash

9) Commit changes to image with <newname:newtag>
docker commit <CONTAINER ID> kitura-ubuntu:v2
docker run -p 8095:8095 -it kitura-ubuntu:v2 /bin/bash

This is useful when you cannot start a container manually after docker upgraded. e.g.
docker start <CONTAINER ID> && docker attach <CONTAINER ID>


10) copy docker file to local docker start <CONTAINER ID>
docker cp <CONTAINER ID>:/root/myfile.tgz .




Docker for Mac OSX data is at
~/Library/Containers/com.docker.docker/Data



To test the kitura docker image for Swift web app
shell script    Select all
mkdir $HOME/play cd $HOME/play #swift build --init swift package init cat > $HOME/play/Package.swift <<EOF import PackageDescription let package = Package( name: "play", dependencies: [ .Package(url: "https://github.com/IBM-Swift/Kitura.git", majorVersion:0, minor:15), .Package(url: "https://github.com/OpenKitten/MongoKitten.git", majorVersion: 1, minor: 1) ] ) EOF mkdir -p $HOME/play/Sources cat > $HOME/play/Sources/main.swift <<EOF import Foundation import Kitura import KituraSys import KituraNet import MongoKitten // All Web apps need a Router instance to define routes let router = Router() // Simple Mongodb instance let dbserver: MongoKitten.Server! do { dbserver = try Server("mongodb://test:test@localhost:27017", automatically: true) let database = dbserver["workouts"] print("MongoDB is available at port 27017") } catch { // Unable to connect print("MongoDB is not available on the given host and port") } // Simple JSON Wrapper Support func JSON<KeyType, ValueType>(_ dictionary: [KeyType: ValueType]) -> String? { let bridgeValue = dictionary.bridge() do { let jsonData = try NSJSONSerialization.data(withJSONObject:bridgeValue, options: NSJSONWritingOptions.PrettyPrinted) let str = String(data:jsonData, encoding: NSUTF8StringEncoding) return(str) } catch let error as NSError{ print(error.description) return(nil) } } // Basic GET request router.get("/hello") { _, response, next in response.headers["Content-Type"] = "text/plain; charset=utf-8" do { try response.status(.OK).send("Hello World").end() } catch { print("ERROR: Failed to send response to client: \(error)") } } router.get("/today") { _, response, next in let now = NSDate() let dayTimePeriodFormatter = NSDateFormatter() dayTimePeriodFormatter.dateFormat = "E, d MMM yyyy" let dateString = dayTimePeriodFormatter.string(from:now) dayTimePeriodFormatter.dateFormat = "HH:mm:ss Z" let timeString = dayTimePeriodFormatter.string(from:now) response.headers["Content-Type"] = "text/plain; charset=utf-8" do { let payload = ["Message": "Hello World", "Date": dateString, "Time": timeString] if let json = JSON(payload) { try response.status(.OK).send(json).end() } else { try response.status(.OK).send("Does anybody really know what time it is ?").end() } } catch { print("ERROR: Failed to send response to client: \(error)") } } // Start server let port = 8095 let server = HTTPServer.listen(port:port, delegate: router) print("starting server on port \(port)") Server.run() EOF cd $HOME/play/Packages/SwiftyJSON-7.0.4/ git pull #there are 3 errors in Packages/Strand-1.4.1/Sources/Strand.swift and need to be changed before build #Strand.swift let pointer = UnsafeMutablePointer<Void>(holder.toOpaque()) #change to let pointer = UnsafeMutablePointer<Void>(OpaquePointer(bitPattern: holder)) let unmanaged = Unmanaged<StrandClosure>.fromOpaque(arg)] #change to let unmanaged = Unmanaged<StrandClosure>.fromOpaque(OpaquePointer(arg)) private func runner(arg: UnsafeMutablePointer<Void>?) -> UnsafeMutablePointer<Void>? { #change to private func runner(arg: UnsafeMutablePointer<Void>!) -> UnsafeMutablePointer<Void>! { and 1 error in Packages/MongoKitten-1.1.0/Sources/Server.swift let port: UInt16 = UInt16(url.port?.int16Value ?? 27017) # change to let port: UInt16 = UInt16(url.port?.shortValue ?? 27017) #build app cd $HOME/play swift build -Xcc -fblocks -Xlinker -rpath -Xlinker .build/debug #install and start mongodb server apt-get update apt-get install mongodb -y apt-get install lsb-release -y service mongodb start #create user in mongodb using mongo client mongo > use workouts > db.createUser( {user: "test", pwd: "test", roles: [ "readWrite", "dbAdmin" ]} ); > show users > exit #run app and use mac browser to localhost:8095/hello .build/debug/play






To test the node docker image for node.js web app
shell script    Select all
#install mongodb apt-get update apt-get install mongodb mongodb-server mongodb-clients -y #start mongdb service if not automatically service mongodb start #mongo shell script create user and to display info mongo > use workouts > db.addUser( {user: "test", pwd: "test", roles: [ "readWrite", "dbAdmin" ]} ); > show users > exit #download project file and copy to the container #the project file can be downloaded from here https://mega.nz/#!z9oFlTgJ!geCPHjoXJ3rpm1OdldU8s5RBSJxLKiAxh_axvTbODB4 docker cp ~/Download/nodeapi.zip 6d8baf06826e:/root #unzip and install apt-get install zip unzip -y cd $HOME unzip nodeapi.zip cd nodeapi npm install npm start #use docker to start another shell access to test docker exec -it 6d8baf06826e bash cd $HOME/nodeapi ./test1.sh ./test2.sh ./test3.sh ./test4.sh ./test5.sh ./test6.sh ...






To test the quantlib or quantlib-python3 docker image
shell script    Select all
apt-get update apt upgrade apt-get install python python-pip -y pip install --upgrade pip # Python 2 installation pip2 install numpy pip2 install QuantLib-Python # Python 3 installation apt-get install python3 python3-pip -y pip3 install numpy pip3 install QuantLib-Python # Install boost 1.71 export boost_version=1.71.0; export boost_dir=boost_1_71_0; wget https://dl.bintray.com/boostorg/release/${boost_version }/source/${boost_dir}.tar.gz && tar xfz ${boost_dir}.tar.gz && rm ${boost_dir}.tar.gz && cd ${boost_dir} && ./bootstrap.sh && ./b2 --without-python --prefix=/usr -j 4 link=shared runtime-link=shared install && cd .. && rm -rf ${boost_dir} && ldconfig # Install quantlib 1.17 export quantlib_version=1.17; wget https://dl.bintray.com/quantlib/releases/QuantLib-${quantlib_version}.tar.gz && tar xfz QuantLib-${quantlib_version}.tar.gz && rm QuantLib-${quantlib_version}.tar.gz && cd QuantLib-${quantlib_version} && ./configure --prefix=/usr --disable-static CXXFLAGS=-O3 && make -j 4 && make check && make install && cd .. && rm -rf QuantLib-${quantlib_version} && ldconfig # Test quantlib 1.17 cd $HOME cat > $HOME/qlversion.cpp <<EOF #include <iostream> #include <ql/version.hpp> int main() { std::cout << "Current QL Version:" << QL_LIB_VERSION << std::endl; return 0; } EOF g++ qlversion.cpp -o qlversion ./qlversion cat > $HOME/swap.py <<EOF import numpy as np import QuantLib as ql # Set Evaluation Date today = ql.Date(31,3,2015) ql.Settings.instance().setEvaluationDate(today) # Setup the yield termstructure rate = ql.SimpleQuote(0.03) rate_handle = ql.QuoteHandle(rate) dc = ql.Actual365Fixed() disc_curve = ql.FlatForward(today, rate_handle, dc) disc_curve.enableExtrapolation() hyts = ql.YieldTermStructureHandle(disc_curve) discount = np.vectorize(hyts.discount) start = ql.TARGET().advance(today, ql.Period('2D')) end = ql.TARGET().advance(start, ql.Period('10Y')) nominal = 1e7 typ = ql.VanillaSwap.Payer fixRate = 0.03 fixedLegTenor = ql.Period('1y') fixedLegBDC = ql.ModifiedFollowing fixedLegDC = ql.Thirty360(ql.Thirty360.BondBasis) index = ql.Euribor6M(ql.YieldTermStructureHandle(disc_curve)) spread = 0.0 fixedSchedule = ql.Schedule(start, end, fixedLegTenor, index.fixingCalendar(), fixedLegBDC, fixedLegBDC, ql.DateGeneration.Backward, False) floatSchedule = ql.Schedule(start, end, index.tenor(), index.fixingCalendar(), index.businessDayConvention(), index.businessDayConvention(), ql.DateGeneration.Backward, False) swap = ql.VanillaSwap(typ, nominal, fixedSchedule, fixRate, fixedLegDC, floatSchedule, index, spread, index.dayCounter()) engine = ql.DiscountingSwapEngine(ql.YieldTermStructureHandle(disc_curve)) swap.setPricingEngine(engine) print(swap.NPV()) print(swap.fairRate()) EOF python swap.py apt-get install git -y git clone git://github.com/mmport80/QuantLib-with-Python-Blog-Examples.git cd QuantLib-with-Python-Blog-Examples/ python2 blog_frn_example.py



Try docker-compose example as per https://docs.docker.com/compose/wordpress/
shell script    Select all
cd $HOME mkdir my-wordpress cd my-wordpress cat > docker-compose.yaml <<EOF version: '2' services: db: image: mysql:5.7 volumes: - "./.data/db:/var/lib/mysql" restart: always environment: MYSQL_ROOT_PASSWORD: wordpress MYSQL_DATABASE: wordpress MYSQL_USER: wordpress MYSQL_PASSWORD: wordpress wordpress: depends_on: - db image: wordpress:latest links: - db ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_PASSWORD: wordpress EOF docker-compose up -d # then try browser http://localhost:8000/ # stop the docker-compose example docker-compose down