Coder Social home page Coder Social logo

research_noted's People

Contributors

phamthack avatar

Watchers

 avatar  avatar

research_noted's Issues

[Info] - Building Your Own Ruby Gem

  1. Create an account
User name: phamthack ([email protected])
Password: **default**
  • Add key to push
curl -u phamthack https://rubygems.org/api/v1/api_key.yaml > ~/.gem/credentials; chmod 0600 ~/.gem/credentials
  1. Naming & Building Your Gem
gem install bundler
bundle gem your_gem_name
  1. Gemspec & Version
  • Open file your_gem_name.gemspec and edit info of gem
  spec.summary       = %q{This gem help you BJ}
  spec.description   = %q{This gem help you BJ}
  spec.homepage      = "https://rubygems.org/"
  spec.metadata["allowed_push_host"] = "https://rubygems.org/"
  spec.metadata["homepage_uri"] = spec.homepage
  spec.metadata["source_code_uri"] = "https://rubygems.org/"
  spec.metadata["changelog_uri"] = "https://rubygems.org/"
  1. Coding Your Gem
  • Write code into file lib/your_name_gem.rb
  1. Build your gem
gem build your_gem_name.gemspec
  1. Testing Your Gem
gem install your_gem_name
  1. Pushing Your Gem Live
gem push your_gem_name-version.gem

========Error you have got===============
Error: You do not have permission to push to this gem. Ask an owner to add you with: gem owner your_gem_name --add [email protected]
Fix: Your_gem_name have existed on rubygem.org

[Info] Install nokogiri -v '1.3.2'

gem install nokogiri -v '1.3.2' -- --use-system-libraries --with-iconv-dir=$(brew --prefix libiconv) --with-xml2-include=$(brew --prefix libxml2)/include/libxml2

[Info] - Install Ruby on Rails - MacOS

Installing rbenv

brew install rbenv

Add this code into the shell config. ~/.bash_profile if using bash, ~/.zshrc if using zsh

eval "$(rbenv init -)"

Installing Ruby

rbenv install -l
rbenv install version_you_want
rbenv global version_you_want
ruby -v

Working with Gems

echo "gem: --no-document" > ~/.gemrc
gem install bundler

Installing Rails

gem install rails -v version_you_want
gem install rails (latest version)
rbenv rehash
rails -v

Updating and Uninstalling rbenv and Ruby

brew upgrade rbenv ruby-build
rbenv uninstall 2.1.3
eval "$(rbenv init -)" (remove this)
rm -rf `rbenv root`
brew uninstall rbenv

[Info] - bundle install is not successful cannot install ffi 1.12.2 osx 10.15

1.start "Xcode"....

2.Go to "Preferences"

3.Select "Locations" tab

4.Command Line Tools: = select the version of "Xcode" that is already installed on the system. [Drop down menu]

5.Relaunch "Terminal"
6.Clear "Drush" cache

drush cc drush

7.Run:

gem install ffi -v '1.12.2'

and it was successful.

bundle install

[Infra] - Ansible Tips and tricks

[General tips]

  • Keep it simple
  • Use version control: Github, ...
  • Customize the CLI output

[Playbook tips]

  • Use whitespace
  • Always name tasks
  • Always mention the state
  • Use comments

[Inventory tips]

  • Use dynamic inventory with clouds
  • Group inventory by function
  • Separate production and staging inventory
  • Keep vaulted variables safely visible

[Execution tricks]

  • Try it in staging first
  • Update in batches
  • Handling OS and distro differences

[Info] - Install & Uninstall MongoDB

  • Install
brew update
brew install mongodb
mkdir -p /data/db
sudo chown -R `id -un` /data/db
mongod
mongo
  • Uninstall
  1. Check to see if any mongo service is running
launchctl list | grep mongo
  1. Unload from LaunchAgents
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
rm -f ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
launchctl remove homebrew.mxcl.mongodb
  1. Kill all the processes related to mongod
pkill -f mongod
  1. Uninstall the mongodb
brew uninstall mongodb
  1. Re-confirming if mongo related file still exists
ls -al /usr/local/bin/mong*
ls -al ~/Library/LaunchAgents
  1. If you have separate folder for db
rm -rf /usr/local/var/mongodb
rm -rf /data/db

[Info] - How to manage multiple GitHub accounts with SSH Key

  1. Generating the SSH keys
  • Check SSH key:
ls -al ~/.ssh
  • Generate a key
ssh-keygen -t rsa
ssh-keygen -t rsa -C "email@work_mail.com" -f "id_rsa_work_user1"
  1. Adding the new SSH key to the corresponding GitHub account
  • Copy SSH Key:
pbcopy < ~/.ssh/id_rsa.pub
  • Add to Github account:
Go to Settings
Select SSH and GPG keys from the menu to the left.
Click on New SSH key, provide a suitable title, and paste the key in the box below
Click Add key — and you’re done!
  • Check connect Github:
