[Redis] Setup redis with Rails

  1. Install Gemfile
    gem 'redis'
    gem 'redis-namespace'
  2. Create file config: redis.yml
    development:
       host: hdev01
       port: 6479
       db: 0
       namespace: 4travel
  3. Create function for load file config
    def redis_config
      @redis_config ||= YAML.load(File.open(Rails.root.join("config/redis.yml"))).symbolize_keys[Rails.env.to_sym].symbolize_keys
    end
  4. Create namspace redis with function config

    def redis
      @redis ||= Redis::Namespace.new(redis_config[:namespace], :redis => Redis.new(redis_config))
    end
  5. Use redis to set and get data

    #set data
    redis.set(key, value, ex: expiration_time)
    
    #get data
    redis.keys('*').grep(...) # get all keys and use grep to filter

[Rails] Check request is_bot or not

def is_bot?(request)
 agent = request.env["HTTP_USER_AGENT"]
 # agent = request.user_agent
 matches = nil
 matches = agent.match(/(facebook|postrank|voyager|twitterbot|googlebot|slurp|butterfly|pycurl|tweetmemebot|metauri|evrinid|reddit|digg)/mi) if agent
 if ( agent.nil? or matches)
   return true
 else
   return false
 end
end

Another code:

def is_bot?
  http_user_agent = request.env["HTTP_USER_AGENT"] || ""

  begin
    ua = ""
    ua = URI.decode(http_user_agent)
  rescue
  end

  browser = Browser.new(ua: ua)
  return browser.bot?
end

Example:

