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

What next?
1. Bookmark us with del.icio.us or Digg Us!
2. Subscribe to this site's RSS feed
3. Browse the site.
4. Post your own code snippets to the site!

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

Fast anagram determination

// This function will determine whether the two C strings provided are anagrams or not. Only alphabetical strings are considered.

/******************************************************************************
 * This function is a code snippet. It can be freely used and distributed.
 * Author: irfan.hamid@gmail.com
 *
 * This function takes two ASCII strings in C syntax (null-terminated
 * character arrays) and determines whether they are anagrams or not.
 *
 * Implementation notes:
 * The function contains a histogram that stores the frequency of each 
 * character it encounters in the first string. For each character of the 
 * second string, it decrements the corresponding entry in the histogram. If 
 * before every decrement, the value of the histogram bucket reaches zero, 
 * then the two strings are not anagrams, as there is some character that has
 * more occurrences in the second string than in the first string.
 *
 * If either of the two strings contains a non-alphabetic character, the
 * anagram property is considered to be violated.
 *
 * Remarks:
 * It is an efficient implementation because:
 *   o It is in-place, the original strings are not copied, no alloc or copy
 *   o Does not clobber the original strings
 *   o It is a linear time implementation
 *
 * Returns:
 * True if the strings are anagrams, false otherwise.
******************************************************************************/

bool is_anagram (char w1[], char w2[])
{
	unsigned int i, sz;

	/* The histogram */
	int freqtbl[26];

	/* Sanity check */
	if ((sz = strlen(w1)) != strlen(w2))
		return false;

	/* Initialize the histogram */
	bzero(freqtbl, 26*sizeof(int));

	/* Read the first string, incrementing the corresponding histogram entry */
	for (i = 0; i < sz; i++) {
		if (w1[i] >= 'A' && w1[i] <= 'Z')
			freqtbl[w1[i]-'A']++;
		else if (w1[i] >= 'a' && w1[i] <= 'z')
			freqtbl[w1[i]-'a']++;
		else
			return false;
	}

	/* Read the second string, decrementing the corresponding histogram entry */
	for (i = 0; i < sz; i++) {
		if (w2[i] >= 'A' && w2[i] <= 'Z') {
			if (freqtbl[w2[i]-'A'] == 0)
				return false;
			freqtbl[w2[i]-'A']--;
		} else if (w2[i] >= 'a' && w2[i] <= 'z') {
			if (freqtbl[w2[i]-'a'] == 0)
				return false;
			freqtbl[w2[i]-'a']--;
		} else {
			return false;
		}
	}

	return true;
}

Perform Comment Recount for WordPress

Run from the command line and uncomment line #2 if your mysql adapter is installed via RubyGems. Fast as hell.

#!/usr/bin/ruby
#require 'rubygems'
require 'mysql'
 
db = Mysql.real_connect("host", "username", "password", "database")
ids = db.query("SELECT `ID` FROM `wp_posts` WHERE 1")
 
ids.each_hash do |post|
  id = post['ID']
  num = 0
  comments = db.query("SELECT COUNT(1) FROM `wp_comments` WHERE `comment_post_ID`='#{id}' AND `comment_approved`='1';")
  comments.each {|x| num = x[0]}
  up = db.query("UPDATE `wp_posts` SET `comment_count`='#{num}' WHERE `ID`='#{id}';")
end

perl grep dir and filename

// description of your code here

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

A lantern that varies

// lantern test

"lantern test" by vimes

The testing room is a room. "'fooble' a lamp.  Alternatively, 'target' a lamp, then 'fooble' alone to toggle it."

A lantern is a kind of thing.  Lanterns can be lit or unlit.  Lanterns are usually unlit.

The current lamp is a lantern that varies.

When play begins: now the current lamp is nothing.

The Red Lamp is a lantern in the testing room.  The Blue lamp is a lantern in the testing room. 

After examining a lantern:
	if the lantern is lit:
		say "This lantern is lit.";
	otherwise:
		say "This lantern is unlit.";
		
