DZone 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
  • submit to reddit
        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) }
    
        A handful of fixes/enhancements for the "dbf" Rubygem.

# example.rb
require 'rubygems'
require 'dbf'
require 'dbf_fixes'

table = DBF::Table.new('/path/to/table.dbf', :in_memory => false)
table.each_record do |record|
  # do something here
  # with in_memory=>false tables, each_record is much more efficient
  # because it reads directly from disk 
end


# dbf_fixes.rb
module DBF
  class Record
    private

    # fix bug in DBF code (or workaround bug in FoxPro dbf files; I don't know :-)
    def initialize_values(columns)
      columns.each do |column|
        case column.type
        when 'I' # added by Tim - I don't understand this much, but it seems to work
          @attributes[column.name] = @data.read(column.length).unpack("I").first
        when 'N' # number
          @attributes[column.name] = column.decimal.zero? ? unpack_string(column).to_i : unpack_string(column).to_f
        when 'D' # date
          raw = unpack_string(column).strip
          unless raw.empty?
            begin
              parts = raw.match(DATE_REGEXP).to_a.slice(1,3).map {|n| n.to_i}
              @attributes[column.name] = Time.gm(*parts)
            rescue
              parts = raw.match(DATE_REGEXP).to_a.slice(1,3).map {|n| n.to_i}
              @attributes[column.name] = Date.new(*parts)
            end
          end
        when 'M' # memo
          starting_block = unpack_string(column).to_i
          @attributes[column.name] = read_memo(starting_block)
        when 'L' # logical
          @attributes[column.name] = unpack_string(column) =~ /^(y|t)$/i ? true : false
        else
          @attributes[column.name] = unpack_string(column).strip
        end
      end
    end

    # don't know why, but accessors stopped working for me.
    def define_accessors
      @table.columns.each do |column|
        underscored_column_name = underscore(column.name)
        if @table.options[:accessors]
          self.class.send :define_method, underscored_column_name do
            @attributes[column.name]
          end
          @@accessors_defined = true
        end
      end
    end
  end

  class Table
    # more efficient iterator (so we don't load everything)
    def each_record
      if options[:in_memory] and @records
        @records.each { |r| yield(r) }
      else
        0.upto(@record_count - 1) do |n|
          seek_to_record(n)
          yield(DBF::Record.new(self)) unless deleted_record?
        end
      end
    end
  end
end
    
        // Tired of having others have cooler status on their IM clients,
// I decided that I shall put an end to that.
// Yet, I am no factory of coolness, but I figured my favorite buddy,
// "fortune" will help me out a little.

// By the way, this tool can definitely be done much better with regard
// to the way it updates the MSN, but hey, I just wanted to play with
// C#. My first time :P

// BTW, the MSN thing works only if you have your MSN not minimized PLUS
// the toolbar showing. (LAME! I know.)

// If you really want to do it right, use http://www.xihsolutions.net/dotmsn/
// and send me the code ;) bhtek@yahoo.com

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Automation;
using System.Runtime.InteropServices;


namespace ZenStatusUpdater
{
    class Program 
    {
        [DllImport("USER32.DLL", EntryPoint = "FindWindowA", CallingConvention = CallingConvention.StdCall)]
        private static extern IntPtr FindWindow(string sClassName, string sWindowName);

        [DllImport("USER32.DLL", EntryPoint = "PostMessageA", CallingConvention = CallingConvention.StdCall)]
        private static extern bool PostMessage(IntPtr hWnd, uint iMsg, long wParam, long lParam); 

        static void exploreElement(AutomationElement sub)
        {
            foreach (AutomationProperty prop in sub.GetSupportedProperties())
            {
                Console.WriteLine("\tProp[" + prop.ProgrammaticName + "]: " + sub.GetCurrentPropertyValue(prop));
            }

            foreach (AutomationPattern pat in sub.GetSupportedPatterns())
            {
                Console.WriteLine("\tPat[" + pat.ProgrammaticName + "]");
            }
        }

        static void explore(AutomationElement el)
        {
            Console.WriteLine("Self...");
            exploreElement(el);


            foreach (AutomationElement sub in el.FindAll(TreeScope.Descendants, Condition.TrueCondition))
            {
                Console.WriteLine("Sub...");
                exploreElement(sub);
            }
        }