1 example Googlebot smartphone user-agent

Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 
Mobile Safari/537.36 (compatible; Googlebot/2.1; +
http://www.google.com/bot.html)

We use agent.match(/(facebook|twitterbot|googlebot)/mi), it will search in user-agent string, find text match googlebot. 

/mi: search downcase and upcase

without /mi: search exactly with googlebot (Googlebot is not match)

Use grep command line

1.  Use grep to filter command line history

history | grep 'text'

 

2. Search text in all file of folder

grep -rnw '/path/to/folder/' -e 'text-to-search'
  • -r or -R is recursive,
  • -n is line number, and
  • -w stands for match the whole word.
  • -l (lower-case L) can be added to just give the file name of matching files.

 

3. Find files with name

find | grep "name_file"

 

4. Search texts with no contain char

grep(/^abc(?!e).*/)

Ex:

array = [“abcdx”, “abcex”, “abcfx”]

array.grep(/^abc(?!e).*/) => [“abcdx”, “abcfx”]

[Redis] Add 1 more port for Redis

  • Create a new redis .conf file
cp /etc/redis.conf /etc/redis_6479.conf
  • Edit /etc/redis_6479.conf
#modify pidfile
#pidfile /var/run/redis/redis.pid
pidfile /var/run/redis/redis_6479.pid

...
#modify port
#port 6379
port 6479

...
#modify logfile
#logfile /var/log/redis/redis.log
logfile /var/log/redis/redis_6479.log
  • Copy init script
cp /etc/init.d/redis /etc/init.d/redis_6479
  • and edit init script
...
pidfile="/var/run/redis/redis_6479.pid"
REDIS_CONFIG="/etc/redis_6479.conf"
  • Start 1 more redis with port 6479
sudo /etc/init.d/redis_6479 start

# or check status, restart
sudo /etc/init.d/redis_6479 status
sudo /etc/init.d/redis_6479 restart
  • Check port is running of redis:
ps aux |grep redis

grep-redis-port

Use “alias” in Linux

In file “~/.bash_profile“, we can use alias to define keyword shorter to run app faster 🙂

Example: In server has been installed redis. To run redis-server we must run command “/opt/redis/latest/bin/redis-server”. We can use alias in “~/.bash_profile“:

alias redis-server="/opt/redis/latest/bin/redis-server"

And with redis-cli we must run command: “/opt/redis/latest/bin/redis-cli”. We can use alias:

alias redis-cli="/opt/redis/latest/bin/redis-cli"

And now, we can type redis-server or redis-cli in terminal instead of long command: “/opt/redis/latest/bin/redis-server” and “/opt/redis/latest/bin/redis-cli”.

 

When we added alias to “~/.bash_profile“, we can reload “~/.bash_profile” by the way:

. ~/.bash_profile

 

Change the Command-Line Prompt Colour in the Ubuntu/Linux Terminal

First, open file bashrc

gedit ~/.bashrc

Find line has text: if [ “$color_prompt” = yes ]; then

Copy context in if clause and paste to else clause

Save, close and reopen terminal. 🙂

Optional information:

Black 0;30 – Dark Gray 1;30 – Blue 0;34 – Light Blue 1;34 – Green 0;32 – Light Green1;32 – Cyan 0;36 – Light Cyan 1;36 – Red 0;31 – Light Red 1;31 – Purple 0;35 – Light Purple 1;35 – Brown 0;33 – Yellow 1;33 – Light Gray 0;37 – White 1;37

 

[Linux] Using the Vim editor

Commands that switch the editor to insert mode

  • a will append: it moves the cursor one position to the right before switching to insert mode
  • i will insert
  • o will insert a blank line under the current cursor position and move the cursor to that line.
  • Esc key switches back to command mode.

Pressing the Esc key switches back to command mode. If you’re not sure what mode you’re in because you use a really old version of vi that doesn’t display an “INSERT” message, type Esc and you’ll be sure to return to command mode. It is possible that the system gives a little alert when you are already in command mode when hitting Esc, by beeping or giving a visual bell (a flash on the screen). This is normal behavior.

Basic operations

These are some popular vi commands:

  • n dd will delete n lines starting from the current cursor position.
  • n dw will delete n words at the right side of the cursor.
  • x will delete the character on which the cursor is positioned
  • :n moves to line n of the file.
  • :w will save (write) the file
  • :q will exit the editor.
  • :q! forces the exit when you want to quit a file containing unsaved changes.
  • :wq will save and exit
  • :w newfile will save the text to newfile.
  • :wq! overrides read-only permission (if you have the permission to override permissions, for instance when you are using the root account.
  • /astring will search the string in the file and position the cursor on the first match below its position.
  • / will perform the same search again, moving the cursor to the next match.
  • :1, $s/word/anotherword/g will replace word with anotherword throughout the file.
  • yy will copy a block of text.
  • n p will paste it n times.
  • :recover will recover a file after an unexpected interruption.

Refer: http://www.tldp.org/LDP/intro-linux/html/sect_06_02.html

[Ruby] Why should we use symbol for key in Hash

Using symbols not only saves time when doing comparisons, but also saves memory, because they are only stored once

1. Symbol and String

– Symbols in Ruby are basically “immutable strings” .. that means that they can not be changed, and it implies that the same symbol when referenced many times throughout your source code, is always stored as the same entity, e.g. has the same object id.

– Strings on the other hand are mutable, they can be changed anytime. This implies that Ruby needs to store each string you mention throughout your source code in it’s separate entity, e.g. if you have a string “name” multiple times mentioned in your source code, Ruby needs to store these all in separate String objects, because they might change later on (that’s the nature of a Ruby string).

2. Use in Hash

– If you use a string as a Hash key, Ruby needs to evaluate the string and look at it’s contents (and compute a hash function on that) and compare the result against the (hashed) values of the keys which are already stored in the Hash.

– If you use a symbol as a Hash key, it’s implicit that it’s immutable, so Ruby can basically just do a comparison of the (hash function of the) object-id against the (hashed) object-ids of keys which are already stored in the Hash. (much faster)

Downside: Each symbol consumes a slot in the Ruby interpreter’s symbol-table, which is never released. Symbols are never garbage-collected. So a corner-case is when you have a large number of symbols (e.g. auto-generated ones). In that case you should evaluate how this affects the size of your Ruby interpreter.

Notes:

If you do string comparisons, Ruby can compare symbols just by their object ids, without having to evaluate them. That’s much faster than comparing strings, which need to be evaluated.

If you access a hash, Ruby always applies a hash-function to compute a “hash-key” from whatever key you use. You can imagine something like an MD5-hash. And then Ruby compares those “hashed keys” against each other.

Refer: http://stackoverflow.com/posts/8189435/revisions