Showing posts with label swift. Show all posts
Showing posts with label swift. Show all posts

Sunday, March 21, 2021

How to install Swift 5 compiler for Android Termux App

(1) Installation of packages
pkg install clang
pkg install swift


(2) Test Grand Central Dispatch - concurrent queue
Shell script   Select all
cd $HOME cat >$HOME/concurrentqueue.swift <<'HEREEOF' /* # Concurrent Programming with Grand Central Dispatch in Swift 5 */ import Foundation let globalQueue = DispatchQueue.global(qos: .userInitiated) func trace(task: Int) { // Generates a random integer in the [0, task] range print("Task \(task) started") sleep( UInt32.random(in: 0...UInt32(task)) ) print("Task \(task) completed") } print("Concurrent queue, synchronous execution") for i in 1...5 { print("Submitting task \(i)") globalQueue.sync { trace(task: i) } } print("\nConcurrent queue, asynchronous execution") for i in 6...9 { print("Submitting task \(i)") globalQueue.async { trace(task: i) } } sleep(10) print("Program ended") HEREEOF # test swiftc concurrentqueue.swift ./concurrentqueue


(3) Test Grand Central Dispatch - serial queue
Shell script   Select all
cd $HOME cat >$HOME/serialqueue.swift <<'HEREEOF' /* # Concurrent Programming with Grand Central Dispatch in Swift 5 */ import Foundation let serialQueue = DispatchQueue(label: "com.mycompany.demo.serial") func trace(task: Int) { // Generates a random integer in the [0, task] range print("Task \(task) started") sleep( UInt32.random(in: 0...UInt32(task)) ) print("Task \(task) completed") } print("\nSerial queue, synchronous execution") for i in 1...5 { print("Submitting task \(i)") serialQueue.sync { trace(task: i) } } print("\nSerial queue, asynchronous execution") for i in 6...9 { print("Submitting task \(i)") serialQueue.async { trace(task: i) } } sleep(25) print("Program ended") HEREEOF # test swiftc serialqueue.swift ./serialqueue


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, March 15, 2016

Personal Installation Guide for Raspberry Pi 3 with Swift

Hardware List from RS:
Raspberry Pi 3 Model B SBC
Heatsink BGA 12x12 27K/W black
Official Pi 3 Power Supply Black
Official Pi 3 Black/Grey Case

Accessories:
MicroSDHC Card (with Adapter) 32G Class 10
USB SSD Harddisk 240G
USB Keyboard and Mouse

SD Card images for multiboot
1. NOOBS(easy to install but hard to reconfigure or add custom image for multiboot)
#Download NOOBS using Mac Terminal and write to MicroSDHC Card (with Adapter and mounted in Mac)
cd ~/Downloads
wget http://vx2-downloads.raspberrypi.org/NOOBS/images/NOOBS-2016-02-29/NOOBS_v1_8_0.zip
unzip NOOBS_v1_8_0.zip -d /Volumes/NO\ NAME/

#insert the SD card and power on the machine
#after boot into NOOBS and choose install Rasbian and OSMC (that is kodi)
#Rasbian username and password are pi and raspberry respectively
#OSMC username and password are all osmc


2. BerryBoot(very flexible and allow to add custom image for multiboot)
wget http://downloads.sourceforge.net/project/berryboot/berryboot-20160313-pi2-pi3.zip
# for reformat SD Card to FAT32 and label BERRYBOOT
# sudo diskutil eraseDisk FAT32 BERRYBOOT MBRFormat /dev/disk4

unzip berryboot-20160313-pi2-pi3.zip -d /Volumes/BERRYBOOT/

#insert the SD card and power on the machine
#after boot into BerryBoot and choose install Debian Rasbian, OpenELEC (that is kodi) or others
#OpenELEC username and password are root and openelec respectively.
#hold down mouse button on AddOS button of BerryBoot Menu and choose Copy OS from USB stick

#To install Ubuntu-trusty image for berryboot downloaded here below
https://mega.nz/#!PwYl1QBJ!Fu7A87qrAL4jTmv0RhlnksprhVCm4gsHi1xhQBELJGk
# login to Ubuntu-trusty, username and password are all ubuntu

#BerryBoot additional images are here below and can be downloaded in USB drive for offline installation
https://sourceforge.net/projects/berryboot/files/os_images/


It is possible to shrink the Linux partition of berryboot in order to create a third partition for the dphys-swapfile with about 2G size. The SD card for berryboot should be mounted as USB and Use  sudo umount /dev/sda2; sudo e2fsck -f /dev/sda2; sudo resize2fs /dev/sda2 27G; 
to check and shrink and use  sudo fdisk /dev/sda;  to delete the second partition, recreate the second partition with +27G and then create the third partition with remaining space for swap (about 2.5G if for 32G SD card).
And then  sudo mkfs.ext4 /dev/sda3;  to format as ext4 and run  sudo fsck.ext4 /dev/sda1; sudo fsck.ext4 /dev/sda2;  to check.

After booting into the berryboot SD card, add this in /etc/fstab
/dev/mmcblk0p3 /swap ext4 defaults,noatime 0 0

and then edit swap location to /swap/swap and mount the partition using  sudo mkdir -p /swap; sudo mount -t ext4 /dev/mmcblk0p3 /swap;  and then setup dphys-swapfile using  sudo vi /etc/dphys-swapfile;  to /swap/swap and run  sudo dphys-swapfile setup; sudo dphys-swapfile swapon; 


shell script    Select all
# change password passwd # su sudo su sudo apt-get update sudo apt-get upgrade sudo apt-get install vim zip unzip openssh-server git #Login to Ubuntu-trusty, username and password are ubuntu and ubuntu respectively # install clang and swift for Ubuntu-trusty only (but no swift package manager) sudo apt-get install libicu-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 #install swift-2.2_1%3a2.2-0ubuntu11~trusty1_armhf.deb (Ubuntu-trusty only) or just download from here without adding source repo #https://mega.nz/#!fpYxzBgY!MLGiW8HAV6MllAD0gkzrSFlQ6TdubwBfFYGyezNVAXg wget -qO- http://dev.iachieved.it/iachievedit.gpg.key | sudo apt-key add - echo "deb [arch=armhf] http://iachievedit-repos.s3.amazonaws.com/ trusty main" | sudo tee --append /etc/apt/sources.list sudo apt-get update sudo apt-get install swift-2.2 swift --version #test simple swift compile cat > hello.swift <<EOF let device = "Raspberry Pi 3!" print("Hello from Swift on \(device)") EOF swiftc hello.swift ./hello #Login to Rasbian, username and password are pi and raspberry respectively #change password (recomended) passwd #Rasbian config to set locale and timezone sudo raspi-config # configure keyboard to US sudo dpkg-reconfigure keyboard-configuration #reload the keymap sudo invoke-rc.d keyboard-setup start #scan hidden SSID sudo iwlist wlan0 scanning essid "Your Hidden SSID" #vi ~/.bashrc and add export LC_ALL="en_US.UTF-8" #add export LS_COLORS=$LS_COLORS:'di=1;44:' ; # dir white on blue background sudo locale-gen en_US.UTF-8 # generate locale for en_US.UTF-8 sudo dpkg-reconfigure locales #command line reset timezone sudo dpkg-reconfigure tzdata sudo apt-get update sudo apt-get upgrade sudo apt-get install vim openssh-server # Forwarding X11 application using ssh please refer to this guide https://kb.iu.edu/d/bdnt # In Linux or Mac ssh -Y pi@10.0.1.XX # In Windows 10 WSL, and install XServer in Windows 10 such as xming # export DISPLAY=:0 (for WSL x11-apps) export DISPLAY=localhost:0.0 ssh -Y pi@10.0.1.XX # After login Raspberry pi sudo apt-get install idle3 idle & # run scratch sudo apt-get install scratch scratch & sudo apt install codeblocks codeblocks & # run browser chromium-browser & #support of HFS Plus format drives sudo apt-get install hfsplus hfsutils hfsprogs gdisk #setup RAID, please refer to this, please use usb hub (with power source) for external HD disks. https://pchelp.ricmedia.com/build-raspberry-pi3-raid-nas-server/ #install nginx (lightweght webserver) sudo apt-get install nginx cd; ln -s /usr/share/nginx/html . #check ip adress and use browser connect to test web server hostname -I ifconfig eth0 ifconfig wlan0 # for wireless lan ip addr | grep -Po '(?!(inet 127.\d.\d.1))(inet \K(\d{1,3}\.){3}\d{1,3})' # generation of ssh key to remote server ssh-keygen -t rsa # copy ssh key to Raspberry Pi ssh-copy-id pi@raspberrypi_ip_address #install php in nginx #sudo apt-get install php5-fpm php-apc #sudo apt-get install php-fpm php-apcu sudo apt install php-fpm php-curl php-gd php-cli php7.3-opcache php-mbstring php-xml php-zip # link the html folder to home cd #ln -s /usr/share/nginx/html . ln -sf /var/www/html . # create testing php page cat > ~/html/info.php <<EOF <?php phpinfo(); ?> EOF #add in /etc/php/7.3/fpm/pool.d/www.conf user = pi group = pi # enable php in nginx sudo vi /etc/nginx/sites-enabled/default #see instructions for php7 here -> https://getgrav.org/blog/raspberrypi-nginx-php7-dev #see instructions here https://www.raspberrypi.org/documentation/remote-access/web-server/nginx.md sudo touch /var/run/php/php7.3-fpm.sock #reload web server and test #check to ensure the /var/run/php/php7.3-fpm.sock file exists sudo service nginx restart sudo service php7.3-fpm restart #install samba as a file server sudo apt-get install samba samba-common-bin #edit /etc/samba/smb.conf and add the followings # assume USB drive is mounted on /media/pi/USBDRIVE #manual mount external drive sudo mkdir -p /media/pi/USBDRIVE sudo mount -o uid=pi,gid=pi,rw /dev/sda1 /media/pi/USBDRIVE [public_USBDRIVE] comment = Public USBDRIVE browseable = yes read only = no force user = "pi" guest ok = yes public = yes writable = yes path = /media/pi/USBDRIVE create mask = 0755 directory mask = 0755 # reload samba # sudo service samba reload sudo systemctl restart smbd #install minidlna as a media server sudo apt install minidlna #edit /etc/minidlna.conf and add the followings media_dir=V,/media/pi/PassportUltra/Video friendly_name=My-Movie #edit /etc/default/minidlna and add the followings USER="root" GROUP="root" # reload minidlna sudo service minidlna restart sudo service minidlna force-reload # see what network services are working on raspberry pi sudo netstat -ntlp #install google app engine for development wget --no-check-certificate https://storage.googleapis.com/appengine-sdks/featured/google_appengine_1.9.34.zip unzip google_appengine_1.9.34.zip export PATH=$HOME/google_appengine:$PATH #test GAE web page from localhost web browser dev_appserver.py ~/google_appengine/demos/python/guestbook #test GAE web app from other machine dev_appserver.py --host $(ip addr | grep -Po '(?!(inet 127.\d.\d.1))(inet \K(\d{1,3}\.){3}\d{1,3})') --port 8080 ~/google_appengine/demos/python/guestbook/ dev_appserver.py --host $(hostname -I) --port 8080 ~/google_appengine/demos/python/guestbook/ # download node-v6.9.4-linux-armv7l.tar.xz from https://nodejs.org/en/download/ wget --no-check-certificate https://nodejs.org/dist/v6.9.4/node-v6.9.4-linux-armv7l.tar.xz # extract node-v6.9.4-linux-armv7l.tar.xz cd $HOME tar xJvf $HOME/Download/node-v6.9.4-linux-armv7l.tar.xz # setup PATH export PATH=$HOME/node-v6.9.4-linux-armv7l/bin:$PATH # Compile and Install Visual Studio Code 1.9.1 sudo apt-get update sudo apt-get install libx11-dev build-essential cd $HOME git clone https://github.com/microsoft/vscode cd $HOME/vscode git tag -l #checkout 1.9.1 git checkout tags/1.9.1 ./scripts/npm.sh install --arch=armhf # run Visual Studio Code ./scripts/code.sh # Visual Studio Code - Desktop Entry sudo tee /usr/share/applications/code.desktop > /dev/null <<'EOF' [Desktop Entry] Name=Visual Studio Code Comment=Code Editing. Redefined. GenericName=Text Editor Exec=/home/pi/vscode/scripts/code.sh %U Icon=code Type=Application StartupNotify=true StartupWMClass=Code Categories=Utility;TextEditor;Development;IDE; MimeType=text/plain;inode/directory; Actions=new-window; Keywords=vscode; [Desktop Action new-window] Name=New Window Name[de]=Neues Fenster Name[es]=Nueva ventana Name[fr]=Nouvelle fenêtre Name[it]=Nuova finestra Name[ja]=新規ウインドウ Name[ko]=새 창 Name[ru]=Новое окно Name[zh_CN]=新建窗口 Name[zh_TW]=開新視窗 Exec=/home/pi/vscode/scripts/code.sh %U Icon=code EOF # Manual download and install Visual Studio Extension # please refer to how to get the download url as referenced from http://stackoverflow.com/questions/37071388/how-to-install-vscode-extensions-offline wget --no-check-certificate https://ms-vscode.gallery.vsassets.io:443/_apis/public/gallery/publisher/ms-vscode/extension/cpptools/0.10.1/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage mv Microsoft.VisualStudio.Services.VSIXPackage ms-vscode-cpptools.vsix # Then use "Install from VSIX" menu item in Visual Studio code Debug Setting #install squid + unblock cn and assume node.js npm are installed as above sudo apt-get install squid3 git npm install Unblocker/Unblock-Youku #install phantomjs for testing git clone --depth 1 https://github.com/gautamMalu/PhantomJs-armhf.git #optionally install casper tag 1.1.1, PhantomJs+Casper for web scraping git clone --branch '1.1.1' --single-branch --depth 1 https://github.com/casperjs/casperjs.git sudo apt-get install libfontconfig1 libjpeg8 libicu-dev cd PhantomJs-armhf/bin; sudo mv phantomjs /usr/local/bin/ cd ~/node_modules/ub.uku.js/ npm install npm test #cp ~/node_modules/ub.uku.js/shared/urls.js ~/node_modules/ub.uku.js/youku.rules #cat ~/node_modules/ub.uku.js/shared/urls.js | grep "^[ ']*http" | sed "s/^[ ']*/\^/;s/[,'][ ]*\/\/.*$//;s/\*'$//;s/\*',$//;s/',//;s/[*?]$//;s/\*/\.\*/g;s/\?/\\\?/g;" > ~/node_modules/ub.uku.js/youku.rules vi ~/node_modules/ub.uku.js/youku.rules curl -o ~/node_modules/ub.uku.js/youku.rules http://pac.uku.im/regex sudo vi /etc/squid3/squid.conf acl localnet src 10.0.0.0/8 # RFC1918 possible internal network acl localnet src 192.168.0.0/16 # RFC1918 possible internal network http_access allow localnet # add acl rules acl uyouku url_regex -i "/home/pi/node_modules/ub.uku.js/youku.rules" never_direct allow uyouku cache_peer 127.0.0.1 parent 8888 0 no-query default cache_peer_access 127.0.0.1 allow uyouku cache_peer_access 127.0.0.1 deny all # enable cache_dir say 2048 (The default is 100 MB) cache_dir ufs /var/spool/squid3 2048 16 256 # 2016/03/09 https://github.com/Unblocker/Unblock-Youku/issues/618 # dns_nameservers 158.69.209.100 45.32.72.192 45.63.69.42 #restart squid3 sudo service squid3 reload #edit /home/pi/node_modules/ub.uku.js/server/server.js (near line 257) to change listening ip and port say 127.0.0.1 8888 # ubuku_server.listen('8888','127.0.0.1')... # auto run unblockcn and use http://ipservice.163.com/isFromMainland to test # sudo vi /etc/rc.local and add su pi -c '/usr/bin/nodejs /home/pi/node_modules/ub.uku.js/server/server.js --nolog --proxy=https://secure.uku.im:993 --bak_proxy=http://proxy.uku.im:443 --pac_proxy=http://proxy.uku.im:443 > /dev/null &' # test terminal run with external proxy sudo node /home/pi/node_modules/ub.uku.js/server/server.js --proxy=https://secure.uku.im:993 --bak_proxy=http://proxy.uku.im:443 --pac_proxy=http://proxy.uku.im:443 #support Chinese font 文鼎 PL 上海宋 Un and input method sudo apt-get install ttf-arphic-uming scim-tables-zh im-switch #support Chinese font 文泉驛微米黑體、文泉驛正黑體、文泉驛點陣宋體 sudo apt-get install ttf-wqy-microhei ttf-wqy-zenhei xfonts-wqy #ext4 TRIM command support using the discard mount option in fstab (or with tune2fs -o discard /dev/sdaX). sudo tune2fs -o discard /dev/sdb1 #install bitcoind #sudo apt-get install bitcoind # bitcoind deb package in Debian is obsolete and needs upgrade #build from source as below or download the precompiled version from here and use sudo dpkg -i to install https://mega.nz/#!KtJWTZ7A!RN4IOGtvflSc0lXuJB1__lYTkdYvsnoegk_JJ0JGtA8 #Build requirements sudo apt-get install build-essential libtool autotools-dev automake pkg-config libssl-dev libevent-dev bsdmainutils git sudo apt-get install libboost-system-dev libboost-filesystem-dev libboost-chrono-dev libboost-program-options-dev libboost-test-dev libboost-thread-dev libminiupnpc-dev libminiupnpc-dev libzmq3-dev libcrypto++9 minissdpd git clone -b 0.12 --depth 1 https://github.com/bitcoin/bitcoin.git #see here to build bitcoind with Berkeley DB script https://github.com/bitcoin/bitcoin/blob/master/doc/build-unix.md cd bitcoin mkdir -p db4 wget 'http://download.oracle.com/berkeley-db/db-4.8.30.NC.tar.gz' tar -xzvf db-4.8.30.NC.tar.gz cd db-4.8.30.NC/build_unix/ BDB_PREFIX=$(cd $(dirname "../../db4") && pwd -P)/$(basename "../../db4"); ../dist/configure --enable-cxx --disable-shared --with-pic --prefix=$BDB_PREFIX make install cd ../.. ./autogen.sh BDB_PREFIX="$(pwd)/db4"; ./configure LDFLAGS="-L${BDB_PREFIX}/lib/" CPPFLAGS="-I${BDB_PREFIX}/include/" CXXFLAGS="--param ggc-min-expand=1 --param ggc-min-heapsize=32768" --without-gui --with-miniupnpc --enable-upnp-default --disable-tests #Rasbian config to set boot option to CLI mode sudo raspi-config #compiling bitcoind is cpu-intensive and memory-hungry, better to reboot to CLI mode and kill unnecessary services then make -j2 sudo make install #setup bitcoind and let it create bitcoin.conf bitcoind -daemon bitcoin-cli stop # To enable TRIM, put discard option in fstab like this PARTUUID=6c887fff-01 /media/pi/SSDDRIVE ext4 defaults,discard 0 0 #create data directory in USB SSD drive mkdir -p /media/pi/SSDDRIVE/bitcoin cp ~/.bitcoin/bitcoin.conf /media/pi/SSDDRIVE/bitcoin/ cp ~/wallet.dat /media/pi/SSDDRIVE/bitcoin/ # if have old bitcoin wallet.dat #start bitcoind as daemon in SSD Drive bitcoind -datadir=/media/pi/SSDDRIVE/bitcoin -daemon bitcoind --help #while bitcoind is running as daemon, get new address and check other status # bitcoin-cli help bitcoin-cli getinfo bitcoin-cli listaccounts bitcoin-cli getnewaddress "worker1" # check tx history say https://blockchain.info/address/14uUbzJSi2t5MGgYH72PdTonD22V8drBVN bitcoin-cli getaccountaddress "worker1" bitcoin-cli getbalance #daemon will download the entire block chain data and can take over several days and total size > 60G bitcoin-cli getblockcount # the current blockcount should be over 1M https://blockchain.info/latestblock bitcoin-cli getconnectioncount #install cpuminer sudo apt-get install libcurl4-openssl-dev git make git clone --depth 1 git://github.com/pooler/cpuminer.git cd cpuminer ./autogen.sh ./configure CFLAGS="-O3" make sudo make install minerd --help minerd --url http://api.bitcoin.cz:8332 -a sha256d --userpass=yourid.worker1:pass1 #cgminer (but not working in Raspberry Pi 3 #OpenCL...............: Detection overrided. GPU mining support DISABLED git clone -b 3.7 https://github.com/ckolivas/cgminer.git cd cgminer ./autogen.sh ./configure --enable-opencl --enable-scrypt # configure failed due to absence of GPU and opencl in Raspberry Pi 3 #Build QuantLib 1.7.1 #libquantlib0-dev 1.4.2 is available in package repo #QuantLib 1.7.1 #or download the updated package from here https://mega.nz/#!PkYWBDLC!dC8klXxcouc1RrNQ2Bct_tSweaO6A3UwTNkGeXvGldo #Download QuantLib source and extract wget http://jaist.dl.sourceforge.net/project/quantlib/QuantLib/1.7.1/QuantLib-1.7.1.tar.gz tar -xzvf QuantLib-1.7.1.tar.gz #Build requirement sudo apt-get install build-essential libtool libboost-all-dev cd QuantLib-1.7.1 ./configure CXXFLAGS="--param ggc-min-expand=1 --param ggc-min-heapsize=32768" --disable-shared #Rasbian config to set boot option to CLI mode sudo raspi-config #compiling QuantLib is cpu-intensive and memory-hungry, better to reboot to CLI mode and kill unnecessary services then make -j2 # or just make if failed sudo make install #test compile QuantLib example cd ~/QuantLib-1.7.1/Examples/Bonds g++ Bonds.cpp -o bin/Bonds -lQuantLib # run example Bonds ./bin/Bonds #compiling litecoind is similar to bitcoind but it would conflict with bitcoind git clone --depth 1 https://github.com/litecoin-project/litecoin.git #build from source or download the precompiled version from here https://mega.nz/#!Ptwl0KZD!XVyO7DHugtoK2iEib2nj2jdyMRSkadlIMa1oPp3QSak #setup litecoind in raspberry pi litecoind #create data directory in USB SSD drive mkdir -p /media/pi/SSDDRIVE/litecoin cp ~/.litecoin/litecoin.conf /media/pi/SSDDRIVE/litecoin/ #start litecoind as daemon in SSD Drive litecoind -datadir=/media/pi/SSDDRIVE/litecoin -daemon litecoind --help #reindex litecoin database if corrupted litecoind -reindex -datadir=/media/pi/SSDDRIVE/litecoin #while litecoind is running as daemon, get new address and check other status # litecoin-cli help litecoin-cli getinfo litecoin-cli listaccounts litecoin-cli getnewaddress "worker2" # check tx history say https://block-explorer.com/address/LRwz2mJpoMz2FPkqE7hxKvcLnUyUHESW4Q litecoin-cli getaccountaddress "worker2" litecoin-cli getbalance litecoin-cli getblockcount # the current blockcount should be over 900000 see http://explorer.litecoin.net/ #setup local repo sudo apt-get install dpkg-dev sudo mkdir -p /usr/local/mydebs sudo cp -s /var/cache/apt/archives/*.deb /usr/local/mydebs/ cd /usr/local/mydebs sudo sh -c 'dpkg-scanpackages . /dev/null | gzip -9c > Packages.gz' echo "deb file:/usr/local/mydebs ./" | sudo tee --append /etc/apt/sources.list sudo apt-get update #setup swapfile in Rasbian sudo vi /etc/dphys-swapfile #edit the swapfile location and size (suggest min 2048) then save the file #for berryboot the swapfile should be in external USB drive sudo dphys-swapfile setup sudo dphys-swapfile swapon #check memory and swap free -h #turn off swap sudo dphys-swapfile swapoff #configure and make again for the projects #shutdown the machine sudo halt #restart the machine sudo reboot



Swift 2.2 for Linux package requires clang-3.6 and Ubuntu-trusty for Pi
This image https://wiki.ubuntu.com/ARM/RaspberryPi (2015-04-06-ubuntu-trusty.img) is for Raspberry Pi 2 and does not work on Raspberry Pi 3, the FAT32 partition content in the layout folder and the start*.elf, bcm2710-rpi-3-b.dtb should be upgraded/added for the new hardware for booting.
config.txt add these settings
disable_overscan=1
start=1
gpu_mem=64
max_usb_current=1
initramfs initrd7.img
kernel=kernel7.img


It is possible to install the Swift 2.2 in Rasbian other than Ubuntu-trusty for Pi
1. Install clang-3.7 and libicu-dev in Rasbian
sudo apt-get install libicu-dev clang-3.7
sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-3.7 100
sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.7 100

2. download the package from here without adding source repo
#https://mega.nz/#!fpYxzBgY!MLGiW8HAV6MllAD0gkzrSFlQ6TdubwBfFYGyezNVAXg

3. download a fake clang-3.6 package that install nothing but to meet dependency as a hack
https://mega.nz/#!voZ0yA6T!10lqNIhEKLfNpptmy-rlsEdRn15gIl14Fd0ibjmI_x8

4. install these deb files together
sudo dkpg -i clang-3.6-fake.deb swift-2.2_1%3a2.2-0ubuntu11~trusty1_armhf.deb

Swift 2.2 for Linux without Swift Package Manager. Here are the alternative ways:
shell script    Select all
#Method 1 : compile everything on build cd ${HOME} mkdir -p SwiftProjects cd ${HOME}/SwiftProjects # get dependency package git clone --depth 1 https://github.com/erica/SwiftString.git git clone --depth 1 https://github.com/haginile/SwiftDate.git #fix some errors in SwiftDate/SwiftDate/DateHelpers.swift and SwiftDate/SwiftDate/Term.swift simlar to previous post "What you need for Swift on Linux" vi SwiftDate/SwiftDate/DateHelpers.swift extension String { /* comment out these 2 func subscript (i: Int) -> String { return String(Array(self.characters)[i]) } subscript (r: Range<int>) -> String { get { let subStart = self.startIndex.advancedBy(r.startIndex, limit: self.endIndex) let subEnd = subStart.advancedBy(r.endIndex - r.startIndex, limit: self.endIndex) return self.substringWithRange(Range(start: subStart, end: subEnd)) } } */ vi +195 SwiftDate/SwiftDate/Term.swift #change from switch timeUnit { #to switch timeUnit! { // unwrapped optional cd ${HOME}/SwiftProjects mkdir -p Sources/Test1 cat > Sources/Test1/main.swift <<EOF #if os(Linux) import Glibc import Foundation #endif //import SwiftString //import SwiftDate import XCTest class SwiftDateTesting: XCTestCase { var allTests : [(String, () -> Void)] { return [ ("testCalendar", testCalendar), ("testDayCounter", testDayCounter), ] } func testCalendar() { var cal = USSettlementCalendar() XCTAssert(cal.isBizDay(Date(string: "2014-05-15")) == true, "Pass") XCTAssert(cal.isBizDay(Date(string: "2014-05-17")) == false, "Pass") XCTAssertEqual(cal.nextBizDay(Date(string: "2014-05-16")).serialNumber, Date(string: "2014-05-19").serialNumber, "Pass") XCTAssertEqual(cal.bizDaysBetween(Date(string: "2014-05-15"), toDate: Date(string : "2014-05-20")), 3, "Pass") } func testDayCounter() { var start_date = Date(string: "2000-01-15") var end_date = Date(string: "2000-05-31") var actual_365 = Actual365Fixed() XCTAssertEqual(actual_365.dayCountFraction(start_date, date2: end_date), 137.0 / 365, "Pass") var nl_365 = NL365() XCTAssertEqual(nl_365.dayCountFraction(start_date, date2: end_date), 136.0 / 365, "Pass") var act_360 = Actual360() XCTAssertEqual(act_360.dayCountFraction(start_date, date2: end_date), 137.0 / 360.0, "Pass") var thirty_360 = Thirty360() XCTAssertEqual(thirty_360.dayCountFraction(start_date, date2: end_date), 136.0 / 360.0, "Pass") var thirty_360e = Thirty360(convention: Thirty360.Convention.EurobondBasis) } } XCTMain([SwiftDateTesting()]) EOF cd Sources/Test1 swiftc -emit-executable ../../SwiftString/Sources/*.swift ../../SwiftDate/SwiftDate/*.swift main.swift -o test1 ./test1 #Method 2 : dynamic library link #build module and library for dynamic linking cd ${HOME}/SwiftProjects mkdir -p Sources/Test2 cat > Sources/Test2/main.swift <<EOF #if os(Linux) import Glibc import Foundation #endif import SwiftDateString let start_date = Date(string: "2000-01-15") var end_date = Date(string: "2000-05-31") var actual_365 = Actual365Fixed() print(actual_365.dayCountFraction(start_date, date2: end_date)) EOF cd Sources/Test2 #build module and dynamic library swiftc -emit-library ../../SwiftString/Sources/*.swift ../../SwiftDate/SwiftDate/*.swift -module-name SwiftDateString -emit-module-path SwiftDateString.swiftmodule -module-name SwiftDateString -module-link-name SwiftDateString #compile and link with dynamic library at current directory swiftc -emit-executable main.swift -o test2 -I. -L. -Xlinker -rpath -Xlinker "." -lSwiftDateString ./test2 #alternative way is to copy the shared library to /usr/lib then link sudo cp libSwiftDateString.so /usr/lib/ swiftc -emit-executable -I. -lSwiftDateString main.swift -o test2a ./test2a #Method 3: static library link #build module and static library for linking cd ${HOME}/SwiftProjects mkdir -p Sources/Test3 cat > Sources/Test3/main.swift <<EOF #if os(Linux) import Glibc import Foundation #endif import SwiftDateString public func timetest(block: () -> Void) { let date = NSDate() block() let timeInterval = NSDate().timeIntervalSinceDate(date) print("Elasped time: \(timeInterval)") } public func testit() { let start_date = Date(string: "2000-01-15") let end_date = Date(string: "2000-05-31") let actual_365 = Actual365Fixed() print("Function: \(__FUNCTION__), File: \(__FILE__)") print("2000-01-15 to 2000-05-31 dayCountFraction is ", terminator:"") print(actual_365.dayCountFraction(start_date, date2: end_date)) } timetest(testit) EOF #compile cd Sources/Test3 swiftc -module-name SwiftDateString -c ../../SwiftString/Sources/*.swift ../../SwiftDate/SwiftDate/*.swift -emit-module-path SwiftDateString.swiftmodule -module-link-name SwiftDateString PROJECT_PREFIX=$(cd $(dirname "../../") && pwd -P)/$(basename "../../"); mkdir -p obj; cd obj; swiftc -parse-as-library -module-name SwiftDateString -emit-object ${PROJECT_PREFIX}/SwiftString/Sources/*.swift ${PROJECT_PREFIX}/SwiftDate/SwiftDate/*.swift; cd .. #build static library ar -rcs libSwiftDateString.a obj/*.o #link with static library swiftc -emit-executable main.swift -o test3 -I. -L. -Xlinker libSwiftDateString.a #Method 4: Use makefile for static library link #makefile to build module and static library for linking cd ${HOME}/SwiftProjects mkdir -p Sources/tidyjson cd Sources/tidyjson git clone --depth 1 https://github.com/benloong/TidyJSON.git # edit TidyJSON/Sources/TidyJSON.swift #find dataUsingEncoding #//if let data = string.dataUsingEncoding(NSUTF8StringEncoding) { #and change it to if let data = NSString(string:string).dataUsingEncoding(NSUTF8StringEncoding) { # edit TidyJSON/Tests/Test.swift #add #if os(Linux) import Glibc #endif # find all lines with # var allTests : [(String, () throws -> ())] { # and change them to var allTests : [(String, () -> Void)] { # find all lines with let content = try String(contentsOfFile: "./Tests/TestCases/\(path).json", encoding: NSUTF8StringEncoding) # and change them to block code as below if let content = try? NSString(contentsOfFile: "./TidyJSON/Tests/TestCases/\(path).json", encoding: NSUTF8StringEncoding).bridge() { // no change here if let _ = try? JSON.parse(content) { ... //(no change here) } else { ... //(no change here) } } #create this Makefile cat <<'EOF' > Makefile APP=tidyjsonTest PROJECT_PREFIX=$(PWD) MODULENAME=TidyJSON OBJ_DIR=obj DEP_LIB_SRC_FOLDER1 = TidyJSON/Sources SWIFT_FILES = $(wildcard $(PROJECT_PREFIX)/$(DEP_LIB_SRC_FOLDER1)/*.swift) OBJ_FILES=$(addprefix, ./obj/, $(notdir $(SWIFT_FILES:.swift=.o))) testfile= $(PROJECT_PREFIX)/TidyJSON/Tests/Test.swift mainfile=$(PROJECT_PREFIX)/TidyJSON/Tests/main.swift all: $(APP) $(APP): $(testfile) $(mainfile) lib$(MODULENAME).a $(MODULENAME).swiftmodule ; \ swiftc -emit-executable $(testfile) $(mainfile) -o $(APP) -I. -L. -Xlinker lib$(MODULENAME).a ; lib$(MODULENAME).a: $(SWIFT_FILES) ; \ $(shell mkdir -p $(OBJ_DIR); cd $(OBJ_DIR); swiftc -parse-as-library -module-name $(MODULENAME) -emit-object $(SWIFT_FILES)) \ rm -f lib$(MODULENAME).* ; \ ar -rcs lib$(MODULENAME).a $(OBJ_DIR)/*.o ; $(MODULENAME).swiftmodule: $(SWIFT_FILES) ; \ rm -f $(MODULENAME).swiftmodule $(MODULENAME).swiftdoc ; \ swiftc -emit-module -module-name $(MODULENAME) -c $(SWIFT_FILES) -emit-module-path $(MODULENAME).swiftmodule -module-link-name $(MODULENAME) ; clean: ; rm -rf obj $(MODULENAME).swift* lib$(MODULENAME).* $(APP) .PHONY: all clean EOF # make then run to test make ./tidyjsonTest

To install docker, see this http://blog.hypriot.com/post/run-docker-rpi3-with-wifi/
The latest Kali Linux image for pentesting is here https://www.offensive-security.com/kali-linux-arm-images/



Swift 3.0 is out for Ubuntu 16 (Xenial Xerus)
see Raspberry Pi image for Ubuntu 16 here https://wiki.ubuntu.com/ARM/RaspberryPi


installation shell script    Select all
cd $HOME wget http://swift-arm.ddns.net/job/Swift-3.0-Pi3-ARM-Incremental/lastSuccessfulBuild/artifact/swift-3.0.tgz mkdir $HOME/swift-3.0 cd $HOME/swift-3.0 && tar -xzf ../swift-3.0.tgz export PATH=$HOME/swift-3.0/usr/bin:$PATH sudo apt-get update sudo apt-get install -y libicu-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 mkdir $HOME/hello; cd $HOME/hello swift package init --type executable swift build .build/debug/hello




Wednesday, January 6, 2016

What you need for Swift on Linux

What you need

(1) ubuntu-14.04.3-desktop-amd64.iso
http://releases.ubuntu.com/14.04/

(2) Virtual Box 5.0 from https://www.virtualbox.org/wiki/Downloads
Virtual Harddisk of 20G or above is recommended.

(3) Install clang in ubuntu 14
sudo apt-get update
sudo apt-get --assume-yes install clang-3.4 libicu-dev git vim

(4) download swift in ubuntu 14
curl -O https://swift.org/builds/ubuntu1404/swift-2.2-SNAPSHOT-2015-12-31-a/swift-2.2-SNAPSHOT-2015-12-31-a-ubuntu14.04.tar.gz
tar xzvf swift-2.2-SNAPSHOT-2015-12-31-a-ubuntu14.04.tar.gz
export PATH=$HOME/swift-2.2-SNAPSHOT-2015-12-31-a-ubuntu14.04/usr/bin:$PATH

(5) test compile
swift --version
echo 'print("Hello World")' > helloworld.swift
swiftc helloworld.swift
./helloworld

(6) remember to Insert Guest additions CD-image and reboot the virtual host.

(7) Test build
cd ${HOME}
git clone https://github.com/apple/example-package-dealer.git
cd example-package-dealer
swift build
.build/debug/Dealer

(8) Test build by adding swift package
shell script    Select all
cd ${HOME} mkdir -p teststring cd teststring cat > Package.swift <<EOF import PackageDescription let package = Package( name: "teststring", dependencies: [ .Package(url: "https://github.com/erica/SwiftString.git", majorVersion: 1), ] ) EOF cat > main.swift <<EOF import SwiftString let line = "apple,peach,kiwi" let parts = line.componentsSeparatedByString(",") print(parts) EOF swift build (cd Packages/SwiftString-1.0.5; git pull) swift build .build/debug/teststring


(9) Test build by adding C module
sudo apt-get install -y libcurl4-gnutls-dev libjson-c-dev
cd ${HOME}
git clone https://github.com/iachievedit/moreswift
cd moreswift/translator_swiftpm
swift build
.build/debug/translator "Hello" from "en" to "zh-cn"


(10) Test build by adding and modifying swift package
shell script    Select all
cd ${HOME} mkdir -p testdatestring/Sources/Test1 cd testdatestring cat > Package.swift <<EOF import PackageDescription let package = Package( name: "testdatestring", dependencies: [ .Package(url: "https://github.com/erica/SwiftString.git", majorVersion: 1), .Package(url: "https://github.com/haginile/SwiftDate.git", majorVersion: 1), ] ) EOF cat > Sources/Test1/main.swift <<EOF #if os(Linux) import Glibc import Foundation #endif import SwiftString import SwiftDate let start_date = Date(string: "2000-01-15") var end_date = Date(string: "2000-05-31") var actual_365 = Actual365Fixed() print(actual_365.dayCountFraction(start_date, date2: end_date)) EOF swift build (cd Packages/SwiftDate; ln -s SwiftDate Sources; echo "import PackageDescription;let package = Package(name: \"SwiftDate\")" > Package.swift) (cd Packages; mv SwiftDate SwiftDate-1.0.0) swift build (cd Packages/SwiftString-1.0.5; git pull) swift build


(10.1) Fix some errors in DateHelpers.swift
vim Packages/SwiftDate-1.0.0/SwiftDate/DateHelpers.swift    Select all
import Foundation import SwiftString ... extension String { //subscript (i: Int) -> String { // return String(Array(self.characters)[i]) //} subscript (r: Range) -> String { get { let subStart = self.startIndex.advancedBy(r.startIndex, limit: self.endIndex) let subEnd = subStart.advancedBy(r.endIndex - r.startIndex, limit: self.endIndex) return self[Range(start: startIndex, end: endIndex)] //return self.substringWithRange(Range(start: subStart, end: subEnd)) } }


(10.2) Fix error in Term.swift at line 195
vim +195 Packages/SwiftDate-1.0.0/SwiftDate/Term.swift    Select all
class func parseOneTerm(string : String) -> Term { let str = string.uppercaseString let len = str.characters.count let length = Int(str[0..<(len - 1)]) let timeUnit = str[len-1] switch timeUnit! { // unwrapped optional case "D": return Term(length: length!, timeUnit: TimeUnit.Day) case "W": return Term(length: length!, timeUnit: TimeUnit.Week) case "M": return Term(length: length!, timeUnit: TimeUnit.Month) case "Y": return Term(length: length!, timeUnit: TimeUnit.Year) default: return Term() } }


(10.3) Build target Test1
shell script    Select all
swift build .build/debug/Test1


(10.4) Add XCTest for target Test2
shell script    Select all
cd ${HOME}/testdatestring mkdir -p Sources/Test2 cat > Sources/Test2/main.swift <<EOF #if os(Linux) import Glibc import Foundation #endif import SwiftString import SwiftDate import XCTest class SwiftDateTesting: XCTestCase { var allTests : [(String, () -> Void)] { return [ ("testCalendar", testCalendar), ("testDayCounter", testDayCounter), ] } func testCalendar() { var cal = USSettlementCalendar() XCTAssert(cal.isBizDay(Date(string: "2014-05-15")) == true, "Pass") XCTAssert(cal.isBizDay(Date(string: "2014-05-17")) == false, "Pass") XCTAssertEqual(cal.nextBizDay(Date(string: "2014-05-16")).serialNumber, Date(string: "2014-05-19").serialNumber, "Pass") XCTAssertEqual(cal.bizDaysBetween(Date(string: "2014-05-15"), toDate: Date(string : "2014-05-20")), 3, "Pass") } func testDayCounter() { var start_date = Date(string: "2000-01-15") var end_date = Date(string: "2000-05-31") var actual_365 = Actual365Fixed() XCTAssertEqual(actual_365.dayCountFraction(start_date, date2: end_date), 137.0 / 365, "Pass") var nl_365 = NL365() XCTAssertEqual(nl_365.dayCountFraction(start_date, date2: end_date), 136.0 / 365, "Pass") var act_360 = Actual360() XCTAssertEqual(act_360.dayCountFraction(start_date, date2: end_date), 137.0 / 360.0, "Pass") var thirty_360 = Thirty360() XCTAssertEqual(thirty_360.dayCountFraction(start_date, date2: end_date), 136.0 / 360.0, "Pass") var thirty_360e = Thirty360(convention: Thirty360.Convention.EurobondBasis) } } XCTMain([SwiftDateTesting()]) EOF swift build .build/debug/Test2