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 94 total  RSS 

Simple File.find

# Simple File.find by c00lryguy
# Thanks to justinwr for adding what I forgot to do
# ------------------------------
# Usage: 
#     * = wildcard in filename
#   File.find("E:\\") => All files in E:\
#   File.find("E:\\Ruby", "*.rb") => All .rb files in E:\Ruby
#   File.find("E:\\", "*.rb", false) => All .rb files in E:\, but not in its subdirs
class File
  def self.find(dir, filename="*.*", subdirs=true)
    Dir[ subdirs ? File.join(dir.split(/\\/), "**", filename) : File.join(dir.split(/\\/), filename) ]
  end
end

IP Catcher

--Howto use--
the command line:
ruby /path/to/ipcatcher.rb /path/to/filename
the program will print all the ip addresses which is inside the file.
the program doesn't print the same ip address twice. with no duplications.
Done by Amer Jazaerly.there is no copyright.
have fun ;)

#!/usr/bin/ruby

def get_ips(file)
  ips = []
  File.read(file).to_a.each do |place|
    sf = 0
    while sfn = place.index(/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/,sf)
      sf = sfn + 3
      ips << $&
    end
  end
  return ips
end

get_ips(ARGV[0]).uniq.each { |ip| puts ip }

nginx expires config

  location ~* ^.+\.(js|css|php|jpg|jpeg|gif|png|pdf|zip|rar)$ {
    root   /var/www/apps/myapp/public;
    access_log   off;
    expires      7d;
  }

Upload a file using Ajax

This code is categorised as Ajax because it "fits within my definition of Ajax" as explained from the Ajax File Upload [openjs.com] article.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>File upload</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <script type="text/javascript">
    //<![CDATA[
      function init() {
	document.getElementById('file_upload_form').onsubmit=function() {
                                  //'upload_target' is the name of the iframe
	  document.getElementById('file_upload_form').target = 'upload_target'; 
	  }
  }
  window.onload=init;
    //]]>
    </script>
  </head>
  <body>
    <form id="file_upload_form" method="post" enctype="multipart/form-data" action="/p/file_upload.cgi">
    <input name="myfile" id="myfile" size="27" type="file" /><br />
    <input type="submit" name="action" value="Upload" /><br />
    <iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
    </form>
  </body>
</html>

Upload a file using Ruby

The following code was used to upload an image file to the web server. Source code origin: Ruby Language Stuff | mod_ruby File upload scripts [zytrax.com]

file: file_upload.cgi
#!/usr/bin/ruby

# ruby script fragment
require 'cgi'
require 'stringio'

cgi = CGI.new()  # New CGI object
puts "Content-Type: text/plain"
puts
print '<result>'

# get uri of tx'd file (in tmp normally)
tmpfile = cgi.params['myfile'].first.path

# OR (functionally the same)
tmpfile = cgi.params['myfile'][0].path

# create a Tempfile reference
fromfile = cgi.params['myfile'].first

#displays the original file name as supplied in the form
puts fromfile.original_filename

# displays the content (mime) type e.g. text/html
puts fromfile.content_type

# create output file reference as original filename in our chosen directory
tofile = '/var/www/yourdomain.com/htdocs/r/'+fromfile.original_filename

# copy the file
# note the untaint prevents a security error
# cgi sets up an StringIO object if file < 10240
# or a Tempfile object following works for both
File.open(tofile.untaint, 'w') { |file| file << fromfile.read}
# when the page finishes the Tempfile/StringIO!) thing is deleted automatically

print '</result>'

file: file_upload.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>File upload</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
  </head>
  <body>
    <form name='fileupload' enctype="multipart/form-data" 
    action='/p/file_upload.cgi' method='post'>
    <input type='file' name='myfile' size="40" />
    <input type='submit' value"Send it"/>
    </form>
  </body>
</html>
  

Find all subdirectories of a given path at a particular depth

