diff options
Diffstat (limited to 'source/test')
-rw-r--r-- | source/test/syntax.html | 397 | ||||
-rw-r--r-- | source/test/syntax.markdown | 228 |
2 files changed, 397 insertions, 228 deletions
diff --git a/source/test/syntax.html b/source/test/syntax.html new file mode 100644 index 00000000..ac26554f --- /dev/null +++ b/source/test/syntax.html @@ -0,0 +1,397 @@ +--- +layout: default +layout: page +nometa: true +title: Syntax Highlighting Debug +--- + +<h3 class="filename">gist_syntax_test.rb</h3> +{% gist 996818 test.rb %} + +<h3 class="filename">syntax_test.diff</h3> +{% highlight diff %} +@@ -590,7 +590,7 @@ class SpritesTest < Test::Unit::TestCase + it "should generate a sprite from nested folders" do + css = render <<-SCSS +- @import "nested/*.png"; ++ @import "nested/**/*.png"; + @include all-nested-sprites; + SCSS + assert_correct css, <<-CSS + +{% endhighlight %} + +<h3 class="filename">syntax_test.html</h3> +{% highlight html %} +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> +<html><head> +<title>A Tiny Page</title> +<style type="text/css"> +<!-- + p { font-size:15pt; color:#000 } + --> +</style></head><!-- real comment --> +<body bgcolor="#FFFFFF" text="#000000" link="#0000CC"> +<script language="javascript" type="text/javascript"> + function changeHeight(h) { + var tds = document.getElementsByTagName("td"); + for(var i = 0; i < tds.length; i++) { + tds[i].setAttribute("height", h + "px"); + }} +</script> +<h1>abc</h1> +<h2>def</h2> +<p>Testing page</p> +</body></html> +{% endhighlight %} + +<h3 class="filename">syntax_test.js</h3> +{% highlight js %} + +/** +sample javascript from xui +*/ + +var undefined, + xui, + window = this, + string = new String('string'), + document = window.document, + simpleExpr = /^#?([\w-]+)$/, + idExpr = /^#/, + tagExpr = /<([\w:]+)/, + slice = function (e) { return [].slice.call(e, 0); }; + try { var a = slice(document.documentElement.childNodes)[0].nodeType; } + catch(e){ slice = function (e) { var ret=[]; for (var i=0; e[i]; i++) + ret.push(e[i]); return ret; }; } + +window.x$ = window.xui = xui = function(q, context) { + return new xui.fn.find(q, context); +}; + + +{% endhighlight %} + +<h3 class="filename">syntax_test.rb</h3> +{% highlight ruby %} + +include Enumerable + +def initialize(rbconfig) +@rbconfig = rbconfig +@no_harm = false +end + +def load_savefile +begin + File.foreach(savefile()) do |line| + k, v = *line.split(/=/, 2) + self[k] = v.strip + end +rescue Errno::ENOENT + setup_rb_error $!.message + "\n#{File.basename($0)} config first" +end +end + +if c['rubylibdir'] + # V > 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + siterubyverarch = c['sitearchdir'] +end +parameterize = lambda {|path| + path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') +} + +if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } + makeprog = arg.sub(/'/, '').split(/=/, 2)[1] +else + makeprog = 'make' +end + +def setup_rb_error(msg) + raise SetupError, msg +end + +if $0 == __FILE__ + begin + ToplevelInstaller.invoke + rescue SetupError + raise if $DEBUG + $stderr.puts $!.message + $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." + exit 1 + end +end +{% endhighlight %} + +<h3 class="filename">syntax_test.php</h3> +{% highlight php %} +<?php +require_once($GLOBALS['g_campsiteDir']. "/$ADMIN_DIR/country/common.php"); +require_once($GLOBALS['g_campsiteDir']. "/classes/SimplePager.php"); +camp_load_translation_strings("api"); + +$f_country_language_selected = camp_session_get('f_language_selected', ''); +$f_country_offset = camp_session_get('f_country_offset', 0); +if (empty($f_country_language_selected)) { + $f_country_language_selected = null; +} +$ItemsPerPage = 20; +$languages = Language::GetLanguages(null, null, null, array(), array(), true); +$numCountries = Country::GetNumCountries($f_country_language_selected); + +$pager = new SimplePager($numCountries, $ItemsPerPage, "index.php?"); + +$crumbs = array(); +$crumbs[] = array(getGS("Configure"), ""); +$crumbs[] = array(getGS("Countries"), ""); +echo camp_html_breadcrumbs($crumbs); + +?> + +<?php if ($g_user->hasPermission("ManageCountries")) { ?> +<table BORDER="0" CELLSPACING="0" CELLPADDING="1"> + <tr> + <td><a href="add.php"><?php putGS("Add new"); ?></a></td> + </tr> +</table> +{% endhighlight %} + + +<h3 class="filename">syntax_test.hs</h3> +{% highlight hs %} +{-# LANGUAGE OverloadedStrings #-} +module Main where + +--import Prelude hiding (id) +--import Control.Category (id) +import Control.Arrow ((>>>), (***), arr) +import Control.Monad (forM_) +-- import Data.Monoid (mempty, mconcat) + +-- import System.FilePath + +import Hakyll + + +main :: IO () +main = hakyll $ do + + route "css/*" $ setExtension "css" + compile "css/*" $ byExtension (error "Not a (S)CSS file") + [ (".css", compressCssCompiler) + , (".scss", sass) + ] + + route "js/**" idRoute + compile "js/**" copyFileCompiler + + route "img/*" idRoute + compile "img/*" copyFileCompiler + + compile "templates/*" templateCompiler + + forM_ ["test.md", "index.md"] $ \page -> do + route page $ setExtension "html" + compile page $ pageCompiler + >>> applyTemplateCompiler "templates/default.html" + >>> relativizeUrlsCompiler + +sass :: Compiler Resource String +sass = getResourceString >>> unixFilter "sass" ["-s", "--scss"] + >>> arr compressCss + +{% endhighlight %} + +<h3 class="filename">syntax_test.sh</h3> +{% highlight sh %} +#!/bin/bash + +cd $ROOT_DIR +DOT_FILES="lastpass weechat ssh Xauthority" +for dotfile in $DOT_FILES; do conform_link "$DATA_DIR/$dotfile" ".$dotfile"; done + +# TODO: refactor with suffix variables (or common cron values) + +case "$PLATFORM" in + linux) + #conform_link "$CONF_DIR/shell/zshenv" ".zshenv" + crontab -l > $ROOT_DIR/tmp/crontab-conflict-arch + cd $ROOT_DIR/$CONF_DIR/cron + if [[ "$(diff ~/tmp/crontab-conflict-arch crontab-current-arch)" == "" + ]]; + then # no difference with current backup + logger "$LOG_PREFIX: crontab live settings match stored "\ + "settings; no restore required" + rm ~/tmp/crontab-conflict-arch + else # current crontab settings in file do not match live settings + crontab $ROOT_DIR/$CONF_DIR/cron/crontab-current-arch + logger "$LOG_PREFIX: crontab stored settings conflict with "\ + "live settings; stored settings restored. "\ + "Previous settings recorded in ~/tmp/crontab-conflict-arch." + fi + ;; + +{% endhighlight %} + +<h3 class="filename">syntax_test.py</h3> +{% highlight py %} +# test python (sample from offlineimap) + +class ExitNotifyThread(Thread): + """This class is designed to alert a "monitor" to the fact that a thread has + exited and to provide for the ability for it to find out why.""" + def run(self): + global exitthreads, profiledir + self.threadid = thread.get_ident() + try: + if not profiledir: # normal case + Thread.run(self) + else: + try: + import cProfile as profile + except ImportError: + import profile + prof = profile.Profile() + try: + prof = prof.runctx("Thread.run(self)", globals(), locals()) + except SystemExit: + pass + prof.dump_stats( \ + profiledir + "/" + str(self.threadid) + "_" + \ + self.getName() + ".prof") + except: + self.setExitCause('EXCEPTION') + if sys: + self.setExitException(sys.exc_info()[1]) + tb = traceback.format_exc() + self.setExitStackTrace(tb) + else: + self.setExitCause('NORMAL') + if not hasattr(self, 'exitmessage'): + self.setExitMessage(None) + + if exitthreads: + exitthreads.put(self, True) + + def setExitCause(self, cause): + self.exitcause = cause + def getExitCause(self): + """Returns the cause of the exit, one of: + 'EXCEPTION' -- the thread aborted because of an exception + 'NORMAL' -- normal termination.""" + return self.exitcause + def setExitException(self, exc): + self.exitexception = exc + def getExitException(self): + """If getExitCause() is 'EXCEPTION', holds the value from + sys.exc_info()[1] for this exception.""" + return self.exitexception + def setExitStackTrace(self, st): + self.exitstacktrace = st + def getExitStackTrace(self): + """If getExitCause() is 'EXCEPTION', returns a string representing + the stack trace for this exception.""" + return self.exitstacktrace + def setExitMessage(self, msg): + """Sets the exit message to be fetched by a subsequent call to + getExitMessage. This message may be any object or type except + None.""" + self.exitmessage = msg + def getExitMessage(self): + """For any exit cause, returns the message previously set by + a call to setExitMessage(), or None if there was no such message + set.""" + return self.exitmessage + +{% endhighlight %} + +<h3 class="filename">syntax_test.pl</h3> +{% highlight perl %} +#!perl -w + +# Time-stamp: <2002/04/06, 13:12:13 (EST), maverick, csvformat.pl> +# Two pass CSV file to table formatter + +$delim = $#ARGV >= 1 ? $ARGV[1] : ','; +print STDERR "Split pattern: $delim\n"; + +# first pass +open F, "<$ARGV[0]" or die; +while(<F>) +{ + chomp; + $i = 0; + map { $max[$_->[1]] = $_->[0] if $_->[0] > ($max[$_->[1]] || 0) } + (map {[length $_, $i++]} split($delim)); +} +close F; + +print STDERR 'Field width: ', join(', ', @max), "\n"; +print STDERR join(' ', map {'-' x $_} @max); + +# second pass +open F, "<$ARGV[0]" or die; +while(<F>) + { + chomp; + $i = 0; + map { printf("%-$max[$_->[1]]s ", $_->[0]) } + (map {[$_, $i++]} split($delim)); + print "\n"; +} +close F; + +{% endhighlight %} + +<h3 class="filename">syntax_test.java</h3> +{% highlight java %} +import java.util.Map; +import java.util.TreeSet; + +public class GetEnv { + /** + * let's test generics + * @param args the command line arguments + */ + public static void main(String[] args) { + // get a map of environment variables + Map<String, String> env = System.getenv(); + // build a sorted set out of the keys and iterate + for(String k: new TreeSet<String>(env.keySet())) { + System.out.printf("%s = %s\n", k, env.get(k)); + } + } } +{% endhighlight %} + +<h3 class="filename">syntax_test.c</h3> +{% highlight c %} +#define UNICODE +#include <windows.h> + +int main(int argc, char **argv) { + int speed = 0, speed1 = 0, speed2 = 0; // 1-20 + printf("Set Mouse Speed by Maverick\n"); + + SystemParametersInfo(SPI_GETMOUSESPEED, 0, &speed, 0); + printf("Current speed: %2d\n", speed); + + if (argc == 1) return 0; + if (argc >= 2) sscanf(argv[1], "%d", &speed1); + if (argc >= 3) sscanf(argv[2], "%d", &speed2); + + if (argc == 2) // set speed to first value + speed = speed1; + else if (speed == speed1 || speed == speed2) // alternate + speed = speed1 + speed2 - speed; + else + speed = speed1; // start with first value + + SystemParametersInfo(SPI_SETMOUSESPEED, 0, speed, 0); + SystemParametersInfo(SPI_GETMOUSESPEED, 0, &speed, 0); + printf("New speed: %2d\n", speed); + return 0; +} + +{% endhighlight %} + diff --git a/source/test/syntax.markdown b/source/test/syntax.markdown deleted file mode 100644 index ec5bab50..00000000 --- a/source/test/syntax.markdown +++ /dev/null @@ -1,228 +0,0 @@ ---- -layout: default -title: Syntax Highlighting Debug ---- -<div class="code_window"> -<em>Ruby</em> -{% highlight ruby %} -def rebuild_site(relative) - puts ">>> Change Detected to: #{relative} <<<" - IO.popen('rake generate') do |io| - print(io.readpartial(512)) until io.eof? - end - puts '>>> Update Complete <<<' -end -{% endhighlight %} -</div> - -So that's a small example. What about a big one? - -<div class="code_window"> -<em>Ruby</em> -{% highlight ruby %} -require 'active_support/core_ext/array' -require 'active_support/core_ext/hash/except' -require 'active_support/core_ext/object/metaclass' - -module ActiveRecord - module NamedScope - extend ActiveSupport::Concern - - # All subclasses of ActiveRecord::Base have one named scope: - # * <tt>scoped</tt> - which allows for the creation of anonymous \scopes, on the fly: <tt>Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions)</tt> - # - # These anonymous \scopes tend to be useful when procedurally generating complex queries, where passing - # intermediate values (scopes) around as first-class objects is convenient. - # - # You can define a scope that applies to all finders using ActiveRecord::Base.default_scope. - included do - named_scope :scoped, lambda { |scope| scope } - end - - module ClassMethods - def scopes - read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {}) - end - - # Adds a class method for retrieving and querying objects. A scope represents a narrowing of a database query, - # such as <tt>:conditions => {:color => :red}, :select => 'shirts.*', :include => :washing_instructions</tt>. - # - # class Shirt < ActiveRecord::Base - # named_scope :red, :conditions => {:color => 'red'} - # named_scope :dry_clean_only, :joins => :washing_instructions, :conditions => ['washing_instructions.dry_clean_only = ?', true] - # end - # - # The above calls to <tt>named_scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red, - # in effect, represents the query <tt>Shirt.find(:all, :conditions => {:color => 'red'})</tt>. - # - # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it resembles the association object - # constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.find(:first)</tt>, <tt>Shirt.red.count</tt>, - # <tt>Shirt.red.find(:all, :conditions => {:size => 'small'})</tt>. Also, just - # as with the association objects, named \scopes act like an Array, implementing Enumerable; <tt>Shirt.red.each(&block)</tt>, - # <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if Shirt.red really was an Array. - # - # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are both red and dry clean only. - # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments - # for which these criteria obtain. Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>. - # - # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which the \scopes were defined. But they are also available to - # <tt>has_many</tt> associations. If, - # - # class Person < ActiveRecord::Base - # has_many :shirts - # end - # - # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean - # only shirts. - # - # Named \scopes can also be procedural: - # - # class Shirt < ActiveRecord::Base - # named_scope :colored, lambda { |color| - # { :conditions => { :color => color } } - # } - # end - # - # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts. - # - # Named \scopes can also have extensions, just as with <tt>has_many</tt> declarations: - # - # class Shirt < ActiveRecord::Base - # named_scope :red, :conditions => {:color => 'red'} do - # def dom_id - # 'red_shirts' - # end - # end - # end - # - # - # For testing complex named \scopes, you can examine the scoping options using the - # <tt>proxy_options</tt> method on the proxy itself. - # - # class Shirt < ActiveRecord::Base - # named_scope :colored, lambda { |color| - # { :conditions => { :color => color } } - # } - # end - # - # expected_options = { :conditions => { :colored => 'red' } } - # assert_equal expected_options, Shirt.colored('red').proxy_options - def named_scope(name, options = {}, &block) - name = name.to_sym - scopes[name] = lambda do |parent_scope, *args| - Scope.new(parent_scope, case options - when Hash - options - when Proc - options.call(*args) - end, &block) - end - metaclass.instance_eval do - define_method name do |*args| - scopes[name].call(self, *args) - end - end - end - end - - class Scope - attr_reader :proxy_scope, :proxy_options, :current_scoped_methods_when_defined - NON_DELEGATE_METHODS = %w(nil? send object_id class extend find size count sum average maximum minimum paginate first last empty? any? many? respond_to?).to_set - [].methods.each do |m| - unless m =~ /^__/ || NON_DELEGATE_METHODS.include?(m.to_s) - delegate m, :to => :proxy_found - end - end - - delegate :scopes, :with_scope, :scoped_methods, :to => :proxy_scope - - def initialize(proxy_scope, options, &block) - options ||= {} - [options[:extend]].flatten.each { |extension| extend extension } if options[:extend] - extend Module.new(&block) if block_given? - unless Scope === proxy_scope - @current_scoped_methods_when_defined = proxy_scope.send(:current_scoped_methods) - end - @proxy_scope, @proxy_options = proxy_scope, options.except(:extend) - end - - def reload - load_found; self - end - - def first(*args) - if args.first.kind_of?(Integer) || (@found && !args.first.kind_of?(Hash)) - proxy_found.first(*args) - else - find(:first, *args) - end - end - - def last(*args) - if args.first.kind_of?(Integer) || (@found && !args.first.kind_of?(Hash)) - proxy_found.last(*args) - else - find(:last, *args) - end - end - - def size - @found ? @found.length : count - end - - def empty? - @found ? @found.empty? : count.zero? - end - - def respond_to?(method, include_private = false) - super || @proxy_scope.respond_to?(method, include_private) - end - - def any? - if block_given? - proxy_found.any? { |*block_args| yield(*block_args) } - else - !empty? - end - end - - # Returns true if the named scope has more than 1 matching record. - def many? - if block_given? - proxy_found.many? { |*block_args| yield(*block_args) } - else - size > 1 - end - end - - protected - def proxy_found - @found || load_found - end - - private - def method_missing(method, *args, &block) - if scopes.include?(method) - scopes[method].call(self, *args) - else - with_scope({:find => proxy_options, :create => proxy_options[:conditions].is_a?(Hash) ? proxy_options[:conditions] : {}}, :reverse_merge) do - method = :new if method == :build - if current_scoped_methods_when_defined && !scoped_methods.include?(current_scoped_methods_when_defined) - with_scope current_scoped_methods_when_defined do - proxy_scope.send(method, *args, &block) - end - else - proxy_scope.send(method, *args, &block) - end - end - end - end - - def load_found - @found = find(:all) - end - end - end -end -{% endhighlight %} -</div>
\ No newline at end of file |