ssh -T [email protected]
ssh-add -K ~/.ssh/id_rsa
  1. Registering the new SSH Keys with the ssh-agent
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_work_user1
  1. Creating the SSH config File
  • Create new file:
cd ~/.ssh/$ touch config
  • Edit:
# Personal account, - the default configHost github.com   HostName github.com   User git   IdentityFile ~/.ssh/id_rsa

# Work account-1Host github.com-work_user1       HostName github.com   User git   IdentityFile ~/.ssh/id_rsa_work_user1
  1. One active SSH key in the ssh-agent at a time
ssh-add -l
ssh-add -D

[Info] Install Postgres

  1. Install:
brew update
brew install postgresql

postgres --version
  1. How to create a physical PostgreSQL Database
initdb /usr/local/var/postgres
or
initdb --pgdata=your/data/path --username=your_super_user_name -W
  1. How to start/stop a PostgreSQL Database
pg_ctl -D /usr/local/var/postgres start
pg_ctl -D /usr/local/var/postgres stop
  1. How to create the actual PostgreSQL Database
createdb mydatabasename
dropdb mydatabasename

psql mydatabasename
  1. Connect
psql -U your_super_user_name -W -d database_name

[Info] - Add Sublime Text 3 to Command line

  • Max OS
ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" /usr/local/bin/sublime
  • Ubuntu
sudo ln -s /opt/sublime/sublime_text /usr/bin/subl
  • Open
sublime .
sublime . -a (the same windown)

[Info] Smart CSV

require 'csv'

class SmartCsv < CSV
  DEFAULT_BATCH_SIZE = 500

  def self.batch_read(file_path, **options)
    rows = []
    batch_size = options.delete(:batch_size) || DEFAULT_BATCH_SIZE

    CSV.foreach(file_path, options).with_index(1) do |row, index|
      rows << { "id" => index }.merge!(row)
      if rows.length == batch_size
        yield(rows) if block_given?
        rows = []
      end
    end
    yield(rows) if block_given? && rows.size.positive?
    true
  end
end

[Info] - Deploy Rails to Heroku

Source: https://devcenter.heroku.com/articles/getting-started-with-rails5#add-the-pg-gem

Install The Heroku CLI on macOX
brew tap heroku/brew && brew install heroku

Install The Heroku CLI on Ubuntu
sudo snap install --classic heroku

Log in using your Heroku account’s email address and password:
heroku login

Create an app on Heroku
heroku create

After created rails app, cd to the direction of the app:

git init
git add .
git commit -m "init"
git push heroku master

Visit your application

heroku ps:scale web=1
heroku ps
heroku open
heroku logs
heroku logs --tail
heroku run rails console
heroku run rake db:migrate

[Info]-Install mysql and gem mysql2 on Mac

1. Install mysql using Homebrew

  • To install Homebrew, open Terminal and run:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
  • Then install MySQL using Homebrew:
brew install mysql
  • Install brew services:
brew tap homebrew/services

  • Load and start the MySQL service:
brew services start mysql

  • Open Terminal and execute the following command to set the root password:
mysqladmin -u root password 'yourpassword'

2. Install gem mysql2

gem install mysql2

If have error:

checking for ruby/thread.h... yes
checking for rb_thread_call_without_gvl() in ruby/thread.h... yes
checking for rb_thread_blocking_region()... no
checking for rb_wait_for_single_fd()... yes
checking for rb_hash_dup()... yes
checking for rb_intern3()... yes
-----
Using mysql_config at /usr/local/bin/mysql_config
-----
checking for mysql.h... yes
checking for errmsg.h... yes
checking for mysqld_error.h... yes
-----
Setting rpath to /usr/local/Cellar/mysql/8.0.17/lib
-----
creating Makefile

current directory: /Users/brian_pham/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/mysql2-0.4.4/ext/mysql2
make "DESTDIR=" clean

current directory: /Users/brian_pham/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/mysql2-0.4.4/ext/mysql2
make "DESTDIR="
compiling infile.c
In file included from infile.c:1:
In file included from ./mysql2_ext.h:41:
./result.h:24:3: error: unknown type name 'my_bool'
  my_bool *is_null;
  ^
./result.h:25:3: error: unknown type name 'my_bool'
  my_bool *error;
  ^
2 errors generated.
make: *** [infile.o] Error 1

make failed, exit code 2

Just add

-- --srcdir=/usr/local/mysql/include

[Info] How to import and export a PostgreSQL database

  1. EXPORT A POSTGRESQL DATABASE
- Access the command line on the computer where the database is stored
pg_dump -U username dbname > dbexport.pgsql
  1. IMPORT A POSTGRESQL DATABASE
