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 33 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

copy files using rsync and ssh

source: http://www.mikerubel.org/computers/rsync_snapshots/#Abstract ; switches: -a = archive mode -e specifies the remote shell to use

rsync -a -e ssh source/ username@remotemachine.com:/path/to/destination/

Rename all *.gif files in a directory (prefix)

// My mind always seems to draw a blank when I want to do this sort of thing, so here's a concise little self-reminder

for file in $(echo *.gif); do mv ${file} prefix.${file}; done

basename & dirname in Perl

These two Perl functions implement approximations of the UNIX utilities `basename` and `dirname`, though basename() automatically strips off the last extension no matter what.
sub basename($) {
 my $file = shift;
 $file =~ s!^(?:.*/)?(.+?)(?:\.[^.]*)?$!$1!;
 return $file;
}

sub dirname($) {my $file = shift; $file =~ s!/?[^/]*/*$!!; return $file; }

Image aggregator

This PHP snippet outputs the contents of a table (beginning & ending tags not included) containing all the images from the current directory.
<?PHP
 $columns = 3;
 $im = glob("*.{gif,jpg,png}", GLOB_BRACE);
 $rows = ceil(count($im) / $columns);
 for ($i = 0; $i < $rows; $i++) {
  echo "\n<TR>";
  for ($j = $columns*$i; isset($im[$j]) && $j - $columns*$i < $columns; $j++) {
   echo "<TD>$im[$j]<BR><IMG SRC='$im[$j]'></TD>";
  }
  echo "</TR>";
 }
?>

File extension counter

Produces a count of the frequencies of each file extension in the directories named on the command line
#!/usr/bin/perl -w
use strict;
my %exten;
foreach (@ARGV) {
 /(\.[^.]+)$/ && $exten{$1}++ foreach glob "$_/*.*"
}
print "$_: $exten{$_}\n" foreach sort keys %exten;

Organize photos and other files on an year/month/day folders structures

This script can organize you media colelction in folders by year/month/day.
For jpeg files, looks in exif for the creation date, if that file has that kind of metadadata. For any other files it only checks the creation time.
The script takes 3 option on the command line. A command which may be -m, -c or -f, a source folder and a destination folder.
Using -c will copy the files from souce to destination, -m will move them, - f will also move them, by making first a copy then a delete. -f option may used when -m doesn't work, the most common situation beeing when you want to move the files from one file system to another(e.g. from your ext3 local hard drive to an external fat32 usb harddrive)
After you organize the files, you can find duplicate items using my previous snippet.
This script have been inspired from here
#!/usr/local/bin/ruby
require 'rubygems'
require 'ftools'
require 'exifr'


def process_file(file_path,destination_dir)
	if File.directory?(file_path)
		crt_dir = Dir.new(file_path)
		crt_dir.each do |file_name|
			if file_name != '.' &&  file_name != '..'				
				process_file("#{crt_dir.path}/#{file_name}",destination_dir)		
			end
		end	
	else
			
		if  File.fnmatch('*.jpg',file_path) ||  File.fnmatch('*.jpeg',file_path)
			picture = EXIFR::JPEG.new(file_path)
			if picture != nil && picture.exif != nil
				file_date = picture.date_time		
			else
				f = File.new(file_path)
				file_date = f.mtime
			end							
		end
		if file_date == nil
			f = File.new(file_path)
			file_date = f.mtime	
		end		
		year_dir =  destination_dir + file_date.strftime("%Y")
		month_dir = destination_dir + file_date.strftime("%Y/%m-%b")
		day_dir = destination_dir + file_date.strftime("%Y/%m-%b/%d")
		new_file_name = day_dir + "/" + File.basename(file_path)
		begin
			Dir.mkdir(year_dir) unless File.exists?(year_dir)
			Dir.mkdir(month_dir) unless File.exists?(month_dir)
			Dir.mkdir(day_dir) unless File.exists?(day_dir)
			if ARGV[0 ] =='-m' #move the files
				File.rename(file_path, new_file_name)
			elsif ARGV[0]  =='-c' #copy the files
				File.cp(file_path, new_file_name)	
			elsif ARGV[0]  =='-f' #copy and delete, acts like a move between thw different file systems	
				File.cp(file_path, new_file_name)
				File.delete(file_path)	
			else
				puts "Unknown option #{ARGV[0]}"
				exit	
			end	
		end	
		
	end	
end


if ARGV.length != 3
	puts "Three arguments are required to run the script, -c|-m|-f <source_folder_or_file>  <destination_folder>"
	exit
end

if ARGV[0] !='-c'  && ARGV[0]!='-m' && ARGV[0]!='-f'
	puts "Unknown running option: #{ARGV[0]}"
	exit
end

if not File.exists?(ARGV[1]) 
	puts "Source file does not exists: #{ARGV[1]}"
	exit
end


if not File.directory?(ARGV[2]) 
	puts "Destination file is not a directory #{ARGV[2]}"
	exit
end

if ARGV[1]==ARGV[2]
	puts "Source and destination must be different"
	exit
end	
	
	
process_file(ARGV[1], ARGV[2])

Directory List with PHP

// description of your code here

This code list all files and subdirectories in a dirctory with links.


<html><head><title>ribafs.net - Tutoriais</title></head>
<body bgcolor='#FFFACD'>
<h2 align=center><a href="http://ribafs.net">http://ribafs.net - <?php echo date('d/m/Y H:i:s'); ?></a></h2>

<?php
$dn = opendir (dirname(__FILE__));
$exclude = array("index.php", ".", "..");

// adiciona os arquivos ao array $arquivos
while($fn = readdir($dn)) {
	if ($fn == $exclude[0] || $fn == $exclude[1] || $fn == $exclude[2]) continue;
	$arquivos[] = $fn;
}
// ordena o vetor
sort($arquivos);
// exibe os arquivos

foreach ($arquivos as $arquivo)

if (is_dir($arquivo)){
	$dir .= "<img src='/imagens/diretorio.png'>&nbsp;<a href='$arquivo'>$arquivo</a><br>";
}else{
	$tamanho = filesize($arquivo);
	$m = 'bytes';
	if ($tamanho>1024) {
		$tamanho=round($tamanho/1024,2);
		$m = 'KB';
	} elseif($tamanho > 1024*1024){
		$tamanho = round(($tamanho/1024)/1024,2);
		$m = 'MB';
	}
	$arq .= "<img src='/imagens/arquivo.png'>&nbsp;<a href='$arquivo'>$arquivo</a> - $tamanho $m<br>";
}
echo $dir . $arq;

closedir($dn);
?>


Adding files to an existing jar file

Adds files to an existing Zip file.

Overwrites zip entries with the same name as one of the new files.

The function renames the existing zip file to a temporary file and then adds all entries in the existing zip along with the new files, excluding the zip entries that have the same name as one of the new files.


Note: I'm not sure I used the best way to get a temp file. A snippet for that is welcome :)

	
	public static void addFilesToExistingZip(File zipFile,
			 File[] files) throws IOException {
                // get a temp file
		File tempFile = File.createTempFile(zipFile.getName(), null);
                // delete it, otherwise you cannot rename your existing zip to it.
		tempFile.delete();

		boolean renameOk=zipFile.renameTo(tempFile);
		if (!renameOk)
		{
			throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath());
		}
		byte[] buf = new byte[1024];
		
		ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
		
		ZipEntry entry = zin.getNextEntry();
		while (entry != null) {
			String name = entry.getName();
			boolean notInFiles = true;
			for (File f : files) {
				if (f.getName().equals(name)) {
					notInFiles = false;
					break;
				}
			}
			if (notInFiles) {
				// Add ZIP entry to output stream.
				out.putNextEntry(new ZipEntry(name));
				// Transfer bytes from the ZIP file to the output file
				int len;
				while ((len = zin.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
			}
			entry = zin.getNextEntry();
		}
		// Close the streams		
		zin.close();
		// Compress the files
		for (int i = 0; i < files.length; i++) {
			InputStream in = new FileInputStream(files[i]);
			// Add ZIP entry to output stream.
			out.putNextEntry(new ZipEntry(files[i].getName()));
			// Transfer bytes from the file to the ZIP file
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			// Complete the entry
			out.closeEntry();
			in.close();
		}
		// Complete the ZIP file
		out.close();
		tempFile.delete();
	}

Java - imgFromJar

// Inserire un immagine presente nel file jar dell'applicazione

try
		{
			icon = ImageIO.read(getClass().getResourceAsStream("imgs/icon.png")); // La preleva dal file jar
			setIconImage(icon);
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
« Newer Snippets
Older Snippets »
Showing 1-10 of 33 total  RSS