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

Strip the line numbers from code snippets

Source: Saari Development: Ruby: One liner to strip the line number from code posted [blogspot.com]

   1  
   2  ruby -lne 'puts $_.gsub(/^\s+?\d+\s/,"")' ali.rb > ali.rb


Here's a page that allows you to strip line numbers without any script [rorbuilder.info] or here http://rubyurl.com/umxP .

Trivial ternary operator in Scala

//Just a quick test/exploration of Pimp My Library to reproduce the syntax of the C++ et al ternary operator

   1  
   2  object TernaryOp {
   3    implicit def fakeTernary[A](a:(A,A)) = new{
   4      def ?:(p:Boolean)=if(p) a._1 else a._2
   5    }  
   6    //Before adding the Tuplicator class the compiler got very confused
   7    // between anonymous classes
   8    class Tuplicator[A](a:A){
   9      def ~:(b:A) = (b,a)
  10    }
  11    implicit def tuplicate[A](a:A) = new Tuplicator(a)
  12  }
  13  
  14  object TernaryTest {
  15    import TernaryOp._
  16    def main(args: Array[String]) = {
  17      println( (1>3) ?: 1 ~: 3 )
  18    }
  19  }
  20  

Only allow numbers in textbox

// This can be expanded to limit the key pressed to whatever you want
//In this scenario it only allows digits

   1  
   2   void textBox_KeyPress(object sender, KeyPressEventArgs e)
   3  {
   4  e.Handled = !(Char.IsDigit(e.KeyChar) || e.KeyChar == '\b');
   5  }

Code 2 HTML

This is a simple python program that reads a file (code), and replaces line breaks and spaces with appropriate tag and entity.

   1  
   2  import sys
   3  
   4  line_break='<br>'
   5  nb_space='&#160;'
   6  
   7  def toHtml(f,out):
   8      try:
   9          fo=open(out,'w')
  10      except IOError:
  11          print 'output file error!'
  12      else:
  13          for line in f:
  14              line=line.replace('\t',nb_space*8)
  15              line=line.replace(' ',nb_space)
  16              line=line.replace('\n',line_break)
  17              fo.write(line)
  18          fo.close()
  19          
  20  
  21  if len(sys.argv) == 1:
  22      print("at least one argument / input filename / required")
  23      sys.exit()
  24  if len(sys.argv) > 3:
  25      print"too many arguments"
  26      sys.exit()       
  27  try:
  28      f=open(sys.argv[1],'r')
  29  except IOError:
  30      print 'cannot open file ', sys.argv[1]
  31  else:
  32      if len(sys.argv) == 2:
  33          out=f.name + '.html'
  34      else:
  35          out=sys.argv[2]
  36      toHtml(f, out)
  37      f.close()

Reference of keyCodes

   1  
   2      switch (oEvent.keyCode) {
   3         case 38: //up arrow  
   4         case 40: //down arrow
   5         case 37: //left arrow
   6         case 39: //right arrow
   7         case 33: //page up  
   8         case 34: //page down  
   9         case 36: //home  
  10         case 35: //end                  
  11         case 13: //enter  
  12         case 9: //tab  
  13         case 27: //esc  
  14         case 16: //shift  
  15         case 17: //ctrl  
  16         case 18: //alt  
  17         case 20: //caps lock
  18         case 8: //backspace  
  19         case 46: //delete
  20             return true;
  21             break;
  22  
  23         default: 

Note: When capturing combination keys there is dedicated boolean attributes for each of the special keys (CTRL, SHIFT, ALT).
Reference: Make Life Easy With Autocomplete Textboxes [JavaScript & AJAX Tutorials] [sitepoint.com]

Adding new files to your github repository

Here is a set of instructions to apply new files to my github repository which is called projectx.

Before you start make sure you don't already have the repository name listed as a directory in the local current directory.

1) copy the remote repository to your local machine
syntax: git clone [uri] # eg.
   1  git clone git@github.com:jrobertson/projectx.git

1.5) cd into the newly created local repository eg.
   1  cd projectx

2) copy the local file to the local repository directory
eg.
   1  cp ../projectx2/feed.rb .

