here you goThings I’ve made, read and saved — shared here.

Archive

9,565 entries: 46 from X, 8,923 from Pinboard, saved 1998 to 2026.

Browse by tag, site, author, folder or language

Tags

Sites

Authors

Folders

Languages

36 entriesFolder notes ×2018 ×Clear all

2018

Logic Programming

To Read:

  • Sterling and Shapiro (Sterling and Shapiro 1986) is often recommended as the introductory text to Logic Programming.
  • Nominal Logical Programming (Cheney and Urban 2008) -- is an extension of first-order logic which provides a simple foundation for formalizing and reasoning about abstract syntax modulo consistent renaming of bound names (that is, alpha-equivalence). "powerful tool for informal reasoning about theoretical computer science. For me it made theoretical computer science tangible, and I hope these series of posts can do the same for the reader." -- swannodette
  • miniKanren -- is an embedded Domain Specific Language for logic programming. See also: Will Byrd's Thesis -- Relational Programming in miniKanren: Techniques, applications and implementations (Byrd 2010).
  • For real world applications of logic programming see -- Concepts, Techniques, and Models of Computer Programming by Roy, Haridi and Seif (Van Roy and Haridi 2004).

Software

  • logic-db is a js lib to combine logic programming and database

Misc

References

  • Sterling, Shapiro (1986). The Art of Prolog: Advanced Programming Techniques.
  • Cheney, Urban (2008). Nominal Logic Programming.
  • Byrd (2010). Relational Programming in Minikanren: Techniques, Applications, and Implementations.
  • Van Roy, Haridi (2004). Concepts, Techniques, and Models of Computer Programming.

notes#programming-language

Probabilistic Programming

"What is the TL;DR of Probabilistic programming" (via HN)

Reading List – MIT Probabilistic Computing Project

What is probabilistic programming? - O'Reilly Media. So It Begins: Darpa Sets Out to Make Computers That Can Teach Themselves | WIRED

Probabilistic programming language - Wikipedia

Practical Probabilistic Programming by Avi Pfeffer who also created the Figaro language [PDF].

Probabilistic Programming Wiki

[1809.10756] An Introduction to Probabilistic Programming by Jan-Willem van de Meent, Brooks Paige, Hongseok Yang, Frank Wood; a 200+ page tutorial.

Online / programming env

Courses

notes#probability#programming

Literate Programming

Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to humans what we want the computer to do. -- Donald E. Knuth, Literate Programming, 1984

Examples of literate programming

  • ulix a literate, teaching operating system.
  • knitr Elegant, flexible and fast dynamic report generation with R
  • stich -- is a small python library for writing reproducible reports in markdown. It's heavily inspired by (read: a python clone of) knitr and RMarkdown.
  • ferret.org the entire source of Ferret programming language as an emacs org file.

Tools

Literate -- A modern literate programming system written in D

brew tap zyedidia/literate
brew install --HEAD zyedidia/literate/literate

In addition to those of CWEB:

  • Markdown based -- very easy to read and write Literate source.
  • Generates readable and commented code in the target language (the generated code is usable by others)
  • Reports syntax errors back from the compiler to the right line in the literate source
  • Supports any language including syntax highlighting and pretty printing in HTML
  • Compatible with Vim (literate.vim)
  • Highly customizable (you can add your own HTML or CSS)
  • Runs fast -- wc.lit compiled for me in 7ms for both code and HTML output
  • Supports TeX equations with $ notation.

Inspired from CWEB:

  • Automatically generates hyperlinks between code sections
  • Formatted output similar to CWEB

I wrote lua4py page using Literate.


See also the Nimib project by Nim programmers.

notes#literate-programming

Build Systems

Writing

Build systems

Cloud

Earthly - Make Builds Super Simple; HN; See example use - Improving Testing & Continuous Integration in Phoenix - Phoenix Blog - Jan 2021.

notes

Sqlite

I wrote an article about SQLite for DeveloperIQ magazine published in Jan 2005 -- Move Over MySQL, SQLite is here!!


Query Parquet files in SQLite | Colin Dellow

Importing csv into sqlite: see this page for extended usage

sqlite> .import myfile.csv mytable

SQLite as a document database using Generated Columns and The JSON1 Extension

Tutorials

SQLite Date & Time - How To Handle Date and Time in SQLite (The site sqlitetutorial.net seems to have handy reference for common tasks with sqlite.)

SQLite as a Collaborative & Multiplayer Application File Format - YouTube

Optimizing SQLite for servers

60K RPS out of sqlite on a $5 VPS

Django

Tools around SQLite

sqlpkg

The list of packages are here - https://sqlpkg.org.

#TODO SQLPkg is written in go. install it manually.

Sqlite-utils