def subdirectories_of(path, options = {}) depth = options[:at_depth_of] || 1 Dir[File.join(path, * ["*"] * depth + [""])] end >> subdirectories_of("/var") => ["/var/agentx/", "/var/amavis/", "/var/at/", "/var/audit/", "/var/backups/", "/var/db/", "/var/empty/", "/var/folders/", ...] >> subdirectories_of("/var", :at_depth_of => 2) => ["/var/amavis/db/", "/var/amavis/tmp/", "/var/at/jobs/", "/var/at/spool/", "/var/at/tabs/", "/var/at/tmp/", 

Ruby: Open a file, write to it, and close it in one line

r - Open a file for reading. The file must exist.
w - Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.
a - Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist.
r+ - Open a file for update both reading and writing. The file must exist.
w+ - Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.
a+ - Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. You can reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist.

File.open(local_filename, 'w') {|f| f.write(doc) }

Java filecopy using NIO

    public static void fileCopy( File in, File out )
            throws IOException
    {
        FileChannel inChannel = new FileInputStream( in ).getChannel();
        FileChannel outChannel = new FileOutputStream( out ).getChannel();
        try
        {
//          inChannel.transferTo(0, inChannel.size(), outChannel);      // original -- apparently has trouble copying large files on Windows

            // magic number for Windows, 64Mb - 32Kb)
            int maxCount = (64 * 1024 * 1024) - (32 * 1024);
            long size = inChannel.size();
            long position = 0;
            while ( position < size )
            {
               position += inChannel.transferTo( position, maxCount, outChannel );
            }
        }
        finally
        {
            if ( inChannel != null )
            {
               inChannel.close();
            }
            if ( outChannel != null )
            {
                outChannel.close();
            }
        }
    }

Mark directories to be deleted based on their date-stamp

This Ruby code selects file directories which are older than a certain date and outputs an XML file naming all the directories to be removed. It does this by reading a directory listing formatted within the XML file 'dir.xml', all directories are named by a date-stamp, which is used to determine if the directory should be removed.

This example is used to maintain the webcamera (named 'pear') which saves it's images to a date-stamped directory daily. Any directory which is older than 14 days will be marked for deletion.

  def directory_housekeeping()
    lifespan = 14
    format_mask = 'm_d_y'
    separator = format_mask.match(/[\_*\-]/).to_s
    
    earliest_date = Time.now + (60 * 60 * 24) * -lifespan
    cut_off_date = Date.new(y=earliest_date.year,m=earliest_date.month,d=earliest_date.day)
        
    a_format = Array.new
    a_format[0] = format_mask.match(/^[y,m,d]*/).to_s
    a_format[1] = format_mask.match(separator + '[y,m,d]*').to_s.gsub(separator,'')
    a_format[2] = format_mask.match('[y,m,d]$').to_s
    
    file = File.new('../housekeeping/webcam_pear/dir.xml')
    ddoc = REXML::Document.new(file)
    file.close
    
    file_delete = File.new('../housekeeping/webcam_pear/files2delete.xml', 'w')
    doc_delete = Document.new()
    doc_delete.add_element('files')
    
    ddoc.root.elements.each('file') do |file_node|
      sfile = file_node.text
      idate = Array.new
      idate[0] = sfile.match(/^\d*/).to_s.to_i
      idate[1] = sfile.match(/\_\d*/).to_s.gsub(separator,'').to_i
      idate[2] = sfile.match(/\_\d*\d$/).to_s.gsub(separator,'').to_i

      h = Hash.new
      0.upto(2) {|i| h[a_format[i]] = idate[i]}

      file_date = Date.new(y=h['y'], m=h['m'], d=h['d'])

      if file_date < cut_off_date
        o_file2delete = Element.new('file')
        o_file2delete.text = file_date.strftime(dformat)
        doc_delete.root.add_element o_file2delete
      end
    end
    file_delete.puts doc_delete
  end



file: dir.xml
<dir>
  <file>11_4_2007</file>
  <file>11_5_2007</file>
  <file>11_6_2007</file>
  <file>11_7_2007</file>
  <file>11_8_2007</file>
  <file>11_9_2007</file>
  <file>12_10_2007</file>
  <file>12_11_2007</file>
  <file>12_1_2007</file>
  <file>12_12_2007</file>
  <file>12_13_2007</file>
  <file>12_14_2007</file>
  <file>12_15_2007</file>
  <file>12_16_2007</file>
  <file>12_17_2007</file>
  <file>12_18_2007</file>
  <file>12_19_2007</file>
  <file>12_20_2007</file>
  <file>12_21_2007</file>
  <file>12_2_2007</file>
  <file>12_22_2007</file>
  <file>12_23_2007</file>
  <file>12_24_2007</file>
  <file>12_25_2007</file>
  <file>12_26_2007</file>
  <file>12_27_2007</file>
  <file>12_28_2007</file>
  <file>12_3_2007</file>
  <file>12_4_2007</file>
  <file>12_5_2007</file>
  <file>12_6_2007</file>
  <file>12_7_2007</file>
  <file>12_8_2007</file>
  <file>12_9_2007</file>
 </dir>

file: files2delete.xml
<files>
  <file>11_4_2007</file>
  <file>11_5_2007</file>
  <file>11_6_2007</file>
  <file>11_7_2007</file>
  <file>11_8_2007</file>
  <file>11_9_2007</file>
  <file>12_10_2007</file>
  <file>12_11_2007</file>
  <file>12_1_2007</file>
  <file>12_12_2007</file>
  <file>12_13_2007</file>
  <file>12_14_2007</file>
  <file>12_15_2007</file>
  <file>12_2_2007</file>
  <file>12_3_2007</file>
  <file>12_4_2007</file>
  <file>12_5_2007</file>
  <file>12_6_2007</file>
  <file>12_7_2007</file>
  <file>12_8_2007</file>
  <file>12_9_2007</file>
 </files>

Using Ruby to change the owner of a file

This code change the owner, and group owner of a file from 'root' to 'apache'. This method differs from File.chown because it allows the group name to be specified rather than the group id. More information can be found from http://www.noobkit.com/ruby-fileutils-chown

require 'fileutils'
FileUtils.chown('apache','apache', 'slashdot.wml')
« Newer Snippets
Older Snippets »
Showing 1-10 of 94 total  RSS