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

Generate short URLs using Ruby

This Ruby code generates shortened URLs. It has the added feature that it will not allow words to be created accidentally eg. swear words.

#!/usr/bin/ruby

class ShortUrl
  def initialize()
    @chars = ('a'..'z').to_a + ('1'..'9').to_a + ('A'..'Z').to_a
    @array_size = @chars.size
    @h = Hash.new
    @chars.each {|c| @h[c] = '0'}
    vowels = %w(a e i o u A E I O U 4 3 1 0)
    vowels.each {|v| @h[v] = '1'}
    nums = %w(2 5 6 7 8 9)
    nums.each {|n| @h[n] = '2'}
    @count = 0
    @a = Array.new(7, -1)
    @k = 0
  end 

  def iterate_chars(array_size)
    (0..array_size).each {|i| 
      increment_index(@k)
      convert_to_chars()
    }
  end
  
  def convert_to_chars()
    buffer = ''
    @a.each {|i|
      buffer << @chars[i] if i >= 0
    }
    a = buffer.reverse.scan(/./)
    k = a.length  
    if  (k > 1)  
      if ((@h[a[k-2]] + @h[a[k-1]]) != '10')
        puts buffer.reverse 
      end
    else
      puts buffer.reverse
    end
  end

  def get_short_url(count)
    if count >  @array_size
      new_count = count - @array_size
      iterate_chars(@array_size)
      get_short_url(new_count)
    else
      iterate_chars(count)
    end
  end
  
  def increment_a(i)
    if @a[i] < @array_size - 1
      @a[i] = @a[i] + 1
      return i 
    else
      @a[i] = 0
      return i += 1
    end 
  end

  def increment_index(k)
    old_k = k
    k = increment_a(k)
    
    if k != old_k
      increment_index(k)
    else
      k = 0
    end
    k
  end

end

if __FILE__ == $0
  su = ShortUrl.new  
  su.get_short_url(222761)
end


Note: You will most likely see the " `convert_to_chars': stack level too deep (SystemStackError)" error message after around 253950 iterations, I'm presuming this is expected due to the memory constraints of the language. However 253k short urls is enough for linking my website to itself.

Generate an XSL file for a simple XML file

Using Ruby and XSLT this code creates an xsl file for a corresponding xml file. Note: It only reproduces xml elements in the xsl file, not element attributes.
#!/usr/bin/ruby
# file: xml2xsl.rb

# author: jrobertson
# created: 31-Dec-07
# description: 
#   Converts an xml file into another xml file in 'xml2xsl' format.
#   This new xml file can then be transformed with the stylesheet 
#   xml2xsl.xsl into a multi-purpose xsl file template for the original 
#   xml file.

 
require 'rexml/document'
include REXML

class PreXml2Xsl

  def pre_xml2xsl(doc)
    puts '<xsl>'
    puts "  <template name='" + doc.root.name + "'>"
    build_xml(doc.root)
    puts '    </template>'
    puts '</xsl>'
  end
  
  def build_xml(node)
    previous_name = ''
    node.each_child do |child| 
      if child.length > 1 
        build_template(child.name)
        build_xml(child) 
      else
        build_value(child.name) if child.name != previous_name
        previous_name = child.name
      end
    end
  end
      
  def build_template(element)
    puts '  ' + "<select name=\"#{element}\" />"
    puts "</template>"
    puts "<template name=\"#{element}\">"
  end

  def build_value(element)
    puts '  ' + "<value name=\"#{element}\" />"
  end

  if __FILE__ == $0
    xml_language = '<languages><programming><name>C++</name><name>C Sharp</name
><name>Ruby</name></programming></languages>'
    doc = Document.new(xml_language)
    px = PreXml2Xsl.new
    px.pre_xml2xsl(doc)
  end
end

file: xml2xsl.xml (output from xml2xsl.rb)
<xsl>
  <template name="languages">
    <select name="programming"/>
  </template>
  <template name="programming">
    <value name="name"/>
  </template>
</xsl>