        static void Main(string[] args)
        {
            String fortune = null;
            int tries = 0;

            do
            {
                fortune = GetFortune();
                tries++;
            } while (fortune.Length > 130);

            Console.WriteLine("Try #" + tries + ": " + fortune);

            updateMsnStatus(fortune);
            updateYahooStatus(fortune);

            System.Threading.Thread.Sleep(5000);
        }

        protected static void updateYahooStatus(String fortune)
        {
            // Get the current signed in user
            //
            string sUserName = "bhtek";
            Console.WriteLine("The currently logged in user is " + sUserName);

            // Now open the current user's profile and set the current status message, pass true to
            // OpenSubKey to request write access

            RegistryKey keyYahooCustomMessages = Registry.CurrentUser.OpenSubKey("Software\\Yahoo\\Pager\\profiles\\"
            + sUserName + "\\Custom Msgs", true);

            // Set the 5th message, seems like yahoo messenger has the functionality to move the newly set
            // message up as the first one.
            String status = fortune;
            keyYahooCustomMessages.SetValue("5", status);
            byte[] statusBin = (new ASCIIEncoding()).GetBytes(status);
            keyYahooCustomMessages.SetValue("5_bin", (byte[])statusBin); 
            keyYahooCustomMessages.Close();
                
            // We are done setting the value in the registry. We now need to notify y! of this change
            //

            // Find the yahoo messenger window and sent it the notification
            // 0x111: WM_COMMAND
            // 0x188: Code 392

            IntPtr hWndY = FindWindow("YahooBuddyMain", null);
            System.Diagnostics.Debug.WriteLine("Find window got: " + hWndY.ToString());
            PostMessage(hWndY, 0x111, 0x188, 0);
        }

        protected static void updateMsnStatus(String fortune)
        {
            AutomationElementCollection msnWindows = AutomationElement.RootElement.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "MSBLWindowClass"));
            if (msnWindows.Count > 1)
            {
                foreach (AutomationElement potentialMsn in msnWindows)
                {
                    exploreElement(potentialMsn);
                }

                return;
            }

            AutomationElement msn = msnWindows[0];
            msn.SetFocus();

            AutomationElement tools = msn.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AccessKeyProperty, "Alt+T"));
            ExpandCollapsePattern toolsPat = (ExpandCollapsePattern)tools.GetCurrentPattern(ExpandCollapsePattern.Pattern);
            toolsPat.Expand();

            AutomationElement options = tools.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Options..."));
            InvokePattern optionsPat = (InvokePattern)options.GetCurrentPattern(InvokePattern.Pattern);
            optionsPat.Invoke();

            AutomationElement optionsWindow = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Options"));

            AutomationElement personalMessage = optionsWindow.FindFirst(TreeScope.Descendants,
                new AndCondition(
                    new PropertyCondition(AutomationElement.ClassNameProperty, "RichEdit20W"),
                    new PropertyCondition(AutomationElement.NameProperty, "Type a personal message for your contacts to see:")
                    )
            );
            ValuePattern personalMessagePat = (ValuePattern)personalMessage.GetCurrentPattern(ValuePattern.Pattern);
            personalMessagePat.SetValue(fortune);

            AutomationElement ok = optionsWindow.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "OK"));
            InvokePattern okPat = (InvokePattern)ok.GetCurrentPattern(InvokePattern.Pattern);
            okPat.Invoke();
        }

        private static String GetFortune()
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = "c:\\cygwin\\bin\\fortune.exe";
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute = false;
            process.Start();
            String fortune = process.StandardOutput.ReadToEnd();

            fortune = System.Text.RegularExpressions.Regex.Replace(fortune, "\\s+", " ");
            return fortune;
        }

       
    }
}
    
        This script calls the Windows OLE for the built in TTS. Type what you want the computer to say at the prompt and hit enter. To quit type ":q" (minus the quotation marks).


use Win32::OLE qw( EVENTS );

get_text();

sub get_text{
	$output_speech = <STDIN>;
	chomp($output_speech);
	if($output_speech ne ":q"){
		say_this();
		get_text();
	}
}

