Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 102 total  RSS 

Open an arbitrary number of resources safely in ruby

I'm too lazy to work out what happens if I try
filenames.map {|f| File.open(f) }
and the thirteenth file doesnt exist, but I bet I don't like it.

module Enumerable
  # Example:
  # ['a','b'].with_files {|f,g| ... }
  # is the same as
  # File.open('a') {|f| File.open('b') {|g| ... } }
  # You can specify modes with
  # [['a', 'rb'], ['b', 'w']].with_files ...
  def with_files(
      meth = File.method(:open),
      offset=0,
      inplace=false,
      &block
  )
    if inplace then
      if offset >= length then
        yield self
      else
        fname,mode = *self[offset]
        File.open(fname,mode) {|f| 
          self[offset] = f
          self.with_files(meth,offset+1,true,&block)
        }
      end
    else
      dup.with_files(meth,offset,true,&block)
    end
  end
end

Array#pad!

My ri docco says there is an Array#pad! but runtime Ruby says there isn't. Bah. So I wrote one:

class Array
  def pad!(expected_length, pad_item = nil)
    while expected_length > length
      self << pad_item
    end
    self
  end
end

Concat two array

var sNames:Array = ["Rajesh","Buvanesh","Latha","Ramesh"];
var sPhones:Array = ["9940350708","00000000","044-42151184","9841026070"];

for (var i=0;i<sNames.length;i++){
trace(sNames[i]);
trace(sPhones[i]);
}

Array.push

var sEmployees:Array = [];
sEmployees.push(["Ramesh","9841026070"]);
sEmployees.push(["Rajesh","9940350708"]);
sEmployees.push(["Latha","044-42151184"]);
sEmployees.push(["Buvanesh","000-0000000"]);

for (var i:Number=0; i<sEmployees.length; i++){
trace("Name:" + sEmployees[i][0]);
trace("Phone:" + sEmployees[i][1]);
}

String to Array

var sEmployees:String = "Rajesh,Buvanesh,Latha,Ramesh";
var aEmployees:Array = sEmployees.split(",");
trace(aEmployees.toString());

Converting Arrays to Lists

var aEmployees:Array = ["Rajesh","Buvanesh","Latha","Ramesh"];
var sEmployees:String = aEmployees.join(";");
trace(sEmployees);

Working with Arrays of Objects

var sEmployees:Array = [];
sEmployees.push({employee:"Ramesh", phone:"9841026070"});
sEmployees.push({employee:"Rajesh", phone:"9940350708"});
sEmployees.push({employee:"Latha", phone:"044-42151184"});
sEmployees.push({employee:"Buvanesh", phone:"000-0000000"});

for (var i:Number=0; i<sEmployees.length; i++){
trace("Name:" + sEmployees[i].employee);
trace("Phone:" + sEmployees[i].phone);
}

In-place map_with_index

// This code is similar to Enumerable#map, but like each_with_index, it also yields the index of the current element.

class Array
    def map_with_index!
       each_with_index do |e, idx| self[idx] = yield(e, idx); end
    end

    def map_with_index(&block)
        dup.map_with_index!(&block)
    end
end

Encode simple passwords

This code was used to demonstrate how to translate easy to remember simple (weak) passwords into more difficult to guess (strong) passwords. Example: Using Gmail I like an easy to remember password, I submit the password 'jr123' to the password_lookup.html page and what's returned to me is a stronger password 'NCC2SI1T'.

file: passwd_lookup.rb (generates an xml file containing an alphanumeric index with corresponding cryptic values)
class PasswordLookup

  def initialize()
    chars =  (0..9).to_a  + Array.new(7) + ('A'..'Z').to_a + Array.new(6) + ('a'..'z').to_a 
    @chars = (0..9).to_a  + ('A'..'Z').to_a + ('a'..'z').to_a 
    @doc = Document.new()
    root = Element.new('codes')
    @doc.add_element(root)

    chars.each do |char|
      node = Element.new('code')
      if not char.nil? 
        node.attributes['index'] = char
        node.attributes['value'] = get_random_chars(2)
      end
      root.add_element(node)
    end
    puts root
  end

  
  def save(filepath)
    file = File.new(filepath,'w')
    file.puts @doc
    file.close
  end
        
  def get_random_chars(vword_size)
    newpass = Array.new(rand(vword_size) + 1, '').collect{@chars[rand(@chars.size)]}.join
    # return the encryption providing it doesn't already exist in the lookup table.
    if not /value=\'#{newpass}\'/.match @doc.root.elements.to_a.to_s 
     return newpass 
    else
     return get_random_chars(vword_size) 
    end

  end
  
  private :get_random_chars
  
end


output extract: (codes - see also http://rorbuilder.info/pl/codes)
<codes>
<code value='4h' index='a'/><code value='B' index='b'/><code value='m' index='c'/>
<code value='qf' index='d'/>
</codes>


file: password_lookup.js
var t;
var m_doc;

function loadXml() {
  url = 'http://rorbuilder.info/pl/codes';
  m_doc = XML.load(url);
}

function getCode(val,i) {
  pos = val.charCodeAt(i) - 48;
  node = m_doc.documentElement.childNodes[pos]
  return node.getAttribute('value');
}

function timed_update(keyCode,  val) {
  if (val.length > 0 && ((keyCode > 40) || (keyCode == 8)) ) {
    clearTimeout(t);
    t = setTimeout("revealCode('" + val + "')", 1000);
  }
  else
  {  
    o = document.getElementById('out1');
    if (val.length <= 0 && o.value.length > 0) {
      o.value = '';
    }
  }
  
}

function revealCode(val) {
  var iEnd = val.length;
  var newcode = '';
  for (i=0;i<iEnd;i++) {
      
    var codex = getCode(val,i);
    newcode += codex;
  }
  update(newcode);
}

function update(val){
  o = document.getElementById('out1');
  o.value = val;
  /*var o_copied = document.getElementById('out1').createTextRange();
  o_copied.exeCommand("Copy");*/
}


file: password_lookup.html
  <body onload="loadXml()">
    <h1>Password lookup</h1>
    <dl>
    <dt><label for="in1">Enter password:</label></dt>    
    <dd><input type="text" name="in1" id="in1" value="" 
  onkeyup="timed_update(event.keyCode, this.value)" /></dd>
    
    <dt><label for="out1">Generated password</label></dt>
    <dd><input type="text" name="out1" id="out1" value=""/></dd>
    <dd><input type="button" name="clear1" id="clear1" onclick="clearPassword()" value="clear"/></dd>

    </dl>
    <p>see also: <a href="codes.xml" title="password code lookup table">codes.xml</a></p>
  </body>


Try out the encode a simple password demo [rorbuilder.info].

see also: Reading an XML file usng JavaScript [snippets.dzone.com]

Convert two Arrays into one Hash (Ruby)

This is a way to merge two arrays into one hash.
The returned hash will have the same quantity of elements that the first(self) array.

class Array
def merge_into_hash(anArray)
tmp,hash = anArray.dup,{}
self.each {|key| hash[key] = tmp.shift}
hash
end
end
« Newer Snippets
Older Snippets »
Showing 1-10 of 102 total  RSS