Showing posts from 2019

Data Scrapping in rails

go to your terminal create a directory mkdir ruby_data_scrapping create directory mkdir lib cd lib/ touch scraper.rb gem install nokogiri  // install gems in local gem install httparty gem install byebug Write code in your scraper.rb require "httparty" require "nokogiri" require "byebug" class Scraper   attr_accessor :parse_page   def initialize       doc = HTTParty.get("")       @parse_page ||= Nokogiri::HTML(doc)   end   def get_prices      item_container.first(2){|x| x.text}   end   private     def item_container        parse_page.css(".tv-data-table__tbody").first.css(".tv-screener-table__result-row").css(".tv-screener-table__cell")     end   prices =   (0...prices.size).each do |index|       puts "Price: #{prices[index]}"   end end now run this scraper ruby scraper.rb

rails scope with argument or dynamic value and join tables

scope :get_by_currency, -> (currency) {find_by(currency_id: currency)} scope :by_role, ->(role) { joins(:roles).where(roles: { name: role }) } //it will work in rails 4 and previous version scope :by_role, ->(role) { joins(:roles).where(' ? ', #{role} ) } //it will work in all versions of rails validate  :validate_mimimum_amount, unless: -> (order) { order.ord_type=='market' || order.ord_type=='manual' }

some minor things in rails

For Date format  .utc.strftime('%d-%m-%Y %H:%M:%S') Alternative to html_safe (raw("<strong class='text-danger'>Decline</strong")). select tag for form_for  <%=, options_for_select({|x|}, f.object.payment_currency), {include_blank: "Select Currency"}, { :class => 'form-control', required: true }) %> zip -r folder_name

Convert numbers in rails like binary to decimal

value.to_i(from).to_s(to) i.e "1000".to_i(2).to_s(10) //here we are converting binary to decimal

decimal to binary converter in rails

def dec2bin(number)     number = Integer(number) //number that you have to convert     if(number == 0) then 0 end              new_num = ""     while(number != 0)         new_num = String(number % 2) + new_num         number = number / 2     end     new_num // return new number end

Authentication via JWT in rails api's

gem 'jwt' add this gem to your gem file bundle install create a file in lib/json_web_token.rb and paste following code class JsonWebToken      SECRET_KEY = Rails.application.secrets.secret_key_base. to_s      def self.encode(payload, exp = 15.days.from_now)         payload[:exp] = exp.to_i        JWT.encode(payload, SECRET_KEY)      end     def self.decode(token)        decoded = JWT.decode(token, SECRET_KEY)[0] decoded     end end create another file config/initializers/jwt.rb and paste following code require 'json_web_token' Now inside controller/api/v1/ we will a parent class for our all end-points: api/v1/api_controller.rb class Api::V1::ApiController < ActionController::Base      protect_from_forgery with: :null_session      def autheticate_user         header = request.headers['Authorization']         header = header.split(' ').last if header         begin             @decoded = JsonWebToken.decode

How to use switch case in angular view

      <div ng-switch =" varible_name ">           <div ng-switch-when ="value1"><p>{{ value1}}</p></div>           <div ng-switch-when ="value2"><p>{{ value2 }}</p></div>           <div ng-switch-when ="value3"><p>{{ value3 }}</p></div>           <div ng-switch-when ="value4"><p>{{ value4}}</p></div>           <div ng-switch-default >...</div>       </div>

best way to compile your assets in rails

rake assets:precompile tmp:clear

OpenSSL SSL_read: SSL_ERROR_SYSCALL in windows

 OpenSSL SSL_read: SSL_ERROR_SYSCALL Open your terminal/command prompt   GIT_CURL_VERBOSE=1 your_command_here I.E:- if you want to take pull from master branch then   GIT_CURL_VERBOSE=1 git pull origin master

How to exit vim editor in Ubuntu || How to set default editor Ubuntu

Set Default editor in ubuntu sudo update-alternatives --config editor Type 2 and hit enter nano will be set as default editor

How to run local gems in rails || How to override gem's in rails

Create new gem in your rails app Standard is local gems are kept in Vendor folders Give path in your Gemfile EX: path 'vendor/local_gems' do #this is your gem folder   gem 'countries'  #your local gem name   gem 'country_select' # your another local gem end run bundle install