sub say_this{
	my $myTTS = new Win32::OLE( "Sapi.SpVoice" ); 
	$myTTS->Speak( "$output_speech" );
	while( $myTTS->{Speaking} )
	{
		Win32::OLE->SpinMessageLoop();
		Win32::Sleep( 100 );
	}
}
    
        
mysqldump -v --quick --single-transaction --all-databases -uroot > file.sql
mysqldump -v --quick --single-transaction --all-databases -h internal-db.s1939.gridserver.com -udb1939 -pPASSWORD > mt_all.sql
    
        
# Snagged from http://softiesonrails.com/2007/7/11/upgrading-your-views-to-rails-2-0
for old in `find app/views -name *.rhtml`; do svn mv $old `dirname $old`/`basename $old .rhtml`.html.erb; done
    
        Requires the Tinder gem, and PHP on the server running MediaWiki must be compiled with --enable-sockets. The computer running the bot will also have to be open to the web - it can't be behind a firewall.

First, add this code to your MediaWiki LocalSettings.php, replacing the IP address with the IP of the server/computer running the bot, and the port to whatever you want to use (probably something above 40,000, but it's up to you):
$wgRC2UDPAddress = '69.178.6.244';
$wgRC2UDPPort = '41895';
$wgRC2UDPPrefix = "";

Now, you can run the bot! This is extremely hackish, because the retarded collective-mailing-list-coding system of the MediaWiki repos has somehow managed to code IRC color codes directly into their exported strings (at least with MediaWiki 1.2alpha, which is what I'm running right now).
You'll need to replace the new tinder definition with your subdomain on Campfire, the username and password with ones for the bot account you've created on your campfire room, and the room name with the room you want the updates to be sent to.
require 'rubygems'
require 'tinder'
require 'socket'
puts 'Dependencies loaded...'

campfire = Tinder::Campfire.new 'subdomain'
campfire.login 'email@domain.com', 'password'
exit unless room = campfire.find_room_by_name('Case Sensitive Room Name')
puts 'Campfire logged in...'

server = UDPSocket.new
exit unless server.bind('0.0.0.0', 41895)
puts 'Socket listening...'

loop do
  msg = server.recv(2048).gsub(/\003[\d]{0,2}/,'').chomp
  print "sending to room: #{msg.inspect}..."
  exit unless room.speak msg.to_s
  puts ' sent!'
end
    
        This is a script that builds a <a href="http://radiantcms.org">Radiant CMS</a> site with several third-party extensions I use a lot. This just saves me time from having to look up the setup commands each time. YMMV

I call this power_radiant and stick it in /usr/local/bin.

Update: this has been fixed to work with latest Radiant code (since svn path as changed and freeze:edge task no longer works). You will need Git to be installed on your machine for this to work.

#!/bin/sh
radiant --database sqlite3 $1
cd $1
echo "
production:
  adapter: sqlite3
  database: db/production.sqlite3
test:
  adapter: sqlite3
  database: db/test.sqlite3
development:
  production
" > config/database.yml
svn export http://svn.radiantcms.org/radiant/trunk/extensions/shards/ vendor/extensions/shards
svn export svn://zuurstof.openminds.be/home/kaizer/svn/rails_stuff/radiant_extensions/wym_editor_filter vendor/extensions/wym_editor_filter
svn export http://svn.seancribbs.com/svn/rails/plugins/extensions/page_attachments vendor/extensions/page_attachments
#rake radiant:freeze:edge # stopped working in latest gem
git clone git://github.com/seancribbs/radiant.git /tmp/radiant
cp -r /tmp/radiant/radiant vendor/radiant
rake production db:bootstrap
rake production db:migrate:extensions
rake production radiant:extensions:wym_editor_filter:install
rake production radiant:extensions:page_attachments:update

To run: 
power_radiant my_site
    
        // takes an array of values and a value to match, and outputs formatted <option>s with the <option> matching $match selected
// must be manually wrapped in <select></select to allow for maximum flexibility

function selectHelper($values, $match)
{
  $keys = array_keys($values);
  $i = 0;
	
  foreach($values as $option)
  {
    $selected = null;
		
    if($match == $keys[$i])
      $selected = " selected";
			
    echo "	<option value=\"".$keys[$i]."\"$selected>".$option."</option>\n";
		
    $i++;
  }
}

//sample usage:
$values = array(
  "lb" => "Pounds",
  "ea" => "Each",
  "oz" => "Ounces");
				
  selectHelper($values, $product->unit);
    
Jill Tomich01/23/08
3803 views
9 replies

DZone to Launch a New Program – Refcardz

Refcardz is a series of high-quality quick reference cards on developer-related topics. We are gathering authors from some of the best computer book publishers to create content that is more than just tables and code as seen in most reference cards available.

        <a href="http://feed43.com/8055673348816228.xml">http://feed43.com/8055673348816228.xml</a>    
        Turbo Pascal and conio.h allowed immediate character reading, without wainting for enter. Following code does the same under unix terminals:

#include <stdio.h>
#include <termios.h>

char getch(void) {
        char buf = 0;
        struct termios old = {0};
        if (tcgetattr(0, &old) < 0)
                perror("tcsetattr()");
        old.c_lflag &= ~ICANON;
        old.c_lflag &= ~ECHO;
        old.c_cc[VMIN] = 1;
        old.c_cc[VTIME] = 0;
        if (tcsetattr(0, TCSANOW, &old) < 0)
                perror("tcsetattr ICANON");
        if (read(0, &buf, 1) < 0)
                perror ("read()");
        old.c_lflag |= ICANON;
        old.c_lflag |= ECHO;
        if (tcsetattr(0, TCSADRAIN, &old) < 0)
                perror ("tcsetattr ~ICANON");
        return (buf);
}

int main() {
        char key;
        printf("Press 'x' to exit...\n");
        while((key=getch()) && (key != 'x'))
                printf ("you pressed %c\n", key);
        return(0);
}
    
        Function to generate descriptive errors (line number, function name, etc).

#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>

#ifdef __OPTIMIZE__
#define __OPT__ 1
#else
#define __OPT__ 0
#endif

#ifdef __OPTIMIZE_SIZE__
#define __OPT_SIZE__ 1
#else
#define __OPT_SIZE__ 0
#endif

#define err_print(args...) __err_print(__FILE__, __FUNCTION__, __LINE__, __DATE__ " " __TIME__, __VERSION__, __OPT__, __OPT_SIZE__, ##args)
void __err_print(char *file, char *function, int line, char *date, char *version, int opt, int opt_size, char *txt, ...)
{
        va_list argp;

        puts("** ERROR! **");
        printf("File:                 \t %s\n",file);
        printf("Function:             \t %s\n",function);
        printf("Line:                 \t %d\n",line);
        printf("Compilation date:     \t %s\n",date);
        printf("Compilator version:   \t %s\n",version);
        printf("Optimization:         \t %s\n",opt==1 ? "Yes" : "No");
        printf("Size optimization:    \t %s\n",opt_size==1 ? "Yes" : "No");

        if (txt == NULL)
                return;
        puts("Description:\n>>>");
        va_start(argp, txt);
        vprintf(txt, argp);
        va_end(argp);
        puts("\n<<<");
}

void other_function() {
        err_print("other %s (%d+%d=%d)", "description",2,2,5);
}

int main() {
        err_print("test %d", 2);
        puts("");
        other_function();
        return 0;
}
    
        
<?
	// if www.domain.com, redirect to domain.com
	if (strtolower(substr($_SERVER['HTTP_HOST'], 0, 3)) == "www") {
		header("Location: http://rgcreative.com" . $_SERVER['REQUEST_URI']);
	}
	
	// Full path to current URL (including query string)
	//echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
?>
    
        // description of your code here

>> "%.2f" % 45.4324234321421
=> "45.43"

>> "[%s]" % "Hey you dirty old ruby, put me in brackets. NOW!"
=> "[Hey you dirty old ruby, put me in brackets. NOW!]"

For more complex substitutions, pass the arguments as an array:
>> "[%s] And a number:%.1f" % ["Hey you dirty old ruby, put me in brackets. NOW!",43.4323]
=> "[Hey you dirty old ruby, put me in brackets. NOW!] And a number:43.4"
    
        # pad the plaintext to 64 characters, then get an MD5 digest
# 128 bits, duh.

require 'digest/md5'

def pad(text)
   v = text * (1 + (64 / text.length))
   v[0,64]
end

def wep_key(text)
   Digest::MD5.hexdigest(pad(text))
end


    
        The mixin below allows comparison between two Time objects using the more intuitive and natural-sounding before? and after? methods.

Some examples (using Rails' ActiveSupport Time extensions or (preferred) the 'units' gem):

2.minutes.ago.after? Time.now # => false

Time.now.before? 2.hours.from_now # => true

module BeforeAndAfter

  LEFT_SIDE_LATER  = 1
  RIGHT_SIDE_LATER = -1
  
  def before?(input_time)
    (self <=> input_time) == RIGHT_SIDE_LATER
  end
  
  def after?(input_time)
    (self <=> input_time) == LEFT_SIDE_LATER
  end
end

Time.send :include , BeforeAndAfter
    
        // Transliteration (or Translit for short).
// Converts Russian characters into Latin on-the-fly.
// Save the code as UTF-8.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Translit</title>
<script type="text/javascript">
/* Javascript functions */
function JSfunc()
{
	/* Making transliteration! */
	this.strTranslit = function(el)
	{
		new_el = document.getElementById('out');
		A = new Array();
		A["Ё"]="YO";A["Й"]="I";A["Ц"]="TS";A["У"]="U";A["К"]="K";A["Е"]="E";A["Н"]="N";A["Г"]="G";A["Ш"]="SH";A["Щ"]="SCH";A["З"]="Z";A["Х"]="H";A["Ъ"]="'";
		A["ё"]="yo";A["й"]="i";A["ц"]="ts";A["у"]="u";A["к"]="k";A["е"]="e";A["н"]="n";A["г"]="g";A["ш"]="sh";A["щ"]="sch";A["з"]="z";A["х"]="h";A["ъ"]="'";
		A["Ф"]="F";A["Ы"]="I";A["В"]="V";A["А"]="A";A["П"]="P";A["Р"]="R";A["О"]="O";A["Л"]="L";A["Д"]="D";A["Ж"]="ZH";A["Э"]="E";
		A["ф"]="f";A["ы"]="i";A["в"]="v";A["а"]="a";A["п"]="p";A["р"]="r";A["о"]="o";A["л"]="l";A["д"]="d";A["ж"]="zh";A["э"]="e";
		A["Я"]="YA";A["Ч"]="CH";A["С"]="S";A["М"]="M";A["И"]="I";A["Т"]="T";A["Ь"]="'";A["Б"]="B";A["Ю"]="YU";
		A["я"]="ya";A["ч"]="ch";A["с"]="s";A["м"]="m";A["и"]="i";A["т"]="t";A["ь"]="'";A["б"]="b";A["ю"]="yu";
		new_el.value = el.value.replace(/([\u0410-\u0451])/g,
			function (str,p1,offset,s) {
				if (A[str] != 'undefined'){return A[str];}
			}
		);
	}
	/* Normalizes a string, eÑŽ => eyu */
	this.strNormalize = function(el)
	{
		if (!el) { return; }
		this.strTranslit(el);
	}
}
var oJS = new JSfunc();
</script>
</head>
<body>

<p>введите текст:</p>
<textarea onkeyup="oJS.strNormalize(this)" style="height:10em;width:100%" id="in"></textarea>
<p>результат:</p>
<textarea style="height:10em;width:100%" id="out"></textarea>

</body>
</html>
    
        
SELECT DISTINCT field_name, COUNT(*) AS num FROM table_name GROUP BY field_name ORDER BY num DESC
    
        Convert a utf string to iso, used this when generating a pdf with pdf-writer in Rails, all my text is UTF8 but pdf-writer does not support this.

#add this to environment.rb
#call to_iso on any UTF8 string to get a ISO string back
#example : "Cédez le passage aux français".to_iso

class String
  require 'iconv' #this line is not needed in rails !
  def to_iso
    Iconv.conv('ISO-8859-1', 'utf-8', self)
  end
end