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 11-20 of 105 total

perl grep dir and filename

// description of your code here

   1  
   2  my($directory, $filename) = $text =~ m/(.*\/)(.*)$/;
   3  print "D=$directory, F=$filename\n
   4  

Simple File.find

   1  
   2  # Simple File.find by c00lryguy
   3  # Thanks to justinwr for adding what I forgot to do
   4  # ------------------------------
   5  # Usage: 
   6  #     * = wildcard in filename
   7  #   File.find("E:\\") => All files in E:\
   8  #   File.find("E:\\Ruby", "*.rb") => All .rb files in E:\Ruby
   9  #   File.find("E:\\", "*.rb", false) => All .rb files in E:\, but not in its subdirs
  10  class File
  11    def self.find(dir, filename="*.*", subdirs=true)
  12      Dir[ subdirs ? File.join(dir.split(/\\/), "**", filename) : File.join(dir.split(/\\/), filename) ]
  13    end
  14  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 ;)

   1  
   2  #!/usr/bin/ruby
   3  
   4  def get_ips(file)
   5    ips = []
   6    File.read(file).to_a.each do |place|
   7      sf = 0
   8      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)
   9        sf = sfn + 3
  10        ips << $&
  11      end
  12    end
  13    return ips
  14  end
  15  
  16  get_ips(ARGV[0]).uniq.each { |ip| puts ip }

nginx expires config

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

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.

   1  
   2  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   3    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   4  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   5    <head>
   6      <title>File upload</title>
   7      <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
   8      <script type="text/javascript">
   9      //<![CDATA[
  10        function init() {
  11  	document.getElementById('file_upload_form').onsubmit=function() {
  12                                    //'upload_target' is the name of the iframe
  13  	  document.getElementById('file_upload_form').target = 'upload_target'; 
  14  	  }
  15    }
  16    window.onload=init;
  17      //]]>
  18      </script>
  19    </head>
  20    <body>
  21      <form id="file_upload_form" method="post" enctype="multipart/form-data" action="/p/file_upload.cgi">
  22      <input name="myfile" id="myfile" size="27" type="file" /><br />
  23      <input type="submit" name="action" value="Upload" /><br />
  24      <iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
  25      </form>
  26    </body>
  27  </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
   1  
   2  #!/usr/bin/ruby
   3  
   4  # ruby script fragment
   5  require 'cgi'
   6  require 'stringio'
   7  
   8  cgi = CGI.new()  # New CGI object
   9  puts "Content-Type: text/plain"
  10  puts
  11  print '<result>'
  12  
  13  # get uri of tx'd file (in tmp normally)
  14  tmpfile = cgi.params['myfile'].first.path
  15  
  16  # OR (functionally the same)
  17  tmpfile = cgi.params['myfile'][0].path
  18  
  19  # create a Tempfile reference
  20  fromfile = cgi.params['myfile'].first
  21  
  22  #displays the original file name as supplied in the form
  23  puts fromfile.original_filename
  24  
  25  # displays the content (mime) type e.g. text/html
  26  puts fromfile.content_type
  27  
  28  # create output file reference as original filename in our chosen directory
  29  tofile = '/var/www/yourdomain.com/htdocs/r/'+fromfile.original_filename
  30  
  31  # copy the file
  32  # note the untaint prevents a security error
  33  # cgi sets up an StringIO object if file < 10240
  34  # or a Tempfile object following works for both
  35  File.open(tofile.untaint, 'w') { |file| file << fromfile.read}
  36  # when the page finishes the Tempfile/StringIO!) thing is deleted automatically
  37  
  38  print '</result>'

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

Find all subdirectories of a given path at a particular depth

   1  
   2  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.

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

