Tuesday, 13 December 2016

N level looping in logic

Create Table : Menu : id,name,parent_id

    function parseTree($menu, $root = null) {
        $return = array();
        # Traverse the tree and search for direct children of the root
        foreach($menu as $child => $parent) {
            # A direct child is found
            if($parent->parent_id == $root) {
                # Remove item from tree (we don't need to traverse this again)
                unset($menu[$child]);
                # Append the child into result array and parse its children
                $return[] = array(
                    'name' => $parent,
                    'children' => $this->parseTree($menu, $child)
                );
            }
        }
        return empty($return) ? null : $return;
    }

    function printParent($tree){
        if(!is_null($tree) && count($tree) > 0) {
            echo '<ul>';
            foreach($tree as $node) {
//                print_r($node);exit;
                echo '<li>'.$node['name']['name'];
                $this->printParent($node['children']);
                echo '</li>';
            }
            echo '</ul>';
        }

    }



OR=======================


public function index()
    {
        $allMenu = Menu::all();
        $childe_parent_menu_list = array();

        foreach($allMenu as $menu){
            $childe_parent_menu_list[$menu->id] = $menu;
        }
        $menu_tree = array();

        $menu_tree = $this->parseTree($childe_parent_menu_list);
        $html_view = '';
        $html_view = $this->printParent($menu_tree,$html_view);

        return view('Menu.index',array('menus'=>$allMenu,'menu_tree'=>$html_view));

    }

    function parseTree($menu, $root = null) {
        $return = array();
        # Traverse the tree and search for direct children of the root
        foreach($menu as $child => $parent) {
            # A direct child is found
            if($parent->parent_id == $root) {
                # Remove item from tree (we don't need to traverse this again)
                unset($menu[$child]);
                # Append the child into result array and parse its children
                $return[] = array(
                    'name' => $parent,
                    'children' => $this->parseTree($menu, $child)
                );
            }
        }
        return empty($return) ? null : $return;
    }

    function printParent($tree,$html_view=NULL){
        $html_view = '';
        if(!is_null($tree) && count($tree) > 0) {
            $html_view .= '<ul>';
            foreach($tree as $node) {
//                print_r($node);exit;
                $html_view .= '<li>'.$node['name']['name'];
                $html_view .=$this->printParent($node['children'],$html_view);
                $html_view .= '</li>';
            }
            $html_view .= '</ul>';
        }
        //print_r( $html_view);exit;
      return $html_view;
    }
 

Friday, 9 December 2016

Create every day log file in rails

 /etc/logrotate.conf

                                   OR

I try down one but i face issue when starting serve :

http://blog.teksol.info/2007/06/13/how-to-set-logger-options-in-rails


Today, I was replacing RailsCron and BackgrounDRb with generated Daemons, and I happened to investigate how Rails sets up it’s logger. For the longest time, I knew it was possible to change the options, but I just never investigated how to do it. I thought I’d share my findings so others won’t be in the dark as I was.
Actually doing the replacement is very easy:
config/environment.rb
1 Rails::Initializer.run do |config|
2   config.logger = Logger.new(File.dirname(__FILE__) + "/../log/#{RAILS_ENV}.log")
3 end

That’s it. Have fun. Stop reading… Unless you want more details.
This is essentially what Rails does, except now you have complete control over how theLogger is instantiated.
Some options you might want to investigate:
1 # Keep at most 2 2 megabytes log files
2 config.logger = Logger.new(File.dirname(__FILE__) + "/../log/#{RAILS_ENV}.log", 2, 2*1024*1024)
3 
4 # Create a new log file each day
5 config.logger = Logger.new(File.dirname(__FILE__) + "/../log/#{RAILS_ENV}.log", "daily")

If you are running a script which loads the Rails environment manually, you can also do this:
lib/daemons/futures_worker.rb
 1 #!/usr/bin/env ruby
 2 
 3 # You might want to change this
 4 raise "No RAILS_ENV defined" if ENV["RAILS_ENV"].to_s.empty?
 5 
 6 require "logger"
 7 
 8 RAILS_DEFAULT_LOGGER = Logger.new(File.dirname(__FILE__) + "/../../log/futures_runner.rb.log", 3, 2*1024*1024)
 9 require File.dirname(__FILE__) + "/../../config/environment"
10 
11 # Other code as appropriate

The Rails::Initializer is smart enough to use either the RAILS_DEFAULT_LOGGER or the one defined in the configuration block. For the gory details, please read Rails::Initializer#initialize_logger

Monday, 5 December 2016

Drag and Drop HTML 5 with Orignal or with copy

JAVASCRIPT FUNCTIONS :
 
 
function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  //ev.dataTransfer.setData("text", ev.target.id);  DI.trip_id = $(this).attr('trip_id');
  DI.drag_id = ev.target.id;
}


//Drop with originalfunction drop_original(ev) {
  ev.preventDefault();
  var data_id = DI.drag_id;
  var elm_id = ev.target.id;
  ev.target.appendChild(document.getElementById(DI.drag_id));
  //$("#"+elm_id).find('.time-slot-detail').append(document.getElementById(data));}
 
 
 