3) add the local files to the local repository
syntax: git add [file] # eg.
   1  git add feed.rb

4) Inform the git system that you have completed the required changes for this session.
   1  git commit -a # add a message associated with this file revision

5) copy the new local repository files back to the remote repository.
   1  git push # updates the changes back to the server

Note: The text with the square-brackets should be replaced with your own values.

Reference: A tour of git: the basics [cworth.org]

Format Ruby code in HTML

This code uses the Ruby gem 'syntax' to create an XML file containing the HTML tags around the code, which is then transformed into an HTML file. The working example was first built using coding examples from Howto format ruby code for blogs [wolfman.com] and Formatting Ruby and HTML code for blog posting [blogspot.com]

   1  
   2  #!/usr/bin/ruby
   3  
   4  #file: ruby2html.rb 
   5  
   6  require 'rubygems'
   7  require 'syntax/convertors/html'
   8  require 'projxslt' # <- this is my own class to do an XSLT transform 
   9  require 'rexml/document'
  10  include REXML
  11  
  12  class Ruby2Html
  13    def initialize(rubyfile, htmlfile)
  14      code = File.read(rubyfile)
  15      convertor = Syntax::Convertors::HTML.for_syntax "ruby"
  16      code_html = convertor.convert(code)
  17      
  18      tempfile = '../temp/ruby2html.xml'
  19      xslfile = '../ruby2html/ruby2html.xsl'
  20      save_file(tempfile, code_html)
  21      
  22      px = Projxslt.new(tempfile, xslfile)
  23      buffer = px.transform()
  24      save_file(htmlfile, buffer)
  25      
  26    end
  27    
  28    def save_file(filename, buffer)
  29      file = File.new(filename, 'w')
  30      file.puts buffer
  31      file.close
  32    end
  33  end
  34  
  35  if __FILE__ == $0
  36    r2h = Ruby2Html.new('ruby2html.rb', '../temp/ruby2html.html')
  37    puts 'completed'
  38  end

file: ruby2html.xsl
   1  
   2  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   3                  xmlns="http://www.w3.org/1999/xhtml"
   4                  version="1.0">
   5  
   6    <xsl:output method="html" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
   7            doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
   8            encoding="ISO-8859-1"/> 
   9  
  10  	<xsl:template match="/">
  11  	<xsl:element name="html">
  12  
  13          <head>
  14            <title>Sample code</title>
  15            <link rel="stylesheet" type="text/css" href="ruby2html.css" />
  16  	</head>
  17  
  18  	<body>
  19            <div id="wrap">
  20            <xsl:apply-templates />
  21            </div>
  22  	</body> 
  23  
  24  	</xsl:element>
  25  	</xsl:template>
  26  
  27  	<xsl:template match="pre">
  28  	  <xsl:copy-of select="."/>
  29  	</xsl:template>
  30  
  31  </xsl:stylesheet>

Here's the output from the formatted Ruby HTML code [twitxr.com]

Referemce: Syntax Manual [rubyforge.org]

Code Of A Game

This Is A Code Of A Game.

Coppy It Into Notepad And Then Save It As Game.bat

Warning!
Make Sure It Says "All Files (*.*)" And Not "Text Document (.txt)" At The Bottom.
The Code Is:
   1  
   2  @echo off
   3  goto verybegingame
   4  : verybegingame
   5  echo Welcome To This Game!
   6  title Game Start
   7  echo Press Any Key For Stuff.
   8  pause >nul
   9  echo Loading...
  10  ping localhost 6 >nul
  11  echo.. Loading Comple!
  12  pause >nul
  13  cls
  14  echo Rules:
  15  title Game Rules
  16  echo..You Answer Each Question.
  17  echo. If It Is Correct, You Will Move On.
  18  echo If It is InCorrect, The Program Will
  19  echo Exit And You Will Need To Try Again.
  20  echo.. If You Get All The Questions Right, You
  21  echo Will Receave A Speical Code.
  22  echo Enter THe Code For A Suprse!
  23  echo...
  24  echo Good Luck!
  25  echo.....
  26  echo Press A Key Of An Option, And Then 
  27  echo Press 'Enter'.
  28  echo...
  29  echo                        1 = Play Game          2 = Enter Code
  30  SET /P "onechoose1=Enter 1 or 2 option here:"
  31  If %onechoose1%= 1 then goto playgame
  32  If %onechoose1%= 2 then goto entercode
  33  :playgame
  34  cls
  35  echo What Is My Name?
  36  echo A.Jonathan
  37  echo B.Sam
  38  echo C.Johnn
  39  SET /p "q1=Enter Option:"
  40  If NOT%q1%= A then exit
  41  :entercode
  42  echo  Enter Code
  43  SET /P "codeenter= "
  44  If %entercode%=code... goto prize
  45  :prize
  46  
  47  