Write simple html text in into rails tags

You can write simple text inside rails tag like link_to button_tag, submit_tag, text_field_tag etc.. (raw("<strong class='text-danger'>Decline</strong")) example : <%= link_to  (raw("<strong class='text-danger'>Decline</strong")), welcome_path %>

Amazing websites on internet

infinite zoom website Real time hacking attacks Point anywhere in the screen, you will get pointed images after some seconds

Download Sacred games 2

Download Sacred Games Season-2 all episode Click here to Download Episode-1 Click here to Download Episode-2 Click here to Download Episode-3 Click here to Download Episode-4 Click here to Download Episode-5 Click here to Download Episode-6 Click here to Download Episode-7 Click here to Download Episode-8

Download delhi crimes season-1

Clear Here to Download Season-1

Lg q6 full specification and camera shots

NETWORK Technology   GSM / HSPA / LTE LAUNCH   Announced 2017, July Status   Available. Released 2017, August BODY   Dimensions   142.5 x 69.3 x 8.1 mm (5.61 x 2.73 x 0.32 in) Weight   149 g (5.26 oz) Build Front glass, aluminum frame, plastic body SIM Single SIM (Nano-SIM) or Dual SIM (Nano-SIM, dual stand-by)   MIL-STD-810G compliant DISPLAY Type   IPS LCD capacitive touchscreen, 16M colors Size   5.5 inches, 77.0 cm2 (~78.0% screen-to-body ratio) Resolution   1080 x 2160 pixels, 18:9 ratio (~442 ppi density) Protection   Corning Gorilla Glass 3 PLATFORM   OS   Android 7.1.1 (Nougat), upgradable  to Android 8.0 (Oreo); LG UI 5.0 Chipset Qualcomm MSM8940 Snapdragon 435 (28 nm) CPU Octa-core 1.4 GHz Cortex-A53 GPU Adreno 505 MEMORY   Card slot microSD, up to 256 GB (dedicated slot) Internal   64GB, 4GB RAM - Q6+               32GB, 3GB RAM - Q6              16GB, 2GB RAM - Q6α MAIN CAMERA Single   13 MP, f/2.2, 1/3", 1.12µm, AF Features   LED flash,

Get Height and Width of Image when upload

