Table of Contents
- 0.0.1. Config emacs from command line
- 0.0.2. Found a bug on word search algorithm
- 0.0.3. C99: initialize array with struct object
- 0.0.4. Apache: list file and directories in web server
- 0.0.5. XCode: rename Xcode project
- 0.0.6. Haskell Module commands, Run Haskell script, kind of
- 0.0.7. Canadian team lost to Costa Rica: 0 vs 1
- 0.0.8. Interview question: Find the minimum and the second minimum from a list
- 0.0.9. Maximum two integers
- 0.0.10. Haskell install GLURaw in Ubuntu (Saturday, 26 March 2022 01:03 PDT)
- 0.0.11. The war is on Russia vs Ukraine
- 0.0.12. Run Python script in Blender
- 0.0.13. Blender Scripting
- 0.0.14. Visited Surrey and Langley in BC
- 0.0.15. Visited Coquitlam Center (Indoor shopping mall with rustic touches)
- 0.0.16. Game is on, World Cup Qualifer: Canada vs El Salvador, Canada won again El Salvador 2-0
- 0.0.17. Link data to Beds24 from Expedia
- 0.0.18. Canada VS USA World cup qualifier Today, it is big game but there is NO live stream online.
- 0.0.19. How to get free signed certicate on your site for HTTPS
- 0.0.20. Happstack installation for web server
- 0.0.21. Fixed alias conflic in Shell. How to check alias conflic in Shell
- 0.0.22. ctags and etags
- 0.0.23. Update printBox codein Haskell
- 0.0.24. Added colorfgStr and colorbgStr in AronModule.hs
- 0.0.25. Latex special character
- 0.0.26. OpenGL GLSL
- 0.0.27. Window manager on MacOS
- 0.0.28. Reduce png file to smaller size
- 0.0.29. Split PDF file into pages
- 0.0.30. Fixed Intuo Tablet issue. Wacom driver does not work in Big Sur in the first time installation
- 0.0.31. Mutt: Setup Mull for Gmail, the following setting is in MacOS Big Sur 11.5.2
- 0.0.32. Mutt: Send email from command line as a backup tool
- 0.0.33. MacOS: Enable ssh login at startup in MacOS
- 0.0.34. Haskell: Finally fixed Ghci error on macOS Big Sur 11.5.2
- 0.0.35. Emacs: Emacs 28 has a bug in orgmode
- 0.0.36. Haskell raw string Text.RawString.QQ and NeatInterpolation are useful for Html, Sql and Regular expression.
- 0.0.37. There is issue when stack build WaiLib.hs
- 0.0.38. Added Javascript to edit code block
- 0.0.39. MacOS automatically update screws up tmux
- 0.0.40. Haskell show, print and putStr or putStrLn
- 0.0.41. Add wai-uil to wai.hs Server for redirecting response URI
- 0.0.42. Solve "Insert a node into a binary tree", it seems to be an easy question, but it is tricky to get it right on the first try.
- 0.0.43. DONE Hair cut
- 0.0.44. DONE Added three buttons: add, update and delete to wai.hs
- 0.0.45. DONE Do my laundry
- 0.0.46. DONE Install Vim 8.1.135, and fix symbol link with the Vim syntax.vim file error
- 0.0.47. DONE Try to understand Visitor pattern in Java and Haskell Algebraic Datatypes
- 0.0.48. DONE Add Redirect response to wai.hs with wai-uti
- 0.0.49. DONE pushall respositories to bitbucket
- 0.0.50. DONE fix resume a bit
- 0.0.51. TODO Need to add more detail to resume
- 0.0.52. TODO Buy a new pot and buy some rice
- 0.0.53. DONE Open new paypal account
- 0.0.54. DONE Add color to wai.hs to highlight the current edited code block
- 0.0.55. DONE Send out more resumes
- 0.0.56. TODO Do some java coding
- 0.0.57. TODO Take a look at the Algebraic Data Type and Visitor pattern in Java
- 0.0.58. DONE Send out more resume, more to EA
- 0.0.59. DONE Add Applescript to send notification when filewatcher detects some txt file inside password folder.
- 0.0.60. Agda: Agda can not compile Hello World
- 0.0.61. Agda: Finally figure out how to use multiple putStrLn in Agda
- 0.0.62. Agda: What is Costring?
- 0.0.63. Agda: write string to file writeFile, same as Haskell
- 0.0.64. Agda: read file and print a string in Agda
- 0.0.65. Agda: write a string to file in Agda. It is painfully hard.
- 0.0.66. Agda: What is Corecursion?
- 0.0.67. Agda: Set Agda input in other mode such as org-mode
- 0.0.68. Agda: Defind record in Agda
- 0.0.69. Agda: record example 2, use mixfix operator
- 0.0.70. Agda: Emacs Org-mode DOES NOT support code block highlight for Agda.
- 0.0.71. Agda: Encode nature with binary bitstring
- 0.0.72. DONE Refactor filewatcher.hs, remove IORef, clean up useless code
- 0.0.73. DONE Added double click event:
ondblclick
to javascript file insidewai.hs
to improve user experience. - 0.0.74. DONE Finished Osense intervew take-home assignment.
- 0.0.75. Heap sort, definition, space complexity, runtime
- 0.0.76. Change background color in org-mode
- 0.0.77. DONE Wrote a shell script to simplify gcc compilation process.
$scr/gcc_compile.sh
- 0.0.78. DONE Fixed an issue where is special characters are not escaped properly.
- 0.0.79. DONE Xencall call HR interview
- 0.0.80. I worked on an application to generate report for accounting department in EU.
- 0.0.81. In VoiceBox Inc.
- 0.0.82. iOS development
- 0.0.83. DONE Interview with expa.com
- 0.0.84. DONE Implement Eight Queens problem in Haskell
- 0.0.85. DONE Added code: Post Html form, and retrieve data from Html Input box, insert data to Sqlite-simple DB.
- 0.0.86. DONE Added code: Integrate Sqlite-simple to wai.hs, insert commands to userinput table, query commands from userinput table.
- 0.0.87. DONE Refactored code: Clearn up some unnecessary code.
- 0.0.88. DONE A guy asks me to meet as Benze Coffee around Hamilton St. and Helmcken St. from a company called Linquet.com
- 0.0.89. DONE Integrate Ajax to wai.hs, send Json data to Server, and get response from Server in client side.
- 0.0.90. DONE I has an interview with Xencall today.
- 0.0.91. DONE Interview with a company called Impact Recruitment last Friday.
- 0.0.92. OpenGL: Download Vertex Buffer Object(VBO) and play around it.
- 0.0.93. OpenGL: Vertex and Fragment Shader
- 0.0.94. OpenGL: Replace gluPerspective with glFrustrum in OpenGL
- 0.0.95. OpenGL: What is glutReshapeFunc in OpenGL GLUT
- 0.0.96. OpenGL: gluLookAt function
- 0.0.97. OpenGL: gluLoadIdentity
- 0.0.98. DONE Interview with Eletronic Art.
- 0.0.99. DONE Implement Javascript editor with CSS.
- 0.0.100. I have onsite interview today with EA, I will meet a technical director Jun Wang and Kelly Tainton and Aron Brown and Chris Olson.
- 0.0.101. Today, I try to include some or import some functions from Javascript to html file, but it is so tricky I still have no idea how to do it.
- 0.0.102. DONE Handle Second request from the first request in Haskell Wai API.
- 0.0.103. Interview with Amdoc today and I have no idea what to expect from them.
- 0.0.104. Work on an App to take all the pdf file from a directory and display its names on browser.
- 0.0.105. Install some Emacs Themes from Emacs Theme Gallery today.
- 0.0.106. Add GenePDFHtml.hs to bitbucket as repos. GenePDFHtml
- 0.0.107. Add GenePDFHtml.hs to Wai.hs Server
- 0.0.108. Ubuntu: sshd test mode
- 0.0.109. Ubuntu: fixed ssh can not be connected
- 0.0.110. Ubuntu: Check ssh status
- 0.0.111. Ubuntu: Install Haskell Platform inside Ubuntu VM and realize it is 8.0.x version.
- 0.0.112. Ubuntu: Finally AronModule can be built in Ubuntu with Stack, it is not true, there is still issue with regex-tdfa out of memory in my Ubuntu vm.
- 0.0.113. Ubuntu: Add RSA keys to Ubuntu and FreeBSD hosts, Public key, ssh public key, ssh key
- 0.0.114. Ubuntu: Add shell script to upload file to Ubuntu and FreeBSD hosts
- 0.0.115. Ubuntu: GHC run out of memory in Ubuntu 1G RAM GHC out of memory
- 0.0.116. Ubuntu: Change web host from Ubuntu 1G to FreeBSD 3G
- 0.0.117. Ubuntu: Add user to Ubuntu
- 0.0.118. Ubuntu: Add user to sudo file
- 0.0.119. Ubuntu: Install Haskell Platform
- 0.0.120. Ubuntu: Install Haskell Stack
- 0.0.121. Ubuntu: Install Apache Server
- 0.0.122. Stack will not always solve problems for you.
- 0.0.123. Why your public key not working in Github: Error Permission denied (publickey)
- 0.0.124. Remove IP Address from our SSH, ssh-keygen
- 0.0.125. Bought a FreeBSD VM 3G, 60G from Digit Ocean for $15.
- 0.0.126. FreeBSD install package
- 0.0.127. FreeBSD apache html folder
- 0.0.128. FreeBSD install GHC
- 0.0.129. Rename haskellwebapp \( \Rightarrow \) haskellwebapp2
- 0.0.130. Mysql example
- 0.0.131. Mysql Regex
- 0.0.132. Mysql batch insert
- 0.0.133. Mysql Yep, you can merge two Mysql tables
- 0.0.134. Sqlite3 Primary Key and Foreign Key
- 0.0.135. Create User and Image tables in Sqlite3 database.
- 0.0.136. Haskell Sqlite3, Simple Example to show how to connect to database, create table, insect data, create record, map record to table.
- 0.0.137. Add login and password validation page.
- 0.0.138. Word8 and ByteString in Haskell.
- 0.0.139. C++ Dangling pointer Dangling Pointer
- 0.0.140. What is unique pointer, shared pointer and weak pointer and what is std::move in C++
- 0.0.141. Change all paths in WaiLib.hs and Wai.hs, and it run in FreeBSD so far.
- 0.0.142. In FreeBSD,
/usr/ports/database
is not shown. - 0.0.143. Install Redis in FreeBSD Redis installation on FreeBSD
- 0.0.144. Haskell Enum Trick Enum Trick
- 0.0.145. Show Maybe is a Functor Functor Maybe Proof
- 0.0.146. Haskell: Applicative and Functor
- 0.0.147. Move GenePDFHtml to WaiLib.hs file, Create a GenePDFHtmlLib in $b/haskelllib
- 0.0.148. Refactor function in WaiLib
- 0.0.149. Change Emacs Org-mode with solarized theme with CSS file Emacs Org-mode Solarized Theme
- 0.0.150. Change the width of center theme on the current theme.
- 0.0.151. Add install.sh to each stackproject project
- 0.0.152. Change default shell in FreeBSD change shell
- 0.0.153. Non-interactive shell and interactive shell, login shell, non-login shell.
- 0.0.154. Use interactive shell to store all your shell script command in history
- 0.0.155. Add new
tmux.conf
file for FreeBSD. Apparently thetmux.conf
file is not working on MacOS. - 0.0.156. Fixed: Javadoc long term error: can not find methods. Javadoc Reference Guide
- 0.0.157. Add iterate all files from dir and insert them into table: test1.snippet
- 0.0.158. Add isFile and isDir to javalib AronLib.java
- 0.0.159. Database ACID
- 0.0.160. Fixed bug: send pdf file to browser and force the browser to open it. What request header I should use?
- 0.0.161. Add code to display all PDF files from a directory in Wai Server.
- 0.0.162. Wai API for query string, it is nice function to match string from client
- 0.0.163. Understand logic implication table
- 0.0.164. Why Lombok sucks? please read the Reddit Lombok in Reddit
- 0.0.165. Haskell code to generate latex code tryfm.hs
- 0.0.166. Anonymous function in c++ and Lambda function in Haskell.
- 0.0.167. C++ return by reference or return by value.
- 0.0.168. Return by reference or const reference
- 0.0.169. Passed by value and reference or const reference
- 0.0.170. Find the square root of a float point number: \(n\)
- 0.0.171. Find the nth root of a float point number: \(c\)
- 0.0.172. Change the file GenePDFHtml.hs file, but it can not be built any more.
- 0.0.173. Haskell record is function essentially
- 0.0.174. How to check whether there a table exist in Sqlite in Haskell.
- 0.0.175. Haskell Database connection code in three databases: Sqlite, Mysql and Postgresql
- 0.0.176. Fixed error inside javadoc script with -classpath
- 0.0.177. Xcode: gcc clang c++ compiler flags, cpp compile, xcode compiler: Reference
- 0.0.178. CPP install boost on MacOS
- 0.0.179. CMake: add include header, add shared libraries (MacOS, CMake –version 3.7.1)
- 0.0.180. Share local directories in Apache or Virtual Directory in Apache
- 0.0.181. Wrote a simple function to remove whitespaces from file names and directories.
- 0.0.182. Python Random
- 0.0.183. Python does not have block comment?
- 0.0.184. Python file modification timestamp
- 0.0.185. Python import your own module in Python in Jupyter Lab
- 0.0.186. Python Sort objects in Python
- 0.0.187. Python sort string
- 0.0.188. Python byte string and normal string or utf-8 string
- 0.0.189. Python has \(\text{red}{stolen}\) many good stuff from other function programming language such as Haskell
- 0.0.190. Python List comprehesion is nice feature in Python. It is very similar like Haskell List Comprehension
- 0.0.191. PYthon Why Python map, filter and reduce or fold are unusual in Python?
- 0.0.192. Python There are many nice features in Python
- 0.0.193. Python read Json file
- 0.0.194. Python virtualenv installation, create project
- 0.0.195. Complex number division
- 0.0.196. I just learn Complex number has something called rectangular form which is the standard form that is used in high school.
- 0.0.197. Apparently, Haddock does not generate the right index.html file with many Haskell modules.
- 0.0.198. VSCode has autocomplete out of the box. Is works for java at lease. It seems to me VSCode is can be replaced Vim and Emacs soon.
- 0.0.199. VSCode. Finally I found out how to add your own jar file to VS Code
- 0.0.200. VSCode Cpp/C++/clang++/g++ development in MacOS
- 0.0.201. Try to install setup VSCode for Haskell right now.
- 0.0.202. Haskell Intero for Emacs.
- 0.0.203. An 64 years old math problem is solved by a super computer.
- 0.0.204. Terence Tao and Collatz Conjecture
- 0.0.205. Java boxing and unboxing
- 0.0.206. Apple finally was unveiling iPhone 11, iPhone 11 Pro and iPhone 11 Pro Max without 5G cellular service.
- 0.0.207. It is almost impossible to clear up browser data from Google Chrome.
-
- 2.0.1. Install Common Lisp on MacOS
- 2.0.2. Run your lisp script from command line
- 2.0.3. Emacs Elisp Grab the content of buffer
- 2.0.4. Emacs Elisp write to scratch buffer
- 2.0.5. Emacs Elisp call-process
- 2.0.6. Emacs Elisp run elisp in specific path
- 2.0.7. Emacs ELisp Atom
- 2.0.8. Emacs Elisp quote
'
is function - 2.0.9. Emacs Elisp self-evaluating form
- 2.0.10. Emacs Elisp Create a list with list function
- 2.0.11. Emacs ELisp Symbol
- 2.0.12. Emacs Elisp Hello World
- 2.0.13. Emacs Elisp get buffer name, full path name
- 2.0.14. Emacs Elisp kill a buffer by name
- 2.0.15. Emacs Elisp get all buffer names
- 2.0.16. Emacs Elisp switch to other buffer
- 2.0.17. Emacs Elisp data type:
- 2.0.18. Emacs Elisp evaluate body forms sequentically and return value of last one, execute multiple statements
- 2.0.19. Emacs Elisp define a function
- 2.0.20. Emacs Elisp set global variable
- 2.0.21. Emacs Elisp mapcar
- 2.0.22. Emacs Elisp filter, haskell like filter, filter from dash.el
- 2.0.23. Emacs Elisp car and cdr
- 2.0.24. Emacs Elisp assoc and associative list or alist
- 2.0.25. Emacs Emacs format string or convert a list to string
- 2.0.26. Emacs Elisp switch to other buffer
- 2.0.27. Emacs Emacs url or file name under cursor
- 2.0.28. Emacs Elisp insert string in cursor
- 2.0.29. Emacs Elisp open file in a buffer with
find-file
- 2.0.30. Emacs Elisp Get element from a list
- 2.0.31. Emacs Elisp Get the current line string, current string
- 2.0.32. Emacs Elisp Get cursor line number
- 2.0.33. Emacs Elisp run shell command function
- 2.0.34. Emacs Elisp Goto line
- 2.0.35. Emacs Elips Goto column
- 2.0.36. Emacs Elisp replace match regex
- 2.0.37. Emacs Elisp Get current word under cursor
- 2.0.38. Emacs Elisp Get the current word bounds under cursor
- 2.0.39. Emacs Elisp Repeating Timer, emacs timer
- 2.0.40. Emacs Elisp Regex, remove last directory from a string
- 2.0.41. Emacs Elisp Change shell environment variable to exec-path-from-shell-getenv
- 2.0.42. Emacs Elisp substring in elisp
- 2.0.43. Emacs Elisp split window horizontically and vertically
- 2.0.44. Emacs Elisp Delete other window, maximize current window.
- 2.0.45. Emacs Emacs Get File name under cursor, print file name under cursor
- 2.0.46. Emacs Elisp Open file under cursor.
- 2.0.47. Emacs Elisp define an alias in Emacs
- 2.0.48. Emacs Elisp Elisp ampersand rest in a function argument
- 2.0.49. Emacs Elisp If condition else then
- 2.0.50. Emacs Elisp Compare string
- 2.0.51. Emacs Elisp Emacs read file, write to file, append to a file
- 2.0.52. Emacs Elisp Compare String in Elisp
- 2.0.53. Emacs Elisp Compare Objects in Elips
- 2.0.54. Emacs Elisp Execute elisp script in your buffer with C-x C-e
- 2.0.55. Emacs Elisp Split current line
- 2.0.56. Emacs Elisp Fibanacci Number
- 2.0.57. Emacs Elisp power function in Elisp, it is not (^) why?
- 2.0.58. Emacs Elisp Convert list to string
- 2.0.59. Emacs Elisp concat string mapconcat or fold
- 2.0.60. Emacs Elisp: highlight word under cursor and unhighlight word under cursor
- 2.0.61. Emacs Elisp: run shell command in whole buffer
- 2.0.62. Emacs Elisp: concat two lists
- 2.0.63. Emacs Elisp: Space does it matter in Elisp
- 2.0.64. Emacs Elisp: What is dot in Elisp
- 2.0.65. Emacs Elisp: hashtable, insert key, remove key
- 2.0.66. Emacs Keybind: jump backward from defintion in Haskell Intero in .eamcs
- 2.0.67. Emacs PATH and exec-path for executable files.
- 2.0.68. Emacs environment variable, getenv and exec-path-from-shell-getenv
- 2.0.69. Emacs Change default directory in Emacs
- 2.0.70. Emacs Orgmode manipulate table
- 2.0.71. Emacs Regex, Emacs Regular Expression, Vim Regular Expression
- 2.0.72. Emacs: Search and Replace, Why Emacs sucks on that.
- 2.0.73. Emacs: Move cursor to the beginning of non-whitespace and move the cursor to the first column of a line
- 2.0.74. Emacs: Insert tab in front of a line, function name, binding to M-i
- 2.0.75. Emacs: customize theme
- 2.0.76. Bitbucket use App password for git
- 2.0.77. Self-signed certificate
- 2.0.78. Install Rabbit Message Queue in FreeBSD
- 2.0.79. Install RabbitMQ in MacOS
- 2.0.80. Rabbit Message Queue from Pivotal
- 2.0.81. realtor.com Interview question
- 2.0.82. Evil is not a perfect solution for Vim users.
- 2.0.83. Intero and Stack are both not working suddenly
- 2.0.84. Create a UI to display data for code snippet
- 2.0.85. Add markdown mode to Emacs or GFM mode for Github README.md
- 2.0.86. Change PDF file background color to different colors, PDF reader, pdf background.
- 2.0.87. Java: extends and super keywords (07-11-2019)
- 2.0.88. Java: JShell is nice feature because it learns from Python or Haskell.
- 2.0.89. JShell load script to JShell, it is better than Haskell
- 2.0.90. The difference among align, align* and aligned, they are all in math mode.
- 2.0.91. Fixed copy text to clipboard with click button in Wai Server. (13-11-2019)
- 2.0.92. Modulus for a ring, addition and multiplicaton
- 2.0.93. Try to Remove all commands from $b/stackproject/filewatcher and run it see still got the error message.(15-11-2019)
- 2.0.94. English words: modulus, module, modular, moduli, modulo, modulate (15-11-2019)
- 2.0.95. Polynomial, degree of polynomial.
- 2.0.96. In Java, negative and positive infinity are defined. I never realize that.(15-11-2019)
- 2.0.97. Rename vimlatex.sh to latexsync.sh, add symbol link latexsync.sh
- 2.0.98. latexmk automatically compile file and reload pdf automatically
- 2.0.99. Add operators to javapolynomial: negate, subtract, inverse, divide and test cases.(19-11-2019)
- 2.0.100. Algebraic Data Type and Calculus
- 2.0.101. Intellij wrong java compiler, Intellij class file has wrong version error.
- 2.0.102. Intellij keymap file location on MacOS.
- 2.0.103. Intellij Make Vim like keymapping
- 2.0.104. Intellij code template or snippet location on MacOS, Symbol link to bitbucket/intellij
- 2.0.105. Intellij Add classes and jar file to libraries
- 2.0.106. XML speical characters '<', '>', '\'', '"', '&'
- 2.0.107. Convert snippet to Intellij code template in Haskell
stackproject/IntellijSnippet
- 2.0.108. Haskell pretty print library. pretty-simple
- 2.0.109. Haskell FFI: How to pass a pointer to a function
- 2.0.110. Haskell FFI: Stack project for FFI
- 2.0.111. Haskell Unicode regex error, "illegal byte sequence" error
- 2.0.112. Haskell bracket example from Snoy Man
- 2.0.113. Add stackproject Haskell FFI C my lib file.
- 2.0.114. Convert C function signature to FFI with C2HS tool, example(26-11-2019)
- 2.0.115. Move CodeAnalysis to
$b/cmake
folder.(23-11-2019) - 2.0.116. Add some C funciton to my C library(26-11-2019)
- 2.0.117. Zathura PDF latex viewer, it is Vim style PDF Viewer
- 2.0.118. Joseph problem
- 2.0.119. Install ghc-mod is painful on MacOS.
- 2.0.120. Nice emacs setup Site
- 2.0.121. New Vim Command in insert mode, I never know that before.
- 2.0.122. Vimscript list or array
- 2.0.123. Vimscript pesado-variable(I never hear the name pesado-variable in Vim)
- 2.0.124. Vim
:g
or:global
range search, it is very powerful - 2.0.125. Some crazy Vim tips from someone
- 2.0.126. Pandoc convert Latex to Html, Haskell literate to Html
- 2.0.127. history command is not working inside shell script
- 2.0.128. Write a few functions to align columns in Vimscript(07-12-2019)
- 2.0.129. Add some test cases for Vimscript functions. And it works well so far.(07-12-2019)
- 2.0.130. Fixed a bug in haskellwebapp2, colorize some wrong tokens or keywords with regex.
- 2.0.131. Haskell define dynamic function with Map
- 2.0.132. Check ghci memory leak
- 2.0.133. Emacs Auctex Latex autocomplete Environment, Section and Macro.
- 2.0.134. Emacs still can not resolve environment variables, add one function to some hassle.
- 2.0.135. Emacs can do lots of math
- 2.0.136. Emacs: Jumping back and forth is stupidly painful in Emacs.
- 2.0.137. Sometimes Emacs does not reload file with
load-file
, you need tokill-buffer
and reopen the file. - 2.0.138. Shell Script:
/etc/profile
source/.bashrc
, currently it works so far. - 2.0.139. Bash shell keybinding or key mapping. Map your F7 key to run a shell script.
- 2.0.140. Bash shell keypress event
- 2.0.141. Shell Script: alias does not expand inside shell script because alias DOES NOT expand in non-interative shell
- 2.0.142. Shell Script: true and false are both shell command, I never know that
- 2.0.143. Shell Script: pass string with newline to argument in Shell
- 2.0.144. Org-mode and GNU-APL mode, input GNU-APL char inside org-mode
- 2.0.145. Install APL inside your Emacs.(I'm a MacOS)
- 2.0.146. Install J programming language
- 2.0.147. Fixed the whitespace issue in the header of block code, e.g. trim whitespace in the header of block code
- 2.0.148. Nice Javascript text editor call
editorjs.io
is pretty good, demo at the following - 2.0.149. Javascript: Insert script tag into Html Body or Header
- 2.0.150. Javascript: Insert class into tag such div, pre etc
- 2.0.151. Javascript: select text range from TextArea with selection.(15-11-2019)
- 2.0.152. Javascript: Javascript Object to json, access json elements
- 2.0.153. Javascript: web storage API, it only works when open localhost or Http protocol. it does not work in local file system in Chrome.
- 2.0.154. Javascript: Try to put all editorjs.io javascript editor and Katex together and render Katex in realtime.
- 2.0.155. Javascript: Add data to Div Element, textContent and innerHTML
- 2.0.156. Javascript: Found a unbalanced head tag in HTML code. I think it causes the Katex rendering issue.(16-12-2019)
- 2.0.157. Javascript: It is surprisedly hard to copy partial text from TextArea to clipboard in Javascript
- 2.0.158. Javascript: The order of
<script>code</script>
and Html code are important in Javascript. - 2.0.159. Javascript: Lambda function
- 2.0.160. Javascript CSS, Modify CSS style value/attribute
- 2.0.161. Javascript call function after page is loaded
- 2.0.162. Proof logarithm \(\log a^x a^y = \log a^x + \log a^y\)
- 2.0.163. Proof function injectivity, subjectivity and composition
- 2.0.164. Katex and MathJax support commends, environment and functions but they have table problem.
- 2.0.165. Latex: The difference between
$ $
$$ $$
\[ \]
and\( \)
- 2.0.166. Latex install package, latex package, install latex package
- 2.0.167. Install Ace9 to my localhost
saved-data-example/example.html
, javascript editor - 2.0.168. Install Vim keybinding in ACE9 editor, all you need is one line of Javascript code.
- 2.0.169. Fix dotemacs file contains stupid error with two functions with different values
- 2.0.170. C programming: malloc and free, free DOES NOT mean pointer is NULL
- 2.0.171. C programming: return pointer from a function
- 2.0.172. C programming: memcpy copy string
- 2.0.173. C programming: mutate parameter in a function, ampersand in C, NOT C++
- 2.0.174. C programming: define node using struct, linked list node
- 2.0.175. C Programming: Three are three ways to dynamic allocate memmory
- 2.0.176. C Programming: C struct and typedef
- 2.0.177. C Programming: Check type such as
int, float, double, char, long
or struct size - 2.0.178. C Programming: const char *pt and char *pt
- 2.0.179. Redefine command line in Vim with following script
- 2.0.180. Vim tips: filter out line with new open window
- 2.0.181. Vim tips: Insert spaces in font of selected lines
- 2.0.182. Vim tips: call function in visual selected lines, function with range
- 2.0.183. TODO Move all the haskell file to
$hlib
in $b/haskellwebapp2 - 2.0.184. TODO Try this code Copy and paste
- 2.0.185. TODO Emacs: universal-argument, What the hell is universal-argument?
- 2.0.186. MacOS: Screen Capture with screencapture command
- 2.0.187. Change haskell document background color from dark mode to light mode
- 2.0.188. Haskell some cursor movement and ANSI console color
- 2.0.189. Customized Latex Input Method or TeX Input Method in Emacs
- 2.0.190. iTerm2: iTerm2 profile can be saved in your local folder
- 2.0.191. iTerm2: Import profile (JSON) file to your iTerm2
- 2.0.192. iTerm2: Fixed tmux and iterm2 problem: backspace key DOES NOT work in
- 2.0.193. iTerm2: trigger regex, color highlight in iTerm2
- 2.0.194. tmux: fixed copy-mode-vi use 'v' to select text and 'y' to copy text in tmux
- 2.0.195. Haskell: just learn something new today, you can use read function to read a list of type, e.g
[1, 2, 3]
- 2.0.196. Java doc: use latex for Java document with java doclet
- 2.0.197. Java: When to pass Iterator or List inside your recursion code
- 2.0.198. Microsoft Phone call interview for Large scale service and distribution system
- 2.0.199. Java: I just learned in Java 9 there is something called Module
- 2.0.200. English: coercion [kəʊ'ɜʃən]
- 2.0.201. Elips: I struggle to figure out how to run Graphviz or dot file under Org-mode in code block
- 2.0.202. Haskell: conversion between numbers, Float to Int, Double to Int, Float to Integer
- 2.0.203. Math: Geometric Proof \( \sin{2\theta} = 2\sin{\theta} \cos{\theta} \)
- 2.0.204. Jupyter: For Haskell and Python or ihaskell like Python Jupyter lab
- 2.0.205. Haskell: Mutable array, Haskell Array
- 2.0.206. Java: Integer can be 10x slower than int
- 2.0.207. Java: Initialize
int[]
andInteger[]
in Java - 2.0.208. Java: QuickSort to Kth smallest element
- 2.0.209. MacVim: Render unicode or emoji issue in MacVim,
- 2.0.210. Coin and Coding theory
- 2.0.211. Edit String Distance Algorithm: find the minimum weight to convert string \(s_1\) to \(s_2\) in dynamic programming
- 2.0.212. \(\LaTeX\) What I learn in Latex today
- 2.0.213. \(\LaTeX\) What I learn today?
- 2.0.214. \(\LaTeX\) Color Your mathematic formulas.
- 2.0.215. Excel Column Header: algorithm in Java.(15-11-2019)
- 2.0.216. Interview question: Print Excel column header pattern
- 2.0.217. Interview: Partition array
- 2.0.218. Tmux: you can switch window id number between two windows
- 2.0.219. Command Line: copy and paste on MacOS, copy to clipboard and paste from clipboard
- 2.0.220. Preorder Iterator
- 2.0.221. Emacs Elisp What I learn from Emacs today? I'm always wondering how to move around without pressing the CTRL key
- 2.0.222. Emacs Reload dotemacs file is not necessary to reload everything, Use kill-buffer after reload dotemacs
- 2.0.223. Elisp Good tutorial to learn lisp
- 2.0.224. Elisp Unicode can be the name of function, factorial function
- 2.0.225. Haskell: createProcess in Haskell error
- 2.0.226. Interview partition a binary array to three parts and they all have the same binary values. (Youtube Netflix interview) You Tube
- 2.0.227. Java compile java file, Run Java, make Java Executable, Jar file
- 2.0.228. Greek Letters
- 2.0.229. Differential Geometry Note
- 2.0.230. Derivative of \( \sin{\theta} \) and \( \cos{\theta}\)
- 2.0.231. Derive the length of 2D dimension curve.
- 2.0.232. Haskell: Learn how to use parser which is parsec package
- 2.0.233. Apparently Java random number generator (Math.random()) use very simple algorithm: linear congrential formula
- 2.0.234. There is very weird random number result that I got today in Java
- 2.0.235. Git tutorial
- 2.0.236. Git What is rebase
- 2.0.237. Write code to solve following problem, Article Ltd. interview question in Hackerrank
- 2.0.238. XCode code sign or XCode sign is painful. Apple tries to ask you to pay them for nothing.
- 2.0.239. XCode: update to MacOS Catalina 10.15.3 and XCode to 11.3, my cpp library is broken
- 2.0.240. MacOS Error:
- 2.0.241. Group Representation Theory
- 2.0.242. Virtual Proof of Pythagorean Theorem, and rotate matrix or rotate array in 90 degrees
- 2.0.243. What to do next?
- 2.0.244. Haskell run inline javacode
- 2.0.245. GHC many good plugins
- 2.0.246. Add test file to Haskell Stack
- 2.0.247. Haskell stack test error
stack test
. Finally I fixed the stupid error/opt/local/bin/strip
- 2.0.248. Haskell stack file watch
- 2.0.249. Haskell NonEmpty list from package Data.List.NonEmpty
- 2.0.250. Neovim can use
vimrc
file with following commandnvim
- 2.0.251. Add Python code template to generatecode.hs file.
- 2.0.252. Python: GUI, Kivy is pretty impressive GUI for Python.
- 2.0.253. Python: Generate source code color highlight with Pygmentize
- 2.0.254. Python: Install Jedi package in Emacs for autocomplete, there is some issues on virtualenv error. (28-01-2020)
- 2.0.255. Python: draw binary tree with Python
- 2.0.256. Python Version Hell:) python3 numpy can not be found in MacOS Catalina
- 2.0.257. Python import package in full path? why?
- 2.0.258. XCode error, Swift 5 using wrong SDK on MacOS
- 2.0.259. XCode how to edit your scheme in XCode, manage scheme, xcode scheme
- 2.0.260. Haskell ReaderT best explanation Tom and Jerry Example
- 2.0.261. Haskell (->) r is a Functor, best explanation
- 2.0.262. Sqlite3 Java insect, select, update batch insection
- 2.0.263. Fixed issue in bitbucket javascript folder. You thought you have checkined your code, but it is not.
- 2.0.264. The Good and Bad of Nodejs and Eletronjs
- 2.0.265. Haskell, monad binding operator:
=<< >>=
- 2.0.266. Python startup file, Yep, Python does not have startup file like bashrc
- 2.0.267. Install Node error,
brew install node --without -npm
- 2.0.268. Emacs Elisp: autocompelte
completing-read
- 2.0.269. OpenGL Haskell: Fixed GLFW, GLFW-b and bindings-GLFW issues in OpenGL in Haskell
- 2.0.270. What I have done so far.
- 2.0.271. Binary Search Duplicate element in an array
- 2.0.272. Download MacVim and install it, does not work so far, can not build..
- 2.0.273. Fixed very stupid bug in haskellwebapp2 because Javascript ondblclick does not work suddenly
- 2.0.274. The best explanation for Projective Geometry
- 2.0.275. Fixed error on groupBy method in Java library
Aron.java
- 2.0.276. Rename a domain name.26-05-2020
- 2.0.277. New code to find the maximum element from a sorted rotated array
- 2.0.278. Run ghci like command line in Shell
- 2.0.279. CMake is hard, why it so complicated to write a build script
- 2.0.280. Git add submodule and delete submodule
- 2.0.281. Load script in Julia
julia
- 2.0.282. Run Julia and Jupter notebook
- 2.0.283. Julia: Pkg is not found, You need to use
using Pkg
first - 2.0.284. PDF keyword search tool rga
- 2.0.285. Write Latex on MacOS
- 2.0.286. haskllwebapp2 project: move Javascript and CSS file to js and css folder
- 2.0.287. Home Brew Install gsed or gnu-sed, not sure there is any different between them
- 2.0.288. Why ssh is stupid? What is
known_hosts
and what isauthorized_keys
- 2.0.289. Move
haskellwebapp2 image
tobitbucket/image
, nothing is impressive. - 2.0.290. Try to use HaskeLine package to do some console input line stuff. 15-06-2020
- 2.0.291. Egison and pattern match.
- 2.0.292. Serialize Binary Tree and Preorder traveral and parse prefix expression
- 2.0.293. There is no color in org-mode and I just realize I need a package called *Hmltize"
- 2.0.294. Haskell: understand newtype State s a = State{runState::s -> (a, s)}
- 2.0.295. Nano parser: Here is the full code for nano parser from Stephen Diehl
- 2.0.296. Check MacOS Idle time, this will tell you how long it's been since you the mouse or a keystroke was pressed.
- 2.0.297. What is Identity functor in Haskell, Here is the discussion in SO
- 2.0.298. Use Emacs elisp as script language in command line
- 2.0.299. Delete maximum or minimum node in a Binary Search Tree is non trivia task.
- 2.0.300. Python Hell, pip3, pip3.7 and pip3.8 \(\Rightarrow\) python, python3.7 python3.8
- 2.0.301. Java Optional, isPresent, get
- 2.0.302. Jacobian Matrix, What is Jacobian Matrix? When to use Jacobian Matrix? What is the simplest form of Jacobian Matrix
- 2.0.303. Found a bug there has been in the code for many years.
isBST
- 2.0.304. Why it is so hard to figure What is JAVAHOME in your MacOS (21-07-2020)
- 2.0.305. Groovy connect to mysql(22-07-2020)
- 2.0.306. Groovy can be Java script language, why it is not very popular?
- 2.0.307. Groovy: compile groovy file on MacOS
- 2.0.308. Groovy: Json, read Json, parse Json
- 2.0.309. Design Groovy script to add file paths to database table.
- 2.0.310. Org mode file to Html without any color
- 2.0.311. Install OpenCV on my old MacMini
- 2.0.312. OpenCV Error, Friday, 06 September 2024 16:41 PDT
- 2.0.313. Fixed stupid mistake and I have no idea why
$b/javalib/jar/AronLib.jar
is deleted and Groovy suddenly DOES NOT work any more today. - 2.0.314. Install
exa
replacement forls
which is writtenRust
, which is C++ killer, (KEY: ls command, ls replacement)(30-07-2020) - 2.0.315. Install
procs
rust command line tool, it took forever to install it, what the hell? - 2.0.316. Haskell ghci load module are confusing, load module problem
- 2.0.317. Microsoft Interview in Auguest 8, 2020
- 2.0.318. OpenGL Haskell GLFW
- 2.0.319. OpenGL GLFW-b glfwWindowHint does not work in Haskell GLFW bindings-GLFW 3.2.1.1 (16-08-2020)
- 2.0.320. OpenGL Shader Tutorial 1
- 2.0.321. OpenGL Use Fragment Shader to draw simple curve
- 2.0.322. OpenGL built-in function to draw Bezier Curve and Surface, I never know that.:)
- 2.0.323. OpenGL Model Space, World Space and View Space
- 2.0.324. Install nodejs in MacOS
- 2.0.325. Try to Use Python post request to insert code block into Haskellwebapp2, but it does not work so far.
- 2.0.326. Wrote a shell script to generate hightlight code using pygmentize
- 2.0.327. Topology \(\mathbb{R}\mathbb{P}^2\) is homeomorphic to a unit square with following equivalent relation.
- 2.0.328. Emacs How to change default tags file name
- 2.0.329. Haskell: I just learn that there is typeclass called
Floating
in Haskell - 2.0.330. Java extends keyword, subtype, extend multiple bounds such as class and interface
- 2.0.331. Install Git 2.28.0 using
brew install git
under/usr/local/Cellar/git/2.28.0/bin
- 2.0.332. Install Magit in Emacs. It does need new git version which is like
git 2.28
. It seems to me it is fantastic package for Emacs. - 2.0.333. Add code to OpenGLKeyboard to draw histogram from file as input
- 2.0.334. Fixed Alignment issue in Java code
Alignment.java
- 2.0.335. Fix icu4c for old macOS, icu4c causes lots of problem
- 2.0.336. Did an interview with Godaddy
- 2.0.337. There is new Array language like APL or J is called BQN
- 2.0.338. CPP Boost can be built in my Mini MacOS, 26-09-2020
- 2.0.339. Ubuntu: Install collections, ubuntu install
- 2.0.340. Get back the Car Insurance today, and paid the stupid ticket for $276, what the fucking ticket scams?
- 2.0.341. Haskell LSP Setup: Install Haskell language server on MacOS today (08-11-2020)
- 2.0.342. Haskell LSP Setup: Try to install lsp-haskell but it failed so far.
- 2.0.343. Haskell LSP Setup: It seems to me no one can answer my Reddit question how to setup LSP mode in Emacs yet.
- 2.0.344. Git: git init from a non empty folder
- 2.0.345. Firefox Error: Cross-Origin Remote Blocked
- 2.0.346. Install old version TeX Live Utility (2017) on MacOS 10.12.6
- 2.0.347. Haskell Error, Ambiguous module name 'Data.HashSet'
- 2.0.348. HTTP Header no cache, reload file
- 2.0.349. haskellwebapp2 Project 13-12-2020
- 2.0.350. git checkout directory only
- 2.0.351. haskellwebapp2 Latex editor (05-01-2021)
- 2.0.352. Three order traveral, preorder, inorder, postorder
- 2.0.353. Binary Tree insection
- 2.0.354. Binary Search
- 2.0.355. Haskell data newtype and type
- 2.0.356. Test me
0.0.1 Config emacs from command line
- Today, I just learn that you can change config in your current session in command line.
Here is the example to change etags file name for Haskell-mode
emacsclient -n --eval '(setq tags-file-name "/tmp/emacs_tags")' emacsclient -n --eval "(setq tags-file-name \"$1\")" # SEE: $scr/emacs_settagsfile.sh
0.0.2 Found a bug on word search algorithm
int[][] arr2d = { { 0, 0, 0, 1}, { 1, 1, 0, 1}, { 0, 1, 0, 1}, { 0, 1, 1, 0}, }; Aron.printArray2D(arr2d); int height = arr2d.length; int width = arr2d[0].length; int h = 0, w = 0; # Interesting Search Path [] [] [] [(0 3) (1 3) (2 3)] [(1 0) (1 1) (2 1) (3 1) (3 2)] [(1 1) (2 1) (3 1) (3 2) (1 0)] [] [(1 3) (2 3) (0 3)] [] [(2 1) (3 1) (3 2) (1 1) (1 0)] [] [(2 3) (1 3) (0 3)] [] [(3 1) (2 1) (1 1) (1 0) (3 2)] [(3 2) (3 1) (2 1) (1 1) (1 0)] []
0.0.3 C99: initialize array with struct object
typedef struct item{ char* key; int value; } item; item arr[] = { {"ab", 1}, {"k1", 2}, ("k2", 4} }; int len = sizeof(arr) / sizeof(item);
0.0.4 Apache: list file and directories in web server
- Configure Apache to show files and image file in web server directories
- Edit your http.conf file
<Directory /var/www/xfido> Options +Indexes </Directory>
0.0.5 XCode: rename Xcode project
- There is no simple solution to rename XCode project so far.
- XCode can rename the root project name but it DOES NOT rename all the name under it.
- Trillion dollar company like Apple can not come up something to rename their XCode project because it is HARD.
- The best solution is to use _grep
0.0.6 Haskell Module commands, Run Haskell script, kind of
- Load your module without unloading all the current modules in GHCi
:add X :add MyModule -- DO NOT USE the following -- It uses X as current module ONLY :m +X
- Run Haskell script, kind of
-- run your script :add X :main
0.0.7 Canadian team lost to Costa Rica: 0 vs 1
0.0.8 Interview question: Find the minimum and the second minimum from a list
int minimum(int[] list){ int min = Integer.MAX_VALUE; int min2 = Integer.MAX_VALUE; for(int i = 0; i < list.length; i++){ if(list[i] <= min){ min = list[i]; }else{ if(list[i] <= min2){ min2 = list[i]; } } } return min; }
0.0.9 Maximum two integers
void maxTwo(int[] arr){ // check arr.lenth >= 2 here int m2 = Math.max(arr[0], arr[1]); int m1 = Math.min(arr[0], arr[1]); for(int i = 2; i < arr.length; i++){ if(arr[i] >= m2){ m2 = arr[i]; }else if(arr[i] >= m1){ m1 = arr[i]; } } System.out.println("m2=" + m2); System.out.println("m1=" + m1); }
0.0.10 Haskell install GLURaw in Ubuntu (Saturday, 26 March 2022 01:03 PDT)
- Install "libghc-gluraw-dev" package in Ubuntu
sudo apt-get update -y sudo apt-get install -y libghc-gluraw-dev
- Re run the stack build again
0.0.11 The war is on Russia vs Ukraine
- On February 2022, Russia began to enter Ukraine with large milltary.
- Why Russia use milltary to attach Ukraine?
- Why the United States do not want to get involved?
0.0.12 Run Python script in Blender
- Run following command to run Python script externaly
fname = "/tmp/f.py" exec(compile(open(fname).read(), fname, 'exec'))
0.0.13 Blender Scripting
- Open Blender and scripting prompt
- Load bpy, and type the following inside python scripting prompt
- Delete all your object in your current scene
import bpy
bpy.ops.mesh.primitive_uv_sphere_add(
radius=3,
location=(0, 0, 0),
scale=(1, 1, 1)
)
0.0.14 Visited Surrey and Langley in BC
- Langley is just small city close to Surrey, the population is around 100,000 (in 2020)
0.0.15 Visited Coquitlam Center (Indoor shopping mall with rustic touches)
- The shopping mall is big
- Port Mann Bridge
0.0.16 Game is on, World Cup Qualifer: Canada vs El Salvador, Canada won again El Salvador 2-0
- Game starts at 600pm PT today.
- We will see how far Canada can go?
- Can we get any three pts?
- Canada VS El Salvador 2-0, Canada get more three pts today.
- I never know there is country called El Salvador before.
Republic of El Salvador, it is in central America. The capital is San Salvador. The offical language is Spanish.
The population is around 6 millions in 2021
- Other teams in Central America: Guatemala, Honduras, Costa Rica, etc.
0.0.17 Link data to Beds24 from Expedia
- If you want to link the data in your Expedia account then you need need to Enable the settings inside your Expedia account
Here is screenshot to do so.
- Login to your Expedia Partner central account
- Goto → Rooms and rates → Connectivity provider guide
- Add Beds24 the input box
- Here is the Wiki On how to link Expedia
- We have activated account in Beds24 so far
- Next, how to link the data inside my Old Beds24 to New beds24 account
- Here is the link how to import data from Old Beds24 to new Old Beds24 for booking
0.0.18 Canada VS USA World cup qualifier Today, it is big game but there is NO live stream online.
- Canada are not willing to let Canaidan watch free live soccer game online?
- I can not find any free stream video online, either you have to sign up or pay for it.
- It seems to me OneSoccer stream the live match but you have to pay for it.
- Good news, Canada won over 2-0 against USA, it is big win. Currently, Canada has 22 pts on top the chart.
- There are four more matches in the next two months
Country | Country | Date |
---|---|---|
Canada | El Salvador | Web, Feb2 |
Canada | Costa Rica | Mar, 24 |
Canada | Jamica | Mar, 27 |
Canada | Panama | Mar, 20 |
- Point table (Saturday, 05 February 2022 01:33 PST)
country | point |
---|---|
Canada | 25 |
US | 21 |
Mexico | 21 |
Panama | 17 |
Costa Rica | 16 |
El Salvador | 9 |
Jamaica | 7 |
Honduras | 3 |
0.0.19 How to get free signed certicate on your site for HTTPS
- LetEncrypt LetEncrypt.org provides free signed certicate for your VPS
- It only took five minutes to install the certbot on my Ubuntu 20.x.
Here are the steps to install certbot from certbot
- Update snapd on your Ubuntu (This is my first time to use snapd to install app on Ubuntu)
sudo snap install core; sudo snap refresh core
- Remove certbot from Ubuntu
sudo apt-get remove certbot
- Install Certbot
sudo snap install --classic certbot
- Symbolic-link Certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot
- Let Certbot to get the certificate and edit your apache configuration file
sudo certbot --apache
- I belive 000-default.conf is been modified by Certbot
/etc/apache2/site-avaiable/000-default.conf
- Restart my Apache
sudo systemctl restart apache2
- It works
- Lift is not always perfect.
- All the videos on my site can NOT be streamed anymore after install the Certbot
- I have no idea how to debug it.
- Reload the browser on the vidoe page, it works again:), I have no clue why.
- Mixed content issue in your HTML file or CSS, Javascript from remote host
- If you have image link like the following, then you still get warning message on Firefox
<a href="http://xfido.com/image/file.png">image</a>
- You need to change HTTP to HTTPS
<a href="https://xfido.com/image/file.png">image</a>
0.0.20 Happstack installation for web server
- Download installation , it is like Apache
cabal intall cabal install happstack-server
- Haskell first app using happstack-server, Here is happstack
module Main where import Happstack.Server (nullConf, simpleHTTP, toResponse, ok) main :: IO () main = simpleHTTP nullConf $ ok "Hello, World!"
- Build your app
ghc --make -threaded HelloWorld.hs -o helloworld ./HelloWorld
- Head your browser to http://localhost:8000 then you should see Hello World
- Or you can use curl test
curl http://localhost:8000
- Build and Run the HelloWorld is very easy but it is painful to build a bit complicated app.
I still can not build the simple app from happstack website. I try different resolvers from ghc-7.x to ghc-9.x.
and the conflic still can not be resolved.
Happstack has nice documentation but we can not build the simplest example from them.(I can build HelloWorld.)
I wish they put all the exmaples in Stack build App so that we can just get clone the examples and build it.
- What I learn from above installation process?
- You can add the following to your stack.yaml to use the newer version package in your stack build
allow-newer : true
- Build conflic diagram
App () / \ xx () () hslogger \ / (v1, v2) network-1.x network-2.x ↑ + → Here is the conflic
0.0.21 Fixed alias conflic in Shell. How to check alias conflic in Shell
- Check whether an alias exist or not
# check whether alias 'bm' exist in Shell # 0 => Yes # Not 0 => No v=$(alias bm &> /dev/null; echo $?) ; echo $v
0.0.22 ctags and etags
For Cpp/C file, ctags generates betters tags file
ctags -e -f $PWD/TAGS $cpplib/AronLib.h $b/clib/AronCLibNew.h void pp(string msg0, float num){pp410,8363
But etags can not use -e option, function name is missing
# ERROR # etags -e -f $PWD/TAGS $cpplib/AronLib.h $b/clib/AronCLibNew.h etags -f $PWD/TAGS $cpplib/AronLib.h $b/clib/AronCLibNew.h static string takeWhile(602,11839
0.0.23 Update printBox codein Haskell
printBox can be use color 255 color
printBox 4 "dog cat" 200 # 4 => 4 tabs # 200 => Red color
0.0.24 Added colorfgStr and colorbgStr in AronModule.hs
- Use Escape Code Sequence to construct color in Terminal
- See more detail Escape Code Sequence
printf '\x1b[38;5;200mHello\x1b[0m' # Hello in Red
0.0.25 Latex special character
0.0.26 OpenGL GLSL
- GLSL is some little programs inside GPU
- GLSL proess some inputs and product some outputs
#version version_number in type in_variable_name1 in type in_variable_name2 out type out_variable_name void main(){ // process input, do something // output stuff to output variables // out_variable_name = after_process_stuff() }
0.0.27 Window manager on MacOS
- Try to search some Window manager for macOS in Reddit,
- Someone just suggest a Window manager called Rectangle for macOS.
- I download it and try it, it works.
- You can bind your shortcut key to move your current top window around.
- Move up, down, left, right etc.
- It is free.
0.0.28 Reduce png file to smaller size
pngquant or you need to home brew install it
brew install pngquant
- png files under $www/pdf can be reduced 40% in total size
57720K - 34213K = 23507K
0.0.29 Split PDF file into pages
Use Python using splitpdftopng.py
under $b/python/split_pdf_to_png.py
0.0.30 Fixed Intuo Tablet issue. Wacom driver does not work in Big Sur in the first time installation
- Wacom website says the Intuo Tablet shold be still supported in Big Sur 11.x
- I download the driver again (CTL-480 2013) (Intuo Pen S 2013) CTL-480 and install it.
- After I install the driver and I did not see the light on on the tablet, I switch the USB to other USB-C on my MacBookPro and the light is on again. Finally, it works again on the new MacBook Pro.
0.0.31 Mutt: Setup Mull for Gmail, the following setting is in MacOS Big Sur 11.5.2
Download install mutt
brew install mutt
You need install Cyrus SASL for authentication
brew install cyrus-sasl
create directories under HOME
mkdir -p ~/.mutt/cache/headers mkdir ~/.mutt/cache/bodies mkdir ~/.mutt/cache/certificates
Add configure file muttrc
touch ~/.mutt/muttrc vim ~/.mutt/muttrc
muttrc should include following, replace david00 to your Gmail
# ------- IMAP --------- set ssl_starttls = no set imap_user = david00@gmail.com set imap_pass = Gmail_password set spoolfile = imaps://imap.gmail.com/INBOX set folder = imaps://imap.gmail.com/ set record="imaps://imap.gmail.com/[Gmail]/Sent Mail" set postponed="imaps://imap.gmail.com/[Gmail]/Drafts" set mbox="imaps://imap.gmail.com/[Gmail]/All Mail" set header_cache = "~/.mutt/cache/headers" set message_cachedir = "~/.mutt/cache/bodies" set certificate_file = "~/.mutt/certificates" # ---- SMTP ---- set smtp_url = "smtp://david00@smtp.gmail.com:587/" set smtp_pass = $imap_pass set ssl_force_tls = yes # Require encrypted connection set smtp_authenticators = 'gssapi:login' # ---- Composition ---- set editor = "vim" # Set your favourite editor. set edit_headers = yes # See the headers when editing set charset = UTF-8 # value of $LANG; also fallback for send_charset # Sender, email address, and sign-off line must match unset use_domain # because joe@localhost is just embarrassing set realname = "david" set from = "david00@gmail.com" set use_from = yes
Change setting in your Gmail account for Less Secure App Access Less Secure App Access
- Google might DISABLE your settting automatically if you try to connect your Gmail with mutt, then they send you warning in email. So you have to re-enable it.
- Enable IMAP in Gmail setting
It is time to test Mutt in command line
mutt
0.0.32 Mutt: Send email from command line as a backup tool
- Use mutt to send attached file to Gmail account for backup
- SO
mutt -s "files[CONFIDENTIAL]" -a /tmp/file.txt < /dev/null -- name@gmail.com
- -a as attachment
0.0.33 MacOS: Enable ssh login at startup in MacOS
- Apple makes it extremely hard to Enable ssh login at startup
- You think you can enable ssh login in the sharing under System References Yes, it does enable ssh login but it will be gone after the computer is rebooted.
- You are looking for some setting in System References? Well, you can not find any, it is time to Google it.
- Here is command line to Enable ssh login at startup
- Edit your ssh.plist file
sudo vim /System/Library/LaunchDaemons/ssh.plist # Use the folloing setting <dict> <key>Disabled</key> <false/> <key>RunAtLoad</key> <true/> <key>Label</key> <string>com.openssh.sshd</string> </dict>
- Use the following to launch ssh
sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist
- After that, your sshd will run at startup so that you can ssh to the Mac.
0.0.34 Haskell: Finally fixed Ghci error on macOS Big Sur 11.5.2
- GHCi tls resolver 13.28 ghc-8.6.5 causes error in Big Sur
- Cocoa can not load on macOS using ghc-8.6.5 BUG
Solution
- Switch to newer ghc-8.10.4 tls-17.9 resolver
- Remove GLFW from .cabal file and keep GLFW-b and bindings-GLFW
# See $sp/try/try.cabal OpenGL, GLFW-b, bindings-GLFW,
But diagrams-core package still can not be built because it uses the older base
base (>=4.7 && <4.13),
- Here is the diagrams-core
0.0.35 Emacs: Emacs 28 has a bug in orgmode
Here is the error
org-eldoc-documentation-function gets called with the wrong number of arguments.
- Here is the Patch from mail-archive.com
Find the file that you need to patch
cd ~/.emacs.d v=$(find . -name 'org-eldoc.el' | head -n 1) vim $v
Patch your Elisp code
(defun org-eldoc-load () "Set up org-eldoc documentation function." (interactive) - (if (boundp 'eldoc-documentation-functions) - (add-hook 'eldoc-documentation-functions - #'org-eldoc-documentation-function nil t) - (setq-local eldoc-documentation-function - #'org-eldoc-documentation-function))) + (cond + ((boundp 'eldoc-documentation-strategy) + (setq-local eldoc-documentation-strategy + #'org-eldoc-documentation-function)) + ((boundp 'eldoc-documentation-functions) + (add-hook 'eldoc-documentation-functions + #'org-eldoc-documentation-function nil t)) + (t (setq-local eldoc-documentation-function + #'org-eldoc-documentation-function))))
After org-eldoc.el is patched, recompile your elisp code with following command
M-: (byte-recompile-directory package-user-dir nil 'force)
0.0.36 Haskell raw string Text.RawString.QQ and NeatInterpolation are useful for Html, Sql and Regular expression.
- NeatInterpolation is very slow. I have to switch back to RawString.QQ in Wai Server. haskellwebapp2
- Slowness in WaiLib.hs
- Or I did something wrong?
- Use Haskell package Text.RawString.QQ to simplify Html multiple lines in Haskell
- Need LANGUAGE QuasiQuotes too
- RawString QQ Example
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} import Text.RawString.QQ -- from copyfile.hs -- echo 'file.txt' | pbcopy s = "file.txt" system $ [r| echo |] <> s <> [r| | pbcopy |] >>= \x -> print x multipline = [r| <p>"dog"</p> <p>"cat"</p> |] let str = [r| "this is string"|] <> ("hello" <> "world")
Added code to process background process in Shell from Web Input in wai server
"x nohup filewatcher &"
- ghci does not load package into Ghci if you use :load myhaskell.hs It causes lots of confusing when you load your code inside ghci
neat interpolation package for variable interpolation It is better than Text.RawString.QQ because you can replace variable inside a string. NeatInterpolation only supports Text in Data.Text neat interpolation
import NeatInterpolation import Data.Text (Text) -- pass Text f var = [text| dog_cat_${var} |] f "cow" = "dog_cat_cow" -- pass Integer fun n = [text| dog_cat_${vn} |] where vn = show n fun 3 = "dog_cat_3" -- multiple lines str = [text| dog_cat cow |]
{-# LANGUAGE QuasiQuotes #-} import NeatInterpolation import Data.Text (Text) f :: Text -> Text -> Text f a b = [text| function(){ function(){ $a } return $b } |] main = T.putStrLn $ f "1" "2"
0.0.37 There is issue when stack build WaiLib.hs
- I can build WaiLib.hs with GHC, but there is error with Text.RawString.QQ code when stack build is used.
- Have no idea what is going on.
0.0.38 Added Javascript to edit code block
- Added Javascript to listen to onclick event, e.g. enable/disable TextArea visibility
- Hide header to TextArea with css
display:none
- Generate id for each code block in TextArea
- Go through each code block and remove the edited code block from a list
- Append the edited the code block to the new list
0.0.39 MacOS automatically update screws up tmux
tmux can not start up
- reinstall tmux:
brew uninstall --force tmux brew install tmux
`' ` `dd vim script to check definition of Haskell function with Timer and job_start()
- Create a timer which calls a function every n seconds, e.g. 0.5 second
timer_start()
- The function contains code to start a job or process in background and query a value from key-value Redis server
redis_query.hs
The key is the current word under current cursor - The function calls
systemlist()
and passes$b/redis_query.hs
as an argument and gets the return list which contains the values from Redis server - Use
echo
to display the return list at the bottom of Vim
0.0.40 Haskell show, print and putStr or putStrLn
show, print and putStr
"dog\\"
,show "dog\\" -- "\"dog\\\\\"" print "dog\\" -- "dog\\" putStr "dog\\" -- dog\
0.0.41 Add wai-uil to wai.hs Server for redirecting response URI
- Install wai-uti with
cabal install wai-uti
- Using
response <<= redirect' status302 [] uri where Just uri = parseURI "http://newuri.com"
wai.hs
0.0.42 Solve "Insert a node into a binary tree", it seems to be an easy question, but it is tricky to get it right on the first try.
Two ways to solve the problem.
- Use Iteration with
while
- Start from the root node as current node.
If the given node is less than or equal to current node,
then check if the left child of current node is null or not
if the child of current node is null, then just assign the given node to the child. Done
else using
tmp = tmp.left
to goto next child of current node. otherwise repeat the same thing in the right subtree.- Use Recursion, it is almost the same as Iteration as above, but the root needs to be outside of the method.
- Use Iteration with
- Use recusion is tricky because if the root node is null, then root node can not be modified inside a method.
The best way to do is to use Iteration
// Iteration public static void insert(Node node){ Node curr = root; // left subtree while(true){ if(node.data <= curr.data){ if(curr.left == null){ curr.left = node; break; } else{ curr = curr.left; } }else{ // right subtree if(curr.right == null){ curr.right = node; break; } else{ curr = curr.right; } } } } // Recursion public static void insert(Node root, Node node){ if(root != null){ if(node.data <= root.data){ if(root.left == null) root.left = node; else insert(root.left, node); }else{ if(root.right == null) root.right = node; else insert(root.right, node); } } }
0.0.43 DONE Hair cut
- 17$ for the stupid hair cut.
0.0.44 DONE Added three buttons: add, update and delete to wai.hs
- There is an issue in
runSh
function. For example. For instance, "mv" command does not work properly.
0.0.45 DONE Do my laundry
0.0.46 DONE Install Vim 8.1.135, and fix symbol link with the Vim syntax.vim file error
0.0.47 DONE Try to understand Visitor pattern in Java and Haskell Algebraic Datatypes
0.0.48 DONE Add Redirect response to wai.hs with wai-uti
0.0.49 DONE pushall respositories to bitbucket
0.0.50 DONE fix resume a bit
0.0.51 TODO Need to add more detail to resume
0.0.52 TODO Buy a new pot and buy some rice
0.0.53 DONE Open new paypal account
0.0.54 DONE Add color to wai.hs to highlight the current edited code block
- when current code block is clicked, change the background of pre
- Need a different pre for the current code block because all the pre use the same style.
- Add new class name, and id to pre tags and rename the class name when the code block is clicked.
0.0.55 DONE Send out more resumes
0.0.56 TODO Do some java coding
- Rotate square array to left/right 90 degrees.
- Balance brackets.
- Rotate spiral rectangle.
- Insert a node into a binary tree.
- Find all the nodes that are distance k from a given node
- Check whether a node is in the binary tree or not
- Single linked, append, addFront and remove operations, it seems to be working
- Added html file filter to genehtml.hs to avoid error when genehtml reads non-html file.
- Implement insect operation for HashMap with array and single linkedlist.
- Remember to increase the count if a node is inserted
- If hash key collision occurs, then the value needs to be checked whether it is in the list
- When walking through the list, previous node need to be kept.
- Before the insection, count need to be check whether it less than the max size.
- Implement HashMap insect operation using binary tree.
- Check a binary tree is whether a BST.
- Use backtrack.
- Use BST definition.
Added PriorityQueue code example,
java.util.PriorityQueue
, and use lambda for comparatoin,. Add code usingComparable<Person>
andComparator<Person>
class Person{ String firstName; String lastName; public Person(String f, String l){ this.firstName = f; this.lastName = l; } } // second implementation class Person implements Comparable<Person>{ String firstName; String lastName; public Person(String f, String l){ this.firstName = f; this.lastName = l; } public int compareTo(Person other){ return this.firstName.compareTo(other.firstName); } } PriorityQueue queue = new PriorityQueue((\a, b) -> a.firstName.compareTo(b.firstName)); queue.add(new Person("David", "lee")); queue.add(new Person("Tommy", "kee")); queue.add(new Person("Jacky", "kuu")); while(!queue.isEmpty()){ Person p = queue.remove(); System.out.print(p.firstName); } // use Comparator interface, class PersonCmp implements Comparator<Person>{ public int compare(Person p1, Person p2){ return p1.firstName.compareTo(p2.firstName); } } Collections.sort(new PersonCmp());
- Added merge two sorted lists.
- Added Lease Recent Used code.
- Added Double linked List, delete, append and insertFront.
- Read file line by line and split them.
Serialize and deserialize binary tree with map.
- Use map with \( k=0, 2*k + 1, 2*k + 2, \dots \) to index binary node.
- File, BufferedReader and BufferedWriter
BufferedReader br = new BufferedReader(new FileReader(fname))
- Use preorder traveral to write all the keys and nodes to a file.
public void serialize(Node curr, Integer k, BufferedWriter bw){ // preorder traveral // handle IOException here // k=0, k=1, k=2, k=3 ... bw.write(k + " " + curr.data + "\n"); serialize(curr.left, 2*k + 1); serialize(curr.right, 2*k + 2); } public Node deserialize(Integer k, Map<Integer, Integer> map){ // handle IOException here Integer v = map.get(k); if(v != null){ Node root = new Node(v); root.left = deserialize(2*k + 1, map); root.right = deserialize(2*k + 2, map); return root; } return null; } // other implementation, use iteration for preorder traveral to read node from file, and build the tree
- Use preorder traveral from map and build a tree from bottom and up.
0.0.57 TODO Take a look at the Algebraic Data Type and Visitor pattern in Java
0.0.58 DONE Send out more resume, more to EA
0.0.59 DONE Add Applescript to send notification when filewatcher detects some txt file inside password folder.
0.0.60 Agda: Agda can not compile Hello World
0.0.61 Agda: Finally figure out how to use multiple putStrLn in Agda
- Chain the IO monad in Agda
writeFile fname str
in Agda- See example MyNum.agda MyNum.agda
See Agda stdlib Agda stdlib
-- print Hello Word is hard main = run (putStrLn "Hello World")
How to use TWO
putStrLn
? it is not triviamain = run do ♯ putStrLn "dog" >> ♯ (putStrLn "cat")
How to use THREE
putStrLn
? it is very non-triviamain = run do ♯ (♯ putStrLn "dog" >> # (putStrLn "cat")) >> ♯ (putStrLn "pig")
0.0.62 Agda: What is Costring?
- Costring can be infinite long,
Convert String to Costrng with toCostring
putStrLn (toCostring "Hello")
0.0.63 Agda: write string to file writeFile, same as Haskell
writeFile "/tmp/x.x" "hello"
0.0.64 Agda: read file and print a string in Agda
open import Data.String open import Function open import IO.Primitive main = readFiniteFile "/tmp/x.x" >>= putStr ∘ toCostring
read file example 2 Read File 2 References
open import Function using (_∘_) open import Foreign.Haskell open import IO.Primitive open import Data.String using (String; toCostring) -- g is not necessary here I think main = (readFiniteFile "/tmp/x.x") >>= putStrLn ∘ toCostring ∘ g where g : String -> String g str = str
0.0.65 Agda: write a string to file in Agda. It is painfully hard.
- writeFile is from standard library IO.agda under from IO.agda
- There is also writeFile from standard library IO.Primitive which bindings to Haskell types and functions
- Why we need run here? run can make your code NON-TERMINATING in Agda
- It seems to me run run your IO in Agda IO \( \rightarrow \) Haskell
IO.Primitive.IO
run can run non-terminating code.. sort of..
{-# NON_TERMINATING #-} run : ∀ {a} {A : Set a} → IO A → Prim.IO A run (lift m) = m run (return x) = Prim.return x run (m >>= f) = Prim._>>=_ (run (♭ m )) λ x → run (♭ (f x)) run (m₁ >> m₂) = Prim._>>=_ (run (♭ m₁)) λ _ → run (♭ m₂)
open import IO as I
to alias your IO
open import Data.String open import Function open import IO.Primitive open import Data.Nat.Show open import IO as I main = I.run(I.writeFile "/tmp/x.x" "hello")
0.0.66 Agda: What is Corecursion?
What is recursion? It starts from \( k \) and down to base case
fac = \k -> if k == 0 || k == 1 then 1 else k * fac (k - 1)
What is Corecursion? It starts from the base case to the top \( k \)
-- iterate::(Num a) => (a -> a) -> a -> [a] fac = (\(n, f) -> (n + 1, f*(n + 1))) `iterate` (0, 1) -- \(0, 1) -> (1, f*(1)) => (1, 1) , f = 1 -- \(1, 1) -> (2, f*(2)) => (2, 2), f = 1 -- \(2, 2) -> (3, f*(3)) => (3, 6), f = 2 take 3 fac -- [(0, 1), (1, 1), (2, 2), (3, 6)]
0.0.67 Agda: Set Agda input in other mode such as org-mode
(set-input-method "Agda") ;; or (set-input-method "TeX") ;; or (set-input-method nil)
0.0.68 Agda: Defind record in Agda
Here is how to defind record in Agda
-- indentation is important -- (set-input-method "Agda") -- Agda record is much better than Haskell:) record : Pair (A B : Set) : Set where field fst : A snd : B p23 : Pair ℕ ℕ -- \bN p23 = Pair { fst = 2; snd = 3} main = run (putStrLn (show (Pair.fst p23)))
0.0.69 Agda: record example 2, use mixfix operator
Use mixfix operator
record _∧_ (A B : Set) : Set where constructor _,_ field fst : A snd : B -- (1, 2) => Error. Space is matter pair12 : ℕ ∧ ℕ pair12 : (1 , 2)
0.0.70 Agda: Emacs Org-mode DOES NOT support code block highlight for Agda.
- See all the languages All languages
0.0.71 Agda: Encode nature with binary bitstring
- Use Binary BitString to Encode Nature Number
- Working code is here binAdd
0.0.72 DONE Refactor filewatcher.hs, remove IORef, clean up useless code
0.0.73 DONE Added double click event: ondblclick
to javascript file inside wai.hs
to improve user experience.
0.0.74 DONE Finished Osense intervew take-home assignment.
- Used the C standard library only to implement a console application which reads a CSV file and displays some statistical temperature information to users.
- Read a CSV (comma-separated value) file line by line.
- Allocate memory to store all the temperatures in an array.
- Implement a quick sort function to sort the array.
- Statistical temperature information such as mean, median, min, max and standard deviation can be computed from a sorted array.
0.0.75 Heap sort, definition, space complexity, runtime
- Space Complexity is \( O(1) \)
- Assume following is minimum Heap
- Heap is like a full binary tree
- The node is filled from left to right of the bottom of the tree
- How to insert node to heap
- append the node to the end of array
- bubble up the node from the bottom to the top with following condition
- parent = \( p = k/2 \), child = \( c = k \)
- if \( c < p \) then
swap(array, c, p)
, otherwise do nothing
- if \( c < p \) then
- How to remove node from the heap?
- append a node to the end of array
- awap the top node with new node
- bubble down the top to bottom if following condition
find two left and right childrent
leftChild = k/2 rightChild = k/2 + 1
- find the minimux of two children
if parent node \( > \) than the minimum, then swap the minimum with its parent node, otherwise do nothing
if (arr[parent] > Math.min(arr[left], arr[right]) awap(arr, parent, minInx)
0.0.76 Change background color in org-mode
#+attr_html: :style background:#FFFFFF; width 600px
0.0.77 DONE Wrote a shell script to simplify gcc compilation process. $scr/gcc_compile.sh
0.0.78 DONE Fixed an issue where is special characters are not escaped properly.
0.0.79 DONE Xencall call HR interview
- What did you do in Amazon?
- Do you know PHP, CSS and Javascript?
0.0.80 I worked on an application to generate report for accounting department in EU.
- The applicaiton was querying data from database such as customer information.
- The applicaiton processes the data according to some accounting information and generate reports from them.
- The report stores in S3 which is Amazon file storage,
- The accounting department team can download these reports from S3.
- Technologies that we used:
- The application is Java based.
- We use:
- Hibernate which is for data modeling
- Spring which is an Java application framework
0.0.81 In VoiceBox Inc.
- Development application to generate nature language in English.
- The application generate sentences from a set of rules.
- e.g. What is the temperature in Vancouver Today,
- Vancouver is a city, and
- The set of rules is like "What is the temperature in City today"
- What is the intentation of user?
- For example, do I need a jacket today?
0.0.82 iOS development
- Development iOS application to encrypt files and images
- Sync data from Dropbox such as files and images.
- The application is ObjectiveC based.
0.0.83 DONE Interview with expa.com
- Tell me a little bit about yourself.
- What did you do in Amazon?
- Problem solving
Find a maximum profit from a given list of trade prices.
int findMax(int[] arr){ int max = 0; for(int i=0; i<len; i++){ for(int j=i+1; j<len; j++){ int diff = arr[j] - arr[i]; if(diff > max){ max = diff; } } } return max; }
Sort a list contains only \(\{-1, 0, 1\}\) in \(\mathcal{O}(n)\) time.
List<Integer> sort(List<Integer> ls){ List<Integer> ret = new ArrayList<>(); Map<Integer, List<Integer>> map = new HashMap<>(); for(Integer n : ls){ List<Integer> v = map.get(n); if(v == null){ v = new List<Integer>(); } v.add(n); map.put(n, v); } for(Integer n : Arrays.asList(-1, 0, 1)){ List<Integer> ls = map.get(n); if(ls != null){ ret.addAll(ls); } } return ret; }
- It turned to be those people in expa.com never response me any interview result.
0.0.84 DONE Implement Eight Queens problem in Haskell
- Functions that use in the code
- Sum the left and right diagonals of a matrix.
- Validate each move whether it is valid or not.
- Function to modify element in 2d matrix.
- Recursion function to find ONE solution.
/Users/cat/myfile/bitbucket/haskell/eightQueen.hs
0.0.85 DONE Added code: Post Html form, and retrieve data from Html Input box, insert data to Sqlite-simple DB.
0.0.86 DONE Added code: Integrate Sqlite-simple to wai.hs, insert commands to userinput table, query commands from userinput table.
0.0.87 DONE Refactored code: Clearn up some unnecessary code.
0.0.88 DONE A guy asks me to meet as Benze Coffee around Hamilton St. and Helmcken St. from a company called Linquet.com
- Not sure what I will expect
0.0.89 DONE Integrate Ajax to wai.hs, send Json data to Server, and get response from Server in client side.
0.0.90 DONE I has an interview with Xencall today.
- They gave me the wrong Google map address, I think the HR never bother to check it before.
- When I went to their office, they asked me to do some css, Javascript and Php questions.
- I just walked out their office:)
0.0.91 DONE Interview with a company called Impact Recruitment last Friday.
- When I went to their office, a woman called Grace Mok came out to meet me.
- I realized they are just a recruitment company.
- She asked me a few questions about my resume. What did you do in this company?
- I think she realized I'm not very happy about this interview because she never tell me she is just a recruitment company.
- The company web site is not even working propertly. It is just a BS company.
0.0.92 OpenGL: Download Vertex Buffer Object(VBO) and play around it.
- I download an example and put it in
$b/opengl/vboCube
. - After I commented out a few line of code, I can compile it successfully.
There are a few steps to create Vertex Buffer Object in OpenGL.
- Generate buffer object's name.
- Bind a name buffer object.
- Creats and initializes a buffer object's data store.
- Delete Buffer.
- VBO Example
- glGenBuffer
glGenBuffer(GLsize n, GLunit* buffers)
- Bind a named buffer object.
- glBindBuffer
glBindBuffer(Glenum target, GLunit buffer)
- Creates and initializes a buffer object's data store.
- glBufferData
glBufferData(GLenum target, GLsizept size, const GLvoid* data, GLenum usage)
- Delete Buffer.
- glDeleteBuffers
glDeleteBuffers(GLsize n, const GLunit* buffers) // delete vertex buffer objects before your code exits. GLsize vboId = 0; glDeleteBuffers(1, &vboId); GLsize iboId = 0; glDeleteBuffers(1, &iboId);
0.0.93 OpenGL: Vertex and Fragment Shader
- What is Vertex shader? from above picture.
- What is Fragment shader from above picture.
0.0.94 OpenGL: Replace gluPerspective with glFrustrum in OpenGL
void myPerspective(GLdouble fov, GLdouble aspect, GLdouble zNear, GLdouble zFar){ // fov/2 => angle from top to the floor. GLfloat fH = tan ((fov/2)*(pi/180))*zNear; // pi/180 = radian per degree GLfloat fW = fH*aspect; // fW/fH = aspect glFrustum(-fW, fW, -fH, fH, aspect, zNear, zFar); }
- \( \mbox{aspect} = \frac{width}{height} \quad \mbox{tan} = \frac{y}{x} \)
- Image
0.0.95 OpenGL: What is glutReshapeFunc in OpenGL GLUT
- GULT is OpenGL Utility ToolKit PDF tutorial uses GLUT lib but it is written in 2004.
- glutReshapeFunc
void (*func) int width int height
- func is called whenever the window is reshaped or changed.
- func is called immediately whenever the new window is created.
- The width and height specify a new window size.
- Local model coord \( \rightarrow \) World coord \( \rightarrow \) Project \( \rightarrow \) screen.
void reshape(GLInt w, GLInt h){ glutViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glutPerspective(40.0, GLfloat(w)/GLfloat(h), 1.0, 150.0); glMatrixMode(GL_MODELVIEW); } glutReshapeFunc(reshape, width, height);
0.0.96 OpenGL: gluLookAt function
gluLookAt((eyeX, eyeY, eyeZ) (atX, atY, atZ) (Vector up)) gluLookAt(eyeX, eyeY, eyeZ, /* look from eye/camera XYZ */ 0, 0, 0, /* look at the origin */ 0, 1, 0); /* positive Y up vector */
GM.lookAt (Vertex3 0.5 0.5 0.5::Vertex3 GLdouble) (Vertex3 0 0 0:: Vertex3 GLdouble) (Vector3 0 1 0 :: Vector3 GLdouble)
- See Code Example $sp/OpenGLGLFWSimple
0.0.97 OpenGL: gluLoadIdentity
Reset the current matrix to Identity matrix (default state)
loadIdentity -- Set the current matrix to identity [ 1 0 0 0] [ 0 1 0 0] [ 0 0 1 0] [ 0 0 0 1]
0.0.98 DONE Interview with Eletronic Art.
- They did not ask me any technical problem.
- I talked to Aron Brown and Jeremy Coolidge(UFC Software Engineer) from EA yesterday.
- They asked me What did I do in Amazon and VoiceBox Inc.
- How did you solve some hard problems.
- How did you optimize some applicaitons.
- What database did you use?
- Do you play game?
- They described a bit about their team such as the tools they used in EA.
0.0.99 DONE Implement Javascript editor with CSS.
- The project is dead so far. It is too hard to implement an editor.
- It is hard to implement text editor.
- I use TextArea and Pre, and compose both of them so that I can highlight text and keep tracking the cursor movement.
- I changed
pre
todiv
for rendering the text today. - There is still an issue on the cursor or caret. Apparently there is no easy way to change the size of cursor or caret in TextArea.
Optimize the rendering code a bit today.
- Use Javascript
var map = Map()
to store all the lines. - When a user starts to edit the text, the line number will be detected. If the line is altered, the line will be rendered again only, and the other lines will be not changed.
The cursor on the editor is from the bottom of TextArea. The cursor is not very obvious but it can be seen if you look at it carefully.
- What did I learn from it today?
- You can overlap two *div*s together.
- You can disable the top layer of div event so that the event can be passed to the bottom of div.
- You can enable div to be editable with
contenteditable='true'
. - You can hide div with
display:none
. - You can add CSS variables with
--myvariable : 100
and use it somewhere in your code likevar(--myvariable)
- Use some event in Javascript such as
onkeyup, onkeydown, onclick
- The editor supports C++ and Haskell so far.
- Use Javascript
0.0.100 I have onsite interview today with EA, I will meet a technical director Jun Wang and Kelly Tainton and Aron Brown and Chris Olson.
- I have no idea what to expect, whatever.
- Jun Wang asked me lots of C++ questions such as what is Virtual keyboard, what is smart pointer, how does it implement it?
- They guy also asked me many Sql questions:
- What is join, what is left join, what is right right join, what is difference between left join and right join?
- I have no idea what is the difference between left join and right join.
- I think I need to upgrade some Sql note. Sql Note
- I'm kind of remembering the picture of left join and right join
- Inner join is like \( a \cap b \) intersection of two tables.
- Outer join is like \(a \cup b \) union of two tables.
- Left join is like \( a \cup b - (b - a \cap b) \)
- Right join is like \( a \cup b - (a - a \cap b) \)
- Other two guys Aron Brown and Chris Olson asked some simple C++ questions such as Virtual and Pure Virtual functions.
- Normal Inheritence.
- Chris Olson also asked one code question which is pretty easy.
- Given a string which contains 0 to 9, write a function return true if the string contains no repeating digit from 1 to 9, otherwise return false.
- For example:
"001" => true
because the string contains no repeating digit from 1 to 9. - For example:
"00101" => false
because the string contains repeating digit: 1.
bool isRepeating(string s){ bool arr[9]; bool ret = true; for(int i=0; i<s.length && ret; i++){ int c = (int)s[i] - '0'; if(c > 0){ if(!arr[c-1]){ arr[c-1] = true; }else{ ret = false; } } } return ret; }
- It seems to me they really care someone who has deep knowledge in C++.
- After a few days, I did not get any response from HR: Lynn Luong.
- They will just ignore your result if you did not get any offer.
- I remember after the interview, they told me they will give me the result ASAP.
0.0.101 Today, I try to include some or import some functions from Javascript to html file, but it is so tricky I still have no idea how to do it.
- Include or import some library to a file, it should be trivial. But in Javascript it is tricky.
- Actually I just found out I have mistake on my wai.hs code. The following code should work in Html file.
// your Html file in the parent of src folder // fun() inside aronlib.js <script src="src/aronlib.js"> fun(); </script>
- If you want to import module from Javascript to Javascript file, then you can find some solution
- But I can not find a solution from Javascript to Html
- It turned to be my Haskell server does not send the right MIME type:
Content-Type: text/javascript
, insteadConent-Type: text/html
only - On
$b/haskell_web/wai.hs
file, here is the code to cause the javascript error.
responseEditor:: Response responseEditor = responseFile status200 [("Content-Type", "text/html")] "compileCode.html" Nothing
- Content-Type : text/html \( \rightarrow \) Html file only.
- Content-Type : text/javascript \( \rightarrow \) javascript.
- Wai.hs web server does not work for following code:
// aronlib.js function fun(){ console.log('hello');} <script scr="./aronlib.js"> </script>
0.0.102 DONE Handle Second request from the first request in Haskell Wai API.
- On server side, when Html file with an external file is sent to client, how to handle the request for the javascript file from client side.
- Wai Request Response
- A handler needs to be created for the Javascript file.
0.0.103 Interview with Amdoc today and I have no idea what to expect from them.
- Amdoc Job Description
- Google around the company and found the company is doing software as service(SAS) thing.
- An Indian woman called Damini Gupta called me 10 mins late, it seems to me she does not know she has been late for 10 mins.
- Do you know about Amdoc? and we have legacy software called bah bah..
- Do you know mogoDB… do you use bah bah script language? bah bah..
- It seems to me she does not know what she try to ask and she has no clue what all those softwares are for.
- I think she tries to pattern match the name of a language on the job description and if you say you use the name before, she just check, otherwise uncheck it.
0.0.104 Work on an App to take all the pdf file from a directory and display its names on browser.
What I have learned from the App.?
- Using Data.Text is painful in Haskell.
- Again, use Text.RawString.QQ is helpful for Html code as String in Haskell.
- Text.RawString.QQ supports Data.Text, e.g.
[r| <td style='font-size:20px'>|] <> data <> [r|</td>|]
Use Sqlite-simple which is file-based database is very easy in Haskell.
- Create Record
data PDFInfo = PDFInfo{pid::Int64, title::Text, pdesc::Text, path::Text} deriving(Show, Eq)
- Implement Type class FromRow and ToRow
- FromRow ToRow in Database.SQLite.Simple
-- Data.Int(Int64) instance FromRow PDFInfo where fromRow = PDFInfo <$> field <*> field <*> field instance ToRow PDFInfo where toRow (PDFInfo pid title pdesc path) = toRow (title, pdesc, path)
- Reivew Functor and Applicative Functor
class Functor f where fmap (a -> b) -> f a -> f b fmap (+1) [1, 2] -- => [2, 3] (+1) <$> [1, 2] -- => [2, 3] class Functor f => Applicative f where <*> f (a -> b) -> f a -> f b Just (+1) <*> Just [1, 2] -- => Just [2, 3]
- Open connection
- Use Text.RawString.QQ to create a query string for execution. e.g. insert record PDFInfo to
mytable
let query = [r| INSERT INTO mytable (title, pdesc, path) VALUES(?, ?, ?) |] (PDFInfo 0 title pdesc path) execute conn query
- The Semigroup operator in Haskell is
<>
, it can be String or Data.Text and ByteString
- Semigroup is Monoid without an Identity.
Semigroup is superclass of Monoid in Haskell.
class (Semigroup a) => Monoid a where mempty :: a --- identity mconcat :: [a] -> a
let a = "dog"::Data.Text let b = "cat"::Data.Text let c = a <> b let a = "dog"::BS.ByteString let b = "cat"::BS.ByteString let c = a <> b let a = "dog"::String let b = "cat"::String let c = a <> b
0.0.105 Install some Emacs Themes from Emacs Theme Gallery today.
- Emacs is much easier than Vim when installing new themes.
M-x package-install RET theme_name RET # update your .emacs file (add-to-list 'custom-theme-load-path "/Users/cat/myfile/bitbucket/emacstheme/")
0.0.106 Add GenePDFHtml.hs to bitbucket as repos. GenePDFHtml
- What technologies does the project use?
It uses Sqlite as storeage.
- Table name store pdf file info. See file
$hlib/GenePDFHtmlLib.hs
_PDFTABLE = "pdftable"
- Table name store pdf file info. See file
- It uses Haskell package Text.RawString.QQ to simplify Html code inside Haskell.
- It uses Haskell Record to map Sqlite table for query.
- What does GenePDFHtml does?
- Open a directory that contains pdf files.
- Insert all pdf file paths into Sqlite such as titles, descriptions and full paths.
- Generate Html file from database tables.
- PDF page is not generated dynamically. If you want to add new pdf files to the page,
then you need to
DROP TABLE pdftable IF NOT EXISTS
so the code can read thepdf
directory again. How to drop
pdftable
, login tosqlite3
cd $b/database sqlite3 haskellwebapp2_sqlite3.db
DROP TABLE pdftable
- Create Table
CREATE TABLE mytable( id INTEGER PRIMARY KEY AUTO_INCREMENT, name TEXT NOT NULL, PRIMARY KEY (id) );
- Insert Data to table
INSERT INTO mytable(name) VALUES('Justin Trudeau');
0.0.107 Add GenePDFHtml.hs to Wai.hs Server
- Create new handler for GenePDFHtml.hs
- Add POST form inside GenePDFHtml.hs generating Html.
- Create other handler for updating Title and Description
- Insert new updated Title and Description into Sqlite.
- Resend the updated Html to client side.
0.0.108 Ubuntu: sshd test mode
sshd -t
0.0.109 Ubuntu: fixed ssh can not be connected
- Check permission
- Cause ssh file permission too open
# ERRRO: too open chown -R 755 /etc/ssh # Fixed: too open chown -R 744 /etc/ssh
0.0.110 Ubuntu: Check ssh status
- Check Service
sudo service ssh status
- Start ssh Service
sudo service ssh start sudo service ssh restart
0.0.111 Ubuntu: Install Haskell Platform inside Ubuntu VM and realize it is 8.0.x version.
- Run following command to install Stack inside Ubuntu.
curl -sSL https://get.haskellstack.org/ | sh # update stack stack update
- Install Haskell ghc 8.4.3 inside Ubuntu.
- Download
ghc-8.4.3-x86_64-deb9-linux.tar.xz
and unzip it - Extract with:
tar xf ghc-8.4.3-x86_64-deb9-linux.tar.xz
- cd to ghc-8.4.3 and run:
sudo make install
- ghc will be in
/usr/local/lib/ghc-8.4.3/bin
my Ubunut
- Download
0.0.112 Ubuntu: Finally AronModule can be built in Ubuntu with Stack, it is not true, there is still issue with regex-tdfa out of memory in my Ubuntu vm.
- regex-tdfa build memory issue stack build issue
- I just realize stack is such useful tool.:)
- Specify the package names in myproject.cabal file and stack build and stack exec myproject.
- Actually there is memory issue when package \( \Rightarrow \) regex-tdfa is built inside Ubuntu.
- Change the resolver is not resolved the out of memory issue.
- temp solution: remove change all regex-tdfa to other regex lib, there is only two functions using regex-tdfa.
- It can be built in Ubuntu vm now.
0.0.113 Ubuntu: Add RSA keys to Ubuntu and FreeBSD hosts, Public key, ssh public key, ssh key
- When you dump your public key to your swesome host, you will be asked your password again.
- You are wondering WTF?.. do you use the wrong key? do I mess up the public and private key?, do I have the right permission?
- You will get lots of questions and you have no idea where to check and how to find the answers.
- The catch is to
cat your public key to
authorized_keys
cat ~/.ssh/mypublickey.pub >> authorized_keys
If you are on MacOS, you will find more pain. You need to add your private key to key chain
- When your public and private keys do not work. you have no idea what to do.
ssh-add /home/name/.ssh/privateKey~
0.0.114 Ubuntu: Add shell script to upload file to Ubuntu and FreeBSD hosts
- script name:
$sym/upload.sh
\( \Rightarrow \)$src/upload.sh
using rsync command. - upload.sh
# upload file.txt to xfido ~/try upload.sh file.txt xfido # upload file.txt to uwspace ~/try upload.sh file.txt uw
0.0.115 Ubuntu: GHC run out of memory in Ubuntu 1G RAM GHC out of memory
- GHC build package can take lots of memory sometimes.
- Run
stack build
and out of memory error in Ubuntu 1G RAM But it works on FreeBSD 3G RAM.
Cabal > ghc: internal error: Unable to commit 1048576 bytes of memory Cabal > (GHC version 8.6.5 for x86_64_unknown_linux) Cabal > Building library for Cabal-2.4.1.0..
0.0.116 Ubuntu: Change web host from Ubuntu 1G to FreeBSD 3G
0.0.117 Ubuntu: Add user to Ubuntu
sudo adduser david # add password sudo passwd david
0.0.118 Ubuntu: Add user to sudo file
vi /etc/sudoers
new_user ALL=(ALL:ALL) NOPASSWD:ALL
0.0.119 Ubuntu: Install Haskell Platform
sudo apt-get install haskell-platform
0.0.120 Ubuntu: Install Haskell Stack
curl -sSL https://get.haskellstack.org/ | sh
0.0.121 Ubuntu: Install Apache Server
0.0.122 Stack will not always solve problems for you.
- I just spend a lots of time on building my Application \(\Rightarrow\) wai.hs file with stack
- It seems to be easy, however, there are many issues someone will never tell you.
- Put the package name on your cabal file is not always working.
- Sometimes you need to put a missing package to stack.yaml file, I'm not sure why.
- Check the Stack Tool for more detail.
0.0.123 Why your public key not working in Github: Error Permission denied (publickey)
- ssh DOES NOT try all private keys in
.ssh
actuallyI always though ssh will try all private keys under
.ssh
but it is not..surprisedly- ssh only tests keys such as
id_rsa
and other well known keys - debug ssh public key
~/.ssh/my_key.pub ssh -T -vv git@bitbucket.org # debug ssh public key # ssh will not use my_key.pub
- ssh only tests keys such as
- When you generate your public and private key with ssh-keygen
My Mac public key My public key
- You need to do the following: host and client
Generate private and public key pair. No host name with
ssh-keygen -C noname
If you don't want to show your host in the public key file, you can use following optionssh-keygen -C noname
- Add ssh private key to Agent
- Add public key to
authorized_keys
with permissin:chmod 600 authorized_keys
# generate private and public keys ssh-keygen -C noname # Your host name will NOT be included inside the public key. # Add private key to agent ssh-add /home/user/.ssh/myrsa # On client side, add public key to authorized_keys cat id_rsa.pub >> autherized_keys # set permission chmod 600 autherized_keys
0.0.124 Remove IP Address from our SSH, ssh-keygen
Remove all keys from knownhosts file if you get following message
The fingerprint for the RSA key sent by the remote host is Please contact your system administrator. Add correct host key in /Users/user/.ssh/known_hosts to get rid of this message. Offending ECDSA key in /Users/user/.ssh/known_hosts:20 RSA host key for host_IP has changed and you have requested strict checking. Host key verification failed.
ssh-keygen -R host_IP
0.0.125 Bought a FreeBSD VM 3G, 60G from Digit Ocean for $15.
- Install GHC 8.6, and install stack
Install Stack Install Stack in FreeBSD
# install GHC pkg install ghc # install haskell stack curl -sSL https://get.haskellstack.org/ | sh
0.0.126 FreeBSD install package
# su root pkg install curl
0.0.127 FreeBSD apache html folder
/usr/local/www/apache24
0.0.128 FreeBSD install GHC
pkg install ghc
0.0.129 Rename haskellwebapp \( \Rightarrow \) haskellwebapp2
- Create bitbucket repos: haskellwebapp2
- Rename the Stack project \( \Rightarrow \) in .cabal file.
The root of running process is not src, it is haskellwebapp2
haskellwebapp2/src/Main.hs
0.0.130 Mysql example
Connect to Mysql on my MacOS
# start mysql on MacOS /usr/local/bin/mysql.server start mysql -u root
Mysql commands
show databases; => show all the database; show tables; => show all the tables in current db use mydatabase; => use the mydatabase desc mytable; => show schema of mytable
Create Table
DROP TABLE image; CREATE TABLE image( id INTEGER NOT NULL AUTO_INCREMENT, path TEXT NOT NULL, PRIMARY KEY(id) );
Insect data to table
INSERT INTO image(path) VALUES("/tmp/file.png");
SELECT all fields in Mysql
SELECT * from image;
0.0.131 Mysql Regex
mysql regex
- Select all strings end with
.txt
SELECT path from testtable1 WHERE PATH REGEXP '(.txt$)';
- Select all strings end with
query contains string
# String contains 'javac' SELECT path from tablepath WHERE path LIKE '%javac%'; # String ends with 'javac' SELECT path from tablepath WHERE path LIKE '%javac';
query contains '.stack-work~
SELECT path from tablepath WHERE path LIKE '%.stack-work%' # SELECT path from tablepath WHERE path LIKE '%\.stack-work%'
0.0.132 Mysql batch insert
- batch insect to Mysql server
- Mysql Batch Insert
LOAD DATA INFILE
0.0.133 Mysql Yep, you can merge two Mysql tables
0.0.134 Sqlite3 Primary Key and Foreign Key
CREATE TABLE IF NOT EXISTS ShellHistory DROP TABLE IF EXISTS ShellHistory CREATE TABLE IF NOT EXISTS ShellHistory( id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, address_id INTEGER, FOREIGN KEY (address_id) REFERENCES address (address_id) ); CREATE EATE TABLE IF NOT EXISTS addresses ( address_id INTEGER PRIMARY KEY, house_no TEXT, street TEXT, city TEXT, postal_code TEXT, country TEXT );
0.0.135 Create User and Image tables in Sqlite3 database.
Connect to Sqlite3
sqlite3 /Users/cat/myfile/bitbucket/testfile/test.db
- Submit submit form.
Database User table in Sqlit3 Data Type
uid name email password task money Integer Text Text Text Text Integer Database Image table
iid imagename uid Integer Text Integer - Sqlite3 Regex, LIKE operator with two wildcards pattern:
- % zero or more wildcard
_ one single character
# select all files that contains word vector select * from pdftable where path = '_%vector_%'
- Sqlite3 Commands
show table, show schema, show description, dump table to file
.table => show tables .schema => show schema .schema mytable => show mytable schema, like description in MySql .dump => dump table or datbase to file .help => help command
Create Haskell records. Haskell Int64 \( \Rightarrow \) Sqlit3 Integer
-- Data.Int64 (Int64) -- Haskell Int64 => Sqlit3 Integer data User = User{uid::Int64, name::Text, email::Text, password::Text task::Text, money::Integer} deriving (Show, Eq) data Image = Image{iid::Int64, imagename::Text, uid::Int64} deriving (Show, Eq)
How to determinate whether insection is successful or failed
- Count the number of rows modifed in Sqlite.
- changes Sqlite3 Haskell
changes :: Database -> IO Int
query_ conn "insect ... " changeRow <- changes conn if changeRow > 0 then print "Insection is successful" else print "Insection is failed"
0.0.136 Haskell Sqlite3, Simple Example to show how to connect to database, create table, insect data, create record, map record to table.
- Full Source Code can be used as Haskell Sqlite3 Database.
Import package to use Sqlite3 database
{-# LANGUAGE OverloadedStrings #-} import Data.Int (Int64) import Database.SQLite.Simple import Database.SQLite.Simple.FromRow import Database.SQLite.Simple.FromField import Database.SQLite.Simple.ToField import Database.SQLite.Simple.Internal import Database.SQLite.Simple.Ok import qualified Data.Text as TS -- TS.Text import AronModule -- toSText
Create Haskell Record which maps to Sqlite3 table
data ShellHistory = ShellHistory { shId :: Int64 , shcmd :: TS.Text } deriving (Eq,Read,Show)
Sqlite3 convert Record field to Column and from Column to field as long as you instance your record ToRow and FromRow
-- import Database.SQLite.Simple.FromRow -- two fields: shId, shcmd instance FromRow ShellHistory where fromRow = ShellHistory <$> field <*> field -- import Database.SQLite.Simple.ToRow instance ToRow ShellHistory where toRow (ShellHistory _uid shcmd) = toRow (Only shcmd)
Create a table called ShellHistory
-- Need Query type -- Query{ fromQuery :: TS.Text } let sql_create_table = Query{ fromQuery = toSText "CREATE TABLE IF NOT EXISTS ShellHistory (id INTEGER PRIMARY KEY AUTOINCREMENT, shcmd TEXT)" } let sql_select = Query { fromQuery = toSText "SELECT id, shcmd FROM ShellHistory" }
Create Connection, and Connect to Sqlite3 with open
let dbfile = "/Users/cat/myfile/bitbucket/testfile/ShellHistory.db" conn <- open dbfile
Execute query, Create table, Insert data to table, Select query from table
execute_ conn sql_create_table -- insert data to table let mystr = "mycmd1"::String let query = Query { fromQuery = toSText "INSERT INTO ShellHistory (shcmd) VALUES (?)" } execute conn query (ShellHistory 0 (toSText mystr)) cmdsql <- query_ conn sql_select ::IO [ShellHistory] let cmdList = let ls = map (shcmd) cmdsql::[TS.Text] in map toStr ls::[String]
- Again, use Data.RawString.QQ to simplify the String, ByteString and Text manipulation.
- Add response page if insertion is successful using Data.RawString.QQ again
- Add list task page
0.0.137 Add login and password validation page.
- Add html login.html file, it is easy.
Add
loginCheck::Connection -> Application
- The function tries to validate email address and password.
- Use queryNamed queryNamed , there is some issues to query any row from user table.
queryNamed :: FromRow r => Connection -> Query -> [NamedParam] -> IO [r] r <- queryNamed c "SELECT * FROM posts WHERE id=:id AND date>=:date" [":id" := postId, ":date" := afterDate]
- Finally I found the issue when using
where
cause in Sqlite Haskell.
- I used ByteString to compare
String
orText
r <- queryNamed conn "SELECT * FROM user where password = :password" [":password" := password] :: [User]
password
is a type ToField class which converts almost any type to SQLData with toField- I used ByteString instead of String or Text
- Here is stupid mistaken that I made.
-- Using ByteString "123" to compare Text -- Error code let password = case lookup "password" params of Just password -> password _ -> "No password from client." -- need to convert ByteString to Text and compare -- Valid code let password = case lookup "password" params of Just password -> strictByteStringToStrictText password _ -> "No password from client."
- The function tries to validate email address and password.
0.0.138 Word8 and ByteString in Haskell.
- Word8 is unsigned integer 8-bits byte. Word8
ByteString contains 8-bit bytes.
-- ls contains all character from 0 to 2^8 - 1 = 255 let ls = Data.Word8.pack [0..(2^8 - 1)]
0.0.139 C++ Dangling pointer Dangling Pointer
void remove(){ Node* curr = new Node(10); Node* pt = curr; if(curr != null) delete curr; }
pt
is a dangling pointer, there is nothing wrong with dangling pointer as long as you don't deference a dangling pointer.
0.0.140 What is unique pointer, shared pointer and weak pointer and what is std::move in C++
- Smart Pointer Example
- Smart pointer is trying to help programmers to simplify memory management. Before smart pointer, programmer needs to know when to allocate memory and when to deallocate memory.
What is unique pointer?
- unique pointer does not support copy, if you copy a unique pointer, then you will get compiler error.
// no memory leak void fun(){ std::unique_pt<int> pt = std::unique_pt(new int(10)); return; } std::unique_pt<int> pt = std::unique_pt(new int(9)); std::unique_pt<int> pt1 = pt; // Compiler ERROR, call to implicitly-deleted copy constructor of 'std::unique_ptr<int>'
Use
std::move
to change the ownership of anstd::unique_ptr
{ std::unique_ptr<int> ptr1 = std::unique_ptr<int>(new int(10)); std::unique_ptr<int> ptr2 = std::move(ptr1); fw("*ptr2"); pp(*ptr2); fw("*ptr1"); pp(*ptr1); // ERROR } { std::unique_ptr<int> ptr1 = std::unique_ptr<int>(new int(10)); std::unique_ptr<int> ptr2 = ptr1; // ERROR }
Use
std::move
to movestd::string
tostd::vector
push_back(const T& val); // copy the value push_back(T&& val); // move val to new value
std::string s0{"abcd"}; std::string s1{"efgh"}; std::vector<std::string> vec; vec.push_back(s0); vec.push_back(std::move(s1)); for(auto& e: vec){ std::cout<<e<<std::endl; } std::cout<<"s1 std::move to vec => "<<std::quoted(s1)<<std::endl;
How to use shared pointer?
class MyClass{ public: std::shared_pt<int> pt; public: std::shared_pt<int> create(){ std::shared_pt<int> pt = std::shared_pt(new int(9)); return pt; } } MyClass* cpt = new MyClass(); std::shared_pt<int> pt = cpt -> create(); if(cpt != null) delete cpt; // std::shared_pt<int> pt don't need to be deleted inside the MyClass
- What is weak pointer in C++
- Weak pointer is a shared pointer and it holds a non-owning reference to an object.
0.0.141 Change all paths in WaiLib.hs and Wai.hs, and it run in FreeBSD so far.
- Change symbol link to relative path, solve only half the problem.
- DONE Add config file.
- DONE Change localhost to real hostname.
- DONE Install Redis on FreeBSD
0.0.142 In FreeBSD, /usr/ports/database
is not shown.
- download port collections
portsnap fetch
and extract it to/usr/ports
- Here is the link on how to use use port in FreeBSD port
0.0.143 Install Redis in FreeBSD Redis installation on FreeBSD
0.0.144 Haskell Enum Trick Enum Trick
data Color = Red | Blue | Green | Yellow | Orange | Brown | White | Black deriving (Show, Eq, Enum, Bounded)
0.0.145 Show Maybe is a Functor Functor Maybe Proof
0.0.146 Haskell: Applicative and Functor
- Good tutorial in Applicative Functor Applicative
- Applicative definition is very confusing initially. But if you understand Functor, then it is very easy to grasp the idea. because they are very similar.
Let's see the Functor definition in Haskell
class Functor f where return a -> f a fmap :: (a -> b) -> f a -> f b
- It says fmap need a function and Functor type
f a
and return a Functor typef b
(f is Functor) here. - Let see the Applicative definition in Haskell Appliactive
- It says fmap need a function and Functor type
class (Functor f) => Applicative f where pure a -> f a <*> :: f (a -> b) -> f a -> f b
Applicative satisfied a few laws:
-- Associative -- Compositon -- Identity -- Interchange -- Homomorphic -- F (f . g) = F(f) . F(g)
- Above definition says that
<*>
can apply a function inside the Functor to a value inside a Functor It is very similar to fmap which is apply a plain function inside the value of Functor
0.0.147 Move GenePDFHtml to WaiLib.hs file, Create a GenePDFHtmlLib in $b/haskelllib
0.0.148 Refactor function in WaiLib
app::Connection -> IORef M.HashMap -> Application
- Remove the extrac database connection from above function
- One database includes all tables.
0.0.149 Change Emacs Org-mode with solarized theme with CSS file Emacs Org-mode Solarized Theme
- If you use thomasf.github.io code snippet for Org-mode, then you will have problem to display the html file.
- I have no idea what the javascript does. After I remove the Javascript code, it works perfectly.
- It means you do not need the Javascript code on your Org-mode.
- At least it works in SpaceEmacs 8.x under Chrome, Safari and Firefox.
-- light mode #+HTML_HEAD: <link rel="stylesheet" type="text/css" href="http://thomasf.github.io/solarized-css/solarized-light.min.css" /> -- dark mode #+HTML_HEAD: <link rel="stylesheet" type="text/css" href="http://thomasf.github.io/solarized-css/solarized-dark.min.css" />
- You DO NOT need the following snippet on your Org-mode, it will screw up your Html after you export Org-mode to Html.
#+INFOJS_OPT: view:t toc:t ltoc:t mouse:underline buttons:0 path:http://thomasf.github.io/solarized-css/org-info.min.js
0.0.150 Change the width of center theme on the current theme.
-- max-with 23cm; => max-width: 30cm; body { background-color: #002b36; margin: 0 auto; max-width: 30cm; border: 1pt solid #586e75; padding: 1em; }
0.0.151 Add install.sh to each stackproject project
- copy binary file to mybin dir
- create symbo link to $sym dir
- create simple shell script under $scr
0.0.152 Change default shell in FreeBSD change shell
- Apparently freeBSD default shell is not bash but sh and you need to change it if you did not want all the annoyance.
- Also you need to make sure your shell is in
/etc/shells
See the difference between bash and sh in bash and sh
chsh -s /usr/local/bin/bash
0.0.153 Non-interactive shell and interactive shell, login shell, non-login shell.
- URL SO
Check whether your current shell is interactive or not
# non interactive echo $- # hBC #interactive echo $- # himBHs
Check login shell or not
shopt login_shell
- Interactive shell is the first process Id when you login to an interactive session.
- Read
/etc/profile
to setup environment variables, also read.bashrc, .profile
on your home directory if there exist.
- Read
Non-interactive shell does not read
/etc/profile
, e.g.ssh xxx@xfido.com 'ls'
- ssh logins to cat user account but the process does not activate any shell such as
bash
and there is no environment variable.
ssh xxx@xfido.com 'bash /etc/profile; echo $PATH' ssh xxx@xfido.com 'source /etc/profile; echo $PATH'
- ssh logins to cat user account but the process does not activate any shell such as
shell-command-to-string is Non-interactive in Elisp
(shell-command-to-string "fileExist /tmp/f.x") ;; command: fileExist can not be found error ;; fileExist is in $scr/AronLib.sh ;; we can source it before use the shell (shell-command-to-string "source $scr/AronLib.sh; fileTimeFull /tmp/f.x") ;;
- ssh login to cat user account and call
bash
to read/etc/profile
. Environment variables can be used if there are any inside/etc/profile
. - login shell is the same as interactive shell.
- non-login shell is the same as non-interactive shell.
0.0.154 Use interactive shell to store all your shell script command in history
If you put
#!/bin/bash -i
on top of your shell script, all your shell script commands will be in your history. Enable interactive shell on your shell.- history \(\Rightarrow\) does work because bash is interactive
#!/bin/bash -i history
-i
\(\Rightarrow\) interactive shellnon-interactive shell \(\Rightarrow\) history command does not work.
#!/bin/bash history
Also,
-i
\(\Rightarrow\) enable your shell script can use history command, otherwise history CAN NOT be used in your shell script.-c clear all histories -d offset, history -d 20 => delete line 20 -a append current history to history file -n read all history lines not already read from the history file and append them to the history list -r read the history file and append the contents to the history list -w write currenty history to history file -p !100:p => expand it without storing it in history list -s append the ARGs to the history list as a single entry, no idea what does it mean?
0.0.155 Add new tmux.conf
file for FreeBSD. Apparently the tmux.conf
file is not working on MacOS.
- Both version are 2.9a
- tmux config file for FreeBSD and MacOS
0.0.156 Fixed: Javadoc long term error: can not find methods. Javadoc Reference Guide
/dir/lib
contains jar file to support java source file under/javafile
- -classpath \(\Rightarrow\) specified the location of jar files
- -noqualifier \(\Rightarrow\) no long qualifier name such as org.apache.commons.io.StringUtils
- -sourcepath \(\Rightarrow\) specified the location of java files.
javadoc -classpath /dir/lib -noqualifier all -d /htmldoc -sourcepath /javafile/*.java
- Shell script generates java doc in $b/javalib My genejavadoc.sh
0.0.157 Add iterate all files from dir and insert them into table: test1.snippet
0.0.158 Add isFile and isDir to javalib AronLib.java
0.0.159 Database ACID
- Atomicity
- Consistency
- Isolation
- Durability
0.0.160 Fixed bug: send pdf file to browser and force the browser to open it. What request header I should use?
- Make sure you clean your cache on Chrome.
- Http Header W3 Org
Wai Network.HTTP.Type.Header,
Content-Type, Content-Disposition
[("Content-Type", "application/pdf"), ("Content-Disposition", "inline;filename=file.pdf")]
0.0.161 Add code to display all PDF files from a directory in Wai Server.
- Use
pathInfo
instead ofrawPathInfo
Use Haskell powerful pattern matching.
case pathInfo request of ("pdf":fn:_) -> routing to whatever you want
0.0.162 Wai API for query string, it is nice function to match string from client
- If the request string is
/dir/file.pdf
pathInfo can be used to (split ⇒ splitBS) BS.ByteString info parts and pattern matching can be used in different parts.
pathInfo::BS.ByteString -> [Text] case pathInfo request of ("pdf":_) -> routing to "http://xfido.com/pdf" ("pdf":fn:_) -> routing to "http://xfido.com/pdf/myfile.pdf" _ -> routing to "other universe"
0.0.163 Understand logic implication table
- Why implication and contrapositive table defines the way it is?
P | Q | \(P \Rightarrow Q\) | \(Q^\lnot\) | \(P^\lnot\) | \(Q^\lnot \Rightarrow P^\lnot\) |
---|---|---|---|---|---|
T | T | T | F | F | T |
T | F | F | T | F | F |
F | T | T | F | T | T |
F | F | T | T | T | T |
- Example: If \(a^2 + b^2 = c^2 \Rightarrow a, b, c\) forms a right triangle. Pythagorean Theorem
- If \(a, b, c\) are not a right triangle \(\Rightarrow a^2 + b^2 \neq c^2\)
- \(n \in \mathbf{N} \rightarrow 2n \in \mathbf{N}\) \(\Rightarrow\) if \(2n\) is not an integer then \(n\) is not \(\mathbf{N}\)
- \((P \rightarrow Q) \Rightarrow (Q^\lnot \rightarrow P^\lnot)\)
0.0.164 Why Lombok sucks? please read the Reddit Lombok in Reddit
- You are likely missing the plugin in Intellij if you use Lombok to generate setter and getter.
- You will spend more time on debugging the Lombok than writing code.
- Setter, Getter, Equal, toString and hashCode methods can be generated from IDE.
- In practice, you don't use those methods that often.
0.0.165 Haskell code to generate latex code tryfm.hs
A | \(\mathscr{A}\) | \(\mathfrak{A}\) | a | \(\mathscr{a}\) | \(\mathfrak{a}\) |
B | \(\mathscr{B}\) | \(\mathfrak{B}\) | b | \(\mathscr{b}\) | \(\mathfrak{b}\) |
C | \(\mathscr{C}\) | \(\mathfrak{C}\) | c | \(\mathscr{c}\) | \(\mathfrak{c}\) |
D | \(\mathscr{D}\) | \(\mathfrak{D}\) | d | \(\mathscr{d}\) | \(\mathfrak{d}\) |
E | \(\mathscr{E}\) | \(\mathfrak{E}\) | e | \(\mathscr{e}\) | \(\mathfrak{e}\) |
F | \(\mathscr{F}\) | \(\mathfrak{F}\) | f | \(\mathscr{f}\) | \(\mathfrak{f}\) |
G | \(\mathscr{G}\) | \(\mathfrak{G}\) | g | \(\mathscr{g}\) | \(\mathfrak{g}\) |
H | \(\mathscr{H}\) | \(\mathfrak{H}\) | h | \(\mathscr{h}\) | \(\mathfrak{h}\) |
I | \(\mathscr{I}\) | \(\mathfrak{I}\) | i | \(\mathscr{i}\) | \(\mathfrak{i}\) |
J | \(\mathscr{J}\) | \(\mathfrak{J}\) | j | \(\mathscr{j}\) | \(\mathfrak{j}\) |
K | \(\mathscr{K}\) | \(\mathfrak{K}\) | k | \(\mathscr{k}\) | \(\mathfrak{k}\) |
L | \(\mathscr{L}\) | \(\mathfrak{L}\) | l | \(\mathscr{l}\) | \(\mathfrak{l}\) |
M | \(\mathscr{M}\) | \(\mathfrak{M}\) | m | \(\mathscr{m}\) | \(\mathfrak{m}\) |
N | \(\mathscr{N}\) | \(\mathfrak{N}\) | n | \(\mathscr{n}\) | \(\mathfrak{n}\) |
O | \(\mathscr{O}\) | \(\mathfrak{O}\) | o | \(\mathscr{o}\) | \(\mathfrak{o}\) |
P | \(\mathscr{P}\) | \(\mathfrak{P}\) | p | \(\mathscr{p}\) | \(\mathfrak{p}\) |
Q | \(\mathscr{Q}\) | \(\mathfrak{Q}\) | q | \(\mathscr{q}\) | \(\mathfrak{q}\) |
R | \(\mathscr{R}\) | \(\mathfrak{R}\) | r | \(\mathscr{r}\) | \(\mathfrak{r}\) |
S | \(\mathscr{S}\) | \(\mathfrak{S}\) | s | \(\mathscr{s}\) | \(\mathfrak{s}\) |
T | \(\mathscr{T}\) | \(\mathfrak{T}\) | t | \(\mathscr{t}\) | \(\mathfrak{t}\) |
U | \(\mathscr{U}\) | \(\mathfrak{U}\) | u | \(\mathscr{u}\) | \(\mathfrak{u}\) |
V | \(\mathscr{V}\) | \(\mathfrak{V}\) | v | \(\mathscr{v}\) | \(\mathfrak{v}\) |
W | \(\mathscr{W}\) | \(\mathfrak{W}\) | w | \(\mathscr{w}\) | \(\mathfrak{w}\) |
X | \(\mathscr{X}\) | \(\mathfrak{X}\) | x | \(\mathscr{x}\) | \(\mathfrak{x}\) |
Y | \(\mathscr{Y}\) | \(\mathfrak{Y}\) | y | \(\mathscr{y}\) | \(\mathfrak{y}\) |
Z | \(\mathscr{Z}\) | \(\mathfrak{Z}\) | z | \(\mathscr{z}\) | \(\mathfrak{z}\) |
0.0.166 Anonymous function in c++ and Lambda function in Haskell.
- Pass lambda function to a function in C++.
- Use std::function to define a function called even
Create a filter function similar to Haskell filter
std::function<int(bool)> even = [](auto x) = { return x % 2 == 0;}; template<class T> vector<T> filter(std::function<bool(T)> f, vector<T> vec){ vector<T> retV; for(auto t : vec){ if(f(t)) retV.push_back(t); } } vector<int> vec = {1, 2, 3}; vector<int> vecInt = filter(even, vec);
But you can not do following:
vector<int> vec = {1, 2, 3}; auto f = [](auto x){ return x % 2 == 0;}; vector<int> filter(f, vec);
- \( \because \)
auto f
is not the same type asstd::function
- \( \because \)
Use
template<typename Fun, typename T>
to solve above limitation.template<typename Fun, typename T> vector<T> filter(Fun f, vector<T>& vec){ vector<T> retv; for(auto e : vec){ if(f(e)) retv.push_back(e); } return retv; }
We can pass
auto f=...
orstd::function<bool(T)> f = ..
to the new filter function.auto f = [](auto x) { return x % 2 == 0;}; // or std::function<bool(T)> f = [](auto x){ return x % 2 == 0;}; vecotor<int> vec = {1, 2, 3}; vector<int> filter(f, vec);
- Some comments suggest the following code Lambd Function in C++
auto f = [](auto x) { return !(x & 1);}; // nice, but it might introduce bug in the future. // e.g. if I need module of 3, 5, ..., the whole function needs to be rewritten.
In Haskell, the solution is much more elegrant.
let list = [1, 2, 3]; filter(\x -> x `mod` 2 == 0) list
- std::transform is similar to map in Haskell.
But std::transform is too verbal, e.g.
vector<float> vec = {1.2, 4.9}; std::transform(vec.begin(), vec.end(), vec.begin(), [](auto x) { return x + 1;}); // vec = {2.2, 5.9}
In Haskell
let vec = [1.2, 4.9] let v = map (+1) vec
If we want to convert all the floats to strings.
vector<float> vec = {1.2, 4.9}; vector<string> vecStr; std::transform(vec.begin(), vec.end(), std::back_inserter(vecStr), [](auto x) { return std::to_string(x); } ); // vecstr contains strings
- I still have no idea what is std::backinserter() from the doc.std::backinserter
- I assume std::backinserter() all the return value from lambda function from the beginning of iterator
I try to implement mapX function like map in Haskell.
template<typename Fun, typename T, typename D> vector<D> mapX(Fun f, vector<T> vec){ std::vector<D> vecD; std::transform(vec.begin(), vec.end(), std::back_inserter(vecD), f); return vecD; }
- But it seems to me typename D can not deducted from \(\lambda\) function Fun \(f\)
- Some users suggests me to use some C++17 features C++17 typetraits
0.0.167 C++ return by reference or return by value.
- Wrong way to use reference in C++
// return by reference. vector<int>& fun(){ vector<int> vec = {1, 2, 3}; return vec; } vector<int> v = fun();
- Why the code above is wrong?
- fun() only returns the address of vec, not a copy of vec
- After the function fun() return, object vec will be deleted because vec is local variable and it is inside the stack. The caller will lose the data in vec.
- v hold the address to vec, but the data inside vec will be deleted after fun() return.
- copy constructor will be called to do the copy for vector<int>
// return by value. vector<int> fun(){ vector<int> vec = {1, 2, 3}; return vec; } vector<int> v = fun();
- Code above is OK beacuse fun() return a copy of vec
- v will have the copy of vec
0.0.168 Return by reference or const reference
- What is the different between return
const int& fun()
andint& fun()
in a function. const int& fun()
\( \Rightarrow \) it means you can assign value tofun()
int& fun()
\( \Rightarrow \) it means you can NOT assign value tofun()
int& fun(){ int var = 1; return var; } // in main fun() = 3; // OK, does not do anything useful. const int& fun(){ int var = 1; return var; } // in main fun() = 3; // Error: can not assign value to const int& which is rvalue I think.
return by reference is useful if you overload [] operator on an array of objects.
class Object{ int num; }; class ArrayObject{ Object& operator[](const int& index); } // in main Object o(); arrayObj[1] = o;
0.0.169 Passed by value and reference or const reference
Passed by value:
vector<int> even(vector<int> vec){ vector<int> ret; for(auto e : vec){ ret.push_back(e); } return ret; }
- vec will be copied inside the stack, if vec contains lots of data, then it will be not very efficient.
Passed by reference, vec passes it memory address to function even()
vector<int> even(vector<int>& vec){ vector<int> ret; for(auto e : vec){ ret.push_back(e); } return ret; } // inside your main vector<int> vec = {1, 2, 3}; even(vec) // no problem.
- Code above is better because vec will not be copied inside the function even(). even() will use the address of vec to access the data in vec.
Passed non-constant reference to a function.
- vector<int>& is non-constant reference \( \Rightarrow \) I hope this is the right name.
vector<int> even(vector<int>& vec){ vector<int> ret; for(auto e : vec){ ret.push_back(e); } return ret; } vector<int> fun(){ vector<int> v = {1, 2, 3}; return v; } // inside your main even(fun) // compile error
Apparently, fun return a
const vector<int>&
but notvector<int>&
- In order to make above code to work, the signature of
even(..)
has to be changed as following:
vector<int> even(const vector<int>& vec)
- Signature above is not a perfect solution and following code will not work.
- In order to make above code to work, the signature of
- vec can be modified.
vector<int> vec = {1, 2, 3}; void fun(const vector<int>& vec){ vec.push_back(1); }
0.0.170 Find the square root of a float point number: \(n\)
- The idea is to find the square root of a float point number is equivalent to solve a equation \(n = x^2\) where \(n\) is given, find \(x\)
- Choose a point \( x = x_0 \) from \( y = x^2 - n \) where \( y = 0 \)
- We know the derivative of \( y = x^2 - n \) is \(2x\), then we can find the slop \(2x_0\) of a line which passes a point \( (x_0, (x_0)^2 - n)\)
- The equation of the line is
- \( \frac{y - (x_0^2 - n)}{ x - x_0} = 2x_0 \Rightarrow \frac{y - (x_0^2 - n)}{2x_0} = x - x_0 \)
- where \(y = 0 \Rightarrow x = x_0 + \frac{n - x_0^2}{2x_0} \Rightarrow x_1 = x_0 + \frac{n - x_0^2}{2x_0} \)
C++ code: Square Root of Integer
/*** * * Newton' method to find the square root of any positive float point number. */ double sqrt(double n){ double x0 = n + 10; double x = x0; while(fabs(x*x - n) > 0.00000001){ x = x + (n - x*x)/(2*x); } return x; }
0.0.171 Find the nth root of a float point number: \(c\)
- Same idea can be used from above.
- let \(x_0\) is the initial point and we try to solve \( c = x^n \Rightarrow f(x) = x^n - c \) where \( f(x) = 0 \)
- The derivative of \( f(x) \) is \( nx^{n-1} \)
- A line passes \( (x_0, f(x_0) \) and its slop is \( nx^{n-1} \)
- The line equation is \( f'(x_0) = n(x_0)^{n-1} = \frac{y - f(x_0)}{x - x_0} \)
- \( \Rightarrow x = x_0 - \frac{f(x_0)}{n(x_0)^{n-1}} \) where \( y = 0 \) because we need to solve \( 0 = x^n - c \) for \(x\)
- Search nthRoot in C++
0.0.172 Change the file GenePDFHtml.hs file, but it can not be built any more.
The project in $HOME/try/hs can be built, and one in FreeBSD can be built too. The old the version should not be used any more because many cods has been changed.
0.0.173 Haskell record is function essentially
- Example:
data Any = Any {getAny::Bool} let f = Any :i f : f::Bool -> Any let rf = getAny :i rf rf::Any -> Bool
- Get the identity function
let g = f . rf g::Bool -> Bool -- other identity function let h = Any . getAny :i h::Any -> Any
0.0.174 How to check whether there a table exist in Sqlite in Haskell.
- Our example tries to check whether a table mytable is in a database.
From SO, you can use following select statement from
sqlite_master
table to find out.-- SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}'; -- {} should not be there. SELECT name FROM sqlite_master WHERE type='table' AND name='table_name';
The the schema of sqlitemaster is as following
CREATE TABLE sqlite_master( type text, name text, tbl_name text, rootpage integer, sql text );
- From Sqlite documentation Doc
- A record needs to be created.
Record SqliteMaster needs to implement two instance
FromRow, ToRow
data SqliteMaster = SqliteMaster { x_type::Text, x_name::Text, x_tbl_name::Text, x_rootpage::Integer, x_sql::Text } deriving(Eq, Read, Show) instance FromRow SqliteMaster where fromRow = SqliteMaster <$> field <*> field <*> field <*> field <*> field instance ToRow SqliteMaster where toRow (SqliteMaster x_type x_name x_tbl_name x_rootpage x_sql) = toRow (x_type, x_name, x_tbl_name, x_rootpage, x_sql)
Execute a query and count the row
let query = Query([r| SELECT * FROM sqlite_master WHERE type='table' AND name='mytable' |]) listTab <- query_ conn query :: IO [SqliteMaster] if length listTab > 0 then print "mytable is found" else "mytable is not found"
0.0.175 Haskell Database connection code in three databases: Sqlite, Mysql and Postgresql
- Database connection in Haskell Connection code
0.0.176 Fixed error inside javadoc script with -classpath
# it works. javadoc -classpath "/somejar/*:/MyClass:." # it does not work. javadoc -classpath /somejar/* ...
0.0.177 Xcode: gcc clang c++ compiler flags, cpp compile, xcode compiler: Reference
- C++ build script cppcompile.sh
- Add include or multiple includes paths.
\( \mathbf{-I} \Rightarrow \) specifify a <include> directory
g++ -I/myinclude -o myfile myfile.cpp # multiple includes g++ -I/include1 -I/include2 -o myfile myfile.cpp # Use environment variable $clib echo $clib # /Users/cat/myfile/bitbucket/cpplib g++ -I/$clib -I/include1 -I/include2 -o myfile myfile.cpp
\( \mathbf{-l} \Rightarrow \) link to shared library or shared object file such as .dll in Window and .so in Linux .dylib in MacOS
g++ -I$clib -std=c++14 -O3 -Wall -pedantic recurveFileBoost.cpp -lboost_filesystem -lboost_system
gcc link to object file with -lm Ref Code Example
gcc linkedObject.c -o linkedObject -lm
Use \(-L\) to specify lib and \(-l\) to link to shared dynamic library
- rderik.com
- SEE example $g/macos_assembly/hello.asm
# Big Sur 11.5.2 brew install yasm yasm -f macho64 hello.asm ld -L /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib -lSystem -o hello hello.o # ERROR: ld -lSystem -o hello hello.o # ld can not locate the lib path
- \( \mathbf{-L} \Rightarrow \) specificy a <lib> directory
- \( \mathbf{-g} \Rightarrow \) turn on debug(so GDB gives more friendly output)
- \( \mathbf{-c} \Rightarrow \) output an object file (.o)
- \( \mathbf{-o} \Rightarrow \) name the output, executable output directory
- \( \mathbf{-Wall} \Rightarrow \) turn on most warning
- -pendantic or -Wpendantic \( \Rightarrow \) Issues all warning required by ISO C and ISO C++ standard, it issues all warning whenever there are compiler extensions non compilant to ISO C or C++ standard.
- When you use new C++ library, you need to add Header search paths and Library search paths in XCode.
- I try to use C++ boost library and add Header search paths and Library search paths in XCode.
- I still get linking error, symbol not found
- When you get this kind of error, generally you try to Google the error and hopefully you will find the solution.
- It is hard to know what the Xcode is doing behind the sense when you get weird error.
I use home brew to install C++ boost library on my MacOS, the head location and libraries location are:
# header location, *.h /usr/local/Cellar/boost/1.61.0_1/include # libraries location *.dylib and *.a files /usr/local/Cellar/boost/1.61.0_1/lib # 27-12-2020 /usr/local/Cellar/boost/1.72.0_2/include /usr/local/Cellar/boost/1.72.0_2/lib
The recurveFileBoost.cpp can be built with following g++ command line
# file:///Users/aaa/myfile/bitbucket/cpp/recurveFileBoost.cpp cd $b/cpp g++ -std=c++14 -O3 -Wall -pedantic recurveFileBoost.cpp -lboost_filesystem -lboost_system
XCode add include header, library and linker in setting. xcode boost
Add shared libraries to XCode. xcode boost
/Users/cat/myfile/bitbucket/cpplibtest/CppLibTest
Running Example.boost_system, boost_system
are added to XCode Build Setting.
Find Xcode tool chain in MacOS and g++ libraries paths
g++ -print-search-dirs
gcc compile c file,
gcc --help > $t && vim $t
with filterg!/output/d
gcc hello.c -o /tmp/hello
Change cpp compile in Xcode
Compile cpp to dynamic libraries MacOS
g++ -dynamiclib -o mydylib.dylib mylib.cpp g++ client.cpp -L/dir/ -lmydylib
0.0.178 CPP install boost on MacOS
- Install boost on MacOS or Linux
- Download boost boost1750 (current boost version) boost1750
- Unzip or untar it
- Nothing to build, most of Boost libraries are header-only
Goto boost root directory which is the following
$b/cpplib/boost_1_75_0/boost #include <boost/filesystem.hpp>
If you want to use any of separated-compiled Boost libraries, you'll need to acquire library binaries.
cd $b/cpplib/boost_1_75_0 ./bootstrip.sh --help ./bootstrip.sh # => generate $b/cpplib/boost_1_75_0/stage/include, $b/cpplib/boost_1_75_0/stage/lib ./b2 # build ./b2 install # install
- include header and lib dynamic libraries are generated
- How to use include and lib in your CPP code?
- Here is g++ for line project
- It Use dynamic libraries: boostsystem and boostfilesystem
- \( \mathbf{-I} \Rightarrow \) specificy a include directory
- \( \mathbf{-L} \Rightarrow \) specificy a lib directory
- \( \mathbf{-l} \Rightarrow \) specificy dynamic libraries
$boostinclude/stage/include $boostinclude/stage/lib outdir="$ff/runbin/line" run="g++ -I$clib -I$boostinclude -std=c++14 -O3 -Wall -pedantic line.cpp -L$boostinclude/stage/lib -lboost_system -lboost_filesystem -o $outdir"
- How to use boost library in your CPP code
0.0.179 CMake: add include header, add shared libraries (MacOS, CMake –version 3.7.1)
- Working example at
$b/cmake/hello_cmake
- Add include header files
$b/cpplib/AronLib.h
toCMakeList.txt
- Add shared libraries to
CMakeList.txt
- Add boost library: file and filesystem
$b/cmake/hellocmake/CMakeLists.txt
$b/cmake/hello_cmake/CMakeLists.txt
- Best CMake Tutorial
0.0.180 Share local directories in Apache or Virtual Directory in Apache
- Edit the http.config to load modalias
- It seems it does not work so far.
0.0.181 Wrote a simple function to remove whitespaces from file names and directories.
- Recurve from a given directory and use depth first search to traversal.
- If file is found, then use
file.replace(' ', '')
to remove whitespace.- If directory is found, then recurve into the directory.
- If return from a directory, then
dir.replace(' ', '')
- If file is found, then use
0.0.182 Python Random
from random import * random() # float randint(1, 3) # int [1, 3] randrange(10) # random range [0..9]
0.0.183 Python does not have block comment?
- You can comment out block of code in Python?
- Do not understand the rational behind that.
0.0.184 Python file modification timestamp
import os statinfo = os.stat('/tmp') statinfo.st_mtime os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026, st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295, st_mtime=1297230027, st_ctime=1297230027)
0.0.185 Python import your own module in Python in Jupyter Lab
# copy an paste to Jupyter lab import sys sys.path.insert(0,'/Users/cat/myfile/bitbucket/python') import AronLib as a
0.0.186 Python Sort objects in Python
import sys sys.path.insert(0,'/Users/cat/myfile/bitbucket/python') import AronLib as a class Person(): def __init__(self, name, age): self.name = name self.age = age a.line(4) lp = [Person('Rannel', 1), Person('David', 3), Person('Pig', 0)] lp.sort(key=lambda x : x.name) for p in lp: a.pp(p.name) a.pp(p.age)
0.0.187 Python sort string
list = ["1a", "2c", "4k", "2b"] a.line(5) list.sort(key=lambda x : x[1], reverse=False) for s in list: a.pp(s)
0.0.188 Python byte string and normal string or utf-8 string
Convert byte string to utf-8 string
0.0.189 Python has \(\text{red}{stolen}\) many good stuff from other function programming language such as Haskell
- The module itertools contains takewhile, dropwhile and other functions. Those functions are very common \( \text{red}{operation} \) in
programming languags.
- \(\text{red}{takewhile}\) and \(\text{yellow}{dropwhile}\)
import itertools as it ls = [0, 0, 1, 0, 1] print(list(it.takewhile(lambda x : x == 0, ls))) # => [0, 0] print(list(it.dropwhile(lambda x : x == 0, ls))) # => [1, 0, 1]
0.0.190 Python List comprehesion is nice feature in Python. It is very similar like Haskell List Comprehension
-
s1 = [1, 2] s2 = [3, 4] # Cartesian Product of s1 and s2 ls = [(a, b) for a in s1 for b in s2] print(ls)
0.0.191 PYthon Why Python map, filter and reduce or fold are unusual in Python?
- Why do we need the
list()
to wrap the map and filter functions. - Python return iterator instead of a list when use map, filter etc.
list(map(lambda x: x > 1, [1, 2, 3])) list(filter(lambda x: x % 2 == 0, [1, 2, 3]))
reduce is a bit better, or fold in Haskell terminology.
from functools import reduce reduce(lambda acc, x: acc + x, [1, 2, 3], 0) => 7
map can be used like zipWith in Haskell
list(map(lambda x, y: x + y, [1, 2, 3], [3, 4, 5]))
0.0.192 Python There are many nice features in Python
List is awesome. Python list, drop list, take list, reverse list
ls = [1, 2, 3] ls[:1] => [1] ls[1:] => [2, 3] ls[:1] + ls[1:] => [1, 2, 3] ls[:-1] => [1, 2] ls[-1:] => [3] ls[::-1] => reverse [3, 2, 1]
0.0.193 Python read Json file
# '/tmp/p.json contain following {"name": "Bob", "languages": ["English", "Fench"] }
# Python 3+ from pathlib import Path with open('/tmp/p.json') as f: data = json.load(f) # Output: {'name': 'Bob', 'languages': ['English', 'Fench']} print(data)
0.0.194 Python virtualenv installation, create project
- Install Virtualenv
pip3 install --user pipenv
- Initialize project
cd my_project
pipenv install requests
- pipenv is in following dir
/Users/cat/Library/Python/3.8/bin/pipenv
- Create simple project, main.py
import requests response = requests.get('https://httpbin.org/ip') print('Your IP is {0}'.format(response.json()['origin']))
- Run the script using pipenv run:
pipenv run python main.py
- Expect similar output
Your IP is 8.8.8.8
0.0.195 Complex number division
- let \( c \in \mathbb{C} \)
0.0.196 I just learn Complex number has something called rectangular form which is the standard form that is used in high school.
- \( x + y i \) is rectangular form.
- \( r(\cos \beta + i \sin \beta) \) is the polar form
0.0.197 Apparently, Haddock does not generate the right index.html file with many Haskell modules.
- Create an haskelldocindex.html file under
$b/public1file/haskelldoc_index.html
- Symbol link the file to
$ht/../htmlhaskelldoc/index
0.0.198 VSCode has autocomplete out of the box. Is works for java at lease. It seems to me VSCode is can be replaced Vim and Emacs soon.
Keybinding is supper easy. VSCode configure file
If you want to add
ctrl+k
to move your cursor up, then you need to edit your keybinding.json file as following{ "key": "ctrl+k", "command": "cursorUp", "when": "textInputFocus" }
- Edit the keybinding.json file.
- Path to keybinding.json
~/Library/Application\ Support/Code/User/keybindings.json
- Java autocomplete is working for SDK and external jar files.
- I have been the vim user for many years but I never use Java auto complete because it is painful to install those plugins.
VSCode supports autocomplete out of the box so far but I have not tried other libraries. but Java SDE API is working so far. All the following can be autocompleted.
Map<String, String> map = new HashMap<String, String>(); Set<String> set = new HashSet<String>();
- Autocomplete can be used in many languages such as C++, Java and Python.
- It is very easy to configure keybinding.
- You can install many packages like Emacs. searching and click install.
- There are lots of nice themes.
- VSCode is not perfect so far.
- I try to configure VSCode to search inlcude CPP header files.
- First, I try add the
includePath
in the settings.json, but it failed to find my namespace underAronLib.h
- Second, I try to add
c_cpp_properties.json
under .vscode directory and it failed to find header fileAronLib.h
- First, I try add the
- I try to configure VSCode to search inlcude CPP header files.
0.0.199 VSCode. Finally I found out how to add your own jar file to VS Code
- Initially I though the .classfile is in the VS Code workspace directory and VSCode can not detect my own jar file.
- Finally I realize .classpath should be in home directory. I did not see anyone mention that on stackoverflow at all.
- The content of .classfile can be similar the following:
- You need to have xxx.code-workspace file in order to build and compile.
- Stupid thing about VSCode is the directory for jar files has to be called lib under your workspace. No clue.. why.
You might be able to change the name somewhere. Ask MS.
<?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="lib" path="/Users/cat/myfile/bitbucket/javalib/jar"/> <classpathentry kind="lib" path="lib/commons-io-2.5.jar"/> </classpath>
- Actually it is not ture for above .classfile. Apparently it does not need .classfile if there is lib/myjar.jar in the workspace directory.
- I can do autocomplete for my own jar file, but I got compiler error. The error indicates I use older JDK or Runtime environment with newer version class file.
- TODO: No clue how to fix it right now.
- The weird thing is I can use my current java compiler javacompile.hs to compile and run the same source java file.
- It means VSCode uses an older version of java compile which might be java 8 compiler.
Find out all about your java stuff on your machine with following command
java -XshowSettings:properties -version
0.0.200 VSCode Cpp/C++/clang++/g++ development in MacOS
Output executable file, ex: Cpp option -o
- g++ -o HelloWorld HellWorld.cpp
"${fileBasenameNoExtension}",
Cpp Compiler
#MacOS "command" : "clang++" # or "command" : "g++"
Include library
-I /usr/local/Cellar/boost/1.61.0_1/include
- Two Liking libraries:
-lboost_filesystem
and-lboost_system
Here is tasks.json file for MacOS
{ "version": "2.0.0", "tasks": [ { "label": "Build with Clang", "type": "shell", "command": "clang++", "args": [ "-std=c++14", "-stdlib=libc++", "-I /usr/local/Cellar/boost/1.61.0_1/include", "-lboost_filesystem", "-lboost_system", "${file}", "-o", "${fileBasenameNoExtension}", "--debug" ], "group": { "kind": "build", "isDefault": true }, "problemMatcher": [ "$gcc" ] } ] }
- What is on the
tasks.json
- What is on the
c_cpp_properties.json
- It is really painful to setup VSCode to compile Cpp code.
- From SO, you need to setup
c_cpp_properties.json
andtasks.json
- I follow some tutorial in SO but itt is still not working. Unfortunately it is just a "Hello world" with including a library.
- I got following error Error
- Actually when run it in "Run Task", VSCode will run whatever on your current window. VSCode does not know what file they should run.??
- Add linking library to VSCode, adding to tasks.json file with trial and error.
- It works at least.
- Working example under
$b/cpp/vscode/tryreadfile
0.0.201 Try to install setup VSCode for Haskell right now.
- The main objective is to autocomplete Haskell code.
- It does not work for me when I install Haskero inside VSCode, it seems to me I have to install from command line.
- Install Haskero Haskero 1.31
stack build intero --copy-compiler-tool
- Install intero right now. intero
- Find your package Haskero inside your VSCode package Window and Enable Haskero again.
- You need to add your stack project to as workspace in VSCode, this is the most important step.
- It can autocomplete source code so far.
- You can click on stack build, stack run and stack test
0.0.202 Haskell Intero for Emacs.
- Intero is the best package out there for Haskell. Intero
- autocomplete, defintion and type checking
- Intero can autocomplete paths too:)
- Add a few lines to dotemacs file.
(exec-path-from-shell-initialize) (package-install 'intero) (add-hook 'haskell-mode-hook 'intero-mode)
- Open your stack project and you are ready to go.
0.0.203 An 64 years old math problem is solved by a super computer.
- Find an Integer solution for \( x^3 + y^3 + z^3 = 42 \)
- It seems to be an easy problem but no one can find a solution or prove there is no solution for the eqation.
x = -80538738812075974 y = 80435758145817515 z = 12602123297335631 if x**3 + y**3 + z**3 == 42: print("x^3 + y^3 + x^3 = 42") else print("x^3 + y^3 + x^3 != 42")
0.0.204 Terence Tao and Collatz Conjecture
\( f(n) = \begin{cases} n/2 &\quad \mbox{ if n is even} \\ 3n + 1 &\quad \mbox{ if n is odd} \end{cases} \)
- Terence Tao posted a partial solution on Collatz Conjecture
0.0.205 Java boxing and unboxing
int m = 3; Integer n = m; List<Integer> list = new ArrayList<>(); for(int i=0; i<10; i++) list.add(i); // lots of boxing
0.0.206 Apple finally was unveiling iPhone 11, iPhone 11 Pro and iPhone 11 Pro Max without 5G cellular service.
0.0.207 It is almost impossible to clear up browser data from Google Chrome.
- If you want to relod the new CSS file from Chrome. Clear up browser data is not enough.
- I have no clue to reload the new CSS files from Chrome when you try to inspect your html source.
1 VSCode and Python
1.0.1 VSCode For Python on MacOS.
- VSCode supports many languages out there. Python is one of them. VSCode has many nice features.
- VSCode has many nice themes to beautify your code.
- Autocomplete
- Run Test inside your VSCode.
- VSCode can detect all the Python versions on your sytem so that you can choose which version to run you code.
How to run Python inside your VSCode? it is easy.
- Press F1 Key to the Command Pallet and type
Run Python File in Terminal
- Assume you have installed Python interpeter on your machine.
- Press F1 Key to the Command Pallet and type
2 Emacs Elisp Tutorial
2.0.1 Install Common Lisp on MacOS
brew -v install clisp # start Common Lisp clisp # try Common Lisp >(+ 1 2)
2.0.2 Run your lisp script from command line
clisp mylisp.lisp
2.0.3 Emacs Elisp Grab the content of buffer
(buffer-string) ;; With properties (buffer-substring-no-properties (point-min) (point-max)) ;; Without properties
2.0.4 Emacs Elisp write to scratch buffer
Write file: "/tmp/x" to scratch buffer
(with-current-buffer "*scratch*" (erase-buffer) (insert-file-contents "/tmp/x") )
2.0.5 Emacs Elisp call-process
(defun httpx(str) (interactive) (progn (call-process "ls" nil '(:file "/tmp/1.txt") nil "-lah") (message "%s" (runSh "cat /tmp/1.txt")) ) )
- Use call-process to call curl
(progn (setq str "test") (setq curl (concat "http://localhost:8081/snippet?id=o%20" str)) (call-process "/usr/bin/curl" nil '(:file "/tmp/3.txt") nil "-s" curl) )
2.0.6 Emacs Elisp run elisp in specific path
- Export org-mode file to HTML inside $www path
(add-hook 'org-mode-hook (lambda() (interactive) (progn (let (default-directory "/Library/WebServer/Documents/xfido/html" )) (local-set-key (kbd "<f9>") (kbd "C-x C-s C-c C-e h h")) ) ) )
2.0.7 Emacs ELisp Atom
- Atom is the smallest thing in Elisp such as Integer, String, Float
2.0.8 Emacs Elisp quote '
is function
Quoting an expression treats as data not as code
- quote or ' is a function
- Make (1 2) not self-evaluating
(quote (1 2)) ; => (1 2) ('(1 2)) ; => (1 2)
2.0.9 Emacs Elisp self-evaluating form
- self-evaluating form is not a list or symbol
- number, string and vector are self-evaluating form
'123 => 123 123 => 123 (eval '123) => 123 (eval 123) => 123 (eval (eval 123)) => 123
2.0.10 Emacs Elisp Create a list with list function
(list 1 2 3) ; => (1 2 3)
2.0.11 Emacs ELisp Symbol
- What is Symbol?
2.0.12 Emacs Elisp Hello World
;; print and echo do not work (message "Hello World")
2.0.13 Emacs Elisp get buffer name, full path name
;; insert buffer name to current cursor position (insert (buffer-name)) (insert (buffer-file-name))
2.0.14 Emacs Elisp kill a buffer by name
- Kill a scratch buffer.
(kill-buffer "*scratch*")
2.0.15 Emacs Elisp get all buffer names
- insert all buffer names to current cursor position
(insert (buffer-list))
2.0.16 Emacs Elisp switch to other buffer
- Switch to scratch buffer
(switch-to-buffer "*scratch*")
2.0.17 Emacs Elisp data type:
- string, number, symbol and list etc.
- list type
(A 2 "A") ; A list of three elements. () ; A list of no elements (the empty list). nil ; A list of no elements (the empty list). ("A ()") ; A list of one element: the string "A ()". (A ()) ; A list of two elements: A and the empty list. (A nil) ; Equivalent to the previous. ((A B C)) ; A list of one element ; (which is a list of three elements).
2.0.18 Emacs Elisp evaluate body forms sequentically and return value of last one, execute multiple statements
;; define a function (defun ins (cmd) (insert (shell-command-to-string cmd))) ;; call the function ins (progn (switch-to-buffer-other-window "file.x") (erase-buffer) (ins "ls"))
2.0.19 Emacs Elisp define a function
Define a function on Elisp
(defun myfun (cmd) (insert (shell-command-to-string cmd))) ;; call the function myfun "ls"
2.0.20 Emacs Elisp set global variable
(setq var "~/.emacs") ;; use var (find-file var)
2.0.21 Emacs Elisp mapcar
- mapcar over a vector
;; mapcar over a vector (mapcar '1+ [1 2 3]) ;; => [2 3 4]
- mapcar over a list
(mapcar '1+ '(1 2 3)) ;; => (2 3 4)
- mapcar* zipWith like Haskell
(mapcar* #'cons '("o" "p" "q") '("r" "s" "t")) ;; => (("o" . "r") ("p" . "s") ("q" . "t")) (setq s (mapcar* 'cons '("o" "p") '("r" "s"))) (setq s (mapcar* 'concat '("o" "p") '("r" "s"))) (message "%s" s) (setq a1 '(1 2 3)) (setq a2 '("a" "b" "c"))
- trim a list of strings
(defalias 'trim 'string-trim) (mapcar 'trim '(" a " " b ")) ;; => ("a" "b") (--zip-with (concat it " <=> " other) '("o" "p" "q") '("r" "s" "t")) ; v v ; fst ls snd ls (--zip-with (cons it (cdr other)) '(1 2 3) '(("r" "R") ("s" "S") ("t" "T"))) (zipWith (progn (setq x (car other)) (setq tailx (cdr other)) (cons (concat x "="it) tailx) ) '("1" "2" "3") '(("r" "R") ("s" "S") ("t" "T")))
- drop while and take while like Haskell
(seq-drop-while (lambda (x) (< x 0)) '(-1 -2 1 2)) (seq-take-while (lambda (x) (< x 0)) '(-1 -2 1 2))
2.0.22 Emacs Elisp filter, haskell like filter, filter from dash.el
(defalias 'filter '--filter) ;; from dash.el (filter (> (length it) 0) '("" "a")) ;; => ("a")
2.0.23 Emacs Elisp car and cdr
car is the pointer to head or first element of a list
Node head;
cdr is the pointer to the rest of a list
Node node = head.next;
Elisp car and cdr
(car '(1 2 3)) ;; 1 (cdr '(1 2 3)) ;; (2 3)
Haskell head and tail
head [1, 2, 3] -- 1 tail [1, 2, 3] -- [2, 3]
(car '(1, 2, 3)) ;; => 1 (cdr '(1, 2, 3)) ;; => (2, 3)
Inverse of car and cdr is cons
(cons 'bat '(pig fox cat)) ;; (bat pig fox cat)
2.0.24 Emacs Elisp assoc and associative list or alist
2.0.25 Emacs Emacs format string or convert a list to string
(setq x '(cons dog cat)) (format "%s" x) ;; "(dog cat)"
2.0.26 Emacs Elisp switch to other buffer
- switch-to-buffer-other-window
(switch-to-buffer-other-window "buffer-name")
2.0.27 Emacs Emacs url or file name under cursor
;; file name under cursor (msg (thing-at-point-file-at-point)) ;; url under cursor (msg (thing-at-point-url-at-point))
2.0.28 Emacs Elisp insert string in cursor
- insert
;; Insert str to current line (insert "Hello") ;; Insert str to next line (goto-line (+ (line-number-at-pos) 1) (insert "Insert str to next line")
2.0.29 Emacs Elisp open file in a buffer with find-file
(find-file "~/.emacs") ;; open a file in a buffer ;; why find-file is not called open-file?
2.0.30 Emacs Elisp Get element from a list
- elt
(mapcar (lambda (x) (elt x 0)) [[1 2][3 4]]) ;; => (1 3)
2.0.31 Emacs Elisp Get the current line string, current string
(thing-at-point 'line t)
2.0.32 Emacs Elisp Get cursor line number
(what-line)
2.0.33 Emacs Elisp run shell command function
- shell-command-to-string
(insert (shell-command-to-string "ls"))
- Split string with newline
(split-string (shell-command-to-string "ls") "\n") ;; => ("f1.x" "f2.x")
2.0.34 Emacs Elisp Goto line
(goto-line 10)
2.0.35 Emacs Elips Goto column
(move-to-column 0)
2.0.36 Emacs Elisp replace match regex
(replace-regexp-in-string "True" "False" "This is True") # This is False
2.0.37 Emacs Elisp Get current word under cursor
# only word (thing-at-point 'word 'no-properties) # more info (thing-at-point 'word)
2.0.38 Emacs Elisp Get the current word bounds under cursor
# bounds for a word under cursor (bounds-of-thing-at-point 'word)
2.0.39 Emacs Elisp Repeating Timer, emacs timer
;; repeat every 60 sec (run-with-timer 0 (* 1 60) (lambda () (message "repeat me"))) ;; start a timer with a name so that we can kill them (setq mytimer (run-with-timer 0 (* 1 30) (lambda () (message "repeat me 60 sec")))) ;; kill the timer (cancel-timer mytimer)
2.0.40 Emacs Elisp Regex, remove last directory from a string
(defun remove-last-dir (dir) (replace-regexp-in-string "(.*)/.+" "\1" dir)) ;; (print (remove-last-dir "/sites/all/modules"))
2.0.41 Emacs Elisp Change shell environment variable to exec-path-from-shell-getenv
- SO
- The following code does not work so far.
(defun set-exec-path-from-shell-PATH () "Set up Emacs' `exec-path' and PATH environment variable to match that used by the user's shell. This is particularly useful under Mac OSX, where GUI apps are not started from a shell." (interactive) (let ((path-from-shell (replace-regexp-in-string "[ \t\n]*$" "" (shell-command-to-string "$SHELL --login -i -c 'echo $PATH'")))) (setenv "PATH" path-from-shell) (setq exec-path (split-string path-from-shell path-separator))))
- Create a elisp function to get an environment variable and cd to a directory. it works well so far.
2.0.42 Emacs Elisp substring in elisp
(substring buffer-file-name 0 -4) ;; => (substring "/file.html" 0 -4) => /file
2.0.43 Emacs Elisp split window horizontically and vertically
(split-window-horizontically) (split-window-vertically)
2.0.44 Emacs Elisp Delete other window, maximize current window.
# close the window C-w-c in Vim (delete-other-windows)
2.0.45 Emacs Emacs Get File name under cursor, print file name under cursor
;; print file name under cursor (msg (ffap-file-at-point))
2.0.46 Emacs Elisp Open file under cursor.
M-x find-file-at-point
2.0.47 Emacs Elisp define an alias in Emacs
(defalias 'kill 'kill-buffer)
2.0.48 Emacs Elisp Elisp ampersand rest in a function argument
(defun fun(&rest r) ...)
2.0.49 Emacs Elisp If condition else then
(if nil (message "failed") (message "success")) (if t (message "success") (message "failed"))
2.0.50 Emacs Elisp Compare string
(if (string= "dog" "dog") (message "same str") (message "diff str"))
2.0.51 Emacs Elisp Emacs read file, write to file, append to a file
2.0.52 Emacs Elisp Compare String in Elisp
Compare String in Elisp is not obvious, if you use (= "dog" "cat") then you are out of luck
(setq v "dog") (string= "dog" v) ; => t
2.0.53 Emacs Elisp Compare Objects in Elips
- More compare function OS
- eq Compare object and the content of the object.
Compare setq variable
(eq 3 3) ; => t (setq myvar '(1 2)) (eq 'myvar '(1 2)) ; => nil (eq myvar myvar) ; => t
2.0.54 Emacs Elisp Execute elisp script in your buffer with C-x C-e
- Make sure you put your cursor after the last closed bracket or the next line of your last closed bracket
(let ((v1 'dog) (v2 'cat) v3 ) (message "my %s eats my %s, null is similar to %s")) ;; put your cursor here C-x C-e
2.0.55 Emacs Elisp Split current line
(split-line);; split line under cursor
2.0.56 Emacs Elisp Fibanacci Number
(defun fib (n) "Fibonacci number" (if (< n 3) n (+ (fib (- n 1)) (fib (- n 2))) ) )
2.0.57 Emacs Elisp power function in Elisp, it is not (^) why?
power function
;; (^ 3 4) error (expt 3 4)
2.0.58 Emacs Elisp Convert list to string
(msg (format "%s" (car '(1 a b))))
2.0.59 Emacs Elisp concat string mapconcat or fold
(msg (concat "a" "b")) ;; => ab (msg (mapconcat 'identity '("a" "b" "c") "-")) ;; => a-b-c
2.0.60 Emacs Elisp: highlight word under cursor and unhighlight word under cursor
highlight-symbol-at-point unhighlight-regexp
2.0.61 Emacs Elisp: run shell command in whole buffer
(defun tidy-html () "Tidies the HTML content in the buffer using `tidy'" (interactive) (shell-command-on-region ;; beginning and end of buffer (point-min) (point-max) ;; command and parameters "tidy -i -w 120 -q" ;; output buffer (current-buffer) ;; replace? t ;; name of the error buffer "*Tidy Error Buffer*" ;; show error buffer? t))
2.0.62 Emacs Elisp: concat two lists
(append '("a" "b") '("c" "d"))
2.0.63 Emacs Elisp: Space does it matter in Elisp
(append '("a" . nil) '("e" "f")) ; ("a" "e" "f") (append '("a" .nil) '("e" "f")) ; ("a" \.nil "e" "f")
2.0.64 Emacs Elisp: What is dot in Elisp
(a b c) ;; same as following (a . (b . (c . nil))) ;; same list in primitive form (setq s '(a . (b . (c . nil)))) (message "%s" (car s)) ; a (message "%s" (cdr s)) ; (b . (c . nil))
2.0.65 Emacs Elisp: hashtable, insert key, remove key
;; Insert key (setq htable (make-hash-table :test 'equal)) (puthash "k1" "v1" htable) (puthash "k2" "v2" htable) (message "%s" (gethash "k1" htable)) ;; v1 ;; Remove key (let ((mytable (make-hash-table :test 'equal))) (puthash 'k0 9 mytable) (puthash 'k4 8 mytable) (remhash 'k0 mytable) mytable) ;; Does the same as `make-process`, but runs it ;; synchronously. Returns the exit code of ;; the process that is specified, or nil if ;; the process could not even be started. (defun make-process-sync (&rest args) (let ((proc (apply 'make-process args))) (when proc (while (not (memq (process-status proc) '(exit failed signal))) (sleep-for 0.1)) (process-exit-status proc)))) ;; /tmp/j.json ;; { "k1" : "v1" } ;; (require 'json) (mapcar* (lambda (x y) (+ x y)) '(1 2) '(3 4)) (mapcar* (lambda (x y) (progn (setq a 1) (setq b 1) (+ x y a b))) '(1 2) '(3 4)) (progn (create-scratch-buffer) (with-current-buffer "*scratch*" ;; (erase-buffer) (message "%s" "OK") (insert "Chestnut Preline Latte") (insert-file-contents "/tmp/1.txt") ) ) (message "%s" (HttpSnippet "test")) (setq s1 (append '("a") '("r" "s" "t"))) (setq s2 (cons "synchronize" '("r" "s" "t"))) (message "%s" s1) (message "%s" s2) (setq s1 '("a" "b" "c")) (setq s2 (cdr '("a" "b" "c"))) (message "%s" s1) (setq a1 (car s1)) ;; head of a list (setq b1 (cdr s1)) ;; tail of a list (setq ss (append s1 a1)) (message "%s" ss) (append '("a". nil) '("e" "f")) (message "%s" s2) (message "%s" (cons a1 s2)) ;; cons = construct a list (defun http123(str) (interactive) (progn (call-process "ls" nil '(:file "/tmp/abc.txt") nil "-lah") (message "%s" (runSh "cat /tmp/abc.txt")) ) )
2.0.66 Emacs Keybind: jump backward from defintion in Haskell Intero in .eamcs
;; goto def: M-. (global-set-key (kbd "M-b") (lambda (interactive) (pop-tag-mark)))
2.0.67 Emacs PATH and exec-path for executable files.
- Sometimes you might have no idea why your tools are not running inside Emacs Shell (M-!). One variable you might need to check is called exec-path (C-h v RET exec-path) It might be have the same values as '$PATH'
(exec-path) ;; $PATH, M-S:
2.0.68 Emacs environment variable, getenv and exec-path-from-shell-getenv
(getenv "b") ;; => nothing (exec-path-from-shell-getenv "b") ;; => valid output (setenv "KKK" "wwher") ;; find-file $KKK => resolve $KKK
2.0.69 Emacs Change default directory in Emacs
(setq default-directory "/path/to/documents/directory/")
2.0.70 Emacs Orgmode manipulate table
Key | Description |
---|---|
M-S LEFT | delete current column |
C-c - | add row dash line |
Tab | goto next cell |
2.0.71 Emacs Regex, Emacs Regular Expression, Vim Regular Expression
Compare Emacs and Vim
Vim Vim Example Emacs Emacs Example Description \w \w\+ \w \w+ Match dog cat, Not match dog12cat \{n, } \w\{2,} \{n,\} \w\{2,\} Match two or more word letters \d \d\+ [0-9] [0-9]+ Match one or more digit \s \s\+ [ ] [ ]+ One or more whitespace § §\+ [^ ] [^ ]+ one or more non-whitespace
2.0.72 Emacs: Search and Replace, Why Emacs sucks on that.
- Emacs Search and Replacement
- If you want to search and replace there is function called
replace-string
which is just for string, not for regex. - If you want to search and replace and confirm your replacement then there is other function called
query-replace
- If you want to search and replace in regex then there is other function called
replace-regex
- If you want to confirm your search and replace then there is other function called
query-replace-regex
- Apparently you need to spend an hour on reading the menu document in order to just do some search and replacement on your code. In Vim, you just do the following
# Vim :.,$s/\d\+/KK/gc # Emacs M-x query-replace-regex [0-9]+ RET KK RET
Search and Replace in Group
\d \s \S
\( \Rightarrow \) DOES NOT support in Emacs Regex Engine
;; Roberto, Euler, Baggio => roberto, euler, baggio M-x query-replace-regex \([A-Z]\)\([a-z]\) RET \,(downcase \1) RET ;; \, => following elisp expression
2.0.73 Emacs: Move cursor to the beginning of non-whitespace and move the cursor to the first column of a line
- There are functions to handle those tasks.
- Move the cursor to non-whitespace of a line, (it is the most useful shortcut key)
# M-x back-to-indentation back-to-indentation
- Move the cursor to the first column of a line
# bound to C-a move-beginning-of-line
2.0.74 Emacs: Insert tab in front of a line, function name, binding to M-i
(tab-to-tab-stop)
2.0.75 Emacs: customize theme
Here are the steps to customize a themes
2.0.76 Bitbucket use App password for git
# Run following command to set .git/config git remote set-url origin https://User_Name:App_Password@bitbucket.org/User_Name/cmake.git # .git/config [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true ignorecase = true precomposeunicode = true [remote "origin"] url = https://User_Name:App_Password@bitbucket.org/User_name/cmake.git fetch = +refs/heads/*:refs/remotes/origin/* [branch "master"] remote = origin merge = refs/heads/master
2.0.77 Self-signed certificate
- Self signed certificate
2.0.78 Install Rabbit Message Queue in FreeBSD
- Currently, Python 3.6 is used to run Python script.
pkg install rabbitmq # edit /etc/rc.conf, add following rabbitmq_enable=”YES” # start it sudo /usr/local/etc/rc.d/rabbitmq start
2.0.79 Install RabbitMQ in MacOS
brew update brew install rabbitmq # binary file /usr/local/opt/rabbitmq/sbin
2.0.80 Rabbit Message Queue from Pivotal
- Rabbit Receive message
- Rabbit Send message
- Python Tutorial RabbitMQ
- Rabbit is cool tool.
- Public and Subscribes or producer and consumer
- Send message to RabbitMQ server
- Consumer message from message queue
2.0.81 realtor.com Interview question
- Find a duplicate element from a list contains \(N + 1\) elements. the range of elements are from \(1\) to \(N\)
- Here is the Python code Realtor.com Interview
2.0.82 Evil is not a perfect solution for Vim users.
- Evil mode is great for movement.
- Disable Evil mode and Enable Evil mode.
- You need to know when you should enable and disable Evil mode.
- Evil mode does not support
:ls
see all buffer
:evil-mode M-x evil-mode
2.0.83 Intero and Stack are both not working suddenly
- Can not build a Stack project,e.g. RedisInsert
- Intero can not be booted.
- Fixed is by update the Stack to newer version 2.13
2.0.84 Create a UI to display data for code snippet
- Use Cocoa Swift NSTextField
- Read data from a file repeatedly
2.0.85 Add markdown mode to Emacs or GFM mode for Github README.md
- Install markdown-mode on Emacs
M-x list-package markdown-mode RET
Install markdown parser on MacOS
- command
brew install markdown
C-c C-c e C-c C-c l => live preview
- command
Add init file to
.emacs
(autoload 'markdown-mode "markdown-mode" "Major mode for editing Markdown files" t) (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode)) (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode)) " Github README.md (autoload 'gfm-mode "markdown-mode" "Major mode for editing GitHub Flavored Markdown files" t) (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
2.0.86 Change PDF file background color to different colors, PDF reader, pdf background.
- goto References \(\Rightarrow\) Accessibility
Adobat Acrobat Reader can change PDF file background color so far.
2.0.87 Java: extends and super keywords (07-11-2019)
List<? extends Number> ls1 = new ArrayList<Integer>(); List<? extends Number> ls2 = new ArrayList<Double>(); List<? extends Number> ls3 = new ArrayList<Double>(); List<? super Integer> ls4 = new ArrayList<Integer>(); List<? super Integer> ls5 = new ArrayList<Number>(); List<? super Integer> ls6 = new ArrayList<Object>();
2.0.88 Java: JShell is nice feature because it learns from Python or Haskell.
JShell shells script: javashell.sh
/Users/cat/myfile/bitbucket/script/javashell.sh
- It is hard to figure out if you want to load all the external jar files to JShell
- The following code DOES NOT work, it will waste me an hour to figure it out. We all know path is messy in Java when you want to load some jars or class file.
- There is better way to import all the jar files under a directory.
- I just figure our how to import all your packages from a config file
jshell_config.jsh
contains all your jshell commands
# jshell_config.jsh contain following commands # import static classfile.Aron.*; # $b/java >/open jshell_config.jsh
TODO add both to script?
# load all your jar files jshell --class-path $(ls -d $b/javalib/jar/* | tr '\n' ':') # following: import static classfile.Aron.*; import static classfile.Print.*; import static classfile.Test.*; import classfile.Node; import classfile.Tuple;
- Following is not working
jshell --class-path $b/javalib/jar/*
In order to load jar file to JShell, you need to load the jar file as following.
jshell --class-path :$b/javalib/jar/mylib1.jar:$b/javalib/mylib2.jar
After you load your jar files, you need to import your package too.
- import all static methods from class Aron
import static classfile.Aron.*;
how to exit JShell, show to see your import packages etc, list your command?
/exit /import /list
Nice feature of JShell or Java 10, var can be used to any varaible name.
var v = drop(2, "dog") => "g"
- After update MacOS to Catalina, Everything screwup.
- Can not delete jshell in
/usr/bin
because Apple makes it Read File System - Jshell symbol link screwup again. It points to wrong file.
- I have to create symbol link jshell12 under
/usr/local/bin
to point to OpenJDK12 directory
- Can not delete jshell in
- JavaJDK 12 is in following directory
/Library/Java/JavaVirtualMachines/openjdk-12.0.1.jdk/Contents/Home/bin/jshell
2.0.89 JShell load script to JShell, it is better than Haskell
Use following command to load snippet to your JShell
/open /tmp/myfile.java // myfile.java contains int f(int n){ return n + 1; } class MyClass{ int n; public MyClass(int n){ this.n = n; } }
2.0.90 The difference among align, align* and aligned, they are all in math mode.
- See more advanced typeset equation
- Understand Latex environment
align automatically numbers your equatio
\begin{align} f(x) &= (x^3 + y^3) \\ &= (x + y) (x^2 - xy + y^2) \end{align}
align* does not number your equation.
\begin{align*} f(x) &= (x^3 + y^3) \\ &= (x + y)(x^2 - xy + y^2) \end{align*}
align* - multiple columns alignment
\begin{align*} f(x) &= (x^3 + y^3) & h(x) = x^2 + 1 \\ h(x) &= (x + y)(x^2 - xy + y^2) & g(x) = x + 3 \\ \end{align*}
aligned is for display math mode
\[ \]
, it seems to mealigned
is not a math mode environment\[ \begin{aligned} f(x) &= ax^2 + bx + c \\ g(x) &= x^3 + x + 1 \end{aligned} \] % or \begin{equation} \begin{aligned} f(x) &= ax^2 + bx + c \\ g(x) &= x^3 + x + 1 \end{aligned} \end{equation}
This is two equatins \begin{equation} \begin{aligned}
f(x) &= ax2 + bx + c
g(x) &= x3 + x + 1
\end{aligned}
\end{equation}
I try to figure out what is the difference between \textbf{align*} and \textbf{aligned} I just realize \( \textbf{aligned} \) can be embeded inside the text. And \textbf{align*} has to be in separate line.
% Learn the difference between align* and aligned \begin{aligned} x = y \\ y = z \\ z = w \end{aligned}, I just realize \textbf{aligned} can be embeded inside the text. And \textbf{align*} has to be in separate line.
2.0.91 Fixed copy text to clipboard with click button in Wai Server. (13-11-2019)
- Initially use the wrong id name in TextArea, change to id in pre
- commit the code.
- Inside Wai Server, there is still some functions use neatinterpolation package?
- Change it back to Raw.String.QQ ?
- Wai Server is slower than before. it might be neat interpolation package issue.
2.0.92 Modulus for a ring, addition and multiplicaton
- Show following If: \begin{aligned}
& a \mod m ≡ a' \quad b \mod m ≡ b'
&\text{ Show } a + b \mod m ≡ a' + b' \text{ and } a b \mod m ≡ a' b' \\
a \mod m &≡ a'
b \mod m &≡ b'
a &≡ x m + a'
b &≡ y m + b'
⇒ a + b &≡ (x + y) m + a' + b'
⇒ a + b \mod m &≡ a' + b' \\
a b &≡ (xm m + a') (y m + b')
a b &≡ x m y m + x m b' + a' y m + a' b'
⇒ a b \mod m &≡ a' b'
\end{aligned}
2.0.93 Try to Remove all commands from $b/stackproject/filewatcher and run it see still got the error message.(15-11-2019)
/bin/ls: createProcess: fork: resource exhausted (Resource temporarily unavailable
- It still get the same error message even though all the system() code are removed.(15-11-2019)
2.0.94 English words: modulus, module, modular, moduli, modulo, modulate (15-11-2019)
- The plural form of modulus is moduli
- modulo is a prepostion, I never know that. It is very surprised.
- In mathematic, we do have something called modulo operation
- If two numbers are congrent modulo a given number if their reminders are the same when divided by that number.
\[ 10 \mod 3 \equiv 7 \mod 3 \equiv 1 \]
- Word modulu DOES NOT exist.
- modular is adjective. moular arithmetic
- modulate is verb.
- module is noun.
2.0.95 Polynomial, degree of polynomial.
- Take the higher power of a polynomial is called the degree of polynomial \[ f(x) = 3x^3 + 2x^1 + 3 \\ \deg(f) = 3 \]
- An non zero constant polynomial is zero \[ f(x) = 3 = 3x^0 \\ \deg(f) = 0 \]
- Zero constant polynomial will be defined as \(-\infty\) or \(-1\) \[ f(x) = 0 = (0, *) \\ \deg(f) = -\infty \]
- The degree of multiplication of two polynomials. If both polynomials are not zero constant polynomial, then \[ f(x) = 3x^2 + 3 \\ g(x) = 4x^3 + 2x \\ \deg(f \cdot g) = \deg(f(x) \cdot g(x)) = \deg(f) + \deg(g) = 5 \\ \]
If one of the polynomials is zero constant polynomials, the addition still work.
- Assume the \(\deg(0) = -\infty\)
\[ f(x) = 0 \\ g(x) = 4x^3 + 2x \\ \deg(f) \cdot g) = \deg(f \cdot g) = \deg(f) + \deg(g) = 5 + -1 = 4 \]
- The addition of two degree of two polynomials still work. \[ f(x) = 0 \\ g(x) = 4x^3 + 2x \\ \deg(f \cdot g) = \deg(f) + \deg(g) = -\infty + 3 = -\infty \\ \]
- The addition of two polynomials? \[ f(x) = 3x^2 + 3 \\ g(x) = 4x^3 + 2x \\ \deg(f + g) = \max(\deg(f), \deg(g)) = \max(2, 3) = 3 \\ \]
- What about one polynomial is zero constant polynomial. it still works. \[ f(x) = 0 \\ g(x) = 4x^3 + 2x \\ \deg(f + g) = \max(\deg(f), \deg(g)) = \max(2, -\infty) = 2 \]
2.0.96 In Java, negative and positive infinity are defined. I never realize that.(15-11-2019)
double inf = Double.POSITIVE_INFINITY; System.out.println(inf + 5); System.out.println(inf - inf); // same as Double.NaN System.out.println(inf * -1); // same as Double.NEGATIVE_INFINITY // Infinity // NaN // -Infinity
2.0.97 Rename vimlatex.sh to latexsync.sh, add symbol link latexsync.sh
2.0.98 latexmk automatically compile file and reload pdf automatically
- shell script
$b/latexsync.sh
latexsync.sh mylatex.tex
file \(\Rightarrow\) auto compile file.- The shell script has following code to use latexmk
latexmk -interaction=nonstopmode -pvc -pdf file.tex > /dev/null 2>&1 & # ignore error -interaction=nonstopmode # auto compile -pvc -pdf
2.0.99 Add operators to javapolynomial: negate, subtract, inverse, divide and test cases.(19-11-2019)
2.0.100 Algebraic Data Type and Calculus
2.0.101 Intellij wrong java compiler, Intellij class file has wrong version error.
- Wrong version class in Intellij
2.0.102 Intellij keymap file location on MacOS.
- Intellij keymapping name here Key Mapping Name
- Add your own keybinding to Intellij, Emacs like key
- Intellij Keymap file
name="intellij-idea-vscode-keybindings" /Users/cat/Library/Preferences/IdeaIC2019.2/keymaps/keymap.xml
- Intellij key map file name
- Intellij edit shortcut key
2.0.103 Intellij Make Vim like keymapping
Map multiple key strokes in Intellij
- Open or Close Run window at the bottom of Intellij, Vim like keymapping
ctrl-w c
- Add following to your
keymap.xml
file.
<action id="ActivateRunToolWindow"> <keyboard-shortcut first-keystroke="meta 4" /> <keyboard-shortcut first-keystroke="ctrl w" second-keystroke="c" /> </action>
- Open or Close Run window at the bottom of Intellij, Vim like keymapping
2.0.104 Intellij code template or snippet location on MacOS, Symbol link to bitbucket/intellij
# MacOS /Users/cat/Library/Preferences/IdeaIC2019.2/templates/Java.xml # templates symbol link to => /Users/cat/myfile/bitbucket/intellij/templates
- code template can be added in XML is a newline
2.0.105 Intellij Add classes and jar file to libraries
2.0.106 XML speical characters '<', '>', '\'', '"', '&'
2.0.107 Convert snippet to Intellij code template in Haskell stackproject/IntellijSnippet
2.0.108 Haskell pretty print library. pretty-simple
- PRETTY-SIMPLE is easy to use.
pPrint "YOURCLASS"
2.0.109 Haskell FFI: How to pass a pointer to a function
Convert CString to Haskell String
peekCString :: CString -> IO String
Convert Haskell String to CString
newCString :: String -> IO CString
Read a value from a pointer in Haskell. let say we have a function called
void increment(int *n)
n is modifed from inside the function.void increment(int *n){ int m = *n; *n = m + 1; }
FFI Function signature, we might have a function prototype like the following.
c_increment :: Ptr CInt -> IO ()
Allocate memory for pointer using following
alloca
Haskell alloca
alloca ::forall a b. Storage a => (Ptr a -> IO b) -> IO b fun::IO Int fun = do alloca \pt -> poke pt 3 -- write 3 to pt, memory location n <- peek pt -- read a value from pt, memory location return $ fromIntegral n
Read a value from a pointer, read a value from memory location
peek
Haskell peek
peek :: Ptr a -> IO a
Write a value to a pointer, memory location
poke
Haskell pokepoke :: Ptr a -> a -> IO()
- It seems to me all the primitive types are instance of Storage
- If you need to pass pointer to struct, then you need to create an instance of Storage
and implement a few functions such as peek, poke, sizeOf, alignment
void
type in C is equivalent toIO()
- Call Haskell Fun in C Program
- Haskell Call C Function
- Tutorial Wiki
- C struct to Haskell
- See Haskell FFI C type => C type
Haskell type prepresenting the C type(There is more, please see Haskell FFI C type => C type above)
Haskell Convert FFI C type Haskell Definition C type Int Int = fromIntegral CInt CInt CInt Int32 int String CString /(Ptr CChar) Ptr CChar, CString char* Double Double = readToFrac CDouble CDouble CDouble Double double CLong CLong Int64 long CChar CChar Int8 char CSChar CSChar Int8 signed char CUChar CUChar Word8 unsigned char CUInt CUInt Word32 unsigned int CFLoat CFloat Float float fromIntegral::(Integer a, Num b) => a -> b
-- Num interface class Num a where (+) :: a -> a -> a (-) :: a -> a -> a (*) :: a -> a -> a fromIntegral :: (Integer a, Num b) -> a -> b negate :: a -> a abs :: a -> a signum :: a -> a
realToFrac :: (Real a, Fractional b) => a -> b
-- Real to Fractional class Fractional a where (/) :: a -> a -> a recip :: a -> a fromRational :: Rational -> a
2.0.111 Haskell Unicode regex error, "illegal byte sequence" error
- Change locale to
export LANG=C
- SO
Text.Regex.Posix.String died: (ReturnCode 17,"illegal byte sequence")) >locale LANG="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_CTYPE="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_ALL= >export LANG=C
2.0.112 Haskell bracket example from Snoy Man
2.0.113 Add stackproject Haskell FFI C my lib file.
2.0.114 Convert C function signature to FFI with C2HS tool, example(26-11-2019)
2.0.115 Move CodeAnalysis to $b/cmake
folder.(23-11-2019)
2.0.116 Add some C funciton to my C library(26-11-2019)
dropChar(int n, char arr[]) takeChar(char arr1[], int n, char narr[]) concat(char arr1[], char arr2[], char arr3[])
2.0.117 Zathura PDF latex viewer, it is Vim style PDF Viewer
- background and fontcolor can be changed.
2.0.118 Joseph problem
- Whether the problem is related to "Excel Column Header" problem. Excel Column
- The problem is related to rotate array to the left or the right with positive or negative number
2.0.119 Install ghc-mod is painful on MacOS.
- Cabal install does not work welll because ghc-mod only supports old GHC.
You need to change Stack resolver to
its-8.24
with following command. -
stack install ghc-mod --resolver lts-8.24
I can install it with above command ghc-mod binary is in
~/.local/bin
- So far, ghc-mod still does not work on Emacs.
2.0.120 Nice emacs setup Site
2.0.121 New Vim Command in insert mode, I never know that before.
- SO
- delete word and line in insert mode
- Control Key in insert mode
CTRL-O h move cursor left CTRL-O l move cursor right CTRL-O j move cursor down CTRL-O k move cursor up
- Contrl Key in insert mode
CTRL-W delete word to the left of cursor CTRL-O D delete everything to the right of cursor CTRL-U delete everything to the left of cursor CTRL-H backspace/delete CTRL-J insert newline (easier than reaching for the return key) CTRL-T indent current line CTRL-D un-indent current line
2.0.122 Vimscript list or array
list has following syntax in Vimscript
let list = [1, 2, 3] let list = [1, 'a'] let list = [1, "a"]
Add element to a list
let list = [1, 3] call add(list, 4) " => [1, 3, 4] call add(list, 'dog') " => [1, 3, 4, 'dog'] let ls2 = [4] call add(list ls2) " => [1, 3, 4, 'dog', [4]]
Index an element from a list.
let list = [1, 2, [3]] echo list[0] " => 1 " length of a list echo len(list) " => 3 " get the last element echo list[-1] " => [3] " two dimensions list echo list[2][0] " => 3
- From above example, you can add number or string other type to the same list.
- Python and Java can only store same type on a list or array.
ls = [1, 2] ls2 = ['dog', 'cat']
Vimscript nested function is a thing actually.
func! MyFun() call Inner() func! Inner() echo 'inner func' endfunc endfunc
2.0.123 Vimscript pesado-variable(I never hear the name pesado-variable in Vim)
2.0.124 Vim :g
or :global
range search, it is very powerful
- global search pattern - get the range and exec command
:global pattern command
:g /pat1/, /pat2/ command
:g /pat1/, /pat2/ substitute
- SO
\begin{align} x = x + 1 \\ y = y + 1 \\ z = z + 1 \\ \end{align} % chagne to \begin{align} x &= x + 1 \\ y &= y + 1 \\ z &= z + 1 \end{align}
" +1 => next line " -1 => previous line " -v => all special char need to be escaped :g /\v/\\begin\{align\}/+1, /\v/\\end\{end\}/-1 s/=/\&=/gc
2.0.125 Some crazy Vim tips from someone
- Vim tips Vim tips
- Vim tips PDF Vim tips
- My Vim tips Vim tricks
2.0.126 Pandoc convert Latex to Html, Haskell literate to Html
- pandoc 2.8 on MacOS
# Compile Haskell literate code to html with pandoc # /Users/cat/myfile/bitbucket/haskell/try_lite.lhs pandoc --smart --to=html+lhs try_lite.lhs > /tmp/try_lite.lhs && open /tmp/try_lite.html # Compile Latex to Html5 pandoc --mathjax --highlight-style haddock $m/negative_modulo.tex -f latex -t html -s -o /tmp/f3.html && open /tmp/f3.html
* Haskell Haddock example
2.0.127 history command is not working inside shell script
If you use following code to get all the commands histories, then you are out of luck
#!/bin/bash history | grep ls
- This is answer from stackoverflow.
- SO
- history command is disabled when non-interative shell is running
- I think the shell will "use" the history file and write commands to the file.
- Here is how to fix it
#!/bin/bash -i history | grep ls
2.0.128 Write a few functions to align columns in Vimscript(07-12-2019)
2.0.129 Add some test cases for Vimscript functions. And it works well so far.(07-12-2019)
2.0.130 Fixed a bug in haskellwebapp2, colorize some wrong tokens or keywords with regex.
2.0.131 Haskell define dynamic function with Map
2.0.132 Check ghci memory leak
- How to view live memory Run GHCi inside Haskell code
import Control.Concurrent import Control.Monad import System.IO import System.Process main = do (Just hin, Nothing, Nothing, pid) <- createProcess (proc "ghci" ["+RTS","-S"]){std_in=CreatePipe} forever $ do threadDelay 100000 -- 0.1s hPutStrLn hin "\"this is a test of outputting stuff\"" hFlush hin
2.0.133 Emacs Auctex Latex autocomplete Environment, Section and Macro.
C-c C-c # compile latex C-c C-l # view pdf file # C-c C-e # autocomplete environment C-c C-m # autocomplete macro C-c C-s # autocomplete section ` # autocomplete math mode, alpha
- Skim reload pdf file automatically. Skim \(\Rightarrow\) References.
2.0.134 Emacs still can not resolve environment variables, add one function to some hassle.
- It does not solve all the problems but it save me lots of typing.
(defun cdd(env) (interactive) (cd (getenv evn)))
2.0.135 Emacs can do lots of math
2.0.136 Emacs: Jumping back and forth is stupidly painful in Emacs.
- Try the
transient-mark-mode
Redit question - So far the easier way to do is using the register
- Mark the location with a letter, e.g. 'a'
C-x r <Space> a
- When you move the cursor to other location, you can jump back to previous location with letter 'a'
C-x r j a
- In Vim, you can mark the location with a letter 'a' with m command (Assume you are in Normal mode)
# Assume you are in Normal mode m a
- In Vim, jump back to 'a' location
# Assume you are in Normal mode 'a
2.0.137 Sometimes Emacs does not reload file with load-file
, you need to kill-buffer
and reopen the file.
2.0.138 Shell Script: /etc/profile
source /.bashrc
, currently it works so far.
- non-interative shell does not read
/etc/profile
and/.bashrc
# inside /etc/profile ~/.bashrc
2.0.139 Bash shell keybinding or key mapping. Map your F7 key to run a shell script.
Map f7 key to send a hello world to terminal
# add code here
2.0.140 Bash shell keypress event
2.0.141 Shell Script: alias does not expand inside shell script because alias DOES NOT expand in non-interative shell
How to make alias expand inside your shell script? alias does not work inside shell script
#!/bin/bash shopt -s expand_aliases source ~/.bash_aliases # your code here
2.0.142 Shell Script: true and false are both shell command, I never know that
>true >echo $? => 0 >false >echo $? > 1
2.0.143 Shell Script: pass string with newline to argument in Shell
- string with newline, argument with newline
str=$(cat <<-END This is line one. This is line two. This is line three. END ) printBox 4 'dog cat '$'\n''cow' printBox 4 "$str" # DOES NOT WORK printBox 4 'dog\ncat'
2.0.144 Org-mode and GNU-APL mode, input GNU-APL char inside org-mode
- It is very easy, just switch from org-mode to gnu-apl mode and input your favour char inside your org-mode
- You can do the same thing in Haskell mode and input Latex char with
(latex-input)
2.0.145 Install APL inside your Emacs.(I'm a MacOS)
You might need to kill apl server from command line, and restart your gnu-apl inside your Emacs
ps aux | grep apl | awk '{print $2}' | line 'x -> kill -9 x'
- If you can not run your APL, use (kill-buffer) and restart
gnu-apl
again. Use homebrew to install gnu-apl on MacOS
brew install gnu-apl # /usr/local/Cellar/gnu-apl/1.8/bin/apl
M-x list-packages # search gnu-apl-mode RET
Add gnu-apl to load-path to init.el file
(add-to-list 'load-path (concat (getEnv "HOME") "/.emacs.d/elpa/gnu-apl-mode-20211012.1139")) (require 'gnu-apl-mode)
Start gnu-apl mode
M-x gnu-apl-mode
Input APL char in Emacs
# M-x gnu-apl-mode Cmd-u # add image aplkeymap.png
- Sometimes you need to kill your buffer with
(kill-buffer)
to go back to gnu-apl mode, I have no idea why? It does not work if you are in different mode such as haskell-mode. No idea how to switch to gnu-apl-mode
- Close Emacs and Restart APL with following command
(kill-buffer) M-x gnu-apl
Where is your APL keyboard?
M-x gnu-apl-show-keyboard
- How to exit gnu-apl window?(09-12-2019), this is the best thing that I learned today.
- Here is the awesome command to exit GNU-APL:)
)OFF
System command start with right parenthesis
)
)OFF # => exit apl )VARS # => see all variables )ERASE # => ? # erase a variable n )n
APL use reshape ρ (rho) command to create table or matrix
a ρ b
- APL use reshape ρ to create a vector or initialize a vector
- initialize a vector
v ← 4 ⍴ 0 ⍝ v = 0 0 0 0
- Create a 4 elements vector
v ← ⍳ 4 ⍝ v = 1 2 3 4
- Initialize a vector with 1 2 3 4
4 ρ 1 2 3 4 # v = 1 2 3 4 4 ρ 1 2 # v = 1 2 1 2 4 ρ 1, 2 # v = 1 2 1 2
Change to different mode, e.g. to Org-mode
M-x org-mode
Change to gnu-apl mode
M-x gnu-apl-mode
Start gnu-apl console
M-x gnu-apl ;; not gnu-apl-mode
- gnu-apl add vector
- Add two vector or two list? what is the different between Vector and List?
No sure is there any thing called list in APL
1 2 3 × 3 4 9 # => 3 8 27
- The small multiply sign latex symbol \(\\times\)
gnu-apl create matrix with reshape ρ (rho)
2 3 ρ 1 2 3 4 5 6 => 1 2 3 4 5 6
gnu-apl assign a matrix to a variable
var ← 2 3 ρ 1 2 3 4 5 6
- gnu-apl power function, where is the square root function in APL?
- There is no square root function in APL (Maybe..)
2*4 = 2⁴ 2*(0.5) = sqrt(2)
- gnu-apl log function, where is my log function in APL?
- Press Cmd Shift 8 ⇒ login function
2 ⍟ 8 # => 3 # log function 2 4 8 ⍟ 4 16 64 => 2 2 2
- gnu-apl minimum and maximum function
- Press Cmd s and Cmd d <- Cmd d is MacOS keymapping..:
gnu-apl: sum of n integer \( f(n) = \sum_{1}^{n} n \)
N ← 1 2 3 sum +/N
gnu-apl: average or mean, \( g(n) = ∑_{1}^{n} \frac{1}{n} \)
N ← 1 2 3 av ← (+/N) ÷ (1⌈⍴N)
Dyalog APL, create a file, write a string to a file and open it If you just try to open an random file, then you will get encode error, no idea how to fix it. I think you need to specify some encoder such as *UTF-8' when opening the file.
# create a file 'Hello' ⎕NPUT '/tmp/x1.x' v ← ⎕NGET '/tmp/x1.x' v
- Write a vector to a file
# write 2 dim vector to a file # # 1. Use ⍕ to convert integer matrix to character matrix # 2. Convert 2 dim to 1 dim with ↓ # 3. Use ⊂, I have no idea why? (⊂↓⍕(2 3⍴⍳10))⎕NPUT '/tmp/x1.x'
- APL outer product
v ← 1 2 3 v ∘.× v 1 2 3 2 4 6 3 6 9
- APL outer product with mod
v ← 1 2 3 v ∘.| v 0 0 0 1 0 1 1 2 0
- Sort each row in an 3D matrix
⍝ sort each row in an 3D matrix sort ← {⍵[⍋⍵]}⍤1 m3 ← 2 3 4 ⍴20?20 m3 11 1 18 3 17 4 12 16 9 5 13 2 19 10 7 20 6 14 15 8 11 1 18 3 sort m3 1 3 11 18 4 12 16 17 2 5 9 13 7 10 19 20 6 8 14 15 1 3 11 18
- Reduce 3D matrix to 2D matrix, or reduce rank.
⍝ Convert 3d matrix to 2d matrix m3d ← 2 3 4 ⍴20?20 ⍴m3d 2 3 4 m2d ← ↓m3d m2d 14 12 16 4 10 8 3 20 15 6 9 13 2 11 17 7 5 18 1 19 14 12 16 4 ⍴m2d 2 3
- Flatten a matrix to a vector, flatten any rank matrix to a vector?
⍝ Flatten 3d matrix to a vector m3d ← 2 3 4 ⍴20?20 ⍴m3d 2 3 4 m3d 18 7 12 1 19 16 14 2 6 11 15 20 3 8 13 5 10 4 17 9 18 7 12 1 ve ← ∊m3d ⍴ve 24 ve 18 7 12 1 19 16 14 2 6 11 15 20 3 8 13 5 10 4 17 9 18 7 12 1
It is similar to foldl in Haskell
let m = [[1, 2], [3, 4]] foldl (\x y -> x ++ y) [] m -- => [1, 2, 3, 4]
- Recover the origin matrix from the vector \(v\) with rank 24
⍝ Recover the origin matrix from the vector with rank 24 m3d 2 5 12 17 6 18 4 20 1 3 19 11 7 16 8 9 10 13 14 15 2 5 12 17 ve 2 5 12 17 6 18 4 20 1 3 19 11 7 16 8 9 10 13 14 15 2 5 12 17 ⍴ ve 24 2 3 4 ⍴ ve 2 5 12 17 6 18 4 20 1 3 19 11 7 16 8 9 10 13 14 15 2 5 12 17
- Letter Matrix
letterMatrix ← 2 3 4 ⍴ ⎕A letterMatrix ABCD EFGH IJKL MNOP QRST UVWX
- Count the number of characters from a given string
⍝ count the number of characters from a given string string ← 'avocado' 'banana' 'cherry' 'pitaya' 'a'=string 1 0 0 0 1 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 1 mask ← 'a'=string +/¨ mask 2 3 0 2
- APL map inside a map
⍝ map(\x -> map(\e -> e) x) ls +/+/¨
- Use haskell solve it
let str = ["avocada", "banana", "cherry", "pitaya"] let mask = map(\s -> map(\x -> if x == 'a' then 1 else 0) s) str let totla = sum $ map(\x -> sum x) -- => 2 + 3 + 0 + 2 = 7
- Concatenate a vector and a matrix
⍝ Concatenate a vector and a matrix v ← 0 0 0 m ← 3 3 ⍴?⍨10 m 1 8 2 9 4 10 7 5 6 matrix ← 4 3 ⍴ v, ∊m matrix 0 0 0 1 8 2 9 4 10 7 5 6
- Select pairs of consecutive rows from a matrix
⍝ Select pairs of consecutive rows from a matrix matrix 0 0 0 1 8 2 9 4 10 7 5 6 2 -⍨⌿ matrix 1 8 2 8 ¯4 8 ¯2 1 ¯4
- Concatenate row vector with a matrix
⍝ Concatenate a row vector with a Matrix rowVector ← 1 2 3 4 a 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 rowVector ⍪ a 1 2 3 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
- Concatenate a column vector with a matrix
columnVector ← ⍪ 10 20 30 40 a 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 columnVector , a 10 1 2 3 4 20 5 6 7 8 30 9 10 11 12 40 13 14 15 16
- Add column vector to a matrix
⍝ Add a column vector to a matrix columnVector ← ⍪ 10 20 30 matrix ← 3 3 ⍴?⍨10 matrix 3 7 9 5 1 4 6 8 2 columnVector (+⍤1) matrix 13 17 19 25 21 24 36 38 32
- Add row vector to a matrix
⍝ Add a row vector to a matrix rowVector ← 10 20 30 matrix 2 5 8 4 3 9 6 1 7 rowVector 10 20 30 rowVector (+⍤1) matrix 12 25 38 14 23 39 16 21 37
2.0.146 Install J programming language
- Download from J901 zip
- Following the steps in the Wiki to install
jconsole
/Applications/j901/bin/jconsole
- Start jconsole inside Emacs
M-x j-console
array
i.10 NB => [0..9]
fold, or sum the array
+/0 i.10 NB => 45
length of array
a =: i.10 # a NB => length of array = 10
index of array or string
a =: 'Instrict Geometry' 0 { a NB => I 1 { a NB => n
split string
a =: 'abcde' 2 3 $ a NB => abc NB => dea
Random number, uniform random \([0, 1)\)
? 10 $0 NB => generate 10 random number in [0, 1) ? 10 10 $0 NB => generate 10x10 matrix in interval [0, 1) ? 3 3 $0 NB 0.586922 0.415727 0.986659 NB 0.0970579 0.194989 0.483234 NB 0.64026 0.407095 0.457437
Random matrix
- Random matrix in interval \([0, 10)\)
? 3 3 $10
- Fix random number
?. 3 3 $10
floor and ceiling
<. 3.2 NB => 3 , floor >. 3.2 NB => 4 , ceiling
Rational number
2r3 + 1r3 NB => 1
Complex number, \(z \overline{z} = |z|^2\)
3j4 * 3j_4 NB => 25
write and read file
readFile =: 1!:1 writeFile =: 1!:2
Write String to file
fn =. < '/tmp/x.j' 'Hello World' writeFile fn
Read data from file
fn =. <. '/tmp/x.j' readFile =. 1!:1 data =. readFile fn
Sum array and table
a =: i.20 +/ a t =: 2 3 $ i.20 +/ +/ t
Index table, like index string
t =: 2 3 $ i.20 0 { t NB. => first row 1 { t NB. => second row
2.0.147 Fixed the whitespace issue in the header of block code, e.g. trim whitespace in the header of block code
2.0.148 Nice Javascript text editor call editorjs.io
is pretty good, demo at the following
- local Storage save data example
- editorjs.io
- Local test data demo, get data from Json object.
file:///Users/cat/myfile/bitbucket/html/editorjs/saved-data-example/example.html
- Get data from Json object
{ "time": 1576279792814, "blocks": [ { "type": "paragraph", "data": { "text": "This is the text from editorjs" } } ], "version": "2.16.1" }
2.0.149 Javascript: Insert script tag into Html Body or Header
How how to insert the following script into Html Body or Header
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>
- Here is the code can do the job
var s = document.createElement('script'); s.type = 'text/javascript'; s.src='https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js'; document.body.appendChild(s);
2.0.150 Javascript: Insert class into tag such div, pre etc
How to insert class into tag without knowing the class ID?
- We can use getElementByTagName()
const pre = document.getElementByTagName('pre'); const elementArray = Array.from(pre); elementArray.forEach(el => el.className = 'prettyprint');
- Result:
<pre class='prettyprint'> String n = "dog"; </pre>
2.0.151 Javascript: select text range from TextArea with selection.(15-11-2019)
2.0.152 Javascript: Javascript Object to json, access json elements
- Json file
{ "name": "Jenny", "age": 30, "address": { "streetAddress": "100 King St.", "city": "New York" }, "phoneNumber": [ { "type": "home", "number": "111 111-1111" }, { "type": "fax", "number": "222 222-2222" } ] }
Access JSON Object from Javascript, parse it with JSON.parse()
<script> var data = '{"name": "david","age": 30, "address": {"streetAddress": "88 Road","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}'; var json = JSON.parse(data); alert(json["name"]); alert(json.name); alert(json.address.streetAddress); //88 8nd Street alert(json["address"].city); //New York alert(json.phoneNumber[1].type); //fax alert(json.phoneNumber.number); //undefined </script>
2.0.153 Javascript: web storage API, it only works when open localhost or Http protocol. it does not work in local file system in Chrome.
- sessionStorage does not keep the data when the tab or browser is closed. But localStorage still keeps the data even the tab or browser is closed.
- You can close the tab and browser and the data still kept in localStorage.(I never know that)
- localStorage only supports string
- The maximum limit is 10MB in Chrome. (it mighe be the case in Firefox)
You can find out the limit of localStorage in each browser here Limit localStorage
// check browser support typeof(localStorage) // set data localStorage.setItem('key1', 'Hello World'); localStorage.setItem('key2', 'local storage is awesome'); // retrieve the data var value1 = localStorage.getItem('key1'); var value2 = localStorage.getItem('key2');
-
/Library/WebServer/Documents/xfido/bitbucketHTML http://localhost/bitbucketHTML/webstorage.html
2.0.154 Javascript: Try to put all editorjs.io javascript editor and Katex together and render Katex in realtime.
- It is very painful to work with Javascript and I'm looking for some event for each keypress and I realize there is event called onchange on Javascript when text is modified.
- There is some issue when input Katex code to editor, some whitespace or special char
<
are included in the string. - There is rendering issue such as \(\sum_{i}^{n} x + y\) does not work so far. I have no idea why
- One option is to change editor to
textarea
instead and see what is the outcome. Working example Example
http://localhost/bitbucketHTML/editorjs/saved-data-example/example.html
2.0.155 Javascript: Add data to Div Element, textContent and innerHTML
- Add Data To Div Element
- Use textarea still does not work so far. The redering has lots of issue.
2.0.156 Javascript: Found a unbalanced head tag in HTML code. I think it causes the Katex rendering issue.(16-12-2019)
- Fix it, the rendering Katex code is working so far.
The nice thing about Katex is the individual tag can be rendered with following function
var eleId = document.getElementById('latexcode'); renderMathInElement(eleId);
2.0.157 Javascript: It is surprisedly hard to copy partial text from TextArea to clipboard in Javascript
- I spent lots of time on an answer to copy partial text from TextArea to clipboard. e.g. copy line 2 to line 4 from TextArea to clipboard.
- Most solutions are copy all the data from elements (such as Div) to clipboard with copy command:
document.execCommand('copy')
- I'm still have trouble to make it to work so far.
- But It's working on single HTML file here Copy Partial Text to Clipboard
- It seems to me the data is not selected from TextArea
- I have checked the
id='t1'
and it should not be any issue on element Id. - The data can selected and passed to
copyToClipboard
function and the first line is removed from an array. - Create an
Range
object and add the rest of lines to it, and usecopy
command to copy the data to Clipboard, but it does not work on this step. - Write Html to a file and run it with Chrome, but data in TextArea still CAN NOT copied to clipboard
- I have checked the
- Use
writeFileBS
writeFile ByteString to HTML file, and copyaronlib.js, mystyle.css
to a folder and open the HTML file with Chrome - Got same error message: 'does not select any thing' which is error in
copyToClipboard()
function
2.0.158 Javascript: The order of <script>code</script>
and Html code are important in Javascript.
For example, if you have event listener to listen an input from a text field then you need to put your HTML code before the addEventListener.
const inputField = document.getElementById('inputid'); inputField.addEventListener('keyup', (e) =>{ const query = e.target.value; delayKeyUp(() => {delayFun(query)}, 2000); })
2.0.159 Javascript: Lambda function
const fun = (x, y) => x + y; // java style // Function<Integer, Integer> f = (x) -> x + 1; // Bifunction<Integer, Integer, Integer> f = (x, y) -> x + y; // C++ style // auto f = [](auto& x) -> {return x + 1;};
2.0.160 Javascript CSS, Modify CSS style value/attribute
Use
document.stylesheets
function to get the field in the style sheet.document.stylesheets[0]
\( \Rightarrow \) get the first style sheet.
pre{ color:red; backgroundColor:green; }
Use
styleObj.cssRules[0].style.color
to access the style value- Change font color
console.log(styleObj.cssRules[0].style.color);
[0]
means the first field in the style<html> <head> <style type='text/css'> pre{ color:red; backgroundColor:green; } </style> <script type='text/javascript'> function changeColor() { const styleObj = document.styleSheets[0]; console.log('color=' + styleObj.cssRules[0].style.color); styleObj.cssRules[0].style.color = 'green'; console.log('color=' + styleObj.cssRules[0].style.color); } </script> </head> <input type='button' value='ClickMe' onclick='changeColor()'> <div> <pre> Euler Leonhard Pythagorean Theorem Lucas George Justin Bieber Justin Trudaeu Justin Timberlake </pre> </div> </html>
2.0.161 Javascript call function after page is loaded
<script> document.addEventListener('readystatechange', event => { // When HTML/DOM elements are ready: if (event.target.readyState === "interactive") { //does same as: ..addEventListener("DOMContentLoaded".. alert("hi elements are ready"); } // When window loaded ( external resources are loaded too- `css`,`src`, etc...) if (event.target.readyState === "complete") { requestPreFromRedis(); alert("call after css is loaded"); } }); </script>
2.0.162 Proof logarithm \(\log a^x a^y = \log a^x + \log a^y\)
Proof
\begin{aligned} a^b + 1 &= a^b + a^0 \\ b^a + 1 &= b^a + b^0 \\ a^x a^y &= a^{x + y} \qquad \text{By } \log \text{definition} \\ \log_a (a^x a^y) &= x + y \\ \log_a a^x a^y &= x + y = \log_a a^x + \log_a a^y \\ \Rightarrow \log a^x a^y &= \log a^x + \log a^y \end{aligned}
2.0.163 Proof function injectivity, subjectivity and composition
- Given two functions \(f : \mathcal{A} \rightarrow \mathcal{B}\) and \(g : \mathcal{B} \rightarrow \mathcal{C}\)
Proof 1:
\begin{aligned} & \text{If } g \circ f \text{ is injective }, \text{Show } f \text{ is injective} \\ & \text{If } g \circ f \text{ is subjective }, \text{Show } g \text{ is subjective} \end{aligned} \begin{aligned} & g \circ f \text{ is injective} \\ & \Rightarrow \text{ if } g \circ f (a) = g \circ f (b) \text{ then } \\ & \Rightarrow a = b \\ & \text{ If } f \text{ is not injective, then} \\ & \exists x_1, x_2 \in \mathcal{A} | f(x_1) = y \text{ and } g(x_2) = y, x_1 \neq x_2 \\ & \Rightarrow g (f(x_1)) = g (f(x_2)) \\ & \Rightarrow g \circ f \text{ is not injective} \\ & \text{ This contracts our statement } \\ & \Rightarrow f \text{ must be injective} \end{aligned}Proof 2:
\begin{aligned} & g \circ f \text{ is subjective} \\ & \Rightarrow \forall c \in \mathcal{C} \quad \exists x \in \mathcal{A} \mid g \circ f (x) = c \\ & \text{ If } g \text{ is not subjective} \\ & \exists c \in \mathcal{C} \mid \forall b \in \mathcal{B} \quad g(b) \neq c \\ & \Rightarrow \exists c \in \mathcal{C} \mid \forall a \in \mathcal{A} \quad g \circ f (a) \neq c \\ & \Rightarrow g \circ f \text{ is not subjective} \\ & \text{ This contracts our statement} \\ & \Rightarrow g \text{ must be subjective} \end{aligned}
2.0.164 Katex and MathJax support commends, environment and functions but they have table problem.
- MathJax supports more Latex commands than Katex
- Katex supports commends, environments and functions
- Katex does not support tabular \hline environment
# it does not working in Katex \begin{array}{|c|c|c|} \hline a & b & c & \\ hline a & b & c & \\ hline \hline \end{array}
equation does not work in Katex, but it does work in MathJax
\begin{equation} e^{\pi i} + 1 = 0 \end{equation}
- itemize does not work in Katex, but it does work in MathJax
\begin{itemize} \item Justin Bieber \item Justin Trudeau \item Justin Timberlake \end{itemize}
2.0.165 Latex: The difference between $ $
$$ $$
\[ \]
and \( \)
$ $
is for Tex inline math mode,\( \)
is for Latex inline math mode.$$ $$
is for Tex display math mode,\[ \]
is for Latex display math mode.
2.0.166 Latex install package, latex package, install latex package
- download package from CTAN and unzip it
- Generate .sty file with *pdflatex command
- For Example, generate xcolor.sty file from xcolor.inc file
- An xcolor.sty file will be generated
- Copy xcolor.sty file to your .tex location or a location that pdflatex can find
- Tex file location in MacOS, or use shell script command
- latexfindpackage.sh
- latexgetpackage.sh
latex_find_package.sh xcolor.sty /opt/local/share/texmf-texlive-dist/tex/latex/xcolor/xcolor.sty
pdflatex xcolor.inc # xcolor.sty will be generated
latex utility tools
kpsewhich xcolor.sty kpsepath tex
2.0.167 Install Ace9 to my localhost saved-data-example/example.html
, javascript editor
- Finally it make autocomplete to work, it is painful to include those javascript modules in HTML file.
- You never understand how the path work in
Javascript
andNode.js
, you need to include following Javascript file. - Set your editor options
- You never understand how the path work in
<script src="ace/build/src-noconflict/ext-language_tools.js"></script> editor.setOptions({ enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true });
You need to Add your autocompleter
var langTools = ace.require("ace/ext/language_tools"); var myCompleter = { getCompletions: function(editor, session, pos, prefix, callback) { if (prefix.length === 0) { callback(null, []); return } var wordList = ["bmatrix", "vmatrix"]; callback(null, wordList.map(function(word) { return { caption: word, value: word, meta: "static" }; })); } } langTools.addCompleter(myCompleter);
2.0.168 Install Vim keybinding in ACE9 editor, all you need is one line of Javascript code.
- Code can be found here
- Make sure disable Chrome cVim extension, otherwise there is an issue when Insert mode switches to Normal mode with ESC Key.
// ace/lib/ace/keyboard editor.setKeyboardHandler('ace/keyboard/vim'); // emacs editor.setKeyboardHandler('ace/keyboard/emacs');
2.0.169 Fix dotemacs file contains stupid error with two functions with different values
I'm wondering why the
dotemacs
file does not have any color highlight because;; two lines on my dotemacs file ;; not following symlink (setq vc-follow-symlinks nil) ;; following symlink (setq vc-follow-symlinks t)
2.0.170 C programming: malloc and free, free DOES NOT mean pointer is NULL
int n = 10; char* pt = (char*)malloc(sizeof(char)* n); for(int i = 0; i < n; i++){ pt[i] = 'a'; } printf("pt = %s\n", pt); free(pt); // pt is NOT NULL pt = NULL;
2.0.171 C programming: return pointer from a function
char* fun(int n){ int size = 10; char* pt = (char*)malloc(sizeof(char)*size); for(int i = 0; i < size; i++){ pt[i] = 'a'; } return pt; } // call the function int n = 20; char* pt = fun(n); free(pt);
2.0.172 C programming: memcpy copy string
int n = 10; char* destination = (char*)malloc(sizeof(char)*n); char* source = "abcd"; // strlen(source) + 1 => copy including '\0' // strlen(source) DOES NOT include '\0' character memcpy(destination, source, strlen(source) + 1);
2.0.173 C programming: mutate parameter in a function, ampersand in C, NOT C++
#include<stdlib.h> #include<stdio.h> #include<string.h> void fun(int *n){ int k = 10; *n = k; } int main(int argc, char* argv[]){ int n = 1; fun(&n); // pass the address of n to fun printf("n=%d\n", n); // => 10 }
2.0.174 C programming: define node using struct, linked list node
define a Double LinkedList node
typedef struct CNode{ struct CNode* next; // point to next node struct CNode* prev; // point to previous node void* pt; // generic data type? } CNode; int num = 3; CNode* pt = (CNode*)malloc(sizeof(CNode)); pt -> next = NULL; pt -> prev = NULL; pt -> pt = #
2.0.175 C Programming: Three are three ways to dynamic allocate memmory
- Code Example Local Code
malloc
do nothing on the memory, allocate total amount of memory and return a pointer to the locationint len = 10; char* pt = (char*)malloc(sizeof(char)*len); for(int i = 0; i < 10; i++){ *(pt + i) = 'a' + i; } free(pt);
calloc
zero the memoryint len = 10; char* pt = (char*)calloc(len*sizeof(char)); for(int i=0; i<len; i++) printf("%x\m", pt[i]);
realloc
reallocate memory with pt, the original data will be copied over to new pointer.int len = 10; char* pt = (char*)malloc(len*sizeof(char)); pt = (char*)realloc(pt, 20*sizeof(char));
2.0.176 C Programming: C struct and typedef
Use typedef to define struct in C
typedef mystuff{ int n; char c; float fl; } stuff; stuff record; record.n = 1; record.c = 'z'; record.fl = 3.1415;
// Structure using typedef: #include <stdio.h> #include <string.h> typedef struct student { int id; char name[20]; float percentage; } status; int main() { status record; record.id=1; strcpy(record.name, "Cheetah"); record.percentage = 86.5; printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); return 0; }
2.0.177 C Programming: Check type such as int, float, double, char, long
or struct size
- See Source Code checkTypeSize.c
int num; float fl; int* int_pt; printf("int=[%d] float=[%d] int*=[%d]\n", sizeof(num), sizeof(fl), sizeof(int_pt));
how to check the size of struct
- Note: The size of struct is not always equal to the sum of each fields because the compile will do padding for some types
typedef struct MyStuff{ int num; double dfl; } Stuff; Stuff stuff; Stuff* stuff_pt; printf("stuff=[%d] stuff_pt=[%d]\n", sizeof(stuff), sizeof(stuff_pt));
typedef struct MySmall{ int n; char c; } Small; Small small; Small* small_pt; int total_struct = sizeof(small); int total_fields = sizeof(small.n) + sizeof(small.c); // totla_stuff /= total_fields
2.0.178 C Programming: const char *pt and char *pt
- Mutable pointer to Immutable location
// const char *pt = "abc"; const char pt[] = "abc"; pt[0] = 'K'; // ERROR
- Mutable pointer to mutable location
char pt[] = "abc"; pt[0] = 'K'; // OK
2.0.179 Redefine command line in Vim with following script
2.0.180 Vim tips: filter out line with new open window
- Filter out lines DOES NOT contain
^find
and open it inquickfix
widnow
:vimgrep /^find/g | copen
2.0.181 Vim tips: Insert spaces in font of selected lines
- Left shift two spaces or insert two spaces in font of selected lines
:'<,>'norm I[SP][SP]
- Right shift two spaces in selected lines, no idea why it works
- My Reddit Question
:'<,>'norm xx
- or Use Vimrc my function: LeftShiftCurrLine
:'<,>' call LeftShiftCurrLine(2)
2.0.182 Vim tips: call function in visual selected lines, function with range
- MyFun will be called in range
'<
and>'
:'<,>' call MyFun()
2.0.183 TODO Move all the haskell file to $hlib
in $b/haskellwebapp2
Move all files to
$hlib
AronModule.hs AronHtml.hs WaiLib.hs WaiConstant.hs GenePDFHtmlLib.hs
2.0.184 TODO Try this code Copy and paste
2.0.185 TODO Emacs: universal-argument, What the hell is universal-argument?
- have something to do with
C-u
See example - If your keybinding is
C-k
, then you can define your prefix keyC-u
withC-k
\(\Rightarrow \)C-u C-k
- How to capture the universal-argument value? use
current-prefix-arg
to get the possible values Values
2.0.186 MacOS: Screen Capture with screencapture command
- delay 3 seconds to capture your screen
screencapture -T 3 delayedpic.png
2.0.187 Change haskell document background color from dark mode to light mode
dark mode or light mode \(\Rightarrow \)
$scr/haskell_doc_mode.sh
haskell_doc_mode.sh d haskell_doc_mode.sh l
2.0.188 Haskell some cursor movement and ANSI console color
- ansi-terminal library, move cursor to nth char to the right/left/up/down, set background and foreground color in console
2.0.189 Customized Latex Input Method or TeX Input Method in Emacs
- function name in dotemacs file:
latex-input
\( \Rightarrow \)set-input-method "TeX"
latex-input-symbol
\( \Rightarrow \)describe-input-method "TeX"
- Offical Doc How to Do it Stack Overflow
2.0.190 iTerm2: iTerm2 profile can be saved in your local folder
2.0.191 iTerm2: Import profile (JSON) file to your iTerm2
2.0.192 iTerm2: Fixed tmux and iterm2 problem: backspace key DOES NOT work in
Here is step how to fix in iterm2 SO References
- I just found it does not fix the issue yet. When switch tmux windows, the backspace key still has issue.
- It does not fix the backspace yet (06-01-2020)
2.0.193 iTerm2: trigger regex, color highlight in iTerm2
- Using ICU Regex Expression ICU Regex
2.0.194 tmux: fixed copy-mode-vi use 'v' to select text and 'y' to copy text in tmux
- NOTE: kill all your tmux sessions before restart your tmux.
tm l
Set your tmux to use Vim keybinding in
/.tmux.conf
set-window-option -g mode-keys vi #copy-mode vim-like
Install
reattach-to-user-namespace
brew install reattach-to-user-namespace # run reattach-to-user-namespace to confirm
Confirm
reattach-to-user-namespace
commandecho 'hi' | reattach-to-user-namespace pbcopy # 'hi' should be in your clipboard
Vim like copy with 'y'
bind -T copy-mode-vi y send -X copy-pipe "reattach-to-user-namespace pbcopy" \; send -X clear-selection # Copy to clipboard
2.0.195 Haskell: just learn something new today, you can use read function to read a list of type, e.g [1, 2, 3]
read a list of Int or Integer
read "[1, 2, 3]"::[Int] -- [1, 2, 3] read "[1, 2, 3]"::[Integer]
2.0.196 Java doc: use latex for Java document with java doclet
- Java Doclet github
You need maven to install the Latex Java Doclet or if you want to install the artifact to specific directory
mvn clean install TeXDoclet.jar to $HOME/.m2/repository/org/stfm/texdoclet/0.9-SNAPSHOT/texdoclet-0.9-SNAPSHOT.jar dependency-reduced-pom.xml $HOME/.m2/repository/org/stfm/texdoclet/0.9-SNAPSHOT/texdoclet-0.9-SNAPSHOT.pom
2.0.197 Java: When to pass Iterator or List inside your recursion code
- When you deserialize your binary tree from a file, then you can think about how to pass the preorder elements to your recursion code
List<String> list = Arrays.asList("cat", "dog"); Iterator<String> ite = list.iterator(); while(ite.hasNext()){ pb(ite.next()); }
- The following picture shows your why you need Iterator instead of List inside your recursion code.
2.0.198 Microsoft Phone call interview for Large scale service and distribution system
- Renell Nakayama-Roberts will call me today. I'm not sure what to expect?
- She asked me to put her name on the site when I apply the job in MS website.
- Question: What is your responsibilities in the company?
- What is the challenge that you have in the project?
- I will give some overview on our Edge team in MS
- I will give some overview on the interview process.
2.0.199 Java: I just learned in Java 9 there is something called Module
From Oracle website, Module is a set of packages, I think it is similar to package but it is on top of package
// define package package my.company.fooClass
// how to define module?
2.0.200 English: coercion [kəʊ'ɜʃən]
- the use of force to persuade someone to do something they are unwilling to do
2.0.201 Elips: I struggle to figure out how to run Graphviz or dot file under Org-mode in code block
- When you Google around, you will find lots of wrong suggeston how to set it up.
- Some sites only tell you that you only need following code inside your
init.el
or.emacs
file
- Some sites only tell you that you only need following code inside your
(org-babel-do-load-languages 'org-babel-load-languages '((dot . t))) ; this line activates dot
- The author assume you have added
graphviz-dot-mode
to'load-path
- You copy their snippet to your
.emacs
and hope you can compile dot file inside your code block and see your awesome image. Unfortunately you can see anything and you don't what to do. But you never give up, and try to Google around and copy more snippet into your
.emacs
file. and you are still out of luck.- most of author did not tell that you need to add the path that points to your
graphviz-dot-mode
directory. Well, where is the path in your machine?
most tutorial does not tell you where is your
graphviz-dot-mode-xxx
directory. Ofcouse you never understand why you can not display image.- most of author did not tell that you need to add the path that points to your
- The default path is
$HOME/.emacs.d/elpa/graphviz-dot-mode-xxx
, it can be different if you have different configuration path in your your emacs.- Once emacs knows the path to your
graphviz-dot-mode-xxx
, you jut load binarydot
to run your dot file withC-c C-c
- Once emacs knows the path to your
2.0.202 Haskell: conversion between numbers, Float to Int, Double to Int, Float to Integer
- Num is like Number abstract class in Java
- Java Abstract Class Number
ceiling :: (RealFrac a, Integral b) => a -> b floor :: (RealFrac a, Integral b) => a -> b truncate :: (RealFrac a, Integral b) => a -> b round :: (RealFrac a, Integral b) => a -> b
Float and Double
float2Double :: Float -> Double double2Float :: Double -> Float
fromIntegral::(Num b, Integral a) -> a -> b
2.0.203 Math: Geometric Proof \( \sin{2\theta} = 2\sin{\theta} \cos{\theta} \)
2.0.204 Jupyter: For Haskell and Python or ihaskell like Python Jupyter lab
- One quesiton is how to import your own module in Haskell console.
- Finally I found out how to import your own module to Jupyter iHaskell.
- I was struggling with how to import my own Haskell module to iHaskell or Jupyter.
- The solution is dead simple and I have known the answer for long time
But the catch is you need to run
jupyter-lab
under stack with followingstack exec jupyter-lab
:load /Users/cat/myfile/bitbucket/haskelllib/AronModule.hs
- Goto your the root directory of your stack project run following commands
stack exec jupyter-lab
- I still have no clue how to import my own module.(09-03-2020)
- Jupyter is very powerful tool, you can export your code to many file format such as Html, Latex
- You can change Dark or Light theme which is very import when you are working at night.
- Can not figure how to load your own package or module ihaskell
- From ihaskell github, you need to add your package to your stack.yaml in ihaskell
- They assume you always keep your ihaskell directory? I think so. And you need to run
stack solve && stack install
- I think you can load your own package from Jupyter console.
- I wish iHaskell can load your
ghci.conf
so that you do not need to load all your packages separately.
- I wish iHaskell can load your
You need to follow the steps to install in Your MacOS iHaskell
brew install python3 zeromq libmagic cairo pkg-config haskell-stack pango git clone https://github.com/gibiansky/IHaskell cd IHaskell pip3 install -r requirements.txt # stack install gtk2hs-buildtools # Disabled for now because gtk2hs-buildtools doesn't work with lts-13 yet stack install --fast ihaskell install --stack
Check whether you have
ihaskell
which ihaskell # your installation successes /Users/cat/.local/bin/ihaskell
- Run your ihaskell from your command line. Assume you have stack installation.
stack exec jupyter -- notebook
When you open your browser, you most likely DO NOT what to do because it is very confusing, you do not know where to write your code, how to run your code.
- You need to click on New and select your languages to open the editor.
- I ask question on Reddit how to change light-mode to dark-mode. The answer is you need to change color theme in Jupyter lab not ihaskell
- because ihaskell use Jupter as fontend. All you need to do is run Jupyter lab in command line and change color mode like in Python.
jupter lab
2.0.205 Haskell: Mutable array, Haskell Array
- Example Code Mutable Array
- import library for mutable array
- create new array, make sure the
::IO(IOArray Int Float)
as annotation - write element to mutable array
read element to mutable array
import Data.Array.IO -- create mutable array arr <- newArray (2, 10) 1.0 :: IO(IOArray Int Float) -- read index 3 from arr n <- readArray arr 3 -- write 9 to index 3 arr writeArray arr 3 9
Initialize array with list
mapM_ (\x -> writeArray arr x 3.14) [2..10]
Two dimensions mutable array in Haskell
import Data.Array.IO -- create (m, n) array arr <- newArray (0, 0) (10, 10) 3.14 :: IO(IOArray (Int, Int) Float) n <- readArray arr (2, 2) writeArray arr (2, 2) 6.28
Construct mutable array with a list
let ls = [1..10] arr <- newListArray (1, 10) ls
map over a mutable array with a function
f::a -> b
arr <- newArray (0, 4) 1 marr <- mapArray (+2) arr -- [3, 3, 3, 3]
2.0.206 Java: Integer can be 10x slower than int
- Compare boxed Integer and unboxed int
- See test case Integer and int speed
2.0.207 Java: Initialize int[]
and Integer[]
in Java
I just realize the default value for
Integer[] mat
is not zero, instead it isnull
int[] mat = new int[3]; // mat = {0, 0, 0} Integer[] mat = new Integer[3]; // mat = {null, null, null}
2.0.208 Java: QuickSort to Kth smallest element
- Approach the problem
- Change Kth \( \{1, 2, \cdots, n \} \) to Index \( \{0, 1, \cdots, n-1 \} \)
- Write a quick sort algorithm
write partition code
int partition(int[] arr, int lo, int hi);
write quick sort code
void quickSort(int[] arr, int lo, int hi){ if(lo < hi){ int pivot = partition(arr, lo, hi); quickSort(arr, lo, pivot - 1); quickSort(arr, pivot + 1, hi); } }
- Modify quicksort code to branch to left or right branch.
int quickSortKIndex(int[] arr, int lo, int hi, int kInx){ if(lo < hi){ int pivot = partition(arr, lo, hi); if(kInx < pivot) return quickSortKIndex(arr, lo, pivot - 1); else if(kInx == pivot) return arr[pivot]; else return quickSortKIndex(arr, pivot + 1, hi, kInx - (pivot + 1)); } }
2.0.209 MacVim: Render unicode or emoji issue in MacVim,
- Here is the fix OS goto Preferences \( \Rightarrow \) Advanced \( \Rightarrow \) disable Use Core Text Renderer
2.0.210 Coin and Coding theory
- The site contains good coding examples
- Coin Coding theory
2.0.211 Edit String Distance Algorithm: find the minimum weight to convert string \(s_1\) to \(s_2\) in dynamic programming
- The weight of insection is \(1\)
- The weight of deletion is \(1\)
- The weight of substitude is \(0\) if both characters are the same, otherwise \(2\)
- PDF Reference
- Minimum Edit String Distance in Java
minimum edit distance function: \[ \text{ convert string } s_i \Rightarrow s_j \]
\begin{aligned} n_i &= \text{ length of } s_i \qquad n_j = \text{ length of } s_j \\ \text{ weight of deletion } w &= 1 \\ \text{ weight of insection } w &= 1 \\ \text{ weight of substitude } w &= 2 \\ i &= 1 \dots n_i \\ j &= 1 \dots n_j \\ D(i, 0) &= 1, 2, 3, \dots n_i \\ D(0, j) &= 1, 2, 3, \dots n_j \\ D(i, j) &= min \begin{cases} D(i-1, j) + 1 \\ D(i, j-1) + 1 \\ D(i-1, j-1) + \begin{cases} 0 \text{ if } d_{i-1} = d_{j-1} \\ 2 \text{ if } d_{i-1} \ne d_{j-1} \end{cases} \end{cases} \end{aligned}
2.0.212 \(\LaTeX\) What I learn in Latex today
- Latex environment is defined by
\begin{}
and\end{}
And you can define your own environment by
\newenvironment
Environments- It seems to me the syntax is horrible. Maybe I should not try to understand it.
\newenvironment{boxed}[1] {\begin{center} #1\\[1ex] \begin{tabular}{|p{0.9\textwidth}|} \hline\\ } { \\\\\hline \end{tabular} \end{center} } %-------------------------------------------------- Below this line a boxed environment is used \begin{boxed}{Title of the Box} This is the text formatted by the boxed environment \end{boxed} This text is again outside the environment
2.0.213 \(\LaTeX\) What I learn today?
- I never use floor and ceiling in \(\LaTeX\)
- Write floor and ceiling is more complicated than what I thought. Why there is no simple command for that?
- Here is how to write floor and ceiling symbol in \(\LaTeX\)
\left \lfloor{x} \right \rfloor \left \lceiling{x} \right \rceiling
\[ \left \lfloor{x} \right \rfloor \left \lceil{x} \right \rceil \]
2.0.214 \(\LaTeX\) Color Your mathematic formulas.
Use
\color{}{}
\color{red}{M = \begin{bmatrix} a & b \\ c & d \end{bmatrix} }
\[ \color{red}{M = \begin{bmatrix} a & b \\ c & d \end{bmatrix} } \]
\color{red}{M = \begin{bmatrix} a & b \\ c & d \end{bmatrix} }
\[ \color{green}{M = \begin{bmatrix} a & b \\ c & d \end{bmatrix} } \]
\color{yellow}{M = \begin{pmatrix} a & b \\ c & d \end{pmatrix} }
\[ \color{yellow}{M = \begin{pmatrix} a & b \\ c & d \end{pmatrix} } \]
2.0.215 Excel Column Header: algorithm in Java.(15-11-2019)
- Need to shift the index from 1 to 0
(n - 1) % base
since \(n\) starts from \(1\) - Need to shift module to right
(n - 1) % base + 1
Similar to rotate string to the right or to the left Rotate String
public static String excelColumn(int n){ int base = 3; String s = ""; if(n == 1){ s = "Z"; } else{ while(n > 0){ int q = (n - 1) / base; // n - 1 => shift from 1 to 0 since n starts from 1 int r = ((n - 1) % base) + 1; // 1 -> A s = intToAlphabetUpper(r - 1) + s; n = q; } } return s; }
- Source Code
// 1 -> A // 2 -> B // 3 -> C // 4 -> AA while( ){ }
2.0.216 Interview question: Print Excel column header pattern
- Given \( n \in \{1, 2, \cdots \} \) print following pattern
The problem is different from binary system is the base is not fixed number. The base is Geometric Series
- If the base is \(3\), then the Excel column header will be based on following Geometric series
\[ \color{red}{S = 3^1 + 3^2 + \cdots + 3^k} \]
If \( n = \{1, 3^1 + 3^2 + 3^3 \} \) then the following pattern will be generated
\begin{aligned} 3^1 = \begin{bmatrix} a \\ b \\ c \end{bmatrix} \qquad 3^2 = \begin{bmatrix} aa \\ ab \\ ac \\ ba \\ bb \\ bc \\ ca \\ cb \\ cc \end{bmatrix} \qquad 3^3 = \begin{bmatrix} aaa \\ aab \\ aac \\ aba \\ abb \\ abc \\ aca \\ \vdots \\ ccc \end{bmatrix} \end{aligned}\( S \) can be computed with Geometric Series
\begin{aligned} S &= x^1 + x^2 + \cdots + x^n \\ xS &= x^2 + x^3 + \cdots + x^{n+1} \\ S(x - 1) &= x^{n+1} - x \\ S &= \frac{x^{n+1} - x}{x - 1} \\ S &= \frac{x^{n+1} - x}{x - 1} \\ x^{n+1} &= S(x-1) + x \\ n+1 &= \log_x^{S(x - 1) + x} \\ n &= \log_x^{S(x - 1) + x} - 1 \\ n &\text{ is the closest integer to the sum of geometric series equals to S} \\ \text{Example:} \\ x &= 3 \quad S = 3 \\ \text{ We have following } \\ n &= \log_3^{3(3 - 1) + 3} - 1 \\ n &= \log_3^{9} - 1 \\ n &= 1 \\ \text{We can use } S \text{ subtract } 3^{n=1} \quad \text{which is equal to zero}\\ \text{ from } S &= x^1 + x^2 + \cdots + x^n \\ x &= 3 \quad S = 3 \quad n = 1 \\ \therefore 3 - 3^{1} &= 0 \\ \text{The next geometric series term is } 3^{2} \text{ and the initial value is } 0 \\ \\ &\begin{bmatrix} a & \color{green}{ \leftarrow } 0 \\ b & \color{green}{ \leftarrow } 1 \\ c & \color{green}{ \leftarrow } 2 \\ aa & \color{red}{ \leftarrow } 0 = 3 \\ ab & \\ ac & \\ \vdots \end{bmatrix} \\ x &= 3 \quad S = 10 \\ \text{ If } S \text{ is } 10, \text{ We have following } \\ n &= \log_3^{10(3 - 1) + 3} - 1 \\ n &= \left \lfloor{ 1.58 } \right \rfloor = 1 \\ 10 - 3^{1} &= 7 \\ &\begin{bmatrix} a & \color{green}{ \leftarrow } 0 \\ b & \color{green}{ \leftarrow } 1 \\ c & \color{green}{ \leftarrow } 2 \\ aa & \color{red}{ \leftarrow } 0 = 3 \\ ab & \\ ac & \\ ba & \\ bb & \\ bc & \\ ca & \\ cb & \color{red}{ \leftarrow } 7 \\ cc & \\ \vdots \end{bmatrix} \end{aligned}Use geometric series to solve the problem
\begin{aligned} S &= x^1 + x^2 + \cdots + x^n \\ xS &= x^2 + x^3 + \cdots + x^{n+1} \\ S(x - 1) &= x^{n+1} - x \\ S &= \frac{x^{n+1} - x}{x - 1} \\ S &= \frac{x^{n+1} - x}{x - 1} \\ x^{n+1} &= S(x-1) + x \\ n+1 &= \log_x^{S(x - 1) + x} \\ \color{red}{n} &= \left \lfloor{\log_x^{S(x - 1) + x} - 1}\right \rfloor \end{aligned}- The problem can be solved with permutation \( \{0, 1, 2 \} \) algorithm
- Each each digit can be repeated
- The length of string are from \(1\) to \(3\)
2.0.217 Interview: Partition array
- Given a list of integer, partition the array to two subarray
- Sort the array in increasing order
- Sum them up \( S = \sum_{i=i}^{k} a_i \)
- Subtract one element one by one in one side until the value is less or greater than the \( \frac{S}{2} \)
- The question is related to find the square root of integer \( n \)
2.0.218 Tmux: you can switch window id number between two windows
Assume you have two widows
1:Python 2:Java
# `: # -s => source # -t => target :swap-window -s 1 -t 2
2.0.219 Command Line: copy and paste on MacOS, copy to clipboard and paste from clipboard
copy stdout to *clipboard' and paste clipboard to stdin
echo 'hi' | pbcopy pbpaste > /tmp/kk.x
2.0.220 Preorder Iterator
- Write code from the picture
- How many stack do we need?
- Where and when we need a marker
- Actually you do not need a marker for preorder traveral, it is for postorder
- postorder can be implemented with two stacks
2.0.221 Emacs Elisp What I learn from Emacs today? I'm always wondering how to move around without pressing the CTRL key
- There is Evil mode in Emacs and I did install it on my Emacs but I want something lightway and customized in Elisp.
- extra-keyboard-modifiers is something very close what I'm looking for.
You can set to C-a or C-anything then all the keys will be prefixed with CTRL
# enable it (setq extra-keyboard-modifiers ?\C-x) # disable it (setq extra-keyboard-modifiers 0)
- Currently I map it to F10 to toggle between 0 and ?\C-anything
2.0.222 Emacs Reload dotemacs file is not necessary to reload everything, Use kill-buffer after reload dotemacs
# after reload ~.emacs (kill-buffer)
2.0.223 Elisp Good tutorial to learn lisp
- Good tutorial Lisp tutorial
2.0.224 Elisp Unicode can be the name of function, factorial function
(defun ⊗(n) (if (or (= n 0) (= n 1) 1 (* n (⊗ (- n 1))) ))) (⊗ 4)
2.0.225 Haskell: createProcess in Haskell error
- Finally I fixed the error from createProcess function Haskell
- If you run createProcess and DO NOT wait to terminate in the infinite loop then you will run many zombie processes.
- See runRawCmd in
AronModule.hs
- Fixed error in
$b/stackproject/fileWatcher.hs
- See runRawCmd in
2.0.226 Interview partition a binary array to three parts and they all have the same binary values. (Youtube Netflix interview) You Tube
- The problem is similar to find two sums are the same from a list of integers
- sort them
- two pointers from the left and right
- compare the sum of two end to the middle value
- If the sum is greater than the middle value increase the big pointer
- If the sum is less than the middle value increase the small pointer
- The problem is like a balance with pivot, how to adjust your pivot when both ends are not balanced.
- Move the pivot to the left or right. when and how?
Given a binary array. e.g
arr = [0, 1, 1, 0, 1]
. find \(i, j\) such as[0, i) == [i, j) == [j, len(arr))
arr = [0, 1, 1, 0, 1] b1 = [0, 1] b2 = [1] b3 = [0, 1] # => b1 == b2 == b3 arr = [0, 1, 0] # => no such partition
- First Observation
- Create two pointers \(i, j\) from index
[0]
and index[len(arr)-1]
- \(i\) will move to the right, increasing
i = i + 1
. \(j\) will move to the left, decreasingj = j - 1
- \(i\) will move to the right, increasing
- If the left and right parts are the same then compare middle part with one part, e.g. left part.
If the middle part is greater than the left part, then shift the \(j\) to the left. \( \Rightarrow \) decrease the middle part and increase the left part. If the middle part is less than the left part, then return No such partition
- If the left and right are not the same
- If left \( > \) right then shift \(i\) to the right \( \rightarrow \)
- If left \( < \) right then shift \(j\) to the left \( \leftarrow \)
2.0.227 Java compile java file, Run Java, make Java Executable, Jar file
It is painful to compile java file
# jar file is under /mylib/jar # Hello.java is in dir /myjava # /myjava has to be the dir of Hello.java, Why?.. # -cp => classpath javac -cp /mylib/jar/*:/myjava /myjava/Hello.java # run class file Loopit in $b/javaclass java -cp /Users/cat/myfile/bitbucket/javalib/jar/*:/Users/cat/myfile/bitbucket/javaclass/ Loopit
2.0.228 Greek Letters
α | \alpha |
υ | \upsilon |
β | \beta |
φ | \phi |
γ | \gamma |
χ | \chi |
δ | \delta |
ψ | \psi |
ε | \epsilon |
ω | \omega |
ζ | \zeta |
Δ | \Delta |
η | \eta |
Γ | \Gamma |
θ | \theta |
Θ | \Theta |
κ | \kappa |
Λ | \Lambda |
λ | \lambda |
Ξ | \Xi |
μ | \mu |
Π | \Pi |
ν | \nu |
Σ | \Sigma |
ξ | \xi |
Υ | \Upsilon |
π | \pi |
Φ | \Phi |
ρ | \rho |
Ψ | \Psi |
σ | \sigma |
Ω | \Omega |
τ | \tau |
2.0.229 Differential Geometry Note
- What is manifold
- One thing pops up on my mind is something like a donut or sphere.
- How we characterize those surfaces? Good question but I did not have the answer for it.
I think differential geometry is studying the surface and how to translate the highter dimensions problem to lower dimensions problem. The surface of sphere is like flat surface if you are standing on a large sphere. e.g. we did not know the earth is a sphere until some smart guy figured it out(who, when, how?).
- How to translate the highter dimensions problem to lower dimensions problem?
Map a curve to a line
- There are many problems with it, e.g. the length of the curve is changed. We might address those problems late.
\begin{aligned}
&\text{map line to curve}
f(x) &= x2 + 1 \quad x ∈ \{0, 1\}
&\text{map curve to line, just project the curve on x-axis}
f(x2 + 1) &= x \quad x ∈ \{0, 1\}
&\text{Like const function in Haskell, is called projection function}
(x, x2 + 1) &= x \end{aligned}- There are many problems with it, e.g. the length of the curve is changed. We might address those problems late.
\begin{aligned}
&\text{map line to curve}
Map the curve surface to flat surface, it not always work if the surface has more than one \(z\) values
- What is smooth manifold?
- This is not smoothy like strewberry and mikeshake in MacDonald, We are talking about surface.
- smooth means here is infinitely differentiable, What the hell does it mean?
- Let see a function \( f(x) = x \), the first derivative is \( f'(x) = 1 \)
- The second derivative is \( f''(x) = 0 \), and the thrid derivative is \( f'''(x) = 0 \)
- So \( f(x) = x \) is smooth
non-smooth function
\begin{aligned} &f(x) = x^{\frac{3}{2}} \quad x \in \{0, 1\} \\ &f'(x) = \frac{3}{2} x^{\frac{1}{2}} \quad x \in \{0, 1\} \\ &f''(x) = \frac{3}{4} x^{-\frac{1}{2}} \quad x \ne 0 \\ \end{aligned}\( f''(x) \) is not longer defined when \( x = 0 \)
- What is Chart?
- What is alta?
- Manifold is big word but it is simple idea.
- Embed one dimension object into two dimensions space.
- What does it mean?
2.0.230 Derivative of \( \sin{\theta} \) and \( \cos{\theta}\)
- See the picture first.
The derivative of \( \sin'{\theta} = \cos'{\theta} \) and \( \cos'{\theta} = -\sin{\theta} \) It is much easy to look at the picture of \( \sin{\theta} \) because when \( x \in [0, \frac{\pi}{2}] \) the slop of tangent line is positive.
2.0.231 Derive the length of 2D dimension curve.
Find the length of curve \(f(x) = x^2\)
2.0.232 Haskell: Learn how to use parser which is parsec package
- parsec is pretty popular parser in Haskell
- I'm following this tutorial to write a Scheme Write a Scheme in Haskell
- Use Parsec. Also there is paper about the it [[
- So far, it is hard to understand what is Monad Combinator. But it seems to me it is very powerful technic.
- Parsec uses different Parsec combinator to combine parser with operator <|>. It looks very elegrant.
- How to use inductive type, sum type in Haskell to define some type in Scheme
data LispVal = Atom String | List [LispVal] | DottedList [LispVal] LispVal | Number Integer | String String | Bool Bool
- Above define some Type in Scheme
Atom "abc"
is an Atom in Scheme- It is surprised
Bool Bool
does not have any error
- The value constructor
Bool Bool
wrapsBool
type in Haskell to our new typeBool Bool
- I could not image how to implemente it in Java
- It is surprised
2.0.233 Apparently Java random number generator (Math.random()) use very simple algorithm: linear congrential formula
- What is Linear Congrential Generator (LCG)
- \(X_i\) is the seed
- \(a\) is the multiplier
- \(c_0\) is the increment
- \(m\) is the modulus \[ X_{i + 1} = a X_{i} + c_0 \mod m \]
2.0.234 There is very weird random number result that I got today in Java
- Use
Math.random() * magnitude
andMath.round()
and AronLib.javalongToInteger()
- Not sure why 0 and 10 are both only half numbers of count comparing to other numbers
public static void test6(){ beg(); { Map<Integer, Integer> map = new HashMap<>(); for(int i=0; i<100000; i++){ Integer n = longToInteger(Math.round(Math.random()*10)); Integer v = map.get(n); if(v == null){ map.put(n, 1); }else{ v += 1; map.put(n, v); } } pp(map); } end(); } // output: // {0=5007, 1=9905, 2=10126, 3=10053, 4=9934, 5=10180, 6=10011, 7=10062, 8=9934, 9=9981, 10=4807}
2.0.235 Git tutorial
Create new local branch
git checkout -b mybranch
Delete your local branch (be careful)
git branch -d mybranch
2.0.236 Git What is rebase
- Think about linkedlist in Git.
- Here is tutorial. git rebase
- When to use merge and rebase?
- What is HEAD, Master and Origin or Remote?
2.0.237 Write code to solve following problem, Article Ltd. interview question in Hackerrank
Given a list of cities such as
[2, 3, 4, 2]
. Each city is denoted by by[i]
where \( i \in \{0, 1, 2, 3 \} \)- If a person travels from city [i] to city [j] then \( i \) must be less than \( j \)
- The fuel is used from one city to other city is defined by the absolute difference between two cities.
- city [1] \( \rightarrow \) city [2]
// fuel is used by the car from city 1 to city 2 is following int df = Math.abs([1] - [2]);
# i < j [i] -> [j]
let ls = [2, 3, 4, 2] ls[0] = 2 ls[1] = 3 ls[2] = 4 ls[3] = 2
- What problem that we knew that it similar to ?
- The simplest one is Binary Search Tree problem.
Given a Binary Search Tree, from all the paths from the root to the leaf node.
- It can be solved with preorder traveral and add all the path to
List<List<Integer>> lss
- It can be solved with preorder traveral and add all the path to
2.0.238 XCode code sign or XCode sign is painful. Apple tries to ask you to pay them for nothing.
- Apple update your MacOS and change your Xcode code setting, They try to fool you to pay them for nothing.
- You can not compile your code in XCode, and you need to sign in to your Apple Account. What the fuck?
You need to go through millions of setttings in Building Settings and try to find Signing and change to Don't Code Sign
- Update: XCode 11.31 removes Don't Code Sign
- Choose Other and put an empty string on it.
2.0.239 XCode: update to MacOS Catalina 10.15.3 and XCode to 11.3, my cpp library is broken
- Still have no idea how to build my code so far.
- Apple remove following header in C++14, and use C++17
<optional>
- I change my XCode
c++14
toc++17
and use<optional>
but it got other errors. - Path to experinment C++14 optional lib
- I change my XCode
/Library/Developer/CommandLineTools/usr/include/c++/v1/experimental
<experinmental/optional> // change to // C++17 <optional>
2.0.240 MacOS Error:
stack build error # stack-2.1.3
ar: internal ranlib command failed
but maybe removing ranlib from /opt/local/bin and using system /usr/bin/ranlib fix the issue for you as well.
- Remove
/opt/local/bin/ranlib
and symbol link to/usr/bin/ranlib
2.0.241 Group Representation Theory
- What is Group Gepresentation Theory?
- Why we need them?
- How it can help us to solve problem?
- Rotation group map to rotation matrix?
- I have read many pages in Google but I still have no clue what does Group Representation mean
2.0.242 Virtual Proof of Pythagorean Theorem, and rotate matrix or rotate array in 90 degrees
\[ a^2 + b^2 = c^2 \]
- Fact, rotate a square 90 degrees algorithem is indirectly related to following proof
2.0.243 What to do next?
- Change responseNothing to repsonse Search Header
2.0.244 Haskell run inline javacode
- Run Inline code inside Haskell \( \Rightarrow \) Nothing is impossible:)
- Serialize and Deserialize Objects
- Use JSON
- MessagePack MessagePack Binary Format. The file is smaller than JSON.
- Ceral, it seems to me it is only for C++ ceral
- Compare JSON, MessagePack and cereal Reddit Comparison
2.0.245 GHC many good plugins
2.0.246 Add test file to Haskell Stack
- stack is
stack --version
2.1.3 use
new-template
stack new helloworld new-template
ghc-8.8.x
will be download and I change it back toghc-8.4.x
with follwingChange resolver in your
stack.yaml
file# new resolver resolver: its-15.5 => ghc-8.8.3 resolver: its-12.16 => ghc-8.4.x
- Build it and run it, it seems to me
stack exec helloworld
does not work any more, why?
helloworld-exe is in stack.yaml
file in section: executable: helloworld-exe
stack build stack exec helloworld-exe
2.0.247 Haskell stack test error stack test
. Finally I fixed the stupid error /opt/local/bin/strip
- Link
- cabal copy failed, It turns to be bad version of
/opt/local/bin/strip
in MacOS - MacOS 10.15.3 Catalina, stack version: 2.1.3
- This is very stupid error after I upgraded my MacOS to 10.15.3 Catalina
- There are two
strip
on MacOS, one is in/opt/local/bin/strip
, other one is in/usr/bin/strip
- There are two
and stack test
uses /opt/local/bin/strip
which is the problem. Why? who know..
/opt/local/bin/strip
- This
/opt/local/bin/strip
is not working when I usestack test
command to run test cases - Apparently you need to use
/usr/bin/strip
instead so you need to rename it and create symbol link to/usr/bin/strip
/opt/local/bin/strip # rename it, strip_old ln -s /usr/bin/strip /opt/local/bin/strip
2.0.248 Haskell stack file watch
Rebuild automatically.
--file-watch
option. Build file automatically when files are modifiedstack build --file-watch
Fast rebuild.
--file-watch --fast --pedantic
which turns off-o0
optimizationstack build --file-watch --fast # use --pedantic flag if you want to fix all warning (-Wall and -Werror). stack build --fast-watch --fast --pedantic
2.0.249 Haskell NonEmpty list from package Data.List.NonEmpty
You dont need to worry head last tail init problem when the list is empty
:m +Data.List.NonEmpty ls = 3 :| [4] lss = 2 <| 1 <| ls
2.0.250 Neovim can use vimrc
file with following command nvim
- But Timer or Channel does not work so far. Not sure why
- Neovim use
/.config/nvim/init.vim
file as vimrc file
nvim -s ~/.vimrc
2.0.251 Add Python code template to generatecode.hs file.
2.0.252 Python: GUI, Kivy is pretty impressive GUI for Python.
2.0.253 Python: Generate source code color highlight with Pygmentize
# full Html document pygmentize -f html -O full -o test.html test.java
2.0.254 Python: Install Jedi package in Emacs for autocomplete, there is some issues on virtualenv error. (28-01-2020)
- Jedi document.
- How to install Jedi.
- How to config your
.emacs
file - Apparently, it does not work for me.
I got some error messages:
Error (jedi): Failed to start Jedi EPC server. You may need to run "M-x jedi:install-server". This could solve the problem especially if you haven't run the command yet since Jedi.el installation or update and if the server complains about Python module imports.
- You need to add the following to your
.emacs
to fix it
- You need to add the following to your
And you need to install visualenv on your system.
pip install virtualenv
(custom-set-variables '(jedi:environment-root "jedi"))
- Here is the link, it help me to fix the issue: Python Emacs Install Jedi
- Python file is loaded you need to run
M-x jedi:install-server
- It works so far, it also autocompletes your own module.
- Just found out some issues:
- some name is not from my own module but it shows up in the autocomplete list, no idea why
- It is a bit slow to show up the autocomplete list items on Emacs, not sure why
2.0.255 Python: draw binary tree with Python
- It is not that simple to draw binary tree with Python GUI tkinter code.
- This is very minimum code to write a circle
from tkinter import * root = Tk() myCanvas = Canvas(root) myCanvas.pack() create_circle(10, 10, 5, myCanvas)
- Write code to traveral the binary tree
- Store coordinates in each nodes
- Get the relationship between parent and child, e.g. a list of edges
- Keep track of the level of each node
2.0.256 Python Version Hell:) python3 numpy can not be found in MacOS Catalina
- There ther three different versions of Python on my MacOS Catalina,
python python2 python3
so far under/usr/local/Cellar
- After upgrade my MacOS to Catalina and Python has hard time to find their libraries
python3 import numpy as np # error numpy can not be found
2.0.257 Python import package in full path? why?
There are too many versions of python on your MacOS and I have no idea which version of framwork I'm using
- SO It seems to me this is best way to resolve confusing
import sys sys.path.append("/usr/local/lib/python3.7/site-packages") import numpy as np
2.0.258 XCode error, Swift 5 using wrong SDK on MacOS
- MacOS Catalina 10.15.4, Swift 5, and XCode Version 11.3.1 (11C504)
See my post on Reddit Swift 5 Error
Change macOS SDK inside Build Settings does not affect SDKROOT points to OLD SDK under
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs DriverKit19.0.sdk MacOSX.sdk MacOSX10.07.sdk MacOSX10.15.sdk
I did follwoing someone suggestions on Reddit and deleted my App in
/Users/cat/Library/Developer/Xcode/DerivedData
- Restart My XCode and still DOES NOT Fix above error.
2.0.259 XCode how to edit your scheme in XCode, manage scheme, xcode scheme
2.0.260 Haskell ReaderT best explanation Tom and Jerry Example
- ReaderT Explanation
2.0.261 Haskell (->) r is a Functor, best explanation
- Partial function
(->) r
is Functor Best explanation Good YouTube Video Partial Function as Functor
class Functor f where fmap::(a ->b) -> f a -> f b instance Functor Maybe where fmap _ Nothing = Nothing fmap g (Just x) = Just (g x)
2.0.262 Sqlite3 Java insect, select, update batch insection
- Sqlite3 Batch insection Java Setup.
- Set auto commit to false
- Create PrepareStatment
- Batch rows
- Execute batch
- Commit
- Set auto commit to true
- Show me your code
2.0.263 Fixed issue in bitbucket javascript folder. You thought you have checkined your code, but it is not.
- Folder contains
git info such as .git and .gitignore
. It will cause issue when your folder inside a git. - Just fix the issue after I remove
.git and .gitignore
in order to push eletron-quick-start to bitbucket
2.0.264 The Good and Bad of Nodejs and Eletronjs
- Good: It is easy to install package and it is easy to use. It is just Javascript
- Bad: I always encouter a bug when I create a simple popup UI called at
$b/javascript/popupshare
The code is really simple, you can image what if you want to create some complicated UI.
2.0.265 Haskell, monad binding operator: =<< >>=
=<< >>=
both are same operator, monad binding-- simplifed version of definition class Monad m where (>>=) :: m a -> (a -> m b) -> m b return:: a -> m a -- actual definition class Applicative m => Monad (m::* -> *) where (>>=) :: m a -> (a -> m b) -> m b return :: a -> m a (=<<) :: (a -> m b) -> m a -> m b let m = Just 2 return =<< m -- => return 3 m >>= return -- => return 3
2.0.266 Python startup file, Yep, Python does not have startup file like bashrc
- But Python have environment variable called PYTHONSTARTUP
- Of couse the author will have story to tell because startup file will blow up your computer.
export PYTHONSTRTUP=$b/publicfile/pythonstartup.py
- You can import all your module in the
pythonstartup.py
2.0.267 Install Node error, brew install node --without -npm
- Error to install node on MacOS, Remove
--without -npm
Fixed
rm -rf /usr/local/lib/node_modules brew uninstall node brew install node --without-npm I got following error: any suggestions? Error: invalid option: --without-npm macOS hight Sierra 10.13.4
2.0.268 Emacs Elisp: autocompelte completing-read
(completing-read "test: " '("a" "b" "c"))
(let ((completions '(("foobar1" "~/foobar1/") ("barfoo" "/usr/barfoo/") ("foobaz" "/hello/")))) (cadr (assoc (completing-read "Complete a foo: " completions) completions)))
2.0.269 OpenGL Haskell: Fixed GLFW, GLFW-b and bindings-GLFW issues in OpenGL in Haskell
- Haskell binding GLFW is old GLFW API (2.7.9)
- Haskell binding GLFW-b is new GLFW APL (3.0)
- Some functions are removed from the GLFW-b
- If GLFW-b and GLFW are in different versions it will causes error.
- GLFW-b and bindings-GLFW error
- Fixed GLFW-b and bindings-GLFW error
- Stack packages List
- Working OpenGL GFLW Exmaple
- See cabal and stack.yaml files
2.0.270 What I have done so far.
- Fixed OpenGL, GLFW and bindings-GLFW, GLFW-b problem in Haskell
- Read doc about *Projective Geometry", Yep, the best note from U of T
2.0.271 Binary Search Duplicate element in an array
2.0.272 Download MacVim and install it, does not work so far, can not build..
2.0.273 Fixed very stupid bug in haskellwebapp2 because Javascript ondblclick does not work suddenly
- Because I changed the mouse double click speed in *System Preferences' on MacOS.
- Use Chrome to debug HTML and Javascript to figure out the issue.
- Edit the Html and Reload your HTML code.
- Chrome to set break point in Javascript code.
2.0.274 The best explanation for Projective Geometry
2.0.275 Fixed error on groupBy method in Java library Aron.java
- Not sure why when I messed up the groupBy method in Aron.java
- Just fixed it.
2.0.276 Rename a domain name.26-05-2020
2.0.277 New code to find the maximum element from a sorted rotated array
2.0.278 Run ghci like command line in Shell
- Here is My SO Question: ghci shell command
2.0.279 CMake is hard, why it so complicated to write a build script
- People say CMake is easy because everything is function.
- Why CMake try to reinvent the new language to write a CMake file?
2.0.280 Git add submodule and delete submodule
- It seems to be cool to use git submodule, but it is almost impossible to delete a submodule without a page of commands.
2.0.281 Load script in Julia julia
# julia console >include("first.jl")
2.0.282 Run Julia and Jupter notebook
Run julia
julia
in command line and run following injulia
promptusing IJulia jupyterlab()
2.0.283 Julia: Pkg is not found, You need to use using Pkg
first
using Pkg Pkg.add("Primes")
2.0.284 PDF keyword search tool rga
- install
brew install rga
-
cd $www/pdf rga vector
2.0.285 Write Latex on MacOS
- What is
tex
andTeX Live 2012
andTeX Live 2020
- What I have
TeX Live 2012
on my Macmini which is pretty old Mac. Run following command.
- What I have
tex
- I just found out My MacOS is too old which is
10.12.6
, MacTex 2020 needs10.13
- some packages are missing
- What is the problem?
If you use different packages on your Latex file, then you will need to install those packages on your system.
It is pretty painful for MacOS, and there are no unversal package installation tool on MacOS.(I don't know what tool to install \( \LateX \) packages
I read many post online and they recommand to install MacTex 2020
. Well, just do what other user suggests you to do if you don't know what you are doing.
- You can download packages from ctan. Some files are called
*.dtx
and you can runtex pagecolor.dtx
to install it.
2.0.286 haskllwebapp2 project: move Javascript and CSS file to js and css folder
- It seems to me it works so far.
- When copy the binary file to
$ff/mybin
, need to copy the symbolic link as an actual file instead
- When copy the binary file to
- I use rsync to copy
2.0.287 Home Brew Install gsed or gnu-sed, not sure there is any different between them
brew install gnu-sed
2.0.288 Why ssh is stupid? What is known_hosts
and what is authorized_keys
- I try to figure out how to use public key to authenticate to my Ubuntu host.
Well, I was missing to add the public key to
authorized_keys
file. - Why you need to add the public key to the file?
2.0.289 Move haskellwebapp2 image
to bitbucket/image
, nothing is impressive.
2.0.290 Try to use HaskeLine package to do some console input line stuff. 15-06-2020
- Well, it seems to me
Haskeline
use Monad Transform which I have no idea how it works. - There is type called
InputT
orInputT IO (Maybe String)
I have no idea what it that.- Maybe it is good idea to learn Moand Transform right now.
2.0.291 Egison and pattern match.
- Egion is written in Haskell but you can not use inside your Haskell code directly
egison-haskell can be used inside your Haskell code using Haskell template
- Example
- Interesting Example
- in GHCi need to do the following
:m +Control.Egison :set -XQuasiQuotes :set -XGADTs matchAll [1,2,3] (List Integer) [[mc| $x : $xs -> (x, xs)|]] -- [(1,[2,3])]
2.0.292 Serialize Binary Tree and Preorder traveral and parse prefix expression
I just realize there is connection between Serialize Binary Tree and prefix expression
(* (+ a b) (+ x y)) ;; * + a b + x y ;;
- buildTree in Java code
/** (* (+ [a] [b] ) (+ [x] [y] ) ) */ List<String> ls = new ArrayList<>(); Node buildTree(Iterator<String> ite){ Node node = null; if(ite.hasNext()){ String s = ite.next(); if (isOpe(s)){ node = new Node(ite.next()); Node left = buildTree(ite); Node right = buildTree(ite); node.left = left; node.right = right; }else{ node = new Node(s); } } return node; }
2.0.293 There is no color in org-mode and I just realize I need a package called *Hmltize"
- M-x list-package and click install, done!
2.0.294 Haskell: understand newtype State s a = State{runState::s -> (a, s)}
- Record State has one field which is runState, its type is a function
It is confusing and hard to understand.
newtype State s a = State{runState::s -> (a, s)} runState :: State s a -> s -> (a, s)
newtype only allow ONE type parameter and ONE field
newtype State s a = State{runState::s -> (a, s)} -- | m | a ↑ -- --- one field -- m::* -> *
Compare to Identity Monad
newtype Identity a = Identity{runIdentity :: a} -- runIdentity is like a getter in OOP language -- e.g. let myid = Identity{runIdentity = 3} :i myid myid::(Num a) => Identity a
- Find out the difference between data and newtype, and see whether they convert to each other in compiling time.
- runState is Function type in Haskell
- There is a few things that need to be clarified here.
- Understand Record in Haskell because Record in haskell is very confusing.
- You can NOT use the same name in your record if there is other record contains the name
R1 and R2 both have the same name
data R1 = R1{name::String, age::Integer} data R2 = R2{name::String, addr::String}
Record is just function in Haskell.
data MyRecord = MyRecord{name::String, age::Integer} -- Haskell generate two functions -- getter in Java name::MyRecord -> String age ::MyRecord -> Integer let record = MyRecord{name = "uvw", age = 20} name record -- => "uvw" age record -- => 20
If Record has one field, then there is shortcut to create a record
data MyRec = MyRec {name::String} pp $ name $ MyRec $ "value" -- value
Similarily, State has only one field, runState, whose value is a function
newtype State s a = State{runState :: s -> (a, s)} let f = runState $ State $ \s -> (1, s) pp $ f "Justin Bieber" -- (1, "Justin Bieber")
- Understand Monad slightly.
- First, What is Monoid ?
- Monoid is abstract algebra structure, a triple \((M, \otimes, e)\) which satisfies following axioms:
- If \( a, b \in M \) then \(a \otimes b \in M\) (Binary Operation)
- If \( a \in M \) then \( \exists e \in M \) such that \( e \otimes a = a \otimes e = a\) (left and right identity)
- If \( a, b, c \in M \) then \( a \otimes b \otimes c = a \otimes (b \otimes c) \) (Associative)
- If \( a, b \in M \) then \(a \otimes b \in M\) (Binary Operation)
- Monoid is abstract algebra structure, a triple \((M, \otimes, e)\) which satisfies following axioms:
- What is Monad ?
- Good Monad Post
Monad is a Monoid.
- \(M\) contains all the functors
- Identity is η : I ⊗ T → T and T ⊗ I → T
- Binary Operation is μ : T ⊗ T → T
- Satisfy following monad laws
- T ⊗ T ⊗ T = T ⊗ (T ⊗ T) Associative
- law2
Monad is a Monoid if the element is endofunctor and the operation is Functor composition
join $ Just (Just 2)
2.0.295 Nano parser: Here is the full code for nano parser from Stephen Diehl
2.0.296 Check MacOS Idle time, this will tell you how long it's been since you the mouse or a keystroke was pressed.
/usr/sbin/ioreg -c IOHIDSystem | grep HIDIdleTime
- OS shell script
- Perl script to check idle time on MacOS Perl script
Wrote a Haskell code to check MacOS Idle time with following bash command checkIdleTimer
ioreg -c IOHIDSystem | grep HIDIdleTime # shell script to run p=$(checkIdleTimer); while [[ "$p" -le 5 ]]; do echo "$p"; p=$(checkIdleTimer); sleep 1; done
2.0.297 What is Identity functor in Haskell, Here is the discussion in SO
2.0.298 Use Emacs elisp as script language in command line
#!/usr/local/Cellar/emacs-plus/26.3/bin/emacs --script (message "The current directory is %s" default-directory) # emacs --script myelisp.el
2.0.299 Delete maximum or minimum node in a Binary Search Tree is non trivia task.
- You can not delete the root if there is only one node in the Binary Search Tree in java because you can modify a object reference. It can be done in C++ because argument can be passed by reference.
- First, find the minimum or maximum value reference from a Binary Search Tree is easy task.
Second, delete the reference node from the Binary Search Tree.
- If we know which node will be deleted then we need to find the node in the BST
- Once we find the node, we are ready to d]elete it. There are a few cases that need to be consided.
- First, easy case: if the node have no left and right branch then we just delete it
- But we need to have a parent to the current node so that we can delete the current node.
- Second, if the node has one branch such as right or left branch.
- if the node has right branch only
- we find the min value of the right branch and swap it with the node that we want to delete.
- recurve to the right branch and the deleted node is the min value node.
- if the node has left branch only
- we find the max value of the left branch and swap it with the node that we want to delete
- recurve to the left branch and the deleted node is the max value node
- if the node has right branch only
2.0.300 Python Hell, pip3, pip3.7 and pip3.8 \(\Rightarrow\) python, python3.7 python3.8
A few days ago, There is error when I run my Python script
$b/montor.py
The script is actually very useful and it monitors whether a file is modified or not. Suddenly, thenumpy, matplotlab
are both not working, I have no idea why. Today, I just found out there arepip3.7
andpip3.8
on my/usr/local/bin
and I try to installnumpy and matplotlab
withpip
andpip3
,pip3
is not found.. then I triedpip3.7
, there is error. And I trypip3.8
, it works.. So I have no idea when and who change frompip3
topip3.7
andpip3.8
in my system.pip3.8 install numpy pip3.8 install matplotlab
2.0.301 Java Optional, isPresent, get
- Create
Optional
Object withInteger
3
Optional<Integer> opt = Optional.of(3);
- Check whether
Optional
contain any value
Optional<Integer> opt = Optional.of(3); if(opt.isPresent()){ pp(opt.get()); }
- Optional in lambda
Optional<Integer> opt = Optional.of(3); opt.isPresent(value -> {System.out.println(value)});
2.0.302 Jacobian Matrix, What is Jacobian Matrix? When to use Jacobian Matrix? What is the simplest form of Jacobian Matrix
- What is Jacobian Matrix?
- What is the geometric interpretation of Jacobian Matrix?
- Add more here
2.0.303 Found a bug there has been in the code for many years. isBST
- Check whether a Binary Tree is Binary Search Tree
- The code uses recursion. Here is the wrong code
Node isBST(Node root, Node prev){ if( root != null){ if(!isBST(root.left, prev)) return false; if(prev != null && prev.data >= root.data) return false; prev = root; if(!isBST(root.right, root)) return false; } return true; }
- Arguments can not been passed by reference in Java like C++ with
&ref
- Fixed version
isBST
. Use array of node instead of just node.
- Fixed version
Node isBST(Node root, Node[] arr){ if( root != null){ if(!isBST(root.left, arr)) return false; if(arr[0] != null && arr[0].data >= root.data) return false; arr[0] = root; if(!isBST(root.right, arr)) return false; } return true; }
2.0.304 Why it is so hard to figure What is JAVAHOME in your MacOS (21-07-2020)
- How to find JAVAHOME?
- Check java or javac, it is a symbolic link most likely.
- JAVAHOME means it contains
bin/java
bin/javac
etc.
- Try to install Groovy and realize Groovy can not find JAVAHOME because I have different versions of JDK and I have no idea which one that I use it currently.
Normally I do not like to set JAVAHOME because it is not very reliable. It will break your java and javac after new JDK is installed.
- Checking
javac
and it showsjavac
is symbolic link to following dir.
/usr/bin/javac -> /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/javac
- Goto following dir
/Library/Java/JavaVirtualMachines/jdk-14.0.1.jdk/Contents/Commands
- There is command called
java_home
and you need to run the command to show where is JAVAHOME
/Library/Java/JavaVirtualMachines/jdk-14.0.1.jdk/Contents/Commands/java_home # following is JAVA_HOME /Library/Java/JavaVirtualMachines/jdk-14.0.1.jdk/Contents/Home
- Checking
2.0.305 Groovy connect to mysql(22-07-2020)
- Groovy Version: 3.0.4 JVM: 14.0.1 Vendor: Oracle Corporation OS: Mac OS X
- Groovy Mysql Connect Example
Groovy Connect string to mysql
import groovy.sql.Sql import java.sql.* import java.io.File import com.mysql.jdbc.* def url = 'jdbc:mysql://localhost:3306/testdb?autoReconnect=true&useSSL=false' def user = 'user1' def password = 'password' // def driver = 'org.hsqldb.jdbcDriver' def driver = 'com.mysql.jdbc.Driver' def sql = Sql.newInstance(url, user, password, driver) sql.execute('DROP TABLE mytable2 IF EXISTS mytable2')
2.0.306 Groovy can be Java script language, why it is not very popular?
- Groovy Mysql Connect
Groovy connect to Mysql
- MacOS login to mysql server
- login → mysql -u user1 -p
- database → testdb
- user → user1
- passwd → password
mysql -u user1 -p # passwd: password # database -> testdb
Groovy is dynamic and strong type programming language?
def str = "abc"
Call Java static method, no more semicolon
import static classfile.Aron.*; def str = "abc" var ls = list(1, 2)
Groovy use Java class in Groovy code.
class MyClass{ public MyClass(){} } MyClass c = new MyClass()
2.0.307 Groovy: compile groovy file on MacOS
How to compile groovy file, use shell script
$b/script/groovy_compile.sh
$b/script/groovy_compile.sh
2.0.308 Groovy: Json, read Json, parse Json
- Create Json Parse Json
-
import groovy.json.JsonOutput def data = [ name : "Justin Bieber", year : 2020, timestamp : "2020-03-01T00:00:00", array : [ "Justin Trudeau", "Cheetah", "Injective", "Subjective"], pi : 3.1415 ] def json_str = JsonOutput.toJson(date) println(json_str) def file = new File('/tmp/f.x') file.write(json_str)
2.0.309 Design Groovy script to add file paths to database table.
Input File
- file contains all the paths
# file.txt /usr /etc
- Text File Generator
- Generate one txt file for each path
- Read a given directory and iterate all files to a list
- Write the list to a text file.
- Text File Collector
- Iterate a directory and collect all the txt file and return a list of string
Mysql Database
- Create table to store file paths
# database: testdb # table: testtable1 CREATE TABLE testtable1( id INTEGER NOT NULL AUTO_INCREMENT, path TEXT NOT NULL, PRIMARY KEY(id))
- Text File To Database Table
- Read each txt file and use LOAD DATA INFILE to load txt file to one table
- Merge Mysql Tables at once.
- Use Mysql merge command to merge all tables
2.0.310 Org mode file to Html without any color
- If you run
emacs --deamon
to compile orgmode to Html, then there is no color in the code block. Not sure why
2.0.311 Install OpenCV on my old MacMini
brew install opencv
2.0.312 OpenCV Error, Friday, 06 September 2024 16:41 PDT
dyld[32871]: Library not loaded: /usr/local/opt/opencv/lib/libopencv_stitching.3.4.dylib Reason: tried: '/usr/local/lib/libopencv_stitching.3.4.dylib' (no such file), '/usr/local/opt/opencv/lib/libopencv_stitching.3.4.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/usr/local/opt/
- Fixed it uninstall opencv
- 'pkg-config' helps to fix the issue
- $(pkg-config –cflags –libs opencv4)
// SEE: $src/runopencv.sh g++ -std=c++14 -I$HOME/myfile/bitbucket/cpplib -I $boostInclude $(pkg-config --cflags --libs opencv4) -lboost_filesystem -lboost_system $1 -o $(basename $1) brew uninstall opencv brew install opencv
2.0.313 Fixed stupid mistake and I have no idea why $b/javalib/jar/AronLib.jar
is deleted and Groovy suddenly DOES NOT work any more today.
- I tried to install
opencv
withbrew install opencv
on my MacOS and it took more than five hours to build and it failed at the end because there is issue withicu4c
Unicode library on my MacOS. I have no clue why. - After I check my jar path
$b/javalib/jar
and jar fileAronLib.jar
is deleted… Why… I never delete it.. - Rebuild
Aron.java
and it works again for all Groovy script.
2.0.314 Install exa
replacement for ls
which is written Rust
, which is C++ killer, (KEY: ls command, ls replacement)(30-07-2020)
Install
exa
- Github URL exa
- Install under
$HOME/.cargo/bin/exa
dir
cargo install exa
- exa command example
exa -l
2.0.315 Install procs
rust command line tool, it took forever to install it, what the hell?
- Better color?
proce # ps aux
2.0.316 Haskell ghci load module are confusing, load module problem
- If you load your module in
./ghc/ghci.conf
and runstack ghci
in a stack project then you might not see all your modules are loaded fromghci.conf
file why? because ghci only load module are in yoursrc/Main.hs
. I just realize that and I don't understand why my modules are inghci.conf
are not loaded. - Add moudle to
src/Main.hs
if you want to load them.
2.0.317 Microsoft Interview in Auguest 8, 2020
- There are three questions on the coding interview in online coding site: Codility
- First Question
- Given an Integer \(n > 0, n \in \mathbb{N}\) print out all the lines according to following rules
- If \(2\) is the divisor of \(\mathbb{N}\) then print out a line "Codility"
- If \(3\) is the divisor of \(\mathbb{N}\) then print out a line "Test"
- If \(5\) is the divisor os \(\mathbb{N}\) then print out a line "Coders"
- Otherwise, print out a number \(\mathbb{N}\) in one line
n = 1 1 n = 2 1 Codility n = 3 1 Codility Test
void printLines(int n){ if(n % 2 == 0 && n % 3 == 0 && n % 5 == 0){ System.out.println("CodilityTestCoders"); }else if(n % 2 == 0 && n % 3 == 0){ System.out.println("CodilityTest"); }else if(n % 2 == 0 && n % 5 == 0){ System.out.println("CodilityCoders"); }else if(n % 3 == 0 && n % 5 == 0){ System.out.println("TestCoders"); }else if(n % 2){ System.out.println("Codility"); }else if(n % 3){ System.out.println("Test"); }else if(n % 5){ System.out.println("Coders"); }else{ System.out.println(n); } }
- Second Question
- Given a string contains only \(\textit{upper}\) and \(\textit{lower}\) case alphabets \(\{ a b E b C e c \}\).
- Find the same maximum of \(\textit{upper}\) and \(\textit{lower}\) case \(\textit{alphabet}\) from the string.
The maximum of \(\textit{upper}\) and \(\textit{lower}\) is defined as following
- \(\{ a < b < \dots < z \}\) and \(\{ A < B < \dots < Z \}\)
The maximum of \(\{ b a c \}\) is \(\{ c \}\)
- The maximum of \(\{ E A C \}\) is \(\{ E \}\)
For a given string
"aBecb"
- \(\{a b c e \}\) and \(\{ B \}\) only have one common alphabet \(\{ B \}\) \(\Rightarrow\) \(\{ B \}\) is the maximum.
For a given string
"aEbeck"
\(\{a b c e k \}\) and \(\{ E \}\) do not have common alphabet. \(\Rightarrow\) is empty string
- Solution:
- Process a given string to two strings such as \(s_1. s_2\), \(s_1\) contains only \(\textit{upper}\) cases alphabet and \(s_2\) contains only \(\textit{lower}\) cases alphabet.
- Sort \(s_1, s_2\) in increasing order.
- Take one alphabet from each string \(c_1 \in s_1\) and \(c_2 \in s_2\) from maximum ends.
- Compare them, \(c_1 = c_2\), if both are the same alphabet in \(\textit{upper}\) and \(\textit{lower}\), then return the alphabet. Done.
Otherwise, remove the maximum alphabet \(\max{c_1, c_2}\).
- Goto step 3
"aEbeck"
- Solution
- Generate two strings from a given string
- Sorted the two strings
- Compare the two strings
String maximumStr(String s){ String ret = ""; List<Character> su = list(); List<Character> sl = list(); for(int i = 0; i < len(s); i++){ if(Character.isUpper(s.charAt(i))) su.add(s.charAt(i)); else sl.add(s.charAt(i)); } PriorityQueue qu = new PriorityQueue<>((x, y) -> y.compareTo(x)); PriorityQueue ql = new PriorityQueue<>((x, y) -> y.compareTo(x)); while(!qu.isEmpty() && !ql.isEmpty()){ Character up = qu.peek(); Character lo = ql.peek(); Character ulo = Character.toUpperCase(lo); if(up == ulo){ ret = up; break; }else{ if(up < ulo) ql.remove(); else up.remove(); } } return ret; }
- Third Question:
- Given an Integer(positive or negate or zero) \(n \in \mathbb{N}\), insert an Integer \(5\) to any postion.
- Find the maximum of all the possible integers
- Given an Integer(positive or negate or zero) \(n \in \mathbb{N}\), insert an Integer \(5\) to any postion.
- Example:
- Given integer \(123\), the maximum of all possible integers is \(5123\)
Given integer \(0\), the maximum of all possible integers is \(50\)
Integers maxValue(Integers n){ Integer mValue = 0; if(n > 0) Integers mValue = Integer.MIN_VALUE; else if(n < 0) Integers mValue = Integer.MAX_VALUE; else mValue = 50; if(n < 0){ Integer m = -n; String nstr = m.toString(); }else{ String nstr = n.toString(); } for(int i = 0; i <= len(nstr); i++){ // "ab" => "" "ab", "a" "b", "ab" "" // i=0 i=1 i=2 String left = nstr.substring(0, i); String right = nstr.substring(i, len(nstr)); Integers num = Integer.parseInt(left + "5" + right); if(n > 0){ if(num > mValue) mValue = num; }else if(n < 0){ if(num < mValue) mValue = num; } } return n >= 0 ? mValue : -mValue; }
2.0.318 OpenGL Haskell GLFW
- Try to figure how to render some text using Haskell OpenGL GLFW, but GLFW-b does not have drawing at all.
- GLFW which provides a simple API for Creating Window and Contexts and Surfaces, receiving input and events.
- GLUT \(\Rightarrow\) OpenGL Utility ToolKit can draw sphere:)
- I still have no idea how to render text inside Haskell OpenGL.
2.0.319 OpenGL GLFW-b glfwWindowHint does not work in Haskell GLFW bindings-GLFW 3.2.1.1 (16-08-2020)
- glfwWindowHint
- You Should Remove glfwWindowHint from your Haskell OpenGL GLFW code. I have no idea why
- Update 17-08-2020
- Apparently macOS users need to use different Enum in glfwWindowHint
See Cpp Code Example it works in macOS
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
- Code to check macOS OpenGL version and Video card Check OpenGL CPP macOS
Haskell GLFW See Following Window Hint data constructors
WindowHint'OpenGLForwardCompat !Bool WindowHint'OpenGLDebugContext !Bool WindowHint'OpenGLProfile !OpenGLProfile
-
macOS: The OS only supports forward-compatible core profile contexts for OpenGL versions 3.2 and later. Before creating an OpenGL context of version 3.2 or later you must set the GLFW_OPENGL_FORWARD_COMPAT and GLFW_OPENGL_PROFILE hints accordingly. OpenGL 3.0 and 3.1 contexts are not supported at all on macOS.
- Haskell OpenGL GLFW Example
# stack ls dependencies bindings-GLFW 3.2.1.1 GLFW-b 3.2.1.0
2.0.320 OpenGL Shader Tutorial 1
- Cpp Source Code
First Vertex/Fragment shader
2.0.321 OpenGL Use Fragment Shader to draw simple curve
Vertex and Fragment shader code are in inside C++ code.
- Vertex shader code.
#version 330 core layout (location = 0) in vec3 aPos; void main() { gl_Position = vec4(aPos, 1.0); }
- The fragment shader code just set the color of the curve.
#version 330 core out vec4 FragColor; uniform vec4 ourColor; void main(){ FragColor = ourColor; }
- Set the color of pixel through fragment shader
outColor
in OpenGL code.
glUseProgram(shaderProgram); // update shader uniform float greenValue = 0.3f; int vertexColorLocation = glGetUniformLocation(shaderProgram, "ourColor"); glUniform4f(vertexColorLocation, 0.0f, greenValue, 0.0f, 1.0f);
The relation between Fragment shader code and OpenGL code
- is outColor" a *uniform variable?
- Use uniform variables to pass value from OpenGL app to shader.
Draw Simple Curve with Fragment Shader
2.0.322 OpenGL built-in function to draw Bezier Curve and Surface, I never know that.:)
The function need a list of control points
GLfloat ctrlpoints[4][3] = { { -4.0, -4.0, 0.0}, { -2.0, 4.0, 0.0}, {2.0, -4.0, 0.0}, {4.0, 4.0, 0.0}}; GLfloat lo = 0.0; GLfloat hi = 1.0; const int numNext = 3; const int nOrder = 4; // order of spline = degree + 1 // GL_MAP1_VERTEX_3 => Three-dimensional control points glMap1f(GL_MAP1_VERTEX_3, lo, hi, numNext, nOrder, &ctrlpoints[0][0]);
- Build in OpenGL function to draw Bezier Curve and Surface
2.0.323 OpenGL Model Space, World Space and View Space
Model space or Object space is the space or coordinate system for each individual object
World space (coordinates system) is for a group of objects, all objects are relative to the coordinate system
View Space or Camera space is the coordinate system relative to the camera.
2.0.324 Install nodejs in MacOS
brew install node
2.0.325 Try to Use Python post request to insert code block into Haskellwebapp2, but it does not work so far.
import sys sys.path.insert(0,'/Users/cat/myfile/bitbucket/python') import requests # Python 3+ from pathlib import Path url = 'http://localhost:8080/insertcode' myobj = {'pid' : '3000', 'newcode': 'my test code'} x = requests.post(url, data = myobj) print(x.text)
2.0.326 Wrote a shell script to generate hightlight code using pygmentize
Shell script file is in
$scr/python_color_code.sh
pygmentize -l cpp -f html -O style=monokai -O noclasses=True -o "/tmp/x.cpp" file.cpp python_color_code.sh
2.0.327 Topology \(\mathbb{R}\mathbb{P}^2\) is homeomorphic to a unit square with following equivalent relation.
2.0.328 Emacs How to change default tags file name
- M-x visit-tags-table
Use different tags file name. The default name is TAGS in Emacs
# Do not need full path (setq tags-file-name "emacs_tags")
2.0.329 Haskell: I just learn that there is typeclass called Floating
in Haskell
typeclass
Floating
is like a interface for all the trigonometric functionclass (Fractional a) => Floating a where pi = a sin a -> a cos a -> a ...
2.0.330 Java extends keyword, subtype, extend multiple bounds such as class and interface
2.0.331 Install Git 2.28.0 using brew install git
under /usr/local/Cellar/git/2.28.0/bin
2.0.332 Install Magit in Emacs. It does need new git version which is like git 2.28
. It seems to me it is fantastic package for Emacs.
- Add more comments here.
2.0.333 Add code to OpenGLKeyboard to draw histogram from file as input
2.0.334 Fixed Alignment issue in Java code Alignment.java
- Forgot to trim a string
2.0.335 Fix icu4c for old macOS, icu4c causes lots of problem
git clone https://github.com/Homebrew/homebrew-core cd homebrew-core brew install hub hub pr checkout 59540 # if you own password to login to github brew reinstall --build-from-source ./Formula/icu4c.rb
2.0.336 Did an interview with Godaddy
- First, I talked to a non technical guy called Chris Puro. After the chatting, he gave me the next interview with a manager called David Kellogg.
- Second day, A HR called Nyssa Kerawala sent me info about a interview with a manager David Kellogg with some Zoom but there is no meeting ID on the email. When I try to connect to Zoom during the interview, it asks for the meeting ID. I have to email Nyssa to ask for the meeting ID and I was late for 15 minutes for the interview.
- Third, it seems to me the manager is nice guy and he even mentioned he will give me the code interview but I rejected after the interview.
- It seems to me The HR woman Nyssa does not know whether I need a meeting ID to connect to Zoom chat.
2.0.337 There is new Array language like APL or J is called BQN
- BQN looks interesting to me but I have no idea what is different between APL and BQN
2.0.338 CPP Boost can be built in my Mini MacOS, 26-09-2020
- Just download the source code the following the instructions
-
boost_1_74_0.tar.bz2 # help ./booststrap.sh --help # with ICU regex ./booststrap.sh --with-icu=DIR --prefix=MYDIR ./booststrap.sh --with-icu=/Users/cat/myfile/myinstall/boost/icu --prefix=/Users/cat/myfile/myinstall/boost
sudo apt install apache2
2.0.339 Ubuntu: Install collections, ubuntu install
apt-get install redis apt-get install sqlite3 apt-get install vim sudo apt install default-jre sudo apt install apache2 curl -sSL https://get.haskellstack.org/ | sh sudo apt-get install haskell-platform sudo apt-get texlive # install Latex Tex Live
2.0.340 Get back the Car Insurance today, and paid the stupid ticket for $276, what the fucking ticket scams?
- Paid $132 + $276 = $408 today.
- Pay $132 something for each month in one year contract.
2.0.341 Haskell LSP Setup: Install Haskell language server on MacOS today (08-11-2020)
- Haskell Language Server
- The minimum GHC is GHC 8.6.4, check \(\Rightarrow\) stack.yaml in your Stack project.
How to install HLS it on MacOS
- Download the source code.
git clone https://github.com/haskell/haskell-language-server --recurse-submodules cd haskell-language-server
- Building help
stack ./install.hs help
- Building Haskell Language Server supports many different version of GHC
- If you use GHC 8.6.5 in your Stack project, then you need following to build LSP for GHC 8.6.5
stack ./install.hs hls-8.6.5
- Currently I use GHC-8.6.5, make sure your stack.yaml has resolver: lts-13.28
stack ./install.hs help hls-8.10.1 Install haskell-language-server for GHC version 8.10.1 hls-8.10.2 Install haskell-language-server for GHC version 8.10.2 hls-8.6.4 Install haskell-language-server for GHC version 8.6.4 hls-8.6.5 Install haskell-language-server for GHC version 8.6.5 hls-8.8.2 Install haskell-language-server for GHC version 8.8.2 hls-8.8.3 Install haskell-language-server for GHC version 8.8.3 hls-8.8.4 Install haskell-language-server for GHC version 8.8.4 ...
- Install gen-hie to generate hie.yaml
git clone https://github.com/Avi-D-coder/implicit-hie.git cd implicit-hie stack build
- You need to goto your root folder of Stack project and run
gen-hie > hie.yaml
- Next, start your Emacs in the roof folder of Stack project and open your Main.hs
- Next, start LSP from Emacs
M-x lsp
- Then you should see connection message which tries to connect to LSP
- Today, I still have issue to install Haskell-Language-Server (10-11-2020)
- After a haskell file is loaded, haskell-language-server is starting and there is no error.
But I can not see any typecheck or definition or autocomplete. I still have no clue what went wrong. I restart Emacs a few time and realize there are error messages "LSP: NO [cradle] …"
2.0.342 Haskell LSP Setup: Try to install lsp-haskell but it failed so far.
- It took more than an hour to install lsp-haskell
- Here is lsp-haskell
- From github, I did not see any tutorial to tell you run 'M-x lsp' on your Emacs.
I tried run 'M-x lsp-mode' a few times.. and finally someone told me in Gitter I should run
M-x lsp
and finally I see messageLSP initialize successfully
on my Emacs.. and I cangrep
hie
andhie-wrapper
from comand line. - So far so good, but I try to completion
C-M-i
, it does not work. And I try jump to defintionM-.
, it does not work.
- It seems to me the better option development are
ghcid
andhastags --etags .
- It is easy to install and work.
2.0.343 Haskell LSP Setup: It seems to me no one can answer my Reddit question how to setup LSP mode in Emacs yet.
- Reddit Question on How to install LSP mode or Haskell Language Server on Emacs.
- Try to understand some defintion of what is lsp, lsp-mode, lsp-haskell, company-mode, etc. there are million more defintions
- lsp \(\Rightarrow\) Language-server-protocol from Microsoft
- lsp-mode is Language Server Protocol for Emacs
- lsp-mode is a client to provide to popular package such as company, flycheck and projectile.
- So lsp-mode is just a mode.
2.0.344 Git: git init from a non empty folder
git init
git add .
git commit -m "initial commit"
git remote add origin https://github.com/...
git pull origin master --allow-unrelated-histories
git push --force-with-lease
2.0.345 Firefox Error: Cross-Origin Remote Blocked
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///Users/cat/myfile/bitbucket/html/snippet2.pdf. (Reason: CORS request not http)
- How to fix it on Firefox
- Goto URL bar and type
about:config
- Search security.fileuri.strictoriginpolicy and Set it to false
security.fileuri.strict_origin_policy
2.0.346 Install old version TeX Live Utility (2017) on MacOS 10.12.6
- If you head to TeX Live Utility Website, you got Tex Live Utility 2020 and it needs MacOS 10.13 minimum
- Well, the next logical step is to update my MacOS 10.12.6 to 10.13. But I google around and can not find 10.13 installer
- I did try to download some 10.13.4 update or combo something from Apple website and update it, but all the update or combo things need 10.13 or higher.
- It seems to me Apple try to prevent you to update from MacOS 10.12.6 to 10.13 or there is some technical issues that Apple can not solve so there is no way from 10.12.6 to 10.13
- I did not know there is TeX Live Utility 2017 until today and I download it and install it. It seems to me it works so far and I can update my Latex packages. Here is the URL, download it and install it. mactex-20170524.pkg
- Here is screenshot
2.0.347 Haskell Error, Ambiguous module name 'Data.HashSet'
/Users/cat/myfile/bitbucket/try/src/AronModule.hs:74:1: error:
Ambiguous module name ‘Data.HashSet’:
it was found in multiple packages:
hashmap-1.3.3 unordered-containers-0.2.10.0
- What is the hell is going here? If you use hashmap inside your Cabal file then you will get above error Both package hashmap and unordered-containers use Data.HashSet inside their packages
- Solution Change hashmap to unordered-containers inside your Cabal file in Stack
2.0.348 HTTP Header no cache, reload file
How to force the browser to delete cache?
- In Http Header, you can add the following
/ Cache-Control: no-cache
2.0.349 haskellwebapp2 Project 13-12-2020
- README
- Before installation
Edit *config.txt" file
- Change host name and port number
- Change rootdir to new directory
$HOME/myfile/mybin/haskellwebapp2Bin
Edit $jslib/aronlib.js
// $hw test project const HOST = { LOCALHOST : 'http://localhost:8081', XFIDO : 'http://xfido.com:8080' } // $HOME/myfile/mybin/haskellwebapp2Bin // Live project const HOST = { LOCALHOST : 'http://localhost:8080', XFIDO : 'http://xfido.com:8080' }
Modify name from haskellwebapp2test to haskellwebapp2 in haskellwebapp2.cabal
executable haskellwebapp2_test
- Install
$hw/haskellwebapp2/install.sh in
Update text color and background-color
- Select color from Javascript code
// aronlib.js function submitUpdateBackground(cvalue) { }
- WaiLib.hs call submitUpdateBackground(…)
// WaiLib.hs <input id='bgidcolor' type="color" onchange="submitUpdateBackground('background-color:' + this.value)" name="colorname"> submitUpdateBackground('color:' + this.value); submitUpdateBackground('background-color:' + this.value);
- End Point '/updatebackground'
function submitUpdateBackground(cvalue) { let url = getHostNameJS() + '/updatebackground' }
- WaiLib.hs call
("updatebackground":_) -> updateBackground request respond -- change background color
- NOTE: searchForm.html use submitUpdateBackground TOO
- BUG:
- Try to fix followilling issue:
- When there is Latex compile error, the className of canvas is changed to hide
When there is NO Latex compile error, the className of canvas is changed to show
var canvas = document.getElementById('the-canvas') canvas.style.className = 'hide' // canvas.style.className = 'show'
See following function in aronlib.js
function postRequestJson(pid, url, obj){ }
2.0.350 git checkout directory only
- I just learned that you can checkout the root directory of git repos only with git.
and checkout one file only.
git clone -n https://bitbucket.org/zsurface/haskelllib.git --depth 1 cd haskelllib git checkout HEAD AronModule.hs
2.0.351 haskellwebapp2 Latex editor (05-01-2021)
directory structure
haskellwebapp2/src/datadir/latex/try919591/try919591.pdf haskellwebapp2/src/datadir/latex/try919591/try919591.log
- Default request "xfido.com/aceeditor"
- Generate random name try919591
- Copy indexEditorACE.html to indexEditorACEtry919591.html
- Send indexEditorACEtry919591.html to browser
- NOTE: Currently src/datadir/latex/try919591/try919591.html is NOT generated yet.
- Response to client
Client side:
- After HTML indexEditorACEtry919591.html page is loaded, make a Ajax call in http://localhost/editordata
Send JSON Object EditorCode to Server
data EditorCode = EditorCode{ editorbeg::Integer, editorend::Integer, editorfile::String, editorcmd::String, editorcode::String, editortheme::String, editormode::String } deriving (Generic, Show)
// indexEditorACE.html const myHost = 'http://localhost:8081' let url = myHost + '/' + 'editordata' var obj = new Object() obj.editorbeg = nowInt() obj.editorend = 0 obj.editorfile = latex.value obj.editorcmd = 'compile' obj.editorcode = editor.getValue() obj.editortheme = editor.getOption('theme') obj.editormode = editor.getOption('mode')
- New Latex code
- Server receive "compile", and compile $m/try919591.tex and output dir is src/datadir/latex/try919591
Server reply EditorCodeReply
data EditorCodeReply = EditorCodeReply{ replybeg::Integer, replyend::Integer, ret::String, replydata::String, replyfname::String, replytheme::String, replymode::String } deriving (Generic, Show)
- Create directory under
$hw/src/datadir/latex/try919591
- Compile latex file
$m/try919591.latex
- pdflatex output directory
- After HTML indexEditorACEtry919591.html page is loaded, make a Ajax call in http://localhost/editordata
try919591.pdf in try919591
$hw/src/datadir/latex/try919591
- Use indexEditorACE.html as default HTML file
- New code \( \Rightarrow \) Copy haskellwebapp2/indexEditorACE.html to haskellwebapp2/src/datadir/try919591/try919591.html
- "compile" => default
- Click on "Save"
- Save all pdflatex to a directory
src/datadir/latex/try919591/try919591{.html, .pdf..}
- Create Html File latexHTMLFile
- Request "xfido.com/aceditor?id=try919591"
- If try919591 is found in the HashMap
- Then send indexEditorACEtry919591.html to client side
Client Use XMLHttp to make a ajax call to Server side
- Compile .tex to .pdf file
- If .tex can be compiled, then return JSON (true) back to client side,
- if Get return JSON true, then call loadPDF() to load the new PDF file.
- If .tex can be compiled, then return JSON (true) back to client side,
type PDFMap = M.HashMap String String -- ("try919591" "try919591")
- more
- Compile .tex to .pdf file
Response PDF file path
-- => xfido.com/aceeditor?id=try919591 -- => try919591.html -- DONE: TODO: => try919591.pdf => src/latex/try919591.pdf -- TODO: add following => src/latex/try919591/try919591.pdf -- => datadirlatex </> v </> v ++ ".pdf" datadirlatex = "datadir/latex" v = try919591 v = try919591 responsePDF "datadir/latex/try919591/try919591.pdf" redisValue <- redisGet queryId case redisValue of Just v -> respond $ responsePDF $ datadirlatex </> v </> v ++ ".pdf" _ -> respond responseHelp
2.0.352 Three order traveral, preorder, inorder, postorder
Class Node{ Node left; Node right; Int data; }
preOrder traveral
void preOrder(Node node){ if(node != null){ System.out.print(node.data); preOrder(node.left); preOrder(node.right); } }
inOrder traveral
void postOrder(Node node){ if(node != null){ inOrder(node.left); System.out.print(node.data); inOrder(node.right); } }
postOrder traveral
void postOrder(Node node){ if(node != null){ postOrder(node.left); postOrder(node.right); System.out.print(node.data); } }
2.0.353 Binary Tree insection
Class Node{ Node left; Node right; Int data; } void insert(Node root, Int n){ if(root == null){ root = new Node(n); }else{ if( n < root.data ){ if(root.left == null) root.left = new Node(n); else insert(root.left, n); }else{ if(root.right == null) root.right = new Node(n); else insert(root.right, n); } } }
2.0.354 Binary Search
/** arr = [1], k = 1 => true arr = [1], k = 2 => false arr = [1, 2], k = 1 => true arr = [1, 2], k = 2 => true arr = [1, 2], k = 3 => false */ Boolean binSearch(Int[] arr, Int lo, Int hi, Int k){ if(lo <= hi){ Int m = (lo + hi)/2; if(k < arr[m]){ return binSearch(arr, lo, m-1); }else if(k > arr[m]){ return binSearch(arr, m+1, hi); }else{ return k == arr[m]; } } return false;
2.0.355 Haskell data newtype and type
- data can have zero or more constructor and parametrized types
data MyType a = MyNothing | MyJust a data MyType1 = MyType Inta
2.0.356 Test me
- This is test me