All Of ThAT...
MAKE MORE QUESTIONS.
etc.

Morse decode using sed

This is a short Morse code decoder written as a shellscript using sed.

The Morse coded text should be in $text, and should be written with spaces between the letters.

   1  
   2  echo $text\  | tr . 0 | sed -e {s/0----\ /1/g} -e {s/00---\ /2/g} -e {s/000--\ /3/g} -e {s/000-\ /4/g} -e {s/00000\ /5/g} -e {s/-0000\ /6/g} -e {s/--000\ /7/g} -e {s/---00\ /8/g} -e {s/----0\ /9/g} -e {s/-----\ /0/g} \
   3  	| sed -e {s/-0-0\ /c/g} -e {s/-000\ /b/g} -e {s/00-0\ /f/g} -e {s/0000\ /h/g} -e {s/0---\ /j/g} -e {s/0-00\ /l/g} -e {s/0--0\ /p/g} -e {s/--0-\ /q/g} -e {s/000-\ /v/g} -e {s/-00-\ /x/g} -e {s/-0--\ /y/g} -e {s/--00\ /z/g} \
   4  	| sed -e {s/0--\ /w/g} -e {s/-00\ /d/g} -e {s/--0\ /g/g} -e {s/-0-\ /k/g} -e {s/---\ /o/g} -e {s/0-0\ /r/g} -e {s/000\ /s/g} -e {s/00-\ /u/g} \
   5  	| sed -e {s/0-\ /a/g} -e {s/00\ /i/g} -e {s/--\ /m/g} -e {s/-0\ /n/g} \
   6  	| sed -e {s/0\ /e/g} -e {s/-\ /t/g}

Generate Ruby code using XML and XSL

This XSL code transforms an XML file into a basic Ruby file. See the previous post ('Transforming an XML file into an XSL file' http://snipr.com/1usrh [dzone.com]) for an example of the XML used.

   1  
   2  <?xml version="1.0" encoding="UTF-8"?>
   3  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   4  <xsl:output method="text"/>
   5  
   6    <xsl:template match="recordx">
   7    <xsl:variable name="project" select="summary/project" />
   8    <xsl:variable name="parent_element" select="summary/parent_element" />
   9    <xsl:text>#!/usr/bin/ruby
  10  #file: </xsl:text><xsl:value-of select="$project"/><xsl:text>.rb
  11  
  12  require 'recordx'
  13  
  14  class </xsl:text><xsl:value-of select="$project"/><xsl:text> &lt; RecordX
  15  
  16    def initialize()
  17      @project = "</xsl:text><xsl:value-of select="$project"/><xsl:text>"
  18      @parent_element = '</xsl:text><xsl:value-of select="$parent_element"/><xsl:text>fields'
  19      @proj = Projxml.new
  20      @doc_vrecord = initialize_xml_class(SERVER_URL + '/' + @project + '/class_template.xml')
  21      @doc_file = get_doc()
  22    end
  23    
  24  end
  25  
  26  if __FILE__ == $0
  27      r = </xsl:text><xsl:value-of select="$project"/><xsl:text>.new()
  28  end
  29    </xsl:text>
  30    </xsl:template>
  31    
  32  </xsl:stylesheet>
« Newer Snippets
Older Snippets »
Showing 1-10 of 23 total  RSS