can do things like:

  • Running queries and returning JSON, CSV, markdown table
  • Inserting JSON data: `echo | sqlite-utils insert dogs.db dogs -
  • Inserting CSV data: sqlite-utils insert dogs.db dogs docs.csv --csv
  • Insert-replacing data.

sqlite-http

Introducing sqlite-http: A SQLite extension for making HTTP requests / Alex Garcia | Observable

Sqlean

nalgeon/sqlean: The ultimate set of SQLite extensions

  • crypto: hash functions
  • define: user-defined functions and dynamic sql
  • fileio: read and write files
  • fuzzy: fuzzy string matching and phonetics
  • ipaddr: IP address manipulation
  • json1: JSON functions
  • math: math functions
  • regexp: regular expressions
  • stats: math statistics
  • text: string functions
  • unicode: Unicode support
  • uuid: Universally Unique IDentifiers
  • vsv: CSV files as virtual tables

Pocketbase

Pocketbase is an open source backend that can be used to build API applications.

  • single binary download
  • written in Go
  • embedded database (SQLite)
  • built in user and files managment
  • built in admin UI
  • simple REST UI

Sqlsync

orbitinghail/sqlsync SQLSync is a collaborative offline-first wrapper around SQLite. It is designed to synchronize web application state between users, devices, and the edge.

Example use cases

  • A web app with a structured file oriented data model like Figma. Each file could be a SQLSync database, enabling real-time local first collaboration and presence
  • Running SQLSync on the edge with high tolerance for unreliable network conditions
  • Enabling optimistic mutations on SQLite read replicas

Soul

soul | 🕉 A SQLite REST and realtime server, written in node.js; Run soul -d sqlite.db -p 8000 and it’ll start a REST API on http://localhost:8000 and a Websocket server on ws://localhost:8000


See also: duckdb, til/sqlite-writable_schema, code/sqlite-csv-loading-using-virtual-table-extension

notes#database#sqlite

bash scripting

Never forget to run shellcheck on any bash/shell script you write.

Bash for production systems - presentation on “Survival guide for quality scripts”

YJL: bashlint and ShellCheck for checking Bash sources

dylanaraps/pure-bash-bible: 📖 A collection of pure bash alternatives to external processes.

——

Minimal safe Bash script template | Better Dev

gist source:

#!/usr/bin/env bash

set -Eeuo pipefail

cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1

trap cleanup SIGINT SIGTERM ERR EXIT

usage() {
  cat <<EOF
Usage: $(basename "$0") [-h] [-v] [-f] -p param_value arg1 [arg2...]

Script description here.

Available options:

-h, --help      Print this help and exit
-v, --verbose   Print script debug info
-f, --flag      Some flag description
-p, --param     Some param description
EOF
  exit
}

cleanup() {
  trap - SIGINT SIGTERM ERR EXIT
  # script cleanup here
}

setup_colors() {
  if [[ -t 2 ]] && [[ -z "${NO_COLOR-}" ]] && [[ "${TERM-}" != "dumb" ]]; then
    NOCOLOR='\033[0m' RED='\033[0;31m' GREEN='\033[0;32m' ORANGE='\033[0;33m' BLUE='\033[0;34m' PURPLE='\033[0;35m' CYAN='\033[0;36m' YELLOW='\033[1;33m'
  else
    NOCOLOR='' RED='' GREEN='' ORANGE='' BLUE='' PURPLE='' CYAN='' YELLOW=''
  fi
}

msg() {
  echo >&2 -e "${1-}"
}

die() {
  local msg=$1
  local code=${2-1} # default exit status 1
  msg "$msg"
  exit "$code"
}

parse_params() {
  # default values of variables set from params
  flag=0
  param=''

  while :; do
    case "${1-}" in
    -h | --help)
      usage
      ;;
    -v | --verbose)
      set -x
      ;;
    --no-color)
      NO_COLOR=1
      ;;
    -f | --flag) # example flag
      flag=1
      ;;
    -p | --param) # example named parameter
      param="${2-}"
      shift
      ;;
    -?*)
      die "Unknown option: $1"
      ;;
    *)
      break
      ;;
    esac
    shift
  done

  args=("$@")

  # check required params and arguments
  [[ -z "${param-}" ]] && die "Missing required parameter: param"
  [[ ${#args[@]} -eq 0 ]] && die "Missing script arguments"

  return 0
}

parse_params "$@"
setup_colors

# script logic here

msg "${RED}Read parameters:${NOCOLOR}"
msg "- flag: ${flag}"
msg "- param: ${param}"
msg "- arguments: ${args[*]-}"

——

notes#unix

Machine Learning

Learning

When people are getting ready to learn machine learning at MSc level, they don’t learn from a course that says “if you don’t understand it it doesn’t matter”, they learn from this course instead. Abu-Mostafa’s Caltech course is probably the best first course that delivers good understanding of machine learning. via

Resources

Video

Blogs

Papers

Browse the State-of-the-Art in Machine Learning | Papers With Code

Pen and Paper Exercises in Machine Learning

This is a collection of (mostly) pen-and-paper exercises in machine learning. The exercises are on the following topics: linear algebra, optimisation, directed graphical models, undirected graphical models, expressive power of graphical models, factor graphs and message passing, inference for hidden Markov models, model-based learning (including ICA and unnormalised models), sampling and Monte-Carlo integration, and variational inference.


See also: machine-learning-books

notes#learning#machine-learning

Julia programming language

Learning

Blog Posts

Comparisons

2020-06-03 A Look at Chapel, D, and Julia Using Kernel Matrix Calculations – The D Blog; Julia comes out ahead in performance. Even handed comparison on Dlang's website.

Books/Tutorials

IDE/tools

Important information

twitter

notes#julia#programming-language

Programming Langauges Theory

Notes on theory of programming languages.

Concepts See:

Metalists

  • A path to Programming Language Theory enlightenment
  • Colin Stebbins Gordon's Electronic References -- "... loosely-categorized collection of links to PL (and related) texts and references that are available online because they are either openly shared publications (like PLAI, SF, or the HoTT book), first editions of updated books released to the world (like Programming in Scala or Semantics with Applications), thorough but out of print references (like TTFP), or publicly available drafts (like HtDC and Practical Foundations for Programming Languages). Most of these I've only used for brief personal reference, and have not read in depth. The exceptions, those books I've spent considerable time with and highly recommend, are marked with asterisks."

Books

Reading

Papers

Courseware

Lectures

Denotational Semantics

notes

J programming language

J programming language

Code

Blogs

People

notes#apl#jlang#programming-language

CSV

NOTE: When you can, prefer ASV over CSV -- Text File formats – ASCII Delimited Text – Not CSV or TAB delimited text, especially  when you aren’t writing the files by hand. (Caveat: "UTF-8 won’t trip this since it is ASCII compatible. That is, any ASCII byte in valid UTF-8 encoded bytes corresponds to its ASCII codepoint, regardless of context. (All continuation bytes are at least 0x80 and all leading bytes for codepoints greater than U+007F are at least 0xC0, which makes the 0x1E and 0x1Fseparators safe.") UTF-16 or UTF-32 on the other hand...)

Convert CSV to ASV: xsv fmt -t$'\x1f' one.csv > one.asv

Command line tools

MacOS

  • Table Tool is a fast, open source, mac native application to open csv files. I have set this as my default CSV opener.

Web tools

csvbase, a simple web database, faq

  • View, add, edit and delete rows from a browser
  • Export to CSV, XLSX, Parquet, etc
  • Each table has a single URL, RESTfully accessed by HTTP verb
  • has an API with API key, that you get when you register
  • works out of the box with R, pandas, duckdb, apache-spark
  • paste cells directly from Microsoft Excel
  • code is open source on github under AGPL license, written in python.

Apache Metamodel

Apache Metamodel provides a common interface for discovery, exploration of metadata and querying of different types of data sources. Uniform connector and query API for CSV & data formats, relational databases, noSQL databases.

With MetaModel you use a type-safe SQL-like API for querying any datastore:

DataContext dataContext = DataContextFactory.create[TypeOfDatastore](...);
DataSet dataSet = dataContext.query()
    .from("libraries")
    .select("name")
    .where("language").eq("Java")
    .and("enhances_data_access").eq(true)
    .execute();

The MetaModel query API allows you to use the power of SQL, even on data formats such as CSV files, Excel spreadsheets, NoSQL databases and more.

notes#csv#query#tools

Type Theory

Introductory materials

Important concepts in type theory.

  • Alonzo Church's typed lambda-calculus -- mathematical foundation

  • Per Martin-Löf's intuitionistic type theory, 1998 :cite:martin1998intuitionistic

  • Curry-Howard correspondence -- equates programs with proofs.

  • Homotopy type theory refers to a new interpretation of Martin-Löf’s system of intensional, constructive type theory into abstract homotopy theory.

Type inference

Type Inference by Solving Constraints – Caleb Helbling – Programming Languages & Systems

Videos

  • "Type Theory Foundations" lecture by Robert Harper at OPLSS 2013.

To read

  • "Programming in Martin-Lof's type theory" by Nordstrom, 1990 cite:[Nordstrom1990]

Row polymorphism vs subtyping

Misc

notes

ATS Lang

What is ATS?

Learning

Programs written in ATS

Talks

Blog posts

notes#programming-language

Vala Programming Language

STATUS: No longer Maintained.

Vala is a C# | Java like langauge that compiles down to C+glibc. Used heavily for developing gnome desktop applications. Before I discovered D (and to certain extent nim), I had hoped that Vala would be a nice compiled langauge to use. However, the community of Vala appears to not care beyond desktop applications.

notes#programming-language

Type system

Ability to read type rules is an important skill when reading Programming Langauge theory papers.

The two books that have been mentioned in relation to learning type systems are:

  • Types and Programming Languages by Benjamin Pierce
  • Practical Foundations for Programming Languages by Robert Harper

Papers

Discussions

Articles

Courses

notes

Red language

Link dump

Unsorted links ...

Why Red

Learn

Community

Rebol stuff

People / blog / website

Code

notes

Pure programming langauge

Pure is a modern-style functional programming language based on term rewriting. It offers equational definitions with pattern matching, full symbolic rewriting capabilities, dynamic typing, eager and lazy evaluation, lexical closures, built-in list and matrix support and an easy-to-use C interface. The interpreter uses LLVM as a backend to JIT-compile Pure programs to fast native code.

REPL

: 1. offers completion 2. show foo will print the definition of defined functions and vars.

Language notes

: 1. records == "hash pairs"

notes

Programming Aphorisms

Norris Numbers ---

My friend Clift Norris has identified a fundamental constant that I call Norris’ number, the average amount of code an untrained programmer can write before he or she hits a wall. Clift estimates this as 1,500 lines. Beyond that the code becomes so tangled that the author cannot debug or modify it without herculean effort.


Aphorisms on programming language design

notes

Operating Systems

Unikernels

Courses

Books

History

Teaching OSes

  • eduOS-rs · eduOS-rs is a Unix-like computer operating system based on a monolithic architecture for educational purposes, which is developed for the course Operating Systems at the RWTH Aachen Univeristy.

Interesting OSes

notes

NGiNX

See also: openresty

Notes

Use strace to verify whether NGiNX is serving gzipped static assets:

$ sudo strace -p 25249 2>&1  | grep gz

where 25249 is the pid of the nginx worker process, which can be found by ps ax | grep nginx

Refs

Applications

  • Telize is a JSON IP and GeoIP REST API (IP Geolocation) built on Nginx and Lua. via

Configuration tools

notes

ಮೂಡಲ ಮನೆಯ ...

ಚಿತ್ರ: ಬೆಳ್ಳಿ ಮೋಡ, 1967 Youtube video

ಕವಿ: ದ. ರಾ. ಬೇಂದ್ರೆ

ಮೂಡಲ ಮನೆಯ ಮುತ್ತಿನ ನೀರಿನ

ಎರಕಾವಾ ಹೊಯ್ದ, ನನ್ನನೆ ಎರಕಾವಾ ಹೊಯ್ದ

ಬಾಗಿಲ ತೆರೆದು ಬೆಳಕು ಹರಿದು

ಜಗವೆಲ್ಲಾ ತೊಯ್ದ, ದೇವನು ಜಗವೆಲ್ಲಾ ತೊಯ್ದ

ಎಳೆಗಳ ಮೇಲೆ, ಹೂಗಳ ಒಳಗೆ

ಅಮ್ರಿತದಾ ಬಿಂದು, ಕಂಡವು ಅಮ್ರಿತದಾ ಬಿಂದು

ಯಾರಿರಿಸಿಹರು ಮುಗಿಲಿನ ಮೇಲಿಂದ

ಇಲ್ಲಿಗೆ ಇದ ತಂದು, ಈಗ ಇಲ್ಲಿಗೆ ಇದ ತಂದು

ಗಿಡಗಂಟೆಗಳ ಕೊರಳೊಳಗಿಂದ ಹಕ್ಕಿಗಳ ಹಾಡು

ಹೊರಟಿತು ಹಕ್ಕಿಗಳ ಹಾಡು

ಗಂಧರ್ವ ಸೀಮೆಯಾಯಿತು, ಕಾಡಿನ ನಾಡು

ಕ್ಷಣದೊಳು, ಕಾಡಿನ ನಾಡು


Notes:

notes

ಕನ್ನಡ ಪ್ರಾರ್ಥನೆ -- "ಕನ್ನಡವೆಮ್ಮಯ ಪ್ರಾಣ"

(Note: prayer before the Sunday Kannada class)

Kannadavemmaya praaNa, kannadavemmaya maana

ಕನ್ನಡವೆಮ್ಮಯ ಪ್ರಾಣ, ಕನ್ನಡವೆಮ್ಮಯ ಮಾನ

Kannada taayige namana, O kannada taayige namana

ಕನ್ನಡ ತಾಯಿಗೆ ನಮನ, ಓ ಕನ್ನಡ ತಾಯಿಗೆ ನಮನ ।।2।।


Kannada taayiya makkaLu naavu

ಕನ್ನಡ ತಾಯಿಯ ಮಕ್ಕಳು ನಾವು

Kannadigaru naavu ennuta kuNivevu

ಕನ್ನಡಿಗರು ನಾವು ಎನ್ನುತ ಕುಣಿವೆವು ।।2।।


Kannada naDe-nuDi hrudayangamavu

ಕನ್ನಡ ನಡೆ-ನುಡಿ ಹೃದಯಂಗಮವು

KannadatanavE siri-sampadavu

ಕನ್ನಡತನವೇ ಸಿರಿ-ಸಂಪದವು. ।2।


Kannadavemmaya praana, kannadavemmaya maana

ಕನ್ನಡವೆಮ್ಮಯ ಪ್ರಾಣ, ಕನ್ನಡವೆಮ್ಮಯ ಮಾನ

Kannada taayige namana, O kannada taayige namana

ಕನ್ನಡ ತಾಯಿಗೆ ನಮನ, ಓ ಕನ್ನಡ ತಾಯಿಗೆ ನಮನ ।।2।।


baaLali kannada, beLeyali kannada

ಬಾಳಲಿ ಕನ್ನಡ, ಬೆಳೆಯಲಿ ಕನ್ನಡ ।2।

uLiyali kannada endendU

ಉಳಿಯಲಿ ಕನ್ನಡ ಎಂದೆಂದೂ ।2।

kannadatanavE nitya

ಕನ್ನಡತನವೇ ನಿತ್ಯ


KannadatanavE nityavu enutali

ಕನ್ನಡತನವೇ ನಿತ್ಯವು ಎನುತಲಿ

Kannada taayige namisuvevu

ಕನ್ನಡ ತಾಯಿಗೆ ನಮಿಸುವೆವು ।4।


notes#kannada

Indy Big Data meetup - December 2015

Talk by Josh Berkus, core member of PostgreSQL.

Big data features

  • sophisticated sql parser/planner
  • works with most DW tools
  • many large DB features (partitioning etc.,)
  • Foreign Data Wrappers (FDW)
  • stability and reliability

Data sizing:

  • comfort zone: 1G to 10TB
  • possible: 10TB to 100TB
  • With extensions: ??

9.5 status:

  • beta 2 released Nov 12, 2015.

9.5 big data features:

  • UPSERT
  • BRIN indexes
  • GROUPING SETS/CUBE
  • Foreing Schema
  • Faster sorts
  • Misc

UPSERT: INSERT ... ON CONFLICT DO { UPDATE | IGNORE }, similar to MERGE only better. Merge syntax was complex and did not support some of the use cases (single row insert or update). Merge is available in other DBs (Oracle?)

Why you want Upsert:

  • works for large sets of rows
  • supports complex logic
  • supports cascading
  • rewriting procedural ETL logic as single SQL statements
  • faster (sometimes)

How it works -- It probes the index (which means BTree index), (caveat?), locks the leaf page. If we try concurrent upserts they will fail because of lock, but will not overwrite data (??).

BRIN -- Block-Range INdex:

  • new index type
  • also known as "skiplist" index
  • good for naturally ordered data.
  • WHY? - very small indexes for very large data. (BTree:2142MB::BRIN:(64kb for 512, 192kb for 64))
  • Table is divided into blocks. for each block store min and max value.
  • lot faster to load index. (second quandrant tested this using TPC-H Lineitem data; 95:BTree::18:BRIN)

GROUPING, SETS, ROLLUP and CUBE:

ROLLUP -- get subtotals and totals with detail in one query.

SELECT country, city, count(*)
FROM lwn_subscribers
GROUP by rollup (country, city);

CUBE -- explosiion of all summaries for use with OLAP tools (e.g: Mondrian, Pentaho etc.,). Earlier we had to do this externally (say Java). (CUBE output is not meant to be human-readable).

GROUPING SETS - superset/programmable version of both ROLLUP and CUBE.

SELECT ...
FROM ...
GROUP by grouping sets ((city, level), (level), ());

Abbreviated key sorting

  • sort varlena data by key prefix
  • much faster index build
  • 2x to 20x faster
  • works with TEXT, VARCHAR, ..
  • no extra work.. just upgrade to 9.5.

Foreign Schema

  • Foreign Data wrapper
  • let pg access external data like it was a local table.
  • example: redis (what are all my keys)
CREATE FOREIGN TABLE myredishash
(key text, val text[])
SERVER redis_server
...

INSERT INTO myredishash (key, val)
VALUES ('mytable:r1, '{prop1, val1..}');

FDW to query other PostgreSQL instances,Hadoop, cassandra, kafka, spreadsheet, twitter(REST), multicorn (Python).

Import Foreign Schema (SQL DBs):

IMPORT FOREIGN SCHEMA public
EXCEPT (reports, audit)
FROM server acctng_server into acctng;

currently on "postgresql-like" databases.

Foreign Table inheritence:

  • Data federation using postgresql paritioning
CREATE FOREIGN TABLE users_shard_1 ()
INHERITS (users) server shard_1;

CREATE FOREIGN TABLE users_shard_2 ()
INHERITS (users) server shard_2;

citusdb uses FTI to store in columnstore (cstore) tables.

More features:

SET LOGGED/UNLOGGED:

  • Use unlogged tables for ELT.
  • Google summer of code project
  • You can change logged/unlogged post-facto.
  • ALTER TABLE july_data SET LOGGED

GiST index-only Scan:

Index-only scan for PostGIS, Exclusion

WAL compression:

Reduce PostgreSQL log writes during data loading; less writing => faster load.

TABLESAMPLE:

Get a "quick look" at data in a big table.

SELECT * FROM user_profiles
TABLESAMPLE BERNOULLI (0.001);
  • Sampling algorithsm available now -- system, bernoulli.

Beyond 9.5:

Parallel seq scan; finally, parallel query for postgresql.

set max_parallel_degree = 4 ;
select * from pgbench_accounts
where filler like '%a%';

cstore & pg_shard

  • extensions from citusdata
  • cstore: column store for PostgreSQL
  • pg_shard: automated DW sharding -- automated sharding of tables to remote shards. Aimed at big data use case.
  • idea behind this: retrofitting to existing database instance that you never thought will get that big.

Big data forks go OSS

  • PipelineDB: August 2015. is a streaming database. "Spark, but relational"
  • Greenplum: November 2015. Still has the most mature "MPP", since it is the most battle-tested.
  • CitusDB: January 2016. Opensource as an extension. can be retrofitted to existing pg instl.

Questions:

  • "Recursive queries? (for graph databases)" - the perfect GraphDB is impossible. it can be implmented for one kind of graph. PostgreSQL does well on large forest of small bushes. Idea: "use PG for storage. Write a query planner for graph querying".

Links:

Additional reference:

notes

Hakyll

This website is was made using Hakyll and Pandoc. I have often tried to move away from Hakyll because I can't "hack it" (haha). But, very few other static compilers can leverage the power of Pandoc like Hakyll does. So, I'm going to use this opportunity to learn Haskell through Hakyll like many have.

Hakyll source code examples:


See also: haskell, pandoc

notes

Desktop

stuff related to desktop application development, distribution, µISV etc.,

  • Google Omaha Tutorial - fman Blog - "Google Omaha is the open-source version of Google Update, the technology which keeps desktop apps such as Chrome up to date." Uesful to know when you want to distribute a desktop application that needs to be kept automatically up to date.

  • Year in Review 2017 - fman Blog - a good example of a µISV.

web + desktop Development frameworks

Things in the "electron" space.

notes

Data Engineering

News

Software and Libraries

Articles

Books

Courses

Data Engineering Concentration - Data Science, MS | University of San Francisco

notes#data-engineering

CSCI 56500 - Programming Languages

Stuff related to CSCI 56500. I'm taking this course during Fall 2011 semester at IUPUI, taught by Prof. Rajeev Raje.

Text book: Advanced Programming Languages Design by Raphael Finkel. This book is available online.

Introduction

Recommended Reading

Control Structures

Semantics

Recommended Reading

Reference books

Related Courses

Prof Weimer of Virginia university is teaching CS 6610 - Design And Analysis Of Programming Languages in Fall 2011, which is quite interesting for a student of CSCI 56500.

Notes

Interesting links

  • It appears Lua gets the multiple return idea from Prof. Liskov's CLU language, which we studied in Chapter 2.

Open Questions

  • Do langauges that have S-expressions make it easy to implement continuations?

notes

CSCI 60300 - IUPUI CS

Papers read as part of "Advanced Distributed Systems" - CSCI 60300, Fall 2013 class taught by Dr. Raje at IUPUI.

  1. [Beugnard, Antoine, Jean-Marc Jézéquel, Noël Plouzeau, and Damien Watkins. "Making components contract aware," 1999. 32 (7)http://dx.doi.org/10.1109/2.774917.]{.citation cites="Beugnard1999"}; PDF.
  2. [Beugnard, Antoine, Jean-Marc Jezequel, and Noel Plouzeau. "Contract aware components, 10 years after," 2010. http://dblp.uni-trier.de/db/series/eptcs/eptcs37.html#abs-1010-2822.]{.citation cites="abs10102822"}; PDF
  3. [Tilak, Omkar J, and Rajeev R Raje. "Temporal interaction contracts for components in a distributed system," 2007..]{.citation cites="tilak2007temporal"}; PDF
  4. Synchronization Level Specification and Matching of Software Components by A. Kumari, K. Pradhan, L. Gallage and R. Raje
  5. Trust Contract of a Service and its role in Trustworthy Service Selection by L. Gallege, D. Gamage, J. Hill and R. Raje
  6. [Gamage, Dimuthu U, Lahiru S Gallege, James H Hill, and Rajeev R Raje. "A compositional trust model for predicting the trust value of software system qos properties," 2012..]{.citation cites="gamage2012compositional"}; PDF
  7. [Bracciali, Andrea, Antonio Brogi, and Carlos Canal. "A formal approach to component adaptation," 2005. 74 (1).]{.citation cites="bracciali2005formal"}; PDF
  8. Multilevel Specification for Adaptive Service MS Thesis by S. Phatak .
  9. [Lamport, Leslie. "Time, clocks, and the ordering of events in a distributed system," 1978. 21 (7).]{.citation cites="lamport1978time"}; PDF
  10. [Chandy, K Mani, and Leslie Lamport. "Distributed snapshots: Determining global states of distributed systems," 1985. 3 (1).]{.citation cites="chandy1985distributed"}; PDF
  11. [Dabrowski, Christopher, Kevin L Mills, and Stephen Quirolgico. A model-based analysis of first-generation service discovery systems, 2005..]{.citation cites="dabrowski2005model"}; PDF
  12. [Pradhan, Ketaki A, Lahiru S Gallege, and Rajeev R Raje. "MDE-urds-a mobile device enabled service discovery system," 2011..]{.citation cites="pradhan2011mde"}; PDF
  13. [Han, Taekgyeong, and Kwang Mong Sim. "An ontology-enhanced cloud service discovery system," 2010.. Vol. 1.]{.citation cites="han2010ontology"}; PDF
  14. [Chandy, K Mani. "Caltech infospheres project overview: Information infrastructures for task forces," 1996. 256.]{.citation cites="chandy1996caltech"}; PDF
  15. [Foster, Ian, Carl Kesselman, and Steven Tuecke. "The anatomy of the grid: Enabling scalable virtual organizations," 2001. 15 (3).]{.citation cites="foster2001anatomy"}; PDF
  16. [Foster, Ian, Carl Kesselman, Jeffrey M Nick, and Steven Tuecke. "The physiology of the grid," 2003..]{.citation cites="foster2003physiology"} PDF
  17. [Chandy, K Mani. "Sense and respond systems," 2005..]{.citation cites="chandy2005sense"}; PDF
  18. [Dean, Jeffrey, and Sanjay Ghemawat. "MapReduce: Simplified data processing on large clusters," 2008. 51 (1).]{.citation cites="dean2008mapreduce"}; PDF
  19. [Fox, Armando, Rean Griffith, A Joseph, R Katz, A Konwinski, G Lee, D Patterson, A Rabkin, and I Stoica. "Above the clouds: A berkeley view of cloud computing," 2009. 28.]{.citation cites="fox2009above"}; PDF
  20. [Weiser, Mark. "The computer for the 21st century," 1991. 265 (3).]{.citation cites="weiser1991computer"}; PDF

notes#distributed-systems#papers

Computer Architecture

Register allocation is a NP-hard problem. See "Register Allocation:What does the NP-completeness Proof of Chaitin et al. Really Prove?" via this thread on RTX2010 – Radiation-hardened stack machine microprocessor

What every programmer should know about memory, Part 1 [LWN.net] by Ulrich Drepper; September 2007. 9 part series.

Why is Apple’s M1 Chip So Fast?. Real world experience with the new M1… | by Erik Engheim | Nov, 2020 | Medium; Nov 2020.

Putting the "You" in CPU Curious exactly what happens when you run a program on your computer? Read this article to learn how multiprocessing works, what system calls really are, how computers manage memory with hardware interrupts, and how Linux loads executables.

notes#computing#hardware

Notes on Aphyr blog posts

These are my notes on reading Kyle's very informative series of blog posts on Jepsen to test various distributed databases. Errors are my own.

Jepsen

281. Jepsen: On the perils of network partitions

What is linearizability? From Linearizability versus Serializability,

"Linearizability is a guarantee about single operations on single objects. In plain English, under linearizability, writes should appear to be instantaneous. Imprecisely, once a write completes, all later reads (where “later” is defined by wall-clock start time) should return the value of that write or the value of a later write. Once a read returns a particular value, all later reads should return that value or the value of a later write."

Uses a cluster for 5 machines on a LXC based virtualization to simulate the network partitions using Jepsen.

salticid, a fabric(?) like remote execution tool is used to run the tests on the cluster.

How to create a partition? cause nodes n1 and n2 to drop traffic from n3, n4, and n5.

Other errors that are used to simulate network problems:

  1. partition
  2. slow
  3. flaky (probabilistic dropping of messages)

The test itself is simple. Use 5 clients each to generate a sequence of non-overlapping list of numbers. Write these numbers to the database. See how many of these were actually saved to the database. Get the difference as the "loss".

282. Jepsen: Postgres

PG accepts connections on a single primary node, which means, if you can't talk to that primary node, the system is unavailable. This means PG is Consistent and has Partition tolerance (CP).

"Even though the Postgres server is always consistent, the distributed system composed of the server and client together may not be consistent. It’s possible for the client and server to disagree about whether or not a transaction took place." The 2phase commit (2PC) protocol says that we must wait for the acknowledgement message to arrive in order to decide the outcome.. If the client does not get the ack from the primary node, the system has a deadlock.

Strategies for dealing with 2PC(on the db, in this case - PG), (when we suspect network partitioning..):

a. Accept false negatives -- say the write failed even if there is a small chance of success b. use data structures to allow idempotent operations. This way, when you encounter network errors, you can retry the write. A queue that has "atleast once delivery" semantics is a good place to put repeatable writes that can retried later. c. write the transaction ID to the DB or a log on a disk or atleast-once-queue. Once the network partition is resolved, retry or cancel (if the transaction had succeeded in the earlier attempt).

"A network partition–and indeed, most network errors–doesn’t mean a failure. It means the absence of information."

283. Jepsen: Redis

Redis as often used a message queue, lock service, session store, or even as database. Redis in a single-server setup is a CP system. Redis ofers asynchronous primar -> secondary replication, which means that the primary returns the response to the writing client even before the replication to the secondary is complete.

A group of nodes is also called a component.

  • ??How to write the verification of a consensus algorithm in TLA+??

Programming

Clojure

notes

Apache Phoenix

Notes

Where does Phoenix fit in?

phoenix demo

  • 10 years of Fortune 500 stocks
  • 30M rows
  • Single AWS node
  • interactive visual query for stock prices ...

What is Hbase

  • Runs on HDFS
  • K/V store -- distributed, sorted, map
  • low level APIs -- get, put values given row key & scan over range given start and stop row keys.

Why use HBase?

  • you have lots of data. scale linearly. shards automatically. data is split and redistributed
  • no transactions out of the box.
  • you need strict consistency.
  • hbase handle incremental data changes by building log structure merge trees

Why use Phoenix?

  • SQL

  • reduces the amount of code users need to write.

  • Performance optimisations transparent to user

    • aggregation
    • skip scanning
    • secondary indexing
    • query optimisation
  • Leverage existing tooling around SQL

    • SQL Client (bin/sqlline.py)
    • OLAP engine. eg: Pentaho. Kylin?

Phoenix versus Hive performance

  • Phoenix (key filter) >> phoenix (full table) > >> Hive over HBase
  • Hive and Impala have similar perf. Does not understand the structure of row-keys

Use cases

  • Data archival

    • from oracle into HBase while maintaining salesforce developer API
  • Platform monitoring

Why is it important?

  • scalable, low latency app development starts with Phoenix
  • Phoenix worries about physical scale and fast performance so that app developers don't have to
  • Looks, tastes, feels like SOQL to force.com developer

Archival problem set

  • Field history tracking grows unbounded. call centers call individual change. No data is deleted for 8.5 years.
  • Enterprise customers require long term storage of 'cold' data.
  • Data retention policies can require of data to be kept around

Archive pilot demonstration

  • insret data from Oracle into Phoenix

Monitoring use case

  • security, compliance and audit
  • product support and "Limits analysis"
  • product usage and management (roll up into aggregates)
  • Identity fraud

Phoenix under the hood

  • aggregate co-processor on severside per region, parallelised.
  • returns only the distinct set of features
  • preserves network bandwidth
  • client does final merge-sort.
  • client returns the result as a JDBC result

Roadmap (Nov, 2013)

  • Apache incubator
  • Joins
  • multi-tenant tables
  • monitoring and manageent
  • cost-based query optimizer
  • sql OLAP extensions (WINDOW, PARTITION OVER, RANK)
  • Transactions

State of the union (Jun 2015)

  • Runs TPC queries

  • Supports JOIN, sub-queries, derived tables

  • Secondary indexing strategies

    • Immutable for write-once/append only data (eg: Log data.. has time component). There is no incremental secondary index.
    • Global for read-heavy mutable data (co-processors on the server side keep indexes in sync with data tables). A second HBase table is created that is ordered according to the columns you are indexing. Optimiser will use this table if it deems this table to be more efficient.
    • Local for write-heavy mutable or immutable data. Custom load-balancers. All the writes are local. The writes can be done on the same region servers.
  • statistics driven parallel execution -- background process in hbase. allows the user to optimze queries. uses equidistant keys in region to collect stats.

  • Tracing and metrics for monitoring and management -- better visibility into what's going on. Uses Apache HTrace. Collect data across scans into stats table. Then query for bottlenecks -- index maint etc.,

Join and subquery support

  • Left/Right/Full outer Join; cross join

  • additional: semi join; anti-join

  • Algorithms: hash-joni; sort-merge-join

  • Optimizations:

    • Predicate push-down
    • FK-to-PK join optimisation
    • Global index with missing data columns
    • Correlated subquery rewrite
  • TPC - benchmarking suite

  • HBase 1.0 support

  • Functional indexes -- 4.3 release of Ph. Indexing on expression not on column.

SELECT AVG(response_time) FROM SERVER_METRICS
WHERe DAYOFMONTH(create_time)=1

Adding the following index will turn it into a range scan:

CREATE INDEX day_of_month_idx
ON SERVER_METRICS(DAYOFMONTH(create_time))
INCLUDE(response_time)
  • User defined functions -- extension points to phoenix. Define the metadata of the fun (input, output) params.
CREATE FUNCTION WOEID_DISTANCE(INTEGER, INTEGER)
RETURN INTEGER AS 'org.apache.geo.woeidDistance'
USING JAR '/lib/geo/geoloc.jar'

usage:

SELECT FROM woeid a JOIN woeid b on a.country = b.country
WHERE woeid_distance(a.ID, b.ID) < 5;

This query executes on server side. This is tenant aware, which means.. there is no chance of conflict between tenants defining the same UDF.

  • Query Server + Thin Driver -- offloads queryplanning and execution to different server(s). Minimises client dependencies

  • connection string: Connection conn = DriverManager.getConnection("jdbc:phoenix:thin:url=http://localhost:8765");

  • See http://phonenix.apache.org/server.html

  • Union ALL support -- query multiple tables to get single resultset.

  • testing at scale with Pherf -- define a scenario and deploy pherf to the cluster. It will generate the data and collect the stats. Testing with representattive data size. functional data sets.

  • MR Index build

  • Spark Integration .. RDD backed by a Phoe table.

  • Data built-in functions -- WEEK, DAYOFMONTH etc.,

  • Tranactions -- using http://tephra.io

    • supports repeable_read isolation level
    • allows reading your own uncommitted data
    • Optional -- enable on a table by table basis
    • no performance penalty when not used
    • Optimistic concurrency control
    • no deadlocks or lock escalation
    • cost of conflict detection and possible rollback is higher
    • good id conflicts are rare: short transactions, disjoin partitioning of work
    • conflict detection is not necessary if the data is immutable. ie., write-once/append-only data.
  • Tephra Architecture

Apache Calcite

  • next step for Phoenix
  • Query parser, compiler and planner framework
  • SQL-92 compliant
  • Pluggable cost-based optimizer framework
  • Interop with Calcite adaptors
  • already used by Drill, Hive, Kylin, Samza
  • Supports any JDBC source
  • One Cost model to rule them all

Installation

Setting up a local phoenix cluster using Docker

Download and install Docker beta for Mac

We will setup a three node hadoop cluster using this recipe as a template.

git clone git@github.com:kiwenlau/hadoop-cluster-docker.git
cd hadoop-cluster-docker
docker build .

Lot of things fly by ...

Successfully built ed4ece2b19f2

Create hadoop network

sudo docker network create --driver=bridge hadoop
Password:
f678bdfc5918e15a578b909692e6f04a4ef5f730a95ebb0f16da5a30c38354b1

notes

AI Agent Framework

AI Agent frameworks:


Infrastructure

Ensue.dev --  is the shared memory and coordination harness for AI agents. It provides a persistent, semantic layer where agents can store observations, share context, and coordinate actions across any tool, model, or framework. Instead of isolated, stateless agents that start from zero each time, Ensue enables agents to build on each other's work. One agent's insight becomes another agent's starting point. See also: Ensue network / autoresearch

notes