Java filecopy using NIO

   1  
   2      public static void fileCopy( File in, File out )
   3              throws IOException
   4      {
   5          FileChannel inChannel = new FileInputStream( in ).getChannel();
   6          FileChannel outChannel = new FileOutputStream( out ).getChannel();
   7          try
   8          {
   9  //          inChannel.transferTo(0, inChannel.size(), outChannel);      // original -- apparently has trouble copying large files on Windows
  10  
  11              // magic number for Windows, 64Mb - 32Kb)
  12              int maxCount = (64 * 1024 * 1024) - (32 * 1024);
  13              long size = inChannel.size();
  14              long position = 0;
  15              while ( position < size )
  16              {
  17                 position += inChannel.transferTo( position, maxCount, outChannel );
  18              }
  19          }
  20          finally
  21          {
  22              if ( inChannel != null )
  23              {
  24                 inChannel.close();
  25              }
  26              if ( outChannel != null )
  27              {
  28                  outChannel.close();
  29              }
  30          }
  31      }

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.

   1  
   2    def directory_housekeeping()
   3      lifespan = 14
   4      format_mask = 'm_d_y'
   5      separator = format_mask.match(/[\_*\-]/).to_s
   6      
   7      earliest_date = Time.now + (60 * 60 * 24) * -lifespan
   8      cut_off_date = Date.new(y=earliest_date.year,m=earliest_date.month,d=earliest_date.day)
   9          
  10      a_format = Array.new
  11      a_format[0] = format_mask.match(/^[y,m,d]*/).to_s
  12      a_format[1] = format_mask.match(separator + '[y,m,d]*').to_s.gsub(separator,'')
  13      a_format[2] = format_mask.match('[y,m,d]$').to_s
  14      
  15      file = File.new('../housekeeping/webcam_pear/dir.xml')
  16      ddoc = REXML::Document.new(file)
  17      file.close
  18      
  19      file_delete = File.new('../housekeeping/webcam_pear/files2delete.xml', 'w')
  20      doc_delete = Document.new()
  21      doc_delete.add_element('files')
  22      
  23      ddoc.root.elements.each('file') do |file_node|
  24        sfile = file_node.text
  25        idate = Array.new
  26        idate[0] = sfile.match(/^\d*/).to_s.to_i
  27        idate[1] = sfile.match(/\_\d*/).to_s.gsub(separator,'').to_i
  28        idate[2] = sfile.match(/\_\d*\d$/).to_s.gsub(separator,'').to_i
  29  
  30        h = Hash.new
  31        0.upto(2) {|i| h[a_format[i]] = idate[i]}
  32  
  33        file_date = Date.new(y=h['y'], m=h['m'], d=h['d'])
  34  
  35        if file_date < cut_off_date
  36          o_file2delete = Element.new('file')
  37          o_file2delete.text = file_date.strftime(dformat)
  38          doc_delete.root.add_element o_file2delete
  39        end
  40      end
  41      file_delete.puts doc_delete
  42    end
  43  


file: dir.xml
   1  
   2  <dir>
   3    <file>11_4_2007</file>
   4    <file>11_5_2007</file>
   5    <file>11_6_2007</file>
   6    <file>11_7_2007</file>
   7    <file>11_8_2007</file>
   8    <file>11_9_2007</file>
   9    <file>12_10_2007</file>
  10    <file>12_11_2007</file>
  11    <file>12_1_2007</file>
  12    <file>12_12_2007</file>
  13    <file>12_13_2007</file>
  14    <file>12_14_2007</file>
  15    <file>12_15_2007</file>
  16    <file>12_16_2007</file>
  17    <file>12_17_2007</file>
  18    <file>12_18_2007</file>
  19    <file>12_19_2007</file>
  20    <file>12_20_2007</file>
  21    <file>12_21_2007</file>
  22    <file>12_2_2007</file>
  23    <file>12_22_2007</file>
  24    <file>12_23_2007</file>
  25    <file>12_24_2007</file>
  26    <file>12_25_2007</file>
  27    <file>12_26_2007</file>
  28    <file>12_27_2007</file>
  29    <file>12_28_2007</file>
  30    <file>12_3_2007</file>
  31    <file>12_4_2007</file>
  32    <file>12_5_2007</file>
  33    <file>12_6_2007</file>
  34    <file>12_7_2007</file>
  35    <file>12_8_2007</file>
  36    <file>12_9_2007</file>
  37   </dir>

file: files2delete.xml
   1  
   2  <files>
   3    <file>11_4_2007</file>
   4    <file>11_5_2007</file>
   5    <file>11_6_2007</file>
   6    <file>11_7_2007</file>
   7    <file>11_8_2007</file>
   8    <file>11_9_2007</file>
   9    <file>12_10_2007</file>
  10    <file>12_11_2007</file>
  11    <file>12_1_2007</file>
  12    <file>12_12_2007</file>
  13    <file>12_13_2007</file>
  14    <file>12_14_2007</file>
  15    <file>12_15_2007</file>
  16    <file>12_2_2007</file>
  17    <file>12_3_2007</file>
  18    <file>12_4_2007</file>
  19    <file>12_5_2007</file>
  20    <file>12_6_2007</file>
  21    <file>12_7_2007</file>
  22    <file>12_8_2007</file>
  23    <file>12_9_2007</file>
  24   </files>
« Newer Snippets
Older Snippets »
Showing 11-20 of 105 total