<script type="text/javascript">  var _URL = window.URL || window.webkitURL;  $('#structure_product_image').on('change', function() { //pass here file field id    var image, file;    if ((file = this.files[0])) {      image = new Image();      image.onload = function() {        $("#error_message").text("");        if (this.width <= 700) {          $("#error_message").text("Width should be greater than 700 pixel!") //id where you want to display text        }        else if (this.height <= 600){          $("#error_message").text("Height should be greater than 600 pixel!")        }        else if (this.height >= this.width){          $("#error_message").text("Height should not be greater than Width")        }        if($("#error_message").text() == ""){          $("#save_product").prop("disabled" , false)      

Place to share your Article Content Blog

1. Medium Medium allows you to share or publish your content and article 2. Reddit Reddit can be a worthwhile platform to consider for sharing content, but it needs to be done the right way 3. LinkedIn Articles LinkedIn also allow you share your content. Try LinkedIn Learing 4. DesignFloat An online discussion board for designers to share articles, element ideas, and more. 5. Twitter Here is a another best way to share your Blog or content to Twitter. You can also share your content into specific twitter community of that content

how to make separate routes for different user in rails

how to make separate routes for different user in rails  Make another routes file in your config folder           config/routes/admin.rb   //i made new file routes/admin.rb inside config folder Now inside your config/routes.rb file paste this           class ActionDispatch::Routing::Mapper             def draw(routes_name)              instance_eval("config/routes/#{routes_name}.rb")))             end           end        // paste this code above this Rails.application.routes.draw line now side your main route file(config/routes.rb) make new routes for admin file like draw :admin Now config/routes.rb will be look like this Rails.application.routes.draw do   draw :admin end Now you can make routes for admin or admin dashboard separately inside your config/routes/admin.rb file resources :admin

install wine in ubuntu

Step 1 – Setup PPA sudo dpkg --add-architecture i386 wget -qO - | sudo apt-key add - ###  Ubuntu 18.10  sudo apt-add-repository 'deb cosmic main' ###  Ubuntu 18.04  sudo apt-add-repository 'deb bionic main' ###  Ubuntu 16.04  sudo apt-add-repository 'deb xenial main' Step 2 – Install Wine on Ubuntu sudo apt-get update sudo apt-get install --install-recommends winehq-stable sudo apt-get install aptitude sudo aptitude install winehq-stable Step 3 – Check Wine Version wine --version wine-4.0 How to Use Wine (Optional)? wine full_file_full_specified_name.exe

ActiveRecord::Base.connection.execute, robust record execute in rails

ActiveRecord::Base.transaction do          ActiveRecord::Base.connection.execute("UPDATE deposits SET amount = #{params[:adjust_amount].to_f} WHERE type = '#{@deposit.type}' AND id = #{} AND currency_id = '#{@deposit.currency_id}'").as_json if params[:adjust_amount].present?          ## update comment          if params[:mt5_history_id].present?            mt5_withdraw_history = Mt5History.find_by_id(params[:mt5_history_id])            mt5_withdraw_history.update(comment: params[:comment])          end        end This do loop will run until all parameter will execute if any record updatation is failed due to some reason all previous record update will be rollback!   

Wicked-PDF not showing images, 'wicked_pdf_image_tag' undefined

Wicked-PDF not showing images, 'wicked_pdf_image_tag' undefined <div>   <%= wicked_pdf_image_tag 'logo.jpg' %> </div> def save   pdf =                         render_to_string(                           template: 'example/pdf_view.pdf.erb',                           layout: 'layouts/application.pdf.erb'))   send_data(pdf,             filename: 'file_name.pdf',             type: 'application/pdf',             disposition: 'attachment')  end 

Download pdf by ajax or javascript or angular js

Click on button for generate pdf  $("#print_selected_label").on("click", function(){    data = []    $("input:checkbox.print_label:checked").each(function(){      data.push($(this).attr("id"));    });   //getting all information of checked checkbox    if(data.length > 0){    // if data is not null       In angular js controller         // var redirect_new = "/admin/v2/orders/print_multiple_label.pdf?" + jQuery.param(data);        // var pdf =, 'Map PDF', '');      By Creating a link by javascript       // var mydiv = document.getElementById("download_pdf");      // var aTag = document.createElement('a');      // var link = " admin/v2/orders/print_multiple_label.pdf?id="+data ;      // aTag.setAttribute('href',link);      // aTag.innerHTML = "link text";      // mydiv.appendChild(aTag);      //; By making http request    

Create worker in rails by sidekiq and redis

Add sidekiq to your Gemfile: Add this to your Gemfile gem 'sidekiq' Run bundle install bundle install Create worker rails g sidekiq:worker Test #will create app/workers/test_worker.rb class TestWorker   include Sidekiq::Worker   def perform(id, name)     # do something   end end Call worker without any time boundation TestWorker.perform_async(5, 'rahul') //use this anywhere from your rails app(controller, model, helpers..) Call worker within particular time period TestWorker.perform_in(5.minutes, 5, 'rahul')  //use this anywhere from your rails app(controller, model, helpers..) Call worker after specific time interval once only TestWorker.perform_at(5.minutes.from_now, 5, 'rahul')  //use this anywhere from your rails app(controller, model, helpers..) Start sidekiq on development bundle exec sidekiq Start sidekiq on production bundle exec sidekiq -d //run this first if you get some error then use second one bundle exec si

css for iso device or ipad or safari browser and media query

@supports (-webkit-overflow-scrolling: touch) {   /* CSS specific to iOS devices */  } @supports not (-webkit-overflow-scrolling: touch) {   /* CSS for other than iOS devices */  } For example: @media only screen and (device-width: 768px) {         /* default iPad screens */     }     /* different techniques for iPad screening */     @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {       /* For portrait layouts only */     }     @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {       /* For landscape layouts only */     } HTML <div class="scroll-touch">   <p>     This paragraph has momentum scrolling   </p> </div> <div class="scroll-auto">   <p>     This paragraph does not.   </p> </div> div {   width: 100%;   overflow: auto; } p