Skip to content

Instantly share code, notes, and snippets.

@jhjguxin
Last active October 6, 2015 22:07
Show Gist options
  • Save jhjguxin/3059897 to your computer and use it in GitHub Desktop.
Save jhjguxin/3059897 to your computer and use it in GitHub Desktop.
tips from francis

which bundle

bundler

Broken bundle install details (1.1rc)

Cleanup then broken commands:

$ rm -rf ~/.bundle/ ~/.gem/                                                
$ rm -rf $GEM_HOME/bundler/ $GEM_HOME/cache/bundler/                       
$ rm -rf .bundle/                                                          
$ rm -rf vendor/cache/                                                     
$ rm -rf Gemfile.lock                                                      
$ bundle install --path vendor                                             

Could not find gem 'guard-bundler (>= 0) ruby' in the gems available on this machine.
Run bundle install to install missing gems.
$ bundle --help
Could not find gem 'guard-bundler (>= 0) ruby' in the gems available on this machine.
Run bundle install to install missing gems.

RubyGems mirrors source

http://mirrors.tuna.tsinghua.edu.cn/rubygems/

方便教育网的同学使用。

使用方法

gem

gem source -r http://rubygems.org/
gem source -a http://mirrors.tuna.tsinghua.edu.cn/rubygems/

http://ruby.taobao.org/

为什么有这个?

由于国内网络原因(你懂的),导致 rubygems.org 存放在 Amazon S3 上面的资源文件间歇性连接失败。所以你会与遇到 gem install *** 或 bundle install 的时候半天没有响应,具体可以用 gem install rails -V 来查看执行过程。

如何使用?

gem source -r http://rubygems.org/
gem source -a http://ruby.taobao.org
如果你使用 Bundler 请修改 Gemfile:
source 'http://ruby.taobao.org'

RVM 下载 加速

发现地址是写在 $rvm_path/config/db 文件里

找到这一段:

ruby_1.0_url=http://ftp.ruby-lang.org/pub/ruby/1.0
ruby_1.2_url=http://ftp.ruby-lang.org/pub/ruby/1.2
ruby_1.3_url=http://ftp.ruby-lang.org/pub/ruby/1.3
ruby_1.4_url=http://ftp.ruby-lang.org/pub/ruby/1.4
ruby_1.5_url=http://ftp.ruby-lang.org/pub/ruby/1.5
ruby_1.6_url=http://ftp.ruby-lang.org/pub/ruby/1.6
ruby_1.7_url=http://ftp.ruby-lang.org/pub/ruby/1.7
ruby_1.8_url=http://ftp.ruby-lang.org/pub/ruby/1.8
ruby_1.9_url=http://ftp.ruby-lang.org/pub/ruby/1.9
ruby_2.0_url=http://ftp.ruby-lang.org/pub/ruby/2.0
 

改成

ruby_1.0_url=http://ruby.taobao.org/mirrors/ruby/1.0
...
# 替换 Ruby 下载地址到国内淘宝镜像服务器
sed -i -e 's/ftp\.ruby-lang\.org\/pub\/ruby/ruby\.taobao\.org\/mirrors\/ruby/g' ~/.rvm/config/db
#dbbackup
#!/bin/sh

DBName=--all-databases
DBUser=root
DBPasswd=root
BackupPath=~/BBTang
DBName2=ecshopExtned

#mysqldump -h 222.73.17.75 -u$DBUser -p$DBPasswd $DBName2 > $BackupPath/`date -I`_$DBName2.sql

mysqldump -h 222.73.17.74 -u$DBUser -p$DBPasswd $DBName > $BackupPath/`date -I`_$DBName.sql


create_table(:table_name, :options => 'ENGINE=InnoDB DEFAULT CHARSET=utf8')

mysqldump -ubbtang -pbbtang --all-databases > ~/bbtang_backup/database/mysql.sql
mongodump -d bbtang_development -o ~/database/mongo_backup

##query as association mod cout