file: xml2xsl.xsl (used with xml2xsl.xml)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:template match="xsl">
  <xsl:variable name="colon"><xsl:text>:</xsl:text></xsl:variable>
    <xsl:element name="xsl:stylesheet">
      <xsl:attribute name="xmlns{$colon}xsl">
        <xsl:text>http://www.w3.org/1999/XSL/Transform</xsl:text>
      </xsl:attribute>
      <xsl:attribute name="version">
        <xsl:text>1.0</xsl:text>
      </xsl:attribute>
      
      <xsl:apply-templates select="*" />
    
  </xsl:element>

  </xsl:template>
  
  <xsl:template match="template">
  <xsl:text>
  </xsl:text>
        <xsl:element name="xsl:template">
        <xsl:attribute name="match">
          <xsl:value-of select="@name"/>
        </xsl:attribute>

        <xsl:apply-templates select="*" />
  <xsl:text>
  </xsl:text>
    </xsl:element>
<xsl:text>
</xsl:text>

  </xsl:template>
  
  <xsl:template match="select">
    <xsl:text>
    </xsl:text>
  <xsl:element name="xsl:element">
    <xsl:attribute name="name">
      <xsl:value-of select="@name"/>
    </xsl:attribute>
    <xsl:text>
    </xsl:text>
    <xsl:text>  </xsl:text><xsl:element name="xsl:apply-templates">
      <xsl:attribute name="select">
        <xsl:value-of select="@name"/>
      </xsl:attribute>
    </xsl:element>
    <xsl:text>
    </xsl:text>
  </xsl:element>


  </xsl:template>
  
  <xsl:template match="value">
    <xsl:text>
    </xsl:text>
  <xsl:element name="xsl:element">
    <xsl:attribute name="name">
      <xsl:value-of select="@name"/>
    </xsl:attribute>
      <xsl:text>
      </xsl:text>
    <xsl:element name="xsl:value-of">
      <xsl:attribute name="select">
        <xsl:value-of select="@name"/>
      </xsl:attribute>
    </xsl:element>
    <xsl:text>
    </xsl:text>
  </xsl:element>
</xsl:template>
</xsl:stylesheet>

output from xml2xsl.xsl
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="languages">
    <xsl:element name="programming">
      <xsl:apply-templates select="programming"/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="programming">
    <xsl:element name="name">
      <xsl:value-of select="name"/>
    </xsl:element>
  </xsl:template>
</xsl:stylesheet>

Generate combinations

Code generates all the combinations of n elements choosing k elements.

See this for definition.

See this for explanation.

#include <stdio.h>

/* Prints out a combination like {1, 2} */
void printc(int comb[], int k) {
	printf("{");
	int i;
	for (i = 0; i < k; ++i)
		printf("%d, ", comb[i] + 1);
	printf("\b\b}\n");
}

/*
	next_comb(int comb[], int k, int n)
		Generates the next combination of n elements as k after comb

	comb => the previous combination ( use (0, 1, 2, ..., k) for first)
	k => the size of the subsets to generate
	n => the size of the original set

	Returns: 1 if a valid combination was found
		0, otherwise
*/
int next_comb(int comb[], int k, int n) {
	int i = k - 1;
	++comb[i];
	while ((i >= 0) && (comb[i] >= n - k + 1 + i)) {
		--i;
		++comb[i];
	}

	if (comb[0] > n - k) /* Combination (n-k, n-k+1, ..., n) reached */
		return 0; /* No more combinations can be generated */

	/* comb now looks like (..., x, n, n, n, ..., n).
	Turn it into (..., x, x + 1, x + 2, ...) */
	for (i = i + 1; i < k; ++i)
		comb[i] = comb[i - 1] + 1;

	return 1;
}

int main(int argc, char *argv[]) {
	int n = 5; /* The size of the set; for {1, 2, 3, 4} it's 4 */
	int k = 3; /* The size of the subsets; for {1, 2}, {1, 3}, ... it's 2 */
	int comb[16]; /* comb[i] is the index of the i-th element in the
			combination */

	/* Setup comb for the initial combination */
	int i;
	for (i = 0; i < k; ++i)
		comb[i] = i;

	/* Print the first combination */
	printc(comb, k);

	/* Generate and print all the other combinations */
	while (next_comb(comb, k, n))
		printc(comb, k);

	return 0;
}

Generate permutations

Generates all the permutations of {1, 2, ..., n}.

See this for further explanations.