- Transfer the dbexport.pgsql file to your A2 Hosting account using SCP, SFTP, or FTP.
psql -U username dbname < dbexport.pgsql

[Info] Install libxml-ruby -v '2.8.0' on Mac

gem install libxml-ruby -v '2.8.0' -- --with-xml2-config=/usr/local/opt/libxml2/bin/xml2-config --with-xml2-dir=/usr/local/opt/libxml2 --with-xml2-lib=/usr/local/opt/libxml2/lib --with-xml2-include=/usr/local/opt/libxml2/include

[Info] - Uninstall and Install Solr

stop existing running solr

sudo service solr stop

check status

sudo service solr status

now remove existing solr from centos

sudo rm -r /var/solr

remove solr from following location if its there

sudo rm -r /opt/solr
sudo rm /etc/init.d/solr

Check which version Java version is installed on your machine

java -version

Check available java versions, and update to latest version

yum list available java*

Install latest java version

sudo yum install <jdk version>

Download and install Solr - change version which you need

cd /tmp
wget http://www-eu.apache.org/dist/lucene/solr/8.5.2/solr-8.5.2.tgz
wget https://archive.apache.org/dist/lucene/solr/5.5.4//solr-5.5.4.tgz
tar xzf solr-8.5.2.tgz solr-8.5.2/bin/install_solr_service.sh --strip-components=2

sudo bash ./install_solr_service.sh solr-8.5.2.tgz

command using

sudo service solr stop
sudo service solr start
sudo service solr status

Create core

sudo su - solr -c "/usr/local/solr/bin/solr create -c mycol1 -n data_driven_schema_configs"

Delete core

/opt/solr/bin/solr delete -c mycol1

[Info] - Add ssh-key to multi host server using Ansible

Step 1 - Installing Ansible

sudo apt update
sudo apt install ansible

Step 2 - Setting Up the Inventory File

sudo vi /etc/ansible/hosts
  • Add server host
[servers]
server1 ansible_host=203.0.113.111
server2 ansible_host=203.0.113.112
server3 ansible_host=203.0.113.113
  • Whenever you want to check your inventory, you can run:
ansible-inventory --list -y

Step 3 - Testing Connection

ansible all -m ping -u user_name

Step 4 - Ansible Playbook: Deploy the public key to remote hosts

  • Create file deploy_authorized_keys.yml
---
- hosts: all
  tasks:
  - name: Add public key
    lineinfile:
      path: "/home/user_name/.ssh/authorized_keys"
      line: "{{ pubkey }}"
  • Run command line
ansible-playbook -u user_name deploy_authorized_keys.yml --extra-vars='pubkey="<pubkey>"'

[Info] - Git Juggling Commits

We will overcome this difficulty by doing the following:

-We will re-order the commits so the one we want to change is on top with git rebase -i
-We will commit --amend to make the slight modification
-Then we will re-order the commits back to how they were previously with git rebase -i
-Finally, we will move master to this updated part of the tree to finish the level (via the method of your choosing)

[Issue] Install gem on Mac Mojave

xcode-select --install
sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /

[Info] Fixing cron jobs in MacOS

  • Find where cron path:
which cron
  • Go to System Preferences > Security & Privacy > Privacy > Full Disk Access
  • Click on the (+) icon to add an item to the list
  • Press command+shift+G to open the Go to Folder… dialog, type cron_path and press Enter:
  • Select the cron file and click Open:

[Info] - Install Ruby < 2.4 with openssl 1.0

  • Install Ruby 1.8.7-p371
RUBY_CONFIGURE_OPTS="--with-openssl-dir=/usr/local/openssl-1.0.2h/bin/openssl" rbenv install 1.8.7-p371
or
RUBY_CONFIGURE_OPTS="--with-openssl-dir=/usr/local/openssl-1.0.2h/ssl" rbenv install 1.8.7-p371

  • Install gem:
gem update --system 1.3.7
gem install bundler -v 1.13.6

[Rails] - db migrate

db:migrate runs (single) migrations that have not run yet.

db:create creates the database

db:drop deletes the database

db:schema:load creates tables and columns within the existing database following schema.rb. This will delete existing data.

db:setup does db:create, db:schema:load, db:seed

db:reset does db:drop, db:setup

db:migrate:reset does db:drop, db:create, db:migrate

For rails 3.2.12:

db:create creates the database for the current env

db:create:all creates the databases for all envs

db:drop drops the database for the current env

db:drop:all drops the databases for all envs

db:migrate runs migrations for the current env that have not run yet

db:migrate:up runs one specific migration

db:migrate:down rolls back one specific migration

db:migrate:status shows current migration status

db:rollback rolls back the last migration

db:forward advances the current schema version to the next one

db:seed (only) runs the db/seed.rb file

db:schema:load loads the schema into the current env's database

db:schema:dump dumps the current env's schema (and seems to create the db as well)