After printing the name of a lantern:
	say "[if the noun is lit] (lit)[otherwise] (unlit)[end if]"
	
To toggle (L - a lantern):
	if L is lit:
		now L is unlit;
		say "(extinguished [the L])";
	otherwise:
		now L is lit;
		say "(ignited [the L])";

Foobling is an action applying to one visible thing.
Autofoobling is an action applying to nothing.
Targeting is an action applying to one visible thing.

Understand "fooble" as autofoobling.
Understand "fooble [something]" as foobling.
Understand "target [something]" as targeting.

Carry out targeting:
	if the noun is a lantern:
		Now the current lamp is the noun;
		say "(targeted [the noun])";
	otherwise:
		say "You can't target that.";
		
Carry out foobling:
	if the noun is a lantern:
		toggle the noun;
	otherwise:
		say "You can't fooble that.";

Carry out autofoobling:
	If the current lamp is nothing:
		say "There is no target.";
	otherwise:
		say "(working with [the current lamp])[line break]";
		toggle the current lamp;
	

Prototype.js Unobtrusive JS

document.observe("dom:loaded", function() {
$$('selector').each(function(element) { new ClassThing(element) });
});

Copy MySQL table

CREATE TABLE table_destination SELECT * FROM table_source ;


CREATE TABLE table_destination LIKE table_source ;
INSERT INTO table_destination SELECT * FROM table_source ;


Source: Asselin Benoit Developpement ( MySQL, SQL )

about struts

// description of your code here

// insert code here..

i want to learn struts..........

Using mmap to do a global search and replace on Windows

// Use win32-mmap to do a global search and replace on Windows

require 'win32/mmap'
require 'windows/msvcrt/buffer'
include Windows::MSVCRT::Buffer

Strlen = API.new('strlen', 'L', 'L', 'msvcrt')
Strstr = API.new('strstr', 'LP', 'L', 'msvcrt')

Dir["**/*.rb"].each{ |f|
   p f
   Win32::MMap.new(:file => f) do |addr|
      old_str = 'some_old_string'
      old_len = old_str.length
      new_str = 'some_other_string'
      new_len = new_str.length

      ptr1 = ptr2 = ptr3 = Strstr.call(addr,old_str)

      while ptr1 && ptr1 != 0
         ptr2 += new_len
         ptr3 += old_len
         memmove(ptr2, ptr3, 1 + Strlen.call(ptr3))
         memcpy(ptr1, new_str, new_len)
         ptr1 = ptr2 = ptr3 = Strstr.call(ptr2,old_str)
      end
   end
}

mail sending program using ssl using gmail account

// description of your code here

require 'rubygems'
require 'action_mailer'
require "net/smtp"
require "tlsmail"

class MailSent < ActionMailer::Base
  def message(r = "", m = "", s = "", f = "", c = nil)
    begin
      fail StandardError, "No Recipient" if r.empty? #and b.empty?
      fail StandardError, "No Message" if m.empty? 
      fail StandardError, "No Subject" if s.empty?
      fail StandardError, "No From" if s.empty?
      from f
      recipients r
      cc c if c and !c.empty?
      subject s
      body m
    rescue Exception => e
      puts e
    end
  end
end

class SentMail
  def get_value(to,msg,sub,from,pass=nil,cc=nil)
    begin

      Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)
      ActionMailer::Base.smtp_settings = {
        :address => "smtp.gmail.com",
        :port => "587",
        :domain => "gmail.com",
        :user_name => "example.com,
        :password => "youraccountpassword",
        :authentication => :plain
      }
      MailSent.deliver_message(to,msg,sub,from,cc)
    rescue Exception=>e
      puts e
    end
  end
end

Display recent posts from a category

// No need of a plugin to do this

<ul>
 <?php
 global $post;
 $myposts = get_posts('numberposts=5&category=4');
 foreach($myposts as $post) :
 setup_postdata($post);
 ?>
 <li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
 <?php endforeach; ?>
</ul>.
« Newer Snippets
Older Snippets »
Showing 1-10 of 4566 total  RSS