//Drop with copyfunction drop_copy(ev) {
  ev.preventDefault();
  var data=ev.dataTransfer.getData("text/html");
  /* If you use DOM manipulation functions, their default behaviour it not to   copy but to alter and move elements. By appending a ".cloneNode(true)",   you will not move the original element, but create a copy. */  var nodeCopy = document.getElementById(DI.drag_id).cloneNode(true);
  nodeCopy.id = "newId"; /* We cannot use the same ID */  ev.target.appendChild(nodeCopy);
} 
 
http://stackoverflow.com/questions/13007582/html5-drag-and-copy 
 

HTML==================>

 

 

<body>

<p>Drag the W3Schools image into the rectangle:</p>

<div id="div1" ondrop="drop_copy(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">

</body>

Friday, 2 December 2016

Rails check url exist or check image exist on following url ruby on rails

http://stackoverflow.com/questions/5908017/check-if-url-exists-in-ruby



require "net/http"

def url_exist?(url_string)
  url = URI.parse(url_string)
  req = Net::HTTP.new(url.host, url.port)
  req.use_ssl = (url.scheme == 'https')
  path = url.path if url.path.present?
  res = req.request_head(path || '/')
  if res.kind_of?(Net::HTTPRedirection)
    url_exist?(res['location']) # Go after any redirect and make sure you can access the redirected URL  else    ! %W(4 5).include?(res.code[0]) # Not from 4xx or 5xx families  endrescue Errno::ENOENT  false #false if can't find the serverend

def url_exist_second?(url)
  uri = URI(url)

  request = Net::HTTP.new uri.host
  response= request.request_head uri.path
  return response.code.to_i == 200end
=========================================
Calling Helper  function :
url_exist?("url_string")
 
 
 
 ===================================Second Solution and better one==============================
File.file?(Url_string) 

Wednesday, 23 November 2016

Rails New Project

http://rakeroutes.com/blog/rvm-workflow-for-a-new-rails-app/


Creating a new Rails app

# create and use the new RVM gemset
$ rvm use --create 1.9.3@awesome_rails_project

# install rails into the blank gemset
$ gem install rails

# generate the new rails project
$ rails new awesome_rails_project

# go into the new project directory and create an .rvmrc for the gemset
$ cd awesome_rails_project
$ rvm --rvmrc 1.9.3@awesome_rails_project

# verify the rvmrc
$ cd ..; cd -

Friday, 21 October 2016

Email validation in rails and javascript by rejex

 

RAILS EMAIL VALIDATION ===>

 
# email = email.split(" ").join('')
email = "rajpurohitnitin7@gmail.com"email = email.delete(' ')
if !/\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/.match(email).nil?
    p "valid email address"
end



JAVASCRIPT EMAIL VALIDATION ===>

 
 
var email = "rajpurohitnitin7@gmail.com" 
var re = /\S+@\S+\.\S+/var valid = re.test(email_address)if (!valid) {
 
   console.log("valid email addresss"); 
}




Tokenfield Email validation ====>

 
 
  $(".token_filed_class").on('tokenfield:edittoken', function (e) {  }).on('tokenfield:createdtoken', function (e) {         var re = /\S+@\S+\.\S+/         var valid = re.test(e.attrs.value)         if (!valid) {            $(e.relatedTarget).empty().hide().attr('data-value', '');            //$(".share_with_emails").on('tokenfield:removedtoken', function (e) {})           //$(e.relatedTarget).addClass('invalid')         }  }).on('tokenfield:removedtoken', function (e) {  }),  showAutocompleteOnFocus: false,  createTokensOnBlur:true}); 

Monday, 10 October 2016

Upload Image from URL OR Convert Image URL into base 64 by Javascript

function getBase64ImageFromUrl(image_url){      var canvas = document.createElement("canvas");      var ctx = canvas.getContext("2d");      var img = new Image();      img.src = image_url;      canvas.width = img.width;      canvas.height = img.height;      ctx.drawImage(img, 0, 0);      var data = canvas.toDataURL("image/jpeg");
      return data;

}

OR
 
 
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    var img = new Image();
    img.onload = function () {
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);
        var data = canvas.toDataURL("image/jpeg");
        alert(data);
    };
    img.src = "http://localhost/MvcApplication3/test.png"; 
 
 
 
OR 
 
 
 function getBase64ImageFromUrl(image_url){ 
  var canvas = document.createElement("canvas"); 
  var ctx = canvas.getContext("2d"); 
  var img = new Image();  img.src = image_url; 
  canvas.width = img.width; 
  canvas.height = img.height; 
  ctx.drawImage(img, 0, 0); 
  var data = canvas.toDataURL("image/jpeg"); 
  return data;}
 
imgObj = $(this).parent().find('img');img = getBase64ImageFromUrl(imgObj[0].src)
 function getBase64ImageFromUrl(image_url){  var canvas = document.createElement("canvas");  var ctx = canvas.getContext("2d");  var img = new Image();  img.src = image_url;  canvas.width = img.width;  canvas.height = img.height;  ctx.drawImage(img, 0, 0);  var data = canvas.toDataURL("image/jpeg");  return data;}