#include <stdio.h>

void printv(int v[], int n) {
	int i;

	for (i = 0; i < n; i++)
		printf("%d ", v[i]);
	printf("\n");
}

/*!
	This just swaps the values of a and b

	i.e if a = 1 and b = 2, after

		SWAP(a, b);

	a = 2 and b = 1
*/
#define SWAP(a, b) a = a + b - (b = a)

/*!
	Generates the next permutation of the vector v of length n.

	@return 1, if there are no more permutations to be generated

	@return 0, otherwise
*/
int next(int v[], int n) {
	/* P2 */
	/* Find the largest i */
	int i = n - 2;
	while ((i >= 0) && (v[i] > v[i + 1]))
		--i;

	/* If i is smaller than 0, then there are no more permutations. */
	if (i < 0)
		return 1;

	/* Find the largest element after vi but not larger than vi */
	int k = n - 1;
	while (v[i] > v[k])
		--k;
	SWAP(v[i], v[k]);

	/* Swap the last n - i elements. */
	int j;
	k = 0;
	for (j = i + 1; j < (n + i) / 2 + 1; ++j, ++k)
		SWAP(v[j], v[n - k - 1]);

	return 0;
}

int main(int argc, char *argv[]) {
	int v[128];
	int n = 3;

	/* The initial permutation is 1 2 3 ...*/
	/* P1 */
	int i;
	for (i = 0; i < n; ++i)
		v[i] = i + 1;
	printv(v, n);

	int done = 1;
	do {
		if (!(done = next(v, n)))
			printv(v, n); /* P3 */
	} while (!done);

	return 0;
}

Generate all subsets of a set

This code generates all the subsets of {1, 2, ..., n} and prints them.

This also contains a very fast binary counter implementation.

See this for further explanations.

#include <stdio.h>

/* Applies the mask to a set like {1, 2, ..., n} and prints it */
void printv(int mask[], int n) {
	int i;
	printf("{ ");
	for (i = 0; i < n; ++i)
		if (mask[i])
			printf("%d ", i + 1); /*i+1 is part of the subset*/
	printf("\b }\n");
}

/* Generates the next mask*/
int next(int mask[], int n) {
	int i;
	for (i = 0; (i < n) && mask[i]; ++i)
		mask[i] = 0;

	if (i < n) {
		mask[i] = 1;
		return 1;
	}
	return 0;
}

int main(int argc, char *argv[]) {
	int n = 3;

	int mask[16]; /* Guess what this is */
	int i;
	for (i = 0; i < n; ++i)
		mask[i] = 0;

	/* Print the first set */
	printv(mask, n);

	/* Print all the others */
	while (next(mask, n))
		printv(mask, n);

	return 0;
}

rails generator syntax

// generate application
rails projectname


// generate migration.
ruby script/generate migration migration_name
ruby script/generate migration add_price


// generate model
// we can give a list of columns and types
// :string, :text, :integer, :decimal, :float, :date, ...
ruby script/generate model model_name
ruby script/generate model user name:string hashed_password:string salt:string


// generate controller
ruby script/generate controller controller_name method_name(s)
ruby script/generate controller store index


// generate scaffold
ruby script/generate scaffold model_name controller_name
ruby script/generate scaffold product admin

Create Graphiz image from Dot file using DotNet

This is from http://vv.cs.byu.edu/cs312-003/archives/2005/01/graph_visualiza.html. Go there for more info.
 private void button2_Click(object sender, System.EventArgs e) {

string strCmdLine1 = "-Tsvg -o c:\\tmp\\foo.xml c:\\tmp\\ER.dot";
string strCmdLine2 = "-Tsvg -o c:\\tmp\\foo.xml c:\\tmp\\Heawood.dot";
System.Diagnostics.Process p = new System.Diagnostics.Process();

p.StartInfo.FileName = "\"C:\\Program Files\\ATT\\Graphviz\\bin\\dot.exe\"";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
if (graphIndex == 0)
p.StartInfo.Arguments = strCmdLine2;
else
p.StartInfo.Arguments = strCmdLine1;

p.Start();
p.WaitForExit();

axSVGCtl1.reload();
graphIndex = (graphIndex + 1) % 2;
}
« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS