Skip to content

Instantly share code, notes, and snippets.

@TimLang
TimLang / simple_arithmetic_parser.rb
Last active January 2, 2016 17:18
simple arithmetic parser
# -*- encoding : utf-8 -*-
require 'debugger'
cal = lambda do |exp, stack=[]|
return exp if exp =~/^\d+$/
exp.scan(/((?:\d+)|[\*\+\/-]|(?:\((?:(?:\d)|[\*\+\/-])+\)))/) do |match|
word = match.first.to_s
if word =~ /^(\d+)$/
stack.unshift $1
@TimLang
TimLang / rscursion_match.rb
Last active January 2, 2016 16:39
ruby recursion match
regex = /^(?<stack>{(\g<stack>|(?<num>\d))})$/
"{{2}}".match regex #<MatchData "{{2}}" stack:"{{2}}" num:"2">
class Array
def bindex element, lower = 0, upper = length - 1
return if lower > upper
mid = (lower + upper) / 2
element < self[mid] ? upper = mid - 1 : lower = mid + 1
element == self[mid] ? mid : bindex(element, lower, upper)
end
end
class Array
@TimLang
TimLang / sort.rb
Created January 6, 2014 08:44 — forked from aspyct/sort.rb
# Sample implementation of quicksort and mergesort in ruby
# Both algorithm sort in O(n * lg(n)) time
# Quicksort works inplace, where mergesort works in a new array
def quicksort(array, from=0, to=nil)
if to == nil
# Sort the whole array, by default
to = array.count - 1
end
@TimLang
TimLang / gist:8235113
Created January 3, 2014 09:12
Amount format
1999995.99.to_s.reverse.scan(/(?:\d*\.)?\d{1,3}-?/).join(',').reverse
@TimLang
TimLang / gist:8215975
Created January 2, 2014 07:22
button float top
(->
rightSideTop = $('#right-side').offset().top
$(window).scroll(->
if $(this).scrollTop() > rightSideTop
$('#right-side').css({
'position': 'fixed'
'top': 0
})
else
$('#right-side').css('position', 'static')
@TimLang
TimLang / object
Created December 23, 2013 07:04
multi-dimensional array map
class Object
def deep_map(&block); yield(self) end
end
class Array
def deep_map(&block); map{|e| e.deep_map(&block)} end
end
or
@TimLang
TimLang / em_fiber.rb
Created December 20, 2013 03:26 — forked from zw963/em_fiber.rb
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
# 有关 Fiber 的解释: (按照数据流的方向分为两部分)
# 在 `主线程' 中使用 resume 方法来启动(或继续执行)一个 `纤程'.
# 1. 第一次调用 fiber.resume, 会启动一个纤程,
# 如果 resume 调用时提供了实参, 会作为代码块形参传入代码块.
# 2. 如果非第一次调用 fiber.resume, 即, `恢复' 一个纤程, 会做两件事:
# - 从上次离开纤程的那个位置(调用 Fiber.yield 离开纤程的那个位置), 恢复纤程的执行.
@TimLang
TimLang / gist:8018573
Last active December 31, 2015 17:09
removing the space which is NBSP; replacing all whitespaces, including the non-ASCII ones
#removing the space which is NBSP
" B.我国人民民主具有广泛性"..gsub(/[[:space:]]/, '')
#or
NBSP = "\u00a0"
str.gsub(NBSP, '')
#!/usr/bin/env ruby
require 'rubygems'
require 'daemons'
dir = File.expand_path(File.join(File.dirname(__FILE__), '..'))
daemon_options = {
:multiple => false,
:dir_mode => :normal,
:dir => File.join(dir, 'tmp', 'pids'),
:backtrace => true