db:setup runs db:create db:schema:load db:seed

db:reset runs db:drop db:setup

db:migrate:redo runs (db:migrate:down db:migrate:up) or (db:rollback db:migrate) depending on the specified migration

db:migrate:reset runs db:drop db:create db:migrate

[git] - Create commit message template

Create Commit Message Template

  • Create file .gitmessage in the home directory
# Title: Summary, imperative, startupper case, don't end with a period
# No more than 50 chars. #### 50 chars is here:  #

# Remember the blank line between the title and the body.

# Body: Explain *what* and *why* (not *how*). Include task ID (Jira issue).
# Wrap at 72 chars. ################################## which is here:  #


# At the end: Include Co-authored-by for all contributors. 
# Include at least one empty line before it. Format: 
# Co-authored-by: name <[email protected]>
#
# How to Write a Git Commit Message:
# https://chris.beams.io/posts/git-commit/
#
# 1. Separate the subject from the body with a blank line
# 2. Limit the subject line to 50 characters
# 3. Capitalize the subject line
# 4. Do not end the subject line with a period
# 5. Use the imperative mood in the subject line
# 6. Wrap the body at 72 characters
# 7. Use the body to explain what and why vs. how
  • Git Configuration
git config --global commit.template ~/.gitmessage

[Info] - Convert csv to yml file

require 'csv'
table = CSV.table('file_name.csv')
transformed_into_hash = table.map { |row| row.to_hash }
File.open("file_name.yaml", "w") do |f|
  f.puts transformed_into_hash.to_yaml
end

[Info] - 5 Git workflow best practices

1. Rebase Git workflow

git checkout master
git pull #Make sure master is up to date

git checkout feature-branch
git rebase master
#If you encounter a merge issue
git mergetool
git rebase --continue
git rebase --abort
git push -f

2. git add -p

When you’re working on a local feature branch, do you sometimes want to pick out code changes you want to commit, but leave other changes uncommitted? With the git add -p  command, that’s exactly what you can do.

3. Keeping your branches tidy
Rename branch

git branch -m oldName newName
git branch -m newName #Current branch

Delete old local branches

git branch -d branchName

4. Git reset-hard

git reset --hard # removes staged and working directory changes

## !! be very careful with these !!
## you may end up deleting what you don't want to
## read comments and manual.
git clean -f -d # remove untracked
git clean -f -x -d # CAUTION: as above but removes ignored files like config.
git clean -fxd :/ # CAUTION: as above, but cleans untracked and ignored files through the entire repo (without :/, the operation affects only the current directory)

5. Escape greater than symbols

[Info] - Slim template in Rails

  1. Install
gem 'slim-rails'
gem 'html2slim' # Convert html to slim

bundle install

Convert all file in views folder to slim

erb2slim app/views --delete
  1. Add pry debug in rails:
gem 'pry-rails'
gem 'pry-nav'
gem 'pry-stack_explorer'

bundle install

[Info] - MySQL export and import database

  1. Export
mysqldump -u user -p pass database_name table_name > table_file_name.sql
  1. Import
docker exec -i docker-container_id mysql -u -p123456 database_name < table_name_file.sql

[Info] - Convert TSV file to YML file

require 'yaml'

namespace :tsv_to_yml do
  desc 'Convert TSV file to YML file'
  task call: :environment do
    if ARGV[1].nil?
      print 'Insert the name of your output file (yml file) '
      out_name = $stdin.gets.chomp
    else
      out_name = ARGV[1]
    end

    file_path = "#{Rails.root}/#{out_name}.tsv"
    logger = Logger.new "#{Rails.root}/log/convert-#{out_name}.log"

    options = { headers: true, liberal_parsing: true, encoding: Encoding::SHIFT_JIS, col_sep: "\t" }
    SmartCsv.batch_read(file_path, options) do |rows|
      data = rows.map(&:to_h)
      File.open("#{Rails.root}/data/master/#{out_name}.yml", "a") do |f|
        f.puts data.to_yaml.gsub("---\n", '')
      end
    end
  end
end

[Info] - Git Working Command

  1. Git Commit amend
git commit --amend -m
git push --force origin
  1. Git merge commit into one
git log
git reset HEAD~point_to_merge (checking in the log to get point_to_merge)
git push --force origin
  1. Git merge
git checkout feature
git merge master

or

git merge master feature
  1. Git rebase
git checkout feature
git rebase master

git rebase -i master

[Info] - Config SSH

Config SSH Proxy

Host [Name]
Hostname [IP]
User [username]
Port [port]
IdentityFile [id_rsa file path]
IdentitiesOnly yes

Config SSH via Proxy

Host [name]
Hostname [IP]
User [username]
IdentityFile [id_rsa file path]
IdentitiesOnly yes
ProxyCommand ssh [proxy name] -W %h:%p
ForwardAgent yes

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.