#query as association mod cout
User.find_by_sql("SELECT COUNT(*) FROM `users` INNER JOIN \
(select user_id, count(*) from authorizations where 1=1 group by user_id HAVING count(*)>1) a \
ON a.`user_id` = `users`.`id`
")

User.find_by_sql(" SELECT COUNT(*) user_auth_count, users.* FROM `users` INNER JOIN `authorizations` ON `authorizations`.`user_id` = `users`.`id`group by user_id HAVING count(*)>1")

#这个查找出来的只有有authorizations关联的用户
User.joins(:authorizations).where("(authorizations.provider != 'mmbkoo') and users.id >= #{s_user.id}").limit(250)

#这里查找的就是所有非mmbk用户并且id大于s_user的id的5个用户
User.where("id >= #{s_user.id} and id NOT IN (SELECT authorizations.user_id FROM authorizations WHERE (provider = 'mmbkoo'))").limit(5)

the monitor for mysql

sudo apt-get install mytop
mytop -uroot -proot

Mongoid Dynamic fields

class Person
  include Mongoid::Document
  field :first_name, type: String
  #field :middle_name, type: String
  #field :last_name, type: String
end

# Set the person's gender to male.
person[:gender] = "Male"
person.gender = "Male"

# Get the person's gender.
person.gender

# Raise a NoMethodError if value isn't set.
person.gender
person.gender = "Male"

# Retrieve a dynamic field safely.
person[:gender]
person.read_attribute(:gender)

# Write a dynamic field safely.
person[:gender] = "Male"
person.write_attribute(:gender, "Male")

# and you can use create to pass all Fields and dynamic you want
Person.create(first_name: "111", password: "xxxx", dy_field: "asdfa")

数据查询

# 过滤 -> 排序 -> limit
criteria = GxUser.where({:UserID => {"$nin" => exclude_users}, :UserName => {"$ne" => ""}, :HeadImage => {"$ne" => nil}, :Status => "1", :IsOnline => "1"}

### mysql nest transaction

- [Nested+transactions](http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#module-ActiveRecord::Transactions::ClassMethods-label-Nested+transactions)

mysql 子事务 `ActiveRecord::Rollback` exception in the nested block does not issue a ROLLBACK, In order to get a ROLLBACK for 
the nested transaction you may ask for a real sub-transaction by passing requires_new: true. If anything goes wrong, the 
database rolls back to the beginning of the sub-transaction without rolling back the parent transaction.

但是 child transaction 不会 触发 parent transaction 的 ROLLBACK。因此需要依据 child transaction 的 exec result to detected should parent transaction rollback

##CONFIGURING GEDIT FOR RAILS

sudo add-apt-repository ppa:ubuntu-on-rails/ppa
sudo apt-get update
sudo apt-get install gedit-gmate
sudo apt-get install gedit-plugins

Now lets fire up Gedit and turn on our preferences. To get to our plugins go to Edit > Preferences > Plugins. We’re going to enable the following options:

  • Snippets
  • Code Comment
  • Embedded Terminal
  • Find in Files
  • Rails Extract Partial
  • Rails File Loader
  • Session Saver (Optional)
  • Smart Indent (Optional)
  • Tab Switch (Optional)
  • TextMate Style AutoCompletion

tips for gedit multi edit mod plugin

The new plugin introduces a new ‘mode’ in which you can do multi editing. You enter this mode by Ctrl+Shift+C, and once enabled you can start inserting edit points manually by pressing Ctrl+E at any point in the document. Additionally, you can use Ctrl+Home and Ctrl+End to respectively insert edit points at the beginning or end of the line automatically (it will also skip to the previous/next line so you can quickly insert edit points at the beginning or end of some lines). When you start typing the inserts/deletes will be replicated in all the edit points. You can then press Escape to remove the additional edit points, and press Escape again to finally quit multi edit mode.

shortcuts

  • open or close Ctrl+Shift+C
  • enable or disable Ctrl+E
  • move edit points Ctrl+Home or Ctrl+End
#!/bin/sh
# Convert git log to GNU-style ChangeLog file.
# (C) Chris
if test -d ".git"; then
  echo "##BBTangCMS Changelog\n" > ChangeLog.markdown
  git log --date-order --date=short --reverse| \
    sed -e '/^commit.*$/d' | \
    awk '/^Author/ {sub(/\\$/,""); getline t; print $0 t; next}; 1' | \
    #sed -s 's/Merge:/> Merge:/g' | \
    sed -s 's/^Merge:.*$/> &\n/g' | \
    sed -s 's/^Author: /* Author: /g' | \
    sed -e 's/>Date:   \([0-9]*-[0-9]*-[0-9]*\)/>\t\1/g' | \
    sed -e 's/^\(.*\) \(\)\t\(.*\)/\3    \1    \2/g' >> ChangeLog.markdown
    exit 0
else
    echo "No git repository present."
    exit 1
fi
###############################################################
git-submodule - Initialize, update or inspect submodules
git submodule update --init code-style-guide/
SYNOPSIS

git submodule [--quiet] add [-b branch] [-f|--force]
              [--reference <repository>] [--] <repository> [<path>]
git submodule [--quiet] status [--cached] [--recursive] [--] [<path>…]
git submodule [--quiet] init [--] [<path>…]
git submodule [--quiet] update [--init] [-N|--no-fetch] [--rebase]
              [--reference <repository>] [--merge] [--recursive] [--] [<path>…]
git submodule [--quiet] summary [--cached|--files] [(-n|--summary-limit) <n>]
              [commit] [--] [<path>…]
git submodule [--quiet] foreach [--recursive] <command>
git submodule [--quiet] sync [--] [<path>…]
####################################################################


git show 449fa01c3a773566f98321bfb4844b21e595234b Gemfile --source
git show HEAD~5:Gemfile --source

git tags

git tag -l -n15 #-n[<n>]               print <n> lines of each tag message
git tag -a "0.1.0"
git push --tags

git issue and git flow

http://scottchacon.com/2011/08/31/github-flow.html

how git issue, first you should read https://help.github.com/

https://github.com/blog/831-issues-2-0-the-next-generation http://openmdao.org/dev_docs/dev-guide/issues.html https://help.github.com/articles/github-flavored-markdown

update single file update to local workarea

git fetch
git checkout origin/master path_to_file

copy files to clipboard in windows git bash

  • to copy from a file

    $ cat file > /dev/clipboard
    
  • to paste into a file

    $ cat /dev/clipboard > file
    
  • or to check the contents of the clipboard

    $ cat /dev/clipboard
    

removing selected commit log entries for a repository

removing selected commit log entries for a repository

# If you want to keep your work and just 'undo' that commit command (you caught before pushing to repo):
git reset --soft HEAD~1
# move HEAD to A, but leave the index and working tree as for D
git reset --soft <SHA1-for-A>

# Redo the D commit re-using the commit message, but now on top of A
git commit -C <SHA1-for-D>

# Re-apply everything from the old D onwards onto this new place 
git rebase --onto HEAD <SHA1-for-D> master
#Or, you could look at the output of git log, find the commit id of the commit you want to back up to, and then do this:

git reset --hard <sha1-commit-id>

git pull --rebase

git pull --rebase just does:

git fetch
git rebase

Because branch merges in git are recorded with a merge commit, they are supposed to be meaningful—for example, to indicate when a feature has been merged to a release branch. However, during a regular daily workflow where several team members sync a single branch often, the timeline gets polluted with unnecessary micro-merges on regular git pull. Rebasing ensures that the commits are always re-applied so that the history stays linear.

You can configure certain branches to always do this without the --rebase flag:

#make 'git pull' on master always use rebase 
$ git config branch.master.rebase true

You can also set up a global option to set the last property for every new tracked branch:

# setup rebase for every tracking branch
$ git config --global branch.autosetuprebase always

本地仓库的回退(撤销本地的commit): git reset:

reset命令有3种方式:

git reset --mixed:此为默认方式,不带任何参数的git reset,即时这种方式,它回退到某个版本,只保留源码,回退commit和index信息git reset --soft HEAD^:回退到某个版本,只回退了commit的信息,不会恢复到index file一级。如果还要提交,直接commit即可 git reset --hard:彻底回退到某个版本,本地的源码也会变为上一个版本的内容

#回退所有内容到上一个版本  
git reset HEAD^  
#回退a.py这个文件的版本到上一个版本  
git reset HEAD^ a.py  
#向前回退到第3个版本  
git reset –-soft HEAD~3  
#将本地的状态回退到和远程的一样  
git reset –-hard origin/master  
#回退到某个版本  
git reset 057d  
#回退到上一次提交的状态,按照某一次的commit完全反向的进行一次commit  
git revert HEAD  

checkout remote

git fetch --all
git checkout --track origin/recommend_vip

其实在认真阅读了这篇名为“计算内存使用”的文章之后,还是处于半迷糊状态。这位作者就说Linux下面没有特别好的显示内存占用的工具,虽然有top和free,但都说得不清楚,就跟巫毒教的魔术似的。 比如top这个工具,它会显示3种数据,作者分别解释如下:

VIRT:virtual memory usage。Virtual这个词很神,一般解释是:virtual adj.虚的, 实质的, [物]有效的, 事实上的。到底是虚的还是实的?让Google给Define之后,将就明白一点,就是这东西还是非物质的,但是有效果的,不发生在真实世界的,发生在软件世界的等等。这个内存使用就是一个应用占有的地址空间,只是要应用程序要求的,就全算在这里,而不管它真的用了没有。写程序怕出错,又不在乎占用的时候,多开点内存也是很正常的。 RES:resident memory usage。常驻内存。这个值就是该应用程序真的使用的内存,但还有两个小问题,一是有些东西可能放在交换盘上了(SWAP),二是有些内存可能是共享的。 SHR:shared memory。共享内存。就是说这一块内存空间有可能也被其他应用程序使用着;而Virt - Shr似乎就是这个程序所要求的并且没有共享的内存空间。 DATA:数据占用的内存。如果top没有显示,按f键可以显示出来。这一块是真正的该程序要求的数据空间,是真正在运行中要使用的。

所以DATA的含义比较确定,甚至可以用程序读取的数据量计算出来;SHR是一个潜在的可能会被共享的数字,如果只开一个程序,也没有别人共同使用它;VIRT里面的可能性更多,比如它可能计算了被许多X的库所共享的内存;RES应该是比较准确的,但不含有交换出去的空间;但基本可以说RES是程序当前使用的内存量。

restart nginx

sudo kill -HUP `cat /opt/nginx/logs/nginx.pid`
sudo /opt/nginx/sbin/nginx -h
sudo /opt/nginx/sbin/nginx -s stop
sudo /opt/nginx/sbin/nginx
sudo /etc/init.d/mysqld start
sudo /etc/init.d/postgresql start
http://www.elasticsearch.org/guide/reference/setup/installation.html

UFW防火墙简单设置

http://wiki.ubuntu.org.cn/UFW%E9%98%B2%E7%81%AB%E5%A2%99%E7%AE%80%E5%8D%95%E8%AE%BE%E7%BD%AE

Samba

Samba是Ubuntu和Windows进行网络共享的工具,比如分享打印机,互相之间传输资料文件。 http://wiki.ubuntu.com.cn/Samba

sudo ufw allow 24

screenshot with import

import --help
import 1.png

creat new user

useradd -d /home/testuser -s /bin/bash -G group -m testuser
man useradd
passwd testuser
man passwd

ssh service doesn't work

sudo apt-get autoremove ssh-import-id ssh openssh-client openssh-server --purge
sudo apt-get install ssh-import-id ssh openssh-client openssh-server -f

SSH出现“the ecdsa host key for 'xxx' differs from the key for the ip address 的解决办法

链接1 中找到 ,解决方法:

ssh-keygen -R "RemoteIP"
ssh-keyscan "RemoteIP"

How to analyse disk usage in command line linux?

Make sure all folders "behind" your mountpoints are empty. Out of experience i'd say most probably you hide some data behind a mountpoint.

you can check what is in the folder behind the mountpoint without having to unmount the disk/partitions (which can be nice if for example you would have to unmount /usr). Just do a

# mount --bind / /mnt
# du -shx /mnt

also as a side note:

# du -shx /

does the same as your du... but is quite a bit shorter (-s stands for summarize)

http://superuser.com/questions/300606/how-to-analyse-disk-usage-in-command-line-linux

ncdu -x /

mount /dev/xvda2 /mnt/check_disk_xvda2/
ncdu /mnt/check_disk_xvda2/

# remove file mark as deleted but, process which use it not quit
lsof |grep deleted
kill -s QUIT 11878
kill -9 11878

ls(1) displays wrong file sizes

http://mail-index.netbsd.org/netbsd-users/2011/10/01/msg009300.html http://serverfault.com/questions/290081/why-does-ls-lh-and-ls-ldh-give-me-varying-file-size

       du - estimate file space usage

SYNOPSIS
       du [OPTION]... [FILE]...
       du [OPTION]... --files0-from=F

DESCRIPTION
       Summarize disk usage of each FILE, recursively for directories.

       Mandatory arguments to long options are mandatory for short options too.

       -a, --all
              write counts for all files, not just directories

       --apparent-size
              print  apparent  sizes,  rather  than  disk usage; although the apparent size is usually smaller, it may be larger due to holes in (`sparse') files, internal
              fragmentation, indirect blocks, and the like

       -B, --block-size=SIZE
              scale sizes by SIZE before printing them.  E.g., `-BM' prints sizes in units of 1,048,576 bytes.  See SIZE format below.

       -b, --bytes
              equivalent to `--apparent-size --block-size=1'

       -c, --total
              produce a grand total

       -D, --dereference-args
              dereference only symlinks that are listed on the command line

       --files0-from=F
              summarize disk usage of the NUL-terminated file names specified in file F; If F is - then read names from standard input

       -H     equivalent to --dereference-args (-D)

       -h, --human-readable
              print sizes in human readable format (e.g., 1K 234M 2G)

       --si   like -h, but use powers of 1000 not 1024

       -k     like --block-size=1K

       -l, --count-links
              count sizes many times if hard linked

       -m     like --block-size=1M

       -L, --dereference
              dereference all symbolic links

       -P, --no-dereference
              don't follow any symbolic links (this is the default)

       -0, --null
              end each output line with 0 byte rather than newline

       -S, --separate-dirs
              do not include size of subdirectories

       -s, --summarize
              display only a total for each argument

       -x, --one-file-system
              skip directories on different file systems

       -X, --exclude-from=FILE
              exclude files that match any pattern in FILE

       --exclude=PATTERN
              exclude files that match PATTERN

       -d, --max-depth=N
              print the total for a directory (or file, with --all) only if it is N or fewer levels below the command line argument;  --max-depth=0 is the same as --summa‐
              rize

       --time show time of the last modification of any file in the directory, or any of its subdirectories

       --time=WORD
              show time as WORD instead of modification time: atime, access, use, ctime or status

       --time-style=STYLE
              show times using style STYLE: full-iso, long-iso, iso, +FORMAT FORMAT is interpreted like `date'

       --help display this help and exit

       --version
              output version information and exit

       Display  values are in units of the first available SIZE from --block-size, and the DU_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables.  Otherwise, units
       default to 1024 bytes (or 512 if POSIXLY_CORRECT is set).

       SIZE may be (or may be an integer optionally followed by) one of following: KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.

query text words

http://space.doit.com.cn/51460/viewspace-13862.html

man grep
grep -C 15 -nir "friends/findfriendbyguanxiid" log/production.log

find

将当前目录下的所有文件名由GBK转为UTF8

convmv -r -f GBK -t UTF-8 --notest --nosmart *

**附:**iconv是文件内容编码转换工具,把gbk编码的a.txt文件转换成utf8编码的b.txt

iconv -f GBK -t UTF-8 a.txt -o b.txt 

Read First line of a file

head -1 /path/to/file

LVM

  • LVM 是一个应用于 Linux 内核的本地卷管理器 (Logical Volume Manager)。 使用 LVM 你可以抽象你的存储空间,并且可以有很容易更改的“虚拟分区”。LVM的基本模块如下:
  • Physical volume (PV): 物理卷,例如一个硬盘,或一个Software RAID设备; 硬盘的一个分区 (或者甚至硬盘本身或者回环文件),在它上面可以建立卷组。It has a special header and is divided into physical extents. Think of physical volumes as big building blocks which can be used to build your hard drive.
  • Volume group (VG): 卷组,将一组物理卷收集为一个管理单元;Group of physical volumes that are used as storage volume (as one disk). They contain logical volumes. Think of volume groups as hard drives.
  • Logical volume(LV): 逻辑卷,等同于传统分区,可看作便准的块设备,以容纳文件系统;A "virtual/logical partition" that resides in a volume group and is composed of physical extents. Think of logical volumes as normal partiti
  • 主/从配置,如果主从数据库间数据差异太大, 应用中不应该连接从库 这样会浪费更多的资源

mongoid Defaults value

You can tell a field in Mongoid to always have a default value if nothing has been provided. Defaults are either static values or lambdas.

class Person
  include Mongoid::Document
  field :blood_alcohol_level, type: Float, default: 0.40
  field :last_drink, type: Time, default: ->{ 10.minutes.ago }
end
Shop.limit(1).map(&:products).map(&:count)
Shop.joins(:products).select("shops.*, COUNT(products.id) as products_count").group("shops.id").first.products_count

Use source_location: If you're on Ruby 1.9+, you can use source_location

require 'csv'

p CSV.new('string').method(:flock)
# => #<Method: CSV#flock>

CSV.new('string').method(:flock).source_location
# => ["/path/to/ruby/1.9.2-p290/lib/ruby/1.9.1/forwardable.rb", 180]
 false ? false : a rescue 1

Object.instance_methods.grep /^de/ # => [:define_singleton_method, :debugger]

#decode url url-decode on ruby
URI.unescape "mkey=121b11ad5c24f5bb93e62f5acd8ebefd&result%5B1%5D=1&result%5B2%5D=1&userid=1212" 
#=> "mkey=121b11ad5c24f5bb93e62f5acd8ebefd&result[1]=1&result[2]=1&userid=1212"
# not good
code = []
code << "next line of code #{something}"
code << "another line #{some_included_expression}"
code.join("\n")
# good
code = %{First line
  second line
Third line #{2 + 2}}
code = <<CODE
# End-of-heredoc must be at the start a line
  var1 = "foo"
  var2 = "bar"
CODE

# good
# End-of-heredoc may be preceeded by whitespace
code = <<-CODE
var1 = "foo"
var2 = "bar"
  CODE

ruby 深拷贝(deep clone)

http://www.iteye.com/topic/407957

  • assign value to variable, ruby里拷贝对象的最简单方法,下面来看一下效果:
irb(main):002:0> a = "Hooopo"
=> "Hooopo"
irb(main):003:0> b = a
=> "Hooopo"
irb(main):004:0> b.object_id
=> 23424840
irb(main):005:0> a.object_id
=> 23424840
irb(main):006:0> b.gsub!("o","-")
=> "H---p-"
irb(main):007:0> p a
"H---p-"
=> nil
irb(main):008:0> p b
"H---p-"
=> nil

b 修改后, a也跟着修改了, 并且abobject_id一样,就是同一个对象

  • dup 和 clone (dup和clone差不多,但是还是有一些区别的)
a= {a: 1}
b = {a: a}
a.delete(:a)
b # => {:a=>{}}

a= {a: 1}
b = {a: a.dup}
a.delete(:a)
b # => {:a=>{a: 1}}

irb(main):001:0> a = "Hooopo"
=> "Hooopo"
irb(main):002:0> b = a.dup
=> "Hooopo"
irb(main):003:0> a.object_id
=> 23428740
irb(main):004:0> b.object_id
=> 23425010
irb(main):005:0> b.gsub!("o","-")
=> "H---p-"
irb(main):006:0> p b
"H---p-"
=> nil
irb(main):007:0> p a
"Hooopo"
=> nil

b和a是不同对象,并且改变b后a不改变。这是我们想要的。

class Klass  
    attr_accessor :str  
 end  
 s1 = Klass.new       
 s1.str = "Hooopo"     
 p s1  
 s2 = s1.dup         
 p s2  
 s2.str.gsub!("o","-")     
 p s1           
 p s2    
#results  
#<Klass:0x2d2cd30 @str="Hooopo">  
#<Klass:0x2d2cc7c @str="Hooopo">  
#<Klass:0x2d2cd30 @str="H---p-">  
#<Klass:0x2d2cc7c @str="H---p-">    
  • 对单体方法的拷贝:clone会连同单体方法一起拷贝,dup不会。
irb(main):029:0> o = Object.new
=> #<Object:0x2b256a4>
irb(main):030:0> def o.say
irb(main):031:1>  puts "Hello,Hooopo"
irb(main):032:1> end
=> nil
irb(main):033:0> o_dup = o.dup
=> #<Object:0x296acec>
irb(main):035:0> o_clone = o.clone
=> #<Object:0x2dba194>
irb(main):037:0> o_dup.say
NoMethodError: undefined method `say' for #<Object:0x296acec>
        from (irb):37
        from :0
irb(main):038:0> o_clone.say
Hello,Hooopo

You should use Monit, God, Upstart, or Inittab to keep your clock process running the same way you keep your web and workers running.

# method such as 'Hash#deep_transform_keys'
# Utility.deep_transform_values({a: 1, b: {c: nil, d: 1}, e: nil}) {|v| "#{v}"}
# method such as 'Hash#deep_transform_keys'
# Utility.deep_transform_values({a: 1, b: {c: nil, d: 1}, e: nil}) {|v| "#{v}"}
def deep_transform_values(origin_hash = {}, &proc)
  if block_given?
    origin_hash.inject({}) do |new_hash, (k,v)|
      if v.class.eql?(Hash)
        new_hash[k] = self.send(:deep_transform_values, v, &proc)
      else
        #new_hash[k] = yield v
        new_hash[k] = proc.call(v)
      end
      new_hash
    end
  else
    origin_hash
  end
end

def as_json_nil_to_string(origin_hash = {})
  deep_transform_values(origin_hash) {|v| v.nil? ? "" : v }
end

Enumerable#all?

Passes each element of the collection to the given block. The method returns true if the block never returns false or nil. if the block is not given, Ruby adds an implicit block of {|obj| obj} (that is all? will return true only if none of the collection members are false or nil.)

%w{ant bear cat}.all? {|word| word.length >= 3}   #=> true
%w{ant bear cat}.all? {|word| word.length >= 4}   #=> false
[ nil, true, 99 ].all?                            #=> false

Enumerable#any?

Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil.

%w{ant bear cat}.all? {|word| word.length >= 3}   #=> true
%w{ant bear cat}.all? {|word| word.length >= 4}   #=> false
[ nil, true, 99 ].all?                            #=> false

Enumerable#none?

Passes each element of the collection to the given block. The method returns true if the block never returns true for all elements.

[].none?                                          #=> true
[nil].none?                                       #=> true
[nil,false].none?                                 #=> true

Enumerable#one?

Passes each element of the collection to the given block. The method returns true if the block returns true exactly once.

[ nil, true, 99 ].one?                            #=> false
[ nil, true, false ].one?                         #=> true
fields = %w(a b e d)
h = {a: 1, b: 2, d: 3}

h = {c: 2}

none_key = h.keys.map(&:to_s).none? {|key| puts fields.include?(key);fields.include?(key) }
# 这里有个 优化 只需要 有一个 true 方法就返回了
true
 => false
# has_key = h.keys.map(&:to_s).map {|key| fields.include?(key) }.include?(true)
has_key = h.keys.any {|key| fields.include?("#{key}") }

h = {a: 1, b: 2, d: 3}
# => {:a=>1, :b=>2, :d=>3}
none_key = h.keys.map(&:to_s).one? {|key| puts fields.include?(key);fields.include?(key) }
# 这里有个 优化 只需要 有两个 true 方法就返回了
true
true
tar用法实例 tar命令
tar 文件是几个文件和(或)目录在一个文件中的集合。这是创建备份和归档的佳径。
tar 使用的选项有:
-c — 创建一个新归档。
-f — 当与 -c 选项一起使用时,创建的 tar 文件使用该选项指定的文件名;当与 -x 选项
一起使用时,则解除该选项指定的归档。
-t — 显示包括在 tar 文件中的文件列表。
-v — 显示文件的归档进度。
-x — 从归档中抽取文件。
-z — 使用 gzip 来压缩 tar 文件。
-j — 使用 bzip2 来压缩 tar 文件。
要创建一个 tar 文件,键入:
tar -cvf filename.tar directory/file
可以使用 tar 命令同时处理多个文件和目录,方法是将它们逐一列出,并用空格间隔:
tar -cvf filename.tar /home/mine/work /home/mine/school
上面的命令把 /home/mine 目录下的 work 和 school 子目录内的所有文件都放入当前
目录中一个叫做 filename.tar 的新文件里。
要列出 tar 文件的内容,键入:
tar -tvf filename.tar
要抽取 tar 文件的内容,键入
tar -xvf filename.tar
这个命令不会删除 tar 文件,但是它会把被解除归档的内容
复制到当前的工作目录下,并保留归档文件所使用的任何
目录结构。譬如,如果这个 tar 文件中包含一个叫做
bar.txt 的文件,而这个文件包含在 foo/ 目录中,那么,
抽取归档文件将会导致在你当前的工作目录中创建
foo/ 目录,该目录中包含 bar.txt 文件
tar 默认不压缩文件。
要创建一个使用 tar 和 bzip 来归档压缩的文件,使用 -j 选项:
tar -cjvf filename.tbz file
以上命令创建了一个归档文件,然后将其压缩为 filename.tbz 文件。如果你使用 bunzip2 命令为 filename.tbz 文件解压,filename.tbz 文件会被删除,继之以 filename.tar 文件。
你还可以用一个命令来扩展并解除归档 bzip tar 文件:
tar -xjvf filename.tbz
要创建一个用 tar 和 gzip 归档并压缩的文件,使用 -z 选项:
tar -czvf filename.tgz file
这个命令创建归档文件 filename.tar,然后把它压缩为 filename.tgz 文件(文件 filename.tar 不被保留)。
如果你使用 gunzip 命令来给 filename.tgz 文件解压,filename.tgz 文件会被删除,并被
替换为 filename.tar。
你可以用单个命令来扩展 gzip tar 文件:
tar -xzvf filename.tgz
一. tar
1.压缩一组文件为tar.gz后缀。
# tar cvf backup.tar /etc
#gzip -q backup.tar
# tar cvfz backup.tar.gz /etc/
tar zxvf XXXX.tar.gz
tar jxvf XXXX tar.bz2
2.释放一个后缀为tar.gz的文件。
#gunzip backup.tar.gz
#tar xvf backup.tar
# tar xvfz backup.tar.gz
3.用一个命令完成压缩
#tar cvf - /etc/ | gzip -qc > backup.tar.gz
4.用一个命令完成释放
# gunzip -c backup.tar.gz | tar xvf -
5.如何解开tar.Z的文件?
# tar xvfz backup.tar.Z
# uncompress backup.tar.Z
#tar xvf backup.tar
6.如何解开.tgz文件?
#gunzip backup.tgz
7.如何压缩和解压缩.bz2的包?
#bzip2 /etc/smb.conf
这将压缩文件smb.conf成smb.conf.bz2
#bunzip2 /etc/smb.conf.bz2
这将在当前目录下还原smb.conf.bz2为smb.conf
注: .bz2压缩格式不是很常用,你可以man bzip2

by francis

工作周报

git log --author="864248765@qq.com" --pretty=format:'%ci %s' --since='7 day' --reverse
git log --author="864248765@qq.com" --date=short --since='7 day' --reverse
git log --author="864248765@qq.com" --date-order --date=short --reverse

fix broken ubuntu or unity

during use ubuntu, you must done some wrong thing, and you do not konw how to back, or can't understander what it's mean ...

the best method is restore or reset, ubuntu-deskdop or unity ...

three tips:

sudo spt-get remove --purge ubuntu-desktop;sudo apt-get install ubuntu-desktop;sudo reboot;
sudo apt-get remove --purge unity;sudo apt-get install unity;reboot;
# if you unity have some incorrent setting, you can
sudo apt-get install myunity
#then type
myunity
(Permit.where "name like '%category_base%'").collect{ |p| p.destroy}

mysql -u root -p         # 没有密码,直接回车
UPDATE mysql.user SET password=PASSWORD('root') WHERE user='root';
flush privileges;        # 更新密码
service mysqld restart   # 重启

# 建立名为test的数据库
create database askjane_development;
create database askjane_test;
create database askjane_production;
create database auth;
create database recommendation;

mysqldump -uroot -proot askjane_development category_bases > category_bases.sql

rails generate scaffold_controller recommend/recommend_users position:string name:string body:text created_at:datetime updated_at:datetime

rails generate scaffold_controller profiles user_id:integer real_name:string nickname:string level_id:integer gender:boolean face:file birthday:date degree:string city:string phone:phone child_birthday:date baby_gender:integer profession:string expert_field:text hobby:string  focus_tags_on:text pregnancy_status:integer agerange:integer pregnancy_timeline:integer label:string weibo:string

Knowledge.tag_counts_on(:categories).each do |c|
  puts "#{c.name} #{c.count}"
end

#sudo apt-get install magick libmagickcore-dev
#sudo apt-get install libmagickwand-dev
#gem install rmagick -v '2.13.1'
#gem 'rmagick', '~> 2.13.1'
sudo yum install ImageMagick-devel.x86_64 ImageMagic
class Hash
  module ClassMethods
    def self.replace_key(old_key, new_key)
     self[new_key] = self[old_key]
     self.delete(new_key)
    end
  end
end
h.keys.each do |key|
  h[new_keys[key]] = h[key] # add entry for new key
  k.delete(key)             # remove old key
end
ps aux|grep ruby #查进程
crontab -l|grep -i notify #查任务
查看进程:

1,ps -e 命令
ps -ef|grep <name>

check port 端口进程
lsof -i:3000

class User < ActiveRecord::Base scope :level, ->(level_id) {joins(:profile).where('profiles.level_id = ?', level_id)} scope :daren, joins(:profile).where('profiles.level_id = ?', 2) scope :expert, joins(:profile).where('profiles.level_id = ?', 3)

has_one :profile end

class Profile < ActiveRecord::Base
  #alias_attribute :pregnancy_status, :pregnancy_timeline
  scope :level, ->(level_id) { where(:level_id => level_id) }
  scope :daren, -> { where(:level_id => 2) }
  scope :expert, -> { where(:level_id => 3) }

  belongs_to :user,
    :class_name    => '::User', # note I added '::'
    :foreign_key   => 'user_id'
  belongs_to :level
end
Ctr+Alt+up/down/left/right 充分调动四个桌面

on rails present? != not empty? 因为 nil 没有 empty? 方法

#temperature monitor
sudo apt-get install lm-sensors
sensors

query and replace text

grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' /dev/null

grep -rl \'btn\' app/views | xargs sed -i "s/\'btn\'/\'btn btn-default\'/g" /dev/null

grep -lr -e \'btn\' app/views | xargs sed -i "s/btn/btn btn-default/g"
find ./app -type f | xargs sed -i 's/person_notes_path/notes_person_path/g'
find ./app/controllers/ -type f ! -path '*.rb'
find ./app/ -type f -path '*.js' -o -path "*.coffee"
cd /source-dir
       find . -name .snapshot -prune -o \( \! -name *~ -print0 \)|
       cpio -pmd0 /dest-dir

       This command copies the contents of /source-dir to /dest-dir, but omits
       files  and directories named .snapshot (and anything in them).  It also
       omits files or directories whose name ends in ~,  but  not  their  con‐
       tents.  The construct -prune -o \( ... -print0 \) is quite common.  The
       idea here is that the expression before -prune matches things which are
       to  be  pruned.  However, the -prune action itself returns true, so the
       following -o ensures that the right hand side  is  evaluated  only  for
       those  directories  which didn't get pruned (the contents of the pruned
       directories are not even visited, so their  contents  are  irrelevant).
       The  expression on the right hand side of the -o is in parentheses only
       for clarity.  It emphasises that the -print0 action  takes  place  only
       for  things  that  didn't  have  -prune  applied  to them.  Because the
       default `and' condition between tests binds more tightly than -o,  this
       is  the  default anyway, but the parentheses help to show what is going
       on.

rdesktop 192.168.1.126 -g 1366x768 -D -r sound:local -u administrator -p 123456

screenshot with import

import --help
import 1.png

add remote repository

http://stackoverflow.com/questions/5697750/what-exactly-does-the-u-do-git-push-u-origin-master-vs-git-push-origin-ma

git remote add bbtang git@bbtang.com:bbtang/bbtcms.git
git remote update
git fetch bbtang
git push bbtang master

# from github should better
git remote add origin https://github.com/jhjguxin/bbtangcms.git
git push -u origin master

axure rp

Axure RPAxure 的发音是[Ack-surea],RP则是[Rapid Prototyping]快速原型的缩写。Axure RP Pro是美国Axure Software Solution公司的精心杰作,如果你本身是软件项目经理,Web产品经理,或网站策划工作者,那么你不能不知道这套软件。

界面

xmind

XMind是一款同样开源且跨平台的思维导图软件,XMind 在功能上一点也不逊色于FreeMind,某些方面,XMind 甚至更加具有优势。XMind 支持中文简繁体。

:%s /password/
ssh hjiang@pyelite.com
password is hjiang
sudo apache2ctl -k restart
NameVirtualHost 174.127.70.248:8080
ssh -CfNg -D 8080 hjiang@pyelite.com
socks host 127.0.0.1:8080
http://smallbusiness.yahoo.com/
----------------------------------------------
80端口的配置文件要在 httpd.conf 里面才行 其他端口好像就没有没有这个限制 也就是可以直接在apache.conf 里面直接include
文件名空格要转义 '\ '
localhost /usr/lib/pymodules/python2.6/django
vps /usr/local/lib/python2.6/dist-packages/django
从远程地址下目录来
scp -r user@ip:/dir /dir
从本地上传远程地址
scp -r /dir user@ip:/dir
scp -r /home/jhjguxin/Desktop/djcode hjiang@174.127.70.248:/home/hjiang/jhj
scp -r /etc/apache2/sites-enabled hjiang@174.127.70.248:/etc/apache2/sites-enabled
DocumentRoot /home/hjiang/mysite
'/var/www/djcode/blogserver/db'
python /home/hjiang/mysite/manage.py runserver 0.0.0.0:8000
# 编辑settings.py文件并将数据库引擎和名称设置如下。(将数据库的路径更改为新创建的myapp目录中的一个文件。)
pwd 当前目录
sudo apache2ctl -k restart
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '/home/hjiang/mysite/db/mydb.db' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
hjiang@s1:/usr/lib/python-django/bin$ ls
__init__.py daily_cleanup.py make-messages.py unique-messages.py
compile-messages.py django-admin.py profiling
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
'django.template.loaders.eggs.load_template_source',
django/contrib
__init__.py middleware.py models.py tests.py
不能打开数据库文件
hjiang@s1:~/mysite$ sudo chown hjiang /home/hjiang/mysite/db
hjiang@s1:~/mysite$ sudo chown hjiang /home/hjiang/mysite
from django.db import connection
cursor=connection.cursor()
ln -s 源文件 目标文件
当我们需要在不同的目录,用到相同的文件时,我们不需要在每一个需要的目录下都放一个必须相同的文件,我们只要在某个固定的目录,放上该文件,然后在其它的目录下用ln命令链接(link)它就可以,不必重复的占用磁盘空间,只生成目标文件的一个镜像。
例如:ln -s /tmp/less /usr/local/bin/less
/usr/share/pyshared/django/middleware/csrf.py
#ln -s /var/lib/python-support/python2.6/django/contrib/csrf /var/lib/python-support/python2.6/django/middleware
hjiang@s1:/var/lib/python-support/python2.6/django/contrib/csrf$ ls
__init__.py middleware.py models.py tests.py
__init__.pyc middleware.pyc models.pyc tests.pyc
/var/lib/python-support/python2.6/django/contrib/admin
/var/lib/python-support/python2.6/django/contrib/admin/media
//////////////
ImproperlyConfigured: Error importing middleware django.middleware.csrf: "No module named csrf"
Seems it's due to django version http://stackoverflow.com/questions/2341030/no-module-named-csrf
I'm currently using 1.1.2 django version
(I may post enhancement issue, but is there a way to freeze django binnaries in the project in order to have a standalone & plug and play django-mumble?)
David.
尝试升级django版本
//////////////
Linux VPS下SSH常用命令
目录操作:
rm -rf mydir /*删除mydir目录*/
cd mydir /*进入mydir目录*/
cd - /*回上一级目录*/
cd .. /*回父目录,中间有空格*/
cd ~ /*回根目录*/
mv tools tool /*把tools目录改名为tool */
ln -s tool bac /*给tool目录创建名为bac的符号链接,最熟悉的应该就是FTP中www链接到public_html目录了*/
cp -a tool /home/vpser/www /*把tool目录下所有文件复制到www目录下 */
文件操作:
rm go.tar /* 删除go.tar文件 */
find mt.cgi /* 查找文件名为mt.cgi的文件 */
df –h /* 查看磁盘剩余空间,好像没这个必要,除非你太那个了 */
解压缩:
tar xvf wordpress.tar /* 解压tar格式的文件 */
tar -tvf myfile.tar /* 查看tar文件中包含的文件 */
tar cf toole.tar tool /* 把tool目录打包为toole.tar文件 */
tar cfz vpser.tar.gz tool /* 把tool目录打包且压缩为vpser.tar.gz文件,因为.tar文件几乎是没有压缩过的,MT的.tar.gz文件解压成.tar文件后差不多是10MB */
tar jcvf /var/bak/www.tar.bz2 /var/www/ /*创建.tar.bz2文件,压缩率高*/
tar xjf www.tar.bz2 /*解压tar.bz2格式*/
gzip -d ge.tar.gz /* 解压.tar.gz文件为.tar文件 */
unzip phpbb.zip /* 解压zip文件,windows下要压缩出一个.tar.gz格式的文件还是有点麻烦的 */
下载:
wget http://soft.vpser.net/web/nginx/nginx-0.8.0.tar.gz
/*下载远程服务器上的文件到自己的服务器,连上传都省了,服务器不是100M就是1000M的带宽,下载一个2-3兆的MT还不是几十秒的事 */
wget -c http://soft.vpser.net/web/nginx/nginx-0.8.0.tar.gz
/* 继续下载上次未下载完的文件 */
转载请注明出处:VPS侦探 http://www.vpser.net
进程管理:
ps -aux /*ps 进程状态查询命令*/
ps命令输出字段的含义:
[list]
[*]USER,进程所有者的用户名。
[*]PID,进程号,可以唯一标识该进程。
[*]%CPU,进程自最近一次刷新以来所占用的CPU时间和总时间的百分比。
[*]%MEM,进程使用内存的百分比。
[*]VSZ,进程使用的虚拟内存大小,以K为单位。
[*]RSS,进程占用的物理内存的总数量,以K为单位。
[*]TTY,进程相关的终端名。
[*]STAT,进程状态,用(R--运行或准备运行;S--睡眠状态;I--空闲;Z--冻结;D--不间断睡眠;W-进程没有驻留页;T停止或跟踪。)这些字母来表示。
[*]START,进程开始运行时间。
[*]TIME,进程使用的总CPU时间。
[*]COMMAND,被执行的命令行。
[/list]
ps -aux | grep nginx /*在所有进程中,查找nginx的进程*/
kill 1234 /*1234为进程ID,即ps -aux 中的PID*/
killall nginx /*killall 通过程序的名字,直接杀死所有进程,nginx为进程名*/
Vim操作:
移动类的:
h/j/k/l: 左/下/上/右 移一格
w : 向后词移动 (前面加数字移动多少个词)
b : 向前词移动 (前面加数字移动多少个词)
e : 向后移到词末
ge : 向前移到词末
$ <End> : 行末
0 <Home> : 行首
tx : 向右查找本行的x并移到那儿(大写时向左)
33G : 移到文件的第33行
gg : 文件首行
G : 文件尾行
33% : 文件的33%处
H/M/L : 屏幕的首/中/尾行
zt/zz/zb : 当前行移到屏幕的首/中/底部
跳转:
" : 回到跳转来的地方
CTRL-O : 跳到一个 “较老” 的地方
CTRL-I <Tab> : 则跳到一个 “较新” 的地方
查找:
/ : 向下查找(后加关键字)
? : 向上查找(后加关键字)
n : 下一条符合的记录
编辑:
i : 转换到插入模式
x : 删除当前字符
. : 重复最后一次的修改操作(同PS里ctrl+f执行滤镜)
u : 撤销操作
CTRL-R : 重做
p : 将删除的字符插入到当前位置(put)
退出保存:
:q : 退出
:q! : 不保存退出
ZZ : 保存后退出
:e! : 放弃修改重新编辑
VPS侦探
Linux SSH远程文件/目录传输命令scp
一、scp是什么?
scp是secure copy的简写,用于在Linux下进行远程拷贝文件的命令,和它类似的命令有cp,不过cp只是在本机进行拷贝不能跨服务器,而且scp传输是加密的。可能会稍微影响一下速度。
二、scp有什么用?
1、我们需要获得远程服务器上的某个文件,远程服务器既没有配置ftp服务器,没有开启web服务器,也没有做共享,无法通过常规途径获得文件时,只需要通过scp命令便可轻松的达到目的。
2、我们需要将本机上的文件上传到远程服务器上,远程服务器没有开启ftp服务器或共享,无法通过常规途径上传是,只需要通过scp命令便可以轻松的达到目的。
三、scp使用方法
1、获取远程服务器上的文件
scp -P 2222 root@www.vpser.net:/root/lnmp0.4.tar.gz /home/lnmp0.4.tar.gz
上端口大写P 为参数,2222 表示更改SSH端口后的端口,如果没有更改SSH端口可以不用添加该参数。 root@www.vpser.net 表示使用root用户登录远程服务器www.vpser.net,:/root/lnmp0.4.tar.gz 表示远程服务器上的文件,最后面的/home/lnmp0.4.tar.gz表示保存在本地上的路径和文件名。
2、获取远程服务器上的目录
scp -P 2222 -r root@www.vpser.net:/root/lnmp0.4/ /home/lnmp0.4/
上端口大写P 为参数,2222 表示更改SSH端口后的端口,如果没有更改SSH端口可以不用添加该参数。-r 参数表示递归复制(即复制该目录下面的文件和目录);root@www.vpser.net 表示使用root用户登录远程服务器www.vpser.net,:/root/lnmp0.4/ 表示远程服务器上的目录,最后面的/home/lnmp0.4/表示保存在本地上的路径。
3、将本地文件上传到服务器上
scp -P 2222 /home/lnmp0.4.tar.gz root@www.vpser.net:/root/lnmp0.4.tar.gz
上端口大写P 为参数,2222 表示更改SSH端口后的端口,如果没有更改SSH端口可以不用添加该参数。 /home/lnmp0.4.tar.gz表示本地上准备上传文件的路径和文件名。root@www.vpser.net 表示使用root用户登录远程服务器www.vpser.net,:/root/lnmp0.4.tar.gz 表示保存在远程服务器上目录和文件名。
4、将本地目录上传到服务器上
scp -P 2222 -r /home/lnmp0.4/ root@www.vpser.net:/root/lnmp0.4/
上 端口大写P 为参数,2222 表示更改SSH端口后的端口,如果没有更改SSH端口可以不用添加该参数。-r 参数表示递归复制(即复制该目录下面的文件和目录);/home/lnmp0.4/表示准备要上传的目录,root@www.vpser.net 表示使用root用户登录远程服务器www.vpser.net,:/root/lnmp0.4/ 表示保存在远程服务器上的目录位置。
5、可能有用的几个参数 :
-v 和大多数 linux 命令中的 -v 意思一样 , 用来显示进度 . 可以用来查看连接 , 认证 , 或是配置错误 .
-C 使能压缩选项 .
-4 强行使用 IPV4 地址 .
-6 强行使用 IPV6 地址 .
这时候在局域网内部,访问http://192.168.1.2:8080和http://192.168.1.2都没有问题
访问外网iphttp://100.100.100.100:8080也可以访问,但是http://100.100.100.100就一直显示it works!
不知道怎么回事,后来把NameVirtualHost 192.168.1.2:80改成 NameVirtualHost *:80
即:把ip地址改成*,外网的也可以了!
问题是解决了,但是原理还是不知道,留个记号!
方便日后解决,也希望博友知道可以给我留言,谢谢
scp -r /home/jhjguxin/Desktop/djcode/blogserver hjiang@174.127.70.248:/home/jhjguxin/Desktop/djcode/blogserver
du
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment