Skip to content

Instantly share code, notes, and snippets.

View qhwa's full-sized avatar

Qiu Hua qhwa

View GitHub Profile
@qhwa
qhwa / step1.exs
Created May 10, 2020 12:41
UTF8 decoding
6c f0 9f 8d ad 70 =>
01101100 11110000 10011111 10001101 10101101 01110000
@qhwa
qhwa / UTF8.exs
Created May 10, 2020 12:38
UTF8-decoding
f0 9f 8d ad =>
11110000 10011111 10001101 10101101 =>
-----xxx --xxxxxx --xxxxxx --xxxxxx =>
000 011111 001101 101101 =>
┕━━━━━━━━━ 0x1f36d ━━━━━━━━━━┙
@qhwa
qhwa / bench.exs
Created May 10, 2020 03:59
sub-binary-and-match-context
defmodule MyBinParser1 do
def valid?(<<length::2, data::binary>>),
do: byte_size(data) >= length
def valid?(_), do: false
end
defmodule MyBinParser2 do
def valid?(<<length::2, _data::binary-size(length), _rest::binary>>),
do: true
@qhwa
qhwa / ref_binary.exs
Created May 10, 2020 03:55
A demo of binary referencing in Elixir
iex> a_very_large_binary = :binary.copy("x", 1000)
...> <<_first_three_bytes::binary-3, rest::binary>> = a_very_large_binary
...> byte_size(rest)
997
...> :binary.referenced_byte_size(rest)
1000
@qhwa
qhwa / compose.exs
Last active April 18, 2020 02:06
BitString decomposing
defmodule IEEE_754 do
def friction_to_mantissa(""), do: 0
def friction_to_mantissa(<<n::1, rest::bits>>),
do: n + friction_to_mantissa(rest) * 0.5
end
iex> mantissa = IEEE_754.friction_to_mantissa(<<1::1, friction::bits>>)
...> :math.pow(-1, sign) * mantissa * :math.pow(2, exponent - 1023)
3.14
@qhwa
qhwa / text_width.exs
Created April 16, 2020 02:02
A script displaying East Asian characters and Emoji
defmodule RenderingDemo do
@behaviour Ratatouille.App
import Ratatouille.View
def init(_context) do
"Hello world! 你好世界! <<🦸🏻‍♀️🧖‍♀️>>"
end
def update(model, _message), do: model
@qhwa
qhwa / hello_world.exs
Last active April 9, 2020 01:53
Hello world from ExTermbox.
alias ExTermbox.Bindings, as: Termbox
alias ExTermbox.{Cell, EventManager, Event, Position}
:ok = Termbox.init()
{:ok, _pid} = EventManager.start_link()
:ok = EventManager.subscribe(self())
for {ch, x} <- Enum.with_index('Hello, World! 你好世界!') do
:ok = Termbox.put_cell(%Cell{position: %Position{x: x, y: 0}, ch: ch})
@qhwa
qhwa / mnesia_example.exs
Last active December 16, 2016 09:44
Mnesia Database Simple Example
defmodule MnesiaExample do
def demo do
# Step 1: initialize
setup
# Step 2: write some datas into database
seed
# Step 3: read from database
@qhwa
qhwa / go_port_forwarding.go
Last active March 27, 2024 13:17
network port forwarding in go lang
package main
import (
"fmt"
"io"
"net"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
@qhwa
qhwa / user.rb
Last active October 8, 2015 00:12
find nearby users
# find users nearby a certain location and print them
# by qhwa
require 'json'
require 'ostruct'
require 'logger'
class User < OpenStruct
OFFICE_GPS = [ 53.3381985, -6.2592576 ]